diff --git a/1801BM1_vm80a/license.md b/1801BM1_vm80a/license.md new file mode 100644 index 0000000000000000000000000000000000000000..e943acc41a0a5679655eecef34ab2c279c08e15c --- /dev/null +++ b/1801BM1_vm80a/license.md @@ -0,0 +1,328 @@ +## Creative Commons 3.0 CC-BY license + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL +SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT +RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. +CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, +AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE. + +#### License + +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE +COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY +COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS +AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE +TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE +CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED +HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. + +#### 1. Definitions + +"Adaptation" means a work based upon the Work, or upon the Work and other +pre-existing works, such as a translation, adaptation, derivative work, +arrangement of music or other alterations of a literary or artistic work, +or phonogram or performance and includes cinematographic adaptations or +any other form in which the Work may be recast, transformed, or adapted +including in any form recognizably derived from the original, except that +a work that constitutes a Collection will not be considered an Adaptation +for the purpose of this License. For the avoidance of doubt, where the Work +is a musical work, performance or phonogram, the synchronization of the +Work in timed-relation with a moving image ("synching") will be considered +an Adaptation for the purpose of this License. + +"Collection" means a collection of literary or artistic works, such as +encyclopedias and anthologies, or performances, phonograms or broadcasts, +or other works or subject matter other than works listed in Section 1(f) +below, which, by reason of the selection and arrangement of their contents, +constitute intellectual creations, in which the Work is included in its +entirety in unmodified form along with one or more other contributions, +each constituting separate and independent works in themselves, which +together are assembled into a collective whole. A work that constitutes +a Collection will not be considered an Adaptation (as defined above) for +the purposes of this License. + +"Distribute" means to make available to the public the original and copies +of the Work or Adaptation, as appropriate, through sale or other transfer +of ownership. + +"Licensor" means the individual, individuals, entity or entities that +offer(s) the Work under the terms of this License. + +"Original Author" means, in the case of a literary or artistic work, +the individual, individuals, entity or entities who created the Work or +if no individual or entity can be identified, the publisher; and in +addition (i) in the case of a performance the actors, singers, musicians, +dancers, and other persons who act, sing, deliver, declaim, play in, +interpret or otherwise perform literary or artistic works or expressions +of folklore; (ii) in the case of a phonogram the producer being the person +or legal entity who first fixes the sounds of a performance or other sounds; +and, (iii) in the case of broadcasts, the organization that transmits +the broadcast. + +"Work" means the literary and/or artistic work offered under the terms +of this License including without limitation any production in the literary, +scientific and artistic domain, whatever may be the mode or form of its +expression including digital form, such as a book, pamphlet and other +writing; a lecture, address, sermon or other work of the same nature; +a dramatic or dramatico-musical work; a choreographic work or entertainment +in dumb show; a musical composition with or without words; a cinematographic +work to which are assimilated works expressed by a process analogous to +cinematography; a work of drawing, painting, architecture, sculpture, +engraving or lithography; a photographic work to which are assimilated +works expressed by a process analogous to photography; a work of applied art; +an illustration, map, plan, sketch or three-dimensional work relative to +geography, topography, architecture or science; a performance; a broadcast; +a phonogram; a compilation of data to the extent it is protected as +a copyrightable work; or a work performed by a variety or circus performer +to the extent it is not otherwise considered a literary or artistic work. + +"You" means an individual or entity exercising rights under this License +who has not previously violated the terms of this License with respect to +the Work, or who has received express permission from the Licensor +to exercise rights under this License despite a previous violation. + +"Publicly Perform" means to perform public recitations of the Work and +to communicate to the public those public recitations, by any means or +process, including by wire or wireless means or public digital performances; +to make available to the public Works in such a way that members of the +public may access these Works from a place and at a place individually +chosen by them; to perform the Work to the public by any means or process +and the communication to the public of the performances of the Work, +including by public digital performance; to broadcast and rebroadcast +the Work by any means including signs, sounds or images. + +"Reproduce" means to make copies of the Work by any means including without +limitation by sound or visual recordings and the right of fixation and +reproducing fixations of the Work, including storage of a protected +performance or phonogram in digital form or other electronic medium. + +#### 2. Fair Dealing Rights. + +Nothing in this License is intended to reduce, limit, or restrict any uses +free from copyright or rights arising from limitations or exceptions that +are provided for in connection with the copyright protection under copyright +law or other applicable laws. + +#### 3. License Grant. + +Subject to the terms and conditions of this License, Licensor hereby grants +You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of +the applicable copyright) license to exercise the rights in the Work as +stated below: + +to Reproduce the Work, to incorporate the Work into one or more +Collections, and to Reproduce the Work as incorporated in the Collections; + +to create and Reproduce Adaptations provided that any such Adaptation, +including any translation in any medium, takes reasonable steps to clearly +label, demarcate or otherwise identify that changes were made to the +original Work. For example, a translation could be marked "The original +work was translated from English to Spanish," or a modification could +indicate "The original work has been modified."; + +to Distribute and Publicly Perform the Work including as incorporated +in Collections; and, + +to Distribute and Publicly Perform Adaptations. + +For the avoidance of doubt: + +Non-waivable Compulsory License Schemes. In those jurisdictions in which +the right to collect royalties through any statutory or compulsory licensing +scheme cannot be waived, the Licensor reserves the exclusive right to +collect such royalties for any exercise by You of the rights granted under +this License; + +Waivable Compulsory License Schemes. In those jurisdictions in which the +right to collect royalties through any statutory or compulsory licensing +scheme can be waived, the Licensor waives the exclusive right to collect +such royalties for any exercise by You of the rights granted under this +License; and, + +Voluntary License Schemes. The Licensor waives the right to collect +royalties, whether individually or, in the event that the Licensor is +a member of a collecting society that administers voluntary licensing +schemes, via that society, from any exercise by You of the rights +granted under this License. + +The above rights may be exercised in all media and formats whether now +known or hereafter devised. The above rights include the right to make +such modifications as are technically necessary to exercise the rights +in other media and formats. Subject to Section 8(f), all rights not +expressly granted by Licensor are hereby reserved. + +#### 4. Restrictions. + +The license granted in Section 3 above is expressly made subject to +and limited by the following restrictions: + +You may Distribute or Publicly Perform the Work only under the terms +of this License. You must include a copy of, or the Uniform Resource +Identifier (URI) for, this License with every copy of the Work You +Distribute or Publicly Perform. You may not offer or impose any terms +on the Work that restrict the terms of this License or the ability +of the recipient of the Work to exercise the rights granted to that +recipient under the terms of the License. You may not sublicense the Work. + +You must keep intact all notices that refer to this License and to the +disclaimer of warranties with every copy of the Work You Distribute +or Publicly Perform. When You Distribute or Publicly Perform the Work, +You may not impose any effective technological measures on the Work +that restrict the ability of a recipient of the Work from You to exercise +the rights granted to that recipient under the terms of the License. +This Section 4(a) applies to the Work as incorporated in a Collection, +but this does not require the Collection apart from the Work itself to +be made subject to the terms of this License. If You create a Collection, +upon notice from any Licensor You must, to the extent practicable, remove +from the Collection any credit as required by Section 4(b), as requested. +If You create an Adaptation, upon notice from any Licensor You must, +to the extent practicable, remove from the Adaptation any credit as +required by Section 4(b), as requested. + +If You Distribute, or Publicly Perform the Work or any Adaptations or +Collections, You must, unless a request has been made pursuant to +Section 4(a), keep intact all copyright notices for the Work and provide, +reasonable to the medium or means You are utilizing: (i) the name of +the Original Author (or pseudonym, if applicable) if supplied, and/or +if the Original Author and/or Licensor designate another party or +parties (e.g., a sponsor institute, publishing entity, journal) for +attribution ("Attribution Parties") in Licensor's copyright notice, +terms of service or by other reasonable means, the name of such party +or parties; (ii) the title of the Work if supplied; (iii) to the extent +reasonably practicable, the URI, if any, that Licensor specifies to be +associated with the Work, unless such URI does not refer to the copyright +notice or licensing information for the Work; and (iv) , consistent +with Section 3(b), in the case of an Adaptation, a credit identifying +the use of the Work in the Adaptation (e.g., "French translation of +the Work by Original Author," or "Screenplay based on original Work +by Original Author"). The credit required by this Section 4 (b) may be +implemented in any reasonable manner; provided, however, that in the case +of a Adaptation or Collection, at a minimum such credit will appear, +if a credit for all contributing authors of the Adaptation or Collection +appears, then as part of these credits and in a manner at least as +prominent as the credits for the other contributing authors. + +For the avoidance of doubt, You may only use the credit required by +this Section for the purpose of attribution in the manner set out +above and, by exercising Your rights under this License, You may not +implicitly or explicitly assert or imply any connection with, sponsorship +or endorsement by the Original Author, Licensor and/or Attribution Parties, +as appropriate, of You or Your use of the Work, without the separate, +express prior written permission of the Original Author, Licensor +and/or Attribution Parties. Except as otherwise agreed in writing by +the Licensor or as may be otherwise permitted by applicable law, if +You Reproduce, Distribute or Publicly Perform the Work either by itself +or as part of any Adaptations or Collections, You must not distort, +mutilate, modify or take other derogatory action in relation to the +Work which would be prejudicial to the Original Author's honor or +reputation. Licensor agrees that in those jurisdictions (e.g. Japan), +in which any exercise of the right granted in Section 3(b) of this +License (the right to make Adaptations) would be deemed to be a distortion, +mutilation, modification or other derogatory action prejudicial to the +Original Author's honor and reputation, the Licensor will waive or not +assert, as appropriate, this Section, to the fullest extent permitted +by the applicable national law, to enable You to reasonably exercise +Your right under Section 3(b) of this License (right to make Adaptations) +but not otherwise. + +#### 5. Representations, Warranties and Disclaimer + +UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR +OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY +KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, +INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, +FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT +OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER +OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED +WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. + +#### 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, +IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY +SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING +OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN +ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 7. Termination + +This License and the rights granted hereunder will terminate automatically +upon any breach by You of the terms of this License. Individuals or entities +who have received Adaptations or Collections from You under this License, +however, will not have their licenses terminated provided such individuals or +entities remain in full compliance with those licenses. Sections 1, 2, 5, +6, 7, and 8 will survive any termination of this License. + +Subject to the above terms and conditions, the license granted here is +perpetual (for the duration of the applicable copyright in the Work). +Notwithstanding the above, Licensor reserves the right to release the Work +under different license terms or to stop distributing the Work at any time; +provided, however that any such election will not serve to withdraw this +License (or any other license that has been, or is required to be, granted +under the terms of this License), and this License will continue in full +force and effect unless terminated as stated above. + +#### 8. Miscellaneous + +Each time You Distribute or Publicly Perform the Work or a Collection, +the Licensor offers to the recipient a license to the Work on the same +terms and conditions as the license granted to You under this License. + +Each time You Distribute or Publicly Perform an Adaptation, Licensor offers +to the recipient a license to the original Work on the same terms and +conditions as the license granted to You under this License. + +If any provision of this License is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this License, and without further action by +the parties to this agreement, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable. + +No term or provision of this License shall be deemed waived and no breach +consented to unless such waiver or consent shall be in writing and signed +by the party to be charged with such waiver or consent. + +This License constitutes the entire agreement between the parties with +respect to the Work licensed here. There are no understandings, agreements +or representations with respect to the Work not specified here. Licensor +shall not be bound by any additional provisions that may appear in any +communication from You. This License may not be modified without the +mutual written agreement of the Licensor and You. + +The rights granted under, and the subject matter referenced, in this +License were drafted utilizing the terminology of the Berne Convention +for the Protection of Literary and Artistic Works (as amended on September 28, +1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, +the WIPO Performances and Phonograms Treaty of 1996 and the Universal +Copyright Convention (as revised on July 24, 1971). These rights and +subject matter take effect in the relevant jurisdiction in which the +License terms are sought to be enforced according to the corresponding +provisions of the implementation of those treaty provisions in the +applicable national law. If the standard suite of rights granted under +applicable copyright law includes additional rights not granted under +this License, such additional rights are deemed to be included in the +License; this License is not intended to restrict the license of any +rights under applicable law. + +#### Creative Commons Notice + +Creative Commons is not a party to this License, and makes no warranty +whatsoever in connection with the Work. Creative Commons will not be +liable to You or any party on any legal theory for any damages whatsoever, +including without limitation any general, special, incidental or +consequential damages arising in connection to this license. +Notwithstanding the foregoing two (2) sentences, if Creative Commons +has expressly identified itself as the Licensor hereunder, it shall +have all rights and obligations of Licensor. + +Except for the limited purpose of indicating to the public that the Work +is licensed under the CCPL, Creative Commons does not authorize the use +by either party of the trademark "Creative Commons" or any related +trademark or logo of Creative Commons without the prior written consent +of Creative Commons. Any permitted use will be in compliance with +Creative Commons' then-current trademark usage guidelines, as may be +published on its website or otherwise made available upon request from +time to time. For the avoidance of doubt, this trademark restriction +does not form part of this License. + +Creative Commons may be contacted at https://creativecommons.org/. diff --git a/1801BM1_vm80a/org/rtl/ax309/ax309_mem.v b/1801BM1_vm80a/org/rtl/ax309/ax309_mem.v new file mode 100644 index 0000000000000000000000000000000000000000..375209277ff3c899074ba0c9e40cf55d0f36c505 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/ax309/ax309_mem.v @@ -0,0 +1,34 @@ +`timescale 1ns/1ps + +module ax309_mem +( + input [13:0] addra, + input clka, + input [7:0] dina, + input wea, + output [7:0] douta +); + +reg [7:0] mem [0:16383]; +reg [13:0] areg; +reg wreg; + +always @ (posedge clka) +begin + areg <= addra; + wreg <= wea; + + if (wreg) + mem[areg] <= dina; +end + +assign douta = mem[areg]; +// +// $readmemh synthezable in XST +// Use inferred block memory instead core generator (work too boring, difficult to change content) +// +initial +begin + $readmemh("..\\..\\..\\tst\\rom\\memini.mem", mem, 0, 16383); +end +endmodule diff --git a/1801BM1_vm80a/org/rtl/ax309/ax309_top.v b/1801BM1_vm80a/org/rtl/ax309/ax309_top.v new file mode 100644 index 0000000000000000000000000000000000000000..e44838fda23dfcfaad4d440e65482070e7e3ef66 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/ax309/ax309_top.v @@ -0,0 +1,298 @@ +//______________________________________________________________________________ +// +// Top module for AX309 board based system +// +//______________________________________________________________________________ +// +// External oscillator clock, feeds the PLLs +// +`define OSC_CLOCK 50000000 +// +// Global system clock +// +`define SYS_CLOCK 50000000 +// +// Console baudrate +// +`define SYS_BAUD 115200 +//______________________________________________________________________________ +// +// Reset button debounce interval (in ms)) +// +`define RESET_BUTTON_DEBOUNCE_MS 5 +// +// Internal reset pulse width (in system clocks) +// +`define RESET_PULSE_WIDTH_CLK 7 + +//______________________________________________________________________________ +// +// Top project module - instantiates the AX309 board itself +// +module ax309 +( + input ax3_clock_50, // clock input 50 MHz + // + input ax3_reset_n, // push reset button + input [3:0] ax3_button, // push button [3:0] + output [3:0] ax3_led, // led outputs [3:0] + output [7:0] ax3_hex, // seven segment digit mask + output [5:0] ax3_hsel, // seven segment digit select +// output ax3_buzzer, // + // + output ax3_uart_txd, // UART transmitter + input ax3_uart_rxd // UART receiver +// // +// inout [15:0] ax3_dram_dq, // SDRAM data bus 16 bits +// output [12:0] ax3_dram_addr, // SDRAM address bus 13 bits +// output ax3_dram_ldqm, // SDRAM low-byte data mask +// output ax3_dram_udqm, // SDRAM high-byte data mask +// output ax3_dram_we_n, // SDRAM write enable +// output ax3_dram_cas_n, // SDRAM column address strobe +// output ax3_dram_ras_n, // SDRAM row address strobe +// output ax3_dram_cs_n, // SDRAM chip select +// output [1:0] ax3_dram_ba, // SDRAM bank address +// output ax3_dram_clk, // SDRAM clock +// output ax3_dram_cke, // SDRAM clock enable +// // +// output ax3_spi_cs_n, // SPI FLASH chip select +// output ax3_spi_clk, // SPI FLASH clock +// output ax3_spi_mosi, // SPI FLASH master output +// input ax3_spi_miso, // SPI FLASH master input +// // +// inout ax3_sd_cs_n, // SD Card chip select +// inout ax3_sd_clk, // SD Card clock +// inout ax3_sd_mosi, // SD Card master output +// inout ax3_sd_miso, // SD Card master input +// // +// inout ax3_i2c_clk, // I2C Clock +// inout ax3_i2c_dat, // I2C Data +// output ax3_rtc_rst_n, // RTC DS1302 reset +// output ax3_rtc_sclk, // RTC DS1302_serial clock +// inout ax3_rtc_sdat, // RTC DS1302 serial data_ +// // +// output ax3_vga_hs, // VGA H_SYNC +// output ax3_vga_vs, // VGA V_SYNC +// output [4:0] ax3_vga_r, // VGA Red[4:0] +// output [5:0] ax3_vga_g, // VGA Green[5:0] +// output [4:0] ax3_vga_b, // VGA Blue[4:0] +// // +// inout [33:0] ax3_gpio0, // GPIO Connection 0 +// inout [33:0] ax3_gpio1 // GPIO Connection 1 +); + +//______________________________________________________________________________ +// +// Top module for AX309 board based system +// +wire [31:0] baud = 921600/`SYS_BAUD-1; +wire clk, wr_n, rst_n, dbin; +wire [7:0] dcpu; +wire [7:0] dsys; +wire [7:0] dsio; +wire [7:0] dram; +wire [15:0] a; +wire uack; + +reg f1, f2; +reg [7:0] hex0, hex1, hex2, hex3, hex4, hex5; +reg [2:0] hsel; +reg [1:0] led; +reg [7:0] rcnt = 8'h00; +reg [2:0] div; +reg [15:0] div1ms; +reg ms, intrq, inta; +wire inte, sync; + +assign clk = ax3_clock_50; +assign rst_n = (rcnt == 8'hFF); +assign dsys = inta ? 8'hE7 + : (a[15:8] == 8'hFF) ? {4'h0, ax3_button[3:0]} + : (a[15:8] == 8'hFE) ? dsio + : dram; + +assign ax3_hex = (hsel == 3'b000) ? ~hex0 + : (hsel == 3'b001) ? ~hex1 + : (hsel == 3'b010) ? ~hex2 + : (hsel == 3'b011) ? ~hex3 + : (hsel == 3'b100) ? ~hex4 + : (hsel == 3'b101) ? ~hex5 : 8'hFF; + +assign ax3_hsel[0] = ~(hsel == 3'b000); +assign ax3_hsel[1] = ~(hsel == 3'b001); +assign ax3_hsel[2] = ~(hsel == 3'b010); +assign ax3_hsel[3] = ~(hsel == 3'b011); +assign ax3_hsel[4] = ~(hsel == 3'b100); +assign ax3_hsel[5] = ~(hsel == 3'b101); + +always @(posedge clk) +begin + div <= div + 3'b001; + f1 <= div[0]; + f2 <= ~div[0]; + + if (sync) inta = dcpu[0]; + if (div1ms == ((`SYS_CLOCK/1000)-1)) + begin + div1ms <= 16'h0000; + ms <= 1; + end + else + begin + div1ms <= div1ms + 16'h0001; + ms <= 0; + end + + if (ms) intrq <= 1; + if (inta) intrq <= 0; + + if (~rst_n) + hsel <= 3'b000; + else + if (ms) + if (hsel == 3'b000) + hsel <= 3'b101; + else + hsel <= hsel - 3'b001; +end + +always @(posedge clk) +begin + if (~ax3_reset_n) + rcnt <= 8'h00; + else + if (rcnt != 8'hFF) rcnt <= rcnt + 8'h01; +end + +/* +memini ram +( + .address(a[13:0]), + .clock(clk), + .wren(~wr_n & rst_n & ~a[15] & ~a[14]), + .data(dcpu), + .q(dram) +); +*/ +ax309_mem ram +( + .addra(a[13:0]), + .clka(clk), + .wea(~wr_n & rst_n & ~a[15] & ~a[14]), + .dina(dcpu), + .douta(dram) +); + +always @(posedge clk) +begin + if (~wr_n) + begin + if (a == 16'hFFFB) led <= dcpu[1:0]; + if (a == 16'hFFFC) hex0 <= dcpu[7:0]; + if (a == 16'hFFFD) hex1 <= dcpu[7:0]; + if (a == 16'hFFFE) hex2 <= dcpu[7:0]; + if (a == 16'hFFFF) hex3 <= dcpu[7:0]; + if (a == 16'hFFF0) hex4 <= dcpu[7:0]; + if (a == 16'hFFF1) hex5 <= dcpu[7:0]; + end +end + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam uart.REFCLK = `SYS_CLOCK; +`endif + +uart_wb uart +( + .wb_clk_i(clk), + .wb_rst_i(~rst_n), + .wb_adr_i(a[0]), + .wb_dat_i(dcpu), + .wb_dat_o(dsio), + .wb_cyc_i((~wr_n | dbin) & (a[15:8] == 8'hFE)), + .wb_we_i(~wr_n & (a[15:8] == 8'hFE)), + .wb_stb_i((~wr_n | (dbin & ~uack)) & (a[15:8] == 8'hFE)), + .wb_ack_o(uack), + + .tx_dat_o(ax3_uart_txd), + .tx_cts_i(1'b0), + .rx_dat_i(ax3_uart_rxd), + +// .rx_dtr_o(), +// .tx_ready(), +// .tx_empty(), +// .rx_ready(), + + .cfg_bdiv(baud[15:0]), + .cfg_nbit(2'b11), + .cfg_nstp(1'b1), + .cfg_pena(1'b0), + .cfg_podd(1'b0) +); + +vm80a_core cpu +( + .pin_clk(clk), + .pin_f1(f1), + .pin_f2(f2), + .pin_reset(~rst_n), + .pin_a(a), + .pin_dout(dcpu), + .pin_din(dsys), + .pin_hold(1'b0), + .pin_ready(1'b1), + .pin_int(intrq), + .pin_wr_n(wr_n), + .pin_dbin(dbin), + .pin_inte(inte), + .pin_sync(sync) +); + +assign ax3_led[1:0] = led; +assign ax3_led[2] = ~wr_n; +assign ax3_led[3] = sync; + +//______________________________________________________________________________ +// +// Temporary and debug assignments +// +// assign ax3_dram_dq = 16'hzzzz; +// assign ax3_dram_addr = 13'h0000; +// assign ax3_dram_ldqm = 1'b0; +// assign ax3_dram_udqm = 1'b0; +// assign ax3_dram_we_n = 1'b1; +// assign ax3_dram_cas_n = 1'b1; +// assign ax3_dram_ras_n = 1'b1; +// assign ax3_dram_cs_n = 1'b1; +// assign ax3_dram_ba[0] = 1'b0; +// assign ax3_dram_ba[1] = 1'b0; +// assign ax3_dram_clk = 1'b0; +// assign ax3_dram_cke = 1'b0; +// +// assign ax3_spi_cs_n = 1'b1; +// assign ax3_spi_clk = 1'b0; +// assign ax3_spi_mosi = 1'bz; +// +// assign ax3_sd_cs_n = 1'bz; +// assign ax3_sd_clk = 1'b0; +// assign ax3_sd_mosi = 1'bz; +// assign ax3_sd_miso = 1'bz; +// +// assign ax3_i2c_dat = 1'hz; +// assign ax3_i2c_clk = 1'hz; +// assign ax3_rtc_rst_n = 1'hz; +// assign ax3_rtc_sclk = 1'hz; +// assign ax3_rtc_sdat = 1'hz; +assign ax3_buzzer = 1'hz; +// +// assign ax3_vga_hs = 1'b0; +// assign ax3_vga_vs = 1'b0; +// assign ax3_vga_r = 5'h0; +// assign ax3_vga_g = 6'h0; +// assign ax3_vga_b = 5'h0; +// +// assign ax3_gpio0 = 34'hzzzzzzzzz; +// assign ax3_gpio1 = 34'hzzzzzzzzz; +// +endmodule diff --git a/1801BM1_vm80a/org/rtl/ax309/ax309_uart.v b/1801BM1_vm80a/org/rtl/ax309/ax309_uart.v new file mode 100644 index 0000000000000000000000000000000000000000..3dc00014e21439a6ad9a4c1bf00e624cee436fc9 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/ax309/ax309_uart.v @@ -0,0 +1,378 @@ +// +// Copyright (c) 2014-2015 by 1801BM1@gmail.com +// +// Universal Serial Asynchronous Receiver-Transmitter (simplified 8251) +//______________________________________________________________________________ +// +module uart_wb #(parameter REFCLK=50000000) +( + input wb_clk_i, // system clock + input wb_rst_i, // peripheral reset + // + input [0:0] wb_adr_i, // + input [7:0] wb_dat_i, // + output reg [7:0] wb_dat_o, // + input wb_cyc_i, // + input wb_we_i, // + input wb_stb_i, // + output reg wb_ack_o, // + // + output tx_dat_o, // output serial data (txd) + input tx_cts_i, // enable transmitter (rts) + input rx_dat_i, // input serial data (rxd) + output rx_dtr_o, // receiver ready (cts) + // + output tx_ready_o, // tx ready request + output tx_empty_o, // tx empty request + output rx_ready_o, // rx ready request + // + input [15:0] cfg_bdiv, // baudrate divisor: (921600/baud)-1 + input [1:0] cfg_nbit, // word length: 00-5, 01-6, 10-7, 11-8 bit + input cfg_nstp, // tx stop bits: 0 - 1 stop, 1 - 2 stop + input cfg_pena, // parity control enable + input cfg_podd // odd parity (complete to odd ones) +); + +wire [63:0] add_arg; +reg [16:0] add_reg; +reg [15:0] baud_div; +reg baud_x16; +wire baud_ref; + +reg [1:0] tx_cts_reg; +reg [1:0] rx_dat_reg; + +wire csr_wstb; +wire rbr_rstb; +wire thr_wstb; + +wire tx_par; +reg [7:0] tx_thr; +reg [9:0] tx_shr; +reg [7:0] tx_bcnt; +reg tx_busy; +reg tx_ready, tx_empty, tx_break; + +wire rx_dat; +reg [7:0] rx_rbr; +reg [8:0] rx_shr; +reg [7:0] rx_bcnt; +reg rx_ready, rx_perr, rx_ovf, rx_break; +wire rx_load, rx_stb; +reg rx_frame, rx_start, rx_par; + +//______________________________________________________________________________ +// +// Caution note: the arithmetic expressions should be calculated in 64-bit width +// +assign add_arg = (64'h0000000000100000 * 64'd921600)/REFCLK; +assign baud_ref = add_reg[16]; +// +// Phase accumulator to generate 921600 * 16 Hz reference clock strobe +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + add_reg <= 17'h00000; + else + begin + add_reg <= {1'b0, add_reg[15:0]} + add_arg[16:0]; + end +end +// +// Baud rate x16 generator +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + baud_div <= 16'h0000; + baud_x16 <= 1'b0; + end + else + begin + if (baud_ref) + if (baud_div == 16'h0000) + baud_div <= cfg_bdiv; + else + baud_div <= baud_div - 16'h0001; + + baud_x16 <= baud_ref & (baud_div == 16'h0000); + end + +end + +//______________________________________________________________________________ +// +assign csr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & wb_adr_i[0]; +assign thr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & ~wb_adr_i[0]; +assign rbr_rstb = wb_cyc_i & wb_stb_i & ~wb_we_i & ~wb_ack_o & ~wb_adr_i[0]; +// +// Output data multiplexed register +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + wb_dat_o <= 8'h00; + else +// +// if (wb_cyc_i & wb_stb_i & ~wb_ack_o) +// + begin + if (wb_adr_i[0]) + wb_dat_o <= (tx_ready << 7) + | (tx_break << 6) + | (tx_empty << 5) + | (rx_ready << 3) + | (rx_break << 2) + | (rx_perr << 1) + | (rx_ovf << 0); + else + wb_dat_o <= rx_rbr; + end +end + +always @(posedge wb_clk_i) + wb_ack_o <= wb_cyc_i & wb_stb_i & ~wb_ack_o; + +// +// Control register bits +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + tx_break <= 1'b0; + else + if (csr_wstb) tx_break <= wb_dat_i[6]; +end + +//______________________________________________________________________________ +// +// Interrupts +// +assign tx_ready_o = tx_ready; +assign tx_empty_o = tx_empty; +assign rx_ready_o = rx_ready; + +//______________________________________________________________________________ +// +// Metastability issues +// +always @(posedge wb_clk_i) +begin + tx_cts_reg[0] <= ~tx_cts_i; + tx_cts_reg[1] <= tx_cts_reg[0]; + + rx_dat_reg[0] <= rx_dat_i; + rx_dat_reg[1] <= rx_dat_reg[0]; +end + +//______________________________________________________________________________ +// +// Transmitter unit +// +assign tx_par = tx_thr[0] ^ tx_thr[1] ^ tx_thr[2] ^ tx_thr[3] ^ tx_thr[4] + ^ (tx_thr[5] & (cfg_nbit >= 2'b01)) + ^ (tx_thr[6] & (cfg_nbit >= 2'b10)) + ^ (tx_thr[7] & (cfg_nbit == 2'b11)) + ^ cfg_podd; +assign tx_dat_o = tx_shr[0] & ~tx_break; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + tx_ready <= 1'b1; + tx_empty <= 1'b1; + tx_shr <= 10'o1777; + tx_busy <= 1'b0; + tx_bcnt <= 8'b00000000; + tx_thr <= 8'b00000000; + end + else + begin + tx_empty <= tx_ready & ~tx_busy; + // + // Transmitter hold register write + // + if (thr_wstb) + begin + tx_ready <= 1'b0; + tx_thr <= wb_dat_i[7:0]; + end + + if (baud_x16) + begin + // + // Transmit process + // + if (tx_busy) + begin + if (tx_bcnt == 8'b00000001) + tx_busy <= 1'b0; + + if (tx_bcnt != 8'b00000000) + tx_bcnt <= tx_bcnt - 8'b00000001; + + if (tx_bcnt[3:0] == 4'b0000) + tx_shr <= {1'b1, tx_shr[9:1]}; + end + + // + // Starting new word transmit + // + if (~tx_ready & ~tx_busy & tx_cts_reg[1]) + begin + tx_busy <= 1'b1; + tx_ready <= ~thr_wstb; + tx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena} + {3'b000, cfg_nstp}, 4'b1111}; + + if (cfg_pena) + case(cfg_nbit) + 2'b00: tx_shr <= {3'b111, tx_par, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {2'b11, tx_par, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {1'b1, tx_par, tx_thr[6:0], 1'b0}; + default: tx_shr <= { tx_par, tx_thr[7:0], 1'b0}; + endcase + else + case(cfg_nbit) + 2'b00: tx_shr <= {4'b1111, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {3'b111, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {2'b11, tx_thr[6:0], 1'b0}; + default: tx_shr <= {1'b1, tx_thr[7:0], 1'b0}; + endcase + end + end + end +end + +//______________________________________________________________________________ +// +// Receiver unit +// +assign rx_dtr_o = rx_ready; +assign rx_dat = rx_dat_reg[1]; + +assign rx_load = rx_stb & (rx_bcnt[7:4] == 4'b0000); +assign rx_stb = (rx_bcnt[3:0] == 4'b0001) & baud_x16; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + rx_ready <= 1'b0; + rx_break <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + rx_frame <= 1'b0; + rx_start <= 1'b0; + rx_par <= 1'b0; + rx_rbr <= 8'b00000000; + rx_shr <= 9'b00000000; + rx_bcnt <= 8'b00000000; + end + else + begin + if (rx_load) + begin + rx_ready <= 1'b1; + case(cfg_nbit) + 2'b00: rx_rbr <= {3'b000, rx_shr[4:0]}; + 2'b01: rx_rbr <= {2'b00, rx_shr[5:0]}; + 2'b10: rx_rbr <= {1'b0, rx_shr[6:0]}; + default: rx_rbr <= rx_shr[7:0]; + endcase + rx_perr <= rx_par; + rx_ovf <= rx_ready; + rx_break <= ~rx_dat; + end + else + if (rbr_rstb) + begin + rx_ready <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + end + + if (baud_x16) + begin + if (~rx_frame) + // + // Waiting for start bit + // + if (~rx_dat) + begin + rx_par <= cfg_pena & cfg_podd; + rx_start <= 1'b1; + rx_frame <= 1'b1; + rx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena}, 4'b0111}; + end + else + begin + rx_start <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + begin + // + // Receiving frame + // + if (rx_bcnt != 8'b00000000) + rx_bcnt <= rx_bcnt - 8'b00000001; + // + // Start bit monitoring + // + if (rx_start) + begin + if (rx_dat) + begin + // + // Spurrious start bit + // + rx_start <= 1'b0; + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + if (rx_bcnt[3:0] == 4'b0010) + rx_start <= 1'b0; + end + else + begin + // + // Receiving data + // + if (rx_stb) + begin + rx_par <= (rx_par ^ rx_dat) & cfg_pena; + if (cfg_pena) + case(cfg_nbit) + 2'b00: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b01: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + 2'b10: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + default: rx_shr <= {rx_dat, rx_shr[8:1]}; + endcase + else + case(cfg_nbit) + 2'b00: rx_shr <= {4'b0000, rx_dat, rx_shr[4:1]}; + 2'b01: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b10: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + default: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + endcase + if (rx_load & rx_dat) + begin + // + // Stop bit detected + // + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + end + if ((rx_bcnt == 8'b00000000) & rx_dat) + rx_frame <= 1'b0; + end + end + end + end +end +endmodule diff --git a/1801BM1_vm80a/org/rtl/de0/de0_mem.v b/1801BM1_vm80a/org/rtl/de0/de0_mem.v new file mode 100644 index 0000000000000000000000000000000000000000..35121a76c1ae53fe8156e7669c3ad131d2ee1a8c --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de0/de0_mem.v @@ -0,0 +1,104 @@ +// megafunction wizard: %RAM: 1-PORT% +// GENERATION: STANDARD +// VERSION: WM1.0 +// MODULE: altsyncram + +// ============================================================ +// File Name: de0_mem.v +// Megafunction Name(s): +// altsyncram +// +// Simulation Library Files(s): +// altera_mf +// ============================================================ +// ************************************************************ +// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! +// +// 12.1 Build 177 11/07/2012 SJ Full Version +// ************************************************************ + + +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. + + +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module memini ( + address, + clock, + data, + wren, + q); + + input [13:0] address; + input clock; + input [7:0] data; + input wren; + output [7:0] q; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_off +`endif + tri1 clock; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_on +`endif + + wire [7:0] sub_wire0; + wire [7:0] q = sub_wire0[7:0]; + + altsyncram altsyncram_component ( + .address_a (address), + .clock0 (clock), + .data_a (data), + .wren_a (wren), + .q_a (sub_wire0), + .aclr0 (1'b0), + .aclr1 (1'b0), + .address_b (1'b1), + .addressstall_a (1'b0), + .addressstall_b (1'b0), + .byteena_a (1'b1), + .byteena_b (1'b1), + .clock1 (1'b1), + .clocken0 (1'b1), + .clocken1 (1'b1), + .clocken2 (1'b1), + .clocken3 (1'b1), + .data_b (1'b1), + .eccstatus (), + .q_b (), + .rden_a (1'b1), + .rden_b (1'b1), + .wren_b (1'b0)); + defparam + altsyncram_component.clock_enable_input_a = "BYPASS", + altsyncram_component.clock_enable_output_a = "BYPASS", + altsyncram_component.init_file = "../../../tst/rom/memini.mif", + altsyncram_component.intended_device_family = "Cyclone III", + altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO", + altsyncram_component.lpm_type = "altsyncram", + altsyncram_component.numwords_a = 16384, + altsyncram_component.operation_mode = "SINGLE_PORT", + altsyncram_component.outdata_aclr_a = "NONE", + altsyncram_component.outdata_reg_a = "UNREGISTERED", + altsyncram_component.power_up_uninitialized = "FALSE", + altsyncram_component.ram_block_type = "M9K", + altsyncram_component.read_during_write_mode_port_a = "DONT_CARE", + altsyncram_component.widthad_a = 14, + altsyncram_component.width_a = 8, + altsyncram_component.width_byteena_a = 1; + +endmodule diff --git a/1801BM1_vm80a/org/rtl/de0/de0_top.v b/1801BM1_vm80a/org/rtl/de0/de0_top.v new file mode 100644 index 0000000000000000000000000000000000000000..9e9a95772f8ae3fdd9cfe8a214312d57748440f4 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de0/de0_top.v @@ -0,0 +1,300 @@ +//______________________________________________________________________________ +// +// Top module for DE0 board based system + +//______________________________________________________________________________ +// +// External oscillator clock, feeds the PLLs +// +`define OSC_CLOCK 50000000 +// +// Global system clock +// +`define SYS_CLOCK 50000000 +// +// Console baudrate +// +`define SYS_BAUD 115200 +//______________________________________________________________________________ +// +// Reset button debounce interval (in ms)) +// +`define RESET_BUTTON_DEBOUNCE_MS 5 +// +// Internal reset pulse width (in system clocks) +// +`define RESET_PULSE_WIDTH_CLK 7 + +//______________________________________________________________________________ +// +// Top project module - instantiates the DE0 board itself +// +module de0 +( + input de0_clock_50, // clock input 50 MHz + input de0_clock_50_2, // clock input 50 MHz + // + input [2:0] de0_button, // push button[2:0] + // + input [9:0] de0_sw, // DPDT toggle switch[9:0] + output [7:0] de0_hex0, // seven segment digit 0 + output [7:0] de0_hex1, // seven segment digit 1 + output [7:0] de0_hex2, // seven segment digit 2 + output [7:0] de0_hex3, // seven segment digit 3 + output [9:0] de0_led, // LED green[9:0] + // + output de0_uart_txd, // UART transmitter + input de0_uart_rxd, // UART receiver + output de0_uart_cts, // UART clear to send + input de0_uart_rts, // UART request to send + // + inout [15:0] de0_dram_dq, // SDRAM data bus 16 bits + output [12:0] de0_dram_addr, // SDRAM address bus 13 bits + output de0_dram_ldqm, // SDRAM low-byte data mask + output de0_dram_udqm, // SDRAM high-byte data mask + output de0_dram_we_n, // SDRAM write enable + output de0_dram_cas_n, // SDRAM column address strobe + output de0_dram_ras_n, // SDRAM row address strobe + output de0_dram_cs_n, // SDRAM chip select + output [1:0] de0_dram_ba, // SDRAM bank address + output de0_dram_clk, // SDRAM clock + output de0_dram_cke, // SDRAM clock enable + // + inout [15:0] de0_fl_dq, // FLASH data bus 15 Bits + output [21:0] de0_fl_addr, // FLASH address bus 22 Bits + output de0_fl_we_n, // FLASH write enable + output de0_fl_rst_n, // FLASH reset + output de0_fl_oe_n, // FLASH output enable + output de0_fl_ce_n, // FLASH chip enable + output de0_fl_wp_n, // FLASH hardware write protect + output de0_fl_byte_n, // FLASH selects 8/16-bit mode + input de0_fl_rb, // FLASH ready/busy + // + output de0_lcd_blig, // LCD back light ON/OFF + output de0_lcd_rw, // LCD read/write select, 0 = write, 1 = read + output de0_lcd_en, // LCD enable + output de0_lcd_rs, // LCD command/data select, 0 = command, 1 = data + inout [7:0] de0_lcd_data, // LCD data bus 8 bits + // + inout de0_sd_mosi, // SD Card Data Output + inout de0_sd_miso, // SD Card Data Input + inout de0_sd_cmd, // SD Card Command Signal + output de0_sd_clk, // SD Card Clock + input de0_sd_wp_n, // SD Card Write Protect + // + inout de0_ps2_kbdat, // PS2 Keyboard Data + inout de0_ps2_kbclk, // PS2 Keyboard Clock + inout de0_ps2_msdat, // PS2 Mouse Data + inout de0_ps2_msclk, // PS2 Mouse Clock + // + output de0_vga_hs, // VGA H_SYNC + output de0_vga_vs, // VGA V_SYNC + output [3:0] de0_vga_r, // VGA Red[3:0] + output [3:0] de0_vga_g, // VGA Green[3:0] + output [3:0] de0_vga_b, // VGA Blue[3:0] + // + input [1:0] de0_gpio0_clkin, // GPIO Connection 0 Clock In Bus + output [1:0] de0_gpio0_clkout, // GPIO Connection 0 Clock Out Bus + inout [31:0] de0_gpio0_d, // GPIO Connection 0 Data Bus + // + input [1:0] de0_gpio1_clkin, // GPIO Connection 1 Clock In Bus + output [1:0] de0_gpio1_clkout, // GPIO Connection 1 Clock Out Bus + inout [31:0] de0_gpio1_d // GPIO Connection 1 Data Bus +); + +wire [31:0] baud = 921600/`SYS_BAUD-1; +wire clk, wr_n, rst_n, dbin; +wire [7:0] dcpu; +wire [7:0] dsys; +wire [7:0] dsio; +wire [7:0] dram; +wire [15:0] a; +wire uack; + +reg f1, f2; +reg [7:0] hex0, hex1, hex2, hex3; +reg [7:0] led; +reg [7:0] rcnt = 8'h00; +reg [2:0] div; +reg [15:0] div1ms; +reg ms, intrq, inta; +wire inte, sync; + +assign clk = de0_clock_50; +assign rst_n = (rcnt == 8'hFF); +assign dsys = inta ? 8'hE7 + : (a[15:8] == 8'hFF) ? {5'h00, de0_button[2:0]} + : (a[15:8] == 8'hFE) ? dsio + : dram; + +always @(posedge clk) +begin + div <= div + 3'b001; + f1 <= div[0]; + f2 <= ~div[0]; + + if (sync) inta = dcpu[0]; + if (div1ms == ((`SYS_CLOCK/1000)-1)) + begin + div1ms <= 16'h0000; + ms <= 1; + end + else + begin + div1ms <= div1ms + 16'h0001; + ms <= 0; + end + + if (ms) intrq <= 1; + if (inta) intrq <= 0; +end + +always @(posedge clk) +begin + if (~de0_button[2]) + rcnt <= 8'h00; + else + if (rcnt != 8'hFF) rcnt <= rcnt + 8'h01; +end + +memini ram +( + .address(a[13:0]), + .clock(clk), + .data(dcpu), + .wren(~wr_n & rst_n & ~a[15] & ~a[14]), + .q(dram) +); + +always @(posedge clk) +begin + if (~wr_n) + begin + if (a == 16'hFFFB) led <= dcpu; + if (a == 16'hFFFC) hex0 <= dcpu; + if (a == 16'hFFFD) hex1 <= dcpu; + if (a == 16'hFFFE) hex2 <= dcpu; + if (a == 16'hFFFF) hex3 <= dcpu; + end +end + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam uart.REFCLK = `SYS_CLOCK; +`endif + +uart_wb uart +( + .wb_clk_i(clk), + .wb_rst_i(~rst_n), + .wb_adr_i(a[0]), + .wb_dat_i(dcpu), + .wb_dat_o(dsio), + .wb_cyc_i((~wr_n | dbin) & (a[15:8] == 8'hFE)), + .wb_we_i(~wr_n & (a[15:8] == 8'hFE)), + .wb_stb_i((~wr_n | (dbin & ~uack)) & (a[15:8] == 8'hFE)), + .wb_ack_o(uack), + + .tx_dat_o(de0_uart_txd), + .tx_cts_i(1'b0), + .rx_dat_i(de0_uart_rxd), + .rx_dtr_o(de0_uart_cts), + +// .tx_ready(), +// .tx_empty(), +// .rx_ready(), + + .cfg_bdiv(baud[15:0]), + .cfg_nbit(2'b11), + .cfg_nstp(1'b1), + .cfg_pena(1'b0), + .cfg_podd(1'b0) +); + +vm80a_core cpu +( + .pin_clk(clk), + .pin_f1(f1), + .pin_f2(f2), + .pin_reset(~rst_n), + .pin_a(a), + .pin_dout(dcpu), + .pin_din(dsys), + .pin_hold(1'b0), + .pin_ready(1'b1), + .pin_int(intrq), + .pin_wr_n(wr_n), + .pin_dbin(dbin), + .pin_inte(inte), + .pin_sync(sync) +); + +assign de0_hex0 = ~hex0; +assign de0_hex1 = ~hex1; +assign de0_hex2 = ~hex2; +assign de0_hex3 = ~hex3; + +assign de0_led[7:0] = led; +assign de0_led[9] = ~wr_n; +assign de0_led[8] = sync; + +//______________________________________________________________________________ +// +// Temporary and debug assignments +// +// assign de0_uart_txd = 1'bz; +// assign de0_uart_cts = 1'bz; + +assign de0_dram_dq = 16'hzzzz; +assign de0_dram_addr = 13'h0000; +assign de0_dram_ldqm = 1'b0; +assign de0_dram_udqm = 1'b0; +assign de0_dram_we_n = 1'b1; +assign de0_dram_cas_n = 1'b1; +assign de0_dram_ras_n = 1'b1; +assign de0_dram_cs_n = 1'b1; +assign de0_dram_ba[0] = 1'b0; +assign de0_dram_ba[1] = 1'b0; +assign de0_dram_clk = 1'b0; +assign de0_dram_cke = 1'b0; + +assign de0_fl_dq = 16'hzzzz; +assign de0_fl_addr = 22'hzzzzzz; +assign de0_fl_we_n = 1'b1; +assign de0_fl_rst_n = 1'b0; +assign de0_fl_oe_n = 1'b1; +assign de0_fl_ce_n = 1'b1; +assign de0_fl_wp_n = 1'b0; +assign de0_fl_byte_n = 1'b1; + +assign de0_lcd_data = 8'hzz; +assign de0_lcd_blig = 1'b0; +assign de0_lcd_rw = 1'b0; +assign de0_lcd_en = 1'b0; +assign de0_lcd_rs = 1'b0; + +assign de0_sd_clk = 1'h0; +assign de0_sd_mosi = 1'hz; +assign de0_sd_miso = 1'hz; +assign de0_sd_cmd = 1'hz; + +assign de0_ps2_kbdat = 1'hz; +assign de0_ps2_kbclk = 1'hz; +assign de0_ps2_msdat = 1'hz; +assign de0_ps2_msclk = 1'hz; + +assign de0_vga_hs = 1'b0; +assign de0_vga_vs = 1'b0; +assign de0_vga_r = 4'h0; +assign de0_vga_g = 4'h0; +assign de0_vga_b = 4'h0; + +assign de0_gpio0_clkout = 2'b00; +assign de0_gpio1_clkout = 2'b00; +assign de0_gpio0_d = 32'hzzzzzzzz; +assign de0_gpio1_d = 32'hzzzzzzzz; + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/org/rtl/de0/de0_uart.v b/1801BM1_vm80a/org/rtl/de0/de0_uart.v new file mode 100644 index 0000000000000000000000000000000000000000..3dc00014e21439a6ad9a4c1bf00e624cee436fc9 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de0/de0_uart.v @@ -0,0 +1,378 @@ +// +// Copyright (c) 2014-2015 by 1801BM1@gmail.com +// +// Universal Serial Asynchronous Receiver-Transmitter (simplified 8251) +//______________________________________________________________________________ +// +module uart_wb #(parameter REFCLK=50000000) +( + input wb_clk_i, // system clock + input wb_rst_i, // peripheral reset + // + input [0:0] wb_adr_i, // + input [7:0] wb_dat_i, // + output reg [7:0] wb_dat_o, // + input wb_cyc_i, // + input wb_we_i, // + input wb_stb_i, // + output reg wb_ack_o, // + // + output tx_dat_o, // output serial data (txd) + input tx_cts_i, // enable transmitter (rts) + input rx_dat_i, // input serial data (rxd) + output rx_dtr_o, // receiver ready (cts) + // + output tx_ready_o, // tx ready request + output tx_empty_o, // tx empty request + output rx_ready_o, // rx ready request + // + input [15:0] cfg_bdiv, // baudrate divisor: (921600/baud)-1 + input [1:0] cfg_nbit, // word length: 00-5, 01-6, 10-7, 11-8 bit + input cfg_nstp, // tx stop bits: 0 - 1 stop, 1 - 2 stop + input cfg_pena, // parity control enable + input cfg_podd // odd parity (complete to odd ones) +); + +wire [63:0] add_arg; +reg [16:0] add_reg; +reg [15:0] baud_div; +reg baud_x16; +wire baud_ref; + +reg [1:0] tx_cts_reg; +reg [1:0] rx_dat_reg; + +wire csr_wstb; +wire rbr_rstb; +wire thr_wstb; + +wire tx_par; +reg [7:0] tx_thr; +reg [9:0] tx_shr; +reg [7:0] tx_bcnt; +reg tx_busy; +reg tx_ready, tx_empty, tx_break; + +wire rx_dat; +reg [7:0] rx_rbr; +reg [8:0] rx_shr; +reg [7:0] rx_bcnt; +reg rx_ready, rx_perr, rx_ovf, rx_break; +wire rx_load, rx_stb; +reg rx_frame, rx_start, rx_par; + +//______________________________________________________________________________ +// +// Caution note: the arithmetic expressions should be calculated in 64-bit width +// +assign add_arg = (64'h0000000000100000 * 64'd921600)/REFCLK; +assign baud_ref = add_reg[16]; +// +// Phase accumulator to generate 921600 * 16 Hz reference clock strobe +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + add_reg <= 17'h00000; + else + begin + add_reg <= {1'b0, add_reg[15:0]} + add_arg[16:0]; + end +end +// +// Baud rate x16 generator +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + baud_div <= 16'h0000; + baud_x16 <= 1'b0; + end + else + begin + if (baud_ref) + if (baud_div == 16'h0000) + baud_div <= cfg_bdiv; + else + baud_div <= baud_div - 16'h0001; + + baud_x16 <= baud_ref & (baud_div == 16'h0000); + end + +end + +//______________________________________________________________________________ +// +assign csr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & wb_adr_i[0]; +assign thr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & ~wb_adr_i[0]; +assign rbr_rstb = wb_cyc_i & wb_stb_i & ~wb_we_i & ~wb_ack_o & ~wb_adr_i[0]; +// +// Output data multiplexed register +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + wb_dat_o <= 8'h00; + else +// +// if (wb_cyc_i & wb_stb_i & ~wb_ack_o) +// + begin + if (wb_adr_i[0]) + wb_dat_o <= (tx_ready << 7) + | (tx_break << 6) + | (tx_empty << 5) + | (rx_ready << 3) + | (rx_break << 2) + | (rx_perr << 1) + | (rx_ovf << 0); + else + wb_dat_o <= rx_rbr; + end +end + +always @(posedge wb_clk_i) + wb_ack_o <= wb_cyc_i & wb_stb_i & ~wb_ack_o; + +// +// Control register bits +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + tx_break <= 1'b0; + else + if (csr_wstb) tx_break <= wb_dat_i[6]; +end + +//______________________________________________________________________________ +// +// Interrupts +// +assign tx_ready_o = tx_ready; +assign tx_empty_o = tx_empty; +assign rx_ready_o = rx_ready; + +//______________________________________________________________________________ +// +// Metastability issues +// +always @(posedge wb_clk_i) +begin + tx_cts_reg[0] <= ~tx_cts_i; + tx_cts_reg[1] <= tx_cts_reg[0]; + + rx_dat_reg[0] <= rx_dat_i; + rx_dat_reg[1] <= rx_dat_reg[0]; +end + +//______________________________________________________________________________ +// +// Transmitter unit +// +assign tx_par = tx_thr[0] ^ tx_thr[1] ^ tx_thr[2] ^ tx_thr[3] ^ tx_thr[4] + ^ (tx_thr[5] & (cfg_nbit >= 2'b01)) + ^ (tx_thr[6] & (cfg_nbit >= 2'b10)) + ^ (tx_thr[7] & (cfg_nbit == 2'b11)) + ^ cfg_podd; +assign tx_dat_o = tx_shr[0] & ~tx_break; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + tx_ready <= 1'b1; + tx_empty <= 1'b1; + tx_shr <= 10'o1777; + tx_busy <= 1'b0; + tx_bcnt <= 8'b00000000; + tx_thr <= 8'b00000000; + end + else + begin + tx_empty <= tx_ready & ~tx_busy; + // + // Transmitter hold register write + // + if (thr_wstb) + begin + tx_ready <= 1'b0; + tx_thr <= wb_dat_i[7:0]; + end + + if (baud_x16) + begin + // + // Transmit process + // + if (tx_busy) + begin + if (tx_bcnt == 8'b00000001) + tx_busy <= 1'b0; + + if (tx_bcnt != 8'b00000000) + tx_bcnt <= tx_bcnt - 8'b00000001; + + if (tx_bcnt[3:0] == 4'b0000) + tx_shr <= {1'b1, tx_shr[9:1]}; + end + + // + // Starting new word transmit + // + if (~tx_ready & ~tx_busy & tx_cts_reg[1]) + begin + tx_busy <= 1'b1; + tx_ready <= ~thr_wstb; + tx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena} + {3'b000, cfg_nstp}, 4'b1111}; + + if (cfg_pena) + case(cfg_nbit) + 2'b00: tx_shr <= {3'b111, tx_par, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {2'b11, tx_par, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {1'b1, tx_par, tx_thr[6:0], 1'b0}; + default: tx_shr <= { tx_par, tx_thr[7:0], 1'b0}; + endcase + else + case(cfg_nbit) + 2'b00: tx_shr <= {4'b1111, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {3'b111, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {2'b11, tx_thr[6:0], 1'b0}; + default: tx_shr <= {1'b1, tx_thr[7:0], 1'b0}; + endcase + end + end + end +end + +//______________________________________________________________________________ +// +// Receiver unit +// +assign rx_dtr_o = rx_ready; +assign rx_dat = rx_dat_reg[1]; + +assign rx_load = rx_stb & (rx_bcnt[7:4] == 4'b0000); +assign rx_stb = (rx_bcnt[3:0] == 4'b0001) & baud_x16; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + rx_ready <= 1'b0; + rx_break <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + rx_frame <= 1'b0; + rx_start <= 1'b0; + rx_par <= 1'b0; + rx_rbr <= 8'b00000000; + rx_shr <= 9'b00000000; + rx_bcnt <= 8'b00000000; + end + else + begin + if (rx_load) + begin + rx_ready <= 1'b1; + case(cfg_nbit) + 2'b00: rx_rbr <= {3'b000, rx_shr[4:0]}; + 2'b01: rx_rbr <= {2'b00, rx_shr[5:0]}; + 2'b10: rx_rbr <= {1'b0, rx_shr[6:0]}; + default: rx_rbr <= rx_shr[7:0]; + endcase + rx_perr <= rx_par; + rx_ovf <= rx_ready; + rx_break <= ~rx_dat; + end + else + if (rbr_rstb) + begin + rx_ready <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + end + + if (baud_x16) + begin + if (~rx_frame) + // + // Waiting for start bit + // + if (~rx_dat) + begin + rx_par <= cfg_pena & cfg_podd; + rx_start <= 1'b1; + rx_frame <= 1'b1; + rx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena}, 4'b0111}; + end + else + begin + rx_start <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + begin + // + // Receiving frame + // + if (rx_bcnt != 8'b00000000) + rx_bcnt <= rx_bcnt - 8'b00000001; + // + // Start bit monitoring + // + if (rx_start) + begin + if (rx_dat) + begin + // + // Spurrious start bit + // + rx_start <= 1'b0; + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + if (rx_bcnt[3:0] == 4'b0010) + rx_start <= 1'b0; + end + else + begin + // + // Receiving data + // + if (rx_stb) + begin + rx_par <= (rx_par ^ rx_dat) & cfg_pena; + if (cfg_pena) + case(cfg_nbit) + 2'b00: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b01: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + 2'b10: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + default: rx_shr <= {rx_dat, rx_shr[8:1]}; + endcase + else + case(cfg_nbit) + 2'b00: rx_shr <= {4'b0000, rx_dat, rx_shr[4:1]}; + 2'b01: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b10: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + default: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + endcase + if (rx_load & rx_dat) + begin + // + // Stop bit detected + // + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + end + if ((rx_bcnt == 8'b00000000) & rx_dat) + rx_frame <= 1'b0; + end + end + end + end +end +endmodule diff --git a/1801BM1_vm80a/org/rtl/de1/de1_mem.v b/1801BM1_vm80a/org/rtl/de1/de1_mem.v new file mode 100644 index 0000000000000000000000000000000000000000..e10dd5c8b56cb662f72edd65bce81ee40f5a1021 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de1/de1_mem.v @@ -0,0 +1,103 @@ +// megafunction wizard: %RAM: 1-PORT% +// GENERATION: STANDARD +// VERSION: WM1.0 +// MODULE: altsyncram + +// ============================================================ +// File Name: de1_mem.v +// Megafunction Name(s): +// altsyncram +// +// Simulation Library Files(s): +// altera_mf +// ============================================================ +// ************************************************************ +// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! +// +// 12.1 Build 243 01/31/2013 SP 1 SJ Full Version +// ************************************************************ + + +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. + + +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module memini ( + address, + clock, + data, + wren, + q); + + input [13:0] address; + input clock; + input [7:0] data; + input wren; + output [7:0] q; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_off +`endif + tri1 clock; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_on +`endif + + wire [7:0] sub_wire0; + wire [7:0] q = sub_wire0[7:0]; + + altsyncram altsyncram_component ( + .address_a (address), + .clock0 (clock), + .data_a (data), + .wren_a (wren), + .q_a (sub_wire0), + .aclr0 (1'b0), + .aclr1 (1'b0), + .address_b (1'b1), + .addressstall_a (1'b0), + .addressstall_b (1'b0), + .byteena_a (1'b1), + .byteena_b (1'b1), + .clock1 (1'b1), + .clocken0 (1'b1), + .clocken1 (1'b1), + .clocken2 (1'b1), + .clocken3 (1'b1), + .data_b (1'b1), + .eccstatus (), + .q_b (), + .rden_a (1'b1), + .rden_b (1'b1), + .wren_b (1'b0)); + defparam + altsyncram_component.clock_enable_input_a = "BYPASS", + altsyncram_component.clock_enable_output_a = "BYPASS", + altsyncram_component.init_file = "../../../tst/rom/memini.mif", + altsyncram_component.intended_device_family = "Cyclone II", + altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO", + altsyncram_component.lpm_type = "altsyncram", + altsyncram_component.numwords_a = 16384, + altsyncram_component.operation_mode = "SINGLE_PORT", + altsyncram_component.outdata_aclr_a = "NONE", + altsyncram_component.outdata_reg_a = "UNREGISTERED", + altsyncram_component.power_up_uninitialized = "FALSE", + altsyncram_component.ram_block_type = "M4K", + altsyncram_component.widthad_a = 14, + altsyncram_component.width_a = 8, + altsyncram_component.width_byteena_a = 1; + +endmodule diff --git a/1801BM1_vm80a/org/rtl/de1/de1_top.v b/1801BM1_vm80a/org/rtl/de1/de1_top.v new file mode 100644 index 0000000000000000000000000000000000000000..ae6ee6570f9ffb918f43067802ed1c0e9cc9f4e1 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de1/de1_top.v @@ -0,0 +1,312 @@ +//______________________________________________________________________________ +// +// Top module for DE1 board based system +// +//______________________________________________________________________________ +// +// External oscillator clock, feeds the PLLs +// +`define OSC_CLOCK 50000000 +// +// Global system clock +// +`define SYS_CLOCK 50000000 + +//______________________________________________________________________________ +// +// Reset button debounce interval (in ms)) +// +`define RESET_BUTTON_DEBOUNCE_MS 5 +// +// Internal reset pulse width (in system clocks) +// +`define RESET_PULSE_WIDTH_CLK 7 +// +// Console baudrate +// +`define SYS_BAUD 115200 + +//______________________________________________________________________________ +// +// Top project module - instantiates the DE1 board itself +// +module de1 +( + input [1:0] de1_clock_24, // clock input 24 MHz + input [1:0] de1_clock_27, // clock input 27 MHz + input de1_clock_50, // clock input 50 MHz + input de1_clock_ext, // external clock input + // + input [3:0] de1_button, // push button[3:0] + // + input [9:0] de1_sw, // DPDT toggle switch[9:0] + output [6:0] de1_hex0, // seven segment digit 0 + output [6:0] de1_hex1, // seven segment digit 1 + output [6:0] de1_hex2, // seven segment digit 2 + output [6:0] de1_hex3, // seven segment digit 3 + output [7:0] de1_ledg, // LED green[7:0] + output [9:0] de1_ledr, // LED red[9:0] + // + output de1_uart_txd, // UART transmitter + input de1_uart_rxd, // UART receiver + // + inout [15:0] de1_dram_dq, // SDRAM data bus 16 bits + output [11:0] de1_dram_addr, // SDRAM address bus 12 bits + output de1_dram_ldqm, // SDRAM low-byte data mask + output de1_dram_udqm, // SDRAM high-byte data mask + output de1_dram_we_n, // SDRAM write enable + output de1_dram_cas_n, // SDRAM column address strobe + output de1_dram_ras_n, // SDRAM row address strobe + output de1_dram_cs_n, // SDRAM chip select + output [1:0] de1_dram_ba, // SDRAM bank address + output de1_dram_clk, // SDRAM clock + output de1_dram_cke, // SDRAM clock enable + // + inout [7:0] de1_fl_dq, // FLASH data bus 8 Bits + output [21:0] de1_fl_addr, // FLASH address bus 22 Bits + output de1_fl_we_n, // FLASH write enable + output de1_fl_rst_n, // FLASH reset + output de1_fl_oe_n, // FLASH output enable + output de1_fl_ce_n, // FLASH chip enable + // + inout [15:0] de1_sram_dq, // SRAM Data bus 16 Bits + output [17:0] de1_sram_addr, // SRAM Address bus 18 Bits + output de1_sram_ub_n, // SRAM High-byte Data Mask + output de1_sram_lb_n, // SRAM Low-byte Data Mask + output de1_sram_we_n, // SRAM Write Enable + output de1_sram_ce_n, // SRAM Chip Enable + output de1_sram_oe_n, // SRAM Output Enable + // + inout de1_sd_mosi, // SD Card Data Output + inout de1_sd_miso, // SD Card Data Input + inout de1_sd_cmd, // SD Card Command Signal + output de1_sd_clk, // SD Card Clock + // + input de1_tdi, // CPLD -> FPGA (data in) + input de1_tck, // CPLD -> FPGA (clk) + input de1_tms, // CPLD -> FPGA (mode select) + output de1_tdo, // FPGA -> CPLD (data out) + // + inout de1_i2c_dat, // I2C Data + output de1_i2c_clk, // I2C Clock + inout de1_ps2_dat, // PS2 Data + inout de1_ps2_clk, // PS2 Clock + // + output de1_vga_hs, // VGA H_SYNC + output de1_vga_vs, // VGA V_SYNC + output [3:0] de1_vga_r, // VGA Red[3:0] + output [3:0] de1_vga_g, // VGA Green[3:0] + output [3:0] de1_vga_b, // VGA Blue[3:0] + // + output de1_aud_adclrck, // Audio CODEC ADC LR Clock + input de1_aud_adcdat, // Audio CODEC ADC Data + output de1_aud_daclrck, // Audio CODEC DAC LR Clock + output de1_aud_dacdat, // Audio CODEC DAC Data + inout de1_aud_bclk, // Audio CODEC Bit-Stream Clock + output de1_aud_xck, // Audio CODEC Chip Clock + // + inout [35:0] de1_gpio0, // GPIO Connection 0 + inout [35:0] de1_gpio1 // GPIO Connection 1 +); + +//______________________________________________________________________________ +// +// Top module for DE1 board based system +// +wire [31:0] baud = 921600/`SYS_BAUD-1; +wire clk, wr_n, rst_n, dbin; +wire [7:0] dcpu; +wire [7:0] dsys; +wire [7:0] dsio; +wire [7:0] dram; +wire [15:0] a; +wire uack; + +reg f1, f2; +reg [6:0] hex0, hex1, hex2, hex3; +reg [7:0] led; +reg [7:0] rcnt = 8'h00; +reg [2:0] div; +reg [15:0] div1ms; +reg ms, intrq, inta; +wire inte, sync; + +assign clk = de1_clock_50; +assign rst_n = (rcnt == 8'hFF); +assign dsys = inta ? 8'hE7 + : (a[15:8] == 8'hFF) ? {4'h0, de1_button[3:0]} + : (a[15:8] == 8'hFE) ? dsio + : dram; + +always @(posedge clk) +begin + div <= div + 3'b001; + f1 <= div[0]; + f2 <= ~div[0]; + + if (sync) inta = dcpu[0]; + if (div1ms == ((`SYS_CLOCK/1000)-1)) + begin + div1ms <= 16'h0000; + ms <= 1; + end + else + begin + div1ms <= div1ms + 16'h0001; + ms <= 0; + end + + if (ms) intrq <= 1; + if (inta) intrq <= 0; +end + +always @(posedge clk) +begin + if (~de1_button[3]) + rcnt <= 8'h00; + else + if (rcnt != 8'hFF) rcnt <= rcnt + 8'h01; +end + +memini ram +( + .address(a[13:0]), + .clock(clk), + .data(dcpu), + .wren(~wr_n & rst_n & ~a[15] & ~a[14]), + .q(dram) +); + +always @(posedge clk) +begin + if (~wr_n) + begin + if (a == 16'hFFFB) led <= dcpu; + if (a == 16'hFFFC) hex0 <= dcpu[6:0]; + if (a == 16'hFFFD) hex1 <= dcpu[6:0]; + if (a == 16'hFFFE) hex2 <= dcpu[6:0]; + if (a == 16'hFFFF) hex3 <= dcpu[6:0]; + end +end + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam uart.REFCLK = `SYS_CLOCK; +`endif + +uart_wb uart +( + .wb_clk_i(clk), + .wb_rst_i(~rst_n), + .wb_adr_i(a[0]), + .wb_dat_i(dcpu), + .wb_dat_o(dsio), + .wb_cyc_i((~wr_n | dbin) & (a[15:8] == 8'hFE)), + .wb_we_i(~wr_n & (a[15:8] == 8'hFE)), + .wb_stb_i((~wr_n | (dbin & ~uack)) & (a[15:8] == 8'hFE)), + .wb_ack_o(uack), + + .tx_dat_o(de1_uart_txd), + .tx_cts_i(1'b0), + .rx_dat_i(de1_uart_rxd), +// .rx_dtr_o(de1_uart_cts), + +// .tx_ready(), +// .tx_empty(), +// .rx_ready(), + + .cfg_bdiv(baud[15:0]), + .cfg_nbit(2'b11), + .cfg_nstp(1'b1), + .cfg_pena(1'b0), + .cfg_podd(1'b0) +); + +vm80a_core cpu +( + .pin_clk(clk), + .pin_f1(f1), + .pin_f2(f2), + .pin_reset(~rst_n), + .pin_a(a), + .pin_dout(dcpu), + .pin_din(dsys), + .pin_hold(1'b0), + .pin_ready(1'b1), + .pin_int(intrq), + .pin_wr_n(wr_n), + .pin_dbin(dbin), + .pin_inte(inte), + .pin_sync(sync) +); + +assign de1_hex0 = ~hex0; +assign de1_hex1 = ~hex1; +assign de1_hex2 = ~hex2; +assign de1_hex3 = ~hex3; + +assign de1_ledr[7:0] = led; +assign de1_ledr[9] = ~wr_n; +assign de1_ledr[8] = sync; + +//______________________________________________________________________________ +// +// Temporary and debug assignments +// +assign de1_dram_dq = 16'hzzzz; +assign de1_dram_addr = 12'h000; +assign de1_dram_ldqm = 1'b0; +assign de1_dram_udqm = 1'b0; +assign de1_dram_we_n = 1'b1; +assign de1_dram_cas_n = 1'b1; +assign de1_dram_ras_n = 1'b1; +assign de1_dram_cs_n = 1'b1; +assign de1_dram_ba[0] = 1'b0; +assign de1_dram_ba[1] = 1'b0; +assign de1_dram_clk = 1'b0; +assign de1_dram_cke = 1'b0; + +assign de1_fl_dq = 7'hzz; +assign de1_fl_addr = 22'hzzzzzz; +assign de1_fl_we_n = 1'b1; +assign de1_fl_rst_n = 1'b0; +assign de1_fl_oe_n = 1'b1; +assign de1_fl_ce_n = 1'b1; + +assign de1_sram_dq = 16'hzzzz; +assign de1_sram_addr = 18'h00000; +assign de1_sram_we_n = 1'b1; +assign de1_sram_ce_n = 1'b1; +assign de1_sram_oe_n = 1'b1; +assign de1_sram_lb_n = 1'b1; +assign de1_sram_ub_n = 1'b1; + +assign de1_sd_clk = 1'b0; +assign de1_sd_mosi = 1'hz; +assign de1_sd_miso = 1'hz; +assign de1_sd_cmd = 1'hz; + +assign de1_ps2_dat = 1'hz; +assign de1_ps2_clk = 1'hz; +assign de1_i2c_dat = 1'hz; +assign de1_i2c_clk = 1'hz; + +assign de1_vga_hs = 1'b0; +assign de1_vga_vs = 1'b0; +assign de1_vga_r = 4'h0; +assign de1_vga_g = 4'h0; +assign de1_vga_b = 4'h0; + +assign de1_gpio0 = 35'hzzzzzzzzz; +assign de1_gpio1 = 35'hzzzzzzzzz; +assign de1_ledg = 8'hzz; + +assign de1_aud_adclrck = 1'b0; +assign de1_aud_daclrck = 1'b0; +assign de1_aud_dacdat = 1'b0; +assign de1_aud_xck = 1'b0; + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/org/rtl/de1/de1_uart.v b/1801BM1_vm80a/org/rtl/de1/de1_uart.v new file mode 100644 index 0000000000000000000000000000000000000000..3dc00014e21439a6ad9a4c1bf00e624cee436fc9 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de1/de1_uart.v @@ -0,0 +1,378 @@ +// +// Copyright (c) 2014-2015 by 1801BM1@gmail.com +// +// Universal Serial Asynchronous Receiver-Transmitter (simplified 8251) +//______________________________________________________________________________ +// +module uart_wb #(parameter REFCLK=50000000) +( + input wb_clk_i, // system clock + input wb_rst_i, // peripheral reset + // + input [0:0] wb_adr_i, // + input [7:0] wb_dat_i, // + output reg [7:0] wb_dat_o, // + input wb_cyc_i, // + input wb_we_i, // + input wb_stb_i, // + output reg wb_ack_o, // + // + output tx_dat_o, // output serial data (txd) + input tx_cts_i, // enable transmitter (rts) + input rx_dat_i, // input serial data (rxd) + output rx_dtr_o, // receiver ready (cts) + // + output tx_ready_o, // tx ready request + output tx_empty_o, // tx empty request + output rx_ready_o, // rx ready request + // + input [15:0] cfg_bdiv, // baudrate divisor: (921600/baud)-1 + input [1:0] cfg_nbit, // word length: 00-5, 01-6, 10-7, 11-8 bit + input cfg_nstp, // tx stop bits: 0 - 1 stop, 1 - 2 stop + input cfg_pena, // parity control enable + input cfg_podd // odd parity (complete to odd ones) +); + +wire [63:0] add_arg; +reg [16:0] add_reg; +reg [15:0] baud_div; +reg baud_x16; +wire baud_ref; + +reg [1:0] tx_cts_reg; +reg [1:0] rx_dat_reg; + +wire csr_wstb; +wire rbr_rstb; +wire thr_wstb; + +wire tx_par; +reg [7:0] tx_thr; +reg [9:0] tx_shr; +reg [7:0] tx_bcnt; +reg tx_busy; +reg tx_ready, tx_empty, tx_break; + +wire rx_dat; +reg [7:0] rx_rbr; +reg [8:0] rx_shr; +reg [7:0] rx_bcnt; +reg rx_ready, rx_perr, rx_ovf, rx_break; +wire rx_load, rx_stb; +reg rx_frame, rx_start, rx_par; + +//______________________________________________________________________________ +// +// Caution note: the arithmetic expressions should be calculated in 64-bit width +// +assign add_arg = (64'h0000000000100000 * 64'd921600)/REFCLK; +assign baud_ref = add_reg[16]; +// +// Phase accumulator to generate 921600 * 16 Hz reference clock strobe +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + add_reg <= 17'h00000; + else + begin + add_reg <= {1'b0, add_reg[15:0]} + add_arg[16:0]; + end +end +// +// Baud rate x16 generator +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + baud_div <= 16'h0000; + baud_x16 <= 1'b0; + end + else + begin + if (baud_ref) + if (baud_div == 16'h0000) + baud_div <= cfg_bdiv; + else + baud_div <= baud_div - 16'h0001; + + baud_x16 <= baud_ref & (baud_div == 16'h0000); + end + +end + +//______________________________________________________________________________ +// +assign csr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & wb_adr_i[0]; +assign thr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & ~wb_adr_i[0]; +assign rbr_rstb = wb_cyc_i & wb_stb_i & ~wb_we_i & ~wb_ack_o & ~wb_adr_i[0]; +// +// Output data multiplexed register +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + wb_dat_o <= 8'h00; + else +// +// if (wb_cyc_i & wb_stb_i & ~wb_ack_o) +// + begin + if (wb_adr_i[0]) + wb_dat_o <= (tx_ready << 7) + | (tx_break << 6) + | (tx_empty << 5) + | (rx_ready << 3) + | (rx_break << 2) + | (rx_perr << 1) + | (rx_ovf << 0); + else + wb_dat_o <= rx_rbr; + end +end + +always @(posedge wb_clk_i) + wb_ack_o <= wb_cyc_i & wb_stb_i & ~wb_ack_o; + +// +// Control register bits +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + tx_break <= 1'b0; + else + if (csr_wstb) tx_break <= wb_dat_i[6]; +end + +//______________________________________________________________________________ +// +// Interrupts +// +assign tx_ready_o = tx_ready; +assign tx_empty_o = tx_empty; +assign rx_ready_o = rx_ready; + +//______________________________________________________________________________ +// +// Metastability issues +// +always @(posedge wb_clk_i) +begin + tx_cts_reg[0] <= ~tx_cts_i; + tx_cts_reg[1] <= tx_cts_reg[0]; + + rx_dat_reg[0] <= rx_dat_i; + rx_dat_reg[1] <= rx_dat_reg[0]; +end + +//______________________________________________________________________________ +// +// Transmitter unit +// +assign tx_par = tx_thr[0] ^ tx_thr[1] ^ tx_thr[2] ^ tx_thr[3] ^ tx_thr[4] + ^ (tx_thr[5] & (cfg_nbit >= 2'b01)) + ^ (tx_thr[6] & (cfg_nbit >= 2'b10)) + ^ (tx_thr[7] & (cfg_nbit == 2'b11)) + ^ cfg_podd; +assign tx_dat_o = tx_shr[0] & ~tx_break; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + tx_ready <= 1'b1; + tx_empty <= 1'b1; + tx_shr <= 10'o1777; + tx_busy <= 1'b0; + tx_bcnt <= 8'b00000000; + tx_thr <= 8'b00000000; + end + else + begin + tx_empty <= tx_ready & ~tx_busy; + // + // Transmitter hold register write + // + if (thr_wstb) + begin + tx_ready <= 1'b0; + tx_thr <= wb_dat_i[7:0]; + end + + if (baud_x16) + begin + // + // Transmit process + // + if (tx_busy) + begin + if (tx_bcnt == 8'b00000001) + tx_busy <= 1'b0; + + if (tx_bcnt != 8'b00000000) + tx_bcnt <= tx_bcnt - 8'b00000001; + + if (tx_bcnt[3:0] == 4'b0000) + tx_shr <= {1'b1, tx_shr[9:1]}; + end + + // + // Starting new word transmit + // + if (~tx_ready & ~tx_busy & tx_cts_reg[1]) + begin + tx_busy <= 1'b1; + tx_ready <= ~thr_wstb; + tx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena} + {3'b000, cfg_nstp}, 4'b1111}; + + if (cfg_pena) + case(cfg_nbit) + 2'b00: tx_shr <= {3'b111, tx_par, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {2'b11, tx_par, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {1'b1, tx_par, tx_thr[6:0], 1'b0}; + default: tx_shr <= { tx_par, tx_thr[7:0], 1'b0}; + endcase + else + case(cfg_nbit) + 2'b00: tx_shr <= {4'b1111, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {3'b111, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {2'b11, tx_thr[6:0], 1'b0}; + default: tx_shr <= {1'b1, tx_thr[7:0], 1'b0}; + endcase + end + end + end +end + +//______________________________________________________________________________ +// +// Receiver unit +// +assign rx_dtr_o = rx_ready; +assign rx_dat = rx_dat_reg[1]; + +assign rx_load = rx_stb & (rx_bcnt[7:4] == 4'b0000); +assign rx_stb = (rx_bcnt[3:0] == 4'b0001) & baud_x16; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + rx_ready <= 1'b0; + rx_break <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + rx_frame <= 1'b0; + rx_start <= 1'b0; + rx_par <= 1'b0; + rx_rbr <= 8'b00000000; + rx_shr <= 9'b00000000; + rx_bcnt <= 8'b00000000; + end + else + begin + if (rx_load) + begin + rx_ready <= 1'b1; + case(cfg_nbit) + 2'b00: rx_rbr <= {3'b000, rx_shr[4:0]}; + 2'b01: rx_rbr <= {2'b00, rx_shr[5:0]}; + 2'b10: rx_rbr <= {1'b0, rx_shr[6:0]}; + default: rx_rbr <= rx_shr[7:0]; + endcase + rx_perr <= rx_par; + rx_ovf <= rx_ready; + rx_break <= ~rx_dat; + end + else + if (rbr_rstb) + begin + rx_ready <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + end + + if (baud_x16) + begin + if (~rx_frame) + // + // Waiting for start bit + // + if (~rx_dat) + begin + rx_par <= cfg_pena & cfg_podd; + rx_start <= 1'b1; + rx_frame <= 1'b1; + rx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena}, 4'b0111}; + end + else + begin + rx_start <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + begin + // + // Receiving frame + // + if (rx_bcnt != 8'b00000000) + rx_bcnt <= rx_bcnt - 8'b00000001; + // + // Start bit monitoring + // + if (rx_start) + begin + if (rx_dat) + begin + // + // Spurrious start bit + // + rx_start <= 1'b0; + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + if (rx_bcnt[3:0] == 4'b0010) + rx_start <= 1'b0; + end + else + begin + // + // Receiving data + // + if (rx_stb) + begin + rx_par <= (rx_par ^ rx_dat) & cfg_pena; + if (cfg_pena) + case(cfg_nbit) + 2'b00: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b01: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + 2'b10: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + default: rx_shr <= {rx_dat, rx_shr[8:1]}; + endcase + else + case(cfg_nbit) + 2'b00: rx_shr <= {4'b0000, rx_dat, rx_shr[4:1]}; + 2'b01: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b10: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + default: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + endcase + if (rx_load & rx_dat) + begin + // + // Stop bit detected + // + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + end + if ((rx_bcnt == 8'b00000000) & rx_dat) + rx_frame <= 1'b0; + end + end + end + end +end +endmodule diff --git a/1801BM1_vm80a/org/rtl/de2-115/de2_mem.v b/1801BM1_vm80a/org/rtl/de2-115/de2_mem.v new file mode 100644 index 0000000000000000000000000000000000000000..9fc555072762b0780158c6e46c5834f48e380239 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de2-115/de2_mem.v @@ -0,0 +1,104 @@ +// megafunction wizard: %RAM: 1-PORT% +// GENERATION: STANDARD +// VERSION: WM1.0 +// MODULE: altsyncram + +// ============================================================ +// File Name: de0_mem.v +// Megafunction Name(s): +// altsyncram +// +// Simulation Library Files(s): +// altera_mf +// ============================================================ +// ************************************************************ +// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! +// +// 12.1 Build 177 11/07/2012 SJ Full Version +// ************************************************************ + + +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. + + +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module memini ( + address, + clock, + data, + wren, + q); + + input [13:0] address; + input clock; + input [7:0] data; + input wren; + output [7:0] q; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_off +`endif + tri1 clock; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_on +`endif + + wire [7:0] sub_wire0; + wire [7:0] q = sub_wire0[7:0]; + + altsyncram altsyncram_component ( + .address_a (address), + .clock0 (clock), + .data_a (data), + .wren_a (wren), + .q_a (sub_wire0), + .aclr0 (1'b0), + .aclr1 (1'b0), + .address_b (1'b1), + .addressstall_a (1'b0), + .addressstall_b (1'b0), + .byteena_a (1'b1), + .byteena_b (1'b1), + .clock1 (1'b1), + .clocken0 (1'b1), + .clocken1 (1'b1), + .clocken2 (1'b1), + .clocken3 (1'b1), + .data_b (1'b1), + .eccstatus (), + .q_b (), + .rden_a (1'b1), + .rden_b (1'b1), + .wren_b (1'b0)); + defparam + altsyncram_component.clock_enable_input_a = "BYPASS", + altsyncram_component.clock_enable_output_a = "BYPASS", + altsyncram_component.init_file = "../../../tst/rom/memini.mif", + altsyncram_component.intended_device_family = "Cyclone IV", + altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO", + altsyncram_component.lpm_type = "altsyncram", + altsyncram_component.numwords_a = 16384, + altsyncram_component.operation_mode = "SINGLE_PORT", + altsyncram_component.outdata_aclr_a = "NONE", + altsyncram_component.outdata_reg_a = "UNREGISTERED", + altsyncram_component.power_up_uninitialized = "FALSE", + altsyncram_component.ram_block_type = "M9K", + altsyncram_component.read_during_write_mode_port_a = "DONT_CARE", + altsyncram_component.widthad_a = 14, + altsyncram_component.width_a = 8, + altsyncram_component.width_byteena_a = 1; + +endmodule diff --git a/1801BM1_vm80a/org/rtl/de2-115/de2_top.v b/1801BM1_vm80a/org/rtl/de2-115/de2_top.v new file mode 100644 index 0000000000000000000000000000000000000000..899248aa7cbe47f137136bba51cd4b61e5ddfd2f --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de2-115/de2_top.v @@ -0,0 +1,450 @@ +//______________________________________________________________________________ +// +// Top module for DE2-115 board based system +//______________________________________________________________________________ +// +// External oscillator clock, feeds the PLLs +// +`define OSC_CLOCK 50000000 +// +// Global system clock +// +`define SYS_CLOCK 50000000 +// +// Console baudrate +// +`define SYS_BAUD 115200 +//______________________________________________________________________________ +// +// Reset button debounce interval (in ms)) +// +`define RESET_BUTTON_DEBOUNCE_MS 5 +// +// Internal reset pulse width (in system clocks) +// +`define RESET_PULSE_WIDTH_CLK 7 + +//______________________________________________________________________________ +// +// Top project module - instantiates the DE2-115 board itself +// +module de2 +( + input de2_clock_50, // clock input 50 MHz + input de2_clock_50_2, // clock input 50 MHz + input de2_clock_50_3, // clock input 50 MHz + input de2_clock_25, // Ethernet clock 25MHz + input de2_sma_clkin, // SMA socket clock input + output de2_sma_clkout, // SMA socket clock output + // + input [3:0] de2_button, // push buttons + input [17:0] de2_sw, // DPDT toggle switches + // + output [6:0] de2_hex0, // seven segment digit 0 + output [6:0] de2_hex1, // seven segment digit 1 + output [6:0] de2_hex2, // seven segment digit 2 + output [6:0] de2_hex3, // seven segment digit 3 + output [6:0] de2_hex4, // seven segment digit 4 + output [6:0] de2_hex5, // seven segment digit 5 + output [6:0] de2_hex6, // seven segment digit 6 + output [6:0] de2_hex7, // seven segment digit 7 + output [8:0] de2_ledg, // LEDs green + output [17:0] de2_ledr, // LEDs red + // + output de2_uart_txd, // UART transmitter + input de2_uart_rxd, // UART receiver + output de2_uart_cts, // UART clear to send + input de2_uart_rts, // UART request to send + // + inout [31:0] de2_dram_dq, // SDRAM data bus 32 bits + output [12:0] de2_dram_addr, // SDRAM address bus 13 bits + output [3:0] de2_dram_dqm, // SDRAM byte data lane mask + output de2_dram_we_n, // SDRAM write enable + output de2_dram_cas_n, // SDRAM column address strobe + output de2_dram_ras_n, // SDRAM row address strobe + output de2_dram_cs_n, // SDRAM chip select + output [1:0] de2_dram_ba, // SDRAM bank address + output de2_dram_clk, // SDRAM clock + output de2_dram_cke, // SDRAM clock enable + // + inout [15:0] de2_sram_dq, // SRAM Data bus 16 Bits + output [19:0] de2_sram_addr, // SRAM Address bus 20 Bits + output de2_sram_ub_n, // SRAM High-byte Data Mask + output de2_sram_lb_n, // SRAM Low-byte Data Mask + output de2_sram_we_n, // SRAM Write Enable + output de2_sram_ce_n, // SRAM Chip Enable + output de2_sram_oe_n, // SRAM Output Enable + // + inout [7:0] de2_fl_dq, // FLASH data bus 8 Bits + output [22:0] de2_fl_addr, // FLASH address bus 23 Bits + output de2_fl_we_n, // FLASH write enable + output de2_fl_rst_n, // FLASH reset + output de2_fl_oe_n, // FLASH output enable + output de2_fl_ce_n, // FLASH chip enable + output de2_fl_wp_n, // FLASH hardware write protect + input de2_fl_rb, // FLASH ready/busy + // + output de2_lcd_blig, // LCD back light ON/OFF + output de2_lcd_on, // LCD power ON + output de2_lcd_rw, // LCD read/write select, 0 = write, 1 = read + output de2_lcd_en, // LCD enable + output de2_lcd_rs, // LCD command/data select, 0 = command, 1 = data + inout [7:0] de2_lcd_data, // LCD data bus 8 bits + // + inout [3:0] de2_sd_dat, // SD Card Data + inout de2_sd_cmd, // SD Card Command Signal + output de2_sd_clk, // SD Card Clock + input de2_sd_wp_n, // SD Card Write Protect + // + inout de2_ps2_kbdat, // PS2 Keyboard Data + inout de2_ps2_kbclk, // PS2 Keyboard Clock + inout de2_ps2_msdat, // PS2 Mouse Data + inout de2_ps2_msclk, // PS2 Mouse Clock + // + output de2_vga_hs, // VGA H_SYNC + output de2_vga_vs, // VGA V_SYNC + output [7:0] de2_vga_r, // VGA Red[3:0] + output [7:0] de2_vga_g, // VGA Green[3:0] + output [7:0] de2_vga_b, // VGA Blue[3:0] + output de2_vga_blank_n, // VGA blank + output de2_vga_clk, // VGA clock + output de2_vga_sync_n, // VGA synchro + // + output de2_enet0_gtx_clk, // Ethernet 0 RGMII + input de2_enet0_int_n, // + output de2_enet0_mdc, // + inout de2_enet0_mdio, // + output de2_enet0_rst_n, // + input de2_enet0_rx_clk, // + input de2_enet0_rx_col, // + input de2_enet0_rx_crs, // + input [3:0] de2_enet0_rx_dat, // + input de2_enet0_rx_dv, // + input de2_enet0_rx_er, // + input de2_enet0_tx_clk, // + output [3:0] de2_enet0_tx_dat, // + output de2_enet0_tx_en, // + output de2_enet0_tx_er, // + input de2_enet0_link100, // + // + output de2_enet1_gtx_clk, // Ethernet 1 RGMII + input de2_enet1_int_n, // + output de2_enet1_mdc, // + inout de2_enet1_mdio, // + output de2_enet1_rst_n, // + input de2_enet1_rx_clk, // + input de2_enet1_rx_col, // + input de2_enet1_rx_crs, // + input [3:0] de2_enet1_rx_dat, // + input de2_enet1_rx_dv, // + input de2_enet1_rx_er, // + input de2_enet1_tx_clk, // + output [3:0] de2_enet1_tx_dat, // + output de2_enet1_tx_en, // + output de2_enet1_tx_er, // + input de2_enet1_link100, // + // + inout [15:0] de2_otg_dat, // USB OTG controller + output [1:0] de2_otg_addr, // + output de2_otg_cs_n, // + output de2_otg_wr_n, // + output de2_otg_rd_n, // + input [1:0] de2_otg_int, // + output de2_otg_rst_n, // + input [1:0] de2_otg_dreq, // + output [1:0] de2_otg_dack_n, // + inout de2_otg_fspeed, // + inout de2_otg_lspeed, // + // + inout [35:0] de2_gpio, // GPIO Connection Data + inout [6:0] de2_exio, // Extend IO pins + input de2_irda, // + // + output de2_aud_adclrck, // Audio CODEC ADC LR Clock + input de2_aud_adcdat, // Audio CODEC ADC Data + output de2_aud_daclrck, // Audio CODEC DAC LR Clock + output de2_aud_dacdat, // Audio CODEC DAC Data + inout de2_aud_bclk, // Audio CODEC Bit-Stream Clock + output de2_aud_xck, // Audio CODEC Chip Clock + // + inout de2_i2c_dat, // I2C Data, Audio and TV + inout de2_i2c_clk, // I2C Clock, Audio and TV + inout de2_eeprom_dat, // I2C Data, EEPROM + inout de2_eeprom_clk, // I2C Clock, EEPROM + // + input de2_td_clk27, // TV Decoder + input [7:0] de2_td_dat, // + input de2_td_hs, // + input de2_td_vs, // + output de2_td_rst_n, // + // + input de2_hsmc_clkin_p1, // HSMC (LVDS) + input de2_hsmc_clkin_p2, // + input de2_hsmc_clkin0, // + output de2_hsmc_clkout_p1, // + output de2_hsmc_clkout_p2, // + output de2_hsmc_clkout0, // + inout [3:0] de2_hsmc_d, // + input [16:0] de2_hsmc_rxd_p, // + output [16:0] de2_hsmc_txd_p // +); + +//______________________________________________________________________________ +// +wire [31:0] baud = 921600/`SYS_BAUD-1; +wire clk, wr_n, rst_n, dbin; +wire [7:0] dcpu; +wire [7:0] dsys; +wire [7:0] dsio; +wire [7:0] dram; +wire [15:0] a; +wire uack; + +reg f1, f2; +reg [6:0] hex0, hex1, hex2, hex3; +reg [6:0] hex4, hex5, hex6, hex7; +reg [7:0] led; +reg [7:0] rcnt = 8'h00; +reg [2:0] div; +reg [15:0] div1ms; +reg ms, intrq, inta; +wire inte, sync; + +assign clk = de2_clock_50; +assign rst_n = (rcnt == 8'hFF); +assign dsys = inta ? 8'hE7 + : (a[15:8] == 8'hFF) ? {4'h00, de2_button[3:0]} + : (a[15:8] == 8'hFE) ? dsio + : dram; + +always @(posedge clk) +begin + div <= div + 3'b001; + f1 <= div[0]; + f2 <= ~div[0]; + + if (sync) inta = dcpu[0]; + if (div1ms == ((`SYS_CLOCK/1000)-1)) + begin + div1ms <= 16'h0000; + ms <= 1; + end + else + begin + div1ms <= div1ms + 16'h0001; + ms <= 0; + end + + if (ms) intrq <= 1; + if (inta) intrq <= 0; +end + +always @(posedge clk) +begin + if (~de2_button[3]) + rcnt <= 8'h00; + else + if (rcnt != 8'hFF) rcnt <= rcnt + 8'h01; +end + +memini ram +( + .address(a[13:0]), + .clock(clk), + .data(dcpu), + .wren(~wr_n & rst_n & ~a[15] & ~a[14]), + .q(dram) +); + +always @(posedge clk) +begin + if (~wr_n) + begin + if (a == 16'hFFFB) led <= dcpu; + if (a == 16'hFFFC) hex0 <= dcpu[6:0]; + if (a == 16'hFFFD) hex1 <= dcpu[6:0]; + if (a == 16'hFFFE) hex2 <= dcpu[6:0]; + if (a == 16'hFFFF) hex3 <= dcpu[6:0]; + if (a == 16'hFFF0) hex4 <= dcpu[6:0]; + if (a == 16'hFFF1) hex5 <= dcpu[6:0]; + if (a == 16'hFFF2) hex6 <= dcpu[6:0]; + if (a == 16'hFFF3) hex7 <= dcpu[6:0]; + end +end + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam uart.REFCLK = `SYS_CLOCK; +`endif + +uart_wb uart +( + .wb_clk_i(clk), + .wb_rst_i(~rst_n), + .wb_adr_i(a[0]), + .wb_dat_i(dcpu), + .wb_dat_o(dsio), + .wb_cyc_i((~wr_n | dbin) & (a[15:8] == 8'hFE)), + .wb_we_i(~wr_n & (a[15:8] == 8'hFE)), + .wb_stb_i((~wr_n | (dbin & ~uack)) & (a[15:8] == 8'hFE)), + .wb_ack_o(uack), + + .tx_dat_o(de2_uart_txd), + .tx_cts_i(1'b0), + .rx_dat_i(de2_uart_rxd), + .rx_dtr_o(de2_uart_cts), + +// .tx_ready(), +// .tx_empty(), +// .rx_ready(), + + .cfg_bdiv(baud[15:0]), + .cfg_nbit(2'b11), + .cfg_nstp(1'b1), + .cfg_pena(1'b0), + .cfg_podd(1'b0) +); + +vm80a_core cpu +( + .pin_clk(clk), + .pin_f1(f1), + .pin_f2(f2), + .pin_reset(~rst_n), + .pin_a(a), + .pin_dout(dcpu), + .pin_din(dsys), + .pin_hold(1'b0), + .pin_ready(1'b1), + .pin_int(intrq), + .pin_wr_n(wr_n), + .pin_dbin(dbin), + .pin_inte(inte), + .pin_sync(sync) +); + +assign de2_hex0 = ~hex0; +assign de2_hex1 = ~hex1; +assign de2_hex2 = ~hex2; +assign de2_hex3 = ~hex3; +assign de2_hex4 = ~hex4; +assign de2_hex5 = ~hex5; +assign de2_hex6 = ~hex6; +assign de2_hex7 = ~hex7; + +assign de2_ledg[7:0] = led; +assign de2_ledg[8] = sync; + +//______________________________________________________________________________ +// +// Temporary and debug assignments +// +// assign de2_uart_txd = 1'bz; +// assign de2_uart_cts = 1'bz; + +assign de2_dram_dq = 32'hzzzzzzzz; +assign de2_dram_addr = 13'h0000; +assign de2_dram_dqm = 4'b0; +assign de2_dram_we_n = 1'b1; +assign de2_dram_cas_n = 1'b1; +assign de2_dram_ras_n = 1'b1; +assign de2_dram_cs_n = 1'b1; +assign de2_dram_ba[0] = 1'b0; +assign de2_dram_ba[1] = 1'b0; +assign de2_dram_clk = 1'b0; +assign de2_dram_cke = 1'b0; + +assign de2_sram_dq = 16'hzzzz; +assign de2_sram_addr = 20'h00000; +assign de2_sram_ub_n = 1'b1; +assign de2_sram_lb_n = 1'b1; +assign de2_sram_we_n = 1'b1; +assign de2_sram_ce_n = 1'b1; +assign de2_sram_oe_n = 1'b1; + +assign de2_fl_dq = 8'hzz; +assign de2_fl_addr = 23'h000000; +assign de2_fl_we_n = 1'b1; +assign de2_fl_rst_n = 1'b0; +assign de2_fl_oe_n = 1'b1; +assign de2_fl_ce_n = 1'b1; +assign de2_fl_wp_n = 1'b0; + +assign de2_lcd_data = 8'hzz; +assign de2_lcd_blig = 1'b0; +assign de2_lcd_on = 1'b0; +assign de2_lcd_rw = 1'b0; +assign de2_lcd_en = 1'b0; +assign de2_lcd_rs = 1'b0; + +assign de2_sd_dat = 4'hz; +assign de2_sd_cmd = 1'hz; +assign de2_sd_clk = 1'h0; + +assign de2_ps2_kbdat = 1'hz; +assign de2_ps2_kbclk = 1'hz; +assign de2_ps2_msdat = 1'hz; +assign de2_ps2_msclk = 1'hz; + +assign de2_vga_blank_n = 1'b0; +assign de2_vga_hs = 1'b00; +assign de2_vga_vs = 1'b00; +assign de2_vga_r = 8'h00; +assign de2_vga_g = 8'h00; +assign de2_vga_b = 8'h00; +assign de2_vga_clk = 1'b00; +assign de2_vga_sync_n = 1'b00; +assign de2_td_rst_n = 1'b0; + +assign de2_gpio = 36'hzzzzzzzzz; +assign de2_exio = 7'hzz; +assign de2_ledr = 18'hzzzzz; + +assign de2_enet0_gtx_clk = 1'b0; +assign de2_enet0_mdc = 1'b0; +assign de2_enet0_mdio = 1'bz; +assign de2_enet0_rst_n = 1'b0; +assign de2_enet0_tx_dat = 4'h0; +assign de2_enet0_tx_en = 1'b0; +assign de2_enet0_tx_er = 1'b0; + +assign de2_enet1_gtx_clk = 1'b0; +assign de2_enet1_mdc = 1'b0; +assign de2_enet1_mdio = 1'bz; +assign de2_enet1_rst_n = 1'b0; +assign de2_enet1_tx_dat = 4'h0; +assign de2_enet1_tx_en = 1'b0; +assign de2_enet1_tx_er = 1'b0; + +assign de2_i2c_dat = 1'bz; +assign de2_i2c_clk = 1'bz; +assign de2_eeprom_dat = 1'bz; +assign de2_eeprom_clk = 1'bz; + +assign de2_otg_dat = 16'hzzzz; +assign de2_otg_addr = 2'b00; +assign de2_otg_cs_n = 1'b1; +assign de2_otg_wr_n = 1'b1; +assign de2_otg_rd_n = 1'b1; +assign de2_otg_rst_n = 1'b1; +assign de2_otg_dack_n = 2'b11; +assign de2_otg_fspeed = 1'bz; +assign de2_otg_lspeed = 1'bz; + +assign de2_aud_adclrck = 1'bz; +assign de2_aud_daclrck = 1'bz; +assign de2_aud_dacdat = 1'bz; +assign de2_aud_bclk = 1'b0; +assign de2_aud_xck = 1'b0; + +assign de2_hsmc_clkout_p1 = 1'b0; +assign de2_hsmc_clkout_p2 = 1'b0; +assign de2_hsmc_clkout0 = 1'b0; +assign de2_hsmc_d = 4'hz; +assign de2_hsmc_txd_p = 16'h0000; +assign de2_sma_clkout = 1'b0; + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/org/rtl/de2-115/de2_uart.v b/1801BM1_vm80a/org/rtl/de2-115/de2_uart.v new file mode 100644 index 0000000000000000000000000000000000000000..3dc00014e21439a6ad9a4c1bf00e624cee436fc9 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/de2-115/de2_uart.v @@ -0,0 +1,378 @@ +// +// Copyright (c) 2014-2015 by 1801BM1@gmail.com +// +// Universal Serial Asynchronous Receiver-Transmitter (simplified 8251) +//______________________________________________________________________________ +// +module uart_wb #(parameter REFCLK=50000000) +( + input wb_clk_i, // system clock + input wb_rst_i, // peripheral reset + // + input [0:0] wb_adr_i, // + input [7:0] wb_dat_i, // + output reg [7:0] wb_dat_o, // + input wb_cyc_i, // + input wb_we_i, // + input wb_stb_i, // + output reg wb_ack_o, // + // + output tx_dat_o, // output serial data (txd) + input tx_cts_i, // enable transmitter (rts) + input rx_dat_i, // input serial data (rxd) + output rx_dtr_o, // receiver ready (cts) + // + output tx_ready_o, // tx ready request + output tx_empty_o, // tx empty request + output rx_ready_o, // rx ready request + // + input [15:0] cfg_bdiv, // baudrate divisor: (921600/baud)-1 + input [1:0] cfg_nbit, // word length: 00-5, 01-6, 10-7, 11-8 bit + input cfg_nstp, // tx stop bits: 0 - 1 stop, 1 - 2 stop + input cfg_pena, // parity control enable + input cfg_podd // odd parity (complete to odd ones) +); + +wire [63:0] add_arg; +reg [16:0] add_reg; +reg [15:0] baud_div; +reg baud_x16; +wire baud_ref; + +reg [1:0] tx_cts_reg; +reg [1:0] rx_dat_reg; + +wire csr_wstb; +wire rbr_rstb; +wire thr_wstb; + +wire tx_par; +reg [7:0] tx_thr; +reg [9:0] tx_shr; +reg [7:0] tx_bcnt; +reg tx_busy; +reg tx_ready, tx_empty, tx_break; + +wire rx_dat; +reg [7:0] rx_rbr; +reg [8:0] rx_shr; +reg [7:0] rx_bcnt; +reg rx_ready, rx_perr, rx_ovf, rx_break; +wire rx_load, rx_stb; +reg rx_frame, rx_start, rx_par; + +//______________________________________________________________________________ +// +// Caution note: the arithmetic expressions should be calculated in 64-bit width +// +assign add_arg = (64'h0000000000100000 * 64'd921600)/REFCLK; +assign baud_ref = add_reg[16]; +// +// Phase accumulator to generate 921600 * 16 Hz reference clock strobe +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + add_reg <= 17'h00000; + else + begin + add_reg <= {1'b0, add_reg[15:0]} + add_arg[16:0]; + end +end +// +// Baud rate x16 generator +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + baud_div <= 16'h0000; + baud_x16 <= 1'b0; + end + else + begin + if (baud_ref) + if (baud_div == 16'h0000) + baud_div <= cfg_bdiv; + else + baud_div <= baud_div - 16'h0001; + + baud_x16 <= baud_ref & (baud_div == 16'h0000); + end + +end + +//______________________________________________________________________________ +// +assign csr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & wb_adr_i[0]; +assign thr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & ~wb_adr_i[0]; +assign rbr_rstb = wb_cyc_i & wb_stb_i & ~wb_we_i & ~wb_ack_o & ~wb_adr_i[0]; +// +// Output data multiplexed register +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + wb_dat_o <= 8'h00; + else +// +// if (wb_cyc_i & wb_stb_i & ~wb_ack_o) +// + begin + if (wb_adr_i[0]) + wb_dat_o <= (tx_ready << 7) + | (tx_break << 6) + | (tx_empty << 5) + | (rx_ready << 3) + | (rx_break << 2) + | (rx_perr << 1) + | (rx_ovf << 0); + else + wb_dat_o <= rx_rbr; + end +end + +always @(posedge wb_clk_i) + wb_ack_o <= wb_cyc_i & wb_stb_i & ~wb_ack_o; + +// +// Control register bits +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + tx_break <= 1'b0; + else + if (csr_wstb) tx_break <= wb_dat_i[6]; +end + +//______________________________________________________________________________ +// +// Interrupts +// +assign tx_ready_o = tx_ready; +assign tx_empty_o = tx_empty; +assign rx_ready_o = rx_ready; + +//______________________________________________________________________________ +// +// Metastability issues +// +always @(posedge wb_clk_i) +begin + tx_cts_reg[0] <= ~tx_cts_i; + tx_cts_reg[1] <= tx_cts_reg[0]; + + rx_dat_reg[0] <= rx_dat_i; + rx_dat_reg[1] <= rx_dat_reg[0]; +end + +//______________________________________________________________________________ +// +// Transmitter unit +// +assign tx_par = tx_thr[0] ^ tx_thr[1] ^ tx_thr[2] ^ tx_thr[3] ^ tx_thr[4] + ^ (tx_thr[5] & (cfg_nbit >= 2'b01)) + ^ (tx_thr[6] & (cfg_nbit >= 2'b10)) + ^ (tx_thr[7] & (cfg_nbit == 2'b11)) + ^ cfg_podd; +assign tx_dat_o = tx_shr[0] & ~tx_break; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + tx_ready <= 1'b1; + tx_empty <= 1'b1; + tx_shr <= 10'o1777; + tx_busy <= 1'b0; + tx_bcnt <= 8'b00000000; + tx_thr <= 8'b00000000; + end + else + begin + tx_empty <= tx_ready & ~tx_busy; + // + // Transmitter hold register write + // + if (thr_wstb) + begin + tx_ready <= 1'b0; + tx_thr <= wb_dat_i[7:0]; + end + + if (baud_x16) + begin + // + // Transmit process + // + if (tx_busy) + begin + if (tx_bcnt == 8'b00000001) + tx_busy <= 1'b0; + + if (tx_bcnt != 8'b00000000) + tx_bcnt <= tx_bcnt - 8'b00000001; + + if (tx_bcnt[3:0] == 4'b0000) + tx_shr <= {1'b1, tx_shr[9:1]}; + end + + // + // Starting new word transmit + // + if (~tx_ready & ~tx_busy & tx_cts_reg[1]) + begin + tx_busy <= 1'b1; + tx_ready <= ~thr_wstb; + tx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena} + {3'b000, cfg_nstp}, 4'b1111}; + + if (cfg_pena) + case(cfg_nbit) + 2'b00: tx_shr <= {3'b111, tx_par, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {2'b11, tx_par, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {1'b1, tx_par, tx_thr[6:0], 1'b0}; + default: tx_shr <= { tx_par, tx_thr[7:0], 1'b0}; + endcase + else + case(cfg_nbit) + 2'b00: tx_shr <= {4'b1111, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {3'b111, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {2'b11, tx_thr[6:0], 1'b0}; + default: tx_shr <= {1'b1, tx_thr[7:0], 1'b0}; + endcase + end + end + end +end + +//______________________________________________________________________________ +// +// Receiver unit +// +assign rx_dtr_o = rx_ready; +assign rx_dat = rx_dat_reg[1]; + +assign rx_load = rx_stb & (rx_bcnt[7:4] == 4'b0000); +assign rx_stb = (rx_bcnt[3:0] == 4'b0001) & baud_x16; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + rx_ready <= 1'b0; + rx_break <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + rx_frame <= 1'b0; + rx_start <= 1'b0; + rx_par <= 1'b0; + rx_rbr <= 8'b00000000; + rx_shr <= 9'b00000000; + rx_bcnt <= 8'b00000000; + end + else + begin + if (rx_load) + begin + rx_ready <= 1'b1; + case(cfg_nbit) + 2'b00: rx_rbr <= {3'b000, rx_shr[4:0]}; + 2'b01: rx_rbr <= {2'b00, rx_shr[5:0]}; + 2'b10: rx_rbr <= {1'b0, rx_shr[6:0]}; + default: rx_rbr <= rx_shr[7:0]; + endcase + rx_perr <= rx_par; + rx_ovf <= rx_ready; + rx_break <= ~rx_dat; + end + else + if (rbr_rstb) + begin + rx_ready <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + end + + if (baud_x16) + begin + if (~rx_frame) + // + // Waiting for start bit + // + if (~rx_dat) + begin + rx_par <= cfg_pena & cfg_podd; + rx_start <= 1'b1; + rx_frame <= 1'b1; + rx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena}, 4'b0111}; + end + else + begin + rx_start <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + begin + // + // Receiving frame + // + if (rx_bcnt != 8'b00000000) + rx_bcnt <= rx_bcnt - 8'b00000001; + // + // Start bit monitoring + // + if (rx_start) + begin + if (rx_dat) + begin + // + // Spurrious start bit + // + rx_start <= 1'b0; + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + if (rx_bcnt[3:0] == 4'b0010) + rx_start <= 1'b0; + end + else + begin + // + // Receiving data + // + if (rx_stb) + begin + rx_par <= (rx_par ^ rx_dat) & cfg_pena; + if (cfg_pena) + case(cfg_nbit) + 2'b00: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b01: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + 2'b10: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + default: rx_shr <= {rx_dat, rx_shr[8:1]}; + endcase + else + case(cfg_nbit) + 2'b00: rx_shr <= {4'b0000, rx_dat, rx_shr[4:1]}; + 2'b01: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b10: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + default: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + endcase + if (rx_load & rx_dat) + begin + // + // Stop bit detected + // + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + end + if ((rx_bcnt == 8'b00000000) & rx_dat) + rx_frame <= 1'b0; + end + end + end + end +end +endmodule diff --git a/1801BM1_vm80a/org/rtl/vm80a.v b/1801BM1_vm80a/org/rtl/vm80a.v new file mode 100644 index 0000000000000000000000000000000000000000..d6783b99b65d36b6eafc8ef80349aa7d5a6bd938 --- /dev/null +++ b/1801BM1_vm80a/org/rtl/vm80a.v @@ -0,0 +1,955 @@ +// +// Copyright (c) 2014-2018 by 1801BM1@gmail.com +// Licensed under CC-BY 3.0 (https://creativecommons.org/licenses/by/3.0/) +// +//______________________________________________________________________________ +// +// vm80a wrapper for direct replacement of microprocessor package +// extra high-speed clock should be provided to operate, F1 and F2 +// phases serve as clock enable gates +// +module vm80a +( + input pin_clk, // global module clock (no in original 8080) + input pin_f1, // clock phase 1 (used as clock enable) + input pin_f2, // clock phase 2 (used as clock enable) + input pin_reset, // module reset + output[15:0] pin_a, // address bus outputs + inout [7:0] pin_d, // data bus inouts + input pin_hold, // + output pin_hlda, // + input pin_ready, // + output pin_wait, // + input pin_int, // + output pin_inte, // + output pin_sync, // + output pin_dbin, // + output pin_wr_n +); + +wire pin_aena, pin_dena; +wire [7:0] pin_din, pin_dout; +wire [15:0] pin_addr; +reg f1_core, f2_core; + +assign pin_a = pin_aena ? pin_addr : 16'hZZZZ; +assign pin_d = pin_dena ? pin_dout : 8'hZZ; +assign pin_din = pin_d; + +always @(posedge pin_clk) +begin + f1_core <= pin_f1; + f2_core <= pin_f2; +end + +vm80a_core core +( + .pin_clk (pin_clk), + .pin_f1 (f1_core), + .pin_f2 (f2_core), + .pin_reset (pin_reset), + .pin_a (pin_addr), + .pin_dout (pin_dout), + .pin_din (pin_din), + .pin_aena (pin_aena), + .pin_dena (pin_dena), + .pin_hold (pin_hold), + .pin_hlda (pin_hlda), + .pin_ready (pin_ready), + .pin_wait (pin_wait), + .pin_int (pin_int), + .pin_inte (pin_inte), + .pin_sync (pin_sync), + .pin_dbin (pin_dbin), + .pin_wr_n (pin_wr_n) +); +endmodule + +module vm80a_core +( + input pin_clk, // global module clock (no in original 8080) + input pin_f1, // clock phase 1 (used as clock enable) + input pin_f2, // clock phase 2 (used as clock enable) + input pin_reset, // module reset + output[15:0] pin_a, // address bus outputs + output[7:0] pin_dout, // data bus output + input [7:0] pin_din, // data bus input + output pin_aena, // address outputs enable + output pin_dena, // data outputs enable + input pin_hold, // + output pin_hlda, // + input pin_ready, // + output pin_wait, // + input pin_int, // + output pin_inte, // + output pin_sync, // + output pin_dbin, // + output pin_wr_n +); + +//______________________________________________________________________________ +// +wire [7:0] d; +reg [7:0] db, di; +reg [15:0] a; +wire clk, f1, f2; +reg abufena, db_ena, db_stb, dbin_pin, dbin_ext; +reg reset; +wire ready; + +reg t851, t404, t382, t383, t712, t735, t773; +reg hold, hlda_pin; +wire hlda, h889; + +reg wr_n, t1124, t1011, sync; +wire ready_int; + +reg [15:0] r16_pc, r16_hl, r16_de, r16_bc, r16_sp, r16_wz, mxo; +wire [15:0] mxi; +wire mxr0, mxr1, mxr2, mxr3, mxr4, mxr5; +wire mxwh, mxwl, mxrh, mxrl, mxw16, mxwadr; +wire dec16, inc16, iad16; +reg xchg_dh, xchg_tt, t3144; +wire t1460, t1467, t1513, t1514, t1519; + +wire sy_inta, sy_wo_n, sy_hlta, sy_out, sy_m1, sy_inp, sy_memr; +reg sy_stack; + +wire thalt, twt2; +reg t1, t2, tw, t3, t4, t5; +reg t1f1, t2f1, twf1, t3f1, t4f1, t5f1; +reg m1, m2, m3, m4, m5; +reg m1f1, m2f1, m3f1, m4f1, m5f1; + +wire start, ms0, ms1, m836, m839, m871; +reg eom, t789, t887, t953, t976, t980; + +reg intr, inta, inte, mstart, minta; +wire irq; + +reg [7:0] i; +reg i25, i14, i03; +wire imx, acc_sel; +wire id_op, id_io, id_in, id_popsw, id_pupsw, + id_nop, id_lxi, id_inx, id_inr, id_dcr, id_idr, id_mvi, id_dad, + id_dcx, id_opa, id_idm, id_hlt, id_mov, id_opm, id_pop, id_rst, + id_cxx, id_jxx, id_rxx, id_ret, id_jmp, id_opi, id_out, id_11x, + id_rlc, id_rxc, id_rar, id_sha, id_daa, id_cma, id_stc, id_cmc, + id_add, id_adc, id_sub, id_sbb, id_ana, id_xra, id_ora, id_cmp, + id_lsax, id_mvim, id_shld, id_lhld, id_mvmr, id_mvrm, id_push, + id_xthl, id_sphl, id_pchl, id_xchg, id_call, id_eidi, id_stlda; + +wire id80, id81, id82, id83, id84, id85, id86, id00, id01, + id02, id03, id04, id05, id06, id07, id08, id09, id10; +wire goto, jmpflag; +reg jmptake, tree0, tree1, tree2; +reg t2806, t2817, t2819, t3047, t2998, t3363, t3403, t3335, t3361; + +reg [7:0] xr, r, acc; +wire [7:0] x, s, c; +wire cl, ch, daa, daa_6x, daa_x6; +wire a398; +reg a327, a357, a358; +wire alu_xout, alu_xwr, alu_xrd, alu_ald, alu_awr, alu_ard, + alu_rld, alu_r00, alu_rwr, alu_srd, alu_zrd, alu_frd; + +reg psw_z, psw_s, psw_p, psw_c, psw_ac, tmp_c; +reg t2222, t1375, t1497, t1698, t1668, t1780, t1993, t1994; +reg psw_ld, psw_wr, t2046, t2133, t2175; + +//_____________________________________________________________________________ +// +assign clk = pin_clk; +assign f1 = pin_f1; +assign f2 = pin_f2; + +assign pin_a = a; +assign pin_aena = abufena; +assign pin_dout = db; +assign pin_dena = db_ena; + +assign d[7] = ~reset & ~alu_zrd & + ( dbin_ext & di[7] + | mxrl & mxo[7] + | mxrh & mxo[15] + | t1f1 & sy_memr + | alu_xrd & xr[7] + | alu_ard & acc[7] + | alu_frd & psw_s + | alu_srd & s[7] ); + +assign d[6] = ~reset & ~alu_zrd & + ( dbin_ext & di[6] + | mxrl & mxo[6] + | mxrh & mxo[14] + | t1f1 & sy_inp + | alu_xrd & xr[6] + | alu_ard & acc[6] + | alu_frd & psw_z + | alu_srd & s[6] ); + +assign d[5] = ~reset & ~alu_zrd & + ( dbin_ext & di[5] + | mxrl & mxo[5] + | mxrh & mxo[13] + | t1f1 & sy_m1 + | alu_xrd & xr[5] + | alu_ard & acc[5] + | alu_frd & 1'b0 + | alu_srd & s[5] ); + +assign d[4] = ~reset & ~alu_zrd & + ( dbin_ext & di[4] + | mxrl & mxo[4] + | mxrh & mxo[12] + | t1f1 & sy_out + | alu_xrd & xr[4] + | alu_ard & acc[4] + | alu_frd & psw_ac + | alu_srd & s[4] ); + +assign d[3] = ~reset & ~alu_zrd & + ( dbin_ext & di[3] + | mxrl & mxo[3] + | mxrh & mxo[11] + | t1f1 & sy_hlta + | alu_xrd & xr[3] + | alu_ard & acc[3] + | alu_frd & 1'b0 + | alu_srd & s[3] ); + +assign d[2] = ~reset & ~alu_zrd & + ( dbin_ext & di[2] + | mxrl & mxo[2] + | mxrh & mxo[10] + | t1f1 & sy_stack + | alu_xrd & xr[2] + | alu_ard & acc[2] + | alu_frd & psw_p + | alu_srd & s[2] ); + +assign d[1] = ~reset & ~alu_zrd & + ( dbin_ext & di[1] + | mxrl & mxo[1] + | mxrh & mxo[9] + | t1f1 & sy_wo_n + | alu_xrd & xr[1] + | alu_ard & acc[1] + | alu_frd & 1'b1 + | alu_srd & s[1] ); + +assign d[0] = ~reset & ~alu_zrd & + ( dbin_ext & di[0] + | mxrl & mxo[0] + | mxrh & mxo[8] + | t1f1 & sy_inta + | alu_xrd & xr[0] + | alu_ard & acc[0] + | alu_frd & psw_c + | alu_srd & s[0] ); + +always @(posedge clk) +begin + if (f2 & db_stb) db <= d; + if (f2) abufena <= (~twt2 | ~thalt) & ~hlda_pin; + if (f1) db_stb <= t1 | (~sy_wo_n & t2); + if (f1) t851 <= t1 | (~sy_wo_n & (t2 | tw | t3)); + if (f2) db_ena <= ~reset & t851; +end + +//______________________________________________________________________________ +// +// reset input buffer +// +always @(posedge clk) +begin + if (f1) t404 <= pin_reset; + if (f2) reset <= t404; +end + +//______________________________________________________________________________ +// +// hold input buffer +// +assign pin_hlda = hlda_pin; +assign hlda = hold & (t773 | (t3 & sy_wo_n) | (~m1 & sy_hlta) | t735); +assign h889 = t2f1 | twf1; + +always @(posedge clk) +begin + if (f1) t712 <= ~sy_wo_n & t3; + if (f2) t735 <= t712; + if (~f2) t382 <= pin_hold; + if (f2) t383 <= ((~t382 & hold) | t383); // extend the front detector pulse for entire F2 duration + if (~f2) t383 <= 1'b0; + if (f2) t773 <= hlda_pin; + if (f1) hlda_pin <= hlda; +end + +always @(posedge clk) +begin + if (reset) + hold <= 1'b0; + else + if (f2) + begin + if (t382) + begin + if (~sy_inta & h889) hold <= 1'b1; + end + else + hold <= 1'b0; + end +end + +//______________________________________________________________________________ +// +assign pin_dbin = dbin_pin; +assign pin_wr_n = wr_n; +assign pin_sync = sync; + +always @(posedge clk) +begin + dbin_ext <= (f2 | dbin_pin) & ((t1124 & (m1f1 | ~sy_hlta)) | dbin_ext); + + if (dbin_pin) di <= pin_din; + if (f2) dbin_pin <= t1124 & (m1f1 | ~sy_hlta); + if (f2) sync <= ~ready_int & t1011; + if (f1) t1011 <= t1 & ~reset; + if (f1) t1124 <= (t2 | tw) & sy_wo_n; + if (f1) wr_n <= ~(t3 | tw) | ready_int | sy_wo_n; +end + +//______________________________________________________________________________ +// +// ready pin and internal circuits +// +assign ready_int = (m4 | m5) & id_dad; +assign ready = ready_int | pin_ready; +assign pin_wait = twf1; + +//______________________________________________________________________________ +// +// register unit - 6 16-bit registers +// +// r0 - pc +// r1 - hl, de +// r2 - de, hl +// r3 - bc +// r4 - sp +// r5 - wz +// +assign t1467 = tree1 | (id04 & t4f1 & ~id_xthl); +assign t1519 = tree2 | (id00 & t4f1 & ~id_xthl); +assign mxi = inc16 ? (a + 16'h0001) + : dec16 ? (a - 16'h0001) + : a; + +assign inc16 = iad16 & ~dec16; +assign dec16 = iad16 & id05 & (t4f1 | t5f1 | m4f1 | m5f1); +assign iad16 = ~(id00 & (t4f1 | t5f1)) & (~minta | m5 | t3144); + +assign mxw16 = t3403; +assign mxwadr = t3363 | (t4f1 & ~id_dad & ~id_hlt); +assign t1513 = (t4f1 & id07) | t3335; +assign t1514 = (t4f1 & id08) | t3361; + +assign mxrh = t2998 | (id08 & t4f1 & ~i03); +assign mxrl = t3047 | (id08 & t4f1 & i03); +assign mxwh = t2817 | (t2806 & ~i03); +assign mxwl = t2819 | (t2806 & i03); + +assign mxr0 = tree0; +assign mxr1 = xchg_dh & (((t1513 | t1514) & (~i14 & i25)) | t1519) + | ~xchg_dh & (t1513 | t1514) & (i14 & ~i25); +assign mxr2 = xchg_dh & (t1513 | t1514) & (i14 & ~i25) + | ~xchg_dh & (((t1513 | t1514) & (~i14 & i25)) | t1519); +assign mxr3 = (t1513 | t1514) & (~i14 & ~i25); +assign mxr4 = t1467 | (t1513 & i14 & i25); +assign mxr5 = ~(t1467 | t1513 | t1514 | t1519 | mxr0); + +always @ (posedge clk) +begin + if (f1) t3144 <= t4 | t5 | (m4 & ~id02); + xchg_tt <= id_xchg & t2; + xchg_dh <= ~reset & ((xchg_tt & ~(id_xchg & t2)) ? ~xchg_dh : xchg_dh); +end + +always @ (*) +case ({mxr0, mxr1, mxr2, mxr3, mxr4, mxr5}) + 6'b100000: mxo = r16_pc; + 6'b010000: mxo = r16_hl; + 6'b001000: mxo = r16_de; + 6'b000100: mxo = r16_bc; + 6'b000010: mxo = r16_sp; + 6'b000001: mxo = r16_wz; + default: mxo = 16'h0000; +endcase + +always @ (posedge clk) +if (f2) +begin + if (mxwadr) a <= mxo; + if (mxw16) + begin + if (mxr0) r16_pc <= mxi; + if (mxr1) r16_hl <= mxi; + if (mxr2) r16_de <= mxi; + if (mxr3) r16_bc <= mxi; + if (mxr4) r16_sp <= mxi; + if (mxr5) r16_wz <= mxi; + end + else + begin + if (mxwl) + begin + if (mxr0) r16_pc[7:0] <= d; + if (mxr1) r16_hl[7:0] <= d; + if (mxr2) r16_de[7:0] <= d; + if (mxr3) r16_bc[7:0] <= d; + if (mxr4) r16_sp[7:0] <= d; + if (mxr5) r16_wz[7:0] <= d; + end + if (mxwh) + begin + if (mxr0) r16_pc[15:8] <= d; + if (mxr1) r16_hl[15:8] <= d; + if (mxr2) r16_de[15:8] <= d; + if (mxr3) r16_bc[15:8] <= d; + if (mxr4) r16_sp[15:8] <= d; + if (mxr5) r16_wz[15:8] <= d; + end + end +end + +//______________________________________________________________________________ +// +// processor state +// +assign sy_hlta = id_hlt; +assign sy_m1 = m1; +assign sy_inp = m5 & id_in; +assign sy_out = m5 & id_out; +assign sy_inta = inta; +assign sy_memr = sy_wo_n & ~sy_inp & ~minta; +assign sy_wo_n = m1 | m2 | m3 | (((m4 & ~id86) | (m5 & ~id85)) & ~ready_int); + +always @(posedge clk) +begin + if (f1) + begin + sy_stack <= (t1 & t1460) + | (t3 & m3 & id_cxx & ~jmptake) + | (t5 & m1 & id_rxx & ~jmptake); + end +end +//______________________________________________________________________________ +// +// ticks state machine +// +assign twt2 = (t2f1 | twf1) & ~start; +assign thalt = ~m1 & sy_hlta; + +always @(posedge clk) +begin + if (f1) + begin + t1f1 <= t1 & ~reset; // ensure the reliable start after reset + t2f1 <= t2; + twf1 <= tw; + t3f1 <= t3; + t4f1 <= t4; + t5f1 <= t5; + end + if (f2) + begin + t1 <= start; + t2 <= ~start & t1f1; + tw <= ~start & (t2f1 | twf1) & (~ready | thalt); + t3 <= ~start & (t2f1 | twf1) & ready & ~thalt; + t4 <= ~start & t3f1 & ms0 & ~ms1; + t5 <= ~start & t4f1 & ms0 & ~ms1; + end +end + +//______________________________________________________________________________ +// +assign m836 = m1f1 & id82; +assign m839 = ~t976 | ~sy_hlta; +assign m871 = t789 | id81; + +assign start = ~m839 + | t953 + | (eom & ~(hold & t887)) + | (f2 & ((~t382 & hold) | t383) & ~(twf1 | t3f1 | t4f1 | t5f1)); + +assign ms0 = ~reset & m839 & ~(sy_stack & ~t1f1) & ~(eom & ~m836); +assign ms1 = ~reset & m839 & ~(sy_stack & ~t1f1) & ~(m871 & ~m836) & eom; + +always @(posedge clk) +begin + if (f1) + begin + t789 <= (id84 & m3) | (id83 & ~id_mvim & m4) | m5; + t887 <= hold; + t953 <= reset; + t976 <= t980 & m4; + eom <= t5 + | t4 & m1 & id80 + | t3 & m2 + | t3 & m3 + | t3 & m4 + | t3 & m5 & ~id_xthl; + end + if (f2) + begin + t980 <= sy_inta; + end +end + +//______________________________________________________________________________ +// +// processor cycles state machine +// +always @(posedge clk) +begin + if (f1) + begin + m1f1 <= m1; + m2f1 <= m2; + m3f1 <= m3; + m4f1 <= m4; + m5f1 <= m5; + end + if (f2) + begin + m1 <= (~ms0 & ~ms1) | (~ms1 & m1f1); + m2 <= (~ms0 | ~ms1) & ((ms0 & m2f1) | (ms1 & m1f1)); + m3 <= (ms0 & m3f1) | (ms1 & m2f1); + m4 <= (ms0 & m4f1) | (ms1 & m3f1) | (ms0 & ms1); + m5 <= (ms0 & m5f1) | (ms1 & m4f1); + end +end + +//______________________________________________________________________________ +// +// interrupt logic +// +assign irq = intr & inte & ~reset & ~hold; +assign pin_inte = inte; + +always @(posedge clk) +begin + if (f2) intr <= pin_int; + if (f2) mstart <= ~ms0 & ~ms1; + if (sy_inta) minta <= 1; + if (f1 & t1 & m1) minta <= 0; +end + +always @(posedge clk or posedge reset) +begin + if (reset) + begin + inta <= 0; + inte <= 0; + end + else + begin + if (f1) + begin + if (irq & ((tw & sy_hlta) | (mstart & ~id_eidi))) inta <= 1; + if (~intr | id_eidi | (t5 & id_rst)) inta <= 0; + end + if (f2) + begin + if (t1f1 & id_eidi) inte <= i[3]; + if (t1f1 & sy_inta) inte <= 0; + end + end +end +//______________________________________________________________________________ +// +// instruction register and decoder +// +function cmp +( + input [7:0] i, + input [7:0] c, + input [7:0] m +); + cmp = &(~(i ^ c) | m); +endfunction + +assign imx = ~(id_op | (id_mov & t4)); +assign acc_sel = imx ? (i[5:3] == 3'b111) : (i[2:0] == 3'b111); +assign jmpflag = (psw_c & i14 & ~i25) // Intel original: d[0] instead of psw_c + | (psw_p & ~i14 & i25) // Intel original: d[2] instead of psw_p + | (psw_z & ~i14 & ~i25) // Intel original: d[6] instead of psw_z + | (psw_s & i14 & i25); // Intel original: d[7] instead of psw_s + +always @(posedge clk) +begin + // + // Simplify the D-bus multiplexer and feed the I-register by input pins directly + // if (f2 & dbin_pin & (reset | (m1 & t3))) i <= pin_din; + // + if (~f2 & (reset | (m1 & t3))) i <= pin_din; + if (f1) + begin + i25 <= imx ? i[5] : i[2]; + i14 <= imx ? i[4] : i[1]; + i03 <= imx ? i[3] : i[0]; + end +end + +assign goto = id_rst | id_jmp | id_call | (jmptake & (id_cxx | id_jxx)); +assign t1460 = (t1 & ((m2 & id00) + | (m3 & id00) + | (m4 & (id01 | id04)) + | (m5 & (id01 | id04))) + | t2 & ( (m2 & id00) + | (m4 & id01) + | (m5 & id01)) + | t3 & ( (m4 & (id04 | id_sphl))) + | t5 & ( (m1 & (id04 | id_sphl)))) & ~(~jmptake & id_cxx & t5); + +always @(posedge clk) +begin + if (f2 & t4f1) + begin + jmptake <= i03 ? jmpflag : ~jmpflag; + end + if (f1) + begin + tree0 <= t1 & ( (m1 & ~goto) + | (m2 & ~id_xthl) + | (m3 & ~id_xthl) + | (m4 & id02)) + | t2 & ( m1 + | (m2 & ~id_xthl) + | (m3 & ~id_xthl) + | (m4 & (id02 | id_rst | id_cxx | id_call)) + | (m5 & (id_rst | id_cxx | id_call))) + | t3 & ( (m4 & (id_ret | id_rxx)) + | (m5 & (id_ret | id_rxx))) + | t5 & id_pchl; + + tree1 <= t1460; + + tree2 <= t1 & ( (m4 & (id_mov | id_idr | id_op)) + | (m5 & id08)) + | t2 & ( (m4 & (id_shld | id00 | id_dad)) + | (m5 & (id_shld | id00 | id_dad))) + | t3 & ( (m4 & (id_lhld | id_dad)) + | (m5 & (id_lhld | id_dad))) + | t5 & m5; + + t2806 <= id08 & ((t3 & m4) | (t5 & m1)); + t2817 <= reset | (t3 & (m1 | m3 | (m4 & id_io) | (m5 & id06))); + t2819 <= reset | (t3 & (m2 | (m4 & id06) | (m5 & id_rst))); + + t3047 <= (t1 | t2) & m4 & id_dad + | t2 & ((m4 & id_shld) | (m5 & id03)); + + t2998 <= (t1 | t2) & m5 & id_dad + | t2 & ((m5 & id_shld) | (m4 & id03)); + + t3403 <= t2 & ( (m1 | m2) + | (m3 & ~id_xthl) + | ((m4 | m5) & ~id_dad & ~id09)) + | t3 & m4 & id09 + | t5 & (m5 | (m1 & ~id08)); + + t3363 <= t1 & (m1 | m2 | m3 | ((m4 | m5) & ~id_hlt & ~id_dad)); + t3335 <= id07 & ((t1 & (m4 | m5)) | (t3 & (m2 | m3)) | t5); + + t3361 <= t1 & m4 & id_lsax + | t2 & id10 & ~sy_wo_n + | t3 & id10 & sy_wo_n & (m4 | m5) + | t5 & id08 & m1; + end +end + +assign id_nop = cmp(i, 8'b00xxx000, 8'b00111000); +assign id_lxi = cmp(i, 8'b00xx0001, 8'b00110000); +assign id_lsax = cmp(i, 8'b000xx010, 8'b00011000); +assign id_inx = cmp(i, 8'b00xx0011, 8'b00110000); +assign id_inr = cmp(i, 8'b00xxx100, 8'b00111000); +assign id_dcr = cmp(i, 8'b00xxx101, 8'b00111000); +assign id_idr = cmp(i, 8'b00xxx10x, 8'b00111001); +assign id_mvi = cmp(i, 8'b00xxx110, 8'b00111000); +assign id_dad = cmp(i, 8'b00xx1001, 8'b00110000); +assign id_dcx = cmp(i, 8'b00xx1011, 8'b00110000); +assign id_opa = cmp(i, 8'b00xxx111, 8'b00111000); +assign id_idm = cmp(i, 8'b0011010x, 8'b00000001); +assign id_stlda = cmp(i, 8'b0011x010, 8'b00001000); +assign id_mvim = cmp(i, 8'b00110110, 8'b00000000); +assign id_shld = cmp(i, 8'b00100010, 8'b00000000); +assign id_lhld = cmp(i, 8'b00101010, 8'b00000000); +assign id_mvmr = cmp(i, 8'b01110xxx, 8'b00000111) & ~id_hlt; +assign id_mvrm = cmp(i, 8'b01xxx110, 8'b00111000) & ~id_hlt; +assign id_hlt = cmp(i, 8'b01110110, 8'b00000000); +assign id_mov = cmp(i, 8'b01xxxxxx, 8'b00111111); +assign id_op = cmp(i, 8'b10xxxxxx, 8'b00111111); +assign id_opm = cmp(i, 8'b10xxx110, 8'b00111000); +assign id_pop = cmp(i, 8'b11xx0001, 8'b00110000); +assign id_push = cmp(i, 8'b11xx0101, 8'b00110000); +assign id_rst = cmp(i, 8'b11xxx111, 8'b00111000); +assign id_xthl = cmp(i, 8'b11100011, 8'b00000000); +assign id_sphl = cmp(i, 8'b11111001, 8'b00000000); +assign id_pchl = cmp(i, 8'b11101001, 8'b00000000); +assign id_xchg = cmp(i, 8'b11101011, 8'b00000000); +assign id_cxx = cmp(i, 8'b11xxx100, 8'b00111000); +assign id_jxx = cmp(i, 8'b11xxx010, 8'b00111000); +assign id_rxx = cmp(i, 8'b11xxx000, 8'b00111000); +assign id_ret = cmp(i, 8'b110x1001, 8'b00010000); +assign id_call = cmp(i, 8'b11xx1101, 8'b00110000); +assign id_eidi = cmp(i, 8'b1111x011, 8'b00001000); +assign id_jmp = cmp(i, 8'b1100x011, 8'b00001000); +assign id_io = cmp(i, 8'b1101x011, 8'b00001000); +assign id_opi = cmp(i, 8'b11xxx110, 8'b00111000); +assign id_in = cmp(i, 8'b11011011, 8'b00000000); +assign id_popsw = cmp(i, 8'b11110001, 8'b00000000); +assign id_out = cmp(i, 8'b11010011, 8'b00000000); +assign id_11x = cmp(i, 8'b11xxxxxx, 8'b00111111); +assign id_pupsw = cmp(i, 8'b11110101, 8'b00000000); + +assign id_rxc = ~i[5] & i[3] & id_opa; +assign id_sha = ~i[5] & id_opa; +assign id_rlc = (i[5:3] == 3'b000) & id_opa; +assign id_rar = (i[5:3] == 3'b011) & id_opa; +assign id_daa = (i[5:3] == 3'b100) & id_opa; +assign id_cma = (i[5:3] == 3'b101) & id_opa; +assign id_stc = (i[5:3] == 3'b110) & id_opa; +assign id_cmc = (i[5:3] == 3'b111) & id_opa; + +assign id_add = (i[5:3] == 3'b000) & (id_op | id_opi); +assign id_adc = (i[5:3] == 3'b001) & (id_op | id_opi); +assign id_sub = (i[5:3] == 3'b010) & (id_op | id_opi); +assign id_sbb = (i[5:3] == 3'b011) & (id_op | id_opi); +assign id_ana = (i[5:3] == 3'b100) & (id_op | id_opi); +assign id_xra = (i[5:3] == 3'b101) & (id_op | id_opi); +assign id_ora = (i[5:3] == 3'b110) & (id_op | id_opi); +assign id_cmp = (i[5:3] == 3'b111) & (id_op | id_opi); + +assign id80 = id_lxi | id_pop | id_opm | id_idm | id_dad + | id_xthl | id_xchg | id_jxx | id_ret | id_eidi + | id_nop | id_stlda | id_mvmr | id_mvrm | id_hlt + | id_opa | id_mvim | id_jmp | id_io | id_opi + | id_mvi | id_lsax | id_lhld | id_shld | id_op; +assign id81 = id_dcx | id_inx | id_sphl | id_pchl | id_xchg + | id_eidi | id_nop | id_opa | id_op | id_mov + | (id_idr & ~id82); +assign id82 = id_pop | id_push | id_opm | id_idm | id_dad + | id_rst | id_ret | id_rxx | id_mvrm | id_mvmr + | id_hlt | id_mvim | id_io | id_opi | id_mvi + | id_lsax; +assign id83 = id_opm | id_stlda | id_mvmr | id_mvrm | id_opi + | id_mvi | id_lsax; +assign id84 = id_lxi | id_jxx | id_jmp; +assign id85 = id_push | id_idm | id_rst | id_xthl | id_cxx + | id_call | id_mvim | id_shld | (id_io & ~i[3]); +assign id86 = id_push | id_rst | id_xthl | id_cxx | id_call + | id_mvmr | id_shld | (~i[3] & (id_lsax | id_stlda)); + +assign id00 = id_xthl | id_pchl | id_sphl; +assign id01 = id_pop | id_rxx | id_ret; +assign id02 = id_mvi | id_opi | id_io; +assign id03 = id_rst | id_push | id_xthl | id_cxx | id_call; +assign id04 = id_rst | id_push | id_xthl | id_cxx | id_call; +assign id05 = id_rst | id_push | id_xthl | id_cxx | id_call | id_dcx; +assign id06 = id_pop | id_rxx | id_ret | id_dad | id_lhld | id_io; +assign id07 = id_dcx | id_inx | id_lxi | id_dad; +assign id08 = id_mov | id_mvi | id_idr | id_op; +assign id09 = id_rst | id_push | id_xthl | id_cxx | id_call | id_shld; +assign id10 = id_pop | id_push | id_mvrm | id_mvi; + +//______________________________________________________________________________ +// +// function alu +// ( +// input rxc, +// input ora, +// input ana, +// input xra, +// input x, +// input r, +// input nc, +// input rn, +// input cp +// ); +// alu = x & r & cp & ~(rxc | ora | ana | xra) +// | nc & (cp | x | r) & ~(rxc | ora | ana | xra) +// | rxc & rn +// | ora & (x | r) +// | ana & (x & r) +// | xra & (x ^ r); +// endfunction +// +// +// assign s[0] = alu(id_rxc, id_ora, id_ana, id_xra, x[0], r[0], ~c[0], r[1], cl) | (id_rlc & c[7]); +// assign s[1] = alu(id_rxc, id_ora, id_ana, id_xra, x[1], r[1], ~c[1], r[2], c[0]); +// assign s[2] = alu(id_rxc, id_ora, id_ana, id_xra, x[2], r[2], ~c[2], r[3], c[1]); +// assign s[3] = alu(id_rxc, id_ora, id_ana, id_xra, x[3], r[3], ~c[3], r[4], c[2]); +// assign s[4] = alu(id_rxc, id_ora, id_ana, id_xra, x[4], r[4], ~c[4], r[5], c[3]); +// assign s[5] = alu(id_rxc, id_ora, id_ana, id_xra, x[5], r[5], ~c[5], r[6], c[4]); +// assign s[6] = alu(id_rxc, id_ora, id_ana, id_xra, x[6], r[6], ~c[6], r[7], c[5]); +// assign s[7] = alu(id_rxc, id_ora, id_ana, id_xra, x[7], r[7], ~c[7], ch, c[6]); +// +//______________________________________________________________________________ +// +// arithmetic and logic unit +// +// assign alu_xwr = (f1 & m1 & t3) | (f2 & (a327 | t4f1 & (id_out | ~id_11x))); +// +assign alu_xwr = (a327 | t4f1 & (id_rst | id_out | ~id_11x)); +assign alu_xout = ~(id_sub | id_sbb | id_cmp | id_cma); +assign alu_xrd = t1698 | a358; +assign x = alu_xout ? xr : ~xr; + +assign alu_ald = t2222 & ( id_adc | id_add | id_daa | id_xra | id_sbb + | id_sub | id_ana | id_ora | id_sha | id_cma); +assign alu_ard = t1375 | a398; +assign alu_awr = t1497 | a357; + +assign alu_r00 = id_dcr & t4f1; +assign alu_srd = t1668; +assign alu_rwr = t1780; +assign alu_rld = t4f1 & (id_sha | id_op | id_opi); + +assign daa = id_daa & t4f1; +assign daa_x6 = (acc[3] & (acc[2] | acc[1])) | psw_ac; +assign daa_6x = ((acc[3] & (acc[2] | acc[1])) & acc[4] & acc[7]) + | (acc[7] & (acc[6] | acc[5])) | tmp_c; + +assign s = {7'b0000000, id_rlc & c[7]} + | ((id_rxc | id_ora | id_ana | id_xra) ? 8'h00 : (x + r + cl)) + | (id_rxc ? {ch, r[7:1]} : 8'h00) + | (id_ora ? (x | r) : 8'h00) + | (id_ana ? (x & r) : 8'h00) + | (id_xra ? (x ^ r) : 8'h00); + +assign cl = tmp_c & ~id_daa & ~id_rlc & ~id_ora & ~id_xra & ~id_rxc; +assign ch = tmp_c & id_rar | r[0] & ~id_rar; + +// +// wire ca0_n, ca2_n, ca1, ca3; +// assign ca0_n = ~(cl & (x[0] | r[0])) & ~(x[0] & r[0]) & ~(id_ana & id_rxc); +// assign ca2_n = ~(ca1 & (x[2] | r[2])) & ~(x[2] & r[2]) & ~(id_ana & id_rxc); +// assign ca1 = ~(~x[1] & ~r[1]) & ~(ca0_n & (~x[1] | ~r[1])) & ~(id_ora | id_rxc | id_xra); +// assign ca3 = ~(~x[3] & ~r[3]) & ~(ca2_n & (~x[3] | ~r[3])) & ~(id_ora | id_rxc | id_xra); +// +assign c[0] = (r[0] & x[0]) | (cl & (r[0] | x[0])); +assign c[1] = (r[1] & x[1]) | (c[0] & (r[1] | x[1])); +assign c[2] = (r[2] & x[2]) | (c[1] & (r[2] | x[2])); +assign c[3] = (r[3] & x[3]) | (c[2] & (r[3] | x[3])); +assign c[4] = (r[4] & x[4]) | (c[3] & (r[4] | x[4])); +assign c[5] = (r[5] & x[5]) | (c[4] & (r[5] | x[5])); +assign c[6] = (r[6] & x[6]) | (c[5] & (r[6] | x[6])); +assign c[7] = (r[7] & x[7]) | (c[6] & (r[7] | x[7])); + +assign alu_zrd = m1f1 & t3f1; +assign alu_frd = t2046; /* | t4f1 & (id_11x & ~id_out); + // as we do need to translate flags on the bus for conditional unit anymore */ + +assign a398 = t1993 & ((t1994 & id08) | id_opa | id_stlda | id_lsax | id_io); + +always @(posedge clk) +begin + if (f1) + begin + t1375 <= t2 & m4 & id_pupsw; + t1497 <= t3 & m5 & id_popsw; + t1698 <= t5 & m1 & ~id_inr & ~id_dcr + | t3 & m5 & id_rst; + t1668 <= t2 & m5 & (id_inr | id_dcr) + | t3 & m5 & id_dad + | t3 & m4 & id_dad + | t5 & m1 & (id_inr | id_dcr); + t1780 <= t3 & m1 + | t1 & (m4 | m5) & id_dad; + t2222 <= (t2 & m1) | (t1 & m5); + a327 <= t3 & m4 & ~(id_dad | id_out | id_rst) + | t2 & (m4 | m5) & id_dad; + a357 <= t3 & m5 & (id_io | id_mvim) & sy_wo_n + | t3 & m4 & (id_stlda | id_lsax | id_mvmr) & sy_wo_n + | acc_sel & id08 & (t5 & m1 | t3 & m4); + a358 <= t2 & ~sy_wo_n & (id_io | id_mvim | id_stlda | id_lsax | id_mvmr); + + psw_ld <= t3 & m4 & id_popsw; + psw_wr <= t2 & m1 & (id_opi | id_inr | id_dcr | id_daa | id_op); + t2046 <= t2 & m5 & id_pupsw; /* | reset | t3 & m1; */ +// +// t2047 <= reset +// | t3 & m1 +// | t3 & m5 & id_rst; +// + t1993 <= t4 & m1; + t1994 <= acc_sel; + t2133 <= ~id_rxc & c[7]; + t2175 <= t3 & m1 + | t2 & m5 & id_dad; + end +end + +always @(posedge clk) +begin + if (f2) + begin + if (alu_xwr) xr <= id_rst ? (i & 8'b00111000) : d; + if (alu_awr) acc <= d; + if (alu_ald) acc <= s; + if (alu_rld) r <= acc; + if (alu_rwr) r <= d; + if (alu_r00) r <= 8'hff; + if (daa) + begin + r[1] <= daa_x6; + r[2] <= daa_x6; + r[5] <= daa_6x; + r[6] <= daa_6x; + end + if (psw_ld) + begin + psw_c <= d[0]; // x register was in original Intel design + psw_p <= d[2]; + psw_ac <= d[4]; + psw_z <= d[6]; + psw_s <= d[7]; + end + if (psw_wr) + begin + psw_p <= ~(^s); + psw_ac <= (c[3] & ~id_xra & ~id_ora & ~id_rxc) | (id_ana & (x[3] | r[3])); + psw_z <= ~(|s); + psw_s <= s[7]; + end + if (t2222) + begin + if (id_xra | id_stc | id_ora | id_ana | id_cmc) + psw_c <= ~tmp_c; + if (id_cmp | id_sbb | id_sub) + psw_c <= ~(t2133 | id_rxc & x[0]); + if (id_dad | id_sha | id_adc | id_add) + psw_c <= t2133 | id_rxc & x[0]; + end + if (daa & daa_6x) + psw_c <= 1'b1; + + if (t2175) + tmp_c <= psw_c; + if (t4f1) + begin + if (id_sbb) + tmp_c <= ~psw_c; + if (id_inr | id_ora | id_xra | id_ana | id_cmp | id_sub) + tmp_c <= 1'b1; + if (id_dad | id_cma | id_dcr | id_add | id_stc) + tmp_c <= 1'b0; + end + end +end + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/org/syn/de0/de0.sdc b/1801BM1_vm80a/org/syn/de0/de0.sdc new file mode 100644 index 0000000000000000000000000000000000000000..103e1b20163089721a533d5096670f6c62ae425e --- /dev/null +++ b/1801BM1_vm80a/org/syn/de0/de0.sdc @@ -0,0 +1,36 @@ +#************************************************************ +# THIS IS A WIZARD-GENERATED FILE. +# +# Version 12.1 Build 177 11/07/2012 SJ Full Version +# +#************************************************************ + +# Copyright (C) 1991-2012 Altera Corporation +# Your use of Altera Corporation's design tools, logic functions +# and other software and tools, and its AMPP partner logic +# functions, and any output files from any of the foregoing +# (including device programming or simulation files), and any +# associated documentation or information are expressly subject +# to the terms and conditions of the Altera Program License +# Subscription Agreement, Altera MegaCore Function License +# Agreement, or other applicable license agreement, including, +# without limitation, that your use is for the sole purpose of +# programming logic devices manufactured by Altera and sold by +# Altera or its authorized distributors. Please refer to the +# applicable agreement for further details. + + + +# Clock constraints + +create_clock -name "clk" -period 20.000ns [get_ports {de0_clock_50}] + + +# Automatically calculate clock uncertainty to jitter and other effects. +derive_clock_uncertainty + +# tsu/th constraints + +# tco constraints + +# tpd constraints diff --git a/1801BM1_vm80a/org/syn/de1/de1.sdc b/1801BM1_vm80a/org/syn/de1/de1.sdc new file mode 100644 index 0000000000000000000000000000000000000000..e70db904da67f5296cad8d3b90bd79c5c76454bc --- /dev/null +++ b/1801BM1_vm80a/org/syn/de1/de1.sdc @@ -0,0 +1,36 @@ +#************************************************************ +# THIS IS A WIZARD-GENERATED FILE. +# +# Version 12.1 Build 177 11/07/2012 SJ Full Version +# +#************************************************************ + +# Copyright (C) 1991-2012 Altera Corporation +# Your use of Altera Corporation's design tools, logic functions +# and other software and tools, and its AMPP partner logic +# functions, and any output files from any of the foregoing +# (including device programming or simulation files), and any +# associated documentation or information are expressly subject +# to the terms and conditions of the Altera Program License +# Subscription Agreement, Altera MegaCore Function License +# Agreement, or other applicable license agreement, including, +# without limitation, that your use is for the sole purpose of +# programming logic devices manufactured by Altera and sold by +# Altera or its authorized distributors. Please refer to the +# applicable agreement for further details. + + + +# Clock constraints + +create_clock -name "clk" -period 20.000ns [get_ports {de1_clock_50}] + + +# Automatically calculate clock uncertainty to jitter and other effects. +derive_clock_uncertainty + +# tsu/th constraints + +# tco constraints + +# tpd constraints diff --git a/1801BM1_vm80a/org/syn/de2-115/de2-115.sdc b/1801BM1_vm80a/org/syn/de2-115/de2-115.sdc new file mode 100644 index 0000000000000000000000000000000000000000..56dfe3064a57d8e62d21b3895dae20d0410e4f63 --- /dev/null +++ b/1801BM1_vm80a/org/syn/de2-115/de2-115.sdc @@ -0,0 +1,36 @@ +#************************************************************ +# THIS IS A WIZARD-GENERATED FILE. +# +# Version 12.1 Build 177 11/07/2012 SJ Full Version +# +#************************************************************ + +# Copyright (C) 1991-2012 Altera Corporation +# Your use of Altera Corporation's design tools, logic functions +# and other software and tools, and its AMPP partner logic +# functions, and any output files from any of the foregoing +# (including device programming or simulation files), and any +# associated documentation or information are expressly subject +# to the terms and conditions of the Altera Program License +# Subscription Agreement, Altera MegaCore Function License +# Agreement, or other applicable license agreement, including, +# without limitation, that your use is for the sole purpose of +# programming logic devices manufactured by Altera and sold by +# Altera or its authorized distributors. Please refer to the +# applicable agreement for further details. + + + +# Clock constraints + +create_clock -name "clk" -period 20.000ns [get_ports {de2_clock_50}] + + +# Automatically calculate clock uncertainty to jitter and other effects. +derive_clock_uncertainty + +# tsu/th constraints + +# tco constraints + +# tpd constraints diff --git a/1801BM1_vm80a/org/tbe/config.h b/1801BM1_vm80a/org/tbe/config.h new file mode 100644 index 0000000000000000000000000000000000000000..bdd18aab23e3c4cbd84f2c2aa20301a52bde62db --- /dev/null +++ b/1801BM1_vm80a/org/tbe/config.h @@ -0,0 +1,26 @@ +//______________________________________________________________________________ +// +// Simulation configuration parameters +// +`timescale 1ns / 100ps +// +// CAUTION: SIM_CONFIG_FAST_RESET should be undefined in release version +// Defining this parameter shorts the system reset time intervals and +// provides much quicker simulation +// +`define SIM_CONFIG_FAST_RESET 1 +// +// Simulation stops (breakpoint) after this time elapsed +// +`define SIM_CONFIG_TIME_LIMIT 2000000 +// +// External clock frequency +// +`define SIM_CONFIG_CLOCK_HPERIOD 10 + +// +// Generated F1/F2/pause phase cycles +// +`define SIM_CONFIG_F1 1 +`define SIM_CONFIG_F2 1 +`define SIM_CONFIG_F0 0 diff --git a/1801BM1_vm80a/org/tbe/tb80a.v b/1801BM1_vm80a/org/tbe/tb80a.v new file mode 100644 index 0000000000000000000000000000000000000000..948667bd00bf120df033552925a8ec740674e4d5 --- /dev/null +++ b/1801BM1_vm80a/org/tbe/tb80a.v @@ -0,0 +1,262 @@ +// +// Copyright (c) 2014 by 1801BM1@gmail.com +// Licensed under CC-BY 3.0 (https://creativecommons.org/licenses/by/3.0/) +// +//______________________________________________________________________________ +// +`include "config.h" + +//______________________________________________________________________________ +// +module memory +( + input [15:0] a, + input [7:0] din, + output reg [7:0] dout, + input read, + input write +); +reg [7:0] mem [0:16383]; +integer i; + +always @ (posedge read) +begin + dout = mem[a[13:0]]; +end + +always @ (negedge write) +begin + mem[a[13:0]] = din; + if (a >= 16'h4000) + begin + $display("Fault write @ %04X<-%02X", a, din); + $stop; + end +end + +always @ (read) +begin + if (a >= 16'h4000) + begin + $display("Fault read @ %04X", a); + $stop; + end +end + +initial +begin + for (i=0; i<16384; i = i + 1) + begin + mem[i] = 8'h00; + end + + $readmemh("..\\..\\..\\tst\\rom\\memini.bin", mem); +end +endmodule + +//______________________________________________________________________________ +// + +module tb80a(); +// +// 580BM80A pins +// +tri1 [7:0] d; +wire [7:0] d_in, d_sys; +reg [7:0] d_out, d_cyc; +wire d_oe; + +wire [15:0] a; +reg clk; +reg f1; +reg f2; +reg reset; +reg ready; +reg hold; +reg intr; + +wire inte; +wire hlda; +wire waitr; +wire sync; +wire dbin; +wire wr_n; + +integer i; +//______________________________________________________________________________ +// +assign d = d_oe ? d_sys : 8'hZZ; +assign d_sys = d_cyc[0] ? 8'hE7 : d_in; + +//_____________________________________________________________________________ +// +// Clock generator +// +initial +begin + clk = 1'b0; + f1 = 1'b0; + f2 = 1'b0; + forever + begin + f1 = 1'b1; + for (i=0; i<`SIM_CONFIG_F1; i = i + 1) + begin + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + end + f1 = 1'b0; + f2 = 1'b1; + for (i=0; i<`SIM_CONFIG_F2; i = i + 1) + begin + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + end + f2 = 1'b0; + for (i=0; i<`SIM_CONFIG_F0; i = i + 1) + begin + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + end + + /* + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + f1 = 1'b1; + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + f1 = 1'b0; + f2 = 1'b1; + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + ckl = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + f2 = 1'b0; + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + + clk = 1'b0; + #(`SIM_CONFIG_CLOCK_HPERIOD); + clk = 1'b1; + #(`SIM_CONFIG_CLOCK_HPERIOD); + */ + end +end + +// +// Simulation time limit (first breakpoint) +// +initial +begin + #`SIM_CONFIG_TIME_LIMIT $stop; +end + +memory mem(.a(a), .din(d), .dout(d_in), .read(dbin), .write(~wr_n)); + +// always @ (DBIN) d_in = a[7:0]; +always @ (posedge wr_n) d_out = d; +always @ (posedge sync) d_cyc = d; + +assign d_oe = dbin; +initial +begin + reset = 1; + intr = 0; + + #(`SIM_CONFIG_CLOCK_HPERIOD*2*9*6); + reset = 0; + + #(`SIM_CONFIG_CLOCK_HPERIOD*2*9*20); + intr = 1; + #(`SIM_CONFIG_CLOCK_HPERIOD*2*9*20); + intr = 0; +end + +initial +begin + ready = 1; + forever + begin + #(`SIM_CONFIG_CLOCK_HPERIOD*2*50); + ready = 0; + #(`SIM_CONFIG_CLOCK_HPERIOD*8); + ready = 1; + end +end + +initial +begin + hold = 0; + #(`SIM_CONFIG_CLOCK_HPERIOD*4); + forever + begin + #(`SIM_CONFIG_CLOCK_HPERIOD*2*500); + hold = 1; + #(`SIM_CONFIG_CLOCK_HPERIOD*80); + hold = 0; + end +end + +//_____________________________________________________________________________ +// +// Instantiation module under test +// +// +vm80a vm80a +( + .pin_clk(clk), + .pin_f1(f1), + .pin_f2(f2), + .pin_d(d), + .pin_a(a), + .pin_reset(reset), + .pin_hold(hold), + .pin_hlda(hlda), + .pin_ready(ready), + .pin_wait(waitr), + .pin_int(intr), + .pin_inte(inte), + .pin_sync(sync), + .pin_dbin(dbin), + .pin_wr_n(wr_n) +); +endmodule + diff --git a/1801BM1_vm80a/readme.md b/1801BM1_vm80a/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b9e90c28b3262a7e8c2ac7ba6406937dd4ba40b2 --- /dev/null +++ b/1801BM1_vm80a/readme.md @@ -0,0 +1,67 @@ +## Die photo + +![Die photo](/img/vm80a.jpg) + +Links to raw photos (please, note, files are LARGE): +- [Top metal, 11Kx10K, 95M](http://www.1801bm1.com/files/retro/580/images/580vm80a-2.jpg) +- [Top metal, 11Kx10K, 140M](http://www.1801bm1.com/files/retro/580/images/580vm80a-3.jpg) +- [Diffusion, 5.5Kx5K, 28M](http://www.1801bm1.com/files/retro/580/images/580vm80a-sil.jpg) + +## Abstract +The vm80a is the core built on the base of the revengineered real 580BM80A die. +The 580BM80A chip is the Soviet replica of early Intel i8080A microprocessor, +and these ones are very close topologically. + +The silicon techology parameters are: +- 5 micron scale +- one metal and one polycrystalline silicon layer +- NMOS schematics with depletion mode loads +- the extra high voltage source (+12V) is required +- high voltage direct clock phases (+12V) +- no built-in negative bias generator, extra negative voltage source is required + +The reversing was performed in the following stages: +- crystall decapsulation (with hot acid etching) +- taking the panorama shapshot of combined upper metal and polysilicon layers +- etching upper metal and polysilicon layers +- taking the panorama shapshot of diffusion layer with the prints of polysilicon layer +- vectorizing the photos in the SprintLayout editor +- transferring the topology to the PCAD-2004 pcb editor +- converting topology to PCAD-2004 schematics using the back annotation +- writing the Verilog code on the precise schematics base +- patching the code to eliminate the asynchronous nature of original circuits +- simulating and testing the resulting vm80a core on the real FPGAs +- thorough i8080 exerciser tests were passed successfully + +## Results +The project provides two i8080 models in Verilog - the one is pin-compatible with original +processor and other is refactored to be implemented within SoC and has the Wishbone interface. +Both approaches are proven on the real boards and FPGAs. +The models are compact and fast enough, the typical speed and area for Wishbone-featured model +on the DE0 board (Cyclone EP3C16F484C6): +- 104MHz clock, 607 LUTs and 187 flip-flops, no RAM blocks + +## Directory structure +#### \sch +- topology in Sprint Layout format +- topology in PCD-2004 pcb format +- schematics in PCD-2004 sch format +- schematics in [pdf](/sch/vm80a.pdf) (gate level) + +#### \org +- synchronous vm80a core, all original timings are kept intact, +includes the wrapper for usage as in-place-substitution of real i8080/580BM80A + +#### \wbc +- Wishbone compatible version of vm80a core, uses single clock, FPGA-optimized, +follows the original command execution timings + +#### \tst +- i8080 Exerciser test software and some other tests + +## Supported FPGA development boards: +- [Altera DE0](http://www.terasic.com.tw/cgi-bin/page/archive.pl?Language=English&No=364) +- [Altera DE1](http://www.terasic.com.tw/cgi-bin/page/archive.pl?Language=English&CategoryNo=53&No=83) +- [Altera DE2-115](http://www.terasic.com.tw/cgi-bin/page/archive.pl?Language=English&CategoryNo=139&No=502) +- [Alinx AX309](http://artofcircuits.com/product/alinx-ax309-spartan-6-fpga-development-board-xc6slx9-2ftg256c) + diff --git a/1801BM1_vm80a/wbc/rtl/de0/de0_mem.v b/1801BM1_vm80a/wbc/rtl/de0/de0_mem.v new file mode 100644 index 0000000000000000000000000000000000000000..35121a76c1ae53fe8156e7669c3ad131d2ee1a8c --- /dev/null +++ b/1801BM1_vm80a/wbc/rtl/de0/de0_mem.v @@ -0,0 +1,104 @@ +// megafunction wizard: %RAM: 1-PORT% +// GENERATION: STANDARD +// VERSION: WM1.0 +// MODULE: altsyncram + +// ============================================================ +// File Name: de0_mem.v +// Megafunction Name(s): +// altsyncram +// +// Simulation Library Files(s): +// altera_mf +// ============================================================ +// ************************************************************ +// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! +// +// 12.1 Build 177 11/07/2012 SJ Full Version +// ************************************************************ + + +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. + + +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module memini ( + address, + clock, + data, + wren, + q); + + input [13:0] address; + input clock; + input [7:0] data; + input wren; + output [7:0] q; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_off +`endif + tri1 clock; +`ifndef ALTERA_RESERVED_QIS +// synopsys translate_on +`endif + + wire [7:0] sub_wire0; + wire [7:0] q = sub_wire0[7:0]; + + altsyncram altsyncram_component ( + .address_a (address), + .clock0 (clock), + .data_a (data), + .wren_a (wren), + .q_a (sub_wire0), + .aclr0 (1'b0), + .aclr1 (1'b0), + .address_b (1'b1), + .addressstall_a (1'b0), + .addressstall_b (1'b0), + .byteena_a (1'b1), + .byteena_b (1'b1), + .clock1 (1'b1), + .clocken0 (1'b1), + .clocken1 (1'b1), + .clocken2 (1'b1), + .clocken3 (1'b1), + .data_b (1'b1), + .eccstatus (), + .q_b (), + .rden_a (1'b1), + .rden_b (1'b1), + .wren_b (1'b0)); + defparam + altsyncram_component.clock_enable_input_a = "BYPASS", + altsyncram_component.clock_enable_output_a = "BYPASS", + altsyncram_component.init_file = "../../../tst/rom/memini.mif", + altsyncram_component.intended_device_family = "Cyclone III", + altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO", + altsyncram_component.lpm_type = "altsyncram", + altsyncram_component.numwords_a = 16384, + altsyncram_component.operation_mode = "SINGLE_PORT", + altsyncram_component.outdata_aclr_a = "NONE", + altsyncram_component.outdata_reg_a = "UNREGISTERED", + altsyncram_component.power_up_uninitialized = "FALSE", + altsyncram_component.ram_block_type = "M9K", + altsyncram_component.read_during_write_mode_port_a = "DONT_CARE", + altsyncram_component.widthad_a = 14, + altsyncram_component.width_a = 8, + altsyncram_component.width_byteena_a = 1; + +endmodule diff --git a/1801BM1_vm80a/wbc/rtl/de0/de0_pll.v b/1801BM1_vm80a/wbc/rtl/de0/de0_pll.v new file mode 100644 index 0000000000000000000000000000000000000000..b49fbd6447eaefd509c536c0024be51fc7a386b7 --- /dev/null +++ b/1801BM1_vm80a/wbc/rtl/de0/de0_pll.v @@ -0,0 +1,636 @@ +// +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. +// +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module de0_pll50 ( + inclk0, + c0, + c1, + locked); + + input inclk0; + output c0; + output c1; + output locked; + + wire [4:0] sub_wire0; + wire sub_wire2; + wire [0:0] sub_wire6 = 1'h0; + wire [0:0] sub_wire3 = sub_wire0[0:0]; + wire [1:1] sub_wire1 = sub_wire0[1:1]; + wire c1 = sub_wire1; + wire locked = sub_wire2; + wire c0 = sub_wire3; + wire sub_wire4 = inclk0; + wire [1:0] sub_wire5 = {sub_wire6, sub_wire4}; + + altpll altpll_component ( + .inclk (sub_wire5), + .clk (sub_wire0), + .locked (sub_wire2), + .activeclock (), + .areset (1'b0), + .clkbad (), + .clkena ({6{1'b1}}), + .clkloss (), + .clkswitch (1'b0), + .configupdate (1'b0), + .enable0 (), + .enable1 (), + .extclk (), + .extclkena ({4{1'b1}}), + .fbin (1'b1), + .fbmimicbidir (), + .fbout (), + .fref (), + .icdrclk (), + .pfdena (1'b1), + .phasecounterselect ({4{1'b1}}), + .phasedone (), + .phasestep (1'b1), + .phaseupdown (1'b1), + .pllena (1'b1), + .scanaclr (1'b0), + .scanclk (1'b0), + .scanclkena (1'b1), + .scandata (1'b0), + .scandataout (), + .scandone (), + .scanread (1'b0), + .scanwrite (1'b0), + .sclkout0 (), + .sclkout1 (), + .vcooverrange (), + .vcounderrange ()); + defparam + altpll_component.bandwidth_type = "AUTO", + altpll_component.clk0_divide_by = 1, + altpll_component.clk0_duty_cycle = 50, + altpll_component.clk0_multiply_by = 1, + altpll_component.clk0_phase_shift = "0", + altpll_component.clk1_divide_by = 1, + altpll_component.clk1_duty_cycle = 50, + altpll_component.clk1_multiply_by = 1, + altpll_component.clk1_phase_shift = "10000", + altpll_component.compensate_clock = "CLK0", + altpll_component.inclk0_input_frequency = 20000, + altpll_component.intended_device_family = "Cyclone III", + altpll_component.lpm_hint = "CBX_MODULE_PREFIX=de0_pll50", + altpll_component.lpm_type = "altpll", + altpll_component.operation_mode = "NORMAL", + altpll_component.pll_type = "AUTO", + altpll_component.port_activeclock = "PORT_UNUSED", + altpll_component.port_areset = "PORT_UNUSED", + altpll_component.port_clkbad0 = "PORT_UNUSED", + altpll_component.port_clkbad1 = "PORT_UNUSED", + altpll_component.port_clkloss = "PORT_UNUSED", + altpll_component.port_clkswitch = "PORT_UNUSED", + altpll_component.port_configupdate = "PORT_UNUSED", + altpll_component.port_fbin = "PORT_UNUSED", + altpll_component.port_inclk0 = "PORT_USED", + altpll_component.port_inclk1 = "PORT_UNUSED", + altpll_component.port_locked = "PORT_USED", + altpll_component.port_pfdena = "PORT_UNUSED", + altpll_component.port_phasecounterselect = "PORT_UNUSED", + altpll_component.port_phasedone = "PORT_UNUSED", + altpll_component.port_phasestep = "PORT_UNUSED", + altpll_component.port_phaseupdown = "PORT_UNUSED", + altpll_component.port_pllena = "PORT_UNUSED", + altpll_component.port_scanaclr = "PORT_UNUSED", + altpll_component.port_scanclk = "PORT_UNUSED", + altpll_component.port_scanclkena = "PORT_UNUSED", + altpll_component.port_scandata = "PORT_UNUSED", + altpll_component.port_scandataout = "PORT_UNUSED", + altpll_component.port_scandone = "PORT_UNUSED", + altpll_component.port_scanread = "PORT_UNUSED", + altpll_component.port_scanwrite = "PORT_UNUSED", + altpll_component.port_clk0 = "PORT_USED", + altpll_component.port_clk1 = "PORT_USED", + altpll_component.port_clk2 = "PORT_UNUSED", + altpll_component.port_clk3 = "PORT_UNUSED", + altpll_component.port_clk4 = "PORT_UNUSED", + altpll_component.port_clk5 = "PORT_UNUSED", + altpll_component.port_clkena0 = "PORT_UNUSED", + altpll_component.port_clkena1 = "PORT_UNUSED", + altpll_component.port_clkena2 = "PORT_UNUSED", + altpll_component.port_clkena3 = "PORT_UNUSED", + altpll_component.port_clkena4 = "PORT_UNUSED", + altpll_component.port_clkena5 = "PORT_UNUSED", + altpll_component.port_extclk0 = "PORT_UNUSED", + altpll_component.port_extclk1 = "PORT_UNUSED", + altpll_component.port_extclk2 = "PORT_UNUSED", + altpll_component.port_extclk3 = "PORT_UNUSED", + altpll_component.self_reset_on_loss_lock = "ON", + altpll_component.width_clock = 5; + + +endmodule + +// ============================================================ +// CNX file retrieval info +// ============================================================ +// Retrieval info: PRIVATE: ACTIVECLK_CHECK STRING "0" +// Retrieval info: PRIVATE: BANDWIDTH STRING "1.000" +// Retrieval info: PRIVATE: BANDWIDTH_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: BANDWIDTH_FREQ_UNIT STRING "MHz" +// Retrieval info: PRIVATE: BANDWIDTH_PRESET STRING "Low" +// Retrieval info: PRIVATE: BANDWIDTH_USE_AUTO STRING "1" +// Retrieval info: PRIVATE: BANDWIDTH_USE_PRESET STRING "0" +// Retrieval info: PRIVATE: CLKBAD_SWITCHOVER_CHECK STRING "0" +// Retrieval info: PRIVATE: CLKLOSS_CHECK STRING "0" +// Retrieval info: PRIVATE: CLKSWITCH_CHECK STRING "0" +// Retrieval info: PRIVATE: CNX_NO_COMPENSATE_RADIO STRING "0" +// Retrieval info: PRIVATE: CREATE_CLKBAD_CHECK STRING "0" +// Retrieval info: PRIVATE: CREATE_INCLK1_CHECK STRING "0" +// Retrieval info: PRIVATE: CUR_DEDICATED_CLK STRING "c0" +// Retrieval info: PRIVATE: CUR_FBIN_CLK STRING "c0" +// Retrieval info: PRIVATE: DEVICE_SPEED_GRADE STRING "Any" +// Retrieval info: PRIVATE: DIV_FACTOR0 NUMERIC "1" +// Retrieval info: PRIVATE: DIV_FACTOR1 NUMERIC "1" +// Retrieval info: PRIVATE: DUTY_CYCLE0 STRING "50.00000000" +// Retrieval info: PRIVATE: DUTY_CYCLE1 STRING "50.00000000" +// Retrieval info: PRIVATE: EFF_OUTPUT_FREQ_VALUE0 STRING "50.000000" +// Retrieval info: PRIVATE: EFF_OUTPUT_FREQ_VALUE1 STRING "50.000000" +// Retrieval info: PRIVATE: EXPLICIT_SWITCHOVER_COUNTER STRING "0" +// Retrieval info: PRIVATE: EXT_FEEDBACK_RADIO STRING "0" +// Retrieval info: PRIVATE: GLOCKED_COUNTER_EDIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: GLOCKED_FEATURE_ENABLED STRING "0" +// Retrieval info: PRIVATE: GLOCKED_MODE_CHECK STRING "0" +// Retrieval info: PRIVATE: GLOCK_COUNTER_EDIT NUMERIC "1048575" +// Retrieval info: PRIVATE: HAS_MANUAL_SWITCHOVER STRING "1" +// Retrieval info: PRIVATE: INCLK0_FREQ_EDIT STRING "50.000" +// Retrieval info: PRIVATE: INCLK0_FREQ_UNIT_COMBO STRING "MHz" +// Retrieval info: PRIVATE: INCLK1_FREQ_EDIT STRING "100.000" +// Retrieval info: PRIVATE: INCLK1_FREQ_EDIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: INCLK1_FREQ_UNIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: INCLK1_FREQ_UNIT_COMBO STRING "MHz" +// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone III" +// Retrieval info: PRIVATE: INT_FEEDBACK__MODE_RADIO STRING "1" +// Retrieval info: PRIVATE: LOCKED_OUTPUT_CHECK STRING "1" +// Retrieval info: PRIVATE: LONG_SCAN_RADIO STRING "1" +// Retrieval info: PRIVATE: LVDS_MODE_DATA_RATE STRING "Not Available" +// Retrieval info: PRIVATE: LVDS_MODE_DATA_RATE_DIRTY NUMERIC "0" +// Retrieval info: PRIVATE: LVDS_PHASE_SHIFT_UNIT0 STRING "deg" +// Retrieval info: PRIVATE: LVDS_PHASE_SHIFT_UNIT1 STRING "deg" +// Retrieval info: PRIVATE: MIG_DEVICE_SPEED_GRADE STRING "Any" +// Retrieval info: PRIVATE: MIRROR_CLK0 STRING "0" +// Retrieval info: PRIVATE: MIRROR_CLK1 STRING "0" +// Retrieval info: PRIVATE: MULT_FACTOR0 NUMERIC "1" +// Retrieval info: PRIVATE: MULT_FACTOR1 NUMERIC "1" +// Retrieval info: PRIVATE: NORMAL_MODE_RADIO STRING "1" +// Retrieval info: PRIVATE: OUTPUT_FREQ0 STRING "100.00000000" +// Retrieval info: PRIVATE: OUTPUT_FREQ1 STRING "100.00000000" +// Retrieval info: PRIVATE: OUTPUT_FREQ_MODE0 STRING "0" +// Retrieval info: PRIVATE: OUTPUT_FREQ_MODE1 STRING "0" +// Retrieval info: PRIVATE: OUTPUT_FREQ_UNIT0 STRING "MHz" +// Retrieval info: PRIVATE: OUTPUT_FREQ_UNIT1 STRING "MHz" +// Retrieval info: PRIVATE: PHASE_RECONFIG_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: PHASE_RECONFIG_INPUTS_CHECK STRING "0" +// Retrieval info: PRIVATE: PHASE_SHIFT0 STRING "0.00000000" +// Retrieval info: PRIVATE: PHASE_SHIFT1 STRING "180.00000000" +// Retrieval info: PRIVATE: PHASE_SHIFT_STEP_ENABLED_CHECK STRING "0" +// Retrieval info: PRIVATE: PHASE_SHIFT_UNIT0 STRING "deg" +// Retrieval info: PRIVATE: PHASE_SHIFT_UNIT1 STRING "deg" +// Retrieval info: PRIVATE: PLL_ADVANCED_PARAM_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_ARESET_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_AUTOPLL_CHECK NUMERIC "1" +// Retrieval info: PRIVATE: PLL_ENHPLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_FASTPLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_FBMIMIC_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_LVDS_PLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_PFDENA_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_TARGET_HARCOPY_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PRIMARY_CLK_COMBO STRING "inclk0" +// Retrieval info: PRIVATE: RECONFIG_FILE STRING "de0_pll50" +// Retrieval info: PRIVATE: SACN_INPUTS_CHECK STRING "0" +// Retrieval info: PRIVATE: SCAN_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: SELF_RESET_LOCK_LOSS STRING "1" +// Retrieval info: PRIVATE: SHORT_SCAN_RADIO STRING "0" +// Retrieval info: PRIVATE: SPREAD_FEATURE_ENABLED STRING "0" +// Retrieval info: PRIVATE: SPREAD_FREQ STRING "50.000" +// Retrieval info: PRIVATE: SPREAD_FREQ_UNIT STRING "KHz" +// Retrieval info: PRIVATE: SPREAD_PERCENT STRING "0.500" +// Retrieval info: PRIVATE: SPREAD_USE STRING "0" +// Retrieval info: PRIVATE: SRC_SYNCH_COMP_RADIO STRING "0" +// Retrieval info: PRIVATE: STICKY_CLK0 STRING "1" +// Retrieval info: PRIVATE: STICKY_CLK1 STRING "1" +// Retrieval info: PRIVATE: SWITCHOVER_COUNT_EDIT NUMERIC "1" +// Retrieval info: PRIVATE: SWITCHOVER_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0" +// Retrieval info: PRIVATE: USE_CLK0 STRING "1" +// Retrieval info: PRIVATE: USE_CLK1 STRING "1" +// Retrieval info: PRIVATE: USE_CLKENA0 STRING "0" +// Retrieval info: PRIVATE: USE_CLKENA1 STRING "0" +// Retrieval info: PRIVATE: USE_MIL_SPEED_GRADE NUMERIC "0" +// Retrieval info: PRIVATE: ZERO_DELAY_RADIO STRING "0" +// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all +// Retrieval info: CONSTANT: BANDWIDTH_TYPE STRING "AUTO" +// Retrieval info: CONSTANT: CLK0_DIVIDE_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK0_DUTY_CYCLE NUMERIC "50" +// Retrieval info: CONSTANT: CLK0_MULTIPLY_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK0_PHASE_SHIFT STRING "0" +// Retrieval info: CONSTANT: CLK1_DIVIDE_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK1_DUTY_CYCLE NUMERIC "50" +// Retrieval info: CONSTANT: CLK1_MULTIPLY_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK1_PHASE_SHIFT STRING "10000" +// Retrieval info: CONSTANT: COMPENSATE_CLOCK STRING "CLK0" +// Retrieval info: CONSTANT: INCLK0_INPUT_FREQUENCY NUMERIC "20000" +// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Cyclone III" +// Retrieval info: CONSTANT: LPM_TYPE STRING "altpll" +// Retrieval info: CONSTANT: OPERATION_MODE STRING "NORMAL" +// Retrieval info: CONSTANT: PLL_TYPE STRING "AUTO" +// Retrieval info: CONSTANT: PORT_ACTIVECLOCK STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_ARESET STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKBAD0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKBAD1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKLOSS STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKSWITCH STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CONFIGUPDATE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_FBIN STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_INCLK0 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_INCLK1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_LOCKED STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_PFDENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASECOUNTERSELECT STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASEDONE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASESTEP STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASEUPDOWN STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PLLENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANACLR STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANCLK STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANCLKENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDATA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDATAOUT STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDONE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANREAD STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANWRITE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk0 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_clk1 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_clk2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk4 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk5 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena4 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena5 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: SELF_RESET_ON_LOSS_LOCK STRING "ON" +// Retrieval info: CONSTANT: WIDTH_CLOCK NUMERIC "5" +// Retrieval info: USED_PORT: @clk 0 0 5 0 OUTPUT_CLK_EXT VCC "@clk[4..0]" +// Retrieval info: USED_PORT: c0 0 0 0 0 OUTPUT_CLK_EXT VCC "c0" +// Retrieval info: USED_PORT: c1 0 0 0 0 OUTPUT_CLK_EXT VCC "c1" +// Retrieval info: USED_PORT: inclk0 0 0 0 0 INPUT_CLK_EXT GND "inclk0" +// Retrieval info: USED_PORT: locked 0 0 0 0 OUTPUT GND "locked" +// Retrieval info: CONNECT: @inclk 0 0 1 1 GND 0 0 0 0 +// Retrieval info: CONNECT: @inclk 0 0 1 0 inclk0 0 0 0 0 +// Retrieval info: CONNECT: c0 0 0 0 0 @clk 0 0 1 0 +// Retrieval info: CONNECT: c1 0 0 0 0 @clk 0 0 1 1 +// Retrieval info: CONNECT: locked 0 0 0 0 @locked 0 0 0 0 +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50.v TRUE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50.ppf TRUE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50.inc FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50.cmp FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50.bsf FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50_inst.v FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll50_bb.v TRUE +// Retrieval info: LIB_FILE: altera_mf +// Retrieval info: CBX_MODULE_PREFIX: ON + + +//Copyright (C) 1991-2012 Altera Corporation +//Your use of Altera Corporation's design tools, logic functions +//and other software and tools, and its AMPP partner logic +//functions, and any output files from any of the foregoing +//(including device programming or simulation files), and any +//associated documentation or information are expressly subject +//to the terms and conditions of the Altera Program License +//Subscription Agreement, Altera MegaCore Function License +//Agreement, or other applicable license agreement, including, +//without limitation, that your use is for the sole purpose of +//programming logic devices manufactured by Altera and sold by +//Altera or its authorized distributors. Please refer to the +//applicable agreement for further details. + + +// synopsys translate_off +`timescale 1 ps / 1 ps +// synopsys translate_on +module de0_pll100 ( + inclk0, + c0, + c1, + locked); + + input inclk0; + output c0; + output c1; + output locked; + + wire [4:0] sub_wire0; + wire sub_wire2; + wire [0:0] sub_wire6 = 1'h0; + wire [0:0] sub_wire3 = sub_wire0[0:0]; + wire [1:1] sub_wire1 = sub_wire0[1:1]; + wire c1 = sub_wire1; + wire locked = sub_wire2; + wire c0 = sub_wire3; + wire sub_wire4 = inclk0; + wire [1:0] sub_wire5 = {sub_wire6, sub_wire4}; + + altpll altpll_component ( + .inclk (sub_wire5), + .clk (sub_wire0), + .locked (sub_wire2), + .activeclock (), + .areset (1'b0), + .clkbad (), + .clkena ({6{1'b1}}), + .clkloss (), + .clkswitch (1'b0), + .configupdate (1'b0), + .enable0 (), + .enable1 (), + .extclk (), + .extclkena ({4{1'b1}}), + .fbin (1'b1), + .fbmimicbidir (), + .fbout (), + .fref (), + .icdrclk (), + .pfdena (1'b1), + .phasecounterselect ({4{1'b1}}), + .phasedone (), + .phasestep (1'b1), + .phaseupdown (1'b1), + .pllena (1'b1), + .scanaclr (1'b0), + .scanclk (1'b0), + .scanclkena (1'b1), + .scandata (1'b0), + .scandataout (), + .scandone (), + .scanread (1'b0), + .scanwrite (1'b0), + .sclkout0 (), + .sclkout1 (), + .vcooverrange (), + .vcounderrange ()); + defparam + altpll_component.bandwidth_type = "AUTO", + altpll_component.clk0_divide_by = 1, + altpll_component.clk0_duty_cycle = 50, + altpll_component.clk0_multiply_by = 2, + altpll_component.clk0_phase_shift = "0", + altpll_component.clk1_divide_by = 1, + altpll_component.clk1_duty_cycle = 50, + altpll_component.clk1_multiply_by = 2, + altpll_component.clk1_phase_shift = "5000", + altpll_component.compensate_clock = "CLK0", + altpll_component.inclk0_input_frequency = 20000, + altpll_component.intended_device_family = "Cyclone III", + altpll_component.lpm_hint = "CBX_MODULE_PREFIX=de0_pll100", + altpll_component.lpm_type = "altpll", + altpll_component.operation_mode = "NORMAL", + altpll_component.pll_type = "AUTO", + altpll_component.port_activeclock = "PORT_UNUSED", + altpll_component.port_areset = "PORT_UNUSED", + altpll_component.port_clkbad0 = "PORT_UNUSED", + altpll_component.port_clkbad1 = "PORT_UNUSED", + altpll_component.port_clkloss = "PORT_UNUSED", + altpll_component.port_clkswitch = "PORT_UNUSED", + altpll_component.port_configupdate = "PORT_UNUSED", + altpll_component.port_fbin = "PORT_UNUSED", + altpll_component.port_inclk0 = "PORT_USED", + altpll_component.port_inclk1 = "PORT_UNUSED", + altpll_component.port_locked = "PORT_USED", + altpll_component.port_pfdena = "PORT_UNUSED", + altpll_component.port_phasecounterselect = "PORT_UNUSED", + altpll_component.port_phasedone = "PORT_UNUSED", + altpll_component.port_phasestep = "PORT_UNUSED", + altpll_component.port_phaseupdown = "PORT_UNUSED", + altpll_component.port_pllena = "PORT_UNUSED", + altpll_component.port_scanaclr = "PORT_UNUSED", + altpll_component.port_scanclk = "PORT_UNUSED", + altpll_component.port_scanclkena = "PORT_UNUSED", + altpll_component.port_scandata = "PORT_UNUSED", + altpll_component.port_scandataout = "PORT_UNUSED", + altpll_component.port_scandone = "PORT_UNUSED", + altpll_component.port_scanread = "PORT_UNUSED", + altpll_component.port_scanwrite = "PORT_UNUSED", + altpll_component.port_clk0 = "PORT_USED", + altpll_component.port_clk1 = "PORT_USED", + altpll_component.port_clk2 = "PORT_UNUSED", + altpll_component.port_clk3 = "PORT_UNUSED", + altpll_component.port_clk4 = "PORT_UNUSED", + altpll_component.port_clk5 = "PORT_UNUSED", + altpll_component.port_clkena0 = "PORT_UNUSED", + altpll_component.port_clkena1 = "PORT_UNUSED", + altpll_component.port_clkena2 = "PORT_UNUSED", + altpll_component.port_clkena3 = "PORT_UNUSED", + altpll_component.port_clkena4 = "PORT_UNUSED", + altpll_component.port_clkena5 = "PORT_UNUSED", + altpll_component.port_extclk0 = "PORT_UNUSED", + altpll_component.port_extclk1 = "PORT_UNUSED", + altpll_component.port_extclk2 = "PORT_UNUSED", + altpll_component.port_extclk3 = "PORT_UNUSED", + altpll_component.self_reset_on_loss_lock = "OFF", + altpll_component.width_clock = 5; + + +endmodule + +// ============================================================ +// CNX file retrieval info +// ============================================================ +// Retrieval info: PRIVATE: ACTIVECLK_CHECK STRING "0" +// Retrieval info: PRIVATE: BANDWIDTH STRING "1.000" +// Retrieval info: PRIVATE: BANDWIDTH_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: BANDWIDTH_FREQ_UNIT STRING "MHz" +// Retrieval info: PRIVATE: BANDWIDTH_PRESET STRING "Low" +// Retrieval info: PRIVATE: BANDWIDTH_USE_AUTO STRING "1" +// Retrieval info: PRIVATE: BANDWIDTH_USE_PRESET STRING "0" +// Retrieval info: PRIVATE: CLKBAD_SWITCHOVER_CHECK STRING "0" +// Retrieval info: PRIVATE: CLKLOSS_CHECK STRING "0" +// Retrieval info: PRIVATE: CLKSWITCH_CHECK STRING "0" +// Retrieval info: PRIVATE: CNX_NO_COMPENSATE_RADIO STRING "0" +// Retrieval info: PRIVATE: CREATE_CLKBAD_CHECK STRING "0" +// Retrieval info: PRIVATE: CREATE_INCLK1_CHECK STRING "0" +// Retrieval info: PRIVATE: CUR_DEDICATED_CLK STRING "c0" +// Retrieval info: PRIVATE: CUR_FBIN_CLK STRING "c0" +// Retrieval info: PRIVATE: DEVICE_SPEED_GRADE STRING "8" +// Retrieval info: PRIVATE: DIV_FACTOR0 NUMERIC "2" +// Retrieval info: PRIVATE: DIV_FACTOR1 NUMERIC "2" +// Retrieval info: PRIVATE: DUTY_CYCLE0 STRING "50.00000000" +// Retrieval info: PRIVATE: DUTY_CYCLE1 STRING "50.00000000" +// Retrieval info: PRIVATE: EFF_OUTPUT_FREQ_VALUE0 STRING "100.000000" +// Retrieval info: PRIVATE: EFF_OUTPUT_FREQ_VALUE1 STRING "100.000000" +// Retrieval info: PRIVATE: EXPLICIT_SWITCHOVER_COUNTER STRING "0" +// Retrieval info: PRIVATE: EXT_FEEDBACK_RADIO STRING "0" +// Retrieval info: PRIVATE: GLOCKED_COUNTER_EDIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: GLOCKED_FEATURE_ENABLED STRING "0" +// Retrieval info: PRIVATE: GLOCKED_MODE_CHECK STRING "0" +// Retrieval info: PRIVATE: GLOCK_COUNTER_EDIT NUMERIC "1048575" +// Retrieval info: PRIVATE: HAS_MANUAL_SWITCHOVER STRING "1" +// Retrieval info: PRIVATE: INCLK0_FREQ_EDIT STRING "50.000" +// Retrieval info: PRIVATE: INCLK0_FREQ_UNIT_COMBO STRING "MHz" +// Retrieval info: PRIVATE: INCLK1_FREQ_EDIT STRING "100.000" +// Retrieval info: PRIVATE: INCLK1_FREQ_EDIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: INCLK1_FREQ_UNIT_CHANGED STRING "1" +// Retrieval info: PRIVATE: INCLK1_FREQ_UNIT_COMBO STRING "MHz" +// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone III" +// Retrieval info: PRIVATE: INT_FEEDBACK__MODE_RADIO STRING "1" +// Retrieval info: PRIVATE: LOCKED_OUTPUT_CHECK STRING "1" +// Retrieval info: PRIVATE: LONG_SCAN_RADIO STRING "1" +// Retrieval info: PRIVATE: LVDS_MODE_DATA_RATE STRING "Not Available" +// Retrieval info: PRIVATE: LVDS_MODE_DATA_RATE_DIRTY NUMERIC "0" +// Retrieval info: PRIVATE: LVDS_PHASE_SHIFT_UNIT0 STRING "deg" +// Retrieval info: PRIVATE: LVDS_PHASE_SHIFT_UNIT1 STRING "deg" +// Retrieval info: PRIVATE: MIG_DEVICE_SPEED_GRADE STRING "Any" +// Retrieval info: PRIVATE: MIRROR_CLK0 STRING "0" +// Retrieval info: PRIVATE: MIRROR_CLK1 STRING "0" +// Retrieval info: PRIVATE: MULT_FACTOR0 NUMERIC "4" +// Retrieval info: PRIVATE: MULT_FACTOR1 NUMERIC "4" +// Retrieval info: PRIVATE: NORMAL_MODE_RADIO STRING "1" +// Retrieval info: PRIVATE: OUTPUT_FREQ0 STRING "100.00000000" +// Retrieval info: PRIVATE: OUTPUT_FREQ1 STRING "100.00000000" +// Retrieval info: PRIVATE: OUTPUT_FREQ_MODE0 STRING "0" +// Retrieval info: PRIVATE: OUTPUT_FREQ_MODE1 STRING "0" +// Retrieval info: PRIVATE: OUTPUT_FREQ_UNIT0 STRING "MHz" +// Retrieval info: PRIVATE: OUTPUT_FREQ_UNIT1 STRING "MHz" +// Retrieval info: PRIVATE: PHASE_RECONFIG_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: PHASE_RECONFIG_INPUTS_CHECK STRING "0" +// Retrieval info: PRIVATE: PHASE_SHIFT0 STRING "0.00000000" +// Retrieval info: PRIVATE: PHASE_SHIFT1 STRING "180.00000000" +// Retrieval info: PRIVATE: PHASE_SHIFT_STEP_ENABLED_CHECK STRING "0" +// Retrieval info: PRIVATE: PHASE_SHIFT_UNIT0 STRING "deg" +// Retrieval info: PRIVATE: PHASE_SHIFT_UNIT1 STRING "deg" +// Retrieval info: PRIVATE: PLL_ADVANCED_PARAM_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_ARESET_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_AUTOPLL_CHECK NUMERIC "1" +// Retrieval info: PRIVATE: PLL_ENHPLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_FASTPLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_FBMIMIC_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_LVDS_PLL_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PLL_PFDENA_CHECK STRING "0" +// Retrieval info: PRIVATE: PLL_TARGET_HARCOPY_CHECK NUMERIC "0" +// Retrieval info: PRIVATE: PRIMARY_CLK_COMBO STRING "inclk0" +// Retrieval info: PRIVATE: RECONFIG_FILE STRING "de0_pll100.mif" +// Retrieval info: PRIVATE: SACN_INPUTS_CHECK STRING "0" +// Retrieval info: PRIVATE: SCAN_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: SELF_RESET_LOCK_LOSS STRING "0" +// Retrieval info: PRIVATE: SHORT_SCAN_RADIO STRING "0" +// Retrieval info: PRIVATE: SPREAD_FEATURE_ENABLED STRING "0" +// Retrieval info: PRIVATE: SPREAD_FREQ STRING "50.000" +// Retrieval info: PRIVATE: SPREAD_FREQ_UNIT STRING "KHz" +// Retrieval info: PRIVATE: SPREAD_PERCENT STRING "0.500" +// Retrieval info: PRIVATE: SPREAD_USE STRING "0" +// Retrieval info: PRIVATE: SRC_SYNCH_COMP_RADIO STRING "0" +// Retrieval info: PRIVATE: STICKY_CLK0 STRING "1" +// Retrieval info: PRIVATE: STICKY_CLK1 STRING "1" +// Retrieval info: PRIVATE: SWITCHOVER_COUNT_EDIT NUMERIC "1" +// Retrieval info: PRIVATE: SWITCHOVER_FEATURE_ENABLED STRING "1" +// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0" +// Retrieval info: PRIVATE: USE_CLK0 STRING "1" +// Retrieval info: PRIVATE: USE_CLK1 STRING "1" +// Retrieval info: PRIVATE: USE_CLKENA0 STRING "0" +// Retrieval info: PRIVATE: USE_CLKENA1 STRING "0" +// Retrieval info: PRIVATE: USE_MIL_SPEED_GRADE NUMERIC "0" +// Retrieval info: PRIVATE: ZERO_DELAY_RADIO STRING "0" +// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all +// Retrieval info: CONSTANT: BANDWIDTH_TYPE STRING "AUTO" +// Retrieval info: CONSTANT: CLK0_DIVIDE_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK0_DUTY_CYCLE NUMERIC "50" +// Retrieval info: CONSTANT: CLK0_MULTIPLY_BY NUMERIC "2" +// Retrieval info: CONSTANT: CLK0_PHASE_SHIFT STRING "0" +// Retrieval info: CONSTANT: CLK1_DIVIDE_BY NUMERIC "1" +// Retrieval info: CONSTANT: CLK1_DUTY_CYCLE NUMERIC "50" +// Retrieval info: CONSTANT: CLK1_MULTIPLY_BY NUMERIC "2" +// Retrieval info: CONSTANT: CLK1_PHASE_SHIFT STRING "5000" +// Retrieval info: CONSTANT: COMPENSATE_CLOCK STRING "CLK0" +// Retrieval info: CONSTANT: INCLK0_INPUT_FREQUENCY NUMERIC "20000" +// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Cyclone III" +// Retrieval info: CONSTANT: LPM_TYPE STRING "altpll" +// Retrieval info: CONSTANT: OPERATION_MODE STRING "NORMAL" +// Retrieval info: CONSTANT: PLL_TYPE STRING "AUTO" +// Retrieval info: CONSTANT: PORT_ACTIVECLOCK STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_ARESET STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKBAD0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKBAD1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKLOSS STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CLKSWITCH STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_CONFIGUPDATE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_FBIN STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_INCLK0 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_INCLK1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_LOCKED STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_PFDENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASECOUNTERSELECT STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASEDONE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASESTEP STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PHASEUPDOWN STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_PLLENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANACLR STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANCLK STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANCLKENA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDATA STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDATAOUT STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANDONE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANREAD STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_SCANWRITE STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk0 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_clk1 STRING "PORT_USED" +// Retrieval info: CONSTANT: PORT_clk2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk4 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clk5 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena4 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_clkena5 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk0 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk1 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk2 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: PORT_extclk3 STRING "PORT_UNUSED" +// Retrieval info: CONSTANT: SELF_RESET_ON_LOSS_LOCK STRING "OFF" +// Retrieval info: CONSTANT: WIDTH_CLOCK NUMERIC "5" +// Retrieval info: USED_PORT: @clk 0 0 5 0 OUTPUT_CLK_EXT VCC "@clk[4..0]" +// Retrieval info: USED_PORT: c0 0 0 0 0 OUTPUT_CLK_EXT VCC "c0" +// Retrieval info: USED_PORT: c1 0 0 0 0 OUTPUT_CLK_EXT VCC "c1" +// Retrieval info: USED_PORT: inclk0 0 0 0 0 INPUT_CLK_EXT GND "inclk0" +// Retrieval info: USED_PORT: locked 0 0 0 0 OUTPUT GND "locked" +// Retrieval info: CONNECT: @inclk 0 0 1 1 GND 0 0 0 0 +// Retrieval info: CONNECT: @inclk 0 0 1 0 inclk0 0 0 0 0 +// Retrieval info: CONNECT: c0 0 0 0 0 @clk 0 0 1 0 +// Retrieval info: CONNECT: c1 0 0 0 0 @clk 0 0 1 1 +// Retrieval info: CONNECT: locked 0 0 0 0 @locked 0 0 0 0 +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100.v TRUE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100.ppf TRUE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100.inc FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100.cmp FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100.bsf FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100_inst.v FALSE +// Retrieval info: GEN_FILE: TYPE_NORMAL de0_pll100_bb.v TRUE +// Retrieval info: LIB_FILE: altera_mf +// Retrieval info: CBX_MODULE_PREFIX: ON diff --git a/1801BM1_vm80a/wbc/rtl/de0/de0_top.v b/1801BM1_vm80a/wbc/rtl/de0/de0_top.v new file mode 100644 index 0000000000000000000000000000000000000000..2b1103d27327a3c9b42065d1fa5a4bad4b537a5c --- /dev/null +++ b/1801BM1_vm80a/wbc/rtl/de0/de0_top.v @@ -0,0 +1,503 @@ +//______________________________________________________________________________ +// +// Top module for DE0 board based system + +//______________________________________________________________________________ +// +// External oscillator clock, feeds the PLLs +// +`define OSC_CLOCK 50000000 +// +// Global system clock +// +//`define SYS_CLOCK 50000000 +`define SYS_CLOCK 100000000 +// +// Console baudrate +// +`define SYS_BAUD 115200 +// +// Retro clock for non-turbo clock mode +// +`define CPU_CLOCK 2500000 + +//______________________________________________________________________________ +// +// Reset button debounce interval (in ms)) +// +`define RESET_BUTTON_DEBOUNCE_MS 5 +// +// Internal reset pulse width (in system clocks) +// +`define RESET_PULSE_WIDTH_CLK 7 + +//______________________________________________________________________________ +// +// Provides the 1 microseconds and 1 milliseconds strobes +// +module de0_timer #(parameter REFCLK=100000000, CPUCLK=2500000) +( + input clk, + input rst, + output reg ena_f2, + output reg ena_us, + output reg ena_ms, + output reg irq_50 +); +localparam F2_COUNTER_WIDTH = log2(REFCLK/CPUCLK); +localparam US_COUNTER_WIDTH = log2(REFCLK/1000000); +localparam MS_COUNTER_WIDTH = log2(1000); + +reg [F2_COUNTER_WIDTH-1:0] count_f2; +reg [US_COUNTER_WIDTH-1:0] count_us; +reg [MS_COUNTER_WIDTH-1:0] count_ms; +reg [4:0] count_50; + +always @(posedge clk, posedge rst) +begin + if (rst) + begin + ena_f2 <= 1'b0; + ena_us <= 1'b0; + ena_ms <= 1'b0; + count_f2 <= 0; + count_us <= 0; + count_ms <= 980; + count_50 <= 0; + end + else + begin + // + // F2 retro clock interval counter + // (use this simpler inmplementation, + // but the phase accumulator is better + // if more precise CPU clock desired) + // + if (count_f2 == ((REFCLK/CPUCLK)-1)) + begin + ena_f2 <= 1'b1; + count_f2 <= 0; + end + else + begin + ena_f2 <= 1'b0; + count_f2 <= count_f2 + 1'b1; + end + // + // One microsecond interval counter + // + if (count_us == ((REFCLK/1000000)-1)) + begin + ena_us <= 1'b1; + count_us <= 0; + end + else + begin + ena_us <= 1'b0; + count_us <= count_us + 1'b1; + end + // + // One millisecond interval counter + // + if (ena_us) + if (count_ms == (1000-1)) + begin + ena_ms <= 1'b1; + count_ms <= 0; + end + else + begin + ena_ms <= 1'b0; + count_ms <= count_ms + 1'b1; + end + else + ena_ms <= 1'b0; + // + // 50Hz timer output + // + if (ena_ms) + if (count_50 == 19) + begin + irq_50 <= 1'b0; + count_50 <= 0; + end + else + begin + if (count_50 == 9) + irq_50 <= 1'b1; + + count_50 <= count_50 + 1'b1; + end + end +end + +function integer log2(input integer value); + begin + for (log2=0; value>0; log2=log2+1) + value = value >> 1; + end +endfunction +endmodule + +//______________________________________________________________________________ +// +// Initialized RAM block - 16K x 8 +// +module mem_wb +( + input wb_clk_i, + input [13:0] wb_adr_i, + input [7:0] wb_dat_i, + output [7:0] wb_dat_o, + input wb_cyc_i, + input wb_we_i, + input wb_stb_i, + output wb_ack_o +); +reg ack; + +memini ram +( + .clock(wb_clk_i), + .address(wb_adr_i[13:0]), + .wren(wb_we_i & wb_cyc_i & wb_stb_i), + .data(wb_dat_i), + .q(wb_dat_o) +); + +assign wb_ack_o = wb_cyc_i & wb_stb_i & (ack | wb_we_i); +always @ (posedge wb_clk_i) ack <= wb_cyc_i; +endmodule + +//______________________________________________________________________________ +// +// Top project module - instantiates the DE0 board itself +// +module de0 +( + input de0_clock_50, // clock input 50 MHz + input de0_clock_50_2, // clock input 50 MHz + // + input [2:0] de0_button, // push button[2:0] + // + input [9:0] de0_sw, // DPDT toggle switch[9:0] + output [7:0] de0_hex0, // seven segment digit 0 + output [7:0] de0_hex1, // seven segment digit 1 + output [7:0] de0_hex2, // seven segment digit 2 + output [7:0] de0_hex3, // seven segment digit 3 + output [9:0] de0_led, // LED green[9:0] + // + output de0_uart_txd, // UART transmitter + input de0_uart_rxd, // UART receiver + output de0_uart_cts, // UART clear to send + input de0_uart_rts, // UART request to send + // + inout [15:0] de0_dram_dq, // SDRAM data bus 16 bits + output [12:0] de0_dram_addr, // SDRAM address bus 13 bits + output de0_dram_ldqm, // SDRAM low-byte data mask + output de0_dram_udqm, // SDRAM high-byte data mask + output de0_dram_we_n, // SDRAM write enable + output de0_dram_cas_n, // SDRAM column address strobe + output de0_dram_ras_n, // SDRAM row address strobe + output de0_dram_cs_n, // SDRAM chip select + output [1:0] de0_dram_ba, // SDRAM bank address + output de0_dram_clk, // SDRAM clock + output de0_dram_cke, // SDRAM clock enable + // + inout [15:0] de0_fl_dq, // FLASH data bus 15 Bits + output [21:0] de0_fl_addr, // FLASH address bus 22 Bits + output de0_fl_we_n, // FLASH write enable + output de0_fl_rst_n, // FLASH reset + output de0_fl_oe_n, // FLASH output enable + output de0_fl_ce_n, // FLASH chip enable + output de0_fl_wp_n, // FLASH hardware write protect + output de0_fl_byte_n, // FLASH selects 8/16-bit mode + input de0_fl_rb, // FLASH ready/busy + // + output de0_lcd_blig, // LCD back light ON/OFF + output de0_lcd_rw, // LCD read/write select, 0 = write, 1 = read + output de0_lcd_en, // LCD enable + output de0_lcd_rs, // LCD command/data select, 0 = command, 1 = data + inout [7:0] de0_lcd_data, // LCD data bus 8 bits + // + inout de0_sd_mosi, // SD Card Data Output + inout de0_sd_miso, // SD Card Data Input + inout de0_sd_cmd, // SD Card Command Signal + output de0_sd_clk, // SD Card Clock + input de0_sd_wp_n, // SD Card Write Protect + // + inout de0_ps2_kbdat, // PS2 Keyboard Data + inout de0_ps2_kbclk, // PS2 Keyboard Clock + inout de0_ps2_msdat, // PS2 Mouse Data + inout de0_ps2_msclk, // PS2 Mouse Clock + // + output de0_vga_hs, // VGA H_SYNC + output de0_vga_vs, // VGA V_SYNC + output [3:0] de0_vga_r, // VGA Red[3:0] + output [3:0] de0_vga_g, // VGA Green[3:0] + output [3:0] de0_vga_b, // VGA Blue[3:0] + // + input [1:0] de0_gpio0_clkin, // GPIO Connection 0 Clock In Bus + output [1:0] de0_gpio0_clkout, // GPIO Connection 0 Clock Out Bus + inout [31:0] de0_gpio0_d, // GPIO Connection 0 Data Bus + // + input [1:0] de0_gpio1_clkin, // GPIO Connection 1 Clock In Bus + output [1:0] de0_gpio1_clkout, // GPIO Connection 1 Clock Out Bus + inout [31:0] de0_gpio1_d // GPIO Connection 1 Data Bus +); + +//______________________________________________________________________________ +// +wire [31:0] baud = 921600/`SYS_BAUD-1; +wire clk50, pll_clk, pll_lock, ena_us, ena_ms, ena_f2; +reg vm_turbo; + +wire wb_rst; // +wire wb_clk; // +wire [15:0] wb_adr; // master address out bus +wire [7:0] wb_out; // master data out bus +wire [7:0] wb_mux; // master data in bus +wire wb_cyc; // master wishbone cycle +wire wb_we; // master wishbone direction +wire wb_stb; // master wishbone strobe +wire wb_ack; // master wishbone acknowledgement +wire [5:0] wb_tag; // 8080 tags + // +wire [3:0] mx_stb; // +wire [3:0] mx_ack; // system wishbone data mux +wire [7:0] mx_dat[3:0]; // + // +reg [7:0] hex0, hex1, hex2, hex3; +reg [7:0] led; +reg [7:0] rcnt = 8'h00; +reg vm_irq; +wire vm_inte; +wire vm_cena; + +//______________________________________________________________________________ +// +// Clock and Reset section +// +assign wb_clk = pll_clk; +assign clk50 = de0_clock_50_2; +assign wb_rst = ~(rcnt == 8'hFF); +assign vm_cena = 1'b1; // vm_turbo | ena_f2; + +de0_pll100 corepll +( + .inclk0(clk50), + .c0(pll_clk), + .locked(pll_lock) +); + +always @(posedge wb_clk) +begin + // + // SW0 selects turbo/original clock mode for the core + // + vm_turbo <= de0_sw[0]; + + if (~de0_button[2]) + begin + vm_irq <= 0; + end + else + begin + if (ena_ms) vm_irq <= 1; + if (mx_ack[3]) vm_irq <= 0; + end + + if (~de0_button[2] | ~pll_lock) + rcnt <= 8'h00; + else + if (rcnt != 8'hFF) + rcnt <= rcnt + 8'h01; +end + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam uart.REFCLK = `SYS_CLOCK; +`endif + +uart_wb uart +( + .wb_clk_i(wb_clk), + .wb_rst_i(wb_rst), + .wb_adr_i(wb_adr[0]), + .wb_dat_i(wb_out), + .wb_dat_o(mx_dat[1]), + .wb_cyc_i(wb_cyc), + .wb_we_i(wb_we), + .wb_stb_i(mx_stb[1]), + .wb_ack_o(mx_ack[1]), + + .tx_dat_o(de0_uart_txd), + .tx_cts_i(1'b0), + .rx_dat_i(de0_uart_rxd), + .rx_dtr_o(de0_uart_cts), + +// .tx_ready(), +// .tx_empty(), +// .rx_ready(), + + .cfg_bdiv(baud[15:0]), + .cfg_nbit(2'b11), + .cfg_nstp(1'b1), + .cfg_pena(1'b0), + .cfg_podd(1'b0) +); + +//______________________________________________________________________________ +// +// Wishbone i8080 CPU +// +vm80_wb cpu +( + .wb_clk_i(wb_clk), + .wb_rst_i(wb_rst), + .wb_adr_o(wb_adr), + .wb_dat_o(wb_out), + .wb_dat_i(wb_mux), + .wb_cyc_o(wb_cyc), + .wb_we_o(wb_we), + .wb_stb_o(wb_stb), + .wb_ack_i(wb_ack), + .wb_tgc_o(wb_tag), + + .vm_cena(vm_cena), + .vm_irq(vm_irq), + .vm_inte(vm_inte) +); + +mem_wb mem( + .wb_clk_i(wb_clk), + .wb_adr_i(wb_adr), + .wb_dat_i(wb_out), + .wb_dat_o(mx_dat[0]), + .wb_cyc_i(wb_cyc), + .wb_we_i(wb_we), + .wb_stb_i(mx_stb[0]), + .wb_ack_o(mx_ack[0]) +); + +//______________________________________________________________________________ +// +always @(posedge wb_clk) +begin + if (mx_stb[2]) + begin + if (wb_adr == 16'hFFFB) led <= wb_out; + if (wb_adr == 16'hFFFC) hex0 <= wb_out; + if (wb_adr == 16'hFFFD) hex1 <= wb_out; + if (wb_adr == 16'hFFFE) hex2 <= wb_out; + if (wb_adr == 16'hFFFF) hex3 <= wb_out; + end +end + +assign de0_hex0 = ~hex0; +assign de0_hex1 = ~hex1; +assign de0_hex2 = ~hex2; +assign de0_hex3 = ~hex3; + +assign de0_led[7:0] = led; +assign de0_led[9] = vm_turbo; +assign de0_led[8] = wb_stb & wb_we; + +assign mx_ack[2] = mx_stb[2]; +assign mx_ack[3] = mx_stb[3]; +assign mx_dat[2] = {5'h00, de0_button[2:0]}; +assign mx_dat[3] = 8'hE7; // interrupt rst 4 + +//______________________________________________________________________________ +// +assign mx_stb[0] = wb_stb & wb_cyc & (wb_adr[15:14] == 2'b00) & ~wb_tag[4]; +assign mx_stb[1] = wb_stb & wb_cyc & (wb_adr[15:8] == 8'hFE) & ~wb_tag[4]; +assign mx_stb[2] = wb_stb & wb_cyc & (wb_adr[15:8] == 8'hFF) & ~wb_tag[4]; +assign mx_stb[3] = wb_stb & wb_cyc & wb_tag[4]; // interrupt acknowledge + +assign wb_ack = mx_ack[0] | mx_ack[1] | mx_ack[2] | mx_ack[3]; +assign wb_mux = (mx_stb[0] ? mx_dat[0] : 8'h00) + | (mx_stb[1] ? mx_dat[1] : 8'h00) + | (mx_stb[2] ? mx_dat[2] : 8'h00) + | (mx_stb[3] ? mx_dat[3] : 8'h00); + +//______________________________________________________________________________ +// +`ifdef SYS_CLOCK +defparam timer.REFCLK = `SYS_CLOCK; +`endif + +`ifdef CPU_CLOCK +defparam timer.CPUCLK = `CPU_CLOCK; +`endif + +de0_timer timer +( + .clk(wb_clk), + .rst(wb_rst), + .ena_f2(ena_f2), + .ena_us(ena_us), + .ena_ms(ena_ms) +); + +//______________________________________________________________________________ +// +// Temporary and debug assignments +// +// assign de0_uart_txd = 1'bz; +// assign de0_uart_cts = 1'bz; + +assign de0_dram_dq = 16'hzzzz; +assign de0_dram_addr = 13'h0000; +assign de0_dram_ldqm = 1'b0; +assign de0_dram_udqm = 1'b0; +assign de0_dram_we_n = 1'b1; +assign de0_dram_cas_n = 1'b1; +assign de0_dram_ras_n = 1'b1; +assign de0_dram_cs_n = 1'b1; + +assign de0_dram_ba[0] = 1'b0; +assign de0_dram_ba[1] = 1'b0; +assign de0_dram_clk = 1'b0; +assign de0_dram_cke = 1'b0; + +assign de0_fl_dq = 16'hzzzz; +assign de0_fl_addr = 22'hzzzzzz; +assign de0_fl_we_n = 1'b1; +assign de0_fl_rst_n = 1'b0; +assign de0_fl_oe_n = 1'b1; +assign de0_fl_ce_n = 1'b1; +assign de0_fl_wp_n = 1'b0; +assign de0_fl_byte_n = 1'b1; + +assign de0_lcd_data = 8'hzz; +assign de0_lcd_blig = 1'b0; +assign de0_lcd_rw = 1'b0; +assign de0_lcd_en = 1'b0; +assign de0_lcd_rs = 1'b0; + +assign de0_sd_clk = 1'h0; +assign de0_sd_mosi = 1'hz; +assign de0_sd_miso = 1'hz; +assign de0_sd_cmd = 1'hz; + +assign de0_ps2_kbdat = 1'hz; +assign de0_ps2_kbclk = 1'hz; +assign de0_ps2_msdat = 1'hz; +assign de0_ps2_msclk = 1'hz; + +assign de0_vga_hs = 1'b0; +assign de0_vga_vs = 1'b0; +assign de0_vga_r = 4'h0; +assign de0_vga_g = 4'h0; +assign de0_vga_b = 4'h0; + +assign de0_gpio0_clkout = 2'b00; +assign de0_gpio1_clkout = 2'b00; +assign de0_gpio0_d = 32'hzzzzzzzz; +assign de0_gpio1_d = 32'hzzzzzzzz; + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/wbc/rtl/de0/de0_uart.v b/1801BM1_vm80a/wbc/rtl/de0/de0_uart.v new file mode 100644 index 0000000000000000000000000000000000000000..4828ed86aa54ed63af6cc36d660ca78f685798be --- /dev/null +++ b/1801BM1_vm80a/wbc/rtl/de0/de0_uart.v @@ -0,0 +1,376 @@ +// +// Copyright (c) 2014-2015 by 1801BM1@gmail.com +// +// Universal Serial Asynchronous Receiver-Transmitter (simplified 8251) +//______________________________________________________________________________ +// +module uart_wb #(parameter REFCLK=50000000) +( + input wb_clk_i, // system clock + input wb_rst_i, // peripheral reset + // + input [0:0] wb_adr_i, // + input [7:0] wb_dat_i, // + output reg [7:0] wb_dat_o, // + input wb_cyc_i, // + input wb_we_i, // + input wb_stb_i, // + output reg wb_ack_o, // + // + output tx_dat_o, // output serial data (txd) + input tx_cts_i, // enable transmitter (rts) + input rx_dat_i, // input serial data (rxd) + output rx_dtr_o, // receiver ready (cts) + // + output tx_ready_o, // tx ready request + output tx_empty_o, // tx empty request + output rx_ready_o, // rx ready request + // + input [15:0] cfg_bdiv, // baudrate divisor: (921600/baud)-1 + input [1:0] cfg_nbit, // word length: 00-5, 01-6, 10-7, 11-8 bit + input cfg_nstp, // tx stop bits: 0 - 1 stop, 1 - 2 stop + input cfg_pena, // parity control enable + input cfg_podd // odd parity (complete to odd ones) +); + +wire [63:0] add_arg; +reg [16:0] add_reg; +reg [15:0] baud_div; +reg baud_x16; +wire baud_ref; + +reg [1:0] tx_cts_reg; +reg [1:0] rx_dat_reg; + +wire csr_wstb; +wire rbr_rstb; +wire thr_wstb; + +wire tx_par; +reg [7:0] tx_thr; +reg [9:0] tx_shr; +reg [7:0] tx_bcnt; +reg tx_busy; +reg tx_ready, tx_empty, tx_break; + +wire rx_dat; +reg [7:0] rx_rbr; +reg [8:0] rx_shr; +reg [7:0] rx_bcnt; +reg rx_ready, rx_perr, rx_ovf, rx_break; +wire rx_load, rx_stb; +reg rx_frame, rx_start, rx_par; + +//______________________________________________________________________________ +// +// Caution note: the arithmetic expressions should be calculated in 64-bit width +// +assign add_arg = (64'h0000000000100000 * 64'd921600)/REFCLK; +assign baud_ref = add_reg[16]; +// +// Phase accumulator to generate 921600 * 16 Hz reference clock strobe +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + add_reg <= 17'h00000; + else + begin + add_reg <= {1'b0, add_reg[15:0]} + add_arg[16:0]; + end +end +// +// Baud rate x16 generator +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + baud_div <= 16'h0000; + baud_x16 <= 1'b0; + end + else + begin + if (baud_ref) + if (baud_div == 16'h0000) + baud_div <= cfg_bdiv; + else + baud_div <= baud_div - 16'h0001; + + baud_x16 <= baud_ref & (baud_div == 16'h0000); + end + +end + +//______________________________________________________________________________ +// +assign csr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & wb_adr_i[0]; +assign thr_wstb = wb_cyc_i & wb_stb_i & wb_we_i & wb_ack_o & ~wb_adr_i[0]; +assign rbr_rstb = wb_cyc_i & wb_stb_i & ~wb_we_i & ~wb_ack_o & ~wb_adr_i[0]; +// +// Output data multiplexed register +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + wb_dat_o <= 8'h00; + else + if (wb_cyc_i & wb_stb_i & ~wb_ack_o) + begin + if (wb_adr_i[0]) + wb_dat_o <= (tx_ready << 7) + | (tx_break << 6) + | (tx_empty << 5) + | (rx_ready << 3) + | (rx_break << 2) + | (rx_perr << 1) + | (rx_ovf << 0); + else + wb_dat_o <= rx_rbr; + end +end + +always @(posedge wb_clk_i) + wb_ack_o <= wb_cyc_i & wb_stb_i & ~wb_ack_o; + +// +// Control register bits +// +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + tx_break <= 1'b0; + else + if (csr_wstb) tx_break <= wb_dat_i[6]; +end + +//______________________________________________________________________________ +// +// Interrupts +// +assign tx_ready_o = tx_ready; +assign tx_empty_o = tx_empty; +assign rx_ready_o = rx_ready; + +//______________________________________________________________________________ +// +// Metastability issues +// +always @(posedge wb_clk_i) +begin + tx_cts_reg[0] <= ~tx_cts_i; + tx_cts_reg[1] <= tx_cts_reg[0]; + + rx_dat_reg[0] <= rx_dat_i; + rx_dat_reg[1] <= rx_dat_reg[0]; +end + +//______________________________________________________________________________ +// +// Transmitter unit +// +assign tx_par = tx_thr[0] ^ tx_thr[1] ^ tx_thr[2] ^ tx_thr[3] ^ tx_thr[4] + ^ (tx_thr[5] & (cfg_nbit >= 2'b01)) + ^ (tx_thr[6] & (cfg_nbit >= 2'b10)) + ^ (tx_thr[7] & (cfg_nbit == 2'b11)) + ^ cfg_podd; +assign tx_dat_o = tx_shr[0] & ~tx_break; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + tx_ready <= 1'b1; + tx_empty <= 1'b1; + tx_shr <= 10'o1777; + tx_busy <= 1'b0; + tx_bcnt <= 8'b00000000; + tx_thr <= 8'b00000000; + end + else + begin + tx_empty <= tx_ready & ~tx_busy; + // + // Transmitter hold register write + // + if (thr_wstb) + begin + tx_ready <= 1'b0; + tx_thr <= wb_dat_i[7:0]; + end + + if (baud_x16) + begin + // + // Transmit process + // + if (tx_busy) + begin + if (tx_bcnt == 8'b00000001) + tx_busy <= 1'b0; + + if (tx_bcnt != 8'b00000000) + tx_bcnt <= tx_bcnt - 8'b00000001; + + if (tx_bcnt[3:0] == 4'b0000) + tx_shr <= {1'b1, tx_shr[9:1]}; + end + + // + // Starting new word transmit + // + if (~tx_ready & ~tx_busy & tx_cts_reg[1]) + begin + tx_busy <= 1'b1; + tx_ready <= ~thr_wstb; + tx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena} + {3'b000, cfg_nstp}, 4'b1111}; + + if (cfg_pena) + case(cfg_nbit) + 2'b00: tx_shr <= {3'b111, tx_par, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {2'b11, tx_par, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {1'b1, tx_par, tx_thr[6:0], 1'b0}; + default: tx_shr <= { tx_par, tx_thr[7:0], 1'b0}; + endcase + else + case(cfg_nbit) + 2'b00: tx_shr <= {4'b1111, tx_thr[4:0], 1'b0}; + 2'b01: tx_shr <= {3'b111, tx_thr[5:0], 1'b0}; + 2'b10: tx_shr <= {2'b11, tx_thr[6:0], 1'b0}; + default: tx_shr <= {1'b1, tx_thr[7:0], 1'b0}; + endcase + end + end + end +end + +//______________________________________________________________________________ +// +// Receiver unit +// +assign rx_dtr_o = rx_ready; +assign rx_dat = rx_dat_reg[1]; + +assign rx_load = rx_stb & (rx_bcnt[7:4] == 4'b0000); +assign rx_stb = (rx_bcnt[3:0] == 4'b0001) & baud_x16; + +always @(posedge wb_clk_i or posedge wb_rst_i) +begin + if (wb_rst_i) + begin + rx_ready <= 1'b0; + rx_break <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + rx_frame <= 1'b0; + rx_start <= 1'b0; + rx_par <= 1'b0; + rx_rbr <= 8'b00000000; + rx_shr <= 9'b00000000; + rx_bcnt <= 8'b00000000; + end + else + begin + if (rx_load) + begin + rx_ready <= 1'b1; + case(cfg_nbit) + 2'b00: rx_rbr <= {3'b000, rx_shr[4:0]}; + 2'b01: rx_rbr <= {2'b00, rx_shr[5:0]}; + 2'b10: rx_rbr <= {1'b0, rx_shr[6:0]}; + default: rx_rbr <= rx_shr[7:0]; + endcase + rx_perr <= rx_par; + rx_ovf <= rx_ready; + rx_break <= ~rx_dat; + end + else + if (rbr_rstb) + begin + rx_ready <= 1'b0; + rx_perr <= 1'b0; + rx_ovf <= 1'b0; + end + + if (baud_x16) + begin + if (~rx_frame) + // + // Waiting for start bit + // + if (~rx_dat) + begin + rx_par <= cfg_pena & cfg_podd; + rx_start <= 1'b1; + rx_frame <= 1'b1; + rx_bcnt <= {4'b0110 + {2'b00, cfg_nbit} + {3'b000, cfg_pena}, 4'b0111}; + end + else + begin + rx_start <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + begin + // + // Receiving frame + // + if (rx_bcnt != 8'b00000000) + rx_bcnt <= rx_bcnt - 8'b00000001; + // + // Start bit monitoring + // + if (rx_start) + begin + if (rx_dat) + begin + // + // Spurrious start bit + // + rx_start <= 1'b0; + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + else + if (rx_bcnt[3:0] == 4'b0010) + rx_start <= 1'b0; + end + else + begin + // + // Receiving data + // + if (rx_stb) + begin + rx_par <= (rx_par ^ rx_dat) & cfg_pena; + if (cfg_pena) + case(cfg_nbit) + 2'b00: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b01: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + 2'b10: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + default: rx_shr <= {rx_dat, rx_shr[8:1]}; + endcase + else + case(cfg_nbit) + 2'b00: rx_shr <= {4'b0000, rx_dat, rx_shr[4:1]}; + 2'b01: rx_shr <= {3'b000, rx_dat, rx_shr[5:1]}; + 2'b10: rx_shr <= {2'b00, rx_dat, rx_shr[6:1]}; + default: rx_shr <= {1'b0, rx_dat, rx_shr[7:1]}; + endcase + if (rx_load & rx_dat) + begin + // + // Stop bit detected + // + rx_frame <= 1'b0; + rx_bcnt <= 8'b00000000; + end + end + if ((rx_bcnt == 8'b00000000) & rx_dat) + rx_frame <= 1'b0; + end + end + end + end +end +endmodule diff --git a/1801BM1_vm80a/wbc/rtl/vm80_wb.v b/1801BM1_vm80a/wbc/rtl/vm80_wb.v new file mode 100644 index 0000000000000000000000000000000000000000..d0649bda2743a1563609c07060da40cb653f3e4e --- /dev/null +++ b/1801BM1_vm80a/wbc/rtl/vm80_wb.v @@ -0,0 +1,779 @@ +// +// Copyright (c) 2014-2018 by 1801BM1@gmail.com +// Licensed under CC-BY 3.0 (https://creativecommons.org/licenses/by/3.0/) +// +// Wishbone compatibe version of revengineered 580BM80A/i8080A +//______________________________________________________________________________ +// +module vm80_wb +( + input wb_clk_i, // module clock + input wb_rst_i, // module reset + // + output[15:0] wb_adr_o, // address bus outputs + output[7:0] wb_dat_o, // data bus output + input [7:0] wb_dat_i, // data bus input + output wb_cyc_o, // master wishbone cycle + output wb_we_o, // master wishbone direction + output wb_stb_o, // master wishbone strobe + input wb_ack_i, // master wishbone acknowledge + // + // Wishbone cycle tags + output [5:0] wb_tgc_o, // [0] M1 command fetch + // [1] IO space tag + // [2] Write cycle tag + // [3] Stack operation + // [4] Interrupt acknowledge + // [5] Processor halted + // + input vm_cena, // clock enable + input vm_irq, // interrupt request + output vm_inte // interrupt enable flag +); + +//______________________________________________________________________________ +// +wire clk; // global module clock +wire ena; // global clock enable +reg reset; // latched module reset + +reg [15:0] a; // output address buffer +wire [7:0] d; // internal data bus mux +reg [7:0] db; // data output buffer +reg [7:0] di; // data input buffer + +reg dbin_rd, wb_cyc; +reg wb_stb, wb_we; +wire ready, dad_m45; +wire io_rdy, io_ena; +reg [2:0] io_cnt; + +reg [15:0] r16_pc, r16_hl, r16_de, r16_bc, r16_sp, r16_wz; +wire [15:0] mxi, mxo; +wire mxr0, mxr1, mxr2, mxr3, mxr4, mxr5; +wire mxwh, mxwl, mxrh, mxrl, mxw16, mxwadr; +wire dec16, inc16, iad16; +reg xchg_dh, xchg_tt; +wire t1467, t1513, t1514, t1519; + +wire sy_wo_n, sy_stack; + +reg t1, t2, tw, t3, t4, t5; +reg m1, m2, m3, m4, m5; + +wire thalt, start, eom, ms0, ms1, m789, m836; +reg intr, inta, inte, minta; +wire irq; + +reg [7:0] i; +wire i25, i14, i03, imx, acc_sel; +wire id_op, id_io, id_in, id_popsw, id_pupsw, + id_nop, id_lxi, id_inx, id_inr, id_dcr, id_idr, id_mvi, id_dad, + id_dcx, id_opa, id_idm, id_hlt, id_mov, id_opm, id_pop, id_rst, + id_cxx, id_jxx, id_rxx, id_ret, id_jmp, id_opi, id_out, id_11x, + id_rlc, id_rxc, id_rar, id_sha, id_daa, id_cma, id_stc, id_cmc, + id_add, id_adc, id_sub, id_sbb, id_ana, id_xra, id_ora, id_cmp, + id_lsax, id_mvim, id_shld, id_lhld, id_mvmr, id_mvrm, id_push, + id_xthl, id_sphl, id_pchl, id_xchg, id_call, id_eidi, id_stlda; + +wire id80, id81, id82, id83, id84, id85, id86, id00, id01, + id02, id03, id04, id05, id06, id07, id08, id09, id10; +wire goto, jmpflag; +reg jmptake, tree1t; +wire tree1, tree2; + +reg [7:0] xr, r, acc; +wire [7:0] x, s, c; +wire cl, ch, daa, daa_6x, daa_x6; +wire alu_xout, alu_xwr, alu_xrd, alu_ald, alu_awr, alu_ard, + alu_rld, alu_r00, alu_rwr, alu_srd, alu_zrd, alu_pha; + +reg psw_z, psw_s, psw_p, psw_c, psw_ac, tmp_c; +wire psw_ld, psw_wr, psw_oe; + +//_____________________________________________________________________________ +// +// Wishbone logic +// +assign clk = wb_clk_i; +// +// Latch the external reset (can has the huge input tree) +// +always @(posedge clk) reset <= wb_rst_i; + +// +// We cannot stop the T-state machine while writing, no present written data on the bus, +// we should wait, but the state machine goes to T3 (at that data and write strobe are) +// and does not wait there (8080 waits on the transfer T2->T3). So we have to use +// the global clock enable. +// +assign io_ena = ~(wb_cyc_o & wb_we_o & wb_stb_o & ~wb_ack_i); +assign io_rdy = ~sy_wo_n | (wb_cyc_o & wb_stb_o & wb_ack_i); +// +// Use former ready external input to stall the CPU while reading +// +assign dad_m45 = (m4 | m5) & id_dad; +assign ready = dad_m45 | io_rdy; +// +// Implement wishbone output registers +// +assign wb_adr_o = a; +assign wb_dat_o = db; +assign wb_cyc_o = wb_cyc; +assign wb_stb_o = wb_stb; +assign wb_we_o = wb_we; + +always @(posedge clk or posedge reset) +begin + if (reset) + begin + wb_cyc <= 1'b0; + wb_stb <= 1'b0; + wb_we <= 1'b0; + end + else + if (wb_ack_i & wb_stb_o & wb_cyc) + begin + wb_cyc <= 1'b0; + wb_stb <= 1'b0; + wb_we <= 1'b0; + end + else + begin + wb_we <= ~sy_wo_n; + + if ( (t1 & ~dad_m45 & ~sy_wo_n) + | (t1 & sy_wo_n)) + wb_cyc <= 1'b1; + + if ( (t2 & ~dad_m45 & ~sy_wo_n) + | (t1 & sy_wo_n)) + wb_stb <= 1'b1; + end +end + +always @(posedge clk) +if (ena) +begin + dbin_rd <= (t2 | tw) & sy_wo_n & (m1 | ~id_hlt); + if ((t2 | tw) & sy_wo_n) di <= wb_dat_i; + if (~sy_wo_n & t2) db <= d; +end + +//______________________________________________________________________________ +// +// Clock moderator for slow origial speed emulation, vm_cena is used for +// The entire core stopped before entering the T1 tick +// +assign ena = ~(~io_ena | eom & (io_cnt != 3'b000)); + +always @(posedge clk or posedge reset) +begin + if (reset) + io_cnt <= 3'b000; + else + begin + if (~ena & vm_cena & (io_cnt != 3'b000)) + io_cnt <= io_cnt - 3'b001; + + if (ena & ~vm_cena & (io_cnt != 3'b111)) + io_cnt <= io_cnt + 3'b001; + end +end + +//______________________________________________________________________________ +// +// Internal data bus mux +// +assign d[7] = ~alu_zrd & + ( dbin_rd & di[7] + | mxrl & mxo[7] + | mxrh & mxo[15] + | alu_xrd & xr[7] + | alu_ard & acc[7] + | alu_srd & s[7] + | psw_oe & psw_s); + +assign d[6] = ~alu_zrd & + ( dbin_rd & di[6] + | mxrl & mxo[6] + | mxrh & mxo[14] + | alu_xrd & xr[6] + | alu_ard & acc[6] + | alu_srd & s[6] + | psw_oe & psw_z); + +assign d[5] = ~alu_zrd & + ( dbin_rd & di[5] + | mxrl & mxo[5] + | mxrh & mxo[13] + | alu_xrd & xr[5] + | alu_ard & acc[5] + | alu_srd & s[5] + | psw_oe & 1'b0); + +assign d[4] = ~alu_zrd & + ( dbin_rd & di[4] + | mxrl & mxo[4] + | mxrh & mxo[12] + | alu_xrd & xr[4] + | alu_ard & acc[4] + | alu_srd & s[4] + | psw_oe & psw_ac); + +assign d[3] = ~alu_zrd & + ( dbin_rd & di[3] + | mxrl & mxo[3] + | mxrh & mxo[11] + | alu_xrd & xr[3] + | alu_ard & acc[3] + | alu_srd & s[3] + | psw_oe & 1'b0); + +assign d[2] = ~alu_zrd & + ( dbin_rd & di[2] + | mxrl & mxo[2] + | mxrh & mxo[10] + | alu_xrd & xr[2] + | alu_ard & acc[2] + | alu_srd & s[2] + | psw_oe & psw_p); + +assign d[1] = ~alu_zrd & + ( dbin_rd & di[1] + | mxrl & mxo[1] + | mxrh & mxo[9] + | alu_xrd & xr[1] + | alu_ard & acc[1] + | alu_srd & s[1] + | psw_oe & 1'b1); + +assign d[0] = ~alu_zrd & + ( dbin_rd & di[0] + | mxrl & mxo[0] + | mxrh & mxo[8] + | alu_xrd & xr[0] + | alu_ard & acc[0] + | alu_srd & s[0] + | psw_oe & psw_c); + +//______________________________________________________________________________ +// +// register unit - 6 16-bit registers +// +// r0 - pc +// r1 - hl, de (runtime alias via xchg_dh flag) +// r2 - de, hl (runtime alias via xchg_dh flag) +// r3 - bc +// r4 - sp +// r5 - wz +// +assign t1467 = tree1 | (id04 & t4 & ~id_xthl); + +assign t1513 = (t4 & id07) + | id07 & ((t1 & (m4 | m5)) | (t3 & (m2 | m3)) | t5); + +assign t1514 = (t4 & id08) + | t1 & m4 & id_lsax + | t2 & id10 & ~sy_wo_n + | t3 & id10 & sy_wo_n & (m4 | m5) + | t5 & id08 & m1; +assign t1519 = tree2 | (id00 & t4 & ~id_xthl); + +assign mxi = inc16 ? (a + 16'h0001) + : dec16 ? (a - 16'h0001) + : a; + +assign inc16 = iad16 & ~dec16; +assign dec16 = iad16 & id05 & (t4 | t5 | m4 | m5); +assign iad16 = ~(id00 & (t4 | t5)) & (~minta | m5 | t4 | t5 | (m4 & ~id02)); + +assign mxw16 = t2 & ( (m1 | m2) + | (m3 & ~id_xthl) + | ((m4 | m5) & ~id_dad & ~id09)) + | t3 & m4 & id09 + | t5 & (m5 | (m1 & ~id08)); + +assign mxwadr = t4 & ~id_dad & ~id_hlt + | t1 & (m1 | m2 | m3 | ((m4 | m5) & ~id_hlt & ~id_dad)); + + +assign mxrh = id08 & t4 & ~i03 + | (t1 | t2) & m5 & id_dad + | t2 & ((m5 & id_shld) | (m4 & id03)); + +assign mxrl = id08 & t4 & i03 + | (t1 | t2) & m4 & id_dad + | t2 & ((m4 & id_shld) | (m5 & id03)); + +assign mxwh = reset + | t3 & (m1 | m3 | (m4 & id_io) | (m5 & id06)) + | ((t3 & m4) | (t5 & m1)) & id08 & ~i03; + +assign mxwl = reset + | t3 & (m2 | (m4 & id06) | (m5 & id_rst)) + | ((t3 & m4) | (t5 & m1)) & id08 & i03; + +assign mxr0 = t1 & ( (m1 & ~goto) + | (m2 & ~id_xthl) + | (m3 & ~id_xthl) + | (m4 & id02)) + | t2 & ( m1 + | (m2 & ~id_xthl) + | (m3 & ~id_xthl) + | (m4 & (id02 | id_rst | id_cxx | id_call)) + | (m5 & (id_rst | id_cxx | id_call))) + | t3 & ( (m4 & (id_ret | id_rxx)) + | (m5 & (id_ret | id_rxx))) + | t5 & id_pchl; + +assign mxr1 = xchg_dh & (((t1513 | t1514) & (~i14 & i25)) | t1519) + | ~xchg_dh & (t1513 | t1514) & (i14 & ~i25); + +assign mxr2 = xchg_dh & (t1513 | t1514) & (i14 & ~i25) + | ~xchg_dh & (((t1513 | t1514) & (~i14 & i25)) | t1519); + +assign mxr3 = (t1513 | t1514) & (~i14 & ~i25); +assign mxr4 = t1467 | (t1513 & i14 & i25); +assign mxr5 = ~(t1467 | t1513 | t1514 | t1519 | mxr0); + +always @ (posedge clk) +if (ena) +begin + xchg_tt <= id_xchg & t2; + xchg_dh <= ~reset & ((xchg_tt & ~(id_xchg & t2)) ? ~xchg_dh : xchg_dh); +end + +assign mxo = (mxr0 ? r16_pc : 16'h0000) + | (mxr1 ? r16_hl : 16'h0000) + | (mxr2 ? r16_de : 16'h0000) + | (mxr3 ? r16_bc : 16'h0000) + | (mxr4 ? r16_sp : 16'h0000) + | (mxr5 ? r16_wz : 16'h0000); + +always @ (posedge clk) +if (ena) +begin + if (mxwadr) a <= mxo; + if (mxw16) + begin + if (mxr0) r16_pc <= mxi; + if (mxr1) r16_hl <= mxi; + if (mxr2) r16_de <= mxi; + if (mxr3) r16_bc <= mxi; + if (mxr4) r16_sp <= mxi; + if (mxr5) r16_wz <= mxi; + end + else + begin + if (mxwl) + begin + if (mxr0) r16_pc[7:0] <= d; + if (mxr1) r16_hl[7:0] <= d; + if (mxr2) r16_de[7:0] <= d; + if (mxr3) r16_bc[7:0] <= d; + if (mxr4) r16_sp[7:0] <= d; + if (mxr5) r16_wz[7:0] <= d; + end + if (mxwh) + begin + if (mxr0) r16_pc[15:8] <= d; + if (mxr1) r16_hl[15:8] <= d; + if (mxr2) r16_de[15:8] <= d; + if (mxr3) r16_bc[15:8] <= d; + if (mxr4) r16_sp[15:8] <= d; + if (mxr5) r16_wz[15:8] <= d; + end + end +end + +//______________________________________________________________________________ +// +// processor state +// +assign wb_tgc_o[0] = m1; // command fetch +assign wb_tgc_o[1] = m5 & (id_in | id_out); // in/out transfer +assign wb_tgc_o[2] = ~sy_wo_n; // write operation +assign wb_tgc_o[3] = t1 ? tree1 : tree1t; // stack operation +assign wb_tgc_o[4] = inta; // interrupt acknowledge +assign wb_tgc_o[5] = id_hlt; // processor halted + +assign sy_wo_n = m1 | m2 | m3 | (((m4 & ~id86) | (m5 & ~id85)) & ~dad_m45); +assign sy_stack = t1 & tree1 + | t3 & m3 & id_cxx & ~jmptake + | t5 & m1 & id_rxx & ~jmptake; + +always @(posedge clk) + if (ena & t1) + tree1t <= tree1; + +//______________________________________________________________________________ +// +// Ticks state machine +// +assign thalt = ~m1 & id_hlt; + +always @(posedge clk or posedge reset) +begin + if (reset) + begin + t1 <= 1'b1; + t2 <= 1'b0; + tw <= 1'b0; + t3 <= 1'b0; + t4 <= 1'b0; + t5 <= 1'b0; + end + else + if (ena) + begin + t1 <= start; + t2 <= ~start & t1; + tw <= ~start & (t2 | tw) & (~ready | thalt); + t3 <= ~start & (t2 | tw) & ready & ~thalt; + t4 <= ~start & t3 & ms0 & ~ms1; + t5 <= ~start & t4 & ms0 & ~ms1; + end +end + +//______________________________________________________________________________ +// +assign start = reset | eom | (id_hlt & minta & m4); +assign m836 = m1 & id82; +assign m789 = (id84 & m3) | (id83 & ~id_mvim & m4) | m5; +assign eom = t5 + | t4 & m1 & id80 + | t3 & m2 + | t3 & m3 + | t3 & m4 + | t3 & m5 & ~id_xthl; + +assign ms0 = ~reset & (~(minta & m4) | ~id_hlt) & ~(sy_stack & ~t1) & ~(eom & ~m836); +assign ms1 = ~reset & (~(minta & m4) | ~id_hlt) & ~(sy_stack & ~t1) & ~((m789 | id81) & ~m836) & eom; + +//______________________________________________________________________________ +// +// Processor M-cycles state machine +// +always @(posedge clk or posedge reset) +begin + if (reset) + begin + m1 <= 1'b1; + m2 <= 1'b0; + m3 <= 1'b0; + m4 <= 1'b0; + m5 <= 1'b0; + end + else + if (ena) + begin + m1 <= (~ms0 & ~ms1) | (~ms1 & m1); + m2 <= (~ms0 | ~ms1) & ((ms0 & m2) | (ms1 & m1)); + m3 <= (ms0 & m3) | (ms1 & m2); + m4 <= (ms0 & m4) | (ms1 & m3) | (ms0 & ms1); + m5 <= (ms0 & m5) | (ms1 & m4); + end +end + +//______________________________________________________________________________ +// +// Interrupt logic +// Interrupt acknowledge in the halt mode and other stuff removed +// +assign irq = intr & inte & ~reset; +assign vm_inte = inte; + +always @(posedge clk or posedge reset) +begin + if (reset) + begin + inta <= 0; + inte <= 0; + minta <= 0; + end + else + if (ena) + begin + intr <= vm_irq; + + if (irq & (~ms0 & ~ms1 | tw & id_hlt) & ~id_eidi) inta <= 1; + if (~intr | id_eidi | (t5 & id_rst)) inta <= 0; + + if (inta) minta <= 1; + if (~ms0 & ~ms1) minta <= 0; + + if (t1 & id_eidi) inte <= i[3]; + if (t1 & inta) inte <= 0; + end +end +//______________________________________________________________________________ +// +// Instruction register and decoder +// +function cmp +( + input [7:0] i, + input [7:0] c, + input [7:0] m +); + cmp = &(~(i ^ c) | m); +endfunction + +assign imx = ~(id_op | (id_mov & t4)); +assign i25 = imx ? i[5] : i[2]; +assign i14 = imx ? i[4] : i[1]; +assign i03 = imx ? i[3] : i[0]; +assign acc_sel = imx ? (i[5:3] == 3'b111) : (i[2:0] == 3'b111); + +assign jmpflag = (psw_c & i14 & ~i25) // Intel original: d[0] instead of psw_c + | (psw_p & ~i14 & i25) // Intel original: d[2] instead of psw_p + | (psw_z & ~i14 & ~i25) // Intel original: d[6] instead of psw_z + | (psw_s & i14 & i25); // Intel original: d[7] instead of psw_s + + +always @(posedge clk or posedge reset) +begin + if (reset) + i <= 8'h00; + else + if (ena & m1 & t3) + i <= di; +end + +assign goto = id_rst | id_jmp | id_call | (jmptake & (id_cxx | id_jxx)); + +assign tree1 = (t1 & ((m2 & id00) + | (m3 & id00) + | (m4 & (id01 | id04)) + | (m5 & (id01 | id04))) + | t2 & ( (m2 & id00) + | (m4 & id01) + | (m5 & id01)) + | t3 & ( (m4 & (id04 | id_sphl))) + | t5 & ( (m1 & (id04 | id_sphl)))) & ~(~jmptake & id_cxx & t5); + +assign tree2 = t1 & ( (m4 & (id_mov | id_idr | id_op)) + | (m5 & id08)) + | t2 & ( (m4 & (id_shld | id00 | id_dad)) + | (m5 & (id_shld | id00 | id_dad))) + | t3 & ( (m4 & (id_lhld | id_dad)) + | (m5 & (id_lhld | id_dad))) + | t5 & m5; + +always @(posedge clk) + if (ena & t4) + jmptake <= i03 ? jmpflag : ~jmpflag; + +assign id_nop = cmp(i, 8'b00xxx000, 8'b00111000); +assign id_lxi = cmp(i, 8'b00xx0001, 8'b00110000); +assign id_lsax = cmp(i, 8'b000xx010, 8'b00011000); +assign id_inx = cmp(i, 8'b00xx0011, 8'b00110000); +assign id_inr = cmp(i, 8'b00xxx100, 8'b00111000); +assign id_dcr = cmp(i, 8'b00xxx101, 8'b00111000); +assign id_idr = cmp(i, 8'b00xxx10x, 8'b00111001); +assign id_mvi = cmp(i, 8'b00xxx110, 8'b00111000); +assign id_dad = cmp(i, 8'b00xx1001, 8'b00110000); +assign id_dcx = cmp(i, 8'b00xx1011, 8'b00110000); +assign id_opa = cmp(i, 8'b00xxx111, 8'b00111000); +assign id_idm = cmp(i, 8'b0011010x, 8'b00000001); +assign id_stlda = cmp(i, 8'b0011x010, 8'b00001000); +assign id_mvim = cmp(i, 8'b00110110, 8'b00000000); +assign id_shld = cmp(i, 8'b00100010, 8'b00000000); +assign id_lhld = cmp(i, 8'b00101010, 8'b00000000); +assign id_mvmr = cmp(i, 8'b01110xxx, 8'b00000111) & ~id_hlt; +assign id_mvrm = cmp(i, 8'b01xxx110, 8'b00111000) & ~id_hlt; +assign id_hlt = cmp(i, 8'b01110110, 8'b00000000); +assign id_mov = cmp(i, 8'b01xxxxxx, 8'b00111111); +assign id_op = cmp(i, 8'b10xxxxxx, 8'b00111111); +assign id_opm = cmp(i, 8'b10xxx110, 8'b00111000); +assign id_pop = cmp(i, 8'b11xx0001, 8'b00110000); +assign id_push = cmp(i, 8'b11xx0101, 8'b00110000); +assign id_rst = cmp(i, 8'b11xxx111, 8'b00111000); +assign id_xthl = cmp(i, 8'b11100011, 8'b00000000); +assign id_sphl = cmp(i, 8'b11111001, 8'b00000000); +assign id_pchl = cmp(i, 8'b11101001, 8'b00000000); +assign id_xchg = cmp(i, 8'b11101011, 8'b00000000); +assign id_cxx = cmp(i, 8'b11xxx100, 8'b00111000); +assign id_jxx = cmp(i, 8'b11xxx010, 8'b00111000); +assign id_rxx = cmp(i, 8'b11xxx000, 8'b00111000); +assign id_ret = cmp(i, 8'b110x1001, 8'b00010000); +assign id_call = cmp(i, 8'b11xx1101, 8'b00110000); +assign id_eidi = cmp(i, 8'b1111x011, 8'b00001000); +assign id_jmp = cmp(i, 8'b1100x011, 8'b00001000); +assign id_io = cmp(i, 8'b1101x011, 8'b00001000); +assign id_opi = cmp(i, 8'b11xxx110, 8'b00111000); +assign id_in = cmp(i, 8'b11011011, 8'b00000000); +assign id_popsw = cmp(i, 8'b11110001, 8'b00000000); +assign id_out = cmp(i, 8'b11010011, 8'b00000000); +assign id_11x = cmp(i, 8'b11xxxxxx, 8'b00111111); +assign id_pupsw = cmp(i, 8'b11110101, 8'b00000000); + +assign id_rxc = ~i[5] & i[3] & id_opa; +assign id_sha = ~i[5] & id_opa; +assign id_rlc = (i[5:3] == 3'b000) & id_opa; +assign id_rar = (i[5:3] == 3'b011) & id_opa; +assign id_daa = (i[5:3] == 3'b100) & id_opa; +assign id_cma = (i[5:3] == 3'b101) & id_opa; +assign id_stc = (i[5:3] == 3'b110) & id_opa; +assign id_cmc = (i[5:3] == 3'b111) & id_opa; + +assign id_add = (i[5:3] == 3'b000) & (id_op | id_opi); +assign id_adc = (i[5:3] == 3'b001) & (id_op | id_opi); +assign id_sub = (i[5:3] == 3'b010) & (id_op | id_opi); +assign id_sbb = (i[5:3] == 3'b011) & (id_op | id_opi); +assign id_ana = (i[5:3] == 3'b100) & (id_op | id_opi); +assign id_xra = (i[5:3] == 3'b101) & (id_op | id_opi); +assign id_ora = (i[5:3] == 3'b110) & (id_op | id_opi); +assign id_cmp = (i[5:3] == 3'b111) & (id_op | id_opi); + +assign id80 = id_lxi | id_pop | id_opm | id_idm | id_dad + | id_xthl | id_xchg | id_jxx | id_ret | id_eidi + | id_nop | id_stlda | id_mvmr | id_mvrm | id_hlt + | id_opa | id_mvim | id_jmp | id_io | id_opi + | id_mvi | id_lsax | id_lhld | id_shld | id_op; +assign id81 = id_dcx | id_inx | id_sphl | id_pchl | id_xchg + | id_eidi | id_nop | id_opa | id_op | id_mov + | (id_idr & ~id82); +assign id82 = id_pop | id_push | id_opm | id_idm | id_dad + | id_rst | id_ret | id_rxx | id_mvrm | id_mvmr + | id_hlt | id_mvim | id_io | id_opi | id_mvi + | id_lsax; +assign id83 = id_opm | id_stlda | id_mvmr | id_mvrm | id_opi + | id_mvi | id_lsax; +assign id84 = id_lxi | id_jxx | id_jmp; +assign id85 = id_push | id_idm | id_rst | id_xthl | id_cxx + | id_call | id_mvim | id_shld | (id_io & ~i[3]); +assign id86 = id_push | id_rst | id_xthl | id_cxx | id_call + | id_mvmr | id_shld | (~i[3] & (id_lsax | id_stlda)); + +assign id00 = id_xthl | id_pchl | id_sphl; +assign id01 = id_pop | id_rxx | id_ret; +assign id02 = id_mvi | id_opi | id_io; +assign id03 = id_rst | id_push | id_xthl | id_cxx | id_call; +assign id04 = id_rst | id_push | id_xthl | id_cxx | id_call; +assign id05 = id_rst | id_push | id_xthl | id_cxx | id_call | id_dcx; +assign id06 = id_pop | id_rxx | id_ret | id_dad | id_lhld | id_io; +assign id07 = id_dcx | id_inx | id_lxi | id_dad; +assign id08 = id_mov | id_mvi | id_idr | id_op; +assign id09 = id_rst | id_push | id_xthl | id_cxx | id_call | id_shld; +assign id10 = id_pop | id_push | id_mvrm | id_mvi; + +//______________________________________________________________________________ +// +// arithmetic and logic unit (refactored) +// +assign alu_xwr = t4 & (id_rst | id_out | ~id_11x) + | t3 & m4 & ~(id_dad | id_out | id_rst) + | t2 & (m4 | m5) & id_dad; + +assign alu_xout = ~(id_sub | id_sbb | id_cmp | id_cma); +assign alu_xrd = t5 & m1 & ~id_inr & ~id_dcr + | t3 & m5 & id_rst + | t2 & ~sy_wo_n & (id_io | id_mvim | id_stlda | id_lsax | id_mvmr); + +assign alu_pha = (t2 & m1) | (t1 & m5); +assign alu_r00 = id_dcr & t4; + +assign alu_ald = alu_pha & ( id_adc | id_add | id_daa | id_xra | id_sbb + | id_sub | id_ana | id_ora | id_sha | id_cma); + +assign alu_ard = t4 & m1 & ((acc_sel & id08) | id_opa | id_stlda | id_lsax | id_io) + | t2 & m4 & id_pupsw; + +assign alu_awr = t3 & m5 & id_popsw + | t3 & m5 & (id_io | id_mvim) & sy_wo_n + | t3 & m4 & (id_stlda | id_lsax | id_mvmr) & sy_wo_n + | acc_sel & id08 & (t5 & m1 | t3 & m4); + +assign alu_srd = t2 & m5 & (id_inr | id_dcr) + | t3 & m5 & id_dad + | t3 & m4 & id_dad + | t5 & m1 & (id_inr | id_dcr); + +assign alu_rwr = t3 & m1 + | t1 & (m4 | m5) & id_dad; + +assign alu_rld = t4 & (id_sha | id_op | id_opi); + +assign daa = id_daa & t4; +assign daa_x6 = (acc[3] & (acc[2] | acc[1])) | psw_ac; +assign daa_6x = ((acc[3] & (acc[2] | acc[1])) & acc[4] & acc[7]) + | (acc[7] & (acc[6] | acc[5])) | tmp_c; + +assign x = alu_xout ? xr : ~xr; +assign s = {7'b0000000, id_rlc & c[7]} + | ((id_rxc | id_ora | id_ana | id_xra) ? 8'h00 : (x + r + cl)) + | (id_rxc ? {ch, r[7:1]} : 8'h00) + | (id_ora ? (x | r) : 8'h00) + | (id_ana ? (x & r) : 8'h00) + | (id_xra ? (x ^ r) : 8'h00); + +assign cl = tmp_c & ~id_daa & ~id_rlc & ~id_ora & ~id_xra & ~id_rxc; +assign ch = tmp_c & id_rar | r[0] & ~id_rar; + +assign c[0] = (r[0] & x[0]) | (cl & (r[0] | x[0])); +assign c[1] = (r[1] & x[1]) | (c[0] & (r[1] | x[1])); +assign c[2] = (r[2] & x[2]) | (c[1] & (r[2] | x[2])); +assign c[3] = (r[3] & x[3]) | (c[2] & (r[3] | x[3])); +assign c[4] = (r[4] & x[4]) | (c[3] & (r[4] | x[4])); +assign c[5] = (r[5] & x[5]) | (c[4] & (r[5] | x[5])); +assign c[6] = (r[6] & x[6]) | (c[5] & (r[6] | x[6])); +assign c[7] = (r[7] & x[7]) | (c[6] & (r[7] | x[7])); + +assign alu_zrd = reset | (m1 & t3); +assign psw_ld = t3 & m4 & id_popsw; +assign psw_wr = t2 & m1 & (id_opi | id_inr | id_dcr | id_daa | id_op); +assign psw_oe = t2 & m5 & id_pupsw; + +always @(posedge clk) +if (ena) +begin + if (alu_xwr) xr <= id_rst ? (i & 8'b00111000) : d; + if (alu_awr) acc <= d; + if (alu_ald) acc <= s; + if (alu_rld) r <= acc; + if (alu_rwr) r <= d; + if (alu_r00) r <= 8'hff; + if (daa) + begin + r[1] <= daa_x6; + r[2] <= daa_x6; + r[5] <= daa_6x; + r[6] <= daa_6x; + end + if (psw_ld) + begin + psw_c <= d[0]; // x register was in original Intel design + psw_p <= d[2]; + psw_ac <= d[4]; + psw_z <= d[6]; + psw_s <= d[7]; + end + if (psw_wr) + begin + psw_p <= ~(^s); + psw_ac <= (c[3] & ~id_xra & ~id_ora & ~id_rxc) | (id_ana & (x[3] | r[3])); + psw_z <= ~(|s); + psw_s <= s[7]; + end + if (alu_pha) + begin + if (id_cmp | id_sbb | id_sub) psw_c <= id_rxc ? ~x[0] : ~c[7]; + if (id_dad | id_sha | id_adc | id_add) psw_c <= id_rxc ? x[0] : c[7]; + if (id_xra | id_stc | id_ora | id_ana | id_cmc) psw_c <= ~tmp_c; + end + if (daa & daa_6x) psw_c <= 1'b1; + + if ((t3 & m1) | (t2 & m5 & id_dad)) tmp_c <= psw_c; + if (t4) + begin + if (id_sbb) tmp_c <= ~psw_c; + if (id_dad | id_cma | id_dcr | id_add | id_stc) tmp_c <= 1'b0; + if (id_inr | id_ora | id_xra | id_ana | id_cmp | id_sub) tmp_c <= 1'b1; + end +end + +//______________________________________________________________________________ +// +endmodule diff --git a/1801BM1_vm80a/wbc/syn/de0/de0.sdc b/1801BM1_vm80a/wbc/syn/de0/de0.sdc new file mode 100644 index 0000000000000000000000000000000000000000..bed3a599c7fee21f5ca855e95e09e5e4bac427e5 --- /dev/null +++ b/1801BM1_vm80a/wbc/syn/de0/de0.sdc @@ -0,0 +1,124 @@ +## Generated SDC file "de0.out.sdc" + +## Copyright (C) 1991-2012 Altera Corporation +## Your use of Altera Corporation's design tools, logic functions +## and other software and tools, and its AMPP partner logic +## functions, and any output files from any of the foregoing +## (including device programming or simulation files), and any +## associated documentation or information are expressly subject +## to the terms and conditions of the Altera Program License +## Subscription Agreement, Altera MegaCore Function License +## Agreement, or other applicable license agreement, including, +## without limitation, that your use is for the sole purpose of +## programming logic devices manufactured by Altera and sold by +## Altera or its authorized distributors. Please refer to the +## applicable agreement for further details. + + +## VENDOR "Altera" +## PROGRAM "Quartus II" +## VERSION "Version 12.1 Build 243 01/31/2013 Service Pack 1 SJ Full Version" + +## DATE "Sat Feb 03 11:24:16 2018" + +## +## DEVICE "EP3C16F484C6" +## + + +#************************************************************** +# Time Information +#************************************************************** + +set_time_format -unit ns -decimal_places 3 + + + +#************************************************************** +# Create Clock +#************************************************************** + +create_clock -name {de0_clock_50_2} -period 20.000 -waveform { 0.000 10.000 } [get_ports {de0_clock_50_2}] + + +#************************************************************** +# Create Generated Clock +#************************************************************** + +create_generated_clock -name {corepll|altpll_component|auto_generated|pll1|clk[0]} -source [get_pins {corepll|altpll_component|auto_generated|pll1|inclk[0]}] -duty_cycle 50.000 -multiply_by 2 -master_clock {de0_clock_50_2} [get_pins {corepll|altpll_component|auto_generated|pll1|clk[0]}] + + +#************************************************************** +# Set Clock Latency +#************************************************************** + + + +#************************************************************** +# Set Clock Uncertainty +#************************************************************** + +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {de0_clock_50_2}] 0.020 +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {de0_clock_50_2}] 0.020 +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -setup 0.070 +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -hold 0.100 +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -setup 0.070 +set_clock_uncertainty -rise_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -hold 0.100 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {de0_clock_50_2}] 0.020 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {de0_clock_50_2}] 0.020 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -setup 0.070 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -hold 0.100 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -setup 0.070 +set_clock_uncertainty -fall_from [get_clocks {de0_clock_50_2}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -hold 0.100 +set_clock_uncertainty -rise_from [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] 0.020 +set_clock_uncertainty -rise_from [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] 0.020 +set_clock_uncertainty -fall_from [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -rise_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] 0.020 +set_clock_uncertainty -fall_from [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] -fall_to [get_clocks {corepll|altpll_component|auto_generated|pll1|clk[0]}] 0.020 + + +#************************************************************** +# Set Input Delay +#************************************************************** + + + +#************************************************************** +# Set Output Delay +#************************************************************** + + + +#************************************************************** +# Set Clock Groups +#************************************************************** + + + +#************************************************************** +# Set False Path +#************************************************************** + + + +#************************************************************** +# Set Multicycle Path +#************************************************************** + + + +#************************************************************** +# Set Maximum Delay +#************************************************************** + + + +#************************************************************** +# Set Minimum Delay +#************************************************************** + + + +#************************************************************** +# Set Input Transition +#************************************************************** + diff --git a/1801BM1_vm80a/wbc/tbe/de0_tb0.v b/1801BM1_vm80a/wbc/tbe/de0_tb0.v new file mode 100644 index 0000000000000000000000000000000000000000..e53fe4b499c82f9478b93777c207e93b77cdd37b --- /dev/null +++ b/1801BM1_vm80a/wbc/tbe/de0_tb0.v @@ -0,0 +1,189 @@ +// +// Copyright (c) 2014 by 1801BM1@gmail.com +// Licensed under CC-BY 3.0 (https://creativecommons.org/licenses/by/3.0/) +// +//______________________________________________________________________________ +// +// Simulation configuration parameters +// +`timescale 1ns / 100ps +// +// Simulation stops (breakpoint) after this time elapsed +// +`define SIM_CONFIG_TIME_LIMIT 100000 +// +// External clock frequency +// +`define SIM_CONFIG_CLOCK_HPERIOD 10 + +module tb80a(); + +//______________________________________________________________________________ +// +// DE board connection lines +// +reg clk50; +reg [2:0] button; +reg [9:0] switch; +wire [7:0] hex0; +wire [7:0] hex1; +wire [7:0] hex2; +wire [7:0] hex3; +wire [9:0] led; + +wire uart_txd; +reg uart_rxd; +wire uart_cts; +reg uart_rts; + +wire [15:0] dram_dq; // SDRAM data bus 16 bits +wire [12:0] dram_addr; // SDRAM address bus 13 bits +wire dram_ldqm; // SDRAM low-byte data mask +wire dram_udqm; // SDRAM high-byte data mask +wire dram_we_n; // SDRAM write enable +wire dram_cas_n; // SDRAM column address strobe +wire dram_ras_n; // SDRAM row address strobe +wire dram_cs_n; // SDRAM chip select +wire [1:0] dram_ba; // SDRAM bank address +wire dram_clk; // SDRAM clock +wire dram_cke; // SDRAM clock enable + // +wire [15:0] fl_dq; // FLASH data bus 15 Bits +wire [21:0] fl_addr; // FLASH address bus 22 Bits +wire fl_we_n; // FLASH write enable +wire fl_rst_n; // FLASH reset +wire fl_oe_n; // FLASH output enable +wire fl_ce_n; // FLASH chip enable +wire fl_wp_n; // FLASH hardware write protect +wire fl_byte_n; // FLASH selects 8/16-bit mode +wire fl_rb; // FLASH ready/busy + // +wire lcd_blig; // LCD back light ON/OFF +wire lcd_rw; // LCD read/write select, 0 = write, 1 = read +wire lcd_en; // LCD enable +wire lcd_rs; // LCD command/data select, 0 = command, 1 = data +wire [7:0] lcd_data; // LCD data bus 8 bits + // +wire sd_dat0; // SD Card Data 0 +wire sd_dat3; // SD Card Data 3 +wire sd_cmd; // SD Card Command Signal +wire sd_clk; // SD Card Clock +wire sd_wp_n; // SD Card Write Protect + // +wire ps2_kbdat; // PS2 Keyboard Data +wire ps2_kbclk; // PS2 Keyboard Clock +wire ps2_msdat; // PS2 Mouse Data +wire ps2_msclk; // PS2 Mouse Clock + // +wire vga_hs; // VGA H_SYNC +wire vga_vs; // VGA V_SYNC +wire [3:0] vga_r; // VGA Red[3:0] +wire [3:0] vga_g; // VGA Green[3:0] +wire [3:0] vga_b; // VGA Blue[3:0] + // +wire [1:0] gpio0_clkin; // GPIO Connection 0 Clock In Bus +wire [1:0] gpio0_clkout; // GPIO Connection 0 Clock Out Bus +wire [31:0] gpio0_d; // GPIO Connection 0 Data Bus + // +wire [1:0] gpio1_clkin; // GPIO Connection 1 Clock In Bus +wire [1:0] gpio1_clkout; // GPIO Connection 1 Clock Out Bus +wire [31:0] gpio1_d; // GPIO Connection 1 Data Bus + +initial +begin + clk50 = 0; + forever + begin + #`SIM_CONFIG_CLOCK_HPERIOD clk50 = 0; + #`SIM_CONFIG_CLOCK_HPERIOD clk50 = 1; + end +end + +initial +begin + uart_rxd = 1'b1; + uart_rts = 1'b0; + button = 3'b000; + switch = 10'h001; // SW0 turbo (100MHz)/slow (2.5MHz) mode + +#200 button = 3'b111; +end + +initial +begin + #`SIM_CONFIG_TIME_LIMIT $stop; +end + +de0 de0_top( + .de0_clock_50(clk50), + .de0_clock_50_2(clk50), + .de0_button(button), + .de0_sw(switch), + .de0_hex0(hex0), + .de0_hex1(hex1), + .de0_hex2(hex2), + .de0_hex3(hex3), + .de0_led(led), + + .de0_uart_txd(uart_txd), + .de0_uart_rxd(uart_rxd), + .de0_uart_cts(uart_cts), + .de0_uart_rts(uart_rts), + + .de0_dram_dq(dram_dq), + .de0_dram_addr(dram_addr), + .de0_dram_ldqm(dram_ldqm), + .de0_dram_udqm(dram_udqm), + .de0_dram_we_n(dram_we_n), + .de0_dram_cas_n(dram_cas_n), + .de0_dram_ras_n(dram_ras_n), + .de0_dram_cs_n(dram_cs_n), + .de0_dram_ba(dram_ba), + .de0_dram_clk(dram_clk), + .de0_dram_cke(dram_cke), + + .de0_fl_dq(fl_dq), + .de0_fl_addr(fl_addr), + .de0_fl_we_n(fl_we_n), + .de0_fl_rst_n(fl_rst_n), + .de0_fl_oe_n(fl_oe_n), + .de0_fl_ce_n(fl_ce_n), + .de0_fl_wp_n(fl_wp_n), + .de0_fl_byte_n(fl_byte_n), + .de0_fl_rb(fl_rb), + + .de0_lcd_blig(lcd_blig), + .de0_lcd_rw(lcd_rw), + .de0_lcd_en(lcd_en), + .de0_lcd_rs(lcd_rs), + .de0_lcd_data(lcd_data), + + .de0_sd_mosi(sd_dat0), + .de0_sd_miso(sd_dat3), + .de0_sd_cmd(sd_cmd), + .de0_sd_clk(sd_clk), + .de0_sd_wp_n(sd_wp_n), + + .de0_ps2_kbdat(ps2_kbdat), + .de0_ps2_kbclk(ps2_kbclk), + .de0_ps2_msdat(ps2_msdat), + .de0_ps2_msclk(ps2_msclk), + + .de0_vga_hs(vga_hs), + .de0_vga_vs(vga_vs), + .de0_vga_r(vga_r), + .de0_vga_g(vga_g), + .de0_vga_b(vga_b), + + .de0_gpio0_clkin(gpio0_clkin), + .de0_gpio0_clkout(gpio0_clkout), + .de0_gpio0_d(gpio0_d), + + .de0_gpio1_clkin(gpio1_clkin), + .de0_gpio1_clkout(gpio1_clkout), + .de0_gpio1_d(gpio1_d) +); + +//_____________________________________________________________________________ +// +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/DEV_NOTES.md b/MiSTer-devel_NeoGeo_MiSTer/DEV_NOTES.md new file mode 100644 index 0000000000000000000000000000000000000000..9bdbb53728e3b8f1c865711f7988a4ccdb532ea7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/DEV_NOTES.md @@ -0,0 +1,242 @@ +These notes were written for myself/my setup but many points could be useful for others. + +# MiSTer basics +The code running on the HPS (ARM CPU) loads the requested core as an .rbf file via fpga_load_rbf in fpga_io.cpp in Main_MiSTer. + +In each core, the files in /sys/ provide the common functionalities: video scaling, video and audio output, the OSD, and the HPS interface logic. The hps_io module "breaks out" a bunch of signals for the core to utilize. + +The core must be held in reset and provide access to the SDRAM controller and BRAM for the HPS during ROM loading. It can then switch to run mode and start using the data itself. + +To connect to the DE10 via ethernet: run `D:\OpenDHCPServer\runstandalone.bat` +**NOTE**: It may already be running as a service ! Make sure the LAN connection is enabled in the Windows network control panel. By matching its MAC address, the DE10 will be assigned IP 192.168.1.200. It's then possible to use FTP or SSH with root:1 as login. + +To debug linux-side stuff (Main_MiSTer): +Putty `root:1@192.168.1.200`, `killall MiSTer` so that the binary file can be replaced, Ctrl+shift+B in VS to build, upload new binary via FTP, sync, and run `/media/fat/MiSTer`. + +neogeo-lite allows for faster compilation time by omitting the HDMI scaler, it outputs 6-6-6 VGA video and stereo audio on the GPIO_1 header as follows: +``` +Bottom header, pin 1 is upper right + _39________________________________________________________01 +| | +| G0 G1 G2 G3 G4 +3 G5 B3 B4 B5 VS -- -- -- +5 RA -- -- -- -- | +| | +| R0 R1 R2 R3 R4 gn R5 B2 B1 B0 HS -- -- -- gn gn -- -- -- LA | +|_____________________________________________________________| + 40 02 +``` +Pin 10 has to be connected to ground to enable the VGA output. This is used to detect the IO extension board. + +# NeoGeo core specifics + +The generated .rbf is `output_files\neogeo-lite.rbf` + +The ROM files are normally loaded by user_io_file_tx from user_io.cpp. For this core, neogeo_romset_tx from `/support/neogeo/loader.cpp` is used instead. + +## Save files for cartridge games + +Data | Start | End +---- | ---- | ---- +Backup RAM | 000000 | 00FFFF +Memory card | 010000 | 0107FF + +## Save file for CD systems + +Data | Start | End +---- | ---- | ---- +Memory card | 000000 | 001FFF + +## SDRAM multiplexing +The SDRAM extension board stores the 68k program, sprites and fix graphics. +It currently runs at 120MHz (5*24M) but may be pushed up to 144MHz (6*24M) if needed. + +### 68k data +Read as soon as nSROMOE (system ROM read), nROMOE (cart ROM read) or nPORTOE (cart ROM extension read) goes low. +Right now, the 68k always runs with 1 wait cycle :( + +An attempt was made to fetch 68k data 4 words at a time with burst reads, but it didn't seem to be very reliable. Try again ? + +### Fix graphics +Read as soon as PCK2B rises. +Since the SDRAM provides 16-bit words and there's only an 8-bit data bus for the fix (2 pixels), one SDRAM read gives 4 pixels. +The fix data is re-organized during loading so that pixel pairs are kept adjacent in the SDRAM. This allows to do only one read for 4 pixels and use S2H1 to select which pair must be fed to NEO-B1 at the right time. + +An attempt was made to fetch fix data 2 words at a time with burst reads to have the whole 8 pixel line at once. It worked but it seems better to have multiple shorter reads for more efficient SDRAM access interleave. + +FIXD is latched on rising edge of CLK_1MB. + +### Sprite graphics +Read as soon as PCK1B rises. +The sprite graphics data bus is 32-bit, so for one 8-pixel line, two words must be read. +The sprite data is re-organized during so that the bitplane data can be read in 4-word bursts and used as-is. The PCK1B edge is used to trigger the reads, and CA4 is used to select which 8-pixel group must be fed to NEO-ZMC2 at the right time. + +CR is latched on rising edge of CLK_12M when LOAD is high. + +## Loading + +Fix graphics are loaded in a way that takes advantage of the 16-bit wide SDRAM data bus. + +Since fix pixels are stored in pairs in columns but always read in lines, instead of storing: +`column 2 (lines 0~7), column 3 (lines 0~7), column 0 (lines 0~7), column 1 (lines 0~7)` + +Load like: +`line 0 (columns 0~3), line 1 (columns 0~3)...` + +Sprite graphics bytes are loaded like this: +C2 C2 C1 C1 C2 C2 C1 C1... + +So bitplanes for a single line look like this: +0 1 2 3 0 1 2 3... + +Complete 16-pixel line: 4*16 = 64 bits = four 16-bit SDRAM words + +ioctl_index is used to tell the core where to store the data being loaded. The currently used values are: +* 0: System ROM (BIOS) +* 1: LO ROM +* 2: SFIX ROM +* 4: P1 ROM first half (or full) +* 5: P1 ROM second half +* 6: P2 ROM +* 8: S1 ROM +* 9: M1 ROM +* 16+: V ROMs, add 512kB bank number +* 64+: C ROMs, the lower 6 bits are used as a bitfield like this: + x1BBBBBS + B: 512kB bank number + S: word shift (used to interleave odd/even ROMs) + So SDRAM address = 0x0800000 + 0b1_BBBBB000_00000000_000000S0 + ioctl_addr + +## romsets.xml file + +* hw: Special cart chip. 0=None, 1=PRO-CT0, 2=Link MCU, 3=NEO-CMC +* pcm: 0=Game uses separate V1x and V2x ROMs, 1=Game uses PCM chip with V1, V2... ROMs +* type: P (68k program), S (fix gfx), C (sprite gfx), M (z80 program) or V (voice samples). See ROM file extension. +* offset: Where to start reading in file. +* size: How many bytes to load. +* index: Where to start writing data in SDRAM. Depends on type. + * P: 4=First P1 half (0x000000), 5=Second P1 half (0x080000), 6=P2 (0x200000) + * S: Always 8 + * M: Always 9 + * V: 16 + (512kB bank). Non-PCM games must have their .v1x ROMs between 16-47, and their .v2x ROMs between 48-63 + * C: 64 + (0=odd, 1=even) + (1MB bank * 2) + +## BRAM zones + +Memory | Size +------ | ---- +68k RAM | 64kB +Z80 RAM | 2kB +Slow VRAM | 64kB +Fast VRAM | 4kB +Palette RAM | 16kB +Line buffers | 9kB +LO ROM | 64kB +M1 ROM | 128kB +Memory card | 2kB +Backup RAM | 32kB +------ | ---- +Total | 385kB + +## SDRAM cart map + +See [sdram_map.odg](sdram_map.odg) + +Memory | Size | Start | End +------ | ---- | ----- | --- +P1 ROM | 1MB | 0000000 | 00FFFFF +P2 ROMs | 4MB | 0200000 | 05FFFFF +System ROM | 128kB | 0600000 | 061FFFF +SFIX ROM | 128kB | 0620000 | 063FFFF +Free | 256kB | 0640000 | 067FFFF +S ROM | 512kB | 0680000 | 06FFFFF +Free | 1MB | 0700000 | 07FFFFF +C ROM | 24MB | 0800000 | 1FFFFFF + +Games using NEO-CMC are able to bankswitch S ROMs larger than 128kB + +## SDRAM CD map + +See [sdram_map.odg](sdram_map.odg) + +Memory | Size | Start | End +------ | ---- | ----- | --- +P1 ROM | 1MB | 0000000 | 00FFFFF +Extended RAM | 1MB | 0100000 | 01FFFFF +Free | 4MB | 0200000 | 05FFFFF +System ROM | 512kB | 0600000 | 067FFFF +S ROM | 512kB | 0680000 | 06FFFFF +Free | 1MB | 0700000 | 07FFFFF +C ROM | 4MB | 0800000 | 0BFFFFF +Free | 20MB | 0C00000 | 1FFFFFF + +## Neo CD loading notes + +``` +To load sectors, the Neo CD does this: +-Starts playing CD at requested MSF - 3 + MSF must be given to the LC8951 module to be copied back in the HEAD registers + Start requesting sectors from HPS with interval timer + Wait a bit to let the system ROM set up the IRQ masks ? +-Enables CDC interrupts +-Sets CMDIEN, DTEIEN, DECIEN and DOUTEN +-Sets DECEN, E01RQ, WRRQ, QRQ and PRQ +-Sets SYIEN, SYDEN, DSCREN, COWREN +-Waits for the CDC decoder interrupt + Trigger the decoder interrupt (CDC_nIRQ) when the HPS has finished sending a sector +-Reads STAT3 to clear the IRQ +-Does the same thing over again (to let at least one sector go by ?) + Need to trigger the decoder interrupt again ? Should have to do that only once per play +-At the second CDC decoder interrupt: +-Checks STAT1 to see if there aren't any error flags +-Checks STAT3 to see if the decoder status is valid +-Reads the HEAD registers, compares them with the requested MSF, if so: +-Reads the STAT registers, checks if there aren't any error flags in STAT0 and CRC OK bit +-Reads PT + Can always be 0004 (skips sector header bytes), the Neo CD doesn't care if it changes or not +-Sets DBC to $7FF (2048-1 bytes) +-Sets DAC to PT-4 + So DAC should always be set to 0000 +-Sets up LC8953 DMA to retrieve 2048 bytes + This triggers the DMA copy from the cache to the CD sector buffer at $111204 +-After copy is done, increment MFS (pulse MSF_INC) +-Decrements sector counter until 0 +``` + +## Neo CD fix data notes + +``` +Normal fix data bytes: +10 18 00 08 +11 19 01 09 +12 1A 02 0A +13 1B 03 0B +14 1C 04 0C +15 1D 05 0D +16 1E 06 0E +17 1F 07 0F + +SDRAM organization words: +10-18 00-08 11-19 01-09 12-1A 02-0A 13-1B 03-0B... + +The Neo CD will write fix data as bytes so two byte writes would have to be grouped in +one SDRAM word write, but that won't work with the byte address remapping. It would require +a 32 byte buffer which would be burst written and it would be a mess... +Instead of that, just use LDQM/UDQM to do byte writes with the remapped address directly. + +addr_out = ?, addr_in[...:0], ~addr_in[4], addr_in[3] +00 -> 02 +01 -> 06 +02 -> 0A +... +07 -> 1E + +08 -> 03 +09 -> 07 +... + +10 -> 00 +11 -> 04 +... + +18 -> 01 +19 -> 05 +``` diff --git a/MiSTer-devel_NeoGeo_MiSTer/NeoGeo.sdc b/MiSTer-devel_NeoGeo_MiSTer/NeoGeo.sdc new file mode 100644 index 0000000000000000000000000000000000000000..a6b805c497742d2dcf64673a56d15e71196c8c29 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/NeoGeo.sdc @@ -0,0 +1,7 @@ +derive_pll_clocks +derive_clock_uncertainty + +set_false_path -from {emu|cfg[*]} + +set_multicycle_path -from {emu|Z80CPU|*} -setup 2 +set_multicycle_path -from {emu|Z80CPU|*} -hold 1 diff --git a/MiSTer-devel_NeoGeo_MiSTer/README.md b/MiSTer-devel_NeoGeo_MiSTer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..554a664c71480becff4a92871f12a4c7195b4146 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/README.md @@ -0,0 +1,47 @@ + +# [SNK Neo Geo](https://en.wikipedia.org/wiki/Neo_Geo_(system)) for [MiSTer Platform](https://github.com/MiSTer-devel/Main_MiSTer/wiki) + +This is an FPGA implementation of the NEO GEO/MVS system by [Furrtek](https://www.patreon.com/furrtek/posts) + +## Features +* Supports memory card saving +* MVS, AES, and CD system support +* Compatible with Darksoft ROM sets using provided XML +* Compatible with decrypted MAME ROM sets using your own XML +* Compatible with decrypted .neo ROM sets +* Compatible with gog.com ROMs using provided XML +* Support for Universe BIOS + +Note: This core does not support encrypted ROMs. Make sure the ROM has no encrypted parts before using. MAME ROM pack includes many encrypted ROMs so it's not recommended for inexperienced users. Using the .neo conversion tool with a MAME ROM set will result in some ROMs still being encrypted. There is an alternate .neo conversion tool for the Darksoft ROM set that will give you a fully decrypted set. + +* [MAME to .neo conversion tool (by Matt Greer)](https://github.com/city41/neosdconv) +* [MAME to .neo conversion tool (by Rupert Carmichael)](https://github.com/carmiker/neoconv) +* [Darksoft to .neo conversion tool](https://gitlab.com/loic.petit/darksoft-to-neosd/) + +## Installation +Copy the NeoGeo_\*.rbf file to the 'Console' or 'Arcade' folder (your choice) on the SD card. ROMs should go in the 'games\NeoGeo' folder. For ease of use, it is strongly suggested that people use the Darksoft ROM pack. These can be either zipped or unzipped with minimal loading speed difference. Several things must be observed: +* When using an unzipped Darksoft ROM set, each game's ROM files must be in their own folder and the folders containing the ROM sets must be named to match the XML (MAME standard names) +* ROMs can be placed inside sub-folders for organization +* Zipped ROMs must **not** contain folders. + +In addition, several bios files must be placed in the 'games\NeoGeo' folder for the core to function properly: +* 000-lo.lo +* sfix.sfix +* sp-s2.sp1 (MVS) +* neo-epo.sp1 (AES) +* uni-bios.rom + +These bios files must be placed in the 'games\NeoGeo-CD' folder: +* top-sp1.bin (CD) +* neocd.bin (CDZ) +* uni-bioscd.rom (CD and CDZ) + +Sometimes these files may be named slightly different depending on where they are obtained, but they must be renamed to match the filenames above to work with MiSTer. You may choose between using the original system BIOS (sp-s2.sp1/neo-epo.sp1) or UniBios (uni-bios.rom). Using UniBios is recommended, and can be obtained [here](http://unibios.free.fr/). + +Lastly, **romsets.xml** from the release folder must also be placed in the directory. The provided XML is for Darksoft ROMs only, you must make your own for MAME ROMs. This file describes to the core where the ROM sets are located and how to load them. **gog-romsets.xml** can be used (renamed to **romsets.xml**) for games purchased from gog.com (which also include all the needed bios files), see comments in gog-romsets.xml . + +## Saving and Loading +In AES mode, all saves are to the memory card only. In MVS mode, some games and UniBios save their settings to a special area of battery backed ram built into the system, while game data can still be saved to a memory card. + +## RAM and Game Sizes +Neo Geo uses very large ROMs. About 84% of the library will fit onto a 32 megabyte SDRAM module. Another 12% will fit onto a 64 megabyte SDRAM module. The remaining 8 games require a 128 megabyte module. For more information about which games can be loaded with which sized RAM, open romsets.xml in your favorite text editor or github. The games are organized by size. diff --git a/MiSTer-devel_NeoGeo_MiSTer/neogeo.sv b/MiSTer-devel_NeoGeo_MiSTer/neogeo.sv new file mode 100644 index 0000000000000000000000000000000000000000..c237adcbb65af438f427450208779a2d444961c3 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/neogeo.sv @@ -0,0 +1,2120 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// Current status: +// Neo CD CD check ok but crashes when loading. No more video glitches. + +// How about not using a cache at all and DMAing directly from the data fed by the HPS ? +// The "sector ready" IRQ could be triggered just when a sector is requested, and the actual transfer +// could be done when the system ROM starts up the DMA transfer ? + +// Neo CD times 12/05/2019: +// SECTOR_READY goes high at SECTOR_TIMER == 430631 +// So it takes 600000-430631=169369 ticks to get a sector from HPS +// 169369/120M=1.41ms (1451 kB/s) +// DMA copy: 215 ticks for 10 bytes +// So 215/120M/10=179.17ns per byte (5450 kB/s) + +// Neo CD times 11/05/2019: +// DMA copy: 616 ticks for 10 bytes +// So 215/120M/10=513.3ns per byte (1902 kB/s) + +module emu +( + `include "sys/emu_ports.vh" +); + +assign ADC_BUS = 'Z; +assign USER_OUT = '1; +assign {UART_RTS, UART_TXD, UART_DTR} = 0; +assign {SD_SCK, SD_MOSI, SD_CS} = 'Z; + +assign AUDIO_S = 1; // Signed +assign AUDIO_MIX = status[6:5]; +assign AUDIO_L = snd_mix_l[16:1]; +assign AUDIO_R = snd_mix_r[16:1]; + +assign LED_USER = status[0] | bk_pending; +assign LED_DISK = 0; +assign LED_POWER = 0; +assign BUTTONS = osd_btn; +assign VGA_SCALER= 0; +assign VGA_DISABLE = 0; +assign HDMI_FREEZE = 0; +assign HDMI_BLACKOUT = 0; +assign HDMI_BOB_DEINT = 0; + +wire [1:0] ar = status[33:32]; +wire vcrop_en = status[34]; +wire [3:0] vcopt = status[38:35]; +reg en216p; +reg [4:0] voff; +always @(posedge CLK_VIDEO) begin + en216p <= ((HDMI_WIDTH == 1920) && (HDMI_HEIGHT == 1080) && !forced_scandoubler && !scale); + voff <= (vcopt < 6) ? {vcopt,1'b0} : ({vcopt,1'b0} - 5'd24); +end + +wire vga_de; +video_freak video_freak +( + .*, + .VGA_DE_IN(vga_de), + .ARX((!ar) ? 12'd10 : (ar - 1'd1)), + .ARY((!ar) ? 12'd7 : 12'd0), + .CROP_SIZE((en216p & vcrop_en) ? 10'd216 : 10'd0), + .CROP_OFF(voff), + .SCALE(status[40:39]) +); + +// status bit definition: +// 31 23 15 7 +// --AA-PSS -------- L--CGGDD DEEMVTTR +// : status[0] System Reset, used by the HPS, keep it there +// T: status[2:1] System type, 0=Console, 1=Arcade, 2=CD, 3=CDZ +// V: status[3] Video mode +// M: status[4] Memory card presence +// E: status[6:5] Stereo mix +// D: status[9:7] DIP switches +// G: status[11:10] Neo CD region +// C: status[12] Save memory card & backup RAM +// L: status[12] CD lid state (DEBUG) +// : status[14] Manual Reset +// : status[20:15] OSD options +// 0123456789 ABCDEFGHIJKLMNO + +// Conditional modification of the CONF strings chaining according to chosen system type +// Con Arc CD CDz +// 00 01 10 11 +// F F + + ~SYSTEM_CDx; +// + + S S SYSTEM_CDx; +// O O + + ~SYSTEM_CDx; +// + O + + SYSTEM_MVS; +// + + O O SYSTEM_CDx; + +// Status Bit Map: +// Upper Lower +// 0 1 2 3 4 5 6 +// 01234567890123456789012345678901 23456789012345678901234567890123 +// 0123456789ABCDEFGHIJKLMNOPQRSTUV 0123456789ABCDEFGHIJKLMNOPQRSTUV +// XXXXXXXXXXXXX XXX XXXXX XXXXXXX XXXXXXXXXXXXX XXXXXX + +`include "build_id.v" +localparam CONF_STR = { + "NEOGEO;;", + "-;", + "FS1,*,Load ROM set;", + "S1,CUECHD,Load CD Image;", + "-;", + "H3OP,FM,ON,OFF;", + "H3OQ,ADPCMA,ON,OFF;", + "H3OR,ADPCMB,ON,OFF;", + "H3OS,PSG,ON,OFF;", + "H3oP,ADPCMA CH 1,ON,OFF;", + "H3oQ,ADPCMA CH 2,ON,OFF;", + "H3oR,ADPCMA CH 3,ON,OFF;", + "H3oS,ADPCMA CH 4,ON,OFF;", + "H3oT,ADPCMA CH 5,ON,OFF;", + "H3oU,ADPCMA CH 6,ON,OFF;", + "H3-;", + "O1,System Type,Console(AES),Arcade(MVS);", + "OM,BIOS,UniBIOS,Original;", + "O3,Video Mode,NTSC,PAL;", + "-;", + "o9A,Input,Joystick or Spinner,Joystick,Spinner,Mouse(Irr.Maze);", + "oBC,Multitap,No,NEO-FTC1B,NeoTris;", + "-;", + "H0O4,Memory Card,Plugged,Unplugged;", + "RL,Reload Memory Card;", + "D4RC,Save Memory Card;", + "OO,Autosave,OFF,ON;", + "-;", + "O2,CD Type,CD,CDZ;", + "OTU,CD Speed,1x,2x,3x,4x;", + "OAB,CD Region,US,EU,JP,AS;", + "OF,CD lid,Closed,Opened;", + "H2-;", + "H2O7,[DIP] Settings,OFF,ON;", + "H2O8,[DIP] Freeplay,OFF,ON;", + "H2O9,[DIP] Freeze,OFF,ON;", + "-;", + "P1,Audio & Video;", + "P1-;", + "P1OG,Width,320px,304px;", + "P1o01,Aspect ratio,Original,Full Screen,[ARC1],[ARC2];", + "P1OIK,Scandoubler Fx,None,HQ2x,CRT 25%,CRT 50%,CRT 75%;", + "P1-;", + "d5P1o2,Vertical Crop,Disabled,216p(5x);", + "d5P1o36,Crop Offset,0,2,4,8,10,12,-12,-10,-8,-6,-4,-2;", + "P1o78,Scale,Normal,V-Integer,Narrower HV-Integer,Wider HV-Integer;", + "P1-;", + "P1O56,Stereo Mix,none,25%,50%,100%;", + "P1-;", + "-;", + "RE,Reset & apply;", // decouple manual reset from system reset + "J1,A,B,C,D,Start,Select,Coin,ABC,A+B,C+D;", // ABC is a special key to press A+B+C at once, useful for keyboards that don't allow more than 2 keypresses at once; A+B/C+D are useful for fighting games (Samurai Shodown, Garou, etc.) + "jn,A,B,X,Y,Start,Select,L,R,L2,R2;", // name mapping + "jp,B,A,D,C,Start,Select,L,R,L2,R2;", // positional mapping consistent with NeoGeoCD controller + "V,v",`BUILD_DATE // +}; + + +//////////////////// CLOCKS /////////////////// + +wire locked; +wire CLK_48M, CLK_96M; +assign CLK_VIDEO = CLK_48M; +wire clk_sys = CLK_48M; + +pll pll +( + .refclk(CLK_50M), + .rst(0), + .outclk_0(CLK_96M), + .outclk_1(CLK_48M), + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll), + .locked(locked) +); + +reg CLK_EN_24M_N, CLK_EN_24M_P; +always @(posedge CLK_48M) begin + CLK_EN_24M_N <= ~CLK_EN_24M_N; + CLK_EN_24M_P <= CLK_EN_24M_N; +end + +wire [63:0] reconfig_to_pll; +wire [63:0] reconfig_from_pll; +wire cfg_waitrequest; +reg cfg_write; +reg [5:0] cfg_address; +reg [31:0] cfg_data; + +pll_cfg pll_cfg +( + .mgmt_clk(CLK_50M), + .mgmt_reset(0), + .mgmt_waitrequest(cfg_waitrequest), + .mgmt_read(0), + .mgmt_readdata(), + .mgmt_write(cfg_write), + .mgmt_address(cfg_address), + .mgmt_writedata(cfg_data), + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll) +); + +always @(posedge CLK_50M) begin + reg sys_mvs = 0, sys_mvs2 = 0; + reg [2:0] state = 0; + reg sys_mvs_r; + + sys_mvs <= SYSTEM_MVS; + sys_mvs2 <= sys_mvs; + + cfg_write <= 0; + if(sys_mvs2 == sys_mvs && sys_mvs2 != sys_mvs_r) begin + state <= 1; + sys_mvs_r <= sys_mvs2; + end + + if(!cfg_waitrequest) begin + if(state) state<=state+1'd1; + case(state) + 1: begin + cfg_address <= 0; + cfg_data <= 0; + cfg_write <= 1; + end + 5: begin + cfg_address <= 7; + cfg_data <= sys_mvs_r ? 2576980378 : 2865308404; + cfg_write <= 1; + end + 7: begin + cfg_address <= 2; + cfg_data <= 0; + cfg_write <= 1; + end + endcase + end +end + +reg [14:0] TRASH_ADDR; +reg SYSTEM_TYPE, SYSTEM_CD_TYPE; + +reg nRESET_CORE; +always @(posedge CLK_48M) begin + reg rst_n; + reg got_rom_write = 0; + + if (RESET) got_rom_write <= 0; + if (ioctl_download & ioctl_wr) got_rom_write <= 1; + + nRESET_CORE <= rst_n; + rst_n <= &TRASH_ADDR; + if(CLK_EN_24M_N && ~&TRASH_ADDR) TRASH_ADDR <= TRASH_ADDR + 1'b1; + + if (status[0] | status[14] | buttons[1] | bk_loading | RESET | ~got_rom_write) begin + TRASH_ADDR <= 0; + SYSTEM_TYPE <= status[1]; // Latch the system type on reset + SYSTEM_CD_TYPE <= status[2]; + end +end + +reg osd_btn = 0; +always @(posedge CLK_48M) begin + integer timeout = 0; + reg last_rst = 0; + + if (RESET) last_rst <= 0; + if (status[0]) last_rst <= 1; + + if (last_rst & ~status[0]) begin + osd_btn <= 0; + if(timeout < 48000000) begin + timeout <= timeout + 1; + osd_btn <= 1; + end + end +end + +////////////////// HPS I/O /////////////////// + +// VD 0: Save file +wire [1:0] img_mounted; +wire sd_buff_wr, img_readonly; +wire [7:0] sd_buff_addr; // Address inside 256-word sector +wire [15:0] sd_buff_dout; +wire [15:0] sd_buff_din[2]; +wire [15:0] sd_req_type; +wire [63:0] img_size; +wire [31:0] sd_lba[2]; +wire [1:0] sd_wr; +wire [1:0] sd_rd; +wire [1:0] sd_ack; + +wire [15:0] joystick_0; // 21--HNLS DCBAUDLR (1=A+B, 2=C+D combos) +wire [15:0] joystick_1; +wire [15:0] joystick_2; +wire [15:0] joystick_3; +wire [8:0] spinner_0, spinner_1; +wire [1:0] buttons; +wire [10:0] ps2_key; +wire [24:0] ps2_mouse; +wire forced_scandoubler; +wire [63:0] status; + +wire [64:0] rtc; + +wire ioctl_wr; +wire [26:0] ioctl_addr; +wire [15:0] ioctl_dout; +wire ioctl_download; +wire [7:0] ioctl_idx; + +wire SYSTEM_MVS = SYSTEM_TYPE & ~cd_en; +wire SYSTEM_CDx = cd_en; +wire SYSTEM_CDZ = SYSTEM_CDx & SYSTEM_CD_TYPE; + +wire [15:0] sdram_sz; +wire [21:0] gamma_bus; + +hps_io #(.CONF_STR(CONF_STR), .WIDE(1), .VDNUM(2)) hps_io +( + .clk_sys(clk_sys), + .HPS_BUS(HPS_BUS), + + .forced_scandoubler(forced_scandoubler), + + .joystick_0(joystick_0), .joystick_1(joystick_1), + .joystick_2(joystick_2), .joystick_3(joystick_3), + .spinner_0(spinner_0), .spinner_1(spinner_1), + .ps2_mouse(ps2_mouse), + .buttons(buttons), + .ps2_key(ps2_key), + + .status(status), // status read (32 bits) + .status_menumask({status[22], 9'd0, en216p, bk_autosave | ~bk_pending, ~dbg_menu,~SYSTEM_MVS,1'b0,SYSTEM_CDx}), + + .RTC(rtc), + .sdram_sz(sdram_sz), + .gamma_bus(gamma_bus), + + // Loading signals + .ioctl_wr(ioctl_wr), + .ioctl_addr(ioctl_addr), + .ioctl_dout(ioctl_dout), + .ioctl_download(ioctl_download), + .ioctl_index(ioctl_idx), + .ioctl_wait((ddr_loading & ddram_wait) | memcp_wait), + + .sd_lba(sd_lba), + .sd_rd(sd_rd), + .sd_wr(sd_wr), + .sd_ack(sd_ack), + .sd_buff_addr(sd_buff_addr), + .sd_buff_dout(sd_buff_dout), + .sd_buff_din(sd_buff_din), + .sd_buff_wr(sd_buff_wr), + + .img_mounted(img_mounted), + .img_readonly(img_readonly), + .img_size(img_size), + + .EXT_BUS(EXT_BUS) +); + +reg [7:0] ioctl_index; +always @(posedge clk_sys) ioctl_index <= ioctl_idx; + +reg dbg_menu = 0; +always @(posedge clk_sys) begin + reg old_stb; + reg enter = 0; + reg esc = 0; + + old_stb <= ps2_key[10]; + if(old_stb ^ ps2_key[10]) begin + if(ps2_key[7:0] == 'h5A) enter <= ps2_key[9]; + if(ps2_key[7:0] == 'h76) esc <= ps2_key[9]; + end + + if(enter & esc) begin + dbg_menu <= ~dbg_menu; + enter <= 0; + esc <= 0; + end +end + +////////////////// Her Majesty /////////////////// + +reg [31:0] cfg = 0; +wire [15:0] snd_right; +wire [15:0] snd_left; + +wire nRESET, nRESETP, nSYSTEM, CARD_WE, SHADOW, nVEC, nREGEN, nSRAMWEN, PALBNK; +wire CD_nRESET_Z80; + +// Clocks +wire CLK_EN_12M, CLK_EN_12M_N, CLK_68KCLK, CLK_68KCLKB, CLK_EN_6MB, CLK_EN_1HB, CLK_EN_4M_P, CLK_EN_4M_N, CLK_EN_68K_P, CLK_EN_68K_N; + +// 68k stuff +wire [15:0] M68K_DATA; +wire [23:1] M68K_ADDR; +wire A22Z, A23Z; +wire M68K_RW, nAS, nLDS, nUDS, nDTACK, nHALT, nBR, nBG, nBGACK; +wire [15:0] M68K_DATA_BYTE_MASK; +wire [15:0] FX68K_DATAIN; +wire [15:0] FX68K_DATAOUT; +wire IPL0, IPL1; +wire FC0, FC1, FC2; +reg [3:0] P_BANK; + +// RTC stuff +wire RTC_DOUT, RTC_DIN, RTC_CLK, RTC_STROBE, RTC_TP; + +// OEs and WEs +wire nSROMOEL, nSROMOEU, nSROMOE; +wire nROMOEL, nROMOEU; +wire nPORTOEL, nPORTOEU, nPORTWEL, nPORTWEU, nPORTADRS; +wire nSRAMOEL, nSRAMOEU, nSRAMWEL, nSRAMWEU; +wire nWRL, nWRU, nWWL, nWWU; +wire nLSPOE, nLSPWE; +wire nPAL, nPAL_WE; +wire nBITW0, nBITW1, nBITWD0, nDIPRD0, nDIPRD1; +wire nSDROE, nSDPOE; + +// RAM outputs +wire [7:0] WRAML_OUT; +wire [7:0] WRAMU_OUT; +wire [15:0] SRAM_OUT; +wire [7:0] CD_Z80_RAM_OUT; + +wire [14:0] WRAM_ADDR; +wire [7:0] WRAML_DATA, WRAMU_DATA; +wire WRAML_WREN, WRAMU_WREN; + +// Memory card stuff +wire [23:0] CDA; +wire [2:0] BNK; +wire [7:0] CDD; +wire nCD1, nCD2; +wire nCRDO, nCRDW, nCRDC; +wire nCARDWEN, CARDWENB; + +// Z80 stuff +wire [7:0] SDD_IN, SDD_OUT, Z80_SDD_OUT; +wire [7:0] SDD_RD_C1; +wire [15:0] SDA, Z80_SDA; +wire nSDRD, nSDWR, nMREQ, nIORQ, nBUSAK; +wire Z80_nSDRD, Z80_nSDWR, Z80_nMREQ; +wire Z80_nINT, Z80_nNMI, nSDW, nSDZ80R, nSDZ80W, nSDZ80CLR; +wire nSDROM, nSDMRD, nSDMWR, SDRD0, SDRD1, nZRAMCS; +wire n2610CS, n2610RD, n2610WR; + +// Graphics stuff +wire [23:0] PBUS; +wire [7:0] LO_ROM_DATA; +wire nPBUS_OUT_EN; + +wire [19:0] C_LATCH; +reg [3:0] C_LATCH_EXT; +wire [63:0] CR_DOUBLE; +wire [26:0] CROM_ADDR; + +wire [1:0] FIX_BANK; +wire [15:0] S_LATCH; +wire [7:0] FIXD; +wire [10:0] FIXMAP_ADDR; + +wire CWE, BWE, BOE; + +wire [14:0] SLOW_VRAM_ADDR; +reg [15:0] SLOW_VRAM_DATA_IN; +wire [15:0] SLOW_VRAM_DATA_OUT; + +wire [10:0] FAST_VRAM_ADDR; +wire [15:0] FAST_VRAM_DATA_IN; +wire [15:0] FAST_VRAM_DATA_OUT; + +wire [11:0] PAL_RAM_ADDR; +wire [15:0] PAL_RAM_DATA; +reg [15:0] PAL_RAM_REG; + +wire PCK1, PCK2, EVEN1, EVEN2, LOAD, H; +wire PCK1_EN_P, PCK2_EN_P; +wire PCK1_EN_N, PCK2_EN_N; +wire DOTA, DOTB; +wire CA4, S1H1, S2H1; +wire CHBL, nBNKB, VCS; +wire CHG, LD1, LD2, SS1, SS2; +wire [3:0] GAD; +wire [3:0] GBD; +wire [3:0] WE; +wire [3:0] CK; + +wire CD_VIDEO_EN, CD_FIX_EN, CD_SPR_EN; + +// SDRAM multiplexing stuff +wire [15:0] SROM_DATA; +wire [15:0] PROM_DATA; + +parameter INDEX_SPROM = 0; +parameter INDEX_LOROM = 1; +parameter INDEX_SFIXROM = 2; +parameter INDEX_P1ROM_A = 4; +parameter INDEX_P1ROM_B = 5; +parameter INDEX_P2ROM = 6; +parameter INDEX_S1ROM = 8; +parameter INDEX_M1ROM = 9; +parameter INDEX_MEMCP = 10; +parameter INDEX_CROM0 = 15; +parameter INDEX_VROMS = 16; +parameter INDEX_CROMS = 64; + +wire video_mode = status[3]; + +wire ms5p_bank = cfg[17]; +wire xram = cfg[18]; +wire adpcma_ext = cfg[19]; +wire [2:0] cart_pchip = cfg[22:20]; +wire use_pcm = cfg[23]; +wire [1:0] cart_chip = cfg[25:24]; // legacy option: 0 - none, 1 - PRO-CT0, 2 - Link MCU +wire [1:0] cmc_chip = cfg[27:26]; // type 1/2 +wire rom_wait = cfg[28]; // ROMWAIT from cart. 0 - Full speed, 1 - 1 wait cycle +wire [1:0] p_wait = cfg[30:29]; // PWAIT from cart. 0 - Full speed, 1 - 1 wait cycle, 2 - 2 cycles +wire cd_en = cfg[31]; // Neo CD + +// Memory card and backup ram image save/load +assign sd_rd[0] = bk_rd; +assign sd_wr[0] = bk_wr; +assign sd_lba[0] = bk_lba; +assign sd_buff_din[0] = bk_dout; +wire bk_ack = sd_ack[0]; + +assign sd_rd[1] = 0; +assign sd_wr[1] = 0; +assign sd_buff_din[1] = 0; +assign sd_lba[1] = 0; + +wire downloading = status[0]; +reg bk_rd, bk_wr; +reg bk_ena = 0; +reg bk_pending = 0; +reg [31:0] bk_lba; + +wire bk_autosave = status[24]; +// Memory write flag for backup memory & memory card +// (~nBWL | ~nBWU) : [AES] Unibios (set to MVS) softdip settings, [MVS] cab settings, dates, timer, high scores, saves, & bookkeeeping +// CARD_WE : [AES/MVS] game saves and high scores +wire bk_change = sram_slot_we | CARD_WE; +wire memcard_change; + +reg sram_slot_we; +always @(posedge clk_sys) begin + sram_slot_we <= 0; + if(~nBWL | ~nBWU) begin + sram_slot_we <= (M68K_ADDR[15:1] >= 'h190 && M68K_ADDR[15:1] < 'h4190); + end +end + +always @(posedge clk_sys) begin + reg old_downloading = 0; + + old_downloading <= downloading; + if(~old_downloading & downloading) bk_ena <= 0; + + // Save file always mounted in the end of downloading state. + if(downloading && img_mounted[0] && !img_readonly) bk_ena <= 1; + + // Determine whether file needs to be written + if (bk_change) bk_pending <= 1; + else if (bk_state) bk_pending <= 0; +end + +wire bk_load = status[21]; +wire bk_save = status[12] | (bk_autosave & OSD_STATUS); +reg bk_loading = 0; +reg bk_state = 0; + +always @(posedge clk_sys) begin + reg old_downloading = 0; + reg old_load = 0, old_save = 0, old_ack; + + old_downloading <= downloading; + + old_load <= bk_load; + old_save <= bk_save; + old_ack <= bk_ack; + + if(~old_ack & bk_ack) {bk_rd, bk_wr} <= 0; + + if(!bk_state) begin + if(bk_ena & ((~old_load & bk_load) | (~old_save & bk_save & bk_pending))) begin + bk_state <= 1; + bk_loading <= bk_load; + bk_lba <= 0; + bk_rd <= bk_load; + bk_wr <= ~bk_load; + end + // always load backup so it will erase the memory if doesn't exist + if(old_downloading & ~downloading & bk_ena) begin + bk_state <= 1; + bk_loading <= 1; + bk_lba <= 0; + bk_rd <= 1; + bk_wr <= 0; + end + end else begin + if(old_ack & ~bk_ack) begin + if (bk_lba >= 'h8F) begin // 64KB + 8KB regardless the selected system + bk_loading <= 0; + bk_state <= 0; + end else begin + bk_lba <= bk_lba + 1'd1; + bk_rd <= bk_loading; + bk_wr <= ~bk_loading; + end + end + end +end + +wire [1:0] CD_REGION; +always @(status[11:10]) +begin + // CD Region code remap: + // status[11:10] remap + // 00 10 US + // 01 01 EU + // 10 11 JP + // 11 00 ASIA + case(status[11:10]) + 2'b00: CD_REGION = 2'b10; + 2'b01: CD_REGION = 2'b01; + 2'b10: CD_REGION = 2'b11; + 2'b11: CD_REGION = 2'b00; + endcase +end + +wire [2:0] CD_TR_AREA; // Transfer area code +wire [15:0] CD_TR_WR_DATA; +wire [19:1] CD_TR_WR_ADDR; +wire [1:0] CD_BANK_SPR; + +wire CD_TR_WR_SPR, CD_TR_WR_PCM, CD_TR_WR_Z80, CD_TR_WR_FIX; +wire CD_TR_RD_SPR, CD_TR_RD_FIX, CD_TR_RD_Z80, CD_TR_RD_PCM; +wire CD_USE_SPR, CD_USE_FIX, CD_USE_Z80, CD_USE_PCM; +wire CD_UPLOAD_EN; +wire CD_BANK_PCM; +wire CD_IRQ; +wire CD_VBLANK_IRQ_EN, CD_TIMER_IRQ_EN; +wire DMA_RUNNING, DMA_WR_OUT, DMA_RD_OUT; +wire [15:0] DMA_DATA_OUT; +wire [23:0] DMA_ADDR_IN; +wire [23:0] DMA_ADDR_OUT; + +wire [15:0] DMA_DATA_IN = CD_TR_RD_PCM ? { 8'h00, ADPCMA_DOUT } : PROM_DATA; + +wire DMA_SDRAM_BUSY; +wire PROM_DATA_READY; + +wire [15:0] CD_AUDIO_L, CD_AUDIO_R; + +//CD communication +reg [48:0] cd_in; +wire [48:0] cd_out; + +wire [35:0] EXT_BUS; + +wire CD_DATA_WR_READY, CDDA_WR_READY; + +hps_ext hps_ext +( + .clk_sys(clk_sys), + .EXT_BUS(EXT_BUS), + + .cd_data_ready(CD_DATA_WR_READY), + .cdda_ready(CDDA_WR_READY), + + .cd_in(cd_in), + .cd_out(cd_out) +); + +reg [39:0] CDD_STATUS; +wire [39:0] CDD_COMMAND_DATA; +wire CDD_COMMAND_SEND; +reg CDD_STATUS_LATCH; +wire [1:0] cd_speed = status[30:29]; + +always @(posedge clk_sys) begin + reg cd_out48_last = 1; + reg cdd_send_old = 0; + + CDD_STATUS_LATCH <= 0; + if (cd_out[48] != cd_out48_last) begin + cd_out48_last <= cd_out[48]; + CDD_STATUS <= cd_out[39:0]; + CDD_STATUS_LATCH <= 1; + end + + cdd_send_old <= CDD_COMMAND_SEND; + if (CDD_COMMAND_SEND && !cdd_send_old) begin + cd_in[47:0] <= {6'd0,cd_speed,CDD_COMMAND_DATA}; + cd_in[48] <= ~cd_in[48]; + end else begin + if (old_reset & ~nRESET) begin + cd_in[47:0] <= 8'hFF; + cd_in[48] <= ~cd_in[48]; + end + end +end + +//extend ioctl_wr for 16 cycles +reg ioctl_wr_x; +always @(posedge clk_sys) begin + reg [3:0] cnt = 0; + + if (ioctl_wr) begin + cnt <= 4'd15; + ioctl_wr_x <= 1; + end + else if (cnt) begin + cnt <= cnt - 1'd1; + end + else begin + ioctl_wr_x <= 0; + end +end + +localparam CD_MCLK = 48335658; + +wire CDDA_CLK; +CEGen CEGEN_CDDA_CLK +( + .CLK(CLK_48M), + .RST_N(nRESET), + .IN_CLK(CD_MCLK), + .OUT_CLK(44100), + .CE(CDDA_CLK) +); + +wire CD_DATA_DOWNLOAD = ioctl_download & (ioctl_index[5:0] == 6'h02); +wire CD_DATA_WR = ioctl_wr_x & CD_DATA_DOWNLOAD; + +wire CDDA_DOWNLOAD = ioctl_download & (ioctl_index[5:0] == 6'h04); +wire CDDA_WR = ioctl_wr_x & CDDA_DOWNLOAD; + +cd_sys #(.MCLK(CD_MCLK)) cdsystem( + .nRESET(nRESET), + .clk_sys(CLK_48M), .CLK_68KCLK_EN(CLK_EN_68K_P), + .M68K_ADDR(M68K_ADDR), .M68K_DATA(M68K_DATA), .A22Z(A22Z), .A23Z(A23Z), + .nLDS(nLDS), .nUDS(nUDS), .M68K_RW(M68K_RW), .nAS(nAS), .nDTACK(nDTACK_ADJ), + .nBR(nBR), .nBG(nBG), .nBGACK(nBGACK), + .SYSTEM_CDx(SYSTEM_CDx), + .CD_REGION(CD_REGION), + .CD_SPEED(cd_speed), + .CD_LID(~status[15] ^ SYSTEM_CDZ), // CD lid state (DEBUG) + .CD_VIDEO_EN(CD_VIDEO_EN), .CD_FIX_EN(CD_FIX_EN), .CD_SPR_EN(CD_SPR_EN), + .CD_nRESET_Z80(CD_nRESET_Z80), + .CD_TR_WR_SPR(CD_TR_WR_SPR), .CD_TR_WR_PCM(CD_TR_WR_PCM), + .CD_TR_WR_Z80(CD_TR_WR_Z80), .CD_TR_WR_FIX(CD_TR_WR_FIX), + .CD_TR_RD_FIX(CD_TR_RD_FIX), .CD_TR_RD_SPR(CD_TR_RD_SPR), + .CD_TR_RD_Z80(CD_TR_RD_Z80), .CD_TR_RD_PCM(CD_TR_RD_PCM), + .CD_USE_FIX(CD_USE_FIX), .CD_USE_SPR(CD_USE_SPR), + .CD_USE_Z80(CD_USE_Z80), .CD_USE_PCM(CD_USE_PCM), + .CD_TR_AREA(CD_TR_AREA), + .CD_BANK_SPR(CD_BANK_SPR), .CD_BANK_PCM(CD_BANK_PCM), + .CD_TR_WR_DATA(CD_TR_WR_DATA), .CD_TR_WR_ADDR(CD_TR_WR_ADDR), + .CD_UPLOAD_EN(CD_UPLOAD_EN), + .CD_IRQ(CD_IRQ), .IACK(IACK), + .CD_VBLANK_IRQ_EN(CD_VBLANK_IRQ_EN), .CD_TIMER_IRQ_EN(CD_TIMER_IRQ_EN), + .CDD_STATUS_IN(CDD_STATUS), .CDD_STATUS_LATCH(CDD_STATUS_LATCH), + .CDD_COMMAND_DATA(CDD_COMMAND_DATA), .CDD_COMMAND_SEND(CDD_COMMAND_SEND), + .CD_DATA_DOWNLOAD(CD_DATA_DOWNLOAD), .CD_DATA_WR(CD_DATA_WR), + .CD_DATA_DIN(ioctl_dout), + .CD_DATA_ADDR(ioctl_addr[11:1]), + .CD_DATA_WR_READY(CD_DATA_WR_READY), + .CDDA_RD(CDDA_CLK), .CDDA_WR(CDDA_WR), + .CD_AUDIO_L(CD_AUDIO_L), .CD_AUDIO_R(CD_AUDIO_R), + .CDDA_WR_READY(CDDA_WR_READY), + .DMA_RUNNING(DMA_RUNNING), + .DMA_DATA_IN(DMA_DATA_IN), .DMA_DATA_OUT(DMA_DATA_OUT), + .DMA_WR_OUT(DMA_WR_OUT), .DMA_RD_OUT(DMA_RD_OUT), + .DMA_ADDR_IN(DMA_ADDR_IN), // Used for reading + .DMA_ADDR_OUT(DMA_ADDR_OUT), // Used for writing + .DMA_SDRAM_BUSY(DMA_SDRAM_BUSY | ddram_wait | ADPCMA_RD_WAIT) +); + +// The P1 zone is writable on the Neo CD +// Is there a write enable register for it ? +wire CD_EXT_WR = DMA_RUNNING ? (SYSTEM_CDx & (DMA_ADDR_OUT[23:21] == 3'd0) & DMA_WR_OUT) : // DMA writes to $000000~$1FFFFF + (SYSTEM_CDx & ~|{A23Z, A22Z, M68K_ADDR[21]} & ~M68K_RW & ~(nLDS & nUDS)); // CPU writes to $000000~$1FFFFF + +wire nROMOE = nROMOEL & nROMOEU; +wire nPORTOE = nPORTOEL & nPORTOEU; + +// CD system work ram is in SDRAM +wire CD_EXT_RD = DMA_RUNNING ? (SYSTEM_CDx & (DMA_ADDR_IN[23:21] == 3'd0) & DMA_RD_OUT) : // DMA reads from $000000~$1FFFFF + (SYSTEM_CDx & (~nWRL | ~nWRU)); // CPU reads from $100000~$1FFFFF + +wire sdram_ready; +wire [26:1] sdram_addr; +wire [15:0] sdram_dout; +wire [15:0] sdram_din; + +// ioctl_download is used to load the system ROM on CD systems, we need it ! +reg ioctl_en; +always_ff @(posedge clk_sys) begin + ioctl_en <= SYSTEM_CDx ? (ioctl_index == INDEX_SPROM) : + (ioctl_index != INDEX_LOROM && ioctl_index != INDEX_M1ROM && ioctl_index != INDEX_MEMCP && (ioctl_index < INDEX_VROMS || ioctl_index >= INDEX_CROMS)); +end + +wire [26:0] CROM_LOAD_ADDR = ({ioctl_addr[25:0], 1'b0} + {ioctl_index[7:1]-INDEX_CROMS[7:1], 18'h00000, ioctl_index[0], 1'b0}); +wire [26:0] VROM_LOAD_ADDR = ({1'b0, ioctl_addr[25:0]} + {ioctl_index[7:0]-INDEX_VROMS[7:0], 19'h00000}); + +localparam SPROM_OFFSET = 27'h0000000; // System ROM: $0000000~$007FFFF +localparam SFIXROM_OFFSET = 27'h0020000; // SFIX: $0020000~$003FFFF (in sys ROM) +localparam S1ROM_OFFSET = 27'h0080000; // S1: $0080000~$00FFFFF +localparam P1ROM_A_OFFSET = 27'h0200000; // P1+: $0200000~... +localparam P1ROM_B_OFFSET = 27'h0280000; // P1: $0280000~$02FFFFF (secondary 512KB) +localparam P2ROM_OFFSET = 27'h0300000; // P2+: $0300000~... + +wire [26:0] ioctl_addr_offset = + (ioctl_index == INDEX_SPROM) ? {SPROM_OFFSET[26:19] , ioctl_addr[18:0]} : // System ROM: $0000000~$007FFFF + (ioctl_index == INDEX_SFIXROM) ? {SFIXROM_OFFSET[26:17], ioctl_addr[16:0]} : // SFIX: $0020000~$003FFFF (in sys ROM) + (ioctl_index == INDEX_S1ROM) ? {S1ROM_OFFSET[26:19] , ioctl_addr[18:0]} : // S1: $0080000~$00FFFFF + (ioctl_index == INDEX_P1ROM_A) ? P1ROM_A_OFFSET + ioctl_addr : // P1+: $0200000~... + (ioctl_index == INDEX_P1ROM_B) ? {P1ROM_B_OFFSET[26:19], ioctl_addr[18:0]} : // P1: $0280000~$02FFFFF (secondary 512KB) + (ioctl_index == INDEX_P2ROM) ? P2ROM_OFFSET + ioctl_addr : // P2+: $0300000~... + (ioctl_index == INDEX_CROM0) ? {CROM_START, 20'd0} + ioctl_addr : // C: end of P, consolidated CROM + (ioctl_index >= INDEX_CROMS) ? {CROM_START, 20'd0} + CROM_LOAD_ADDR : // C*: end of P + 27'h0100000; // undefined case, use work RAM address to make sure no ROM gets overwritten + +reg [6:0] CROM_START; +reg [26:0] P2ROM_MASK, CROM_MASK, V1ROM_MASK, V2ROM_MASK, MROM_MASK; +always_ff @(posedge clk_sys) begin + reg old_rst; + reg old_download; + + old_rst <= status[0]; + + if(status[0]) begin + if (SYSTEM_CDx) begin + CROM_MASK <= 27'h3FFFFF; // 4MB + V1ROM_MASK <= 27'hFFFFF; // 1MB + MROM_MASK <= 27'hFFFF; // 64KB + end else begin + P2ROM_MASK <= P2ROM_MASK | P2ROM_MASK[26:1]; + CROM_MASK <= CROM_MASK | CROM_MASK[26:1]; + V1ROM_MASK <= adpcma_ext ? 27'h1FFFFFF : (V1ROM_MASK | V1ROM_MASK[26:1]); + V2ROM_MASK <= adpcma_ext ? 27'h0 : (V2ROM_MASK | V2ROM_MASK[26:1]); + MROM_MASK <= MROM_MASK | MROM_MASK[26:1]; + end + end + + if(ioctl_wr) begin + if(ioctl_index >= INDEX_CROMS) CROM_MASK <= CROM_MASK | CROM_LOAD_ADDR; + else if(ioctl_index >= INDEX_VROMS) begin + if(~VROM_LOAD_ADDR[24]) V1ROM_MASK <= V1ROM_MASK | VROM_LOAD_ADDR; + else V2ROM_MASK <= V2ROM_MASK | VROM_LOAD_ADDR; + end + else if(ioctl_index == INDEX_CROM0) CROM_MASK <= CROM_MASK | ioctl_addr; + else if(ioctl_index == INDEX_M1ROM) MROM_MASK <= MROM_MASK | ioctl_addr; + else if(ioctl_index == INDEX_P2ROM || ioctl_index == INDEX_P1ROM_A) begin + if(ioctl_addr_offset >= P2ROM_OFFSET) P2ROM_MASK <= P2ROM_MASK | (ioctl_addr_offset - P2ROM_OFFSET); + end + + if(ioctl_index == INDEX_MEMCP && ioctl_addr == 6 && cp_op) begin + if(cp_idx >= INDEX_VROMS) begin + if(cp_idx < (INDEX_VROMS+32)) V1ROM_MASK <= V1ROM_MASK | (cp_end[23:0]-1'd1); + else V2ROM_MASK <= V2ROM_MASK | (cp_end[23:0]-1'd1); + end + else if(cp_idx == INDEX_CROM0) CROM_MASK <= CROM_MASK | (cp_size-1'd1); + else if(cp_idx == INDEX_M1ROM) MROM_MASK <= MROM_MASK | (cp_size-1'd1); + else if(cp_idx == INDEX_P2ROM || cp_idx == INDEX_P1ROM_A) begin + if((cp_end-1'd1)>=P2ROM_OFFSET) P2ROM_MASK <= P2ROM_MASK | (cp_end - P2ROM_OFFSET - 1'd1); + end + + if(cp_idx == INDEX_P2ROM || cp_idx == INDEX_P1ROM_A) begin + if(CROM_START < cp_end[26:20]) CROM_START <= cp_end[26:20]; + end + end + + if(old_download && ~ioctl_download && (ioctl_index == INDEX_P2ROM || ioctl_index == INDEX_P1ROM_A)) begin + if(CROM_START < ioctl_addr_offset[26:20]) CROM_START <= ioctl_addr_offset[26:20]; + end + end + + if(~old_rst & status[0]) begin + CROM_MASK <= 0; + V1ROM_MASK <= 0; + V2ROM_MASK <= 0; + MROM_MASK <= 0; + P2ROM_MASK <= 0; + CROM_START <= 3; + end + + old_download <= ioctl_download; + if(old_download && ~ioctl_download && (ioctl_index == INDEX_P2ROM || ioctl_index == INDEX_P1ROM_A)) begin + if(CROM_START < ioctl_addr_offset[26:20]) CROM_START <= ioctl_addr_offset[26:20]; + end +end + +reg [26:0] ioctl_addr_r; +reg ioctl_wr_r; +always @(posedge clk_sys) begin + ioctl_addr_r <= ioctl_addr_offset; + ioctl_wr_r <= ioctl_wr; +end + +reg ioctl_wr_rd, ioctl_wr_rd1; +always @(posedge CLK_96M) begin + ioctl_wr_rd <= ioctl_wr_r; + ioctl_wr_rd1 <= ioctl_wr_rd; +end + +wire SDRAM_WR; +wire SDRAM_RD; +wire SDRAM_RFSH; +wire [1:0] SDRAM_BS; +wire sdr2_en; + +sdram_mux SDRAM_MUX( + .CLK(CLK_96M), + .nRESET(nRESET), + .nSYSTEM_G(nSYSTEM_G), + .SYSTEM_CDx(SYSTEM_CDx), + + .M68K_ADDR(M68K_ADDR), + .M68K_DATA(M68K_DATA), + .nAS(nAS | (FC1 == FC0)), + .nLDS(nLDS), + .nUDS(nUDS), + .nROMOE(nROMOE), + .nPORTOE(nPORTOE), + .nSROMOE(nSROMOE), + .DATA_TYPE(~FC1 & FC0), // 0 - program, 1 - data, + .P2ROM_ADDR(P2ROM_ADDR & P2ROM_MASK), + .PROM_DATA(PROM_DATA), + .PROM_DATA_READY(PROM_DATA_READY), + + .CD_TR_AREA(CD_TR_AREA), + .CD_EXT_WR(CD_EXT_WR), + .CD_EXT_RD(CD_EXT_RD), + .CD_USE_FIX(CD_USE_FIX), + .CD_TR_RD_FIX(CD_TR_RD_FIX), + .CD_TR_WR_FIX(CD_TR_WR_FIX), + .CD_BANK_SPR(CD_BANK_SPR), + .CD_USE_SPR(CD_USE_SPR), + .CD_TR_RD_SPR(CD_TR_RD_SPR), + .CD_TR_WR_SPR(CD_TR_WR_SPR), + + .DMA_ADDR_OUT(DMA_ADDR_OUT), + .DMA_ADDR_IN(DMA_ADDR_IN), + .DMA_DATA_OUT(DMA_DATA_OUT), + .DMA_RUNNING(DMA_RUNNING), + .DMA_SDRAM_BUSY(DMA_SDRAM_BUSY), + + .PCK1(PCK1), + .SPR_EN(SPR_EN), + .CROM_ADDR({CROM_ADDR[26:20] + (SYSTEM_CDx ? 7'd8 : CROM_START), CROM_ADDR[19:0]}), + .CR_DOUBLE(CR_DOUBLE), + + .PCK2(PCK2), + .S_LATCH(S_LATCH), + .FIX_BANK(FIX_BANK), + .FIX_EN(FIX_EN), + + .SROM_DATA(SROM_DATA), + + .DL_EN(ioctl_download & ioctl_en), + .DL_ADDR(ioctl_addr_r), + .DL_DATA(ioctl_dout), + .DL_WR(~ioctl_wr_rd1 & ioctl_wr_rd), + + .REFRESH_EN(RFSH), + + .SDRAM_ADDR(sdram_addr), + .SDRAM_DOUT(sdram_dout), + .SDRAM_DIN(sdram_din), + .SDRAM_WR(SDRAM_WR), + .SDRAM_RD(SDRAM_RD), + .SDRAM_RFSH(SDRAM_RFSH), + .SDRAM_BS(SDRAM_BS), + .SDRAM_READY(sdram_ready) +); + +reg [1:0] sdr_pri_128_64; +wire sdr_pri_cpsel = (~sdr_cpaddr[26] | sdr_pri_128_64[1]) & (~sdr_cpaddr[25] | sdr_pri_128_64[0]); +always @(posedge CLK_96M) if (~nRESET) sdr_pri_128_64 <= {~sdram_sz[14] & &sdram_sz[1:0], ~sdram_sz[14] & sdram_sz[1]}; + +wire sdram1_ready, sdram2_ready; +wire [15:0] sdram1_dout, sdram2_dout; + +sdram ram1( + .SDRAM_CLK(SDRAM_CLK), + .SDRAM_CKE(SDRAM_CKE), + .SDRAM_A(SDRAM_A), + .SDRAM_BA(SDRAM_BA), + .SDRAM_DQ(SDRAM_DQ), + .SDRAM_DQML(SDRAM_DQML), + .SDRAM_DQMH(SDRAM_DQMH), + .SDRAM_nCS(SDRAM_nCS), + .SDRAM_nCAS(SDRAM_nCAS), + .SDRAM_nRAS(SDRAM_nRAS), + .SDRAM_nWE(SDRAM_nWE), + .SDRAM_EN(1), + + .init(~locked), // Init SDRAM as soon as the PLL is locked + .clk(CLK_96M), + .addr(sdram_addr[26:1]), + .sel(sdr_pri_sel), + .dout(sdram1_dout), + .din(sdram_din), + .bs(SDRAM_BS), + .wr(SDRAM_WR), + .rd(SDRAM_RD), + .refresh(SDRAM_RFSH), + .ready(sdram1_ready), + + .cpsel(sdr_pri_cpsel), + .cpaddr(sdr_cpaddr[26:1]), + .cpdin(sdr_cpdin), + .cprd(sdr1_cprd), + .cpreq(sdr_cpreq), + .cpbusy(sdr1_cpbusy) +); + +`ifdef MISTER_DUAL_SDRAM +sdram ram2( + .SDRAM_CLK(SDRAM2_CLK), + .SDRAM_A(SDRAM2_A), + .SDRAM_BA(SDRAM2_BA), + .SDRAM_DQ(SDRAM2_DQ), + .SDRAM_nCS(SDRAM2_nCS), + .SDRAM_nCAS(SDRAM2_nCAS), + .SDRAM_nRAS(SDRAM2_nRAS), + .SDRAM_nWE(SDRAM2_nWE), + .SDRAM_EN(SDRAM2_EN), + + .init(~locked), // Init SDRAM as soon as the PLL is locked + .clk(CLK_96M), + .addr(sdram_addr[25:1]), + .sel(~sdr_pri_sel), + .dout(sdram2_dout), + .din(sdram_din), + .bs(SDRAM_BS), + .wr(SDRAM_WR), + .rd(SDRAM_RD), + .refresh(SDRAM_RFSH), + .ready(sdram2_ready), + + .cpsel(~sdr_pri_cpsel), + .cpaddr(sdr_cpaddr[25:1]), + .cpdin(sdr_cpdin), + .cprd(sdr2_cprd), + .cpreq(sdr_cpreq), + .cpbusy(sdr2_cpbusy) +); + +wire sdr_pri_sel = (~sdram_addr[26] | sdr_pri_128_64[1]) & (~sdram_addr[25] | sdr_pri_128_64[0]); +assign sdr2_en = SDRAM2_EN; +`else +wire sdr_pri_sel = 1; +assign sdram2_dout = '0; +assign sdram2_ready = 1; +assign sdr2_cprd = 0; +assign sdr2_cpbusy = 0; +assign sdr2_en = 0; +`endif + +assign sdram_dout = sdr_pri_sel ? sdram1_dout : sdram2_dout; +assign sdram_ready = sdram2_ready & sdram1_ready; + +wire [2:0] P1_OUT, P2_OUT; + +neo_d0 D0( + .CLK(CLK_48M), + .CLK_EN_24M_P(CLK_EN_24M_P), + .CLK_EN_24M_N(CLK_EN_24M_N), + .nRESET(nRESET), .nRESETP(nRESETP), + .CLK_68KCLK(CLK_68KCLK), .CLK_68KCLKB(CLK_68KCLKB), .CLK_EN_12M(CLK_EN_12M), .CLK_EN_12M_N(CLK_EN_12M_N), .CLK_EN_6MB(CLK_EN_6MB), .CLK_EN_1HB(CLK_EN_1HB), + .CLK_EN_68K_P(CLK_EN_68K_P), .CLK_EN_68K_N(CLK_EN_68K_N), + .M68K_ADDR_A4(M68K_ADDR[4]), + .M68K_DATA(M68K_DATA[5:0]), + .nBITWD0(nBITWD0), + .SDA_H(SDA[15:11]), .SDA_L(SDA[4:2]), + .nSDRD(nSDRD), .nSDWR(nSDWR), .nMREQ(nMREQ), .nIORQ(nIORQ), + .nZ80NMI(Z80_nNMI), + .nSDW(nSDW), .nSDZ80R(nSDZ80R), .nSDZ80W(nSDZ80W), .nSDZ80CLR(nSDZ80CLR), + .nSDROM(nSDROM), .nSDMRD(nSDMRD), .nSDMWR(nSDMWR), .nZRAMCS(nZRAMCS), + .SDRD0(SDRD0), .SDRD1(SDRD1), + .n2610CS(n2610CS), .n2610RD(n2610RD), .n2610WR(n2610WR), + .P1_OUT(P1_OUT), .P2_OUT(P2_OUT), + .BNK(BNK) +); + +// Re-priority-encode the interrupt lines with the CD_IRQ one (IPL* are active-low) +// +// IPL2 IPL1 IPL0 Cartridge CD +// 1 1 1 No IRQ No IRQ +// 1 1 0 Vblank (64) Vblank (68) +// 1 0 1 Timer (68) CD IRQ (54/58) +// 1 0 0 Cold boot (6C) Timer (64) +// +wire [1:0] CD_IPL = {IPL1,IPL0} == 2'b01 ? 2'b00 // Level 3 Timer + : CD_IRQ ? 2'b01 // Level 2 CD IRQ + : {IPL1,IPL0} == 2'b10 ? 2'b10 // Level 1 VBlank + : 2'b11; + +wire [1:0] IPL_OUT = ~SYSTEM_CDx ? { IPL1,IPL0 } : CD_IPL; + +// Because of the SDRAM latency, nDTACK is handled differently for ROM zones +// If the address is in a ROM zone, PROM_DATA_READY is used to extend the normal nDTACK output by NEO-C1 +wire nDTACK_ADJ = ~&{nSROMOE, nROMOE, nPORTOE, ~CD_EXT_RD, ~CD_TR_RD_FIX, ~CD_TR_RD_SPR} ? ~PROM_DATA_READY | nDTACK + : (CD_TR_WR_PCM) ? ~ddram_dtack | nDTACK + : (CD_TR_RD_PCM) ? ~ADPCMA_RD_DTACK | nDTACK + : nDTACK; + +cpu_68k M68KCPU( + .CLK(CLK_48M), + .CLK_EN_68K_P(CLK_EN_68K_P), + .CLK_EN_68K_N(CLK_EN_68K_N), + .nRESET(nRESET), + .M68K_ADDR(M68K_ADDR), + .FX68K_DATAIN(FX68K_DATAIN), .FX68K_DATAOUT(FX68K_DATAOUT), + .nLDS(nLDS), .nUDS(nUDS), .nAS(nAS), .M68K_RW(M68K_RW), + .nDTACK(nDTACK_ADJ), // nDTACK + .IPL2(1'b1), .IPL1(IPL_OUT[1]), .IPL0(IPL_OUT[0]), + .FC2(FC2), .FC1(FC1), .FC0(FC0), + .nBG(nBG), .nBR(nBR), .nBGACK(nBGACK), + .SYSTEM_CDx(SYSTEM_CDx) +); + +wire IACK = &{FC2, FC1, FC0}; + +// FX68K doesn't like byte masking with Z's, replace with 0's: +assign M68K_DATA_BYTE_MASK = (~|{nLDS, nUDS}) ? M68K_DATA : + (~nLDS) ? {8'h00, M68K_DATA[7:0]} : + (~nUDS) ? {M68K_DATA[15:8], 8'h00} : + 16'h0000; + +assign M68K_DATA = M68K_RW ? 16'bzzzzzzzz_zzzzzzzz : FX68K_DATAOUT; +assign FX68K_DATAIN = M68K_RW ? M68K_DATA_BYTE_MASK : 16'h0000; + +assign FIXD = CD_USE_FIX ? 8'bzzzz_zzzz : S2H1 ? SROM_DATA[15:8] : SROM_DATA[7:0]; + +// Disable ROM read in PORT zone if the game uses a special chip +assign M68K_DATA = (nROMOE & nSROMOE & ~CD_TR_RD_SPR & |{nPORTOE, cart_chip, cart_pchip, xram, CD_TR_RD_FIX}) ? 16'bzzzzzzzzzzzzzzzz : PROM_DATA; + +// Output correct FIX byte +assign M68K_DATA[7:0] = ~CD_TR_RD_FIX ? 8'bzzzz_zzzz : (M68K_ADDR[4] ? PROM_DATA[15:8] : PROM_DATA[7:0]); + +// Neo CD 68k work RAM is in SDRAM so we can use this for Z80 RAM instead. +assign WRAM_ADDR = SYSTEM_CDx ? SDA[15:1] : M68K_ADDR[15:1]; +assign { WRAMU_DATA, WRAML_DATA } = SYSTEM_CDx ? { SDD_OUT, SDD_OUT } : { M68K_DATA[15:0] }; +assign WRAMU_WREN = SYSTEM_CDx ? (~nSDMWR & SDA[0]) : ~nWWU; +assign WRAML_WREN = SYSTEM_CDx ? (~nSDMWR & ~SDA[0]) : ~nWWL; + +// 68k/Z80 work RAM +dpram #(15) WRAML( + .clock_a(CLK_48M), + .address_a(WRAM_ADDR), + .data_a(WRAML_DATA), + .wren_a(WRAML_WREN), + .q_a(WRAML_OUT), + + .clock_b(CLK_48M), + .address_b(TRASH_ADDR), + .data_b(TRASH_ADDR[7:0]), + .wren_b(~nRESET_CORE) +); + +dpram #(15) WRAMU( + .clock_a(CLK_48M), + .address_a(WRAM_ADDR), + .data_a(WRAMU_DATA), + .wren_a(WRAMU_WREN), + .q_a(WRAMU_OUT), + + .clock_b(CLK_48M), + .address_b(TRASH_ADDR), + .data_b(TRASH_ADDR[7:0]), + .wren_b(~nRESET_CORE) +); + +wire [23:0] P2ROM_ADDR_PVC, P2ROM_ADDR_SMA; +wire [23:0] P2ROM_ADDR = cart_pchip ? (P2ROM_ADDR_PVC | P2ROM_ADDR_SMA) : {P_BANK, M68K_ADDR[19:1], 1'b0}; + +neo_pvc neo_pvc +( + .nRESET(nRESET), + .CLK_48M(CLK_48M), + + .ENABLE(cart_pchip == 2), + + .M68K_ADDR(M68K_ADDR), + .M68K_DATA(M68K_DATA), + .PROM_DATA(PROM_DATA), + .nPORTOEL(nPORTOEL), + .nPORTOEU(nPORTOEU), + .nPORTWEL(nPORTWEL), + .nPORTWEU(nPORTWEU), + .P2_ADDR(P2ROM_ADDR_PVC) +); + +neo_sma neo_sma +( + .nRESET(nRESET), + .CLK_48M(CLK_48M), + + .TYPE(cart_pchip), + + .M68K_ADDR(M68K_ADDR), + .M68K_DATA(M68K_DATA), + .PROM_DATA(PROM_DATA), + .nPORTOEL(nPORTOEL), + .nPORTOEU(nPORTOEU), + .nPORTWEL(nPORTWEL), + .nPORTWEU(nPORTWEU), + .P2_ADDR(P2ROM_ADDR_SMA) +); + +wire XRAM_CS = ~nPORTADRS && !M68K_ADDR[19:13] && xram; +wire [15:0] XRAM_OUT; +wire [15:0] xram_buff_dout; + +dpram #(12) XRAML( + .clock_a(CLK_48M), + .address_a(M68K_ADDR[12:1]), + .data_a(M68K_DATA[7:0]), + .wren_a(~nPORTWEL & XRAM_CS), + .q_a(XRAM_OUT[7:0]), + + .clock_b(clk_sys), + .address_b(memcard_addr), + .wren_b(memcard_wr & xram), + .data_b(sd_buff_dout[7:0]), + .q_b(xram_buff_dout[7:0]) +); + +dpram #(12) XRAMU( + .clock_a(CLK_48M), + .address_a(M68K_ADDR[12:1]), + .data_a(M68K_DATA[15:8]), + .wren_a(~nPORTWEU & XRAM_CS), + .q_a(XRAM_OUT[15:8]), + + .clock_b(clk_sys), + .address_b(memcard_addr), + .wren_b(memcard_wr & xram), + .data_b(sd_buff_dout[15:8]), + .q_b(xram_buff_dout[15:8]) +); + +assign M68K_DATA[7:0] = (XRAM_CS & ~nPORTOEL) ? XRAM_OUT[7:0] : 8'bZ; +assign M68K_DATA[15:8] = (XRAM_CS & ~nPORTOEU) ? XRAM_OUT[15:8] : 8'bZ; + +assign M68K_DATA[7:0] = (~nPORTOEL && M68K_ADDR[19] && !M68K_ADDR[18:1] && xram) ? {~joystick_0[8],1'b1,~joystick_0[9],~joystick_0[11],2'b11, ~joystick_1[10],~joystick_0[10]} : 8'bZ; + +// Work RAM or CD extended RAM read +assign M68K_DATA[7:0] = nWRL ? 8'bzzzzzzzz : SYSTEM_CDx ? PROM_DATA[7:0] : WRAML_OUT; +assign M68K_DATA[15:8] = nWRU ? 8'bzzzzzzzz : SYSTEM_CDx ? PROM_DATA[15:8] : WRAMU_OUT; + +wire save_wr = sd_buff_wr & bk_ack; +wire sram_wr = ~bk_lba[7] & save_wr; // 000000~00FFFF +wire memcard_wr = bk_lba[7] & save_wr; // 010000-011FFF +wire [14:0] sram_addr = {bk_lba[6:0], sd_buff_addr}; //64KB +wire [11:0] memcard_addr = {bk_lba[3:0], sd_buff_addr}; //8KB + +// Backup RAM +wire nBWL = nSRAMWEL | nSRAMWEN_G; +wire nBWU = nSRAMWEU | nSRAMWEN_G; + +wire [15:0] sram_buff_dout; +backup BACKUP +( + .CLK(CLK_48M), + .M68K_ADDR(M68K_ADDR[15:1]), + .M68K_DATA(M68K_DATA), + .nBWL(nBWL), .nBWU(nBWU), + .SRAM_OUT(SRAM_OUT), + .clk_sys(clk_sys), + .sram_addr(sram_addr), + .sram_wr(sram_wr), + .sd_buff_dout(sd_buff_dout), + .sd_buff_din_sram(sram_buff_dout) +); + +// Backup RAM is only for MVS +assign M68K_DATA[7:0] = (nSRAMOEL | ~SYSTEM_MVS) ? 8'bzzzzzzzz : SRAM_OUT[7:0]; +assign M68K_DATA[15:8] = (nSRAMOEU | ~SYSTEM_MVS) ? 8'bzzzzzzzz : SRAM_OUT[15:8]; + +// Memory card +assign {nCD1, nCD2} = {2{status[4] & ~SYSTEM_CDx}}; // Always plugged in CD systems +assign CARD_WE = (SYSTEM_CDx | (~nCARDWEN & CARDWENB)) & ~nCRDW; + +wire [15:0] memcard_buff_dout; +memcard MEMCARD( + .CLK(CLK_48M), + .SYSTEM_CDx(SYSTEM_CDx), + .CDA(CDA), .CDD(CDD), + .CARD_WE(CARD_WE), + .M68K_DATA(M68K_DATA[7:0]), + .clk_sys(clk_sys), + .memcard_addr(memcard_addr), + .memcard_wr(memcard_wr), + .memcard_din(sd_buff_dout), + .memcard_dout(memcard_buff_dout) +); + +// Feed save file writer with backup RAM data or memory card data +wire [15:0] bk_dout = ~bk_lba[7] ? sram_buff_dout : xram ? xram_buff_dout : memcard_buff_dout; + +assign CROM_ADDR = {C_LATCH_EXT, C_LATCH, 3'b000} & CROM_MASK; + +zmc ZMC( + .CLK(CLK_48M), + .nRESET(nRESET), + .nSDRD0(SDRD0), + .SDA_L(SDA[1:0]), .SDA_U(SDA[15:8]), + .MA(MA) +); + +// Bankswitching for the PORT zone, do all games use a 1MB window ? +// P_BANK stays at 0 for CD systems +always @(posedge CLK_48M) +begin + reg nPORTWEL_d; + nPORTWEL_d <= nPORTWEL; + + if (!nRESET || SYSTEM_CDx) P_BANK <= 0; + else if (~nPORTWEL & nPORTWEL_d) begin + if(~ms5p_bank) P_BANK <= M68K_DATA[3:0]; + else if(&M68K_ADDR[19:4] && M68K_ADDR[3:1] == 2) P_BANK <= M68K_DATA[7:4] - 1'd1; + end +end + +// PRO-CT0 used as security chip +wire [3:0] GAD_SEC; +wire [3:0] GBD_SEC; + +reg nPORTWEL_D; +always @(posedge CLK_48M) nPORTWEL_D <= nPORTWEL; + +zmc2_dot ZMC2DOT( + .CLK(CLK_48M), + .CLK_EN_12M_N(nPORTWEL_D & ~nPORTWEL), + .EVEN(M68K_ADDR[2]), .LOAD(M68K_ADDR[1]), .H(M68K_ADDR[3]), + .CR({ + M68K_ADDR[19], M68K_ADDR[15], M68K_ADDR[18], M68K_ADDR[14], + M68K_ADDR[17], M68K_ADDR[13], M68K_ADDR[16], M68K_ADDR[12], + M68K_ADDR[11], M68K_ADDR[7], M68K_ADDR[10], M68K_ADDR[6], + M68K_ADDR[9], M68K_ADDR[5], M68K_ADDR[8], M68K_ADDR[4], + M68K_DATA[15], M68K_DATA[11], M68K_DATA[14], M68K_DATA[10], + M68K_DATA[13], M68K_DATA[9], M68K_DATA[12], M68K_DATA[8], + M68K_DATA[7], M68K_DATA[3], M68K_DATA[6], M68K_DATA[2], + M68K_DATA[5], M68K_DATA[1], M68K_DATA[4], M68K_DATA[0] + }), + .GAD(GAD_SEC), .GBD(GBD_SEC) +); + +assign M68K_DATA[7:0] = ((cart_chip == 1) & ~nPORTOEL) ? + {GBD_SEC[1], GBD_SEC[0], GBD_SEC[3], GBD_SEC[2], + GAD_SEC[1], GAD_SEC[0], GAD_SEC[3], GAD_SEC[2]} : 8'bzzzzzzzz; + +neo_273 NEO273( + .CLK(CLK_48M), + .PBUS(PBUS[19:0]), + .PCK1B_EN(PCK1_EN_N), .PCK2B_EN(PCK2_EN_N), + .C_LATCH(C_LATCH), .S_LATCH(S_LATCH) +); + +// 4 MSBs not handled by NEO-273 +always @(posedge CLK_48M) begin + if (PCK1_EN_N) C_LATCH_EXT <= PBUS[23:20]; +end + +neo_cmc neo_cmc +( + .CLK(CLK_48M), + .PCK2B_EN(PCK2_EN_N), + .PBUS(PBUS[14:0]), + .TYPE(cmc_chip), + .ADDR(FIXMAP_ADDR), + .BANK(FIX_BANK) +); + + +// Fake COM MCU +wire [15:0] COM_DOUT; + +com COM( + .nRESET(nRESET), + .CLK_48M(CLK_48M), + .nPORTOEL(nPORTOEL), .nPORTOEU(nPORTOEU), .nPORTWEL(nPORTWEL), + .M68K_DIN(COM_DOUT) +); + +assign M68K_DATA = (cart_chip == 2) ? COM_DOUT : 16'bzzzzzzzz_zzzzzzzz; + +syslatch SL( + .nRESET(nRESET), + .CLK(CLK_48M), + .CLK_EN_68K_P(CLK_EN_68K_P), + .M68K_ADDR(M68K_ADDR[4:1]), + .nBITW1(nBITW1), + .SHADOW(SHADOW), .nVEC(nVEC), .nCARDWEN(nCARDWEN), .CARDWENB(CARDWENB), .nREGEN(nREGEN), .nSYSTEM(nSYSTEM), .nSRAMWEN(nSRAMWEN), .PALBNK(PALBNK) +); + +wire nSRAMWEN_G = SYSTEM_MVS ? nSRAMWEN : 1'b1; // nSRAMWEN is only for MVS +wire nSYSTEM_G = SYSTEM_MVS ? nSYSTEM : 1'b1; // nSYSTEM is only for MVS + +neo_e0 E0( + .M68K_ADDR(M68K_ADDR[23:1]), + .BNK(BNK), + .nSROMOEU(nSROMOEU), .nSROMOEL(nSROMOEL), .nSROMOE(nSROMOE), + .nVEC(nVEC), + .A23Z(A23Z), .A22Z(A22Z), + .CDA(CDA) +); + +neo_f0 F0( + .CLK(CLK_48M), + .nRESET(nRESET), + .nDIPRD0(nDIPRD0), .nDIPRD1(nDIPRD1), + .nBITW0(nBITW0), .nBITWD0(nBITWD0), + .DIPSW({~status[9:8], 5'b11111, ~status[7]}), + .COIN1(~joystick_0[10]), .COIN2(~joystick_1[10]), + .M68K_ADDR(M68K_ADDR[7:4]), + .M68K_DATA(M68K_DATA[7:0]), + .SYSTEMB(~nSYSTEM_G), + .RTC_DOUT(RTC_DOUT), .RTC_TP(RTC_TP), .RTC_DIN(RTC_DIN), .RTC_CLK(RTC_CLK), .RTC_STROBE(RTC_STROBE), + .SYSTEM_TYPE(SYSTEM_MVS) +); + +uPD4990 RTC( + .rtc(rtc), + .nRESET(nRESET), + .CLK(CLK_48M), + .CLK_EN_12M(CLK_EN_12M), + .DATA_CLK(RTC_CLK), .STROBE(RTC_STROBE), + .DATA_IN(RTC_DIN), .DATA_OUT(RTC_DOUT), + .CS(1'b1), .OE(1'b1), + .TP(RTC_TP) +); + +neo_g0 G0( + .M68K_DATA(M68K_DATA), + .G0(nCRDC), .G1(nPAL), .DIR(M68K_RW), .WE(nPAL_WE), + .CDD({8'hFF, CDD}), .PC(PAL_RAM_DATA) +); + +wire [11:0] joy_0a = P1_OUT[0] ? (joystick_2[11:0] | {P1_OUT[2],5'b00000}) : (joystick_0[11:0] | {P1_OUT[2],4'b0000}); +wire [11:0] joy_1a = P1_OUT[0] ? (joystick_3[11:0] | {P1_OUT[2],5'b00000}) : (joystick_1[11:0] | {P1_OUT[2],4'b0000}); + +wire [11:0] joy_0b = ({12{P1_OUT[0]}} & joystick_0[11:0]) | ({12{P1_OUT[1]}} & joystick_2[11:0]) | {P1_OUT[2], 9'd0}; +wire [11:0] joy_1b = ({12{P2_OUT[0]}} & joystick_1[11:0]) | ({12{P2_OUT[1]}} & joystick_3[11:0]) | {P2_OUT[2], 9'd0}; + +wire [11:0] joy_0 = status[43] ? joy_0a : status[44] ? joy_0b : joystick_0; +wire [11:0] joy_1 = status[43] ? joy_1a : status[44] ? joy_1b : joystick_1; + + +neo_c1 C1( + .CLK(CLK_48M), + .M68K_ADDR(M68K_ADDR[21:17]), + .M68K_DATA(M68K_DATA[15:8]), .A22Z(A22Z), .A23Z(A23Z), + .nLDS(nLDS), .nUDS(nUDS), .RW(M68K_RW), .nAS(nAS), + .nROMOEL(nROMOEL), .nROMOEU(nROMOEU), + .nPORTOEL(nPORTOEL), .nPORTOEU(nPORTOEU), .nPORTWEL(nPORTWEL), .nPORTWEU(nPORTWEU), + .nPORT_ZONE(nPORTADRS), + .nWRL(nWRL), .nWRU(nWRU), .nWWL(nWWL), .nWWU(nWWU), + .nSROMOEL(nSROMOEL), .nSROMOEU(nSROMOEU), + .nSRAMOEL(nSRAMOEL), .nSRAMOEU(nSRAMOEU), .nSRAMWEL(nSRAMWEL), .nSRAMWEU(nSRAMWEU), + .nLSPOE(nLSPOE), .nLSPWE(nLSPWE), + .nCRDO(nCRDO), .nCRDW(nCRDW), .nCRDC(nCRDC), + .nSDW(nSDW), + .P1_IN(~{(joy_0[9:8]|ps2_mouse[2]), {use_mouse ? ms_pos : use_sp ? {|{joy_0[7:4],ps2_mouse[1:0]},sp0} : {joy_0[7:4]|{3{~xram & joy_0[11]}}|{{2{joystick_0[13]}},{2{joystick_0[12]}}}, joy_0[0], joy_0[1], joy_0[2], joy_0[3]}}}), + .P2_IN(~{ joy_1[9:8], {use_mouse ? ms_btn : use_sp ? {|{joy_1[7:4]}, sp1} : {joy_1[7:4]|{3{~xram & joy_1[11]}}|{{2{joystick_1[13]}},{2{joystick_1[12]}}}, joy_1[0], joy_1[1], joy_1[2], joy_1[3]}}}), + .nCD1(nCD1), .nCD2(nCD2), + .nWP(0), // Memory card is never write-protected + .nROMWAIT(~rom_wait), .nPWAIT0(~p_wait[0]), .nPWAIT1(~p_wait[1]), .PDTACK(1), + .SDD_WR(SDD_OUT), + .SDD_RD(SDD_RD_C1), + .nSDZ80R(nSDZ80R), .nSDZ80W(nSDZ80W), .nSDZ80CLR(nSDZ80CLR), + .CLK_EN_68K_P(CLK_EN_68K_P), + .nDTACK(nDTACK), + .nBITW0(nBITW0), .nBITW1(nBITW1), + .nDIPRD0(nDIPRD0), .nDIPRD1(nDIPRD1), + .nPAL_ZONE(nPAL), + .SYSTEM_TYPE({SYSTEM_CDx, SYSTEM_MVS}) +); + +reg use_sp = 0; +reg [6:0] sp0 = 0, sp1 = 0; +always @(posedge clk_sys) begin + reg old_sp0, old_sp1, old_ms; + reg latch_done = 0, ms_filtered = 0; + + old_sp0 <= spinner_0[8]; + if(latch_done && (old_sp0 ^ spinner_0[8])) sp0 <= sp0 - spinner_0[6:0]; + + // Main fires a single mouse event on cold boot in input.cpp in input_notify_mode() + // Filter this event once to prevent accidental latching of use_sp on cold boot + old_ms <= ps2_mouse[24]; + if(latch_done && (old_ms ^ ps2_mouse[24])) begin + ms_filtered <= 1; + if (ms_filtered) sp0 <= sp0 - ps2_mouse[14:8]; + end + + old_sp1 <= spinner_1[8]; + if(latch_done && (old_sp1 ^ spinner_1[8])) sp1 <= sp1 - spinner_1[6:0]; + + latch_done <= 1; + + if(status[42]) use_sp <= 1; + else if(status[41]) use_sp <= 0; + else if(latch_done) begin + if((old_sp0 ^ spinner_0[8]) || (old_sp1 ^ spinner_1[8]) || (ms_filtered && (old_ms ^ ps2_mouse[24]))) use_sp <= 1; + if(joystick_0[3:0] || joystick_1[3:0]) use_sp <= 0; + end +end + +wire use_mouse = &status[42:41]; + +reg ms_xy; +reg [7:0] ms_x, ms_y; +wire [7:0] ms_pos = ms_xy ? ms_y : ms_x; +wire [7:0] ms_btn = {2'b00, ps2_mouse[1:0], 4'b0000}; + +always @(posedge clk_sys) begin + reg old_ms; + + if(!nBITW0 && !M68K_ADDR[6:3]) ms_xy <= M68K_DATA[0]; + + old_ms <= ps2_mouse[24]; + if(old_ms ^ ps2_mouse[24]) begin + ms_x <= ms_x + ps2_mouse[15:8]; + ms_y <= ms_y - ps2_mouse[23:16]; + end +end + +zmc2_dot ZMC2( + .CLK(CLK_48M), + .CLK_EN_12M_N(CLK_EN_12M_N), + .EVEN(EVEN1), .LOAD(LOAD), .H(H), + .CR(CA4 ? CR_DOUBLE[63:32] : CR_DOUBLE[31:0]), + .GAD(GAD), .GBD(GBD), + .DOTA(DOTA), .DOTB(DOTB) +); + +dpram #(16) LO( + .clock_a(clk_sys), + .address_a(ioctl_addr[16:1]), + .data_a(ioctl_dout[7:0]), + .wren_a(ioctl_download & (ioctl_index == INDEX_LOROM) & ioctl_wr), + .clock_b(CLK_48M), + .address_b(PBUS[15:0]), + .q_b(LO_ROM_DATA) +); + +// VCS is normally used as the LO ROM's nOE but the NeoGeo relies on the fact that the LO ROM +// will still have its output active for a short moment (~50ns) after nOE goes high +// nPBUS_OUT_EN is used internally by LSPC2 but it's broken out here to use the additional +// half mclk cycle it provides compared to VCS. This makes sure LO_ROM_DATA is valid when latched. +assign PBUS[23:16] = nPBUS_OUT_EN ? LO_ROM_DATA : 8'bzzzzzzzz; + +spram #(11,16) UFV( + .clock(CLK_48M), + .address(FAST_VRAM_ADDR), + .data(FAST_VRAM_DATA_OUT), + .wren(~CWE), + .q(FAST_VRAM_DATA_IN) +); + +spram #(15,16) USV( + .clock(CLK_48M), + .address(SLOW_VRAM_ADDR), + .data(SLOW_VRAM_DATA_OUT), + .wren(~BWE), + .q(SLOW_VRAM_DATA_IN) +); + +wire [18:11] MA; +wire [7:0] Z80_RAM_DATA; + +// 2KB Z80 work RAM (Cart) +spram #(11) Z80RAM(.clock(CLK_48M), .address(SDA[10:0]), .data(SDD_OUT), .wren(~(nZRAMCS | nSDMWR)), .q(Z80_RAM_DATA)); + +// 64KB Z80 work RAM (CD) +assign CD_Z80_RAM_OUT = SDA[0] ? WRAMU_OUT : WRAML_OUT; + +assign SDD_IN = (~nSDZ80R) ? SDD_RD_C1 : + (~nSDMRD & SYSTEM_CDx) ? CD_Z80_RAM_OUT : + (~nSDMRD & ~nSDROM) ? M1_ROM_DATA : + (~nSDMRD & ~nZRAMCS) ? Z80_RAM_DATA : + (~n2610CS & ~n2610RD) ? YM2610_DOUT : + 8'b00000000; + +wire Z80_nRESET = SYSTEM_CDx ? nRESET & CD_nRESET_Z80 : nRESET; +wire CD_HAS_Z80_BUS = (CD_USE_Z80 & ~(nBUSAK & CD_nRESET_Z80)); + +wire [7:0] M1_ROM_DATA; +reg z80rd_req; +wire z80rd_ack; +wire z80_rom_rd = ~(nSDMRD | nSDROM | SYSTEM_CDx); +always @(posedge DDRAM_CLK) begin + reg old_rd, old_rd1; + + old_rd <= z80_rom_rd; + if(old_rd == z80_rom_rd) old_rd1 <= old_rd; + + // nRESET is used here because otherwise z80rd_req is toggled at core boot + // which causes problems with DDRAM. (Z80_nSDRD is probably low for a few DDRAM_CLK + // cycles at core boot). + // If the core is loaded with SignalTap then DDRAM is stuck at waiting for + // DDRAM_DOUT_READY to go high which does not happen. + if(~old_rd1 & old_rd & nRESET) z80rd_req <= ~z80rd_req; +end + +wire Z80_nWAIT = (z80rd_req == z80rd_ack); + +cpu_z80 Z80CPU( + .CLK(CLK_48M), + .CLK4P_EN(CLK_EN_4M_P), + .CLK4N_EN(CLK_EN_4M_N), + .nRESET(Z80_nRESET), + .SDA(Z80_SDA), .SDD_IN(SDD_IN), .SDD_OUT(Z80_SDD_OUT), + .nIORQ(nIORQ), .nMREQ(Z80_nMREQ), .nRD(Z80_nSDRD), .nWR(Z80_nSDWR), + .nBUSRQ(~CD_USE_Z80), .nBUSAK(nBUSAK), + .nINT(Z80_nINT), .nNMI(Z80_nNMI), .nWAIT(Z80_nWAIT) +); + +assign { SDA, SDD_OUT } = ~CD_HAS_Z80_BUS ? { Z80_SDA, Z80_SDD_OUT } : DMA_RUNNING ? { DMA_ADDR_OUT[16:1], DMA_DATA_OUT[7:0] } : { M68K_ADDR[16:1], M68K_DATA[7:0] }; +assign { nSDRD, nSDWR } = ~CD_HAS_Z80_BUS ? { Z80_nSDRD, Z80_nSDWR } : { ~CD_TR_RD_Z80, ~CD_TR_WR_Z80 }; +assign { nMREQ } = ~CD_HAS_Z80_BUS ? { Z80_nMREQ } : {~(CD_TR_RD_Z80 | CD_TR_WR_Z80)}; + +assign M68K_DATA[7:0] = ~(CD_HAS_Z80_BUS & CD_TR_RD_Z80) ? 8'bzzzz_zzzz : SDD_IN; + +wire [19:0] ADPCMA_ADDR; +wire [4:0] ADPCMA_BANK; +wire [23:0] ADPCMB_ADDR; + +reg adpcm_wr, adpcm_rd; +reg old_download, old_reset, old_CD_TR_WR_PCM; +wire adpcm_wrack, adpcm_rdack; + +wire ddr_loading = ioctl_download & (((ioctl_index >= INDEX_VROMS) & (ioctl_index < INDEX_CROMS)) | (ioctl_index == INDEX_M1ROM)); +reg ddram_wait = 0; +reg ddram_dtack; + +// Copied from Genesis_MiSTer/Genesis.sv +always @(posedge clk_sys) +begin + + old_download <= ddr_loading; + old_reset <= nRESET; + old_CD_TR_WR_PCM <= CD_TR_WR_PCM; + + if (old_reset & ~nRESET) ddram_wait <= 0; + + if (old_download & ~ddr_loading) + ddram_wait <= 0; // Needed ? + + if (ddram_dtack & nAS) begin + ddram_dtack <= 0; + end + + if (ddr_loading & ioctl_wr) begin + ddram_wait <= 1; + adpcm_wr <= ~adpcm_wr; + ddr_waddr <= (ioctl_index == INDEX_M1ROM) ? {1'b1,ioctl_addr[24:0]} : VROM_LOAD_ADDR; + ddr_wr_din <= ioctl_dout; + ddr_we_byte <= 0; + end else if (~old_CD_TR_WR_PCM & CD_TR_WR_PCM) begin // CD write to PCM + ddram_wait <= 1; + adpcm_wr <= ~adpcm_wr; + ddr_waddr <= { 6'b00_0000, CD_BANK_PCM, (DMA_RUNNING ? DMA_ADDR_OUT[19:1] : M68K_ADDR[19:1])}; + ddr_wr_din <= DMA_RUNNING ? DMA_DATA_OUT : M68K_DATA; + ddr_we_byte <= 1; + end else if (ddram_wait & (adpcm_wr == adpcm_wrack)) begin + ddram_wait <= 0; + ddram_dtack <= 1; + end +end + +assign DDRAM_CLK = CLK_96M; + +// The ddram request and ack signals work on either edge +// To trigger a read request, just set adpcm_rd to ~adpcm_rdack + +reg ADPCMA_READ_REQ, ADPCMB_READ_REQ; +reg ADPCMA_READ_ACK, ADPCMB_READ_ACK; +reg [24:0] ADPCMA_ADDR_LATCH; // 16MB(32MB) +reg [24:0] ADPCMB_ADDR_LATCH; // 32MB +reg [23:0] ADPCMB_MASK; +reg [7:0] ADPCMA_ACK_COUNTER; +reg [10:0] ADPCMB_ACK_COUNTER; +wire ADPCMA_DATA_READY = ~((ADPCMA_READ_REQ ^ ADPCMA_READ_ACK) & (ADPCMA_ACK_COUNTER == 8'd0)); +wire ADPCMB_DATA_READY = ~((ADPCMB_READ_REQ ^ ADPCMB_READ_ACK) & (ADPCMB_ACK_COUNTER == 11'd0)); + +reg OLD_CD_TR_RD_PCM; +reg ADPCMA_RD_DTACK, ADPCMA_RD_WAIT; +always @(posedge DDRAM_CLK) begin + reg [1:0] ADPCMA_OE_SR; + reg [1:0] ADPCMB_OE_SR; + ADPCMA_OE_SR <= {ADPCMA_OE_SR[0], nSDROE}; + ADPCMA_ACK_COUNTER <= ADPCMA_ACK_COUNTER == 8'd0 ? 8'd0 : ADPCMA_ACK_COUNTER - 8'd1; + ADPCMB_ACK_COUNTER <= ADPCMB_ACK_COUNTER == 11'd0 ? 11'd0 : ADPCMB_ACK_COUNTER - 11'd1; + // Trigger ADPCM A data read on nSDROE falling edge + if (ADPCMA_OE_SR == 2'b10 & ~CD_USE_PCM) begin + ADPCMA_READ_REQ <= ~ADPCMA_READ_REQ; + ADPCMA_ADDR_LATCH <= {ADPCMA_BANK, ADPCMA_ADDR} & V1ROM_MASK[24:0]; + // Data is needed on one previous 8MHz clk before next 666KHz clock->(96MHz/666KHz = 144)-12-4=128 + ADPCMA_ACK_COUNTER <= 8'd128; + end + + ADPCMB_MASK <= use_pcm ? V1ROM_MASK[23:0] : V2ROM_MASK[23:0]; + + // Trigger ADPCM B data read on nSDPOE falling edge + ADPCMB_OE_SR <= {ADPCMB_OE_SR[0], nSDPOE}; + if (ADPCMB_OE_SR == 2'b10 & ~SYSTEM_CDx) begin + ADPCMB_READ_REQ <= ~ADPCMB_READ_REQ; + ADPCMB_ADDR_LATCH <= {~use_pcm, ADPCMB_ADDR & ADPCMB_MASK}; + // Data is needed on one previous 8MHz clk before next 55KHz clock->(96MHz/55KHz = 1728)-144-4=1580 + ADPCMB_ACK_COUNTER <= 11'd1580; + end + + // ADPCM A read by 68K + OLD_CD_TR_RD_PCM <= CD_TR_RD_PCM; + if (~OLD_CD_TR_RD_PCM & CD_TR_RD_PCM) begin + ADPCMA_ADDR_LATCH <= { 4'b0000, CD_BANK_PCM, (DMA_RUNNING ? DMA_ADDR_IN[19:1] : M68K_ADDR[19:1]) }; + ADPCMA_READ_REQ <= ~ADPCMA_READ_REQ; + ADPCMA_RD_WAIT <= 1; + end else if (ADPCMA_RD_WAIT & (ADPCMA_READ_REQ == ADPCMA_READ_ACK)) begin + ADPCMA_RD_WAIT <= 0; + ADPCMA_RD_DTACK <= 1; + end + + if (ADPCMA_RD_DTACK & nAS) begin + ADPCMA_RD_DTACK <= 0; + end +end + +assign M68K_DATA[7:0] = ~CD_TR_RD_PCM ? 8'bzzzz_zzzz : ADPCMA_DOUT; + +wire [7:0] ADPCMA_DOUT; +wire [7:0] ADPCMA_DATA = (CD_USE_PCM || !V1ROM_MASK) ? 8'h80 : ADPCMA_DOUT; + +wire [7:0] ADPCMB_DOUT; +wire [7:0] ADPCMB_DATA = (!ADPCMB_MASK) ? 8'h80 : ADPCMB_DOUT; + +reg [27:0] ddr_waddr; +reg [15:0] ddr_wr_din; +reg ddr_we_byte; + +ddram DDRAM( + .*, + + .cache_reset(~nRESET), + + .wraddr(ddr_waddr), + .din(ddr_wr_din), + .we_req(adpcm_wr), + .we_ack(adpcm_wrack), + .we_byte(ddr_we_byte), + + .rdaddr(ADPCMA_ADDR_LATCH), + .dout(ADPCMA_DOUT), + .rd_req(ADPCMA_READ_REQ), + .rd_ack(ADPCMA_READ_ACK), + + .rdaddr2(ADPCMB_ADDR_LATCH), + .dout2(ADPCMB_DOUT), + .rd_req2(ADPCMB_READ_REQ), + .rd_ack2(ADPCMB_READ_ACK), + + .rdaddr3({7'b10_0000_0,MA & MROM_MASK[18:11],SDA[10:0]}), + .dout3(M1_ROM_DATA), + .rd_req3(z80rd_req), + .rd_ack3(z80rd_ack), + + .cpaddr({1'b1, ddr_cpaddr}), + .cpdout(ddr_cpdout), + .cpwr(ddr_cpwr), + .cpreq(ddr_cpreq), + .cpbusy(ddr_cpbusy) +); + +wire [26:0] ddr_cpaddr = cur_off; +wire [63:0] ddr_cpdout; +wire ddr_cpwr; +wire ddr_cpbusy; +reg ddr_cpreq; +wire [26:0] sdr_cpaddr = cp_addr + cur_off; +wire [15:0] sdr_cpdin; +wire sdr1_cprd, sdr2_cprd; +wire sdr_cprd = sdr1_cprd | sdr2_cprd; +wire sdr1_cpbusy, sdr2_cpbusy; +wire sdr_cpbusy = sdr1_cpbusy | sdr2_cpbusy; +reg sdr_cpreq; + +cpram cpram +( + .clock(CLK_96M), + .reset(~memcp_wait), + + .wr(ddr_cpwr), + .data(ddr_cpdout), + + .rd(sdr_cprd), + .q(sdr_cpdin) +); + +reg cp_op; +reg [7:0] cp_idx; +reg [26:0] cp_size; +reg [26:0] cp_addr; +reg [26:0] cp_last; +reg [26:0] cur_off; + +reg [26:0] cp_end; + +wire [26:0] cp_offset = + (cp_idx == INDEX_SPROM) ? SPROM_OFFSET : + (cp_idx == INDEX_SFIXROM) ? SFIXROM_OFFSET : + (cp_idx == INDEX_S1ROM) ? S1ROM_OFFSET : + (cp_idx == INDEX_P1ROM_A) ? P1ROM_A_OFFSET : + (cp_idx == INDEX_P1ROM_B) ? P1ROM_B_OFFSET : + (cp_idx == INDEX_P2ROM) ? P2ROM_OFFSET : + (cp_idx == INDEX_CROM0) ? {CROM_START, 20'd0}: + (cp_idx >= INDEX_VROMS) ? ({cp_idx[7:0]-INDEX_VROMS[7:0], 19'h00000}) : + 27'd0; + +reg memcp_req = 0; +reg memcp_ack = 0; +wire memcp_wait = (memcp_req != memcp_ack); + +always @(posedge clk_sys) begin + if(ioctl_download && ioctl_index == INDEX_MEMCP) begin + if(ioctl_wr) begin + case(ioctl_addr[3:0]) + 0: {cp_op,cp_idx} <= {~ioctl_dout[15],ioctl_dout[7:0]}; + 2: cp_size[15:0] <= ioctl_dout; + 4: begin + cp_size[26:16] <= ioctl_dout[10:0]; + cp_addr <= cp_offset; + cp_end <= cp_offset + {ioctl_dout[10:0], cp_size[15:0]}; + end + 6: if(ioctl_dout && cp_op) memcp_req <= ~memcp_req; + endcase + + if(~cp_op) begin + case(ioctl_addr[3:0]) + 2: cfg[15:0] <= ioctl_dout; + 4: cfg[31:16] <= ioctl_dout; + endcase + end + end + end +end + +reg [1:0] memcp_state = 0; +always @(posedge CLK_96M) begin + case(memcp_state) + 0: if(~memcp_wait) begin + ddr_cpreq <= 0; + sdr_cpreq <= 0; + cur_off <= 0; + end + else if((~sdr2_en && ~sdr_pri_cpsel) || (cur_off >= cp_size)) memcp_ack <= memcp_req; + else begin + ddr_cpreq <= 1; + memcp_state <= 1; + end + + 1: if(ddr_cpbusy) ddr_cpreq <= 0; + else if(~ddr_cpreq & ~ddr_cpbusy) begin + sdr_cpreq <= 1; + memcp_state <= 2; + end + + 2: if(sdr_cpbusy) sdr_cpreq <= 0; + else if(~sdr_cpreq & ~sdr_cpbusy) begin + cur_off <= cur_off + 27'd1024; + memcp_state <= 0; + end + endcase + + if(~memcp_wait) memcp_state <= 0; +end + +wire [7:0] YM2610_DOUT; + +reg adpcm_en; +reg [7:0] adpcma_d, adpcmb_d; +always @(posedge CLK_48M) begin + reg en; + en <= ADPCMA_DATA_READY & ADPCMB_DATA_READY; + adpcm_en <= en; + + adpcma_d <= ADPCMA_DATA; + adpcmb_d <= ADPCMB_DATA; +end + +jt10 YM2610( + .rst(~Z80_nRESET), + .clk(CLK_48M), .cen((CLK_EN_4M_P | CLK_EN_4M_N) & adpcm_en), + .addr(SDA[1:0]), + .din(SDD_OUT), .dout(YM2610_DOUT), + .cs_n(n2610CS), .wr_n(n2610WR), + .irq_n(Z80_nINT), + .adpcma_addr(ADPCMA_ADDR), .adpcma_bank(ADPCMA_BANK), .adpcma_roe_n(nSDROE), .adpcma_data(adpcma_d), + .adpcmb_addr(ADPCMB_ADDR), .adpcmb_roe_n(nSDPOE), .adpcmb_data(SYSTEM_CDx ? 8'h08 : adpcmb_d), // CD has no ADPCM-B + .snd_right(snd_right), .snd_left(snd_left), .snd_enable(~{4{dbg_menu}} | ~status[28:25]), .ch_enable(~status[62:57]) +); + +wire [16:0] snd_mix_l = $signed(snd_left) + $signed(CD_AUDIO_L); +wire [16:0] snd_mix_r = $signed(snd_right) + $signed(CD_AUDIO_R); + + +// For Neo CD only +wire VIDEO_EN = SYSTEM_CDx ? CD_VIDEO_EN : 1'b1; +wire FIX_EN = SYSTEM_CDx ? CD_FIX_EN : 1'b1; +wire SPR_EN = SYSTEM_CDx ? CD_SPR_EN : 1'b1; +wire DOTA_GATED = SPR_EN & DOTA; +wire DOTB_GATED = SPR_EN & DOTB; +wire HSync; //,VSync; + +lspc2_a2_sync LSPC( + .CLK(CLK_48M), + .CLK_EN_24M_P(CLK_EN_24M_P), + .CLK_EN_24M_N(CLK_EN_24M_N), + .RESET(nRESET), + .nRESETP(nRESETP), + .LSPC_8M(), .LSPC_4M(), + .LSPC_EN_4M_P(CLK_EN_4M_P), .LSPC_EN_4M_N(CLK_EN_4M_N), + .M68K_ADDR(M68K_ADDR[3:1]), .M68K_DATA(M68K_DATA), + .IPL0(IPL0), .IPL1(IPL1), + .CD_VBLANK_IRQ_EN(CD_VBLANK_IRQ_EN | ~SYSTEM_CDx), + .CD_TIMER_IRQ_EN(CD_TIMER_IRQ_EN | ~SYSTEM_CDx), + .LSPOE(nLSPOE), .LSPWE(nLSPWE), + .PBUS_OUT(PBUS[15:0]), .PBUS_IO(PBUS[23:16]), + .nPBUS_OUT_EN(nPBUS_OUT_EN), + .DOTA(DOTA_GATED), .DOTB(DOTB_GATED), + .CA4(CA4), .S2H1(S2H1), .S1H1(S1H1), + .LOAD(LOAD), .H(H), .EVEN1(EVEN1), .EVEN2(EVEN2), + .PCK1(PCK1), .PCK2(PCK2), + .PCK1_EN_N(PCK1_EN_N), .PCK2_EN_N(PCK2_EN_N), + .PCK1_EN_P(PCK1_EN_P), .PCK2_EN_P(PCK2_EN_P), + .CHG(CHG), + .LD1(LD1), .LD2(LD2), + .WE(WE), .CK(CK), .SS1(SS1), .SS2(SS2), + .HSYNC(HSync), //.VSYNC(VSync), + .CHBL(CHBL), .BNKB(nBNKB), + .VCS(VCS), + .SVRAM_ADDR(SLOW_VRAM_ADDR), + .SVRAM_DATA_IN(SLOW_VRAM_DATA_IN), .SVRAM_DATA_OUT(SLOW_VRAM_DATA_OUT), + .BOE(BOE), .BWE(BWE), + .FVRAM_ADDR(FAST_VRAM_ADDR), + .FVRAM_DATA_IN(FAST_VRAM_DATA_IN), .FVRAM_DATA_OUT(FAST_VRAM_DATA_OUT), + .CWE(CWE), + .VMODE(video_mode), + .FIXMAP_ADDR(FIXMAP_ADDR) // Extracted for NEO-CMC +); + +wire DOGE = SYSTEM_CDx ? ~CD_UPLOAD_EN : 1'b1; // UPLOAD_EN disables Watchdog? + +neo_b1 B1( + .CLK(CLK_48M), .CLK_EN_6MB(CLK_EN_6MB), .CLK_EN_1HB(CLK_EN_1HB), + .S1H1(S1H1), + .A23I(A23Z), .A22I(A22Z), + .M68K_ADDR_U(M68K_ADDR[21:17]), .M68K_ADDR_L(M68K_ADDR[12:1]), + .nLDS(nLDS), .RW(M68K_RW), .nAS(nAS), + .PBUS(PBUS), + .FIXD(FIXD), + .PCK1_EN(PCK1_EN_P), .PCK2_EN(PCK2_EN_P), + .CHBL(CHBL), .BNKB(nBNKB), + .GAD(GAD), .GBD(GBD), + .WE(WE), .CK(CK), + .TMS0(CHG), .LD1(LD1), .LD2(LD2), .SS1(SS1), .SS2(SS2), + .PA(PAL_RAM_ADDR), + .EN_FIX(FIX_EN), + .DOGE(DOGE), + .nRST(nRESET_CORE), + .nRESET(nRESET) +); + +spram #(13,16) PALRAM( + .clock(CLK_48M), // Was CLK_12M + .address({PALBNK, PAL_RAM_ADDR}), + .data(M68K_DATA), + .wren(~nPAL_WE), + .q(PAL_RAM_DATA) +); + +// DAC latches +reg ce_pix; +reg [2:0] HBlank; +reg HBlank304; +always @(posedge CLK_VIDEO) begin + reg [9:0] pxcnt; + + ce_pix <= 0; + if(CLK_EN_6MB) begin + ce_pix <= 1; + PAL_RAM_REG <= (nRESET && VIDEO_EN && ((pxcnt >= 7 && pxcnt < 311) || ~status[16])) ? PAL_RAM_DATA : 16'h8000; + end + + if(ce_pix) begin + HBlank <= (HBlank<<1) | CHBL; + + pxcnt <= pxcnt + 1'b1; + if(HBlank[1:0] == 2'b10) pxcnt <= 0; + end +end + +//Re-create VSync as original one is barely equals to VBlank +reg VSync; +reg RFSH; +always @(posedge CLK_VIDEO) begin + reg old_hs; + reg old_vbl; + reg [2:0] vbl; + reg [7:0] vblcnt, vspos, rfsh_cnt; + + if(ce_pix) begin + old_hs <= HSync; + if(~old_hs & HSync) begin + old_vbl <= nBNKB; + + if(~nBNKB) vblcnt <= vblcnt+1'd1; + if(old_vbl & ~nBNKB) vblcnt <= 0; + if(~old_vbl & nBNKB) begin + vspos <= (vblcnt>>1) - 8'd7; + rfsh_cnt <= vblcnt-2'd2; + end + + {VSync,vbl} <= {vbl,1'b0}; + if(vblcnt == vspos) {VSync,vbl} <= '1; + end + + RFSH <= (vblcnt < rfsh_cnt); + end +end + +assign VGA_SL = scale ? scale[1:0] - 1'd1 : 2'd0; +assign VGA_F1 = 0; + +wire [2:0] scale = status[20:18]; + +wire [6:0] R6 = {1'b0, PAL_RAM_REG[11:8], PAL_RAM_REG[14], PAL_RAM_REG[11]} - PAL_RAM_REG[15]; +wire [6:0] G6 = {1'b0, PAL_RAM_REG[7:4], PAL_RAM_REG[13], PAL_RAM_REG[7] } - PAL_RAM_REG[15]; +wire [6:0] B6 = {1'b0, PAL_RAM_REG[3:0], PAL_RAM_REG[12], PAL_RAM_REG[3] } - PAL_RAM_REG[15]; + +wire [7:0] R8 = R6[6] ? 8'd0 : {R6[5:0], R6[4:3]}; +wire [7:0] G8 = G6[6] ? 8'd0 : {G6[5:0], G6[4:3]}; +wire [7:0] B8 = B6[6] ? 8'd0 : {B6[5:0], B6[4:3]}; + +wire [7:0] r,g,b; +wire hs,vs,hblank,vblank; +video_cleaner video_cleaner +( + .clk_vid(CLK_VIDEO), + .ce_pix(ce_pix), + + .R(~SHADOW ? R8 : {1'b0, R8[7:1]}), + .G(~SHADOW ? G8 : {1'b0, G8[7:1]}), + .B(~SHADOW ? B8 : {1'b0, B8[7:1]}), + + .HSync(HSync), + .VSync(VSync), + .HBlank(HBlank[0]), + .VBlank(~nBNKB), + + .VGA_R(r), + .VGA_G(g), + .VGA_B(b), + .VGA_VS(vs), + .VGA_HS(hs), + .HBlank_out(hblank), + .VBlank_out(vblank) +); + +video_mixer #(.LINE_LENGTH(320), .HALF_DEPTH(0), .GAMMA(1)) video_mixer +( + .*, + .scandoubler(scale || forced_scandoubler), + .hq2x(scale==1), + .freeze_sync(), + + .VGA_DE(vga_de), + .R(r), + .G(g), + .B(b), + + // Positive pulses. + .HSync(hs), + .VSync(vs), + .HBlank(hblank), + .VBlank(vblank) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/releases/README.md b/MiSTer-devel_NeoGeo_MiSTer/releases/README.md new file mode 100644 index 0000000000000000000000000000000000000000..91abd5fd1fe831e59d750a409d3f9b19393d5849 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/releases/README.md @@ -0,0 +1,79 @@ +# Using purchased ROMs (gog-romset.xml) + +Good Old Games (at least the Linux versions), Humble Bundle store and possibly +other sellers contain the image of individual ROM chips, unlike the Darksoft +rom pack which preprocessed these images. + +This document will help you locate the ROM files in an installed game, get them +where you need them, and get the most out of your purchase. + +Note: gog-romsets.xml needs to be renamed to romsets.xml for these games to function. + +## BIOS images + +Chances are, your purchase contains all the ROM images you need for MiSTer +(see the top-level README file in this repository), maybe located in an +archive named `neogeo.zip`. + +## Locating game ROM images + +You will need to do this once per game. + +Once you have installed a game, you will need to locate the game ROMs. + +Plain rom images have names which should look like `201-p1.p1` (number, dash, +one or two letters, a number, dot, one or two letters, a number). The number +identifies the game, and is listed in the tables below. + +Chances are these files will be in a `.zip` archive. For Metal Slug, they would +be in a file named `mslug.zip`, for example. + +Locate your game in the table below. In your MiSTer NeoGeo folder +(`/games/NeoGeo`), create a folder named like the +game (this would be `mslug` for Metal Slug) and put the ROM images there +(extracted from the `.zip` file if any). + +Some games contain come in more than one version (ex: a Korean version). In +this case, create the folders listed in the "other versions" column, and they +will appear. Unless otherwise noted, you do not have to put anything in these +folders - they are just here to let MiSTer know these versions should be +displayed. Note: you must keep the main folder, as it contains the ROMs +actually being used. + +## Game list + +Grouped by MiSTer SDRAM requirements. + +### 32 MB + +| Number | Name | Title | Other Versions | Notes | +| --- | --- | --- | --- | --- | +| 056 | `aof2` | Art of Fighting 2 | `aof2a` | | +| 041 | `bstars2` | Baseball Stars 2 | | | +| 058 | `fatfursp` | Fatal Fury Special | `fatfurspa` | | +| 220 | `ironclad` | Iron Clad | ironclado | Most ROM names start with `proto_` | +| 016 | `kotm` | King of the Monsters | `kotmh` | | +| 201 | `mslug` | Metal Slug | | | +| 201 | `mslug2` | Metal Slug 2 | `mslug2t` | `mslug2t` requires the [3rd-party "turbo" patch](http://blog.system11.org/?p=1442). This will produce the `941-p1.p1` file which you must place in the `mslug2t` folder. | +| 063 | `samsho2` | Samurai Shodown II | `samsho2k` `samsho2k2` | | +| 200 | `turfmast` | Neo Turf Masters | | | +| 224 | `twinspri` | Twinkle Star Sprites | | | + +### 64 MB + +| Number | Name | Title | Other Versions | Notes | +| --- | --- | --- | --- | --- | +| 239 | `blazstar` | Blazing Star | | | +| 234 | `lastblad` | Last Blade (The) | `lastbladh` `lastsold` | | +| 089 | `pulstar` | Pulstar | | | +| 240 | `rbff2` | Real Bout Fatal Fury 2 | `rbff2h` `rbff2k` | | +| 246 | `shocktr2` | Shock Troopers - 2nd Squad | | | +| 238 | `shocktro` | Shock Troopers | `shcktroa` | | + +### 96 MB + +(none working) + +### 128 MB + +(none) diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/CEGen.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/CEGen.vhd new file mode 100644 index 0000000000000000000000000000000000000000..37d74c4194547d1f575094969f975e13936457c0 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/CEGen.vhd @@ -0,0 +1,34 @@ +LIBRARY ieee; +USE ieee.std_logic_1164.all; + +ENTITY CEGen IS + PORT + ( + CLK : in STD_LOGIC; + RST_N : in STD_LOGIC; + + IN_CLK : in integer; + OUT_CLK : in integer; + + CE : out STD_LOGIC + ); +END CEGen; + +ARCHITECTURE SYN OF CEGen IS +BEGIN + process( RST_N, CLK ) + variable CLK_SUM : integer; + begin + if RST_N = '0' then + CLK_SUM := 0; + CE <= '0'; + elsif falling_edge(CLK) then + CE <= '0'; + CLK_SUM := CLK_SUM + OUT_CLK; + if CLK_SUM >= IN_CLK then + CLK_SUM := CLK_SUM - IN_CLK; + CE <= '1'; + end if; + end if; + end process; +END SYN; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cd.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cd.sv new file mode 100644 index 0000000000000000000000000000000000000000..b26cd300c9c65f855b5376bf2d609f3274b03347 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cd.sv @@ -0,0 +1,811 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module cd_sys( + input nRESET, + //input CLK_68KCLK, + input CLK_68KCLK_EN, + input [23:1] M68K_ADDR, + inout [15:0] M68K_DATA, + input A22Z, A23Z, + input nLDS, nUDS, + input M68K_RW, nAS, nDTACK, + input SYSTEM_CDx, + input [1:0] CD_REGION, + input [1:0] CD_SPEED, + output reg CD_VIDEO_EN, + output reg CD_FIX_EN, + output reg CD_SPR_EN, + + output reg CD_nRESET_Z80, + + output CD_TR_WR_SPR, + output CD_TR_WR_PCM, + output CD_TR_WR_Z80, + output CD_TR_WR_FIX, + + output CD_TR_RD_FIX, + output CD_TR_RD_SPR, + output CD_TR_RD_Z80, + output CD_TR_RD_PCM, + + output reg CD_USE_FIX, + output reg CD_USE_SPR, + output reg CD_USE_Z80, + output reg CD_USE_PCM, + output reg [2:0] CD_TR_AREA, + output reg [1:0] CD_BANK_SPR, + output reg CD_BANK_PCM, + output reg [15:0] CD_TR_WR_DATA, + output reg [19:1] CD_TR_WR_ADDR, + output reg CD_UPLOAD_EN, // The bios writes to Z80 RAM without CD_UPLOAD_EN enabled. Maybe this is only watchdog disable? + + output CD_VBLANK_IRQ_EN, + output CD_TIMER_IRQ_EN, + + input IACK, + output reg CD_IRQ, + + input clk_sys, + input [39:0] CDD_STATUS_IN, + input CDD_STATUS_LATCH, + output [39:0] CDD_COMMAND_DATA, + output CDD_COMMAND_SEND, + + input CD_DATA_DOWNLOAD, + input CD_DATA_WR, + input [15:0] CD_DATA_DIN, + input [11:1] CD_DATA_ADDR, // word address + output CD_DATA_WR_READY, // Ready to receive sector + + input CDDA_RD, + input CDDA_WR, + output [15:0] CD_AUDIO_L, + output [15:0] CD_AUDIO_R, + output CDDA_WR_READY, + + input CD_LID, // DEBUG + + // For DMA + output reg nBR, + input nBG, + output reg nBGACK, + + output reg DMA_RUNNING, + output reg [15:0] DMA_DATA_OUT, + input [15:0] DMA_DATA_IN, + output reg DMA_WR_OUT, + output reg DMA_RD_OUT, + output reg [23:0] DMA_ADDR_IN, // Used for reading + output reg [23:0] DMA_ADDR_OUT, // Used for writing + + input DMA_SDRAM_BUSY +); + parameter MCLK = 96671316; + + reg CD_nRESET_DRIVE; + reg [15:0] REG_FF0002; + reg [11:0] REG_FF0004; + reg [2:0] CD_IRQ_FLAGS; + + reg [23:0] DMA_ADDR_A; + reg [23:0] DMA_ADDR_B; + reg [31:0] DMA_VALUE; + reg [31:0] DMA_COUNT; // TODO: This can probably be 23:0 + reg [15:0] DMA_MICROCODE [9]; + + reg CDD_nIRQ_PREV, CDC_nIRQ_PREV; + reg nLDS_PREV, nUDS_PREV; + + reg [3:0] CDD_DIN; + wire [3:0] CDD_DOUT; + + wire HOCK, CDCK, CDD_nIRQ; + + cd_drive DRIVE( + .clk_sys(clk_sys), + .nRESET(nRESET & CD_nRESET_DRIVE), + .HOCK(HOCK), .CDCK(CDCK), + .CDD_DIN(CDD_DIN), .CDD_DOUT(CDD_DOUT), + .CDD_nIRQ(CDD_nIRQ), + .STATUS_IN(CDD_STATUS_IN), + .STATUS_LATCH(CDD_STATUS_LATCH), + .COMMAND_DATA(CDD_COMMAND_DATA), + .COMMAND_SEND(CDD_COMMAND_SEND) + ); + + wire [7:0] LC8951_DOUT; + wire CDC_nIRQ; + wire [31:0] HEADER_DIN; + + lc8951 LC8951( + .nRESET(nRESET), + .clk_sys(clk_sys), + //.CLK_12M(CLK_68KCLK), + .CLK_68KCLK_EN(CLK_68KCLK_EN), + .nWR(~LC8951_WR), .nRD(~LC8951_RD), + .RS(M68K_ADDR[1]), + .DIN(M68K_DATA[7:0]), + .DOUT(LC8951_DOUT), + .HEADER_DIN(HEADER_DIN), + .SECTOR_READY(SECTOR_READY), + .DMA_RUNNING(DMA_RUNNING), + .CDC_nIRQ(CDC_nIRQ) + ); + + cdda CDDA( + .CLK(clk_sys), + .nRESET(nRESET), + .READ(CDDA_RD), + .WRITE(CDDA_WR), + .DIN(CD_DATA_DIN), + .AUDIO_L(CD_AUDIO_L), + .AUDIO_R(CD_AUDIO_R), + .WRITE_READY(CDDA_WR_READY) + ); + + localparam SECTOR_TIME_1X = MCLK / 75; + localparam SECTOR_TIME_2X = MCLK / 150; + localparam SECTOR_TIME_3X = MCLK / 225; + localparam SECTOR_TIME_4X = MCLK / 300; + + reg [20:0] SECTOR_TIME; + wire [20:0] SECTOR_TIME_SEL = (CD_SPEED == 2'd0) ? SECTOR_TIME_1X[20:0] : + (CD_SPEED == 2'd1) ? SECTOR_TIME_2X[20:0] : + (CD_SPEED == 2'd2) ? SECTOR_TIME_3X[20:0] : + SECTOR_TIME_4X[20:0]; + + reg SECTOR_READY; // For decoder interrupt + reg SECTOR_FILLED[2]; + reg [23:0] SECTOR_TIME_CNT; + + reg FORCE_WR; + reg [2:0] LOADING_STATE; + reg [10:0] CACHE_RD_ADDR, CACHE_WR_ADDR; // 0~2047 + reg CACHE_RD_BANK, CACHE_WR_BANK; + reg CACHE_WR_EN; + + assign CD_DATA_WR_READY = ~SECTOR_FILLED[~CACHE_RD_BANK]; + + reg [7:0] HEAD_0[2]; + reg [7:0] HEAD_1[2]; + reg [7:0] HEAD_2[2]; + reg [7:0] HEAD_3[2]; + + assign HEADER_DIN = { HEAD_3[CACHE_RD_BANK], HEAD_2[CACHE_RD_BANK], HEAD_1[CACHE_RD_BANK], HEAD_0[CACHE_RD_BANK] }; + + wire [7:0] CACHE_DIN = CACHE_WR_ADDR[0] ? CD_DATA_DIN[15:8] : CD_DATA_DIN[7:0]; + wire CACHE_WR = CACHE_WR_EN & (CD_DATA_WR_START | FORCE_WR); + wire [7:0] CACHE_DOUT; + + dpram #(12,8) CACHE( + .clock_a(clk_sys), + .address_a( {CACHE_WR_BANK, CACHE_WR_ADDR} ), + .data_a(CACHE_DIN), + .wren_a(CACHE_WR), + + .clock_b(clk_sys), + .address_b( {CACHE_RD_BANK, CACHE_RD_ADDR} ), + .wren_b(0), + .q_b(CACHE_DOUT) +); + + localparam DMA_STATE_IDLE = 4'd0, DMA_STATE_BR = 4'd1, DMA_STATE_WAIT_BG = 4'd2, + DMA_STATE_WAIT_AS = 4'd3, DMA_STATE_START = 4'd4, + DMA_STATE_CACHE_RD = 4'd5, DMA_STATE_CACHE_RD_L = 4'd6, + DMA_STATE_INIT_RD = 4'd7, DMA_STATE_RD = 4'd8, DMA_STATE_RD_DONE = 4'd9, + DMA_STATE_INIT_WR = 4'd10, DMA_STATE_WR = 4'd11, DMA_STATE_WR_DONE = 4'd12, + DMA_STATE_DONE = 4'd13; + + localparam DMA_COPY_CD_WORD = 3'd0, DMA_COPY_CD_BYTE = 3'd1, DMA_COPY_WORD = 3'd2, + DMA_COPY_BYTE = 3'd3, DMA_FILL_VALUE = 3'd4; + + reg DMA_START_PREV, DMA_START; + reg [2:0] DMA_MODE; + reg [3:0] DMA_STATE; + reg [3:0] DMA_IO_CNT; + reg [7:0] DMA_TIMER; + reg [15:0] DMA_RD_DATA; + reg [31:0] DMA_COUNT_RUN; + + localparam DMA_RW_CYCLES = MCLK / 4800000; // TODO: Tune this + + reg CD_DATA_WR_PREV; + wire CD_DATA_WR_START = CD_DATA_WR & ~CD_DATA_WR_PREV; + wire CD_DATA_WR_END = ~CD_DATA_WR & CD_DATA_WR_PREV; + + always @(posedge clk_sys) + begin + if (!nRESET) + begin + FORCE_WR <= 0; + SECTOR_READY <= 0; + SECTOR_FILLED[0] <= 0; + SECTOR_FILLED[1] <= 0; + SECTOR_TIME_CNT <= 0; + SECTOR_TIME <= SECTOR_TIME_1X[20:0]; + + LOADING_STATE <= 3'd0; // Idle, waiting for request + + DMA_STATE <= 4'd0; + nBR <= 1; + nBGACK <= 1; + + DMA_RUNNING <= 0; + DMA_TIMER <= 8'd0; + + CACHE_WR_EN <= 0; + CACHE_RD_BANK <= 0; + CACHE_WR_BANK <= 0; + + CD_DATA_WR_PREV <= 0; + end + else + begin + + if (SECTOR_TIME_CNT == {1'b0, SECTOR_TIME[20:1]}) begin + SECTOR_READY <= 0; + end + + if (SECTOR_TIME_CNT < SECTOR_TIME) begin + SECTOR_TIME_CNT <= SECTOR_TIME_CNT + 1'b1; + end else begin + if (SECTOR_FILLED[~CACHE_RD_BANK]) begin + SECTOR_FILLED[CACHE_RD_BANK] <= 0; + SECTOR_READY <= 1; + CACHE_RD_BANK <= ~CACHE_RD_BANK; + SECTOR_TIME_CNT <= 0; + SECTOR_TIME <= SECTOR_TIME_SEL; + end + end + + CD_DATA_WR_PREV <= CD_DATA_WR; + if (LOADING_STATE == 3'd0) begin + if (CD_DATA_WR_READY) begin + if (CD_DATA_DOWNLOAD & CD_DATA_WR_END & (CD_DATA_ADDR == 11'd6)) begin + // Bytes 12-13 (Header 0-1) + CACHE_WR_BANK <= ~CACHE_RD_BANK; + + HEAD_0[~CACHE_RD_BANK] <= CD_DATA_DIN[7:0]; + HEAD_1[~CACHE_RD_BANK] <= CD_DATA_DIN[15:8]; + + LOADING_STATE <= 3'd1; + end + end + end + + if (LOADING_STATE == 3'd1) begin + if (CD_DATA_DOWNLOAD & CD_DATA_WR_END & (CD_DATA_ADDR == 11'd7)) begin + // Bytes 14-15 (Header 2-3) + HEAD_2[CACHE_WR_BANK] <= CD_DATA_DIN[7:0]; + HEAD_3[CACHE_WR_BANK] <= CD_DATA_DIN[15:8]; + + CACHE_WR_ADDR <= 11'h000; + CACHE_WR_EN <= 1; + + LOADING_STATE <= 3'd2; + end + end + + if (LOADING_STATE == 3'd2) begin + if (CD_DATA_WR_START) begin + // First byte of pair was written by CD_DATA_WR + CACHE_WR_ADDR <= CACHE_WR_ADDR + 1'b1; + LOADING_STATE <= 3'd3; + FORCE_WR <= 1; + end + + if (~CD_DATA_DOWNLOAD) begin // Incomplete data, should not happen. + LOADING_STATE <= 3'd4; + end + end + + if (LOADING_STATE == 3'd3) begin + // Second byte of pair was written by FORCE_WR + FORCE_WR <= 0; + CACHE_WR_ADDR <= CACHE_WR_ADDR + 1'b1; + if (CACHE_WR_ADDR == 11'd2047) begin + LOADING_STATE <= 3'd4; + end else begin + LOADING_STATE <= 3'd2; + end + end + + if (LOADING_STATE == 3'd4) begin + // Sector load done + CACHE_WR_EN <= 0; + SECTOR_FILLED[CACHE_WR_BANK] <= 1; + LOADING_STATE <= 3'd0; + end + + DMA_START_PREV <= DMA_START; + + // Rising edge of DMA_START + if (~DMA_START_PREV & DMA_START) + begin + DMA_STATE <= 4'd1; + DMA_IO_CNT <= 4'd0; + + DMA_COUNT_RUN <= DMA_COUNT; + + case (DMA_MODE) + + DMA_COPY_CD_WORD, DMA_COPY_CD_BYTE: + begin + // Init byte copy LC8951 cache -> DMA_ADDR_A + DMA_ADDR_OUT <= DMA_ADDR_A; + CACHE_RD_ADDR <= 11'h000; + end + + DMA_COPY_WORD, DMA_COPY_BYTE: + begin + // Init copy DMA_ADDR_A -> DMA_ADDR_B + DMA_ADDR_IN <= DMA_ADDR_A; + DMA_ADDR_OUT <= DMA_ADDR_B; + end + + DMA_FILL_VALUE: + begin + // Init word fill from DMA_ADDR_A + DMA_ADDR_OUT <= DMA_ADDR_A; + DMA_DATA_OUT <= DMA_VALUE[31:16]; // Is [15:0] ever used ? + end + + default: ; + endcase + end + + // DMA logic + + // DMA_TIMER is a minimum wait, so tick it even when DMA_SDRAM_BUSY + if (DMA_TIMER) + DMA_TIMER <= DMA_TIMER - 1'b1; + + if (!DMA_SDRAM_BUSY) + begin + if (!DMA_TIMER) + begin + if (DMA_STATE == DMA_STATE_BR) + begin + // Init: Do 68k bus request + nBR <= 0; + DMA_STATE <= DMA_STATE_WAIT_BG; + end + + if (DMA_STATE == DMA_STATE_WAIT_BG) + begin + // Init: Wait for nBG low + if (~nBG) + DMA_STATE <= DMA_STATE_WAIT_AS; + end + + if (DMA_STATE == DMA_STATE_WAIT_AS) + begin + // Init: Wait for nAS and nDTACK high + if (nAS & nDTACK) + begin + nBR <= 1; + nBGACK <= 0; + DMA_RUNNING <= 1; + DMA_STATE <= DMA_STATE_START; + end + end + + if (DMA_STATE == DMA_STATE_START) + begin + // Base state for DMA loop + // FX68K doesn't tri-state its outputs when it releases the bus (good !) + // So use separate busses and signals when doing DMA and switch them according to DMA_RUNNING + if (!DMA_COUNT_RUN) + begin + // DMA done ! + DMA_STATE <= DMA_STATE_IDLE; // Go back to idle + nBGACK <= 1; // Release bus + DMA_RUNNING <= 0; // Inform CDC that the transfer is finished + end + else + begin + // Working... + case (DMA_MODE) + DMA_COPY_CD_WORD: + begin + // Word copy LC8951 cache -> DMA_ADDR_A + case(DMA_IO_CNT) + 4'd0: DMA_STATE <= DMA_STATE_CACHE_RD; // Read word from Cache + 4'd1: begin + DMA_DATA_OUT <= DMA_RD_DATA; + DMA_STATE <= DMA_STATE_WR; // Write word + end + + default: DMA_STATE <= DMA_STATE_DONE; + endcase + end + + DMA_COPY_CD_BYTE: + begin + // Copy LC8951 cache -> DMA_ADDR_A odd bytes + case(DMA_IO_CNT) + 4'd0: DMA_STATE <= DMA_STATE_CACHE_RD; // Read word from Cache + 4'd1: begin + DMA_DATA_OUT <= {DMA_RD_DATA[7:0], DMA_RD_DATA[15:8]}; + DMA_STATE <= DMA_STATE_WR; // Write low byte + end + 4'd2: begin + DMA_DATA_OUT <= DMA_RD_DATA; + DMA_STATE <= DMA_STATE_WR; // Write high byte + end + + default: DMA_STATE <= DMA_STATE_DONE; + endcase + end + + DMA_COPY_WORD: + begin + // Word copy DMA_ADDR_A -> DMA_ADDR_B + case(DMA_IO_CNT) + 4'd0: DMA_STATE <= DMA_STATE_RD; // Read word + 4'd1: begin + DMA_DATA_OUT <= DMA_RD_DATA; + DMA_STATE <= DMA_STATE_WR; // Write word + end + + default: DMA_STATE <= DMA_STATE_DONE; + endcase + end + + DMA_COPY_BYTE: + begin + // Byte copy DMA_ADDR_A -> DMA_ADDR_B odd bytes + case(DMA_IO_CNT) + 4'd0: DMA_STATE <= DMA_STATE_RD; // Read word + 4'd1: begin + DMA_DATA_OUT <= {DMA_RD_DATA[7:0], DMA_RD_DATA[15:8]}; + DMA_STATE <= DMA_STATE_WR; // Write low byte + end + 4'd2: begin + DMA_DATA_OUT <= DMA_RD_DATA; + DMA_STATE <= DMA_STATE_WR; // Write high byte + end + + default: DMA_STATE <= DMA_STATE_DONE; + endcase + end + + DMA_FILL_VALUE: + begin + // Word fill from DMA_ADDR_A + case(DMA_IO_CNT) + 4'd0: DMA_STATE <= DMA_STATE_WR; + default: DMA_STATE <= DMA_STATE_DONE; + endcase + end + + default: ; + endcase + end + end + + if (DMA_STATE == DMA_STATE_CACHE_RD) + begin + DMA_RD_DATA[15:8] <= CACHE_DOUT; // Got upper byte + CACHE_RD_ADDR <= CACHE_RD_ADDR + 1'b1; + DMA_TIMER <= DMA_RW_CYCLES[7:0] >> 1; // TODO: Tune this + DMA_STATE <= DMA_STATE_CACHE_RD_L; + end + + if (DMA_STATE == DMA_STATE_CACHE_RD_L) + begin + DMA_RD_DATA[7:0] <= CACHE_DOUT; // Got lower byte + CACHE_RD_ADDR <= CACHE_RD_ADDR + 1'b1; + DMA_IO_CNT <= DMA_IO_CNT + 1'b1; + DMA_STATE <= DMA_STATE_START; + end + + if (DMA_STATE == DMA_STATE_WR) + begin + DMA_WR_OUT <= 1; + DMA_TIMER <= DMA_RW_CYCLES[7:0]; // TODO: Tune this + DMA_STATE <= DMA_STATE_WR_DONE; + end + + if (DMA_STATE == DMA_STATE_WR_DONE) + begin + // Write done + DMA_WR_OUT <= 0; + DMA_ADDR_OUT <= DMA_ADDR_OUT + 2'd2; + DMA_IO_CNT <= DMA_IO_CNT + 1'b1; + DMA_STATE <= DMA_STATE_START; + end + + if (DMA_STATE == DMA_STATE_RD) + begin + DMA_RD_OUT <= 1; + DMA_TIMER <= DMA_RW_CYCLES[7:0]; // TODO: Tune this + DMA_STATE <= DMA_STATE_RD_DONE; + end + + if (DMA_STATE == DMA_STATE_RD_DONE) + begin + DMA_RD_OUT <= 0; + DMA_RD_DATA <= DMA_DATA_IN; + DMA_ADDR_IN <= DMA_ADDR_IN + 2'd2; + DMA_IO_CNT <= DMA_IO_CNT + 1'b1; + DMA_STATE <= DMA_STATE_START; + end + + if (DMA_STATE == DMA_STATE_DONE) + begin + DMA_COUNT_RUN <= DMA_COUNT_RUN - 1'b1; + DMA_STATE <= DMA_STATE_START; + DMA_IO_CNT <= 4'd0; + end + + end + end + end + end + + wire READING = ~nAS & M68K_RW & (M68K_ADDR[23:12] == 12'hFF0) & SYSTEM_CDx; + wire WRITING = ~nAS & ~M68K_RW & (M68K_ADDR[23:12] == 12'hFF0) & SYSTEM_CDx; + + wire LC8951_RD = (READING & (M68K_ADDR[11:2] == 10'b0001_000000)); // FF0101, FF0103 + wire LC8951_WR = (WRITING & (M68K_ADDR[11:2] == 10'b0001_000000)); // FF0101, FF0103 + + // nAS used ? + wire TR_ZONE = (DMA_RUNNING ? (DMA_ADDR_OUT[23:20] == 4'hE) : (M68K_ADDR[23:20] == 4'hE)) & SYSTEM_CDx; + + wire TR_ZONE_RD = TR_ZONE & (DMA_RUNNING ? DMA_RD_OUT : M68K_RW & ~(nLDS & nUDS)); + wire TR_ZONE_WR = TR_ZONE & (DMA_RUNNING ? DMA_WR_OUT : ~M68K_RW & ~(nLDS & nUDS)); + + wire CD_TR_SPR = (CD_TR_AREA == 3'd0) & CD_USE_SPR; + wire CD_TR_PCM = (CD_TR_AREA == 3'd1) & CD_USE_PCM; + wire CD_TR_Z80 = (CD_TR_AREA == 3'd4) & CD_USE_Z80; + wire CD_TR_FIX = (CD_TR_AREA == 3'd5) & CD_USE_FIX; + + // Allow writes only if the "allow write" flag of the corresponding region is set + assign CD_TR_WR_SPR = TR_ZONE_WR & CD_TR_SPR; + assign CD_TR_WR_PCM = TR_ZONE_WR & CD_TR_PCM; + assign CD_TR_WR_Z80 = TR_ZONE_WR & CD_TR_Z80; + assign CD_TR_WR_FIX = TR_ZONE_WR & CD_TR_FIX; + + assign CD_TR_RD_FIX = TR_ZONE_RD & CD_TR_FIX; + assign CD_TR_RD_SPR = TR_ZONE_RD & CD_TR_SPR; + assign CD_TR_RD_Z80 = TR_ZONE_RD & CD_TR_Z80; + assign CD_TR_RD_PCM = TR_ZONE_RD & CD_TR_PCM; + + reg [1:0] CDD_nIRQ_SR; + + always @(posedge clk_sys) + begin + if (!nRESET) + begin + CD_USE_SPR <= 0; + CD_USE_PCM <= 0; + CD_USE_Z80 <= 0; + CD_USE_FIX <= 0; + CD_SPR_EN <= 1; // ? + CD_FIX_EN <= 1; // ? + CD_VIDEO_EN <= 1; // ? + CD_UPLOAD_EN <= 0; + CD_nRESET_Z80 <= 0; // ? + CD_nRESET_DRIVE <= 0; // ? + HOCK <= 1; + REG_FF0002 <= 16'h0; // ? + REG_FF0004 <= 0; // ? + nLDS_PREV <= 1; + nUDS_PREV <= 1; + CD_IRQ <= 1; + CD_IRQ_FLAGS <= 3'b111; + DMA_START <= 0; + + CDD_nIRQ_SR <= 2'b11; + end + else if (CLK_68KCLK_EN) begin + nLDS_PREV <= nLDS; + nUDS_PREV <= nUDS; + CDD_nIRQ_SR <= {CDD_nIRQ_SR[0], CDD_nIRQ}; + CDC_nIRQ_PREV <= CDC_nIRQ; + + // Falling edge of CDD_nIRQ + //if (CDD_nIRQ_PREV & ~CDD_nIRQ) + if (CDD_nIRQ_SR == 2'b10) + begin + // Trigger CD comm. interrupt + if (REG_FF0002[6] & REG_FF0002[4]) + CD_IRQ_FLAGS[1] <= 0; + + // REG_FF0002: + // C = CD comm. interrupt + // S = Sector ready interrupt ? + // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + // S S C C + end + + // Falling edge of CDC_nIRQ + if (CDC_nIRQ_PREV & ~CDC_nIRQ) + begin + // Trigger CDC interrupt (decoder or transfer end) + if (REG_FF0002[10] & REG_FF0002[8]) + CD_IRQ_FLAGS[2] <= 0; + end + + CD_IRQ <= ~&{CD_IRQ_FLAGS}; + + // Trigger + if (DMA_START) + DMA_START <= 0; + + if (SYSTEM_CDx & ((nLDS_PREV & ~nLDS) | (nUDS_PREV & ~nUDS))) // & PREV_nAS & ~nAS + begin + // Writes + if ((M68K_ADDR[23:9] == 15'b11111111_0000000) & ~M68K_RW) + begin + casez ({M68K_ADDR[8:1], nUDS, nLDS}) + // FF00xx + 10'b0_0000001_00: REG_FF0002 <= M68K_DATA; // FF0002 + 10'b0_0000010_00: REG_FF0004 <= M68K_DATA[11:0]; // FF0004 + 10'b0_0000111_?0: CD_IRQ_FLAGS <= CD_IRQ_FLAGS | M68K_DATA[5:3]; // FF000E + + 10'b0_0110000_10: // FF0061 + begin + if (M68K_DATA[6]) + begin + // DMA start + DMA_START <= 1; + case (DMA_MICROCODE[0]) + 16'hFF89, 16'hFFC5: + begin + // Copy LC8951 cache -> DMA_ADDR_A + // Count in words even it's really a byte copy + // TOP-SP1 @ C119F4 + // $FF89 $FCF5 $D8A6 $F627 $03FD $FFFF + DMA_MODE <= DMA_COPY_CD_WORD; + end + + 16'hFC2D: + begin + // Copy LC8951 cache -> DMA_ADDR_A odd bytes + // FC2D + DMA_MODE <= DMA_COPY_CD_BYTE; + end + + 16'hFE6D, 16'hFE3D: + begin + // Word copy DMA_ADDR_A -> DMA_ADDR_B + // Count in words + // TOP-SP1 @ C119D4 + // $FE6D $FCF5 $82BF $F693 $BF29 $02FD $FFFF $C515 $FCF5 + + // Word copy DMA_ADDR_A -> DMA_ADDR_B + // Different microcode, same operation ? + // Used by UploadPRGDMAWords, UploadPalDMAWords + // TOP-SP1 @ C0C07C + // $FE6D $FCF5 $82BF $F693 $BF29 $02FD $FFFF $F97D $FCF5 + DMA_MODE <= DMA_COPY_WORD; + end + + 16'hF2DD, 16'hE2DD: + begin + // Byte copy DMA_ADDR_A -> odd bytes DMA_ADDR_B ? + // Used by UploadFIXDMABytes, UploadPCMDMABytes, UploadZ80DMABytes + // Count in words + // TOP-SP1 @ C0C09A + // $F2DD $82F6 $93DA $BE93 $DABE $2C02 $FDFF + DMA_MODE <= DMA_COPY_BYTE; + end + + 16'hFFCD, 16'hFFDD: + begin + // Word fill starting at DMA_ADDR_A + // Used by DMAClearPalettes, DMAClearPCMDRAM? + // Count in words + // TOP-SP1 @ C0C09A + // $FFCD $FCF5 $92F6 $2602 $FDFF + DMA_MODE <= DMA_FILL_VALUE; + end + + default: ; + endcase + // Other microcodes are used but only for the test mode, those can wait + // See TOP-SP1 @ C0AB26, TOP-SP1 @ C0AB3E, TOP-SP1 @ C0AB5A + end + end + 10'b0_0110010_00: DMA_ADDR_A[23:16] <= M68K_DATA[7:0]; // FF0064~FF0065 + 10'b0_0110011_00: DMA_ADDR_A[15:0] <= M68K_DATA; // FF0066~FF0067 + 10'b0_0110100_00: DMA_ADDR_B[23:16] <= M68K_DATA[7:0]; // FF0068~FF0069 + 10'b0_0110101_00: DMA_ADDR_B[15:0] <= M68K_DATA; // FF006A~FF006B + 10'b0_0110110_00: DMA_VALUE[31:16] <= M68K_DATA; // FF006C~FF006D + 10'b0_0110111_00: DMA_VALUE[15:0] <= M68K_DATA; // FF006E~FF006F + 10'b0_0111000_00: DMA_COUNT[31:16] <= M68K_DATA; // FF0070~FF0071 + 10'b0_0111001_00: DMA_COUNT[15:0] <= M68K_DATA; // FF0072~FF0073 + 10'b0_0111111_00: DMA_MICROCODE[0] <= M68K_DATA; // FF007E M68K_ADDR[4:1] + 10'b0_1000000_00: DMA_MICROCODE[1] <= M68K_DATA; // FF0080 M68K_ADDR[4:1] + 10'b0_1000001_00: DMA_MICROCODE[2] <= M68K_DATA; // FF0082 M68K_ADDR[4:1] + 10'b0_1000010_00: DMA_MICROCODE[3] <= M68K_DATA; // FF0084 M68K_ADDR[4:1] + 10'b0_1000011_00: DMA_MICROCODE[4] <= M68K_DATA; // FF0086 M68K_ADDR[4:1] + 10'b0_1000100_00: DMA_MICROCODE[5] <= M68K_DATA; // FF0088 M68K_ADDR[4:1] + 10'b0_1000101_00: DMA_MICROCODE[6] <= M68K_DATA; // FF008A M68K_ADDR[4:1] + 10'b0_1000110_00: DMA_MICROCODE[7] <= M68K_DATA; // FF008C M68K_ADDR[4:1] + 10'b0_1000111_00: DMA_MICROCODE[8] <= M68K_DATA; // FF008E M68K_ADDR[4:1] + + // FF01xx + 10'b1_0000010_?0: CD_TR_AREA <= M68K_DATA[2:0]; // FF0105 Upload area select + 10'b1_0001000_?0: CD_SPR_EN <= ~M68K_DATA[0]; // FF0111 REG_DISBLSPR + 10'b1_0001010_?0: CD_FIX_EN <= ~M68K_DATA[0]; // FF0115 REG_DISBLFIX + 10'b1_0001100_?0: CD_VIDEO_EN <= M68K_DATA[0]; // FF0119 REG_ENVIDEO + 10'b1_0010000_?0: CD_USE_SPR <= 1; // FF0121 REG_UPMAPSPR + 10'b1_0010001_?0: CD_USE_PCM <= 1; // FF0123 REG_UPMAPPCM + 10'b1_0010011_?0: CD_USE_Z80 <= 1; // FF0127 REG_UPMAPZ80 + 10'b1_0010100_?0: CD_USE_FIX <= 1; // FF0129 REG_UPMAPFIX + 10'b1_0100000_?0: CD_USE_SPR <= 0; // FF0141 REG_UPUNMAPSPR + 10'b1_0100001_?0: CD_USE_PCM <= 0; // FF0143 REG_UPUNMAPSPR + 10'b1_0100011_?0: CD_USE_Z80 <= 0; // FF0147 REG_UPUNMAPSPR + 10'b1_0100100_?0: CD_USE_FIX <= 0; // FF0149 REG_UPUNMAPSPR + 10'b1_0110001_10: CDD_DIN <= M68K_DATA[3:0]; // FF0163 REG_CDDOUTPUT + 10'b1_0110010_10: HOCK <= M68K_DATA[0]; // FF0165 REG_CDDCTRL + 10'b1_0110111_?0: CD_UPLOAD_EN <= M68K_DATA[0]; // FF016F + 10'b1_1000000_?0: CD_nRESET_DRIVE <= M68K_DATA[0]; // FF0181 + 10'b1_1000001_?0: CD_nRESET_Z80 <= M68K_DATA[0]; // FF0183 + 10'b1_1010000_?0: CD_BANK_SPR <= M68K_DATA[1:0]; // FF01A1 REG_SPRBANK + 10'b1_1010001_?0: CD_BANK_PCM <= M68K_DATA[0]; // FF01A3 REG_PCMBANK + default:; + endcase + end + else if ((M68K_ADDR[23:20] == 4'hE) & ~M68K_RW) + begin + // Upload zone + // Is this buffered or is the write directy forwarded to memory ? + CD_TR_WR_DATA <= M68K_DATA; + CD_TR_WR_ADDR <= M68K_ADDR[19:1]; + end + end + end + end + + // 1111:JP, 1110:US, 1101: EU + wire [3:0] CD_JUMPERS = {2'b11, CD_REGION}; + + wire [7:0] CD_IRQ_VECTOR = (M68K_ADDR[2:1] == 2'd3) ? 8'd25 : // Timer $64 + (M68K_ADDR[2:1] == 2'd2) & ~CD_IRQ_FLAGS[0] ? 8'd23 : + (M68K_ADDR[2:1] == 2'd2) & ~CD_IRQ_FLAGS[1] ? 8'd22 : // CD comm. $58 + (M68K_ADDR[2:1] == 2'd2) & ~CD_IRQ_FLAGS[2] ? 8'd21 : // CD decoder $54 + (M68K_ADDR[2:1] == 2'd1) ? 8'd26 : // VBlank $68 + 8'd24; // Spurious interrupt, should not happen + + function [15:0] bit_reverse; + input [15:0] a; + begin + bit_reverse = { a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15] }; + end + endfunction + + assign CD_VBLANK_IRQ_EN = &{REG_FF0004[5:4]}; + assign CD_TIMER_IRQ_EN = &{REG_FF0004[9:8]}; + + assign M68K_DATA = (SYSTEM_CDx & ~nAS & M68K_RW & IACK) ? {8'h00, CD_IRQ_VECTOR} : // Vectored interrupt handler + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h004) ? {4'h0, REG_FF0004} : + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h11C) ? {3'b110, CD_LID, CD_JUMPERS, 8'h00} : // Top mech + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h160) ? {11'b00000000_000, CDCK, CDD_DOUT} : // REG_CDDINPUT + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h166) ? {16'd0} : // Bit 5 needs to be clear for VU meters in CD player to work + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h188) ? bit_reverse(CD_AUDIO_L) : // CDDA L + (READING & {M68K_ADDR[11:1], 1'b0} == 12'h18A) ? bit_reverse(CD_AUDIO_R) : // CDDA R + (LC8951_RD) ? {8'h00, LC8951_DOUT} : + 16'bzzzzzzzz_zzzzzzzz; +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cdda.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cdda.v new file mode 100644 index 0000000000000000000000000000000000000000..f4a4b54e83bc3efd67922efcdc259f5cbea07ec6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/cdda.v @@ -0,0 +1,90 @@ +module cdda +( + input CLK, + input nRESET, + input READ, + input WRITE, + input [15:0] DIN, + output WRITE_READY, + output reg [15:0] AUDIO_L, + output reg [15:0] AUDIO_R + +); + +localparam SECTOR_SIZE = 2352*8/32; +localparam BUFFER_AMOUNT = 2 * SECTOR_SIZE; + +reg OLD_WRITE, OLD_READ, LRCK, WR_REQ; + +reg [15:0] DATA; +reg [12:0] FILLED_COUNT; + +reg [12:0] READ_ADDR, WRITE_ADDR; + +wire EMPTY = ~|FILLED_COUNT; +wire FULL = (FILLED_COUNT == BUFFER_AMOUNT); +wire WRITE_CE = ~OLD_WRITE & WRITE; +wire READ_CE = ~OLD_READ & READ; +wire READ_REQ = READ_CE & ~EMPTY; + +assign WRITE_READY = (FILLED_COUNT <= (BUFFER_AMOUNT - SECTOR_SIZE)); // Ready to receive sector + +always @(posedge CLK) begin + if (~nRESET) begin + OLD_WRITE <= 0; + OLD_READ <= 0; + LRCK <= 0; + READ_ADDR <= 0; + WRITE_ADDR <= 0; + FILLED_COUNT <= 0; + end else begin + OLD_WRITE <= WRITE; + OLD_READ <= READ; + + WR_REQ <= 0; + if (WRITE_CE) begin + LRCK <= ~LRCK; + if (~LRCK) begin + DATA <= DIN; + end else if(~FULL) begin + WR_REQ <= 1; + end + end + + if (WR_REQ) begin + if (WRITE_ADDR == BUFFER_AMOUNT-1) begin + WRITE_ADDR <= 0; + end else begin + WRITE_ADDR <= WRITE_ADDR + 1'b1; + end + end + + if (READ_REQ) begin + if (READ_ADDR == BUFFER_AMOUNT-1) begin + READ_ADDR <= 0; + end else begin + READ_ADDR <= READ_ADDR + 1'b1; + end + AUDIO_L <= BUFFER_Q[15:0]; + AUDIO_R <= BUFFER_Q[31:16]; + end + + if (READ_CE & EMPTY) begin + AUDIO_L <= 0; + AUDIO_R <= 0; + end + + FILLED_COUNT <= FILLED_COUNT + WR_REQ - READ_REQ; + end +end + +reg [31:0] BUFFER[BUFFER_AMOUNT]; +reg [31:0] BUFFER_Q; +always @(posedge CLK) begin + BUFFER_Q <= BUFFER[READ_ADDR]; + if (WR_REQ) begin + BUFFER[WRITE_ADDR] <= { DIN, DATA }; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/drive.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/drive.v new file mode 100644 index 0000000000000000000000000000000000000000..d9c4600840578459115dba1ba172619723c21a06 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/drive.v @@ -0,0 +1,260 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// This module handles the CDD 4-bit communication bus, TOC readback and keeps +// track of the current MSF +// The protocol is very similar (if not identical) to the one used by the Mega CD drive + +module cd_drive( + input nRESET, // System reset OR drive reset + input HOCK, + output reg CDCK, + input [3:0] CDD_DIN, + output reg [3:0] CDD_DOUT, + output reg CDD_nIRQ, + + input clk_sys, + input [39:0] STATUS_IN, + input STATUS_LATCH, + output reg [39:0] COMMAND_DATA, + output reg COMMAND_SEND +); + + // Command codes + parameter CMD_NOP=4'd0, CMD_STOP=4'd1, CMD_TOC=4'd2, CMD_PLAY=4'd3, CMD_SEEK=4'd4, CMD_PAUSE=4'd6, CMD_RESUME=4'd7, + CMD_FFW=4'd8, CMD_REW=4'd9, CMD_CLOSE=4'd12, CMD_OPEN=4'd13; + + // TOC sub-commands + parameter TOC_ABSPOS=4'd0, TOC_RELPOS=4'd1, TOC_TRACK=4'd2, TOC_LENGTH=4'd3, TOC_FIRSTLAST=4'd4, TOC_START=4'd5, + TOC_ERROR=4'd6; + + // Status codes + parameter STAT_STOPPED=4'd0, STAT_PLAYING=4'd1, STAT_READTOC=4'd9; + + // Current TOC sub-command implementation: + // 0: Get position + // Unimplemented + // 1: Get position relative + // Unimplemented + // 2: Get track number + // Unimplemented + // 3: Get CD length: sd_req_type = 16'hD100 + // 0: M + // 1: S + // 2: F + // 4: Get first/last: sd_req_type = 16'hD000 + // 0: First track # BCD + // 1: Last track # BCD + // 5: Get track start: sd_req_type = 16'hD2nn + // 0: M + // 1: S + // 2: F + // 3: Type + // 6: Get last error + // Unimplemented + + reg [8:0] CLK_DIV; // SLOW THE FUCK DOWN + reg [11:0] IRQ_TIMER; + reg [3:0] DOUT_COUNTER; // 0~10 + reg [3:0] DIN_COUNTER; // 0~10, 11 is special code for processing + + reg [3:0] STATUS_DATA [10]; + reg STATUS_LATCH_OLD, STATUS_PENDING; + + reg HOCK_PREV; + reg [1:0] COMM_STATE; // 0~2 + reg COMM_RUN; + + always @(posedge clk_sys) + begin + if (!nRESET) + begin + CLK_DIV <= 9'd0; + IRQ_TIMER <= 12'd0; + DOUT_COUNTER <= 4'd0; + DIN_COUNTER <= 4'd0; + HOCK_PREV <= 0; + CDCK <= 1; + COMM_STATE <= 2'd0; + COMM_RUN <= 0; + CDD_nIRQ <= 1; + STATUS_DATA[0] <= STAT_STOPPED; + STATUS_DATA[1] <= 4'd0; + STATUS_DATA[2] <= 4'd0; + STATUS_DATA[3] <= 4'd0; + STATUS_DATA[4] <= 4'd0; + STATUS_DATA[5] <= 4'd0; + STATUS_DATA[6] <= 4'd0; + STATUS_DATA[7] <= 4'd0; + STATUS_DATA[8] <= 4'd0; + STATUS_DATA[9] <= 4'd0; + STATUS_PENDING <= 0; + STATUS_LATCH_OLD <= 0; + COMMAND_SEND <= 0; + end + else + begin + + STATUS_LATCH_OLD <= STATUS_LATCH; + if (~STATUS_LATCH_OLD & STATUS_LATCH) begin + STATUS_PENDING <= 1; + end + + COMMAND_SEND <= 0; + + // This simulates the Sony CDD MCU, so it must be quite slow + // Here it "runs" at clk_sys/192=48M/192=250kHz + + if (CLK_DIV == 9'd192-1) + begin + CLK_DIV <= 9'd0; + + HOCK_PREV <= HOCK; + + // Fire CDD comm. IRQ at 64Hz + // Does it switch to 75Hz when playing ? + if (IRQ_TIMER == 12'd3906-1) + begin + IRQ_TIMER <= 12'd0; + CDD_nIRQ <= 0; + COMM_STATE <= 2'd0; + COMM_RUN <= 0; + end + else + begin + // Retry whatever happens + if (IRQ_TIMER == 12'd1953-1) + CDD_nIRQ <= 1; + + IRQ_TIMER <= IRQ_TIMER + 1'b1; + end + + if (STATUS_PENDING & (DOUT_COUNTER == 4'd10)) begin + STATUS_PENDING <= 0; + STATUS_DATA[0] <= STATUS_IN[ 3: 0]; + STATUS_DATA[1] <= STATUS_IN[ 7: 4]; + STATUS_DATA[2] <= STATUS_IN[11: 8]; + STATUS_DATA[3] <= STATUS_IN[15:12]; + STATUS_DATA[4] <= STATUS_IN[19:16]; + STATUS_DATA[5] <= STATUS_IN[23:20]; + STATUS_DATA[6] <= STATUS_IN[27:24]; + STATUS_DATA[7] <= STATUS_IN[31:28]; + STATUS_DATA[8] <= STATUS_IN[35:32]; + STATUS_DATA[9] <= STATUS_IN[39:36]; + end + + if (~HOCK & ~CDD_nIRQ) begin + CDD_nIRQ <= 1; // Comm. started ok, ack + COMM_RUN <= 1; + DOUT_COUNTER <= 4'd0; + DIN_COUNTER <= 4'd0; + end + + if (COMM_RUN) + begin + if (DOUT_COUNTER != 4'd10) + begin + // CDD to HOST + + if (COMM_STATE == 2'd0) + begin + // Put data on bus + CDD_DOUT <= STATUS_DATA[DOUT_COUNTER]; + CDCK <= 0; + COMM_STATE <= 2'd1; + end + else if (COMM_STATE == 2'd1) + begin + // Wait for HOCK high + if (~HOCK_PREV & HOCK) + begin + CDCK <= 1; + COMM_STATE <= 2'd2; + // Escape from CDD -> HOST mode at last word + if (DOUT_COUNTER == 4'd9) + begin + DOUT_COUNTER <= 4'd10; + COMM_STATE <= 2'd1; + end + end + end + else if (COMM_STATE == 2'd2) + begin + // Wait for HOCK low + if (HOCK_PREV & ~HOCK) + begin + DOUT_COUNTER <= DOUT_COUNTER + 1'b1; + COMM_STATE <= 2'd0; + end + end + + end + else if (DIN_COUNTER < 4'd10) + begin + // HOST to CDD + + if (COMM_STATE == 2'd0) + begin + // Wait for HOCK rising edge + if (~HOCK_PREV & HOCK) + begin + case (DIN_COUNTER) + 4'd0: COMMAND_DATA[ 3: 0] <= CDD_DIN; + 4'd1: COMMAND_DATA[ 7: 4] <= CDD_DIN; + 4'd2: COMMAND_DATA[11: 8] <= CDD_DIN; + 4'd3: COMMAND_DATA[15:12] <= CDD_DIN; + 4'd4: COMMAND_DATA[19:16] <= CDD_DIN; + 4'd5: COMMAND_DATA[23:20] <= CDD_DIN; + 4'd6: COMMAND_DATA[27:24] <= CDD_DIN; + 4'd7: COMMAND_DATA[31:28] <= CDD_DIN; + 4'd8: COMMAND_DATA[35:32] <= CDD_DIN; + 4'd9: COMMAND_DATA[39:36] <= CDD_DIN; + default: ; + endcase + CDCK <= 1; + DIN_COUNTER <= DIN_COUNTER + 1'b1; + COMM_STATE <= 2'd1; + end + end + else if (COMM_STATE == 2'd1) + begin + // Wait for HOCK falling edge + if (HOCK_PREV & ~HOCK) + begin + CDCK <= 0; + COMM_STATE <= 2'd0; + end + end + + end + else if (DIN_COUNTER == 4'd10) + begin + // Comm frame just ended, do this just once + COMMAND_SEND <= 1; + COMM_RUN <= 0; + end + + end + end + else + CLK_DIV <= CLK_DIV + 1'b1; + end + end +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/hps_ext.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/hps_ext.v new file mode 100644 index 0000000000000000000000000000000000000000..5bbbfe565d9b851edb69ab9fab8865e898a7fc69 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/hps_ext.v @@ -0,0 +1,110 @@ +// +// hps_ext for Mega CD +// +// Copyright (c) 2020 Alexey Melnikov +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +/////////////////////////////////////////////////////////////////////// + +module hps_ext +( + input clk_sys, + inout [35:0] EXT_BUS, + + // CD interface + input [48:0] cd_in, + output reg [48:0] cd_out, + + input cdda_ready, + input cd_data_ready +); + +assign EXT_BUS[15:0] = io_dout; +wire [15:0] io_din = EXT_BUS[31:16]; +assign EXT_BUS[32] = dout_en; +wire io_strobe = EXT_BUS[33]; +wire io_enable = EXT_BUS[34]; + +localparam EXT_CMD_MIN = CD_GET; +localparam EXT_CMD_MAX = CD_SET; + +localparam CD_GET = 'h34; +localparam CD_SET = 'h35; + +reg [15:0] io_dout; +reg dout_en = 0; +reg [9:0] byte_cnt; + +always@(posedge clk_sys) begin + reg [15:0] cmd; + reg [7:0] cd_req = 0; + reg old_cd = 0; + reg [1:0] get_cmd; + reg send_data_type; + + old_cd <= cd_in[48]; + if(old_cd ^ cd_in[48]) cd_req <= cd_req + 1'd1; + + if(~io_enable) begin + dout_en <= 0; + io_dout <= 0; + byte_cnt <= 0; + if(cmd == 'h35) cd_out[48] <= ~cd_out[48]; + end + else if(io_strobe) begin + + io_dout <= 0; + if(~&byte_cnt) byte_cnt <= byte_cnt + 1'd1; + + if(byte_cnt == 0) begin + cmd <= io_din; + dout_en <= (io_din >= EXT_CMD_MIN && io_din <= EXT_CMD_MAX); + if(io_din == CD_GET) io_dout <= cd_req; + end else begin + case(cmd) + CD_GET: + if(!byte_cnt[9:3]) begin + if (byte_cnt[2:0] == 1) begin + get_cmd <= io_din[1:0]; + send_data_type <= io_din[2]; + end else begin + if (get_cmd == 0) begin // Request Command data + case(byte_cnt[2:0]) + 2: io_dout <= cd_in[15:0]; + 3: io_dout <= cd_in[31:16]; + 4: io_dout <= cd_in[47:32]; + endcase + end else if (get_cmd == 1) begin // Request ready for data + if (byte_cnt[2:0] == 2) begin + io_dout <= {15'd0, send_data_type ? cd_data_ready : cdda_ready}; + end + end + end + end + + CD_SET: + if(!byte_cnt[9:3]) begin + case(byte_cnt[2:0]) + 1: cd_out[15:0] <= io_din; + 2: cd_out[31:16] <= io_din; + 3: cd_out[47:32] <= io_din; + endcase + end + endcase + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/lc8951.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/lc8951.v new file mode 100644 index 0000000000000000000000000000000000000000..8d5389dc788f8939fd3a7d785d8e3088b10ef6d6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cd/lc8951.v @@ -0,0 +1,234 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// This module handles the bare essentials to make the Neo CD system ROM happy with +// communicating with the LC8951 CD host chip +// The LC8953-LC8951 handshake signals aren't implemented, no functional need for +// that as it's all automatic while the 68k waits + +// altera message_off 10036 10240 + +module lc8951( + input nRESET, + input clk_sys, + input CLK_68KCLK_EN, + input nWR, nRD, + input RS, // Register select, 0=Access address register, 1=Access pointed register + input [7:0] DIN, + output reg [7:0] DOUT, + + input [31:0] HEADER_DIN, + + input SECTOR_READY, + input DMA_RUNNING, + + output reg CDC_nIRQ // Triggers when SECTOR_READY or DMA_RUNNING rises and IRQ enabled +); + + reg [3:0] AR; // Address Register + reg [7:0] REGS_WRITE [16]; + + reg [11:0] DBC; // Byte counter for transfer + reg [15:0] DAC; // Transfer address - Can ignore ? Should always be set to 0000 + //reg [15:0] PT; // Pointer to start of data block - Can always be 0004 ? + // System ROM subtracts 4 to ignore MSF/Mode header + reg [15:0] WA; // Unused on Neo CD ? + reg nDTBSY, nSTBSY, nDTEN, nSTEN, nVALST; + reg [7:0] HEAD [4]; + + // Bunch of decoder and error detection/correction flags which could be hardcoded + // Can't have CD errors if there's no CD ! + reg CMDI_FLAG, DTEI_FLAG, DECI_FLAG; + reg CMDIEN, DTEIEN, DECIEN, nCMDBRK, nDTWAI, nSTWAI, DOUTEN, SOUTEN; + reg DTTRG; + reg DECEN, EDCRQ, E01RQ, AUTORQ, ERAMRQ, WRRQ, QRQ, PRQ; + reg SYIEN, SYDEN, DSCREN, COWREN, MODRQ, FORMRQ, SHDREN; + + reg nWR_PREV, nRD_PREV; + reg SECTOR_READY_PREV, DMA_RUNNING_PREV, HEADER_WR_PREV; + + reg [15:0] INT_CYCLE_CNT; + + // 12 x 1800. LC8950 manual says that LC8951 /INT goes low for 1.8ms + localparam INT_CYCLES = 16'd21600; + + always @(posedge clk_sys) + begin + if (!nRESET) + begin + AR <= 4'd0; + nWR_PREV <= 1; + nRD_PREV <= 1; + + CDC_nIRQ <= 1; + + DBC <= 12'h000; + DAC <= 16'h0000; + //PT <= 16'h0000; + WA <= 16'h0000; + + CMDI_FLAG <= 0; + DTEI_FLAG <= 0; + DECI_FLAG <= 0; + nDTBSY <= 1; + nSTBSY <= 1; + nDTEN <= 1; + nSTEN <= 1; + + HEAD[0] <= 8'h00; + HEAD[1] <= 8'h00; + HEAD[2] <= 8'h00; + HEAD[3] <= 8'h00; + + nVALST <= 1; + + {CMDIEN, DTEIEN, DECIEN, nCMDBRK, nDTWAI, nSTWAI, DOUTEN, SOUTEN} <= 8'b00000000; + DTTRG <= 0; + {DECEN, EDCRQ, E01RQ, AUTORQ, ERAMRQ, WRRQ, QRQ, PRQ} <= 8'b00000000; + {SYIEN, SYDEN, DSCREN, COWREN, MODRQ, FORMRQ, SHDREN} <= 7'b0000000; + + SECTOR_READY_PREV <= 0; + DMA_RUNNING_PREV <= 0; + HEADER_WR_PREV <= 0; + + INT_CYCLE_CNT <= 0; + end + else + if (CLK_68KCLK_EN) begin + + SECTOR_READY_PREV <= SECTOR_READY; + DMA_RUNNING_PREV <= DMA_RUNNING; + + // Rising edge of SECTOR_READY: Set decoder IRQ flag + if (~SECTOR_READY_PREV & SECTOR_READY) begin + if (DECEN) begin + DECI_FLAG <= 1; + nVALST <= 0; + INT_CYCLE_CNT <= 0; + HEAD[0] <= HEADER_DIN[ 7: 0]; + HEAD[1] <= HEADER_DIN[15: 8]; + HEAD[2] <= HEADER_DIN[23:16]; + HEAD[3] <= HEADER_DIN[31:24]; + end + end else if (~nVALST) begin // Use nVALST because DECI can be reset by reading STAT3. + if (INT_CYCLE_CNT < INT_CYCLES) begin + INT_CYCLE_CNT <= INT_CYCLE_CNT + 1'b1; + end else begin // Decoder INT timeout + DECI_FLAG <= 0; + nVALST <= 1; + end + end + + // Falling edge of DMA_RUNNING: Set transfer end IRQ flag + if (DMA_RUNNING_PREV & ~DMA_RUNNING) begin + //DTEI_FLAG <= 1; + nDTBSY <= 1; + end + + CDC_nIRQ <= ~|{(CMDI_FLAG & CMDIEN), (DTEI_FLAG & DTEIEN), (DECI_FLAG & DECIEN)}; + + nWR_PREV <= nWR; + nRD_PREV <= nRD; + + if (nWR_PREV & ~nWR) + begin + // Write + if (~RS) + AR <= DIN[3:0]; + else + begin + case(AR) + 4'd0:; // COMIN - Is the command system used at all ? + 4'd1: {CMDIEN, DTEIEN, DECIEN, nCMDBRK, nDTWAI, nSTWAI, DOUTEN, SOUTEN} <= DIN; // IFCTRL + + 4'd2: DBC[7:0] <= DIN; // DBCL - Data transfer byte counter + 4'd3: DBC[11:8] <= DIN[3:0]; // DBCH + + 4'd4: DAC[7:0] <= DIN; // DACL + 4'd5: DAC[15:8] <= DIN; // DACH + 4'd6: begin + DTTRG <= 1; + if (DOUTEN) begin + nDTBSY <= 0; + end + end + 4'd7: DTEI_FLAG <= 0; // DTACK - Clears the transfer end IRQ flag + + 4'd8: WA[7:0] <= DIN; // WAL + 4'd9: WA[15:8] <= DIN; // WAH + + 4'd10: {DECEN, EDCRQ, E01RQ, AUTORQ, ERAMRQ, WRRQ, QRQ, PRQ} <= DIN; // CTRL0 + 4'd11: {SYIEN, SYDEN, DSCREN, COWREN, MODRQ, FORMRQ, SHDREN} <= {DIN[7:2], DIN[0]}; // CTRL1 + + 4'd12:; //PT[7:0] <= DIN; // PTL + 4'd13:; //PT[15:8] <= DIN; // PTH + 4'd14:; + 4'd15:; // RESET - Unused ? + endcase + + // Auto-inc if AR is nonzero + if (|{AR}) + AR <= AR + 1'b1; + end + end + else if (nRD_PREV & ~nRD) + begin + // Read + if (~RS) + DOUT <= {4'b0000, AR}; + else + begin + case(AR) + 4'd0: DOUT <= 8'b00000000; // SBOUT - Is the command system used at all ? + 4'd1: DOUT <= {~CMDI_FLAG, ~DTEI_FLAG, ~DECI_FLAG, 1'b1, nDTBSY, nSTBSY, nDTEN, nSTEN}; // IFSTAT + + 4'd2: DOUT <= DBC[7:0]; // DBCL - Data transfer byte counter + 4'd3: DOUT <= {{4{DTEI_FLAG}}, DBC[11:8]}; // DBCH + + 4'd4: DOUT <= HEAD[0]; + 4'd5: DOUT <= HEAD[1]; + 4'd6: DOUT <= HEAD[2]; + 4'd7: DOUT <= HEAD[3]; // CD-ROM mode, always 1 + + 4'd8: DOUT <= 8'h04; //PT[7:0]; // PTL + 4'd9: DOUT <= 8'h00; //PT[15:8]; // PTH + + 4'd10: DOUT <= WA[7:0]; // WAL - Datasheet says these are undefined after reset + 4'd11: DOUT <= WA[15:8]; // WAH + + 4'd12: DOUT <= 8'b10000000; // STAT0 - CRC OK + 4'd13: DOUT <= 8'b00000000; // STAT1 + 4'd14: DOUT <= 8'b00000000; // STAT2 - MODE, FORM (Mode 1) + 4'd15: + begin + DOUT <= {nVALST, 7'b0000000}; // STAT3 - Reading clears the decoder IRQ + DECI_FLAG <= 0; + end + endcase + + // Auto-inc if AR is nonzero + if (|{AR}) + AR <= AR + 1'b1; + end + end + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/C43.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/C43.v new file mode 100644 index 0000000000000000000000000000000000000000..4685a9b8ed018e6a40b9ba38580f555258a3dd9f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/C43.v @@ -0,0 +1,46 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module C43( + input CK, + input [3:0] D, + input nL, EN, CI, nCL, + output reg [3:0] Q = 4'd0, + output CO +); + + wire CL = ~nCL; + + always @(posedge CK, posedge CL) + begin + if (CL) + begin + Q <= 4'd0; // Clear + end + else + begin + if (!nL) + Q <= D; // Load + else if (EN & CI) + Q <= Q + 1'b1; // Count + else + Q <= Q; + end + end + + assign CO = &{Q[3:0], CI}; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/bd3.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/bd3.v new file mode 100644 index 0000000000000000000000000000000000000000..568487d173935895bc01d04cfb43f2309f5ec795 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/bd3.v @@ -0,0 +1,24 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module BD3( + input INPT, + output OUTPT +); + + assign #5 OUTPT = INPT; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fdm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fdm.v new file mode 100644 index 0000000000000000000000000000000000000000..a2a5ac0085934ddb433874c9191b38ed76d53e6b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fdm.v @@ -0,0 +1,29 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module FDM( + input CK, + input D, + output reg Q, + output nQ +); + + always @(posedge CK) + Q <= #2 D; + + assign nQ = ~Q; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds.v new file mode 100644 index 0000000000000000000000000000000000000000..42b0a42ecd110a614bce160a8890b094ad06711a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds.v @@ -0,0 +1,26 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module FDSCell( + input CK, + input [3:0] D, + output reg [3:0] Q = 4'd0 +); + + always @(posedge CK) + Q <= #1 D; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds16bit.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds16bit.v new file mode 100644 index 0000000000000000000000000000000000000000..4fb9e4b98ba1e7cc4dbce6215c8aa185d2dbec51 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/fds16bit.v @@ -0,0 +1,28 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module FDS16bit( + input CK, + input [15:0] D, + output [15:0] Q +); + + FDSCell CellA(CK, D[3:0], Q[3:0]); + FDSCell CellB(CK, D[7:4], Q[7:4]); + FDSCell CellC(CK, D[11:8], Q[11:8]); + FDSCell CellD(CK, D[15:12], Q[15:12]); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/lt4.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/lt4.v new file mode 100644 index 0000000000000000000000000000000000000000..5a5f8cf3c1c6f0f60a3f58e42e49f9e7f67cc0ad --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cells/lt4.v @@ -0,0 +1,30 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// altera message_off 10240 +module LT4( + input nG, + input [3:0] D, + output reg [3:0] P = 4'd0, + output [3:0] N +); + + always @(*) + P = (!nG) ? D : P; // Latch + + assign N = ~P; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sdc b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sdc new file mode 100644 index 0000000000000000000000000000000000000000..b2089ca77d203af002f517b658a4f84b016928fb --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sdc @@ -0,0 +1,9 @@ +set_multicycle_path -start -setup -from [get_keepers *fx68k:*|Ir[*]] -to [get_keepers *fx68k:*|microAddr[*]] 2 +set_multicycle_path -start -hold -from [get_keepers *fx68k:*|Ir[*]] -to [get_keepers *fx68k:*|microAddr[*]] 1 +set_multicycle_path -start -setup -from [get_keepers *fx68k:*|Ir[*]] -to [get_keepers *fx68k:*|nanoAddr[*]] 2 +set_multicycle_path -start -hold -from [get_keepers *fx68k:*|Ir[*]] -to [get_keepers *fx68k:*|nanoAddr[*]] 1 + +set_multicycle_path -start -setup -from {*|nanoLatch[*]} -to {*|excUnit|alu|pswCcr[*]} 2 +set_multicycle_path -start -hold -from {*|nanoLatch[*]} -to {*|excUnit|alu|pswCcr[*]} 1 +set_multicycle_path -start -setup -from {*|excUnit|alu|oper[*]} -to {*|excUnit|alu|pswCcr[*]} 2 +set_multicycle_path -start -hold -from {*|excUnit|alu|oper[*]} -to {*|excUnit|alu|pswCcr[*]} 1 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sv new file mode 100644 index 0000000000000000000000000000000000000000..c51347dfb28f89b80d005e7358d960a4cba4b3ab --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.sv @@ -0,0 +1,2684 @@ +// +// FX68K +// +// M68000 cycle accurate, fully synchronous +// Copyright (c) 2018 by Jorge Cwik +// +// TODO: +// - Everything except bus retry already implemented. + +// altera message_off 10030 +// altera message_off 10230 + +`timescale 1 ns / 1 ns + +// Define this to run a self contained compilation test build +// `define FX68K_TEST + +localparam CF = 0, VF = 1, ZF = 2, NF = 3, XF = 4, SF = 13; + +localparam UADDR_WIDTH = 10; +localparam UROM_WIDTH = 17; +localparam UROM_DEPTH = 1024; + +localparam NADDR_WIDTH = 9; +localparam NANO_WIDTH = 68; +localparam NANO_DEPTH = 336; + +localparam BSER1_NMA = 'h003; +localparam RSTP0_NMA = 'h002; +localparam HALT1_NMA = 'h001; +localparam TRAC1_NMA = 'h1C0; +localparam ITLX1_NMA = 'h1C4; + +localparam TVN_SPURIOUS = 12; +localparam TVN_AUTOVEC = 13; +localparam TVN_INTERRUPT = 15; + +localparam NANO_DOB_DBD = 2'b01; +localparam NANO_DOB_ADB = 2'b10; +localparam NANO_DOB_ALU = 2'b11; + + +// Clocks, phases and resets +typedef struct { + logic clk; + logic extReset; // External sync reset on emulated system + logic pwrUp; // Asserted together with reset on emulated system coldstart + logic enPhi1, enPhi2; // Clock enables. Next cycle is PHI1 or PHI2 +} s_clks; + +// IRD decoded signals +typedef struct { + logic isPcRel; + logic isTas; + logic implicitSp; + logic toCcr; + logic rxIsDt, ryIsDt; + logic rxIsUsp, rxIsMovem, movemPreDecr; + logic isByte; + logic isMovep; + logic [2:0] rx, ry; + logic rxIsAreg, ryIsAreg; + logic [15:0] ftuConst; + logic [5:0] macroTvn; + logic inhibitCcr; +} s_irdecod; + +// Nano code decoded signals +typedef struct { + logic permStart; + logic waitBusFinish; + logic isWrite; + logic busByte; + logic isRmc; + logic noLowByte, noHighByte; + + logic updTpend, clrTpend; + logic tvn2Ftu, const2Ftu; + logic ftu2Dbl, ftu2Abl; + logic abl2Pren, updPren; + logic inl2psw, ftu2Sr, sr2Ftu, ftu2Ccr, pswIToFtu; + logic ird2Ftu, ssw2Ftu; + logic initST; + logic Ir2Ird; + + logic auClkEn, noSpAlign; + logic [2:0] auCntrl; + logic todbin, toIrc; + logic dbl2Atl, abl2Atl, atl2Abl, atl2Dbl; + logic abh2Ath, dbh2Ath; + logic ath2Dbh, ath2Abh; + + logic db2Aob, ab2Aob, au2Aob; + logic aob2Ab, updSsw; + // logic adb2Dob, dbd2Dob, alu2Dob; + logic [1:0] dobCtrl; + + logic abh2reg, abl2reg; + logic reg2abl, reg2abh; + logic dbh2reg, dbl2reg; + logic reg2dbl, reg2dbh; + logic ssp, pchdbh, pcldbl, pclabl, pchabh; + + logic rxh2dbh, rxh2abh; + logic dbl2rxl, dbh2rxh; + logic rxl2db, rxl2ab; + logic abl2rxl, abh2rxh; + logic dbh2ryh, abh2ryh; + logic ryl2db, ryl2ab; + logic ryh2dbh, ryh2abh; + logic dbl2ryl, abl2ryl; + logic rz; + logic rxlDbl; + + logic [2:0] aluColumn; + logic [1:0] aluDctrl; + logic aluActrl; + logic aluInit, aluFinish; + logic abd2Dcr, dcr2Dbd; + logic dbd2Alue, alue2Dbd; + logic dbd2Alub, abd2Alub; + + logic alu2Dbd, alu2Abd; + logic au2Db, au2Ab, au2Pc; + logic dbin2Abd, dbin2Dbd; + logic extDbh, extAbh; + logic ablAbd, ablAbh; + logic dblDbd, dblDbh; + logic abdIsByte; +} s_nanod; + +module fx68k( + input clk, + + // These two signals don't need to be registered. They are not async reset. + input extReset, // External sync reset on emulated system + input pwrUp, // Asserted together with reset on emulated system coldstart + input enPhi1, enPhi2, // Clock enables. Next cycle is PHI1 or PHI2 + + output eRWn, output ASn, output LDSn, output UDSn, + output logic E, output VMAn, + output FC0, output FC1, output FC2, + output BGn, + output oRESETn, output oHALTEDn, + input DTACKn, input VPAn, + input BERRn, + input BRn, BGACKn, + input IPL0n, input IPL1n, input IPL2n, + input [15:0] iEdb, output [15:0] oEdb, + output [23:1] eab + ); + + // wire clock = Clks.clk; + s_clks Clks; + + assign Clks.clk = clk; + assign Clks.extReset = extReset; + assign Clks.pwrUp = pwrUp; + assign Clks.enPhi1 = enPhi1; + assign Clks.enPhi2 = enPhi2; + + wire wClk; + + // Internal sub clocks T1-T4 + enum int unsigned { T0 = 0, T1, T2, T3, T4} tState; + wire enT1 = Clks.enPhi1 & (tState == T4) & ~wClk; + wire enT2 = Clks.enPhi2 & (tState == T1); + wire enT3 = Clks.enPhi1 & (tState == T2); + wire enT4 = Clks.enPhi2 & ((tState == T0) | (tState == T3)); + + // T4 continues ticking during reset and group0 exception. + // We also need it to erase ucode output latched on T4. + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) + tState <= T0; + else begin + case( tState) + T0: if( Clks.enPhi2) tState <= T4; + T1: if( Clks.enPhi2) tState <= T2; + T2: if( Clks.enPhi1) tState <= T3; + T3: if( Clks.enPhi2) tState <= T4; + T4: if( Clks.enPhi1) tState <= wClk ? T0 : T1; + endcase + end + end + + // The following signals are synchronized with 3 couplers, phi1-phi2-phi1. + // Will be valid internally one cycle later if changed at the rasing edge of the clock. + // + // DTACK, BERR + + // DTACK valid at S6 if changed at the rasing edge of S4 to avoid wait states. + // SNC (sncClkEn) is deasserted together (unless DTACK asserted too early). + // + // We synchronize some signals half clock earlier. We compensate later + reg rDtack, rBerr; + reg [2:0] rIpl, iIpl; + reg Vpai, BeI, BRi, BgackI, BeiDelay; + // reg rBR; + wire BeDebounced = ~( BeI | BeiDelay); + + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) begin + rBerr <= 1'b0; + BeI <= 1'b0; + end + else if( Clks.enPhi2) begin + rDtack <= DTACKn; + rBerr <= BERRn; + rIpl <= ~{ IPL2n, IPL1n, IPL0n}; + iIpl <= rIpl; + + // rBR <= BRn; // Needed for cycle accuracy but only if BR is changed on the wrong edge of the clock + end + else if( Clks.enPhi1) begin + Vpai <= VPAn; + BeI <= rBerr; + BeiDelay <= BeI; + + BRi <= BRn; + BgackI <= BGACKn; + // BRi <= rBR; + end + end + + // Instantiate micro and nano rom + logic [NANO_WIDTH-1:0] nanoLatch; + logic [NANO_WIDTH-1:0] nanoOutput; + logic [UROM_WIDTH-1:0] microLatch; + logic [UROM_WIDTH-1:0] microOutput; + + logic [UADDR_WIDTH-1:0] microAddr, nma; + logic [NADDR_WIDTH-1:0] nanoAddr, orgAddr; + wire rstUrom; + + // For the time being, address translation is done for nanorom only. + microToNanoAddr microToNanoAddr( .uAddr( nma), .orgAddr); + + // Output of these modules will be updated at T2 at the latest (depending on clock division) + + nanoRom nanoRom( .clk( Clks.clk), .nanoAddr, .nanoOutput); + uRom uRom( .clk( Clks.clk), .microAddr, .microOutput); + + always_ff @( posedge Clks.clk) begin + // uaddr originally latched on T1, except bits 6 & 7, the conditional bits, on T2 + // Seems we can latch whole address at either T1 or T2 + + // Originally it's invalid on hardware reset, and forced later when coming out of reset + if( Clks.pwrUp) begin + microAddr <= RSTP0_NMA; + nanoAddr <= RSTP0_NMA; + end + else if( enT1) begin + microAddr <= nma; + nanoAddr <= orgAddr; // Register translated uaddr to naddr + end + + if( Clks.extReset) begin + microLatch <= '0; + nanoLatch <= '0; + end + else if( rstUrom) begin + // Originally reset these bits only. Not strictly needed like this. + // Can reset the whole register if it is important. + { microLatch[16], microLatch[15], microLatch[0]} <= '0; + nanoLatch <= '0; + end + else if( enT3) begin + microLatch <= microOutput; + nanoLatch <= nanoOutput; + end + + end + + + // Decoded nanocode signals + s_nanod Nanod; + // IRD decoded control signals + s_irdecod Irdecod; + + // + reg Tpend; + reg intPend; // Interrupt pending + reg pswT, pswS; + reg [ 2:0] pswI; + wire [7:0] ccr; + + wire [15:0] psw = { pswT, 1'b0, pswS, 2'b00, pswI, ccr}; + + reg [15:0] ftu; + reg [15:0] Irc, Ir, Ird; + + wire [15:0] alue; + wire [15:0] Abl; + wire prenEmpty, au05z, dcr4, ze; + + wire [UADDR_WIDTH-1:0] a1, a2, a3; + wire isPriv, isIllegal, isLineA, isLineF; + + + // IR & IRD forwarding + always_ff @( posedge Clks.clk) begin + if( enT1) begin + if( Nanod.Ir2Ird) + Ird <= Ir; + else if(microLatch[0]) // prevented by IR => IRD ! + Ir <= Irc; + end + end + + wire [3:0] tvn; + wire waitBusCycle, busStarting; + wire BusRetry = 1'b0; + wire busAddrErr; + wire bciWrite; // Last bus cycle was write + wire bgBlock, busAvail; + wire addrOe; + + wire busIsByte = Nanod.busByte & (Irdecod.isByte | Irdecod.isMovep); + wire aob0; + + reg iStop; // Internal signal for ending bus cycle + reg A0Err; // Force bus/address error ucode + reg excRst; // Signal reset exception to sequencer + reg BerrA; + reg Spuria, Avia; + wire Iac; + + reg rAddrErr, iBusErr, Err6591; + wire iAddrErr = rAddrErr & addrOe; // To simulate async reset + wire enErrClk; + + // Reset micro/nano latch after T4 of the current ublock. + assign rstUrom = Clks.enPhi1 & enErrClk; + + uaddrDecode uaddrDecode( .opcode( Ir), .a1, .a2, .a3, .isPriv, .isIllegal, .isLineA, .isLineF, .lineBmap()); + + sequencer sequencer( .Clks, .enT3, .microLatch, .Ird, + .A0Err, .excRst, .BerrA, .busAddrErr, .Spuria, .Avia, + .Tpend, .intPend, .isIllegal, .isPriv, .isLineA, .isLineF, + .nma, .a1, .a2, .a3, .tvn, + .psw, .prenEmpty, .au05z, .dcr4, .ze, .alue01( alue[1:0]), .i11( Irc[ 11]) ); + + excUnit excUnit( .Clks, .Nanod, .Irdecod, .enT1, .enT2, .enT3, .enT4, + .Ird, .ftu, .iEdb, .pswS, + .prenEmpty, .au05z, .dcr4, .ze, .AblOut( Abl), .eab, .aob0, .Irc, .oEdb, + .alue, .ccr); + + nDecoder3 nDecoder( .Clks, .Nanod, .Irdecod, .enT2, .enT4, .microLatch, .nanoLatch); + + irdDecode irdDecode( .ird( Ird), .Irdecod); + + busControl busControl( .Clks, .enT1, .enT4, .permStart( Nanod.permStart), .permStop( Nanod.waitBusFinish), .iStop, + .aob0, .isWrite( Nanod.isWrite), .isRmc( Nanod.isRmc), .isByte( busIsByte), .busAvail, + .bciWrite, .addrOe, .bgBlock, .waitBusCycle, .busStarting, .busAddrErr, + .rDtack, .BeDebounced, .Vpai, + .ASn, .LDSn, .UDSn, .eRWn); + + busArbiter busArbiter( .Clks, .BRi, .BgackI, .Halti( 1'b1), .bgBlock, .busAvail, .BGn); + + + // Output reset & halt control + wire [1:0] uFc = microLatch[ 16:15]; + logic oReset, oHalted; + assign oRESETn = !oReset; + assign oHALTEDn = !oHalted; + + // FC without permStart is special, either reset or halt + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) begin + oReset <= 1'b0; + oHalted <= 1'b0; + end + else if( enT1) begin + oReset <= (uFc == 2'b01) & !Nanod.permStart; + oHalted <= (uFc == 2'b10) & !Nanod.permStart; + end + end + + logic [2:0] rFC; + assign { FC2, FC1, FC0} = rFC; // ~rFC; + assign Iac = {rFC == 3'b111}; // & Control output enable !! + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) + rFC <= '0; + else if( enT1 & Nanod.permStart) begin // S0 phase of bus cycle + rFC[2] <= pswS; + // If FC is type 'n' (0) at ucode, access type depends on PC relative mode + // We don't care about RZ in this case. Those uinstructions with RZ don't start a bus cycle. + rFC[1] <= microLatch[ 16] | ( ~microLatch[ 15] & Irdecod.isPcRel); + rFC[0] <= microLatch[ 15] | ( ~microLatch[ 16] & ~Irdecod.isPcRel); + end + end + + + // IPL interface + reg [2:0] inl; // Int level latch + reg updIll; + reg prevNmi; + + wire nmi = (iIpl == 3'b111); + wire iplStable = (iIpl == rIpl); + wire iplComp = iIpl > pswI; + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) begin + intPend <= 1'b0; + prevNmi <= 1'b0; + end + else begin + if( Clks.enPhi2) + prevNmi <= nmi; + + // Originally async RS-Latch on PHI2, followed by a transparent latch on T2 + // Tricky because they might change simultaneously + // Syncronous on PHI2 is equivalent as long as the output is read on T3! + + // Set on stable & NMI edge or compare + // Clear on: NMI Iack or (stable & !NMI & !Compare) + + if( Clks.enPhi2) begin + if( iplStable & ((nmi & ~prevNmi) | iplComp) ) + intPend <= 1'b1; + else if( ((inl == 3'b111) & Iac) | (iplStable & !nmi & !iplComp) ) + intPend <= 1'b0; + end + end + + if( Clks.extReset) begin + inl <= '1; + updIll <= 1'b0; + end + else if( enT4) + updIll <= microLatch[0]; // Update on any IRC->IR + else if( enT1 & updIll) + inl <= iIpl; // Timing is correct. + + // Spurious interrupt, BERR on Interrupt Ack. + // Autovector interrupt. VPA on IACK. + // Timing is tight. Spuria is deasserted just after exception exception is recorded. + if( enT4) begin + Spuria <= ~BeiDelay & Iac; + Avia <= ~Vpai & Iac; + end + + end + + assign enErrClk = iAddrErr | iBusErr; + assign wClk = waitBusCycle | ~BeI | iAddrErr | Err6591; + + // E clock and counter, VMA + reg [3:0] eCntr; + reg rVma; + + assign VMAn = rVma; + + // Internal stop just one cycle before E falling edge + wire xVma = ~rVma & (eCntr == 8); + + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) begin + E <= 1'b0; + eCntr <='0; + rVma <= 1'b1; + end + if( Clks.enPhi2) begin + if( eCntr == 9) + E <= 1'b0; + else if( eCntr == 5) + E <= 1'b1; + + if( eCntr == 9) + eCntr <= '0; + else + eCntr <= eCntr + 1'b1; + end + + if( Clks.enPhi2 & addrOe & ~Vpai & (eCntr == 3)) + rVma <= 1'b0; + else if( Clks.enPhi1 & eCntr == '0) + rVma <= 1'b1; + end + + always_ff @( posedge Clks.clk) begin + + // This timing is critical to stop the clock phases at the exact point on bus/addr error. + // Timing should be such that current ublock completes (up to T3 or T4). + // But T1 for the next ublock shouldn't happen. Next T1 only after resetting ucode and ncode latches. + + if( Clks.extReset) + rAddrErr <= 1'b0; + else if( Clks.enPhi1) begin + if( busAddrErr & addrOe) // Not on T1 ?! + rAddrErr <= 1'b1; + else if( ~addrOe) // Actually async reset! + rAddrErr <= 1'b0; + end + + if( Clks.extReset) + iBusErr <= 1'b0; + else if( Clks.enPhi1) begin + iBusErr <= ( BerrA & ~BeI & ~Iac & !BusRetry); + end + + if( Clks.extReset) + BerrA <= 1'b0; + else if( Clks.enPhi2) begin + if( ~BeI & ~Iac & addrOe) + BerrA <= 1'b1; + // else if( BeI & addrOe) // Bad, async reset since addrOe raising edge + else if( BeI & busStarting) // So replaced with this that raises one cycle earlier + BerrA <= 1'b0; + end + + // Signal reset exception to sequencer. + // Originally cleared on 1st T2 after permstart. Must keep it until TVN latched. + if( Clks.extReset) + excRst <= 1'b1; + else if( enT2 & Nanod.permStart) + excRst <= 1'b0; + + if( Clks.extReset) + A0Err <= 1'b1; // A0 Reset + else if( enT3) // Keep set until new urom words are being latched + A0Err <= 1'b0; + else if( Clks.enPhi1 & enErrClk & (busAddrErr | BerrA)) // Check bus error timing + A0Err <= 1'b1; + + if( Clks.extReset) begin + iStop <= 1'b0; + Err6591 <= 1'b0; + end + else if( Clks.enPhi1) + Err6591 <= enErrClk; + else if( Clks.enPhi2) + iStop <= xVma | (Vpai & (iAddrErr | ~rBerr)); + end + + // PSW + logic irdToCcr_t4; + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) begin + Tpend <= 1'b0; + {pswT, pswS, pswI } <= '0; + irdToCcr_t4 <= '0; + end + + else if( enT4) begin + irdToCcr_t4 <= Irdecod.toCcr; + end + + else if( enT3) begin + + // UNIQUE IF !! + if( Nanod.updTpend) + Tpend <= pswT; + else if( Nanod.clrTpend) + Tpend <= 1'b0; + + // UNIQUE IF !! + if( Nanod.ftu2Sr & !irdToCcr_t4) + {pswT, pswS, pswI } <= { ftu[ 15], ftu[13], ftu[10:8]}; + else begin + if( Nanod.initST) begin + pswS <= 1'b1; + pswT <= 1'b0; + end + if( Nanod.inl2psw) + pswI <= inl; + end + + end + end + + // FTU + reg [4:0] ssw; + reg [3:0] tvnLatch; + logic [15:0] tvnMux; + reg inExcept01; + + // Seems CPU has a buglet here. + // Flagging group 0 exceptions from TVN might not work because some bus cycles happen before TVN is updated. + // But doesn't matter because a group 0 exception inside another one will halt the CPU anyway and won't save the SSW. + + always_ff @( posedge Clks.clk) begin + + // Updated at the start of the exception ucode + if( Nanod.updSsw & enT3) begin + ssw <= { ~bciWrite, inExcept01, rFC}; + end + + // Update TVN on T1 & IR=>IRD + if( enT1 & Nanod.Ir2Ird) begin + tvnLatch <= tvn; + inExcept01 <= (tvn != 1); + end + + if( Clks.pwrUp) + ftu <= '0; + else if( enT3) begin + unique case( 1'b1) + Nanod.tvn2Ftu: ftu <= tvnMux; + + // 0 on unused bits seem to come from ftuConst PLA previously clearing FBUS + Nanod.sr2Ftu: ftu <= {pswT, 1'b0, pswS, 2'b00, pswI, 3'b000, ccr[4:0] }; + + Nanod.ird2Ftu: ftu <= Ird; + Nanod.ssw2Ftu: ftu[4:0] <= ssw; // Undoc. Other bits must be preserved from IRD saved above! + Nanod.pswIToFtu: ftu <= { 12'hFFF, pswI, 1'b0}; // Interrupt level shifted + Nanod.const2Ftu: ftu <= Irdecod.ftuConst; + Nanod.abl2Pren: ftu <= Abl; // From ALU or datareg. Used for SR modify + default: ftu <= ftu; + endcase + end + end + + always_comb begin + if( inExcept01) begin + // Unique IF !!! + if( tvnLatch == TVN_SPURIOUS) + tvnMux = {9'b0, 5'd24, 2'b00}; + else if( tvnLatch == TVN_AUTOVEC) + tvnMux = {9'b0, 2'b11, pswI, 2'b00}; // Set TVN PLA decoder + else if( tvnLatch == TVN_INTERRUPT) + tvnMux = {6'b0, Ird[7:0], 2'b00}; // Interrupt vector was read and transferred to IRD + else + tvnMux = {10'b0, tvnLatch, 2'b00}; + end + else + tvnMux = { 8'h0, Irdecod.macroTvn, 2'b00}; + end + +endmodule + +// Nanorom (plus) decoder for die nanocode +module nDecoder3( input s_clks Clks, input s_irdecod Irdecod, output s_nanod Nanod, + input enT2, enT4, + input [UROM_WIDTH-1:0] microLatch, + input [NANO_WIDTH-1:0] nanoLatch); + +localparam NANO_IR2IRD = 67; +localparam NANO_TOIRC = 66; +localparam NANO_ALU_COL = 63; // ALU operator column order is 63-64-65 ! +localparam NANO_ALU_FI = 61; // ALU finish-init 62-61 +localparam NANO_TODBIN = 60; +localparam NANO_ALUE = 57; // 57-59 shared with DCR control +localparam NANO_DCR = 57; // 57-59 shared with ALUE control +localparam NANO_DOBCTRL_1 = 56; // Input to control and permwrite +localparam NANO_LOWBYTE = 55; // Used by MOVEP +localparam NANO_HIGHBYTE = 54; +localparam NANO_DOBCTRL_0 = 53; // Input to control and permwrite +localparam NANO_ALU_DCTRL = 51; // 52-51 databus input mux control +localparam NANO_ALU_ACTRL = 50; // addrbus input mux control +localparam NANO_DBD2ALUB = 49; +localparam NANO_ABD2ALUB = 48; +localparam NANO_DBIN2DBD = 47; +localparam NANO_DBIN2ABD = 46; +localparam NANO_ALU2ABD = 45; +localparam NANO_ALU2DBD = 44; +localparam NANO_RZ = 43; +localparam NANO_BUSBYTE = 42; // If *both* this set and instruction is byte sized, then bus cycle is byte sized. +localparam NANO_PCLABL = 41; +localparam NANO_RXL_DBL = 40; // Switches RXL/RYL on DBL/ABL buses +localparam NANO_PCLDBL = 39; +localparam NANO_ABDHRECHARGE = 38; +localparam NANO_REG2ABL = 37; // register to ABL +localparam NANO_ABL2REG = 36; // ABL to register +localparam NANO_ABLABD = 35; +localparam NANO_DBLDBD = 34; +localparam NANO_DBL2REG = 33; // DBL to register +localparam NANO_REG2DBL = 32; // register to DBL +localparam NANO_ATLCTRL = 29; // 31-29 +localparam NANO_FTUCONTROL = 25; +localparam NANO_SSP = 24; +localparam NANO_RXH_DBH = 22; // Switches RXH/RYH on DBH/ABH buses +localparam NANO_AUOUT = 20; // 21-20 +localparam NANO_AUCLKEN = 19; +localparam NANO_AUCTRL = 16; // 18-16 +localparam NANO_DBLDBH = 15; +localparam NANO_ABLABH = 14; +localparam NANO_EXT_ABH = 13; +localparam NANO_EXT_DBH = 12; +localparam NANO_ATHCTRL = 9; // 11-9 +localparam NANO_REG2ABH = 8; // register to ABH +localparam NANO_ABH2REG = 7; // ABH to register +localparam NANO_REG2DBH = 6; // register to DBH +localparam NANO_DBH2REG = 5; // DBH to register +localparam NANO_AOBCTRL = 3; // 4-3 +localparam NANO_PCH = 0; // 1-0 PchDbh PchAbh +localparam NANO_NO_SP_ALGN = 0; // Same bits as above when both set + +localparam NANO_FTU_UPDTPEND = 1; // Also loads FTU constant according to IRD ! +localparam NANO_FTU_INIT_ST = 15; // Set S, clear T (but not TPEND) +localparam NANO_FTU_CLRTPEND = 14; +localparam NANO_FTU_TVN = 13; +localparam NANO_FTU_ABL2PREN = 12; // ABL => FTU & ABL => PREN. Both transfers enabled, but only one will be used depending on uroutine. +localparam NANO_FTU_SSW = 11; +localparam NANO_FTU_RSTPREN = 10; +localparam NANO_FTU_IRD = 9; +localparam NANO_FTU_2ABL = 8; +localparam NANO_FTU_RDSR = 7; +localparam NANO_FTU_INL = 6; +localparam NANO_FTU_PSWI = 5; // Read Int Mask into FTU +localparam NANO_FTU_DBL = 4; +localparam NANO_FTU_2SR = 2; +localparam NANO_FTU_CONST = 1; + + reg [3:0] ftuCtrl; + + logic [2:0] athCtrl, atlCtrl; + assign athCtrl = nanoLatch[ NANO_ATHCTRL+2: NANO_ATHCTRL]; + assign atlCtrl = nanoLatch[ NANO_ATLCTRL+2: NANO_ATLCTRL]; + wire [1:0] aobCtrl = nanoLatch[ NANO_AOBCTRL+1:NANO_AOBCTRL]; + wire [1:0] dobCtrl = {nanoLatch[ NANO_DOBCTRL_1], nanoLatch[NANO_DOBCTRL_0]}; + + always_ff @( posedge Clks.clk) begin + if( enT4) begin + // Reverse order! + ftuCtrl <= { nanoLatch[ NANO_FTUCONTROL+0], nanoLatch[ NANO_FTUCONTROL+1], nanoLatch[ NANO_FTUCONTROL+2], nanoLatch[ NANO_FTUCONTROL+3]} ; + + Nanod.auClkEn <= !nanoLatch[ NANO_AUCLKEN]; + Nanod.auCntrl <= nanoLatch[ NANO_AUCTRL+2 : NANO_AUCTRL+0]; + Nanod.noSpAlign <= (nanoLatch[ NANO_NO_SP_ALGN + 1:NANO_NO_SP_ALGN] == 2'b11); + Nanod.extDbh <= nanoLatch[ NANO_EXT_DBH]; + Nanod.extAbh <= nanoLatch[ NANO_EXT_ABH]; + Nanod.todbin <= nanoLatch[ NANO_TODBIN]; + Nanod.toIrc <= nanoLatch[ NANO_TOIRC]; + + // ablAbd is disabled on byte transfers (adbhCharge plus irdIsByte). Not sure the combination makes much sense. + // It happens in a few cases but I don't see anything enabled on abL (or abH) section anyway. + + Nanod.ablAbd <= nanoLatch[ NANO_ABLABD]; + Nanod.ablAbh <= nanoLatch[ NANO_ABLABH]; + Nanod.dblDbd <= nanoLatch[ NANO_DBLDBD]; + Nanod.dblDbh <= nanoLatch[ NANO_DBLDBH]; + + Nanod.dbl2Atl <= (atlCtrl == 3'b010); + Nanod.atl2Dbl <= (atlCtrl == 3'b011); + Nanod.abl2Atl <= (atlCtrl == 3'b100); + Nanod.atl2Abl <= (atlCtrl == 3'b101); + + Nanod.aob2Ab <= (athCtrl == 3'b101); // Used on BSER1 only + + Nanod.abh2Ath <= (athCtrl == 3'b001) | (athCtrl == 3'b101); + Nanod.dbh2Ath <= (athCtrl == 3'b100); + Nanod.ath2Dbh <= (athCtrl == 3'b110); + Nanod.ath2Abh <= (athCtrl == 3'b011); + + Nanod.alu2Dbd <= nanoLatch[ NANO_ALU2DBD]; + Nanod.alu2Abd <= nanoLatch[ NANO_ALU2ABD]; + + Nanod.abd2Dcr <= (nanoLatch[ NANO_DCR+1:NANO_DCR] == 2'b11); + Nanod.dcr2Dbd <= (nanoLatch[ NANO_DCR+2:NANO_DCR+1] == 2'b11); + Nanod.dbd2Alue <= (nanoLatch[ NANO_ALUE+2:NANO_ALUE+1] == 2'b10); + Nanod.alue2Dbd <= (nanoLatch[ NANO_ALUE+1:NANO_ALUE] == 2'b01); + + Nanod.dbd2Alub <= nanoLatch[ NANO_DBD2ALUB]; + Nanod.abd2Alub <= nanoLatch[ NANO_ABD2ALUB]; + + // Originally not latched. We better should because we transfer one cycle later, T3 instead of T1. + Nanod.dobCtrl <= dobCtrl; + // Nanod.adb2Dob <= (dobCtrl == 2'b10); Nanod.dbd2Dob <= (dobCtrl == 2'b01); Nanod.alu2Dob <= (dobCtrl == 2'b11); + + end + end + + // Update SSW at the start of Bus/Addr error ucode + assign Nanod.updSsw = Nanod.aob2Ab; + + assign Nanod.updTpend = (ftuCtrl == NANO_FTU_UPDTPEND); + assign Nanod.clrTpend = (ftuCtrl == NANO_FTU_CLRTPEND); + assign Nanod.tvn2Ftu = (ftuCtrl == NANO_FTU_TVN); + assign Nanod.const2Ftu = (ftuCtrl == NANO_FTU_CONST); + assign Nanod.ftu2Dbl = (ftuCtrl == NANO_FTU_DBL) | ( ftuCtrl == NANO_FTU_INL); + assign Nanod.ftu2Abl = (ftuCtrl == NANO_FTU_2ABL); + assign Nanod.inl2psw = (ftuCtrl == NANO_FTU_INL); + assign Nanod.pswIToFtu = (ftuCtrl == NANO_FTU_PSWI); + assign Nanod.ftu2Sr = (ftuCtrl == NANO_FTU_2SR); + assign Nanod.sr2Ftu = (ftuCtrl == NANO_FTU_RDSR); + assign Nanod.ird2Ftu = (ftuCtrl == NANO_FTU_IRD); // Used on bus/addr error + assign Nanod.ssw2Ftu = (ftuCtrl == NANO_FTU_SSW); + assign Nanod.initST = (ftuCtrl == NANO_FTU_INL) | (ftuCtrl == NANO_FTU_CLRTPEND) | (ftuCtrl == NANO_FTU_INIT_ST); + assign Nanod.abl2Pren = (ftuCtrl == NANO_FTU_ABL2PREN); + assign Nanod.updPren = (ftuCtrl == NANO_FTU_RSTPREN); + + assign Nanod.Ir2Ird = nanoLatch[ NANO_IR2IRD]; + + // ALU control better latched later after combining with IRD decoding + + assign Nanod.aluDctrl = nanoLatch[ NANO_ALU_DCTRL+1 : NANO_ALU_DCTRL]; + assign Nanod.aluActrl = nanoLatch[ NANO_ALU_ACTRL]; + assign Nanod.aluColumn = { nanoLatch[ NANO_ALU_COL], nanoLatch[ NANO_ALU_COL+1], nanoLatch[ NANO_ALU_COL+2]}; + wire [1:0] aluFinInit = nanoLatch[ NANO_ALU_FI+1:NANO_ALU_FI]; + assign Nanod.aluFinish = (aluFinInit == 2'b10); + assign Nanod.aluInit = (aluFinInit == 2'b01); + + // FTU 2 CCR encoded as both ALU Init and ALU Finish set. + // In theory this encoding allows writes to CCR without writing to SR + // But FTU 2 CCR and to SR are both set together at nanorom. + assign Nanod.ftu2Ccr = ( aluFinInit == 2'b11); + + assign Nanod.abdIsByte = nanoLatch[ NANO_ABDHRECHARGE]; + + // Not being latched on T4 creates non unique case warning! + assign Nanod.au2Db = (nanoLatch[ NANO_AUOUT + 1: NANO_AUOUT] == 2'b01); + assign Nanod.au2Ab = (nanoLatch[ NANO_AUOUT + 1: NANO_AUOUT] == 2'b10); + assign Nanod.au2Pc = (nanoLatch[ NANO_AUOUT + 1: NANO_AUOUT] == 2'b11); + + assign Nanod.db2Aob = (aobCtrl == 2'b10); + assign Nanod.ab2Aob = (aobCtrl == 2'b01); + assign Nanod.au2Aob = (aobCtrl == 2'b11); + + assign Nanod.dbin2Abd = nanoLatch[ NANO_DBIN2ABD]; + assign Nanod.dbin2Dbd = nanoLatch[ NANO_DBIN2DBD]; + + assign Nanod.permStart = (| aobCtrl); + assign Nanod.isWrite = ( | dobCtrl); + assign Nanod.waitBusFinish = nanoLatch[ NANO_TOIRC] | nanoLatch[ NANO_TODBIN] | Nanod.isWrite; + assign Nanod.busByte = nanoLatch[ NANO_BUSBYTE]; + + assign Nanod.noLowByte = nanoLatch[ NANO_LOWBYTE]; + assign Nanod.noHighByte = nanoLatch[ NANO_HIGHBYTE]; + + // Not registered. Register at T4 after combining + // Might be better to remove all those and combine here instead of at execution unit !! + assign Nanod.abl2reg = nanoLatch[ NANO_ABL2REG]; + assign Nanod.abh2reg = nanoLatch[ NANO_ABH2REG]; + assign Nanod.dbl2reg = nanoLatch[ NANO_DBL2REG]; + assign Nanod.dbh2reg = nanoLatch[ NANO_DBH2REG]; + assign Nanod.reg2dbl = nanoLatch[ NANO_REG2DBL]; + assign Nanod.reg2dbh = nanoLatch[ NANO_REG2DBH]; + assign Nanod.reg2abl = nanoLatch[ NANO_REG2ABL]; + assign Nanod.reg2abh = nanoLatch[ NANO_REG2ABH]; + + assign Nanod.ssp = nanoLatch[ NANO_SSP]; + + assign Nanod.rz = nanoLatch[ NANO_RZ]; + + // Actually DTL can't happen on PC relative mode. See IR decoder. + + wire dtldbd = 1'b0; + wire dthdbh = 1'b0; + wire dtlabd = 1'b0; + wire dthabh = 1'b0; + + wire dblSpecial = Nanod.pcldbl | dtldbd; + wire dbhSpecial = Nanod.pchdbh | dthdbh; + wire ablSpecial = Nanod.pclabl | dtlabd; + wire abhSpecial = Nanod.pchabh | dthabh; + + // + // Combine with IRD decoding + // Careful that IRD is updated only on T1! All output depending on IRD must be latched on T4! + // + + // PC used instead of RY on PC relative instuctions + + assign Nanod.rxlDbl = nanoLatch[ NANO_RXL_DBL]; + wire isPcRel = Irdecod.isPcRel & !Nanod.rz; + wire pcRelDbl = isPcRel & !nanoLatch[ NANO_RXL_DBL]; + wire pcRelDbh = isPcRel & !nanoLatch[ NANO_RXH_DBH]; + wire pcRelAbl = isPcRel & nanoLatch[ NANO_RXL_DBL]; + wire pcRelAbh = isPcRel & nanoLatch[ NANO_RXH_DBH]; + + assign Nanod.pcldbl = nanoLatch[ NANO_PCLDBL] | pcRelDbl; + assign Nanod.pchdbh = (nanoLatch[ NANO_PCH+1:NANO_PCH] == 2'b01) | pcRelDbh; + + assign Nanod.pclabl = nanoLatch[ NANO_PCLABL] | pcRelAbl; + assign Nanod.pchabh = (nanoLatch[ NANO_PCH+1:NANO_PCH] == 2'b10) | pcRelAbh; + + // Might be better not to register these signals to allow latching RX/RY mux earlier! + // But then must latch Irdecod.isPcRel on T3! + + always_ff @( posedge Clks.clk) begin + if( enT4) begin + Nanod.rxl2db <= Nanod.reg2dbl & !dblSpecial & nanoLatch[ NANO_RXL_DBL]; + Nanod.rxl2ab <= Nanod.reg2abl & !ablSpecial & !nanoLatch[ NANO_RXL_DBL]; + + Nanod.dbl2rxl <= Nanod.dbl2reg & !dblSpecial & nanoLatch[ NANO_RXL_DBL]; + Nanod.abl2rxl <= Nanod.abl2reg & !ablSpecial & !nanoLatch[ NANO_RXL_DBL]; + + Nanod.rxh2dbh <= Nanod.reg2dbh & !dbhSpecial & nanoLatch[ NANO_RXH_DBH]; + Nanod.rxh2abh <= Nanod.reg2abh & !abhSpecial & !nanoLatch[ NANO_RXH_DBH]; + + Nanod.dbh2rxh <= Nanod.dbh2reg & !dbhSpecial & nanoLatch[ NANO_RXH_DBH]; + Nanod.abh2rxh <= Nanod.abh2reg & !abhSpecial & !nanoLatch[ NANO_RXH_DBH]; + + Nanod.dbh2ryh <= Nanod.dbh2reg & !dbhSpecial & !nanoLatch[ NANO_RXH_DBH]; + Nanod.abh2ryh <= Nanod.abh2reg & !abhSpecial & nanoLatch[ NANO_RXH_DBH]; + + Nanod.dbl2ryl <= Nanod.dbl2reg & !dblSpecial & !nanoLatch[ NANO_RXL_DBL]; + Nanod.abl2ryl <= Nanod.abl2reg & !ablSpecial & nanoLatch[ NANO_RXL_DBL]; + + Nanod.ryl2db <= Nanod.reg2dbl & !dblSpecial & !nanoLatch[ NANO_RXL_DBL]; + Nanod.ryl2ab <= Nanod.reg2abl & !ablSpecial & nanoLatch[ NANO_RXL_DBL]; + + Nanod.ryh2dbh <= Nanod.reg2dbh & !dbhSpecial & !nanoLatch[ NANO_RXH_DBH]; + Nanod.ryh2abh <= Nanod.reg2abh & !abhSpecial & nanoLatch[ NANO_RXH_DBH]; + end + + // Originally isTas only delayed on T2 (and seems only a late mask rev fix) + // Better latch the combination on T4 + if( enT4) + Nanod.isRmc <= Irdecod.isTas & nanoLatch[ NANO_BUSBYTE]; + end + + +endmodule + +// +// IRD execution decoder. Complements nano code decoder +// +// IRD updated on T1, while ncode still executing. To avoid using the next IRD, +// decoded signals must be registered on T3, or T4 before using them. +// +module irdDecode( input [15:0] ird, + output s_irdecod Irdecod); + + wire [3:0] line = ird[15:12]; + logic [15:0] lineOnehot; + + // This can be registered and pipelined from the IR decoder ! + onehotEncoder4 irdLines( line, lineOnehot); + + wire isRegShift = (lineOnehot['he]) & (ird[7:6] != 2'b11); + wire isDynShift = isRegShift & ird[5]; + + assign Irdecod.isPcRel = (& ird[ 5:3]) & ~isDynShift & !ird[2] & ird[1]; + assign Irdecod.isTas = lineOnehot[4] & (ird[11:6] == 6'b101011); + + assign Irdecod.rx = ird[11:9]; + assign Irdecod.ry = ird[ 2:0]; + + wire isPreDecr = (ird[ 5:3] == 3'b100); + wire eaAreg = (ird[5:3] == 3'b001); + + // rx is A or D + // movem + always_comb begin + unique case( 1'b1) + lineOnehot[1], + lineOnehot[2], + lineOnehot[3]: + // MOVE: RX always Areg except if dest mode is Dn 000 + Irdecod.rxIsAreg = (| ird[8:6]); + + lineOnehot[4]: Irdecod.rxIsAreg = (& ird[8:6]); // not CHK (LEA) + + lineOnehot['h8]: Irdecod.rxIsAreg = eaAreg & ird[8] & ~ird[7]; // SBCD + lineOnehot['hc]: Irdecod.rxIsAreg = eaAreg & ird[8] & ~ird[7]; // ABCD/EXG An,An + + lineOnehot['h9], + lineOnehot['hb], + lineOnehot['hd]: Irdecod.rxIsAreg = + (ird[7] & ird[6]) | // SUBA/CMPA/ADDA + (eaAreg & ird[8] & (ird[7:6] != 2'b11)); // SUBX/CMPM/ADDX + default: + Irdecod.rxIsAreg = Irdecod.implicitSp; + endcase + end + + // RX is movem + always_comb begin + Irdecod.rxIsMovem = lineOnehot[4] & ~ird[8] & ~Irdecod.implicitSp; + end + assign Irdecod.movemPreDecr = Irdecod.rxIsMovem & isPreDecr; + + // RX is DT. + // but SSP explicit or pc explicit has higher priority! + // addq/subq (scc & dbcc also, but don't use rx) + // Immediate including static bit + assign Irdecod.rxIsDt = lineOnehot[5] | (lineOnehot[0] & ~ird[8]); + + // RX is USP + assign Irdecod.rxIsUsp = lineOnehot[4] & (ird[ 11:4] == 8'he6); + + // RY is DT + // rz or PC explicit has higher priority + + wire eaImmOrAbs = (ird[5:3] == 3'b111) & ~ird[1]; + assign Irdecod.ryIsDt = eaImmOrAbs & ~isRegShift; + + // RY is Address register + always_comb begin + logic eaIsAreg; + + // On most cases RY is Areg expect if mode is 000 (DATA REG) or 111 (IMM, ABS,PC REL) + eaIsAreg = (ird[5:3] != 3'b000) & (ird[5:3] != 3'b111); + + unique case( 1'b1) + // MOVE: RY always Areg expect if mode is 000 (DATA REG) or 111 (IMM, ABS,PC REL) + // Most lines, including misc line 4, also. + default: Irdecod.ryIsAreg = eaIsAreg; + + lineOnehot[5]: // DBcc is an exception + Irdecod.ryIsAreg = eaIsAreg & (ird[7:3] != 5'b11001); + + lineOnehot[6], + lineOnehot[7]: Irdecod.ryIsAreg = 1'b0; + + lineOnehot['he]: + Irdecod.ryIsAreg = ~isRegShift; + endcase + end + + // Byte sized instruction + + // Original implementation sets this for some instructions that aren't really byte size + // but doesn't matter because they don't have a byte transfer enabled at nanocode, such as MOVEQ + + wire xIsScc = (ird[7:6] == 2'b11) & (ird[5:3] != 3'b001); + wire xStaticMem = (ird[11:8] == 4'b1000) & (ird[5:4] == 2'b00); // Static bit to mem + always_comb begin + unique case( 1'b1) + lineOnehot[0]: + Irdecod.isByte = + ( ird[8] & (ird[5:4] != 2'b00) ) | // Dynamic bit to mem + ( (ird[11:8] == 4'b1000) & (ird[5:4] != 2'b00) ) | // Static bit to mem + ( (ird[8:7] == 2'b10) & (ird[5:3] == 3'b001) ) | // Movep from mem only! For byte mux + ( (ird[8:6] == 3'b000) & !xStaticMem ); // Immediate byte + + lineOnehot[1]: Irdecod.isByte = 1'b1; // MOVE.B + + + lineOnehot[4]: Irdecod.isByte = (ird[7:6] == 2'b00) | Irdecod.isTas; + lineOnehot[5]: Irdecod.isByte = (ird[7:6] == 2'b00) | xIsScc; + + lineOnehot[8], + lineOnehot[9], + lineOnehot['hb], + lineOnehot['hc], + lineOnehot['hd], + lineOnehot['he]: Irdecod.isByte = (ird[7:6] == 2'b00); + + default: Irdecod.isByte = 1'b0; + endcase + end + + // Need it for special byte size. Bus is byte, but whole register word is modified. + assign Irdecod.isMovep = lineOnehot[0] & ird[8] & eaAreg; + + + // rxIsSP implicit use of RX for actual SP transfer + // + // This logic is simple and will include some instructions that don't actually reference SP. + // But doesn't matter as long as they don't perform any RX transfer. + + always_comb begin + unique case( 1'b1) + lineOnehot[6]: Irdecod.implicitSp = (ird[11:8] == 4'b0001); // BSR + lineOnehot[4]: + // Misc like RTS, JSR, etc + Irdecod.implicitSp = (ird[11:8] == 4'b1110) | (ird[11:6] == 6'b1000_01); + default: Irdecod.implicitSp = 1'b0; + endcase + end + + // Modify CCR (and not SR) + // Probably overkill !! Only needs to distinguish SR vs CCR + // RTR, MOVE to CCR, xxxI to CCR + assign Irdecod.toCcr = ( lineOnehot[4] & ((ird[11:0] == 12'he77) | (ird[11:6] == 6'b010011)) ) | + ( lineOnehot[0] & (ird[8:6] == 3'b000)); + + // FTU constants + // This should not be latched on T3/T4. Latch on T2 or not at all. FTU needs it on next T3. + // Note: Reset instruction gets constant from ALU not from FTU! + logic [15:0] ftuConst; + wire [3:0] zero28 = (ird[11:9] == 0) ? 4'h8 : { 1'b0, ird[11:9]}; // xltate 0,1-7 into 8,1-7 + + always_comb begin + unique case( 1'b1) + lineOnehot[6], // Bcc short + lineOnehot[7]: ftuConst = { { 8{ ird[ 7]}}, ird[ 7:0] }; // MOVEQ + + lineOnehot['h5], // addq/subq/static shift double check this + lineOnehot['he]: ftuConst = { 12'b0, zero28}; + + // MULU/MULS DIVU/DIVS + lineOnehot['h8], + lineOnehot['hc]: ftuConst = 16'h0f; + + lineOnehot[4]: ftuConst = 16'h80; // TAS + + default: ftuConst = '0; + endcase + end + assign Irdecod.ftuConst = ftuConst; + + // + // TRAP Vector # for group 2 exceptions + // + + always_comb begin + if( lineOnehot[4]) begin + case ( ird[6:5]) + 2'b00,2'b01: Irdecod.macroTvn = 6; // CHK + 2'b11: Irdecod.macroTvn = 7; // TRAPV + 2'b10: Irdecod.macroTvn = {2'b10, ird[3:0]}; // TRAP + endcase + end + else + Irdecod.macroTvn = 5; // Division by zero + end + + + wire eaAdir = (ird[ 5:3] == 3'b001); + wire size11 = ird[7] & ird[6]; + + // Opcodes variants that don't affect flags + // ADDA/SUBA ADDQ/SUBQ MOVEA + + assign Irdecod.inhibitCcr = + ( (lineOnehot[9] | lineOnehot['hd]) & size11) | // ADDA/SUBA + ( lineOnehot[5] & eaAdir) | // ADDQ/SUBQ to An (originally checks for line[4] as well !?) + ( (lineOnehot[2] | lineOnehot[3]) & ird[8:6] == 3'b001); // MOVEA + +endmodule + +/* + Execution unit + + Executes register transfers set by the microcode. Originally through a set of bidirectional buses. + Most sources are available at T3, but DBIN only at T4! CCR also might be updated at T4, but it is not connected to these buses. + We mux at T1 and T2, then transfer to the destination at T3. The exception is AOB that need to be updated earlier. + +*/ + +module excUnit( input s_clks Clks, + input enT1, enT2, enT3, enT4, + input s_nanod Nanod, input s_irdecod Irdecod, + input [15:0] Ird, // ALU row (and others) decoder needs it + input pswS, + input [15:0] ftu, + input [15:0] iEdb, + + output logic [7:0] ccr, + output [15:0] alue, + + output prenEmpty, au05z, + output logic dcr4, ze, + output logic aob0, + output [15:0] AblOut, + output logic [15:0] Irc, + output logic [15:0] oEdb, + output logic [23:1] eab); + +localparam REG_USP = 15; +localparam REG_SSP = 16; +localparam REG_DT = 17; + + // Register file + reg [15:0] regs68L[ 18]; + reg [15:0] regs68H[ 18]; + +// synthesis translate off + /* + It is bad practice to initialize simulation registers that the hardware doesn't. + There is risk that simulation would be different than the real hardware. But in this case is the other way around. + Some ROM uses something like sub.l An,An at powerup which clears the register + Simulator power ups the registers with 'X, as they are really undetermined at the real hardware. + But the simulator doesn't realize (it can't) that the same value is substracting from itself, + and that the result should be zero even when it's 'X - 'X. + */ + + initial begin + for( int i = 0; i < 18; i++) begin + regs68L[i] <= '0; + regs68H[i] <= '0; + end + end + + // For simulation display only + wire [31:0] SSP = { regs68H[REG_SSP], regs68L[REG_SSP]}; + +// synthesis translate on + + + wire [15:0] aluOut; + wire [15:0] dbin; + logic [15:0] dcrOutput; + + reg [15:0] PcL, PcH; + + reg [31:0] auReg, aob; + + reg [15:0] Ath, Atl; + + // Bus execution + reg [15:0] Dbl, Dbh; + reg [15:0] Abh, Abl; + reg [15:0] Abd, Dbd; + + assign AblOut = Abl; + assign au05z = (~| auReg[5:0]); + + logic [15:0] dblMux, dbhMux; + logic [15:0] abhMux, ablMux; + logic [15:0] abdMux, dbdMux; + + logic abdIsByte; + + logic Pcl2Dbl, Pch2Dbh; + logic Pcl2Abl, Pch2Abh; + + + // RX RY muxes + // RX and RY actual registers + logic [4:0] actualRx, actualRy; + logic [3:0] movemRx; + logic byteNotSpAlign; // Byte instruction and no sp word align + + // IRD decoded signals must be latched. See comments on decoder + // But nanostore decoding can't be latched before T4. + // + // If we need this earlier we can register IRD decode on T3 and use nano async + + logic [4:0] rxMux, ryMux; + logic [3:0] rxReg, ryReg; + logic rxIsSp, ryIsSp; + logic rxIsAreg, ryIsAreg; + + always_comb begin + + // Unique IF !! + if( Nanod.ssp) begin + rxMux = REG_SSP; + rxIsSp = 1'b1; + rxReg = 1'bX; + end + else if( Irdecod.rxIsUsp) begin + rxMux = REG_USP; + rxIsSp = 1'b1; + rxReg = 1'bX; + end + else if( Irdecod.rxIsDt & !Irdecod.implicitSp) begin + rxMux = REG_DT; + rxIsSp = 1'b0; + rxReg = 1'bX; + end + else begin + if( Irdecod.implicitSp) + rxReg = 15; + else if( Irdecod.rxIsMovem) + rxReg = movemRx; + else + rxReg = { Irdecod.rxIsAreg, Irdecod.rx}; + + if( (& rxReg)) begin + rxMux = pswS ? REG_SSP : 15; + rxIsSp = 1'b1; + end + else begin + rxMux = { 1'b0, rxReg}; + rxIsSp = 1'b0; + end + end + + // RZ has higher priority! + if( Irdecod.ryIsDt & !Nanod.rz) begin + ryMux = REG_DT; + ryIsSp = 1'b0; + ryReg = 'X; + end + else begin + ryReg = Nanod.rz ? Irc[15:12] : {Irdecod.ryIsAreg, Irdecod.ry}; + ryIsSp = (& ryReg); + if( ryIsSp & pswS) // No implicit SP on RY + ryMux = REG_SSP; + else + ryMux = { 1'b0, ryReg}; + end + + end + + always_ff @( posedge Clks.clk) begin + if( enT4) begin + byteNotSpAlign <= Irdecod.isByte & ~(Nanod.rxlDbl ? rxIsSp : ryIsSp); + + actualRx <= rxMux; + actualRy <= ryMux; + + rxIsAreg <= rxIsSp | rxMux[3]; + ryIsAreg <= ryIsSp | ryMux[3]; + end + + if( enT4) + abdIsByte <= Nanod.abdIsByte & Irdecod.isByte; + end + + // Set RX/RY low word to which bus segment is connected. + + wire ryl2Abl = Nanod.ryl2ab & (ryIsAreg | Nanod.ablAbd); + wire ryl2Abd = Nanod.ryl2ab & (~ryIsAreg | Nanod.ablAbd); + wire ryl2Dbl = Nanod.ryl2db & (ryIsAreg | Nanod.dblDbd); + wire ryl2Dbd = Nanod.ryl2db & (~ryIsAreg | Nanod.dblDbd); + + wire rxl2Abl = Nanod.rxl2ab & (rxIsAreg | Nanod.ablAbd); + wire rxl2Abd = Nanod.rxl2ab & (~rxIsAreg | Nanod.ablAbd); + wire rxl2Dbl = Nanod.rxl2db & (rxIsAreg | Nanod.dblDbd); + wire rxl2Dbd = Nanod.rxl2db & (~rxIsAreg | Nanod.dblDbd); + + // Buses. Main mux + + logic abhIdle, ablIdle, abdIdle; + logic dbhIdle, dblIdle, dbdIdle; + + always_comb begin + {abhIdle, ablIdle, abdIdle} = '0; + {dbhIdle, dblIdle, dbdIdle} = '0; + + unique case( 1'b1) + ryl2Dbd: dbdMux = regs68L[ actualRy]; + rxl2Dbd: dbdMux = regs68L[ actualRx]; + Nanod.alue2Dbd: dbdMux = alue; + Nanod.dbin2Dbd: dbdMux = dbin; + Nanod.alu2Dbd: dbdMux = aluOut; + Nanod.dcr2Dbd: dbdMux = dcrOutput; + default: begin dbdMux = 'X; dbdIdle = 1'b1; end + endcase + + unique case( 1'b1) + rxl2Dbl: dblMux = regs68L[ actualRx]; + ryl2Dbl: dblMux = regs68L[ actualRy]; + Nanod.ftu2Dbl: dblMux = ftu; + Nanod.au2Db: dblMux = auReg[15:0]; + Nanod.atl2Dbl: dblMux = Atl; + Pcl2Dbl: dblMux = PcL; + default: begin dblMux = 'X; dblIdle = 1'b1; end + endcase + + unique case( 1'b1) + Nanod.rxh2dbh: dbhMux = regs68H[ actualRx]; + Nanod.ryh2dbh: dbhMux = regs68H[ actualRy]; + Nanod.au2Db: dbhMux = auReg[31:16]; + Nanod.ath2Dbh: dbhMux = Ath; + Pch2Dbh: dbhMux = PcH; + default: begin dbhMux = 'X; dbhIdle = 1'b1; end + endcase + + unique case( 1'b1) + ryl2Abd: abdMux = regs68L[ actualRy]; + rxl2Abd: abdMux = regs68L[ actualRx]; + Nanod.dbin2Abd: abdMux = dbin; + Nanod.alu2Abd: abdMux = aluOut; + default: begin abdMux = 'X; abdIdle = 1'b1; end + endcase + + unique case( 1'b1) + Pcl2Abl: ablMux = PcL; + rxl2Abl: ablMux = regs68L[ actualRx]; + ryl2Abl: ablMux = regs68L[ actualRy]; + Nanod.ftu2Abl: ablMux = ftu; + Nanod.au2Ab: ablMux = auReg[15:0]; + Nanod.aob2Ab: ablMux = aob[15:0]; + Nanod.atl2Abl: ablMux = Atl; + default: begin ablMux = 'X; ablIdle = 1'b1; end + endcase + + unique case( 1'b1) + Pch2Abh: abhMux = PcH; + Nanod.rxh2abh: abhMux = regs68H[ actualRx]; + Nanod.ryh2abh: abhMux = regs68H[ actualRy]; + Nanod.au2Ab: abhMux = auReg[31:16]; + Nanod.aob2Ab: abhMux = aob[31:16]; + Nanod.ath2Abh: abhMux = Ath; + default: begin abhMux = 'X; abhIdle = 1'b1; end + endcase + + end + + // Source starts driving the bus on T1. Bus holds data until end of T3. Destination latches at T3. + + // These registers store the first level mux, without bus interconnections. + // Even when this uses almost to 100 registers, it saves a lot of comb muxing and it is much faster. + reg [15:0] preAbh, preAbl, preAbd; + reg [15:0] preDbh, preDbl, preDbd; + + always_ff @( posedge Clks.clk) begin + + // Register first level mux at T1 + if( enT1) begin + {preAbh, preAbl, preAbd} <= { abhMux, ablMux, abdMux}; + {preDbh, preDbl, preDbd} <= { dbhMux, dblMux, dbdMux}; + end + + // Process bus interconnection at T2. Many combinations only used on DIV + // We use a simple method. If a specific bus segment is not driven we know that it should get data from a neighbour segment. + // In some cases this is not true and the segment is really idle without any destination. But then it doesn't matter. + + if( enT2) begin + if( Nanod.extAbh) + Abh <= { 16{ ablIdle ? preAbd[ 15] : preAbl[ 15] }}; + else if( abhIdle) + Abh <= ablIdle ? preAbd : preAbl; + else + Abh <= preAbh; + + if( ~ablIdle) + Abl <= preAbl; + else + Abl <= Nanod.ablAbh ? preAbh : preAbd; + + Abd <= ~abdIdle ? preAbd : ablIdle ? preAbh : preAbl; + + if( Nanod.extDbh) + Dbh <= { 16{ dblIdle ? preDbd[ 15] : preDbl[ 15] }}; + else if( dbhIdle) + Dbh <= dblIdle ? preDbd : preDbl; + else + Dbh <= preDbh; + + if( ~dblIdle) + Dbl <= preDbl; + else + Dbl <= Nanod.dblDbh ? preDbh : preDbd; + + Dbd <= ~dbdIdle ? preDbd: dblIdle ? preDbh : preDbl; + + /* + Dbl <= dblMux; Dbh <= dbhMux; + Abd <= abdMux; Dbd <= dbdMux; + Abh <= abhMux; Abl <= ablMux; */ + end + end + + // AOB + // + // Originally change on T1. We do on T2, only then the output is enabled anyway. + // + // AOB[0] is used for address error. But even when raises on T1, seems not actually used until T2 or possibly T3. + // It is used on T1 when deasserted at the BSER exception ucode. Probably deassertion timing is not critical. + // But in that case (at BSER), AOB is loaded from AU, so we can safely transfer on T1. + + // We need to take directly from first level muxes that are updated and T1 + + wire au2Aob = Nanod.au2Aob | (Nanod.au2Db & Nanod.db2Aob); + + always_ff @( posedge Clks.clk) begin + // UNIQUE IF ! + + if( enT1 & au2Aob) // From AU we do can on T1 + aob <= auReg; + else if( enT2) begin + if( Nanod.db2Aob) + aob <= { preDbh, ~dblIdle ? preDbl : preDbd}; + else if( Nanod.ab2Aob) + aob <= { preAbh, ~ablIdle ? preAbl : preAbd}; + end + end + + assign eab = aob[23:1]; + assign aob0 = aob[0]; + + // AU + logic [31:0] auInpMux; + + // `ifdef ALW_COMB_BUG + // Old Modelsim bug. Doesn't update ouput always. Need excplicit sensitivity list !? + // always @( Nanod.auCntrl) begin + + always_comb begin + unique case( Nanod.auCntrl) + 3'b000: auInpMux = 0; + 3'b001: auInpMux = byteNotSpAlign | Nanod.noSpAlign ? 1 : 2; // +1/+2 + 3'b010: auInpMux = -4; + 3'b011: auInpMux = { Abh, Abl}; + 3'b100: auInpMux = 2; + 3'b101: auInpMux = 4; + 3'b110: auInpMux = -2; + 3'b111: auInpMux = byteNotSpAlign | Nanod.noSpAlign ? -1 : -2; // -1/-2 + default: auInpMux = 'X; + endcase + end + + // Simulation problem + // Sometimes (like in MULM1) DBH is not set. AU is used in these cases just as a 6 bits counter testing if bits 5-0 are zero. + // But when adding something like 32'hXXXX0000, the simulator (incorrectly) will set *all the 32 bits* of the result as X. + +// synthesis translate_off + `define SIMULBUGX32 1 + wire [16:0] aulow = Dbl + auInpMux[15:0]; + wire [31:0] auResult = {Dbh + auInpMux[31:16] + aulow[16], aulow[15:0]}; +// synthesis translate_on + + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) + auReg <= '0; + else if( enT3 & Nanod.auClkEn) + `ifdef SIMULBUGX32 + auReg <= auResult; + `else + auReg <= { Dbh, Dbl } + auInpMux; + `endif + end + + + // Main A/D registers + + always_ff @( posedge Clks.clk) begin + if( enT3) begin + if( Nanod.dbl2rxl | Nanod.abl2rxl) begin + if( ~rxIsAreg) begin + if( Nanod.dbl2rxl) regs68L[ actualRx] <= Dbd; + else if( abdIsByte) regs68L[ actualRx][7:0] <= Abd[7:0]; + else regs68L[ actualRx] <= Abd; + end + else + regs68L[ actualRx] <= Nanod.dbl2rxl ? Dbl : Abl; + end + + if( Nanod.dbl2ryl | Nanod.abl2ryl) begin + if( ~ryIsAreg) begin + if( Nanod.dbl2ryl) regs68L[ actualRy] <= Dbd; + else if( abdIsByte) regs68L[ actualRy][7:0] <= Abd[7:0]; + else regs68L[ actualRy] <= Abd; + end + else + regs68L[ actualRy] <= Nanod.dbl2ryl ? Dbl : Abl; + end + + // High registers are easier. Both A & D on the same buses, and not byte ops. + if( Nanod.dbh2rxh | Nanod.abh2rxh) + regs68H[ actualRx] <= Nanod.dbh2rxh ? Dbh : Abh; + if( Nanod.dbh2ryh | Nanod.abh2ryh) + regs68H[ actualRy] <= Nanod.dbh2ryh ? Dbh : Abh; + + end + end + + // PC & AT + reg dbl2Pcl, dbh2Pch, abh2Pch, abl2Pcl; + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) begin + { dbl2Pcl, dbh2Pch, abh2Pch, abl2Pcl } <= '0; + + Pcl2Dbl <= 1'b0; + Pch2Dbh <= 1'b0; + Pcl2Abl <= 1'b0; + Pch2Abh <= 1'b0; + end + else if( enT4) begin // Must latch on T4 ! + dbl2Pcl <= Nanod.dbl2reg & Nanod.pcldbl; + dbh2Pch <= Nanod.dbh2reg & Nanod.pchdbh; + abh2Pch <= Nanod.abh2reg & Nanod.pchabh; + abl2Pcl <= Nanod.abl2reg & Nanod.pclabl; + + Pcl2Dbl <= Nanod.reg2dbl & Nanod.pcldbl; + Pch2Dbh <= Nanod.reg2dbh & Nanod.pchdbh; + Pcl2Abl <= Nanod.reg2abl & Nanod.pclabl; + Pch2Abh <= Nanod.reg2abh & Nanod.pchabh; + end + + // Unique IF !!! + if( enT1 & Nanod.au2Pc) + PcL <= auReg[15:0]; + else if( enT3) begin + if( dbl2Pcl) + PcL <= Dbl; + else if( abl2Pcl) + PcL <= Abl; + end + + // Unique IF !!! + if( enT1 & Nanod.au2Pc) + PcH <= auReg[31:16]; + else if( enT3) begin + if( dbh2Pch) + PcH <= Dbh; + else if( abh2Pch) + PcH <= Abh; + end + + // Unique IF !!! + if( enT3) begin + if( Nanod.dbl2Atl) + Atl <= Dbl; + else if( Nanod.abl2Atl) + Atl <= Abl; + end + + // Unique IF !!! + if( enT3) begin + if( Nanod.abh2Ath) + Ath <= Abh; + else if( Nanod.dbh2Ath) + Ath <= Dbh; + end + + end + + // Movem reg mask priority encoder + + wire rmIdle; + logic [3:0] prHbit; + logic [15:0] prenLatch; + + // Invert reg order for predecrement mode + assign prenEmpty = (~| prenLatch); + pren rmPren( .mask( prenLatch), .hbit (prHbit)); + + always_ff @( posedge Clks.clk) begin + // Cheating: PREN always loaded from DBIN + // Must be on T1 to branch earlier if reg mask is empty! + if( enT1 & Nanod.abl2Pren) + prenLatch <= dbin; + else if( enT3 & Nanod.updPren) begin + prenLatch [prHbit] <= 1'b0; + movemRx <= Irdecod.movemPreDecr ? ~prHbit : prHbit; + end + end + + // DCR + wire [15:0] dcrCode; + + wire [3:0] dcrInput = abdIsByte ? { 1'b0, Abd[ 2:0]} : Abd[ 3:0]; + onehotEncoder4 dcrDecoder( .bin( dcrInput), .bitMap( dcrCode)); + + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) + dcr4 <= '0; + else if( enT3 & Nanod.abd2Dcr) begin + dcrOutput <= dcrCode; + dcr4 <= Abd[4]; + end + end + + // ALUB + reg [15:0] alub; + + always_ff @( posedge Clks.clk) begin + if( enT3) begin + // UNIQUE IF !! + if( Nanod.dbd2Alub) + alub <= Dbd; + else if( Nanod.abd2Alub) + alub <= Abd; // abdIsByte affects this !!?? + end + end + + wire alueClkEn = enT3 & Nanod.dbd2Alue; + + // DOB/DBIN/IRC + + logic [15:0] dobInput; + wire dobIdle = (~| Nanod.dobCtrl); + + always_comb begin + unique case (Nanod.dobCtrl) + NANO_DOB_ADB: dobInput = Abd; + NANO_DOB_DBD: dobInput = Dbd; + NANO_DOB_ALU: dobInput = aluOut; + default: dobInput = 'X; + endcase + end + + dataIo dataIo( .Clks, .enT1, .enT2, .enT3, .enT4, .Nanod, .Irdecod, + .iEdb, .dobIdle, .dobInput, .aob0, + .Irc, .dbin, .oEdb); + + fx68kAlu alu( + .clk( Clks.clk), .pwrUp( Clks.pwrUp), .enT1, .enT3, .enT4, + .ird( Ird), + .aluColumn( Nanod.aluColumn), .aluAddrCtrl( Nanod.aluActrl), + .init( Nanod.aluInit), .finish( Nanod.aluFinish), .aluIsByte( Irdecod.isByte), + .ftu2Ccr( Nanod.ftu2Ccr), + .alub, .ftu, .alueClkEn, .alue, + .aluDataCtrl( Nanod.aluDctrl), .iDataBus( Dbd), .iAddrBus(Abd), + .ze, .aluOut, .ccr); + +endmodule + +// +// Data bus I/O +// At a separate module because it is a bit complicated and the timing is special. +// Here we do the low/high byte mux and the special case of MOVEP. +// +// Original implementation is rather complex because both the internal and external buses are bidirectional. +// Input is latched async at the EDB register. +// We capture directly from the external data bus to the internal registers (IRC & DBIN) on PHI2, starting the external S7 phase, at a T4 internal period. + +module dataIo( input s_clks Clks, + input enT1, enT2, enT3, enT4, + input s_nanod Nanod, input s_irdecod Irdecod, + input [15:0] iEdb, + input aob0, + + input dobIdle, + input [15:0] dobInput, + + output logic [15:0] Irc, + output logic [15:0] dbin, + output logic [15:0] oEdb + ); + + reg [15:0] dob; + + // DBIN/IRC + + // Timing is different than any other register. We can latch only on the next T4 (bus phase S7). + // We need to register all control signals correctly because the next ublock will already be started. + // Can't latch control on T4 because if there are wait states there might be multiple T4 before we latch. + + reg xToDbin, xToIrc; + reg dbinNoLow, dbinNoHigh; + reg byteMux, isByte_T4; + + always_ff @( posedge Clks.clk) begin + + // Byte mux control. Can't latch at T1. AOB might be not ready yet. + // Must latch IRD decode at T1 (or T4). Then combine and latch only at T3. + + // Can't latch at T3, a new IRD might be loaded already at T1. + // Ok to latch at T4 if combination latched then at T3 + if( enT4) + isByte_T4 <= Irdecod.isByte; // Includes MOVEP from mem, we could OR it here + + if( enT3) begin + dbinNoHigh <= Nanod.noHighByte; + dbinNoLow <= Nanod.noLowByte; + byteMux <= Nanod.busByte & isByte_T4 & ~aob0; + end + + if( enT1) begin + // If on wait states, we continue latching until next T1 + xToDbin <= 1'b0; + xToIrc <= 1'b0; + end + else if( enT3) begin + xToDbin <= Nanod.todbin; + xToIrc <= Nanod.toIrc; + end + + // Capture on T4 of the next ucycle + // If there are wait states, we keep capturing every PHI2 until the next T1 + + if( xToIrc & Clks.enPhi2) + Irc <= iEdb; + if( xToDbin & Clks.enPhi2) begin + // Original connects both halves of EDB. + if( ~dbinNoLow) + dbin[ 7:0] <= byteMux ? iEdb[ 15:8] : iEdb[7:0]; + if( ~dbinNoHigh) + dbin[ 15:8] <= ~byteMux & dbinNoLow ? iEdb[ 7:0] : iEdb[ 15:8]; + end + end + + // DOB + logic byteCycle; + + always_ff @( posedge Clks.clk) begin + // Originaly on T1. Transfer to internal EDB also on T1 (stays enabled upto the next T1). But only on T4 (S3) output enables. + // It is safe to do on T3, then, but control signals if derived from IRD must be registered. + // Originally control signals are not registered. + + // Wait states don't affect DOB operation that is done at the start of the bus cycle. + + if( enT4) + byteCycle <= Nanod.busByte & Irdecod.isByte; // busIsByte but not MOVEP + + // Originally byte low/high interconnect is done at EDB, not at DOB. + if( enT3 & ~dobIdle) begin + dob[7:0] <= Nanod.noLowByte ? dobInput[15:8] : dobInput[ 7:0]; + dob[15:8] <= (byteCycle | Nanod.noHighByte) ? dobInput[ 7:0] : dobInput[15:8]; + end + end + assign oEdb = dob; + +endmodule + + +// Provides ucode routine entries (A1/A3) for each opcode +// Also checks for illegal opcode and priv violation + +// This is one of the slowest part of the processor. +// But no need to optimize or pipeline because the result is not needed until at least 4 cycles. +// IR updated at the least one microinstruction earlier. +// Just need to configure the timing analizer correctly. + +module uaddrDecode( + input [15:0] opcode, + output [UADDR_WIDTH-1:0] a1, a2, a3, + output logic isPriv, isIllegal, isLineA, isLineF, + output [15:0] lineBmap); + + wire [3:0] line = opcode[15:12]; + logic [3:0] eaCol, movEa; + + onehotEncoder4 irLineDecod( line, lineBmap); + + assign isLineA = lineBmap[ 'hA]; + assign isLineF = lineBmap[ 'hF]; + + pla_lined pla_lined( .movEa( movEa), .col( eaCol), + .opcode( opcode), .lineBmap( lineBmap), + .palIll( isIllegal), .plaA1( a1), .plaA2( a2), .plaA3( a3) ); + + // ea decoding + assign eaCol = eaDecode( opcode[ 5:0]); + assign movEa = eaDecode( {opcode[ 8:6], opcode[ 11:9]} ); + + // EA decode + function [3:0] eaDecode; + input [5:0] eaBits; + begin + unique case( eaBits[ 5:3]) + 3'b111: + case( eaBits[ 2:0]) + 3'b000: eaDecode = 7; // Absolute short + 3'b001: eaDecode = 8; // Absolute long + 3'b010: eaDecode = 9; // PC displacement + 3'b011: eaDecode = 10; // PC offset + 3'b100: eaDecode = 11; // Immediate + default: eaDecode = 12; // Invalid + endcase + + default: eaDecode = eaBits[5:3]; // Register based EAs + endcase + end + endfunction + + + /* + Privileged instructions: + + ANDI/EORI/ORI SR + MOVE to SR + MOVE to/from USP + RESET + RTE + STOP + */ + + always_comb begin + unique case( lineBmap) + + // ori/andi/eori SR + 'h01: isPriv = ((opcode & 16'hf5ff) == 16'h007c); + + 'h10: + begin + // No priority !!! + if( (opcode & 16'hffc0) == 16'h46c0) // move to sr + isPriv = 1'b1; + + else if( (opcode & 16'hfff0) == 16'h4e60) // move usp + isPriv = 1'b1; + + else if( opcode == 16'h4e70 || // reset + opcode == 16'h4e73 || // rte + opcode == 16'h4e72) // stop + isPriv = 1'b1; + else + isPriv = 1'b0; + end + + default: isPriv = 1'b0; + endcase + end + + +endmodule + +// bin to one-hot, 4 bits to 16-bit bitmap +module onehotEncoder4( input [3:0] bin, output reg [15:0] bitMap); + always_comb begin + case( bin) + 'b0000: bitMap = 16'h0001; + 'b0001: bitMap = 16'h0002; + 'b0010: bitMap = 16'h0004; + 'b0011: bitMap = 16'h0008; + 'b0100: bitMap = 16'h0010; + 'b0101: bitMap = 16'h0020; + 'b0110: bitMap = 16'h0040; + 'b0111: bitMap = 16'h0080; + 'b1000: bitMap = 16'h0100; + 'b1001: bitMap = 16'h0200; + 'b1010: bitMap = 16'h0400; + 'b1011: bitMap = 16'h0800; + 'b1100: bitMap = 16'h1000; + 'b1101: bitMap = 16'h2000; + 'b1110: bitMap = 16'h4000; + 'b1111: bitMap = 16'h8000; + endcase + end +endmodule + +// priority encoder +// used by MOVEM regmask +// this might benefit from device specific features +// MOVEM doesn't need speed, will read the result 2 CPU cycles after each update. +module pren( mask, hbit); + parameter size = 16; + parameter outbits = 4; + + input [size-1:0] mask; + output reg [outbits-1:0] hbit; + // output reg idle; + + always @( mask) begin + integer i; + hbit = 0; + // idle = 1; + for( i = size-1; i >= 0; i = i - 1) begin + if( mask[ i]) begin + hbit = i; + // idle = 0; + end + end + end + +endmodule + +// Microcode sequencer + +module sequencer( input s_clks Clks, input enT3, + input [UROM_WIDTH-1:0] microLatch, + input A0Err, BerrA, busAddrErr, Spuria, Avia, + input Tpend, intPend, isIllegal, isPriv, excRst, isLineA, isLineF, + input [15:0] psw, + input prenEmpty, au05z, dcr4, ze, i11, + input [1:0] alue01, + input [15:0] Ird, + input [UADDR_WIDTH-1:0] a1, a2, a3, + output logic [3:0] tvn, + output logic [UADDR_WIDTH-1:0] nma); + + logic [UADDR_WIDTH-1:0] uNma; + logic [UADDR_WIDTH-1:0] grp1Nma; + logic [1:0] c0c1; + reg a0Rst; + wire A0Sel; + wire inGrp0Exc; + + // assign nma = Clks.extReset ? RSTP0_NMA : (A0Err ? BSER1_NMA : uNma); + // assign nma = A0Err ? (a0Rst ? RSTP0_NMA : BSER1_NMA) : uNma; + + // word type I: 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00 + // NMA : .. .. 09 08 01 00 05 04 03 02 07 06 .. .. .. .. .. + + wire [UADDR_WIDTH-1:0] dbNma = { microLatch[ 14:13], microLatch[ 6:5], microLatch[ 10:7], microLatch[ 12:11]}; + + // Group 0 exception. + // Separated block from regular NMA. Otherwise simulation might depend on order of assigments. + always_comb begin + if( A0Err) begin + if( a0Rst) // Reset + nma = RSTP0_NMA; + else if( inGrp0Exc) // Double fault + nma = HALT1_NMA; + else // Bus or address error + nma = BSER1_NMA; + end + else + nma = uNma; + end + + always_comb begin + // Format II (conditional) or I (direct branch) + if( microLatch[1]) + uNma = { microLatch[ 14:13], c0c1, microLatch[ 10:7], microLatch[ 12:11]}; + else + case( microLatch[ 3:2]) + 0: uNma = dbNma; // DB + 1: uNma = A0Sel ? grp1Nma : a1; + 2: uNma = a2; + 3: uNma = a3; + endcase + end + + // Format II, conditional, NMA decoding + wire [1:0] enl = { Ird[6], prenEmpty}; // Updated on T3 + + wire [1:0] ms0 = { Ird[8], alue01[0]}; + wire [3:0] m01 = { au05z, Ird[8], alue01}; + wire [1:0] nz1 = { psw[ NF], psw[ ZF]}; + wire [1:0] nv = { psw[ NF], psw[ VF]}; + + logic ccTest; + wire [4:0] cbc = microLatch[ 6:2]; // CBC bits + + always_comb begin + unique case( cbc) + 'h0: c0c1 = {i11, i11}; // W/L offset EA, from IRC + + 'h1: c0c1 = (au05z) ? 2'b01 : 2'b11; // Updated on T3 + 'h11: c0c1 = (au05z) ? 2'b00 : 2'b11; + + 'h02: c0c1 = { 1'b0, ~psw[ CF]}; // C used in DIV + 'h12: c0c1 = { 1'b1, ~psw[ CF]}; + + 'h03: c0c1 = {psw[ ZF], psw[ ZF]}; // Z used in DIVU + + 'h04: // nz1, used in DIVS + case( nz1) + 'b00: c0c1 = 2'b10; + 'b10: c0c1 = 2'b01; + 'b01,'b11: c0c1 = 2'b11; + endcase + + 'h05: c0c1 = {psw[ NF], 1'b1}; // N used in CHK and DIV + 'h15: c0c1 = {1'b1, psw[ NF]}; + + // nz2, used in DIVS (same combination as nz1) + 'h06: c0c1 = { ~nz1[1] & ~nz1[0], 1'b1}; + + 'h07: // ms0 used in MUL + case( ms0) + 'b10, 'b00: c0c1 = 2'b11; + 'b01: c0c1 = 2'b01; + 'b11: c0c1 = 2'b10; + endcase + + 'h08: // m01 used in MUL + case( m01) + 'b0000,'b0001,'b0100,'b0111: c0c1 = 2'b11; + 'b0010,'b0011,'b0101: c0c1 = 2'b01; + 'b0110: c0c1 = 2'b10; + default: c0c1 = 2'b00; + endcase + + // Conditional + 'h09: c0c1 = (ccTest) ? 2'b11 : 2'b01; + 'h19: c0c1 = (ccTest) ? 2'b11 : 2'b10; + + // DCR bit 4 (high or low word) + 'h0c: c0c1 = dcr4 ? 2'b01: 2'b11; + 'h1c: c0c1 = dcr4 ? 2'b10: 2'b11; + + // DBcc done + 'h0a: c0c1 = ze ? 2'b11 : 2'b00; + + // nv, used in CHK + 'h0b: c0c1 = (nv == 2'b00) ? 2'b00 : 2'b11; + + // V, used in trapv + 'h0d: c0c1 = { ~psw[ VF], ~psw[VF]}; + + // enl, combination of pren idle and word/long on IRD + 'h0e,'h1e: + case( enl) + 2'b00: c0c1 = 'b10; + 2'b10: c0c1 = 'b11; + // 'hx1 result 00/01 depending on condition 0e/1e + 2'b01,2'b11: + c0c1 = { 1'b0, microLatch[ 6]}; + endcase + + default: c0c1 = 'X; + endcase + end + + // CCR conditional + always_comb begin + unique case( Ird[ 11:8]) + 'h0: ccTest = 1'b1; // T + 'h1: ccTest = 1'b0; // F + 'h2: ccTest = ~psw[ CF] & ~psw[ ZF]; // HI + 'h3: ccTest = psw[ CF] | psw[ZF]; // LS + 'h4: ccTest = ~psw[ CF]; // CC (HS) + 'h5: ccTest = psw[ CF]; // CS (LO) + 'h6: ccTest = ~psw[ ZF]; // NE + 'h7: ccTest = psw[ ZF]; // EQ + 'h8: ccTest = ~psw[ VF]; // VC + 'h9: ccTest = psw[ VF]; // VS + 'ha: ccTest = ~psw[ NF]; // PL + 'hb: ccTest = psw[ NF]; // MI + 'hc: ccTest = (psw[ NF] & psw[ VF]) | (~psw[ NF] & ~psw[ VF]); // GE + 'hd: ccTest = (psw[ NF] & ~psw[ VF]) | (~psw[ NF] & psw[ VF]); // LT + 'he: ccTest = (psw[ NF] & psw[ VF] & ~psw[ ZF]) | + (~psw[ NF] & ~psw[ VF] & ~psw[ ZF]); // GT + 'hf: ccTest = psw[ ZF] | (psw[ NF] & ~psw[VF]) | (~psw[ NF] & psw[VF]); // LE + endcase + end + + // Exception logic + logic rTrace, rInterrupt; + logic rIllegal, rPriv, rLineA, rLineF; + logic rExcRst, rExcAdrErr, rExcBusErr; + logic rSpurious, rAutovec; + wire grp1LatchEn, grp0LatchEn; + + // Originally control signals latched on T4. Then exception latches updated on T3 + assign grp1LatchEn = microLatch[0] & (microLatch[1] | !microLatch[4]); + assign grp0LatchEn = microLatch[4] & !microLatch[1]; + + assign inGrp0Exc = rExcRst | rExcBusErr | rExcAdrErr; + + always_ff @( posedge Clks.clk) begin + if( grp0LatchEn & enT3) begin + rExcRst <= excRst; + rExcBusErr <= BerrA; + rExcAdrErr <= busAddrErr; + rSpurious <= Spuria; + rAutovec <= Avia; + end + + // Update group 1 exception latches + // Inputs from IR decoder updated on T1 as soon as IR loaded + // Trace pending updated on T3 at the start of the instruction + // Interrupt pending on T2 + if( grp1LatchEn & enT3) begin + rTrace <= Tpend; + rInterrupt <= intPend; + rIllegal <= isIllegal & ~isLineA & ~isLineF; + rLineA <= isLineA; + rLineF <= isLineF; + rPriv <= isPriv & !psw[ SF]; + end + end + + // exception priority + always_comb begin + grp1Nma = TRAC1_NMA; + if( rExcRst) + tvn = '0; // Might need to change that to signal in exception + else if( rExcBusErr | rExcAdrErr) + tvn = { 1'b1, rExcAdrErr}; + + // Seudo group 0 exceptions. Just for updating TVN + else if( rSpurious | rAutovec) + tvn = rSpurious ? TVN_SPURIOUS : TVN_AUTOVEC; + + else if( rTrace) + tvn = 9; + else if( rInterrupt) begin + tvn = TVN_INTERRUPT; + grp1Nma = ITLX1_NMA; + end + else begin + unique case( 1'b1) // Can't happen more than one of these + rIllegal: tvn = 4; + rPriv: tvn = 8; + rLineA: tvn = 10; + rLineF: tvn = 11; + default: tvn = 1; // Signal no group 0/1 exception + endcase + end + end + + assign A0Sel = rIllegal | rLineF | rLineA | rPriv | rTrace | rInterrupt; + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) + a0Rst <= 1'b1; + else if( enT3) + a0Rst <= 1'b0; + end + +endmodule + + +// +// DMA/BUS Arbitration +// + +module busArbiter( input s_clks Clks, + input BRi, BgackI, Halti, bgBlock, + output busAvail, + output logic BGn); + + enum int unsigned { DRESET = 0, DIDLE, D1, D_BR, D_BA, D_BRA, D3, D2} dmaPhase, next; + + always_comb begin + case(dmaPhase) + DRESET: next = DIDLE; + DIDLE: begin + if( bgBlock) + next = DIDLE; + else if( ~BgackI) + next = D_BA; + else if( ~BRi) + next = D1; + else + next = DIDLE; + end + + D_BA: begin // Loop while only BGACK asserted, BG negated here + if( ~BRi & !bgBlock) + next = D3; + else if( ~BgackI & !bgBlock) + next = D_BA; + else + next = DIDLE; + end + + D1: next = D_BR; // Loop while only BR asserted + D_BR: next = ~BRi & BgackI ? D_BR : D_BA; // No direct path to IDLE ! + + D3: next = D_BRA; + D_BRA: begin // Loop while both BR and BGACK asserted + case( {BgackI, BRi} ) + 2'b11: next = DIDLE; // Both deasserted + 2'b10: next = D_BR; // BR asserted only + 2'b01: next = D2; // BGACK asserted only + 2'b00: next = D_BRA; // Stay here while both asserted + endcase + end + + // Might loop here if both deasserted, should normally don't arrive here anyway? + // D2: next = (BgackI & BRi) | bgBlock ? D2: D_BA; + + D2: next = D_BA; + + default: next = DIDLE; // Should not reach here normally + endcase + end + + logic granting; + always_comb begin + unique case( next) + D1, D3, D_BR, D_BRA: granting = 1'b1; + default: granting = 1'b0; + endcase + end + + reg rGranted; + assign busAvail = Halti & BRi & BgackI & ~rGranted; + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) begin + dmaPhase <= DRESET; + rGranted <= 1'b0; + end + else if( Clks.enPhi2) begin + dmaPhase <= next; + // Internal signal changed on PHI2 + rGranted <= granting; + end + + // External Output changed on PHI1 + if( Clks.extReset) + BGn <= 1'b1; + else if( Clks.enPhi1) + BGn <= ~rGranted; + + end + +endmodule + +module busControl( input s_clks Clks, input enT1, input enT4, + input permStart, permStop, iStop, + input aob0, + input isWrite, isByte, isRmc, + input busAvail, + output bgBlock, + output busAddrErr, + output waitBusCycle, + output busStarting, // Asserted during S0 + output logic addrOe, // Asserted from S1 to the end, whole bus cycle except S0 + output bciWrite, // Used for SSW on bus/addr error + + input rDtack, BeDebounced, Vpai, + output ASn, output LDSn, output UDSn, eRWn); + + reg rAS, rLDS, rUDS, rRWn; + assign ASn = rAS; + assign LDSn = rLDS; + assign UDSn = rUDS; + assign eRWn = rRWn; + + //reg dataOe; + + reg bcPend; + reg isWriteReg, bciByte, isRmcReg, wendReg; + assign bciWrite = isWriteReg; + reg addrOeDelay; + reg isByteT4; + + wire canStart, busEnd; + wire bcComplete, bcReset; + + wire isRcmReset = bcComplete & bcReset & isRmcReg; + + assign busAddrErr = aob0 & ~bciByte; + + // Bus retry not really supported. + // It's BERR and HALT and not address error, and not read-modify cycle. + wire busRetry = ~busAddrErr & 1'b0; + + enum int unsigned { SRESET = 0, SIDLE, S0, S2, S4, S6, SRMC_RES} busPhase, next; + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) + busPhase <= SRESET; + else if( Clks.enPhi1) + busPhase <= next; + end + + always_comb begin + case( busPhase) + SRESET: next = SIDLE; + SRMC_RES: next = SIDLE; // Single cycle special state when read phase of RMC reset + S0: next = S2; + S2: next = S4; + S4: next = busEnd ? S6 : S4; + S6: next = isRcmReset ? SRMC_RES : (canStart ? S0 : SIDLE); + SIDLE: next = canStart ? S0 : SIDLE; + default: next = SIDLE; + endcase + end + + // Idle phase of RMC bus cycle. Might be better to just add a new state + wire rmcIdle = (busPhase == SIDLE) & ~ASn & isRmcReg; + + assign canStart = (busAvail | rmcIdle) & (bcPend | permStart) & !busRetry & !bcReset; + + wire busEnding = (next == SIDLE) | (next == S0); + + assign busStarting = (busPhase == S0); + + // term signal (DTACK, BERR, VPA, adress error) + assign busEnd = ~rDtack | iStop; + + // bcComplete asserted on raising edge of S6 (together with SNC). + assign bcComplete = (busPhase == S6); + + // Clear bus info latch on completion (regular or aborted) and no bus retry (and not PHI1). + // bciClear asserted half clock later on PHI2, and bci latches cleared async concurrently + wire bciClear = bcComplete & ~busRetry; + + // Reset on reset or (berr & berrDelay & (not halt or rmc) & not 6800 & in bus cycle) (and not PHI1) + assign bcReset = Clks.extReset | (addrOeDelay & BeDebounced & Vpai); + + // Enable uclock only on S6 (S8 on Bus Error) or not bciPermStop + assign waitBusCycle = wendReg & !bcComplete; + + // Block Bus Grant when starting new bus cycle. But No need if AS already asserted (read phase of RMC) + // Except that when that RMC phase aborted on bus error, it's asserted one cycle later! + assign bgBlock = ((busPhase == S0) & ASn) | (busPhase == SRMC_RES); + + always_ff @( posedge Clks.clk) begin + if( Clks.extReset) begin + addrOe <= 1'b0; + end + else if( Clks.enPhi2 & ( busPhase == S0)) // From S1, whole bus cycle except S0 + addrOe <= 1'b1; + else if( Clks.enPhi1 & (busPhase == SRMC_RES)) + addrOe <= 1'b0; + else if( Clks.enPhi1 & ~isRmcReg & busEnding) + addrOe <= 1'b0; + + if( Clks.enPhi1) + addrOeDelay <= addrOe; + + if( Clks.extReset) begin + rAS <= 1'b1; + rUDS <= 1'b1; + rLDS <= 1'b1; + rRWn <= 1'b1; + //dataOe <= '0; + end + else begin +/* + if( Clks.enPhi2 & isWriteReg & (busPhase == S2)) + dataOe <= 1'b1; + else if( Clks.enPhi1 & (busEnding | (busPhase == SIDLE)) ) + dataOe <= 1'b0; +*/ + if( Clks.enPhi1 & busEnding) + rRWn <= 1'b1; + else if( Clks.enPhi1 & isWriteReg) begin + // Unlike LDS/UDS Asserted even in address error + if( (busPhase == S0) & isWriteReg) + rRWn <= 1'b0; + end + + // AS. Actually follows addrOe half cycle later! + if( Clks.enPhi1 & (busPhase == S0)) + rAS <= 1'b0; + else if( Clks.enPhi2 & (busPhase == SRMC_RES)) // Bus error on read phase of RMC. Deasserted one cycle later + rAS <= 1'b1; + else if( Clks.enPhi2 & bcComplete & ~SRMC_RES) + if( ~isRmcReg) // Keep AS asserted on the IDLE phase of RMC + rAS <= 1'b1; + + if( Clks.enPhi1 & (busPhase == S0)) begin + if( ~isWriteReg & !busAddrErr) begin + rUDS <= ~(~bciByte | ~aob0); + rLDS <= ~(~bciByte | aob0); + end + end + else if( Clks.enPhi1 & isWriteReg & (busPhase == S2) & !busAddrErr) begin + rUDS <= ~(~bciByte | ~aob0); + rLDS <= ~(~bciByte | aob0); + end + else if( Clks.enPhi2 & bcComplete) begin + rUDS <= 1'b1; + rLDS <= 1'b1; + end + + end + + end + + // Bus cycle info latch. Needed because uinstr might change if the bus is busy and we must wait. + // Note that urom advances even on wait states. It waits *after* updating urom and nanorom latches. + // Even without wait states, ublocks of type ir (init reading) will not wait for bus completion. + // Originally latched on (permStart AND T1). + + // Bus cycle info latch: isRead, isByte, read-modify-cycle, and permStart (bus cycle pending). Some previously latched on T4? + // permStop also latched, but unconditionally on T1 + + // Might make more sense to register this outside this module + always_ff @( posedge Clks.clk) begin + if( enT4) begin + isByteT4 <= isByte; + end + end + + // Bus Cycle Info Latch + always_ff @( posedge Clks.clk) begin + if( Clks.pwrUp) begin + bcPend <= 1'b0; + wendReg <= 1'b0; + isWriteReg <= 1'b0; + bciByte <= 1'b0; + isRmcReg <= 1'b0; + end + + else if( Clks.enPhi2 & (bciClear | bcReset)) begin + bcPend <= 1'b0; + wendReg <= 1'b0; + end + else begin + if( enT1 & permStart) begin + isWriteReg <= isWrite; + bciByte <= isByteT4; + isRmcReg <= isRmc & ~isWrite; // We need special case the end of the read phase only. + bcPend <= 1'b1; + end + if( enT1) + wendReg <= permStop; + end + end + +endmodule + +// +// microrom and nanorom instantiation +// +// There is bit of wasting of resources here. An extra registering pipeline happens that is not needed. +// This is just for the purpose of helping inferring block RAM using pure generic code. Inferring RAM is important for performance. +// Might be more efficient to use vendor specific features such as clock enable. +// + +module uRom( input clk, input [UADDR_WIDTH-1:0] microAddr, output logic [UROM_WIDTH-1:0] microOutput); + reg [UROM_WIDTH-1:0] uRam[ UROM_DEPTH]; + initial begin + $readmemb("microrom.mem", uRam); + end + + always_ff @( posedge clk) + microOutput <= uRam[ microAddr]; +endmodule + + +module nanoRom( input clk, input [NADDR_WIDTH-1:0] nanoAddr, output logic [NANO_WIDTH-1:0] nanoOutput); + reg [NANO_WIDTH-1:0] nRam[ NANO_DEPTH]; + initial begin + $readmemb("nanorom.mem", nRam); + end + + always_ff @( posedge clk) + nanoOutput <= nRam[ nanoAddr]; +endmodule + +// Translate uaddr to nanoaddr +module microToNanoAddr( + input [UADDR_WIDTH-1:0] uAddr, + output [NADDR_WIDTH-1:0] orgAddr); + + wire [UADDR_WIDTH-1:2] baseAddr = uAddr[UADDR_WIDTH-1:2]; + logic [NADDR_WIDTH-1:2] orgBase; + assign orgAddr = { orgBase, uAddr[1:0]}; + + always @( baseAddr) + begin + // nano ROM (136 addresses) + case( baseAddr) + +'h00: orgBase = 7'h0 ; +'h01: orgBase = 7'h1 ; +'h02: orgBase = 7'h2 ; +'h03: orgBase = 7'h2 ; +'h08: orgBase = 7'h3 ; +'h09: orgBase = 7'h4 ; +'h0A: orgBase = 7'h5 ; +'h0B: orgBase = 7'h5 ; +'h10: orgBase = 7'h6 ; +'h11: orgBase = 7'h7 ; +'h12: orgBase = 7'h8 ; +'h13: orgBase = 7'h8 ; +'h18: orgBase = 7'h9 ; +'h19: orgBase = 7'hA ; +'h1A: orgBase = 7'hB ; +'h1B: orgBase = 7'hB ; +'h20: orgBase = 7'hC ; +'h21: orgBase = 7'hD ; +'h22: orgBase = 7'hE ; +'h23: orgBase = 7'hD ; +'h28: orgBase = 7'hF ; +'h29: orgBase = 7'h10 ; +'h2A: orgBase = 7'h11 ; +'h2B: orgBase = 7'h10 ; +'h30: orgBase = 7'h12 ; +'h31: orgBase = 7'h13 ; +'h32: orgBase = 7'h14 ; +'h33: orgBase = 7'h14 ; +'h38: orgBase = 7'h15 ; +'h39: orgBase = 7'h16 ; +'h3A: orgBase = 7'h17 ; +'h3B: orgBase = 7'h17 ; +'h40: orgBase = 7'h18 ; +'h41: orgBase = 7'h18 ; +'h42: orgBase = 7'h18 ; +'h43: orgBase = 7'h18 ; +'h44: orgBase = 7'h19 ; +'h45: orgBase = 7'h19 ; +'h46: orgBase = 7'h19 ; +'h47: orgBase = 7'h19 ; +'h48: orgBase = 7'h1A ; +'h49: orgBase = 7'h1A ; +'h4A: orgBase = 7'h1A ; +'h4B: orgBase = 7'h1A ; +'h4C: orgBase = 7'h1B ; +'h4D: orgBase = 7'h1B ; +'h4E: orgBase = 7'h1B ; +'h4F: orgBase = 7'h1B ; +'h54: orgBase = 7'h1C ; +'h55: orgBase = 7'h1D ; +'h56: orgBase = 7'h1E ; +'h57: orgBase = 7'h1F ; +'h5C: orgBase = 7'h20 ; +'h5D: orgBase = 7'h21 ; +'h5E: orgBase = 7'h22 ; +'h5F: orgBase = 7'h23 ; +'h70: orgBase = 7'h24 ; +'h71: orgBase = 7'h24 ; +'h72: orgBase = 7'h24 ; +'h73: orgBase = 7'h24 ; +'h74: orgBase = 7'h24 ; +'h75: orgBase = 7'h24 ; +'h76: orgBase = 7'h24 ; +'h77: orgBase = 7'h24 ; +'h78: orgBase = 7'h25 ; +'h79: orgBase = 7'h25 ; +'h7A: orgBase = 7'h25 ; +'h7B: orgBase = 7'h25 ; +'h7C: orgBase = 7'h25 ; +'h7D: orgBase = 7'h25 ; +'h7E: orgBase = 7'h25 ; +'h7F: orgBase = 7'h25 ; +'h84: orgBase = 7'h26 ; +'h85: orgBase = 7'h27 ; +'h86: orgBase = 7'h28 ; +'h87: orgBase = 7'h29 ; +'h8C: orgBase = 7'h2A ; +'h8D: orgBase = 7'h2B ; +'h8E: orgBase = 7'h2C ; +'h8F: orgBase = 7'h2D ; +'h94: orgBase = 7'h2E ; +'h95: orgBase = 7'h2F ; +'h96: orgBase = 7'h30 ; +'h97: orgBase = 7'h31 ; +'h9C: orgBase = 7'h32 ; +'h9D: orgBase = 7'h33 ; +'h9E: orgBase = 7'h34 ; +'h9F: orgBase = 7'h35 ; +'hA4: orgBase = 7'h36 ; +'hA5: orgBase = 7'h36 ; +'hA6: orgBase = 7'h37 ; +'hA7: orgBase = 7'h37 ; +'hAC: orgBase = 7'h38 ; +'hAD: orgBase = 7'h38 ; +'hAE: orgBase = 7'h39 ; +'hAF: orgBase = 7'h39 ; +'hB4: orgBase = 7'h3A ; +'hB5: orgBase = 7'h3A ; +'hB6: orgBase = 7'h3B ; +'hB7: orgBase = 7'h3B ; +'hBC: orgBase = 7'h3C ; +'hBD: orgBase = 7'h3C ; +'hBE: orgBase = 7'h3D ; +'hBF: orgBase = 7'h3D ; +'hC0: orgBase = 7'h3E ; +'hC1: orgBase = 7'h3F ; +'hC2: orgBase = 7'h40 ; +'hC3: orgBase = 7'h41 ; +'hC8: orgBase = 7'h42 ; +'hC9: orgBase = 7'h43 ; +'hCA: orgBase = 7'h44 ; +'hCB: orgBase = 7'h45 ; +'hD0: orgBase = 7'h46 ; +'hD1: orgBase = 7'h47 ; +'hD2: orgBase = 7'h48 ; +'hD3: orgBase = 7'h49 ; +'hD8: orgBase = 7'h4A ; +'hD9: orgBase = 7'h4B ; +'hDA: orgBase = 7'h4C ; +'hDB: orgBase = 7'h4D ; +'hE0: orgBase = 7'h4E ; +'hE1: orgBase = 7'h4E ; +'hE2: orgBase = 7'h4F ; +'hE3: orgBase = 7'h4F ; +'hE8: orgBase = 7'h50 ; +'hE9: orgBase = 7'h50 ; +'hEA: orgBase = 7'h51 ; +'hEB: orgBase = 7'h51 ; +'hF0: orgBase = 7'h52 ; +'hF1: orgBase = 7'h52 ; +'hF2: orgBase = 7'h52 ; +'hF3: orgBase = 7'h52 ; +'hF8: orgBase = 7'h53 ; +'hF9: orgBase = 7'h53 ; +'hFA: orgBase = 7'h53 ; +'hFB: orgBase = 7'h53 ; + + default: + orgBase = 'X; + endcase + end + +endmodule + +// +// For compilation test only +// + +`ifdef FX68K_TEST +module fx68kTop( input clk32, + input extReset, + // input pwrUp, + + input DTACKn, input VPAn, + input BERRn, + input BRn, BGACKn, + input IPL0n, input IPL1n, input IPL2n, + input [15:0] iEdb, + + output [15:0] oEdb, + output eRWn, output ASn, output LDSn, output UDSn, + output logic E, output VMAn, + output FC0, output FC1, output FC2, + output BGn, + output oRESETn, output oHALTEDn, + output [23:1] eab + ); + + // Clock must be at least twice the desired frequency. A 32 MHz clock means a maximum 16 MHz effective frequency. + // In this example we divide the clock by 4. Resulting on an effective processor running at 8 MHz. + + reg [1:0] clkDivisor = '0; + always @( posedge clk32) begin + clkDivisor <= clkDivisor + 1'b1; + end + + /* + These two signals must be a single cycle pulse. They don't need to be registered. + Same signal can't be asserted twice in a row. Other than that there are no restrictions. + There can be any number of cycles, or none, even variable non constant cycles, between each pulse. + */ + + wire enPhi1 = (clkDivisor == 2'b11); + wire enPhi2 = (clkDivisor == 2'b01); + + + fx68k fx68k( .clk( clk32), + .extReset, .pwrUp( extReset), .enPhi1, .enPhi2, + + .DTACKn, .VPAn, .BERRn, .BRn, .BGACKn, + .IPL0n, .IPL1n, .IPL2n, + .iEdb, + + .oEdb, + .eRWn, .ASn, .LDSn, .UDSn, + .E, .VMAn, + .FC0, .FC1, .FC2, + .BGn, + .oRESETn, .oHALTEDn, .eab); + +endmodule +`endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.txt b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9c3c5a4dced49ff317d05736176fa4bf2632f2d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68k.txt @@ -0,0 +1,87 @@ +FX68K + +68000 cycle accurate core +Copyright (c) 2018 by Jorge Cwik +fx68k@fxatari.com + + +FX68K is a 68K cycle exact compatible core. In theory at least, it should be impossible to distinguish functionally from a real 68K processor. + +On Cyclone families it uses just over 5,100 LEs and about 5KB internal ram, reaching a max clock frequency close to 40MHz. Some optimizations are still possible to implement and increase the performance. + +The core is fully synchronous. Considerable effort was done to avoid any asynchronous logic. + +Written in SystemVerilog. + +The timing of the external bus signals is exactly as the original processor. The only feature that is not implemented yet is bus retry using the external HALT input signal. + +It was designed to replace an actual chip on a real board. This wasn't yet tested however and not all necessary output enable control signals are fully implemented. + + +Copyright + +// +// This source file is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// + + +Developer Notes + + +The core receives a clock that must be at least twice the frequency of the desired nominal speed. The core also receives two signals for masking both phases of the clock (PHI1 and PHI2). These signals are implemented as simple clock enable for all the flip flops used by the core. This way, the original clock frequency can be any multiple and it doesn't even need to be regular or constant. + +These two signals are enPhi1 and enPhi2. They must be a single cycle pulse, and they don't need to be registered. Because they are actually used as clock enable, the output signals change one cycle later. + +enPhi1 should be asserted one cycle before the high phase of the nominal clock, and enPhi2 one cycle before the low phase. + +E.g., during a bus cycle, AS is asserted one cycle after enPhi1 is asserted, and AS is deasserted one cycle after enPhi2 is asserted. This follows the original bus timing that specify AS being asserted on the raising edge of the clock, and deasserted on the falling edge one. + +All signals follow the original polarity and then most are low active. + +extReset is external reset and is synchronous and high active. Hence is doesn't have to be registered. + +pwrUp qualifies external reset as being a cold power up reset. If it is asserted, then extReset must be asserted as well. Most system don't need to distinguish between a cold and a warm reset at the CPU level. Then both signals can be always asserted together. The core does expect pwrUp to be asserted initially because there is no true asynchronous reset. The signal is high active. + + +Timing analysis + +Microcode access is one of the slowest paths on the core. But the microcode output is not needed immediately. Use the following constraints to get a more accurate timing analysis. Note that the full path might need to be modified: + +# Altera/Intel + +set_multicycle_path -start -setup -from [get_keepers fx68k:fx68k|Ir[*]] -to [get_keepers fx68k:fx68k|microAddr[*]] 2 +set_multicycle_path -start -hold -from [get_keepers fx68k:fx68k|Ir[*]] -to [get_keepers fx68k:fx68k|microAddr[*]] 1 +set_multicycle_path -start -setup -from [get_keepers fx68k:fx68k|Ir[*]] -to [get_keepers fx68k:fx68k|nanoAddr[*]] 2 +set_multicycle_path -start -hold -from [get_keepers fx68k:fx68k|Ir[*]] -to [get_keepers fx68k:fx68k|nanoAddr[*]] 1 + +# For Xilinx Vivado + +set_multicycle_path -setup -from [get_pins fx68k/Ir*/C] -to [get_pins fx68k/nanoAddr_reg*/D] 2 +set_multicycle_path -setup -from [get_pins fx68k/Ir*/C] -to [get_pins fx68k/microAddr_reg*/D] 2 +set_multicycle_path -hold -from [get_pins fx68k/Ir*/C] -to [get_pins fx68k/nanoAddr_reg*/D] 1 +set_multicycle_path -hold -from [get_pins fx68k/Ir*/C] -to [get_pins fx68k/microAddr_reg*/D] 1 + + +The update of the CCR flags is also time critical. Some compilers might benefit with the following constraints, but this wasn't fully verified yet: + + +# Altera/Intel +# set_multicycle_path -start -setup -from [fx68k:fx68k|nanoLatch[*]] +# -to [get_keepers fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|pswCcr[*]] 2 +# set_multicycle_path -start -setup -from [fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|oper[*]] +# -to [get_keepers fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|pswCcr[*]] 2 +# set_multicycle_path -start -hold -from [fx68k:fx68k|nanoLatch[*]] +# -to [get_keepers fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|pswCcr[*]] 1 +# set_multicycle_path -start -hold -from [fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|oper[*]] +# -to [get_keepers fx68k:fx68k|excUnit:excUnit|fx68kAlu:alu|pswCcr[*]] 1 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68kAlu.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68kAlu.sv new file mode 100644 index 0000000000000000000000000000000000000000..49b5a19a2280193cc4d04ac0da06f2dfd588e2f3 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/fx68kAlu.sv @@ -0,0 +1,843 @@ +// +// FX 68K +// +// M68K cycle accurate, fully synchronous +// Copyright (c) 2018 by Jorge Cwik +// +// ALU +// + +// altera message_off 10230 +// altera message_off 10763 +// altera message_off 10958 + +`timescale 1 ns / 1 ns + +localparam MASK_NBITS = 5; + +localparam + OP_AND = 1, + OP_SUB = 2, OP_SUBX = 3, OP_ADD = 4, + OP_EXT = 5, OP_SBCD = 6, OP_SUB0 = 7, + OP_OR = 8, OP_EOR = 9, + OP_SUBC = 10, OP_ADDC = 11, OP_ADDX = 12, + OP_ASL = 13, + OP_ASR = 14, + OP_LSL = 15, + OP_LSR = 16, + OP_ROL = 17, + OP_ROR = 18, + OP_ROXL = 19, + OP_ROXR = 20, + OP_SLAA = 21, + OP_ABCD = 22; + +module fx68kAlu ( input clk, pwrUp, enT1, enT3, enT4, + input [15:0] ird, + input [2:0] aluColumn, + input [1:0] aluDataCtrl, + input aluAddrCtrl, alueClkEn, ftu2Ccr, init, finish, aluIsByte, + input [15:0] ftu, + input [15:0] alub, + input [15:0] iDataBus, input [15:0] iAddrBus, + output ze, + output reg [15:0] alue, + output reg [7:0] ccr, + output [15:0] aluOut); + + +`define ALU_ROW_01 16'h0002 +`define ALU_ROW_02 16'h0004 +`define ALU_ROW_03 16'h0008 +`define ALU_ROW_04 16'h0010 +`define ALU_ROW_05 16'h0020 +`define ALU_ROW_06 16'h0040 +`define ALU_ROW_07 16'h0080 +`define ALU_ROW_08 16'h0100 +`define ALU_ROW_09 16'h0200 +`define ALU_ROW_10 16'h0400 +`define ALU_ROW_11 16'h0800 +`define ALU_ROW_12 16'h1000 +`define ALU_ROW_13 16'h2000 +`define ALU_ROW_14 16'h4000 +`define ALU_ROW_15 16'h8000 + + + // Bit positions for flags in CCR + localparam CF = 0, VF = 1, ZF = 2, NF = 3, XF = 4; + + reg [15:0] aluLatch; + reg [4:0] pswCcr; + reg [4:0] ccrCore; + + logic [15:0] result; + logic [4:0] ccrTemp; + reg coreH; // half carry latch + + logic [15:0] subResult; + logic subHcarry; + logic subCout, subOv; + + assign aluOut = aluLatch; + assign ze = ~ccrCore[ ZF]; // Check polarity !!! + + // + // Control + // Signals derived from IRD *must* be registered on either T3 or T4 + // Signals derived from nano rom can be registered on T4. + + reg [15:0] row; + reg isArX; // Don't set Z + reg noCcrEn; + reg isByte; + + reg [4:0] ccrMask; + reg [4:0] oper; + + logic [15:0] aOperand, dOperand; + wire isCorf = ( aluDataCtrl == 2'b10); + + wire [15:0] cRow; + wire cIsArX; + wire cNoCcrEn; + rowDecoder rowDecoder( .ird( ird), .row( cRow), .noCcrEn( cNoCcrEn), .isArX( cIsArX)); + + // Get Operation & CCR Mask from row/col + // Registering them on T4 increase performance. But slowest part seems to be corf ! + wire [4:0] cMask; + wire [4:0] aluOp; + + aluGetOp aluGetOp( .row, .col( aluColumn), .isCorf, .aluOp); + ccrTable ccrTable( .col( aluColumn), .row( row), .finish, .ccrMask( cMask)); + + // Inefficient, uCode could help ! + wire shftIsMul = row[7]; + wire shftIsDiv = row[1]; + + wire [31:0] shftResult; + reg [7:0] bcdLatch; + reg bcdCarry, bcdOverf; + + reg isLong; + reg rIrd8; + logic isShift; + logic shftCin, shftRight, addCin; + + // Register some decoded signals + always_ff @( posedge clk) begin + if( enT3) begin + row <= cRow; + isArX <= cIsArX; + noCcrEn <= cNoCcrEn; + rIrd8 <= ird[8]; + isByte <= aluIsByte; + end + + if( enT4) begin + // Decode if long shift + // MUL and DIV are long (but special !) + isLong <= (ird[7] & ~ird[6]) | shftIsMul | shftIsDiv; + + ccrMask <= cMask; + oper <= aluOp; + end + end + + + always_comb begin + // Dest (addr) operand source + // If aluCsr (depends on column/row) addrbus is shifted !! + aOperand = (aluAddrCtrl ? alub : iAddrBus); + + // Second (data,source) operand mux + case( aluDataCtrl) + 2'b00: dOperand = iDataBus; + 2'b01: dOperand = 'h0000; + 2'b11: dOperand = 'hffff; + // 2'b10: dOperand = bcdResult; + 2'b10: dOperand = 'X; + endcase + end + + // Execution + + // shift operand MSB. Input in ASR/ROL. Carry in right. + // Can't be registered because uses bus operands that aren't available early ! + wire shftMsb = isLong ? alue[15] : (isByte ? aOperand[7] : aOperand[15]); + + aluShifter shifter( .data( { alue, aOperand}), + .swapWords( shftIsMul | shftIsDiv), + .cin( shftCin), .dir( shftRight), .isByte( isByte), .isLong( isLong), + .result( shftResult)); + + wire [7:0] bcdResult; + wire bcdC, bcdV; + aluCorf aluCorf( .binResult( aluLatch[7:0]), .hCarry( coreH), + .bAdd( (oper != OP_SBCD) ), .cin( pswCcr[ XF]), + .bcdResult( bcdResult), .dC( bcdC), .ov( bcdV)); + + // BCD adjust is among the slowest processing on ALU ! + // Precompute and register BCD result on T1 + // We don't need to wait for execution buses because corf is always added to ALU previous result + always_ff @( posedge clk) + if( enT1) begin + bcdLatch <= bcdResult; + bcdCarry <= bcdC; + bcdOverf <= bcdV; + end + + // Adder carry in selector + always_comb + begin + case( oper) + OP_ADD, OP_SUB: addCin = 1'b0; + OP_SUB0: addCin = 1'b1; // NOT = 0 - op - 1 + OP_ADDC,OP_SUBC: addCin = ccrCore[ CF]; + OP_ADDX,OP_SUBX: addCin = pswCcr[ XF]; + default: addCin = 1'bX; + endcase + end + + // Shifter carry in and direction selector + always_comb begin + case( oper) + OP_LSL, OP_ASL, OP_ROL, OP_ROXL, OP_SLAA: shftRight = 1'b0; + OP_LSR, OP_ASR, OP_ROR, OP_ROXR: shftRight = 1'b1; + default: shftRight = 1'bX; + endcase + + case( oper) + OP_LSR, + OP_ASL, + OP_LSL: shftCin = 1'b0; + OP_ROL, + OP_ASR: shftCin = shftMsb; + OP_ROR: shftCin = aOperand[0]; + OP_ROXL, + OP_ROXR: + if( shftIsMul) + shftCin = rIrd8 ? pswCcr[NF] ^ pswCcr[VF] : pswCcr[ CF]; + else + shftCin = pswCcr[ XF]; + + OP_SLAA: shftCin = aluColumn[1]; // col4 -> 0, col 6-> 1 + default: shftCin = 'X; + endcase + end + + // ALU operation selector + always_comb begin + + // sub is DATA - ADDR + mySubber( aOperand, dOperand, addCin, + (oper == OP_ADD) | (oper == OP_ADDC) | (oper == OP_ADDX), + isByte, subResult, subCout, subOv); + + isShift = 1'b0; + case( oper) + OP_AND: result = aOperand & dOperand; + OP_OR: result = aOperand | dOperand; + OP_EOR: result = aOperand ^ dOperand; + + OP_EXT: result = { {8{aOperand[7]}}, aOperand[7:0]}; + + OP_SLAA, + OP_ASL, OP_ASR, + OP_LSL, OP_LSR, + OP_ROL, OP_ROR, + OP_ROXL, OP_ROXR: + begin + result = shftResult[15:0]; + isShift = 1'b1; + end + + OP_ADD, + OP_ADDC, + OP_ADDX, + OP_SUB, + OP_SUBC, + OP_SUB0, + OP_SUBX: result = subResult; + + OP_ABCD, + OP_SBCD: result = { 8'hXX, bcdLatch}; + + default: result = 'X; + endcase + end + + task mySubber; + input [15:0] inpa, inpb; + input cin, bAdd, isByte; + output reg [15:0] result; + output cout, ov; + + // Not very efficient! + logic [16:0] rtemp; + logic rm,sm,dm,tsm; + + begin + if( isByte) + begin + rtemp = bAdd ? { 1'b0, inpb[7:0]} + { 1'b0, inpa[7:0]} + cin: + { 1'b0, inpb[7:0] } - { 1'b0, inpa[7:0]} - cin; + result = { {8{ rtemp[7]}}, rtemp[7:0]}; + cout = rtemp[8]; + end + else begin + rtemp = bAdd ? { 1'b0, inpb } + { 1'b0, inpa} + cin: + { 1'b0, inpb } - { 1'b0, inpa} - cin; + result = rtemp[ 15:0]; + cout = rtemp[16]; + end + + rm = isByte ? rtemp[7] : rtemp[15]; + dm = isByte ? inpb[ 7] : inpb[ 15]; + tsm = isByte ? inpa[ 7] : inpa[ 15]; + sm = bAdd ? tsm : ~tsm; + + ov = (sm & dm & ~rm) | (~sm & ~dm & rm); + + // Store half carry for bcd correction + subHcarry = inpa[4] ^ inpb[4] ^ rtemp[4]; + + end + endtask + + + // CCR flags process + always_comb begin + + ccrTemp[XF] = pswCcr[XF]; ccrTemp[CF] = 0; ccrTemp[VF] = 0; + + // Not on all operators + ccrTemp[ ZF] = isByte ? ~(| result[7:0]) : ~(| result); + ccrTemp[ NF] = isByte ? result[7] : result[15]; + + unique case( oper) + + OP_EXT: + // Division overflow. + if( aluColumn == 5) begin + ccrTemp[VF] = 1'b1; + ccrTemp[NF] = 1'b1; ccrTemp[ ZF] = 1'b0; + end + + OP_SUB0, // used by NOT + OP_OR, + OP_EOR: + begin + ccrTemp[CF] = 0; ccrTemp[VF] = 0; + end + + OP_AND: + begin + // ROXL/ROXR indeed copy X to C in column 1 (OP_AND), executed before entering the loop. + // Needed when rotate count is zero, the ucode with the ROX operator never reached. + // C must be set to the value of X, X remains unaffected. + if( (aluColumn == 1) & (row[11] | row[8])) + ccrTemp[CF] = pswCcr[XF]; + else + ccrTemp[CF] = 0; + ccrTemp[VF] = 0; + end + + // Assumes col 3 of DIV use C and not X ! + // V will be set in other cols (2/3) of DIV + OP_SLAA: ccrTemp[ CF] = aOperand[15]; + + OP_LSL,OP_ROXL: + begin + ccrTemp[ CF] = shftMsb; + ccrTemp[ XF] = shftMsb; + ccrTemp[ VF] = 1'b0; + end + + OP_LSR,OP_ROXR: + begin + // 0 Needed for mul, or carry gets in high word + ccrTemp[ CF] = shftIsMul ? 1'b0 : aOperand[0]; + ccrTemp[ XF] = aOperand[0]; + // Not relevant for MUL, we clear it at mulm6 (1f) anyway. + // Not that MUL can never overlow! + ccrTemp[ VF] = 0; + // Z is checking here ALU (low result is actually in ALUE). + // But it is correct, see comment above. + end + + OP_ASL: + begin + ccrTemp[ XF] = shftMsb; ccrTemp[ CF] = shftMsb; + // V set if msb changed on any shift. + // Otherwise clear previously on OP_AND (col 1i). + ccrTemp[ VF] = pswCcr[VF] | (shftMsb ^ + (isLong ? alue[15-1] : (isByte ? aOperand[7-1] : aOperand[15-1])) ); + end + OP_ASR: + begin + ccrTemp[ XF] = aOperand[0]; ccrTemp[ CF] = aOperand[0]; + ccrTemp[ VF] = 0; + end + + // X not changed on ROL/ROR ! + OP_ROL: ccrTemp[ CF] = shftMsb; + OP_ROR: ccrTemp[ CF] = aOperand[0]; + + OP_ADD, + OP_ADDC, + OP_ADDX, + OP_SUB, + OP_SUBC, + OP_SUBX: + begin + ccrTemp[ CF] = subCout; + ccrTemp[ XF] = subCout; + ccrTemp[ VF] = subOv; + end + + OP_ABCD, + OP_SBCD: + begin + ccrTemp[ XF] = bcdCarry; + ccrTemp[ CF] = bcdCarry; + ccrTemp[ VF] = bcdOverf; + end + + endcase + + end + + // Core and psw latched at the same cycle + + // CCR filter + // CCR out mux for Z & C flags + // Z flag for 32-bit result + // Not described, but should be used also for instructions + // that clear but not set Z (ADDX/SUBX/ABCD, etc)! + logic [4:0] ccrMasked; + always_comb begin + ccrMasked = (ccrTemp & ccrMask) | (pswCcr & ~ccrMask); + // if( finish | isCorf | isArX) // No need to check specicially for isCorf as they always have the "finish" flag anyway + if( finish | isArX) + ccrMasked[ ZF] = ccrTemp[ ZF] & pswCcr[ ZF]; + end + + always_ff @( posedge clk) begin + if( enT3) begin + // Update latches from ALU operators + if( (| aluColumn)) begin + aluLatch <= result; + + coreH <= subHcarry; + + // Update CCR core + if( (| aluColumn)) + ccrCore <= ccrTemp; // Most bits not really used + end + + if( alueClkEn) + alue <= iDataBus; + else if( isShift & (| aluColumn)) + alue <= shftResult[31:16]; + end + + // CCR + // Originally on T3-T4 edge pulse !! + // Might be possible to update on T4 (but not after T0) from partial result registered on T3, it will increase performance! + if( pwrUp) + pswCcr <= '0; + else if( enT3 & ftu2Ccr) + pswCcr <= ftu[4:0]; + else if( enT3 & ~noCcrEn & (finish | init)) + pswCcr <= ccrMasked; + end + assign ccr = { 3'b0, pswCcr}; + + +endmodule + +// add bcd correction factor +// It would be more efficient to merge add/sub with main ALU !!! +module aluCorf( input [7:0] binResult, input bAdd, input cin, input hCarry, + output [7:0] bcdResult, output dC, output logic ov); + + reg [8:0] htemp; + reg [4:0] hNib; + + wire lowC = hCarry | (bAdd ? gt9( binResult[ 3:0]) : 1'b0); + wire highC = cin | (bAdd ? (gt9( htemp[7:4]) | htemp[8]) : 1'b0); + + always_comb begin + if( bAdd) begin + htemp = { 1'b0, binResult} + (lowC ? 4'h6 : 4'h0); + hNib = htemp[8:4] + (highC ? 4'h6 : 4'h0); + ov = hNib[3] & ~binResult[7]; + end + else begin + htemp = { 1'b0, binResult} - (lowC ? 4'h6 : 4'h0); + hNib = htemp[8:4] - (highC ? 4'h6 : 4'h0); + ov = ~hNib[3] & binResult[7]; + end + end + + assign bcdResult = { hNib[ 3:0], htemp[3:0]}; + assign dC = hNib[4] | cin; + + // Nibble > 9 + function gt9 (input [3:0] nib); + begin + gt9 = nib[3] & (nib[2] | nib[1]); + end + endfunction + +endmodule + + +module aluShifter( input [31:0] data, + input isByte, input isLong, swapWords, + input dir, input cin, + output logic [31:0] result); + // output reg cout + + logic [31:0] tdata; + + // size mux, put cin in position if dir == right + always_comb begin + tdata = data; + if( isByte & dir) + tdata[8] = cin; + else if( !isLong & dir) + tdata[16] = cin; + end + + always_comb begin + // Reverse alu/alue position for MUL & DIV + // Result reversed again + if( swapWords & dir) + result = { tdata[0], tdata[31:17], cin, tdata[15:1]}; + else if( swapWords) + result = { tdata[30:16], cin, tdata[14:0], tdata[31]}; + + else if( dir) + result = { cin, tdata[31:1]}; + else + result = { tdata[30:0], cin}; + end + +endmodule + + +// Get current OP from row & col +module aluGetOp( input [15:0] row, input [2:0] col, input isCorf, + output logic [4:0] aluOp); + + always_comb begin + aluOp = 'X; + unique case( col) + 1: aluOp = OP_AND; + 5: aluOp = OP_EXT; + + default: + unique case( 1'b1) + row[1]: + unique case( col) + 2: aluOp = OP_SUB; + 3: aluOp = OP_SUBC; + 4,6: aluOp = OP_SLAA; + endcase + + row[2]: + unique case( col) + 2: aluOp = OP_ADD; + 3: aluOp = OP_ADDC; + 4: aluOp = OP_ASR; + endcase + + row[3]: + unique case( col) + 2: aluOp = OP_ADDX; + 3: aluOp = isCorf ? OP_ABCD : OP_ADD; + 4: aluOp = OP_ASL; + endcase + + row[4]: + aluOp = ( col == 4) ? OP_LSL : OP_AND; + + row[5], + row[6]: + unique case( col) + 2: aluOp = OP_SUB; + 3: aluOp = OP_SUBC; + 4: aluOp = OP_LSR; + endcase + + row[7]: // MUL + unique case( col) + 2: aluOp = OP_SUB; + 3: aluOp = OP_ADD; + 4: aluOp = OP_ROXR; + endcase + + row[8]: + // OP_AND For EXT.L + // But would be more efficient to change ucode and use column 1 instead of col3 at ublock extr1! + unique case( col) + 2: aluOp = OP_EXT; + 3: aluOp = OP_AND; + 4: aluOp = OP_ROXR; + endcase + + row[9]: + unique case( col) + 2: aluOp = OP_SUBX; + 3: aluOp = OP_SBCD; + 4: aluOp = OP_ROL; + endcase + + row[10]: + unique case( col) + 2: aluOp = OP_SUBX; + 3: aluOp = OP_SUBC; + 4: aluOp = OP_ROR; + endcase + + row[11]: + unique case( col) + 2: aluOp = OP_SUB0; + 3: aluOp = OP_SUB0; + 4: aluOp = OP_ROXL; + endcase + + row[12]: aluOp = OP_ADDX; + row[13]: aluOp = OP_EOR; + row[14]: aluOp = (col == 4) ? OP_EOR : OP_OR; + row[15]: aluOp = (col == 3) ? OP_ADD : OP_OR; // OP_ADD used by DBcc + + endcase + endcase + end +endmodule + +// Decodes IRD into ALU row (1-15) +// Slow, but no need to optimize for speed since IRD is latched at least two CPU cycles before it is used +// We also register the result after combining with column from nanocode +// +// Many opcodes are not decoded because they either don't do any ALU op, +// or use only columns 1 and 5 that are the same for all rows. + +module rowDecoder( input [15:0] ird, + output logic [15:0] row, output noCcrEn, output logic isArX); + + + // Addr or data register direct + wire eaRdir = (ird[ 5:4] == 2'b00); + // Addr register direct + wire eaAdir = (ird[ 5:3] == 3'b001); + wire size11 = ird[7] & ird[6]; + + always_comb begin + case( ird[15:12]) + 'h4, + 'h9, + 'hd: + isArX = row[10] | row[12]; + default: + isArX = 1'b0; + endcase + end + + always_comb begin + unique case( ird[15:12]) + + 'h4: begin + if( ird[8]) + row = `ALU_ROW_06; // chk (or lea) + else case( ird[11:9]) + 'b000: row = `ALU_ROW_10; // negx + 'b001: row = `ALU_ROW_04; // clr + 'b010: row = `ALU_ROW_05; // neg + 'b011: row = `ALU_ROW_11; // not + 'b100: row = (ird[7]) ? `ALU_ROW_08 : `ALU_ROW_09; // nbcd/swap/ext(or pea) + 'b101: row = `ALU_ROW_15; // tst & tas + default: row = 0; + endcase + end + + 'h0: begin + if( ird[8]) // dynamic bit + row = ird[7] ? `ALU_ROW_14 : `ALU_ROW_13; + else case( ird[ 11:9]) + 'b000: row = `ALU_ROW_14; // ori + 'b001: row = `ALU_ROW_04; // andi + 'b010: row = `ALU_ROW_05; // subi + 'b011: row = `ALU_ROW_02; // addi + 'b100: row = ird[7] ? `ALU_ROW_14 : `ALU_ROW_13; // static bit + 'b101: row = `ALU_ROW_13; // eori + 'b110: row = `ALU_ROW_06; // cmpi + default: row = 0; + endcase + end + + // MOVE + // move.b originally also rows 5 & 15. Only because IRD bit 14 is not decoded. + // It's the same for move the operations performed by MOVE.B + + 'h1,'h2,'h3: row = `ALU_ROW_02; + + 'h5: + if( size11) + row = `ALU_ROW_15; // As originally and easier to decode + else + row = ird[8] ? `ALU_ROW_05 : `ALU_ROW_02; // addq/subq + 'h6: row = 0; //bcc/bra/bsr + 'h7: row = `ALU_ROW_02; // moveq + 'h8: + if( size11) // div + row = `ALU_ROW_01; + else if( ird[8] & eaRdir) // sbcd + row = `ALU_ROW_09; + else + row = `ALU_ROW_14; // or + 'h9: + if( ird[8] & ~size11 & eaRdir) + row = `ALU_ROW_10; // subx + else + row = `ALU_ROW_05; // sub/suba + 'hb: + if( ird[8] & ~size11 & ~eaAdir) + row = `ALU_ROW_13; // eor + else + row = `ALU_ROW_06; // cmp/cmpa/cmpm + 'hc: + if( size11) + row = `ALU_ROW_07; // mul + else if( ird[8] & eaRdir) // abcd + row = `ALU_ROW_03; + else + row = `ALU_ROW_04; // and + 'hd: + if( ird[8] & ~size11 & eaRdir) + row = `ALU_ROW_12; // addx + else + row = `ALU_ROW_02; // add/adda + 'he: + begin + reg [1:0] stype; + + if( size11) // memory shift/rotate + stype = ird[ 10:9]; + else // register shift/rotate + stype = ird[ 4:3]; + + case( {stype, ird[8]}) + 0: row = `ALU_ROW_02; // ASR + 1: row = `ALU_ROW_03; // ASL + 2: row = `ALU_ROW_05; // LSR + 3: row = `ALU_ROW_04; // LSL + 4: row = `ALU_ROW_08; // ROXR + 5: row = `ALU_ROW_11; // ROXL + 6: row = `ALU_ROW_10; // ROR + 7: row = `ALU_ROW_09; // ROL + endcase + end + + default: row = 0; + endcase + end + + // Decode opcodes that don't affect flags + // ADDA/SUBA ADDQ/SUBQ MOVEA + + assign noCcrEn = + // ADDA/SUBA + ( ird[15] & ~ird[13] & ird[12] & size11) | + // ADDQ/SUBQ to An + ( (ird[15:12] == 4'h5) & eaAdir) | + // MOVEA + ( (~ird[15] & ~ird[14] & ird[13]) & ird[8:6] == 3'b001); + +endmodule + +// Row/col CCR update table +module ccrTable( + input [2:0] col, input [15:0] row, input finish, + output logic [MASK_NBITS-1:0] ccrMask); + + localparam + KNZ00 = 5'b01111, // ok coz operators clear them + KKZKK = 5'b00100, + KNZKK = 5'b01100, + KNZ10 = 5'b01111, // Used by OP_EXT on divison overflow + KNZ0C = 5'b01111, // Used by DIV. V should be 0, but it is ok: + // DIVU: ends with quotient - 0, so V & C always clear. + // DIVS: ends with 1i (AND), again, V & C always clear. + + KNZVC = 5'b01111, + XNKVC = 5'b11011, // Used by BCD instructions. Don't modify Z at all at the binary operation. Only at the BCD correction cycle + + CUPDALL = 5'b11111, + CUNUSED = 5'bxxxxx; + + + logic [MASK_NBITS-1:0] ccrMask1; + + always_comb begin + unique case( col) + 1: ccrMask = ccrMask1; + + 2,3: + unique case( 1'b1) + row[1]: ccrMask = KNZ0C; // DIV, used as 3n in col3 + + row[3], // ABCD + row[9]: // SBCD/NBCD + ccrMask = (col == 2) ? XNKVC : CUPDALL; + + row[2], + row[5], + row[10], // SUBX/NEGX + row[12]: ccrMask = CUPDALL; // ADDX + + row[6], // CMP + row[7], // MUL + row[11]: ccrMask = KNZVC; // NOT + row[4], + row[8], // Not used in col 3 + row[13], + row[14]: ccrMask = KNZ00; + row[15]: ccrMask = 5'b0; // TAS/Scc, not used in col 3 + // default: ccrMask = CUNUSED; + endcase + + 4: + unique case( row) + // 1: DIV, only n (4n & 6n) + // 14: BCLR 4n + // 6,12,13,15 // not used + `ALU_ROW_02, + `ALU_ROW_03, // ASL (originally ANZVA) + `ALU_ROW_04, + `ALU_ROW_05: ccrMask = CUPDALL; // Shifts (originally ANZ0A) + + `ALU_ROW_07: ccrMask = KNZ00; // MUL (originally KNZ0A) + `ALU_ROW_09, + `ALU_ROW_10: ccrMask = KNZ00; // RO[lr] (originally KNZ0A) + `ALU_ROW_08, // ROXR (originally ANZ0A) + `ALU_ROW_11: ccrMask = CUPDALL; // ROXL (originally ANZ0A) + default: ccrMask = CUNUSED; + endcase + + 5: ccrMask = row[1] ? KNZ10 : 5'b0; + default: ccrMask = CUNUSED; + endcase + end + + // Column 1 (AND) + always_comb begin + if( finish) + ccrMask1 = row[7] ? KNZ00 : KNZKK; + else + ccrMask1 = row[13] | row[14] ? KKZKK : KNZ00; + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/uaddrPla.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/uaddrPla.sv new file mode 100644 index 0000000000000000000000000000000000000000..3be2f74d6d351fc52477ee4006942a31c89325d5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/FX68K/uaddrPla.sv @@ -0,0 +1,2195 @@ +// +// FX68K +// +// Opcode to uaddr entry routines (A2-A2-A3) PLA +// + +// altera message_off 10230 + + +`timescale 1 ns / 1 ns + +`define NMA_BITS 10 + +`define SFTM1 'h3C7 +`define SRRW1 'h382 +`define SRIW1 'h381 +`define SRRL1 'h386 +`define SRIL1 'h385 +`define BSRI1 'h089 +`define BSRW1 'h0A9 +`define BBCI1 'h308 +`define BBCW1 'h068 +`define RLQL1 'h23B +`define ADRW1 'h006 +`define PINW1 'h21C +`define PDCW1 'h103 +`define ADSW1 'h1C2 +`define AIXW0 'h1E3 +`define ABWW1 'h00A +`define ABLW1 'h1E2 +`define TRAP1 'h1D0 +`define LINK1 'h30B +`define UNLK1 'h119 +`define LUSP1 'h2F5 +`define SUSP1 'h230 +`define TRPV1 'h06D +`define RSET1 'h3A6 +`define B 'h363 +`define STOP1 'h3A2 +`define RTR1 'h12A +`define RTS1 'h126 + + +module pla_lined( + input [3:0] movEa, + input [3:0] col, + + input [15:0] opcode, + input [15:0] lineBmap, + + output palIll, + output logic [`NMA_BITS-1:0] plaA1, + output logic [`NMA_BITS-1:0] plaA2, + output logic [`NMA_BITS-1:0] plaA3 + ); + + wire [3:0] line = opcode[ 15:12]; + wire [2:0] row86 = opcode[8:6]; + + logic [15:0] arIll; + logic [`NMA_BITS-1:0] arA1[ 15:0]; + logic [`NMA_BITS-1:0] arA23[ 15:0]; + logic [`NMA_BITS-1:0] scA3; + + logic illMisc; + logic [`NMA_BITS-1:0] a1Misc; + + /* + reg [`NMA_BITS-1:0] lineMask[ 15:0]; + always_comb begin + integer i; + for( i = 0; i < 16; i = i + 1) + lineMask[i] = { 16{lineBmap[ i]}}; + end + */ + + assign palIll = (| (arIll & lineBmap)); + + // Only line 0 has 3 subs + assign plaA1 = arA1[ line]; + assign plaA2 = arA23[ line]; + assign plaA3 = lineBmap[0] ? scA3 : arA23[ line]; + + + // Simple lines + always_comb begin + // Line 6: Branch + arIll[ 'h6] = 1'b0; + arA23[ 'h6] = 'X; + if( opcode[ 11:8] == 4'h1) + arA1[ 'h6] = (| opcode[7:0]) ? `BSRI1 : `BSRW1; + else + arA1[ 'h6] = (| opcode[7:0]) ? `BBCI1 : `BBCW1; + + // Line 7: moveq + arIll[ 'h7] = opcode[ 8]; + arA23[ 'h7] = 'X; + arA1[ 'h7] = `RLQL1; + + // Line A & F + arIll[ 'ha] = 1'b1; arIll[ 'hf] = 1'b1; + arA1[ 'ha] = 'X; arA1[ 'hf] = 'X; + arA23[ 'ha] = 'X; arA23[ 'hf] = 'X; + + end + + // Special lines + + // Line e: shifts + always_comb begin + if( ~opcode[11] & opcode[7] & opcode[6]) + begin + arA23[ 'he] = `SFTM1; + unique case( col) + 2: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `ADRW1; end + 3: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `PINW1; end + 4: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `PDCW1; end + 5: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `ADSW1; end + 6: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `AIXW0; end + 7: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `ABWW1; end + 8: begin arIll[ 'he] = 1'b0; arA1[ 'he] = `ABLW1; end + default: begin arIll[ 'he] = 1'b1; arA1[ 'he] = 'X; end + endcase + end + else + begin + arA23[ 'he] = 'X; + unique case( opcode[ 7:6]) + 2'b00, + 2'b01: begin + arIll[ 'he] = 1'b0; + arA1[ 'he] = opcode[ 5] ? `SRRW1 : `SRIW1; + end + 2'b10: begin + arIll[ 'he] = 1'b0; + arA1[ 'he] = opcode[ 5] ? `SRRL1 : `SRIL1; + end + 2'b11: begin arIll[ 'he] = 1'b1; arA1[ 'he] = 'X; end + endcase + end + end + + // Misc. line 4 row + always_comb begin + illMisc = 1'b0; + case( opcode[ 5:3]) + 3'b000, + 3'b001: a1Misc = `TRAP1; + 3'b010: a1Misc = `LINK1; + 3'b011: a1Misc = `UNLK1; + 3'b100: a1Misc = `LUSP1; + 3'b101: a1Misc = `SUSP1; + + 3'b110: + case( opcode[ 2:0]) + 3'b110: a1Misc = `TRPV1; + 3'b000: a1Misc = `RSET1; + 3'b001: a1Misc = `B; + 3'b010: a1Misc = `STOP1; + 3'b011: a1Misc = `RTR1; + 3'b111: a1Misc = `RTR1; + 3'b101: a1Misc = `RTS1; + default: begin illMisc = 1'b1; a1Misc = 'X; end + endcase + + default: begin illMisc = 1'b1; a1Misc = 'X; end + endcase + end + +// +// Past here +// + + +// +// Line: 0 +// +always_comb begin + +if( (opcode[11:6] & 'h1F) == 'h8) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1CC; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h0) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1CC; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h1F) == 'h9) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1CC; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h1) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1CC; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h1F) == 'hA) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h10C; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00B; scA3 = 'h29D; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00F; scA3 = 'h29D; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h179; scA3 = 'h29D; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1C6; scA3 = 'h29D; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E7; scA3 = 'h29D; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00E; scA3 = 'h29D; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E6; scA3 = 'h29D; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h2) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h10C; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00B; scA3 = 'h29D; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00F; scA3 = 'h29D; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h179; scA3 = 'h29D; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1C6; scA3 = 'h29D; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E7; scA3 = 'h29D; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00E; scA3 = 'h29D; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E6; scA3 = 'h29D; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h10) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h11) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h100; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h299; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h299; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h299; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h299; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h299; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h299; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h299; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h37) == 'h12) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h10C; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00B; scA3 = 'h29D; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00F; scA3 = 'h29D; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h179; scA3 = 'h29D; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1C6; scA3 = 'h29D; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E7; scA3 = 'h29D; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00E; scA3 = 'h29D; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E6; scA3 = 'h29D; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h4) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E7; arA23[ 'h0] = 'X; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1D2; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h006; arA23[ 'h0] = 'X; scA3 = 'h215; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h21C; arA23[ 'h0] = 'X; scA3 = 'h215; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h103; arA23[ 'h0] = 'X; scA3 = 'h215; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1C2; arA23[ 'h0] = 'X; scA3 = 'h215; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E3; arA23[ 'h0] = 'X; scA3 = 'h215; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h00A; arA23[ 'h0] = 'X; scA3 = 'h215; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E2; arA23[ 'h0] = 'X; scA3 = 'h215; end + 9: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1C2; arA23[ 'h0] = 'X; scA3 = 'h215; end + 10: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E3; arA23[ 'h0] = 'X; scA3 = 'h215; end + 11: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h0EA; arA23[ 'h0] = 'h0AB; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h5) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3EF; arA23[ 'h0] = 'X; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1D6; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h006; arA23[ 'h0] = 'X; scA3 = 'h081; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h21C; arA23[ 'h0] = 'X; scA3 = 'h081; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h103; arA23[ 'h0] = 'X; scA3 = 'h081; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1C2; arA23[ 'h0] = 'X; scA3 = 'h081; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E3; arA23[ 'h0] = 'X; scA3 = 'h081; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h00A; arA23[ 'h0] = 'X; scA3 = 'h081; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E2; arA23[ 'h0] = 'X; scA3 = 'h081; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h7) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3EF; arA23[ 'h0] = 'X; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1CE; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h006; arA23[ 'h0] = 'X; scA3 = 'h081; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h21C; arA23[ 'h0] = 'X; scA3 = 'h081; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h103; arA23[ 'h0] = 'X; scA3 = 'h081; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1C2; arA23[ 'h0] = 'X; scA3 = 'h081; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E3; arA23[ 'h0] = 'X; scA3 = 'h081; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h00A; arA23[ 'h0] = 'X; scA3 = 'h081; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E2; arA23[ 'h0] = 'X; scA3 = 'h081; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h6) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3EB; arA23[ 'h0] = 'X; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1CA; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h006; arA23[ 'h0] = 'X; scA3 = 'h069; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h21C; arA23[ 'h0] = 'X; scA3 = 'h069; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h103; arA23[ 'h0] = 'X; scA3 = 'h069; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1C2; arA23[ 'h0] = 'X; scA3 = 'h069; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E3; arA23[ 'h0] = 'X; scA3 = 'h069; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h00A; arA23[ 'h0] = 'X; scA3 = 'h069; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h1E2; arA23[ 'h0] = 'X; scA3 = 'h069; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h20) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h3E7; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h215; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h215; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h215; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h215; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h215; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h215; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h215; end + 9: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h215; end + 10: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h215; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h21) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h3EF; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h081; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h081; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h081; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h081; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h081; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h081; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h081; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h23) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h3EF; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h081; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h081; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h081; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h081; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h081; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h081; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h081; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h22) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h3EB; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h069; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h069; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h069; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h069; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h069; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h069; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h069; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h30) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h108; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h087; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h087; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h087; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h087; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h087; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h087; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h087; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h31) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h108; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h006; scA3 = 'h087; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h21C; scA3 = 'h087; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h103; scA3 = 'h087; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1C2; scA3 = 'h087; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E3; scA3 = 'h087; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h00A; scA3 = 'h087; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h2B9; arA23[ 'h0] = 'h1E2; scA3 = 'h087; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else if( opcode[11:6] == 'h32) begin + unique case ( col) + 0: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h104; scA3 = 'X; end + 1: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 2: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00B; scA3 = 'h08F; end + 3: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00F; scA3 = 'h08F; end + 4: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h179; scA3 = 'h08F; end + 5: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1C6; scA3 = 'h08F; end + 6: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E7; scA3 = 'h08F; end + 7: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h00E; scA3 = 'h08F; end + 8: begin arIll[ 'h0] = 1'b0; arA1[ 'h0] = 'h3E0; arA23[ 'h0] = 'h1E6; scA3 = 'h08F; end + 9: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 10: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + 11: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + default: begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + endcase +end + +else begin arIll[ 'h0] = 1'b1; arA1[ 'h0] = 'X ; arA23[ 'h0] = 'X; scA3 = 'X; end + +end + + +// +// Line: 4 +// +always_comb begin + +if( (opcode[11:6] & 'h27) == 'h0) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h133; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h2B8; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h2B8; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h2B8; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h2B8; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h2B8; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h2B8; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h2B8; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h27) == 'h1) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h133; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h2B8; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h2B8; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h2B8; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h2B8; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h2B8; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h2B8; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h2B8; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h27) == 'h2) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h137; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00B; arA23[ 'h4] = 'h2BC; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00F; arA23[ 'h4] = 'h2BC; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h179; arA23[ 'h4] = 'h2BC; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C6; arA23[ 'h4] = 'h2BC; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E7; arA23[ 'h4] = 'h2BC; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00E; arA23[ 'h4] = 'h2BC; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E6; arA23[ 'h4] = 'h2BC; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h3) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3A5; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h3A1; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h3A1; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h3A1; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h3A1; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h3A1; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h3A1; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h3A1; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h13) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h301; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h159; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h159; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h159; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h159; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h159; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h159; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h159; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h159; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h159; end + 11: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h0EA; arA23[ 'h4] = 'h301; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h1B) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h301; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h159; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h159; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h159; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h159; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h159; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h159; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h159; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h159; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h159; end + 11: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h0EA; arA23[ 'h4] = 'h301; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h20) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h13B; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h15C; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h15C; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h15C; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h15C; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h15C; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h15C; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h15C; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h21) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h341; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h17C; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h17D; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FF; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h178; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FA; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h17D; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FF; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h22) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h133; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3A0; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3A4; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F1; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h325; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1ED; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E5; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h23) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h232; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3A0; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3A4; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F1; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h325; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1ED; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E5; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h28) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h12D; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h3C3; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h3C3; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h3C3; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h3C3; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h3C3; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h3C3; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h3C3; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h29) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h12D; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h3C3; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h3C3; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h3C3; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h3C3; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h3C3; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h3C3; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h3C3; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h2A) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h125; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00B; arA23[ 'h4] = 'h3CB; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00F; arA23[ 'h4] = 'h3CB; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h179; arA23[ 'h4] = 'h3CB; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C6; arA23[ 'h4] = 'h3CB; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E7; arA23[ 'h4] = 'h3CB; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00E; arA23[ 'h4] = 'h3CB; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E6; arA23[ 'h4] = 'h3CB; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h2B) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h345; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h343; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h343; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h343; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h343; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h343; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h343; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h343; end + 9: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h3E) == 'h32) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h127; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h123; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FD; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F5; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F9; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E9; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FD; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F5; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h6) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h152; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h006; arA23[ 'h4] = 'h151; end + 3: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h21C; arA23[ 'h4] = 'h151; end + 4: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h103; arA23[ 'h4] = 'h151; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h151; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h151; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h00A; arA23[ 'h4] = 'h151; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E2; arA23[ 'h4] = 'h151; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1C2; arA23[ 'h4] = 'h151; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1E3; arA23[ 'h4] = 'h151; end + 11: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h0EA; arA23[ 'h4] = 'h152; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( (opcode[11:6] & 'h7) == 'h7) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2F1; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2F2; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FB; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h275; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h3E4; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2F2; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1FB; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h3A) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h273; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2B0; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F3; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h293; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F2; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2B0; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F3; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h3B) begin + unique case ( col) + 0: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 1: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 2: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h255; arA23[ 'h4] = 'X; end + 3: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 4: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + 5: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2B4; arA23[ 'h4] = 'X; end + 6: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F7; arA23[ 'h4] = 'X; end + 7: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h297; arA23[ 'h4] = 'X; end + 8: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F6; arA23[ 'h4] = 'X; end + 9: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h2B4; arA23[ 'h4] = 'X; end + 10: begin arIll[ 'h4] = 1'b0; arA1[ 'h4] = 'h1F7; arA23[ 'h4] = 'X; end + 11: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + default: begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + endcase +end + +else if( opcode[11:6] == 'h39) begin + arIll[ 'h4] = illMisc; arA1[ 'h4] = a1Misc ; arA23[ 'h4] = 'X; +end + +else begin arIll[ 'h4] = 1'b1; arA1[ 'h4] = 'X ; arA23[ 'h4] = 'X; end + +end + +always_comb begin + +// +// Line: 1 +// +unique case( movEa) + +0: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h121; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h29B; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h29B; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h29B; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h29B; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h29B; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h29B; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h29B; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h29B; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h29B; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h121; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +2: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h2FA; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h3AB; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h3AB; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h3AB; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h3AB; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h3AB; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h3AB; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h3AB; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h3AB; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h3AB; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h2FA; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +3: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h2FE; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h3AF; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h3AF; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h3AF; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h3AF; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h3AF; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h3AF; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h3AF; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h3AF; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h3AF; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h2FE; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +4: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h2F8; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h38B; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h38B; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h38B; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h38B; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h38B; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h38B; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h38B; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h38B; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h38B; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h2F8; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +5: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h2DA; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h38A; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h38A; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h38A; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h38A; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h38A; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h38A; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h38A; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h38A; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h38A; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h2DA; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +6: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1EB; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h298; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h298; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h298; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h298; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h298; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h298; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h298; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h298; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h298; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h1EB; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +7: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h2D9; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h388; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h388; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h388; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h388; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h388; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h388; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h388; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h388; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h388; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h2D9; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase + +8: // Row: 8 + unique case ( col) + 0: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1EA; arA23[ 'h1] = 'X; end + 1: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + 2: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h006; arA23[ 'h1] = 'h32B; end + 3: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h21C; arA23[ 'h1] = 'h32B; end + 4: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h103; arA23[ 'h1] = 'h32B; end + 5: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h32B; end + 6: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h32B; end + 7: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h00A; arA23[ 'h1] = 'h32B; end + 8: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E2; arA23[ 'h1] = 'h32B; end + 9: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1C2; arA23[ 'h1] = 'h32B; end + 10: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h1E3; arA23[ 'h1] = 'h32B; end + 11: begin arIll[ 'h1] = 1'b0; arA1[ 'h1] = 'h0EA; arA23[ 'h1] = 'h1EA; end + default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end + endcase +default: begin arIll[ 'h1] = 1'b1; arA1[ 'h1] = 'X ; arA23[ 'h1] = 'X; end +endcase + +// +// Line: 2 +// +unique case( movEa) + +0: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h129; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h129; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h29F; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h29F; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h29F; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29F; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29F; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h29F; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h29F; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29F; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29F; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h129; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +1: // Row: 1 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h129; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h129; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h29F; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h29F; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h29F; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29F; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29F; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h29F; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h29F; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29F; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29F; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h129; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +2: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2F9; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2F9; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h3A9; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h3A9; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h3A9; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h3A9; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h3A9; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h3A9; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h3A9; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h3A9; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h3A9; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h2F9; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +3: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2FD; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2FD; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h3AD; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h3AD; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h3AD; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h3AD; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h3AD; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h3AD; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h3AD; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h3AD; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h3AD; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h2FD; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +4: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2FC; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2FC; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h38F; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h38F; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h38F; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38F; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38F; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h38F; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h38F; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38F; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38F; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h2FC; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +5: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2DE; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2DE; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h38E; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h38E; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h38E; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38E; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38E; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h38E; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h38E; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38E; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38E; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h2DE; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +6: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1EF; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1EF; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h29C; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h29C; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h29C; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29C; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29C; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h29C; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h29C; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h29C; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h29C; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h1EF; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +7: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2DD; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h2DD; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h38C; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h38C; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h38C; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38C; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38C; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h38C; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h38C; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h38C; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h38C; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h2DD; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase + +8: // Row: 8 + unique case ( col) + 0: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1EE; arA23[ 'h2] = 'X; end + 1: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1EE; arA23[ 'h2] = 'X; end + 2: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00B; arA23[ 'h2] = 'h30F; end + 3: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00F; arA23[ 'h2] = 'h30F; end + 4: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h179; arA23[ 'h2] = 'h30F; end + 5: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h30F; end + 6: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h30F; end + 7: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h00E; arA23[ 'h2] = 'h30F; end + 8: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E6; arA23[ 'h2] = 'h30F; end + 9: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1C6; arA23[ 'h2] = 'h30F; end + 10: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h1E7; arA23[ 'h2] = 'h30F; end + 11: begin arIll[ 'h2] = 1'b0; arA1[ 'h2] = 'h0A7; arA23[ 'h2] = 'h1EE; end + default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end + endcase +default: begin arIll[ 'h2] = 1'b1; arA1[ 'h2] = 'X ; arA23[ 'h2] = 'X; end +endcase + +// +// Line: 3 +// +unique case( movEa) + +0: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h121; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h121; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h29B; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h29B; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h29B; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h29B; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h29B; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h29B; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h29B; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h29B; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h29B; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h121; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +1: // Row: 1 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h279; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h279; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h158; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h158; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h158; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h158; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h158; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h158; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h158; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h158; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h158; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h279; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +2: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2FA; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2FA; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h3AB; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h3AB; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h3AB; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h3AB; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h3AB; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h3AB; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h3AB; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h3AB; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h3AB; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h2FA; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +3: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2FE; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2FE; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h3AF; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h3AF; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h3AF; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h3AF; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h3AF; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h3AF; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h3AF; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h3AF; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h3AF; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h2FE; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +4: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2F8; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2F8; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h38B; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h38B; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h38B; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h38B; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h38B; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h38B; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h38B; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h38B; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h38B; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h2F8; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +5: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2DA; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2DA; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h38A; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h38A; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h38A; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h38A; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h38A; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h38A; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h38A; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h38A; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h38A; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h2DA; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +6: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1EB; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1EB; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h298; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h298; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h298; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h298; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h298; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h298; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h298; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h298; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h298; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h1EB; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +7: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2D9; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h2D9; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h388; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h388; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h388; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h388; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h388; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h388; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h388; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h388; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h388; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h2D9; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase + +8: // Row: 8 + unique case ( col) + 0: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1EA; arA23[ 'h3] = 'X; end + 1: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1EA; arA23[ 'h3] = 'X; end + 2: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h006; arA23[ 'h3] = 'h32B; end + 3: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h21C; arA23[ 'h3] = 'h32B; end + 4: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h103; arA23[ 'h3] = 'h32B; end + 5: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h32B; end + 6: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h32B; end + 7: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h00A; arA23[ 'h3] = 'h32B; end + 8: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E2; arA23[ 'h3] = 'h32B; end + 9: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1C2; arA23[ 'h3] = 'h32B; end + 10: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h1E3; arA23[ 'h3] = 'h32B; end + 11: begin arIll[ 'h3] = 1'b0; arA1[ 'h3] = 'h0EA; arA23[ 'h3] = 'h1EA; end + default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end + endcase +default: begin arIll[ 'h3] = 1'b1; arA1[ 'h3] = 'X ; arA23[ 'h3] = 'X; end +endcase + +// +// Line: 5 +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2D8; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h2F3; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h2F3; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h2F3; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h2F3; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h2F3; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h2F3; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h2F3; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2D8; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h2F3; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h2F3; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h2F3; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h2F3; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h2F3; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h2F3; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h2F3; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00B; arA23[ 'h5] = 'h2F7; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00F; arA23[ 'h5] = 'h2F7; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h179; arA23[ 'h5] = 'h2F7; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C6; arA23[ 'h5] = 'h2F7; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E7; arA23[ 'h5] = 'h2F7; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00E; arA23[ 'h5] = 'h2F7; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E6; arA23[ 'h5] = 'h2F7; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h384; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h06C; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h380; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h380; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h380; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h380; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h380; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h380; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h380; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2D8; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h2F3; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h2F3; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h2F3; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h2F3; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h2F3; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h2F3; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h2F3; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2D8; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h2F3; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h2F3; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h2F3; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h2F3; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h2F3; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h2F3; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h2F3; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h2DC; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00B; arA23[ 'h5] = 'h2F7; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00F; arA23[ 'h5] = 'h2F7; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h179; arA23[ 'h5] = 'h2F7; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C6; arA23[ 'h5] = 'h2F7; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E7; arA23[ 'h5] = 'h2F7; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00E; arA23[ 'h5] = 'h2F7; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E6; arA23[ 'h5] = 'h2F7; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h384; arA23[ 'h5] = 'X; end + 1: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h06C; arA23[ 'h5] = 'X; end + 2: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h006; arA23[ 'h5] = 'h380; end + 3: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h21C; arA23[ 'h5] = 'h380; end + 4: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h103; arA23[ 'h5] = 'h380; end + 5: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1C2; arA23[ 'h5] = 'h380; end + 6: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E3; arA23[ 'h5] = 'h380; end + 7: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h00A; arA23[ 'h5] = 'h380; end + 8: begin arIll[ 'h5] = 1'b0; arA1[ 'h5] = 'h1E2; arA23[ 'h5] = 'h380; end + default: begin arIll[ 'h5] = 1'b1; arA1[ 'h5] = 'X ; arA23[ 'h5] = 'X; end + endcase +endcase + +// +// Line: 8 +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C1; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h1C3; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h1C3; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h1C3; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h1C3; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h1C3; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h1C3; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h1C3; end + 9: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h1C3; end + 10: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h1C3; end + 11: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0EA; arA23[ 'h8] = 'h1C1; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C1; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h1C3; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h1C3; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h1C3; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h1C3; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h1C3; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h1C3; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h1C3; end + 9: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h1C3; end + 10: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h1C3; end + 11: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0EA; arA23[ 'h8] = 'h1C1; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C5; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00B; arA23[ 'h8] = 'h1CB; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00F; arA23[ 'h8] = 'h1CB; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h179; arA23[ 'h8] = 'h1CB; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C6; arA23[ 'h8] = 'h1CB; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E7; arA23[ 'h8] = 'h1CB; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00E; arA23[ 'h8] = 'h1CB; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E6; arA23[ 'h8] = 'h1CB; end + 9: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C6; arA23[ 'h8] = 'h1CB; end + 10: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E7; arA23[ 'h8] = 'h1CB; end + 11: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0A7; arA23[ 'h8] = 'h1C5; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0A6; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h0A4; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h0A4; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h0A4; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h0A4; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h0A4; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h0A4; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h0A4; end + 9: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h0A4; end + 10: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h0A4; end + 11: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0EA; arA23[ 'h8] = 'h0A6; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1CD; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h107; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h299; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h299; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h299; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h299; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h299; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h299; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h299; end + 9: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 10: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 11: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h299; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h299; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h299; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h299; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h299; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h299; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h299; end + 9: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 10: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 11: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00B; arA23[ 'h8] = 'h29D; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00F; arA23[ 'h8] = 'h29D; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h179; arA23[ 'h8] = 'h29D; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C6; arA23[ 'h8] = 'h29D; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E7; arA23[ 'h8] = 'h29D; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00E; arA23[ 'h8] = 'h29D; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E6; arA23[ 'h8] = 'h29D; end + 9: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 10: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 11: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0AE; arA23[ 'h8] = 'X; end + 1: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + 2: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h006; arA23[ 'h8] = 'h0AC; end + 3: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h21C; arA23[ 'h8] = 'h0AC; end + 4: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h103; arA23[ 'h8] = 'h0AC; end + 5: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h0AC; end + 6: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h0AC; end + 7: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h00A; arA23[ 'h8] = 'h0AC; end + 8: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E2; arA23[ 'h8] = 'h0AC; end + 9: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1C2; arA23[ 'h8] = 'h0AC; end + 10: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h1E3; arA23[ 'h8] = 'h0AC; end + 11: begin arIll[ 'h8] = 1'b0; arA1[ 'h8] = 'h0EA; arA23[ 'h8] = 'h0AE; end + default: begin arIll[ 'h8] = 1'b1; arA1[ 'h8] = 'X ; arA23[ 'h8] = 'X; end + endcase +endcase + +// +// Line: 9 +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C1; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h006; arA23[ 'h9] = 'h1C3; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h21C; arA23[ 'h9] = 'h1C3; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h103; arA23[ 'h9] = 'h1C3; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C3; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C3; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00A; arA23[ 'h9] = 'h1C3; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E2; arA23[ 'h9] = 'h1C3; end + 9: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C3; end + 10: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C3; end + 11: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h0EA; arA23[ 'h9] = 'h1C1; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C1; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C1; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h006; arA23[ 'h9] = 'h1C3; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h21C; arA23[ 'h9] = 'h1C3; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h103; arA23[ 'h9] = 'h1C3; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C3; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C3; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00A; arA23[ 'h9] = 'h1C3; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E2; arA23[ 'h9] = 'h1C3; end + 9: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C3; end + 10: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C3; end + 11: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h0EA; arA23[ 'h9] = 'h1C1; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C5; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C5; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00B; arA23[ 'h9] = 'h1CB; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00F; arA23[ 'h9] = 'h1CB; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h179; arA23[ 'h9] = 'h1CB; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C6; arA23[ 'h9] = 'h1CB; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E7; arA23[ 'h9] = 'h1CB; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00E; arA23[ 'h9] = 'h1CB; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E6; arA23[ 'h9] = 'h1CB; end + 9: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C6; arA23[ 'h9] = 'h1CB; end + 10: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E7; arA23[ 'h9] = 'h1CB; end + 11: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h0A7; arA23[ 'h9] = 'h1C5; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C9; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C9; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h006; arA23[ 'h9] = 'h1C7; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h21C; arA23[ 'h9] = 'h1C7; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h103; arA23[ 'h9] = 'h1C7; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C7; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C7; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00A; arA23[ 'h9] = 'h1C7; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E2; arA23[ 'h9] = 'h1C7; end + 9: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h1C7; end + 10: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h1C7; end + 11: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h0EA; arA23[ 'h9] = 'h1C9; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C1; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h10F; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h006; arA23[ 'h9] = 'h299; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h21C; arA23[ 'h9] = 'h299; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h103; arA23[ 'h9] = 'h299; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h299; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h299; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00A; arA23[ 'h9] = 'h299; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E2; arA23[ 'h9] = 'h299; end + 9: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 10: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 11: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C1; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h10F; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h006; arA23[ 'h9] = 'h299; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h21C; arA23[ 'h9] = 'h299; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h103; arA23[ 'h9] = 'h299; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C2; arA23[ 'h9] = 'h299; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E3; arA23[ 'h9] = 'h299; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00A; arA23[ 'h9] = 'h299; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E2; arA23[ 'h9] = 'h299; end + 9: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 10: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 11: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C5; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h10B; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00B; arA23[ 'h9] = 'h29D; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00F; arA23[ 'h9] = 'h29D; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h179; arA23[ 'h9] = 'h29D; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C6; arA23[ 'h9] = 'h29D; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E7; arA23[ 'h9] = 'h29D; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00E; arA23[ 'h9] = 'h29D; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E6; arA23[ 'h9] = 'h29D; end + 9: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 10: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + 11: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C5; arA23[ 'h9] = 'X; end + 1: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C5; arA23[ 'h9] = 'X; end + 2: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00B; arA23[ 'h9] = 'h1CB; end + 3: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00F; arA23[ 'h9] = 'h1CB; end + 4: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h179; arA23[ 'h9] = 'h1CB; end + 5: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C6; arA23[ 'h9] = 'h1CB; end + 6: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E7; arA23[ 'h9] = 'h1CB; end + 7: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h00E; arA23[ 'h9] = 'h1CB; end + 8: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E6; arA23[ 'h9] = 'h1CB; end + 9: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1C6; arA23[ 'h9] = 'h1CB; end + 10: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h1E7; arA23[ 'h9] = 'h1CB; end + 11: begin arIll[ 'h9] = 1'b0; arA1[ 'h9] = 'h0A7; arA23[ 'h9] = 'h1C5; end + default: begin arIll[ 'h9] = 1'b1; arA1[ 'h9] = 'X ; arA23[ 'h9] = 'X; end + endcase +endcase + +// +// Line: B +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D1; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h006; arA23[ 'hb] = 'h1D3; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h21C; arA23[ 'hb] = 'h1D3; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h103; arA23[ 'hb] = 'h1D3; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1D3; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1D3; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00A; arA23[ 'hb] = 'h1D3; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E2; arA23[ 'hb] = 'h1D3; end + 9: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1D3; end + 10: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1D3; end + 11: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h0EA; arA23[ 'hb] = 'h1D1; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D1; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D1; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h006; arA23[ 'hb] = 'h1D3; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h21C; arA23[ 'hb] = 'h1D3; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h103; arA23[ 'hb] = 'h1D3; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1D3; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1D3; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00A; arA23[ 'hb] = 'h1D3; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E2; arA23[ 'hb] = 'h1D3; end + 9: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1D3; end + 10: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1D3; end + 11: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h0EA; arA23[ 'hb] = 'h1D1; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D5; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D5; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00B; arA23[ 'hb] = 'h1D7; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00F; arA23[ 'hb] = 'h1D7; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h179; arA23[ 'hb] = 'h1D7; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C6; arA23[ 'hb] = 'h1D7; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E7; arA23[ 'hb] = 'h1D7; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00E; arA23[ 'hb] = 'h1D7; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E6; arA23[ 'hb] = 'h1D7; end + 9: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C6; arA23[ 'hb] = 'h1D7; end + 10: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E7; arA23[ 'hb] = 'h1D7; end + 11: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h0A7; arA23[ 'hb] = 'h1D5; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D9; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D9; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h006; arA23[ 'hb] = 'h1CF; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h21C; arA23[ 'hb] = 'h1CF; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h103; arA23[ 'hb] = 'h1CF; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1CF; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1CF; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00A; arA23[ 'hb] = 'h1CF; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E2; arA23[ 'hb] = 'h1CF; end + 9: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h1CF; end + 10: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h1CF; end + 11: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h0EA; arA23[ 'hb] = 'h1D9; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h100; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h06B; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h006; arA23[ 'hb] = 'h299; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h21C; arA23[ 'hb] = 'h299; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h103; arA23[ 'hb] = 'h299; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h299; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h299; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00A; arA23[ 'hb] = 'h299; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E2; arA23[ 'hb] = 'h299; end + 9: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 10: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 11: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h100; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h06B; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h006; arA23[ 'hb] = 'h299; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h21C; arA23[ 'hb] = 'h299; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h103; arA23[ 'hb] = 'h299; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C2; arA23[ 'hb] = 'h299; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E3; arA23[ 'hb] = 'h299; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00A; arA23[ 'hb] = 'h299; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E2; arA23[ 'hb] = 'h299; end + 9: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 10: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 11: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h10C; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h06F; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00B; arA23[ 'hb] = 'h29D; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00F; arA23[ 'hb] = 'h29D; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h179; arA23[ 'hb] = 'h29D; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C6; arA23[ 'hb] = 'h29D; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E7; arA23[ 'hb] = 'h29D; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00E; arA23[ 'hb] = 'h29D; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E6; arA23[ 'hb] = 'h29D; end + 9: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 10: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + 11: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D5; arA23[ 'hb] = 'X; end + 1: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1D5; arA23[ 'hb] = 'X; end + 2: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00B; arA23[ 'hb] = 'h1D7; end + 3: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00F; arA23[ 'hb] = 'h1D7; end + 4: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h179; arA23[ 'hb] = 'h1D7; end + 5: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C6; arA23[ 'hb] = 'h1D7; end + 6: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E7; arA23[ 'hb] = 'h1D7; end + 7: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h00E; arA23[ 'hb] = 'h1D7; end + 8: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E6; arA23[ 'hb] = 'h1D7; end + 9: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1C6; arA23[ 'hb] = 'h1D7; end + 10: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h1E7; arA23[ 'hb] = 'h1D7; end + 11: begin arIll[ 'hb] = 1'b0; arA1[ 'hb] = 'h0A7; arA23[ 'hb] = 'h1D5; end + default: begin arIll[ 'hb] = 1'b1; arA1[ 'hb] = 'X ; arA23[ 'hb] = 'X; end + endcase +endcase + +// +// Line: C +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C1; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h1C3; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h1C3; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h1C3; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h1C3; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h1C3; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h1C3; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h1C3; end + 9: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h1C3; end + 10: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h1C3; end + 11: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h0EA; arA23[ 'hc] = 'h1C1; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C1; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h1C3; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h1C3; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h1C3; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h1C3; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h1C3; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h1C3; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h1C3; end + 9: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h1C3; end + 10: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h1C3; end + 11: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h0EA; arA23[ 'hc] = 'h1C1; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C5; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00B; arA23[ 'hc] = 'h1CB; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00F; arA23[ 'hc] = 'h1CB; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h179; arA23[ 'hc] = 'h1CB; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C6; arA23[ 'hc] = 'h1CB; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E7; arA23[ 'hc] = 'h1CB; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00E; arA23[ 'hc] = 'h1CB; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E6; arA23[ 'hc] = 'h1CB; end + 9: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C6; arA23[ 'hc] = 'h1CB; end + 10: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E7; arA23[ 'hc] = 'h1CB; end + 11: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h0A7; arA23[ 'hc] = 'h1C5; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h15B; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h15A; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h15A; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h15A; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h15A; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h15A; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h15A; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h15A; end + 9: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h15A; end + 10: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h15A; end + 11: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h0EA; arA23[ 'hc] = 'h15B; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1CD; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h107; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h299; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h299; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h299; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h299; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h299; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h299; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h299; end + 9: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 10: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 11: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h3E3; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h3E3; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h299; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h299; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h299; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h299; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h299; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h299; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h299; end + 9: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 10: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 11: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h3E3; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00B; arA23[ 'hc] = 'h29D; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00F; arA23[ 'hc] = 'h29D; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h179; arA23[ 'hc] = 'h29D; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C6; arA23[ 'hc] = 'h29D; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E7; arA23[ 'hc] = 'h29D; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00E; arA23[ 'hc] = 'h29D; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E6; arA23[ 'hc] = 'h29D; end + 9: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 10: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 11: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h15B; arA23[ 'hc] = 'X; end + 1: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + 2: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h006; arA23[ 'hc] = 'h15A; end + 3: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h21C; arA23[ 'hc] = 'h15A; end + 4: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h103; arA23[ 'hc] = 'h15A; end + 5: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h15A; end + 6: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h15A; end + 7: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h00A; arA23[ 'hc] = 'h15A; end + 8: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E2; arA23[ 'hc] = 'h15A; end + 9: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1C2; arA23[ 'hc] = 'h15A; end + 10: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h1E3; arA23[ 'hc] = 'h15A; end + 11: begin arIll[ 'hc] = 1'b0; arA1[ 'hc] = 'h0EA; arA23[ 'hc] = 'h15B; end + default: begin arIll[ 'hc] = 1'b1; arA1[ 'hc] = 'X ; arA23[ 'hc] = 'X; end + endcase +endcase + +// +// Line: D +// +unique case( row86) + +3'b000: // Row: 0 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C1; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h006; arA23[ 'hd] = 'h1C3; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h21C; arA23[ 'hd] = 'h1C3; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h103; arA23[ 'hd] = 'h1C3; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C3; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C3; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00A; arA23[ 'hd] = 'h1C3; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E2; arA23[ 'hd] = 'h1C3; end + 9: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C3; end + 10: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C3; end + 11: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h0EA; arA23[ 'hd] = 'h1C1; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b001: // Row: 1 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C1; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C1; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h006; arA23[ 'hd] = 'h1C3; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h21C; arA23[ 'hd] = 'h1C3; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h103; arA23[ 'hd] = 'h1C3; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C3; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C3; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00A; arA23[ 'hd] = 'h1C3; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E2; arA23[ 'hd] = 'h1C3; end + 9: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C3; end + 10: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C3; end + 11: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h0EA; arA23[ 'hd] = 'h1C1; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b010: // Row: 2 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C5; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C5; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00B; arA23[ 'hd] = 'h1CB; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00F; arA23[ 'hd] = 'h1CB; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h179; arA23[ 'hd] = 'h1CB; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C6; arA23[ 'hd] = 'h1CB; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E7; arA23[ 'hd] = 'h1CB; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00E; arA23[ 'hd] = 'h1CB; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E6; arA23[ 'hd] = 'h1CB; end + 9: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C6; arA23[ 'hd] = 'h1CB; end + 10: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E7; arA23[ 'hd] = 'h1CB; end + 11: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h0A7; arA23[ 'hd] = 'h1C5; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b011: // Row: 3 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C9; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C9; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h006; arA23[ 'hd] = 'h1C7; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h21C; arA23[ 'hd] = 'h1C7; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h103; arA23[ 'hd] = 'h1C7; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C7; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C7; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00A; arA23[ 'hd] = 'h1C7; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E2; arA23[ 'hd] = 'h1C7; end + 9: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h1C7; end + 10: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h1C7; end + 11: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h0EA; arA23[ 'hd] = 'h1C9; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b100: // Row: 4 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C1; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h10F; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h006; arA23[ 'hd] = 'h299; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h21C; arA23[ 'hd] = 'h299; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h103; arA23[ 'hd] = 'h299; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h299; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h299; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00A; arA23[ 'hd] = 'h299; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E2; arA23[ 'hd] = 'h299; end + 9: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 10: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 11: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b101: // Row: 5 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C1; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h10F; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h006; arA23[ 'hd] = 'h299; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h21C; arA23[ 'hd] = 'h299; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h103; arA23[ 'hd] = 'h299; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C2; arA23[ 'hd] = 'h299; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E3; arA23[ 'hd] = 'h299; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00A; arA23[ 'hd] = 'h299; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E2; arA23[ 'hd] = 'h299; end + 9: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 10: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 11: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b110: // Row: 6 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C5; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h10B; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00B; arA23[ 'hd] = 'h29D; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00F; arA23[ 'hd] = 'h29D; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h179; arA23[ 'hd] = 'h29D; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C6; arA23[ 'hd] = 'h29D; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E7; arA23[ 'hd] = 'h29D; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00E; arA23[ 'hd] = 'h29D; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E6; arA23[ 'hd] = 'h29D; end + 9: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 10: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + 11: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase + +3'b111: // Row: 7 + unique case ( col) + 0: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C5; arA23[ 'hd] = 'X; end + 1: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C5; arA23[ 'hd] = 'X; end + 2: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00B; arA23[ 'hd] = 'h1CB; end + 3: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00F; arA23[ 'hd] = 'h1CB; end + 4: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h179; arA23[ 'hd] = 'h1CB; end + 5: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C6; arA23[ 'hd] = 'h1CB; end + 6: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E7; arA23[ 'hd] = 'h1CB; end + 7: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h00E; arA23[ 'hd] = 'h1CB; end + 8: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E6; arA23[ 'hd] = 'h1CB; end + 9: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1C6; arA23[ 'hd] = 'h1CB; end + 10: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h1E7; arA23[ 'hd] = 'h1CB; end + 11: begin arIll[ 'hd] = 1'b0; arA1[ 'hd] = 'h0A7; arA23[ 'hd] = 'h1C5; end + default: begin arIll[ 'hd] = 1'b1; arA1[ 'hd] = 'X ; arA23[ 'hd] = 'X; end + endcase +endcase +end + + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80.vhd new file mode 100644 index 0000000000000000000000000000000000000000..c081f108236c0da105282d255cdee221a13d7ab2 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80.vhd @@ -0,0 +1,1346 @@ +-------------------------------------------------------------------------------- +-- **** +-- T80(c) core. Attempt to finish all undocumented features and provide +-- accurate timings. +-- Version 350. +-- Copyright (c) 2018 Sorgelig +-- Test passed: ZEXDOC, ZEXALL, Z80Full(*), Z80memptr +-- (*) Currently only SCF and CCF instructions aren't passed X/Y flags check as +-- correct implementation is still unclear. +-- +-- **** +-- T80(b) core. In an effort to merge and maintain bug fixes .... +-- +-- Ver 303 add undocumented DDCB and FDCB opcodes by TobiFlex 20.04.2010 +-- Ver 301 parity flag is just parity for 8080, also overflow for Z80, by Sean Riddle +-- Ver 300 started tidyup. +-- +-- MikeJ March 2005 +-- Latest version from www.fpgaarcade.com (original www.opencores.org) +-- +-- **** +-- Z80 compatible microprocessor core +-- +-- Version : 0250 +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- Limitations : +-- +-- File history : +-- +-- 0208 : First complete release +-- 0210 : Fixed wait and halt +-- 0211 : Fixed Refresh addition and IM 1 +-- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test +-- 0232 : Removed refresh address output for Mode > 1 and added DJNZ M1_n fix by Mike Johnson +-- 0235 : Added clock enable and IM 2 fix by Mike Johnson +-- 0237 : Changed 8080 I/O address output, added IntE output +-- 0238 : Fixed (IX/IY+d) timing and 16 bit ADC and SBC zero flag +-- 0240 : Added interrupt ack fix by Mike Johnson, changed (IX/IY+d) timing and changed flags in GB mode +-- 0242 : Added I/O wait, fixed refresh address, moved some registers to RAM +-- 0247 : Fixed bus req/ack cycle +-- 0250 : Added R800 Multiplier by TobiFlex 2017.10.15 +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; +use IEEE.STD_LOGIC_UNSIGNED.all; +use work.T80_Pack.all; + +entity T80 is + generic( + Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB + IOWait : integer := 0; -- 0 => Single cycle I/O, 1 => Std I/O cycle + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + RESET_n : in std_logic; + CLK_n : in std_logic; + CEN : in std_logic; + WAIT_n : in std_logic; + INT_n : in std_logic; + NMI_n : in std_logic; + BUSRQ_n : in std_logic; + M1_n : out std_logic; + IORQ : out std_logic; + NoRead : out std_logic; + Write : out std_logic; + RFSH_n : out std_logic; + HALT_n : out std_logic; + BUSAK_n : out std_logic; + A : out std_logic_vector(15 downto 0); + DInst : in std_logic_vector(7 downto 0); + DI : in std_logic_vector(7 downto 0); + DO : out std_logic_vector(7 downto 0); + MC : out std_logic_vector(2 downto 0); + TS : out std_logic_vector(2 downto 0); + IntCycle_n : out std_logic; + IntE : out std_logic; + Stop : out std_logic; + R800_mode : in std_logic := '0'; + out0 : in std_logic := '0'; -- 0 => OUT(C),0, 1 => OUT(C),255 + REG : out std_logic_vector(211 downto 0); -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + + DIRSet : in std_logic := '0'; + DIR : in std_logic_vector(211 downto 0) := (others => '0') -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + ); +end T80; + +architecture rtl of T80 is + + -- Registers + signal ACC, F : std_logic_vector(7 downto 0); + signal Ap, Fp : std_logic_vector(7 downto 0); + signal I : std_logic_vector(7 downto 0); + signal R : unsigned(7 downto 0); + signal SP, PC : unsigned(15 downto 0); + + signal RegDIH : std_logic_vector(7 downto 0); + signal RegDIL : std_logic_vector(7 downto 0); + signal RegBusA : std_logic_vector(15 downto 0); + signal RegBusB : std_logic_vector(15 downto 0); + signal RegBusC : std_logic_vector(15 downto 0); + signal RegAddrA_r : std_logic_vector(2 downto 0); + signal RegAddrA : std_logic_vector(2 downto 0); + signal RegAddrB_r : std_logic_vector(2 downto 0); + signal RegAddrB : std_logic_vector(2 downto 0); + signal RegAddrC : std_logic_vector(2 downto 0); + signal RegWEH : std_logic; + signal RegWEL : std_logic; + signal Alternate : std_logic; + + -- Help Registers + signal WZ : std_logic_vector(15 downto 0); -- MEMPTR register + signal TmpAddr2 : std_logic_vector(15 downto 0); -- Temporary address register + signal IR : std_logic_vector(7 downto 0); -- Instruction register + signal ISet : std_logic_vector(1 downto 0); -- Instruction set selector + signal RegBusA_r : std_logic_vector(15 downto 0); + signal MULU_Prod32 : std_logic_vector(31 downto 0); + signal MULU_tmp : std_logic_vector(31 downto 0); + signal MULU_Fakt1 : std_logic_vector(15 downto 0); + + signal ID16 : signed(15 downto 0); + signal Save_Mux : std_logic_vector(7 downto 0); + + signal TState : unsigned(2 downto 0); + signal MCycle : std_logic_vector(2 downto 0); + signal IntE_FF1 : std_logic; + signal IntE_FF2 : std_logic; + signal Halt_FF : std_logic; + signal BusReq_s : std_logic := '0'; + signal BusAck : std_logic := '0'; + signal ClkEn : std_logic; + signal NMI_s : std_logic; + signal IStatus : std_logic_vector(1 downto 0); + + signal DI_Reg : std_logic_vector(7 downto 0); + signal T_Res : std_logic; + signal XY_State : std_logic_vector(1 downto 0); + signal Pre_XY_F_M : std_logic_vector(2 downto 0); + signal NextIs_XY_Fetch : std_logic; + signal XY_Ind : std_logic; + signal No_BTR : std_logic; + signal BTR_r : std_logic; + signal Auto_Wait : std_logic; + signal Auto_Wait_t1 : std_logic; + signal Auto_Wait_t2 : std_logic; + signal IncDecZ : std_logic; + + -- ALU signals + signal BusB : std_logic_vector(7 downto 0); + signal BusA : std_logic_vector(7 downto 0); + signal ALU_Q : std_logic_vector(7 downto 0); + signal F_Out : std_logic_vector(7 downto 0); + + -- Registered micro code outputs + signal Read_To_Reg_r : std_logic_vector(4 downto 0); + signal Arith16_r : std_logic; + signal Z16_r : std_logic; + signal ALU_Op_r : std_logic_vector(3 downto 0); + signal Save_ALU_r : std_logic; + signal PreserveC_r : std_logic; + signal MCycles : std_logic_vector(2 downto 0); + + -- Micro code outputs + signal MCycles_d : std_logic_vector(2 downto 0); + signal TStates : std_logic_vector(2 downto 0); + signal IntCycle : std_logic; + signal NMICycle : std_logic; + signal Inc_PC : std_logic; + signal Inc_WZ : std_logic; + signal IncDec_16 : std_logic_vector(3 downto 0); + signal Prefix : std_logic_vector(1 downto 0); + signal Read_To_Acc : std_logic; + signal Read_To_Reg : std_logic; + signal Set_BusB_To : std_logic_vector(3 downto 0); + signal Set_BusA_To : std_logic_vector(3 downto 0); + signal ALU_Op : std_logic_vector(3 downto 0); + signal Save_ALU : std_logic; + signal Rot_Akku : std_logic; + signal PreserveC : std_logic; + signal Arith16 : std_logic; + signal Set_Addr_To : std_logic_vector(2 downto 0); + signal Jump : std_logic; + signal JumpE : std_logic; + signal JumpXY : std_logic; + signal Call : std_logic; + signal RstP : std_logic; + signal LDZ : std_logic; + signal LDW : std_logic; + signal LDSPHL : std_logic; + signal LDHLSP : std_logic; + signal ADDSPdd : std_logic; + signal IORQ_i : std_logic; + signal Write_i : std_logic; + signal NoRead_i : std_logic; + signal Special_LD : std_logic_vector(2 downto 0); + signal ExchangeDH : std_logic; + signal ExchangeRp : std_logic; + signal ExchangeAF : std_logic; + signal ExchangeRS : std_logic; + signal ExchangeWH : std_logic; + signal I_DJNZ : std_logic; + signal I_CPL : std_logic; + signal I_CCF : std_logic; + signal I_SCF : std_logic; + signal I_RETN : std_logic; + signal I_BT : std_logic; + signal I_BC : std_logic; + signal I_BTR : std_logic; + signal I_RLD : std_logic; + signal I_RRD : std_logic; + signal I_RXDD : std_logic; + signal I_INRC : std_logic; + signal I_MULUB : std_logic; + signal I_MULU : std_logic; + signal SetWZ : std_logic_vector(1 downto 0); + signal SetDI : std_logic; + signal SetEI : std_logic; + signal IMode : std_logic_vector(1 downto 0); + signal Halt : std_logic; + signal XYbit_undoc : std_logic; + signal No_PC : std_logic; + signal DOR : std_logic_vector(127 downto 0); + + signal Really_Wait : std_logic; + +begin + + REG <= IntE_FF2 & IntE_FF1 & IStatus & DOR & std_logic_vector(PC) & std_logic_vector(SP) & std_logic_vector(R) & I & Fp & Ap & F & ACC when Alternate = '0' + else IntE_FF2 & IntE_FF1 & IStatus & DOR(127 downto 112) & DOR(47 downto 0) & DOR(63 downto 48) & DOR(111 downto 64) & + std_logic_vector(PC) & std_logic_vector(SP) & std_logic_vector(R) & I & Fp & Ap & F & ACC; + + mcode : T80_MCode + generic map( + Mode => Mode, + Flag_C => Flag_C, + Flag_N => Flag_N, + Flag_P => Flag_P, + Flag_X => Flag_X, + Flag_H => Flag_H, + Flag_Y => Flag_Y, + Flag_Z => Flag_Z, + Flag_S => Flag_S) + port map( + IR => IR, + ISet => ISet, + MCycle => MCycle, + F => F, + NMICycle => NMICycle, + IntCycle => IntCycle, + XY_State => XY_State, + MCycles => MCycles_d, + TStates => TStates, + Prefix => Prefix, + Inc_PC => Inc_PC, + Inc_WZ => Inc_WZ, + IncDec_16 => IncDec_16, + Read_To_Acc => Read_To_Acc, + Read_To_Reg => Read_To_Reg, + Set_BusB_To => Set_BusB_To, + Set_BusA_To => Set_BusA_To, + ALU_Op => ALU_Op, + Save_ALU => Save_ALU, + Rot_Akku => Rot_Akku, + PreserveC => PreserveC, + Arith16 => Arith16, + Set_Addr_To => Set_Addr_To, + IORQ => IORQ_i, + Jump => Jump, + JumpE => JumpE, + JumpXY => JumpXY, + Call => Call, + RstP => RstP, + LDZ => LDZ, + LDW => LDW, + LDSPHL => LDSPHL, + LDHLSP => LDHLSP, + ADDSPdd => ADDSPdd, + Special_LD => Special_LD, + ExchangeDH => ExchangeDH, + ExchangeRp => ExchangeRp, + ExchangeAF => ExchangeAF, + ExchangeRS => ExchangeRS, + ExchangeWH => ExchangeWH, + I_DJNZ => I_DJNZ, + I_CPL => I_CPL, + I_CCF => I_CCF, + I_SCF => I_SCF, + I_RETN => I_RETN, + I_BT => I_BT, + I_BC => I_BC, + I_BTR => I_BTR, + I_RLD => I_RLD, + I_RRD => I_RRD, + I_INRC => I_INRC, + I_MULUB => I_MULUB, + I_MULU => I_MULU, + SetWZ => SetWZ, + SetDI => SetDI, + SetEI => SetEI, + IMode => IMode, + Halt => Halt, + NoRead => NoRead_i, + Write => Write_i, + R800_mode => R800_mode, + No_PC => No_PC, + XYbit_undoc => XYbit_undoc); + + alu : T80_ALU + generic map( + Mode => Mode, + Flag_C => Flag_C, + Flag_N => Flag_N, + Flag_P => Flag_P, + Flag_X => Flag_X, + Flag_H => Flag_H, + Flag_Y => Flag_Y, + Flag_Z => Flag_Z, + Flag_S => Flag_S) + port map( + Arith16 => Arith16_r, + Z16 => Z16_r, + WZ => WZ, + XY_State=> XY_State, + ALU_Op => ALU_Op_r, + Rot_Akku => Rot_Akku, + IR => IR(5 downto 0), + ISet => ISet, + BusA => BusA, + BusB => BusB, + F_In => F, + Q => ALU_Q, + F_Out => F_Out); + + Really_Wait <= not Wait_n and (Write_i or not NoRead_i); + + ClkEn <= CEN and not BusAck; + + T_Res <= '1' when TState = unsigned(TStates) else '0'; + + NextIs_XY_Fetch <= '1' when XY_State /= "00" and XY_Ind = '0' and + ((Set_Addr_To = aXY) or + (MCycle = "001" and IR = "11001011") or + (MCycle = "001" and IR = "00110110")) else '0'; + + Save_Mux <= BusB when ExchangeRp = '1' else + DI_Reg when Save_ALU_r = '0' else + ALU_Q; + + process (RESET_n, CLK_n) + variable n : std_logic_vector(7 downto 0); + variable ioq : std_logic_vector(8 downto 0); + variable temp_c : unsigned(8 downto 0); + variable temp_h : unsigned(4 downto 0); + begin + if RESET_n = '0' then + PC <= (others => '0'); -- Program Counter + A <= (others => '0'); + WZ <= (others => '0'); + IR <= "00000000"; + ISet <= "00"; + XY_State <= "00"; + IStatus <= "00"; + MCycles <= "000"; + DO <= "00000000"; + + ACC <= (others => '1'); + F <= (others => '1'); + if Mode = 3 then + ACC <= (others => '0'); + F <= "11110000"; + end if; + + Ap <= (others => '1'); + Fp <= (others => '1'); + I <= (others => '0'); + R <= (others => '0'); + SP <= (others => '1'); + Alternate <= '0'; + + Read_To_Reg_r <= "00000"; + Arith16_r <= '0'; + BTR_r <= '0'; + Z16_r <= '0'; + ALU_Op_r <= "0000"; + Save_ALU_r <= '0'; + PreserveC_r <= '0'; + XY_Ind <= '0'; + I_RXDD <= '0'; + + elsif rising_edge(CLK_n) then + + if DIRSet = '1' then + ACC <= DIR( 7 downto 0); + F <= DIR(15 downto 8); + Ap <= DIR(23 downto 16); + Fp <= DIR(31 downto 24); + I <= DIR(39 downto 32); + R <= unsigned(DIR(47 downto 40)); + SP <= unsigned(DIR(63 downto 48)); + PC <= unsigned(DIR(79 downto 64)); + A <= DIR(79 downto 64); + IStatus <= DIR(209 downto 208); + + elsif ClkEn = '1' then + ALU_Op_r <= "0000"; + Save_ALU_r <= '0'; + Read_To_Reg_r <= "00000"; + + MCycles <= MCycles_d; + + if LDHLSP = '1' and MCycle = "011" and TState = 1 then + temp_c := unsigned('0'&SP(7 downto 0))+unsigned('0'&Save_Mux); + temp_h := unsigned('0'&SP(3 downto 0))+unsigned('0'&Save_Mux(3 downto 0)); + F(Flag_Z) <= '0'; + F(Flag_N) <= '0'; + F(Flag_H) <= temp_h(4); + F(Flag_C) <= temp_c(8); + end if; + + if ADDSPdd = '1' and TState = 1 then + temp_c := unsigned('0'&SP(7 downto 0))+unsigned('0'&Save_Mux); + temp_h := unsigned('0'&SP(3 downto 0))+unsigned('0'&Save_Mux(3 downto 0)); + F(Flag_Z) <= '0'; + F(Flag_N) <= '0'; + F(Flag_H) <= temp_h(4); + F(Flag_C) <= temp_c(8); + end if; + + if Mode = 3 then + IStatus <= "10"; + elsif IMode /= "11" then + IStatus <= IMode; + end if; + + Arith16_r <= Arith16; + PreserveC_r <= PreserveC; + if ISet = "10" and ALU_OP(2) = '0' and ALU_OP(0) = '1' and MCycle = "011" then + Z16_r <= '1'; + else + Z16_r <= '0'; + end if; + + if MCycle = "001" and TState(2) = '0' then + -- MCycle = 1 and TState = 1, 2, or 3 + + if TState = 2 and Wait_n = '1' then + if Mode < 2 then + A(7 downto 0) <= std_logic_vector(R); + A(15 downto 8) <= I; + R(6 downto 0) <= R(6 downto 0) + 1; + end if; + + if Jump = '0' and Call = '0' and NMICycle = '0' and IntCycle = '0' and not (Halt_FF = '1' or Halt = '1') then + PC <= PC + 1; + end if; + + if IntCycle = '1' and IStatus = "01" then + IR <= "11111111"; + elsif Halt_FF = '1' or (IntCycle = '1' and IStatus = "10") or NMICycle = '1' then + IR <= "00000000"; + else + IR <= DInst; + end if; + + if Mode <= 1 and IntCycle = '1' and IStatus = "10" then + -- IM2 vector address low byte from bus + WZ(7 downto 0) <= DInst; + end if; + + ISet <= "00"; + if Prefix /= "00" then + if Prefix = "11" then + if IR(5) = '1' then + XY_State <= "10"; + else + XY_State <= "01"; + end if; + else + if Prefix = "10" then + XY_State <= "00"; + XY_Ind <= '0'; + end if; + ISet <= Prefix; + end if; + else + XY_State <= "00"; + XY_Ind <= '0'; + end if; + end if; + + else + -- either (MCycle > 1) OR (MCycle = 1 AND TState > 3) + + if MCycle = "110" then + XY_Ind <= '1'; + if Prefix = "01" then + ISet <= "01"; + end if; + end if; + + if T_Res = '1' then + BTR_r <= (I_BT or I_BC or I_BTR) and not No_BTR; + if Jump = '1' then + A(15 downto 8) <= DI_Reg; + A(7 downto 0) <= WZ(7 downto 0); + PC(15 downto 8) <= unsigned(DI_Reg); + PC(7 downto 0) <= unsigned(WZ(7 downto 0)); + elsif JumpXY = '1' then + A <= RegBusC; + PC <= unsigned(RegBusC); + elsif Call = '1' or RstP = '1' then + A <= WZ; + PC <= unsigned(WZ); + elsif MCycle = MCycles and NMICycle = '1' then + A <= "0000000001100110"; + PC <= "0000000001100110"; + elsif ((Mode /= 3 and MCycle = "011") or (Mode = 3 and MCycle = "100")) + and IntCycle = '1' and IStatus = "10" then + A(15 downto 8) <= I; + A(7 downto 0) <= WZ(7 downto 0); + PC(15 downto 8) <= unsigned(I); + PC(7 downto 0) <= unsigned(WZ(7 downto 0)); + else + case Set_Addr_To is + when aXY => + if XY_State = "00" then + A <= RegBusC; + else + if NextIs_XY_Fetch = '1' then + A <= std_logic_vector(PC); + else + A <= WZ; + end if; + end if; + when aIOA => + if Mode = 3 then + -- Memory map I/O on GBZ80 + A(15 downto 8) <= (others => '1'); + elsif Mode = 2 then + -- Duplicate I/O address on 8080 + A(15 downto 8) <= DI_Reg; + else + A(15 downto 8) <= ACC; + end if; + A(7 downto 0) <= DI_Reg; + WZ <= (ACC & DI_Reg) + "1"; + when aSP => + A <= std_logic_vector(SP); + when aBC => + if Mode = 3 and IORQ_i = '1' then + -- Memory map I/O on GBZ80 + A(15 downto 8) <= (others => '1'); + A(7 downto 0) <= RegBusC(7 downto 0); + else + A <= RegBusC; + if SetWZ = "01" then + WZ <= RegBusC + "1"; + end if; + if SetWZ = "10" then + WZ(7 downto 0) <= RegBusC(7 downto 0) + "1"; + WZ(15 downto 8) <= ACC; + end if; + end if; + when aDE => + A <= RegBusC; + if SetWZ = "10" then + WZ(7 downto 0) <= RegBusC(7 downto 0) + "1"; + WZ(15 downto 8) <= ACC; + end if; + when aZI => + if Inc_WZ = '1' then + A <= std_logic_vector(unsigned(WZ) + 1); + else + A(15 downto 8) <= DI_Reg; + A(7 downto 0) <= WZ(7 downto 0); + if SetWZ = "10" then + WZ(7 downto 0) <= WZ(7 downto 0) + "1"; + WZ(15 downto 8) <= ACC; + end if; + end if; + when others => + if ISet = "10" and IR(7 downto 4) = x"B" and IR(2 downto 1) = "01" and MCycle = 3 and No_BTR = '0' then + -- INIR, INDR, OTIR, OTDR + A <= RegBusA_r; + elsif No_PC = '0' or No_BTR = '1' or (I_DJNZ = '1' and IncDecZ = '1') or Mode > 1 then + A <= std_logic_vector(PC); + end if; + end case; + end if; + + if SetWZ = "11" then + WZ <= std_logic_vector(ID16); + end if; + + Save_ALU_r <= Save_ALU; + ALU_Op_r <= ALU_Op; + + if Mode = 3 then + if I_CPL = '1' then + -- CPL + ACC <= not ACC; + F(Flag_H) <= '1'; + F(Flag_N) <= '1'; + end if; + if I_CCF = '1' then + -- CCF + F(Flag_C) <= not F(Flag_C); + F(Flag_H) <= '0'; + F(Flag_N) <= '0'; + end if; + if I_SCF = '1' then + -- SCF + F(Flag_C) <= '1'; + F(Flag_H) <= '0'; + F(Flag_N) <= '0'; + end if; + else + if I_CPL = '1' then + -- CPL + ACC <= not ACC; + F(Flag_Y) <= not ACC(5); + F(Flag_H) <= '1'; + F(Flag_X) <= not ACC(3); + F(Flag_N) <= '1'; + end if; + if I_CCF = '1' then + -- CCF + F(Flag_C) <= not F(Flag_C); + F(Flag_Y) <= ACC(5); + F(Flag_H) <= F(Flag_C); + F(Flag_X) <= ACC(3); + F(Flag_N) <= '0'; + end if; + if I_SCF = '1' then + -- SCF + F(Flag_C) <= '1'; + F(Flag_Y) <= ACC(5); + F(Flag_H) <= '0'; + F(Flag_X) <= ACC(3); + F(Flag_N) <= '0'; + end if; + end if; + end if; + + if (TState = 2 and Really_Wait = '0' and I_BTR = '1' and IR(0) = '1') or (TState = 1 and I_BTR = '1' and IR(0) = '0') then + ioq := ('0' & DI_Reg) + ('0' & std_logic_vector(ID16(7 downto 0))); + F(Flag_N) <= DI_Reg(7); + F(Flag_C) <= ioq(8); + F(Flag_H) <= ioq(8); + ioq := (ioq and "000000111") xor ('0'&BusA); + F(Flag_P) <= not (ioq(0) xor ioq(1) xor ioq(2) xor ioq(3) xor ioq(4) xor ioq(5) xor ioq(6) xor ioq(7)); + end if; + + if TState = 2 and Really_Wait = '0' then + if ISet = "01" and MCycle = "111" then + IR <= DInst; + end if; + if JumpE = '1' then + PC <= unsigned(signed(PC) + signed(DI_Reg)); + WZ <= std_logic_vector(signed(PC) + signed(DI_Reg)); + elsif Inc_PC = '1' then + PC <= PC + 1; + end if; + if BTR_r = '1' then + PC <= PC - 2; + end if; + if RstP = '1' then + WZ <= (others =>'0'); + WZ(5 downto 3) <= IR(5 downto 3); + end if; + end if; + if TState = 3 and MCycle = "110" then + WZ <= std_logic_vector(signed(RegBusC) + signed(DI_Reg)); + end if; + + if MCycle = "011" and TState = 4 and No_BTR = '0' then + if I_BT = '1' or I_BC = '1' then + WZ <= std_logic_vector(PC)-"1"; + end if; + end if; + + if (TState = 2 and Really_Wait = '0') or (TState = 4 and MCycle = "001") then + if IncDec_16(2 downto 0) = "111" then + if IncDec_16(3) = '1' then + SP <= SP - 1; + else + SP <= SP + 1; + end if; + end if; + end if; + + if ADDSPdd = '1' and TState = 2 then + WZ <= std_logic_vector(SP); + SP <= unsigned(signed(SP)+signed(Save_Mux)); + end if; + + if LDSPHL = '1' then + SP <= unsigned(RegBusC); + end if; + if ExchangeAF = '1' then + Ap <= ACC; + ACC <= Ap; + Fp <= F; + F <= Fp; + end if; + if ExchangeRS = '1' then + Alternate <= not Alternate; + end if; + end if; + + if TState = 3 then + if LDZ = '1' then + WZ(7 downto 0) <= DI_Reg; + end if; + if LDW = '1' then + WZ(15 downto 8) <= DI_Reg; + end if; + + if Special_LD(2) = '1' then + case Special_LD(1 downto 0) is + when "00" => + ACC <= I; + F(Flag_P) <= IntE_FF2; + F(Flag_S) <= I(7); + + if I = x"00" then + F(Flag_Z) <= '1'; + else + F(Flag_Z) <= '0'; + end if; + + F(Flag_Y) <= I(5); + F(Flag_H) <= '0'; + F(Flag_X) <= I(3); + F(Flag_N) <= '0'; + + + when "01" => + ACC <= std_logic_vector(R); + F(Flag_P) <= IntE_FF2; + F(Flag_S) <= R(7); + + if R = x"00" then + F(Flag_Z) <= '1'; + else + F(Flag_Z) <= '0'; + end if; + + F(Flag_Y) <= R(5); + F(Flag_H) <= '0'; + F(Flag_X) <= R(3); + F(Flag_N) <= '0'; + + when "10" => + I <= ACC; + when others => + R <= unsigned(ACC); + end case; + end if; + end if; + + if (I_DJNZ = '0' and Save_ALU_r = '1') or ALU_Op_r = "1001" then + if Mode = 3 then + F(6) <= F_Out(6); + F(5) <= F_Out(5); + F(7) <= F_Out(7); + if PreserveC_r = '0' then + F(4) <= F_Out(4); + end if; + else + F(7 downto 1) <= F_Out(7 downto 1); + if PreserveC_r = '0' then + F(Flag_C) <= F_Out(0); + end if; + end if; + end if; + if T_Res = '1' and I_INRC = '1' then + F(Flag_H) <= '0'; + F(Flag_N) <= '0'; + F(Flag_X) <= DI_Reg(3); + F(Flag_Y) <= DI_Reg(5); + if DI_Reg(7 downto 0) = "00000000" then + F(Flag_Z) <= '1'; + else + F(Flag_Z) <= '0'; + end if; + F(Flag_S) <= DI_Reg(7); + F(Flag_P) <= not (DI_Reg(0) xor DI_Reg(1) xor DI_Reg(2) xor DI_Reg(3) xor + DI_Reg(4) xor DI_Reg(5) xor DI_Reg(6) xor DI_Reg(7)); + end if; + + if TState = 1 and Auto_Wait_t1 = '0' then + -- Keep D0 from M3 for RLD/RRD (Sorgelig) + I_RXDD <= I_RLD or I_RRD; + if I_RXDD='0' then + DO <= BusB; + end if; + if I_RLD = '1' then + DO(3 downto 0) <= BusA(3 downto 0); + DO(7 downto 4) <= BusB(3 downto 0); + end if; + if I_RRD = '1' then + DO(3 downto 0) <= BusB(7 downto 4); + DO(7 downto 4) <= BusA(3 downto 0); + end if; + end if; + + if T_Res = '1' then + Read_To_Reg_r(3 downto 0) <= Set_BusA_To; + Read_To_Reg_r(4) <= Read_To_Reg; + if Read_To_Acc = '1' then + Read_To_Reg_r(3 downto 0) <= "0111"; + Read_To_Reg_r(4) <= '1'; + end if; + end if; + + if TState = 1 and I_BT = '1' then + F(Flag_X) <= ALU_Q(3); + F(Flag_Y) <= ALU_Q(1); + F(Flag_H) <= '0'; + F(Flag_N) <= '0'; + end if; + if TState = 1 and I_BC = '1' then + n := ALU_Q - ("0000000" & F_Out(Flag_H)); + F(Flag_X) <= n(3); + F(Flag_Y) <= n(1); + end if; + if I_BC = '1' or I_BT = '1' then + F(Flag_P) <= IncDecZ; + end if; + + if (TState = 1 and Save_ALU_r = '0' and Auto_Wait_t1 = '0') or + (Save_ALU_r = '1' and ALU_OP_r /= "0111") then + case Read_To_Reg_r is + when "10111" => + ACC <= Save_Mux; + when "10110" => + DO <= Save_Mux; + when "11000" => + SP(7 downto 0) <= unsigned(Save_Mux); + when "11001" => + SP(15 downto 8) <= unsigned(Save_Mux); + when "11011" => + if Mode = 3 then + F(7 downto 4) <= Save_Mux(7 downto 4); + F(3 downto 0) <= "0000"; -- bit 3 to 0 always return 0 + else + F <= Save_Mux; + end if; + when others => + end case; + if XYbit_undoc='1' then + DO <= ALU_Q; + end if; + end if; + end if; + end if; + end process; + +--------------------------------------------------------------------------- +-- +-- Multiply +-- +--------------------------------------------------------------------------- + process (CLK_n, ACC, RegBusB, MULU_tmp, MULU_Fakt1, MULU_Prod32) + begin + + MULU_tmp(31 downto 12) <= std_logic_vector((unsigned(MULU_Fakt1)*unsigned(MULU_Prod32(3 downto 0)))+unsigned("0000"&MULU_Prod32(31 downto 16))); + MULU_tmp(11 downto 0) <= MULU_Prod32(15 downto 4); + + if rising_edge(CLK_n) then + if ClkEn = '1' then + if T_Res='1' then + if I_MULUB='1' then + MULU_Prod32(7 downto 0) <= ACC; + MULU_Prod32(15 downto 8) <= "--------"; + MULU_Prod32(31 downto 16) <= X"0000"; + MULU_Fakt1(7 downto 0) <= "00000000"; + if Set_BusB_To(0) = '1' then + MULU_Fakt1(15 downto 8) <= RegBusB(7 downto 0); + else + MULU_Fakt1(15 downto 8) <= RegBusB(15 downto 8); + end if; + else + MULU_Prod32(15 downto 0) <= RegBusA; + MULU_Prod32(31 downto 16) <= X"0000"; + MULU_Fakt1 <= RegBusB; + end if; + else + MULU_Prod32 <= MULU_tmp; + end if; + end if; + end if; + end process; + +--------------------------------------------------------------------------- +-- +-- BC('), DE('), HL('), IX and IY +-- +--------------------------------------------------------------------------- + process (CLK_n) + begin + if rising_edge(CLK_n) then + if ClkEn = '1' then + -- Bus A / Write + RegAddrA_r <= Alternate & Set_BusA_To(2 downto 1); + if XY_Ind = '0' and XY_State /= "00" and Set_BusA_To(2 downto 1) = "10" then + RegAddrA_r <= XY_State(1) & "11"; + end if; + + -- Bus B + RegAddrB_r <= Alternate & Set_BusB_To(2 downto 1); + if XY_Ind = '0' and XY_State /= "00" and Set_BusB_To(2 downto 1) = "10" then + RegAddrB_r <= XY_State(1) & "11"; + end if; + + -- Address from register + RegAddrC <= Alternate & Set_Addr_To(1 downto 0); + -- Jump (HL), LD SP,HL + if (JumpXY = '1' or LDSPHL = '1') then + RegAddrC <= Alternate & "10"; + end if; + if ((JumpXY = '1' or LDSPHL = '1') and XY_State /= "00") or (MCycle = "110") then + RegAddrC <= XY_State(1) & "11"; + end if; + + if I_DJNZ = '1' and Save_ALU_r = '1' and Mode < 2 then + IncDecZ <= F_Out(Flag_Z); + end if; + if (TState = 2 or (TState = 3 and MCycle = "001")) and IncDec_16(2 downto 0) = "100" then + if ID16 = 0 then + IncDecZ <= '0'; + else + IncDecZ <= '1'; + end if; + end if; + + RegBusA_r <= RegBusA; + end if; + end if; + end process; + + RegAddrA <= + -- 16 bit increment/decrement + Alternate & IncDec_16(1 downto 0) when (TState = 2 or + (TState = 3 and MCycle = "001" and IncDec_16(2) = '1')) and XY_State = "00" else + XY_State(1) & "11" when (TState = 2 or + (TState = 3 and MCycle = "001" and IncDec_16(2) = '1')) and IncDec_16(1 downto 0) = "10" else + -- EX HL,DL + Alternate & "10" when ExchangeDH = '1' and TState = 3 else + Alternate & "01" when (ExchangeDH = '1' or I_MULU = '1') and TState = 4 else + -- EX (SP),HL (HL(IX,IY) <= WZ) + Alternate & "10" when ExchangeWH = '1' and XY_State = "00" and TState = 4 else + XY_State(1) & "11" when ExchangeWH = '1' and TState = 4 else + -- LDHLSP + "010" when LDHLSP = '1' and TState = 4 else + + -- Bus A / Write + RegAddrA_r; + + RegAddrB <= + -- EX HL,DL + Alternate & "01" when ExchangeDH = '1' and TState = 3 else + -- Bus B + RegAddrB_r; + + ID16 <= signed(RegBusA) - 1 when IncDec_16(3) = '1' else + signed(RegBusA) + 1; + + process (Save_ALU_r, Auto_Wait_t1, ALU_OP_r, Read_To_Reg_r, I_MULU, T_Res, + ExchangeDH, ExchangeWH, IncDec_16, MCycle, TState, Really_Wait, LDHLSP) + begin + RegWEH <= '0'; + RegWEL <= '0'; + if (TState = 1 and Save_ALU_r = '0' and Auto_Wait_t1 = '0') or + (Save_ALU_r = '1' and ALU_OP_r /= "0111") then + case Read_To_Reg_r is + when "10000" | "10001" | "10010" | "10011" | "10100" | "10101" => + RegWEH <= not Read_To_Reg_r(0); + RegWEL <= Read_To_Reg_r(0); + when others => + end case; + end if; + + if I_MULU = '1' and (T_Res = '1' or TState = 4) then -- TState = 4 DE write + RegWEH <= '1'; + RegWEL <= '1'; + end if; + + if ExchangeDH = '1' and (TState = 3 or TState = 4) then + RegWEH <= '1'; + RegWEL <= '1'; + end if; + + if ((LDHLSP = '1' and MCycle = "010") or ExchangeWH = '1') and TState = 4 then + RegWEH <= '1'; + RegWEL <= '1'; + end if; + + if IncDec_16(2) = '1' and ((TState = 2 and Really_Wait = '0' and MCycle /= "001") or (TState = 3 and MCycle = "001")) then + case IncDec_16(1 downto 0) is + when "00" | "01" | "10" => + RegWEH <= '1'; + RegWEL <= '1'; + when others => + end case; + end if; + end process; + + TmpAddr2 <= std_logic_vector(unsigned(signed(SP) + signed(Save_Mux))); + + process (Save_Mux, RegBusB, RegBusA_r, ID16, I_MULU, MULU_Prod32, MULU_tmp, T_Res, + ExchangeDH, ExchangeWH, IncDec_16, MCycle, TState, Really_Wait, LDHLSP, TmpAddr2, WZ) + begin + RegDIH <= Save_Mux; + RegDIL <= Save_Mux; + + if I_MULU = '1' then + if T_Res = '1' then + RegDIH <= MULU_Prod32(31 downto 24); + RegDIL <= MULU_Prod32(23 downto 16); + else + RegDIH <= MULU_tmp(15 downto 8); -- TState = 4 DE write + RegDIL <= MULU_tmp(7 downto 0); + end if; + end if; + + if LDHLSP = '1' and MCycle = "010" and TState = 4 then + RegDIH <= TmpAddr2(15 downto 8); + RegDIL <= TmpAddr2(7 downto 0); + end if; + + if ExchangeDH = '1' and TState = 3 then + RegDIH <= RegBusB(15 downto 8); + RegDIL <= RegBusB(7 downto 0); + end if; + if ExchangeDH = '1' and TState = 4 then + RegDIH <= RegBusA_r(15 downto 8); + RegDIL <= RegBusA_r(7 downto 0); + end if; + if ExchangeWH = '1' and TState = 4 then + RegDIH <= WZ(15 downto 8); + RegDIL <= WZ(7 downto 0); + end if; + if IncDec_16(2) = '1' and ((TState = 2 and MCycle /= "001") or (TState = 3 and MCycle = "001")) then + RegDIH <= std_logic_vector(ID16(15 downto 8)); + RegDIL <= std_logic_vector(ID16(7 downto 0)); + end if; + end process; + + Regs : T80_Reg + port map( + Clk => CLK_n, + CEN => ClkEn, + WEH => RegWEH, + WEL => RegWEL, + AddrA => RegAddrA, + AddrB => RegAddrB, + AddrC => RegAddrC, + DIH => RegDIH, + DIL => RegDIL, + DOAH => RegBusA(15 downto 8), + DOAL => RegBusA(7 downto 0), + DOBH => RegBusB(15 downto 8), + DOBL => RegBusB(7 downto 0), + DOCH => RegBusC(15 downto 8), + DOCL => RegBusC(7 downto 0), + DOR => DOR, + DIRSet => DIRSet, + DIR => DIR(207 downto 80)); + +--------------------------------------------------------------------------- +-- +-- Buses +-- +--------------------------------------------------------------------------- + process (CLK_n) + begin + if rising_edge(CLK_n) then + if ClkEn = '1' then + case Set_BusB_To is + when "0111" => + BusB <= ACC; + when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" => + if Set_BusB_To(0) = '1' then + BusB <= RegBusB(7 downto 0); + else + BusB <= RegBusB(15 downto 8); + end if; + when "0110" => + BusB <= DI_Reg; + when "1000" => + BusB <= std_logic_vector(SP(7 downto 0)); + when "1001" => + BusB <= std_logic_vector(SP(15 downto 8)); + when "1010" => + BusB <= "00000001"; + when "1011" => + BusB <= F; + when "1100" => + BusB <= std_logic_vector(PC(7 downto 0)); + when "1101" => + BusB <= std_logic_vector(PC(15 downto 8)); + when "1110" => + if IR = x"71" and out0 = '1' then + BusB <= "11111111"; + else + BusB <= "00000000"; + end if; + when others => + BusB <= "--------"; + end case; + + case Set_BusA_To is + when "0111" => + BusA <= ACC; + when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" => + if Set_BusA_To(0) = '1' then + BusA <= RegBusA(7 downto 0); + else + BusA <= RegBusA(15 downto 8); + end if; + when "0110" => + BusA <= DI_Reg; + when "1000" => + BusA <= std_logic_vector(SP(7 downto 0)); + when "1001" => + BusA <= std_logic_vector(SP(15 downto 8)); + when "1010" => + BusA <= "00000000"; + when others => + BusA <= "--------"; + end case; + if XYbit_undoc='1' then + BusA <= DI_Reg; + BusB <= DI_Reg; + end if; + end if; + end if; + end process; + +--------------------------------------------------------------------------- +-- +-- Generate external control signals +-- +--------------------------------------------------------------------------- + process (RESET_n,CLK_n) + begin + if RESET_n = '0' then + RFSH_n <= '1'; + elsif rising_edge(CLK_n) then + if DIRSet = '0' and CEN = '1' then + if MCycle = "001" and ((TState = 2 and Wait_n = '1') or TState = 3) then + RFSH_n <= '0'; + else + RFSH_n <= '1'; + end if; + end if; + end if; + end process; + + MC <= std_logic_vector(MCycle); + TS <= std_logic_vector(TState); + DI_Reg <= DI; + HALT_n <= not Halt_FF; + BUSAK_n <= not (BusAck and RESET_n); + IntCycle_n <= not IntCycle; + IntE <= IntE_FF1; + IORQ <= IORQ_i; + NoRead <= NoRead_i; + Write <= Write_i; + Stop <= I_DJNZ; +------------------------------------------------------------------------- +-- +-- Main state machine +-- +------------------------------------------------------------------------- + process (RESET_n, CLK_n) + variable OldNMI_n : std_logic; + begin + if RESET_n = '0' then + MCycle <= "001"; + TState <= "000"; + Pre_XY_F_M <= "000"; + Halt_FF <= '0'; + --BusAck <= '0'; + NMICycle <= '0'; + IntCycle <= '0'; + IntE_FF1 <= '0'; + IntE_FF2 <= '0'; + No_BTR <= '0'; + Auto_Wait_t1 <= '0'; + Auto_Wait_t2 <= '0'; + M1_n <= '1'; + --BusReq_s <= '0'; + NMI_s <= '0'; + elsif rising_edge(CLK_n) then + if DIRSet = '1' then + IntE_FF2 <= DIR(211); + IntE_FF1 <= DIR(210); + else + if NMI_n = '0' and OldNMI_n = '1' then + NMI_s <= '1'; + end if; + OldNMI_n := NMI_n; + + if CEN = '1' then + BusReq_s <= not BUSRQ_n; + Auto_Wait_t2 <= Auto_Wait_t1; + if T_Res = '1' then + Auto_Wait_t1 <= '0'; + Auto_Wait_t2 <= '0'; + else + Auto_Wait_t1 <= Auto_Wait or IORQ_i; + end if; + No_BTR <= (I_BT and (not IR(4) or not F(Flag_P))) or + (I_BC and (not IR(4) or F(Flag_Z) or not F(Flag_P))) or + (I_BTR and (not IR(4) or F(Flag_Z))); + if TState = 2 then + if SetEI = '1' then + IntE_FF1 <= '1'; + IntE_FF2 <= '1'; + end if; + if I_RETN = '1' then + IntE_FF1 <= IntE_FF2; + end if; + end if; + if TState = 3 then + if SetDI = '1' then + IntE_FF1 <= '0'; + IntE_FF2 <= '0'; + end if; + end if; + if IntCycle = '1' or NMICycle = '1' then + Halt_FF <= '0'; + end if; + if MCycle = "001" and TState = 2 and Wait_n = '1' then + M1_n <= '1'; + end if; + if BusReq_s = '1' and BusAck = '1' then + else + BusAck <= '0'; + if TState = 2 and Really_Wait = '1' then + elsif T_Res = '1' then + if Halt = '1' and ( not(Mode = 3 and INT_n = '0' and IntE_FF1 = '0')) then -- halt bug when Mode = 3 , INT_n = '0' and IME=0 + Halt_FF <= '1'; + end if; + if BusReq_s = '1' then + BusAck <= '1'; + else + TState <= "001"; + if (IntCycle = '1' and Mode = 3) then -- GB: read interrupt at MCycle 3 + if (MCycle = "010") then + M1_n <= '0'; + else + M1_n <= '1'; + end if; + end if; + if NextIs_XY_Fetch = '1' then + MCycle <= "110"; + Pre_XY_F_M <= MCycle; + if IR = "00110110" and Mode = 0 then + Pre_XY_F_M <= "010"; + end if; + elsif (MCycle = "111") or (MCycle = "110" and Mode = 1 and ISet /= "01") then + MCycle <= std_logic_vector(unsigned(Pre_XY_F_M) + 1); + elsif (MCycle = MCycles) or No_BTR = '1' or (MCycle = "010" and I_DJNZ = '1' and IncDecZ = '1') then + M1_n <= '0'; + MCycle <= "001"; + IntCycle <= '0'; + NMICycle <= '0'; + if NMI_s = '1' and Prefix = "00" then + NMI_s <= '0'; + NMICycle <= '1'; + IntE_FF1 <= '0'; + elsif IntE_FF1 = '1' and INT_n='0' and Prefix = "00" and SetEI = '0' then + IntCycle <= '1'; + IntE_FF1 <= '0'; + IntE_FF2 <= '0'; + elsif (Halt_FF = '1' and INT_n = '0' and Mode = 3) then + Halt_FF <= '0'; + end if; + else + MCycle <= std_logic_vector(unsigned(MCycle) + 1); + end if; + end if; + else + if (Auto_Wait = '1' and Auto_Wait_t2 = '0') nor + (IOWait = 1 and IORQ_i = '1' and Auto_Wait_t1 = '0') then + TState <= TState + 1; + end if; + end if; + end if; + if TState = 0 then + M1_n <= '0'; + end if; + end if; + end if; + end if; + end process; + + Auto_Wait <= '1' when IntCycle = '1' and MCycle = "001" else '0'; +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_ALU.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_ALU.vhd new file mode 100644 index 0000000000000000000000000000000000000000..1192e0b9d4998210d1683926b37447f16cb938a5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_ALU.vhd @@ -0,0 +1,409 @@ +-------------------------------------------------------------------------------- +-- **** +-- T80(c) core. Attempt to finish all undocumented features and provide +-- accurate timings. +-- Version 350. +-- Copyright (c) 2018 Sorgelig +-- Test passed: ZEXDOC, ZEXALL, Z80Full(*), Z80memptr +-- (*) Currently only SCF and CCF instructions aren't passed X/Y flags check as +-- correct implementation is still unclear. +-- +-- **** +-- T80(b) core. In an effort to merge and maintain bug fixes .... +-- +-- Ver 301 parity flag is just parity for 8080, also overflow for Z80, by Sean Riddle +-- Ver 300 started tidyup +-- MikeJ March 2005 +-- Latest version from www.fpgaarcade.com (original www.opencores.org) +-- +-- **** +-- Z80 compatible microprocessor core +-- +-- Version : 0247 +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- Limitations : +-- +-- File history : +-- +-- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test +-- 0238 : Fixed zero flag for 16 bit SBC and ADC +-- 0240 : Added GB operations +-- 0242 : Cleanup +-- 0247 : Cleanup +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; + +entity T80_ALU is + generic( + Mode : integer := 0; + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + Arith16 : in std_logic; + Z16 : in std_logic; + WZ : in std_logic_vector(15 downto 0); + XY_State : in std_logic_vector(1 downto 0); + ALU_Op : in std_logic_vector(3 downto 0); + Rot_Akku : in std_logic; + IR : in std_logic_vector(5 downto 0); + ISet : in std_logic_vector(1 downto 0); + BusA : in std_logic_vector(7 downto 0); + BusB : in std_logic_vector(7 downto 0); + F_In : in std_logic_vector(7 downto 0); + Q : out std_logic_vector(7 downto 0); + F_Out : out std_logic_vector(7 downto 0) + ); +end T80_ALU; + +architecture rtl of T80_ALU is + + procedure AddSub(A : std_logic_vector; + B : std_logic_vector; + Sub : std_logic; + Carry_In : std_logic; + signal Res : out std_logic_vector; + signal Carry : out std_logic) is + + variable B_i : unsigned(A'length - 1 downto 0); + variable Res_i : unsigned(A'length + 1 downto 0); + begin + if Sub = '1' then + B_i := not unsigned(B); + else + B_i := unsigned(B); + end if; + + Res_i := unsigned("0" & A & Carry_In) + unsigned("0" & B_i & "1"); + Carry <= Res_i(A'length + 1); + Res <= std_logic_vector(Res_i(A'length downto 1)); + end; + + -- AddSub variables (temporary signals) + signal UseCarry : std_logic; + signal Carry7_v : std_logic; + signal Overflow_v : std_logic; + signal HalfCarry_v : std_logic; + signal Carry_v : std_logic; + signal Q_v : std_logic_vector(7 downto 0); + + signal BitMask : std_logic_vector(7 downto 0); + +begin + + with IR(5 downto 3) select BitMask <= "00000001" when "000", + "00000010" when "001", + "00000100" when "010", + "00001000" when "011", + "00010000" when "100", + "00100000" when "101", + "01000000" when "110", + "10000000" when others; + + UseCarry <= not ALU_Op(2) and ALU_Op(0); + AddSub(BusA(3 downto 0), BusB(3 downto 0), ALU_Op(1), ALU_Op(1) xor (UseCarry and F_In(Flag_C)), Q_v(3 downto 0), HalfCarry_v); + AddSub(BusA(6 downto 4), BusB(6 downto 4), ALU_Op(1), HalfCarry_v, Q_v(6 downto 4), Carry7_v); + AddSub(BusA(7 downto 7), BusB(7 downto 7), ALU_Op(1), Carry7_v, Q_v(7 downto 7), Carry_v); + + -- bug fix - parity flag is just parity for 8080, also overflow for Z80 + process (Carry_v, Carry7_v, Q_v) + begin + if(Mode=2) then + OverFlow_v <= not (Q_v(0) xor Q_v(1) xor Q_v(2) xor Q_v(3) xor + Q_v(4) xor Q_v(5) xor Q_v(6) xor Q_v(7)); else + OverFlow_v <= Carry_v xor Carry7_v; + end if; + end process; + + process (Arith16, ALU_OP, F_In, BusA, BusB, IR, Q_v, Carry_v, HalfCarry_v, OverFlow_v, BitMask, ISet, Z16, Rot_Akku, WZ, XY_State) + variable Q_t : std_logic_vector(7 downto 0); + variable DAA_Q : unsigned(8 downto 0); + begin + Q_t := "--------"; + F_Out <= F_In; + DAA_Q := "---------"; + case ALU_Op is + when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" | "0110" | "0111" => + F_Out(Flag_N) <= '0'; + F_Out(Flag_C) <= '0'; + case ALU_OP(2 downto 0) is + when "000" | "001" => -- ADD, ADC + Q_t := Q_v; + F_Out(Flag_C) <= Carry_v; + F_Out(Flag_H) <= HalfCarry_v; + F_Out(Flag_P) <= OverFlow_v; + when "010" | "011" | "111" => -- SUB, SBC, CP + Q_t := Q_v; + F_Out(Flag_N) <= '1'; + F_Out(Flag_C) <= not Carry_v; + F_Out(Flag_H) <= not HalfCarry_v; + F_Out(Flag_P) <= OverFlow_v; + when "100" => -- AND + Q_t(7 downto 0) := BusA and BusB; + F_Out(Flag_H) <= '1'; + when "101" => -- XOR + Q_t(7 downto 0) := BusA xor BusB; + F_Out(Flag_H) <= '0'; + when others => -- OR "110" + Q_t(7 downto 0) := BusA or BusB; + F_Out(Flag_H) <= '0'; + end case; + if ALU_Op(2 downto 0) = "111" then -- CP + F_Out(Flag_X) <= BusB(3); + F_Out(Flag_Y) <= BusB(5); + else + F_Out(Flag_X) <= Q_t(3); + F_Out(Flag_Y) <= Q_t(5); + end if; + if Q_t(7 downto 0) = "00000000" then + F_Out(Flag_Z) <= '1'; + if Z16 = '1' then + F_Out(Flag_Z) <= F_In(Flag_Z); -- 16 bit ADC,SBC + end if; + else + F_Out(Flag_Z) <= '0'; + end if; + F_Out(Flag_S) <= Q_t(7); + case ALU_Op(2 downto 0) is + when "000" | "001" | "010" | "011" | "111" => -- ADD, ADC, SUB, SBC, CP + when others => + F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor + Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); + end case; + if Arith16 = '1' then + F_Out(Flag_S) <= F_In(Flag_S); + F_Out(Flag_Z) <= F_In(Flag_Z); + F_Out(Flag_P) <= F_In(Flag_P); + end if; + when "1100" => + -- DAA + if Mode = 3 then + F_Out(Flag_H) <= '0'; + F_Out(Flag_C) <= F_In(Flag_C); + DAA_Q(7 downto 0) := unsigned(BusA); + DAA_Q(8) := '0'; + if F_In(Flag_N) = '0' then + -- After addition + -- Alow > 9 or H = 1 + if DAA_Q(3 downto 0) > 9 or F_In(Flag_H) = '1' then + DAA_Q := DAA_Q + 6; + end if; + -- new Ahigh > 9 or C = 1 + if DAA_Q(8 downto 4) > 9 or F_In(Flag_C) = '1' then + DAA_Q := DAA_Q + 96; -- 0x60 + end if; + else + -- After subtraction + if F_In(Flag_H) = '1' then + DAA_Q := DAA_Q - 6; + if F_In(Flag_C) = '0' then + DAA_Q(8) := '0'; + end if; + end if; + if F_In(Flag_C) = '1' then + DAA_Q := DAA_Q - 96; -- 0x60 + end if; + end if; + else + F_Out(Flag_H) <= F_In(Flag_H); + F_Out(Flag_C) <= F_In(Flag_C); + DAA_Q(7 downto 0) := unsigned(BusA); + DAA_Q(8) := '0'; + if F_In(Flag_N) = '0' then + -- After addition + -- Alow > 9 or H = 1 + if DAA_Q(3 downto 0) > 9 or F_In(Flag_H) = '1' then + if (DAA_Q(3 downto 0) > 9) then + F_Out(Flag_H) <= '1'; + else + F_Out(Flag_H) <= '0'; + end if; + DAA_Q := DAA_Q + 6; + end if; + -- new Ahigh > 9 or C = 1 + if DAA_Q(8 downto 4) > 9 or F_In(Flag_C) = '1' then + DAA_Q := DAA_Q + 96; -- 0x60 + end if; + else + -- After subtraction + if DAA_Q(3 downto 0) > 9 or F_In(Flag_H) = '1' then + if DAA_Q(3 downto 0) > 5 then + F_Out(Flag_H) <= '0'; + end if; + DAA_Q(7 downto 0) := DAA_Q(7 downto 0) - 6; + end if; + if unsigned(BusA) > 153 or F_In(Flag_C) = '1' then + DAA_Q := DAA_Q - 352; -- 0x160 + end if; + end if; + end if; + F_Out(Flag_X) <= DAA_Q(3); + F_Out(Flag_Y) <= DAA_Q(5); + F_Out(Flag_C) <= F_In(Flag_C) or DAA_Q(8); + Q_t := std_logic_vector(DAA_Q(7 downto 0)); + if DAA_Q(7 downto 0) = "00000000" then + F_Out(Flag_Z) <= '1'; + else + F_Out(Flag_Z) <= '0'; + end if; + F_Out(Flag_S) <= DAA_Q(7); + F_Out(Flag_P) <= not (DAA_Q(0) xor DAA_Q(1) xor DAA_Q(2) xor DAA_Q(3) xor + DAA_Q(4) xor DAA_Q(5) xor DAA_Q(6) xor DAA_Q(7)); + when "1101" | "1110" => + -- RLD, RRD + Q_t(7 downto 4) := BusA(7 downto 4); + if ALU_Op(0) = '1' then + Q_t(3 downto 0) := BusB(7 downto 4); + else + Q_t(3 downto 0) := BusB(3 downto 0); + end if; + F_Out(Flag_H) <= '0'; + F_Out(Flag_N) <= '0'; + F_Out(Flag_X) <= Q_t(3); + F_Out(Flag_Y) <= Q_t(5); + if Q_t(7 downto 0) = "00000000" then + F_Out(Flag_Z) <= '1'; + else + F_Out(Flag_Z) <= '0'; + end if; + F_Out(Flag_S) <= Q_t(7); + F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor + Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); + when "1001" => + -- BIT + Q_t(7 downto 0) := BusB and BitMask; + F_Out(Flag_S) <= Q_t(7); + if Q_t(7 downto 0) = "00000000" then + F_Out(Flag_Z) <= '1'; + F_Out(Flag_P) <= '1'; + else + F_Out(Flag_Z) <= '0'; + F_Out(Flag_P) <= '0'; + end if; + F_Out(Flag_H) <= '1'; + F_Out(Flag_N) <= '0'; + if IR(2 downto 0) = "110" or XY_State /= "00" then + F_Out(Flag_X) <= WZ(11); + F_Out(Flag_Y) <= WZ(13); + else + F_Out(Flag_X) <= BusB(3); + F_Out(Flag_Y) <= BusB(5); + end if; + when "1010" => + -- SET + Q_t(7 downto 0) := BusB or BitMask; + when "1011" => + -- RES + Q_t(7 downto 0) := BusB and not BitMask; + when "1000" => + -- ROT + case IR(5 downto 3) is + when "000" => -- RLC + Q_t(7 downto 1) := BusA(6 downto 0); + Q_t(0) := BusA(7); + F_Out(Flag_C) <= BusA(7); + when "010" => -- RL + Q_t(7 downto 1) := BusA(6 downto 0); + Q_t(0) := F_In(Flag_C); + F_Out(Flag_C) <= BusA(7); + when "001" => -- RRC + Q_t(6 downto 0) := BusA(7 downto 1); + Q_t(7) := BusA(0); + F_Out(Flag_C) <= BusA(0); + when "011" => -- RR + Q_t(6 downto 0) := BusA(7 downto 1); + Q_t(7) := F_In(Flag_C); + F_Out(Flag_C) <= BusA(0); + when "100" => -- SLA + Q_t(7 downto 1) := BusA(6 downto 0); + Q_t(0) := '0'; + F_Out(Flag_C) <= BusA(7); + when "110" => -- SLL (Undocumented) / SWAP + if Mode = 3 then + Q_t(7 downto 4) := BusA(3 downto 0); + Q_t(3 downto 0) := BusA(7 downto 4); + F_Out(Flag_C) <= '0'; + else + Q_t(7 downto 1) := BusA(6 downto 0); + Q_t(0) := '1'; + F_Out(Flag_C) <= BusA(7); + end if; + when "101" => -- SRA + Q_t(6 downto 0) := BusA(7 downto 1); + Q_t(7) := BusA(7); + F_Out(Flag_C) <= BusA(0); + when others => -- SRL + Q_t(6 downto 0) := BusA(7 downto 1); + Q_t(7) := '0'; + F_Out(Flag_C) <= BusA(0); + end case; + F_Out(Flag_H) <= '0'; + F_Out(Flag_N) <= '0'; + F_Out(Flag_X) <= Q_t(3); + F_Out(Flag_Y) <= Q_t(5); + F_Out(Flag_S) <= Q_t(7); + if Q_t(7 downto 0) = "00000000" then + F_Out(Flag_Z) <= '1'; + else + F_Out(Flag_Z) <= '0'; + end if; + F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor + Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); + if ISet = "00" then + F_Out(Flag_P) <= F_In(Flag_P); + F_Out(Flag_S) <= F_In(Flag_S); + F_Out(Flag_Z) <= F_In(Flag_Z); + end if; + if Mode = 3 and Rot_Akku = '1' then + F_Out(Flag_Z) <= '0'; + end if; + when others => + null; + end case; + Q <= Q_t; + end process; +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_MCode.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_MCode.vhd new file mode 100644 index 0000000000000000000000000000000000000000..554ec9b5bbfdb3fe2fa03a92a2822e3820c00256 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_MCode.vhd @@ -0,0 +1,2289 @@ +-------------------------------------------------------------------------------- +-- **** +-- T80(c) core. Attempt to finish all undocumented features and provide +-- accurate timings. +-- Version 350. +-- Copyright (c) 2018 Sorgelig +-- Test passed: ZEXDOC, ZEXALL, Z80Full(*), Z80memptr +-- (*) Currently only SCF and CCF instructions aren't passed X/Y flags check as +-- correct implementation is still unclear. +-- +-- **** +-- T80(b) core. In an effort to merge and maintain bug fixes .... +-- +-- Ver 303 add undocumented DDCB and FDCB opcodes by TobiFlex 20.04.2010 +-- Ver 300 started tidyup +-- MikeJ March 2005 +-- Latest version from www.fpgaarcade.com (original www.opencores.org) +-- +-- **** +-- Z80 compatible microprocessor core +-- +-- Version : 0250 +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- Limitations : +-- +-- File history : +-- +-- 0208 : First complete release +-- 0211 : Fixed IM 1 +-- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test +-- 0235 : Added IM 2 fix by Mike Johnson +-- 0238 : Added NoRead signal +-- 0238b: Fixed instruction timing for POP and DJNZ +-- 0240 : Added (IX/IY+d) states, removed op-codes from mode 2 and added all remaining mode 3 op-codes +-- 0240mj1 fix for HL inc/dec for INI, IND, INIR, INDR, OUTI, OUTD, OTIR, OTDR +-- 0242 : Fixed I/O instruction timing, cleanup +-- 0250 : Added R800 Multiplier by TobiFlex 2017.10.15 +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; +use work.T80_Pack.all; + +entity T80_MCode is + generic( + Mode : integer := 0; + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + IR : in std_logic_vector(7 downto 0); + ISet : in std_logic_vector(1 downto 0); + MCycle : in std_logic_vector(2 downto 0); + F : in std_logic_vector(7 downto 0); + NMICycle : in std_logic; + IntCycle : in std_logic; + XY_State : in std_logic_vector(1 downto 0); + MCycles : out std_logic_vector(2 downto 0); + TStates : out std_logic_vector(2 downto 0); + Prefix : out std_logic_vector(1 downto 0); -- None,CB,ED,DD/FD + Inc_PC : out std_logic; + Inc_WZ : out std_logic; + IncDec_16 : out std_logic_vector(3 downto 0); -- BC,DE,HL,SP 0 is inc + Read_To_Reg : out std_logic; + Read_To_Acc : out std_logic; + Set_BusA_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI/DB,A,SP(L),SP(M),0,F + Set_BusB_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI,A,SP(L),SP(M),1,F,PC(L),PC(M),0 + ALU_Op : out std_logic_vector(3 downto 0); + -- ADD, ADC, SUB, SBC, AND, XOR, OR, CP, ROT, BIT, SET, RES, DAA, RLD, RRD, None + Save_ALU : out std_logic; + Rot_Akku : out std_logic; + PreserveC : out std_logic; + Arith16 : out std_logic; + Set_Addr_To : out std_logic_vector(2 downto 0); -- aNone,aXY,aIOA,aSP,aBC,aDE,aZI + IORQ : out std_logic; + Jump : out std_logic; + JumpE : out std_logic; + JumpXY : out std_logic; + Call : out std_logic; + RstP : out std_logic; + LDZ : out std_logic; + LDW : out std_logic; + LDSPHL : out std_logic; + LDHLSP : out std_logic; + ADDSPdd : out std_logic; + Special_LD : out std_logic_vector(2 downto 0); -- A,I;A,R;I,A;R,A;None + ExchangeDH : out std_logic; + ExchangeRp : out std_logic; + ExchangeAF : out std_logic; + ExchangeRS : out std_logic; + ExchangeWH : out std_logic; + I_DJNZ : out std_logic; + I_CPL : out std_logic; + I_CCF : out std_logic; + I_SCF : out std_logic; + I_RETN : out std_logic; + I_BT : out std_logic; + I_BC : out std_logic; + I_BTR : out std_logic; + I_RLD : out std_logic; + I_RRD : out std_logic; + I_INRC : out std_logic; + I_MULUB : out std_logic; + I_MULU : out std_logic; + SetWZ : out std_logic_vector(1 downto 0); + SetDI : out std_logic; + SetEI : out std_logic; + IMode : out std_logic_vector(1 downto 0); + Halt : out std_logic; + NoRead : out std_logic; + Write : out std_logic; + R800_mode : in std_logic; + No_PC : out std_logic; + XYbit_undoc : out std_logic + ); +end T80_MCode; + +architecture rtl of T80_MCode is + + function is_cc_true( + F : std_logic_vector(7 downto 0); + cc : bit_vector(2 downto 0) + ) return boolean is + begin + if Mode = 3 then + case cc is + when "000" => return F(Flag_Z) = '0'; -- NZ + when "001" => return F(Flag_Z) = '1'; -- Z + when "010" => return F(Flag_C) = '0'; -- NC + when "011" => return F(Flag_C) = '1'; -- C + when "100" => return false; + when "101" => return false; + when "110" => return false; + when "111" => return false; + end case; + else + case cc is + when "000" => return F(Flag_Z) = '0'; -- NZ + when "001" => return F(Flag_Z) = '1'; -- Z + when "010" => return F(Flag_C) = '0'; -- NC + when "011" => return F(Flag_C) = '1'; -- C + when "100" => return F(Flag_P) = '0'; -- PO + when "101" => return F(Flag_P) = '1'; -- PE + when "110" => return F(Flag_S) = '0'; -- P + when "111" => return F(Flag_S) = '1'; -- M + end case; + end if; + end; + +begin + + process (IR, ISet, MCycle, F, NMICycle, IntCycle, XY_State, R800_mode) + variable DDD : std_logic_vector(2 downto 0); + variable SSS : std_logic_vector(2 downto 0); + variable DPair : std_logic_vector(1 downto 0); + variable IRB : bit_vector(7 downto 0); + begin + DDD := IR(5 downto 3); + SSS := IR(2 downto 0); + DPair := IR(5 downto 4); + IRB := to_bitvector(IR); + + MCycles <= "001"; + if MCycle = "001" then + TStates <= "100"; + else + TStates <= "011"; + end if; + Prefix <= "00"; + Inc_PC <= '0'; + Inc_WZ <= '0'; + IncDec_16 <= "0000"; + Read_To_Acc <= '0'; + Read_To_Reg <= '0'; + Set_BusB_To <= "0000"; + Set_BusA_To <= "0000"; + ALU_Op <= "0" & IR(5 downto 3); + Save_ALU <= '0'; + Rot_Akku <= '0'; + PreserveC <= '0'; + Arith16 <= '0'; + IORQ <= '0'; + Set_Addr_To <= aNone; + Jump <= '0'; + JumpE <= '0'; + JumpXY <= '0'; + Call <= '0'; + RstP <= '0'; + LDZ <= '0'; + LDW <= '0'; + LDSPHL <= '0'; + LDHLSP <= '0'; + ADDSPdd <= '0'; + Special_LD <= "000"; + ExchangeDH <= '0'; + ExchangeRp <= '0'; + ExchangeAF <= '0'; + ExchangeRS <= '0'; + ExchangeWH <= '0'; + I_DJNZ <= '0'; + I_CPL <= '0'; + I_CCF <= '0'; + I_SCF <= '0'; + I_RETN <= '0'; + I_BT <= '0'; + I_BC <= '0'; + I_BTR <= '0'; + I_RLD <= '0'; + I_RRD <= '0'; + I_INRC <= '0'; + I_MULUB <= '0'; + I_MULU <= '0'; + SetDI <= '0'; + SetEI <= '0'; + IMode <= "11"; + Halt <= '0'; + NoRead <= '0'; + Write <= '0'; + No_PC <= '0'; + XYbit_undoc <= '0'; + SetWZ <= "00"; + + case ISet is + when "00" => + +------------------------------------------------------------------------------ +-- +-- Unprefixed instructions +-- +------------------------------------------------------------------------------ + + case IRB is +-- 8 BIT LOAD GROUP + when "01000000"|"01000001"|"01000010"|"01000011"|"01000100"|"01000101"|"01000111" + |"01001000"|"01001001"|"01001010"|"01001011"|"01001100"|"01001101"|"01001111" + |"01010000"|"01010001"|"01010010"|"01010011"|"01010100"|"01010101"|"01010111" + |"01011000"|"01011001"|"01011010"|"01011011"|"01011100"|"01011101"|"01011111" + |"01100000"|"01100001"|"01100010"|"01100011"|"01100100"|"01100101"|"01100111" + |"01101000"|"01101001"|"01101010"|"01101011"|"01101100"|"01101101"|"01101111" + |"01111000"|"01111001"|"01111010"|"01111011"|"01111100"|"01111101"|"01111111" => + -- LD r,r' + Set_BusB_To(2 downto 0) <= SSS; + ExchangeRp <= '1'; + Set_BusA_To(2 downto 0) <= DDD; + Read_To_Reg <= '1'; + when "00000110"|"00001110"|"00010110"|"00011110"|"00100110"|"00101110"|"00111110" => + -- LD r,n + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_BusA_To(2 downto 0) <= DDD; + Read_To_Reg <= '1'; + when others => null; + end case; + when "01000110"|"01001110"|"01010110"|"01011110"|"01100110"|"01101110"|"01111110" => + -- LD r,(HL) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Set_BusA_To(2 downto 0) <= DDD; + Read_To_Reg <= '1'; + when others => null; + end case; + when "01110000"|"01110001"|"01110010"|"01110011"|"01110100"|"01110101"|"01110111" => + -- LD (HL),r + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusB_To(3) <= '0'; + when 2 => + Write <= '1'; + when others => null; + end case; + when "00110110" => + -- LD (HL),n + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_Addr_To <= aXY; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusB_To(3) <= '0'; + when 3 => + Write <= '1'; + when others => null; + end case; + when "00001010" => + -- LD A,(BC) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + when 2 => + Read_To_Acc <= '1'; + when others => null; + end case; + when "00011010" => + -- LD A,(DE) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aDE; + when 2 => + Read_To_Acc <= '1'; + when others => null; + end case; + when "00111010" => + if Mode = 3 then + -- LDD A,(HL) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Read_To_Acc <= '1'; + IncDec_16 <= "1110"; + when others => null; + end case; + else + -- LD A,(nn) + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + when 4 => + Read_To_Acc <= '1'; + when others => null; + end case; + end if; + when "00000010" => + -- LD (BC),A + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + Set_BusB_To <= "0111"; + SetWZ <= "10"; + when 2 => + Write <= '1'; + when others => null; + end case; + when "00010010" => + -- LD (DE),A + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aDE; + Set_BusB_To <= "0111"; + SetWZ <= "10"; + when 2 => + Write <= '1'; + when others => null; + end case; + when "00110010" => + if Mode = 3 then + -- LDD (HL),A + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + Set_BusB_To <= "0111"; + when 2 => + Write <= '1'; + IncDec_16 <= "1110"; + when others => null; + end case; + else + -- LD (nn),A + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + SetWZ <= "10"; + Inc_PC <= '1'; + Set_BusB_To <= "0111"; + when 4 => + Write <= '1'; + when others => null; + end case; + end if; + +-- 16 BIT LOAD GROUP + when "00000001"|"00010001"|"00100001"|"00110001" => + -- LD dd,nn + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Read_To_Reg <= '1'; + if DPAIR = "11" then + Set_BusA_To(3 downto 0) <= "1000"; + else + Set_BusA_To(2 downto 1) <= DPAIR; + Set_BusA_To(0) <= '1'; + end if; + when 3 => + Inc_PC <= '1'; + Read_To_Reg <= '1'; + if DPAIR = "11" then + Set_BusA_To(3 downto 0) <= "1001"; + else + Set_BusA_To(2 downto 1) <= DPAIR; + Set_BusA_To(0) <= '0'; + end if; + when others => null; + end case; + when "00101010" => + if Mode = 3 then + -- LDI A,(HL) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Read_To_Acc <= '1'; + IncDec_16 <= "0110"; + when others => null; + end case; + else + -- LD HL,(nn) + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + LDW <= '1'; + when 4 => + Set_BusA_To(2 downto 0) <= "101"; -- L + Read_To_Reg <= '1'; + Inc_WZ <= '1'; + Set_Addr_To <= aZI; + when 5 => + Set_BusA_To(2 downto 0) <= "100"; -- H + Read_To_Reg <= '1'; + when others => null; + end case; + end if; + when "00100010" => + if Mode = 3 then + -- LDI (HL),A + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + Set_BusB_To <= "0111"; + when 2 => + Write <= '1'; + IncDec_16 <= "0110"; + when others => null; + end case; + else + -- LD (nn),HL + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + LDW <= '1'; + Set_BusB_To <= "0101"; -- L + when 4 => + Inc_WZ <= '1'; + Set_Addr_To <= aZI; + Write <= '1'; + Set_BusB_To <= "0100"; -- H + when 5 => + Write <= '1'; + when others => null; + end case; + end if; + when "11111001" => + -- LD SP,HL + if Mode = 3 then + MCycles <= "010"; + if MCycle = "010" then + LDSPHL <= '1'; + end if; + else + TStates <= "110"; + LDSPHL <= '1'; + end if; + when "11000101"|"11010101"|"11100101"|"11110101" => + -- PUSH qq + if Mode = 3 then + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_TO <= aSP; + if DPAIR = "11" then + Set_BusB_To <= "0111"; + else + Set_BusB_To(2 downto 1) <= DPAIR; + Set_BusB_To(0) <= '0'; + Set_BusB_To(3) <= '0'; + end if; + when 3 => + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + if DPAIR = "11" then + Set_BusB_To <= "1011"; + else + Set_BusB_To(2 downto 1) <= DPAIR; + Set_BusB_To(0) <= '1'; + Set_BusB_To(3) <= '0'; + end if; + Write <= '1'; + when 4 => + Write <= '1'; + when others => null; + end case; + else + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_TO <= aSP; + if DPAIR = "11" then + Set_BusB_To <= "0111"; + else + Set_BusB_To(2 downto 1) <= DPAIR; + Set_BusB_To(0) <= '0'; + Set_BusB_To(3) <= '0'; + end if; + when 2 => + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + if DPAIR = "11" then + Set_BusB_To <= "1011"; + else + Set_BusB_To(2 downto 1) <= DPAIR; + Set_BusB_To(0) <= '1'; + Set_BusB_To(3) <= '0'; + end if; + Write <= '1'; + when 3 => + Write <= '1'; + when others => null; + end case; + end if; + when "11000001"|"11010001"|"11100001"|"11110001" => + -- POP qq + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aSP; + when 2 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + Read_To_Reg <= '1'; + if DPAIR = "11" then + Set_BusA_To(3 downto 0) <= "1011"; + else + Set_BusA_To(2 downto 1) <= DPAIR; + Set_BusA_To(0) <= '1'; + end if; + when 3 => + IncDec_16 <= "0111"; + Read_To_Reg <= '1'; + if DPAIR = "11" then + Set_BusA_To(3 downto 0) <= "0111"; + else + Set_BusA_To(2 downto 1) <= DPAIR; + Set_BusA_To(0) <= '0'; + end if; + when others => null; + end case; + +-- EXCHANGE, BLOCK TRANSFER AND SEARCH GROUP + when "11101011" => + if Mode /= 3 then + -- EX DE,HL + ExchangeDH <= '1'; + end if; + when "00001000" => + if Mode = 3 then + -- LD (nn),SP + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + LDW <= '1'; + Set_BusB_To <= "1000"; + when 4 => + Inc_WZ <= '1'; + Set_Addr_To <= aZI; + Write <= '1'; + Set_BusB_To <= "1001"; + when 5 => + Write <= '1'; + when others => null; + end case; + elsif Mode < 2 then + -- EX AF,AF' + ExchangeAF <= '1'; + end if; + when "11011001" => + if Mode = 3 then + -- RETI + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_TO <= aSP; + when 2 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 3 => + Jump <= '1'; + IncDec_16 <= "0111"; + --I_RETN <= '1'; + SetEI <= '1'; + when others => null; + end case; + elsif Mode < 2 then + -- EXX + ExchangeRS <= '1'; + end if; + when "11100011" => + if Mode /= 3 then + -- EX (SP),HL + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aSP; + when 2 => + Set_Addr_To <= aSP; + LDZ <= '1'; + IncDec_16 <= "0111"; -- SP <= SP+1 + when 3 => + TStates <= "100"; + Set_BusB_To <= "0100"; + Set_Addr_To <= aSP; + LDW <= '1'; + when 4 => + Set_BusB_To <= "0101"; + Write <= '1'; + IncDec_16 <= "1111"; -- SP <= SP-1 + Set_Addr_To <= aSP; + when 5 => + ExchangeWH <= '1'; -- save WZ to HL + TStates <= "101"; + Write <= '1'; + when others => null; + end case; + end if; + +-- 8 BIT ARITHMETIC AND LOGICAL GROUP + when "10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000111" + |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001111" + |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010111" + |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011111" + |"10100000"|"10100001"|"10100010"|"10100011"|"10100100"|"10100101"|"10100111" + |"10101000"|"10101001"|"10101010"|"10101011"|"10101100"|"10101101"|"10101111" + |"10110000"|"10110001"|"10110010"|"10110011"|"10110100"|"10110101"|"10110111" + |"10111000"|"10111001"|"10111010"|"10111011"|"10111100"|"10111101"|"10111111" => + -- ADD A,r + -- ADC A,r + -- SUB A,r + -- SBC A,r + -- AND A,r + -- OR A,r + -- XOR A,r + -- CP A,r + Set_BusB_To(2 downto 0) <= SSS; + Set_BusA_To(2 downto 0) <= "111"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + when "10000110"|"10001110"|"10010110"|"10011110"|"10100110"|"10101110"|"10110110"|"10111110" => + -- ADD A,(HL) + -- ADC A,(HL) + -- SUB A,(HL) + -- SBC A,(HL) + -- AND A,(HL) + -- OR A,(HL) + -- XOR A,(HL) + -- CP A,(HL) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusA_To(2 downto 0) <= "111"; + when others => null; + end case; + when "11000110"|"11001110"|"11010110"|"11011110"|"11100110"|"11101110"|"11110110"|"11111110" => + -- ADD A,n + -- ADC A,n + -- SUB A,n + -- SBC A,n + -- AND A,n + -- OR A,n + -- XOR A,n + -- CP A,n + MCycles <= "010"; + if MCycle = "010" then + Inc_PC <= '1'; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusA_To(2 downto 0) <= "111"; + end if; + when "00000100"|"00001100"|"00010100"|"00011100"|"00100100"|"00101100"|"00111100" => + -- INC r + Set_BusB_To <= "1010"; + Set_BusA_To(2 downto 0) <= DDD; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + PreserveC <= '1'; + ALU_Op <= "0000"; + when "00110100" => + -- INC (HL) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + TStates <= "100"; + Set_Addr_To <= aXY; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + PreserveC <= '1'; + ALU_Op <= "0000"; + Set_BusB_To <= "1010"; + Set_BusA_To(2 downto 0) <= DDD; + when 3 => + Write <= '1'; + when others => null; + end case; + when "00000101"|"00001101"|"00010101"|"00011101"|"00100101"|"00101101"|"00111101" => + -- DEC r + Set_BusB_To <= "1010"; + Set_BusA_To(2 downto 0) <= DDD; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + PreserveC <= '1'; + ALU_Op <= "0010"; + when "00110101" => + -- DEC (HL) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + TStates <= "100"; + Set_Addr_To <= aXY; + ALU_Op <= "0010"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + PreserveC <= '1'; + Set_BusB_To <= "1010"; + Set_BusA_To(2 downto 0) <= DDD; + when 3 => + Write <= '1'; + when others => null; + end case; + +-- GENERAL PURPOSE ARITHMETIC AND CPU CONTROL GROUPS + when "00100111" => + -- DAA + Set_BusA_To(2 downto 0) <= "111"; + Read_To_Reg <= '1'; + ALU_Op <= "1100"; + Save_ALU <= '1'; + when "00101111" => + -- CPL + I_CPL <= '1'; + when "00111111" => + -- CCF + I_CCF <= '1'; + when "00110111" => + -- SCF + I_SCF <= '1'; + when "00000000" => + if NMICycle = '1' then + -- NMI + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1101"; + when 2 => + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 3 => + Write <= '1'; + when others => null; + end case; + elsif IntCycle = '1' then + -- INT (IM 2) + if Mode = 3 then + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "110"; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1101"; + when 2 => + Write <= '1'; + when 3 => -- GB: interrupt is acknowledged on MCycle 3 + LDZ <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 4 => + Write <= '1'; + when others => null; + end case; + else + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1101"; + when 2 => + --TStates <= "100"; + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 3 => + --TStates <= "100"; + Write <= '1'; + when 4 => + Inc_PC <= '1'; + LDZ <= '1'; + when 5 => + Jump <= '1'; + when others => null; + end case; + end if; + else + -- NOP + end if; + when "01110110" => + -- HALT + Halt <= '1'; + when "11110011" => + -- DI + SetDI <= '1'; + when "11111011" => + -- EI + SetEI <= '1'; + +-- 16 BIT ARITHMETIC GROUP + when "00001001"|"00011001"|"00101001"|"00111001" => + -- ADD HL,ss + if Mode = 3 then + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + NoRead <= '1'; + ALU_Op <= "0000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusA_To(2 downto 0) <= "101"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '1'; + when others => + Set_BusB_To <= "1000"; + end case; + TStates <= "100"; + Arith16 <= '1'; + SetWZ <= "11"; + when 2 => + NoRead <= '1'; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0001"; + Set_BusA_To(2 downto 0) <= "100"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + when others => + Set_BusB_To <= "1001"; + end case; + Arith16 <= '1'; + when others => + end case; + else + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + No_PC <= '1'; + when 2 => + NoRead <= '1'; + ALU_Op <= "0000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusA_To(2 downto 0) <= "101"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '1'; + when others => + Set_BusB_To <= "1000"; + end case; + TStates <= "100"; + Arith16 <= '1'; + SetWZ <= "11"; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0001"; + Set_BusA_To(2 downto 0) <= "100"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + when others => + Set_BusB_To <= "1001"; + end case; + Arith16 <= '1'; + when others => + end case; + end if; + when "00000011"|"00010011"|"00100011"|"00110011" => + -- INC ss + if Mode = 3 then + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 2 => + IncDec_16(3 downto 2) <= "01"; + IncDec_16(1 downto 0) <= DPair; + when others => + end case; + else + TStates <= "110"; + IncDec_16(3 downto 2) <= "01"; + IncDec_16(1 downto 0) <= DPair; + end if; + when "00001011"|"00011011"|"00101011"|"00111011" => + -- DEC ss + if Mode = 3 then + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 2 => + IncDec_16(3 downto 2) <= "11"; + IncDec_16(1 downto 0) <= DPair; + when others => + end case; + else + TStates <= "110"; + IncDec_16(3 downto 2) <= "11"; + IncDec_16(1 downto 0) <= DPair; + end if; + +-- ROTATE AND SHIFT GROUP + when "00000111" + -- RLCA + |"00010111" + -- RLA + |"00001111" + -- RRCA + |"00011111" => + -- RRA + Set_BusA_To(2 downto 0) <= "111"; + ALU_Op <= "1000"; + Read_To_Reg <= '1'; + Rot_Akku <= '1'; + Save_ALU <= '1'; + +-- JUMP GROUP + when "11000011" => + -- JP nn + if Mode = 3 then + MCycles <= "100"; + else + MCycles <= "011"; + end if; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Inc_PC <= '1'; + Jump <= '1'; + if Mode /= 3 then + LDW <= '1'; + end if; + when others => null; + end case; + when "11000010"|"11001010"|"11010010"|"11011010"|"11100010"|"11101010"|"11110010"|"11111010" => + if IR(5) = '1' and Mode = 3 then + case IRB(4 downto 3) is + when "00" => + -- LD ($FF00+C),A + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + Set_BusB_To <= "0111"; + IORQ <= '1'; --TH must be earlier to be stable when address is generated + when 2 => + Write <= '1'; + when others => + end case; + when "01" => + -- LD (nn),A + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + Set_BusB_To <= "0111"; + when 4 => + Write <= '1'; + when others => null; + end case; + when "10" => + -- LD A,($FF00+C) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + IORQ <= '1'; --TH must be earlier to be stable when address is generated + when 2 => + Read_To_Acc <= '1'; + when others => + end case; + when "11" => + -- LD A,(nn) + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + when 4 => + Read_To_Acc <= '1'; + when others => null; + end case; + end case; + else + -- JP cc,nn + if Mode = 3 then + MCycles <= "100"; + else + MCycles <= "011"; + end if; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + if Mode /= 3 then + LDW <= '1'; + end if; + Inc_PC <= '1'; + if is_cc_true(F, to_bitvector(IR(5 downto 3))) then + Jump <= '1'; + elsif Mode = 3 then + MCycles <= "011"; + end if; + when others => null; + end case; + end if; + when "00011000" => + if Mode /= 2 then + -- JR e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + when "00111000" => + if Mode /= 2 then + -- JR C,e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + if F(Flag_C) = '0' then + MCycles <= "010"; + else + No_PC <= '1'; + end if; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + when "00110000" => + if Mode /= 2 then + -- JR NC,e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + if F(Flag_C) = '1' then + MCycles <= "010"; + else + No_PC <= '1'; + end if; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + when "00101000" => + if Mode /= 2 then + -- JR Z,e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + if F(Flag_Z) = '0' then + MCycles <= "010"; + else + No_PC <= '1'; + end if; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + when "00100000" => + if Mode /= 2 then + -- JR NZ,e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + if F(Flag_Z) = '1' then + MCycles <= "010"; + else + No_PC <= '1'; + end if; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + when "11101001" => + -- JP (HL) + JumpXY <= '1'; + when "00010000" => + if Mode = 3 then -- STOP and skip next byte + MCycles <= "010"; + I_DJNZ <= '1'; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + when others => null; + end case; + elsif Mode < 2 then + -- DJNZ,e + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + I_DJNZ <= '1'; + Set_BusB_To <= "1010"; + Set_BusA_To(2 downto 0) <= "000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0010"; + when 2 => + I_DJNZ <= '1'; + Inc_PC <= '1'; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + JumpE <= '1'; + TStates <= "101"; + when others => null; + end case; + end if; + +-- CALL AND RETURN GROUP + when "11001101" => + -- CALL nn + if Mode = 3 then + MCycles <= "110"; + else + MCycles <= "101"; + end if; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + IncDec_16 <= "1111"; + Inc_PC <= '1'; + TStates <= "100"; + Set_Addr_To <= aSP; + LDW <= '1'; + Set_BusB_To <= "1101"; + when 4 => + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 5 => + Write <= '1'; + Call <= '1'; + when others => null; + end case; + when "11000100"|"11001100"|"11010100"|"11011100"|"11100100"|"11101100"|"11110100"|"11111100" => + if IR(5) = '0' or Mode /= 3 then + -- CALL cc,nn + if Mode = 3 then + MCycles <= "110"; + else + MCycles <= "101"; + end if; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Inc_PC <= '1'; + LDW <= '1'; + if is_cc_true(F, to_bitvector(IR(5 downto 3))) then + IncDec_16 <= "1111"; + Set_Addr_TO <= aSP; + TStates <= "100"; + Set_BusB_To <= "1101"; + else + MCycles <= "011"; + end if; + when 4 => + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 5 => + Write <= '1'; + Call <= '1'; + when others => null; + end case; + end if; + when "11001001" => + -- RET + if Mode = 3 then + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + Set_Addr_TO <= aSP; + when 3 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 4 => + Jump <= '1'; + IncDec_16 <= "0111"; + when others => null; + end case; + else + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + --TStates <= "101"; + Set_Addr_TO <= aSP; + when 2 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 3 => + Jump <= '1'; + IncDec_16 <= "0111"; + when others => null; + end case; + end if; + when "11000000"|"11001000"|"11010000"|"11011000"|"11100000"|"11101000"|"11110000"|"11111000" => + if IR(5) = '1' and Mode = 3 then + case IRB(4 downto 3) is + when "00" => + -- LD ($FF00+nn),A + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_Addr_To <= aIOA; + Set_BusB_To <= "0111"; + when 3 => + Write <= '1'; + when others => null; + end case; + when "01" => + -- ADD SP,n + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 3 => + Inc_PC <= '1'; + ADDSPdd <= '1'; + when others => + end case; + when "10" => + -- LD A,($FF00+nn) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_Addr_To <= aIOA; + when 3 => + Read_To_Acc <= '1'; + when others => null; + end case; + when "11" => + -- LD HL,SP+n + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + Inc_PC <= '1'; + when 2 => + LDHLSP <= '1'; + Inc_PC <= '1'; + when 3 => + LDHLSP <= '1'; + when others => null; + end case; + end case; + else + -- RET cc + if Mode = 3 then + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + if is_cc_true(F, to_bitvector(IR(5 downto 3))) then + Set_Addr_TO <= aSP; + else + MCycles <= "010"; + end if; + TStates <= "101"; + when 3 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 4 => + Jump <= '1'; + IncDec_16 <= "0111"; + when others => null; + end case; + else + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + if is_cc_true(F, to_bitvector(IR(5 downto 3))) then + Set_Addr_TO <= aSP; + else + MCycles <= "001"; + end if; + TStates <= "101"; + when 2 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 3 => + Jump <= '1'; + IncDec_16 <= "0111"; + when others => null; + end case; + end if; + end if; + when "11000111"|"11001111"|"11010111"|"11011111"|"11100111"|"11101111"|"11110111"|"11111111" => + -- RST p + if Mode = 3 then + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 2 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1101"; + when 3 => + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 4 => + Write <= '1'; + RstP <= '1'; + when others => null; + end case; + else + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1101"; + when 2 => + Write <= '1'; + IncDec_16 <= "1111"; + Set_Addr_To <= aSP; + Set_BusB_To <= "1100"; + when 3 => + Write <= '1'; + RstP <= '1'; + when others => null; + end case; + end if; + +-- INPUT AND OUTPUT GROUP + when "11011011" => + if Mode /= 3 then + -- IN A,(n) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_Addr_To <= aIOA; + when 3 => + Read_To_Acc <= '1'; + IORQ <= '1'; + when others => null; + end case; + end if; + when "11010011" => + if Mode /= 3 then + -- OUT (n),A + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + Set_Addr_To <= aIOA; + Set_BusB_To <= "0111"; + when 3 => + Write <= '1'; + IORQ <= '1'; + when others => null; + end case; + end if; + +------------------------------------------------------------------------------ +------------------------------------------------------------------------------ +-- MULTIBYTE INSTRUCTIONS +------------------------------------------------------------------------------ +------------------------------------------------------------------------------ + + when "11001011" => + if Mode /= 2 then + Prefix <= "01"; + end if; + + when "11101101" => + if Mode < 2 then + Prefix <= "10"; + end if; + + when "11011101"|"11111101" => + if Mode < 2 then + Prefix <= "11"; + end if; + + end case; + + when "01" => + +------------------------------------------------------------------------------ +-- +-- CB prefixed instructions +-- +------------------------------------------------------------------------------ + + Set_BusA_To(2 downto 0) <= IR(2 downto 0); + Set_BusB_To(2 downto 0) <= IR(2 downto 0); + + case IRB is + when "00000000"|"00000001"|"00000010"|"00000011"|"00000100"|"00000101"|"00000111" + |"00010000"|"00010001"|"00010010"|"00010011"|"00010100"|"00010101"|"00010111" + |"00001000"|"00001001"|"00001010"|"00001011"|"00001100"|"00001101"|"00001111" + |"00011000"|"00011001"|"00011010"|"00011011"|"00011100"|"00011101"|"00011111" + |"00100000"|"00100001"|"00100010"|"00100011"|"00100100"|"00100101"|"00100111" + |"00101000"|"00101001"|"00101010"|"00101011"|"00101100"|"00101101"|"00101111" + |"00110000"|"00110001"|"00110010"|"00110011"|"00110100"|"00110101"|"00110111" + |"00111000"|"00111001"|"00111010"|"00111011"|"00111100"|"00111101"|"00111111" => + -- RLC r + -- RL r + -- RRC r + -- RR r + -- SLA r + -- SRA r + -- SRL r + -- SLL r (Undocumented) / SWAP r + if XY_State="00" then + if MCycle = "001" then + ALU_Op <= "1000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + end if; + else + -- R/S (IX+d),Reg, undocumented + MCycles <= "011"; + XYbit_undoc <= '1'; + case to_integer(unsigned(MCycle)) is + when 1 | 7=> + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => null; + end case; + end if; + + when "00000110"|"00010110"|"00001110"|"00011110"|"00101110"|"00111110"|"00100110"|"00110110" => + -- RLC (HL) + -- RL (HL) + -- RRC (HL) + -- RR (HL) + -- SRA (HL) + -- SRL (HL) + -- SLA (HL) + -- SLL (HL) (Undocumented) / SWAP (HL) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 | 7 => + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => + end case; + when "01000000"|"01000001"|"01000010"|"01000011"|"01000100"|"01000101"|"01000111" + |"01001000"|"01001001"|"01001010"|"01001011"|"01001100"|"01001101"|"01001111" + |"01010000"|"01010001"|"01010010"|"01010011"|"01010100"|"01010101"|"01010111" + |"01011000"|"01011001"|"01011010"|"01011011"|"01011100"|"01011101"|"01011111" + |"01100000"|"01100001"|"01100010"|"01100011"|"01100100"|"01100101"|"01100111" + |"01101000"|"01101001"|"01101010"|"01101011"|"01101100"|"01101101"|"01101111" + |"01110000"|"01110001"|"01110010"|"01110011"|"01110100"|"01110101"|"01110111" + |"01111000"|"01111001"|"01111010"|"01111011"|"01111100"|"01111101"|"01111111" => + -- BIT b,r + if XY_State="00" then + if MCycle = "001" then + Set_BusB_To(2 downto 0) <= IR(2 downto 0); + ALU_Op <= "1001"; + end if; + else + -- BIT b,(IX+d), undocumented + MCycles <= "010"; + XYbit_undoc <= '1'; + case to_integer(unsigned(MCycle)) is + when 1 | 7=> + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1001"; + TStates <= "100"; + when others => null; + end case; + end if; + + when "01000110"|"01001110"|"01010110"|"01011110"|"01100110"|"01101110"|"01110110"|"01111110" => + -- BIT b,(HL) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 | 7 => + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1001"; + TStates <= "100"; + when others => null; + end case; + when "11000000"|"11000001"|"11000010"|"11000011"|"11000100"|"11000101"|"11000111" + |"11001000"|"11001001"|"11001010"|"11001011"|"11001100"|"11001101"|"11001111" + |"11010000"|"11010001"|"11010010"|"11010011"|"11010100"|"11010101"|"11010111" + |"11011000"|"11011001"|"11011010"|"11011011"|"11011100"|"11011101"|"11011111" + |"11100000"|"11100001"|"11100010"|"11100011"|"11100100"|"11100101"|"11100111" + |"11101000"|"11101001"|"11101010"|"11101011"|"11101100"|"11101101"|"11101111" + |"11110000"|"11110001"|"11110010"|"11110011"|"11110100"|"11110101"|"11110111" + |"11111000"|"11111001"|"11111010"|"11111011"|"11111100"|"11111101"|"11111111" => + -- SET b,r + if XY_State="00" then + if MCycle = "001" then + ALU_Op <= "1010"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + end if; + else + -- SET b,(IX+d),Reg, undocumented + MCycles <= "011"; + XYbit_undoc <= '1'; + case to_integer(unsigned(MCycle)) is + when 1 | 7=> + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1010"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => null; + end case; + end if; + + when "11000110"|"11001110"|"11010110"|"11011110"|"11100110"|"11101110"|"11110110"|"11111110" => + -- SET b,(HL) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 | 7 => + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1010"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => null; + end case; + when "10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000111" + |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001111" + |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010111" + |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011111" + |"10100000"|"10100001"|"10100010"|"10100011"|"10100100"|"10100101"|"10100111" + |"10101000"|"10101001"|"10101010"|"10101011"|"10101100"|"10101101"|"10101111" + |"10110000"|"10110001"|"10110010"|"10110011"|"10110100"|"10110101"|"10110111" + |"10111000"|"10111001"|"10111010"|"10111011"|"10111100"|"10111101"|"10111111" => + -- RES b,r + if XY_State="00" then + if MCycle = "001" then + ALU_Op <= "1011"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + end if; + else + -- RES b,(IX+d),Reg, undocumented + MCycles <= "011"; + XYbit_undoc <= '1'; + case to_integer(unsigned(MCycle)) is + when 1 | 7=> + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1011"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => null; + end case; + end if; + + when "10000110"|"10001110"|"10010110"|"10011110"|"10100110"|"10101110"|"10110110"|"10111110" => + -- RES b,(HL) + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 | 7 => + Set_Addr_To <= aXY; + when 2 => + ALU_Op <= "1011"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_Addr_To <= aXY; + TStates <= "100"; + when 3 => + Write <= '1'; + when others => null; + end case; + end case; + + when others => + +------------------------------------------------------------------------------ +-- +-- ED prefixed instructions +-- +------------------------------------------------------------------------------ + + case IRB is + when "00000000"|"00000001"|"00000010"|"00000011"|"00000100"|"00000101"|"00000110"|"00000111" + |"00001000"|"00001001"|"00001010"|"00001011"|"00001100"|"00001101"|"00001110"|"00001111" + |"00010000"|"00010001"|"00010010"|"00010011"|"00010100"|"00010101"|"00010110"|"00010111" + |"00011000"|"00011001"|"00011010"|"00011011"|"00011100"|"00011101"|"00011110"|"00011111" + |"00100000"|"00100001"|"00100010"|"00100011"|"00100100"|"00100101"|"00100110"|"00100111" + |"00101000"|"00101001"|"00101010"|"00101011"|"00101100"|"00101101"|"00101110"|"00101111" + |"00110000"|"00110001"|"00110010"|"00110011"|"00110100"|"00110101"|"00110110"|"00110111" + |"00111000"|"00111001"|"00111010"|"00111011"|"00111100"|"00111101"|"00111110"|"00111111" + + + |"10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000110"|"10000111" + |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001110"|"10001111" + |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010110"|"10010111" + |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011110"|"10011111" + | "10100100"|"10100101"|"10100110"|"10100111" + | "10101100"|"10101101"|"10101110"|"10101111" + | "10110100"|"10110101"|"10110110"|"10110111" + | "10111100"|"10111101"|"10111110"|"10111111" + |"11000000"| "11000010" |"11000100"|"11000101"|"11000110"|"11000111" + |"11001000"| "11001010"|"11001011"|"11001100"|"11001101"|"11001110"|"11001111" + |"11010000"| "11010010"|"11010011"|"11010100"|"11010101"|"11010110"|"11010111" + |"11011000"| "11011010"|"11011011"|"11011100"|"11011101"|"11011110"|"11011111" + |"11100000"|"11100001"|"11100010"|"11100011"|"11100100"|"11100101"|"11100110"|"11100111" + |"11101000"|"11101001"|"11101010"|"11101011"|"11101100"|"11101101"|"11101110"|"11101111" + |"11110000"|"11110001"|"11110010" |"11110100"|"11110101"|"11110110"|"11110111" + |"11111000"|"11111001"|"11111010"|"11111011"|"11111100"|"11111101"|"11111110"|"11111111" => + null; -- NOP, undocumented + when "01110111"|"01111111" => + -- NOP, undocumented + null; +-- 8 BIT LOAD GROUP + when "01010111" => + -- LD A,I + Special_LD <= "100"; + TStates <= "101"; + when "01011111" => + -- LD A,R + Special_LD <= "101"; + TStates <= "101"; + when "01000111" => + -- LD I,A + Special_LD <= "110"; + TStates <= "101"; + when "01001111" => + -- LD R,A + Special_LD <= "111"; + TStates <= "101"; +-- 16 BIT LOAD GROUP + when "01001011"|"01011011"|"01101011"|"01111011" => + -- LD dd,(nn) + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + LDW <= '1'; + when 4 => + Read_To_Reg <= '1'; + if IR(5 downto 4) = "11" then + Set_BusA_To <= "1000"; + else + Set_BusA_To(2 downto 1) <= IR(5 downto 4); + Set_BusA_To(0) <= '1'; + end if; + Inc_WZ <= '1'; + Set_Addr_To <= aZI; + when 5 => + Read_To_Reg <= '1'; + if IR(5 downto 4) = "11" then + Set_BusA_To <= "1001"; + else + Set_BusA_To(2 downto 1) <= IR(5 downto 4); + Set_BusA_To(0) <= '0'; + end if; + when others => null; + end case; + when "01000011"|"01010011"|"01100011"|"01110011" => + -- LD (nn),dd + MCycles <= "101"; + case to_integer(unsigned(MCycle)) is + when 2 => + Inc_PC <= '1'; + LDZ <= '1'; + when 3 => + Set_Addr_To <= aZI; + Inc_PC <= '1'; + LDW <= '1'; + if IR(5 downto 4) = "11" then + Set_BusB_To <= "1000"; + else + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '1'; + Set_BusB_To(3) <= '0'; + end if; + when 4 => + Inc_WZ <= '1'; + Set_Addr_To <= aZI; + Write <= '1'; + if IR(5 downto 4) = "11" then + Set_BusB_To <= "1001"; + else + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '0'; + Set_BusB_To(3) <= '0'; + end if; + when 5 => + Write <= '1'; + when others => null; + end case; + when "10100000" | "10101000" | "10110000" | "10111000" => + -- LDI, LDD, LDIR, LDDR + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + IncDec_16 <= "1100"; -- BC + when 2 => + Set_BusB_To <= "0110"; + Set_BusA_To(2 downto 0) <= "111"; + ALU_Op <= "0000"; + Set_Addr_To <= aDE; + if IR(3) = '0' then + IncDec_16 <= "0110"; -- IX + else + IncDec_16 <= "1110"; + end if; + when 3 => + I_BT <= '1'; + TStates <= "101"; + Write <= '1'; + if IR(3) = '0' then + IncDec_16 <= "0101"; -- DE + else + IncDec_16 <= "1101"; + end if; + No_PC <= '1'; + when 4 => + NoRead <= '1'; + TStates <= "101"; + when others => null; + end case; + when "10100001" | "10101001" | "10110001" | "10111001" => + -- CPI, CPD, CPIR, CPDR + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + IncDec_16 <= "1100"; -- BC + when 2 => + Set_BusB_To <= "0110"; + Set_BusA_To(2 downto 0) <= "111"; + ALU_Op <= "0111"; + Save_ALU <= '1'; + PreserveC <= '1'; + if IR(3) = '0' then + IncDec_16 <= "0110"; + else + IncDec_16 <= "1110"; + end if; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + I_BC <= '1'; + TStates <= "101"; + No_PC <= '1'; + when 4 => + NoRead <= '1'; + TStates <= "101"; + when others => null; + end case; + when "01000100"|"01001100"|"01010100"|"01011100"|"01100100"|"01101100"|"01110100"|"01111100" => + -- NEG + Alu_OP <= "0010"; + Set_BusB_To <= "0111"; + Set_BusA_To <= "1010"; + Read_To_Acc <= '1'; + Save_ALU <= '1'; + when "01000110"|"01001110"|"01100110"|"01101110" => + -- IM 0 + IMode <= "00"; + when "01010110"|"01110110" => + -- IM 1 + IMode <= "01"; + when "01011110"|"01111110" => + -- IM 2 + IMode <= "10"; +-- 16 bit arithmetic + when "01001010"|"01011010"|"01101010"|"01111010" => + -- ADC HL,ss + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + No_PC <= '1'; + when 2 => + NoRead <= '1'; + ALU_Op <= "0001"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusA_To(2 downto 0) <= "101"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '1'; + when others => + Set_BusB_To <= "1000"; + end case; + TStates <= "100"; + SetWZ <= "11"; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0001"; + Set_BusA_To(2 downto 0) <= "100"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '0'; + when others => + Set_BusB_To <= "1001"; + end case; + when others => + end case; + when "01000010"|"01010010"|"01100010"|"01110010" => + -- SBC HL,ss + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + No_PC <= '1'; + when 2 => + NoRead <= '1'; + ALU_Op <= "0011"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusA_To(2 downto 0) <= "101"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + Set_BusB_To(0) <= '1'; + when others => + Set_BusB_To <= "1000"; + end case; + TStates <= "100"; + SetWZ <= "11"; + No_PC <= '1'; + when 3 => + NoRead <= '1'; + ALU_Op <= "0011"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + Set_BusA_To(2 downto 0) <= "100"; + case to_integer(unsigned(IR(5 downto 4))) is + when 0|1|2 => + Set_BusB_To(2 downto 1) <= IR(5 downto 4); + when others => + Set_BusB_To <= "1001"; + end case; + when others => + end case; + when "01101111" => + -- RLD -- Read in M2, not M3! fixed by Sorgelig + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Read_To_Reg <= '1'; + Set_BusB_To(2 downto 0) <= "110"; + Set_BusA_To(2 downto 0) <= "111"; + ALU_Op <= "1101"; + Save_ALU <= '1'; + No_PC <= '1'; + when 3 => + TStates <= "100"; + I_RLD <= '1'; + NoRead <= '1'; + Set_Addr_To <= aXY; + when 4 => + Write <= '1'; + when others => + end case; + when "01100111" => + -- RRD -- Read in M2, not M3! fixed by Sorgelig + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aXY; + when 2 => + Read_To_Reg <= '1'; + Set_BusB_To(2 downto 0) <= "110"; + Set_BusA_To(2 downto 0) <= "111"; + ALU_Op <= "1110"; + Save_ALU <= '1'; + No_PC <= '1'; + when 3 => + TStates <= "100"; + I_RRD <= '1'; + NoRead <= '1'; + Set_Addr_To <= aXY; + when 4 => + Write <= '1'; + when others => + end case; + when "01000101"|"01001101"|"01010101"|"01011101"|"01100101"|"01101101"|"01110101"|"01111101" => + -- RETI/RETN + MCycles <= "011"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_TO <= aSP; + when 2 => + IncDec_16 <= "0111"; + Set_Addr_To <= aSP; + LDZ <= '1'; + when 3 => + Jump <= '1'; + IncDec_16 <= "0111"; + LDW <= '1'; + I_RETN <= '1'; + when others => null; + end case; + when "01000000"|"01001000"|"01010000"|"01011000"|"01100000"|"01101000"|"01110000"|"01111000" => + -- IN r,(C) + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + SetWZ <= "01"; + when 2 => + IORQ <= '1'; + if IR(5 downto 3) /= "110" then + Read_To_Reg <= '1'; + Set_BusA_To(2 downto 0) <= IR(5 downto 3); + end if; + I_INRC <= '1'; + when others => + end case; + when "01000001"|"01001001"|"01010001"|"01011001"|"01100001"|"01101001"|"01110001"|"01111001" => + -- OUT (C),r + -- OUT (C),0 + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + Set_Addr_To <= aBC; + SetWZ <= "01"; + Set_BusB_To(2 downto 0) <= IR(5 downto 3); + if IR(5 downto 3) = "110" then + Set_BusB_To(3) <= '1'; + end if; + when 2 => + Write <= '1'; + IORQ <= '1'; + when others => + end case; + when "10100010" | "10101010" | "10110010" | "10111010" => + -- INI, IND, INIR, INDR + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + Set_Addr_To <= aBC; + Set_BusB_To <= "1010"; + Set_BusA_To <= "0000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0010"; + SetWZ <= "11"; + IncDec_16(3) <= IR(3); + when 2 => + IORQ <= '1'; + Set_BusB_To <= "0110"; + Set_Addr_To <= aXY; + when 3 => + if IR(3) = '0' then + IncDec_16 <= "0110"; + else + IncDec_16 <= "1110"; + end if; + Write <= '1'; + I_BTR <= '1'; + when 4 => + NoRead <= '1'; + TStates <= "101"; + when others => null; + end case; + when "10100011" | "10101011" | "10110011" | "10111011" => + -- OUTI, OUTD, OTIR, OTDR + MCycles <= "100"; + case to_integer(unsigned(MCycle)) is + when 1 => + TStates <= "101"; + Set_Addr_To <= aXY; + Set_BusB_To <= "1010"; + Set_BusA_To <= "0000"; + Read_To_Reg <= '1'; + Save_ALU <= '1'; + ALU_Op <= "0010"; + when 2 => + Set_BusB_To <= "0110"; + Set_Addr_To <= aBC; + SetWZ <= "11"; + IncDec_16(3) <= IR(3); + when 3 => + if IR(3) = '0' then + IncDec_16 <= "0110"; + else + IncDec_16 <= "1110"; + end if; + IORQ <= '1'; + Write <= '1'; + I_BTR <= '1'; + when 4 => + NoRead <= '1'; + TStates <= "101"; + when others => null; + end case; + when "11000001"|"11001001"|"11010001"|"11011001" => + --R800 MULUB + if R800_mode = '1' then + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + NoRead <= '1'; + I_MULUB <= '1'; + Set_BusB_To(2 downto 0) <= IR(5 downto 3); + Set_BusB_To(3) <= '0'; + when 2 => + NoRead <= '1'; + I_MULU <= '1'; + Set_BusA_To(2 downto 0) <= "100"; + when others => null; + end case; + end if; + when "11000011"|"11110011" => + --R800 MULUW + if R800_mode = '1' then + MCycles <= "010"; + case to_integer(unsigned(MCycle)) is + when 1 => + NoRead <= '1'; + if DPAIR = "11" then + Set_BusB_To(3 downto 0) <= "1000"; + else + Set_BusB_To(2 downto 1) <= DPAIR; + Set_BusB_To(0) <= '0'; + Set_BusB_To(3) <= '0'; + end if; + Set_BusA_To(2 downto 0) <= "100"; + when 2 => + TStates <= "101"; + NoRead <= '1'; + I_MULU <= '1'; + Set_BusA_To(2 downto 0) <= "100"; + when others => null; + end case; + end if; + end case; + + end case; + + if Mode = 1 then + if MCycle = "001" then +-- TStates <= "100"; + else + TStates <= "011"; + end if; + end if; + + if Mode = 3 then + if MCycle = "001" then +-- TStates <= "100"; + else + TStates <= "100"; + end if; + end if; + + if Mode < 2 then + if MCycle = "110" then + Inc_PC <= '1'; + if Mode = 1 then + Set_Addr_To <= aXY; + TStates <= "100"; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusB_To(3) <= '0'; + end if; + if IRB = "00110110" or IRB = "11001011" then + Set_Addr_To <= aNone; + end if; + if not (IRB = "00110110" or ISet = "01") then + No_PC <= '1'; + end if; + end if; + if MCycle = "111" then + if Mode = 0 then + TStates <= "101"; + end if; + if ISet /= "01" then + Set_Addr_To <= aXY; + end if; + Set_BusB_To(2 downto 0) <= SSS; + Set_BusB_To(3) <= '0'; + if IRB = "00110110" or ISet = "01" then + -- LD (HL),n + Inc_PC <= '1'; + else + NoRead <= '1'; + end if; + end if; + end if; + + end process; + +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Pack.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Pack.vhd new file mode 100644 index 0000000000000000000000000000000000000000..3ac15221eed3eb1df155a70547f31ca5012e64b7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Pack.vhd @@ -0,0 +1,248 @@ +-- **** +-- T80(b) core. In an effort to merge and maintain bug fixes .... +-- +-- +-- Ver 303 add undocumented DDCB and FDCB opcodes by TobiFlex 20.04.2010 +-- Ver 300 started tidyup +-- MikeJ March 2005 +-- Latest version from www.fpgaarcade.com (original www.opencores.org) +-- +-- **** +-- +-- Z80 compatible microprocessor core +-- +-- Version : 0250 +-- +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- Limitations : +-- +-- File history : +-- + +library IEEE; +use IEEE.std_logic_1164.all; + +package T80_Pack is + + constant aNone : std_logic_vector(2 downto 0) := "111"; + constant aBC : std_logic_vector(2 downto 0) := "000"; + constant aDE : std_logic_vector(2 downto 0) := "001"; + constant aXY : std_logic_vector(2 downto 0) := "010"; + constant aIOA : std_logic_vector(2 downto 0) := "100"; + constant aSP : std_logic_vector(2 downto 0) := "101"; + constant aZI : std_logic_vector(2 downto 0) := "110"; + + component T80 + generic( + Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB + IOWait : integer := 0; -- 1 => Single cycle I/O, 1 => Std I/O cycle + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + RESET_n : in std_logic; + CLK_n : in std_logic; + CEN : in std_logic; + WAIT_n : in std_logic; + INT_n : in std_logic; + NMI_n : in std_logic; + BUSRQ_n : in std_logic; + M1_n : out std_logic; + IORQ : out std_logic; + NoRead : out std_logic; + Write : out std_logic; + RFSH_n : out std_logic; + HALT_n : out std_logic; + BUSAK_n : out std_logic; + A : out std_logic_vector(15 downto 0); + DInst : in std_logic_vector(7 downto 0); + DI : in std_logic_vector(7 downto 0); + DO : out std_logic_vector(7 downto 0); + MC : out std_logic_vector(2 downto 0); + TS : out std_logic_vector(2 downto 0); + IntCycle_n : out std_logic; + IntE : out std_logic; + Stop : out std_logic; + R800_mode : in std_logic := '0'; + out0 : in std_logic := '0'; -- 0 => OUT(C),0, 1 => OUT(C),255 + REG : out std_logic_vector(211 downto 0); -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + DIRSet : in std_logic := '0'; + DIR : in std_logic_vector(211 downto 0) := (others => '0') -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + ); + end component; + + component T80_Reg + port( + Clk : in std_logic; + CEN : in std_logic; + WEH : in std_logic; + WEL : in std_logic; + AddrA : in std_logic_vector(2 downto 0); + AddrB : in std_logic_vector(2 downto 0); + AddrC : in std_logic_vector(2 downto 0); + DIH : in std_logic_vector(7 downto 0); + DIL : in std_logic_vector(7 downto 0); + DOAH : out std_logic_vector(7 downto 0); + DOAL : out std_logic_vector(7 downto 0); + DOBH : out std_logic_vector(7 downto 0); + DOBL : out std_logic_vector(7 downto 0); + DOCH : out std_logic_vector(7 downto 0); + DOCL : out std_logic_vector(7 downto 0); + DOR : out std_logic_vector(127 downto 0); + DIRSet : in std_logic; + DIR : in std_logic_vector(127 downto 0) + ); + end component; + + component T80_MCode + generic( + Mode : integer := 0; + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + IR : in std_logic_vector(7 downto 0); + ISet : in std_logic_vector(1 downto 0); + MCycle : in std_logic_vector(2 downto 0); + F : in std_logic_vector(7 downto 0); + NMICycle : in std_logic; + IntCycle : in std_logic; + XY_State : in std_logic_vector(1 downto 0); + MCycles : out std_logic_vector(2 downto 0); + TStates : out std_logic_vector(2 downto 0); + Prefix : out std_logic_vector(1 downto 0); -- None,BC,ED,DD/FD + Inc_PC : out std_logic; + Inc_WZ : out std_logic; + IncDec_16 : out std_logic_vector(3 downto 0); -- BC,DE,HL,SP 0 is inc + Read_To_Reg : out std_logic; + Read_To_Acc : out std_logic; + Set_BusA_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI/DB,A,SP(L),SP(M),0,F + Set_BusB_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI,A,SP(L),SP(M),1,F,PC(L),PC(M),0 + ALU_Op : out std_logic_vector(3 downto 0); + -- ADD, ADC, SUB, SBC, AND, XOR, OR, CP, ROT, BIT, SET, RES, DAA, RLD, RRD, None + Save_ALU : out std_logic; + Rot_Akku : out std_logic; + PreserveC : out std_logic; + Arith16 : out std_logic; + Set_Addr_To : out std_logic_vector(2 downto 0); -- aNone,aXY,aIOA,aSP,aBC,aDE,aZI + IORQ : out std_logic; + Jump : out std_logic; + JumpE : out std_logic; + JumpXY : out std_logic; + Call : out std_logic; + RstP : out std_logic; + LDZ : out std_logic; + LDW : out std_logic; + LDSPHL : out std_logic; + LDHLSP : out std_logic; + ADDSPdd : out std_logic; + Special_LD : out std_logic_vector(2 downto 0); -- A,I;A,R;I,A;R,A;None + ExchangeDH : out std_logic; + ExchangeRp : out std_logic; + ExchangeAF : out std_logic; + ExchangeRS : out std_logic; + ExchangeWH : out std_logic; + I_DJNZ : out std_logic; + I_CPL : out std_logic; + I_CCF : out std_logic; + I_SCF : out std_logic; + I_RETN : out std_logic; + I_BT : out std_logic; + I_BC : out std_logic; + I_BTR : out std_logic; + I_RLD : out std_logic; + I_RRD : out std_logic; + I_INRC : out std_logic; + I_MULUB : out std_logic; + I_MULU : out std_logic; + SetWZ : out std_logic_vector(1 downto 0); + SetDI : out std_logic; + SetEI : out std_logic; + IMode : out std_logic_vector(1 downto 0); + Halt : out std_logic; + NoRead : out std_logic; + Write : out std_logic; + R800_mode : in std_logic; + No_PC : out std_logic; + XYbit_undoc : out std_logic + ); + end component; + + component T80_ALU + generic( + Mode : integer := 0; + Flag_C : integer := 0; + Flag_N : integer := 1; + Flag_P : integer := 2; + Flag_X : integer := 3; + Flag_H : integer := 4; + Flag_Y : integer := 5; + Flag_Z : integer := 6; + Flag_S : integer := 7 + ); + port( + Arith16 : in std_logic; + Z16 : in std_logic; + WZ : in std_logic_vector(15 downto 0); + XY_State : in std_logic_vector(1 downto 0); + ALU_Op : in std_logic_vector(3 downto 0); + Rot_Akku : in std_logic; + IR : in std_logic_vector(5 downto 0); + ISet : in std_logic_vector(1 downto 0); + BusA : in std_logic_vector(7 downto 0); + BusB : in std_logic_vector(7 downto 0); + F_In : in std_logic_vector(7 downto 0); + Q : out std_logic_vector(7 downto 0); + F_Out : out std_logic_vector(7 downto 0) + ); + end component; + +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Reg.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Reg.vhd new file mode 100644 index 0000000000000000000000000000000000000000..e7e86454c36da39f42612d83c5759f7460f21db5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80_Reg.vhd @@ -0,0 +1,152 @@ +-------------------------------------------------------------------------------- +-- **** +-- T80(c) core. Attempt to finish all undocumented features and provide +-- accurate timings. +-- Version 350. +-- Copyright (c) 2018 Sorgelig +-- Test passed: ZEXDOC, ZEXALL, Z80Full(*), Z80memptr +-- (*) Currently only SCF and CCF instructions aren't passed X/Y flags check as +-- correct implementation is still unclear. +-- +-- **** +-- T80(b) core. In an effort to merge and maintain bug fixes .... +-- +-- +-- Ver 300 started tidyup +-- MikeJ March 2005 +-- Latest version from www.fpgaarcade.com (original www.opencores.org) +-- +-- **** +-- +-- T80 Registers, technology independent +-- +-- Version : 0244 +-- +-- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) +-- +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t51/ +-- +-- Limitations : +-- +-- File history : +-- +-- 0242 : Initial release +-- +-- 0244 : Changed to single register file +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; + +entity T80_Reg is + port( + Clk : in std_logic; + CEN : in std_logic; + WEH : in std_logic; + WEL : in std_logic; + AddrA : in std_logic_vector(2 downto 0); + AddrB : in std_logic_vector(2 downto 0); + AddrC : in std_logic_vector(2 downto 0); + DIH : in std_logic_vector(7 downto 0); + DIL : in std_logic_vector(7 downto 0); + DOAH : out std_logic_vector(7 downto 0); + DOAL : out std_logic_vector(7 downto 0); + DOBH : out std_logic_vector(7 downto 0); + DOBL : out std_logic_vector(7 downto 0); + DOCH : out std_logic_vector(7 downto 0); + DOCL : out std_logic_vector(7 downto 0); + DOR : out std_logic_vector(127 downto 0); + DIRSet : in std_logic; + DIR : in std_logic_vector(127 downto 0) + ); +end T80_Reg; + +architecture rtl of T80_Reg is + + type Register_Image is array (natural range <>) of std_logic_vector(7 downto 0); + signal RegsH : Register_Image(0 to 7); + signal RegsL : Register_Image(0 to 7); + +begin + + process (Clk) + begin + if rising_edge(Clk) then + if DIRSet = '1' then + RegsL(0) <= DIR( 7 downto 0); + RegsH(0) <= DIR( 15 downto 8); + + RegsL(1) <= DIR( 23 downto 16); + RegsH(1) <= DIR( 31 downto 24); + + RegsL(2) <= DIR( 39 downto 32); + RegsH(2) <= DIR( 47 downto 40); + + RegsL(3) <= DIR( 55 downto 48); + RegsH(3) <= DIR( 63 downto 56); + + RegsL(4) <= DIR( 71 downto 64); + RegsH(4) <= DIR( 79 downto 72); + + RegsL(5) <= DIR( 87 downto 80); + RegsH(5) <= DIR( 95 downto 88); + + RegsL(6) <= DIR(103 downto 96); + RegsH(6) <= DIR(111 downto 104); + + RegsL(7) <= DIR(119 downto 112); + RegsH(7) <= DIR(127 downto 120); + elsif CEN = '1' then + if WEH = '1' then + RegsH(to_integer(unsigned(AddrA))) <= DIH; + end if; + if WEL = '1' then + RegsL(to_integer(unsigned(AddrA))) <= DIL; + end if; + end if; + end if; + end process; + + DOAH <= RegsH(to_integer(unsigned(AddrA))); + DOAL <= RegsL(to_integer(unsigned(AddrA))); + DOBH <= RegsH(to_integer(unsigned(AddrB))); + DOBL <= RegsL(to_integer(unsigned(AddrB))); + DOCH <= RegsH(to_integer(unsigned(AddrC))); + DOCL <= RegsL(to_integer(unsigned(AddrC))); + DOR <= RegsH(7) & RegsL(7) & RegsH(6) & RegsL(6) & RegsH(5) & RegsL(5) & RegsH(4) & RegsL(4) & RegsH(3) & RegsL(3) & RegsH(2) & RegsL(2) & RegsH(1) & RegsL(1) & RegsH(0) & RegsL(0); + +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80pa.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80pa.vhd new file mode 100644 index 0000000000000000000000000000000000000000..7df3008a2674744e598f7551679688985ae3f578 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80pa.vhd @@ -0,0 +1,217 @@ +-- +-- Z80 compatible microprocessor core, preudo-asynchronous top level (by Sorgelig) +-- +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- File history : +-- +-- v1.0: convert to preudo-asynchronous model with original Z80 timings. +-- +-- v2.0: rewritten for more precise timings. +-- support for both CEN_n and CEN_p set to 1. Effective clock will be CLK/2. +-- +-- v2.1: Output Address 0 during non-bus MCycle (fix ZX contention) +-- +-- v2.2: Interrupt acknowledge cycle has been corrected +-- WAIT_n is broken in T80.vhd. Simulate correct WAIT_n locally. +-- +-- v2.3: Output last used Address during non-bus MCycle seems more correct. +-- +-- v2.4: Use the fixed WAIT_n in T80.vhd +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; +use work.T80_Pack.all; + +entity T80pa is + generic( + Mode : integer := 0 -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB + ); + port( + RESET_n : in std_logic; + CLK : in std_logic; + CEN_p : in std_logic := '1'; + CEN_n : in std_logic := '1'; + WAIT_n : in std_logic := '1'; + INT_n : in std_logic := '1'; + NMI_n : in std_logic := '1'; + BUSRQ_n : in std_logic := '1'; + M1_n : out std_logic; + MREQ_n : out std_logic; + IORQ_n : out std_logic; + RD_n : out std_logic; + WR_n : out std_logic; + RFSH_n : out std_logic; + HALT_n : out std_logic; + BUSAK_n : out std_logic; + OUT0 : in std_logic := '0'; -- 0 => OUT(C),0, 1 => OUT(C),255 + A : out std_logic_vector(15 downto 0); + DI : in std_logic_vector(7 downto 0); + DO : out std_logic_vector(7 downto 0); + R800_mode : in std_logic := '0'; + REG : out std_logic_vector(211 downto 0); -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + DIRSet : in std_logic := '0'; + DIR : in std_logic_vector(211 downto 0) := (others => '0') -- IFF2, IFF1, IM, IY, HL', DE', BC', IX, HL, DE, BC, PC, SP, R, I, F', A', F, A + ); +end T80pa; + +architecture rtl of T80pa is + + signal IntCycle_n : std_logic; + signal IntCycleD_n : std_logic_vector(1 downto 0); + signal IORQ : std_logic; + signal NoRead : std_logic; + signal Write : std_logic; + signal BUSAK : std_logic; + signal DI_Reg : std_logic_vector (7 downto 0); -- Input synchroniser + signal MCycle : std_logic_vector(2 downto 0); + signal TState : std_logic_vector(2 downto 0); + signal CEN_pol : std_logic; + signal CEN : std_logic; + signal Wait_s : std_logic; +begin + + CEN <= CEN_p and not CEN_pol; + BUSAK_n <= BUSAK; + + u0 : T80 + generic map( + Mode => Mode, + IOWait => 1 + ) + port map( + CEN => CEN, + M1_n => M1_n, + IORQ => IORQ, + NoRead => NoRead, + Write => Write, + RFSH_n => RFSH_n, + HALT_n => HALT_n, + WAIT_n => Wait_s, + INT_n => INT_n, + NMI_n => NMI_n, + RESET_n => RESET_n, + BUSRQ_n => BUSRQ_n, + BUSAK_n => BUSAK, + CLK_n => CLK, + A => A, + DInst => DI, -- valid at beginning of T3 + DI => DI_Reg, -- latched at middle of T3 + DO => DO, + REG => REG, + MC => MCycle, + TS => TState, + OUT0 => OUT0, + R800_mode => R800_mode, + IntCycle_n => IntCycle_n, + DIRSet => DIRSet, + DIR => DIR + ); + + process(CLK) + begin + if rising_edge(CLK) then + if RESET_n = '0' then + WR_n <= '1'; + RD_n <= '1'; + IORQ_n <= '1'; + MREQ_n <= '1'; + DI_Reg <= "00000000"; + CEN_pol <= '0'; + IntCycleD_n <= "11"; + elsif CEN_p = '1' and CEN_pol = '0' then + CEN_pol <= '1'; + if WAIT_s = '1' or TState /= "010" then + if MCycle = "001" then + if TState = "010" then + IORQ_n <= '1'; + MREQ_n <= '1'; + RD_n <= '1'; + end if; + else + if TState = "001" and IORQ = '1' then + WR_n <= not Write; + RD_n <= Write; + IORQ_n <= '0'; + end if; + end if; + end if; + elsif CEN_n = '1' and CEN_pol = '1' then + Wait_s <= Wait_n; + CEN_pol <= '0'; + if TState = "011" and BUSAK = '1' then + DI_Reg <= DI; + end if; + if MCycle = "001" then + if TState = "001" then + IntCycleD_n <= IntCycleD_n(0) & IntCycle_n; + RD_n <= not IntCycle_n; + MREQ_n <= not IntCycle_n; + IORQ_n <= IntCycleD_n(1); + end if; + if TState = "011" then + IntCycleD_n <= "11"; + RD_n <= '1'; + MREQ_n <= '0'; + end if; + if TState = "100" then + MREQ_n <= '1'; + end if; + else + if NoRead = '0' and IORQ = '0' then + if TState = "001" then + RD_n <= Write; + MREQ_n <= '0'; + end if; + end if; + if TState = "010" then + WR_n <= not Write; + end if; + if TState = "011" then + WR_n <= '1'; + RD_n <= '1'; + IORQ_n <= '1'; + MREQ_n <= '1'; + end if; + end if; + end if; + end if; + end process; +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80s.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80s.vhd new file mode 100644 index 0000000000000000000000000000000000000000..6967292c952882ff7f57312c8398684f90062aac --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/T80/T80s.vhd @@ -0,0 +1,193 @@ +-- +-- Z80 compatible microprocessor core, synchronous top level +-- Different timing than the original z80 +-- Inputs needs to be synchronous and outputs may glitch +-- +-- Version : 0242 +-- +-- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) +-- +-- All rights reserved +-- +-- Redistribution and use in source and synthezised forms, with or without +-- modification, are permitted provided that the following conditions are met: +-- +-- Redistributions of source code must retain the above copyright notice, +-- this list of conditions and the following disclaimer. +-- +-- Redistributions in synthesized form must reproduce the above copyright +-- notice, this list of conditions and the following disclaimer in the +-- documentation and/or other materials provided with the distribution. +-- +-- Neither the name of the author nor the names of other contributors may +-- be used to endorse or promote products derived from this software without +-- specific prior written permission. +-- +-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +-- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +-- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE +-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +-- POSSIBILITY OF SUCH DAMAGE. +-- +-- Please report bugs to the author, but before you do so, please +-- make sure that this is not a derivative work and that +-- you have the latest version of this file. +-- +-- The latest version of this file can be found at: +-- http://www.opencores.org/cvsweb.shtml/t80/ +-- +-- Limitations : +-- +-- File history : +-- +-- 0208 : First complete release +-- +-- 0210 : Fixed read with wait +-- +-- 0211 : Fixed interrupt cycle +-- +-- 0235 : Updated for T80 interface change +-- +-- 0236 : Added T2Write generic +-- +-- 0237 : Fixed T2Write with wait state +-- +-- 0238 : Updated for T80 interface change +-- +-- 0240 : Updated for T80 interface change +-- +-- 0242 : Updated for T80 interface change +-- + +library IEEE; +use IEEE.std_logic_1164.all; +use IEEE.numeric_std.all; +use IEEE.STD_LOGIC_UNSIGNED.all; +use work.T80_Pack.all; + +entity T80s is + generic( + Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB + T2Write : integer := 1; -- 0 => WR_n active in T3, /=0 => WR_n active in T2 + IOWait : integer := 1 -- 0 => Single cycle I/O, 1 => Std I/O cycle + ); + port( + RESET_n : in std_logic; + CLK : in std_logic; + CEN : in std_logic := '1'; + WAIT_n : in std_logic := '1'; + INT_n : in std_logic := '1'; + NMI_n : in std_logic := '1'; + BUSRQ_n : in std_logic := '1'; + M1_n : out std_logic; + MREQ_n : out std_logic; + IORQ_n : out std_logic; + RD_n : out std_logic; + WR_n : out std_logic; + RFSH_n : out std_logic; + HALT_n : out std_logic; + BUSAK_n : out std_logic; + OUT0 : in std_logic := '0'; -- 0 => OUT(C),0, 1 => OUT(C),255 + A : out std_logic_vector(15 downto 0); + DI : in std_logic_vector(7 downto 0); + DO : out std_logic_vector(7 downto 0) + ); +end T80s; + +architecture rtl of T80s is + + signal IntCycle_n : std_logic; + signal NoRead : std_logic; + signal Write : std_logic; + signal IORQ : std_logic; + signal DI_Reg : std_logic_vector(7 downto 0); + signal MCycle : std_logic_vector(2 downto 0); + signal TState : std_logic_vector(2 downto 0); + +begin + + u0 : T80 + generic map( + Mode => Mode, + IOWait => IOWait) + port map( + CEN => CEN, + M1_n => M1_n, + IORQ => IORQ, + NoRead => NoRead, + Write => Write, + RFSH_n => RFSH_n, + HALT_n => HALT_n, + WAIT_n => Wait_n, + INT_n => INT_n, + NMI_n => NMI_n, + RESET_n => RESET_n, + BUSRQ_n => BUSRQ_n, + BUSAK_n => BUSAK_n, + CLK_n => CLK, + A => A, + DInst => DI, + DI => DI_Reg, + DO => DO, + MC => MCycle, + TS => TState, + OUT0 => OUT0, + IntCycle_n => IntCycle_n + ); + + process (RESET_n, CLK) + begin + if RESET_n = '0' then + RD_n <= '1'; + WR_n <= '1'; + IORQ_n <= '1'; + MREQ_n <= '1'; + DI_Reg <= "00000000"; + elsif rising_edge(CLK) then + if CEN = '1' then + RD_n <= '1'; + WR_n <= '1'; + IORQ_n <= '1'; + MREQ_n <= '1'; + if MCycle = 1 then + if TState = 1 or (TState = 2 and Wait_n = '0') then + RD_n <= not IntCycle_n; + MREQ_n <= not IntCycle_n; + IORQ_n <= IntCycle_n; + end if; + if TState = 3 then + MREQ_n <= '0'; + end if; + else + if (TState = 1 or (TState = 2 and Wait_n = '0')) and NoRead = '0' and Write = '0' then + RD_n <= '0'; + IORQ_n <= not IORQ; + MREQ_n <= IORQ; + end if; + if T2Write = 0 then + if TState = 2 and Write = '1' then + WR_n <= '0'; + IORQ_n <= not IORQ; + MREQ_n <= IORQ; + end if; + else + if (TState = 1 or (TState = 2 and Wait_n = '0')) and Write = '1' then + WR_n <= '0'; + IORQ_n <= not IORQ; + MREQ_n <= IORQ; + end if; + end if; + end if; + if TState = 2 and Wait_n = '1' then + DI_Reg <= DI; + end if; + end if; + end if; + end process; +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_68k.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_68k.v new file mode 100644 index 0000000000000000000000000000000000000000..16606f52f6da65f0c474b65fee508ca10f94edc5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_68k.v @@ -0,0 +1,83 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2019 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module cpu_68k( + input CLK, + input CLK_EN_68K_P, //CLK_68KCLK + input CLK_EN_68K_N, + input nRESET, + input IPL2, IPL1, IPL0, + input nDTACK, + output [23:1] M68K_ADDR, + input [15:0] FX68K_DATAIN, + output [15:0] FX68K_DATAOUT, + output nLDS, nUDS, + output nAS, + output M68K_RW, + output FC2, FC1, FC0, + output nBG, + input nBR, nBGACK, + input SYSTEM_CDx + +); + +wire EN_PHI1 = CLK_EN_68K_P; +wire EN_PHI2 = CLK_EN_68K_N; + +reg reset; +always @(posedge CLK) + if (EN_PHI2) reset <= ~nRESET; + +fx68k FX68K( + .clk(CLK), + .extReset(reset), + .pwrUp(reset), + + .enPhi1(EN_PHI1), + .enPhi2(EN_PHI2), + + .eRWn(M68K_RW), + .ASn(nAS), + .UDSn(nUDS), + .LDSn(nLDS), + + .BGn(nBG), + .BRn(nBR), + .BGACKn(nBGACK), + + .DTACKn(nDTACK), + + .VPAn(SYSTEM_CDx | nAS | ~&M68K_ADDR[23:4]), //VPA must be fired only in IACK cycle! (NeoGeo doesn't use FC) + .BERRn(1'b1), + + .IPL0n(IPL0), + .IPL1n(IPL1), + .IPL2n(IPL2), + + .FC0(FC0), + .FC1(FC1), + .FC2(FC2), + + .iEdb(FX68K_DATAIN), + .oEdb(FX68K_DATAOUT), + .eab(M68K_ADDR) + ); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_z80.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_z80.v new file mode 100644 index 0000000000000000000000000000000000000000..f0559eb2fe82b6a336234d92d9168837bc199381 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/cpu/cpu_z80.v @@ -0,0 +1,58 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// Z80 CPU plug into TV80 core + +module cpu_z80( + input CLK, + input CLK4P_EN, + input CLK4N_EN, + input nRESET, + input [7:0] SDD_IN, + output [7:0] SDD_OUT, + output [15:0] SDA, + output reg nIORQ, + output nMREQ, + output reg nRD, nWR, + input nBUSRQ, + output nBUSAK, + input nINT, nNMI, nWAIT +); + + wire RFSH_n, MREQ_n; + assign nMREQ = MREQ_n | ~RFSH_n; + + T80pa cpu( + .RESET_n(nRESET), + .CLK(CLK), + .CEN_p(CLK4P_EN), + .CEN_n(CLK4N_EN), + .WAIT_n(nWAIT), + .INT_n(nINT), + .NMI_n(nNMI), + .MREQ_n(MREQ_n), + .IORQ_n(nIORQ), + .RD_n(nRD), + .WR_n(nWR), + .RFSH_n(RFSH_n), + .BUSRQ_n(nBUSRQ), + .BUSAK_n(nBUSAK), + .A(SDA), + .DI(SDD_IN), + .DO(SDD_OUT) + ); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_inputs.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_inputs.v new file mode 100644 index 0000000000000000000000000000000000000000..45954201c3fd38f5cfd4dd41643aa0d891fc4c11 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_inputs.v @@ -0,0 +1,40 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module c1_inputs( + input nCTRL1_ZONE, + input nCTRL2_ZONE, + input nSTATUSB_ZONE, + output [15:8] M68K_DATA, + input [9:0] P1_IN, + input [9:0] P2_IN, + input nWP, nCD2, nCD1, + input SYSTEM_TYPE +); + + // REG_P1CNT + assign M68K_DATA[15:8] = nCTRL1_ZONE ? 8'bzzzzzzzz : P1_IN[7:0]; + // REG_P2CNT + assign M68K_DATA[15:8] = nCTRL2_ZONE ? 8'bzzzzzzzz : P2_IN[7:0]; + + // REG_STATUS_B + assign M68K_DATA[15:8] = nSTATUSB_ZONE ? 8'bzzzzzzzz : {SYSTEM_TYPE, nWP, nCD2, nCD1, P2_IN[9:8], P1_IN[9:8]}; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_regs.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_regs.v new file mode 100644 index 0000000000000000000000000000000000000000..596bb5507dfcd09c64e8939076cc0a31ce5e21ab --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_regs.v @@ -0,0 +1,71 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module c1_regs( + input CLK, + input nICOM_ZONE, + input RW, + inout [15:8] M68K_DATA, + output [7:0] SDD_RD, + input [7:0] SDD_WR, + input nSDZ80R, nSDZ80W, nSDZ80CLR, + output nSDW +); + + reg [7:0] SDD_LATCH_CMD; + reg [7:0] SDD_LATCH_REP; + + // Z80 command read + assign SDD_RD = SDD_LATCH_CMD; //nSDZ80R ? 8'bzzzzzzzz : SDD_LATCH_CMD; + + // Z80 reply write + always @(posedge CLK) begin + reg nSDZ80W_d; + nSDZ80W_d <= nSDZ80W; + if (nSDZ80W & ~nSDZ80W_d) + SDD_LATCH_REP <= SDD_WR; + end + + // REG_SOUND read + assign M68K_DATA = (RW & ~nICOM_ZONE) ? SDD_LATCH_REP : 8'bzzzzzzzz; + + // REG_SOUND write + assign nSDW = (RW | nICOM_ZONE); // Tells Z80 that 68k sent a command + + // REG_SOUND write + always @(posedge CLK) // Which one has priority ? + begin + reg nICOM_ZONE_d; + reg nSDZ80CLR_d; + nICOM_ZONE_d <= nICOM_ZONE; + nSDZ80CLR_d <= nSDZ80CLR; + + if (!nSDZ80CLR & nSDZ80CLR_d) + begin + SDD_LATCH_CMD <= 8'b00000000; + end + else + if (!nICOM_ZONE & nICOM_ZONE_d) begin + if (!RW) + SDD_LATCH_CMD <= M68K_DATA; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_wait.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_wait.v new file mode 100644 index 0000000000000000000000000000000000000000..0b99dab62bd9ea6e715e828ced2b9031a6eb9166 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/c1_wait.v @@ -0,0 +1,55 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module c1_wait( + input CLK, CLK_EN_68K_P, nAS, + input SYSTEM_CDx, + input nROM_ZONE, nWRAM_ZONE, nPORT_ZONE, nCARD_ZONE, nSROM_ZONE, + input nROMWAIT, nPWAIT0, nPWAIT1, PDTACK, + output nDTACK +); + + reg [2:0] WAIT_CNT; + + //assign nPDTACK = ~(nPORT_ZONE | PDTACK); // Really a NOR ? May stall CPU if PDTACK = GND + + assign nDTACK = nAS | WAIT_MUX; + + // When nROMWAIT == 1, nDTACK = nAS for nROM_ZONE (no wait) + wire WAIT_MUX = (!nROM_ZONE & !nROMWAIT) ? (WAIT_CNT > 3) : + (!nPORT_ZONE & ( nPWAIT1 & !nPWAIT0)) ? (WAIT_CNT > 3) : + (!nPORT_ZONE & (!nPWAIT1 & nPWAIT0)) ? (WAIT_CNT > 2) : + (!nCARD_ZONE) ? (WAIT_CNT > 3) : // Maybe 2 but not important here, used JEIDA compliance + 1'b0; + + always @(posedge CLK) + if (CLK_EN_68K_P) begin + if (!nAS) + begin + if (WAIT_CNT) + WAIT_CNT <= WAIT_CNT - 1'b1; + end + else + begin + WAIT_CNT <= 5; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/clocks.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/clocks.v new file mode 100644 index 0000000000000000000000000000000000000000..4d5076f853e7f4e1b3d597b8a4ed5c6dd97cdaa0 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/clocks.v @@ -0,0 +1,77 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// Everything here was verified on a MV4 board +// Todo: Check phase relations between 12M, 68KCLK and 68KCLKB +// Todo: Check cycle right after nRESETP goes high, real hw might have an important delay added + +module clocks_sync( + input CLK, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + input nRESETP, + output CLK_24M, + output CLK_12M, + output reg CLK_68KCLK, + output CLK_68KCLKB, + output CLK_EN_68K_P, + output CLK_EN_68K_N, + output CLK_6MB, + output reg CLK_1HB, + output CLK_EN_12M, + output CLK_EN_12M_N, + output CLK_EN_6MB, + output CLK_EN_1HB +); + + reg [2:0] CLK_DIV; + wire CLK_3M; + + assign CLK_68KCLKB = ~CLK_68KCLK; + + always @(posedge CLK or negedge nRESETP) + begin + if (!nRESETP) + CLK_68KCLK <= 1'b0; // Thanks ElectronAsh ! Real hw doesn't clearly init DFF + else if (CLK_EN_24M_P) + CLK_68KCLK <= ~CLK_68KCLK; // MV4 C4:A + end + assign CLK_EN_68K_P = ~CLK_68KCLK & CLK_EN_24M_P; + assign CLK_EN_68K_N = CLK_68KCLK & CLK_EN_24M_P; + + always @(posedge CLK, negedge nRESETP) + begin + if (!nRESETP) + CLK_DIV <= 3'b100; + else if (CLK_EN_24M_N) + CLK_DIV <= CLK_DIV + 1'b1; + end + + assign CLK_24M = CLK_EN_24M_N; + assign CLK_12M = CLK_DIV[0]; + assign CLK_EN_12M = CLK_EN_24M_N & ~CLK_DIV[0]; + assign CLK_EN_12M_N = CLK_EN_24M_N & CLK_DIV[0]; + assign CLK_6MB = ~CLK_DIV[1]; + assign CLK_3M = CLK_DIV[2]; + + // MV4 C4:B + always @(posedge CLK) + if (CLK_EN_12M) CLK_1HB <= ~CLK_3M; + + assign CLK_EN_6MB = CLK_EN_24M_N & CLK_DIV[1:0] == 3; + assign CLK_EN_1HB = CLK_EN_24M_N & CLK_DIV == 0; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/com.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/com.v new file mode 100644 index 0000000000000000000000000000000000000000..61f1e8fc8568ed8a631439665c57b997f208ddd1 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/com.v @@ -0,0 +1,53 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2019 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// This simulates the COM MCU idle reply to make Riding Hero run at normal speed + +module com( + input nRESET, + input CLK_48M, + input nPORTOEL, + input nPORTOEU, + input nPORTWEL, + output [15:0] M68K_DIN +); + +reg nPORTWEL_PREV, TOGGLE_BIT; + +assign M68K_DIN[15:8] = nPORTOEU ? 8'bzzzzzzzz : {4'b0000, TOGGLE_BIT ,3'b000}; +assign M68K_DIN[7:0] = nPORTOEL ? 8'bzzzzzzzz : 8'h00; + +always @(posedge CLK_48M) +begin + if (!nRESET) + begin + TOGGLE_BIT <= 1'b0; + end + else + begin + nPORTWEL_PREV <= nPORTWEL; + + // Detect rising edge of nPORTWEL + if (~nPORTWEL_PREV & nPORTWEL) + TOGGLE_BIT <= ~TOGGLE_BIT; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_c1.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_c1.v new file mode 100644 index 0000000000000000000000000000000000000000..721bafa789467e65d6a05fbad21520ae9f5efc29 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_c1.v @@ -0,0 +1,161 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// Missing pin: VPA +// All address decoding was checked except BITW1, nCTRL1_ZONE, and nCTRL2_ZONE + +module neo_c1( + input CLK, + input [21:17] M68K_ADDR, + inout [15:8] M68K_DATA, + input A22Z, A23Z, + input nLDS, nUDS, + input RW, nAS, + output nROMOEL, nROMOEU, + output nPORTOEL, nPORTOEU, + output nPORTWEL, nPORTWEU, + output nPORT_ZONE, + output nWRL, nWRU, + output nWWL, nWWU, + output nSROMOEL, nSROMOEU, + output nSRAMOEL, nSRAMOEU, + output nSRAMWEL, nSRAMWEU, + output nLSPOE, nLSPWE, + output nCRDO, nCRDW, nCRDC, + output nSDW, + input [9:0] P1_IN, + input [9:0] P2_IN, + input nCD1, nCD2, nWP, + input nROMWAIT, nPWAIT0, nPWAIT1, PDTACK, + input [7:0] SDD_WR, + output [7:0] SDD_RD, + input nSDZ80R, nSDZ80W, nSDZ80CLR, + input CLK_EN_68K_P, + output nDTACK, + output nBITW0, nBITW1, nDIPRD0, nDIPRD1, + output nPAL_ZONE, + input [1:0] SYSTEM_TYPE +); + + wire nIO_ZONE; // Internal + wire nC1REGS_ZONE; // Internal + wire nROM_ZONE; // Internal + wire nWRAM_ZONE; // Internal (external for PCB) + wire nCTRL1_ZONE; // Internal (external for PCB) + wire nICOM_ZONE; // Internal + wire nCTRL2_ZONE; // Internal (external for PCB) + wire nSTATUSB_ZONE; // Internal (external for PCB) + wire nLSPC_ZONE; // Internal + wire nCARD_ZONE; // Internal + wire nSROM_ZONE; // Internal + wire nSRAM_ZONE; // Internal (external for PCB) + + c1_regs C1REGS(CLK, nICOM_ZONE, RW, M68K_DATA, SDD_RD, SDD_WR, nSDZ80R, nSDZ80W, nSDZ80CLR, nSDW); + + c1_wait C1WAIT(CLK, CLK_EN_68K_P, nAS, SYSTEM_TYPE[1], nROM_ZONE, nWRAM_ZONE, nPORT_ZONE, nCARD_ZONE, nSROM_ZONE, + nROMWAIT, nPWAIT0, nPWAIT1, PDTACK, nDTACK); + + c1_inputs C1INPUTS(nCTRL1_ZONE, nCTRL2_ZONE, nSTATUSB_ZONE, M68K_DATA, P1_IN, P2_IN, + nWP, nCD2, nCD1, SYSTEM_TYPE[0]); + + // 000000~0FFFFF read/write + assign nROM_ZONE = |{A23Z, A22Z, M68K_ADDR[21], M68K_ADDR[20]}; + + // 100000~1FFFFF read/write + assign nWRAM_ZONE = |{A23Z, A22Z, M68K_ADDR[21], ~M68K_ADDR[20]}; + + // 200000~2FFFFF read/write + assign nPORT_ZONE = |{A23Z, A22Z, ~M68K_ADDR[21], M68K_ADDR[20]}; + + // 300000~3FFFFF read/write + assign nIO_ZONE = |{A23Z, A22Z, ~M68K_ADDR[21], ~M68K_ADDR[20]}; + + // 300000~3FFFFE even bytes read/write + assign nC1REGS_ZONE = nUDS | nIO_ZONE; + + // 300000~31FFFE even bytes read only + assign nCTRL1_ZONE = nC1REGS_ZONE | ~RW | |{M68K_ADDR[19], M68K_ADDR[18], M68K_ADDR[17]}; + + // 320000~33FFFE even bytes read/write + assign nICOM_ZONE = nC1REGS_ZONE | |{M68K_ADDR[19], M68K_ADDR[18], ~M68K_ADDR[17]}; + + // 340000~35FFFE even bytes read only - Todo: MAME says A17 is used, see right below + assign nCTRL2_ZONE = nC1REGS_ZONE | ~RW | |{M68K_ADDR[19], ~M68K_ADDR[18], M68K_ADDR[17]}; + // 360000~37FFFF is not mapped ? + + // 30xxxx 31xxxx odd bytes read only + assign nDIPRD0 = |{nIO_ZONE, M68K_ADDR[19], M68K_ADDR[18], M68K_ADDR[17], ~RW, nLDS}; + + // 32xxxx 33xxxx odd bytes read only + assign nDIPRD1 = |{nIO_ZONE, M68K_ADDR[19], M68K_ADDR[18], ~M68K_ADDR[17], ~RW, nLDS}; + + // 38xxxx 39xxxx odd bytes write only + assign nBITW0 = |{nIO_ZONE, ~M68K_ADDR[19], M68K_ADDR[18], M68K_ADDR[17], RW, nLDS}; + + // 380000~39FFFE even bytes read only + assign nSTATUSB_ZONE = nC1REGS_ZONE | ~RW | |{~M68K_ADDR[19], M68K_ADDR[18], M68K_ADDR[17]}; + + // 3A0001~3BFFFF odd bytes write only + assign nBITW1 = |{nIO_ZONE, ~M68K_ADDR[19], M68K_ADDR[18], ~M68K_ADDR[17], RW, nLDS}; + + // 3C0000~3DFFFF + assign nLSPC_ZONE = |{nIO_ZONE, ~M68K_ADDR[19], ~M68K_ADDR[18], M68K_ADDR[17]}; + + // 3E0000~3FFFFF is not mapped ? To check + + // 400000~7FFFFF + assign nPAL_ZONE = |{A23Z, ~A22Z, (nLDS & nUDS)}; + + // 800000~BFFFFF + assign nCARD_ZONE = |{~A23Z, A22Z}; + + // C00000~CFFFFF + assign nSROM_ZONE = |{~A23Z, ~A22Z, M68K_ADDR[21], M68K_ADDR[20]}; + + // D00000~DFFFFF + assign nSRAM_ZONE = |{~A23Z, ~A22Z, M68K_ADDR[21], ~M68K_ADDR[20]}; + + // Outputs: + assign nROMOEL = ~RW | nLDS | nROM_ZONE; + assign nROMOEU = ~RW | nUDS | nROM_ZONE; + assign nPORTOEL = ~RW | nLDS | nPORT_ZONE; + assign nPORTOEU = ~RW | nUDS | nPORT_ZONE; + assign nPORTWEL = RW | nLDS | nPORT_ZONE; + assign nPORTWEU = RW | nUDS | nPORT_ZONE; + assign nWRL = ~RW | nLDS | nWRAM_ZONE; + assign nWRU = ~RW | nUDS | nWRAM_ZONE; + assign nWWL = RW | nLDS | nWRAM_ZONE; + assign nWWU = RW | nUDS | nWRAM_ZONE; + assign nSROMOEL = ~RW | nLDS | nSROM_ZONE; + assign nSROMOEU = ~RW | nUDS | nSROM_ZONE; + assign nSRAMOEL = ~RW | nLDS | nSRAM_ZONE; + assign nSRAMOEU = ~RW | nUDS | nSRAM_ZONE; + assign nSRAMWEL = RW | nLDS | nSRAM_ZONE; + assign nSRAMWEU = RW | nUDS | nSRAM_ZONE; + + // Todo: Check if TG68k duplicates byte on data bus on byte writes (it should !) + assign nLSPWE = RW | nUDS | nLSPC_ZONE; + assign nLSPOE = ~RW | nUDS | nLSPC_ZONE; + + assign nCRDO = ~RW | nCARD_ZONE | nLDS; + assign nCRDW = RW | nCARD_ZONE | nLDS; + assign nCRDC = nCARD_ZONE | nAS; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_d0.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_d0.v new file mode 100644 index 0000000000000000000000000000000000000000..8c0b26727fe060b689dc38dfa5e78a11d880cd69 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_d0.v @@ -0,0 +1,78 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// All pins ok except TRES, but apparently never used (something to do with crystal oscillator ?) + +module neo_d0( + input CLK, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + output CLK_24M, + input nRESET, nRESETP, + output CLK_12M, + output CLK_68KCLK, + output CLK_68KCLKB, + output CLK_EN_68K_P, + output CLK_EN_68K_N, + output CLK_6MB, + output CLK_1HB, + output CLK_EN_12M, + output CLK_EN_12M_N, + output CLK_EN_6MB, + output CLK_EN_1HB, + input M68K_ADDR_A4, + input nBITWD0, + input [5:0] M68K_DATA, + input [15:11] SDA_H, + input [4:2] SDA_L, + input nSDRD, nSDWR, nMREQ, nIORQ, + output nZ80NMI, + input nSDW, + output nSDZ80R, nSDZ80W, nSDZ80CLR, + output nSDROM, nSDMRD, nSDMWR, + output SDRD0, SDRD1, + output n2610CS, n2610RD, n2610WR, + output nZRAMCS, + output [2:0] BNK, + output [2:0] P1_OUT, + output [2:0] P2_OUT +); + reg [2:0] REG_BNK; + reg [5:0] REG_OUT; + + // Clock divider part + clocks_sync CLKS(CLK, CLK_EN_24M_P, CLK_EN_24M_N, nRESETP, CLK_24M, CLK_12M, CLK_68KCLK, CLK_68KCLKB, CLK_EN_68K_P, CLK_EN_68K_N, CLK_6MB, CLK_1HB, CLK_EN_12M, CLK_EN_12M_N, CLK_EN_6MB, CLK_EN_1HB); + + // Z80 controller part + z80ctrl Z80CTRL(CLK, SDA_L, SDA_H, nSDRD, nSDWR, nMREQ, nIORQ, nSDW, nRESET, nZ80NMI, nSDZ80R, nSDZ80W, + nSDZ80CLR, nSDROM, nSDMRD, nSDMWR, SDRD0, SDRD1, n2610CS, n2610RD, n2610WR, nZRAMCS); + + assign {P2_OUT, P1_OUT} = REG_OUT; + assign BNK = REG_BNK; + + always @(posedge CLK) begin + reg nBITWD0_d; + nBITWD0_d <= nBITWD0; + if (!nBITWD0 & nBITWD0_d) begin + if (M68K_ADDR_A4) + REG_BNK <= M68K_DATA[2:0]; + else + REG_OUT <= M68K_DATA[5:0]; + end + if(~nRESETP) {REG_BNK, REG_OUT} <= 0; + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_e0.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_e0.v new file mode 100644 index 0000000000000000000000000000000000000000..a3771195917be1f2a22562f5d33b6ddb71bf1e69 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_e0.v @@ -0,0 +1,41 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module neo_e0( + input [23:1] M68K_ADDR, + input [2:0] BNK, + input nSROMOEU, nSROMOEL, + output nSROMOE, + input nVEC, + output A23Z, A22Z, + output [23:0] CDA +); + + assign nSROMOE = nSROMOEU & nSROMOEL; + + // Vector table swap + // A2*Z = 1 if nVEC == 0 and A == 11000000000000000xxxxxxx + assign {A23Z, A22Z} = M68K_ADDR[23:22] ^ {2{~|{M68K_ADDR[21:7], ^M68K_ADDR[23:22], nVEC}}}; + + // Todo: Check this on real hw (MV4 ?) + // Memcard area is $800000~$BFFFFF, each word is mapped to one byte + // 10000000 00000000 00000000 + // 10111111 11111111 11111111 + // --xxxxxx xxxxxxxx xxxxxxx- + // bbbaaaaa aaaaaaaa aaaaaaaa + assign CDA = {BNK, M68K_ADDR[21:1]}; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_f0.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_f0.v new file mode 100644 index 0000000000000000000000000000000000000000..32dd248c8b41acfb3796783c4acc7560b6eaea7c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_f0.v @@ -0,0 +1,115 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module neo_f0( + input CLK, + input nRESET, + input nDIPRD0, + input nDIPRD1, // Also called "IN3" + input nBITW0, + output nBITWD0, // "nBITW0 for NEO-D0" + input [7:0] DIPSW, + input COIN1, COIN2, + input [7:4] M68K_ADDR, + inout [7:0] M68K_DATA, + input SYSTEMB, + output [5:0] nSLOT, + output SLOTA, SLOTB, SLOTC, + output reg [2:0] LED_LATCH, + output reg [7:0] LED_DATA, + + input RTC_DOUT, RTC_TP, + output RTC_DIN, RTC_CLK, RTC_STROBE, + + output nCOUNTOUT, + + input SYSTEM_TYPE + + //output [3:0] EL_OUT, + //output [8:0] LED_OUT1, + //output [8:0] LED_OUT2 +); + + reg [2:0] REG_RTCCTRL; + reg [2:0] SLOTS; + + // Todo: verify + // This is used (among other things) for the RTC + assign nBITWD0 = |{nBITW0, M68K_ADDR[6:5]}; + + // Todo: verify + // This is used to select NEO-I0 + assign nCOUNTOUT = |{nBITW0, ~M68K_ADDR[6:5]}; + + assign RTC_DIN = REG_RTCCTRL[0]; + assign RTC_CLK = REG_RTCCTRL[1]; + assign RTC_STROBE = REG_RTCCTRL[2]; + + // REG_DIPSW $300001~?, odd bytes + // REG_SYSTYPE $300081~?, odd bytes (TODO: Test switch and stuff... Neutral for now) + assign M68K_DATA = nDIPRD0 ? 8'bzzzzzzzz : + (M68K_ADDR[7]) ? 8'b10000000 : + DIPSW; + + // REG_STATUS_A $320001~?, odd bytes + // In console mode, reading REG_STATUS_A returns 00. This is used by the Unibios to detect the system type. It detects console if read value is $FF or [4:3] = 0. + assign M68K_DATA = nDIPRD1 ? 8'bzzzzzzzz : + SYSTEM_TYPE ? {RTC_DOUT, RTC_TP, 4'b0111, COIN2, COIN1} : 8'h00; + + reg nBITW0_d; + always @(posedge CLK) + nBITW0_d <= nBITW0; + + always @(posedge CLK) + begin + if (!nRESET) + begin + SLOTS <= 3'b000; + REG_RTCCTRL <= 3'b000; + end + else if (!nBITW0 & nBITW0_d) + begin + case (M68K_ADDR[6:4]) + 3'b010: + SLOTS <= M68K_DATA[2:0]; // REG_SLOT $380021 + 3'b011: + LED_LATCH <= M68K_DATA[5:3]; // REG_LEDLATCHES $380031 + 3'b100: + LED_DATA <= M68K_DATA[7:0]; // REG_LEDDATA $380041 + 3'b101: + REG_RTCCTRL <= M68K_DATA[2:0]; // REG_RTCCTRL $380051 + endcase + end + end + + assign {SLOTC, SLOTB, SLOTA} = SYSTEMB ? SLOTS : 3'b000; // Maybe not + + // TODO: check this + assign nSLOT = SYSTEMB ? + (SLOTS == 3'b000) ? 6'b111110 : + (SLOTS == 3'b001) ? 6'b111101 : + (SLOTS == 3'b010) ? 6'b111011 : + (SLOTS == 3'b011) ? 6'b110111 : + (SLOTS == 3'b100) ? 6'b101111 : + (SLOTS == 3'b101) ? 6'b011111 : + 6'b111111 : // Invalid + 6'b111111 ; // All slots disabled + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_g0.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_g0.v new file mode 100644 index 0000000000000000000000000000000000000000..b1a94df5523a207cb8d7ed73654b649cbc798f83 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_g0.v @@ -0,0 +1,51 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2019 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module neo_g0( + output [15:0] M68K_DATA, + input G0, G1, + input DIR, + input [15:0] CDD, + input [15:0] PC, + output WE +); + + // G0 G1 DIR M68K_DATA CDD PC WE + // 0 0 0 Should not happen, write to both hi-z active active 0 + // 0 0 1 Should not happen, read memcard ? active hi-z hi-z 1 + // 0 1 0 Write to memcard hi-z active hi-z 1 + // 0 1 1 Read from memcard active hi-z hi-z 1 + // 1 0 0 Write to palette hi-z hi-z active 0 + // 1 0 1 Read from palette active hi-z hi-z 1 + // 1 1 0 Do nothing hi-z hi-z hi-z 1 + // 1 1 1 Do nothing hi-z hi-z hi-z 1 + + wire [15:0] READ_DATA = G0 ? PC : CDD; + assign M68K_DATA = (~(G0 & G1) & DIR) ? READ_DATA : 16'bzzzzzzzz_zzzzzzzz; + + assign WE = G1 | DIR; + + // CDD output is done in the higher-level module + //assign CDD = G0 | DIR ? 16'bzzzzzzzz_zzzzzzzz : M68K_DOUT; + + // PC output is done in the higher-level module + //assign PC = WE ? 16'bzzzzzzzz_zzzzzzzz : M68K_DOUT; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_pvc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_pvc.v new file mode 100644 index 0000000000000000000000000000000000000000..26b30c8589ddf001b4394cd5a6934178e6db0b04 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_pvc.v @@ -0,0 +1,156 @@ +//============================================================================ +// NEO-PVC +// +// Copyright (C) 2019 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module neo_pvc +( + input nRESET, + input CLK_48M, + + input [19:1] M68K_ADDR, + inout [15:0] M68K_DATA, + input [15:0] PROM_DATA, + input nPORTOEL, nPORTOEU, + input nPORTWEL, nPORTWEU, + + input ENABLE, + output [23:0] P2_ADDR +); + +assign P2_ADDR = ENABLE ? bank + {M68K_ADDR,1'b0} : 24'h0; + +assign M68K_DATA[7:0] = (nPORTOEL | ~ENABLE) ? 8'bZ : + PORT_RD ? PORT_DO[7:0] : + RAM_ACC ? RAM_DO[7:0] : + PROM_DATA[7:0]; + +assign M68K_DATA[15:8] = (nPORTOEU | ~ENABLE) ? 8'bZ : + PORT_RD ? PORT_DO[15:8] : + RAM_ACC ? RAM_DO[15:8] : + PROM_DATA[15:8]; + +wire RAM_ACC = &M68K_ADDR[19:13]; +wire PORT_ACC = &M68K_ADDR[19:5]; +wire [3:0] PORT_NO = M68K_ADDR[4:1]; + +reg [11:0] CLR_ADDR; +always @(posedge CLK_48M) CLR_ADDR <= CLR_ADDR + 1'd1; + +wire [15:0] RAM_DO; +dpram #(12) RAML( + .clock_a(CLK_48M), + .address_a(M68K_ADDR[12:1]), + .data_a(M68K_DATA[7:0]), + .wren_a(RAM_ACC & ~nPORTWEL), + .q_a(RAM_DO[7:0]), + + .clock_b(CLK_48M), + .address_b(CLR_ADDR), + .data_b(CLR_ADDR[7:0]), + .wren_b(~nRESET) +); + +dpram #(12) RAMU( + .clock_a(CLK_48M), + .address_a(M68K_ADDR[12:1]), + .data_a(M68K_DATA[15:8]), + .wren_a(RAM_ACC & ~nPORTWEU), + .q_a(RAM_DO[15:8]), + + .clock_b(CLK_48M), + .address_b(CLR_ADDR), + .data_b(CLR_ADDR[7:0]), + .wren_b(~nRESET) +); + +reg nPORTWEU_d; +reg nPORTWEL_d; +always @(posedge CLK_48M) begin + nPORTWEU_d <= nPORTWEU; + nPORTWEL_d <= nPORTWEL; +end + +reg [23:0] bank = 0; +always @(posedge CLK_48M) begin + if(~nRESET) {bank[23:16],bank[7:0]} <= 0; + else if (~nPORTWEU & nPORTWEU_d) begin + if(PORT_ACC && PORT_NO == 8) bank[7:0] <= {M68K_DATA[15:9],1'b0}; + if(PORT_ACC && PORT_NO == 9) bank[23:16] <= {1'b0,M68K_DATA[14:8]}; + end +end + +always @(posedge CLK_48M) begin + if(~nRESET) bank[15:8] <= 0; + else if (~nPORTWEL & nPORTWEL_d) begin + if(PORT_ACC && PORT_NO == 9) bank[15:8] <= M68K_DATA[7:0]; + end +end + +reg [4:0] ur,ug,ub; +reg us; +always @(posedge CLK_48M) begin + if(~nPORTWEU && nPORTWEU_d && PORT_ACC && PORT_NO == 0) begin + ub[0] <= M68K_DATA[12]; + ug[0] <= M68K_DATA[13]; + ur <= {M68K_DATA[11:8], M68K_DATA[14]}; + us <= M68K_DATA[15]; + end +end + +always @(posedge CLK_48M) begin + if(~nPORTWEL && nPORTWEL_d && PORT_ACC && PORT_NO == 0) begin + ub[4:1] <= M68K_DATA[3:0]; + ug[4:1] <= M68K_DATA[7:4]; + end +end + +reg [15:0] pcol; +always @(posedge CLK_48M) begin + if (~nPORTWEU && nPORTWEU_d) begin + if(PORT_ACC && PORT_NO == 4) {pcol[13],pcol[7:4] } <= {M68K_DATA[8],M68K_DATA[12:9]}; + if(PORT_ACC && PORT_NO == 5) pcol[15] <= M68K_DATA[8]; + end +end + +always @(posedge CLK_48M) begin + if (~nPORTWEL && nPORTWEL_d) begin + if(PORT_ACC && PORT_NO == 4) {pcol[12],pcol[3:0] } <= {M68K_DATA[0],M68K_DATA[4:1]}; + if(PORT_ACC && PORT_NO == 5) {pcol[14],pcol[11:8]} <= {M68K_DATA[0],M68K_DATA[4:1]}; + end +end + +reg [15:0] PORT_DO; +reg PORT_RD; +always @(*) begin + PORT_RD = PORT_ACC; + case(PORT_NO) + 1: PORT_DO = {3'b0,ug,3'b0,ub}; + 2: PORT_DO = {7'b0,us,3'b0,ur}; + 6: PORT_DO = pcol; + 8: PORT_DO = {bank[7:0], 8'hA0}; + 9: PORT_DO = bank[23:8]; + default: + begin + PORT_DO = 0; + PORT_RD = 0; + end + endcase +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_sma.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_sma.sv new file mode 100644 index 0000000000000000000000000000000000000000..9c67588342c1d4f2486c32cebbeb73956c385817 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/neo_sma.sv @@ -0,0 +1,226 @@ +//============================================================================ +// NEO-SMA +// +// Copyright (C) 2019 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module neo_sma +( + input nRESET, + input CLK_48M, + + input [19:1] M68K_ADDR, + inout [15:0] M68K_DATA, + input [15:0] PROM_DATA, + input nPORTOEL, nPORTOEU, + input nPORTWEL, nPORTWEU, + + input [2:0] TYPE, + output [23:0] P2_ADDR +); + +assign P2_ADDR = ENABLE ? bank + {M68K_ADDR,1'b0} : 24'h0; + +wire ENABLE = (TYPE>=3); +wire BANK_SEL = (M68K_ADDR == BANK_ADDR); +wire ID_SEL = (M68K_ADDR == 'h7F223); +wire RNG_SEL = (M68K_ADDR == RNG_ADDR1 || M68K_ADDR == RNG_ADDR2); + +reg [19:1] BANK_ADDR, RNG_ADDR1, RNG_ADDR2; +always @(posedge CLK_48M) begin + case(TYPE) + 3: begin // kof99 + BANK_ADDR <= 'h7FFF8; + RNG_ADDR1 <= 'h7FFFC; + RNG_ADDR2 <= 'h7FFFD; + end + 4, + 5: begin // garou,garouh + BANK_ADDR <= 'h7FFE0; + RNG_ADDR1 <= 'h7FFE6; + RNG_ADDR2 <= 'h7FFF8; + end + 6: begin // mslug3 + BANK_ADDR <= 'h7FFF2; + //mslug3 has no RNG. (?) + RNG_ADDR1 <= 'h7F223; + RNG_ADDR2 <= 'h7F223; + end + 7: begin // kof2000 + BANK_ADDR <= 'h7FFF6; + RNG_ADDR1 <= 'h7FFEC; + RNG_ADDR2 <= 'h7FFED; + end + endcase +end + +assign M68K_DATA[7:0] = (nPORTOEL | ~ENABLE) ? 8'bZ : ID_SEL ? 8'h37 : RNG_SEL ? rng[7:0] : PROM_DATA[7:0]; +assign M68K_DATA[15:8] = (nPORTOEU | ~ENABLE) ? 8'bZ : ID_SEL ? 8'h9A : RNG_SEL ? rng[15:8] : PROM_DATA[15:8]; + +wire nPORTWE = nPORTWEL & nPORTWEU; +wire nPORTOE = nPORTOEL & nPORTOEU; + +//////////////////////////////////////////////////// + +wire [23:0] kof99_map[64] = +'{ + 'h000000, 'h100000, 'h200000, 'h300000, + 'h3cc000, 'h4cc000, 'h3f2000, 'h4f2000, + 'h407800, 'h507800, 'h40d000, 'h50d000, + 'h417800, 'h517800, 'h420800, 'h520800, + 'h424800, 'h524800, 'h429000, 'h529000, + 'h42e800, 'h52e800, 'h431800, 'h531800, + 'h54d000, 'h551000, 'h567000, 'h592800, + 'h588800, 'h581800, 'h599800, 'h594800, + 'h598000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000 +}; + +wire [5:0] kof99_idx = {M68K_DATA[5],M68K_DATA[12],M68K_DATA[10],M68K_DATA[8],M68K_DATA[6],M68K_DATA[14]}; +//////////////////////////////////////////////////// + +wire [23:0] garou_map[64] = +'{ + 'h000000, 'h100000, 'h200000, 'h300000, + 'h280000, 'h380000, 'h2d0000, 'h3d0000, + 'h2f0000, 'h3f0000, 'h400000, 'h500000, + 'h420000, 'h520000, 'h440000, 'h540000, + 'h498000, 'h598000, 'h4a0000, 'h5a0000, + 'h4a8000, 'h5a8000, 'h4b0000, 'h5b0000, + 'h4b8000, 'h5b8000, 'h4c0000, 'h5c0000, + 'h4c8000, 'h5c8000, 'h4d0000, 'h5d0000, + 'h458000, 'h558000, 'h460000, 'h560000, + 'h468000, 'h568000, 'h470000, 'h570000, + 'h478000, 'h578000, 'h480000, 'h580000, + 'h488000, 'h588000, 'h490000, 'h590000, + 'h5d0000, 'h5d8000, 'h5e0000, 'h5e8000, + 'h5f0000, 'h5f8000, 'h600000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000 +}; + +wire [5:0] garou_idx = {M68K_DATA[12],M68K_DATA[14],M68K_DATA[6],M68K_DATA[7],M68K_DATA[9],M68K_DATA[5]}; +//////////////////////////////////////////////////// + +wire [23:0] garouh_map[64] = +'{ + 'h000000, 'h100000, 'h200000, 'h300000, + 'h280000, 'h380000, 'h2d0000, 'h3d0000, + 'h2c8000, 'h3c8000, 'h400000, 'h500000, + 'h420000, 'h520000, 'h440000, 'h540000, + 'h598000, 'h698000, 'h5a0000, 'h6a0000, + 'h5a8000, 'h6a8000, 'h5b0000, 'h6b0000, + 'h5b8000, 'h6b8000, 'h5c0000, 'h6c0000, + 'h5c8000, 'h6c8000, 'h5d0000, 'h6d0000, + 'h458000, 'h558000, 'h460000, 'h560000, + 'h468000, 'h568000, 'h470000, 'h570000, + 'h478000, 'h578000, 'h480000, 'h580000, + 'h488000, 'h588000, 'h490000, 'h590000, + 'h5d8000, 'h6d8000, 'h5e0000, 'h6e0000, + 'h5e8000, 'h6e8000, 'h6e8000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000 +}; + +wire [5:0] garouh_idx = {M68K_DATA[13],M68K_DATA[11],M68K_DATA[2],M68K_DATA[14],M68K_DATA[8],M68K_DATA[4]}; +//////////////////////////////////////////////////// + +wire [23:0] mslug3_map[64] = +'{ + 'h000000, 'h020000, 'h040000, 'h060000, + 'h070000, 'h090000, 'h0b0000, 'h0d0000, + 'h0e0000, 'h0f0000, 'h120000, 'h130000, + 'h140000, 'h150000, 'h180000, 'h190000, + 'h1a0000, 'h1b0000, 'h1e0000, 'h1f0000, + 'h200000, 'h210000, 'h240000, 'h250000, + 'h260000, 'h270000, 'h2a0000, 'h2b0000, + 'h2c0000, 'h2d0000, 'h300000, 'h310000, + 'h320000, 'h330000, 'h360000, 'h370000, + 'h380000, 'h390000, 'h3c0000, 'h3d0000, + 'h400000, 'h410000, 'h440000, 'h450000, + 'h460000, 'h470000, 'h4a0000, 'h4b0000, + 'h4c0000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000 +}; + +wire [5:0] mslug3_idx = {M68K_DATA[9],M68K_DATA[3],M68K_DATA[6],M68K_DATA[15],M68K_DATA[12],M68K_DATA[14]}; +//////////////////////////////////////////////////// + +wire [23:0] kof2000_map[64] = +'{ + 'h000000, 'h100000, 'h200000, 'h300000, + 'h3f7800, 'h4f7800, 'h3ff800, 'h4ff800, + 'h407800, 'h507800, 'h40f800, 'h50f800, + 'h416800, 'h516800, 'h41d800, 'h51d800, + 'h424000, 'h524000, 'h523800, 'h623800, + 'h526000, 'h626000, 'h528000, 'h628000, + 'h52a000, 'h62a000, 'h52b800, 'h62b800, + 'h52d000, 'h62d000, 'h52e800, 'h62e800, + 'h618000, 'h619000, 'h61a000, 'h61a800, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000, + 'h000000, 'h000000, 'h000000, 'h000000 +}; + +wire [5:0] kof2000_idx = {M68K_DATA[5],M68K_DATA[10],M68K_DATA[3],M68K_DATA[7],M68K_DATA[14],M68K_DATA[15]}; +//////////////////////////////////////////////////// + +reg nPORTWE_d; +reg nPORTOE_d; +always @(posedge CLK_48M) begin + nPORTWE_d <= nPORTWE; + nPORTOE_d <= nPORTOE; +end + +reg [23:0] bank = 0; +always @(posedge CLK_48M) begin + if(~nRESET) bank <= 0; + else if(~nPORTWE & nPORTWE_d & BANK_SEL) begin + case(TYPE) + 3: bank <= kof99_map[kof99_idx]; + 4: bank <= garou_map[garou_idx]; + 5: bank <= garouh_map[garouh_idx]; + 6: bank <= mslug3_map[mslug3_idx]; + 7: bank <= kof2000_map[kof2000_idx]; + endcase + end +end + +reg [15:0] rng = 0; +always @(posedge CLK_48M) begin + reg rst = 0; + if(~nRESET) rst = 1; + else if (~nPORTOE & nPORTOE_d) begin + if(rst) rng <= 'h2345; + else rng <= {rng[14:0], rng[2] ^ rng[3] ^ rng[5] ^ rng[6] ^ rng[7] ^ rng[11] ^ rng[12] ^ rng[15]}; + rst <= 0; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/pcm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/pcm.v new file mode 100644 index 0000000000000000000000000000000000000000..5db55dd2227689d42511e64c03f5795eb22e4290 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/pcm.v @@ -0,0 +1,86 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2019 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module PCM( + input CLK_68KCLKB, + input nSDROE, SDRMPX, + input nSDPOE, SDPMPX, + inout [7:0] SDRAD, + input [9:8] SDRA_L, + input [23:20] SDRA_U, + inout [7:0] SDPAD, + input [11:8] SDPA, + input [7:0] D, + output [23:0] A + ); + + reg [1:0] COUNT; + reg [7:0] RDLATCH; + reg [7:0] PDLATCH; + reg [23:0] RALATCH; + reg [23:0] PALATCH; + + wire nSDRMPX = ~SDRMPX; + wire nSDPMPX = ~SDPMPX; + wire SDPOE = ~nSDPOE; + wire CEN = ~COUNT[1]; + + always @(posedge CLK_68KCLKB or negedge nSDPOE) + begin + if (!nSDPOE) + COUNT <= 0; + else + if (CEN) COUNT <= COUNT + 1'b1; + end + + assign SDRAD = nSDROE ? 8'bzzzzzzzz : RDLATCH; + always @(*) + if (COUNT[1]) RDLATCH <= D; + + assign SDPAD = nSDPOE ? 8'bzzzzzzzz : PDLATCH; + always @(*) + if (!nSDPOE) PDLATCH <= D; + + assign A = nSDPOE ? RALATCH : PALATCH; + + always @(posedge nSDRMPX) + begin + RALATCH[7:0] <= SDRAD[7:0]; + RALATCH[9:8] <= SDRA_L[9:8]; + end + always @(posedge SDRMPX) + begin + RALATCH[17:10] <= SDRAD[7:0]; + RALATCH[23:18] <= {SDRA_U[23:20], SDRA_L[9:8]}; + end + + always @(posedge nSDPMPX) + begin + PALATCH[7:0] <= SDPAD[7:0]; + PALATCH[11:8] <= SDPA[11:8]; + end + always @(posedge SDPMPX) + begin + PALATCH[19:12] <= SDPAD[7:0]; + PALATCH[23:20] <= SDPA[11:8]; + end + +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/register.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/register.v new file mode 100644 index 0000000000000000000000000000000000000000..965a80bd81269dec299d83cc0bf6b8e3ba610bcc --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/register.v @@ -0,0 +1,46 @@ +// simulate registers with async clocks in the 'clock' domain +// has a delay of one clock + +module register ( + input clock, + input s, // set + input r, // reset + input c, // write clock + input [WIDTH-1:0] d, // new value + output reg [WIDTH-1:0] q // value +); + +parameter WIDTH = 1; + +reg [WIDTH-1:0] val_reg; +reg c_d; +/* +always @(posedge c, posedge s, posedge r) +begin + if (r) + q <= 0; + else if (s) + q <= 1; + else + q <= d; +end +*/ + +always @(*) begin + if (r) + q = 0; + else if (s) + q = {WIDTH{1'b1}}; + else + q = val_reg; +end + +always @(posedge clock) begin + c_d <= c; + if (~c_d & c & ~r & ~s) + val_reg <= d; + else + val_reg <= q; +end + +endmodule \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/resetp.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/resetp.v new file mode 100644 index 0000000000000000000000000000000000000000..03ac3f837904334f372c8f2e3b14dde586ef5b4c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/resetp.v @@ -0,0 +1,42 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2019 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module resetp_sync( + input CLK, + input CLK_EN_24_N, + input nRESET, + output reg nRESETP +); + + reg O49_nQ; + + // 24MB ""__""__""__""__""__ + // nRESET ____________"""""""" + // nRESETP """"""""""""""____"" + + always @(posedge CLK) + begin + if (CLK_EN_24_N) begin + O49_nQ <= ~nRESET; + nRESETP <= ~&{O49_nQ, nRESET}; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/syslatch.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/syslatch.v new file mode 100644 index 0000000000000000000000000000000000000000..0671053414f2adf3111b754848df0e4ba07dc039 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/syslatch.v @@ -0,0 +1,89 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module syslatch( + input [4:1] M68K_ADDR, + input nBITW1, + input nRESET, + output SHADOW, nVEC, nCARDWEN, CARDWENB, nREGEN, nSYSTEM, nSRAMWEN, PALBNK, + input CLK, CLK_EN_68K_P +); + + reg [7:0] SLATCH; + + assign SHADOW = SLATCH[0]; + assign nVEC = SLATCH[1]; + assign nCARDWEN = SLATCH[2]; + assign CARDWENB = SLATCH[3]; + assign nREGEN = SLATCH[4]; + assign nSYSTEM = SLATCH[5]; + assign nSRAMWEN = ~SLATCH[6]; // See MVS schematics page 3 + assign PALBNK = SLATCH[7]; + + // System latch + /*always @(*) // M68K_ADDR[4:1] or nBITW1 or nRESET + begin + if (!nRESET) + begin + if (nBITW1) + SLATCH <= 8'h00; // Clear + else + begin // Demux mode + case (M68K_ADDR[3:1]) + 0: SLATCH <= {7'b0000000, M68K_ADDR[4]}; + 1: SLATCH <= {6'b000000, M68K_ADDR[4], 1'b0}; + 2: SLATCH <= {5'b00000, M68K_ADDR[4], 2'b00}; + 3: SLATCH <= {4'b0000, M68K_ADDR[4], 3'b000}; + 4: SLATCH <= {3'b000, M68K_ADDR[4], 4'b0000}; + 5: SLATCH <= {2'b00, M68K_ADDR[4], 5'b00000}; + 6: SLATCH <= {1'b0, M68K_ADDR[4], 6'b000000}; + 7: SLATCH <= {M68K_ADDR[4], 7'b0000000}; + endcase + end + end + else if (!nBITW1) + begin // Latch mode + SLATCH[M68K_ADDR[3:1]] <= M68K_ADDR[4]; + end + end*/ + + always @(posedge CLK) // M68K_ADDR[4:1] or nBITW1 or nRESET + if (CLK_EN_68K_P) begin + if (!nRESET) + begin + if (nBITW1) + SLATCH <= 8'h00; // Clear + else + begin // Demux mode + case (M68K_ADDR[3:1]) + 0: SLATCH <= {7'b0000000, M68K_ADDR[4]}; + 1: SLATCH <= {6'b000000, M68K_ADDR[4], 1'b0}; + 2: SLATCH <= {5'b00000, M68K_ADDR[4], 2'b00}; + 3: SLATCH <= {4'b0000, M68K_ADDR[4], 3'b000}; + 4: SLATCH <= {3'b000, M68K_ADDR[4], 4'b0000}; + 5: SLATCH <= {2'b00, M68K_ADDR[4], 5'b00000}; + 6: SLATCH <= {1'b0, M68K_ADDR[4], 6'b000000}; + 7: SLATCH <= {M68K_ADDR[4], 7'b0000000}; + endcase + end + end + else if (!nBITW1) + begin // Latch mode + SLATCH[M68K_ADDR[3:1]] <= M68K_ADDR[4]; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/upd4990.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/upd4990.v new file mode 100644 index 0000000000000000000000000000000000000000..5fee888225ef62cf591a611d3cb14321645bc3da --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/upd4990.v @@ -0,0 +1,174 @@ +// NeoGeo logic definition +// MiSTer RTC to uPD4990 +// +// Copyright (C) 2019 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module uPD4990( + input nRESET, + input CLK, + input CLK_EN_12M, // 12MHz please + input [64:0] rtc, + input CS, OE, // Both always low + input DATA_CLK, + input DATA_IN, + input STROBE, + output TP, + output DATA_OUT +); + + wire [47:0] TIME_DATA; + wire [3:0] MONTH_HEX; + reg [47:0] SHIFT_REG; + reg [3:0] CMD_REG; + reg OUT_HOLD; // Prevents CLK from shifting the 48 lower bits of SHIFT_REG + + reg [2:0] TP_SEL; + reg [5:0] TP_HSECONDS; // Half seconds (incremented at 2Hz) + reg TP_SEC_RUN; + reg INTERVAL_FLAG; + + reg [8:0] DIV9; + reg [14:0] DIV15; + reg [5:0] DIV6; + + reg [1:0] DATA_CLK_G_SR; + reg [1:0] STROBE_G_SR; + + + // "rtc" format: + // 64 63 55 47 39 31 23 15 7 + // x 01000000 00000WWW YYYYYYYY 000MMMMM 00DDDDDD 0PHHHHHH 0MMMMMMM 0SSSSSSS + // Values are in BCD + // P: 1=PM 0=AM + // Weekday: 1 to 7 + // Month: 1 to 12 + + // uPD4990 datasheet: + // Data is represented in BCD notation. Only months are represented in hexadecimal notation. + // Format: + // CCCC YYYYYYYY MMMM WWWW DDDDDDDD HHHHHHHH MMMMMMMM SSSSSSSS + + // BCD to hex + assign MONTH_HEX = rtc[36] ? rtc[35:32] + 4'd10 : rtc[35:32]; + + assign TIME_DATA = {rtc[47:40], MONTH_HEX, 1'b0, rtc[50:48], rtc[31:24], 2'b00, rtc[21:0]}; + + wire [14:0] DIV15_INC = DIV15 + 1'b1; // Look-ahead for edge detection + wire [5:0] DIV6_INC = DIV6 + 1'b1; // Look-ahead for edge detection + + wire INTERVAL_TRIG = (((TP_SEL == 3'd4) & (TP_HSECONDS >= 6'd1-1)) | + ((TP_SEL == 3'd5) & (TP_HSECONDS >= 6'd10-1)) | + ((TP_SEL == 3'd6) & (TP_HSECONDS >= 6'd30-1)) | + ((TP_SEL == 3'd7) & (TP_HSECONDS >= 6'd60-1))); + + wire DATA_CLK_G = CS & DATA_CLK; + wire STROBE_G = CS & STROBE; + + always @(posedge CLK) + begin + if (!nRESET) + begin + OUT_HOLD <= 1; + TP_SEL <= 0; + CMD_REG <= 0; + TP_SEL <= 0; + TP_HSECONDS <= 0; + TP_SEC_RUN <= 1; + INTERVAL_FLAG <= 1; + DIV9 <= 9'd0; + DIV15 <= 15'd0; + DIV6 <= 6'd0; + DATA_CLK_G_SR <= 0; + STROBE_G_SR <= 0; + end + else + if (CLK_EN_12M) begin + if (DIV9 == 9'd366-1) // 12000000/32768 + begin + // 32768Hz from 12MHz + DIV9 <= 9'd0; + + DIV15 <= DIV15_INC; + + if ({DIV15[8], DIV15_INC[8]} == 2'b01) + begin + // 64Hz from 32768Hz + if (TP_SEC_RUN) + begin + DIV6 <= DIV6_INC; + if ({DIV6[4], DIV6_INC[4]} == 2'b01) + begin + // 2Hz from 64Hz + // INTERVAL_FLAG is toggled in the middle of the interval (50% duty cycle) + // It can be forced back high with command b1100 + if (INTERVAL_TRIG) + begin + TP_HSECONDS <= 6'd0; + INTERVAL_FLAG <= ~INTERVAL_FLAG; + end + else + TP_HSECONDS <= TP_HSECONDS + 1'b1; + end + end + end + end + else + DIV9 <= DIV9 + 1'b1; + + + DATA_CLK_G_SR <= {DATA_CLK_G_SR[0], DATA_CLK_G}; + STROBE_G_SR <= {STROBE_G_SR[0], STROBE_G}; + + // Rising edge of DATA_CLK_G + if (DATA_CLK_G_SR == 2'b01) + begin + if (!OUT_HOLD) + SHIFT_REG <= {CMD_REG[0], SHIFT_REG[47:1]}; + + // CMD_REG always shifts regardless of OUT_HOLD + CMD_REG <= {DATA_IN, CMD_REG[3:1]}; + end + + // Rising edge of STROBE_G + if (STROBE_G_SR == 2'b01) + begin + casez(CMD_REG) + 4'b0000: OUT_HOLD <= 1'b1; // Hold + 4'b0001: OUT_HOLD <= 1'b0; // Allow shift + 4'b0010: OUT_HOLD <= 1'b1; // Setting time isn't supported + 4'b0011: // Read time + begin + SHIFT_REG <= TIME_DATA; + OUT_HOLD <= 1'b1; + end + 4'b01zz, 4'b10zz: TP_SEL <= {CMD_REG[3], CMD_REG[1:0]}; + 4'b1100: INTERVAL_FLAG <= 1'b1; // Reset + 4'b1101: TP_SEC_RUN <= 1'b1; + 4'b111z: TP_SEC_RUN <= 1'b0; + endcase + end + end + end + + assign TP = (TP_SEL == 3'd0) ? DIV15[8] : + (TP_SEL == 3'd1) ? DIV15[6] : + (TP_SEL == 3'd2) ? DIV15[3] : + (TP_SEL == 3'd3) ? DIV15[2] : + INTERVAL_FLAG; + + assign DATA_OUT = OUT_HOLD ? rtc[0] : SHIFT_REG[0]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/watchdog.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/watchdog.v new file mode 100644 index 0000000000000000000000000000000000000000..4856fbcb53d8a90eba314f72e44b4dba8c7ad9f8 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/watchdog.v @@ -0,0 +1,63 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module watchdog( + input CLK, + input DOGE, + input nLDS, RW, + input A23I, A22I, + input [21:17] M68K_ADDR_U, + //input [12:1] M68K_ADDR_L, + input WDCLK, + output nHALT, + output nRESET, + input nRST +); + + reg [3:0] WDCNT; + + initial + WDCNT = 4'b0000; + + // IMPORTANT: + // nRESET is an open-collector output on B1, so that the 68k can drive it (RESET instruction) + // The line has a 4.7k pullup (schematics page 1) + // nRESET changes state on posedge nBNKB (posedge mclk), but takes a slightly variable amount of time to + // return high after it is released. Low during 8 frames, released during 8 frames. + assign nRESET = nRST & ~WDCNT[3]; + assign nHALT = nRESET; // Yup (these are open-collector) + + // $300001 (LDS) + // 0011000xxxxxxxxxxxxxxxx1 + // MAME says 00110001xxxxxxxxxxxxxxx1 but NEO-B1 doesn't have A16 + wire WDRESET = ~DOGE | &{nRST, ~|{nLDS, RW, A23I, A22I}, M68K_ADDR_U[21:20], ~|{M68K_ADDR_U[19:17]}}; + + always @(posedge CLK) + begin + reg WDCLK_D; + WDCLK_D <= WDCLK; + + if (WDRESET) + WDCNT <= 4'b0000; + else if (!nRST) + WDCNT <= 4'b1000; + else begin + if (~WDCLK_D & WDCLK) + WDCNT <= WDCNT + 1'b1; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/z80ctrl.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/z80ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..026bb6179a582e6edbc2bcd74ae298dec9dd6811 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/z80ctrl.v @@ -0,0 +1,101 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// Everything here was verified on a MV4 board + +module z80ctrl( + input CLK, + input [4:2] SDA_L, + input [15:11] SDA_U, + input nSDRD, nSDWR, + input nMREQ, nIORQ, + input nSDW, // From NEO-C1 + input nRESET, + output reg nZ80NMI, + output nSDZ80R, nSDZ80W, // To NEO-C1 + output nSDZ80CLR, // To NEO-C1 + output nSDROM, + output nSDMRD, nSDMWR, + output nSDRD0, nSDRD1, + output n2610CS, + output n2610RD, n2610WR, + output nZRAMCS +); + + reg nNMI_EN; + wire nIORD, nIOWR; + wire nNMI_SET, nNMI_RESET; + + // $0000~$F7FF: ROM + // $F800~$FFFF: RAM + assign nSDROM = &{SDA_U}; + assign nZRAMCS = ~nSDROM; + + assign nSDMRD = nMREQ | nSDRD; // RAM read + assign nSDMWR = nMREQ | nSDWR; // RAM write + + assign nIORD = nIORQ | nSDRD; // Port read + assign nIOWR = nIORQ | nSDWR; // Port write + + // Port $x0, $x1, $x2, $x3 read + assign nSDZ80R = (nIORD | SDA_L[3] | SDA_L[2]); + // Port $x0, $x1, $x2, $x3 write + assign nSDZ80CLR = (nIOWR | SDA_L[3] | SDA_L[2]); + + // Port $x4, $x5, $x6, $x7 read + assign n2610RD = (nIORD | SDA_L[3] | ~SDA_L[2]); + // Port $x4, $x5, $x6, $x7 write + assign n2610WR = (nIOWR | SDA_L[3] | ~SDA_L[2]); + assign n2610CS = n2610RD & n2610WR; + + // Port $x8, $x9, $xA, $xB read + assign nSDRD0 = (nIORD | ~SDA_L[3] | SDA_L[2]); + // Port $x8, $x9, $xA, $xB write + assign nNMI_SET = (nIOWR | ~SDA_L[3] | SDA_L[2]); + + // Port $xC, $xD, $xE, $xF read + assign nSDRD1 = (nIORD | ~SDA_L[3] | ~SDA_L[2]); + // Port $xC, $xD, $xE, $xF write + assign nSDZ80W = (nIOWR | ~SDA_L[3] | ~SDA_L[2]); + + assign nNMI_RESET = nSDZ80R & nRESET; + + // NMI enable DFF + reg nNMI_SET_d; + reg nSDW_d; + always @(posedge CLK) begin + nNMI_SET_d <= nNMI_SET; + nSDW_d <= nSDW; + end + + always @(posedge CLK) + begin + if (!nRESET) + nNMI_EN <= 1'b1; + else if (nNMI_SET & !nNMI_SET_d) + nNMI_EN <= SDA_L[4]; + end + + // NMI trig DFF + always @(posedge CLK) + begin + if (!nNMI_RESET) + nZ80NMI <= 1'b1; + else if (nSDW & !nSDW_d) + nZ80NMI <= nNMI_EN; + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/io/zmc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/zmc.v new file mode 100644 index 0000000000000000000000000000000000000000..1cec0db4edfe4c3b9d46438144bcdee92beb1250 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/io/zmc.v @@ -0,0 +1,68 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module zmc( + input CLK, + input nRESET, + input nSDRD0, + input [1:0] SDA_L, + input [15:8] SDA_U, + output [18:11] MA +); + + // Z80 ROM Region Reg + // 1E = F000~F7FF = F000~F7FF 1111 (0) + // 0E = E000~EFFF = E000~EFFF 1110 (1) + // 06 = C000~DFFF = C000~DFFF 110x (2) + // 02 = 8000~BFFF = 8000~BFFF 10xx (3) + + reg [7:0] WINDOW_0; + reg [6:0] WINDOW_1; + reg [5:0] WINDOW_2; + reg [4:0] WINDOW_3; + + assign MA = (~SDA_U[15]) ? {3'b000, SDA_U[15:11]} : // Pass-through + (SDA_U[15:12] == 4'b1111) ? WINDOW_0 : // F000~F7FF + (SDA_U[15:12] == 4'b1110) ? {WINDOW_1, SDA_U[11]} : // E000~EFFF + (SDA_U[15:13] == 3'b110) ? {WINDOW_2, SDA_U[12:11]} : // C000~DFFF + {WINDOW_3, SDA_U[13:11]}; // 8000~BFFF + + reg nSDRD0_d; + always @(posedge CLK) nSDRD0_d <= nSDRD0; + + always @(posedge CLK) + begin + if(!nRESET) begin + WINDOW_0 <= 'h1E; + WINDOW_1 <= 'h0E; + WINDOW_2 <= 'h06; + WINDOW_3 <= 'h02; + end + else if (nSDRD0 & !nSDRD0_d) begin + case (SDA_L) + 0: WINDOW_0 <= SDA_U[15:8]; + 1: WINDOW_1 <= SDA_U[14:8]; + 2: WINDOW_2 <= SDA_U[13:8]; + 3: WINDOW_3 <= SDA_U[12:8]; + endcase + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/README.md b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/README.md new file mode 100644 index 0000000000000000000000000000000000000000..80f1c7a91f31a24125f1fd8adaf9c68dcbf222fa --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/README.md @@ -0,0 +1,59 @@ +# JT12 FPGA Clone of Yamaha OPN hardware by Jose Tejada (@topapate) +=================================================================== + +You can show your appreciation through +* [Patreon](https://patreon.com/jotego), by supporting releases +* [Paypal](https://paypal.me/topapate), with a donation + + +JT12 is an FM sound source written in Verilog, fully compatible with YM2612/YM3438 (Megadrive), YM2610 (NeoGeo) and YM2203 (PC88, arcades). + +The implementation tries to be as close to original hardware as possible. Low usage of FPGA resources has also been a design goal. Except in the operator section (jt12_op) where an exact replica of the original circuit is done. This could be done in less space with a different style but because this piece of the circuit was reversed engineered by Sauraen, I decided to use that knowledge. + +## Using JT12 in a git project + +If you are using JT12 in a git project, the best way to add it to your project is: + +1. Optionally fork JT12's repository to your own GitHub account +2. Add it as a submodule to your git project: `git submodule add https://github.com/jotego/jt12.git` +3. Now you can refer to the RTL files in **jt12/hdl** + +The advantages of a using a git submodule are: + +1. Your project contains a reference to a commit of the JT12 repository +2. As long as you do not manually update the JT12 submodule, it will keep pointing to the same commit +3. Each time you make a commit in your project, it will include a pointer to the JT12 commit used. So you will always know the JT12 that worked for you +4. If JT12 is updated and you want to get the changes, simply update the submodule using git. The new JT12 commit used will be annotated in your project's next commit. So the history of your project will reflect that change too. +5. JT12 files will be intact and you will use the files without altering them. + +## Directories + +* hdl -> all relevant RTL files, written in verilog +* ver -> test benches +* ver/verilator -> test bench that can play vgm files + +## Usage + +Chip | Top Level | QIP File +--------|---------------|--------- +YM2610 | jt10.v | jt10.qip +YM2612 | jt12.v | jt12.qip +YM2203 | jt03.v | jt03.qip + +## Simulation + +There are several simulation test benches in the **ver** folder. The most important one is in the **ver/verilator** folder. The simulation script is called with the shell script **go** in the same folder. The script will compile the file **test.cpp** together with other files and the design and will simulate the tune specificied with the -f command. It can read **vgm** tunes and generate .wav output of them. + +## Related Projects + +Other sound chips from the same author + +Chip | Repository +-----------------------|------------ +YM2203, YM2612, YM2610 | [JT12](https://github.com/jotego/jt12) +YM2151 | [JT51](https://github.com/jotego/jt51) +YM3526 | [JTOPL](https://github.com/jotego/jtopl) +YM2149 | [JT49](https://github.com/jotego/jt49) +sn76489an | [JT89](https://github.com/jotego/jt89) +OKI 6295 | [JT6295](https://github.com/jotego/jt6295) +OKI MSM5205 | [JT5205](https://github.com/jotego/jt5205) \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nedit.txt b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nedit.txt new file mode 100644 index 0000000000000000000000000000000000000000..f612e6117b4c98aa851038510bca5bf0b0e6c3ee --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nedit.txt @@ -0,0 +1,3 @@ + +(output|input)[\t ]*(reg|\t| )[\t ]*(\[.*\]|\t| )[\t ]*(.*), +.\4\t\t( \4\t\t), diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/ISN76489.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/ISN76489.h new file mode 100644 index 0000000000000000000000000000000000000000..f2350ee442421e7c544f61488c2fcf444c9cfd8c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/ISN76489.h @@ -0,0 +1,64 @@ +#ifndef __ISN76489_H__ +#define __ISN76489_H__ +#include "GenericAccess/GenericAccess.pkg" +#include + +class ISN76489 :public virtual IGenericAccess +{ +public: + //Constants + static const unsigned int channelCount = 4; + static const unsigned int noiseChannelNo = 3; + static const unsigned int toneRegisterBitCount = 10; + static const unsigned int volumeRegisterBitCount = 4; + static const unsigned int noiseRegisterBitCount = 3; + + //Enumerations + enum class ISN76489DataSource; + +public: + //Interface version functions + static inline unsigned int ThisISN76489Version() { return 1; } + virtual unsigned int GetISN76489Version() const = 0; + + //Raw register functions + inline unsigned int GetVolumeRegisterExternal(unsigned int channelNo) const; + inline void SetVolumeRegisterExternal(unsigned int channelNo, unsigned int adata); + inline unsigned int GetToneRegisterExternal(unsigned int channelNo) const; + inline void SetToneRegisterExternal(unsigned int channelNo, unsigned int adata); + inline unsigned int GetNoiseShiftRegisterExternal() const; + inline void SetNoiseShiftRegisterExternal(unsigned int adata); + + //Latched register functions + inline unsigned int GetLatchedChannelNoExternal() const; + inline void SetLatchedChannelNoExternal(unsigned int adata); + inline bool GetVolumeRegisterLatchedExternal() const; + inline void SetVolumeRegisterLatchedExternal(bool adata); + + //Device property functions + inline double GetExternalClockRate() const; + inline void SetExternalClockRate(double adata); + inline double GetExternalClockDivider() const; + inline void SetExternalClockDivider(double adata); + inline unsigned int GetShiftRegisterBitCount() const; + inline void SetShiftRegisterBitCount(unsigned int adata); + inline unsigned int GetShiftRegisterDefaultValue() const; + inline void SetShiftRegisterDefaultValue(unsigned int adata); + inline unsigned int GetNoiseChannelWhiteNoiseTappedBitMask() const; + inline void SetNoiseChannelWhiteNoiseTappedBitMask(unsigned int adata); + inline unsigned int GetNoiseChannelPeriodicNoiseTappedBitMask() const; + inline void SetNoiseChannelPeriodicNoiseTappedBitMask(unsigned int adata); + + //Audio logging functions + inline bool IsAudioLoggingEnabled() const; + inline void SetAudioLoggingEnabled(bool adata); + inline bool IsChannelAudioLoggingEnabled(unsigned int channelNo) const; + inline void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool adata); + inline std::wstring GetAudioLoggingOutputPath() const; + inline void SetAudioLoggingOutputPath(const std::wstring& adata); + inline std::wstring GetChannelAudioLoggingOutputPath(unsigned int channelNo) const; + inline void SetChannelAudioLoggingOutputPath(unsigned int channelNo, const std::wstring& adata); +}; + +#include "ISN76489.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62b9170d73cd8fbbfe615aeb4ca3fbdb429f1c44 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.cpp @@ -0,0 +1,1267 @@ +#include "SN76489.h" +#include +#include + +//---------------------------------------------------------------------------------------- +//Constructors +//---------------------------------------------------------------------------------------- +SN76489::SN76489(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID) +:Device(aimplementationName, ainstanceName, amoduleID), reg(channelCount * 2, false, Data(toneRegisterBitCount)) +{ + //Initialize the audio output stream + outputSampleRate = 48000; //44100; + outputStream.Open(1, 16, outputSampleRate, outputSampleRate/4, outputSampleRate/20); + + //Initialize the locked register state + for(unsigned int i = 0; i < channelCount; ++i) + { + channelVolumeRegisterLocked[i] = false; + channelDataRegisterLocked[i] = false; + } + noiseChannelTypeLocked = false; + noiseChannelPeriodLocked = false; + + //##TODO## Provide a way for these properties to be defined externally, and provide + //debug windows which can modify them on the fly. + externalClockRate = 0.0; + externalClockDivider = 16.0; + shiftRegisterBitCount = 16; + shiftRegisterDefaultValue = 0x8000; + noiseWhiteTappedBitMask = 0x0009; + noisePeriodicTappedBitMask = 0x0001; +} + +//---------------------------------------------------------------------------------------- +//Interface version functions +//---------------------------------------------------------------------------------------- +unsigned int SN76489::GetISN76489Version() const +{ + return ThisISN76489Version(); +} + +//---------------------------------------------------------------------------------------- +//Initialization functions +//---------------------------------------------------------------------------------------- +bool SN76489::BuildDevice() +{ + //Initialize the wave logging state + std::wstring captureFolder = GetSystemInterface().GetCapturePath(); + wavLoggingEnabled = false; + std::wstring wavLoggingFileName = GetDeviceInstanceName() + L".wav"; + wavLoggingPath = PathCombinePaths(captureFolder, wavLoggingFileName); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + wavLoggingChannelEnabled[channelNo] = false; + std::wstringstream wavLoggingChannelFileName; + wavLoggingChannelFileName << GetDeviceInstanceName() << L" - C" << channelNo << L".wav"; + wavLoggingChannelPath[channelNo] = PathCombinePaths(captureFolder, wavLoggingChannelFileName.str()); + } + + //Register each data source with the generic data access base class + std::wstring audioLogExtensionFilter = L"Wave file|wav"; + std::wstring audioLogDefaultExtension = L"wav"; + GenericAccessDataInfo* dataInfoShiftRegister; + GenericAccessDataInfo* dataInfoShiftRegisterDefaultValue; + GenericAccessDataInfo* dataInfoShiftRegisterWhiteNoiseBits; + GenericAccessDataInfo* dataInfoShiftRegisterPeriodicNoiseBits; + bool result = true; + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel1VolumeRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel2VolumeRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel3VolumeRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4VolumeRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel1ToneRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel2ToneRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel3ToneRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4ToneRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4NoiseType, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4NoisePeriod, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue(3)->SetLockingSupported(true)); + result &= AddGenericDataInfo(dataInfoShiftRegister = (new GenericAccessDataInfo(ISN76489DataSource::NoiseShiftRegister, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::LatchedChannelNo, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue(channelCount-1)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::VolumeRegisterLatched, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::ExternalClockRate, IGenericAccessDataValue::DataType::Double))->SetDoubleMinValue(0.0)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::ExternalClockDivider, IGenericAccessDataValue::DataType::Double))->SetDoubleMinValue(1.0)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::ShiftRegisterBitCount, IGenericAccessDataValue::DataType::UInt))->SetUIntMinValue(1)->SetUIntMaxValue(32)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Decimal)); + result &= AddGenericDataInfo(dataInfoShiftRegisterDefaultValue = (new GenericAccessDataInfo(ISN76489DataSource::ShiftRegisterDefaultValue, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo(dataInfoShiftRegisterWhiteNoiseBits = (new GenericAccessDataInfo(ISN76489DataSource::WhiteNoiseTappedBitMask, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo(dataInfoShiftRegisterPeriodicNoiseBits = (new GenericAccessDataInfo(ISN76489DataSource::PeriodicNoiseTappedBitMask, IGenericAccessDataValue::DataType::UInt))->SetUIntMaxValue((1<SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel1AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel2AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel3AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel1AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel2AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel3AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(ISN76489DataSource::Channel4AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + + //Save references to the data info structures which contain values that need to have + //their limits changed when the bitcount for the shift register is changed. + genericDataToUpdateOnShiftRegisterBitCountChange.push_back(dataInfoShiftRegister); + genericDataToUpdateOnShiftRegisterBitCountChange.push_back(dataInfoShiftRegisterDefaultValue); + genericDataToUpdateOnShiftRegisterBitCountChange.push_back(dataInfoShiftRegisterWhiteNoiseBits); + genericDataToUpdateOnShiftRegisterBitCountChange.push_back(dataInfoShiftRegisterPeriodicNoiseBits); + + //Register page layouts for generic access to this device + //##TODO## Investigate implementing a central resource system using resource key names + //of the form "AssemblyName:DictionaryName:KeyName", where each assembly registers its + //internal resource strings using FindResourceEx, LoadResource, LockResource, and the + //platform retrieves the most appropriate matching resource based on the current + //culture. That would remove literal text strings here and open our platform up for + //easy localization. Note that it must be possible for an assembly to register + //resource keys against another assembly, as well as register the same resource key + //against different cultures. I would also suggest we have the concept of a fallback + //value for a particular resource key, where a device for example could ship with all + //strings in a particular language, but another assembly could be added later which + //specifies resource overrides for all strings, including the invariant culture, while + //the fallback resource values are used in the case that nothing else is defined which + //is appropriate, IE, as might be the case if the device is updated and the + //localization isn't yet. + GenericAccessPage* registersPage = new GenericAccessPage(L"Registers", L"Registers"); + registersPage->AddEntry((new GenericAccessGroup(L"Channel 1")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel1VolumeRegister, L"Volume")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel1ToneRegister, L"Tone"))) + ->AddEntry((new GenericAccessGroup(L"Channel 2")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel2VolumeRegister, L"Volume")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel2ToneRegister, L"Tone"))) + ->AddEntry((new GenericAccessGroup(L"Channel 3")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel3VolumeRegister, L"Volume")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel3ToneRegister, L"Tone"))) + ->AddEntry((new GenericAccessGroup(L"Channel 4")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel4VolumeRegister, L"Volume")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel4ToneRegister, L"Tone")) + ->AddEntry((new GenericAccessGroupSingleSelectionList(ISN76489DataSource::Channel4NoiseType, L"Noise Type"))->SetAllowNewItemEntry(true) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"Periodic [0]"), new GenericAccessDataValueBool(false)) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"White [1]"), new GenericAccessDataValueBool(true))) + ->AddEntry((new GenericAccessGroupSingleSelectionList(ISN76489DataSource::Channel4NoisePeriod, L"Noise Period"))->SetAllowNewItemEntry(true) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"Low"), new GenericAccessDataValueUInt(0x0)) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"Medium"), new GenericAccessDataValueUInt(0x01)) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"High"), new GenericAccessDataValueUInt(0x02)) + ->AddSelectionListEntry(new GenericAccessDataValueString(L"Channel 3 Tone"), new GenericAccessDataValueUInt(0x03))) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::NoiseShiftRegister, L"Noise Shift Register"))) + ->AddEntry((new GenericAccessGroup(L"Control")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::LatchedChannelNo, L"Latched Channel No")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::VolumeRegisterLatched, L"Volume Register Latched"))); + result &= AddGenericAccessPage(registersPage); + GenericAccessPage* parametersPage = new GenericAccessPage(L"Parameters", L"Parameters"); + parametersPage->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::ExternalClockRate, L"External Clock Rate")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::ExternalClockDivider, L"External Clock Divider")) + ->AddEntry((new GenericAccessGroup(L"Noise Channel")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::ShiftRegisterBitCount, L"Shift Register Bit Count")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::ShiftRegisterDefaultValue, L"Shift Register Default Value")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::WhiteNoiseTappedBitMask, L"White Noise Tapped Bit Mask")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::PeriodicNoiseTappedBitMask, L"Periodic Noise Tapped Bit Mask"))); + result &= AddGenericAccessPage(parametersPage); + GenericAccessPage* audioLoggingPage = new GenericAccessPage(L"Audio Logging", L"Audio Logging"); + audioLoggingPage->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::AudioLoggingEnabled, L"Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::AudioLoggingPath, L"Log Path")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel1AudioLoggingEnabled, L"Channel 1 Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel2AudioLoggingEnabled, L"Channel 2 Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel3AudioLoggingEnabled, L"Channel 3 Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel4AudioLoggingEnabled, L"Channel 4 Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel1AudioLoggingPath, L"Channel 1 Log Path")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel2AudioLoggingPath, L"Channel 2 Log Path")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel3AudioLoggingPath, L"Channel 3 Log Path")) + ->AddEntry(new GenericAccessGroupDataEntry(ISN76489DataSource::Channel4AudioLoggingPath, L"Channel 4 Log Path")); + result &= AddGenericAccessPage(audioLoggingPage); + + return result; +} + +//---------------------------------------------------------------------------------------- +bool SN76489::ValidateDevice() +{ + return (externalClockRate != 0.0); +} + +//---------------------------------------------------------------------------------------- +void SN76489::Initialize() +{ + //Initialize the render thread properties + remainingRenderTime = 0; + + //Initialize the render data + for(unsigned int i = 0; i < channelCount; ++i) + { + channelRenderData[i].polarityNegative = false; + channelRenderData[i].remainingToneCycles = 0; + } + noiseShiftRegister = shiftRegisterDefaultValue; + noiseOutputMasked = true; + outputBuffer.clear(); + + //Initialize the register block, and set the correct register sizes for each entry. + reg.Initialize(); + for(unsigned int i = 0; i < channelCount; ++i) + { + if(i == noiseChannelNo) + { + reg.ReferenceCommitted((i*2) + 0).Resize(volumeRegisterBitCount); + reg.ReferenceCommitted((i*2) + 1).Resize(noiseRegisterBitCount); + } + else + { + reg.ReferenceCommitted((i*2) + 0).Resize(volumeRegisterBitCount); + reg.ReferenceCommitted((i*2) + 1).Resize(toneRegisterBitCount); + } + } + + //According to SN76489.txt by Maxim, SEGA integrated versions of the PSG have the + //channels initialized with data all zeros, and volume all ones. This has been + //verified through hardware tests. + for(unsigned int i = 0; i < channelCount; ++i) + { + if(!channelVolumeRegisterLocked[i]) + { + SetVolumeRegister(i, Data(volumeRegisterBitCount, ~0u), AccessTarget().AccessLatest()); + } + if(!channelDataRegisterLocked[i]) + { + SetToneRegister(i, Data(toneRegisterBitCount, 0), AccessTarget().AccessLatest()); + } + } + + //Note that hardware tests on a Mega Drive have shown that SEGA integrated versions of + //the PSG are initialized with the volume register of the second channel latched. + //##TODO## Make these power-on defaults configurable through the system XML file + latchedChannel = 1; + latchedVolume = true; +} + +//---------------------------------------------------------------------------------------- +//Clock source functions +//---------------------------------------------------------------------------------------- +unsigned int SN76489::GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const +{ + if(clockSourceName == L"CLOCK") + { + return (unsigned int)ClockID::Clock; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +MarshalSupport::Marshal::Ret SN76489::GetClockSourceName(unsigned int clockSourceID) const +{ + switch((ClockID)clockSourceID) + { + case ClockID::Clock: + return L"CLOCK"; + } + return L""; +} + +//---------------------------------------------------------------------------------------- +void SN76489::SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::Clock) + { + externalClockRate = clockRate; + } + + //Since a clock rate change will affect our timing point calculations, trigger a + //rollback. + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); +} + +//---------------------------------------------------------------------------------------- +void SN76489::TransparentSetClockSourceRate(unsigned int clockInput, double clockRate) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::Clock) + { + externalClockRate = clockRate; + } +} + +//---------------------------------------------------------------------------------------- +//Execute functions +//---------------------------------------------------------------------------------------- +void SN76489::BeginExecution() +{ + //Initialize the worker thread state + pendingRenderOperationCount = 0; + renderThreadLagging = false; + regTimesliceList.clear(); + + //Start the render worker thread + renderThreadActive = true; + std::thread workerThread(std::bind(std::mem_fn(&SN76489::RenderThread), this)); + workerThread.detach(); +} + +//---------------------------------------------------------------------------------------- +void SN76489::SuspendExecution() +{ + std::unique_lock lock(renderThreadMutex); + + //Suspend the render worker thread + if(renderThreadActive) + { + renderThreadActive = false; + renderThreadUpdate.notify_all(); + renderThreadStopped.wait(lock); + } +} + +//---------------------------------------------------------------------------------------- +bool SN76489::SendNotifyUpcomingTimeslice() const +{ + return true; +} + +//---------------------------------------------------------------------------------------- +void SN76489::NotifyUpcomingTimeslice(double nanoseconds) +{ + lastAccessTime = 0; + + //Add the new timeslice to all our timed buffers + reg.AddTimeslice(nanoseconds); + + //Add references to the new timeslice entry from our timed buffers to the uncommitted + //timeslice lists for the buffers + regTimesliceListUncommitted.push_back(reg.GetLatestTimeslice()); +} + +//---------------------------------------------------------------------------------------- +Device::UpdateMethod SN76489::GetUpdateMethod() const +{ + return UpdateMethod::Timeslice; +} + +//---------------------------------------------------------------------------------------- +void SN76489::ExecuteTimeslice(double nanoseconds) +{ + //If the render thread is lagging, pause here until it has caught up, so we don't + //leave the render thread behind with an ever-increasing workload it will never be + //able to complete. + if(renderThreadLagging) + { + std::unique_lock lock(timesliceMutex); + while(renderThreadLagging) + { + renderThreadLaggingStateChange.wait(lock); + } + } +} + +//---------------------------------------------------------------------------------------- +void SN76489::ExecuteRollback() +{ + //Rollback our timed buffers + reg.Rollback(); + + latchedChannel = blatchedChannel; + latchedVolume = blatchedVolume; + + //Clear any uncommitted timeslices from our render timeslice buffers + regTimesliceListUncommitted.clear(); +} + +//---------------------------------------------------------------------------------------- +void SN76489::ExecuteCommit() +{ + //Commit our timed buffers + reg.Commit(); + + blatchedChannel = latchedChannel; + blatchedVolume = latchedVolume; + + //Ensure that a valid latest timeslice exists in all our buffers. We need this check + //here, because commits can be triggered by the system at potentially any point in + //time, whether a timeslice has been issued or not. + if(!regTimesliceListUncommitted.empty()) + { + //Obtain a timeslice lock so we can update the data we feed to the render thread + std::unique_lock lock(timesliceMutex); + + //Add the number of timeslices we are about to commit to the count of pending + //render operations. This is used to track if the render thread is lagging. + pendingRenderOperationCount += (unsigned int)regTimesliceListUncommitted.size(); + + //Move all timeslices in our uncommitted timeslice lists over to the committed + //timeslice lists, for processing by the render thread. + regTimesliceList.splice(regTimesliceList.end(), regTimesliceListUncommitted); + + //Notify the render thread that it's got more work to do + renderThreadUpdate.notify_all(); + } +} + +//---------------------------------------------------------------------------------------- +//Render functions +//---------------------------------------------------------------------------------------- +void SN76489::RenderThread() +{ + std::unique_lock lock(renderThreadMutex); + + //Start the render loop + bool done = false; + while(!done) + { + //Obtain a copy of the latest completed timeslice period + RandomTimeAccessBuffer::Timeslice regTimesliceCopy; + bool renderTimesliceObtained = false; + { + std::unique_lock timesliceLock(timesliceMutex); + + //If there is at least one render timeslice pending, grab it from the queue. + if(!regTimesliceList.empty()) + { + //Update the lagging state for the render thread + --pendingRenderOperationCount; + renderThreadLagging = (pendingRenderOperationCount > maxPendingRenderOperationCount); + renderThreadLaggingStateChange.notify_all(); + + //Grab the next completed timeslice from the timeslice list + regTimesliceCopy = *regTimesliceList.begin(); + regTimesliceList.pop_front(); + + //Flag that we managed to obtain a render timeslice + renderTimesliceObtained = true; + } + } + + //If no render timeslice was available, we need to wait for a thread suspension + //request or a new timeslice to be received, then begin the loop again. + if(!renderTimesliceObtained) + { + //If the render thread has not already been instructed to stop, suspend this + //thread until a timeslice becomes available or this thread is instructed to + //stop. + if(renderThreadActive) + { + renderThreadUpdate.wait(lock); + } + + //If the render thread has been suspended, flag that we need to exit this + //render loop. + done = !renderThreadActive; + + //Begin the loop again + continue; + } + + //Render the audio output + size_t outputBufferPos = outputBuffer.size(); + double outputFrequency = externalClockRate / externalClockDivider; + bool moreSamplesRemaining = true; + while(moreSamplesRemaining) + { + //Determine the time of the next write. Note that currently, this may be + //negative under certain circumstances, in particular when a write occurs past + //the end of a timeslice. Negative times won't cause writes to be processed at + //the incorrect time under the current model, but we do need to ensure that + //remainingRenderTime isn't negative before attempting to generate an output. + remainingRenderTime += reg.GetNextWriteTime(regTimesliceCopy); + + //Calculate the output sample count. Note that remainingRenderTime may be + //negative, but we catch that below before using outputSampleCount. + unsigned int outputSampleCount = (unsigned int)(remainingRenderTime * (outputFrequency / 1000000000.0)); + + //If we have one or more output samples to generate before the next settings + //change or the end of the target timeslice, generate and output the samples. + if((remainingRenderTime > 0) && (outputSampleCount > 0)) + { + //Resize the output buffer to fit the samples we're about to add + outputBuffer.resize(outputBuffer.size() + outputSampleCount); + + //For each channel, calculate the output data for the elapsed time + std::vector channelBuffer[channelCount]; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + channelBuffer[channelNo].resize(outputSampleCount); + UpdateChannel(channelNo, outputSampleCount, channelBuffer[channelNo]); + + //Output the channel wave log + if(wavLoggingChannelEnabled[channelNo]) + { + std::unique_lock lock(waveLoggingMutex); + for(unsigned int i = 0; i < channelBuffer[channelNo].size(); ++i) + { + short sample = (short)(channelBuffer[channelNo][i] * (32767.0f/channelCount)); + wavLogChannel[channelNo].WriteData(sample); + } + } + } + + //Mix the output from each channel into a combined output buffer + for(unsigned int sampleNo = 0; sampleNo < outputSampleCount; ++sampleNo) + { + float mixedSample = 0.0; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + mixedSample += channelBuffer[channelNo][sampleNo]; + } + mixedSample /= channelCount; + outputBuffer[outputBufferPos++] = (short)(mixedSample * (32767.0f / 6.0f)); + } + + RandomTimeAccessBuffer::WriteInfo writeInfo = reg.GetWriteInfo(0, regTimesliceCopy); + if(writeInfo.exists) + { + //If the noise register is being modified, we need to reset the LFSR + //to the default for value for the next cycle. + if(writeInfo.writeAddress == (noiseChannelNo * 2) + 1) + { + noiseShiftRegister = shiftRegisterDefaultValue; + } + } + + //Adjust the remainingRenderTime variable to remove the time we just + //consumed generating the output samples. + remainingRenderTime -= (double)outputSampleCount * (1000000000.0 / outputFrequency); + } + + //Advance to the next write operation, or the end of the current timeslice. + moreSamplesRemaining = reg.AdvanceByStep(regTimesliceCopy); + } + + //Output the mixed channel wave log + if(wavLoggingEnabled) + { + std::unique_lock lock(waveLoggingMutex); + wavLog.WriteData(outputBuffer); + } + + //Play the mixed audio stream. Note that we fold samples from successive render + //operations together, ensuring that we only send data to the output audio stream + //when we have a significant number of samples to send. + size_t minimumSamplesToOutput = (size_t)(outputFrequency / 60.0); + if(outputBuffer.size() >= minimumSamplesToOutput) + { + unsigned int internalSampleCount = (unsigned int)outputBuffer.size(); + unsigned int outputSampleCount = (unsigned int)((double)internalSampleCount * ((double)outputSampleRate / outputFrequency)); + AudioStream::AudioBuffer* outputBufferFinal = outputStream.CreateAudioBuffer(outputSampleCount, 1); + if(outputBufferFinal != 0) + { + outputStream.ConvertSampleRate(outputBuffer, internalSampleCount, 1, outputBufferFinal->buffer, outputSampleCount); + outputStream.PlayBuffer(outputBufferFinal); + } + outputBuffer.clear(); + outputBuffer.reserve(minimumSamplesToOutput * 2); + } + + //Advance past the timeslice we've just rendered from + { + std::unique_lock lock(timesliceMutex); + reg.AdvancePastTimeslice(regTimesliceCopy); + } + } + renderThreadStopped.notify_all(); +} + +//---------------------------------------------------------------------------------------- +void SN76489::UpdateChannel(unsigned int channelNo, unsigned int outputSampleCount, std::vector& outputBuffer) +{ + ChannelRenderData* renderData = &channelRenderData[channelNo]; + + //Read current register data, and calculate half-frequency and amplitude + Data volumeRegisterData(GetVolumeRegister(channelNo, AccessTarget().AccessCommitted())); + Data toneRegisterData(GetToneRegister(channelNo, AccessTarget().AccessCommitted())); + float amplitude = 0.0; + if(volumeRegisterData.GetData() < 0xF) + { + //##NOTE## There is an error in SN76489.txt regarding attenuation. The document + //correctly states that each step of the volume register corresponds with 2db of + //attenuation (as stated by the SN76489 datasheet), however the math that follows + //is erroneous. A decibel is a 10th of a bel(0.1 bels), not 10 bels, and a 2db + //drop corresponds to the ratio 10^(-0.2), not 10^(-0.1). + //##NOTE## There might be more to this. Remember that we had to divide the + //attenuation power in the YM2612 core by 2 to get the correct result. Maybe + //Maxim is right afterall, and you have to halve the attenuation power in the + //YM2612 core, and this core, in order to get the correct result. Examine the + //math he provided and do some more research. Maybe we're wrong about our + //conversion from db to linear. +// float attenuationInBels = (float)(volumeRegisterData.GetData() * 2) / 10.0f; + float attenuationInBels = (float)volumeRegisterData.GetData() / 10.0f; + amplitude = pow(10.0f, -attenuationInBels); + } + + //If we're updating the noise register, decode the noise register data. + bool whiteNoiseSelected = false; + if(channelNo == noiseChannelNo) + { + //Noise register format + // -------------- + // | 2 | 1 | 0 | + // |------------| + // |Type|Period | + // ============== + //Type: Noise type (0 = Periodic, 1 = White) + //Period: Shift rate (0 = 0x10, 1 = 0x20, 2 = 0x40, 3 = Tone2) + whiteNoiseSelected = toneRegisterData.GetBit(2); + switch(toneRegisterData.GetDataSegment(0, 2)) + { + case 0: + toneRegisterData = 0x10; + break; + case 1: + toneRegisterData = 0x20; + break; + case 2: + toneRegisterData = 0x40; + break; + case 3: + //Read the current tone register data from channel 2 + toneRegisterData = GetToneRegister(2, AccessTarget().AccessCommitted()).GetData(); + break; + } + } + + //If we were partway through a cycle on this channel when we rendered the last step, + //resume the last cycle. + unsigned int samplesWritten = 0; + while((renderData->remainingToneCycles > 0) && (samplesWritten < outputSampleCount)) + { + //If we're starting the output on a negative cycle, negate the output data. + float writeData = (renderData->polarityNegative)? -amplitude: amplitude; + + //If we're updating the noise register, calculate the output data based on + //the shift register. + if(channelNo == noiseChannelNo) + { + //Use the current noise bit to calculate the output data + writeData = (noiseOutputMasked)? 0: amplitude; + } + + //Write the sample to the output buffer + outputBuffer[samplesWritten++] = writeData; + --renderData->remainingToneCycles; + } + + //##NOTE## Hardware tests on the SEGA integrated chip have shown that when the tone + //data is set to 0, it behaves the same as a tone data value of 1. This includes the + //noise channel when the period is obtained from the channel 2 tone data. This + //behaviour contradicts the information in SN76489.txt, but our readings are clear. + //Tone data values of both 0 and 1 produce a square wave that toggles between + //positive and negative each internal clock cycle. This has been confirmed by + //sampling the PSG output directly from the chip using an oscilloscope. SN76489.txt + //states that the channel output is held at +1 when the tone data is set to 0. + //Perhaps this is true for other implementations of this device, but our observed + //behaviour is correct for the SEGA embedded version used in the Mega Drive. Note + //that "After Burner II" uses a tone value of 0 in all PSG channels for its audio, + //causing distorted sound on the system. The PSG sound emulation for this game is + //fundamentally inaccurate when we hold the output at +1. + if(toneRegisterData == 0) + { + toneRegisterData = 1; + } + + //Output repeating oscillations of the wave at the target frequency and amplitude + while(samplesWritten < outputSampleCount) + { + unsigned int samplesToWrite = toneRegisterData.GetData(); + + //Invert the polarity of the wave in preparation for the new cycle + renderData->polarityNegative = !renderData->polarityNegative; + + //If we're starting the output on a negative cycle, negate the output data. + float writeData = (renderData->polarityNegative)? -amplitude: amplitude; + + //If we're updating the noise register, calculate the output data based on + //the shift register. + if(channelNo == noiseChannelNo) + { + unsigned int tappedBitMask = whiteNoiseSelected? noiseWhiteTappedBitMask: noisePeriodicTappedBitMask; + + //If the polarity has shifted from -1 to +1, read a new output bit + //and adjust the shift register. + if(!renderData->polarityNegative) + { + Data shiftRegister(shiftRegisterBitCount, noiseShiftRegister); + noiseOutputMasked = !shiftRegister.GetBit(0); + bool newUpperBit = !((shiftRegister & tappedBitMask).ParityEven()); + shiftRegister >>= 1; + shiftRegister.SetBit(shiftRegister.GetBitCount() - 1, newUpperBit); + noiseShiftRegister = shiftRegister.GetData(); + } + + //Use the current noise bit to calculate the output data + writeData = (noiseOutputMasked)? 0: amplitude; + } + + if(samplesToWrite > (outputSampleCount - samplesWritten)) + { + //If we don't have enough samples remaining in this step to complete + //the next cycle, clamp the number of samples to write, and save the + //number of additional samples we need to complete for the next step. + renderData->initialToneCycles = samplesToWrite; + renderData->remainingToneCycles = samplesToWrite - (outputSampleCount - samplesWritten); + samplesToWrite = (outputSampleCount - samplesWritten); + } + + //Write a block of samples to the output buffer + for(unsigned int i = 0; i < samplesToWrite; ++i) + { + outputBuffer[samplesWritten++] = writeData; + } + } +} + +//---------------------------------------------------------------------------------------- +//Memory interface functions +//---------------------------------------------------------------------------------------- +IBusInterface::AccessResult SN76489::WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(accessMutex); + AccessTarget accessTarget; + accessTarget.AccessTime(accessTime); + + //Trigger a system rollback if the device has been accessed out of order. This is + //required in order to ensure that the register latch settings are correct when each + //write occurs. + if(accessTime < lastAccessTime) + { + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); + } + lastAccessTime = accessTime; + + //Process the write + if(data.MSB()) + { + //Latch/Data byte format + //---------------------------------- + //| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //|---|-------|----|---------------| + //| 1 |Channel|Type|Data (low bits)| + //---------------------------------- + + //Process a latch/data byte + latchedChannel = data.GetDataSegment(5, 2); + latchedVolume = data.GetBit(4); + if(latchedVolume) + { + Data temp(GetVolumeRegister(latchedChannel, accessTarget)); + temp.SetLowerBits(4, data.GetDataSegment(0, 4)); + if(!channelVolumeRegisterLocked[latchedChannel]) + { + SetVolumeRegister(latchedChannel, temp, accessTarget); + } + } + else + { + Data temp(GetToneRegister(latchedChannel, accessTarget)); + temp.SetLowerBits(4, data.GetDataSegment(0, 4)); + if(latchedChannel == noiseChannelNo) + { + if(noiseChannelTypeLocked) + { + temp.SetBit(2, GetToneRegister(latchedChannel, accessTarget).GetBit(2)); + } + if(noiseChannelPeriodLocked) + { + temp.SetDataSegment(0, 2, GetToneRegister(latchedChannel, accessTarget).GetDataSegment(0, 2)); + } + } + if(!channelDataRegisterLocked[latchedChannel]) + { + SetToneRegister(latchedChannel, temp, accessTarget); + } + } + } + else + { + //Data byte format + //--------------------------------- + //| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //|---|---|-----------------------| + //| 0 | - | Data (high bits) | + //--------------------------------- + + //Process a data byte + if(latchedVolume) + { + Data temp(GetVolumeRegister(latchedChannel, accessTarget)); + temp.SetUpperBits(6, data.GetDataSegment(0, 6)); + if(!channelVolumeRegisterLocked[latchedChannel]) + { + SetVolumeRegister(latchedChannel, temp, accessTarget); + } + } + else + { + Data temp(GetToneRegister(latchedChannel, accessTarget)); + temp.SetUpperBits(6, data.GetDataSegment(0, 6)); + if(latchedChannel == noiseChannelNo) + { + if(noiseChannelTypeLocked) + { + temp.SetBit(2, GetToneRegister(latchedChannel, accessTarget).GetBit(2)); + } + if(noiseChannelPeriodLocked) + { + temp.SetDataSegment(0, 2, GetToneRegister(latchedChannel, accessTarget).GetDataSegment(0, 2)); + } + } + if(!channelDataRegisterLocked[latchedChannel]) + { + SetToneRegister(latchedChannel, temp, accessTarget); + } + } + } + + return true; +} + +//---------------------------------------------------------------------------------------- +//Savestate functions +//---------------------------------------------------------------------------------------- +void SN76489::LoadState(IHierarchicalStorageNode& node) +{ + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + //Clock settings + if((*i)->GetName() == L"ExternalClockRate") + { + (*i)->ExtractData(externalClockRate); + } + + //Register data + else if((*i)->GetName() == L"Registers") + { + reg.LoadState(*(*i)); + } + + //Register latch settings + else if((*i)->GetName() == L"LatchedChannel") + { + (*i)->ExtractData(latchedChannel); + if(latchedChannel >= channelCount) + { + latchedChannel = channelCount - 1; + } + } + else if((*i)->GetName() == L"VolumeRegisterLatched") + { + (*i)->ExtractData(latchedVolume); + } + + //Render thread properties + else if((*i)->GetName() == L"RemainingRenderTime") + { + (*i)->ExtractData(remainingRenderTime); + } + + //Render data + else if((*i)->GetName() == L"RenderData") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + (*i)->ExtractAttributeHex(L"InitialToneCycles", channelRenderData[channelNo].initialToneCycles); + (*i)->ExtractAttributeHex(L"RemainingToneCycles", channelRenderData[channelNo].remainingToneCycles); + (*i)->ExtractAttribute(L"PolarityNegative", channelRenderData[channelNo].polarityNegative); + } + } + else if((*i)->GetName() == L"NoiseShiftRegister") + { + (*i)->ExtractHexData(noiseShiftRegister); + } + else if((*i)->GetName() == L"NoiseOutputMasked") + { + (*i)->ExtractData(noiseOutputMasked); + } + } +} + +//---------------------------------------------------------------------------------------- +void SN76489::SaveState(IHierarchicalStorageNode& node) const +{ + //Clock settings + node.CreateChild(L"ExternalClockRate").SetData(externalClockRate); + + //Register data + reg.SaveState(node.CreateChild(L"Registers"), L"", true); + + //Register latch settings + node.CreateChild(L"LatchedChannel", latchedChannel); + node.CreateChild(L"VolumeRegisterLatched", latchedVolume); + + //Render thread properties + node.CreateChild(L"RemainingRenderTime", remainingRenderTime); + + //Render data + for(unsigned int i = 0; i < channelCount; ++i) + { + IHierarchicalStorageNode& renderDataState = node.CreateChild(L"RenderData"); + renderDataState.CreateAttribute(L"ChannelNo", i); + renderDataState.CreateAttributeHex(L"InitialToneCycles", channelRenderData[i].initialToneCycles, (toneRegisterBitCount+3)/4); + renderDataState.CreateAttributeHex(L"RemainingToneCycles", channelRenderData[i].remainingToneCycles, (toneRegisterBitCount+3)/4); + renderDataState.CreateAttribute(L"PolarityNegative", channelRenderData[i].polarityNegative); + } + node.CreateChildHex(L"NoiseShiftRegister", noiseShiftRegister, (shiftRegisterBitCount+3)/4); + node.CreateChild(L"NoiseOutputMasked", noiseOutputMasked); +} + +//---------------------------------------------------------------------------------------- +void SN76489::LoadDebuggerState(IHierarchicalStorageNode& node) +{ + //Initialize the register locking state + for(unsigned int i = 0; i < channelCount; ++i) + { + channelVolumeRegisterLocked[i] = false; + channelDataRegisterLocked[i] = false; + } + + //Load the register locking state + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + if((*i)->GetName() == L"LockedVolumeRegister") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + channelVolumeRegisterLocked[channelNo] = true; + } + } + else if((*i)->GetName() == L"LockedDataRegister") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + channelDataRegisterLocked[channelNo] = true; + } + } + } +} + +//---------------------------------------------------------------------------------------- +void SN76489::SaveDebuggerState(IHierarchicalStorageNode& node) const +{ + //Save the register locking state + for(unsigned int i = 0; i < channelCount; ++i) + { + if(channelVolumeRegisterLocked[i]) + { + node.CreateChild(L"LockedVolumeRegister").CreateAttribute(L"ChannelNo", i); + } + if(channelDataRegisterLocked[i]) + { + node.CreateChild(L"LockedDataRegister").CreateAttribute(L"ChannelNo", i); + } + } +} + +//---------------------------------------------------------------------------------------- +//Data read/write functions +//---------------------------------------------------------------------------------------- +bool SN76489::ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const +{ + ApplyGenericDataValueDisplaySettings(dataID, dataValue); + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::Channel1VolumeRegister: + return dataValue.SetValue(GetVolumeRegister(0, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel2VolumeRegister: + return dataValue.SetValue(GetVolumeRegister(1, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel3VolumeRegister: + return dataValue.SetValue(GetVolumeRegister(2, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel4VolumeRegister: + return dataValue.SetValue(GetVolumeRegister(3, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel1ToneRegister: + return dataValue.SetValue(GetToneRegister(0, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel2ToneRegister: + return dataValue.SetValue(GetToneRegister(1, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel3ToneRegister: + return dataValue.SetValue(GetToneRegister(2, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel4ToneRegister: + return dataValue.SetValue(GetToneRegister(3, AccessTarget().AccessLatest()).GetData()); + case ISN76489DataSource::Channel4NoiseType: + return dataValue.SetValue(GetToneRegister(3, AccessTarget().AccessLatest()).GetBit(2)); + case ISN76489DataSource::Channel4NoisePeriod: + return dataValue.SetValue(GetToneRegister(3, AccessTarget().AccessLatest()).GetDataSegment(0, 2)); + case ISN76489DataSource::NoiseShiftRegister: + return dataValue.SetValue(noiseShiftRegister); + case ISN76489DataSource::LatchedChannelNo: + return dataValue.SetValue(latchedChannel); + case ISN76489DataSource::VolumeRegisterLatched: + return dataValue.SetValue(latchedVolume); + case ISN76489DataSource::ExternalClockRate: + return dataValue.SetValue(externalClockRate); + case ISN76489DataSource::ExternalClockDivider: + return dataValue.SetValue(externalClockDivider); + case ISN76489DataSource::ShiftRegisterBitCount: + return dataValue.SetValue(shiftRegisterBitCount); + case ISN76489DataSource::ShiftRegisterDefaultValue: + return dataValue.SetValue(shiftRegisterDefaultValue); + case ISN76489DataSource::WhiteNoiseTappedBitMask: + return dataValue.SetValue(noiseWhiteTappedBitMask); + case ISN76489DataSource::PeriodicNoiseTappedBitMask: + return dataValue.SetValue(noisePeriodicTappedBitMask); + case ISN76489DataSource::AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingEnabled); + case ISN76489DataSource::AudioLoggingPath: + return dataValue.SetValue(wavLoggingPath); + case ISN76489DataSource::Channel1AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingChannelEnabled[0]); + case ISN76489DataSource::Channel2AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingChannelEnabled[1]); + case ISN76489DataSource::Channel3AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingChannelEnabled[2]); + case ISN76489DataSource::Channel4AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingChannelEnabled[3]); + case ISN76489DataSource::Channel1AudioLoggingPath: + return dataValue.SetValue(wavLoggingChannelPath[0]); + case ISN76489DataSource::Channel2AudioLoggingPath: + return dataValue.SetValue(wavLoggingChannelPath[1]); + case ISN76489DataSource::Channel3AudioLoggingPath: + return dataValue.SetValue(wavLoggingChannelPath[2]); + case ISN76489DataSource::Channel4AudioLoggingPath: + return dataValue.SetValue(wavLoggingChannelPath[3]); + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool SN76489::WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) +{ + //##TODO## Restructure this to be a flat switch statement as per other devices + ApplyGenericDataValueLimitSettings(dataID, dataValue); + IGenericAccessDataValue::DataType dataType = dataValue.GetType(); + if(dataType == IGenericAccessDataValue::DataType::UInt) + { + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::Channel1VolumeRegister: + SetVolumeRegister(0, Data(volumeRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel2VolumeRegister: + SetVolumeRegister(1, Data(volumeRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel3VolumeRegister: + SetVolumeRegister(2, Data(volumeRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel4VolumeRegister: + SetVolumeRegister(3, Data(volumeRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel1ToneRegister: + SetToneRegister(0, Data(toneRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel2ToneRegister: + SetToneRegister(1, Data(toneRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel3ToneRegister: + SetToneRegister(2, Data(toneRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel4ToneRegister: + SetToneRegister(3, Data(toneRegisterBitCount, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::Channel4NoisePeriod: + SetToneRegister(3, GetToneRegister(3, AccessTarget().AccessLatest()).SetDataSegment(0, 2, dataValueAsUInt.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::NoiseShiftRegister: + noiseShiftRegister = Data(GetShiftRegisterBitCount(), dataValueAsUInt.GetValue()).GetData(); + return true; + case ISN76489DataSource::LatchedChannelNo: + latchedChannel = dataValueAsUInt.GetValue(); + return true; + case ISN76489DataSource::ShiftRegisterBitCount:{ + shiftRegisterBitCount = dataValueAsUInt.GetValue(); + //Update the maximum allowable values for each data value that depends on the + //shift register bit count + unsigned int shiftRegisterBitCountMask = (((1 << (shiftRegisterBitCount - 1)) - 1) << 1) | 1; + for(std::list::const_iterator i = genericDataToUpdateOnShiftRegisterBitCountChange.begin(); i != genericDataToUpdateOnShiftRegisterBitCountChange.end(); ++i) + { + (*i)->SetUIntMaxValue(shiftRegisterBitCountMask); + } + //Limit the current values of any settings that are affected by the shift + //register bit count + shiftRegisterDefaultValue &= shiftRegisterBitCountMask; + noiseWhiteTappedBitMask &= shiftRegisterBitCountMask; + noisePeriodicTappedBitMask &= shiftRegisterBitCountMask; + return true;} + case ISN76489DataSource::ShiftRegisterDefaultValue: + shiftRegisterDefaultValue = dataValueAsUInt.GetValue(); + return true; + case ISN76489DataSource::WhiteNoiseTappedBitMask: + noiseWhiteTappedBitMask = dataValueAsUInt.GetValue(); + return true; + case ISN76489DataSource::PeriodicNoiseTappedBitMask: + noisePeriodicTappedBitMask = dataValueAsUInt.GetValue(); + return true; + } + } + else if(dataType == IGenericAccessDataValue::DataType::Bool) + { + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::Channel4NoiseType: + SetToneRegister(3, GetToneRegister(3, AccessTarget().AccessLatest()).SetBit(2, dataValueAsBool.GetValue()), AccessTarget().AccessLatest()); + return true; + case ISN76489DataSource::VolumeRegisterLatched: + latchedVolume = dataValueAsBool.GetValue(); + return true; + case ISN76489DataSource::AudioLoggingEnabled: + SetAudioLoggingEnabled(dataValueAsBool.GetValue()); + return true; + case ISN76489DataSource::Channel1AudioLoggingEnabled: + SetChannelAudioLoggingEnabled(0, dataValueAsBool.GetValue()); + return true; + case ISN76489DataSource::Channel2AudioLoggingEnabled: + SetChannelAudioLoggingEnabled(1, dataValueAsBool.GetValue()); + return true; + case ISN76489DataSource::Channel3AudioLoggingEnabled: + SetChannelAudioLoggingEnabled(2, dataValueAsBool.GetValue()); + return true; + case ISN76489DataSource::Channel4AudioLoggingEnabled: + SetChannelAudioLoggingEnabled(3, dataValueAsBool.GetValue()); + return true; + } + } + else if(dataType == IGenericAccessDataValue::DataType::Double) + { + IGenericAccessDataValueDouble& dataValueAsDouble = (IGenericAccessDataValueDouble&)dataValue; + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::ExternalClockRate: + externalClockRate = dataValueAsDouble.GetValue(); + return true; + case ISN76489DataSource::ExternalClockDivider: + externalClockDivider = dataValueAsDouble.GetValue(); + return true; + } + } + else if(dataType == IGenericAccessDataValue::DataType::FilePath) + { + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::AudioLoggingPath: + wavLoggingPath = dataValueAsFilePath.GetValue(); + return true; + case ISN76489DataSource::Channel1AudioLoggingPath: + wavLoggingChannelPath[0] = dataValueAsFilePath.GetValue(); + return true; + case ISN76489DataSource::Channel2AudioLoggingPath: + wavLoggingChannelPath[1] = dataValueAsFilePath.GetValue(); + return true; + case ISN76489DataSource::Channel3AudioLoggingPath: + wavLoggingChannelPath[2] = dataValueAsFilePath.GetValue(); + return true; + case ISN76489DataSource::Channel4AudioLoggingPath: + wavLoggingChannelPath[3] = dataValueAsFilePath.GetValue(); + return true; + } + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Data locking functions +//---------------------------------------------------------------------------------------- +bool SN76489::GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const +{ + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::Channel1VolumeRegister: + return channelVolumeRegisterLocked[0]; + case ISN76489DataSource::Channel2VolumeRegister: + return channelVolumeRegisterLocked[1]; + case ISN76489DataSource::Channel3VolumeRegister: + return channelVolumeRegisterLocked[2]; + case ISN76489DataSource::Channel4VolumeRegister: + return channelVolumeRegisterLocked[3]; + case ISN76489DataSource::Channel1ToneRegister: + return channelDataRegisterLocked[0]; + case ISN76489DataSource::Channel2ToneRegister: + return channelDataRegisterLocked[1]; + case ISN76489DataSource::Channel3ToneRegister: + return channelDataRegisterLocked[2]; + case ISN76489DataSource::Channel4ToneRegister: + return channelDataRegisterLocked[3]; + case ISN76489DataSource::Channel4NoiseType: + return channelDataRegisterLocked[3] || noiseChannelTypeLocked; + case ISN76489DataSource::Channel4NoisePeriod: + return channelDataRegisterLocked[3] || noiseChannelPeriodLocked; + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool SN76489::SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state) +{ + switch((ISN76489DataSource)dataID) + { + case ISN76489DataSource::Channel1VolumeRegister: + channelVolumeRegisterLocked[0] = state; + return true; + case ISN76489DataSource::Channel2VolumeRegister: + channelVolumeRegisterLocked[1] = state; + return true; + case ISN76489DataSource::Channel3VolumeRegister: + channelVolumeRegisterLocked[2] = state; + return true; + case ISN76489DataSource::Channel4VolumeRegister: + channelVolumeRegisterLocked[3] = state; + return true; + case ISN76489DataSource::Channel1ToneRegister: + channelDataRegisterLocked[0] = state; + return true; + case ISN76489DataSource::Channel2ToneRegister: + channelDataRegisterLocked[1] = state; + return true; + case ISN76489DataSource::Channel3ToneRegister: + channelDataRegisterLocked[2] = state; + return true; + case ISN76489DataSource::Channel4ToneRegister: + channelDataRegisterLocked[3] = state; + return true; + case ISN76489DataSource::Channel4NoiseType: + noiseChannelTypeLocked = state; + channelDataRegisterLocked[3] = false; + return true; + case ISN76489DataSource::Channel4NoisePeriod: + noiseChannelPeriodLocked = state; + channelDataRegisterLocked[3] = false; + return true; + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Audio logging functions +//---------------------------------------------------------------------------------------- +void SN76489::SetAudioLoggingEnabled(bool state) +{ + std::unique_lock lock(waveLoggingMutex); + if(wavLoggingEnabled != state) + { + if(state) + { + double outputFrequency = externalClockRate / externalClockDivider; + wavLog.SetDataFormat(1, 16, (unsigned int)outputFrequency); + wavLog.Open(wavLoggingPath, Stream::WAVFile::OpenMode::WriteOnly, Stream::WAVFile::CreateMode::Create); + } + else + { + wavLog.Close(); + } + wavLoggingEnabled = state; + } +} + +//---------------------------------------------------------------------------------------- +void SN76489::SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state) +{ + std::unique_lock lock(waveLoggingMutex); + if(wavLoggingChannelEnabled[channelNo] != state) + { + if(state) + { + double outputFrequency = externalClockRate / externalClockDivider; + wavLogChannel[channelNo].SetDataFormat(1, 16, (unsigned int)outputFrequency); + wavLogChannel[channelNo].Open(wavLoggingChannelPath[channelNo], Stream::WAVFile::OpenMode::WriteOnly, Stream::WAVFile::CreateMode::Create); + } + else + { + wavLogChannel[channelNo].Close(); + } + wavLoggingChannelEnabled[channelNo] = state; + } +} diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.h new file mode 100644 index 0000000000000000000000000000000000000000..5de439ec87ddc67eca99fc584234ff2b1770467b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/SN76489.h @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------*\ +Description: +This core emulates the SN76489 Programmable Sound Generator (PSG), and is designed to +produce a sample-accurate output. Each channel is generated and mixed at the correct +internal sample rate, and all known aspects and behaviour of this device are faithfully +emulated. + +Things to do: +-Get a final answer on the conversion from attenuation to linear power, and document it +within your core. +-Make it possible to define the clock and noise register settings externally + +Output filtering: +-Note that there is real "decay-like" behaviour, which comes from the audio output +circuitry in the Mega Drive. The same circuit affects the output of the YM2612 in the +same way. If we want to emulate this behaviour, we need to emulate it using a form of +audio filter which can be applied to any sound core, just like we need to emulate analog +video distortion using output filters. These filters need to be separate from the device +cores, and be modular and chainable. Note that we should also use output "filters" to +balance output levels between sound devices. +-Measure the final audio output levels from the embedded SN76489 in the Mega Drive, both +directly from the chip and after the mixing circuit. According to SN76489.txt, several of +the minimum attenuation levels may in fact be clipped, which will greatly affect the +overall volume of the PSG, and the relative volume levels of the different register +settings on the system. + +Debug output modifications: +-Add the calculated frequency, and attenuation in db, for each channel, on the register +debug window. +-Display the noise register using its actual separate register values, named correctly, +on the register debug window. + +References: +-SN76489 Notes (SN76489.txt), Maxim, 2005 +-Genesis Sound Software Manual, Sega Enterprises, 1992, scans by antime +-SN76489 Datasheet, Texas Instruments +-SN76494 Datasheet, Texas Instruments +-SN76489 sound chip details, John Kortink, http://web.inter.nl.net/users/J.Kortink/home/articles/sn76489/index.htm +\*--------------------------------------------------------------------------------------*/ +#include "ISN76489.h" +#ifndef __SN76489_H__ +#define __SN76489_H__ +#include "DeviceInterface/DeviceInterface.pkg" +#include "TimedBuffers/TimedBuffers.pkg" +#include +#include +#include +#include +#include "Device/Device.pkg" +#include "AudioStream/AudioStream.pkg" +#include "Stream/Stream.pkg" +#include +#include + +class SN76489 :public Device, public GenericAccessBase +{ +public: + //Constructors + SN76489(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID); + + //Interface version functions + virtual unsigned int GetISN76489Version() const; + + //Initialization functions + virtual bool BuildDevice(); + virtual bool ValidateDevice(); + virtual void Initialize(); + + //Clock source functions + virtual unsigned int GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const; + virtual MarshalSupport::Marshal::Ret GetClockSourceName(unsigned int clockSourceID) const; + virtual void SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual void TransparentSetClockSourceRate(unsigned int clockInput, double clockRate); + + //Execute functions + virtual void BeginExecution(); + virtual void SuspendExecution(); + virtual bool SendNotifyUpcomingTimeslice() const; + virtual void NotifyUpcomingTimeslice(double nanoseconds); + virtual UpdateMethod GetUpdateMethod() const; + virtual void ExecuteTimeslice(double nanoseconds); + virtual void ExecuteRollback(); + virtual void ExecuteCommit(); + + //Memory interface functions + virtual IBusInterface::AccessResult WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext); + + //Savestate functions + virtual void LoadState(IHierarchicalStorageNode& node); + virtual void SaveState(IHierarchicalStorageNode& node) const; + virtual void LoadDebuggerState(IHierarchicalStorageNode& node); + virtual void SaveDebuggerState(IHierarchicalStorageNode& node) const; + + //Data read/write functions + virtual bool ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const; + virtual bool WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue); + + //Data locking functions + virtual bool GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const; + virtual bool SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state); + +private: + //Enumerations + enum class ClockID; + + //Structures + struct ChannelRenderData + { + unsigned int initialToneCycles; + unsigned int remainingToneCycles; + bool polarityNegative; + }; + + //Typedefs + typedef RandomTimeAccessBuffer::AccessTarget AccessTarget; + +private: + //Render functions + void RenderThread(); + void UpdateChannel(unsigned int channelNo, unsigned int outputSampleCount, std::vector& outputBuffer); + + //Raw register functions + inline Data GetVolumeRegister(unsigned int channelNo, const AccessTarget& accessTarget) const; + inline void SetVolumeRegister(unsigned int channelNo, const Data& adata, const AccessTarget& accessTarget); + inline Data GetToneRegister(unsigned int channelNo, const AccessTarget& accessTarget) const; + inline void SetToneRegister(unsigned int channelNo, const Data& adata, const AccessTarget& accessTarget); + + //Audio logging functions + void SetAudioLoggingEnabled(bool state); + void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state); + +private: + //Registers + mutable std::mutex accessMutex; + double lastAccessTime; + RandomTimeAccessBuffer reg; + unsigned int latchedChannel; + unsigned int blatchedChannel; + bool latchedVolume; + bool blatchedVolume; + + //Render thread properties + mutable std::mutex renderThreadMutex; + mutable std::mutex timesliceMutex; + std::condition_variable renderThreadUpdate; + std::condition_variable renderThreadStopped; + bool renderThreadActive; + static const unsigned int maxPendingRenderOperationCount = 4; + bool renderThreadLagging; + std::condition_variable renderThreadLaggingStateChange; + unsigned int pendingRenderOperationCount; + std::list::Timeslice> regTimesliceList; + std::list::Timeslice> regTimesliceListUncommitted; + double remainingRenderTime; + unsigned int outputSampleRate; + AudioStream outputStream; + std::vector outputBuffer; + + //Render data + ChannelRenderData channelRenderData[channelCount]; + unsigned int noiseShiftRegister; + bool noiseOutputMasked; + + //Device Properties + double externalClockRate; + double externalClockDivider; + unsigned int shiftRegisterBitCount; + unsigned int shiftRegisterDefaultValue; + unsigned int noiseWhiteTappedBitMask; + unsigned int noisePeriodicTappedBitMask; + std::list genericDataToUpdateOnShiftRegisterBitCountChange; + + //Register locking + bool channelVolumeRegisterLocked[channelCount]; + bool channelDataRegisterLocked[channelCount]; + bool noiseChannelTypeLocked; + bool noiseChannelPeriodLocked; + + //Wave logging + mutable std::mutex waveLoggingMutex; + bool wavLoggingEnabled; + bool wavLoggingChannelEnabled[channelCount]; + std::wstring wavLoggingPath; + std::wstring wavLoggingChannelPath[channelCount]; + Stream::WAVFile wavLog; + Stream::WAVFile wavLogChannel[channelCount]; +}; + +#include "SN76489.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..131ffb2f5b1f7d436a532a0ac3c95aabd7d1baab --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.cpp @@ -0,0 +1,42 @@ +#include "DeviceInterface/DeviceInterface.pkg" +#include "SN76489.h" + +IDevice* GetSN76489(const wchar_t* implementationName, const wchar_t* instanceName, unsigned int moduleID) +{ + return static_cast(new SN76489(implementationName, instanceName, moduleID)); +} + +void DeleteSN76489(IDevice* device) +{ + delete static_cast(device); +} + +#ifdef EX_DLLINTERFACE +extern "C" __declspec(dllexport) unsigned int GetInterfaceVersion() +{ + return EXODUS_INTERFACEVERSION; +} + +extern "C" __declspec(dllexport) bool GetDeviceEntry(unsigned int entryNo, IDeviceInfo& entry) +{ + //Retrieve any required information from the version info table for our plugin + std::wstring copyrightText; + std::wstring commentsText; + HMODULE moduleHandle = NULL; + BOOL getModuleHandleExReturn = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)GetDeviceEntry, &moduleHandle); + if(getModuleHandleExReturn != 0) + { + std::wstring modulePath = GetModuleFilePath(moduleHandle); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_LEGALCOPYRIGHT, copyrightText); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_COMMENTS, commentsText); + } + + switch(entryNo) + { + case 0: + entry.SetDeviceSettings(GetSN76489, DeleteSN76489, L"Audio.SN76489", L"SN76489", 1, copyrightText, commentsText); + return true; + } + return false; +} +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..35571bdb732d1ccfaa394079700849a936f2d5d5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/interface.h @@ -0,0 +1,7 @@ +#ifndef __SN76489_INTERFACE_H__ +#define __SN76489_INTERFACE_H__ +#include "DeviceInterface/DeviceInterface.pkg" + +void GetSN76489DeviceInfo(IDeviceInfo& deviceInfo); + +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/resource.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/resource.h new file mode 100644 index 0000000000000000000000000000000000000000..659964375a88b6160f63101eb35fe983ad6a516b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/SN76489/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by SN76489.rc +// +#define IDI_ICON1 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/IYM2612.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/IYM2612.h new file mode 100644 index 0000000000000000000000000000000000000000..c964f2f97e057fc84f3071815cd154fd37e3c837 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/IYM2612.h @@ -0,0 +1,169 @@ +#ifndef __IYM2612_H__ +#define __IYM2612_H__ +#include "GenericAccess/GenericAccess.pkg" +#include + +class IYM2612 :public virtual IGenericAccess +{ +public: + //Constants + static const unsigned int channelCount = 6; + static const unsigned int operatorCount = 4; + static const unsigned int partCount = 2; + static const unsigned int registerCountPerPart = 0x100; + static const unsigned int registerCountTotal = registerCountPerPart * partCount; + + //Enumerations + enum class IYM2612DataSource; + enum Channels :unsigned int; + enum Operators :unsigned int; + + //Structures + struct RegisterDataContext; + struct ChannelDataContext; + struct OperatorDataContext; + +public: + //Interface version functions + static inline unsigned int ThisIYM2612Version() { return 1; } + virtual unsigned int GetIYM2612Version() const = 0; + + //Clock setting functions + inline double GetExternalClockRate() const; + inline void SetExternalClockRate(double adata); + inline unsigned int GetFMClockDivider() const; + inline void SetFMClockDivider(unsigned int adata); + inline unsigned int GetEGClockDivider() const; + inline void SetEGClockDivider(unsigned int adata); + inline unsigned int GetOutputClockDivider() const; + inline void SetOutputClockDivider(unsigned int adata); + inline unsigned int GetTimerAClockDivider() const; + inline void SetTimerAClockDivider(unsigned int adata); + inline unsigned int GetTimerBClockDivider() const; + inline void SetTimerBClockDivider(unsigned int adata); + + //Raw register functions + inline unsigned int GetRegisterData(unsigned int registerNo) const; + inline void SetRegisterData(unsigned int registerNo, unsigned int adata); + + //Common FM register functions + inline unsigned int GetTestData() const; + inline void SetTestData(unsigned int adata); + inline bool GetLFOEnabled() const; + inline void SetLFOEnabled(bool adata); + inline unsigned int GetLFOData() const; + inline void SetLFOData(unsigned int adata); + inline unsigned int GetTimerAData() const; + inline void SetTimerAData(unsigned int adata); + inline unsigned int GetTimerBData() const; + inline void SetTimerBData(unsigned int adata); + inline unsigned int GetCH3Mode() const; + inline void SetCH3Mode(unsigned int adata); + inline bool GetTimerBReset() const; + inline void SetTimerBReset(bool adata); + inline bool GetTimerAReset() const; + inline void SetTimerAReset(bool adata); + inline bool GetTimerBEnable() const; + inline void SetTimerBEnable(bool adata); + inline bool GetTimerAEnable() const; + inline void SetTimerAEnable(bool adata); + inline bool GetTimerBLoad() const; + inline void SetTimerBLoad(bool adata); + inline bool GetTimerALoad() const; + inline void SetTimerALoad(bool adata); + inline unsigned int GetDACData() const; + inline void SetDACData(unsigned int adata); + inline bool GetDACEnabled() const; + inline void SetDACEnabled(bool adata); + + //FM operator register functions + inline unsigned int GetDetuneData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetDetuneData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetMultipleData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetMultipleData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetTotalLevelData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetTotalLevelData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetKeyScaleData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetKeyScaleData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetAttackRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetAttackRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline bool GetAmplitudeModulationEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetAmplitudeModulationEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline unsigned int GetDecayRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetDecayRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSustainRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSustainRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSustainLevelData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSustainLevelData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetReleaseRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetReleaseRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSSGData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline bool GetSSGEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGAttack(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGAttack(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGAlternate(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGAlternate(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGHold(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGHold(unsigned int channelNo, unsigned int operatorNo, bool adata); + + //FM channel register functions + inline unsigned int GetFrequencyData(unsigned int channelNo) const; + inline void SetFrequencyData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetBlockData(unsigned int channelNo) const; + inline void SetBlockData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetFrequencyDataChannel3(unsigned int operatorNo) const; + inline void SetFrequencyDataChannel3(unsigned int operatorNo, unsigned int adata); + inline unsigned int GetBlockDataChannel3(unsigned int operatorNo) const; + inline void SetBlockDataChannel3(unsigned int operatorNo, unsigned int adata); + inline unsigned int GetFeedbackData(unsigned int channelNo) const; + inline void SetFeedbackData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetAlgorithmData(unsigned int channelNo) const; + inline void SetAlgorithmData(unsigned int channelNo, unsigned int adata); + inline bool GetOutputLeft(unsigned int channelNo) const; + inline void SetOutputLeft(unsigned int channelNo, bool adata); + inline bool GetOutputRight(unsigned int channelNo) const; + inline void SetOutputRight(unsigned int channelNo, bool adata); + inline unsigned int GetAMSData(unsigned int channelNo) const; + inline void SetAMSData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetPMSData(unsigned int channelNo) const; + inline void SetPMSData(unsigned int channelNo, unsigned int adata); + + //Key on/off functions + inline bool GetKeyState(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetKeyState(unsigned int channelNo, unsigned int operatorNo, bool adata); + + //Status register functions + inline unsigned int GetStatusRegister() const; + inline void SetStatusRegister(unsigned int adata); + inline bool GetBusyFlag() const; + inline void SetBusyFlag(bool adata); + inline bool GetTimerBOverflow() const; + inline void SetTimerBOverflow(bool adata); + inline bool GetTimerAOverflow() const; + inline void SetTimerAOverflow(bool adata); + + //Timer functions + inline unsigned int GetTimerACurrentCounter() const; + inline void SetTimerACurrentCounter(unsigned int adata); + inline unsigned int GetTimerBCurrentCounter() const; + inline void SetTimerBCurrentCounter(unsigned int adata); + + //Audio logging functions + inline bool IsAudioLoggingEnabled() const; + inline void SetAudioLoggingEnabled(bool adata); + inline bool IsChannelAudioLoggingEnabled(unsigned int channelNo) const; + inline void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool adata); + inline bool IsOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline std::wstring GetAudioLoggingOutputPath() const; + inline void SetAudioLoggingOutputPath(const std::wstring& adata); + inline std::wstring GetChannelAudioLoggingOutputPath(unsigned int channelNo) const; + inline void SetChannelAudioLoggingOutputPath(unsigned int channelNo, const std::wstring& adata); + inline std::wstring GetOperatorAudioLoggingOutputPath(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetOperatorAudioLoggingOutputPath(unsigned int channelNo, unsigned int operatorNo, const std::wstring& adata); +}; + +#include "IYM2612.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ee73b04cafc5f4c7330fc94438d6983e9e5ce04 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.cpp @@ -0,0 +1,4061 @@ +#include "YM2612.h" +#include "DataConversion/DataConversion.pkg" +#include +#include +//##DEBUG## +//#include + +//---------------------------------------------------------------------------------------- +//These tables are primarily based on the work of Jarek Burczynski in his OPN envelope +//generator implementation for the MAME core. Some corrections have been made to the +//attenuation increment table following hardware tests. +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::counterShiftTable[1 << rateBitCount] = { + 11, 11, 11, 11, //0-3 (0x00-0x03) + 10, 10, 10, 10, //4-7 (0x04-0x07) + 9, 9, 9, 9, //8-11 (0x08-0x0B) + 8, 8, 8, 8, //12-15 (0x0C-0x0F) + 7, 7, 7, 7, //16-19 (0x10-0x13) + 6, 6, 6, 6, //20-23 (0x14-0x17) + 5, 5, 5, 5, //24-27 (0x18-0x1B) + 4, 4, 4, 4, //28-31 (0x1C-0x1F) + 3, 3, 3, 3, //32-35 (0x20-0x23) + 2, 2, 2, 2, //36-39 (0x24-0x27) + 1, 1, 1, 1, //40-43 (0x28-0x2B) + 0, 0, 0, 0, //44-47 (0x2C-0x2F) + 0, 0, 0, 0, //48-51 (0x30-0x33) + 0, 0, 0, 0, //52-55 (0x34-0x37) + 0, 0, 0, 0, //56-59 (0x38-0x3B) + 0, 0, 0, 0}; //60-63 (0x3C-0x3F) + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::attenuationIncrementTable[1 << rateBitCount][8] = { + {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,1,0,1,0,1,0,1}, {0,1,0,1,0,1,0,1}, //0-3 (0x00-0x03) + {0,1,0,1,0,1,0,1}, {0,1,0,1,0,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,0,1,1,1}, //4-7 (0x04-0x07) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //8-11 (0x08-0x0B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //12-15 (0x0C-0x0F) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //16-19 (0x10-0x13) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //20-23 (0x14-0x17) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //24-27 (0x18-0x1B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //28-31 (0x1C-0x1F) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //32-35 (0x20-0x23) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //36-39 (0x24-0x27) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //40-43 (0x28-0x2B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //44-47 (0x2C-0x2F) + {1,1,1,1,1,1,1,1}, {1,1,1,2,1,1,1,2}, {1,2,1,2,1,2,1,2}, {1,2,2,2,1,2,2,2}, //48-51 (0x30-0x33) + {2,2,2,2,2,2,2,2}, {2,2,2,4,2,2,2,4}, {2,4,2,4,2,4,2,4}, {2,4,4,4,2,4,4,4}, //52-55 (0x34-0x37) + {4,4,4,4,4,4,4,4}, {4,4,4,8,4,4,4,8}, {4,8,4,8,4,8,4,8}, {4,8,8,8,4,8,8,8}, //56-59 (0x38-0x3B) + {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}}; //60-63 (0x3C-0x3F) + +//---------------------------------------------------------------------------------------- +//This table is derived from the detune table given in the YM2608 Application Manual, +//page 26. The negative inverse of the table (detune 4-7) is generated in code. +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::detunePhaseIncrementTable[1 << keyCodeBitCount][1 << (detuneBitCount - 1)] = { +// Detune Key-Code +// 0 1 2 3 + {0, 0, 1, 2}, //0 (0x00) + {0, 0, 1, 2}, //1 (0x01) + {0, 0, 1, 2}, //2 (0x02) + {0, 0, 1, 2}, //3 (0x03) + {0, 1, 2, 2}, //4 (0x04) + {0, 1, 2, 3}, //5 (0x05) + {0, 1, 2, 3}, //6 (0x06) + {0, 1, 2, 3}, //7 (0x07) + {0, 1, 2, 4}, //8 (0x08) + {0, 1, 3, 4}, //9 (0x09) + {0, 1, 3, 4}, //10 (0x0A) + {0, 1, 3, 5}, //11 (0x0B) + {0, 2, 4, 5}, //12 (0x0C) + {0, 2, 4, 6}, //13 (0x0D) + {0, 2, 4, 6}, //14 (0x0E) + {0, 2, 5, 7}, //15 (0x0F) + {0, 2, 5, 8}, //16 (0x10) + {0, 3, 6, 8}, //17 (0x11) + {0, 3, 6, 9}, //18 (0x12) + {0, 3, 7,10}, //19 (0x13) + {0, 4, 8,11}, //20 (0x14) + {0, 4, 8,12}, //21 (0x15) + {0, 4, 9,13}, //22 (0x16) + {0, 5,10,14}, //23 (0x17) + {0, 5,11,16}, //24 (0x18) + {0, 6,12,17}, //25 (0x19) + {0, 6,13,19}, //26 (0x1A) + {0, 7,14,20}, //27 (0x1B) + {0, 8,16,22}, //28 (0x1C) + {0, 8,16,22}, //29 (0x1D) + {0, 8,16,22}, //30 (0x1E) + {0, 8,16,22}}; //31 (0x1F) + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::phaseModIncrementTable[1 << pmsBitCount][1 << (phaseModIndexBitCount - 2)] = { + {0, 0, 0, 0, 0, 0, 0, 0}, //0 + {0, 0, 0, 0, 1, 1, 1, 1}, //1 + {0, 0, 0, 1, 1, 1, 2, 2}, //2 + {0, 0, 1, 1, 2, 2, 3, 3}, //3 + {0, 0, 1, 2, 2, 2, 3, 4}, //4 + {0, 0, 2, 3, 4, 4, 5, 6}, //5 + {0, 0, 4, 6, 8, 8,10,12}, //6 + {0, 0, 8,12,16,16,20,24}}; //7 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::channelAddressOffsets[channelCount] = { + 0, //Channel 1 + 1, //Channel 2 + 2, //Channel 3 + registerCountPerPart + 0, //Channel 4 + registerCountPerPart + 1, //Channel 5 + registerCountPerPart + 2}; //Channel 6 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::operatorAddressOffsets[channelCount][operatorCount] = { + {channelAddressOffsets[0] + 0x0, channelAddressOffsets[0] + 0x8, channelAddressOffsets[0] + 0x4, channelAddressOffsets[0] + 0xC}, //Channel 1 + {channelAddressOffsets[1] + 0x0, channelAddressOffsets[1] + 0x8, channelAddressOffsets[1] + 0x4, channelAddressOffsets[1] + 0xC}, //Channel 2 + {channelAddressOffsets[2] + 0x0, channelAddressOffsets[2] + 0x8, channelAddressOffsets[2] + 0x4, channelAddressOffsets[2] + 0xC}, //Channel 3 + {channelAddressOffsets[3] + 0x0, channelAddressOffsets[3] + 0x8, channelAddressOffsets[3] + 0x4, channelAddressOffsets[3] + 0xC}, //Channel 4 + {channelAddressOffsets[4] + 0x0, channelAddressOffsets[4] + 0x8, channelAddressOffsets[4] + 0x4, channelAddressOffsets[4] + 0xC}, //Channel 5 + {channelAddressOffsets[5] + 0x0, channelAddressOffsets[5] + 0x8, channelAddressOffsets[5] + 0x4, channelAddressOffsets[5] + 0xC}}; //Channel 6 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::channel3OperatorFrequencyAddressOffsets[2][operatorCount] = { + {0xA9, 0xAA, 0xA8, 0xA2}, + {0xAD, 0xAE, 0xAC, 0xA6}}; + +//---------------------------------------------------------------------------------------- +//Constructors +//---------------------------------------------------------------------------------------- +YM2612::YM2612(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID) +:Device(aimplementationName, ainstanceName, amoduleID), +status(8), bstatus(8), reg(registerCountTotal, false, Data(8)), +latchedFrequencyData(channelCount, Data(8)), blatchedFrequencyData(channelCount, Data(8)), +latchedFrequencyDataCH3(3, Data(8)), blatchedFrequencyDataCH3(3, Data(8)), +timerAOverflowTimes(false) +{ + //Bus interface + memoryBus = 0; + icLineState = false; + + //Set the default clock rate parameters + externalClockRate = 0; + fmClockDivider = 6; + egClockDivider = 3; + outputClockDivider = channelCount * operatorCount; //24 + timerAClockDivider = 1; + timerBClockDivider = 16; + + //Initialize the audio output stream + outputSampleRate = 48000; //44100; + outputStream.Open(2, 16, outputSampleRate, outputSampleRate/4, outputSampleRate/20); + + //Initialize the raw register locking state + for(unsigned int registerNo = 0; registerNo < registerCountTotal; ++registerNo) + { + rawRegisterLocking[registerNo] = false; + } + + //Initialize the key locking state + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + keyStateLocking[channelNo][operatorNo] = false; + } + } + + //Initialize the timer locking state + timerAStateLocking.load = false; + timerAStateLocking.enable = false; + timerAStateLocking.overflow = false; + timerAStateLocking.rate = false; + timerAStateLocking.counter = false; + timerBStateLocking.load = false; + timerBStateLocking.enable = false; + timerBStateLocking.overflow = false; + timerBStateLocking.rate = false; + timerBStateLocking.counter = false; +} + +//---------------------------------------------------------------------------------------- +//Interface version functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetIYM2612Version() const +{ + return ThisIYM2612Version(); +} + +//---------------------------------------------------------------------------------------- +//Initialization functions +//---------------------------------------------------------------------------------------- +bool YM2612::BuildDevice() +{ + //Build the sin table. This table has been tested and confirmed to be 100% identical + //to the one in the real chip, by reading the internal operator output using the test + //register. + for(unsigned int i = 0; i < (1 << sinTableBitCount); ++i) + { + //Calculate the normalized phase value for the input into the sine table. Note + //that this is calculated as a normalized result from 0.0-1.0 where 0 is not + //reached, because the phase is calculated as if it was a 9-bit index with the + //LSB fixed to 1. This was done so that the sine table would be more accurate + //when it was "mirrored" to create the negative oscillation of the wave. It's + //also convenient we don't have to worry about a phase of 0, because 0 is an + //invalid input for a log function, which we need to use below. + double phaseNormalized = ((double)((i << 1) + 1) / (1 << (sinTableBitCount + 1))); + + //Calculate the pure sine value for the input. Note that we only build a sine + //table for a quarter of the full oscillation (0-PI/2), since the upper two bits + //of the full phase are extracted by the external circuit. + const double pi = 3.14159265358979323846; + double sinResultNormalized = sin(phaseNormalized * (pi / 2)); + + //Convert the sine result from a linear representation of volume, to a + //logarithmic representation of attenuation. The YM2612 stores values in the sine + //table in this form because logarithms simplify multiplication down to addition, + //and this allowed them to attenuate the sine result by the envelope generator + //output simply by adding the two numbers together. + double sinResultAsAttenuation = -log(sinResultNormalized) / log(2.0); + //The division by log(2) is required because the log function is base 10, but the + //YM2612 uses a base 2 logarithmic value. Dividing the base 10 log result by + //log10(2) will convert the result to a base 2 logarithmic value, which can then + //be converted back to a linear value by a pow2 function. In other words: + //2^(log10(x)/log10(2)) = 2^log2(x) = x + //If there was a native log2() function provided we could use that instead. + + //Convert the attenuation value to a rounded 12-bit result in 4.8 fixed point + //format. + const unsigned int fixedBitCount = 8; + unsigned int sinResult = (unsigned int)((sinResultAsAttenuation * (1 << fixedBitCount)) + 0.5); + + //Write the result to the table + sinTable[i] = sinResult; + } + + //Build the pow table. This table has been tested and confirmed to be 100% identical + //to the one in the real chip, by reading the internal operator output using the test + //register. + for(unsigned int i = 0; i < (1 << powTableBitCount); ++i) + { + //Normalize the current index to the range 0.0-1.0. Note that in this case, 0.0 + //is a value which is never actually reached, since we start from i+1. They only + //did this to keep the result to an 11-bit output. It probably would have been + //better to simply subtract 1 from every final number and have 1.0 as the input + //limit instead when building the table, so an input of 0 would output 0x7FF, + //but they didn't. + double entryNormalized = (double)(i + 1) / (double)(1 << powTableBitCount); + + //Calculate 2^-entryNormalized + double resultNormalized = pow(2, -entryNormalized); + + //Convert the normalized result to an 11-bit rounded result + unsigned int result = (unsigned int)((resultNormalized * (1 << powTableOutputBitCount)) + 0.5); + + //Write the result to the table + powTable[i] = result; + } + + //Initialize the wave logging state + std::wstring captureFolder = GetSystemInterface().GetCapturePath(); + wavLoggingEnabled = false; + std::wstring wavLoggingFileName = GetDeviceInstanceName() + L".wav"; + wavLoggingPath = PathCombinePaths(captureFolder, wavLoggingFileName); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + wavLoggingChannelEnabled[channelNo] = false; + std::wstringstream wavLoggingChannelFileName; + wavLoggingChannelFileName << GetDeviceInstanceName() << L" - C" << channelNo + 1 << L".wav"; + wavLoggingChannelPath[channelNo] = PathCombinePaths(captureFolder, wavLoggingChannelFileName.str()); + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + wavLoggingOperatorEnabled[channelNo][operatorNo] = false; + std::wstringstream wavLoggingOperatorFileName; + wavLoggingOperatorFileName << GetDeviceInstanceName() << L" - C" << channelNo + 1 << L"O" << operatorNo + 1 << L".wav"; + wavLoggingOperatorPath[channelNo][operatorNo] = PathCombinePaths(captureFolder, wavLoggingOperatorFileName.str()); + } + } + + //Register each data source with the generic data access base class + std::wstring audioLogExtensionFilter = L"Wave file|wav"; + std::wstring audioLogDefaultExtension = L"wav"; + bool result = true; + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::RawRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TestData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::LFOEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::LFOData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x3FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::CH3Mode, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBReset, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAReset, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBEnable, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAEnable, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBLoad, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerALoad, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DACData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DACEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DetuneData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::MultipleData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TotalLevelData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::KeyScaleData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AttackRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AmplitudeModulationEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DecayRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SustainRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SustainLevelData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ReleaseRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGAttack, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGAlternate, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGHold, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FrequencyData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BlockData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FrequencyDataChannel3, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BlockDataChannel3, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FeedbackData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AlgorithmData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputLeft, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputRight, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AMSData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::PMSData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::KeyState, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::StatusRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BusyFlag, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBOverflow, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAOverflow, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerACurrentCounter, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x3FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBCurrentCounter, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ExternalClockRate, IGenericAccessDataValue::DataType::Double))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FMClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::EGClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ChannelAudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ChannelAudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OperatorAudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OperatorAudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + + //Register page layouts for generic access to this device + GenericAccessPage* audioLoggingPage = new GenericAccessPage(L"Audio Logging", L"Audio Logging"); + audioLoggingPage->AddEntry((new GenericAccessGroup(L"Combined Output")) + ->AddEntry(new GenericAccessGroupDataEntry(IYM2612DataSource::AudioLoggingEnabled, L"Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(IYM2612DataSource::AudioLoggingPath, L"Log Path"))); + GenericAccessGroup* channelGroup = new GenericAccessGroup(L"Channel Output"); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + channelGroup->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::ChannelAudioLoggingEnabled, L"Channel " + channelNoAsString + L" Log Enabled"))->SetDataContext(new ChannelDataContext(channelNo))); + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + channelGroup->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::ChannelAudioLoggingPath, L"Channel " + channelNoAsString + L" Log Path"))->SetDataContext(new ChannelDataContext(channelNo))); + } + audioLoggingPage->AddEntry(channelGroup); + GenericAccessGroup* operatorGroup = new GenericAccessGroup(L"Operator Output"); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + GenericAccessGroup* channelGroupForOperators = (new GenericAccessGroup(L"Channel " + channelNoAsString))->SetOpenByDefault(false); + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + std::wstring operatorNoAsString; + IntToString(operatorNo + 1, operatorNoAsString); + channelGroupForOperators->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::OperatorAudioLoggingEnabled, L"Operator " + operatorNoAsString + L" Log Enabled"))->SetDataContext(new OperatorDataContext(channelNo, operatorNo))); + } + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + std::wstring operatorNoAsString; + IntToString(operatorNo + 1, operatorNoAsString); + channelGroupForOperators->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::OperatorAudioLoggingPath, L"Operator " + operatorNoAsString + L" Log Path"))->SetDataContext(new OperatorDataContext(channelNo, operatorNo))); + } + operatorGroup->AddEntry(channelGroupForOperators); + } + audioLoggingPage->AddEntry(operatorGroup); + result &= AddGenericAccessPage(audioLoggingPage); + + return result; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::ValidateDevice() +{ + return (externalClockRate != 0.0); +} + +//---------------------------------------------------------------------------------------- +void YM2612::Initialize() +{ + //All registers are initialized to 0, with one exception. The Left/Right output flags + //for the accumulator both power up selected for all channels. Without support for + //this, the SEGA sound for Sonic 1 on the Mega Drive fails to play. This exception + //probably only exists for compatibility reasons. The YM2612 aims for a degree of + //compatibility with the YM2203(OPN), and this chip didn't have the L/R registers. If + //the YM2612 powered up with these registers unset, all legacy code would require + //modification in order to set these flags, otherwise no sound would be produced. The + //YM2608 would also select these flags by default, as it has an even greater focus on + //YM2203 compatibility. + reg.Initialize(); + timerAOverflowTimes.Initialize(); + currentReg = 0; + status = 0; + + //Bus interface + icLineState = false; + + //We have confirmed that the YM2612 powers up with output enabled to both the left and + //right speakers for all channels. + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + SetOutputLeft(channelAddressOffset, true, AccessTarget().AccessLatest()); + SetOutputRight(channelAddressOffset, true, AccessTarget().AccessLatest()); + } + + //Initialize the timer state + lastTimesliceLength = 0; + timersLastUpdateTime = 0; + timersRemainingTime = 0; + timerARemainingCycles = 0; + timerBRemainingCycles = 0; + timerACounter = 0; + timerBCounter = 0; + timerAInitialCounter = 0; + timerBInitialCounter = 0; + timerAEnable = false; + timerBEnable = false; + timerALoad = false; + timerBLoad = false; + irqLineState = false; + + //Initialize the render thread properties + remainingRenderTime = 0; + egRemainingRenderCycles = 0; + outputBuffer.clear(); + + //Clear all register latch data + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + latchedFrequencyDataPending[channelNo] = false; + latchedFrequencyData[channelNo] = 0; + } + for(unsigned int regNo = 0; regNo < 3; ++regNo) + { + latchedFrequencyDataPendingCH3[regNo] = false; + latchedFrequencyDataCH3[regNo] = 0; + } + + //Initialize the envelope generator state + envelopeCycleCounter = 0; + cyclesUntilLFOIncrement = 0; + currentLFOCounter = 0; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + operatorData[channelNo][operatorNo].phase = OperatorData::ADSR_RELEASE; + operatorData[channelNo][operatorNo].keyonPrevious = false; + operatorData[channelNo][operatorNo].keyon = false; + operatorData[channelNo][operatorNo].csmKeyOn = false; + operatorData[channelNo][operatorNo].attenuation = (1 << attenuationBitCount) - 1; + operatorData[channelNo][operatorNo].ssgOutputInverted = false; + } + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::Reset(double accessTime) +{ + //Initialize all our internal registers to 0 + std::unique_lock lock(accessMutex); + AccessTarget accessTarget; + if(reg.DoesLatestTimesliceExist()) + { + accessTarget.AccessTime(accessTime); + } + else + { + accessTarget.AccessLatest(); + } + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + Data data(8, 0); + RegisterSpecialUpdateFunction(i, data, accessTime, GetDeviceContext(), 0); + SetRegisterData(i, data, accessTarget); + } + + //We have confirmed that the YM2612 powers up with output enabled to both the left and + //right speakers for all channels. + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + SetOutputLeft(channelAddressOffset, true, AccessTarget().AccessLatest()); + SetOutputRight(channelAddressOffset, true, AccessTarget().AccessLatest()); + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +//Reference functions +//---------------------------------------------------------------------------------------- +bool YM2612::AddReference(const MarshalSupport::Marshal::In& referenceName, IBusInterface* target) +{ + if(referenceName == L"BusInterface") + { + memoryBus = target; + } + else + { + return false; + } + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::RemoveReference(IBusInterface* target) +{ + if(memoryBus == target) + { + memoryBus = 0; + } +} + +//---------------------------------------------------------------------------------------- +//Line functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetLineID(const MarshalSupport::Marshal::In& lineName) const +{ + if(lineName == L"IRQ") //O + { + return (unsigned int)LineID::IRQ; + } + else if(lineName == L"IC") //I + { + return (unsigned int)LineID::IC; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +MarshalSupport::Marshal::Ret YM2612::GetLineName(unsigned int lineID) const +{ + switch((LineID)lineID) + { + case LineID::IRQ: + return L"IRQ"; + case LineID::IC: + return L"IC"; + } + return L""; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetLineWidth(unsigned int lineID) const +{ + switch((LineID)lineID) + { + case LineID::IRQ: + return 1; + case LineID::IC: + return 1; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetLineState(unsigned int targetLine, const Data& lineData, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(lineMutex); + + //Process the line state change + switch((LineID)targetLine) + { + case LineID::IC:{ + bool icLineStateNew = lineData.LSB(); + if(icLineStateNew != icLineState) + { + icLineState = icLineStateNew; + Reset(accessTime); + } + break;} + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::AssertCurrentOutputLineState() const +{ + if(memoryBus != 0) + { + if(irqLineState) memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), 1), GetDeviceContext(), GetDeviceContext(), GetCurrentTimesliceProgress(), 0); + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::NegateCurrentOutputLineState() const +{ + if(memoryBus != 0) + { + if(irqLineState) memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), 0), GetDeviceContext(), GetDeviceContext(), GetCurrentTimesliceProgress(), 0); + } +} + +//---------------------------------------------------------------------------------------- +//Clock source functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const +{ + if(clockSourceName == L"0M") + { + return (unsigned int)ClockID::C0M; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +MarshalSupport::Marshal::Ret YM2612::GetClockSourceName(unsigned int clockSourceID) const +{ + switch((ClockID)clockSourceID) + { + case ClockID::C0M: + return L"0M"; + } + return L""; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::C0M) + { + externalClockRate = clockRate; + } + + //Since a clock rate change will affect our timing point calculations, trigger a + //rollback. + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); +} + +//---------------------------------------------------------------------------------------- +void YM2612::TransparentSetClockSourceRate(unsigned int clockInput, double clockRate) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::C0M) + { + externalClockRate = clockRate; + } +} + +//---------------------------------------------------------------------------------------- +//Execute functions +//---------------------------------------------------------------------------------------- +void YM2612::BeginExecution() +{ + //Initialize the worker thread state + pendingRenderOperationCount = 0; + renderThreadLagging = false; + regTimesliceList.clear(); + timerATimesliceList.clear(); + + //Start the render worker thread + renderThreadActive = true; + std::thread workerThread(std::bind(std::mem_fn(&YM2612::RenderThread), this)); + workerThread.detach(); +} + +//---------------------------------------------------------------------------------------- +void YM2612::SuspendExecution() +{ + std::unique_lock lock(renderThreadMutex); + + //Suspend the render worker thread + if(renderThreadActive) + { + renderThreadActive = false; + renderThreadUpdate.notify_all(); + renderThreadStopped.wait(lock); + } +} + +//---------------------------------------------------------------------------------------- +YM2612::UpdateMethod YM2612::GetUpdateMethod() const +{ + return UpdateMethod::Timeslice; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::SendNotifyUpcomingTimeslice() const +{ + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::NotifyUpcomingTimeslice(double nanoseconds) +{ + //Update the timer status, and reset the last access time for each timer. We need to + //perform this operation here, as we calculate the amount of time that has passed + //between timer updates based on the progress through the current timeslice. Since + //we're now switching to a new timeslice, we need to advance to the end of the last + //timeslice and reset the access time. + if(lastTimesliceLength > 0) + { + std::unique_lock lock(accessMutex); + UpdateTimers(lastTimesliceLength); + } + timersLastUpdateTime = 0; + + lastTimesliceLength = nanoseconds; + lastAccessTime = 0; + + //Add the new timeslice to all our timed buffers + reg.AddTimeslice(nanoseconds); + timerAOverflowTimes.AddTimeslice(nanoseconds); + + //Add references to the new timeslice entry from our timed buffers to the uncommitted + //timeslice lists for the buffers + regTimesliceListUncommitted.push_back(reg.GetLatestTimeslice()); + timerATimesliceListUncommitted.push_back(timerAOverflowTimes.GetLatestTimeslice()); +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteTimeslice(double nanoseconds) +{ + //If the render thread is lagging, pause here until it has caught up, so we don't + //leave the render thread behind with an ever-increasing workload it will never be + //able to complete. + if(renderThreadLagging) + { + std::unique_lock lock(timesliceMutex); + while(renderThreadLagging) + { + renderThreadLaggingStateChange.wait(lock); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteRollback() +{ + //Clock settings + externalClockRate = bexternalClockRate; + + //Bus interface + icLineState = bicLineState; + + //Rollback our timed buffers + reg.Rollback(); + timerAOverflowTimes.Rollback(); + + //Rollback our port registers + currentReg = bcurrentReg; + status = bstatus; + + //Rollback the register latch data + for(unsigned int i = 0; i < channelCount; ++i) + { + latchedFrequencyDataPending[i] = blatchedFrequencyDataPending[i]; + latchedFrequencyData[i] = blatchedFrequencyData[i]; + } + for(unsigned int i = 0; i < 3; ++i) + { + latchedFrequencyDataPendingCH3[i] = blatchedFrequencyDataPendingCH3[i]; + latchedFrequencyDataCH3[i] = blatchedFrequencyDataCH3[i]; + } + + //Rollback the timer data + timersRemainingTime = btimersRemainingTime; + timerARemainingCycles = btimerARemainingCycles; + timerBRemainingCycles = btimerBRemainingCycles; + timerACounter = btimerACounter; + timerBCounter = btimerBCounter; + timerAInitialCounter = btimerAInitialCounter; + timerBInitialCounter = btimerBInitialCounter; + timerAEnable = btimerAEnable; + timerBEnable = btimerBEnable; + timerALoad = btimerALoad; + timerBLoad = btimerBLoad; + irqLineState = birqLineState; + + //Clear any uncommitted timeslices from our render timeslice buffers + regTimesliceListUncommitted.clear(); + timerATimesliceListUncommitted.clear(); +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteCommit() +{ + //Clock settings + bexternalClockRate = externalClockRate; + + //Bus interface + bicLineState = icLineState; + + //Commit our timed buffers + reg.Commit(); + timerAOverflowTimes.Commit(); + + //Take a backup of our port registers + bcurrentReg = currentReg; + bstatus = status; + + //Take a backup of the register latch data + for(unsigned int i = 0; i < channelCount; ++i) + { + blatchedFrequencyDataPending[i] = latchedFrequencyDataPending[i]; + blatchedFrequencyData[i] = latchedFrequencyData[i]; + } + for(unsigned int i = 0; i < 3; ++i) + { + blatchedFrequencyDataPendingCH3[i] = latchedFrequencyDataPendingCH3[i]; + blatchedFrequencyDataCH3[i] = latchedFrequencyDataCH3[i]; + } + + //Take a backup of the timer data + btimersRemainingTime = timersRemainingTime; + btimerARemainingCycles = timerARemainingCycles; + btimerBRemainingCycles = timerBRemainingCycles; + btimerACounter = timerACounter; + btimerBCounter = timerBCounter; + btimerAInitialCounter = timerAInitialCounter; + btimerBInitialCounter = timerBInitialCounter; + btimerAEnable = timerAEnable; + btimerBEnable = timerBEnable; + btimerALoad = timerALoad; + btimerBLoad = timerBLoad; + birqLineState = irqLineState; + + //Ensure that a valid latest timeslice exists in all our buffers. We need this + //check here, because commits can be triggered by the system at potentially any + //point in time, whether a timeslice has been issued or not. + if(!regTimesliceListUncommitted.empty() && !timerATimesliceListUncommitted.empty()) + { + //Obtain a timeslice lock so we can update the data we feed to the render + //thread + std::unique_lock lock(timesliceMutex); + + //Add the number of timeslices we are about to commit to the count of pending + //render operations. This is used to track if the render thread is lagging. + pendingRenderOperationCount += (unsigned int)regTimesliceListUncommitted.size(); + + //Move all timeslices in our uncommitted timeslice lists over to the committed + //timeslice lists, for processing by the render thread. + regTimesliceList.splice(regTimesliceList.end(), regTimesliceListUncommitted); + timerATimesliceList.splice(timerATimesliceList.end(), timerATimesliceListUncommitted); + + //Notify the render thread that it's got more work to do + renderThreadUpdate.notify_all(); + } +} + +//---------------------------------------------------------------------------------------- +//##TODO## Refactor this function to break it down into a set of smaller functions +void YM2612::RenderThread() +{ + std::unique_lock lock(renderThreadMutex); + + //Start the render loop + bool done = false; + while(!done) + { + //Obtain a copy of the latest completed timeslice period + RandomTimeAccessBuffer::Timeslice regTimesliceCopy; + RandomTimeAccessValue::Timeslice timerATimesliceCopy; + bool renderTimesliceObtained = false; + { + std::unique_lock timesliceLock(timesliceMutex); + + //If there is at least one render timeslice pending, grab it from the queue. + if(!regTimesliceList.empty() && !timerATimesliceList.empty()) + { + //Update the lagging state for the render thread + --pendingRenderOperationCount; + renderThreadLagging = (pendingRenderOperationCount > maxPendingRenderOperationCount); + renderThreadLaggingStateChange.notify_all(); + + //Grab the next completed timeslice from the timeslice list + regTimesliceCopy = *regTimesliceList.begin(); + timerATimesliceCopy = *timerATimesliceList.begin(); + regTimesliceList.pop_front(); + timerATimesliceList.pop_front(); + + //Flag that we managed to obtain a render timeslice + renderTimesliceObtained = true; + } + } + + //If no render timeslice was available, we need to wait for a thread suspension + //request or a new timeslice to be received, then begin the loop again. + if(!renderTimesliceObtained) + { + //If the render thread has not already been instructed to stop, suspend this + //thread until a timeslice becomes available or this thread is instructed to + //stop. + if(renderThreadActive) + { + renderThreadUpdate.wait(lock); + } + + //If the render thread has been suspended, flag that we need to exit this + //render loop. + done = !renderThreadActive; + + //Begin the loop again + continue; + } + + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + + //Calculate the FM clock period + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + double fmClockPeriod = 1000000000 / fmClock; + + //Render the YM2612 output + size_t outputBufferPos = outputBuffer.size(); +// unsigned int outputBufferMultiplexedPos = 0; +// std::vector outputBufferMultiplexed(0); + bool moreSamplesRemaining = true; + while(moreSamplesRemaining) + { + //Determine the time of the next write. Note that currently, this may be + //negative under certain circumstances, in particular when a write occurs past + //the end of a timeslice. Negative times won't cause writes to be processed at + //the incorrect time under the current model, but we do need to ensure that + //remainingRenderTime isn't negative before attempting to generate an output. + remainingRenderTime += reg.GetNextWriteTime(regTimesliceCopy); + + //##DEBUG## +// std::wcout << "YM2612 Buffer:\t" << remainingRenderTime << '\t' << outputBuffer.size() << '\t' << ((unsigned int)(remainingRenderTime / fmClockPeriod) * 2) << '\n'; + + //Calculate the output sample count. Note that remainingRenderTime may be + //negative, but we catch that below before using outputSampleCount. + unsigned int outputSampleCount = ((unsigned int)(remainingRenderTime / fmClockPeriod) * 2); + + //If we have one or more output samples to generate before the next settings + //change or the end of the target timeslice, generate and output the samples. + if((remainingRenderTime > 0) && (outputSampleCount > 0)) + { + //Resize the output buffer to fit the samples we're about to add + outputBuffer.resize(outputBuffer.size() + outputSampleCount); + // outputBufferMultiplexed.resize(outputBufferMultiplexed.size() + (outputSampleCount * channelCount)); + + //##TODO## Change the way we advance the render thread so that the update + //steps are driven by integer cycle numbers, rather than timeslice values. + //Refer to the timer update function. + while(remainingRenderTime >= fmClockPeriod) + { + //If CSM mode is active, advance the timer A overflow buffer by one step. + //We make this conditional as an optimization, to prevent the need to + //advance the timer A overflow buffer at such a fine resolution every + //update cycle, for such a rarely used feature. We use a larger update + //step later on for cases where CSM mode is inactive. + if(GetCH3Mode(accessTarget) == 2) + { + //Reset the committed state. We do this before each update, as we use + //the overflow value as a signal line which is only asserted when an + //overflow has occurred after the last update. Each write always sets + //it to true, and we reset it once that write has been processed. + timerAOverflowTimes.WriteCommitted(false); + //Advance the buffer + timerAOverflowTimes.AdvanceByTime(fmClockPeriod, timerATimesliceCopy); + } + + //Advance the global envelope generator state, and determine whether an + //envelope generator update cycle needs to run for each operator on this + //update step. + bool updateEnvelopeGenerator = false; + --egRemainingRenderCycles; + if(egRemainingRenderCycles <= 0) + { + egRemainingRenderCycles = (int)egClockDivider; + ++envelopeCycleCounter; + updateEnvelopeGenerator = true; + } + + //Update the state of the envelope and phase generators for each operator + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + UpdateOperator(channelNo, operatorNo, updateEnvelopeGenerator); + } + } + + //Update the LFO + if(GetLFOEnabled(accessTarget)) + { + --cyclesUntilLFOIncrement; + if(cyclesUntilLFOIncrement <= 0) + { + const unsigned int lfoIncrementValues[8] = {108, 77, 71, 67, 62, 44, 8, 5}; + unsigned int lfoData = GetLFOData(accessTarget); + cyclesUntilLFOIncrement = lfoIncrementValues[lfoData]; + ++currentLFOCounter; + } + } + else + { + //If the LFO is disabled, the LFO counter is forced to 0 + currentLFOCounter = 0; + } + + //Calculate the FM output for each channel in the YM2612 for this sample + int channelOutput[channelCount][2]; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + //Calculate the address offset for all channel registers for the + //target channel + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + + //Read the current algorithm selection for the channel + unsigned int algorithmNo = GetAlgorithmData(channelAddressOffset, accessTarget); + + //Calculate the output for each operator in the channel + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + //Calculate the address offset for all operator registers for + //the target channel and operator + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(channelNo, operatorNo); + + //Calculate the phase modulation input for the operator unit + int phaseModulation = 0; + if((operatorNo == OPERATOR2) && ((algorithmNo == 0) || (algorithmNo == 3) || (algorithmNo == 4) || (algorithmNo == 5) || (algorithmNo == 6))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + else if((operatorNo == OPERATOR3) && ((algorithmNo == 0) || (algorithmNo == 2))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR2]; + } + else if((operatorNo == OPERATOR3) && (algorithmNo == 1)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1] + operatorOutput[channelNo][OPERATOR2]; + } + else if((operatorNo == OPERATOR3) && (algorithmNo == 5)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + else if((operatorNo == OPERATOR4) && ((algorithmNo == 0) || (algorithmNo == 1) || (algorithmNo == 4))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 2)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1] + operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 3)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 5)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + //Convert the 14-bit operator unit output from the modulator into + //a 10-bit phase modulation input. Note that the bits are not + //mapped quite the way you might expect. The operator output is + //shifted down by 1 when it is mapped to the phase modulation + //input. The remaining upper 3 bits of the operator output are + //discarded. + // --------------------------------------------------------- + // | Operator Output (14-bit) | + // |-------------------------------------------------------| + // |13 |12 |11 |10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ------------=========================================---- + // | Modulation Input (10-bit) | + // |---------------------------------------| + // | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----------------------------------------- + phaseModulation >>= 1; + phaseModulation &= ((1 << phaseBitCount) - 1); + + //If we're updating operator 1, calculate the self-feedback value + //for phase modulation. + if(operatorNo == OPERATOR1) + { + unsigned int feedback = GetFeedbackData(channelAddressOffset, accessTarget); + if(feedback > 0) + { + phaseModulation = feedbackBuffer[channelNo][0] + feedbackBuffer[channelNo][1]; + phaseModulation >>= (10 - feedback); + + phaseModulation &= ((1 << phaseBitCount) - 1); + } + } + + //Read the current phase value from the phase generator + unsigned int phase = GetCurrentPhase(channelNo, operatorNo); + + //Read the current attenuation value from the envelope generator + unsigned int attenuation = GetOutputAttenuation(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); + + //Calculate the output from the operator unit + int result = CalculateOperator(phase, phaseModulation, attenuation); + operatorOutput[channelNo][operatorNo] = result; + + //If we're updating operator 1, add the output sample to the + //self-feedback output buffer. + if(operatorNo == OPERATOR1) + { + feedbackBuffer[channelNo][0] = feedbackBuffer[channelNo][1]; + feedbackBuffer[channelNo][1] = result; + } + + //Write to the wav log + if(wavLoggingOperatorEnabled[channelNo][operatorNo]) + { + std::unique_lock lock(waveLoggingMutex); + short outputSample; + float operatorOutputNormalized = (float)operatorOutput[channelNo][operatorNo] / ((1 << (operatorOutputBitCount - 1)) - 1); + //We halve the amplitude of the operator output just to + //make it a little easier to work with. + outputSample = (short)(operatorOutputNormalized * (32767.0f/2)); + wavLogOperator[channelNo][operatorNo].WriteData(outputSample); + } + } + + //The Accumulator + //Calculate the combined operator output for this channel + int combinedChannelOutput = 0; + switch(algorithmNo) + { + case 0: + // ----- ----- ----- ----- + // | 1 |--| 2 |--| 3 |--| 4 |- + // ----- ----- ----- ----- + case 1: + // ----- + // | 1 |--\ + // ----- | ----- ----- + // +--| 3 |--| 4 |- + // ----- | ----- ----- + // | 2 |--/ + // ----- + case 2: + // ----- + // | 1 |--\ + // ----- | ----- + // +--| 4 |- + // ----- ----- | ----- + // | 2 |--| 3 |--/ + // ----- ----- + case 3: + // ----- ----- + // | 1 |--| 2 |--\ + // ----- ----- | ----- + // +--| 4 |- + // ----- | ----- + // | 3 |--/ + // ----- + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4]; + break; + case 4: + // ----- ----- + // | 1 |--| 2 |--\ + // ----- ----- | + // +- + // ----- ----- | + // | 3 |--| 4 |--/ + // ----- ----- + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2]; + break; + case 5: + // ----- + // /--| 2 |--\ + // | ----- | + // | | + // ----- | ----- | + // | 1 |--+--| 3 |--+- + // ----- | ----- | + // | | + // | ----- | + // \--| 4 |--/ + // ----- + case 6: + // ----- + // | 1 | + // ----- + // | + // ----- ----- ----- + // | 2 | | 3 | | 4 | + // ----- ----- ----- + // | | | + // \-------+-------/ + // | + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3]; + break; + case 7: + // ----- ----- ----- ----- + // | 1 | | 2 | | 3 | | 4 | + // ----- ----- ----- ----- + // | | | | + // \-----------+-----------/ + // | + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3] + operatorOutput[channelNo][OPERATOR1]; + break; + } + + //DAC support + if((channelNo == CHANNEL6) && GetDACEnabled(accessTarget)) + { + const unsigned int dacDataBitCount = 8; + //The DAC data is written as an unsigned value. We convert it to + //a signed value here. + //##TODO## It's possible the DAC data uses a primitive sign bit. + //Perform a test to determine whether this is the case. + unsigned int dacData = GetDACData(accessTarget); + int dacResult = (int)dacData - 0x80; + //Convert from the 8-bit signed DAC data value to a 14-bit signed + //operator output. The DAC data is mapped to the upper 8 bits of + //the 14-bit output. + dacResult <<= operatorOutputBitCount - dacDataBitCount; + //Since DAC is enabled, the specified DAC sample replaces the + //calculated FM output for this channel. + combinedChannelOutput = dacResult; + } + + //The result needs to be shifted up by 2 to correctly convert from + //the 14-bit output from the operator unit, to the 16-bit output from + //the accumulator. + //##TODO## Confirm whether operators are summed before the shift + //occurs, or whether the operators are shifted to 16-bit values + //first, and then summed. + combinedChannelOutput <<= 2; + + //A single operator at max attenuation won't clip, but multiple + //operators combined might. We add a limit here to reproduce the + //clipping operation. + int maxAccumulatorOutput = (int)((1 << (accumulatorOutputBitCount - 1)) - 1); + int minAccumulatorOutput = -(int)((1 << (accumulatorOutputBitCount - 1)) - 1); + if(combinedChannelOutput > maxAccumulatorOutput) + { + combinedChannelOutput = maxAccumulatorOutput; + } + else if(combinedChannelOutput < minAccumulatorOutput) + { + combinedChannelOutput = minAccumulatorOutput; + } + + //Pan Left/Right + channelOutput[channelNo][0] = GetOutputLeft(channelAddressOffset, accessTarget)? combinedChannelOutput: 0; + channelOutput[channelNo][1] = GetOutputRight(channelAddressOffset, accessTarget)? combinedChannelOutput: 0; + + //Write to the wave log + if(wavLoggingChannelEnabled[channelNo]) + { + std::unique_lock lock(waveLoggingMutex); + short outputSampleLeft; + short outputSampleRight; + float channelOutputLeftNormalized = (float)channelOutput[channelNo][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + float channelOutputRightNormalized = (float)channelOutput[channelNo][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + //We halve the amplitude of the channel output just to + //make it a little easier to work with. + outputSampleLeft = (short)(channelOutputLeftNormalized * (32767.0f/2)); + outputSampleRight = (short)(channelOutputRightNormalized * (32767.0f/2)); + wavLogChannel[channelNo].WriteData(outputSampleLeft); + wavLogChannel[channelNo].WriteData(outputSampleRight); + } + } + + //##FIX## + //Run the combined channel output from the accumulator through the + //embedded YM3016 DAC. Note that we perform this calculation in the 2's + //compliment mode for the DAC. + // Data channelOutputLeft(16, channelOutput[channelNo][0]); + + //Calculate the shift value + // unsigned int shiftLeft = 6; + // for(unsigned int i = 14; i >= 9; --i) + // { + // if(channelOutputLeft.GetBit(i)) + // { + // shiftLeft = 14 - i; + // break; + // } + // } + + //Calculate the mantissa + // Data mantissaLeft(10); + // mantissaLeft = channelOutputLeft.GetDataSegment(14 - shiftLeft, 9); + // mantissaLeft.SetBit(10, channelOutputLeft.GetBit(15)); + + //Calculate a single combined output for the YM2612. The DAC in the real + //YM2612 multiplexes the output from each of the 6 channels, and outputs + //at 6 times the output frequency we use here. We combine the output of + //each channel here, and calculate the average sample output instead. The + //apparent output should basically be the same. The best possible output + //would be obtained by generating the true multiplexed output, and + //resampling from the true output to the final audio output frequency + //we're sending to the sound card. + double finalOutputLeft = 0; + double finalOutputRight = 0; + for(unsigned int i = 0; i < channelCount; ++i) + { + float channelOutputLeftNormalized = (float)channelOutput[i][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + float channelOutputRightNormalized = (float)channelOutput[i][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + finalOutputLeft += (channelOutputLeftNormalized / channelCount); + finalOutputRight += (channelOutputRightNormalized / channelCount); + } + short outputSampleLeft = (short)(32767.0f * finalOutputLeft); + short outputSampleRight = (short)(32767.0f * finalOutputRight); + outputBuffer[outputBufferPos++] = outputSampleLeft; + outputBuffer[outputBufferPos++] = outputSampleRight; + + //Write to the wave log + if(wavLoggingEnabled) + { + std::unique_lock lock(waveLoggingMutex); + Stream::ViewBinary wavlogStream(wavLog); + wavlogStream << outputSampleLeft; + wavlogStream << outputSampleRight; + } + + ////Calculate the true multiplexed output for the YM2612 + //for(unsigned int i = 0; i < channelCount; ++i) + //{ + // float channelOutputLeftNormalized = (float)channelOutput[i][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + // float channelOutputRightNormalized = (float)channelOutput[i][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + // short outputSampleLeft = (short)(32767.0f * channelOutputLeftNormalized); + // short outputSampleRight = (short)(32767.0f * channelOutputRightNormalized); + // outputBufferMultiplexed[outputBufferMultiplexedPos++] = outputSampleLeft; + // outputBufferMultiplexed[outputBufferMultiplexedPos++] = outputSampleRight; + + // Write to the wave log + // if(wavLoggingEnabled) + // { + // std::unique_lock lock(waveLoggingMutex); + // wavLog.WriteData(outputSampleLeft); + // wavLog.WriteData(outputSampleRight); + // } + //} + + remainingRenderTime -= fmClockPeriod; + } + } + + RandomTimeAccessBuffer::WriteInfo writeInfo = reg.GetWriteInfo(0, regTimesliceCopy); + if(writeInfo.exists) + { + //Handle any special case register changes + switch(writeInfo.writeAddress) + { + case 0x28: + { + //Key-on/off + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // |-------------------------------| + //28H | Key State | | | + // |---------------| / | Channel | + // |OP4|OP3|OP2|OP1| | | + // --------------------------------- + //##TODO## Confirm that bit 3 really is ignored when processing + //key on/off writes. + bool op4KeyState = writeInfo.newValue.GetBit(7); + bool op3KeyState = writeInfo.newValue.GetBit(6); + bool op2KeyState = writeInfo.newValue.GetBit(5); + bool op1KeyState = writeInfo.newValue.GetBit(4); + bool validChannelSelected = true; + Channels channelNo; + switch(writeInfo.newValue.GetDataSegment(0, 3)) + { + case 0: //000 - Channel 1 + channelNo = CHANNEL1; + break; + case 1: //001 - Channel 2 + channelNo = CHANNEL2; + break; + case 2: //010 - Channel 3 + channelNo = CHANNEL3; + break; + case 4: //100 - Channel 4 + channelNo = CHANNEL4; + break; + case 5: //101 - Channel 5 + channelNo = CHANNEL5; + break; + case 6: //110 - Channel 6 + channelNo = CHANNEL6; + break; + default: //011, 111 + validChannelSelected = false; + break; + } + + if(validChannelSelected) + { + if(!keyStateLocking[channelNo][OPERATOR4]) + { + operatorData[channelNo][OPERATOR4].keyon = op4KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR3]) + { + operatorData[channelNo][OPERATOR3].keyon = op3KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR2]) + { + operatorData[channelNo][OPERATOR2].keyon = op2KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR1]) + { + operatorData[channelNo][OPERATOR1].keyon = op1KeyState; + } + } + } + } + } + + //See the notes above where we update the envelope generator for more info + //about this conditional step of the timer A overflow buffer. + if(GetCH3Mode(accessTarget) != 2) + { + timerAOverflowTimes.AdvanceByTime(writeInfo.writeTime, timerATimesliceCopy); + //Reset the committed state. We do this after each update here, as CSM + //mode has been disabled until this point, so all the overflow events + //we've just advanced through would have been ignored. + timerAOverflowTimes.WriteCommitted(false); + } + moreSamplesRemaining = reg.AdvanceByStep(regTimesliceCopy); + } + + //Play the mixed audio stream. Note that we fold samples from successive render + //operations together, ensuring that we only send data to the output audio stream + //when we have a significant number of samples to send. + unsigned int outputFrequency = (unsigned int)fmClock; + size_t minimumSamplesToOutput = (size_t)(outputFrequency / 60); + if(outputBuffer.size() >= minimumSamplesToOutput) + { + unsigned int internalSampleCount = (unsigned int)outputBuffer.size() / 2; + unsigned int outputSampleCount = (unsigned int)((double)internalSampleCount * ((double)outputSampleRate / (double)outputFrequency)); + AudioStream::AudioBuffer* outputBufferFinal = outputStream.CreateAudioBuffer(outputSampleCount, 2); + if(outputBufferFinal != 0) + { + outputStream.ConvertSampleRate(outputBuffer, internalSampleCount, 2, outputBufferFinal->buffer, outputSampleCount); + outputStream.PlayBuffer(outputBufferFinal); + } + outputBuffer.clear(); + outputBuffer.reserve(minimumSamplesToOutput * 2); + + //##DEBUG## + //std::wcout << "YM2612 Output: " << internalSampleCount << '\t' << outputSampleCount << '\n'; + } + + //Play the multiplexed output audio stream + //if(!outputBufferMultiplexed.empty()) + //{ + // unsigned int outputFrequency = (unsigned int)fmClock * channelCount; + // unsigned int internalSampleCount = (unsigned int)outputBufferMultiplexed.size() / 2; + // unsigned int outputSampleCount = (unsigned int)((double)internalSampleCount * ((double)outputSampleRate / (double)outputFrequency)); + // AudioStream::AudioBuffer* outputBufferFinal = outputStream.CreateAudioBuffer(outputSampleCount, 2); + // if(outputBufferFinal != 0) + // { + // outputStream.ConvertSampleRate(outputBufferMultiplexed, internalSampleCount, 2, outputBufferFinal->buffer, outputSampleCount); + // outputStream.PlayBuffer(outputBufferFinal); + // } + //} + + //Advance past the timeslice we've just rendered from + { + std::unique_lock lock(timesliceMutex); + reg.AdvancePastTimeslice(regTimesliceCopy); + timerAOverflowTimes.AdvancePastTimeslice(timerATimesliceCopy); + } + } + renderThreadStopped.notify_all(); +} + +//---------------------------------------------------------------------------------------- +//General operator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateOperator(unsigned int channelNo, unsigned int operatorNo, bool updateEnvelopeGenerator) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //Calculate the address offsets for all channel and operator registers for the target + //channel and operator. + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(channelNo, operatorNo); + + //Update the key-on state. Note that hardware tests have shown that this does in fact + //happen each FM clock cycle, not just each envelope generator update cycle. Also + //note the update process for CSM key-on events, and the interaction between CSM and + //manual key-on events. This implementation is based on comprehensive hardware tests. + + //Update the CSM key-on state + if(channelNo == CHANNEL3) + { + state->csmKeyOn = (GetCH3Mode(accessTarget) == 2) && timerAOverflowTimes.ReadCommitted(); + } + + //Respond to any key on/off changes + bool keyonState = state->keyon || state->csmKeyOn; + if(keyonState != state->keyonPrevious) + { + if(keyonState) + { + //Key-on + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_ATTACK); + + //Restart the phase counter. Hardware tests have shown that the phase counter + //is always reset to 0 when key-on occurs. Note that this does include cases + //where key-on is triggered automatically by CSM mode. + state->phaseCounter = 0; + + //Reset the SSG-EG output inversion flag + state->ssgOutputInverted = false; + } + else + { + //Key-off + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_RELEASE); + + //If SSG-EG is enabled and the output is currently inverted, convert the + //current attenuation value into an equivalent non-inverted value. This + //emulates the release mode behaviour when SSG-EG is active. Note that we do + //not alter the output inversion flag here. Output inversion is ignored + //during the release phase. The output inversion flag is cleared when key-on + //occurs. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) && (state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) + { + state->attenuation = Data(attenuationBitCount, 0x200) - state->attenuation; + } + } + state->keyonPrevious = keyonState; + } + + //If SSG-EG is enabled, and the current internal attenuation level of the envelope + //generator is greater than or equal to 0x200, we need to run some special SSG-EG + //update steps. Note that hardware tests have proven that these operations occur each + //time the output of the envelope generator is calculated (IE, each sample), not just + //each time the envelope generator is updated. The output inversion and phase counter + //reset steps in particular are easily measurable, and have been shown to occur each + //sample. Note that hardware tests have also shown that this update process occurs + //before the normal envelope generator update steps in the case where both run on the + //same cycle. This can allow a single sample to be output at an attenuation level of + //0x200 before these update steps are applied. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) //SSG-EG mode is enabled + && (state->attenuation >= 0x200)) //The internal attenuation value has reached the magic 0x200 threshold + { + if(GetSSGAlternate(operatorAddressOffset, accessTarget) //SSG-EG is set to an alternating pattern + && (!GetSSGHold(operatorAddressOffset, accessTarget) || !state->ssgOutputInverted)) //Hold mode is disabled, or the current inversion state matches the initial inversion state at key-on + { + //Toggle the current inversion state of the envelope generator output. Note + //that extensive hardware tests have been performed on SSG-EG output + //inversion. This implementation has been shown to always produce the correct + //output, even under unusual circumstances such as when an attack phase is + //present, and/or changes are made to the SSG-EG mode at critical points. + state->ssgOutputInverted = !state->ssgOutputInverted; + + //Note that if the hold bit is set, the inversion state is only toggled if + //the current inversion state matches the initial inversion state. Under + //normal circumstances, this prevents the inversion state from being toggled + //more than once when the hold bit is set. This matches the confirmed + //behaviour of the real chip. This behaviour is vital, as the internal + //attenuation value finishes on 0x200 after each decay phase. Without this + //test, once hold mode begins, the inversion state would be toggled each + //sample. Note that the envelope generator does not maintain a separate flag + //which tracks whether the output has been inverted since key-on, as changes + //to the SSG-EG mode after key-on can cause the output to be inverted more + //than once under hold mode. + } + + if(!GetSSGAlternate(operatorAddressOffset, accessTarget) + && !GetSSGHold(operatorAddressOffset, accessTarget)) + { + //Hardware tests have shown that the phase counter is held at 0 in cases + //where SSG-EG is enabled, both the hold bit and alternate bit are unset, and + //the internal envelope generator attenuation value is greater than or equal + //to 0x200. Once any of these conditions change, the phase counter will + //resume counting up from 0. This causes the phase of the output wave to + //restart on each repetition of patterns 08 and 0C, which occurs on the real + //hardware. Note that the phase counter really is held at 0, not simply set + //to 0 at a particular point in time. This can create silence gaps between + //repetitions of the SSG-EG envelope where an attack phase exists. + state->phaseCounter = 0; + } + + if(state->phase != OperatorData::ADSR_ATTACK) + { + if((state->phase != OperatorData::ADSR_RELEASE) + && !GetSSGHold(operatorAddressOffset, accessTarget)) + { + //If SSG-EG is enabled, we're in either the decay or sustain phase, and + //the hold bit is not set, now that we've reached an attenuation level of + //0x200, we need to loop back to the attack phase and begin the ADSR + //envelope again. + + //Switch back to the attack phase + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_ATTACK); + + //Note that we've confirmed that the attenuation is not clamped to 0x200 + //in SSG-EG mode when the ADSR envelope loops. By toggling DR during the + //decay phase, we've proven that the final attenuation value is allowed + //to move past 0x200 before looping. If an attack curve follows, it + //begins its decay from this final attenuation value. Don't uncomment the + //line below, it is incorrect. It is only provided as an example of what + //NOT to do. + //state->attenuation = 0x200; + } + else if((state->phase == OperatorData::ADSR_RELEASE) + || !(state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) //If the output is not currently inverted + { + //If the output is not currently inverted, and we've reached an internal + //attenuation level of 0x200 in one of the decay phases (either the + //decay, sustain, or release phase), but the envelope is not looping back + //to the attack phase, we need to force the internal attenuation value to + //0x3FF. This emulates the behaviour of the YM2612 when entering a + //low-hold state in SSG-EG mode, and when the release phase reaches + //0x200. In both cases, the internal attenuation value is forced directly + //to 0x3FF. This has been confirmed through hardware tests. Note that + //this step occurs after the inversion state has been toggled. Performing + //these steps the wrong way around would break SSG-EG pattern 0xB, where + //both the hold and alternate bits are set, and the attack bit is clear. + + //Force the internal attenuation value to 0x3FF + state->attenuation = 0x3FF; + + //Note that this behaviour can be observed when switching from an + //inverted hold pattern to a low-hold pattern, then back again after the + //hold sequence has begun. When the inverted hold pattern resumes, the + //digital output will be 0x001F instead of 0x1FE8, as the internal + //attenuation value has been forced from 0x200 to 0x3FF, which becomes + //0x201 when it is inverted, outputting a value of 0x001F. This effect + //can also be observed when reading the decay sequence under the release + //phase when SSG-EG mode is active. With an increment value of 1, the + //digital output from the operator unit can be observed to jump directly + //from 0x0021 to 0, indicating the output attenuation value from the + //envelope generator skipped from a known value of 0x1FC from the decay + //sequence, to a value greater than 0x33F. + } + } + } + + //Update the Envelope Generator + if(updateEnvelopeGenerator) + { + UpdateEnvelopeGenerator(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); + } + + //Update the Phase Generator + UpdatePhaseGenerator(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); +} + +//---------------------------------------------------------------------------------------- +//This function implements the KeyCode formula as described on page 25 of the YM2608 +//documentation. Result is a 5-bit number with the following structure: +// --------------------- +// | 4 | 3 | 2 | 1 | 0 | +// |-------------------| +// | Block |N4 |N3 | +// --------------------- +//Where Block is the 3-bit block data, and N4/N3 are built from fnumber as follows: +// N4=F11 +// N3=F11&(F10|F9|F8) | !F11&F10&F9&F8 +//Where FXX indicates bit XX from fnumber, starting with the LSB as 1. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateKeyCode(unsigned int block, unsigned int fnumber) const +{ + Data keyCode(keyCodeBitCount); + Data fnumberData(fnumDataBitCount, fnumber); + keyCode.SetDataSegment(2, 3, block); + keyCode.SetBit(1, fnumberData.GetBit(10)); + keyCode.SetBit(0, (fnumberData.GetBit(10) && (fnumberData.GetBit(9) || fnumberData.GetBit(8) || fnumberData.GetBit(7))) || (!fnumberData.GetBit(10) && (fnumberData.GetBit(9) && fnumberData.GetBit(8) && fnumberData.GetBit(7)))); + return keyCode.GetData(); +} + +//---------------------------------------------------------------------------------------- +//Phase generator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdatePhaseGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //This algorithm is primarily based on the F-Number calculation given in the YM2608 + //manual, page 24. That formula is as follows: + //F-Number = (144 * fnote * 2^20 / M) / 2^(B-1) + //Additional tests were performed on hardware to answer all remaining questions about + //the update process. + + //Read the frequency and block data + unsigned int frequencyData = GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget); + unsigned int blockData = GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget); + + //Apply frequency modulation to fnum + // --------------------------------- + // | LFO Counter | + // |-------------------------------| + // |...| 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----=====================-------- + // | Phase Modulation | + // | Index (5-bit) | + // |-------------------| + // | 4 | 3 | 2 | 1 | 0 | + // --------------------- + Data pmCounter(phaseModIndexBitCount, currentLFOCounter >> 2); + unsigned int pmSensitivity = GetPMSData(channelAddressOffset, accessTarget); + if((pmCounter != 0) && (pmSensitivity != 0)) + { + bool pmInverted = pmCounter.GetBit(phaseModIndexBitCount - 1); + bool pmSlopeNegative = pmCounter.GetBit(phaseModIndexBitCount - 2); + Data quarterPhase(phaseModIndexBitCount - 2, pmCounter.GetData()); + if(pmSlopeNegative) + { + quarterPhase = ~quarterPhase; + } + + //##TODO## Run a test where the upper 6 bits of fnum are 0, and see if the + //inverted frequency modulation wave will create a measurable, effective 1-bit + //frequency modulation due to sign-extension. + //##TODO## Determine whether all 11 bits of fnum are used to calculate the + //frequency modulation value. It's possible that all 11 bits of fnum are used to + //build a frequency modulation value, and that value is calculated at full + //precision, without any loss. That value is then sign-extended, and added to + //fnum, but lower bits of the frequency modulation value are discarded. If this + //is the case, the sign-extension behaviour will mean that a 1-bit modulation + //value is present, even when only the LSB of fnum is set. It would also mean + //that we would be able to detect the results of carry operations in the addition + //for the increment values for each bit, below the level of the LSB of fnum. + + int pmIncrement = 0; + for(unsigned int i = 0; i < fnumDataBitCount; ++i) + { + if((frequencyData & (1 << i)) != 0) + { + unsigned int pmIncrementValue = phaseModIncrementTable[pmSensitivity][quarterPhase.GetData()]; + pmIncrement += (int)(pmIncrementValue << i); + } + } + if(pmInverted) + { + pmIncrement = -pmIncrement; + } + pmIncrement >>= 9; + frequencyData += (unsigned int)pmIncrement; + + ////Calculate the frequency modulation value based on the upper 6 bits of fnum + //const unsigned int fnumModulationBits = 6; + //unsigned int pmSensitivity = GetPMSData(channelNo, accessTarget); + //unsigned int pmIncrement = 0; + //unsigned int frequencyDataUpperBits = frequencyData >> (fnumDataBitCount - fnumModulationBits); + //for(unsigned int i = 0; i < fnumModulationBits; ++i) + //{ + // if((frequencyDataUpperBits & (1 << i)) != 0) + // { + // unsigned int pmIncrementValue = phaseModIncrementTable[pmSensitivity][quarterPhase.GetData()]; + // unsigned int pmIncrementForBit = (pmIncrementValue << 1) >> ((fnumModulationBits - 1) - i); + // pmIncrement += pmIncrementForBit; + // } + //} + + //if(pmInverted) + //{ + // frequencyData -= pmIncrement; + //} + //else + //{ + // frequencyData += pmIncrement; + //} + + //Clamp the adjusted fnum value to an 11-bit result. + frequencyData &= ((1 << fnumDataBitCount) - 1); + } + + //Adjust the fnum data by the block shift data, to calculate the initial phase + //increment value. The block data applies a shift to fnum in the following way: + //------------------------------------------------- + //| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | + //|-----------------------------------------------| + //| >>1 | - | <<1 | <<2 | <<3 | <<4 | <<5 | <<6 | + //------------------------------------------------- + //Note the loss of precision when block=0. The LSB of fnum is discarded when block=0. + //This has been confirmed through hardware tests. + unsigned int phaseIncrement; + if(blockData == 0) + { + phaseIncrement = (frequencyData >> 1); + } + else + { + phaseIncrement = frequencyData << (blockData - 1); + } + + //Apply detune to the phase increment value. Note that the detune adjustment is + //applied before the frequency multiplier. + unsigned int keyCode = CalculateKeyCode(blockData, frequencyData); + Data detuneData(detuneBitCount, GetDetuneData(operatorAddressOffset, accessTarget)); + bool detuneNegative = detuneData.GetBit(detuneBitCount - 1); + unsigned int detuneIndex = detuneData.GetDataSegment(0, 2); + unsigned int detuneIncrement = detunePhaseIncrementTable[keyCode][detuneIndex]; + if(detuneNegative) + { + phaseIncrement -= detuneIncrement; + } + else + { + phaseIncrement += detuneIncrement; + } + + //Clamp the intermediate phase increment to a 17-bit result. This is necessary in + //order to accurately emulate overflows caused by the detune adjustment. + const unsigned int intermediatePhaseIncrementBitCount = 17; + phaseIncrement &= ((1 << intermediatePhaseIncrementBitCount) - 1); + + //Apply the frequency multiplier to the phase increment value + unsigned int mul = GetMultipleData(operatorAddressOffset, accessTarget); + if(mul == 0) + { + phaseIncrement /= 2; + } + else + { + phaseIncrement *= mul; + } + + //Apply the phase increment to the phase counter + state->phaseCounter += phaseIncrement; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetCurrentPhase(unsigned int channelNo, unsigned int operatorNo) const +{ + const OperatorData* state = &operatorData[channelNo][operatorNo]; + //This function returns the 10-bit output from the phase generator, which is used by + //the operator unit. This 10-bit output represents the upper 10 bits of the internal + //phase counter. We extract the upper 10 bits of the internal phase counter here, to + //build that 10-bit output. + return state->phaseCounter.GetDataSegment(state->phaseCounter.GetBitCount() - 10, 10); +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetFrequencyData(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, const AccessTarget& accessTarget) const +{ + if((channelNo == CHANNEL3) && (GetCH3Mode(accessTarget) != 0)) + { + //If we're in channel 3 special mode, read the separate frequency data for the + //operator. + return GetFrequencyDataChannel3(operatorNo, accessTarget); + } + else + { + //Read the global frequency data for the channel + return GetFrequencyData(channelAddressOffset, accessTarget); + } +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetBlockData(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, const AccessTarget& accessTarget) const +{ + if((channelNo == CHANNEL3) && (GetCH3Mode(accessTarget) != 0)) + { + //If we're in channel 3 special mode, read the separate block data for the + //operator. + return GetBlockDataChannel3(operatorNo, accessTarget); + } + else + { + //Read the global block data for the channel + return GetBlockData(channelAddressOffset, accessTarget); + } +} + +//---------------------------------------------------------------------------------------- +//Envelope generator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateEnvelopeGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //Check if we need to progress to a different phase of the ADSR envelope + if(state->phase == OperatorData::ADSR_ATTACK) + { + //If we're in the attack phase and attenuation has hit minimum, switch to the + //decay phase. + if(state->attenuation == 0) + { + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_DECAY); + } + } + else if(state->phase == OperatorData::ADSR_DECAY) + { + unsigned int sustainLevelAsAttenuation = ConvertSustainLevelToAttenuation(GetSustainLevelData(operatorAddressOffset, accessTarget)); + + //If we're in the decay phase and attenuation has passed SL, switch to the + //sustain phase. + if(state->attenuation >= sustainLevelAsAttenuation) + { + //We have confirmed that the current internal attenuation number is NOT + //clamped to SL when the decay phase passes SL. This can't happen under normal + //circumstances. The minimum step for SL is 0x20, which is also 8*4=0x20 the + //maximum output step for the decay phase under SSG-EG. Decay should always + //end exactly on SL. Where this may not be true is when DR is modified during + //the decay phase. We know from hardware tests where we modified DR during the + //decay phase to get the attenuation value to "skip over" 0x200 that the final + //level is allowed to move past SL during the decay phase. The sustain phase + //then begins from the point at which the decay rate finished. This has been + //confirmed both under normal mode and when SSG-EG is active. Don't uncomment + //the line below, it is incorrect. It is only provided as an example of what + //NOT to do. + //state->attenuation = sustainLevelAsAttenuation; + + //Switch from the decay phase to the sustain phase. Note that we have + //confirmed that changing SL after the sustain phase has been entered can't + //cause the operator to re-enter the decay phase. The switch from decay to + //sustain is a one-way process. The selection between the decay or sustain + //phases is not based on the current attenuation value relative to SL. + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_SUSTAIN); + } + } + + //Calculate the current rate value for the envelope. Note that we have confirmed this + //value is evaluated on every update cycle. Changes to the effective rate for the + //current phase of the envelope generator take effect immediately. + unsigned int rateKeyScale = CalculateRateKeyScale(GetKeyScaleData(operatorAddressOffset, accessTarget), CalculateKeyCode(GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget), GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget))); + unsigned int rate = 0; + switch(state->phase) + { + case OperatorData::ADSR_ATTACK: + rate = CalculateRate(GetAttackRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_DECAY: + rate = CalculateRate(GetDecayRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_SUSTAIN: + rate = CalculateRate(GetSustainRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_RELEASE:{ + //Note that we pass the 4-bit release rate data as a 5-bit number, with the LSB + //fixed to 1. This is based on the information given in the YM2608 Application + //Manual, page 30, which states that the release rate data is passed as + //(value * 2 + 1). + unsigned int adjustedRateData = (GetReleaseRateData(operatorAddressOffset, accessTarget) << 1) | 0x01; + rate = CalculateRate(adjustedRateData, rateKeyScale); + break;} + } + + //Check the envelope cycle counter and see if we should be adjusting the attenuation + //for the operator on this cycle. + unsigned int counterShiftValue = counterShiftTable[rate]; + if((envelopeCycleCounter % (1 << counterShiftValue)) == 0) + { + //Get the index of the next attenuation increment value in the update cycle (0-7) + unsigned int updateCycle = (envelopeCycleCounter >> counterShiftValue) & 0x07; + + //Read the next attenuation increment value in the cycle + unsigned int attenuationIncrement = attenuationIncrementTable[rate][updateCycle]; + + //Update the attenuation + unsigned int newAttenuation = state->attenuation.GetData(); + if(state->phase == OperatorData::ADSR_ATTACK) + { + //If the attack rate is less than 62, advance the attack curve. Attack rate + //values of 62 and 63 have special case handling when the attack phase is + //first entered, which forces the attenuation directly to 0. Note that if an + //attack phase begins with an attack rate less than 62, then the attack rate + //changes during the attack phase to a rate value of 62 or 63, this exclusion + //will prevent the attack curve from advancing, and the attack phase will + //stall. This matches the confirmed behaviour of the real hardware. + if(rate < 62) + { + //Note that we've confirmed this formula for the attack curve produces a + //binary accurate result. + unsigned int attenuationAdjustment = (~newAttenuation * attenuationIncrement) >> 4; + + //Combine the attenuation adjustment value with the current attenuation + //value. The attenuation adjustment is a two's compliment representation + //of a negative number, so this addition operation will actually subtract + //a value from the current attenuation level. Note that we don't apply any + //limiting operation here, so an overflow is possible. This is vital, as + //the addition of the two's compliment negative value will always cause an + //overflow to occur. + newAttenuation += attenuationAdjustment; + } + } + else + { + //Advance the linear decay for the decay, sustain, or release phase. Note that + //if SSG-EG is enabled for this operator, the decay phase runs at 4x the + //normal speed. + if(GetSSGEnabled(operatorAddressOffset, accessTarget)) + { + //If the current internal attenuation value is below 0x200, advance the + //decay phase. In most cases when the attenuation level reaches 0x200, + //the envelope will move back to the attack phase, or the attenuation + //level will be forced to 0x3FF anyway. One case where neither of these + //changes occur, and we need this check here to ensure the attenuation + //level isn't permitted to advance any further, is when we enter an + //inverted hold phase. Hardware tests have conclusively shown that in + //these cases, if the internal attenuation level is greater than or equal + //to 0x200, the attenuation level remains unchanged. This is true even in + //cases where the internal attenuation level has been offset from a + //multiple of 4, and the precise value of 0x200 is skipped over by an + //SSG-EG increment. + if(newAttenuation < 0x200) + { + newAttenuation += (int)(4 * attenuationIncrement); + } + } + else + { + newAttenuation += (int)attenuationIncrement; + } + + //Limit the result to the maximum attenuation value. This is necessary to stop + //the final step in a decay phase overflowing back to 0. The last update step + //in a decay phase is always capped at 0x3FF, even when the step would have + //advanced past 0x3FF. Under normal circumstances, all decay phases would + //always end on a value of 0x400 which would be clamped back to 0x3FF, but + //this this clamping behaviour has also been confirmed to work correctly when + //the decay rate is modified during the decay phase, to cause the final step + //to "skip over" the usual ending value of 0x400. + unsigned int maxAttenuation = (1 << attenuationBitCount) - 1; + if(newAttenuation > maxAttenuation) + { + newAttenuation = maxAttenuation; + } + } + + //Write the new attenuation value to the envelope generator state + state->attenuation = newAttenuation; + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetADSRPhase(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset, OperatorData::ADSRPhase phase) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + if(phase != state->phase) + { + if(phase == OperatorData::ADSR_ATTACK) + { + //If the rate is greater than or equal to 62, the current attenuation level is + //forced directly to 0. This causes the next envelope generator update cycle + //to advance through the first step of the decay phase. It seems a little odd + //to have to evaluate the effective attack rate here, but this implementation + //does appear to match the behaviour of the chip. + unsigned int rateKeyScale = CalculateRateKeyScale(GetKeyScaleData(operatorAddressOffset, accessTarget), CalculateKeyCode(GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget), GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget))); + unsigned int rate = CalculateRate(GetAttackRateData(operatorAddressOffset, accessTarget), rateKeyScale); + if(rate >= 62) + { + state->attenuation = 0; + } + } + state->phase = phase; + } +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetOutputAttenuation(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) const +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + const OperatorData* state = &operatorData[channelNo][operatorNo]; + + unsigned int attenuation = state->attenuation.GetData(); + + //If SSG-EG is enabled and the output is inverted, invert the output data. Note that + //extensive testing has been performed on the hardware to build this implementation. + //This test is performed exactly as shown each time the attenuation value is used. + //Note the way the attack bit is combined with the inversion state. This is known to + //be correct, and is essential in order to deal with cases where the SSG-EG state is + //changed after key-on. A change in the state of the attack bit will result in an + //immediate inversion of the output. Also note the calculation performed to derive + //the "inverted" data. This calculation has been proven to be binary-accurate. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) + && (state->phase != OperatorData::ADSR_RELEASE) + && (state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) + { + attenuation = 0x200 - attenuation; + attenuation &= 0x3FF; + } + + //Combine TL with the output attenuation value. Note that TL is applied after SSG-EG + //output inversion has been applied. + attenuation += ConvertTotalLevelToAttenuation(GetTotalLevelData(operatorAddressOffset, accessTarget)); + + //Apply amplitude modulation to the output attenuation value + if(GetAmplitudeModulationEnabled(operatorAddressOffset, accessTarget)) + { + // --------------------------------- + // | LFO Counter | + // |-------------------------------| + // |...| 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----============================= + // | Amplitude Modulation | + // | Index (7-bit) | + // |---------------------------| + // | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----------------------------- + //Calculate the current attenuation value from the LFO. Note that the amplitude + //modulation wave starts off inverted. An index of 0 corresponds with the maximum + //attenuation value that amplitude modulation can apply, according to the current + //amplitude modulation sensitivity. This is of particular importance when the LFO + //is set to the disabled state. In this state, the LFO counter is held at 0, but + //since an amplitude modulation index of 0 represents the "peak" of the wave, the + //operator will be attenuated by a fixed amount through amplitude modulation while + //the LFO counter is being held at 0. + bool inverted = (currentLFOCounter & 0x40) == 0; + unsigned int amValue = currentLFOCounter & 0x3F; + if(inverted) + { + amValue = ~amValue & 0x3F; + } + + //Adjust the attenuation value by the amplitude modulation sensitivity + const unsigned int amShiftValues[4] = {8, 3, 1, 0}; + unsigned int amSensitivity = GetAMSData(channelAddressOffset, accessTarget); + amValue = (amValue << 1) >> amShiftValues[amSensitivity]; + + //Attenuate the operator output by the current amplitude modulation value + attenuation += amValue; + } + + //Limit the result to the maximum attenuation value + if(attenuation >= (1 << attenuationBitCount)) + { + attenuation = (1 << attenuationBitCount) - 1; + } + + return attenuation; +} + +//---------------------------------------------------------------------------------------- +//This function implements the ADSR envelope rate calculation. Refer to page 30 of +//the YM2608 documentation for further info. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateRate(unsigned int rateData, unsigned int rateKeyScale) const +{ + //Parameters rateData and rateKeyScale are 5-bit numbers in the range 0x00-0x1F + unsigned int rate = (2 * rateData) + rateKeyScale; + //Special case. If rateData is 0, rate is forced to 0, regardless of the value of + //rateKeyScale. + if(rateData == 0) + { + rate = 0; + } + //The rate number is a 6-bit number, and the result is capped at the max to prevent + //overflows. We limit the result to the maximum value here in the case where the + //calculation exceeds the maximum. + if(rate >= (1 << rateBitCount)) + { + rate = (1 << rateBitCount) - 1; + } + return rate; +} + +//---------------------------------------------------------------------------------------- +//This function implements the rate key-scaling calculation. Refer to page 29 of the +//YM2608 documentation for further info. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateRateKeyScale(unsigned int keyScaleData, unsigned int keyCode) const +{ + //Parameter keyScaleData is a 2-bit value. Parameter keyCode is a 5-bit value. Result + //is a 5-bit value. + unsigned int keyScaleDivisor = 1 << (3 - keyScaleData); + unsigned int rateKeyScale = keyCode / keyScaleDivisor; + return rateKeyScale; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::ConvertTotalLevelToAttenuation(unsigned int totalLevel) const +{ + //Note that in the YM2608 Application Manual, section 2-5-3, page 32, there's a + //comment that when all the bits of TL are set, the attenuation level is set to the + //maximum amount (96db). This is a little misleading for our purposes here. This does + //NOT mean that all 10 bits of the attenuation output have to be forced to set when + //all 7 bits of TL are set. In reality, due to the precision limitations of the + //operator unit, an envelope generator output of 0x340 or greater will always force + //the final output to maximum attenuation (96db). This is well below the output of + //0x3F8 we would get if all the bits in TL are set. Due to this, it's impossible to + //know if the YM2612 forces all 10 bits of the envelope generator output to set when + //all 7 bits of TL are set, but it doesn't matter for the same reason, as there's no + //way for that to have any measurable effect. + return totalLevel << 3; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::ConvertSustainLevelToAttenuation(unsigned int sustainLevel) const +{ + //Note that in the YM2608 Application Manual, section 2-5-1, page 28, there's a + //comment that when all the bits of SL are set, SL is set to 93db. You might wonder + //whether they really meant 96db. In reality, it makes no difference. At 93db, the + //10-bit output from the envelope generator would be 0x370, which is over the maximum + //attenuation value of 0x340 that the operator unit can accept, before precision + //limitations force the output to minimum. + if(sustainLevel == 0xF) + { + //If all bits are set, sustain level is forced to 93db + sustainLevel |= 0x10; + } + sustainLevel <<= 5; + return sustainLevel; +} + +//---------------------------------------------------------------------------------------- +//Operator unit functions +//---------------------------------------------------------------------------------------- +//This function duplicates the exact power conversion performed by the YM2612 in the +//final stage of the operator unit. It is an implementation of the following: +// result = pow(2, -num); +// num: A 13-bit fixed point value of the form 5.8 (5 bit whole, 8 bit fractional) +// result: A 13-bit normalized output in the range 1-0. +//Internally, a 256 entry lookup table is used. This lookup stores a rounded 11-bit result +//for a range 0-1. Since we're dealing with powers of 2, this result can be adjusted for +//source numbers outside the range 0-1 by shifting the result. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::InversePow2(unsigned int num) const +{ + unsigned int shiftCount = num >> powTableBitCount; + unsigned int tableIndex = num & ((1 << powTableBitCount) - 1); + unsigned int tableEntry = powTable[tableIndex]; + unsigned int outputShifted = (tableEntry << 2) >> shiftCount; + return outputShifted; +} + +//---------------------------------------------------------------------------------------- +int YM2612::CalculateOperator(unsigned int phase, int phaseModulation, unsigned int attenuation) const +{ + //Add the current phase and phase modulation values + Data combinedPhase(phaseBitCount); + combinedPhase = (unsigned int)((int)phase + phaseModulation); + + //The YM2612 sine table only stores values for a quarter of the full sine wave. We + //separate the sign bit of the phase value here, which leaves us with a half-phase + //representing positive wave oscillations only. For the remaining half-phase, if + //the phase is on the second half of the oscillation (decreasing slope), we invert + //the phase. The second half of the oscillation is a mirror of the first, so by + //inverting the half-phase, the quarter-phase sine table can be used to resolve the + //correct sine value for the full positive oscillation. The separated sign bit is + //used later to correct the result for negative oscillations. + bool signBit = combinedPhase.GetBit(phaseBitCount - 1); + bool slopeBit = combinedPhase.GetBit(phaseBitCount - 2); + Data quarterPhase(phaseBitCount - 2); + quarterPhase = combinedPhase; + if(slopeBit) + { + //If the MSB of the half-phase is set, the sine wave is decreasing in slope. In + //this case, we need to invert the quarter phase value, to mirror the lookup + //index into the sine table. + quarterPhase = ~quarterPhase; + } + + //Output from sinTable is a 4.8 fixed point attenuation value + unsigned int sinValue = sinTable[quarterPhase.GetData()]; + //Convert attenuation from a 4.6 fixed point value, to a 4.8 fixed point value. + unsigned int convertedAttenuation = attenuation << 2; + //Combined attenuation is a 5.8 fixed point value + unsigned int combinedAttenuation = sinValue + convertedAttenuation; + + //Convert the 5.8 fixed point attenuation value from a logarithmic representation of + //attenuation, to a linear representation of power. + int powResult = (int)InversePow2(combinedAttenuation); + + //Our calculated value currently represents the absolute value of the true result. If + //the original phase value specified a negative oscillation of the wave, negate the + //result. This will give us the true signed result. + if(signBit) + { + powResult = 0 - powResult; + } + return powResult; +} + +//---------------------------------------------------------------------------------------- +//Memory interface functions +//---------------------------------------------------------------------------------------- +IBusInterface::AccessResult YM2612::ReadInterface(unsigned int interfaceNumber, unsigned int location, Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(accessMutex); + + //Trigger a system rollback if the device has been accessed out of order. This is + //required in order to ensure that the address register is correct when each write + //occurs. + if(accessTime < lastAccessTime) + { + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); + } + lastAccessTime = accessTime; + + UpdateTimers(accessTime); + data.SetLowerBits(status); + + return true; +} + +//---------------------------------------------------------------------------------------- +IBusInterface::AccessResult YM2612::WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(accessMutex); + AccessTarget accessTarget; + accessTarget.AccessTime(accessTime); + + //Trigger a system rollback if the device has been accessed out of order. This is + //required in order to ensure that the register latch settings are correct when each + //write occurs. + if(accessTime < lastAccessTime) + { + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); + } + lastAccessTime = accessTime; + + //Decode and carry out the write operation. Note that hardware tests have shown that + //both data ports are equivalent, and that a write to either of the address ports + //stores both the part number and the register number. Regardless of whether the + //currently selected register is in part 1 or part 2, both data ports can be used to + //update the currently selected register value. + if(location == 0) + { + //Set the currently latched register to the specified part 1 register + currentReg = data.GetData(); + } + else if(location == 2) + { + //Set the currently latched register to the specified part 2 register + currentReg = registerCountPerPart + data.GetData(); + } + else if((location == 1) || (location == 3)) + { + //Only commit this register write if it wasn't latched + if(!rawRegisterLocking[currentReg] && !CheckForLatchedWrite(currentReg, data, accessTime)) + { + //Write to the selected register + RegisterSpecialUpdateFunction(currentReg, data, accessTime, caller, accessContext); + SetRegisterData(currentReg, data, accessTarget); + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } + } + } + + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::RegisterSpecialUpdateFunction(unsigned int location, const Data& data, double accessTime, IDeviceContext* caller, unsigned int accessContext) +{ + //Note that the only register changes which currently require special handling at the + //time they are written are registers which relate to the timers. Writes to all other + //registers including key-on/off notifications are handled in the render thread. + switch(location) + { + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //24H |-------------------------------| + // | Timer A MSBs (bits 2-9) | + // --------------------------------- + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //25H |-------------------------------| + // | / / / / / / | Timer | + // | |A LSBs | + // --------------------------------- + case 0x24:{ + UpdateTimers(accessTime); + if(!timerAStateLocking.rate) + { + unsigned int trueTimerAInitialCounter = ~timerAInitialCounter & 0x3FF; + trueTimerAInitialCounter = (trueTimerAInitialCounter & 0x003) | (data.GetDataSegment(0, 8) << 2); + timerAInitialCounter = ~trueTimerAInitialCounter & 0x3FF; + } + break;} + case 0x25:{ + UpdateTimers(accessTime); + if(!timerAStateLocking.rate) + { + unsigned int trueTimerAInitialCounter = ~timerAInitialCounter & 0x3FF; + trueTimerAInitialCounter = (trueTimerAInitialCounter & 0x3FC) | data.GetDataSegment(0, 2); + timerAInitialCounter = ~trueTimerAInitialCounter & 0x3FF; + } + break;} + case 0x26: + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //26H |-------------------------------| + // | Timer B | + // --------------------------------- + UpdateTimers(accessTime); + if(!timerBStateLocking.rate) + { + timerBInitialCounter = ~data.GetDataSegment(0, 8) & 0xFF; + } + break; + case 0x27: + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // |-------------------------------| + // | | Timer | Timer | Timer | + //27H | CH3 | Reset | Enable| Load | + // | Mode |-------|-------|-------| + // | | B | A | B | A | B | A | + // --------------------------------- + //##TODO## According to the Y8950AM Application Manual, page 17, when the IRQ + //RESET bit is flagged in that processor, all other bits in the write to the + //register are ignored. Confirm this is not the case on the YM2612. + UpdateTimers(accessTime); + + //Update the load bits for timers A and B. Note that hardware tests have shown + //that the current counter value for a timer is reloaded when the load bit is + //changed from 0 to 1. A timer does not resume counting from its previous + //position when the load bit is toggled from 0 to 1. Setting the load bit to 1 + //for a timer which is already loaded does not force a re-load of the counter. + if(!timerAStateLocking.load) + { + bool timerALoadNew = data.GetBit(0); + if(!timerALoad && timerALoadNew) + { + timerACounter = timerAInitialCounter; + } + timerALoad = timerALoadNew; + } + if(!timerBStateLocking.load) + { + bool timerBLoadNew = data.GetBit(1); + if(!timerBLoad && timerBLoadNew) + { + timerBCounter = timerBInitialCounter; + } + timerBLoad = timerBLoadNew; + } + + //Update the enable bits for timers A and B + if(!timerAStateLocking.enable) + { + timerAEnable = data.GetBit(2); + } + if(!timerBStateLocking.enable) + { + timerBEnable = data.GetBit(3); + } + + //Update the overflow bits for timers A and B. We also negate the IRQ line here + //if it was asserted, and is now clear after processing the reset bits. + bool initialIntLineState = GetTimerAOverflow() || GetTimerBOverflow(); + if(!timerAStateLocking.overflow && data.GetBit(4)) + { + SetTimerAOverflow(false); + } + if(!timerBStateLocking.overflow && data.GetBit(5)) + { + SetTimerBOverflow(false); + } + if(initialIntLineState && !GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = false; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), caller, accessTime, accessContext); + } + } + break; + } +} + +//---------------------------------------------------------------------------------------- +bool YM2612::CheckForLatchedWrite(unsigned int location, const Data& data, double accessTime) +{ + AccessTarget accessTarget; + accessTarget.AccessTime(accessTime); + + switch(location) + { + //If we're writing to a block/fnum register, the write needs to be put in limbo until + //the corresponding fnum register is next written to. + case 0xA4: + latchedFrequencyDataPending[CHANNEL1] = true; + latchedFrequencyData[CHANNEL1] = data; + return true; + case 0xA5: + latchedFrequencyDataPending[CHANNEL2] = true; + latchedFrequencyData[CHANNEL2] = data; + return true; + case 0xA6: + latchedFrequencyDataPending[CHANNEL3] = true; + latchedFrequencyData[CHANNEL3] = data; + return true; + case 0x1A4: + latchedFrequencyDataPending[CHANNEL4] = true; + latchedFrequencyData[CHANNEL4] = data; + return true; + case 0x1A5: + latchedFrequencyDataPending[CHANNEL5] = true; + latchedFrequencyData[CHANNEL5] = data; + return true; + case 0x1A6: + latchedFrequencyDataPending[CHANNEL6] = true; + latchedFrequencyData[CHANNEL6] = data; + return true; + case 0xAD: + latchedFrequencyDataPendingCH3[0] = true; + latchedFrequencyDataCH3[0] = data; + return true; + case 0xAC: + latchedFrequencyDataPendingCH3[1] = true; + latchedFrequencyDataCH3[1] = data; + return true; + case 0xAE: + latchedFrequencyDataPendingCH3[2] = true; + latchedFrequencyDataCH3[2] = data; + return true; + + //If we're writing to an fnum register, commit any latched write to the corresponding + //block/fnum register. + case 0xA0: + if(latchedFrequencyDataPending[CHANNEL1]) + { + SetRegisterData(0xA4, latchedFrequencyData[CHANNEL1], accessTarget); + latchedFrequencyDataPending[CHANNEL1] = false; + latchedFrequencyData[CHANNEL1] = 0; + } + return false; + case 0xA1: + if(latchedFrequencyDataPending[CHANNEL2]) + { + SetRegisterData(0xA5, latchedFrequencyData[CHANNEL2], accessTarget); + latchedFrequencyDataPending[CHANNEL2] = false; + latchedFrequencyData[CHANNEL2] = 0; + } + return false; + case 0xA2: + if(latchedFrequencyDataPending[CHANNEL3]) + { + SetRegisterData(0xA6, latchedFrequencyData[CHANNEL3], accessTarget); + latchedFrequencyDataPending[CHANNEL3] = false; + latchedFrequencyData[CHANNEL3] = 0; + } + return false; + case 0x1A0: + if(latchedFrequencyDataPending[CHANNEL4]) + { + SetRegisterData(0x1A4, latchedFrequencyData[CHANNEL4], accessTarget); + latchedFrequencyDataPending[CHANNEL4] = false; + latchedFrequencyData[CHANNEL4] = 0; + } + return false; + case 0x1A1: + if(latchedFrequencyDataPending[CHANNEL5]) + { + SetRegisterData(0x1A5, latchedFrequencyData[CHANNEL5], accessTarget); + latchedFrequencyDataPending[CHANNEL5] = false; + latchedFrequencyData[CHANNEL5] = 0; + } + return false; + case 0x1A2: + if(latchedFrequencyDataPending[CHANNEL6]) + { + SetRegisterData(0x1A6, latchedFrequencyData[CHANNEL6], accessTarget); + latchedFrequencyDataPending[CHANNEL6] = false; + latchedFrequencyData[CHANNEL6] = 0; + } + return false; + case 0xA9: + if(latchedFrequencyDataPendingCH3[0]) + { + SetRegisterData(0xAD, latchedFrequencyDataCH3[0], accessTarget); + latchedFrequencyDataPendingCH3[0] = false; + latchedFrequencyDataCH3[0] = 0; + } + return false; + case 0xA8: + if(latchedFrequencyDataPendingCH3[1]) + { + SetRegisterData(0xAC, latchedFrequencyDataCH3[1], accessTarget); + latchedFrequencyDataPendingCH3[1] = false; + latchedFrequencyDataCH3[1] = 0; + } + return false; + case 0xAA: + if(latchedFrequencyDataPendingCH3[2]) + { + SetRegisterData(0xAE, latchedFrequencyDataCH3[2], accessTarget); + latchedFrequencyDataPendingCH3[2] = false; + latchedFrequencyDataCH3[2] = 0; + } + return false; + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Timer management functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateTimers(double timesliceProgress) +{ + //Calculate the total number of cycles that have executed since the last timer update + double initialTimersRemainingTime = timersRemainingTime; + double timerClockPeriod = 1000000000.0 / ((externalClockRate / (double)fmClockDivider) / (double)outputClockDivider); + double timePeriod = timersRemainingTime + (timesliceProgress - timersLastUpdateTime); + unsigned int timerClockCyclesExecuted = (unsigned int)(timePeriod / timerClockPeriod); + timersRemainingTime = timePeriod - ((double)timerClockCyclesExecuted * timerClockPeriod); + timersLastUpdateTime = timesliceProgress; + + //Calculate the total number of steps the timers have advanced + unsigned int initialTimerARemainingCycles = timerARemainingCycles; + unsigned int totalTimerACyclesExecuted = (timerClockCyclesExecuted + timerARemainingCycles) / timerAClockDivider; + timerARemainingCycles = (timerClockCyclesExecuted + timerARemainingCycles) % timerAClockDivider; + unsigned int initialTimerBRemainingCycles = timerBRemainingCycles; + unsigned int totalTimerBCyclesExecuted = (timerClockCyclesExecuted + timerBRemainingCycles) / timerBClockDivider; + timerBRemainingCycles = (timerClockCyclesExecuted + timerBRemainingCycles) % timerBClockDivider; + + //If timer A is loaded and the counter isn't locked, update the timer value + if(timerALoad && !timerAStateLocking.counter) + { + unsigned int timerAPeriod = timerAInitialCounter + 1; + + //Calculate each overflow time. In the case of timer A, we do this regardless of + //whether the timer is enabled, or whether the overflow flag is locked, since CSM + //key-on events are still generated each time timer A expires, regardless of + //whether the timer is enabled or the state of the overflow bit. + int timerAOverflowCount = ((int)totalTimerACyclesExecuted + ((int)timerAInitialCounter - (int)timerACounter)) / (int)timerAPeriod; + for(int i = 0; i < timerAOverflowCount; ++i) + { + unsigned int overflowCycle = ((unsigned int)i * timerAPeriod) + timerACounter; + double interruptTime = ((double)((overflowCycle * timerAClockDivider) + initialTimerARemainingCycles) * timerClockPeriod) - initialTimersRemainingTime; + + //Only use this overflow time to adjust the overflow flag and IRQ line state + //if the timer is enabled, and the overflow flag isn't locked. + if(timerAEnable && !timerAStateLocking.overflow) + { + //If the IRQ line is currently negated, and we're about to generate an + //overflow, assert the IRQ line. + if(!GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = true; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), GetDeviceContext(), interruptTime, (unsigned int)AccessContext::IRQ); + } + } + //Update the overflow flag + SetTimerAOverflow(true); + } + //Record the exact times when each timer A overflow occurred since the + //last update cycle. This is required in order to implement accurate CSM + //support. + timerAOverflowTimes.Write(interruptTime, true); + } + + //Calculate the new counter value for the timer + unsigned int timerACounterDisplace = totalTimerACyclesExecuted % timerAPeriod; + timerACounter = (timerACounter + (timerAPeriod - timerACounterDisplace)) % timerAPeriod; + } + + //If timer B is loaded and the counter isn't locked, update the timer value + if(timerBLoad && !timerBStateLocking.counter) + { + unsigned int timerBPeriod = timerBInitialCounter + 1; + + //If the timer is enabled, generate interrupts for each time an overflow has + //occurred, and update the overflow flag. + if(timerBEnable && !timerBStateLocking.overflow) + { + //Calculate each overflow time + int timerBOverflowCount = ((int)totalTimerBCyclesExecuted + ((int)timerBInitialCounter - (int)timerBCounter)) / (int)timerBPeriod; + for(int i = 0; i < timerBOverflowCount; ++i) + { + unsigned int overflowCycle = ((unsigned int)i * timerBPeriod) + timerBCounter; + double interruptTime = ((double)((overflowCycle * timerBClockDivider) + initialTimerBRemainingCycles) * timerClockPeriod) - initialTimersRemainingTime; + //If the IRQ line is currently negated, and we're about to generate an + //overflow, assert the IRQ line. + if(!GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = true; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), GetDeviceContext(), interruptTime, (unsigned int)AccessContext::IRQ); + } + } + //Update the overflow flag + SetTimerBOverflow(true); + } + } + + //Calculate the new counter value for the timer + unsigned int timerBCounterDisplace = totalTimerBCyclesExecuted % timerBPeriod; + timerBCounter = (timerBCounter + (timerBPeriod - timerBCounterDisplace)) % timerBPeriod; + } +} + +//---------------------------------------------------------------------------------------- +//Savestate functions +//---------------------------------------------------------------------------------------- +void YM2612::LoadState(IHierarchicalStorageNode& node) +{ + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + //Clock settings + if((*i)->GetName() == L"ExternalClockRate") + { + (*i)->ExtractData(externalClockRate); + } + + //Bus interface + else if((*i)->GetName() == L"ICLineState") + { + icLineState = (*i)->ExtractData(); + } + + //Register data + else if((*i)->GetName() == L"Registers") + { + reg.LoadState(*(*i)); + } + else if((*i)->GetName() == L"StatusRegister") + { + (*i)->ExtractData(status); + } + + //Register latch settings + else if((*i)->GetName() == L"LatchedRegister") + { + (*i)->ExtractData(currentReg); + } + else if((*i)->GetName() == L"LatchedFrequencyData") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + latchedFrequencyDataPending[channelNo] = true; + (*i)->ExtractData(latchedFrequencyData[channelNo]); + } + } + else if((*i)->GetName() == L"LatchedFrequencyDataCH3") + { + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"OperatorNo", operatorNo) && (operatorNo < operatorCount)) + { + latchedFrequencyDataPendingCH3[operatorNo] = true; + (*i)->ExtractData(latchedFrequencyDataCH3[operatorNo]); + } + } + + //Render thread properties + else if((*i)->GetName() == L"RemainingRenderTime") + { + (*i)->ExtractData(remainingRenderTime); + } + else if((*i)->GetName() == L"EGRemainingRenderCycles") + { + (*i)->ExtractData(egRemainingRenderCycles); + } + + //Render data + else if((*i)->GetName() == L"EnvelopeCycleCounter") + { + (*i)->ExtractHexData(envelopeCycleCounter); + } + else if((*i)->GetName() == L"RenderData") + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount) && + (*i)->ExtractAttribute(L"OperatorNo", operatorNo) && (operatorNo < operatorCount)) + { + OperatorData* state = &operatorData[channelNo][operatorNo]; + (*i)->ExtractAttributeHex(L"Attenuation", state->attenuation); + (*i)->ExtractAttributeHex(L"PhaseCounter", state->phaseCounter); + if(!keyStateLocking[channelNo][operatorNo]) + { + (*i)->ExtractAttribute(L"KeyOn", state->keyon); + } + (*i)->ExtractAttribute(L"CSMKeyOn", state->csmKeyOn); + (*i)->ExtractAttribute(L"KeyOnPrevious", state->keyonPrevious); + (*i)->ExtractAttribute(L"SSGOutputInverted", state->ssgOutputInverted); + + std::wstring phaseString; + (*i)->ExtractAttribute(L"Phase", phaseString); + if(phaseString == L"ADSR_ATTACK") + { + state->phase = OperatorData::ADSR_ATTACK; + } + else if(phaseString == L"ADSR_DECAY") + { + state->phase = OperatorData::ADSR_DECAY; + } + else if(phaseString == L"ADSR_SUSTAIN") + { + state->phase = OperatorData::ADSR_SUSTAIN; + } + else if(phaseString == L"ADSR_RELEASE") + { + state->phase = OperatorData::ADSR_RELEASE; + } + } + } + else if((*i)->GetName() == L"OP1FeedbackData") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + (*i)->ExtractAttributeHex(L"Sample1", feedbackBuffer[channelNo][0]); + (*i)->ExtractAttributeHex(L"Sample2", feedbackBuffer[channelNo][1]); + } + } + else if((*i)->GetName() == L"CyclesUntilLFOIncrement") + { + (*i)->ExtractData(cyclesUntilLFOIncrement); + } + else if((*i)->GetName() == L"CurrentLFOCounter") + { + (*i)->ExtractData(currentLFOCounter); + } + + //Timer status + else if((*i)->GetName() == L"LastTimesliceLength") + { + (*i)->ExtractData(lastTimesliceLength); + } + else if((*i)->GetName() == L"TimersRemainingTime") + { + (*i)->ExtractData(timersRemainingTime); + } + else if((*i)->GetName() == L"TimerARemainingCycles") + { + (*i)->ExtractData(timerARemainingCycles); + } + else if((*i)->GetName() == L"TimerBRemainingCycles") + { + (*i)->ExtractData(timerBRemainingCycles); + } + else if(((*i)->GetName() == L"TimerACounter") && !timerAStateLocking.counter) + { + (*i)->ExtractData(timerACounter); + } + else if(((*i)->GetName() == L"TimerBCounter") && !timerBStateLocking.counter) + { + (*i)->ExtractData(timerBCounter); + } + else if(((*i)->GetName() == L"TimerAInitialCounter") && !timerAStateLocking.rate) + { + (*i)->ExtractData(timerAInitialCounter); + } + else if(((*i)->GetName() == L"TimerBInitialCounter") && !timerBStateLocking.rate) + { + (*i)->ExtractData(timerBInitialCounter); + } + else if(((*i)->GetName() == L"TimerAEnable") && !timerAStateLocking.enable) + { + (*i)->ExtractData(timerAEnable); + } + else if(((*i)->GetName() == L"TimerBEnable") && !timerBStateLocking.enable) + { + (*i)->ExtractData(timerBEnable); + } + else if(((*i)->GetName() == L"TimerALoad") && !timerAStateLocking.load) + { + (*i)->ExtractData(timerALoad); + } + else if(((*i)->GetName() == L"TimerBLoad") && !timerBStateLocking.load) + { + (*i)->ExtractData(timerBLoad); + } + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SaveState(IHierarchicalStorageNode& node) const +{ + //Clock settings + node.CreateChild(L"ExternalClockRate").SetData(externalClockRate); + + //Bus interface + node.CreateChild(L"ICLineState").SetData(icLineState); + + //Register data + IHierarchicalStorageNode& regNode = node.CreateChild(L"Registers"); + std::wstring regBufferName = GetFullyQualifiedDeviceInstanceName(); + regBufferName += L".Registers"; + reg.SaveState(regNode, regBufferName, false); + node.CreateChild(L"StatusRegister").SetData(status); + + //Register latch settings + node.CreateChild(L"LatchedRegister").SetData(currentReg); + for(unsigned int i = 0; i < channelCount; ++i) + { + if(latchedFrequencyDataPending[i]) + { + node.CreateChild(L"LatchedFrequencyData").SetData(latchedFrequencyData[i]).CreateAttribute(L"ChannelNo", i); + } + } + for(unsigned int i = 0; i < 3; ++i) + { + if(latchedFrequencyDataPendingCH3[i]) + { + node.CreateChild(L"LatchedFrequencyDataCH3").SetData(latchedFrequencyDataCH3[i]).CreateAttribute(L"OperatorNo", i); + } + } + + //Render thread properties + node.CreateChild(L"RemainingRenderTime", remainingRenderTime); + node.CreateChild(L"EGRemainingRenderCycles", egRemainingRenderCycles); + + //Render data + node.CreateChildHex(L"EnvelopeCycleCounter", envelopeCycleCounter, sizeof(envelopeCycleCounter)*2); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + const OperatorData* state = &operatorData[channelNo][operatorNo]; + IHierarchicalStorageNode& renderDataState = node.CreateChild(L"RenderData"); + renderDataState.CreateAttribute(L"ChannelNo", channelNo); + renderDataState.CreateAttribute(L"OperatorNo", operatorNo); + renderDataState.CreateAttributeHex(L"Attenuation", state->attenuation, (attenuationBitCount+3)/4); + renderDataState.CreateAttributeHex(L"PhaseCounter", state->phaseCounter, (phaseBitCount+3)/4); + renderDataState.CreateAttribute(L"KeyOn", state->keyon); + renderDataState.CreateAttribute(L"CSMKeyOn", state->csmKeyOn); + renderDataState.CreateAttribute(L"KeyOnPrevious", state->keyonPrevious); + renderDataState.CreateAttribute(L"SSGOutputInverted", state->ssgOutputInverted); + + std::wstring phaseString; + switch(state->phase) + { + case OperatorData::ADSR_ATTACK: + phaseString = L"ADSR_ATTACK"; + break; + case OperatorData::ADSR_DECAY: + phaseString = L"ADSR_DECAY"; + break; + case OperatorData::ADSR_SUSTAIN: + phaseString = L"ADSR_SUSTAIN"; + break; + case OperatorData::ADSR_RELEASE: + phaseString = L"ADSR_RELEASE"; + break; + } + renderDataState.CreateAttribute(L"Phase", phaseString); + } + } + for(unsigned int i = 0; i < channelCount; ++i) + { + IHierarchicalStorageNode& feedbackData = node.CreateChild(L"OP1FeedbackData"); + feedbackData.CreateAttribute(L"ChannelNo", i); + feedbackData.CreateAttributeHex(L"Sample1", feedbackBuffer[i][0], (operatorOutputBitCount+3)/4); + feedbackData.CreateAttributeHex(L"Sample2", feedbackBuffer[i][1], (operatorOutputBitCount+3)/4); + } + node.CreateChild(L"CyclesUntilLFOIncrement", cyclesUntilLFOIncrement); + node.CreateChild(L"CurrentLFOCounter", currentLFOCounter); + + //Timer status + node.CreateChild(L"LastTimesliceLength", lastTimesliceLength); + node.CreateChild(L"TimersRemainingTime", timersRemainingTime); + node.CreateChild(L"TimerARemainingCycles", timerARemainingCycles); + node.CreateChild(L"TimerBRemainingCycles", timerBRemainingCycles); + node.CreateChild(L"TimerACounter", timerACounter); + node.CreateChild(L"TimerBCounter", timerBCounter); + node.CreateChild(L"TimerAInitialCounter", timerAInitialCounter); + node.CreateChild(L"TimerBInitialCounter", timerBInitialCounter); + node.CreateChild(L"TimerAEnable", timerAEnable); + node.CreateChild(L"TimerBEnable", timerBEnable); + node.CreateChild(L"TimerALoad", timerALoad); + node.CreateChild(L"TimerBLoad", timerBLoad); +} + +//---------------------------------------------------------------------------------------- +void YM2612::LoadDebuggerState(IHierarchicalStorageNode& node) +{ + //Initialize the register locking state + std::unique_lock lock2(registerLockMutex); + lockedRegisterState.clear(); + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + rawRegisterLocking[i] = false; + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + keyStateLocking[channelNo][operatorNo] = false; + } + } + timerAStateLocking.rate = false; + timerAStateLocking.counter = false; + timerAStateLocking.load = false; + timerAStateLocking.enable = false; + timerAStateLocking.overflow = false; + timerBStateLocking.rate = false; + timerBStateLocking.counter = false; + timerBStateLocking.load = false; + timerBStateLocking.enable = false; + timerBStateLocking.overflow = false; + + //Load the register locking state + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + if((*i)->GetName() == L"LockedRegisterState") + { + unsigned int dataID; + std::wstring lockedValue; + if((*i)->ExtractAttribute(L"DataID", dataID) && (*i)->ExtractAttribute(L"LockedValue", lockedValue)) + { + IHierarchicalStorageAttribute* usingChannelDataContextAttribute = (*i)->GetAttribute(L"UsingChannelDataContext"); + IHierarchicalStorageAttribute* usingOperatorDataContextAttribute = (*i)->GetAttribute(L"UsingOperatorDataContext"); + if(usingChannelDataContextAttribute != 0) + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo)) + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, ChannelDataContext(channelNo), lockedValue)); + } + } + else if(usingOperatorDataContextAttribute != 0) + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (*i)->ExtractAttribute(L"OperatorNo", operatorNo)) + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, OperatorDataContext(channelNo, operatorNo), lockedValue)); + } + } + else + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, lockedValue)); + } + } + } + else if((*i)->GetName() == L"LockedRawRegister") + { + unsigned int registerNo; + if((*i)->ExtractAttribute(L"RegisterNo", registerNo)) + { + if(registerNo < registerCountTotal) + { + rawRegisterLocking[registerNo] = true; + } + } + } + else if((*i)->GetName() == L"LockedKeyState") + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (*i)->ExtractAttribute(L"OperatorNo", operatorNo)) + { + if((channelNo < channelCount) && (operatorNo < operatorCount)) + { + keyStateLocking[channelNo][operatorNo] = true; + } + } + } + else if((*i)->GetName() == L"LockedTimerARate") + { + timerAStateLocking.rate = true; + } + else if((*i)->GetName() == L"LockedTimerACounter") + { + timerAStateLocking.counter = true; + } + else if((*i)->GetName() == L"LockedTimerALoad") + { + timerAStateLocking.load = true; + } + else if((*i)->GetName() == L"LockedTimerAEnable") + { + timerAStateLocking.enable = true; + } + else if((*i)->GetName() == L"LockedTimerAOverflow") + { + timerAStateLocking.overflow = true; + } + else if((*i)->GetName() == L"LockedTimerBRate") + { + timerBStateLocking.rate = true; + } + else if((*i)->GetName() == L"LockedTimerBCounter") + { + timerBStateLocking.counter = true; + } + else if((*i)->GetName() == L"LockedTimerBLoad") + { + timerBStateLocking.load = true; + } + else if((*i)->GetName() == L"LockedTimerBEnable") + { + timerBStateLocking.enable = true; + } + else if((*i)->GetName() == L"LockedTimerBOverflow") + { + timerBStateLocking.overflow = true; + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SaveDebuggerState(IHierarchicalStorageNode& node) const +{ + //Save the register locking state + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator lockedRegisterStateListIterator = lockedRegisterStateIterator->second.begin(); lockedRegisterStateListIterator != lockedRegisterStateIterator->second.end(); ++lockedRegisterStateListIterator) + { + const RegisterLocking& registerLockingInfo = *lockedRegisterStateListIterator; + IHierarchicalStorageNode& childNode = node.CreateChild(L"LockedRegisterState"); + childNode.CreateAttribute(L"DataID", registerLockingInfo.dataID); + childNode.CreateAttribute(L"LockedValue", registerLockingInfo.lockedValue); + if(registerLockingInfo.usingChannelDataContext) + { + childNode.CreateAttribute(L"UsingChannelDataContext", true); + childNode.CreateAttribute(L"ChannelNo", registerLockingInfo.channelDataContext.channelNo); + } + else if(registerLockingInfo.usingOperatorDataContext) + { + childNode.CreateAttribute(L"UsingOperatorDataContext", true); + childNode.CreateAttribute(L"ChannelNo", registerLockingInfo.operatorDataContext.channelNo); + childNode.CreateAttribute(L"OperatorNo", registerLockingInfo.operatorDataContext.operatorNo); + } + } + } + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + if(rawRegisterLocking[i]) + { + node.CreateChild(L"LockedRawRegister").CreateAttributeHex(L"RegisterNo", i, 3); + } + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + if(keyStateLocking[channelNo][operatorNo]) + { + node.CreateChild(L"LockedKeyState").CreateAttribute(L"ChannelNo", channelNo).CreateAttribute(L"OperatorNo", operatorNo); + } + } + } + if(timerAStateLocking.rate) + { + node.CreateChild(L"LockedTimerARate"); + } + if(timerAStateLocking.counter) + { + node.CreateChild(L"LockedTimerACounter"); + } + if(timerAStateLocking.load) + { + node.CreateChild(L"LockedTimerALoad"); + } + if(timerAStateLocking.enable) + { + node.CreateChild(L"LockedTimerAEnable"); + } + if(timerAStateLocking.overflow) + { + node.CreateChild(L"LockedTimerAOverflow"); + } + if(timerBStateLocking.rate) + { + node.CreateChild(L"LockedTimerBRate"); + } + if(timerBStateLocking.counter) + { + node.CreateChild(L"LockedTimerBCounter"); + } + if(timerBStateLocking.load) + { + node.CreateChild(L"LockedTimerBLoad"); + } + if(timerBStateLocking.enable) + { + node.CreateChild(L"LockedTimerBEnable"); + } + if(timerBStateLocking.overflow) + { + node.CreateChild(L"LockedTimerBOverflow"); + } +} + +//---------------------------------------------------------------------------------------- +//Data read/write functions +//---------------------------------------------------------------------------------------- +bool YM2612::ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const +{ + ApplyGenericDataValueDisplaySettings(dataID, dataValue); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + Data registerData = GetRegisterData(registerDataContext.registerNo, AccessTarget().AccessLatest()); + return dataValue.SetValue(registerData.GetData());} + case IYM2612DataSource::TestData: + return dataValue.SetValue(GetTestData(AccessTarget().AccessLatest())); + case IYM2612DataSource::LFOEnabled: + return dataValue.SetValue(GetLFOEnabled(AccessTarget().AccessLatest())); + case IYM2612DataSource::LFOData: + return dataValue.SetValue(GetLFOData(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerAData: + return dataValue.SetValue(GetTimerAData(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBData: + return dataValue.SetValue(GetTimerBData(AccessTarget().AccessLatest())); + case IYM2612DataSource::CH3Mode: + return dataValue.SetValue(GetCH3Mode(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBReset: + return dataValue.SetValue(GetTimerBReset(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerAReset: + return dataValue.SetValue(GetTimerAReset(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBEnable: + return dataValue.SetValue(timerBEnable); + case IYM2612DataSource::TimerAEnable: + return dataValue.SetValue(timerAEnable); + case IYM2612DataSource::TimerBLoad: + return dataValue.SetValue(timerBLoad); + case IYM2612DataSource::TimerALoad: + return dataValue.SetValue(timerALoad); + case IYM2612DataSource::DACData: + return dataValue.SetValue(GetDACData(AccessTarget().AccessLatest())); + case IYM2612DataSource::DACEnabled: + return dataValue.SetValue(GetDACEnabled(AccessTarget().AccessLatest())); + case IYM2612DataSource::DetuneData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetDetuneData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::MultipleData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetMultipleData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::TotalLevelData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetTotalLevelData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::KeyScaleData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetKeyScaleData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AttackRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetAttackRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AmplitudeModulationEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetAmplitudeModulationEnabled(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::DecayRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetDecayRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SustainRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSustainRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SustainLevelData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSustainLevelData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::ReleaseRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetReleaseRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGEnabled(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGAttack:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGAttack(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGAlternate:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGAlternate(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGHold:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGHold(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FrequencyData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetFrequencyData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::BlockData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetBlockData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FrequencyDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(GetFrequencyDataChannel3(operatorDataContext.operatorNo, AccessTarget().AccessLatest()));} + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(GetBlockDataChannel3(operatorDataContext.operatorNo, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FeedbackData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetFeedbackData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AlgorithmData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetAlgorithmData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::OutputLeft:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetOutputLeft(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::OutputRight:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetOutputRight(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetAMSData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetPMSData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(operatorData[operatorDataContext.channelNo][operatorDataContext.operatorNo].keyon);} + case IYM2612DataSource::StatusRegister: + return dataValue.SetValue(status.GetData()); + case IYM2612DataSource::BusyFlag: + return dataValue.SetValue(GetBusyFlag()); + case IYM2612DataSource::TimerBOverflow: + return dataValue.SetValue(GetTimerBOverflow()); + case IYM2612DataSource::TimerAOverflow: + return dataValue.SetValue(GetTimerAOverflow()); + case IYM2612DataSource::TimerACurrentCounter: + return dataValue.SetValue(timerACounter); + case IYM2612DataSource::TimerBCurrentCounter: + return dataValue.SetValue(timerBCounter); + case IYM2612DataSource::ExternalClockRate: + return dataValue.SetValue(externalClockRate); + case IYM2612DataSource::FMClockDivider: + return dataValue.SetValue(fmClockDivider); + case IYM2612DataSource::EGClockDivider: + return dataValue.SetValue(egClockDivider); + case IYM2612DataSource::OutputClockDivider: + return dataValue.SetValue(outputClockDivider); + case IYM2612DataSource::TimerAClockDivider: + return dataValue.SetValue(timerAClockDivider); + case IYM2612DataSource::TimerBClockDivider: + return dataValue.SetValue(timerBClockDivider); + case IYM2612DataSource::AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingEnabled); + case IYM2612DataSource::ChannelAudioLoggingEnabled:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + return dataValue.SetValue(wavLoggingChannelEnabled[channelDataContext.channelNo]);} + case IYM2612DataSource::OperatorAudioLoggingEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(wavLoggingOperatorEnabled[operatorDataContext.channelNo][operatorDataContext.operatorNo]);} + case IYM2612DataSource::AudioLoggingPath: + return dataValue.SetValue(wavLoggingPath); + case IYM2612DataSource::ChannelAudioLoggingPath:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + return dataValue.SetValue(wavLoggingChannelPath[channelDataContext.channelNo]);} + case IYM2612DataSource::OperatorAudioLoggingPath:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(wavLoggingOperatorPath[operatorDataContext.channelNo][operatorDataContext.operatorNo]);} + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) +{ + ApplyGenericDataValueLimitSettings(dataID, dataValue); + IGenericAccessDataValue::DataType dataType = dataValue.GetType(); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + Data registerData(8, dataValueAsUInt.GetValue()); + std::unique_lock lock(accessMutex); + RegisterSpecialUpdateFunction(registerDataContext.registerNo, registerData, timersLastUpdateTime, GetDeviceContext(), 0); + SetRegisterData(registerDataContext.registerNo, registerData, AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TestData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTestData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::LFOEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetLFOEnabled(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::LFOData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetLFOData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerAData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTimerAData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + timerAInitialCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTimerBData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + timerBInitialCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::CH3Mode:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetCH3Mode(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerBReset:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBReset(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerAReset:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAReset(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerBEnable:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBEnable(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerBEnable = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerAEnable:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAEnable(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerAEnable = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerBLoad:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBLoad(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerBLoad = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerALoad:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerALoad(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerALoad = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::DACData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetDACData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DACEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetDACEnabled(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DetuneData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetDetuneData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::MultipleData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetMultipleData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TotalLevelData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetTotalLevelData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::KeyScaleData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetKeyScaleData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AttackRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetAttackRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AmplitudeModulationEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetAmplitudeModulationEnabled(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DecayRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetDecayRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SustainRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSustainRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SustainLevelData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSustainLevelData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::ReleaseRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetReleaseRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGEnabled(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGAttack:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGAttack(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGAlternate:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGAlternate(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGHold:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGHold(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FrequencyData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(operatorDataContext.channelNo); + SetFrequencyData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::BlockData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(operatorDataContext.channelNo); + SetBlockData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FrequencyDataChannel3:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetFrequencyDataChannel3(operatorDataContext.operatorNo, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::BlockDataChannel3:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetBlockDataChannel3(operatorDataContext.operatorNo, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FeedbackData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetFeedbackData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AlgorithmData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetAlgorithmData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::OutputLeft:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetOutputLeft(channelAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::OutputRight:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetOutputRight(channelAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AMSData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetAMSData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::PMSData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetPMSData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::KeyState:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + operatorData[operatorDataContext.channelNo][operatorDataContext.operatorNo].keyon = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::StatusRegister:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + status = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::BusyFlag:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetBusyFlag(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerBOverflow:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBOverflow(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerAOverflow:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAOverflow(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerACurrentCounter:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerACounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBCurrentCounter:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerBCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::ExternalClockRate:{ + if(dataType != IGenericAccessDataValue::DataType::Double) return false; + IGenericAccessDataValueDouble& dataValueAsDouble = (IGenericAccessDataValueDouble&)dataValue; + externalClockRate = dataValueAsDouble.GetValue(); + return true;} + case IYM2612DataSource::FMClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + fmClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::EGClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + egClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::OutputClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + outputClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerAClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerAClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerBClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::AudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetAudioLoggingEnabled(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::ChannelAudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + SetChannelAudioLoggingEnabled(channelDataContext.channelNo, dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::OperatorAudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetOperatorAudioLoggingEnabled(operatorDataContext.channelNo, operatorDataContext.operatorNo, dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::AudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + wavLoggingPath = dataValueAsFilePath.GetValue(); + return true;} + case IYM2612DataSource::ChannelAudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + wavLoggingChannelPath[channelDataContext.channelNo] = dataValueAsFilePath.GetValue(); + return true;} + case IYM2612DataSource::OperatorAudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + wavLoggingOperatorPath[operatorDataContext.channelNo][operatorDataContext.operatorNo] = dataValueAsFilePath.GetValue(); + return true;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Data locking functions +//---------------------------------------------------------------------------------------- +bool YM2612::GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const +{ + std::unique_lock lock(registerLockMutex); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + return rawRegisterLocking[registerDataContext.registerNo];} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return keyStateLocking[operatorDataContext.channelNo][operatorDataContext.operatorNo];} + case IYM2612DataSource::TestData: + case IYM2612DataSource::LFOEnabled: + case IYM2612DataSource::LFOData: + case IYM2612DataSource::CH3Mode: + case IYM2612DataSource::DACData: + case IYM2612DataSource::DACEnabled: + case IYM2612DataSource::TimerBReset: + case IYM2612DataSource::TimerAReset:{ + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + return true; + } + break;} + case IYM2612DataSource::TimerBEnable: + return timerBStateLocking.enable; + case IYM2612DataSource::TimerAEnable: + return timerAStateLocking.enable; + case IYM2612DataSource::TimerBLoad: + return timerBStateLocking.load; + case IYM2612DataSource::TimerALoad: + return timerAStateLocking.load; + case IYM2612DataSource::TimerBData: + return timerBStateLocking.rate; + case IYM2612DataSource::TimerAData: + return timerAStateLocking.rate; + case IYM2612DataSource::TimerBCurrentCounter: + return timerBStateLocking.counter; + case IYM2612DataSource::TimerACurrentCounter: + return timerAStateLocking.counter; + case IYM2612DataSource::TimerBOverflow: + return timerBStateLocking.overflow; + case IYM2612DataSource::TimerAOverflow: + return timerAStateLocking.overflow; + case IYM2612DataSource::FeedbackData: + case IYM2612DataSource::AlgorithmData: + case IYM2612DataSource::OutputLeft: + case IYM2612DataSource::OutputRight: + case IYM2612DataSource::AMSData: + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + if(i->channelDataContext.channelNo == channelDataContext.channelNo) + { + return true; + } + } + } + break;} + case IYM2612DataSource::DetuneData: + case IYM2612DataSource::MultipleData: + case IYM2612DataSource::TotalLevelData: + case IYM2612DataSource::KeyScaleData: + case IYM2612DataSource::AttackRateData: + case IYM2612DataSource::AmplitudeModulationEnabled: + case IYM2612DataSource::DecayRateData: + case IYM2612DataSource::SustainRateData: + case IYM2612DataSource::SustainLevelData: + case IYM2612DataSource::ReleaseRateData: + case IYM2612DataSource::SSGData: + case IYM2612DataSource::SSGEnabled: + case IYM2612DataSource::SSGAttack: + case IYM2612DataSource::SSGAlternate: + case IYM2612DataSource::SSGHold: + case IYM2612DataSource::FrequencyData: + case IYM2612DataSource::BlockData: + case IYM2612DataSource::FrequencyDataChannel3: + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + if((i->operatorDataContext.channelNo == operatorDataContext.channelNo) && (i->operatorDataContext.operatorNo == operatorDataContext.operatorNo)) + { + return true; + } + } + } + break;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state) +{ + std::unique_lock lock2(registerLockMutex); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + rawRegisterLocking[registerDataContext.registerNo] = state; + return true;} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + keyStateLocking[operatorDataContext.channelNo][operatorDataContext.operatorNo] = state; + return true;} + case IYM2612DataSource::TestData: + case IYM2612DataSource::LFOEnabled: + case IYM2612DataSource::LFOData: + case IYM2612DataSource::CH3Mode: + case IYM2612DataSource::TimerBReset: + case IYM2612DataSource::TimerAReset: + case IYM2612DataSource::DACData: + case IYM2612DataSource::DACEnabled:{ + if(!state) + { + lockedRegisterState.erase(dataID); + } + else + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, 0, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, lockedDataValue)); + } + return true;} + case IYM2612DataSource::TimerBEnable: + timerBStateLocking.enable = state; + return true; + case IYM2612DataSource::TimerAEnable: + timerAStateLocking.enable = state; + return true; + case IYM2612DataSource::TimerBLoad: + timerBStateLocking.load = state; + return true; + case IYM2612DataSource::TimerALoad: + timerAStateLocking.load = state; + return true; + case IYM2612DataSource::TimerBData: + timerBStateLocking.rate = state; + return true; + case IYM2612DataSource::TimerAData: + timerAStateLocking.rate = state; + return true; + case IYM2612DataSource::TimerBCurrentCounter: + timerBStateLocking.counter = state; + return true; + case IYM2612DataSource::TimerACurrentCounter: + timerAStateLocking.counter = state; + return true; + case IYM2612DataSource::TimerBOverflow: + timerBStateLocking.overflow = state; + return true; + case IYM2612DataSource::TimerAOverflow: + timerAStateLocking.overflow = state; + return true; + case IYM2612DataSource::FeedbackData: + case IYM2612DataSource::AlgorithmData: + case IYM2612DataSource::OutputLeft: + case IYM2612DataSource::OutputRight: + case IYM2612DataSource::AMSData: + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + std::list& lockedRegisterList = lockedRegisterState[dataID]; + std::list::iterator lockedRegisterListIterator = lockedRegisterList.begin(); + while(lockedRegisterListIterator != lockedRegisterList.end()) + { + if(lockedRegisterListIterator->channelDataContext.channelNo == channelDataContext.channelNo) + { + lockedRegisterList.erase(lockedRegisterListIterator); + if(lockedRegisterList.empty()) + { + lockedRegisterState.erase(dataID); + } + break; + } + ++lockedRegisterListIterator; + } + if(state) + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, &channelDataContext, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, channelDataContext, lockedDataValue)); + } + return true;} + case IYM2612DataSource::DetuneData: + case IYM2612DataSource::MultipleData: + case IYM2612DataSource::TotalLevelData: + case IYM2612DataSource::KeyScaleData: + case IYM2612DataSource::AttackRateData: + case IYM2612DataSource::AmplitudeModulationEnabled: + case IYM2612DataSource::DecayRateData: + case IYM2612DataSource::SustainRateData: + case IYM2612DataSource::SustainLevelData: + case IYM2612DataSource::ReleaseRateData: + case IYM2612DataSource::SSGData: + case IYM2612DataSource::SSGEnabled: + case IYM2612DataSource::SSGAttack: + case IYM2612DataSource::SSGAlternate: + case IYM2612DataSource::SSGHold: + case IYM2612DataSource::FrequencyData: + case IYM2612DataSource::BlockData: + case IYM2612DataSource::FrequencyDataChannel3: + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + std::list& lockedRegisterList = lockedRegisterState[dataID]; + std::list::iterator lockedRegisterListIterator = lockedRegisterList.begin(); + while(lockedRegisterListIterator != lockedRegisterList.end()) + { + if((lockedRegisterListIterator->operatorDataContext.channelNo == operatorDataContext.channelNo) && (lockedRegisterListIterator->operatorDataContext.operatorNo == operatorDataContext.operatorNo)) + { + lockedRegisterList.erase(lockedRegisterListIterator); + if(lockedRegisterList.empty()) + { + lockedRegisterState.erase(dataID); + } + break; + } + ++lockedRegisterListIterator; + } + if(state) + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, &operatorDataContext, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, operatorDataContext, lockedDataValue)); + } + return true;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Audio logging functions +//---------------------------------------------------------------------------------------- +void YM2612::SetAudioLoggingEnabled(bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLog, wavLoggingPath, wavLoggingEnabled, state, 2, 16, (unsigned int)fmClock); + wavLoggingEnabled = state; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLogChannel[channelNo], wavLoggingChannelPath[channelNo], wavLoggingChannelEnabled[channelNo], state, 2, 16, (unsigned int)fmClock); + wavLoggingChannelEnabled[channelNo] = state; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLogOperator[channelNo][operatorNo], wavLoggingOperatorPath[channelNo][operatorNo], wavLoggingOperatorEnabled[channelNo][operatorNo], state, 1, 16, (unsigned int)fmClock); + wavLoggingOperatorEnabled[channelNo][operatorNo] = state; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::ToggleLoggingEnabledState(Stream::WAVFile& wavFile, const std::wstring& fileName, bool currentState, bool newState, unsigned int channelCount, unsigned int bitsPerSample, unsigned int samplesPerSec) +{ + if(newState != currentState) + { + if(newState) + { + wavFile.SetDataFormat(channelCount, bitsPerSample, samplesPerSec); + wavFile.Open(fileName, Stream::WAVFile::OpenMode::WriteOnly, Stream::WAVFile::CreateMode::Create); + } + else + { + wavFile.Close(); + } + } + return newState; +} diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e3b1381acf6014964fc2c9d2397ff008d13d1e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/YM2612.h @@ -0,0 +1,493 @@ +/*--------------------------------------------------------------------------------------*\ +Description: +This core emulates the Yamaha YM2612(OPN2) FM synthesizer chip. Extensive hardware testing +has been done on the YM2612 in order to confirm the behaviour of the real chip, and this +emulation core has been built using those results. + +Things to do: +-Test and implement the saved results within operator circuits present in the MAME core. +-Investigate new information on the embedded DAC and implement more accurate handling of +the DAC stage. +-Revamp the way CSM overflow events are tracked. We need to record overflow events using +a cycle count rather than a timeslice value. Rounding error can introduce some 1-cycle +errors in CSM timing events in the current implementation. +-Make the render process cycle-accurate. Rather than advancing by time steps, we need to +advance by cycles. +-Try toggling SSG-EG mode off when the output is currently inverted in an SSG-EG pattern, +and see if the output inversion is also immediately disabled. +-Figure out what we're going to do with the multiplexed output stream from this chip +long-term. Do we keep it around? +-Research and implement full support for all the behaviour of the YM2612 test register +-Implement support for the busy flag. We will need to perform tests on the actual waiting +times the chip requires. The integrated YM2612 will also need to be tested in case its +waiting times are different. Note also that the DAC registers in particular must be +tested. The DAC data is the register which is most likely to be hammered, and we have no +documentation on its waiting times whatsoever, as the YM2608 didn't have it. It is likely +however that the waiting time for a DAC data write is the same as changing the left/right +flags. + +Debug options to add: +-Create a panel where each operator and channel can be either muted or disabled. Muted +only prevents sound being output to the accumulator while still allowing modulators to +modulate other operators, while disabling an operator forces it to always output 0. Also +add options to disable DAC, and disable output to either speaker for channel and master +outputs. Suggest rather than muted and disabled, simply call them disable as carrier and +disable as modulator. + +References: +-YM2608(OPNA) Application Manual, Yamaha +-Genesis Sound Software Manual, Sega Enterprises, 1992, scans by antime +-MAME Envelope Generator Implementation, Jarek Burczynski +-YM2151 Users Manual, Yamaha +-YM2413 Application Manual, Yamaha, scans by Ricardo Bittencourt +-Y8950 Application Manual, Yamaha, scans by Albert Beevendorp +-YM2203(OPN) Datasheet, Yamaha +-YM3015 Datasheet, Yamaha LSI +-YM3016 Datasheet, Yamaha LSI +-YM2612 Test Register Notes, Charles MacDonald +-YM2151 Test Register Notes, Jarek Burczynski +\*--------------------------------------------------------------------------------------*/ +#include "IYM2612.h" +#ifndef __YM2612_H__ +#define __YM2612_H__ +#include "DeviceInterface/DeviceInterface.pkg" +#include +#include +#include +#include +#include +#include +#include +#include "Device/Device.pkg" +#include "TimedBuffers/TimedBuffers.pkg" +#include "AudioStream/AudioStream.pkg" +#include "Stream/Stream.pkg" + +class YM2612 :public Device, public GenericAccessBase +{ +public: + //Constructors + YM2612(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID); + + //Interface version functions + virtual unsigned int GetIYM2612Version() const; + + //Initialization functions + virtual bool BuildDevice(); + virtual bool ValidateDevice(); + virtual void Initialize(); + void Reset(double accessTime); + + //Reference functions + virtual bool AddReference(const MarshalSupport::Marshal::In& referenceName, IBusInterface* target); + virtual void RemoveReference(IBusInterface* target); + + //Line functions + virtual unsigned int GetLineID(const MarshalSupport::Marshal::In& lineName) const; + virtual MarshalSupport::Marshal::Ret GetLineName(unsigned int lineID) const; + virtual unsigned int GetLineWidth(unsigned int lineID) const; + virtual void SetLineState(unsigned int targetLine, const Data& lineData, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual void AssertCurrentOutputLineState() const; + virtual void NegateCurrentOutputLineState() const; + + //Clock source functions + virtual unsigned int GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const; + virtual MarshalSupport::Marshal::Ret GetClockSourceName(unsigned int clockSourceID) const; + virtual void SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual void TransparentSetClockSourceRate(unsigned int clockInput, double clockRate); + + //Execute functions + virtual void BeginExecution(); + virtual void SuspendExecution(); + virtual UpdateMethod GetUpdateMethod() const; + virtual bool SendNotifyUpcomingTimeslice() const; + virtual void NotifyUpcomingTimeslice(double nanoseconds); + virtual void ExecuteTimeslice(double nanoseconds); + virtual void ExecuteRollback(); + virtual void ExecuteCommit(); + + //Memory interface functions + virtual IBusInterface::AccessResult ReadInterface(unsigned int interfaceNumber, unsigned int location, Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual IBusInterface::AccessResult WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext); + + //Savestate functions + virtual void LoadState(IHierarchicalStorageNode& node); + virtual void SaveState(IHierarchicalStorageNode& node) const; + virtual void LoadDebuggerState(IHierarchicalStorageNode& node); + virtual void SaveDebuggerState(IHierarchicalStorageNode& node) const; + + //Data read/write functions + using IGenericAccess::ReadGenericData; + using IGenericAccess::WriteGenericData; + virtual bool ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const; + virtual bool WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue); + + //Data locking functions + virtual bool GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const; + virtual bool SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state); + +private: + //Enumerations + enum class LineID; + enum class ClockID; + enum class AccessContext; + + //Structures + struct OperatorData + { + enum ADSRPhase + { + ADSR_ATTACK, + ADSR_DECAY, + ADSR_SUSTAIN, + ADSR_RELEASE + }; + + OperatorData() + :attenuation(10), phaseCounter(20) + {} + + Data attenuation; //10-bit + Data phaseCounter; //20-bit + ADSRPhase phase; + bool keyon; + bool csmKeyOn; + bool keyonPrevious; + bool ssgOutputInverted; + }; + struct TimerStateLocking + { + bool rate; + bool counter; + bool load; + bool enable; + bool overflow; + }; + struct RegisterLocking + { + RegisterLocking(unsigned int adataID, const std::wstring& alockedValue) + :dataID(adataID), usingChannelDataContext(false), usingOperatorDataContext(false), lockedValue(alockedValue) + {} + RegisterLocking(unsigned int adataID, const ChannelDataContext& achannelDataContext, const std::wstring& alockedValue) + :dataID(adataID), channelDataContext(achannelDataContext), usingChannelDataContext(true), usingOperatorDataContext(false), lockedValue(alockedValue) + {} + RegisterLocking(unsigned int adataID, const OperatorDataContext& aoperatorDataContext, const std::wstring& alockedValue) + :dataID(adataID), operatorDataContext(aoperatorDataContext), usingChannelDataContext(false), usingOperatorDataContext(true), lockedValue(alockedValue) + {} + + const IGenericAccess::DataContext* GetDataContext() const + { + if(usingChannelDataContext) + { + return &channelDataContext; + } + if(usingOperatorDataContext) + { + return &operatorDataContext; + } + return 0; + } + + unsigned int dataID; + bool usingChannelDataContext; + ChannelDataContext channelDataContext; + bool usingOperatorDataContext; + OperatorDataContext operatorDataContext; + const IGenericAccess::DataContext* dataContext; + std::wstring lockedValue; + }; + + //Typedefs + typedef RandomTimeAccessBuffer::AccessTarget AccessTarget; + +private: + //Execute functions + void RenderThread(); + + //General operator functions + void UpdateOperator(unsigned int channelNo, unsigned int operatorNo, bool updateEnvelopeGenerator); + unsigned int CalculateKeyCode(unsigned int block, unsigned int fnumber) const; + + //Phase generator functions + void UpdatePhaseGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset); + unsigned int GetCurrentPhase(unsigned int channelNo, unsigned int operatorNo) const; + unsigned int GetFrequencyData(unsigned int channelNo, unsigned int operatorNo, unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + unsigned int GetBlockData(unsigned int channelNo, unsigned int operatorNo, unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + + //Envelope generator functions + void UpdateEnvelopeGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset); + void SetADSRPhase(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset, OperatorData::ADSRPhase phase); + unsigned int GetOutputAttenuation(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) const; + unsigned int CalculateRate(unsigned int rateData, unsigned int rateKeyScale) const; + unsigned int CalculateRateKeyScale(unsigned int keyScaleData, unsigned int keyCode) const; + unsigned int ConvertTotalLevelToAttenuation(unsigned int totalLevel) const; + unsigned int ConvertSustainLevelToAttenuation(unsigned int sustainLevel) const; + + //Operator unit functions + unsigned int InversePow2(unsigned int num) const; + int CalculateOperator(unsigned int phase, int phaseModulation, unsigned int attenuation) const; + + //Memory interface functions + void RegisterSpecialUpdateFunction(unsigned int location, const Data& data, double accessTime, IDeviceContext* caller, unsigned int accessContext); + bool CheckForLatchedWrite(unsigned int location, const Data& data, double accessTime); + + //Timer management functions + void UpdateTimers(double timesliceProgress); + + //Raw register functions + inline Data GetRegisterData(unsigned int location, const AccessTarget& accessTarget) const; + inline void SetRegisterData(unsigned int location, const Data& data, const AccessTarget& accessTarget); + inline unsigned int GetChannelBlockAddressOffset(unsigned int channelNo) const; + inline unsigned int GetOperatorBlockAddressOffset(unsigned int channelNo, unsigned int operatorNo) const; + inline unsigned int GetAddressChannel3FrequencyBlock1(unsigned int operatorNo) const; + inline unsigned int GetAddressChannel3FrequencyBlock2(unsigned int operatorNo) const; + + //Common FM register functions + inline unsigned int GetTestData(const AccessTarget& accessTarget) const; //21H + inline void SetTestData(unsigned int data, const AccessTarget& accessTarget); + inline bool GetLFOEnabled(const AccessTarget& accessTarget) const; //22H + inline void SetLFOEnabled(bool data, const AccessTarget& accessTarget); + inline unsigned int GetLFOData(const AccessTarget& accessTarget) const; + inline void SetLFOData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTimerAData(const AccessTarget& accessTarget) const; //24H-25H + inline void SetTimerAData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTimerBData(const AccessTarget& accessTarget) const; //26H + inline void SetTimerBData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetCH3Mode(const AccessTarget& accessTarget) const; //27H + inline void SetCH3Mode(unsigned int data, const AccessTarget& accessTarget); + inline bool GetTimerBReset(const AccessTarget& accessTarget) const; + inline void SetTimerBReset(bool data, const AccessTarget& accessTarget); + inline bool GetTimerAReset(const AccessTarget& accessTarget) const; + inline void SetTimerAReset(bool data, const AccessTarget& accessTarget); + inline bool GetTimerBEnable(const AccessTarget& accessTarget) const; + inline void SetTimerBEnable(bool data, const AccessTarget& accessTarget); + inline bool GetTimerAEnable(const AccessTarget& accessTarget) const; + inline void SetTimerAEnable(bool data, const AccessTarget& accessTarget); + inline bool GetTimerBLoad(const AccessTarget& accessTarget) const; + inline void SetTimerBLoad(bool data, const AccessTarget& accessTarget); + inline bool GetTimerALoad(const AccessTarget& accessTarget) const; + inline void SetTimerALoad(bool data, const AccessTarget& accessTarget); + inline unsigned int GetDACData(const AccessTarget& accessTarget) const; //2AH + inline void SetDACData(unsigned int data, const AccessTarget& accessTarget); + inline bool GetDACEnabled(const AccessTarget& accessTarget) const; //2BH + inline void SetDACEnabled(bool data, const AccessTarget& accessTarget); + + //FM operator register functions + inline unsigned int GetDetuneData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //30H-3FH + inline void SetDetuneData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetMultipleData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetMultipleData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTotalLevelData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //40H-4FH + inline void SetTotalLevelData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetKeyScaleData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //50H-5FH + inline void SetKeyScaleData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetAttackRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAttackRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetAmplitudeModulationEnabled(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //60H-6FH + inline void SetAmplitudeModulationEnabled(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline unsigned int GetDecayRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetDecayRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSustainRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //70H-7FH + inline void SetSustainRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSustainLevelData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //80H-8FH + inline void SetSustainLevelData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetReleaseRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetReleaseRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSSGData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //90H-9FH + inline void SetSSGData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetSSGEnabled(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGEnabled(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGAttack(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGAttack(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGAlternate(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGAlternate(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGHold(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGHold(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + + //FM channel register functions + inline unsigned int GetFrequencyData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //A0H-A7H + inline void SetFrequencyData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetBlockData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetBlockData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetFrequencyDataChannel3(unsigned int operatorNo, const AccessTarget& accessTarget) const; //A8H-AFH + inline void SetFrequencyDataChannel3(unsigned int operatorNo, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetBlockDataChannel3(unsigned int operatorNo, const AccessTarget& accessTarget) const; + inline void SetBlockDataChannel3(unsigned int operatorNo, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetFeedbackData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //B0H-B3H + inline void SetFeedbackData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetAlgorithmData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAlgorithmData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetOutputLeft(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //B4H-B7H + inline void SetOutputLeft(unsigned int channelAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetOutputRight(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetOutputRight(unsigned int channelAddressOffset, bool data, const AccessTarget& accessTarget); + inline unsigned int GetAMSData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAMSData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetPMSData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetPMSData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + + //Status register functions + inline Data GetStatusRegister() const; + inline void SetStatusRegister(unsigned int adata); + inline bool GetBusyFlag() const; + inline void SetBusyFlag(bool astate); + inline bool GetTimerBOverflow() const; + inline void SetTimerBOverflow(bool astate); + inline bool GetTimerAOverflow() const; + inline void SetTimerAOverflow(bool astate); + + //Audio logging functions + void SetAudioLoggingEnabled(bool state); + void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state); + void SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool state); + static bool ToggleLoggingEnabledState(Stream::WAVFile& wavFile, const std::wstring& fileName, bool currentState, bool newState, unsigned int channelCount, unsigned int bitsPerSample, unsigned int samplesPerSec); + +private: + //Constants + static const unsigned int channelAddressOffsets[channelCount]; + static const unsigned int operatorAddressOffsets[channelCount][operatorCount]; + static const unsigned int channel3OperatorFrequencyAddressOffsets[2][operatorCount]; + + //Envelope generator constants + static const unsigned int rateBitCount = 6; + static const unsigned int attenuationBitCount = 10; + static const unsigned int fnumDataBitCount = 11; + static const unsigned int phaseGeneratorOutputBitCount = 10; + static const unsigned int keyCodeBitCount = 5; + static const unsigned int counterShiftTable[1 << rateBitCount]; + static const unsigned int attenuationIncrementTable[1 << rateBitCount][8]; + static const unsigned int pmsBitCount = 3; + static const unsigned int phaseModIndexBitCount = 5; + static const unsigned int phaseModIncrementTable[1 << pmsBitCount][1 << (phaseModIndexBitCount - 2)]; + static const unsigned int detuneBitCount = 3; + static const unsigned int detunePhaseIncrementTable[1 << keyCodeBitCount][1 << (detuneBitCount - 1)]; + + //Operator unit constants + static const unsigned int phaseBitCount = 10; + static const unsigned int sinTableBitCount = 8; + static const unsigned int powTableBitCount = 8; + static const unsigned int sinTableOutputBitCount = 12; + static const unsigned int powTableOutputBitCount = 11; + static const unsigned int operatorOutputBitCount = 14; + static const unsigned int accumulatorOutputBitCount = 16; + unsigned int sinTable[1 << sinTableBitCount]; + unsigned int powTable[1 << powTableBitCount]; + +private: + //Clock settings + double externalClockRate; + double bexternalClockRate; + unsigned int fmClockDivider; + unsigned int egClockDivider; + unsigned int outputClockDivider; + unsigned int timerAClockDivider; + unsigned int timerBClockDivider; + + //Bus interface + mutable std::mutex lineMutex; + IBusInterface* memoryBus; + volatile bool icLineState; + bool bicLineState; + + //Registers + mutable std::mutex accessMutex; + double lastAccessTime; + RandomTimeAccessBuffer reg; + unsigned int currentReg; + unsigned int bcurrentReg; + Data status; + Data bstatus; + + //Temporary storage for fnum/block register latch behaviour + bool latchedFrequencyDataPending[channelCount]; + std::vector latchedFrequencyData; + bool latchedFrequencyDataPendingCH3[3]; + std::vector latchedFrequencyDataCH3; + bool blatchedFrequencyDataPending[channelCount]; + std::vector blatchedFrequencyData; + bool blatchedFrequencyDataPendingCH3[3]; + std::vector blatchedFrequencyDataCH3; + + //Timer status + double lastTimesliceLength; + double timersLastUpdateTime; + double timersRemainingTime; + double btimersRemainingTime; + unsigned int timerARemainingCycles; + unsigned int timerBRemainingCycles; + unsigned int btimerARemainingCycles; + unsigned int btimerBRemainingCycles; + unsigned int timerACounter; + unsigned int timerBCounter; + unsigned int btimerACounter; + unsigned int btimerBCounter; + unsigned int timerAInitialCounter; + unsigned int timerBInitialCounter; + unsigned int btimerAInitialCounter; + unsigned int btimerBInitialCounter; + bool timerAEnable; + bool timerBEnable; + bool btimerAEnable; + bool btimerBEnable; + bool timerALoad; + bool timerBLoad; + bool btimerALoad; + bool btimerBLoad; + bool irqLineState; + bool birqLineState; + + //This register records the times at which Timer A overflows. It is needed in order to + //implement CSM support. + RandomTimeAccessValue timerAOverflowTimes; + + //Render thread properties + mutable std::mutex renderThreadMutex; + mutable std::mutex timesliceMutex; + std::condition_variable renderThreadUpdate; + std::condition_variable renderThreadStopped; + bool renderThreadActive; + static const unsigned int maxPendingRenderOperationCount = 4; + bool renderThreadLagging; + std::condition_variable renderThreadLaggingStateChange; + unsigned int pendingRenderOperationCount; + std::list::Timeslice> regTimesliceList; + std::list::Timeslice> timerATimesliceList; + std::list::Timeslice> regTimesliceListUncommitted; + std::list::Timeslice> timerATimesliceListUncommitted; + double remainingRenderTime; + int egRemainingRenderCycles; + unsigned int outputSampleRate; + AudioStream outputStream; + std::vector outputBuffer; + + //Render data + unsigned int envelopeCycleCounter; + OperatorData operatorData[channelCount][operatorCount]; + int operatorOutput[channelCount][operatorCount]; + int feedbackBuffer[channelCount][2]; + int cyclesUntilLFOIncrement; + unsigned int currentLFOCounter; + + //Register locking + mutable std::mutex registerLockMutex; + bool keyStateLocking[channelCount][operatorCount]; + bool rawRegisterLocking[registerCountTotal]; + std::map> lockedRegisterState; + TimerStateLocking timerAStateLocking; + TimerStateLocking timerBStateLocking; + + //Wave logging + mutable std::mutex waveLoggingMutex; + bool wavLoggingEnabled; + bool wavLoggingChannelEnabled[channelCount]; + bool wavLoggingOperatorEnabled[channelCount][operatorCount]; + std::wstring wavLoggingPath; + std::wstring wavLoggingChannelPath[channelCount]; + std::wstring wavLoggingOperatorPath[channelCount][operatorCount]; + Stream::WAVFile wavLog; + Stream::WAVFile wavLogChannel[channelCount]; + Stream::WAVFile wavLogOperator[channelCount][operatorCount]; +}; + +#include "YM2612.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92422e9d8c4173af5a069c03fed95944dbbad0ad --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.cpp @@ -0,0 +1,42 @@ +#include "DeviceInterface/DeviceInterface.pkg" +#include "YM2612.h" + +IDevice* GetYM2612(const wchar_t* implementationName, const wchar_t* instanceName, unsigned int moduleID) +{ + return static_cast(new YM2612(implementationName, instanceName, moduleID)); +} + +void DeleteYM2612(IDevice* device) +{ + delete static_cast(device); +} + +#ifdef EX_DLLINTERFACE +extern "C" __declspec(dllexport) unsigned int GetInterfaceVersion() +{ + return EXODUS_INTERFACEVERSION; +} + +extern "C" __declspec(dllexport) bool GetDeviceEntry(unsigned int entryNo, IDeviceInfo& entry) +{ + //Retrieve any required information from the version info table for our plugin + std::wstring copyrightText; + std::wstring commentsText; + HMODULE moduleHandle = NULL; + BOOL getModuleHandleExReturn = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)GetDeviceEntry, &moduleHandle); + if(getModuleHandleExReturn != 0) + { + std::wstring modulePath = GetModuleFilePath(moduleHandle); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_LEGALCOPYRIGHT, copyrightText); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_COMMENTS, commentsText); + } + + switch(entryNo) + { + case 0: + entry.SetDeviceSettings(GetYM2612, DeleteYM2612, L"Audio.YM2612", L"YM2612", 1, copyrightText, commentsText); + return true; + } + return false; +} +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..9e5dd992e0fb2c0307194ec33e0ba86a131d3f78 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/interface.h @@ -0,0 +1,7 @@ +#ifndef __YM2612_INTERFACE_H__ +#define __YM2612_INTERFACE_H__ +#include "DeviceInterface/DeviceInterface.pkg" + +void GetYM2612DeviceInfo(IDeviceInfo& deviceInfo); + +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/resource.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/resource.h new file mode 100644 index 0000000000000000000000000000000000000000..599615316dc96c2283692c18996477e71d1fc688 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/nemesis/YM2612/resource.h @@ -0,0 +1,20 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by YM2612.rc +// +#define IDI_ICON1 101 +#define IDC_EDIT1 1323 +#define IDC_EDIT12 1325 +#define IDC_YM2612_DEBUGGER_CS12 1408 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/common.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/common.vhd new file mode 100644 index 0000000000000000000000000000000000000000..c2422a327827a13a7496ced320a9e1137b83a21e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/common.vhd @@ -0,0 +1,60 @@ +--------======== common.vhd ========-------- +-- Common entities for use with YM2203/YM2612 implementation +-- Copyright (C) 2015 Sauraen +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + + +-- circular_buffer +-- A simple circular buffer, used for most of the YM2612's registers. + +library ieee; +use ieee.std_logic_1164.all; + +entity circular_buffer is + generic ( + DATA_WIDTH: positive := 8; --arbitrary default value + BUFFER_DEPTH: positive := 3; --arbitrary default value + CLEAR_ON_RESET: boolean := false + ); + port ( + clk, rst_bar: in std_logic; + din: in std_logic_vector(DATA_WIDTH-1 downto 0); + dout: out std_logic_vector(DATA_WIDTH-1 downto 0); + load: in std_logic + ); +end entity; + +architecture arch of circular_buffer is + type memtype is array(BUFFER_DEPTH-1 downto 0) of std_logic_vector(DATA_WIDTH-1 downto 0); + signal mem : memtype; +begin + process(clk, rst_bar) is begin + if rst_bar = '0' and CLEAR_ON_RESET then + for i in BUFFER_DEPTH-1 downto 0 loop + mem(i) <= (others => '0'); + end loop; + elsif rising_edge(clk) then + if load = '1' then + mem(BUFFER_DEPTH-1) <= din; + else + mem(BUFFER_DEPTH-1) <= mem(0); + end if; + for i in buffer_depth-2 downto 0 loop + mem(i) <= mem(i+1); + end loop; + dout <= mem(0); + end if; + end process; +end architecture; \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/IYM2612.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/IYM2612.h new file mode 100644 index 0000000000000000000000000000000000000000..c964f2f97e057fc84f3071815cd154fd37e3c837 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/IYM2612.h @@ -0,0 +1,169 @@ +#ifndef __IYM2612_H__ +#define __IYM2612_H__ +#include "GenericAccess/GenericAccess.pkg" +#include + +class IYM2612 :public virtual IGenericAccess +{ +public: + //Constants + static const unsigned int channelCount = 6; + static const unsigned int operatorCount = 4; + static const unsigned int partCount = 2; + static const unsigned int registerCountPerPart = 0x100; + static const unsigned int registerCountTotal = registerCountPerPart * partCount; + + //Enumerations + enum class IYM2612DataSource; + enum Channels :unsigned int; + enum Operators :unsigned int; + + //Structures + struct RegisterDataContext; + struct ChannelDataContext; + struct OperatorDataContext; + +public: + //Interface version functions + static inline unsigned int ThisIYM2612Version() { return 1; } + virtual unsigned int GetIYM2612Version() const = 0; + + //Clock setting functions + inline double GetExternalClockRate() const; + inline void SetExternalClockRate(double adata); + inline unsigned int GetFMClockDivider() const; + inline void SetFMClockDivider(unsigned int adata); + inline unsigned int GetEGClockDivider() const; + inline void SetEGClockDivider(unsigned int adata); + inline unsigned int GetOutputClockDivider() const; + inline void SetOutputClockDivider(unsigned int adata); + inline unsigned int GetTimerAClockDivider() const; + inline void SetTimerAClockDivider(unsigned int adata); + inline unsigned int GetTimerBClockDivider() const; + inline void SetTimerBClockDivider(unsigned int adata); + + //Raw register functions + inline unsigned int GetRegisterData(unsigned int registerNo) const; + inline void SetRegisterData(unsigned int registerNo, unsigned int adata); + + //Common FM register functions + inline unsigned int GetTestData() const; + inline void SetTestData(unsigned int adata); + inline bool GetLFOEnabled() const; + inline void SetLFOEnabled(bool adata); + inline unsigned int GetLFOData() const; + inline void SetLFOData(unsigned int adata); + inline unsigned int GetTimerAData() const; + inline void SetTimerAData(unsigned int adata); + inline unsigned int GetTimerBData() const; + inline void SetTimerBData(unsigned int adata); + inline unsigned int GetCH3Mode() const; + inline void SetCH3Mode(unsigned int adata); + inline bool GetTimerBReset() const; + inline void SetTimerBReset(bool adata); + inline bool GetTimerAReset() const; + inline void SetTimerAReset(bool adata); + inline bool GetTimerBEnable() const; + inline void SetTimerBEnable(bool adata); + inline bool GetTimerAEnable() const; + inline void SetTimerAEnable(bool adata); + inline bool GetTimerBLoad() const; + inline void SetTimerBLoad(bool adata); + inline bool GetTimerALoad() const; + inline void SetTimerALoad(bool adata); + inline unsigned int GetDACData() const; + inline void SetDACData(unsigned int adata); + inline bool GetDACEnabled() const; + inline void SetDACEnabled(bool adata); + + //FM operator register functions + inline unsigned int GetDetuneData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetDetuneData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetMultipleData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetMultipleData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetTotalLevelData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetTotalLevelData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetKeyScaleData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetKeyScaleData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetAttackRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetAttackRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline bool GetAmplitudeModulationEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetAmplitudeModulationEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline unsigned int GetDecayRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetDecayRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSustainRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSustainRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSustainLevelData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSustainLevelData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetReleaseRateData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetReleaseRateData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline unsigned int GetSSGData(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGData(unsigned int channelNo, unsigned int operatorNo, unsigned int adata); + inline bool GetSSGEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGAttack(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGAttack(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGAlternate(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGAlternate(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline bool GetSSGHold(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetSSGHold(unsigned int channelNo, unsigned int operatorNo, bool adata); + + //FM channel register functions + inline unsigned int GetFrequencyData(unsigned int channelNo) const; + inline void SetFrequencyData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetBlockData(unsigned int channelNo) const; + inline void SetBlockData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetFrequencyDataChannel3(unsigned int operatorNo) const; + inline void SetFrequencyDataChannel3(unsigned int operatorNo, unsigned int adata); + inline unsigned int GetBlockDataChannel3(unsigned int operatorNo) const; + inline void SetBlockDataChannel3(unsigned int operatorNo, unsigned int adata); + inline unsigned int GetFeedbackData(unsigned int channelNo) const; + inline void SetFeedbackData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetAlgorithmData(unsigned int channelNo) const; + inline void SetAlgorithmData(unsigned int channelNo, unsigned int adata); + inline bool GetOutputLeft(unsigned int channelNo) const; + inline void SetOutputLeft(unsigned int channelNo, bool adata); + inline bool GetOutputRight(unsigned int channelNo) const; + inline void SetOutputRight(unsigned int channelNo, bool adata); + inline unsigned int GetAMSData(unsigned int channelNo) const; + inline void SetAMSData(unsigned int channelNo, unsigned int adata); + inline unsigned int GetPMSData(unsigned int channelNo) const; + inline void SetPMSData(unsigned int channelNo, unsigned int adata); + + //Key on/off functions + inline bool GetKeyState(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetKeyState(unsigned int channelNo, unsigned int operatorNo, bool adata); + + //Status register functions + inline unsigned int GetStatusRegister() const; + inline void SetStatusRegister(unsigned int adata); + inline bool GetBusyFlag() const; + inline void SetBusyFlag(bool adata); + inline bool GetTimerBOverflow() const; + inline void SetTimerBOverflow(bool adata); + inline bool GetTimerAOverflow() const; + inline void SetTimerAOverflow(bool adata); + + //Timer functions + inline unsigned int GetTimerACurrentCounter() const; + inline void SetTimerACurrentCounter(unsigned int adata); + inline unsigned int GetTimerBCurrentCounter() const; + inline void SetTimerBCurrentCounter(unsigned int adata); + + //Audio logging functions + inline bool IsAudioLoggingEnabled() const; + inline void SetAudioLoggingEnabled(bool adata); + inline bool IsChannelAudioLoggingEnabled(unsigned int channelNo) const; + inline void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool adata); + inline bool IsOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool adata); + inline std::wstring GetAudioLoggingOutputPath() const; + inline void SetAudioLoggingOutputPath(const std::wstring& adata); + inline std::wstring GetChannelAudioLoggingOutputPath(unsigned int channelNo) const; + inline void SetChannelAudioLoggingOutputPath(unsigned int channelNo, const std::wstring& adata); + inline std::wstring GetOperatorAudioLoggingOutputPath(unsigned int channelNo, unsigned int operatorNo) const; + inline void SetOperatorAudioLoggingOutputPath(unsigned int channelNo, unsigned int operatorNo, const std::wstring& adata); +}; + +#include "IYM2612.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48ca25c16c5b4646959ba8437194c19a13cde627 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.cpp @@ -0,0 +1,4061 @@ +#include "YM2612.h" +#include "DataConversion/DataConversion.pkg" +#include +#include +//##DEBUG## +//#include + +//---------------------------------------------------------------------------------------- +//These tables are primarily based on the work of Jarek Burczynski in his OPN envelope +//generator implementation for the MAME core. Some corrections have been made to the +//attenuation increment table following hardware tests. +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::counterShiftTable[1 << rateBitCount] = { + 11, 11, 11, 11, //0-3 (0x00-0x03) + 10, 10, 10, 10, //4-7 (0x04-0x07) + 9, 9, 9, 9, //8-11 (0x08-0x0B) + 8, 8, 8, 8, //12-15 (0x0C-0x0F) + 7, 7, 7, 7, //16-19 (0x10-0x13) + 6, 6, 6, 6, //20-23 (0x14-0x17) + 5, 5, 5, 5, //24-27 (0x18-0x1B) + 4, 4, 4, 4, //28-31 (0x1C-0x1F) + 3, 3, 3, 3, //32-35 (0x20-0x23) + 2, 2, 2, 2, //36-39 (0x24-0x27) + 1, 1, 1, 1, //40-43 (0x28-0x2B) + 0, 0, 0, 0, //44-47 (0x2C-0x2F) + 0, 0, 0, 0, //48-51 (0x30-0x33) + 0, 0, 0, 0, //52-55 (0x34-0x37) + 0, 0, 0, 0, //56-59 (0x38-0x3B) + 0, 0, 0, 0}; //60-63 (0x3C-0x3F) + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::attenuationIncrementTable[1 << rateBitCount][8] = { + {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,1,0,1,0,1,0,1}, {0,1,0,1,0,1,0,1}, //0-3 (0x00-0x03) + {0,1,0,1,0,1,0,1}, {0,1,0,1,0,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,0,1,1,1}, //4-7 (0x04-0x07) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //8-11 (0x08-0x0B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //12-15 (0x0C-0x0F) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //16-19 (0x10-0x13) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //20-23 (0x14-0x17) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //24-27 (0x18-0x1B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //28-31 (0x1C-0x1F) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //32-35 (0x20-0x23) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //36-39 (0x24-0x27) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //40-43 (0x28-0x2B) + {0,1,0,1,0,1,0,1}, {0,1,0,1,1,1,0,1}, {0,1,1,1,0,1,1,1}, {0,1,1,1,1,1,1,1}, //44-47 (0x2C-0x2F) + {1,1,1,1,1,1,1,1}, {1,1,1,2,1,1,1,2}, {1,2,1,2,1,2,1,2}, {1,2,2,2,1,2,2,2}, //48-51 (0x30-0x33) + {2,2,2,2,2,2,2,2}, {2,2,2,4,2,2,2,4}, {2,4,2,4,2,4,2,4}, {2,4,4,4,2,4,4,4}, //52-55 (0x34-0x37) + {4,4,4,4,4,4,4,4}, {4,4,4,8,4,4,4,8}, {4,8,4,8,4,8,4,8}, {4,8,8,8,4,8,8,8}, //56-59 (0x38-0x3B) + {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}, {8,8,8,8,8,8,8,8}}; //60-63 (0x3C-0x3F) + +//---------------------------------------------------------------------------------------- +//This table is derived from the detune table given in the YM2608 Application Manual, +//page 26. The negative inverse of the table (detune 4-7) is generated in code. +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::detunePhaseIncrementTable[1 << keyCodeBitCount][1 << (detuneBitCount - 1)] = { +// Detune Key-Code +// 0 1 2 3 + {0, 0, 1, 2}, //0 (0x00) + {0, 0, 1, 2}, //1 (0x01) + {0, 0, 1, 2}, //2 (0x02) + {0, 0, 1, 2}, //3 (0x03) + {0, 1, 2, 2}, //4 (0x04) + {0, 1, 2, 3}, //5 (0x05) + {0, 1, 2, 3}, //6 (0x06) + {0, 1, 2, 3}, //7 (0x07) + {0, 1, 2, 4}, //8 (0x08) + {0, 1, 3, 4}, //9 (0x09) + {0, 1, 3, 4}, //10 (0x0A) + {0, 1, 3, 5}, //11 (0x0B) + {0, 2, 4, 5}, //12 (0x0C) + {0, 2, 4, 6}, //13 (0x0D) + {0, 2, 4, 6}, //14 (0x0E) + {0, 2, 5, 7}, //15 (0x0F) + {0, 2, 5, 8}, //16 (0x10) + {0, 3, 6, 8}, //17 (0x11) + {0, 3, 6, 9}, //18 (0x12) + {0, 3, 7,10}, //19 (0x13) + {0, 4, 8,11}, //20 (0x14) + {0, 4, 8,12}, //21 (0x15) + {0, 4, 9,13}, //22 (0x16) + {0, 5,10,14}, //23 (0x17) + {0, 5,11,16}, //24 (0x18) + {0, 6,12,17}, //25 (0x19) + {0, 6,13,19}, //26 (0x1A) + {0, 7,14,20}, //27 (0x1B) + {0, 8,16,22}, //28 (0x1C) + {0, 8,16,22}, //29 (0x1D) + {0, 8,16,22}, //30 (0x1E) + {0, 8,16,22}}; //31 (0x1F) + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::phaseModIncrementTable[1 << pmsBitCount][1 << (phaseModIndexBitCount - 2)] = { + {0, 0, 0, 0, 0, 0, 0, 0}, //0 + {0, 0, 0, 0, 1, 1, 1, 1}, //1 + {0, 0, 0, 1, 1, 1, 2, 2}, //2 + {0, 0, 1, 1, 2, 2, 3, 3}, //3 + {0, 0, 1, 2, 2, 2, 3, 4}, //4 + {0, 0, 2, 3, 4, 4, 5, 6}, //5 + {0, 0, 4, 6, 8, 8,10,12}, //6 + {0, 0, 8,12,16,16,20,24}}; //7 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::channelAddressOffsets[channelCount] = { + 0, //Channel 1 + 1, //Channel 2 + 2, //Channel 3 + registerCountPerPart + 0, //Channel 4 + registerCountPerPart + 1, //Channel 5 + registerCountPerPart + 2}; //Channel 6 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::operatorAddressOffsets[channelCount][operatorCount] = { + {channelAddressOffsets[0] + 0x0, channelAddressOffsets[0] + 0x8, channelAddressOffsets[0] + 0x4, channelAddressOffsets[0] + 0xC}, //Channel 1 + {channelAddressOffsets[1] + 0x0, channelAddressOffsets[1] + 0x8, channelAddressOffsets[1] + 0x4, channelAddressOffsets[1] + 0xC}, //Channel 2 + {channelAddressOffsets[2] + 0x0, channelAddressOffsets[2] + 0x8, channelAddressOffsets[2] + 0x4, channelAddressOffsets[2] + 0xC}, //Channel 3 + {channelAddressOffsets[3] + 0x0, channelAddressOffsets[3] + 0x8, channelAddressOffsets[3] + 0x4, channelAddressOffsets[3] + 0xC}, //Channel 4 + {channelAddressOffsets[4] + 0x0, channelAddressOffsets[4] + 0x8, channelAddressOffsets[4] + 0x4, channelAddressOffsets[4] + 0xC}, //Channel 5 + {channelAddressOffsets[5] + 0x0, channelAddressOffsets[5] + 0x8, channelAddressOffsets[5] + 0x4, channelAddressOffsets[5] + 0xC}}; //Channel 6 + +//---------------------------------------------------------------------------------------- +const unsigned int YM2612::channel3OperatorFrequencyAddressOffsets[2][operatorCount] = { + {0xA9, 0xAA, 0xA8, 0xA2}, + {0xAD, 0xAE, 0xAC, 0xA6}}; + +//---------------------------------------------------------------------------------------- +//Constructors +//---------------------------------------------------------------------------------------- +YM2612::YM2612(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID) +:Device(aimplementationName, ainstanceName, amoduleID), +status(8), bstatus(8), reg(registerCountTotal, false, Data(8)), +latchedFrequencyData(channelCount, Data(8)), blatchedFrequencyData(channelCount, Data(8)), +latchedFrequencyDataCH3(3, Data(8)), blatchedFrequencyDataCH3(3, Data(8)), +timerAOverflowTimes(false) +{ + //Bus interface + memoryBus = 0; + icLineState = false; + + //Set the default clock rate parameters + externalClockRate = 0; + fmClockDivider = 6; + egClockDivider = 3; + outputClockDivider = channelCount * operatorCount; //24 + timerAClockDivider = 1; + timerBClockDivider = 16; + + //Initialize the audio output stream + outputSampleRate = 48000; //44100; + outputStream.Open(2, 16, outputSampleRate, outputSampleRate/4, outputSampleRate/20); + + //Initialize the raw register locking state + for(unsigned int registerNo = 0; registerNo < registerCountTotal; ++registerNo) + { + rawRegisterLocking[registerNo] = false; + } + + //Initialize the key locking state + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + keyStateLocking[channelNo][operatorNo] = false; + } + } + + //Initialize the timer locking state + timerAStateLocking.load = false; + timerAStateLocking.enable = false; + timerAStateLocking.overflow = false; + timerAStateLocking.rate = false; + timerAStateLocking.counter = false; + timerBStateLocking.load = false; + timerBStateLocking.enable = false; + timerBStateLocking.overflow = false; + timerBStateLocking.rate = false; + timerBStateLocking.counter = false; +} + +//---------------------------------------------------------------------------------------- +//Interface version functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetIYM2612Version() const +{ + return ThisIYM2612Version(); +} + +//---------------------------------------------------------------------------------------- +//Initialization functions +//---------------------------------------------------------------------------------------- +bool YM2612::BuildDevice() +{ + //Build the sin table. This table has been tested and confirmed to be 100% identical + //to the one in the real chip, by reading the internal operator output using the test + //register. + for(unsigned int i = 0; i < (1 << sinTableBitCount); ++i) + { + //Calculate the normalized phase value for the input into the sine table. Note + //that this is calculated as a normalized result from 0.0-1.0 where 0 is not + //reached, because the phase is calculated as if it was a 9-bit index with the + //LSB fixed to 1. This was done so that the sine table would be more accurate + //when it was "mirrored" to create the negative oscillation of the wave. It's + //also convenient we don't have to worry about a phase of 0, because 0 is an + //invalid input for a log function, which we need to use below. + double phaseNormalized = ((double)((i << 1) + 1) / (1 << (sinTableBitCount + 1))); + + //Calculate the pure sine value for the input. Note that we only build a sine + //table for a quarter of the full oscillation (0-PI/2), since the upper two bits + //of the full phase are extracted by the external circuit. + const double pi = 3.14159265358979323846; + double sinResultNormalized = sin(phaseNormalized * (pi / 2)); + + //Convert the sine result from a linear representation of volume, to a + //logarithmic representation of attenuation. The YM2612 stores values in the sine + //table in this form because logarithms simplify multiplication down to addition, + //and this allowed them to attenuate the sine result by the envelope generator + //output simply by adding the two numbers together. + double sinResultAsAttenuation = -log(sinResultNormalized) / log(2.0); + //The division by log(2) is required because the log function is base 10, but the + //YM2612 uses a base 2 logarithmic value. Dividing the base 10 log result by + //log10(2) will convert the result to a base 2 logarithmic value, which can then + //be converted back to a linear value by a pow2 function. In other words: + //2^(log10(x)/log10(2)) = 2^log2(x) = x + //If there was a native log2() function provided we could use that instead. + + //Convert the attenuation value to a rounded 12-bit result in 4.8 fixed point + //format. + const unsigned int fixedBitCount = 8; + unsigned int sinResult = (unsigned int)((sinResultAsAttenuation * (1 << fixedBitCount)) + 0.5); + + //Write the result to the table + sinTable[i] = sinResult; + } + + //Build the pow table. This table has been tested and confirmed to be 100% identical + //to the one in the real chip, by reading the internal operator output using the test + //register. + for(unsigned int i = 0; i < (1 << powTableBitCount); ++i) + { + //Normalize the current index to the range 0.0-1.0. Note that in this case, 0.0 + //is a value which is never actually reached, since we start from i+1. They only + //did this to keep the result to an 11-bit output. It probably would have been + //better to simply subtract 1 from every final number and have 1.0 as the input + //limit instead when building the table, so an input of 0 would output 0x7FF, + //but they didn't. + double entryNormalized = (double)(i + 1) / (double)(1 << powTableBitCount); + + //Calculate 2^-entryNormalized + double resultNormalized = pow(2, -entryNormalized); + + //Convert the normalized result to an 11-bit rounded result + unsigned int result = (unsigned int)((resultNormalized * (1 << powTableOutputBitCount)) + 0.5); + + //Write the result to the table + powTable[i] = result; + } + + //Initialize the wave logging state + std::wstring captureFolder = GetSystemInterface().GetCapturePath(); + wavLoggingEnabled = false; + std::wstring wavLoggingFileName = GetDeviceInstanceName() + L".wav"; + wavLoggingPath = PathCombinePaths(captureFolder, wavLoggingFileName); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + wavLoggingChannelEnabled[channelNo] = false; + std::wstringstream wavLoggingChannelFileName; + wavLoggingChannelFileName << GetDeviceInstanceName() << L" - C" << channelNo + 1 << L".wav"; + wavLoggingChannelPath[channelNo] = PathCombinePaths(captureFolder, wavLoggingChannelFileName.str()); + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + wavLoggingOperatorEnabled[channelNo][operatorNo] = false; + std::wstringstream wavLoggingOperatorFileName; + wavLoggingOperatorFileName << GetDeviceInstanceName() << L" - C" << channelNo + 1 << L"O" << operatorNo + 1 << L".wav"; + wavLoggingOperatorPath[channelNo][operatorNo] = PathCombinePaths(captureFolder, wavLoggingOperatorFileName.str()); + } + } + + //Register each data source with the generic data access base class + std::wstring audioLogExtensionFilter = L"Wave file|wav"; + std::wstring audioLogDefaultExtension = L"wav"; + bool result = true; + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::RawRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TestData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::LFOEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::LFOData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x3FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::CH3Mode, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBReset, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAReset, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBEnable, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAEnable, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBLoad, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerALoad, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DACData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DACEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DetuneData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::MultipleData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TotalLevelData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::KeyScaleData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AttackRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AmplitudeModulationEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::DecayRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SustainRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x1F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SustainLevelData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ReleaseRateData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x0F)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGEnabled, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGAttack, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGAlternate, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::SSGHold, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FrequencyData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BlockData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FrequencyDataChannel3, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x7FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BlockDataChannel3, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FeedbackData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AlgorithmData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputLeft, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputRight, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AMSData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x03)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::PMSData, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x07)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::KeyState, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::StatusRegister, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::BusyFlag, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBOverflow, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAOverflow, IGenericAccessDataValue::DataType::Bool))->SetLockingSupported(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerACurrentCounter, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0x3FF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBCurrentCounter, IGenericAccessDataValue::DataType::UInt))->SetLockingSupported(true)->SetUIntMaxValue(0xFF)->SetIntDisplayMode(IGenericAccessDataValue::IntDisplayMode::Hexadecimal)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ExternalClockRate, IGenericAccessDataValue::DataType::Double))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::FMClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::EGClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OutputClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerAClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::TimerBClockDivider, IGenericAccessDataValue::DataType::UInt))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::AudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ChannelAudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::ChannelAudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OperatorAudioLoggingEnabled, IGenericAccessDataValue::DataType::Bool))); + result &= AddGenericDataInfo((new GenericAccessDataInfo(IYM2612DataSource::OperatorAudioLoggingPath, IGenericAccessDataValue::DataType::FilePath))->SetFilePathExtensionFilter(audioLogExtensionFilter)->SetFilePathDefaultExtension(audioLogDefaultExtension)->SetFilePathCreatingTarget(true)); + + //Register page layouts for generic access to this device + GenericAccessPage* audioLoggingPage = new GenericAccessPage(L"Audio Logging", L"Audio Logging"); + audioLoggingPage->AddEntry((new GenericAccessGroup(L"Combined Output")) + ->AddEntry(new GenericAccessGroupDataEntry(IYM2612DataSource::AudioLoggingEnabled, L"Log Enabled")) + ->AddEntry(new GenericAccessGroupDataEntry(IYM2612DataSource::AudioLoggingPath, L"Log Path"))); + GenericAccessGroup* channelGroup = new GenericAccessGroup(L"Channel Output"); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + channelGroup->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::ChannelAudioLoggingEnabled, L"Channel " + channelNoAsString + L" Log Enabled"))->SetDataContext(new ChannelDataContext(channelNo))); + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + channelGroup->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::ChannelAudioLoggingPath, L"Channel " + channelNoAsString + L" Log Path"))->SetDataContext(new ChannelDataContext(channelNo))); + } + audioLoggingPage->AddEntry(channelGroup); + GenericAccessGroup* operatorGroup = new GenericAccessGroup(L"Operator Output"); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + std::wstring channelNoAsString; + IntToString(channelNo + 1, channelNoAsString); + GenericAccessGroup* channelGroupForOperators = (new GenericAccessGroup(L"Channel " + channelNoAsString))->SetOpenByDefault(false); + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + std::wstring operatorNoAsString; + IntToString(operatorNo + 1, operatorNoAsString); + channelGroupForOperators->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::OperatorAudioLoggingEnabled, L"Operator " + operatorNoAsString + L" Log Enabled"))->SetDataContext(new OperatorDataContext(channelNo, operatorNo))); + } + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + std::wstring operatorNoAsString; + IntToString(operatorNo + 1, operatorNoAsString); + channelGroupForOperators->AddEntry((new GenericAccessGroupDataEntry(IYM2612DataSource::OperatorAudioLoggingPath, L"Operator " + operatorNoAsString + L" Log Path"))->SetDataContext(new OperatorDataContext(channelNo, operatorNo))); + } + operatorGroup->AddEntry(channelGroupForOperators); + } + audioLoggingPage->AddEntry(operatorGroup); + result &= AddGenericAccessPage(audioLoggingPage); + + return result; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::ValidateDevice() +{ + return (externalClockRate != 0.0); +} + +//---------------------------------------------------------------------------------------- +void YM2612::Initialize() +{ + //All registers are initialized to 0, with one exception. The Left/Right output flags + //for the accumulator both power up selected for all channels. Without support for + //this, the SEGA sound for Sonic 1 on the Mega Drive fails to play. This exception + //probably only exists for compatibility reasons. The YM2612 aims for a degree of + //compatibility with the YM2203(OPN), and this chip didn't have the L/R registers. If + //the YM2612 powered up with these registers unset, all legacy code would require + //modification in order to set these flags, otherwise no sound would be produced. The + //YM2608 would also select these flags by default, as it has an even greater focus on + //YM2203 compatibility. + reg.Initialize(); + timerAOverflowTimes.Initialize(); + currentReg = 0; + status = 0; + + //Bus interface + icLineState = false; + + //We have confirmed that the YM2612 powers up with output enabled to both the left and + //right speakers for all channels. + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + SetOutputLeft(channelAddressOffset, true, AccessTarget().AccessLatest()); + SetOutputRight(channelAddressOffset, true, AccessTarget().AccessLatest()); + } + + //Initialize the timer state + lastTimesliceLength = 0; + timersLastUpdateTime = 0; + timersRemainingTime = 0; + timerARemainingCycles = 0; + timerBRemainingCycles = 0; + timerACounter = 0; + timerBCounter = 0; + timerAInitialCounter = 0; + timerBInitialCounter = 0; + timerAEnable = false; + timerBEnable = false; + timerALoad = false; + timerBLoad = false; + irqLineState = false; + + //Initialize the render thread properties + remainingRenderTime = 0; + egRemainingRenderCycles = 0; + outputBuffer.clear(); + + //Clear all register latch data + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + latchedFrequencyDataPending[channelNo] = false; + latchedFrequencyData[channelNo] = 0; + } + for(unsigned int regNo = 0; regNo < 3; ++regNo) + { + latchedFrequencyDataPendingCH3[regNo] = false; + latchedFrequencyDataCH3[regNo] = 0; + } + + //Initialize the envelope generator state + envelopeCycleCounter = 0; + cyclesUntilLFOIncrement = 0; + currentLFOCounter = 0; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + operatorData[channelNo][operatorNo].phase = OperatorData::ADSR_RELEASE; + operatorData[channelNo][operatorNo].keyonPrevious = false; + operatorData[channelNo][operatorNo].keyon = false; + operatorData[channelNo][operatorNo].csmKeyOn = false; + operatorData[channelNo][operatorNo].attenuation = (1 << attenuationBitCount) - 1; + operatorData[channelNo][operatorNo].ssgOutputInverted = false; + } + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::Reset(double accessTime) +{ + //Initialize all our internal registers to 0 + std::unique_lock lock(accessMutex); + AccessTarget accessTarget; + if(reg.DoesLatestTimesliceExist()) + { + accessTarget.AccessTime(accessTime); + } + else + { + accessTarget.AccessLatest(); + } + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + Data data(8, 0); + RegisterSpecialUpdateFunction(i, data, accessTime, GetDeviceContext(), 0); + SetRegisterData(i, data, accessTarget); + } + + //We have confirmed that the YM2612 powers up with output enabled to both the left and + //right speakers for all channels. + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + SetOutputLeft(channelAddressOffset, true, AccessTarget().AccessLatest()); + SetOutputRight(channelAddressOffset, true, AccessTarget().AccessLatest()); + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +//Reference functions +//---------------------------------------------------------------------------------------- +bool YM2612::AddReference(const MarshalSupport::Marshal::In& referenceName, IBusInterface* target) +{ + if(referenceName == L"BusInterface") + { + memoryBus = target; + } + else + { + return false; + } + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::RemoveReference(IBusInterface* target) +{ + if(memoryBus == target) + { + memoryBus = 0; + } +} + +//---------------------------------------------------------------------------------------- +//Line functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetLineID(const MarshalSupport::Marshal::In& lineName) const +{ + if(lineName == L"IRQ") //O + { + return (unsigned int)LineID::IRQ; + } + else if(lineName == L"IC") //I + { + return (unsigned int)LineID::IC; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +MarshalSupport::Marshal::Ret YM2612::GetLineName(unsigned int lineID) const +{ + switch((LineID)lineID) + { + case LineID::IRQ: + return L"IRQ"; + case LineID::IC: + return L"IC"; + } + return L""; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetLineWidth(unsigned int lineID) const +{ + switch((LineID)lineID) + { + case LineID::IRQ: + return 1; + case LineID::IC: + return 1; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetLineState(unsigned int targetLine, const Data& lineData, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(lineMutex); + + //Process the line state change + switch((LineID)targetLine) + { + case LineID::IC:{ + bool icLineStateNew = lineData.LSB(); + if(icLineStateNew != icLineState) + { + icLineState = icLineStateNew; + Reset(accessTime); + } + break;} + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::AssertCurrentOutputLineState() const +{ + if(memoryBus != 0) + { + if(irqLineState) memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), 1), GetDeviceContext(), GetDeviceContext(), GetCurrentTimesliceProgress(), 0); + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::NegateCurrentOutputLineState() const +{ + if(memoryBus != 0) + { + if(irqLineState) memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), 0), GetDeviceContext(), GetDeviceContext(), GetCurrentTimesliceProgress(), 0); + } +} + +//---------------------------------------------------------------------------------------- +//Clock source functions +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const +{ + if(clockSourceName == L"0M") + { + return (unsigned int)ClockID::C0M; + } + return 0; +} + +//---------------------------------------------------------------------------------------- +MarshalSupport::Marshal::Ret YM2612::GetClockSourceName(unsigned int clockSourceID) const +{ + switch((ClockID)clockSourceID) + { + case ClockID::C0M: + return L"0M"; + } + return L""; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::C0M) + { + externalClockRate = clockRate; + } + + //Since a clock rate change will affect our timing point calculations, trigger a + //rollback. + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); +} + +//---------------------------------------------------------------------------------------- +void YM2612::TransparentSetClockSourceRate(unsigned int clockInput, double clockRate) +{ + //Apply the input clock rate change + if((ClockID)clockInput == ClockID::C0M) + { + externalClockRate = clockRate; + } +} + +//---------------------------------------------------------------------------------------- +//Execute functions +//---------------------------------------------------------------------------------------- +void YM2612::BeginExecution() +{ + //Initialize the worker thread state + pendingRenderOperationCount = 0; + renderThreadLagging = false; + regTimesliceList.clear(); + timerATimesliceList.clear(); + + //Start the render worker thread + renderThreadActive = true; + std::thread workerThread(std::bind(std::mem_fn(&YM2612::RenderThread), this)); + workerThread.detach(); +} + +//---------------------------------------------------------------------------------------- +void YM2612::SuspendExecution() +{ + std::unique_lock lock(renderThreadMutex); + + //Suspend the render worker thread + if(renderThreadActive) + { + renderThreadActive = false; + renderThreadUpdate.notify_all(); + renderThreadStopped.wait(lock); + } +} + +//---------------------------------------------------------------------------------------- +YM2612::UpdateMethod YM2612::GetUpdateMethod() const +{ + return UpdateMethod::Timeslice; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::SendNotifyUpcomingTimeslice() const +{ + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::NotifyUpcomingTimeslice(double nanoseconds) +{ + //Update the timer status, and reset the last access time for each timer. We need to + //perform this operation here, as we calculate the amount of time that has passed + //between timer updates based on the progress through the current timeslice. Since + //we're now switching to a new timeslice, we need to advance to the end of the last + //timeslice and reset the access time. + if(lastTimesliceLength > 0) + { + std::unique_lock lock(accessMutex); + UpdateTimers(lastTimesliceLength); + } + timersLastUpdateTime = 0; + + lastTimesliceLength = nanoseconds; + lastAccessTime = 0; + + //Add the new timeslice to all our timed buffers + reg.AddTimeslice(nanoseconds); + timerAOverflowTimes.AddTimeslice(nanoseconds); + + //Add references to the new timeslice entry from our timed buffers to the uncommitted + //timeslice lists for the buffers + regTimesliceListUncommitted.push_back(reg.GetLatestTimeslice()); + timerATimesliceListUncommitted.push_back(timerAOverflowTimes.GetLatestTimeslice()); +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteTimeslice(double nanoseconds) +{ + //If the render thread is lagging, pause here until it has caught up, so we don't + //leave the render thread behind with an ever-increasing workload it will never be + //able to complete. + if(renderThreadLagging) + { + std::unique_lock lock(timesliceMutex); + while(renderThreadLagging) + { + renderThreadLaggingStateChange.wait(lock); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteRollback() +{ + //Clock settings + externalClockRate = bexternalClockRate; + + //Bus interface + icLineState = bicLineState; + + //Rollback our timed buffers + reg.Rollback(); + timerAOverflowTimes.Rollback(); + + //Rollback our port registers + currentReg = bcurrentReg; + status = bstatus; + + //Rollback the register latch data + for(unsigned int i = 0; i < channelCount; ++i) + { + latchedFrequencyDataPending[i] = blatchedFrequencyDataPending[i]; + latchedFrequencyData[i] = blatchedFrequencyData[i]; + } + for(unsigned int i = 0; i < 3; ++i) + { + latchedFrequencyDataPendingCH3[i] = blatchedFrequencyDataPendingCH3[i]; + latchedFrequencyDataCH3[i] = blatchedFrequencyDataCH3[i]; + } + + //Rollback the timer data + timersRemainingTime = btimersRemainingTime; + timerARemainingCycles = btimerARemainingCycles; + timerBRemainingCycles = btimerBRemainingCycles; + timerACounter = btimerACounter; + timerBCounter = btimerBCounter; + timerAInitialCounter = btimerAInitialCounter; + timerBInitialCounter = btimerBInitialCounter; + timerAEnable = btimerAEnable; + timerBEnable = btimerBEnable; + timerALoad = btimerALoad; + timerBLoad = btimerBLoad; + irqLineState = birqLineState; + + //Clear any uncommitted timeslices from our render timeslice buffers + regTimesliceListUncommitted.clear(); + timerATimesliceListUncommitted.clear(); +} + +//---------------------------------------------------------------------------------------- +void YM2612::ExecuteCommit() +{ + //Clock settings + bexternalClockRate = externalClockRate; + + //Bus interface + bicLineState = icLineState; + + //Commit our timed buffers + reg.Commit(); + timerAOverflowTimes.Commit(); + + //Take a backup of our port registers + bcurrentReg = currentReg; + bstatus = status; + + //Take a backup of the register latch data + for(unsigned int i = 0; i < channelCount; ++i) + { + blatchedFrequencyDataPending[i] = latchedFrequencyDataPending[i]; + blatchedFrequencyData[i] = latchedFrequencyData[i]; + } + for(unsigned int i = 0; i < 3; ++i) + { + blatchedFrequencyDataPendingCH3[i] = latchedFrequencyDataPendingCH3[i]; + blatchedFrequencyDataCH3[i] = latchedFrequencyDataCH3[i]; + } + + //Take a backup of the timer data + btimersRemainingTime = timersRemainingTime; + btimerARemainingCycles = timerARemainingCycles; + btimerBRemainingCycles = timerBRemainingCycles; + btimerACounter = timerACounter; + btimerBCounter = timerBCounter; + btimerAInitialCounter = timerAInitialCounter; + btimerBInitialCounter = timerBInitialCounter; + btimerAEnable = timerAEnable; + btimerBEnable = timerBEnable; + btimerALoad = timerALoad; + btimerBLoad = timerBLoad; + birqLineState = irqLineState; + + //Ensure that a valid latest timeslice exists in all our buffers. We need this + //check here, because commits can be triggered by the system at potentially any + //point in time, whether a timeslice has been issued or not. + if(!regTimesliceListUncommitted.empty() && !timerATimesliceListUncommitted.empty()) + { + //Obtain a timeslice lock so we can update the data we feed to the render + //thread + std::unique_lock lock(timesliceMutex); + + //Add the number of timeslices we are about to commit to the count of pending + //render operations. This is used to track if the render thread is lagging. + pendingRenderOperationCount += (unsigned int)regTimesliceListUncommitted.size(); + + //Move all timeslices in our uncommitted timeslice lists over to the committed + //timeslice lists, for processing by the render thread. + regTimesliceList.splice(regTimesliceList.end(), regTimesliceListUncommitted); + timerATimesliceList.splice(timerATimesliceList.end(), timerATimesliceListUncommitted); + + //Notify the render thread that it's got more work to do + renderThreadUpdate.notify_all(); + } +} + +//---------------------------------------------------------------------------------------- +//##TODO## Refactor this function to break it down into a set of smaller functions +void YM2612::RenderThread() +{ + std::unique_lock lock(renderThreadMutex); + + //Start the render loop + bool done = false; + while(!done) + { + //Obtain a copy of the latest completed timeslice period + RandomTimeAccessBuffer::Timeslice regTimesliceCopy; + RandomTimeAccessValue::Timeslice timerATimesliceCopy; + bool renderTimesliceObtained = false; + { + std::unique_lock timesliceLock(timesliceMutex); + + //If there is at least one render timeslice pending, grab it from the queue. + if(!regTimesliceList.empty() && !timerATimesliceList.empty()) + { + //Update the lagging state for the render thread + --pendingRenderOperationCount; + renderThreadLagging = (pendingRenderOperationCount > maxPendingRenderOperationCount); + renderThreadLaggingStateChange.notify_all(); + + //Grab the next completed timeslice from the timeslice list + regTimesliceCopy = *regTimesliceList.begin(); + timerATimesliceCopy = *timerATimesliceList.begin(); + regTimesliceList.pop_front(); + timerATimesliceList.pop_front(); + + //Flag that we managed to obtain a render timeslice + renderTimesliceObtained = true; + } + } + + //If no render timeslice was available, we need to wait for a thread suspension + //request or a new timeslice to be received, then begin the loop again. + if(!renderTimesliceObtained) + { + //If the render thread has not already been instructed to stop, suspend this + //thread until a timeslice becomes available or this thread is instructed to + //stop. + if(renderThreadActive) + { + renderThreadUpdate.wait(lock); + } + + //If the render thread has been suspended, flag that we need to exit this + //render loop. + done = !renderThreadActive; + + //Begin the loop again + continue; + } + + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + + //Calculate the FM clock period + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + double fmClockPeriod = 1000000000 / fmClock; + + //Render the YM2612 output + size_t outputBufferPos = outputBuffer.size(); +// unsigned int outputBufferMultiplexedPos = 0; +// std::vector outputBufferMultiplexed(0); + bool moreSamplesRemaining = true; + while(moreSamplesRemaining) + { + //Determine the time of the next write. Note that currently, this may be + //negative under certain circumstances, in particular when a write occurs past + //the end of a timeslice. Negative times won't cause writes to be processed at + //the incorrect time under the current model, but we do need to ensure that + //remainingRenderTime isn't negative before attempting to generate an output. + remainingRenderTime += reg.GetNextWriteTime(regTimesliceCopy); + + //##DEBUG## +// std::wcout << "YM2612 Buffer:\t" << remainingRenderTime << '\t' << outputBuffer.size() << '\t' << ((unsigned int)(remainingRenderTime / fmClockPeriod) * 2) << '\n'; + + //Calculate the output sample count. Note that remainingRenderTime may be + //negative, but we catch that below before using outputSampleCount. + unsigned int outputSampleCount = ((unsigned int)(remainingRenderTime / fmClockPeriod) * 2); + + //If we have one or more output samples to generate before the next settings + //change or the end of the target timeslice, generate and output the samples. + if((remainingRenderTime > 0) && (outputSampleCount > 0)) + { + //Resize the output buffer to fit the samples we're about to add + outputBuffer.resize(outputBuffer.size() + outputSampleCount); + // outputBufferMultiplexed.resize(outputBufferMultiplexed.size() + (outputSampleCount * channelCount)); + + //##TODO## Change the way we advance the render thread so that the update + //steps are driven by integer cycle numbers, rather than timeslice values. + //Refer to the timer update function. + while(remainingRenderTime >= fmClockPeriod) + { + //If CSM mode is active, advance the timer A overflow buffer by one step. + //We make this conditional as an optimization, to prevent the need to + //advance the timer A overflow buffer at such a fine resolution every + //update cycle, for such a rarely used feature. We use a larger update + //step later on for cases where CSM mode is inactive. + if(GetCH3Mode(accessTarget) == 2) + { + //Reset the committed state. We do this before each update, as we use + //the overflow value as a signal line which is only asserted when an + //overflow has occurred after the last update. Each write always sets + //it to true, and we reset it once that write has been processed. + timerAOverflowTimes.WriteCommitted(false); + //Advance the buffer + timerAOverflowTimes.AdvanceByTime(fmClockPeriod, timerATimesliceCopy); + } + + //Advance the global envelope generator state, and determine whether an + //envelope generator update cycle needs to run for each operator on this + //update step. + bool updateEnvelopeGenerator = false; + --egRemainingRenderCycles; + if(egRemainingRenderCycles <= 0) + { + egRemainingRenderCycles = (int)egClockDivider; + ++envelopeCycleCounter; + updateEnvelopeGenerator = true; + } + + //Update the state of the envelope and phase generators for each operator + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + UpdateOperator(channelNo, operatorNo, updateEnvelopeGenerator); + } + } + + //Update the LFO + if(GetLFOEnabled(accessTarget)) + { + --cyclesUntilLFOIncrement; + if(cyclesUntilLFOIncrement <= 0) + { + const unsigned int lfoIncrementValues[8] = {108, 77, 71, 67, 62, 44, 8, 5}; + unsigned int lfoData = GetLFOData(accessTarget); + cyclesUntilLFOIncrement = lfoIncrementValues[lfoData]; + ++currentLFOCounter; + } + } + else + { + //If the LFO is disabled, the LFO counter is forced to 0 + currentLFOCounter = 0; + } + + //Calculate the FM output for each channel in the YM2612 for this sample + int channelOutput[channelCount][2]; + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + //Calculate the address offset for all channel registers for the + //target channel + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + + //Read the current algorithm selection for the channel + unsigned int algorithmNo = GetAlgorithmData(channelAddressOffset, accessTarget); + + //Calculate the output for each operator in the channel + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + //Calculate the address offset for all operator registers for + //the target channel and operator + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(channelNo, operatorNo); + + //Calculate the phase modulation input for the operator unit + int phaseModulation = 0; + if((operatorNo == OPERATOR2) && ((algorithmNo == 0) || (algorithmNo == 3) || (algorithmNo == 4) || (algorithmNo == 5) || (algorithmNo == 6))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + else if((operatorNo == OPERATOR3) && ((algorithmNo == 0) || (algorithmNo == 2))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR2]; + } + else if((operatorNo == OPERATOR3) && (algorithmNo == 1)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1] + operatorOutput[channelNo][OPERATOR2]; + } + else if((operatorNo == OPERATOR3) && (algorithmNo == 5)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + else if((operatorNo == OPERATOR4) && ((algorithmNo == 0) || (algorithmNo == 1) || (algorithmNo == 4))) + { + phaseModulation = operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 2)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1] + operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 3)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3]; + } + else if((operatorNo == OPERATOR4) && (algorithmNo == 5)) + { + phaseModulation = operatorOutput[channelNo][OPERATOR1]; + } + //Convert the 14-bit operator unit output from the modulator into + //a 10-bit phase modulation input. Note that the bits are not + //mapped quite the way you might expect. The operator output is + //shifted down by 1 when it is mapped to the phase modulation + //input. The remaining upper 3 bits of the operator output are + //discarded. + // --------------------------------------------------------- + // | Operator Output (14-bit) | + // |-------------------------------------------------------| + // |13 |12 |11 |10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ------------=========================================---- + // | Modulation Input (10-bit) | + // |---------------------------------------| + // | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----------------------------------------- + phaseModulation >>= 1; + phaseModulation &= ((1 << phaseBitCount) - 1); + + //If we're updating operator 1, calculate the self-feedback value + //for phase modulation. + if(operatorNo == OPERATOR1) + { + unsigned int feedback = GetFeedbackData(channelAddressOffset, accessTarget); + if(feedback > 0) + { + phaseModulation = feedbackBuffer[channelNo][0] + feedbackBuffer[channelNo][1]; + phaseModulation >>= (10 - feedback); + + phaseModulation &= ((1 << phaseBitCount) - 1); + } + } + + //Read the current phase value from the phase generator + unsigned int phase = GetCurrentPhase(channelNo, operatorNo); + + //Read the current attenuation value from the envelope generator + unsigned int attenuation = GetOutputAttenuation(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); + + //Calculate the output from the operator unit + int result = CalculateOperator(phase, phaseModulation, attenuation); + operatorOutput[channelNo][operatorNo] = result; + + //If we're updating operator 1, add the output sample to the + //self-feedback output buffer. + if(operatorNo == OPERATOR1) + { + feedbackBuffer[channelNo][0] = feedbackBuffer[channelNo][1]; + feedbackBuffer[channelNo][1] = result; + } + + //Write to the wav log + if(wavLoggingOperatorEnabled[channelNo][operatorNo]) + { + std::unique_lock lock(waveLoggingMutex); + short outputSample; + float operatorOutputNormalized = (float)operatorOutput[channelNo][operatorNo] / ((1 << (operatorOutputBitCount - 1)) - 1); + //We halve the amplitude of the operator output just to + //make it a little easier to work with. + outputSample = (short)(operatorOutputNormalized * (32767.0f/2)); + wavLogOperator[channelNo][operatorNo].WriteData(outputSample); + } + } + + //The Accumulator + //Calculate the combined operator output for this channel + int combinedChannelOutput = 0; + switch(algorithmNo) + { + case 0: + // ----- ----- ----- ----- + // | 1 |--| 2 |--| 3 |--| 4 |- + // ----- ----- ----- ----- + case 1: + // ----- + // | 1 |--\ + // ----- | ----- ----- + // +--| 3 |--| 4 |- + // ----- | ----- ----- + // | 2 |--/ + // ----- + case 2: + // ----- + // | 1 |--\ + // ----- | ----- + // +--| 4 |- + // ----- ----- | ----- + // | 2 |--| 3 |--/ + // ----- ----- + case 3: + // ----- ----- + // | 1 |--| 2 |--\ + // ----- ----- | ----- + // +--| 4 |- + // ----- | ----- + // | 3 |--/ + // ----- + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4]; + break; + case 4: + // ----- ----- + // | 1 |--| 2 |--\ + // ----- ----- | + // +- + // ----- ----- | + // | 3 |--| 4 |--/ + // ----- ----- + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2]; + break; + case 5: + // ----- + // /--| 2 |--\ + // | ----- | + // | | + // ----- | ----- | + // | 1 |--+--| 3 |--+- + // ----- | ----- | + // | | + // | ----- | + // \--| 4 |--/ + // ----- + case 6: + // ----- + // | 1 | + // ----- + // | + // ----- ----- ----- + // | 2 | | 3 | | 4 | + // ----- ----- ----- + // | | | + // \-------+-------/ + // | + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3]; + break; + case 7: + // ----- ----- ----- ----- + // | 1 | | 2 | | 3 | | 4 | + // ----- ----- ----- ----- + // | | | | + // \-----------+-----------/ + // | + combinedChannelOutput = operatorOutput[channelNo][OPERATOR4] + operatorOutput[channelNo][OPERATOR2] + operatorOutput[channelNo][OPERATOR3] + operatorOutput[channelNo][OPERATOR1]; + break; + } + + //DAC support + if((channelNo == CHANNEL6) && GetDACEnabled(accessTarget)) + { + const unsigned int dacDataBitCount = 8; + //The DAC data is written as an unsigned value. We convert it to + //a signed value here. + //##TODO## It's possible the DAC data uses a primitive sign bit. + //Perform a test to determine whether this is the case. + unsigned int dacData = GetDACData(accessTarget); + int dacResult = (int)dacData - 0x80; + //Convert from the 8-bit signed DAC data value to a 14-bit signed + //operator output. The DAC data is mapped to the upper 8 bits of + //the 14-bit output. + dacResult <<= operatorOutputBitCount - dacDataBitCount; + //Since DAC is enabled, the specified DAC sample replaces the + //calculated FM output for this channel. + combinedChannelOutput = dacResult; + } + + //The result needs to be shifted up by 2 to correctly convert from + //the 14-bit output from the operator unit, to the 16-bit output from + //the accumulator. + //##TODO## Confirm whether operators are summed before the shift + //occurs, or whether the operators are shifted to 16-bit values + //first, and then summed. + combinedChannelOutput <<= 2; + + //A single operator at max attenuation won't clip, but multiple + //operators combined might. We add a limit here to reproduce the + //clipping operation. + int maxAccumulatorOutput = (int)((1 << (accumulatorOutputBitCount - 1)) - 1); + int minAccumulatorOutput = -(int)((1 << (accumulatorOutputBitCount - 1)) - 1); + if(combinedChannelOutput > maxAccumulatorOutput) + { + combinedChannelOutput = maxAccumulatorOutput; + } + else if(combinedChannelOutput < minAccumulatorOutput) + { + combinedChannelOutput = minAccumulatorOutput; + } + + //Pan Left/Right + channelOutput[channelNo][0] = GetOutputLeft(channelAddressOffset, accessTarget)? combinedChannelOutput: 0; + channelOutput[channelNo][1] = GetOutputRight(channelAddressOffset, accessTarget)? combinedChannelOutput: 0; + + //Write to the wave log + if(wavLoggingChannelEnabled[channelNo]) + { + std::unique_lock lock(waveLoggingMutex); + short outputSampleLeft; + short outputSampleRight; + float channelOutputLeftNormalized = (float)channelOutput[channelNo][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + float channelOutputRightNormalized = (float)channelOutput[channelNo][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + //We halve the amplitude of the channel output just to + //make it a little easier to work with. + outputSampleLeft = (short)(channelOutputLeftNormalized * (32767.0f/2)); + outputSampleRight = (short)(channelOutputRightNormalized * (32767.0f/2)); + wavLogChannel[channelNo].WriteData(outputSampleLeft); + wavLogChannel[channelNo].WriteData(outputSampleRight); + } + } + + //##FIX## + //Run the combined channel output from the accumulator through the + //embedded YM3016 DAC. Note that we perform this calculation in the 2's + //compliment mode for the DAC. + // Data channelOutputLeft(16, channelOutput[channelNo][0]); + + //Calculate the shift value + // unsigned int shiftLeft = 6; + // for(unsigned int i = 14; i >= 9; --i) + // { + // if(channelOutputLeft.GetBit(i)) + // { + // shiftLeft = 14 - i; + // break; + // } + // } + + //Calculate the mantissa + // Data mantissaLeft(10); + // mantissaLeft = channelOutputLeft.GetDataSegment(14 - shiftLeft, 9); + // mantissaLeft.SetBit(10, channelOutputLeft.GetBit(15)); + + //Calculate a single combined output for the YM2612. The DAC in the real + //YM2612 multiplexes the output from each of the 6 channels, and outputs + //at 6 times the output frequency we use here. We combine the output of + //each channel here, and calculate the average sample output instead. The + //apparent output should basically be the same. The best possible output + //would be obtained by generating the true multiplexed output, and + //resampling from the true output to the final audio output frequency + //we're sending to the sound card. + double finalOutputLeft = 0; + double finalOutputRight = 0; + for(unsigned int i = 0; i < channelCount; ++i) + { + float channelOutputLeftNormalized = (float)channelOutput[i][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + float channelOutputRightNormalized = (float)channelOutput[i][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + finalOutputLeft += (channelOutputLeftNormalized / channelCount); + finalOutputRight += (channelOutputRightNormalized / channelCount); + } + short outputSampleLeft = (short)(32767.0f * finalOutputLeft); + short outputSampleRight = (short)(32767.0f * finalOutputRight); + outputBuffer[outputBufferPos++] = outputSampleLeft; + outputBuffer[outputBufferPos++] = outputSampleRight; + + //Write to the wave log + if(wavLoggingEnabled) + { + std::unique_lock lock(waveLoggingMutex); + Stream::ViewBinary wavlogStream(wavLog); + wavlogStream << outputSampleLeft; + wavlogStream << outputSampleRight; + } + + ////Calculate the true multiplexed output for the YM2612 + //for(unsigned int i = 0; i < channelCount; ++i) + //{ + // float channelOutputLeftNormalized = (float)channelOutput[i][0] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + // float channelOutputRightNormalized = (float)channelOutput[i][1] / ((1 << (accumulatorOutputBitCount - 1)) - 1); + // short outputSampleLeft = (short)(32767.0f * channelOutputLeftNormalized); + // short outputSampleRight = (short)(32767.0f * channelOutputRightNormalized); + // outputBufferMultiplexed[outputBufferMultiplexedPos++] = outputSampleLeft; + // outputBufferMultiplexed[outputBufferMultiplexedPos++] = outputSampleRight; + + // Write to the wave log + // if(wavLoggingEnabled) + // { + // std::unique_lock lock(waveLoggingMutex); + // wavLog.WriteData(outputSampleLeft); + // wavLog.WriteData(outputSampleRight); + // } + //} + + remainingRenderTime -= fmClockPeriod; + } + } + + RandomTimeAccessBuffer::WriteInfo writeInfo = reg.GetWriteInfo(0, regTimesliceCopy); + if(writeInfo.exists) + { + //Handle any special case register changes + switch(writeInfo.writeAddress) + { + case 0x28: + { + //Key-on/off + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // |-------------------------------| + //28H | Key State | | | + // |---------------| / | Channel | + // |OP4|OP3|OP2|OP1| | | + // --------------------------------- + //##TODO## Confirm that bit 3 really is ignored when processing + //key on/off writes. + bool op4KeyState = writeInfo.newValue.GetBit(7); + bool op3KeyState = writeInfo.newValue.GetBit(6); + bool op2KeyState = writeInfo.newValue.GetBit(5); + bool op1KeyState = writeInfo.newValue.GetBit(4); + bool validChannelSelected = true; + Channels channelNo; + switch(writeInfo.newValue.GetDataSegment(0, 3)) + { + case 0: //000 - Channel 1 + channelNo = CHANNEL1; + break; + case 1: //001 - Channel 2 + channelNo = CHANNEL2; + break; + case 2: //010 - Channel 3 + channelNo = CHANNEL3; + break; + case 4: //100 - Channel 4 + channelNo = CHANNEL4; + break; + case 5: //101 - Channel 5 + channelNo = CHANNEL5; + break; + case 6: //110 - Channel 6 + channelNo = CHANNEL6; + break; + default: //011, 111 + validChannelSelected = false; + break; + } + + if(validChannelSelected) + { + if(!keyStateLocking[channelNo][OPERATOR4]) + { + operatorData[channelNo][OPERATOR4].keyon = op4KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR3]) + { + operatorData[channelNo][OPERATOR3].keyon = op3KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR2]) + { + operatorData[channelNo][OPERATOR2].keyon = op2KeyState; + } + if(!keyStateLocking[channelNo][OPERATOR1]) + { + operatorData[channelNo][OPERATOR1].keyon = op1KeyState; + } + } + } + } + } + + //See the notes above where we update the envelope generator for more info + //about this conditional step of the timer A overflow buffer. + if(GetCH3Mode(accessTarget) != 2) + { + timerAOverflowTimes.AdvanceByTime(writeInfo.writeTime, timerATimesliceCopy); + //Reset the committed state. We do this after each update here, as CSM + //mode has been disabled until this point, so all the overflow events + //we've just advanced through would have been ignored. + timerAOverflowTimes.WriteCommitted(false); + } + moreSamplesRemaining = reg.AdvanceByStep(regTimesliceCopy); + } + + //Play the mixed audio stream. Note that we fold samples from successive render + //operations together, ensuring that we only send data to the output audio stream + //when we have a significant number of samples to send. + unsigned int outputFrequency = (unsigned int)fmClock; + size_t minimumSamplesToOutput = (size_t)(outputFrequency / 60); + if(outputBuffer.size() >= minimumSamplesToOutput) + { + unsigned int internalSampleCount = (unsigned int)outputBuffer.size() / 2; + unsigned int outputSampleCount = (unsigned int)((double)internalSampleCount * ((double)outputSampleRate / (double)outputFrequency)); + AudioStream::AudioBuffer* outputBufferFinal = outputStream.CreateAudioBuffer(outputSampleCount, 2); + if(outputBufferFinal != 0) + { + outputStream.ConvertSampleRate(outputBuffer, internalSampleCount, 2, outputBufferFinal->buffer, outputSampleCount); + outputStream.PlayBuffer(outputBufferFinal); + } + outputBuffer.clear(); + outputBuffer.reserve(minimumSamplesToOutput * 2); + + //##DEBUG## + //std::wcout << "YM2612 Output: " << internalSampleCount << '\t' << outputSampleCount << '\n'; + } + + //Play the multiplexed output audio stream + //if(!outputBufferMultiplexed.empty()) + //{ + // unsigned int outputFrequency = (unsigned int)fmClock * channelCount; + // unsigned int internalSampleCount = (unsigned int)outputBufferMultiplexed.size() / 2; + // unsigned int outputSampleCount = (unsigned int)((double)internalSampleCount * ((double)outputSampleRate / (double)outputFrequency)); + // AudioStream::AudioBuffer* outputBufferFinal = outputStream.CreateAudioBuffer(outputSampleCount, 2); + // if(outputBufferFinal != 0) + // { + // outputStream.ConvertSampleRate(outputBufferMultiplexed, internalSampleCount, 2, outputBufferFinal->buffer, outputSampleCount); + // outputStream.PlayBuffer(outputBufferFinal); + // } + //} + + //Advance past the timeslice we've just rendered from + { + std::unique_lock lock(timesliceMutex); + reg.AdvancePastTimeslice(regTimesliceCopy); + timerAOverflowTimes.AdvancePastTimeslice(timerATimesliceCopy); + } + } + renderThreadStopped.notify_all(); +} + +//---------------------------------------------------------------------------------------- +//General operator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateOperator(unsigned int channelNo, unsigned int operatorNo, bool updateEnvelopeGenerator) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //Calculate the address offsets for all channel and operator registers for the target + //channel and operator. + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelNo); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(channelNo, operatorNo); + + //Update the key-on state. Note that hardware tests have shown that this does in fact + //happen each FM clock cycle, not just each envelope generator update cycle. Also + //note the update process for CSM key-on events, and the interaction between CSM and + //manual key-on events. This implementation is based on comprehensive hardware tests. + + //Update the CSM key-on state + if(channelNo == CHANNEL3) + { + state->csmKeyOn = (GetCH3Mode(accessTarget) == 2) && timerAOverflowTimes.ReadCommitted(); + } + + //Respond to any key on/off changes + bool keyonState = state->keyon || state->csmKeyOn; + if(keyonState != state->keyonPrevious) + { + if(keyonState) + { + //Key-on + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_ATTACK); + + //Restart the phase counter. Hardware tests have shown that the phase counter + //is always reset to 0 when key-on occurs. Note that this does include cases + //where key-on is triggered automatically by CSM mode. + state->phaseCounter = 0; + + //Reset the SSG-EG output inversion flag + state->ssgOutputInverted = false; + } + else + { + //Key-off + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_RELEASE); + + //If SSG-EG is enabled and the output is currently inverted, convert the + //current attenuation value into an equivalent non-inverted value. This + //emulates the release mode behaviour when SSG-EG is active. Note that we do + //not alter the output inversion flag here. Output inversion is ignored + //during the release phase. The output inversion flag is cleared when key-on + //occurs. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) && (state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) + { + state->attenuation = Data(attenuationBitCount, 0x200) - state->attenuation; + } + } + state->keyonPrevious = keyonState; + } + + //If SSG-EG is enabled, and the current internal attenuation level of the envelope + //generator is greater than or equal to 0x200, we need to run some special SSG-EG + //update steps. Note that hardware tests have proven that these operations occur each + //time the output of the envelope generator is calculated (IE, each sample), not just + //each time the envelope generator is updated. The output inversion and phase counter + //reset steps in particular are easily measurable, and have been shown to occur each + //sample. Note that hardware tests have also shown that this update process occurs + //before the normal envelope generator update steps in the case where both run on the + //same cycle. This can allow a single sample to be output at an attenuation level of + //0x200 before these update steps are applied. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) //SSG-EG mode is enabled + && (state->attenuation >= 0x200)) //The internal attenuation value has reached the magic 0x200 threshold + { + if(GetSSGAlternate(operatorAddressOffset, accessTarget) //SSG-EG is set to an alternating pattern + && (!GetSSGHold(operatorAddressOffset, accessTarget) || !state->ssgOutputInverted)) //Hold mode is disabled, or the current inversion state matches the initial inversion state at key-on + { + //Toggle the current inversion state of the envelope generator output. Note + //that extensive hardware tests have been performed on SSG-EG output + //inversion. This implementation has been shown to always produce the correct + //output, even under unusual circumstances such as when an attack phase is + //present, and/or changes are made to the SSG-EG mode at critical points. + state->ssgOutputInverted = !state->ssgOutputInverted; + + //Note that if the hold bit is set, the inversion state is only toggled if + //the current inversion state matches the initial inversion state. Under + //normal circumstances, this prevents the inversion state from being toggled + //more than once when the hold bit is set. This matches the confirmed + //behaviour of the real chip. This behaviour is vital, as the internal + //attenuation value finishes on 0x200 after each decay phase. Without this + //test, once hold mode begins, the inversion state would be toggled each + //sample. Note that the envelope generator does not maintain a separate flag + //which tracks whether the output has been inverted since key-on, as changes + //to the SSG-EG mode after key-on can cause the output to be inverted more + //than once under hold mode. + } + + if(!GetSSGAlternate(operatorAddressOffset, accessTarget) + && !GetSSGHold(operatorAddressOffset, accessTarget)) + { + //Hardware tests have shown that the phase counter is held at 0 in cases + //where SSG-EG is enabled, both the hold bit and alternate bit are unset, and + //the internal envelope generator attenuation value is greater than or equal + //to 0x200. Once any of these conditions change, the phase counter will + //resume counting up from 0. This causes the phase of the output wave to + //restart on each repetition of patterns 08 and 0C, which occurs on the real + //hardware. Note that the phase counter really is held at 0, not simply set + //to 0 at a particular point in time. This can create silence gaps between + //repetitions of the SSG-EG envelope where an attack phase exists. + state->phaseCounter = 0; + } + + if(state->phase != OperatorData::ADSR_ATTACK) + { + if((state->phase != OperatorData::ADSR_RELEASE) + && !GetSSGHold(operatorAddressOffset, accessTarget)) + { + //If SSG-EG is enabled, we're in either the decay or sustain phase, and + //the hold bit is not set, now that we've reached an attenuation level of + //0x200, we need to loop back to the attack phase and begin the ADSR + //envelope again. + + //Switch back to the attack phase + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_ATTACK); + + //Note that we've confirmed that the attenuation is not clamped to 0x200 + //in SSG-EG mode when the ADSR envelope loops. By toggling DR during the + //decay phase, we've proven that the final attenuation value is allowed + //to move past 0x200 before looping. If an attack curve follows, it + //begins its decay from this final attenuation value. Don't uncomment the + //line below, it is incorrect. It is only provided as an example of what + //NOT to do. + //state->attenuation = 0x200; + } + else if((state->phase == OperatorData::ADSR_RELEASE) + || !(state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) //If the output is not currently inverted + { + //If the output is not currently inverted, and we've reached an internal + //attenuation level of 0x200 in one of the decay phases (either the + //decay, sustain, or release phase), but the envelope is not looping back + //to the attack phase, we need to force the internal attenuation value to + //0x3FF. This emulates the behaviour of the YM2612 when entering a + //low-hold state in SSG-EG mode, and when the release phase reaches + //0x200. In both cases, the internal attenuation value is forced directly + //to 0x3FF. This has been confirmed through hardware tests. Note that + //this step occurs after the inversion state has been toggled. Performing + //these steps the wrong way around would break SSG-EG pattern 0xB, where + //both the hold and alternate bits are set, and the attack bit is clear. + + //Force the internal attenuation value to 0x3FF + state->attenuation = 0x3FF; + + //Note that this behaviour can be observed when switching from an + //inverted hold pattern to a low-hold pattern, then back again after the + //hold sequence has begun. When the inverted hold pattern resumes, the + //digital output will be 0x001F instead of 0x1FE8, as the internal + //attenuation value has been forced from 0x200 to 0x3FF, which becomes + //0x201 when it is inverted, outputting a value of 0x001F. This effect + //can also be observed when reading the decay sequence under the release + //phase when SSG-EG mode is active. With an increment value of 1, the + //digital output from the operator unit can be observed to jump directly + //from 0x0021 to 0, indicating the output attenuation value from the + //envelope generator skipped from a known value of 0x1FC from the decay + //sequence, to a value greater than 0x33F. + } + } + } + + //Update the Envelope Generator + if(updateEnvelopeGenerator) + { + UpdateEnvelopeGenerator(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); + } + + //Update the Phase Generator + UpdatePhaseGenerator(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset); +} + +//---------------------------------------------------------------------------------------- +//This function implements the KeyCode formula as described on page 25 of the YM2608 +//documentation. Result is a 5-bit number with the following structure: +// --------------------- +// | 4 | 3 | 2 | 1 | 0 | +// |-------------------| +// | Block |N4 |N3 | +// --------------------- +//Where Block is the 3-bit block data, and N4/N3 are built from fnumber as follows: +// N4=F11 +// N3=(F11&(F10|F9|F8)) | !F11&F10&F9&F8 +//Where FXX indicates bit XX from fnumber, starting with the LSB as 1. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateKeyCode(unsigned int block, unsigned int fnumber) const +{ + Data keyCode(keyCodeBitCount); + Data fnumberData(fnumDataBitCount, fnumber); + keyCode.SetDataSegment(2, 3, block); + keyCode.SetBit(1, fnumberData.GetBit(10)); + keyCode.SetBit(0, (fnumberData.GetBit(10) && (fnumberData.GetBit(9) || fnumberData.GetBit(8) || fnumberData.GetBit(7))) || (!fnumberData.GetBit(10) && (fnumberData.GetBit(9) && fnumberData.GetBit(8) && fnumberData.GetBit(7)))); + return keyCode.GetData(); +} + +//---------------------------------------------------------------------------------------- +//Phase generator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdatePhaseGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //This algorithm is primarily based on the F-Number calculation given in the YM2608 + //manual, page 24. That formula is as follows: + //F-Number = (144 * fnote * 2^20 / M) / 2^(B-1) + //Additional tests were performed on hardware to answer all remaining questions about + //the update process. + + //Read the frequency and block data + unsigned int frequencyData = GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget); + unsigned int blockData = GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget); + + //Apply frequency modulation to fnum + // --------------------------------- + // | LFO Counter | + // |-------------------------------| + // |...| 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----=====================-------- + // | Phase Modulation | + // | Index (5-bit) | + // |-------------------| + // | 4 | 3 | 2 | 1 | 0 | + // --------------------- + Data pmCounter(phaseModIndexBitCount, currentLFOCounter >> 2); + unsigned int pmSensitivity = GetPMSData(channelAddressOffset, accessTarget); + if((pmCounter != 0) && (pmSensitivity != 0)) + { + bool pmInverted = pmCounter.GetBit(phaseModIndexBitCount - 1); + bool pmSlopeNegative = pmCounter.GetBit(phaseModIndexBitCount - 2); + Data quarterPhase(phaseModIndexBitCount - 2, pmCounter.GetData()); + if(pmSlopeNegative) + { + quarterPhase = ~quarterPhase; + } + + //##TODO## Run a test where the upper 6 bits of fnum are 0, and see if the + //inverted frequency modulation wave will create a measurable, effective 1-bit + //frequency modulation due to sign-extension. + //##TODO## Determine whether all 11 bits of fnum are used to calculate the + //frequency modulation value. It's possible that all 11 bits of fnum are used to + //build a frequency modulation value, and that value is calculated at full + //precision, without any loss. That value is then sign-extended, and added to + //fnum, but lower bits of the frequency modulation value are discarded. If this + //is the case, the sign-extension behaviour will mean that a 1-bit modulation + //value is present, even when only the LSB of fnum is set. It would also mean + //that we would be able to detect the results of carry operations in the addition + //for the increment values for each bit, below the level of the LSB of fnum. + + int pmIncrement = 0; + for(unsigned int i = 0; i < fnumDataBitCount; ++i) + { + if((frequencyData & (1 << i)) != 0) + { + unsigned int pmIncrementValue = phaseModIncrementTable[pmSensitivity][quarterPhase.GetData()]; + pmIncrement += (int)(pmIncrementValue << i); + } + } + if(pmInverted) + { + pmIncrement = -pmIncrement; + } + pmIncrement >>= 9; + frequencyData += (unsigned int)pmIncrement; + + ////Calculate the frequency modulation value based on the upper 6 bits of fnum + //const unsigned int fnumModulationBits = 6; + //unsigned int pmSensitivity = GetPMSData(channelNo, accessTarget); + //unsigned int pmIncrement = 0; + //unsigned int frequencyDataUpperBits = frequencyData >> (fnumDataBitCount - fnumModulationBits); + //for(unsigned int i = 0; i < fnumModulationBits; ++i) + //{ + // if((frequencyDataUpperBits & (1 << i)) != 0) + // { + // unsigned int pmIncrementValue = phaseModIncrementTable[pmSensitivity][quarterPhase.GetData()]; + // unsigned int pmIncrementForBit = (pmIncrementValue << 1) >> ((fnumModulationBits - 1) - i); + // pmIncrement += pmIncrementForBit; + // } + //} + + //if(pmInverted) + //{ + // frequencyData -= pmIncrement; + //} + //else + //{ + // frequencyData += pmIncrement; + //} + + //Clamp the adjusted fnum value to an 11-bit result. + frequencyData &= ((1 << fnumDataBitCount) - 1); + } + + //Adjust the fnum data by the block shift data, to calculate the initial phase + //increment value. The block data applies a shift to fnum in the following way: + //------------------------------------------------- + //| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | + //|-----------------------------------------------| + //| >>1 | - | <<1 | <<2 | <<3 | <<4 | <<5 | <<6 | + //------------------------------------------------- + //Note the loss of precision when block=0. The LSB of fnum is discarded when block=0. + //This has been confirmed through hardware tests. + unsigned int phaseIncrement; + if(blockData == 0) + { + phaseIncrement = (frequencyData >> 1); + } + else + { + phaseIncrement = frequencyData << (blockData - 1); + } + + //Apply detune to the phase increment value. Note that the detune adjustment is + //applied before the frequency multiplier. + unsigned int keyCode = CalculateKeyCode(blockData, frequencyData); + Data detuneData(detuneBitCount, GetDetuneData(operatorAddressOffset, accessTarget)); + bool detuneNegative = detuneData.GetBit(detuneBitCount - 1); + unsigned int detuneIndex = detuneData.GetDataSegment(0, 2); + unsigned int detuneIncrement = detunePhaseIncrementTable[keyCode][detuneIndex]; + if(detuneNegative) + { + phaseIncrement -= detuneIncrement; + } + else + { + phaseIncrement += detuneIncrement; + } + + //Clamp the intermediate phase increment to a 17-bit result. This is necessary in + //order to accurately emulate overflows caused by the detune adjustment. + const unsigned int intermediatePhaseIncrementBitCount = 17; + phaseIncrement &= ((1 << intermediatePhaseIncrementBitCount) - 1); + + //Apply the frequency multiplier to the phase increment value + unsigned int mul = GetMultipleData(operatorAddressOffset, accessTarget); + if(mul == 0) + { + phaseIncrement /= 2; + } + else + { + phaseIncrement *= mul; + } + + //Apply the phase increment to the phase counter + state->phaseCounter += phaseIncrement; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetCurrentPhase(unsigned int channelNo, unsigned int operatorNo) const +{ + const OperatorData* state = &operatorData[channelNo][operatorNo]; + //This function returns the 10-bit output from the phase generator, which is used by + //the operator unit. This 10-bit output represents the upper 10 bits of the internal + //phase counter. We extract the upper 10 bits of the internal phase counter here, to + //build that 10-bit output. + return state->phaseCounter.GetDataSegment(state->phaseCounter.GetBitCount() - 10, 10); +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetFrequencyData(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, const AccessTarget& accessTarget) const +{ + if((channelNo == CHANNEL3) && (GetCH3Mode(accessTarget) != 0)) + { + //If we're in channel 3 special mode, read the separate frequency data for the + //operator. + return GetFrequencyDataChannel3(operatorNo, accessTarget); + } + else + { + //Read the global frequency data for the channel + return GetFrequencyData(channelAddressOffset, accessTarget); + } +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetBlockData(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, const AccessTarget& accessTarget) const +{ + if((channelNo == CHANNEL3) && (GetCH3Mode(accessTarget) != 0)) + { + //If we're in channel 3 special mode, read the separate block data for the + //operator. + return GetBlockDataChannel3(operatorNo, accessTarget); + } + else + { + //Read the global block data for the channel + return GetBlockData(channelAddressOffset, accessTarget); + } +} + +//---------------------------------------------------------------------------------------- +//Envelope generator functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateEnvelopeGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + //Check if we need to progress to a different phase of the ADSR envelope + if(state->phase == OperatorData::ADSR_ATTACK) + { + //If we're in the attack phase and attenuation has hit minimum, switch to the + //decay phase. + if(state->attenuation == 0) + { + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_DECAY); + } + } + else if(state->phase == OperatorData::ADSR_DECAY) + { + unsigned int sustainLevelAsAttenuation = ConvertSustainLevelToAttenuation(GetSustainLevelData(operatorAddressOffset, accessTarget)); + + //If we're in the decay phase and attenuation has passed SL, switch to the + //sustain phase. + if(state->attenuation >= sustainLevelAsAttenuation) + { + //We have confirmed that the current internal attenuation number is NOT + //clamped to SL when the decay phase passes SL. This can't happen under normal + //circumstances. The minimum step for SL is 0x20, which is also 8*4=0x20 the + //maximum output step for the decay phase under SSG-EG. Decay should always + //end exactly on SL. Where this may not be true is when DR is modified during + //the decay phase. We know from hardware tests where we modified DR during the + //decay phase to get the attenuation value to "skip over" 0x200 that the final + //level is allowed to move past SL during the decay phase. The sustain phase + //then begins from the point at which the decay rate finished. This has been + //confirmed both under normal mode and when SSG-EG is active. Don't uncomment + //the line below, it is incorrect. It is only provided as an example of what + //NOT to do. + //state->attenuation = sustainLevelAsAttenuation; + + //Switch from the decay phase to the sustain phase. Note that we have + //confirmed that changing SL after the sustain phase has been entered can't + //cause the operator to re-enter the decay phase. The switch from decay to + //sustain is a one-way process. The selection between the decay or sustain + //phases is not based on the current attenuation value relative to SL. + SetADSRPhase(channelNo, operatorNo, channelAddressOffset, operatorAddressOffset, OperatorData::ADSR_SUSTAIN); + } + } + + //Calculate the current rate value for the envelope. Note that we have confirmed this + //value is evaluated on every update cycle. Changes to the effective rate for the + //current phase of the envelope generator take effect immediately. + unsigned int rateKeyScale = CalculateRateKeyScale(GetKeyScaleData(operatorAddressOffset, accessTarget), CalculateKeyCode(GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget), GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget))); + unsigned int rate = 0; + switch(state->phase) + { + case OperatorData::ADSR_ATTACK: + rate = CalculateRate(GetAttackRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_DECAY: + rate = CalculateRate(GetDecayRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_SUSTAIN: + rate = CalculateRate(GetSustainRateData(operatorAddressOffset, accessTarget), rateKeyScale); + break; + case OperatorData::ADSR_RELEASE:{ + //Note that we pass the 4-bit release rate data as a 5-bit number, with the LSB + //fixed to 1. This is based on the information given in the YM2608 Application + //Manual, page 30, which states that the release rate data is passed as + //(value * 2 + 1). + unsigned int adjustedRateData = (GetReleaseRateData(operatorAddressOffset, accessTarget) << 1) | 0x01; + rate = CalculateRate(adjustedRateData, rateKeyScale); + break;} + } + + //Check the envelope cycle counter and see if we should be adjusting the attenuation + //for the operator on this cycle. + unsigned int counterShiftValue = counterShiftTable[rate]; + if((envelopeCycleCounter % (1 << counterShiftValue)) == 0) + { + //Get the index of the next attenuation increment value in the update cycle (0-7) + unsigned int updateCycle = (envelopeCycleCounter >> counterShiftValue) & 0x07; + + //Read the next attenuation increment value in the cycle + unsigned int attenuationIncrement = attenuationIncrementTable[rate][updateCycle]; + + //Update the attenuation + unsigned int newAttenuation = state->attenuation.GetData(); + if(state->phase == OperatorData::ADSR_ATTACK) + { + //If the attack rate is less than 62, advance the attack curve. Attack rate + //values of 62 and 63 have special case handling when the attack phase is + //first entered, which forces the attenuation directly to 0. Note that if an + //attack phase begins with an attack rate less than 62, then the attack rate + //changes during the attack phase to a rate value of 62 or 63, this exclusion + //will prevent the attack curve from advancing, and the attack phase will + //stall. This matches the confirmed behaviour of the real hardware. + if(rate < 62) + { + //Note that we've confirmed this formula for the attack curve produces a + //binary accurate result. + unsigned int attenuationAdjustment = (~newAttenuation * attenuationIncrement) >> 4; + + //Combine the attenuation adjustment value with the current attenuation + //value. The attenuation adjustment is a two's compliment representation + //of a negative number, so this addition operation will actually subtract + //a value from the current attenuation level. Note that we don't apply any + //limiting operation here, so an overflow is possible. This is vital, as + //the addition of the two's compliment negative value will always cause an + //overflow to occur. + newAttenuation += attenuationAdjustment; + } + } + else + { + //Advance the linear decay for the decay, sustain, or release phase. Note that + //if SSG-EG is enabled for this operator, the decay phase runs at 4x the + //normal speed. + if(GetSSGEnabled(operatorAddressOffset, accessTarget)) + { + //If the current internal attenuation value is below 0x200, advance the + //decay phase. In most cases when the attenuation level reaches 0x200, + //the envelope will move back to the attack phase, or the attenuation + //level will be forced to 0x3FF anyway. One case where neither of these + //changes occur, and we need this check here to ensure the attenuation + //level isn't permitted to advance any further, is when we enter an + //inverted hold phase. Hardware tests have conclusively shown that in + //these cases, if the internal attenuation level is greater than or equal + //to 0x200, the attenuation level remains unchanged. This is true even in + //cases where the internal attenuation level has been offset from a + //multiple of 4, and the precise value of 0x200 is skipped over by an + //SSG-EG increment. + if(newAttenuation < 0x200) + { + newAttenuation += (int)(4 * attenuationIncrement); + } + } + else + { + newAttenuation += (int)attenuationIncrement; + } + + //Limit the result to the maximum attenuation value. This is necessary to stop + //the final step in a decay phase overflowing back to 0. The last update step + //in a decay phase is always capped at 0x3FF, even when the step would have + //advanced past 0x3FF. Under normal circumstances, all decay phases would + //always end on a value of 0x400 which would be clamped back to 0x3FF, but + //this this clamping behaviour has also been confirmed to work correctly when + //the decay rate is modified during the decay phase, to cause the final step + //to "skip over" the usual ending value of 0x400. + unsigned int maxAttenuation = (1 << attenuationBitCount) - 1; + if(newAttenuation > maxAttenuation) + { + newAttenuation = maxAttenuation; + } + } + + //Write the new attenuation value to the envelope generator state + state->attenuation = newAttenuation; + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetADSRPhase(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset, OperatorData::ADSRPhase phase) +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + OperatorData* state = &operatorData[channelNo][operatorNo]; + + if(phase != state->phase) + { + if(phase == OperatorData::ADSR_ATTACK) + { + //If the rate is greater than or equal to 62, the current attenuation level is + //forced directly to 0. This causes the next envelope generator update cycle + //to advance through the first step of the decay phase. It seems a little odd + //to have to evaluate the effective attack rate here, but this implementation + //does appear to match the behaviour of the chip. + unsigned int rateKeyScale = CalculateRateKeyScale(GetKeyScaleData(operatorAddressOffset, accessTarget), CalculateKeyCode(GetBlockData(channelNo, operatorNo, channelAddressOffset, accessTarget), GetFrequencyData(channelNo, operatorNo, channelAddressOffset, accessTarget))); + unsigned int rate = CalculateRate(GetAttackRateData(operatorAddressOffset, accessTarget), rateKeyScale); + if(rate >= 62) + { + state->attenuation = 0; + } + } + state->phase = phase; + } +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::GetOutputAttenuation(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) const +{ + AccessTarget accessTarget; + accessTarget.AccessCommitted(); + const OperatorData* state = &operatorData[channelNo][operatorNo]; + + unsigned int attenuation = state->attenuation.GetData(); + + //If SSG-EG is enabled and the output is inverted, invert the output data. Note that + //extensive testing has been performed on the hardware to build this implementation. + //This test is performed exactly as shown each time the attenuation value is used. + //Note the way the attack bit is combined with the inversion state. This is known to + //be correct, and is essential in order to deal with cases where the SSG-EG state is + //changed after key-on. A change in the state of the attack bit will result in an + //immediate inversion of the output. Also note the calculation performed to derive + //the "inverted" data. This calculation has been proven to be binary-accurate. + if(GetSSGEnabled(operatorAddressOffset, accessTarget) + && (state->phase != OperatorData::ADSR_RELEASE) + && (state->ssgOutputInverted ^ GetSSGAttack(operatorAddressOffset, accessTarget))) + { + attenuation = 0x200 - attenuation; + attenuation &= 0x3FF; + } + + //Combine TL with the output attenuation value. Note that TL is applied after SSG-EG + //output inversion has been applied. + attenuation += ConvertTotalLevelToAttenuation(GetTotalLevelData(operatorAddressOffset, accessTarget)); + + //Apply amplitude modulation to the output attenuation value + if(GetAmplitudeModulationEnabled(operatorAddressOffset, accessTarget)) + { + // --------------------------------- + // | LFO Counter | + // |-------------------------------| + // |...| 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----============================= + // | Amplitude Modulation | + // | Index (7-bit) | + // |---------------------------| + // | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // ----------------------------- + //Calculate the current attenuation value from the LFO. Note that the amplitude + //modulation wave starts off inverted. An index of 0 corresponds with the maximum + //attenuation value that amplitude modulation can apply, according to the current + //amplitude modulation sensitivity. This is of particular importance when the LFO + //is set to the disabled state. In this state, the LFO counter is held at 0, but + //since an amplitude modulation index of 0 represents the "peak" of the wave, the + //operator will be attenuated by a fixed amount through amplitude modulation while + //the LFO counter is being held at 0. + bool inverted = (currentLFOCounter & 0x40) == 0; + unsigned int amValue = currentLFOCounter & 0x3F; + if(inverted) + { + amValue = ~amValue & 0x3F; + } + + //Adjust the attenuation value by the amplitude modulation sensitivity + const unsigned int amShiftValues[4] = {8, 3, 1, 0}; + unsigned int amSensitivity = GetAMSData(channelAddressOffset, accessTarget); + amValue = (amValue << 1) >> amShiftValues[amSensitivity]; + + //Attenuate the operator output by the current amplitude modulation value + attenuation += amValue; + } + + //Limit the result to the maximum attenuation value + if(attenuation >= (1 << attenuationBitCount)) + { + attenuation = (1 << attenuationBitCount) - 1; + } + + return attenuation; +} + +//---------------------------------------------------------------------------------------- +//This function implements the ADSR envelope rate calculation. Refer to page 30 of +//the YM2608 documentation for further info. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateRate(unsigned int rateData, unsigned int rateKeyScale) const +{ + //Parameters rateData and rateKeyScale are 5-bit numbers in the range 0x00-0x1F + unsigned int rate = (2 * rateData) + rateKeyScale; + //Special case. If rateData is 0, rate is forced to 0, regardless of the value of + //rateKeyScale. + if(rateData == 0) + { + rate = 0; + } + //The rate number is a 6-bit number, and the result is capped at the max to prevent + //overflows. We limit the result to the maximum value here in the case where the + //calculation exceeds the maximum. + if(rate >= (1 << rateBitCount)) + { + rate = (1 << rateBitCount) - 1; + } + return rate; +} + +//---------------------------------------------------------------------------------------- +//This function implements the rate key-scaling calculation. Refer to page 29 of the +//YM2608 documentation for further info. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::CalculateRateKeyScale(unsigned int keyScaleData, unsigned int keyCode) const +{ + //Parameter keyScaleData is a 2-bit value. Parameter keyCode is a 5-bit value. Result + //is a 5-bit value. + unsigned int keyScaleDivisor = 1 << (3 - keyScaleData); + unsigned int rateKeyScale = keyCode / keyScaleDivisor; + return rateKeyScale; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::ConvertTotalLevelToAttenuation(unsigned int totalLevel) const +{ + //Note that in the YM2608 Application Manual, section 2-5-3, page 32, there's a + //comment that when all the bits of TL are set, the attenuation level is set to the + //maximum amount (96db). This is a little misleading for our purposes here. This does + //NOT mean that all 10 bits of the attenuation output have to be forced to set when + //all 7 bits of TL are set. In reality, due to the precision limitations of the + //operator unit, an envelope generator output of 0x340 or greater will always force + //the final output to maximum attenuation (96db). This is well below the output of + //0x3F8 we would get if all the bits in TL are set. Due to this, it's impossible to + //know if the YM2612 forces all 10 bits of the envelope generator output to set when + //all 7 bits of TL are set, but it doesn't matter for the same reason, as there's no + //way for that to have any measurable effect. + return totalLevel << 3; +} + +//---------------------------------------------------------------------------------------- +unsigned int YM2612::ConvertSustainLevelToAttenuation(unsigned int sustainLevel) const +{ + //Note that in the YM2608 Application Manual, section 2-5-1, page 28, there's a + //comment that when all the bits of SL are set, SL is set to 93db. You might wonder + //whether they really meant 96db. In reality, it makes no difference. At 93db, the + //10-bit output from the envelope generator would be 0x370, which is over the maximum + //attenuation value of 0x340 that the operator unit can accept, before precision + //limitations force the output to minimum. + if(sustainLevel == 0xF) + { + //If all bits are set, sustain level is forced to 93db + sustainLevel |= 0x10; + } + sustainLevel <<= 5; + return sustainLevel; +} + +//---------------------------------------------------------------------------------------- +//Operator unit functions +//---------------------------------------------------------------------------------------- +//This function duplicates the exact power conversion performed by the YM2612 in the +//final stage of the operator unit. It is an implementation of the following: +// result = pow(2, -num); +// num: A 13-bit fixed point value of the form 5.8 (5 bit whole, 8 bit fractional) +// result: A 13-bit normalized output in the range 1-0. +//Internally, a 256 entry lookup table is used. This lookup stores a rounded 11-bit result +//for a range 0-1. Since we're dealing with powers of 2, this result can be adjusted for +//source numbers outside the range 0-1 by shifting the result. +//---------------------------------------------------------------------------------------- +unsigned int YM2612::InversePow2(unsigned int num) const +{ + unsigned int shiftCount = num >> powTableBitCount; + unsigned int tableIndex = num & ((1 << powTableBitCount) - 1); + unsigned int tableEntry = powTable[tableIndex]; + unsigned int outputShifted = (tableEntry << 2) >> shiftCount; + return outputShifted; +} + +//---------------------------------------------------------------------------------------- +int YM2612::CalculateOperator(unsigned int phase, int phaseModulation, unsigned int attenuation) const +{ + //Add the current phase and phase modulation values + Data combinedPhase(phaseBitCount); + combinedPhase = (unsigned int)((int)phase + phaseModulation); + + //The YM2612 sine table only stores values for a quarter of the full sine wave. We + //separate the sign bit of the phase value here, which leaves us with a half-phase + //representing positive wave oscillations only. For the remaining half-phase, if + //the phase is on the second half of the oscillation (decreasing slope), we invert + //the phase. The second half of the oscillation is a mirror of the first, so by + //inverting the half-phase, the quarter-phase sine table can be used to resolve the + //correct sine value for the full positive oscillation. The separated sign bit is + //used later to correct the result for negative oscillations. + bool signBit = combinedPhase.GetBit(phaseBitCount - 1); + bool slopeBit = combinedPhase.GetBit(phaseBitCount - 2); + Data quarterPhase(phaseBitCount - 2); + quarterPhase = combinedPhase; + if(slopeBit) + { + //If the MSB of the half-phase is set, the sine wave is decreasing in slope. In + //this case, we need to invert the quarter phase value, to mirror the lookup + //index into the sine table. + quarterPhase = ~quarterPhase; + } + + //Output from sinTable is a 4.8 fixed point attenuation value + unsigned int sinValue = sinTable[quarterPhase.GetData()]; + //Convert attenuation from a 4.6 fixed point value, to a 4.8 fixed point value. + unsigned int convertedAttenuation = attenuation << 2; + //Combined attenuation is a 5.8 fixed point value + unsigned int combinedAttenuation = sinValue + convertedAttenuation; + + //Convert the 5.8 fixed point attenuation value from a logarithmic representation of + //attenuation, to a linear representation of power. + int powResult = (int)InversePow2(combinedAttenuation); + + //Our calculated value currently represents the absolute value of the true result. If + //the original phase value specified a negative oscillation of the wave, negate the + //result. This will give us the true signed result. + if(signBit) + { + powResult = 0 - powResult; + } + return powResult; +} + +//---------------------------------------------------------------------------------------- +//Memory interface functions +//---------------------------------------------------------------------------------------- +IBusInterface::AccessResult YM2612::ReadInterface(unsigned int interfaceNumber, unsigned int location, Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(accessMutex); + + //Trigger a system rollback if the device has been accessed out of order. This is + //required in order to ensure that the address register is correct when each write + //occurs. + if(accessTime < lastAccessTime) + { + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); + } + lastAccessTime = accessTime; + + UpdateTimers(accessTime); + data.SetLowerBits(status); + + return true; +} + +//---------------------------------------------------------------------------------------- +IBusInterface::AccessResult YM2612::WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext) +{ + std::unique_lock lock(accessMutex); + AccessTarget accessTarget; + accessTarget.AccessTime(accessTime); + + //Trigger a system rollback if the device has been accessed out of order. This is + //required in order to ensure that the register latch settings are correct when each + //write occurs. + if(accessTime < lastAccessTime) + { + GetSystemInterface().SetSystemRollback(GetDeviceContext(), caller, accessTime, accessContext); + } + lastAccessTime = accessTime; + + //Decode and carry out the write operation. Note that hardware tests have shown that + //both data ports are equivalent, and that a write to either of the address ports + //stores both the part number and the register number. Regardless of whether the + //currently selected register is in part 1 or part 2, both data ports can be used to + //update the currently selected register value. + if(location == 0) + { + //Set the currently latched register to the specified part 1 register + currentReg = data.GetData(); + } + else if(location == 2) + { + //Set the currently latched register to the specified part 2 register + currentReg = registerCountPerPart + data.GetData(); + } + else if((location == 1) || (location == 3)) + { + //Only commit this register write if it wasn't latched + if(!rawRegisterLocking[currentReg] && !CheckForLatchedWrite(currentReg, data, accessTime)) + { + //Write to the selected register + RegisterSpecialUpdateFunction(currentReg, data, accessTime, caller, accessContext); + SetRegisterData(currentReg, data, accessTarget); + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } + } + } + + return true; +} + +//---------------------------------------------------------------------------------------- +void YM2612::RegisterSpecialUpdateFunction(unsigned int location, const Data& data, double accessTime, IDeviceContext* caller, unsigned int accessContext) +{ + //Note that the only register changes which currently require special handling at the + //time they are written are registers which relate to the timers. Writes to all other + //registers including key-on/off notifications are handled in the render thread. + switch(location) + { + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //24H |-------------------------------| + // | Timer A MSBs (bits 2-9) | + // --------------------------------- + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //25H |-------------------------------| + // | / / / / / / | Timer | + // | |A LSBs | + // --------------------------------- + case 0x24:{ + UpdateTimers(accessTime); + if(!timerAStateLocking.rate) + { + unsigned int trueTimerAInitialCounter = ~timerAInitialCounter & 0x3FF; + trueTimerAInitialCounter = (trueTimerAInitialCounter & 0x003) | (data.GetDataSegment(0, 8) << 2); + timerAInitialCounter = ~trueTimerAInitialCounter & 0x3FF; + } + break;} + case 0x25:{ + UpdateTimers(accessTime); + if(!timerAStateLocking.rate) + { + unsigned int trueTimerAInitialCounter = ~timerAInitialCounter & 0x3FF; + trueTimerAInitialCounter = (trueTimerAInitialCounter & 0x3FC) | data.GetDataSegment(0, 2); + timerAInitialCounter = ~trueTimerAInitialCounter & 0x3FF; + } + break;} + case 0x26: + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + //26H |-------------------------------| + // | Timer B | + // --------------------------------- + UpdateTimers(accessTime); + if(!timerBStateLocking.rate) + { + timerBInitialCounter = ~data.GetDataSegment(0, 8) & 0xFF; + } + break; + case 0x27: + // --------------------------------- + // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + // |-------------------------------| + // | | Timer | Timer | Timer | + //27H | CH3 | Reset | Enable| Load | + // | Mode |-------|-------|-------| + // | | B | A | B | A | B | A | + // --------------------------------- + //##TODO## According to the Y8950AM Application Manual, page 17, when the IRQ + //RESET bit is flagged in that processor, all other bits in the write to the + //register are ignored. Confirm this is not the case on the YM2612. + UpdateTimers(accessTime); + + //Update the load bits for timers A and B. Note that hardware tests have shown + //that the current counter value for a timer is reloaded when the load bit is + //changed from 0 to 1. A timer does not resume counting from its previous + //position when the load bit is toggled from 0 to 1. Setting the load bit to 1 + //for a timer which is already loaded does not force a re-load of the counter. + if(!timerAStateLocking.load) + { + bool timerALoadNew = data.GetBit(0); + if(!timerALoad && timerALoadNew) + { + timerACounter = timerAInitialCounter; + } + timerALoad = timerALoadNew; + } + if(!timerBStateLocking.load) + { + bool timerBLoadNew = data.GetBit(1); + if(!timerBLoad && timerBLoadNew) + { + timerBCounter = timerBInitialCounter; + } + timerBLoad = timerBLoadNew; + } + + //Update the enable bits for timers A and B + if(!timerAStateLocking.enable) + { + timerAEnable = data.GetBit(2); + } + if(!timerBStateLocking.enable) + { + timerBEnable = data.GetBit(3); + } + + //Update the overflow bits for timers A and B. We also negate the IRQ line here + //if it was asserted, and is now clear after processing the reset bits. + bool initialIntLineState = GetTimerAOverflow() || GetTimerBOverflow(); + if(!timerAStateLocking.overflow && data.GetBit(4)) + { + SetTimerAOverflow(false); + } + if(!timerBStateLocking.overflow && data.GetBit(5)) + { + SetTimerBOverflow(false); + } + if(initialIntLineState && !GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = false; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), caller, accessTime, accessContext); + } + } + break; + } +} + +//---------------------------------------------------------------------------------------- +bool YM2612::CheckForLatchedWrite(unsigned int location, const Data& data, double accessTime) +{ + AccessTarget accessTarget; + accessTarget.AccessTime(accessTime); + + switch(location) + { + //If we're writing to a block/fnum register, the write needs to be put in limbo until + //the corresponding fnum register is next written to. + case 0xA4: + latchedFrequencyDataPending[CHANNEL1] = true; + latchedFrequencyData[CHANNEL1] = data; + return true; + case 0xA5: + latchedFrequencyDataPending[CHANNEL2] = true; + latchedFrequencyData[CHANNEL2] = data; + return true; + case 0xA6: + latchedFrequencyDataPending[CHANNEL3] = true; + latchedFrequencyData[CHANNEL3] = data; + return true; + case 0x1A4: + latchedFrequencyDataPending[CHANNEL4] = true; + latchedFrequencyData[CHANNEL4] = data; + return true; + case 0x1A5: + latchedFrequencyDataPending[CHANNEL5] = true; + latchedFrequencyData[CHANNEL5] = data; + return true; + case 0x1A6: + latchedFrequencyDataPending[CHANNEL6] = true; + latchedFrequencyData[CHANNEL6] = data; + return true; + case 0xAD: + latchedFrequencyDataPendingCH3[0] = true; + latchedFrequencyDataCH3[0] = data; + return true; + case 0xAC: + latchedFrequencyDataPendingCH3[1] = true; + latchedFrequencyDataCH3[1] = data; + return true; + case 0xAE: + latchedFrequencyDataPendingCH3[2] = true; + latchedFrequencyDataCH3[2] = data; + return true; + + //If we're writing to an fnum register, commit any latched write to the corresponding + //block/fnum register. + case 0xA0: + if(latchedFrequencyDataPending[CHANNEL1]) + { + SetRegisterData(0xA4, latchedFrequencyData[CHANNEL1], accessTarget); + latchedFrequencyDataPending[CHANNEL1] = false; + latchedFrequencyData[CHANNEL1] = 0; + } + return false; + case 0xA1: + if(latchedFrequencyDataPending[CHANNEL2]) + { + SetRegisterData(0xA5, latchedFrequencyData[CHANNEL2], accessTarget); + latchedFrequencyDataPending[CHANNEL2] = false; + latchedFrequencyData[CHANNEL2] = 0; + } + return false; + case 0xA2: + if(latchedFrequencyDataPending[CHANNEL3]) + { + SetRegisterData(0xA6, latchedFrequencyData[CHANNEL3], accessTarget); + latchedFrequencyDataPending[CHANNEL3] = false; + latchedFrequencyData[CHANNEL3] = 0; + } + return false; + case 0x1A0: + if(latchedFrequencyDataPending[CHANNEL4]) + { + SetRegisterData(0x1A4, latchedFrequencyData[CHANNEL4], accessTarget); + latchedFrequencyDataPending[CHANNEL4] = false; + latchedFrequencyData[CHANNEL4] = 0; + } + return false; + case 0x1A1: + if(latchedFrequencyDataPending[CHANNEL5]) + { + SetRegisterData(0x1A5, latchedFrequencyData[CHANNEL5], accessTarget); + latchedFrequencyDataPending[CHANNEL5] = false; + latchedFrequencyData[CHANNEL5] = 0; + } + return false; + case 0x1A2: + if(latchedFrequencyDataPending[CHANNEL6]) + { + SetRegisterData(0x1A6, latchedFrequencyData[CHANNEL6], accessTarget); + latchedFrequencyDataPending[CHANNEL6] = false; + latchedFrequencyData[CHANNEL6] = 0; + } + return false; + case 0xA9: + if(latchedFrequencyDataPendingCH3[0]) + { + SetRegisterData(0xAD, latchedFrequencyDataCH3[0], accessTarget); + latchedFrequencyDataPendingCH3[0] = false; + latchedFrequencyDataCH3[0] = 0; + } + return false; + case 0xA8: + if(latchedFrequencyDataPendingCH3[1]) + { + SetRegisterData(0xAC, latchedFrequencyDataCH3[1], accessTarget); + latchedFrequencyDataPendingCH3[1] = false; + latchedFrequencyDataCH3[1] = 0; + } + return false; + case 0xAA: + if(latchedFrequencyDataPendingCH3[2]) + { + SetRegisterData(0xAE, latchedFrequencyDataCH3[2], accessTarget); + latchedFrequencyDataPendingCH3[2] = false; + latchedFrequencyDataCH3[2] = 0; + } + return false; + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Timer management functions +//---------------------------------------------------------------------------------------- +void YM2612::UpdateTimers(double timesliceProgress) +{ + //Calculate the total number of cycles that have executed since the last timer update + double initialTimersRemainingTime = timersRemainingTime; + double timerClockPeriod = 1000000000.0 / ((externalClockRate / (double)fmClockDivider) / (double)outputClockDivider); + double timePeriod = timersRemainingTime + (timesliceProgress - timersLastUpdateTime); + unsigned int timerClockCyclesExecuted = (unsigned int)(timePeriod / timerClockPeriod); + timersRemainingTime = timePeriod - ((double)timerClockCyclesExecuted * timerClockPeriod); + timersLastUpdateTime = timesliceProgress; + + //Calculate the total number of steps the timers have advanced + unsigned int initialTimerARemainingCycles = timerARemainingCycles; + unsigned int totalTimerACyclesExecuted = (timerClockCyclesExecuted + timerARemainingCycles) / timerAClockDivider; + timerARemainingCycles = (timerClockCyclesExecuted + timerARemainingCycles) % timerAClockDivider; + unsigned int initialTimerBRemainingCycles = timerBRemainingCycles; + unsigned int totalTimerBCyclesExecuted = (timerClockCyclesExecuted + timerBRemainingCycles) / timerBClockDivider; + timerBRemainingCycles = (timerClockCyclesExecuted + timerBRemainingCycles) % timerBClockDivider; + + //If timer A is loaded and the counter isn't locked, update the timer value + if(timerALoad && !timerAStateLocking.counter) + { + unsigned int timerAPeriod = timerAInitialCounter + 1; + + //Calculate each overflow time. In the case of timer A, we do this regardless of + //whether the timer is enabled, or whether the overflow flag is locked, since CSM + //key-on events are still generated each time timer A expires, regardless of + //whether the timer is enabled or the state of the overflow bit. + int timerAOverflowCount = ((int)totalTimerACyclesExecuted + ((int)timerAInitialCounter - (int)timerACounter)) / (int)timerAPeriod; + for(int i = 0; i < timerAOverflowCount; ++i) + { + unsigned int overflowCycle = ((unsigned int)i * timerAPeriod) + timerACounter; + double interruptTime = ((double)((overflowCycle * timerAClockDivider) + initialTimerARemainingCycles) * timerClockPeriod) - initialTimersRemainingTime; + + //Only use this overflow time to adjust the overflow flag and IRQ line state + //if the timer is enabled, and the overflow flag isn't locked. + if(timerAEnable && !timerAStateLocking.overflow) + { + //If the IRQ line is currently negated, and we're about to generate an + //overflow, assert the IRQ line. + if(!GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = true; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), GetDeviceContext(), interruptTime, (unsigned int)AccessContext::IRQ); + } + } + //Update the overflow flag + SetTimerAOverflow(true); + } + //Record the exact times when each timer A overflow occurred since the + //last update cycle. This is required in order to implement accurate CSM + //support. + timerAOverflowTimes.Write(interruptTime, true); + } + + //Calculate the new counter value for the timer + unsigned int timerACounterDisplace = totalTimerACyclesExecuted % timerAPeriod; + timerACounter = (timerACounter + (timerAPeriod - timerACounterDisplace)) % timerAPeriod; + } + + //If timer B is loaded and the counter isn't locked, update the timer value + if(timerBLoad && !timerBStateLocking.counter) + { + unsigned int timerBPeriod = timerBInitialCounter + 1; + + //If the timer is enabled, generate interrupts for each time an overflow has + //occurred, and update the overflow flag. + if(timerBEnable && !timerBStateLocking.overflow) + { + //Calculate each overflow time + int timerBOverflowCount = ((int)totalTimerBCyclesExecuted + ((int)timerBInitialCounter - (int)timerBCounter)) / (int)timerBPeriod; + for(int i = 0; i < timerBOverflowCount; ++i) + { + unsigned int overflowCycle = ((unsigned int)i * timerBPeriod) + timerBCounter; + double interruptTime = ((double)((overflowCycle * timerBClockDivider) + initialTimerBRemainingCycles) * timerClockPeriod) - initialTimersRemainingTime; + //If the IRQ line is currently negated, and we're about to generate an + //overflow, assert the IRQ line. + if(!GetTimerAOverflow() && !GetTimerBOverflow()) + { + if(memoryBus != 0) + { + irqLineState = true; + memoryBus->SetLineState((unsigned int)LineID::IRQ, Data(GetLineWidth((unsigned int)LineID::IRQ), (unsigned int)irqLineState), GetDeviceContext(), GetDeviceContext(), interruptTime, (unsigned int)AccessContext::IRQ); + } + } + //Update the overflow flag + SetTimerBOverflow(true); + } + } + + //Calculate the new counter value for the timer + unsigned int timerBCounterDisplace = totalTimerBCyclesExecuted % timerBPeriod; + timerBCounter = (timerBCounter + (timerBPeriod - timerBCounterDisplace)) % timerBPeriod; + } +} + +//---------------------------------------------------------------------------------------- +//Savestate functions +//---------------------------------------------------------------------------------------- +void YM2612::LoadState(IHierarchicalStorageNode& node) +{ + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + //Clock settings + if((*i)->GetName() == L"ExternalClockRate") + { + (*i)->ExtractData(externalClockRate); + } + + //Bus interface + else if((*i)->GetName() == L"ICLineState") + { + icLineState = (*i)->ExtractData(); + } + + //Register data + else if((*i)->GetName() == L"Registers") + { + reg.LoadState(*(*i)); + } + else if((*i)->GetName() == L"StatusRegister") + { + (*i)->ExtractData(status); + } + + //Register latch settings + else if((*i)->GetName() == L"LatchedRegister") + { + (*i)->ExtractData(currentReg); + } + else if((*i)->GetName() == L"LatchedFrequencyData") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + latchedFrequencyDataPending[channelNo] = true; + (*i)->ExtractData(latchedFrequencyData[channelNo]); + } + } + else if((*i)->GetName() == L"LatchedFrequencyDataCH3") + { + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"OperatorNo", operatorNo) && (operatorNo < operatorCount)) + { + latchedFrequencyDataPendingCH3[operatorNo] = true; + (*i)->ExtractData(latchedFrequencyDataCH3[operatorNo]); + } + } + + //Render thread properties + else if((*i)->GetName() == L"RemainingRenderTime") + { + (*i)->ExtractData(remainingRenderTime); + } + else if((*i)->GetName() == L"EGRemainingRenderCycles") + { + (*i)->ExtractData(egRemainingRenderCycles); + } + + //Render data + else if((*i)->GetName() == L"EnvelopeCycleCounter") + { + (*i)->ExtractHexData(envelopeCycleCounter); + } + else if((*i)->GetName() == L"RenderData") + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount) && + (*i)->ExtractAttribute(L"OperatorNo", operatorNo) && (operatorNo < operatorCount)) + { + OperatorData* state = &operatorData[channelNo][operatorNo]; + (*i)->ExtractAttributeHex(L"Attenuation", state->attenuation); + (*i)->ExtractAttributeHex(L"PhaseCounter", state->phaseCounter); + if(!keyStateLocking[channelNo][operatorNo]) + { + (*i)->ExtractAttribute(L"KeyOn", state->keyon); + } + (*i)->ExtractAttribute(L"CSMKeyOn", state->csmKeyOn); + (*i)->ExtractAttribute(L"KeyOnPrevious", state->keyonPrevious); + (*i)->ExtractAttribute(L"SSGOutputInverted", state->ssgOutputInverted); + + std::wstring phaseString; + (*i)->ExtractAttribute(L"Phase", phaseString); + if(phaseString == L"ADSR_ATTACK") + { + state->phase = OperatorData::ADSR_ATTACK; + } + else if(phaseString == L"ADSR_DECAY") + { + state->phase = OperatorData::ADSR_DECAY; + } + else if(phaseString == L"ADSR_SUSTAIN") + { + state->phase = OperatorData::ADSR_SUSTAIN; + } + else if(phaseString == L"ADSR_RELEASE") + { + state->phase = OperatorData::ADSR_RELEASE; + } + } + } + else if((*i)->GetName() == L"OP1FeedbackData") + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (channelNo < channelCount)) + { + (*i)->ExtractAttributeHex(L"Sample1", feedbackBuffer[channelNo][0]); + (*i)->ExtractAttributeHex(L"Sample2", feedbackBuffer[channelNo][1]); + } + } + else if((*i)->GetName() == L"CyclesUntilLFOIncrement") + { + (*i)->ExtractData(cyclesUntilLFOIncrement); + } + else if((*i)->GetName() == L"CurrentLFOCounter") + { + (*i)->ExtractData(currentLFOCounter); + } + + //Timer status + else if((*i)->GetName() == L"LastTimesliceLength") + { + (*i)->ExtractData(lastTimesliceLength); + } + else if((*i)->GetName() == L"TimersRemainingTime") + { + (*i)->ExtractData(timersRemainingTime); + } + else if((*i)->GetName() == L"TimerARemainingCycles") + { + (*i)->ExtractData(timerARemainingCycles); + } + else if((*i)->GetName() == L"TimerBRemainingCycles") + { + (*i)->ExtractData(timerBRemainingCycles); + } + else if(((*i)->GetName() == L"TimerACounter") && !timerAStateLocking.counter) + { + (*i)->ExtractData(timerACounter); + } + else if(((*i)->GetName() == L"TimerBCounter") && !timerBStateLocking.counter) + { + (*i)->ExtractData(timerBCounter); + } + else if(((*i)->GetName() == L"TimerAInitialCounter") && !timerAStateLocking.rate) + { + (*i)->ExtractData(timerAInitialCounter); + } + else if(((*i)->GetName() == L"TimerBInitialCounter") && !timerBStateLocking.rate) + { + (*i)->ExtractData(timerBInitialCounter); + } + else if(((*i)->GetName() == L"TimerAEnable") && !timerAStateLocking.enable) + { + (*i)->ExtractData(timerAEnable); + } + else if(((*i)->GetName() == L"TimerBEnable") && !timerBStateLocking.enable) + { + (*i)->ExtractData(timerBEnable); + } + else if(((*i)->GetName() == L"TimerALoad") && !timerAStateLocking.load) + { + (*i)->ExtractData(timerALoad); + } + else if(((*i)->GetName() == L"TimerBLoad") && !timerBStateLocking.load) + { + (*i)->ExtractData(timerBLoad); + } + } + + //Fix any locked registers at their set value + std::unique_lock lock2(registerLockMutex); + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + WriteGenericData(i->dataID, i->GetDataContext(), i->lockedValue); + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SaveState(IHierarchicalStorageNode& node) const +{ + //Clock settings + node.CreateChild(L"ExternalClockRate").SetData(externalClockRate); + + //Bus interface + node.CreateChild(L"ICLineState").SetData(icLineState); + + //Register data + IHierarchicalStorageNode& regNode = node.CreateChild(L"Registers"); + std::wstring regBufferName = GetFullyQualifiedDeviceInstanceName(); + regBufferName += L".Registers"; + reg.SaveState(regNode, regBufferName, false); + node.CreateChild(L"StatusRegister").SetData(status); + + //Register latch settings + node.CreateChild(L"LatchedRegister").SetData(currentReg); + for(unsigned int i = 0; i < channelCount; ++i) + { + if(latchedFrequencyDataPending[i]) + { + node.CreateChild(L"LatchedFrequencyData").SetData(latchedFrequencyData[i]).CreateAttribute(L"ChannelNo", i); + } + } + for(unsigned int i = 0; i < 3; ++i) + { + if(latchedFrequencyDataPendingCH3[i]) + { + node.CreateChild(L"LatchedFrequencyDataCH3").SetData(latchedFrequencyDataCH3[i]).CreateAttribute(L"OperatorNo", i); + } + } + + //Render thread properties + node.CreateChild(L"RemainingRenderTime", remainingRenderTime); + node.CreateChild(L"EGRemainingRenderCycles", egRemainingRenderCycles); + + //Render data + node.CreateChildHex(L"EnvelopeCycleCounter", envelopeCycleCounter, sizeof(envelopeCycleCounter)*2); + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + const OperatorData* state = &operatorData[channelNo][operatorNo]; + IHierarchicalStorageNode& renderDataState = node.CreateChild(L"RenderData"); + renderDataState.CreateAttribute(L"ChannelNo", channelNo); + renderDataState.CreateAttribute(L"OperatorNo", operatorNo); + renderDataState.CreateAttributeHex(L"Attenuation", state->attenuation, (attenuationBitCount+3)/4); + renderDataState.CreateAttributeHex(L"PhaseCounter", state->phaseCounter, (phaseBitCount+3)/4); + renderDataState.CreateAttribute(L"KeyOn", state->keyon); + renderDataState.CreateAttribute(L"CSMKeyOn", state->csmKeyOn); + renderDataState.CreateAttribute(L"KeyOnPrevious", state->keyonPrevious); + renderDataState.CreateAttribute(L"SSGOutputInverted", state->ssgOutputInverted); + + std::wstring phaseString; + switch(state->phase) + { + case OperatorData::ADSR_ATTACK: + phaseString = L"ADSR_ATTACK"; + break; + case OperatorData::ADSR_DECAY: + phaseString = L"ADSR_DECAY"; + break; + case OperatorData::ADSR_SUSTAIN: + phaseString = L"ADSR_SUSTAIN"; + break; + case OperatorData::ADSR_RELEASE: + phaseString = L"ADSR_RELEASE"; + break; + } + renderDataState.CreateAttribute(L"Phase", phaseString); + } + } + for(unsigned int i = 0; i < channelCount; ++i) + { + IHierarchicalStorageNode& feedbackData = node.CreateChild(L"OP1FeedbackData"); + feedbackData.CreateAttribute(L"ChannelNo", i); + feedbackData.CreateAttributeHex(L"Sample1", feedbackBuffer[i][0], (operatorOutputBitCount+3)/4); + feedbackData.CreateAttributeHex(L"Sample2", feedbackBuffer[i][1], (operatorOutputBitCount+3)/4); + } + node.CreateChild(L"CyclesUntilLFOIncrement", cyclesUntilLFOIncrement); + node.CreateChild(L"CurrentLFOCounter", currentLFOCounter); + + //Timer status + node.CreateChild(L"LastTimesliceLength", lastTimesliceLength); + node.CreateChild(L"TimersRemainingTime", timersRemainingTime); + node.CreateChild(L"TimerARemainingCycles", timerARemainingCycles); + node.CreateChild(L"TimerBRemainingCycles", timerBRemainingCycles); + node.CreateChild(L"TimerACounter", timerACounter); + node.CreateChild(L"TimerBCounter", timerBCounter); + node.CreateChild(L"TimerAInitialCounter", timerAInitialCounter); + node.CreateChild(L"TimerBInitialCounter", timerBInitialCounter); + node.CreateChild(L"TimerAEnable", timerAEnable); + node.CreateChild(L"TimerBEnable", timerBEnable); + node.CreateChild(L"TimerALoad", timerALoad); + node.CreateChild(L"TimerBLoad", timerBLoad); +} + +//---------------------------------------------------------------------------------------- +void YM2612::LoadDebuggerState(IHierarchicalStorageNode& node) +{ + //Initialize the register locking state + std::unique_lock lock2(registerLockMutex); + lockedRegisterState.clear(); + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + rawRegisterLocking[i] = false; + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + keyStateLocking[channelNo][operatorNo] = false; + } + } + timerAStateLocking.rate = false; + timerAStateLocking.counter = false; + timerAStateLocking.load = false; + timerAStateLocking.enable = false; + timerAStateLocking.overflow = false; + timerBStateLocking.rate = false; + timerBStateLocking.counter = false; + timerBStateLocking.load = false; + timerBStateLocking.enable = false; + timerBStateLocking.overflow = false; + + //Load the register locking state + std::list childList = node.GetChildList(); + for(std::list::iterator i = childList.begin(); i != childList.end(); ++i) + { + if((*i)->GetName() == L"LockedRegisterState") + { + unsigned int dataID; + std::wstring lockedValue; + if((*i)->ExtractAttribute(L"DataID", dataID) && (*i)->ExtractAttribute(L"LockedValue", lockedValue)) + { + IHierarchicalStorageAttribute* usingChannelDataContextAttribute = (*i)->GetAttribute(L"UsingChannelDataContext"); + IHierarchicalStorageAttribute* usingOperatorDataContextAttribute = (*i)->GetAttribute(L"UsingOperatorDataContext"); + if(usingChannelDataContextAttribute != 0) + { + unsigned int channelNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo)) + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, ChannelDataContext(channelNo), lockedValue)); + } + } + else if(usingOperatorDataContextAttribute != 0) + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (*i)->ExtractAttribute(L"OperatorNo", operatorNo)) + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, OperatorDataContext(channelNo, operatorNo), lockedValue)); + } + } + else + { + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, lockedValue)); + } + } + } + else if((*i)->GetName() == L"LockedRawRegister") + { + unsigned int registerNo; + if((*i)->ExtractAttribute(L"RegisterNo", registerNo)) + { + if(registerNo < registerCountTotal) + { + rawRegisterLocking[registerNo] = true; + } + } + } + else if((*i)->GetName() == L"LockedKeyState") + { + unsigned int channelNo; + unsigned int operatorNo; + if((*i)->ExtractAttribute(L"ChannelNo", channelNo) && (*i)->ExtractAttribute(L"OperatorNo", operatorNo)) + { + if((channelNo < channelCount) && (operatorNo < operatorCount)) + { + keyStateLocking[channelNo][operatorNo] = true; + } + } + } + else if((*i)->GetName() == L"LockedTimerARate") + { + timerAStateLocking.rate = true; + } + else if((*i)->GetName() == L"LockedTimerACounter") + { + timerAStateLocking.counter = true; + } + else if((*i)->GetName() == L"LockedTimerALoad") + { + timerAStateLocking.load = true; + } + else if((*i)->GetName() == L"LockedTimerAEnable") + { + timerAStateLocking.enable = true; + } + else if((*i)->GetName() == L"LockedTimerAOverflow") + { + timerAStateLocking.overflow = true; + } + else if((*i)->GetName() == L"LockedTimerBRate") + { + timerBStateLocking.rate = true; + } + else if((*i)->GetName() == L"LockedTimerBCounter") + { + timerBStateLocking.counter = true; + } + else if((*i)->GetName() == L"LockedTimerBLoad") + { + timerBStateLocking.load = true; + } + else if((*i)->GetName() == L"LockedTimerBEnable") + { + timerBStateLocking.enable = true; + } + else if((*i)->GetName() == L"LockedTimerBOverflow") + { + timerBStateLocking.overflow = true; + } + } +} + +//---------------------------------------------------------------------------------------- +void YM2612::SaveDebuggerState(IHierarchicalStorageNode& node) const +{ + //Save the register locking state + for(std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.begin(); lockedRegisterStateIterator != lockedRegisterState.end(); ++lockedRegisterStateIterator) + { + for(std::list::const_iterator lockedRegisterStateListIterator = lockedRegisterStateIterator->second.begin(); lockedRegisterStateListIterator != lockedRegisterStateIterator->second.end(); ++lockedRegisterStateListIterator) + { + const RegisterLocking& registerLockingInfo = *lockedRegisterStateListIterator; + IHierarchicalStorageNode& childNode = node.CreateChild(L"LockedRegisterState"); + childNode.CreateAttribute(L"DataID", registerLockingInfo.dataID); + childNode.CreateAttribute(L"LockedValue", registerLockingInfo.lockedValue); + if(registerLockingInfo.usingChannelDataContext) + { + childNode.CreateAttribute(L"UsingChannelDataContext", true); + childNode.CreateAttribute(L"ChannelNo", registerLockingInfo.channelDataContext.channelNo); + } + else if(registerLockingInfo.usingOperatorDataContext) + { + childNode.CreateAttribute(L"UsingOperatorDataContext", true); + childNode.CreateAttribute(L"ChannelNo", registerLockingInfo.operatorDataContext.channelNo); + childNode.CreateAttribute(L"OperatorNo", registerLockingInfo.operatorDataContext.operatorNo); + } + } + } + for(unsigned int i = 0; i < registerCountTotal; ++i) + { + if(rawRegisterLocking[i]) + { + node.CreateChild(L"LockedRawRegister").CreateAttributeHex(L"RegisterNo", i, 3); + } + } + for(unsigned int channelNo = 0; channelNo < channelCount; ++channelNo) + { + for(unsigned int operatorNo = 0; operatorNo < operatorCount; ++operatorNo) + { + if(keyStateLocking[channelNo][operatorNo]) + { + node.CreateChild(L"LockedKeyState").CreateAttribute(L"ChannelNo", channelNo).CreateAttribute(L"OperatorNo", operatorNo); + } + } + } + if(timerAStateLocking.rate) + { + node.CreateChild(L"LockedTimerARate"); + } + if(timerAStateLocking.counter) + { + node.CreateChild(L"LockedTimerACounter"); + } + if(timerAStateLocking.load) + { + node.CreateChild(L"LockedTimerALoad"); + } + if(timerAStateLocking.enable) + { + node.CreateChild(L"LockedTimerAEnable"); + } + if(timerAStateLocking.overflow) + { + node.CreateChild(L"LockedTimerAOverflow"); + } + if(timerBStateLocking.rate) + { + node.CreateChild(L"LockedTimerBRate"); + } + if(timerBStateLocking.counter) + { + node.CreateChild(L"LockedTimerBCounter"); + } + if(timerBStateLocking.load) + { + node.CreateChild(L"LockedTimerBLoad"); + } + if(timerBStateLocking.enable) + { + node.CreateChild(L"LockedTimerBEnable"); + } + if(timerBStateLocking.overflow) + { + node.CreateChild(L"LockedTimerBOverflow"); + } +} + +//---------------------------------------------------------------------------------------- +//Data read/write functions +//---------------------------------------------------------------------------------------- +bool YM2612::ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const +{ + ApplyGenericDataValueDisplaySettings(dataID, dataValue); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + Data registerData = GetRegisterData(registerDataContext.registerNo, AccessTarget().AccessLatest()); + return dataValue.SetValue(registerData.GetData());} + case IYM2612DataSource::TestData: + return dataValue.SetValue(GetTestData(AccessTarget().AccessLatest())); + case IYM2612DataSource::LFOEnabled: + return dataValue.SetValue(GetLFOEnabled(AccessTarget().AccessLatest())); + case IYM2612DataSource::LFOData: + return dataValue.SetValue(GetLFOData(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerAData: + return dataValue.SetValue(GetTimerAData(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBData: + return dataValue.SetValue(GetTimerBData(AccessTarget().AccessLatest())); + case IYM2612DataSource::CH3Mode: + return dataValue.SetValue(GetCH3Mode(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBReset: + return dataValue.SetValue(GetTimerBReset(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerAReset: + return dataValue.SetValue(GetTimerAReset(AccessTarget().AccessLatest())); + case IYM2612DataSource::TimerBEnable: + return dataValue.SetValue(timerBEnable); + case IYM2612DataSource::TimerAEnable: + return dataValue.SetValue(timerAEnable); + case IYM2612DataSource::TimerBLoad: + return dataValue.SetValue(timerBLoad); + case IYM2612DataSource::TimerALoad: + return dataValue.SetValue(timerALoad); + case IYM2612DataSource::DACData: + return dataValue.SetValue(GetDACData(AccessTarget().AccessLatest())); + case IYM2612DataSource::DACEnabled: + return dataValue.SetValue(GetDACEnabled(AccessTarget().AccessLatest())); + case IYM2612DataSource::DetuneData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetDetuneData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::MultipleData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetMultipleData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::TotalLevelData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetTotalLevelData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::KeyScaleData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetKeyScaleData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AttackRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetAttackRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AmplitudeModulationEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetAmplitudeModulationEnabled(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::DecayRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetDecayRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SustainRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSustainRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SustainLevelData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSustainLevelData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::ReleaseRateData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetReleaseRateData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGData:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGData(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGEnabled(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGAttack:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGAttack(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGAlternate:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGAlternate(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::SSGHold:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + return dataValue.SetValue(GetSSGHold(operatorAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FrequencyData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetFrequencyData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::BlockData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetBlockData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FrequencyDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(GetFrequencyDataChannel3(operatorDataContext.operatorNo, AccessTarget().AccessLatest()));} + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(GetBlockDataChannel3(operatorDataContext.operatorNo, AccessTarget().AccessLatest()));} + case IYM2612DataSource::FeedbackData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetFeedbackData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AlgorithmData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetAlgorithmData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::OutputLeft:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetOutputLeft(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::OutputRight:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetOutputRight(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::AMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetAMSData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + return dataValue.SetValue(GetPMSData(channelAddressOffset, AccessTarget().AccessLatest()));} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(operatorData[operatorDataContext.channelNo][operatorDataContext.operatorNo].keyon);} + case IYM2612DataSource::StatusRegister: + return dataValue.SetValue(status.GetData()); + case IYM2612DataSource::BusyFlag: + return dataValue.SetValue(GetBusyFlag()); + case IYM2612DataSource::TimerBOverflow: + return dataValue.SetValue(GetTimerBOverflow()); + case IYM2612DataSource::TimerAOverflow: + return dataValue.SetValue(GetTimerAOverflow()); + case IYM2612DataSource::TimerACurrentCounter: + return dataValue.SetValue(timerACounter); + case IYM2612DataSource::TimerBCurrentCounter: + return dataValue.SetValue(timerBCounter); + case IYM2612DataSource::ExternalClockRate: + return dataValue.SetValue(externalClockRate); + case IYM2612DataSource::FMClockDivider: + return dataValue.SetValue(fmClockDivider); + case IYM2612DataSource::EGClockDivider: + return dataValue.SetValue(egClockDivider); + case IYM2612DataSource::OutputClockDivider: + return dataValue.SetValue(outputClockDivider); + case IYM2612DataSource::TimerAClockDivider: + return dataValue.SetValue(timerAClockDivider); + case IYM2612DataSource::TimerBClockDivider: + return dataValue.SetValue(timerBClockDivider); + case IYM2612DataSource::AudioLoggingEnabled: + return dataValue.SetValue(wavLoggingEnabled); + case IYM2612DataSource::ChannelAudioLoggingEnabled:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + return dataValue.SetValue(wavLoggingChannelEnabled[channelDataContext.channelNo]);} + case IYM2612DataSource::OperatorAudioLoggingEnabled:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(wavLoggingOperatorEnabled[operatorDataContext.channelNo][operatorDataContext.operatorNo]);} + case IYM2612DataSource::AudioLoggingPath: + return dataValue.SetValue(wavLoggingPath); + case IYM2612DataSource::ChannelAudioLoggingPath:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + return dataValue.SetValue(wavLoggingChannelPath[channelDataContext.channelNo]);} + case IYM2612DataSource::OperatorAudioLoggingPath:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return dataValue.SetValue(wavLoggingOperatorPath[operatorDataContext.channelNo][operatorDataContext.operatorNo]);} + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) +{ + ApplyGenericDataValueLimitSettings(dataID, dataValue); + IGenericAccessDataValue::DataType dataType = dataValue.GetType(); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + Data registerData(8, dataValueAsUInt.GetValue()); + std::unique_lock lock(accessMutex); + RegisterSpecialUpdateFunction(registerDataContext.registerNo, registerData, timersLastUpdateTime, GetDeviceContext(), 0); + SetRegisterData(registerDataContext.registerNo, registerData, AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TestData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTestData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::LFOEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetLFOEnabled(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::LFOData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetLFOData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerAData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTimerAData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + timerAInitialCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetTimerBData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + timerBInitialCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::CH3Mode:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetCH3Mode(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerBReset:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBReset(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerAReset:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAReset(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TimerBEnable:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBEnable(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerBEnable = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerAEnable:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAEnable(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerAEnable = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerBLoad:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBLoad(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerBLoad = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::TimerALoad:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerALoad(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + timerALoad = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::DACData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + SetDACData(dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DACEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetDACEnabled(dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DetuneData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetDetuneData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::MultipleData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetMultipleData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::TotalLevelData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetTotalLevelData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::KeyScaleData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetKeyScaleData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AttackRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetAttackRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AmplitudeModulationEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetAmplitudeModulationEnabled(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::DecayRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetDecayRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SustainRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSustainRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SustainLevelData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSustainLevelData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::ReleaseRateData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetReleaseRateData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGData(operatorAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGEnabled(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGAttack:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGAttack(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGAlternate:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGAlternate(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::SSGHold:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int operatorAddressOffset = GetOperatorBlockAddressOffset(operatorDataContext.channelNo, operatorDataContext.operatorNo); + SetSSGHold(operatorAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FrequencyData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(operatorDataContext.channelNo); + SetFrequencyData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::BlockData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(operatorDataContext.channelNo); + SetBlockData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FrequencyDataChannel3:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetFrequencyDataChannel3(operatorDataContext.operatorNo, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::BlockDataChannel3:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetBlockDataChannel3(operatorDataContext.operatorNo, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::FeedbackData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetFeedbackData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AlgorithmData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetAlgorithmData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::OutputLeft:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetOutputLeft(channelAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::OutputRight:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetOutputRight(channelAddressOffset, dataValueAsBool.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::AMSData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetAMSData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::PMSData:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + unsigned int channelAddressOffset = GetChannelBlockAddressOffset(channelDataContext.channelNo); + SetPMSData(channelAddressOffset, dataValueAsUInt.GetValue(), AccessTarget().AccessLatest()); + return true;} + case IYM2612DataSource::KeyState:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + operatorData[operatorDataContext.channelNo][operatorDataContext.operatorNo].keyon = dataValueAsBool.GetValue(); + return true;} + case IYM2612DataSource::StatusRegister:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + status = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::BusyFlag:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetBusyFlag(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerBOverflow:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerBOverflow(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerAOverflow:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetTimerAOverflow(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::TimerACurrentCounter:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerACounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBCurrentCounter:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerBCounter = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::ExternalClockRate:{ + if(dataType != IGenericAccessDataValue::DataType::Double) return false; + IGenericAccessDataValueDouble& dataValueAsDouble = (IGenericAccessDataValueDouble&)dataValue; + externalClockRate = dataValueAsDouble.GetValue(); + return true;} + case IYM2612DataSource::FMClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + fmClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::EGClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + egClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::OutputClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + outputClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerAClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerAClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::TimerBClockDivider:{ + if(dataType != IGenericAccessDataValue::DataType::UInt) return false; + IGenericAccessDataValueUInt& dataValueAsUInt = (IGenericAccessDataValueUInt&)dataValue; + timerBClockDivider = dataValueAsUInt.GetValue(); + return true;} + case IYM2612DataSource::AudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + SetAudioLoggingEnabled(dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::ChannelAudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + SetChannelAudioLoggingEnabled(channelDataContext.channelNo, dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::OperatorAudioLoggingEnabled:{ + if(dataType != IGenericAccessDataValue::DataType::Bool) return false; + IGenericAccessDataValueBool& dataValueAsBool = (IGenericAccessDataValueBool&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + SetOperatorAudioLoggingEnabled(operatorDataContext.channelNo, operatorDataContext.operatorNo, dataValueAsBool.GetValue()); + return true;} + case IYM2612DataSource::AudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + wavLoggingPath = dataValueAsFilePath.GetValue(); + return true;} + case IYM2612DataSource::ChannelAudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + wavLoggingChannelPath[channelDataContext.channelNo] = dataValueAsFilePath.GetValue(); + return true;} + case IYM2612DataSource::OperatorAudioLoggingPath:{ + if(dataType != IGenericAccessDataValue::DataType::FilePath) return false; + IGenericAccessDataValueFilePath& dataValueAsFilePath = (IGenericAccessDataValueFilePath&)dataValue; + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + wavLoggingOperatorPath[operatorDataContext.channelNo][operatorDataContext.operatorNo] = dataValueAsFilePath.GetValue(); + return true;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Data locking functions +//---------------------------------------------------------------------------------------- +bool YM2612::GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const +{ + std::unique_lock lock(registerLockMutex); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + return rawRegisterLocking[registerDataContext.registerNo];} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + return keyStateLocking[operatorDataContext.channelNo][operatorDataContext.operatorNo];} + case IYM2612DataSource::TestData: + case IYM2612DataSource::LFOEnabled: + case IYM2612DataSource::LFOData: + case IYM2612DataSource::CH3Mode: + case IYM2612DataSource::DACData: + case IYM2612DataSource::DACEnabled: + case IYM2612DataSource::TimerBReset: + case IYM2612DataSource::TimerAReset:{ + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + return true; + } + break;} + case IYM2612DataSource::TimerBEnable: + return timerBStateLocking.enable; + case IYM2612DataSource::TimerAEnable: + return timerAStateLocking.enable; + case IYM2612DataSource::TimerBLoad: + return timerBStateLocking.load; + case IYM2612DataSource::TimerALoad: + return timerAStateLocking.load; + case IYM2612DataSource::TimerBData: + return timerBStateLocking.rate; + case IYM2612DataSource::TimerAData: + return timerAStateLocking.rate; + case IYM2612DataSource::TimerBCurrentCounter: + return timerBStateLocking.counter; + case IYM2612DataSource::TimerACurrentCounter: + return timerAStateLocking.counter; + case IYM2612DataSource::TimerBOverflow: + return timerBStateLocking.overflow; + case IYM2612DataSource::TimerAOverflow: + return timerAStateLocking.overflow; + case IYM2612DataSource::FeedbackData: + case IYM2612DataSource::AlgorithmData: + case IYM2612DataSource::OutputLeft: + case IYM2612DataSource::OutputRight: + case IYM2612DataSource::AMSData: + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + if(i->channelDataContext.channelNo == channelDataContext.channelNo) + { + return true; + } + } + } + break;} + case IYM2612DataSource::DetuneData: + case IYM2612DataSource::MultipleData: + case IYM2612DataSource::TotalLevelData: + case IYM2612DataSource::KeyScaleData: + case IYM2612DataSource::AttackRateData: + case IYM2612DataSource::AmplitudeModulationEnabled: + case IYM2612DataSource::DecayRateData: + case IYM2612DataSource::SustainRateData: + case IYM2612DataSource::SustainLevelData: + case IYM2612DataSource::ReleaseRateData: + case IYM2612DataSource::SSGData: + case IYM2612DataSource::SSGEnabled: + case IYM2612DataSource::SSGAttack: + case IYM2612DataSource::SSGAlternate: + case IYM2612DataSource::SSGHold: + case IYM2612DataSource::FrequencyData: + case IYM2612DataSource::BlockData: + case IYM2612DataSource::FrequencyDataChannel3: + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + std::map>::const_iterator lockedRegisterStateIterator = lockedRegisterState.find(dataID); + if(lockedRegisterStateIterator != lockedRegisterState.end()) + { + for(std::list::const_iterator i = lockedRegisterStateIterator->second.begin(); i != lockedRegisterStateIterator->second.end(); ++i) + { + if((i->operatorDataContext.channelNo == operatorDataContext.channelNo) && (i->operatorDataContext.operatorNo == operatorDataContext.operatorNo)) + { + return true; + } + } + } + break;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state) +{ + std::unique_lock lock2(registerLockMutex); + switch((IYM2612DataSource)dataID) + { + case IYM2612DataSource::RawRegister:{ + const RegisterDataContext& registerDataContext = *((RegisterDataContext*)dataContext); + rawRegisterLocking[registerDataContext.registerNo] = state; + return true;} + case IYM2612DataSource::KeyState:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + keyStateLocking[operatorDataContext.channelNo][operatorDataContext.operatorNo] = state; + return true;} + case IYM2612DataSource::TestData: + case IYM2612DataSource::LFOEnabled: + case IYM2612DataSource::LFOData: + case IYM2612DataSource::CH3Mode: + case IYM2612DataSource::TimerBReset: + case IYM2612DataSource::TimerAReset: + case IYM2612DataSource::DACData: + case IYM2612DataSource::DACEnabled:{ + if(!state) + { + lockedRegisterState.erase(dataID); + } + else + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, 0, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, lockedDataValue)); + } + return true;} + case IYM2612DataSource::TimerBEnable: + timerBStateLocking.enable = state; + return true; + case IYM2612DataSource::TimerAEnable: + timerAStateLocking.enable = state; + return true; + case IYM2612DataSource::TimerBLoad: + timerBStateLocking.load = state; + return true; + case IYM2612DataSource::TimerALoad: + timerAStateLocking.load = state; + return true; + case IYM2612DataSource::TimerBData: + timerBStateLocking.rate = state; + return true; + case IYM2612DataSource::TimerAData: + timerAStateLocking.rate = state; + return true; + case IYM2612DataSource::TimerBCurrentCounter: + timerBStateLocking.counter = state; + return true; + case IYM2612DataSource::TimerACurrentCounter: + timerAStateLocking.counter = state; + return true; + case IYM2612DataSource::TimerBOverflow: + timerBStateLocking.overflow = state; + return true; + case IYM2612DataSource::TimerAOverflow: + timerAStateLocking.overflow = state; + return true; + case IYM2612DataSource::FeedbackData: + case IYM2612DataSource::AlgorithmData: + case IYM2612DataSource::OutputLeft: + case IYM2612DataSource::OutputRight: + case IYM2612DataSource::AMSData: + case IYM2612DataSource::PMSData:{ + const ChannelDataContext& channelDataContext = *((ChannelDataContext*)dataContext); + std::list& lockedRegisterList = lockedRegisterState[dataID]; + std::list::iterator lockedRegisterListIterator = lockedRegisterList.begin(); + while(lockedRegisterListIterator != lockedRegisterList.end()) + { + if(lockedRegisterListIterator->channelDataContext.channelNo == channelDataContext.channelNo) + { + lockedRegisterList.erase(lockedRegisterListIterator); + if(lockedRegisterList.empty()) + { + lockedRegisterState.erase(dataID); + } + break; + } + ++lockedRegisterListIterator; + } + if(state) + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, &channelDataContext, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, channelDataContext, lockedDataValue)); + } + return true;} + case IYM2612DataSource::DetuneData: + case IYM2612DataSource::MultipleData: + case IYM2612DataSource::TotalLevelData: + case IYM2612DataSource::KeyScaleData: + case IYM2612DataSource::AttackRateData: + case IYM2612DataSource::AmplitudeModulationEnabled: + case IYM2612DataSource::DecayRateData: + case IYM2612DataSource::SustainRateData: + case IYM2612DataSource::SustainLevelData: + case IYM2612DataSource::ReleaseRateData: + case IYM2612DataSource::SSGData: + case IYM2612DataSource::SSGEnabled: + case IYM2612DataSource::SSGAttack: + case IYM2612DataSource::SSGAlternate: + case IYM2612DataSource::SSGHold: + case IYM2612DataSource::FrequencyData: + case IYM2612DataSource::BlockData: + case IYM2612DataSource::FrequencyDataChannel3: + case IYM2612DataSource::BlockDataChannel3:{ + const OperatorDataContext& operatorDataContext = *((OperatorDataContext*)dataContext); + std::list& lockedRegisterList = lockedRegisterState[dataID]; + std::list::iterator lockedRegisterListIterator = lockedRegisterList.begin(); + while(lockedRegisterListIterator != lockedRegisterList.end()) + { + if((lockedRegisterListIterator->operatorDataContext.channelNo == operatorDataContext.channelNo) && (lockedRegisterListIterator->operatorDataContext.operatorNo == operatorDataContext.operatorNo)) + { + lockedRegisterList.erase(lockedRegisterListIterator); + if(lockedRegisterList.empty()) + { + lockedRegisterState.erase(dataID); + } + break; + } + ++lockedRegisterListIterator; + } + if(state) + { + std::wstring lockedDataValue; + if(!ReadGenericData(dataID, &operatorDataContext, lockedDataValue)) + { + return false; + } + lockedRegisterState[dataID].push_back(RegisterLocking(dataID, operatorDataContext, lockedDataValue)); + } + return true;} + } + return false; +} + +//---------------------------------------------------------------------------------------- +//Audio logging functions +//---------------------------------------------------------------------------------------- +void YM2612::SetAudioLoggingEnabled(bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLog, wavLoggingPath, wavLoggingEnabled, state, 2, 16, (unsigned int)fmClock); + wavLoggingEnabled = state; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLogChannel[channelNo], wavLoggingChannelPath[channelNo], wavLoggingChannelEnabled[channelNo], state, 2, 16, (unsigned int)fmClock); + wavLoggingChannelEnabled[channelNo] = state; +} + +//---------------------------------------------------------------------------------------- +void YM2612::SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool state) +{ + double fmClock = (externalClockRate / fmClockDivider) / outputClockDivider; + ToggleLoggingEnabledState(wavLogOperator[channelNo][operatorNo], wavLoggingOperatorPath[channelNo][operatorNo], wavLoggingOperatorEnabled[channelNo][operatorNo], state, 1, 16, (unsigned int)fmClock); + wavLoggingOperatorEnabled[channelNo][operatorNo] = state; +} + +//---------------------------------------------------------------------------------------- +bool YM2612::ToggleLoggingEnabledState(Stream::WAVFile& wavFile, const std::wstring& fileName, bool currentState, bool newState, unsigned int channelCount, unsigned int bitsPerSample, unsigned int samplesPerSec) +{ + if(newState != currentState) + { + if(newState) + { + wavFile.SetDataFormat(channelCount, bitsPerSample, samplesPerSec); + wavFile.Open(fileName, Stream::WAVFile::OpenMode::WriteOnly, Stream::WAVFile::CreateMode::Create); + } + else + { + wavFile.Close(); + } + } + return newState; +} diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e3b1381acf6014964fc2c9d2397ff008d13d1e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/YM2612.h @@ -0,0 +1,493 @@ +/*--------------------------------------------------------------------------------------*\ +Description: +This core emulates the Yamaha YM2612(OPN2) FM synthesizer chip. Extensive hardware testing +has been done on the YM2612 in order to confirm the behaviour of the real chip, and this +emulation core has been built using those results. + +Things to do: +-Test and implement the saved results within operator circuits present in the MAME core. +-Investigate new information on the embedded DAC and implement more accurate handling of +the DAC stage. +-Revamp the way CSM overflow events are tracked. We need to record overflow events using +a cycle count rather than a timeslice value. Rounding error can introduce some 1-cycle +errors in CSM timing events in the current implementation. +-Make the render process cycle-accurate. Rather than advancing by time steps, we need to +advance by cycles. +-Try toggling SSG-EG mode off when the output is currently inverted in an SSG-EG pattern, +and see if the output inversion is also immediately disabled. +-Figure out what we're going to do with the multiplexed output stream from this chip +long-term. Do we keep it around? +-Research and implement full support for all the behaviour of the YM2612 test register +-Implement support for the busy flag. We will need to perform tests on the actual waiting +times the chip requires. The integrated YM2612 will also need to be tested in case its +waiting times are different. Note also that the DAC registers in particular must be +tested. The DAC data is the register which is most likely to be hammered, and we have no +documentation on its waiting times whatsoever, as the YM2608 didn't have it. It is likely +however that the waiting time for a DAC data write is the same as changing the left/right +flags. + +Debug options to add: +-Create a panel where each operator and channel can be either muted or disabled. Muted +only prevents sound being output to the accumulator while still allowing modulators to +modulate other operators, while disabling an operator forces it to always output 0. Also +add options to disable DAC, and disable output to either speaker for channel and master +outputs. Suggest rather than muted and disabled, simply call them disable as carrier and +disable as modulator. + +References: +-YM2608(OPNA) Application Manual, Yamaha +-Genesis Sound Software Manual, Sega Enterprises, 1992, scans by antime +-MAME Envelope Generator Implementation, Jarek Burczynski +-YM2151 Users Manual, Yamaha +-YM2413 Application Manual, Yamaha, scans by Ricardo Bittencourt +-Y8950 Application Manual, Yamaha, scans by Albert Beevendorp +-YM2203(OPN) Datasheet, Yamaha +-YM3015 Datasheet, Yamaha LSI +-YM3016 Datasheet, Yamaha LSI +-YM2612 Test Register Notes, Charles MacDonald +-YM2151 Test Register Notes, Jarek Burczynski +\*--------------------------------------------------------------------------------------*/ +#include "IYM2612.h" +#ifndef __YM2612_H__ +#define __YM2612_H__ +#include "DeviceInterface/DeviceInterface.pkg" +#include +#include +#include +#include +#include +#include +#include +#include "Device/Device.pkg" +#include "TimedBuffers/TimedBuffers.pkg" +#include "AudioStream/AudioStream.pkg" +#include "Stream/Stream.pkg" + +class YM2612 :public Device, public GenericAccessBase +{ +public: + //Constructors + YM2612(const std::wstring& aimplementationName, const std::wstring& ainstanceName, unsigned int amoduleID); + + //Interface version functions + virtual unsigned int GetIYM2612Version() const; + + //Initialization functions + virtual bool BuildDevice(); + virtual bool ValidateDevice(); + virtual void Initialize(); + void Reset(double accessTime); + + //Reference functions + virtual bool AddReference(const MarshalSupport::Marshal::In& referenceName, IBusInterface* target); + virtual void RemoveReference(IBusInterface* target); + + //Line functions + virtual unsigned int GetLineID(const MarshalSupport::Marshal::In& lineName) const; + virtual MarshalSupport::Marshal::Ret GetLineName(unsigned int lineID) const; + virtual unsigned int GetLineWidth(unsigned int lineID) const; + virtual void SetLineState(unsigned int targetLine, const Data& lineData, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual void AssertCurrentOutputLineState() const; + virtual void NegateCurrentOutputLineState() const; + + //Clock source functions + virtual unsigned int GetClockSourceID(const MarshalSupport::Marshal::In& clockSourceName) const; + virtual MarshalSupport::Marshal::Ret GetClockSourceName(unsigned int clockSourceID) const; + virtual void SetClockSourceRate(unsigned int clockInput, double clockRate, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual void TransparentSetClockSourceRate(unsigned int clockInput, double clockRate); + + //Execute functions + virtual void BeginExecution(); + virtual void SuspendExecution(); + virtual UpdateMethod GetUpdateMethod() const; + virtual bool SendNotifyUpcomingTimeslice() const; + virtual void NotifyUpcomingTimeslice(double nanoseconds); + virtual void ExecuteTimeslice(double nanoseconds); + virtual void ExecuteRollback(); + virtual void ExecuteCommit(); + + //Memory interface functions + virtual IBusInterface::AccessResult ReadInterface(unsigned int interfaceNumber, unsigned int location, Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext); + virtual IBusInterface::AccessResult WriteInterface(unsigned int interfaceNumber, unsigned int location, const Data& data, IDeviceContext* caller, double accessTime, unsigned int accessContext); + + //Savestate functions + virtual void LoadState(IHierarchicalStorageNode& node); + virtual void SaveState(IHierarchicalStorageNode& node) const; + virtual void LoadDebuggerState(IHierarchicalStorageNode& node); + virtual void SaveDebuggerState(IHierarchicalStorageNode& node) const; + + //Data read/write functions + using IGenericAccess::ReadGenericData; + using IGenericAccess::WriteGenericData; + virtual bool ReadGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue) const; + virtual bool WriteGenericData(unsigned int dataID, const DataContext* dataContext, IGenericAccessDataValue& dataValue); + + //Data locking functions + virtual bool GetGenericDataLocked(unsigned int dataID, const DataContext* dataContext) const; + virtual bool SetGenericDataLocked(unsigned int dataID, const DataContext* dataContext, bool state); + +private: + //Enumerations + enum class LineID; + enum class ClockID; + enum class AccessContext; + + //Structures + struct OperatorData + { + enum ADSRPhase + { + ADSR_ATTACK, + ADSR_DECAY, + ADSR_SUSTAIN, + ADSR_RELEASE + }; + + OperatorData() + :attenuation(10), phaseCounter(20) + {} + + Data attenuation; //10-bit + Data phaseCounter; //20-bit + ADSRPhase phase; + bool keyon; + bool csmKeyOn; + bool keyonPrevious; + bool ssgOutputInverted; + }; + struct TimerStateLocking + { + bool rate; + bool counter; + bool load; + bool enable; + bool overflow; + }; + struct RegisterLocking + { + RegisterLocking(unsigned int adataID, const std::wstring& alockedValue) + :dataID(adataID), usingChannelDataContext(false), usingOperatorDataContext(false), lockedValue(alockedValue) + {} + RegisterLocking(unsigned int adataID, const ChannelDataContext& achannelDataContext, const std::wstring& alockedValue) + :dataID(adataID), channelDataContext(achannelDataContext), usingChannelDataContext(true), usingOperatorDataContext(false), lockedValue(alockedValue) + {} + RegisterLocking(unsigned int adataID, const OperatorDataContext& aoperatorDataContext, const std::wstring& alockedValue) + :dataID(adataID), operatorDataContext(aoperatorDataContext), usingChannelDataContext(false), usingOperatorDataContext(true), lockedValue(alockedValue) + {} + + const IGenericAccess::DataContext* GetDataContext() const + { + if(usingChannelDataContext) + { + return &channelDataContext; + } + if(usingOperatorDataContext) + { + return &operatorDataContext; + } + return 0; + } + + unsigned int dataID; + bool usingChannelDataContext; + ChannelDataContext channelDataContext; + bool usingOperatorDataContext; + OperatorDataContext operatorDataContext; + const IGenericAccess::DataContext* dataContext; + std::wstring lockedValue; + }; + + //Typedefs + typedef RandomTimeAccessBuffer::AccessTarget AccessTarget; + +private: + //Execute functions + void RenderThread(); + + //General operator functions + void UpdateOperator(unsigned int channelNo, unsigned int operatorNo, bool updateEnvelopeGenerator); + unsigned int CalculateKeyCode(unsigned int block, unsigned int fnumber) const; + + //Phase generator functions + void UpdatePhaseGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset); + unsigned int GetCurrentPhase(unsigned int channelNo, unsigned int operatorNo) const; + unsigned int GetFrequencyData(unsigned int channelNo, unsigned int operatorNo, unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + unsigned int GetBlockData(unsigned int channelNo, unsigned int operatorNo, unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + + //Envelope generator functions + void UpdateEnvelopeGenerator(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset); + void SetADSRPhase(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset, OperatorData::ADSRPhase phase); + unsigned int GetOutputAttenuation(unsigned int channelNo, unsigned int operatorNo, unsigned int channelAddressOffset, unsigned int operatorAddressOffset) const; + unsigned int CalculateRate(unsigned int rateData, unsigned int rateKeyScale) const; + unsigned int CalculateRateKeyScale(unsigned int keyScaleData, unsigned int keyCode) const; + unsigned int ConvertTotalLevelToAttenuation(unsigned int totalLevel) const; + unsigned int ConvertSustainLevelToAttenuation(unsigned int sustainLevel) const; + + //Operator unit functions + unsigned int InversePow2(unsigned int num) const; + int CalculateOperator(unsigned int phase, int phaseModulation, unsigned int attenuation) const; + + //Memory interface functions + void RegisterSpecialUpdateFunction(unsigned int location, const Data& data, double accessTime, IDeviceContext* caller, unsigned int accessContext); + bool CheckForLatchedWrite(unsigned int location, const Data& data, double accessTime); + + //Timer management functions + void UpdateTimers(double timesliceProgress); + + //Raw register functions + inline Data GetRegisterData(unsigned int location, const AccessTarget& accessTarget) const; + inline void SetRegisterData(unsigned int location, const Data& data, const AccessTarget& accessTarget); + inline unsigned int GetChannelBlockAddressOffset(unsigned int channelNo) const; + inline unsigned int GetOperatorBlockAddressOffset(unsigned int channelNo, unsigned int operatorNo) const; + inline unsigned int GetAddressChannel3FrequencyBlock1(unsigned int operatorNo) const; + inline unsigned int GetAddressChannel3FrequencyBlock2(unsigned int operatorNo) const; + + //Common FM register functions + inline unsigned int GetTestData(const AccessTarget& accessTarget) const; //21H + inline void SetTestData(unsigned int data, const AccessTarget& accessTarget); + inline bool GetLFOEnabled(const AccessTarget& accessTarget) const; //22H + inline void SetLFOEnabled(bool data, const AccessTarget& accessTarget); + inline unsigned int GetLFOData(const AccessTarget& accessTarget) const; + inline void SetLFOData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTimerAData(const AccessTarget& accessTarget) const; //24H-25H + inline void SetTimerAData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTimerBData(const AccessTarget& accessTarget) const; //26H + inline void SetTimerBData(unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetCH3Mode(const AccessTarget& accessTarget) const; //27H + inline void SetCH3Mode(unsigned int data, const AccessTarget& accessTarget); + inline bool GetTimerBReset(const AccessTarget& accessTarget) const; + inline void SetTimerBReset(bool data, const AccessTarget& accessTarget); + inline bool GetTimerAReset(const AccessTarget& accessTarget) const; + inline void SetTimerAReset(bool data, const AccessTarget& accessTarget); + inline bool GetTimerBEnable(const AccessTarget& accessTarget) const; + inline void SetTimerBEnable(bool data, const AccessTarget& accessTarget); + inline bool GetTimerAEnable(const AccessTarget& accessTarget) const; + inline void SetTimerAEnable(bool data, const AccessTarget& accessTarget); + inline bool GetTimerBLoad(const AccessTarget& accessTarget) const; + inline void SetTimerBLoad(bool data, const AccessTarget& accessTarget); + inline bool GetTimerALoad(const AccessTarget& accessTarget) const; + inline void SetTimerALoad(bool data, const AccessTarget& accessTarget); + inline unsigned int GetDACData(const AccessTarget& accessTarget) const; //2AH + inline void SetDACData(unsigned int data, const AccessTarget& accessTarget); + inline bool GetDACEnabled(const AccessTarget& accessTarget) const; //2BH + inline void SetDACEnabled(bool data, const AccessTarget& accessTarget); + + //FM operator register functions + inline unsigned int GetDetuneData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //30H-3FH + inline void SetDetuneData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetMultipleData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetMultipleData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetTotalLevelData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //40H-4FH + inline void SetTotalLevelData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetKeyScaleData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //50H-5FH + inline void SetKeyScaleData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetAttackRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAttackRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetAmplitudeModulationEnabled(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //60H-6FH + inline void SetAmplitudeModulationEnabled(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline unsigned int GetDecayRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetDecayRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSustainRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //70H-7FH + inline void SetSustainRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSustainLevelData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //80H-8FH + inline void SetSustainLevelData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetReleaseRateData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetReleaseRateData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetSSGData(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; //90H-9FH + inline void SetSSGData(unsigned int operatorAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetSSGEnabled(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGEnabled(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGAttack(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGAttack(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGAlternate(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGAlternate(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetSSGHold(unsigned int operatorAddressOffset, const AccessTarget& accessTarget) const; + inline void SetSSGHold(unsigned int operatorAddressOffset, bool data, const AccessTarget& accessTarget); + + //FM channel register functions + inline unsigned int GetFrequencyData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //A0H-A7H + inline void SetFrequencyData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetBlockData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetBlockData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetFrequencyDataChannel3(unsigned int operatorNo, const AccessTarget& accessTarget) const; //A8H-AFH + inline void SetFrequencyDataChannel3(unsigned int operatorNo, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetBlockDataChannel3(unsigned int operatorNo, const AccessTarget& accessTarget) const; + inline void SetBlockDataChannel3(unsigned int operatorNo, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetFeedbackData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //B0H-B3H + inline void SetFeedbackData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetAlgorithmData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAlgorithmData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline bool GetOutputLeft(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; //B4H-B7H + inline void SetOutputLeft(unsigned int channelAddressOffset, bool data, const AccessTarget& accessTarget); + inline bool GetOutputRight(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetOutputRight(unsigned int channelAddressOffset, bool data, const AccessTarget& accessTarget); + inline unsigned int GetAMSData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetAMSData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + inline unsigned int GetPMSData(unsigned int channelAddressOffset, const AccessTarget& accessTarget) const; + inline void SetPMSData(unsigned int channelAddressOffset, unsigned int data, const AccessTarget& accessTarget); + + //Status register functions + inline Data GetStatusRegister() const; + inline void SetStatusRegister(unsigned int adata); + inline bool GetBusyFlag() const; + inline void SetBusyFlag(bool astate); + inline bool GetTimerBOverflow() const; + inline void SetTimerBOverflow(bool astate); + inline bool GetTimerAOverflow() const; + inline void SetTimerAOverflow(bool astate); + + //Audio logging functions + void SetAudioLoggingEnabled(bool state); + void SetChannelAudioLoggingEnabled(unsigned int channelNo, bool state); + void SetOperatorAudioLoggingEnabled(unsigned int channelNo, unsigned int operatorNo, bool state); + static bool ToggleLoggingEnabledState(Stream::WAVFile& wavFile, const std::wstring& fileName, bool currentState, bool newState, unsigned int channelCount, unsigned int bitsPerSample, unsigned int samplesPerSec); + +private: + //Constants + static const unsigned int channelAddressOffsets[channelCount]; + static const unsigned int operatorAddressOffsets[channelCount][operatorCount]; + static const unsigned int channel3OperatorFrequencyAddressOffsets[2][operatorCount]; + + //Envelope generator constants + static const unsigned int rateBitCount = 6; + static const unsigned int attenuationBitCount = 10; + static const unsigned int fnumDataBitCount = 11; + static const unsigned int phaseGeneratorOutputBitCount = 10; + static const unsigned int keyCodeBitCount = 5; + static const unsigned int counterShiftTable[1 << rateBitCount]; + static const unsigned int attenuationIncrementTable[1 << rateBitCount][8]; + static const unsigned int pmsBitCount = 3; + static const unsigned int phaseModIndexBitCount = 5; + static const unsigned int phaseModIncrementTable[1 << pmsBitCount][1 << (phaseModIndexBitCount - 2)]; + static const unsigned int detuneBitCount = 3; + static const unsigned int detunePhaseIncrementTable[1 << keyCodeBitCount][1 << (detuneBitCount - 1)]; + + //Operator unit constants + static const unsigned int phaseBitCount = 10; + static const unsigned int sinTableBitCount = 8; + static const unsigned int powTableBitCount = 8; + static const unsigned int sinTableOutputBitCount = 12; + static const unsigned int powTableOutputBitCount = 11; + static const unsigned int operatorOutputBitCount = 14; + static const unsigned int accumulatorOutputBitCount = 16; + unsigned int sinTable[1 << sinTableBitCount]; + unsigned int powTable[1 << powTableBitCount]; + +private: + //Clock settings + double externalClockRate; + double bexternalClockRate; + unsigned int fmClockDivider; + unsigned int egClockDivider; + unsigned int outputClockDivider; + unsigned int timerAClockDivider; + unsigned int timerBClockDivider; + + //Bus interface + mutable std::mutex lineMutex; + IBusInterface* memoryBus; + volatile bool icLineState; + bool bicLineState; + + //Registers + mutable std::mutex accessMutex; + double lastAccessTime; + RandomTimeAccessBuffer reg; + unsigned int currentReg; + unsigned int bcurrentReg; + Data status; + Data bstatus; + + //Temporary storage for fnum/block register latch behaviour + bool latchedFrequencyDataPending[channelCount]; + std::vector latchedFrequencyData; + bool latchedFrequencyDataPendingCH3[3]; + std::vector latchedFrequencyDataCH3; + bool blatchedFrequencyDataPending[channelCount]; + std::vector blatchedFrequencyData; + bool blatchedFrequencyDataPendingCH3[3]; + std::vector blatchedFrequencyDataCH3; + + //Timer status + double lastTimesliceLength; + double timersLastUpdateTime; + double timersRemainingTime; + double btimersRemainingTime; + unsigned int timerARemainingCycles; + unsigned int timerBRemainingCycles; + unsigned int btimerARemainingCycles; + unsigned int btimerBRemainingCycles; + unsigned int timerACounter; + unsigned int timerBCounter; + unsigned int btimerACounter; + unsigned int btimerBCounter; + unsigned int timerAInitialCounter; + unsigned int timerBInitialCounter; + unsigned int btimerAInitialCounter; + unsigned int btimerBInitialCounter; + bool timerAEnable; + bool timerBEnable; + bool btimerAEnable; + bool btimerBEnable; + bool timerALoad; + bool timerBLoad; + bool btimerALoad; + bool btimerBLoad; + bool irqLineState; + bool birqLineState; + + //This register records the times at which Timer A overflows. It is needed in order to + //implement CSM support. + RandomTimeAccessValue timerAOverflowTimes; + + //Render thread properties + mutable std::mutex renderThreadMutex; + mutable std::mutex timesliceMutex; + std::condition_variable renderThreadUpdate; + std::condition_variable renderThreadStopped; + bool renderThreadActive; + static const unsigned int maxPendingRenderOperationCount = 4; + bool renderThreadLagging; + std::condition_variable renderThreadLaggingStateChange; + unsigned int pendingRenderOperationCount; + std::list::Timeslice> regTimesliceList; + std::list::Timeslice> timerATimesliceList; + std::list::Timeslice> regTimesliceListUncommitted; + std::list::Timeslice> timerATimesliceListUncommitted; + double remainingRenderTime; + int egRemainingRenderCycles; + unsigned int outputSampleRate; + AudioStream outputStream; + std::vector outputBuffer; + + //Render data + unsigned int envelopeCycleCounter; + OperatorData operatorData[channelCount][operatorCount]; + int operatorOutput[channelCount][operatorCount]; + int feedbackBuffer[channelCount][2]; + int cyclesUntilLFOIncrement; + unsigned int currentLFOCounter; + + //Register locking + mutable std::mutex registerLockMutex; + bool keyStateLocking[channelCount][operatorCount]; + bool rawRegisterLocking[registerCountTotal]; + std::map> lockedRegisterState; + TimerStateLocking timerAStateLocking; + TimerStateLocking timerBStateLocking; + + //Wave logging + mutable std::mutex waveLoggingMutex; + bool wavLoggingEnabled; + bool wavLoggingChannelEnabled[channelCount]; + bool wavLoggingOperatorEnabled[channelCount][operatorCount]; + std::wstring wavLoggingPath; + std::wstring wavLoggingChannelPath[channelCount]; + std::wstring wavLoggingOperatorPath[channelCount][operatorCount]; + Stream::WAVFile wavLog; + Stream::WAVFile wavLogChannel[channelCount]; + Stream::WAVFile wavLogOperator[channelCount][operatorCount]; +}; + +#include "YM2612.inl" +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/interface.cpp b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92422e9d8c4173af5a069c03fed95944dbbad0ad --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/nemesis/interface.cpp @@ -0,0 +1,42 @@ +#include "DeviceInterface/DeviceInterface.pkg" +#include "YM2612.h" + +IDevice* GetYM2612(const wchar_t* implementationName, const wchar_t* instanceName, unsigned int moduleID) +{ + return static_cast(new YM2612(implementationName, instanceName, moduleID)); +} + +void DeleteYM2612(IDevice* device) +{ + delete static_cast(device); +} + +#ifdef EX_DLLINTERFACE +extern "C" __declspec(dllexport) unsigned int GetInterfaceVersion() +{ + return EXODUS_INTERFACEVERSION; +} + +extern "C" __declspec(dllexport) bool GetDeviceEntry(unsigned int entryNo, IDeviceInfo& entry) +{ + //Retrieve any required information from the version info table for our plugin + std::wstring copyrightText; + std::wstring commentsText; + HMODULE moduleHandle = NULL; + BOOL getModuleHandleExReturn = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)GetDeviceEntry, &moduleHandle); + if(getModuleHandleExReturn != 0) + { + std::wstring modulePath = GetModuleFilePath(moduleHandle); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_LEGALCOPYRIGHT, copyrightText); + GetModuleVersionInfoString(modulePath, VERSIONINFOPROPERTY_COMMENTS, commentsText); + } + + switch(entryNo) + { + case 0: + entry.SetDeviceSettings(GetYM2612, DeleteYM2612, L"Audio.YM2612", L"YM2612", 1, copyrightText, commentsText); + return true; + } + return false; +} +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/operator.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/operator.vhd new file mode 100644 index 0000000000000000000000000000000000000000..d58deb5965c3a1bd468ad903fd615571f506368f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/operator.vhd @@ -0,0 +1,429 @@ +--------======== operator.vhd ========-------- +-- YM2203 / YM2612 (OPN / OPN2) Operator Unit +-- Reverse engineered from YM2203 (and YM2612) die shots +-- Copyright (C) 2015 Sauraen +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- NOTICE: +-- This is an UNTESTED implementation! +-- +-- I attempted to get the overall architecture of this unit correct, +-- especially the position and number of registers in the pipeline. I +-- am confident that this is correct at a large-scale level. I am not, +-- however, confident that this description is free from errors. In +-- particular, it is very likely that one or more bits are wrong in the +-- sine or exponential tables. Also, since the chip uses both positive +-- and negative logic throughout, it is easy to miss an inverter, and +-- so there may be an error where a particular signal or variable should +-- be inverted from how it is written here. I tried my best to trace +-- adders, etc. completely, but this is not error-proof. +-- +-- The benefit of this situation is that if anyone does test an +-- implementation based on this code, the errors that may exist here are +-- likely to produce obviously wrong results. In previous implementations, +-- authors tried to get the right sound 99% of the time, but had no idea +-- of the pipelined architecture or certain other details here which became +-- important in the other cases. Thus it is much harder to make a perfect +-- implementation. + + +--------======== EXTERNALLY DEFINED ENTITIES ========-------- + +-- circular_buffer +-- A simple circular buffer, used for most of the YM2612's registers. + +library ieee; +use ieee.std_logic_1164.all; + +entity circular_buffer is + generic ( + DATA_WIDTH: positive := 8; --arbitrary default value + BUFFER_DEPTH: positive := 3; --arbitrary default value + CLEAR_ON_RESET: boolean := false + ); + port ( + clk, rst_bar: in std_logic; + din: in std_logic_vector(DATA_WIDTH-1 downto 0); + dout: out std_logic_vector(DATA_WIDTH-1 downto 0); + load: in std_logic + ); +end entity; + + +--------======== FILE BODY ========-------- + +library ieee; +use ieee.std_logic_1164.all; +use ieee.numeric_std.all; + +entity opn_operator is + generic ( + NUM_VOICES : positive := 6 + ); + port ( + -- Global control + clk, rst_bar: in std_logic; + -- Operator inputs, not all applying to the same operator at the same time + pg_phase: in unsigned(9 downto 0); + eg_atten: in unsigned(9 downto 0); + voice_fb: in unsigned(2 downto 0); + op_fb_enable: in std_logic; + op_algorithm_ctl: in std_logic_vector(5 downto 0); + test_214: in std_logic; + -- Operator output + op_result: out unsigned(13 downto 0) + ); +end entity; + +architecture arch of opn_operator is + type pipeline_delayer_t is array(natural range <>) of unsigned(9 downto 0); + signal prev1, prevprev1, prev2: unsigned(13 downto 0); + signal fm_preshift: unsigned(14 downto 0); + signal pipeline_delayer : pipeline_delayer_t(2*NUM_VOICES - 7 downto 0); + signal phaselo: unsigned(7 downto 0); + signal signbit, signbit_1, signbit_2: std_logic; + signal totalatten: unsigned(11 downto 0); + signal mantissa: unsigned(9 downto 0); + signal exponent: unsigned(3 downto 0); + signal op_result_pre: unsigned(13 downto 0); + signal op_result_internal: unsigned(13 downto 0); +begin + + + -- REGISTER/CYCLE 1 + -- Creation of phase modulation (FM) feedback signal, before shifting + make_fm_preshift: process(clk) is + variable x, y: unsigned(13 downto 0); + variable xs, ys: unsigned(14 downto 0); + begin + if rising_edge(clk) then + x := (prevprev1 and op_algorithm_ctl(0)) + or (prev2 and op_algorithm_ctl(1)) + or (op_result_internal and op_algorithm_ctl(2)); + y := (op_result_internal and op_algorithm_ctl(3)) + or (prev1 and op_algorithm_ctl(4)); + xs := x(13) & x(13 downto 0); -- sign-extend + ys := y(13) & y(13 downto 0); -- sign-extend + fm_preshift <= xs + ys; -- carry is discarded + end if; + end process; + + + -- REGISTER/CYCLE 2 (also YM2612 extra cycles 1-6) + -- Shifting of FM feedback signal, adding phase from PG to FM phase + -- In YM2203, fm_feedback is not registered at all, it is latched on the first edge + -- in add_pg_phase and the second edge is the output of add_pg_phase. In the YM2612, there + -- are 6 cycles worth of registers between the generated (non-registered) fm_feedback signal + -- and the input to add_pg_phase. + shift_fb_and_add_pg_phase: process(clk) is + variable fm_feedback: unsigned(9 downto 0); + variable fm_feedback_delayed: unsigned(9 downto 0); + variable phase: unsigned(9 downto 0); + begin + if rising_edge(clk) then + -- Shift FM feedback signal + if op_fb_enable = '1' then + fm_feedback := fm_preshift(10 downto 1); -- Bit 0 of fm_preshift is never used + else + case to_integer(voice_fb) is + when 1 => fm_feedback := + (9 downto 6 => fm_preshift(14), 5 downto 0 => fm_preshift(14 downto 9)); + when 2 => fm_feedback := + (9 downto 7 => fm_preshift(14), 6 downto 0 => fm_preshift(14 downto 8)); + when 3 => fm_feedback := + (9 downto 8 => fm_preshift(14), 7 downto 0 => fm_preshift(14 downto 7)); + when 4 => fm_feedback := + (9 => fm_preshift(14), 8 downto 0 => fm_preshift(14 downto 6)); + when 5 => fm_feedback := fm_preshift(14 downto 5); + when 6 => fm_feedback := fm_preshift(13 downto 4); + when 7 => fm_feedback := fm_preshift(12 downto 3); + when others => fm_feedback := (others => '0'); + end case; + end if; + -- Delay pipeline by 6 cycles if this is a YM2612 + if NUM_VOICES <= 3 then + fm_feedback_delayed := fm_feedback; -- Don't delay, don't register at all + else + pipeline_delayer((2*NUM_VOICES)-7) <= fm_feedback; + for i in (2*NUM_VOICES-8) downto 0 loop + pipeline_delayer(i) <= pipeline_delayer(i+1); + end loop; + fm_feedback_delayed := pipeline_delayer(0); + end if; + -- Add in PG phase + add_pg_phase: + phase := fm_feedback_delayed + pg_phase; + phaselo <= phase(7 downto 0) xor phase(8); + signbit <= phase(9); + end if; + end process; + + + -- REGISTER/CYCLE 3 + -- Sine table + sine_table: process(clk) is + type sinetable_t is array(31 downto 0) of std_logic_vector(45 downto 0); + constant sinetable: sinetable_t := ( + "0001100000100100010001000010101010101001010010", + "0001100000110100000100000010010001001101000001", + "0001100000110100000100110010001011001101100000", + "0001110000010000000000110010110001001101110010", + "0001110000010000001100000010111010001101101001", + "0001110000010100001001100010000000101101111010", + "0001110000010100001101100010010011001101011010", + "0001110000011100000101010010111000101111111100", + "0001110000111000000001110010101110001101110111", + "0001110000111000010100111000011101011010100110", + "0001110000111100011000011000111100001001111010", + "0001110000111100011100111001101011001001110111", + "0100100001010000010001011001001000111010110111", + "0100100001010100010001001001110001111100101010", + "0100100001010100010101101101111110100101000110", + "0100100011100000001000011001010110101101111001", + "0100100011100100001000101011100101001011101111", + "0100100011101100000111011010000001011010110001", + "0100110011001000000111101010000010111010111111", + "0100110011001100001011011110101110110110000001", + "0100110011101000011010111011001010001101110001", + "0100110011101101011010110101111001010100001111", + "0111000010000001010111000101010101010110010111", + "0111000010000101010111110111110101010010111011", + "0111000010110101101000101100001000010000011001", + "0111010010011001100100011110100100010010010010", + "0111010010111010100101100101000000110100100011", + "1010000010011010101101011101100001110010011010", + "1010000010111111111100100111010100010000111001", + "1010010111110100110010001100111001010110100000", + "1011010111010011111011011110000100110010100001", + "1110011011110001111011100111100001110110100111" + ); + variable sta : std_logic_vector(45 downto 0); + variable stb : std_logic_vector(18 downto 0); + variable stf, stg : std_logic_vector(10 downto 0); + variable logsin : unsigned(11 downto 0); + variable subtresult : unsigned(10 downto 0); + variable atten_internal : unsigned(11 downto 0); + + begin + if rising_edge(clk) then + -- Main sine table body + sta := sinetable(to_integer(phaselo(5 downto 1))); + -- 2-bit row chooser + case std_logic_vector(phaselo(7 downto 6)) is + when "00" => stb := + "0000000000" & sta(29) & sta(25) + & "00" & sta(18) & sta(14) + & "0" & sta(7) & sta(3); + when "01" => stb := + "000000" & sta(37) & sta(34) + & "00" & sta(28) & sta(24) + & "00" & sta(17) & sta(13) + & sta(10) & sta(6) & sta(2); + when "10" => stb := + "00" & sta(43) & sta(41) + & "00" & sta(36) & sta(33) + & "00" & sta(27) & sta(23) + & "0" & sta(20) & sta(16) + & sta(12) & sta(9) & sta(5) & sta(1); + when others => stb := + sta(45) & sta(44) & sta(42) & sta(40) + & sta(39) & sta(38) & sta(35) & sta(32) + & sta(31) & sta(30) & sta(26) & sta(22) + & sta(21) & sta(19) & sta(15) & sta(11) + & sta(8) & sta(4) & sta(0); + end case; + -- Fixed value to sum + stf := stb(18 downto 15) & stb(12 downto 11) & stb(8 downto 7) & stb(4 downto 3) & stb(0); + -- Gated value to sum; bit 14 is indeed used twice + stg := "00" & stb(14) & stb(14 downto 13) & stb(10 downto 9) & stb(6 downto 5) & stb(2 downto 1); + stg := stg and phaselo(0); + -- Sum to produce final logsin value + logsin := unsigned('0' & stf) + unsigned('0' & stg); -- Carry-out of 11-bit addition becomes 12th bit + -- Invert-subtract logsin value from EG attenuation value, with inverted carry + -- In the actual chip, the output of the above logsin sum is already inverted. + -- The two LSBs go through inverters (so they're non-inverted); the eg_atten signal goes through inverters. + -- The adder is normal except the carry-in is 1. It's a 10-bit adder. + -- The outputs are inverted outputs, including the carry bit. + --subtresult := not (('0' & not eg_atten) - ('1' & logsin(11 downto 2))); + -- After a little pencil-and-paper, turns out this is equivalent to a regular adder! + subtresult := ('0' & eg_atten) + ('0' & logsin(11 downto 2)); + -- Place all but carry bit into result; also two LSBs of logsin + atten_internal := subtresult(9 downto 0) & logsin(1 downto 0); + -- If addition overflowed, make it the largest value (saturate) + atten_internal := atten_internal or subtresult(10); + totalatten <= atten_internal; + signbit_1 <= signbit; + end if; + end process; + + + -- REGISTER/CYCLE 4 + -- Exponential table + exp_table: process(clk) is + type exptable_t is array(31 downto 0) of std_logic_vector(44 downto 0); + constant exptable: exptable_t := ( + "101110011001000000110100010111111000111111011", + "110011011100001100000011111001011000111111011", + "010110111001011101110101101111000000111111011", + "011010101010000001110110000111000000111111011", + "110110101010000001010001100001000000111111011", + "101110111001111000110110111010101010010111011", + "000000110000110100111001011110111011010011011", + "011110111001100100010110100100111011010011011", + "010110111000101000110101100010110011010011011", + "001010111001010011110011001110000011010011011", + "101010011001011011010100111101000111000011011", + "110110011000011111110011110011001111100001011", + "101111011101100111100100000011001111100001011", + "100010101010101011010111101101111100100001011", + "110010011001100011010000001101111100100001011", + "101010111000011100110101011010110100100001011", + "111011011101010100100010110000110100100001011", + "100011011100111000000001010100100100100001011", + "110011011101110000000110101110001100000001011", + "101011111100001110100001101000001100000001011", + "101010011001000110110110010001001000000001011", + "101011011100101010000101110111010001000101110", + "110011111101100010000010011111110011001100110", + "100011011100001100100111001001110011001100110", + "010101011100000000100100101011111011101110100", + "000111011101101000000011000111101011101110100", + "010110011000100100010100110100101011101110100", + "000010011001000110010011011000001011101110100", + "100011011100101010100000011010000011101110100", + "110111011101100010100111100100010010101110100", + "000000001001000100110000000100010010101110100", + "000011011100101000000001100010011010001110100" + ); + variable eta : std_logic_vector(44 downto 0); + variable etb : std_logic_vector(12 downto 0); + variable etf, etg : std_logic_vector(9 downto 0); + + begin + if rising_edge(clk) then + -- Main sine table body + eta := exptable(to_integer(totalatten(5 downto 1))); + -- 2-bit row chooser + case std_logic_vector(totalatten(7 downto 6)) is + when "00" => etb := "1" & eta(43) & eta(40) & eta(36) & eta(32) & eta(28) + & eta(24) & "1" & eta(18) & eta(14) & eta(10) & eta(7) & eta(3); + when "01" => etb := eta(44) & eta(42) & eta(39) & eta(35) & eta(31) & eta(27) + & eta(23) & "1" & eta(17) & eta(13) & "0" & eta(6) & eta(2); + when "10" => etb := "0" & eta(41) & eta(38) & eta(34) & eta(30) & eta(26) + & eta(22) & eta(19) & eta(16) & eta(12) & eta(9) & eta(5) & eta(1); + when others => etb := "00" & eta(37) & eta(33) & eta(29) & eta(25) + & eta(21) & eta(20) & eta(15) & eta(11) & eta(8) & eta(4) & eta(0); + end case; + -- Fixed value to sum + etf := etb(12 downto 6) & etb(4) & etb(3) & etb(0); + -- Gated value to sum + etg := "0000000" & etb(5) & etb(2) & etb(1); + etg := etg and not totalatten(0); + --RESULT + mantissa <= unsigned(etf) + unsigned(etg); --carry-out discarded + exponent <= totalatten(11 downto 8); + signbit_2 <= signbit_1; + end if; + end process; + + -- REGISTER/CYCLE 5 + -- Floating-point to integer, and incorporating sign bit + shift_and_flip: process(clk) is + variable shifter : unsigned(12 downto 0); + variable result : unsigned(13 downto 0); + begin + if rising_edge(clk) then + -- Two-stage shifting of mantissa by exponent + shifter := "001" & mantissa; + case std_logic_vector(exponent(1 downto 0)) is + when "00" => shifter := '0' & shifter(12 downto 1); -- LSB discarded + -- when "01" => shifter := shifter; -- no change + when "10" => shifter := shifter(11 downto 0) & '0'; + when "11" => shifter := shifter(10 downto 0) & "00"; + when others => null; + end case; + case std_logic_vector(exponent(3 downto 2)) is + when "00" => shifter := "000000000000" & shifter(12); + when "01" => shifter := "00000000" & shifter(12 downto 8); + when "10" => shifter := "0000" & shifter(12 downto 4); + -- when "11" => shifter := shifter; -- no change + when others => null; + end case; + result := test_214 & shifter; -- Introduce test bit as MSB + -- 2's complement + result := result xor signbit_2; + result := result + signbit_2; -- Carry-out discarded + op_result_pre <= result; + end if; + end process; + + + -- REGISTER/CYCLE 6 + -- Extra register, take output after here + register_output: process(clk) is begin + if rising_edge(clk) then + op_result_internal <= op_result_pre; + end if; + end process; + + op_result <= op_result_internal; + + + -- Circular buffers for old operator output values + -- These latch op_result_internal on the clock after + -- it is generated in register_output, and they provide + -- their output (prev1, etc.) on the same cycle as + -- op_result_internal is available. + prev1_buffer: entity circular_buffer + generic map( + DATA_WIDTH => 14, + BUFFER_DEPTH => NUM_VOICES, + CLEAR_ON_RESET => false) + port map( + clk => clk, + rst_bar => rst_bar, + din => std_logic_vector(op_result_internal), + std_logic_vector(dout) => prev1, + load => op_algorithm_ctl(5) + ); + + prevprev1_buffer: entity circular_buffer + generic map( + DATA_WIDTH => 14, + BUFFER_DEPTH => NUM_VOICES, + CLEAR_ON_RESET => false) + port map( + clk => clk, + rst_bar => rst_bar, + din => std_logic_vector(prev1), + std_logic_vector(dout) => prevprev1, + load => op_algorithm_ctl(5) + ); + + prev2_buffer: entity circular_buffer + generic map( + DATA_WIDTH => 14, + BUFFER_DEPTH => NUM_VOICES, + CLEAR_ON_RESET => false) + port map( + clk => clk, + rst_bar => rst_bar, + din => std_logic_vector(op_result_internal), + std_logic_vector(dout) => prev2, + load => op_algorithm_ctl(0) + ); + + +end architecture; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/vgmspec170.txt b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/vgmspec170.txt new file mode 100644 index 0000000000000000000000000000000000000000..70192e8d58c14f41d150d070e3b72be57d4e78d7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/vgmspec170.txt @@ -0,0 +1,734 @@ +VGM Spec v1.70 +============== +VGM (Video Game Music) is a sample-accurate sound logging format for the Sega +Master System, the Sega Game Gear and possibly many other machines (e.g. Sega +Genesis). + +The normal file extension is .vgm but files can also be GZip compressed into +.vgz files. However, a VGM player should attempt to support compressed and +uncompressed files with either extension. (ZLib's GZIO library makes this +trivial to implement.) + +The format starts with a 256 byte header: + + 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +0x00 ["Vgm " ident ][EoF offset ][Version ][SN76489 clock ] +0x10 [YM2413 clock ][GD3 offset ][Total # samples][Loop offset ] +0x20 [Loop # samples ][Rate ][SN FB ][SNW][SF][YM2612 clock ] +0x30 [YM2151 clock ][VGM data offset][Sega PCM clock ][SPCM Interface ] +0x40 [RF5C68 clock ][YM2203 clock ][YM2608 clock ][YM2610/B clock ] +0x50 [YM3812 clock ][YM3526 clock ][Y8950 clock ][YMF262 clock ] +0x60 [YMF278B clock ][YMF271 clock ][YMZ280B clock ][RF5C164 clock ] +0x70 [PWM clock ][AY8910 clock ][AYT][AY Flags ][VM] *** [LB][LM] +0x80 [GB DMG clock ][NES APU clock ][MultiPCM clock ][uPD7759 clock ] +0x90 [OKIM6258 clock ][OF][KF][CF] *** [OKIM6295 clock ][K051649 clock ] +0xA0 [K054539 clock ][HuC6280 clock ][C140 clock ][K053260 clock ] +0xB0 [Pokey clock ][QSound clock ] *** *** *** *** [Extra Hdr ofs ] +0xC0 *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** +0xD0 *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** +0xE0 *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** +0xF0 *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** + +- Unused space (marked with *) is reserved for future expansion, and must be + zero. +- All integer values are *unsigned* and written in "Intel" byte order (Little + Endian), so for example 0x12345678 is written as 0x78 0x56 0x34 0x12. +- All pointer offsets are written as relative to the current position in the + file, so for example the GD3 offset at 0x14 in the header is the file + position of the GD3 tag minus 0x14. +- All header sizes are valid for all versions from 1.50 on, as long as header + has at least 64 bytes. If the VGM data starts at an offset that is lower + than 0x100, all overlapping header bytes have to be handled as they were + zero. +- VGMs run with a rate of 44100 samples per second. All sample values use this + unit. + +0x00: "Vgm " (0x56 0x67 0x6d 0x20) file identification (32 bits) +0x04: Eof offset (32 bits) + Relative offset to end of file (i.e. file length - 4). + This is mainly used to find the next track when concatanating + player stubs and multiple files. +0x08: Version number (32 bits) + Version number in BCD-Code. e.g. Version 1.70 is stored as 0x00000170. + This is used for backwards compatibility in players, and defines which + header values are valid. +0x0C: SN76489 clock (32 bits) + Input clock rate in Hz for the SN76489 PSG chip. A typical value is + 3579545. It should be 0 if there is no PSG chip used. + Note: Bit 31 (0x80000000) is used on combination with the dual-chip-bit + to indicate that this is a T6W28. (PSG variant used in NeoGeo Pocket) +0x10: YM2413 clock (32 bits) + Input clock rate in Hz for the YM2413 chip. A typical value is 3579545. + It should be 0 if there is no YM2413 chip used. +0x14: GD3 offset (32 bits) + Relative offset to GD3 tag. 0 if no GD3 tag. + GD3 tags are descriptive tags similar in use to ID3 tags in MP3 files. + See the GD3 specification for more details. The GD3 tag is usually + stored immediately after the VGM data. +0x18: Total # samples (32 bits) + Total of all wait values in the file. +0x1C: Loop offset (32 bits) + Relative offset to loop point, or 0 if no loop. + For example, if the data for the one-off intro to a song was in bytes + 0x0040-0x3FFF of the file, but the main looping section started at + 0x4000, this would contain the value 0x4000-0x1C = 0x00003FE4. +0x20: Loop # samples (32 bits) + Number of samples in one loop, or 0 if there is no loop. + Total of all wait values between the loop point and the end of + the file. +[VGM 1.01 additions:] +0x24: Rate (32 bits) + "Rate" of recording in Hz, used for rate scaling on playback. It is + typically 50 for PAL systems and 60 for NTSC systems. It should be set + to zero if rate scaling is not appropriate - for example, if the game + adjusts its music engine for the system's speed. + VGM 1.00 files will have a value of 0. +[VGM 1.10 additions:] +0x28: SN76489 feedback (16 bits) + The white noise feedback pattern for the SN76489 PSG. Known values are: + 0x0009 Sega Master System 2/Game Gear/Mega Drive + (SN76489/SN76496 integrated into Sega VDP chip) + 0x0003 Sega Computer 3000H, BBC Micro + (SN76489AN) + 0x0006 SN76494, SN76496 + For version 1.01 and earlier files, the feedback pattern should be + assumed to be 0x0009. If the PSG is not used then this may be omitted + (left at zero). +0x2A: SN76489 shift register width (8 bits) + The noise feedback shift register width, in bits. Known values are: + 16 Sega Master System 2/Game Gear/Mega Drive + (SN76489/SN76496 integrated into Sega VDP chip) + 15 Sega Computer 3000H, BBC Micro + (SN76489AN) + For version 1.01 and earlier files, the shift register width should be + assumed to be 16. If the PSG is not used then this may be omitted (left + at zero). +[VGM 1.51 additions:] +0x2B: SN76489 Flags (8 bits) + Misc flags for the SN76489. Most of them don't make audible changes and + can be ignored, if the SN76489 emulator lacks the features. + bit 0 frequency 0 is 0x400 + bit 1 output negate flag + bit 2 stereo on/off (on when bit clear) + bit 3 /8 Clock Divider on/off (on when bit clear) + bit 4-7 reserved (must be zero) + For version 1.51 and earlier files, all the flags should not be set. + If the PSG is not used then this may be omitted (left at zero). +[VGM 1.10 additions:] +0x2C: YM2612 clock (32 bits) + Input clock rate in Hz for the YM2612 chip. A typical value is 7670454. + It should be 0 if there us no YM2612 chip used. + For version 1.01 and earlier files, the YM2413 clock rate should be + used for the clock rate of the YM2612. +0x30: YM2151 clock (32 bits) + Input clock rate in Hz for the YM2151 chip. A typical value is 3579545. + It should be 0 if there us no YM2151 chip used. + For version 1.01 and earlier files, the YM2413 clock rate should be + used for the clock rate of the YM2151. +[VGM 1.50 additions:] +0x34: VGM data offset (32 bits) + Relative offset to VGM data stream. + If the VGM data starts at absolute offset 0x40, this will contain + value 0x0000000C. For versions prior to 1.50, it should be 0 and the + VGM data must start at offset 0x40. +[VGM 1.51 additions:] +0x38: Sega PCM clock (32 bits) + Input clock rate in Hz for the Sega PCM chip. A typical value is + 4000000. It should be 0 if there is no Sega PCM chip used. +0x3C: Sega PCM interface register (32 bits) + The interface register for the Sega PCM chip. It should be 0 if there + is no Sega PCM chip used. +0x40: RF5C68 clock (32 bits) + Input clock rate in Hz for the RF5C68 PCM chip. A typical value is + 12500000. It should be 0 if there is no RF5C68 chip used. +0x44: YM2203 clock (32 bits) + Input clock rate in Hz for the YM2203 chip. A typical value is 3000000. + It should be 0 if there is no YM2203 chip used. +0x48: YM2608 clock (32 bits) + Input clock rate in Hz for the YM2608 chip. A typical value is 8000000. + It should be 0 if there is no YM2608 chip used. +0x4C: YM2610/YM2610B clock (32 bits) + Input clock rate in Hz for the YM2610/B chip. A typical value is + 8000000. It should be 0 if there is no YM2610/B chip used. + Note: Bit 31 is used to set whether it is an YM2610 or an YM2610B chip. + If bit 31 is set it is an YM2610B, if bit 31 is clear it is an YM2610. +0x50: YM3812 clock (32 bits) + Input clock rate in Hz for the YM3812 chip. A typical value is 3579545. + It should be 0 if there is no YM3812 chip used. +0x54: YM3526 clock (32 bits) + Input clock rate in Hz for the YM3526 chip. A typical value is 3579545. + It should be 0 if there is no YM3526 chip used. +0x58: Y8950 clock (32 bits) + Input clock rate in Hz for the Y8950 chip. A typical value is 3579545. + It should be 0 if there is no Y8950 chip used. +0x5C: YMF262 clock (32 bits) + Input clock rate in Hz for the YMF262 chip. A typical value is + 14318180. It should be 0 if there is no YMF262 chip used. +0x60: YMF278B clock (32 bits) + Input clock rate in Hz for the YMF278B chip. A typical value is + 33868800. It should be 0 if there is no YMF278B chip used. +0x64: YMF271 clock (32 bits) + Input clock rate in Hz for the YMF271 chip. A typical value is + 16934400. It should be 0 if there is no YMF271 chip used. +0x68: YMZ280B clock (32 bits) + Input clock rate in Hz for the YMZ280B chip. A typical value is + 16934400. It should be 0 if there is no YMZ280B chip used. +0x6C: RF5C164 clock (32 bits) + Input clock rate in Hz for the RF5C164 PCM chip. A typical value is + 12500000. It should be 0 if there is no RF5C164 chip used. +0x70: PWM clock (32 bits) + Input clock rate in Hz for the PWM chip. A typical value is + 23011361. It should be 0 if there is no PWM chip used. +0x74: AY8910 clock (32 bits) + Input clock rate in Hz for the AY8910 chip. A typical value is 1789750. + It should be 0 if there is no AY8910 chip used. +0x78: AY8910 Chip Type (8 bits) + Defines the exact type of AY8910. The values are: + 0x00 - AY8910 + 0x01 - AY8912 + 0x02 - AY8913 + 0x03 - AY8930 + 0x10 - YM2149 + 0x11 - YM3439 + 0x12 - YMZ284 + 0x13 - YMZ294 + If the AY8910 is not used then this may be omitted (left at zero). +0x79: AY8910 Flags (8 bits) + Misc flags for the AY8910. Default is 0x01. + For additional description see ay8910.h in MAME source code. + bit 0 Legacy Output + bit 1 Single Output + bit 2 Discrete Output + bit 3 RAW Output + bit 4-7 reserved (must be zero) + If the AY8910 is not used then this may be omitted (left at zero). +0x7A: YM2203/AY8910 Flags (8 bits) + Misc flags for the AY8910. This one is specific for the AY8910 that's + connected with/part of the YM2203. +0x7B: YM2608/AY8910 Flags (8 bits) + Misc flags for the AY8910. This one is specific for the AY8910 that's + connected with/part of the YM2608. +[VGM 1.60 additions:] +0x7C: Volume Modifier (8 bits) + Volume = 2 ^ (VolumeModifier / 0x20) where VolumeModifier is a number + from -63 to 192 (-63 = 0xC1, 0 = 0x00, 192 = 0xC0). Also the value -63 + gets replaces with -64 in order to get make factor of 0.25 possible. + Therefore the volume can reach levels between 0.25 and 64. + Default is 0, which is equal to a factor of 1 or 100%. + Note: Players should support the Volume Modifier in v1.50 files and + higher. This way MegaDrive VGMs can use the Volume Modifier without + breaking compatibility with old players. +0x7D: reserved + Reserved byte for future use. It must be 0. +0x7E: Loop Base (8 bits) + Modifies the number of loops that are played before the playback ends. + Set this value to eg. 1 to reduce the number of played loops by one. + This is useful, if the song is looped twice in the vgm, because there + are minor differences between the first and second loop and the song + repeats just the second loop. + The resulting number of loops that are played is calculated as + following: NumLoops = NumLoopsModified - LoopBase + Default is 0. Negative numbers are possible (80h...FFh = -128...-1) +[VGM 1.51 additions:] +0x7F: Loop Modifier (8 bits) + Modifies the number of loops that are played before the playback ends. + You may want to use this, e.g. if a tune has a very short, but non- + repetive loop (then set it to 0x20 double the loop number). + The resulting number of loops that are played is calculated as + following: NumLoops = ProgramNumLoops * LoopModifier / 0x10 + Default is 0, which is equal to 0x10. +[VGM 1.61 additions:] +0x80: GameBoy DMG clock (32 bits) + Input clock rate in Hz for the GameBoy DMG chip, LR35902. A typical + value is 4194304. It should be 0 if there is no GB DMG chip used. +0x84: NES APU clock (32 bits) + Input clock rate in Hz for the NES APU chip, N2A03. A typical value is + 1789772. It should be 0 if there is no NES APU chip used. +0x88: MultiPCM clock (32 bits) + Input clock rate in Hz for the MultiPCM chip. A typical value is + 8053975. It should be 0 if there is no MultiPCM chip used. +0x8C: uPD7759 clock (32 bits) + Input clock rate in Hz for the uPD7759 chip. A typical value is 640000. + It should be 0 if there is no uPD7759 chip used. +0x90: OKIM6258 clock (32 bits) + Input clock rate in Hz for the OKIM6258 chip. A typical value is + 4000000. It should be 0 if there is no OKIM6258 chip used. +0x94: OKIM6258 Flags (8 bits) + Misc flags for the OKIM6258. Default is 0x00. + bit 0-1 Clock Divider (clock dividers are 1024, 768, 512, 512) + bit 2 3/4-bit ADPCM select (default is 4-bit, doesn't work currently) + bit 3 10/12-bit Output (default is 10-bit) + bit 4-7 reserved (must be zero) + If the OKIM6258 is not used then this may be omitted (left at zero). +0x95: K054539 Flags (8 bits) + Misc flags for the K054539. Default is 0x01. + See also k054539.h in MAME source code. + bit 0 Reverse Stereo + bit 1 Disable Reverb + bit 2 Update at KeyOn + bit 3-7 reserved (must be zero) + If the K054539 is not used then this may be omitted (left at zero). +0x96: C140 Chip Type (8 bits) + Defines the exact type of C140 and its banking method. The values are: + 0x00 - C140, Namco System 2 + 0x01 - C140, Namco System 21a + 0x02 - C140, Namco System 21b + 0x03 - 219 ASIC, Namco NA-1/2 + If the C140 is not used then this may be omitted (left at zero). +0x97: reserved + Reserved byte for future use. It must be 0. +0x98: OKIM6295 clock (32 bits) + Input clock rate in Hz for the OKIM6295 chip. A typical value is + 4000000. It should be 0 if there is no OKIM6295 chip used. +0x9C: K051649 clock (32 bits) + Input clock rate in Hz for the K051649 chip. A typical value is + 1500000. It should be 0 if there is no K051649 chip used. +0xA0: K054539 clock (32 bits) + Input clock rate in Hz for the K054539 chip. A typical value is 48000. + It should be 0 if there is no K054539 chip used. +0xA4: HuC6280 clock (32 bits) + Input clock rate in Hz for the HuC6280 chip. A typical value is + 3579545. It should be 0 if there is no HuC6280 chip used. +0xA8: C140 clock (32 bits) + Input clock rate in Hz for the C140 chip. A typical value is 21390. + It should be 0 if there is no C140 chip used. +0xAC: K053260 clock (32 bits) + Input clock rate in Hz for the K053260 chip. A typical value is + 3579545. It should be 0 if there is no K053260 chip used. +0xB0: Pokey clock (32 bits) + Input clock rate in Hz for the Pokey chip. A typical value is 1789772. + It should be 0 if there is no Pokey chip used. +0xB4: QSound clock (32 bits) + Input clock rate in Hz for the QSound chip. A typical value is 4000000. + It should be 0 if there is no QSound chip used. +0xB8: reserved + Reserved bytes for future use. They must be 0. +[VGM 1.70 additions:] +0xBC: Extra Header Offset + Relative offset to the extra header or 0 if no extra header is present. +0xC0: reserved + Reserved bytes for future use. They must be 0. + + +Starting at the location specified by the VGM data offset (or, offset 0x40 for +file versions below 1.50) is found a sequence of commands containing data +written to the chips or timing information. A command is one of: + + 0x4F dd : Game Gear PSG stereo, write dd to port 0x06 + 0x50 dd : PSG (SN76489/SN76496) write value dd + 0x51 aa dd : YM2413, write value dd to register aa + 0x52 aa dd : YM2612 port 0, write value dd to register aa + 0x53 aa dd : YM2612 port 1, write value dd to register aa + 0x54 aa dd : YM2151, write value dd to register aa + 0x55 aa dd : YM2203, write value dd to register aa + 0x56 aa dd : YM2608 port 0, write value dd to register aa + 0x57 aa dd : YM2608 port 1, write value dd to register aa + 0x58 aa dd : YM2610 port 0, write value dd to register aa + 0x59 aa dd : YM2610 port 1, write value dd to register aa + 0x5A aa dd : YM3812, write value dd to register aa + 0x5B aa dd : YM3526, write value dd to register aa + 0x5C aa dd : Y8950, write value dd to register aa + 0x5D aa dd : YMZ280B, write value dd to register aa + 0x5E aa dd : YMF262 port 0, write value dd to register aa + 0x5F aa dd : YMF262 port 1, write value dd to register aa + 0x61 nn nn : Wait n samples, n can range from 0 to 65535 (approx 1.49 + seconds). Longer pauses than this are represented by multiple + wait commands. + 0x62 : wait 735 samples (60th of a second), a shortcut for + 0x61 0xdf 0x02 + 0x63 : wait 882 samples (50th of a second), a shortcut for + 0x61 0x72 0x03 + 0x64 cc nn nn : override length of 0x62/0x63 + cc - command (0x62/0x63) + nn - delay in samples + [Note: Not yet implemented. Am I really sure about this?] + 0x66 : end of sound data + 0x67 ... : data block: see below + 0x68 ... : PCM RAM write: see below + 0x7n : wait n+1 samples, n can range from 0 to 15. + 0x8n : YM2612 port 0 address 2A write from the data bank, then wait + n samples; n can range from 0 to 15. Note that the wait is n, + NOT n+1. (Note: Written to first chip instance only.) + 0x90-0x95 : DAC Stream Control Write: see below + 0xA0 aa dd : AY8910, write value dd to register aa + 0xB0 aa dd : RF5C68, write value dd to register aa + 0xB1 aa dd : RF5C164, write value dd to register aa + 0xB2 ad dd : PWM, write value ddd to register a (d is MSB, dd is LSB) + 0xB3 aa dd : GameBoy DMG, write value dd to register aa + 0xB4 aa dd : NES APU, write value dd to register aa + 0xB5 aa dd : MultiPCM, write value dd to register aa + 0xB6 aa dd : uPD7759, write value dd to register aa + 0xB7 aa dd : OKIM6258, write value dd to register aa + 0xB8 aa dd : OKIM6295, write value dd to register aa + 0xB9 aa dd : HuC6280, write value dd to register aa + 0xBA aa dd : K053260, write value dd to register aa + 0xBB aa dd : Pokey, write value dd to register aa + 0xC0 aaaa dd : Sega PCM, write value dd to memory offset aaaa + 0xC1 aaaa dd : RF5C68, write value dd to memory offset aaaa + 0xC2 aaaa dd : RF5C164, write value dd to memory offset aaaa + 0xC3 cc aaaa : MultiPCM, write set bank offset aaaa to channel cc + 0xC4 mmll rr : QSound, write value mmll to register rr + (mm - data MSB, ll - data LSB) + 0xD0 pp aa dd : YMF278B port pp, write value dd to register aa + 0xD1 pp aa dd : YMF271 port pp, write value dd to register aa + 0xD2 pp aa dd : SCC1 port pp, write value dd to register aa + 0xD3 pp aa dd : K054539 write value dd to register ppaa + 0xD4 pp aa dd : C140 write value dd to register ppaa + 0xE0 dddddddd : seek to offset dddddddd (Intel byte order) in PCM data bank + +Some ranges are reserved for future use, with different numbers of operands: + + 0x30..0x3F dd : one operand, reserved for future use + Note: used for dual-chip support (see below) + 0x40..0x4E dd dd : two operands, reserved for future use + Note: was one operand only til v1.60 + 0xA1..0xAF dd dd : two operands, reserved for future use + Note: used for dual-chip support (see below) + 0xBC..0xBF dd dd : two operands, reserved for future use + 0xC5..0xCF dd dd dd : three operands, reserved for future use + 0xD5..0xDF dd dd dd : three operands, reserved for future use + 0xE1..0xFF dd dd dd dd : four operands, reserved for future use + +On encountering these, the correct number of bytes should be skipped. + + +Data blocks +----------- +VGM command 0x67 specifies a data block. These are used to store large amounts +of data, which can be used in parallel with the normal VGM data stream. The +data block format is: + + 0x67 0x66 tt ss ss ss ss (data) + +where: + 0x67 = VGM command + 0x66 = compatibility command to make older players stop parsing the stream + tt = data type + ss ss ss ss (32 bits) = size of data, in bytes + (data) = data, of size previously specified + +Data blocks of recorded streams, if present, should be at the very start of the +VGM data. Multiple data blocks expand the data bank. (The start offset and +length of the block in the data bank should be saved for command 0x95.) +Because data blocks can happen anywhere in the stream, players must be able to +parse data blocks anywhere in the stream. + +The data block type specifies what type of data it contains. Currently defined +types are: + +00..3F : data of recorded streams (uncompressed) +40..7E : data of recorded streams (compressed) + data block format for compressed streams: + tt (8 bits) = compression type + 00 - n-Bit-Compression + 01 - DPCM-Compression + ss ss ss ss (32 bits) = size of uncompressed data + (attr) = attribute bytes used by the decompression-algorithm + n-Bit-Compression: + bd (8 bits) = Bits decompressed + bc (8 bits) = Bits compressed + st (8 bits) = compression sub-type + 00 - copy (high bits aren't used) + 01 - shift left (low bits aren't used) + 02 - use table (uses a decompression table) + aa aa (16 bits) = value that is added (ignored if table is used) + DPCM-Compression: + bd (8 bits) = Bits decompressed + bc (8 bits) = Bits compressed + st (8 bits) = [reserved for future use] + aa aa (16 bits) = start value + (data) = compressed data, of size (block size - 0x0A - attr size) +7F : Compression Table + tt (8 bits) = compression type (see above) + st (8 bits) = compression sub-type (see above) + bd (8 bits) = Bits decompressed + bc (8 bits) = Bits compressed + cc cc (16 bits) = number of following values (with each of size + ceil(bd / 8)) + (data) = table data, of size (block size - 0x06) +80..BF : ROM/RAM Image dumps (contain usually samples) + data block format for ROM dumps: + rr rr rr rr (32 bits) = size of the entire ROM + ss ss ss ss (32 bits) = start address of data + (data) = ROM data, of size (block size - 0x08) + The size of the VGM can be decreased a lot by saving only the used parts + of the ROM. This is done by saving multiple small ROM data blocks. + The start address is the ROM offset where the data will be written, the + ROM size is used to allocate space for the ROM (and some chips rely on it). +C0..FF : RAM writes + data block format for direct RAM writes: + ss ss (16 bits) = start address of data (affected by a chip's registers) + (data) = ROM data, of size (block size - 0x02) + +00 = YM2612 PCM data for use with associated commands +01 = RF5C68 PCM data for use with associated commands +02 = RF5C164 PCM data for use with associated commands +03 = PWM PCM data for use with associated commands +40..7E = same as 00..3E, just compressed +80 = Sega PCM ROM data +81 = YM2608 DELTA-T ROM data +82 = YM2610 ADPCM ROM data +83 = YM2610 DELTA-T ROM data +84 = YMF278B ROM data +85 = YMF271 ROM data +86 = YMZ280B ROM data +87 = YMF278B RAM data +88 = Y8950 DELTA-T ROM data +89 = MultiPCM ROM data +8A = uPD7759 ROM data +8B = OKIM6295 ROM data +8C = K054539 ROM data +8D = C140 ROM data +8E = K053260 ROM data +8F = Q-Sound ROM data +C0 = RF5C68 RAM write +C1 = RF5C164 RAM write +C2 = NES APU RAM write + +All unknown types must be skipped by the player. + + +PCM RAM writes +-------------- +VGM command 0x68 specifies a PCM RAM write. These are used to write data from +data blocks to the RAM of a PCM chip. The data block format is: + + 0x68 0x66 cc oo oo oo dd dd dd ss ss ss + +where: + 0x68 = VGM command + 0x66 = compatibility command to make older players stop parsing the stream + cc = chip type (see data block types 00..3F) + oo oo oo (24 bits) = read offset in data block + dd dd dd (24 bits) = write offset in chip's ram (affected by chip's + registers) + ss ss ss (24 bits) = size of data, in bytes + Since size can't be zero, a size of 0 bytes means 0x0100 0000 bytes. + +All unknown types must be skipped by the player. + + +DAC Stream Control Write +------------------------ +VGM commands 0x90 to 0x95 specify writes to the DAC Stream Control Driver. +These are used to stream data from data blocks to the chips via chip writes. +To use it you must: +1. Setup the Stream (set chip type and command) - this activates the stream +2. Set the Stream Data Bank +3. Set the Stream Frequency +4. Now you can start the stream, change its frequency, start it again, stop it, + etc ... + +There are the following commands: + +Note: Stream ID 0xFF is reserved and ignored unless noted otherwise. + +Setup Stream Control: + 0x90 ss tt pp cc + ss = Stream ID + tt = Chip Type (see clock-order in header, e.g. YM2612 = 0x02) + bit 7 is used to select the 2nd chip + pp cc = write command/register cc at port pp + Note: For chips that use Channel Select Registers (like the RF5C-family + and the HuC6280), the format is pp cd where pp is the channel + number, c is the channel register and d is the data register. + If you set pp to FF, the channel select write is skipped. + +Set Stream Data: + 0x91 ss dd ll bb + ss = Stream ID + dd = Data Bank ID (see data block types 0x00..0x3f) + ll = Step Size (how many data is skipped after every write, usually 1) + Set to 2, if you're using an interleaved stream (e.g. for + left/right channel). + bb = Step Base (data offset added to the Start Offset when starting + stream playback, usually 0) + If you're using an interleaved stream, set it to 0 in one stream + and to 1 in the other one. + Note: Step Size/Step Step are given in command-data-size + (i.e. 1 for YM2612, 2 for PWM), not bytes + +Set Stream Frequency: + 0x92 ss ff ff ff ff + ss = Stream ID + ff = Frequency (or Sample Rate, in Hz) at which the writes are done + +Start Stream: + 0x93 ss aa aa aa aa mm ll ll ll ll + ss = Stream ID + aa = Data Start offset in data bank (byte offset in data bank) + Note: if set to -1, the Data Start offset is ignored + mm = Length Mode (how the Data Length is calculated) + 00 - ignore (just change current data position) + 01 - length = number of commands + 02 - length in msec + 03 - play until end of data + 1? - (bit 4) Reverse Mode + 8? - (bit 7) Loop (automatically restarts when finished) + ll = Data Length + +Stop Stream: + 0x94 ss + ss = Stream ID + Note: 0xFF stops all streams + +Start Stream (fast call): + 0x95 ss bb bb ff + ss = Stream ID + bb = Block ID (number of the data block that is part of the data bank set + with command 0x91) + ff = Flags + bit 0 - Loop (see command 0x93, mm bit 7) + bit 4 - Reverse Mode (see command 0x93) + +General Note to the DAC Stream Control: +Although it may be quite hard to press already streamed data into these +commands, it makes it very easy to write vgm-creation tools that need to stream +something. (like YM2612 DAC drums/voices/etc.) +The DAC Stream Control can use with almost all chips and is NOT limited to +chips such as YM2612 and PWM. + + +Dual Chip Support +----------------- +These chips support two instances of a chip in one vgm: +PSG, YM2413, YM2612, YM2151, YM2203, YM2608, YM2610, YM3812, YM3526, Y8950, +YMZ280B, YMF262, YMF278B, YMF271, AY8910, GameBoy DMG, NES APU, MultiPCM, +uPD7759, OKIM6258, OKIM6295, K051649, K054539, HuC6280, C140, K053260, Pokey + +Dual chip support is activated by setting bit 30 (0x40000000) in the chip's +clock value. (Note: The PSG needs this bit for T6W28 mode.) + +Dual Chip Supprt #1: +The second chip instance is controlled via seperate commands. + +The second PSG uses 0x30 (0x3F for GG Stereo). +All chips of the YM-family use 0xAn. n is the last digit of the main command. +e.g. 0x52 (1st chip) -> 0xA2 (2nd chip) + +Dual Chip Supprt #2: +All other chips use bit 7 (0x80) of the first parameter byte to distinguish +between the 1st and 2nd chip. (0x00-7F = Chip 1, 0x80-0xFF = chip 2) + + +Extra Header +------------ +With VGM v1.70, there was an extra header added. This one has to be placed +between the usual header and the actual VGM data. + +This is the format of the extra header: + + 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +0x00 [Header Size ][ChpClock Offset][ChpVol Offset ] + +Header Size is the size of the extra header. It has to be 4 or larger, +depending in the needed offsets. + +Then there are two offsets that point to extra header data for: +- additional Chip Clocks for second chips +- user-defined chip volumes + + +Chip Clock Header +----------------- +1 byte - Entry Count (chips with extra clocks) +[5 bytes - List Entry 1] +[5 bytes - List Entry 2] +... + +Each list entry has the format: +1 byte - Chip ID (chip order follows the header) +4 bytes - clock for second chip of the type above + + +Chip Volume Header +------------------ +1 byte - Entry Count (chips with user-defined volumes) +[4 bytes - List Entry 1] +[4 bytes - List Entry 2] +... + +Each list entry has the format: +1 byte - Chip ID (chip order follows the header) + Note: If bit 7 is set, it's the volume for a paired chip. + (e.g. the AY-part of the YM2203) +1 byte - Flags + Note: If bit 0 is set, it's the volume for the second chip. +2 bytes - volume for the chip + Note: If Bit 15 is 0, this is an absolute volume setting. + If Bit 15 is 1, it's relative and the chip volume gets + multiplied by ((Value & 0x7FFF) / 0x0100). + + +History +------- +[1.00] +Initial public release by Dave + +[1.01] +Rate value added by Maxim; 1.00 files are fully compatible + +[1.10] +PSG white noise feedback and shift register width parameters added by Maxim, +with note on how to handle earlier version files. +Additional wait command added by Maxim with thanks to Steve Snake for the +suggestion. +1.01 files are fully compatible but 1.01 players might have problems +with 1.10 files, hence the 0.1 version change. + +[1.50] +VGM data offset added to header by Maxim. +Data block support added by blargg, to allow for better handling of YM2612 PCM +data. +Both of these changes have the potential to cause problems, but are really good +changes, so the version number has been increased all the way to 1.50. + +[1.51] +Sega PCM, RF5C68, YM2203, YM2608, YM2610/B, YM3812, YM3526, Y8950, YMF262, +YMF278B, YMF271, YMZ280B, RF5C164, PWM and AY8910 chips and commands added. + +Additional data block types RF5C68 RAM write, RF5C164 RAM write, Sega PCM ROM, +YM2608 DELTA-T ROM, YM2610 ADPCM ROM, YM2610 DELTA-T ROM, YMF278B ROM, +YMF271 ROM, YMF271 RAM, YMZ280B ROM and Y8950 DELTA-T ROM Data added. + +Data Block Types splitted into 4 categories. (PCM Stream, compressed PCM +Stream, ROM/RAM Dump, RAM write) + +SN76489 Flags and Loop Modifier added. + +It is the first time the header size exceeds 0x40 bytes. +1.51 files are fully compatible to 1.50 players, but there may be problems with +the new commands. + +Note: Dual chip support was added too, but as a "cheat"-feature. The dual-chip +-bits in the clock values are not compatible to 1.50, but the rest is. + +All changes done by Valley Bell. + +[1.60] +RF5C68, RF5C164 and PWM PCM blocks and compressed data blocks added. + +A whole bunch of new commands (PCM RAM write and DAC Stream Control) added. + +Volume Modifier and Loop Base added. + +The new commands (especially 0x9?) may cause problems with older players. + +All changes done by Valley Bell. + +[1.61] +GameBoy DMG, NES APU, MultiPCM, uPD7759, OKIM6258, OKIM6295, K051649, K051649, +HuC6280, C140, K053260, Pokey and Q-Sound chips added. +(including necessary data blocks) + +Changed number of operands from 1 to 2 for reserved commands 0x40-0x4E. +Although they're still unused, old players might handle future vgm versions +wrongly. + +All changes done by Valley Bell. + +[1.70] +Added extra header with seperate chip clocks for the second one of dual chips +and chip volume adjustments. + +All changes done by Valley Bell. diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.c b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.c new file mode 100644 index 0000000000000000000000000000000000000000..b19e03c50a9835b87822df83cd44bbaf6bcdfa04 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.c @@ -0,0 +1,1417 @@ +// +// Copyright (C) 2017 Alexey Khokholov (Nuke.YKT) +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// +// Nuked OPN2(Yamaha YM3438) emulator. +// Thanks: +// Silicon Pr0n: +// Yamaha YM3438 decap and die shot(digshadow). +// OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): +// OPL2 ROMs. +// +// version: 1.0.7 +// + +#include +#include "ym3438.h" + +enum { + eg_num_attack = 0, + eg_num_decay = 1, + eg_num_sustain = 2, + eg_num_release = 3 +}; + +/* logsin table */ +static const Bit16u logsinrom[256] = { + 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, + 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365, + 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, + 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, + 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, + 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, + 0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, + 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, + 0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, + 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118, + 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, + 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, + 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, + 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, + 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, + 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, + 0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, + 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060, + 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, + 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045, + 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, + 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, + 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, + 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, + 0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, + 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, + 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, + 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007, + 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, + 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, + 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, + 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000 +}; + +/* exp table */ +static const Bit16u exprom[256] = { + 0x000, 0x003, 0x006, 0x008, 0x00b, 0x00e, 0x011, 0x014, + 0x016, 0x019, 0x01c, 0x01f, 0x022, 0x025, 0x028, 0x02a, + 0x02d, 0x030, 0x033, 0x036, 0x039, 0x03c, 0x03f, 0x042, + 0x045, 0x048, 0x04b, 0x04e, 0x051, 0x054, 0x057, 0x05a, + 0x05d, 0x060, 0x063, 0x066, 0x069, 0x06c, 0x06f, 0x072, + 0x075, 0x078, 0x07b, 0x07e, 0x082, 0x085, 0x088, 0x08b, + 0x08e, 0x091, 0x094, 0x098, 0x09b, 0x09e, 0x0a1, 0x0a4, + 0x0a8, 0x0ab, 0x0ae, 0x0b1, 0x0b5, 0x0b8, 0x0bb, 0x0be, + 0x0c2, 0x0c5, 0x0c8, 0x0cc, 0x0cf, 0x0d2, 0x0d6, 0x0d9, + 0x0dc, 0x0e0, 0x0e3, 0x0e7, 0x0ea, 0x0ed, 0x0f1, 0x0f4, + 0x0f8, 0x0fb, 0x0ff, 0x102, 0x106, 0x109, 0x10c, 0x110, + 0x114, 0x117, 0x11b, 0x11e, 0x122, 0x125, 0x129, 0x12c, + 0x130, 0x134, 0x137, 0x13b, 0x13e, 0x142, 0x146, 0x149, + 0x14d, 0x151, 0x154, 0x158, 0x15c, 0x160, 0x163, 0x167, + 0x16b, 0x16f, 0x172, 0x176, 0x17a, 0x17e, 0x181, 0x185, + 0x189, 0x18d, 0x191, 0x195, 0x199, 0x19c, 0x1a0, 0x1a4, + 0x1a8, 0x1ac, 0x1b0, 0x1b4, 0x1b8, 0x1bc, 0x1c0, 0x1c4, + 0x1c8, 0x1cc, 0x1d0, 0x1d4, 0x1d8, 0x1dc, 0x1e0, 0x1e4, + 0x1e8, 0x1ec, 0x1f0, 0x1f5, 0x1f9, 0x1fd, 0x201, 0x205, + 0x209, 0x20e, 0x212, 0x216, 0x21a, 0x21e, 0x223, 0x227, + 0x22b, 0x230, 0x234, 0x238, 0x23c, 0x241, 0x245, 0x249, + 0x24e, 0x252, 0x257, 0x25b, 0x25f, 0x264, 0x268, 0x26d, + 0x271, 0x276, 0x27a, 0x27f, 0x283, 0x288, 0x28c, 0x291, + 0x295, 0x29a, 0x29e, 0x2a3, 0x2a8, 0x2ac, 0x2b1, 0x2b5, + 0x2ba, 0x2bf, 0x2c4, 0x2c8, 0x2cd, 0x2d2, 0x2d6, 0x2db, + 0x2e0, 0x2e5, 0x2e9, 0x2ee, 0x2f3, 0x2f8, 0x2fd, 0x302, + 0x306, 0x30b, 0x310, 0x315, 0x31a, 0x31f, 0x324, 0x329, + 0x32e, 0x333, 0x338, 0x33d, 0x342, 0x347, 0x34c, 0x351, + 0x356, 0x35b, 0x360, 0x365, 0x36a, 0x370, 0x375, 0x37a, + 0x37f, 0x384, 0x38a, 0x38f, 0x394, 0x399, 0x39f, 0x3a4, + 0x3a9, 0x3ae, 0x3b4, 0x3b9, 0x3bf, 0x3c4, 0x3c9, 0x3cf, + 0x3d4, 0x3da, 0x3df, 0x3e4, 0x3ea, 0x3ef, 0x3f5, 0x3fa +}; + +/* Note table */ +static const Bit32u fn_note[16] = { + 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3 +}; + +/* Envelope generator */ +static const Bit32u eg_stephi[4][4] = { + { 0, 0, 0, 0 }, + { 1, 0, 0, 0 }, + { 1, 0, 1, 0 }, + { 1, 1, 1, 0 } +}; + +static const Bit8u eg_am_shift[4] = { + 7, 3, 1, 0 +}; + +/* Phase generator */ +static const Bit32u pg_detune[8] = { 16, 17, 19, 20, 22, 24, 27, 29 }; + +static const Bit32u pg_lfo_sh1[8][8] = { + { 7, 7, 7, 7, 7, 7, 7, 7 }, + { 7, 7, 7, 7, 7, 7, 7, 7 }, + { 7, 7, 7, 7, 7, 7, 1, 1 }, + { 7, 7, 7, 7, 1, 1, 1, 1 }, + { 7, 7, 7, 1, 1, 1, 1, 0 }, + { 7, 7, 1, 1, 0, 0, 0, 0 }, + { 7, 7, 1, 1, 0, 0, 0, 0 }, + { 7, 7, 1, 1, 0, 0, 0, 0 } +}; + +static const Bit32u pg_lfo_sh2[8][8] = { + { 7, 7, 7, 7, 7, 7, 7, 7 }, + { 7, 7, 7, 7, 2, 2, 2, 2 }, + { 7, 7, 7, 2, 2, 2, 7, 7 }, + { 7, 7, 2, 2, 7, 7, 2, 2 }, + { 7, 7, 2, 7, 7, 7, 2, 7 }, + { 7, 7, 7, 2, 7, 7, 2, 1 }, + { 7, 7, 7, 2, 7, 7, 2, 1 }, + { 7, 7, 7, 2, 7, 7, 2, 1 } +}; + +/* Address decoder */ +static const Bit32u op_offset[12] = { + 0x000, /* Ch1 OP1/OP2 */ + 0x001, /* Ch2 OP1/OP2 */ + 0x002, /* Ch3 OP1/OP2 */ + 0x100, /* Ch4 OP1/OP2 */ + 0x101, /* Ch5 OP1/OP2 */ + 0x102, /* Ch6 OP1/OP2 */ + 0x004, /* Ch1 OP3/OP4 */ + 0x005, /* Ch2 OP3/OP4 */ + 0x006, /* Ch3 OP3/OP4 */ + 0x104, /* Ch4 OP3/OP4 */ + 0x105, /* Ch5 OP3/OP4 */ + 0x106 /* Ch6 OP3/OP4 */ +}; + +static const Bit32u ch_offset[6] = { + 0x000, /* Ch1 */ + 0x001, /* Ch2 */ + 0x002, /* Ch3 */ + 0x100, /* Ch4 */ + 0x101, /* Ch5 */ + 0x102 /* Ch6 */ +}; + +/* LFO */ +static const Bit32u lfo_cycles[8] = { + 108, 77, 71, 67, 62, 44, 8, 5 +}; + +/* FM algorithm */ +static const Bit32u fm_algorithm[4][6][8] = { + { + { 1, 1, 1, 1, 1, 1, 1, 1 }, /* OP1_0 */ + { 1, 1, 1, 1, 1, 1, 1, 1 }, /* OP1_1 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP2 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* Last operator */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* Last operator */ + { 0, 0, 0, 0, 0, 0, 0, 1 } /* Out */ + }, + { + { 0, 1, 0, 0, 0, 1, 0, 0 }, /* OP1_0 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP1_1 */ + { 1, 1, 1, 0, 0, 0, 0, 0 }, /* OP2 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* Last operator */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* Last operator */ + { 0, 0, 0, 0, 0, 1, 1, 1 } /* Out */ + }, + { + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP1_0 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP1_1 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP2 */ + { 1, 0, 0, 1, 1, 1, 1, 0 }, /* Last operator */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* Last operator */ + { 0, 0, 0, 0, 1, 1, 1, 1 } /* Out */ + }, + { + { 0, 0, 1, 0, 0, 1, 0, 0 }, /* OP1_0 */ + { 0, 0, 0, 0, 0, 0, 0, 0 }, /* OP1_1 */ + { 0, 0, 0, 1, 0, 0, 0, 0 }, /* OP2 */ + { 1, 1, 0, 1, 1, 0, 0, 0 }, /* Last operator */ + { 0, 0, 1, 0, 0, 0, 0, 0 }, /* Last operator */ + { 1, 1, 1, 1, 1, 1, 1, 1 } /* Out */ + } +}; + +static Bit32u chip_type = ym3438_type_discrete; + +void OPN2_DoIO(ym3438_t *chip) +{ + /* Write signal check */ + chip->write_a_en = (chip->write_a & 0x03) == 0x01; + chip->write_d_en = (chip->write_d & 0x03) == 0x01; + chip->write_a <<= 1; + chip->write_d <<= 1; + /* Busy counter */ + chip->busy = chip->write_busy; + chip->write_busy_cnt += chip->write_busy; + chip->write_busy = (chip->write_busy && !(chip->write_busy_cnt >> 5)) || chip->write_d_en; + chip->write_busy_cnt &= 0x1f; +} + +void OPN2_DoRegWrite(ym3438_t *chip) +{ + Bit32u i; + Bit32u slot = chip->cycles % 12; + Bit32u address; + Bit32u channel = chip->channel; + /* Update registers */ + if (chip->write_fm_data) + { + /* Slot */ + if (op_offset[slot] == (chip->address & 0x107)) + { + if (chip->address & 0x08) + { + /* OP2, OP4 */ + slot += 12; + } + address = chip->address & 0xf0; + switch (address) + { + case 0x30: /* DT, MULTI */ + chip->multi[slot] = chip->data & 0x0f; + if (!chip->multi[slot]) + { + chip->multi[slot] = 1; + } + else + { + chip->multi[slot] <<= 1; + } + chip->dt[slot] = (chip->data >> 4) & 0x07; + break; + case 0x40: /* TL */ + chip->tl[slot] = chip->data & 0x7f; + break; + case 0x50: /* KS, AR */ + chip->ar[slot] = chip->data & 0x1f; + chip->ks[slot] = (chip->data >> 6) & 0x03; + break; + case 0x60: /* AM, DR */ + chip->dr[slot] = chip->data & 0x1f; + chip->am[slot] = (chip->data >> 7) & 0x01; + break; + case 0x70: /* SR */ + chip->sr[slot] = chip->data & 0x1f; + break; + case 0x80: /* SL, RR */ + chip->rr[slot] = chip->data & 0x0f; + chip->sl[slot] = (chip->data >> 4) & 0x0f; + chip->sl[slot] |= (chip->sl[slot] + 1) & 0x10; + break; + case 0x90: /* SSG-EG */ + chip->ssg_eg[slot] = chip->data & 0x0f; + break; + default: + break; + } + } + + /* Channel */ + if (ch_offset[channel] == (chip->address & 0x103)) + { + address = chip->address & 0xfc; + switch (address) + { + case 0xa0: + chip->fnum[channel] = (chip->data & 0xff) | ((chip->reg_a4 & 0x07) << 8); + chip->block[channel] = (chip->reg_a4 >> 3) & 0x07; + chip->kcode[channel] = (chip->block[channel] << 2) | fn_note[chip->fnum[channel] >> 7]; + break; + case 0xa4: + chip->reg_a4 = chip->data & 0xff; + break; + case 0xa8: + chip->fnum_3ch[channel] = (chip->data & 0xff) | ((chip->reg_ac & 0x07) << 8); + chip->block_3ch[channel] = (chip->reg_ac >> 3) & 0x07; + chip->kcode_3ch[channel] = (chip->block_3ch[channel] << 2) | fn_note[chip->fnum_3ch[channel] >> 7]; + break; + case 0xac: + chip->reg_ac = chip->data & 0xff; + break; + case 0xb0: + chip->connect[channel] = chip->data & 0x07; + chip->fb[channel] = (chip->data >> 3) & 0x07; + break; + case 0xb4: + chip->pms[channel] = chip->data & 0x07; + chip->ams[channel] = (chip->data >> 4) & 0x03; + chip->pan_l[channel] = (chip->data >> 7) & 0x01; + chip->pan_r[channel] = (chip->data >> 6) & 0x01; + break; + default: + break; + } + } + } + + if (chip->write_a_en || chip->write_d_en) + { + /* Data */ + if (chip->write_a_en) + { + chip->write_fm_data = 0; + } + + if (chip->write_fm_address && chip->write_d_en) + { + chip->write_fm_data = 1; + } + + /* Address */ + if (chip->write_a_en) + { + if ((chip->write_data & 0xf0) != 0x00) + { + /* FM Write */ + chip->address = chip->write_data; + chip->write_fm_address = 1; + } + else + { + /* SSG write */ + chip->write_fm_address = 0; + } + } + + /* FM Mode */ + /* Data */ + if (chip->write_d_en && (chip->write_data & 0x100) == 0) + { + switch (chip->address) + { + case 0x21: /* LSI test 1 */ + for (i = 0; i < 8; i++) + { + chip->mode_test_21[i] = (chip->write_data >> i) & 0x01; + } + break; + case 0x22: /* LFO control */ + if ((chip->write_data >> 3) & 0x01) + { + chip->lfo_en = 0x7f; + } + else + { + chip->lfo_en = 0; + } + chip->lfo_freq = chip->write_data & 0x07; + break; + case 0x24: /* Timer A */ + chip->timer_a_reg &= 0x03; + chip->timer_a_reg |= (chip->write_data & 0xff) << 2; + break; + case 0x25: + chip->timer_a_reg &= 0x3fc; + chip->timer_a_reg |= chip->write_data & 0x03; + break; + case 0x26: /* Timer B */ + chip->timer_b_reg = chip->write_data & 0xff; + break; + case 0x27: /* CSM, Timer control */ + chip->mode_ch3 = (chip->write_data & 0xc0) >> 6; + chip->mode_csm = chip->mode_ch3 == 2; + chip->timer_a_load = chip->write_data & 0x01; + chip->timer_a_enable = (chip->write_data >> 2) & 0x01; + chip->timer_a_reset = (chip->write_data >> 4) & 0x01; + chip->timer_b_load = (chip->write_data >> 1) & 0x01; + chip->timer_b_enable = (chip->write_data >> 3) & 0x01; + chip->timer_b_reset = (chip->write_data >> 5) & 0x01; + break; + case 0x28: /* Key on/off */ + for (i = 0; i < 4; i++) + { + chip->mode_kon_operator[i] = (chip->write_data >> (4 + i)) & 0x01; + } + if ((chip->write_data & 0x03) == 0x03) + { + /* Invalid address */ + chip->mode_kon_channel = 0xff; + } + else + { + chip->mode_kon_channel = (chip->write_data & 0x03) + ((chip->write_data >> 2) & 1) * 3; + } + break; + case 0x2a: /* DAC data */ + chip->dacdata &= 0x01; + chip->dacdata |= (chip->write_data ^ 0x80) << 1; + break; + case 0x2b: /* DAC enable */ + chip->dacen = chip->write_data >> 7; + break; + case 0x2c: /* LSI test 2 */ + for (i = 0; i < 8; i++) + { + chip->mode_test_2c[i] = (chip->write_data >> i) & 0x01; + } + chip->dacdata &= 0x1fe; + chip->dacdata |= chip->mode_test_2c[3]; + chip->eg_custom_timer = !chip->mode_test_2c[7] && chip->mode_test_2c[6]; + break; + default: + break; + } + } + + /* Address */ + if (chip->write_a_en) + { + chip->write_fm_mode_a = chip->write_data & 0xff; + } + } + + if (chip->write_fm_data) + { + chip->data = chip->write_data & 0xff; + } +} + +void OPN2_PhaseCalcIncrement(ym3438_t *chip) +{ + Bit32u chan = chip->channel; + Bit32u slot = chip->cycles; + Bit32u fnum = chip->pg_fnum; + Bit32u fnum_h = fnum >> 4; + Bit32u fm; + Bit32u basefreq; + Bit8u lfo = chip->lfo_pm; + Bit8u lfo_l = lfo & 0x0f; + Bit8u pms = chip->pms[chan]; + Bit8u dt = chip->dt[slot]; + Bit8u dt_l = dt & 0x03; + Bit8u detune = 0; + Bit8u block, note; + Bit8u sum, sum_h, sum_l; + Bit8u kcode = chip->pg_kcode; + + fnum <<= 1; + /* Apply LFO */ + if (lfo_l & 0x08) + { + lfo_l ^= 0x0f; + } + fm = (fnum_h >> pg_lfo_sh1[pms][lfo_l]) + (fnum_h >> pg_lfo_sh2[pms][lfo_l]); + if (pms > 5) + { + fm <<= pms - 5; + } + fm >>= 2; + if (lfo & 0x10) + { + fnum -= fm; + } + else + { + fnum += fm; + } + fnum &= 0xfff; + + basefreq = (fnum << chip->pg_block) >> 2; + + /* Apply detune */ + if (dt_l) + { + if (kcode > 0x1c) + { + kcode = 0x1c; + } + block = kcode >> 2; + note = kcode & 0x03; + sum = block + 9 + ((dt_l == 3) | (dt_l & 0x02)); + sum_h = sum >> 1; + sum_l = sum & 0x01; + detune = pg_detune[(sum_l << 2) | note] >> (9 - sum_h); + } + if (dt & 0x04) + { + basefreq -= detune; + } + else + { + basefreq += detune; + } + basefreq &= 0x1ffff; + chip->pg_inc[slot] = (basefreq * chip->multi[slot]) >> 1; + chip->pg_inc[slot] &= 0xfffff; +} + +void OPN2_PhaseGenerate(ym3438_t *chip) +{ + Bit32u slot; + /* Mask increment */ + slot = (chip->cycles + 20) % 24; + if (chip->pg_reset[slot]) + { + chip->pg_inc[slot] = 0; + } + /* Phase step */ + slot = (chip->cycles + 19) % 24; + chip->pg_phase[slot] += chip->pg_inc[slot]; + chip->pg_phase[slot] &= 0xfffff; + if (chip->pg_reset[slot] || chip->mode_test_21[3]) + { + chip->pg_phase[slot] = 0; + } +} + +void OPN2_EnvelopeSSGEG(ym3438_t *chip) +{ + Bit32u slot = chip->cycles; + Bit8u direction = 0; + chip->eg_ssg_pgrst_latch[slot] = 0; + chip->eg_ssg_repeat_latch[slot] = 0; + chip->eg_ssg_hold_up_latch[slot] = 0; + chip->eg_ssg_inv[slot] = 0; + if (chip->ssg_eg[slot] & 0x08) + { + direction = chip->eg_ssg_dir[slot]; + if (chip->eg_level[slot] & 0x200) + { + /* Reset */ + if ((chip->ssg_eg[slot] & 0x03) == 0x00) + { + chip->eg_ssg_pgrst_latch[slot] = 1; + } + /* Repeat */ + if ((chip->ssg_eg[slot] & 0x01) == 0x00) + { + chip->eg_ssg_repeat_latch[slot] = 1; + } + /* Inverse */ + if ((chip->ssg_eg[slot] & 0x03) == 0x02) + { + direction ^= 1; + } + if ((chip->ssg_eg[slot] & 0x03) == 0x03) + { + direction = 1; + } + } + /* Hold up */ + if (chip->eg_kon_latch[slot] + && ((chip->ssg_eg[slot] & 0x07) == 0x05 || (chip->ssg_eg[slot] & 0x07) == 0x03)) + { + chip->eg_ssg_hold_up_latch[slot] = 1; + } + direction &= chip->eg_kon[slot]; + chip->eg_ssg_inv[slot] = (chip->eg_ssg_dir[slot] ^ ((chip->ssg_eg[slot] >> 2) & 0x01)) + & chip->eg_kon[slot]; + } + chip->eg_ssg_dir[slot] = direction; + chip->eg_ssg_enable[slot] = (chip->ssg_eg[slot] >> 3) & 0x01; +} + +void OPN2_EnvelopeADSR(ym3438_t *chip) +{ + Bit32u slot = (chip->cycles + 22) % 24; + + Bit8u nkon = chip->eg_kon_latch[slot]; + Bit8u okon = chip->eg_kon[slot]; + Bit8u kon_event; + Bit8u koff_event; + Bit8u eg_off; + Bit16s level; + Bit16s nextlevel = 0; + Bit16s ssg_level; + Bit8u nextstate = chip->eg_state[slot]; + Bit16s inc = 0; + chip->eg_read[0] = chip->eg_read_inc; + chip->eg_read_inc = chip->eg_inc > 0; + + /* Reset phase generator */ + chip->pg_reset[slot] = (nkon && !okon) || chip->eg_ssg_pgrst_latch[slot]; + + /* KeyOn/Off */ + kon_event = (nkon && !okon) || (okon && chip->eg_ssg_repeat_latch[slot]); + koff_event = okon && !nkon; + + ssg_level = level = (Bit16s)chip->eg_level[slot]; + + if (chip->eg_ssg_inv[slot]) + { + /* Inverse */ + ssg_level = 512 - level; + ssg_level &= 0x3ff; + } + if (koff_event) + { + level = ssg_level; + } + if (chip->eg_ssg_enable[slot]) + { + eg_off = level >> 9; + } + else + { + eg_off = (level & 0x3f0) == 0x3f0; + } + nextlevel = level; + if (kon_event) + { + nextstate = eg_num_attack; + /* Instant attack */ + if (chip->eg_ratemax) + { + nextlevel = 0; + } + else if (chip->eg_state[slot] == eg_num_attack && level != 0 && chip->eg_inc && nkon) + { + inc = (~level << chip->eg_inc) >> 5; + } + } + else + { + switch (chip->eg_state[slot]) + { + case eg_num_attack: + if (level == 0) + { + nextstate = eg_num_decay; + } + else if(chip->eg_inc && !chip->eg_ratemax && nkon) + { + inc = (~level << chip->eg_inc) >> 5; + } + break; + case eg_num_decay: + if ((level >> 5) == chip->eg_sl[1]) + { + nextstate = eg_num_sustain; + } + else if (!eg_off && chip->eg_inc) + { + inc = 1 << (chip->eg_inc - 1); + if (chip->eg_ssg_enable[slot]) + { + inc <<= 2; + } + } + break; + case eg_num_sustain: + case eg_num_release: + if (!eg_off && chip->eg_inc) + { + inc = 1 << (chip->eg_inc - 1); + if (chip->eg_ssg_enable[slot]) + { + inc <<= 2; + } + } + break; + default: + break; + } + if (!nkon) + { + nextstate = eg_num_release; + } + } + if (chip->eg_kon_csm[slot]) + { + nextlevel |= chip->eg_tl[1] << 3; + } + + /* Envelope off */ + if (!kon_event && !chip->eg_ssg_hold_up_latch[slot] && chip->eg_state[slot] != eg_num_attack && eg_off) + { + nextstate = eg_num_release; + nextlevel = 0x3ff; + } + + nextlevel += inc; + + chip->eg_kon[slot] = chip->eg_kon_latch[slot]; + chip->eg_level[slot] = (Bit16u)nextlevel & 0x3ff; + chip->eg_state[slot] = nextstate; +} + +void OPN2_EnvelopePrepare(ym3438_t *chip) +{ + Bit8u rate; + Bit8u sum; + Bit8u inc = 0; + Bit32u slot = chip->cycles; + Bit8u rate_sel; + + /* Prepare increment */ + rate = (chip->eg_rate << 1) + chip->eg_ksv; + + if (rate > 0x3f) + { + rate = 0x3f; + } + + sum = ((rate >> 2) + chip->eg_shift_lock) & 0x0f; + if (chip->eg_rate != 0 && chip->eg_quotient == 2) + { + if (rate < 48) + { + switch (sum) + { + case 12: + inc = 1; + break; + case 13: + inc = (rate >> 1) & 0x01; + break; + case 14: + inc = rate & 0x01; + break; + default: + break; + } + } + else + { + inc = eg_stephi[rate & 0x03][chip->eg_timer_low_lock] + (rate >> 2) - 11; + if (inc > 4) + { + inc = 4; + } + } + } + chip->eg_inc = inc; + chip->eg_ratemax = (rate >> 1) == 0x1f; + + /* Prepare rate & ksv */ + rate_sel = chip->eg_state[slot]; + if ((chip->eg_kon[slot] && chip->eg_ssg_repeat_latch[slot]) + || (!chip->eg_kon[slot] && chip->eg_kon_latch[slot])) + { + rate_sel = eg_num_attack; + } + switch (rate_sel) + { + case eg_num_attack: + chip->eg_rate = chip->ar[slot]; + break; + case eg_num_decay: + chip->eg_rate = chip->dr[slot]; + break; + case eg_num_sustain: + chip->eg_rate = chip->sr[slot]; + break; + case eg_num_release: + chip->eg_rate = (chip->rr[slot] << 1) | 0x01; + break; + default: + break; + } + chip->eg_ksv = chip->pg_kcode >> (chip->ks[slot] ^ 0x03); + if (chip->am[slot]) + { + chip->eg_lfo_am = chip->lfo_am >> eg_am_shift[chip->ams[chip->channel]]; + } + else + { + chip->eg_lfo_am = 0; + } + /* Delay TL & SL value */ + chip->eg_tl[1] = chip->eg_tl[0]; + chip->eg_tl[0] = chip->tl[slot]; + chip->eg_sl[1] = chip->eg_sl[0]; + chip->eg_sl[0] = chip->sl[slot]; +} + +void OPN2_EnvelopeGenerate(ym3438_t *chip) +{ + Bit32u slot = (chip->cycles + 23) % 24; + Bit16u level; + + level = chip->eg_level[slot]; + + if (chip->eg_ssg_inv[slot]) + { + /* Inverse */ + level = 512 - level; + } + if (chip->mode_test_21[5]) + { + level = 0; + } + level &= 0x3ff; + + /* Apply AM LFO */ + level += chip->eg_lfo_am; + + /* Apply TL */ + if (!(chip->mode_csm && chip->channel == 2 + 1)) + { + level += chip->eg_tl[0] << 3; + } + if (level > 0x3ff) + { + level = 0x3ff; + } + chip->eg_out[slot] = level; +} + +void OPN2_UpdateLFO(ym3438_t *chip) +{ + if ((chip->lfo_quotient & lfo_cycles[chip->lfo_freq]) == lfo_cycles[chip->lfo_freq]) + { + chip->lfo_quotient = 0; + chip->lfo_cnt++; + } + else + { + chip->lfo_quotient += chip->lfo_inc; + } + chip->lfo_cnt &= chip->lfo_en; +} + +void OPN2_FMPrepare(ym3438_t *chip) +{ + Bit32u slot = (chip->cycles + 6) % 24; + Bit32u channel = chip->channel; + Bit16s mod, mod1, mod2; + Bit32u op = slot / 6; + Bit8u connect = chip->connect[channel]; + Bit32u prevslot = (chip->cycles + 18) % 24; + + /* Calculate modulation */ + mod1 = mod2 = 0; + + if (fm_algorithm[op][0][connect]) + { + mod2 |= chip->fm_op1[channel][0]; + } + if (fm_algorithm[op][1][connect]) + { + mod1 |= chip->fm_op1[channel][1]; + } + if (fm_algorithm[op][2][connect]) + { + mod1 |= chip->fm_op2[channel]; + } + if (fm_algorithm[op][3][connect]) + { + mod2 |= chip->fm_out[prevslot]; + } + if (fm_algorithm[op][4][connect]) + { + mod1 |= chip->fm_out[prevslot]; + } + mod = mod1 + mod2; + if (op == 0) + { + /* Feedback */ + mod = mod >> (10 - chip->fb[channel]); + if (!chip->fb[channel]) + { + mod = 0; + } + } + else + { + mod >>= 1; + } + chip->fm_mod[slot] = mod; + + slot = (chip->cycles + 18) % 24; + /* OP1 */ + if (slot / 6 == 0) + { + chip->fm_op1[channel][1] = chip->fm_op1[channel][0]; + chip->fm_op1[channel][0] = chip->fm_out[slot]; + } + /* OP2 */ + if (slot / 6 == 2) + { + chip->fm_op2[channel] = chip->fm_out[slot]; + } +} + +void OPN2_ChGenerate(ym3438_t *chip) +{ + Bit32u slot = (chip->cycles + 18) % 24; + Bit32u channel = chip->channel; + Bit32u op = slot / 6; + Bit32u test_dac = chip->mode_test_2c[5]; + Bit16s acc = chip->ch_acc[channel]; + Bit16s add = test_dac; + Bit16s sum = 0; + if (op == 0 && !test_dac) + { + acc = 0; + } + if (fm_algorithm[op][5][chip->connect[channel]] && !test_dac) + { + add += chip->fm_out[slot] >> 5; + } + sum = acc + add; + /* Clamp */ + if (sum > 255) + { + sum = 255; + } + else if(sum < -256) + { + sum = -256; + } + + if (op == 0 || test_dac) + { + chip->ch_out[channel] = chip->ch_acc[channel]; + } + chip->ch_acc[channel] = sum; +} + +void OPN2_ChOutput(ym3438_t *chip) +{ + Bit32u cycles = chip->cycles; + Bit32u slot = chip->cycles; + Bit32u channel = chip->channel; + Bit32u test_dac = chip->mode_test_2c[5]; + Bit16s out; + Bit16s sign; + Bit32u out_en; + chip->ch_read = chip->ch_lock; + if (slot < 12) + { + /* Ch 4,5,6 */ + channel++; + } + if ((cycles & 3) == 0) + { + if (!test_dac) + { + /* Lock value */ + chip->ch_lock = chip->ch_out[channel]; + } + chip->ch_lock_l = chip->pan_l[channel]; + chip->ch_lock_r = chip->pan_r[channel]; + } + /* Ch 6 */ + if (((cycles >> 2) == 1 && chip->dacen) || test_dac) + { + out = (Bit16s)chip->dacdata; + out <<= 7; + out >>= 7; + } + else + { + out = chip->ch_lock; + } + chip->mol = 0; + chip->mor = 0; + + if (chip_type == ym3438_type_ym2612) + { + out_en = ((cycles & 3) == 3) || test_dac; + /* YM2612 DAC emulation(not verified) */ + sign = out >> 8; + if (out >= 0) + { + out++; + sign++; + } + if (chip->ch_lock_l && out_en) + { + chip->mol = out; + } + else + { + chip->mol = sign; + } + if (chip->ch_lock_r && out_en) + { + chip->mor = out; + } + else + { + chip->mor = sign; + } + /* Amplify signal */ + chip->mol *= 3; + chip->mor *= 3; + } + else + { + out_en = ((cycles & 3) != 0) || test_dac; + /* Discrete YM3438 seems has the ladder effect too */ + if (out >= 0 && chip_type == ym3438_type_discrete) + { + out++; + } + if (chip->ch_lock_l && out_en) + { + chip->mol = out; + } + if (chip->ch_lock_r && out_en) + { + chip->mor = out; + } + } +} + +void OPN2_FMGenerate(ym3438_t *chip) +{ + Bit32u slot = (chip->cycles + 19) % 24; + /* Calculate phase */ + Bit16u phase = (chip->fm_mod[slot] + (chip->pg_phase[slot] >> 10)) & 0x3ff; + Bit16u quarter; + Bit16u level; + Bit16s output; + if (phase & 0x100) + { + quarter = (phase ^ 0xff) & 0xff; + } + else + { + quarter = phase & 0xff; + } + level = logsinrom[quarter]; + /* Apply envelope */ + level += chip->eg_out[slot] << 2; + /* Transform */ + if (level > 0x1fff) + { + level = 0x1fff; + } + output = ((exprom[(level & 0xff) ^ 0xff] | 0x400) << 2) >> (level >> 8); + if (phase & 0x200) + { + output = ((~output) ^ (chip->mode_test_21[4] << 13)) + 1; + } + else + { + output = output ^ (chip->mode_test_21[4] << 13); + } + output <<= 2; + output >>= 2; + chip->fm_out[slot] = output; +} + +void OPN2_DoTimerA(ym3438_t *chip) +{ + Bit16u time; + Bit8u load; + load = chip->timer_a_overflow; + if (chip->cycles == 2) + { + /* Lock load value */ + load |= (!chip->timer_a_load_lock && chip->timer_a_load); + chip->timer_a_load_lock = chip->timer_a_load; + if (chip->mode_csm) + { + /* CSM KeyOn */ + chip->mode_kon_csm = load; + } + else + { + chip->mode_kon_csm = 0; + } + } + /* Load counter */ + if (chip->timer_a_load_latch) + { + time = chip->timer_a_reg; + } + else + { + time = chip->timer_a_cnt; + } + chip->timer_a_load_latch = load; + /* Increase counter */ + if ((chip->cycles == 1 && chip->timer_a_load_lock) || chip->mode_test_21[2]) + { + time++; + } + /* Set overflow flag */ + if (chip->timer_a_reset) + { + chip->timer_a_reset = 0; + chip->timer_a_overflow_flag = 0; + } + else + { + chip->timer_a_overflow_flag |= chip->timer_a_overflow & chip->timer_a_enable; + } + chip->timer_a_overflow = (time >> 10); + chip->timer_a_cnt = time & 0x3ff; +} + +void OPN2_DoTimerB(ym3438_t *chip) +{ + Bit16u time; + Bit8u load; + load = chip->timer_b_overflow; + if (chip->cycles == 2) + { + /* Lock load value */ + load |= (!chip->timer_b_load_lock && chip->timer_b_load); + chip->timer_b_load_lock = chip->timer_b_load; + } + /* Load counter */ + if (chip->timer_b_load_latch) + { + time = chip->timer_b_reg; + } + else + { + time = chip->timer_b_cnt; + } + chip->timer_b_load_latch = load; + /* Increase counter */ + if (chip->cycles == 1) + { + chip->timer_b_subcnt++; + } + if ((chip->timer_b_subcnt == 0x10 && chip->timer_b_load_lock) || chip->mode_test_21[2]) + { + time++; + } + chip->timer_b_subcnt &= 0x0f; + /* Set overflow flag */ + if (chip->timer_b_reset) + { + chip->timer_b_reset = 0; + chip->timer_b_overflow_flag = 0; + } + else + { + chip->timer_b_overflow_flag |= chip->timer_b_overflow & chip->timer_b_enable; + } + chip->timer_b_overflow = (time >> 8); + chip->timer_b_cnt = time & 0xff; +} + +void OPN2_KeyOn(ym3438_t*chip) +{ + Bit32u slot = chip->cycles; + Bit32u chan = chip->channel; + /* Key On */ + chip->eg_kon_latch[slot] = chip->mode_kon[slot]; + chip->eg_kon_csm[slot] = 0; + if (chip->channel == 2 && chip->mode_kon_csm) + { + /* CSM Key On */ + chip->eg_kon_latch[slot] = 1; + chip->eg_kon_csm[slot] = 1; + } + if (chip->cycles == chip->mode_kon_channel) + { + /* OP1 */ + chip->mode_kon[chan] = chip->mode_kon_operator[0]; + /* OP2 */ + chip->mode_kon[chan + 12] = chip->mode_kon_operator[1]; + /* OP3 */ + chip->mode_kon[chan + 6] = chip->mode_kon_operator[2]; + /* OP4 */ + chip->mode_kon[chan + 18] = chip->mode_kon_operator[3]; + } +} + +void OPN2_Reset(ym3438_t *chip) +{ + Bit32u i; + memset(chip, 0, sizeof(ym3438_t)); + for (i = 0; i < 24; i++) + { + chip->eg_out[i] = 0x3ff; + chip->eg_level[i] = 0x3ff; + chip->eg_state[i] = eg_num_release; + chip->multi[i] = 1; + } + for (i = 0; i < 6; i++) + { + chip->pan_l[i] = 1; + chip->pan_r[i] = 1; + } +} + +void OPN2_SetChipType(Bit32u type) +{ + chip_type = type; +} + +void OPN2_Clock(ym3438_t *chip, Bit32u *buffer) +{ + Bit32u slot = chip->cycles; + chip->lfo_inc = chip->mode_test_21[1]; + chip->pg_read >>= 1; + chip->eg_read[1] >>= 1; + chip->eg_cycle++; + /* Lock envelope generator timer value */ + if (chip->cycles == 1 && chip->eg_quotient == 2) + { + if (chip->eg_cycle_stop) + { + chip->eg_shift_lock = 0; + } + else + { + chip->eg_shift_lock = chip->eg_shift + 1; + } + chip->eg_timer_low_lock = chip->eg_timer & 0x03; + } + /* Cycle specific functions */ + switch (chip->cycles) + { + case 0: + chip->lfo_pm = chip->lfo_cnt >> 2; + if (chip->lfo_cnt & 0x40) + { + chip->lfo_am = chip->lfo_cnt & 0x3f; + } + else + { + chip->lfo_am = chip->lfo_cnt ^ 0x3f; + } + chip->lfo_am <<= 1; + break; + case 1: + chip->eg_quotient++; + chip->eg_quotient %= 3; + chip->eg_cycle = 0; + chip->eg_cycle_stop = 1; + chip->eg_shift = 0; + chip->eg_timer_inc |= chip->eg_quotient >> 1; + chip->eg_timer = chip->eg_timer + chip->eg_timer_inc; + chip->eg_timer_inc = chip->eg_timer >> 12; + chip->eg_timer &= 0xfff; + break; + case 2: + chip->pg_read = chip->pg_phase[21] & 0x3ff; + chip->eg_read[1] = chip->eg_out[0]; + break; + case 13: + chip->eg_cycle = 0; + chip->eg_cycle_stop = 1; + chip->eg_shift = 0; + chip->eg_timer = chip->eg_timer + chip->eg_timer_inc; + chip->eg_timer_inc = chip->eg_timer >> 12; + chip->eg_timer &= 0xfff; + break; + case 23: + chip->lfo_inc |= 1; + break; + } + chip->eg_timer &= ~(chip->mode_test_21[5] << chip->eg_cycle); + if (((chip->eg_timer >> chip->eg_cycle) | (chip->pin_test_in & chip->eg_custom_timer)) & chip->eg_cycle_stop) + { + chip->eg_shift = chip->eg_cycle; + chip->eg_cycle_stop = 0; + } + + OPN2_DoIO(chip); + + OPN2_DoTimerA(chip); + OPN2_DoTimerB(chip); + OPN2_KeyOn(chip); + + OPN2_ChOutput(chip); + OPN2_ChGenerate(chip); + + OPN2_FMPrepare(chip); + OPN2_FMGenerate(chip); + + OPN2_PhaseGenerate(chip); + OPN2_PhaseCalcIncrement(chip); + + OPN2_EnvelopeADSR(chip); + OPN2_EnvelopeGenerate(chip); + OPN2_EnvelopeSSGEG(chip); + OPN2_EnvelopePrepare(chip); + + /* Prepare fnum & block */ + if (chip->mode_ch3) + { + /* Channel 3 special mode */ + switch (slot) + { + case 1: /* OP1 */ + chip->pg_fnum = chip->fnum_3ch[1]; + chip->pg_block = chip->block_3ch[1]; + chip->pg_kcode = chip->kcode_3ch[1]; + break; + case 7: /* OP3 */ + chip->pg_fnum = chip->fnum_3ch[0]; + chip->pg_block = chip->block_3ch[0]; + chip->pg_kcode = chip->kcode_3ch[0]; + break; + case 13: /* OP2 */ + chip->pg_fnum = chip->fnum_3ch[2]; + chip->pg_block = chip->block_3ch[2]; + chip->pg_kcode = chip->kcode_3ch[2]; + break; + case 19: /* OP4 */ + default: + chip->pg_fnum = chip->fnum[(chip->channel + 1) % 6]; + chip->pg_block = chip->block[(chip->channel + 1) % 6]; + chip->pg_kcode = chip->kcode[(chip->channel + 1) % 6]; + break; + } + } + else + { + chip->pg_fnum = chip->fnum[(chip->channel + 1) % 6]; + chip->pg_block = chip->block[(chip->channel + 1) % 6]; + chip->pg_kcode = chip->kcode[(chip->channel + 1) % 6]; + } + + OPN2_UpdateLFO(chip); + OPN2_DoRegWrite(chip); + chip->cycles = (chip->cycles + 1) % 24; + chip->channel = chip->cycles % 6; + + buffer[0] = chip->mol; + buffer[1] = chip->mor; +} + +void OPN2_Write(ym3438_t *chip, Bit32u port, Bit8u data) +{ + port &= 3; + chip->write_data = ((port << 7) & 0x100) | data; + if (port & 1) + { + /* Data */ + chip->write_d |= 1; + } + else + { + /* Address */ + chip->write_a |= 1; + } +} + +void OPN2_SetTestPin(ym3438_t *chip, Bit32u value) +{ + chip->pin_test_in = value & 1; +} + +Bit32u OPN2_ReadTestPin(ym3438_t *chip) +{ + if (!chip->mode_test_2c[7]) + { + return 0; + } + return chip->cycles == 23; +} + +Bit32u OPN2_ReadIRQPin(ym3438_t *chip) +{ + return chip->timer_a_overflow_flag | chip->timer_b_overflow_flag; +} + +Bit8u OPN2_Read(ym3438_t *chip, Bit32u port) +{ + if ((port & 3) == 0 || chip_type == ym3438_type_asic) + { + if (chip->mode_test_21[6]) + { + /* Read test data */ + Bit32u slot = (chip->cycles + 18) % 24; + Bit16u testdata = ((chip->pg_read & 0x01) << 15) + | ((chip->eg_read[chip->mode_test_21[0]] & 0x01) << 14); + if (chip->mode_test_2c[4]) + { + testdata |= chip->ch_read & 0x1ff; + } + else + { + testdata |= chip->fm_out[slot] & 0x3fff; + } + if (chip->mode_test_21[7]) + { + return testdata & 0xff; + } + else + { + return testdata >> 8; + } + } + else + { + return (chip->busy << 7) | (chip->timer_b_overflow_flag << 1) + | chip->timer_a_overflow_flag; + } + } + return 0; +} diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.h b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.h new file mode 100644 index 0000000000000000000000000000000000000000..7f9687ca935e4816f9acfff35925015da4f43eff --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/other/ym3438.h @@ -0,0 +1,201 @@ +// +// Copyright (C) 2017 Alexey Khokholov (Nuke.YKT) +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// +// Nuked OPN2(Yamaha YM3438) emulator. +// Thanks: +// Silicon Pr0n: +// Yamaha YM3438 decap and die shot(digshadow). +// OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): +// OPL2 ROMs. +// +// version: 1.0.7 +// + +#ifndef YM3438_H +#define YM3438_H + +enum { + ym3438_type_discrete = 0, /* Discrete YM3438 (Teradrive) */ + ym3438_type_asic = 1, /* ASIC YM3438 (MD1 VA7, MD2, MD3, etc) */ + ym3438_type_ym2612 = 2 /* YM2612 (MD1, MD2 VA2) */ +}; + +#include + +typedef uintptr_t Bitu; +typedef intptr_t Bits; +typedef uint64_t Bit64u; +typedef int64_t Bit64s; +typedef uint32_t Bit32u; +typedef int32_t Bit32s; +typedef uint16_t Bit16u; +typedef int16_t Bit16s; +typedef uint8_t Bit8u; +typedef int8_t Bit8s; + +typedef struct +{ + Bit32u cycles; + Bit32u channel; + Bit16s mol, mor; + /* IO */ + Bit16u write_data; + Bit8u write_a; + Bit8u write_d; + Bit8u write_a_en; + Bit8u write_d_en; + Bit8u write_busy; + Bit8u write_busy_cnt; + Bit8u write_fm_address; + Bit8u write_fm_data; + Bit8u write_fm_mode_a; + Bit16u address; + Bit8u data; + Bit8u pin_test_in; + Bit8u pin_irq; + Bit8u busy; + /* LFO */ + Bit8u lfo_en; + Bit8u lfo_freq; + Bit8u lfo_pm; + Bit8u lfo_am; + Bit8u lfo_cnt; + Bit8u lfo_inc; + Bit8u lfo_quotient; + /* Phase generator */ + Bit16u pg_fnum; + Bit8u pg_block; + Bit8u pg_kcode; + Bit32u pg_inc[24]; + Bit32u pg_phase[24]; + Bit8u pg_reset[24]; + Bit32u pg_read; + /* Envelope generator */ + Bit8u eg_cycle; + Bit8u eg_cycle_stop; + Bit8u eg_shift; + Bit8u eg_shift_lock; + Bit8u eg_timer_low_lock; + Bit16u eg_timer; + Bit8u eg_timer_inc; + Bit16u eg_quotient; + Bit8u eg_custom_timer; + Bit8u eg_rate; + Bit8u eg_ksv; + Bit8u eg_inc; + Bit8u eg_ratemax; + Bit8u eg_sl[2]; + Bit8u eg_lfo_am; + Bit8u eg_tl[2]; + Bit8u eg_state[24]; + Bit16u eg_level[24]; + Bit16u eg_out[24]; + Bit8u eg_kon[24]; + Bit8u eg_kon_csm[24]; + Bit8u eg_kon_latch[24]; + Bit8u eg_csm_mode[24]; + Bit8u eg_ssg_enable[24]; + Bit8u eg_ssg_pgrst_latch[24]; + Bit8u eg_ssg_repeat_latch[24]; + Bit8u eg_ssg_hold_up_latch[24]; + Bit8u eg_ssg_dir[24]; + Bit8u eg_ssg_inv[24]; + Bit32u eg_read[2]; + Bit8u eg_read_inc; + /* FM */ + Bit16s fm_op1[6][2]; + Bit16s fm_op2[6]; + Bit16s fm_out[24]; + Bit16u fm_mod[24]; + /* Channel */ + Bit16s ch_acc[6]; + Bit16s ch_out[6]; + Bit16s ch_lock; + Bit8u ch_lock_l; + Bit8u ch_lock_r; + Bit16s ch_read; + /* Timer */ + Bit16u timer_a_cnt; + Bit16u timer_a_reg; + Bit8u timer_a_load_lock; + Bit8u timer_a_load; + Bit8u timer_a_enable; + Bit8u timer_a_reset; + Bit8u timer_a_load_latch; + Bit8u timer_a_overflow_flag; + Bit8u timer_a_overflow; + + Bit16u timer_b_cnt; + Bit8u timer_b_subcnt; + Bit16u timer_b_reg; + Bit8u timer_b_load_lock; + Bit8u timer_b_load; + Bit8u timer_b_enable; + Bit8u timer_b_reset; + Bit8u timer_b_load_latch; + Bit8u timer_b_overflow_flag; + Bit8u timer_b_overflow; + + /* Register set */ + Bit8u mode_test_21[8]; + Bit8u mode_test_2c[8]; + Bit8u mode_ch3; + Bit8u mode_kon_channel; + Bit8u mode_kon_operator[4]; + Bit8u mode_kon[24]; + Bit8u mode_csm; + Bit8u mode_kon_csm; + Bit8u dacen; + Bit16s dacdata; + + Bit8u ks[24]; + Bit8u ar[24]; + Bit8u sr[24]; + Bit8u dt[24]; + Bit8u multi[24]; + Bit8u sl[24]; + Bit8u rr[24]; + Bit8u dr[24]; + Bit8u am[24]; + Bit8u tl[24]; + Bit8u ssg_eg[24]; + + Bit16u fnum[6]; + Bit8u block[6]; + Bit8u kcode[6]; + Bit16u fnum_3ch[6]; + Bit8u block_3ch[6]; + Bit8u kcode_3ch[6]; + Bit8u reg_a4; + Bit8u reg_ac; + Bit8u connect[6]; + Bit8u fb[6]; + Bit8u pan_l[6], pan_r[6]; + Bit8u ams[6]; + Bit8u pms[6]; +} ym3438_t; + +void OPN2_Reset(ym3438_t *chip); +void OPN2_SetChipType(Bit32u type); +void OPN2_Clock(ym3438_t *chip, Bit32u *buffer); +void OPN2_Write(ym3438_t *chip, Bit32u port, Bit8u data); +void OPN2_SetTestPin(ym3438_t *chip, Bit32u value); +Bit32u OPN2_ReadTestPin(ym3438_t *chip); +Bit32u OPN2_ReadIRQPin(ym3438_t *chip); +Bit8u OPN2_Read(ym3438_t *chip, Bit32u port); +#endif diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/quartus_usage.txt b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/quartus_usage.txt new file mode 100644 index 0000000000000000000000000000000000000000..86ffc5c36ad31561a919318f05b1c43d666dbb0d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/quartus_usage.txt @@ -0,0 +1,127 @@ +Version 0.61 + ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ +; Compilation Hierarchy Node ; Logic Cells ; Dedicated Logic Registers ; I/O Registers ; Memory Bits ; M9Ks ; DSP Elements ; DSP 9x9 ; DSP 18x18 ; Pins ; Virtual Pins ; LUT-Only LCs ; Register-Only LCs ; LUT/Register LCs ; Full Hierarchy Name ; Library Name ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ +; |jt12 ; 2412 (1) ; 1464 (0) ; 0 (0) ; 7350 ; 7 ; 0 ; 0 ; 0 ; 77 ; 0 ; 948 (1) ; 97 (0) ; 1367 (1) ; |jt12 ; work ; +; |jt12_acc:u_acc| ; 173 (171) ; 95 (93) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 65 (65) ; 27 (27) ; 81 (79) ; |jt12|jt12_acc:u_acc ; work ; +; |jt12_sh:u_acc| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc ; work ; +; |altshift_taps:bits_rtl_0| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0 ; work ; +; |shift_taps_jmm:auto_generated| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated ; work ; +; |altsyncram_rc81:altsyncram2| ; 0 (0) ; 0 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated|altsyncram_rc81:altsyncram2 ; work ; +; |cntr_unf:cntr1| ; 2 (2) ; 2 (2) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (2) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated|cntr_unf:cntr1 ; work ; +; |jt12_eg:u_eg| ; 674 (58) ; 420 (50) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 249 (12) ; 24 (3) ; 401 (21) ; |jt12|jt12_eg:u_eg ; work ; +; |altshift_taps:eg_V_rtl_0| ; 5 (0) ; 2 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0 ; work ; +; |shift_taps_cmm:auto_generated| ; 5 (0) ; 2 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated ; work ; +; |altsyncram_dc81:altsyncram2| ; 0 (0) ; 0 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated|altsyncram_dc81:altsyncram2 ; work ; +; |cntr_tnf:cntr1| ; 5 (5) ; 2 (2) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (3) ; 0 (0) ; 2 (2) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated|cntr_tnf:cntr1 ; work ; +; |jt12_eg_cnt:u_egcnt| ; 20 (20) ; 17 (17) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (3) ; 0 (0) ; 17 (17) ; |jt12|jt12_eg:u_eg|jt12_eg_cnt:u_egcnt ; work ; +; |jt12_eg_comb:u_comb| ; 259 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 225 (0) ; 0 (0) ; 34 (0) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb ; work ; +; |jt12_eg_ctrl:u_ctrl| ; 36 (36) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 28 (28) ; 0 (0) ; 8 (8) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_ctrl:u_ctrl ; work ; +; |jt12_eg_final:u_final| ; 66 (66) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 64 (64) ; 0 (0) ; 2 (2) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_final:u_final ; work ; +; |jt12_eg_pure:u_pure| ; 78 (78) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 70 (70) ; 0 (0) ; 8 (8) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_pure:u_pure ; work ; +; |jt12_eg_step:u_step| ; 79 (79) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 63 (63) ; 0 (0) ; 16 (16) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_step:u_step ; work ; +; |jt12_sh:u_cntsh| ; 24 (24) ; 24 (24) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 21 (21) ; 3 (3) ; |jt12|jt12_eg:u_eg|jt12_sh:u_cntsh ; work ; +; |jt12_sh_rst:u_egsh| ; 210 (210) ; 210 (210) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 210 (210) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_egsh ; work ; +; |jt12_sh_rst:u_egstate| ; 78 (78) ; 72 (72) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 6 (6) ; 0 (0) ; 72 (72) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_egstate ; work ; +; |jt12_sh_rst:u_konsh| ; 24 (24) ; 24 (24) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 24 (24) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_konsh ; work ; +; |jt12_sh_rst:u_ssg_inv| ; 21 (21) ; 21 (21) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 21 (21) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_ssg_inv ; work ; +; |jt12_lfo:u_lfo| ; 27 (27) ; 14 (14) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 13 (13) ; 0 (0) ; 14 (14) ; |jt12|jt12_lfo:u_lfo ; work ; +; |jt12_mmr:u_mmr| ; 502 (174) ; 339 (131) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 162 (45) ; 41 (35) ; 299 (56) ; |jt12|jt12_mmr:u_mmr ; work ; +; |jt12_div:u_div| ; 7 (7) ; 5 (5) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 2 (2) ; 0 (0) ; 5 (5) ; |jt12|jt12_mmr:u_mmr|jt12_div:u_div ; work ; +; |jt12_reg:u_reg| ; 360 (144) ; 203 (10) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 115 (95) ; 6 (3) ; 239 (46) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg ; work ; +; |jt12_kon:u_kon| ; 39 (15) ; 31 (8) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 6 (6) ; 3 (3) ; 30 (7) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_kon:u_kon ; work ; +; |jt12_sh_rst:u_konch| ; 24 (24) ; 23 (23) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 24 (24) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_kon:u_kon|jt12_sh_rst:u_konch ; work ; +; |jt12_mod:u_mod| ; 10 (10) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 9 (9) ; 0 (0) ; 1 (1) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_mod:u_mod ; work ; +; |jt12_opram:u_opram| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram ; work ; +; |altsyncram:ram_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram|altsyncram:ram_rtl_0 ; work ; +; |altsyncram_1od1:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram|altsyncram:ram_rtl_0|altsyncram_1od1:auto_generated ; work ; +; |jt12_sh_rst:u_regch_rl| ; 12 (12) ; 12 (12) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 12 (12) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sh_rst:u_regch_rl ; work ; +; |jt12_sh_rst:u_regch| ; 153 (153) ; 150 (150) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (3) ; 0 (0) ; 150 (150) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sh_rst:u_regch ; work ; +; |jt12_sumch:u_opch_II| ; 2 (2) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 2 (2) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sumch:u_opch_II ; work ; +; |jt12_op:u_op| ; 251 (251) ; 54 (54) ; 0 (0) ; 5632 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 195 (195) ; 2 (2) ; 54 (54) ; |jt12|jt12_op:u_op ; work ; +; |jt12_exprom:u_exprom| ; 0 (0) ; 0 (0) ; 0 (0) ; 2560 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom ; work ; +; |altsyncram:explut_jt51_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 2560 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom|altsyncram:explut_jt51_rtl_0 ; work ; +; |altsyncram_0581:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 2560 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom|altsyncram:explut_jt51_rtl_0|altsyncram_0581:auto_generated ; work ; +; |jt12_logsin:u_logsin| ; 0 (0) ; 0 (0) ; 0 (0) ; 3072 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_logsin:u_logsin ; work ; +; |altsyncram:sinelut_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 3072 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_logsin:u_logsin|altsyncram:sinelut_rtl_0 ; work ; +; |altsyncram_i381:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 3072 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_logsin:u_logsin|altsyncram:sinelut_rtl_0|altsyncram_i381:auto_generated ; work ; +; |jt12_pg:u_pg| ; 752 (33) ; 508 (28) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 239 (5) ; 3 (3) ; 510 (17) ; |jt12|jt12_pg:u_pg ; work ; +; |jt12_pg_comb:u_comb| ; 246 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 233 (0) ; 0 (0) ; 13 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb ; work ; +; |jt12_pg_dt:u_dt| ; 32 (32) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 30 (30) ; 0 (0) ; 2 (2) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_dt:u_dt ; work ; +; |jt12_pg_inc:u_inc| ; 35 (35) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 27 (27) ; 0 (0) ; 8 (8) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_inc:u_inc ; work ; +; |jt12_pg_sum:u_sum| ; 130 (38) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 130 (38) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum ; work ; +; |lpm_mult:Mult0| ; 92 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 92 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum|lpm_mult:Mult0 ; work ; +; |mult_9at:auto_generated| ; 92 (92) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 92 (92) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum|lpm_mult:Mult0|mult_9at:auto_generated ; work ; +; |jt12_pm:u_pm| ; 49 (49) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 46 (46) ; 0 (0) ; 3 (3) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pm:u_pm ; work ; +; |jt12_sh_rst:u_pad| ; 60 (60) ; 60 (60) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 60 (60) ; |jt12|jt12_pg:u_pg|jt12_sh_rst:u_pad ; work ; +; |jt12_sh_rst:u_phsh| ; 421 (421) ; 420 (420) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 1 (1) ; 0 (0) ; 420 (420) ; |jt12|jt12_pg:u_pg|jt12_sh_rst:u_phsh ; work ; +; |jt12_timers:u_timers| ; 69 (1) ; 34 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 24 (0) ; 0 (0) ; 45 (1) ; |jt12|jt12_timers:u_timers ; work ; +; |jt12_timer:timer_A| ; 34 (34) ; 16 (16) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 16 (16) ; 0 (0) ; 18 (18) ; |jt12|jt12_timers:u_timers|jt12_timer:timer_A ; work ; +; |jt12_timer:timer_B| ; 34 (34) ; 18 (18) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 8 (8) ; 0 (0) ; 26 (26) ; |jt12|jt12_timers:u_timers|jt12_timer:timer_B ; work ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ + +Version 0.60 + ++----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +; Fitter Resource Utilization by Entity ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ +; Compilation Hierarchy Node ; Logic Cells ; Dedicated Logic Registers ; I/O Registers ; Memory Bits ; M9Ks ; DSP Elements ; DSP 9x9 ; DSP 18x18 ; Pins ; Virtual Pins ; LUT-Only LCs ; Register-Only LCs ; LUT/Register LCs ; Full Hierarchy Name ; Library Name ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ +; |jt12 ; 2493 (1) ; 1480 (0) ; 0 (0) ; 4630 ; 9 ; 0 ; 0 ; 0 ; 77 ; 0 ; 1013 (1) ; 104 (0) ; 1376 (1) ; |jt12 ; work ; +; |jt12_acc:u_acc| ; 174 (172) ; 95 (93) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 64 (64) ; 29 (29) ; 81 (79) ; |jt12|jt12_acc:u_acc ; work ; +; |jt12_sh:u_acc| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc ; work ; +; |altshift_taps:bits_rtl_0| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0 ; work ; +; |shift_taps_jmm:auto_generated| ; 2 (0) ; 2 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated ; work ; +; |altsyncram_rc81:altsyncram2| ; 0 (0) ; 0 (0) ; 0 (0) ; 280 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated|altsyncram_rc81:altsyncram2 ; work ; +; |cntr_unf:cntr1| ; 2 (2) ; 2 (2) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 2 (2) ; |jt12|jt12_acc:u_acc|jt12_sh:u_acc|altshift_taps:bits_rtl_0|shift_taps_jmm:auto_generated|cntr_unf:cntr1 ; work ; +; |jt12_eg:u_eg| ; 677 (59) ; 420 (50) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 254 (12) ; 26 (3) ; 397 (22) ; |jt12|jt12_eg:u_eg ; work ; +; |altshift_taps:eg_V_rtl_0| ; 5 (0) ; 2 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0 ; work ; +; |shift_taps_cmm:auto_generated| ; 5 (0) ; 2 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (0) ; 0 (0) ; 2 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated ; work ; +; |altsyncram_dc81:altsyncram2| ; 0 (0) ; 0 (0) ; 0 (0) ; 30 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated|altsyncram_dc81:altsyncram2 ; work ; +; |cntr_tnf:cntr1| ; 5 (5) ; 2 (2) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (3) ; 0 (0) ; 2 (2) ; |jt12|jt12_eg:u_eg|altshift_taps:eg_V_rtl_0|shift_taps_cmm:auto_generated|cntr_tnf:cntr1 ; work ; +; |jt12_eg_cnt:u_egcnt| ; 20 (20) ; 17 (17) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 3 (3) ; 0 (0) ; 17 (17) ; |jt12|jt12_eg:u_eg|jt12_eg_cnt:u_egcnt ; work ; +; |jt12_eg_comb:u_comb| ; 259 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 230 (0) ; 0 (0) ; 29 (0) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb ; work ; +; |jt12_eg_ctrl:u_ctrl| ; 36 (36) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 28 (28) ; 0 (0) ; 8 (8) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_ctrl:u_ctrl ; work ; +; |jt12_eg_final:u_final| ; 66 (66) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 66 (66) ; 0 (0) ; 0 (0) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_final:u_final ; work ; +; |jt12_eg_pure:u_pure| ; 78 (78) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 68 (68) ; 0 (0) ; 10 (10) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_pure:u_pure ; work ; +; |jt12_eg_step:u_step| ; 79 (79) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 68 (68) ; 0 (0) ; 11 (11) ; |jt12|jt12_eg:u_eg|jt12_eg_comb:u_comb|jt12_eg_step:u_step ; work ; +; |jt12_sh:u_cntsh| ; 24 (24) ; 24 (24) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 23 (23) ; 1 (1) ; |jt12|jt12_eg:u_eg|jt12_sh:u_cntsh ; work ; +; |jt12_sh_rst:u_egsh| ; 210 (210) ; 210 (210) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 210 (210) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_egsh ; work ; +; |jt12_sh_rst:u_egstate| ; 78 (78) ; 72 (72) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 6 (6) ; 0 (0) ; 72 (72) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_egstate ; work ; +; |jt12_sh_rst:u_konsh| ; 24 (24) ; 24 (24) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 24 (24) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_konsh ; work ; +; |jt12_sh_rst:u_ssg_inv| ; 21 (21) ; 21 (21) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 21 (21) ; |jt12|jt12_eg:u_eg|jt12_sh_rst:u_ssg_inv ; work ; +; |jt12_lfo:u_lfo| ; 27 (27) ; 14 (14) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 13 (13) ; 0 (0) ; 14 (14) ; |jt12|jt12_lfo:u_lfo ; work ; +; |jt12_mmr:u_mmr| ; 499 (173) ; 339 (131) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 159 (43) ; 44 (39) ; 296 (54) ; |jt12|jt12_mmr:u_mmr ; work ; +; |jt12_div:u_div| ; 7 (7) ; 5 (5) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 2 (2) ; 0 (0) ; 5 (5) ; |jt12|jt12_mmr:u_mmr|jt12_div:u_div ; work ; +; |jt12_reg:u_reg| ; 356 (139) ; 203 (10) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 114 (90) ; 5 (1) ; 237 (48) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg ; work ; +; |jt12_kon:u_kon| ; 39 (15) ; 31 (8) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 8 (7) ; 3 (3) ; 28 (6) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_kon:u_kon ; work ; +; |jt12_sh_rst:u_konch| ; 24 (24) ; 23 (23) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 1 (1) ; 0 (0) ; 23 (23) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_kon:u_kon|jt12_sh_rst:u_konch ; work ; +; |jt12_mod:u_mod| ; 10 (10) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 10 (10) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_mod:u_mod ; work ; +; |jt12_opram:u_opram| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram ; work ; +; |altsyncram:ram_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram|altsyncram:ram_rtl_0 ; work ; +; |altsyncram_1od1:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 1408 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_opram:u_opram|altsyncram:ram_rtl_0|altsyncram_1od1:auto_generated ; work ; +; |jt12_sh_rst:u_regch_rl| ; 12 (12) ; 12 (12) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 12 (12) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sh_rst:u_regch_rl ; work ; +; |jt12_sh_rst:u_regch| ; 154 (154) ; 150 (150) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 4 (4) ; 1 (1) ; 149 (149) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sh_rst:u_regch ; work ; +; |jt12_sumch:u_opch_II| ; 2 (2) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 2 (2) ; 0 (0) ; 0 (0) ; |jt12|jt12_mmr:u_mmr|jt12_reg:u_reg|jt12_sumch:u_opch_II ; work ; +; |jt12_op:u_op| ; 332 (332) ; 70 (70) ; 0 (0) ; 2912 ; 4 ; 0 ; 0 ; 0 ; 0 ; 0 ; 259 (259) ; 3 (3) ; 70 (70) ; |jt12|jt12_op:u_op ; work ; +; |jt12_exprom:u_exprom| ; 0 (0) ; 0 (0) ; 0 (0) ; 1440 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom ; work ; +; |altsyncram:explut_jt51_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 1440 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom|altsyncram:explut_jt51_rtl_0 ; work ; +; |altsyncram_d381:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 1440 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_exprom:u_exprom|altsyncram:explut_jt51_rtl_0|altsyncram_d381:auto_generated ; work ; +; |jt12_phrom:u_phrom| ; 0 (0) ; 0 (0) ; 0 (0) ; 1472 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_phrom:u_phrom ; work ; +; |altsyncram:sinetable_rtl_0| ; 0 (0) ; 0 (0) ; 0 (0) ; 1472 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_phrom:u_phrom|altsyncram:sinetable_rtl_0 ; work ; +; |altsyncram_ir71:auto_generated| ; 0 (0) ; 0 (0) ; 0 (0) ; 1472 ; 2 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_op:u_op|jt12_phrom:u_phrom|altsyncram:sinetable_rtl_0|altsyncram_ir71:auto_generated ; work ; +; |jt12_pg:u_pg| ; 750 (30) ; 508 (28) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 236 (2) ; 2 (2) ; 512 (18) ; |jt12|jt12_pg:u_pg ; work ; +; |jt12_pg_comb:u_comb| ; 247 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 233 (0) ; 0 (0) ; 14 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb ; work ; +; |jt12_pg_dt:u_dt| ; 32 (32) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 29 (29) ; 0 (0) ; 3 (3) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_dt:u_dt ; work ; +; |jt12_pg_inc:u_inc| ; 36 (36) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 28 (28) ; 0 (0) ; 8 (8) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_inc:u_inc ; work ; +; |jt12_pg_sum:u_sum| ; 130 (38) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 130 (38) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum ; work ; +; |lpm_mult:Mult0| ; 92 (0) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 92 (0) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum|lpm_mult:Mult0 ; work ; +; |mult_9at:auto_generated| ; 92 (92) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 92 (92) ; 0 (0) ; 0 (0) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pg_sum:u_sum|lpm_mult:Mult0|mult_9at:auto_generated ; work ; +; |jt12_pm:u_pm| ; 49 (49) ; 0 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 46 (46) ; 0 (0) ; 3 (3) ; |jt12|jt12_pg:u_pg|jt12_pg_comb:u_comb|jt12_pm:u_pm ; work ; +; |jt12_sh_rst:u_pad| ; 61 (61) ; 60 (60) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 1 (1) ; 0 (0) ; 60 (60) ; |jt12|jt12_pg:u_pg|jt12_sh_rst:u_pad ; work ; +; |jt12_sh_rst:u_phsh| ; 420 (420) ; 420 (420) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 (0) ; 0 (0) ; 420 (420) ; |jt12|jt12_pg:u_pg|jt12_sh_rst:u_phsh ; work ; +; |jt12_timers:u_timers| ; 69 (1) ; 34 (0) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 27 (0) ; 0 (0) ; 42 (1) ; |jt12|jt12_timers:u_timers ; work ; +; |jt12_timer:timer_A| ; 34 (34) ; 16 (16) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 16 (16) ; 0 (0) ; 18 (18) ; |jt12|jt12_timers:u_timers|jt12_timer:timer_A ; work ; +; |jt12_timer:timer_B| ; 34 (34) ; 18 (18) ; 0 (0) ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 11 (11) ; 0 (0) ; 23 (23) ; |jt12|jt12_timers:u_timers|jt12_timer:timer_B ; work ; ++-------------------------------------------------+-------------+---------------------------+---------------+-------------+------+--------------+---------+-----------+------+--------------+--------------+-------------------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+ diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/slice_usage.txt b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/slice_usage.txt new file mode 100644 index 0000000000000000000000000000000000000000..4956a7c3a381bc6c70eb3902e63e50c769ed5bc1 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/doc/slice_usage.txt @@ -0,0 +1,48 @@ ++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical Name | ++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| jt12/ | | 0/558 | 0/810 | 0/1043 | 0/111 | 0/8 | 0/0 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | jt12 | +| +u_clksync | | 6/11 | 6/11 | 3/4 | 0/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_clksync | +| ++u_cpu2syn | | 2/2 | 2/2 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_clksync/u_cpu2syn | +| ++u_syn2cpu | | 3/3 | 3/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_clksync/u_syn2cpu | +| +u_syn | | 0/547 | 0/799 | 0/1039 | 0/110 | 0/8 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn | +| ++u_acc | | 39/56 | 50/86 | 74/82 | 0/8 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_acc | +| +++u_acc | | 9/9 | 18/18 | 4/4 | 4/4 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_acc/u_acc | +| +++u_buffer | | 8/8 | 18/18 | 4/4 | 4/4 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_acc/u_buffer | +| ++u_eg | | 94/113 | 140/174 | 250/267 | 0/17 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg | +| +++u_aroffsh | | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_aroffsh | +| +++u_cntsh | | 1/1 | 1/1 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_cntsh | +| +++u_egsh | | 8/8 | 20/20 | 10/10 | 10/10 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_egsh | +| +++u_konsh | | 1/1 | 1/1 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_konsh | +| +++u_ssg1sh | | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_ssg1sh | +| +++u_ssg2sh | | 1/1 | 1/1 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_ssg2sh | +| +++u_ssgattsh | | 2/2 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_ssgattsh | +| +++u_ssgen | | 3/3 | 4/4 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_ssgen | +| +++u_statesh | | 1/1 | 3/3 | 3/3 | 3/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_eg/u_statesh | +| ++u_lfo | | 9/9 | 14/14 | 18/18 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_lfo | +| ++u_mmr | | 52/149 | 126/207 | 73/216 | 0/19 | 0/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr | +| +++u_reg | | 69/97 | 18/81 | 117/143 | 0/19 | 0/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg | +| ++++u_kon | | 2/3 | 1/3 | 4/5 | 0/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_kon | +| +++++u_konch | | 1/1 | 2/2 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_kon/u_konch | +| ++++u_mod | | 2/2 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_mod | +| ++++u_opch_III | | 1/1 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_opch_III | +| ++++u_opch_IV | | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_opch_IV | +| ++++u_opch_V | | 2/2 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_opch_V | +| ++++u_opram | | 0/0 | 0/0 | 0/0 | 0/0 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_opram | +| ++++u_regch | | 17/17 | 56/56 | 16/16 | 16/16 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_regch | +| ++++u_regch_rl | | 2/2 | 4/4 | 2/2 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_mmr/u_reg/u_regch_rl | +| ++u_op | | 73/114 | 54/158 | 178/204 | 5/31 | 0/4 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op | +| +++phasemod_sh | | 8/8 | 20/20 | 2/2 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/phasemod_sh | +| +++prev1_buffer | | 13/13 | 28/28 | 8/8 | 8/8 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/prev1_buffer | +| +++prev2_buffer | | 10/10 | 28/28 | 8/8 | 8/8 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/prev2_buffer | +| +++prevprev1_buffer | | 10/10 | 28/28 | 8/8 | 8/8 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/prevprev1_buffer | +| +++u_exprom | | 0/0 | 0/0 | 0/0 | 0/0 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/u_exprom | +| +++u_phrom | | 0/0 | 0/0 | 0/0 | 0/0 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_op/u_phrom | +| ++u_pg | | 74/88 | 105/136 | 190/211 | 14/35 | 2/2 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_pg | +| +++u_phsh | | 13/13 | 30/30 | 20/20 | 20/20 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_pg/u_phsh | +| +++u_rstsh | | 1/1 | 1/1 | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_pg/u_rstsh | +| ++u_timers | | 2/18 | 0/24 | 2/41 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_timers | +| +++timer_A | | 8/8 | 11/11 | 23/23 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_timers/timer_A | +| +++timer_B | | 8/8 | 13/13 | 16/16 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | jt12/u_syn/u_timers/timer_B | ++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/gen_lingain.py b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/gen_lingain.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fbb850cd1170f244b8192eda64a4efa66f5aaf --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/gen_lingain.py @@ -0,0 +1,14 @@ +#!/usr/bin/python + +import sys + +db=0 + +for k in range(64): + lin = 10**(db/20)*511 + sys.stdout.write(" mem[%03d] = 9'd%03d;" % (k, lin)) + if( k%4 == 3 ): + sys.stdout.write("\n") + # else: + # sys.stdout.write(" ") + db = db - 0.75 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm.v new file mode 100644 index 0000000000000000000000000000000000000000..e137e1b0acf4b36226030be2dbff4f833365b1dc --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm.v @@ -0,0 +1,120 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// ADPCM-A algorithm + +module jt10_adpcm( + input rst_n, + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [3:0] data, + input chon, // high if this channel is on + input clr, + output signed [15:0] pcm +); + +localparam sigw = 12; + +reg signed [sigw-1:0] x1, x2, x3, x4, x5, x6; +reg signed [sigw-1:0] inc4; +reg [5:0] step1, step2, step6, step3, step4, step5; +reg [5:0] step_next, step_1p; +reg sign2, sign3, sign4, sign5, xsign5; + +// All outputs from stage 1 +assign pcm = { {16-sigw{x1[sigw-1]}}, x1 }; + +// This could be decomposed in more steps as the pipeline +// has room for it +always @(*) begin + casez( data[2:0] ) + 3'b0??: step_next = step1==6'd0 ? 6'd0 : (step1-1'd1); + 3'b100: step_next = step1+6'd2; + 3'b101: step_next = step1+6'd5; + 3'b110: step_next = step1+6'd7; + 3'b111: step_next = step1+6'd9; + endcase + step_1p = step_next > 6'd48 ? 6'd48 : step_next; +end + +wire [11:0] inc3; +reg [8:0] lut_addr2; + + +jt10_adpcma_lut u_lut( + .clk ( clk ), + .rst_n ( rst_n ), + .cen ( cen ), + .addr ( lut_addr2 ), + .inc ( inc3 ) +); + +// Original pipeline: 6 stages, 6 channels take 36 clock cycles +// 8 MHz -> /12 divider -> 666 kHz +// 666 kHz -> 18.5 kHz = 55.5/3 kHz + +reg chon2, chon3, chon4; +wire [sigw-1:0] inc3_long = { {sigw-12{1'b0}},inc3 }; + +always @( posedge clk or negedge rst_n ) + if( ! rst_n ) begin + x1 <= 'd0; step1 <= 0; + x2 <= 'd0; step2 <= 0; + x3 <= 'd0; step3 <= 0; + x4 <= 'd0; step4 <= 0; + x5 <= 'd0; step5 <= 0; + x6 <= 'd0; step6 <= 0; + sign2 <= 'b0; + chon2 <= 'b0; chon3 <= 'b0; chon4 <= 'b0; + lut_addr2 <= 'd0; + inc4 <= 'd0; + end else if(cen) begin + // I + sign2 <= data[3]; + x2 <= clr ? {sigw-1{1'b0}} : x1; + step2 <= clr ? 6'd0 : (chon ? step_1p : step1); + chon2 <= ~clr && chon; + lut_addr2 <= { step1, data[2:0] }; + // II 2's complement of inc2 if necessary + sign3 <= sign2; + x3 <= x2; + step3 <= step2; + chon3 <= chon2; + // III + //sign4 <= sign3; + inc4 <= sign3 ? ~inc3_long + 1'd1 : inc3_long; + x4 <= x3; + step4 <= step3; + chon4 <= chon3; + // IV + //sign5 <= sign4; + //xsign5 <= x4[sigw-1]; + x5 <= chon4 ? x4 + inc4 : x4; + step5 <= step4; + // V + x6 <= x5; + step6 <= step5; + // VI: close the loop + x1 <= x6; + step1 <= step6; + end + +endmodule // jt10_adpcm diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_acc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_acc.v new file mode 100644 index 0000000000000000000000000000000000000000..2a74678f3ddbb8be3cb465f9f8adad53a315a791 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_acc.v @@ -0,0 +1,90 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Adds all 6 channels and apply linear interpolation to rise +// sampling frequency to 55.5 kHz + +module jt10_adpcm_acc( + input rst_n, + input clk, // CPU clock + input cen, // 111 kHz + // pipeline channel + input [5:0] cur_ch, + input [5:0] en_ch, + input match, + + input en_sum, + input signed [15:0] pcm_in, // 18.5 kHz + output reg signed [15:0] pcm_out // 55.5 kHz +); + +wire signed [17:0] pcm_in_long = en_sum ? { {2{pcm_in[15]}}, pcm_in } : 18'd0; +reg signed [17:0] acc, last, pcm_full; +reg signed [17:0] step; + +reg signed [17:0] diff; +reg signed [22:0] diff_ext, step_full; + +always @(*) begin + diff = acc-last; + diff_ext = { {5{diff[17]}}, diff }; + step_full = diff_ext // 1/128 + + ( diff_ext << 1 ) // 1/64 + + ( diff_ext << 3 ) // 1/16 + + ( diff_ext << 5 ); // 1/4 + +end + +wire adv = en_ch[0] & cur_ch[0]; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + step <= 'd0; + acc <= 18'd0; + last <= 18'd0; + end else if(cen) begin + if( match ) + acc <= cur_ch[0] ? pcm_in_long : ( pcm_in_long + acc ); + if( adv ) begin + // step = diff * (1/4+1/16+1/64+1/128) + step <= { {2{step_full[22]}}, step_full[22:7] }; // >>>7; + last <= acc; + end + end +wire overflow = |pcm_full[17:15] & ~&pcm_full[17:15]; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + pcm_full <= 18'd0; + end else if(cen && cur_ch[0]) begin + case( en_ch ) + 6'b000_001: pcm_full <= last; + 6'b000_100, + 6'b010_000: pcm_full <= pcm_full + step; + default:; + endcase + if( overflow ) + pcm_out <= pcm_full[17] ? 16'h8000 : 16'h7fff; // saturate + else + pcm_out <= pcm_full[15:0]; + end + +endmodule // jt10_adpcm_acc \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_cnt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_cnt.v new file mode 100644 index 0000000000000000000000000000000000000000..3e1cec07f31f2f9eb1104a066b80f5fe5250c54b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_cnt.v @@ -0,0 +1,194 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt10_adpcm_cnt( + input rst_n, + input clk, // CPU clock + input cen, // 666 kHz + // pipeline channel + input [ 5:0] cur_ch, + input [ 5:0] en_ch, + // Address writes from CPU + input [16:0] addr_in, + input [ 2:0] addr_ch, + input up_start, + input up_end, + // Counter control + input aon, + input aoff, + // ROM driver + output [19:0] addr_out, + output [ 4:0] bank, + output sel, + output roe_n, + output decon, + output clr, // inform the decoder that a new section begins + // Flags + output reg [ 5:0] flags, + input [ 5:0] clr_flags, + // + output [16:0] start_top, + output [16:0] end_top +); + +reg [20:0] addr1, addr2, addr3, addr4, addr5, addr6; +reg [4:0] bank1, bank2, bank3, bank4, bank5, bank6; +reg [11:0] start1, start2, start3, start4, start5, start6, + end1, end2, end3, end4, end5, end6; +reg on1, on2, on3, on4, on5, on6; +reg done1, done2, done3, done4, done5, done6; +reg [5:0] done_sr, zero; + +reg roe_n1, decon1; + +reg clr1, clr2, clr3, clr4, clr5, clr6; +reg skip1, skip2, skip3, skip4, skip5, skip6; + +// All outputs from stage 1 +assign addr_out = addr1[20:1]; +assign sel = addr1[0]; +assign bank = bank1; +assign roe_n = roe_n1; +assign clr = clr1; +assign decon = decon1; + +// Two cycles early: 0 0 1 1 2 2 3 3 4 4 5 5 +wire active5 = (en_ch[1] && cur_ch[4]) || (en_ch[2] && cur_ch[5]) || (en_ch[2] && cur_ch[0]) || (en_ch[3] && cur_ch[1]) || (en_ch[4] && cur_ch[2]) || (en_ch[5] && cur_ch[3]);//{ cur_ch[3:0], cur_ch[5:4] } == en_ch; +wire sumup5 = on5 && !done5 && active5; +reg sumup6; + +reg [5:0] last_done, set_flags; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + zero <= 6'd1; + done_sr <= ~6'd0; + last_done <= ~6'd0; + end else if(cen) begin + zero <= { zero[0], zero[5:1] }; + done_sr <= { done1, done_sr[5:1]}; + if( zero[0] ) begin + last_done <= done_sr; + set_flags <= ~last_done & done_sr; + end + end + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + flags <= 6'd0; + end else begin + flags <= ~clr_flags & (set_flags | flags); + end + +`ifdef SIMULATION +wire [11:0] addr1_cmp = addr1[20:9]; +`endif + +assign start_top = {bank1, start1}; +assign end_top = {bank1, end1}; + +reg [5:0] addr_ch_dec; + +always @(*) + case(addr_ch) + 3'd0: addr_ch_dec = 6'b000_001; + 3'd1: addr_ch_dec = 6'b000_010; + 3'd2: addr_ch_dec = 6'b000_100; + 3'd3: addr_ch_dec = 6'b001_000; + 3'd4: addr_ch_dec = 6'b010_000; + 3'd5: addr_ch_dec = 6'b100_000; + default: addr_ch_dec = 6'd0; + endcase // up_addr + +wire up1 = cur_ch == addr_ch_dec; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + addr1 <= 'd0; addr2 <= 'd0; addr3 <= 'd0; + addr4 <= 'd0; addr5 <= 'd0; addr6 <= 'd0; + done1 <= 'd1; done2 <= 'd1; done3 <= 'd1; + done4 <= 'd1; done5 <= 'd1; done6 <= 'd1; + start1 <= 'd0; start2 <= 'd0; start3 <= 'd0; + start4 <= 'd0; start5 <= 'd0; start6 <= 'd0; + end1 <= 'd0; end2 <= 'd0; end3 <= 'd0; + end4 <= 'd0; end5 <= 'd0; end6 <= 'd0; + skip1 <= 'd0; skip2 <= 'd0; skip3 <= 'd0; + skip4 <= 'd0; skip5 <= 'd0; skip6 <= 'd0; + end else if( cen ) begin + addr2 <= addr1; + on2 <= aoff ? 1'b0 : (aon | (on1 && ~done1)); + clr2 <= aoff || aon || done1; // Each time a A-ON is sent the address counter restarts + done2 <= done1; + start2 <= (up_start && up1) ? addr_in[11:0] : start1; + end2 <= (up_end && up1) ? addr_in[11:0] : end1; + bank2 <= (up_start && up1) ? addr_in[16:12] : bank1; + skip2 <= skip1; + + addr3 <= addr2; // clr2 ? {start2,9'd0} : addr2; + on3 <= on2; + clr3 <= clr2; + done3 <= done2; + start3 <= start2; + end3 <= end2; + bank3 <= bank2; + skip3 <= skip2; + + addr4 <= addr3; + on4 <= on3; + clr4 <= clr3; + done4 <= done3; + start4 <= start3; + end4 <= end3; + bank4 <= bank3; + skip4 <= skip3; + + addr5 <= addr4; + on5 <= on4; + clr5 <= clr4; + done5 <= ~on4 ? done4 : (addr4[20:9] == end4 && addr4[8:0]==~9'b0 && ~clr4); + start5 <= start4; + end5 <= end4; + bank5 <= bank4; + skip5 <= skip4; + // V + addr6 <= addr5; + on6 <= on5; + clr6 <= clr5; + done6 <= done5; + start6 <= start5; + end6 <= end5; + bank6 <= bank5; + sumup6 <= sumup5; + skip6 <= skip5; + + addr1 <= (clr6 && on6) ? {start6,9'd0} : (sumup6 && ~skip6 ? addr6+21'd1 :addr6); + on1 <= on6; + done1 <= done6; + start1 <= start6; + end1 <= end6; + roe_n1 <= ~sumup6; + decon1 <= sumup6; + bank1 <= bank6; + clr1 <= clr6; + skip1 <= (clr6 && on6) ? 1'b1 : sumup6 ? 1'b0 : skip6; + end + +endmodule // jt10_adpcm_cnt diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_comb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..c0f63ac715255debce2fd0a8789a02d19d9a4994 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_comb.v @@ -0,0 +1,134 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Sampling rates: 2kHz ~ 55.5 kHz. in 0.85Hz steps + +module jt10_adpcm_comb( + input rst_n, + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [3:0] data, + input chon, // high if this channel is on + output signed [15:0] pcm +); + +localparam stepw = 15; + +reg signed [15:0] x1, x2, x3, x4, x5, x6; +reg [stepw-1:0] step1, step2, step6; +reg [stepw+1:0] step3, step4, step5; +assign pcm = x2; + +reg [18:0] d2l; +reg [15:0] d3,d4; +reg [3:0] d1,d2; +reg sign2, sign3, sign4, sign5; +reg [7:0] step_val; +reg [22:0] step2l; + +// Original pipeline: 6 stages, 6 channels take 36 clock cycles +// 8 MHz -> /12 divider -> 666 kHz +// 666 kHz -> 18.5 kHz = 55.5/3 kHz + +reg chon2, chon3, chon4, chon5; +reg signEqu4, signEqu5; +reg [3:0] data1,data2; + +always @( * ) + if( ! rst_n ) begin + x2 = 'd0; step2 = 'd127; + x3 = 'd0; step3 = 'd127; + x4 = 'd0; step4 = 'd127; + x5 = 'd0; step5 = 'd127; + x6 = 'd0; step6 = 'd127; + d2 = 'd0; d3 = 'd0; d4 = 'd0; + sign2 = 'b0; + sign3 = 'b0; + sign4 = 'b0; sign5 = 'b0; + chon2 = 'b0; chon3 = 'b0; chon4 = 'b0; chon5 = 1'b0; + end else begin + // I + d2 = d1; + sign2 = data1[3]; + data2 = data1; + x2 = x1; + step2 = step1; + chon2 = chon; + // II multiply and obtain the offset + casez( d2[3:1] ) + 3'b0_??: step_val = 8'd57; + 3'b1_00: step_val = 8'd77; + 3'b1_01: step_val = 8'd102; + 3'b1_10: step_val = 8'd128; + 3'b1_11: step_val = 8'd153; + endcase // data[2:0] + d2l = d2 * step2; // 4 + 15 = 19 bits -> div by 8 -> 16 bits + step2l = step_val * step2; // 15 bits + 8 bits = 23 bits -> div 64 -> 17 bits + d3 = d2l[18:3]; // 16 bits + sign3 = sign2; + x3 = x2; + step3 = step2l[22:6]; + chon3 = chon2; + // III 2's complement of d3 if necessary + d4 = sign3 ? ~d3+16'b1 : d3; + sign4 = sign3; + signEqu4 = sign3 == x3[15]; + x4 = x3; + step4 = step3; + chon4 = chon3; + // IV Advance the waveform + x5 = x4+d4; + sign5 = sign4; + signEqu5 = signEqu4; + step5 = step4; + chon5 = chon4; + // V: limit or reset outputs + if( chon5 ) begin + if( signEqu5 && (sign5!=x5[15]) ) + x6 = sign5 ? 16'h8000 : 16'h7FFF; + else + x6 = x5; + + if( step5 < 127 ) + step6 = 15'd127; + else if( step5 > 24576 ) + step6 = 15'd24576; + else + step6 = step5[14:0]; + end else begin + x6 = 'd0; + step6 = 'd127; + end + end + +always @(posedge clk or negedge rst_n) + if( ! rst_n ) begin + x1 <= 'd0; step1 <= 'd127; + d1 <= 'd0; data1 <= 'd0; + end else if(cen) begin + // VI: close the loop + d1 <= {data[2:0],1'b1}; + x1 <= x6; + step1 <= step6; + data1 <= data; + end + +endmodule // jt10_adpcm \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dbrom.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dbrom.v new file mode 100644 index 0000000000000000000000000000000000000000..10d15387743b8f43763817a7384331760cd92944 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dbrom.v @@ -0,0 +1,54 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// dB to linear + +module jt10_adpcm_dbrom( + input clk, // CPU clock + input [5:0] db, + output reg [8:0] lin +); + +reg [8:0] mem[0:63]; + +initial begin // generated with file gen_lingain.py + mem[000] = 9'd511; mem[001] = 9'd468; mem[002] = 9'd429; mem[003] = 9'd394; + mem[004] = 9'd361; mem[005] = 9'd331; mem[006] = 9'd304; mem[007] = 9'd279; + mem[008] = 9'd256; mem[009] = 9'd234; mem[010] = 9'd215; mem[011] = 9'd197; + mem[012] = 9'd181; mem[013] = 9'd166; mem[014] = 9'd152; mem[015] = 9'd139; + mem[016] = 9'd128; mem[017] = 9'd117; mem[018] = 9'd107; mem[019] = 9'd099; + mem[020] = 9'd090; mem[021] = 9'd083; mem[022] = 9'd076; mem[023] = 9'd070; + mem[024] = 9'd064; mem[025] = 9'd059; mem[026] = 9'd054; mem[027] = 9'd049; + mem[028] = 9'd045; mem[029] = 9'd041; mem[030] = 9'd038; mem[031] = 9'd035; + mem[032] = 9'd032; mem[033] = 9'd029; mem[034] = 9'd027; mem[035] = 9'd024; + mem[036] = 9'd022; mem[037] = 9'd020; mem[038] = 9'd019; mem[039] = 9'd017; + mem[040] = 9'd016; mem[041] = 9'd014; mem[042] = 9'd013; mem[043] = 9'd012; + mem[044] = 9'd011; mem[045] = 9'd010; mem[046] = 9'd009; mem[047] = 9'd008; + mem[048] = 9'd008; mem[049] = 9'd007; mem[050] = 9'd006; mem[051] = 9'd006; + mem[052] = 9'd005; mem[053] = 9'd005; mem[054] = 9'd004; mem[055] = 9'd004; + mem[056] = 9'd004; mem[057] = 9'd003; mem[058] = 9'd003; mem[059] = 9'd003; + mem[060] = 9'd002; mem[061] = 9'd002; mem[062] = 9'd002; mem[063] = 9'd002; +end + +always @(posedge clk) + lin <= mem[db]; + +endmodule // jt10_adpcm_dbrom \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_div.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_div.v new file mode 100644 index 0000000000000000000000000000000000000000..e669874c85bdb881e91dd144086702c5f6330c0f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_div.v @@ -0,0 +1,62 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// calculates d=a/b +// a = b*d + r + +module jt10_adpcm_div #(parameter DW=16)( + input rst_n, + input clk, // CPU clock + input cen, + input start, // strobe + input [DW-1:0] a, + input [DW-1:0] b, + output reg [DW-1:0] d, + output reg [DW-1:0] r, + output working +); + +reg [DW-1:0] cycle; +assign working = cycle[0]; + +wire [DW:0] sub = { r[DW-2:0], d[DW-1] } - b; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + cycle <= 'd0; + end else if(cen) begin + if( start ) begin + cycle <= {DW{1'b1}}; + r <= 0; + d <= a; + end else if(cycle[0]) begin + cycle <= { 1'b0, cycle[DW-1:1] }; + if( sub[DW] == 0 ) begin + r <= sub[DW-1:0]; + d <= { d[DW-2:0], 1'b1}; + end else begin + r <= { r[DW-2:0], d[DW-1] }; + d <= { d[DW-2:0], 1'b0 }; + end + end + end + +endmodule // jt10_adpcm_div diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvA.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvA.v new file mode 100644 index 0000000000000000000000000000000000000000..e98ea7c69acc8bbf14bfa9fb9f3993b51faa0151 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvA.v @@ -0,0 +1,334 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt10_adpcm_drvA( + input rst_n, + input clk, // CPU clock + input cen, // same cen as MMR + input cen6, // clk & cen = 666 kHz + input cen1, // clk & cen = 111 kHz + + output [19:0] addr, // real hardware has 10 pins multiplexed through RMPX pin + output [4:0] bank, + output roe_n, // ADPCM-A ROM output enable + + // Control Registers + input [5:0] atl, // ADPCM Total Level + input [7:0] lracl_in, + input [16:0] addr_in, + + input [2:0] up_lracl, + input up_start, + input up_end, + input [2:0] up_addr, + + input [7:0] aon_cmd, // ADPCM ON equivalent to key on for FM + input up_aon, + + input [7:0] datain, + + // Flags + output [5:0] flags, + input [5:0] clr_flags, + + output signed [15:0] pcm55_l, + output signed [15:0] pcm55_r, + input [5:0] ch_enable +); + +reg [5:0] cur_ch; +reg [5:0] en_ch; +reg [3:0] data; +wire nibble_sel; +wire signed [15:0] pcm_att; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + data <= 4'd0; + end else if(cen) begin + data <= !nibble_sel ? datain[7:4] : datain[3:0]; + end + +reg [ 5:0] aon_sr, aoff_sr; + +reg [7:0] aon_cmd_cpy; + +always @(posedge clk) if(cen) begin + if( up_aon ) aon_cmd_cpy <= aon_cmd; else if(cur_ch[5] && cen6) aon_cmd_cpy <= 8'd0; +end + +always @(posedge clk) if(cen6) begin + if( cur_ch[5] ) begin + aon_sr <= ~{6{aon_cmd_cpy[7]}} & aon_cmd_cpy[5:0]; + aoff_sr <= {6{aon_cmd_cpy[7]}} & aon_cmd_cpy[5:0]; + end else begin + aon_sr <= { 1'b0, aon_sr[5:1] }; + aoff_sr <= { 1'b0, aoff_sr[5:1] }; + end +end + +reg match; // high when cur_ch==en_ch, but calculated one clock cycle ahead + // so it can be latched +wire [5:0] cur_next = { cur_ch[4:0], cur_ch[5] }; +wire [5:0] en_next = { en_ch[0], en_ch[5:1] }; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + cur_ch <= 6'b1; en_ch <= 6'b1; + match <= 0; + end else if( cen6 ) begin + cur_ch <= cur_next; + if( cur_ch[5] ) en_ch <= en_next; + match <= cur_next == (cur_ch[5] ? en_next : en_ch); + end + +wire [16:0] start_top, end_top; + +wire clr_dec, decon; + +jt10_adpcm_cnt u_cnt( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen6 ), + // Pipeline + .cur_ch ( cur_ch ), + .en_ch ( en_ch ), + // START/END update + .addr_in ( addr_in ), + .addr_ch ( up_addr ), + .up_start ( up_start ), + .up_end ( up_end ), + // Control + .aon ( aon_sr[0] ), + .aoff ( aoff_sr[0] ), + .clr ( clr_dec ), + // ROM driver + .addr_out ( addr ), + .bank ( bank ), + .sel ( nibble_sel ), + .roe_n ( roe_n ), + .decon ( decon ), + // Flags + .flags ( flags ), + .clr_flags ( clr_flags ), + .start_top ( start_top ), + .end_top ( end_top ) +); + +// wire chactive = chon & cen6; +wire signed [15:0] pcmdec; + +jt10_adpcm u_decoder( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen6 ), + .data ( data ), + .chon ( decon ), + .clr ( clr_dec ), + .pcm ( pcmdec ) +); +/* + +always @(posedge clk) begin + if( cen3 && chon ) begin + pcm55_l <= pre_pcm55_l; + pcm55_r <= pre_pcm55_r; + end +end +*/ + +wire [1:0] lr; + +jt10_adpcm_gain u_gain( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen6 ), + // Pipeline + .cur_ch ( cur_ch ), + .en_ch ( en_ch ), + .match ( match ), + // Gain control + .atl ( atl ), // ADPCM Total Level + .lracl ( lracl_in ), + .up_ch ( up_lracl ), + + .lr ( lr ), + .pcm_in ( pcmdec ), + .pcm_att( pcm_att ) +); + +wire signed [15:0] pre_pcm55_l, pre_pcm55_r; + +assign pcm55_l = pre_pcm55_l; +assign pcm55_r = pre_pcm55_r; + +jt10_adpcm_acc u_acc_left( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen6 ), + // Pipeline + .cur_ch ( cur_ch ), + .en_ch ( en_ch ), + .match ( match ), + // left/right enable + .en_sum ( lr[1] && (ch_enable & cur_ch) ), + + .pcm_in ( pcm_att ), // 18.5 kHz + .pcm_out( pre_pcm55_l ) // 55.5 kHz +); + +jt10_adpcm_acc u_acc_right( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen6 ), + // Pipeline + .cur_ch ( cur_ch ), + .en_ch ( en_ch ), + .match ( match ), + // left/right enable + .en_sum ( lr[0] && (ch_enable & cur_ch) ), + + .pcm_in ( pcm_att ), // 18.5 kHz + .pcm_out( pre_pcm55_r ) // 55.5 kHz +); + + +`ifdef SIMULATION +integer fch0, fch1, fch2, fch3, fch4, fch5; +initial begin + fch0 = $fopen("ch0.dec","w"); + fch1 = $fopen("ch1.dec","w"); + fch2 = $fopen("ch2.dec","w"); + fch3 = $fopen("ch3.dec","w"); + fch4 = $fopen("ch4.dec","w"); + fch5 = $fopen("ch5.dec","w"); +end + +reg signed [15:0] pcm_ch0, pcm_ch1, pcm_ch2, pcm_ch3, pcm_ch4, pcm_ch5; +always @(posedge cen6) if(en_ch[0]) begin + if(cur_ch[0]) begin + pcm_ch0 <= pcmdec; + $fwrite( fch0, "%d\n", pcmdec ); + end + if(cur_ch[1]) begin + pcm_ch1 <= pcmdec; + $fwrite( fch1, "%d\n", pcmdec ); + end + if(cur_ch[2]) begin + pcm_ch2 <= pcmdec; + $fwrite( fch2, "%d\n", pcmdec ); + end + if(cur_ch[3]) begin + pcm_ch3 <= pcmdec; + $fwrite( fch3, "%d\n", pcmdec ); + end + if(cur_ch[4]) begin + pcm_ch4 <= pcmdec; + $fwrite( fch4, "%d\n", pcmdec ); + end + if(cur_ch[5]) begin + pcm_ch5 <= pcmdec; + $fwrite( fch5, "%d\n", pcmdec ); + end +end + +reg [15:0] sim_start0, sim_start1, sim_start2, sim_start3, sim_start4, sim_start5; +reg [15:0] sim_end0, sim_end1, sim_end2, sim_end3, sim_end4, sim_end5; +reg [ 7:0] sim_lracl0, sim_lracl1, sim_lracl2, sim_lracl3, sim_lracl4, sim_lracl5; +/* +reg div3b; +reg [2:0] chframe; +always @(posedge clk) div3b<=div3; +always @(negedge div3b) chframe <= chfast; + + +reg [7:0] aon_cpy, aon_cpy2; +always @(posedge clk) begin + aon_cpy<=aon_cmd; // This prevents a Verilator circular-logic warning + aon_cpy2 <= aon_cmd; +end + +always @(posedge aon_cpy[0]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 0 - %X",sim_start0); +always @(posedge aon_cpy[1]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 1 - %X",sim_start1); +always @(posedge aon_cpy[2]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 2 - %X",sim_start2); +always @(posedge aon_cpy[3]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 3 - %X",sim_start3); +always @(posedge aon_cpy[4]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 4 - %X",sim_start4); +always @(posedge aon_cpy[5]) if(!aon_cpy2[7]) $display("INFO: ADPCM-A ON 5 - %X",sim_start5); +*/ +always @(posedge cen6) if(up_start) + case(up_addr) + 3'd0: sim_start0 <= addr_in; + 3'd1: sim_start1 <= addr_in; + 3'd2: sim_start2 <= addr_in; + 3'd3: sim_start3 <= addr_in; + 3'd4: sim_start4 <= addr_in; + 3'd5: sim_start5 <= addr_in; + default:; + endcase // up_addr + +always @(posedge cen6) if(up_end) + case(up_addr) + 3'd0: sim_end0 <= addr_in; + 3'd1: sim_end1 <= addr_in; + 3'd2: sim_end2 <= addr_in; + 3'd3: sim_end3 <= addr_in; + 3'd4: sim_end4 <= addr_in; + 3'd5: sim_end5 <= addr_in; + default:; + endcase // up_addr + +always @(posedge cen6) + case(up_lracl) + 3'd0: sim_lracl0 <= lracl_in; + 3'd1: sim_lracl1 <= lracl_in; + 3'd2: sim_lracl2 <= lracl_in; + 3'd3: sim_lracl3 <= lracl_in; + 3'd4: sim_lracl4 <= lracl_in; + 3'd5: sim_lracl5 <= lracl_in; + default:; + endcase // up_addr + + /* +reg start_error, end_error; +always @(posedge cen6) begin + case(chframe) + 3'd0: start_error <= start_top != sim_start0; + 3'd1: start_error <= start_top != sim_start1; + 3'd2: start_error <= start_top != sim_start2; + 3'd3: start_error <= start_top != sim_start3; + 3'd4: start_error <= start_top != sim_start4; + 3'd5: start_error <= start_top != sim_start5; + default:; + endcase + case(chframe) + 3'd0: end_error <= end_top != sim_end0; + 3'd1: end_error <= end_top != sim_end1; + 3'd2: end_error <= end_top != sim_end2; + 3'd3: end_error <= end_top != sim_end3; + 3'd4: end_error <= end_top != sim_end4; + 3'd5: end_error <= end_top != sim_end5; + default:; + endcase +end +*/ +`endif + +endmodule // jt10_adpcm_drvA \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvB.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvB.v new file mode 100644 index 0000000000000000000000000000000000000000..8561f5376875899f17bb02594184356356a10c8b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_drvB.v @@ -0,0 +1,131 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt10_adpcm_drvB( + input rst_n, + input clk, + input cen, // 8MHz cen + input cen55, // clk & cen55 = 55 kHz + // Control + input acmd_on_b, // Control - Process start, Key On + input acmd_rep_b, // Control - Repeat + input acmd_rst_b, // Control - Reset + input acmd_up_b, // Control - New command received + input [ 1:0] alr_b, // Left / Right + input [15:0] astart_b, // Start address + input [15:0] aend_b, // End address + input [15:0] adeltan_b, // Delta-N + input [ 7:0] aeg_b, // Envelope Generator Control + output flag, + input clr_flag, + // memory + output [23:0] addr, + input [ 7:0] data, + output reg roe_n, + + output reg signed [15:0] pcm55_l, + output reg signed [15:0] pcm55_r +); + +wire nibble_sel; +wire adv; // advance to next reading +wire clr_dec; +wire chon; + +// `ifdef SIMULATION +// real fsample; +// always @(posedge acmd_on_b) begin +// fsample = adeltan_b; +// fsample = fsample/65536; +// fsample = fsample * 55.5; +// $display("\nINFO: ADPCM-B ON: %X delta N = %6d (%2.1f kHz)", astart_b, adeltan_b, fsample ); +// end +// `endif + +always @(posedge clk) roe_n <= ~(adv & cen55); + +jt10_adpcmb_cnt u_cnt( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen55 ), + .delta_n ( adeltan_b ), + .acmd_up_b ( acmd_up_b ), + .clr ( acmd_rst_b ), + .on ( acmd_on_b ), + .astart ( astart_b ), + .aend ( aend_b ), + .arepeat ( acmd_rep_b ), + .addr ( addr ), + .nibble_sel ( nibble_sel ), + // Flag control + .chon ( chon ), + .clr_flag ( clr_flag ), + .flag ( flag ), + .clr_dec ( clr_dec ), + .adv ( adv ) +); + +reg [3:0] din; + +always @(posedge clk) din <= !nibble_sel ? data[7:4] : data[3:0]; + +wire signed [15:0] pcmdec, pcminter, pcmgain; + +jt10_adpcmb u_decoder( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen ), + .adv ( adv & cen55 ), + .data ( din ), + .chon ( chon ), + .clr ( clr_dec ), + .pcm ( pcmdec ) +); + +`ifndef NOBINTERPOL +jt10_adpcmb_interpol u_interpol( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen ), + .cen55 ( cen55 && chon ), + .adv ( adv ), + .pcmdec ( pcmdec ), + .pcmout ( pcminter ) +); +`else +assign pcminter = pcmdec; +`endif + +jt10_adpcmb_gain u_gain( + .rst_n ( rst_n ), + .clk ( clk ), + .cen55 ( cen55 ), + .tl ( aeg_b ), + .pcm_in ( pcminter ), + .pcm_out( pcmgain ) +); + +always @(posedge clk) if(cen55) begin + pcm55_l <= alr_b[1] ? pcmgain : 16'd0; + pcm55_r <= alr_b[0] ? pcmgain : 16'd0; +end + +endmodule // jt10_adpcm_drvB diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dt.v new file mode 100644 index 0000000000000000000000000000000000000000..06aba77685463eed27c6cc458eebe03fe0e42181 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_dt.v @@ -0,0 +1,130 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Sampling rates: 2kHz ~ 55.5 kHz. in 0.85Hz steps + +module jt10_adpcm_dt( + input rst_n, + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [3:0] data, + input chon, // high if this channel is on + output signed [15:0] pcm +); + +localparam stepw = 15; + +reg signed [15:0] x1, x2, x3, x4, x5, x6; +reg [stepw-1:0] step1, step2, step6; +reg [stepw+1:0] step3, step4, step5; +assign pcm = x2; + +reg [18:0] d2l; +reg [15:0] d3,d4; +reg [3:0] d2; +reg sign2, sign3, sign4, sign5; +reg [7:0] step_val; +reg [22:0] step2l; + +always @(*) begin + casez( d2[3:1] ) + 3'b0_??: step_val = 8'd57; + 3'b1_00: step_val = 8'd77; + 3'b1_01: step_val = 8'd102; + 3'b1_10: step_val = 8'd128; + 3'b1_11: step_val = 8'd153; + endcase // data[2:0] + d2l = d2 * step2; // 4 + 15 = 19 bits -> div by 8 -> 16 bits + step2l = step_val * step2; // 15 bits + 8 bits = 23 bits -> div 64 -> 17 bits +end + +// Original pipeline: 6 stages, 6 channels take 36 clock cycles +// 8 MHz -> /12 divider -> 666 kHz +// 666 kHz -> 18.5 kHz = 55.5/3 kHz + +reg chon2, chon3, chon4, chon5; +reg signEqu4, signEqu5; +reg [3:0] data2; + +always @( posedge clk or negedge rst_n ) + if( ! rst_n ) begin + x1 <= 'd0; step1 <= 'd127; + x2 <= 'd0; step2 <= 'd127; + x3 <= 'd0; step3 <= 'd127; + x4 <= 'd0; step4 <= 'd127; + x5 <= 'd0; step5 <= 'd127; + x6 <= 'd0; step6 <= 'd127; + d2 <= 'd0; d3 <= 'd0; d4 <= 'd0; + sign2 <= 'b0; + sign3 <= 'b0; + sign4 <= 'b0; sign5 <= 'b0; + chon2 <= 'b0; chon3 <= 'b0; chon4 <= 'b0; chon5 <= 1'b0; + end else if(cen) begin + // I + d2 <= {data[2:0],1'b1}; + sign2 <= data[3]; + data2 <= data; + x2 <= x1; + step2 <= step1; + chon2 <= chon; + // II multiply and obtain the offset + d3 <= d2l[18:3]; // 16 bits + sign3 <= sign2; + x3 <= x2; + step3 <= step2l[22:6]; + chon3 <= chon2; + // III 2's complement of d3 if necessary + d4 <= sign3 ? ~d3+16'b1 : d3; + sign4 <= sign3; + signEqu4 <= sign3 == x3[15]; + x4 <= x3; + step4 <= step3; + chon4 <= chon3; + // IV Advance the waveform + x5 <= x4+d4; + sign5 <= sign4; + signEqu5 <= signEqu4; + step5 <= step4; + chon5 <= chon4; + // V: limit or reset outputs + if( chon5 ) begin + if( signEqu5 && (sign5!=x5[15]) ) + x6 <= sign5 ? 16'h8000 : 16'h7FFF; + else + x6 <= x5; + + if( step5 < 127 ) + step6 <= 15'd127; + else if( step5 > 24576 ) + step6 <= 15'd24576; + else + step6 <= step5[14:0]; + end else begin + x6 <= 'd0; + step6 <= 'd127; + end + // VI: close the loop + x1 <= x6; + step1 <= step6; + end + + +endmodule // jt10_adpcm \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_gain.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_gain.v new file mode 100644 index 0000000000000000000000000000000000000000..48f2985c7ab53b9e47d76b636fdc2b7f263dc51b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcm_gain.v @@ -0,0 +1,176 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt10_adpcm_gain( + input rst_n, + input clk, // CPU clock + input cen, // 666 kHz + // pipeline channel + input [5:0] cur_ch, + input [5:0] en_ch, + input match, + + input [5:0] atl, // ADPCM Total Level + // Gain update + input [7:0] lracl, + input [2:0] up_ch, + // Data + output [1:0] lr, + input signed [15:0] pcm_in, + output signed [15:0] pcm_att +); + +reg [9:0] lin_5b, lin1, lin2, lin6; +reg [7:0] lracl1, lracl2, lracl3, lracl4, lracl5, lracl6; +reg [6:0] db5; +reg [5:0] up_ch_dec; +reg [3:0] sh1, sh6; + +always @(*) + case(up_ch) + 3'd0: up_ch_dec = 6'b000_001; + 3'd1: up_ch_dec = 6'b000_010; + 3'd2: up_ch_dec = 6'b000_100; + 3'd3: up_ch_dec = 6'b001_000; + 3'd4: up_ch_dec = 6'b010_000; + 3'd5: up_ch_dec = 6'b100_000; + default: up_ch_dec = 6'd0; + endcase + +//wire [5:0] en_ch2 = { en_ch[4:0], en_ch[5] }; // shift the bits to fit in the pipeline slot correctly + +always @(*) + case( db5[2:0] ) + 3'd0: lin_5b = 10'd512; + 3'd1: lin_5b = 10'd470; + 3'd2: lin_5b = 10'd431; + 3'd3: lin_5b = 10'd395; + 3'd4: lin_5b = 10'd362; + 3'd5: lin_5b = 10'd332; + 3'd6: lin_5b = 10'd305; + 3'd7: lin_5b = 10'd280; + endcase + + +// dB to linear conversion +assign lr = lracl1[7:6]; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + lracl1 <= 8'd0; lracl2 <= 8'd0; + lracl3 <= 8'd0; lracl4 <= 8'd0; + lracl5 <= 8'd0; lracl6 <= 8'd0; + db5 <= 'd0; + sh1 <= 4'd0; sh6 <= 4'd0; + lin1 <= 10'd0; + lin6 <= 10'd0; + end else if(cen) begin + + // I + lracl2 <= up_ch_dec == cur_ch ? lracl : lracl1; + // II + lracl3 <= lracl2; + // III + lracl4 <= lracl3; + // IV: new data is accepted here + lracl5 <= lracl4; + db5 <= { 2'b0, ~lracl4[4:0] } + {1'b0, ~atl}; + // V + lracl6 <= lracl5; + lin6 <= lin_5b; + sh6 <= db5[6:3]; + // VI close the loop + lracl1 <= lracl6; + lin1 <= sh6[3] ? 10'h0 : lin6; + sh1 <= sh6; + end + +// Apply gain +// The pipeline has 6 stages, there is new input data once every 6*6=36 clock cycles +// New data is read once and it takes 4*6 cycles to get through because the shift +// operation is distributed among several iterations. This prevents the need of +// a 10x16-input mux which is very large. Instead of that, this uses two 10x2-input mux'es +// which iterated allow the max 16 shift operation + +reg [3:0] shcnt1, shcnt2, shcnt3, shcnt4, shcnt5, shcnt6; + +reg shcnt_mod3, shcnt_mod4, shcnt_mod5; +reg [31:0] pcm2_mul; +wire signed [15:0] lin2s = {6'b0,lin2}; +reg signed [15:0] pcm1, pcm2, pcm3, pcm4, pcm5, pcm6; +reg match2; + +always @(*) begin + shcnt_mod3 = shcnt3 != 0; + shcnt_mod4 = shcnt4 != 0; + shcnt_mod5 = shcnt5 != 0; + pcm2_mul = pcm2 * lin2s; +end + +assign pcm_att = pcm1; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + pcm1 <= 'd0; pcm2 <= 'd0; + pcm3 <= 'd0; pcm4 <= 'd0; + pcm5 <= 'd0; pcm6 <= 'd0; + shcnt1 <= 'd0; shcnt2 <= 'd0; + shcnt3 <= 'd0; shcnt4 <= 'd0; + shcnt5 <= 'd0; shcnt6 <= 'd0; + end else if(cen) begin + // I + pcm2 <= match ? pcm_in : pcm1; + lin2 <= lin1; + shcnt2 <= match ? sh1 : shcnt1; + match2 <= match; + // II + pcm3 <= match2 ? pcm2_mul[24:9] : pcm2; + shcnt3 <= shcnt2; + // III, shift by 0 or 1 + if( shcnt_mod3 ) begin + pcm4 <= pcm3>>>1; + shcnt4 <= shcnt3-1'd1; + end else begin + pcm4 <= pcm3; + shcnt4 <= shcnt3; + end + // IV, shift by 0 or 1 + if( shcnt_mod4 ) begin + pcm5 <= pcm4>>>1; + shcnt5 <= shcnt4-1'd1; + end else begin + pcm5 <= pcm4; + shcnt5 <= shcnt4; + end + // V, shift by 0 or 1 + if( shcnt_mod5 ) begin + pcm6 <= pcm5>>>1; + shcnt6 <= shcnt5-1'd1; + end else begin + pcm6 <= pcm5; + shcnt6 <= shcnt5; + end + // VI close the loop and output + pcm1 <= pcm6; + shcnt1 <= shcnt6; + end + +endmodule // jt10_adpcm_gain diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcma_lut.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcma_lut.v new file mode 100644 index 0000000000000000000000000000000000000000..49501264c08b8929af37ade8132e1810f5d310be --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcma_lut.v @@ -0,0 +1,144 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +//altera message_off 10030 + +// ADPCM-A uses a LUT because it is very sensitive to rounding +// it looks like the original algorithm also used a table + +module jt10_adpcma_lut( + input clk, // CPU clock + input rst_n, + input cen, + input [8:0] addr, // = {step,delta}; + output reg [11:0] inc +); + +reg [11:0] lut[0:391]; + +initial begin +lut[9'o00_0] = 12'o0002; lut[9'o00_1] = 12'o0006; lut[9'o00_2] = 12'o0012; lut[9'o00_3] = 12'o0016; +lut[9'o00_4] = 12'o0022; lut[9'o00_5] = 12'o0026; lut[9'o00_6] = 12'o0032; lut[9'o00_7] = 12'o0036; +lut[9'o01_0] = 12'o0002; lut[9'o01_1] = 12'o0006; lut[9'o01_2] = 12'o0012; lut[9'o01_3] = 12'o0016; +lut[9'o01_4] = 12'o0023; lut[9'o01_5] = 12'o0027; lut[9'o01_6] = 12'o0033; lut[9'o01_7] = 12'o0037; +lut[9'o02_0] = 12'o0002; lut[9'o02_1] = 12'o0007; lut[9'o02_2] = 12'o0013; lut[9'o02_3] = 12'o0020; +lut[9'o02_4] = 12'o0025; lut[9'o02_5] = 12'o0032; lut[9'o02_6] = 12'o0036; lut[9'o02_7] = 12'o0043; +lut[9'o03_0] = 12'o0002; lut[9'o03_1] = 12'o0007; lut[9'o03_2] = 12'o0015; lut[9'o03_3] = 12'o0022; +lut[9'o03_4] = 12'o0027; lut[9'o03_5] = 12'o0034; lut[9'o03_6] = 12'o0042; lut[9'o03_7] = 12'o0047; +lut[9'o04_0] = 12'o0002; lut[9'o04_1] = 12'o0010; lut[9'o04_2] = 12'o0016; lut[9'o04_3] = 12'o0024; +lut[9'o04_4] = 12'o0031; lut[9'o04_5] = 12'o0037; lut[9'o04_6] = 12'o0045; lut[9'o04_7] = 12'o0053; +lut[9'o05_0] = 12'o0003; lut[9'o05_1] = 12'o0011; lut[9'o05_2] = 12'o0017; lut[9'o05_3] = 12'o0025; +lut[9'o05_4] = 12'o0034; lut[9'o05_5] = 12'o0042; lut[9'o05_6] = 12'o0050; lut[9'o05_7] = 12'o0056; +lut[9'o06_0] = 12'o0003; lut[9'o06_1] = 12'o0012; lut[9'o06_2] = 12'o0021; lut[9'o06_3] = 12'o0030; +lut[9'o06_4] = 12'o0037; lut[9'o06_5] = 12'o0046; lut[9'o06_6] = 12'o0055; lut[9'o06_7] = 12'o0064; +lut[9'o07_0] = 12'o0003; lut[9'o07_1] = 12'o0013; lut[9'o07_2] = 12'o0023; lut[9'o07_3] = 12'o0033; +lut[9'o07_4] = 12'o0042; lut[9'o07_5] = 12'o0052; lut[9'o07_6] = 12'o0062; lut[9'o07_7] = 12'o0072; +lut[9'o10_0] = 12'o0004; lut[9'o10_1] = 12'o0014; lut[9'o10_2] = 12'o0025; lut[9'o10_3] = 12'o0035; +lut[9'o10_4] = 12'o0046; lut[9'o10_5] = 12'o0056; lut[9'o10_6] = 12'o0067; lut[9'o10_7] = 12'o0077; +lut[9'o11_0] = 12'o0004; lut[9'o11_1] = 12'o0015; lut[9'o11_2] = 12'o0027; lut[9'o11_3] = 12'o0040; +lut[9'o11_4] = 12'o0051; lut[9'o11_5] = 12'o0062; lut[9'o11_6] = 12'o0074; lut[9'o11_7] = 12'o0105; +lut[9'o12_0] = 12'o0005; lut[9'o12_1] = 12'o0017; lut[9'o12_2] = 12'o0031; lut[9'o12_3] = 12'o0043; +lut[9'o12_4] = 12'o0056; lut[9'o12_5] = 12'o0070; lut[9'o12_6] = 12'o0102; lut[9'o12_7] = 12'o0114; +lut[9'o13_0] = 12'o0005; lut[9'o13_1] = 12'o0020; lut[9'o13_2] = 12'o0034; lut[9'o13_3] = 12'o0047; +lut[9'o13_4] = 12'o0062; lut[9'o13_5] = 12'o0075; lut[9'o13_6] = 12'o0111; lut[9'o13_7] = 12'o0124; +lut[9'o14_0] = 12'o0006; lut[9'o14_1] = 12'o0022; lut[9'o14_2] = 12'o0037; lut[9'o14_3] = 12'o0053; +lut[9'o14_4] = 12'o0070; lut[9'o14_5] = 12'o0104; lut[9'o14_6] = 12'o0121; lut[9'o14_7] = 12'o0135; +lut[9'o15_0] = 12'o0006; lut[9'o15_1] = 12'o0024; lut[9'o15_2] = 12'o0042; lut[9'o15_3] = 12'o0060; +lut[9'o15_4] = 12'o0075; lut[9'o15_5] = 12'o0113; lut[9'o15_6] = 12'o0131; lut[9'o15_7] = 12'o0147; +lut[9'o16_0] = 12'o0007; lut[9'o16_1] = 12'o0026; lut[9'o16_2] = 12'o0045; lut[9'o16_3] = 12'o0064; +lut[9'o16_4] = 12'o0103; lut[9'o16_5] = 12'o0122; lut[9'o16_6] = 12'o0141; lut[9'o16_7] = 12'o0160; +lut[9'o17_0] = 12'o0010; lut[9'o17_1] = 12'o0030; lut[9'o17_2] = 12'o0051; lut[9'o17_3] = 12'o0071; +lut[9'o17_4] = 12'o0112; lut[9'o17_5] = 12'o0132; lut[9'o17_6] = 12'o0153; lut[9'o17_7] = 12'o0173; +lut[9'o20_0] = 12'o0011; lut[9'o20_1] = 12'o0033; lut[9'o20_2] = 12'o0055; lut[9'o20_3] = 12'o0077; +lut[9'o20_4] = 12'o0122; lut[9'o20_5] = 12'o0144; lut[9'o20_6] = 12'o0166; lut[9'o20_7] = 12'o0210; +lut[9'o21_0] = 12'o0012; lut[9'o21_1] = 12'o0036; lut[9'o21_2] = 12'o0062; lut[9'o21_3] = 12'o0106; +lut[9'o21_4] = 12'o0132; lut[9'o21_5] = 12'o0156; lut[9'o21_6] = 12'o0202; lut[9'o21_7] = 12'o0226; +lut[9'o22_0] = 12'o0013; lut[9'o22_1] = 12'o0041; lut[9'o22_2] = 12'o0067; lut[9'o22_3] = 12'o0115; +lut[9'o22_4] = 12'o0143; lut[9'o22_5] = 12'o0171; lut[9'o22_6] = 12'o0217; lut[9'o22_7] = 12'o0245; +lut[9'o23_0] = 12'o0014; lut[9'o23_1] = 12'o0044; lut[9'o23_2] = 12'o0074; lut[9'o23_3] = 12'o0124; +lut[9'o23_4] = 12'o0155; lut[9'o23_5] = 12'o0205; lut[9'o23_6] = 12'o0235; lut[9'o23_7] = 12'o0265; +lut[9'o24_0] = 12'o0015; lut[9'o24_1] = 12'o0050; lut[9'o24_2] = 12'o0102; lut[9'o24_3] = 12'o0135; +lut[9'o24_4] = 12'o0170; lut[9'o24_5] = 12'o0223; lut[9'o24_6] = 12'o0255; lut[9'o24_7] = 12'o0310; +lut[9'o25_0] = 12'o0016; lut[9'o25_1] = 12'o0054; lut[9'o25_2] = 12'o0111; lut[9'o25_3] = 12'o0147; +lut[9'o25_4] = 12'o0204; lut[9'o25_5] = 12'o0242; lut[9'o25_6] = 12'o0277; lut[9'o25_7] = 12'o0335; +lut[9'o26_0] = 12'o0020; lut[9'o26_1] = 12'o0060; lut[9'o26_2] = 12'o0121; lut[9'o26_3] = 12'o0161; +lut[9'o26_4] = 12'o0222; lut[9'o26_5] = 12'o0262; lut[9'o26_6] = 12'o0323; lut[9'o26_7] = 12'o0363; +lut[9'o27_0] = 12'o0021; lut[9'o27_1] = 12'o0065; lut[9'o27_2] = 12'o0131; lut[9'o27_3] = 12'o0175; +lut[9'o27_4] = 12'o0240; lut[9'o27_5] = 12'o0304; lut[9'o27_6] = 12'o0350; lut[9'o27_7] = 12'o0414; +lut[9'o30_0] = 12'o0023; lut[9'o30_1] = 12'o0072; lut[9'o30_2] = 12'o0142; lut[9'o30_3] = 12'o0211; +lut[9'o30_4] = 12'o0260; lut[9'o30_5] = 12'o0327; lut[9'o30_6] = 12'o0377; lut[9'o30_7] = 12'o0446; +lut[9'o31_0] = 12'o0025; lut[9'o31_1] = 12'o0100; lut[9'o31_2] = 12'o0154; lut[9'o31_3] = 12'o0227; +lut[9'o31_4] = 12'o0302; lut[9'o31_5] = 12'o0355; lut[9'o31_6] = 12'o0431; lut[9'o31_7] = 12'o0504; +lut[9'o32_0] = 12'o0027; lut[9'o32_1] = 12'o0107; lut[9'o32_2] = 12'o0166; lut[9'o32_3] = 12'o0246; +lut[9'o32_4] = 12'o0325; lut[9'o32_5] = 12'o0405; lut[9'o32_6] = 12'o0464; lut[9'o32_7] = 12'o0544; +lut[9'o33_0] = 12'o0032; lut[9'o33_1] = 12'o0116; lut[9'o33_2] = 12'o0202; lut[9'o33_3] = 12'o0266; +lut[9'o33_4] = 12'o0353; lut[9'o33_5] = 12'o0437; lut[9'o33_6] = 12'o0523; lut[9'o33_7] = 12'o0607; +lut[9'o34_0] = 12'o0034; lut[9'o34_1] = 12'o0126; lut[9'o34_2] = 12'o0217; lut[9'o34_3] = 12'o0311; +lut[9'o34_4] = 12'o0402; lut[9'o34_5] = 12'o0474; lut[9'o34_6] = 12'o0565; lut[9'o34_7] = 12'o0657; +lut[9'o35_0] = 12'o0037; lut[9'o35_1] = 12'o0136; lut[9'o35_2] = 12'o0236; lut[9'o35_3] = 12'o0335; +lut[9'o35_4] = 12'o0434; lut[9'o35_5] = 12'o0533; lut[9'o35_6] = 12'o0633; lut[9'o35_7] = 12'o0732; +lut[9'o36_0] = 12'o0042; lut[9'o36_1] = 12'o0150; lut[9'o36_2] = 12'o0256; lut[9'o36_3] = 12'o0364; +lut[9'o36_4] = 12'o0471; lut[9'o36_5] = 12'o0577; lut[9'o36_6] = 12'o0705; lut[9'o36_7] = 12'o1013; +lut[9'o37_0] = 12'o0046; lut[9'o37_1] = 12'o0163; lut[9'o37_2] = 12'o0277; lut[9'o37_3] = 12'o0414; +lut[9'o37_4] = 12'o0531; lut[9'o37_5] = 12'o0646; lut[9'o37_6] = 12'o0762; lut[9'o37_7] = 12'o1077; +lut[9'o40_0] = 12'o0052; lut[9'o40_1] = 12'o0176; lut[9'o40_2] = 12'o0322; lut[9'o40_3] = 12'o0446; +lut[9'o40_4] = 12'o0573; lut[9'o40_5] = 12'o0717; lut[9'o40_6] = 12'o1043; lut[9'o40_7] = 12'o1167; +lut[9'o41_0] = 12'o0056; lut[9'o41_1] = 12'o0213; lut[9'o41_2] = 12'o0347; lut[9'o41_3] = 12'o0504; +lut[9'o41_4] = 12'o0641; lut[9'o41_5] = 12'o0776; lut[9'o41_6] = 12'o1132; lut[9'o41_7] = 12'o1267; +lut[9'o42_0] = 12'o0063; lut[9'o42_1] = 12'o0231; lut[9'o42_2] = 12'o0377; lut[9'o42_3] = 12'o0545; +lut[9'o42_4] = 12'o0713; lut[9'o42_5] = 12'o1061; lut[9'o42_6] = 12'o1227; lut[9'o42_7] = 12'o1375; +lut[9'o43_0] = 12'o0070; lut[9'o43_1] = 12'o0250; lut[9'o43_2] = 12'o0430; lut[9'o43_3] = 12'o0610; +lut[9'o43_4] = 12'o0771; lut[9'o43_5] = 12'o1151; lut[9'o43_6] = 12'o1331; lut[9'o43_7] = 12'o1511; +lut[9'o44_0] = 12'o0075; lut[9'o44_1] = 12'o0271; lut[9'o44_2] = 12'o0464; lut[9'o44_3] = 12'o0660; +lut[9'o44_4] = 12'o1053; lut[9'o44_5] = 12'o1247; lut[9'o44_6] = 12'o1442; lut[9'o44_7] = 12'o1636; +lut[9'o45_0] = 12'o0104; lut[9'o45_1] = 12'o0314; lut[9'o45_2] = 12'o0524; lut[9'o45_3] = 12'o0734; +lut[9'o45_4] = 12'o1144; lut[9'o45_5] = 12'o1354; lut[9'o45_6] = 12'o1564; lut[9'o45_7] = 12'o1774; +lut[9'o46_0] = 12'o0112; lut[9'o46_1] = 12'o0340; lut[9'o46_2] = 12'o0565; lut[9'o46_3] = 12'o1013; +lut[9'o46_4] = 12'o1240; lut[9'o46_5] = 12'o1466; lut[9'o46_6] = 12'o1713; lut[9'o46_7] = 12'o2141; +lut[9'o47_0] = 12'o0122; lut[9'o47_1] = 12'o0366; lut[9'o47_2] = 12'o0633; lut[9'o47_3] = 12'o1077; +lut[9'o47_4] = 12'o1344; lut[9'o47_5] = 12'o1610; lut[9'o47_6] = 12'o2055; lut[9'o47_7] = 12'o2321; +lut[9'o50_0] = 12'o0132; lut[9'o50_1] = 12'o0417; lut[9'o50_2] = 12'o0704; lut[9'o50_3] = 12'o1171; +lut[9'o50_4] = 12'o1456; lut[9'o50_5] = 12'o1743; lut[9'o50_6] = 12'o2230; lut[9'o50_7] = 12'o2515; +lut[9'o51_0] = 12'o0143; lut[9'o51_1] = 12'o0452; lut[9'o51_2] = 12'o0761; lut[9'o51_3] = 12'o1270; +lut[9'o51_4] = 12'o1577; lut[9'o51_5] = 12'o2106; lut[9'o51_6] = 12'o2415; lut[9'o51_7] = 12'o2724; +lut[9'o52_0] = 12'o0155; lut[9'o52_1] = 12'o0510; lut[9'o52_2] = 12'o1043; lut[9'o52_3] = 12'o1376; +lut[9'o52_4] = 12'o1731; lut[9'o52_5] = 12'o2264; lut[9'o52_6] = 12'o2617; lut[9'o52_7] = 12'o3152; +lut[9'o53_0] = 12'o0170; lut[9'o53_1] = 12'o0551; lut[9'o53_2] = 12'o1131; lut[9'o53_3] = 12'o1512; +lut[9'o53_4] = 12'o2073; lut[9'o53_5] = 12'o2454; lut[9'o53_6] = 12'o3034; lut[9'o53_7] = 12'o3415; +lut[9'o54_0] = 12'o0204; lut[9'o54_1] = 12'o0615; lut[9'o54_2] = 12'o1226; lut[9'o54_3] = 12'o1637; +lut[9'o54_4] = 12'o2250; lut[9'o54_5] = 12'o2661; lut[9'o54_6] = 12'o3272; lut[9'o54_7] = 12'o3703; +lut[9'o55_0] = 12'o0221; lut[9'o55_1] = 12'o0665; lut[9'o55_2] = 12'o1330; lut[9'o55_3] = 12'o1774;// Not sure if these should clip at 11 bits or not +lut[9'o55_4] = 12'o2437; lut[9'o55_5] = 12'o3103; lut[9'o55_6] = 12'o3546; lut[9'o55_7] = 12'o4212;//12'o3777; +lut[9'o56_0] = 12'o0240; lut[9'o56_1] = 12'o0740; lut[9'o56_2] = 12'o1441; lut[9'o56_3] = 12'o2141; +lut[9'o56_4] = 12'o2642; lut[9'o56_5] = 12'o3342; lut[9'o56_6] = 12'o4043; lut[9'o56_7] = 12'o4543;//12'o3777; lut[9'o56_7] = 12'o3777; +lut[9'o57_0] = 12'o0260; lut[9'o57_1] = 12'o1021; lut[9'o57_2] = 12'o1561; lut[9'o57_3] = 12'o2322; +lut[9'o57_4] = 12'o3063; lut[9'o57_5] = 12'o3624; lut[9'o57_6] = 12'o4364; lut[9'o57_7] = 12'o5125;//12'o3777; lut[9'o57_7] = 12'o3777; +lut[9'o60_0] = 12'o0302; lut[9'o60_1] = 12'o1106; lut[9'o60_2] = 12'o1712; lut[9'o60_3] = 12'o2516; +lut[9'o60_4] = 12'o3322; lut[9'o60_5] = 12'o4126; lut[9'o60_6] = 12'o4732; lut[9'o60_7] = 12'o5536;//12'o3777; lut[9'o60_6] = 12'o3777; lut[9'o60_7] = 12'o3777; +end + +always @(posedge clk or negedge rst_n) + if(!rst_n) + inc <= 'd0; + else if(cen) + inc <= lut[addr]; + +endmodule // jt10_adpcma_lut \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb.v new file mode 100644 index 0000000000000000000000000000000000000000..8a01f3dcc436edb53751efb223becd4eab5a1a64 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb.v @@ -0,0 +1,131 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Sampling rates: 2kHz ~ 55.5 kHz. in 0.85Hz steps + +module jt10_adpcmb( + input rst_n, + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [3:0] data, + input chon, // high if this channel is on + input adv, + input clr, + output signed [15:0] pcm +); + +localparam stepw = 15, xw=16; + +reg signed [xw-1:0] x1, next_x5; +reg [stepw-1:0] step1; +reg [stepw+1:0] next_step3; +assign pcm = x1[xw-1:xw-16]; + +wire [xw-1:0] limpos = {1'b0, {xw-1{1'b1}}}; +wire [xw-1:0] limneg = {1'b1, {xw-1{1'b0}}}; + +reg [18:0] d2l; +reg [xw-1:0] d3,d4; +reg [3:0] d2; +reg [7:0] step_val; +reg [22:0] step2l; + +always @(*) begin + casez( d2[3:1] ) + 3'b0_??: step_val = 8'd57; + 3'b1_00: step_val = 8'd77; + 3'b1_01: step_val = 8'd102; + 3'b1_10: step_val = 8'd128; + 3'b1_11: step_val = 8'd153; + endcase + d2l = d2 * step1; // 4 + 15 = 19 bits -> div by 8 -> 16 bits + step2l = step_val * step1; // 15 bits + 8 bits = 23 bits -> div 64 -> 17 bits +end + +// Original pipeline: 6 stages, 6 channels take 36 clock cycles +// 8 MHz -> /12 divider -> 666 kHz +// 666 kHz -> 18.5 kHz = 55.5/3 kHz + +reg [3:0] data2; +reg sign_data2, sign_data3, sign_data4, sign_data5; + +reg [3:0] adv2; +reg need_clr; + +wire [3:0] data_use = clr || ~chon ? 4'd0 : data; + +always @( posedge clk or negedge rst_n ) + if( ! rst_n ) begin + x1 <= 'd0; step1 <= 'd127; + d2 <= 'd0; d3 <= 'd0; d4 <= 'd0; + need_clr <= 0; + end else begin + if( clr ) + need_clr <= 1'd1; + if(cen) begin + adv2 <= {1'b0,adv2[3:1]}; + // I + if( adv ) begin + d2 <= {data_use[2:0],1'b1}; + sign_data2 <= data_use[3]; + adv2[3] <= 1'b1; + end + // II multiply and obtain the offset + d3 <= { {xw-16{1'b0}}, d2l[18:3] }; // xw bits + next_step3<= step2l[22:6]; + sign_data3<=sign_data2; + // III 2's complement of d3 if necessary + d4 <= sign_data3 ? ~d3+1'd1 : d3; + sign_data4<=sign_data3; + // IV Advance the waveform + next_x5 <= x1+d4; + sign_data5<=sign_data4; + // V: limit or reset outputs + if( chon ) begin // update values if needed + if( adv2[0] ) begin + if( sign_data5 == x1[xw-1] && (x1[xw-1]!=next_x5[xw-1]) ) + x1 <= x1[xw-1] ? limneg : limpos; + else + x1 <= next_x5; + + if( next_step3 < 127 ) + step1 <= 15'd127; + else if( next_step3 > 24576 ) + step1 <= 15'd24576; + else + step1 <= next_step3[14:0]; + end + end else begin + x1 <= 'd0; + step1 <= 'd127; + end + if( need_clr ) begin + x1 <= 'd0; + step1 <= 'd127; + next_step3 <= 'd127; + d2 <= 'd0; d3 <= 'd0; d4 <= 'd0; + next_x5 <= 'd0; + need_clr <= 1'd0; + end + end + end + +endmodule // jt10_adpcm \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_cnt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_cnt.v new file mode 100644 index 0000000000000000000000000000000000000000..a10b95eda9bb0d2a32abaa5f94a42968e5fe8ded --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_cnt.v @@ -0,0 +1,125 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// ADPCM-B counter + +module jt10_adpcmb_cnt( + input rst_n, + input clk, // CPU clock + input cen, // clk & cen = 55 kHz + + // counter control + input [15:0] delta_n, + input clr, + input on, + input acmd_up_b, + // Address + input [15:0] astart, + input [15:0] aend, + input arepeat, + output reg [23:0] addr, + output reg nibble_sel, + // Flag + output reg chon, + output reg flag, + input clr_flag, + output reg clr_dec, + + output reg adv +); + +// Counter +reg [15:0] cnt; + +always @(posedge clk or negedge rst_n) + if(!rst_n) begin + cnt <= 'd0; + adv <= 'b0; + end else if(cen) begin + if( clr) begin + cnt <= 'd0; + adv <= 'b0; + end else begin + if( on ) + {adv, cnt} <= {1'b0, cnt} + {1'b0, delta_n }; + else begin + cnt <= 'd0; + adv <= 1'b1; // let the rest of the signal chain advance + // when channel is off so all registers go to reset values + end + end + end + +reg set_flag, last_set; +reg restart; + +always @(posedge clk or negedge rst_n) + if(!rst_n) begin + flag <= 1'b0; + last_set <= 'b0; + end else begin + last_set <= set_flag; + if( clr_flag ) begin + flag <= 1'b0; + end else if( !last_set && set_flag ) begin + flag <= 1'b1; + end + end + +// Address +always @(posedge clk or negedge rst_n) + if(!rst_n) begin + addr <= 'd0; + nibble_sel <= 'b0; + set_flag <= 'd0; + chon <= 'b0; + restart <= 'b0; + clr_dec <= 'b1; + end else if( !on || clr ) begin + restart <= 'd0; + chon <= 'd0; + clr_dec <= 'd1; + end else if( acmd_up_b && on ) begin + restart <= 'd1; + end else if( cen ) begin + if( restart && adv ) begin + addr <= {astart,8'd0}; + nibble_sel <= 'b0; + restart <= 'd0; + chon <= 'd1; + clr_dec <= 'd0; + end else if( chon && adv ) begin + if( { addr, nibble_sel } != { aend, 8'hFF, 1'b1 } ) begin + { addr, nibble_sel } <= { addr, nibble_sel } + 25'd1; + set_flag <= 'd0; + end else if(arepeat) begin + restart <= 'd1; + clr_dec <= 'd1; + end else begin + set_flag <= 'd1; + chon <= 'd0; + clr_dec <= 'd1; + end + end + end // cen + + +endmodule // jt10_adpcmb_cnt diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_gain.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_gain.v new file mode 100644 index 0000000000000000000000000000000000000000..e501c7d89816791a2fe5c06885956f24d16184f0 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_gain.v @@ -0,0 +1,39 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Gain is assumed to be 0.75dB per bit. + +module jt10_adpcmb_gain( + input rst_n, + input clk, // CPU clock + input cen55, + input [ 7:0] tl, // ADPCM Total Level + input signed [15:0] pcm_in, + output reg signed [15:0] pcm_out +); + +wire signed [15:0] factor = {8'd0, tl}; +wire signed [31:0] pcm_mul = pcm_in * factor; // linear gain + +always @(posedge clk) if(cen55) + pcm_out <= pcm_mul[23:8]; + +endmodule // jt10_adpcm_gain diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_interpol.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_interpol.v new file mode 100644 index 0000000000000000000000000000000000000000..4a9a04afdb58e207d2930de392c848d0cfe8b258 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_adpcmb_interpol.v @@ -0,0 +1,96 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt10_adpcmb_interpol( + input rst_n, + input clk, + input cen, // 8MHz cen + input cen55, // clk & cen55 = 55 kHz + input adv, + input signed [15:0] pcmdec, + output signed [15:0] pcmout +); + +localparam stages=6; + +reg signed [15:0] pcmlast, delta_x; +reg signed [16:0] pre_dx; +reg start_div=1'b0; +reg [3:0] deltan, pre_dn; +reg [stages-1:0] adv2; +reg signed [15:0] pcminter; +wire [15:0] next_step; +reg [15:0] step; +reg step_sign, next_step_sign; + +assign pcmout = pcminter; + +always @(posedge clk) if(cen) begin + adv2 <= {adv2[stages-2:0], cen55 & adv }; // give some time to get the data from memory +end + +always @(posedge clk) if(cen55) begin + if ( adv ) begin + pre_dn <= 'd1; + deltan <= pre_dn; + end else if ( pre_dn != 4'hF ) + pre_dn <= pre_dn + 1'd1; +end + + +always @(posedge clk) if(cen) begin + start_div <= 1'b0; + if(adv2[1]) begin + pcmlast <= pcmdec; + end + if(adv2[4]) begin + pre_dx <= { pcmdec[15], pcmdec } - { pcmlast[15], pcmlast }; + end + if( adv2[5] ) begin + start_div <= 1'b1; + delta_x <= pre_dx[16] ? ~pre_dx[15:0]+1'd1 : pre_dx[15:0]; + next_step_sign <= pre_dx[16]; + end +end + +always @(posedge clk) if(cen55) begin + if( adv ) begin + step <= next_step; + step_sign <= next_step_sign; + pcminter <= pcmlast; + end + else pcminter <= ( (pcminter < pcmlast) == step_sign ) ? pcminter : step_sign ? pcminter - step : pcminter + step; +end + +jt10_adpcm_div #(.DW(16)) u_div( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen ), + .start ( start_div ), + .a ( delta_x ), + .b ( {12'd0, deltan } ), + .d ( next_step ), + .r ( ), + .working( ) +); + + +endmodule // jt10_adpcmb_interpol \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_cen_burst.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_cen_burst.v new file mode 100644 index 0000000000000000000000000000000000000000..393665ba6ac6d98942d7c5307ac58aec55f7f0e5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/adpcm/jt10_cen_burst.v @@ -0,0 +1,59 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// Let a fixed number of clock enable pulses to pass through + +module jt10_cen_burst #(parameter cntmax=3'd6, cntw=3)( + input rst_n, + input clk, + input cen, // 8MHz cen + input start, + input start_cen, + output cen_out +); + +reg [cntw-1:0] cnt; +reg last_start; +reg pass; + +always @(posedge clk or negedge rst_n) + if( !rst_n ) begin + cnt <= {cntw{1'b1}}; + pass <= 1'b0; + end else if(cen) begin + last_start <= start; + if( start && start_cen ) begin + cnt <= 'd0; + pass <= 1'b1; + end else begin + if(cnt != cntmax ) cnt <= cnt+1; + else pass <= 1'b0; + end + end + +reg pass_negedge; +assign cen_out = cen & pass_negedge; + +always @(negedge clk) begin + pass_negedge <= pass; +end + +endmodule // jt10_cen_burst \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_cnt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_cnt.v new file mode 100644 index 0000000000000000000000000000000000000000..8e838b8c48995ff0552f264639434bf0b9af60b6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_cnt.v @@ -0,0 +1,84 @@ +/* +Using two large case statements: ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_cnt/ | | 9/13 | 13/19 | 15/18 | 0/3 | 0/0 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | eg_cnt | +| +u_cntsh | | 4/4 | 6/6 | 3/3 | 3/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_cnt/u_cntsh | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +Using one large case statement: ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_cnt/ | | 8/11 | 13/19 | 12/15 | 0/3 | 0/0 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | eg_cnt | +| +u_cntsh | | 3/3 | 6/6 | 3/3 | 3/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_cnt/u_cntsh | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +*/ + +module eg_cnt( + input clk, + input clk_en, + input rst, + input [14:0] eg_cnt, + input [2:0] state_IV, + input [5:0] rate_IV, + + output reg [2:0] state_V, + output reg [5:0] rate_V, + output [2:0] cnt_V, + output reg sum_up +); + +localparam ATTACK=3'd0, DECAY1=3'd1, DECAY2=3'd2, RELEASE=3'd7, HOLD=3'd3; +wire [2:0] cnt_out; +assign cnt_V = cnt_out; +reg lsb; +reg [2:0] cnt_in; +reg [3:0] mux_sel; + +always @(*) begin + mux_sel = (state_IV == ATTACK && rate_IV[5:2]!=4'hf) ? (rate_IV[5:2]+4'd1): rate_IV[5:2]; + case( mux_sel ) + 4'h0: lsb = eg_cnt[12]; + 4'h1: lsb = eg_cnt[11]; + 4'h2: lsb = eg_cnt[10]; + 4'h3: lsb = eg_cnt[ 9]; + 4'h4: lsb = eg_cnt[ 8]; + 4'h5: lsb = eg_cnt[ 7]; + 4'h6: lsb = eg_cnt[ 6]; + 4'h7: lsb = eg_cnt[ 5]; + 4'h8: lsb = eg_cnt[ 4]; + 4'h9: lsb = eg_cnt[ 3]; + 4'ha: lsb = eg_cnt[ 2]; + 4'hb: lsb = eg_cnt[ 1]; + default: lsb = eg_cnt[ 0]; + endcase + cnt_in =lsb!=cnt_out ? (cnt_out+3'd1) : cnt_out; +end + +always @(posedge clk) if( clk_en ) begin + if( rst ) begin + state_V <= RELEASE; + rate_V <= 6'h1F; // should it be 6'h3F? TODO + //cnt_V<= 3'd0; + end + else begin + state_V <= state_IV; + rate_V <= rate_IV; + end +end + +jt12_sh/*_rst*/ #( .width(3), .stages(24) ) u_cntsh( + .clk ( clk ), + .clk_en ( clk_en ), +// .rst ( rst ), + .din ( cnt_in ), + .drop ( cnt_out ) +); + +always @(posedge clk) + if( clk_en ) + sum_up <= lsb!=cnt_out; + +endmodule // eg_mux \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_comb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..7f127669ae1f616fd37bb6e79eaa42a4fa2b6975 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_comb.v @@ -0,0 +1,184 @@ +/* ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_comb/ | | 49/49 | 0/0 | 153/153 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_comb | +| eg_comb/ | | 42/42 | 0/0 | 134/134 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_comb | +| eg_comb/ | | 39/39 | 0/0 | 129/129 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_comb | +| eg_comb/ | | 43/43 | 0/0 | 122/122 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_comb | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +This module represents all the envelope generator calculations. +Everything is combinational. The testbench ver/eg2 checks the +functionality of this module. + +*/ + +module eg_comb( + input attack, + input [ 4:0] base_rate, + input [ 4:0] keycode, + input [14:0] eg_cnt, + input cnt_in, + input [ 1:0] ks, + input [ 9:0] eg_in, + input [ 6:0] lfo_mod, + input amsen, + input [ 1:0] ams, + input [ 6:0] tl, + output cnt_lsb, + output reg [9:0] eg_limited, + output reg [9:0] eg_pure +); + +reg [6:0] pre_rate; +reg [5:0] rate; + +always @(*) begin : pre_rate_calc + if( base_rate == 5'd0 ) + pre_rate = 7'd0; + else + case( ks ) + 2'd3: pre_rate = { base_rate, 1'b0 } + { 1'b0, keycode }; + 2'd2: pre_rate = { base_rate, 1'b0 } + { 2'b0, keycode[4:1] }; + 2'd1: pre_rate = { base_rate, 1'b0 } + { 3'b0, keycode[4:2] }; + 2'd0: pre_rate = { base_rate, 1'b0 } + { 4'b0, keycode[4:3] }; + endcase +end + +always @(*) + rate = pre_rate[6] ? 6'd63 : pre_rate[5:0]; + +reg [2:0] cnt; + +reg [4:0] mux_sel; +always @(*) begin + mux_sel = attack ? (rate[5:2]+4'd1): {1'b0,rate[5:2]}; +end // always @(*) + +always @(*) + case( mux_sel ) + 5'h0: cnt = eg_cnt[14:12]; + 5'h1: cnt = eg_cnt[13:11]; + 5'h2: cnt = eg_cnt[12:10]; + 5'h3: cnt = eg_cnt[11: 9]; + 5'h4: cnt = eg_cnt[10: 8]; + 5'h5: cnt = eg_cnt[ 9: 7]; + 5'h6: cnt = eg_cnt[ 8: 6]; + 5'h7: cnt = eg_cnt[ 7: 5]; + 5'h8: cnt = eg_cnt[ 6: 4]; + 5'h9: cnt = eg_cnt[ 5: 3]; + 5'ha: cnt = eg_cnt[ 4: 2]; + 5'hb: cnt = eg_cnt[ 3: 1]; + default: cnt = eg_cnt[ 2: 0]; + endcase + +//////////////////////////////// +reg step; +reg [7:0] step_idx; + +always @(*) begin : rate_step + if( rate[5:4]==2'b11 ) begin // 0 means 1x, 1 means 2x + if( rate[5:2]==4'hf && attack) + step_idx = 8'b11111111; // Maximum attack speed, rates 60&61 + else + case( rate[1:0] ) + 2'd0: step_idx = 8'b00000000; + 2'd1: step_idx = 8'b10001000; // 2 + 2'd2: step_idx = 8'b10101010; // 4 + 2'd3: step_idx = 8'b11101110; // 6 + endcase + end + else begin + if( rate[5:2]==4'd0 && !attack) + step_idx = 8'b11111110; // limit slowest decay rate + else + case( rate[1:0] ) + 2'd0: step_idx = 8'b10101010; // 4 + 2'd1: step_idx = 8'b11101010; // 5 + 2'd2: step_idx = 8'b11101110; // 6 + 2'd3: step_idx = 8'b11111110; // 7 + endcase + end + // a rate of zero keeps the level still + step = rate[5:1]==5'd0 ? 1'b0 : step_idx[ cnt ]; +end + +reg sum_up; +assign cnt_lsb = cnt[0]; +always @(*) begin + sum_up = cnt[0] != cnt_in; +end +////////////////////////////////////////////////////////////// +// cnt/cnt_lsb/cnt_in not used below this point + +reg [3:0] dr_sum; +reg [10:0] dr_result; + +always @(*) begin + case( rate[5:2] ) + 4'b1100: dr_sum = { 2'b0, step, ~step }; // 12 + 4'b1101: dr_sum = { 1'b0, step, ~step, 1'b0 }; // 13 + 4'b1110: dr_sum = { step, ~step, 2'b0 }; // 14 + 4'b1111: dr_sum = 4'd8;// 15 + default: dr_sum = { 2'b0, step, 1'b0 }; + endcase + dr_result = {6'd0, dr_sum} + eg_in; +end + +reg [ 7:0] ar_sum0; +reg [ 8:0] ar_sum1; +reg [10:0] ar_result; +reg [ 9:0] ar_sum; + +always @(*) begin : ar_calculation + casez( rate[5:2] ) + default: ar_sum0 = {2'd0, eg_in[9:4]}; + 4'b1101: ar_sum0 = {1'd0, eg_in[9:3]}; + 4'b111?: ar_sum0 = eg_in[9:2]; + endcase + ar_sum1 = ar_sum0+9'd1; + if( rate[5:4] == 2'b11 ) + ar_sum = step ? { ar_sum1, 1'b0 } : { 1'b0, ar_sum1 }; + else + ar_sum = step ? { 1'b0, ar_sum1 } : 10'd0; + ar_result = rate[5:1]==5'h1F ? 11'd0 : eg_in-ar_sum; +end +/////////////////////////////////////////////////////////// +// rate not used below this point +always @(*) begin + if(sum_up) begin + if( attack ) + eg_pure = ar_result[10] ? 10'd0: ar_result[9:0]; + else + eg_pure = dr_result[10] ? 10'h3FF : dr_result[9:0]; + end + else eg_pure = eg_in; +end + +////////////////////////////////////////////////////////////// +reg [ 8:0] am_final; +reg [10:0] sum_eg_tl; +reg [11:0] sum_eg_tl_am; +reg [ 5:0] am_inverted; + +always @(*) begin + am_inverted = lfo_mod[6] ? ~lfo_mod[5:0] : lfo_mod[5:0]; +end + +always @(*) begin + casez( {amsen, ams } ) + default: am_final = 9'd0; + 3'b1_01: am_final = { 5'd0, am_inverted[5:2] }; + 3'b1_10: am_final = { 3'd0, am_inverted }; + 3'b1_11: am_final = { 2'd0, am_inverted, 1'b0 }; + endcase + sum_eg_tl = { tl, 3'd0 } + eg_pure; + sum_eg_tl_am = sum_eg_tl + { 3'd0, am_final }; +end + +always @(*) + eg_limited = sum_eg_tl_am[11:10]==2'd0 ? sum_eg_tl_am[9:0] : 10'h3ff; + + +endmodule // eg_comb \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_mux.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_mux.v new file mode 100644 index 0000000000000000000000000000000000000000..6e59c21294bdbf8144e3d57568fc4ef80357db14 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_mux.v @@ -0,0 +1,79 @@ +/* +Using two large case statements: ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_mux/ | | 11/12 | 13/14 | 31/31 | 1/1 | 0/0 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | eg_mux | +| +u_cntsh | | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_mux/u_cntsh | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +Using one large case statement: ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_mux/ | | 11/12 | 13/14 | 21/21 | 1/1 | 0/0 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | eg_mux | +| +u_cntsh | | 1/1 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_mux/u_cntsh | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +*/ + +module eg_mux( + input clk, + input clk_en, + input rst, + input [14:0] eg_cnt, + input [2:0] state_IV, + input [5:0] rate_IV, + + output reg [2:0] state_V, + output reg [5:0] rate_V, + output reg [2:0] cnt_V, + output reg sum_up +); + +localparam ATTACK=3'd0, DECAY1=3'd1, DECAY2=3'd2, RELEASE=3'd7, HOLD=3'd3; +wire cnt_out; +reg [3:0] mux_sel; + +always @(*) begin + mux_sel = (state_IV == ATTACK && rate_IV[5:2]!=4'hf) ? (rate_IV[5:2]+4'd1): rate_IV[5:2]; +end // always @(*) + +always @(posedge clk) if( clk_en ) begin + if( rst ) begin + state_V <= RELEASE; + rate_V <= 6'h1F; // should it be 6'h3F? TODO + //cnt_V<= 3'd0; + end + else begin + state_V <= state_IV; + rate_V <= rate_IV; + case( mux_sel ) + 4'h0: cnt_V <= eg_cnt[14:12]; + 4'h1: cnt_V <= eg_cnt[13:11]; + 4'h2: cnt_V <= eg_cnt[12:10]; + 4'h3: cnt_V <= eg_cnt[11: 9]; + 4'h4: cnt_V <= eg_cnt[10: 8]; + 4'h5: cnt_V <= eg_cnt[ 9: 7]; + 4'h6: cnt_V <= eg_cnt[ 8: 6]; + 4'h7: cnt_V <= eg_cnt[ 7: 5]; + 4'h8: cnt_V <= eg_cnt[ 6: 4]; + 4'h9: cnt_V <= eg_cnt[ 5: 3]; + 4'ha: cnt_V <= eg_cnt[ 4: 2]; + 4'hb: cnt_V <= eg_cnt[ 3: 1]; + default: cnt_V <= eg_cnt[ 2: 0]; + endcase + end +end + +jt12_sh/*_rst*/ #( .width(1), .stages(24) ) u_cntsh( + .clk ( clk ), + .clk_en ( clk_en ), +// .rst ( rst ), + .din ( cnt_V[0] ), + .drop ( cnt_out ) +); + +always @(posedge clk) + if( clk_en ) + sum_up <= cnt_V[0] != cnt_out; + +endmodule // eg_mux \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step.v new file mode 100644 index 0000000000000000000000000000000000000000..a06614f693418aae11670ce23572a2ebf0481728 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step.v @@ -0,0 +1,46 @@ +/* ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_step/ | | 3/3 | 0/0 | 7/7 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_step | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +*/ + +module eg_step( + input [2:0] state_V, + input [5:0] rate_V, + input [2:0] cnt_V, + output reg step_V +); + +localparam ATTACK=3'd0, DECAY1=3'd1, DECAY2=3'd2, RELEASE=3'd7, HOLD=3'd3; +reg [7:0] step_idx; + +always @(*) begin : rate_step + if( rate_V[5:4]==2'b11 ) begin // 0 means 1x, 1 means 2x + if( rate_V[5:2]==4'hf && state_V == ATTACK) + step_idx = 8'b11111111; // Maximum attack speed, rates 60&61 + else + case( rate_V[1:0] ) + 2'd0: step_idx = 8'b00000000; + 2'd1: step_idx = 8'b10001000; // 2 + 2'd2: step_idx = 8'b10101010; // 4 + 2'd3: step_idx = 8'b11101110; // 6 + endcase + end + else begin + if( rate_V[5:2]==4'd0 && state_V != ATTACK) + step_idx = 8'b11111110; // limit slowest decay rate_IV + else + case( rate_V[1:0] ) + 2'd0: step_idx = 8'b10101010; // 4 + 2'd1: step_idx = 8'b11101010; // 5 + 2'd2: step_idx = 8'b11101110; // 6 + 2'd3: step_idx = 8'b11111110; // 7 + endcase + end + // a rate_IV of zero keeps the level still + step_V = rate_V[5:1]==5'd0 ? 1'b0 : step_idx[ cnt_V ]; +end + +endmodule // eg_step \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step_ram.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step_ram.v new file mode 100644 index 0000000000000000000000000000000000000000..ea701ebc1498e43b10b0ecce88bdea8dd52dfa40 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/alt/eg_step_ram.v @@ -0,0 +1,45 @@ +/* ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Module | Partition | Slices* | Slice Reg | LUTs | LUTRAM | BRAM/FIFO | DSP48A1 | BUFG | BUFIO | BUFR | DCM | PLL_ADV | Full Hierarchical | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| eg_step_ram/ | | 3/3 | 0/0 | 7/7 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | eg_step | ++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +*/ + +module eg_step_ram( + input [2:0] state_V, + input [5:0] rate_V, + input [2:0] cnt_V, + output reg step_V +); + +localparam ATTACK=3'd0, DECAY1=3'd1, DECAY2=3'd2, RELEASE=3'd7, HOLD=3'd3; +reg [7:0] step_idx; +reg [7:0] step_ram; + +always @(*) + case( { rate_V[5:4]==2'b11, rate_V[1:0]} ) + 3'd0: step_ram = 8'b00000000; + 3'd1: step_ram = 8'b10001000; // 2 + 3'd2: step_ram = 8'b10101010; // 4 + 3'd3: step_ram = 8'b11101110; // 6 + 3'd4: step_ram = 8'b10101010; // 4 + 3'd5: step_ram = 8'b11101010; // 5 + 3'd6: step_ram = 8'b11101110; // 6 + 3'd7: step_ram = 8'b11111110; // 7 + endcase + +always @(*) begin : rate_step + if( rate_V[5:2]==4'hf && state_V == ATTACK) + step_idx = 8'b11111111; // Maximum attack speed, rates 60&61 + else + if( rate_V[5:2]==4'd0 && state_V != ATTACK) + step_idx = 8'b11111110; // limit slowest decay rate_IV + else + step_idx = step_ram; + // a rate_IV of zero keeps the level still + step_V = rate_V[5:1]==5'd0 ? 1'b0 : step_idx[ cnt_V ]; +end + +endmodule // eg_step \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac.v new file mode 100644 index 0000000000000000000000000000000000000000..6fb6ed0e56ce1168cfc7b22c2880a756b600917d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac.v @@ -0,0 +1,56 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: March, 9th 2017 + */ + +`timescale 1ns / 1ps + +/* + + input sampling rate must be the same as clk frequency + interpolation the input signal accordingly to get the + right sampling rate + +*/ + +module jt12_dac #(parameter width=12) +( + input clk, + input rst, + input signed [width-1:0] din, + output dout +); +localparam acc_w = width+1; + +reg [width-1:0] nosign; +reg [acc_w-1:0] acc; +wire [acc_w-2:0] err = acc[acc_w-2:0]; + +assign dout = acc[acc_w-1]; + +always @(posedge clk) +if( rst ) begin + acc <= {(acc_w){1'b0}}; + nosign <= {width{1'b0}}; +end +else begin + nosign <= { ~din[width-1], din[width-2:0] }; + acc <= nosign + err; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac2.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac2.v new file mode 100644 index 0000000000000000000000000000000000000000..08f7af41aaf47cf589a7598b9dc07489816b34c7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/dac/jt12_dac2.v @@ -0,0 +1,63 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: March, 9th 2017 + */ + +`timescale 1ns / 1ps + +/* + + input sampling rate must be the same as clk frequency + interpolate input signal accordingly to get the + right sampling rate. + + Refer to sigmadelta.ods to see how the internal width (int_w) + was determined. + +*/ + +module jt12_dac2 #(parameter width=12) +( + input clk, + input rst, + input signed [width-1:0] din, + output reg dout +); + +localparam int_w = width+5; + +reg [int_w-1:0] y, error, error_1, error_2; + +wire [width-1:0] undin = { ~din[width-1], din[width-2:0] }; + +always @(*) begin + y = undin + { error_1, 1'b0} - error_2; + dout = ~y[int_w-1]; + error = y - {dout, {width{1'b0}}}; +end + +always @(posedge clk) + if( rst ) begin + error_1 <= {int_w{1'b0}}; + error_2 <= {int_w{1'b0}}; + end else begin + error_1 <= error; + error_2 <= error_1; + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_amp.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_amp.v new file mode 100644 index 0000000000000000000000000000000000000000..ddb9c401ef218fe94ce2569b1ccd98339ca92f0f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_amp.v @@ -0,0 +1,172 @@ +`timescale 1ns / 1ps + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 23-2-2017 + +*/ + + + +`timescale 1ns / 1ps + +module jt12_amp( + input clk, + input rst, + input sample, + input [2:0] volume, + + input signed [13:0] pre, + output reg signed [15:0] post +); + +wire signed [14:0] x2 = pre<<<1; +wire signed [15:0] x3 = x2+pre; +wire signed [15:0] x4 = pre<<<2; +//wire signed [16:0] x5 = x4+pre; +wire signed [16:0] x6 = x4+x2; +//wire signed [16:0] x7 = x4+x3; +wire signed [16:0] x8 = pre<<<3; +wire signed [17:0] x12 = x8+x4; +wire signed [17:0] x16 = pre<<<4; + +always @(posedge clk) +if( rst ) + post <= 16'd0; +else +if( sample ) + case( volume ) + 3'd0: // /2 + post <= { {2{pre[13]}}, pre }; + 3'd1: // x1 + post <= { x2[14], x2 }; + 3'd2: // x2 + post <= { x2, 1'd0 }; + /* + 3'd3: // x3 + case( x3[15:14] ) + 2'b00, 2'b11: post <= { x3[14:0], 1'd0 }; + 2'b01: post <= 16'h7FFF; + 2'b10: post <= 16'h8000; + endcase + */ + 3'd3: // x4 + post <= x4; + /* + 3'd5: // x5 + case( x5[16:15] ) + 2'b00, 2'b11: post <= x5[15:0]; + 2'b01: post <= 16'h7FFF; + 2'b10: post <= 16'h8000; + endcase + */ + 3'd4: // x6 + casex( x6[16:15] ) + 2'b00, 2'b11: post <= x6[15:0]; + 2'b0x: post <= 16'h7FFF; + 2'b1x: post <= 16'h8000; + endcase +/* + 3'd7: // x7 + case( x7[16:15] ) + 2'b00, 2'b11: post <= x7[15:0]; + 2'b01: post <= 16'h7FFF; + 2'b10: post <= 16'h8000; + endcase +*/ + 3'd5: // x8 + casex( x8[16:15] ) + 2'b00, 2'b11: post <= x8[15:0]; + 2'b0x: post <= 16'h7FFF; + 2'b1x: post <= 16'h8000; + endcase + 3'd6: // x12 + casex( x12[17:15] ) + 3'b000, 3'b111: post <= x12[15:0]; + 3'b0xx: post <= 16'h7FFF; + 3'b1xx: post <= 16'h8000; + endcase + 3'd7: // x16 + casex( x16[17:15] ) + 3'b000, 3'b111: post <= x16[15:0]; + 3'b0xx: post <= 16'h7FFF; + 3'b1xx: post <= 16'h8000; + endcase + endcase + +endmodule + +module jt12_amp_stereo( + input clk, + input rst, + input sample, + + input [ 5:0] psg, + input enable_psg, + + input signed [11:0] fmleft, + input signed [11:0] fmright, + input [2:0] volume, + + output signed [15:0] postleft, + output signed [15:0] postright +); + +wire signed [13:0] preleft; +wire signed [13:0] preright; + +// psg, 6'd0 suena muy fuerte +// According to Nemesis: +// All 4 PSG channels at max combined is equivalent to the maximum output of a single YM2612 channel at max. +// A single channel at max is 11'd255 + +//wire signed [5:0] psgm = psg-6'h20; +//wire signed [8:0] psg_dac = psgm<<<3; +//wire signed [12:0] psg_sum = {13{enable_psg}} & { {3{psg_dac[8]}}, psg_dac }; + +//wire signed [5:0] psgm = psg-6'h20; +wire signed [8:0] psg_dac = psg<<<3; + +//wire signed [12:0] psg_sum = {13{enable_psg}} & { 3'b0, psg_dac }; +wire signed [12:0] psg_sum = {13{enable_psg}} & { 2'b0, psg_dac, 1'b0 }; + + +assign preleft = { fmleft [11], fmleft, 1'd0 } + psg_sum; +assign preright= { fmright[11],fmright, 1'd0 } + psg_sum; + +jt12_amp amp_left( + .clk ( clk ), + .rst ( rst ), + .sample ( sample ), + .pre ( preleft ), + .post ( postleft ), + .volume ( volume ) +); + +jt12_amp amp_right( + .clk ( clk ), + .rst ( rst ), + .sample ( sample ), + .pre ( preright ), + .post ( postright ), + .volume ( volume ) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_clk.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_clk.v new file mode 100644 index 0000000000000000000000000000000000000000..393e8865adf4924dfa13eb2c53d0b22c5177aae9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_clk.v @@ -0,0 +1,93 @@ +`timescale 1ns / 1ps + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + +*/ + +module jt12_clk( + input rst, + input clk, + + input set_n6, + input set_n3, // not implemented because it relies on 50% duty cycle of clk + input set_n2, + + output reg clk_int, + output reg rst_int +); + +reg clk_n2, clk_n6; +wire clk_n3; + +reg [1:0] clksel; + +parameter USE6=2'd0, USE3=2'b10, USE2=2'b01; + +always @(negedge clk_n6 or posedge rst_int) + if( rst_int ) begin + clksel <= USE6; + end + else + clksel <= { set_n3, set_n2 }; + +always @(*) + case( clksel ) + USE3: clk_int <= clk_n3; + USE2: clk_int <= clk_n2; + default: clk_int <= clk_n6; + endcase + +// n=2 +// Generate internal clock and synchronous reset for it. +reg [1:0] rst_int_aux; + +always @(posedge clk or posedge rst) + clk_n2 <= rst ? 1'b0 : ~clk_n2; + +reg [1:0] cnt3; +reg [2:0] cnt6; +assign clk_n3 = cnt3[0]; + +always @(posedge clk or posedge rst) + if( rst ) begin + cnt3 <= 2'd0; + cnt6 <= 3'd0; + clk_n6 <= 1'b0; + end else begin + cnt3 <= cnt3==2'd2 ? 2'd0 : cnt3+2'd1; + cnt6 <= cnt6==3'd5 ? 3'd0 : cnt6+3'd1; + clk_n6 <= cnt6<=3'd2; + end + +wire [3:0] delay; + +always @(posedge clk_n6 or posedge rst) + if( rst ) begin + rst_int_aux <= 2'b11; + rst_int <= 1'b1; + end + else begin + { rst_int, rst_int_aux } <= { rst_int_aux, 1'b0 }; + end + + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod24.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod24.v new file mode 100644 index 0000000000000000000000000000000000000000..0d5568a1600517d355da7d319375d79f5fde83e4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod24.v @@ -0,0 +1,14 @@ +`timescale 1ns / 1ps + +module jt12_mod24( + input [4:0] base, + input [3:0] extra, + output [4:0] mod +); + +wire [5:0] sum = base+extra; +wire [4:0] wrap = base+extra-5'd24; + +assign mod = sum > 6'd23 ? wrap : sum[4:0]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod6.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod6.v new file mode 100644 index 0000000000000000000000000000000000000000..c64f25afdf2a3242009472ff2ad862b884cd449c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_mod6.v @@ -0,0 +1,52 @@ +`timescale 1ns / 1ps + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 19-3-2017 + +*/ + + +module jt12_mod6 +( + input [2:0] in, // only 0 to 5 are valid entries + input [2:0] sum, + output reg [2:0] out // output between 0 to 5 +); + +reg [3:0] aux; + +always @(*) begin + aux <= in+sum; + case( aux ) + 4'd6: out <= 3'd0; + 4'd7: out <= 3'd1; + 4'd8: out <= 3'd2; + 4'd9: out <= 3'd3; + 4'ha: out <= 3'd4; + 4'hb: out <= 3'd5; + 4'hc: out <= 3'd0; + 4'he: out <= 3'd1; + 4'hf: out <= 3'd2; + default: out <= aux; + endcase +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_opram.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_opram.v new file mode 100644 index 0000000000000000000000000000000000000000..d695a17a71cee2d4f9c945572e70cf891d80f166 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/deprecated/jt12_opram.v @@ -0,0 +1,45 @@ +`timescale 1ns / 1ps + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Based on Sauraen VHDL version of OPN/OPN2, which is based on die shots. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +module jt12_opram +( + input [4:0] wr_addr, + input [4:0] rd_addr, + input clk, + input clk_en, + input [43:0] data, + output reg [43:0] q +); + + reg [43:0] ram[31:0]; + + always @ (posedge clk) if(clk_en) begin + q <= ram[rd_addr]; + ram[wr_addr] <= data; + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.v new file mode 100644 index 0000000000000000000000000000000000000000..8092c9e5195fa11731fc34712b8385d65a189a44 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.v @@ -0,0 +1,110 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-12-2018 +*/ + +// Wrapper to output only combined channels. Defaults to YM2203 mode. + +module jt03( + input rst, // rst should be at least 6 clk&cen cycles long + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [7:0] din, + input addr, + input cs_n, + input wr_n, + + output [7:0] dout, + output irq_n, + // I/O pins used by YM2203 embedded YM2149 chip + input [7:0] IOA_in, + input [7:0] IOB_in, + output [7:0] IOA_out, + output [7:0] IOB_out, + output IOA_oe, + output IOB_oe, + // Separated output + output [ 7:0] psg_A, + output [ 7:0] psg_B, + output [ 7:0] psg_C, + output signed [15:0] fm_snd, + // combined output + output [ 9:0] psg_snd, + output signed [15:0] snd, + output snd_sample, + // Debug + //input [ 7:0] debug_bus, + output [ 7:0] debug_view +); + +parameter YM2203_LUMPED=0; // set to 1 if all PSG outputs are shorted together without any resistor + +jt12_top #( + .use_lfo(0),.use_ssg(1), .num_ch(3), .use_pcm(0), .use_adpcm(0), .mask_div(0), + .YM2203_LUMPED(YM2203_LUMPED) ) +u_jt12( + .rst ( rst ), // rst should be at least 6 clk&cen cycles long + .clk ( clk ), // CPU clock + .cen ( cen ), // optional clock enable, it not needed leave as 1'b1 + .din ( din ), + .addr ( {1'b0, addr} ), + .cs_n ( cs_n ), + .wr_n ( wr_n ), + .ch_enable ( 6'd0 ), + + .dout ( dout ), + .irq_n ( irq_n ), + // YM2203 I/O pins + .IOA_in ( IOA_in ), + .IOB_in ( IOB_in ), + .IOA_out ( IOA_out ), + .IOB_out ( IOB_out ), + .IOA_oe ( IOA_oe ), + .IOB_oe ( IOB_oe ), + // Unused ADPCM pins + .en_hifi_pcm ( 1'b0 ), // used only on YM2612 mode + .adpcma_addr ( ), // real hardware has 10 pins multiplexed through RMPX pin + .adpcma_bank ( ), + .adpcma_roe_n ( ), // ADPCM-A ROM output enable + .adpcma_data ( 8'd0 ), // Data from RAM + .adpcmb_data ( 8'd0 ), + .adpcmb_addr ( ), // real hardware has 12 pins multiplexed through PMPX pin + .adpcmb_roe_n ( ), // ADPCM-B ROM output enable + // Separated output + .psg_A ( psg_A ), + .psg_B ( psg_B ), + .psg_C ( psg_C ), + .psg_snd ( psg_snd ), + .fm_snd_left ( fm_snd ), + .fm_snd_right (), + .adpcmA_l (), + .adpcmA_r (), + .adpcmB_l (), + .adpcmB_r (), + + .snd_right ( snd ), + .snd_left (), + .snd_sample ( snd_sample ), + + //.debug_bus ( debug_bus ), + .debug_bus ( 8'd0 ), + .debug_view ( debug_view ) +); + +endmodule // jt03 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.yaml b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1fc89ac01706420c56420b02bcd2f9b296f1afdb --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03.yaml @@ -0,0 +1,36 @@ +here: + - jt03.v + - jt12_top.v + - jt03_acc.v + - jt12_single_acc.v + - jt12_eg.v + - jt12_eg_cnt.v + - jt12_eg_comb.v + - jt12_eg_step.v + - jt12_eg_pure.v + - jt12_eg_final.v + - jt12_eg_ctrl.v + - jt12_exprom.v + - jt12_kon.v + - jt12_lfo.v + - jt12_mmr.v + - jt12_div.v + - jt12_mod.v + - jt12_op.v + - jt12_csr.v + - jt12_pg.v + - jt12_pg_inc.v + - jt12_pg_dt.v + - jt12_pg_sum.v + - jt12_pg_comb.v + - jt12_pm.v + - jt12_logsin.v + - jt12_reg.v + - jt12_reg_ch.v + - jt12_sh.v + - jt12_sh_rst.v + - jt12_sh24.v + - jt12_sumch.v + - jt12_timers.v + - jt12_dout.v + - ../jt49/hdl/jt49.yaml diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03_acc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03_acc.v new file mode 100644 index 0000000000000000000000000000000000000000..89dae34f19b617681072109fdc1621cd4b361656 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt03_acc.v @@ -0,0 +1,73 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 15-11-2018 + +*/ + + +// Use for YM2203 +// no left/right channels +// full operator resolution +// clamped to maximum output of signed 16 bits +// This version does not clamp each channel individually +// That does not correspond to real hardware behaviour. I should +// change it. + +module jt03_acc +( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input signed [13:0] op_result, + input s1_enters, + input s2_enters, + input s3_enters, + input s4_enters, + input zero, + input [2:0] alg, + // combined output + output signed [15:0] snd +); + +reg sum_en; + +always @(*) begin + case ( alg ) + default: sum_en = s4_enters; + 3'd4: sum_en = s2_enters | s4_enters; + 3'd5,3'd6: sum_en = ~s1_enters; + 3'd7: sum_en = 1'b1; + endcase +end + +// real YM2608 drops the op_result LSB, resulting in a 13-bit accumulator +// but in YM2203, a 13-bit acc for 3 channels only requires 15 bits +// and YM3014 has a 16-bit dynamic range. +// I am leaving the LSB and scaling the output voltage accordingly. This +// should result in less quantification noise. +jt12_single_acc #(.win(14),.wout(16)) u_mono( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( op_result ), + .sum_en ( sum_en ), + .zero ( zero ), + .snd ( snd ) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.v new file mode 100644 index 0000000000000000000000000000000000000000..b6caa97c5e4707b0563c6816ec27bb03ba4551c2 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.v @@ -0,0 +1,112 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +// YM2610 wrapper +// Clock enabled at 7.5 - 8.5MHz + +module jt10( + input rst, // rst should be at least 6 clk&cen cycles long + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [7:0] din, + input [1:0] addr, + input cs_n, + input wr_n, + + output [7:0] dout, + output irq_n, + // ADPCM pins + output [19:0] adpcma_addr, // real hardware has 10 pins multiplexed through RMPX pin + output [4:0] adpcma_bank, + output adpcma_roe_n, // ADPCM-A ROM output enable + input [7:0] adpcma_data, // Data from RAM + output [23:0] adpcmb_addr, // real hardware has 12 pins multiplexed through PMPX pin + output adpcmb_roe_n, // ADPCM-B ROM output enable + input [7:0] adpcmb_data, + // Separated output + output [ 7:0] psg_A, + output [ 7:0] psg_B, + output [ 7:0] psg_C, + output signed [15:0] fm_snd, + // combined output + output [ 9:0] psg_snd, + output signed [15:0] snd_right, + output signed [15:0] snd_left, + output snd_sample, + input [3:0] snd_enable, + input [ 5:0] ch_enable // ADPCM-A channels +); + +// Uses 6 FM channels but only 4 are outputted +jt12_top #( + .use_lfo(1),.use_ssg(1), .num_ch(6), .use_pcm(0), .use_adpcm(1), + .JT49_DIV(3) ) +u_jt12( + .rst ( rst ), // rst should be at least 6 clk&cen cycles long + .clk ( clk ), // CPU clock + .cen ( cen ), // optional clock enable, it not needed leave as 1'b1 + .din ( din ), + .addr ( addr ), + .cs_n ( cs_n ), + .wr_n ( wr_n ), + + .dout ( dout ), + .irq_n ( irq_n ), + // ADPCM pins + .adpcma_addr ( adpcma_addr ), // real hardware has 10 pins multiplexed through RMPX pin + .adpcma_bank ( adpcma_bank ), + .adpcma_roe_n ( adpcma_roe_n ), // ADPCM-A ROM output enable + .adpcma_data ( adpcma_data ), // Data from RAM + .adpcmb_addr ( adpcmb_addr ), // real hardware has 12 pins multiplexed through PMPX pin + .adpcmb_roe_n ( adpcmb_roe_n ), // ADPCM-B ROM output enable + .adpcmb_data ( adpcmb_data ), // Data from RAM + // Separated output + .psg_A ( psg_A ), + .psg_B ( psg_B ), + .psg_C ( psg_C ), + .psg_snd ( psg_snd ), + .fm_snd_left ( fm_snd ), + .fm_snd_right ( ), + .adpcmA_l ( ), + .adpcmA_r ( ), + .adpcmB_l ( ), + .adpcmB_r ( ), + // Unused YM2203 + // unused + .IOA_in ( 8'b0 ), + .IOB_in ( 8'b0 ), + .IOA_out ( ), + .IOB_out ( ), + .IOA_oe ( ), + .IOB_oe ( ), + .debug_bus ( 8'd0 ), + // Sound output + .snd_right ( snd_right ), + .snd_left ( snd_left ), + .snd_sample ( snd_sample ), + .snd_enable ( snd_enable ), + .ch_enable ( ch_enable ), + // unused pins + .en_hifi_pcm ( 1'b0 ), // used only on YM2612 mode + .debug_view ( ) +); + +endmodule // jt03 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.yaml b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0df2ad443548c1dabf0bbb1bb1281302f447f069 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10.yaml @@ -0,0 +1,36 @@ +here: + - jt10.v + - jt10_acc.v + - jt12_top.v + - jt12_single_acc.v + - jt12_eg.v + - jt12_eg_cnt.v + - jt12_eg_comb.v + - jt12_eg_step.v + - jt12_eg_pure.v + - jt12_eg_final.v + - jt12_eg_ctrl.v + - jt12_exprom.v + - jt12_kon.v + - jt12_lfo.v + - jt12_mmr.v + - jt12_div.v + - jt12_mod.v + - jt12_op.v + - jt12_csr.v + - jt12_pg.v + - jt12_pg_inc.v + - jt12_pg_dt.v + - jt12_pg_sum.v + - jt12_pg_comb.v + - jt12_pm.v + - jt12_logsin.v + - jt12_reg.v + - jt12_reg_ch.v + - jt12_sh.v + - jt12_sh_rst.v + - jt12_sh24.v + - jt12_sumch.v + - jt12_timers.v + - jt12_dout.v + - ../jt49/hdl/jt49.yaml diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10_acc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10_acc.v new file mode 100644 index 0000000000000000000000000000000000000000..f0756d7579e4a912c7f467af87a180fcc84ae974 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt10_acc.v @@ -0,0 +1,173 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 + + Each channel can use the full range of the DAC as they do not + get summed in the real chip. + + Operator data is summed up without adding extra bits. This is + the case of real YM3438, which was used on Megadrive 2 models. + + +*/ + +// YM2610 +// ADPCM inputs +// Full OP resolution +// No PCM +// 4 OP channels + +// ADPCM-A input is added for the time assigned to FM channel 0_10 (i.e. 3) + +module jt10_acc( + input clk, + input clk_en /* synthesis direct_enable */, + input signed [13:0] op_result, + input [ 1:0] rl, + input zero, + input s1_enters, + input s2_enters, + input s3_enters, + input s4_enters, + input [2:0] cur_ch, + input [1:0] cur_op, + input [2:0] alg, + input signed [15:0] adpcmA_l, + input signed [15:0] adpcmA_r, + input signed [15:0] adpcmB_l, + input signed [15:0] adpcmB_r, + // combined output + output signed [15:0] left, + output signed [15:0] right +); + +reg sum_en; + +always @(*) begin + case ( alg ) + default: sum_en = s4_enters; + 3'd4: sum_en = s2_enters | s4_enters; + 3'd5,3'd6: sum_en = ~s1_enters; + 3'd7: sum_en = 1'b1; + endcase +end + +wire left_en = rl[1]; +wire right_en= rl[0]; +wire signed [15:0] opext = { {2{op_result[13]}}, op_result }; +reg signed [15:0] acc_input_l, acc_input_r; +reg acc_en_l, acc_en_r; + +// YM2610 mode: +// uses channels 0 and 4 for ADPCM data, throwing away FM data for those channels +// reference: YM2610 Application Notes. +always @(*) + case( {cur_op,cur_ch} ) + {2'd0,3'd0}: begin // ADPCM-A: + acc_input_l = (adpcmA_l <<< 2) + (adpcmA_l <<< 1) + adpcmA_l + (adpcmA_l >>> 2); // amplify by 7.25x to match AES channel balance + acc_input_r = (adpcmA_r <<< 2) + (adpcmA_r <<< 1) + adpcmA_r + (adpcmA_r >>> 2); + `ifndef NOMIX + acc_en_l = 1'b1; + acc_en_r = 1'b1; + `else + acc_en_l = 1'b0; + acc_en_r = 1'b0; + `endif + end + {2'd0,3'd4}: begin // ADPCM-B: + acc_input_l = adpcmB_l >>> 1; // Operator width is 14 bit, ADPCM-B is 16 bit + acc_input_r = adpcmB_r >>> 1; // accumulator width per input channel is 14 bit + `ifndef NOMIX + acc_en_l = 1'b1; + acc_en_r = 1'b1; + `else + acc_en_l = 1'b0; + acc_en_r = 1'b0; + `endif + end + default: begin + // Note by Jose Tejada: + // I don't think we should divide down the FM output + // but someone was looking at the balance of the different + // channels and made this arrangement + // I suppose ADPCM-A would saturate if taken up a factor of 8 instead of 4 + // I'll leave it as it is but I think it is worth revisiting this: + acc_input_l = opext >>> 1; + acc_input_r = opext >>> 1; + acc_en_l = sum_en & left_en; + acc_en_r = sum_en & right_en; + end + endcase + +// Continuous output + +jt12_single_acc #(.win(16),.wout(16)) u_left( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( acc_input_l ), + .sum_en ( acc_en_l ), + .zero ( zero ), + .snd ( left ) +); + +jt12_single_acc #(.win(16),.wout(16)) u_right( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( acc_input_r ), + .sum_en ( acc_en_r ), + .zero ( zero ), + .snd ( right ) +); + +`ifdef SIMULATION +// Dump each channel independently +// It dumps values in decimal, left and right +integer f0,f1,f2,f4,f5,f6; +reg signed [15:0] sum_l[0:7], sum_r[0:7]; + +initial begin + f0=$fopen("fm0.raw","w"); + f1=$fopen("fm1.raw","w"); + f2=$fopen("fm2.raw","w"); + f4=$fopen("fm4.raw","w"); + f5=$fopen("fm5.raw","w"); + f6=$fopen("fm6.raw","w"); +end + +always @(posedge clk) begin + if(cur_op==2'b0) begin + sum_l[cur_ch] <= acc_en_l ? acc_input_l : 16'd0; + sum_r[cur_ch] <= acc_en_r ? acc_input_r : 16'd0; + end else begin + sum_l[cur_ch] <= sum_l[cur_ch] + (acc_en_l ? acc_input_l : 16'd0); + sum_r[cur_ch] <= sum_r[cur_ch] + (acc_en_r ? acc_input_r : 16'd0); + end +end + +always @(posedge zero) begin + $fwrite(f0,"%d,%d\n", sum_l[0], sum_r[0]); + $fwrite(f1,"%d,%d\n", sum_l[1], sum_r[1]); + $fwrite(f2,"%d,%d\n", sum_l[2], sum_r[2]); + $fwrite(f4,"%d,%d\n", sum_l[4], sum_r[4]); + $fwrite(f5,"%d,%d\n", sum_l[5], sum_r[5]); + $fwrite(f6,"%d,%d\n", sum_l[6], sum_r[6]); +end +`endif + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.v new file mode 100644 index 0000000000000000000000000000000000000000..3262535a81b48967114865db17657a9019757622 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.v @@ -0,0 +1,92 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-12-2018 + +*/ + +// Wrapper to output only combined channels. Defaults to YM2612 mode. + +module jt12 ( + input rst, // rst should be at least 6 clk&cen cycles long + input clk, // CPU clock + input cen, // optional clock enable, if not needed leave as 1'b1 + input [7:0] din, + input [1:0] addr, + input cs_n, + input wr_n, + + output [7:0] dout, + output irq_n, + // configuration + input en_hifi_pcm, + // combined output + output signed [15:0] snd_right, + output signed [15:0] snd_left, + output snd_sample +); + +// Default parameters for JT12 select a YM2612 +jt12_top u_jt12( + .rst ( rst ), // rst should be at least 6 clk&cen cycles long + .clk ( clk ), // CPU clock + .cen ( cen ), // optional clock enable, it not needed leave as 1'b1 + .din ( din ), + .addr ( addr ), + .cs_n ( cs_n ), + .wr_n ( wr_n ), + + .dout ( dout ), + .irq_n ( irq_n ), + // configuration + .en_hifi_pcm ( en_hifi_pcm ), + // Unused ADPCM pins + .adpcma_addr ( ), // real hardware has 10 pins multiplexed through RMPX pin + .adpcma_bank ( ), + .adpcma_roe_n ( ), // ADPCM-A ROM output enable + .adpcma_data ( 8'd0 ), // Data from RAM + .adpcmb_addr ( ), // real hardware has 12 pins multiplexed through PMPX pin + .adpcmb_roe_n ( ), // ADPCM-B ROM output enable + .adpcmb_data ( 8'd0 ), + .ch_enable ( 6'h3f), + // Separated output + .psg_A (), + .psg_B (), + .psg_C (), + .fm_snd_left (), + .fm_snd_right (), + .adpcmA_l ( ), + .adpcmA_r ( ), + .adpcmB_l ( ), + .adpcmB_r ( ), + // Unused YM2203 + .IOA_in ( 8'b0 ), + .IOB_in ( 8'b0 ), + .IOA_out ( ), + .IOB_out ( ), + .IOA_oe ( ), + .IOB_oe ( ), + .debug_bus ( 8'd0 ), + // combined output + .psg_snd (), + .snd_right ( snd_right ), // FM+PSG + .snd_left ( snd_left ), // FM+PSG + .snd_sample ( snd_sample ), + .debug_view ( ) +); +endmodule // jt03 diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.vhd b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.vhd new file mode 100644 index 0000000000000000000000000000000000000000..d2e402550ed0b52ad2e63bc57ed6eab9d611566d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.vhd @@ -0,0 +1,44 @@ +library IEEE; +use IEEE.std_logic_1164.all; + +package jt12 is + +component jt12 +port +( + rst : in std_logic; + clk : in std_logic; -- CPU clock + cen : in std_logic := '1'; -- optional clock enable, if not needed leave as '1' + din : in std_logic_vector(7 downto 0); + addr : in std_logic_vector(1 downto 0); + cs_n : in std_logic; + wr_n : in std_logic; + + dout : out std_logic_vector(7 downto 0); + irq_n : out std_logic; + en_hifi_pcm: in std_logic; -- set high to use interpolation on PCM samples + + -- combined output + snd_right : out std_logic_vector(15 downto 0); -- signed + snd_left : out std_logic_vector(15 downto 0); -- signed + snd_sample : out std_logic +); +end component; + +component jt12_genmix +port +( + rst : in std_logic; + clk : in std_logic; -- expects 54 MHz clock + fm_left : in std_logic_vector(15 downto 0); -- FM at 55kHz + fm_right: in std_logic_vector(15 downto 0); -- FM at 55kHz + psg_snd : in std_logic_vector(10 downto 0); -- PSG at 220kHz + fm_en : in std_logic; + psg_en : in std_logic; + -- Mixed sound at 54 MHz + snd_left : out std_logic_vector(15 downto 0); + snd_right : out std_logic_vector(15 downto 0) +); +end component; + +end; diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.yaml b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0b81ceb3bf587a505b88f0a21d689e07828cb69a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12.yaml @@ -0,0 +1,10 @@ +modules: + other: + - from: jt12/hdl + get: + - "*.v" + - adpcm/*.v + - from: jt12/jt49/hdl + get: + - jt49.yaml + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_acc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_acc.v new file mode 100644 index 0000000000000000000000000000000000000000..3d59c10014e3b2defe73d5cccf2c23d5abaf0b5c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_acc.v @@ -0,0 +1,107 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + + Each channel can use the full range of the DAC as they do not + get summed in the real chip. + + Operator data is summed up without adding extra bits. This is + the case of real YM3438, which was used on Megadrive 2 models. + + +*/ + +/* + YM2612 had a limiter to prevent overflow + YM3438 did not + JT12 always has a limiter enabled + */ + +module jt12_acc( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input signed [8:0] op_result, + input [ 1:0] rl, + input zero, + input s1_enters, + input s2_enters, + input s3_enters, + input s4_enters, + input ch6op, + input [2:0] alg, + input pcm_en, // only enabled for channel 6 + input signed [8:0] pcm, + // combined output + output reg signed [11:0] left, + output reg signed [11:0] right +); + +reg sum_en; + +always @(*) begin + case ( alg ) + default: sum_en = s4_enters; + 3'd4: sum_en = s2_enters | s4_enters; + 3'd5,3'd6: sum_en = ~s1_enters; + 3'd7: sum_en = 1'b1; + endcase +end + +reg pcm_sum; + +always @(posedge clk) if(clk_en) + if( zero ) pcm_sum <= 1'b1; + else if( ch6op ) pcm_sum <= 1'b0; + +wire use_pcm = ch6op && pcm_en; +wire sum_or_pcm = sum_en | use_pcm; +wire left_en = rl[1]; +wire right_en= rl[0]; +wire signed [8:0] pcm_data = pcm_sum ? pcm : 9'd0; +wire [8:0] acc_input = use_pcm ? pcm_data : op_result; + +// Continuous output +wire signed [11:0] pre_left, pre_right; +jt12_single_acc #(.win(9),.wout(12)) u_left( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( acc_input ), + .sum_en ( sum_or_pcm & left_en ), + .zero ( zero ), + .snd ( pre_left ) +); + +jt12_single_acc #(.win(9),.wout(12)) u_right( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( acc_input ), + .sum_en ( sum_or_pcm & right_en ), + .zero ( zero ), + .snd ( pre_right ) +); + +// Output can be amplied by 8/6=1.33 to use full range +// an easy alternative is to add 1/4th and get 1.25 amplification +always @(posedge clk) if(clk_en) begin + left <= pre_left + { {2{pre_left [11]}}, pre_left [11:2] }; + right <= pre_right + { {2{pre_right[11]}}, pre_right[11:2] }; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_csr.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_csr.v new file mode 100644 index 0000000000000000000000000000000000000000..74e56abec93d026380e0a37d86af33a4400e0209 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_csr.v @@ -0,0 +1,82 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + +*/ + +module jt12_csr( // Circular Shift Register + input mux + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input [ 7:0] din, + input [43:0] shift_in, + output [43:0] shift_out, + + input up_tl, + input up_dt1, + input up_ks_ar, + input up_amen_dr, + input up_sr, + input up_sl_rr, + input up_ssgeg, + input update_op_I, + input update_op_II, + input update_op_IV +); + +localparam regop_width=44; + +reg [regop_width-1:0] regop_in; + +jt12_sh_rst #(.width(regop_width),.stages(12)) u_regch( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( regop_in ), + .drop ( shift_out ) +); + +wire up_tl_op = up_tl & update_op_IV; +wire up_dt1_op = up_dt1 & update_op_I; +wire up_mul_op = up_dt1 & update_op_II; +wire up_ks_op = up_ks_ar & update_op_II; +wire up_ar_op = up_ks_ar & update_op_I; +wire up_amen_op = up_amen_dr& update_op_IV; +wire up_dr_op = up_amen_dr& update_op_I; +wire up_sr_op = up_sr & update_op_I; +wire up_sl_op = up_sl_rr & update_op_I; +wire up_rr_op = up_sl_rr & update_op_I; +wire up_ssg_op = up_ssgeg & update_op_I; + +always @(*) + regop_in = { + up_tl_op ? din[6:0] : shift_in[43:37], // 7 + up_dt1_op ? din[6:4] : shift_in[36:34], // 3 + up_mul_op ? din[3:0] : shift_in[33:30], // 4 + up_ks_op ? din[7:6] : shift_in[29:28], // 2 + up_ar_op ? din[4:0] : shift_in[27:23], // 5 + up_amen_op ? din[7] : shift_in[ 22], // 1 + up_dr_op ? din[4:0] : shift_in[21:17], // 5 + up_sr_op ? din[4:0] : shift_in[16:12], // 5 + up_sl_op ? din[7:4] : shift_in[11: 8], // 4 + up_rr_op ? din[3:0] : shift_in[ 7: 4], // 4 + up_ssg_op ? din[3:0] : shift_in[ 3: 0] // 4 + }; + +endmodule // jt12_reg \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_div.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_div.v new file mode 100644 index 0000000000000000000000000000000000000000..4b58315e8a407798cb9d1c91c6416eef88cc100c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_div.v @@ -0,0 +1,141 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + */ + + +module jt12_div( + input rst, + input clk, + input cen /* synthesis direct_enable */, + input [1:0] div_setting, + output reg clk_en, // after prescaler + output reg clk_en_2, // cen divided by 2 + output reg clk_en_ssg, + output reg clk_en_666, // 666 kHz + output reg clk_en_111, // 111 kHz + output reg clk_en_55 // 55 kHz +); + +parameter use_ssg=0; + +reg [3:0] opn_pres, opn_cnt=4'd0; +reg [2:0] ssg_pres, ssg_cnt=3'd0; +reg [4:0] adpcm_cnt666 = 5'd0; +reg [2:0] adpcm_cnt111 = 3'd0, adpcm_cnt55=3'd0; +reg cen_int, cen_ssg_int, cen_adpcm_int, cen_adpcm3_int; + +// prescaler values for FM +// reset: 1/3 +// sel1/sel2 +// 0 0 1/3 +// 0 1 1/2 +// 1 0 1/6 +// 1 1 1/2 +// +// According to YM2608 document +// FM SSG div[1:0] +// reset value 1/6 1/4 10 +// 2D 1/6 1/4 10 | 10 +// 2D,2E 1/3 1/2 11 | 01 +// 2F 1/2 1/1 00 & 00 +// + +always @(*) begin + casez( div_setting ) + 2'b0?: begin // FM 1/2 - SSG 1/1 + opn_pres = 4'd2-4'd1; + ssg_pres = 3'd0; + end + 2'b10: begin // FM 1/6 - SSG 1/4 (reset value. Fixed for YM2610) + opn_pres = 4'd6-4'd1; + ssg_pres = 3'd3; + end + 2'b11: begin // FM 1/3 - SSG 1/2 + opn_pres = 4'd3-4'd1; + ssg_pres = 3'd1; + end + endcase // div_setting +end + +`ifdef SIMULATION +initial clk_en_666 = 1'b0; +`endif + +reg cen_55_int; +reg [1:0] div2=2'b0; + +always @(negedge clk) begin + cen_int <= opn_cnt == 4'd0; + cen_ssg_int <= ssg_cnt == 3'd0; + cen_adpcm_int <= adpcm_cnt666 == 5'd0; + cen_adpcm3_int <= adpcm_cnt111 == 3'd0; + cen_55_int <= adpcm_cnt55 == 3'd0; + `ifdef FASTDIV + // always enabled for fast sims (use with GYM output, the timers will not work well) + clk_en <= 1'b1; + clk_en_2 <= 1'b1; + clk_en_ssg <= 1'b1; + clk_en_666 <= 1'b1; + clk_en_55 <= 1'b1; + `else + clk_en <= cen & cen_int; + clk_en_2 <= cen && (div2==2'b00); + clk_en_ssg <= use_ssg ? (cen & cen_ssg_int) : 1'b0; + clk_en_666 <= cen & cen_adpcm_int; + clk_en_111 <= cen & cen_adpcm_int & cen_adpcm3_int; + clk_en_55 <= cen & cen_adpcm_int & cen_adpcm3_int & cen_55_int; + `endif +end + +// Div/2 +always @(posedge clk) + if( cen ) begin + div2 <= div2==2'b10 ? 2'b00 : (div2+2'b01); + end + +// OPN +always @(posedge clk) + if( cen ) begin + if( opn_cnt == opn_pres ) begin + opn_cnt <= 4'd0; + end + else opn_cnt <= opn_cnt + 4'd1; + end + +// SSG +always @(posedge clk) + if( cen ) begin + if( ssg_cnt == ssg_pres ) begin + ssg_cnt <= 3'd0; + end + else ssg_cnt <= ssg_cnt + 3'd1; + end + +// ADPCM-A +always @(posedge clk) + if( cen ) begin + adpcm_cnt666 <= adpcm_cnt666==5'd11 ? 5'd0 : adpcm_cnt666 + 5'd1; + if( adpcm_cnt666==5'd0 ) begin + adpcm_cnt111 <= adpcm_cnt111==3'd5 ? 3'd0 : adpcm_cnt111+3'd1; + if( adpcm_cnt111==3'd0) + adpcm_cnt55 <= adpcm_cnt55==3'd1 ? 3'd0: adpcm_cnt55+3'd1; + end + end + +endmodule // jt12_div diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_dout.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_dout.v new file mode 100644 index 0000000000000000000000000000000000000000..4666b57244bb6a10112e93b056d5cf9c27169aa3 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_dout.v @@ -0,0 +1,47 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt12_dout( + // input rst_n, + input clk, // CPU clock + input flag_A, + input flag_B, + input busy, + input [5:0] adpcma_flags, + input adpcmb_flag, + input [7:0] psg_dout, + input [1:0] addr, + output reg [7:0] dout +); + +parameter use_ssg=0, use_adpcm=0; + +always @(posedge clk) begin + casez( addr ) + 2'b00: dout <= {busy, 5'd0, flag_B, flag_A }; // YM2203 + 2'b01: dout <= (use_ssg ==1) ? psg_dout : {busy, 5'd0, flag_B, flag_A }; + 2'b1?: dout <= (use_adpcm==1) ? + { adpcmb_flag, 1'b0, adpcma_flags } : + { busy, 5'd0, flag_B, flag_A }; + endcase +end + +endmodule // jt12_dout \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg.v new file mode 100644 index 0000000000000000000000000000000000000000..fbf10640de335d243112568afe0ada9b0fa5151a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg.v @@ -0,0 +1,203 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg ( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input zero, + input eg_stop, + // envelope configuration + input [4:0] keycode_II, + input [4:0] arate_I, // attack rate + input [4:0] rate1_I, // decay rate + input [4:0] rate2_I, // sustain rate + input [3:0] rrate_I, // release rate + input [3:0] sl_I, // sustain level + input [1:0] ks_II, // key scale + // SSG operation + input ssg_en_I, + input [2:0] ssg_eg_I, + // envelope operation + input keyon_I, + // envelope number + input [6:0] lfo_mod, + input amsen_IV, + input [1:0] ams_IV, + input [6:0] tl_IV, + + output reg [9:0] eg_V, + output reg pg_rst_II +); + +parameter num_ch=6; + +wire [14:0] eg_cnt; + +jt12_eg_cnt u_egcnt( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en & ~eg_stop ), + .zero ( zero ), + .eg_cnt ( eg_cnt) +); + +wire keyon_last_I; +wire keyon_now_I = !keyon_last_I && keyon_I; +wire keyoff_now_I = keyon_last_I && !keyon_I; + +wire cnt_in_II, cnt_lsb_II, step_II, pg_rst_I; + +wire ssg_inv_in_I, ssg_inv_out_I; +reg ssg_inv_II, ssg_inv_III, ssg_inv_IV; +wire [2:0] state_in_I, state_next_I; + +reg attack_II, attack_III; +wire [4:0] base_rate_I; +reg [4:0] base_rate_II; +wire [5:0] rate_out_II; +reg [5:1] rate_in_III; +reg step_III, ssg_en_II, ssg_en_III; +wire sum_out_II; +reg sum_in_III; + +wire [9:0] eg_in_I, pure_eg_out_III, eg_next_III, eg_out_IV; +reg [9:0] eg_in_II, eg_in_III, eg_in_IV; + + + +jt12_eg_comb u_comb( + /////////////////////////////////// + // I + .keyon_now ( keyon_now_I ), + .keyoff_now ( keyoff_now_I ), + .state_in ( state_in_I ), + .eg_in ( eg_in_I ), + // envelope configuration + .arate ( arate_I ), // attack rate + .rate1 ( rate1_I ), // decay rate + .rate2 ( rate2_I ), // sustain rate + .rrate ( rrate_I ), + .sl ( sl_I ), // sustain level + // SSG operation + .ssg_en ( ssg_en_I ), + .ssg_eg ( ssg_eg_I ), + // SSG output inversion + .ssg_inv_in ( ssg_inv_in_I ), + .ssg_inv_out ( ssg_inv_out_I ), + + .base_rate ( base_rate_I ), + .state_next ( state_next_I ), + .pg_rst ( pg_rst_I ), + /////////////////////////////////// + // II + .step_attack ( attack_II ), + .step_rate_in ( base_rate_II ), + .keycode ( keycode_II ), + .eg_cnt ( eg_cnt ), + .cnt_in ( cnt_in_II ), + .ks ( ks_II ), + .cnt_lsb ( cnt_lsb_II ), + .step ( step_II ), + .step_rate_out ( rate_out_II ), + .sum_up_out ( sum_out_II ), + /////////////////////////////////// + // III + .pure_attack ( attack_III ), + .pure_step ( step_III ), + .pure_rate ( rate_in_III[5:1] ), + .pure_ssg_en ( ssg_en_III ), + .pure_eg_in ( eg_in_III ), + .pure_eg_out ( pure_eg_out_III ), + .sum_up_in ( sum_in_III ), + /////////////////////////////////// + // IV + .lfo_mod ( lfo_mod ), + .amsen ( amsen_IV ), + .ams ( ams_IV ), + .tl ( tl_IV ), + .final_ssg_inv ( ssg_inv_IV ), + .final_eg_in ( eg_in_IV ), + .final_eg_out ( eg_out_IV ) +); + +always @(posedge clk) if(clk_en) begin + eg_in_II <= eg_in_I; + attack_II <= state_next_I[0]; + base_rate_II<= base_rate_I; + ssg_en_II <= ssg_en_I; + ssg_inv_II <= ssg_inv_out_I; + pg_rst_II <= pg_rst_I; + + eg_in_III <= eg_in_II; + attack_III <= attack_II; + rate_in_III <= rate_out_II[5:1]; + ssg_en_III <= ssg_en_II; + ssg_inv_III <= ssg_inv_II; + step_III <= step_II; + sum_in_III <= sum_out_II; + + ssg_inv_IV <= ssg_inv_III; + eg_in_IV <= pure_eg_out_III; + eg_V <= eg_out_IV; +end + +jt12_sh #( .width(1), .stages(4*num_ch) ) u_cntsh( + .clk ( clk ), + .clk_en ( clk_en ), + .din ( cnt_lsb_II), + .drop ( cnt_in_II ) +); + +jt12_sh_rst #( .width(10), .stages(4*num_ch-3), .rstval(1'b1) ) u_egsh( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( eg_in_IV ), + .drop ( eg_in_I ) +); + +jt12_sh_rst #( .width(3), .stages(4*num_ch), .rstval(1'b1) ) u_egstate( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( state_next_I ), + .drop ( state_in_I ) +); + +jt12_sh_rst #( .width(1), .stages(4*num_ch-3), .rstval(1'b0) ) u_ssg_inv( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( ssg_inv_IV ), + .drop ( ssg_inv_in_I ) +); + +jt12_sh_rst #( .width(1), .stages(4*num_ch), .rstval(1'b0) ) u_konsh( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( keyon_I ), + .drop ( keyon_last_I ) +); + + +endmodule // jt12_eg \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_cnt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_cnt.v new file mode 100644 index 0000000000000000000000000000000000000000..df006d6e79f7c25cc180352bbe725f6c25352050 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_cnt.v @@ -0,0 +1,50 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg_cnt( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input zero, + output reg [14:0] eg_cnt +); + +reg [1:0] eg_cnt_base; + +always @(posedge clk, posedge rst) begin : envelope_counter + if( rst ) begin + eg_cnt_base <= 2'd0; + eg_cnt <=15'd0; + end + else begin + if( zero && clk_en ) begin + // envelope counter increases every 3 output samples, + // there is one sample every 24 clock ticks + if( eg_cnt_base == 2'd2 ) begin + eg_cnt <= eg_cnt + 1'b1; + eg_cnt_base <= 2'd0; + end + else eg_cnt_base <= eg_cnt_base + 1'b1; + end + end +end + +endmodule // jt12_eg_cnt \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_comb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..ddf0c533a54786f40e39bc7578a0f82040970e44 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_comb.v @@ -0,0 +1,139 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 30-10-2018 + + */ + +module jt12_eg_comb( + input keyon_now, + input keyoff_now, + input [2:0] state_in, + input [9:0] eg_in, + // envelope configuration + input [4:0] arate, // attack rate + input [4:0] rate1, // decay rate + input [4:0] rate2, // sustain rate + input [3:0] rrate, + input [3:0] sl, // sustain level + // SSG operation + input ssg_en, + input [2:0] ssg_eg, + // SSG output inversion + input ssg_inv_in, + output ssg_inv_out, + + output [4:0] base_rate, + output [2:0] state_next, + output pg_rst, + /////////////////////////////////// + // II + input step_attack, + input [ 4:0] step_rate_in, + input [ 4:0] keycode, + input [14:0] eg_cnt, + input cnt_in, + input [ 1:0] ks, + output cnt_lsb, + output step, + output [5:0] step_rate_out, + output sum_up_out, + /////////////////////////////////// + // III + input pure_attack, + input pure_step, + input [ 5:1] pure_rate, + input pure_ssg_en, + input [ 9:0] pure_eg_in, + output [9:0] pure_eg_out, + input sum_up_in, + /////////////////////////////////// + // IV + input [ 6:0] lfo_mod, + input amsen, + input [ 1:0] ams, + input [ 6:0] tl, + input [ 9:0] final_eg_in, + input final_ssg_inv, + output [9:0] final_eg_out +); + +// I +jt12_eg_ctrl u_ctrl( + .keyon_now ( keyon_now ), + .keyoff_now ( keyoff_now ), + .state_in ( state_in ), + .eg ( eg_in ), + // envelope configuration + .arate ( arate ), // attack rate + .rate1 ( rate1 ), // decay rate + .rate2 ( rate2 ), // sustain rate + .rrate ( rrate ), + .sl ( sl ), // sustain level + // SSG operation + .ssg_en ( ssg_en ), + .ssg_eg ( ssg_eg ), + // SSG output inversion + .ssg_inv_in ( ssg_inv_in ), + .ssg_inv_out ( ssg_inv_out ), + + .base_rate ( base_rate ), + .state_next ( state_next ), + .pg_rst ( pg_rst ) +); + +// II + +jt12_eg_step u_step( + .attack ( step_attack ), + .base_rate ( step_rate_in ), + .keycode ( keycode ), + .eg_cnt ( eg_cnt ), + .cnt_in ( cnt_in ), + .ks ( ks ), + .cnt_lsb ( cnt_lsb ), + .step ( step ), + .rate ( step_rate_out ), + .sum_up ( sum_up_out ) +); + +// III + +wire [9:0] egin, egout; +jt12_eg_pure u_pure( + .attack ( pure_attack ), + .step ( pure_step ), + .rate ( pure_rate ), + .ssg_en ( pure_ssg_en ), + .eg_in ( pure_eg_in ), + .eg_pure( pure_eg_out ), + .sum_up ( sum_up_in ) +); + +// IV + +jt12_eg_final u_final( + .lfo_mod ( lfo_mod ), + .amsen ( amsen ), + .ams ( ams ), + .tl ( tl ), + .ssg_inv ( final_ssg_inv ), + .eg_pure_in ( final_eg_in ), + .eg_limited ( final_eg_out ) +); + +endmodule // jt12_eg_comb \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_ctrl.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..ddd8698edce58d43e3e634a5f6052e098e519e9b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_ctrl.v @@ -0,0 +1,122 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg_ctrl( + input keyon_now, + input keyoff_now, + input [2:0] state_in, + input [9:0] eg, + // envelope configuration + input [4:0] arate, // attack rate + input [4:0] rate1, // decay rate + input [4:0] rate2, // sustain rate + input [3:0] rrate, + input [3:0] sl, // sustain level + // SSG operation + input ssg_en, + input [2:0] ssg_eg, + // SSG output inversion + input ssg_inv_in, + output reg ssg_inv_out, + + output reg [4:0] base_rate, + output reg [2:0] state_next, + output reg pg_rst +); + +localparam ATTACK = 3'b001, + DECAY = 3'b010, + HOLD = 3'b100, + RELEASE= 3'b000; // default state is release + +// wire is_decaying = state_in[1] | state_in[2]; + +reg [4:0] sustain; + +always @(*) + if( sl == 4'd15 ) + sustain = 5'h1f; // 93dB + else + sustain = {1'b0, sl}; + +wire ssg_en_out; +reg ssg_en_in, ssg_pg_rst; + +// aliases +wire ssg_att = ssg_eg[2]; +wire ssg_alt = ssg_eg[1]; +wire ssg_hold = ssg_eg[0] & ssg_en; + +reg ssg_over; + + +always @(*) begin + ssg_over = ssg_en && eg[9]; // eg >=10'h200 + ssg_pg_rst = ssg_over && !( ssg_alt || ssg_hold ); + pg_rst = keyon_now | ssg_pg_rst; +end + +always @(*) + casez ( { keyoff_now, keyon_now, state_in} ) + 5'b01_???: begin // key on + base_rate = arate; + state_next = ATTACK; + ssg_inv_out = ssg_att & ssg_en; + end + {2'b00, ATTACK}: + if( eg==10'd0 ) begin + base_rate = rate1; + state_next = DECAY; + ssg_inv_out = ssg_inv_in; + end + else begin + base_rate = arate; + state_next = ATTACK; + ssg_inv_out = ssg_inv_in; + end + {2'b00, DECAY}: begin + if( ssg_over ) begin + base_rate = ssg_hold ? 5'd0 : arate; + state_next = ssg_hold ? HOLD : ATTACK; + ssg_inv_out = ssg_en & (ssg_alt ^ ssg_inv_in); + end + else begin + base_rate = eg[9:5] >= sustain ? rate2 : rate1; // equal comparison according to Nuke + state_next = DECAY; + ssg_inv_out = ssg_inv_in; + end + end + {2'b00, HOLD}: begin + base_rate = 5'd0; + state_next = HOLD; + ssg_inv_out = ssg_inv_in; + end + default: begin // RELEASE, note that keyoff_now==1 will enter this state too + base_rate = { rrate, 1'b1 }; + state_next = RELEASE; // release + ssg_inv_out = 1'b0; // this can produce a glitch in the output + // But to release from SSG cannot be done nicely while + // inverting the ouput + end + endcase + + +endmodule // jt12_eg_ctrl \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_final.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_final.v new file mode 100644 index 0000000000000000000000000000000000000000..5919fc0f05d91bcd9e649fd617a1619a11e5f6b6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_final.v @@ -0,0 +1,57 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg_final( + input [ 6:0] lfo_mod, + input amsen, + input [ 1:0] ams, + input [ 6:0] tl, + input [ 9:0] eg_pure_in, + input ssg_inv, + output reg [9:0] eg_limited +); + +reg [ 8:0] am_final; +reg [11:0] sum_eg_tl; +reg [11:0] sum_eg_tl_am; +reg [ 5:0] am_inverted; +reg [ 9:0] eg_pream; + +always @(*) begin + am_inverted = lfo_mod[6] ? ~lfo_mod[5:0] : lfo_mod[5:0]; +end + +always @(*) begin + casez( {amsen, ams } ) + default: am_final = 9'd0; + 3'b1_01: am_final = { 5'd0, am_inverted[5:2] }; + 3'b1_10: am_final = { 3'd0, am_inverted }; + 3'b1_11: am_final = { 2'd0, am_inverted, 1'b0 }; + endcase + eg_pream = ssg_inv ? (10'h200-eg_pure_in) : eg_pure_in; + sum_eg_tl = { 1'b0, tl, 3'd0 } + {1'b0, eg_pream}; // leading zeros needed to compute correctly + sum_eg_tl_am = sum_eg_tl + { 3'd0, am_final }; +end + +always @(*) + eg_limited = sum_eg_tl_am[11:10]==2'd0 ? sum_eg_tl_am[9:0] : 10'h3ff; + +endmodule // jt12_eg_final \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_pure.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_pure.v new file mode 100644 index 0000000000000000000000000000000000000000..02a36780ea4f54a15c2c75c2488435039e6d6b90 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_pure.v @@ -0,0 +1,81 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg_pure( + input attack, + input step, + input [ 5:1] rate, + input [ 9:0] eg_in, + input ssg_en, + input sum_up, + output reg [9:0] eg_pure +); + +reg [ 3:0] dr_sum; +reg [ 9:0] dr_adj; +reg [10:0] dr_result; + +always @(*) begin : dr_calculation + case( rate[5:2] ) + 4'b1100: dr_sum = { 2'b0, step, ~step }; // 12 + 4'b1101: dr_sum = { 1'b0, step, ~step, 1'b0 }; // 13 + 4'b1110: dr_sum = { step, ~step, 2'b0 }; // 14 + 4'b1111: dr_sum = 4'd8;// 15 + default: dr_sum = { 2'b0, step, 1'b0 }; + endcase + // Decay rate attenuation is multiplied by 4 for SSG operation + dr_adj = ssg_en ? {4'd0, dr_sum, 2'd0} : {6'd0, dr_sum}; + dr_result = dr_adj + eg_in; +end + +reg [ 7:0] ar_sum0; +reg [ 8:0] ar_sum1; +reg [10:0] ar_result; +reg [ 9:0] ar_sum; + +always @(*) begin : ar_calculation + casez( rate[5:2] ) + default: ar_sum0 = {2'd0, eg_in[9:4]}; + 4'b1101: ar_sum0 = {1'd0, eg_in[9:3]}; + 4'b111?: ar_sum0 = eg_in[9:2]; + endcase + ar_sum1 = ar_sum0+9'd1; + if( rate[5:4] == 2'b11 ) + ar_sum = step ? { ar_sum1, 1'b0 } : { 1'b0, ar_sum1 }; + else + ar_sum = step ? { 1'b0, ar_sum1 } : 10'd0; + ar_result = eg_in-ar_sum; +end +/////////////////////////////////////////////////////////// +// rate not used below this point +reg [9:0] eg_pre_fastar; // pre fast attack rate +always @(*) begin + if(sum_up) begin + if( attack ) + eg_pre_fastar = ar_result[10] ? 10'd0: ar_result[9:0]; + else + eg_pre_fastar = dr_result[10] ? 10'h3FF : dr_result[9:0]; + end + else eg_pre_fastar = eg_in; + eg_pure = (attack&rate[5:1]==5'h1F) ? 10'd0 : eg_pre_fastar; +end + +endmodule // jt12_eg_pure \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_step.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_step.v new file mode 100644 index 0000000000000000000000000000000000000000..4225e4efebc991cb297f525312cbb02915d01bf1 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_eg_step.v @@ -0,0 +1,111 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 29-10-2018 + + */ + +module jt12_eg_step( + input attack, + input [ 4:0] base_rate, + input [ 4:0] keycode, + input [14:0] eg_cnt, + input cnt_in, + input [ 1:0] ks, + output cnt_lsb, + output reg step, + output reg [5:0] rate, + output reg sum_up +); + +reg [6:0] pre_rate; + +always @(*) begin : pre_rate_calc + if( base_rate == 5'd0 ) + pre_rate = 7'd0; + else + case( ks ) + 2'd3: pre_rate = { base_rate, 1'b0 } + { 1'b0, keycode }; + 2'd2: pre_rate = { base_rate, 1'b0 } + { 2'b0, keycode[4:1] }; + 2'd1: pre_rate = { base_rate, 1'b0 } + { 3'b0, keycode[4:2] }; + 2'd0: pre_rate = { base_rate, 1'b0 } + { 4'b0, keycode[4:3] }; + endcase +end + +always @(*) + rate = pre_rate[6] ? 6'd63 : pre_rate[5:0]; + +reg [2:0] cnt; + +reg [4:0] mux_sel; +always @(*) begin + mux_sel = attack ? (rate[5:2]+4'd1): {1'b0,rate[5:2]}; +end // always @(*) + +always @(*) + case( mux_sel ) + 5'h0: cnt = eg_cnt[14:12]; + 5'h1: cnt = eg_cnt[13:11]; + 5'h2: cnt = eg_cnt[12:10]; + 5'h3: cnt = eg_cnt[11: 9]; + 5'h4: cnt = eg_cnt[10: 8]; + 5'h5: cnt = eg_cnt[ 9: 7]; + 5'h6: cnt = eg_cnt[ 8: 6]; + 5'h7: cnt = eg_cnt[ 7: 5]; + 5'h8: cnt = eg_cnt[ 6: 4]; + 5'h9: cnt = eg_cnt[ 5: 3]; + 5'ha: cnt = eg_cnt[ 4: 2]; + 5'hb: cnt = eg_cnt[ 3: 1]; + default: cnt = eg_cnt[ 2: 0]; + endcase + +//////////////////////////////// +reg [7:0] step_idx; + +always @(*) begin : rate_step + if( rate[5:4]==2'b11 ) begin // 0 means 1x, 1 means 2x + if( rate[5:2]==4'hf && attack) + step_idx = 8'b11111111; // Maximum attack speed, rates 60&61 + else + case( rate[1:0] ) + 2'd0: step_idx = 8'b00000000; + 2'd1: step_idx = 8'b10001000; // 2 + 2'd2: step_idx = 8'b10101010; // 4 + 2'd3: step_idx = 8'b11101110; // 6 + endcase + end + else begin + if( rate[5:2]==4'd0 && !attack) + step_idx = 8'b11111110; // limit slowest decay rate + else + case( rate[1:0] ) + 2'd0: step_idx = 8'b10101010; // 4 + 2'd1: step_idx = 8'b11101010; // 5 + 2'd2: step_idx = 8'b11101110; // 6 + 2'd3: step_idx = 8'b11111110; // 7 + endcase + end + // a rate of zero keeps the level still + step = rate[5:1]==5'd0 ? 1'b0 : step_idx[ cnt ]; +end + +assign cnt_lsb = cnt[0]; +always @(*) begin + sum_up = cnt[0] != cnt_in; +end + +endmodule // eg_step \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_exprom.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_exprom.v new file mode 100644 index 0000000000000000000000000000000000000000..beca296362fe2af78fc51e931cd811334fcc9c50 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_exprom.v @@ -0,0 +1,301 @@ + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Based on Sauraen VHDL version of OPN/OPN2, which is based on die shots. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +// altera message_off 10030 + +module jt12_exprom +( + input [7:0] addr, + input clk, + input clk_en /* synthesis direct_enable */, + output reg [9:0] exp +); + + reg [9:0] explut_jt51[255:0]; + initial + begin + explut_jt51[8'd000] = 10'd1018; + explut_jt51[8'd001] = 10'd1013; + explut_jt51[8'd002] = 10'd1007; + explut_jt51[8'd003] = 10'd1002; + explut_jt51[8'd004] = 10'd0996; + explut_jt51[8'd005] = 10'd0991; + explut_jt51[8'd006] = 10'd0986; + explut_jt51[8'd007] = 10'd0980; + explut_jt51[8'd008] = 10'd0975; + explut_jt51[8'd009] = 10'd0969; + explut_jt51[8'd010] = 10'd0964; + explut_jt51[8'd011] = 10'd0959; + explut_jt51[8'd012] = 10'd0953; + explut_jt51[8'd013] = 10'd0948; + explut_jt51[8'd014] = 10'd0942; + explut_jt51[8'd015] = 10'd0937; + explut_jt51[8'd016] = 10'd0932; + explut_jt51[8'd017] = 10'd0927; + explut_jt51[8'd018] = 10'd0921; + explut_jt51[8'd019] = 10'd0916; + explut_jt51[8'd020] = 10'd0911; + explut_jt51[8'd021] = 10'd0906; + explut_jt51[8'd022] = 10'd0900; + explut_jt51[8'd023] = 10'd0895; + explut_jt51[8'd024] = 10'd0890; + explut_jt51[8'd025] = 10'd0885; + explut_jt51[8'd026] = 10'd0880; + explut_jt51[8'd027] = 10'd0874; + explut_jt51[8'd028] = 10'd0869; + explut_jt51[8'd029] = 10'd0864; + explut_jt51[8'd030] = 10'd0859; + explut_jt51[8'd031] = 10'd0854; + explut_jt51[8'd032] = 10'd0849; + explut_jt51[8'd033] = 10'd0844; + explut_jt51[8'd034] = 10'd0839; + explut_jt51[8'd035] = 10'd0834; + explut_jt51[8'd036] = 10'd0829; + explut_jt51[8'd037] = 10'd0824; + explut_jt51[8'd038] = 10'd0819; + explut_jt51[8'd039] = 10'd0814; + explut_jt51[8'd040] = 10'd0809; + explut_jt51[8'd041] = 10'd0804; + explut_jt51[8'd042] = 10'd0799; + explut_jt51[8'd043] = 10'd0794; + explut_jt51[8'd044] = 10'd0789; + explut_jt51[8'd045] = 10'd0784; + explut_jt51[8'd046] = 10'd0779; + explut_jt51[8'd047] = 10'd0774; + explut_jt51[8'd048] = 10'd0770; + explut_jt51[8'd049] = 10'd0765; + explut_jt51[8'd050] = 10'd0760; + explut_jt51[8'd051] = 10'd0755; + explut_jt51[8'd052] = 10'd0750; + explut_jt51[8'd053] = 10'd0745; + explut_jt51[8'd054] = 10'd0741; + explut_jt51[8'd055] = 10'd0736; + explut_jt51[8'd056] = 10'd0731; + explut_jt51[8'd057] = 10'd0726; + explut_jt51[8'd058] = 10'd0722; + explut_jt51[8'd059] = 10'd0717; + explut_jt51[8'd060] = 10'd0712; + explut_jt51[8'd061] = 10'd0708; + explut_jt51[8'd062] = 10'd0703; + explut_jt51[8'd063] = 10'd0698; + explut_jt51[8'd064] = 10'd0693; + explut_jt51[8'd065] = 10'd0689; + explut_jt51[8'd066] = 10'd0684; + explut_jt51[8'd067] = 10'd0680; + explut_jt51[8'd068] = 10'd0675; + explut_jt51[8'd069] = 10'd0670; + explut_jt51[8'd070] = 10'd0666; + explut_jt51[8'd071] = 10'd0661; + explut_jt51[8'd072] = 10'd0657; + explut_jt51[8'd073] = 10'd0652; + explut_jt51[8'd074] = 10'd0648; + explut_jt51[8'd075] = 10'd0643; + explut_jt51[8'd076] = 10'd0639; + explut_jt51[8'd077] = 10'd0634; + explut_jt51[8'd078] = 10'd0630; + explut_jt51[8'd079] = 10'd0625; + explut_jt51[8'd080] = 10'd0621; + explut_jt51[8'd081] = 10'd0616; + explut_jt51[8'd082] = 10'd0612; + explut_jt51[8'd083] = 10'd0607; + explut_jt51[8'd084] = 10'd0603; + explut_jt51[8'd085] = 10'd0599; + explut_jt51[8'd086] = 10'd0594; + explut_jt51[8'd087] = 10'd0590; + explut_jt51[8'd088] = 10'd0585; + explut_jt51[8'd089] = 10'd0581; + explut_jt51[8'd090] = 10'd0577; + explut_jt51[8'd091] = 10'd0572; + explut_jt51[8'd092] = 10'd0568; + explut_jt51[8'd093] = 10'd0564; + explut_jt51[8'd094] = 10'd0560; + explut_jt51[8'd095] = 10'd0555; + explut_jt51[8'd096] = 10'd0551; + explut_jt51[8'd097] = 10'd0547; + explut_jt51[8'd098] = 10'd0542; + explut_jt51[8'd099] = 10'd0538; + explut_jt51[8'd100] = 10'd0534; + explut_jt51[8'd101] = 10'd0530; + explut_jt51[8'd102] = 10'd0526; + explut_jt51[8'd103] = 10'd0521; + explut_jt51[8'd104] = 10'd0517; + explut_jt51[8'd105] = 10'd0513; + explut_jt51[8'd106] = 10'd0509; + explut_jt51[8'd107] = 10'd0505; + explut_jt51[8'd108] = 10'd0501; + explut_jt51[8'd109] = 10'd0496; + explut_jt51[8'd110] = 10'd0492; + explut_jt51[8'd111] = 10'd0488; + explut_jt51[8'd112] = 10'd0484; + explut_jt51[8'd113] = 10'd0480; + explut_jt51[8'd114] = 10'd0476; + explut_jt51[8'd115] = 10'd0472; + explut_jt51[8'd116] = 10'd0468; + explut_jt51[8'd117] = 10'd0464; + explut_jt51[8'd118] = 10'd0460; + explut_jt51[8'd119] = 10'd0456; + explut_jt51[8'd120] = 10'd0452; + explut_jt51[8'd121] = 10'd0448; + explut_jt51[8'd122] = 10'd0444; + explut_jt51[8'd123] = 10'd0440; + explut_jt51[8'd124] = 10'd0436; + explut_jt51[8'd125] = 10'd0432; + explut_jt51[8'd126] = 10'd0428; + explut_jt51[8'd127] = 10'd0424; + explut_jt51[8'd128] = 10'd0420; + explut_jt51[8'd129] = 10'd0416; + explut_jt51[8'd130] = 10'd0412; + explut_jt51[8'd131] = 10'd0409; + explut_jt51[8'd132] = 10'd0405; + explut_jt51[8'd133] = 10'd0401; + explut_jt51[8'd134] = 10'd0397; + explut_jt51[8'd135] = 10'd0393; + explut_jt51[8'd136] = 10'd0389; + explut_jt51[8'd137] = 10'd0385; + explut_jt51[8'd138] = 10'd0382; + explut_jt51[8'd139] = 10'd0378; + explut_jt51[8'd140] = 10'd0374; + explut_jt51[8'd141] = 10'd0370; + explut_jt51[8'd142] = 10'd0367; + explut_jt51[8'd143] = 10'd0363; + explut_jt51[8'd144] = 10'd0359; + explut_jt51[8'd145] = 10'd0355; + explut_jt51[8'd146] = 10'd0352; + explut_jt51[8'd147] = 10'd0348; + explut_jt51[8'd148] = 10'd0344; + explut_jt51[8'd149] = 10'd0340; + explut_jt51[8'd150] = 10'd0337; + explut_jt51[8'd151] = 10'd0333; + explut_jt51[8'd152] = 10'd0329; + explut_jt51[8'd153] = 10'd0326; + explut_jt51[8'd154] = 10'd0322; + explut_jt51[8'd155] = 10'd0318; + explut_jt51[8'd156] = 10'd0315; + explut_jt51[8'd157] = 10'd0311; + explut_jt51[8'd158] = 10'd0308; + explut_jt51[8'd159] = 10'd0304; + explut_jt51[8'd160] = 10'd0300; + explut_jt51[8'd161] = 10'd0297; + explut_jt51[8'd162] = 10'd0293; + explut_jt51[8'd163] = 10'd0290; + explut_jt51[8'd164] = 10'd0286; + explut_jt51[8'd165] = 10'd0283; + explut_jt51[8'd166] = 10'd0279; + explut_jt51[8'd167] = 10'd0276; + explut_jt51[8'd168] = 10'd0272; + explut_jt51[8'd169] = 10'd0268; + explut_jt51[8'd170] = 10'd0265; + explut_jt51[8'd171] = 10'd0262; + explut_jt51[8'd172] = 10'd0258; + explut_jt51[8'd173] = 10'd0255; + explut_jt51[8'd174] = 10'd0251; + explut_jt51[8'd175] = 10'd0248; + explut_jt51[8'd176] = 10'd0244; + explut_jt51[8'd177] = 10'd0241; + explut_jt51[8'd178] = 10'd0237; + explut_jt51[8'd179] = 10'd0234; + explut_jt51[8'd180] = 10'd0231; + explut_jt51[8'd181] = 10'd0227; + explut_jt51[8'd182] = 10'd0224; + explut_jt51[8'd183] = 10'd0220; + explut_jt51[8'd184] = 10'd0217; + explut_jt51[8'd185] = 10'd0214; + explut_jt51[8'd186] = 10'd0210; + explut_jt51[8'd187] = 10'd0207; + explut_jt51[8'd188] = 10'd0204; + explut_jt51[8'd189] = 10'd0200; + explut_jt51[8'd190] = 10'd0197; + explut_jt51[8'd191] = 10'd0194; + explut_jt51[8'd192] = 10'd0190; + explut_jt51[8'd193] = 10'd0187; + explut_jt51[8'd194] = 10'd0184; + explut_jt51[8'd195] = 10'd0181; + explut_jt51[8'd196] = 10'd0177; + explut_jt51[8'd197] = 10'd0174; + explut_jt51[8'd198] = 10'd0171; + explut_jt51[8'd199] = 10'd0168; + explut_jt51[8'd200] = 10'd0164; + explut_jt51[8'd201] = 10'd0161; + explut_jt51[8'd202] = 10'd0158; + explut_jt51[8'd203] = 10'd0155; + explut_jt51[8'd204] = 10'd0152; + explut_jt51[8'd205] = 10'd0148; + explut_jt51[8'd206] = 10'd0145; + explut_jt51[8'd207] = 10'd0142; + explut_jt51[8'd208] = 10'd0139; + explut_jt51[8'd209] = 10'd0136; + explut_jt51[8'd210] = 10'd0133; + explut_jt51[8'd211] = 10'd0130; + explut_jt51[8'd212] = 10'd0126; + explut_jt51[8'd213] = 10'd0123; + explut_jt51[8'd214] = 10'd0120; + explut_jt51[8'd215] = 10'd0117; + explut_jt51[8'd216] = 10'd0114; + explut_jt51[8'd217] = 10'd0111; + explut_jt51[8'd218] = 10'd0108; + explut_jt51[8'd219] = 10'd0105; + explut_jt51[8'd220] = 10'd0102; + explut_jt51[8'd221] = 10'd0099; + explut_jt51[8'd222] = 10'd0096; + explut_jt51[8'd223] = 10'd0093; + explut_jt51[8'd224] = 10'd0090; + explut_jt51[8'd225] = 10'd0087; + explut_jt51[8'd226] = 10'd0084; + explut_jt51[8'd227] = 10'd0081; + explut_jt51[8'd228] = 10'd0078; + explut_jt51[8'd229] = 10'd0075; + explut_jt51[8'd230] = 10'd0072; + explut_jt51[8'd231] = 10'd0069; + explut_jt51[8'd232] = 10'd0066; + explut_jt51[8'd233] = 10'd0063; + explut_jt51[8'd234] = 10'd0060; + explut_jt51[8'd235] = 10'd0057; + explut_jt51[8'd236] = 10'd0054; + explut_jt51[8'd237] = 10'd0051; + explut_jt51[8'd238] = 10'd0048; + explut_jt51[8'd239] = 10'd0045; + explut_jt51[8'd240] = 10'd0042; + explut_jt51[8'd241] = 10'd0040; + explut_jt51[8'd242] = 10'd0037; + explut_jt51[8'd243] = 10'd0034; + explut_jt51[8'd244] = 10'd0031; + explut_jt51[8'd245] = 10'd0028; + explut_jt51[8'd246] = 10'd0025; + explut_jt51[8'd247] = 10'd0022; + explut_jt51[8'd248] = 10'd0020; + explut_jt51[8'd249] = 10'd0017; + explut_jt51[8'd250] = 10'd0014; + explut_jt51[8'd251] = 10'd0011; + explut_jt51[8'd252] = 10'd0008; + explut_jt51[8'd253] = 10'd0006; + explut_jt51[8'd254] = 10'd0003; + explut_jt51[8'd255] = 10'd0000; + end + + always @ (posedge clk) if(clk_en) + exp <= explut_jt51[addr]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_kon.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_kon.v new file mode 100644 index 0000000000000000000000000000000000000000..db4b82cbb266ed906e0cde90ef44fa1b533068e6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_kon.v @@ -0,0 +1,150 @@ + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +module jt12_kon( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input [3:0] keyon_op, + input [2:0] keyon_ch, + input [1:0] next_op, + input [2:0] next_ch, + input up_keyon, + input csm, + // input flag_A, + input overflow_A, + + output reg keyon_I +); + +parameter num_ch=6; + +wire csr_out; + +generate +if(num_ch==6) begin + // capture overflow signal so it lasts long enough + reg overflow2; + reg [4:0] overflow_cycle; + + always @(posedge clk) if( clk_en ) begin + if(overflow_A) begin + overflow2 <= 1'b1; + overflow_cycle <= { next_op, next_ch }; + end else begin + if(overflow_cycle == {next_op, next_ch}) overflow2<=1'b0; + end + end + + always @(posedge clk) if( clk_en ) + keyon_I <= (csm&&next_ch==3'd2&&overflow2) || csr_out; + + reg up_keyon_reg; + reg [3:0] tkeyon_op; + reg [2:0] tkeyon_ch; + wire key_upnow; + + assign key_upnow = up_keyon_reg && (tkeyon_ch==next_ch) && (next_op == 2'd3); + + always @(posedge clk) if( clk_en ) begin + if (rst) + up_keyon_reg <= 1'b0; + if (up_keyon) begin + up_keyon_reg <= 1'b1; + tkeyon_op <= keyon_op; + tkeyon_ch <= keyon_ch; end + else if (key_upnow) + up_keyon_reg <= 1'b0; + end + + + wire middle1; + wire middle2; + wire middle3; + wire din = key_upnow ? tkeyon_op[3] : csr_out; + wire mid_din2 = key_upnow ? tkeyon_op[1] : middle1; + wire mid_din3 = key_upnow ? tkeyon_op[2] : middle2; + wire mid_din4 = key_upnow ? tkeyon_op[0] : middle3; + + jt12_sh_rst #(.width(1),.stages(6),.rstval(1'b0)) u_konch0( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( din ), + .drop ( middle1 ) + ); + + jt12_sh_rst #(.width(1),.stages(6),.rstval(1'b0)) u_konch1( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( mid_din2 ), + .drop ( middle2 ) + ); + + jt12_sh_rst #(.width(1),.stages(6),.rstval(1'b0)) u_konch2( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( mid_din3 ), + .drop ( middle3 ) + ); + + jt12_sh_rst #(.width(1),.stages(6),.rstval(1'b0)) u_konch3( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( mid_din4 ), + .drop ( csr_out ) + ); +end +else begin // 3 channels + reg din; + reg [3:0] next_op_hot; + + always @(*) begin + case( next_op ) + 2'd0: next_op_hot = 4'b0001; // S1 + 2'd1: next_op_hot = 4'b0100; // S3 + 2'd2: next_op_hot = 4'b0010; // S2 + 2'd3: next_op_hot = 4'b1000; // S4 + endcase + din = keyon_ch[1:0]==next_ch[1:0] && up_keyon ? |(keyon_op&next_op_hot) : csr_out; + end + + always @(posedge clk) if( clk_en ) + keyon_I <= csr_out; // No CSM for YM2203 + + jt12_sh_rst #(.width(1),.stages(12),.rstval(1'b0)) u_konch1( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( din ), + .drop ( csr_out ) + ); +end +endgenerate + + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_lfo.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_lfo.v new file mode 100644 index 0000000000000000000000000000000000000000..7c58efb9aa9582b7963efc612aa6911f293dc1f0 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_lfo.v @@ -0,0 +1,102 @@ +/* This file is part of jt12. + + jt12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + jt12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with jt12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 25-2-2017 + */ + + +/* + + Does the LFO frequency depend on the pre-scaler for YM2608 ? + + From spritesmind.net: + "That would be 7-bit LFO step counter (which is incremented on each LFO clock and reset when LFO enable bit is cleared). + LFO AM value indeed corresponds to LFO step counter bits 0:5 shifted left by one + and XORed with inversion of bit 6 (to generate an inverted triangle waveform) + + LFO AM sensitivity (2 bits) indicates to EG how much LFO AM value is shifted before adding to EG output + [...] + LFO PM step (0-31), which takes bits 2:6 of LFO step counter (0-127) and goes to LFO PM calcuation unit + " + + From Sauraen: + +The LFO seems to have 3 sections: + + [*] 7-bit linear prescaler. The test bit 0x21:1 goes into what looks like the carry-in or something similar; + it could go into the reset, I can't quite tell with more detailed analysis. The 7-bit output (plus maybe carry-out) + gets logiced together into 8 lines (evidently perform "== N" with N hardcoded for each line), and these go into a + little selector unit which is also fed by the LFO Speed and LFO Enable bits. I can't quite see the output of this, + but I do see there's some sort of feedback to the prescaler's reset. So this clearly seems like a divide-by-N prescaler. + I can try to read the eight N's for you if you want, but you should be able to reverse engineer them from knowing what the LFO speeds are. + + [*] 7-bit linear counter, with an 8-bit unit after the output (possibly inverts the output after each cycle to make a triangle wave?). + Bits 1:6 of the output of this go to the EG, and stick into its pipeline at the same place where the LFO->Amplitude two bits go. + (Elsewhere the operator LFO enable flag simply forces these two bits to zero for operators not affected by the LFO.) + Some modified version of the 8-bit signal between the counter and the inverter unit thing goes to the third unit of the LFO. + + [*] Highly complex unit which modifies the frequency data as it goes from the channel registers to the PG. The block bits bypass this, + but all the frequency bits get modified by it. There's a bitslice portion corresponding to bits 0:6, and then what appears to be + the same logic folded over to process bits 7:A. But the interesting part is that bits 4:A of the frequency data go into the + bitslices 0:6. That is, the bitslice unit for bit 0 has bit 0 enter at the middle and leave (to the PG) at the bottom. But it also has bit 4 enter at the top. + And so on through bit 6 having bit A enter at the top. It looks like the top portion is some sort of shifter for bits 4:A--the wires go diagonally + so that bit 4 only gets used once, bit 5 gets used in bitslice 1 and 0, bit 6 gets used in bitslices 2:0, and so on so that bit A gets used in all of them. + I'm guessing this whole unit is basically a multiplier, multiplying bits 4:A of the frequency value by bits 0:7 of the LFO state, and then adding the result + to bits 0:6 of the frequency value (with carry up to the higher bits). It looks like, between the multiplied output and the adder, there's another shifter + whose value is based on the the LFO->Frequency bits. But it looks like it's a bit more complex than I'm describing. + +*/ + +module jt12_lfo( + input rst, + input clk, + input clk_en, + input zero, + input lfo_rst, + input lfo_en, + input [2:0] lfo_freq, + output reg [6:0] lfo_mod // 7-bit width according to spritesmind.net +); + +reg [6:0] cnt, limit; + +always @(*) + case( lfo_freq ) // same values as in MAME + 3'd0: limit = 7'd108; + 3'd1: limit = 7'd77; + 3'd2: limit = 7'd71; + 3'd3: limit = 7'd67; + 3'd4: limit = 7'd62; + 3'd5: limit = 7'd44; + 3'd6: limit = 7'd8; + 3'd7: limit = 7'd5; + endcase + +always @(posedge clk) + if( rst || !lfo_en ) + { lfo_mod, cnt } <= 14'd0; + else if( clk_en && zero) begin + if( cnt == limit ) begin + cnt <= 7'd0; + lfo_mod <= lfo_mod + 1'b1; + end + else begin + cnt <= cnt + 1'b1; + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_logsin.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_logsin.v new file mode 100644 index 0000000000000000000000000000000000000000..897437544d5e7d52bb8f1744886aac0f1f67ac07 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_logsin.v @@ -0,0 +1,298 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Based on Sauraen VHDL version of OPN/OPN2, which is based on die shots. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +//altera message_off 10030 + +module jt12_logsin +( + input [7:0] addr, + input clk, + input clk_en, + output reg [11:0] logsin +); + +reg [11:0] sinelut[255:0]; +initial begin + sinelut[8'd000] = 12'h000; + sinelut[8'd001] = 12'h000; + sinelut[8'd002] = 12'h000; + sinelut[8'd003] = 12'h000; + sinelut[8'd004] = 12'h000; + sinelut[8'd005] = 12'h000; + sinelut[8'd006] = 12'h000; + sinelut[8'd007] = 12'h000; + sinelut[8'd008] = 12'h001; + sinelut[8'd009] = 12'h001; + sinelut[8'd010] = 12'h001; + sinelut[8'd011] = 12'h001; + sinelut[8'd012] = 12'h001; + sinelut[8'd013] = 12'h001; + sinelut[8'd014] = 12'h001; + sinelut[8'd015] = 12'h002; + sinelut[8'd016] = 12'h002; + sinelut[8'd017] = 12'h002; + sinelut[8'd018] = 12'h002; + sinelut[8'd019] = 12'h003; + sinelut[8'd020] = 12'h003; + sinelut[8'd021] = 12'h003; + sinelut[8'd022] = 12'h004; + sinelut[8'd023] = 12'h004; + sinelut[8'd024] = 12'h004; + sinelut[8'd025] = 12'h005; + sinelut[8'd026] = 12'h005; + sinelut[8'd027] = 12'h005; + sinelut[8'd028] = 12'h006; + sinelut[8'd029] = 12'h006; + sinelut[8'd030] = 12'h007; + sinelut[8'd031] = 12'h007; + sinelut[8'd032] = 12'h007; + sinelut[8'd033] = 12'h008; + sinelut[8'd034] = 12'h008; + sinelut[8'd035] = 12'h009; + sinelut[8'd036] = 12'h009; + sinelut[8'd037] = 12'h00a; + sinelut[8'd038] = 12'h00a; + sinelut[8'd039] = 12'h00b; + sinelut[8'd040] = 12'h00c; + sinelut[8'd041] = 12'h00c; + sinelut[8'd042] = 12'h00d; + sinelut[8'd043] = 12'h00d; + sinelut[8'd044] = 12'h00e; + sinelut[8'd045] = 12'h00f; + sinelut[8'd046] = 12'h00f; + sinelut[8'd047] = 12'h010; + sinelut[8'd048] = 12'h011; + sinelut[8'd049] = 12'h011; + sinelut[8'd050] = 12'h012; + sinelut[8'd051] = 12'h013; + sinelut[8'd052] = 12'h014; + sinelut[8'd053] = 12'h014; + sinelut[8'd054] = 12'h015; + sinelut[8'd055] = 12'h016; + sinelut[8'd056] = 12'h017; + sinelut[8'd057] = 12'h017; + sinelut[8'd058] = 12'h018; + sinelut[8'd059] = 12'h019; + sinelut[8'd060] = 12'h01a; + sinelut[8'd061] = 12'h01b; + sinelut[8'd062] = 12'h01c; + sinelut[8'd063] = 12'h01d; + sinelut[8'd064] = 12'h01e; + sinelut[8'd065] = 12'h01f; + sinelut[8'd066] = 12'h020; + sinelut[8'd067] = 12'h021; + sinelut[8'd068] = 12'h022; + sinelut[8'd069] = 12'h023; + sinelut[8'd070] = 12'h024; + sinelut[8'd071] = 12'h025; + sinelut[8'd072] = 12'h026; + sinelut[8'd073] = 12'h027; + sinelut[8'd074] = 12'h028; + sinelut[8'd075] = 12'h029; + sinelut[8'd076] = 12'h02a; + sinelut[8'd077] = 12'h02b; + sinelut[8'd078] = 12'h02d; + sinelut[8'd079] = 12'h02e; + sinelut[8'd080] = 12'h02f; + sinelut[8'd081] = 12'h030; + sinelut[8'd082] = 12'h031; + sinelut[8'd083] = 12'h033; + sinelut[8'd084] = 12'h034; + sinelut[8'd085] = 12'h035; + sinelut[8'd086] = 12'h037; + sinelut[8'd087] = 12'h038; + sinelut[8'd088] = 12'h039; + sinelut[8'd089] = 12'h03b; + sinelut[8'd090] = 12'h03c; + sinelut[8'd091] = 12'h03e; + sinelut[8'd092] = 12'h03f; + sinelut[8'd093] = 12'h040; + sinelut[8'd094] = 12'h042; + sinelut[8'd095] = 12'h043; + sinelut[8'd096] = 12'h045; + sinelut[8'd097] = 12'h046; + sinelut[8'd098] = 12'h048; + sinelut[8'd099] = 12'h04a; + sinelut[8'd100] = 12'h04b; + sinelut[8'd101] = 12'h04d; + sinelut[8'd102] = 12'h04e; + sinelut[8'd103] = 12'h050; + sinelut[8'd104] = 12'h052; + sinelut[8'd105] = 12'h053; + sinelut[8'd106] = 12'h055; + sinelut[8'd107] = 12'h057; + sinelut[8'd108] = 12'h059; + sinelut[8'd109] = 12'h05b; + sinelut[8'd110] = 12'h05c; + sinelut[8'd111] = 12'h05e; + sinelut[8'd112] = 12'h060; + sinelut[8'd113] = 12'h062; + sinelut[8'd114] = 12'h064; + sinelut[8'd115] = 12'h066; + sinelut[8'd116] = 12'h068; + sinelut[8'd117] = 12'h06a; + sinelut[8'd118] = 12'h06c; + sinelut[8'd119] = 12'h06e; + sinelut[8'd120] = 12'h070; + sinelut[8'd121] = 12'h072; + sinelut[8'd122] = 12'h074; + sinelut[8'd123] = 12'h076; + sinelut[8'd124] = 12'h078; + sinelut[8'd125] = 12'h07a; + sinelut[8'd126] = 12'h07d; + sinelut[8'd127] = 12'h07f; + sinelut[8'd128] = 12'h081; + sinelut[8'd129] = 12'h083; + sinelut[8'd130] = 12'h086; + sinelut[8'd131] = 12'h088; + sinelut[8'd132] = 12'h08a; + sinelut[8'd133] = 12'h08d; + sinelut[8'd134] = 12'h08f; + sinelut[8'd135] = 12'h092; + sinelut[8'd136] = 12'h094; + sinelut[8'd137] = 12'h097; + sinelut[8'd138] = 12'h099; + sinelut[8'd139] = 12'h09c; + sinelut[8'd140] = 12'h09f; + sinelut[8'd141] = 12'h0a1; + sinelut[8'd142] = 12'h0a4; + sinelut[8'd143] = 12'h0a7; + sinelut[8'd144] = 12'h0a9; + sinelut[8'd145] = 12'h0ac; + sinelut[8'd146] = 12'h0af; + sinelut[8'd147] = 12'h0b2; + sinelut[8'd148] = 12'h0b5; + sinelut[8'd149] = 12'h0b8; + sinelut[8'd150] = 12'h0bb; + sinelut[8'd151] = 12'h0be; + sinelut[8'd152] = 12'h0c1; + sinelut[8'd153] = 12'h0c4; + sinelut[8'd154] = 12'h0c7; + sinelut[8'd155] = 12'h0ca; + sinelut[8'd156] = 12'h0cd; + sinelut[8'd157] = 12'h0d1; + sinelut[8'd158] = 12'h0d4; + sinelut[8'd159] = 12'h0d7; + sinelut[8'd160] = 12'h0db; + sinelut[8'd161] = 12'h0de; + sinelut[8'd162] = 12'h0e2; + sinelut[8'd163] = 12'h0e5; + sinelut[8'd164] = 12'h0e9; + sinelut[8'd165] = 12'h0ec; + sinelut[8'd166] = 12'h0f0; + sinelut[8'd167] = 12'h0f4; + sinelut[8'd168] = 12'h0f8; + sinelut[8'd169] = 12'h0fb; + sinelut[8'd170] = 12'h0ff; + sinelut[8'd171] = 12'h103; + sinelut[8'd172] = 12'h107; + sinelut[8'd173] = 12'h10b; + sinelut[8'd174] = 12'h10f; + sinelut[8'd175] = 12'h114; + sinelut[8'd176] = 12'h118; + sinelut[8'd177] = 12'h11c; + sinelut[8'd178] = 12'h121; + sinelut[8'd179] = 12'h125; + sinelut[8'd180] = 12'h129; + sinelut[8'd181] = 12'h12e; + sinelut[8'd182] = 12'h133; + sinelut[8'd183] = 12'h137; + sinelut[8'd184] = 12'h13c; + sinelut[8'd185] = 12'h141; + sinelut[8'd186] = 12'h146; + sinelut[8'd187] = 12'h14b; + sinelut[8'd188] = 12'h150; + sinelut[8'd189] = 12'h155; + sinelut[8'd190] = 12'h15b; + sinelut[8'd191] = 12'h160; + sinelut[8'd192] = 12'h166; + sinelut[8'd193] = 12'h16b; + sinelut[8'd194] = 12'h171; + sinelut[8'd195] = 12'h177; + sinelut[8'd196] = 12'h17c; + sinelut[8'd197] = 12'h182; + sinelut[8'd198] = 12'h188; + sinelut[8'd199] = 12'h18f; + sinelut[8'd200] = 12'h195; + sinelut[8'd201] = 12'h19b; + sinelut[8'd202] = 12'h1a2; + sinelut[8'd203] = 12'h1a9; + sinelut[8'd204] = 12'h1b0; + sinelut[8'd205] = 12'h1b7; + sinelut[8'd206] = 12'h1be; + sinelut[8'd207] = 12'h1c5; + sinelut[8'd208] = 12'h1cd; + sinelut[8'd209] = 12'h1d4; + sinelut[8'd210] = 12'h1dc; + sinelut[8'd211] = 12'h1e4; + sinelut[8'd212] = 12'h1ec; + sinelut[8'd213] = 12'h1f5; + sinelut[8'd214] = 12'h1fd; + sinelut[8'd215] = 12'h206; + sinelut[8'd216] = 12'h20f; + sinelut[8'd217] = 12'h218; + sinelut[8'd218] = 12'h222; + sinelut[8'd219] = 12'h22c; + sinelut[8'd220] = 12'h236; + sinelut[8'd221] = 12'h240; + sinelut[8'd222] = 12'h24b; + sinelut[8'd223] = 12'h256; + sinelut[8'd224] = 12'h261; + sinelut[8'd225] = 12'h26d; + sinelut[8'd226] = 12'h279; + sinelut[8'd227] = 12'h286; + sinelut[8'd228] = 12'h293; + sinelut[8'd229] = 12'h2a0; + sinelut[8'd230] = 12'h2af; + sinelut[8'd231] = 12'h2bd; + sinelut[8'd232] = 12'h2cd; + sinelut[8'd233] = 12'h2dc; + sinelut[8'd234] = 12'h2ed; + sinelut[8'd235] = 12'h2ff; + sinelut[8'd236] = 12'h311; + sinelut[8'd237] = 12'h324; + sinelut[8'd238] = 12'h339; + sinelut[8'd239] = 12'h34e; + sinelut[8'd240] = 12'h365; + sinelut[8'd241] = 12'h37e; + sinelut[8'd242] = 12'h398; + sinelut[8'd243] = 12'h3b5; + sinelut[8'd244] = 12'h3d3; + sinelut[8'd245] = 12'h3f5; + sinelut[8'd246] = 12'h41a; + sinelut[8'd247] = 12'h443; + sinelut[8'd248] = 12'h471; + sinelut[8'd249] = 12'h4a6; + sinelut[8'd250] = 12'h4e4; + sinelut[8'd251] = 12'h52e; + sinelut[8'd252] = 12'h58b; + sinelut[8'd253] = 12'h607; + sinelut[8'd254] = 12'h6c3; + sinelut[8'd255] = 12'h859; +end + + always @ (posedge clk) if(clk_en) + logsin <= sinelut[addr]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr.v new file mode 100644 index 0000000000000000000000000000000000000000..381b7c2b203f6f7d37e1f96e55952507ef7509fb --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr.v @@ -0,0 +1,532 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + */ + + +module jt12_mmr( + input rst, + input clk, + input cen /* synthesis direct_enable */, + output clk_en, + output clk_en_2, + output clk_en_ssg, + output clk_en_666, + output clk_en_111, + output clk_en_55, + input [7:0] din, + input write, + input [1:0] addr, + output reg busy, + output ch6op, + output [2:0] cur_ch, + output [1:0] cur_op, + // LFO + output reg [2:0] lfo_freq, + output reg lfo_en, + // Timers + output reg [9:0] value_A, + output reg [7:0] value_B, + output reg load_A, + output reg load_B, + output reg enable_irq_A, + output reg enable_irq_B, + output reg clr_flag_A, + output reg clr_flag_B, + output reg fast_timers, + input flag_A, + input overflow_A, + output reg [1:0] div_setting, + // PCM + output reg [8:0] pcm, + output reg pcm_en, + output reg pcm_wr, // high for one clock cycle when PCM is written + // ADPCM-A + output reg [ 7:0] aon_a, // ON + output reg [ 5:0] atl_a, // TL + output reg [16:0] addr_a, // address latch + output reg [ 7:0] lracl, // L/R ADPCM Channel Level + output reg up_start, // write enable start address latch + output reg up_end, // write enable end address latch + output reg [ 2:0] up_addr, // write enable end address latch + output reg [ 2:0] up_lracl, + output reg up_aon, // There was a write AON register + // ADPCM-B + output reg acmd_on_b, // Control - Process start, Key On + output reg acmd_rep_b, // Control - Repeat + output reg acmd_rst_b, // Control - Reset + output reg acmd_up_b, // Control - New cmd received + output reg [ 1:0] alr_b, // Left / Right + output reg [15:0] astart_b, // Start address + output reg [15:0] aend_b, // End address + output reg [15:0] adeltan_b, // Delta-N + output reg [ 7:0] aeg_b, // Envelope Generator Control + output reg [ 6:0] flag_ctl, + // Operator + output xuse_prevprev1, + output xuse_internal, + output yuse_internal, + output xuse_prev2, + output yuse_prev1, + output yuse_prev2, + // PG + output [10:0] fnum_I, + output [ 2:0] block_I, + output reg pg_stop, + // REG + output [ 1:0] rl, + output [ 2:0] fb_II, + output [ 2:0] alg_I, + output [ 2:0] pms_I, + output [ 1:0] ams_IV, + output amsen_IV, + output [ 2:0] dt1_I, + output [ 3:0] mul_II, + output [ 6:0] tl_IV, + output reg eg_stop, + + output [ 4:0] ar_I, + output [ 4:0] d1r_I, + output [ 4:0] d2r_I, + output [ 3:0] rr_I, + output [ 3:0] sl_I, + output [ 1:0] ks_II, + // SSG operation + output ssg_en_I, + output [2:0] ssg_eg_I, + + output keyon_I, + + // Operator + output zero, + output s1_enters, + output s2_enters, + output s3_enters, + output s4_enters, + + // PSG interace + output [3:0] psg_addr, + output [7:0] psg_data, + output reg psg_wr_n, + input [7:0] debug_bus +); + +parameter use_ssg=0, num_ch=6, use_pcm=1, use_adpcm=0, mask_div=1; + +jt12_div #(.use_ssg(use_ssg)) u_div ( + .rst ( rst ), + .clk ( clk ), + .cen ( cen ), + .div_setting ( div_setting ), + .clk_en ( clk_en ), + .clk_en_2 ( clk_en_2 ), + .clk_en_ssg ( clk_en_ssg ), + .clk_en_666 ( clk_en_666 ), + .clk_en_111 ( clk_en_111 ), + .clk_en_55 ( clk_en_55 ) +); + +reg [7:0] selected_register; + +/* +reg irq_zero_en, irq_brdy_en, irq_eos_en, + irq_tb_en, irq_ta_en; + */ +reg [6:0] up_opreg; // hot-one encoding. tells which operator register gets updated next +reg [2:0] up_chreg; // hot-one encoding. tells which channel register gets updated next +reg up_keyon; + +localparam REG_TESTYM = 8'h21, + REG_LFO = 8'h22, + REG_CLKA1 = 8'h24, + REG_CLKA2 = 8'h25, + REG_CLKB = 8'h26, + REG_TIMER = 8'h27, + REG_KON = 8'h28, + REG_IRQMASK = 8'h29, + REG_PCM = 8'h2A, + REG_PCM_EN = 8'h2B, + REG_DACTEST = 8'h2C, + REG_CLK_N6 = 8'h2D, + REG_CLK_N3 = 8'h2E, + REG_CLK_N2 = 8'h2F, + // ADPCM (YM2610) + REG_ADPCMA_ON = 8'h00, + REG_ADPCMA_TL = 8'h01, + REG_ADPCMA_TEST = 8'h02; + +reg csm, effect; + +reg [ 2:0] block_ch3op2, block_ch3op3, block_ch3op1; +reg [10:0] fnum_ch3op2, fnum_ch3op3, fnum_ch3op1; +reg [ 5:0] latch_fnum; + + +reg [2:0] up_ch; +reg [1:0] up_op; + +reg [7:0] op_din, ch_din; + +generate + if( use_ssg ) begin + assign psg_addr = selected_register[3:0]; + assign psg_data = ch_din; + end else begin + assign psg_addr = 4'd0; + assign psg_data = 8'd0; + end +endgenerate + +reg part; +reg [5:0] exbank; + +`ifdef SIMULATION +always @(posedge clk) if( write && rst ) begin + $display("WARNING [JT12]: detected write request while in reset.\nThis is likely a glue-logic error in the CPU-FM module."); + $finish; +end +`endif + +wire [2:0] ch_sel = {part, selected_register[1:0]}; + +// this runs at clk speed, no clock gating here +// if I try to make this an async rst it fails to map it +// as flip flops but uses latches instead. So I keep it as sync. reset +always @(posedge clk) begin : memory_mapped_registers + if( rst ) begin + selected_register <= 0; + div_setting <= 2'b10; // FM=1/6, SSG=1/4 + up_ch <= 0; + up_op <= 0; + up_keyon <= 0; + up_opreg <= 0; + up_chreg <= 0; + // IRQ Mask + /*{ irq_zero_en, irq_brdy_en, irq_eos_en, + irq_tb_en, irq_ta_en } = 5'h1f; */ + // timers + { value_A, value_B } <= 0; + { clr_flag_B, clr_flag_A, + enable_irq_B, enable_irq_A, load_B, load_A } <= 0; + fast_timers <= 0; + // LFO + lfo_freq <= 0; + lfo_en <= 0; + csm <= 0; + effect <= 0; + // PCM + pcm <= 0; + pcm_en <= 0; + pcm_wr <= 0; + // ADPCM-A + aon_a <= 0; + atl_a <= 0; + up_start <= 0; + up_end <= 0; + up_addr <= 7; + up_lracl <= 7; + up_aon <= 0; + lracl <= 0; + addr_a <= 0; + // ADPCM-B + acmd_on_b <= 0; + acmd_rep_b <= 0; + acmd_rst_b <= 0; + alr_b <= 0; + flag_ctl <= 0; + astart_b <= 0; + aend_b <= 0; + adeltan_b <= 0; + aeg_b <= 8'hff; + // Original test features + eg_stop <= 0; + pg_stop <= 0; + psg_wr_n <= 1; + // + { block_ch3op1, fnum_ch3op1 } <= {3'd0, 11'd0 }; + { block_ch3op3, fnum_ch3op3 } <= {3'd0, 11'd0 }; + { block_ch3op2, fnum_ch3op2 } <= {3'd0, 11'd0 }; + latch_fnum <= 0; + op_din <= 0; + part <= 0; + end else begin + up_chreg <= 0; + // WRITE IN REGISTERS + if( write ) begin + if( !addr[0] ) begin + selected_register <= din; + part <= addr[1]; + if (!mask_div) + case(din) + // clock divider: should work only for ym2203 + // and ym2608. + // clock divider works just by selecting the register + REG_CLK_N6: div_setting[1] <= 1'b1; // 2D + REG_CLK_N3: div_setting[0] <= 1'b1; // 2E + REG_CLK_N2: div_setting <= 2'b0; // 2F + default:; + endcase + end else if ( part == addr[1] ) begin + // Global registers + ch_din <= din; + if( selected_register == REG_KON && !part ) begin + up_keyon <= 1; + op_din <= din; + end else begin + up_keyon <= 0; + end + // General control (<0x20 registers and A0==0) + if(!part) begin + casez( selected_register) + //REG_TEST: lfo_rst <= 1'b1; // regardless of din + 8'h0?: psg_wr_n <= 1'b0; + REG_TESTYM: begin + eg_stop <= din[5]; + pg_stop <= din[3]; + fast_timers <= din[2]; + end + REG_CLKA1: value_A[9:2]<= din; + REG_CLKA2: value_A[1:0]<= din[1:0]; + REG_CLKB: value_B <= din; + REG_TIMER: begin + effect <= |din[7:6]; + csm <= din[7:6] == 2'b10; + { clr_flag_B, clr_flag_A, + enable_irq_B, enable_irq_A, + load_B, load_A } <= din[5:0]; + end + `ifndef NOLFO + REG_LFO: { lfo_en, lfo_freq } <= din[3:0]; + `endif + default:; + endcase + end + + // CH3 special registers + casez( selected_register) + 8'hA9: { block_ch3op1, fnum_ch3op1 } <= { latch_fnum, din }; + 8'hA8: { block_ch3op3, fnum_ch3op3 } <= { latch_fnum, din }; + 8'hAA: { block_ch3op2, fnum_ch3op2 } <= { latch_fnum, din }; + // According to http://www.mjsstuf.x10host.com/pages/vgmPlay/vgmPlay.htm + // There is a single fnum latch for all channels + 8'hA4, 8'hA5, 8'hA6, 8'hAD, 8'hAC, 8'hAE: latch_fnum <= din[5:0]; + default:; // avoid incomplete-case warning + endcase + + // YM2612 PCM support + if( use_pcm==1 ) begin + casez( selected_register) + REG_DACTEST: pcm[0] <= din[3]; + REG_PCM: + pcm <= { ~din[7], din[6:0], 1'b1 }; + REG_PCM_EN: pcm_en <= din[7]; + default:; + endcase + pcm_wr <= selected_register==REG_PCM; + end + if( use_adpcm==1 ) begin + // YM2610 ADPCM-A support, A1=1, regs 0-2D + if(part && selected_register[7:6]==2'b0) begin + casez( selected_register[5:0] ) + 6'h0: begin + aon_a <= din; + up_aon <= 1'b1; + end + 6'h1: atl_a <= din[5:0]; + // LRACL + 6'h8, 6'h9, 6'hA, 6'hB, 6'hC, 6'hD: begin + lracl <= din; + up_lracl <= selected_register[2:0]; + exbank[selected_register[2:0]] <= &din[7:4]; + end + 6'b01_????, 6'b10_????: begin + if( !selected_register[3] ) addr_a[ 7:0] <= din; + if( selected_register[3] ) addr_a[16:8] <= {exbank[selected_register[2:0]], din}; + case( selected_register[5:4] ) + 2'b01, 2'b10: begin + {up_end, up_start } <= selected_register[5:4]; + up_addr <= selected_register[2:0]; + end + default: begin + up_start <= 1'b0; + up_end <= 1'b0; + end + endcase + end + default:; + endcase + end + if( !part && selected_register[7:4]==4'h1 ) begin + // YM2610 ADPCM-B support, A1=0, regs 1x + case(selected_register[3:0]) + 4'd0: {acmd_up_b, acmd_on_b, acmd_rep_b,acmd_rst_b} <= {1'd1,din[7],din[4],din[0]}; + 4'd1: alr_b <= din[7:6]; + 4'd2: astart_b [ 7:0] <= din; + 4'd3: astart_b [15:8] <= din; + 4'd4: aend_b [ 7:0] <= din; + 4'd5: aend_b [15:8] <= din; + 4'h9: adeltan_b[ 7:0] <= din; + 4'ha: adeltan_b[15:8] <= din; + 4'hb: aeg_b <= din; + 4'hc: begin + flag_ctl <= {din[7],din[5:0]}; + end + default:; + endcase + end + end + if( selected_register[1:0]==2'b11 ) + { up_chreg, up_opreg } <= { 3'h0, 7'h0 }; + else begin + casez( selected_register ) + // channel registers + 8'hA0, 8'hA1, 8'hA2: { up_chreg, up_opreg } <= { 3'h1, 7'd0 }; // up_fnumlo + // FB + Algorithm + 8'hB0, 8'hB1, 8'hB2: { up_chreg, up_opreg } <= { 3'h2, 7'd0 }; // up_alg + 8'hB4, 8'hB5, 8'hB6: { up_chreg, up_opreg } <= { 3'h4, 7'd0 }; // up_pms + // operator registers + 8'h3?: { up_chreg, up_opreg } <= { 3'h0, 7'h01 }; // up_dt1 + 8'h4?: { up_chreg, up_opreg } <= { 3'h0, 7'h02 }; // up_tl + 8'h5?: { up_chreg, up_opreg } <= { 3'h0, 7'h04 }; // up_ks_ar + 8'h6?: { up_chreg, up_opreg } <= { 3'h0, 7'h08 }; // up_amen_dr + 8'h7?: { up_chreg, up_opreg } <= { 3'h0, 7'h10 }; // up_sr + 8'h8?: { up_chreg, up_opreg } <= { 3'h0, 7'h20 }; // up_sl + 8'h9?: { up_chreg, up_opreg } <= { 3'h0, 7'h40 }; // up_ssgeg + default: { up_chreg, up_opreg } <= { 3'h0, 7'h0 }; + endcase // selected_register + if( selected_register[7:4]>=3 && selected_register[7:4]<=9 ) begin + op_din <= din; + up_ch <= {part, selected_register[1:0]}; + up_op <= selected_register[3:2]; // 0=S1,1=S3,2=S2,3=S4 + end + end + end + end + else if(clk_en) begin /* clear once-only bits */ + // lfo_rst <= 1'b0; + { clr_flag_B, clr_flag_A } <= 2'd0; + psg_wr_n <= 1'b1; + pcm_wr <= 1'b0; + up_aon <= 1'b0; + acmd_up_b <= 1'b0; + end + end +end + +reg [4:0] busy_cnt; // busy lasts for 32 synthesizer clock cycles +wire [5:0] nx_busy = {1'd0,busy_cnt}+{5'd0,busy}; + +always @(posedge clk, posedge rst) begin + if( rst ) begin + busy <= 0; + busy_cnt <= 0; + end else begin + if( write&addr[0] ) begin + busy <= 1; + busy_cnt <= 0; + end else if(clk_en) begin + busy <= ~nx_busy[5] & busy; + busy_cnt <= nx_busy[4:0]; + end + end +end + +jt12_reg #(.num_ch(num_ch)) u_reg( + .rst ( rst ), + .clk ( clk ), // P1 + .clk_en ( clk_en ), + + // channel udpates + .ch_sel ( ch_sel ), + .ch_din ( ch_din ), + .up_fnumlo ( up_chreg[0] ), + .up_alg ( up_chreg[1] ), + .up_pms ( up_chreg[2] ), + + // operator updates + .din ( op_din ), + .up_keyon ( up_keyon ), + .up_dt1 ( up_opreg[0] ), + .up_tl ( up_opreg[1] ), + .up_ks_ar ( up_opreg[2] ), + .up_amen_dr ( up_opreg[3] ), + .up_sr ( up_opreg[4] ), + .up_sl_rr ( up_opreg[5] ), + .up_ssgeg ( up_opreg[6] ), + + .op ( up_op ), // operator to update + .ch ( up_ch ), // channel to update + + .csm ( csm ), + .flag_A ( flag_A ), + .overflow_A ( overflow_A), + + .ch6op ( ch6op ), + .cur_ch ( cur_ch ), + .cur_op ( cur_op ), + // CH3 Effect-mode operation + .effect ( effect ), // allows independent freq. for CH 3 + .fnum_ch3op2( fnum_ch3op2 ), + .fnum_ch3op3( fnum_ch3op3 ), + .fnum_ch3op1( fnum_ch3op1 ), + .block_ch3op2( block_ch3op2 ), + .block_ch3op3( block_ch3op3 ), + .block_ch3op1( block_ch3op1 ), + .latch_fnum ( latch_fnum ), + // Operator + .xuse_prevprev1 ( xuse_prevprev1 ), + .xuse_internal ( xuse_internal ), + .yuse_internal ( yuse_internal ), + .xuse_prev2 ( xuse_prev2 ), + .yuse_prev1 ( yuse_prev1 ), + .yuse_prev2 ( yuse_prev2 ), + // PG + .fnum_I ( fnum_I ), + .block_I ( block_I ), + .mul_II ( mul_II ), + .dt1_I ( dt1_I ), + + // EG + .ar_I (ar_I ), // attack rate + .d1r_I (d1r_I ), // decay rate + .d2r_I (d2r_I ), // sustain rate + .rr_I (rr_I ), // release rate + .sl_I (sl_I ), // sustain level + .ks_II (ks_II ), // key scale + // SSG operation + .ssg_en_I ( ssg_en_I ), + .ssg_eg_I ( ssg_eg_I ), + // envelope number + .tl_IV (tl_IV ), + .pms_I (pms_I ), + .ams_IV (ams_IV ), + .amsen_IV (amsen_IV ), + // channel configuration + .rl ( rl ), + .fb_II ( fb_II ), + .alg_I ( alg_I ), + .keyon_I ( keyon_I ), + + .zero ( zero ), + .s1_enters ( s1_enters ), + .s2_enters ( s2_enters ), + .s3_enters ( s3_enters ), + .s4_enters ( s4_enters ) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr_sim.vh b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr_sim.vh new file mode 100644 index 0000000000000000000000000000000000000000..96d60d8f176f9813e489b2905b770d74e77bd461 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mmr_sim.vh @@ -0,0 +1,854 @@ +`ifdef SIMULATION +/* verilator lint_off PINMISSING */ + +reg [4:0] sep24_cnt; +reg mmr_dump; + +always @(posedge clk ) if(clk_en) + sep24_cnt <= !zero ? sep24_cnt+1'b1 : 5'd0; + +wire [10:0] fnum_ch0s1, fnum_ch1s1, fnum_ch2s1, fnum_ch3s1, + fnum_ch4s1, fnum_ch5s1, fnum_ch0s2, fnum_ch1s2, + fnum_ch2s2, fnum_ch3s2, fnum_ch4s2, fnum_ch5s2, + fnum_ch0s3, fnum_ch1s3, fnum_ch2s3, fnum_ch3s3, + fnum_ch4s3, fnum_ch5s3, fnum_ch0s4, fnum_ch1s4, + fnum_ch2s4, fnum_ch3s4, fnum_ch4s4, fnum_ch5s4; + +sep24 #( .width(11), .pos0(1) ) fnum_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( fnum_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (fnum_ch0s1), + .ch1s1 (fnum_ch1s1), + .ch2s1 (fnum_ch2s1), + .ch3s1 (fnum_ch3s1), + .ch4s1 (fnum_ch4s1), + .ch5s1 (fnum_ch5s1), + + .ch0s2 (fnum_ch0s2), + .ch1s2 (fnum_ch1s2), + .ch2s2 (fnum_ch2s2), + .ch3s2 (fnum_ch3s2), + .ch4s2 (fnum_ch4s2), + .ch5s2 (fnum_ch5s2), + + .ch0s3 (fnum_ch0s3), + .ch1s3 (fnum_ch1s3), + .ch2s3 (fnum_ch2s3), + .ch3s3 (fnum_ch3s3), + .ch4s3 (fnum_ch4s3), + .ch5s3 (fnum_ch5s3), + + .ch0s4 (fnum_ch0s4), + .ch1s4 (fnum_ch1s4), + .ch2s4 (fnum_ch2s4), + .ch3s4 (fnum_ch3s4), + .ch4s4 (fnum_ch4s4), + .ch5s4 (fnum_ch5s4) +); + +wire [2:0] block_ch0s1, block_ch1s1, block_ch2s1, block_ch3s1, + block_ch4s1, block_ch5s1, block_ch0s2, block_ch1s2, + block_ch2s2, block_ch3s2, block_ch4s2, block_ch5s2, + block_ch0s3, block_ch1s3, block_ch2s3, block_ch3s3, + block_ch4s3, block_ch5s3, block_ch0s4, block_ch1s4, + block_ch2s4, block_ch3s4, block_ch4s4, block_ch5s4; + +sep24 #( .width(3), .pos0(1) ) block_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( block_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (block_ch0s1), + .ch1s1 (block_ch1s1), + .ch2s1 (block_ch2s1), + .ch3s1 (block_ch3s1), + .ch4s1 (block_ch4s1), + .ch5s1 (block_ch5s1), + + .ch0s2 (block_ch0s2), + .ch1s2 (block_ch1s2), + .ch2s2 (block_ch2s2), + .ch3s2 (block_ch3s2), + .ch4s2 (block_ch4s2), + .ch5s2 (block_ch5s2), + + .ch0s3 (block_ch0s3), + .ch1s3 (block_ch1s3), + .ch2s3 (block_ch2s3), + .ch3s3 (block_ch3s3), + .ch4s3 (block_ch4s3), + .ch5s3 (block_ch5s3), + + .ch0s4 (block_ch0s4), + .ch1s4 (block_ch1s4), + .ch2s4 (block_ch2s4), + .ch3s4 (block_ch3s4), + .ch4s4 (block_ch4s4), + .ch5s4 (block_ch5s4) +); + +wire [1:0] rl_ch0s1, rl_ch1s1, rl_ch2s1, rl_ch3s1, + rl_ch4s1, rl_ch5s1, rl_ch0s2, rl_ch1s2, + rl_ch2s2, rl_ch3s2, rl_ch4s2, rl_ch5s2, + rl_ch0s3, rl_ch1s3, rl_ch2s3, rl_ch3s3, + rl_ch4s3, rl_ch5s3, rl_ch0s4, rl_ch1s4, + rl_ch2s4, rl_ch3s4, rl_ch4s4, rl_ch5s4; + +sep24 #( .width(2), .pos0(1) ) rl_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( rl ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (rl_ch0s1), + .ch1s1 (rl_ch1s1), + .ch2s1 (rl_ch2s1), + .ch3s1 (rl_ch3s1), + .ch4s1 (rl_ch4s1), + .ch5s1 (rl_ch5s1), + + .ch0s2 (rl_ch0s2), + .ch1s2 (rl_ch1s2), + .ch2s2 (rl_ch2s2), + .ch3s2 (rl_ch3s2), + .ch4s2 (rl_ch4s2), + .ch5s2 (rl_ch5s2), + + .ch0s3 (rl_ch0s3), + .ch1s3 (rl_ch1s3), + .ch2s3 (rl_ch2s3), + .ch3s3 (rl_ch3s3), + .ch4s3 (rl_ch4s3), + .ch5s3 (rl_ch5s3), + + .ch0s4 (rl_ch0s4), + .ch1s4 (rl_ch1s4), + .ch2s4 (rl_ch2s4), + .ch3s4 (rl_ch3s4), + .ch4s4 (rl_ch4s4), + .ch5s4 (rl_ch5s4) +); + +wire [2:0] fb_ch0s1, fb_ch1s1, fb_ch2s1, fb_ch3s1, + fb_ch4s1, fb_ch5s1, fb_ch0s2, fb_ch1s2, + fb_ch2s2, fb_ch3s2, fb_ch4s2, fb_ch5s2, + fb_ch0s3, fb_ch1s3, fb_ch2s3, fb_ch3s3, + fb_ch4s3, fb_ch5s3, fb_ch0s4, fb_ch1s4, + fb_ch2s4, fb_ch3s4, fb_ch4s4, fb_ch5s4; + +sep24 #( .width(3), .pos0(0) ) fb_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( fb_II ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (fb_ch0s1), + .ch1s1 (fb_ch1s1), + .ch2s1 (fb_ch2s1), + .ch3s1 (fb_ch3s1), + .ch4s1 (fb_ch4s1), + .ch5s1 (fb_ch5s1), + + .ch0s2 (fb_ch0s2), + .ch1s2 (fb_ch1s2), + .ch2s2 (fb_ch2s2), + .ch3s2 (fb_ch3s2), + .ch4s2 (fb_ch4s2), + .ch5s2 (fb_ch5s2), + + .ch0s3 (fb_ch0s3), + .ch1s3 (fb_ch1s3), + .ch2s3 (fb_ch2s3), + .ch3s3 (fb_ch3s3), + .ch4s3 (fb_ch4s3), + .ch5s3 (fb_ch5s3), + + .ch0s4 (fb_ch0s4), + .ch1s4 (fb_ch1s4), + .ch2s4 (fb_ch2s4), + .ch3s4 (fb_ch3s4), + .ch4s4 (fb_ch4s4), + .ch5s4 (fb_ch5s4) +); + +wire [2:0] alg_ch0s1, alg_ch1s1, alg_ch2s1, alg_ch3s1, + alg_ch4s1, alg_ch5s1, alg_ch0s2, alg_ch1s2, + alg_ch2s2, alg_ch3s2, alg_ch4s2, alg_ch5s2, + alg_ch0s3, alg_ch1s3, alg_ch2s3, alg_ch3s3, + alg_ch4s3, alg_ch5s3, alg_ch0s4, alg_ch1s4, + alg_ch2s4, alg_ch3s4, alg_ch4s4, alg_ch5s4; + +sep24 #( .width(3), .pos0(1) ) alg_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( alg ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (alg_ch0s1), + .ch1s1 (alg_ch1s1), + .ch2s1 (alg_ch2s1), + .ch3s1 (alg_ch3s1), + .ch4s1 (alg_ch4s1), + .ch5s1 (alg_ch5s1), + + .ch0s2 (alg_ch0s2), + .ch1s2 (alg_ch1s2), + .ch2s2 (alg_ch2s2), + .ch3s2 (alg_ch3s2), + .ch4s2 (alg_ch4s2), + .ch5s2 (alg_ch5s2), + + .ch0s3 (alg_ch0s3), + .ch1s3 (alg_ch1s3), + .ch2s3 (alg_ch2s3), + .ch3s3 (alg_ch3s3), + .ch4s3 (alg_ch4s3), + .ch5s3 (alg_ch5s3), + + .ch0s4 (alg_ch0s4), + .ch1s4 (alg_ch1s4), + .ch2s4 (alg_ch2s4), + .ch3s4 (alg_ch3s4), + .ch4s4 (alg_ch4s4), + .ch5s4 (alg_ch5s4) +); + +wire [2:0] dt1_ch0s1, dt1_ch1s1, dt1_ch2s1, dt1_ch3s1, + dt1_ch4s1, dt1_ch5s1, dt1_ch0s2, dt1_ch1s2, + dt1_ch2s2, dt1_ch3s2, dt1_ch4s2, dt1_ch5s2, + dt1_ch0s3, dt1_ch1s3, dt1_ch2s3, dt1_ch3s3, + dt1_ch4s3, dt1_ch5s3, dt1_ch0s4, dt1_ch1s4, + dt1_ch2s4, dt1_ch3s4, dt1_ch4s4, dt1_ch5s4; + +sep24 #( .width(3), .pos0(0) ) dt1_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( dt1_II ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (dt1_ch0s1), + .ch1s1 (dt1_ch1s1), + .ch2s1 (dt1_ch2s1), + .ch3s1 (dt1_ch3s1), + .ch4s1 (dt1_ch4s1), + .ch5s1 (dt1_ch5s1), + + .ch0s2 (dt1_ch0s2), + .ch1s2 (dt1_ch1s2), + .ch2s2 (dt1_ch2s2), + .ch3s2 (dt1_ch3s2), + .ch4s2 (dt1_ch4s2), + .ch5s2 (dt1_ch5s2), + + .ch0s3 (dt1_ch0s3), + .ch1s3 (dt1_ch1s3), + .ch2s3 (dt1_ch2s3), + .ch3s3 (dt1_ch3s3), + .ch4s3 (dt1_ch4s3), + .ch5s3 (dt1_ch5s3), + + .ch0s4 (dt1_ch0s4), + .ch1s4 (dt1_ch1s4), + .ch2s4 (dt1_ch2s4), + .ch3s4 (dt1_ch3s4), + .ch4s4 (dt1_ch4s4), + .ch5s4 (dt1_ch5s4) +); + +wire [3:0] mul_ch0s1, mul_ch1s1, mul_ch2s1, mul_ch3s1, + mul_ch4s1, mul_ch5s1, mul_ch0s2, mul_ch1s2, + mul_ch2s2, mul_ch3s2, mul_ch4s2, mul_ch5s2, + mul_ch0s3, mul_ch1s3, mul_ch2s3, mul_ch3s3, + mul_ch4s3, mul_ch5s3, mul_ch0s4, mul_ch1s4, + mul_ch2s4, mul_ch3s4, mul_ch4s4, mul_ch5s4; + +sep24 #( .width(4), .pos0(21) ) mul_sep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( mul_V ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (mul_ch0s1), + .ch1s1 (mul_ch1s1), + .ch2s1 (mul_ch2s1), + .ch3s1 (mul_ch3s1), + .ch4s1 (mul_ch4s1), + .ch5s1 (mul_ch5s1), + + .ch0s2 (mul_ch0s2), + .ch1s2 (mul_ch1s2), + .ch2s2 (mul_ch2s2), + .ch3s2 (mul_ch3s2), + .ch4s2 (mul_ch4s2), + .ch5s2 (mul_ch5s2), + + .ch0s3 (mul_ch0s3), + .ch1s3 (mul_ch1s3), + .ch2s3 (mul_ch2s3), + .ch3s3 (mul_ch3s3), + .ch4s3 (mul_ch4s3), + .ch5s3 (mul_ch5s3), + + .ch0s4 (mul_ch0s4), + .ch1s4 (mul_ch1s4), + .ch2s4 (mul_ch2s4), + .ch3s4 (mul_ch3s4), + .ch4s4 (mul_ch4s4), + .ch5s4 (mul_ch5s4) +); + +wire [6:0] tl_ch0s1, tl_ch1s1, tl_ch2s1, tl_ch3s1, + tl_ch4s1, tl_ch5s1, tl_ch0s2, tl_ch1s2, + tl_ch2s2, tl_ch3s2, tl_ch4s2, tl_ch5s2, + tl_ch0s3, tl_ch1s3, tl_ch2s3, tl_ch3s3, + tl_ch4s3, tl_ch5s3, tl_ch0s4, tl_ch1s4, + tl_ch2s4, tl_ch3s4, tl_ch4s4, tl_ch5s4; + +sep24 #( .width(7), .pos0(22) ) tl_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( tl_IV ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (tl_ch0s1), + .ch1s1 (tl_ch1s1), + .ch2s1 (tl_ch2s1), + .ch3s1 (tl_ch3s1), + .ch4s1 (tl_ch4s1), + .ch5s1 (tl_ch5s1), + + .ch0s2 (tl_ch0s2), + .ch1s2 (tl_ch1s2), + .ch2s2 (tl_ch2s2), + .ch3s2 (tl_ch3s2), + .ch4s2 (tl_ch4s2), + .ch5s2 (tl_ch5s2), + + .ch0s3 (tl_ch0s3), + .ch1s3 (tl_ch1s3), + .ch2s3 (tl_ch2s3), + .ch3s3 (tl_ch3s3), + .ch4s3 (tl_ch4s3), + .ch5s3 (tl_ch5s3), + + .ch0s4 (tl_ch0s4), + .ch1s4 (tl_ch1s4), + .ch2s4 (tl_ch2s4), + .ch3s4 (tl_ch3s4), + .ch4s4 (tl_ch4s4), + .ch5s4 (tl_ch5s4) +); + +wire [4:0] ar_ch0s1, ar_ch1s1, ar_ch2s1, ar_ch3s1, + ar_ch4s1, ar_ch5s1, ar_ch0s2, ar_ch1s2, + ar_ch2s2, ar_ch3s2, ar_ch4s2, ar_ch5s2, + ar_ch0s3, ar_ch1s3, ar_ch2s3, ar_ch3s3, + ar_ch4s3, ar_ch5s3, ar_ch0s4, ar_ch1s4, + ar_ch2s4, ar_ch3s4, ar_ch4s4, ar_ch5s4; + +sep24 #( .width(5), .pos0(1) ) ar_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( ar_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (ar_ch0s1), + .ch1s1 (ar_ch1s1), + .ch2s1 (ar_ch2s1), + .ch3s1 (ar_ch3s1), + .ch4s1 (ar_ch4s1), + .ch5s1 (ar_ch5s1), + + .ch0s2 (ar_ch0s2), + .ch1s2 (ar_ch1s2), + .ch2s2 (ar_ch2s2), + .ch3s2 (ar_ch3s2), + .ch4s2 (ar_ch4s2), + .ch5s2 (ar_ch5s2), + + .ch0s3 (ar_ch0s3), + .ch1s3 (ar_ch1s3), + .ch2s3 (ar_ch2s3), + .ch3s3 (ar_ch3s3), + .ch4s3 (ar_ch4s3), + .ch5s3 (ar_ch5s3), + + .ch0s4 (ar_ch0s4), + .ch1s4 (ar_ch1s4), + .ch2s4 (ar_ch2s4), + .ch3s4 (ar_ch3s4), + .ch4s4 (ar_ch4s4), + .ch5s4 (ar_ch5s4) +); + +wire [4:0] d1r_ch0s1, d1r_ch1s1, d1r_ch2s1, d1r_ch3s1, + d1r_ch4s1, d1r_ch5s1, d1r_ch0s2, d1r_ch1s2, + d1r_ch2s2, d1r_ch3s2, d1r_ch4s2, d1r_ch5s2, + d1r_ch0s3, d1r_ch1s3, d1r_ch2s3, d1r_ch3s3, + d1r_ch4s3, d1r_ch5s3, d1r_ch0s4, d1r_ch1s4, + d1r_ch2s4, d1r_ch3s4, d1r_ch4s4, d1r_ch5s4; + +sep24 #( .width(5), .pos0(1) ) d1r_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( d1r_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (d1r_ch0s1), + .ch1s1 (d1r_ch1s1), + .ch2s1 (d1r_ch2s1), + .ch3s1 (d1r_ch3s1), + .ch4s1 (d1r_ch4s1), + .ch5s1 (d1r_ch5s1), + + .ch0s2 (d1r_ch0s2), + .ch1s2 (d1r_ch1s2), + .ch2s2 (d1r_ch2s2), + .ch3s2 (d1r_ch3s2), + .ch4s2 (d1r_ch4s2), + .ch5s2 (d1r_ch5s2), + + .ch0s3 (d1r_ch0s3), + .ch1s3 (d1r_ch1s3), + .ch2s3 (d1r_ch2s3), + .ch3s3 (d1r_ch3s3), + .ch4s3 (d1r_ch4s3), + .ch5s3 (d1r_ch5s3), + + .ch0s4 (d1r_ch0s4), + .ch1s4 (d1r_ch1s4), + .ch2s4 (d1r_ch2s4), + .ch3s4 (d1r_ch3s4), + .ch4s4 (d1r_ch4s4), + .ch5s4 (d1r_ch5s4) +); + +wire [4:0] d2r_ch0s1, d2r_ch1s1, d2r_ch2s1, d2r_ch3s1, + d2r_ch4s1, d2r_ch5s1, d2r_ch0s2, d2r_ch1s2, + d2r_ch2s2, d2r_ch3s2, d2r_ch4s2, d2r_ch5s2, + d2r_ch0s3, d2r_ch1s3, d2r_ch2s3, d2r_ch3s3, + d2r_ch4s3, d2r_ch5s3, d2r_ch0s4, d2r_ch1s4, + d2r_ch2s4, d2r_ch3s4, d2r_ch4s4, d2r_ch5s4; + +sep24 #( .width(5), .pos0(1) ) d2r_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( d2r_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (d2r_ch0s1), + .ch1s1 (d2r_ch1s1), + .ch2s1 (d2r_ch2s1), + .ch3s1 (d2r_ch3s1), + .ch4s1 (d2r_ch4s1), + .ch5s1 (d2r_ch5s1), + + .ch0s2 (d2r_ch0s2), + .ch1s2 (d2r_ch1s2), + .ch2s2 (d2r_ch2s2), + .ch3s2 (d2r_ch3s2), + .ch4s2 (d2r_ch4s2), + .ch5s2 (d2r_ch5s2), + + .ch0s3 (d2r_ch0s3), + .ch1s3 (d2r_ch1s3), + .ch2s3 (d2r_ch2s3), + .ch3s3 (d2r_ch3s3), + .ch4s3 (d2r_ch4s3), + .ch5s3 (d2r_ch5s3), + + .ch0s4 (d2r_ch0s4), + .ch1s4 (d2r_ch1s4), + .ch2s4 (d2r_ch2s4), + .ch3s4 (d2r_ch3s4), + .ch4s4 (d2r_ch4s4), + .ch5s4 (d2r_ch5s4) +); + +wire [3:0] rr_ch0s1, rr_ch1s1, rr_ch2s1, rr_ch3s1, + rr_ch4s1, rr_ch5s1, rr_ch0s2, rr_ch1s2, + rr_ch2s2, rr_ch3s2, rr_ch4s2, rr_ch5s2, + rr_ch0s3, rr_ch1s3, rr_ch2s3, rr_ch3s3, + rr_ch4s3, rr_ch5s3, rr_ch0s4, rr_ch1s4, + rr_ch2s4, rr_ch3s4, rr_ch4s4, rr_ch5s4; + +sep24 #( .width(4), .pos0(1) ) rr_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( rr_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (rr_ch0s1), + .ch1s1 (rr_ch1s1), + .ch2s1 (rr_ch2s1), + .ch3s1 (rr_ch3s1), + .ch4s1 (rr_ch4s1), + .ch5s1 (rr_ch5s1), + + .ch0s2 (rr_ch0s2), + .ch1s2 (rr_ch1s2), + .ch2s2 (rr_ch2s2), + .ch3s2 (rr_ch3s2), + .ch4s2 (rr_ch4s2), + .ch5s2 (rr_ch5s2), + + .ch0s3 (rr_ch0s3), + .ch1s3 (rr_ch1s3), + .ch2s3 (rr_ch2s3), + .ch3s3 (rr_ch3s3), + .ch4s3 (rr_ch4s3), + .ch5s3 (rr_ch5s3), + + .ch0s4 (rr_ch0s4), + .ch1s4 (rr_ch1s4), + .ch2s4 (rr_ch2s4), + .ch3s4 (rr_ch3s4), + .ch4s4 (rr_ch4s4), + .ch5s4 (rr_ch5s4) +); + +wire [3:0] d1l_ch0s1, d1l_ch1s1, d1l_ch2s1, d1l_ch3s1, + d1l_ch4s1, d1l_ch5s1, d1l_ch0s2, d1l_ch1s2, + d1l_ch2s2, d1l_ch3s2, d1l_ch4s2, d1l_ch5s2, + d1l_ch0s3, d1l_ch1s3, d1l_ch2s3, d1l_ch3s3, + d1l_ch4s3, d1l_ch5s3, d1l_ch0s4, d1l_ch1s4, + d1l_ch2s4, d1l_ch3s4, d1l_ch4s4, d1l_ch5s4; + +sep24 #( .width(4), .pos0(1) ) d1l_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( sl_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (d1l_ch0s1), + .ch1s1 (d1l_ch1s1), + .ch2s1 (d1l_ch2s1), + .ch3s1 (d1l_ch3s1), + .ch4s1 (d1l_ch4s1), + .ch5s1 (d1l_ch5s1), + + .ch0s2 (d1l_ch0s2), + .ch1s2 (d1l_ch1s2), + .ch2s2 (d1l_ch2s2), + .ch3s2 (d1l_ch3s2), + .ch4s2 (d1l_ch4s2), + .ch5s2 (d1l_ch5s2), + + .ch0s3 (d1l_ch0s3), + .ch1s3 (d1l_ch1s3), + .ch2s3 (d1l_ch2s3), + .ch3s3 (d1l_ch3s3), + .ch4s3 (d1l_ch4s3), + .ch5s3 (d1l_ch5s3), + + .ch0s4 (d1l_ch0s4), + .ch1s4 (d1l_ch1s4), + .ch2s4 (d1l_ch2s4), + .ch3s4 (d1l_ch3s4), + .ch4s4 (d1l_ch4s4), + .ch5s4 (d1l_ch5s4) +); + +wire [1:0] ks_ch0s1, ks_ch1s1, ks_ch2s1, ks_ch3s1, + ks_ch4s1, ks_ch5s1, ks_ch0s2, ks_ch1s2, + ks_ch2s2, ks_ch3s2, ks_ch4s2, ks_ch5s2, + ks_ch0s3, ks_ch1s3, ks_ch2s3, ks_ch3s3, + ks_ch4s3, ks_ch5s3, ks_ch0s4, ks_ch1s4, + ks_ch2s4, ks_ch3s4, ks_ch4s4, ks_ch5s4; + +sep24 #( .width(2), .pos0(0) ) ks_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( ks_II ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (ks_ch0s1), + .ch1s1 (ks_ch1s1), + .ch2s1 (ks_ch2s1), + .ch3s1 (ks_ch3s1), + .ch4s1 (ks_ch4s1), + .ch5s1 (ks_ch5s1), + + .ch0s2 (ks_ch0s2), + .ch1s2 (ks_ch1s2), + .ch2s2 (ks_ch2s2), + .ch3s2 (ks_ch3s2), + .ch4s2 (ks_ch4s2), + .ch5s2 (ks_ch5s2), + + .ch0s3 (ks_ch0s3), + .ch1s3 (ks_ch1s3), + .ch2s3 (ks_ch2s3), + .ch3s3 (ks_ch3s3), + .ch4s3 (ks_ch4s3), + .ch5s3 (ks_ch5s3), + + .ch0s4 (ks_ch0s4), + .ch1s4 (ks_ch1s4), + .ch2s4 (ks_ch2s4), + .ch3s4 (ks_ch3s4), + .ch4s4 (ks_ch4s4), + .ch5s4 (ks_ch5s4) +); + +wire [3:0] ssg_I = {ssg_en_I, ssg_eg_I}; + +wire [3:0] ssg_ch0s1, ssg_ch1s1, ssg_ch2s1, ssg_ch3s1, + ssg_ch4s1, ssg_ch5s1, ssg_ch0s2, ssg_ch1s2, + ssg_ch2s2, ssg_ch3s2, ssg_ch4s2, ssg_ch5s2, + ssg_ch0s3, ssg_ch1s3, ssg_ch2s3, ssg_ch3s3, + ssg_ch4s3, ssg_ch5s3, ssg_ch0s4, ssg_ch1s4, + ssg_ch2s4, ssg_ch3s4, ssg_ch4s4, ssg_ch5s4; + +sep24 #( .width(4), .pos0(1) ) ssg_step +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( ssg_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (ssg_ch0s1), + .ch1s1 (ssg_ch1s1), + .ch2s1 (ssg_ch2s1), + .ch3s1 (ssg_ch3s1), + .ch4s1 (ssg_ch4s1), + .ch5s1 (ssg_ch5s1), + + .ch0s2 (ssg_ch0s2), + .ch1s2 (ssg_ch1s2), + .ch2s2 (ssg_ch2s2), + .ch3s2 (ssg_ch3s2), + .ch4s2 (ssg_ch4s2), + .ch5s2 (ssg_ch5s2), + + .ch0s3 (ssg_ch0s3), + .ch1s3 (ssg_ch1s3), + .ch2s3 (ssg_ch2s3), + .ch3s3 (ssg_ch3s3), + .ch4s3 (ssg_ch4s3), + .ch5s3 (ssg_ch5s3), + + .ch0s4 (ssg_ch0s4), + .ch1s4 (ssg_ch1s4), + .ch2s4 (ssg_ch2s4), + .ch3s4 (ssg_ch3s4), + .ch4s4 (ssg_ch4s4), + .ch5s4 (ssg_ch5s4) +); + +wire kon_ch0s1, kon_ch1s1, kon_ch2s1, kon_ch3s1, + kon_ch4s1, kon_ch5s1, kon_ch0s2, kon_ch1s2, + kon_ch2s2, kon_ch3s2, kon_ch4s2, kon_ch5s2, + kon_ch0s3, kon_ch1s3, kon_ch2s3, kon_ch3s3, + kon_ch4s3, kon_ch5s3, kon_ch0s4, kon_ch1s4, + kon_ch2s4, kon_ch3s4, kon_ch4s4, kon_ch5s4; + +sep24 #( .width(1), .pos0(1) ) konstep +( + .clk ( clk ), + .clk_en ( clk_en ), + .mixed ( keyon_I ), + .mask ( 24'd0 ), + .cnt ( sep24_cnt ), + + .ch0s1 (kon_ch0s1), + .ch1s1 (kon_ch1s1), + .ch2s1 (kon_ch2s1), + .ch3s1 (kon_ch3s1), + .ch4s1 (kon_ch4s1), + .ch5s1 (kon_ch5s1), + + .ch0s2 (kon_ch0s2), + .ch1s2 (kon_ch1s2), + .ch2s2 (kon_ch2s2), + .ch3s2 (kon_ch3s2), + .ch4s2 (kon_ch4s2), + .ch5s2 (kon_ch5s2), + + .ch0s3 (kon_ch0s3), + .ch1s3 (kon_ch1s3), + .ch2s3 (kon_ch2s3), + .ch3s3 (kon_ch3s3), + .ch4s3 (kon_ch4s3), + .ch5s3 (kon_ch5s3), + + .ch0s4 (kon_ch0s4), + .ch1s4 (kon_ch1s4), + .ch2s4 (kon_ch2s4), + .ch3s4 (kon_ch3s4), + .ch4s4 (kon_ch4s4), + .ch5s4 (kon_ch5s4) +); + +/* Dump all registers on request */ +integer fmmr; +initial begin + fmmr=$fopen("mmr_dump.log","w"); +end + +always @(posedge clk ) +if (mmr_dump ) begin + $fdisplay( fmmr, "-------------------------------"); + // Channel 0 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch0s1, fnum_ch0s1, rl_ch0s1, fb_ch0s1, alg_ch0s1, + dt1_ch0s1, mul_ch0s1, tl_ch0s1, ar_ch0s1, d1r_ch0s1, + d2r_ch0s1, rr_ch0s1, d1l_ch0s1, ks_ch0s1, ssg_ch0s1, + kon_ch0s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch0s2, fnum_ch0s2, rl_ch0s2, fb_ch0s2, alg_ch0s2, + dt1_ch0s2, mul_ch0s2, tl_ch0s2, ar_ch0s2, d1r_ch0s2, + d2r_ch0s2, rr_ch0s2, d1l_ch0s2, ks_ch0s2, ssg_ch0s2, + kon_ch0s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch0s1, fnum_ch0s3, rl_ch0s3, fb_ch0s3, alg_ch0s3, + dt1_ch0s3, mul_ch0s3, tl_ch0s3, ar_ch0s3, d1r_ch0s3, + d2r_ch0s3, rr_ch0s3, d1l_ch0s3, ks_ch0s3, ssg_ch0s3, + kon_ch0s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch0s4, fnum_ch0s4, rl_ch0s4, fb_ch0s4, alg_ch0s4, + dt1_ch0s4, mul_ch0s4, tl_ch0s4, ar_ch0s4, d1r_ch0s4, + d2r_ch0s4, rr_ch0s4, d1l_ch0s4, ks_ch0s4, ssg_ch0s4, + kon_ch0s4 ); + // Channel 1 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch1s1, fnum_ch1s1, rl_ch1s1, fb_ch1s1, alg_ch1s1, + dt1_ch1s1, mul_ch1s1, tl_ch1s1, ar_ch1s1, d1r_ch1s1, + d2r_ch1s1, rr_ch1s1, d1l_ch1s1, ks_ch1s1, ssg_ch1s1, + kon_ch1s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch1s2, fnum_ch1s2, rl_ch1s2, fb_ch1s2, alg_ch1s2, + dt1_ch1s2, mul_ch1s2, tl_ch1s2, ar_ch1s2, d1r_ch1s2, + d2r_ch1s2, rr_ch1s2, d1l_ch1s2, ks_ch1s2, ssg_ch1s2, + kon_ch1s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch1s3, fnum_ch1s3, rl_ch1s3, fb_ch1s3, alg_ch1s3, + dt1_ch1s3, mul_ch1s3, tl_ch1s3, ar_ch1s3, d1r_ch1s3, + d2r_ch1s3, rr_ch1s3, d1l_ch1s3, ks_ch1s3, ssg_ch1s3, + kon_ch1s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch1s4, fnum_ch1s4, rl_ch1s4, fb_ch1s4, alg_ch1s4, + dt1_ch1s4, mul_ch1s4, tl_ch1s4, ar_ch1s4, d1r_ch1s4, + d2r_ch1s4, rr_ch1s4, d1l_ch1s4, ks_ch1s4, ssg_ch1s4, + kon_ch1s4 ); + // Channel 2 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch2s1, fnum_ch2s1, rl_ch2s1, fb_ch2s1, alg_ch2s1, + dt1_ch2s1, mul_ch2s1, tl_ch2s1, ar_ch2s1, d1r_ch2s1, + d2r_ch2s1, rr_ch2s1, d1l_ch2s1, ks_ch2s1, ssg_ch2s1, + kon_ch2s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch2s2, fnum_ch2s2, rl_ch2s2, fb_ch2s2, alg_ch2s2, + dt1_ch2s2, mul_ch2s2, tl_ch2s2, ar_ch2s2, d1r_ch2s2, + d2r_ch2s2, rr_ch2s2, d1l_ch2s2, ks_ch2s2, ssg_ch2s2, + kon_ch2s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch2s3, fnum_ch2s3, rl_ch2s3, fb_ch2s3, alg_ch2s3, + dt1_ch2s3, mul_ch2s3, tl_ch2s3, ar_ch2s3, d1r_ch2s3, + d2r_ch2s3, rr_ch2s3, d1l_ch2s3, ks_ch2s3, ssg_ch2s3, + kon_ch2s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch2s4, fnum_ch2s4, rl_ch2s4, fb_ch2s4, alg_ch2s4, + dt1_ch2s4, mul_ch2s4, tl_ch2s4, ar_ch2s4, d1r_ch2s4, + d2r_ch2s4, rr_ch2s4, d1l_ch2s4, ks_ch2s4, ssg_ch2s4, + kon_ch2s4 ); + // Channel 3 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch3s1, fnum_ch3s1, rl_ch3s1, fb_ch3s1, alg_ch3s1, + dt1_ch3s1, mul_ch3s1, tl_ch3s1, ar_ch3s1, d1r_ch3s1, + d2r_ch3s1, rr_ch3s1, d1l_ch3s1, ks_ch3s1, ssg_ch3s1, + kon_ch3s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch3s2, fnum_ch3s2, rl_ch3s2, fb_ch3s2, alg_ch3s2, + dt1_ch3s2, mul_ch3s2, tl_ch3s2, ar_ch3s2, d1r_ch3s2, + d2r_ch3s2, rr_ch3s2, d1l_ch3s2, ks_ch3s2, ssg_ch3s2, + kon_ch3s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch3s3, fnum_ch3s3, rl_ch3s3, fb_ch3s3, alg_ch3s3, + dt1_ch3s3, mul_ch3s3, tl_ch3s3, ar_ch3s3, d1r_ch3s3, + d2r_ch3s3, rr_ch3s3, d1l_ch3s3, ks_ch3s3, ssg_ch3s3, + kon_ch3s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch3s4, fnum_ch3s4, rl_ch3s4, fb_ch3s4, alg_ch3s4, + dt1_ch3s4, mul_ch3s4, tl_ch3s4, ar_ch3s4, d1r_ch3s4, + d2r_ch3s4, rr_ch3s4, d1l_ch3s4, ks_ch3s4, ssg_ch3s4, + kon_ch3s4 ); + // Channel 4 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch4s1, fnum_ch4s1, rl_ch4s1, fb_ch4s1, alg_ch4s1, + dt1_ch4s1, mul_ch4s1, tl_ch4s1, ar_ch4s1, d1r_ch4s1, + d2r_ch4s1, rr_ch4s1, d1l_ch4s1, ks_ch4s1, ssg_ch4s1, + kon_ch4s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch4s2, fnum_ch4s2, rl_ch4s2, fb_ch4s2, alg_ch4s2, + dt1_ch4s2, mul_ch4s2, tl_ch4s2, ar_ch4s2, d1r_ch4s2, + d2r_ch4s2, rr_ch4s2, d1l_ch4s2, ks_ch4s2, ssg_ch4s2, + kon_ch4s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch4s3, fnum_ch4s3, rl_ch4s3, fb_ch4s3, alg_ch4s3, + dt1_ch4s3, mul_ch4s3, tl_ch4s3, ar_ch4s3, d1r_ch4s3, + d2r_ch4s3, rr_ch4s3, d1l_ch4s3, ks_ch4s3, ssg_ch4s3, + kon_ch4s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch4s4, fnum_ch4s4, rl_ch4s4, fb_ch4s4, alg_ch4s4, + dt1_ch4s4, mul_ch4s4, tl_ch4s4, ar_ch4s4, d1r_ch4s4, + d2r_ch4s4, rr_ch4s4, d1l_ch4s4, ks_ch4s4, ssg_ch4s4, + kon_ch4s4 ); + // Channel 5 + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch5s1, fnum_ch5s1, rl_ch5s1, fb_ch5s1, alg_ch5s1, + dt1_ch5s1, mul_ch5s1, tl_ch5s1, ar_ch5s1, d1r_ch5s1, + d2r_ch5s1, rr_ch5s1, d1l_ch5s1, ks_ch5s1, ssg_ch5s1, + kon_ch5s1 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch5s2, fnum_ch5s2, rl_ch5s2, fb_ch5s2, alg_ch5s2, + dt1_ch5s2, mul_ch5s2, tl_ch5s2, ar_ch5s2, d1r_ch5s2, + d2r_ch5s2, rr_ch5s2, d1l_ch5s2, ks_ch5s2, ssg_ch5s2, + kon_ch5s2 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch5s3, fnum_ch5s3, rl_ch5s3, fb_ch5s3, alg_ch5s3, + dt1_ch5s3, mul_ch5s3, tl_ch5s3, ar_ch5s3, d1r_ch5s3, + d2r_ch5s3, rr_ch5s3, d1l_ch5s3, ks_ch5s3, ssg_ch5s3, + kon_ch5s3 ); + $fdisplay( fmmr, "%x %x %x %x %x, %x %x %x %x %x %x, %x %x %x %x %x", + block_ch5s4, fnum_ch5s4, rl_ch5s4, fb_ch5s4, alg_ch5s4, + dt1_ch5s4, mul_ch5s4, tl_ch5s4, ar_ch5s4, d1r_ch5s4, + d2r_ch5s4, rr_ch5s4, d1l_ch5s4, ks_ch5s4, ssg_ch5s4, + kon_ch5s4 ); +end +/* verilator lint_on PINMISSING */ +`endif + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mod.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mod.v new file mode 100644 index 0000000000000000000000000000000000000000..2e7bef38fa0404580a26aeee8112dfd869a0e7e5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_mod.v @@ -0,0 +1,152 @@ + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +module jt12_mod( + input s1_enters, + input s2_enters, + input s3_enters, + input s4_enters, + + input [2:0] alg_I, + + output reg xuse_prevprev1, + output reg xuse_internal, + output reg yuse_internal, + output reg xuse_prev2, + output reg yuse_prev1, + output reg yuse_prev2 +); + +parameter num_ch=6; + +reg [7:0] alg_hot; + +always @(*) begin + case( alg_I ) + 3'd0: alg_hot = 8'h1; // D0 + 3'd1: alg_hot = 8'h2; // D1 + 3'd2: alg_hot = 8'h4; // D2 + 3'd3: alg_hot = 8'h8; // D3 + 3'd4: alg_hot = 8'h10; // D4 + 3'd5: alg_hot = 8'h20; // D5 + 3'd6: alg_hot = 8'h40; // D6 + 3'd7: alg_hot = 8'h80; // D7 + endcase +end + +// prev2 cannot modulate with prevprev1 at the same time +// x = prev2, prevprev1, internal_x +// y = prev1, internal_y + +generate + if( num_ch==6 ) begin + always @(*) begin + xuse_prevprev1 = s1_enters | (s3_enters&alg_hot[5]); + xuse_prev2 = (s3_enters&(|alg_hot[2:0])) | (s4_enters&alg_hot[3]); + xuse_internal = s4_enters & alg_hot[2]; + yuse_internal = s4_enters & (|{alg_hot[4:3],alg_hot[1:0]}); + yuse_prev1 = s1_enters | (s3_enters&alg_hot[1]) | + (s2_enters&(|{alg_hot[6:3],alg_hot[0]}) )| + (s4_enters&(|{alg_hot[5],alg_hot[2]})); + yuse_prev2 = 1'b0; // unused for 6 channels + end + end else begin + reg [2:0] xuse_s4, xuse_s3, xuse_s2, xuse_s1; + reg [2:0] yuse_s4, yuse_s3, yuse_s2, yuse_s1; + always @(*) begin // 3 ch + // S1 + { xuse_s1, yuse_s1 } = { 3'b001, 3'b100 }; + // S2 + casez( 1'b1 ) + // S2 modulated by S1 + alg_hot[6], alg_hot[5], alg_hot[4], alg_hot[3], alg_hot[0]: + { xuse_s2, yuse_s2 } = { 3'b000, 3'b100 }; // prev1 + default: { xuse_s2, yuse_s2 } = 6'd0; + endcase + // S3 + casez( 1'b1 ) + // S3 modulated by S1 + alg_hot[5]: + { xuse_s3, yuse_s3 } = { 3'b000, 3'b100 }; // prev1 + // S3 modulated by S2 + alg_hot[2], alg_hot[0]: + { xuse_s3, yuse_s3 } = { 3'b000, 3'b010 }; // prev2 + // S3 modulated by S2+S1 + alg_hot[1]: + { xuse_s3, yuse_s3 } = { 3'b010, 3'b100 }; // prev2 + prev1 + default: { xuse_s3, yuse_s3 } = 6'd0; + endcase + // S4 + casez( 1'b1 ) + // S4 modulated by S1 + alg_hot[5]: + { xuse_s4, yuse_s4 } = { 3'b000, 3'b100 }; // prev1 + // S4 modulated by S3 + alg_hot[4], alg_hot[1], alg_hot[0]: + { xuse_s4, yuse_s4 } = { 3'b100, 3'b000 }; // prevprev1 + // S4 modulated by S3+S2 + alg_hot[3]: + { xuse_s4, yuse_s4 } = { 3'b100, 3'b010 }; // prevprev1+prev2 + // S4 modulated by S3+S1 + alg_hot[2]: + { xuse_s4, yuse_s4 } = { 3'b100, 3'b100 }; // prevprev1+prev1 + default: { xuse_s4, yuse_s4 } = 6'd0; + endcase + case( {s4_enters, s3_enters, s2_enters, s1_enters}) + 4'b1000: begin + {xuse_prevprev1, xuse_prev2, xuse_internal} = xuse_s4; + {yuse_prev1, yuse_prev2, yuse_internal } = yuse_s4; + end + 4'b0100: begin + {xuse_prevprev1, xuse_prev2, xuse_internal} = xuse_s3; + {yuse_prev1, yuse_prev2, yuse_internal } = yuse_s3; + end + 4'b0010: begin + {xuse_prevprev1, xuse_prev2, xuse_internal} = xuse_s2; + {yuse_prev1, yuse_prev2, yuse_internal } = yuse_s2; + end + 4'b0001: begin + {xuse_prevprev1, xuse_prev2, xuse_internal} = xuse_s1; + {yuse_prev1, yuse_prev2, yuse_internal } = yuse_s1; + end + default: begin + {xuse_prevprev1, xuse_prev2, xuse_internal} = 3'b0; + {yuse_prev1, yuse_prev2, yuse_internal } = 3'b0; + end + endcase + end + end +endgenerate + +// Control signals for simulation: should be 2'b0 or 2'b1 +// wire [1:0] xusage = xuse_prevprev1+xuse_prev2+xuse_internal; +// wire [1:0] yusage = yuse_prev1+yuse_internal; +// +// always @(xusage,yusage) +// if( xusage>2'b1 || yusage>2'b1 ) begin +// $display("ERROR: x/y over use in jt12_mod"); +// $finish; +// end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_op.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_op.v new file mode 100644 index 0000000000000000000000000000000000000000..d0d29816219c851c5969ac2b98ba26705d5d0bdf --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_op.v @@ -0,0 +1,331 @@ + + +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Based on Sauraen VHDL version of OPN/OPN2, which is based on die shots. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + + +module jt12_op( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input [9:0] pg_phase_VIII, + input [9:0] eg_atten_IX, // output from envelope generator + input [2:0] fb_II, // voice feedback + input xuse_prevprev1, + input xuse_prev2, + input xuse_internal, + input yuse_prev1, + input yuse_prev2, + input yuse_internal, + input test_214, + + input s1_enters, + input s2_enters, + input s3_enters, + input s4_enters, + input zero, + + output signed [ 8:0] op_result, + output signed [13:0] full_result +); + +parameter num_ch = 6; + +/* enters exits + S1 S2 + S3 S4 + S2 S1 + S4 S3 +*/ + +reg [13:0] op_result_internal, op_XII; +reg [11:0] atten_internal_IX; + +assign op_result = op_result_internal[13:5]; +assign full_result = op_result_internal; + +reg signbit_IX, signbit_X, signbit_XI; +reg [11:0] totalatten_X; + +wire [13:0] prev1, prevprev1, prev2; + +reg [13:0] prev1_din, prevprev1_din, prev2_din; + +always @(*) + if( num_ch==3 ) begin + prev1_din = s1_enters ? op_result_internal : prev1; + prevprev1_din = s3_enters ? op_result_internal : prevprev1; + prev2_din = s2_enters ? op_result_internal : prev2; + end else begin // 6 channels + prev1_din = s2_enters ? op_result_internal : prev1; + prevprev1_din = s2_enters ? prev1 : prevprev1; + prev2_din = s1_enters ? op_result_internal : prev2; + end + +jt12_sh #( .width(14), .stages(num_ch)) prev1_buffer( +// .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( prev1_din ), + .drop ( prev1 ) +); + +jt12_sh #( .width(14), .stages(num_ch)) prevprev1_buffer( +// .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( prevprev1_din ), + .drop ( prevprev1 ) +); + +jt12_sh #( .width(14), .stages(num_ch)) prev2_buffer( +// .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( prev2_din ), + .drop ( prev2 ) +); + + +reg [10:0] subtresult; + +reg [12:0] shifter, shifter_2, shifter_3; + +// REGISTER/CYCLE 1 +// Creation of phase modulation (FM) feedback signal, before shifting +reg [13:0] x, y; +reg [14:0] xs, ys, pm_preshift_II; +reg s1_II; + +always @(*) begin + casez( {xuse_prevprev1, xuse_prev2, xuse_internal }) + 3'b1??: x = prevprev1; + 3'b01?: x = prev2; + 3'b001: x = op_result_internal; + default: x = 14'd0; + endcase + casez( {yuse_prev1, yuse_prev2, yuse_internal }) + 3'b1??: y = prev1; + 3'b01?: y = prev2; + 3'b001: y = op_result_internal; + default: y = 14'd0; + endcase + xs = { x[13], x }; // sign-extend + ys = { y[13], y }; // sign-extend +end + +always @(posedge clk) if( clk_en ) begin + pm_preshift_II <= xs + ys; // carry is discarded + s1_II <= s1_enters; +end + +/* REGISTER/CYCLE 2-7 (also YM2612 extra cycles 1-6) + Shifting of FM feedback signal, adding phase from PG to FM phase + In YM2203, phasemod_II is not registered at all, it is latched on the first edge + in add_pg_phase and the second edge is the output of add_pg_phase. In the YM2612, there + are 6 cycles worth of registers between the generated (non-registered) phasemod_II signal + and the input to add_pg_phase. */ + +reg [9:0] phasemod_II; +wire [9:0] phasemod_VIII; + +always @(*) begin + // Shift FM feedback signal + if (!s1_II ) // Not S1 + phasemod_II = pm_preshift_II[10:1]; // Bit 0 of pm_preshift_II is never used + else // S1 + case( fb_II ) + 3'd0: phasemod_II = 10'd0; + 3'd1: phasemod_II = { {4{pm_preshift_II[14]}}, pm_preshift_II[14:9] }; + 3'd2: phasemod_II = { {3{pm_preshift_II[14]}}, pm_preshift_II[14:8] }; + 3'd3: phasemod_II = { {2{pm_preshift_II[14]}}, pm_preshift_II[14:7] }; + 3'd4: phasemod_II = { pm_preshift_II[14], pm_preshift_II[14:6] }; + 3'd5: phasemod_II = pm_preshift_II[14:5]; + 3'd6: phasemod_II = pm_preshift_II[13:4]; + 3'd7: phasemod_II = pm_preshift_II[12:3]; + endcase +end + +// REGISTER/CYCLE 2-7 +//generate +// if( num_ch==6 ) + jt12_sh #( .width(10), .stages(6)) phasemod_sh( + .clk ( clk ), + .clk_en ( clk_en), + .din ( phasemod_II ), + .drop ( phasemod_VIII ) + ); +// else begin +// assign phasemod_VIII = phasemod_II; +// end +// endgenerate + +// REGISTER/CYCLE 8 +reg [ 9:0] phase; +// Sets the maximum number of fanouts for a register or combinational +// cell. The Quartus II software will replicate the cell and split +// the fanouts among the duplicates until the fanout of each cell +// is below the maximum. + +reg [ 7:0] aux_VIII; + +always @(*) begin + phase = phasemod_VIII + pg_phase_VIII; + aux_VIII= phase[7:0] ^ {8{~phase[8]}}; +end + +always @(posedge clk) if( clk_en ) begin + signbit_IX <= phase[9]; +end + +wire [11:0] logsin_IX; + +jt12_logsin u_logsin ( + .clk ( clk ), + .clk_en ( clk_en ), + .addr ( aux_VIII[7:0] ), + .logsin ( logsin_IX ) +); + + +// REGISTER/CYCLE 9 +// Sine table +// Main sine table body + +always @(*) begin + subtresult = eg_atten_IX + logsin_IX[11:2]; + atten_internal_IX = { subtresult[9:0], logsin_IX[1:0] } | {12{subtresult[10]}}; +end + +wire [9:0] mantissa_X; +reg [9:0] mantissa_XI; +reg [3:0] exponent_X, exponent_XI; + +jt12_exprom u_exprom( + .clk ( clk ), + .clk_en ( clk_en ), + .addr ( atten_internal_IX[7:0] ), + .exp ( mantissa_X ) +); + +always @(posedge clk) if( clk_en ) begin + exponent_X <= atten_internal_IX[11:8]; + signbit_X <= signbit_IX; +end + +always @(posedge clk) if( clk_en ) begin + mantissa_XI <= mantissa_X; + exponent_XI <= exponent_X; + signbit_XI <= signbit_X; +end + +// REGISTER/CYCLE 11 +// Introduce test bit as MSB, 2's complement & Carry-out discarded + +always @(*) begin + // Floating-point to integer, and incorporating sign bit + // Two-stage shifting of mantissa_XI by exponent_XI + shifter = { 3'b001, mantissa_XI }; + case( ~exponent_XI[1:0] ) + 2'b00: shifter_2 = { 1'b0, shifter[12:1] }; // LSB discarded + 2'b01: shifter_2 = shifter; + 2'b10: shifter_2 = { shifter[11:0], 1'b0 }; + 2'b11: shifter_2 = { shifter[10:0], 2'b0 }; + endcase + case( ~exponent_XI[3:2] ) + 2'b00: shifter_3 = {12'b0, shifter_2[12] }; + 2'b01: shifter_3 = { 8'b0, shifter_2[12:8] }; + 2'b10: shifter_3 = { 4'b0, shifter_2[12:4] }; + 2'b11: shifter_3 = shifter_2; + endcase +end + +always @(posedge clk) if( clk_en ) begin + // REGISTER CYCLE 11 + op_XII <= ({ test_214, shifter_3 } ^ {14{signbit_XI}}) + {13'd0,signbit_XI}; + // REGISTER CYCLE 12 + // Extra register, take output after here + op_result_internal <= op_XII; +end + +`ifdef SIMULATION +reg signed [13:0] op_sep2_0; +reg signed [13:0] op_sep4_0; +reg signed [13:0] op_sep5_0; +reg signed [13:0] op_sep6_0; +reg signed [13:0] op_sep0_0; +reg signed [13:0] op_sep1_0; +reg signed [13:0] op_sep2_1; +reg signed [13:0] op_sep4_1; +reg signed [13:0] op_sep5_1; +reg signed [13:0] op_sep6_1; +reg signed [13:0] op_sep0_1; +reg signed [13:0] op_sep1_1; +reg signed [13:0] op_sep2_2; +reg signed [13:0] op_sep4_2; +reg signed [13:0] op_sep5_2; +reg signed [13:0] op_sep6_2; +reg signed [13:0] op_sep0_2; +reg signed [13:0] op_sep1_2; +reg signed [13:0] op_sep2_3; +reg signed [13:0] op_sep4_3; +reg signed [13:0] op_sep5_3; +reg signed [13:0] op_sep6_3; +reg signed [13:0] op_sep0_3; +reg signed [13:0] op_sep1_3; +reg [ 4:0] sepcnt; + +always @(posedge clk) if(clk_en) begin + sepcnt <= zero ? 5'd0 : sepcnt+5'd1; + case( (sepcnt+14)%24 ) + 0: op_sep0_0 <= op_XII; + 1: op_sep1_0 <= op_XII; + 2: op_sep2_0 <= op_XII; + 3: op_sep4_0 <= op_XII; + 4: op_sep5_0 <= op_XII; + 5: op_sep6_0 <= op_XII; + 6: op_sep0_2 <= op_XII; + 7: op_sep1_2 <= op_XII; + 8: op_sep2_2 <= op_XII; + 9: op_sep4_2 <= op_XII; + 10: op_sep5_2 <= op_XII; + 11: op_sep6_2 <= op_XII; + 12: op_sep0_1 <= op_XII; + 13: op_sep1_1 <= op_XII; + 14: op_sep2_1 <= op_XII; + 15: op_sep4_1 <= op_XII; + 16: op_sep5_1 <= op_XII; + 17: op_sep6_1 <= op_XII; + 18: op_sep0_3 <= op_XII; + 19: op_sep1_3 <= op_XII; + 20: op_sep2_3 <= op_XII; + 21: op_sep4_3 <= op_XII; + 22: op_sep5_3 <= op_XII; + 23: op_sep6_3 <= op_XII; + endcase +end + +`endif + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm.v new file mode 100644 index 0000000000000000000000000000000000000000..b0d04f53984327bb501235d0fd51aad4369e4bf6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm.v @@ -0,0 +1,109 @@ +module jt12_pcm( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input zero, + input signed [8:0] pcm, + input pcm_wr, + output reg signed [8:0] pcm_resampled +); + +// reg [2:0] ratesel; +// reg [3:0] cnt8; +// reg wrcnt, wrclr; +reg last_zero; +wire zero_edge = !last_zero && zero; +/* +always @(posedge clk) + if(rst) begin + cnt8 <= 4'd0; + wrclr <= 1'd0; + ratesel <= 3'd1; + wrcnt <= 1'b0; + end else if(clk_en) begin + if( pcm_wr ) begin + if( wrcnt ) begin + // case( cnt8[3:2] ) + // 2'd3: ratesel <= 3'b111; // x8 + // 2'd2: ratesel <= 3'b011; // x4 + // 2'd1: ratesel <= 3'b001; // x2 + // 2'd0: ratesel <= 3'b000; // x1 + // endcase + cnt8 <= 4'd0; + wrcnt <= 1'b0; + end + else wrcnt <= 1'b1; + end else + if( cnt8!=4'hf && zero ) cnt8 <= cnt8 + 4'd1; + end +*/ +// up-rate PCM samples +reg rate1, rate2; //, rate4, rate8; +reg cen1, cen2; //, cen4, cen8; + +always @(posedge clk, posedge rst) + if(rst) + rate2 <= 1'b0; + else begin + last_zero <= zero; + rate1 <= zero_edge; + if(zero_edge) begin + rate2 <= ~rate2; +// if(rate2) begin +// rate4 <= ~rate4; +// if(rate4) rate8<=~rate8; +// end + end + end + +always @(posedge clk) begin + cen1 <= rate1; + cen2 <= rate1 && rate2; +// cen4 <= rate1 && rate2 && rate4; +// cen8 <= rate1 && rate2 && rate4 && rate8; +end + +wire signed [8:0] pcm3; //,pcm2, pcm1; + +//always @(posedge clk) if( clk_en ) +// pcm_resampled <= ratesel[0] ? pcm3 : pcm; +always @(*) + pcm_resampled = pcm3; + +// rate x2 +//wire signed [8:0] pcm_in2 = ratesel[1] ? pcm2 : pcm; +jt12_interpol #(.calcw(10),.inw(9),.rate(2),.m(1),.n(2)) +u_uprate_3( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen2 ), + .cen_out( cen1 ), + // .snd_in ( pcm_in2 ), + .snd_in ( pcm ), + .snd_out( pcm3 ) +); +/* +// rate x2 +wire signed [8:0] pcm_in1 = ratesel[2] ? pcm1 : pcm; +jt12_interpol #(.calcw(10),.inw(9),.rate(2),.m(1),.n(2)) +u_uprate_2( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen4 ), + .cen_out( cen2 ), + .snd_in ( pcm_in1 ), + .snd_out( pcm2 ) +); + +// rate x2 +jt12_interpol #(.calcw(10),.inw(9),.rate(2),.m(1),.n(2)) +u_uprate_1( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen8 ), + .cen_out( cen4 ), + .snd_in ( pcm ), + .snd_out( pcm1 ) +); +*/ +endmodule // jt12_pcm \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm_interpol.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm_interpol.v new file mode 100644 index 0000000000000000000000000000000000000000..b6f989976b54bc8d2035da9c8a1eda56f9da8436 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pcm_interpol.v @@ -0,0 +1,109 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt12_pcm_interpol +#(parameter DW=9, stepw=5) +( + input rst_n, + input clk, + input cen, // 8MHz cen + input cen55, // clk & cen55 = 55 kHz + input pcm_wr, // advance to next sample + input signed [DW-1:0] pcmin, + output reg signed [DW-1:0] pcmout +); + +reg sign, last_pcm_wr; +reg [stepw-1:0] dn, pre_dn={stepw{1'b1}}; +wire posedge_pcmwr = pcm_wr && !last_pcm_wr; +wire negedge_pcmwr = !pcm_wr && last_pcm_wr; + +reg start_div = 0; +wire working; + +reg signed [DW-1:0] pcmnew, dx, pcmlast, pcminter; +wire signed [DW:0] dx_ext = { pcmin[DW-1], pcmin } - { pcmnew[DW-1], pcmnew }; + +// latch new data and compute the two deltas : dx and dn, slope = dx/dn +always @(posedge clk) begin + last_pcm_wr <= pcm_wr; + start_div <= posedge_pcmwr; + + if( posedge_pcmwr ) begin + pre_dn <= 1; + pcmnew <= pcmin; + pcmlast <= pcmnew; + dn <= pre_dn; + dx <= dx_ext[DW] ? -dx_ext[DW-1:0] : dx_ext[DW-1:0]; + sign <= dx_ext[DW]; + start_div <= 1; + end + + if( !pcm_wr && cen55 ) begin + if( pre_dn != {stepw{1'b1}} ) pre_dn <= pre_dn + 'd1; + end +end + +// interpolate samples +wire [DW-1:0] step; +wire signed [DW-1:0] next_up = pcminter + step; +wire signed [DW-1:0] next_down = pcminter - step; +wire overflow_up = 0;//next_up[DW-1] != pcmnew[DW-1]; +wire overflow_down = 0;//next_down[DW-1] != pcmnew[DW-1]; + + +always @(posedge clk) begin + if( negedge_pcmwr ) begin + pcminter <= pcmlast; + end else if(cen55 && !working && !pcm_wr) begin // only advance if the divider has finished + if( sign ) begin // subtract + if( next_down > pcmnew && !overflow_down ) + pcminter <= next_down; + else + pcminter <= pcmnew; // done + end + else begin // add + if( next_up < pcmnew && !overflow_up ) + pcminter <= next_up; + else + pcminter <= pcmnew; // done + end + end +end + +// output only at cen55 + +always @(posedge clk) if(cen55) pcmout <= pcminter; + +jt10_adpcm_div #(.DW(DW)) u_div( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( 1'b1 ), + .start ( start_div ), + .a ( dx ), + .b ( { {DW-stepw{1'b0}}, dn } ), + .d ( step ), + .r ( ), + .working( working ) +); + + +endmodule // jt10_adpcmb_interpol \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg.v new file mode 100644 index 0000000000000000000000000000000000000000..913a7398105a3620bf7811f3acb2016481a60e0f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg.v @@ -0,0 +1,113 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2016 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + Based on jt51_phasegen.v, from JT51 + + */ + + +/* + + tab size 4 + +*/ + +module jt12_pg( + input clk, + input clk_en /* synthesis direct_enable */, + input rst, + // Channel frequency + input [10:0] fnum_I, + input [ 2:0] block_I, + // Operator multiplying + input [ 3:0] mul_II, + // Operator detuning + input [ 2:0] dt1_I, // same as JT51's DT1 + // phase modulation from LFO + input [ 6:0] lfo_mod, + input [ 2:0] pms_I, + // phase operation + input pg_rst_II, + input pg_stop, // not implemented + + output reg [ 4:0] keycode_II, + output [ 9:0] phase_VIII +); + +parameter num_ch=6; + +wire [4:0] keycode_I; +wire signed [5:0] detune_mod_I; +reg signed [5:0] detune_mod_II; +wire [16:0] phinc_I; +reg [16:0] phinc_II; +wire [19:0] phase_drop, phase_in; +wire [ 9:0] phase_II; + +always @(posedge clk) if(clk_en) begin + keycode_II <= keycode_I; + detune_mod_II <= detune_mod_I; + phinc_II <= phinc_I; +end + +jt12_pg_comb u_comb( + .block ( block_I ), + .fnum ( fnum_I ), + // Phase Modulation + .lfo_mod ( lfo_mod[6:2] ), + .pms ( pms_I ), + + // Detune + .detune ( dt1_I ), + .keycode ( keycode_I ), + .detune_out ( detune_mod_I ), + // Phase increment + .phinc_out ( phinc_I ), + // Phase add + .mul ( mul_II ), + .phase_in ( phase_drop ), + .pg_rst ( pg_rst_II ), + .detune_in ( detune_mod_II ), + .phinc_in ( phinc_II ), + + .phase_out ( phase_in ), + .phase_op ( phase_II ) +); + +jt12_sh_rst #( .width(20), .stages(4*num_ch) ) u_phsh( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( phase_in ), + .drop ( phase_drop) +); + +jt12_sh_rst #( .width(10), .stages(6) ) u_pad( + .clk ( clk ), + .clk_en ( clk_en ), + .rst ( rst ), + .din ( phase_II ), + .drop ( phase_VIII) +); + +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_comb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..a8091d217abca6749f755130e119c8c1c26c7618 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_comb.v @@ -0,0 +1,90 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 2-11-2018 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + 100% compared with Alexey Khokholov (Nuke.YKT) work with identical results. +*/ + +module jt12_pg_comb( + input [ 2:0] block, + input [10:0] fnum, + // Phase Modulation + input [ 4:0] lfo_mod, + input [ 2:0] pms, + // output [ 7:0] pm_out, + + // Detune + input [ 2:0] detune, + + output [ 4:0] keycode, + output signed [5:0] detune_out, + // Phase increment + output [16:0] phinc_out, + // Phase add + input [ 3:0] mul, + input [19:0] phase_in, + input pg_rst, + // input signed [7:0] pm_in, + input signed [5:0] detune_in, + input [16:0] phinc_in, + + output [19:0] phase_out, + output [ 9:0] phase_op +); + +wire signed [8:0] pm_offset; + +/* pm, pg_dt and pg_inc operate in parallel */ +jt12_pm u_pm( + .lfo_mod ( lfo_mod ), + .fnum ( fnum ), + .pms ( pms ), + .pm_offset ( pm_offset ) +); + +jt12_pg_dt u_dt( + .block ( block ), + .fnum ( fnum ), + .detune ( detune ), + .keycode ( keycode ), + .detune_signed( detune_out ) +); + +jt12_pg_inc u_inc( + .block ( block ), + .fnum ( fnum ), + .pm_offset ( pm_offset ), + .phinc_pure ( phinc_out ) +); + +// pg_sum uses the output from the previous blocks + +jt12_pg_sum u_sum( + .mul ( mul ), + .phase_in ( phase_in ), + .pg_rst ( pg_rst ), + .detune_signed ( detune_in ), + .phinc_pure ( phinc_in ), + .phase_out ( phase_out ), + .phase_op ( phase_op ) +); + +endmodule // jt12_pg_comb \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_dt.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_dt.v new file mode 100644 index 0000000000000000000000000000000000000000..9b9e0f31c5b18660025439a84655500b3892ea61 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_dt.v @@ -0,0 +1,82 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 2-11-2018 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + Note that detune produces an output even for fnum==0, is that correct? + + Based on jt51_phasegen.v, from JT51 + + */ + +module jt12_pg_dt( + input [ 2:0] block, + input [10:0] fnum, + input [ 2:0] detune, + + output reg [ 4:0] keycode, + output reg signed [5:0] detune_signed +); + +reg [5:0] detune_kf; +reg [4:0] pow2; +reg [5:0] detune_unlimited; +reg [4:0] detune_limit, detune_limited; + + +always @(*) begin + keycode = { block, fnum[10], fnum[10] ? (|fnum[9:7]) : (&fnum[9:7])}; + case( detune[1:0] ) + 2'd1: detune_kf = { 1'b0, keycode } - 6'd4; + 2'd2: detune_kf = { 1'b0, keycode } + 6'd4; + 2'd3: detune_kf = { 1'b0, keycode } + 6'd8; + default:detune_kf = { 1'b0, keycode }; + endcase + case( detune_kf[2:0] ) + 3'd0: pow2 = 5'd16; + 3'd1: pow2 = 5'd17; + 3'd2: pow2 = 5'd19; + 3'd3: pow2 = 5'd20; + 3'd4: pow2 = 5'd22; + 3'd5: pow2 = 5'd24; + 3'd6: pow2 = 5'd26; + 3'd7: pow2 = 5'd29; + endcase + case( detune[1:0] ) + 2'd0: detune_limit = 5'd0; + 2'd1: detune_limit = 5'd8; + 2'd2: detune_limit = 5'd16; + 2'd3: detune_limit = 5'd22; + endcase + case( detune_kf[5:3] ) + 3'd0: detune_unlimited = { 5'd0, pow2[4] }; // <2 + 3'd1: detune_unlimited = { 4'd0, pow2[4:3] }; // <4 + 3'd2: detune_unlimited = { 3'd0, pow2[4:2] }; // <8 + 3'd3: detune_unlimited = { 2'd0, pow2[4:1] }; + 3'd4: detune_unlimited = { 1'd0, pow2[4:0] }; + 3'd5: detune_unlimited = { pow2[4:0], 1'd0 }; + default:detune_unlimited = 6'd0; + endcase + detune_limited = detune_unlimited > {1'b0, detune_limit} ? + detune_limit : detune_unlimited[4:0]; + detune_signed = !detune[2] ? {1'b0,detune_limited} : (~{1'b0,detune_limited}+6'd1); +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_inc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_inc.v new file mode 100644 index 0000000000000000000000000000000000000000..bee1c8dbe5fc8c09a975cde9cf67a4ec0c29ab90 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_inc.v @@ -0,0 +1,50 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 2-11-2018 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + Based on jt51_phasegen.v, from JT51 + + */ + +module jt12_pg_inc ( + input [ 2:0] block, + input [10:0] fnum, + input signed [8:0] pm_offset, + output reg [16:0] phinc_pure +); + +reg [11:0] fnum_mod; + +always @(*) begin + fnum_mod = {fnum,1'b0} + {{3{pm_offset[8]}},pm_offset}; + case ( block ) + 3'd0: phinc_pure = { 7'd0, fnum_mod[11:2] }; + 3'd1: phinc_pure = { 6'd0, fnum_mod[11:1] }; + 3'd2: phinc_pure = { 5'd0, fnum_mod[11:0] }; + 3'd3: phinc_pure = { 4'd0, fnum_mod, 1'd0 }; + 3'd4: phinc_pure = { 3'd0, fnum_mod, 2'd0 }; + 3'd5: phinc_pure = { 2'd0, fnum_mod, 3'd0 }; + 3'd6: phinc_pure = { 1'd0, fnum_mod, 4'd0 }; + 3'd7: phinc_pure = { fnum_mod, 5'd0 }; + endcase +end + +endmodule // jt12_pg_inc \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_sum.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_sum.v new file mode 100644 index 0000000000000000000000000000000000000000..6369c53a889e5f35dee21987836caed1df72705a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pg_sum.v @@ -0,0 +1,49 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 2-11-2018 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + Based on jt51_phasegen.v, from JT51 + + */ + +module jt12_pg_sum ( + input [ 3:0] mul, + input [19:0] phase_in, + input pg_rst, + input signed [5:0] detune_signed, + input [16:0] phinc_pure, + + output reg [19:0] phase_out, + output reg [ 9:0] phase_op +); + +reg [16:0] phinc_premul; +reg [19:0] phinc_mul; + +always @(*) begin + phinc_premul = phinc_pure + {{11{detune_signed[5]}},detune_signed}; + phinc_mul = ( mul==4'd0 ) ? {4'b0,phinc_premul[16:1]} : ({3'd0,phinc_premul} * mul); + + phase_out = pg_rst ? 20'd0 : (phase_in + { phinc_mul}); + phase_op = phase_out[19:10]; +end + +endmodule // jt12_pg_sum \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pm.v new file mode 100644 index 0000000000000000000000000000000000000000..acfafdc171c010d8e092232c8620974252414736 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_pm.v @@ -0,0 +1,185 @@ +/* This file is part of jt12. + + jt12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + jt12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with jt12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-10-2018 + */ + + +// This implementation follows that of Alexey Khokholov (Nuke.YKT) in C language. + +module jt12_pm ( + input [4:0] lfo_mod, + input [10:0] fnum, + input [2:0] pms, + output reg signed [8:0] pm_offset +); + + +reg [7:0] pm_unsigned; +reg [7:0] pm_base; +reg [9:0] pm_shifted; + +wire [2:0] index = lfo_mod[3] ? (~lfo_mod[2:0]) : lfo_mod[2:0]; + +reg [2:0] lfo_sh1_lut [0:63]; +reg [2:0] lfo_sh2_lut [0:63]; +reg [2:0] lfo_sh1, lfo_sh2; + +initial begin + lfo_sh1_lut[6'h00] = 3'd7; + lfo_sh1_lut[6'h01] = 3'd7; + lfo_sh1_lut[6'h02] = 3'd7; + lfo_sh1_lut[6'h03] = 3'd7; + lfo_sh1_lut[6'h04] = 3'd7; + lfo_sh1_lut[6'h05] = 3'd7; + lfo_sh1_lut[6'h06] = 3'd7; + lfo_sh1_lut[6'h07] = 3'd7; + lfo_sh1_lut[6'h08] = 3'd7; + lfo_sh1_lut[6'h09] = 3'd7; + lfo_sh1_lut[6'h0A] = 3'd7; + lfo_sh1_lut[6'h0B] = 3'd7; + lfo_sh1_lut[6'h0C] = 3'd7; + lfo_sh1_lut[6'h0D] = 3'd7; + lfo_sh1_lut[6'h0E] = 3'd7; + lfo_sh1_lut[6'h0F] = 3'd7; + lfo_sh1_lut[6'h10] = 3'd7; + lfo_sh1_lut[6'h11] = 3'd7; + lfo_sh1_lut[6'h12] = 3'd7; + lfo_sh1_lut[6'h13] = 3'd7; + lfo_sh1_lut[6'h14] = 3'd7; + lfo_sh1_lut[6'h15] = 3'd7; + lfo_sh1_lut[6'h16] = 3'd1; + lfo_sh1_lut[6'h17] = 3'd1; + lfo_sh1_lut[6'h18] = 3'd7; + lfo_sh1_lut[6'h19] = 3'd7; + lfo_sh1_lut[6'h1A] = 3'd7; + lfo_sh1_lut[6'h1B] = 3'd7; + lfo_sh1_lut[6'h1C] = 3'd1; + lfo_sh1_lut[6'h1D] = 3'd1; + lfo_sh1_lut[6'h1E] = 3'd1; + lfo_sh1_lut[6'h1F] = 3'd1; + lfo_sh1_lut[6'h20] = 3'd7; + lfo_sh1_lut[6'h21] = 3'd7; + lfo_sh1_lut[6'h22] = 3'd7; + lfo_sh1_lut[6'h23] = 3'd1; + lfo_sh1_lut[6'h24] = 3'd1; + lfo_sh1_lut[6'h25] = 3'd1; + lfo_sh1_lut[6'h26] = 3'd1; + lfo_sh1_lut[6'h27] = 3'd0; + lfo_sh1_lut[6'h28] = 3'd7; + lfo_sh1_lut[6'h29] = 3'd7; + lfo_sh1_lut[6'h2A] = 3'd1; + lfo_sh1_lut[6'h2B] = 3'd1; + lfo_sh1_lut[6'h2C] = 3'd0; + lfo_sh1_lut[6'h2D] = 3'd0; + lfo_sh1_lut[6'h2E] = 3'd0; + lfo_sh1_lut[6'h2F] = 3'd0; + lfo_sh1_lut[6'h30] = 3'd7; + lfo_sh1_lut[6'h31] = 3'd7; + lfo_sh1_lut[6'h32] = 3'd1; + lfo_sh1_lut[6'h33] = 3'd1; + lfo_sh1_lut[6'h34] = 3'd0; + lfo_sh1_lut[6'h35] = 3'd0; + lfo_sh1_lut[6'h36] = 3'd0; + lfo_sh1_lut[6'h37] = 3'd0; + lfo_sh1_lut[6'h38] = 3'd7; + lfo_sh1_lut[6'h39] = 3'd7; + lfo_sh1_lut[6'h3A] = 3'd1; + lfo_sh1_lut[6'h3B] = 3'd1; + lfo_sh1_lut[6'h3C] = 3'd0; + lfo_sh1_lut[6'h3D] = 3'd0; + lfo_sh1_lut[6'h3E] = 3'd0; + lfo_sh1_lut[6'h3F] = 3'd0; + lfo_sh2_lut[6'h00] = 3'd7; + lfo_sh2_lut[6'h01] = 3'd7; + lfo_sh2_lut[6'h02] = 3'd7; + lfo_sh2_lut[6'h03] = 3'd7; + lfo_sh2_lut[6'h04] = 3'd7; + lfo_sh2_lut[6'h05] = 3'd7; + lfo_sh2_lut[6'h06] = 3'd7; + lfo_sh2_lut[6'h07] = 3'd7; + lfo_sh2_lut[6'h08] = 3'd7; + lfo_sh2_lut[6'h09] = 3'd7; + lfo_sh2_lut[6'h0A] = 3'd7; + lfo_sh2_lut[6'h0B] = 3'd7; + lfo_sh2_lut[6'h0C] = 3'd2; + lfo_sh2_lut[6'h0D] = 3'd2; + lfo_sh2_lut[6'h0E] = 3'd2; + lfo_sh2_lut[6'h0F] = 3'd2; + lfo_sh2_lut[6'h10] = 3'd7; + lfo_sh2_lut[6'h11] = 3'd7; + lfo_sh2_lut[6'h12] = 3'd7; + lfo_sh2_lut[6'h13] = 3'd2; + lfo_sh2_lut[6'h14] = 3'd2; + lfo_sh2_lut[6'h15] = 3'd2; + lfo_sh2_lut[6'h16] = 3'd7; + lfo_sh2_lut[6'h17] = 3'd7; + lfo_sh2_lut[6'h18] = 3'd7; + lfo_sh2_lut[6'h19] = 3'd7; + lfo_sh2_lut[6'h1A] = 3'd2; + lfo_sh2_lut[6'h1B] = 3'd2; + lfo_sh2_lut[6'h1C] = 3'd7; + lfo_sh2_lut[6'h1D] = 3'd7; + lfo_sh2_lut[6'h1E] = 3'd2; + lfo_sh2_lut[6'h1F] = 3'd2; + lfo_sh2_lut[6'h20] = 3'd7; + lfo_sh2_lut[6'h21] = 3'd7; + lfo_sh2_lut[6'h22] = 3'd2; + lfo_sh2_lut[6'h23] = 3'd7; + lfo_sh2_lut[6'h24] = 3'd7; + lfo_sh2_lut[6'h25] = 3'd7; + lfo_sh2_lut[6'h26] = 3'd2; + lfo_sh2_lut[6'h27] = 3'd7; + lfo_sh2_lut[6'h28] = 3'd7; + lfo_sh2_lut[6'h29] = 3'd7; + lfo_sh2_lut[6'h2A] = 3'd7; + lfo_sh2_lut[6'h2B] = 3'd2; + lfo_sh2_lut[6'h2C] = 3'd7; + lfo_sh2_lut[6'h2D] = 3'd7; + lfo_sh2_lut[6'h2E] = 3'd2; + lfo_sh2_lut[6'h2F] = 3'd1; + lfo_sh2_lut[6'h30] = 3'd7; + lfo_sh2_lut[6'h31] = 3'd7; + lfo_sh2_lut[6'h32] = 3'd7; + lfo_sh2_lut[6'h33] = 3'd2; + lfo_sh2_lut[6'h34] = 3'd7; + lfo_sh2_lut[6'h35] = 3'd7; + lfo_sh2_lut[6'h36] = 3'd2; + lfo_sh2_lut[6'h37] = 3'd1; + lfo_sh2_lut[6'h38] = 3'd7; + lfo_sh2_lut[6'h39] = 3'd7; + lfo_sh2_lut[6'h3A] = 3'd7; + lfo_sh2_lut[6'h3B] = 3'd2; + lfo_sh2_lut[6'h3C] = 3'd7; + lfo_sh2_lut[6'h3D] = 3'd7; + lfo_sh2_lut[6'h3E] = 3'd2; + lfo_sh2_lut[6'h3F] = 3'd1; +end + +always @(*) begin + lfo_sh1 = lfo_sh1_lut[{pms,index}]; + lfo_sh2 = lfo_sh2_lut[{pms,index}]; + pm_base = ({1'b0,fnum[10:4]}>>lfo_sh1) + ({1'b0,fnum[10:4]}>>lfo_sh2); + case( pms ) + default: pm_shifted = { 2'b0, pm_base }; + 3'd6: pm_shifted = { 1'b0, pm_base, 1'b0 }; + 3'd7: pm_shifted = { pm_base, 2'b0 }; + endcase // pms + pm_offset = lfo_mod[4] ? (-{1'b0,pm_shifted[9:2]}) : {1'b0,pm_shifted[9:2]}; +end // always @(*) + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg.v new file mode 100644 index 0000000000000000000000000000000000000000..0b1b4e2a16a8676fdb49e16ac938b5274fd869c9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg.v @@ -0,0 +1,339 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + +*/ + +module jt12_reg( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + + input [2:0] ch, // channel to update + input [1:0] op, + + input csm, + input flag_A, + input overflow_A, + + // channel udpates + input [2:0] ch_sel, + input [7:0] ch_din, + input up_alg, + input up_fnumlo, + // operator updates + input [7:0] din, + input up_keyon, + input up_pms, + input up_dt1, + input up_tl, + input up_ks_ar, + input up_amen_dr, + input up_sr, + input up_sl_rr, + input up_ssgeg, + + output reg ch6op, // 1 when the operator belongs to CH6 + output reg [2:0] cur_ch, + output reg [1:0] cur_op, + + // CH3 Effect-mode operation + input effect, + input [10:0] fnum_ch3op2, + input [10:0] fnum_ch3op3, + input [10:0] fnum_ch3op1, + input [ 2:0] block_ch3op2, + input [ 2:0] block_ch3op3, + input [ 2:0] block_ch3op1, + input [ 5:0] latch_fnum, + // Pipeline order + output reg zero, + output s1_enters, + output s2_enters, + output s3_enters, + output s4_enters, + + // Operator + output xuse_prevprev1, + output xuse_internal, + output yuse_internal, + output xuse_prev2, + output yuse_prev1, + output yuse_prev2, + + // PG + output [10:0] fnum_I, + output [ 2:0] block_I, + // channel configuration + output [1:0] rl, + output reg [2:0] fb_II, + output [2:0] alg_I, + // Operator multiplying + output [ 3:0] mul_II, + // Operator detuning + output [ 2:0] dt1_I, + + // EG + output [4:0] ar_I, // attack rate + output [4:0] d1r_I, // decay rate + output [4:0] d2r_I, // sustain rate + output [3:0] rr_I, // release rate + output [3:0] sl_I, // sustain level + output [1:0] ks_II, // key scale + output ssg_en_I, + output [2:0] ssg_eg_I, + output [6:0] tl_IV, + output [2:0] pms_I, + output [1:0] ams_IV, + output amsen_IV, + + // envelope operation + output keyon_I +); + +parameter num_ch=6; // Use only 3 (YM2203/YM2610) or 6 (YM2612/YM2608) + + +reg [1:0] next_op; +reg [2:0] next_ch; +reg last; + +`ifdef SIMULATION +// These signals need to operate during rst +// initial state is not relevant (or critical) in real life +// but we need a clear value during simulation +// This does not work with NCVERILOG +initial begin + cur_op = 2'd0; + cur_ch = 3'd0; + next_op = 2'd0; + next_ch = 3'd1; + last = 1'b0; + zero = 1'b1; +end +`endif + +assign s1_enters = cur_op == 2'b00; +assign s3_enters = cur_op == 2'b01; +assign s2_enters = cur_op == 2'b10; +assign s4_enters = cur_op == 2'b11; + +wire [4:0] next = { next_op, next_ch }; +wire [4:0] cur = { cur_op, cur_ch }; + +wire [2:0] fb_I; + +always @(posedge clk) if( clk_en ) begin + fb_II <= fb_I; + ch6op <= next_ch==3'd6; +end + +// FNUM and BLOCK +wire [10:0] fnum_I_raw; +wire [ 2:0] block_I_raw; +wire effect_on = effect && (cur_ch==3'd2); +wire effect_on_s1 = effect_on && (cur_op == 2'd0 ); +wire effect_on_s3 = effect_on && (cur_op == 2'd1 ); +wire effect_on_s2 = effect_on && (cur_op == 2'd2 ); +wire noeffect = ~|{effect_on_s1, effect_on_s3, effect_on_s2}; +assign fnum_I = ( {11{effect_on_s1}} & fnum_ch3op1 ) | + ( {11{effect_on_s2}} & fnum_ch3op2 ) | + ( {11{effect_on_s3}} & fnum_ch3op3 ) | + ( {11{noeffect}} & fnum_I_raw ); + +assign block_I =( {3{effect_on_s1}} & block_ch3op1 ) | + ( {3{effect_on_s2}} & block_ch3op2 ) | + ( {3{effect_on_s3}} & block_ch3op3 ) | + ( {3{noeffect}} & block_I_raw ); + +wire [4:0] req_opch_I = { op, ch }; +wire [4:0] req_opch_II, req_opch_III, + req_opch_IV, req_opch_V; //, req_opch_VI; + +jt12_sumch #(.num_ch(num_ch)) u_opch_II ( .chin(req_opch_I ), .chout(req_opch_II ) ); +jt12_sumch #(.num_ch(num_ch)) u_opch_III( .chin(req_opch_II ), .chout(req_opch_III) ); +jt12_sumch #(.num_ch(num_ch)) u_opch_IV ( .chin(req_opch_III), .chout(req_opch_IV ) ); +jt12_sumch #(.num_ch(num_ch)) u_opch_V ( .chin(req_opch_IV ), .chout(req_opch_V ) ); +// jt12_sumch #(.num_ch(num_ch)) u_opch_VI ( .chin(req_opch_V ), .chout(req_opch_VI) ); + +wire update_op_I = cur == req_opch_I; +wire update_op_II = cur == req_opch_II; +// wire update_op_III= cur == req_opch_III; +wire update_op_IV = cur == req_opch_IV; +// wire update_op_V = cur == req_opch_V; +// wire update_op_VI = cur == opch_VI; +// wire [2:0] op_plus1 = op+2'd1; +// wire update_op_VII= cur == { op_plus1[1:0], ch }; + +// key on/off +wire [3:0] keyon_op = din[7:4]; +wire [2:0] keyon_ch = din[2:0]; + +always @(*) begin + // next = cur==5'd23 ? 5'd0 : cur +1'b1; + if( num_ch==6 ) begin + next_op = cur_ch==3'd6 ? cur_op+1'b1 : cur_op; + next_ch = cur_ch[1:0]==2'b10 ? cur_ch+2'd2 : cur_ch+1'd1; + end else begin // 3 channels + next_op = cur_ch==3'd2 ? cur_op+1'b1 : cur_op; + next_ch = cur_ch[1:0]==2'b10 ? 3'd0 : cur_ch+1'd1; + end +end + +always @(posedge clk) begin : up_counter + if( clk_en ) begin + { cur_op, cur_ch } <= { next_op, next_ch }; + zero <= next == 5'd0; + end +end + +`ifndef NOFM +jt12_kon #(.num_ch(num_ch)) u_kon( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .keyon_op ( keyon_op ), + .keyon_ch ( keyon_ch ), + .next_op ( next_op ), + .next_ch ( next_ch ), + .up_keyon ( up_keyon ), + .csm ( csm ), + // .flag_A ( flag_A ), + .overflow_A ( overflow_A), + + .keyon_I ( keyon_I ) +); + +jt12_mod #(.num_ch(num_ch)) u_mod( + .alg_I ( alg_I ), + .s1_enters ( s1_enters ), + .s3_enters ( s3_enters ), + .s2_enters ( s2_enters ), + .s4_enters ( s4_enters ), + + .xuse_prevprev1 ( xuse_prevprev1 ), + .xuse_internal ( xuse_internal ), + .yuse_internal ( yuse_internal ), + .xuse_prev2 ( xuse_prev2 ), + .yuse_prev1 ( yuse_prev1 ), + .yuse_prev2 ( yuse_prev2 ) +); + +wire [43:0] shift_out; + +generate + if( num_ch==6 ) begin + // YM2612 / YM3438: Two CSR. + wire [43:0] shift_middle; + + jt12_csr u_csr0( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( din ), + .shift_in ( shift_out ), + .shift_out ( shift_middle ), + .up_tl ( up_tl ), + .up_dt1 ( up_dt1 ), + .up_ks_ar ( up_ks_ar ), + .up_amen_dr ( up_amen_dr ), + .up_sr ( up_sr ), + .up_sl_rr ( up_sl_rr ), + .up_ssgeg ( up_ssgeg ), + .update_op_I ( update_op_I ), + .update_op_II ( update_op_II ), + .update_op_IV ( update_op_IV ) + ); + + wire up_midop_I = { ~cur[4], cur[3:0] } == req_opch_I; + wire up_midop_II = { ~cur[4], cur[3:0] } == req_opch_II; + wire up_midop_IV = { ~cur[4], cur[3:0] } == req_opch_IV; + + jt12_csr u_csr1( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( din ), + .shift_in ( shift_middle ), + .shift_out ( shift_out ), + .up_tl ( up_tl ), + .up_dt1 ( up_dt1 ), + .up_ks_ar ( up_ks_ar ), + .up_amen_dr ( up_amen_dr ), + .up_sr ( up_sr ), + .up_sl_rr ( up_sl_rr ), + .up_ssgeg ( up_ssgeg ), + // update in the middle: + .update_op_I ( up_midop_I ), + .update_op_II ( up_midop_II ), + .update_op_IV ( up_midop_IV ) + ); + end + else begin // YM2203 only has one CSR + jt12_csr u_csr0( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .din ( din ), + .shift_in ( shift_out ), + .shift_out ( shift_out ), + .up_tl ( up_tl ), + .up_dt1 ( up_dt1 ), + .up_ks_ar ( up_ks_ar ), + .up_amen_dr ( up_amen_dr ), + .up_sr ( up_sr ), + .up_sl_rr ( up_sl_rr ), + .up_ssgeg ( up_ssgeg ), + .update_op_I ( update_op_I ), + .update_op_II ( update_op_II ), + .update_op_IV ( update_op_IV ) + ); + end // else +endgenerate + +assign { tl_IV, dt1_I, mul_II, ks_II, + ar_I, amsen_IV, d1r_I, d2r_I, + sl_I, rr_I, ssg_en_I, ssg_eg_I } = shift_out; + + +// memory for CH registers +jt12_reg_ch #(.NUM_CH(num_ch)) u_regch( + .rst ( rst ), + .clk ( clk ), + .cen ( clk_en ), + .din ( ch_din ), + + .up_ch ( ch_sel ), + .latch_fnum ( latch_fnum ), + .up_fnumlo ( up_fnumlo ), + .up_alg ( up_alg ), + .up_pms ( up_pms ), + + .ch ( next_ch ), // next active channel + .block ( block_I_raw ), + .fnum ( fnum_I_raw ), + .fb ( fb_I ), + .alg ( alg_I ), + .rl ( rl ), + .ams_IV ( ams_IV ), + .pms ( pms_I ) +); + +`endif +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg_ch.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg_ch.v new file mode 100644 index 0000000000000000000000000000000000000000..d3f5b2e0a8e8b69ca56177ce082762638d543522 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_reg_ch.v @@ -0,0 +1,128 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 23-10-2019 + */ + +// Channel data is not stored in a CSR as operators +// Proof of that is the Splatter House arcade writes +// channel and operator data in two consequitive accesses +// without enough time in between to have the eight +// channels go through the CSR. So the channel data +// cannot be CSR, but regular registers. +module jt12_reg_ch( + input rst, + input clk, + input cen, + input [ 7:0] din, + + input [ 2:0] up_ch, + input [ 5:0] latch_fnum, + input up_fnumlo, + input up_alg, + input up_pms, + + input [ 2:0] ch, // next active channel + output reg [ 2:0] block, + output reg [10:0] fnum, + output reg [ 2:0] fb, + output reg [ 2:0] alg, + output reg [ 1:0] rl, + output reg [ 1:0] ams_IV, + output reg [ 2:0] pms +); + +parameter NUM_CH=6; +localparam M=NUM_CH==3?2:3; + +reg [ 2:0] reg_block[0:NUM_CH-1]; +reg [10:0] reg_fnum [0:NUM_CH-1]; +reg [ 2:0] reg_fb [0:NUM_CH-1]; +reg [ 2:0] reg_alg [0:NUM_CH-1]; +reg [ 1:0] reg_rl [0:NUM_CH-1]; +reg [ 1:0] reg_ams [0:NUM_CH-1]; +reg [ 2:0] reg_pms [0:NUM_CH-1]; +reg [ 2:0] ch_IV; + +wire [M-1:0] ch_sel, out_sel; + +function [M-1:0] chtr( input [2:0] chin ); +reg [2:0] aux; +begin + aux = chin[M-1] ? {1'b0,chin[1:0]}+3'd3 : // upper channels + {1'b0,chin[1:0]}; // lower + chtr = NUM_CH==3 ? chin[M-1:0] : aux[M-1:0]; + +end +endfunction + +assign ch_sel = chtr(up_ch); +assign out_sel = chtr(ch); + +integer i; +/* verilator lint_off WIDTHEXPAND */ +always @* begin + ch_IV = ch; + if( NUM_CH==6 ) + case(out_sel) + 0: ch_IV = 3; + 1: ch_IV = 4; + 2: ch_IV = 5; + 3: ch_IV = 0; + 4: ch_IV = 1; + 5: ch_IV = 2; + default: ch_IV = 0; + endcase +end +/* verilator lint_on WIDTHEXPAND */ + +always @(posedge clk) if(cen) begin + block <= reg_block[out_sel]; + fnum <= reg_fnum [out_sel]; + fb <= reg_fb [out_sel]; + alg <= reg_alg [out_sel]; + rl <= reg_rl [out_sel]; + ams_IV<= reg_ams [ch_IV[M-1:0]]; + pms <= reg_pms [out_sel]; + if( NUM_CH==3 ) rl <= 3; // YM2203 has no stereo output +end + +always @(posedge clk, posedge rst) begin + if( rst ) for(i=0;i. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 21-03-2019 +*/ + +module jt12_rst( + input rst, + input clk, + output reg rst_n +); + +reg r; + +always @(negedge clk) + if( rst ) begin + r <= 1'b0; + rst_n <= 1'b0; + end else begin + { rst_n, r } <= { r, 1'b1 }; + end + +endmodule // jt12_rst \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh.v new file mode 100644 index 0000000000000000000000000000000000000000..fca2568a9aff76640e551b8474e2eef6ad6fabba --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh.v @@ -0,0 +1,43 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 1-31-2017 + */ + + +// stages must be greater than 2 +module jt12_sh #(parameter width=5, stages=24 ) +( + input clk, + input clk_en /* synthesis direct_enable */, + input [width-1:0] din, + output [width-1:0] drop +); + +reg [stages-1:0] bits[width-1:0]; + +genvar i; +generate + for (i=0; i < width; i=i+1) begin: bit_shifter + always @(posedge clk) if(clk_en) begin + bits[i] <= {bits[i][stages-2:0], din[i]}; + end + assign drop[i] = bits[i][stages-1]; + end +endgenerate + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh24.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh24.v new file mode 100644 index 0000000000000000000000000000000000000000..e597ba511aff4683d612230fe0961ebf1e890b3f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh24.v @@ -0,0 +1,80 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 1-31-2017 + */ + + +module jt12_sh24 #(parameter width=5 ) +( + input clk, + input clk_en /* synthesis direct_enable */, + input [width-1:0] din, + output reg [width-1:0] st1, + output reg [width-1:0] st2, + output reg [width-1:0] st3, + output reg [width-1:0] st4, + output reg [width-1:0] st5, + output reg [width-1:0] st6, + output reg [width-1:0] st7, + output reg [width-1:0] st8, + output reg [width-1:0] st9, + output reg [width-1:0] st10, + output reg [width-1:0] st11, + output reg [width-1:0] st12, + output reg [width-1:0] st13, + output reg [width-1:0] st14, + output reg [width-1:0] st15, + output reg [width-1:0] st16, + output reg [width-1:0] st17, + output reg [width-1:0] st18, + output reg [width-1:0] st19, + output reg [width-1:0] st20, + output reg [width-1:0] st21, + output reg [width-1:0] st22, + output reg [width-1:0] st23, + output reg [width-1:0] st24 +); + +always @(posedge clk) if(clk_en) begin + st24<= st23; + st23<= st22; + st22<= st21; + st21<= st20; + st20<= st19; + st19<= st18; + st18<= st17; + st17<= st16; + st16<= st15; + st15<= st14; + st14<= st13; + st13<= st12; + st12<= st11; + st11<= st10; + st10<= st9; + st9 <= st8; + st8 <= st7; + st7 <= st6; + st6 <= st5; + st5 <= st4; + st4 <= st3; + st3 <= st2; + st2 <= st1; + st1 <= din; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh_rst.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh_rst.v new file mode 100644 index 0000000000000000000000000000000000000000..026d74d874eff742b6953af4b24741c81b33a0a4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sh_rst.v @@ -0,0 +1,45 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 1-31-2017 + */ + + +// stages must be greater than 2 +module jt12_sh_rst #(parameter width=5, stages=32, rstval=1'b0 ) +( + input rst, + input clk, + input clk_en /* synthesis direct_enable */, + input [width-1:0] din, + output [width-1:0] drop +); + +reg [stages-1:0] bits[width-1:0]; +wire [width-1:0] din_mx = rst ? {width{rstval[0]}} : din; + +genvar i; +generate + for (i=0; i < width; i=i+1) begin: bit_shifter + always @(posedge clk) if(clk_en) begin + bits[i] <= {bits[i][stages-2:0], din_mx[i]}; + end + assign drop[i] = bits[i][stages-1]; + end +endgenerate + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_single_acc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_single_acc.v new file mode 100644 index 0000000000000000000000000000000000000000..b3596a2e789eee3a445172903f1d4ebaacd6e45b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_single_acc.v @@ -0,0 +1,62 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 27-1-2017 + +*/ + +// Accumulates an arbitrary number of inputs with saturation +// restart the sum when input "zero" is high + + +module jt12_single_acc #(parameter + win=14, // input data width + wout=16 // output data width +)( + input clk, + input clk_en /* synthesis direct_enable */, + input [win-1:0] op_result, + input sum_en, + input zero, + output reg [wout-1:0] snd +); + +// for full resolution use win=14, wout=16 +// for cut down resolution use win=9, wout=12 +// wout-win should be > 0 + +reg signed [wout-1:0] next, acc, current; +reg overflow; + +wire [wout-1:0] plus_inf = { 1'b0, {(wout-1){1'b1}} }; // maximum positive value +wire [wout-1:0] minus_inf = { 1'b1, {(wout-1){1'b0}} }; // minimum negative value + +always @(*) begin + current = sum_en ? { {(wout-win){op_result[win-1]}}, op_result } : {wout{1'b0}}; + next = zero ? current : current + acc; + overflow = !zero && + (current[wout-1] == acc[wout-1]) && + (acc[wout-1]!=next[wout-1]); +end + +always @(posedge clk) if( clk_en ) begin + acc <= overflow ? (acc[wout-1] ? minus_inf : plus_inf) : next; + if(zero) snd <= acc; +end + +endmodule // jt12_single_acc \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sumch.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sumch.v new file mode 100644 index 0000000000000000000000000000000000000000..fde798b7e81f88f9984a39fe02b7559c0e9e4e93 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_sumch.v @@ -0,0 +1,46 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 1-31-2017 + */ + + +/* The input is {op[1:0], ch[2:0]} + it adds 1 to the channel and overflow to the operator correctly */ + +module jt12_sumch +( + input [4:0] chin, + output reg [4:0] chout +); + +parameter num_ch=6; + +reg [2:0] aux; + +always @(*) begin + aux = chin[2:0] + 3'd1; + if( num_ch==6 ) begin + chout[2:0] = aux[1:0]==2'b11 ? aux+3'd1 : aux; + chout[4:3] = chin[2:0]==3'd6 ? chin[4:3]+2'd1 : chin[4:3]; // next operator + end else begin // 3 channels + chout[2:0] = aux[1:0]==2'b11 ? 3'd0 : aux; + chout[4:3] = chin[2:0]==3'd2 ? chin[4:3]+2'd1 : chin[4:3]; // next operator + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_timers.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_timers.v new file mode 100644 index 0000000000000000000000000000000000000000..9b6cd96a45c14d3cdc5cf72cf5662704ccfd0c38 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_timers.v @@ -0,0 +1,140 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2017 + + YM3438_APL.pdf + Timer A = 144*(1024-NA)/Phi M + Timer B = 2304*(256-NB)/Phi M + */ + + +module jt12_timers( + input clk, + input rst, + input clk_en /* synthesis direct_enable */, + input zero, + input [9:0] value_A, + input [7:0] value_B, + input load_A, + input load_B, + input clr_flag_A, + input clr_flag_B, + input enable_irq_A, + input enable_irq_B, + output flag_A, + output flag_B, + output overflow_A, + output irq_n +); + +parameter num_ch = 6; + +assign irq_n = ~( (flag_A&enable_irq_A) | (flag_B&enable_irq_B) ); + +/* +reg zero2; + +always @(posedge clk, posedge rst) begin + if( rst ) + zero2 <= 0; + else if(clk_en) begin + if( zero ) zero2 <= ~zero; + end +end + +wire zero = num_ch == 6 ? zero : (zero2&zero); +*/ +jt12_timer #(.CW(10)) timer_A( + .clk ( clk ), + .rst ( rst ), + .cen ( clk_en ), + .zero ( zero ), + .start_value( value_A ), + .load ( load_A ), + .clr_flag ( clr_flag_A ), + .flag ( flag_A ), + .overflow ( overflow_A ) +); + +jt12_timer #(.CW(8),.FREE_EN(1)) timer_B( + .clk ( clk ), + .rst ( rst ), + .cen ( clk_en ), + .zero ( zero ), + .start_value( value_B ), + .load ( load_B ), + .clr_flag ( clr_flag_B ), + .flag ( flag_B ), + .overflow ( ) +); + +endmodule + +module jt12_timer #(parameter + CW = 8, // counter bit width. This is the counter that can be loaded + FW = 4, // number of bits for the free-running counter + FREE_EN = 0 // enables a 4-bit free enable count +) ( + input rst, + input clk, + input cen, + input zero, + input [CW-1:0] start_value, + input load, + input clr_flag, + output reg flag, + output reg overflow +); +/* verilator lint_off WIDTH */ +reg load_l; +reg [CW-1:0] cnt, next; +reg [FW-1:0] free_cnt, free_next; +reg free_ov; + +always@(posedge clk, posedge rst) + if( rst ) + flag <= 1'b0; + else /*if(cen)*/ begin + if( clr_flag ) + flag <= 1'b0; + else if( cen && zero && load && overflow ) flag<=1'b1; + end + +always @(*) begin + {free_ov, free_next} = { 1'b0, free_cnt} + 1'b1; + {overflow, next } = { 1'b0, cnt } + (FREE_EN ? free_ov : 1'b1); +end + +always @(posedge clk) begin + load_l <= load; + if( !load_l && load ) begin + cnt <= start_value; + end else if( cen && zero && load ) + cnt <= overflow ? start_value : next; +end + +// Free running counter +always @(posedge clk) begin + if( rst ) begin + free_cnt <= 0; + end else if( cen && zero ) begin + free_cnt <= free_next; + end +end +/* verilator lint_on WIDTH */ +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_top.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_top.v new file mode 100644 index 0000000000000000000000000000000000000000..8bdac2dc39f714d4d76fcab1017ce77f75b53c94 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/jt12_top.v @@ -0,0 +1,706 @@ +/* This file is part of JT12. + + JT12 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 14-2-2016 + + Based on information posted by Nemesis on: +http://gendev.spritesmind.net/forum/viewtopic.php?t=386&postdays=0&postorder=asc&start=167 + + Based on jt51_phasegen.v, from JT51 + + */ + +module jt12_top ( + input rst, // rst should be at least 6 clk&cen cycles long + input clk, // CPU clock + (* direct_enable *) input cen, // optional clock enable, if not needed leave as 1'b1 + input [7:0] din, + input [1:0] addr, + input cs_n, + input wr_n, + + output [7:0] dout, + output irq_n, + // Configuration + input en_hifi_pcm, // high to enable PCM interpolation on YM2612 mode + // ADPCM pins + output [19:0] adpcma_addr, // real hardware has 10 pins multiplexed through RMPX pin + output [ 4:0] adpcma_bank, + output adpcma_roe_n, // ADPCM-A ROM output enable + input [ 7:0] adpcma_data, // Data from RAM + output [23:0] adpcmb_addr, // real hardware has 12 pins multiplexed through PMPX pin + input [ 7:0] adpcmb_data, + output adpcmb_roe_n, // ADPCM-B ROM output enable + // I/O pins used by YM2203 embedded YM2149 chip + input [7:0] IOA_in, + input [7:0] IOB_in, + output [7:0] IOA_out, + output [7:0] IOB_out, + output IOA_oe, + output IOB_oe, + // Separated output + output [ 7:0] psg_A, + output [ 7:0] psg_B, + output [ 7:0] psg_C, + output signed [15:0] fm_snd_left, + output signed [15:0] fm_snd_right, + output signed [15:0] adpcmA_l, + output signed [15:0] adpcmA_r, + output signed [15:0] adpcmB_l, + output signed [15:0] adpcmB_r, + // combined output + output [ 9:0] psg_snd, + output signed [15:0] snd_right, // FM+PSG + output signed [15:0] snd_left, // FM+PSG + output snd_sample, + input [3:0] snd_enable, + input [ 5:0] ch_enable, // ADPCM-A channels + input [ 7:0] debug_bus, + output [ 7:0] debug_view +); + +// parameters to select the features for each chip type +// defaults to YM2612 +parameter use_lfo=1, use_ssg=0, num_ch=6, use_pcm=1; +parameter use_adpcm=0; +parameter JT49_DIV=2, + YM2203_LUMPED=0; +parameter mask_div=1; + +wire flag_A, flag_B, busy; + +wire write = !cs_n && !wr_n; +wire clk_en, clk_en_ssg; + +// Timers +wire [9:0] value_A; +wire [7:0] value_B; +wire load_A, load_B; +wire enable_irq_A, enable_irq_B; +wire clr_flag_A, clr_flag_B; +wire overflow_A; +wire fast_timers; + +wire zero; // Single-clock pulse at the begginig of s1_enters +// LFO +wire [2:0] lfo_freq; +wire lfo_en; +// Operators +wire amsen_IV; +wire [ 2:0] dt1_I; +wire [ 3:0] mul_II; +wire [ 6:0] tl_IV; + +wire [ 4:0] keycode_II; +wire [ 4:0] ar_I; +wire [ 4:0] d1r_I; +wire [ 4:0] d2r_I; +wire [ 3:0] rr_I; +wire [ 3:0] sl_I; +wire [ 1:0] ks_II; +// SSG operation +wire ssg_en_I; +wire [2:0] ssg_eg_I; +// envelope operation +wire keyon_I; +wire [9:0] eg_IX; +wire pg_rst_II; +// Channel +wire [10:0] fnum_I; +wire [ 2:0] block_I; +wire [ 1:0] rl; +wire [ 2:0] fb_II; +wire [ 2:0] alg_I; +wire [ 2:0] pms_I; +wire [ 1:0] ams_IV; +// PCM +wire pcm_en, pcm_wr; +wire [ 8:0] pcm; +// Test +wire pg_stop, eg_stop; + +wire ch6op; +wire [ 2:0] cur_ch; +wire [ 1:0] cur_op; + +// Operator +wire xuse_internal, yuse_internal; +wire xuse_prevprev1, xuse_prev2, yuse_prev1, yuse_prev2; +wire [ 9:0] phase_VIII; +wire s1_enters, s2_enters, s3_enters, s4_enters; +wire rst_int; +// LFO +wire [6:0] lfo_mod; +wire lfo_rst; +// PSG +wire [3:0] psg_addr; +wire [7:0] psg_data, psg_dout; +wire psg_wr_n; +// ADPCM-A +wire [16:0] addr_a; +wire [ 2:0] up_addr, up_lracl; +wire up_start, up_end; +wire [ 7:0] aon_a, lracl; +wire [ 5:0] atl_a; // ADPCM Total Level +wire up_aon; +// APDCM-B +wire acmd_on_b; // Control - Process start, Key On +wire acmd_rep_b; // Control - Repeat +wire acmd_rst_b; // Control - Reset +wire acmd_up_b; // Control - New cmd received +wire [ 1:0] alr_b; // Left / Right +wire [15:0] astart_b; // Start address +wire [15:0] aend_b; // End address +wire [15:0] adeltan_b; // Delta-N +wire [ 7:0] aeg_b; // Envelope Generator Control +wire [ 5:0] adpcma_flags; // ADPMC-A read over flags +wire adpcmb_flag; +wire [ 6:0] flag_ctl; +wire [ 1:0] div_setting; + +wire clk_en_2, clk_en_666, clk_en_111, clk_en_55; +wire signed [15:0] adpcmAt_l; +wire signed [15:0] adpcmAt_r; +wire signed [15:0] adpcmBt_l; +wire signed [15:0] adpcmBt_r; +assign adpcmA_l = snd_enable[1] ? adpcmAt_l : 16'd0; +assign adpcmA_r = snd_enable[1] ? adpcmAt_r : 16'd0; +assign adpcmB_l = snd_enable[2] ? adpcmBt_l : 16'd0; +assign adpcmB_r = snd_enable[2] ? adpcmBt_r : 16'd0; +wire [13:0] op_result_hdt; +assign op_result_hd = snd_enable[0] ? op_result_hdt : 14'd0; + +assign debug_view = { 4'd0, flag_B, flag_A, div_setting }; + +generate +if( use_adpcm==1 ) begin: gen_adpcm + wire rst_n; + + jt12_rst u_rst( + .rst ( rst ), + .clk ( clk ), + .rst_n ( rst_n ) + ); + + jt10_adpcm_drvA u_adpcm_a( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen ), + .cen6 ( clk_en_666 ), // clk & cen must be 666 kHz + .cen1 ( clk_en_111 ), // clk & cen must be 111 kHz + + .addr ( adpcma_addr ), // real hardware has 10 pins multiplexed through RMPX pin + .bank ( adpcma_bank ), + .roe_n ( adpcma_roe_n ), // ADPCM-A ROM output enable + .datain ( adpcma_data ), + + // Control Registers + .atl ( atl_a ), // ADPCM Total Level + .addr_in ( addr_a ), + .lracl_in ( lracl ), + .up_start ( up_start ), + .up_end ( up_end ), + .up_addr ( up_addr ), + .up_lracl ( up_lracl ), + + .aon_cmd ( aon_a ), // ADPCM ON equivalent to key on for FM + .up_aon ( up_aon ), + // Flags + .flags ( adpcma_flags ), + .clr_flags ( flag_ctl[5:0] ), + + .pcm55_l ( adpcmAt_l ), + .pcm55_r ( adpcmAt_r ), + .ch_enable ( ch_enable ) + ); + + jt10_adpcm_drvB u_adpcm_b( + .rst_n ( rst_n ), + .clk ( clk ), + .cen ( cen ), + .cen55 ( clk_en_55 ), + + // Control + .acmd_on_b ( acmd_on_b ), // Control - Process start, Key On + .acmd_rep_b ( acmd_rep_b ), // Control - Repeat + .acmd_rst_b ( acmd_rst_b ), // Control - Reset + .acmd_up_b ( acmd_up_b ), // Control - New command received + .alr_b ( alr_b ), // Left / Right + .astart_b ( astart_b ), // Start address + .aend_b ( aend_b ), // End address + .adeltan_b ( adeltan_b ), // Delta-N + .aeg_b ( aeg_b ), // Envelope Generator Control + // Flag + .flag ( adpcmb_flag ), + .clr_flag ( flag_ctl[6] ), + // memory + .addr ( adpcmb_addr ), + .data ( adpcmb_data ), + .roe_n ( adpcmb_roe_n ), + + .pcm55_l ( adpcmBt_l ), + .pcm55_r ( adpcmBt_r ) + ); + + assign snd_sample = zero; + jt10_acc u_acc( + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( op_result_hd ), + .rl ( rl ), + .zero ( zero ), + .s1_enters ( s2_enters ), + .s2_enters ( s1_enters ), + .s3_enters ( s4_enters ), + .s4_enters ( s3_enters ), + .cur_ch ( cur_ch ), + .cur_op ( cur_op ), + .alg ( alg_I ), + .adpcmA_l ( adpcmA_l ), + .adpcmA_r ( adpcmA_r ), + .adpcmB_l ( adpcmB_l ), + .adpcmB_r ( adpcmB_r ), + // combined output + .left ( fm_snd_left ), + .right ( fm_snd_right ) + ); +end else begin : gen_adpcm_no + assign adpcmA_l = 'd0; + assign adpcmA_r = 'd0; + assign adpcmB_l = 'd0; + assign adpcmB_r = 'd0; + assign adpcma_addr = 'd0; + assign adpcma_bank = 'd0; + assign adpcma_roe_n = 'b1; + assign adpcmb_addr = 'd0; + assign adpcmb_roe_n = 'd1; + assign adpcma_flags = 0; + assign adpcmb_flag = 0; +end +endgenerate + +jt12_dout #(.use_ssg(use_ssg),.use_adpcm(use_adpcm)) u_dout( +// .rst_n ( rst_n ), + .clk ( clk ), // CPU clock + .flag_A ( flag_A ), + .flag_B ( flag_B ), + .busy ( busy ), + .adpcma_flags ( adpcma_flags ), + .adpcmb_flag ( adpcmb_flag ), + .psg_dout ( psg_dout ), + .addr ( addr ), + .dout ( dout ) +); + +jt12_mmr #(.use_ssg(use_ssg),.num_ch(num_ch),.use_pcm(use_pcm), .use_adpcm(use_adpcm), .mask_div(mask_div)) + u_mmr( + .rst ( rst ), + .clk ( clk ), + .cen ( cen ), // external clock enable + .clk_en ( clk_en ), // internal clock enable + .clk_en_2 ( clk_en_2 ), // input cen divided by 2 + .clk_en_ssg ( clk_en_ssg), // internal clock enable + .clk_en_666 ( clk_en_666), + .clk_en_111 ( clk_en_111), + .clk_en_55 ( clk_en_55 ), + .din ( din ), + .write ( write ), + .addr ( addr ), + .busy ( busy ), + .ch6op ( ch6op ), + .cur_ch ( cur_ch ), + .cur_op ( cur_op ), + // LFO + .lfo_freq ( lfo_freq ), + .lfo_en ( lfo_en ), + // Timers + .value_A ( value_A ), + .value_B ( value_B ), + .load_A ( load_A ), + .load_B ( load_B ), + .enable_irq_A ( enable_irq_A ), + .enable_irq_B ( enable_irq_B ), + .clr_flag_A ( clr_flag_A ), + .clr_flag_B ( clr_flag_B ), + .flag_A ( flag_A ), + .overflow_A ( overflow_A ), + .fast_timers( fast_timers ), + // PCM + .pcm ( pcm ), + .pcm_en ( pcm_en ), + .pcm_wr ( pcm_wr ), + // ADPCM-A + .aon_a ( aon_a ), // ON + .atl_a ( atl_a ), // TL + .addr_a ( addr_a ), // address latch + .lracl ( lracl ), // L/R ADPCM Channel Level + .up_start ( up_start ), // write enable start address latch + .up_end ( up_end ), // write enable end address latch + .up_addr ( up_addr ), // write enable end address latch + .up_lracl ( up_lracl ), + .up_aon ( up_aon ), + // ADPCM-B + .acmd_on_b ( acmd_on_b ), // Control - Process start, Key On + .acmd_rep_b ( acmd_rep_b ), // Control - Repeat + .acmd_rst_b ( acmd_rst_b ), // Control - Reset + .acmd_up_b ( acmd_up_b ), // Control - New command received + .alr_b ( alr_b ), // Left / Right + .astart_b ( astart_b ), // Start address + .aend_b ( aend_b ), // End address + .adeltan_b ( adeltan_b ), // Delta-N + .aeg_b ( aeg_b ), // Envelope Generator Control + .flag_ctl ( flag_ctl ), + // Operator + .xuse_prevprev1 ( xuse_prevprev1 ), + .xuse_internal ( xuse_internal ), + .yuse_internal ( yuse_internal ), + .xuse_prev2 ( xuse_prev2 ), + .yuse_prev1 ( yuse_prev1 ), + .yuse_prev2 ( yuse_prev2 ), + // PG + .fnum_I ( fnum_I ), + .block_I ( block_I ), + .pg_stop ( pg_stop ), + // EG + .rl ( rl ), + .fb_II ( fb_II ), + .alg_I ( alg_I ), + .pms_I ( pms_I ), + .ams_IV ( ams_IV ), + .amsen_IV ( amsen_IV ), + .dt1_I ( dt1_I ), + .mul_II ( mul_II ), + .tl_IV ( tl_IV ), + + .ar_I ( ar_I ), + .d1r_I ( d1r_I ), + .d2r_I ( d2r_I ), + .rr_I ( rr_I ), + .sl_I ( sl_I ), + .ks_II ( ks_II ), + + .eg_stop ( eg_stop ), + // SSG operation + .ssg_en_I ( ssg_en_I ), + .ssg_eg_I ( ssg_eg_I ), + + .keyon_I ( keyon_I ), + // Operator + .zero ( zero ), + .s1_enters ( s1_enters ), + .s2_enters ( s2_enters ), + .s3_enters ( s3_enters ), + .s4_enters ( s4_enters ), + // PSG interace + .psg_addr ( psg_addr ), + .psg_data ( psg_data ), + .psg_wr_n ( psg_wr_n ), + .debug_bus ( debug_bus ), + .div_setting(div_setting) +); + +// YM2203 seems to use a fixed cen/3 clock for the timers, regardless +// of the prescaler setting +wire timer_cen = fast_timers ? cen : clk_en; +jt12_timers #(.num_ch(num_ch)) u_timers ( + .clk ( clk ), + .clk_en ( timer_cen ), + .rst ( rst ), + .zero ( zero ), + .value_A ( value_A ), + .value_B ( value_B ), + .load_A ( load_A ), + .load_B ( load_B ), + .enable_irq_A( enable_irq_A ), + .enable_irq_B( enable_irq_B ), + .clr_flag_A ( clr_flag_A ), + .clr_flag_B ( clr_flag_B ), + .flag_A ( flag_A ), + .flag_B ( flag_B ), + .overflow_A ( overflow_A ), + .irq_n ( irq_n ) +); + +// YM2203 does not have LFO +generate +if( use_lfo== 1) begin : gen_lfo + jt12_lfo u_lfo( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .zero ( zero ), + `ifdef NOLFO + .lfo_rst ( 1'b1 ), + `else + .lfo_rst ( 1'b0 ), + `endif + .lfo_en ( lfo_en ), + .lfo_freq ( lfo_freq ), + .lfo_mod ( lfo_mod ) + ); +end else begin : gen_nolfo + assign lfo_mod = 7'd0; +end +endgenerate + +// YM2203/YM2610 have a PSG + +`ifndef NOSSG +generate + if( use_ssg==1 ) begin : gen_ssg + jt49 #(.COMP(3'b01), .CLKDIV(JT49_DIV), .YM2203_LUMPED(YM2203_LUMPED)) + u_psg( // note that input ports are not multiplexed + .rst_n ( ~rst ), + .clk ( clk ), // signal on positive edge + .clk_en ( clk_en_ssg), // clock enable on negative edge + .addr ( psg_addr ), + .cs_n ( 1'b0 ), + .wr_n ( psg_wr_n ), // write + .din ( psg_data ), + .sound ( psg_snd ), // combined output + .A ( psg_A ), + .B ( psg_B ), + .C ( psg_C ), + .dout ( psg_dout ), + .sel ( 1'b1 ), // half clock speed + .IOA_out ( IOA_out ), + .IOB_out ( IOB_out ), + .IOA_in ( IOA_in ), + .IOB_in ( IOB_in ), + .IOA_oe ( IOA_oe ), + .IOB_oe ( IOB_oe ), + // Unused: + .sample ( ) + ); + assign snd_left = snd_enable[3] ? fm_snd_left + { 1'b0, psg_snd[9:0],5'd0} : fm_snd_left; + assign snd_right = snd_enable[3] ? fm_snd_right + { 1'b0, psg_snd[9:0],5'd0} : fm_snd_right; + end else begin : gen_nossg + assign psg_snd = 10'd0; + assign snd_left = fm_snd_left; + assign snd_right= fm_snd_right; + assign psg_dout = 8'd0; + assign psg_A = 8'd0; + assign psg_B = 8'd0; + assign psg_C = 8'd0; + assign IOA_oe = 0; + assign IOB_oe = 0; + assign IOA_out = 0; + assign IOB_out = 0; + end +endgenerate +`else + assign psg_snd = 10'd0; + assign snd_left = fm_snd_left; + assign snd_right= fm_snd_right; + assign psg_dout = 8'd0; +`endif + +wire [ 8:0] op_result; +wire [13:0] op_result_hd; +`ifndef NOFM + +jt12_pg #(.num_ch(num_ch)) u_pg( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + // Channel frequency + .fnum_I ( fnum_I ), + .block_I ( block_I ), + // Operator multiplying + .mul_II ( mul_II ), + // Operator detuning + .dt1_I ( dt1_I ), // same as JT51's DT1 + // Phase modulation by LFO + .lfo_mod ( lfo_mod ), + .pms_I ( pms_I ), + // phase operation + .pg_rst_II ( pg_rst_II ), + .pg_stop ( pg_stop ), + .keycode_II ( keycode_II ), + .phase_VIII ( phase_VIII ) +); + +wire [9:0] eg_V; + +jt12_eg #(.num_ch(num_ch)) u_eg( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .zero ( zero ), + .eg_stop ( eg_stop ), + // envelope configuration + .keycode_II ( keycode_II ), + .arate_I ( ar_I ), // attack rate + .rate1_I ( d1r_I ), // decay rate + .rate2_I ( d2r_I ), // sustain rate + .rrate_I ( rr_I ), // release rate + .sl_I ( sl_I ), // sustain level + .ks_II ( ks_II ), // key scale + // SSG operation + .ssg_en_I ( ssg_en_I ), + .ssg_eg_I ( ssg_eg_I ), + // envelope operation + .keyon_I ( keyon_I ), + // envelope number + .lfo_mod ( lfo_mod ), + .tl_IV ( tl_IV ), + .ams_IV ( ams_IV ), + .amsen_IV ( amsen_IV ), + + .eg_V ( eg_V ), + .pg_rst_II ( pg_rst_II ) +); + +jt12_sh #(.width(10),.stages(4)) u_egpad( + .clk ( clk ), + .clk_en ( clk_en ), + .din ( eg_V ), + .drop ( eg_IX ) +); + +jt12_op #(.num_ch(num_ch)) u_op( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .pg_phase_VIII ( phase_VIII ), + .eg_atten_IX ( eg_IX ), + .fb_II ( fb_II ), + + .test_214 ( 1'b0 ), + .s1_enters ( s1_enters ), + .s2_enters ( s2_enters ), + .s3_enters ( s3_enters ), + .s4_enters ( s4_enters ), + .xuse_prevprev1 ( xuse_prevprev1), + .xuse_internal ( xuse_internal ), + .yuse_internal ( yuse_internal ), + .xuse_prev2 ( xuse_prev2 ), + .yuse_prev1 ( yuse_prev1 ), + .yuse_prev2 ( yuse_prev2 ), + .zero ( zero ), + .op_result ( op_result ), + .full_result ( op_result_hdt ) +); +`else +assign op_result = 'd0; +assign op_result_hdt = 'd0; +`endif + +generate + if( use_pcm==1 ) begin: gen_pcm_acc // YM2612 accumulator + assign fm_snd_right[3:0] = 4'd0; + assign fm_snd_left [3:0] = 4'd0; + assign snd_sample = zero; + reg signed [8:0] pcm2; + + // interpolate PCM samples with automatic sample rate detection + // this feature is not present in original YM2612 + // this improves PCM sample sound greatly + /* + jt12_pcm u_pcm( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .zero ( zero ), + .pcm ( pcm ), + .pcm_wr ( pcm_wr ), + .pcm_resampled ( pcm2 ) + ); + */ + wire rst_pcm_n; + + jt12_rst u_rst_pcm( + .rst ( rst ), + .clk ( clk ), + .rst_n ( rst_pcm_n ) + ); + + `ifndef NOPCMLINEAR + wire signed [10:0] pcm_full; + always @(*) + pcm2 = en_hifi_pcm ? pcm_full[9:1] : pcm; + + jt12_pcm_interpol #(.DW(11), .stepw(5)) u_pcm ( + .rst_n ( rst_pcm_n ), + .clk ( clk ), + .cen ( clk_en ), + .cen55 ( clk_en_55 ), + .pcm_wr( pcm_wr ), + .pcmin ( {pcm[8],pcm, 1'b0} ), + .pcmout( pcm_full ) + ); + `else + assign pcm2 = pcm; + `endif + + jt12_acc u_acc( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( op_result ), + .rl ( rl ), + // note that the order changes to deal + // with the operator pipeline delay + .zero ( zero ), + .s1_enters ( s2_enters ), + .s2_enters ( s1_enters ), + .s3_enters ( s4_enters ), + .s4_enters ( s3_enters ), + .ch6op ( ch6op ), + .pcm_en ( pcm_en ), // only enabled for channel 6 + .pcm ( pcm2 ), + .alg ( alg_I ), + // combined output + .left ( fm_snd_left [15:4] ), + .right ( fm_snd_right[15:4] ) + ); + end + if( use_pcm==0 && use_adpcm==0 ) begin : gen_2203_acc // YM2203 accumulator + wire signed [15:0] mono_snd; + assign fm_snd_left = mono_snd; + assign fm_snd_right = mono_snd; + assign snd_sample = zero; + jt03_acc u_acc( + .rst ( rst ), + .clk ( clk ), + .clk_en ( clk_en ), + .op_result ( op_result_hd ), + // note that the order changes to deal + // with the operator pipeline delay + .s1_enters ( s1_enters ), + .s2_enters ( s2_enters ), + .s3_enters ( s3_enters ), + .s4_enters ( s4_enters ), + .alg ( alg_I ), + .zero ( zero ), + // combined output + .snd ( mono_snd ) + ); + end +endgenerate + +`ifdef SIMULATION +integer fsnd; +initial begin + fsnd=$fopen("jt12.raw","wb"); +end + +always @(posedge zero) begin + $fwrite(fsnd,"%u", {snd_left, snd_right}); +end +`endif +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_comb.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..dfd390e6df78851b1508815c3eda6d3ebe2908b4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_comb.v @@ -0,0 +1,59 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-12-2018 + +*/ + +module jt12_comb #(parameter + w=16, // bit width + m=1 // depth of comb filter +)( + input rst, + input clk, +(* direct_enable *) input cen, + input signed [w-1:0] snd_in, + output reg signed [w-1:0] snd_out +); + +wire signed [w-1:0] prev; + +// m-delay stage +generate + genvar k; + reg signed [w-1:0] mem[0:m-1]; + assign prev=mem[m-1]; + for(k=0;k. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-12-2018 + +*/ + +module jt12_decim #(parameter calcw=18, inw=16, + n=2, // number of stages + m=1, // depth of comb filter + rate=2 // it will stuff with as many as (rate-1) zeros +)( + input rst, + input clk, +(* direct_enable *) input cen_in, +(* direct_enable *) input cen_out, + input signed [inw-1:0] snd_in, + output reg signed [inw-1:0] snd_out +); + +reg signed [calcw-1:0] inter6; +wire signed [calcw-1:0] integ_op, comb_op; +localparam wdiff = calcw - inw; + +// integrator at clk x cen sampling rate +generate + genvar k2; + reg [calcw-1:0] integ_data[0:n]; + assign integ_op = integ_data[n]; + always @(*) + integ_data[0] = { {wdiff{snd_in[inw-1]}}, snd_in }; + for(k2=1;k2<=n;k2=k2+1) begin : integ_gen + always @(posedge clk) + if(rst) begin + integ_data[k2] <= {calcw{1'b0}}; + end else if(cen_in) begin + integ_data[k2] <= integ_data[k2] + integ_data[k2-1]; + end + end +endgenerate + +// interpolator +always @(posedge clk) + if(rst) begin + inter6 <= {calcw{1'b0}}; + end else if(cen_out) begin + inter6 <= integ_op; + end + +generate + genvar k; + wire [calcw-1:0] comb_data[0:n]; + assign comb_data[0] = inter6; + assign comb_op = comb_data[n]; + for(k=0;k. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 11-12-2018 + + Each channel can use the full range of the DAC as they do not + get summed in the real chip. + + Operator data is summed up without adding extra bits. This is + the case of real YM3438, which was used on Megadrive 2 models. + +*/ + +/* rate up-scaler for FM+PSG channel +*/ + +module jt12_fm_uprate( + input rst, + input clk, + input signed [15:0] fm_snd, + input signed [11:0] psg_snd, + input fm_en, // enable FM + input cen_1008, + input cen_252, + input cen_63, + input cen_9, + output signed [15:0] snd // Mixed sound at clk sample rate +); + +wire signed [15:0] fm2,fm3,fm4; +reg signed [15:0] mix_sum, mixed, fmin, psgin; +reg ov; + +always @* begin + fmin = fm_en?fm_snd:16'd0; + psgin = {{1{psg_snd[11]}},psg_snd,3'b0}; + mix_sum = fmin + psgin; + ov = &{fmin[15],psgin[15],~mix_sum[15]} | &{~fmin[15],~psgin[15],mix_sum[15]}; +end + +always @(posedge clk) begin + mixed <= ov ? {fmin[15],{15{~fmin[15]}}} : mix_sum; +end + +// 1008 --> 252 x4 +jt12_interpol #(.calcw(17),.inw(16),.rate(4),.m(1),.n(1)) +u_fm2( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen_1008 ), + .cen_out( cen_252 ), + .snd_in ( mixed ), + .snd_out( fm2 ) +); + +// 252 --> 63 x4 +jt12_interpol #(.calcw(19),.inw(16),.rate(4),.m(1),.n(3)) +u_fm3( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen_252 ), + .cen_out( cen_63 ), + .snd_in ( fm2 ), + .snd_out( fm3 ) +); + +// 63 --> 9 x7 +jt12_interpol #(.calcw(21),.inw(16),.rate(7),.m(2),.n(2)) +u_fm4( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen_63 ), + .cen_out( cen_9 ), + .snd_in ( fm3 ), + .snd_out( fm4 ) +); + +// 9 --> 1 x9 +jt12_interpol #(.calcw(21),.inw(16),.rate(9),.m(2),.n(2)) +u_fm5( + .clk ( clk ), + .rst ( rst ), + .cen_in ( cen_9 ), + .cen_out( 1'b1 ), + .snd_in ( fm4 ), + .snd_out( snd ) +); + +endmodule // jt12_fm_uprate \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_genmix.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_genmix.v new file mode 100644 index 0000000000000000000000000000000000000000..1963fdcd42b2ea029df1cc00470ea883168b669b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_genmix.v @@ -0,0 +1,180 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 11-12-2018 + + Each channel can use the full range of the DAC as they do not + get summed in the real chip. + + Operator data is summed up without adding extra bits. This is + the case of real YM3438, which was used on Megadrive 2 models. + +*/ + +/* Mixer for Megadrive/Genesis + cen_fm must be 1 over 7 of clk + psg_cen_240 must be 1 over 15 of clk + PSG and FM signals are interpolated up to clk sample rate. +*/ + +module jt12_genmix( + input rst, + input clk, + input signed [15:0] fm_left, + input signed [15:0] fm_right, + input signed [10:0] psg_snd, + input fm_en, // enable FM + input psg_en, // enable PSG + // Mixed sound at clk sample rate + output signed [15:0] snd_left, + output signed [15:0] snd_right +); + +///////////////////////////////////////////////// +// PSG +// x5 -> div 3 -> div 7 +// 54MHz count up to: +// orig -> 16*15 = 240 +// x5 -> 16*15/5 = 48 +// div 3 -> 48*3 = 144 +// div 7 -> 144*7 = 1008 <=> fm_sample +// 48 x 5 = 240, +reg [5:0] psgcnt48; +reg [2:0] psgcnt240, psgcnt1008; +reg [1:0] psgcnt144; + +always @(posedge clk) + if( rst ) begin + psgcnt48 <= 6'd0; + psgcnt240 <= 3'd0; + psgcnt144 <= 2'd0; + psgcnt1008<= 3'd0; + end else begin + psgcnt48 <= psgcnt48 ==6'd47 ? 6'd0 : psgcnt48 +6'd1; + if( psgcnt48 == 6'd47 ) begin + psgcnt240 <= psgcnt240==3'd4 ? 3'd0 : psgcnt240+3'd1; + psgcnt144 <= psgcnt144 ==2'd2 ? 2'd0 : psgcnt144+2'd1; + if( psgcnt144==2'd0 ) + psgcnt1008 <= psgcnt1008==3'd6 ? 3'd0 : psgcnt1008+3'd1; + end + end + +reg psg_cen_1008, psg_cen_240, psg_cen_48, psg_cen_144; +always @(posedge clk) begin + psg_cen_240 <= psgcnt48 ==6'd47 && psgcnt240 == 3'd0; + psg_cen_48 <= psgcnt48 ==6'd47; + psg_cen_144 <= psgcnt48 ==6'd47 && psgcnt144==2'd0; + psg_cen_1008<= psgcnt48 ==6'd47 && psgcnt144==2'd0 && psgcnt1008==3'd0; +end + +wire signed [11:0] psg0, psg1, psg2, psg3; +assign psg0 = psg_en ? { psg_snd[10], psg_snd } : 12'b0; + +// 48 +jt12_interpol #(.calcw(19),.inw(12),.rate(5),.m(4),.n(2)) +u_psg1( + .clk ( clk ), + .rst ( rst ), + .cen_in ( psg_cen_240 ), + .cen_out( psg_cen_48 ), + .snd_in ( psg0 ), + .snd_out( psg1 ) +); + +// 144 +jt12_decim #(.calcw(19),.inw(12),.rate(3),.m(2),.n(3) ) +u_psg2( + .clk ( clk ), + .rst ( rst ), + .cen_in ( psg_cen_48 ), + .cen_out( psg_cen_144 ), + .snd_in ( psg1 ), + .snd_out( psg2 ) +); + +// 1008 +jt12_decim #(.calcw(15),.inw(12),.rate(7),.m(1),.n(1) ) +u_psg3( + .clk ( clk ), + .rst ( rst ), + .cen_in ( psg_cen_144 ), + .cen_out( psg_cen_1008), + .snd_in ( psg2 ), + .snd_out( psg3 ) +); + +///////////////////////////////////////////////// +// FM +// x4 -> x4 -> x7 -> x9 +// 54MHz count up to: +// 252 -> 63 -> 9 -> 1 +reg [1:0] clkcnt252, clkcnt1008; +reg [2:0] clkcnt63; +reg [3:0] clkcnt9; +always @(posedge clk) + if( rst ) begin + clkcnt1008<= 2'd0; + clkcnt252 <= 2'd0; + clkcnt63 <= 3'd0; + clkcnt9 <= 4'd0; + end else begin + clkcnt9 <= clkcnt9 ==4'd8 ? 4'd0 : clkcnt9 +4'd1; + if( clkcnt9== 4'd8 ) begin + clkcnt63 <= clkcnt63 ==3'd6 ? 3'd0 : clkcnt63 +3'd1; + if( clkcnt63==3'd6 ) begin + clkcnt252 <= clkcnt252+2'd1; + if(clkcnt252==2'd3) clkcnt1008<=clkcnt1008+2'd1; + end + end + end +// evenly spaced clock enable signals +reg cen_1008, cen_252, cen_63, cen_9; +always @(posedge clk) begin + cen_9 <= clkcnt9 ==4'd8; + cen_63 <= clkcnt9 ==4'd8 && clkcnt63 ==3'd0; + cen_252 <= clkcnt9 ==4'd8 && clkcnt63 ==3'd0 && clkcnt252 ==2'd0; + cen_1008 <= clkcnt9 ==4'd8 && clkcnt63 ==3'd0 && clkcnt252 ==2'd0 && clkcnt1008==2'd0; +end + +jt12_fm_uprate u_left( + .rst ( rst ), + .clk ( clk ), + .fm_snd ( fm_left ), + .psg_snd ( psg3 ), + .fm_en ( fm_en ), + .cen_1008 ( cen_1008 ), + .cen_252 ( cen_252 ), + .cen_63 ( cen_63 ), + .cen_9 ( cen_9 ), + .snd ( snd_left ) // Mixed sound at clk sample rate +); + +jt12_fm_uprate u_right( + .rst ( rst ), + .clk ( clk ), + .fm_snd ( fm_right ), + .psg_snd ( psg3 ), + .fm_en ( fm_en ), + .cen_1008 ( cen_1008 ), + .cen_252 ( cen_252 ), + .cen_63 ( cen_63 ), + .cen_9 ( cen_9 ), + .snd ( snd_right ) // Mixed sound at clk sample rate +); + +endmodule // jt12_genmix \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_interpol.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_interpol.v new file mode 100644 index 0000000000000000000000000000000000000000..e5ff23ba7aa0d03d95497e419120bebce37e56be --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt12/hdl/mixer/jt12_interpol.v @@ -0,0 +1,92 @@ +/* This file is part of JT12. + + + JT12 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT12 program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT12. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-12-2018 + +*/ + +module jt12_interpol #(parameter calcw=18, inw=16, + n=2, // number of stages + m=1, // depth of comb filter + rate=2 // it will stuff with as many as (rate-1) zeros +)( + input rst, + input clk, +(* direct_enable *) input cen_in, +(* direct_enable *) input cen_out, + input signed [inw-1:0] snd_in, + output reg signed [inw-1:0] snd_out +); + +reg signed [calcw-1:0] inter6; +wire signed [calcw-1:0] comb_op, integ_op; +localparam wdiff = calcw - inw; + +generate + genvar k; + wire [calcw-1:0] comb_data[0:n]; + assign comb_data[0] = { {wdiff{snd_in[inw-1]}}, snd_in }; + assign comb_op = comb_data[n]; + for(k=0;k. + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 11-12-2018 + + Each channel can use the full range of the DAC as they do not + get summed in the real chip. + + Operator data is summed up without adding extra bits. This is + the case of real YM3438, which was used on Megadrive 2 models. + +*/ + +// Generic mixer +// wout should be larger or equal than any input (w0,w1,w2,w3) + +module jt12_mixer #(parameter w0=16,w1=16,w2=16,w3=16,wout=20) +( + input clk, + input cen, + // input signals + input signed [w0-1:0] ch0, + input signed [w1-1:0] ch1, + input signed [w2-1:0] ch2, + input signed [w3-1:0] ch3, + // gain for each channel in 4.4 fixed point format + input [7:0] gain0, + input [7:0] gain1, + input [7:0] gain2, + input [7:0] gain3, + output reg signed [wout-1:0] mixed +); + +reg signed [w0+7:0] ch0_amp; +reg signed [w1+7:0] ch1_amp; +reg signed [w2+7:0] ch2_amp; +reg signed [w3+7:0] ch3_amp; + +// rescale to wout+4+8 +wire signed [wout+11:0] scaled0 = { {wout+4-w0{ch0_amp[w0+7]}}, ch0_amp }; +wire signed [wout+11:0] scaled1 = { {wout+4-w1{ch1_amp[w1+7]}}, ch1_amp }; +wire signed [wout+11:0] scaled2 = { {wout+4-w2{ch2_amp[w2+7]}}, ch2_amp }; +wire signed [wout+11:0] scaled3 = { {wout+4-w3{ch3_amp[w3+7]}}, ch3_amp }; + +reg signed [wout+11:0] sum, limited; + +wire signed [wout+11:0] max_pos = { {12{1'b0}}, {(wout-1){1'b1}}}; + +wire signed [8:0] + g0 = {1'b0, gain0}, + g1 = {1'b0, gain1}, + g2 = {1'b0, gain2}, + g3 = {1'b0, gain3}; + +// Apply gain +always @(posedge clk) if(cen) begin + ch0_amp <= g0 * ch0; + ch1_amp <= g1 * ch1; + ch2_amp <= g2 * ch2; + ch3_amp <= g3 * ch3; + + // divides by 16 to take off the decimal part and leave only + // the integer part + sum <= (scaled0 + scaled1 + scaled2 + scaled3)>>>4; + limited <= sum>max_pos ? max_pos : (sum<~max_pos ? ~max_pos : sum); + mixed <= limited[wout-1:0]; +end + +endmodule // jt12_mixer diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/README.md b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/README.md new file mode 100644 index 0000000000000000000000000000000000000000..025682afd7233ae5652e54bcd248289015a9c113 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/README.md @@ -0,0 +1,131 @@ +# JT49 FPGA Clone of YM2149 hardware by Jose Tejada (@topapate) + +You can show your appreciation through + +* [Patreon](https://patreon.com/jotego), by supporting open source retro releases + +YM2149 compatible Verilog core, with emphasis on FPGA implementation as part of JT12 in order to recreate the YM2203 part. + +## Documentation + +- [AY-3-8910 Data Manual](https://archive.org/details/AY-3-8910-8912_Feb-1979/page/n51/mode/2up) +- [AY-3-8919 Reverse Engineered](https://github.com/lvd2/ay-3-8910_reverse_engineered) +- [YM2149](https://archive.org/details/bitsavers_yamahaYM21_3070829) + +## Using JT49 in a git project + +If you are using JT49 in a git project, the best way to add it to your project is: + +1. Optionally fork JT49's repository to your own GitHub account +2. Add it as a submodule to your git project: `git submodule add https://github.com/jotego/jt49.git` +3. Now you can refer to the RTL files in **jt49/hdl** + +The advantages of a using a git submodule are: + +1. Your project contains a reference to a commit of the JT49 repository +2. As long as you do not manually update the JT49 submodule, it will keep pointing to the same commit +3. Each time you make a commit in your project, it will include a pointer to the JT49 commit used. So you will always know the JT49 that worked for you +4. If JT49 is updated and you want to get the changes, simply update the submodule using git. The new JT49 commit used will be annotated in your project's next commit. So the history of your project will reflect that change too. +5. JT49 files will be intact and you will use the files without altering them. + +## Usage + +There are two top level files you can use: + - **jt49_bus**: presents the expected AY-3-8910 interface + - **jt49**: presents a simplified interface, ideal to embed. This is the one used by jt12 + +clk_en cannot be set to 1 for correct operation. The design assumes that there will be at least one empty clock cycle between every two clk_en high clock cycles. + +## Files for Simulation and Synthesis + +When used inside a [JTFRAME](https://github.com/jotego/jtframe) project, you can use the [yaml](hdl/jt49.yaml) file provided. If you are using this repository on its own, there is a [qip](syn/quartus/jt49.qip) for Intel Quartus available. + +It is recommended to use this repository as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) in your project. + + +## Port Description jt49 + +Name | Direction | Width | Purpose +---------|-----------|-------|------------------------------------- +rst_n | input | | active-low asynchronous reset signal +clk | input | | clock +clk_en | input | | clock enable. It cannot be a permanent 1 +addr | input | 4 | selects the register to access to +cs_n | input | | chip-select, active low +wr_n | input | | active-low write signal +din | input | 8 | data to write to registers +sel | input | | input clock is further divided by 2 when low +dout | output | 8 | data read from registers. Updated when cs_n is low +sound | output | 10 | Unsigned combined output of the three channels +A | output | 8 | Unsigned output of channel A +B | output | 8 | Unsigned output of channel B +C | output | 8 | Unsigned output of channel C + +The module is not designed to be used at full clk speed. The clock enable input signal should divide the clock at least by two. This is needed because the volume LUT is shared for all three channels and the pipeline does not include wait states for the LUT as wait states happen naturally when clk_en is used. + +The ports of **jt49_bus** replace the CPU interface with that of the original AY-3-8910. + +Name | Direction | Width | Purpose +---------|-----------|-------|------------------------------------- +rst_n | input | | active-low asynchronous reset signal +clk | input | | clock +clk_en | input | | clock enable. It cannot be a permanent 1 +bdir | input | | bdir pin of AY-3-8910 +bc1 | input | | bc1 pin of AY-3-8910 +din | input | 8 | data to write to registers +sel | input | | input clock is further divided by 2 when low +dout | output | 8 | data read from registers. Updated when cs_n is low +sound | output | 10 | Unsigned combined output of the three channels +A | output | 8 | Unsigned output of channel A +B | output | 8 | Unsigned output of channel B +C | output | 8 | Unsigned output of channel C +IOA_in | input | 8 | I/O port A, input side +IOA_in | output | 8 | I/O port A, output side +IOB_in | input | 8 | I/O port B, input side +IOB_in | output | 8 | I/O port B, output side + +## Comparison with AY-3-8910 Verilog Model + +A simulation test bench of jt49 vs the AY-3-8910 model (available in the doc folder via a git submodule) is available in folder ver/comp. The simulation uses a simple text file to enter arbitrary commands (test_cmd). The command file is converted to hexadecimal by parser.awk and used in simulation. The following parameters were tested: + +Item | Compliance | Remarks +---------------------|------------------|------------------------------- +channel period | Yes | Tested: 0, 1 and FFFF values +noise period | Yes | Tested: 0, 7 and 1F values +envelope shape | Yes | Tested all 16 shapes +envelope period | Yes | Tested 0 and FFF values + +## Resistor Load Modelling + +The YM2149 was used to measure the output circuitry. According to AY-3-8910 schematics, there are 16 NMOS devices for each channel. Depending on the amplitude settings, only one of them will be active. These numbers render values that agree with the datasheet and measurements: + +- Rload = 1 kOhm +- Smallest Ron = 900 Ohm (for level=15) +- Largest Roff = 3 MOhm (for level=0) +- Scale factor from one MOS to the next = 1.55 + +Each output level is the combination of one MOS being on and the rest off, so they combine into a single impedance, which then forms a resistor divider with the load. + +The output MOS will hold its impedance even if an extra 1V is added at the load resistor (reducing the MOS headroom) + +## Non Linear Effects + +- Channel mixing effects by short circuiting the outputs in AY-3-8910 are not modelled +- Non linearity in YM2203 when shorting all outputs is modeled via parameter YM2203_LUMPED + +Non linear effects depend on the way the chip is connected and its model. See [the connection list](doc/conn.md). + +## Related Projects + +Other sound chips from the same author + +Chip | Repository +-----------------------|------------ +YM2203, YM2612, YM2610 | [JT12](https://github.com/jotego/jt12) +YM2151 | [JT51](https://github.com/jotego/jt51) +YM3526 | [JTOPL](https://github.com/jotego/jtopl) +YM2149 | [JT49](https://github.com/jotego/jt49) +sn76489an | [JT89](https://github.com/jotego/jt89) +OKI 6295 | [JT6295](https://github.com/jotego/jt6295) +OKI MSM5205 | [JT5205](https://github.com/jotego/jt5205) +NEC uPN7759 | [JT7759](https://github.com/jotego/jt7759) \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm.v new file mode 100644 index 0000000000000000000000000000000000000000..32d46609f4c3ae734ae851b1dd81b16025aee614 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm.v @@ -0,0 +1,56 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 15-Jan-2019 + + */ + +// DC removal filter +// input is unsigned +// output is signed +/* verilator tracing_off */ +module jt49_dcrm( + input clk, + input cen, + input rst, + input [7:0] din, + output reg signed [7:0] dout +); + +wire signed [7:0] ave0, ave1; + +jt49_mave u_mave0( + .clk ( clk ), + .cen ( cen ), + .rst ( rst ), + .din ( {1'b0, din[7:1] } ), + .dout ( ave0 ) +); + +jt49_mave u_mave1( + .clk ( clk ), + .cen ( cen ), + .rst ( rst ), + .din ( ave0 ), + .dout ( ave1 ) +); + +always @(posedge clk) + if( cen ) + dout <= ({1'b0,din} - {ave1,1'b0})>>>1; + +endmodule \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm2.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm2.v new file mode 100644 index 0000000000000000000000000000000000000000..f775d03db97ede5a86da75974c66d2d1c218ee34 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dcrm2.v @@ -0,0 +1,64 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 15-Jan-2019 + + */ + +// DC removal filter +// input is unsigned +// output is signed + +module jt49_dcrm2 #(parameter sw=8) ( + input clk, + input cen, + input rst, + input [sw-1:0] din, + output signed [sw-1:0] dout +); + +localparam DW=10; // width of the decimal portion + +reg signed [sw+DW:0] integ, exact, error; +//reg signed [2*(9+DW)-1:0] mult; +// wire signed [sw+DW:0] plus1 = { {sw+DW{1'b0}},1'b1}; +reg signed [sw:0] pre_dout; +// reg signed [sw+DW:0] dout_ext; +reg signed [sw:0] q; + +always @(*) begin + exact = integ+error; + q = exact[sw+DW:DW]; + pre_dout = { 1'b0, din } - q; + //dout_ext = { pre_dout, {DW{1'b0}} }; + //mult = dout_ext; +end + +assign dout = pre_dout[sw-1:0]; + +always @(posedge clk) + if( rst ) begin + integ <= {sw+DW+1{1'b0}}; + error <= {sw+DW+1{1'b0}}; + end else if( cen ) begin + /* verilator lint_off WIDTH */ + integ <= integ + pre_dout; //mult[sw+DW*2:DW]; + /* verilator lint_on WIDTH */ + error <= exact-{q, {DW{1'b0}}}; + end + +endmodule \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dly.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dly.v new file mode 100644 index 0000000000000000000000000000000000000000..3ac254100d183dca67793d147dae20e4f5a05a28 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_dly.v @@ -0,0 +1,67 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 15-Jan-2019 + + */ + +// Delay stage +// use for long delays + +module jt49_dly #(parameter DW=8, depth=10)( + input clk, + input cen, + input rst, + input [7:0] din, + output reg [7:0] dout, + output reg [7:0] pre_dout + +); + +reg [depth-1:0] rdpos, wrpos; + + +// memory +reg [DW-1:0] ram[0:2**depth-1]; +always @(posedge clk) + if(rst) + pre_dout <= {DW{1'b0}}; + else begin + pre_dout <= ram[rdpos]; + if( cen ) ram[wrpos] <= din; + end + +`ifdef SIMULATION +integer k; +initial begin + for(k=0;k<=2**depth-1;k=k+1) + ram[k] = 0; +end +`endif + +always @(posedge clk) + if( rst ) begin + rdpos <= { {depth-1{1'b0}}, 1'b1}; + wrpos <= {depth{1'b1}}; + dout <= {DW{1'b0}}; + end else if(cen) begin + dout <= pre_dout; + rdpos <= rdpos+1'b1; + wrpos <= wrpos+1'b1; + end + +endmodule // jt49_dly \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_mave.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_mave.v new file mode 100644 index 0000000000000000000000000000000000000000..02a091628d34c609004c2b888de8c4a9f7cb85be --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/filter/jt49_mave.v @@ -0,0 +1,60 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 15-Jan-2019 + + */ + +// Moving averager + +module jt49_mave #(parameter depth=8, DW=8)( + input clk, + input cen, + input rst, + input signed [DW-1:0] din, + output signed [DW-1:0] dout +); + +wire [DW-1:0] dly0; +wire [DW-1:0] pre_dly0; + +jt49_dly #(.depth(depth),.DW(DW)) u_dly0( + .clk ( clk ), + .cen ( cen ), + .rst ( rst ), + .din ( din ), + .dout ( dly0 ), + .pre_dout ( pre_dly0 ) +); + +// moving average +// D=2048 +reg signed [DW:0] diff; +reg signed [DW+depth-1:0] sum; + + +always @(posedge clk) + if( rst ) begin + diff <= {DW+1{1'd0}}; + sum <= {DW+depth+1{1'd0}}; + end else if(cen) begin + diff <= {1'b0,din } - { 1'b0, dly0 }; + sum <= { {depth{diff[DW]}}, diff } + sum; + end +assign dout = sum[DW+depth-1:depth]; + +endmodule \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.v new file mode 100644 index 0000000000000000000000000000000000000000..08145bf9f857ecaf55ec7179e899b9ac6dc0c690 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.v @@ -0,0 +1,258 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + +module jt49 ( // note that input ports are not multiplexed + input rst_n, + input clk, // signal on positive edge + input clk_en /* synthesis direct_enable = 1 */, + input [3:0] addr, + input cs_n, + input wr_n, // write + input [7:0] din, + input sel, // if sel is low, the clock is divided by 2 + output reg [7:0] dout, + output reg [9:0] sound, // combined channel output + output reg [7:0] A, // linearised channel output + output reg [7:0] B, + output reg [7:0] C, + output sample, + + input [7:0] IOA_in, + output [7:0] IOA_out, + output IOA_oe, + + input [7:0] IOB_in, + output [7:0] IOB_out, + output IOB_oe +); + +parameter [2:0] COMP=3'b000; +parameter YM2203_LUMPED=0; +parameter CLKDIV=3; +wire [2:0] comp = COMP; + +reg [7:0] regarray[15:0]; +wire [7:0] port_A, port_B; + +wire [4:0] envelope; +wire bitA, bitB, bitC; +wire noise; +reg Amix, Bmix, Cmix; + +wire cen16, cen256; + +assign IOA_out = regarray[14]; +assign IOB_out = regarray[15]; +assign port_A = IOA_in; +assign port_B = IOB_in; +assign IOA_oe = regarray[7][6]; +assign IOB_oe = regarray[7][7]; +assign sample = cen16; + +jt49_cen #(.CLKDIV(CLKDIV)) u_cen( + .clk ( clk ), + .rst_n ( rst_n ), + .cen ( clk_en ), + .sel ( sel ), + .cen16 ( cen16 ), + .cen256 ( cen256 ) +); + +// internal modules operate at clk/16 +jt49_div #(12) u_chA( + .clk ( clk ), + .rst_n ( rst_n ), + .cen ( cen16 ), + .period ( {regarray[1][3:0], regarray[0][7:0] } ), + .div ( bitA ) +); + +jt49_div #(12) u_chB( + .clk ( clk ), + .rst_n ( rst_n ), + .cen ( cen16 ), + .period ( {regarray[3][3:0], regarray[2][7:0] } ), + .div ( bitB ) +); + +jt49_div #(12) u_chC( + .clk ( clk ), + .rst_n ( rst_n ), + .cen ( cen16 ), + .period ( {regarray[5][3:0], regarray[4][7:0] } ), + .div ( bitC ) +); + +jt49_noise u_ng( + .clk ( clk ), + .cen ( cen16 ), + .rst_n ( rst_n ), + .period ( regarray[6][4:0] ), + .noise ( noise ) +); + +// envelope generator +wire eg_step; +wire [15:0] eg_period = {regarray[4'hc],regarray[4'hb]}; +wire null_period = eg_period == 16'h0; + +jt49_div #(16) u_envdiv( + .clk ( clk ), + .cen ( cen256 ), + .rst_n ( rst_n ), + .period ( eg_period ), + .div ( eg_step ) +); + +reg eg_restart; + +jt49_eg u_env( + .clk ( clk ), + .cen ( cen256 ), + .step ( eg_step ), + .rst_n ( rst_n ), + .restart ( eg_restart ), + .null_period( null_period ), + .ctrl ( regarray[4'hD][3:0] ), + .env ( envelope ) +); + +reg [4:0] logA, logB, logC, log; +wire [7:0] lin; + +jt49_exp u_exp( + .clk ( clk ), + .comp ( comp ), + .din ( log ), + .dout ( lin ) +); + +wire [4:0] volA = { regarray[ 8][3:0], regarray[ 8][3] }; +wire [4:0] volB = { regarray[ 9][3:0], regarray[ 9][3] }; +wire [4:0] volC = { regarray[10][3:0], regarray[10][3] }; +wire use_envA = regarray[ 8][4]; +wire use_envB = regarray[ 9][4]; +wire use_envC = regarray[10][4]; +wire use_noA = regarray[ 7][3]; +wire use_noB = regarray[ 7][4]; +wire use_noC = regarray[ 7][5]; + +reg [3:0] acc_st; + +always @(posedge clk) if( clk_en ) begin + Amix <= (noise|use_noA) & (bitA|regarray[7][0]); + Bmix <= (noise|use_noB) & (bitB|regarray[7][1]); + Cmix <= (noise|use_noC) & (bitC|regarray[7][2]); + + logA <= !Amix ? 5'd0 : (use_envA ? envelope : volA ); + logB <= !Bmix ? 5'd0 : (use_envB ? envelope : volB ); + logC <= !Cmix ? 5'd0 : (use_envC ? envelope : volC ); +end + +reg [9:0] acc; +wire [9:0] elin; + +assign elin = {2'd0,lin}; + +always @(posedge clk, negedge rst_n) begin + if( !rst_n ) begin + acc_st <= 4'b1; + acc <= 10'd0; + A <= 8'd0; + B <= 8'd0; + C <= 8'd0; + sound <= 10'd0; + end else if(clk_en) begin + acc_st <= { acc_st[2:0], acc_st[3] }; + // Lumping the channel outputs for YM2203 will cause only the higher + // voltage to pass throuh, as the outputs seem to use a source follower. + acc <= YM2203_LUMPED==1 ? (acc>elin ? acc : elin) : acc + elin; + case( acc_st ) + 4'b0001: begin + log <= logA; + acc <= 10'd0; + sound <= acc; + end + 4'b0010: begin + A <= lin; + log <= logB; + end + 4'b0100: begin + B <= lin; + log <= logC; + end + 4'b1000: begin // last sum + C <= lin; + end + default:; + endcase + end +end + +reg [7:0] read_mask; + +always @(*) + case(addr) + 4'h0,4'h2,4'h4,4'h7,4'hb,4'hc,4'he,4'hf: + read_mask = 8'hff; + 4'h1,4'h3,4'h5,4'hd: + read_mask = 8'h0f; + 4'h6,4'h8,4'h9,4'ha: + read_mask = 8'h1f; + endcase // addr + +// register array +wire write; +reg last_write; +wire wr_edge = write & ~last_write; + +assign write = !wr_n && !cs_n; + +always @(posedge clk, negedge rst_n) begin + if( !rst_n ) begin + dout <= 8'd0; + last_write <= 0; + eg_restart <= 0; + regarray[0]<=8'd0; regarray[4]<=8'd0; regarray[ 8]<=8'd0; regarray[12]<=8'd0; + regarray[1]<=8'd0; regarray[5]<=8'd0; regarray[ 9]<=8'd0; regarray[13]<=8'd0; + regarray[2]<=8'd0; regarray[6]<=8'd0; regarray[10]<=8'd0; regarray[14]<=8'd0; + regarray[3]<=8'd0; regarray[7]<=8'd0; regarray[11]<=8'd0; regarray[15]<=8'd0; + end else begin + last_write <= write; + // Data read + case( addr ) + 4'he: dout <= port_A; + 4'hf: dout <= port_B; + default: dout <= regarray[ addr ] & read_mask; + endcase + // Data write + if( write ) begin + regarray[addr] <= din; + if ( addr == 4'hD && wr_edge ) eg_restart <= 1; + end else begin + eg_restart <= 0; + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.yaml b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8db67301a61f59cbeccb7d28c9b79382b6ab171a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49.yaml @@ -0,0 +1,8 @@ +here: + - jt49.v + - jt49_bus.v + - jt49_div.v + - jt49_cen.v + - jt49_eg.v + - jt49_exp.v + - jt49_noise.v diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_bus.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_bus.v new file mode 100644 index 0000000000000000000000000000000000000000..ac48e8ed684492d27cbf62a8c7bd8065484ba581 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_bus.v @@ -0,0 +1,105 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 28-Jan-2019 + + Based on sqmusic, by the same author + + */ + +// This is a wrapper with the BDIR/BC1 pins + +module jt49_bus ( // note that input ports are not multiplexed + input rst_n, + input clk, // signal on positive edge + input clk_en /* synthesis direct_enable = 1 */, + // bus control pins of original chip + input bdir, + input bc1, + input [7:0] din, + + input sel, // if sel is low, the clock is divided by 2 + output [7:0] dout, + output [9:0] sound, // combined channel output + output [7:0] A, // linearised channel output + output [7:0] B, + output [7:0] C, + output sample, + + input [7:0] IOA_in, + output [7:0] IOA_out, + output IOA_oe, + + input [7:0] IOB_in, + output [7:0] IOB_out, + output IOB_oe +); + +parameter [2:0] COMP=3'b000; + +reg wr_n, cs_n; +reg [3:0] addr; +reg addr_ok; +reg [7:0] din_latch; + +always @(posedge clk) + if( !rst_n ) begin + wr_n <= 1'b1; + cs_n <= 1'b1; + addr <= 4'd0; + addr_ok <= 1'b1; + end else begin // I/O cannot use clk_en + // addr must be + case( {bdir,bc1} ) + 2'b00: { wr_n, cs_n } <= 2'b11; + 2'b01: { wr_n, cs_n } <= addr_ok ? 2'b10 : 2'b11; + 2'b10: begin + { wr_n, cs_n } <= addr_ok ? 2'b00 : 2'b11; + din_latch <= din; + end + 2'b11: begin + { wr_n, cs_n } <= 2'b11; + addr <= din[3:0]; + addr_ok <= din[7:4] == 4'd0; + end + endcase // {bdir,bc1} + end + +jt49 #(.COMP(COMP)) u_jt49( // note that input ports are not multiplexed + .rst_n ( rst_n ), + .clk ( clk ), // signal on positive edge + .clk_en ( clk_en ), // clock enable on negative edge + .addr ( addr[3:0] ), + .cs_n ( cs_n ), + .wr_n ( wr_n ), // write + .din ( din_latch ), + .sel ( sel ), // if sel is low, the clock is divided by 2 + .dout ( dout ), + .sound ( sound ), // combined channel output + .sample ( sample ), + .A ( A ), // linearised channel output + .B ( B ), + .C ( C ), + .IOA_in ( IOA_in ), + .IOA_out( IOA_out ), + .IOA_oe ( IOA_oe ), + .IOB_in ( IOB_in ), + .IOB_out( IOB_out ), + .IOB_oe ( IOB_oe ) +); + +endmodule // jt49_bus \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_cen.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_cen.v new file mode 100644 index 0000000000000000000000000000000000000000..671eceb232251302bc063fc9168a9566a5a9ae64 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_cen.v @@ -0,0 +1,55 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + +module jt49_cen( + input clk, + input rst_n, + input cen, // base clock enable signal + input sel, // when low, divide by 2 once more + output reg cen16, + output reg cen256 +); + +reg [9:0] cencnt; +parameter CLKDIV = 3; // use 3 for standalone JT49 or 2 +localparam eg = CLKDIV; //8; + +wire toggle16 = sel ? ~|cencnt[CLKDIV-1:0] : ~|cencnt[CLKDIV:0]; +wire toggle256= sel ? ~|cencnt[eg-2:0] : ~|cencnt[eg-1:0]; + + +always @(posedge clk, negedge rst_n) begin + if(!rst_n) + cencnt <= 10'd0; + else begin + if(cen) cencnt <= cencnt+10'd1; + end +end + +always @(posedge clk) begin + cen16 <= cen & toggle16; + cen256 <= cen & toggle256; +end + + +endmodule // jt49_cen diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_div.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_div.v new file mode 100644 index 0000000000000000000000000000000000000000..ac4564ce9add8056387d35c6ee7cf4643459ef11 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_div.v @@ -0,0 +1,52 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + + +module jt49_div #(parameter W=12 )( + (* direct_enable *) input cen, + input clk, // this is the divided down clock from the core + input rst_n, + input [W-1:0] period, + output reg div +); + +reg [W-1:0]count; + +wire [W-1:0] one = { {W-1{1'b0}}, 1'b1}; + +always @(posedge clk, negedge rst_n ) begin + if( !rst_n) begin + count <= one; + div <= 1'b0; + end + else if(cen) begin + if( count>=period ) begin + count <= one; + div <= ~div; + end + else + /*if( period!={W{1'b0}} )*/ count <= count + one ; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_eg.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_eg.v new file mode 100644 index 0000000000000000000000000000000000000000..46dd62ace1f080bce6678469ca0b8b99b0c2b74e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_eg.v @@ -0,0 +1,88 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + +module jt49_eg( + (* direct_enable *) input cen, + input clk, // this is the divided down clock from the core + input step, + input null_period, + input rst_n, + input restart, + input [3:0] ctrl, + output reg [4:0]env +); + +reg inv, stop; +reg [4:0] gain; + +wire CONT = ctrl[3]; +wire ATT = ctrl[2]; +wire ALT = ctrl[1]; +wire HOLD = ctrl[0]; + +wire will_hold = !CONT || HOLD; + +always @(posedge clk) + if( cen ) env <= inv ? ~gain : gain; + +reg last_step; +wire step_edge = (step && !last_step) || null_period; +wire will_invert = (!CONT&&ATT) || (CONT&&ALT); +reg rst_latch, rst_clr; + +always @(posedge clk) begin + if( restart ) rst_latch <= 1; + else if(rst_clr ) rst_latch <= 0; +end + +always @( posedge clk, negedge rst_n ) + if( !rst_n) begin + gain <= 5'h1F; + inv <= 0; + stop <= 0; + rst_clr <= 0; + end + else if( cen ) begin + last_step <= step; + if( rst_latch ) begin + gain <= 5'h1F; + inv <= ATT; + stop <= 1'b0; + rst_clr <= 1; + end + else begin + rst_clr <= 0; + if (step_edge && !stop) begin + if( gain==5'h00 ) begin + if( will_hold ) + stop <= 1'b1; + else + gain <= gain-5'b1; + if( will_invert ) inv<=~inv; + end + else gain <= gain-5'b1; + end + end + end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_exp.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_exp.v new file mode 100644 index 0000000000000000000000000000000000000000..25efa3885ae3a9dbb339a4774490f442f1426a02 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_exp.v @@ -0,0 +1,205 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + +// Compression vs dynamic range +// 0 -> 43.6dB +// 1 -> 29.1 +// 2 -> 21.8 +// 3 -> 13.4 + +module jt49_exp( + input clk, + input [2:0] comp, // compression + input [4:0] din, + output reg [7:0] dout +); + +reg [7:0] lut[0:159]; + +always @(posedge clk) + dout <= lut[ {comp,din} ]; + +initial begin + lut[0] = 8'd0; + lut[1] = 8'd1; + lut[2] = 8'd1; + lut[3] = 8'd1; + lut[4] = 8'd2; + lut[5] = 8'd2; + lut[6] = 8'd3; + lut[7] = 8'd3; + lut[8] = 8'd4; + lut[9] = 8'd5; + lut[10] = 8'd6; + lut[11] = 8'd7; + lut[12] = 8'd9; + lut[13] = 8'd11; + lut[14] = 8'd13; + lut[15] = 8'd15; + lut[16] = 8'd18; + lut[17] = 8'd22; + lut[18] = 8'd26; + lut[19] = 8'd31; + lut[20] = 8'd37; + lut[21] = 8'd45; + lut[22] = 8'd53; + lut[23] = 8'd63; + lut[24] = 8'd75; + lut[25] = 8'd90; + lut[26] = 8'd107; + lut[27] = 8'd127; + lut[28] = 8'd151; + lut[29] = 8'd180; + lut[30] = 8'd214; + lut[31] = 8'd255; + lut[32] = 8'd0; + lut[33] = 8'd7; + lut[34] = 8'd8; + lut[35] = 8'd10; + lut[36] = 8'd11; + lut[37] = 8'd12; + lut[38] = 8'd14; + lut[39] = 8'd15; + lut[40] = 8'd17; + lut[41] = 8'd20; + lut[42] = 8'd22; + lut[43] = 8'd25; + lut[44] = 8'd28; + lut[45] = 8'd31; + lut[46] = 8'd35; + lut[47] = 8'd40; + lut[48] = 8'd45; + lut[49] = 8'd50; + lut[50] = 8'd56; + lut[51] = 8'd63; + lut[52] = 8'd71; + lut[53] = 8'd80; + lut[54] = 8'd90; + lut[55] = 8'd101; + lut[56] = 8'd113; + lut[57] = 8'd127; + lut[58] = 8'd143; + lut[59] = 8'd160; + lut[60] = 8'd180; + lut[61] = 8'd202; + lut[62] = 8'd227; + lut[63] = 8'd255; + lut[64] = 8'd0; + lut[65] = 8'd18; + lut[66] = 8'd20; + lut[67] = 8'd22; + lut[68] = 8'd24; + lut[69] = 8'd26; + lut[70] = 8'd29; + lut[71] = 8'd31; + lut[72] = 8'd34; + lut[73] = 8'd37; + lut[74] = 8'd41; + lut[75] = 8'd45; + lut[76] = 8'd49; + lut[77] = 8'd53; + lut[78] = 8'd58; + lut[79] = 8'd63; + lut[80] = 8'd69; + lut[81] = 8'd75; + lut[82] = 8'd82; + lut[83] = 8'd90; + lut[84] = 8'd98; + lut[85] = 8'd107; + lut[86] = 8'd116; + lut[87] = 8'd127; + lut[88] = 8'd139; + lut[89] = 8'd151; + lut[90] = 8'd165; + lut[91] = 8'd180; + lut[92] = 8'd196; + lut[93] = 8'd214; + lut[94] = 8'd233; + lut[95] = 8'd255; + lut[96] = 8'd0; + lut[97] = 8'd51; + lut[98] = 8'd54; + lut[99] = 8'd57; + lut[100] = 8'd60; + lut[101] = 8'd63; + lut[102] = 8'd67; + lut[103] = 8'd70; + lut[104] = 8'd74; + lut[105] = 8'd78; + lut[106] = 8'd83; + lut[107] = 8'd87; + lut[108] = 8'd92; + lut[109] = 8'd97; + lut[110] = 8'd103; + lut[111] = 8'd108; + lut[112] = 8'd114; + lut[113] = 8'd120; + lut[114] = 8'd127; + lut[115] = 8'd134; + lut[116] = 8'd141; + lut[117] = 8'd149; + lut[118] = 8'd157; + lut[119] = 8'd166; + lut[120] = 8'd175; + lut[121] = 8'd185; + lut[122] = 8'd195; + lut[123] = 8'd206; + lut[124] = 8'd217; + lut[125] = 8'd229; + lut[126] = 8'd241; + lut[127] = 8'd255; + lut[128] = 8'd0; + lut[129] = 8'd8; + lut[130] = 8'd10; + lut[131] = 8'd12; + lut[132] = 8'd16; + lut[133] = 8'd22; + lut[134] = 8'd29; + lut[135] = 8'd35; + lut[136] = 8'd44; + lut[137] = 8'd50; + lut[138] = 8'd56; + lut[139] = 8'd60; + lut[140] = 8'd64; + lut[141] = 8'd85; + lut[142] = 8'd97; + lut[143] = 8'd103; + lut[144] = 8'd108; + lut[145] = 8'd120; + lut[146] = 8'd127; + lut[147] = 8'd134; + lut[148] = 8'd141; + lut[149] = 8'd149; + lut[150] = 8'd157; + lut[151] = 8'd166; + lut[152] = 8'd175; + lut[153] = 8'd185; + lut[154] = 8'd195; + lut[155] = 8'd206; + lut[156] = 8'd217; + lut[157] = 8'd229; + lut[158] = 8'd241; + lut[159] = 8'd255; + +end +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_noise.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_noise.v new file mode 100644 index 0000000000000000000000000000000000000000..ffc1fb978e55157d7d36ca11e2feea6b3229fd63 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/jt49/hdl/jt49_noise.v @@ -0,0 +1,62 @@ +/* This file is part of JT49. + + JT49 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + JT49 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with JT49. If not, see . + + Author: Jose Tejada Gomez. Twitter: @topapate + Version: 1.0 + Date: 10-Nov-2018 + + Based on sqmusic, by the same author + + */ + + +module jt49_noise( + (* direct_enable *) input cen, + input clk, + input rst_n, + input [4:0] period, + output reg noise +); + +reg [5:0]count; +reg [16:0]poly17; +wire poly17_zero = poly17==17'b0; +wire noise_en; +reg last_en; + +wire noise_up = noise_en && !last_en; + +always @(posedge clk ) if(cen) begin + noise <= ~poly17[0]; +end + +always @( posedge clk, negedge rst_n ) + if( !rst_n ) + poly17 <= 17'd0; + else if( cen ) begin + last_en <= noise_en; + if( noise_up ) + poly17 <= { poly17[0] ^ poly17[3] ^ poly17_zero, poly17[16:1] }; + end + +jt49_div #(5) u_div( + .clk ( clk ), + .cen ( cen ), + .rst_n ( rst_n ), + .period ( period ), + .div ( noise_en ) +); + +endmodule \ No newline at end of file diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/backup.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/backup.v new file mode 100644 index 0000000000000000000000000000000000000000..1af9ba6d91cad1550573bc2737b572ae4f6e127d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/backup.v @@ -0,0 +1,64 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module backup( + input CLK, + input [15:1] M68K_ADDR, + input nBWL, nBWU, + input [15:0] M68K_DATA, + output [15:0] SRAM_OUT, + input clk_sys, + input [14:0] sram_addr, + input sram_wr, + input [15:0] sd_buff_dout, + output [15:0] sd_buff_din_sram +); + +dpram #(.ADDRWIDTH(15)) SRAML +( + .clock_a(CLK), + .address_a(M68K_ADDR[15:1]), + .wren_a(~nBWL), + .data_a(M68K_DATA[7:0]), + .q_a(SRAM_OUT[7:0]), + + .clock_b(clk_sys), + .address_b(sram_addr), + .wren_b(sram_wr), + .data_b(sd_buff_dout[7:0]), + .q_b(sd_buff_din_sram[7:0]) +); + +dpram #(.ADDRWIDTH(15)) SRAMU +( + .clock_a(CLK), + .address_a(M68K_ADDR[15:1]), + .wren_a(~nBWU), + .data_a(M68K_DATA[15:8]), + .q_a(SRAM_OUT[15:8]), + + .clock_b(clk_sys), + .address_b(sram_addr), + .wren_b(sram_wr), + .data_b(sd_buff_dout[15:8]), + .q_b(sd_buff_din_sram[15:8]) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/ddram.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/ddram.sv new file mode 100644 index 0000000000000000000000000000000000000000..51368bf4896eb6cc1a930c65d13df468665cf1d2 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/ddram.sv @@ -0,0 +1,248 @@ +// +// ddram.v +// Copyright (c) 2017 Sorgelig +// +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ------------------------------------------ +// + +// 8-bit version + +module ddram +( + input DDRAM_CLK, + + input DDRAM_BUSY, + output [7:0] DDRAM_BURSTCNT, + output [28:0] DDRAM_ADDR, + input [63:0] DDRAM_DOUT, + input DDRAM_DOUT_READY, + output DDRAM_RD, + output [63:0] DDRAM_DIN, + output [7:0] DDRAM_BE, + output DDRAM_WE, + + input cache_reset, + + input [27:0] wraddr, + input [15:0] din, + input we_byte, // 0:word write, 1:byte write + input we_req, + output reg we_ack, + + input [27:0] rdaddr, + output reg [7:0] dout, + input rd_req, + output reg rd_ack, + + input [27:0] rdaddr2, + output reg [7:0] dout2, + input rd_req2, + output reg rd_ack2, + + input [27:0] rdaddr3, + output reg [7:0] dout3, + input rd_req3, + output reg rd_ack3, + + input [27:0] cpaddr, + output reg[63:0] cpdout, + output reg cpwr, + input cpreq, + output cpbusy +); + +assign DDRAM_BURSTCNT = ram_burst; +assign DDRAM_BE = ram_wr_be | {8{ram_read}}; +assign DDRAM_ADDR = {4'b0011, ram_address[27:3]}; // RAM at 0x30000000 +assign DDRAM_RD = ram_read; +assign DDRAM_DIN = ram_data; +assign DDRAM_WE = ram_write; + +reg [7:0] ram_burst; +reg [63:0] ram_q, next_q, ram_q2, next_q2, ram_q3, next_q3; +reg [63:0] ram_data; +reg [27:0] ram_address, cache_addr, cache_addr2, cache_addr3; +reg ram_read = 0; +reg ram_write = 0; +reg [7:0] ram_wr_be; + +reg [2:0] state = 0; +reg [1:0] ch = 0; + +reg [2:0] cache_valid; + +always @(posedge DDRAM_CLK) begin + reg old_cpreq; + reg [6:0] cpcnt; + + if (cache_reset) begin + cache_valid <= 3'b000; + end + + cpwr <= 0; + if(!DDRAM_BUSY) begin + ram_write <= 0; + ram_read <= 0; + + case(state) + 0: if(we_ack != we_req) begin + ram_data <= we_byte ? {8{din[7:0]}} : {4{din}}; + ram_address <= wraddr; + ram_write <= 1; + ram_burst <= 1; + ram_wr_be <= we_byte ? (8'd1<<{wraddr[2:0]}) : (8'd3<<{wraddr[2:1],1'b0}); + state <= 1; + end + else if(rd_req != rd_ack) begin + if(cache_valid[0] & (cache_addr[27:3] == rdaddr[27:3])) begin + rd_ack <= rd_req; + dout <= ram_q[{rdaddr[2:0],3'b000} +:8]; + end + else if(cache_valid[0] & ((cache_addr[27:3]+1'd1) == rdaddr[27:3])) begin + rd_ack <= rd_req; + ram_q <= next_q; + dout <= next_q[{rdaddr[2:0],3'b000} +:8]; + cache_addr <= {rdaddr[27:3],3'b000}; + ram_address <= {rdaddr[27:3]+1'd1,3'b000}; + ram_read <= 1; + ram_burst <= 1; + ch <= 0; + state <= 3; + end + else begin + ram_address <= {rdaddr[27:3],3'b000}; + cache_addr <= {rdaddr[27:3],3'b000}; + ram_read <= 1; + ram_burst <= 2; + ch <= 0; + state <= 2; + end + end + else if(rd_req2 != rd_ack2) begin + if(cache_valid[1] & (cache_addr2[27:3] == rdaddr2[27:3])) begin + rd_ack2 <= rd_req2; + dout2 <= ram_q2[{rdaddr2[2:0],3'b000} +:8]; + end + else if(cache_valid[1] & ((cache_addr2[27:3]+1'd1) == rdaddr2[27:3])) begin + rd_ack2 <= rd_req2; + ram_q2 <= next_q2; + dout2 <= next_q2[{rdaddr2[2:0],3'b000} +:8]; + cache_addr2 <= {rdaddr2[27:3],3'b000}; + ram_address <= {rdaddr2[27:3]+1'd1,3'b000}; + ram_read <= 1; + ram_burst <= 1; + ch <= 1; + state <= 3; + end + else begin + ram_address <= {rdaddr2[27:3],3'b000}; + cache_addr2 <= {rdaddr2[27:3],3'b000}; + ram_read <= 1; + ram_burst <= 2; + ch <= 1; + state <= 2; + end + end + else if(rd_req3 != rd_ack3) begin + if(cache_valid[2] & (cache_addr3[27:3] == rdaddr3[27:3])) begin + rd_ack3 <= rd_req3; + dout3 <= ram_q3[{rdaddr3[2:0],3'b000} +:8]; + end + else if(cache_valid[2] & ((cache_addr3[27:3]+1'd1) == rdaddr3[27:3])) begin + rd_ack3 <= rd_req3; + ram_q3 <= next_q3; + dout3 <= next_q3[{rdaddr3[2:0],3'b000} +:8]; + cache_addr3 <= {rdaddr3[27:3],3'b000}; + ram_address <= {rdaddr3[27:3]+1'd1,3'b000}; + ram_read <= 1; + ram_burst <= 1; + ch <= 2; + state <= 3; + end + else begin + ram_address <= {rdaddr3[27:3],3'b000}; + cache_addr3 <= {rdaddr3[27:3],3'b000}; + ram_read <= 1; + ram_burst <= 2; + ch <= 2; + state <= 2; + end + end else begin + cpbusy <= 0; + old_cpreq <= cpreq; + if(~old_cpreq & cpreq) begin + ram_address <= {cpaddr[27:3],3'b000}; + ram_burst <= 128; + ram_read <= 1; + state <= 4; + cpcnt <= 127; + cpbusy <= 1; + end + end + + 1: begin + cache_valid <= 3'b000; + we_ack <= we_req; + state <= 0; + end + + 2: if(DDRAM_DOUT_READY) begin + if (ch==0) begin + ram_q <= DDRAM_DOUT; + dout <= DDRAM_DOUT[{rdaddr[2:0],3'b000} +:8]; + rd_ack <= rd_req; + end + else if (ch==1) begin + ram_q2 <= DDRAM_DOUT; + dout2 <= DDRAM_DOUT[{rdaddr2[2:0],3'b000} +:8]; + rd_ack2 <= rd_req2; + end + else begin + ram_q3 <= DDRAM_DOUT; + dout3 <= DDRAM_DOUT[{rdaddr3[2:0],3'b000} +:8]; + rd_ack3 <= rd_req3; + end + state <= 3; + end + + 3: if(DDRAM_DOUT_READY) begin + if (ch==0) begin + next_q <= DDRAM_DOUT; + cache_valid[0] <= 1'b1; + end + else if (ch==1) begin + next_q2 <= DDRAM_DOUT; + cache_valid[1] <= 1'b1; + end + else begin + next_q3 <= DDRAM_DOUT; + cache_valid[2] <= 1'b1; + end + state <= 0; + end + + 4: if(DDRAM_DOUT_READY) begin + cpwr <= 1; + cpcnt <= cpcnt - 1'd1; + cpdout <= DDRAM_DOUT; + if(!cpcnt) state <= 0; + end + endcase + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/dpram.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/dpram.v new file mode 100644 index 0000000000000000000000000000000000000000..4b3bdc119e3fc96544ef3d7a3d051994e9f113da --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/dpram.v @@ -0,0 +1,167 @@ +module dpram #(parameter ADDRWIDTH=8, DATAWIDTH=8, NUMWORDS=1<. +// +// ------------------------------------------ +// +// furrtek 2019-01-24 : Added ugly burst reading +// Sorgelig 2019-08 : rework, support mem copy and larger chips. +// + +module sdram +( + input init, // reset to initialize RAM + input clk, // clock ~100MHz + + inout reg [15:0] SDRAM_DQ, // 16 bit bidirectional data bus + output reg [12:0] SDRAM_A, // 13 bit multiplexed address bus + output SDRAM_DQML, // two byte masks + output SDRAM_DQMH, // + output reg [1:0] SDRAM_BA, // two banks + output SDRAM_nCS, // a single chip select + output SDRAM_nWE, // write enable + output SDRAM_nRAS, // row address select + output SDRAM_nCAS, // columns address select + output SDRAM_CKE, // clock enable + output SDRAM_CLK, + input SDRAM_EN, // clock enable + + input sel, + input [26:1] addr, // 25 bit address for 8bit mode. addr[0] = 0 for 16bit mode for correct operations. + output reg [15:0] dout, // data output to cpu + input [15:0] din, // data input from cpu + input wr, // request write + input [1:0] bs, // bit1 - write high byte, bit0 - write low byte, Ignored while reading. + input rd, // request read + output reg ready, + input refresh, + + input cpsel, + input [26:1] cpaddr, + input [15:0] cpdin, + output reg cprd, + input cpreq, + output reg cpbusy +); + +assign SDRAM_nCS = chip; +assign SDRAM_nRAS = command[2]; +assign SDRAM_nCAS = command[1]; +assign SDRAM_nWE = command[0]; +assign SDRAM_CKE = 1; +assign {SDRAM_DQMH,SDRAM_DQML} = SDRAM_A[12:11]; + +localparam BURST_LENGTH = 4; +localparam BURST_CODE = (BURST_LENGTH == 8) ? 3'b011 : (BURST_LENGTH == 4) ? 3'b010 : (BURST_LENGTH == 2) ? 3'b001 : 3'b000; // 000=1, 001=2, 010=4, 011=8 +localparam ACCESS_TYPE = 1'b0; // 0=sequential, 1=interleaved +localparam CAS_LATENCY = 3'd2; // 2 for < 100MHz, 3 for >100MHz +localparam OP_MODE = 2'b00; // only 00 (standard operation) allowed +localparam NO_WRITE_BURST = 1'b1; // 0= write burst enabled, 1=only single access write +localparam MODE = {3'b000, NO_WRITE_BURST, OP_MODE, CAS_LATENCY, ACCESS_TYPE, BURST_CODE}; + +localparam sdram_startup_cycles= 14'd12100;// 100us, plus a little more, @ 100MHz +localparam cycles_per_refresh = 14'd780; // (64000*100)/8192-1 Calc'd as (64ms @ 100MHz)/8192 rose +localparam startup_refresh_max = 14'b11111111111111; + +// SDRAM commands +wire [2:0] CMD_NOP = 3'b111; +wire [2:0] CMD_ACTIVE = 3'b011; +wire [2:0] CMD_READ = 3'b101; +wire [2:0] CMD_WRITE = 3'b100; +wire [2:0] CMD_PRECHARGE = 3'b010; +wire [2:0] CMD_AUTO_REFRESH = 3'b001; +wire [2:0] CMD_LOAD_MODE = 3'b000; + +reg [13:0] refresh_count = startup_refresh_max - sdram_startup_cycles; +reg [2:0] command; +reg chip; + +localparam STATE_STARTUP = 0; +localparam STATE_WAIT = 1; +localparam STATE_RW = 2; +localparam STATE_WAITCP = 3; +localparam STATE_CP = 4; +localparam STATE_IDLE = 5; +localparam STATE_IDLE_1 = 6; +localparam STATE_IDLE_2 = 7; +localparam STATE_IDLE_3 = 8; +localparam STATE_IDLE_4 = 9; +localparam STATE_IDLE_5 = 10; +localparam STATE_RFSH = 11; + + +always @(posedge clk) begin + reg [CAS_LATENCY:0] data_ready_delay; + + reg saved_wr; + reg [12:0] cas_addr; + reg [15:0] saved_data; + reg [8:0] cpcnt; + reg old_cpreq = 0; + reg [3:0] state = STATE_STARTUP; + reg refresh_old; + + refresh_count <= refresh_count+1'b1; + + data_ready_delay <= data_ready_delay>>1; + if(data_ready_delay[0]) ready <= 1; + + dout <= SDRAM_DQ; + SDRAM_DQ <= 'Z; + + if(SDRAM_EN) begin + command <= CMD_NOP; + case (state) + STATE_STARTUP: begin + //------------------------------------------------------------------------ + //-- This is the initial startup state, where we wait for at least 100us + //-- before starting the start sequence + //-- + //-- The initialisation is sequence is + //-- * de-assert SDRAM_CKE + //-- * 100us wait, + //-- * assert SDRAM_CKE + //-- * wait at least one cycle, + //-- * PRECHARGE + //-- * wait 2 cycles + //-- * REFRESH, + //-- * tREF wait + //-- * REFRESH, + //-- * tREF wait + //-- * LOAD_MODE_REG + //-- * 2 cycles wait + //------------------------------------------------------------------------ + SDRAM_A <= 0; + SDRAM_BA <= 0; + + if (refresh_count == (startup_refresh_max-64)) chip <= 0; + if (refresh_count == (startup_refresh_max-32)) chip <= 1; + + // All the commands during the startup are NOPS, except these + if (refresh_count == startup_refresh_max-63 || refresh_count == startup_refresh_max-31) begin + // ensure all rows are closed + command <= CMD_PRECHARGE; + SDRAM_A[10] <= 1; // all banks + SDRAM_BA <= 2'b00; + end + if (refresh_count == startup_refresh_max-55 || refresh_count == startup_refresh_max-23) begin + // these refreshes need to be at least tREF (66ns) apart + command <= CMD_AUTO_REFRESH; + end + if (refresh_count == startup_refresh_max-47 || refresh_count == startup_refresh_max-15) begin + command <= CMD_AUTO_REFRESH; + end + if (refresh_count == startup_refresh_max-39 || refresh_count == startup_refresh_max-7) begin + // Now load the mode register + command <= CMD_LOAD_MODE; + SDRAM_A <= MODE; + end + + //------------------------------------------------------ + //-- if startup is complete then go into idle mode, + //-- get prepared to accept a new command, and schedule + //-- the first refresh cycle + //------------------------------------------------------ + if (!refresh_count) begin + state <= STATE_IDLE; + ready <= 1; + refresh_count <= 0; + end + cpbusy <= 0; + end + + STATE_RFSH: begin + state <= STATE_IDLE_5; + command <= CMD_AUTO_REFRESH; + chip <= 1; + end + + STATE_IDLE_5: state <= STATE_IDLE_4; + STATE_IDLE_4: state <= STATE_IDLE_3; + STATE_IDLE_3: state <= STATE_IDLE_2; + STATE_IDLE_2: state <= STATE_IDLE_1; + STATE_IDLE_1: state <= STATE_IDLE; + + STATE_IDLE: begin + if (refresh ^ refresh_old) begin + state <= STATE_RFSH; + command <= CMD_AUTO_REFRESH; + chip <= 0; + refresh_old<= refresh; + end + else if (sel & (rd | wr)) begin + {cas_addr[12:9],SDRAM_BA,SDRAM_A,cas_addr[8:0]} <= {~wr ? 2'b00 : ~bs, 1'b1, addr[25:1]}; + chip <= addr[26]; + saved_data <= din; + saved_wr <= wr; + command <= CMD_ACTIVE; + state <= STATE_WAIT; + ready <= 0; + end + else begin + cpbusy <= 0; + cprd <= 0; + old_cpreq <= cpreq; + if(~old_cpreq & cpreq & cpsel) begin + {cas_addr[12:9],SDRAM_BA,SDRAM_A,cas_addr[8:0]} <= {2'b00, 1'b0, cpaddr[25:1]}; + chip <= cpaddr[26]; + cpbusy <= 1; + cpcnt <= 511; + command <= CMD_ACTIVE; + state <= STATE_WAITCP; + cprd <= 1; + end + end + end + + STATE_WAIT: state <= STATE_RW; + STATE_RW: begin + // Wait at least 4 cycles @96MHz (2 CAS_LATENCY + 2 PRECHARGE (tRP 21ns)) + state <= STATE_IDLE_4; + SDRAM_A <= cas_addr; + if(saved_wr) begin + command <= CMD_WRITE; + SDRAM_DQ <= saved_data; + ready <= 1; + end + else begin + command <= CMD_READ; + data_ready_delay[CAS_LATENCY] <= 1; + end + end + + STATE_WAITCP: state <= STATE_CP; + STATE_CP: begin + SDRAM_A <= {2'b00, !cpcnt, cas_addr[9:0]}; + cas_addr[8:0] <= cas_addr[8:0] + 1'd1; + cpcnt <= cpcnt - 1'd1; + command <= CMD_WRITE; + SDRAM_DQ <= cpdin; + if(!cpcnt) begin + state <= STATE_IDLE_4; + cprd <= 0; + end + end + endcase + + if (init) begin + state <= STATE_STARTUP; + refresh_count <= startup_refresh_max - sdram_startup_cycles; + end + end + else begin + ready <= 1; + cpbusy <= 0; + cprd <= 0; + dout <= 0; + SDRAM_A <= 0; + SDRAM_BA <= 0; + command <= 0; + chip <= 0; + end +end + +altddio_out +#( + .extend_oe_disable("OFF"), + .intended_device_family("Cyclone V"), + .invert_output("OFF"), + .lpm_hint("UNUSED"), + .lpm_type("altddio_out"), + .oe_reg("UNREGISTERED"), + .power_up_high("OFF"), + .width(1) +) +sdramclk_ddr +( + .datain_h(1'b0), + .datain_l(1'b1), + .outclock(clk), + .dataout(SDRAM_CLK), + .aclr(1'b0), + .aset(1'b0), + .oe(1'b1), + .outclocken(1'b1), + .sclr(1'b0), + .sset(1'b0) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram2.sdc b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram2.sdc new file mode 100644 index 0000000000000000000000000000000000000000..800c463a0b44a64cb5631e5dace9cc602db806b6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram2.sdc @@ -0,0 +1,15 @@ +derive_pll_clocks + +set clk_sdram_sys {*|pll|pll_inst|altera_pll_i|*[0].*|divclk} +set clk_sdram_chip {*|pll|pll_inst|altera_pll_i|*[2].*|divclk} + +create_generated_clock -name SDRAM2_CLK -source [get_pins -compatibility_mode $clk_sdram_chip] [get_ports {SDRAM2_CLK}] + +derive_clock_uncertainty + +# Set acceptable delays for SDRAM2 chip (See correspondent chip datasheet) +set_input_delay -max -clock $clk_sdram_sys 8.7ns [get_ports SDRAM2_DQ[*]] +set_input_delay -min -clock $clk_sdram_sys 6.0ns [get_ports SDRAM2_DQ[*]] + +set_output_delay -max -clock SDRAM2_CLK 1.6ns [get_ports {SDRAM2_D* SDRAM2_A* SDRAM2_BA* SDRAM2_n*}] +set_output_delay -min -clock SDRAM2_CLK -0.9ns [get_ports {SDRAM2_D* SDRAM2_A* SDRAM2_BA* SDRAM2_n*}] diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram_mux.sv b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram_mux.sv new file mode 100644 index 0000000000000000000000000000000000000000..b74246f5d107d40e067a9810f8d301cc92455f62 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/mem/sdram_mux.sv @@ -0,0 +1,299 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// SDRAM mux/demux logic + +module sdram_mux( + input CLK, + + input nRESET, + input nSYSTEM_G, + input SYSTEM_CDx, + + input [20:1] M68K_ADDR, + input [15:0] M68K_DATA, + input nAS, + input nLDS, + input nUDS, + input DATA_TYPE, + input nROMOE, + input nPORTOE, + input nSROMOE, + input [26:0] P2ROM_ADDR, + output reg [15:0] PROM_DATA, + output reg PROM_DATA_READY, + + input PCK2, + input [15:0] S_LATCH, + input [1:0] FIX_BANK, + input FIX_EN, + output reg [15:0] SROM_DATA, // 4 pixels + + input PCK1, + input [26:0] CROM_ADDR, + input SPR_EN, + output reg [63:0] CR_DOUBLE, // 16 pixels + + input REFRESH_EN, + + output reg SDRAM_WR, + output reg SDRAM_RD, + output reg [26:1] SDRAM_ADDR, + input [15:0] SDRAM_DOUT, + output reg [15:0] SDRAM_DIN, + input SDRAM_READY, + output reg [1:0] SDRAM_BS, + output reg SDRAM_RFSH, + + input DL_EN, + input [15:0] DL_DATA, + input [26:0] DL_ADDR, + input DL_WR, + + input DMA_RUNNING, + input [23:0] DMA_ADDR_IN, + input [23:0] DMA_ADDR_OUT, + input [15:0] DMA_DATA_OUT, + output reg DMA_SDRAM_BUSY, + input [2:0] CD_TR_AREA, + input CD_EXT_WR, + input CD_EXT_RD, + input [1:0] CD_BANK_SPR, + input CD_USE_SPR, + input CD_TR_RD_SPR, + input CD_TR_WR_SPR, + input CD_USE_FIX, + input CD_TR_RD_FIX, + input CD_TR_WR_FIX +); + + localparam P2ROM_OFFSET = 27'h0300000; + + reg M68K_RD_RUN, SFIX_RD_RUN, CROM_RD_RUN, CD_TR_RUN; + + reg SDRAM_M68K_SIG_SR; + reg SDRAM_CROM_SIG_SR; + reg SDRAM_SROM_SIG_SR; + reg CD_WR_SDRAM_SIG_SR; + reg CD_RD_SDRAM_SIG_SR; + + wire SDRAM_M68K_SIG = ~&{nSROMOE, nROMOE, nPORTOE}; + + wire REQ_CD_RD = (~CD_RD_SDRAM_SIG_SR & CD_RD_SDRAM_SIG); + wire REQ_CD_WR = (~CD_WR_SDRAM_SIG_SR & CD_WR_SDRAM_SIG); + wire REQ_M68K_RD = (~SDRAM_M68K_SIG_SR & SDRAM_M68K_SIG) | REQ_CD_RD; + wire REQ_CROM_RD = (SDRAM_CROM_SIG_SR & ~PCK1) & SPR_EN & ~CD_USE_SPR & ~REFRESH_EN; + wire REQ_SROM_RD = (SDRAM_SROM_SIG_SR & ~PCK2) & FIX_EN & ~CD_USE_FIX & ~REFRESH_EN; + wire REQ_RFSH = (SDRAM_CROM_SIG_SR & ~PCK1) & REFRESH_EN; + + wire CD_RD_SDRAM_SIG = CD_EXT_RD | CD_TR_RD_FIX | CD_TR_RD_SPR; + wire CD_WR_SDRAM_SIG = CD_EXT_WR | CD_TR_WR_FIX | CD_TR_WR_SPR; + wire CD_LDS_ONLY_WR = CD_TR_WR_FIX; + + wire [24:0] CD_REMAP_TR_ADDR; + always_comb begin + casez({CD_EXT_RD, CD_EXT_WR, CD_TR_AREA}) + // Read P1 (CD DMA) or Extended RAM (CD DMA+68K) $0100000~$01FFFFF + 5'b1_?_???: CD_REMAP_TR_ADDR = DMA_RUNNING ? {3'b0_00, ~DMA_ADDR_IN[20], DMA_ADDR_IN[20:1], 1'b0} : {3'b0_00, ~M68K_ADDR[20], M68K_ADDR[20:1], ~nLDS}; + + // Write P1 or Extended RAM + 5'b0_1_???: CD_REMAP_TR_ADDR = DMA_RUNNING ? {3'b0_00, ~DMA_ADDR_OUT[20], DMA_ADDR_OUT[20:1], 1'b0} : {3'b0_00, ~M68K_ADDR[20], M68K_ADDR[20:1], ~nLDS}; + + // Sprites SDRAM + 5'b0_0_000: CD_REMAP_TR_ADDR = DMA_RUNNING ? {3'b0_10, CD_BANK_SPR, DMA_ADDR_OUT[19:7], DMA_ADDR_OUT[5:2], ~DMA_ADDR_OUT[6], ~DMA_ADDR_OUT[1], 1'b0} : {3'b0_10, CD_BANK_SPR, M68K_ADDR[19:7], M68K_ADDR[5:2], ~M68K_ADDR[6], ~M68K_ADDR[1], ~nLDS}; + + // FIX SDRAM + 5'b0_0_101: CD_REMAP_TR_ADDR = DMA_RUNNING ? {8'b0_0000_100, DMA_ADDR_OUT[17:6], DMA_ADDR_OUT[3:1], ~DMA_ADDR_OUT[5], ~DMA_ADDR_OUT[4]} : {8'b0_0000_100, M68K_ADDR[17:6], M68K_ADDR[3:1], ~M68K_ADDR[5], ~M68K_ADDR[4]}; + + default: CD_REMAP_TR_ADDR = 25'h0AAAAAA; // DEBUG + endcase + end + + always @(posedge CLK) begin + reg M68K_RD_REQ, SROM_RD_REQ, CROM_RD_REQ, CD_WR_REQ, RFSH_REQ; + reg nAS_PREV; + reg old_ready; + reg [8:0] refresh_cnt; + reg [1:0] cr_shift; + + if(DL_WR & DL_EN) begin + SDRAM_ADDR<= DL_ADDR[26:1]; + SDRAM_DIN <= DL_DATA; + SDRAM_WR <= 1; + SDRAM_BS <= 2'b11; + end + + old_ready <= SDRAM_READY; + if(old_ready & ~SDRAM_READY) begin + SDRAM_WR <= 0; + SDRAM_RD <= 0; + end + + if(~&cr_shift) begin + CR_DOUBLE[cr_shift*16 +:16] <= SDRAM_DOUT; + cr_shift <= cr_shift - 1'd1; + end + + nAS_PREV <= nAS; + + CD_RD_SDRAM_SIG_SR <= CD_RD_SDRAM_SIG; + CD_WR_SDRAM_SIG_SR <= CD_WR_SDRAM_SIG; + + SDRAM_M68K_SIG_SR <= SDRAM_M68K_SIG; + SDRAM_CROM_SIG_SR <= PCK1; + SDRAM_SROM_SIG_SR <= PCK2; + + refresh_cnt <= refresh_cnt + 1'd1; + + if (!nRESET) begin + CROM_RD_REQ <= 0; + SROM_RD_REQ <= 0; + M68K_RD_REQ <= 0; + CD_WR_REQ <= 0; + + CROM_RD_RUN <= 0; + SFIX_RD_RUN <= 0; + M68K_RD_RUN <= 0; + CD_TR_RUN <= 0; + RFSH_REQ <= 0; + + if(!refresh_cnt) SDRAM_RFSH <= ~SDRAM_RFSH; + + DMA_SDRAM_BUSY <= 0; + + if(~DL_EN) begin + SDRAM_WR <= 0; + SDRAM_RD <= 0; + end + end + else begin + if ((~nAS_PREV & nAS) | DMA_RUNNING) PROM_DATA_READY <= 0; + if (~DMA_RUNNING) DMA_SDRAM_BUSY <= 0; + + // Detect 68k or CD read requests + // Detect rising edge of SDRAM_M68K_SIG + if (REQ_M68K_RD) M68K_RD_REQ <= 1; + + // In DMA, start if: nothing is running, no LSPC read (priority case C) + // Out of DMA, start if: nothing is running (priority case B) + if (REQ_CD_WR) CD_WR_REQ <= 1; + + // Detect sprite data read requests + // Detect rising edge of PCK1B + if (REQ_CROM_RD) CROM_RD_REQ <= 1; + + // Detect fix data read requests + // Detect rising edge of PCK2B + // See dev_notes.txt about why there's only one read for FIX graphics + // regardless of the S2H1 signal + if (REQ_SROM_RD) SROM_RD_REQ <= 1; + + if (REQ_RFSH) RFSH_REQ <= 1; + + if (SDRAM_READY & ~SDRAM_RD & ~SDRAM_WR) begin + + // Terminate running access, if needed + // Having two non-nested IF statements with the & in the condition + // prevents synthesis from chaining too many muxes and causing + // timing analysis to fail + if (CD_TR_RUN) begin + CD_TR_RUN <= 0; + DMA_SDRAM_BUSY <= 0; + end + if (SFIX_RD_RUN) begin + SROM_DATA <= SDRAM_DOUT; + SFIX_RD_RUN <= 0; + end + if (M68K_RD_RUN) begin + PROM_DATA <= SDRAM_DOUT; + PROM_DATA_READY<= 1; + M68K_RD_RUN <= 0; + DMA_SDRAM_BUSY <= 0; + end + if (CROM_RD_RUN) begin + CR_DOUBLE[63:48]<= SDRAM_DOUT; + CROM_RD_RUN <= 0; + cr_shift <= 2; + end + + // Start requested access, if needed + if (M68K_RD_REQ | REQ_M68K_RD) begin + M68K_RD_REQ <= 0; + M68K_RD_RUN <= 1; + CD_TR_RUN <= CD_RD_SDRAM_SIG; + SDRAM_RD <= 1; + DMA_SDRAM_BUSY <= DMA_RUNNING; + + casez ({CD_RD_SDRAM_SIG, ~nROMOE, ~nPORTOE}) + // CD transfer + 3'b1zz: SDRAM_ADDR <= CD_REMAP_TR_ADDR[24:1]; + + // P1 ROM $0200000~$02FFFFF + 3'b01z: SDRAM_ADDR <= {5'b0_0010, M68K_ADDR[19:1]}; + + // P2 ROM (cart) $0300000~... bankswitched + 3'b001: SDRAM_ADDR <= P2ROM_OFFSET[26:1] + P2ROM_ADDR[26:1]; + + // System ROM (CD) $0000000~$007FFFF + // System ROM (cart) $0000000~$001FFFF + default: SDRAM_ADDR <= SYSTEM_CDx ? {6'b0_0000_0, M68K_ADDR[18:1]} : + {8'b0_0000_000, M68K_ADDR[16:1]} ; + endcase + + end + else if (CROM_RD_REQ | REQ_CROM_RD) begin + CROM_RD_REQ <= 0; + CROM_RD_RUN <= 1; + SDRAM_RD <= 1; + SDRAM_ADDR <= CROM_ADDR[26:1]; + end + else if (SROM_RD_REQ | REQ_SROM_RD) begin + SROM_RD_REQ <= 0; + SFIX_RD_RUN <= 1; + SDRAM_RD <= 1; + + // SFIX ROM (CD) $0080000~$009FFFF + // S1 ROM (cart) $0080000~$00FFFFF + // SFIX ROM (cart) $0020000~$003FFFF + SDRAM_ADDR <= SYSTEM_CDx ? {8'b0_0000_100, S_LATCH[15:4], S_LATCH[2:0], ~S_LATCH[3]}: + nSYSTEM_G ? {6'b0_0000_1, FIX_BANK, S_LATCH[15:4], S_LATCH[2:0], ~S_LATCH[3]}: + {8'b0_0000_001, S_LATCH[15:4], S_LATCH[2:0], ~S_LATCH[3]}; + end + else if (REQ_CD_WR | CD_WR_REQ) begin + CD_WR_REQ <= 0; + CD_TR_RUN <= 1; + SDRAM_WR <= 1; + DMA_SDRAM_BUSY <= DMA_RUNNING; + SDRAM_ADDR <= CD_REMAP_TR_ADDR[24:1]; + + // DMA writes are always done in words. FIX layer is on a 8bit bus so should only write the low byte. + SDRAM_BS <= (CD_LDS_ONLY_WR | ((CD_EXT_WR | (CD_TR_AREA == 3'd0)) & (nLDS ^ nUDS))) ? {~CD_REMAP_TR_ADDR[0],CD_REMAP_TR_ADDR[0]} : 2'b11; + + SDRAM_DIN <= DMA_RUNNING ? (CD_LDS_ONLY_WR ? {DMA_DATA_OUT[7:0],DMA_DATA_OUT[7:0]} : DMA_DATA_OUT) : + (CD_LDS_ONLY_WR ? {M68K_DATA[7:0], M68K_DATA[7:0]} : M68K_DATA); + end + else if(REQ_RFSH & RFSH_REQ) begin + RFSH_REQ <= 0; + SDRAM_RFSH <= ~SDRAM_RFSH; + end + end + end + end +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/pll.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/pll.v new file mode 100644 index 0000000000000000000000000000000000000000..8c8e54eafe7c987f054979b738e5eb1bdf3ef6e9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/pll.v @@ -0,0 +1,259 @@ +// megafunction wizard: %Altera PLL v17.0% +// GENERATION: XML +// pll.v + +// Generated using ACDS version 17.0 602 + +`timescale 1 ps / 1 ps +module pll ( + input wire refclk, // refclk.clk + input wire rst, // reset.reset + output wire outclk_0, // outclk0.clk + output wire outclk_1, // outclk1.clk + output wire locked, // locked.export + input wire [63:0] reconfig_to_pll, // reconfig_to_pll.reconfig_to_pll + output wire [63:0] reconfig_from_pll // reconfig_from_pll.reconfig_from_pll + ); + + pll_0002 pll_inst ( + .refclk (refclk), // refclk.clk + .rst (rst), // reset.reset + .outclk_0 (outclk_0), // outclk0.clk + .outclk_1 (outclk_1), // outclk1.clk + .locked (locked), // locked.export + .reconfig_to_pll (reconfig_to_pll), // reconfig_to_pll.reconfig_to_pll + .reconfig_from_pll (reconfig_from_pll) // reconfig_from_pll.reconfig_from_pll + ); + +endmodule +// Retrieval info: +// +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// IPFS_FILES : pll.vo +// RELATED_FILES: pll.v, pll_0002.v diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/pll/pll_0002.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/pll/pll_0002.v new file mode 100644 index 0000000000000000000000000000000000000000..df2f27c470b3b190a60a5929cc472e2de6bafda0 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/pll/pll_0002.v @@ -0,0 +1,244 @@ +`timescale 1ns/10ps +module pll_0002( + + // interface 'refclk' + input wire refclk, + + // interface 'reset' + input wire rst, + + // interface 'outclk0' + output wire outclk_0, + + // interface 'outclk1' + output wire outclk_1, + + // interface 'locked' + output wire locked, + + // interface 'reconfig_to_pll' + input wire [63:0] reconfig_to_pll, + + // interface 'reconfig_from_pll' + output wire [63:0] reconfig_from_pll +); + + altera_pll #( + .fractional_vco_multiplier("true"), + .reference_clock_frequency("50.0 MHz"), + .pll_fractional_cout(32), + .pll_dsm_out_sel("1st_order"), + .operation_mode("direct"), + .number_of_clocks(2), + .output_clock_frequency0("96.671316 MHz"), + .phase_shift0("0 ps"), + .duty_cycle0(50), + .output_clock_frequency1("48.335658 MHz"), + .phase_shift1("0 ps"), + .duty_cycle1(50), + .output_clock_frequency2("0 MHz"), + .phase_shift2("0 ps"), + .duty_cycle2(50), + .output_clock_frequency3("0 MHz"), + .phase_shift3("0 ps"), + .duty_cycle3(50), + .output_clock_frequency4("0 MHz"), + .phase_shift4("0 ps"), + .duty_cycle4(50), + .output_clock_frequency5("0 MHz"), + .phase_shift5("0 ps"), + .duty_cycle5(50), + .output_clock_frequency6("0 MHz"), + .phase_shift6("0 ps"), + .duty_cycle6(50), + .output_clock_frequency7("0 MHz"), + .phase_shift7("0 ps"), + .duty_cycle7(50), + .output_clock_frequency8("0 MHz"), + .phase_shift8("0 ps"), + .duty_cycle8(50), + .output_clock_frequency9("0 MHz"), + .phase_shift9("0 ps"), + .duty_cycle9(50), + .output_clock_frequency10("0 MHz"), + .phase_shift10("0 ps"), + .duty_cycle10(50), + .output_clock_frequency11("0 MHz"), + .phase_shift11("0 ps"), + .duty_cycle11(50), + .output_clock_frequency12("0 MHz"), + .phase_shift12("0 ps"), + .duty_cycle12(50), + .output_clock_frequency13("0 MHz"), + .phase_shift13("0 ps"), + .duty_cycle13(50), + .output_clock_frequency14("0 MHz"), + .phase_shift14("0 ps"), + .duty_cycle14(50), + .output_clock_frequency15("0 MHz"), + .phase_shift15("0 ps"), + .duty_cycle15(50), + .output_clock_frequency16("0 MHz"), + .phase_shift16("0 ps"), + .duty_cycle16(50), + .output_clock_frequency17("0 MHz"), + .phase_shift17("0 ps"), + .duty_cycle17(50), + .pll_type("Cyclone V"), + .pll_subtype("Reconfigurable"), + .m_cnt_hi_div(5), + .m_cnt_lo_div(4), + .n_cnt_hi_div(256), + .n_cnt_lo_div(256), + .m_cnt_bypass_en("false"), + .n_cnt_bypass_en("true"), + .m_cnt_odd_div_duty_en("true"), + .n_cnt_odd_div_duty_en("false"), + .c_cnt_hi_div0(3), + .c_cnt_lo_div0(2), + .c_cnt_prst0(1), + .c_cnt_ph_mux_prst0(0), + .c_cnt_in_src0("ph_mux_clk"), + .c_cnt_bypass_en0("false"), + .c_cnt_odd_div_duty_en0("true"), + .c_cnt_hi_div1(5), + .c_cnt_lo_div1(5), + .c_cnt_prst1(1), + .c_cnt_ph_mux_prst1(0), + .c_cnt_in_src1("ph_mux_clk"), + .c_cnt_bypass_en1("false"), + .c_cnt_odd_div_duty_en1("false"), + .c_cnt_hi_div2(1), + .c_cnt_lo_div2(1), + .c_cnt_prst2(1), + .c_cnt_ph_mux_prst2(0), + .c_cnt_in_src2("ph_mux_clk"), + .c_cnt_bypass_en2("true"), + .c_cnt_odd_div_duty_en2("false"), + .c_cnt_hi_div3(1), + .c_cnt_lo_div3(1), + .c_cnt_prst3(1), + .c_cnt_ph_mux_prst3(0), + .c_cnt_in_src3("ph_mux_clk"), + .c_cnt_bypass_en3("true"), + .c_cnt_odd_div_duty_en3("false"), + .c_cnt_hi_div4(1), + .c_cnt_lo_div4(1), + .c_cnt_prst4(1), + .c_cnt_ph_mux_prst4(0), + .c_cnt_in_src4("ph_mux_clk"), + .c_cnt_bypass_en4("true"), + .c_cnt_odd_div_duty_en4("false"), + .c_cnt_hi_div5(1), + .c_cnt_lo_div5(1), + .c_cnt_prst5(1), + .c_cnt_ph_mux_prst5(0), + .c_cnt_in_src5("ph_mux_clk"), + .c_cnt_bypass_en5("true"), + .c_cnt_odd_div_duty_en5("false"), + .c_cnt_hi_div6(1), + .c_cnt_lo_div6(1), + .c_cnt_prst6(1), + .c_cnt_ph_mux_prst6(0), + .c_cnt_in_src6("ph_mux_clk"), + .c_cnt_bypass_en6("true"), + .c_cnt_odd_div_duty_en6("false"), + .c_cnt_hi_div7(1), + .c_cnt_lo_div7(1), + .c_cnt_prst7(1), + .c_cnt_ph_mux_prst7(0), + .c_cnt_in_src7("ph_mux_clk"), + .c_cnt_bypass_en7("true"), + .c_cnt_odd_div_duty_en7("false"), + .c_cnt_hi_div8(1), + .c_cnt_lo_div8(1), + .c_cnt_prst8(1), + .c_cnt_ph_mux_prst8(0), + .c_cnt_in_src8("ph_mux_clk"), + .c_cnt_bypass_en8("true"), + .c_cnt_odd_div_duty_en8("false"), + .c_cnt_hi_div9(1), + .c_cnt_lo_div9(1), + .c_cnt_prst9(1), + .c_cnt_ph_mux_prst9(0), + .c_cnt_in_src9("ph_mux_clk"), + .c_cnt_bypass_en9("true"), + .c_cnt_odd_div_duty_en9("false"), + .c_cnt_hi_div10(1), + .c_cnt_lo_div10(1), + .c_cnt_prst10(1), + .c_cnt_ph_mux_prst10(0), + .c_cnt_in_src10("ph_mux_clk"), + .c_cnt_bypass_en10("true"), + .c_cnt_odd_div_duty_en10("false"), + .c_cnt_hi_div11(1), + .c_cnt_lo_div11(1), + .c_cnt_prst11(1), + .c_cnt_ph_mux_prst11(0), + .c_cnt_in_src11("ph_mux_clk"), + .c_cnt_bypass_en11("true"), + .c_cnt_odd_div_duty_en11("false"), + .c_cnt_hi_div12(1), + .c_cnt_lo_div12(1), + .c_cnt_prst12(1), + .c_cnt_ph_mux_prst12(0), + .c_cnt_in_src12("ph_mux_clk"), + .c_cnt_bypass_en12("true"), + .c_cnt_odd_div_duty_en12("false"), + .c_cnt_hi_div13(1), + .c_cnt_lo_div13(1), + .c_cnt_prst13(1), + .c_cnt_ph_mux_prst13(0), + .c_cnt_in_src13("ph_mux_clk"), + .c_cnt_bypass_en13("true"), + .c_cnt_odd_div_duty_en13("false"), + .c_cnt_hi_div14(1), + .c_cnt_lo_div14(1), + .c_cnt_prst14(1), + .c_cnt_ph_mux_prst14(0), + .c_cnt_in_src14("ph_mux_clk"), + .c_cnt_bypass_en14("true"), + .c_cnt_odd_div_duty_en14("false"), + .c_cnt_hi_div15(1), + .c_cnt_lo_div15(1), + .c_cnt_prst15(1), + .c_cnt_ph_mux_prst15(0), + .c_cnt_in_src15("ph_mux_clk"), + .c_cnt_bypass_en15("true"), + .c_cnt_odd_div_duty_en15("false"), + .c_cnt_hi_div16(1), + .c_cnt_lo_div16(1), + .c_cnt_prst16(1), + .c_cnt_ph_mux_prst16(0), + .c_cnt_in_src16("ph_mux_clk"), + .c_cnt_bypass_en16("true"), + .c_cnt_odd_div_duty_en16("false"), + .c_cnt_hi_div17(1), + .c_cnt_lo_div17(1), + .c_cnt_prst17(1), + .c_cnt_ph_mux_prst17(0), + .c_cnt_in_src17("ph_mux_clk"), + .c_cnt_bypass_en17("true"), + .c_cnt_odd_div_duty_en17("false"), + .pll_vco_div(2), + .pll_cp_current(30), + .pll_bwctrl(2000), + .pll_output_clk_frequency("483.356579 MHz"), + .pll_fractional_division("2865308404"), + .mimic_fbclk_type("none"), + .pll_fbclk_mux_1("glb"), + .pll_fbclk_mux_2("m_cnt"), + .pll_m_cnt_in_src("ph_mux_clk"), + .pll_slf_rst("true") + ) altera_pll_i ( + .rst (rst), + .outclk ({outclk_1, outclk_0}), + .locked (locked), + .reconfig_to_pll (reconfig_to_pll), + .fboutclk ( ), + .fbclk (1'b0), + .refclk (refclk), + .reconfig_from_pll (reconfig_from_pll) + ); +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/autoanim.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/autoanim.v new file mode 100644 index 0000000000000000000000000000000000000000..0a7b8be13a5271cc1eb9e6bb21078d6ac12924d4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/autoanim.v @@ -0,0 +1,65 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +/* verilator lint_off PINMISSING */ + +module autoanim_sync( + input CLK, + input RASTER8, + input RESETP, + input [7:0] AA_SPEED, + output [2:0] AA_COUNT +); + + wire [3:0] D151_Q; + + //wire B91_CO; + //wire E117_CO; + + //wire E95A_OUT = ~|{E117_CO, 1'b0}; // Used for test mode + //wire E149_OUT = ~^{CLK, 1'b0}; // Used for test mode + + // Timer counters + //C43 B91(E149_OUT, ~AA_SPEED[3:0], E95A_OUT, 1'b1, 1'b1, 1'b1, , B91_CO); + //C43 E117(E149_OUT, ~AA_SPEED[7:4], E95A_OUT, 1'b1, B91_CO, 1'b1, , E117_CO); + + // Auto-anim tile counter + //C43 D151(E149_OUT, 4'b0000, 1'b1, 1'b1, E117_CO, RESETP, D151_Q); + + //assign AA_COUNT = D151_Q[2:0]; + + reg [7:0] TIMER_CNT; + reg [3:0] AA_CNT_FULL; + always @(posedge CLK) begin + reg RASTER8_d; + RASTER8_d <= RASTER8; + if (~RASTER8_d & RASTER8) begin + if (&TIMER_CNT) + TIMER_CNT <= ~AA_SPEED; + else + TIMER_CNT <= TIMER_CNT + 1'd1; + + if (!RESETP) + AA_CNT_FULL <= 0; + else if (&TIMER_CNT) + AA_CNT_FULL <= AA_CNT_FULL + 1'd1; + end + end + + assign AA_COUNT = AA_CNT_FULL[2:0]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/fast_cycle.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/fast_cycle.v new file mode 100644 index 0000000000000000000000000000000000000000..6d352e591353b058466b700ff99cb06dfc08a706 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/fast_cycle.v @@ -0,0 +1,503 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi + +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +/* verilator lint_off PINMISSING */ + +module fast_cycle_sync( + input CLK, + input CLK_24M, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + input LSPC_EN_12M, + input LSPC_EN_6M, + input LSPC_EN_3M, + input LSPC_1_5M, + input RESETP, + input nVRAM_WRITE_REQ, + input [15:0] VRAM_ADDR, + input [15:0] VRAM_WRITE, + input REG_VRAMADDR_MSB, + input FLIP, nFLIP, + input [8:0] PIXELC, + input [8:0] RASTERC, + input P50_CO, + output reg nCPU_WR_HIGH, + output [3:0] HSHRINK, + output [13:0] PIPE_C, + output reg [15:0] VRAM_HIGH_READ, + output reg [7:0] ACTIVE_RD, + output reg R91_Q, + output reg R91_nQ, + input T140_Q, + input T58A_OUT, + input T73A_OUT, + input U129A_Q, + input T125A_OUT, + input T125A_OUT_RISE, + output CLK_ACTIVE_RD_EN, + output reg ACTIVE_RD_PRE8, + output reg [8:0] SPR_Y, + output reg [7:0] YSHRINK, + output reg SPR_SIZE0, + output reg SPR_SIZE5, + output O159_QB, + + output [10:0] FVRAM_ADDR, + input [15:0] FVRAM_DATA_IN, + output [15:0] FVRAM_DATA_OUT, + output CWE +); + + wire [10:0] C; + wire [15:0] F; + reg [8:0] PARSE_Y; + reg [5:0] PARSE_SIZE; + wire [15:0] F_OUT_MUX; + reg [7:0] ACTIVE_RD_PRE; + wire [3:0] J127_Q; + reg [3:0] T102_Q; + wire [7:0] PARSE_LOOKAHEAD; + wire [8:0] PARSE_ADD_Y; + wire [5:0] PARSE_ADD_SIZE; + reg [3:0] XSHRINK; //O141_Q + reg [7:0] ACTIVE_RD_ADDR; // Bit 7 unused + reg [7:0] ACTIVE_WR_ADDR; // Bit 7 unused + wire [10:0] A_TOP; + wire [10:0] B_TOP; + wire [10:0] C_TOP; + wire [10:0] D_TOP; + wire [10:0] A_BOT; + wire [10:0] B_BOT; + wire [10:0] C_BOT; + wire [10:0] D_BOT; + reg PARSE_CHAIN /* synthesis keep */; // DEBUG + wire T90A_OUT /* synthesis keep */; // DEBUG + reg [8:0] PARSE_INDEX_test; + reg [8:0] PARSE_INDEX; + wire P39A_OUT; + reg [41:0] SR_SPR_PARAMS; // 3*14 + reg S105_OUT; + reg [7:0] J87_G152_Q; + reg J231_Q; + reg [7:0] J102_E175_Q; + reg J194_Q; + + reg N98_QC; + reg SPR_CHAIN; + reg N98_QB; + reg N98_QD; + wire N98_QD_DELAYED; + reg O98_Q; + reg nPARSING_DONE; + reg S111_Q; + reg S111_nQ; + reg WR_ACTIVE; + reg T129A_nQ; + reg T66_Q; + reg S67_nQ; + wire S71A_OUT; + reg S74_Q; + reg T148_Q; + wire H198_CO; + reg N98_QA; + wire I151_CO; + + assign FVRAM_ADDR = C; + assign F = FVRAM_DATA_IN; + assign FVRAM_DATA_OUT = F_OUT_MUX; + + // CPU read + // L251 L269 L233 K249 + reg CLK_CPU_READ_HIGH /* synthesis keep */; + //FDS16bit L251(~CLK_CPU_READ_HIGH, F, VRAM_HIGH_READ); + always @(posedge CLK) if (CLK_CPU_READ_HIGH_FALL) VRAM_HIGH_READ <= F; + + // Y parsing read + // N214 M214 M178 L190 + //FDS16bit N214(O109A_OUT, F, {PARSE_Y, PARSE_CHAIN, PARSE_SIZE}); + always @(posedge CLK) if (O109A_OUT_RISE) {PARSE_Y, PARSE_CHAIN, PARSE_SIZE} <= F; + + // Y Rendering read + //FDSCell M250(N98_QC, F[15:12], SPR_Y[8:5]); + //FDSCell M269(N98_QC, F[11:8], SPR_Y[4:1]); + //FDSCell M233(N98_QC, {F[7:5], F[0]}, {SPR_Y[0], SPR_CHAIN, SPR_SIZE5, SPR_SIZE0}); + always @(posedge CLK) if (N98_QC_RISE) {SPR_Y[8:0], SPR_CHAIN, SPR_SIZE5, SPR_SIZE0} <= {F[15:5], F[0]}; + + // Active list read + //FDSCell J117(H125A_OUT, F[7:4], ACTIVE_RD_PRE[7:4]); + //FDSCell J178(H125A_OUT, F[3:0], ACTIVE_RD_PRE[3:0]); + // Next step + //FDSCell I32(CLK_ACTIVE_RD, ACTIVE_RD_PRE[7:4], ACTIVE_RD[7:4]); + //FDSCell H165(CLK_ACTIVE_RD, ACTIVE_RD_PRE[3:0], ACTIVE_RD[3:0]); + always @(posedge CLK) + if (CLK_ACTIVE_RD_EN) begin + ACTIVE_RD_PRE[7:0] <= F[7:0]; + ACTIVE_RD_PRE8 <= F[8]; + ACTIVE_RD[7:0] <= ACTIVE_RD_PRE[7:0]; + end + + // Shrink read + //FDSCell O141(N98_QB, F[11:8], O141_Q); + //FDSCell O123(N98_QB, F[7:4], YSHRINK[7:4]); + //FDSCell K178(N98_QB, F[3:0], YSHRINK[3:0]); + always @(posedge CLK) if (N98_QB_RISE) {XSHRINK, YSHRINK} <= F[11:0]; + + // Data output selectors + // O171B O171A O173B O173A + // B178B B173B B171B C180B + // C146B C144B C142B C149B + // E207B E207A E209B E209A + + assign F_OUT_MUX = CLK_CPU_READ_HIGH ? VRAM_WRITE : {7'b0000000, J194_Q, J102_E175_Q}; + + //assign F = CWE ? 16'bzzzzzzzzzzzzzzzz : F_OUT_MUX; + + // OK + //always @(posedge PARSE_INDEX_INC_CLK) + //{J231_Q, J87_G152_Q} <= PARSE_INDEX; + always @(posedge CLK) if (PARSE_INDEX_INC_CLK_EN) {J231_Q, J87_G152_Q} <= PARSE_INDEX; + + // OK +/* + always @(posedge O109A_OUT or negedge nPARSING_DONE) + begin + if (!nPARSING_DONE) + {J194_Q, J102_E175_Q} <= 9'd0; + else + {J194_Q, J102_E175_Q} <= {J231_Q, J87_G152_Q}; + end +*/ + always @(posedge CLK, negedge nPARSING_DONE) + if (!nPARSING_DONE) {J194_Q, J102_E175_Q} <= 9'd0; + else if (O109A_OUT_RISE) {J194_Q, J102_E175_Q} <= {J231_Q, J87_G152_Q}; + + //wire O112B_OUT = O109A_OUT; // 2x inverter + /*FDSCell G152(PARSE_INDEX_INC_CLK, PARSE_INDEX[3:0], G152_Q); + //assign #5 G152_Q_DELAYED = G152_Q; // 4x BD3 + always @(posedge CLK_24M) // TESTING - ok, solves issue + G152_Q_DELAYED <= G152_Q; + FDSCell J87(PARSE_INDEX_INC_CLK, PARSE_INDEX[7:4], J87_Q); + //assign #5 J87_Q_DELAYED = J87_Q; // 4x BD3 + always @(posedge CLK_24M) // TESTING - ok, solves issue + J87_Q_DELAYED <= J87_Q; + + FDRCell E175(O109A_OUT, G152_Q_DELAYED, nPARSING_DONE, E175_Q); + FDRCell J102(O109A_OUT, J87_Q_DELAYED, nPARSING_DONE, J102_Q); + FDM J231(PARSE_INDEX_INC_CLK, PARSE_INDEX[8], J231_Q); + BD3 J235A(J231_Q, J231_Q_DELAYED); + //always @(posedge CLK_24M) // TESTED: don't do this + // J231_Q_DELAYED <= J231_Q; + FDPCell J194(O112B_OUT, J231_Q_DELAYED, 1'b1, nPARSING_DONE, J194_Q);*/ + + + // CWE output + wire O107A_OUT = VRAM_HIGH_ADDR_SB & nCPU_WR_HIGH; + wire T146A_OUT = ~|{T129A_nQ, T148_Q}; + assign CWE = O107A_OUT | T146A_OUT; + // O103A + wire VRAM_HIGH_ADDR_SB = ~&{WR_ACTIVE, O98_Q}; + BD3 O84A(N98_QD, N98_QD_DELAYED); + //FDPCell O98(T125A_OUT, N98_QD_DELAYED, 1'b1, RESETP, O98_Q, CLK_CPU_READ_HIGH); + always @(posedge CLK, negedge RESETP) + if (!RESETP) {O98_Q, CLK_CPU_READ_HIGH} <= 2'b01; + else if (T125A_OUT_RISE) {O98_Q, CLK_CPU_READ_HIGH} <= {N98_QD_DELAYED, ~N98_QD_DELAYED}; + wire CLK_CPU_READ_HIGH_RISE = ~CLK_CPU_READ_HIGH & ~N98_QD_DELAYED & T125A_OUT_RISE; + wire CLK_CPU_READ_HIGH_FALL = CLK_CPU_READ_HIGH & N98_QD_DELAYED & T125A_OUT_RISE; + + //FDPCell N93(N98_QD, F58A_OUT, CLK_CPU_READ_HIGH, 1'b1, nCPU_WR_HIGH); + always @(posedge CLK) + if (~CLK_CPU_READ_HIGH) nCPU_WR_HIGH <= 1; + else if (T125A_OUT_RISE & !N98_QD & N98_QC) nCPU_WR_HIGH <= F58A_OUT; + + + wire F58A_OUT = ~REG_VRAMADDR_MSB | nVRAM_WRITE_REQ; + //FDM I148(H125A_OUT, F[8], ACTIVE_RD_PRE8); + //wire H125A_OUT = CLK_ACTIVE_RD; + + + // Parsing end detection + // TESTING THIS: + /*reg nPARSING_DONE; + always @(posedge O109A_OUT or negedge nNEW_LINE) + begin + if (!nNEW_LINE) + nPARSING_DONE <= 1'b1; + else + begin + if (&{PARSE_INDEX[8], PARSE_INDEX[6:1]}) + nPARSING_DONE <= 1'b0; + end + end*/ + wire I145_OUT = ~&{PARSE_INDEX[6:1], PARSE_INDEX[8]}; + wire R113A_OUT = I145_OUT & nPARSING_DONE; + //FDPCell R109(O109A_OUT, R113A_OUT, nNEW_LINE, 1'b1, nPARSING_DONE); + always @(posedge CLK, negedge nNEW_LINE) + if (!nNEW_LINE) nPARSING_DONE <= 1; + else if (O109A_OUT_RISE) nPARSING_DONE <= R113A_OUT; + + // Active list full detection + /*reg S111_Q; + wire S111_nQ = ~S111_Q; + always @(posedge O109A_OUT or negedge nNEW_LINE) + begin + if (!nNEW_LINE) + S111_Q <= 1'b1; + else + begin + if (&{ACTIVE_WR_ADDR[6:5]}) + S111_Q <= 1'b0; + end + end*/ + wire S109B_OUT = S111_Q & nACTIVE_FULL; + //FDPCell S111(O109A_OUT, S109B_OUT, nNEW_LINE, 1'b1, S111_Q, S111_nQ); + + always @(posedge CLK, negedge nNEW_LINE) + if (!nNEW_LINE) {S111_Q, S111_nQ} <= 2'b10; + else if (O109A_OUT_RISE) {S111_Q, S111_nQ} <= {S109B_OUT, ~S109B_OUT}; + + wire S109A_OUT = S111_Q & nNEW_LINE; + + // Write to fast VRAM enable + wire T95A_OUT = IS_ACTIVE & T102_Q[0]; + wire R107A_OUT = nPARSING_DONE | S111_nQ; + //FDPCell R103(O109A_OUT, T95A_OUT, R107A_OUT, S109A_OUT, WR_ACTIVE); + + reg WR_ACTIVE_REG; + always @(*) begin + if (!R107A_OUT) + WR_ACTIVE = 1; + else if (!S109A_OUT) + WR_ACTIVE = 0; + else + WR_ACTIVE = WR_ACTIVE_REG; + end + always @(posedge CLK) begin + WR_ACTIVE_REG <= WR_ACTIVE; + if (O109A_OUT_RISE) WR_ACTIVE_REG <= T95A_OUT; + end + + //FD2 T129A(CLK_24M, T126B_OUT, , T129A_nQ); + always @(posedge CLK) if (CLK_EN_24M_N) T129A_nQ <= ~T126B_OUT; + wire T126B_OUT = ~&{T66_Q, T140_Q}; + //FDM T66(LSPC_12M, T58A_OUT, T66_Q); + always @(posedge CLK) if (LSPC_EN_12M) T66_Q <= T58A_OUT; + + wire P49A_OUT = PIXELC[8]; + //FDM S67(LSPC_3M, P49A_OUT, , S67_nQ); + always @(posedge CLK) if (LSPC_EN_3M) S67_nQ <= ~P49A_OUT; + wire S70B_OUT = ~&{S67_nQ, P49A_OUT}; + BD3 S71A(S70B_OUT, S71A_OUT); + //FDM S74(LSPC_6M, S71A_OUT, S74_Q); + always @(posedge CLK) if (LSPC_EN_6M) S74_Q <= S71A_OUT; + // S107A Used for test mode + wire nNEW_LINE = 1'b1 & S74_Q /* synthesis keep */; + + //FDM T148(CLK_24M, T128B_OUT, T148_Q); + always @(posedge CLK) if (CLK_EN_24M_P) T148_Q <= T128B_OUT; + wire T128B_OUT = ~&{T73A_OUT, U129A_Q}; + + // T181A + wire IS_ACTIVE = PARSE_CHAIN ? T90A_OUT : M176A_OUT; + + wire M176A_OUT = PARSE_MATCH | PARSE_SIZE[5]; + //BD3 S105(VRAM_HIGH_ADDR_SB, S105_OUT); + always @(posedge CLK/*_24M*/) + S105_OUT <= VRAM_HIGH_ADDR_SB; // TESTING - ok, solves issue + //FDRCell T102(O109A_OUT, {1'b0, T102_Q[1], T102_Q[0], S105_OUT}, nNEW_LINE, T102_Q); + always @(posedge CLK, negedge nNEW_LINE) + if (!nNEW_LINE) + T102_Q <= 0; + else if (O109A_OUT_RISE) + T102_Q <= {1'b0, T102_Q[1], T102_Q[0], S105_OUT}; + + wire T94_OUT = ~&{T102_Q[1:0], O102B_OUT}; + wire T92_OUT = ~&{~T102_Q[2], ~T102_Q[1], T102_Q[0], VRAM_HIGH_ADDR_SB}; + assign T90A_OUT = ~&{T94_OUT, T92_OUT}; + /* + always @(posedge O110B_OUT or negedge nNEW_LINE) + begin + if (!nNEW_LINE) + ACTIVE_WR_ADDR <= 0; + else + ACTIVE_WR_ADDR <= ACTIVE_WR_ADDR + 1'd1; + end + */ + always @(posedge CLK, negedge nNEW_LINE) + if (!nNEW_LINE) + ACTIVE_WR_ADDR <= 0; + else if (O110B_OUT_RISE) + ACTIVE_WR_ADDR <= ACTIVE_WR_ADDR + 1'd1; + /* + C43 H198(O110B_OUT, 4'b0000, 1'b1, 1'b1, 1'b1, nNEW_LINE, ACTIVE_WR_ADDR[3:0], H198_CO); + // Used for test mode + wire H222A_OUT = H198_CO | 1'b0; + C43 I189(O110B_OUT, 4'b0000, 1'b1, 1'b1, H222A_OUT, nNEW_LINE, ACTIVE_WR_ADDR[7:4]); + */ + //wire O110B_OUT = O109A_OUT | VRAM_HIGH_ADDR_SB; + wire O110B_OUT_RISE = O109A_OUT_RISE & ~VRAM_HIGH_ADDR_SB; + wire nACTIVE_FULL = ~&{ACTIVE_WR_ADDR[6:5]}; // J100B + + + //FS3 N98(T125A_OUT, 4'b0000, R91_nQ, RESETP, {N98_QD, N98_QC, N98_QB, N98_QA}); + always @(posedge CLK) + if (!RESETP) {N98_QD, N98_QC, N98_QB, N98_QA} <= 0; + else if (T125A_OUT_RISE) {N98_QD, N98_QC, N98_QB, N98_QA} <= {N98_QC, N98_QB, N98_QA, R91_nQ}; + //assign CLK_ACTIVE_RD = ~K131B_OUT; + assign CLK_ACTIVE_RD_EN = T125A_OUT_RISE & ~N98_QA & R91_nQ; + + wire N98_QB_RISE = T125A_OUT_RISE & !N98_QB & N98_QA; + wire N98_QC_RISE = T125A_OUT_RISE & !N98_QC & N98_QB; + wire N98_QD_RISE = T125A_OUT_RISE & !N98_QD & N98_QC; + + //FDM R91(LSPC_12M, LSPC_1_5M, R91_Q, R91_nQ); + always @(posedge CLK) if (LSPC_EN_12M) {R91_Q, R91_nQ} <= {LSPC_1_5M, ~LSPC_1_5M}; + + // Address mux + // I213 I218 G169A G164 G182A G194A G200 G205A I175A I182A + // J62 J72A I104 I109A J205A J200 J49 J54A H28A H34 I13 I18A + assign A_TOP = {N98_QC, J36_OUT, ACTIVE_RD_PRE8, ACTIVE_RD_PRE}; + assign B_TOP = {3'b110, H293B_OUT, ACTIVE_RD_ADDR[6:0]}; + assign C_TOP = {3'b110, H293B_OUT, ACTIVE_RD_ADDR[6:0]}; + assign D_TOP = {N98_QC, J36_OUT, ACTIVE_RD_PRE8, ACTIVE_RD_PRE}; + + assign A_BOT = {3'b110, I237A_OUT, ACTIVE_WR_ADDR[6:0]}; + assign B_BOT = VRAM_ADDR[10:0]; + assign C_BOT = VRAM_ADDR[10:0]; + assign D_BOT = {2'b01, PARSE_INDEX}; + + // L110B_OUT A + // ~VRAM_HIGH_ADDR_SB B + // M95B_OUT C + // ABC: + assign C = M95B_OUT ? + ~VRAM_HIGH_ADDR_SB ? + L110B_OUT ? C_TOP : A_TOP // 111 - 110 + : + L110B_OUT ? B_TOP : D_TOP // 101 - 100 + : + ~VRAM_HIGH_ADDR_SB ? + L110B_OUT ? C_BOT : A_BOT // 011 - 010 + : + L110B_OUT ? B_BOT : D_BOT; // 001 - 000 +/* + assign C = L110B_OUT ? + ~VRAM_HIGH_ADDR_SB ? + M95B_OUT ? C_TOP : A_TOP // 111 - 110 + : + M95B_OUT ? B_TOP : D_TOP // 101 - 100 + : + ~VRAM_HIGH_ADDR_SB ? + M95B_OUT ? C_BOT : A_BOT // 011 - 010 + : + M95B_OUT ? B_BOT : D_BOT; // 001 - 000 + */ + + wire K131B_OUT = ~N98_QA; + wire M95B_OUT = ~|{N98_QD, O98_Q}; + wire L110B_OUT = ~|{L110A_OUT, O98_Q}; + wire L110A_OUT = ~|{K131B_OUT, N98_QD}; + wire I237A_OUT = FLIP; + wire K260B_OUT = FLIP; + wire H293B_OUT = nFLIP; + wire J36_OUT = N98_QB ^ N98_QC; + + // Active list read counter + + assign #1 P39A_OUT = ~PIXELC[8]; + //always @(posedge CLK_24M) // TESTING + //P39A_OUT <= ~PIXELC[8]; + wire nRELOAD_RD_ACTIVE = ~&{PIXELC[6], P50_CO, P39A_OUT}; // O55A + //C43 I151(CLK_ACTIVE_RD, 4'b0000, nRELOAD_RD_ACTIVE, 1'b1, 1'b1, 1'b1, ACTIVE_RD_ADDR[3:0], I151_CO); + //wire J176A_OUT = I151_CO | 1'b0; // Used for test mode + //C43 J151(CLK_ACTIVE_RD, 4'b0000, nRELOAD_RD_ACTIVE, 1'b1, J176A_OUT, 1'b1, ACTIVE_RD_ADDR[7:4]); + always @(posedge CLK) + if (CLK_ACTIVE_RD_EN) begin + if (!nRELOAD_RD_ACTIVE) + ACTIVE_RD_ADDR <= 0; + else + ACTIVE_RD_ADDR <= ACTIVE_RD_ADDR + 1'd1; + end + + + // OK + // Parsing counter + /* + always @(posedge PARSE_INDEX_INC_CLK or negedge nNEW_LINE) + begin + if (!nNEW_LINE) + PARSE_INDEX_test <= 9'd0; + else + PARSE_INDEX_test <= PARSE_INDEX_test + 1'd1; + end*/ + always @(posedge CLK, negedge nNEW_LINE) + if (!nNEW_LINE) + PARSE_INDEX <= 0; + else if (PARSE_INDEX_INC_CLK_EN) + PARSE_INDEX <= PARSE_INDEX + 1'd1; + + //wire PARSE_INDEX_INC_CLK = O102B_OUT | O109A_OUT; // O105B + wire PARSE_INDEX_INC_CLK_EN = O109A_OUT_RISE & ~O102B_OUT; + /*C43 H127(PARSE_INDEX_INC_CLK, 4'b0000, 1'b1, 1'b1, 1'b1, nNEW_LINE, PARSE_INDEX[3:0], H127_CO); + assign H125B_OUT = H127_CO | 1'b0; // Used for test mode + C43 I121(PARSE_INDEX_INC_CLK, 4'b0000, 1'b1, H125B_OUT, 1'b1, nNEW_LINE, PARSE_INDEX[7:4], I121_CO); + C43 J127(PARSE_INDEX_INC_CLK, 4'b0000, 1'b1, H125B_OUT, I121_CO, nNEW_LINE, J127_Q); + assign PARSE_INDEX[8] = J127_Q[0];*/ + + wire O109A_OUT = T125A_OUT | CLK_CPU_READ_HIGH; + wire O109A_OUT_RISE = ~O109A_OUT & (T125A_OUT_RISE | CLK_CPU_READ_HIGH_RISE); + + wire O102B_OUT = WR_ACTIVE & O98_Q; + + + // Y parse matching + // L200 O200 + assign PARSE_LOOKAHEAD = 8'd2 + {RASTERC[7:1], K260B_OUT}; + // M190 N190 + assign PARSE_ADD_Y = PARSE_LOOKAHEAD + PARSE_Y[7:0]; + wire N186_OUT = ~^{PARSE_ADD_Y[8], PARSE_Y[8]}; + // K195 M151 + assign PARSE_ADD_SIZE = {N186_OUT, ~PARSE_ADD_Y[7:4]} + PARSE_SIZE[4:0]; + wire PARSE_MATCH = PARSE_ADD_SIZE[5]; + + + // OK + // Pipeline for x position and h-shrink + // Implemented as 14-bit 3-stage shift register + //always @(posedge N98_QD) + // SR_SPR_PARAMS <= {SR_SPR_PARAMS[27:0], {SPR_CHAIN, O141_Q, F[15:7]}}; + always @(posedge CLK) + if (N98_QD_RISE) SR_SPR_PARAMS <= {SR_SPR_PARAMS[27:0], {SPR_CHAIN, XSHRINK, F[15:7]}}; + + assign O159_QB = SR_SPR_PARAMS[13]; + assign HSHRINK = SR_SPR_PARAMS[40:37]; + assign PIPE_C = SR_SPR_PARAMS[41:28]; + /* + // O159 P131 O87 N131 + FDS16bit O159(N98_QD, {2'b00, SPR_CHAIN, O141_Q, F[15:7]}, PIPE_A); + assign O159_QB = PIPE_A[13]; + // P165 P121 P87 N121 + FDS16bit P165(N98_QD, PIPE_A, PIPE_B); + // P155 P141 P104 N141 + FDS16bit P155(N98_QD, PIPE_B, PIPE_C); + assign HSHRINK = PIPE_C[12:9]; + */ + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/hshrink.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/hshrink.v new file mode 100644 index 0000000000000000000000000000000000000000..110e57e95418666ca91f2a17178a972c5c496aff --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/hshrink.v @@ -0,0 +1,88 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module hshrink_sync( + input CLK, + input [3:0] SHRINK, // Shrink value + input CK_EN, L, + output OUTA, OUTB +); + + wire [3:0] nSHRINK; + + reg [3:0] U193_REG; + reg [3:0] T196_REG; + reg [3:0] U243_REG; + reg [3:0] U226_REG; + + wire [3:0] U193_P; + wire [3:0] T196_P; + wire [3:0] U243_P; + wire [3:0] U226_P; + + assign nSHRINK[3:0] = ~SHRINK[3:0]; + + // Lookup + assign U193_P[0] = ~&{nSHRINK[3:2]}; + assign U193_P[1] = ~&{nSHRINK[3:1]}; + assign U193_P[2] = ~&{nSHRINK[3], ~&{SHRINK[2:1]}}; + assign U193_P[3] = 1'b1; + + assign T196_P[0] = ~|{&{SHRINK[2], ~|{SHRINK[1:0], SHRINK[3]}}, ~|{SHRINK[3:2]}}; + assign T196_P[1] = ~&{nSHRINK[3:0]}; + assign T196_P[2] = ~&{~&{SHRINK[1:0]}, ~|{SHRINK[3:2]}}; + assign T196_P[3] = ~&{nSHRINK[3], ~&{SHRINK[2:0]}}; + + assign U243_P[0] = ~|{nSHRINK[3], ~|{SHRINK[2:1]}}; + assign U243_P[1] = ~|{nSHRINK[3:2]}; + assign U243_P[2] = ~|{nSHRINK[3:1]}; + assign U243_P[3] = SHRINK[3]; + + assign U226_P[0] = ~&{~&{SHRINK[1:0], nSHRINK[2], SHRINK[3]}, ~&{SHRINK[3:2]}}; + assign U226_P[1] = &{SHRINK[3:0]}; + assign U226_P[2] = ~|{nSHRINK[3], ~|{SHRINK[2:0]}}; + assign U226_P[3] = ~|{~&{SHRINK[3:2]}, ~|{SHRINK[1:0]}}; + + // Shift registers + wire T193A_OUT, U258A_OUT; + //FS2 U193(CK, U193_P, 1'b1, ~L, U193_REG); + BD3 T193A(U193_REG[3], T193A_OUT); + //FS2 T196(CK, T196_P, T193A_OUT, ~L, T196_REG); + + //FS2 U243(CK, U243_P, 1'b1, ~L, U243_REG); + BD3 U258A(U243_REG[3], U258A_OUT); + //FS2 U226(CK, U226_P, U258A_OUT, ~L, U226_REG); + + always @(posedge CLK) + if (CK_EN) begin + if (~L) begin + U193_REG <= U193_P; + T196_REG <= T196_P; + U243_REG <= U243_P; + U226_REG <= U226_P; + end else begin + U193_REG <= {U193_REG[2:0], 1'b1}; + T196_REG <= {T196_REG[2:0], T193A_OUT}; + U243_REG <= {U243_REG[2:0], 1'b1}; + U226_REG <= {U226_REG[2:0], U258A_OUT}; + end + end + + assign OUTA = T196_REG[3]; + assign OUTB = U226_REG[3]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/irq.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/irq.v new file mode 100644 index 0000000000000000000000000000000000000000..5cdd2e697777a26de5e179a1ea03fe508f3e86a2 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/irq.v @@ -0,0 +1,70 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +/* verilator lint_off PINMISSING */ + +module irq_sync( + input CLK, + input WR_ACK, + input [2:0] ACK_BITS, + input RESET_IRQ, + input TIMER_IRQ, + input TIMER_IRQ_EN, + input VBL_IRQ, + input VBL_IRQ_EN, + input CLK_EN, + output IPL0, IPL1 +); + + wire [2:0] ACK; + //wire [3:0] B32_Q; + + wire nWR_ACK = ~WR_ACK; + + assign ACK[0] = ~&{nWR_ACK, ACK_BITS[0]}; + assign ACK[1] = ~&{nWR_ACK, ACK_BITS[1]}; + assign ACK[2] = ~&{nWR_ACK, ACK_BITS[2]}; + + wire B56_Q, B56_nQ = ~B56_Q, B52_Q, B52_nQ = ~B52_Q, C52_Q; + //FD3 B56(RESET_IRQ, 1'b0, ACK[0], B56_Q, B56_nQ); + //FD3 B52(TIMER_IRQ, 1'b0, ACK[1], B52_Q, B52_nQ); + //FD3 C52(VBL_IRQ, 1'b0, ACK[2], C52_Q); + register B56(CLK, ~ACK[0], 1'b0, RESET_IRQ, 1'b0, B56_Q); + register B52(CLK, ~ACK[1], 1'b0, TIMER_IRQ, ~TIMER_IRQ_EN, B52_Q); + register C52(CLK, ~ACK[2], 1'b0, VBL_IRQ, ~VBL_IRQ_EN, C52_Q); + + // B49 + wire B49_OUT = B52_Q | B56_nQ; + + // B50A + wire B50A_OUT = ~|{C52_Q, B56_nQ, B52_nQ}; + + //FDSCell B32(CLK, {1'b0, B50A_OUT, B49_OUT, B56_Q}, B32_Q); + reg [3:0] B32_Q; + always @(posedge CLK) if (CLK_EN) B32_Q <= {1'b0, B50A_OUT, B49_OUT, B56_Q}; + + assign IPL0 = ~|{~B32_Q[0], B32_Q[2]}; + assign IPL1 = ~|{~B32_Q[1], ~B32_Q[0]}; + + // Interrupt priority encoder + // IRQ IPL + // xx1: 100 Reset IRQ + // x10: 101 Timer IRQ + // 100: 110 VBL IRQ + // 000: 111 No interrupt + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/linebuffer.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/linebuffer.v new file mode 100644 index 0000000000000000000000000000000000000000..73c0fe2270f55a58dee408a0e9084c94aa92f637 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/linebuffer.v @@ -0,0 +1,115 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module linebuffer( + //input TEST_MODE, + //input [7:0] GBD, + input CLK, + input CK, + input WE, + input LOAD, + input CLEARING, + input [3:0] COLOR_INDEX, + input PCK2_EN, + input [7:0] SPR_PAL, + input [7:0] ADDR_LOAD, + output [11:0] DATA_OUT +); + // 192 pixels * 12 bits + //reg [11:0] LB_RAM[0:255]; // TODO: Add a check, should never go over 191 + reg [7:0] PAL_REG; + reg [7:0] ADDR_COUNTER; + reg [7:0] ADDR_LATCH; + wire [7:0] ADDR_MUX; + wire [11:0] DATA_IN; + wire [3:0] COLOR_GATED; + + // Switch between color index or backdrop clear + // BL: NUDE NOSY... + // BR: NEGA NACO... + // TL: MOZA MAKO... + // TR: NUDE NOSY... + assign COLOR_GATED = COLOR_INDEX | {4{CLEARING}}; + + // Select color index or test data (unused) + // BL: NODO NUJA... + // BR: NOFA NYKO... + // TL: MAPE MUCA... + // TR: LANO LODO... + assign DATA_IN[3:0] = COLOR_GATED; // TEST_MODE ? GBD : COLOR_GATED; + + // Latch sprite palette from P bus + // BL: MANA NAKA... + // BR: MESY NEPA... + // TL: JETU JUMA... + // TR: GENA HARU... + always @(posedge CLK) + if (PCK2_EN) PAL_REG <= SPR_PAL; + + // Switch between sprite palette or backdrop clear + // BL: MORA NOKU... + // BR: MECY NUXA... + // TL: JEZA JODE... + // TR: GUSU HYKU... + assign DATA_IN[11:4] = PAL_REG | {8{CLEARING}}; + + // Switch between address inc or address reload + // BL: RUFY QAZU... + // BR: PECU QUNY... + // TL: BAME CUNU... + // TR: EGED DUGA... + assign ADDR_MUX = LOAD ? (ADDR_COUNTER_REG + 1'b1) : ADDR_LOAD; + + // Address counter update + // BL: REVA QEVU... + // BR: PAJE QATA... + // TL: BEWA CENA... + // TR: EPAQ DAFU... + + reg CK_D; + reg [7:0] ADDR_COUNTER_REG; + always @(posedge CLK) begin + CK_D <= CK; + ADDR_COUNTER_REG <= ADDR_COUNTER; + end + always @(*) begin + if (!CK_D & CK) + ADDR_COUNTER = ADDR_MUX; + else + ADDR_COUNTER = ADDR_COUNTER_REG; + end + +// always @(posedge CK) +// ADDR_COUNTER <= ADDR_MUX; + + // Address counter latch + // BL: NACY OKYS... + // BR: PEXU QUVU... + // TL: ERYV ENOG... + // TR: EDYZ ASYX... + reg [11:0] DATA_LATCH; + always @(posedge CLK) if(WE) begin ADDR_LATCH <= ADDR_COUNTER; DATA_LATCH <= DATA_IN; end + + spram #(8,12) UR( + .clock(CLK), + .address(ADDR_LATCH), + .data(DATA_LATCH), + .wren(~WE), + .q(DATA_OUT) + ); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_a2.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_a2.v new file mode 100644 index 0000000000000000000000000000000000000000..4ceffb944706ad78e641ab763157218fef78959e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_a2.v @@ -0,0 +1,751 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +// All pins listed ok. REF, DIVI and DIVO only used on AES for video PLL hack + +/* verilator lint_off PINMISSING */ + +module lspc2_a2_sync( + input CLK, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + input RESET, + output [15:0] PBUS_OUT, + inout [23:16] PBUS_IO, + input [3:1] M68K_ADDR, + inout [15:0] M68K_DATA, + input LSPOE, LSPWE, + input DOTA, DOTB, + output CA4, + output S2H1, + output S1H1, + output LOAD, + output reg H, + output EVEN1, // For ZMC2 + output reg EVEN2, + output IPL0, IPL1, + input CD_VBLANK_IRQ_EN, + input CD_TIMER_IRQ_EN, + output CHG, // Also called TMS0 + output LD1, LD2, // Buffer address load + output reg PCK1, PCK2, + output PCK1_EN_P, PCK2_EN_P, + output PCK1_EN_N, PCK2_EN_N, + output [3:0] WE, + output [3:0] CK, + output SS1, SS2, // Buffer pair selection for B1 + output nRESETP, + output HSYNC, + output VSYNC, + output CHBL, + output BNKB, + output VCS, // LO ROM output enable + output LSPC_8M, + output LSPC_4M, + output LSPC_EN_4M_P, + output LSPC_EN_4M_N, + + output [14:0] SVRAM_ADDR, + input [31:0] SVRAM_DATA_IN, + output [15:0] SVRAM_DATA_OUT, + output BOE, BWE, + + output [10:0] FVRAM_ADDR, + input [15:0] FVRAM_DATA_IN, + output [15:0] FVRAM_DATA_OUT, + output CWE, + + output nPBUS_OUT_EN, + + input VMODE, + + output [14:0] FIXMAP_ADDR, // Extracted for NEO-CMC + output [14:0] SPRMAP_ADDR, + output [15:0] VRAM_ADDR, // CPU access address + output [1:0] VRAM_CYCLE, + output SVRAM_WR, // Full cycle WR signal + output [15:0] LO_ROM_ADDR +); + + wire [8:0] PIXELC; + wire [3:0] PIXEL_HPLUS; + wire [8:0] RASTERC; + + wire [7:0] AA_SPEED; + wire [2:0] AA_COUNT /* verilator public */; // Auto-animation tile # + + wire [15:0] CPU_DATA_OUT; + + wire [15:0] VRAM_LOW_READ; + wire [15:0] VRAM_HIGH_READ; + wire [15:0] REG_VRAMADDR; + //wire [15:0] VRAM_ADDR; + wire [15:0] VRAM_ADDR_MUX; + wire [15:0] VRAM_ADDR_AUTOINC; + wire [15:0] REG_VRAMRW; + wire [15:0] VRAM_WRITE; + + wire [15:0] REG_VRAMMOD; + wire [15:0] REG_LSPCMODE; + + wire [2:0] TIMER_MODE; + +/* verilator lint_off UNOPTFLAT */ + wire [3:0] T31_P; + wire [3:0] U24_P; +/* verilator lint_on UNOPTFLAT */ + reg [3:0] O227_Q; + + wire [7:0] P_MUX_HIGH; + wire [7:0] P_MUX_LOW; + wire [23:0] P_OUT_MUX; + + reg [3:0] VSHRINK_INDEX; + reg [3:0] VSHRINK_LINE; + wire [8:0] XPOS; + wire [7:0] XPOS_ROUND_UP; + wire [2:0] SPR_TILE_AA; + reg [3:0] G233_Q; + wire [7:0] SPR_Y_LOOKAHEAD; + wire [8:0] SPR_Y_ADD; + wire [7:0] LO_LINE_A; + wire [7:0] LO_LINE_B; + wire [8:0] SPR_Y_SHRINK; + wire [3:0] SPR_LINE; + wire [7:0] LO_LINE_MUX; + wire [19:0] SPR_TILE; + wire [7:0] YSHRINK; + wire [8:0] SPR_Y; + wire [7:0] SPR_PAL; + wire [3:0] FIX_PAL; + wire [11:0] FIX_TILE; + wire [3:0] HSHRINK; + wire [13:0] PIPE_C; + reg [3:0] SPR_TILEMAP; + wire [7:0] ACTIVE_RD; + reg [3:0] P201_Q; + + reg D112B_OUT_DELAY; + + wire LSPC_3M, LSPC_1_5M; + wire LSPC_EN_12M_P, LSPC_EN_12M_N, LSPC_EN_6M_P, LSPC_EN_6M_N, LSPC_EN_3M, LSPC_EN_1_5M_P, LSPC_EN_1_5M_N; + + assign S1H1 = LSPC_3M; + assign S2H1 = LSPC_1_5M; + assign SVRAM_WR = ~nCPU_WR_LOW; + //FD2 T168A(CLK_24M, T160A_OUT, PCK1, nPCK1); + //FD2 T162A(CLK_24M, T160B_OUT, PCK2); + //FDM T172(nPCK1, SPR_TILE_HFLIP, T172_Q); + //FD2 U167(~PCK2, T172_Q, H); + + // PCK1, PCK2, H + reg T172_Q; + //reg nPCK1; + assign PCK1_EN_P = CLK_EN_24M_N & ~PCK1 & T160A_OUT; + assign PCK2_EN_P = CLK_EN_24M_N & ~PCK2 & T160B_OUT; + assign PCK1_EN_N = CLK_EN_24M_N & PCK1 & ~T160A_OUT; + assign PCK2_EN_N = CLK_EN_24M_N & PCK2 & ~T160B_OUT; + always @(posedge CLK) + if (CLK_EN_24M_N) begin + // FD2 T168A(CLK_24M, T160A_OUT, PCK1, nPCK1); + PCK1 <= T160A_OUT; + //nPCK1 <= ~T160A_OUT; + // FD2 T162A(CLK_24M, T160B_OUT, PCK2); + PCK2 <= T160B_OUT; + // FDM T172(nPCK1, SPR_TILE_HFLIP, T172_Q); + if (PCK1 & ~T160A_OUT) + T172_Q <= SPR_TILE_HFLIP; + // FD2 U167(~PCK2, T172_Q, H); + if (~PCK2 & T160B_OUT) + H <= T172_Q; + end + + assign CA4 = T172_Q ^ LSPC_1_5M; + + // EVEN1, EVEN2 + wire U105A_OUT = ~&{nHSHRINK_OUT_A, nHSHRINK_OUT_B, nEVEN_ODD}; + wire U107_OUT = ~&{nHSHRINK_OUT_A, EVEN_nODD, HSHRINK_OUT_B}; + wire U109_OUT = ~&{HSHRINK_OUT_A, nEVEN_ODD}; + wire U112_OUT = ~&{U105A_OUT, U107_OUT, U109_OUT}; + //assign #13 EVEN1 = U112_OUT; // BD5 U162 + assign EVEN1 = U112_OUT; + + // Pixel parity select + wire nPARITY_INIT = ~&{nCHAINED, S53A_OUT}; // R42A + wire nXPOS_ZERO = ~PIPE_C[0]; + wire S58A_OUT = ~|{nXPOS_ZERO, nPARITY_INIT}; + wire ONE_PIXEL = HSHRINK_OUT_A ^ HSHRINK_OUT_B; // U83 + wire U72_OUT = ONE_PIXEL ^ nEVEN_ODD; + wire U57B_OUT = nPARITY_INIT & U72_OUT; + wire U56A_OUT = ~|{S58A_OUT, U57B_OUT}; + wire CLK_24MB, LSPC_12M; //, U68A_nQ = ~CK_HSHRINK_REG; + reg CK_HSHRINK_REG, EVEN_nODD, nEVEN_ODD; +// FD2 U68A(CLK_24MB, ~LSPC_12M, CK_HSHRINK_REG, /*U68A_nQ*/); +// FD2 U74A(~U68A_nQ, U56A_OUT, EVEN_nODD, nEVEN_ODD); + always @(posedge CLK) + if (CLK_EN_24M_P) begin + CK_HSHRINK_REG <= ~LSPC_12M; + if (LSPC_12M && CK_HSHRINK_REG) begin + EVEN_nODD <= U56A_OUT; + nEVEN_ODD <= ~U56A_OUT; + end + end + wire CK_HSHRINK_EN = CLK_EN_24M_P & CK_HSHRINK_REG & LSPC_12M; + + // CPU VRAM address update select + // $3C0000 REG_VRAMADDR 0 (update with written value) + // $3C0002 REG_VRAMRW 1 (update with REG_VRAMMOD) + //wire C22A_OUT = ~&{WR_VRAM_RW, WR_VRAM_ADDR}; + wire VRAM_ADDR_UPD_TYPE; + //FDM B18(C22A_OUT, M68K_ADDR[1], VRAM_ADDR_UPD_TYPE); + register B18(CLK, 1'b0, 1'b0, ~(WR_VRAM_RW & WR_VRAM_ADDR), M68K_ADDR[1], VRAM_ADDR_UPD_TYPE); + + // VRAM_ADDR with REG_VRAMMOD applied + // G18 G81 F91 F127 + assign VRAM_ADDR_AUTOINC = REG_VRAMMOD + VRAM_ADDR; + + // CPU VRAM address update mux + // C144A C142A C140B C138B + // A112B A111A A109A A110B + // D110B D106B D108B D85A + // F10A F12A F26A F12B + assign VRAM_ADDR_MUX = VRAM_ADDR_UPD_TYPE ? VRAM_ADDR_AUTOINC : REG_VRAMADDR; + + // VRAM address update FFs + // F14 D48 C105 C164 + // TESTING + always @(posedge CLK) D112B_OUT_DELAY <= D112B_OUT; + //FDS16bit F14(D112B_OUT_DELAY, VRAM_ADDR_MUX, VRAM_ADDR); + register #(16) F14(CLK, 1'b0, 1'b0, D112B_OUT, VRAM_ADDR_MUX, VRAM_ADDR); + + // ...Second stage + // F165 D178 D141 E196 + //FDS16bit E196(O108B_OUT, REG_VRAMRW, VRAM_WRITE); + register #(16) E196(CLK, 1'b0, 1'b0, ~(nCPU_WR_HIGH & nCPU_WR_LOW), REG_VRAMRW, VRAM_WRITE); + + // Pulse for updating internal VRAM address + // nCPU_WR_HIGH and nCPU_WR_LOW are "write done" pulses for both VRAM zones + // Happens when write is done or write to REG_VRAMADDR + wire O108B_OUT = ~&{nCPU_WR_HIGH, nCPU_WR_LOW}; + wire D112B_OUT = ~|{~WR_VRAM_ADDR, O108B_OUT}; + + // CPU read data output. Outputs are not enabled all at once, this is strange. + // Transient current spike reduction ? + // After LSPOE goes low, at least 1.5mclk is required for all outputs to be enabled. + // **Gyurco**: not relevant in a SOC design +/* + wire C71_Q, LSPOE_SEQB, LSPOE_SEQA, C68_Q, LSPOE_SEQC; + FDM C71(CLK_24M, LSPOE, C71_Q, LSPOE_SEQA); + FDM C68(CLK_24MB, C71_Q, C68_Q, LSPOE_SEQB); + FDM C75(CLK_24M, C68_Q, , LSPOE_SEQC); + + assign M68K_DATA[1:0] = LSPOE ? 2'bzz : CPU_DATA_OUT[1:0]; // No delay + wire B71_OUT = ~&{~LSPOE, LSPOE_SEQA}; + assign M68K_DATA[7:2] = B71_OUT ? 6'bzzzzzz : CPU_DATA_OUT[7:2]; // t+1 + wire B75A_OUT = ~&{~LSPOE, LSPOE_SEQB}; + assign M68K_DATA[9:8] = B75A_OUT ? 2'bzz : CPU_DATA_OUT[9:8]; // t+2 + wire B74_OUT = ~&{~LSPOE, LSPOE_SEQC}; + assign M68K_DATA[15:10] = B74_OUT ? 6'bzzzzzz : CPU_DATA_OUT[15:10]; // t+3 +*/ + assign M68K_DATA = LSPOE ? 16'bzzzzzzzzzzzzzzzz : CPU_DATA_OUT; + + // Auto-animation bit enables + // C184A + wire AUTOANIM3_EN = SPR_AA_3 & ~AA_DISABLE; + wire C186A_OUT = SPR_AA_2 & ~AA_DISABLE; + // B180B + wire AUTOANIM2_EN = AUTOANIM3_EN | C186A_OUT; + + + // Timing/sequencing stuff + // This doesn't mean anything special, it just outputs periodic signals to get everything moving + wire T56A_OUT = ~&{LSPC_6M, LSPC_3M}; + wire T58A_OUT = ~&{LSPC_6M, LSPC_3M}; + //wire T53_Q, U53_Q; + //FDM T53(LSPC_12M, T56A_OUT, T53_Q); + //FDM U53(CLK_24M, T53_Q, U53_Q); + reg T53_Q, U53_Q; + always @(posedge CLK) if (LSPC_EN_12M_P) T53_Q <= T56A_OUT; + always @(posedge CLK) if (CLK_EN_24M_P) U53_Q <= T53_Q; + + assign nPBUS_OUT_EN = U53_Q & T53_Q; + + reg T69_nQ; + + always @(posedge CLK or negedge nRESETP) + begin + //FDPCell T69(LSPC_12M, LSPC_3M, nRESETP, 1'b1, , T69_nQ); + if (!nRESETP) + begin + T69_nQ <= 1'b0; + end + else + if (LSPC_EN_12M_P) T69_nQ <= ~LSPC_3M; + end + + wire T73A_OUT = LSPC_3M | T69_nQ; + + reg T140_Q, T134_Q; + always @(posedge CLK or negedge T73A_OUT) + begin + if (!T73A_OUT) + begin + T140_Q <= 1'b0; + T134_Q <= 1'b0; + end + else + if (CLK_EN_24M_P) begin + //FJD T140(CLK_24M, T134_nQ, 1'b1, T73A_OUT, T140_Q); + T140_Q <= (~T134_Q) ? ~T140_Q : 1'b0; + //FJD T134(CLK_24M, T140_Q, 1'b1, T73A_OUT, , T134_nQ); + T134_Q <= (T140_Q) ? ~T134_Q : 1'b0; + end + end + + reg U129A_Q; + always @(posedge CLK) + if (CLK_EN_24M_N) begin + //FD2 U129A(CLK_24M, ~T134_Q, U129A_Q, U129A_nQ); + U129A_Q <= ~T134_Q; + //FD2 U144A(CLK_24M, U112_OUT, EVEN2); + EVEN2 <= U112_OUT; + end + + //wire T125A_OUT_RISE = ~T125A_OUT & T73A_OUT & (T134_Q | (~T134_Q & ~T140_Q)); + wire T125A_OUT_RISE = ~T125A_OUT & T73A_OUT; + wire T125A_OUT = ~U129A_Q | T140_Q; + wire Q174B_OUT, P198A_OUT; + BD3 P198A(Q174B_OUT, P198A_OUT); + //FS1 P201(LSPC_12M, P198A_OUT, P201_Q); + always @(posedge CLK) if (LSPC_EN_12M_N) P201_Q <= {P201_Q[2:0], ~P198A_OUT}; + //wire P219A_OUT = ~|{O159_QB, ~P201_Q[0]}; + //wire P222A_OUT = ~&{P219A_OUT, ~P201_Q[1]}; + wire P222A_OUT_RISE = P201_Q[0] & ~P201_Q[1] & ~O159_QB & LSPC_EN_12M_N; + //wire CLK_SPR_TILE = P201_Q[1]; + wire R94A_OUT = ~&{P201_Q[2], R91_Q}; + //wire D208B_OUT = ~P201_Q[3]; + wire CLK_SPR_TILE_EN = LSPC_EN_12M_N & !P201_Q[0] & &P201_Q[3:1]; + wire CLK_SPR_ATTR_EN = LSPC_EN_12M_N & P201_Q[3] & ~|P201_Q[2:0]; + + + // NEO-B1 control signals + + // Latch for CK1/2 and WE1/2 + //LT4 T31(LSPC_12M, {T38A_OUT, T28_OUT, T29A_OUT, T20B_OUT}, T31_P); + reg [3:0] T31_P_REG; + assign T31_P = ~LSPC_12M ? {T38A_OUT, T28_OUT, T29A_OUT, T20B_OUT} : T31_P_REG; + always @(posedge CLK) T31_P_REG <= T31_P; + // Latch for CK3/4 and WE3/4 + //LT4 U24(LSPC_12M, {U37B_OUT, U21B_OUT, U35A_OUT, U31A_OUT}, U24_P); + reg [3:0] U24_P_REG; + assign U24_P = ~LSPC_12M ? {U37B_OUT, U21B_OUT, U35A_OUT, U31A_OUT} : U24_P_REG; + always @(posedge CLK) U24_P_REG <= U24_P; + + // CKs and WEs can only be low when LSPC_12M is high + wire WE1 = ~&{T31_P[0], LSPC_12M}; + wire WE2 = ~&{T31_P[1], LSPC_12M}; + wire CK1 = ~&{T31_P[2], LSPC_12M}; + wire CK2 = ~&{T31_P[3], LSPC_12M}; + + wire WE3 = ~&{U24_P[2], LSPC_12M}; + wire WE4 = ~&{U24_P[3], LSPC_12M}; + wire CK3 = ~&{U24_P[0], LSPC_12M}; + wire CK4 = ~&{U24_P[1], LSPC_12M}; + + assign WE = {WE4, WE3, WE2, WE1}; + assign CK = {CK4, CK3, CK2, CK1}; + + // Most of the following NAND gates are making 2:1 muxes like on the Alpha68k + + reg WRITEPX_A, WRITEPX_B; + // For buffer A: + // Clearing write pulses gates + wire T22A_OUT = ~&{T50B_OUT, SS1}; + wire T40B_OUT = ~&{T48A_OUT, SS1}; + // WRITEPX* gates + wire T50A_OUT = ~&{WRITEPX_A, CHG_D}; + wire T40A_OUT = ~&{WRITEPX_B, CHG_D}; + // Enable writes for opaque pixels only + wire T17A_OUT = ~&{DOTA, ~T50A_OUT}; + wire T22B_OUT = ~&{DOTB, ~T40A_OUT}; + // Merge writes with clearing write pulses + wire T20B_OUT = ~&{T22A_OUT, T17A_OUT}; + wire T29A_OUT = ~&{T40B_OUT, T22B_OUT}; + // Merge clocks with LD1_D pulses + wire T28_OUT = ~&{T22A_OUT, LD1_D, T50A_OUT}; + wire T38A_OUT = ~&{T40B_OUT, T40A_OUT, LD1_D}; + + // For buffer B: + // Clearing write pulses gates + wire U33B_OUT = ~&{T48A_OUT, SS2}; + wire T20A_OUT = ~&{T50B_OUT, SS2}; + // WRITEPX* gates + wire U51B_OUT = ~&{WRITEPX_A, nCHG_D}; + wire U39B_OUT = ~&{WRITEPX_B, nCHG_D}; + // Enable writes for opaque pixels only + wire U18A_OUT = ~&{DOTA, ~U51B_OUT}; + wire U38A_OUT = ~&{DOTB, ~U39B_OUT}; + // Merge writes with clearing write pulses + wire U21B_OUT = ~&{T20A_OUT, U18A_OUT}; + wire U37B_OUT = ~&{U33B_OUT, U38A_OUT}; + // Merge clocks with LD1_D pulses + wire U35A_OUT = ~&{LD2_D, U33B_OUT, U39B_OUT}; + wire U31A_OUT = ~&{LD2_D, T20A_OUT, U51B_OUT}; + + + // Buffer shift-out clocks, alternates between odd/even + wire T50B_OUT = LSPC_3M & LSPC_6M; + wire T48A_OUT = ~LSPC_3M & LSPC_6M; + + + // Pixel write pulse selection (odd/even) + wire U89A_OUT = ~&{nHSHRINK_OUT_B, nEVEN_ODD, HSHRINK_OUT_A}; + wire U92A_OUT = ~&{nHSHRINK_OUT_A, nEVEN_ODD, HSHRINK_OUT_B}; + wire U91_OUT = ~&{nHSHRINK_OUT_B, EVEN_nODD, HSHRINK_OUT_A}; + wire U94_OUT = ~&{nHSHRINK_OUT_A, EVEN_nODD, HSHRINK_OUT_B}; + // Enabled write pulses only if pixel is not skipped for h-shrink + wire U88B_OUT = HSHRINK_OUT_A | HSHRINK_OUT_B; + wire U85_OUT = &{U89A_OUT, U92A_OUT, U88B_OUT}; + wire U86A_OUT = &{U88B_OUT, U94_OUT, U91_OUT}; + // Final FFs + //FD2 T82A(CLK_24M, U85_OUT, WRITEPX_A); + //FD2 T86(CLK_24M, U86A_OUT, WRITEPX_B); + always @(posedge CLK) if (CLK_EN_24M_N) {WRITEPX_A, WRITEPX_B} <= {U85_OUT, U86A_OUT}; + + + // LD1/2 signal generation. Those are used to tell NEO-B1 to reload the write address (X position) + // Get which buffer should have the rendering pulses, and which should have the reset pulse + //wire FLIP_nQ; + //wire R50_Q, R50_nQ; + //FDM R50(LSPC_3M, FLIP_nQ, R50_Q, R50_nQ); + reg R50_Q; + wire R50_nQ = ~R50_Q; + always @(posedge CLK) if (LSPC_EN_3M) R50_Q <= FLIP_nQ; + + // Periodic signals + //wire R69_Q, R69_nQ; + //FDM R69(LSPC_3M, LSPC_1_5M, R69_Q, R69_nQ); + //FDM S55(LSPC_12M, LSPC_3M, S55_Q); + //wire S55_Q; + reg R69_Q, S55_Q; + wire R69_nQ = ~R69_Q; + always @(posedge CLK) begin + if (LSPC_EN_3M) R69_Q <= LSPC_1_5M; + if (LSPC_EN_12M_P) S55_Q <= LSPC_3M; + end + wire S53A_OUT = S55_Q & LSPC_6M; + // LOAD output + //FD2 R35A(CLK_24MB, S53A_OUT, LOAD); + reg LOAD_r; + always @(posedge CLK) if (CLK_EN_24M_P) LOAD_r <= S53A_OUT; + assign LOAD = LOAD_r; + // LOAD enable + //assign LOAD_EN = S55_Q & LSPC_EN_6M_P; + + // For LD1: + // Gate with chain bit (prevents address reload) + wire nCHAINED = ~|{PIPE_C[13], R69_nQ}; + // Gate reset LD pulse (once at start of line being shifted out) + wire R44B_OUT = ~&{R50_nQ, R53_Q}; + // Gate rendering LD pulses + wire R48B_OUT = ~&{nCHAINED, R50_Q}; + // Merge + wire R42B_OUT = ~&{R44B_OUT, R48B_OUT}; + // Sync + wire LD1_D = ~&{R42B_OUT, S53A_OUT}; + //FD2 R32(CLK_24MB, LD1_D, LD1); + reg LD1_r; + always @(posedge CLK) if (CLK_EN_24M_P) LD1_r <= LD1_D; + assign LD1 = LD1_r; + + // For LD2: + // Gate reset LD pulse (once at start of line being shifted out) + wire R44A_OUT = ~&{R53_Q, R50_Q}; + // Gate rendering LD pulses + wire R46A_OUT = ~&{R50_nQ, nCHAINED}; + // Merge + wire R46B_OUT = ~&{R44A_OUT, R46A_OUT}; + // Sync + wire LD2_D = ~&{R46B_OUT, S53A_OUT}; + //FD2 R28A(CLK_24MB, LD2_D, LD2); + reg LD2_r; + always @(posedge CLK) if (CLK_EN_24M_P) LD2_r <= LD2_D; + assign LD2 = LD2_r; + + // Reset LD pulse generation. This tells NEO-B1 to reload the address before shifting out a buffer + // At this very moment, the address should be 000 on the P bus + // Triggers at pixel #264 + //wire O62_Q, P74_Q, R53_Q, R74_nQ; + //FDPCell O62(PIXELC[3], PIXELC[8], 1'b1, nRESETP, O62_Q); + reg O62_Q; + wire O62_Q_next = (LSPC_EN_6M_N && PIXELC[3:0] == 4'b0111) ? PIXELC[8] : O62_Q; + always @(posedge CLK, negedge nRESETP) + if (!nRESETP) O62_Q <= 0; + else if (CLK_EN_24M_N) O62_Q <= O62_Q_next; + // Triggers at pixel #268 + //FDPCell P74(PIXELC[2], O62_Q, 1'b1, nRESETP, P74_Q); + reg P74_Q; + always @(posedge CLK, negedge nRESETP) + if (!nRESETP) P74_Q <= 0; + else if (LSPC_EN_6M_N && PIXELC[2:0] == 3'b011) P74_Q <= O62_Q; + // Make unique pulse + //FDM R53(LSPC_3M, R67A_OUT, R53_Q); + reg R53_Q; + always @(posedge CLK) if (LSPC_EN_3M) R53_Q <= R67A_OUT; + wire R67A_OUT = R74_nQ & P74_Q; + //FDPCell R74(LSPC_1_5M, P74_Q, 1'b1, nRESETP, , R74_nQ); + reg R74_nQ; + always @(posedge CLK, negedge nRESETP) + if (!nRESETP) R74_nQ <= 1; + else if (LSPC_EN_1_5M_P) R74_nQ <= ~P74_Q; + wire R74_nQ_EN = ~R74_nQ & ~P74_Q & LSPC_EN_1_5M_P; + + // Reload pulse for the h-shrink shift registers + // Perdiodic as all sprites take the same time to render regardless of h-shrink value + wire R48A_OUT = ~&{S53A_OUT, R69_Q}; + //wire LD_HSHRINK_REG; + //FD2 R56A(CLK_24MB, R48A_OUT, LD_HSHRINK_REG); + reg LD_HSHRINK_REG; + always @(posedge CLK) if (CLK_EN_24M_P) LD_HSHRINK_REG <= R48A_OUT; + + + // CHG output + //wire CHG_D; + //FDPCell S137(LSPC_1_5M, CHG_D, 1'b1, nRESETP, CHG); + reg CHG_r; + always @(posedge CLK) if (LSPC_EN_1_5M_P) CHG_r <= CHG_D; + assign CHG = CHG_r; + + // SS1/2 outputs, periodic + wire nFLIP, nCHG_D = ~CHG_D, R15_QD; + reg S48_nQ; + + // Latch nFLIP at pixel 264 (O62_Q). That will make the line buffers switch at pixel 267. + // The first write of the new line to the line buffer happens at pixel 268. + //FDPCell O69(CLK_24MB, nFLIP, nRESETP, 1'b1, , FLIP_nQ); + //FDPCell O69(O62_Q, nFLIP, nRESETP, 1'b1, , FLIP_nQ); + reg FLIP_nQ; + always @(posedge CLK) if (CLK_EN_24M_N & !O62_Q & O62_Q_next) FLIP_nQ <= ~nFLIP; + //FDPCell R63(PIXELC[2], FLIP_nQ, 1'b1, nRESETP, CHG_D, /*nCHG_D*/); + reg CHG_D; + always @(posedge CLK) if (LSPC_EN_6M_N && PIXELC[2:0] == 3'b011) CHG_D <= FLIP_nQ; + //FDM S48(LSPC_3M, R15_QD, , S48_nQ); + always @(posedge CLK) if (LSPC_EN_3M) S48_nQ <= ~R15_QD; + // S40A + assign SS1 = ~|{S48_nQ, CHG_D}; + // S39 + assign SS2 = ~|{nCHG_D, S48_nQ}; + + + // 16-pixel lookahead for fix tiles + wire J20A_OUT = ~&{PIXELC[8:7]}; + // I51 + assign PIXEL_HPLUS = 4'd15 + {~J20A_OUT, PIXELC[6:4]} + {3'd0, PIXELC[3]}; + + + // V-shrink mirroring and pipeline + wire SPR_CONTINUOUS; + //wire R179_Q; + //FDM R179(VCS, SPR_CONTINUOUS, R179_Q); + reg R179_Q; + always @(posedge CLK) if (VCS_EN) R179_Q <= SPR_CONTINUOUS; + // Mirror V-shrink values for second half of sprite if needed + wire S186_OUT = ~(~P235_OUT ^ R179_Q); + wire SPRITEMAP_ADDR_MSB = ~S186_OUT; + wire S166_OUT = VSHRINK_LINE[3] ^ ~S186_OUT; + wire S164_OUT = VSHRINK_LINE[2] ^ ~S186_OUT; + wire S162_OUT = VSHRINK_LINE[1] ^ ~S186_OUT; + wire S168_OUT = VSHRINK_LINE[0] ^ ~S186_OUT; + //FDSCell O227(P222A_OUT, {S166_OUT, S164_OUT, S162_OUT, S168_OUT}, O227_Q); + always @(posedge CLK) if (P222A_OUT_RISE) O227_Q <= {S166_OUT, S164_OUT, S162_OUT, S168_OUT}; + //FDSCell G233(~P201_Q[1], O227_Q, G233_Q); + always @(posedge CLK) if (LSPC_EN_12M_N & P201_Q[1] & P198A_OUT) G233_Q <= O227_Q; // falling edge of P201_Q[1] + assign SPR_LINE[0] = SPR_TILE_VFLIP ^ G233_Q[0]; + assign SPR_LINE[1] = SPR_TILE_VFLIP ^ G233_Q[1]; + assign SPR_LINE[2] = SPR_TILE_VFLIP ^ G233_Q[2]; + assign SPR_LINE[3] = SPR_TILE_VFLIP ^ G233_Q[3]; + wire Q184_OUT = VSHRINK_INDEX[3] ^ ~S186_OUT; + wire Q182_OUT = VSHRINK_INDEX[2] ^ ~S186_OUT; + wire Q186_OUT = VSHRINK_INDEX[1] ^ ~S186_OUT; + wire Q172_OUT = VSHRINK_INDEX[0] ^ ~S186_OUT; + //FDSCell O175(P222A_OUT, {Q184_OUT, Q182_OUT, Q186_OUT, Q172_OUT}, SPR_TILEMAP); + always @(posedge CLK) if (P222A_OUT_RISE) SPR_TILEMAP <= {Q184_OUT, Q182_OUT, Q186_OUT, Q172_OUT}; + + + wire VCS_EN = ~VCS & R94A_OUT; // VCS rising edge + // P bus stuff + // Lookup ROM data latch + //FDSCell Q87(VCS, PBUS_IO[23:20], VSHRINK_INDEX); + //FDSCell S141(VCS, PBUS_IO[19:16], VSHRINK_LINE); + always @(posedge CLK) if (VCS_EN) {VSHRINK_INDEX, VSHRINK_LINE} <= PBUS_IO[23:16]; + + + //wire R88_Q, R88_nQ; + //FDM R88(CLK_24M, R94A_OUT, R88_Q, R88_nQ); + reg R88_Q, R88_nQ; + always @(posedge CLK) if (CLK_EN_24M_P) {R88_Q, R88_nQ} <= {R94A_OUT, ~R94A_OUT}; + assign VCS = ~R88_nQ; + + + //wire T185B_OUT = PCK1 | PCK2; + // Data select lines + //wire S183_Q, S183_Q_DELAYED; + //FDM S183(T185B_OUT, S171_Q, S183_Q); + reg S183_Q; + always @(posedge CLK) if (PCK1_EN_P | PCK2_EN_P) S183_Q <= S171_Q; + //wire S183_Q_DELAYED; + //BD3 P196(S183_Q, S183_Q_DELAYED); + reg S183_Q_DELAYED; + always @(posedge CLK) S183_Q_DELAYED <= S183_Q; + + //wire S171_Q, S171_nQ; + //FDM S171(U53_Q, LSPC_1_5M, S171_Q, S171_nQ); + reg S171_Q, S171_nQ; + always @(posedge CLK) if (CLK_EN_24M_P & ~U53_Q & T53_Q) {S171_Q, S171_nQ} <= {LSPC_1_5M, ~LSPC_1_5M}; + + assign XPOS = PIPE_C[8:0]; + + assign SPR_TILE_AA[2] = AUTOANIM3_EN ? AA_COUNT[2] : SPR_TILE[2]; + assign SPR_TILE_AA[1:0] = AUTOANIM2_EN ? AA_COUNT[1:0] : SPR_TILE[1:0]; + + // Q125 R120 + assign XPOS_ROUND_UP = XPOS[8:1] + {7'd0, XPOS[0]}; + + // K143A K145A K147A K149A + // Q111A Q113B Q113A Q111B + assign P_MUX_HIGH = R88_Q ? XPOS[8:1] : YSHRINK; + + // R185A R185B R183A R183B + // R277A R277B R275A R275B + assign LO_LINE_MUX = SPR_CONTINUOUS ? ~LO_LINE_B : LO_LINE_A; // Might be swapped + + // R149A R149B R147A R147B + // Q149A Q120A Q121B Q149B + assign P_MUX_LOW = R88_Q ? XPOS_ROUND_UP : LO_LINE_MUX; + + + // **Gyurco** exposed to SDRAM controller + assign LO_ROM_ADDR = {YSHRINK, LO_LINE_MUX}; + + // Output mux + // C250 A238A A232 A234A + // E271 E273A E268A D255 + assign P_OUT_MUX[23:16] = ~S183_Q_DELAYED ? + ~S171_nQ ? + {SPR_PAL} + : + {SPR_TILE[19:16], SPR_LINE} + : + ~S171_nQ ? + {8'b00000000} + : + {4'b0000, FIX_PAL}; + + // J39A M230A L228A L247A + // C256 B269A B273A B276A + // B220 C248 B217A B215 + // B197A B130A B128 B148A + assign P_OUT_MUX[15:0] = ~S183_Q_DELAYED ? + ~S171_nQ ? + {P_MUX_HIGH, P_MUX_LOW} + : + {SPR_TILE[15:8], SPR_TILE[7:3], SPR_TILE_AA} + : + ~S171_nQ ? + {PIXELC[2], RASTERC[2:1], FLIP, FIX_TILE[11:8], FIX_TILE[7:0]} + : + {8'b00000000, 8'b00000000}; + + assign PBUS_IO = nPBUS_OUT_EN ? 8'bzzzzzzzz : P_OUT_MUX[23:16]; + assign PBUS_OUT = P_OUT_MUX[15:0]; + + + // Y position stuff + // O268 O237 + assign SPR_Y_LOOKAHEAD = {RASTERC[7:1], FLIP} + 1'b1; + // P261 P237 + assign SPR_Y_ADD = SPR_Y_LOOKAHEAD + SPR_Y[7:0]; + // R216 R218 R238 R241 + // R281 R283 Q289 Q291 + assign LO_LINE_A = SPR_Y_ADD[7:0] ^ {8{~P235_OUT}}; + wire P235_OUT = ~(SPR_Y[8] ^ SPR_Y_ADD[8]); + // Q237 R189 + assign SPR_Y_SHRINK = LO_LINE_A + {1'b0, ~YSHRINK}; + // Q265 R151 + assign LO_LINE_B = LO_LINE_A + {~YSHRINK[6:0], 1'b0}; + + // Special #33 height detection + // R222A + assign SPR_CONTINUOUS = &{SPR_SIZE0, SPR_SIZE5, SPR_Y_SHRINK[8]}; + + wire WR_VRAM_ADDR, WR_VRAM_RW, WR_TIMER_HIGH, WR_TIMER_LOW, WR_IRQ_ACK, TIMER_IRQ_EN, AA_DISABLE, TIMER_STOP, nVRAM_WRITE_REQ; + lspc_regs_sync REGS_SYNC(CLK, RESET, nRESETP, M68K_ADDR, M68K_DATA, LSPOE, LSPWE, VMODE, RASTERC, AA_COUNT, VRAM_LOW_READ, + VRAM_HIGH_READ, WR_VRAM_ADDR, WR_VRAM_RW, WR_TIMER_HIGH, WR_TIMER_LOW, WR_IRQ_ACK, REG_VRAMADDR, + REG_VRAMMOD, REG_VRAMRW, REG_LSPCMODE, CPU_DATA_OUT, AA_SPEED, TIMER_MODE, TIMER_IRQ_EN, + AA_DISABLE, TIMER_STOP, nVRAM_WRITE_REQ, D112B_OUT_DELAY); + + wire LSPC_6M, D46A_OUT; + lspc_timer_sync TIMER_SYNC(CLK, LSPC_6M, LSPC_EN_6M_N, LSPC_EN_6M_P, nRESETP, M68K_DATA, WR_TIMER_HIGH, WR_TIMER_LOW, VMODE, TIMER_MODE, TIMER_STOP, + RASTERC, TIMER_IRQ_EN, R74_nQ_EN, BNKB, D46A_OUT); + + resetp_sync RSTP_SYNC(CLK, CLK_EN_24M_N, RESET, nRESETP); + + wire BNK; + irq_sync IRQ_SYNC(CLK, WR_IRQ_ACK, M68K_DATA[2:0], RESET, D46A_OUT, CD_TIMER_IRQ_EN, BNK, CD_VBLANK_IRQ_EN, LSPC_EN_6M_P, IPL0, IPL1); + + wire FLIP, P50_CO; + videosync_sync VS_SYNC(CLK, CLK_EN_24M_P, CLK_EN_24M_N, LSPC_3M, LSPC_1_5M, LSPC_EN_1_5M_P, LSPC_EN_1_5M_N, nRESETP, VMODE, PIXELC, RASTERC, HSYNC, VSYNC, BNK, + BNKB, CHBL, R15_QD, FLIP, nFLIP, P50_CO); + + wire CLK_24M = ~CLK_24MB; + wire Q53_CO; + lspc2_clk_sync LSPCCLK_SYNC(CLK, CLK_EN_24M_P, CLK_EN_24M_N, nRESETP, CLK_24MB, LSPC_12M, LSPC_8M, LSPC_6M, LSPC_4M, LSPC_3M, LSPC_1_5M, Q53_CO, + LSPC_EN_12M_P, LSPC_EN_12M_N, LSPC_EN_6M_P, LSPC_EN_6M_N, LSPC_EN_3M, LSPC_EN_1_5M_P, LSPC_EN_1_5M_N, LSPC_EN_4M_P, LSPC_EN_4M_N); + + wire SPR_TILE_VFLIP, SPR_TILE_HFLIP, SPR_AA_3, SPR_AA_2, nCPU_WR_LOW, R91_nQ, T160A_OUT, T160B_OUT, CLK_ACTIVE_RD_EN; + wire ACTIVE_RD_PRE8; + wire PIXEL_H8_RISE = LSPC_EN_6M_N && PIXELC[3:0] == 4'b0111; + slow_cycle_sync SCY_SYNC(CLK, CLK_EN_24M_P, LSPC_12M, LSPC_EN_12M_N, LSPC_EN_12M_P, LSPC_6M, LSPC_EN_6M_N, LSPC_3M, LSPC_EN_1_5M_N, + nRESETP, VRAM_ADDR[14:0], VRAM_WRITE, + REG_VRAMADDR[15], PIXELC[3], PIXEL_H8_RISE, PIXELC[8], RASTERC[7:3], PIXEL_HPLUS, ACTIVE_RD, + nVRAM_WRITE_REQ, SPR_TILEMAP, SPR_TILE_VFLIP, SPR_TILE_HFLIP, SPR_AA_3, SPR_AA_2, + FIX_TILE, FIX_PAL, SPR_TILE, SPR_PAL, VRAM_LOW_READ, nCPU_WR_LOW, R91_nQ, + T160A_OUT, T160B_OUT, CLK_ACTIVE_RD_EN, ACTIVE_RD_PRE8, Q174B_OUT, + CLK_SPR_ATTR_EN, SPRITEMAP_ADDR_MSB, CLK_SPR_TILE_EN, P222A_OUT_RISE, ~P201_Q[1], + SVRAM_ADDR, SVRAM_DATA_IN, SVRAM_DATA_OUT, BOE, BWE, FIXMAP_ADDR, SPRMAP_ADDR, VRAM_CYCLE); + + wire nCPU_WR_HIGH, R91_Q, SPR_SIZE0, SPR_SIZE5, O159_QB; + + fast_cycle_sync FCY_SYNC(CLK, CLK_24M, CLK_EN_24M_P, CLK_EN_24M_N, LSPC_EN_12M_P, LSPC_EN_6M_P, LSPC_EN_3M, LSPC_1_5M, nRESETP, nVRAM_WRITE_REQ, + VRAM_ADDR, VRAM_WRITE, REG_VRAMADDR[15], FLIP, nFLIP, + PIXELC, RASTERC, P50_CO, nCPU_WR_HIGH, HSHRINK, PIPE_C, VRAM_HIGH_READ, + ACTIVE_RD, R91_Q, R91_nQ, T140_Q, T58A_OUT, T73A_OUT, U129A_Q, T125A_OUT, T125A_OUT_RISE, + CLK_ACTIVE_RD_EN, ACTIVE_RD_PRE8, SPR_Y, YSHRINK, SPR_SIZE0, SPR_SIZE5, O159_QB, + FVRAM_ADDR, FVRAM_DATA_IN, FVRAM_DATA_OUT, CWE); + + autoanim_sync AA_SYNC(CLK, RASTERC[8], nRESETP, AA_SPEED, AA_COUNT); + + wire HSHRINK_OUT_A, HSHRINK_OUT_B; + hshrink_sync HSH_SYNC(CLK, HSHRINK, CK_HSHRINK_EN, LD_HSHRINK_REG, HSHRINK_OUT_A, HSHRINK_OUT_B); + wire nHSHRINK_OUT_A = ~HSHRINK_OUT_A; + wire nHSHRINK_OUT_B = ~HSHRINK_OUT_B; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_clk.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_clk.v new file mode 100644 index 0000000000000000000000000000000000000000..50094ea9c8064c1e41050a7bdb28bd8f95deaeea --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc2_clk.v @@ -0,0 +1,92 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module lspc2_clk_sync( + input CLK, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + input nRESETP, + + output CLK_24MB, + output LSPC_12M, + output reg LSPC_8M, + output LSPC_6M, + output reg LSPC_4M, + output LSPC_3M, + output LSPC_1_5M, + output Q53_CO, + + output reg LSPC_EN_12M_P, + output reg LSPC_EN_12M_N, + output reg LSPC_EN_6M_P, + output reg LSPC_EN_6M_N, + output reg LSPC_EN_3M, + output reg LSPC_EN_1_5M_P, + output reg LSPC_EN_1_5M_N, // Q53_CO + output LSPC_EN_4M_P, + output LSPC_EN_4M_N +); +reg CLK_24M; +/* verilator lint_off UNOPTFLAT */ +reg [3:0] DIV_CNT; +/* verilator lint_on UNOPTFLAT */ +reg [1:0] DIV_CNT3; + +always @(posedge CLK) begin + if (CLK_EN_24M_N) begin + CLK_24M <= 0; + if (!nRESETP) begin + DIV_CNT <= 4'b0010; + end else begin + DIV_CNT <= DIV_CNT + 1'd1; + DIV_CNT3 <= DIV_CNT3 + 1'd1; + if (DIV_CNT3 == 2) DIV_CNT3 <= 0; + end + end + if (CLK_EN_24M_P) + CLK_24M <= 1; + + LSPC_EN_12M_P <= CLK_EN_24M_P && ~DIV_CNT[0]; + LSPC_EN_12M_N <= CLK_EN_24M_P && DIV_CNT[0]; + LSPC_EN_6M_P <= CLK_EN_24M_P && (DIV_CNT[1:0] == 1); + LSPC_EN_6M_N <= CLK_EN_24M_P && (DIV_CNT[1:0] == 3); + LSPC_EN_3M <= CLK_EN_24M_P && (DIV_CNT[2:0] == 3); + LSPC_EN_1_5M_P <= CLK_EN_24M_P && (DIV_CNT == 7); + LSPC_EN_1_5M_N <= CLK_EN_24M_P && (DIV_CNT == 15); + +end +assign Q53_CO = (DIV_CNT == 15); // Q53_CO + +wire CLK8_FALL = CLK_EN_24M_P & DIV_CNT3 == 2; +wire CLK8_RISE = CLK_EN_24M_N & DIV_CNT3 == 0; +always @(posedge CLK) if (CLK8_FALL) LSPC_8M <= 0; else if (CLK8_RISE) LSPC_8M <= 1; + +always @(posedge CLK) if (CLK8_FALL) LSPC_4M <= ~LSPC_4M; +assign LSPC_EN_4M_P = ~LSPC_4M & CLK8_FALL; +assign LSPC_EN_4M_N = LSPC_4M & CLK8_FALL; + +assign CLK_24MB = ~CLK_24M; +assign LSPC_1_5M = DIV_CNT[3]; +assign LSPC_3M = DIV_CNT[2]; +assign LSPC_6M = DIV_CNT[1]; +assign LSPC_12M = DIV_CNT[0]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_regs.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_regs.v new file mode 100644 index 0000000000000000000000000000000000000000..83227325d4485984bd2df4de2e5d62e4a40e4588 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_regs.v @@ -0,0 +1,165 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + + +/* verilator lint_off PINMISSING */ + +module lspc_regs_sync( + input CLK, + input RESET, + input RESETP, + + input [3:1] M68K_ADDR, + input [15:0] M68K_DATA, + + input LSPOE, + input LSPWE, + + input VMODE, + input [8:0] RASTERC, + input [2:0] AA_COUNT, + input [15:0] VRAM_LOW_READ, + input [15:0] VRAM_HIGH_READ, + + + output WR_VRAM_ADDR, + output WR_VRAM_RW, + output WR_TIMER_HIGH, + output WR_TIMER_LOW, + output WR_IRQ_ACK, + + output [15:0] REG_VRAMADDR, + output [15:0] REG_VRAMMOD, + output [15:0] REG_VRAMRW, + output [15:0] REG_LSPCMODE, + output [15:0] CPU_DATA_OUT, + output [7:0] AA_SPEED, // Auto-animation speed + output [2:0] TIMER_MODE, // Timer mode + output TIMER_IRQ_EN, // Timer interrupt enable + output AA_DISABLE, // Auto-animation disable + output TIMER_STOP, + output nVRAM_WRITE_REQ, + input VRAM_WRITE_ACK //D112B_OUT +); + + reg [7:0] WR_DECODED /* synthesis keep */; // DEBUG + wire [15:0] CPU_DATA_MUX; + + // CPU address decode + // C27 + always @(*) + begin + if (~LSPWE) + begin + case (M68K_ADDR) + 3'h0 : WR_DECODED = 8'b11111110; + 3'h1 : WR_DECODED = 8'b11111101; + 3'h2 : WR_DECODED = 8'b11111011; + 3'h3 : WR_DECODED = 8'b11110111; + 3'h4 : WR_DECODED = 8'b11101111; + 3'h5 : WR_DECODED = 8'b11011111; + 3'h6 : WR_DECODED = 8'b10111111; + 3'h7 : WR_DECODED = 8'b01111111; + endcase + end + else + WR_DECODED = 8'b11111111; + end + + assign WR_VRAM_ADDR = WR_DECODED[0]; + assign WR_VRAM_RW = WR_DECODED[1]; + wire WR_VRAM_MOD = WR_DECODED[2]; + wire WR_LSPC_MODE = WR_DECODED[3]; + assign WR_TIMER_HIGH = WR_DECODED[4]; + assign WR_TIMER_LOW = WR_DECODED[5]; + assign WR_IRQ_ACK = WR_DECODED[6]; + wire WR_TIMER_STOP = WR_DECODED[7]; + + + // CPU reads + assign REG_LSPCMODE = {RASTERC, 3'b0, VMODE, AA_COUNT}; + + // Read: CPU_READ_SW: + // $3C0000 REG_VRAMRW REG_VRAMADDR_MSB + // $3C0002 REG_VRAMRW REG_VRAMADDR_MSB + // $3C0004 REG_VRAMMOD 0 + // $3C0006 REG_LSPCMODE 1 + // C20A C22B C20B + wire CPU_READ_SW = ~|{~|{M68K_ADDR[1], ~M68K_ADDR[2]}, ~|{REG_VRAMADDR[15], M68K_ADDR[2]}}; + + // CPU read data select + // F218A F221A F230 G252A + // K172 F235 F232 G250 + // G274 G276A G267A H266A + // I250A I253 I255A H264 + assign CPU_DATA_MUX = M68K_ADDR[2] ? + CPU_READ_SW ? REG_LSPCMODE : REG_VRAMMOD + : + CPU_READ_SW ? VRAM_HIGH_READ : VRAM_LOW_READ; + + // CPU read data latch + // B138 A123 A68 A28 + //FDS16bit B138(~LSPOE, CPU_DATA_MUX, CPU_DATA_OUT); + register #(16) B138(CLK, 1'b0, 1'b0, ~LSPOE, CPU_DATA_MUX, CPU_DATA_OUT); + + // CPU write to REG_VRAMRW + // F155 D131 D121 E154 + //FDS16bit F155(~WR_VRAM_RW, M68K_DATA, REG_VRAMRW); + register #(16) F155(CLK, 1'b0, 1'b0, ~WR_VRAM_RW, M68K_DATA, REG_VRAMRW); + + // CPU VRAM write request flag handling + // Set by write to REG_VRAMRW, reset when write is done or write to REG_VRAMADDR + //wire D32A_OUT = D28_nQ & 1'b1; // Used for test mode + //wire D28_nQ; + //wire VRAM_WRITE_REQ; // D38_Q + //wire nVRAM_WRITE_DONE; // D28_nQ, D32A_OUT + //FDPCell D38(~WR_VRAM_RW, 1'b1, 1'b1, nVRAM_WRITE_DONE, VRAM_WRITE_REQ, nVRAM_WRITE_REQ); + //FDPCell D28(D112B_OUT, 1'b1, 1'b1, VRAM_WRITE_REQ, , nVRAM_WRITE_DONE); + wire VRAM_WRITE_REQ; + reg VRAM_WRITE_DONE; + register D38(CLK, 1'b0, VRAM_WRITE_DONE, ~WR_VRAM_RW, 1'b1, VRAM_WRITE_REQ); + always @(posedge CLK) begin + reg VRAM_WRITE_ACK_d; + VRAM_WRITE_ACK_d <= VRAM_WRITE_ACK; + if (~VRAM_WRITE_REQ) + VRAM_WRITE_DONE <= 0; + else if (~VRAM_WRITE_ACK_d & VRAM_WRITE_ACK) + VRAM_WRITE_DONE <= 1; + end + assign nVRAM_WRITE_REQ = ~VRAM_WRITE_REQ; + // CPU write to REG_VRAMMOD + // H105 G105 F81 G123 + //FDS16bit H105(~WR_VRAM_MOD, M68K_DATA, REG_VRAMMOD); + register #(16) H105(CLK, 1'b0, 1'b0, ~WR_VRAM_MOD, M68K_DATA, REG_VRAMMOD); + + // CPU write to REG_VRAMADDR + // F47 D87 A79 C123 + //FDS16bit F47(~WR_VRAM_ADDR, M68K_DATA, REG_VRAMADDR); + register #(16) F47(CLK, 1'b0, 1'b0, ~WR_VRAM_ADDR, M68K_DATA, REG_VRAMADDR); + + // CPU write to REG_LSPCMODE + //FDSCell E105(WR_LSPC_MODE, M68K_DATA[15:12], AA_SPEED[7:4]); + //FDSCell C87(WR_LSPC_MODE, M68K_DATA[11:8], AA_SPEED[3:0]); + //FDPCell E74(WR_LSPC_MODE, M68K_DATA[7], 1'b1, RESET, TIMER_MODE[2]); + //FDRCell E61(WR_LSPC_MODE, M68K_DATA[6:3], RESET, {TIMER_MODE[1:0], TIMER_IRQ_EN, AA_DISABLE}); + register #(8) E105_C87(CLK, 1'b0, 1'b0, WR_LSPC_MODE, M68K_DATA[15:8], AA_SPEED); + register #(5) E74_E61(CLK, 1'b0, ~RESET, WR_LSPC_MODE, M68K_DATA[7:3], {TIMER_MODE, TIMER_IRQ_EN, AA_DISABLE}); + // CPU write to REG_TIMERSTOP + //FDPCell D34(WR_TIMER_STOP, M68K_DATA[0], RESETP, 1'b1, , TIMER_STOP); + register D34(CLK, ~RESETP, 1'b0, WR_TIMER_STOP, M68K_DATA[0], TIMER_STOP); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_timer.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_timer.v new file mode 100644 index 0000000000000000000000000000000000000000..28c9066a36c6835865b8877753e35ceaaa8aea70 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/lspc_timer.v @@ -0,0 +1,167 @@ +//============================================================================ +// SNK NeoGeo for MiSTer +// +// Copyright (C) 2018 Sean 'Furrtek' Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +/* verilator lint_off PINMISSING */ + +module lspc_timer_sync( + input CLK, + input LSPC_6M, + input LSPC_EN_6M_N, + input LSPC_EN_6M_P, + input nRESETP, + input [15:0] M68K_DATA, + input WR_TIMER_HIGH, + input WR_TIMER_LOW, + input VMODE, + input [2:0] TIMER_MODE, + input TIMER_STOP, + input [8:0] RASTERC, + input TIMER_IRQ_EN, + input R74_nQ_EN, + input BNKB, + output D46A_OUT +); + + wire [15:0] REG_TIMERHIGH; + wire [15:0] REG_TIMERLOW; + + + reg nTIMER_EN; + // Lower 16 bits + // K104 K68 K87 K121 + //FDS16bit K104(WR_TIMER_LOW, M68K_DATA, REG_TIMERLOW); + register #(16) K104(CLK, 1'b0, 1'b0, WR_TIMER_LOW, M68K_DATA, REG_TIMERLOW); + + /* + wire nTIMER_EN, L127_CO, M125_CO; + C43 L127(~LSPC_6M, ~REG_TIMERLOW[3:0], nRELOAD, nTIMER_EN, nTIMER_EN, nRESETP, , L127_CO); + C43 M125(~LSPC_6M, ~REG_TIMERLOW[7:4], nRELOAD, L127_CO, nTIMER_EN, nRESETP, , M125_CO); + + wire M52_OUT = M125_CO ^ 1'b0; // Used for test mode + + wire L107A_OUT = L127_CO; + wire M54_CO, L81_CO; + C43 M54(~LSPC_6M, ~REG_TIMERLOW[11:8], nRELOAD, L107A_OUT, M52_OUT, nRESETP, , M54_CO); + C43 L81(~LSPC_6M, ~REG_TIMERLOW[15:12], nRELOAD, L107A_OUT, M54_CO, nRESETP, , L81_CO); + + */ + reg [15:0] TIMER_LOW; + always @(posedge CLK) + if (LSPC_EN_6M_N) begin + if (!nRESETP) + TIMER_LOW <= 0; + else if (!nRELOAD) + TIMER_LOW <= ~REG_TIMERLOW; + else if (nTIMER_EN) + TIMER_LOW <= TIMER_LOW + 1'd1; + end + //wire L81_CO = nTIMER_EN & &TIMER_LOW; + wire L127_CO = nTIMER_EN & &TIMER_LOW[3:0]; + + // Higher 16 bits + // K31 G50 K48 K58 + //FDS16bit K31(WR_TIMER_HIGH, M68K_DATA, REG_TIMERHIGH); + register #(16) K31(CLK, 1'b0, 1'b0, WR_TIMER_HIGH, M68K_DATA, REG_TIMERHIGH); + /* + wire L106A_OUT = L127_CO; + wire L76_OUT = L81_CO ^ 1'b0; // Used for test mode + + wire N50_CO, M18_CO; + C43 N50(~LSPC_6M, ~REG_TIMERHIGH[3:0], nRELOAD, L106A_OUT, L76_OUT, nRESETP, , N50_CO); + C43 M18(~LSPC_6M, ~REG_TIMERHIGH[7:4], nRELOAD, L106A_OUT, N50_CO, nRESETP, , M18_CO); + + wire K29_OUT = M18_CO ^ 1'b0; // Used for test mode + + wire L51_CO, TIMER_CO; + C43 L51(~LSPC_6M, ~REG_TIMERHIGH[11:8], nRELOAD, L106A_OUT, K29_OUT, nRESETP, , L51_CO); + C43 L16(~LSPC_6M, ~REG_TIMERHIGH[15:12], nRELOAD, L106A_OUT, L51_CO, nRESETP, , TIMER_CO); + */ + reg [15:0] TIMER_HIGH; + always @(posedge CLK) + if (LSPC_EN_6M_N) begin + if (!nRESETP) + TIMER_HIGH <= 0; + else if (!nRELOAD) + TIMER_HIGH <= ~REG_TIMERHIGH; + else if (nTIMER_EN & &TIMER_LOW) + TIMER_HIGH <= TIMER_HIGH + 1'd1; + end + wire TIMER_CO = nTIMER_EN & &TIMER_LOW & &TIMER_HIGH; + + // Mode 0 reload pulse gen + wire E10_Q; + reg E20_Q, E20_nQ, E32_nQ; + //FDPCell E10(WR_TIMER_LOW, 1'b0, E14A_OUT, 1'b1, E10_Q); + register E10(CLK, !E14A_OUT, 1'b0, WR_TIMER_LOW, 1'b0, E10_Q); + //FDPCell E20(~LSPC_6M, E10_Q, 1'b1, nRESETP, E20_Q, E20_nQ); + //FDPCell E32(~LSPC_6M, E20_Q, 1'b1, nRESETP, , E32_nQ); + always @(posedge CLK) + if (LSPC_EN_6M_N) begin + {E20_Q, E20_nQ} <= {E10_Q, ~E10_Q}; + E32_nQ <= ~E20_Q; + end + wire E14A_OUT = ~&{E20_nQ, E32_nQ}; + wire RELOAD_MODE0 = ~|{E32_nQ, ~TIMER_MODE[0], E20_Q}; + + // Mode 1 reload pulse gen + reg K18_Q, E16_Q, E36_Q, E46_nQ; + //FDPCell K18(R74_nQ, BNKB, nRESETP, 1'b1, K18_Q); + always @(posedge CLK, negedge nRESETP) + if (!nRESETP) + K18_Q <= 0; + else if (R74_nQ_EN) + K18_Q <= BNKB; + //FDPCell E16(LSPC_6M, K18_Q, nRESETP, 1'b1, E16_Q); + //FDPCell E36(~LSPC_6M, E16_Q, nRESETP, 1'b1, E36_Q); + //FDM E46(~LSPC_6M, E36_Q, , E46_nQ); + always @(posedge CLK, negedge nRESETP) + if (!nRESETP) begin + //K18_Q <= 0; + E16_Q <= 0; + E36_Q <= 0; + end else if (LSPC_EN_6M_P) + E16_Q <= K18_Q; + else if (LSPC_EN_6M_N) begin + E36_Q <= E16_Q; + E46_nQ <= ~E36_Q; + end + + wire RELOAD_MODE1 = ~|{~TIMER_MODE[1], E46_nQ, E36_Q}; + + // Mode 2 reload pulse gen and IRQ + wire K22A_OUT = L127_CO & TIMER_CO; + reg E43_nQ; + //FDM E43(~LSPC_6M, K22A_OUT, , E43_nQ); + always @(posedge CLK) if (LSPC_EN_6M_N) E43_nQ <= ~K22A_OUT; + + wire RELOAD_MODE2 = TIMER_MODE[2] & K22A_OUT; + assign D46A_OUT = ~|{~TIMER_IRQ_EN, E43_nQ}; + + wire nRELOAD = ~|{RELOAD_MODE0, RELOAD_MODE1, RELOAD_MODE2}; + + // Stop option + wire J257A_OUT = ~|{RASTERC[5:4]}; + wire I234_OUT = |{RASTERC[8], ~VMODE, ~TIMER_STOP}; + wire J238B_OUT = ~|{J257A_OUT, I234_OUT}; + //FDM J69(LSPC_6M, J238B_OUT, , nTIMER_EN); + always @(posedge CLK) if (LSPC_EN_6M_P) nTIMER_EN <= ~J238B_OUT; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_273.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_273.v new file mode 100644 index 0000000000000000000000000000000000000000..f3e40b526724d03ebffadc3e56ce3b18f861601e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_273.v @@ -0,0 +1,41 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +module neo_273( + input CLK, + input [19:0] PBUS, + input PCK1B_EN, + input PCK2B_EN, + output reg [19:0] C_LATCH, + output reg [15:0] S_LATCH +); + always @(posedge CLK) begin + if (PCK1B_EN) C_LATCH <= {PBUS[15:0], PBUS[19:16]}; + if (PCK2B_EN) S_LATCH <= {PBUS[11:0], PBUS[15:12]}; + end +/* + always @(posedge PCK1B) + begin + C_LATCH <= {PBUS[15:0], PBUS[19:16]}; + end + + always @(posedge PCK2B) + begin + S_LATCH <= {PBUS[11:0], PBUS[15:12]}; + end +*/ +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_b1.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_b1.v new file mode 100644 index 0000000000000000000000000000000000000000..47cdf3fab0caa3bdeb4c753cb648921cafa80c3f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_b1.v @@ -0,0 +1,146 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// The funny 4-letter names correspond to those on the NEO-B1 die shot trace + +module neo_b1( + input CLK, // For linebuffers RAM + input CLK_EN_6MB, // Pixel clock + input CLK_EN_1HB, // 3MHz 2px Even/odd pixel selection + + input [23:0] PBUS, // Used to retrieve LB addresses loads, SPR palette # and FIX palette # from LSPC + input [7:0] FIXD, // 2 fix pixels + input PCK1_EN, + input PCK2_EN, + input CHBL, // Force PA to zeros + input BNKB, // For Watchdog and PA + input [3:0] GAD, GBD, // 2 sprite pixels + input [3:0] WE, // LB writes + input [3:0] CK, // LB address counter clocks + input TMS0, // LB flip + input LD1, LD2, // Load LB addresses + input SS1, SS2, // Clearing enable for each LB + input S1H1, // 3MHz offset from CLK_1HB + + input A23I, A22I, + output [11:0] PA, // Palette address bus + + input nLDS, // For watchdog kick + input RW, + input nAS, + input [21:17] M68K_ADDR_U, + input [12:1] M68K_ADDR_L, + output nHALT, + output nRESET, + input nRST, + input DOGE, + + input EN_FIX +); + + reg nCPU_ACCESS; + + reg [7:0] FIXD_REG; + reg [3:0] FIX_PAL_REG; + wire [3:0] FIX_COLOR; + wire [3:0] SPR_COLOR; + wire [11:0] RAMBL_OUT; + wire [11:0] RAMBR_OUT; + wire [11:0] RAMTL_OUT; + wire [11:0] RAMTR_OUT; + wire [7:0] SPR_PAL; + wire [1:0] MUX_BA; + wire [11:0] PA_MUX_A; + wire [11:0] PA_MUX_B; + wire [11:0] RAM_MUX_OUT; + reg [11:0] PA_VIDEO; + + // 2px fix data reg + // BEKU AKUR... + always @(posedge CLK) + if (CLK_EN_1HB) FIXD_REG <= FIXD; + + // Switch between odd/even fix pixel + // BEVU AWEQ... + assign FIX_COLOR = S1H1 ? FIXD_REG[7:4] : FIXD_REG[3:0]; + + // IDUF + // EN_FIX gate for Neo CD only + wire FIX_OPAQUE = |{FIX_COLOR} & EN_FIX; + + // GETU FUCA... + always @(posedge CLK) + if (PCK1_EN) FIX_PAL_REG <= PBUS[19:16]; + + assign SPR_PAL = PBUS[23:16]; + + linebuffer RAMBR(CLK, CK[0], WE[0], LD1, SS1, GAD, PCK2_EN, SPR_PAL, PBUS[7:0], RAMBR_OUT); + linebuffer RAMBL(CLK, CK[1], WE[1], LD1, SS1, GBD, PCK2_EN, SPR_PAL, PBUS[15:8], RAMBL_OUT); + linebuffer RAMTR(CLK, CK[2], WE[2], LD2, SS2, GAD, PCK2_EN, SPR_PAL, PBUS[7:0], RAMTR_OUT); + linebuffer RAMTL(CLK, CK[3], WE[3], LD2, SS2, GBD, PCK2_EN, SPR_PAL, PBUS[15:8], RAMTL_OUT); + + assign MUX_BA = {TMS0, S1H1}; + + /* + assign VORU = S1H1 & TMS0; + assign VOTO = S1H1 & ~TMS0; + assign VEZA = ~S1H1 & TMS0; + assign VOKE = ~S1H1 & ~TMS0; + */ + + // Output buffer select + // MEGA MAKA MEJU ORUG... + assign RAM_MUX_OUT = + (MUX_BA == 2'b00) ? RAMBR_OUT : + (MUX_BA == 2'b01) ? RAMBL_OUT : + (MUX_BA == 2'b10) ? RAMTR_OUT : + RAMTL_OUT; + + // Priority for palette address bus (PA): + // -CPU over everything else + // -CHBL (h-blank) + // -Fix pixel if opaque + // -Line buffers (sprites) ouput + + // CPU palette RAM access decode + // JAGU JURA... + always @(posedge CLK) begin + reg nAS_d; + nAS_d <= nAS; + if (!nAS & nAS_d) + nCPU_ACCESS <= A23I | ~A22I; + end + + // Fix/Sprite/Blanking select + // KUQA KUTU JARA... + assign PA_MUX_A = FIX_OPAQUE ? {4'b0000, FIX_PAL_REG, FIX_COLOR} : RAM_MUX_OUT; + assign PA_MUX_B = CHBL ? 12'h000 : PA_MUX_A; + + // KAWE KESE... + always @(posedge CLK) + if (CLK_EN_6MB) PA_VIDEO <= PA_MUX_B; + + // KUTE KENU... + assign PA = nCPU_ACCESS ? PA_VIDEO : M68K_ADDR_L; + + + // Note: nRESET is sync'd to frame start + watchdog WD(CLK, DOGE, nLDS, RW, A23I, A22I, M68K_ADDR_U, BNKB, nHALT, nRESET, nRST); + //assign nHALT = 1; + //assign nRESET = 1; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_cmc.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_cmc.v new file mode 100644 index 0000000000000000000000000000000000000000..e91446ee12d4b2ed513d42f7f11835a1a1769caa --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/neo_cmc.v @@ -0,0 +1,78 @@ +//============================================================================ +// NEO-CMC (bankswitching only) +// +// Copyright (C) 2019 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +//============================================================================ + +module neo_cmc +( + input CLK, + input PCK2B_EN, + input [14:0] PBUS, + input [10:0] ADDR, + input [1:0] TYPE, + output reg [1:0] BANK +); + +always @(posedge CLK) begin + reg [10:0] old_addr; + reg skip; + reg [0:79] banks; + reg [3:0] map[32]; + reg [4:0] line; + + if (PCK2B_EN) begin + + if(ADDR == 'h7E2 && !PBUS[14:12]) begin + skip <= 0; + line <= 0; + BANK <= 1; // for parental advisory (mslug4) + end + + old_addr <= ADDR; + if(old_addr == ADDR) begin + if(TYPE[0]) begin + if(ADDR[10:8] == 7 && !PBUS[14:12]) begin + if(&map[line][3:2] && ~skip) begin + BANK <= map[line][1:0]; + skip <= 1; + end + else begin + line <= line + 1'd1; + skip <= 0; + end + end + + // even words + if ({ADDR[6],ADDR[0],ADDR[10:8]} == 5) begin + if(ADDR[7]) map[ADDR[5:1]][2:0] <= {&PBUS[11:8], ~PBUS[1:0]}; // 7580~75BE + else map[ADDR[5:1]][3] <= (PBUS[11:0] == 'h200); // 7500~753E + end + end + + if(TYPE[1]) begin + // 7500 - 75DF + if(ADDR[10:8] == 5 && &PBUS[14:12]) banks[{1'b0,ADDR[7:5],3'b000}+{2'b00,ADDR[7:5],2'b00} +:12] <= ~PBUS[11:0]; + BANK <= banks[{ADDR[10:5],1'b0} +:2]; + end + end + + if(~^TYPE) BANK <= 0; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/slow_cycle.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/slow_cycle.v new file mode 100644 index 0000000000000000000000000000000000000000..af11535a200e2e29b81d7236d0487e06e9a6ee4d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/slow_cycle.v @@ -0,0 +1,205 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// Slow VRAM is 120ns (3mclk or more, probably 3.5mclk) + +/* verilator lint_off PINMISSING */ + +module slow_cycle_sync( + input CLK, + input CLK_EN_24M_P, + input LSPC_12M, + input LSPC_EN_12M_N, + input LSPC_EN_12M_P, + input LSPC_6M, + input LSPC_EN_6M_N, + input LSPC_3M, + input LSPC_EN_1_5M_N, + input RESETP, + input [14:0] VRAM_ADDR, + input [15:0] VRAM_WRITE, + input REG_VRAMADDR_MSB, + input PIXEL_H8, + input PIXEL_H8_RISE, + input PIXEL_H256, + input [7:3] RASTERC, + input [3:0] PIXEL_HPLUS, + input [7:0] ACTIVE_RD, + input nVRAM_WRITE_REQ, + input [3:0] SPR_TILEMAP, + output reg SPR_TILE_VFLIP, + output reg SPR_TILE_HFLIP, + output reg SPR_AA_3, SPR_AA_2, + output [11:0] FIX_TILE, + output reg [3:0] FIX_PAL, + output reg [19:0] SPR_TILE, + output reg [7:0] SPR_PAL, + output reg [15:0] VRAM_LOW_READ, + output reg nCPU_WR_LOW, + input R91_nQ, + output T160A_OUT, + output T160B_OUT, + input CLK_ACTIVE_RD_EN, + input ACTIVE_RD_PRE8, + output Q174B_OUT, + input CLK_SPR_ATTR_EN, + input SPRITEMAP_ADDR_MSB, + input CLK_SPR_TILE_EN, + input P222A_OUT_RISE, + input P210A_OUT, + + output [14:0] SVRAM_ADDR, + //input [15:0] SVRAM_DATA, + input [31:0] SVRAM_DATA_IN, + output [15:0] SVRAM_DATA_OUT, + output reg BOE, BWE, + + output [14:0] FIXMAP_ADDR, // Extracted for NEO-CMC + output [14:0] SPRMAP_ADDR, + output [1:0] VRAM_CYCLE // Hint to SDRAM controller (10 - Sprite map read, 01 - CPU R/W, 00 - fixmap read) +); + + wire [14:0] B; + wire [15:0] E; + reg [15:0] FIX_MAP_READ; + //wire [14:0] FIXMAP_ADDR; + //wire [14:0] SPRMAP_ADDR; + reg [3:0] D233_Q; + reg [3:0] D283_Q; + reg [3:0] Q162_Q; + + assign SVRAM_ADDR = B; + assign E = SVRAM_DATA_IN[15:0]; + assign SVRAM_DATA_OUT = VRAM_WRITE; + + // CPU read + // H251 F269 F250 D214 + //FDS16bit H251(~CLK_CPU_READ_LOW, E, VRAM_LOW_READ); + always @(posedge CLK) if (CLK_CPU_READ_LOW_EN) VRAM_LOW_READ <= E; + + // Fix map read + // E233 C269 B233 B200 + //FDS16bit E233(Q174B_OUT, E, FIX_MAP_READ); + always @(posedge CLK) if (CLK_SPR_PAL_EN) FIX_MAP_READ <= E; + assign FIX_TILE = FIX_MAP_READ[11:0]; + //FDSCell E251(~CLK_SPR_TILE, FIX_MAP_READ[15:12], FIX_PAL); + always @(posedge CLK) if (CLK_SPR_TILE_EN) FIX_PAL <= FIX_MAP_READ[15:12]; + + // Sprite map read even + // H233 C279 B250 C191 + `ifdef VRAM32 + //**Gyurco** latch later (same time as even address) to make us of 32 bit VRAM reads + //FDS16bit H233(D208B_OUT, E, SPR_TILE[15:0]); + always @(posedge CLK) if (CLK_SPR_ATTR_EN) SPR_TILE[15:0] <= E; + `else + //FDS16bit H233(~CLK_SPR_TILE, E, SPR_TILE[15:0]); + always @(posedge CLK) if (CLK_SPR_TILE_EN) SPR_TILE[15:0] <= E; + `endif + + // Sprite map read odd + // D233 D283 A249 C201 + `ifdef VRAM32 + //**Gyurco** latch second word from 32-bit read + //FDS16bit D233(D208B_OUT, SVRAM_DATA_IN[31:16], {D233_Q, D283_Q, SPR_TILE[19:16], SPR_AA_3, SPR_AA_2, SPR_TILE_VFLIP, SPR_TILE_HFLIP}); + always @(posedge CLK) if (CLK_SPR_ATTR_EN) {D233_Q, D283_Q, SPR_TILE[19:16], SPR_AA_3, SPR_AA_2, SPR_TILE_VFLIP, SPR_TILE_HFLIP} <= SVRAM_DATA_IN[31:16]; + `else + //FDS16bit D233(D208B_OUT, E, {D233_Q, D283_Q, SPR_TILE[19:16], SPR_AA_3, SPR_AA_2, SPR_TILE_VFLIP, SPR_TILE_HFLIP}); + always @(posedge CLK) if (CLK_SPR_ATTR_EN) {D233_Q, D283_Q, SPR_TILE[19:16], SPR_AA_3, SPR_AA_2, SPR_TILE_VFLIP, SPR_TILE_HFLIP} <= E; + `endif + //FDSCell C233(Q174B_OUT, D233_Q, SPR_PAL[7:4]); + //FDSCell D269(Q174B_OUT, D283_Q, SPR_PAL[3:0]); + always @(posedge CLK) if (CLK_SPR_PAL_EN) SPR_PAL <= {D233_Q, D283_Q}; + + //assign E = VRAM_LOW_WRITE ? VRAM_WRITE : 16'bzzzzzzzzzzzzzzzz; + + // BOE and BWE outputs + wire Q220_Q, R287A_OUT, R289_nQ; + //FD2 Q220(CLK_24MB, nCPU_WR_LOW, Q220_Q, BOE); + always @(posedge CLK) if (CLK_EN_24M_P) BOE <= ~nCPU_WR_LOW; + //FD2 R289(LSPC_12M, R287A_OUT, BWE, R289_nQ); + always @(posedge CLK) if (LSPC_EN_12M_N) BWE <= R287A_OUT; + //assign R287A_OUT = Q220_Q | R289_nQ; + assign R287A_OUT = ~BOE | ~BWE; + //assign VRAM_LOW_WRITE = ~BWE; + + + // Address mux + // E54A F34 F30A + // F39A J31A H39A H75A + // F206A I75A E146A N177 + // N179A N182 N172A K169A + assign B = ~N165_nQ ? + ~N160_Q ? SPRMAP_ADDR : 15'd0 + : + ~N160_Q ? FIXMAP_ADDR : VRAM_ADDR; + + assign VRAM_CYCLE = {~N165_nQ, N160_Q}; + assign FIXMAP_ADDR = {4'b1110, O62_nQ, PIXEL_HPLUS, ~PIXEL_H8, RASTERC[7:3]}; + assign SPRMAP_ADDR = {H57_Q, ACTIVE_RD, O185_Q, SPR_TILEMAP, K166_Q}; + + wire /*O185_Q, H57_Q, K166_Q, N165_nQ,*/ N169A_OUT/*, N160_Q*/; + reg O185_Q; + //FDM O185(P222A_OUT, SPRITEMAP_ADDR_MSB, O185_Q); + always @(posedge CLK) if (P222A_OUT_RISE) O185_Q <= SPRITEMAP_ADDR_MSB; + reg H57_Q; + //FDM H57(CLK_ACTIVE_RD, ACTIVE_RD_PRE8, H57_Q); + always @(posedge CLK) if (CLK_ACTIVE_RD_EN) H57_Q <= ACTIVE_RD_PRE8; + //FDM K166(CLK_24M, P210A_OUT, K166_Q); + //FDM N165(CLK_24M, Q174B_OUT, , N165_nQ); + //FDM N160(CLK_24M, N169A_OUT, N160_Q); + reg K166_Q, N165_nQ, N160_Q; + always @(posedge CLK) + if (CLK_EN_24M_P) {K166_Q, N165_nQ, N160_Q} <= {P210A_OUT, ~Q174B_OUT, N169A_OUT}; + + //FS1 Q162(LSPC_12M, R91_nQ, Q162_Q); + always @(posedge CLK) + if (LSPC_EN_12M_N) Q162_Q <= {Q162_Q[2:0], ~R91_nQ}; + assign Q174B_OUT = ~Q162_Q[3]; + assign N169A_OUT = ~|{Q174B_OUT, ~CLK_CPU_READ_LOW}; + wire CLK_SPR_PAL_EN = LSPC_EN_12M_N & Q162_Q[3] & ~Q162_Q[2]; + + //wire T75_Q/*, O62_Q, O62_nQ*/; + //FDM T75(CLK_24M, T64A_OUT, T75_Q); + reg T75_Q; + always @(posedge CLK) if (CLK_EN_24M_P) T75_Q <= T64A_OUT; + wire CLK_CPU_READ_LOW = Q162_Q[1]; + wire CLK_CPU_READ_LOW_EN = LSPC_EN_12M_N & Q162_Q[1] & ~Q162_Q[0]; + assign T160B_OUT = ~|{T75_Q, ~Q162_Q[0]}; + assign T160A_OUT = ~|{Q162_Q[0], T75_Q}; + wire T64A_OUT = ~&{LSPC_12M, LSPC_6M, LSPC_3M}; + + //FDPCell O62(PIXEL_H8, PIXEL_H256, 1'b1, RESETP, O62_Q, O62_nQ); + reg O62_nQ; + always @(posedge CLK) + if (~RESETP) + O62_nQ <= 1'b1; + else if (PIXEL_H8_RISE) + O62_nQ <= ~PIXEL_H256; + + wire F58B_OUT = REG_VRAMADDR_MSB | nVRAM_WRITE_REQ /* synthesis keep */; + //FDPCell Q106(~LSPC_1_5M, F58B_OUT, CLK_CPU_READ_LOW, 1'b1, nCPU_WR_LOW); + always @(posedge CLK) + if (!CLK_CPU_READ_LOW) + nCPU_WR_LOW <= 1; + else if (LSPC_EN_1_5M_N) + nCPU_WR_LOW <= F58B_OUT; + + + //vram_slow_u VRAMLU(B, E[15:8], 1'b0, BOE, BWE); + //vram_slow_l VRAMLL(B, E[7:0], 1'b0, BOE, BWE); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/videosync.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/videosync.v new file mode 100644 index 0000000000000000000000000000000000000000..ba1ac92c8dfcea2309bea79cc2a617b885a5f72d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/videosync.v @@ -0,0 +1,223 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// Rewrite to fully synchronous logic by (C) 2023 Gyorgy Szombathelyi +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +/* verilator lint_off PINMISSING */ + +module videosync_sync( + input CLK, + input CLK_EN_24M_P, + input CLK_EN_24M_N, + input LSPC_3M, + input LSPC_1_5M, + input LSPCE_EN_1_5M_P, + input LSPCE_EN_1_5M_N, // Q53_CO + input nRESETP, + input VMODE, + output [8:0] PIXELC, + output [8:0] RASTERC, + output HSYNC, + output VSYNC, + output BNK, + output BNKB, + output CHBL, + output R15_QD, + output reg FLIP, + output nFLIP, + output reg P50_CO +); + + //wire [3:0] S122_REG; + //wire [3:0] R15_REG; + //wire [3:0] T116_REG; + + assign R15_QD = R15_REG[3]; + assign nFLIP = ~FLIP; + + wire RASTER_CHG = ({P15_Q[2:0], P50_Q} == 7'b0111111) & LSPCE_EN_1_5M_N; + + always @(posedge CLK or negedge nRESETP) + begin + if (!nRESETP) + FLIP <= 0; + else + begin + if (RASTER_CHG) + FLIP <= ~FLIP; + end + end + /*FDPCell H287(J22_OUT, H287_nQ, 1'b1, nRESETP, H287_Q, H287_nQ); + assign nFLIP = ~H287_Q; + assign FLIP = ~H287_nQ;*/ + + + // Pixel counter + + reg [3:0] P50_Q; + reg [3:0] P15_Q; + + assign PIXELC = {P15_Q[2:0], P50_Q, LSPC_1_5M, LSPC_3M}; + + always @(posedge CLK) + begin + //C43 P50(CLK_24MB, 4'b1110, nRESETP, Q53_CO, 1'b1, 1'b1, {P50_QD, P50_QC, P50_QB, P50_QA}, P50_CO); + if (!nRESETP) + begin + P50_Q <= 4'b1110; + P50_CO <= 1'b0; + end + else + begin + if (LSPCE_EN_1_5M_N) + begin + P50_Q <= P50_Q + 1'd1; + P50_CO <= (P50_Q == 4'd14); + end + end + + //C43 P15(CLK_24MB, {3'b101, ~nRESETP}, P13B_OUT, Q53_CO, P40A_OUT, 1'b1, {P15_QD, P15_QC, P15_QB, P15_QA}, P15_CO); + //assign P13B_OUT = ~|{P39B_OUT, ~nRESETP}; + //assign P39B_OUT = P15_CO & Q53_CO; + if (~nRESETP | ((P15_Q == 4'd15) & (P50_Q == 4'd15) & LSPCE_EN_1_5M_N)) + P15_Q <= {3'b101, ~nRESETP}; + else + begin + if (LSPCE_EN_1_5M_N & P50_CO) + P15_Q <= P15_Q + 1'd1; + end + end + + // Used for test mode + /*assign P40A_OUT = P50_CO | 1'b0; + + assign PIXELC = {P15_QC, P15_QB, P15_QA, P50_QD, P50_QC, P50_QB, P50_QA, LSPC_1_5M, LSPC_3M}; + + C43 P50(CLK_24MB, 4'b1110, nRESETP, Q53_CO, 1'b1, 1'b1, {P50_QD, P50_QC, P50_QB, P50_QA}, P50_CO); + C43 P15(CLK_24MB, {3'b101, ~nRESETP}, P13B_OUT, Q53_CO, P40A_OUT, 1'b1, {P15_QD, P15_QC, P15_QB, P15_QA}, P15_CO); + + assign P39B_OUT = P15_CO & Q53_CO; + assign P13B_OUT = ~|{P39B_OUT, ~nRESETP};*/ + + + + // Raster counter + + assign RASTERC = {J268_J269_Q, FLIP}; + + reg [7:0] J268_J269_Q; + + + always @(posedge CLK or negedge nRESETP) + begin + if (!nRESETP) + begin + J268_J269_Q <= 8'd0; + end + else + begin + if (RASTER_CHG & FLIP) + begin + // 011001000 0C8 1FF-C8=311d (PAL) + // 011111000 0F8 1FF-F8=263d (NTSC) + if (J268_J269_Q == 8'hFF) + J268_J269_Q <= {3'b011, ~VMODE, ~VMODE, 3'b100}; // Load + else + J268_J269_Q <= J268_J269_Q + 1'd1; + end + end + end + + // Used for test mode + /*assign J22_OUT = PIXELC[8]; //P15_QC ^ 1'b0; + assign H284A_OUT = I269_CO | 1'b0; + + C43 I269(J22_OUT, {~VMODE, 3'b100}, ~J268_CO, FLIP, FLIP, nRESETP, RASTERC[4:1], I269_CO); + C43 J268(J22_OUT, {3'b011, ~VMODE}, ~J268_CO, H284A_OUT, H284A_OUT, nRESETP, RASTERC[8:5], J268_CO);*/ + //assign RASTERC[0] = FLIP; + + // H277B H269B H275A + wire MATCH_PAL = ~&{RASTERC[4:3]} | RASTERC[5] | RASTERC[8]; + + reg BLANK_PAL; + //FDM H272(RASTERC[2], MATCH_PAL, H272_Q); + //FDM I238(FLIP, H272_Q, BLANK_PAL); + always @(posedge CLK) begin + reg MATCH_PAL_D; + if (RASTER_CHG) begin + if (RASTERC[2:0] == 3'b011) MATCH_PAL_D <= MATCH_PAL; // H272 + if (!FLIP) BLANK_PAL <= MATCH_PAL_D; + end + end + + // J259A + wire MATCH_NTSC = ~&{RASTERC[7:5]}; + + // J251 + //FD4 J251(~RASTERC[4], MATCH_NTSC, 1'b1, nRESETP, BLANK_NTSC); + reg BLANK_NTSC; + always @(posedge CLK, negedge nRESETP) begin + if (!nRESETP) + BLANK_NTSC <= 0; + else if (RASTERC[4:0] == 5'b01111 && RASTER_CHG) // rising edge of RASTERC[4] + BLANK_NTSC <= MATCH_NTSC; + end + + // J240A: T2E + assign VSYNC = VMODE ? BLANK_PAL : RASTERC[8]; + assign BNK = ~(VMODE ? RASTERC[8] : BLANK_NTSC); + + // K15B + assign BNKB = ~BNK; + + //assign #1 S136A_OUT = ~LSPC_1_5M; + + // P13A + wire #1 nPIXEL_H256 = ~PIXELC[8]; //~P15_QC + wire P13A_OUT = PIXELC[6] & nPIXEL_H256; //P15_QA + + reg [3:0] R15_REG; + reg [3:0] T116_REG; + reg [3:0] S122_REG; + reg S116_Q; + always @(posedge CLK) + if (LSPCE_EN_1_5M_P) begin + // FS1 R15(S136A_OUT, P13A_OUT, R15_REG); + R15_REG <= {R15_REG[2:0], ~P13A_OUT}; + // FS1 T116(S136A_OUT, ~S51_OUT, T116_REG); + T116_REG <= {T116_REG[2:0], R15_REG[3]}; + // FS1 S122(S136A_OUT, ~U127_OUT, S122_REG); + S122_REG <= {S122_REG[2:0], T116_REG[3]}; + // FD2 S116(S136A_OUT, S119_OUT, S116_Q); + S116_Q <= S122_REG[3]; + end + /*FS1 R15(S136A_OUT, P13A_OUT, R15_REG); + BD3 S51(R15_REG[3], S51_OUT); + FS1 T116(S136A_OUT, ~S51_OUT, T116_REG); + BD3 U127(T116_REG[3], U127_OUT); + FS1 S122(S136A_OUT, ~U127_OUT, S122_REG); + BD3 S119A(S122_REG[3], S119_OUT); + FD2 S116(S136A_OUT, S119_OUT, S116_Q);*/ + + // S131A + assign HSYNC = ~&{S116_Q, ~T116_REG[1]}; + + // M149 + //assign SYNC = ~^{HSYNC, VSYNC}; + + // L40A + assign CHBL = ~R15_REG[3]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/rtl/video/zmc2_dot.v b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/zmc2_dot.v new file mode 100644 index 0000000000000000000000000000000000000000..57e1a833c6c63323f42596e689fe2c8abc0ed5c4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/rtl/video/zmc2_dot.v @@ -0,0 +1,61 @@ +// NeoGeo logic definition +// Copyright (C) 2018 Sean Gonsalves +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// This is by Kyuusaku + +module zmc2_dot( + input CLK, + input CLK_EN_12M_N, + input EVEN, + input LOAD, + input H, + input [31:0] CR, + output reg [3:0] GAD, GBD, + output reg DOTA, DOTB +); + + reg [31:0] SR; + + always @(posedge CLK) + if (CLK_EN_12M_N) begin + if (LOAD) SR <= CR; + else if (H) SR <= {SR[29:24], 2'b00, SR[21:16], 2'b00, SR[13:8], 2'b00, SR[5:0], 2'b00}; + else SR <= {2'b00, SR[31:26], 2'b00, SR[23:18], 2'b00, SR[15:10], 2'b00, SR[7:2]}; + end + + // Load: FEDCBA98 76543210 FEDCBA98 76543210 + // Shift H=0: --FEDCBA --765432 --FEDCBA --765432 --> Two pixels right + // Shift H=1: DCBA98-- 543210-- DCBA98-- 543210-- <-- Two pixels left + + always @* + begin + case ({EVEN, H}) + 3: {GBD, GAD} = {SR[31], SR[23], SR[15], SR[7], SR[30], SR[22], SR[14], SR[6]}; + 2: {GBD, GAD} = {SR[24], SR[16], SR[8], SR[0], SR[25], SR[17], SR[9], SR[1]}; + 1: {GBD, GAD} = {SR[30], SR[22], SR[14], SR[6], SR[31], SR[23], SR[15], SR[7]}; + 0: {GBD, GAD} = {SR[25], SR[17], SR[9], SR[1], SR[24], SR[16], SR[8], SR[0]}; + endcase + + {DOTA, DOTB} = {|GAD, |GBD}; + end + + // EVEN H FEDCBA98 76543210 FEDCBA98 76543210 + // 0 0 BA BA BA BA Reverse shift, X is even + // 0 1 AB AB AB AB Normal shift, X is even + // 1 0 AB AB AB AB Reverse shift, X is odd + // 1 1 BA BA BA BA Normal shift, X is odd + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/alsa.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/alsa.sv new file mode 100644 index 0000000000000000000000000000000000000000..90343893eac82574438c6dbdc0881d2a3d9048fa --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/alsa.sv @@ -0,0 +1,157 @@ +//============================================================================ +// +// ALSA sound support for MiSTer +// (c)2019,2020 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + +module alsa +#( + parameter CLK_RATE = 24576000 +) +( + input reset, + input clk, + + output reg [31:3] ram_address, + input [63:0] ram_data, + output reg ram_req = 0, + input ram_ready, + + input spi_ss, + input spi_sck, + input spi_mosi, + output spi_miso, + + output reg [15:0] pcm_l, + output reg [15:0] pcm_r +); + +reg [60:0] buf_info; +reg [6:0] spicnt = 0; +always @(posedge spi_sck, posedge spi_ss) begin + reg [95:0] spi_data; + + if(spi_ss) spicnt <= 0; + else begin + spi_data[{spicnt[6:3],~spicnt[2:0]}] <= spi_mosi; + if(&spicnt) buf_info <= {spi_data[82:67],spi_data[50:35],spi_data[31:3]}; + spicnt <= spicnt + 1'd1; + end +end + +assign spi_miso = spi_out[{spicnt[4:3],~spicnt[2:0]}]; + +reg [31:0] spi_out = 0; +always @(posedge clk) if(spi_ss) spi_out <= {buf_rptr, hurryup, 8'h00}; + + +reg [31:3] buf_addr; +reg [18:3] buf_len; +reg [18:3] buf_wptr = 0; + +always @(posedge clk) begin + reg [60:0] data1,data2; + + data1 <= buf_info; + data2 <= data1; + if(data2 == data1) {buf_wptr,buf_len,buf_addr} <= data2; +end + +reg [2:0] hurryup = 0; +reg [18:3] buf_rptr = 0; + +always @(posedge clk) begin + reg [18:3] len = 0; + reg [1:0] ready = 0; + reg [63:0] readdata; + reg got_first = 0; + reg [7:0] ce_cnt = 0; + reg [1:0] state = 0; + + if(reset) begin + ready <= 0; + ce_cnt <= 0; + state <= 0; + got_first <= 0; + len <= 0; + end + else begin + + //ramp up + if(len[18:14] && (hurryup < 1)) hurryup <= 1; + if(len[18:16] && (hurryup < 2)) hurryup <= 2; + if(len[18:17] && (hurryup < 4)) hurryup <= 4; + + //ramp down + if(!len[18:15] && (hurryup > 2)) hurryup <= 2; + if(!len[18:13] && (hurryup > 1)) hurryup <= 1; + if(!len[18:10]) hurryup <= 0; + + if(ce_sample && ~&ce_cnt) ce_cnt <= ce_cnt + 1'd1; + + case(state) + 0: if(!ce_sample) begin + if(ready) begin + if(ce_cnt) begin + {readdata[31:0],pcm_r,pcm_l} <= readdata; + ready <= ready - 1'd1; + ce_cnt <= ce_cnt - 1'd1; + end + end + else if(buf_rptr != buf_wptr) begin + if(~got_first) begin + buf_rptr <= buf_wptr; + got_first <= 1; + end + else begin + ram_address <= buf_addr + buf_rptr; + ram_req <= ~ram_req; + buf_rptr <= buf_rptr + 1'd1; + len <= (buf_wptr < buf_rptr) ? (buf_len + buf_wptr - buf_rptr) : (buf_wptr - buf_rptr); + state <= 1; + end + end + else begin + len <= 0; + ce_cnt <= 0; + hurryup <= 0; + end + end + 1: if(ram_ready) begin + ready <= 2; + readdata <= ram_data; + if(buf_rptr >= buf_len) buf_rptr <= buf_rptr - buf_len; + state <= 0; + end + endcase + end +end + +reg ce_sample; +always @(posedge clk) begin + reg [31:0] acc = 0; + + ce_sample <= 0; + acc <= acc + 48000 + {hurryup,6'd0}; + if(acc >= CLK_RATE) begin + acc <= acc - CLK_RATE; + ce_sample <= 1; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/arcade_video.v b/MiSTer-devel_NeoGeo_MiSTer/sys/arcade_video.v new file mode 100644 index 0000000000000000000000000000000000000000..f41d0422958ad1ebf97f10934a05129c1bca9bb8 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/arcade_video.v @@ -0,0 +1,329 @@ +//============================================================================ +// +// Copyright (C) 2017-2020 Sorgelig +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + +////////////////////////////////////////////////////////// +// DW: +// 6 : 2R 2G 2B +// 8 : 3R 3G 2B +// 9 : 3R 3G 3B +// 12 : 4R 4G 4B +// 24 : 8R 8G 8B + +module arcade_video #(parameter WIDTH=320, DW=8, GAMMA=1) +( + input clk_video, + input ce_pix, + + input[DW-1:0] RGB_in, + input HBlank, + input VBlank, + input HSync, + input VSync, + + output CLK_VIDEO, + output CE_PIXEL, + output [7:0] VGA_R, + output [7:0] VGA_G, + output [7:0] VGA_B, + output VGA_HS, + output VGA_VS, + output VGA_DE, + output [1:0] VGA_SL, + + input [2:0] fx, + input forced_scandoubler, + inout [21:0] gamma_bus +); + +assign CLK_VIDEO = clk_video; + +wire hs_fix,vs_fix; +sync_fix sync_v(CLK_VIDEO, HSync, hs_fix); +sync_fix sync_h(CLK_VIDEO, VSync, vs_fix); + +reg [DW-1:0] RGB_fix; + +reg CE,HS,VS,HBL,VBL; +always @(posedge CLK_VIDEO) begin + reg old_ce; + old_ce <= ce_pix; + CE <= 0; + if(~old_ce & ce_pix) begin + CE <= 1; + HS <= hs_fix; + if(~HS & hs_fix) VS <= vs_fix; + + RGB_fix <= RGB_in; + HBL <= HBlank; + if(HBL & ~HBlank) VBL <= VBlank; + end +end + +wire [7:0] R,G,B; + +generate + if(DW == 6) begin + assign R = {RGB_fix[5:4],RGB_fix[5:4],RGB_fix[5:4],RGB_fix[5:4]}; + assign G = {RGB_fix[3:2],RGB_fix[3:2],RGB_fix[3:2],RGB_fix[3:2]}; + assign B = {RGB_fix[1:0],RGB_fix[1:0],RGB_fix[1:0],RGB_fix[1:0]}; + end + else if(DW == 8) begin + assign R = {RGB_fix[7:5],RGB_fix[7:5],RGB_fix[7:6]}; + assign G = {RGB_fix[4:2],RGB_fix[4:2],RGB_fix[4:3]}; + assign B = {RGB_fix[1:0],RGB_fix[1:0],RGB_fix[1:0],RGB_fix[1:0]}; + end + else if(DW == 9) begin + assign R = {RGB_fix[8:6],RGB_fix[8:6],RGB_fix[8:7]}; + assign G = {RGB_fix[5:3],RGB_fix[5:3],RGB_fix[5:4]}; + assign B = {RGB_fix[2:0],RGB_fix[2:0],RGB_fix[2:1]}; + end + else if(DW == 12) begin + assign R = {RGB_fix[11:8],RGB_fix[11:8]}; + assign G = {RGB_fix[7:4],RGB_fix[7:4]}; + assign B = {RGB_fix[3:0],RGB_fix[3:0]}; + end + else if(DW == 18) begin + assign R = {RGB_fix[17:12],RGB_fix[17:16]}; + assign G = {RGB_fix[11: 6],RGB_fix[11:10]}; + assign B = {RGB_fix[ 5: 0],RGB_fix[ 5: 4]}; + end + else begin // 24 + assign R = RGB_fix[23:16]; + assign G = RGB_fix[15:8]; + assign B = RGB_fix[7:0]; + end +endgenerate + +assign VGA_SL = sl[1:0]; +wire [2:0] sl = fx ? fx - 1'd1 : 3'd0; +wire scandoubler = fx || forced_scandoubler; + +video_mixer #(.LINE_LENGTH(WIDTH+4), .HALF_DEPTH(DW!=24), .GAMMA(GAMMA)) video_mixer +( + .CLK_VIDEO(CLK_VIDEO), + .ce_pix(CE), + .CE_PIXEL(CE_PIXEL), + + .scandoubler(scandoubler), + .hq2x(fx==1), + .gamma_bus(gamma_bus), + + .R((DW!=24) ? R[7:4] : R), + .G((DW!=24) ? G[7:4] : G), + .B((DW!=24) ? B[7:4] : B), + + .HSync (HS), + .VSync (VS), + .HBlank(HBL), + .VBlank(VBL), + + .VGA_R(VGA_R), + .VGA_G(VGA_G), + .VGA_B(VGA_B), + .VGA_VS(VGA_VS), + .VGA_HS(VGA_HS), + .VGA_DE(VGA_DE) +); + +endmodule + +//============================================================================ +// +// Screen +90/-90 deg. rotation +// Copyright (C) 2020 Sorgelig +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + +module screen_rotate +( + input CLK_VIDEO, + input CE_PIXEL, + + input [7:0] VGA_R, + input [7:0] VGA_G, + input [7:0] VGA_B, + input VGA_HS, + input VGA_VS, + input VGA_DE, + + input rotate_ccw, + input no_rotate, + input flip, + output video_rotated, + + output FB_EN, + output [4:0] FB_FORMAT, + output reg [11:0] FB_WIDTH, + output reg [11:0] FB_HEIGHT, + output [31:0] FB_BASE, + output [13:0] FB_STRIDE, + input FB_VBL, + input FB_LL, + + output DDRAM_CLK, + input DDRAM_BUSY, + output [7:0] DDRAM_BURSTCNT, + output [28:0] DDRAM_ADDR, + output [63:0] DDRAM_DIN, + output [7:0] DDRAM_BE, + output DDRAM_WE, + output DDRAM_RD +); + +parameter MEM_BASE = 7'b0010010; // buffer at 0x24000000, 3x8MB + +reg do_flip; + +assign DDRAM_CLK = CLK_VIDEO; +assign DDRAM_BURSTCNT = 1; +assign DDRAM_ADDR = {MEM_BASE, i_fb, ram_addr[22:3]}; +assign DDRAM_BE = ram_addr[2] ? 8'hF0 : 8'h0F; +assign DDRAM_DIN = {ram_data,ram_data}; +assign DDRAM_WE = ram_wr; +assign DDRAM_RD = 0; + +assign FB_EN = fb_en[2]; +assign FB_FORMAT = 5'b00110; +assign FB_BASE = {MEM_BASE,o_fb,23'd0}; +assign FB_STRIDE = stride; + +function [1:0] buf_next; + input [1:0] a,b; + begin + buf_next = 1; + if ((a==0 && b==1) || (a==1 && b==0)) buf_next = 2; + if ((a==1 && b==2) || (a==2 && b==1)) buf_next = 0; + end +endfunction + +assign video_rotated = ~no_rotate; + +always @(posedge CLK_VIDEO) begin + do_flip <= no_rotate && flip; + if( do_flip ) begin + FB_WIDTH <= hsz; + FB_HEIGHT <= vsz; + end else begin + FB_WIDTH <= vsz; + FB_HEIGHT <= hsz; + end +end + +reg [1:0] i_fb,o_fb; +always @(posedge CLK_VIDEO) begin + reg old_vbl,old_vs; + old_vbl <= FB_VBL; + old_vs <= VGA_VS; + + if(FB_LL) begin + if(~old_vbl & FB_VBL) o_fb<={1'b0,~i_fb[0]}; + if(~old_vs & VGA_VS) i_fb<={1'b0,~i_fb[0]}; + end + else begin + if(~old_vbl & FB_VBL) o_fb<=buf_next(o_fb,i_fb); + if(~old_vs & VGA_VS) i_fb<=buf_next(i_fb,o_fb); + end +end + +initial begin + fb_en = 0; +end + +reg [2:0] fb_en = 0; +reg [11:0] hsz = 320, vsz = 240; +reg [11:0] bwidth; +reg [22:0] bufsize; +always @(posedge CLK_VIDEO) begin + reg [11:0] hcnt = 0, vcnt = 0; + reg old_vs, old_de; + + if(CE_PIXEL) begin + old_vs <= VGA_VS; + old_de <= VGA_DE; + + hcnt <= hcnt + 1'd1; + if(~old_de & VGA_DE) begin + hcnt <= 1; + vcnt <= vcnt + 1'd1; + end + if(old_de & ~VGA_DE) begin + hsz <= hcnt; + if( do_flip ) bwidth <= hcnt + 2'd3; + end + if(~old_vs & VGA_VS) begin + vsz <= vcnt; + if( !do_flip ) bwidth <= vcnt + 2'd3; + vcnt <= 0; + fb_en <= {fb_en[1:0], ~no_rotate | flip}; + end + if(old_vs & ~VGA_VS) bufsize <= (do_flip ? vsz : hsz ) * stride; + end +end + +wire [13:0] stride = {bwidth[11:2], 4'd0}; + +reg [22:0] ram_addr, next_addr; +reg [31:0] ram_data; +reg ram_wr; +always @(posedge CLK_VIDEO) begin + reg [13:0] hcnt = 0; + reg old_vs, old_de; + + ram_wr <= 0; + if(CE_PIXEL && FB_EN) begin + old_vs <= VGA_VS; + old_de <= VGA_DE; + + if(~old_vs & VGA_VS) begin + next_addr <= + do_flip ? bufsize-3'd4 : + rotate_ccw ? (bufsize - stride) : {vsz-1'd1, 2'b00}; + hcnt <= rotate_ccw ? 3'd4 : {vsz-2'd2, 2'b00}; + end + if(VGA_DE) begin + ram_wr <= 1; + ram_data <= {8'd0,VGA_B,VGA_G,VGA_R}; + ram_addr <= next_addr; + next_addr <= + do_flip ? next_addr-3'd4 : + rotate_ccw ? (next_addr - stride) : (next_addr + stride); + end + if(old_de & ~VGA_DE & ~do_flip) begin + next_addr <= rotate_ccw ? (bufsize - stride + hcnt) : hcnt; + hcnt <= rotate_ccw ? (hcnt + 3'd4) : (hcnt - 3'd4); + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/ascal.vhd b/MiSTer-devel_NeoGeo_MiSTer/sys/ascal.vhd new file mode 100644 index 0000000000000000000000000000000000000000..a735e6b40db8b1e7b5ef2c7836a11d521a96eb7c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/ascal.vhd @@ -0,0 +1,3033 @@ +-------------------------------------------------------------------------------- +-- AVALON SCALER +-------------------------------------------------------------------------------- +-- TEMLIB 2018 - 2020 +-------------------------------------------------------------------------------- +-- This code can be freely distributed and used for any purpose, but, if you +-- find any bug, or want to suggest an enhancement, you ought to send a mail +-- to info@temlib.org. +-------------------------------------------------------------------------------- + +-- Features +-- - Arbitrary output video format +-- - Autodetect input image size or fixed window +-- - Progressive and interlaced input +-- - Interpolation +-- Upscaling : Nearest, Bilinear, Sharp Bilinear, Bicubic, Polyphase +-- Downscaling : Nearest, Bilinear +-- - Avalon bus interface with 128 or 64 bits DATA +-- - Optional triple buffering +-- - Support for external low lag syntonization + +-------------------------------------------- +-- Downscaling +-- - Horizontal and vertical up-/down-scaling are independant. +-- - Downscaling, H and/or V, supports only nearest-neighbour and bilinear +-- filtering. +-- - For interlaced video, when the vertical size is lower than a deinterlaced +-- frame size (2x half-frame), the scaler processes only half-frames +-- and upscales (when the output size is between 1x an 2x) or downscales (size +-- below 1x) them. + +-------------------------------------------- +-- 5 clock domains +-- i_xxx : Input video +-- o_xxx : Output video +-- avl_xxx : Avalon memory bus +-- poly_xxx : Polyphase filters memory +-- pal_xxx : Framebuffer mode 8bpp palette. + +-------------------------------------------- +-- O_FB_FORMAT : Framebuffer format +-- [2:0] : 011=8bpp(palette) 100=16bpp 101=24bpp 110=32bpp +-- [3] : 0=16bits 565 1=16bits 1555 +-- [4] : 0=RGB 1=BGR (for 16/24/32 modes) +-- [5] : TBD + +-------------------------------------------- +-- Image header. When HEADER = TRUE +-- Header Address = RAMBASE +-- Image Address = RAMBASE + HEADER_SIZE + +-- Header (Bytes. Big Endian.) +-- 0 : Type = 1 +-- 1 : Pixel format +-- 0 : 16 bits/pixel, RGB : RRRRRGGGGGGBBBBB +-- 1 : 24 bits/pixel, RGB +-- 2 : 32 bits/pixel, RGB0 + +-- 3:2 : Header size : Offset to start of picture (= N_BURST). 12 bits +-- 5:4 : Attributes +-- b0 ; Interlaced +-- b1 : Field number +-- b2 : Horizontal downscaled +-- b3 : Vertical downscaled +-- b4 : Triple buffered +-- b7-5 : Frame counter +-- 7:6 : Image width. Pixels. 12 bits +-- 9:8 : Image height. Pixels. 12 bits +-- 11:10 : Line length. Bytes. +-- 13:12 : Output width. Pixels. 12 bits +-- 15:14 : Output height. Pixels. 12 bits +-------------------------------------------- + +LIBRARY ieee; +USE ieee.std_logic_1164.ALL; +USE ieee.numeric_std.ALL; + +-- MODE[2:0] +-- 000 : Nearest +-- 001 : Bilinear +-- 010 : Sharp Bilinear +-- 011 : Bicubic +-- 100 : Polyphase +-- 101 : TBD +-- 110 : TBD +-- 111 : TBD + +-- MODE[3] +-- 0 : Direct. Single framebuffer. +-- 1 : Triple buffering + +-- MODE[4] : TBD + +-- MASK : Enable / Disable selected interpoler +-- 0:Nearest 1:Bilinear 2:SharpBilinear 3:Bicubic 4:Polyphase +-- RAMBASE : RAM base address for framebuffer +-- RAMSIZE : RAM allocated for one framebuffer (needs x3 if triple-buffering) +-- Must be a power of two +-- INTER : True=Autodetect interlaced video False=Force progressive scan +-- HEADER : True=Add image properties header +-- PALETTE : Enable palette for framebuffer 8bpp mode +-- PALETTE2 : Enable palette for framebuffer 8bpp mode supplied by core +-- DOWNSCALE : True=Support downscaling False=Downscaling disabled +-- BYTESWAP : Little/Big endian byte swap +-- FRAC : Fractional bits, subpixel resolution +-- OHRES : Max. output horizontal resolution. 1024, 2048, 2304, 2560, 4096 +-- (Used for sizing line buffers) +-- IHRES : Max. input horizontal resolution. Must be a power of two. +-- (Used for sizing line buffers) +-- N_DW : Avalon data bus width. 64 or 128 bits +-- N_AW : Avalon address bus width +-- N_BURST : Burst size in bytes. Power of two. + +ENTITY ascal IS + GENERIC ( + MASK : unsigned(7 DOWNTO 0) :=x"FF"; + RAMBASE : unsigned(31 DOWNTO 0); + RAMSIZE : unsigned(31 DOWNTO 0) := x"0080_0000"; -- =8MB + INTER : boolean := true; + HEADER : boolean := true; + DOWNSCALE : boolean := true; + BYTESWAP : boolean := true; + PALETTE : boolean := true; + PALETTE2 : boolean := true; + ADAPTIVE : boolean := true; + DOWNSCALE_NN : boolean := false; + FRAC : natural RANGE 4 TO 8 :=4; + OHRES : natural RANGE 1 TO 4096 :=2304; + IHRES : natural RANGE 1 TO 2048 :=2048; + N_DW : natural RANGE 64 TO 128 := 128; + N_AW : natural RANGE 8 TO 32 := 32; + N_BURST : natural := 256 -- 256 bytes per burst + ); + PORT ( + ------------------------------------ + -- Input video + i_r : IN unsigned(7 DOWNTO 0); + i_g : IN unsigned(7 DOWNTO 0); + i_b : IN unsigned(7 DOWNTO 0); + i_hs : IN std_logic; -- H sync + i_vs : IN std_logic; -- V sync + i_fl : IN std_logic; -- Interlaced field + i_de : IN std_logic; -- Display Enable + i_ce : IN std_logic; -- Clock Enable + i_clk : IN std_logic; -- Input clock + + ------------------------------------ + -- Output video + o_r : OUT unsigned(7 DOWNTO 0); + o_g : OUT unsigned(7 DOWNTO 0); + o_b : OUT unsigned(7 DOWNTO 0); + o_hs : OUT std_logic; -- H sync + o_vs : OUT std_logic; -- V sync + o_de : OUT std_logic; -- Display Enable + o_vbl : OUT std_logic; -- V blank + o_brd : OUT std_logic; -- border enable + o_ce : IN std_logic; -- Clock Enable + o_clk : IN std_logic; -- Output clock + + -- Border colour R G B + o_border : IN unsigned(23 DOWNTO 0) := x"000000"; + + ------------------------------------ + -- Framebuffer mode + o_fb_ena : IN std_logic :='0'; -- Enable Framebuffer Mode + o_fb_hsize : IN natural RANGE 0 TO 4095 :=0; + o_fb_vsize : IN natural RANGE 0 TO 4095 :=0; + o_fb_format : IN unsigned(5 DOWNTO 0) :="000100"; + o_fb_base : IN unsigned(31 DOWNTO 0) :=x"0000_0000"; + o_fb_stride : IN unsigned(13 DOWNTO 0) :=(OTHERS =>'0'); + + -- Framebuffer palette in 8bpp mode + pal1_clk : IN std_logic :='0'; + pal1_dw : IN unsigned(47 DOWNTO 0) :=x"000000000000"; -- R1 G1 B1 R0 G0 B0 + pal1_dr : OUT unsigned(47 DOWNTO 0) :=x"000000000000"; + pal1_a : IN unsigned(6 DOWNTO 0) :="0000000"; -- Colour index/2 + pal1_wr : IN std_logic :='0'; + + pal_n : IN std_logic :='0'; + + pal2_clk : IN std_logic :='0'; + pal2_dw : IN unsigned(23 DOWNTO 0) :=x"000000"; -- R G B + pal2_dr : OUT unsigned(23 DOWNTO 0) :=x"000000"; + pal2_a : IN unsigned(7 DOWNTO 0) :="00000000"; -- Colour index + pal2_wr : IN std_logic :='0'; + + ------------------------------------ + -- Low lag PLL tuning + o_lltune : OUT unsigned(15 DOWNTO 0); + + ------------------------------------ + -- Input video parameters + iauto : IN std_logic :='1'; -- 1=Autodetect image size 0=Choose window + himin : IN natural RANGE 0 TO 4095 :=0; -- MIN < MAX, MIN >=0, MAX < DISP + himax : IN natural RANGE 0 TO 4095 :=0; + vimin : IN natural RANGE 0 TO 4095 :=0; + vimax : IN natural RANGE 0 TO 4095 :=0; + + -- Detected input image size + i_hdmax : OUT natural RANGE 0 TO 4095; + i_vdmax : OUT natural RANGE 0 TO 4095; + + -- Output video parameters + run : IN std_logic :='1'; -- 1=Enable output image. 0=No image + freeze : IN std_logic :='0'; -- 1=Disable framebuffer writes + mode : IN unsigned(4 DOWNTO 0); + bob_deint : IN std_logic := '0'; + -- SYNC |_________________________/"""""""""\_______| + -- DE |""""""""""""""""""\________________________| + -- RGB | <#IMAGE#> ^HDISP | + -- ^HMIN ^HMAX ^HSSTART ^HSEND ^HTOTAL + htotal : IN natural RANGE 0 TO 4095; + hsstart : IN natural RANGE 0 TO 4095; + hsend : IN natural RANGE 0 TO 4095; + hdisp : IN natural RANGE 0 TO 4095; + hmin : IN natural RANGE 0 TO 4095; + hmax : IN natural RANGE 0 TO 4095; -- 0 <= hmin < hmax < hdisp + vtotal : IN natural RANGE 0 TO 4095; + vsstart : IN natural RANGE 0 TO 4095; + vsend : IN natural RANGE 0 TO 4095; + vdisp : IN natural RANGE 0 TO 4095; + vmin : IN natural RANGE 0 TO 4095; + vmax : IN natural RANGE 0 TO 4095; -- 0 <= vmin < vmax < vdisp + vrr : IN std_logic := '0'; + vrrmax : IN natural RANGE 0 TO 4095 := 0; + swblack : IN std_logic := '0'; -- will output 3 black frame on every resolution switch + + -- Scaler format. 00=16bpp 565, 01=24bpp 10=32bpp + format : IN unsigned(1 DOWNTO 0) :="01"; + + ------------------------------------ + -- Polyphase filter coefficients + -- Order : + -- [Horizontal] [Vertical] [Horizontal2] [Vertical2] + -- [0]...[2**FRAC-1] + -- [-1][0][1][2] + poly_clk : IN std_logic; + poly_dw : IN unsigned(9 DOWNTO 0); + poly_a : IN unsigned(FRAC+3 DOWNTO 0); + poly_wr : IN std_logic; + + ------------------------------------ + -- Avalon + avl_clk : IN std_logic; -- Avalon clock + avl_waitrequest : IN std_logic; + avl_readdata : IN std_logic_vector(N_DW-1 DOWNTO 0); + avl_readdatavalid : IN std_logic; + avl_burstcount : OUT std_logic_vector(7 DOWNTO 0); + avl_writedata : OUT std_logic_vector(N_DW-1 DOWNTO 0); + avl_address : OUT std_logic_vector(N_AW-1 DOWNTO 0); + avl_write : OUT std_logic; + avl_read : OUT std_logic; + avl_byteenable : OUT std_logic_vector(N_DW/8-1 DOWNTO 0); + + ------------------------------------ + reset_na : IN std_logic + ); + +BEGIN + ASSERT N_DW=64 OR N_DW=128 REPORT "DW" SEVERITY failure; + + ASSERT OHRES = 1024 OR OHRES = 2048 OR OHRES = 2304 OR + OHRES = 2560 OR OHRES = 4096 REPORT "OHRES" SEVERITY failure; + +END ENTITY ascal; + +--############################################################################## + +ARCHITECTURE rtl OF ascal IS + + CONSTANT MASK_NEAREST : natural :=0; + CONSTANT MASK_BILINEAR : natural :=1; + CONSTANT MASK_SHARP_BILINEAR : natural :=2; + CONSTANT MASK_BICUBIC : natural :=3; + CONSTANT MASK_POLY : natural :=4; + + ---------------------------------------------------------- + FUNCTION ilog2 (CONSTANT v : natural) RETURN natural IS + VARIABLE r : natural := 1; + VARIABLE n : natural := 0; + BEGIN + WHILE v>r LOOP + n:=n+1; + r:=r*2; + END LOOP; + RETURN n; + END FUNCTION ilog2; + FUNCTION to_std_logic (a : boolean) RETURN std_logic IS + BEGIN + IF a THEN RETURN '1'; + ELSE RETURN '0'; + END IF; + END FUNCTION to_std_logic; + + ---------------------------------------------------------- + FUNCTION ohres_h(CONSTANT r : natural) RETURN natural IS + BEGIN + CASE r IS + WHEN 1024 => RETURN 1024; + WHEN 2048 => RETURN 2048; + WHEN OTHERS => RETURN 4096; + END CASE; + END FUNCTION; + FUNCTION ohres_l(CONSTANT r : natural) RETURN natural IS + BEGIN + CASE r IS + WHEN 1024 => RETURN 1024; + WHEN 2048 | 2304 | 2560 => RETURN 2048; + WHEN OTHERS => RETURN 4096; + END CASE; + END FUNCTION; + FUNCTION ohres_m(CONSTANT r : natural) RETURN natural IS + BEGIN + CASE r IS + WHEN 1024 | 2048 | 2304 => RETURN 256; + WHEN OTHERS => RETURN 512; + END CASE; + END FUNCTION; + + CONSTANT OHRESH : natural := ohres_h(OHRES); + CONSTANT OHRESL : natural := ohres_l(OHRES); + CONSTANT OHRESM : natural := ohres_m(OHRES); + + ---------------------------------------------------------- + CONSTANT NB_BURST : natural :=ilog2(N_BURST); + CONSTANT NB_LA : natural :=ilog2(N_DW/8); -- Low address bits + CONSTANT BLEN : natural :=N_BURST / N_DW * 8; -- Burst length + + ---------------------------------------------------------- + TYPE arr_dw IS ARRAY (natural RANGE <>) OF unsigned(N_DW-1 DOWNTO 0); + + TYPE type_pix IS RECORD + r,g,b : unsigned(7 DOWNTO 0); -- 0.8 + END RECORD; + TYPE arr_pix IS ARRAY (natural RANGE <>) OF type_pix; + TYPE arr_pixq IS ARRAY(natural RANGE <>) OF arr_pix(0 TO 3); + ATTRIBUTE ramstyle : string; + + SUBTYPE uint12 IS natural RANGE 0 TO 4095; + SUBTYPE uint13 IS natural RANGE 0 TO 8191; + + TYPE arr_uv48 IS ARRAY (natural RANGE <>) OF unsigned(47 DOWNTO 0); + TYPE arr_uv24 IS ARRAY (natural RANGE <>) OF unsigned(23 DOWNTO 0); + TYPE arr_uv40 IS ARRAY (natural RANGE <>) OF unsigned(39 DOWNTO 0); + TYPE arr_int9 IS ARRAY (natural RANGE <>) OF integer RANGE -256 TO 255; + TYPE arr_uint12 IS ARRAY (natural RANGE <>) OF uint12; + TYPE arr_frac IS ARRAY (natural RANGE <>) OF unsigned(11 DOWNTO 0); + TYPE arr_div IS ARRAY (natural RANGE <>) OF unsigned(20 DOWNTO 0); + + ---------------------------------------------------------- + -- Input image + SIGNAL i_pvs,i_pfl,i_pde,i_pce : std_logic; + SIGNAL i_ppix : type_pix; + SIGNAL i_freeze : std_logic; + SIGNAL i_bob_deint : std_logic; + SIGNAL i_count : unsigned(2 DOWNTO 0); + SIGNAL i_hsize,i_hmin,i_hmax,i_hcpt : uint12; + SIGNAL i_hrsize,i_vrsize : uint12; + SIGNAL i_himax,i_vimax : uint12; + SIGNAL i_vsize,i_vmaxmin,i_vmin,i_vmax,i_vcpt : uint12; + SIGNAL i_iauto : std_logic; + SIGNAL i_mode : unsigned(4 DOWNTO 0); + SIGNAL i_format : unsigned(1 DOWNTO 0); + SIGNAL i_ven,i_sof : std_logic; + SIGNAL i_wr : std_logic; + SIGNAL i_divstart,i_divrun : std_logic; + SIGNAL i_de_pre,i_vs_pre,i_fl_pre : std_logic; + SIGNAL i_de_delay : natural RANGE 0 TO 31; + SIGNAL i_intercnt : natural RANGE 0 TO 3; + SIGNAL i_inter,i_half,i_flm : std_logic; + SIGNAL i_wfl : std_logic_vector(2 DOWNTO 0); + SIGNAL i_write,i_wreq,i_alt,i_line,i_wline,i_wline_mem : std_logic; + SIGNAL i_walt,i_walt_mem,i_wreq_mem : std_logic; + SIGNAL i_wdelay : natural RANGE 0 TO 7; + SIGNAL i_push,i_pushend,i_pushend2 : std_logic; + SIGNAL i_eol : std_logic; + SIGNAL i_pushhead,i_pushhead2,i_pushhead3 : std_logic; + SIGNAL i_hburst,i_hbcpt : natural RANGE 0 TO 31; + SIGNAL i_shift : unsigned(0 TO 119) := (OTHERS =>'0'); + SIGNAL i_head : unsigned(127 DOWNTO 0); + SIGNAL i_acpt : natural RANGE 0 TO 15; + SIGNAL i_dpram : arr_dw(0 TO BLEN*2-1); + ATTRIBUTE ramstyle OF i_dpram : SIGNAL IS "no_rw_check"; + SIGNAL i_endframe0,i_endframe1,i_vss : std_logic; + SIGNAL i_wad : natural RANGE 0 TO BLEN*2-1; + SIGNAL i_dw : unsigned(N_DW-1 DOWNTO 0); + SIGNAL i_adrs,i_adrsi,i_wadrs,i_wadrs_mem : unsigned(31 DOWNTO 0); + SIGNAL i_reset_na : std_logic; + SIGNAL i_hnp,i_vnp : std_logic; + SIGNAL i_mem : arr_pix(0 TO IHRES-1); -- Downscale line buffer + ATTRIBUTE ramstyle OF i_mem : SIGNAL IS "no_rw_check"; + SIGNAL i_ohsize,i_ovsize : uint12; + SIGNAL i_vdivi : unsigned(12 DOWNTO 0); + SIGNAL i_vdivr : unsigned(24 DOWNTO 0); + SIGNAL i_div : unsigned(16 DOWNTO 0); + SIGNAL i_dir : unsigned(11 DOWNTO 0); + SIGNAL i_h_frac,i_v_frac : unsigned(11 DOWNTO 0); + SIGNAL i_hacc,i_vacc : uint13; + SIGNAL i_hdown,i_vdown : std_logic; + SIGNAL i_divcpt : natural RANGE 0 TO 36; + SIGNAL i_lwad,i_lrad : natural RANGE 0 TO OHRESH-1; + SIGNAL i_lwr,i_bil : std_logic; + SIGNAL i_ldw,i_ldrm : type_pix; + SIGNAL i_hpixp,i_hpix0,i_hpix1,i_hpix2,i_hpix3,i_hpix4 : type_pix; + SIGNAL i_hpix,i_pix : type_pix; + SIGNAL i_hnp1,i_hnp2,i_hnp3,i_hnp4 : std_logic; + SIGNAL i_ven1,i_ven2,i_ven3,i_ven4,i_ven5,i_ven6 : std_logic; + + ---------------------------------------------------------- + -- Avalon + TYPE type_avl_state IS (sIDLE,sWRITE,sREAD); + SIGNAL avl_state : type_avl_state; + SIGNAL avl_write_i,avl_write_sync,avl_write_sync2 : std_logic; + SIGNAL avl_read_i,avl_read_sync,avl_read_sync2 : std_logic; + SIGNAL avl_read_pulse,avl_write_pulse : std_logic; + SIGNAL avl_read_sr,avl_write_sr,avl_read_clr,avl_write_clr : std_logic; + SIGNAL avl_rad,avl_rad_c,avl_wad : natural RANGE 0 TO 2*BLEN-1; + SIGNAL avl_walt,avl_wline,avl_rline : std_logic; + SIGNAL avl_dw,avl_dr : unsigned(N_DW-1 DOWNTO 0); + SIGNAL avl_wr : std_logic; + SIGNAL avl_readdataack,avl_readack : std_logic; + SIGNAL avl_radrs,avl_wadrs : unsigned(31 DOWNTO 0); + SIGNAL avl_i_offset0,avl_o_offset0 : unsigned(31 DOWNTO 0); + SIGNAL avl_i_offset1,avl_o_offset1 : unsigned(31 DOWNTO 0); + SIGNAL avl_reset_na : std_logic; + SIGNAL avl_o_vs_sync,avl_o_vs : std_logic; + SIGNAL avl_fb_ena : std_logic; + + FUNCTION buf_next(a,b : natural RANGE 0 TO 2; freeze : std_logic := '0') RETURN natural IS + BEGIN + IF (freeze='1') THEN RETURN a; END IF; + IF (a=0 AND b=1) OR (a=1 AND b=0) THEN RETURN 2; END IF; + IF (a=1 AND b=2) OR (a=2 AND b=1) THEN RETURN 0; END IF; + RETURN 1; + END FUNCTION; + FUNCTION buf_offset(b : natural RANGE 0 TO 2; + base : unsigned(31 DOWNTO 0); + size : unsigned(31 DOWNTO 0)) RETURN unsigned IS + BEGIN + IF b=1 THEN RETURN base+size; END IF; + IF b=2 THEN RETURN base+(size(30 DOWNTO 0) & '0'); END IF; + RETURN base; + END FUNCTION; + + ---------------------------------------------------------- + -- Output + SIGNAL o_run : std_logic; + SIGNAL o_freeze : std_logic; + SIGNAL o_bob_deint : std_logic; + SIGNAL o_iwfl : std_logic_vector(2 DOWNTO 0); + SIGNAL o_mode,o_hmode,o_vmode : unsigned(4 DOWNTO 0); + SIGNAL o_format : unsigned(5 DOWNTO 0); + SIGNAL o_fb_pal_dr : unsigned(23 DOWNTO 0); + SIGNAL o_fb_pal_dr2 : unsigned(23 DOWNTO 0); + SIGNAL o_fb_pal_dr_x2 : unsigned(47 DOWNTO 0); + SIGNAL pal_idx: unsigned(7 DOWNTO 0); + SIGNAL pal_idx_lsb: std_logic; + SIGNAL pal1_mem : arr_uv48(0 TO 127); + SIGNAL pal2_mem : arr_uv24(0 TO 255); + ATTRIBUTE ramstyle of pal1_mem : signal is "no_rw_check"; + ATTRIBUTE ramstyle of pal2_mem : signal is "no_rw_check"; + SIGNAL o_htotal,o_hsstart,o_hsend : uint12; + SIGNAL o_hmin,o_hmax,o_hdisp,o_v_hmin_adj : uint12; + SIGNAL o_hsize,o_vsize : uint12; + SIGNAL o_vtotal,o_vsstart,o_vsend : uint12; + SIGNAL o_vrr,o_isync,o_isync2 : std_logic; + SIGNAL o_vrr_sync,o_vrr_sync2 : boolean; + SIGNAL o_vrr_min,o_vrr_min2 : boolean; + SIGNAL o_vrr_max,o_vrr_max2 : boolean; + SIGNAL o_vcpt_sync,o_vcpt_sync2, o_vrrmax : uint12; + SIGNAL o_sync, o_sync_max : boolean; + SIGNAL o_vmin,o_vmax,o_vdisp : uint12; + SIGNAL o_divcpt : natural RANGE 0 TO 36; + SIGNAL o_iendframe0,o_iendframe02,o_iendframe1,o_iendframe12 : std_logic; + SIGNAL o_bufup0,o_bufup1,o_inter : std_logic; + SIGNAL o_ibuf0,o_ibuf1,o_obuf0,o_obuf1 : natural RANGE 0 TO 2; + TYPE enum_o_state IS (sDISP,sHSYNC,sREAD,sWAITREAD); + SIGNAL o_state : enum_o_state; + TYPE enum_o_copy IS (sWAIT,sSHIFT,sCOPY); + SIGNAL o_copy : enum_o_copy; + SIGNAL o_pshift : natural RANGE 0 TO 15; + SIGNAL o_readack,o_readack_sync,o_readack_sync2 : std_logic; + SIGNAL o_readdataack,o_readdataack_sync,o_readdataack_sync2 : std_logic; + SIGNAL o_copyv : unsigned(0 TO 14); + SIGNAL o_adrs : unsigned(31 DOWNTO 0); -- Avalon address + SIGNAL o_adrs_pre : natural RANGE 0 TO 2**24-1; + SIGNAL o_stride : unsigned(13 DOWNTO 0); + SIGNAL o_adrsa,o_adrsb,o_rline : std_logic; + SIGNAL o_ad,o_ad1,o_ad2,o_ad3 : natural RANGE 0 TO 2*BLEN-1; + SIGNAL o_adturn : std_logic; + SIGNAL o_dr : unsigned(N_DW-1 DOWNTO 0); + SIGNAL o_shift : unsigned(0 TO N_DW+15); + SIGNAL o_sh,o_sh1,o_sh2,o_sh3,o_sh4 : std_logic; + SIGNAL o_reset_na : std_logic; + SIGNAL o_dpram : arr_dw(0 TO BLEN*2-1); + ATTRIBUTE ramstyle OF o_dpram : SIGNAL IS "no_rw_check"; + SIGNAL o_line0,o_line1,o_line2,o_line3 : arr_pix(0 TO OHRESL-1); + SIGNAL o_linf0,o_linf1,o_linf2,o_linf3 : arr_pix(0 TO OHRESM-1); + + ATTRIBUTE ramstyle OF o_line0 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_line1 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_line2 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_line3 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_linf0 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_linf1 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_linf2 : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_linf3 : SIGNAL IS "no_rw_check"; + SIGNAL o_wadl,o_radl0,o_radl1,o_radl2,o_radl3 : natural RANGE 0 TO OHRESH-1; + SIGNAL o_ldr0,o_ldr1,o_ldr2,o_ldr3,o_ldw : type_pix; + SIGNAL o_ler0,o_ler1,o_ler2,o_ler3 : type_pix; + SIGNAL o_lex0,o_lex1,o_lex2,o_lex3 : std_logic; + SIGNAL o_wr : unsigned(3 DOWNTO 0); + SIGNAL o_hcpt,o_vcpt,o_vcpt_pre,o_vcpt_pre2,o_vcpt_pre3,o_vcpt2 : uint12; + SIGNAL o_ihsize,o_ihsizem,o_ivsize : uint12; + SIGNAL o_ihsize_temp, o_ihsize_temp2 : natural RANGE 0 TO 32767; + + SIGNAL o_vfrac : unsigned(11 DOWNTO 0); + SIGNAL o_hfrac : arr_frac(0 TO 9); + ATTRIBUTE ramstyle OF o_hfrac : SIGNAL IS "logic"; -- avoid blockram shift register + + SIGNAL o_hacc,o_hacc_ini,o_hacc_next,o_vacc,o_vacc_next,o_vacc_ini : natural RANGE 0 TO 4*OHRESH-1; + SIGNAL o_hsv,o_vsv,o_dev,o_pev,o_end : unsigned(0 TO 11); + SIGNAL o_hsp,o_vss : std_logic; + SIGNAL o_vcarrym,o_prim : boolean; + SIGNAL o_read,o_read_pre : std_logic; + SIGNAL o_readlev,o_copylev : natural RANGE 0 TO 2; + SIGNAL o_hburst,o_hbcpt : natural RANGE 0 TO 31; + SIGNAL o_fload : natural RANGE 0 TO 3; + SIGNAL o_acpt,o_acpt1,o_acpt2,o_acpt3,o_acpt4 : natural RANGE 0 TO 15; -- Alternance pixels FIFO + SIGNAL o_dshi : natural RANGE 0 TO 3; + SIGNAL o_first,o_last,o_last1,o_last2 : std_logic; + SIGNAL o_lastt1,o_lastt2,o_lastt3,o_lastt4 : std_logic; + SIGNAL o_alt,o_altx : unsigned(3 DOWNTO 0); + SIGNAL o_hdown,o_vdown : std_logic; + SIGNAL o_primv,o_lastv,o_bibv : unsigned(0 TO 2); + TYPE arr_uint4 IS ARRAY (natural RANGE <>) OF natural RANGE 0 TO 15; + SIGNAL o_off : arr_uint4(0 TO 2); + SIGNAL o_bibu : std_logic :='0'; + SIGNAL o_dcptv : arr_uint12(13 TO 14); + SIGNAL o_dcpt_clr, o_dcpt_inc : std_logic; + SIGNAL o_dcptv_clr, o_dcptv_inc : std_logic_vector(1 TO 12); + SIGNAL o_hpixs,o_hpix0,o_hpix1,o_hpix2,o_hpix3 : type_pix; + SIGNAL o_hpixq : arr_pixq(2 TO 8); + ATTRIBUTE ramstyle OF o_hpixq : SIGNAL IS "logic"; -- avoid blockram shift register + SIGNAL o_vpixq, o_vpixq_pre : arr_pix(0 TO 3); + SIGNAL o_vpix_outer : arr_pix(0 TO 2); + SIGNAL o_vpix_inner : arr_pix(0 TO 6); + + SIGNAL o_vpe : std_logic; + SIGNAL o_div : arr_div(0 TO 2); --uint12; + SIGNAL o_dir : arr_frac(0 TO 2); + ATTRIBUTE ramstyle OF o_div, o_dir : SIGNAL IS "logic"; -- avoid blockram shift register + SIGNAL o_vdivi : unsigned(12 DOWNTO 0); + SIGNAL o_vdivr : unsigned(24 DOWNTO 0); + SIGNAL o_divstart : std_logic; + SIGNAL o_divrun : std_logic; + SIGNAL o_hacpt,o_vacpt : unsigned(11 DOWNTO 0); + SIGNAL o_vacptl : unsigned(1 DOWNTO 0); + signal o_newres : integer range 0 to 3; + + ----------------------------------------------------------------------------- + FUNCTION shift_ishift(shift : unsigned(0 TO 119); + pix : type_pix; + format : unsigned(1 DOWNTO 0)) RETURN unsigned IS + BEGIN + CASE format IS + WHEN "01" => -- 24bpp + RETURN shift(24 TO 119) & pix.r & pix.g & pix.b; + WHEN "10" => -- 32bpp + RETURN shift(32 TO 119) & pix.r & pix.g & pix.b & x"00"; + WHEN OTHERS => -- 16bpp 565 + RETURN shift(16 TO 119) & + pix.g(4 DOWNTO 2) & pix.r(7 DOWNTO 3) & + pix.b(7 DOWNTO 3) & pix.g(7 DOWNTO 5); + END CASE; + END FUNCTION; + + FUNCTION shift_ipack(i_dw : unsigned(N_DW-1 DOWNTO 0); + acpt : natural RANGE 0 TO 15; + shift : unsigned(0 TO 119); + pix : type_pix; + format : unsigned(1 DOWNTO 0)) RETURN unsigned IS + VARIABLE dw : unsigned(N_DW-1 DOWNTO 0); + BEGIN + dw:=i_dw; + CASE format IS + WHEN "01" => -- 24bpp + IF N_DW=128 THEN + IF acpt=5 THEN dw:=shift(0 TO 119) & pix.r; + ELSIF acpt=10 THEN dw:=shift(8 TO 119) & pix.r & pix.g; + ELSIF acpt=15 THEN dw:=shift(16 TO 119) & pix.r & pix.g & pix.b; + END IF; + ELSE -- N_DW=64 + IF (acpt MOD 8)=2 THEN dw:=shift(72 TO 119) & pix.r & pix.g; + ELSIF (acpt MOD 8)=5 THEN dw:=shift(64 TO 119) & pix.r; + ELSIF (acpt MOD 8)=7 THEN dw:=shift(80 TO 119) & pix.r & pix.g & pix.b; + END IF; + END IF; + WHEN "10" => -- 32bpp + IF (N_DW=128 AND (acpt MOD 4)=3) OR (N_DW=64 AND (acpt MOD 8)=7) THEN + dw:=shift(128-N_DW+24 TO 119) & pix.r & pix.g & pix.b & x"00"; + END IF; + WHEN OTHERS => -- 16bpp 565 + IF (N_DW=128 AND (acpt MOD 8)=7) OR (N_DW=64 AND (acpt MOD 4)=3) THEN + dw:=shift(128-N_DW+8 TO 119) & pix.g(4 DOWNTO 2) & pix.r(7 DOWNTO 3) & + pix.b(7 DOWNTO 3) & pix.g(7 DOWNTO 5); + END IF; + END CASE; + RETURN dw; + END FUNCTION; + + FUNCTION shift_inext (acpt : natural RANGE 0 TO 15; + format : unsigned(1 DOWNTO 0)) RETURN boolean IS + BEGIN + CASE format IS + WHEN "01" => -- 24bpp + RETURN (N_DW=128 AND (acpt=5 OR acpt=10 OR acpt=15)) OR + (N_DW=64 AND ((acpt MOD 8)=2 OR (acpt MOD 8)=5 OR (acpt MOD 8)=7)); + WHEN "10" => -- 32bpp + RETURN (N_DW=128 AND ((acpt MOD 4)=3)) OR + (N_DW=64 AND ((acpt MOD 2)=1)); + WHEN OTHERS => -- 16bpp + RETURN (N_DW=128 AND ((acpt MOD 8)=7)) OR + (N_DW=64 AND ((acpt MOD 4)=3)); + END CASE; + END FUNCTION; + + FUNCTION shift_opack(acpt : natural RANGE 0 TO 15; + shift : unsigned(0 TO N_DW+15); + dr : unsigned(N_DW-1 DOWNTO 0); + format : unsigned(5 DOWNTO 0)) RETURN unsigned IS + VARIABLE shift_v : unsigned(0 TO N_DW+15); + BEGIN + CASE format(2 DOWNTO 0) IS + WHEN "011" => -- 8bpp + IF (N_DW=128 AND acpt=0) OR (N_DW=64 AND (acpt MOD 8)=0) THEN + shift_v:=dr & dr(15 DOWNTO 0); + ELSE + shift_v:=shift(8 TO N_DW+15) & dr(7 DOWNTO 0); + END IF; + + WHEN "100" => -- 16bpp + IF (N_DW=128 AND (acpt MOD 8)=0) OR (N_DW=64 AND (acpt MOD 4)=0) THEN + shift_v:=dr & dr(15 DOWNTO 0); + ELSE + shift_v:=shift(16 TO N_DW+15) & dr(15 DOWNTO 0); + END IF; + + WHEN "101" => -- 24bpp + IF N_DW=128 THEN + IF acpt=0 THEN + shift_v:=dr & dr(15 DOWNTO 0); + ELSIF acpt=5 THEN + shift_v:=shift(24 TO 31) & dr & dr(7 DOWNTO 0); + ELSIF acpt=10 THEN + shift_v:=shift(24 TO 39) & dr; + ELSE + shift_v:=shift(24 TO N_DW+15) & dr(23 DOWNTO 0); + END IF; + ELSE -- N_DW=64 + IF (acpt MOD 8)=0 THEN + shift_v:=dr & dr(15 DOWNTO 0); + ELSIF (acpt MOD 8)=2 THEN + shift_v:=shift(24 TO 39) & dr; + ELSIF (acpt MOD 8)=5 THEN + shift_v:=shift(24 TO 31) & dr & dr(7 DOWNTO 0); + ELSE + shift_v:=shift(24 TO N_DW+15) & dr(23 DOWNTO 0); + END IF; + END IF; + WHEN OTHERS => -- 32bpp + IF (N_DW=128 AND (acpt MOD 4)=0) OR (N_DW=64 AND (acpt MOD 2)=0) THEN + shift_v:=dr & dr(15 DOWNTO 0); + ELSE + shift_v:=shift(32 TO N_DW+15) & dr(31 DOWNTO 0); + END IF; + END CASE; + RETURN shift_v; + END FUNCTION; + + FUNCTION shift_onext (acpt : natural RANGE 0 TO 15; + format : unsigned(5 DOWNTO 0)) RETURN boolean IS + BEGIN + CASE format(2 DOWNTO 0) IS + WHEN "011" => -- 8bpp + RETURN (N_DW=128 AND acpt=0) OR + (N_DW=64 AND ((acpt MOD 8)=0)); + WHEN "100" => -- 16bpp + RETURN (N_DW=128 AND ((acpt MOD 8)=0)) OR + (N_DW=64 AND ((acpt MOD 4)=0)); + WHEN "101" => -- 24bpp + RETURN (N_DW=128 AND (acpt=0 OR acpt=5 OR acpt=10)) OR + (N_DW=64 AND ((acpt MOD 8)=0 OR (acpt MOD 8)=2 OR (acpt MOD 8)=5)); + WHEN OTHERS => -- 32bpp + RETURN (N_DW=128 AND ((acpt MOD 4)=0)) OR + (N_DW=64 AND ((acpt MOD 2)=0)); + END CASE; + END FUNCTION; + + FUNCTION shift_opix (shift : unsigned(0 TO N_DW+15); + format : unsigned(5 DOWNTO 0)) RETURN type_pix IS + BEGIN + CASE format(3 DOWNTO 0) IS + WHEN "0100" => -- 16bpp 565 + RETURN (b=>shift(8 TO 12) & shift(8 TO 10), + g=>shift(13 TO 15) & shift(0 TO 2) & shift(13 TO 14), + r=>shift(3 TO 7) & shift(3 TO 5)); + WHEN "1100" => -- 16bpp 1555 + RETURN (b=>shift(9 TO 13) & shift(9 TO 11), + g=>shift(14 TO 15) & shift(0 TO 2) & shift(14 TO 15) & shift(0), + r=>shift(3 TO 7) & shift(3 TO 5)); + WHEN "0101" | "0110" => -- 24bpp / 32bpp + RETURN (r=>shift(0 TO 7),g=>shift(8 TO 15),b=>shift(16 TO 23)); + + WHEN OTHERS => + RETURN (r=>shift(0 TO 7),g=>shift(8 TO 15),b=>shift(16 TO 23)); + + END CASE; + END FUNCTION; + + FUNCTION pixoffset(adrs : unsigned(31 DOWNTO 0); + format : unsigned (5 DOWNTO 0)) RETURN natural IS + BEGIN + CASE format(2 DOWNTO 0) IS + WHEN "011" => -- 8bbp + RETURN to_integer(adrs(NB_LA-1 DOWNTO 0)); + WHEN "100" => -- 16bpp 565 + RETURN to_integer(adrs(NB_LA-1 DOWNTO 1)); + WHEN OTHERS => -- 32bpp + RETURN to_integer(adrs(NB_LA-1 DOWNTO 2)); + END CASE; + END FUNCTION; + + FUNCTION swap(d : unsigned(N_DW-1 DOWNTO 0)) RETURN unsigned IS + VARIABLE e : unsigned(N_DW-1 DOWNTO 0); + BEGIN + IF BYTESWAP THEN + FOR i IN 0 TO N_DW/8-1 LOOP + e(i*8+7 DOWNTO i*8):=d(N_DW-i*8-1 DOWNTO N_DW-i*8-8); + END LOOP; + RETURN e; + ELSE + RETURN d; + END IF; + END FUNCTION swap; + + ----------------------------------------------------------------------------- + FUNCTION altx (a : unsigned(1 DOWNTO 0)) RETURN unsigned IS + BEGIN + CASE a IS + WHEN "00" => RETURN "0001"; + WHEN "01" => RETURN "0010"; + WHEN "10" => RETURN "0100"; + WHEN OTHERS => RETURN "1000"; + END CASE; + END FUNCTION; + + ----------------------------------------------------------------------------- + FUNCTION bound(a : unsigned; + s : natural) RETURN unsigned IS + BEGIN + IF a(a'left)='1' THEN + RETURN x"00"; + ELSIF a(a'left DOWNTO s)/=0 THEN + RETURN x"FF"; + ELSE + RETURN a(s-1 DOWNTO s-8); + END IF; + END FUNCTION bound; + + ----------------------------------------------------------------------------- + -- Nearest + FUNCTION near_frac(f : unsigned) RETURN unsigned IS + VARIABLE x : unsigned(FRAC-1 DOWNTO 0); + BEGIN + x:=(OTHERS =>f(f'left)); + RETURN x; + END FUNCTION; + + SIGNAL o_h_near_frac,o_v_near_frac : unsigned(FRAC-1 DOWNTO 0); + SIGNAL o_h_bil_frac,o_v_bil_frac : unsigned(FRAC-1 DOWNTO 0); + SIGNAL o_h_bil_pix,o_v_bil_pix : type_pix; + + ----------------------------------------------------------------------------- + -- Nearest + Bilinear + Sharp Bilinear + FUNCTION bil_frac(f : unsigned) RETURN unsigned IS + BEGIN + RETURN f(f'left DOWNTO f'left+1-FRAC); + END FUNCTION; + + TYPE type_bil_t IS RECORD + r,g,b : unsigned(8+FRAC DOWNTO 0); + END RECORD; + + FUNCTION bil_calc(f : unsigned(FRAC-1 DOWNTO 0); + p : arr_pix(0 TO 3)) RETURN type_bil_t IS + VARIABLE fp,fn : unsigned(FRAC DOWNTO 0); + VARIABLE u : unsigned(8+FRAC DOWNTO 0); + VARIABLE x : type_bil_t; + CONSTANT Z : unsigned(FRAC-1 DOWNTO 0):=(OTHERS =>'0'); + BEGIN + fp:=('0' & f) + (Z & f(FRAC-1)); + fn:=('1' & Z) - fp; + u:=p(2).r * fp + p(1).r * fn; + x.r:=u; + u:=p(2).g * fp + p(1).g * fn; + x.g:=u; + u:=p(2).b * fp + p(1).b * fn; + x.b:=u; + RETURN x; + END FUNCTION; + + FUNCTION near_calc(f : unsigned(FRAC-1 DOWNTO 0); + p : arr_pix(0 TO 3)) RETURN type_bil_t IS + VARIABLE fp,fn : unsigned(FRAC DOWNTO 0); + VARIABLE u : unsigned(8+FRAC DOWNTO 0); + VARIABLE x : type_bil_t; + CONSTANT Z : unsigned(FRAC-1 DOWNTO 0):=(OTHERS =>'0'); + BEGIN + IF f(FRAC-1)='0' THEN + x.r := '0' & p(1).r & Z; + x.g := '0' & p(1).g & Z; + x.b := '0' & p(1).b & Z; + ELSE + x.r := '0' & p(2).r & Z; + x.g := '0' & p(2).g & Z; + x.b := '0' & p(2).b & Z; + END IF; + RETURN x; + END FUNCTION; + + SIGNAL o_h_bil_t,o_v_bil_t : type_bil_t; + SIGNAL o_h_near_t,o_v_near_t : type_bil_t; + SIGNAL i_h_bil_t : type_bil_t; + + ----------------------------------------------------------------------------- + -- Sharp Bilinear + -- <0.5 : x*x*x*4 + -- >0.5 : 1 - (1-x)*(1-x)*(1-x)*4 + + TYPE type_sbil_tt IS RECORD + f : unsigned(FRAC-1 DOWNTO 0); + s : unsigned(FRAC-1 DOWNTO 0); + END RECORD; + + SIGNAL o_h_sbil_t,o_v_sbil_t : type_sbil_tt; + + FUNCTION sbil_frac1(f : unsigned(11 DOWNTO 0)) RETURN type_sbil_tt IS + VARIABLE u : unsigned(FRAC-1 DOWNTO 0); + VARIABLE v : unsigned(2*FRAC-1 DOWNTO 0); + VARIABLE x : type_sbil_tt; + BEGIN + IF f(11)='0' THEN + u:=f(11 DOWNTO 12-FRAC); + ELSE + u:=NOT f(11 DOWNTO 12-FRAC); + END IF; + v:=u*u; + x.f:=u; + x.s:=v(2*FRAC-2 DOWNTO FRAC-1); + RETURN x; + END FUNCTION; + + FUNCTION sbil_frac2(f : unsigned(11 DOWNTO 0); + t : type_sbil_tt) RETURN unsigned IS + VARIABLE v : unsigned(2*FRAC-1 DOWNTO 0); + BEGIN + v:=t.f*t.s; + IF f(11)='0' THEN + RETURN v(2*FRAC-2 DOWNTO FRAC-1); + ELSE + RETURN NOT v(2*FRAC-2 DOWNTO FRAC-1); + END IF; + END FUNCTION; + + ----------------------------------------------------------------------------- + -- Bicubic + TYPE type_bic_abcd IS RECORD + a : unsigned(7 DOWNTO 0); -- 0.8 + b : signed(8 DOWNTO 0); -- 0.9 + c : signed(11 DOWNTO 0); -- 3.9 + d : signed(10 DOWNTO 0); -- 2.9 + xx : signed(8 DOWNTO 0); -- X.X 1.8 + END RECORD; + TYPE type_bic_pix_abcd IS RECORD + r,g,b : type_bic_abcd; + END RECORD; + TYPE type_bic_tt1 IS RECORD -- Intermediate result + r_bx,g_bx,b_bx : signed(8 DOWNTO 0); -- B.X 1.8 + r_cxx,g_cxx,b_cxx : signed(11 DOWNTO 0); -- C.XX 3.9 + r_dxx,g_dxx,b_dxx : signed(10 DOWNTO 0); -- D.XX 2.9 + END RECORD; + TYPE type_bic_tt2 IS RECORD -- Intermediate result + r_abxcxx,g_abxcxx,b_abxcxx : signed(9 DOWNTO 0); -- A + B.X + C.XX 2.8 + r_dxxx,g_dxxx,b_dxxx : signed(9 DOWNTO 0); -- D.X.X.X 2.8 + END RECORD; + + ---------------------------------------------------------- + -- Y = A + B.X + C.X.X + D.X.X.X = A + X.(B + X.(C + X.D)) + -- A = Y(0) 0 .. 1 unsigned + -- B = Y(1)/2 - Y(-1)/2 -1/2 .. +1/2 signed + -- C = Y(-1) - 5*Y(0)/2 + 2*Y(1) - Y(2)/2 -3 .. +3 signed + -- D = -Y(-1)/2 + 3*Y(0)/2 - 3*Y(1)/2 + Y(2)/2 -2 .. +2 signed + + FUNCTION bic_calc0(f : unsigned(11 DOWNTO 0); + pm,p0,p1,p2 : unsigned(7 DOWNTO 0)) RETURN type_bic_abcd IS + VARIABLE xx : signed(2*FRAC+1 DOWNTO 0); -- 2.(2*FRAC) + BEGIN + xx := signed('0' & f(11 DOWNTO 12-FRAC)) * + signed('0' & f(11 DOWNTO 12-FRAC)); -- 2.(2*FRAC) + RETURN type_bic_abcd'( + a=>p0,-- 0.8 + b=>signed(('0' & p1) - ('0' & pm)), -- 0.9 + c=>signed(("000" & pm & '0') - ("00" & p0 & "00") - ("0000" & p0) + + ("00" & p1 & "00") - ("0000" & p2)), -- 3.9 + d=>signed(("00" & p0 & '0') - ("00" & p1 & '0') - ("000" & p1) + + ("000" & p0) + ("000" & p2) - ("000" & pm)), -- 2.9 + xx=>xx(2*FRAC DOWNTO 2*FRAC-8)); -- 1.8 + END FUNCTION; + FUNCTION bic_calc0(f : unsigned(11 DOWNTO 0); + p : arr_pix(0 TO 3)) RETURN type_bic_pix_abcd IS + BEGIN + RETURN type_bic_pix_abcd'( r=>bic_calc0(f,p(0).r,p(1).r,p(2).r,p(3).r), + g=>bic_calc0(f,p(0).g,p(1).g,p(2).g,p(3).g), + b=>bic_calc0(f,p(0).b,p(1).b,p(2).b,p(3).b)); + END FUNCTION; + + ---------------------------------------------------------- + -- Calc : B.X, C.XX, D.XX + FUNCTION bic_calc1(f : unsigned(11 DOWNTO 0); + abcd : type_bic_pix_abcd) RETURN type_bic_tt1 IS + VARIABLE t : type_bic_tt1; + VARIABLE bx : signed(9+FRAC DOWNTO 0); -- 1.(FRAC+9) + VARIABLE cxx : signed(20 DOWNTO 0); -- 4.17 + VARIABLE dxx : signed(19 DOWNTO 0); -- 3.17 + BEGIN + bx := abcd.r.b * signed('0' & f(11 DOWNTO 12-FRAC)); -- 1.(FRAC+9) + t.r_bx:=bx(9+FRAC DOWNTO 9+FRAC-8); -- 1.8 + cxx:= abcd.r.c * abcd.r.xx; -- 3.9 * 1.8 = 4.17 + t.r_cxx:=cxx(19 DOWNTO 8); -- 3.9 + dxx:= abcd.r.d * abcd.r.xx; -- 2.9 * 1.8 = 3.17 + t.r_dxx:=dxx(18 DOWNTO 8); -- 2.9 + bx := abcd.g.b * signed('0' & f(11 DOWNTO 12-FRAC)); -- 1.(FRAC+9) + t.g_bx:=bx(9+FRAC DOWNTO 9+FRAC-8); -- 1.8 + cxx:= abcd.g.c * abcd.g.xx; -- 3.9 * 1.8 = 4.17 + t.g_cxx:=cxx(19 DOWNTO 8); -- 3.9 + dxx:= abcd.g.d * abcd.g.xx; -- 2.9 * 1.8 = 3.17 + t.g_dxx:=dxx(18 DOWNTO 8); -- 2.9 + bx := abcd.b.b * signed('0' & f(11 DOWNTO 12-FRAC)); -- 1.(FRAC+9) + t.b_bx:=bx(9+FRAC DOWNTO 9+FRAC-8); -- 1.8 + cxx:= abcd.b.c * abcd.b.xx; -- 3.9 * 1.8 = 4.17 + t.b_cxx:=cxx(19 DOWNTO 8); -- 3.9 + dxx:= abcd.b.d * abcd.b.xx; -- 2.9 * 1.8 = 3.17 + t.b_dxx:=dxx(18 DOWNTO 8); -- 2.9 + RETURN t; + END FUNCTION; + + ---------------------------------------------------------- + -- Calc A + BX + CXX , X.DXX + FUNCTION bic_calc2(f : unsigned(11 DOWNTO 0); + t : type_bic_tt1; + abcd : type_bic_pix_abcd) RETURN type_bic_tt2 IS + VARIABLE u : type_bic_tt2; + VARIABLE x : signed(11+FRAC DOWNTO 0); -- 3.(9+FRAC) + BEGIN + u.r_abxcxx:=(t.r_bx(8) & t.r_bx) + ("00" & signed(abcd.r.a)) + t.r_cxx(10 DOWNTO 1); -- 2.8 + u.g_abxcxx:=(t.g_bx(8) & t.g_bx) + ("00" & signed(abcd.g.a)) + t.g_cxx(10 DOWNTO 1); -- 2.8 + u.b_abxcxx:=(t.b_bx(8) & t.b_bx) + ("00" & signed(abcd.b.a)) + t.b_cxx(10 DOWNTO 1); -- 2.8 + + x:=t.r_dxx * signed('0' & f(11 DOWNTO 12-FRAC)); --2.9 * 1.FRAC =3.(9+FRAC) + u.r_dxxx:=x(10+FRAC DOWNTO 9+FRAC-8); -- 2.8 + x:=t.g_dxx * signed('0' & f(11 DOWNTO 12-FRAC)); --2.9 * 1.FRAC =3.(9+FRAC) + u.g_dxxx:=x(10+FRAC DOWNTO 9+FRAC-8); -- 2.8 + x:=t.b_dxx * signed('0' & f(11 DOWNTO 12-FRAC)); --2.9 * 1.FRAC =3.(9+FRAC) + u.b_dxxx:=x(10+FRAC DOWNTO 9+FRAC-8); -- 2.8 + RETURN u; + END FUNCTION; + + ---------------------------------------------------------- + -- Calc (A + BX + CXX) + (DXXX) + FUNCTION bic_calc3(f : unsigned(11 DOWNTO 0); + t : type_bic_tt2; + abcd : type_bic_pix_abcd) RETURN type_pix IS + VARIABLE x : type_pix; + VARIABLE v : signed(9 DOWNTO 0); -- 2.8 + BEGIN + v:=t.r_abxcxx + t.r_dxxx; + x.r:=bound(unsigned(v),8); + v:=t.g_abxcxx + t.g_dxxx; + x.g:=bound(unsigned(v),8); + v:=t.b_abxcxx + t.b_dxxx; + x.b:=bound(unsigned(v),8); + RETURN x; + END FUNCTION; + + ----------------------------------------------------------------------------- + SIGNAL o_h_bic_pix,o_v_bic_pix : type_pix; + SIGNAL o_h_bic_abcd1,o_h_bic_abcd2 : type_bic_pix_abcd; + SIGNAL o_v_bic_abcd1,o_v_bic_abcd2 : type_bic_pix_abcd; + SIGNAL o_h_bic_tt1,o_v_bic_tt1 : type_bic_tt1; + SIGNAL o_h_bic_tt2,o_v_bic_tt2 : type_bic_tt2; + + ----------------------------------------------------------------------------- + -- Polyphase + -- 2.7 + TYPE poly_phase_t IS RECORD + t0, t1, t2, t3 : signed(9 DOWNTO 0); + END RECORD; + + -- 4.14 + TYPE poly_phase_interp_t IS RECORD + t0, t1, t2, t3 : signed(17 DOWNTO 0); + END RECORD; + + -- 5.22 + TYPE type_poly_t IS RECORD + r0,r1,b0,b1,g0,g1 : signed(26 DOWNTO 0); + END RECORD; + + SIGNAL o_h_poly_mem : arr_uv40(0 TO 2**FRAC-1); + SIGNAL o_v_poly_mem : arr_uv40(0 TO 2**FRAC-1); + SIGNAL o_a_poly_mem : arr_uv40(0 TO 2**FRAC-1); + ATTRIBUTE ramstyle OF o_h_poly_mem : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_v_poly_mem : SIGNAL IS "no_rw_check"; + ATTRIBUTE ramstyle OF o_a_poly_mem : SIGNAL IS "no_rw_check"; + SIGNAL o_a_poly_addr, o_v_poly_addr : integer RANGE 0 TO 2**FRAC-1; + SIGNAL o_h_poly_phase_a,o_h_poly_phase_a2,o_h_poly_phase_a3, o_h_poly_phase_a4, o_h_poly_phase_a5 : poly_phase_t; + SIGNAL o_v_poly_phase_a,o_v_poly_phase_a2,o_v_poly_phase_a3, o_v_poly_phase_a4, o_v_poly_phase_a5 : poly_phase_t; + SIGNAL o_poly_phase_a, o_poly_phase_a2, o_poly_phase_a3 : poly_phase_t; + SIGNAL o_poly_phase_b,o_poly_phase_b2,o_poly_phase_b3 : poly_phase_t; + SIGNAL o_v_poly_phase, o_v_poly_phase2, o_h_poly_phase, o_poly_phase, o_poly_phase1 : poly_phase_interp_t; + SIGNAL o_v_poly_pix, o_h_poly_pix, o_h_lum_pix, o_v_lum_pix : type_pix; + SIGNAL o_poly_lum, o_poly_lum1 : unsigned(7 DOWNTO 0); + SIGNAL o_poly_lerp_ta, o_poly_lerp_tb : signed(9 DOWNTO 0); + SIGNAL o_h_poly_t,o_h_poly_t2,o_v_poly_t : type_poly_t; + + SIGNAL o_v_poly_adaptive, o_h_poly_adaptive, o_v_poly_use_adaptive, o_h_poly_use_adaptive : std_logic; + SIGNAL poly_wr_mode : std_logic_vector(2 DOWNTO 0); + SIGNAL poly_tdw : unsigned(39 DOWNTO 0); + SIGNAL poly_a2 : unsigned(FRAC-1 DOWNTO 0); + + FUNCTION poly_unpack(a : unsigned(39 DOWNTO 0)) RETURN poly_phase_t IS + VARIABLE v : poly_phase_t; + BEGIN + v.t0 := signed(a(39 DOWNTO 30)); + v.t1 := signed(a(29 DOWNTO 20)); + v.t2 := signed(a(19 DOWNTO 10)); + v.t3 := signed(a( 9 DOWNTO 0)); + RETURN v; + END FUNCTION; + + -- 6 DSP 18*18 + 18*18 + FUNCTION poly_calc(fi : poly_phase_interp_t; + p : arr_pix(0 TO 3)) RETURN type_poly_t IS + VARIABLE t : type_poly_t; + BEGIN + -- 3.15 * 1.8 = 4.23 + t.r0:=(fi.t0 * signed('0' & p(0).r) + + fi.t1 * signed('0' & p(1).r)); + t.r1:=(fi.t2 * signed('0' & p(2).r) + + fi.t3 * signed('0' & p(3).r)); + t.g0:=(fi.t0 * signed('0' & p(0).g) + + fi.t1 * signed('0' & p(1).g)); + t.g1:=(fi.t2 * signed('0' & p(2).g) + + fi.t3 * signed('0' & p(3).g)); + t.b0:=(fi.t0 * signed('0' & p(0).b) + + fi.t1 * signed('0' & p(1).b)); + t.b1:=(fi.t2 * signed('0' & p(2).b) + + fi.t3 * signed('0' & p(3).b)); + RETURN t; + END FUNCTION; + + FUNCTION poly_final(t : type_poly_t) RETURN type_pix IS + VARIABLE p : type_pix; + BEGIN + p.r:=bound(unsigned(t.r0(26 DOWNTO 8)+t.r1(26 DOWNTO 8)),15); + p.g:=bound(unsigned(t.g0(26 DOWNTO 8)+t.g1(26 DOWNTO 8)),15); + p.b:=bound(unsigned(t.b0(26 DOWNTO 8)+t.b1(26 DOWNTO 8)),15); + RETURN p; + END FUNCTION; + + -- 4 DSP 18*18 + 18*18 + FUNCTION poly_lerp(a : poly_phase_t; + b : poly_phase_t; + ta : SIGNED(9 DOWNTO 0); + tb : SIGNED(9 DOWNTO 0)) RETURN poly_phase_interp_t IS + VARIABLE v : poly_phase_interp_t; + VARIABLE t0,t1,t2,t3 : signed(19 DOWNTO 0); + BEGIN + -- 2.8 * 2.8 = 4.16 + t0 := (a.t0 * ta) + (b.t0 * tb); + t1 := (a.t1 * ta) + (b.t1 * tb); + t2 := (a.t2 * ta) + (b.t2 * tb); + t3 := (a.t3 * ta) + (b.t3 * tb); + + -- 4.16 -> 3.15 + v.t0 := t0(18 DOWNTO 1); + v.t1 := t1(18 DOWNTO 1); + v.t2 := t2(18 DOWNTO 1); + v.t3 := t3(18 DOWNTO 1); + + RETURN v; + END FUNCTION; + + FUNCTION poly_cvt(a : poly_phase_t) RETURN poly_phase_interp_t IS + VARIABLE v : poly_phase_interp_t; + BEGIN + v.t0 := resize(signed( a.t0 & "0000000" ), v.t0'length); + v.t1 := resize(signed( a.t1 & "0000000" ), v.t1'length); + v.t2 := resize(signed( a.t2 & "0000000" ), v.t2'length); + v.t3 := resize(signed( a.t3 & "0000000" ), v.t3'length); + RETURN v; + END FUNCTION; + + -- Nearest neighbor polyphase ceoffs + FUNCTION poly_nn(frac : unsigned(FRAC-1 DOWNTO 0)) RETURN poly_phase_t IS + VARIABLE v : poly_phase_t; + BEGIN + IF frac(frac'left)='0' THEN + v := (t1=>to_signed(256, 10), OTHERS=>to_signed(0, 10)); + ELSE + v := (t2=>to_signed(256, 10), OTHERS=>to_signed(0, 10)); + END IF; + RETURN v; + END FUNCTION; + + + FUNCTION poly_lum(p : type_pix) RETURN unsigned IS + VARIABLE v : UNSIGNED(7 DOWNTO 0); + BEGIN + -- 0.375 R + 0.5 G + 0.125 B + --v := ("00" & p.r(7 DOWNTO 2)) + ("000" & p.r(7 DOWNTO 3)) + ("0" & p.g(7 DOWNTO 1)) + ("000" & p.b(7 DOWNTO 3)); + + -- 0.25 R + 0.5 G + 0.25 B + -- v := ( ("00" & p.r(7 DOWNTO 2)) + ("0" & p.g(7 DOWNTO 1)) + ("00" & p.b(7 DOWNTO 2)) ); + + -- Just OR them all together + --v := (p.r OR p.g OR p.b); + + -- Maximum + IF p.r > p.g THEN + v := p.r; + ELSE + v := p.g; + END IF; + + IF p.b > v THEN + v := p.b; + END IF; + + -- 100% + -- v := "1111111"; + + RETURN v; + END FUNCTION; +BEGIN + + ----------------------------------------------------------------------------- + i_reset_na<='0' WHEN reset_na='0' ELSE '1' WHEN rising_edge(i_clk); + o_reset_na<='0' WHEN reset_na='0' ELSE '1' WHEN rising_edge(o_clk); + avl_reset_na<='0' WHEN reset_na='0' ELSE '1' WHEN rising_edge(avl_clk); + + ----------------------------------------------------------------------------- + -- Input pixels FIFO and shreg + InAT:PROCESS(i_clk,i_reset_na) IS + CONSTANT Z : unsigned(FRAC-1 DOWNTO 0):=(OTHERS =>'0'); + VARIABLE frac_v : unsigned(FRAC-1 DOWNTO 0); + VARIABLE div_v : unsigned(16 DOWNTO 0); + VARIABLE dir_v : unsigned(11 DOWNTO 0); + VARIABLE bil_t_v : type_bil_t; + BEGIN + IF i_reset_na='0' THEN + i_write<='0'; + + ELSIF rising_edge(i_clk) THEN + i_push<='0'; + i_pushhead<='0'; + i_eol<='0'; -- End Of Line + i_freeze <=freeze; -- + i_bob_deint <= bob_deint; + i_iauto<=iauto; -- + i_wreq<='0'; + i_wr<='0'; + + ------------------------------------------------------ + i_head(127 DOWNTO 120)<=x"01"; -- Header type + i_head(119 DOWNTO 112)<="000000" & i_format; -- Header format + i_head(111 DOWNTO 96)<="0000" & to_unsigned(N_BURST,12); -- Header size + i_head(95 DOWNTO 80)<=x"0000"; -- Attributes. TBD + i_head(80)<=i_inter; + i_head(81)<=i_flm; + i_head(82)<=i_hdown; + i_head(83)<=i_vdown; + i_head(84)<=i_mode(3); + i_head(87 DOWNTO 85)<=i_count; + i_head(79 DOWNTO 64)<="0000" & to_unsigned(i_hrsize,12); -- Image width + i_head(63 DOWNTO 48)<="0000" & to_unsigned(i_vrsize,12); -- Image height + i_head(47 DOWNTO 32)<= to_unsigned(N_BURST * i_hburst,16); -- Line Length. Bytes + i_head(31 DOWNTO 16)<="0000" & to_unsigned(i_ohsize,12); + i_head(15 DOWNTO 0) <="0000" & to_unsigned(i_ovsize,12); + + ------------------------------------------------------ + i_ppix<=(i_r,i_g,i_b); + i_pvs<=i_vs; + i_pfl<=i_fl; + i_pde<=i_de; + i_pce<=i_ce; + + ------------------------------------------------------ + IF i_pce='1' THEN + ---------------------------------------------------- + i_vs_pre<=i_pvs; + i_de_pre<=i_pde; + i_fl_pre<=i_pfl; + + ---------------------------------------------------- + -- Detect interlaced video + IF NOT INTER THEN + i_intercnt<=0; + ELSIF i_pfl/=i_fl_pre THEN + i_intercnt<=3; + ELSIF i_pvs='1' AND i_vs_pre='0' AND i_intercnt>0 THEN + i_intercnt<=i_intercnt-1; + END IF; + i_inter<=to_std_logic(i_intercnt>0); + + ---------------------------------------------------- + IF i_pvs='1' AND i_vs_pre='0' THEN + i_sof<='1'; + END IF; + + IF i_pde='1' AND i_de_pre='0' THEN + i_flm<=i_pfl; + END IF; + + IF i_pde='1' AND i_sof='1' THEN + i_sof<='0'; + i_vcpt<=0; + IF i_inter='1' AND i_flm='0' AND i_half='0' AND INTER THEN + i_line<='1'; + i_wfl(o_ibuf1) <= '0'; + i_adrsi<=to_unsigned(N_BURST * i_hburst,32) + + to_unsigned(N_BURST * to_integer( + unsigned'("00") & to_std_logic(HEADER)),32); + ELSE + i_line<='0'; + i_wfl(o_ibuf0) <= '1'; + i_adrsi<=to_unsigned(N_BURST * to_integer( + unsigned'("00") & to_std_logic(HEADER)),32); + END IF; + END IF; + + i_ven<=to_std_logic(i_hcpt>=i_hmin AND i_hcpt<=i_hmax AND + i_vcpt>=i_vmin AND i_vcpt<=i_vmax); + + -- Detects end of frame for triple buffering. + i_endframe0<=i_vs AND (NOT i_inter OR i_flm OR i_bob_deint); + i_endframe1<=i_vs AND (NOT i_inter OR NOT i_flm OR i_bob_deint); + + i_vss<=to_std_logic(i_vcpt>=i_vmin AND i_vcpt<=i_vmax); + + ---------------------------------------------------- + IF i_pde='1' AND i_de_pre='0' THEN + i_vimax<=i_vcpt; + i_hcpt<=0; + ELSE + i_hcpt<=(i_hcpt+1) MOD 4096; + END IF; + + IF i_pde='0' AND i_de_pre='1' THEN + i_himax<=i_hcpt; + END IF; + + IF i_iauto='1' THEN + -- Auto-size + i_hmin<=0; + i_hmax<=i_himax; + i_vmin<=0; + IF i_pvs='1' AND i_vs_pre='0' AND (i_inter='0' OR i_pfl='0') THEN + i_vmax<=i_vimax; + END IF; + ELSE + -- Forced image + i_hmin<=himin; -- + i_hmax<=himax; -- + i_vmin<=vimin; -- + IF i_pvs='1' AND i_vs_pre='0' AND (i_inter='0' OR i_pfl='0') THEN + i_vmax<=vimax; -- + END IF; + END IF; + + IF i_pvs='1' AND i_vs_pre='0' AND (i_inter='0' OR i_pfl='0') THEN + i_vdmax<=i_vimax; + END IF; + i_hdmax<=i_himax; + + IF i_format="00" OR i_format="11" THEN -- 16bpp + i_hburst<=(i_hrsize*2 + N_BURST - 1) / N_BURST; + ELSIF i_format="01" THEN -- 24bpp + i_hburst<=(i_hrsize*3 + N_BURST - 1) / N_BURST; + ELSE -- 32bpp + i_hburst<=(i_hrsize*4 + N_BURST - 1) / N_BURST; + END IF; + ---------------------------------------------------- + i_mode<=mode; -- + i_format<=format; -- + + -- Downscaling : Nearest or bilinear + i_bil<=to_std_logic(i_mode(2 DOWNTO 0)/="000" AND NOT DOWNSCALE_NN); + + i_hdown<=to_std_logic(i_hsize>i_ohsize AND DOWNSCALE); --H downscale + i_vdown<=to_std_logic(i_vsize>i_ovsize AND DOWNSCALE); --V downscale + + ---------------------------------------------------- + i_hsize <=(4096+i_hmax-i_hmin+1) MOD 4096; + i_vmaxmin<=(4096+i_vmax-i_vmin+1) MOD 4096; + + IF i_inter='0' THEN + -- Non interlaced + i_vsize<=i_vmaxmin; + i_half <='0'; + ELSIF i_ovsize<2*i_vmaxmin THEN + -- Interlaced, but downscaling, use only half frames + i_vsize<=i_vmaxmin; + i_half <='1'; + ELSE + -- Interlaced : Double image height + i_vsize<=2*i_vmaxmin; + i_half <='0'; + END IF; + + i_ohsize<=o_hsize; -- + i_ovsize<=o_vsize; -- + + ---------------------------------------------------- + -- Downscaling vertical + i_divstart<='0'; + IF i_de_delay=16 THEN + IF (i_vacc + 2*i_ovsize) < 2*i_vsize THEN + i_vacc<=(i_vacc + 2*i_ovsize) MOD 8192; + i_vnp<='0'; + ELSE + i_vacc<=(i_vacc + 2*i_ovsize - 2*i_vsize + 8192) MOD 8192; + i_vnp<='1'; + END IF; + i_divstart<='1'; + + IF i_vcpt=i_vmin THEN + i_vacc<=(i_vsize - i_ovsize + 8192) MOD 8192; + i_vnp<='1'; -- + END IF; + END IF; + + IF i_vdown='0' THEN + i_vnp<='1'; + END IF; + + -- Downscaling horizontal + IF i_ven='1' THEN + IF i_hacc + 2*i_ohsize < 2*i_hsize THEN + i_hacc<=(i_hacc + 2*i_ohsize) MOD 8192; + i_hnp<='0'; -- Skip. pix. + ELSE + i_hacc<=(i_hacc + 2*i_ohsize - 2*i_hsize + 8192) MOD 8192; + i_hnp<='1'; + END IF; + END IF; + IF i_hdown='0' THEN + i_hnp<='1'; + END IF; + + ---------------------------------------------------- + -- Downscaling interpolation + i_hpixp<=i_ppix; + i_hpix0<=i_hpixp; + i_hpix1<=i_hpix0; + i_hpix2<=i_hpix1; + i_hpix3<=i_hpix2; + i_hpix4<=i_hpix3; + + i_hnp1<=i_hnp; i_hnp2<=i_hnp1; i_hnp3<=i_hnp2; i_hnp4<=i_hnp3; + i_ven1<=i_ven; i_ven2<=i_ven1; i_ven3<=i_ven2; i_ven4<=i_ven3; + i_ven5<=i_ven4; i_ven6<=i_ven5; + + -- C1 : DIV 1. Pipelined 4 bits non-restoring divider + dir_v:=x"000"; + div_v:=to_unsigned(i_hacc * 16,17); + + div_v:=div_v-to_unsigned(i_hsize*16,17); + dir_v(11):=NOT div_v(16); + IF div_v(16)='0' THEN + div_v:=div_v-to_unsigned(i_hsize*8,17); + ELSE + div_v:=div_v+to_unsigned(i_hsize*8,17); + END IF; + dir_v(10):=NOT div_v(16); + i_div<=div_v; + i_dir<=dir_v; + + -- C2 : DIV 2. + div_v:=i_div; + dir_v:=i_dir; + IF div_v(16)='0' THEN + div_v:=div_v-to_unsigned(i_hsize*4,17); + ELSE + div_v:=div_v+to_unsigned(i_hsize*4,17); + END IF; + dir_v(9):=NOT div_v(16); + + IF div_v(16)='0' THEN + div_v:=div_v-to_unsigned(i_hsize*2,17); + ELSE + div_v:=div_v+to_unsigned(i_hsize*2,17); + END IF; + dir_v(8):=NOT div_v(16); + i_h_frac<=dir_v; + + -- C4 : Horizontal Bilinear + IF i_bil='0' THEN + frac_v:=near_frac(i_h_frac); + i_h_bil_t<=near_calc(frac_v,(i_hpix2,i_hpix2,i_hpix3,i_hpix3)); + ELSE + frac_v:=bil_frac(i_h_frac); + i_h_bil_t<=bil_calc(frac_v,(i_hpix2,i_hpix2,i_hpix3,i_hpix3)); + END IF; + + i_hpix.r<=bound(i_h_bil_t.r,8+FRAC); + i_hpix.g<=bound(i_h_bil_t.g,8+FRAC); + i_hpix.b<=bound(i_h_bil_t.b,8+FRAC); + + IF i_hdown='0' THEN + i_hpix<=i_hpix4; + END IF; + + -- C5 : Vertical Bilinear + IF i_bil='0' THEN + frac_v:=near_frac(i_v_frac(11 DOWNTO 0)); + bil_t_v:=near_calc(frac_v,(i_hpix,i_hpix,i_ldrm,i_ldrm)); + ELSE + frac_v:=bil_frac(i_v_frac(11 DOWNTO 0)); + bil_t_v:=bil_calc(frac_v,(i_hpix,i_hpix,i_ldrm,i_ldrm)); + END IF; + + i_pix.r<=bound(bil_t_v.r,8+FRAC); + i_pix.g<=bound(bil_t_v.g,8+FRAC); + i_pix.b<=bound(bil_t_v.b,8+FRAC); + + IF i_vdown='0' THEN + i_pix<=i_hpix; + END IF; + + ---------------------------------------------------- + -- VNP : Vert. downscaling line enable + -- HNP : Horiz. downscaling pix. enable + -- VEN : Enable pixel within displayed window + + IF (i_hnp4='1' AND i_ven6='1') OR i_pushend='1' THEN + i_shift<=shift_ishift(i_shift,i_pix,i_format); + i_dw<=shift_ipack(i_dw,i_acpt,i_shift,i_pix,i_format); + + IF shift_inext(i_acpt,i_format) AND i_vnp='1' THEN + i_push<='1'; + i_pushend<='0'; + END IF; + i_acpt<=(i_acpt+1) MOD 16; + END IF; + + IF i_ven6='1' AND i_ven5='0' AND i_vnp='1' THEN + i_pushend<='1'; + END IF; + i_pushend2<=i_pushend; + + IF i_pushend2='1' AND i_pushend='0' THEN + i_eol<='1'; + END IF; + + IF i_pde='0' AND i_de_pre='1' THEN + i_de_delay<=0; + ELSIF i_de_delay<18 THEN + i_de_delay<=i_de_delay+1; + END IF; + + IF i_de_delay=16 THEN + i_lwad<=0; + i_lrad<=0; + i_vcpt<=i_vcpt+1; + i_hacc<=(i_hsize - i_ohsize + 8192) MOD 8192; + i_hbcpt<=0; + END IF; + IF i_de_delay=17 THEN + i_acpt<=0; + i_wad<=2*BLEN-1; + END IF; + + IF i_pvs='0' AND i_vs_pre='1' THEN + -- Push header + i_pushhead<=to_std_logic(HEADER); + END IF; + + END IF; -- IF i_pce='1' + + ------------------------------------------------------ + -- Push pixels to downscaling line buffer + i_lwr<=i_hnp4 AND i_ven5 AND i_pce; + IF i_lwr='1' THEN + i_lwad<=(i_lwad+1) MOD OHRESH; + END IF; + i_ldw<=i_hpix; + + IF i_hnp3='1' AND i_ven4='1' AND i_pce='1' THEN + i_lrad<=(i_lrad+1) MOD OHRESH; + END IF; + + ------------------------------------------------------ + -- Write image properties header + i_pushhead2<=i_pushhead; i_pushhead3<=i_pushhead2; + + IF i_pushhead='1' AND i_freeze='0' THEN + i_dw<=i_head(127 DOWNTO 128-N_DW); + i_count<=i_count+1; + i_wr<='1'; + i_wad<=0; + IF N_DW=128 THEN + i_alt<='0'; + i_wreq<=NOT i_freeze; + i_adrs<=(OTHERS =>'0'); + END IF; + END IF; + + IF i_pushhead2='1' AND i_freeze='0' AND N_DW=64 THEN + i_dw<=i_head(N_DW-1 DOWNTO 0); + i_wr<='1'; + i_wad<=1; + i_wreq<=NOT i_freeze; + i_alt<='0'; + i_adrs<=(OTHERS =>'0'); + END IF; + IF i_pushhead3='1' THEN + i_wad<=BLEN-1; + END IF; + + ------------------------------------------------------ + -- Push pixels to DPRAM + IF i_push='1' AND i_freeze='0' THEN + i_wr<='1'; + i_wad<=(i_wad+1) MOD (BLEN*2); + IF (i_wad+1) MOD BLEN=BLEN-1 AND i_hbcpt 12 + IDividers:PROCESS (i_clk,i_reset_na) IS + BEGIN + IF i_reset_na='0' THEN +--pragma synthesis_off + i_v_frac<=x"000"; +--pragma synthesis_on + NULL; + ELSIF rising_edge(i_clk) THEN + i_vdivi<=to_unsigned(2*i_vsize,13); + i_vdivr<=to_unsigned(i_vacc*4096,25); + + ------------------------------------------------------ + IF i_divstart='1' THEN + i_divcpt<=0; + i_divrun<='1'; + + ELSIF i_divrun='1' THEN + ---------------------------------------------------- + IF i_divcpt=6 THEN + i_divrun<='0'; + i_v_frac<=i_vdivr(4 DOWNTO 0) & NOT i_vdivr(24) & "000000"; + ELSE + i_divcpt<=i_divcpt+1; + END IF; + + IF i_vdivr(24)='0' THEN + i_vdivr(24 DOWNTO 12)<=i_vdivr(23 DOWNTO 11) - i_vdivi; + ELSE + i_vdivr(24 DOWNTO 12)<=i_vdivr(23 DOWNTO 11) + i_vdivi; + END IF; + i_vdivr(11 DOWNTO 0)<=i_vdivr(10 DOWNTO 0) & NOT i_vdivr(24); + + ---------------------------------------------------- + END IF; + END IF; + END PROCESS IDividers; + + ----------------------------------------------------------------------------- + -- DPRAM Input. Double buffer for RAM bursts. + PROCESS (i_clk) IS + BEGIN + IF rising_edge(i_clk) THEN + IF i_wr='1' THEN + i_dpram(i_wad)<=i_dw; + END IF; + END IF; + END PROCESS; + + avl_dr<=i_dpram(avl_rad_c) WHEN rising_edge(avl_clk); + + -- Line buffer for downscaling with interpolation + DownLine:IF DOWNSCALE GENERATE + ILBUF:PROCESS(i_clk) IS + BEGIN + IF rising_edge(i_clk) THEN + IF i_lwr='1' THEN + i_mem(i_lwad MOD IHRES)<=i_ldw; + END IF; + IF i_pce='1' THEN + i_ldrm<=i_mem(i_lrad MOD IHRES); + END IF; + END IF; + END PROCESS ILBUF; + END GENERATE DownLine; + + ----------------------------------------------------------------------------- + -- AVALON interface + Avaloir:PROCESS(avl_clk,avl_reset_na) IS + VARIABLE adr_v : unsigned(31 DOWNTO 0); + BEGIN + IF avl_reset_na='0' THEN + avl_state<=sIDLE; + avl_write_sr<='0'; + avl_read_sr<='0'; + avl_readdataack<='0'; + avl_readack<='0'; + + ELSIF rising_edge(avl_clk) THEN + ---------------------------------- + avl_write_sync<=i_write; -- + avl_write_sync2<=avl_write_sync; + avl_write_pulse<=avl_write_sync XOR avl_write_sync2; + IF avl_write_pulse='1' THEN + avl_wadrs <=i_wadrs AND (RAMSIZE - 1); -- + avl_wline <=i_wline; -- + avl_walt <=i_walt; -- + END IF; + + ---------------------------------- + avl_read_sync<=o_read; -- + avl_read_sync2<=avl_read_sync; + avl_read_pulse<=avl_read_sync XOR avl_read_sync2; + avl_radrs <=o_adrs; -- + avl_rline <=o_rline; -- + + -------------------------------------------- + avl_o_vs_sync<=o_vsv(0); -- + avl_o_vs<=avl_o_vs_sync; + + avl_fb_ena<=o_fb_ena; -- + IF avl_fb_ena='0' THEN + IF HEADER THEN + avl_o_offset0<=buf_offset(o_obuf0,RAMBASE,RAMSIZE) + N_BURST; -- + avl_o_offset1<=buf_offset(o_obuf1,RAMBASE,RAMSIZE) + N_BURST; -- + ELSE + avl_o_offset0<=buf_offset(o_obuf0,RAMBASE,RAMSIZE); -- + avl_o_offset1<=buf_offset(o_obuf1,RAMBASE,RAMSIZE); -- + END IF; + ELSIF avl_o_vs_sync='0' AND avl_o_vs='1' THEN + -- Copy framebuffer base address at VS falling edge + avl_o_offset0<=o_fb_base; -- + avl_o_offset1<=o_fb_base; -- + END IF; + + avl_i_offset0<=buf_offset(o_ibuf0,RAMBASE,RAMSIZE); -- + avl_i_offset1<=buf_offset(o_ibuf1,RAMBASE,RAMSIZE); -- + + -------------------------------------------- + avl_dw<=swap(unsigned(avl_readdata)); + avl_read_i<='0'; + avl_write_i<='0'; + + avl_write_sr<=(avl_write_sr OR avl_write_pulse) AND NOT avl_write_clr; + avl_read_sr <=(avl_read_sr OR avl_read_pulse) AND NOT avl_read_clr; + avl_write_clr<='0'; + avl_read_clr <='0'; + + avl_rad<=avl_rad_c; + + -------------------------------------------- + CASE avl_state IS + WHEN sIDLE => + IF avl_write_sr='1' THEN + avl_state<=sWRITE; + avl_write_clr<='1'; + IF avl_walt='0' THEN + avl_rad<=0; + ELSE + avl_rad<=BLEN; + END IF; + IF avl_wline='0' THEN + avl_address<=std_logic_vector( + avl_wadrs(N_AW+NB_LA-1 DOWNTO NB_LA) + + avl_i_offset0(N_AW+NB_LA-1 DOWNTO NB_LA)); + ELSE + avl_address<=std_logic_vector( + avl_wadrs(N_AW+NB_LA-1 DOWNTO NB_LA) + + avl_i_offset1(N_AW+NB_LA-1 DOWNTO NB_LA)); + END IF; + ELSIF avl_read_sr='1' THEN + avl_state<=sREAD; + avl_read_clr<='1'; + END IF; + + WHEN sWRITE => + avl_write_i<='1'; + IF avl_write_i='1' AND avl_waitrequest='0' THEN + IF (avl_rad MOD BLEN)=BLEN-1 THEN + avl_write_i<='0'; + avl_state<=sIDLE; + END IF; + END IF; + + WHEN sREAD => + IF avl_rline='0' THEN + adr_v:=avl_radrs + avl_o_offset0; + ELSE + adr_v:=avl_radrs + avl_o_offset1; + END IF; + avl_address<=std_logic_vector(adr_v(N_AW+NB_LA-1 DOWNTO NB_LA)); + + avl_read_i<='1'; + IF avl_read_i='1' AND avl_waitrequest='0' THEN + avl_state<=sIDLE; + avl_read_i<='0'; + avl_readack<=NOT avl_readack; + END IF; + END CASE; + + -------------------------------------------- + -- Pipelined data read + avl_wr<='0'; + IF avl_readdatavalid='1' THEN + avl_wr<='1'; + avl_wad<=(avl_wad+1) MOD (2*BLEN); + IF (avl_wad MOD BLEN)=BLEN-2 THEN + avl_readdataack<=NOT avl_readdataack; + END IF; + END IF; + + IF avl_o_vs_sync='0' AND avl_o_vs='1' THEN + avl_wad<=2*BLEN-1; + END IF; + + -------------------------------------------- + END IF; + END PROCESS Avaloir; + + avl_read<=avl_read_i; + avl_write<=avl_write_i; + avl_writedata<=std_logic_vector(swap(avl_dr)); + avl_burstcount<=std_logic_vector(to_unsigned(BLEN,8)); + avl_byteenable<=(OTHERS =>'1'); + + avl_rad_c<=(avl_rad+1) MOD (2*BLEN) + WHEN avl_write_i='1' AND avl_waitrequest='0' ELSE avl_rad; + + ----------------------------------------------------------------------------- + -- DPRAM Output. Double buffer for RAM bursts. + PROCESS (avl_clk) IS + BEGIN + IF rising_edge(avl_clk) THEN + IF avl_wr='1' THEN + o_dpram(avl_wad)<=avl_dw; + END IF; + END IF; + END PROCESS; + + o_dr<=o_dpram(o_ad3) WHEN rising_edge(o_clk); + + ----------------------------------------------------------------------------- + -- Output Vertical Divider + -- Vfrac = Vacc / Vsize + ODivider:PROCESS (o_clk,o_reset_na) IS + BEGIN + IF o_reset_na='0' THEN +--pragma synthesis_off + o_vfrac<=x"000"; +--pragma synthesis_on + ELSIF rising_edge(o_clk) THEN + o_vdivi<=to_unsigned(2*o_vsize,13); + o_vdivr<=to_unsigned(o_vacc*4096,25); + ------------------------------------------------------ + IF o_divstart='1' THEN + o_divcpt<=0; + o_divrun<='1'; + + ELSIF o_divrun='1' THEN + ---------------------------------------------------- + IF o_divcpt=12 THEN + o_divrun<='0'; + o_vfrac<=o_vdivr(10 DOWNTO 0) & NOT o_vdivr(24); + ELSE + o_divcpt<=o_divcpt+1; + END IF; + + IF o_vdivr(24)='0' THEN + o_vdivr(24 DOWNTO 12)<=o_vdivr(23 DOWNTO 11) - o_vdivi; + ELSE + o_vdivr(24 DOWNTO 12)<=o_vdivr(23 DOWNTO 11) + o_vdivi; + END IF; + o_vdivr(11 DOWNTO 0)<=o_vdivr(10 DOWNTO 0) & NOT o_vdivr(24); + ---------------------------------------------------- + END IF; + END IF; + END PROCESS ODivider; + + ----------------------------------------------------------------------------- + Scalaire:PROCESS (o_clk,o_reset_na) IS + VARIABLE lev_inc_v,lev_dec_v : std_logic; + VARIABLE prim_v,last_v,bib_v : std_logic; + VARIABLE shift_v : unsigned(0 TO N_DW+15); + VARIABLE hpix_v : type_pix; + VARIABLE hcarry_v,vcarry_v : boolean; + VARIABLE dif_v : natural RANGE 0 TO 8*OHRESH-1; + VARIABLE off_v : natural RANGE 0 TO 15; + BEGIN + IF o_reset_na='0' THEN + o_copy<=sWAIT; + o_state<=sDISP; + o_read_pre<='0'; + o_readlev<=0; + o_copylev<=0; + o_hsp<='0'; + + ELSIF rising_edge(o_clk) THEN + ------------------------------------------------------ + o_mode <=mode; -- ? + o_format <="0001" & format; -- ? + + o_run <=run; -- ? + + o_htotal <=htotal; -- ? + o_hsstart<=hsstart; -- ? + o_hsend <=hsend; -- ? + o_hdisp <=hdisp; -- ? + o_hmin <=hmin; -- ? + o_hmax <=hmax; -- ? + + o_vtotal <=vtotal; -- ? + o_vsstart<=vsstart; -- ? + o_vsend <=vsend; -- ? + o_vdisp <=vdisp; -- ? + o_vmin <=vmin; -- ? + o_vmax <=vmax; -- ? + + o_hsize <=o_hmax - o_hmin + 1; + o_vsize <=o_vmax - o_vmin + 1; + + o_vrr <=vrr; + o_vrrmax <= vrrmax; + + -------------------------------------------- + -- Triple buffering. + -- For intelaced video, half frames are updated independently + -- Input : Toggle buffer at end of input frame + o_isync <= '0'; + o_isync2 <= o_isync; + o_freeze <= freeze; + o_bob_deint <= bob_deint; + o_iwfl <= i_wfl; + o_inter <=i_inter; -- + o_iendframe0<=i_endframe0; -- + o_iendframe02<=o_iendframe0; + IF o_iendframe0='1' AND o_iendframe02='0' THEN + o_ibuf0<=buf_next(o_ibuf0,o_obuf0,o_freeze); + o_bufup0<='1'; + o_isync <= '1'; + END IF; + o_iendframe1<=i_endframe1; -- + o_iendframe12<=o_iendframe1; + IF o_iendframe1='1' AND o_iendframe12='0' THEN + o_ibuf1<=buf_next(o_ibuf1,o_obuf1,o_freeze); + o_bufup1<='1'; + o_isync <= '1'; + END IF; + + -- Output : Change framebuffer, and image properties, at VS falling edge + IF o_vsv(1)='1' AND o_vsv(0)='0' AND o_bufup0='1' THEN + o_obuf0<=buf_next(o_obuf0,o_ibuf0,o_freeze); + o_bufup0<='0'; + END IF; + IF o_vsv(1)='1' AND o_vsv(0)='0' AND o_bufup1='1' THEN + o_obuf1<=buf_next(o_obuf1,o_ibuf1,o_freeze); + o_bufup1<='0'; + o_ihsize<=i_hrsize; -- + o_ivsize<=i_vrsize; -- + o_hdown<=i_hdown; -- + o_vdown<=i_vdown; -- + + IF (o_newres > 0) then + o_newres <= o_newres- 1; + END IF; + END IF; + + IF (swblack = '1' and o_fb_ena = '0' and (o_ihsize /= i_hrsize or o_ivsize /= i_vrsize)) then + o_newres <= 3; + END IF; + + -- Simultaneous change of input and output framebuffers + IF o_vsv(1)='1' AND o_vsv(0)='0' AND + o_iendframe0='1' AND o_iendframe02='0' THEN + o_bufup0<='0'; + o_obuf0<=o_ibuf0; + END IF; + IF o_vsv(1)='1' AND o_vsv(0)='0' AND + o_iendframe1='1' AND o_iendframe12='0' THEN + o_bufup1<='0'; + o_obuf1<=o_ibuf1; + END IF; + + -- Non-interlaced, use same buffer for even and odd lines + IF o_inter='0' THEN + o_ibuf1<=o_ibuf0; + o_obuf1<=o_obuf0; + END IF; + + -- Triple buffer disabled + IF o_mode(3)='0' THEN + o_obuf0<=0; + o_obuf1<=0; + o_ibuf0<=0; + o_ibuf1<=0; + END IF; + + -- Framebuffer mode. + IF o_fb_ena='1' THEN + o_ihsize<=o_fb_hsize; + o_ivsize<=o_fb_vsize; + o_format<=o_fb_format; + o_hdown<='0'; + o_vdown<='0'; + END IF; + + -- 011=8bpp(palette) 100=16bpp 101=24bpp 110=32bpp + CASE o_format(2 DOWNTO 0) IS + WHEN "011" => o_ihsize_temp <= o_ihsize; + WHEN "100" => o_ihsize_temp <= o_ihsize * 2; + WHEN "110" => o_ihsize_temp <= o_ihsize * 4; + WHEN OTHERS => o_ihsize_temp <= o_ihsize * 3; + END CASE; + + o_ihsize_temp2 <= (o_ihsize_temp + N_BURST - 1); + o_hburst <= o_ihsize_temp2 / N_BURST; + + IF o_fb_ena='1' AND o_fb_stride /= 0 THEN + o_stride<=o_fb_stride; + ELSE + o_stride<=to_unsigned(o_ihsize_temp2,14); + o_stride(NB_BURST-1 DOWNTO 0)<=(OTHERS =>'0'); + END IF; + ------------------------------------------------------ + o_hmode<=o_mode; + IF o_hdown='1' AND DOWNSCALE THEN + -- Force nearest if downscaling : Downscaled framebuffer + o_hmode(2 DOWNTO 0)<="000"; + END IF; + + o_vmode<=o_mode; + IF o_vdown='1' AND DOWNSCALE THEN + -- Force nearest if downscaling : Downscaled framebuffer + o_vmode(2 DOWNTO 0)<="000"; + END IF; + + ------------------------------------------------------ + -- End DRAM READ + o_readack_sync<=avl_readack; -- + o_readack_sync2<=o_readack_sync; + o_readack<=o_readack_sync XOR o_readack_sync2; + + o_readdataack_sync<=avl_readdataack; -- + o_readdataack_sync2<=o_readdataack_sync; + o_readdataack<=o_readdataack_sync XOR o_readdataack_sync2; + + ------------------------------------------------------ + lev_inc_v:='0'; + lev_dec_v:='0'; + + -- acpt : Pixel position within current data word + -- dcpt : Destination image position + + -- Force preload 2 lines at top of screen + IF o_hsv(0)='1' AND o_hsv(1)='0' THEN + IF o_vcpt_pre3=o_vmin THEN + o_fload<=2; + o_bibu<='0'; + END IF; + o_hsp<='1'; + END IF; + + o_vpe<=to_std_logic(o_vcpt_pre=o_vmin); + o_divstart<='0'; + o_adrsa<='0'; + o_adrsb<=o_adrsa; + + o_vacc_ini<=(o_vsize - o_ivsize + 8192) MOD 8192; + o_hacc_ini<=(o_hsize + o_ihsize + 8192) MOD 8192; + + --Alternate phase + --o_vacc_ini<=o_ivsize; + --o_hacc_ini<=(2*o_hsize - o_ihsize + 8192) MOD 8192; + + CASE o_state IS + -------------------------------------------------- + WHEN sDISP => + IF o_hsp='1' THEN + o_state<=sHSYNC; + o_hsp<='0'; + END IF; + o_prim<=true; + o_vcarrym<=false; + + -------------------------------------------------- + WHEN sHSYNC => + dif_v :=(o_vacc_next - 2*o_vsize + 16384) MOD 16384; + IF o_prim THEN + IF dif_v>=8192 THEN + o_vacc <=o_vacc_next; + ELSE + o_vacc <=dif_v; + END IF; + END IF; + IF dif_v>=8192 THEN + o_vacc_next<=(o_vacc_next + 2*o_ivsize) MOD 8192; + vcarry_v:=false; + ELSE + o_vacc_next<=dif_v; + vcarry_v:=true; + END IF; + + IF o_vcpt_pre2=o_vmin THEN + o_vacc <=o_vacc_ini; + o_vacc_next<=o_vacc_ini + 2*o_ivsize; + o_vacpt <=x"001"; + o_vacptl<="01"; + vcarry_v:=false; + END IF; + + IF vcarry_v THEN + o_vacpt<=o_vacpt+1; + END IF; + IF vcarry_v AND o_prim THEN + o_vacptl<=o_vacptl+1; + END IF; + o_vcarrym <= o_vcarrym OR vcarry_v; + o_prim <= false; + o_hbcpt<=0; -- Clear burst counter on line + o_divstart<=to_std_logic(NOT vcarry_v); + IF NOT vcarry_v OR o_fload>0 THEN + IF (o_vpe='1' AND o_vcarrym) OR o_fload>0 THEN + o_state<=sREAD; + ELSE + o_state<=sDISP; + END IF; + END IF; + + WHEN sREAD => + -- Read a block + IF o_readlev<2 AND o_adrsb='1' THEN + lev_inc_v:='1'; + o_read_pre<=NOT o_read_pre; + o_state <=sWAITREAD; + o_bibu<=NOT o_bibu; + END IF; + prim_v:=to_std_logic(o_hbcpt=0); + last_v:=to_std_logic(o_hbcpt=o_hburst-1); + bib_v :=o_bibu; + off_v :=pixoffset(o_adrs + o_fb_base(NB_LA-1 DOWNTO 0),o_fb_format); + IF o_fb_ena='0' THEN + off_v:=0; + END IF; + o_adrsa<='1'; + + WHEN sWAITREAD => + IF o_readack='1' THEN + o_hbcpt<=o_hbcpt+1; + IF o_hbcpt=1 THEN + o_fload<=o_fload-1; + END IF; + END IF; + END IF; + + -------------------------------------------------- + END CASE; + + o_read<=o_read_pre AND o_run; + o_rline<=o_vacpt(0); -- Even/Odd line for interlaced video + + ---- + -- When bob deinterlacing we read lines from one buffer (the most current) but we read them twice + -- (in contrast to weave deinterlacing where we read each 480p line from alternating buffers) + -- To counteract the severe vibrating/motion with bob deinterlacing, we need to offset one field + -- by a half-line. This is done by only reading the first line of the 'even' frame once + + IF o_inter='1' AND o_bob_deint='1' THEN + IF o_iwfl(o_obuf0)='0' THEN + IF o_vacpt=0 OR o_rline='1' THEN + o_adrs_pre <= to_integer(o_vacpt) * to_integer(o_stride); + ELSE + o_adrs_pre <= (to_integer(o_vacpt)-1) * to_integer(o_stride); + END IF; + ELSE + o_adrs_pre <= to_integer(o_vacpt(11 DOWNTO 1) & "0") * to_integer(o_stride); + END IF; + ELSE + o_adrs_pre<=to_integer(o_vacpt) * to_integer(o_stride); + END IF; + + IF o_adrsa='1' THEN + IF o_fload=2 THEN + o_adrs<=to_unsigned(o_hbcpt * N_BURST,32); + o_alt<="1111"; + ELSIF o_fload=1 THEN + o_adrs<=to_unsigned(o_hbcpt * N_BURST,32) + o_stride; + o_alt<="0100"; + ELSE + o_adrs<=to_unsigned(o_adrs_pre + (o_hbcpt * N_BURST),32); + o_alt<=altx(o_vacptl + 1); + END IF; + END IF; + + ------------------------------------------------------ + -- Copy from buffered memory to pixel lines + o_sh<='0'; + o_dcpt_clr <= '0'; + o_dcpt_inc <= '0'; + + CASE o_copy IS + WHEN sWAIT => + o_copyv(0)<='0'; + IF o_copylev>0 AND o_copyv(0)='0' THEN + o_copy<=sCOPY; + IF o_off(0)>0 AND o_primv(0)='1' THEN + o_copy<=sSHIFT; + END IF; + o_altx<=o_alt; + END IF; + o_adturn<='0'; + o_pshift<=o_off(0) -1; + IF o_primv(0)='1' THEN + -- First memcopy of a horizontal line, carriage return ! + o_ihsizem<=o_ihsize + o_off(0) - 2; + o_hacc <=o_hacc_ini; + o_hacc_next<=o_hacc_ini + 2*o_ihsize; + o_hacpt <=x"000"; + o_dcpt_clr <= '1'; + o_dshi<=2; + o_acpt<=0; + o_first<='1'; + o_last<='0'; + END IF; + + IF o_bibv(0)='0' THEN + o_ad<=0; + ELSE + o_ad<=BLEN; + END IF; + + WHEN sSHIFT => + o_hacpt<=o_hacpt+1; + o_sh<='1'; + o_acpt<=(o_acpt+1) MOD 16; + IF shift_onext(o_acpt,o_format) THEN + o_ad<=(o_ad+1) MOD (2*BLEN); + END IF; + o_pshift<=o_pshift-1; + IF o_pshift=0 THEN + o_copy<=sCOPY; + END IF; + + WHEN sCOPY => + -- dshi : Force shift first two or three pixels of each line + IF o_dshi=0 THEN + dif_v:=(o_hacc_next - 2*o_hsize + (8*OHRESH)) MOD (8*OHRESH); + IF dif_v>=4*OHRESH THEN + o_hacc<=o_hacc_next; + o_hacc_next<=o_hacc_next + 2*o_ihsize; + hcarry_v:=false; + ELSE + o_hacc<=dif_v; + o_hacc_next<=(dif_v + 2*o_ihsize + (4*OHRESH)) MOD (4*OHRESH); + hcarry_v:=true; + END IF; + o_dcpt_inc <= '1'; + ELSE + o_dshi<=o_dshi-1; + hcarry_v:=false; + END IF; + IF o_dshi<=1 THEN + o_copyv(0)<='1'; + END IF; + IF hcarry_v THEN + o_hacpt<=o_hacpt+1; + o_last <=to_std_logic(o_hacpt>=o_ihsizem); + END IF; + + IF hcarry_v OR o_dshi>0 THEN + o_sh<='1'; + o_acpt<=(o_acpt+1) MOD 16; + + -- Shift two more pixels to the right before ending line. + o_last1<=o_last; + o_last2<=o_last1; + + IF shift_onext(o_acpt,o_format) THEN + o_ad<=(o_ad+1) MOD (2*BLEN); + END IF; + + IF o_adturn='1' AND (shift_onext((o_acpt+1) MOD 16,o_format)) AND + (((o_ad MOD BLEN=0) AND o_lastv(0)='0') OR o_last2='1') THEN + o_copy<=sWAIT; + lev_dec_v:='1'; + END IF; + + IF o_ad MOD BLEN=4 THEN + o_adturn<='1'; + END IF; + END IF; + END CASE; + + o_acpt1<=o_acpt; o_acpt2<=o_acpt1; o_acpt3<=o_acpt2; o_acpt4<=o_acpt3; + o_ad1<=o_ad; o_ad2<=o_ad1; o_ad3<=o_ad2; + o_sh1<=o_sh; o_sh2<=o_sh1; o_sh3<=o_sh2; o_sh4<=o_sh3; + o_lastt1<=o_last; o_lastt2<=o_lastt1; + o_lastt3<=o_lastt2; o_lastt4<=o_lastt3; + + ------------------------------------------------------ + IF o_sh3='1' THEN + shift_v:=shift_opack(o_acpt4,o_shift,o_dr,o_format); + o_shift<=shift_v; + o_hpixs<=shift_opix(shift_v,o_format); + END IF; + + IF o_sh4='1' THEN + hpix_v:=o_hpixs; + IF o_format(4)='1' THEN -- Swap B <-> R + hpix_v:=(r=>o_hpixs.b,g=>o_hpixs.g,b=>o_hpixs.r); + END IF; + IF o_format(2 DOWNTO 0)="011" THEN + -- 8bpp indexed colour mode + hpix_v:=(r=>o_fb_pal_dr(23 DOWNTO 16),g=>o_fb_pal_dr(15 DOWNTO 8), + b=>o_fb_pal_dr(7 DOWNTO 0)); + END IF; + IF (o_newres > 0) then + hpix_v := (others => (others => '0')); + END IF; + o_hpix0<=hpix_v; + o_hpix1<=o_hpix0; + o_hpix2<=o_hpix1; + o_hpix3<=o_hpix2; + + IF o_first='1' THEN + -- Left edge. Duplicate first pixel + o_hpix1<=hpix_v; + o_hpix2<=hpix_v; + o_first<='0'; + END IF; + IF o_lastt4='1' THEN + -- Right edge. Keep last pixel. + o_hpix0<=o_hpix0; + END IF; + END IF; + + ------------------------------------------------------ + -- lev_inc : read start + -- lev_dec : end of copy + -- READLEV : Number of ongoing Avalon Reads + IF lev_dec_v='0' AND lev_inc_v='1' THEN + o_readlev<=o_readlev+1; + ELSIF lev_dec_v='1' AND lev_inc_v='0' THEN + o_readlev<=o_readlev-1; + END IF; + + -- COPYLEV : Number of ongoing copies to line buffers + IF lev_dec_v='1' AND o_readdataack='0' THEN + o_copylev<=o_copylev-1; + ELSIF lev_dec_v='0' AND o_readdataack='1' THEN + o_copylev<=o_copylev+1; + END IF; + + -- FIFOs + IF lev_dec_v='1' THEN + o_primv(0 TO 1)<=o_primv(1 TO 2); -- First buffer of line + o_lastv(0 TO 1)<=o_lastv(1 TO 2); -- Last buffer of line + o_bibv (0 TO 1)<=o_bibv (1 TO 2); -- Double buffer select + o_off (0 TO 1)<=o_off (1 TO 2); -- Start offset + END IF; + + IF lev_inc_v='1' THEN + IF o_readlev=0 OR (o_readlev=1 AND lev_dec_v='1') THEN + o_primv(0)<=prim_v; + o_lastv(0)<=last_v; + o_bibv (0)<=bib_v; + o_off (0)<=off_v; + ELSIF (o_readlev=1 AND lev_dec_v='0') OR + (o_readlev=2 AND lev_dec_v='1') THEN + o_primv(1)<=prim_v; + o_lastv(1)<=last_v; + o_bibv (1)<=bib_v; + o_off (1)<=off_v; + END IF; + o_primv(2)<=prim_v; + o_lastv(2)<=last_v; + o_bibv (2)<=bib_v; + o_off (2)<=off_v; + END IF; + + ------------------------------------------------------ + END IF; + END PROCESS Scalaire; + + -- Fetch polyphase coefficients + PolyFetch:PROCESS (o_clk) IS + VARIABLE hfrac3_v, vfrac_v : unsigned(FRAC-1 DOWNTO 0); + BEGIN + IF rising_edge(o_clk) THEN + hfrac3_v:=o_hfrac(3)(11 DOWNTO 12-FRAC); + vfrac_v:=o_vfrac(11 DOWNTO 12-FRAC); + + o_v_poly_use_adaptive <= to_std_logic((o_vmode(2 DOWNTO 0)/="000") AND (o_v_poly_adaptive = '1')); + o_h_poly_use_adaptive <= to_std_logic((o_hmode(2 DOWNTO 0)/="000") AND (o_h_poly_adaptive = '1')); + o_v_poly_addr<=to_integer(o_vfrac(11 DOWNTO 12-FRAC)); + + -- C3 / HC3 / VC4 + IF o_vmode(2 DOWNTO 0)/="000" THEN + o_v_poly_phase_a<=poly_unpack(o_v_poly_mem(o_v_poly_addr)); + ELSE + o_v_poly_phase_a<=poly_nn(vfrac_v); + END IF; + + IF o_hmode(2 DOWNTO 0)/="000" THEN + o_h_poly_phase_a<=poly_unpack(o_h_poly_mem(to_integer(hfrac3_v))); + ELSE + o_h_poly_phase_a<=poly_nn(hfrac3_v); + END IF; + + IF o_v_poly_use_adaptive='1' THEN + o_poly_lum<=poly_lum(o_v_lum_pix); + o_a_poly_addr<=o_v_poly_addr; + ELSIF o_h_poly_use_adaptive='1' THEN + o_poly_lum<=poly_lum(o_h_lum_pix); + o_a_poly_addr<=to_integer(hfrac3_v); + END IF; + + -- C4 / HC4 / VC5 + o_poly_phase_b<=poly_unpack(o_a_poly_mem(o_a_poly_addr)); + + IF o_v_poly_use_adaptive='1' THEN + o_poly_phase_a<=o_v_poly_phase_a; + ELSIF o_h_poly_use_adaptive = '1' THEN + o_poly_phase_a<=o_h_poly_phase_a; + END IF; + + o_h_poly_phase_a2<=o_h_poly_phase_a; + o_v_poly_phase_a2<=o_v_poly_phase_a; + o_poly_lum1<=o_poly_lum; + + -- C5 / HC5 / VC6 + o_poly_lerp_ta<=signed(to_unsigned(256,10) - resize(o_poly_lum1,10)); + o_poly_lerp_tb<=signed(resize(o_poly_lum1,10)); + + o_poly_phase_b2<=o_poly_phase_b; + o_poly_phase_a2<=o_poly_phase_a; + + o_h_poly_phase_a3<=o_h_poly_phase_a2; + o_v_poly_phase_a3<=o_v_poly_phase_a2; + + -- C6 / HC6 / VC7 + o_poly_phase<=poly_lerp(o_poly_phase_a2, o_poly_phase_b2, o_poly_lerp_ta, o_poly_lerp_tb); + o_h_poly_phase_a4<=o_h_poly_phase_a3; + o_v_poly_phase_a4<=o_v_poly_phase_a3; + + -- C7 / HC7 / VC8 + o_h_poly_phase_a5<=o_h_poly_phase_a4; + o_v_poly_phase_a5<=o_v_poly_phase_a4; + o_poly_phase1<=o_poly_phase; + + -- C8 / HC8 / VC9 + o_v_poly_phase<=poly_cvt(o_v_poly_phase_a5); + o_h_poly_phase<=poly_cvt(o_h_poly_phase_a5); + + IF o_v_poly_use_adaptive = '1' THEN + o_v_poly_phase<=o_poly_phase1; + ELSIF o_h_poly_use_adaptive = '1' THEN + o_h_poly_phase<=o_poly_phase1; + END IF; + + END IF; + END PROCESS PolyFetch; + + + -- Framebuffer palette + GenPal1:IF PALETTE GENERATE + Tempera1:PROCESS(pal1_clk) IS + BEGIN + IF rising_edge(pal1_clk) THEN + IF pal1_wr='1' THEN + pal1_mem(to_integer(pal1_a))<=pal1_dw; + END IF; + pal1_dr<=pal1_mem(to_integer(pal1_a)); + END IF; + END PROCESS; + + pal_idx <= shift_opack(o_acpt4,o_shift,o_dr,o_format)(0 TO 7); + pal_idx_lsb <= pal_idx(0) WHEN rising_edge(o_clk); + o_fb_pal_dr_x2 <= pal1_mem(to_integer(pal_idx(7 DOWNTO 1))) WHEN rising_edge(o_clk); + END GENERATE GenPal1; + + GenPal2:IF PALETTE and PALETTE2 GENERATE + Tempera2:PROCESS(pal2_clk) IS + BEGIN + IF rising_edge(pal2_clk) THEN + IF pal2_wr='1' THEN + pal2_mem(to_integer(pal2_a))<=pal2_dw; + END IF; + pal2_dr<=pal2_mem(to_integer(pal2_a)); + END IF; + END PROCESS; + + o_fb_pal_dr2 <= pal2_mem(to_integer(pal_idx(7 DOWNTO 0))) WHEN rising_edge(o_clk); + o_fb_pal_dr <= o_fb_pal_dr2 when pal_n = '1' else o_fb_pal_dr_x2(47 DOWNTO 24) WHEN pal_idx_lsb = '1' ELSE o_fb_pal_dr_x2(23 DOWNTO 0); + END GENERATE GenPal2; + + GenPal1not2:IF PALETTE and not PALETTE2 GENERATE + o_fb_pal_dr <= o_fb_pal_dr_x2(47 DOWNTO 24) WHEN pal_idx_lsb = '1' ELSE o_fb_pal_dr_x2(23 DOWNTO 0); + END GENERATE GenPal1not2; + + GenNoPal:IF NOT PALETTE GENERATE + o_fb_pal_dr<=x"000000"; + END GENERATE GenNoPal; + + ----------------------------------------------------------------------------- + -- Polyphase ROMs + Polikarpov:PROCESS(poly_clk) IS + BEGIN + IF rising_edge(poly_clk) THEN + IF poly_wr='1' THEN + poly_tdw(9+10*(3-to_integer(poly_a(1 DOWNTO 0))) DOWNTO + 10*(3-to_integer(poly_a(1 DOWNTO 0))))<=poly_dw; + END IF; + + poly_wr_mode(0)<=poly_wr AND NOT poly_a(FRAC+2); + poly_wr_mode(1)<=poly_wr AND poly_a(FRAC+2); + poly_wr_mode(2)<=poly_wr AND poly_a(FRAC+3) AND to_std_logic(ADAPTIVE); + poly_a2<=poly_a(FRAC+1 DOWNTO 2); + + CASE poly_wr_mode IS + WHEN "001" => -- horiz + o_h_poly_mem(to_integer(poly_a2))<=poly_tdw; + o_h_poly_adaptive<='0'; + WHEN "010" => -- vert + o_v_poly_mem(to_integer(poly_a2))<=poly_tdw; + o_v_poly_adaptive<='0'; + WHEN "101" => -- horiz adaptive + o_a_poly_mem(to_integer(poly_a2))<=poly_tdw; + o_h_poly_adaptive<='1'; + WHEN "110" => -- vert adaptive + o_a_poly_mem(to_integer(poly_a2))<=poly_tdw; + o_v_poly_adaptive<='1'; + WHEN OTHERS => NULL; + END CASE; + END IF; + END PROCESS Polikarpov; + + ----------------------------------------------------------------------------- + -- Horizontal Scaler + HSCAL:PROCESS(o_clk) IS + VARIABLE div_v : unsigned(20 DOWNTO 0); + VARIABLE dir_v : unsigned(11 DOWNTO 0); + BEGIN + IF rising_edge(o_clk) THEN + -- Pipeline signals + ----------------------------------- + -- Pipelined 8 bits non-restoring divider. Cycle 1 + dir_v:=x"000"; + div_v:=to_unsigned(o_hacc * 256,21); + + div_v:=div_v-to_unsigned(o_hsize*256,21); + dir_v(11):=NOT div_v(20); + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*128,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*128,21); + END IF; + dir_v(10):=NOT div_v(20); + + o_div(0)<=div_v; + o_dir(0)<=dir_v; + + -- Cycle 2 + div_v:=o_div(0); + dir_v:=o_dir(0); + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*64,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*64,21); + END IF; + dir_v( 9):=NOT div_v(20); + + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*32,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*32,21); + END IF; + dir_v( 8):=NOT div_v(20); + + o_div(1)<=div_v; + o_dir(1)<=dir_v; + + -- Cycle 3 + div_v:=o_div(1); + dir_v:=o_dir(1); + IF FRAC>4 THEN + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*16,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*16,21); + END IF; + dir_v(7):=NOT div_v(20); + + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*8,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*8,21); + END IF; + dir_v(6):=NOT div_v(20); + END IF; + o_div(2)<=div_v; + o_dir(2)<=dir_v; + + div_v:=o_div(2); + dir_v:=o_dir(2); + IF FRAC>6 THEN + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*4,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*4,21); + END IF; + dir_v(5):=NOT div_v(20); + + IF div_v(20)='0' THEN + div_v:=div_v-to_unsigned(o_hsize*2,21); + ELSE + div_v:=div_v+to_unsigned(o_hsize*2,21); + END IF; + dir_v(4):=NOT div_v(20); + END IF; + + ----------------------------------- + o_hfrac(1)<=dir_v; + o_hfrac(2 TO 9) <= o_hfrac(1 TO 8); + + o_copyv(1 TO 14)<=o_copyv(0 TO 13); + o_dcptv_clr(1 TO 12)<=o_dcpt_clr & o_dcptv_clr(1 TO 11); + o_dcptv_inc(1 TO 12)<=o_dcpt_inc & o_dcptv_inc(1 TO 11); + + IF o_dcptv_clr(12)='1' THEN + o_dcptv(13) <= 0; + ELSIF o_dcptv_inc(12)='1' THEN + o_dcptv(13) <= (o_dcptv(13) + 1) MOD OHRESH; + END IF; + o_dcptv(14)<=o_dcptv(13); + + IF o_dcptv(13)>=o_hsize THEN + o_copyv(14)<='0'; + END IF; + + -- C2 + o_hpixq(2)<=(o_hpix3,o_hpix2,o_hpix1,o_hpix0); + o_hpixq(3 TO 8)<=o_hpixq(2 TO 7); + + -- BILINEAR / SHARP BILINEAR --------------- + -- C7 : Pre-calc Sharp Bilinear + o_h_sbil_t<=sbil_frac1(o_hfrac(6)); + + -- C8 : Select + o_h_bil_frac<=(OTHERS =>'0'); + IF o_hmode(0)='1' THEN -- Bilinear + IF MASK(MASK_BILINEAR)='1' THEN + o_h_bil_frac<=bil_frac(o_hfrac(7)); + END IF; + ELSE -- Sharp Bilinear + IF MASK(MASK_SHARP_BILINEAR)='1' THEN + o_h_bil_frac<=sbil_frac2(o_hfrac(7),o_h_sbil_t); + END IF; + END IF; + + -- C9 : Opposite frac + o_h_bil_t<=bil_calc(o_h_bil_frac,o_hpixq(8)); + + -- C10 : Bilinear / Sharp Bilinear + o_h_bil_pix.r<=bound(o_h_bil_t.r,8+FRAC); + o_h_bil_pix.g<=bound(o_h_bil_t.g,8+FRAC); + o_h_bil_pix.b<=bound(o_h_bil_t.b,8+FRAC); + + -- BICUBIC ------------------------------------------- + -- C8 : Bicubic coefficients A,B,C,D + -- C8 : Bicubic calc T1 = X.D + C + o_h_bic_abcd1<=bic_calc0(o_hfrac(7),o_hpixq(6)); + o_h_bic_tt1<=bic_calc1(o_hfrac(7), + bic_calc0(o_hfrac(7),o_hpixq(6))); + + -- C9 : Bicubic calc T2 = X.T1 + B + o_h_bic_abcd2<=o_h_bic_abcd1; + o_h_bic_tt2<=bic_calc2(o_hfrac(8),o_h_bic_tt1,o_h_bic_abcd1); + + -- C10 : Bicubic final Y = X.T2 + A + o_h_bic_pix<=bic_calc3(o_hfrac(9),o_h_bic_tt2,o_h_bic_abcd2); + + -- POLYPHASE ----------------------------------------- + -- C2 + IF o_hfrac(2)(o_hfrac(2)'left)='0' THEN + o_h_lum_pix<=o_hpix2; + ELSE + o_h_lum_pix<=o_hpix1; + END IF; + + -- C3-C8 in PolyFetch + + -- C9 : Apply Polyphase + o_h_poly_t<=poly_calc(o_h_poly_phase,o_hpixq(8)); + + -- C10 : Sum and bound + o_h_poly_pix<=poly_final(o_h_poly_t); + + -- C11 : Select interpoler ---------------------------- + o_wadl<=o_dcptv(14); + o_wr<=o_altx AND (o_copyv(14) & o_copyv(14) & o_copyv(14) & o_copyv(14)); + o_ldw<=(x"00",x"00",x"00"); + + CASE o_hmode(2 DOWNTO 0) IS + WHEN "000" => -- Nearest + IF MASK(MASK_NEAREST)='1' THEN + o_ldw<=o_h_poly_pix; + END IF; + WHEN "001" | "010" => -- Bilinear | Sharp Bilinear + IF MASK(MASK_BILINEAR)='1' OR + MASK(MASK_SHARP_BILINEAR)='1' THEN + o_ldw<=o_h_bil_pix; + END IF; + WHEN "011" => -- BiCubic + IF MASK(MASK_BICUBIC)='1' THEN + o_ldw<=o_h_bic_pix; + END IF; + WHEN OTHERS => -- PolyPhase + IF MASK(MASK_POLY)='1' THEN + o_ldw<=o_h_poly_pix; + END IF; + END CASE; + ------------------------------------------------------ + END IF; + END PROCESS HSCAL; + + ----------------------------------------------------------------------------- + -- Line buffers 4 x OHRES x (R+G+B) + OLBUF:PROCESS(o_clk) IS + BEGIN + IF rising_edge(o_clk) THEN + ----------------------------------------------- + -- WRITES + IF o_wr(0)='1' AND o_wadl < OHRESL THEN o_line0(o_wadl MOD OHRESL)<=o_ldw; END IF; + IF o_wr(1)='1' AND o_wadl < OHRESL THEN o_line1(o_wadl MOD OHRESL)<=o_ldw; END IF; + IF o_wr(2)='1' AND o_wadl < OHRESL THEN o_line2(o_wadl MOD OHRESL)<=o_ldw; END IF; + IF o_wr(3)='1' AND o_wadl < OHRESL THEN o_line3(o_wadl MOD OHRESL)<=o_ldw; END IF; + IF OHRES = 2304 OR OHRES = 2560 THEN + IF o_wr(0)='1' AND o_wadl >= OHRESL THEN o_linf0(o_wadl MOD OHRESM)<=o_ldw; END IF; + IF o_wr(1)='1' AND o_wadl >= OHRESL THEN o_linf1(o_wadl MOD OHRESM)<=o_ldw; END IF; + IF o_wr(2)='1' AND o_wadl >= OHRESL THEN o_linf2(o_wadl MOD OHRESM)<=o_ldw; END IF; + IF o_wr(3)='1' AND o_wadl >= OHRESL THEN o_linf3(o_wadl MOD OHRESM)<=o_ldw; END IF; + END IF; + + ----------------------------------------------- + -- READS + o_ldr0<=o_line0(o_radl0 MOD OHRESL); + o_ldr1<=o_line1(o_radl1 MOD OHRESL); + o_ldr2<=o_line2(o_radl2 MOD OHRESL); + o_ldr3<=o_line3(o_radl3 MOD OHRESL); + + IF OHRES = 2304 OR OHRES = 2560 THEN + o_ler0<=o_linf0(o_radl0 MOD OHRESM); + o_ler1<=o_linf1(o_radl1 MOD OHRESM); + o_ler2<=o_linf2(o_radl2 MOD OHRESM); + o_ler3<=o_linf3(o_radl3 MOD OHRESM); + END IF; + + o_lex0 <= to_std_logic(o_radl0 >= OHRESL); + o_lex1 <= to_std_logic(o_radl1 >= OHRESL); + o_lex2 <= to_std_logic(o_radl2 >= OHRESL); + o_lex3 <= to_std_logic(o_radl3 >= OHRESL); + ----------------------------------------------- + + END IF; + END PROCESS OLBUF; + + ----------------------------------------------------------------------------- + -- Output video sweep + OSWEEP:PROCESS(o_clk) IS + BEGIN + IF rising_edge(o_clk) THEN + + IF o_ce='1' THEN + -- Output pixels count + IF o_hcpt+1=o_vtotal THEN + o_vcpt_pre3<=0; + ELSIF o_vrr_sync2 THEN + o_vcpt_pre3<=o_vsstart; + o_sync<=false; + ELSE + o_vcpt_pre3<=(o_vcpt_pre3+1) MOD 4096; + END IF; + + o_vcpt_pre2<=o_vcpt_pre3; + o_vcpt_pre<=o_vcpt_pre2; + o_vcpt<=o_vcpt_pre; + END IF; + + o_end(0)<=to_std_logic(o_vcpt>=o_vdisp); + o_dev(0)<=to_std_logic(o_hcpt=o_hmin AND o_hcpt<=o_hmax AND + o_vcpt>=o_vmin AND o_vcpt<=o_vmax); + o_hsv(0)<=to_std_logic(o_hcpt>=o_hsstart AND o_hcpt=o_hsstart) OR + (o_vcpt>o_vsstart AND o_vcpt=o_vmin AND o_vcpt_pre2<=o_vmax); + o_hsv(1 TO 11)<=o_hsv(0 TO 10); + o_vsv(1 TO 11)<=o_vsv(0 TO 10); + o_dev(1 TO 11)<=o_dev(0 TO 10); + o_pev(1 TO 11)<=o_pev(0 TO 10); + o_end(1 TO 11)<=o_end(0 TO 10); + + IF o_run='0' THEN + o_hsv(2)<='0'; + o_vsv(2)<='0'; + o_dev(2)<='0'; + o_pev(2)<='0'; + o_end(2)<='0'; + END IF; + END IF; + + o_vcpt_sync2<=o_vcpt_sync; + o_vrr_min<=(o_vcpt_sync2=o_vdisp AND o_vcpt2 o_radl1<=r2_v; + WHEN "11" => o_radl2<=r2_v; + WHEN "00" => o_radl3<=r2_v; + WHEN OTHERS => o_radl0<=r2_v; + END CASE; + ELSE + CASE o_vacptl IS + WHEN "10" => o_radl2<=r2_v; + WHEN "11" => o_radl3<=r2_v; + WHEN "00" => o_radl0<=r2_v; + WHEN OTHERS => o_radl1<=r2_v; + END CASE; + END IF; + + -- CYCLE 2 ----------------------------------------- + -- Lines reordering + IF o_lex0='0' THEN o_l0_v := o_ldr0; ELSE o_l0_v := o_ler0; END IF; + IF o_lex1='0' THEN o_l1_v := o_ldr1; ELSE o_l1_v := o_ler1; END IF; + IF o_lex2='0' THEN o_l2_v := o_ldr2; ELSE o_l2_v := o_ler2; END IF; + IF o_lex3='0' THEN o_l3_v := o_ldr3; ELSE o_l3_v := o_ler3; END IF; + + CASE o_vacptl IS + WHEN "10" => pixq_v:=(o_l0_v,o_l1_v,o_l2_v,o_l3_v); + WHEN "11" => pixq_v:=(o_l1_v,o_l2_v,o_l3_v,o_l0_v); + WHEN "00" => pixq_v:=(o_l2_v,o_l3_v,o_l0_v,o_l1_v); + WHEN OTHERS => pixq_v:=(o_l3_v,o_l0_v,o_l1_v,o_l2_v); + END CASE; + + IF fracnn_v = '0' THEN + o_vpix_outer<=(pixq_v(0), pixq_v(2), pixq_v(3)); + o_vpix_inner(0)<=pixq_v(1); + ELSE + o_vpix_outer<=(pixq_v(0), pixq_v(1), pixq_v(3)); + o_vpix_inner(0)<=pixq_v(2); + END IF; + + -- CYCLE 3-7 + o_vpix_inner(1 TO 5)<=o_vpix_inner(0 TO 4); + + -- CYCLE 8 + IF to_integer(o_vacpt)>o_ivsize THEN + IF fracnn_v = '0' THEN + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_inner(5), o_vpix_inner(5), o_vpix_inner(5)); + ELSE + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_outer(1), o_vpix_outer(1), o_vpix_outer(1)); + END IF; + ELSIF to_integer(o_vacpt)=o_ivsize THEN + IF fracnn_v = '0' THEN + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_inner(5), o_vpix_outer(1), o_vpix_outer(1)); + ELSE + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_outer(1), o_vpix_inner(5), o_vpix_inner(5)); + END IF; + ELSE + IF fracnn_v = '0' THEN + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_inner(5), o_vpix_outer(1), o_vpix_outer(2)); + ELSE + o_vpixq_pre<=(o_vpix_outer(0), o_vpix_outer(1), o_vpix_inner(5), o_vpix_outer(2)); + END IF; + END IF; + + -- CYCLE 9 + o_vpixq<=o_vpixq_pre; + + -- BILINEAR / SHARP BILINEAR ----------------------- + -- C8 : Pre-calc Sharp Bilinear + o_v_sbil_t<=sbil_frac1(o_vfrac); + + -- C9 : Select + o_v_bil_frac<=(OTHERS =>'0'); + IF o_vmode(0)='1' THEN -- Bilinear + IF MASK(MASK_BILINEAR)='1' THEN + o_v_bil_frac<=bil_frac(o_vfrac); + END IF; + ELSE -- Sharp Bilinear + IF MASK(MASK_SHARP_BILINEAR)='1' THEN + o_v_bil_frac<=sbil_frac2(o_vfrac,o_v_sbil_t); + END IF; + END IF; + + -- C10 : + o_v_bil_t<=bil_calc(o_v_bil_frac,o_vpixq); + + -- C11 : Nearest / Bilinear / Sharp Bilinear + o_v_bil_pix.r<=bound(o_v_bil_t.r,8+FRAC); + o_v_bil_pix.g<=bound(o_v_bil_t.g,8+FRAC); + o_v_bil_pix.b<=bound(o_v_bil_t.b,8+FRAC); + + -- BICUBIC ----------------------------------------- + -- C9 : Bicubic coefficients A,B,C,D + -- C9 : Bicubic calc T1 = X.D + C + o_v_bic_abcd1<=bic_calc0(o_vfrac,o_vpixq); + o_v_bic_tt1<=bic_calc1(o_vfrac,bic_calc0(o_vfrac,o_vpixq)); + + -- C10 : Bicubic calc T2 = X.T1 + B + o_v_bic_abcd2<=o_v_bic_abcd1; + o_v_bic_tt2<=bic_calc2(o_vfrac,o_v_bic_tt1,o_v_bic_abcd1); + + -- C11 : Bicubic final Y = X.T2 + A + o_v_bic_pix<=bic_calc3(o_vfrac,o_v_bic_tt2,o_v_bic_abcd2); + + -- POLYPHASE --------------------------------------- + -- C3 : Setup luminance + o_v_lum_pix<=o_vpix_inner(0); + + -- C4-C9 in PolyFetch + + -- C10 : Apply polyphase + o_v_poly_t<=poly_calc(o_v_poly_phase,o_vpixq); + + -- C11 : Bound + o_v_poly_pix<=poly_final(o_v_poly_t); + + -- CYCLE 12 ----------------------------------------- + o_hs<=o_hsv(11); + o_vs<=o_vsv(11); + o_de<=o_dev(11); + o_vbl<=o_end(11); + o_r<=x"00"; + o_g<=x"00"; + o_b<=x"00"; + o_brd<= not o_pev(11); + + CASE o_vmode(2 DOWNTO 0) IS + WHEN "000" => -- Nearest + IF MASK(MASK_NEAREST)='1' THEN + o_r<=o_v_poly_pix.r; + o_g<=o_v_poly_pix.g; + o_b<=o_v_poly_pix.b; + END IF; + WHEN "001" | "010" => -- Bilinear | Sharp Bilinear + IF MASK(MASK_BILINEAR)='1' OR + MASK(MASK_SHARP_BILINEAR)='1' THEN + o_r<=o_v_bil_pix.r; + o_g<=o_v_bil_pix.g; + o_b<=o_v_bil_pix.b; + END IF; + WHEN "011" => -- BiCubic + IF MASK(MASK_BICUBIC)='1' THEN + o_r<=o_v_bic_pix.r; + o_g<=o_v_bic_pix.g; + o_b<=o_v_bic_pix.b; + END IF; + + WHEN OTHERS => -- Polyphase + IF MASK(MASK_POLY)='1' THEN + o_r<=o_v_poly_pix.r; + o_g<=o_v_poly_pix.g; + o_b<=o_v_poly_pix.b; + END IF; + END CASE; + + IF o_pev(11)='0' THEN + o_r<=o_border(23 DOWNTO 16); -- Copy border colour + o_g<=o_border(15 DOWNTO 8); + o_b<=o_border(7 DOWNTO 0); + END IF; + + ---------------------------------------------------- + END IF; + END IF; + END PROCESS VSCAL; + + ----------------------------------------------------------------------------- + -- Low Lag syntoniser interface + o_lltune<=(0 => i_vss, + 1 => i_pde, + 2 => i_inter, + 3 => i_flm, + 4 => o_vss, + 5 => i_pce, + 6 => i_clk, + 7 => o_clk, + OTHERS =>'0'); + + ---------------------------------------------------------------------------- +END ARCHITECTURE rtl; diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/audio_out.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/audio_out.sv new file mode 100644 index 0000000000000000000000000000000000000000..309b92eefe97e4646ba39e9a1cc2f4792c716249 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/audio_out.sv @@ -0,0 +1,343 @@ +//============================================================================ +// +// MiSTer Audio mixing & filtering +// (c)2020-2026 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + +module audio_out +#( + parameter CLK_RATE = 24576000 +) +( + input reset, + input clk, + + //0 - 48KHz, 1 - 96KHz + input sample_rate, + + input [31:0] flt_rate, + input [39:0] cx, + input [7:0] cx0, + input [7:0] cx1, + input [7:0] cx2, + input [23:0] cy0, + input [23:0] cy1, + input [23:0] cy2, + + input [4:0] att, + input [1:0] boost, + input [1:0] mix, + + input is_signed, + input [15:0] core_l, + input [15:0] core_r, + + input [15:0] alsa_l, + input [15:0] alsa_r, + + // I2S + output i2s_bclk, + output i2s_lrclk, + output i2s_data, + + // SPDIF + output spdif, + + // Sigma-Delta DAC + output dac_l, + output dac_r +); + +localparam AUDIO_RATE = 48000; +localparam AUDIO_DW = 16; + +localparam CE_RATE = AUDIO_RATE*AUDIO_DW*8; +localparam FILTER_DIV = (CE_RATE/(AUDIO_RATE*32))-1; + +wire [31:0] real_ce = sample_rate ? {CE_RATE[30:0],1'b0} : CE_RATE[31:0]; + +reg mclk_ce; +always @(posedge clk) begin + reg [31:0] cnt; + + mclk_ce = 0; + cnt = cnt + real_ce; + if(cnt >= CLK_RATE) begin + cnt = cnt - CLK_RATE; + mclk_ce = 1; + end +end + +reg i2s_ce; +always @(posedge clk) begin + reg div; + i2s_ce <= 0; + if(mclk_ce) begin + div <= ~div; + i2s_ce <= div; + end +end + +i2s i2s +( + .reset(reset), + + .clk(clk), + .ce(i2s_ce), + + .sclk(i2s_bclk), + .lrclk(i2s_lrclk), + .sdata(i2s_data), + + .left_chan(al), + .right_chan(ar) +); + +spdif toslink +( + .rst_i(reset), + + .clk_i(clk), + .bit_out_en_i(mclk_ce), + + .sample_i({ar,al}), + .spdif_o(spdif) +); + +sigma_delta_dac #(15) sd_l +( + .CLK(clk), + .RESET(reset), + .DACin({~al[15], al[14:0]}), + .DACout(dac_l) +); + +sigma_delta_dac #(15) sd_r +( + .CLK(clk), + .RESET(reset), + .DACin({~ar[15], ar[14:0]}), + .DACout(dac_r) +); + +reg sample_ce; +always @(posedge clk) begin + reg [8:0] div = 0; + reg [1:0] add = 0; + + div <= div + add; + if(!div) begin + div <= 2'd1 << sample_rate; + add <= 2'd1 << sample_rate; + end + + sample_ce <= !div; +end + +reg flt_ce; +always @(posedge clk) begin + reg [31:0] cnt = 0; + + flt_ce = 0; + cnt = cnt + {flt_rate[30:0],1'b0}; + if(cnt >= CLK_RATE) begin + cnt = cnt - CLK_RATE; + flt_ce = 1; + end +end + +reg [15:0] cl,cr; +always @(posedge clk) begin + reg [15:0] cl1,cl2; + reg [15:0] cr1,cr2; + + cl1 <= core_l; cl2 <= cl1; + if(cl2 == cl1) cl <= cl2; + + cr1 <= core_r; cr2 <= cr1; + if(cr2 == cr1) cr <= cr2; +end + +reg a_en1 = 0, a_en2 = 0; +always @(posedge clk, posedge reset) begin + reg [1:0] dly1 = 0; + reg [14:0] dly2 = 0; + + if(reset) begin + dly1 <= 0; + dly2 <= 0; + a_en1 <= 0; + a_en2 <= 0; + end + else begin + if(flt_ce) begin + if(~&dly1) dly1 <= dly1 + 1'd1; + else a_en1 <= 1; + end + + if(sample_ce) begin + if(!dly2[13+sample_rate]) dly2 <= dly2 + 1'd1; + else a_en2 <= 1; + end + end +end + +wire [15:0] acl, acr; +IIR_filter #(.use_params(0)) IIR_filter +( + .clk(clk), + .reset(reset), + + .ce(flt_ce & a_en1), + .sample_ce(sample_ce), + + .cx(cx), + .cx0(cx0), + .cx1(cx1), + .cx2(cx2), + .cy0(cy0), + .cy1(cy1), + .cy2(cy2), + + .input_l({~is_signed ^ cl[15], cl[14:0]}), + .input_r({~is_signed ^ cr[15], cr[14:0]}), + .output_l(acl), + .output_r(acr) +); + +wire [15:0] adl; +DC_blocker dcb_l +( + .clk(clk), + .ce(sample_ce), + .sample_rate(sample_rate), + .mute(~a_en2), + .din(acl), + .dout(adl) +); + +wire [15:0] adr; +DC_blocker dcb_r +( + .clk(clk), + .ce(sample_ce), + .sample_rate(sample_rate), + .mute(~a_en2), + .din(acr), + .dout(adr) +); + +wire [15:0] al, audio_l_pre; +aud_mix_top audmix_l +( + .clk(clk), + .ce(sample_ce), + .att(att), + .boost(boost), + .mix(mix), + + .core_audio(adl), + .pre_in(audio_r_pre), + .linux_audio(alsa_l), + + .pre_out(audio_l_pre), + .out(al) +); + +wire [15:0] ar, audio_r_pre; +aud_mix_top audmix_r +( + .clk(clk), + .ce(sample_ce), + .att(att), + .boost(boost), + .mix(mix), + + .core_audio(adr), + .pre_in(audio_l_pre), + .linux_audio(alsa_r), + + .pre_out(audio_r_pre), + .out(ar) +); + +endmodule + +module aud_mix_top +( + input clk, + input ce, + + input [4:0] att, + input [1:0] boost, + input [1:0] mix, + + input [15:0] core_audio, + input [15:0] linux_audio, + input [15:0] pre_in, + + output reg [15:0] pre_out = 0, + output reg [15:0] out = 0 +); + +localparam boost_f1 = 4; +localparam boost_a1 = 2; +localparam boost_x1 = ((32767 * (boost_f1 - 1)) / ((boost_f1 * boost_a1) - 1)) + 1; +localparam boost_b1 = boost_x1 * boost_a1; + +localparam boost_f2 = 8; +localparam boost_a2 = 4; +localparam boost_x2 = ((32767 * (boost_f2 - 1)) / ((boost_f2 * boost_a2) - 1)) + 1; +localparam boost_b2 = boost_x2 * boost_a2; + +localparam [1:0][2:0] boost_f = '{$clog2(boost_f2), $clog2(boost_f1)}; +localparam [1:0][2:0] boost_a = '{$clog2(boost_a2), $clog2(boost_a1)}; +localparam [1:0][15:0] boost_x = '{boost_x2[15:0], boost_x1[15:0]}; +localparam [1:0][15:0] boost_b = '{boost_b2[15:0], boost_b1[15:0]}; + +reg signed [15:0] a1; +reg signed [16:0] a2, a3, a4; +reg [15:0] v0, v1; +reg s0,s1; +always @(posedge clk) if (ce) begin + + v0 <= core_audio[15] ? (~core_audio) + 1'd1 : core_audio; + s0 <= core_audio[15]; + v1 <= (v0 < boost_x[boost[1]]) ? (v0 << boost_a[boost[1]]) : (((v0 - boost_x[boost[1]]) >> boost_f[boost[1]]) + boost_b[boost[1]]); + s1 <= s0; + + a1 <= boost ? (s1 ? ~(v1-1'd1) : v1) : core_audio; + a2 <= {a1[15],a1} + {linux_audio[15],linux_audio}; + + pre_out <= a2[16:1]; + + case(mix) + 0: a3 <= a2; + 1: a3 <= $signed(a2) - $signed(a2[16:3]) + $signed(pre_in[15:2]); + 2: a3 <= $signed(a2) - $signed(a2[16:2]) + $signed(pre_in[15:1]); + 3: a3 <= {a2[16],a2[16:1]} + {pre_in[15],pre_in}; + endcase + + if(att[4]) a4 <= 0; + else a4 <= a3 >>> att[3:0]; + + //clamping + out <= ^a4[16:15] ? {a4[16],{15{a4[15]}}} : a4[15:0]; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/build_id.tcl b/MiSTer-devel_NeoGeo_MiSTer/sys/build_id.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b43b9d926855ff6b33ad8bab1880f243672c972e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/build_id.tcl @@ -0,0 +1,73 @@ + +# Build TimeStamp Verilog Module +# Jeff Wiencrot - 8/1/2011 +# Sorgelig - 02/11/2019 +proc generateBuildID_Verilog {} { + + # Get the timestamp (see: http://www.altera.com/support/examples/tcl/tcl-date-time-stamp.html) + set buildDate "`define BUILD_DATE \"[clock format [ clock seconds ] -format %y%m%d]\"" + + # Create a Verilog file for output + set outputFileName "build_id.v" + + set fileData "" + if { [file exists $outputFileName]} { + set outputFile [open $outputFileName "r"] + set fileData [read $outputFile] + close $outputFile + } + + if {$buildDate ne $fileData} { + set outputFile [open $outputFileName "w"] + puts -nonewline $outputFile $buildDate + close $outputFile + # Send confirmation message to the Messages window + post_message "Generated: [pwd]/$outputFileName: $buildDate" + } +} + +# Build CDF file +# Sorgelig - 17/2/2018 +proc generateCDF {revision device outpath} { + + set outputFileName "jtag.cdf" + set outputFile [open $outputFileName "w"] + + puts $outputFile "JedecChain;" + puts $outputFile " FileRevision(JESD32A);" + puts $outputFile " DefaultMfr(6E);" + puts $outputFile "" + puts $outputFile " P ActionCode(Ign)" + puts $outputFile " Device PartName(SOCVHPS) MfrSpec(OpMask(0));" + puts $outputFile " P ActionCode(Cfg)" + puts $outputFile " Device PartName($device) Path(\"$outpath/\") File(\"$revision.sof\") MfrSpec(OpMask(1));" + puts $outputFile "ChainEnd;" + puts $outputFile "" + puts $outputFile "AlteraBegin;" + puts $outputFile " ChainType(JTAG);" + puts $outputFile "AlteraEnd;" +} + +set project_name [lindex $quartus(args) 1] +set revision [lindex $quartus(args) 2] + +if {[project_exists $project_name]} { + if {[string equal "" $revision]} { + project_open $project_name -revision [get_current_revision $project_name] + } else { + project_open $project_name -revision $revision + } +} else { + post_message -type error "Project $project_name does not exist" + exit +} + +set device [get_global_assignment -name DEVICE] +set outpath [get_global_assignment -name PROJECT_OUTPUT_DIRECTORY] + +if [is_project_open] { + project_close +} + +generateBuildID_Verilog +generateCDF $revision $device $outpath diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/ddr_svc.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/ddr_svc.sv new file mode 100644 index 0000000000000000000000000000000000000000..ed24d4e8e8b2c7c747df3ed124ff187c5c340e7d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/ddr_svc.sv @@ -0,0 +1,108 @@ +// +// Copyright (c) 2020 Alexey Melnikov +// +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ------------------------------------------ +// + +// 16-bit version + +module ddr_svc +( + input clk, + + input ram_waitrequest, + output [7:0] ram_burstcnt, + output [28:0] ram_addr, + input [63:0] ram_readdata, + input ram_read_ready, + output reg ram_read, + output [63:0] ram_writedata, + output [7:0] ram_byteenable, + output reg ram_write, + + output [7:0] ram_bcnt, + + input [31:3] ch0_addr, + input [7:0] ch0_burst, + output [63:0] ch0_data, + input ch0_req, + output ch0_ready, + + input [31:3] ch1_addr, + input [7:0] ch1_burst, + output [63:0] ch1_data, + input ch1_req, + output ch1_ready +); + +assign ram_burstcnt = ram_burst; +assign ram_byteenable = 8'hFF; +assign ram_addr = ram_address; +assign ram_writedata = 0; + +assign ch0_data = ram_q[0]; +assign ch1_data = ram_q[1]; +assign ch0_ready = ready[0]; +assign ch1_ready = ready[1]; + +reg [7:0] ram_burst; +reg [63:0] ram_q[2]; +reg [31:3] ram_address; +reg [1:0] ack = 0; +reg [1:0] ready; +reg state = 0; +reg ch = 0; + +always @(posedge clk) begin + ready <= 0; + + if(!ram_waitrequest) begin + ram_read <= 0; + ram_write <= 0; + + case(state) + 0: if(ch0_req != ack[0]) begin + ack[0] <= ch0_req; + ram_address <= ch0_addr; + ram_burst <= ch0_burst; + ram_read <= 1; + ch <= 0; + ram_bcnt <= 8'hFF; + state <= 1; + end + else if(ch1_req != ack[1]) begin + ack[1] <= ch1_req; + ram_address <= ch1_addr; + ram_burst <= ch1_burst; + ram_read <= 1; + ch <= 1; + ram_bcnt <= 8'hFF; + state <= 1; + end + 1: begin + if(ram_read_ready) begin + ram_bcnt <= ram_bcnt + 1'd1; + ram_q[ch] <= ram_readdata; + ready[ch] <= 1; + if ((ram_bcnt+2'd2) == ram_burst) state <= 0; + end + end + endcase + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/emu_ports.vh b/MiSTer-devel_NeoGeo_MiSTer/sys/emu_ports.vh new file mode 100644 index 0000000000000000000000000000000000000000..ad59e00a3ff68fc3702f008e217ba091eb65d862 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/emu_ports.vh @@ -0,0 +1,153 @@ +//Master input clock +input CLK_50M, + +//Async reset from top-level module. +//Can be used as initial reset. +input RESET, + +//Must be passed to hps_io module +inout [45:0] HPS_BUS, + +//Base video clock. Usually equals to CLK_SYS. +output CLK_VIDEO, + +//Multiple resolutions are supported using different CE_PIXEL rates. +//Must be based on CLK_VIDEO +output CE_PIXEL, + +//Video aspect ratio for HDMI. Most retro systems have ratio 4:3. +//if VIDEO_ARX[12] or VIDEO_ARY[12] is set then [11:0] contains scaled size instead of aspect ratio. +output [12:0] VIDEO_ARX, +output [12:0] VIDEO_ARY, + +output [7:0] VGA_R, +output [7:0] VGA_G, +output [7:0] VGA_B, +output VGA_HS, +output VGA_VS, +output VGA_DE, // = ~(VBlank | HBlank) +output VGA_F1, +output [1:0] VGA_SL, +output VGA_SCALER, // Force VGA scaler +output VGA_DISABLE, // analog out is off + +input [11:0] HDMI_WIDTH, +input [11:0] HDMI_HEIGHT, +output HDMI_FREEZE, +output HDMI_BLACKOUT, +output HDMI_BOB_DEINT, + +`ifdef MISTER_FB +// Use framebuffer in DDRAM +// FB_FORMAT: +// [2:0] : 011=8bpp(palette) 100=16bpp 101=24bpp 110=32bpp +// [3] : 0=16bits 565 1=16bits 1555 +// [4] : 0=RGB 1=BGR (for 16/24/32 modes) +// +// FB_STRIDE either 0 (rounded to 256 bytes) or multiple of pixel size (in bytes) +output FB_EN, +output [4:0] FB_FORMAT, +output [11:0] FB_WIDTH, +output [11:0] FB_HEIGHT, +output [31:0] FB_BASE, +output [13:0] FB_STRIDE, +input FB_VBL, +input FB_LL, +output FB_FORCE_BLANK, + +`ifdef MISTER_FB_PALETTE +// Palette control for 8bit modes. +// Ignored for other video modes. +output FB_PAL_CLK, +output [7:0] FB_PAL_ADDR, +output [23:0] FB_PAL_DOUT, +input [23:0] FB_PAL_DIN, +output FB_PAL_WR, +`endif +`endif + +output LED_USER, // 1 - ON, 0 - OFF. + +// b[1]: 0 - LED status is system status OR'd with b[0] +// 1 - LED status is controled solely by b[0] +// hint: supply 2'b00 to let the system control the LED. +output [1:0] LED_POWER, +output [1:0] LED_DISK, + +// I/O board button press simulation (active high) +// b[1]: user button +// b[0]: osd button +output [1:0] BUTTONS, + +input CLK_AUDIO, // 24.576 MHz +output [15:0] AUDIO_L, +output [15:0] AUDIO_R, +output AUDIO_S, // 1 - signed audio samples, 0 - unsigned +output [1:0] AUDIO_MIX, // 0 - no mix, 1 - 25%, 2 - 50%, 3 - 100% (mono) + +//ADC +inout [3:0] ADC_BUS, + +//SD-SPI +output SD_SCK, +output SD_MOSI, +input SD_MISO, +output SD_CS, +input SD_CD, + +//High latency DDR3 RAM interface +//Use for non-critical time purposes +output DDRAM_CLK, +input DDRAM_BUSY, +output [7:0] DDRAM_BURSTCNT, +output [28:0] DDRAM_ADDR, +input [63:0] DDRAM_DOUT, +input DDRAM_DOUT_READY, +output DDRAM_RD, +output [63:0] DDRAM_DIN, +output [7:0] DDRAM_BE, +output DDRAM_WE, + +//SDRAM interface with lower latency +output SDRAM_CLK, +output SDRAM_CKE, +output [12:0] SDRAM_A, +output [1:0] SDRAM_BA, +inout [15:0] SDRAM_DQ, +output SDRAM_DQML, +output SDRAM_DQMH, +output SDRAM_nCS, +output SDRAM_nCAS, +output SDRAM_nRAS, +output SDRAM_nWE, + +`ifdef MISTER_DUAL_SDRAM +//Secondary SDRAM +//Set all output SDRAM_* signals to Z ASAP if SDRAM2_EN is 0 +input SDRAM2_EN, +output SDRAM2_CLK, +output [12:0] SDRAM2_A, +output [1:0] SDRAM2_BA, +inout [15:0] SDRAM2_DQ, +output SDRAM2_nCS, +output SDRAM2_nCAS, +output SDRAM2_nRAS, +output SDRAM2_nWE, +`endif + +input UART_CTS, +output UART_RTS, +input UART_RXD, +output UART_TXD, +output UART_DTR, +input UART_DSR, + +// Open-drain User port. +// 0 - D+/RX +// 1 - D-/TX +// 2..6 - USR2..USR6 +// Set USER_OUT to 1 to read from USER_IN. +input [6:0] USER_IN, +output [6:0] USER_OUT, + +input OSD_STATUS diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/f2sdram_safe_terminator.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/f2sdram_safe_terminator.sv new file mode 100644 index 0000000000000000000000000000000000000000..3586365dda0828507bf8a51a9ad688ab53700024 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/f2sdram_safe_terminator.sv @@ -0,0 +1,250 @@ +// ============================================================================ +// +// f2sdram_safe_terminator for MiSTer platform +// +// ============================================================================ +// Copyright (c) 2021 bellwood420 +// +// Background: +// +// Terminating a transaction of burst writing(/reading) in its midstream +// seems to cause an illegal state to f2sdram interface. +// +// Forced reset request that occurs when loading other core is inevitable. +// +// So if it happens exactly within the transaction period, +// unexpected issues with accessing to f2sdram interface will be caused +// in next loaded core. +// +// It seems that only way to reset broken f2sdram interface is to reset +// whole SDRAM Controller Subsystem from HPS via permodrst register +// in Reset Manager. +// But it cannot be done safely while Linux is running. +// It is usually done when cold or warm reset is issued in HPS. +// +// Main_MiSTer is issuing reset for FPGA <> HPS bridges +// via brgmodrst register in Reset Manager when loading rbf. +// But it has no effect on f2sdram interface. +// f2sdram interface seems to belong to SDRAM Controller Subsystem +// rather than FPGA-to-HPS bridge. +// +// Main_MiSTer is also trying to issuing reset for f2sdram ports +// via fpgaportrst register in SDRAM Controller Subsystem when loading rbf. +// But according to the Intel's document, fpgaportrst register can be +// used to stretch the port reset. +// It seems that it cannot be used to assert the port reset. +// +// According to the Intel's document, there seems to be a reset port on +// Avalon-MM slave interface, but it cannot be found in Qsys generated HDL. +// +// To conclude, the only thing FPGA can do is not to break the transaction. +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +// Purpose: +// To prevent the issue, this module completes ongoing transaction +// on behalf of user logic, when reset is asserted. +// +// Usage: +// Insert this module into the bus line between +// f2sdram (Avalon-MM slave) and user logic (Avalon-MM master). +// +// Notice: +// Asynchronous reset request is not supported. +// Please feed reset request synchronized to clock. +// +module f2sdram_safe_terminator #( + parameter DATA_WIDTH = 64, + parameter BURSTCOUNT_WIDTH = 8 +) ( + // clk should be the same as one provided to f2sdram port + // clk should not be stop when reset is asserted + input clk, + // rst_req_sync should be synchronized to clk + // Asynchronous reset request is not supported + input rst_req_sync, + + // Master port: connecting to Alavon-MM slave(f2sdram) + input waitrequest_master, + output [BURSTCOUNT_WIDTH-1:0] burstcount_master, + output [ADDRESS_WITDH-1:0] address_master, + input [DATA_WIDTH-1:0] readdata_master, + input readdatavalid_master, + output read_master, + output [DATA_WIDTH-1:0] writedata_master, + output [BYTEENABLE_WIDTH-1:0] byteenable_master, + output write_master, + + // Slave port: connecting to Alavon-MM master(user logic) + output waitrequest_slave, + input [BURSTCOUNT_WIDTH-1:0] burstcount_slave, + input [ADDRESS_WITDH-1:0] address_slave, + output [DATA_WIDTH-1:0] readdata_slave, + output readdatavalid_slave, + input read_slave, + input [DATA_WIDTH-1:0] writedata_slave, + input [BYTEENABLE_WIDTH-1:0] byteenable_slave, + input write_slave +); + +localparam BYTEENABLE_WIDTH = DATA_WIDTH/8; +localparam ADDRESS_WITDH = 32-$clog2(BYTEENABLE_WIDTH); + +/* +* Capture init reset deaseert +*/ +reg init_reset_deasserted = 1'b0; + +always_ff @(posedge clk) begin + if (!rst_req_sync) begin + init_reset_deasserted <= 1'b1; + end +end + +/* +* Lock stage +*/ +reg lock_stage = 1'b0; + +always_ff @(posedge clk) begin + if (rst_req_sync) begin + // Reset assert + if (init_reset_deasserted) begin + lock_stage <= 1'b1; + end + end + else begin + // Reset deassert + lock_stage <= 1'b0; + end +end + +/* +* Write burst transaction observer +*/ +reg state_write = 1'b0; +wire next_state_write; + +wire burst_write_start = !state_write && next_state_write; +wire valid_write_data = state_write && !waitrequest_master; +wire burst_write_end = state_write && (write_burstcounter == write_burstcount_latch - 1'd1); +wire valid_non_burst_write = !state_write && write_slave && (burstcount_slave == 1) && !waitrequest_master; + +reg [BURSTCOUNT_WIDTH-1:0] write_burstcounter = 0; +reg [BURSTCOUNT_WIDTH-1:0] write_burstcount_latch = 0; +reg [ADDRESS_WITDH-1:0] write_address_latch = 0; + +always_ff @(posedge clk) begin + state_write <= next_state_write; + + if (burst_write_start) begin + write_burstcounter <= waitrequest_master ? 1'd0 : 1'd1; + write_burstcount_latch <= burstcount_slave; + write_address_latch <= address_slave; + end + else if (valid_write_data) begin + write_burstcounter <= write_burstcounter + 1'd1; + end +end + +always_comb begin + if (!state_write) begin + if (valid_non_burst_write) + next_state_write = 1'b0; + else if (write_slave) + next_state_write = 1'b1; + else + next_state_write = 1'b0; + end + else begin + if (burst_write_end) + next_state_write = 1'b0; + else + next_state_write = 1'b1; + end +end + +reg [BURSTCOUNT_WIDTH-1:0] write_terminate_counter = 0; +reg [BURSTCOUNT_WIDTH-1:0] burstcount_latch = 0; +reg [ADDRESS_WITDH-1:0] address_latch = 0; + +reg terminating = 0; +reg read_terminating = 0; +reg write_terminating = 0; + +wire on_write_transaction = state_write && next_state_write; +wire on_start_write_transaction = !state_write && next_state_write; + +always_ff @(posedge clk) begin + if (rst_req_sync) begin + // Reset assert + if (init_reset_deasserted) begin + if (!lock_stage) begin + // Even not knowing reading is in progress or not, + // if it is in progress, it will finish at some point, and no need to do anything. + // Assume that reading is in progress when we are not on write transaction. + burstcount_latch <= burstcount_slave; + address_latch <= address_slave; + terminating <= 1; + + if (on_write_transaction) begin + write_terminating <= 1; + burstcount_latch <= write_burstcount_latch; + address_latch <= write_address_latch; + write_terminate_counter <= waitrequest_master ? write_burstcounter : write_burstcounter + 1'd1; + end + else if (on_start_write_transaction) begin + if (!valid_non_burst_write) begin + write_terminating <= 1; + write_terminate_counter <= waitrequest_master ? 1'd0 : 1'd1; + end + end + else if (read_slave && waitrequest_master) begin + // Need to keep read signal, burstcount and address until waitrequest_master deasserted + read_terminating <= 1; + end + end + else if (!waitrequest_master) begin + read_terminating <= 0; + end + end + end + else begin + // Reset deassert + if (!write_terminating) terminating <= 0; + read_terminating <= 0; + end + + if (write_terminating) begin + // Continue write transaction until the end + if (!waitrequest_master) write_terminate_counter <= write_terminate_counter + 1'd1; + if (write_terminate_counter == burstcount_latch - 1'd1) write_terminating <= 0; + end +end + +/* +* Bus mux depending on the stage. +*/ +always_comb begin + if (terminating) begin + burstcount_master = burstcount_latch; + address_master = address_latch; + read_master = read_terminating; + write_master = write_terminating; + byteenable_master = 0; + end + else begin + burstcount_master = burstcount_slave; + address_master = address_slave; + read_master = read_slave; + byteenable_master = byteenable_slave; + write_master = write_slave; + end +end + +// Just passing master <-> slave +assign writedata_master = writedata_slave; +assign readdata_slave = readdata_master; +assign readdatavalid_slave = readdatavalid_master; +assign waitrequest_slave = waitrequest_master; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/gamma_corr.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/gamma_corr.sv new file mode 100644 index 0000000000000000000000000000000000000000..321b83f7e1a7e52d6997e59a67eeac8ae4c5d849 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/gamma_corr.sv @@ -0,0 +1,124 @@ +module gamma_corr +( + input clk_sys, + input clk_vid, + input ce_pix, + input gamma_en, + input gamma_wr, + input [9:0] gamma_wr_addr, + input [7:0] gamma_value, + input HSync, + input VSync, + input HBlank, + input VBlank, + input [23:0] RGB_in, + output reg HSync_out, + output reg VSync_out, + output reg HBlank_out, + output reg VBlank_out, + output reg [23:0] RGB_out +); + +(* ramstyle="no_rw_check" *) reg [7:0] gamma_curve[768]; + +always @(posedge clk_sys) if (gamma_wr) gamma_curve[gamma_wr_addr] <= gamma_value; +always @(posedge clk_vid) gamma <= gamma_curve[gamma_index]; + +reg [9:0] gamma_index; +reg [7:0] gamma; + +always @(posedge clk_vid) begin + reg [7:0] R_in, G_in, B_in; + reg [7:0] R_gamma, G_gamma; + reg hs,vs,hb,vb; + reg [1:0] ctr = 0; + reg old_ce; + + old_ce <= ce_pix; + if(~old_ce & ce_pix) begin + {R_in,G_in,B_in} <= RGB_in; + hs <= HSync; vs <= VSync; + hb <= HBlank; vb <= VBlank; + + RGB_out <= gamma_en ? {R_gamma,G_gamma,gamma} : {R_in,G_in,B_in}; + HSync_out <= hs; VSync_out <= vs; + HBlank_out <= hb; VBlank_out <= vb; + + ctr <= 1; + gamma_index <= {2'b00,RGB_in[23:16]}; + end + + if (|ctr) ctr <= ctr + 1'd1; + + case(ctr) + 1: begin gamma_index <= {2'b01,G_in}; end + 2: begin R_gamma <= gamma; gamma_index <= {2'b10,B_in}; end + 3: begin G_gamma <= gamma; end + endcase +end + +endmodule + +module gamma_fast +( + input clk_vid, + input ce_pix, + + inout [21:0] gamma_bus, + + input HSync, + input VSync, + input HBlank, + input VBlank, + input DE, + input [23:0] RGB_in, + + output reg HSync_out, + output reg VSync_out, + output reg HBlank_out, + output reg VBlank_out, + output reg DE_out, + output reg [23:0] RGB_out +); + +(* ramstyle="no_rw_check" *) reg [7:0] gamma_curve_r[256]; +(* ramstyle="no_rw_check" *) reg [7:0] gamma_curve_g[256]; +(* ramstyle="no_rw_check" *) reg [7:0] gamma_curve_b[256]; + +assign gamma_bus[21] = 1; +wire clk_sys = gamma_bus[20]; +wire gamma_en = gamma_bus[19]; +wire gamma_wr = gamma_bus[18]; +wire [9:0] gamma_wr_addr = gamma_bus[17:8]; +wire [7:0] gamma_value = gamma_bus[7:0]; + +always @(posedge clk_sys) if (gamma_wr) begin + case(gamma_wr_addr[9:8]) + 0: gamma_curve_r[gamma_wr_addr[7:0]] <= gamma_value; + 1: gamma_curve_g[gamma_wr_addr[7:0]] <= gamma_value; + 2: gamma_curve_b[gamma_wr_addr[7:0]] <= gamma_value; + endcase +end + +reg [7:0] gamma_index_r,gamma_index_g,gamma_index_b; + +always @(posedge clk_vid) begin + reg [7:0] R_in, G_in, B_in; + reg [7:0] R_gamma, G_gamma; + reg hs,vs,hb,vb,de; + + if(ce_pix) begin + {gamma_index_r,gamma_index_g,gamma_index_b} <= RGB_in; + hs <= HSync; vs <= VSync; + hb <= HBlank; vb <= VBlank; + de <= DE; + + RGB_out <= gamma_en ? {gamma_curve_r[gamma_index_r],gamma_curve_g[gamma_index_g],gamma_curve_b[gamma_index_b]} + : {gamma_index_r,gamma_index_g,gamma_index_b}; + HSync_out <= hs; VSync_out <= vs; + HBlank_out <= hb; VBlank_out <= vb; + DE_out <= de; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/hps_io.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/hps_io.sv new file mode 100644 index 0000000000000000000000000000000000000000..1df2e0247aa57b3b8498df6c52ad1b91261f458a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/hps_io.sv @@ -0,0 +1,1040 @@ +// +// hps_io.v +// +// Copyright (c) 2014 Till Harbaum +// Copyright (c) 2017-2026 Alexey Melnikov +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +/////////////////////////////////////////////////////////////////////// +// altera message_off 10665 + +// +// Use buffer to access SD card. It's time-critical part. +// +// WIDE=1 for 16 bit file I/O +// VDNUM 1..10 +// BLKSZ 0..7: 0 = 128, 1 = 256, 2 = 512(default), .. 7 = 16384 + +// F12KEYMOD - is modifier key requested to raise fremework menu? +// 0 - no, F12 bring framework menu +// 1 - F12 is passed to core, F12 + (L/R)GUI key bring framework menu + +// +module hps_io #(parameter CONF_STR, CONF_STR_BRAM=0, PS2DIV=0, WIDE=0, VDNUM=1, BLKSZ=2, PS2WE=0, STRLEN=$size(CONF_STR)>>3, F12KEYMOD=0) +( + input clk_sys, + inout [45:0] HPS_BUS, + + // buttons up to 32 + output reg [31:0] joystick_0, + output reg [31:0] joystick_1, + output reg [31:0] joystick_2, + output reg [31:0] joystick_3, + output reg [31:0] joystick_4, + output reg [31:0] joystick_5, + + // analog -127..+127, Y: [15:8], X: [7:0] + output reg [15:0] joystick_l_analog_0, + output reg [15:0] joystick_l_analog_1, + output reg [15:0] joystick_l_analog_2, + output reg [15:0] joystick_l_analog_3, + output reg [15:0] joystick_l_analog_4, + output reg [15:0] joystick_l_analog_5, + + output reg [15:0] joystick_r_analog_0, + output reg [15:0] joystick_r_analog_1, + output reg [15:0] joystick_r_analog_2, + output reg [15:0] joystick_r_analog_3, + output reg [15:0] joystick_r_analog_4, + output reg [15:0] joystick_r_analog_5, + + input [15:0] joystick_0_rumble, // 15:8 - 'large' rumble motor magnitude, 7:0 'small' rumble motor magnitude + input [15:0] joystick_1_rumble, + input [15:0] joystick_2_rumble, + input [15:0] joystick_3_rumble, + input [15:0] joystick_4_rumble, + input [15:0] joystick_5_rumble, + + // paddle 0..255 + output reg [7:0] paddle_0, + output reg [7:0] paddle_1, + output reg [7:0] paddle_2, + output reg [7:0] paddle_3, + output reg [7:0] paddle_4, + output reg [7:0] paddle_5, + + // spinner [7:0] -128..+127, [8] - toggle with every update + output reg [8:0] spinner_0, + output reg [8:0] spinner_1, + output reg [8:0] spinner_2, + output reg [8:0] spinner_3, + output reg [8:0] spinner_4, + output reg [8:0] spinner_5, + + // ps2 keyboard emulation + output ps2_kbd_clk_out, + output ps2_kbd_data_out, + input ps2_kbd_clk_in, + input ps2_kbd_data_in, + + input [2:0] ps2_kbd_led_status, + input [2:0] ps2_kbd_led_use, + + output ps2_mouse_clk_out, + output ps2_mouse_data_out, + input ps2_mouse_clk_in, + input ps2_mouse_data_in, + + // ps2 alternative interface. + + // [8] - extended, [9] - pressed, [10] - toggles with every press/release + output reg [10:0] ps2_key = 0, + + // [24] - toggles with every event + output reg [24:0] ps2_mouse = 0, + output reg [15:0] ps2_mouse_ext = 0, // 15:8 - reserved(additional buttons), 7:0 - wheel movements + + output [1:0] buttons, + output forced_scandoubler, + output direct_video, + input video_rotated, + + //toggle to force notify of video mode change + input new_vmode, + + inout [21:0] gamma_bus, + + output reg [127:0] status, + input [127:0] status_in, + input status_set, + input [15:0] status_menumask, + + input info_req, + input [7:0] info, + + // SD config + output reg [VD:0] img_mounted, // signaling that new image has been mounted + output reg img_readonly, // mounted as read only. valid only for active bit in img_mounted + output reg [63:0] img_size, // size of image in bytes. valid only for active bit in img_mounted + + // SD block level access + input [31:0] sd_lba[VDNUM], + input [5:0] sd_blk_cnt[VDNUM], // number of blocks-1, total size ((sd_blk_cnt+1)*(1<<(BLKSZ+7))) must be <= 16384! + input [VD:0] sd_rd, + input [VD:0] sd_wr, + output reg [VD:0] sd_ack, + + // SD byte level access. Signals for 2-PORT altsyncram. + output reg [AW:0] sd_buff_addr, + output reg [DW:0] sd_buff_dout, + input [DW:0] sd_buff_din[VDNUM], + output reg sd_buff_wr, + + // ARM -> FPGA download + output reg ioctl_download = 0, // signal indicating an active download + output reg [15:0] ioctl_index, // menu index used to upload the file + output reg ioctl_wr, + output reg [26:0] ioctl_addr, // in WIDE mode address will be incremented by 2 + output reg [DW:0] ioctl_dout, + output reg ioctl_upload = 0, // signal indicating an active upload + input ioctl_upload_req, // request to save (must be supported on HPS side for specific core) + input [7:0] ioctl_upload_index, + input [DW:0] ioctl_din, + output reg ioctl_rd, + output reg [31:0] ioctl_file_ext, + input ioctl_wait, + + // [15]: 0 - unset, 1 - set. [1:0]: 0 - none, 1 - 32MB, 2 - 64MB, 3 - 128MB + // [14]: debug mode: [8]: 1 - phase up, 0 - phase down. [7:0]: amount of shift. + output reg [15:0] sdram_sz, + + // RTC MSM6242B layout + output reg [64:0] RTC, + + // Seconds since 1970-01-01 00:00:00 + output reg [32:0] TIMESTAMP, + + // UART flags + output reg [7:0] uart_mode, + output reg [31:0] uart_speed, + + // for core-specific extensions + inout [35:0] EXT_BUS +); + +assign EXT_BUS[31:16] = HPS_BUS[31:16]; +assign EXT_BUS[35:33] = HPS_BUS[35:33]; + +localparam DW = (WIDE) ? 15 : 7; +localparam AW = (WIDE) ? 12 : 13; +localparam VD = VDNUM-1; + +wire io_strobe= HPS_BUS[33]; +wire io_enable= HPS_BUS[34]; +wire fp_enable= HPS_BUS[35]; +wire io_wide = (WIDE) ? 1'b1 : 1'b0; +wire [15:0] io_din = HPS_BUS[31:16]; +reg [15:0] io_dout; + +assign HPS_BUS[37] = ioctl_wait; +assign HPS_BUS[36] = clk_sys; +assign HPS_BUS[32] = io_wide; +assign HPS_BUS[15:0] = EXT_BUS[32] ? EXT_BUS[15:0] : fp_enable ? fp_dout : io_dout; + +reg [15:0] cfg; +assign buttons = cfg[1:0]; +//cfg[2] - vga_scaler handled in sys_top +//cfg[3] - csync handled in sys_top +assign forced_scandoubler = cfg[4]; +//cfg[5] - ypbpr handled in sys_top +assign direct_video = cfg[10]; + +reg [3:0] sdn; +reg [3:0] sd_rrb = 0; +always_comb begin + int n, i; + + sdn = 0; + for(i = VDNUM - 1; i >= 0; i = i - 1) begin + n = i + sd_rrb; + if(n >= VDNUM) n = n - VDNUM; + if(sd_wr[n] | sd_rd[n]) sdn = n[3:0]; + end +end + +///////////////////////////////////////////////////////// + +wire [15:0] vc_dout; +video_calc video_calc +( + .clk_100(HPS_BUS[43]), + .clk_vid(HPS_BUS[42]), + .clk_sys(clk_sys), + .ce_pix(HPS_BUS[41]), + .de(HPS_BUS[40]), + .hs(HPS_BUS[39]), + .vs(HPS_BUS[38]), + .vs_hdmi(HPS_BUS[44]), + .f1(HPS_BUS[45]), + .new_vmode(new_vmode), + .video_rotated(video_rotated), + + .par_num(byte_cnt[4:0]), + .dout(vc_dout) +); + +///////////////////////////////////////////////////////// + +localparam MAX_W = $clog2((64 > (STRLEN+2)) ? 64 : (STRLEN+2))-1; + +wire [7:0] conf_byte; +generate + if(CONF_STR_BRAM) begin + confstr_rom #(CONF_STR, STRLEN) confstr_rom(.*, .conf_addr(byte_cnt - 1'd1)); + end + else begin + assign conf_byte = CONF_STR[{(STRLEN - byte_cnt),3'b000} +:8]; + end +endgenerate + +assign gamma_bus[20:0] = {clk_sys, gamma_en, gamma_wr, gamma_wr_addr, gamma_value}; +reg gamma_en; +reg gamma_wr; +reg [9:0] gamma_wr_addr; +reg [7:0] gamma_value; + +reg [31:0] ps2_key_raw = 0; +wire pressed = (ps2_key_raw[15:8] != 8'hf0); +wire extended = (~pressed ? (ps2_key_raw[23:16] == 8'he0) : (ps2_key_raw[15:8] == 8'he0)); + +reg [MAX_W:0] byte_cnt; +reg [3:0] sdn_ack; +wire [15:0] disk = 16'd1 << io_din[11:8]; + +always@(posedge clk_sys) begin : uio_block + reg [15:0] cmd; + reg [2:0] b_wr; + reg [3:0] stick_idx; + reg [3:0] pdsp_idx; + reg ps2skip = 0; + reg [3:0] stflg = 0; + reg[127:0] status_req; + reg old_status_set = 0; + reg old_upload_req = 0; + reg upload_req = 0; + reg old_info = 0; + reg [7:0] info_n = 0; + reg [15:0] tmp1; + reg [7:0] tmp2; + reg [3:0] sdn_r; + + old_status_set <= status_set; + if(~old_status_set & status_set) begin + stflg <= stflg + 1'd1; + status_req <= status_in; + end + + old_upload_req <= ioctl_upload_req; + if(~old_upload_req & ioctl_upload_req) upload_req <= 1; + + old_info <= info_req; + if(~old_info & info_req) info_n <= info; + + sd_buff_wr <= b_wr[0]; + if(b_wr[2] && (~&sd_buff_addr)) sd_buff_addr <= sd_buff_addr + 1'b1; + b_wr <= (b_wr<<1); + + if(PS2DIV) {kbd_rd,kbd_we,mouse_rd,mouse_we} <= 0; + + gamma_wr <= 0; + + if(~io_enable) begin + if(cmd == 4 && !ps2skip) ps2_mouse[24] <= ~ps2_mouse[24]; + if(cmd == 5 && !ps2skip) begin + ps2_key <= {~ps2_key[10], pressed, extended, ps2_key_raw[7:0]}; + if(ps2_key_raw == 'hE012E07C) ps2_key[9:0] <= 'h37C; // prnscr pressed + if(ps2_key_raw == 'h7CE0F012) ps2_key[9:0] <= 'h17C; // prnscr released + if(ps2_key_raw == 'hF014F077) ps2_key[9:0] <= 'h377; // pause pressed + end + if(cmd == 'h22) RTC[64] <= ~RTC[64]; + if(cmd == 'h24) TIMESTAMP[32] <= ~TIMESTAMP[32]; + cmd <= 0; + byte_cnt <= 0; + sd_ack <= 0; + io_dout <= 0; + ps2skip <= 0; + img_mounted <= 0; + end + else if(io_strobe) begin + + io_dout <= 0; + if(~&byte_cnt) byte_cnt <= byte_cnt + 1'd1; + + if(byte_cnt == 0) begin + cmd <= io_din; + + casex(io_din) + 'h16: begin io_dout <= {1'b1, sd_blk_cnt[sdn], BLKSZ[2:0], sdn, sd_wr[sdn], sd_rd[sdn]}; sdn_r <= sdn; end + 'h0X17, + 'h0X18: begin sd_ack <= disk[VD:0]; sdn_ack <= io_din[11:8]; end + 'h29: io_dout <= {4'hA, stflg}; + 'h32: io_dout <= gamma_bus[21]; + 'h36: begin io_dout <= info_n; info_n <= 0; end + 'h3C: if(upload_req) begin io_dout <= {ioctl_upload_index, 8'd1}; upload_req <= 0; end + 'h43: io_dout <= |F12KEYMOD; + 'h003F: io_dout <= joystick_0_rumble; + 'h013F: io_dout <= joystick_1_rumble; + 'h023F: io_dout <= joystick_2_rumble; + 'h033F: io_dout <= joystick_3_rumble; + 'h043F: io_dout <= joystick_4_rumble; + 'h053F: io_dout <= joystick_5_rumble; + endcase + + sd_buff_addr <= 0; + if(io_din == 5) ps2_key_raw <= 0; + end else begin + + casex(cmd) + // buttons and switches + 'h01: cfg <= io_din; + 'h02: if(byte_cnt==1) joystick_0[15:0] <= io_din; else joystick_0[31:16] <= io_din; + 'h03: if(byte_cnt==1) joystick_1[15:0] <= io_din; else joystick_1[31:16] <= io_din; + 'h10: if(byte_cnt==1) joystick_2[15:0] <= io_din; else joystick_2[31:16] <= io_din; + 'h11: if(byte_cnt==1) joystick_3[15:0] <= io_din; else joystick_3[31:16] <= io_din; + 'h12: if(byte_cnt==1) joystick_4[15:0] <= io_din; else joystick_4[31:16] <= io_din; + 'h13: if(byte_cnt==1) joystick_5[15:0] <= io_din; else joystick_5[31:16] <= io_din; + + // store incoming ps2 mouse bytes + 'h04: begin + if(PS2DIV) begin + mouse_data <= io_din[7:0]; + mouse_we <= 1; + end + if(&io_din[15:8]) ps2skip <= 1; + if(~&io_din[15:8] && ~ps2skip && !byte_cnt[MAX_W:2]) begin + case(byte_cnt[1:0]) + 1: ps2_mouse[7:0] <= io_din[7:0]; + 2: ps2_mouse[15:8] <= io_din[7:0]; + 3: ps2_mouse[23:16] <= io_din[7:0]; + endcase + case(byte_cnt[1:0]) + 1: ps2_mouse_ext[7:0] <= {io_din[14], io_din[14:8]}; + 2: ps2_mouse_ext[11:8] <= io_din[11:8]; + 3: ps2_mouse_ext[15:12]<= io_din[11:8]; + endcase + end + end + + // store incoming ps2 keyboard bytes + 'h05: begin + if(&io_din[15:8]) ps2skip <= 1; + if(~&io_din[15:8] & ~ps2skip) ps2_key_raw[31:0] <= {ps2_key_raw[23:0], io_din[7:0]}; + if(PS2DIV) begin + kbd_data <= io_din[7:0]; + kbd_we <= 1; + end + end + + // reading config string, returning a byte from string + 'h14: if(byte_cnt <= STRLEN) io_dout[7:0] <= conf_byte; + + // reading sd card status + 'h16: if(!byte_cnt[MAX_W:2]) begin + case(byte_cnt[1:0]) + 1: sd_rrb <= (sd_rrb == VD) ? 4'd0 : (sd_rrb + 1'd1); + 2: io_dout <= sd_lba[sdn_r][15:0]; + 3: io_dout <= sd_lba[sdn_r][31:16]; + endcase + end + + // send sector IO -> FPGA + // flag that download begins + 'h0X17: begin + sd_buff_dout <= io_din[DW:0]; + b_wr <= 1; + end + + // reading sd card write data + 'h0X18: begin + if(~&sd_buff_addr) sd_buff_addr <= sd_buff_addr + 1'b1; + io_dout <= sd_buff_din[sdn_ack]; + end + + // joystick left analog + 'h1a: if(!byte_cnt[MAX_W:2]) begin + case(byte_cnt[1:0]) + 1: {pdsp_idx,stick_idx} <= io_din[7:0]; // first byte is joystick index + 2: case(stick_idx) + 0: joystick_l_analog_0 <= io_din; + 1: joystick_l_analog_1 <= io_din; + 2: joystick_l_analog_2 <= io_din; + 3: joystick_l_analog_3 <= io_din; + 4: joystick_l_analog_4 <= io_din; + 5: joystick_l_analog_5 <= io_din; + 15: case(pdsp_idx) + 0: paddle_0 <= io_din[7:0]; + 1: paddle_1 <= io_din[7:0]; + 2: paddle_2 <= io_din[7:0]; + 3: paddle_3 <= io_din[7:0]; + 4: paddle_4 <= io_din[7:0]; + 5: paddle_5 <= io_din[7:0]; + 8: spinner_0 <= {~spinner_0[8],io_din[7:0]}; + 9: spinner_1 <= {~spinner_1[8],io_din[7:0]}; + 10: spinner_2 <= {~spinner_2[8],io_din[7:0]}; + 11: spinner_3 <= {~spinner_3[8],io_din[7:0]}; + 12: spinner_4 <= {~spinner_4[8],io_din[7:0]}; + 13: spinner_5 <= {~spinner_5[8],io_din[7:0]}; + endcase + endcase + endcase + end + + // joystick right analog + 'h3d: if(!byte_cnt[MAX_W:2]) begin + case(byte_cnt[1:0]) + 1: stick_idx <= io_din[3:0]; // first byte is joystick index + 2: case(stick_idx) + 0: joystick_r_analog_0 <= io_din; + 1: joystick_r_analog_1 <= io_din; + 2: joystick_r_analog_2 <= io_din; + 3: joystick_r_analog_3 <= io_din; + 4: joystick_r_analog_4 <= io_din; + 5: joystick_r_analog_5 <= io_din; + endcase + endcase + end + + // notify image selection + 'h1c: begin + img_mounted <= io_din[VD:0] ? io_din[VD:0] : 1'b1; + img_readonly <= io_din[7]; + end + + // send image info + 'h1d: if(byte_cnt<5) img_size[{byte_cnt-1'b1, 4'b0000} +:16] <= io_din; + + // status, 128bit version + 'h1e: if(!byte_cnt[MAX_W:4]) begin + case(byte_cnt[3:0]) + 1: status[15:00] <= io_din; + 2: status[31:16] <= io_din; + 3: status[47:32] <= io_din; + 4: status[63:48] <= io_din; + 5: status[79:64] <= io_din; + 6: status[95:80] <= io_din; + 7: status[111:96] <= io_din; + 8: status[127:112] <= io_din; + endcase + end + + // reading keyboard LED status + 'h1f: io_dout <= {|PS2WE, 2'b01, ps2_kbd_led_status[2], ps2_kbd_led_use[2], ps2_kbd_led_status[1], ps2_kbd_led_use[1], ps2_kbd_led_status[0], ps2_kbd_led_use[0]}; + + // reading ps2 keyboard/mouse control + 'h21: if(PS2DIV) begin + if(byte_cnt == 1) begin + io_dout <= kbd_data_host; + kbd_rd <= 1; + end + else + if(byte_cnt == 2) begin + io_dout <= mouse_data_host; + mouse_rd <= 1; + end + end + + //RTC + 'h22: RTC[(byte_cnt-6'd1)<<4 +:16] <= io_din; + + //Video res. + 'h23: if(!byte_cnt[MAX_W:5]) io_dout <= vc_dout; + + //RTC + 'h24: TIMESTAMP[(byte_cnt-6'd1)<<4 +:16] <= io_din; + + //status set + 'h29: if(!byte_cnt[MAX_W:4]) begin + case(byte_cnt[3:0]) + 1: io_dout <= status_req[15:00]; + 2: io_dout <= status_req[31:16]; + 3: io_dout <= status_req[47:32]; + 4: io_dout <= status_req[63:48]; + 5: io_dout <= status_req[79:64]; + 6: io_dout <= status_req[95:80]; + 7: io_dout <= status_req[111:96]; + 8: io_dout <= status_req[127:112]; + endcase + end + + //menu mask + 'h2E: if(byte_cnt == 1) io_dout <= status_menumask; + + //sdram size set + 'h31: if(byte_cnt == 1) sdram_sz <= io_din; + + // Gamma + 'h32: gamma_en <= io_din[0]; + 'h33: begin + gamma_wr_addr <= {(byte_cnt[1:0]-1'b1),io_din[15:8]}; + {gamma_wr, gamma_value} <= {1'b1,io_din[7:0]}; + if (byte_cnt[1:0] == 3) byte_cnt <= 1; + end + + // UART + 'h3b: if(!byte_cnt[MAX_W:2]) begin + case(byte_cnt[1:0]) + 1: tmp2 <= io_din[7:0]; + 2: tmp1 <= io_din; + 3: {uart_speed, uart_mode} <= {io_din, tmp1, tmp2}; + endcase + end + endcase + end + end +end + + +/////////////////////////////// PS2 /////////////////////////////// +generate + if(PS2DIV) begin + reg clk_ps2; + always @(posedge clk_sys) begin + integer cnt; + cnt <= cnt + 1'd1; + if(cnt == PS2DIV) begin + clk_ps2 <= ~clk_ps2; + cnt <= 0; + end + end + + reg [7:0] kbd_data; + reg kbd_we; + wire [8:0] kbd_data_host; + reg kbd_rd; + + ps2_device keyboard + ( + .clk_sys(clk_sys), + + .wdata(kbd_data), + .we(kbd_we), + + .ps2_clk(clk_ps2), + .ps2_clk_out(ps2_kbd_clk_out), + .ps2_dat_out(ps2_kbd_data_out), + + .ps2_clk_in(ps2_kbd_clk_in || !PS2WE), + .ps2_dat_in(ps2_kbd_data_in || !PS2WE), + + .rdata(kbd_data_host), + .rd(kbd_rd) + ); + + reg [7:0] mouse_data; + reg mouse_we; + wire [8:0] mouse_data_host; + reg mouse_rd; + + ps2_device mouse + ( + .clk_sys(clk_sys), + + .wdata(mouse_data), + .we(mouse_we), + + .ps2_clk(clk_ps2), + .ps2_clk_out(ps2_mouse_clk_out), + .ps2_dat_out(ps2_mouse_data_out), + + .ps2_clk_in(ps2_mouse_clk_in || !PS2WE), + .ps2_dat_in(ps2_mouse_data_in || !PS2WE), + + .rdata(mouse_data_host), + .rd(mouse_rd) + ); + end + else begin + assign ps2_kbd_clk_out = 0; + assign ps2_kbd_data_out = 0; + assign ps2_mouse_clk_out = 0; + assign ps2_mouse_data_out = 0; + end +endgenerate + +/////////////////////////////// DOWNLOADING /////////////////////////////// + +localparam FIO_FILE_TX = 8'h53; +localparam FIO_FILE_TX_DAT = 8'h54; +localparam FIO_FILE_INDEX = 8'h55; +localparam FIO_FILE_INFO = 8'h56; + +reg [15:0] fp_dout; +always@(posedge clk_sys) begin : fio_block + reg [15:0] cmd; + reg [2:0] cnt; + reg has_cmd; + reg wr; + reg [1:0] req_io; + reg skip_add; + + ioctl_rd <= 0; + ioctl_wr <= wr; + wr <= 0; + + if(~fp_enable) begin + if(has_cmd && (cmd == FIO_FILE_TX)) begin + {ioctl_upload, ioctl_download} <= req_io; + skip_add <= req_io[0]; + end + has_cmd <= 0; + end + else begin + if(io_strobe) begin + + if(!has_cmd) begin + cmd <= io_din; + has_cmd <= 1; + cnt <= 0; + req_io <= 0; + end else begin + + case(cmd) + FIO_FILE_INFO: + if(~cnt[1]) begin + case(cnt) + 0: ioctl_file_ext[31:16] <= io_din; + 1: ioctl_file_ext[15:00] <= io_din; + endcase + cnt <= cnt + 1'd1; + end + + FIO_FILE_INDEX: + begin + ioctl_index <= io_din[15:0]; + end + + FIO_FILE_TX: + begin + cnt <= cnt + 1'd1; + case(cnt) + 0: if(io_din[7:0]) begin + ioctl_addr <= 0; + req_io <= (io_din[7:0] == 8'hAA) ? 2'b10 : 2'b01; + end + else begin + if(ioctl_download) ioctl_addr <= ioctl_addr + (WIDE ? 2'd2 : 2'd1); + ioctl_download <= 0; + ioctl_upload <= 0; + end + 1: ioctl_addr[15:0] <= io_din; + 2: ioctl_addr[26:16] <= io_din[10:0]; + endcase + end + + FIO_FILE_TX_DAT: + begin + if(!skip_add) ioctl_addr <= ioctl_addr + (WIDE ? 2'd2 : 2'd1); + skip_add <= 0; + + if(ioctl_download) begin + ioctl_dout <= io_din[DW:0]; + wr <= 1; + end + else begin + fp_dout <= ioctl_din; + ioctl_rd <= 1; + end + end + endcase + end + end + end +end + +endmodule + +////////////////////////////////////////////////////////////////////////////////// + + +module ps2_device #(parameter PS2_FIFO_BITS=5) +( + input clk_sys, + + input [7:0] wdata, + input we, + + input ps2_clk, + output reg ps2_clk_out, + output reg ps2_dat_out, + output reg tx_empty, + + input ps2_clk_in, + input ps2_dat_in, + + output [8:0] rdata, + input rd +); + + +(* ramstyle = "logic" *) reg [7:0] fifo[1<= 1)&&(tx_state < 9)) begin + ps2_dat_out <= tx_byte[0]; // data bits + tx_byte[6:0] <= tx_byte[7:1]; // shift down + if(tx_byte[0]) + parity <= !parity; + end + + // transmission of parity + if(tx_state == 9) ps2_dat_out <= parity; + + // transmission of stop bit + if(tx_state == 10) ps2_dat_out <= 1; // stop bit is 1 + + // advance state machine + if(tx_state < 11) tx_state <= tx_state + 1'd1; + else tx_state <= 0; + end + end + end + + if(~old_clk & ps2_clk) ps2_clk_out <= 1; + if(old_clk & ~ps2_clk) ps2_clk_out <= ((tx_state == 0) && (rx_state<2)); + +end + +endmodule + + +///////////////// calc video parameters ////////////////// +module video_calc +( + input clk_100, + input clk_vid, + input clk_sys, + + input ce_pix, + input de, + input hs, + input vs, + input vs_hdmi, + input f1, + input new_vmode, + input video_rotated, + + input [4:0] par_num, + output reg [15:0] dout +); + +always @(posedge clk_sys) begin + case(par_num) + 1: dout <= {video_rotated, |vid_int, vid_nres}; + 2: dout <= vid_hcnt[15:0]; + 3: dout <= vid_hcnt[31:16]; + 4: dout <= vid_vcnt[15:0]; + 5: dout <= vid_vcnt[31:16]; + 6: dout <= vid_htime[15:0]; + 7: dout <= vid_htime[31:16]; + 8: dout <= vid_vtime[15:0]; + 9: dout <= vid_vtime[31:16]; + 10: dout <= vid_pix[15:0]; + 11: dout <= vid_pix[31:16]; + 12: dout <= vid_vtime_hdmi[15:0]; + 13: dout <= vid_vtime_hdmi[31:16]; + 14: dout <= vid_ccnt[15:0]; + 15: dout <= vid_ccnt[31:16]; + 16: dout <= vid_pixrep; + 17: dout <= vid_de_h; + 18: dout <= vid_de_v; + default dout <= 0; + endcase +end + +reg [31:0] vid_hcnt = 0; +reg [31:0] vid_vcnt = 0; +reg [31:0] vid_ccnt = 0; +reg [7:0] vid_nres = 0; +reg [1:0] vid_int = 0; +reg [7:0] vid_pixrep; +reg [15:0] vid_de_h; +reg [7:0] vid_de_v; + +always @(posedge clk_vid) begin + integer hcnt; + integer vcnt; + integer ccnt; + reg [7:0] pcnt; + reg [7:0] de_v; + reg [15:0] de_h; + reg old_vs = 0, old_hs = 0, old_hs_vclk = 0, old_de = 0, old_de_vclk = 0, old_de1 = 0, old_vmode = 0; + reg [3:0] resto = 0; + reg calch = 0; + + if(calch & de) ccnt <= ccnt + 1; + pcnt <= pcnt + 1'd1; + + old_hs_vclk <= hs; + de_h <= de_h + 1'd1; + if(old_hs_vclk & ~hs) de_h <= 1; + + old_de_vclk <= de; + if(calch & ~old_de_vclk & de) vid_de_h <= de_h; + + if(ce_pix) begin + old_vs <= vs; + old_hs <= hs; + old_de <= de; + old_de1 <= old_de; + pcnt <= 1; + + if(~vs & ~old_de & de) vcnt <= vcnt + 1; + if(calch & de) hcnt <= hcnt + 1; + if(old_de & ~de) calch <= 0; + if(~old_de1 & old_de) vid_pixrep <= pcnt; + if(old_hs & ~hs) de_v <= de_v + 1'd1; + if(calch & ~old_de & de) vid_de_v <= de_v; + + if(old_vs & ~vs) begin + vid_int <= {vid_int[0],f1}; + if(~f1) begin + if(hcnt && vcnt) begin + old_vmode <= new_vmode; + + //report new resolution after timeout + if(resto) resto <= resto + 1'd1; + if(vid_hcnt != hcnt || vid_vcnt != vcnt || old_vmode != new_vmode) resto <= 1; + if(&resto) vid_nres <= vid_nres + 1'd1; + vid_hcnt <= hcnt; + vid_vcnt <= vcnt; + vid_ccnt <= ccnt; + end + vcnt <= 0; + hcnt <= 0; + ccnt <= 0; + calch <= 1; + de_v <= 0; + end + end + end +end + +reg [31:0] vid_htime = 0; +reg [31:0] vid_vtime = 0; +reg [31:0] vid_pix = 0; + +always @(posedge clk_100) begin + integer vtime, htime, hcnt; + reg old_vs, old_hs, old_vs2, old_hs2, old_de, old_de2; + reg calch = 0; + + old_vs <= vs; + old_hs <= hs; + + old_vs2 <= old_vs; + old_hs2 <= old_hs; + + vtime <= vtime + 1'd1; + htime <= htime + 1'd1; + + if(~old_vs2 & old_vs) begin + vid_pix <= hcnt; + vid_vtime <= vtime; + vtime <= 0; + hcnt <= 0; + end + + if(old_vs2 & ~old_vs) calch <= 1; + + if(~old_hs2 & old_hs) begin + vid_htime <= htime; + htime <= 0; + end + + old_de <= de; + old_de2 <= old_de; + + if(calch & old_de) hcnt <= hcnt + 1; + if(old_de2 & ~old_de) calch <= 0; +end + +reg [31:0] vid_vtime_hdmi; +always @(posedge clk_100) begin + integer vtime; + reg old_vs, old_vs2; + + old_vs <= vs_hdmi; + old_vs2 <= old_vs; + + vtime <= vtime + 1'd1; + + if(~old_vs2 & old_vs) begin + vid_vtime_hdmi <= vtime; + vtime <= 0; + end +end + +endmodule + +module confstr_rom #(parameter CONF_STR, STRLEN) +( + input clk_sys, + input [$clog2(STRLEN+1)-1:0] conf_addr, + output reg [7:0] conf_byte +); + +reg [7:0] rom[STRLEN]; + +initial begin + if( CONF_STR=="" ) + $readmemh("cfgstr.hex",rom); + else + for(int i = 0; i < STRLEN; i++) rom[i] = CONF_STR[((STRLEN-i)*8)-1 -:8]; +end + +always @ (posedge clk_sys) conf_byte <= rom[conf_addr]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/hq2x.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/hq2x.sv new file mode 100644 index 0000000000000000000000000000000000000000..f5fcc712bea537a137f6152bc73afce1f423acb5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/hq2x.sv @@ -0,0 +1,371 @@ +// +// +// Copyright (c) 2012-2013 Ludvig Strigeus +// Copyright (c) 2017,2018 Sorgelig +// +// This program is GPL Licensed. See COPYING for the full license. +// +// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +// altera message_off 10030 + +module Hq2x #(parameter LENGTH, parameter HALF_DEPTH) +( + input clk, + + input ce_in, + input [DWIDTH:0] inputpixel, + input mono, + input disable_hq2x, + input reset_frame, + input reset_line, + + input ce_out, + input [1:0] read_y, + input hblank, + output [DWIDTH:0] outpixel +); + + +localparam AWIDTH = $clog2(LENGTH)-1; +localparam DWIDTH = HALF_DEPTH ? 11 : 23; +localparam DWIDTH1 = DWIDTH+1; + +(* romstyle = "MLAB" *) reg [5:0] hqTable[256]; +initial begin + hqTable = '{ + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 47, 35, 23, 15, 55, 39, + 19, 19, 26, 58, 19, 19, 26, 58, 23, 15, 35, 35, 23, 15, 7, 35, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 55, 39, 23, 15, 51, 43, + 19, 19, 26, 58, 19, 19, 26, 58, 23, 15, 51, 35, 23, 15, 7, 43, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 61, 35, 35, 23, 61, 51, 35, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 35, 23, 15, 51, 35, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 61, 7, 35, 23, 61, 7, 43, + 19, 19, 26, 11, 19, 19, 26, 58, 23, 15, 51, 35, 23, 61, 7, 43, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 47, 35, 23, 15, 55, 39, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 35, 23, 15, 51, 35, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 55, 39, 23, 15, 51, 43, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 39, 23, 15, 7, 43, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 35, 23, 15, 51, 39, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 35, 23, 15, 7, 35, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 51, 35, 23, 15, 7, 43, + 19, 19, 26, 11, 19, 19, 26, 11, 23, 15, 7, 35, 23, 15, 7, 43 + }; +end + +wire [5:0] hqrule = hqTable[nextpatt]; + +reg [23:0] Prev0, Prev1, Prev2, Curr0, Curr1, Curr2, Next0, Next1, Next2; +reg [23:0] A, B, D, F, G, H; +reg [7:0] pattern, nextpatt; +reg [1:0] cyc; + +reg curbuf; +reg prevbuf = 0; +wire iobuf = !curbuf; + +wire diff0, diff1; +DiffCheck diffcheck0(Curr1, (cyc == 0) ? Prev0 : (cyc == 1) ? Curr0 : (cyc == 2) ? Prev2 : Next1, diff0); +DiffCheck diffcheck1(Curr1, (cyc == 0) ? Prev1 : (cyc == 1) ? Next0 : (cyc == 2) ? Curr2 : Next2, diff1); + +wire [7:0] new_pattern = {diff1, diff0, pattern[7:2]}; + +wire [23:0] X = (cyc == 0) ? A : (cyc == 1) ? Prev1 : (cyc == 2) ? Next1 : G; +wire [23:0] blend_result_pre; +Blend blender(clk, ce_in, disable_hq2x ? 6'd0 : hqrule, Curr0, X, B, D, F, H, blend_result_pre); + +wire [DWIDTH:0] Curr20tmp; +wire [23:0] Curr20 = HALF_DEPTH ? h2rgb(Curr20tmp) : Curr20tmp; +wire [DWIDTH:0] Curr21tmp; +wire [23:0] Curr21 = HALF_DEPTH ? h2rgb(Curr21tmp) : Curr21tmp; + +reg [AWIDTH:0] wrin_addr2; +reg [DWIDTH:0] wrpix; +reg wrin_en; + +function [23:0] h2rgb; + input [11:0] v; +begin + h2rgb = mono ? {v[7:0], v[7:0], v[7:0]} : {v[11:8],v[11:8],v[7:4],v[7:4],v[3:0],v[3:0]}; +end +endfunction + +function [11:0] rgb2h; + input [23:0] v; +begin + rgb2h = mono ? {4'b0000, v[23:20], v[19:16]} : {v[23:20], v[15:12], v[7:4]}; +end +endfunction + +hq2x_in #(.LENGTH(LENGTH), .DWIDTH(DWIDTH)) hq2x_in +( + .clk(clk), + + .rdaddr(offs), + .rdbuf0(prevbuf), + .rdbuf1(curbuf), + .q0(Curr20tmp), + .q1(Curr21tmp), + + .wraddr(wrin_addr2), + .wrbuf(iobuf), + .data(wrpix), + .wren(wrin_en) +); + +reg [AWIDTH+1:0] read_x; +reg [AWIDTH+1:0] wrout_addr; +reg wrout_en; +reg [DWIDTH1*4-1:0] wrdata, wrdata_pre; +wire [DWIDTH1*4-1:0] outpixel_x4; +reg [DWIDTH1*2-1:0] outpixel_x2; + +assign outpixel = read_x[0] ? outpixel_x2[DWIDTH1*2-1:DWIDTH1] : outpixel_x2[DWIDTH:0]; + +hq2x_buf #(.NUMWORDS(LENGTH*2), .AWIDTH(AWIDTH+1), .DWIDTH(DWIDTH1*4-1)) hq2x_out +( + .clock(clk), + + .rdaddress({read_x[AWIDTH+1:1],read_y[1]}), + .q(outpixel_x4), + + .data(wrdata), + .wraddress(wrout_addr), + .wren(wrout_en) +); + +always @(posedge clk) begin + if(ce_out) begin + if(read_x[0]) outpixel_x2 <= read_y[0] ? outpixel_x4[DWIDTH1*4-1:DWIDTH1*2] : outpixel_x4[DWIDTH1*2-1:0]; + if(~hblank & ~&read_x) read_x <= read_x + 1'd1; + if(hblank) read_x <= 0; + end +end + +wire [DWIDTH:0] blend_result = HALF_DEPTH ? rgb2h(blend_result_pre) : blend_result_pre[DWIDTH:0]; + +reg [AWIDTH:0] offs; +always @(posedge clk) begin + reg old_reset_line; + reg old_reset_frame; + reg [3:0] wrdata_finished; + reg [AWIDTH+1:0] waddr; + + wrout_en <= 0; + wrin_en <= 0; + + if(ce_in) begin + + // blend_result has been delayed by 4 cycles + case(cyc) + 0: wrdata[DWIDTH:0] <= blend_result; + 1: wrdata[DWIDTH1+DWIDTH:DWIDTH1] <= blend_result; + 2: wrdata[DWIDTH1*3+DWIDTH:DWIDTH1*3] <= blend_result; + 3: wrdata[DWIDTH1*2+DWIDTH:DWIDTH1*2] <= blend_result; + endcase + + wrdata_finished <= wrdata_finished << 1; + if(wrdata_finished[3]) begin + wrout_en <= 1; + wrout_addr <= waddr; + end + + if(~&offs) begin + if (cyc == 1) begin + Prev2 <= Curr20; + Curr2 <= Curr21; + Next2 <= HALF_DEPTH ? h2rgb(inputpixel) : inputpixel; + wrpix <= inputpixel; + wrin_addr2 <= offs; + wrin_en <= 1; + end + + if(cyc==3) begin + offs <= offs + 1'd1; + waddr <= {offs, curbuf}; + wrdata_finished[0] <= 1; + end + end + + pattern <= new_pattern; + if(cyc==3) begin + nextpatt <= {new_pattern[7:6], new_pattern[3], new_pattern[5], new_pattern[2], new_pattern[4], new_pattern[1:0]}; + {A, G} <= {Prev0, Next0}; + {B, F, H, D} <= {Prev1, Curr2, Next1, Curr0}; + {Prev0, Prev1} <= {Prev1, Prev2}; + {Curr0, Curr1} <= {Curr1, Curr2}; + {Next0, Next1} <= {Next1, Next2}; + end else begin + nextpatt <= {nextpatt[5], nextpatt[3], nextpatt[0], nextpatt[6], nextpatt[1], nextpatt[7], nextpatt[4], nextpatt[2]}; + {B, F, H, D} <= {F, H, D, B}; + end + + cyc <= cyc + 1'b1; + if(old_reset_line && ~reset_line) begin + old_reset_frame <= reset_frame; + offs <= 0; + cyc <= 0; + curbuf <= ~curbuf; + prevbuf <= curbuf; + {Prev0, Prev1, Prev2, Curr0, Curr1, Curr2, Next0, Next1, Next2} <= '0; + if(old_reset_frame & ~reset_frame) begin + curbuf <= 0; + prevbuf <= 0; + end + end + + old_reset_line <= reset_line; + end +end + +endmodule + +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +module hq2x_in #(parameter LENGTH, parameter DWIDTH) +( + input clk, + + input [AWIDTH:0] rdaddr, + input rdbuf0, rdbuf1, + output[DWIDTH:0] q0,q1, + + input [AWIDTH:0] wraddr, + input wrbuf, + input [DWIDTH:0] data, + input wren +); + +localparam AWIDTH = $clog2(LENGTH)-1; +wire [DWIDTH:0] out[2]; +assign q0 = out[rdbuf0]; +assign q1 = out[rdbuf1]; + +hq2x_buf #(.NUMWORDS(LENGTH), .AWIDTH(AWIDTH), .DWIDTH(DWIDTH)) buf0(clk,data,rdaddr,wraddr,wren && (wrbuf == 0),out[0]); +hq2x_buf #(.NUMWORDS(LENGTH), .AWIDTH(AWIDTH), .DWIDTH(DWIDTH)) buf1(clk,data,rdaddr,wraddr,wren && (wrbuf == 1),out[1]); + +endmodule + +module hq2x_buf #(parameter NUMWORDS, parameter AWIDTH, parameter DWIDTH) +( + input clock, + input [DWIDTH:0] data, + input [AWIDTH:0] rdaddress, + input [AWIDTH:0] wraddress, + input wren, + output reg [DWIDTH:0] q +); + +reg [DWIDTH:0] ram[0:NUMWORDS-1]; + +always_ff@(posedge clock) begin + if(wren) ram[wraddress] <= data; + q <= ram[rdaddress]; +end + +endmodule + +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +module DiffCheck +( + input [23:0] rgb1, + input [23:0] rgb2, + output result +); + + wire [7:0] r = rgb1[7:1] - rgb2[7:1]; + wire [7:0] g = rgb1[15:9] - rgb2[15:9]; + wire [7:0] b = rgb1[23:17] - rgb2[23:17]; + wire [8:0] t = $signed(r) + $signed(b); + wire [9:0] y = $signed(t) + $signed({g[7], g}); + wire [8:0] u = $signed(r) - $signed(b); + wire [9:0] v = $signed({g, 1'b0}) - $signed(t); + + // if y is inside (-96..96) + wire y_inside = (y < 10'h60 || y >= 10'h3a0); + + // if u is inside (-16, 16) + wire u_inside = (!u[8:4] || &u[8:4]); //(u < 9'h10 || u >= 9'h1f0); + + // if v is inside (-24, 24) + wire v_inside = (v < 10'h18 || v >= 10'h3e8); + assign result = !(y_inside && u_inside && v_inside); + +endmodule + +module Blend +( + input clk, + input clk_en, + input [5:0] rule, + input [23:0] E, + input [23:0] A, + input [23:0] B, + input [23:0] D, + input [23:0] F, + input [23:0] H, + output [23:0] Result +); + + localparam BLEND1 = 7'b110_10_00; // (A * 12 + B * 4 ) >> 4 + localparam BLEND2 = 7'b100_10_10; // (A * 8 + B * 4 + C * 4) >> 4 + localparam BLEND3 = 7'b101_10_01; // (A * 10 + B * 4 + C * 2) >> 4 + localparam BLEND4 = 7'b110_01_01; // (A * 12 + B * 2 + C * 2) >> 4 + localparam BLEND5 = 7'b010_11_11; // (A * 4 + B * 6 + C * 6) >> 4 + localparam BLEND6 = 7'b111_00_00; // (A * 14 + B * 1 + C * 1) >> 4 + + reg [23:0] a,b,d,e,h,f; + reg [3:0] bl_rule; + reg [1:0] df_rule; + always @(posedge clk) if (clk_en) begin + {bl_rule,df_rule} <= rule; + a <= A; b <= B; d <= D; e <= E; f <= F; h <= H; + end + + wire is_diff; + DiffCheck diff_checker(df_rule[1] ? b : h, df_rule[0] ? d : f, is_diff); + + reg [23:0] i10,i20,i30; + reg [6:0] op0; + always @(posedge clk) if (clk_en) begin + i10 <= e; + case({!is_diff, bl_rule}) + 1,11,12,13,17: {op0, i20, i30} <= {BLEND1, a, 24'd0}; + 2,14,18: {op0, i20, i30} <= {BLEND1, d, 24'd0}; + 3,15,19: {op0, i20, i30} <= {BLEND1, b, 24'd0}; + 4,20,24,27: {op0, i20, i30} <= {BLEND2, d, b}; + 5,21: {op0, i20, i30} <= {BLEND2, a, b}; + 6,22: {op0, i20, i30} <= {BLEND2, a, d}; + 25,29: {op0, i20, i30} <= {BLEND5, d, b}; + 26: {op0, i20, i30} <= {BLEND6, d, b}; + 28: {op0, i20, i30} <= {BLEND4, d, b}; + 30: {op0, i20, i30} <= {BLEND3, b, d}; + 31: {op0, i20, i30} <= {BLEND3, d, b}; + default: {op0, i20, i30} <= {BLEND1, e, 24'd0}; + endcase + end + + reg [23:0] i1,i2,i3; + reg [6:0] op; + always @(posedge clk) if (clk_en) begin + op <= op0; i1 <= i10; i2 <= i20; i3 <= i30; + end + + function [34:0] mul24x3; + input [23:0] op1; + input [2:0] op2; + begin + mul24x3 = 0; + if(op2[0]) mul24x3 = mul24x3 + {op1[23:16], 4'b0000, op1[15:8], 4'b0000, op1[7:0]}; + if(op2[1]) mul24x3 = mul24x3 + {op1[23:16], 4'b0000, op1[15:8], 4'b0000, op1[7:0], 1'b0}; + if(op2[2]) mul24x3 = mul24x3 + {op1[23:16], 4'b0000, op1[15:8], 4'b0000, op1[7:0], 2'b00}; + end + endfunction + + wire [35:0] res = {mul24x3(i1, op[6:4]), 1'b0} + mul24x3(i2, {op[3:2], !op[3:2]}) + mul24x3(i3, {op[1:0], !op[3:2]}); + + always @(posedge clk) if (clk_en) Result <= {res[35:28],res[23:16],res[11:4]}; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/i2c.v b/MiSTer-devel_NeoGeo_MiSTer/sys/i2c.v new file mode 100644 index 0000000000000000000000000000000000000000..6da6a144dcf8ac509cd892fc24c1392f6d9ceebc --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/i2c.v @@ -0,0 +1,103 @@ + +module i2c +( + input CLK, + + input START, + input READ, + input [6:0] I2C_ADDR, + input I2C_WLEN, // 0 - one byte, 1 - two bytes + input [7:0] I2C_WDATA1, + input [7:0] I2C_WDATA2, + output [7:0] I2C_RDATA, + output reg END = 1, + output reg ACK = 0, + + //I2C bus + output I2C_SCL, + inout I2C_SDA +); + + +// Clock Setting +parameter CLK_Freq = 50_000_000; // 50 MHz +parameter I2C_Freq = 400_000; // 400 KHz + +localparam I2C_FreqX2 = I2C_Freq*2; + +reg I2C_CLOCK; +reg [31:0] cnt; +wire [31:0] cnt_next = cnt + I2C_FreqX2; + +always @(posedge CLK) begin + cnt <= cnt_next; + if(cnt_next >= CLK_Freq) begin + cnt <= cnt_next - CLK_Freq; + I2C_CLOCK <= ~I2C_CLOCK; + end +end + +assign I2C_SCL = (SCLK | I2C_CLOCK) ? 1'bZ : 1'b0; +assign I2C_SDA = SDO[3] ? 1'bz : 1'b0; + +reg SCLK; +reg [3:0] SDO; +reg [0:7] rdata; + +reg [5:0] SD_COUNTER; +reg [0:31] SD; + +initial begin + SD_COUNTER = 'b111111; + SD = 'hFFFF; + SCLK = 1; + SDO = 4'b1111; +end + +assign I2C_RDATA = rdata; + +always @(posedge CLK) begin + reg old_clk; + reg old_st; + reg rd,len; + + old_clk <= I2C_CLOCK; + old_st <= START; + + // delay to make sure SDA changed while SCL is stabilized at low + if(old_clk && ~I2C_CLOCK && ~SD_COUNTER[5]) SDO[0] <= SD[SD_COUNTER[4:0]]; + SDO[3:1] <= SDO[2:0]; + + if(~old_st && START) begin + SCLK <= 1; + SDO <= 4'b1111; + ACK <= 0; + END <= 0; + rd <= READ; + len <= I2C_WLEN; + if(READ) SD <= {2'b10, I2C_ADDR, 1'b1, 1'b1, 8'b11111111, 1'b1, 3'b011, 9'b111111111}; + else SD <= {2'b10, I2C_ADDR, 1'b0, 1'b1, I2C_WDATA1, 1'b1, I2C_WDATA2, 4'b1011}; + SD_COUNTER <= 0; + end else begin + if(~old_clk && I2C_CLOCK && ~&SD_COUNTER) begin + SD_COUNTER <= SD_COUNTER + 6'd1; + case(SD_COUNTER) + 01: SCLK <= 0; + 10: ACK <= ACK | I2C_SDA; + 19: if(~rd) begin + ACK <= ACK | I2C_SDA; + if(~len) SD_COUNTER <= 29; + end + 20: if(rd) SCLK <= 1; + 23: if(rd) END <= 1; + 28: if(~rd) ACK <= ACK | I2C_SDA; + 29: if(~rd) SCLK <= 1; + 32: if(~rd) END <= 1; + endcase + + if(SD_COUNTER >= 11 && SD_COUNTER <= 18) rdata[SD_COUNTER[4:0]-11] <= I2C_SDA; + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/i2s.v b/MiSTer-devel_NeoGeo_MiSTer/sys/i2s.v new file mode 100644 index 0000000000000000000000000000000000000000..7d4517bac6625a9fa104a862e7327122ebf8c9b4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/i2s.v @@ -0,0 +1,54 @@ + +module i2s +#( + parameter AUDIO_DW = 16 +) +( + input reset, + input clk, + input ce, + + output reg sclk, + output reg lrclk, + output reg sdata, + + input [AUDIO_DW-1:0] left_chan, + input [AUDIO_DW-1:0] right_chan +); + +always @(posedge clk) begin + reg [7:0] bit_cnt; + reg msclk; + + reg [AUDIO_DW-1:0] left; + reg [AUDIO_DW-1:0] right; + + if (reset) begin + bit_cnt <= 1; + lrclk <= 1; + sclk <= 1; + msclk <= 1; + end + else begin + sclk <= msclk; + if(ce) begin + msclk <= ~msclk; + if(msclk) begin + if(bit_cnt >= AUDIO_DW) begin + bit_cnt <= 1; + lrclk <= ~lrclk; + if(lrclk) begin + left <= left_chan; + right <= right_chan; + end + end + else begin + bit_cnt <= bit_cnt + 1'd1; + end + sdata <= lrclk ? right[AUDIO_DW - bit_cnt] : left[AUDIO_DW - bit_cnt]; + end + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/iir_filter.v b/MiSTer-devel_NeoGeo_MiSTer/sys/iir_filter.v new file mode 100644 index 0000000000000000000000000000000000000000..b8bcf4f008e39a02d77bc9d37436405aa87dd9ea --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/iir_filter.v @@ -0,0 +1,213 @@ + +// 3-tap IIR filter for 2 channels. +// Copyright (C) 2020 Sorgelig +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +// +// Can be converted to 2-tap (coeff_x2 = 0, coeff_y2 = 0) or 1-tap (coeff_x1,2 = 0, coeff_y1,2 = 0) +// +module IIR_filter +#( + parameter use_params = 1, // set to 1 to use following parameters, 0 for input port variables. + parameter stereo = 1, // 0 for mono (input_l) + + parameter coeff_x = 0.00000774701983513660, // Base gain value for X. Float. Range: 0.0 ... 0.999(9) + parameter coeff_x0 = 3, // Gain scale factor for X0. Integer. Range -7 ... +7 + parameter coeff_x1 = 3, // Gain scale factor for X1. Integer. Range -7 ... +7 + parameter coeff_x2 = 1, // Gain scale factor for X2. Integer. Range -7 ... +7 + parameter coeff_y0 = -2.96438150626551080000, // Coefficient for Y0. Float. Range -3.999(9) ... 3.999(9) + parameter coeff_y1 = 2.92939452735121100000, // Coefficient for Y1. Float. Range -3.999(9) ... 3.999(9) + parameter coeff_y2 = -0.96500747158831091000 // Coefficient for Y2. Float. Range -3.999(9) ... 3.999(9) +) +( + input clk, + input reset, + + input ce, // must be double of calculated rate for stereo! + input sample_ce, // desired output sample rate + + input [39:0] cx, + input [7:0] cx0, + input [7:0] cx1, + input [7:0] cx2, + input [23:0] cy0, + input [23:0] cy1, + input [23:0] cy2, + + input [15:0] input_l, input_r, // signed samples + output [15:0] output_l, output_r // signed samples +); + +localparam [39:0] pcoeff_x = coeff_x * 40'h8000000000; +localparam [31:0] pcoeff_y0 = coeff_y0 * 24'h200000; +localparam [31:0] pcoeff_y1 = coeff_y1 * 24'h200000; +localparam [31:0] pcoeff_y2 = coeff_y2 * 24'h200000; + +wire [39:0] vcoeff = use_params ? pcoeff_x : cx; +wire [23:0] vcoeff_y0 = use_params ? pcoeff_y0[23:0] : cy0; +wire [23:0] vcoeff_y1 = use_params ? pcoeff_y1[23:0] : cy1; +wire [23:0] vcoeff_y2 = use_params ? pcoeff_y2[23:0] : cy2; + +wire [59:0] inp_mul = $signed(inp) * $signed(vcoeff); + +wire [39:0] x = inp_mul[59:20]; +wire [39:0] y = x + tap0; + +wire [39:0] tap0; +iir_filter_tap iir_tap_0 +( + .clk(clk), + .reset(reset), + .ce(ce), + .ch(ch), + .cx(use_params ? coeff_x0[7:0] : cx0), + .cy(vcoeff_y0), + .x(x), + .y(y), + .z(tap1), + .tap(tap0) +); + +wire [39:0] tap1; +iir_filter_tap iir_tap_1 +( + .clk(clk), + .reset(reset), + .ce(ce), + .ch(ch), + .cx(use_params ? coeff_x1[7:0] : cx1), + .cy(vcoeff_y1), + .x(x), + .y(y), + .z(tap2), + .tap(tap1) +); + +wire [39:0] tap2; +iir_filter_tap iir_tap_2 +( + .clk(clk), + .reset(reset), + .ce(ce), + .ch(ch), + .cx(use_params ? coeff_x2[7:0] : cx2), + .cy(vcoeff_y2), + .x(x), + .y(y), + .z(0), + .tap(tap2) +); + +wire [15:0] y_clamp = (~y[39] & |y[38:35]) ? 16'h7FFF : (y[39] & ~&y[38:35]) ? 16'h8000 : y[35:20]; + +reg ch = 0; +reg [15:0] out_l, out_r, out_m; +reg [15:0] inp, inp_m; +always @(posedge clk) if (ce) begin + if(!stereo) begin + ch <= 0; + inp <= input_l; + out_l <= y_clamp; + out_r <= y_clamp; + end + else begin + ch <= ~ch; + if(ch) begin + out_m <= y_clamp; + inp <= inp_m; + end + else begin + out_l <= out_m; + out_r <= y_clamp; + inp <= input_l; + inp_m <= input_r; + end + end +end + +reg [31:0] out; +always @(posedge clk) if (sample_ce) out <= {out_l, out_r}; + +assign {output_l, output_r} = out; + +endmodule + +module iir_filter_tap +( + input clk, + input reset, + + input ce, + input ch, + + input [7:0] cx, + input [23:0] cy, + + input [39:0] x, + input [39:0] y, + input [39:0] z, + output [39:0] tap +); + +wire signed [60:0] y_mul = $signed(y[36:0]) * $signed(cy); + +function [39:0] x_mul; + input [39:0] x; +begin + x_mul = 0; + if(cx[0]) x_mul = x_mul + {{4{x[39]}}, x[39:4]}; + if(cx[1]) x_mul = x_mul + {{3{x[39]}}, x[39:3]}; + if(cx[2]) x_mul = x_mul + {{2{x[39]}}, x[39:2]}; + if(cx[7]) x_mul = ~x_mul; //cheap NEG +end +endfunction + +(* ramstyle = "logic" *) reg [39:0] intreg[2]; +always @(posedge clk, posedge reset) begin + if(reset) {intreg[0],intreg[1]} <= 80'd0; + else if(ce) intreg[ch] <= x_mul(x) - y_mul[60:21] + z; +end + +assign tap = intreg[ch]; + +endmodule + +// simplified IIR 1-tap. +module DC_blocker +( + input clk, + input ce, // 48/96 KHz + input mute, + + input sample_rate, + input [15:0] din, + output [15:0] dout +); + +wire [39:0] x = {din[15], din, 23'd0}; +wire [39:0] x0 = x - (sample_rate ? {{11{x[39]}}, x[39:11]} : {{10{x[39]}}, x[39:10]}); +wire [39:0] y1 = y - (sample_rate ? {{10{y[39]}}, y[39:10]} : {{09{y[39]}}, y[39:09]}); +wire [39:0] y0 = x0 - x1 + y1; + +reg [39:0] x1, y; +always @(posedge clk) if(ce) begin + x1 <= x0; + y <= ^y0[39:38] ? {{2{y0[39]}},{38{y0[38]}}} : y0; +end + +assign dout = mute ? 16'd0 : y[38:23]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/ltc2308.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/ltc2308.sv new file mode 100644 index 0000000000000000000000000000000000000000..4d3ccc1590057222ba6c461bf89443a31672952e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/ltc2308.sv @@ -0,0 +1,162 @@ +//============================================================================ +// +// LTC2308 controller +// Copyright (C) 2019 Sorgelig +// +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + + +// NUM_CH 1..8 +// Sampling rate = ADC_RATE/NUM_CH +// ADC_RATE max is ~500KHz +// CLK_RATE max is ~80MHz +module ltc2308 #(parameter NUM_CH = 2, ADC_RATE = 96000, CLK_RATE = 50000000) +( + input reset, + input clk, + + inout [3:0] ADC_BUS, + + output reg dout_sync, // toggle with every ADC round + output reg [(NUM_CH*12)-1:0] dout // 12 bits per channel (unsigned) +); + +localparam TCONV = CLK_RATE/625000; + +reg sck; +wire sdo = cfg[5]; + +assign ADC_BUS[3] = sck; +wire sdi = ADC_BUS[2]; +assign ADC_BUS[1] = sdo; +assign ADC_BUS[0] = convst; + +reg convst; +reg [5:0] cfg; + +reg [31:0] sum; +wire [31:0] next_sum = sum + ADC_RATE; + +reg [2:0] pin; +wire [2:0] next_pin = (pin == (NUM_CH-1)) ? 3'd0 : (pin + 1'd1); + +always @(posedge clk) begin + reg [7:0] tconv; + reg [3:0] bitcnt; + reg [10:0] adcin; + + convst <= 0; + + if(reset) begin + sum <= 0; + tconv <= 0; + bitcnt <= 0; + sck <= 0; + cfg <= 0; + dout <= 0; + pin <= NUM_CH[2:0]-1'd1; + end + else begin + sum <= next_sum; + if(next_sum >= CLK_RATE) begin + sum <= next_sum - CLK_RATE; + tconv <= TCONV[7:0]; + convst <= 1; + bitcnt <= 12; + cfg <= {1'b1, next_pin[0], next_pin[2:1], 1'b1, 1'b0}; + if(!next_pin) dout_sync <= ~dout_sync; + end + + if(tconv) tconv <= tconv - 1'd1; + else if(bitcnt) begin + sck <= ~sck; + + if(sck) cfg <= cfg<<1; + else begin + adcin <= {adcin[9:0],sdi}; + bitcnt <= bitcnt - 1'd1; + if(bitcnt == 1) begin + dout[pin*12 +:12] <= {adcin,sdi}; + pin <= next_pin; + end + end + end + else sck <= 0; + end +end + +endmodule + +module ltc2308_tape #(parameter HIST_LOW = 16, HIST_HIGH = 64, ADC_RATE = 48000, CLK_RATE = 50000000, NUM_CH = 1) +( + input reset, + input clk, + + inout [3:0] ADC_BUS, + output reg dout, + output active, + output adc_sync, + output [(NUM_CH*12)-1:0] adc_data +); + +ltc2308 #(NUM_CH, ADC_RATE, CLK_RATE) adc +( + .reset(reset), + .clk(clk), + + .ADC_BUS(ADC_BUS), + .dout(adc_data), + .dout_sync(adc_sync) +); + +always @(posedge clk) begin + reg [13:0] data1,data2,data3,data4, sum; + reg adc_sync_d; + + adc_sync_d<=adc_sync; + if(adc_sync_d ^ adc_sync) begin + data1 <= data2; + data2 <= data3; + data3 <= data4; + data4 <= adc_data[11:0]; + + sum <= data1+data2+data3+data4; + + if(sum[13:2]HIST_HIGH) dout <= 1; + end +end + +assign active = |act; + +reg [1:0] act; +always @(posedge clk) begin + reg [31:0] onesec; + reg old_dout; + + onesec <= onesec + 1; + if(onesec>CLK_RATE) begin + onesec <= 0; + if(act) act <= act - 1'd1; + end + + old_dout <= dout; + if(old_dout ^ dout) act <= 2; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/math.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/math.sv new file mode 100644 index 0000000000000000000000000000000000000000..e7c0144b09463d42333530947b2607143ab8d8b9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/math.sv @@ -0,0 +1,109 @@ + +// result = num/div +module sys_udiv +#( + parameter NB_NUM, + parameter NB_DIV +) +( + input clk, + input start, + output busy, + + input [NB_NUM-1:0] num, + input [NB_DIV-1:0] div, + output reg [NB_NUM-1:0] result, + output reg [NB_DIV-1:0] remainder +); + +reg run; +assign busy = run; + +always @(posedge clk) begin + reg [5:0] cpt; + reg [NB_NUM+NB_DIV+1:0] rem; + + if (start) begin + cpt <= 0; + run <= 1; + rem <= num; + end + else if (run) begin + cpt <= cpt + 1'd1; + run <= (cpt != NB_NUM + 1'd1); + remainder <= rem[NB_NUM+NB_DIV:NB_NUM+1]; + if (!rem[NB_DIV + NB_NUM + 1'd1]) + rem <= {rem[NB_DIV+NB_NUM:0] - (div << NB_NUM),1'b0}; + else + rem <= {rem[NB_DIV+NB_NUM:0] + (div << NB_NUM),1'b0}; + result <= {result[NB_NUM-2:0], !rem[NB_DIV + NB_NUM + 1'd1]}; + end +end + +endmodule + +// result = mul1*mul2 +module sys_umul +#( + parameter NB_MUL1, + parameter NB_MUL2 +) +( + input clk, + input start, + output busy, + + input [NB_MUL1-1:0] mul1, + input [NB_MUL2-1:0] mul2, + output reg [NB_MUL1+NB_MUL2-1:0] result +); + +reg run; +assign busy = run; + +always @(posedge clk) begin + reg [NB_MUL1+NB_MUL2-1:0] add; + reg [NB_MUL2-1:0] map; + + if (start) begin + run <= 1; + result <= 0; + add <= mul1; + map <= mul2; + end + else if (run) begin + if(!map) run <= 0; + if(map[0]) result <= result + add; + add <= add << 1; + map <= map >> 1; + end +end + +endmodule + +// result = (mul1*mul2)/div +module sys_umuldiv +#( + parameter NB_MUL1, + parameter NB_MUL2, + parameter NB_DIV +) +( + input clk, + input start, + output busy, + + input [NB_MUL1-1:0] mul1, + input [NB_MUL2-1:0] mul2, + input [NB_DIV-1:0] div, + output [NB_MUL1+NB_MUL2-1:0] result, + output [NB_DIV-1:0] remainder +); + +wire mul_run; +wire [NB_MUL1+NB_MUL2-1:0] mul_res; +sys_umul #(NB_MUL1,NB_MUL2) umul(clk,start,mul_run,mul1,mul2,mul_res); + +sys_udiv #(NB_MUL1+NB_MUL2,NB_DIV) udiv(clk,start|mul_run,busy,mul_res,div,result,remainder); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/mcp23009.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/mcp23009.sv new file mode 100644 index 0000000000000000000000000000000000000000..82eaf37f140d4fc60c227d3913d0ff5fac5ea43e --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/mcp23009.sv @@ -0,0 +1,120 @@ +// +// MCP23009 +// (C) 2019 Alexey Melnikov +// +module mcp23009 +( + input clk, + + output reg [2:0] btn, + input [2:0] led, + output reg flg_sd_cd, + output reg flg_present, + output reg flg_mode, + + output scl, + inout sda +); + + +reg start = 0; +wire ready; +wire error; +reg rw; +wire [7:0] dout; +reg [15:0] din; + +i2c #(50_000_000, 500_000) i2c +( + .CLK(clk), + .START(start), + .READ(rw), + .I2C_ADDR('h20), + .I2C_WLEN(1), + .I2C_WDATA1(din[15:8]), + .I2C_WDATA2(din[7:0]), + .I2C_RDATA(dout), + .END(ready), + .ACK(error), + .I2C_SCL(scl), + .I2C_SDA(sda) +); + +always@(posedge clk) begin + reg [3:0] idx = 0; + reg [1:0] state = 0; + reg [15:0] timeout = 0; + + if(~&timeout) begin + timeout <= timeout + 1'd1; + start <= 0; + state <= 0; + idx <= 0; + btn <= 0; + rw <= 0; + flg_sd_cd <= 1; + flg_present <= 0; + flg_mode <= 1; + end + else begin + if(~&init_data[idx]) begin + case(state) + 0: begin + start <= 1; + state <= 1; + din <= init_data[idx]; + end + 1: if(~ready) state <= 2; + 2: begin + start <= 0; + if(ready) begin + state <= 0; + if(!error) idx <= idx + 1'd1; + end + end + endcase + end + else begin + case(state) + 0: begin + start <= 1; + state <= 1; + din <= {8'h09,5'b00000,led}; + end + 1: if(~ready) state <= 2; + 2: begin + start <= 0; + if(ready) begin + state <= 0; + rw <= 0; + if(!error) begin + if(rw) begin + {flg_sd_cd, flg_mode, btn} <= {dout[7:3]}; + flg_present <= 1; + end + rw <= ~rw; + end + end + end + endcase + end + end +end + +wire [15:0] init_data[12] = +'{ + 16'h00F8, + 16'h0138, + 16'h0200, + 16'h0300, + 16'h0400, + 16'h0524, + 16'h06FF, + 16'h0700, + 16'h0800, + 16'h0900, + 16'h0A00, + 16'hFFFF +}; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/mt32pi.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/mt32pi.sv new file mode 100644 index 0000000000000000000000000000000000000000..67048074f68e84fcb7d1a1946494cc3f609fa52a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/mt32pi.sv @@ -0,0 +1,283 @@ +// +// Communication module to MT32-pi (external MIDI emulator on RPi) +// (C) 2020 Sorgelig, Kitrinx +// +// https://github.com/dwhinham/mt32-pi +// + +module mt32pi +( + input CLK_AUDIO, + + input CLK_VIDEO, + input CE_PIXEL, + input VGA_VS, + input VGA_DE, + + input [6:0] USER_IN, + output [6:0] USER_OUT, + + input reset, + input midi_tx, + output midi_rx, + + output reg [15:0] mt32_i2s_r, + output reg [15:0] mt32_i2s_l, + + output reg mt32_available, + + input mt32_mode_req, + input [1:0] mt32_rom_req, + input [7:0] mt32_sf_req, + + output reg [7:0] mt32_mode, + output reg [7:0] mt32_rom, + output reg [7:0] mt32_sf, + output reg mt32_newmode, + + output reg mt32_lcd_en, + output reg mt32_lcd_pix, + output reg mt32_lcd_update +); + +// +// Pin | USB Name | Signal +// ----+----------+-------------- +// 0 | D+ | I/O I2C_SDA / RX (midi in) +// 1 | D- | O TX (midi out) +// 2 | TX- | I I2S_WS (1 == right) +// 3 | GND_d | I I2C_SCL +// 4 | RX+ | I I2S_BCLK +// 5 | RX- | I I2S_DAT +// 6 | TX+ | - none +// + +assign USER_OUT[0] = sda_out; +assign USER_OUT[1] = midi_tx; +assign USER_OUT[6:2] = '1; + + +// +// crossed/straight cable selection +// + +generate + genvar i; + for(i = 0; i<2; i++) begin : clk_rate + wire clk_in = i ? USER_IN[6] : USER_IN[4]; + reg [4:0] cnt; + always @(posedge CLK_AUDIO) begin : clkr + reg clk_sr, clk, old_clk; + reg [4:0] cnt_tmp; + + clk_sr <= clk_in; + if (clk_sr == clk_in) clk <= clk_sr; + + if(~&cnt_tmp) cnt_tmp <= cnt_tmp + 1'd1; + else cnt <= '1; + + old_clk <= clk; + if(~old_clk & clk) begin + cnt <= cnt_tmp; + cnt_tmp <= 0; + end + end + end + + reg crossed; + always @(posedge CLK_AUDIO) crossed <= (clk_rate[0].cnt <= clk_rate[1].cnt); +endgenerate + +wire i2s_ws = crossed ? USER_IN[2] : USER_IN[5]; +wire i2s_data = crossed ? USER_IN[5] : USER_IN[2]; +wire i2s_bclk = crossed ? USER_IN[4] : USER_IN[6]; +assign midi_rx = ~mt32_available ? USER_IN[0] : crossed ? USER_IN[6] : USER_IN[4]; + + +// +// i2s receiver +// + +always @(posedge CLK_AUDIO) begin : i2s_proc + reg [15:0] i2s_buf = 0; + reg [4:0] i2s_cnt = 0; + reg clk_sr; + reg i2s_clk = 0; + reg old_clk, old_ws; + reg i2s_next = 0; + + // Debounce clock + clk_sr <= i2s_bclk; + if (clk_sr == i2s_bclk) i2s_clk <= clk_sr; + + // Latch data and ws on rising edge + old_clk <= i2s_clk; + if (i2s_clk && ~old_clk) begin + + if (~i2s_cnt[4]) begin + i2s_cnt <= i2s_cnt + 1'd1; + i2s_buf[~i2s_cnt[3:0]] <= i2s_data; + end + + // Word Select will change 1 clock before the new word starts + old_ws <= i2s_ws; + if (old_ws != i2s_ws) i2s_next <= 1; + end + + if (i2s_next) begin + i2s_next <= 0; + i2s_cnt <= 0; + i2s_buf <= 0; + + if (i2s_ws) mt32_i2s_l <= i2s_buf; + else mt32_i2s_r <= i2s_buf; + end + + if (reset) begin + i2s_buf <= 0; + mt32_i2s_l <= 0; + mt32_i2s_r <= 0; + end +end + + +// +// i2c slave +// + +reg sda_out; +reg [7:0] lcd_data[1024]; +reg lcd_sz; + +reg reset_r = 0; +wire [7:0] mode_req = reset_r ? 8'hA0 : mt32_mode_req ? 8'hA2 : 8'hA1; +wire [7:0] rom_req = {6'd0, mt32_rom_req}; + +always @(posedge CLK_AUDIO) begin : i2c_slave + reg sda_sr, scl_sr; + reg old_sda, old_scl; + reg sda, scl; + reg [7:0] tmp; + reg [3:0] cnt = 0; + reg [10:0] bcnt = 0; + reg ack; + reg i2c_rw; + reg disp, dispdata; + reg [2:0] div; + reg old_reset; + + old_reset <= reset; + if(old_reset & ~reset) sda_out <= 1; + + div <= div + 1'd1; + if(!div) begin + sda_sr <= USER_IN[0]; + if(sda_sr == USER_IN[0]) sda <= sda_sr; + old_sda <= sda; + + scl_sr <= USER_IN[3]; + if(scl_sr == USER_IN[3]) scl <= scl_sr; + old_scl <= scl; + + //start + if(old_scl & scl & old_sda & ~sda) begin + cnt <= 9; + bcnt <= 0; + ack <= 0; + i2c_rw <= 0; + disp <= 0; + dispdata <= 0; + end + + //stop + if(old_scl & scl & ~old_sda & sda) begin + cnt <= 0; + if(dispdata) begin + lcd_sz <= ~bcnt[9]; + mt32_lcd_update <= ~mt32_lcd_update; + end + end + + //data latch + if(~old_scl && scl && cnt) begin + tmp <= {tmp[6:0], sda}; + cnt <= cnt - 1'd1; + end + + if(!cnt) sda_out <= 1; + + //data set + if(old_scl && ~scl) begin + sda_out <= 1; + if(cnt == 1) begin + if(!bcnt) begin + if(tmp[7:1] == 'h45 || tmp[7:1] == 'h3c) begin + disp <= (tmp[7:1] == 'h3c); + sda_out <= 0; + mt32_available <= 1; + ack <= 1; + i2c_rw <= tmp[0]; + bcnt <= bcnt + 1'd1; + cnt <= 10; + end + else begin + // wrong address, stop + cnt <= 0; + end + end + else if(ack) begin + if(~i2c_rw) begin + if(disp) begin + if(bcnt == 1) dispdata <= (tmp[7:6] == 2'b01); + else if(dispdata) lcd_data[bcnt[9:0] - 2'd2] <= tmp; + end + else begin + if(bcnt == 1) mt32_mode <= tmp; + if(bcnt == 2) mt32_rom <= tmp; + if(bcnt == 3) mt32_sf <= tmp; + if(bcnt == 3) mt32_newmode <= ~mt32_newmode; + end + end + if(~&bcnt) bcnt <= bcnt + 1'd1; + sda_out <= 0; + cnt <= 10; + end + end + else if(i2c_rw && ack && cnt && ~disp) begin + if(bcnt == 1) sda_out <= mode_req[cnt[2:0] - 2'd2]; + if(bcnt == 2) sda_out <= rom_req[cnt[2:0] - 2'd2]; + if(bcnt == 3) sda_out <= mt32_sf_req[cnt[2:0] - 2'd2]; + if(bcnt == 3) reset_r <= 0; + end + end + end + + if(reset) begin + reset_r <= 1; + mt32_available <= 0; + end +end + +always @(posedge CLK_VIDEO) begin + reg old_de, old_vs; + reg [7:0] hcnt; + reg [6:0] vcnt; + reg [7:0] sh; + + if(CE_PIXEL) begin + old_de <= VGA_DE; + old_vs <= VGA_VS; + + if(~&hcnt) hcnt <= hcnt + 1'd1; + sh <= (sh << 1) | (~old_de & VGA_DE); + if(sh[7]) hcnt <= 0; + + if(old_de & ~VGA_DE & ~&vcnt) vcnt <= vcnt + 1'd1; + if(~old_vs & VGA_VS) vcnt <= 0; + + mt32_lcd_en <= mt32_available & ~hcnt[7] && (lcd_sz ? !vcnt[6] : !vcnt[6:5]); + mt32_lcd_pix <= lcd_data[{vcnt[5:3],hcnt[6:0]}][vcnt[2:0]]; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/osd.v b/MiSTer-devel_NeoGeo_MiSTer/sys/osd.v new file mode 100644 index 0000000000000000000000000000000000000000..724ab95d879fb2993e26a704248f54429a1dae9f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/osd.v @@ -0,0 +1,286 @@ +// A simple OSD implementation. Can be hooked up between a cores +// VGA output and the physical VGA pins + +module osd +( + input clk_sys, + input io_osd, + input io_strobe, + input [15:0] io_din, + + input clk_video, + input [23:0] din, + input de_in, + input vs_in, + input hs_in, + output [23:0] dout, + output reg de_out, + output reg vs_out, + output reg hs_out, + + output reg osd_status +); + +parameter OSD_COLOR = 3'd4; + +localparam OSD_WIDTH = 12'd256; +localparam OSD_HEIGHT = 12'd64; + +`ifdef MENU_CORE +localparam OSD_HDR = 12'd24; +`else +localparam OSD_HDR = 12'd0; +`endif + +reg osd_enable; +(* ramstyle="no_rw_check" *) reg [7:0] osd_buffer[OSD_HDR ? (4096+1024) : 4096]; + +reg info = 0; +reg [8:0] infoh; +reg [8:0] infow; +reg [21:0] infox; +reg [21:0] infoy; +reg [21:0] osd_h; +reg [21:0] osd_t; +reg [21:0] osd_w; + +reg [1:0] rot = 0; + +always@(posedge clk_sys) begin + reg [12:0] bcnt; + reg [7:0] cmd; + reg has_cmd; + reg old_strobe; + reg highres = 0; + + osd_t <= rot[0] ? OSD_WIDTH : (OSD_HEIGHT<<1); + osd_h <= rot[0] ? (info ? infow : OSD_WIDTH) : info ? infoh : (OSD_HEIGHT<> (9-rot[0])) > 1) ? (((cnt+1'b1) >> (9-rot[0])) - 1'd1) : 22'd0; + pixcnt <= 0; + end +end + +reg [2:0] osd_de; +reg osd_pixel; +reg [21:0] v_cnt; +reg v_cnt_h, v_cnt_1, v_cnt_2, v_cnt_3, v_cnt_4; +reg [21:0] v_osd_start_h, v_osd_start_1, v_osd_start_2, v_osd_start_3, v_osd_start_4, v_osd_start_5; +reg [21:0] v_info_start_h, v_info_start_1, v_info_start_2, v_info_start_3, v_info_start_4, v_info_start_5; + +wire [21:0] osd_h_hdr = (info || rot) ? osd_h : (osd_h + OSD_HDR); + +// pipeline the comparisons a bit +always @(posedge clk_video) if(ce_pix) begin + v_cnt_h <= v_cnt <= osd_t; + v_cnt_1 <= v_cnt < 320; + v_cnt_2 <= v_cnt < 640; + v_cnt_3 <= v_cnt < 960; + v_cnt_4 <= v_cnt < 1280; + + v_osd_start_h <= (v_cnt-(osd_h_hdr>>1))>>1; + v_osd_start_1 <= (v_cnt-osd_h_hdr)>>1; + v_osd_start_2 <= (v_cnt-(osd_h_hdr<<1))>>1; + v_osd_start_3 <= (v_cnt-(osd_h_hdr + (osd_h_hdr<<1)))>>1; + v_osd_start_4 <= (v_cnt-(osd_h_hdr<<2))>>1; + v_osd_start_5 <= (v_cnt-(osd_h_hdr + (osd_h_hdr<<2)))>>1; + + v_info_start_h <= rot[0] ? infox : infoy; + v_info_start_1 <= rot[0] ? infox : infoy; + v_info_start_2 <= rot[0] ? (infox<<1) : (infoy<<1); + v_info_start_3 <= rot[0] ? (infox + (infox << 1)) : (infoy + (infoy << 1)); + v_info_start_4 <= rot[0] ? (infox << 2) : (infoy << 2); + v_info_start_5 <= rot[0] ? (infox + (infox << 2)) : (infoy + (infoy << 2)); +end + +always @(posedge clk_video) begin + reg deD; + reg [2:0] osd_div; + reg [2:0] multiscan; + reg [7:0] osd_byte; + reg [23:0] h_cnt; + reg [21:0] dsp_width; + reg [21:0] osd_vcnt; + reg [21:0] h_osd_start; + reg [21:0] v_osd_start; + reg [21:0] osd_hcnt; + reg [21:0] osd_hcnt2; + reg osd_de1,osd_de2; + reg [1:0] osd_en; + reg f1; + reg half; + + if(ce_pix) begin + + deD <= de_in; + if(~&h_cnt) h_cnt <= h_cnt + 1'd1; + + if(~&osd_hcnt) osd_hcnt <= osd_hcnt + 1'd1; + if(~&osd_hcnt2) osd_hcnt2 <= osd_hcnt2 + 1'd1; + + if (h_cnt == h_osd_start) begin + osd_de[0] <= osd_en[1] && osd_h && ( + osd_vcnt[11] ? (osd_vcnt[7] && (osd_vcnt[6:0] >= 4) && (osd_vcnt[6:0] < 19)) : + (info && (rot == 3)) ? !osd_vcnt[21:8] : + (osd_vcnt < osd_h) + ); + osd_hcnt <= 0; + osd_hcnt2 <= 0; + if(info && rot == 1) osd_hcnt2 <= 22'd128-infoh; + end + if (osd_hcnt+1 == osd_w) osd_de[0] <= 0; + + // falling edge of de + if(!de_in && deD) dsp_width <= h_cnt[21:0]; + + // rising edge of de + if(de_in && !deD) begin + h_cnt <= 0; + v_cnt <= v_cnt + 1'd1; + h_osd_start <= info ? (rot[0] ? infoy : infox) : (((dsp_width - osd_w)>>1) - 2'd2); + + if(h_cnt > {dsp_width, 2'b00}) begin + v_cnt <= 1; + f1 <= ~f1; // skip every other frame for interlace compatibility. + if(~f1) begin + + osd_en <= (osd_en << 1) | osd_enable; + if(~osd_enable) osd_en <= 0; + + half <= 0; + if(v_cnt_h) begin + multiscan <= 0; + v_osd_start <= info ? v_info_start_h : v_osd_start_h; + half <= 1; + end + else if(v_cnt_1 | (rot[0] & v_cnt_2)) begin + multiscan <= 0; + v_osd_start <= info ? v_info_start_1 : v_osd_start_1; + end + else if(rot[0] ? v_cnt_3 : v_cnt_2) begin + multiscan <= 1; + v_osd_start <= info ? v_info_start_2 : v_osd_start_2; + end + else if(rot[0] ? v_cnt_4 : v_cnt_3) begin + multiscan <= 2; + v_osd_start <= info ? v_info_start_3 : v_osd_start_3; + end + else if(rot[0] | v_cnt_4) begin + multiscan <= 3; + v_osd_start <= info ? v_info_start_4 : v_osd_start_4; + end + else begin + multiscan <= 4; + v_osd_start <= info ? v_info_start_5 : v_osd_start_5; + end + end + end + + osd_div <= osd_div + 1'd1; + if(osd_div == multiscan) begin + osd_div <= 0; + if(~osd_vcnt[10]) osd_vcnt <= osd_vcnt + 1'd1 + half; + if(osd_vcnt == 'b100010011111 && ~info) osd_vcnt <= 0; + end + if(v_osd_start == v_cnt) begin + {osd_div,osd_vcnt} <= 0; + if(info && rot == 3) osd_vcnt <= 22'd256-infow; + else if(OSD_HDR && !rot) osd_vcnt <= {~info, 3'b000, ~info, 7'b0000000}; + end + end + + osd_byte <= osd_buffer[rot[0] ? ({osd_hcnt2[6:3], osd_vcnt[7:0]} ^ { {4{~rot[1]}}, {8{rot[1]}} }) : {osd_vcnt[7:3], osd_hcnt[7:0]}]; + osd_pixel <= osd_byte[rot[0] ? ((osd_hcnt2[2:0]-1'd1) ^ {3{~rot[1]}}) : osd_vcnt[2:0]]; + osd_de[2:1] <= osd_de[1:0]; + end +end + +reg [23:0] rdout; +assign dout = rdout; + +always @(posedge clk_video) begin + reg [23:0] ordout1, nrdout1, rdout2, rdout3; + reg de1,de2,de3; + reg osd_mux; + reg vs1,vs2,vs3; + reg hs1,hs2,hs3; + + nrdout1 <= din; + ordout1 <= {{osd_pixel, osd_pixel, OSD_COLOR[2], din[23:19]},// 23:16 + {osd_pixel, osd_pixel, OSD_COLOR[1], din[15:11]},// 15:8 + {osd_pixel, osd_pixel, OSD_COLOR[0], din[7:3]}}; // 7:0 + + osd_mux <= ~osd_de[2]; + rdout2 <= osd_mux ? nrdout1 : ordout1; + rdout3 <= rdout2; + + de1 <= de_in; de2 <= de1; de3 <= de2; + hs1 <= hs_in; hs2 <= hs1; hs3 <= hs2; + vs1 <= vs_in; vs2 <= vs1; vs3 <= vs2; + + rdout <= rdout3; + de_out <= de3; + hs_out <= hs3; + vs_out <= vs3; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio.v new file mode 100644 index 0000000000000000000000000000000000000000..185a94c28ecbb3d054334c3e6ffab0fb69308352 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio.v @@ -0,0 +1,252 @@ +// megafunction wizard: %Altera PLL v17.0% +// GENERATION: XML +// pll_audio.v + +// Generated using ACDS version 17.0 602 + +`timescale 1 ps / 1 ps +module pll_audio ( + input wire refclk, // refclk.clk + input wire rst, // reset.reset + output wire outclk_0 // outclk0.clk + ); + + pll_audio_0002 pll_audio_inst ( + .refclk (refclk), // refclk.clk + .rst (rst), // reset.reset + .outclk_0 (outclk_0), // outclk0.clk + .locked () // (terminated) + ); + +endmodule +// Retrieval info: +// +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// IPFS_FILES : pll_audio.vo +// RELATED_FILES: pll_audio.v, pll_audio_0002.v diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio/pll_audio_0002.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio/pll_audio_0002.v new file mode 100644 index 0000000000000000000000000000000000000000..789891438b29868b5bd7aca3d4ed6a662ff6c7f4 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_audio/pll_audio_0002.v @@ -0,0 +1,87 @@ +`timescale 1ns/10ps +module pll_audio_0002( + + // interface 'refclk' + input wire refclk, + + // interface 'reset' + input wire rst, + + // interface 'outclk0' + output wire outclk_0, + + // interface 'locked' + output wire locked +); + + altera_pll #( + .fractional_vco_multiplier("true"), + .reference_clock_frequency("50.0 MHz"), + .operation_mode("direct"), + .number_of_clocks(1), + .output_clock_frequency0("24.576000 MHz"), + .phase_shift0("0 ps"), + .duty_cycle0(50), + .output_clock_frequency1("0 MHz"), + .phase_shift1("0 ps"), + .duty_cycle1(50), + .output_clock_frequency2("0 MHz"), + .phase_shift2("0 ps"), + .duty_cycle2(50), + .output_clock_frequency3("0 MHz"), + .phase_shift3("0 ps"), + .duty_cycle3(50), + .output_clock_frequency4("0 MHz"), + .phase_shift4("0 ps"), + .duty_cycle4(50), + .output_clock_frequency5("0 MHz"), + .phase_shift5("0 ps"), + .duty_cycle5(50), + .output_clock_frequency6("0 MHz"), + .phase_shift6("0 ps"), + .duty_cycle6(50), + .output_clock_frequency7("0 MHz"), + .phase_shift7("0 ps"), + .duty_cycle7(50), + .output_clock_frequency8("0 MHz"), + .phase_shift8("0 ps"), + .duty_cycle8(50), + .output_clock_frequency9("0 MHz"), + .phase_shift9("0 ps"), + .duty_cycle9(50), + .output_clock_frequency10("0 MHz"), + .phase_shift10("0 ps"), + .duty_cycle10(50), + .output_clock_frequency11("0 MHz"), + .phase_shift11("0 ps"), + .duty_cycle11(50), + .output_clock_frequency12("0 MHz"), + .phase_shift12("0 ps"), + .duty_cycle12(50), + .output_clock_frequency13("0 MHz"), + .phase_shift13("0 ps"), + .duty_cycle13(50), + .output_clock_frequency14("0 MHz"), + .phase_shift14("0 ps"), + .duty_cycle14(50), + .output_clock_frequency15("0 MHz"), + .phase_shift15("0 ps"), + .duty_cycle15(50), + .output_clock_frequency16("0 MHz"), + .phase_shift16("0 ps"), + .duty_cycle16(50), + .output_clock_frequency17("0 MHz"), + .phase_shift17("0 ps"), + .duty_cycle17(50), + .pll_type("General"), + .pll_subtype("General") + ) altera_pll_i ( + .rst (rst), + .outclk ({outclk_0}), + .locked (locked), + .fboutclk ( ), + .fbclk (1'b0), + .refclk (refclk) + ); +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_core.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_core.v new file mode 100644 index 0000000000000000000000000000000000000000..a9e2b8c01788133d1588c5c1b160bf509b6c63b8 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_core.v @@ -0,0 +1,2184 @@ +// (C) 2001-2017 Intel Corporation. All rights reserved. +// Your use of Intel Corporation's design tools, logic functions and other +// software and tools, and its AMPP partner logic functions, and any output +// files any of the foregoing (including device programming or simulation +// files), and any associated documentation or information are expressly subject +// to the terms and conditions of the Intel Program License Subscription +// Agreement, Intel MegaCore Function License Agreement, or other applicable +// license agreement, including, without limitation, that your use is for the +// sole purpose of programming logic devices manufactured by Intel and sold by +// Intel or its authorized distributors. Please refer to the applicable +// agreement for further details. + + +`timescale 1ps/1ps + +module altera_pll_reconfig_core +#( + parameter reconf_width = 64, + parameter device_family = "Cyclone V", + // MIF Streaming parameters + parameter RECONFIG_ADDR_WIDTH = 6, + parameter RECONFIG_DATA_WIDTH = 32, + parameter ROM_ADDR_WIDTH = 9, + parameter ROM_DATA_WIDTH = 32, + parameter ROM_NUM_WORDS = 512 +) ( + + //input + input wire mgmt_clk, + input wire mgmt_reset, + + + //conduits + output wire [reconf_width-1:0] reconfig_to_pll, + input wire [reconf_width-1:0] reconfig_from_pll, + + // user data (avalon-MM slave interface) + output wire [31:0] mgmt_readdata, + output wire mgmt_waitrequest, + input wire [5:0] mgmt_address, + input wire mgmt_read, + input wire mgmt_write, + input wire [31:0] mgmt_writedata, + + //other + output wire mif_start_out, + output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr +); + localparam mode_WR = 1'b0; + localparam mode_POLL = 1'b1; + localparam MODE_REG = 6'b000000; + localparam STATUS_REG = 6'b000001; + localparam START_REG = 6'b000010; + localparam N_REG = 6'b000011; + localparam M_REG = 6'b000100; + localparam C_COUNTERS_REG = 6'b000101; + localparam DPS_REG = 6'b000110; + localparam DSM_REG = 6'b000111; + localparam BWCTRL_REG = 6'b001000; + localparam CP_CURRENT_REG = 6'b001001; + localparam ANY_DPRIO = 6'b100000; + localparam CNT_BASE = 5'b001010; + localparam VCO_REG = 6'b011100; + localparam MIF_REG = 6'b011111; + + //C Counters + localparam number_of_counters = 5'd18; + localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2, + CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5, + CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8, + CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11, + CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14, + CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17; + //C counter addresses + localparam C_CNT_0_DIV_ADDR = 5'h00; + localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11; + localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15; + localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17; + localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14; + localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16; + //N counter addresses + localparam N_CNT_DIV_ADDR = 5'h13; + localparam N_CNT_BYPASS_EN_ADDR = 5'h15; + localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17; + //M counter addresses + localparam M_CNT_DIV_ADDR = 5'h12; + localparam M_CNT_BYPASS_EN_ADDR = 5'h15; + localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17; + + //DSM address + localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18; + localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19; + localparam DSM_K_READY_ADDR = 5'h17; + localparam DSM_K_DITHER_ADDR = 5'h17; + localparam DSM_OUT_SEL_ADDR = 6'h30; + + //Other DSM params + localparam DSM_K_READY_BIT_INDEX = 4'd11; + //BWCTRL address + //Bit 0-3 of addr + localparam BWCTRL_ADDR = 6'h30; + //CP_CURRENT address + //Bit 0-2 of addr + localparam CP_CURRENT_ADDR = 6'h31; + + // VCODIV address + localparam VCO_ADDR = 5'h17; + + localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4, + FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10, + ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15; + localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10; + + wire clk; + wire reset; + wire gnd; + + wire [5: 0] slave_address; + wire slave_read; + wire slave_write; + wire [31: 0] slave_writedata; + + reg [31: 0] slave_readdata_d; + reg [31: 0] slave_readdata_q; + wire slave_waitrequest; + reg slave_mode; + + assign clk = mgmt_clk; + + assign slave_address = mgmt_address; + assign slave_read = mgmt_read; + assign slave_write = mgmt_write; + assign slave_writedata = mgmt_writedata; + + reg read_waitrequest; + // Outputs + assign mgmt_readdata = slave_readdata_q; + assign mgmt_waitrequest = slave_waitrequest | read_waitrequest; //Read waitrequest asserted in polling mode + + //internal signals + wire locked_orig; + wire locked; + + wire pll_start; + wire pll_start_valid; + reg status_read; + wire read_slave_mode_asserted; + + wire pll_start_asserted; + + reg [1:0] current_state; + reg [1:0] next_state; + + reg status;//0=busy, 1=ready + //user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load); + //declaring the init wires. These will have 0 on them for 64 clk cycles + wire [ 5:0] init_dprio_address; + wire init_dprio_read; + wire [ 1:0] init_dprio_byteen; + wire init_dprio_write; + wire [15:0] init_dprio_writedata; + + wire init_atpgmode; + wire init_mdio_dis; + wire init_scanen; + wire init_ser_shift_load; + wire dprio_init_done; + + //DPRIO output signals after initialization is done + wire dprio_clk; + reg avmm_dprio_write; + reg avmm_dprio_read; + reg [5:0] avmm_dprio_address; + reg [15:0] avmm_dprio_writedata; + reg [1:0] avmm_dprio_byteen; + wire avmm_atpgmode; + wire avmm_mdio_dis; + wire avmm_scanen; + + //Final output wires that are muxed between the init and avmm wires. + wire dprio_init_reset; + wire [5:0] dprio_address /*synthesis keep*/; + wire dprio_read/*synthesis keep*/; + wire [1:0] dprio_byteen/*synthesis keep*/; + wire dprio_write/*synthesis keep*/; + wire [15:0] dprio_writedata/*synthesis keep*/; + wire dprio_mdio_dis/*synthesis keep*/; + wire dprio_ser_shift_load/*synthesis keep*/; + wire dprio_atpgmode/*synthesis keep*/; + wire dprio_scanen/*synthesis keep*/; + + + //other PLL signals for dyn ph shift + wire phase_done/*synthesis keep*/; + wire phase_en/*synthesis keep*/; + wire up_dn/*synthesis keep*/; + wire [4:0] cnt_sel; + + //DPRIO input signals + wire [15:0] dprio_readdata; + + //internal logic signals + //storage registers for user sent data + reg dprio_temp_read_1; + reg dprio_temp_read_2; + reg dprio_start; + reg mif_start_assert; + reg dps_start_assert; + wire usr_valid_changes; + reg [3:0] dprio_cur_state; + reg [3:0] dprio_next_state; + reg [15:0] dprio_temp_m_n_c_readdata_1_d; + reg [15:0] dprio_temp_m_n_c_readdata_2_d; + reg [15:0] dprio_temp_m_n_c_readdata_1_q; + reg [15:0] dprio_temp_m_n_c_readdata_2_q; + reg dprio_write_done; + //C counters signals + reg [7:0] usr_c_cnt_lo; + reg [7:0] usr_c_cnt_hi; + reg usr_c_cnt_bypass_en; + reg usr_c_cnt_odd_duty_div_en; + reg [7:0] temp_c_cnt_lo [0:17]; + reg [7:0] temp_c_cnt_hi [0:17]; + reg temp_c_cnt_bypass_en [0:17]; + reg temp_c_cnt_odd_duty_div_en [0:17]; + reg any_c_cnt_changed; + reg all_c_cnt_done_q; + reg all_c_cnt_done_d; + reg [17:0] c_cnt_changed; + reg [17:0] c_cnt_done_d; + reg [17:0] c_cnt_done_q; + //N counter signals + reg [7:0] usr_n_cnt_lo; + reg [7:0] usr_n_cnt_hi; + reg usr_n_cnt_bypass_en; + reg usr_n_cnt_odd_duty_div_en; + reg n_cnt_changed; + reg n_cnt_done_d; + reg n_cnt_done_q; + //M counter signals + reg [7:0] usr_m_cnt_lo; + reg [7:0] usr_m_cnt_hi; + reg usr_m_cnt_bypass_en; + reg usr_m_cnt_odd_duty_div_en; + reg m_cnt_changed; + reg m_cnt_done_d; + reg m_cnt_done_q; + //dyn phase regs + reg [15:0] usr_num_shifts; + reg [4:0] usr_cnt_sel /*synthesis preserve*/; + reg usr_up_dn; + reg dps_changed; + wire dps_changed_valid; + wire dps_done; + + //DSM Signals + reg [31:0] usr_k_value; + reg dsm_k_changed; + reg dsm_k_done_d; + reg dsm_k_done_q; + reg dsm_k_ready_false_done_d; + //BW signals + reg [3:0] usr_bwctrl_value; + reg bwctrl_changed; + reg bwctrl_done_d; + reg bwctrl_done_q; + //CP signals + reg [2:0] usr_cp_current_value; + reg cp_current_changed; + reg cp_current_done_d; + reg cp_current_done_q; + //VCO signals + reg usr_vco_value; + reg vco_changed; + reg vco_done_d; + reg vco_done_q; + //Manual DPRIO signals + reg manual_dprio_done_q; + reg manual_dprio_done_d; + reg manual_dprio_changed; + reg [5:0] usr_dprio_address; + reg [15:0] usr_dprio_writedata_0; + reg usr_r_w; + //keeping track of which operation happened last + reg [5:0] operation_address; + // Address wires for all C_counter DPRIO registers + // These are outputs of LUTS, changing depending + // on whether PLL_0 or PLL_1 being used + + + //Fitter will tell if FPLL1 is being used + wire fpll_1; + + // other + reg mif_reg_asserted; + // MAIN FSM + + // Synchronize locked signal + altera_std_synchronizer #( + .depth(3) + ) altera_std_synchronizer_inst ( + .clk(mgmt_clk), + .reset_n(~mgmt_reset), + .din(locked_orig), + .dout(locked) + ); + + always @(posedge clk) + begin + if (reset) + begin + dprio_cur_state <= DPRIO_IDLE; + current_state <= IDLE; + end + else + begin + current_state <= next_state; + dprio_cur_state <= dprio_next_state; + end + end + + always @(*) + begin + case(current_state) + IDLE: + begin + if (pll_start & !slave_waitrequest & usr_valid_changes) + next_state = WAIT_ON_LOCK; + else + next_state = IDLE; + end + WAIT_ON_LOCK: + begin + if (locked & dps_done & dprio_write_done) // received locked high from PLL + begin + if (slave_mode==mode_WR) //if the mode is waitrequest, then + // goto IDLE state directly + next_state = IDLE; + else + next_state = LOCKED; //otherwise go the locked state + end + else + next_state = WAIT_ON_LOCK; + end + + LOCKED: + begin + if (status_read) // stay in LOCKED until user reads status + next_state = IDLE; + else + next_state = LOCKED; + end + + default: next_state = 2'bxx; + + endcase + end + + + // ask the pll to start reconfig + assign pll_start = (pll_start_asserted & (current_state==IDLE)) ; + assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ; + + + + // WRITE OPERATIONS + assign pll_start_asserted = slave_write & (slave_address == START_REG); + assign mif_start_out = pll_start & mif_reg_asserted; + + //reading the mode register to determine what mode the slave will operate + //in. + always @(posedge clk) + begin + if (reset) + slave_mode <= mode_WR; + else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest) + slave_mode <= slave_writedata[0]; + end + + //record which values user wants to change. + + //reading in the actual values that need to be reconfigged and sending + //them to the PLL + always @(posedge clk) + begin + if (reset) + begin + //reset all regs here + //BW signals reset + usr_bwctrl_value <= 0; + bwctrl_changed <= 0; + bwctrl_done_q <= 0; + //CP signals reset + usr_cp_current_value <= 0; + cp_current_changed <= 0; + cp_current_done_q <= 0; + //VCO signals reset + usr_vco_value <= 0; + vco_changed <= 0; + vco_done_q <= 0; + //DSM signals reset + usr_k_value <= 0; + dsm_k_changed <= 0; + dsm_k_done_q <= 0; + //N counter signals reset + usr_n_cnt_lo <= 0; + usr_n_cnt_hi <= 0; + usr_n_cnt_bypass_en <= 0; + usr_n_cnt_odd_duty_div_en <= 0; + n_cnt_changed <= 0; + n_cnt_done_q <= 0; + //M counter signals reset + usr_m_cnt_lo <= 0; + usr_m_cnt_hi <= 0; + usr_m_cnt_bypass_en <= 0; + usr_m_cnt_odd_duty_div_en <= 0; + m_cnt_changed <= 0; + m_cnt_done_q <= 0; + //C counter signals reset + usr_c_cnt_lo <= 0; + usr_c_cnt_hi <= 0; + usr_c_cnt_bypass_en <= 0; + usr_c_cnt_odd_duty_div_en <= 0; + any_c_cnt_changed <= 0; + all_c_cnt_done_q <= 0; + c_cnt_done_q <= 0; + //generic signals + dprio_start <= 0; + mif_start_assert <= 0; + dps_start_assert <= 0; + dprio_temp_m_n_c_readdata_1_q <= 0; + dprio_temp_m_n_c_readdata_2_q <= 0; + c_cnt_done_q <= 0; + //DPS signals + usr_up_dn <= 0; + usr_cnt_sel <= 0; + usr_num_shifts <= 0; + dps_changed <= 0; + //manual DPRIO signals + manual_dprio_changed <= 0; + usr_dprio_address <= 0; + usr_dprio_writedata_0 <= 0; + usr_r_w <= 0; + operation_address <= 0; + mif_reg_asserted <= 0; + mif_base_addr <= 0; + end + else + begin + if (dprio_temp_read_1) + begin + dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d; + end + if (dprio_temp_read_2) + begin + dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d; + end + if ((dps_done)) dps_changed <= 0; + if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d; + if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d; + if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d; + if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d; + if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d; + if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d; + if (cp_current_done_d) cp_current_done_q <= cp_current_done_d; + if (vco_done_d) vco_done_q <= vco_done_d; + if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d; + + if (mif_start_out == 1'b1) + mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle + + if (dps_done != 1'b1) + dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle + + if (dprio_next_state == ONE) + dprio_start <= 0; + if (dprio_write_done) + begin + bwctrl_done_q <= 0; + cp_current_done_q <= 0; + vco_done_q <= 0; + dsm_k_done_q <= 0; + dsm_k_done_q <= 0; + n_cnt_done_q <= 0; + m_cnt_done_q <= 0; + all_c_cnt_done_q <= 0; + c_cnt_done_q <= 0; + dsm_k_changed <= 0; + n_cnt_changed <= 0; + m_cnt_changed <= 0; + any_c_cnt_changed <= 0; + bwctrl_changed <= 0; + cp_current_changed <= 0; + vco_changed <= 0; + manual_dprio_changed <= 0; + manual_dprio_done_q <= 0; + if (dps_changed | dps_changed_valid | !dps_done ) + begin + usr_cnt_sel <= usr_cnt_sel; + end + else + begin + usr_cnt_sel <= 0; + end + mif_reg_asserted <= 0; + end + else + begin + dsm_k_changed <= dsm_k_changed; + n_cnt_changed <= n_cnt_changed; + m_cnt_changed <= m_cnt_changed; + any_c_cnt_changed <= any_c_cnt_changed; + manual_dprio_changed <= manual_dprio_changed; + mif_reg_asserted <= mif_reg_asserted; + usr_cnt_sel <= usr_cnt_sel; + end + + + if(slave_write & !slave_waitrequest) + begin + case(slave_address) + //read in the values here from the user and act on them + DSM_REG: + begin + operation_address <= DSM_REG; + usr_k_value <= slave_writedata[31:0]; + dsm_k_changed <= 1'b1; + dsm_k_done_q <= 0; + dprio_start <= 1'b1; + end + N_REG: + begin + operation_address <= N_REG; + usr_n_cnt_lo <= slave_writedata[7:0]; + usr_n_cnt_hi <= slave_writedata[15:8]; + usr_n_cnt_bypass_en <= slave_writedata[16]; + usr_n_cnt_odd_duty_div_en <= slave_writedata[17]; + n_cnt_changed <= 1'b1; + n_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + M_REG: + begin + operation_address <= M_REG; + usr_m_cnt_lo <= slave_writedata[7:0]; + usr_m_cnt_hi <= slave_writedata[15:8]; + usr_m_cnt_bypass_en <= slave_writedata[16]; + usr_m_cnt_odd_duty_div_en <= slave_writedata[17]; + m_cnt_changed <= 1'b1; + m_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + DPS_REG: + begin + operation_address <= DPS_REG; + usr_num_shifts <= slave_writedata[15:0]; + usr_cnt_sel <= slave_writedata[20:16]; + usr_up_dn <= slave_writedata[21]; + dps_changed <= 1; + dps_start_assert <= 1; + end + C_COUNTERS_REG: + begin + operation_address <= C_COUNTERS_REG; + usr_c_cnt_lo <= slave_writedata[7:0]; + usr_c_cnt_hi <= slave_writedata[15:8]; + usr_c_cnt_bypass_en <= slave_writedata[16]; + usr_c_cnt_odd_duty_div_en <= slave_writedata[17]; + usr_cnt_sel <= slave_writedata[22:18]; + any_c_cnt_changed <= 1'b1; + all_c_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + BWCTRL_REG: + begin + usr_bwctrl_value <= slave_writedata[3:0]; + bwctrl_changed <= 1'b1; + bwctrl_done_q <= 0; + dprio_start <= 1'b1; + operation_address <= BWCTRL_REG; + end + CP_CURRENT_REG: + begin + usr_cp_current_value <= slave_writedata[2:0]; + cp_current_changed <= 1'b1; + cp_current_done_q <= 0; + dprio_start <= 1'b1; + operation_address <= CP_CURRENT_REG; + end + VCO_REG: + begin + usr_vco_value <= slave_writedata[0]; + vco_changed <= 1'b1; + vco_done_q <= 0; + dprio_start <= 1'b1; + operation_address <= VCO_REG; + end + ANY_DPRIO: + begin + operation_address <= ANY_DPRIO; + manual_dprio_changed <= 1'b1; + usr_dprio_address <= slave_writedata[5:0]; + usr_dprio_writedata_0 <= slave_writedata[21:6]; + usr_r_w <= slave_writedata[22]; + manual_dprio_done_q <= 0; + dprio_start <= 1'b1; + end + MIF_REG: + begin + mif_reg_asserted <= 1'b1; + mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0]; + mif_start_assert <= 1'b1; + end + endcase + end + end + end + //C Counter assigning values to the 2-d array of values for each C counter + + reg [4:0] j; + always @(posedge clk) + begin + + if (reset) + begin + c_cnt_changed[17:0] <= 0; + for (j = 0; j < number_of_counters; j = j + 1'b1) + begin : c_cnt_reset + temp_c_cnt_bypass_en[j] <= 0; + temp_c_cnt_odd_duty_div_en[j] <= 0; + temp_c_cnt_lo[j][7:0] <= 0; + temp_c_cnt_hi[j][7:0] <= 0; + end + end + else + begin + if (dprio_write_done) + begin + c_cnt_changed <= 0; + end + if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG)) + begin + case (cnt_sel) + CNT_0: + begin + temp_c_cnt_lo [0] <= usr_c_cnt_lo; + temp_c_cnt_hi [0] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [0] <= 1'b1; + end + CNT_1: + begin + temp_c_cnt_lo [1] <= usr_c_cnt_lo; + temp_c_cnt_hi [1] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [1] <= 1'b1; + end + CNT_2: + begin + temp_c_cnt_lo [2] <= usr_c_cnt_lo; + temp_c_cnt_hi [2] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [2] <= 1'b1; + end + CNT_3: + begin + temp_c_cnt_lo [3] <= usr_c_cnt_lo; + temp_c_cnt_hi [3] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [3] <= 1'b1; + end + CNT_4: + begin + temp_c_cnt_lo [4] <= usr_c_cnt_lo; + temp_c_cnt_hi [4] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [4] <= 1'b1; + end + CNT_5: + begin + temp_c_cnt_lo [5] <= usr_c_cnt_lo; + temp_c_cnt_hi [5] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [5] <= 1'b1; + end + CNT_6: + begin + temp_c_cnt_lo [6] <= usr_c_cnt_lo; + temp_c_cnt_hi [6] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [6] <= 1'b1; + end + CNT_7: + begin + temp_c_cnt_lo [7] <= usr_c_cnt_lo; + temp_c_cnt_hi [7] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [7] <= 1'b1; + end + CNT_8: + begin + temp_c_cnt_lo [8] <= usr_c_cnt_lo; + temp_c_cnt_hi [8] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [8] <= 1'b1; + end + CNT_9: + begin + temp_c_cnt_lo [9] <= usr_c_cnt_lo; + temp_c_cnt_hi [9] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [9] <= 1'b1; + end + CNT_10: + begin + temp_c_cnt_lo [10] <= usr_c_cnt_lo; + temp_c_cnt_hi [10] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [10] <= 1'b1; + end + CNT_11: + begin + temp_c_cnt_lo [11] <= usr_c_cnt_lo; + temp_c_cnt_hi [11] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [11] <= 1'b1; + end + CNT_12: + begin + temp_c_cnt_lo [12] <= usr_c_cnt_lo; + temp_c_cnt_hi [12] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [12] <= 1'b1; + end + CNT_13: + begin + temp_c_cnt_lo [13] <= usr_c_cnt_lo; + temp_c_cnt_hi [13] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [13] <= 1'b1; + end + CNT_14: + begin + temp_c_cnt_lo [14] <= usr_c_cnt_lo; + temp_c_cnt_hi [14] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [14] <= 1'b1; + end + CNT_15: + begin + temp_c_cnt_lo [15] <= usr_c_cnt_lo; + temp_c_cnt_hi [15] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [15] <= 1'b1; + end + CNT_16: + begin + temp_c_cnt_lo [16] <= usr_c_cnt_lo; + temp_c_cnt_hi [16] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [16] <= 1'b1; + end + CNT_17: + begin + temp_c_cnt_lo [17] <= usr_c_cnt_lo; + temp_c_cnt_hi [17] <= usr_c_cnt_hi; + temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [17] <= 1'b1; + end + endcase + + end + end + end + + + //logic to handle which writes the user indicated and wants to start. + assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed|vco_changed; + + + //start the reconfig operations by writing to the DPRIO + reg break_loop; + reg [4:0] i; + always @(*) + begin + dprio_temp_read_1 = 0; + dprio_temp_read_2 = 0; + dprio_temp_m_n_c_readdata_1_d = 0; + dprio_temp_m_n_c_readdata_2_d = 0; + break_loop = 0; + dprio_next_state = DPRIO_IDLE; + avmm_dprio_write = 0; + avmm_dprio_read = 0; + avmm_dprio_address = 0; + avmm_dprio_writedata = 0; + avmm_dprio_byteen = 0; + dprio_write_done = 1; + manual_dprio_done_d = 0; + n_cnt_done_d = 0; + dsm_k_done_d = 0; + dsm_k_ready_false_done_d = 0; + m_cnt_done_d = 0; + c_cnt_done_d[17:0] = 0; + all_c_cnt_done_d = 0; + bwctrl_done_d = 0; + cp_current_done_d = 0; + vco_done_d = 0; + i = 0; + + // Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes) + if (dprio_start | mif_start_assert) + dprio_write_done = 0; + + if (current_state == WAIT_ON_LOCK) + begin + case (dprio_cur_state) + ONE: + begin + if (n_cnt_changed & !n_cnt_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_address = N_CNT_DIV_ADDR; + avmm_dprio_writedata[7:0] = usr_n_cnt_lo; + avmm_dprio_writedata[15:8] = usr_n_cnt_hi; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_address = M_CNT_DIV_ADDR; + avmm_dprio_writedata[7:0] = usr_m_cnt_lo; + avmm_dprio_writedata[15:8] = usr_m_cnt_hi; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_hilo + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i; + else avmm_dprio_address = C_CNT_0_DIV_ADDR + i; + avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i]; + avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i]; + //To break from the loop, since only one counter + //is addressed at a time + break_loop = 1'b1; + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (cp_current_changed & !cp_current_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (vco_changed & !vco_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (manual_dprio_changed & !manual_dprio_done_q) + begin + dprio_write_done = 0; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_write = usr_r_w; + avmm_dprio_address = usr_dprio_address; + avmm_dprio_writedata[15:0] = usr_dprio_writedata_0; + end + else dprio_next_state = DPRIO_IDLE; + end + + TWO: + begin + //handle reading the two setting bits on n_cnt, then + //writing them back while preserving other bits. + //Issue two consecutive reads then wait; readLatency=3 + dprio_write_done = 0; + dprio_next_state = THREE; + avmm_dprio_byteen = 2'b11; + avmm_dprio_read = 1'b1; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_BYPASS_EN_ADDR; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_BYPASS_EN_ADDR; + end + + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_read_bypass + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + end + end + end + //reading the K ready 16 bit word. Need to write 0 to it + //afterwards to indicate that K has not been done writing + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + dprio_next_state = FOUR; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_address = BWCTRL_ADDR; + dprio_next_state = FOUR; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_address = CP_CURRENT_ADDR; + dprio_next_state = FOUR; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_address = VCO_ADDR; + dprio_next_state = FOUR; + end + else if (manual_dprio_changed & !manual_dprio_done_q) + begin + avmm_dprio_read = ~usr_r_w; + avmm_dprio_address = usr_dprio_address; + dprio_next_state = DPRIO_DONE; + end + else dprio_next_state = DPRIO_IDLE; + end + THREE: + begin + dprio_write_done = 0; + avmm_dprio_byteen = 2'b11; + avmm_dprio_read = 1'b1; + dprio_next_state = FOUR; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_read_odd_div + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + end + end + end + else dprio_next_state = DPRIO_IDLE; + end + FOUR: + begin + dprio_temp_read_1 = 1'b1; + dprio_write_done = 0; + if (vco_changed|cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed) + begin + dprio_temp_m_n_c_readdata_1_d = dprio_readdata; + dprio_next_state = FIVE; + end + else dprio_next_state = DPRIO_IDLE; + end + FIVE: + begin + dprio_write_done = 0; + dprio_temp_read_2 = 1'b1; + if (vco_changed|cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed) + begin + //this is where DSM ready value comes. + //Need to store in a register to be used later + dprio_temp_m_n_c_readdata_2_d = dprio_readdata; + dprio_next_state = SIX; + end + else dprio_next_state = DPRIO_IDLE; + end + SIX: + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = SEVEN; + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_BYPASS_EN_ADDR; + avmm_dprio_writedata[5] = usr_n_cnt_bypass_en; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_BYPASS_EN_ADDR; + avmm_dprio_writedata[4] = usr_m_cnt_bypass_en; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_bypass + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_write = 0; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_write = 0; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_write = 0; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_write = 0; + end + else dprio_next_state = DPRIO_IDLE; + end + SEVEN: + begin + dprio_write_done = 0; + dprio_next_state = EIGHT; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en; + n_cnt_done_d = 1'b1; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en; + m_cnt_done_d = 1'b1; + end + + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_odd_div + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + //have to OR the signals to prevent + //overwriting of previous dones + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + //have to OR the signals to prevent + //overwriting of previous dones + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0; + dsm_k_ready_false_done_d = 1'b1; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_address = BWCTRL_ADDR; + avmm_dprio_writedata[3:0] = usr_bwctrl_value; + bwctrl_done_d = 1'b1; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_address = CP_CURRENT_ADDR; + avmm_dprio_writedata[2:0] = usr_cp_current_value; + cp_current_done_d = 1'b1; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_address = VCO_ADDR; + avmm_dprio_writedata[8] = usr_vco_value; + vco_done_d = 1'b1; + end + + + //if all C_cnt that were changed are done, then assert all_c_cnt_done + if (c_cnt_done_d == c_cnt_changed) + all_c_cnt_done_d = 1'b1; + if (n_cnt_changed & n_cnt_done_d) + dprio_next_state = DPRIO_DONE; + if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q) + dprio_next_state = ONE; + else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q) + dprio_next_state = ONE; + else if (dsm_k_changed & !dsm_k_ready_false_done_d) + dprio_next_state = TWO; + else if (dsm_k_changed & !dsm_k_done_q) + dprio_next_state = EIGHT; + else if (bwctrl_changed & !bwctrl_done_d) + dprio_next_state = TWO; + else if (cp_current_changed & !cp_current_done_d) + dprio_next_state = TWO; + else if (vco_changed & !vco_done_d) + dprio_next_state = TWO; + else + begin + dprio_next_state = DPRIO_DONE; + dprio_write_done = 1'b1; + end + end + //finish the rest of the DSM reads/writes + //writing k value, writing k_ready to 1. + EIGHT: + begin + dprio_write_done = 0; + dprio_next_state = NINE; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0; + avmm_dprio_writedata[15:0] = usr_k_value[15:0]; + end + end + NINE: + begin + dprio_write_done = 0; + dprio_next_state = TEN; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1; + avmm_dprio_writedata[15:0] = usr_k_value[31:16]; + end + end + TEN: + begin + dprio_write_done = 0; + dprio_next_state = ONE; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + //already have the readdata for DSM_K_READY_ADDR since we read it + //earlier. Just reuse here + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q; + avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1; + dsm_k_done_d = 1'b1; + end + end + DPRIO_DONE: + begin + dprio_write_done = 1'b1; + if (dprio_start) dprio_next_state = DPRIO_IDLE; + else dprio_next_state = DPRIO_DONE; + end + DPRIO_IDLE: + begin + if (dprio_start) dprio_next_state = ONE; + else dprio_next_state = DPRIO_IDLE; + end + default: dprio_next_state = 4'bxxxx; + endcase + end + + end + + + //assert the waitreq signal according to the state of the slave + assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0; + + // Read operations + always @(*) + begin + status = 0; + if (slave_mode == mode_POLL) + //asserting status to 1 if the slave is done. + status = (current_state == LOCKED); + end + //************************************************************// + //************************************************************// + //******************** READ STATE MACHINE ********************// + //************************************************************// + //************************************************************// + reg [1:0] current_read_state; + reg [1:0] next_read_state; + reg [5:0] slave_address_int_d; + reg [5:0] slave_address_int_q; + reg dprio_read_1; + reg [5:0] dprio_address_1; + reg [1:0] dprio_byteen_1; + reg [4:0] usr_cnt_sel_1; + localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10, READ_POST_WAIT = 2'b11; + + always @(*) + begin + if(next_read_state == READ_IDLE) + begin + read_waitrequest <= 1'b0; + end + else + begin + read_waitrequest <= 1'b1; + end + end + + always @(posedge clk) + begin + if (reset) + begin + current_read_state <= READ_IDLE; + slave_address_int_q <= 0; + slave_readdata_q <= 0; + end + else + begin + current_read_state <= next_read_state; + slave_address_int_q <= slave_address_int_d; + slave_readdata_q <= slave_readdata_d; + end + end + always @(*) + begin + dprio_read_1 = 0; + dprio_address_1 = 0; + dprio_byteen_1 = 0; + slave_address_int_d = 0; + slave_readdata_d = 0; + status_read = 0; + usr_cnt_sel_1 = 0; + case(current_read_state) + READ_IDLE: + begin + slave_address_int_d = 0; + next_read_state = READ_IDLE; + if ((current_state != WAIT_ON_LOCK) && slave_read) + begin + slave_address_int_d = slave_address; + if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18)) + begin + next_read_state = READ_WAIT; + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE); + if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel; + else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel; + end + else + begin + case (slave_address) + MODE_REG: + begin + next_read_state = READ_WAIT; + slave_readdata_d = slave_mode; + end + STATUS_REG: + begin + next_read_state = READ_WAIT; + status_read = 1'b1; + slave_readdata_d = status; + end + N_REG: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + dprio_address_1 = N_CNT_DIV_ADDR; + next_read_state = READ_WAIT; + end + M_REG: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + dprio_address_1 = M_CNT_DIV_ADDR; + next_read_state = READ_WAIT; + end + BWCTRL_REG: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + dprio_address_1 = BWCTRL_ADDR; + next_read_state = READ_WAIT; + end + CP_CURRENT_REG: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + dprio_address_1 = CP_CURRENT_ADDR; + next_read_state = READ_WAIT; + end + VCO_REG: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = 1'b1; + dprio_address_1 = VCO_ADDR; + next_read_state = READ_WAIT; + end + ANY_DPRIO: + begin + dprio_byteen_1 = 2'b11; + dprio_read_1 = ~slave_writedata[22]; + dprio_address_1 = slave_writedata[5:0]; + next_read_state = READ_WAIT; + end + default : next_read_state = READ_IDLE; + endcase + end + end + else + next_read_state = READ_IDLE; + end + READ_WAIT: + begin + next_read_state = READ; + slave_address_int_d = slave_address_int_q; + case (slave_address_int_q) + MODE_REG: + begin + slave_readdata_d = slave_readdata_q; + end + STATUS_REG: + begin + slave_readdata_d = slave_readdata_q; + end + endcase + end + READ: + begin + next_read_state = READ_POST_WAIT; + slave_address_int_d = slave_address_int_q; + slave_readdata_d = dprio_readdata; + case (slave_address_int_q) + MODE_REG: + begin + slave_readdata_d = slave_readdata_q; + end + STATUS_REG: + begin + slave_readdata_d = slave_readdata_q; + end + BWCTRL_REG: + begin + slave_readdata_d = dprio_readdata[3:0]; + end + CP_CURRENT_REG: + begin + slave_readdata_d = dprio_readdata[2:0]; + end + VCO_REG: + begin + slave_readdata_d = dprio_readdata[8]; + end + ANY_DPRIO: + begin + slave_readdata_d = dprio_readdata; + end + endcase + end + READ_POST_WAIT: + begin + next_read_state = READ_IDLE; + end + default: next_read_state = 2'bxx; + endcase + end + + + dyn_phase_shift dyn_phase_shift_inst ( + .clk(clk), + .reset(reset), + .phase_done(phase_done), + .pll_start_valid(pll_start_valid), + .dps_changed(dps_changed), + .dps_changed_valid(dps_changed_valid), + .dprio_write_done(dprio_write_done), + .usr_num_shifts(usr_num_shifts), + .usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1), + .usr_up_dn(usr_up_dn), + .locked(locked), + .dps_done(dps_done), + .phase_en(phase_en), + .up_dn(up_dn), + .cnt_sel(cnt_sel)); + defparam dyn_phase_shift_inst.device_family = device_family; + + assign dprio_clk = clk; + self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset); + + dprio_mux dprio_mux_inst ( + .init_dprio_address(init_dprio_address), + .init_dprio_read(init_dprio_read), + .init_dprio_byteen(init_dprio_byteen), + .init_dprio_write(init_dprio_write), + .init_dprio_writedata(init_dprio_writedata), + + + .init_atpgmode(init_atpgmode), + .init_mdio_dis(init_mdio_dis), + .init_scanen(init_scanen), + .init_ser_shift_load(init_ser_shift_load), + .dprio_init_done(dprio_init_done), + + // Inputs from avmm master + .avmm_dprio_address(avmm_dprio_address | dprio_address_1), + .avmm_dprio_read(avmm_dprio_read | dprio_read_1), + .avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1), + .avmm_dprio_write(avmm_dprio_write), + .avmm_dprio_writedata(avmm_dprio_writedata), + + .avmm_atpgmode(avmm_atpgmode), + .avmm_mdio_dis(avmm_mdio_dis), + .avmm_scanen(avmm_scanen), + + // Outputs to fpll + .dprio_address(dprio_address), + .dprio_read(dprio_read), + .dprio_byteen(dprio_byteen), + .dprio_write(dprio_write), + .dprio_writedata(dprio_writedata), + + .atpgmode(dprio_atpgmode), + .mdio_dis(dprio_mdio_dis), + .scanen(dprio_scanen), + .ser_shift_load(dprio_ser_shift_load) + ); + + + fpll_dprio_init fpll_dprio_init_inst ( + .clk(clk), + .reset_n(~reset), + .locked(locked), + + //outputs + .dprio_address(init_dprio_address), + .dprio_read(init_dprio_read), + .dprio_byteen(init_dprio_byteen), + .dprio_write(init_dprio_write), + .dprio_writedata(init_dprio_writedata), + + .atpgmode(init_atpgmode), + .mdio_dis(init_mdio_dis), + .scanen(init_scanen), + .ser_shift_load(init_ser_shift_load), + .dprio_init_done(dprio_init_done)); + + //address luts, to be reconfigged by the Fitter + //FPLL_1 or 0 address lut + generic_lcell_comb lcell_fpll_0_1 ( + .dataa(1'b0), + .combout (fpll_1)); + defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA; + defparam lcell_fpll_0_1.dont_touch = "on"; + defparam lcell_fpll_0_1.family = device_family; + + + wire dprio_read_combout; + generic_lcell_comb lcell_dprio_read ( + .dataa(fpll_1), + .datab(dprio_read), + .datac(1'b0), + .datad(1'b0), + .datae(1'b0), + .dataf(1'b0), + .combout (dprio_read_combout)); + defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC; + defparam lcell_dprio_read.dont_touch = "on"; + defparam lcell_dprio_read.family = device_family; + + + + + + //assign reconfig_to_pll signals + assign reconfig_to_pll[0] = dprio_clk; + assign reconfig_to_pll[1] = ~dprio_init_reset; + assign reconfig_to_pll[2] = dprio_write; + assign reconfig_to_pll[3] = dprio_read_combout; + assign reconfig_to_pll[9:4] = dprio_address; + assign reconfig_to_pll[25:10] = dprio_writedata; + assign reconfig_to_pll[27:26] = dprio_byteen; + assign reconfig_to_pll[28] = dprio_ser_shift_load; + assign reconfig_to_pll[29] = dprio_mdio_dis; + assign reconfig_to_pll[30] = phase_en; + assign reconfig_to_pll[31] = up_dn; + assign reconfig_to_pll[36:32] = cnt_sel; + assign reconfig_to_pll[37] = dprio_scanen; + assign reconfig_to_pll[38] = dprio_atpgmode; + //assign reconfig_to_pll[40:37] = clken; + assign reconfig_to_pll[63:39] = 0; + + //assign reconfig_from_pll signals + assign dprio_readdata = reconfig_from_pll [15:0]; + assign locked_orig = reconfig_from_pll [16]; + assign phase_done = reconfig_from_pll [17]; + +endmodule +module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset); + + localparam RESET_COUNTER_VALUE = 3'd2; + localparam INITIAL_WAIT_VALUE = 9'd340; + reg [9:0]counter; + reg local_reset; + reg usr_mode_init_wait; + initial + begin + local_reset = 1'b1; + counter = 0; + usr_mode_init_wait = 0; + end + + always @(posedge clk) + begin + if (mgmt_reset) + begin + counter <= 0; + end + else + begin + if (!usr_mode_init_wait) + begin + if (counter == INITIAL_WAIT_VALUE) + begin + local_reset <= 0; + usr_mode_init_wait <= 1'b1; + counter <= 0; + end + else + begin + counter <= counter + 1'b1; + end + end + else + begin + if (counter == RESET_COUNTER_VALUE) + local_reset <= 0; + else + counter <= counter + 1'b1; + end + end + end + assign reset = mgmt_reset | local_reset; + assign init_reset = local_reset; +endmodule + +module dprio_mux ( + // Inputs from init block + input [ 5:0] init_dprio_address, + input init_dprio_read, + input [ 1:0] init_dprio_byteen, + input init_dprio_write, + input [15:0] init_dprio_writedata, + + input init_atpgmode, + input init_mdio_dis, + input init_scanen, + input init_ser_shift_load, + input dprio_init_done, + + // Inputs from avmm master + input [ 5:0] avmm_dprio_address, + input avmm_dprio_read, + input [ 1:0] avmm_dprio_byteen, + input avmm_dprio_write, + input [15:0] avmm_dprio_writedata, + + input avmm_atpgmode, + input avmm_mdio_dis, + input avmm_scanen, + input avmm_ser_shift_load, + + // Outputs to fpll + output [ 5:0] dprio_address, + output dprio_read, + output [ 1:0] dprio_byteen, + output dprio_write, + output [15:0] dprio_writedata, + + output atpgmode, + output mdio_dis, + output scanen, + output ser_shift_load +); + + assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address; + assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read; + assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen; + assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write; + assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata; + + assign atpgmode = init_atpgmode; + assign scanen = init_scanen; + assign mdio_dis = init_mdio_dis; + assign ser_shift_load = init_ser_shift_load ; +endmodule +module fpll_dprio_init ( + input clk, + input reset_n, + input locked, + + output [ 5:0] dprio_address, + output dprio_read, + output [ 1:0] dprio_byteen, + output dprio_write, + output [15:0] dprio_writedata, + + output reg atpgmode, + output reg mdio_dis, + output reg scanen, + output reg ser_shift_load, + output reg dprio_init_done +); + + reg [1:0] rst_n = 2'b00; + reg [6:0] count = 7'd0; + reg init_done_forever; + + // Internal versions of control signals + wire int_mdio_dis; + wire int_ser_shift_load; + wire int_dprio_init_done; + wire int_atpgmode/*synthesis keep*/; + wire int_scanen/*synthesis keep*/; + + + assign dprio_address = count[6] ? 5'b0 : count[5:0] ; + assign dprio_byteen = 2'b11; // always enabled + assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles + assign dprio_read = 1'b0; + assign dprio_writedata = 16'd0; + + assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1; + assign int_mdio_dis = count[6] ? ~count[2] : 1'b1; + assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0) + : 1'b1; + assign int_atpgmode = 0; + assign int_scanen = 0; + + initial begin + count = 7'd0; + init_done_forever = 0; + mdio_dis = 1'b1; + ser_shift_load = 1'b1; + dprio_init_done = 1'b0; + scanen = 1'b0; + atpgmode = 1'b0; + end + + // reset synch. + always @(posedge clk or negedge reset_n) + if(!reset_n) rst_n <= 2'b00; + else rst_n <= {rst_n[0],1'b1}; + + // counter + always @(posedge clk) + begin + if (!rst_n[1]) + init_done_forever <= 1'b0; + else + begin + if (count[6] && &count[1:0]) + init_done_forever <= 1'b1; + end + end + always @(posedge clk or negedge rst_n[1]) + begin + if(!rst_n[1]) + begin + count <= 7'd0; + end + else if(~int_dprio_init_done) + begin + count <= count + 7'd1; + end + else + begin + count <= count; + end + end + + // outputs + always @(posedge clk) begin + mdio_dis <= int_mdio_dis; + ser_shift_load <= int_ser_shift_load; + dprio_init_done <= int_dprio_init_done; + atpgmode <= int_atpgmode; + scanen <= int_scanen; + end + +endmodule +module dyn_phase_shift +#( + parameter device_family = "Cyclone V" +) ( + + input wire clk, + input wire reset, + input wire phase_done, + input wire pll_start_valid, + input wire dps_changed, + input wire dprio_write_done, + input wire [15:0] usr_num_shifts, + input wire [4:0] usr_cnt_sel, + input wire usr_up_dn, + input wire locked, + + //output + output wire dps_done, + output reg phase_en, + output wire up_dn, + output wire dps_changed_valid, + output wire [4:0] cnt_sel); + + + + reg first_phase_shift_d; + reg first_phase_shift_q; + reg [15:0] phase_en_counter; + reg [3:0] dps_current_state; + reg [3:0] dps_next_state; + localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5; + localparam PHASE_EN_WAIT_COUNTER = 5'd1; + + reg [15:0] shifts_done_counter; + reg phase_done_final; + wire gnd /*synthesis keep*/; + + //fsm + //always block controlling the state regs + always @(posedge clk) + begin + if (reset) + begin + dps_current_state <= DPS_DONE; + end + else + begin + dps_current_state <= dps_next_state; + end + end + //the combinational part. assigning the next state + //this turns on the phase_done_final signal when phase_done does this: + //_____ ______ + // |______| + always @(*) + begin + phase_done_final = 0; + first_phase_shift_d = 0; + phase_en = 0; + dps_next_state = DPS_DONE; + case (dps_current_state) + DPS_START: + begin + phase_en = 1'b1; + dps_next_state = DPS_WAIT_PHASE_EN; + end + DPS_WAIT_PHASE_EN: + begin + phase_en = 1'b1; + if (first_phase_shift_q) + begin + first_phase_shift_d = 1'b1; + dps_next_state = DPS_WAIT_PHASE_EN; + end + else + begin + if (phase_en_counter == PHASE_EN_WAIT_COUNTER) + dps_next_state = DPS_WAIT_PHASE_DONE; + else dps_next_state = DPS_WAIT_PHASE_EN; + end + end + DPS_WAIT_PHASE_DONE: + begin + if (!phase_done | !locked) + begin + dps_next_state = DPS_WAIT_PHASE_DONE; + end + else + begin + if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0)) + begin + dps_next_state = DPS_START; + phase_done_final = 1'b1; + end + else + begin + dps_next_state = DPS_DONE; + end + + end + end + DPS_DONE: + begin + phase_done_final = 0; + if (dps_changed) + dps_next_state = DPS_CHANGED; + else dps_next_state = DPS_DONE; + + end + DPS_CHANGED: + begin + if (pll_start_valid) + dps_next_state = DPS_WAIT_DPRIO_WRITING; + else + dps_next_state = DPS_CHANGED; + end + DPS_WAIT_DPRIO_WRITING: + begin + if (dprio_write_done) + dps_next_state = DPS_START; + else + dps_next_state = DPS_WAIT_DPRIO_WRITING; + end + + default: dps_next_state = 4'bxxxx; + endcase + + + end + + always @(posedge clk) + begin + + + if (dps_current_state == DPS_WAIT_PHASE_DONE) + phase_en_counter <= 0; + else if (dps_current_state == DPS_WAIT_PHASE_EN) + phase_en_counter <= phase_en_counter + 1'b1; + + if (reset) + begin + phase_en_counter <= 0; + shifts_done_counter <= 1'b1; + first_phase_shift_q <= 1; + end + else + begin + if (first_phase_shift_d) + first_phase_shift_q <= 0; + if (dps_done) + begin + shifts_done_counter <= 1'b1; + end + else + begin + if (phase_done_final & (dps_next_state!= DPS_DONE)) + shifts_done_counter <= shifts_done_counter + 1'b1; + else + shifts_done_counter <= shifts_done_counter; + end + end + end + + assign dps_changed_valid = (dps_current_state == DPS_CHANGED); + assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED); + assign up_dn = usr_up_dn; + assign gnd = 1'b0; + + //cnt select luts (5) + generic_lcell_comb lcell_cnt_sel_0 ( + .dataa(usr_cnt_sel[0]), + .datab(usr_cnt_sel[1]), + .datac(usr_cnt_sel[2]), + .datad(usr_cnt_sel[3]), + .datae(usr_cnt_sel[4]), + .dataf(gnd), + .combout (cnt_sel[0])); + defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA; + defparam lcell_cnt_sel_0.dont_touch = "on"; + defparam lcell_cnt_sel_0.family = device_family; + generic_lcell_comb lcell_cnt_sel_1 ( + .dataa(usr_cnt_sel[0]), + .datab(usr_cnt_sel[1]), + .datac(usr_cnt_sel[2]), + .datad(usr_cnt_sel[3]), + .datae(usr_cnt_sel[4]), + .dataf(gnd), + .combout (cnt_sel[1])); + defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC; + defparam lcell_cnt_sel_1.dont_touch = "on"; + defparam lcell_cnt_sel_1.family = device_family; + generic_lcell_comb lcell_cnt_sel_2 ( + .dataa(usr_cnt_sel[0]), + .datab(usr_cnt_sel[1]), + .datac(usr_cnt_sel[2]), + .datad(usr_cnt_sel[3]), + .datae(usr_cnt_sel[4]), + .dataf(gnd), + .combout (cnt_sel[2])); + defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0; + defparam lcell_cnt_sel_2.dont_touch = "on"; + defparam lcell_cnt_sel_2.family = device_family; + generic_lcell_comb lcell_cnt_sel_3 ( + .dataa(usr_cnt_sel[0]), + .datab(usr_cnt_sel[1]), + .datac(usr_cnt_sel[2]), + .datad(usr_cnt_sel[3]), + .datae(usr_cnt_sel[4]), + .dataf(gnd), + .combout (cnt_sel[3])); + defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00; + defparam lcell_cnt_sel_3.dont_touch = "on"; + defparam lcell_cnt_sel_3.family = device_family; + generic_lcell_comb lcell_cnt_sel_4 ( + .dataa(usr_cnt_sel[0]), + .datab(usr_cnt_sel[1]), + .datac(usr_cnt_sel[2]), + .datad(usr_cnt_sel[3]), + .datae(usr_cnt_sel[4]), + .dataf(gnd), + .combout (cnt_sel[4])); + defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000; + defparam lcell_cnt_sel_4.dont_touch = "on"; + defparam lcell_cnt_sel_4.family = device_family; + + +endmodule + +module generic_lcell_comb +#( + //parameter + parameter family = "Cyclone V", + parameter lut_mask = 64'hAAAAAAAAAAAAAAAA, + parameter dont_touch = "on" +) ( + + input dataa, + input datab, + input datac, + input datad, + input datae, + input dataf, + + output combout +); + + generate + if (family == "Stratix V") + begin + stratixv_lcell_comb lcell_inst ( + .dataa(dataa), + .datab(datab), + .datac(datac), + .datad(datad), + .datae(datae), + .dataf(dataf), + .combout (combout)); + defparam lcell_inst.lut_mask = lut_mask; + defparam lcell_inst.dont_touch = dont_touch; + end + else if (family == "Arria V") + begin + arriav_lcell_comb lcell_inst ( + .dataa(dataa), + .datab(datab), + .datac(datac), + .datad(datad), + .datae(datae), + .dataf(dataf), + .combout (combout)); + defparam lcell_inst.lut_mask = lut_mask; + defparam lcell_inst.dont_touch = dont_touch; + end + else if (family == "Arria V GZ") + begin + arriavgz_lcell_comb lcell_inst ( + .dataa(dataa), + .datab(datab), + .datac(datac), + .datad(datad), + .datae(datae), + .dataf(dataf), + .combout (combout)); + defparam lcell_inst.lut_mask = lut_mask; + defparam lcell_inst.dont_touch = dont_touch; + end + else if (family == "Cyclone V") + begin + cyclonev_lcell_comb lcell_inst ( + .dataa(dataa), + .datab(datab), + .datac(datac), + .datad(datad), + .datae(datae), + .dataf(dataf), + .combout (combout)); + defparam lcell_inst.lut_mask = lut_mask; + defparam lcell_inst.dont_touch = dont_touch; + end + endgenerate +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_top.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_top.v new file mode 100644 index 0000000000000000000000000000000000000000..843c9705bede6a3fb6fbe2ef9326a5241dd648d5 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/altera_pll_reconfig_top.v @@ -0,0 +1,428 @@ +// (C) 2001-2017 Intel Corporation. All rights reserved. +// Your use of Intel Corporation's design tools, logic functions and other +// software and tools, and its AMPP partner logic functions, and any output +// files any of the foregoing (including device programming or simulation +// files), and any associated documentation or information are expressly subject +// to the terms and conditions of the Intel Program License Subscription +// Agreement, Intel MegaCore Function License Agreement, or other applicable +// license agreement, including, without limitation, that your use is for the +// sole purpose of programming logic devices manufactured by Intel and sold by +// Intel or its authorized distributors. Please refer to the applicable +// agreement for further details. + + +`timescale 1ps/1ps + +module altera_pll_reconfig_top +#( + parameter reconf_width = 64, + parameter device_family = "Cyclone V", + parameter RECONFIG_ADDR_WIDTH = 6, + parameter RECONFIG_DATA_WIDTH = 32, + + parameter ROM_ADDR_WIDTH = 9, + parameter ROM_DATA_WIDTH = 32, + parameter ROM_NUM_WORDS = 512, + + parameter ENABLE_MIF = 0, + parameter MIF_FILE_NAME = "", + + parameter ENABLE_BYTEENABLE = 0, + parameter BYTEENABLE_WIDTH = 4, + parameter WAIT_FOR_LOCK = 1 +) ( + + //input + input wire mgmt_clk, + input wire mgmt_reset, + + + //conduits + output wire [reconf_width-1:0] reconfig_to_pll, + input wire [reconf_width-1:0] reconfig_from_pll, + + // user data (avalon-MM slave interface) + output wire [RECONFIG_DATA_WIDTH-1:0] mgmt_readdata, + output wire mgmt_waitrequest, + input wire [RECONFIG_ADDR_WIDTH-1:0] mgmt_address, + input wire mgmt_read, + input wire mgmt_write, + input wire [RECONFIG_DATA_WIDTH-1:0] mgmt_writedata, + + //conditional input + input wire [BYTEENABLE_WIDTH-1:0] mgmt_byteenable +); + +localparam NM28_START_REG = 6'b000010; +localparam NM20_START_REG = 9'b000000000; +localparam NM20_MIFSTART_ADDR = 9'b000010000; + +localparam MIF_STATE_DONE = 2'b00; +localparam MIF_STATE_START = 2'b01; +localparam MIF_STATE_BUSY = 2'b10; + +wire mgmt_byteenable_write; +assign mgmt_byteenable_write = (ENABLE_BYTEENABLE == 1) ? + ((mgmt_byteenable == {BYTEENABLE_WIDTH{1'b1}}) ? mgmt_write : 1'b0) : + mgmt_write; + +generate +if (device_family == "Arria 10") +begin:nm20_reconfig + if(ENABLE_MIF == 1) + begin:mif_reconfig_20nm // Generate Reconfig with MIF + + // MIF-related regs/wires + reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr; + reg reconfig_mgmt_read; + reg reconfig_mgmt_write; + reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata; + wire reconfig_mgmt_waitrequest; + wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata; + + wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr; + wire mif_busy; + wire mif2reconfig_read; + wire mif2reconfig_write; + wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata; + wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; + reg mif_select; + //wire mif_user_start; // start signal provided by user to start mif + //reg user_start; + + reg [1:0] mif_curstate; + reg [1:0] mif_nextstate; + + wire mif_start; //start signal to mif reader + + assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif_busy;// | user_start; + // Don't output readdata if MIF streaming is taking place + assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata; + + //user must lower this by the time mif streaming is done - suggest to lower after 1 cycle + assign mif_start = mgmt_byteenable_write & (mgmt_address == NM20_MIFSTART_ADDR); + + //mif base addr is initially specified by the user + assign mif_base_addr = mgmt_writedata[ROM_ADDR_WIDTH-1:0]; + + //MIF statemachine + always @(posedge mgmt_clk) + begin + if(mgmt_reset) + mif_curstate <= MIF_STATE_DONE; + else + mif_curstate <= mif_nextstate; + end + + always @(*) + begin + case (mif_curstate) + MIF_STATE_DONE: + begin + if(mif_start) + mif_nextstate <= MIF_STATE_START; + else + mif_nextstate <= MIF_STATE_DONE; + end + MIF_STATE_START: + begin + mif_nextstate <= MIF_STATE_BUSY; + end + MIF_STATE_BUSY: + begin + if(mif_busy) + mif_nextstate <= MIF_STATE_BUSY; + else + mif_nextstate <= MIF_STATE_DONE; + end + endcase + end + + //Mif muxes + always @(*) + begin + if (mgmt_reset) + begin + reconfig_mgmt_addr <= 0; + reconfig_mgmt_read <= 0; + reconfig_mgmt_write <= 0; + reconfig_mgmt_writedata <= 0; + //user_start <= 0; + end + else + begin + reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address; + reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read; + reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_byteenable_write; + reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata; + //user_start <= (mgmt_address == NM20_START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0; + end + end + + always @(*) + begin + if (mgmt_reset) + begin + mif_select <= 0; + end + else + begin + mif_select <= (mif_start || mif_busy) ? 1'b1 : 1'b0; + end + end + + twentynm_pll_reconfig_mif_reader + #( + .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), + .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), + .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), + .ROM_DATA_WIDTH(ROM_DATA_WIDTH), + .ROM_NUM_WORDS(ROM_NUM_WORDS), + .DEVICE_FAMILY(device_family), + .ENABLE_MIF(ENABLE_MIF), + .MIF_FILE_NAME(MIF_FILE_NAME) + ) twentynm_pll_reconfig_mif_reader_inst0 ( + .mif_clk(mgmt_clk), + .mif_rst(mgmt_reset), + + //Altera_PLL Reconfig interface + //inputs + .reconfig_waitrequest(reconfig_mgmt_waitrequest), + //.reconfig_read_data(reconfig_mgmt_readdata), + //outputs + .reconfig_write_data(mif2reconfig_writedata), + .reconfig_addr(mif2reconfig_addr), + .reconfig_write(mif2reconfig_write), + .reconfig_read(mif2reconfig_read), + + //MIF Ctrl Interface + //inputs + .mif_base_addr(mif_base_addr), + .mif_start(mif_start), + //outputs + .mif_busy(mif_busy) + ); + + // ------ END MIF-RELATED MANAGEMENT ------ + + twentynm_iopll_reconfig_core + #( + .WAIT_FOR_LOCK(WAIT_FOR_LOCK) + ) twentynm_iopll_reconfig_core_inst ( + // Inputs + .mgmt_clk(mgmt_clk), + .mgmt_rst_n(~mgmt_reset), + .mgmt_read(reconfig_mgmt_read), + .mgmt_write(reconfig_mgmt_write), + .mgmt_address(reconfig_mgmt_addr), + .mgmt_writedata(reconfig_mgmt_writedata), + + // Outputs + .mgmt_readdata(reconfig_mgmt_readdata), + .mgmt_waitrequest(reconfig_mgmt_waitrequest), + + // PLL Conduits + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll) + ); + + end // End generate reconfig with MIF + else + begin:reconfig_core_20nm + twentynm_iopll_reconfig_core + #( + .WAIT_FOR_LOCK(WAIT_FOR_LOCK) + ) twentynm_iopll_reconfig_core_inst ( + // Inputs + .mgmt_clk(mgmt_clk), + .mgmt_rst_n(~mgmt_reset), + .mgmt_read(mgmt_read), + .mgmt_write(mgmt_byteenable_write), + .mgmt_address(mgmt_address), + .mgmt_writedata(mgmt_writedata), + + // Outputs + .mgmt_readdata(mgmt_readdata), + .mgmt_waitrequest(mgmt_waitrequest), + + // PLL Conduits + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll) + ); + end +end // 20nm reconfig +else +begin:NM28_reconfig + if (ENABLE_MIF == 1) + begin:mif_reconfig // Generate Reconfig with MIF + + // MIF-related regs/wires + reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr; + reg reconfig_mgmt_read; + reg reconfig_mgmt_write; + reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata; + wire reconfig_mgmt_waitrequest; + wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata; + + wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr; + wire mif2reconfig_busy; + wire mif2reconfig_read; + wire mif2reconfig_write; + wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata; + wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; + reg mif_select; + reg user_start; + + wire reconfig2mif_start_out; + + assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start; + // Don't output readdata if MIF streaming is taking place + assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata; + + always @(posedge mgmt_clk) + begin + if (mgmt_reset) + begin + reconfig_mgmt_addr <= 0; + reconfig_mgmt_read <= 0; + reconfig_mgmt_write <= 0; + reconfig_mgmt_writedata <= 0; + user_start <= 0; + end + else + begin + reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address; + reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read; + reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_byteenable_write; + reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata; + user_start <= (mgmt_address == NM28_START_REG && mgmt_byteenable_write == 1'b1) ? 1'b1 : 1'b0; + end + end + + always @(*) + begin + if (mgmt_reset) + begin + mif_select <= 0; + end + else + begin + mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0; + end + end + + altera_pll_reconfig_mif_reader + #( + .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), + .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), + .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), + .ROM_DATA_WIDTH(ROM_DATA_WIDTH), + .ROM_NUM_WORDS(ROM_NUM_WORDS), + .DEVICE_FAMILY(device_family), + .ENABLE_MIF(ENABLE_MIF), + .MIF_FILE_NAME(MIF_FILE_NAME) + ) altera_pll_reconfig_mif_reader_inst0 ( + .mif_clk(mgmt_clk), + .mif_rst(mgmt_reset), + + //Altera_PLL Reconfig interface + //inputs + .reconfig_busy(reconfig_mgmt_waitrequest), + .reconfig_read_data(reconfig_mgmt_readdata), + //outputs + .reconfig_write_data(mif2reconfig_writedata), + .reconfig_addr(mif2reconfig_addr), + .reconfig_write(mif2reconfig_write), + .reconfig_read(mif2reconfig_read), + + //MIF Ctrl Interface + //inputs + .mif_base_addr(mif_base_addr), + .mif_start(reconfig2mif_start_out), + //outputs + .mif_busy(mif2reconfig_busy) + ); + + // ------ END MIF-RELATED MANAGEMENT ------ + + + altera_pll_reconfig_core + #( + .reconf_width(reconf_width), + .device_family(device_family), + .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), + .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), + .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), + .ROM_DATA_WIDTH(ROM_DATA_WIDTH), + .ROM_NUM_WORDS(ROM_NUM_WORDS) + ) altera_pll_reconfig_core_inst0 ( + //inputs + .mgmt_clk(mgmt_clk), + .mgmt_reset(mgmt_reset), + + //PLL interface conduits + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll), + + //User data outputs + .mgmt_readdata(reconfig_mgmt_readdata), + .mgmt_waitrequest(reconfig_mgmt_waitrequest), + + //User data inputs + .mgmt_address(reconfig_mgmt_addr), + .mgmt_read(reconfig_mgmt_read), + .mgmt_write(reconfig_mgmt_write), + .mgmt_writedata(reconfig_mgmt_writedata), + + // other + .mif_start_out(reconfig2mif_start_out), + .mif_base_addr(mif_base_addr) + ); + + end // End generate reconfig with MIF + else + begin:reconfig_core // Generate Reconfig core only + + wire reconfig2mif_start_out; + wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; + + altera_pll_reconfig_core + #( + .reconf_width(reconf_width), + .device_family(device_family), + .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), + .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), + .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), + .ROM_DATA_WIDTH(ROM_DATA_WIDTH), + .ROM_NUM_WORDS(ROM_NUM_WORDS) + ) altera_pll_reconfig_core_inst0 ( + //inputs + .mgmt_clk(mgmt_clk), + .mgmt_reset(mgmt_reset), + + //PLL interface conduits + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll), + + //User data outputs + .mgmt_readdata(mgmt_readdata), + .mgmt_waitrequest(mgmt_waitrequest), + + //User data inputs + .mgmt_address(mgmt_address), + .mgmt_read(mgmt_read), + .mgmt_write(mgmt_byteenable_write), + .mgmt_writedata(mgmt_writedata), + + // other + .mif_start_out(reconfig2mif_start_out), + .mif_base_addr(mif_base_addr) + ); + + + end // End generate reconfig core only +end // End 28nm Reconfig +endgenerate + +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg.v new file mode 100644 index 0000000000000000000000000000000000000000..0adc36f26727d8fbda1a080758ce2bc1f017e2fd --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg.v @@ -0,0 +1,86 @@ +// megafunction wizard: %Altera PLL Reconfig v17.0% +// GENERATION: XML +// pll_cfg.v + +// Generated using ACDS version 17.0 598 + +`timescale 1 ps / 1 ps +module pll_cfg #( + parameter ENABLE_BYTEENABLE = 0, + parameter BYTEENABLE_WIDTH = 4, + parameter RECONFIG_ADDR_WIDTH = 6, + parameter RECONFIG_DATA_WIDTH = 32, + parameter reconf_width = 64, + parameter WAIT_FOR_LOCK = 1 + ) ( + input wire mgmt_clk, // mgmt_clk.clk + input wire mgmt_reset, // mgmt_reset.reset + output wire mgmt_waitrequest, // mgmt_avalon_slave.waitrequest + input wire mgmt_read, // .read + input wire mgmt_write, // .write + output wire [31:0] mgmt_readdata, // .readdata + input wire [5:0] mgmt_address, // .address + input wire [31:0] mgmt_writedata, // .writedata + output wire [63:0] reconfig_to_pll, // reconfig_to_pll.reconfig_to_pll + input wire [63:0] reconfig_from_pll // reconfig_from_pll.reconfig_from_pll + ); + + altera_pll_reconfig_top #( + .device_family ("Cyclone V"), + .ENABLE_MIF (0), + .MIF_FILE_NAME ("sys/pll_cfg.mif"), + .ENABLE_BYTEENABLE (ENABLE_BYTEENABLE), + .BYTEENABLE_WIDTH (BYTEENABLE_WIDTH), + .RECONFIG_ADDR_WIDTH (RECONFIG_ADDR_WIDTH), + .RECONFIG_DATA_WIDTH (RECONFIG_DATA_WIDTH), + .reconf_width (reconf_width), + .WAIT_FOR_LOCK (WAIT_FOR_LOCK) + ) pll_cfg_inst ( + .mgmt_clk (mgmt_clk), // mgmt_clk.clk + .mgmt_reset (mgmt_reset), // mgmt_reset.reset + .mgmt_waitrequest (mgmt_waitrequest), // mgmt_avalon_slave.waitrequest + .mgmt_read (mgmt_read), // .read + .mgmt_write (mgmt_write), // .write + .mgmt_readdata (mgmt_readdata), // .readdata + .mgmt_address (mgmt_address), // .address + .mgmt_writedata (mgmt_writedata), // .writedata + .reconfig_to_pll (reconfig_to_pll), // reconfig_to_pll.reconfig_to_pll + .reconfig_from_pll (reconfig_from_pll), // reconfig_from_pll.reconfig_from_pll + .mgmt_byteenable (4'b0000) // (terminated) + ); + +endmodule +// Retrieval info: +// +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// IPFS_FILES : pll_cfg.vo +// RELATED_FILES: pll_cfg.v, altera_pll_reconfig_top.v, altera_pll_reconfig_core.v, altera_std_synchronizer.v diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg_hdmi.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg_hdmi.v new file mode 100644 index 0000000000000000000000000000000000000000..1912c2af7e44aa3fb813acabc0fd7dc00a2bb8e7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_cfg/pll_cfg_hdmi.v @@ -0,0 +1,1282 @@ +// (C) 2001-2017 Intel Corporation. All rights reserved. +// Your use of Intel Corporation's design tools, logic functions and other +// software and tools, and its AMPP partner logic functions, and any output +// files any of the foregoing (including device programming or simulation +// files), and any associated documentation or information are expressly subject +// to the terms and conditions of the Intel Program License Subscription +// Agreement, Intel MegaCore Function License Agreement, or other applicable +// license agreement, including, without limitation, that your use is for the +// sole purpose of programming logic devices manufactured by Intel and sold by +// Intel or its authorized distributors. Please refer to the applicable +// agreement for further details. + +// original file was altera_pll_reconfig_core.v +// not needed functionality was cut out to reduce ressource consumption + +module pll_cfg_hdmi +#( + parameter reconf_width = 64, + parameter device_family = "Cyclone V" +) ( + + //input + input wire mgmt_clk, + input wire mgmt_reset, + + + //conduits + output wire [reconf_width-1:0] reconfig_to_pll, + input wire [reconf_width-1:0] reconfig_from_pll, + + // user data (avalon-MM slave interface) + output wire mgmt_waitrequest, + input wire [5:0] mgmt_address, + input wire mgmt_write, + input wire [31:0] mgmt_writedata +); + localparam mode_WR = 1'b0; + localparam MODE_REG = 6'b000000; + localparam START_REG = 6'b000010; + localparam N_REG = 6'b000011; + localparam M_REG = 6'b000100; + localparam C_COUNTERS_REG = 6'b000101; + //localparam DPS_REG = 6'b000110; // unused + localparam DSM_REG = 6'b000111; + localparam BWCTRL_REG = 6'b001000; + localparam CP_CURRENT_REG = 6'b001001; + //localparam ANY_DPRIO = 6'b100000; // unused + //localparam CNT_BASE = 5'b001010; // unused + //localparam VCO_REG = 6'b011100; // unused + + //C Counters + localparam number_of_counters = 5'd6; + //C counter addresses + localparam C_CNT_0_DIV_ADDR = 5'h00; + localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11; + localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15; + localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17; + localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14; + localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16; + //N counter addresses + localparam N_CNT_DIV_ADDR = 5'h13; + localparam N_CNT_BYPASS_EN_ADDR = 5'h15; + localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17; + //M counter addresses + localparam M_CNT_DIV_ADDR = 5'h12; + localparam M_CNT_BYPASS_EN_ADDR = 5'h15; + localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17; + + //DSM address + localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18; + localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19; + localparam DSM_K_READY_ADDR = 5'h17; + localparam DSM_K_DITHER_ADDR = 5'h17; + localparam DSM_OUT_SEL_ADDR = 6'h30; + + //Other DSM params + localparam DSM_K_READY_BIT_INDEX = 4'd11; + //BWCTRL address + //Bit 0-3 of addr + localparam BWCTRL_ADDR = 6'h30; + //CP_CURRENT address + //Bit 0-2 of addr + localparam CP_CURRENT_ADDR = 6'h31; + + // VCODIV address + localparam VCO_ADDR = 5'h17; + + localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4, + FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10, + ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15; + localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10; + + wire clk; + wire reset; + wire gnd; + + wire [5: 0] slave_address; + wire slave_write; + wire [31: 0] slave_writedata; + + wire slave_waitrequest; + reg slave_mode; + + assign clk = mgmt_clk; + + assign slave_address = mgmt_address; + assign slave_write = mgmt_write; + assign slave_writedata = mgmt_writedata; + + // Outputs + assign mgmt_waitrequest = slave_waitrequest; //Read waitrequest asserted in polling mode + + //internal signals + wire locked_orig; + wire locked; + + wire pll_start; + wire pll_start_valid; + + wire pll_start_asserted; + + reg [1:0] current_state; + reg [1:0] next_state; + + reg status;//0=busy, 1=ready + //user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load); + //declaring the init wires. These will have 0 on them for 64 clk cycles + wire [ 5:0] init_dprio_address; + wire init_dprio_read; + wire [ 1:0] init_dprio_byteen; + wire init_dprio_write; + wire [15:0] init_dprio_writedata; + + wire init_atpgmode; + wire init_mdio_dis; + wire init_scanen; + wire init_ser_shift_load; + wire dprio_init_done; + + //DPRIO output signals after initialization is done + wire dprio_clk; + reg avmm_dprio_write; + reg avmm_dprio_read; + reg [5:0] avmm_dprio_address; + reg [15:0] avmm_dprio_writedata; + reg [1:0] avmm_dprio_byteen; + wire avmm_atpgmode; + wire avmm_mdio_dis; + wire avmm_scanen; + + //Final output wires that are muxed between the init and avmm wires. + wire dprio_init_reset; + wire [5:0] dprio_address /*synthesis keep*/; + wire dprio_read/*synthesis keep*/; + wire [1:0] dprio_byteen/*synthesis keep*/; + wire dprio_write/*synthesis keep*/; + wire [15:0] dprio_writedata/*synthesis keep*/; + wire dprio_mdio_dis/*synthesis keep*/; + wire dprio_ser_shift_load/*synthesis keep*/; + wire dprio_atpgmode/*synthesis keep*/; + wire dprio_scanen/*synthesis keep*/; + + + //other PLL signals for dyn ph shift + wire phase_done/*synthesis keep*/; + wire phase_en/*synthesis keep*/; + wire up_dn/*synthesis keep*/; + wire [4:0] cnt_sel; + + //DPRIO input signals + wire [15:0] dprio_readdata; + + //internal logic signals + //storage registers for user sent data + reg dprio_temp_read_1; + reg dprio_temp_read_2; + reg dprio_start; + wire usr_valid_changes; + reg [3:0] dprio_cur_state; + reg [3:0] dprio_next_state; + reg [15:0] dprio_temp_m_n_c_readdata_1_d; + reg [15:0] dprio_temp_m_n_c_readdata_2_d; + reg [15:0] dprio_temp_m_n_c_readdata_1_q; + reg [15:0] dprio_temp_m_n_c_readdata_2_q; + reg dprio_write_done; + //C counters signals + reg [7:0] usr_c_cnt_lo; + reg [7:0] usr_c_cnt_hi; + reg usr_c_cnt_bypass_en; + reg usr_c_cnt_odd_duty_div_en; + reg temp_c_cnt_bypass_en [0:17]; + reg temp_c_cnt_odd_duty_div_en [0:17]; + reg any_c_cnt_changed; + reg all_c_cnt_done_q; + reg all_c_cnt_done_d; + reg [17:0] c_cnt_changed; + reg [17:0] c_cnt_done_d; + reg [17:0] c_cnt_done_q; + //N counter signals + reg [7:0] usr_n_cnt_lo; + reg [7:0] usr_n_cnt_hi; + reg usr_n_cnt_bypass_en; + reg usr_n_cnt_odd_duty_div_en; + reg n_cnt_changed; + reg n_cnt_done_d; + reg n_cnt_done_q; + //M counter signals + reg [7:0] usr_m_cnt_lo; + reg [7:0] usr_m_cnt_hi; + reg usr_m_cnt_bypass_en; + reg usr_m_cnt_odd_duty_div_en; + reg m_cnt_changed; + reg m_cnt_done_d; + reg m_cnt_done_q; + //dyn phase regs + reg [15:0] usr_num_shifts; + reg [4:0] usr_cnt_sel /*synthesis preserve*/; + reg usr_up_dn; + reg dps_changed; + wire dps_changed_valid; + wire dps_done; + + //DSM Signals + reg [31:0] usr_k_value; + reg dsm_k_changed; + reg dsm_k_done_d; + reg dsm_k_done_q; + reg dsm_k_ready_false_done_d; + //BW signals + reg [3:0] usr_bwctrl_value; + reg bwctrl_changed; + reg bwctrl_done_d; + reg bwctrl_done_q; + //CP signals + reg [2:0] usr_cp_current_value; + reg cp_current_changed; + reg cp_current_done_d; + reg cp_current_done_q; + //VCO signals + reg usr_vco_value; + reg vco_changed; + reg vco_done_d; + reg vco_done_q; + //Manual DPRIO signals + reg manual_dprio_done_q; + reg manual_dprio_done_d; + reg manual_dprio_changed; + reg [5:0] usr_dprio_address; + reg [15:0] usr_dprio_writedata_0; + reg usr_r_w; + //keeping track of which operation happened last + reg [5:0] operation_address; + // Address wires for all C_counter DPRIO registers + // These are outputs of LUTS, changing depending + // on whether PLL_0 or PLL_1 being used + + + //Fitter will tell if FPLL1 is being used + wire fpll_1; + + // MAIN FSM + + // Synchronize locked signal + altera_std_synchronizer #( + .depth(3) + ) altera_std_synchronizer_inst ( + .clk(mgmt_clk), + .reset_n(~mgmt_reset), + .din(locked_orig), + .dout(locked) + ); + + always @(posedge clk) + begin + if (reset) + begin + dprio_cur_state <= DPRIO_IDLE; + current_state <= IDLE; + end + else + begin + current_state <= next_state; + dprio_cur_state <= dprio_next_state; + end + end + + always @(*) + begin + case(current_state) + IDLE: + begin + if (pll_start & !slave_waitrequest & usr_valid_changes) + next_state = WAIT_ON_LOCK; + else + next_state = IDLE; + end + WAIT_ON_LOCK: + begin + if (locked & dps_done & dprio_write_done) // received locked high from PLL + begin + if (slave_mode==mode_WR) //if the mode is waitrequest, then + // goto IDLE state directly + next_state = IDLE; + else + next_state = LOCKED; //otherwise go the locked state + end + else + next_state = WAIT_ON_LOCK; + end + + LOCKED: + begin + next_state = LOCKED; + end + + default: next_state = 2'bxx; + + endcase + end + + + // ask the pll to start reconfig + assign pll_start = (pll_start_asserted & (current_state==IDLE)) ; + assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ; + + + + // WRITE OPERATIONS + assign pll_start_asserted = slave_write & (slave_address == START_REG); + + //reading the mode register to determine what mode the slave will operate + //in. + always @(posedge clk) + begin + if (reset) + slave_mode <= mode_WR; + else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest) + slave_mode <= slave_writedata[0]; + end + + //record which values user wants to change. + + //reading in the actual values that need to be reconfigged and sending + //them to the PLL + always @(posedge clk) + begin + if (reset) + begin + //reset all regs here + //BW signals reset + usr_bwctrl_value <= 0; + bwctrl_changed <= 0; + bwctrl_done_q <= 0; + //CP signals reset + usr_cp_current_value <= 0; + cp_current_changed <= 0; + cp_current_done_q <= 0; + //VCO signals reset + usr_vco_value <= 0; + vco_changed <= 0; + vco_done_q <= 0; + //DSM signals reset + usr_k_value <= 0; + dsm_k_changed <= 0; + dsm_k_done_q <= 0; + //N counter signals reset + usr_n_cnt_lo <= 0; + usr_n_cnt_hi <= 0; + usr_n_cnt_bypass_en <= 0; + usr_n_cnt_odd_duty_div_en <= 0; + n_cnt_changed <= 0; + n_cnt_done_q <= 0; + //M counter signals reset + usr_m_cnt_lo <= 0; + usr_m_cnt_hi <= 0; + usr_m_cnt_bypass_en <= 0; + usr_m_cnt_odd_duty_div_en <= 0; + m_cnt_changed <= 0; + m_cnt_done_q <= 0; + //C counter signals reset + usr_c_cnt_lo <= 0; + usr_c_cnt_hi <= 0; + usr_c_cnt_bypass_en <= 0; + usr_c_cnt_odd_duty_div_en <= 0; + any_c_cnt_changed <= 0; + all_c_cnt_done_q <= 0; + c_cnt_done_q <= 0; + //generic signals + dprio_start <= 0; + dprio_temp_m_n_c_readdata_1_q <= 0; + dprio_temp_m_n_c_readdata_2_q <= 0; + c_cnt_done_q <= 0; + //DPS signals + usr_up_dn <= 0; + usr_cnt_sel <= 0; + usr_num_shifts <= 0; + dps_changed <= 0; + //manual DPRIO signals + manual_dprio_changed <= 0; + usr_dprio_address <= 0; + usr_dprio_writedata_0 <= 0; + usr_r_w <= 0; + operation_address <= 0; + end + else + begin + if (dprio_temp_read_1) + begin + dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d; + end + if (dprio_temp_read_2) + begin + dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d; + end + if ((dps_done)) dps_changed <= 0; + if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d; + if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d; + if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d; + if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d; + if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d; + if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d; + if (cp_current_done_d) cp_current_done_q <= cp_current_done_d; + if (vco_done_d) vco_done_q <= vco_done_d; + if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d; + + if (dprio_next_state == ONE) + dprio_start <= 0; + if (dprio_write_done) + begin + bwctrl_done_q <= 0; + cp_current_done_q <= 0; + vco_done_q <= 0; + dsm_k_done_q <= 0; + dsm_k_done_q <= 0; + n_cnt_done_q <= 0; + m_cnt_done_q <= 0; + all_c_cnt_done_q <= 0; + c_cnt_done_q <= 0; + dsm_k_changed <= 0; + n_cnt_changed <= 0; + m_cnt_changed <= 0; + any_c_cnt_changed <= 0; + bwctrl_changed <= 0; + cp_current_changed <= 0; + vco_changed <= 0; + manual_dprio_changed <= 0; + manual_dprio_done_q <= 0; + + end + else + begin + dsm_k_changed <= dsm_k_changed; + n_cnt_changed <= n_cnt_changed; + m_cnt_changed <= m_cnt_changed; + any_c_cnt_changed <= any_c_cnt_changed; + manual_dprio_changed <= manual_dprio_changed; + end + + + if(slave_write & !slave_waitrequest) + begin + case(slave_address) + //read in the values here from the user and act on them + DSM_REG: + begin + operation_address <= DSM_REG; + usr_k_value <= slave_writedata[31:0]; + dsm_k_changed <= 1'b1; + dsm_k_done_q <= 0; + dprio_start <= 1'b1; + end + N_REG: + begin + operation_address <= N_REG; + usr_n_cnt_lo <= slave_writedata[7:0]; + usr_n_cnt_hi <= slave_writedata[15:8]; + usr_n_cnt_bypass_en <= slave_writedata[16]; + usr_n_cnt_odd_duty_div_en <= slave_writedata[17]; + n_cnt_changed <= 1'b1; + n_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + M_REG: + begin + operation_address <= M_REG; + usr_m_cnt_lo <= slave_writedata[7:0]; + usr_m_cnt_hi <= slave_writedata[15:8]; + usr_m_cnt_bypass_en <= slave_writedata[16]; + usr_m_cnt_odd_duty_div_en <= slave_writedata[17]; + m_cnt_changed <= 1'b1; + m_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + //DPS_REG: + //begin + // operation_address <= DPS_REG; + // usr_num_shifts <= slave_writedata[15:0]; + // usr_up_dn <= slave_writedata[21]; + // dps_changed <= 1; + //end + C_COUNTERS_REG: + begin + operation_address <= C_COUNTERS_REG; + usr_c_cnt_lo <= slave_writedata[7:0]; + usr_c_cnt_hi <= slave_writedata[15:8]; + usr_c_cnt_bypass_en <= slave_writedata[16]; + usr_c_cnt_odd_duty_div_en <= slave_writedata[17]; + any_c_cnt_changed <= 1'b1; + all_c_cnt_done_q <= 0; + dprio_start <= 1'b1; + end + BWCTRL_REG: + begin + usr_bwctrl_value <= slave_writedata[3:0]; + bwctrl_changed <= 1'b1; + bwctrl_done_q <= 0; + dprio_start <= 1'b1; + operation_address <= BWCTRL_REG; + end + CP_CURRENT_REG: + begin + usr_cp_current_value <= slave_writedata[2:0]; + cp_current_changed <= 1'b1; + cp_current_done_q <= 0; + dprio_start <= 1'b1; + operation_address <= CP_CURRENT_REG; + end + //VCO_REG: + //begin + // usr_vco_value <= slave_writedata[0]; + // vco_changed <= 1'b1; + // vco_done_q <= 0; + // dprio_start <= 1'b1; + // operation_address <= VCO_REG; + //end + //ANY_DPRIO: + //begin + // operation_address <= ANY_DPRIO; + // manual_dprio_changed <= 1'b1; + // usr_dprio_address <= slave_writedata[5:0]; + // usr_dprio_writedata_0 <= slave_writedata[21:6]; + // usr_r_w <= slave_writedata[22]; + // manual_dprio_done_q <= 0; + // dprio_start <= 1'b1; + //end + endcase + end + end + end + //C Counter assigning values to the 2-d array of values for each C counter + + reg [4:0] j; + always @(posedge clk) + begin + + if (reset) + begin + c_cnt_changed[17:0] <= 0; + for (j = 0; j < number_of_counters; j = j + 1'b1) + begin : c_cnt_reset + temp_c_cnt_bypass_en[j] <= 0; + temp_c_cnt_odd_duty_div_en[j] <= 0; + end + end + else + begin + if (dprio_write_done) + begin + c_cnt_changed <= 0; + end + if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG)) + begin + temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en; + temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en; + c_cnt_changed [5] <= 1'b1; + end + end + end + + + //logic to handle which writes the user indicated and wants to start. + assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed|vco_changed; + + + //start the reconfig operations by writing to the DPRIO + reg break_loop; + reg [4:0] i; + always @(*) + begin + dprio_temp_read_1 = 0; + dprio_temp_read_2 = 0; + dprio_temp_m_n_c_readdata_1_d = 0; + dprio_temp_m_n_c_readdata_2_d = 0; + break_loop = 0; + dprio_next_state = DPRIO_IDLE; + avmm_dprio_write = 0; + avmm_dprio_read = 0; + avmm_dprio_address = 0; + avmm_dprio_writedata = 0; + avmm_dprio_byteen = 0; + dprio_write_done = 1; + manual_dprio_done_d = 0; + n_cnt_done_d = 0; + dsm_k_done_d = 0; + dsm_k_ready_false_done_d = 0; + m_cnt_done_d = 0; + c_cnt_done_d[17:0] = 0; + all_c_cnt_done_d = 0; + bwctrl_done_d = 0; + cp_current_done_d = 0; + vco_done_d = 0; + i = 0; + + // Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes) + if (dprio_start) + dprio_write_done = 0; + + if (current_state == WAIT_ON_LOCK) + begin + case (dprio_cur_state) + ONE: + begin + if (n_cnt_changed & !n_cnt_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_address = N_CNT_DIV_ADDR; + avmm_dprio_writedata[7:0] = usr_n_cnt_lo; + avmm_dprio_writedata[15:8] = usr_n_cnt_hi; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_address = M_CNT_DIV_ADDR; + avmm_dprio_writedata[7:0] = usr_m_cnt_lo; + avmm_dprio_writedata[15:8] = usr_m_cnt_hi; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + + for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_hilo + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i; + else avmm_dprio_address = C_CNT_0_DIV_ADDR + i; + avmm_dprio_writedata[7:0] = usr_c_cnt_lo; + avmm_dprio_writedata[15:8] = usr_c_cnt_hi; + //To break from the loop, since only one counter + //is addressed at a time + break_loop = 1'b1; + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (cp_current_changed & !cp_current_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (vco_changed & !vco_done_q) + begin + dprio_write_done = 0; + avmm_dprio_write = 0; + dprio_next_state = TWO; + end + else if (manual_dprio_changed & !manual_dprio_done_q) + begin + dprio_write_done = 0; + avmm_dprio_byteen = 2'b11; + dprio_next_state = TWO; + avmm_dprio_write = usr_r_w; + avmm_dprio_address = usr_dprio_address; + avmm_dprio_writedata[15:0] = usr_dprio_writedata_0; + end + else dprio_next_state = DPRIO_IDLE; + end + + TWO: + begin + //handle reading the two setting bits on n_cnt, then + //writing them back while preserving other bits. + //Issue two consecutive reads then wait; readLatency=3 + dprio_write_done = 0; + dprio_next_state = THREE; + avmm_dprio_byteen = 2'b11; + avmm_dprio_read = 1'b1; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_BYPASS_EN_ADDR; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_BYPASS_EN_ADDR; + end + + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 5; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_read_bypass + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + break_loop = 1'b1; + end + end + end + end + end + //reading the K ready 16 bit word. Need to write 0 to it + //afterwards to indicate that K has not been done writing + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + dprio_next_state = FOUR; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_address = BWCTRL_ADDR; + dprio_next_state = FOUR; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_address = CP_CURRENT_ADDR; + dprio_next_state = FOUR; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_address = VCO_ADDR; + dprio_next_state = FOUR; + end + else if (manual_dprio_changed & !manual_dprio_done_q) + begin + avmm_dprio_read = ~usr_r_w; + avmm_dprio_address = usr_dprio_address; + dprio_next_state = DPRIO_DONE; + end + else dprio_next_state = DPRIO_IDLE; + end + THREE: + begin + dprio_write_done = 0; + avmm_dprio_byteen = 2'b11; + avmm_dprio_read = 1'b1; + dprio_next_state = FOUR; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 5; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_read_odd_div + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + break_loop = 1'b1; + end + end + end + end + end + else dprio_next_state = DPRIO_IDLE; + end + FOUR: + begin + dprio_temp_read_1 = 1'b1; + dprio_write_done = 0; + if (vco_changed|cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed) + begin + dprio_temp_m_n_c_readdata_1_d = dprio_readdata; + dprio_next_state = FIVE; + end + else dprio_next_state = DPRIO_IDLE; + end + FIVE: + begin + dprio_write_done = 0; + dprio_temp_read_2 = 1'b1; + if (vco_changed|cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed) + begin + //this is where DSM ready value comes. + //Need to store in a register to be used later + dprio_temp_m_n_c_readdata_2_d = dprio_readdata; + dprio_next_state = SIX; + end + else dprio_next_state = DPRIO_IDLE; + end + SIX: + begin + dprio_write_done = 0; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + dprio_next_state = SEVEN; + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_BYPASS_EN_ADDR; + avmm_dprio_writedata[5] = usr_n_cnt_bypass_en; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_BYPASS_EN_ADDR; + avmm_dprio_writedata[4] = usr_m_cnt_bypass_en; + end + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 5; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_bypass + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR; + avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR; + avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i]; + break_loop = 1'b1; + end + end + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_write = 0; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_write = 0; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_write = 0; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_write = 0; + end + else dprio_next_state = DPRIO_IDLE; + end + SEVEN: + begin + dprio_write_done = 0; + dprio_next_state = EIGHT; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q; + if (n_cnt_changed & !n_cnt_done_q) + begin + avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en; + n_cnt_done_d = 1'b1; + end + else if (m_cnt_changed & !m_cnt_done_q) + begin + avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en; + m_cnt_done_d = 1'b1; + end + + else if (any_c_cnt_changed & !all_c_cnt_done_q) + begin + for (i = 5; (i < number_of_counters) & !break_loop; i = i + 1'b1) + begin : c_cnt_write_odd_div + if (fpll_1) + begin + if (i > 13) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + //have to OR the signals to prevent + //overwriting of previous dones + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + end + else + begin + if (i < 4) + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + //have to OR the signals to prevent + //overwriting of previous dones + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + else + begin + if (c_cnt_changed[i] & !c_cnt_done_q[i]) + begin + avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR; + avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i]; + c_cnt_done_d[i] = 1'b1; + c_cnt_done_d = c_cnt_done_d | c_cnt_done_q; + break_loop = 1'b1; + end + end + end + end + end + else if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0; + dsm_k_ready_false_done_d = 1'b1; + end + else if (bwctrl_changed & !bwctrl_done_q) + begin + avmm_dprio_address = BWCTRL_ADDR; + avmm_dprio_writedata[3:0] = usr_bwctrl_value; + bwctrl_done_d = 1'b1; + end + else if (cp_current_changed & !cp_current_done_q) + begin + avmm_dprio_address = CP_CURRENT_ADDR; + avmm_dprio_writedata[2:0] = usr_cp_current_value; + cp_current_done_d = 1'b1; + end + else if (vco_changed & !vco_done_q) + begin + avmm_dprio_address = VCO_ADDR; + avmm_dprio_writedata[8] = usr_vco_value; + vco_done_d = 1'b1; + end + + + //if all C_cnt that were changed are done, then assert all_c_cnt_done + if (c_cnt_done_d == c_cnt_changed) + all_c_cnt_done_d = 1'b1; + if (n_cnt_changed & n_cnt_done_d) + dprio_next_state = DPRIO_DONE; + if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q) + dprio_next_state = ONE; + else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q) + dprio_next_state = ONE; + else if (dsm_k_changed & !dsm_k_ready_false_done_d) + dprio_next_state = TWO; + else if (dsm_k_changed & !dsm_k_done_q) + dprio_next_state = EIGHT; + else if (bwctrl_changed & !bwctrl_done_d) + dprio_next_state = TWO; + else if (cp_current_changed & !cp_current_done_d) + dprio_next_state = TWO; + else if (vco_changed & !vco_done_d) + dprio_next_state = TWO; + else + begin + dprio_next_state = DPRIO_DONE; + dprio_write_done = 1'b1; + end + end + //finish the rest of the DSM reads/writes + //writing k value, writing k_ready to 1. + EIGHT: + begin + dprio_write_done = 0; + dprio_next_state = NINE; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0; + avmm_dprio_writedata[15:0] = usr_k_value[15:0]; + end + end + NINE: + begin + dprio_write_done = 0; + dprio_next_state = TEN; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1; + avmm_dprio_writedata[15:0] = usr_k_value[31:16]; + end + end + TEN: + begin + dprio_write_done = 0; + dprio_next_state = ONE; + avmm_dprio_write = 1'b1; + avmm_dprio_byteen = 2'b11; + if (dsm_k_changed & !dsm_k_done_q) + begin + avmm_dprio_address = DSM_K_READY_ADDR; + //already have the readdata for DSM_K_READY_ADDR since we read it + //earlier. Just reuse here + avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q; + avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1; + dsm_k_done_d = 1'b1; + end + end + DPRIO_DONE: + begin + dprio_write_done = 1'b1; + if (dprio_start) dprio_next_state = DPRIO_IDLE; + else dprio_next_state = DPRIO_DONE; + end + DPRIO_IDLE: + begin + if (dprio_start) dprio_next_state = ONE; + else dprio_next_state = DPRIO_IDLE; + end + default: dprio_next_state = 4'bxxxx; + endcase + end + + end + + + //assert the waitreq signal according to the state of the slave + assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0; + + + dyn_phase_shift dyn_phase_shift_inst ( + .clk(clk), + .reset(reset), + .phase_done(phase_done), + .pll_start_valid(pll_start_valid), + .dps_changed(dps_changed), + .dps_changed_valid(dps_changed_valid), + .dprio_write_done(dprio_write_done), + .usr_num_shifts(usr_num_shifts), + .usr_cnt_sel(usr_cnt_sel), + .usr_up_dn(usr_up_dn), + .locked(locked), + .dps_done(dps_done), + .phase_en(phase_en), + .up_dn(up_dn), + .cnt_sel(cnt_sel)); + defparam dyn_phase_shift_inst.device_family = device_family; + + assign dprio_clk = clk; + self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset); + + dprio_mux dprio_mux_inst ( + .init_dprio_address(init_dprio_address), + .init_dprio_read(init_dprio_read), + .init_dprio_byteen(init_dprio_byteen), + .init_dprio_write(init_dprio_write), + .init_dprio_writedata(init_dprio_writedata), + + + .init_atpgmode(init_atpgmode), + .init_mdio_dis(init_mdio_dis), + .init_scanen(init_scanen), + .init_ser_shift_load(init_ser_shift_load), + .dprio_init_done(dprio_init_done), + + // Inputs from avmm master + .avmm_dprio_address(avmm_dprio_address), + .avmm_dprio_read(avmm_dprio_read), + .avmm_dprio_byteen(avmm_dprio_byteen), + .avmm_dprio_write(avmm_dprio_write), + .avmm_dprio_writedata(avmm_dprio_writedata), + + .avmm_atpgmode(avmm_atpgmode), + .avmm_mdio_dis(avmm_mdio_dis), + .avmm_scanen(avmm_scanen), + + // Outputs to fpll + .dprio_address(dprio_address), + .dprio_read(dprio_read), + .dprio_byteen(dprio_byteen), + .dprio_write(dprio_write), + .dprio_writedata(dprio_writedata), + + .atpgmode(dprio_atpgmode), + .mdio_dis(dprio_mdio_dis), + .scanen(dprio_scanen), + .ser_shift_load(dprio_ser_shift_load) + ); + + + fpll_dprio_init fpll_dprio_init_inst ( + .clk(clk), + .reset_n(~reset), + .locked(locked), + + //outputs + .dprio_address(init_dprio_address), + .dprio_read(init_dprio_read), + .dprio_byteen(init_dprio_byteen), + .dprio_write(init_dprio_write), + .dprio_writedata(init_dprio_writedata), + + .atpgmode(init_atpgmode), + .mdio_dis(init_mdio_dis), + .scanen(init_scanen), + .ser_shift_load(init_ser_shift_load), + .dprio_init_done(dprio_init_done)); + + //address luts, to be reconfigged by the Fitter + //FPLL_1 or 0 address lut + generic_lcell_comb lcell_fpll_0_1 ( + .dataa(1'b0), + .combout (fpll_1)); + defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA; + defparam lcell_fpll_0_1.dont_touch = "on"; + defparam lcell_fpll_0_1.family = device_family; + + + wire dprio_read_combout; + generic_lcell_comb lcell_dprio_read ( + .dataa(fpll_1), + .datab(dprio_read), + .datac(1'b0), + .datad(1'b0), + .datae(1'b0), + .dataf(1'b0), + .combout (dprio_read_combout)); + defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC; + defparam lcell_dprio_read.dont_touch = "on"; + defparam lcell_dprio_read.family = device_family; + + + + + + //assign reconfig_to_pll signals + assign reconfig_to_pll[0] = dprio_clk; + assign reconfig_to_pll[1] = ~dprio_init_reset; + assign reconfig_to_pll[2] = dprio_write; + assign reconfig_to_pll[3] = dprio_read_combout; + assign reconfig_to_pll[9:4] = dprio_address; + assign reconfig_to_pll[25:10] = dprio_writedata; + assign reconfig_to_pll[27:26] = dprio_byteen; + assign reconfig_to_pll[28] = dprio_ser_shift_load; + assign reconfig_to_pll[29] = dprio_mdio_dis; + assign reconfig_to_pll[30] = phase_en; + assign reconfig_to_pll[31] = up_dn; + assign reconfig_to_pll[36:32] = cnt_sel; + assign reconfig_to_pll[37] = dprio_scanen; + assign reconfig_to_pll[38] = dprio_atpgmode; + //assign reconfig_to_pll[40:37] = clken; + assign reconfig_to_pll[63:39] = 0; + + //assign reconfig_from_pll signals + assign dprio_readdata = reconfig_from_pll [15:0]; + assign locked_orig = reconfig_from_pll [16]; + assign phase_done = reconfig_from_pll [17]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi.v new file mode 100644 index 0000000000000000000000000000000000000000..0cefd2546624c2ae252348963be192c39f7342ee --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi.v @@ -0,0 +1,256 @@ +// megafunction wizard: %Altera PLL v17.0% +// GENERATION: XML +// pll_hdmi.v + +// Generated using ACDS version 17.0 598 + +`timescale 1 ps / 1 ps +module pll_hdmi ( + input wire refclk, // refclk.clk + input wire rst, // reset.reset + output wire outclk_0, // outclk0.clk + input wire [63:0] reconfig_to_pll, // reconfig_to_pll.reconfig_to_pll + output wire [63:0] reconfig_from_pll // reconfig_from_pll.reconfig_from_pll + ); + + pll_hdmi_0002 pll_hdmi_inst ( + .refclk (refclk), // refclk.clk + .rst (rst), // reset.reset + .outclk_0 (outclk_0), // outclk0.clk + .reconfig_to_pll (reconfig_to_pll), // reconfig_to_pll.reconfig_to_pll + .reconfig_from_pll (reconfig_from_pll), // reconfig_from_pll.reconfig_from_pll + .locked () // (terminated) + ); + +endmodule +// Retrieval info: +// +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// Retrieval info: +// IPFS_FILES : pll_hdmi.vo +// RELATED_FILES: pll_hdmi.v, pll_hdmi_0002.v diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi/pll_hdmi_0002.v b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi/pll_hdmi_0002.v new file mode 100644 index 0000000000000000000000000000000000000000..9347c76021f035efafef82e1ca3381451dd0d4a6 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi/pll_hdmi_0002.v @@ -0,0 +1,241 @@ +`timescale 1ns/10ps +module pll_hdmi_0002( + + // interface 'refclk' + input wire refclk, + + // interface 'reset' + input wire rst, + + // interface 'outclk0' + output wire outclk_0, + + // interface 'locked' + output wire locked, + + // interface 'reconfig_to_pll' + input wire [63:0] reconfig_to_pll, + + // interface 'reconfig_from_pll' + output wire [63:0] reconfig_from_pll +); + + altera_pll #( + .fractional_vco_multiplier("true"), + .reference_clock_frequency("50.0 MHz"), + .pll_fractional_cout(32), + .pll_dsm_out_sel("1st_order"), + .operation_mode("direct"), + .number_of_clocks(1), + .output_clock_frequency0("148.500000 MHz"), + .phase_shift0("0 ps"), + .duty_cycle0(50), + .output_clock_frequency1("0 MHz"), + .phase_shift1("0 ps"), + .duty_cycle1(50), + .output_clock_frequency2("0 MHz"), + .phase_shift2("0 ps"), + .duty_cycle2(50), + .output_clock_frequency3("0 MHz"), + .phase_shift3("0 ps"), + .duty_cycle3(50), + .output_clock_frequency4("0 MHz"), + .phase_shift4("0 ps"), + .duty_cycle4(50), + .output_clock_frequency5("0 MHz"), + .phase_shift5("0 ps"), + .duty_cycle5(50), + .output_clock_frequency6("0 MHz"), + .phase_shift6("0 ps"), + .duty_cycle6(50), + .output_clock_frequency7("0 MHz"), + .phase_shift7("0 ps"), + .duty_cycle7(50), + .output_clock_frequency8("0 MHz"), + .phase_shift8("0 ps"), + .duty_cycle8(50), + .output_clock_frequency9("0 MHz"), + .phase_shift9("0 ps"), + .duty_cycle9(50), + .output_clock_frequency10("0 MHz"), + .phase_shift10("0 ps"), + .duty_cycle10(50), + .output_clock_frequency11("0 MHz"), + .phase_shift11("0 ps"), + .duty_cycle11(50), + .output_clock_frequency12("0 MHz"), + .phase_shift12("0 ps"), + .duty_cycle12(50), + .output_clock_frequency13("0 MHz"), + .phase_shift13("0 ps"), + .duty_cycle13(50), + .output_clock_frequency14("0 MHz"), + .phase_shift14("0 ps"), + .duty_cycle14(50), + .output_clock_frequency15("0 MHz"), + .phase_shift15("0 ps"), + .duty_cycle15(50), + .output_clock_frequency16("0 MHz"), + .phase_shift16("0 ps"), + .duty_cycle16(50), + .output_clock_frequency17("0 MHz"), + .phase_shift17("0 ps"), + .duty_cycle17(50), + .pll_type("Cyclone V"), + .pll_subtype("Reconfigurable"), + .m_cnt_hi_div(4), + .m_cnt_lo_div(4), + .n_cnt_hi_div(256), + .n_cnt_lo_div(256), + .m_cnt_bypass_en("false"), + .n_cnt_bypass_en("true"), + .m_cnt_odd_div_duty_en("false"), + .n_cnt_odd_div_duty_en("false"), + .c_cnt_hi_div0(2), + .c_cnt_lo_div0(1), + .c_cnt_prst0(1), + .c_cnt_ph_mux_prst0(0), + .c_cnt_in_src0("ph_mux_clk"), + .c_cnt_bypass_en0("false"), + .c_cnt_odd_div_duty_en0("true"), + .c_cnt_hi_div1(1), + .c_cnt_lo_div1(1), + .c_cnt_prst1(1), + .c_cnt_ph_mux_prst1(0), + .c_cnt_in_src1("ph_mux_clk"), + .c_cnt_bypass_en1("true"), + .c_cnt_odd_div_duty_en1("false"), + .c_cnt_hi_div2(1), + .c_cnt_lo_div2(1), + .c_cnt_prst2(1), + .c_cnt_ph_mux_prst2(0), + .c_cnt_in_src2("ph_mux_clk"), + .c_cnt_bypass_en2("true"), + .c_cnt_odd_div_duty_en2("false"), + .c_cnt_hi_div3(1), + .c_cnt_lo_div3(1), + .c_cnt_prst3(1), + .c_cnt_ph_mux_prst3(0), + .c_cnt_in_src3("ph_mux_clk"), + .c_cnt_bypass_en3("true"), + .c_cnt_odd_div_duty_en3("false"), + .c_cnt_hi_div4(1), + .c_cnt_lo_div4(1), + .c_cnt_prst4(1), + .c_cnt_ph_mux_prst4(0), + .c_cnt_in_src4("ph_mux_clk"), + .c_cnt_bypass_en4("true"), + .c_cnt_odd_div_duty_en4("false"), + .c_cnt_hi_div5(1), + .c_cnt_lo_div5(1), + .c_cnt_prst5(1), + .c_cnt_ph_mux_prst5(0), + .c_cnt_in_src5("ph_mux_clk"), + .c_cnt_bypass_en5("true"), + .c_cnt_odd_div_duty_en5("false"), + .c_cnt_hi_div6(1), + .c_cnt_lo_div6(1), + .c_cnt_prst6(1), + .c_cnt_ph_mux_prst6(0), + .c_cnt_in_src6("ph_mux_clk"), + .c_cnt_bypass_en6("true"), + .c_cnt_odd_div_duty_en6("false"), + .c_cnt_hi_div7(1), + .c_cnt_lo_div7(1), + .c_cnt_prst7(1), + .c_cnt_ph_mux_prst7(0), + .c_cnt_in_src7("ph_mux_clk"), + .c_cnt_bypass_en7("true"), + .c_cnt_odd_div_duty_en7("false"), + .c_cnt_hi_div8(1), + .c_cnt_lo_div8(1), + .c_cnt_prst8(1), + .c_cnt_ph_mux_prst8(0), + .c_cnt_in_src8("ph_mux_clk"), + .c_cnt_bypass_en8("true"), + .c_cnt_odd_div_duty_en8("false"), + .c_cnt_hi_div9(1), + .c_cnt_lo_div9(1), + .c_cnt_prst9(1), + .c_cnt_ph_mux_prst9(0), + .c_cnt_in_src9("ph_mux_clk"), + .c_cnt_bypass_en9("true"), + .c_cnt_odd_div_duty_en9("false"), + .c_cnt_hi_div10(1), + .c_cnt_lo_div10(1), + .c_cnt_prst10(1), + .c_cnt_ph_mux_prst10(0), + .c_cnt_in_src10("ph_mux_clk"), + .c_cnt_bypass_en10("true"), + .c_cnt_odd_div_duty_en10("false"), + .c_cnt_hi_div11(1), + .c_cnt_lo_div11(1), + .c_cnt_prst11(1), + .c_cnt_ph_mux_prst11(0), + .c_cnt_in_src11("ph_mux_clk"), + .c_cnt_bypass_en11("true"), + .c_cnt_odd_div_duty_en11("false"), + .c_cnt_hi_div12(1), + .c_cnt_lo_div12(1), + .c_cnt_prst12(1), + .c_cnt_ph_mux_prst12(0), + .c_cnt_in_src12("ph_mux_clk"), + .c_cnt_bypass_en12("true"), + .c_cnt_odd_div_duty_en12("false"), + .c_cnt_hi_div13(1), + .c_cnt_lo_div13(1), + .c_cnt_prst13(1), + .c_cnt_ph_mux_prst13(0), + .c_cnt_in_src13("ph_mux_clk"), + .c_cnt_bypass_en13("true"), + .c_cnt_odd_div_duty_en13("false"), + .c_cnt_hi_div14(1), + .c_cnt_lo_div14(1), + .c_cnt_prst14(1), + .c_cnt_ph_mux_prst14(0), + .c_cnt_in_src14("ph_mux_clk"), + .c_cnt_bypass_en14("true"), + .c_cnt_odd_div_duty_en14("false"), + .c_cnt_hi_div15(1), + .c_cnt_lo_div15(1), + .c_cnt_prst15(1), + .c_cnt_ph_mux_prst15(0), + .c_cnt_in_src15("ph_mux_clk"), + .c_cnt_bypass_en15("true"), + .c_cnt_odd_div_duty_en15("false"), + .c_cnt_hi_div16(1), + .c_cnt_lo_div16(1), + .c_cnt_prst16(1), + .c_cnt_ph_mux_prst16(0), + .c_cnt_in_src16("ph_mux_clk"), + .c_cnt_bypass_en16("true"), + .c_cnt_odd_div_duty_en16("false"), + .c_cnt_hi_div17(1), + .c_cnt_lo_div17(1), + .c_cnt_prst17(1), + .c_cnt_ph_mux_prst17(0), + .c_cnt_in_src17("ph_mux_clk"), + .c_cnt_bypass_en17("true"), + .c_cnt_odd_div_duty_en17("false"), + .pll_vco_div(2), + .pll_cp_current(20), + .pll_bwctrl(4000), + .pll_output_clk_frequency("445.499999 MHz"), + .pll_fractional_division("3908420153"), + .mimic_fbclk_type("none"), + .pll_fbclk_mux_1("glb"), + .pll_fbclk_mux_2("m_cnt"), + .pll_m_cnt_in_src("ph_mux_clk"), + .pll_slf_rst("true") + ) altera_pll_i ( + .rst (rst), + .outclk ({outclk_0}), + .locked (locked), + .reconfig_to_pll (reconfig_to_pll), + .fboutclk ( ), + .fbclk (1'b0), + .refclk (refclk), + .reconfig_from_pll (reconfig_from_pll) + ); +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi_adj.vhd b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi_adj.vhd new file mode 100644 index 0000000000000000000000000000000000000000..67287cb3f521e7ab8f3945eb0be4978166146413 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/pll_hdmi_adj.vhd @@ -0,0 +1,433 @@ +-------------------------------------------------------------------------------- +-- HDMI PLL Adjust +-------------------------------------------------------------------------------- + +-- Changes the HDMI PLL frequency according to the scaler suggestions. +-------------------------------------------- +-- LLTUNE : +-- 0 : Input Display Enable +-- 1 : Input Vsync +-- 2 : Input Interlaced mode +-- 3 : Input Interlaced field +-- 4 : Output Image frame +-- 5 : +-- 6 : Input clock +-- 7 : Output clock + +LIBRARY ieee; +USE ieee.std_logic_1164.ALL; +USE ieee.numeric_std.ALL; + +ENTITY pll_hdmi_adj IS + PORT ( + -- Scaler + llena : IN std_logic; -- 0=Disabled 1=Enabled + lltune : IN unsigned(15 DOWNTO 0); -- Outputs from scaler + + locked : OUT std_logic; + + -- Signals from reconfig commands + i_waitrequest : OUT std_logic; + i_write : IN std_logic; + i_address : IN unsigned(5 DOWNTO 0); + i_writedata : IN unsigned(31 DOWNTO 0); + + -- Outputs to PLL_HDMI_CFG + o_waitrequest : IN std_logic; + o_write : OUT std_logic; + o_address : OUT unsigned(5 DOWNTO 0); + o_writedata : OUT unsigned(31 DOWNTO 0); + + ------------------------------------ + clk : IN std_logic; + reset_na : IN std_logic + ); + +BEGIN + + +END ENTITY pll_hdmi_adj; + +--############################################################################## + +ARCHITECTURE rtl OF pll_hdmi_adj IS + + SIGNAL i_clk,i_de,i_de2,i_vss,i_vss2,i_vss_delay,i_ce : std_logic; + SIGNAL i_linecpt,i_line : natural RANGE 0 TO 2**12-1; + SIGNAL i_delay : natural RANGE 0 TO 2**14-1; + + SIGNAL pwrite : std_logic; + SIGNAL paddress : unsigned(5 DOWNTO 0); + SIGNAL pdata : unsigned(31 DOWNTO 0); + TYPE enum_state IS (sIDLE,sW1,sW2,sW3,sW4,sW5,sW6); + SIGNAL state : enum_state; + SIGNAL tune_freq,tune_phase : unsigned(5 DOWNTO 0); + SIGNAL lltune_sync,lltune_sync2,lltune_sync3 : unsigned(15 DOWNTO 0); + SIGNAL mfrac,mfrac_mem,mfrac_ref,diff : unsigned(40 DOWNTO 0); + SIGNAL mul : unsigned(15 DOWNTO 0); + SIGNAL sign,sign_pre : std_logic; + SIGNAL expand : boolean; + SIGNAL up,modo,phm,dir : std_logic; + SIGNAL cpt : natural RANGE 0 TO 3; + SIGNAL col : natural RANGE 0 TO 15; + + SIGNAL icpt,ocpt,o2cpt,ssh,ofsize,ifsize : natural RANGE 0 TO 2**24-1; + SIGNAL ivss,ivss2,itog : std_logic; + SIGNAL ovss,ovss2,otog : std_logic; + SIGNAL sync,pulse,los,lop : std_logic; + SIGNAL osize,offset,osizep,offsetp : signed(23 DOWNTO 0); + SIGNAL logcpt : natural RANGE 0 TO 31; + SIGNAL udiff : integer RANGE -2**23 TO 2**23-1 :=0; + +BEGIN + + ---------------------------------------------------------------------------- + -- 4 lines delay to input + i_vss<=lltune(0); + i_de <=lltune(1); + i_ce <=lltune(5); + i_clk<=lltune(6); + + Delay:PROCESS(i_clk) IS + BEGIN + IF rising_edge(i_clk) THEN + IF i_ce='1' THEN + -- Measure input line time. + i_de2<=i_de; + + IF i_de='1' AND i_de2='0' THEN + i_linecpt<=0; + IF i_vss='1' THEN + i_line<=i_linecpt; + END IF; + ELSE + i_linecpt<=i_linecpt+1; + END IF; + + -- Delay 4 lines + i_vss2<=i_vss; + IF i_vss/=i_vss2 THEN + i_delay<=0; + ELSIF i_delay=i_line * 4 THEN + i_vss_delay<=i_vss; + ELSE + i_delay<=i_delay+1; + END IF; + END IF; + END IF; + END PROCESS Delay; + + ---------------------------------------------------------------------------- + -- Sample image sizes + Sampler:PROCESS(clk,reset_na) IS + BEGIN + IF reset_na='0' THEN +--pragma synthesis_off + otog<='0'; + itog<='0'; + ivss<='0'; + ivss2<='0'; + ovss<='0'; + ovss2<='0'; +--pragma synthesis_on + + ELSIF rising_edge(clk) THEN + -- Clock domain crossing + + ivss<=i_vss_delay; -- + ivss2<=ivss; + + ovss<=lltune(4); -- + ovss2<=ovss; + + otog<=otog XOR (ovss AND NOT ovss2); + + -- Measure output frame time + IF ovss='1' AND ovss2='0' AND otog='1' THEN + ocpt<=0; + osizep<=to_signed(ocpt,24); + ELSE + ocpt<=ocpt+1; + END IF; + IF ovss='0' AND ovss2='1' AND otog='0' THEN + o2cpt<=0; + ELSE + o2cpt<=o2cpt+1; + END IF; + + -- Measure output image time + IF ovss='0' AND ovss2='1' AND otog='0' THEN + ofsize<=ocpt; + END IF; + + itog<=itog XOR (ivss AND NOT ivss2); + + -- Measure input frame time + IF ivss='1' AND ivss2='0' AND itog='1' THEN + icpt<=0; + osize<=osizep; + udiff<=integer(to_integer(osizep)) - integer(icpt); + sync<='1'; + ELSE + icpt<=icpt+1; + sync<='0'; + END IF; + + -- Measure input image time + IF ivss='0' AND ivss2='1' AND itog='0' THEN + ifsize<=icpt; + END IF; + + expand<=(ofsize>=ifsize); + -- IN | ######### | EXPAND = 1 + -- OUT | ############# | + + -- IN | ######### | EXPAND = 0 + -- OUT | ###### | + + IF expand THEN + IF ivss='1' AND ivss2='0' AND itog='1' THEN + offset<=to_signed(ocpt,24); + END IF; + ELSE + IF ivss='0' AND ivss2='1' AND itog='0' THEN + offset<=to_signed(o2cpt,24); + END IF; + END IF; + + -------------------------------------------- + pulse<='0'; + IF sync='1' THEN + logcpt<=0; + ssh<=to_integer(osize); + los<='0'; + lop<='0'; + + ELSIF logcpt<24 THEN + -- Frequency difference + IF udiff>0 AND ssh=osize/2 AND ssh<(osize-offset) AND lop='0' THEN + tune_phase<='1' & to_unsigned(logcpt,5); + lop<='1'; + END IF; + ssh<=ssh/2; + logcpt<=logcpt+1; + + ELSIF logcpt=24 THEN + pulse<='1'; + ssh<=ssh/2; + logcpt<=logcpt+1; + END IF; + + END IF; + END PROCESS Sampler; + + ---------------------------------------------------------------------------- + -- 000010 : Start reg "Write either 0 or 1 to start fractional PLL reconf. + -- 000100 : M counter + -- 000111 : M counter Fractional Value K + + Comb:PROCESS(i_write,i_address, + i_writedata,pwrite,paddress,pdata) IS + BEGIN + IF i_write='1' THEN + o_write <=i_write; + o_address <=i_address; + o_writedata <=i_writedata; + ELSE + o_write <=pwrite; + o_address <=paddress; + o_writedata<=pdata; + END IF; + END PROCESS Comb; + + i_waitrequest<=o_waitrequest WHEN state=sIDLE ELSE '0'; + + ---------------------------------------------------------------------------- + Schmurtz:PROCESS(clk,reset_na) IS + VARIABLE off_v,ofp_v : natural RANGE 0 TO 63; + VARIABLE diff_v : unsigned(40 DOWNTO 0); + VARIABLE mulco : unsigned(15 DOWNTO 0); + VARIABLE up_v,sign_v : std_logic; + BEGIN + IF reset_na='0' THEN + modo<='0'; + state<=sIDLE; + ELSIF rising_edge(clk) THEN + ------------------------------------------------------ + -- Snoop accesses to PLL reconfiguration + IF i_address="000100" AND i_write='1' THEN + mfrac (40 DOWNTO 32)<=('0' & i_writedata(15 DOWNTO 8)) + + ('0' & i_writedata(7 DOWNTO 0)); + mfrac_ref(40 DOWNTO 32)<=('0' & i_writedata(15 DOWNTO 8)) + + ('0' & i_writedata(7 DOWNTO 0)); + mfrac_mem(40 DOWNTO 32)<=('0' & i_writedata(15 DOWNTO 8)) + + ('0' & i_writedata(7 DOWNTO 0)); + mul<=i_writedata(15 DOWNTO 0); + modo<='1'; + END IF; + + IF i_address="000111" AND i_write='1' THEN + mfrac (31 DOWNTO 0)<=i_writedata; + mfrac_ref(31 DOWNTO 0)<=i_writedata; + mfrac_mem(31 DOWNTO 0)<=i_writedata; + modo<='1'; + END IF; + + ------------------------------------------------------ + -- Tuning + off_v:=to_integer('0' & tune_freq(4 DOWNTO 0)); + ofp_v:=to_integer('0' & tune_phase(4 DOWNTO 0)); + --IF off_v<8 THEN off_v:=8; END IF; + --IF ofp_v<7 THEN ofp_v:=7; END IF; + IF off_v<4 THEN off_v:=4; END IF; + IF ofp_v<4 THEN ofp_v:=4; END IF; + + IF off_v>=18 AND ofp_v>=18 THEN + locked<=llena; + ELSE + locked<='0'; + END IF; + + up_v:='0'; + IF pulse='1' THEN + cpt<=(cpt+1) MOD 4; + IF llena='0' THEN + -- Recover original freq when disabling low lag mode + cpt<=0; + col<=0; + IF modo='1' THEN + mfrac<=mfrac_mem; + mfrac_ref<=mfrac_mem; + up<='1'; + modo<='0'; + END IF; + + ELSIF phm='0' AND cpt=0 THEN + -- Frequency adjust + sign_v:=tune_freq(5); + IF col<10 THEN col<=col+1; END IF; + IF off_v>=16 AND col>=10 THEN + phm<='1'; + col<=0; + ELSE + off_v:=off_v+1; + IF off_v>17 THEN + off_v:=off_v + 3; + END IF; + up_v:='1'; + up<='1'; + END IF; + + ELSIF cpt=0 THEN + -- Phase adjust + sign_v:=NOT tune_phase(5); + col<=col+1; + IF col>=10 THEN + phm<='0'; + up_v:='1'; + off_v:=31; + col<=0; + ELSE + off_v:=ofp_v + 1; + IF ofp_v>7 THEN + off_v:=off_v + 1; + END IF; + IF ofp_v>14 THEN + off_v:=off_v + 2; + END IF; + IF ofp_v>17 THEN + off_v:=off_v + 3; + END IF; + up_v:='1'; + END IF; + up<='1'; + END IF; + END IF; + + diff_v:=shift_right(mfrac_ref,off_v); + IF sign_v='0' THEN + diff_v:=mfrac_ref + diff_v; + ELSE + diff_v:=mfrac_ref - diff_v; + END IF; + + IF up_v='1' THEN + mfrac<=diff_v; + END IF; + + IF up_v='1' AND phm='0' THEN + mfrac_ref<=diff_v; + END IF; + + ------------------------------------------------------ + -- Update PLL registers + mulco:=mfrac(40 DOWNTO 33) & (mfrac(40 DOWNTO 33) + ('0' & mfrac(32))); + + CASE state IS + WHEN sIDLE => + pwrite<='0'; + IF up='1' THEN + up<='0'; + IF mulco/=mul THEN + state<=sW1; + ELSE + state<=sW3; + END IF; + END IF; + + WHEN sW1 => -- Change M multiplier + mul<=mulco; + pdata<=x"0000" & mulco; + paddress<="000100"; + pwrite<='1'; + state<=sW2; + + WHEN sW2 => + IF pwrite='1' AND o_waitrequest='0' THEN + state<=sW3; + pwrite<='0'; + END IF; + + WHEN sW3 => -- Change M fractional value + pdata<=mfrac(31 DOWNTO 0); + paddress<="000111"; + pwrite<='1'; + state<=sW4; + + WHEN sW4 => + IF pwrite='1' AND o_waitrequest='0' THEN + state<=sW5; + pwrite<='0'; + END IF; + + WHEN sW5 => + pdata<=x"0000_0001"; + paddress<="000010"; + pwrite<='1'; + state<=sW6; + + WHEN sW6 => + IF pwrite='1' AND o_waitrequest='0' THEN + pwrite<='0'; + state<=sIDLE; + END IF; + END CASE; + + END IF; + END PROCESS Schmurtz; + + ---------------------------------------------------------------------------- + +END ARCHITECTURE rtl; + diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/scandoubler.v b/MiSTer-devel_NeoGeo_MiSTer/sys/scandoubler.v new file mode 100644 index 0000000000000000000000000000000000000000..81e7c3f4e62d7214186ccffa48856494e6a7005d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/scandoubler.v @@ -0,0 +1,211 @@ +// +// scandoubler.v +// +// Copyright (c) 2015 Till Harbaum +// Copyright (c) 2017-2021 Alexey Melnikov +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// TODO: Delay vsync one line + +module scandoubler #(parameter LENGTH, parameter HALF_DEPTH) +( + // system interface + input clk_vid, + input hq2x, + + // shifter video interface + input ce_pix, + input hs_in, + input vs_in, + input hb_in, + input vb_in, + input [DWIDTH:0] r_in, + input [DWIDTH:0] g_in, + input [DWIDTH:0] b_in, + + // output interface + output ce_pix_out, + output reg hs_out, + output vs_out, + output hb_out, + output vb_out, + output [DWIDTH:0] r_out, + output [DWIDTH:0] g_out, + output [DWIDTH:0] b_out +); + +localparam DWIDTH = HALF_DEPTH ? 3 : 7; + +reg [7:0] pix_len = 0; +wire [7:0] pl = pix_len + 1'b1; + +reg [7:0] pix_in_cnt = 0; +wire [7:0] pc_in = pix_in_cnt + 1'b1; +reg [7:0] pixsz, pixsz2, pixsz4 = 0; + +reg ce_x4i, ce_x1i; +always @(posedge clk_vid) begin + reg old_ce, valid, hs; + + if(~&pix_len) pix_len <= pl; + if(~&pix_in_cnt) pix_in_cnt <= pc_in; + + ce_x4i <= 0; + ce_x1i <= 0; + + // use such odd comparison to place ce_x4 evenly if master clock isn't multiple of 4. + if((pc_in == pixsz4) || (pc_in == pixsz2) || (pc_in == (pixsz2+pixsz4))) ce_x4i <= 1; + + old_ce <= ce_pix; + if(~old_ce & ce_pix) begin + if(valid & ~hb_in & ~vb_in) begin + pixsz <= pl; + pixsz2 <= {1'b0, pl[7:1]}; + pixsz4 <= {2'b00, pl[7:2]}; + end + pix_len <= 0; + valid <= 1; + end + + hs <= hs_in; + if((~hs & hs_in) || (pc_in >= pixsz)) begin + ce_x4i <= 1; + ce_x1i <= 1; + pix_in_cnt <= 0; + end + + if(hb_in | vb_in) valid <= 0; +end + +reg req_line_reset; +reg [DWIDTH:0] r_d, g_d, b_d; +always @(posedge clk_vid) begin + if(ce_x1i) begin + req_line_reset <= hb_in; + r_d <= r_in; + g_d <= g_in; + b_d <= b_in; + end +end + +Hq2x #(.LENGTH(LENGTH), .HALF_DEPTH(HALF_DEPTH)) Hq2x +( + .clk(clk_vid), + + .ce_in(ce_x4i), + .inputpixel({b_d,g_d,r_d}), + .disable_hq2x(~hq2x), + .reset_frame(vb_in), + .reset_line(req_line_reset), + + .ce_out(ce_x4o), + .read_y(sd_line), + .hblank(hbo[0]&hbo[8]), + .outpixel({b_out,g_out,r_out}) +); + +reg [7:0] pix_out_cnt = 0; +wire [7:0] pc_out = pix_out_cnt + 1'b1; + +reg ce_x4o, ce_x2o; +always @(posedge clk_vid) begin + reg hs; + + if(~&pix_out_cnt) pix_out_cnt <= pc_out; + + ce_x4o <= 0; + ce_x2o <= 0; + + // use such odd comparison to place ce_x4 evenly if master clock isn't multiple of 4. + if((pc_out == pixsz4) || (pc_out == pixsz2) || (pc_out == (pixsz2+pixsz4))) ce_x4o <= 1; + if( pc_out == pixsz2) ce_x2o <= 1; + + hs <= hs_out; + if((~hs & hs_out) || (pc_out >= pixsz)) begin + ce_x2o <= 1; + ce_x4o <= 1; + pix_out_cnt <= 0; + end +end + +reg [1:0] sd_line; +reg [3:0] vbo; +reg [3:0] vso; +reg [8:0] hbo; +always @(posedge clk_vid) begin + + reg [31:0] hcnt; + reg [30:0] sd_hcnt; + reg [30:0] hs_start, hs_end; + reg [30:0] hde_start, hde_end; + + reg hs, hb; + + if(ce_x4o) begin + hbo[8:1] <= hbo[7:0]; + end + + // output counter synchronous to input and at twice the rate + sd_hcnt <= sd_hcnt + 1'd1; + if(sd_hcnt == hde_start) begin + sd_hcnt <= 0; + vbo[3:1] <= vbo[2:0]; + end + + if(sd_hcnt == hs_end) begin + sd_line <= sd_line + 1'd1; + if(&vbo[3:2]) sd_line <= 1; + vso[3:1] <= vso[2:0]; + end + + if(sd_hcnt == hde_start)hbo[0] <= 0; + if(sd_hcnt == hde_end) hbo[0] <= 1; + + // replicate horizontal sync at twice the speed + if(sd_hcnt == hs_end) hs_out <= 0; + if(sd_hcnt == hs_start) hs_out <= 1; + + hs <= hs_in; + hb <= hb_in; + + hcnt <= hcnt + 1'd1; + if(hb && !hb_in) begin + hde_start <= hcnt[31:1]; + hbo[0] <= 0; + hcnt <= 0; + sd_hcnt <= 0; + vbo <= {vbo[2:0],vb_in}; + end + + if(!hb && hb_in) hde_end <= hcnt[31:1]; + + // falling edge of hsync indicates start of line + if(hs && !hs_in) begin + hs_end <= hcnt[31:1]; + vso[0] <= vs_in; + end + + // save position of rising edge + if(!hs && hs_in) hs_start <= hcnt[31:1]; +end + +assign vs_out = vso[3]; +assign ce_pix_out = hq2x ? ce_x4o : ce_x2o; + +//Compensate picture shift after HQ2x +assign vb_out = vbo[3]; +assign hb_out = hbo[6]; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/scanlines.v b/MiSTer-devel_NeoGeo_MiSTer/sys/scanlines.v new file mode 100644 index 0000000000000000000000000000000000000000..43f890f148d3a642f403f611792efe8f253b022d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/scanlines.v @@ -0,0 +1,68 @@ +module scanlines #(parameter v2=0) +( + input clk, + + input [1:0] scanlines, + input [23:0] din, + input hs_in,vs_in, + input de_in,ce_in, + + output reg [23:0] dout, + output reg hs_out,vs_out, + output reg de_out,ce_out +); + +reg [1:0] scanline; +always @(posedge clk) begin + reg old_hs, old_vs; + + old_hs <= hs_in; + old_vs <= vs_in; + + if(old_hs && ~hs_in) begin + if(v2) begin + scanline <= scanline + 1'd1; + if (scanline == scanlines) scanline <= 0; + end + else scanline <= scanline ^ scanlines; + end + if(old_vs && ~vs_in) scanline <= 0; +end + +wire [7:0] r,g,b; +assign {r,g,b} = din; + +reg [23:0] d; +always @(*) begin + case(scanline) + 1: // reduce 25% = 1/2 + 1/4 + d = {{1'b0, r[7:1]} + {2'b00, r[7:2]}, + {1'b0, g[7:1]} + {2'b00, g[7:2]}, + {1'b0, b[7:1]} + {2'b00, b[7:2]}}; + + 2: // reduce 50% = 1/2 + d = {{1'b0, r[7:1]}, + {1'b0, g[7:1]}, + {1'b0, b[7:1]}}; + + 3: // reduce 75% = 1/4 + d = {{2'b00, r[7:2]}, + {2'b00, g[7:2]}, + {2'b00, b[7:2]}}; + + default: d = {r,g,b}; + endcase +end + +always @(posedge clk) begin + reg [23:0] dout1, dout2; + reg de1,de2,vs1,vs2,hs1,hs2,ce1,ce2; + + dout <= dout2; dout2 <= dout1; dout1 <= d; + vs_out <= vs2; vs2 <= vs1; vs1 <= vs_in; + hs_out <= hs2; hs2 <= hs1; hs1 <= hs_in; + de_out <= de2; de2 <= de1; de1 <= de_in; + ce_out <= ce2; ce2 <= ce1; ce1 <= ce_in; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sd_card.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/sd_card.sv new file mode 100644 index 0000000000000000000000000000000000000000..417d8d400d324452bae6e77c6852f2d1c6102c82 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sd_card.sv @@ -0,0 +1,463 @@ +// +// sd_card.v +// +// Copyright (c) 2014 Till Harbaum +// Copyright (c) 2015-2018 Sorgelig +// +// This source file is free software: you can redistribute it and/or modify +// it under the terms of the Lesser GNU General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This source file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// http://elm-chan.org/docs/mmc/mmc_e.html +// +///////////////////////////////////////////////////////////////////////// + +// +// Made module syncrhronous. Total code refactoring. (Sorgelig) +// clk_spi must be at least 2 x sck for proper work. + +module sd_card #(parameter WIDE = 0, OCTAL=0) +( + input clk_sys, + input reset, + + input sdhc, + input img_mounted, + input [63:0] img_size, + + output reg [31:0] sd_lba, + output reg sd_rd, + output reg sd_wr, + input sd_ack, + + input [AW:0] sd_buff_addr, + input [DW:0] sd_buff_dout, + output [DW:0] sd_buff_din, + input sd_buff_wr, + + // SPI interface + input clk_spi, + + input ss, + input sck, + input [SW:0] mosi, + output reg [SW:0] miso +); + +localparam AW = WIDE ? 7 : 8; +localparam DW = WIDE ? 15 : 7; +localparam SZ = OCTAL ? 8 : 1; +localparam SW = SZ-1; + +localparam DATA_TOKEN_CMD25 = 8'hfc; +localparam STOP_TRAN = 8'hfd; +localparam DATA_TOKEN = 8'hfe; +localparam WRITE_DATA_RESPONSE = 8'he5; + +// number of bytes to wait after a command before sending the reply +localparam NCR = 5+3; // 5 bytes are required (command length) + +localparam RD_STATE_IDLE = 0; +localparam RD_STATE_START = 1; +localparam RD_STATE_WAIT_IO = 2; +localparam RD_STATE_SEND_TOKEN = 3; +localparam RD_STATE_SEND_DATA = 4; +localparam RD_STATE_WAIT_M = 5; + +localparam WR_STATE_IDLE = 0; +localparam WR_STATE_EXP_DTOKEN = 1; +localparam WR_STATE_RECV_DATA = 2; +localparam WR_STATE_RECV_CRC0 = 3; +localparam WR_STATE_RECV_CRC1 = 4; +localparam WR_STATE_SEND_DRESP = 5; +localparam WR_STATE_BUSY = 6; + +localparam PREF_STATE_IDLE = 0; +localparam PREF_STATE_RD = 1; +localparam PREF_STATE_FINISH = 2; + +altsyncram sdbuf +( + .clock0 (clk_sys), + .address_a ({sd_buf,sd_buff_addr}), + .data_a (sd_buff_dout), + .wren_a (sd_ack & sd_buff_wr), + .q_a (sd_buff_din), + + .clock1 (clk_spi), + .address_b ({spi_buf,buffer_ptr}), + .data_b (buffer_din), + .wren_b (buffer_wr), + .q_b (buffer_dout), + + .aclr0(1'b0), + .aclr1(1'b0), + .addressstall_a(1'b0), + .addressstall_b(1'b0), + .byteena_a(1'b1), + .byteena_b(1'b1), + .clocken0(1'b1), + .clocken1(1'b1), + .clocken2(1'b1), + .clocken3(1'b1), + .eccstatus(), + .rden_a(1'b1), + .rden_b(1'b1) +); +defparam + sdbuf.numwords_a = 1<<(AW+3), + sdbuf.widthad_a = AW+3, + sdbuf.width_a = DW+1, + sdbuf.numwords_b = 2048, + sdbuf.widthad_b = 11, + sdbuf.width_b = 8, + sdbuf.address_reg_b = "CLOCK1", + sdbuf.clock_enable_input_a = "BYPASS", + sdbuf.clock_enable_input_b = "BYPASS", + sdbuf.clock_enable_output_a = "BYPASS", + sdbuf.clock_enable_output_b = "BYPASS", + sdbuf.indata_reg_b = "CLOCK1", + sdbuf.intended_device_family = "Cyclone V", + sdbuf.lpm_type = "altsyncram", + sdbuf.operation_mode = "BIDIR_DUAL_PORT", + sdbuf.outdata_aclr_a = "NONE", + sdbuf.outdata_aclr_b = "NONE", + sdbuf.outdata_reg_a = "UNREGISTERED", + sdbuf.outdata_reg_b = "UNREGISTERED", + sdbuf.power_up_uninitialized = "FALSE", + sdbuf.read_during_write_mode_port_a = "NEW_DATA_NO_NBE_READ", + sdbuf.read_during_write_mode_port_b = "NEW_DATA_NO_NBE_READ", + sdbuf.width_byteena_a = 1, + sdbuf.width_byteena_b = 1, + sdbuf.wrcontrol_wraddress_reg_b = "CLOCK1"; + +reg [26:0] csd_size; +reg csd_sdhc; +always @(posedge clk_sys) begin + if (img_mounted) begin + csd_sdhc <= sdhc; + if (sdhc) begin + csd_size[0] <= 0; + csd_size[22:1] <= img_size[40:19]; // in 512K units + csd_size[26:23] <= 0; + end + else begin + csd_size[2:0] <= 7; // C_SIZE_MULT + csd_size[14:3] <= 12'b101101101101; + csd_size[26:15] <= img_size[29:18]; // in 256K units ((2**(C_SIZE_MULT+2))*512) + end + end +end + +wire [127:0] CSD = {1'b0,csd_sdhc,6'h00,8'h0e,8'h00,8'h32,8'h5b,8'h59,6'h00,csd_size,7'h7f,8'h80,8'h0a,8'h40,8'h40,8'hf1}; +wire [127:0] CID = {8'hcd,8'hc7,8'h00,8'h93,8'h6f,8'h2f,8'h73,8'h00,8'h00,8'h44,8'h32,8'h38,8'h34,8'h00,8'h00,8'h3e}; + +reg [8:0] buffer_ptr; +reg [7:0] buffer_din; +wire [7:0] buffer_dout; +reg buffer_wr; + +reg [1:0] sd_buf, spi_buf; + +reg [6:0] sbuf; +reg [2:0] bit_cnt; + +wire last_bit = &bit_cnt || OCTAL; +wire [7:0] ibuf = OCTAL ? mosi : {sbuf,mosi[0]}; + +always @(posedge clk_spi) begin + reg [2:0] read_state; + reg [2:0] write_state; + reg [1:0] pref_state; + reg [5:0] cmd; + reg cmd55; + reg [39:0] reply; + reg [3:0] byte_cnt; + reg old_sck; + reg [2:0] ack; + reg [2:0] wait_m_cnt; + reg [31:0] arg; + + ack[1:0] <= {ack[0],sd_ack}; + if(ack[1] == ack[0]) ack[2] <= ack[1]; + + if(~ack[2] & ack[1]) {sd_rd,sd_wr} <= 0; + if( ack[2] & ~ack[1]) begin + sd_buf <= sd_buf + 1'd1; + sd_lba <= sd_lba + 1; + end + + buffer_wr <= 0; + + if(reset) begin + bit_cnt <= 0; + byte_cnt <= '1; + miso <= '1; + cmd <= 0; + sd_wr <= 0; + sd_rd <= 0; + read_state <= RD_STATE_IDLE; + write_state <= WR_STATE_IDLE; + pref_state <= PREF_STATE_IDLE; + end + else begin + + if(buffer_wr) begin + if(~&buffer_ptr) buffer_ptr <= buffer_ptr + 1'd1; + else begin + spi_buf <= spi_buf + 1'd1; + sd_wr <= 1; + end + end + + case(pref_state) + PREF_STATE_IDLE: + if(((sd_buf - spi_buf) <= 1) && (read_state != RD_STATE_IDLE) && (cmd == 17 || cmd == 18)) begin + sd_rd <= 1; + pref_state <= PREF_STATE_RD; + end + + PREF_STATE_RD: + if(read_state == RD_STATE_IDLE) begin + pref_state <= PREF_STATE_IDLE; + end + else if(ack[2] & ~ack[1]) begin + pref_state <= (cmd == 18) ? PREF_STATE_IDLE : PREF_STATE_FINISH; + end + + PREF_STATE_FINISH: + if(read_state == RD_STATE_IDLE) begin + pref_state <= PREF_STATE_IDLE; + end + endcase + + old_sck <= sck; + if(ss) begin + bit_cnt <= 0; + byte_cnt <= '1; + miso <= '1; + end + else if(old_sck & ~sck) begin + miso <= '1; // default: send 1's (busy/wait) + if(byte_cnt >= NCR) {miso,reply} <= {reply, {SZ{1'b1}}}; + + // ---------- read state machine processing ------------- + case(read_state) + RD_STATE_IDLE: ; + + RD_STATE_START: begin + if(byte_cnt == NCR && last_bit) read_state <= (cmd == 9 || cmd == 10) ? RD_STATE_SEND_TOKEN : RD_STATE_WAIT_IO; + end + + // waiting for io controller to return data + RD_STATE_WAIT_IO: begin + if(sd_buf != spi_buf && last_bit) read_state <= RD_STATE_SEND_TOKEN; + end + + // send data token + RD_STATE_SEND_TOKEN: begin + miso <= DATA_TOKEN[~bit_cnt -:SZ]; + if(last_bit) begin + read_state <= RD_STATE_SEND_DATA; // next: send data + buffer_ptr <= 0; + end + end + + // send data + RD_STATE_SEND_DATA: begin + + miso <= (cmd == 9) ? CSD[{buffer_ptr[3:0],~bit_cnt} -:SZ] : (cmd == 10) ? CID[{buffer_ptr[3:0],~bit_cnt} -:SZ] : buffer_dout[~bit_cnt -:SZ]; + + if(last_bit) begin + + // sent 512 sector data bytes? + if(cmd == 17 && &buffer_ptr) read_state <= RD_STATE_IDLE; + else if(cmd == 18 && &buffer_ptr) begin + read_state <= RD_STATE_WAIT_M; + wait_m_cnt <= 0; + end + + // sent 16 cid/csd data bytes? + else if((cmd == 9 || cmd == 10) && &buffer_ptr[3:0]) read_state <= RD_STATE_IDLE; + + // not done yet -> trigger read of next data byte + else buffer_ptr <= buffer_ptr + 1'd1; + end + end + + RD_STATE_WAIT_M: begin + if(last_bit) begin + wait_m_cnt <= wait_m_cnt + 1'd1; + if(&wait_m_cnt) begin + spi_buf <= spi_buf + 1'd1; + read_state <= RD_STATE_WAIT_IO; + end + end + end + endcase + + // ------------------ write support ---------------------- + // send write data response + if(write_state == WR_STATE_SEND_DRESP) miso <= WRITE_DATA_RESPONSE[~bit_cnt -:SZ]; + + // busy after write until the io controller sends ack + if(write_state == WR_STATE_BUSY) miso <= 0; + end + else if(~old_sck & sck) begin + + sbuf[6:0] <= {sbuf[5:0],mosi[0]}; + bit_cnt <= bit_cnt + SZ[2:0]; + + if(last_bit) begin + // finished reading one byte + // byte counter runs against 15 byte boundary + if(~&byte_cnt) byte_cnt <= byte_cnt + 1'd1; + + // byte_cnt > 6 -> complete command received + // first byte of valid command is 01xxxxxx + // don't accept new commands once a write or read command has been accepted + if(byte_cnt > 5 && + ((write_state == WR_STATE_IDLE && read_state == RD_STATE_IDLE && ibuf[7:6] == 1) || + (read_state != RD_STATE_IDLE && ibuf == 8'h4c))) begin + byte_cnt <= 0; + cmd <= ibuf[5:0]; + cmd55 <= (cmd == 55); // set cmd55 flag if previous command was 55 + if(ibuf[5:0] == 12) read_state <= RD_STATE_IDLE; + end + + // parse additional command bytes + if(byte_cnt == 0) arg[31:24] <= ibuf; + if(byte_cnt == 1) arg[23:16] <= ibuf; + if(byte_cnt == 2) arg[15:8] <= ibuf; + if(byte_cnt == 3) arg[7:0] <= ibuf; + + // last byte (crc) received, evaluate + if(byte_cnt == 4) begin + + // default: + reply <= 40'h04FFFFFFFF; // illegal command + + case(cmd) + // CMD0: GO_IDLE_STATE + 0: reply[39:32] <= 1; // ok, busy + + // CMD1: SEND_OP_COND + 1: reply[39:32] <= 0; + + // CMD8: SEND_IF_COND (V2 only) + 8: reply <= 40'h01000001AA; // ok, busy + + // CMD9: SEND_CSD + 9, + // CMD10: SEND_CID + 10: begin + reply[39:32] <= 0; + read_state <= RD_STATE_START; + end + + // CMD12: STOP_TRANSMISSION + 12: reply[39:32] <= 0; + + // CMD13: SEND_STATUS + 13: reply[39:24] <= 16'h0000; + + // CMD16: SET_BLOCKLEN + 16: reply[39:32] <= (arg == 512) ? 8'h00 : 8'h40; // we only support a block size of 512 + + // CMD17: READ_SINGLE_BLOCK + 17, + // CMD18: READ_MULTIPLE + 18: begin + reply[39:32] <= 0; + read_state <= RD_STATE_START; + spi_buf <= 0; + sd_buf <= 0; + sd_lba <= csd_sdhc ? arg : {9'd0, arg[31:9]}; + end + + // ACMD23: SET_WR_BLK_ERASE_COUNT + 23: reply[39:32] <= 0; + + // CMD24: WRITE_BLOCK + 24, + // CMD25: WRITE_MULTIPLE + 25: begin + reply[39:32] <= 0; + write_state <= WR_STATE_EXP_DTOKEN; // expect data token + spi_buf <= 0; + sd_buf <= 0; + sd_lba <= csd_sdhc ? arg : {9'd0, arg[31:9]}; + end + + // ACMD41: APP_SEND_OP_COND + 41: if(cmd55) reply[39:32] <= 0; // ok, not busy + + // CMD55: APP_COND + 55: reply[39:32] <= 1; // ok, busy + + // CMD58: READ_OCR + 58: reply <= { 8'h00, 1'b1, csd_sdhc, 30'd0 }; // bit 30 = 1 -> high capacity card + + // CMD59: CRC_ON_OFF + 59: reply[39:32] <= 0; + endcase + end + + // ---------- handle write ----------- + case(write_state) + // do nothing in idle state + WR_STATE_IDLE: ; + + // waiting for data token + WR_STATE_EXP_DTOKEN: begin + buffer_ptr <= 0; + if(cmd == 24) begin + if(ibuf == DATA_TOKEN) write_state <= WR_STATE_RECV_DATA; + end + else begin + if(ibuf == DATA_TOKEN_CMD25) write_state <= WR_STATE_RECV_DATA; + if(ibuf == STOP_TRAN) write_state <= WR_STATE_IDLE; + end + end + + // transfer 512 bytes + WR_STATE_RECV_DATA: begin + // push one byte into local buffer + buffer_wr <= 1; + buffer_din <= ibuf; + + // all bytes written? + if(&buffer_ptr) write_state <= WR_STATE_RECV_CRC0; + end + + // transfer 1st crc byte + WR_STATE_RECV_CRC0: + write_state <= WR_STATE_RECV_CRC1; + + // transfer 2nd crc byte + WR_STATE_RECV_CRC1: + write_state <= WR_STATE_SEND_DRESP; + + // send data response + WR_STATE_SEND_DRESP: + write_state <= WR_STATE_BUSY; + + // wait for io controller to accept data + WR_STATE_BUSY: + if(spi_buf == sd_buf) write_state <= (cmd == 25) ? WR_STATE_EXP_DTOKEN : WR_STATE_IDLE; + endcase + end + end + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/shadowmask.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/shadowmask.sv new file mode 100644 index 0000000000000000000000000000000000000000..572679c2fcc4bd8193c760751f82fa9b872f2b9b --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/shadowmask.sv @@ -0,0 +1,136 @@ +module shadowmask +( + input clk, + input clk_sys, + + input cmd_wr, + input [15:0] cmd_in, + + input [23:0] din, + input hs_in,vs_in, + input de_in, + input brd_in, + input enable, + + output reg [23:0] dout, + output reg hs_out,vs_out, + output reg de_out +); + + +reg [4:0] hmax; +reg [4:0] vmax; +reg [7:0] mask_idx; +reg mask_2x; +reg mask_rotate; +reg mask_enable; +reg [10:0] mask_lut[256]; + +always @(posedge clk) begin + reg [4:0] hcount; + reg [4:0] vcount; + reg [3:0] hindex; + reg [3:0] vindex; + reg [4:0] hmax2; + reg [4:0] vmax2; + reg [11:0] pcnt,pde; + reg old_hs, old_vs, old_brd; + reg next_v; + + old_hs <= hs_in; + old_vs <= vs_in; + old_brd<= brd_in; + + // hcount and vcount counts pixel rows and columns + // hindex and vindex half the value of the counters for double size patterns + // hindex2, vindex2 swap the h and v counters for drawing rotated masks + hindex <= mask_2x ? hcount[4:1] : hcount[3:0]; + vindex <= mask_2x ? vcount[4:1] : vcount[3:0]; + mask_idx <= mask_rotate ? {hindex,vindex} : {vindex,hindex}; + + // hmax and vmax store these sizes + // hmax2 and vmax2 swap the values to handle rotation + hmax2 <= ((mask_rotate ? vmax : hmax) << mask_2x) | mask_2x; + vmax2 <= ((mask_rotate ? hmax : vmax) << mask_2x) | mask_2x; + + pcnt <= pcnt+1'd1; + if(old_brd && ~brd_in) pde <= pcnt-4'd3; + + hcount <= hcount+1'b1; + if(hcount == hmax2 || pde == pcnt) hcount <= 0; + + if(~old_brd && brd_in) next_v <= 1; + if(old_vs && ~vs_in) vcount <= 0; + if(old_hs && ~hs_in) begin + vcount <= vcount + next_v; + next_v <= 0; + pcnt <= 0; + if (vcount == vmax2) vcount <= 0; + end +end + +reg [4:0] r_mul, g_mul, b_mul; // 1.4 fixed point multipliers +always @(posedge clk) begin + reg [10:0] lut; + + lut <= mask_lut[mask_idx]; + + r_mul <= 5'b10000; g_mul <= 5'b10000; b_mul <= 5'b10000; // default 100% to all channels + if (mask_enable) begin + r_mul <= lut[10] ? {1'b1,lut[7:4]} : {1'b0,lut[3:0]}; + g_mul <= lut[9] ? {1'b1,lut[7:4]} : {1'b0,lut[3:0]}; + b_mul <= lut[8] ? {1'b1,lut[7:4]} : {1'b0,lut[3:0]}; + end +end + +always @(posedge clk) begin + reg [11:0] vid; + reg [7:0] r1, g1, b1; + reg [7:0] r2, g2, b2; + reg [7:0] r3_x, g3_x, b3_x; // 6.25% + 12.5% + reg [8:0] r3_y, g3_y, b3_y; // 25% + 50% + 100% + reg [8:0] r4, g4, b4; + + // C1 - data input + {r1,g1,b1} <= din; + vid <= {vid[8:0],vs_in, hs_in, de_in}; + + // C2 - relax timings + {r2,g2,b2} <= {r1,g1,b1}; + + // C3 - perform multiplications + r3_x <= ({4{r_mul[0]}} & r2[7:4]) + ({8{r_mul[1]}} & r2[7:3]); + r3_y <= ({6{r_mul[2]}} & r2[7:2]) + ({7{r_mul[3]}} & r2[7:1]) + ({9{r_mul[4]}} & r2[7:0]); + g3_x <= ({4{g_mul[0]}} & g2[7:4]) + ({8{g_mul[1]}} & g2[7:3]); + g3_y <= ({6{g_mul[2]}} & g2[7:2]) + ({7{g_mul[3]}} & g2[7:1]) + ({9{g_mul[4]}} & g2[7:0]); + b3_x <= ({4{b_mul[0]}} & b2[7:4]) + ({8{b_mul[1]}} & b2[7:3]); + b3_y <= ({6{b_mul[2]}} & b2[7:2]) + ({7{b_mul[3]}} & b2[7:1]) + ({9{b_mul[4]}} & b2[7:0]); + + // C4 - combine results + r4 <= r3_x + r3_y; + g4 <= g3_x + g3_y; + b4 <= b3_x + b3_y; + + // C5 - clamp and output + dout <= {{8{r4[8]}} | r4[7:0], {8{g4[8]}} | g4[7:0], {8{b4[8]}} | b4[7:0]}; + {vs_out,hs_out,de_out} <= vid[11:9]; +end + +// clock in mask commands +always @(posedge clk_sys) begin + reg m_enable; + reg [7:0] idx; + + if (cmd_wr) begin + case(cmd_in[15:13]) + 3'b000: begin {m_enable, mask_rotate, mask_2x} <= cmd_in[3:1]; idx <= 0; end + 3'b001: vmax <= cmd_in[3:0]; + 3'b010: hmax <= cmd_in[3:0]; + 3'b011: begin mask_lut[idx] <= cmd_in[10:0]; idx <= idx + 1'd1; end + endcase + end + + mask_enable <= m_enable & enable; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sigma_delta_dac.v b/MiSTer-devel_NeoGeo_MiSTer/sys/sigma_delta_dac.v new file mode 100644 index 0000000000000000000000000000000000000000..d0d6be0877b42623605939845c343f9a4ee97fa9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sigma_delta_dac.v @@ -0,0 +1,33 @@ +// +// PWM DAC +// +// MSBI is the highest bit number. NOT amount of bits! +// +module sigma_delta_dac #(parameter MSBI=7, parameter INV=1'b1) +( + output reg DACout, //Average Output feeding analog lowpass + input [MSBI:0] DACin, //DAC input (excess 2**MSBI) + input CLK, + input RESET +); + +reg [MSBI+2:0] DeltaAdder; //Output of Delta Adder +reg [MSBI+2:0] SigmaAdder; //Output of Sigma Adder +reg [MSBI+2:0] SigmaLatch; //Latches output of Sigma Adder +reg [MSBI+2:0] DeltaB; //B input of Delta Adder + +always @(*) DeltaB = {SigmaLatch[MSBI+2], SigmaLatch[MSBI+2]} << (MSBI+1); +always @(*) DeltaAdder = DACin + DeltaB; +always @(*) SigmaAdder = DeltaAdder + SigmaLatch; + +always @(posedge CLK or posedge RESET) begin + if(RESET) begin + SigmaLatch <= 1'b1 << (MSBI+1); + DACout <= INV; + end else begin + SigmaLatch <= SigmaAdder; + DACout <= SigmaLatch[MSBI+2] ^ INV; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/spdif.v b/MiSTer-devel_NeoGeo_MiSTer/sys/spdif.v new file mode 100644 index 0000000000000000000000000000000000000000..eee2b0817641c83bd46c5919150be54f98a4dd8c --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/spdif.v @@ -0,0 +1,320 @@ +//----------------------------------------------------------------- +// SPDIF Transmitter +// V0.1 +// Ultra-Embedded.com +// Copyright 2012 +// +// Email: admin@ultra-embedded.com +// +// License: GPL +// If you would like a version with a more permissive license for +// use in closed source commercial applications please contact me +// for details. +//----------------------------------------------------------------- +// +// This file is open source HDL; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of +// the License, or (at your option) any later version. +// +// This file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this file; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +// USA +//----------------------------------------------------------------- +// altera message_off 10762 +// altera message_off 10240 + +module spdif +( + input clk_i, + input rst_i, + + // SPDIF bit output enable + // Single cycle pulse synchronous to clk_i which drives + // the output bit rate. + // For 44.1KHz, 44100×32×2×2 = 5,644,800Hz + // For 48KHz, 48000×32×2×2 = 6,144,000Hz + input bit_out_en_i, + + // Output + output spdif_o, + + // Audio interface (16-bit x 2 = RL) + input [31:0] sample_i, + output reg sample_req_o +); + +//----------------------------------------------------------------- +// Registers +//----------------------------------------------------------------- +reg [15:0] audio_sample_q; +reg [8:0] subframe_count_q; + +reg load_subframe_q; +reg [7:0] preamble_q; +wire [31:0] subframe_w; + +reg [5:0] bit_count_q; +reg bit_toggle_q; + +reg spdif_out_q; + +reg [5:0] parity_count_q; + +reg channel_status_bit_q; + +//----------------------------------------------------------------- +// Subframe Counter +//----------------------------------------------------------------- +always @ (posedge rst_i or posedge clk_i ) +begin + if (rst_i == 1'b1) + subframe_count_q <= 9'd0; + else if (load_subframe_q) + begin + // 192 frames (384 subframes) in an audio block + if (subframe_count_q == 9'd383) + subframe_count_q <= 9'd0; + else + subframe_count_q <= subframe_count_q + 9'd1; + end +end + +//----------------------------------------------------------------- +// Sample capture +//----------------------------------------------------------------- +reg [15:0] sample_buf_q; + +always @ (posedge rst_i or posedge clk_i ) +begin + if (rst_i == 1'b1) + begin + audio_sample_q <= 16'h0000; + sample_buf_q <= 16'h0000; + sample_req_o <= 1'b0; + end + else if (load_subframe_q) + begin + // Start of frame (first subframe)? + if (subframe_count_q[0] == 1'b0) + begin + // Use left sample + audio_sample_q <= sample_i[15:0]; + + // Store right sample + sample_buf_q <= sample_i[31:16]; + + // Request next sample + sample_req_o <= 1'b1; + end + else + begin + // Use right sample + audio_sample_q <= sample_buf_q; + + sample_req_o <= 1'b0; + end + end + else + sample_req_o <= 1'b0; +end + +// Timeslots 3 - 0 = Preamble +assign subframe_w[3:0] = 4'b0000; + +// Timeslots 7 - 4 = 24-bit audio LSB +assign subframe_w[7:4] = 4'b0000; + +// Timeslots 11 - 8 = 20-bit audio LSB +assign subframe_w[11:8] = 4'b0000; + +// Timeslots 27 - 12 = 16-bit audio +assign subframe_w[27:12] = audio_sample_q; + +// Timeslots 28 = Validity +assign subframe_w[28] = 1'b0; // Valid + +// Timeslots 29 = User bit +assign subframe_w[29] = 1'b0; + +// Timeslots 30 = Channel status bit +assign subframe_w[30] = channel_status_bit_q ; //was constant 1'b0 enabling copy-bit; + +// Timeslots 31 = Even Parity bit (31:4) +assign subframe_w[31] = 1'b0; + +//----------------------------------------------------------------- +// Preamble and Channel status bit +//----------------------------------------------------------------- +localparam PREAMBLE_Z = 8'b00010111; // "B" channel A data at start of block +localparam PREAMBLE_Y = 8'b00100111; // "W" channel B data +localparam PREAMBLE_X = 8'b01000111; // "M" channel A data not at start of block + +reg [7:0] preamble_r; +reg channel_status_bit_r; + +always @ * +begin + // Start of audio block? + // Z(B) - Left channel + if (subframe_count_q == 9'd0) + preamble_r = PREAMBLE_Z; // Z(B) + // Right Channel? + else if (subframe_count_q[0] == 1'b1) + preamble_r = PREAMBLE_Y; // Y(W) + // Left Channel (but not start of block)? + else + preamble_r = PREAMBLE_X; // X(M) + + if (subframe_count_q[8:1] == 8'd2) // frame 2 => subframes 4 and 5 => 0 = copy inhibited, 1 = copy permitted + channel_status_bit_r = 1'b1; + else if (subframe_count_q[8:1] == 8'd15) // frame 15 => 0 = no indication, 1 = original media + channel_status_bit_r = 1'b1; + else if (subframe_count_q[8:1] == 8'd25) // frame 24 to 27 => sample frequency, 0100 = 48kHz, 0000 = 44kHz (l2r) + channel_status_bit_r = 1'b1; + else + channel_status_bit_r = 1'b0; // everything else defaults to 0 +end + +always @ (posedge rst_i or posedge clk_i ) +begin + if (rst_i == 1'b1) + begin + preamble_q <= 8'h00; + channel_status_bit_q <= 1'b0; + end + else if (load_subframe_q) + begin + preamble_q <= preamble_r; + channel_status_bit_q <= channel_status_bit_r; + end +end + +//----------------------------------------------------------------- +// Parity Counter +//----------------------------------------------------------------- +always @ (posedge rst_i or posedge clk_i ) +begin + if (rst_i == 1'b1) + begin + parity_count_q <= 6'd0; + end + // Time to output a bit? + else if (bit_out_en_i) + begin + // Preamble bits? + if (bit_count_q < 6'd8) + begin + parity_count_q <= 6'd0; + end + // Normal timeslots + else if (bit_count_q < 6'd62) + begin + // On first pass through this timeslot, count number of high bits + if (bit_count_q[0] == 0 && subframe_w[bit_count_q / 2] == 1'b1) + parity_count_q <= parity_count_q + 6'd1; + end + end +end + +//----------------------------------------------------------------- +// Bit Counter +//----------------------------------------------------------------- +always @ (posedge rst_i or posedge clk_i) +begin + if (rst_i == 1'b1) + begin + bit_count_q <= 6'b0; + load_subframe_q <= 1'b1; + end + // Time to output a bit? + else if (bit_out_en_i) + begin + // 32 timeslots (x2 for double frequency) + if (bit_count_q == 6'd63) + begin + bit_count_q <= 6'd0; + load_subframe_q <= 1'b1; + end + else + begin + bit_count_q <= bit_count_q + 6'd1; + load_subframe_q <= 1'b0; + end + end + else + load_subframe_q <= 1'b0; +end + +//----------------------------------------------------------------- +// Bit half toggle +//----------------------------------------------------------------- +always @ (posedge rst_i or posedge clk_i) +if (rst_i == 1'b1) + bit_toggle_q <= 1'b0; +// Time to output a bit? +else if (bit_out_en_i) + bit_toggle_q <= ~bit_toggle_q; + +//----------------------------------------------------------------- +// Output bit (BMC encoded) +//----------------------------------------------------------------- +reg bit_r; + +always @ * +begin + bit_r = spdif_out_q; + + // Time to output a bit? + if (bit_out_en_i) + begin + // Preamble bits? + if (bit_count_q < 6'd8) + begin + bit_r = preamble_q[bit_count_q[2:0]]; + end + // Normal timeslots + else if (bit_count_q < 6'd62) + begin + if (subframe_w[bit_count_q / 2] == 1'b0) + begin + if (bit_toggle_q == 1'b0) + bit_r = ~spdif_out_q; + else + bit_r = spdif_out_q; + end + else + bit_r = ~spdif_out_q; + end + // Parity timeslot + else + begin + // Even number of high bits, make odd + if (parity_count_q[0] == 1'b0) + begin + if (bit_toggle_q == 1'b0) + bit_r = ~spdif_out_q; + else + bit_r = spdif_out_q; + end + else + bit_r = ~spdif_out_q; + end + end +end + +always @ (posedge rst_i or posedge clk_i ) +if (rst_i == 1'b1) + spdif_out_q <= 1'b0; +else + spdif_out_q <= bit_r; + +assign spdif_o = spdif_out_q; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sys.tcl b/MiSTer-devel_NeoGeo_MiSTer/sys/sys.tcl new file mode 100644 index 0000000000000000000000000000000000000000..9f3de3e5a74b246f5a72136e4dcc15108d1eb541 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sys.tcl @@ -0,0 +1,220 @@ +set_global_assignment -name FAMILY "Cyclone V" +set_global_assignment -name DEVICE 5CSEBA6U23I7 +set_global_assignment -name DEVICE_FILTER_PACKAGE UFBGA +set_global_assignment -name DEVICE_FILTER_PIN_COUNT 672 +set_global_assignment -name DEVICE_FILTER_SPEED_GRADE 7 + +#============================================================ +# ADC +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to ADC_CONVST +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to ADC_SCK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to ADC_SDI +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to ADC_SDO +set_location_assignment PIN_U9 -to ADC_CONVST +set_location_assignment PIN_V10 -to ADC_SCK +set_location_assignment PIN_AC4 -to ADC_SDI +set_location_assignment PIN_AD4 -to ADC_SDO + +#============================================================ +# I2C LEDS/BUTTONS +#============================================================ +set_location_assignment PIN_U14 -to IO_SCL +set_location_assignment PIN_AG9 -to IO_SDA +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to IO_S* +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to IO_S* +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to IO_S* + +#============================================================ +# USER PORT +#============================================================ +set_location_assignment PIN_AF17 -to USER_IO[6] +set_location_assignment PIN_AF15 -to USER_IO[5] +set_location_assignment PIN_AG16 -to USER_IO[4] +set_location_assignment PIN_AH11 -to USER_IO[3] +set_location_assignment PIN_AH12 -to USER_IO[2] +set_location_assignment PIN_AH9 -to USER_IO[1] +set_location_assignment PIN_AG11 -to USER_IO[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to USER_IO[*] +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to USER_IO[*] +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to USER_IO[*] + +#============================================================ +# SDIO_CD or SPDIF_OUT +#============================================================ +set_location_assignment PIN_AH7 -to SDCD_SPDIF +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to SDCD_SPDIF +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SDCD_SPDIF +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to SDCD_SPDIF + +#============================================================ +# SDRAM +#============================================================ +set_location_assignment PIN_Y11 -to SDRAM_A[0] +set_location_assignment PIN_AA26 -to SDRAM_A[1] +set_location_assignment PIN_AA13 -to SDRAM_A[2] +set_location_assignment PIN_AA11 -to SDRAM_A[3] +set_location_assignment PIN_W11 -to SDRAM_A[4] +set_location_assignment PIN_Y19 -to SDRAM_A[5] +set_location_assignment PIN_AB23 -to SDRAM_A[6] +set_location_assignment PIN_AC23 -to SDRAM_A[7] +set_location_assignment PIN_AC22 -to SDRAM_A[8] +set_location_assignment PIN_C12 -to SDRAM_A[9] +set_location_assignment PIN_AB26 -to SDRAM_A[10] +set_location_assignment PIN_AD17 -to SDRAM_A[11] +set_location_assignment PIN_D12 -to SDRAM_A[12] +set_location_assignment PIN_Y17 -to SDRAM_BA[0] +set_location_assignment PIN_AB25 -to SDRAM_BA[1] +set_location_assignment PIN_V12 -to SDRAM_DQ[0] +set_location_assignment PIN_E8 -to SDRAM_DQ[1] +set_location_assignment PIN_D11 -to SDRAM_DQ[2] +set_location_assignment PIN_W12 -to SDRAM_DQ[3] +set_location_assignment PIN_AH13 -to SDRAM_DQ[4] +set_location_assignment PIN_D8 -to SDRAM_DQ[5] +set_location_assignment PIN_AH14 -to SDRAM_DQ[6] +set_location_assignment PIN_AF7 -to SDRAM_DQ[7] +set_location_assignment PIN_AE24 -to SDRAM_DQ[8] +set_location_assignment PIN_AD23 -to SDRAM_DQ[9] +set_location_assignment PIN_AE6 -to SDRAM_DQ[10] +set_location_assignment PIN_AE23 -to SDRAM_DQ[11] +set_location_assignment PIN_AG14 -to SDRAM_DQ[12] +set_location_assignment PIN_AD5 -to SDRAM_DQ[13] +set_location_assignment PIN_AF4 -to SDRAM_DQ[14] +set_location_assignment PIN_AH3 -to SDRAM_DQ[15] +set_location_assignment PIN_AG13 -to SDRAM_DQML +set_location_assignment PIN_AF13 -to SDRAM_DQMH +set_location_assignment PIN_AD20 -to SDRAM_CLK +set_location_assignment PIN_AG10 -to SDRAM_CKE +set_location_assignment PIN_AA19 -to SDRAM_nWE +set_location_assignment PIN_AA18 -to SDRAM_nCAS +set_location_assignment PIN_Y18 -to SDRAM_nCS +set_location_assignment PIN_W14 -to SDRAM_nRAS + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SDRAM_* +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to SDRAM_* +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to SDRAM_* +set_instance_assignment -name FAST_OUTPUT_ENABLE_REGISTER ON -to SDRAM_DQ[*] +set_instance_assignment -name FAST_INPUT_REGISTER ON -to SDRAM_DQ[*] +set_instance_assignment -name ALLOW_SYNCH_CTRL_USAGE OFF -to *|SDRAM_* + +#============================================================ +# SPI SD +#============================================================ +set_location_assignment PIN_AE15 -to SD_SPI_CS +set_location_assignment PIN_AH8 -to SD_SPI_MISO +set_location_assignment PIN_AG8 -to SD_SPI_CLK +set_location_assignment PIN_U13 -to SD_SPI_MOSI +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to SD_SPI* +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_SPI* +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to SD_SPI* + + +#============================================================ +# CLOCK +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FPGA_CLK1_50 +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FPGA_CLK2_50 +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FPGA_CLK3_50 +set_location_assignment PIN_V11 -to FPGA_CLK1_50 +set_location_assignment PIN_Y13 -to FPGA_CLK2_50 +set_location_assignment PIN_E11 -to FPGA_CLK3_50 + +#============================================================ +# HDMI +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_I2C_* +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_I2S +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_LRCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_MCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_SCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to HDMI_TX_* +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to HDMI_TX_D[*] +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to HDMI_TX_DE +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to HDMI_TX_HS +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to HDMI_TX_VS +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to HDMI_TX_CLK +set_location_assignment PIN_U10 -to HDMI_I2C_SCL +set_location_assignment PIN_AA4 -to HDMI_I2C_SDA +set_location_assignment PIN_T13 -to HDMI_I2S +set_location_assignment PIN_T11 -to HDMI_LRCLK +set_location_assignment PIN_U11 -to HDMI_MCLK +set_location_assignment PIN_T12 -to HDMI_SCLK +set_location_assignment PIN_AG5 -to HDMI_TX_CLK +set_location_assignment PIN_AD19 -to HDMI_TX_DE +set_location_assignment PIN_AD12 -to HDMI_TX_D[0] +set_location_assignment PIN_AE12 -to HDMI_TX_D[1] +set_location_assignment PIN_W8 -to HDMI_TX_D[2] +set_location_assignment PIN_Y8 -to HDMI_TX_D[3] +set_location_assignment PIN_AD11 -to HDMI_TX_D[4] +set_location_assignment PIN_AD10 -to HDMI_TX_D[5] +set_location_assignment PIN_AE11 -to HDMI_TX_D[6] +set_location_assignment PIN_Y5 -to HDMI_TX_D[7] +set_location_assignment PIN_AF10 -to HDMI_TX_D[8] +set_location_assignment PIN_Y4 -to HDMI_TX_D[9] +set_location_assignment PIN_AE9 -to HDMI_TX_D[10] +set_location_assignment PIN_AB4 -to HDMI_TX_D[11] +set_location_assignment PIN_AE7 -to HDMI_TX_D[12] +set_location_assignment PIN_AF6 -to HDMI_TX_D[13] +set_location_assignment PIN_AF8 -to HDMI_TX_D[14] +set_location_assignment PIN_AF5 -to HDMI_TX_D[15] +set_location_assignment PIN_AE4 -to HDMI_TX_D[16] +set_location_assignment PIN_AH2 -to HDMI_TX_D[17] +set_location_assignment PIN_AH4 -to HDMI_TX_D[18] +set_location_assignment PIN_AH5 -to HDMI_TX_D[19] +set_location_assignment PIN_AH6 -to HDMI_TX_D[20] +set_location_assignment PIN_AG6 -to HDMI_TX_D[21] +set_location_assignment PIN_AF9 -to HDMI_TX_D[22] +set_location_assignment PIN_AE8 -to HDMI_TX_D[23] +set_location_assignment PIN_T8 -to HDMI_TX_HS +set_location_assignment PIN_AF11 -to HDMI_TX_INT +set_location_assignment PIN_V13 -to HDMI_TX_VS + +#============================================================ +# KEY +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to KEY[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to KEY[1] +set_location_assignment PIN_AH17 -to KEY[0] +set_location_assignment PIN_AH16 -to KEY[1] + +#============================================================ +# LED +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED[7] +set_location_assignment PIN_W15 -to LED[0] +set_location_assignment PIN_AA24 -to LED[1] +set_location_assignment PIN_V16 -to LED[2] +set_location_assignment PIN_V15 -to LED[3] +set_location_assignment PIN_AF26 -to LED[4] +set_location_assignment PIN_AE26 -to LED[5] +set_location_assignment PIN_Y16 -to LED[6] +set_location_assignment PIN_AA23 -to LED[7] + +#============================================================ +# SW +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SW[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SW[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SW[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SW[3] +set_location_assignment PIN_Y24 -to SW[0] +set_location_assignment PIN_W24 -to SW[1] +set_location_assignment PIN_W21 -to SW[2] +set_location_assignment PIN_W20 -to SW[3] + +set_instance_assignment -name HPS_LOCATION HPSINTERFACEPERIPHERALSPIMASTER_X52_Y72_N111 -entity sys_top -to spi +set_instance_assignment -name HPS_LOCATION HPSINTERFACEPERIPHERALUART_X52_Y67_N111 -entity sys_top -to uart +set_instance_assignment -name HPS_LOCATION HPSINTERFACEPERIPHERALI2C_X52_Y60_N111 -entity sys_top -to hdmi_i2c + +set_global_assignment -name PRE_FLOW_SCRIPT_FILE "quartus_sh:sys/build_id.tcl" + +set_global_assignment -name CDF_FILE jtag.cdf +set_global_assignment -name QIP_FILE sys/sys.qip + diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sys_analog.tcl b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_analog.tcl new file mode 100644 index 0000000000000000000000000000000000000000..692043f8c9de847c7b68c2277579c207bded9d9a --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_analog.tcl @@ -0,0 +1,71 @@ +#============================================================ +# SDIO +#============================================================ +set_location_assignment PIN_AF25 -to SDIO_DAT[0] +set_location_assignment PIN_AF23 -to SDIO_DAT[1] +set_location_assignment PIN_AD26 -to SDIO_DAT[2] +set_location_assignment PIN_AF28 -to SDIO_DAT[3] +set_location_assignment PIN_AF27 -to SDIO_CMD +set_location_assignment PIN_AH26 -to SDIO_CLK +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to SDIO_* + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SDIO_* +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to SDIO_DAT[*] +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to SDIO_CMD + +#============================================================ +# VGA +#============================================================ +set_location_assignment PIN_AE17 -to VGA_R[0] +set_location_assignment PIN_AE20 -to VGA_R[1] +set_location_assignment PIN_AF20 -to VGA_R[2] +set_location_assignment PIN_AH18 -to VGA_R[3] +set_location_assignment PIN_AH19 -to VGA_R[4] +set_location_assignment PIN_AF21 -to VGA_R[5] + +set_location_assignment PIN_AE19 -to VGA_G[0] +set_location_assignment PIN_AG15 -to VGA_G[1] +set_location_assignment PIN_AF18 -to VGA_G[2] +set_location_assignment PIN_AG18 -to VGA_G[3] +set_location_assignment PIN_AG19 -to VGA_G[4] +set_location_assignment PIN_AG20 -to VGA_G[5] + +set_location_assignment PIN_AG21 -to VGA_B[0] +set_location_assignment PIN_AA20 -to VGA_B[1] +set_location_assignment PIN_AE22 -to VGA_B[2] +set_location_assignment PIN_AF22 -to VGA_B[3] +set_location_assignment PIN_AH23 -to VGA_B[4] +set_location_assignment PIN_AH21 -to VGA_B[5] + +set_location_assignment PIN_AH22 -to VGA_HS +set_location_assignment PIN_AG24 -to VGA_VS + +set_location_assignment PIN_AH27 -to VGA_EN +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to VGA_EN + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_* +set_instance_assignment -name CURRENT_STRENGTH_NEW 8MA -to VGA_* + +#============================================================ +# AUDIO +#============================================================ +set_location_assignment PIN_AC24 -to AUDIO_L +set_location_assignment PIN_AE25 -to AUDIO_R +set_location_assignment PIN_AG26 -to AUDIO_SPDIF +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to AUDIO_* +set_instance_assignment -name CURRENT_STRENGTH_NEW 8MA -to AUDIO_* + +#============================================================ +# I/O #1 +#============================================================ +set_location_assignment PIN_Y15 -to LED_USER +set_location_assignment PIN_AA15 -to LED_HDD +set_location_assignment PIN_AG28 -to LED_POWER + +set_location_assignment PIN_AH24 -to BTN_USER +set_location_assignment PIN_AG25 -to BTN_OSD +set_location_assignment PIN_AG23 -to BTN_RESET + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LED_* +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to BTN_* +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to BTN_* diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sys_dual_sdram.tcl b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_dual_sdram.tcl new file mode 100644 index 0000000000000000000000000000000000000000..cf90eab8b045ed4deaa26a059cb51e19a5be0026 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_dual_sdram.tcl @@ -0,0 +1,51 @@ +#============================================================ +# Secondary SDRAM +#============================================================ +set_location_assignment PIN_Y15 -to SDRAM2_DQ[0] +set_location_assignment PIN_AC24 -to SDRAM2_DQ[1] +set_location_assignment PIN_AA15 -to SDRAM2_DQ[2] +set_location_assignment PIN_AD26 -to SDRAM2_DQ[3] +set_location_assignment PIN_AG28 -to SDRAM2_DQ[4] +set_location_assignment PIN_AF28 -to SDRAM2_DQ[5] +set_location_assignment PIN_AE25 -to SDRAM2_DQ[6] +set_location_assignment PIN_AF27 -to SDRAM2_DQ[7] +set_location_assignment PIN_AG26 -to SDRAM2_DQ[14] +set_location_assignment PIN_AH27 -to SDRAM2_DQ[15] + +set_location_assignment PIN_AG25 -to SDRAM2_DQ[13] +set_location_assignment PIN_AH26 -to SDRAM2_DQ[12] +set_location_assignment PIN_AH24 -to SDRAM2_DQ[11] +set_location_assignment PIN_AF25 -to SDRAM2_DQ[10] +set_location_assignment PIN_AG23 -to SDRAM2_DQ[9] +set_location_assignment PIN_AF23 -to SDRAM2_DQ[8] +set_location_assignment PIN_AG24 -to SDRAM2_A[12] +set_location_assignment PIN_AH22 -to SDRAM2_CLK +set_location_assignment PIN_AH21 -to SDRAM2_A[9] +set_location_assignment PIN_AG21 -to SDRAM2_A[11] +set_location_assignment PIN_AH23 -to SDRAM2_A[7] +set_location_assignment PIN_AA20 -to SDRAM2_A[8] +set_location_assignment PIN_AF22 -to SDRAM2_A[5] +set_location_assignment PIN_AE22 -to SDRAM2_A[6] +set_location_assignment PIN_AG20 -to SDRAM2_nWE +set_location_assignment PIN_AF21 -to SDRAM2_A[4] + +set_location_assignment PIN_AG19 -to SDRAM2_nCAS +set_location_assignment PIN_AH19 -to SDRAM2_nRAS +set_location_assignment PIN_AG18 -to SDRAM2_nCS +set_location_assignment PIN_AH18 -to SDRAM2_BA[0] +set_location_assignment PIN_AF18 -to SDRAM2_BA[1] +set_location_assignment PIN_AF20 -to SDRAM2_A[10] +set_location_assignment PIN_AG15 -to SDRAM2_A[0] +set_location_assignment PIN_AE20 -to SDRAM2_A[1] +set_location_assignment PIN_AE19 -to SDRAM2_A[2] +set_location_assignment PIN_AE17 -to SDRAM2_A[3] + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SDRAM2_* +set_instance_assignment -name CURRENT_STRENGTH_NEW "MAXIMUM CURRENT" -to SDRAM2_* +set_instance_assignment -name FAST_OUTPUT_REGISTER ON -to SDRAM2_* +set_instance_assignment -name FAST_OUTPUT_ENABLE_REGISTER ON -to SDRAM2_DQ[*] +set_instance_assignment -name FAST_INPUT_REGISTER ON -to SDRAM2_DQ[*] +set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to SDRAM2_DQ[*] +set_instance_assignment -name ALLOW_SYNCH_CTRL_USAGE OFF -to *|SDRAM2_* + +set_global_assignment -name VERILOG_MACRO "MISTER_DUAL_SDRAM=1" diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.sdc b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.sdc new file mode 100644 index 0000000000000000000000000000000000000000..c2b4118caccb2fd4629a3ca81a8ec7b71f9ad64f --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.sdc @@ -0,0 +1,77 @@ +# Specify root clocks +create_clock -period "50.0 MHz" [get_ports FPGA_CLK1_50] +create_clock -period "50.0 MHz" [get_ports FPGA_CLK2_50] +create_clock -period "50.0 MHz" [get_ports FPGA_CLK3_50] +create_clock -period "100.0 MHz" [get_pins -compatibility_mode *|h2f_user0_clk] +create_clock -period "100.0 MHz" [get_pins -compatibility_mode spi|sclk_out] -name spi_sck +create_clock -period "10.0 MHz" [get_pins -compatibility_mode hdmi_i2c|out_clk] -name hdmi_sck + +derive_pll_clocks +derive_clock_uncertainty + +# Decouple different clock groups (to simplify routing) +set_clock_groups -exclusive \ + -group [get_clocks { *|pll|pll_inst|altera_pll_i|*[*].*|divclk}] \ + -group [get_clocks { pll_hdmi|pll_hdmi_inst|altera_pll_i|*[0].*|divclk}] \ + -group [get_clocks { pll_audio|pll_audio_inst|altera_pll_i|*[0].*|divclk}] \ + -group [get_clocks { spi_sck}] \ + -group [get_clocks { hdmi_sck}] \ + -group [get_clocks { *|h2f_user0_clk}] \ + -group [get_clocks { FPGA_CLK1_50 }] \ + -group [get_clocks { FPGA_CLK2_50 }] \ + -group [get_clocks { FPGA_CLK3_50 }] + +set_false_path -from [get_ports {KEY*}] +set_false_path -from [get_ports {BTN_*}] +set_false_path -to [get_ports {LED_*}] +set_false_path -to [get_ports {VGA_*}] +set_false_path -from [get_ports {VGA_EN}] +set_false_path -to [get_ports {AUDIO_SPDIF}] +set_false_path -to [get_ports {AUDIO_L}] +set_false_path -to [get_ports {AUDIO_R}] +set_false_path -from {get_ports {SW[*]}} +set_false_path -to {cfg[*]} +set_false_path -from {cfg[*]} +set_false_path -from {VSET[*]} +set_false_path -to {wcalc[*] hcalc[*]} +set_false_path -to {hdmi_width[*] hdmi_height[*]} +set_false_path -to {deb_* btn_en btn_up} + +set_multicycle_path -to {*_osd|osd_vcnt*} -setup 2 +set_multicycle_path -to {*_osd|osd_vcnt*} -hold 1 + +set_false_path -to {*_osd|v_cnt*} +set_false_path -to {*_osd|v_osd_start*} +set_false_path -to {*_osd|v_info_start*} +set_false_path -to {*_osd|h_osd_start*} +set_false_path -from {*_osd|v_osd_start*} +set_false_path -from {*_osd|v_info_start*} +set_false_path -from {*_osd|h_osd_start*} +set_false_path -from {*_osd|rot*} +set_false_path -from {*_osd|dsp_width*} +set_false_path -to {*_osd|half} + +set_false_path -to {WIDTH[*] HFP[*] HS[*] HBP[*] HEIGHT[*] VFP[*] VS[*] VBP[*]} +set_false_path -from {WIDTH[*] HFP[*] HS[*] HBP[*] HEIGHT[*] VFP[*] VS[*] VBP[*]} +set_false_path -to {FB_BASE[*] FB_BASE[*] FB_WIDTH[*] FB_HEIGHT[*] LFB_HMIN[*] LFB_HMAX[*] LFB_VMIN[*] LFB_VMAX[*]} +set_false_path -from {FB_BASE[*] FB_BASE[*] FB_WIDTH[*] FB_HEIGHT[*] LFB_HMIN[*] LFB_HMAX[*] LFB_VMIN[*] LFB_VMAX[*]} +set_false_path -to {vol_att[*] scaler_flt[*] led_overtake[*] led_state[*]} +set_false_path -from {vol_att[*] scaler_flt[*] led_overtake[*] led_state[*]} +set_false_path -from {aflt_* acx* acy* areset* arc*} +set_false_path -from {arx* ary*} +set_false_path -from {vs_line*} +set_false_path -from {ColorBurst_Range* PhaseInc* pal_en cvbs yc_en} + +set_false_path -from {ascal|o_ihsize*} +set_false_path -from {ascal|o_ivsize*} +set_false_path -from {ascal|o_format*} +set_false_path -from {ascal|o_hdown} +set_false_path -from {ascal|o_vdown} +set_false_path -from {ascal|o_hmin* ascal|o_hmax* ascal|o_vmin* ascal|o_vmax* ascal|o_vrrmax* ascal|o_vrr} +set_false_path -from {ascal|o_hdisp* ascal|o_vdisp*} +set_false_path -from {ascal|o_htotal* ascal|o_vtotal*} +set_false_path -from {ascal|o_hsstart* ascal|o_vsstart* ascal|o_hsend* ascal|o_vsend*} +set_false_path -from {ascal|o_hsize* ascal|o_vsize*} + +set_false_path -from {mcp23009|flg_*} +set_false_path -to {sysmem|fpga_interfaces|clocks_resets|f2h*} diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.v b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.v new file mode 100644 index 0000000000000000000000000000000000000000..a4168795b68bed4b655b00cb7ced5cf5b4f32741 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sys_top.v @@ -0,0 +1,1949 @@ +//============================================================================ +// +// MiSTer hardware abstraction module +// (c)2017-2020 Alexey Melnikov +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ + +module sys_top +( + /////////// CLOCK ////////// + input FPGA_CLK1_50, + input FPGA_CLK2_50, + input FPGA_CLK3_50, + + //////////// HDMI ////////// + output HDMI_I2C_SCL, + inout HDMI_I2C_SDA, + + output HDMI_MCLK, + output HDMI_SCLK, + output HDMI_LRCLK, + output HDMI_I2S, + + output HDMI_TX_CLK, + output HDMI_TX_DE, + output [23:0] HDMI_TX_D, + output HDMI_TX_HS, + output HDMI_TX_VS, + + input HDMI_TX_INT, + + //////////// SDR /////////// + output [12:0] SDRAM_A, + inout [15:0] SDRAM_DQ, + output SDRAM_DQML, + output SDRAM_DQMH, + output SDRAM_nWE, + output SDRAM_nCAS, + output SDRAM_nRAS, + output SDRAM_nCS, + output [1:0] SDRAM_BA, + output SDRAM_CLK, + output SDRAM_CKE, + +`ifdef MISTER_DUAL_SDRAM + ////////// SDR #2 ////////// + output [12:0] SDRAM2_A, + inout [15:0] SDRAM2_DQ, + output SDRAM2_nWE, + output SDRAM2_nCAS, + output SDRAM2_nRAS, + output SDRAM2_nCS, + output [1:0] SDRAM2_BA, + output SDRAM2_CLK, + +`else + //////////// VGA /////////// + output [5:0] VGA_R, + output [5:0] VGA_G, + output [5:0] VGA_B, + inout VGA_HS, + output VGA_VS, + input VGA_EN, // active low + + /////////// AUDIO ////////// + output AUDIO_L, + output AUDIO_R, + output AUDIO_SPDIF, + + //////////// SDIO /////////// + inout [3:0] SDIO_DAT, + inout SDIO_CMD, + output SDIO_CLK, + + //////////// I/O /////////// + output LED_USER, + output LED_HDD, + output LED_POWER, + input BTN_USER, + input BTN_OSD, + input BTN_RESET, +`endif + + ////////// I/O ALT ///////// + output SD_SPI_CS, + input SD_SPI_MISO, + output SD_SPI_CLK, + output SD_SPI_MOSI, + + inout SDCD_SPDIF, + output IO_SCL, + inout IO_SDA, + + ////////// ADC ////////////// + output ADC_SCK, + input ADC_SDO, + output ADC_SDI, + output ADC_CONVST, + + ////////// MB KEY /////////// + input [1:0] KEY, + + ////////// MB SWITCH //////// + input [3:0] SW, + + ////////// MB LED /////////// + output [7:0] LED, + + ///////// USER IO /////////// + inout [6:0] USER_IO +); + +////////////////////// Secondary SD /////////////////////////////////// +wire SD_CS, SD_CLK, SD_MOSI, SD_MISO, SD_CD; + +`ifndef MISTER_DUAL_SDRAM + wire sd_cd = SDCD_SPDIF & ~SW[2]; // SW[2]=ON workaround for faulty boards without SD card detect pin. + assign SD_CD = mcp_en ? mcp_sdcd : sd_cd; + assign SD_MISO = SD_CD | (mcp_en ? SD_SPI_MISO : (VGA_EN | SDIO_DAT[0])); + assign SD_SPI_CS = mcp_en ? (mcp_sdcd ? 1'bZ : SD_CS) : (sog & ~cs1 & ~VGA_EN) ? 1'b1 : 1'bZ; + assign SD_SPI_CLK = (~mcp_en | mcp_sdcd) ? 1'bZ : SD_CLK; + assign SD_SPI_MOSI = (~mcp_en | mcp_sdcd) ? 1'bZ : SD_MOSI; + assign {SDIO_CLK,SDIO_CMD,SDIO_DAT} = av_dis ? 6'bZZZZZZ : (mcp_en | sd_cd) ? {vga_g,vga_r,vga_b} : {SD_CLK,SD_MOSI,SD_CS,3'bZZZ}; +`else + assign SD_CD = mcp_sdcd; + assign SD_MISO = mcp_sdcd | SD_SPI_MISO; + assign SD_SPI_CS = mcp_sdcd ? 1'bZ : SD_CS; + assign SD_SPI_CLK = mcp_sdcd ? 1'bZ : SD_CLK; + assign SD_SPI_MOSI = mcp_sdcd ? 1'bZ : SD_MOSI; +`endif + +////////////////////// LEDs/Buttons /////////////////////////////////// + +reg [7:0] led_overtake = 0; +reg [7:0] led_state = 0; + +wire led_p = led_power[1] ? ~led_power[0] : 1'b0; +wire led_d = led_disk[1] ? ~led_disk[0] : ~(led_disk[0] | gp_out[29]); +wire led_u = ~led_user; +wire led_locked; + +//LEDs on de10-nano board +assign LED = (led_overtake & led_state) | (~led_overtake & {1'b0,led_locked,1'b0, ~led_p, 1'b0, ~led_d, 1'b0, ~led_u}); + +wire [2:0] mcp_btn; +wire mcp_sdcd; +wire mcp_en; +wire mcp_mode; +mcp23009 mcp23009 +( + .clk(FPGA_CLK2_50), + + .btn(mcp_btn), + .led({led_p, led_d, led_u}), + .flg_sd_cd(mcp_sdcd), + .flg_present(mcp_en), + .flg_mode(mcp_mode), + + .scl(IO_SCL), + .sda(IO_SDA) +); + +wire io_dig = mcp_en ? mcp_mode : SW[3]; + +`ifndef MISTER_DUAL_SDRAM + wire av_dis = io_dig | VGA_EN; + assign LED_POWER = av_dis ? 1'bZ : mcp_en ? de1 : led_p ? 1'bZ : 1'b0; + assign LED_HDD = av_dis ? 1'bZ : mcp_en ? (sog & ~cs1) : led_d ? 1'bZ : 1'b0; + //assign LED_USER = av_dis ? 1'bZ : mcp_en ? ~vga_tx_clk : led_u ? 1'bZ : 1'b0; + assign LED_USER = VGA_TX_CLK; + wire BTN_DIS = VGA_EN; +`else + wire BTN_RESET = 1'b1; + wire BTN_OSD = 1'b1; + wire BTN_USER = 1'b1; + wire BTN_DIS = 1'b1; +`endif + +reg BTN_EN = 0; +reg [25:0] btn_timeout = 0; +initial btn_timeout = 0; +always @(posedge FPGA_CLK2_50) begin + reg btn_up = 0; + reg btn_en = 0; + + btn_up <= BTN_RESET & BTN_OSD & BTN_USER; + if(~reset & btn_up & ~&btn_timeout) btn_timeout <= btn_timeout + 1'd1; + btn_en <= ~BTN_DIS; + BTN_EN <= &btn_timeout & btn_en; +end + +wire btn_r = (mcp_en | SW[3]) ? mcp_btn[1] : (BTN_EN & ~BTN_RESET); +wire btn_o = (mcp_en | SW[3]) ? mcp_btn[2] : (BTN_EN & ~BTN_OSD ); +wire btn_u = (mcp_en | SW[3]) ? mcp_btn[0] : (BTN_EN & ~BTN_USER ); + +reg btn_user, btn_osd; +always @(posedge FPGA_CLK2_50) begin + integer div; + reg [7:0] deb_user; + reg [7:0] deb_osd; + + div <= div + 1'b1; + if(div > 100000) div <= 0; + + if(!div) begin + deb_user <= {deb_user[6:0], btn_u | ~KEY[1]}; + if(&deb_user) btn_user <= 1; + if(!deb_user) btn_user <= 0; + + deb_osd <= {deb_osd[6:0], btn_o | ~KEY[0]}; + if(&deb_osd) btn_osd <= 1; + if(!deb_osd) btn_osd <= 0; + end +end + +///////////////////////// HPS I/O ///////////////////////////////////// + +// gp_in[31] = 0 - quick flag that FPGA is initialized (HPS reads 1 when FPGA is not in user mode) +// used to avoid lockups while JTAG loading +wire [31:0] gp_in = {1'b0, btn_user | btn[1], btn_osd | btn[0], io_dig, 7'd0, ~HDMI_TX_INT, io_ver, io_ack, io_wide, io_dout | io_dout_sys}; +wire [31:0] gp_out; + +wire [1:0] io_ver = 1; // 0 - obsolete. 1 - optimized HPS I/O. 2,3 - reserved for future. +wire io_wait; +wire io_wide; +wire [15:0] io_dout; +wire [15:0] io_din = gp_outr[15:0]; +wire io_clk = gp_outr[17]; +wire io_ss0 = gp_outr[18]; +wire io_ss1 = gp_outr[19]; +wire io_ss2 = gp_outr[20]; + +`ifndef MISTER_DEBUG_NOHDMI + wire io_osd_hdmi = io_ss1 & ~io_ss0; +`endif + +wire io_fpga = ~io_ss1 & io_ss0; +wire io_uio = ~io_ss1 & io_ss2; + +reg io_ack; +reg rack; +wire io_strobe = ~rack & io_clk; + +always @(posedge clk_sys) begin + if(~(io_wait | vs_wait) | io_strobe) begin + rack <= io_clk; + io_ack <= rack; + end +end + +reg [31:0] gp_outr; +always @(posedge clk_sys) begin + reg [31:0] gp_outd; + gp_outr <= gp_outd; + gp_outd <= gp_out; +end + +`ifdef MISTER_DUAL_SDRAM + wire [7:0] core_type = 'hA8; // generic core, dual SDRAM. +`else + wire [7:0] core_type = 'hA4; // generic core. +`endif + +// HPS will not communicate to core if magic is different +wire [31:0] core_magic = {24'h5CA623, core_type}; + +cyclonev_hps_interface_mpu_general_purpose h2f_gp +( + .gp_in({~gp_out[31] ? core_magic : gp_in}), + .gp_out(gp_out) +); + + +reg [15:0] cfg; +reg cfg_set = 0; + +`ifdef MISTER_DEBUG_NOHDMI + wire vga_fb = 0; + wire direct_video = 1; +`else + wire vga_fb = cfg[12] | vga_force_scaler; + wire direct_video = cfg[10]; +`endif + +wire audio_96k = cfg[6]; +wire csync_en = cfg[3]; +wire io_osd_vga = io_ss1 & ~io_ss2; +`ifndef MISTER_DUAL_SDRAM + wire forced_scandoubler = cfg[4]; + wire ypbpr_en = cfg[5]; + wire sog = cfg[9]; + `ifdef MISTER_DEBUG_NOHDMI + wire vga_scaler = 0; + `else + wire vga_scaler = cfg[2] | vga_force_scaler; + `endif +`endif + +reg cfg_custom_t = 0; +reg [5:0] cfg_custom_p1; +reg [31:0] cfg_custom_p2; + +reg [4:0] vol_att; +initial vol_att = 5'b11111; +reg [1:0] vol_boost = 0; + +reg [11:0] coef_addr; +reg [9:0] coef_data; +reg coef_wr = 0; + +wire[12:0] ARX, ARY; +reg [11:0] VSET = 0, HSET = 0; +reg FREESCALE = 0; +reg [2:0] scaler_flt; +reg lowlat = 0; +reg cfg_done = 0; + +reg vs_wait = 0; +reg [11:0] vs_line = 0; + +reg scaler_out = 0; +reg vrr_mode = 0; +wire hdmi_blackout; + +reg [31:0] aflt_rate = 7056000; +reg [39:0] acx = 4258969; +reg [7:0] acx0 = 3; +reg [7:0] acx1 = 3; +reg [7:0] acx2 = 1; +reg [23:0] acy0 = -24'd6216759; +reg [23:0] acy1 = 24'd6143386; +reg [23:0] acy2 = -24'd2023767; +reg areset = 0; +reg [12:0] arc1x = 0; +reg [12:0] arc1y = 0; +reg [12:0] arc2x = 0; +reg [12:0] arc2y = 0; +reg [15:0] io_dout_sys; + +always@(posedge clk_sys) begin + reg [7:0] cmd; + reg has_cmd; + reg [7:0] cnt = 0; + reg vs_d0,vs_d1,vs_d2; + reg [4:0] acx_att; + reg [7:0] fb_crc; + reg [1:0] sl_r; + + coef_wr <= 0; + sl_r <= FB_EN ? 2'b00 : scanlines; + +`ifndef MISTER_DEBUG_NOHDMI + shadowmask_wr <= 0; +`endif + + if(~io_uio) begin + has_cmd <= 0; + cmd <= 0; + areset <= 0; + acx_att <= 0; + acx <= acx >> acx_att; + io_dout_sys <= 0; + end + else + if(io_strobe) begin + io_dout_sys <= 0; + if(!has_cmd) begin + has_cmd <= 1; + cmd <= io_din[7:0]; + cnt <= 0; + if(io_din[7:0] == 'h30) vs_wait <= 1; + if(io_din[7:0] == 'h39) begin + aflt_rate <= 7056000; + acx <= 4258969; + acx0 <= 3; + acx1 <= 3; + acx2 <= 1; + acy0 <= -24'd6216759; + acy1 <= 24'd6143386; + acy2 <= -24'd2023767; + areset <= 1; + io_dout_sys <= 'b11; + end + if(io_din[7:0] == 'h20) io_dout_sys <= 'b11; +`ifdef MISTER_DISABLE_ADAPTIVE + if(io_din[7:0] == 'h2B) io_dout_sys <= {fb_en, sl_r, 4'b0110}; +`else + if(io_din[7:0] == 'h2B) io_dout_sys <= {fb_en, sl_r, 4'b0111}; +`endif + if(io_din[7:0] == 'h2F) io_dout_sys <= 1; + if(io_din[7:0] == 'h3E) io_dout_sys <= 1; +`ifndef MISTER_DEBUG_NOHDMI + if(io_din[7:0] == 'h40) io_dout_sys <= fb_crc; +`endif + if(io_din[7:0] == 'h42) io_dout_sys <= {1'b1, frame_cnt}; + if(io_din[7:0] == 'h44) io_dout_sys <= 1; + end + else begin + cnt <= cnt + 1'd1; + if(cmd == 1) begin + cfg <= io_din; + cfg_set <= 1; + scaler_out <= 1; + end + if(cmd == 'h20) begin + cfg_set <= 0; + if(cnt<8) begin + case(cnt[2:0]) + 0: {HDMI_PR,vrr_mode,WIDTH} <= {io_din[15:14], io_din[11:0]}; + 1: HFP <= io_din[11:0]; + 2: HS <= {io_din[15], io_din[11:0]}; + 3: HBP <= io_din[11:0]; + 4: HEIGHT <= io_din[11:0]; + 5: VFP <= io_din[11:0]; + 6: VS <= {io_din[15],io_din[11:0]}; + 7: VBP <= io_din[11:0]; + endcase +`ifndef MISTER_DEBUG_NOHDMI + if(cnt == 1) begin + cfg_custom_p1 <= 0; + cfg_custom_p2 <= 0; + cfg_custom_t <= ~cfg_custom_t; + end + end + else begin + if(cnt[1:0]==0) cfg_custom_p1 <= io_din[5:0]; + if(cnt[1:0]==1) cfg_custom_p2[15:0] <= io_din; + if(cnt[1:0]==2) begin + cfg_custom_p2[31:16] <= io_din; + cfg_custom_t <= ~cfg_custom_t; + cnt[2:0] <= 3'b100; + end + if(cnt == 8) {lowlat,cfg_done} <= {io_din[15],1'b1}; +`endif + end + end + if(cmd == 'h2F) begin + case(cnt[3:0]) + 0: {LFB_EN,LFB_FLT,LFB_FMT} <= {io_din[15], io_din[14], io_din[5:0]}; + 1: LFB_BASE[15:0] <= io_din[15:0]; + 2: LFB_BASE[31:16] <= io_din[15:0]; + 3: LFB_WIDTH <= io_din[11:0]; + 4: LFB_HEIGHT <= io_din[11:0]; + 5: LFB_HMIN <= io_din[11:0]; + 6: LFB_HMAX <= io_din[11:0]; + 7: LFB_VMIN <= io_din[11:0]; + 8: LFB_VMAX <= io_din[11:0]; + 9: LFB_STRIDE <= io_din[13:0]; + endcase + end + if(cmd == 'h25) {led_overtake, led_state} <= io_din; + if(cmd == 'h26) vol_att <= io_din[4:0]; + if(cmd == 'h27) VSET <= io_din[11:0]; + if(cmd == 'h2A) begin + if(cnt[0]) {coef_wr,coef_data} <= {1'b1,io_din[9:0]}; + else coef_addr <= io_din[11:0]; + end + if(cmd == 'h2B) scaler_flt <= io_din[2:0]; + if(cmd == 'h37) {FREESCALE,HSET} <= {io_din[15],io_din[11:0]}; + if(cmd == 'h38) vs_line <= io_din[11:0]; + if(cmd == 'h39) begin + case(cnt[3:0]) + 0: {vol_boost,acx_att} <= io_din[6:0]; + 1: aflt_rate[15:0] <= io_din; + 2: aflt_rate[31:16] <= io_din; + 3: acx[15:0] <= io_din; + 4: acx[31:16] <= io_din; + 5: acx[39:32] <= io_din[7:0]; + 6: acx0 <= io_din[7:0]; + 7: acx1 <= io_din[7:0]; + 8: acx2 <= io_din[7:0]; + 9: acy0[15:0] <= io_din; + 10: acy0[23:16] <= io_din[7:0]; + 11: acy1[15:0] <= io_din; + 12: acy1[23:16] <= io_din[7:0]; + 13: acy2[15:0] <= io_din; + 14: acy2[23:16] <= io_din[7:0]; + endcase + end + if(cmd == 'h3A) begin + case(cnt[3:0]) + 0: arc1x <= io_din[12:0]; + 1: arc1y <= io_din[12:0]; + 2: arc2x <= io_din[12:0]; + 3: arc2y <= io_din[12:0]; + endcase + end +`ifndef MISTER_DEBUG_NOHDMI + if(cmd == 'h3E) {shadowmask_wr,shadowmask_data} <= {1'b1, io_din}; + if(cmd == 'h40) begin + case(cnt[3:0]) + 0: io_dout_sys <= {arxy, arx}; + 1: io_dout_sys <= {arxy, ary}; + 2: io_dout_sys <= {LFB_EN, FB_EN, FB_FMT}; + 3: io_dout_sys <= FB_WIDTH; + 4: io_dout_sys <= FB_HEIGHT; + 5: io_dout_sys <= FB_BASE[15:0]; + 6: io_dout_sys <= FB_BASE[31:16]; + 7: io_dout_sys <= FB_STRIDE; + endcase + end +`endif + if(cmd == 'h41) begin + case(cnt[3:0]) +`ifndef MISTER_DISABLE_YC + 0: {pal_en,cvbs,yc_en} <= io_din[2:0]; + 4: ColorBurst_Range[15:0] <= io_din; + 5: ColorBurst_Range[16] <= io_din[0]; +`endif + // Subcarrier commands (independent of YC module) + 1: PhaseInc[15:0] <= io_din; + 2: PhaseInc[31:16] <= io_din; + 3: PhaseInc[39:32] <= io_din[7:0]; +`ifndef MISTER_DUAL_SDRAM + 6: subcarrier <= io_din[0]; +`endif + endcase + end + end + end + +`ifndef MISTER_DEBUG_NOHDMI + fb_crc <= {LFB_EN, FB_EN, FB_FMT} + ^ FB_WIDTH[7:0] ^ FB_WIDTH[11:8] + ^ FB_HEIGHT[7:0] ^ FB_HEIGHT[11:8] + ^ arx[7:0] ^ arx[11:8] ^ arxy + ^ ary[7:0] ^ ary[11:8]; +`endif + + vs_d0 <= HDMI_TX_VS; + if(vs_d0 == HDMI_TX_VS) vs_d1 <= vs_d0; + + vs_d2 <= vs_d1; + if(~vs_d2 & vs_d1) vs_wait <= 0; +end + +reg [7:0] frame_cnt; +always @(posedge clk_sys) begin + reg vs_r, vs_old; + + vs_r <= vs_fix; + if(vs_r == vs_fix) vs_old <= vs_r; + if(~vs_old & vs_r) frame_cnt <= frame_cnt + 1'd1; +end + +cyclonev_hps_interface_peripheral_uart uart +( + .ri(0), + .dsr(uart_dsr), + .dcd(uart_dsr), + .dtr(uart_dtr), + + .cts(uart_cts), + .rts(uart_rts), + .rxd(uart_rxd), + .txd(uart_txd) +); + +wire [63:0] f2h_irq = {video_sync,HDMI_TX_VS}; +cyclonev_hps_interface_interrupts interrupts +( + .irq(f2h_irq) +); + +/////////////////////////// RESET /////////////////////////////////// + +reg reset_req = 0; +always @(posedge FPGA_CLK2_50) begin + reg [1:0] resetd, resetd2; + reg old_reset; + + //latch the reset + old_reset <= reset; + if(~old_reset & reset) reset_req <= 1; + + //special combination to set/clear the reset + //preventing of accidental reset control + if(resetd==1) reset_req <= 1; + if(resetd==2 && resetd2==0) reset_req <= 0; + + resetd <= gp_out[31:30]; + resetd2 <= resetd; +end + +//////////////////// SYSTEM MEMORY & SCALER ///////////////////////// + +wire reset; +wire clk_100m; + +sysmem_lite sysmem +( + //Reset/Clock + .reset_core_req(reset_req), + .reset_out(reset), + .clock(clk_100m), + + //DE10-nano has no reset signal on GPIO, so core has to emulate cold reset button. + .reset_hps_cold_req(btn_r), + + //64-bit DDR3 RAM access + .ram1_clk(ram_clk), + .ram1_address(ram_address), + .ram1_burstcount(ram_burstcount), + .ram1_waitrequest(ram_waitrequest), + .ram1_readdata(ram_readdata), + .ram1_readdatavalid(ram_readdatavalid), + .ram1_read(ram_read), + .ram1_writedata(ram_writedata), + .ram1_byteenable(ram_byteenable), + .ram1_write(ram_write), + + //64-bit DDR3 RAM access + .ram2_clk(clk_audio), + .ram2_address(ram2_address), + .ram2_burstcount(ram2_burstcount), + .ram2_waitrequest(ram2_waitrequest), + .ram2_readdata(ram2_readdata), + .ram2_readdatavalid(ram2_readdatavalid), + .ram2_read(ram2_read), + .ram2_writedata(ram2_writedata), + .ram2_byteenable(ram2_byteenable), + .ram2_write(ram2_write), + + //128-bit DDR3 RAM access + // HDMI frame buffer + .vbuf_clk(clk_100m), + .vbuf_address(vbuf_address), + .vbuf_burstcount(vbuf_burstcount), + .vbuf_waitrequest(vbuf_waitrequest), + .vbuf_writedata(vbuf_writedata), + .vbuf_byteenable(vbuf_byteenable), + .vbuf_write(vbuf_write), + .vbuf_readdata(vbuf_readdata), + .vbuf_readdatavalid(vbuf_readdatavalid), + .vbuf_read(vbuf_read) +); + +wire [28:0] ram2_address; +wire [7:0] ram2_burstcount; +wire [7:0] ram2_byteenable; +wire ram2_waitrequest; +wire [63:0] ram2_readdata; +wire [63:0] ram2_writedata; +wire ram2_readdatavalid; +wire ram2_read; +wire ram2_write; +wire [7:0] ram2_bcnt; + +ddr_svc ddr_svc +( + .clk(clk_audio), + + .ram_waitrequest(ram2_waitrequest), + .ram_burstcnt(ram2_burstcount), + .ram_addr(ram2_address), + .ram_readdata(ram2_readdata), + .ram_read_ready(ram2_readdatavalid), + .ram_read(ram2_read), + .ram_writedata(ram2_writedata), + .ram_byteenable(ram2_byteenable), + .ram_write(ram2_write), + .ram_bcnt(ram2_bcnt), + +`ifndef MISTER_DISABLE_ALSA + .ch0_addr(alsa_address), + .ch0_burst(1), + .ch0_data(alsa_readdata), + .ch0_req(alsa_req), + .ch0_ready(alsa_ready), +`endif + + .ch1_addr(pal_addr), + .ch1_burst(128), + .ch1_data(pal_data), + .ch1_req(pal_req), + .ch1_ready(pal_wr) +); + +wire clk_pal = clk_audio; + + +wire [27:0] vbuf_address; +wire [7:0] vbuf_burstcount; +wire vbuf_waitrequest; +wire [127:0] vbuf_readdata; +wire vbuf_readdatavalid; +wire vbuf_read; +wire [127:0] vbuf_writedata; +wire [15:0] vbuf_byteenable; +wire vbuf_write; + +wire [23:0] hdmi_data; +wire hdmi_vs, hdmi_hs, hdmi_de, hdmi_vbl, hdmi_brd; +wire freeze; +wire bob_deint; + +`ifndef MISTER_DEBUG_NOHDMI + wire clk_hdmi = hdmi_clk_out; + + ascal + #( + .RAMBASE(32'h20000000), + `ifdef MISTER_SMALL_VBUF + .RAMSIZE(32'h00200000), + `else + .RAMSIZE(32'h00800000), + `endif + `ifndef MISTER_FB + .PALETTE2("false"), + `else + `ifndef MISTER_FB_PALETTE + .PALETTE2("false"), + `endif + `endif + `ifdef MISTER_DISABLE_ADAPTIVE + .ADAPTIVE("false"), + `endif + `ifdef MISTER_DOWNSCALE_NN + .DOWNSCALE_NN("true"), + `endif + .FRAC(8), +`ifdef MENU_CORE + .N_BURST(2048), +`endif + .N_DW(128), + .N_AW(28) + ) + ascal + ( + .reset_na (~reset_req), + .run (1), + .freeze (freeze), + .bob_deint (bob_deint), + + .i_clk (clk_ihdmi), + .i_ce (ce_hpix), + .i_r (hr_out), + .i_g (hg_out), + .i_b (hb_out), + .i_hs (hhs_fix), + .i_vs (hvs_fix), + .i_fl (f1), + .i_de (hde_emu), + .iauto (1), + .himin (0), + .himax (0), + .vimin (0), + .vimax (0), + + .o_clk (clk_hdmi), + .o_ce (scaler_out), + .o_r (hdmi_data[23:16]), + .o_g (hdmi_data[15:8]), + .o_b (hdmi_data[7:0]), + .o_hs (hdmi_hs), + .o_vs (hdmi_vs), + .o_de (hdmi_de), + .o_vbl (hdmi_vbl), + .o_brd (hdmi_brd), + .o_lltune (lltune), + .htotal (WIDTH + HFP + HBP + HS[11:0]), + .hsstart (WIDTH + HFP), + .hsend (WIDTH + HFP + HS[11:0]), + .hdisp (WIDTH), + .hmin (hmin), + .hmax (hmax), + .vtotal (HEIGHT + VFP + VBP + VS[11:0]), + .vsstart (HEIGHT + VFP), + .vsend (HEIGHT + VFP + VS[11:0]), + .vdisp (HEIGHT), + .vmin (vmin), + .vmax (vmax), + .vrr (vrr_mode), + .vrrmax (HEIGHT + VBP + VS[11:0] + 12'd1), + .swblack (hdmi_blackout), + + .mode ({~lowlat,LFB_EN ? LFB_FLT : |scaler_flt,2'b00}), + .poly_clk (clk_sys), + .poly_a (coef_addr), + .poly_dw (coef_data), + .poly_wr (coef_wr), + + .pal1_clk (clk_pal), + .pal1_dw (pal_d), + .pal1_a (pal_a), + .pal1_wr (pal_wr), + + `ifdef MISTER_FB + `ifdef MISTER_FB_PALETTE + .pal2_clk (fb_pal_clk), + .pal2_dw (fb_pal_d), + .pal2_dr (fb_pal_q), + .pal2_a (fb_pal_a), + .pal2_wr (fb_pal_wr), + .pal_n (fb_en), + `endif + `endif + + .o_fb_ena (FB_EN), + .o_fb_hsize (FB_WIDTH), + .o_fb_vsize (FB_HEIGHT), + .o_fb_format (FB_FMT), + .o_fb_base (FB_BASE), + .o_fb_stride (FB_STRIDE), + + .avl_clk (clk_100m), + .avl_waitrequest (vbuf_waitrequest), + .avl_readdata (vbuf_readdata), + .avl_readdatavalid(vbuf_readdatavalid), + .avl_burstcount (vbuf_burstcount), + .avl_writedata (vbuf_writedata), + .avl_address (vbuf_address), + .avl_write (vbuf_write), + .avl_read (vbuf_read), + .avl_byteenable (vbuf_byteenable) + ); +`endif + +reg LFB_EN = 0; +reg LFB_FLT = 0; +reg [5:0] LFB_FMT = 0; +reg [11:0] LFB_WIDTH = 0; +reg [11:0] LFB_HEIGHT = 0; +reg [11:0] LFB_HMIN = 0; +reg [11:0] LFB_HMAX = 0; +reg [11:0] LFB_VMIN = 0; +reg [11:0] LFB_VMAX = 0; +reg [31:0] LFB_BASE = 0; +reg [13:0] LFB_STRIDE = 0; + +reg FB_EN = 0; +reg [5:0] FB_FMT = 0; +reg [11:0] FB_WIDTH = 0; +reg [11:0] FB_HEIGHT = 0; +reg [31:0] FB_BASE = 0; +reg [13:0] FB_STRIDE = 0; + +always @(posedge clk_sys) begin + FB_EN <= LFB_EN | fb_en; + if(LFB_EN) begin + FB_FMT <= LFB_FMT; + FB_WIDTH <= LFB_WIDTH; + FB_HEIGHT <= LFB_HEIGHT; + FB_BASE <= LFB_BASE; + FB_STRIDE <= LFB_STRIDE; + end + else begin + FB_FMT <= fb_fmt; + FB_WIDTH <= fb_width; + FB_HEIGHT <= fb_height; + FB_BASE <= fb_base; + FB_STRIDE <= fb_stride; + end +end + +`ifdef MISTER_FB + reg fb_vbl; + always @(posedge clk_vid) fb_vbl <= hdmi_vbl; +`endif + +reg ar_md_start; +wire ar_md_busy; +reg [11:0] ar_md_mul1, ar_md_mul2, ar_md_div; +wire [11:0] ar_md_res; + +sys_umuldiv #(12,12,12) ar_muldiv +( + .clk(clk_vid), + .start(ar_md_start), + .busy(ar_md_busy), + + .mul1(ar_md_mul1), + .mul2(ar_md_mul2), + .div(ar_md_div), + .result(ar_md_res) +); + +reg [11:0] hmin; +reg [11:0] hmax; +reg [11:0] vmin; +reg [11:0] vmax; +reg [11:0] hdmi_height; +reg [11:0] hdmi_width; + +reg [11:0] arx; +reg [11:0] ary; +reg arxy; + +always @(posedge clk_vid) begin + reg [11:0] hmini,hmaxi,vmini,vmaxi; + reg [11:0] wcalc,videow; + reg [11:0] hcalc,videoh; + reg [2:0] state; + + hdmi_height <= (VSET && (VSET < HEIGHT)) ? VSET : HEIGHT; + hdmi_width <= (HSET && (HSET < WIDTH)) ? HSET << HDMI_PR : WIDTH << HDMI_PR; + + if(!ARY) begin + if(ARX == 1) begin + arx <= arc1x[11:0]; + ary <= arc1y[11:0]; + arxy <= arc1x[12] | arc1y[12]; + end + else if(ARX == 2) begin + arx <= arc2x[11:0]; + ary <= arc2y[11:0]; + arxy <= arc2x[12] | arc2y[12]; + end + else begin + arx <= 0; + ary <= 0; + arxy <= 0; + end + end + else begin + arx <= ARX[11:0]; + ary <= ARY[11:0]; + arxy <= ARX[12] | ARY[12]; + end + + ar_md_start <= 0; + state <= state + 1'd1; + case(state) + 0: if(LFB_EN) begin + hmini <= LFB_HMIN; + vmini <= LFB_VMIN; + hmaxi <= LFB_HMAX; + vmaxi <= LFB_VMAX; + state <= 0; + end + else if(FREESCALE || !arx || !ary) begin + wcalc <= hdmi_width; + hcalc <= hdmi_height; + state <= 6; + end + else if(arxy) begin + wcalc <= arx; + hcalc <= ary; + state <= 6; + end + + 1: begin + ar_md_mul1 <= hdmi_height; + ar_md_mul2 <= arx; + ar_md_div <= ary; + ar_md_start<= 1; + end + 2: begin + wcalc <= ar_md_res; + if(ar_md_start | ar_md_busy) state <= 2; + end + + 3: begin + ar_md_mul1 <= hdmi_width; + ar_md_mul2 <= ary; + ar_md_div <= arx; + ar_md_start<= 1; + end + 4: begin + hcalc <= ar_md_res; + if(ar_md_start | ar_md_busy) state <= 4; + end + + 6: begin + videow <= (wcalc > hdmi_width) ? (hdmi_width >> HDMI_PR) : (wcalc[11:0] >> HDMI_PR); + videoh <= (hcalc > hdmi_height) ? hdmi_height : hcalc[11:0]; + end + + 7: begin + hmini <= ((WIDTH - videow)>>1); + hmaxi <= ((WIDTH - videow)>>1) + videow - 1'd1; + vmini <= ((HEIGHT - videoh)>>1); + vmaxi <= ((HEIGHT - videoh)>>1) + videoh - 1'd1; + end + endcase + + hmin <= hmini; + hmax <= hmaxi; + vmin <= vmini; + vmax <= vmaxi; +end + +`ifndef MISTER_DEBUG_NOHDMI + wire [15:0] lltune; + pll_hdmi_adj pll_hdmi_adj + ( + .clk(FPGA_CLK1_50), + .reset_na(~reset_req), + + .llena(lowlat), + .lltune({16{cfg_done}} & lltune), + .locked(led_locked), + .i_waitrequest(adj_waitrequest), + .i_write(adj_write), + .i_address(adj_address), + .i_writedata(adj_data), + .o_waitrequest(cfg_waitrequest), + .o_write(cfg_write), + .o_address(cfg_address), + .o_writedata(cfg_data) + ); +`else + assign led_locked = 0; +`endif + +wire [63:0] pal_data; +wire [47:0] pal_d = {pal_data[55:32], pal_data[23:0]}; +wire [6:0] pal_a = ram2_bcnt[6:0]; +wire pal_wr; + +reg [28:0] pal_addr; +reg pal_req = 0; +always @(posedge clk_pal) begin + reg old_vs1, old_vs2; + + pal_addr <= LFB_BASE[31:3] - 29'd512; + + old_vs1 <= hdmi_vs; + old_vs2 <= old_vs1; + + if(~old_vs2 & old_vs1 & ~FB_FMT[2] & FB_FMT[1] & FB_FMT[0] & FB_EN) pal_req <= ~pal_req; +end + + +///////////////////////// HDMI output ///////////////////////////////// +`ifndef MISTER_DEBUG_NOHDMI + wire hdmi_clk_out; + pll_hdmi pll_hdmi + ( + .refclk(FPGA_CLK1_50), + .rst(reset_req), + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll), + .outclk_0(hdmi_clk_out) + ); +`endif + +//1920x1080@60 PCLK=148.5MHz CEA +reg [11:0] WIDTH = 1920; +reg [11:0] HFP = 88; +reg [12:0] HS = 48; +reg [11:0] HBP = 148; +reg [11:0] HEIGHT = 1080; +reg [11:0] VFP = 4; +reg [12:0] VS = 5; +reg [11:0] VBP = 36; +reg HDMI_PR = 0; + +wire [63:0] reconfig_to_pll; +wire [63:0] reconfig_from_pll; +wire cfg_waitrequest,adj_waitrequest; +wire cfg_write; +wire [5:0] cfg_address; +wire [31:0] cfg_data; +reg adj_write; +reg [5:0] adj_address; +reg [31:0] adj_data; + +`ifndef MISTER_DEBUG_NOHDMI + pll_cfg_hdmi pll_cfg_hdmi + ( + .mgmt_clk(FPGA_CLK1_50), + .mgmt_reset(reset_req), + .mgmt_waitrequest(cfg_waitrequest), + .mgmt_write(cfg_write), + .mgmt_address(cfg_address), + .mgmt_writedata(cfg_data), + .reconfig_to_pll(reconfig_to_pll), + .reconfig_from_pll(reconfig_from_pll) + ); + + reg cfg_got = 0; + always @(posedge clk_sys) begin + reg vsd, vsd2; + if(~cfg_ready || ~cfg_set) cfg_got <= cfg_set; + else begin + vsd <= HDMI_TX_VS; + vsd2 <= vsd; + if(~vsd2 & vsd) cfg_got <= cfg_set; + end + end + + reg cfg_ready = 0; + always @(posedge FPGA_CLK1_50) begin + reg gotd = 0, gotd2 = 0; + reg custd = 0, custd2 = 0; + reg old_wait = 0; + + gotd <= cfg_got; + gotd2 <= gotd; + + adj_write <= 0; + + custd <= cfg_custom_t; + custd2 <= custd; + if(custd2 != custd & ~gotd) begin + adj_address <= cfg_custom_p1; + adj_data <= cfg_custom_p2; + adj_write <= 1; + end + + if(~gotd2 & gotd) begin + adj_address <= 2; + adj_data <= 0; + adj_write <= 1; + end + + old_wait <= adj_waitrequest; + if(old_wait & ~adj_waitrequest & gotd) cfg_ready <= 1; + end +`else + wire cfg_ready = 1; +`endif + +assign HDMI_I2C_SCL = hdmi_scl_en ? 1'b0 : 1'bZ; +assign HDMI_I2C_SDA = hdmi_sda_en ? 1'b0 : 1'bZ; + +wire hdmi_scl_en, hdmi_sda_en; +cyclonev_hps_interface_peripheral_i2c hdmi_i2c +( + .out_clk(hdmi_scl_en), + .scl(HDMI_I2C_SCL), + .out_data(hdmi_sda_en), + .sda(HDMI_I2C_SDA) +); + +`ifndef MISTER_DEBUG_NOHDMI + `ifdef MISTER_FB + reg dis_output; + always @(posedge clk_hdmi) begin + reg dis; + dis <= fb_force_blank & ~LFB_EN; + dis_output <= dis; + end + `else + wire dis_output = 0; + `endif + + wire [23:0] hdmi_data_mask; + wire hdmi_de_mask, hdmi_vs_mask, hdmi_hs_mask; + + reg [15:0] shadowmask_data; + reg shadowmask_wr = 0; + + shadowmask HDMI_shadowmask + ( + .clk(clk_hdmi), + .clk_sys(clk_sys), + + .cmd_wr(shadowmask_wr), + .cmd_in(shadowmask_data), + + .din(dis_output ? 24'd0 : hdmi_data), + .hs_in(hdmi_hs), + .vs_in(hdmi_vs), + .de_in(hdmi_de), + .brd_in(hdmi_brd), + .enable(~LFB_EN), + + .dout(hdmi_data_mask), + .hs_out(hdmi_hs_mask), + .vs_out(hdmi_vs_mask), + .de_out(hdmi_de_mask) + ); + + wire [23:0] hdmi_data_osd; + wire hdmi_de_osd, hdmi_vs_osd, hdmi_hs_osd; + + osd hdmi_osd + ( + .clk_sys(clk_sys), + + .io_osd(io_osd_hdmi), + .io_strobe(io_strobe), + .io_din(io_din), + + .clk_video(clk_hdmi), + .din(hdmi_data_mask), + .hs_in(hdmi_hs_mask), + .vs_in(hdmi_vs_mask), + .de_in(hdmi_de_mask), + + .dout(hdmi_data_osd), + .hs_out(hdmi_hs_osd), + .vs_out(hdmi_vs_osd), + .de_out(hdmi_de_osd) + ); + + wire hdmi_cs_osd; + csync csync_hdmi(clk_hdmi, hdmi_hs_osd, hdmi_vs_osd, hdmi_cs_osd); +`endif + +reg [23:0] dv_data; +reg dv_hs, dv_vs, dv_de; +wire [23:0] dv_data_osd; +wire dv_hs_osd, dv_vs_osd, dv_cs_osd; + +always @(posedge clk_vid) begin + reg [23:0] dv_d1, dv_d2; + reg dv_de1, dv_de2, dv_hs1, dv_hs2, dv_vs1, dv_vs2; + reg [12:0] vsz, vcnt, vcnt_l, vcnt_ll; + reg old_hs, old_vs; + reg vde; + reg [3:0] hss; + + if(ce_pix) begin + hss <= (hss << 1) | dv_hs_osd; + + old_hs <= dv_hs_osd; + if(~old_hs && dv_hs_osd) begin + old_vs <= dv_vs_osd; + if(~&vcnt) vcnt <= vcnt + 1'd1; + if(~old_vs & dv_vs_osd) begin + if (vcnt != vcnt_ll || vcnt < vcnt_l) vsz <= vcnt; + vcnt_l <= vcnt; + vcnt_ll <= vcnt_l; + end + if(old_vs & ~dv_vs_osd) vcnt <= 0; + + if(vcnt == 1) vde <= 1; + if(vcnt == vsz - 3) vde <= 0; + end + + dv_de1 <= !{hss,dv_hs_osd} && vde; + end + + dv_d1 <= dv_data_osd; + dv_hs1 <= csync_en ? dv_cs_osd : dv_hs_osd; + dv_vs1 <= dv_vs_osd; + + dv_d2 <= dv_d1; + dv_de2 <= dv_de1; + dv_hs2 <= dv_hs1; + dv_vs2 <= dv_vs1; + + dv_data<= dv_d2; + dv_de <= dv_de2; + dv_hs <= dv_hs2; + dv_vs <= dv_vs2; +end + +`ifndef MISTER_DISABLE_YC + assign {dv_data_osd, dv_hs_osd, dv_vs_osd, dv_cs_osd } = ~yc_en ? {vga_data_osd, vga_hs_osd, vga_vs_osd, vga_cs_osd } : {yc_o, yc_hs, yc_vs, yc_cs }; +`else + assign {dv_data_osd, dv_hs_osd, dv_vs_osd, dv_cs_osd } = {vga_data_osd, vga_hs_osd, vga_vs_osd, vga_cs_osd }; +`endif + +wire hdmi_tx_clk; +`ifndef MISTER_DEBUG_NOHDMI + cyclonev_clkselect hdmi_clk_sw + ( + .clkselect({1'b1, ~vga_fb & direct_video}), + .inclk({clk_vid, hdmi_clk_out, 2'b00}), + .outclk(hdmi_tx_clk) + ); +`else + assign hdmi_tx_clk = clk_vid; +`endif + +altddio_out +#( + .extend_oe_disable("OFF"), + .intended_device_family("Cyclone V"), + .invert_output("OFF"), + .lpm_hint("UNUSED"), + .lpm_type("altddio_out"), + .oe_reg("UNREGISTERED"), + .power_up_high("OFF"), + .width(1) +) +hdmiclk_ddr +( + .datain_h(1'b0), + .datain_l(1'b1), + .outclock(hdmi_tx_clk), + .dataout(HDMI_TX_CLK), + .aclr(1'b0), + .aset(1'b0), + .oe(1'b1), + .outclocken(1'b1), + .sclr(1'b0), + .sset(1'b0) +); + +reg hdmi_out_hs; +reg hdmi_out_vs; +reg hdmi_out_de; +reg [23:0] hdmi_out_d; + +always @(posedge hdmi_tx_clk) begin + reg [23:0] hdmi_dv_data; + reg hdmi_dv_hs, hdmi_dv_vs, hdmi_dv_de; + + reg hs,vs,de; + reg [23:0] d; + + hdmi_dv_data <= dv_data; + hdmi_dv_hs <= dv_hs; + hdmi_dv_vs <= dv_vs; + hdmi_dv_de <= dv_de; + +`ifndef MISTER_DEBUG_NOHDMI + hs <= (~vga_fb & direct_video) ? hdmi_dv_hs : (direct_video & csync_en) ? hdmi_cs_osd : hdmi_hs_osd; + vs <= (~vga_fb & direct_video) ? hdmi_dv_vs : hdmi_vs_osd; + de <= (~vga_fb & direct_video) ? hdmi_dv_de : hdmi_de_osd; + d <= (~vga_fb & direct_video) ? hdmi_dv_data : hdmi_data_osd; +`else + hs <= hdmi_dv_hs; + vs <= hdmi_dv_vs; + de <= hdmi_dv_de; + d <= hdmi_dv_data; +`endif + + hdmi_out_hs <= hs; + hdmi_out_vs <= vs; + hdmi_out_de <= de; + hdmi_out_d <= d; +end + +assign HDMI_TX_HS = hdmi_out_hs; +assign HDMI_TX_VS = hdmi_out_vs; +assign HDMI_TX_DE = hdmi_out_de; +assign HDMI_TX_D = hdmi_out_d; + +///////////////////////// VGA output ////////////////////////////////// + +`ifndef MISTER_DUAL_SDRAM + wire vga_tx_clk; + `ifndef MISTER_DEBUG_NOHDMI + cyclonev_clkselect vga_clk_sw + ( + .clkselect({1'b1, ~vga_fb & ~vga_scaler}), + .inclk({clk_vid, hdmi_clk_out, 2'b00}), + .outclk(vga_tx_clk) + ); + `else + assign vga_tx_clk = clk_vid; + `endif + + wire VGA_TX_CLK; + altddio_out + #( + .extend_oe_disable("OFF"), + .intended_device_family("Cyclone V"), + .invert_output("OFF"), + .lpm_hint("UNUSED"), + .lpm_type("altddio_out"), + .oe_reg("UNREGISTERED"), + .power_up_high("OFF"), + .width(1) + ) + vgaclk_ddr + ( + .datain_h(1'b0), + .datain_l(1'b1), + .outclock(vga_tx_clk), + .dataout(VGA_TX_CLK), + .aclr(~mcp_en & ~av_dis), + .aset(1'b0), + .oe(~av_dis & (mcp_en | ~led_u)), + .outclocken(1'b1), + .sclr(1'b0), + .sset(1'b0) + ); +`endif + +wire [23:0] vga_data_sl; +wire vga_de_sl, vga_ce_sl, vga_vs_sl, vga_hs_sl; +scanlines #(0) VGA_scanlines +( + .clk(clk_vid), + + .scanlines(scanlines), + .din(de_emu ? {r_out, g_out, b_out} : 24'd0), + .hs_in(hs_fix), + .vs_in(vs_fix), + .de_in(de_emu), + .ce_in(ce_pix), + + .dout(vga_data_sl), + .hs_out(vga_hs_sl), + .vs_out(vga_vs_sl), + .de_out(vga_de_sl), + .ce_out(vga_ce_sl) +); + +wire [23:0] vga_data_osd; +wire vga_vs_osd, vga_hs_osd, vga_de_osd; +osd vga_osd +( + .clk_sys(clk_sys), + + .io_osd(io_osd_vga), + .io_strobe(io_strobe), + .io_din(io_din), + .osd_status(osd_status), + + .clk_video(clk_vid), + .din(vga_data_sl), + .hs_in(vga_hs_sl), + .vs_in(vga_vs_sl), + .de_in(vga_de_sl), + + .dout(vga_data_osd), + .hs_out(vga_hs_osd), + .vs_out(vga_vs_osd), + .de_out(vga_de_osd) +); + +wire vga_cs_osd; +csync csync_vga(clk_vid, vga_hs_osd, vga_vs_osd, vga_cs_osd); + +`ifndef MISTER_DISABLE_YC + reg pal_en; + reg yc_en; + reg cvbs; + reg [16:0] ColorBurst_Range; + wire [23:0] yc_o; + wire yc_hs, yc_vs, yc_cs, yc_de; + + yc_out yc_out + ( + .clk(clk_vid), + .PAL_EN(pal_en), + .CVBS(cvbs), + .PHASE_INC(PhaseInc), + .COLORBURST_RANGE(ColorBurst_Range), + .hsync(vga_hs_osd), + .vsync(vga_vs_osd), + .csync(vga_cs_osd), + .de(vga_de_osd), + .dout(yc_o), + .din(vga_data_osd), + .hsync_o(yc_hs), + .vsync_o(yc_vs), + .csync_o(yc_cs), + .de_o(yc_de) + ); +`endif + +reg [39:0] PhaseInc; + +`ifndef MISTER_DUAL_SDRAM + // Subcarrier generation for external encoders (independent of YC module) + reg subcarrier; + + reg [39:0] sub_accum; + always @(posedge clk_vid) sub_accum <= sub_accum + PhaseInc; + + // 1-bit output for positive/negative of wave, no LUT required. Output 1 if disabled for further logic + reg subcarrier_out; + always @(posedge clk_vid) subcarrier_out <= ~(subcarrier & csync_en & ~ypbpr_en & ~forced_scandoubler & ~vgas_en) | sub_accum[39]; + + + wire VGA_DISABLE; + wire [23:0] vgas_o; + wire vgas_hs, vgas_vs, vgas_cs, vgas_de; + `ifndef MISTER_DEBUG_NOHDMI + vga_out vga_scaler_out + ( + .clk(clk_hdmi), + .ypbpr_en(ypbpr_en), + .hsync(hdmi_hs_osd), + .vsync(hdmi_vs_osd), + .csync(hdmi_cs_osd), + .de(hdmi_de_osd), + .dout(vgas_o), + .din({24{hdmi_de_osd}} & hdmi_data_osd), + .hsync_o(vgas_hs), + .vsync_o(vgas_vs), + .csync_o(vgas_cs), + .de_o(vgas_de) + ); + `else + assign {vgas_o, vgas_hs, vgas_vs, vgas_cs, vgas_de} = 0; + `endif + + wire [23:0] vga_o, vga_o_t; + wire vga_hs, vga_vs, vga_cs, vga_de, vga_hs_t, vga_vs_t, vga_cs_t, vga_de_t; + vga_out vga_out + ( + .clk(clk_vid), + .ypbpr_en(ypbpr_en), + .hsync(vga_hs_osd), + .vsync(vga_vs_osd), + .csync(vga_cs_osd), + .de(vga_de_osd), + .dout(vga_o_t), + .din(vga_data_osd), + .hsync_o(vga_hs_t), + .vsync_o(vga_vs_t), + .csync_o(vga_cs_t), + .de_o(vga_de_t) + ); + + `ifndef MISTER_DISABLE_YC + assign {vga_o, vga_hs, vga_vs, vga_cs, vga_de } = ~yc_en ? {vga_o_t, vga_hs_t, vga_vs_t, vga_cs_t, vga_de_t } : {yc_o, yc_hs, yc_vs, yc_cs, yc_de }; + `else + assign {vga_o, vga_hs, vga_vs, vga_cs, vga_de } = {vga_o_t, vga_hs_t, vga_vs_t, vga_cs_t, vga_de_t } ; + `endif + + wire vgas_en = vga_fb | vga_scaler; + + wire cs1 = vgas_en ? vgas_cs : vga_cs; + wire de1 = vgas_en ? vgas_de : vga_de; + + assign VGA_VS = av_dis ? 1'bZ :(((vgas_en ? (~vgas_vs ^ VS[12]) : VGA_DISABLE ? 1'd1 : ~vga_vs) | csync_en) & subcarrier_out); + assign VGA_HS = av_dis ? 1'bZ : (vgas_en ? ((csync_en ? ~vgas_cs : ~vgas_hs) ^ HS[12]) : VGA_DISABLE ? 1'd1 : (csync_en ? ~vga_cs : ~vga_hs)); + assign VGA_R = av_dis ? 6'bZZZZZZ : vgas_en ? vgas_o[23:18] : VGA_DISABLE ? 6'd0 : vga_o[23:18]; + assign VGA_G = av_dis ? 6'bZZZZZZ : vgas_en ? vgas_o[15:10] : VGA_DISABLE ? 6'd0 : vga_o[15:10]; + assign VGA_B = av_dis ? 6'bZZZZZZ : vgas_en ? vgas_o[7:2] : VGA_DISABLE ? 6'd0 : vga_o[7:2] ; + + wire [1:0] vga_r = vgas_en ? vgas_o[17:16] : VGA_DISABLE ? 2'd0 : vga_o[17:16]; + wire [1:0] vga_g = vgas_en ? vgas_o[9:8] : VGA_DISABLE ? 2'd0 : vga_o[9:8]; + wire [1:0] vga_b = vgas_en ? vgas_o[1:0] : VGA_DISABLE ? 2'd0 : vga_o[1:0]; +`endif + +reg video_sync = 0; +always @(posedge clk_vid) begin + reg [11:0] line_cnt = 0; + reg [11:0] sync_line = 0; + reg [1:0] hs_cnt = 0; + reg old_hs; + + old_hs <= hs_fix; + if(~old_hs & hs_fix) begin + + video_sync <= (sync_line == line_cnt); + + line_cnt <= line_cnt + 1'd1; + if(~hs_cnt[1]) begin + hs_cnt <= hs_cnt + 1'd1; + if(hs_cnt[0]) begin + sync_line <= (line_cnt - vs_line); + line_cnt <= 0; + end + end + end + + if(de_emu) hs_cnt <= 0; +end + +///////////////////////// Audio output //////////////////////////////// + +assign SDCD_SPDIF = (mcp_en & ~spdif) ? 1'b0 : 1'bZ; + +`ifndef MISTER_DUAL_SDRAM + wire analog_l, analog_r; + + assign AUDIO_SPDIF = av_dis ? 1'bZ : (SW[0] | mcp_en) ? HDMI_LRCLK : spdif; + assign AUDIO_R = av_dis ? 1'bZ : (SW[0] | mcp_en) ? HDMI_I2S : analog_r; + assign AUDIO_L = av_dis ? 1'bZ : (SW[0] | mcp_en) ? HDMI_SCLK : analog_l; +`endif + +assign HDMI_MCLK = clk_audio; +wire clk_audio; + +pll_audio pll_audio +( + .refclk(FPGA_CLK3_50), + .rst(0), + .outclk_0(clk_audio) +); + +wire spdif; +audio_out audio_out +( + .reset(reset | areset), + .clk(clk_audio), + + .att(vol_att), + .boost(vol_boost), + .mix(audio_mix), + .sample_rate(audio_96k), + + .flt_rate(aflt_rate), + .cx(acx), + .cx0(acx0), + .cx1(acx1), + .cx2(acx2), + .cy0(acy0), + .cy1(acy1), + .cy2(acy2), + + .is_signed(audio_s), + .core_l(audio_l), + .core_r(audio_r), + +`ifndef MISTER_DISABLE_ALSA + .alsa_l(alsa_l), + .alsa_r(alsa_r), +`endif + + .i2s_bclk(HDMI_SCLK), + .i2s_lrclk(HDMI_LRCLK), + .i2s_data(HDMI_I2S), +`ifndef MISTER_DUAL_SDRAM + .dac_l(analog_l), + .dac_r(analog_r), +`endif + .spdif(spdif) +); + + +`ifndef MISTER_DISABLE_ALSA + wire aspi_sck,aspi_mosi,aspi_ss,aspi_miso; + cyclonev_hps_interface_peripheral_spi_master spi + ( + .sclk_out(aspi_sck), + .txd(aspi_mosi), // mosi + .rxd(aspi_miso), // miso + + .ss_0_n(aspi_ss), + .ss_in_n(1) + ); + + wire [28:0] alsa_address; + wire [63:0] alsa_readdata; + wire alsa_ready; + wire alsa_req; + wire alsa_late; + + wire [15:0] alsa_l, alsa_r; + + alsa alsa + ( + .reset(reset), + .clk(clk_audio), + + .ram_address(alsa_address), + .ram_data(alsa_readdata), + .ram_req(alsa_req), + .ram_ready(alsa_ready), + + .spi_ss(aspi_ss), + .spi_sck(aspi_sck), + .spi_mosi(aspi_mosi), + .spi_miso(aspi_miso), + + .pcm_l(alsa_l), + .pcm_r(alsa_r) + ); +`endif + +//////////////// User I/O (USB 3.0 connector) ///////////////////////// + +assign USER_IO[0] = !user_out[0] ? 1'b0 : 1'bZ; +assign USER_IO[1] = !user_out[1] ? 1'b0 : 1'bZ; +assign USER_IO[2] = !(SW[1] ? HDMI_I2S : user_out[2]) ? 1'b0 : 1'bZ; +assign USER_IO[3] = !user_out[3] ? 1'b0 : 1'bZ; +assign USER_IO[4] = !(SW[1] ? HDMI_SCLK : user_out[4]) ? 1'b0 : 1'bZ; +assign USER_IO[5] = !(SW[1] ? HDMI_LRCLK : user_out[5]) ? 1'b0 : 1'bZ; +assign USER_IO[6] = !user_out[6] ? 1'b0 : 1'bZ; + +assign user_in[0] = USER_IO[0]; +assign user_in[1] = USER_IO[1]; +assign user_in[2] = SW[1] | USER_IO[2]; +assign user_in[3] = USER_IO[3]; +assign user_in[4] = SW[1] | USER_IO[4]; +assign user_in[5] = SW[1] | USER_IO[5]; +assign user_in[6] = USER_IO[6]; + + +/////////////////// User module connection //////////////////////////// + +wire clk_sys; +wire [15:0] audio_l, audio_r; +wire audio_s; +wire [1:0] audio_mix; +wire [1:0] scanlines; +wire [7:0] r_out, g_out, b_out, hr_out, hg_out, hb_out; +wire vs_fix, hs_fix, de_emu, vs_emu, hs_emu, f1; +wire hvs_fix, hhs_fix, hde_emu; +wire clk_vid, ce_pix, clk_ihdmi, ce_hpix; +wire vga_force_scaler; + +wire ram_clk; +wire [28:0] ram_address; +wire [7:0] ram_burstcount; +wire ram_waitrequest; +wire [63:0] ram_readdata; +wire ram_readdatavalid; +wire ram_read; +wire [63:0] ram_writedata; +wire [7:0] ram_byteenable; +wire ram_write; + +wire led_user; +wire [1:0] led_power; +wire [1:0] led_disk; +wire [1:0] btn; + +sync_fix sync_v(clk_vid, vs_emu, vs_fix); +sync_fix sync_h(clk_vid, hs_emu, hs_fix); + +wire [6:0] user_out, user_in; + +assign clk_ihdmi= clk_vid; +assign ce_hpix = vga_ce_sl; +assign hr_out = vga_data_sl[23:16]; +assign hg_out = vga_data_sl[15:8]; +assign hb_out = vga_data_sl[7:0]; +assign hhs_fix = vga_hs_sl; +assign hvs_fix = vga_vs_sl; +assign hde_emu = vga_de_sl; + +wire uart_dtr; +wire uart_dsr; +wire uart_cts; +wire uart_rts; +wire uart_rxd; +wire uart_txd; + +wire osd_status; + +wire fb_en; +wire [4:0] fb_fmt; +wire [11:0] fb_width; +wire [11:0] fb_height; +wire [31:0] fb_base; +wire [13:0] fb_stride; + + +`ifdef MISTER_FB + `ifdef MISTER_FB_PALETTE + wire fb_pal_clk; + wire [7:0] fb_pal_a; + wire [23:0] fb_pal_d; + wire [23:0] fb_pal_q; + wire fb_pal_wr; + `endif + wire fb_force_blank; +`else + assign fb_en = 0; + assign fb_fmt = 0; + assign fb_width = 0; + assign fb_height = 0; + assign fb_base = 0; + assign fb_stride = 0; +`endif + +emu emu +( + .CLK_50M(FPGA_CLK2_50), + .RESET(reset), + .HPS_BUS({f1, HDMI_TX_VS, + clk_100m, clk_ihdmi, + ce_hpix, hde_emu, hhs_fix, hvs_fix, + io_wait, clk_sys, io_fpga, io_uio, io_strobe, io_wide, io_din, io_dout}), + + .VGA_R(r_out), + .VGA_G(g_out), + .VGA_B(b_out), + .VGA_HS(hs_emu), + .VGA_VS(vs_emu), + .VGA_DE(de_emu), + .VGA_F1(f1), + .VGA_SCALER(vga_force_scaler), + +`ifndef MISTER_DUAL_SDRAM + .VGA_DISABLE(VGA_DISABLE), +`endif + + .HDMI_WIDTH(direct_video ? 12'd0 : hdmi_width), + .HDMI_HEIGHT(direct_video ? 12'd0 : hdmi_height), + .HDMI_FREEZE(freeze), + .HDMI_BLACKOUT(hdmi_blackout), + .HDMI_BOB_DEINT(bob_deint), + + .CLK_VIDEO(clk_vid), + .CE_PIXEL(ce_pix), + .VGA_SL(scanlines), + .VIDEO_ARX(ARX), + .VIDEO_ARY(ARY), + +`ifdef MISTER_FB + .FB_EN(fb_en), + .FB_FORMAT(fb_fmt), + .FB_WIDTH(fb_width), + .FB_HEIGHT(fb_height), + .FB_BASE(fb_base), + .FB_STRIDE(fb_stride), + .FB_VBL(fb_vbl), + .FB_LL(lowlat), + .FB_FORCE_BLANK(fb_force_blank), + +`ifdef MISTER_FB_PALETTE + .FB_PAL_CLK (fb_pal_clk), + .FB_PAL_ADDR(fb_pal_a), + .FB_PAL_DOUT(fb_pal_d), + .FB_PAL_DIN (fb_pal_q), + .FB_PAL_WR (fb_pal_wr), +`endif + +`endif + + .LED_USER(led_user), + .LED_POWER(led_power), + .LED_DISK(led_disk), + + .CLK_AUDIO(clk_audio), + .AUDIO_L(audio_l), + .AUDIO_R(audio_r), + .AUDIO_S(audio_s), + .AUDIO_MIX(audio_mix), + + .ADC_BUS({ADC_SCK,ADC_SDO,ADC_SDI,ADC_CONVST}), + + .DDRAM_CLK(ram_clk), + .DDRAM_ADDR(ram_address), + .DDRAM_BURSTCNT(ram_burstcount), + .DDRAM_BUSY(ram_waitrequest), + .DDRAM_DOUT(ram_readdata), + .DDRAM_DOUT_READY(ram_readdatavalid), + .DDRAM_RD(ram_read), + .DDRAM_DIN(ram_writedata), + .DDRAM_BE(ram_byteenable), + .DDRAM_WE(ram_write), + + .SDRAM_DQ(SDRAM_DQ), + .SDRAM_A(SDRAM_A), + .SDRAM_DQML(SDRAM_DQML), + .SDRAM_DQMH(SDRAM_DQMH), + .SDRAM_BA(SDRAM_BA), + .SDRAM_nCS(SDRAM_nCS), + .SDRAM_nWE(SDRAM_nWE), + .SDRAM_nRAS(SDRAM_nRAS), + .SDRAM_nCAS(SDRAM_nCAS), + .SDRAM_CLK(SDRAM_CLK), + .SDRAM_CKE(SDRAM_CKE), + +`ifdef MISTER_DUAL_SDRAM + .SDRAM2_DQ(SDRAM2_DQ), + .SDRAM2_A(SDRAM2_A), + .SDRAM2_BA(SDRAM2_BA), + .SDRAM2_nCS(SDRAM2_nCS), + .SDRAM2_nWE(SDRAM2_nWE), + .SDRAM2_nRAS(SDRAM2_nRAS), + .SDRAM2_nCAS(SDRAM2_nCAS), + .SDRAM2_CLK(SDRAM2_CLK), + .SDRAM2_EN(io_dig), +`endif + + .BUTTONS(btn), + .OSD_STATUS(osd_status), + + .SD_SCK(SD_CLK), + .SD_MOSI(SD_MOSI), + .SD_MISO(SD_MISO), + .SD_CS(SD_CS), + .SD_CD(SD_CD), + + .UART_CTS(uart_rts), + .UART_RTS(uart_cts), + .UART_RXD(uart_txd), + .UART_TXD(uart_rxd), + .UART_DTR(uart_dsr), + .UART_DSR(uart_dtr), + + .USER_OUT(user_out), + .USER_IN(user_in) +); + +endmodule + +///////////////////////////////////////////////////////////////////// + +module sync_fix +( + input clk, + + input sync_in, + output sync_out +); + +assign sync_out = sync_in ^ pol; + +reg pol; +always @(posedge clk) begin + reg [31:0] cnt; + reg s1,s2; + + s1 <= sync_in; + s2 <= s1; + cnt <= s2 ? (cnt - 1) : (cnt + 1); + + if(~s2 & s1) begin + cnt <= 0; + pol <= cnt[31]; + end +end + +endmodule + +///////////////////////////////////////////////////////////////////// + +// CSync generation +// Shifts HSync left by 1 HSync period during VSync + +module csync +( + input clk, + input hsync, + input vsync, + + output csync +); + +assign csync = (csync_vs ^ csync_hs); + +reg csync_hs, csync_vs; +always @(posedge clk) begin + reg prev_hs; + reg [15:0] h_cnt, line_len, hs_len; + + // Count line/Hsync length + h_cnt <= h_cnt + 1'd1; + + prev_hs <= hsync; + if (prev_hs ^ hsync) begin + h_cnt <= 0; + if (hsync) begin + line_len <= h_cnt - hs_len; + csync_hs <= 0; + end + else hs_len <= h_cnt; + end + + if (~vsync) csync_hs <= hsync; + else if(h_cnt == line_len) csync_hs <= 1; + + csync_vs <= vsync; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/sysmem.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/sysmem.sv new file mode 100644 index 0000000000000000000000000000000000000000..8c17e868502c1768cff70f48aebe427ba88e0527 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/sysmem.sv @@ -0,0 +1,570 @@ +`timescale 1 ps / 1 ps +module sysmem_lite +( + output clock, + output reset_out, + + input reset_hps_cold_req, + input reset_hps_warm_req, + input reset_core_req, + + input ram1_clk, + input [28:0] ram1_address, + input [7:0] ram1_burstcount, + output ram1_waitrequest, + output [63:0] ram1_readdata, + output ram1_readdatavalid, + input ram1_read, + input [63:0] ram1_writedata, + input [7:0] ram1_byteenable, + input ram1_write, + + input ram2_clk, + input [28:0] ram2_address, + input [7:0] ram2_burstcount, + output ram2_waitrequest, + output [63:0] ram2_readdata, + output ram2_readdatavalid, + input ram2_read, + input [63:0] ram2_writedata, + input [7:0] ram2_byteenable, + input ram2_write, + + input vbuf_clk, + input [27:0] vbuf_address, + input [7:0] vbuf_burstcount, + output vbuf_waitrequest, + output [127:0] vbuf_readdata, + output vbuf_readdatavalid, + input vbuf_read, + input [127:0] vbuf_writedata, + input [15:0] vbuf_byteenable, + input vbuf_write +); + +assign reset_out = ~init_reset_n | ~hps_h2f_reset_n | reset_core_req; + +//////////////////////////////////////////////////////// +//// f2sdram_safe_terminator_ram1 //// +//////////////////////////////////////////////////////// +wire [28:0] f2h_ram1_address; +wire [7:0] f2h_ram1_burstcount; +wire f2h_ram1_waitrequest; +wire [63:0] f2h_ram1_readdata; +wire f2h_ram1_readdatavalid; +wire f2h_ram1_read; +wire [63:0] f2h_ram1_writedata; +wire [7:0] f2h_ram1_byteenable; +wire f2h_ram1_write; + +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg ram1_reset_0 = 1'b1; +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg ram1_reset_1 = 1'b1; +always @(posedge ram1_clk) begin + ram1_reset_0 <= reset_out; + ram1_reset_1 <= ram1_reset_0; +end + +f2sdram_safe_terminator #(64, 8) f2sdram_safe_terminator_ram1 +( + .clk (ram1_clk), + .rst_req_sync (ram1_reset_1), + + .waitrequest_slave (ram1_waitrequest), + .burstcount_slave (ram1_burstcount), + .address_slave (ram1_address), + .readdata_slave (ram1_readdata), + .readdatavalid_slave (ram1_readdatavalid), + .read_slave (ram1_read), + .writedata_slave (ram1_writedata), + .byteenable_slave (ram1_byteenable), + .write_slave (ram1_write), + + .waitrequest_master (f2h_ram1_waitrequest), + .burstcount_master (f2h_ram1_burstcount), + .address_master (f2h_ram1_address), + .readdata_master (f2h_ram1_readdata), + .readdatavalid_master (f2h_ram1_readdatavalid), + .read_master (f2h_ram1_read), + .writedata_master (f2h_ram1_writedata), + .byteenable_master (f2h_ram1_byteenable), + .write_master (f2h_ram1_write) +); + +//////////////////////////////////////////////////////// +//// f2sdram_safe_terminator_ram2 //// +//////////////////////////////////////////////////////// +wire [28:0] f2h_ram2_address; +wire [7:0] f2h_ram2_burstcount; +wire f2h_ram2_waitrequest; +wire [63:0] f2h_ram2_readdata; +wire f2h_ram2_readdatavalid; +wire f2h_ram2_read; +wire [63:0] f2h_ram2_writedata; +wire [7:0] f2h_ram2_byteenable; +wire f2h_ram2_write; + +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg ram2_reset_0 = 1'b1; +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg ram2_reset_1 = 1'b1; +always @(posedge ram2_clk) begin + ram2_reset_0 <= reset_out; + ram2_reset_1 <= ram2_reset_0; +end + +f2sdram_safe_terminator #(64, 8) f2sdram_safe_terminator_ram2 +( + .clk (ram2_clk), + .rst_req_sync (ram2_reset_1), + + .waitrequest_slave (ram2_waitrequest), + .burstcount_slave (ram2_burstcount), + .address_slave (ram2_address), + .readdata_slave (ram2_readdata), + .readdatavalid_slave (ram2_readdatavalid), + .read_slave (ram2_read), + .writedata_slave (ram2_writedata), + .byteenable_slave (ram2_byteenable), + .write_slave (ram2_write), + + .waitrequest_master (f2h_ram2_waitrequest), + .burstcount_master (f2h_ram2_burstcount), + .address_master (f2h_ram2_address), + .readdata_master (f2h_ram2_readdata), + .readdatavalid_master (f2h_ram2_readdatavalid), + .read_master (f2h_ram2_read), + .writedata_master (f2h_ram2_writedata), + .byteenable_master (f2h_ram2_byteenable), + .write_master (f2h_ram2_write) +); + +//////////////////////////////////////////////////////// +//// f2sdram_safe_terminator_vbuf //// +//////////////////////////////////////////////////////// +wire [27:0] f2h_vbuf_address; +wire [7:0] f2h_vbuf_burstcount; +wire f2h_vbuf_waitrequest; +wire [127:0] f2h_vbuf_readdata; +wire f2h_vbuf_readdatavalid; +wire f2h_vbuf_read; +wire [127:0] f2h_vbuf_writedata; +wire [15:0] f2h_vbuf_byteenable; +wire f2h_vbuf_write; + +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg vbuf_reset_0 = 1'b1; +(* altera_attribute = {"-name SYNCHRONIZER_IDENTIFICATION FORCED_IF_ASYNCHRONOUS"} *) reg vbuf_reset_1 = 1'b1; +always @(posedge vbuf_clk) begin + vbuf_reset_0 <= reset_out; + vbuf_reset_1 <= vbuf_reset_0; +end + +f2sdram_safe_terminator #(128, 8) f2sdram_safe_terminator_vbuf +( + .clk (vbuf_clk), + .rst_req_sync (vbuf_reset_1), + + .waitrequest_slave (vbuf_waitrequest), + .burstcount_slave (vbuf_burstcount), + .address_slave (vbuf_address), + .readdata_slave (vbuf_readdata), + .readdatavalid_slave (vbuf_readdatavalid), + .read_slave (vbuf_read), + .writedata_slave (vbuf_writedata), + .byteenable_slave (vbuf_byteenable), + .write_slave (vbuf_write), + + .waitrequest_master (f2h_vbuf_waitrequest), + .burstcount_master (f2h_vbuf_burstcount), + .address_master (f2h_vbuf_address), + .readdata_master (f2h_vbuf_readdata), + .readdatavalid_master (f2h_vbuf_readdatavalid), + .read_master (f2h_vbuf_read), + .writedata_master (f2h_vbuf_writedata), + .byteenable_master (f2h_vbuf_byteenable), + .write_master (f2h_vbuf_write) +); + +//////////////////////////////////////////////////////// +//// HPS <> FPGA interfaces //// +//////////////////////////////////////////////////////// +sysmem_HPS_fpga_interfaces fpga_interfaces ( + .f2h_cold_rst_req_n (~reset_hps_cold_req), + .f2h_warm_rst_req_n (~reset_hps_warm_req), + .h2f_user0_clk (clock), + .h2f_rst_n (hps_h2f_reset_n), + .f2h_sdram0_clk (vbuf_clk), + .f2h_sdram0_ADDRESS (f2h_vbuf_address), + .f2h_sdram0_BURSTCOUNT (f2h_vbuf_burstcount), + .f2h_sdram0_WAITREQUEST (f2h_vbuf_waitrequest), + .f2h_sdram0_READDATA (f2h_vbuf_readdata), + .f2h_sdram0_READDATAVALID (f2h_vbuf_readdatavalid), + .f2h_sdram0_READ (f2h_vbuf_read), + .f2h_sdram0_WRITEDATA (f2h_vbuf_writedata), + .f2h_sdram0_BYTEENABLE (f2h_vbuf_byteenable), + .f2h_sdram0_WRITE (f2h_vbuf_write), + .f2h_sdram1_clk (ram1_clk), + .f2h_sdram1_ADDRESS (f2h_ram1_address), + .f2h_sdram1_BURSTCOUNT (f2h_ram1_burstcount), + .f2h_sdram1_WAITREQUEST (f2h_ram1_waitrequest), + .f2h_sdram1_READDATA (f2h_ram1_readdata), + .f2h_sdram1_READDATAVALID (f2h_ram1_readdatavalid), + .f2h_sdram1_READ (f2h_ram1_read), + .f2h_sdram1_WRITEDATA (f2h_ram1_writedata), + .f2h_sdram1_BYTEENABLE (f2h_ram1_byteenable), + .f2h_sdram1_WRITE (f2h_ram1_write), + .f2h_sdram2_clk (ram2_clk), + .f2h_sdram2_ADDRESS (f2h_ram2_address), + .f2h_sdram2_BURSTCOUNT (f2h_ram2_burstcount), + .f2h_sdram2_WAITREQUEST (f2h_ram2_waitrequest), + .f2h_sdram2_READDATA (f2h_ram2_readdata), + .f2h_sdram2_READDATAVALID (f2h_ram2_readdatavalid), + .f2h_sdram2_READ (f2h_ram2_read), + .f2h_sdram2_WRITEDATA (f2h_ram2_writedata), + .f2h_sdram2_BYTEENABLE (f2h_ram2_byteenable), + .f2h_sdram2_WRITE (f2h_ram2_write) +); + +wire hps_h2f_reset_n; + +reg init_reset_n = 0; +always @(posedge clock) begin + integer timeout = 0; + + if(timeout < 2000000) begin + init_reset_n <= 0; + timeout <= timeout + 1; + end + else init_reset_n <= 1; +end + +endmodule + + +module sysmem_HPS_fpga_interfaces +( + // h2f_reset + output wire [1 - 1 : 0 ] h2f_rst_n + + // f2h_cold_reset_req + ,input wire [1 - 1 : 0 ] f2h_cold_rst_req_n + + // f2h_warm_reset_req + ,input wire [1 - 1 : 0 ] f2h_warm_rst_req_n + + // h2f_user0_clock + ,output wire [1 - 1 : 0 ] h2f_user0_clk + + // f2h_sdram0_data + ,input wire [28 - 1 : 0 ] f2h_sdram0_ADDRESS + ,input wire [8 - 1 : 0 ] f2h_sdram0_BURSTCOUNT + ,output wire [1 - 1 : 0 ] f2h_sdram0_WAITREQUEST + ,output wire [128 - 1 : 0 ] f2h_sdram0_READDATA + ,output wire [1 - 1 : 0 ] f2h_sdram0_READDATAVALID + ,input wire [1 - 1 : 0 ] f2h_sdram0_READ + ,input wire [128 - 1 : 0 ] f2h_sdram0_WRITEDATA + ,input wire [16 - 1 : 0 ] f2h_sdram0_BYTEENABLE + ,input wire [1 - 1 : 0 ] f2h_sdram0_WRITE + + // f2h_sdram0_clock + ,input wire [1 - 1 : 0 ] f2h_sdram0_clk + + // f2h_sdram1_data + ,input wire [29 - 1 : 0 ] f2h_sdram1_ADDRESS + ,input wire [8 - 1 : 0 ] f2h_sdram1_BURSTCOUNT + ,output wire [1 - 1 : 0 ] f2h_sdram1_WAITREQUEST + ,output wire [64 - 1 : 0 ] f2h_sdram1_READDATA + ,output wire [1 - 1 : 0 ] f2h_sdram1_READDATAVALID + ,input wire [1 - 1 : 0 ] f2h_sdram1_READ + ,input wire [64 - 1 : 0 ] f2h_sdram1_WRITEDATA + ,input wire [8 - 1 : 0 ] f2h_sdram1_BYTEENABLE + ,input wire [1 - 1 : 0 ] f2h_sdram1_WRITE + + // f2h_sdram1_clock + ,input wire [1 - 1 : 0 ] f2h_sdram1_clk + + // f2h_sdram2_data + ,input wire [29 - 1 : 0 ] f2h_sdram2_ADDRESS + ,input wire [8 - 1 : 0 ] f2h_sdram2_BURSTCOUNT + ,output wire [1 - 1 : 0 ] f2h_sdram2_WAITREQUEST + ,output wire [64 - 1 : 0 ] f2h_sdram2_READDATA + ,output wire [1 - 1 : 0 ] f2h_sdram2_READDATAVALID + ,input wire [1 - 1 : 0 ] f2h_sdram2_READ + ,input wire [64 - 1 : 0 ] f2h_sdram2_WRITEDATA + ,input wire [8 - 1 : 0 ] f2h_sdram2_BYTEENABLE + ,input wire [1 - 1 : 0 ] f2h_sdram2_WRITE + + // f2h_sdram2_clock + ,input wire [1 - 1 : 0 ] f2h_sdram2_clk +); + + +wire [29 - 1 : 0] intermediate; +assign intermediate[0:0] = ~intermediate[1:1]; +assign intermediate[8:8] = intermediate[4:4]|intermediate[7:7]; +assign intermediate[2:2] = intermediate[9:9]; +assign intermediate[3:3] = intermediate[9:9]; +assign intermediate[5:5] = intermediate[9:9]; +assign intermediate[6:6] = intermediate[9:9]; +assign intermediate[10:10] = intermediate[9:9]; +assign intermediate[11:11] = ~intermediate[12:12]; +assign intermediate[17:17] = intermediate[14:14]|intermediate[16:16]; +assign intermediate[13:13] = intermediate[18:18]; +assign intermediate[15:15] = intermediate[18:18]; +assign intermediate[19:19] = intermediate[18:18]; +assign intermediate[20:20] = ~intermediate[21:21]; +assign intermediate[26:26] = intermediate[23:23]|intermediate[25:25]; +assign intermediate[22:22] = intermediate[27:27]; +assign intermediate[24:24] = intermediate[27:27]; +assign intermediate[28:28] = intermediate[27:27]; +assign f2h_sdram0_WAITREQUEST[0:0] = intermediate[0:0]; +assign f2h_sdram1_WAITREQUEST[0:0] = intermediate[11:11]; +assign f2h_sdram2_WAITREQUEST[0:0] = intermediate[20:20]; +assign intermediate[4:4] = f2h_sdram0_READ[0:0]; +assign intermediate[7:7] = f2h_sdram0_WRITE[0:0]; +assign intermediate[9:9] = f2h_sdram0_clk[0:0]; +assign intermediate[14:14] = f2h_sdram1_READ[0:0]; +assign intermediate[16:16] = f2h_sdram1_WRITE[0:0]; +assign intermediate[18:18] = f2h_sdram1_clk[0:0]; +assign intermediate[23:23] = f2h_sdram2_READ[0:0]; +assign intermediate[25:25] = f2h_sdram2_WRITE[0:0]; +assign intermediate[27:27] = f2h_sdram2_clk[0:0]; + +cyclonev_hps_interface_clocks_resets clocks_resets( + .f2h_warm_rst_req_n({ + f2h_warm_rst_req_n[0:0] // 0:0 + }) +,.f2h_pending_rst_ack({ + 1'b1 // 0:0 + }) +,.f2h_dbg_rst_req_n({ + 1'b1 // 0:0 + }) +,.h2f_rst_n({ + h2f_rst_n[0:0] // 0:0 + }) +,.f2h_cold_rst_req_n({ + f2h_cold_rst_req_n[0:0] // 0:0 + }) +,.h2f_user0_clk({ + h2f_user0_clk[0:0] // 0:0 + }) +); + + +cyclonev_hps_interface_dbg_apb debug_apb( + .DBG_APB_DISABLE({ + 1'b0 // 0:0 + }) +,.P_CLK_EN({ + 1'b0 // 0:0 + }) +); + + +cyclonev_hps_interface_tpiu_trace tpiu( + .traceclk_ctl({ + 1'b1 // 0:0 + }) +); + + +cyclonev_hps_interface_boot_from_fpga boot_from_fpga( + .boot_from_fpga_ready({ + 1'b0 // 0:0 + }) +,.boot_from_fpga_on_failure({ + 1'b0 // 0:0 + }) +,.bsel_en({ + 1'b0 // 0:0 + }) +,.csel_en({ + 1'b0 // 0:0 + }) +,.csel({ + 2'b01 // 1:0 + }) +,.bsel({ + 3'b001 // 2:0 + }) +); + + +cyclonev_hps_interface_fpga2hps fpga2hps( + .port_size_config({ + 2'b11 // 1:0 + }) +); + + +cyclonev_hps_interface_hps2fpga hps2fpga( + .port_size_config({ + 2'b11 // 1:0 + }) +); + + +cyclonev_hps_interface_fpga2sdram f2sdram( + .cfg_rfifo_cport_map({ + 16'b0010000100000000 // 15:0 + }) +,.cfg_wfifo_cport_map({ + 16'b0010000100000000 // 15:0 + }) +,.rd_ready_3({ + 1'b1 // 0:0 + }) +,.cmd_port_clk_2({ + intermediate[28:28] // 0:0 + }) +,.rd_ready_2({ + 1'b1 // 0:0 + }) +,.cmd_port_clk_1({ + intermediate[19:19] // 0:0 + }) +,.rd_ready_1({ + 1'b1 // 0:0 + }) +,.cmd_port_clk_0({ + intermediate[10:10] // 0:0 + }) +,.rd_ready_0({ + 1'b1 // 0:0 + }) +,.wrack_ready_2({ + 1'b1 // 0:0 + }) +,.wrack_ready_1({ + 1'b1 // 0:0 + }) +,.wrack_ready_0({ + 1'b1 // 0:0 + }) +,.cmd_ready_2({ + intermediate[21:21] // 0:0 + }) +,.cmd_ready_1({ + intermediate[12:12] // 0:0 + }) +,.cmd_ready_0({ + intermediate[1:1] // 0:0 + }) +,.cfg_port_width({ + 12'b000000010110 // 11:0 + }) +,.rd_valid_3({ + f2h_sdram2_READDATAVALID[0:0] // 0:0 + }) +,.rd_valid_2({ + f2h_sdram1_READDATAVALID[0:0] // 0:0 + }) +,.rd_valid_1({ + f2h_sdram0_READDATAVALID[0:0] // 0:0 + }) +,.rd_clk_3({ + intermediate[22:22] // 0:0 + }) +,.rd_data_3({ + f2h_sdram2_READDATA[63:0] // 63:0 + }) +,.rd_clk_2({ + intermediate[13:13] // 0:0 + }) +,.rd_data_2({ + f2h_sdram1_READDATA[63:0] // 63:0 + }) +,.rd_clk_1({ + intermediate[3:3] // 0:0 + }) +,.rd_data_1({ + f2h_sdram0_READDATA[127:64] // 63:0 + }) +,.rd_clk_0({ + intermediate[2:2] // 0:0 + }) +,.rd_data_0({ + f2h_sdram0_READDATA[63:0] // 63:0 + }) +,.cfg_axi_mm_select({ + 6'b000000 // 5:0 + }) +,.cmd_valid_2({ + intermediate[26:26] // 0:0 + }) +,.cmd_valid_1({ + intermediate[17:17] // 0:0 + }) +,.cmd_valid_0({ + intermediate[8:8] // 0:0 + }) +,.cfg_cport_rfifo_map({ + 18'b000000000011010000 // 17:0 + }) +,.wr_data_3({ + 2'b00 // 89:88 + ,f2h_sdram2_BYTEENABLE[7:0] // 87:80 + ,16'b0000000000000000 // 79:64 + ,f2h_sdram2_WRITEDATA[63:0] // 63:0 + }) +,.wr_data_2({ + 2'b00 // 89:88 + ,f2h_sdram1_BYTEENABLE[7:0] // 87:80 + ,16'b0000000000000000 // 79:64 + ,f2h_sdram1_WRITEDATA[63:0] // 63:0 + }) +,.wr_data_1({ + 2'b00 // 89:88 + ,f2h_sdram0_BYTEENABLE[15:8] // 87:80 + ,16'b0000000000000000 // 79:64 + ,f2h_sdram0_WRITEDATA[127:64] // 63:0 + }) +,.cfg_cport_type({ + 12'b000000111111 // 11:0 + }) +,.wr_data_0({ + 2'b00 // 89:88 + ,f2h_sdram0_BYTEENABLE[7:0] // 87:80 + ,16'b0000000000000000 // 79:64 + ,f2h_sdram0_WRITEDATA[63:0] // 63:0 + }) +,.cfg_cport_wfifo_map({ + 18'b000000000011010000 // 17:0 + }) +,.wr_clk_3({ + intermediate[24:24] // 0:0 + }) +,.wr_clk_2({ + intermediate[15:15] // 0:0 + }) +,.wr_clk_1({ + intermediate[6:6] // 0:0 + }) +,.wr_clk_0({ + intermediate[5:5] // 0:0 + }) +,.cmd_data_2({ + 18'b000000000000000000 // 59:42 + ,f2h_sdram2_BURSTCOUNT[7:0] // 41:34 + ,3'b000 // 33:31 + ,f2h_sdram2_ADDRESS[28:0] // 30:2 + ,intermediate[25:25] // 1:1 + ,intermediate[23:23] // 0:0 + }) +,.cmd_data_1({ + 18'b000000000000000000 // 59:42 + ,f2h_sdram1_BURSTCOUNT[7:0] // 41:34 + ,3'b000 // 33:31 + ,f2h_sdram1_ADDRESS[28:0] // 30:2 + ,intermediate[16:16] // 1:1 + ,intermediate[14:14] // 0:0 + }) +,.cmd_data_0({ + 18'b000000000000000000 // 59:42 + ,f2h_sdram0_BURSTCOUNT[7:0] // 41:34 + ,4'b0000 // 33:30 + ,f2h_sdram0_ADDRESS[27:0] // 29:2 + ,intermediate[7:7] // 1:1 + ,intermediate[4:4] // 0:0 + }) +); + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/vga_out.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/vga_out.sv new file mode 100644 index 0000000000000000000000000000000000000000..41606354e37c98111138446aa13c7870244db89d --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/vga_out.sv @@ -0,0 +1,73 @@ + +module vga_out +( + input clk, + input ypbpr_en, + + input hsync, + input vsync, + input csync, + input de, + + input [23:0] din, + output [23:0] dout, + + output reg hsync_o, + output reg vsync_o, + output reg csync_o, + output reg de_o +); + +wire [7:0] red = din[23:16]; +wire [7:0] green = din[15:8]; +wire [7:0] blue = din[7:0]; + +// http://marsee101.blog19.fc2.com/blog-entry-2311.html + + +// Y = 0.301*R + 0.586*G + 0.113*B (Y = 0.299*R + 0.587*G + 0.114*B) +// Pb = 128 - 0.168*R - 0.332*G + 0.500*B (Pb = -0.169*R - 0.331*G + 0.500*B) +// Pr = 128 + 0.500*R - 0.418*G - 0.082*B (Pr = 0.500*R - 0.419*G - 0.081*B) + +reg [7:0] y, pb, pr; +reg [23:0] rgb; +always @(posedge clk) begin + reg [18:0] y_1r, pb_1r, pr_1r; + reg [18:0] y_1g, pb_1g, pr_1g; + reg [18:0] y_1b, pb_1b, pr_1b; + reg [18:0] y_2, pb_2, pr_2; + reg [23:0] din1, din2; + reg hsync2, vsync2, csync2, de2; + reg hsync1, vsync1, csync1, de1; + + y_1r <= {red, 6'd0} + {red, 3'd0} + {red, 2'd0} + red; + pb_1r <= 19'd32768 - ({red, 5'd0} + {red, 3'd0} + {red, 1'd0}); + pr_1r <= 19'd32768 + {red, 7'd0}; + + y_1g <= {green, 7'd0} + {green, 4'd0} + {green, 2'd0} + {green, 1'd0}; + pb_1g <= {green, 6'd0} + {green, 4'd0} + {green, 2'd0} + green; + pr_1g <= {green, 6'd0} + {green, 5'd0} + {green, 3'd0} + {green, 1'd0}; + + y_1b <= {blue, 4'd0} + {blue, 3'd0} + {blue, 2'd0} + blue; + pb_1b <= {blue, 7'd0}; + pr_1b <= {blue, 4'd0} + {blue, 2'd0} + blue; + + y_2 <= y_1r + y_1g + y_1b; + pb_2 <= pb_1r - pb_1g + pb_1b; + pr_2 <= pr_1r - pr_1g - pr_1b; + + y <= y_2[18] ? 8'd0 : y_2[16] ? 8'd255 : y_2[15:8]; + pb <= pb_2[18] ? 8'd0 : pb_2[16] ? 8'd255 : pb_2[15:8]; + pr <= pr_2[18] ? 8'd0 : pr_2[16] ? 8'd255 : pr_2[15:8]; + + hsync_o <= hsync2; hsync2 <= hsync1; hsync1 <= hsync; + vsync_o <= vsync2; vsync2 <= vsync1; vsync1 <= vsync; + csync_o <= csync2; csync2 <= csync1; csync1 <= csync; + de_o <= de2; de2 <= de1; de1 <= de; + + rgb <= din2; din2 <= din1; din1 <= din; +end + +assign dout = ypbpr_en ? {pr, y, pb} : rgb; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/video_cleaner.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/video_cleaner.sv new file mode 100644 index 0000000000000000000000000000000000000000..4c057a834197df0bbf6dfda4ecf94efbaea9eb64 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/video_cleaner.sv @@ -0,0 +1,108 @@ +// +// +// Copyright (c) 2018 Sorgelig +// +// This program is GPL Licensed. See COPYING for the full license. +// +// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +`timescale 1ns / 1ps + +module video_cleaner +( + input clk_vid, + input ce_pix, + + input [7:0] R, + input [7:0] G, + input [7:0] B, + + input HSync, + input VSync, + input HBlank, + input VBlank, + + //optional de + input DE_in, + + //optional interlace support + input interlace, + input f1, + + // video output signals + output reg [7:0] VGA_R, + output reg [7:0] VGA_G, + output reg [7:0] VGA_B, + output reg VGA_VS, + output reg VGA_HS, + output VGA_DE, + + // optional aligned blank + output reg HBlank_out, + output reg VBlank_out, + + // optional aligned de + output reg DE_out +); + +wire hs, vs; +s_fix sync_v(clk_vid, HSync, hs); +s_fix sync_h(clk_vid, VSync, vs); + +wire hbl = hs | HBlank; +wire vbl = vs | VBlank; + +assign VGA_DE = ~(HBlank_out | VBlank_out); + +always @(posedge clk_vid) begin + if(ce_pix) begin + HBlank_out <= hbl; + + VGA_HS <= hs; + + VGA_R <= R; + VGA_G <= G; + VGA_B <= B; + DE_out <= DE_in; + + if (interlace & f1) begin + VGA_VS <= vs; + VBlank_out <= vbl; + end else begin + if(~VGA_HS & hs) VGA_VS <= vs; + if(HBlank_out & ~hbl) VBlank_out <= vbl; + end + end +end + +endmodule + +module s_fix +( + input clk, + + input sync_in, + output sync_out +); + +assign sync_out = sync_in ^ pol; + +reg pol; +always @(posedge clk) begin + integer pos = 0, neg = 0, cnt = 0; + reg s1,s2; + + s1 <= sync_in; + s2 <= s1; + + if(~s2 & s1) neg <= cnt; + if(s2 & ~s1) pos <= cnt; + + cnt <= cnt + 1; + if(s2 != s1) cnt <= 0; + + pol <= pos > neg; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/video_freak.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/video_freak.sv new file mode 100644 index 0000000000000000000000000000000000000000..65375cd278940c6d6560f6d777d3c0352ab106be --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/video_freak.sv @@ -0,0 +1,329 @@ +// +// +// Video crop +// Copyright (c) 2020 Grabulosaure, (c) 2021 Alexey Melnikov +// +// Integer scaling +// Copyright (c) 2021 Alexey Melnikov +// +// This program is GPL Licensed. See COPYING for the full license. +// +// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +`timescale 1ns / 1ps + +module video_freak +( + input CLK_VIDEO, + input CE_PIXEL, + input VGA_VS, + input [11:0] HDMI_WIDTH, + input [11:0] HDMI_HEIGHT, + output VGA_DE, + output reg [12:0] VIDEO_ARX, + output reg [12:0] VIDEO_ARY, + + input VGA_DE_IN, + input [11:0] ARX, + input [11:0] ARY, + input [11:0] CROP_SIZE, + input [4:0] CROP_OFF, // -16...+15 + input [2:0] SCALE //0 - normal, 1 - V-integer, 2 - HV-Integer-, 3 - HV-Integer+, 4 - HV-Integer +); + +reg mul_start; +wire mul_run; +reg [11:0] mul_arg1, mul_arg2; +wire [23:0] mul_res; +sys_umul #(12,12) mul(CLK_VIDEO,mul_start,mul_run, mul_arg1,mul_arg2,mul_res); + +reg vde; +reg [11:0] arxo,aryo; +reg [11:0] vsize; +reg [11:0] hsize; + +always @(posedge CLK_VIDEO) begin + reg old_de, old_vs,ovde; + reg [11:0] vtot,vcpt,vcrop,voff; + reg [11:0] hcpt; + reg [11:0] vadj; + reg [23:0] ARXG,ARYG; + reg [11:0] arx,ary; + reg [1:0] vcalc; + + if (CE_PIXEL) begin + old_de <= VGA_DE_IN; + old_vs <= VGA_VS; + if (VGA_VS & ~old_vs) begin + vcpt <= 0; + vtot <= vcpt; + vcalc <= 1; + vcrop <= (CROP_SIZE >= vcpt) ? 12'd0 : CROP_SIZE; + end + + if (VGA_DE_IN) hcpt <= hcpt + 1'd1; + if (~VGA_DE_IN & old_de) begin + vcpt <= vcpt + 1'd1; + if(!vcpt) hsize <= hcpt; + hcpt <= 0; + end + end + + arx <= ARX; + ary <= ARY; + + vsize <= vcrop ? vcrop : vtot; + + mul_start <= 0; + + if(!vcrop || !ary || !arx) begin + arxo <= arx; + aryo <= ary; + end + else if (vcalc) begin + if(~mul_start & ~mul_run) begin + vcalc <= vcalc + 1'd1; + case(vcalc) + 1: begin + mul_arg1 <= arx; + mul_arg2 <= vtot; + mul_start <= 1; + end + + 2: begin + ARXG <= mul_res; + mul_arg1 <= ary; + mul_arg2 <= vcrop; + mul_start <= 1; + end + + 3: begin + ARYG <= mul_res; + end + endcase + end + end + else if (ARXG[23] | ARYG[23]) begin + arxo <= ARXG[23:12]; + aryo <= ARYG[23:12]; + end + else begin + ARXG <= ARXG << 1; + ARYG <= ARYG << 1; + end + + vadj <= (vtot-vcrop) + {{6{CROP_OFF[4]}},CROP_OFF,1'b0}; + voff <= vadj[11] ? 12'd0 : ((vadj[11:1] + vcrop) > vtot) ? vtot-vcrop : vadj[11:1]; + ovde <= ((vcpt >= voff) && (vcpt < (vcrop + voff))) || !vcrop; + vde <= ovde; +end + +assign VGA_DE = vde & VGA_DE_IN; + +video_scale_int scale +( + .CLK_VIDEO(CLK_VIDEO), + .HDMI_WIDTH(HDMI_WIDTH), + .HDMI_HEIGHT(HDMI_HEIGHT), + .SCALE(SCALE), + .hsize(hsize), + .vsize(vsize), + .arx_i(arxo), + .ary_i(aryo), + .arx_o(VIDEO_ARX), + .ary_o(VIDEO_ARY) +); + +endmodule + + +module video_scale_int +( + input CLK_VIDEO, + + input [11:0] HDMI_WIDTH, + input [11:0] HDMI_HEIGHT, + + input [2:0] SCALE, + + input [11:0] hsize, + input [11:0] vsize, + + input [11:0] arx_i, + input [11:0] ary_i, + + output reg [12:0] arx_o, + output reg [12:0] ary_o +); + +reg div_start; +wire div_run; +reg [23:0] div_num; +reg [11:0] div_den; +wire [23:0] div_res; +sys_udiv #(24,12) div(CLK_VIDEO,div_start,div_run, div_num,div_den,div_res); + +reg mul_start; +wire mul_run; +reg [11:0] mul_arg1, mul_arg2; +wire [23:0] mul_res; +sys_umul #(12,12) mul(CLK_VIDEO,mul_start,mul_run, mul_arg1,mul_arg2,mul_res); + +always @(posedge CLK_VIDEO) begin + reg [11:0] oheight,htarget,wres,hinteger,wideres; + reg [12:0] arxf,aryf; + reg [3:0] cnt; + reg narrow; + + div_start <= 0; + mul_start <= 0; + + if (!SCALE || (!ary_i && arx_i)) begin + arxf <= arx_i; + aryf <= ary_i; + end + else if(~div_start & ~div_run & ~mul_start & ~mul_run) begin + cnt <= cnt + 1'd1; + case(cnt) + // example ideal and non-ideal cases: + // [1] 720x400 4:3 VGA 80x25 text-mode (non-square pixels) + // [2] 640x480 4:3 VGA graphics mode (square pixels) + // [3] 512x512 4:3 X68000 graphics mode (non-square pixels) + 0: begin + div_num <= HDMI_HEIGHT; + div_den <= vsize; + div_start <= 1; + end + // [1] 1080 / 400 -> 2 + // [2] 1080 / 480 -> 2 + // [3] 1080 / 512 -> 2 + + 1: if(!div_res[11:0]) begin + // screen resolution is lower than video resolution. + // Integer scaling is impossible. + arxf <= arx_i; + aryf <= ary_i; + cnt <= 0; + end + else begin + mul_arg1 <= vsize; + mul_arg2 <= div_res[11:0]; + mul_start <= 1; + end + // [1] 1080 / 400 * 400 -> 800 + // [2] 1080 / 480 * 480 -> 960 + // [3] 1080 / 512 * 512 -> 1024 + + 2: begin + oheight <= mul_res[11:0]; + if(!ary_i) begin + cnt <= 8; + end + end + + 3: begin + mul_arg1 <= mul_res[11:0]; + mul_arg2 <= arx_i; + mul_start <= 1; + end + // [1] 1080 / 400 * 400 * 4 -> 3200 + // [2] 1080 / 480 * 480 * 4 -> 3840 + // [3] 1080 / 512 * 512 * 4 -> 4096 + + 4: begin + div_num <= mul_res; + div_den <= ary_i; + div_start <= 1; + end + // [1] 1080 / 480 * 480 * 4 / 3 -> 1066 + // [2] 1080 / 480 * 480 * 4 / 3 -> 1280 + // [3] 1080 / 512 * 512 * 4 / 3 -> 1365 + // saved as htarget + + 5: begin + htarget <= div_res[11:0]; + div_num <= div_res; + div_den <= hsize; + div_start <= 1; + end + // computes wide scaling factor as a ceiling division + // [1] 1080 / 400 * 400 * 4 / 3 / 720 -> 1 + // [2] 1080 / 480 * 480 * 4 / 3 / 640 -> 2 + // [3] 1080 / 512 * 512 * 4 / 3 / 512 -> 2 + + 6: begin + mul_arg1 <= hsize; + mul_arg2 <= div_res[11:0] ? div_res[11:0] : 12'd1; + mul_start <= 1; + end + // [1] 1080 / 400 * 400 * 4 / 3 / 720 * 720 -> 720 + // [2] 1080 / 480 * 480 * 4 / 3 / 640 * 640 -> 1280 + // [3] 1080 / 512 * 512 * 4 / 3 / 512 * 512 -> 1024 + + 7: if(mul_res <= HDMI_WIDTH) begin + hinteger = mul_res[11:0]; + cnt <= 12; + end + + 8: begin + div_num <= HDMI_WIDTH; + div_den <= hsize; + div_start <= 1; + end + // [1] 1920 / 720 -> 2 + // [2] 1920 / 640 -> 3 + // [3] 1920 / 512 -> 3 + + 9: begin + mul_arg1 <= hsize; + mul_arg2 <= div_res[11:0] ? div_res[11:0] : 12'd1; + mul_start <= 1; + end + // [1] 1920 / 720 * 720 -> 1440 + // [2] 1920 / 640 * 640 -> 1920 + // [3] 1920 / 512 * 512 -> 1536 + + 10: begin + hinteger <= mul_res[11:0]; + mul_arg1 <= vsize; + mul_arg2 <= div_res[11:0] ? div_res[11:0] : 12'd1; + mul_start <= 1; + end + + 11: begin + oheight <= mul_res[11:0]; + end + + 12: begin + wideres <= hinteger + hsize; + narrow <= ((htarget - hinteger) <= (wideres - htarget)) || (wideres > HDMI_WIDTH); + wres <= hinteger == htarget ? hinteger : wideres; + end + // [1] 1066 - 720 = 346 <= 1440 - 1066 = 374 || 1440 > 1920 -> true + // [2] 1280 - 1280 = 0 <= 1920 - 1280 = 640 || 1920 > 1920 -> true + // [3] 1365 - 1024 = 341 <= 1536 - 1365 = 171 || 1536 > 1920 -> false + // 1. narrow flag is true when mul_res[11:0] narrow width is closer to + // htarget aspect ratio target width or when wideres wider width + // does not fit to the screen. + // 2. wres becomes wideres only when mul_res[11:0] narrow width not equal + // to target width, meaning it is not optimal for source aspect ratio. + // otherwise it is set to narrow width that is optimal. + + 13: begin + case(SCALE) + 2: arxf <= {1'b1, hinteger}; + 3: arxf <= {1'b1, (wres > HDMI_WIDTH) ? hinteger : wres}; + 4: arxf <= {1'b1, narrow ? hinteger : wres}; + default: arxf <= {1'b1, div_num[11:0]}; + endcase + aryf <= {1'b1, oheight}; + end + endcase + end + + arx_o <= arxf; + ary_o <= aryf; +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/video_freezer.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/video_freezer.sv new file mode 100644 index 0000000000000000000000000000000000000000..24d2c65139b72d13c3172eb9722f2a63f0f200d9 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/video_freezer.sv @@ -0,0 +1,143 @@ +// +// video freeze with sync +// (C) Alexey Melnikov +// +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + +module video_freezer +( + input clk, + + output sync, + input freeze, + + input hs_in, + input vs_in, + input hbl_in, + input vbl_in, + + output hs_out, + output vs_out, + output hbl_out, + output vbl_out +); + +sync_lock #(33) vs_lock +( + .clk(clk), + .sync_in(vs_in), + .sync_out(vs_out), + .de_in(vbl_in), + .de_out(vbl_out), + .freeze(freeze) +); + +wire sync_pt; +sync_lock #(21) hs_lock +( + .clk(clk), + .sync_in(hs_in), + .sync_out(hs_out), + .de_in(hbl_in), + .de_out(hbl_out), + .freeze(freeze), + .sync_pt(sync_pt) +); + +reg sync_o; +always @(posedge clk) begin + reg old_hs, old_vs; + reg vs_sync; + + old_vs <= vs_out; + + if(~old_vs & vs_out) vs_sync <= 1; + if(sync_pt & vs_sync) begin + vs_sync <= 0; + sync_o <= ~sync_o; + end +end + +assign sync = sync_o; + +endmodule + + +module sync_lock #(parameter WIDTH) +( + input clk, + + input sync_in, + input de_in, + + output sync_out, + output de_out, + + input freeze, + output sync_pt, + output valid +); + +reg [WIDTH-1:0] f_len, s_len, de_start, de_end; +reg sync_valid; + +reg old_sync; +always @(posedge clk) old_sync <= sync_in; + +always @(posedge clk) begin + reg [WIDTH-1:0] cnti; + reg f_valid; + reg old_de; + + cnti <= cnti + 1'd1; + if(~old_sync & sync_in) begin + if(sync_valid) f_len <= cnti; + f_valid <= 1; + sync_valid <= f_valid; + cnti <= 0; + end + + if(old_sync & ~sync_in & sync_valid) s_len <= cnti; + + old_de <= de_in; + if(~old_de & de_in & sync_valid) de_start <= cnti; + if(old_de & ~de_in & sync_valid) de_end <= cnti; + + if(freeze) {f_valid, sync_valid} <= 0; +end + +reg sync_o, de_o, sync_o_pre; +always @(posedge clk) begin + reg [WIDTH-1:0] cnto; + + cnto <= cnto + 1'd1; + if(old_sync & ~sync_in & sync_valid) cnto <= s_len + 2'd2; + if(cnto == f_len) cnto <= 0; + + sync_o_pre <= (cnto == (s_len>>1)); // middle in sync + if(cnto == f_len) sync_o <= 1; + if(cnto == s_len) sync_o <= 0; + if(cnto == de_start) de_o <= 1; + if(cnto == de_end) de_o <= 0; +end + +assign sync_out = freeze ? sync_o : sync_in; +assign valid = sync_valid; +assign sync_pt = sync_o_pre; +assign de_out = freeze ? de_o : de_in; + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/video_mixer.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/video_mixer.sv new file mode 100644 index 0000000000000000000000000000000000000000..e53e1c06e53e3ff953b02398486b50202e8b8129 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/video_mixer.sv @@ -0,0 +1,219 @@ +// +// +// Copyright (c) 2017,2021 Alexey Melnikov +// +// This program is GPL Licensed. See COPYING for the full license. +// +// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +`timescale 1ns / 1ps + +// +// LINE_LENGTH: Length of display line in pixels when HBlank = 0; +// HALF_DEPTH: If =1 then color dept is 4 bits per component +// +// altera message_off 10720 +// altera message_off 12161 + +module video_mixer +#( + parameter LINE_LENGTH = 768, + parameter HALF_DEPTH = 0, + parameter GAMMA = 0 +) +( + input CLK_VIDEO, // should be multiple by (ce_pix*4) + output reg CE_PIXEL, // output pixel clock enable + + input ce_pix, // input pixel clock or clock_enable + + input scandoubler, + input hq2x, // high quality 2x scaling + + inout [21:0] gamma_bus, + + // color + input [DWIDTH:0] R, + input [DWIDTH:0] G, + input [DWIDTH:0] B, + + // Positive pulses. + input HSync, + input VSync, + input HBlank, + input VBlank, + + // Freeze engine + // HDMI: displays last frame + // VGA: black screen with HSync and VSync + input HDMI_FREEZE, + output freeze_sync, + + // video output signals + output reg [7:0] VGA_R, + output reg [7:0] VGA_G, + output reg [7:0] VGA_B, + output reg VGA_VS, + output reg VGA_HS, + output reg VGA_DE +); + +localparam DWIDTH = HALF_DEPTH ? 3 : 7; +localparam DWIDTH_SD = GAMMA ? 7 : DWIDTH; +localparam HALF_DEPTH_SD = GAMMA ? 0 : HALF_DEPTH; + +wire frz_hs, frz_vs; +wire frz_hbl, frz_vbl; +video_freezer freezer +( + .clk(CLK_VIDEO), + .freeze(HDMI_FREEZE), + .hs_in(HSync), + .vs_in(VSync), + .hbl_in(HBlank), + .vbl_in(VBlank), + .sync(freeze_sync), + .hs_out(frz_hs), + .vs_out(frz_vs), + .hbl_out(frz_hbl), + .vbl_out(frz_vbl) +); + +reg frz; +always @(posedge CLK_VIDEO) begin + reg frz1; + + frz1 <= HDMI_FREEZE; + frz <= frz1; +end + +generate + if(GAMMA && HALF_DEPTH) begin + wire [7:0] R_in = frz ? 8'd0 : {R,R}; + wire [7:0] G_in = frz ? 8'd0 : {G,G}; + wire [7:0] B_in = frz ? 8'd0 : {B,B}; + end else begin + wire [DWIDTH:0] R_in = frz ? 1'd0 : R; + wire [DWIDTH:0] G_in = frz ? 1'd0 : G; + wire [DWIDTH:0] B_in = frz ? 1'd0 : B; + end +endgenerate + +wire hs_g, vs_g; +wire hb_g, vb_g; +wire [DWIDTH_SD:0] R_gamma, G_gamma, B_gamma; + +generate + if(GAMMA) begin + assign gamma_bus[21] = 1; + gamma_corr gamma( + .clk_sys(gamma_bus[20]), + .clk_vid(CLK_VIDEO), + .ce_pix(ce_pix), + + .gamma_en(gamma_bus[19]), + .gamma_wr(gamma_bus[18]), + .gamma_wr_addr(gamma_bus[17:8]), + .gamma_value(gamma_bus[7:0]), + + .HSync(frz_hs), + .VSync(frz_vs), + .HBlank(frz_hbl), + .VBlank(frz_vbl), + .RGB_in({R_in,G_in,B_in}), + + .HSync_out(hs_g), + .VSync_out(vs_g), + .HBlank_out(hb_g), + .VBlank_out(vb_g), + .RGB_out({R_gamma,G_gamma,B_gamma}) + ); + end else begin + assign gamma_bus[21] = 0; + assign {R_gamma,G_gamma,B_gamma} = {R_in,G_in,B_in}; + assign {hs_g, vs_g, hb_g, vb_g} = {frz_hs, frz_vs, frz_hbl, frz_vbl}; + end +endgenerate + +wire [DWIDTH_SD:0] R_sd; +wire [DWIDTH_SD:0] G_sd; +wire [DWIDTH_SD:0] B_sd; +wire hs_sd, vs_sd, hb_sd, vb_sd, ce_pix_sd; + +scandoubler #(.LENGTH(LINE_LENGTH), .HALF_DEPTH(HALF_DEPTH_SD)) sd +( + .clk_vid(CLK_VIDEO), + .hq2x(hq2x), + + .ce_pix(ce_pix), + .hs_in(hs_g), + .vs_in(vs_g), + .hb_in(hb_g), + .vb_in(vb_g), + .r_in(R_gamma), + .g_in(G_gamma), + .b_in(B_gamma), + + .ce_pix_out(ce_pix_sd), + .hs_out(hs_sd), + .vs_out(vs_sd), + .hb_out(hb_sd), + .vb_out(vb_sd), + .r_out(R_sd), + .g_out(G_sd), + .b_out(B_sd) +); + +wire [DWIDTH_SD:0] rt = (scandoubler ? R_sd : R_gamma); +wire [DWIDTH_SD:0] gt = (scandoubler ? G_sd : G_gamma); +wire [DWIDTH_SD:0] bt = (scandoubler ? B_sd : B_gamma); + +always @(posedge CLK_VIDEO) begin + reg [7:0] r,g,b; + reg hde,vde,hs,vs, old_vs; + reg old_hde; + reg old_ce; + reg ce_osc, fs_osc; + + old_ce <= ce_pix; + ce_osc <= ce_osc | (old_ce ^ ce_pix); + + old_vs <= vs; + if(~old_vs & vs) begin + fs_osc <= ce_osc; + ce_osc <= 0; + end + + CE_PIXEL <= scandoubler ? ce_pix_sd : fs_osc ? (~old_ce & ce_pix) : ce_pix; + + if(!GAMMA && HALF_DEPTH) begin + r <= {rt,rt}; + g <= {gt,gt}; + b <= {bt,bt}; + end + else begin + r <= rt; + g <= gt; + b <= bt; + end + + hde <= scandoubler ? ~hb_sd : ~hb_g; + vde <= scandoubler ? ~vb_sd : ~vb_g; + vs <= scandoubler ? vs_sd : vs_g; + hs <= scandoubler ? hs_sd : hs_g; + + if(CE_PIXEL) begin + VGA_R <= r; + VGA_G <= g; + VGA_B <= b; + + VGA_VS <= vs; + VGA_HS <= hs; + + old_hde <= hde; + if(old_hde ^ hde) VGA_DE <= vde & hde; + end +end + +endmodule diff --git a/MiSTer-devel_NeoGeo_MiSTer/sys/yc_out.sv b/MiSTer-devel_NeoGeo_MiSTer/sys/yc_out.sv new file mode 100644 index 0000000000000000000000000000000000000000..984fc379afed7c038061be50ae95302e250fab18 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/sys/yc_out.sv @@ -0,0 +1,233 @@ +//============================================================================ +// YC - Luma / Chroma Generation +// Copyright (C) 2022 Mike Simone +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 2 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//============================================================================ +/* +Colorspace +Y 0.299R' + 0.587G' + 0.114B' +U 0.492(B' - Y) = 504 (X 1024) +V 0.877(R' - Y) = 898 (X 1024) +*/ +////////////////////////////////////////////////////////// + +module yc_out +( + input clk, + input [39:0] PHASE_INC, + input PAL_EN, + input CVBS, + input [16:0] COLORBURST_RANGE, + + input hsync, + input vsync, + input csync, + input de, + + input [23:0] din, + output [23:0] dout, + + output reg hsync_o, + output reg vsync_o, + output reg csync_o, + output reg de_o +); + +wire [7:0] red = din[23:16]; +wire [7:0] green = din[15:8]; +wire [7:0] blue = din[7:0]; + +logic [9:0] red_1, blue_1, green_1, red_2, blue_2, green_2; + +logic signed [20:0] yr = 0, yb = 0, yg = 0; + +typedef struct { + logic signed [20:0] y; + logic signed [20:0] c; + logic signed [20:0] u; + logic signed [20:0] v; + logic hsync; + logic vsync; + logic csync; + logic de; +} phase_t; + +localparam MAX_PHASES = 7'd8; + +phase_t phase[MAX_PHASES]; +reg unsigned [7:0] Y, C, c, U, V; + + +reg [10:0] cburst_phase; // colorburst counter +reg unsigned [7:0] vref = 'd128; // Voltage reference point (Used for Chroma) +logic [7:0] chroma_LUT_COS; // Chroma cos LUT reference +logic [7:0] chroma_LUT_SIN; // Chroma sin LUT reference +logic [7:0] chroma_LUT_BURST; // Chroma colorburst LUT reference +logic [7:0] chroma_LUT = 8'd0; + +/* +THe following LUT table was calculated by Sin(2*pi*t/2^8) where t: 0 - 255 +*/ + +/************************************* + 8 bit Sine look up Table +**************************************/ +wire signed [10:0] chroma_SIN_LUT[256] = '{ + 11'h000, 11'h006, 11'h00C, 11'h012, 11'h018, 11'h01F, 11'h025, 11'h02B, 11'h031, 11'h037, 11'h03D, 11'h044, 11'h04A, 11'h04F, + 11'h055, 11'h05B, 11'h061, 11'h067, 11'h06D, 11'h072, 11'h078, 11'h07D, 11'h083, 11'h088, 11'h08D, 11'h092, 11'h097, 11'h09C, + 11'h0A1, 11'h0A6, 11'h0AB, 11'h0AF, 11'h0B4, 11'h0B8, 11'h0BC, 11'h0C1, 11'h0C5, 11'h0C9, 11'h0CC, 11'h0D0, 11'h0D4, 11'h0D7, + 11'h0DA, 11'h0DD, 11'h0E0, 11'h0E3, 11'h0E6, 11'h0E9, 11'h0EB, 11'h0ED, 11'h0F0, 11'h0F2, 11'h0F4, 11'h0F5, 11'h0F7, 11'h0F8, + 11'h0FA, 11'h0FB, 11'h0FC, 11'h0FD, 11'h0FD, 11'h0FE, 11'h0FE, 11'h0FE, 11'h0FF, 11'h0FE, 11'h0FE, 11'h0FE, 11'h0FD, 11'h0FD, + 11'h0FC, 11'h0FB, 11'h0FA, 11'h0F8, 11'h0F7, 11'h0F5, 11'h0F4, 11'h0F2, 11'h0F0, 11'h0ED, 11'h0EB, 11'h0E9, 11'h0E6, 11'h0E3, + 11'h0E0, 11'h0DD, 11'h0DA, 11'h0D7, 11'h0D4, 11'h0D0, 11'h0CC, 11'h0C9, 11'h0C5, 11'h0C1, 11'h0BC, 11'h0B8, 11'h0B4, 11'h0AF, + 11'h0AB, 11'h0A6, 11'h0A1, 11'h09C, 11'h097, 11'h092, 11'h08D, 11'h088, 11'h083, 11'h07D, 11'h078, 11'h072, 11'h06D, 11'h067, + 11'h061, 11'h05B, 11'h055, 11'h04F, 11'h04A, 11'h044, 11'h03D, 11'h037, 11'h031, 11'h02B, 11'h025, 11'h01F, 11'h018, 11'h012, + 11'h00C, 11'h006, 11'h000, 11'h7F9, 11'h7F3, 11'h7ED, 11'h7E7, 11'h7E0, 11'h7DA, 11'h7D4, 11'h7CE, 11'h7C8, 11'h7C2, 11'h7BB, + 11'h7B5, 11'h7B0, 11'h7AA, 11'h7A4, 11'h79E, 11'h798, 11'h792, 11'h78D, 11'h787, 11'h782, 11'h77C, 11'h777, 11'h772, 11'h76D, + 11'h768, 11'h763, 11'h75E, 11'h759, 11'h754, 11'h750, 11'h74B, 11'h747, 11'h743, 11'h73E, 11'h73A, 11'h736, 11'h733, 11'h72F, + 11'h72B, 11'h728, 11'h725, 11'h722, 11'h71F, 11'h71C, 11'h719, 11'h716, 11'h714, 11'h712, 11'h70F, 11'h70D, 11'h70B, 11'h70A, + 11'h708, 11'h707, 11'h705, 11'h704, 11'h703, 11'h702, 11'h702, 11'h701, 11'h701, 11'h701, 11'h701, 11'h701, 11'h701, 11'h701, + 11'h702, 11'h702, 11'h703, 11'h704, 11'h705, 11'h707, 11'h708, 11'h70A, 11'h70B, 11'h70D, 11'h70F, 11'h712, 11'h714, 11'h716, + 11'h719, 11'h71C, 11'h71F, 11'h722, 11'h725, 11'h728, 11'h72B, 11'h72F, 11'h733, 11'h736, 11'h73A, 11'h73E, 11'h743, 11'h747, + 11'h74B, 11'h750, 11'h754, 11'h759, 11'h75E, 11'h763, 11'h768, 11'h76D, 11'h772, 11'h777, 11'h77C, 11'h782, 11'h787, 11'h78D, + 11'h792, 11'h798, 11'h79E, 11'h7A4, 11'h7AA, 11'h7B0, 11'h7B5, 11'h7BB, 11'h7C2, 11'h7C8, 11'h7CE, 11'h7D4, 11'h7DA, 11'h7E0, + 11'h7E7, 11'h7ED, 11'h7F3, 11'h7F9 +}; + +logic [39:0] phase_accum; +logic PAL_FLIP = 1'd0; +logic PAL_line_count = 1'd0; + +/************************************** + Generate Luma and Chroma Signals +***************************************/ + +always_ff @(posedge clk) begin + for (logic [3:0] x = 0; x < (MAX_PHASES - 1'd1); x = x + 1'd1) begin + phase[x + 1] <= phase[x]; + end + + // delay red / blue signals to align luma with U/V calculation (Fixes colorbleeding) + red_1 <= red; + blue_1 <= blue; + red_2 <= red_1; + blue_2 <= blue_1; + + // Calculate Luma signal + yr <= {red, 8'd0} + {red, 5'd0}+ {red, 4'd0} + {red, 1'd0}; + yg <= {green, 9'd0} + {green, 6'd0} + {green, 4'd0} + {green, 3'd0} + green; + yb <= {blue, 6'd0} + {blue, 5'd0} + {blue, 4'd0} + {blue, 2'd0} + blue; + phase[0].y <= yr + yg + yb; + + // Generate the LUT values using the phase accumulator reference. + phase_accum <= phase_accum + PHASE_INC; + chroma_LUT <= phase_accum[39:32]; + + // Adjust SINE carrier reference for PAL (Also adjust for PAL Switch) + if (PAL_EN) begin + if (PAL_FLIP) + chroma_LUT_BURST <= chroma_LUT + 8'd160; + else + chroma_LUT_BURST <= chroma_LUT + 8'd96; + end else // Adjust SINE carrier reference for NTSC + chroma_LUT_BURST <= chroma_LUT + 8'd128; + + // Prepare LUT values for sin / cos (+90 degress) + chroma_LUT_SIN <= chroma_LUT; + chroma_LUT_COS <= chroma_LUT + 8'd64; + + // Calculate for U, V - Bit Shift Multiple by u = by * 1024 x 0.492 = 504, v = ry * 1024 x 0.877 = 898 + phase[0].u <= $signed({2'b0 ,(blue_2)}) - $signed({2'b0 ,phase[0].y[17:10]}); + phase[0].v <= $signed({2'b0 , (red_2)}) - $signed({2'b0 ,phase[0].y[17:10]}); + phase[1].u <= 21'($signed({phase[0].u, 8'd0}) + $signed({phase[0].u, 7'd0}) + $signed({phase[0].u, 6'd0}) + $signed({phase[0].u, 5'd0}) + $signed({phase[0].u, 4'd0}) + $signed({phase[0].u, 3'd0})); + phase[1].v <= 21'($signed({phase[0].v, 9'd0}) + $signed({phase[0].v, 8'd0}) + $signed({phase[0].v, 7'd0}) + $signed({phase[0].v, 1'd0})); + + phase[0].c <= vref; + phase[1].c <= phase[0].c; + phase[2].c <= phase[1].c; + phase[3].c <= phase[2].c; + + if (hsync) begin // Reset colorburst counter, as well as the calculated cos / sin values. + cburst_phase <= 'd0; + phase[2].u <= 21'b0; + phase[2].v <= 21'b0; + phase[4].c <= phase[3].c; + + if (PAL_line_count) begin + PAL_FLIP <= ~PAL_FLIP; + PAL_line_count <= ~PAL_line_count; + end + end + else begin // Generate Colorburst for 9 cycles + if (cburst_phase >= COLORBURST_RANGE[16:10] && cburst_phase <= COLORBURST_RANGE[9:0]) begin // Start the color burst signal at 40 samples or 0.9 us + // COLORBURST SIGNAL GENERATION (9 CYCLES ONLY or between count 40 - 240) + phase[2].u <= $signed({chroma_SIN_LUT[chroma_LUT_BURST],5'd0}); + phase[2].v <= 21'b0; + + // Division to scale down the results to fit 8 bit. + if (PAL_EN) + phase[3].u <= $signed(phase[2].u[20:8]) + $signed(phase[2].u[20:10]) + $signed(phase[2].u[20:14]); + else + phase[3].u <= $signed(phase[2].u[20:8]) + $signed(phase[2].u[20:11]) + $signed(phase[2].u[20:12]) + $signed(phase[2].u[20:13]); + + phase[3].v <= phase[2].v; + end else begin // MODULATE U, V for chroma + /* + U,V are both multiplied by 1024 earlier to scale for the decimals in the YUV colorspace conversion. + U and V are both divided by 2^10 which introduce chroma subsampling of 4:1:1 (25% or from 8 bit to 6 bit) + */ + phase[2].u <= $signed((phase[1].u)>>>10) * $signed(chroma_SIN_LUT[chroma_LUT_SIN]); + phase[2].v <= $signed((phase[1].v)>>>10) * $signed(chroma_SIN_LUT[chroma_LUT_COS]); + + // Divide U*sin(wt) and V*cos(wt) to fit results to 8 bit + phase[3].u <= $signed(phase[2].u[20:9]) + $signed(phase[2].u[20:10]) + $signed(phase[2].u[20:14]); + phase[3].v <= $signed(phase[2].v[20:9]) + $signed(phase[2].v[20:10]) + $signed(phase[2].u[20:14]); + end + + // Stop the colorburst timer as its only needed for the initial pulse + if (cburst_phase <= COLORBURST_RANGE[9:0]) + cburst_phase <= cburst_phase + 9'd1; + + // Calculate for chroma (Note: "PAL SWITCH" routine flips V * COS(Wt) every other line) + if (PAL_EN) begin + if (PAL_FLIP) + phase[4].c <= vref + phase[3].u - phase[3].v; + else + phase[4].c <= vref + phase[3].u + phase[3].v; + PAL_line_count <= 1'd1; + end else + phase[4].c <= vref + phase[3].u + phase[3].v; + end + + // Adjust sync timing correctly + phase[1].hsync <= hsync; phase[1].vsync <= vsync; phase[1].csync <= csync; phase[1].de <= de; + phase[2].hsync <= phase[1].hsync; phase[2].vsync <= phase[1].vsync; phase[2].csync <= phase[1].csync; phase[2].de <= phase[1].de; + phase[3].hsync <= phase[2].hsync; phase[3].vsync <= phase[2].vsync; phase[3].csync <= phase[2].csync; phase[3].de <= phase[2].de; + phase[4].hsync <= phase[3].hsync; phase[4].vsync <= phase[3].vsync; phase[4].csync <= phase[3].csync; phase[4].de <= phase[3].de; + hsync_o <= phase[4].hsync; vsync_o <= phase[4].vsync; csync_o <= phase[4].csync; de_o <= phase[4].de; + + phase[1].y <= phase[0].y; phase[2].y <= phase[1].y; phase[3].y <= phase[2].y; phase[4].y <= phase[3].y; phase[5].y <= phase[4].y; + + // Set Chroma / Luma output + C <= CVBS ? 8'd0 : phase[4].c[7:0]; + Y <= CVBS ? ({1'b0, phase[5].y[17:11]} + {1'b0, phase[4].c[7:1]}) : phase[5].y[17:10]; +end + +assign dout = {C, Y, 8'd0}; + +endmodule + diff --git a/MiSTer-devel_NeoGeo_MiSTer/xml.md b/MiSTer-devel_NeoGeo_MiSTer/xml.md new file mode 100644 index 0000000000000000000000000000000000000000..af8774107304b6c7b1fc510dc7c387e9f86853c7 --- /dev/null +++ b/MiSTer-devel_NeoGeo_MiSTer/xml.md @@ -0,0 +1,74 @@ + +# Advanced ROM Options + +### Example MAME style rom entry +Below is an example of an XML entry for a MAME style ROM set. + + + + + + + + + + + + + + + + + +#### Header Fields +|Field|Use| +|--|--| +|name|Specifies the folder or zip name of the ROM set. This may have multiple entries, separated by commas.| +|altname|The human readable name of the game.| +|pcm|Indicates that the game uses a PCM combination chip.| +|ct0|Indicates the presence of CT0 chip if 1.| +|sma|Indicates the presence of SMA chip. Valid values are 1 to 5.| +|pvc|Indicates the presence of PVC chip if 1.| +|cmc|Indicates the presence of CMC chip. Valid values are 1 to 2.| +|link|Indicates the presence of Link chip if 1.| +|rom_wait|1 wait cycle for ROM zone if 1.| +|p_wait|Wait cycles for PORT zone. Valid values are 1 to 2.| + +#### File Fields +|Field|Use| +|--|--| +|name|Specifies the name of the file| +|type|Specifies the file's ROM type (optional)| +|index|Memory position into which to load the file. See below for more information.| +|offset|Offset in file to load from (0 if absent).| +|size|Size of data to load (whole file if absent)| + +##### Indexes +Indexes are determines by file types and the size of files being loaded. +|ROM type| Possible index(es)| +|--|--| +| P | 4 for P1(or P1A) ROM or merged P ROM, 5 - P1B ROM, 6 - P2 ROM +| S | 8 +| M | 9 +| V | 16-47 for A part, 48-63 for B part. 512KB chunks +| C | 15 for merged C ROM (Darksoft), 64-255 for unmerged ROM (MAME) LSB is low/high word. 512KB chunks. + +### Example Darksoft Entry + + + +#### Header Fields +The header fields are mostly the same as MAME entries, with two additions: +|Field|Use| +|--|--| +|vromb_offset|Specifies the offset in file for the second V ROM entry.| +|vrom_mirror|Specifies if the V ROM file should use address mirroring (enabled by default).| + +## Zips +ZIP files are treated as folders and may include either single game or multiple + +## romsets.xml +romsets.xml must be placed in the main NeoGeo directory. Each sub-folder may include its own romsets.xml which replaces the parent romsets.xml. + +## romset.xml +romset.xml is a single entry from romsets.xml. If this file is found then current folder it treated as a single game folder (all subfolders will be ignored). diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if.v new file mode 100644 index 0000000000000000000000000000000000000000..967dea5e54ac7fce66d2f1c8cd2bfe317bf54609 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if.v @@ -0,0 +1,557 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ahbl_if( + ahbl_bmu_dbus_acc_err, + ahbl_bmu_dbus_data, + ahbl_bmu_dbus_grnt, + ahbl_bmu_dbus_trans_cmplt, + ahbl_bmu_ibus_acc_err, + ahbl_bmu_ibus_data, + ahbl_bmu_ibus_grnt, + ahbl_bmu_ibus_trans_cmplt, + ahbl_clk_en, + ahbl_dbginfo, + ahbl_gated_clk, + ahbl_pad_haddr, + ahbl_pad_hburst, + ahbl_pad_hlock, + ahbl_pad_hprot, + ahbl_pad_hsize, + ahbl_pad_htrans, + ahbl_pad_hwdata, + ahbl_pad_hwrite, + ahbl_sysio_idle, + bmu_ahbl_dbus_acc_deny, + bmu_ahbl_dbus_addr, + bmu_ahbl_dbus_burst, + bmu_ahbl_dbus_lock, + bmu_ahbl_dbus_lrsc, + bmu_ahbl_dbus_prot, + bmu_ahbl_dbus_req, + bmu_ahbl_dbus_req_dp, + bmu_ahbl_dbus_seq, + bmu_ahbl_dbus_size, + bmu_ahbl_dbus_wdata, + bmu_ahbl_dbus_write, + bmu_ahbl_ibus_acc_deny, + bmu_ahbl_ibus_addr, + bmu_ahbl_ibus_burst, + bmu_ahbl_ibus_prot, + bmu_ahbl_ibus_req, + bmu_ahbl_ibus_req_dp, + bmu_ahbl_ibus_seq, + bmu_ahbl_ibus_size, + cpurst_b, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_xx_flush, + pad_ahbl_hrdata, + pad_ahbl_hready, + pad_ahbl_hresp, + rtu_yy_xx_async_flush, + sysio_xx_halt_req +); + +// &Ports; @24 +input ahbl_gated_clk; +input bmu_ahbl_dbus_acc_deny; +input [31:0] bmu_ahbl_dbus_addr; +input [2 :0] bmu_ahbl_dbus_burst; +input bmu_ahbl_dbus_lock; +input bmu_ahbl_dbus_lrsc; +input [3 :0] bmu_ahbl_dbus_prot; +input bmu_ahbl_dbus_req; +input bmu_ahbl_dbus_req_dp; +input bmu_ahbl_dbus_seq; +input [1 :0] bmu_ahbl_dbus_size; +input [31:0] bmu_ahbl_dbus_wdata; +input bmu_ahbl_dbus_write; +input bmu_ahbl_ibus_acc_deny; +input [31:0] bmu_ahbl_ibus_addr; +input [2 :0] bmu_ahbl_ibus_burst; +input [3 :0] bmu_ahbl_ibus_prot; +input bmu_ahbl_ibus_req; +input bmu_ahbl_ibus_req_dp; +input bmu_ahbl_ibus_seq; +input [1 :0] bmu_ahbl_ibus_size; +input cpurst_b; +input lsu_biu_amo_pmp_deny; +input lsu_biu_async_expt_ack; +input lsu_xx_flush; +input [31:0] pad_ahbl_hrdata; +input pad_ahbl_hready; +input pad_ahbl_hresp; +input rtu_yy_xx_async_flush; +input sysio_xx_halt_req; +output ahbl_bmu_dbus_acc_err; +output [31:0] ahbl_bmu_dbus_data; +output ahbl_bmu_dbus_grnt; +output ahbl_bmu_dbus_trans_cmplt; +output ahbl_bmu_ibus_acc_err; +output [31:0] ahbl_bmu_ibus_data; +output ahbl_bmu_ibus_grnt; +output ahbl_bmu_ibus_trans_cmplt; +output ahbl_clk_en; +output [10:0] ahbl_dbginfo; +output [31:0] ahbl_pad_haddr; +output [2 :0] ahbl_pad_hburst; +output ahbl_pad_hlock; +output [3 :0] ahbl_pad_hprot; +output [2 :0] ahbl_pad_hsize; +output [1 :0] ahbl_pad_htrans; +output [31:0] ahbl_pad_hwdata; +output ahbl_pad_hwrite; +output ahbl_sysio_idle; + +// &Regs; @25 +reg [2 :0] ahblif_cur_state; +reg [2 :0] ahblif_nxt_state; +reg [2 :0] burst_cnt; +reg ibus_not_grant; +reg [1 :0] lock_cur_state; +reg [1 :0] lock_next_state; +reg [1 :0] req_mask; +reg [1 :0] req_sel; + +// &Wires; @26 +wire acc_err; +wire ahbl_bmu_dbus_acc_err; +wire [31:0] ahbl_bmu_dbus_data; +wire ahbl_bmu_dbus_grnt; +wire ahbl_bmu_dbus_trans_cmplt; +wire ahbl_bmu_ibus_acc_err; +wire [31:0] ahbl_bmu_ibus_data; +wire ahbl_bmu_ibus_grnt; +wire ahbl_bmu_ibus_trans_cmplt; +wire ahbl_clk_en; +wire [10:0] ahbl_dbginfo; +wire ahbl_gated_clk; +wire [31:0] ahbl_pad_haddr; +wire [2 :0] ahbl_pad_hburst; +wire ahbl_pad_hlock; +wire [3 :0] ahbl_pad_hprot; +wire [2 :0] ahbl_pad_hsize; +wire [1 :0] ahbl_pad_htrans; +wire [31:0] ahbl_pad_hwdata; +wire ahbl_pad_hwrite; +wire ahbl_sysio_idle; +wire ahblif_req_idle; +wire ahblif_req_idle_dp; +wire [31:0] bmu_ahbl_dbus_addr; +wire [2 :0] bmu_ahbl_dbus_burst; +wire bmu_ahbl_dbus_lock; +wire bmu_ahbl_dbus_lrsc; +wire [3 :0] bmu_ahbl_dbus_prot; +wire bmu_ahbl_dbus_req; +wire bmu_ahbl_dbus_req_dp; +wire bmu_ahbl_dbus_seq; +wire [1 :0] bmu_ahbl_dbus_size; +wire [31:0] bmu_ahbl_dbus_wdata; +wire bmu_ahbl_dbus_write; +wire [31:0] bmu_ahbl_ibus_addr; +wire [2 :0] bmu_ahbl_ibus_burst; +wire [3 :0] bmu_ahbl_ibus_prot; +wire bmu_ahbl_ibus_req; +wire bmu_ahbl_ibus_req_dp; +wire bmu_ahbl_ibus_seq; +wire [1 :0] bmu_ahbl_ibus_size; +wire burst_clr; +wire burst_req; +wire [31:0] bus_rdata; +wire bus_ready; +wire bus_resp; +wire [31:0] cpu_addr; +wire [2 :0] cpu_burst; +wire cpu_burst_vld; +wire cpu_lock; +wire [3 :0] cpu_prot; +wire cpu_req; +wire cpu_req_gate; +wire cpu_seq; +wire [1 :0] cpu_size; +wire [31:0] cpu_wdata; +wire cpu_write; +wire cpurst_b; +wire dbus_req; +wire dbus_sel; +wire dbus_sel_raw; +wire ibus_req; +wire ibus_sel; +wire ibus_sel_raw; +wire inc2; +wire [2 :0] init_cnt_inc; +wire lock_clr; +wire lock_cur_idle; +wire lock_req_vld; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_xx_flush; +wire [31:0] pad_ahbl_hrdata; +wire pad_ahbl_hready; +wire pad_ahbl_hresp; +wire req_grnt; +wire req_last; +wire [1 :0] req_mask_raw; +wire req_mask_vld; +wire [1 :0] req_sel_dp; +wire [1 :0] req_valid; +wire [1 :0] req_valid_dp; +wire rtu_yy_xx_async_flush; +wire sysio_xx_halt_req; +wire trans_cmplt; + + +parameter DATA_WIDTH = 32; + +//============================================================================== +// +// AHB LITE master interface FSM +// +//============================================================================== +//1. control one transfer: SINGLE +//2. generate control signals for AHB LITE control signals: HTRANS, HCTRL + +//=================================================================== +// parameter description +//IDLE : wait for the cpu request; when cpu has request and hready, +// control information is put on the AHB LITE in this state. +//WFD : wait for the data from the AHB LITE; if back-to-back +// transfer occur, the fsm will stay in the state. +//ERROR : wait for the second phase of the two signal error response. +//ERROR1: generate the error vld signal to cpu. +//=================================================================== +parameter IDLE = 3'b000, + WFG = 3'b010, + WFD = 3'b001, + ERROR1 = 3'b110, + ERROR2 = 3'b111; + +//========================================================== +// FSM main body +//========================================================== +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ahblif_cur_state[2:0] <= IDLE; + else + ahblif_cur_state[2:0] <= ahblif_nxt_state[2:0]; +end + +// &CombBeg; @64 +always @( bus_ready + or cpu_req + or sysio_xx_halt_req + or bus_resp + or ahblif_cur_state[2:0] + or cpu_lock) +begin +case(ahblif_cur_state[2:0]) + IDLE: + begin + if(cpu_req & !sysio_xx_halt_req) begin + if(bus_ready) + ahblif_nxt_state[2:0] = WFD; + else //no ready + ahblif_nxt_state[2:0] = WFG; + end + else //no request + ahblif_nxt_state[2:0] = IDLE; + end + WFG: + begin + if(bus_ready) + ahblif_nxt_state[2:0] = WFD; + else //no ready + ahblif_nxt_state[2:0] = WFG; + end + WFD: // in this state[2:0] AHBL wait for the data. + begin + if(bus_resp) //resp is ERROR + ahblif_nxt_state[2:0] = ERROR1; + else if(!bus_ready) //resp == OK, hready == 0 + ahblif_nxt_state[2:0] = WFD; + else //resp == OK, hready == 1 + begin + if(cpu_req & !cpu_lock) + ahblif_nxt_state[2:0] = WFD; + else + ahblif_nxt_state[2:0] = IDLE; + end + end + ERROR1: // error occurs + begin + if(bus_resp) // resp is ERROR + begin + if(!bus_ready) // ready == 0 + ahblif_nxt_state[2:0] = ERROR1; + else + ahblif_nxt_state[2:0] = ERROR2; // bus resp is ERROR, hready == 1 + end + else + ahblif_nxt_state[2:0] = ERROR2; // bus resp is ERROR, hready == 1 + end + ERROR2: // error occurs + ahblif_nxt_state[2:0] = IDLE; + default: + ahblif_nxt_state[2:0] = IDLE; +endcase +// &CombEnd; @115 +end + +assign ahblif_req_idle_dp = (ahblif_cur_state[2:0] == IDLE) | + (ahblif_cur_state[2:0] == WFD); + +assign ahblif_req_idle = (ahblif_cur_state[2:0] == IDLE) & !sysio_xx_halt_req | + (ahblif_cur_state[2:0] == WFD) & bus_ready; + +//=========================================================== +// BUS LOCK +//=========================================================== +parameter LOCK_IDLE = 2'b00; +parameter LOCK_WFS = 2'b01; +parameter LOCK_WFC = 2'b10; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + lock_cur_state[1:0] <= LOCK_IDLE; + else if (lsu_biu_amo_pmp_deny) + lock_cur_state[1:0] <= LOCK_IDLE; + else + lock_cur_state[1:0] <= lock_next_state[1:0]; +end + +assign lock_req_vld = cpu_req & cpu_lock & ahblif_req_idle & !cpu_write & !lsu_biu_amo_pmp_deny & !sysio_xx_halt_req; + +// &CombBeg; @142 +always @( req_grnt + or req_last + or cpu_req + or lsu_biu_async_expt_ack + or lock_req_vld + or cpu_burst_vld + or acc_err + or lsu_xx_flush + or lock_cur_state[1:0] + or rtu_yy_xx_async_flush) +begin + case(lock_cur_state[1:0]) + LOCK_IDLE: begin + if (lock_req_vld) + lock_next_state[1:0] = (req_grnt & !cpu_burst_vld) ? LOCK_WFC : LOCK_WFS; + else + lock_next_state[1:0] = LOCK_IDLE; + end + LOCK_WFS: begin + if (acc_err) + lock_next_state[1:0] = LOCK_IDLE; + else if (req_grnt & req_last) + lock_next_state[1:0] = LOCK_WFC; + else + lock_next_state[1:0] = LOCK_WFS; + end + LOCK_WFC: begin + if (cpu_req & req_grnt | lsu_xx_flush | acc_err | rtu_yy_xx_async_flush | lsu_biu_async_expt_ack) + lock_next_state[1:0] = LOCK_IDLE; + else + lock_next_state[1:0] = LOCK_WFC; + end + default: lock_next_state[1:0] = LOCK_IDLE; + endcase +// &CombEnd; @166 +end + +assign lock_cur_idle = lock_cur_state[1:0] == LOCK_IDLE; +assign lock_clr = (lock_cur_state[1:0] == LOCK_WFC) & (cpu_req & req_grnt | acc_err | lsu_biu_async_expt_ack) | + (lock_cur_state[1:0] == LOCK_WFS) & acc_err | + !lock_cur_idle & (lsu_xx_flush | + lsu_biu_amo_pmp_deny); + +assign cpu_burst_vld = cpu_burst[2:0] != 3'b000; +assign burst_req = cpu_req & cpu_burst_vld & ahblif_req_idle; +assign burst_clr = burst_req & cpu_seq & req_last | acc_err | rtu_yy_xx_async_flush & (req_mask[1:0] == 2'b10); + +assign req_mask_raw[1:0] = rtu_yy_xx_async_flush & (req_valid[1:0] == 2'b01) + ? 2'b0 + : ~req_valid[1:0]; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + req_mask[1:0] <= 2'b0; + else if (lock_clr & !burst_req | burst_clr) + req_mask[1:0] <= 2'b0; + else if (lock_req_vld & lock_cur_idle | burst_req) + req_mask[1:0] <= req_mask_raw[1:0]; +end + +assign req_mask_vld = req_mask[1:0] != 2'b00; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + burst_cnt[2:0] <= 3'b0; + else if (burst_req & !cpu_seq) + burst_cnt[2:0] <= init_cnt_inc[2:0]; + else if (burst_req & burst_cnt[2:0] != 3'b0) + burst_cnt[2:0] <= burst_cnt[2:0] - 3'b001; +end + +assign inc2 = cpu_burst[2:0] == 3'b001; +assign init_cnt_inc[2:0] = inc2 ? 3'b000 : 3'b110; +//assign init_cnt[2:0] = inc2 ? 3'b001 : 3'b111; +assign req_last = req_mask_vld & burst_cnt[2:0] == 3'b000; + +//=========================================================== +// FSM output signal +//=========================================================== +// &Force("input","bmu_ahbl_dbus_acc_deny"); @212 +// &Force("input","bmu_ahbl_ibus_acc_deny"); @213 +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ibus_not_grant <= 1'b0; + else if (ibus_req & !req_grnt) + ibus_not_grant <= 1'b1; + else if (req_grnt) + ibus_not_grant <= 1'b0; +end + +assign dbus_req = bmu_ahbl_dbus_req & !req_mask[0] & !ibus_not_grant; +assign ibus_req = bmu_ahbl_ibus_req & !req_mask[1] & !dbus_sel_raw; +assign cpu_req = ibus_req | dbus_req; + +assign req_valid[1:0] = {ibus_req,dbus_req}; + +assign dbus_sel_raw = bmu_ahbl_dbus_req_dp & !req_mask[0] & !ibus_not_grant; +assign ibus_sel_raw = bmu_ahbl_ibus_req_dp & !req_mask[1] & !dbus_sel_raw; + +assign req_valid_dp[1:0] = {ibus_sel_raw, dbus_sel_raw}; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + req_sel[1:0] <= 2'b0; + else if (ahblif_req_idle & cpu_req) + req_sel[1:0] <= req_valid[1:0]; +end + +assign req_sel_dp[1:0] = ahblif_req_idle_dp ? req_valid_dp[1:0] : req_sel[1:0]; + +assign dbus_sel = req_sel_dp[0]; +assign ibus_sel = req_sel_dp[1]; + +//assign cpu_acc_deny = dbus_sel & bmu_ahbl_dbus_acc_deny +// | ibus_sel & bmu_ahbl_ibus_acc_deny + +assign cpu_addr[31:0] = {32{dbus_sel}} & bmu_ahbl_dbus_addr[31:0] + | {32{ibus_sel}} & bmu_ahbl_ibus_addr[31:0]; + +assign cpu_prot[3:0] = {4{dbus_sel}} & bmu_ahbl_dbus_prot[3:0] + | {4{ibus_sel}} & bmu_ahbl_ibus_prot[3:0]; + +assign cpu_size[1:0] = {2{dbus_sel}} & bmu_ahbl_dbus_size[1:0] + | {2{ibus_sel}} & bmu_ahbl_ibus_size[1:0]; + +assign cpu_seq = dbus_sel & bmu_ahbl_dbus_seq + | ibus_sel & bmu_ahbl_ibus_seq; + +assign cpu_burst[2:0] = {3{dbus_sel}} & bmu_ahbl_dbus_burst[2:0] + | {3{ibus_sel}} & bmu_ahbl_ibus_burst[2:0]; + +assign cpu_write = dbus_sel & bmu_ahbl_dbus_write; + +assign cpu_wdata[DATA_WIDTH-1:0] = bmu_ahbl_dbus_wdata[DATA_WIDTH-1:0]; + +assign cpu_lock = dbus_sel & bmu_ahbl_dbus_lock & !bmu_ahbl_dbus_lrsc; +//assign cpu_lrsc = dbus_sel & bmu_ahbl_dbus_lrsc; + +//assign cpu_amo = cpu_lock & !cpu_lrsc; + +//========================================================== +// interface to AHBL +//========================================================== +//output +// &Force("output","ahbl_pad_htrans"); @279 +assign ahbl_pad_htrans[1] = cpu_req & ((ahblif_cur_state[2:0]==IDLE) & !sysio_xx_halt_req | + (ahblif_cur_state[2:0]==WFD) & !cpu_lock) | + (ahblif_cur_state[2:0]==WFG); + +assign ahbl_pad_htrans[0] = req_mask_vld & cpu_burst_vld & (ahblif_cur_state[2:0]==WFD); + +assign ahbl_pad_haddr[31:0] = cpu_addr[31:0]; +assign ahbl_pad_hwrite = cpu_write; +assign ahbl_pad_hsize[2:0] = {1'b0, cpu_size[1:0]}; +assign ahbl_pad_hprot[3:0] = cpu_prot[3:0]; +assign ahbl_pad_hburst[2:0] = cpu_burst[2:0]; +assign ahbl_pad_hlock = ahbl_pad_htrans[1] & cpu_lock | !lock_cur_idle; +assign ahbl_pad_hwdata[DATA_WIDTH-1:0] = cpu_wdata[DATA_WIDTH-1:0]; +//input +assign bus_ready = pad_ahbl_hready; +assign bus_resp = pad_ahbl_hresp; +assign bus_rdata[DATA_WIDTH-1:0] = pad_ahbl_hrdata[DATA_WIDTH-1:0]; + +//============================================================================== +// interface with CPU +//============================================================================== +// cpu grant singal +assign req_grnt = ((ahblif_cur_state[2:0]==IDLE && !sysio_xx_halt_req) + || ahblif_cur_state[2:0]==WFG + || (ahblif_cur_state[2:0]==WFD) && !cpu_lock) + && bus_ready && !bus_resp; + +// trans complete singal +assign trans_cmplt = (ahblif_cur_state[2:0]==WFD) && bus_ready && !bus_resp + || (ahblif_cur_state[2:0]==ERROR2); //error vld + +// access error valid singal +assign acc_err = (ahblif_cur_state[2:0]==ERROR2); + +//========================================================== +// to BMU +//========================================================== +assign ahbl_bmu_ibus_grnt = req_sel_dp[1] & req_grnt; +assign ahbl_bmu_ibus_trans_cmplt = req_sel[1] & trans_cmplt; +assign ahbl_bmu_ibus_acc_err = req_sel[1] & acc_err; +assign ahbl_bmu_ibus_data[DATA_WIDTH-1:0] = bus_rdata[DATA_WIDTH-1:0]; + +assign ahbl_bmu_dbus_grnt = req_sel_dp[0] & req_grnt; +assign ahbl_bmu_dbus_trans_cmplt = req_sel[0] & trans_cmplt; +assign ahbl_bmu_dbus_acc_err = req_sel[0] & acc_err; +assign ahbl_bmu_dbus_data[DATA_WIDTH-1:0] = bus_rdata[DATA_WIDTH-1:0]; + +//========================================================== +// BIU CLK EN +//========================================================== + +assign cpu_req_gate = bmu_ahbl_dbus_req_dp | + bmu_ahbl_ibus_req_dp; + +assign ahbl_clk_en = !(ahblif_cur_state[2:0]==IDLE) | cpu_req_gate | + !(lock_cur_state[1:0]==LOCK_IDLE) | + rtu_yy_xx_async_flush; +assign ahbl_sysio_idle = (ahblif_cur_state[2:0]==IDLE); + +assign ahbl_dbginfo[10:0] = {burst_cnt[2:0],1'b0,req_mask[1:0],lock_cur_state[1:0],ahblif_cur_state[2:0]}; + +// &Force("nonport", "dbus_ibus_cmpt"); @386 +// &Force("nonport", "ibus_req_reg"); @387 + +// &ModuleEnd; @390 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if_fo.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if_fo.v new file mode 100644 index 0000000000000000000000000000000000000000..84dfedba9d98bd4d50fe1cddb3b6426762e0b99c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_ahbl_if_fo.v @@ -0,0 +1,534 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ahbl_if_fo( + ahbl_bmu_dbus_acc_err, + ahbl_bmu_dbus_data, + ahbl_bmu_dbus_grnt, + ahbl_bmu_dbus_trans_cmplt, + ahbl_bmu_ibus_acc_err, + ahbl_bmu_ibus_data, + ahbl_bmu_ibus_grnt, + ahbl_bmu_ibus_trans_cmplt, + ahbl_clk_en, + ahbl_dbginfo, + ahbl_gated_clk, + ahbl_pad_haddr, + ahbl_pad_hburst, + ahbl_pad_hlock, + ahbl_pad_hprot, + ahbl_pad_hsize, + ahbl_pad_htrans, + ahbl_pad_hwdata, + ahbl_pad_hwrite, + ahbl_sysio_idle, + bmu_ahbl_dbus_acc_deny, + bmu_ahbl_dbus_addr, + bmu_ahbl_dbus_burst, + bmu_ahbl_dbus_lock, + bmu_ahbl_dbus_lrsc, + bmu_ahbl_dbus_prot, + bmu_ahbl_dbus_req, + bmu_ahbl_dbus_req_dp, + bmu_ahbl_dbus_seq, + bmu_ahbl_dbus_size, + bmu_ahbl_dbus_wdata, + bmu_ahbl_dbus_write, + bmu_ahbl_ibus_acc_deny, + bmu_ahbl_ibus_addr, + bmu_ahbl_ibus_burst, + bmu_ahbl_ibus_prot, + bmu_ahbl_ibus_req, + bmu_ahbl_ibus_req_dp, + bmu_ahbl_ibus_seq, + bmu_ahbl_ibus_size, + clk_en, + cpurst_b, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_xx_flush, + lsu_xx_warm_up, + pad_ahbl_hrdata, + pad_ahbl_hready, + pad_ahbl_hresp, + sysio_xx_halt_req +); + +// &Ports; @24 +input ahbl_gated_clk; +input bmu_ahbl_dbus_acc_deny; +input [31:0] bmu_ahbl_dbus_addr; +input [2 :0] bmu_ahbl_dbus_burst; +input bmu_ahbl_dbus_lock; +input bmu_ahbl_dbus_lrsc; +input [3 :0] bmu_ahbl_dbus_prot; +input bmu_ahbl_dbus_req; +input bmu_ahbl_dbus_req_dp; +input bmu_ahbl_dbus_seq; +input [1 :0] bmu_ahbl_dbus_size; +input [31:0] bmu_ahbl_dbus_wdata; +input bmu_ahbl_dbus_write; +input bmu_ahbl_ibus_acc_deny; +input [31:0] bmu_ahbl_ibus_addr; +input [2 :0] bmu_ahbl_ibus_burst; +input [3 :0] bmu_ahbl_ibus_prot; +input bmu_ahbl_ibus_req; +input bmu_ahbl_ibus_req_dp; +input bmu_ahbl_ibus_seq; +input [1 :0] bmu_ahbl_ibus_size; +input clk_en; +input cpurst_b; +input lsu_biu_amo_pmp_deny; +input lsu_biu_async_expt_ack; +input lsu_xx_flush; +input lsu_xx_warm_up; +input [31:0] pad_ahbl_hrdata; +input pad_ahbl_hready; +input pad_ahbl_hresp; +input sysio_xx_halt_req; +output ahbl_bmu_dbus_acc_err; +output [31:0] ahbl_bmu_dbus_data; +output ahbl_bmu_dbus_grnt; +output ahbl_bmu_dbus_trans_cmplt; +output ahbl_bmu_ibus_acc_err; +output [31:0] ahbl_bmu_ibus_data; +output ahbl_bmu_ibus_grnt; +output ahbl_bmu_ibus_trans_cmplt; +output ahbl_clk_en; +output [10:0] ahbl_dbginfo; +output [31:0] ahbl_pad_haddr; +output [2 :0] ahbl_pad_hburst; +output ahbl_pad_hlock; +output [3 :0] ahbl_pad_hprot; +output [2 :0] ahbl_pad_hsize; +output [1 :0] ahbl_pad_htrans; +output [31:0] ahbl_pad_hwdata; +output ahbl_pad_hwrite; +output ahbl_sysio_idle; + +// &Regs; @25 +reg [2 :0] ahblif_cur_state; +reg [2 :0] ahblif_nxt_state; +reg [1 :0] lock_cur_state; +reg [1 :0] lock_next_state; +reg [31:0] req_buf_addr; +reg req_buf_lock; +reg req_buf_pmp_deny; +reg [3 :0] req_buf_prot; +reg [1 :0] req_buf_size; +reg req_buf_vld; +reg [31:0] req_buf_wdata; +reg req_buf_write; +reg [1 :0] req_mask; +reg [1 :0] req_sel; + +// &Wires; @26 +wire acc_err; +wire ahbl_bmu_dbus_acc_err; +wire [31:0] ahbl_bmu_dbus_data; +wire ahbl_bmu_dbus_grnt; +wire ahbl_bmu_dbus_trans_cmplt; +wire ahbl_bmu_ibus_acc_err; +wire [31:0] ahbl_bmu_ibus_data; +wire ahbl_bmu_ibus_grnt; +wire ahbl_bmu_ibus_trans_cmplt; +wire ahbl_clk_en; +wire [10:0] ahbl_dbginfo; +wire ahbl_gated_clk; +wire [31:0] ahbl_pad_haddr; +wire [2 :0] ahbl_pad_hburst; +wire ahbl_pad_hlock; +wire [3 :0] ahbl_pad_hprot; +wire [2 :0] ahbl_pad_hsize; +wire [1 :0] ahbl_pad_htrans; +wire [31:0] ahbl_pad_hwdata; +wire ahbl_pad_hwrite; +wire ahbl_sysio_idle; +wire ahblif_req_idle; +wire bmu_ahbl_dbus_acc_deny; +wire [31:0] bmu_ahbl_dbus_addr; +wire bmu_ahbl_dbus_lock; +wire bmu_ahbl_dbus_lrsc; +wire [3 :0] bmu_ahbl_dbus_prot; +wire bmu_ahbl_dbus_req; +wire bmu_ahbl_dbus_req_dp; +wire [1 :0] bmu_ahbl_dbus_size; +wire [31:0] bmu_ahbl_dbus_wdata; +wire bmu_ahbl_dbus_write; +wire bmu_ahbl_ibus_acc_deny; +wire [31:0] bmu_ahbl_ibus_addr; +wire [3 :0] bmu_ahbl_ibus_prot; +wire bmu_ahbl_ibus_req; +wire bmu_ahbl_ibus_req_dp; +wire [1 :0] bmu_ahbl_ibus_size; +wire [31:0] bus_rdata; +wire bus_ready; +wire bus_resp; +wire clk_en; +wire cpu_acc_deny; +wire [31:0] cpu_addr; +wire cpu_grant; +wire cpu_lock; +wire [3 :0] cpu_prot; +wire cpu_req; +wire cpu_req_gate; +wire [1 :0] cpu_size; +wire [31:0] cpu_wdata; +wire cpu_write; +wire cpurst_b; +wire dbus_req; +wire dbus_sel; +wire ibus_req; +wire ibus_sel; +wire lock_clr; +wire lock_cur_idle; +wire lock_req_vld; +wire lsu_biu_async_expt_ack; +wire lsu_xx_flush; +wire lsu_xx_warm_up; +wire [31:0] pad_ahbl_hrdata; +wire pad_ahbl_hready; +wire pad_ahbl_hresp; +wire req_buf_create_en; +wire req_buf_lock_clr; +wire req_buf_pop_en; +wire req_buf_wdata_create_en; +wire req_data_ready; +wire [1 :0] req_valid; +wire req_vld; +wire sysio_xx_halt_req; +wire trans_cmplt; + + +parameter DATA_WIDTH = 32; + +//============================================================================== +// +// AHB LITE master interface FSM +// +//============================================================================== +//1. control one transfer: SINGLE +//2. generate control signals for AHB LITE control signals: HTRANS, HCTRL + +//=================================================================== +// parameter description +//IDLE : wait for the cpu request; when cpu has request and hready, +// control information is put on the AHB LITE in this state. +//WFD : wait for the data from the AHB LITE; if back-to-back +// transfer occur, the fsm will stay in the state. +//ERROR : wait for the second phase of the two signal error response. +//ERROR1: generate the error vld signal to cpu. +//=================================================================== +parameter IDLE = 3'b000, + WFG = 3'b010, + WFD = 3'b001, + ERROR1 = 3'b110, + ERROR2 = 3'b111; + +//========================================================== +// FSM main body +//========================================================== +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ahblif_cur_state[2:0] <= IDLE; + else if (clk_en) + ahblif_cur_state[2:0] <= ahblif_nxt_state[2:0]; +end + +// &CombBeg; @64 +always @( req_buf_pmp_deny + or bus_ready + or req_buf_vld + or bus_resp + or ahblif_cur_state[2:0]) +begin +case(ahblif_cur_state[2:0]) + IDLE: begin + if (req_buf_vld) + ahblif_nxt_state[2:0] = (bus_ready | req_buf_pmp_deny) ? WFD : WFG; + else + ahblif_nxt_state[2:0] = IDLE; + end + WFG: begin + if (bus_ready) + ahblif_nxt_state[2:0] = WFD; + else + ahblif_nxt_state[2:0] = WFG; + end + WFD: begin + if (bus_resp) + ahblif_nxt_state[2:0] = ERROR1; + else if (!bus_ready & !req_buf_pmp_deny) + ahblif_nxt_state[2:0] = WFD; + else + ahblif_nxt_state[2:0] = IDLE; + end + ERROR1: begin + if (bus_ready | !bus_resp) + ahblif_nxt_state[2:0] = ERROR2; + else + ahblif_nxt_state[2:0] = ERROR1; + end + ERROR2: + ahblif_nxt_state[2:0] = IDLE; + default: ahblif_nxt_state[2:0] = IDLE; +endcase +// &CombEnd; @96 +end + +assign ahblif_req_idle = (ahblif_cur_state[2:0] == IDLE) | + (ahblif_cur_state[2:0] == WFD) & bus_ready; + +assign req_data_ready = (ahblif_cur_state[2:0] == WFD) & bus_ready; + +//=========================================================== +// BUS LOCK +//=========================================================== +// &Force("input","lsu_biu_amo_pmp_deny"); @106 +parameter LOCK_IDLE = 2'b00; +parameter LOCK_WFS = 2'b01; +parameter LOCK_WFC = 2'b10; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + lock_cur_state[1:0] <= LOCK_IDLE; + else if (req_buf_vld & req_buf_pmp_deny) + lock_cur_state[1:0] <= LOCK_IDLE; + else if (clk_en) + lock_cur_state[1:0] <= lock_next_state[1:0]; +end + +assign lock_req_vld = cpu_req & cpu_lock & !cpu_write & + cpu_grant; + +// &CombBeg; @124 +always @( acc_err + or cpu_grant + or cpu_req + or lsu_biu_async_expt_ack + or lock_req_vld + or lock_cur_state[1:0]) +begin + case(lock_cur_state[1:0]) + LOCK_IDLE: begin + if (lock_req_vld) + lock_next_state[1:0] = LOCK_WFC; + else + lock_next_state[1:0] = LOCK_IDLE; + end +// LOCK_WFS: begin +// if (acc_err) +// lock_next_state[1:0] = LOCK_IDLE; +// else if (trans_cmplt) +// lock_next_state[1:0] = LOCK_WFC; +// else +// lock_next_state[1:0] = LOCK_WFS; +// end + LOCK_WFC: begin + if (acc_err | cpu_req & cpu_grant | lsu_biu_async_expt_ack) + lock_next_state[1:0] = LOCK_IDLE; + else + lock_next_state[1:0] = LOCK_WFC; + end + default: lock_next_state[1:0] = LOCK_IDLE; + endcase +// &CombEnd; @148 +end + +assign lock_cur_idle = lock_cur_state[1:0] == LOCK_IDLE; +assign lock_clr = (lock_cur_state[1:0] == LOCK_WFC) & (cpu_grant & cpu_req | acc_err | lsu_biu_async_expt_ack) | + !lock_cur_idle & lsu_xx_flush | + req_buf_vld & req_buf_pmp_deny; + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + req_mask[1:0] <= 2'b0; + else if (lock_req_vld & lock_cur_idle) + req_mask[1:0] <= ~req_valid[1:0]; + else if (lock_clr) + req_mask[1:0] <= 2'b0; +end + +//=========================================================== +// FSM output signal +//=========================================================== +// &Force("input", "bmu_ahbl_dbus_burst"); &Force("bus", "bmu_ahbl_dbus_burst",2,0); @168 +// &Force("input", "bmu_ahbl_ibus_burst"); &Force("bus", "bmu_ahbl_ibus_burst",2,0); @169 +// &Force("input", "bmu_ahbl_dbus_seq"); @170 +// &Force("input", "bmu_ahbl_ibus_seq"); @171 + +assign dbus_req = bmu_ahbl_dbus_req & !req_mask[0]; +assign ibus_req = bmu_ahbl_ibus_req & !req_mask[1] & !dbus_sel; + +assign cpu_req = ibus_req | dbus_req; + +assign dbus_sel = bmu_ahbl_dbus_req_dp & !req_mask[0]; +assign ibus_sel = bmu_ahbl_ibus_req_dp & !req_mask[1] & !dbus_sel; + +assign req_valid[1:0] = {ibus_req, dbus_req}; + +assign cpu_acc_deny = dbus_sel & bmu_ahbl_dbus_acc_deny + | ibus_sel & bmu_ahbl_ibus_acc_deny; + +assign cpu_addr[31:0] = {32{dbus_sel}} & bmu_ahbl_dbus_addr[31:0] + | {32{ibus_sel}} & bmu_ahbl_ibus_addr[31:0]; + +assign cpu_prot[3:0] = {4{dbus_sel}} & bmu_ahbl_dbus_prot[3:0] + | {4{ibus_sel}} & bmu_ahbl_ibus_prot[3:0]; + +assign cpu_size[1:0] = {2{dbus_sel}} & bmu_ahbl_dbus_size[1:0] + | {2{ibus_sel}} & bmu_ahbl_ibus_size[1:0]; + +assign cpu_write = dbus_sel & bmu_ahbl_dbus_write; + +assign cpu_wdata[DATA_WIDTH-1:0] = bmu_ahbl_dbus_wdata[DATA_WIDTH-1:0]; + +assign cpu_lock = dbus_sel & bmu_ahbl_dbus_lock & !bmu_ahbl_dbus_lrsc; +//assign cpu_amo = cpu_lock & !bmu_ahbl_dbus_lrsc; + +assign req_buf_create_en = cpu_req & cpu_grant; +//assign req_buf_pop_en = req_buf_vld & ahblif_req_idle & clk_en; +assign req_buf_pop_en = clk_en & (req_buf_vld & req_data_ready | (ahblif_cur_state[2:0] == ERROR2)); + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_buf_vld <= 1'b0; + else if (req_buf_create_en) + req_buf_vld <= 1'b1; + else if (req_buf_pop_en) + req_buf_vld <= 1'b0; +end + +always@(posedge ahbl_gated_clk) +begin + if (lsu_xx_warm_up)begin + req_sel[1:0] <= 2'b0; + req_buf_pmp_deny <= 1'b0; + req_buf_addr[31:0] <= 32'b0; + req_buf_prot[3:0] <= 4'b0; + req_buf_size[1:0] <= 2'b0; + req_buf_write <= 1'b0; + end + else if (req_buf_create_en) begin + req_sel[1:0] <= req_valid[1:0]; + req_buf_pmp_deny <= cpu_acc_deny; + req_buf_addr[31:0] <= cpu_addr[31:0]; + req_buf_prot[3:0] <= cpu_prot[3:0]; + req_buf_size[1:0] <= cpu_size[1:0]; + req_buf_write <= cpu_write; + end +end + +//assign req_buf_lock_clr = req_buf_pop_en & (bus_ready | req_buf_pmp_deny) | +// ahblif_req_idle[2:0]==WFG & bus_ready & clk_en; + +assign req_buf_lock_clr = req_buf_pop_en & (bus_ready | req_buf_pmp_deny); + + +always@(posedge ahbl_gated_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_buf_lock <= 1'b0; + else if (req_buf_create_en) + req_buf_lock <= cpu_lock; + else if (req_buf_lock_clr & lock_cur_idle) + req_buf_lock <= 1'b0; +end + +assign req_buf_wdata_create_en = req_buf_vld & bus_ready & clk_en; + +always@(posedge ahbl_gated_clk) +begin + if (lsu_xx_warm_up) + req_buf_wdata[DATA_WIDTH-1:0]<= {DATA_WIDTH{1'b0}}; + else if (req_buf_wdata_create_en) + req_buf_wdata[DATA_WIDTH-1:0]<= cpu_wdata[DATA_WIDTH-1:0]; +end + +assign req_vld = req_buf_vld & !req_buf_pmp_deny; + +//========================================================== +// interface to AHBL +//========================================================== + +assign ahbl_pad_htrans[1] = req_vld & (ahblif_cur_state[2:0]==IDLE) | + (ahblif_cur_state[2:0]==WFG); + +assign ahbl_pad_htrans[0] = 1'b0; + +assign ahbl_pad_haddr[31:0] = req_buf_addr[31:0]; +assign ahbl_pad_hwrite = req_buf_write; +assign ahbl_pad_hsize[2:0] = {1'b0, req_buf_size[1:0]}; +assign ahbl_pad_hprot[3:0] = req_buf_prot[3:0]; +assign ahbl_pad_hburst[2:0] = 3'b000; +assign ahbl_pad_hlock = req_buf_lock; +assign ahbl_pad_hwdata[DATA_WIDTH-1:0] = req_buf_wdata[DATA_WIDTH-1:0]; +//input +assign bus_ready = pad_ahbl_hready; +assign bus_resp = pad_ahbl_hresp; +assign bus_rdata[DATA_WIDTH-1:0] = pad_ahbl_hrdata[DATA_WIDTH-1:0]; + +//============================================================================== +// interface with CPU +//============================================================================== +assign cpu_grant = !req_buf_vld & ahblif_req_idle & clk_en & !sysio_xx_halt_req; + +// trans complete singal +assign trans_cmplt = clk_en & + ((ahblif_cur_state[2:0]==WFD) & (bus_ready & !bus_resp | req_buf_vld & req_buf_pmp_deny) + | (ahblif_cur_state[2:0]==ERROR2)); //error vld + +// access error valid singal +assign acc_err = (ahblif_cur_state[2:0]==ERROR2) & clk_en; + +//========================================================== +// to BMU +//========================================================== +assign ahbl_bmu_ibus_grnt = ibus_sel & cpu_grant; +assign ahbl_bmu_ibus_trans_cmplt = req_sel[1] & trans_cmplt; +assign ahbl_bmu_ibus_acc_err = req_sel[1] & acc_err; +assign ahbl_bmu_ibus_data[DATA_WIDTH-1:0] = bus_rdata[DATA_WIDTH-1:0]; + +assign ahbl_bmu_dbus_grnt = dbus_sel & cpu_grant; +assign ahbl_bmu_dbus_trans_cmplt = req_sel[0] & trans_cmplt; +assign ahbl_bmu_dbus_acc_err = req_sel[0] & acc_err; +assign ahbl_bmu_dbus_data[DATA_WIDTH-1:0] = bus_rdata[DATA_WIDTH-1:0]; + +//========================================================== +// BIU CLK EN +//========================================================== +assign cpu_req_gate = bmu_ahbl_dbus_req_dp | + bmu_ahbl_ibus_req_dp; +assign ahbl_clk_en = !(ahblif_cur_state[2:0]==IDLE) | cpu_req_gate | req_buf_vld | !lock_cur_idle | lsu_xx_warm_up; +assign ahbl_sysio_idle = (ahblif_cur_state[2:0]==IDLE) & !req_buf_vld | lsu_xx_warm_up; + +assign ahbl_dbginfo[10:0] = {4'b0,req_mask[1:0],lock_cur_state[1:0],ahblif_cur_state[2:0]}; + +// &Force("nonport", "req_grnt_reg"); @376 +// &Force("output", "ahbl_bmu_ibus_grnt"); @377 +// &Force("output", "ahbl_bmu_dbus_grnt"); @378 +// // &Force("nonport", "dbus_ibus_hold"); @379 +// &Force("nonport", "ibus_req_reg"); @380 + + +// &ModuleEnd; @384 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_dahbl_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_dahbl_top.v new file mode 100644 index 0000000000000000000000000000000000000000..08c36e0a2bcce4d0877cdabe8823c069a92539bb --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_dahbl_top.v @@ -0,0 +1,263 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_dahbl_top( + bmu_dahbl_dbus_acc_deny, + bmu_dahbl_dbus_addr, + bmu_dahbl_dbus_burst, + bmu_dahbl_dbus_lock, + bmu_dahbl_dbus_lrsc, + bmu_dahbl_dbus_prot, + bmu_dahbl_dbus_req, + bmu_dahbl_dbus_req_dp, + bmu_dahbl_dbus_seq, + bmu_dahbl_dbus_size, + bmu_dahbl_dbus_wdata, + bmu_dahbl_dbus_write, + bmu_dahbl_ibus_acc_deny, + bmu_dahbl_ibus_addr, + bmu_dahbl_ibus_burst, + bmu_dahbl_ibus_prot, + bmu_dahbl_ibus_req, + bmu_dahbl_ibus_req_dp, + bmu_dahbl_ibus_seq, + bmu_dahbl_ibus_size, + cp0_biu_icg_en, + cpurst_b, + dahbl_bmu_dbus_acc_err, + dahbl_bmu_dbus_data, + dahbl_bmu_dbus_grnt, + dahbl_bmu_dbus_trans_cmplt, + dahbl_bmu_ibus_acc_err, + dahbl_bmu_ibus_data, + dahbl_bmu_ibus_grnt, + dahbl_bmu_ibus_trans_cmplt, + dahbl_dtu_debug_info, + dahbl_pad_haddr, + dahbl_pad_hburst, + dahbl_pad_hlock, + dahbl_pad_hprot, + dahbl_pad_hsize, + dahbl_pad_htrans, + dahbl_pad_hwdata, + dahbl_pad_hwrite, + dahbl_sysio_idle, + forever_cpuclk, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_xx_flush, + lsu_xx_warm_up, + pad_dahbl_hrdata, + pad_dahbl_hready, + pad_dahbl_hresp, + pad_yy_icg_scan_en, + rtu_yy_xx_async_flush, + sysio_xx_halt_req +); + +// &Ports; @23 +input bmu_dahbl_dbus_acc_deny; +input [31:0] bmu_dahbl_dbus_addr; +input [2 :0] bmu_dahbl_dbus_burst; +input bmu_dahbl_dbus_lock; +input bmu_dahbl_dbus_lrsc; +input [3 :0] bmu_dahbl_dbus_prot; +input bmu_dahbl_dbus_req; +input bmu_dahbl_dbus_req_dp; +input bmu_dahbl_dbus_seq; +input [1 :0] bmu_dahbl_dbus_size; +input [31:0] bmu_dahbl_dbus_wdata; +input bmu_dahbl_dbus_write; +input bmu_dahbl_ibus_acc_deny; +input [31:0] bmu_dahbl_ibus_addr; +input [2 :0] bmu_dahbl_ibus_burst; +input [3 :0] bmu_dahbl_ibus_prot; +input bmu_dahbl_ibus_req; +input bmu_dahbl_ibus_req_dp; +input bmu_dahbl_ibus_seq; +input [1 :0] bmu_dahbl_ibus_size; +input cp0_biu_icg_en; +input cpurst_b; +input forever_cpuclk; +input lsu_biu_amo_pmp_deny; +input lsu_biu_async_expt_ack; +input lsu_xx_flush; +input lsu_xx_warm_up; +input [31:0] pad_dahbl_hrdata; +input pad_dahbl_hready; +input pad_dahbl_hresp; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +input sysio_xx_halt_req; +output dahbl_bmu_dbus_acc_err; +output [31:0] dahbl_bmu_dbus_data; +output dahbl_bmu_dbus_grnt; +output dahbl_bmu_dbus_trans_cmplt; +output dahbl_bmu_ibus_acc_err; +output [31:0] dahbl_bmu_ibus_data; +output dahbl_bmu_ibus_grnt; +output dahbl_bmu_ibus_trans_cmplt; +output [10:0] dahbl_dtu_debug_info; +output [31:0] dahbl_pad_haddr; +output [2 :0] dahbl_pad_hburst; +output dahbl_pad_hlock; +output [3 :0] dahbl_pad_hprot; +output [2 :0] dahbl_pad_hsize; +output [1 :0] dahbl_pad_htrans; +output [31:0] dahbl_pad_hwdata; +output dahbl_pad_hwrite; +output dahbl_sysio_idle; + +// &Regs; @24 + +// &Wires; @25 +wire bmu_dahbl_dbus_acc_deny; +wire [31:0] bmu_dahbl_dbus_addr; +wire [2 :0] bmu_dahbl_dbus_burst; +wire bmu_dahbl_dbus_lock; +wire bmu_dahbl_dbus_lrsc; +wire [3 :0] bmu_dahbl_dbus_prot; +wire bmu_dahbl_dbus_req; +wire bmu_dahbl_dbus_req_dp; +wire bmu_dahbl_dbus_seq; +wire [1 :0] bmu_dahbl_dbus_size; +wire [31:0] bmu_dahbl_dbus_wdata; +wire bmu_dahbl_dbus_write; +wire bmu_dahbl_ibus_acc_deny; +wire [31:0] bmu_dahbl_ibus_addr; +wire [2 :0] bmu_dahbl_ibus_burst; +wire [3 :0] bmu_dahbl_ibus_prot; +wire bmu_dahbl_ibus_req; +wire bmu_dahbl_ibus_req_dp; +wire bmu_dahbl_ibus_seq; +wire [1 :0] bmu_dahbl_ibus_size; +wire cp0_biu_icg_en; +wire cpurst_b; +wire dahbl_bmu_dbus_acc_err; +wire [31:0] dahbl_bmu_dbus_data; +wire dahbl_bmu_dbus_grnt; +wire dahbl_bmu_dbus_trans_cmplt; +wire dahbl_bmu_ibus_acc_err; +wire [31:0] dahbl_bmu_ibus_data; +wire dahbl_bmu_ibus_grnt; +wire dahbl_bmu_ibus_trans_cmplt; +wire dahbl_clk_en; +wire [10:0] dahbl_dbginfo; +wire [10:0] dahbl_dtu_debug_info; +wire dahbl_gated_clk; +wire [31:0] dahbl_pad_haddr; +wire [2 :0] dahbl_pad_hburst; +wire dahbl_pad_hlock; +wire [3 :0] dahbl_pad_hprot; +wire [2 :0] dahbl_pad_hsize; +wire [1 :0] dahbl_pad_htrans; +wire [31:0] dahbl_pad_hwdata; +wire dahbl_pad_hwrite; +wire dahbl_sysio_idle; +wire forever_cpuclk; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_xx_flush; +wire [31:0] pad_dahbl_hrdata; +wire pad_dahbl_hready; +wire pad_dahbl_hresp; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_async_flush; +wire sysio_xx_halt_req; + + +//========================================================== +// Instance Gated Cell for Most Common Use +//========================================================== +// &Instance("gated_clk_cell", "x_pa_dahbl_cpuclk_cell"); @30 +gated_clk_cell x_pa_dahbl_cpuclk_cell ( + .clk_in (forever_cpuclk ), + .clk_out (dahbl_gated_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dahbl_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @31 +// .global_en (1'b1 ), @32 +// .local_en (dahbl_clk_en ), @33 +// .module_en (cp0_biu_icg_en), @34 +// .external_en(1'b0 ), @35 +// .clk_out (dahbl_gated_clk)); @36 + +// &ConnRule(s/ahbl/dahbl/); @38 +// &Instance("pa_ahbl_if_fo", "x_pa_ahbl_if"); @40 +// &Connect(.clk_en (dlite_clk_en_f)); @41 +// &Force("input","lsu_xx_warm_up"); @43 +// &Instance("pa_ahbl_if", "x_pa_ahbl_if"); @44 +pa_ahbl_if x_pa_ahbl_if ( + .ahbl_bmu_dbus_acc_err (dahbl_bmu_dbus_acc_err ), + .ahbl_bmu_dbus_data (dahbl_bmu_dbus_data ), + .ahbl_bmu_dbus_grnt (dahbl_bmu_dbus_grnt ), + .ahbl_bmu_dbus_trans_cmplt (dahbl_bmu_dbus_trans_cmplt), + .ahbl_bmu_ibus_acc_err (dahbl_bmu_ibus_acc_err ), + .ahbl_bmu_ibus_data (dahbl_bmu_ibus_data ), + .ahbl_bmu_ibus_grnt (dahbl_bmu_ibus_grnt ), + .ahbl_bmu_ibus_trans_cmplt (dahbl_bmu_ibus_trans_cmplt), + .ahbl_clk_en (dahbl_clk_en ), + .ahbl_dbginfo (dahbl_dbginfo ), + .ahbl_gated_clk (dahbl_gated_clk ), + .ahbl_pad_haddr (dahbl_pad_haddr ), + .ahbl_pad_hburst (dahbl_pad_hburst ), + .ahbl_pad_hlock (dahbl_pad_hlock ), + .ahbl_pad_hprot (dahbl_pad_hprot ), + .ahbl_pad_hsize (dahbl_pad_hsize ), + .ahbl_pad_htrans (dahbl_pad_htrans ), + .ahbl_pad_hwdata (dahbl_pad_hwdata ), + .ahbl_pad_hwrite (dahbl_pad_hwrite ), + .ahbl_sysio_idle (dahbl_sysio_idle ), + .bmu_ahbl_dbus_acc_deny (bmu_dahbl_dbus_acc_deny ), + .bmu_ahbl_dbus_addr (bmu_dahbl_dbus_addr ), + .bmu_ahbl_dbus_burst (bmu_dahbl_dbus_burst ), + .bmu_ahbl_dbus_lock (bmu_dahbl_dbus_lock ), + .bmu_ahbl_dbus_lrsc (bmu_dahbl_dbus_lrsc ), + .bmu_ahbl_dbus_prot (bmu_dahbl_dbus_prot ), + .bmu_ahbl_dbus_req (bmu_dahbl_dbus_req ), + .bmu_ahbl_dbus_req_dp (bmu_dahbl_dbus_req_dp ), + .bmu_ahbl_dbus_seq (bmu_dahbl_dbus_seq ), + .bmu_ahbl_dbus_size (bmu_dahbl_dbus_size ), + .bmu_ahbl_dbus_wdata (bmu_dahbl_dbus_wdata ), + .bmu_ahbl_dbus_write (bmu_dahbl_dbus_write ), + .bmu_ahbl_ibus_acc_deny (bmu_dahbl_ibus_acc_deny ), + .bmu_ahbl_ibus_addr (bmu_dahbl_ibus_addr ), + .bmu_ahbl_ibus_burst (bmu_dahbl_ibus_burst ), + .bmu_ahbl_ibus_prot (bmu_dahbl_ibus_prot ), + .bmu_ahbl_ibus_req (bmu_dahbl_ibus_req ), + .bmu_ahbl_ibus_req_dp (bmu_dahbl_ibus_req_dp ), + .bmu_ahbl_ibus_seq (bmu_dahbl_ibus_seq ), + .bmu_ahbl_ibus_size (bmu_dahbl_ibus_size ), + .cpurst_b (cpurst_b ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .pad_ahbl_hrdata (pad_dahbl_hrdata ), + .pad_ahbl_hready (pad_dahbl_hready ), + .pad_ahbl_hresp (pad_dahbl_hresp ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + + +assign dahbl_dtu_debug_info[10:0] = dahbl_dbginfo[10:0]; +// &ModuleEnd; @48 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_iahbl_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_iahbl_top.v new file mode 100644 index 0000000000000000000000000000000000000000..34509bf10d67e8141b4dfd01dc70b58a883abb60 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_iahbl_top.v @@ -0,0 +1,262 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_iahbl_top( + bmu_iahbl_dbus_acc_deny, + bmu_iahbl_dbus_addr, + bmu_iahbl_dbus_burst, + bmu_iahbl_dbus_lock, + bmu_iahbl_dbus_lrsc, + bmu_iahbl_dbus_prot, + bmu_iahbl_dbus_req, + bmu_iahbl_dbus_req_dp, + bmu_iahbl_dbus_seq, + bmu_iahbl_dbus_size, + bmu_iahbl_dbus_wdata, + bmu_iahbl_dbus_write, + bmu_iahbl_ibus_acc_deny, + bmu_iahbl_ibus_addr, + bmu_iahbl_ibus_burst, + bmu_iahbl_ibus_prot, + bmu_iahbl_ibus_req, + bmu_iahbl_ibus_req_dp, + bmu_iahbl_ibus_seq, + bmu_iahbl_ibus_size, + cp0_biu_icg_en, + cpurst_b, + forever_cpuclk, + iahbl_bmu_dbus_acc_err, + iahbl_bmu_dbus_data, + iahbl_bmu_dbus_grnt, + iahbl_bmu_dbus_trans_cmplt, + iahbl_bmu_ibus_acc_err, + iahbl_bmu_ibus_data, + iahbl_bmu_ibus_grnt, + iahbl_bmu_ibus_trans_cmplt, + iahbl_dtu_debug_info, + iahbl_pad_haddr, + iahbl_pad_hburst, + iahbl_pad_hlock, + iahbl_pad_hprot, + iahbl_pad_hsize, + iahbl_pad_htrans, + iahbl_pad_hwdata, + iahbl_pad_hwrite, + iahbl_sysio_idle, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_xx_flush, + lsu_xx_warm_up, + pad_iahbl_hrdata, + pad_iahbl_hready, + pad_iahbl_hresp, + pad_yy_icg_scan_en, + rtu_yy_xx_async_flush, + sysio_xx_halt_req +); + +// &Ports; @23 +input bmu_iahbl_dbus_acc_deny; +input [31:0] bmu_iahbl_dbus_addr; +input [2 :0] bmu_iahbl_dbus_burst; +input bmu_iahbl_dbus_lock; +input bmu_iahbl_dbus_lrsc; +input [3 :0] bmu_iahbl_dbus_prot; +input bmu_iahbl_dbus_req; +input bmu_iahbl_dbus_req_dp; +input bmu_iahbl_dbus_seq; +input [1 :0] bmu_iahbl_dbus_size; +input [31:0] bmu_iahbl_dbus_wdata; +input bmu_iahbl_dbus_write; +input bmu_iahbl_ibus_acc_deny; +input [31:0] bmu_iahbl_ibus_addr; +input [2 :0] bmu_iahbl_ibus_burst; +input [3 :0] bmu_iahbl_ibus_prot; +input bmu_iahbl_ibus_req; +input bmu_iahbl_ibus_req_dp; +input bmu_iahbl_ibus_seq; +input [1 :0] bmu_iahbl_ibus_size; +input cp0_biu_icg_en; +input cpurst_b; +input forever_cpuclk; +input lsu_biu_amo_pmp_deny; +input lsu_biu_async_expt_ack; +input lsu_xx_flush; +input lsu_xx_warm_up; +input [31:0] pad_iahbl_hrdata; +input pad_iahbl_hready; +input pad_iahbl_hresp; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +input sysio_xx_halt_req; +output iahbl_bmu_dbus_acc_err; +output [31:0] iahbl_bmu_dbus_data; +output iahbl_bmu_dbus_grnt; +output iahbl_bmu_dbus_trans_cmplt; +output iahbl_bmu_ibus_acc_err; +output [31:0] iahbl_bmu_ibus_data; +output iahbl_bmu_ibus_grnt; +output iahbl_bmu_ibus_trans_cmplt; +output [10:0] iahbl_dtu_debug_info; +output [31:0] iahbl_pad_haddr; +output [2 :0] iahbl_pad_hburst; +output iahbl_pad_hlock; +output [3 :0] iahbl_pad_hprot; +output [2 :0] iahbl_pad_hsize; +output [1 :0] iahbl_pad_htrans; +output [31:0] iahbl_pad_hwdata; +output iahbl_pad_hwrite; +output iahbl_sysio_idle; + +// &Regs; @24 + +// &Wires; @25 +wire bmu_iahbl_dbus_acc_deny; +wire [31:0] bmu_iahbl_dbus_addr; +wire [2 :0] bmu_iahbl_dbus_burst; +wire bmu_iahbl_dbus_lock; +wire bmu_iahbl_dbus_lrsc; +wire [3 :0] bmu_iahbl_dbus_prot; +wire bmu_iahbl_dbus_req; +wire bmu_iahbl_dbus_req_dp; +wire bmu_iahbl_dbus_seq; +wire [1 :0] bmu_iahbl_dbus_size; +wire [31:0] bmu_iahbl_dbus_wdata; +wire bmu_iahbl_dbus_write; +wire bmu_iahbl_ibus_acc_deny; +wire [31:0] bmu_iahbl_ibus_addr; +wire [2 :0] bmu_iahbl_ibus_burst; +wire [3 :0] bmu_iahbl_ibus_prot; +wire bmu_iahbl_ibus_req; +wire bmu_iahbl_ibus_req_dp; +wire bmu_iahbl_ibus_seq; +wire [1 :0] bmu_iahbl_ibus_size; +wire cp0_biu_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire iahbl_bmu_dbus_acc_err; +wire [31:0] iahbl_bmu_dbus_data; +wire iahbl_bmu_dbus_grnt; +wire iahbl_bmu_dbus_trans_cmplt; +wire iahbl_bmu_ibus_acc_err; +wire [31:0] iahbl_bmu_ibus_data; +wire iahbl_bmu_ibus_grnt; +wire iahbl_bmu_ibus_trans_cmplt; +wire iahbl_clk_en; +wire [10:0] iahbl_dbginfo; +wire [10:0] iahbl_dtu_debug_info; +wire iahbl_gated_clk; +wire [31:0] iahbl_pad_haddr; +wire [2 :0] iahbl_pad_hburst; +wire iahbl_pad_hlock; +wire [3 :0] iahbl_pad_hprot; +wire [2 :0] iahbl_pad_hsize; +wire [1 :0] iahbl_pad_htrans; +wire [31:0] iahbl_pad_hwdata; +wire iahbl_pad_hwrite; +wire iahbl_sysio_idle; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_xx_flush; +wire [31:0] pad_iahbl_hrdata; +wire pad_iahbl_hready; +wire pad_iahbl_hresp; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_async_flush; +wire sysio_xx_halt_req; + + +//========================================================== +// Instance Gated Cell for Most Common Use +//========================================================== +// &Instance("gated_clk_cell", "x_pa_iahbl_cpuclk_cell"); @30 +gated_clk_cell x_pa_iahbl_cpuclk_cell ( + .clk_in (forever_cpuclk ), + .clk_out (iahbl_gated_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (iahbl_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @31 +// .global_en (1'b1 ), @32 +// .local_en (iahbl_clk_en ), @33 +// .module_en (cp0_biu_icg_en ), @34 +// .external_en(1'b0 ), @35 +// .clk_out (iahbl_gated_clk)); @36 + +// &ConnRule(s/ahbl/iahbl/); @38 +// &Instance("pa_ahbl_if_fo", "x_pa_ahbl_if"); @40 +// &Connect(.clk_en (ilite_clk_en_f)); @41 +// &Force("input","lsu_xx_warm_up"); @43 +// &Instance("pa_ahbl_if", "x_pa_ahbl_if"); @44 +pa_ahbl_if x_pa_ahbl_if ( + .ahbl_bmu_dbus_acc_err (iahbl_bmu_dbus_acc_err ), + .ahbl_bmu_dbus_data (iahbl_bmu_dbus_data ), + .ahbl_bmu_dbus_grnt (iahbl_bmu_dbus_grnt ), + .ahbl_bmu_dbus_trans_cmplt (iahbl_bmu_dbus_trans_cmplt), + .ahbl_bmu_ibus_acc_err (iahbl_bmu_ibus_acc_err ), + .ahbl_bmu_ibus_data (iahbl_bmu_ibus_data ), + .ahbl_bmu_ibus_grnt (iahbl_bmu_ibus_grnt ), + .ahbl_bmu_ibus_trans_cmplt (iahbl_bmu_ibus_trans_cmplt), + .ahbl_clk_en (iahbl_clk_en ), + .ahbl_dbginfo (iahbl_dbginfo ), + .ahbl_gated_clk (iahbl_gated_clk ), + .ahbl_pad_haddr (iahbl_pad_haddr ), + .ahbl_pad_hburst (iahbl_pad_hburst ), + .ahbl_pad_hlock (iahbl_pad_hlock ), + .ahbl_pad_hprot (iahbl_pad_hprot ), + .ahbl_pad_hsize (iahbl_pad_hsize ), + .ahbl_pad_htrans (iahbl_pad_htrans ), + .ahbl_pad_hwdata (iahbl_pad_hwdata ), + .ahbl_pad_hwrite (iahbl_pad_hwrite ), + .ahbl_sysio_idle (iahbl_sysio_idle ), + .bmu_ahbl_dbus_acc_deny (bmu_iahbl_dbus_acc_deny ), + .bmu_ahbl_dbus_addr (bmu_iahbl_dbus_addr ), + .bmu_ahbl_dbus_burst (bmu_iahbl_dbus_burst ), + .bmu_ahbl_dbus_lock (bmu_iahbl_dbus_lock ), + .bmu_ahbl_dbus_lrsc (bmu_iahbl_dbus_lrsc ), + .bmu_ahbl_dbus_prot (bmu_iahbl_dbus_prot ), + .bmu_ahbl_dbus_req (bmu_iahbl_dbus_req ), + .bmu_ahbl_dbus_req_dp (bmu_iahbl_dbus_req_dp ), + .bmu_ahbl_dbus_seq (bmu_iahbl_dbus_seq ), + .bmu_ahbl_dbus_size (bmu_iahbl_dbus_size ), + .bmu_ahbl_dbus_wdata (bmu_iahbl_dbus_wdata ), + .bmu_ahbl_dbus_write (bmu_iahbl_dbus_write ), + .bmu_ahbl_ibus_acc_deny (bmu_iahbl_ibus_acc_deny ), + .bmu_ahbl_ibus_addr (bmu_iahbl_ibus_addr ), + .bmu_ahbl_ibus_burst (bmu_iahbl_ibus_burst ), + .bmu_ahbl_ibus_prot (bmu_iahbl_ibus_prot ), + .bmu_ahbl_ibus_req (bmu_iahbl_ibus_req ), + .bmu_ahbl_ibus_req_dp (bmu_iahbl_ibus_req_dp ), + .bmu_ahbl_ibus_seq (bmu_iahbl_ibus_seq ), + .bmu_ahbl_ibus_size (bmu_iahbl_ibus_size ), + .cpurst_b (cpurst_b ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .pad_ahbl_hrdata (pad_iahbl_hrdata ), + .pad_ahbl_hready (pad_iahbl_hready ), + .pad_ahbl_hresp (pad_iahbl_hresp ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + +assign iahbl_dtu_debug_info[10:0] = iahbl_dbginfo[10:0]; +// &ModuleEnd; @47 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_sahbl_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_sahbl_top.v new file mode 100644 index 0000000000000000000000000000000000000000..ec052b4b63f2827d752f3b56f23f12d9470f1c90 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/biu/rtl/pa_sahbl_top.v @@ -0,0 +1,268 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_sahbl_top( + bmu_sahbl_dbus_acc_deny, + bmu_sahbl_dbus_addr, + bmu_sahbl_dbus_burst, + bmu_sahbl_dbus_lock, + bmu_sahbl_dbus_lrsc, + bmu_sahbl_dbus_prot, + bmu_sahbl_dbus_req, + bmu_sahbl_dbus_req_dp, + bmu_sahbl_dbus_seq, + bmu_sahbl_dbus_size, + bmu_sahbl_dbus_wdata, + bmu_sahbl_dbus_write, + bmu_sahbl_ibus_acc_deny, + bmu_sahbl_ibus_addr, + bmu_sahbl_ibus_burst, + bmu_sahbl_ibus_prot, + bmu_sahbl_ibus_req, + bmu_sahbl_ibus_req_dp, + bmu_sahbl_ibus_seq, + bmu_sahbl_ibus_size, + clk_en_f, + cp0_biu_icg_en, + cpurst_b, + forever_cpuclk, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_xx_flush, + lsu_xx_warm_up, + pad_sahbl_hrdata, + pad_sahbl_hready, + pad_sahbl_hresp, + pad_yy_icg_scan_en, + sahbl_bmu_dbus_acc_err, + sahbl_bmu_dbus_data, + sahbl_bmu_dbus_grnt, + sahbl_bmu_dbus_trans_cmplt, + sahbl_bmu_ibus_acc_err, + sahbl_bmu_ibus_data, + sahbl_bmu_ibus_grnt, + sahbl_bmu_ibus_trans_cmplt, + sahbl_dtu_debug_info, + sahbl_pad_haddr, + sahbl_pad_hburst, + sahbl_pad_hlock, + sahbl_pad_hprot, + sahbl_pad_hsize, + sahbl_pad_htrans, + sahbl_pad_hwdata, + sahbl_pad_hwrite, + sahbl_sysio_idle, + sysio_xx_halt_req +); + +// &Ports; @23 +input bmu_sahbl_dbus_acc_deny; +input [31:0] bmu_sahbl_dbus_addr; +input [2 :0] bmu_sahbl_dbus_burst; +input bmu_sahbl_dbus_lock; +input bmu_sahbl_dbus_lrsc; +input [3 :0] bmu_sahbl_dbus_prot; +input bmu_sahbl_dbus_req; +input bmu_sahbl_dbus_req_dp; +input bmu_sahbl_dbus_seq; +input [1 :0] bmu_sahbl_dbus_size; +input [31:0] bmu_sahbl_dbus_wdata; +input bmu_sahbl_dbus_write; +input bmu_sahbl_ibus_acc_deny; +input [31:0] bmu_sahbl_ibus_addr; +input [2 :0] bmu_sahbl_ibus_burst; +input [3 :0] bmu_sahbl_ibus_prot; +input bmu_sahbl_ibus_req; +input bmu_sahbl_ibus_req_dp; +input bmu_sahbl_ibus_seq; +input [1 :0] bmu_sahbl_ibus_size; +input clk_en_f; +input cp0_biu_icg_en; +input cpurst_b; +input forever_cpuclk; +input lsu_biu_amo_pmp_deny; +input lsu_biu_async_expt_ack; +input lsu_xx_flush; +input lsu_xx_warm_up; +input [31:0] pad_sahbl_hrdata; +input pad_sahbl_hready; +input pad_sahbl_hresp; +input pad_yy_icg_scan_en; +input sysio_xx_halt_req; +output sahbl_bmu_dbus_acc_err; +output [31:0] sahbl_bmu_dbus_data; +output sahbl_bmu_dbus_grnt; +output sahbl_bmu_dbus_trans_cmplt; +output sahbl_bmu_ibus_acc_err; +output [31:0] sahbl_bmu_ibus_data; +output sahbl_bmu_ibus_grnt; +output sahbl_bmu_ibus_trans_cmplt; +output [10:0] sahbl_dtu_debug_info; +output [31:0] sahbl_pad_haddr; +output [2 :0] sahbl_pad_hburst; +output sahbl_pad_hlock; +output [3 :0] sahbl_pad_hprot; +output [2 :0] sahbl_pad_hsize; +output [1 :0] sahbl_pad_htrans; +output [31:0] sahbl_pad_hwdata; +output sahbl_pad_hwrite; +output sahbl_sysio_idle; + +// &Regs; @24 + +// &Wires; @25 +wire bmu_sahbl_dbus_acc_deny; +wire [31:0] bmu_sahbl_dbus_addr; +wire [2 :0] bmu_sahbl_dbus_burst; +wire bmu_sahbl_dbus_lock; +wire bmu_sahbl_dbus_lrsc; +wire [3 :0] bmu_sahbl_dbus_prot; +wire bmu_sahbl_dbus_req; +wire bmu_sahbl_dbus_req_dp; +wire bmu_sahbl_dbus_seq; +wire [1 :0] bmu_sahbl_dbus_size; +wire [31:0] bmu_sahbl_dbus_wdata; +wire bmu_sahbl_dbus_write; +wire bmu_sahbl_ibus_acc_deny; +wire [31:0] bmu_sahbl_ibus_addr; +wire [2 :0] bmu_sahbl_ibus_burst; +wire [3 :0] bmu_sahbl_ibus_prot; +wire bmu_sahbl_ibus_req; +wire bmu_sahbl_ibus_req_dp; +wire bmu_sahbl_ibus_seq; +wire [1 :0] bmu_sahbl_ibus_size; +wire clk_en_f; +wire cp0_biu_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_xx_flush; +wire lsu_xx_warm_up; +wire [31:0] pad_sahbl_hrdata; +wire pad_sahbl_hready; +wire pad_sahbl_hresp; +wire pad_yy_icg_scan_en; +wire sahbl_bmu_dbus_acc_err; +wire [31:0] sahbl_bmu_dbus_data; +wire sahbl_bmu_dbus_grnt; +wire sahbl_bmu_dbus_trans_cmplt; +wire sahbl_bmu_ibus_acc_err; +wire [31:0] sahbl_bmu_ibus_data; +wire sahbl_bmu_ibus_grnt; +wire sahbl_bmu_ibus_trans_cmplt; +wire sahbl_clk_en; +wire [10:0] sahbl_dbginfo; +wire [10:0] sahbl_dtu_debug_info; +wire sahbl_gated_clk; +wire [31:0] sahbl_pad_haddr; +wire [2 :0] sahbl_pad_hburst; +wire sahbl_pad_hlock; +wire [3 :0] sahbl_pad_hprot; +wire [2 :0] sahbl_pad_hsize; +wire [1 :0] sahbl_pad_htrans; +wire [31:0] sahbl_pad_hwdata; +wire sahbl_pad_hwrite; +wire sahbl_sysio_idle; +wire sysio_xx_halt_req; + + +//========================================================== +// Instance Gated Cell for Most Common Use +//========================================================== +// &Instance("gated_clk_cell", "x_pa_sahbl_cpuclk_cell"); @30 +gated_clk_cell x_pa_sahbl_cpuclk_cell ( + .clk_in (forever_cpuclk ), + .clk_out (sahbl_gated_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (sahbl_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @31 +// .global_en (1'b1 ), @32 +// .local_en (sahbl_clk_en ), @33 +// .module_en (cp0_biu_icg_en ), @34 +// .external_en(1'b0 ), @35 +// .clk_out (sahbl_gated_clk)); @36 + +// &ConnRule(s/ahbl/sahbl/); @38 +// &Instance("pa_ahbl_if_fo", "x_pa_ahbl_if"); @40 +pa_ahbl_if_fo x_pa_ahbl_if ( + .ahbl_bmu_dbus_acc_err (sahbl_bmu_dbus_acc_err ), + .ahbl_bmu_dbus_data (sahbl_bmu_dbus_data ), + .ahbl_bmu_dbus_grnt (sahbl_bmu_dbus_grnt ), + .ahbl_bmu_dbus_trans_cmplt (sahbl_bmu_dbus_trans_cmplt), + .ahbl_bmu_ibus_acc_err (sahbl_bmu_ibus_acc_err ), + .ahbl_bmu_ibus_data (sahbl_bmu_ibus_data ), + .ahbl_bmu_ibus_grnt (sahbl_bmu_ibus_grnt ), + .ahbl_bmu_ibus_trans_cmplt (sahbl_bmu_ibus_trans_cmplt), + .ahbl_clk_en (sahbl_clk_en ), + .ahbl_dbginfo (sahbl_dbginfo ), + .ahbl_gated_clk (sahbl_gated_clk ), + .ahbl_pad_haddr (sahbl_pad_haddr ), + .ahbl_pad_hburst (sahbl_pad_hburst ), + .ahbl_pad_hlock (sahbl_pad_hlock ), + .ahbl_pad_hprot (sahbl_pad_hprot ), + .ahbl_pad_hsize (sahbl_pad_hsize ), + .ahbl_pad_htrans (sahbl_pad_htrans ), + .ahbl_pad_hwdata (sahbl_pad_hwdata ), + .ahbl_pad_hwrite (sahbl_pad_hwrite ), + .ahbl_sysio_idle (sahbl_sysio_idle ), + .bmu_ahbl_dbus_acc_deny (bmu_sahbl_dbus_acc_deny ), + .bmu_ahbl_dbus_addr (bmu_sahbl_dbus_addr ), + .bmu_ahbl_dbus_burst (bmu_sahbl_dbus_burst ), + .bmu_ahbl_dbus_lock (bmu_sahbl_dbus_lock ), + .bmu_ahbl_dbus_lrsc (bmu_sahbl_dbus_lrsc ), + .bmu_ahbl_dbus_prot (bmu_sahbl_dbus_prot ), + .bmu_ahbl_dbus_req (bmu_sahbl_dbus_req ), + .bmu_ahbl_dbus_req_dp (bmu_sahbl_dbus_req_dp ), + .bmu_ahbl_dbus_seq (bmu_sahbl_dbus_seq ), + .bmu_ahbl_dbus_size (bmu_sahbl_dbus_size ), + .bmu_ahbl_dbus_wdata (bmu_sahbl_dbus_wdata ), + .bmu_ahbl_dbus_write (bmu_sahbl_dbus_write ), + .bmu_ahbl_ibus_acc_deny (bmu_sahbl_ibus_acc_deny ), + .bmu_ahbl_ibus_addr (bmu_sahbl_ibus_addr ), + .bmu_ahbl_ibus_burst (bmu_sahbl_ibus_burst ), + .bmu_ahbl_ibus_prot (bmu_sahbl_ibus_prot ), + .bmu_ahbl_ibus_req (bmu_sahbl_ibus_req ), + .bmu_ahbl_ibus_req_dp (bmu_sahbl_ibus_req_dp ), + .bmu_ahbl_ibus_seq (bmu_sahbl_ibus_seq ), + .bmu_ahbl_ibus_size (bmu_sahbl_ibus_size ), + .clk_en (clk_en_f ), + .cpurst_b (cpurst_b ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_ahbl_hrdata (pad_sahbl_hrdata ), + .pad_ahbl_hready (pad_sahbl_hready ), + .pad_ahbl_hresp (pad_sahbl_hresp ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + +// &Connect(.clk_en(clk_en_f)); @41 + +assign sahbl_dtu_debug_info[10:0] = sahbl_dbginfo[10:0]; + +// &Force("input", "lsu_xx_warm_up"); @46 +// &Instance("pa_ahbl_if", "x_pa_ahbl_if"); @47 +// &Force("nonport","sahbl_dbginfo"); @48 + +// &ModuleEnd; @51 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_bus_if.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_bus_if.v new file mode 100644 index 0000000000000000000000000000000000000000..0feed69d8bd6ab77e917e43efeda5af587e19496 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_bus_if.v @@ -0,0 +1,445 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_bmu_bus_if( + bmu_clk, + bmu_dahbl_xx_acc_deny, + bmu_dahbl_xx_addr, + bmu_dahbl_xx_burst, + bmu_dahbl_xx_prot, + bmu_dahbl_xx_req, + bmu_dahbl_xx_req_dp, + bmu_dahbl_xx_seq, + bmu_dahbl_xx_size, + bmu_dahbl_xx_wdata, + bmu_dahbl_xx_write, + bmu_iahbl_xx_acc_deny, + bmu_iahbl_xx_addr, + bmu_iahbl_xx_burst, + bmu_iahbl_xx_prot, + bmu_iahbl_xx_req, + bmu_iahbl_xx_req_dp, + bmu_iahbl_xx_seq, + bmu_iahbl_xx_size, + bmu_iahbl_xx_wdata, + bmu_iahbl_xx_write, + bmu_sahbl_xx_acc_deny, + bmu_sahbl_xx_addr, + bmu_sahbl_xx_burst, + bmu_sahbl_xx_prot, + bmu_sahbl_xx_req, + bmu_sahbl_xx_req_dp, + bmu_sahbl_xx_seq, + bmu_sahbl_xx_size, + bmu_sahbl_xx_wdata, + bmu_sahbl_xx_write, + bmu_tcipif_xx_acc_deny, + bmu_tcipif_xx_addr, + bmu_tcipif_xx_req, + bmu_tcipif_xx_req_dp, + bmu_tcipif_xx_size, + bmu_tcipif_xx_supv_mode, + bmu_tcipif_xx_wdata, + bmu_tcipif_xx_write, + bmu_tt_acc_err, + bmu_tt_clk_en, + bmu_tt_grant, + bmu_tt_rdata, + bmu_tt_trans_cmplt, + cpurst_b, + dahbl_bmu_xx_acc_err, + dahbl_bmu_xx_data, + dahbl_bmu_xx_grnt, + dahbl_bmu_xx_trans_cmplt, + iahbl_bmu_xx_acc_err, + iahbl_bmu_xx_data, + iahbl_bmu_xx_grnt, + iahbl_bmu_xx_trans_cmplt, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_cpu_tcip_base, + sahbl_bmu_xx_acc_err, + sahbl_bmu_xx_data, + sahbl_bmu_xx_grnt, + sahbl_bmu_xx_trans_cmplt, + tcipif_bmu_xx_acc_err, + tcipif_bmu_xx_data, + tcipif_bmu_xx_grnt, + tcipif_bmu_xx_trans_cmplt, + tt_bmu_acc_deny, + tt_bmu_addr, + tt_bmu_burst, + tt_bmu_data_req, + tt_bmu_prot, + tt_bmu_req, + tt_bmu_seq, + tt_bmu_size, + tt_bmu_wdata, + tt_bmu_write, + xx_dbginfo +); + +// &Ports; @25 +input bmu_clk; +input cpurst_b; +input dahbl_bmu_xx_acc_err; +input [31:0] dahbl_bmu_xx_data; +input dahbl_bmu_xx_grnt; +input dahbl_bmu_xx_trans_cmplt; +input iahbl_bmu_xx_acc_err; +input [31:0] iahbl_bmu_xx_data; +input iahbl_bmu_xx_grnt; +input iahbl_bmu_xx_trans_cmplt; +input [11:0] pad_bmu_dahbl_base; +input [11:0] pad_bmu_dahbl_mask; +input [11:0] pad_bmu_iahbl_base; +input [11:0] pad_bmu_iahbl_mask; +input [31:0] pad_cpu_tcip_base; +input sahbl_bmu_xx_acc_err; +input [31:0] sahbl_bmu_xx_data; +input sahbl_bmu_xx_grnt; +input sahbl_bmu_xx_trans_cmplt; +input tcipif_bmu_xx_acc_err; +input [31:0] tcipif_bmu_xx_data; +input tcipif_bmu_xx_grnt; +input tcipif_bmu_xx_trans_cmplt; +input tt_bmu_acc_deny; +input [31:0] tt_bmu_addr; +input [2 :0] tt_bmu_burst; +input tt_bmu_data_req; +input [3 :0] tt_bmu_prot; +input tt_bmu_req; +input tt_bmu_seq; +input [1 :0] tt_bmu_size; +input [31:0] tt_bmu_wdata; +input tt_bmu_write; +output bmu_dahbl_xx_acc_deny; +output [31:0] bmu_dahbl_xx_addr; +output [2 :0] bmu_dahbl_xx_burst; +output [3 :0] bmu_dahbl_xx_prot; +output bmu_dahbl_xx_req; +output bmu_dahbl_xx_req_dp; +output bmu_dahbl_xx_seq; +output [1 :0] bmu_dahbl_xx_size; +output [31:0] bmu_dahbl_xx_wdata; +output bmu_dahbl_xx_write; +output bmu_iahbl_xx_acc_deny; +output [31:0] bmu_iahbl_xx_addr; +output [2 :0] bmu_iahbl_xx_burst; +output [3 :0] bmu_iahbl_xx_prot; +output bmu_iahbl_xx_req; +output bmu_iahbl_xx_req_dp; +output bmu_iahbl_xx_seq; +output [1 :0] bmu_iahbl_xx_size; +output [31:0] bmu_iahbl_xx_wdata; +output bmu_iahbl_xx_write; +output bmu_sahbl_xx_acc_deny; +output [31:0] bmu_sahbl_xx_addr; +output [2 :0] bmu_sahbl_xx_burst; +output [3 :0] bmu_sahbl_xx_prot; +output bmu_sahbl_xx_req; +output bmu_sahbl_xx_req_dp; +output bmu_sahbl_xx_seq; +output [1 :0] bmu_sahbl_xx_size; +output [31:0] bmu_sahbl_xx_wdata; +output bmu_sahbl_xx_write; +output bmu_tcipif_xx_acc_deny; +output [31:0] bmu_tcipif_xx_addr; +output bmu_tcipif_xx_req; +output bmu_tcipif_xx_req_dp; +output [1 :0] bmu_tcipif_xx_size; +output bmu_tcipif_xx_supv_mode; +output [31:0] bmu_tcipif_xx_wdata; +output bmu_tcipif_xx_write; +output bmu_tt_acc_err; +output bmu_tt_clk_en; +output bmu_tt_grant; +output [31:0] bmu_tt_rdata; +output bmu_tt_trans_cmplt; +output [1 :0] xx_dbginfo; + +// &Regs; @26 +reg [1 :0] bmu_cur_state; +reg [1 :0] bmu_next_state; +reg [3 :0] bus_sel_f; + +// &Wires; @27 +wire bmu_clk; +wire bmu_dahbl_xx_acc_deny; +wire [31:0] bmu_dahbl_xx_addr; +wire [2 :0] bmu_dahbl_xx_burst; +wire [3 :0] bmu_dahbl_xx_prot; +wire bmu_dahbl_xx_req; +wire bmu_dahbl_xx_req_dp; +wire bmu_dahbl_xx_seq; +wire [1 :0] bmu_dahbl_xx_size; +wire [31:0] bmu_dahbl_xx_wdata; +wire bmu_dahbl_xx_write; +wire bmu_iahbl_xx_acc_deny; +wire [31:0] bmu_iahbl_xx_addr; +wire [2 :0] bmu_iahbl_xx_burst; +wire [3 :0] bmu_iahbl_xx_prot; +wire bmu_iahbl_xx_req; +wire bmu_iahbl_xx_req_dp; +wire bmu_iahbl_xx_seq; +wire [1 :0] bmu_iahbl_xx_size; +wire [31:0] bmu_iahbl_xx_wdata; +wire bmu_iahbl_xx_write; +wire bmu_sahbl_xx_acc_deny; +wire [31:0] bmu_sahbl_xx_addr; +wire [2 :0] bmu_sahbl_xx_burst; +wire [3 :0] bmu_sahbl_xx_prot; +wire bmu_sahbl_xx_req; +wire bmu_sahbl_xx_req_dp; +wire bmu_sahbl_xx_seq; +wire [1 :0] bmu_sahbl_xx_size; +wire [31:0] bmu_sahbl_xx_wdata; +wire bmu_sahbl_xx_write; +wire bmu_tcipif_xx_acc_deny; +wire [31:0] bmu_tcipif_xx_addr; +wire bmu_tcipif_xx_req; +wire bmu_tcipif_xx_req_dp; +wire [1 :0] bmu_tcipif_xx_size; +wire bmu_tcipif_xx_supv_mode; +wire [31:0] bmu_tcipif_xx_wdata; +wire bmu_tcipif_xx_write; +wire bmu_tt_acc_err; +wire bmu_tt_clk_en; +wire bmu_tt_grant; +wire [31:0] bmu_tt_rdata; +wire bmu_tt_trans_cmplt; +wire bus_acc_err; +wire bus_cmplt; +wire bus_grant; +wire [3 :0] bus_sel; +wire bus_sel_same; +wire cpurst_b; +wire dahbl_bmu_xx_acc_err; +wire [31:0] dahbl_bmu_xx_data; +wire dahbl_bmu_xx_grnt; +wire dahbl_bmu_xx_trans_cmplt; +wire dahbl_hit; +wire dahbl_sel_pred; +wire iahbl_bmu_xx_acc_err; +wire [31:0] iahbl_bmu_xx_data; +wire iahbl_bmu_xx_grnt; +wire iahbl_bmu_xx_trans_cmplt; +wire iahbl_hit; +wire iahbl_sel_pred; +wire new_req_en; +wire [11:0] pad_bmu_dahbl_base; +wire [11:0] pad_bmu_dahbl_mask; +wire [11:0] pad_bmu_iahbl_base; +wire [11:0] pad_bmu_iahbl_mask; +wire [31:0] pad_cpu_tcip_base; +wire req_en; +wire sahbl_bmu_xx_acc_err; +wire [31:0] sahbl_bmu_xx_data; +wire sahbl_bmu_xx_grnt; +wire sahbl_bmu_xx_trans_cmplt; +wire sahbl_hit; +wire sahbl_sel_pred; +wire tcip_sel_pred; +wire [15:0] tcipif_addr_low; +wire tcipif_bmu_xx_acc_err; +wire [31:0] tcipif_bmu_xx_data; +wire tcipif_bmu_xx_grnt; +wire tcipif_bmu_xx_trans_cmplt; +wire tcipif_hit; +wire tt_bmu_acc_deny; +wire [31:0] tt_bmu_addr; +wire [2 :0] tt_bmu_burst; +wire tt_bmu_data_req; +wire [3 :0] tt_bmu_prot; +wire tt_bmu_req; +wire tt_bmu_seq; +wire [1 :0] tt_bmu_size; +wire [31:0] tt_bmu_wdata; +wire tt_bmu_write; +wire [1 :0] xx_dbginfo; + + +//========================================================== +// compare base address with ahbl base addr +//========================================================== +assign iahbl_hit = ((tt_bmu_addr[31:20] & pad_bmu_iahbl_mask[11:0]) == pad_bmu_iahbl_base[11:0]) + & ~tcipif_hit & ~dahbl_hit; + +assign dahbl_hit = ((tt_bmu_addr[31:20] & pad_bmu_dahbl_mask[11:0]) == pad_bmu_dahbl_base[11:0]) + & ~tcipif_hit; + +// &Force("input", "pad_cpu_tcip_base"); @47 +// &Force("bus","pad_cpu_tcip_base",31,0); @48 +// &Force("bus","tt_bmu_addr",31,0); @49 +assign tcipif_hit = (tt_bmu_addr[31:28] == pad_cpu_tcip_base[31:28]); + +assign sahbl_hit = ~dahbl_hit & ~iahbl_hit & ~tcipif_hit; + +assign bus_sel[3:0] = {sahbl_hit,tcipif_hit,iahbl_hit,dahbl_hit}; + +//========================================================== +// FSM +//========================================================== +parameter REQ = 2'b00; +parameter WFG = 2'b01; +parameter WFD = 2'b10; + +always @(posedge bmu_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bmu_cur_state[1:0] <= REQ; + else + bmu_cur_state[1:0] <= bmu_next_state[1:0]; +end +// &CombBeg; @73 +always @( bus_grant + or bus_cmplt + or bus_acc_err + or bmu_cur_state[1:0] + or bus_sel_same + or tt_bmu_req) +begin + case(bmu_cur_state[1:0]) + REQ: begin + if (tt_bmu_req) + bmu_next_state[1:0] = bus_grant ? WFD : WFG; + else + bmu_next_state[1:0] = REQ; + end + WFG:begin + if (bus_grant) + bmu_next_state[1:0] = WFD; + else + bmu_next_state[1:0] = WFG; + end + WFD: begin + if (bus_cmplt)begin + if (tt_bmu_req & bus_sel_same & !bus_acc_err) + bmu_next_state[1:0] = bus_grant ? WFD : WFG; + else + bmu_next_state[1:0] = REQ; + end + else + bmu_next_state[1:0] = WFD; + end + default: bmu_next_state[1:0] = REQ; + endcase +// &CombEnd; @99 +end + +assign req_en = (bmu_cur_state[1:0] == REQ) | + (bmu_cur_state[1:0] == WFG) | + (bmu_cur_state[1:0] == WFD) & bus_sel_same; + +assign new_req_en = (bmu_cur_state[1:0] == REQ); + +always @(posedge bmu_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bus_sel_f[3:0] <= 4'b0; + else if (tt_bmu_req & new_req_en) + bus_sel_f[3:0] <= bus_sel[3:0]; +end +assign bus_sel_same = (bus_sel_f[3:0] == bus_sel[3:0]); + +assign sahbl_sel_pred = bus_sel_f[3]; +assign dahbl_sel_pred = bus_sel_f[0]; +assign iahbl_sel_pred = bus_sel_f[1]; +assign tcip_sel_pred = bus_sel_f[2]; +//========================================================== +// interface +//========================================================== +//input +assign bus_grant = iahbl_hit & iahbl_bmu_xx_grnt | + dahbl_hit & dahbl_bmu_xx_grnt | + tcipif_hit & tcipif_bmu_xx_grnt | + sahbl_hit & sahbl_bmu_xx_grnt; +assign bus_cmplt = iahbl_bmu_xx_trans_cmplt | + dahbl_bmu_xx_trans_cmplt | + tcipif_bmu_xx_trans_cmplt | + sahbl_bmu_xx_trans_cmplt; +assign bus_acc_err = iahbl_bmu_xx_acc_err | + dahbl_bmu_xx_acc_err | + tcipif_bmu_xx_acc_err| + sahbl_bmu_xx_acc_err; + +assign bmu_tt_grant = bus_grant & req_en; +assign bmu_tt_trans_cmplt = bus_cmplt; +assign bmu_tt_acc_err = bus_acc_err; +assign bmu_tt_rdata[31:0] = ({32{bus_sel_f[0]}} & dahbl_bmu_xx_data[31:0]) | + ({32{bus_sel_f[1]}} & iahbl_bmu_xx_data[31:0]) | + ({32{bus_sel_f[2]}} & tcipif_bmu_xx_data[31:0]) | + ({32{bus_sel_f[3]}} & sahbl_bmu_xx_data[31:0]); + +//-------------------------------------- +//output +//-------------------------------------- +//interface to ILITE +assign bmu_iahbl_xx_req = tt_bmu_req & iahbl_hit & req_en & iahbl_sel_pred; +assign bmu_iahbl_xx_req_dp = tt_bmu_data_req & iahbl_sel_pred; +assign bmu_iahbl_xx_acc_deny = tt_bmu_acc_deny; +assign bmu_iahbl_xx_size[1:0] = tt_bmu_size[1:0]; +assign bmu_iahbl_xx_addr[31:0] = tt_bmu_addr[31:0]; +assign bmu_iahbl_xx_prot[3:0] = tt_bmu_prot[3:0]; +assign bmu_iahbl_xx_write = tt_bmu_write; +assign bmu_iahbl_xx_wdata[31:0] = tt_bmu_wdata[31:0]; +assign bmu_iahbl_xx_seq = tt_bmu_seq; +assign bmu_iahbl_xx_burst[2:0] = tt_bmu_burst[2:0]; + +//interface to DL +assign bmu_dahbl_xx_req = tt_bmu_req & dahbl_hit & req_en & dahbl_sel_pred; +assign bmu_dahbl_xx_req_dp = tt_bmu_data_req & dahbl_sel_pred; +assign bmu_dahbl_xx_acc_deny = tt_bmu_acc_deny; +assign bmu_dahbl_xx_size[1:0] = tt_bmu_size[1:0]; +assign bmu_dahbl_xx_addr[31:0] = tt_bmu_addr[31:0]; +assign bmu_dahbl_xx_prot[3:0] = tt_bmu_prot[3:0]; +assign bmu_dahbl_xx_write = tt_bmu_write; +assign bmu_dahbl_xx_wdata[31:0] = tt_bmu_wdata[31:0]; +assign bmu_dahbl_xx_seq = tt_bmu_seq; +assign bmu_dahbl_xx_burst[2:0] = tt_bmu_burst[2:0]; + +//tcipif +assign bmu_tcipif_xx_req = tt_bmu_req & req_en & tcipif_hit & tcip_sel_pred; +assign bmu_tcipif_xx_req_dp = tt_bmu_data_req & tcip_sel_pred; +assign bmu_tcipif_xx_acc_deny = tt_bmu_acc_deny; +assign bmu_tcipif_xx_write = tt_bmu_write; +assign bmu_tcipif_xx_size[1:0] = tt_bmu_size[1:0]; +assign bmu_tcipif_xx_supv_mode = tt_bmu_prot[1]; +assign bmu_tcipif_xx_wdata[31:0] = tt_bmu_wdata[31:0]; +assign bmu_tcipif_xx_addr[31:0] = {tt_bmu_addr[31:16], tcipif_addr_low[15:0]}; +assign tcipif_addr_low[15:0] = {16{tcipif_hit}} & tt_bmu_addr[15:0]; + +//sahbl +assign bmu_sahbl_xx_req = tt_bmu_req & sahbl_hit & req_en & sahbl_sel_pred; +assign bmu_sahbl_xx_req_dp = tt_bmu_data_req & sahbl_sel_pred; +assign bmu_sahbl_xx_acc_deny = tt_bmu_acc_deny; +assign bmu_sahbl_xx_size[1:0] = tt_bmu_size[1:0]; +assign bmu_sahbl_xx_addr[31:0] = tt_bmu_addr[31:0]; +assign bmu_sahbl_xx_prot[3:0] = tt_bmu_prot[3:0]; +assign bmu_sahbl_xx_write = tt_bmu_write; +assign bmu_sahbl_xx_wdata[31:0] = tt_bmu_wdata[31:0]; +assign bmu_sahbl_xx_seq = tt_bmu_seq; +assign bmu_sahbl_xx_burst[2:0] = tt_bmu_burst[2:0]; + +assign bmu_tt_clk_en = tt_bmu_data_req | ~(bmu_cur_state[1:0] == REQ); + +assign xx_dbginfo[1:0] = bmu_cur_state[1:0]; + +// &ModuleEnd; @227 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_dbus_if.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_dbus_if.v new file mode 100644 index 0000000000000000000000000000000000000000..7208499b9249c0db1f9398755e5b32456dcd092d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_dbus_if.v @@ -0,0 +1,486 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_bmu_dbus_if( + bmu_clk, + bmu_dahbl_dbus_acc_deny, + bmu_dahbl_dbus_addr, + bmu_dahbl_dbus_burst, + bmu_dahbl_dbus_lock, + bmu_dahbl_dbus_lrsc, + bmu_dahbl_dbus_prot, + bmu_dahbl_dbus_req, + bmu_dahbl_dbus_req_dp, + bmu_dahbl_dbus_seq, + bmu_dahbl_dbus_size, + bmu_dahbl_dbus_wdata, + bmu_dahbl_dbus_write, + bmu_iahbl_dbus_acc_deny, + bmu_iahbl_dbus_addr, + bmu_iahbl_dbus_burst, + bmu_iahbl_dbus_lock, + bmu_iahbl_dbus_lrsc, + bmu_iahbl_dbus_prot, + bmu_iahbl_dbus_req, + bmu_iahbl_dbus_req_dp, + bmu_iahbl_dbus_seq, + bmu_iahbl_dbus_size, + bmu_iahbl_dbus_wdata, + bmu_iahbl_dbus_write, + bmu_lsu_acc_err, + bmu_lsu_clk_en, + bmu_lsu_grant, + bmu_lsu_rdata, + bmu_lsu_trans_cmplt, + bmu_sahbl_dbus_acc_deny, + bmu_sahbl_dbus_addr, + bmu_sahbl_dbus_burst, + bmu_sahbl_dbus_lock, + bmu_sahbl_dbus_lrsc, + bmu_sahbl_dbus_prot, + bmu_sahbl_dbus_req, + bmu_sahbl_dbus_req_dp, + bmu_sahbl_dbus_seq, + bmu_sahbl_dbus_size, + bmu_sahbl_dbus_wdata, + bmu_sahbl_dbus_write, + bmu_tcipif_dbus_acc_deny, + bmu_tcipif_dbus_addr, + bmu_tcipif_dbus_req, + bmu_tcipif_dbus_req_dp, + bmu_tcipif_dbus_size, + bmu_tcipif_dbus_supv_mode, + bmu_tcipif_dbus_wdata, + bmu_tcipif_dbus_write, + cpurst_b, + dahbl_bmu_dbus_acc_err, + dahbl_bmu_dbus_data, + dahbl_bmu_dbus_grnt, + dahbl_bmu_dbus_trans_cmplt, + dbus_dbginfo, + iahbl_bmu_dbus_acc_err, + iahbl_bmu_dbus_data, + iahbl_bmu_dbus_grnt, + iahbl_bmu_dbus_trans_cmplt, + lsu_bmu_acc_deny, + lsu_bmu_addr, + lsu_bmu_burst, + lsu_bmu_lock, + lsu_bmu_lrsc, + lsu_bmu_prot, + lsu_bmu_req, + lsu_bmu_req_dp, + lsu_bmu_seq, + lsu_bmu_size, + lsu_bmu_wdata, + lsu_bmu_write, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_cpu_tcip_base, + rtu_yy_xx_async_flush, + sahbl_bmu_dbus_acc_err, + sahbl_bmu_dbus_data, + sahbl_bmu_dbus_grnt, + sahbl_bmu_dbus_trans_cmplt, + tcipif_bmu_dbus_acc_err, + tcipif_bmu_dbus_data, + tcipif_bmu_dbus_grnt, + tcipif_bmu_dbus_trans_cmplt +); + +// &Ports; @22 +input bmu_clk; +input cpurst_b; +input dahbl_bmu_dbus_acc_err; +input [31:0] dahbl_bmu_dbus_data; +input dahbl_bmu_dbus_grnt; +input dahbl_bmu_dbus_trans_cmplt; +input iahbl_bmu_dbus_acc_err; +input [31:0] iahbl_bmu_dbus_data; +input iahbl_bmu_dbus_grnt; +input iahbl_bmu_dbus_trans_cmplt; +input lsu_bmu_acc_deny; +input [31:0] lsu_bmu_addr; +input [2 :0] lsu_bmu_burst; +input lsu_bmu_lock; +input lsu_bmu_lrsc; +input [3 :0] lsu_bmu_prot; +input lsu_bmu_req; +input lsu_bmu_req_dp; +input lsu_bmu_seq; +input [1 :0] lsu_bmu_size; +input [31:0] lsu_bmu_wdata; +input lsu_bmu_write; +input [11:0] pad_bmu_dahbl_base; +input [11:0] pad_bmu_dahbl_mask; +input [11:0] pad_bmu_iahbl_base; +input [11:0] pad_bmu_iahbl_mask; +input [31:0] pad_cpu_tcip_base; +input rtu_yy_xx_async_flush; +input sahbl_bmu_dbus_acc_err; +input [31:0] sahbl_bmu_dbus_data; +input sahbl_bmu_dbus_grnt; +input sahbl_bmu_dbus_trans_cmplt; +input tcipif_bmu_dbus_acc_err; +input [31:0] tcipif_bmu_dbus_data; +input tcipif_bmu_dbus_grnt; +input tcipif_bmu_dbus_trans_cmplt; +output bmu_dahbl_dbus_acc_deny; +output [31:0] bmu_dahbl_dbus_addr; +output [2 :0] bmu_dahbl_dbus_burst; +output bmu_dahbl_dbus_lock; +output bmu_dahbl_dbus_lrsc; +output [3 :0] bmu_dahbl_dbus_prot; +output bmu_dahbl_dbus_req; +output bmu_dahbl_dbus_req_dp; +output bmu_dahbl_dbus_seq; +output [1 :0] bmu_dahbl_dbus_size; +output [31:0] bmu_dahbl_dbus_wdata; +output bmu_dahbl_dbus_write; +output bmu_iahbl_dbus_acc_deny; +output [31:0] bmu_iahbl_dbus_addr; +output [2 :0] bmu_iahbl_dbus_burst; +output bmu_iahbl_dbus_lock; +output bmu_iahbl_dbus_lrsc; +output [3 :0] bmu_iahbl_dbus_prot; +output bmu_iahbl_dbus_req; +output bmu_iahbl_dbus_req_dp; +output bmu_iahbl_dbus_seq; +output [1 :0] bmu_iahbl_dbus_size; +output [31:0] bmu_iahbl_dbus_wdata; +output bmu_iahbl_dbus_write; +output bmu_lsu_acc_err; +output bmu_lsu_clk_en; +output bmu_lsu_grant; +output [31:0] bmu_lsu_rdata; +output bmu_lsu_trans_cmplt; +output bmu_sahbl_dbus_acc_deny; +output [31:0] bmu_sahbl_dbus_addr; +output [2 :0] bmu_sahbl_dbus_burst; +output bmu_sahbl_dbus_lock; +output bmu_sahbl_dbus_lrsc; +output [3 :0] bmu_sahbl_dbus_prot; +output bmu_sahbl_dbus_req; +output bmu_sahbl_dbus_req_dp; +output bmu_sahbl_dbus_seq; +output [1 :0] bmu_sahbl_dbus_size; +output [31:0] bmu_sahbl_dbus_wdata; +output bmu_sahbl_dbus_write; +output bmu_tcipif_dbus_acc_deny; +output [31:0] bmu_tcipif_dbus_addr; +output bmu_tcipif_dbus_req; +output bmu_tcipif_dbus_req_dp; +output [1 :0] bmu_tcipif_dbus_size; +output bmu_tcipif_dbus_supv_mode; +output [31:0] bmu_tcipif_dbus_wdata; +output bmu_tcipif_dbus_write; +output [1 :0] dbus_dbginfo; + +// &Regs; @23 +reg [1 :0] bmu_cur_state; +reg [1 :0] bmu_next_state; +reg [3 :0] bus_sel_f; + +// &Wires; @24 +wire bmu_clk; +wire bmu_dahbl_dbus_acc_deny; +wire [31:0] bmu_dahbl_dbus_addr; +wire [2 :0] bmu_dahbl_dbus_burst; +wire bmu_dahbl_dbus_lock; +wire bmu_dahbl_dbus_lrsc; +wire [3 :0] bmu_dahbl_dbus_prot; +wire bmu_dahbl_dbus_req; +wire bmu_dahbl_dbus_req_dp; +wire bmu_dahbl_dbus_seq; +wire [1 :0] bmu_dahbl_dbus_size; +wire [31:0] bmu_dahbl_dbus_wdata; +wire bmu_dahbl_dbus_write; +wire bmu_iahbl_dbus_acc_deny; +wire [31:0] bmu_iahbl_dbus_addr; +wire [2 :0] bmu_iahbl_dbus_burst; +wire bmu_iahbl_dbus_lock; +wire bmu_iahbl_dbus_lrsc; +wire [3 :0] bmu_iahbl_dbus_prot; +wire bmu_iahbl_dbus_req; +wire bmu_iahbl_dbus_req_dp; +wire bmu_iahbl_dbus_seq; +wire [1 :0] bmu_iahbl_dbus_size; +wire [31:0] bmu_iahbl_dbus_wdata; +wire bmu_iahbl_dbus_write; +wire bmu_lsu_acc_err; +wire bmu_lsu_clk_en; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire bmu_req_vld; +wire bmu_sahbl_dbus_acc_deny; +wire [31:0] bmu_sahbl_dbus_addr; +wire [2 :0] bmu_sahbl_dbus_burst; +wire bmu_sahbl_dbus_lock; +wire bmu_sahbl_dbus_lrsc; +wire [3 :0] bmu_sahbl_dbus_prot; +wire bmu_sahbl_dbus_req; +wire bmu_sahbl_dbus_req_dp; +wire bmu_sahbl_dbus_seq; +wire [1 :0] bmu_sahbl_dbus_size; +wire [31:0] bmu_sahbl_dbus_wdata; +wire bmu_sahbl_dbus_write; +wire bmu_tcipif_dbus_acc_deny; +wire [31:0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31:0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire [3 :0] bus_sel; +wire bus_sel_same; +wire cpurst_b; +wire dahbl_bmu_dbus_acc_err; +wire [31:0] dahbl_bmu_dbus_data; +wire dahbl_bmu_dbus_grnt; +wire dahbl_bmu_dbus_trans_cmplt; +wire dahbl_hit; +wire dahbl_sel_pred; +wire dbus_acc_err; +wire dbus_cmplt; +wire [1 :0] dbus_dbginfo; +wire dbus_grant; +wire iahbl_bmu_dbus_acc_err; +wire [31:0] iahbl_bmu_dbus_data; +wire iahbl_bmu_dbus_grnt; +wire iahbl_bmu_dbus_trans_cmplt; +wire iahbl_hit; +wire iahbl_sel_pred; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire new_req_en; +wire [11:0] pad_bmu_dahbl_base; +wire [11:0] pad_bmu_dahbl_mask; +wire [11:0] pad_bmu_iahbl_base; +wire [11:0] pad_bmu_iahbl_mask; +wire [31:0] pad_cpu_tcip_base; +wire req_en; +wire rtu_yy_xx_async_flush; +wire sahbl_bmu_dbus_acc_err; +wire [31:0] sahbl_bmu_dbus_data; +wire sahbl_bmu_dbus_grnt; +wire sahbl_bmu_dbus_trans_cmplt; +wire sahbl_hit; +wire sahbl_sel_pred; +wire tcip_sel_pred; +wire [15:0] tcipif_addr_low; +wire tcipif_bmu_dbus_acc_err; +wire [31:0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_hit; + + +//========================================================== +// request direction checking +//========================================================== +assign iahbl_hit = ((lsu_bmu_addr[31:20] & pad_bmu_iahbl_mask[11:0]) == pad_bmu_iahbl_base[11:0]) + & ~tcipif_hit & ~dahbl_hit; + +assign dahbl_hit = ((lsu_bmu_addr[31:20] & pad_bmu_dahbl_mask[11:0]) == pad_bmu_dahbl_base[11:0]) + & ~tcipif_hit; + +// &Force("input", "pad_cpu_tcip_base"); @44 +// &Force("bus","pad_cpu_tcip_base",31,0); @45 +assign tcipif_hit = (lsu_bmu_addr[31:28] == pad_cpu_tcip_base[31:28]); + +assign sahbl_hit = ~dahbl_hit & ~iahbl_hit & ~tcipif_hit; + +assign bus_sel[3:0] = {sahbl_hit,tcipif_hit,iahbl_hit,dahbl_hit}; + +//========================================================== +// FSM +//========================================================== +parameter REQ = 2'b00; +parameter WFG = 2'b11; +parameter WFD = 2'b01; + +always @(posedge bmu_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bmu_cur_state[1:0] <= REQ; + else if (rtu_yy_xx_async_flush) + bmu_cur_state[1:0] <= REQ; + else + bmu_cur_state[1:0] <= bmu_next_state[1:0]; +end + +assign bmu_req_vld = lsu_bmu_req; + +// &CombBeg; @74 +always @( dbus_grant + or dbus_cmplt + or dbus_acc_err + or bmu_cur_state[1:0] + or bus_sel_same + or bmu_req_vld) +begin + case(bmu_cur_state[1:0]) + REQ: begin + if (bmu_req_vld) + bmu_next_state[1:0] = dbus_grant ? WFD : WFG; + else + bmu_next_state[1:0] = REQ; + end + WFG:begin + if (dbus_grant) + bmu_next_state[1:0] = WFD; + else + bmu_next_state[1:0] = WFG; + end + WFD: begin + if (dbus_cmplt)begin + if (bmu_req_vld & bus_sel_same & !dbus_acc_err) + bmu_next_state[1:0] = dbus_grant ? WFD : WFG; + else + bmu_next_state[1:0] = REQ; + end + else + bmu_next_state[1:0] = WFD; + end + default: bmu_next_state[1:0] = REQ; + endcase +// &CombEnd; @100 +end + +assign req_en = (bmu_cur_state[1:0] == REQ) | + (bmu_cur_state[1:0] == WFG) | + (bmu_cur_state[1:0] == WFD) & bus_sel_same; + +assign new_req_en = (bmu_cur_state[1:0] == REQ); + +always @(posedge bmu_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bus_sel_f[3:0] <= 4'b0; + else if (bmu_req_vld & new_req_en) + bus_sel_f[3:0] <= bus_sel[3:0]; +end + +assign bus_sel_same = (bus_sel_f[3:0] == bus_sel[3:0]); + +assign sahbl_sel_pred = bus_sel_f[3]; +assign dahbl_sel_pred = bus_sel_f[0]; +assign iahbl_sel_pred = bus_sel_f[1]; +assign tcip_sel_pred = bus_sel_f[2]; + +//========================================================== +// interface +//========================================================== +//input +assign dbus_grant = dahbl_hit & dahbl_bmu_dbus_grnt | + iahbl_hit & iahbl_bmu_dbus_grnt | + tcipif_hit & tcipif_bmu_dbus_grnt | + sahbl_hit & sahbl_bmu_dbus_grnt; +assign dbus_cmplt = dahbl_bmu_dbus_trans_cmplt | + iahbl_bmu_dbus_trans_cmplt | + tcipif_bmu_dbus_trans_cmplt | + sahbl_bmu_dbus_trans_cmplt; +assign dbus_acc_err = dahbl_bmu_dbus_acc_err | + iahbl_bmu_dbus_acc_err | + tcipif_bmu_dbus_acc_err | + sahbl_bmu_dbus_acc_err; + +assign bmu_lsu_grant = dbus_grant & req_en; +assign bmu_lsu_trans_cmplt = dbus_cmplt; +assign bmu_lsu_acc_err = dbus_acc_err; +assign bmu_lsu_rdata[31:0] = ({32{bus_sel_f[0]}} & dahbl_bmu_dbus_data[31:0]) | + ({32{bus_sel_f[1]}} & iahbl_bmu_dbus_data[31:0]) | + ({32{bus_sel_f[2]}} & tcipif_bmu_dbus_data[31:0]) | + ({32{bus_sel_f[3]}} & sahbl_bmu_dbus_data[31:0]); + +//-------------------------------------- +//output +//-------------------------------------- +//iahbl +assign bmu_iahbl_dbus_req = lsu_bmu_req & req_en & iahbl_hit & iahbl_sel_pred; +assign bmu_iahbl_dbus_req_dp = lsu_bmu_req_dp & iahbl_sel_pred; +assign bmu_iahbl_dbus_addr[31:0] = lsu_bmu_addr[31:0]; +assign bmu_iahbl_dbus_acc_deny = lsu_bmu_acc_deny; +assign bmu_iahbl_dbus_write = lsu_bmu_write; +assign bmu_iahbl_dbus_size[1:0] = lsu_bmu_size[1:0]; +assign bmu_iahbl_dbus_prot[3:0] = lsu_bmu_prot[3:0]; +assign bmu_iahbl_dbus_wdata[31:0] = lsu_bmu_wdata[31:0]; +assign bmu_iahbl_dbus_lock = lsu_bmu_lock; +assign bmu_iahbl_dbus_lrsc = lsu_bmu_lrsc; +assign bmu_iahbl_dbus_seq = lsu_bmu_seq; +assign bmu_iahbl_dbus_burst[2:0] = lsu_bmu_burst[2:0]; + +//dahbl +assign bmu_dahbl_dbus_req = lsu_bmu_req & req_en & dahbl_hit & dahbl_sel_pred; +assign bmu_dahbl_dbus_req_dp = lsu_bmu_req_dp & dahbl_sel_pred; +assign bmu_dahbl_dbus_addr[31:0] = lsu_bmu_addr[31:0]; +assign bmu_dahbl_dbus_acc_deny = lsu_bmu_acc_deny; +assign bmu_dahbl_dbus_write = lsu_bmu_write; +assign bmu_dahbl_dbus_size[1:0] = lsu_bmu_size[1:0]; +assign bmu_dahbl_dbus_prot[3:0] = lsu_bmu_prot[3:0]; +assign bmu_dahbl_dbus_wdata[31:0] = lsu_bmu_wdata[31:0]; +assign bmu_dahbl_dbus_lock = lsu_bmu_lock; +assign bmu_dahbl_dbus_lrsc = lsu_bmu_lrsc; +assign bmu_dahbl_dbus_seq = lsu_bmu_seq; +assign bmu_dahbl_dbus_burst[2:0] = lsu_bmu_burst[2:0]; + +//tcipif +assign bmu_tcipif_dbus_req = lsu_bmu_req & req_en & tcipif_hit & tcip_sel_pred; +assign bmu_tcipif_dbus_req_dp = lsu_bmu_req_dp & tcip_sel_pred; +assign bmu_tcipif_dbus_acc_deny = lsu_bmu_acc_deny; +assign bmu_tcipif_dbus_write = lsu_bmu_write; +assign bmu_tcipif_dbus_size[1:0] = lsu_bmu_size[1:0]; +assign bmu_tcipif_dbus_supv_mode = lsu_bmu_prot[1]; +assign bmu_tcipif_dbus_wdata[31:0] = lsu_bmu_wdata[31:0]; +assign bmu_tcipif_dbus_addr[31:0] = {lsu_bmu_addr[31:16], tcipif_addr_low[15:0]}; +assign tcipif_addr_low[15:0] = {16{tcipif_hit}} & lsu_bmu_addr[15:0]; + +//sahbl +assign bmu_sahbl_dbus_req = lsu_bmu_req & req_en & sahbl_hit & sahbl_sel_pred; +assign bmu_sahbl_dbus_req_dp = lsu_bmu_req_dp & sahbl_sel_pred; +assign bmu_sahbl_dbus_addr[31:0] = lsu_bmu_addr[31:0]; +assign bmu_sahbl_dbus_acc_deny = lsu_bmu_acc_deny; +assign bmu_sahbl_dbus_write = lsu_bmu_write; +assign bmu_sahbl_dbus_size[1:0] = lsu_bmu_size[1:0]; +assign bmu_sahbl_dbus_prot[3:0] = lsu_bmu_prot[3:0]; +assign bmu_sahbl_dbus_wdata[31:0] = lsu_bmu_wdata[31:0]; +assign bmu_sahbl_dbus_lock = lsu_bmu_lock; +assign bmu_sahbl_dbus_lrsc = lsu_bmu_lrsc; +assign bmu_sahbl_dbus_seq = lsu_bmu_seq; +assign bmu_sahbl_dbus_burst[2:0] = lsu_bmu_burst[2:0]; + +assign bmu_lsu_clk_en = lsu_bmu_req_dp | + ~(bmu_cur_state[1:0] == REQ); + +assign dbus_dbginfo[1:0] = bmu_cur_state[1:0]; + +// &ModuleEnd; @237 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..7c0bdbfe46bd239e3becf8446cb6af845255f409 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/bmu/rtl/pa_bmu_top.v @@ -0,0 +1,700 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_bmu_top( + bmu_dahbl_dbus_acc_deny, + bmu_dahbl_dbus_addr, + bmu_dahbl_dbus_burst, + bmu_dahbl_dbus_lock, + bmu_dahbl_dbus_lrsc, + bmu_dahbl_dbus_prot, + bmu_dahbl_dbus_req, + bmu_dahbl_dbus_req_dp, + bmu_dahbl_dbus_seq, + bmu_dahbl_dbus_size, + bmu_dahbl_dbus_wdata, + bmu_dahbl_dbus_write, + bmu_dahbl_ibus_acc_deny, + bmu_dahbl_ibus_addr, + bmu_dahbl_ibus_burst, + bmu_dahbl_ibus_prot, + bmu_dahbl_ibus_req, + bmu_dahbl_ibus_req_dp, + bmu_dahbl_ibus_seq, + bmu_dahbl_ibus_size, + bmu_dtu_debug_info, + bmu_iahbl_dbus_acc_deny, + bmu_iahbl_dbus_addr, + bmu_iahbl_dbus_burst, + bmu_iahbl_dbus_lock, + bmu_iahbl_dbus_lrsc, + bmu_iahbl_dbus_prot, + bmu_iahbl_dbus_req, + bmu_iahbl_dbus_req_dp, + bmu_iahbl_dbus_seq, + bmu_iahbl_dbus_size, + bmu_iahbl_dbus_wdata, + bmu_iahbl_dbus_write, + bmu_iahbl_ibus_acc_deny, + bmu_iahbl_ibus_addr, + bmu_iahbl_ibus_burst, + bmu_iahbl_ibus_prot, + bmu_iahbl_ibus_req, + bmu_iahbl_ibus_req_dp, + bmu_iahbl_ibus_seq, + bmu_iahbl_ibus_size, + bmu_ifu_acc_err, + bmu_ifu_grant, + bmu_ifu_rdata, + bmu_ifu_trans_cmplt, + bmu_lsu_acc_err, + bmu_lsu_grant, + bmu_lsu_rdata, + bmu_lsu_trans_cmplt, + bmu_sahbl_dbus_acc_deny, + bmu_sahbl_dbus_addr, + bmu_sahbl_dbus_burst, + bmu_sahbl_dbus_lock, + bmu_sahbl_dbus_lrsc, + bmu_sahbl_dbus_prot, + bmu_sahbl_dbus_req, + bmu_sahbl_dbus_req_dp, + bmu_sahbl_dbus_seq, + bmu_sahbl_dbus_size, + bmu_sahbl_dbus_wdata, + bmu_sahbl_dbus_write, + bmu_sahbl_ibus_acc_deny, + bmu_sahbl_ibus_addr, + bmu_sahbl_ibus_burst, + bmu_sahbl_ibus_prot, + bmu_sahbl_ibus_req, + bmu_sahbl_ibus_req_dp, + bmu_sahbl_ibus_seq, + bmu_sahbl_ibus_size, + bmu_tcipif_dbus_acc_deny, + bmu_tcipif_dbus_addr, + bmu_tcipif_dbus_req, + bmu_tcipif_dbus_req_dp, + bmu_tcipif_dbus_size, + bmu_tcipif_dbus_supv_mode, + bmu_tcipif_dbus_wdata, + bmu_tcipif_dbus_write, + bmu_tcipif_ibus_acc_deny, + bmu_tcipif_ibus_addr, + bmu_tcipif_ibus_req, + bmu_tcipif_ibus_req_dp, + bmu_tcipif_ibus_size, + bmu_tcipif_ibus_supv_mode, + bmu_tcipif_ibus_wdata, + bmu_tcipif_ibus_write, + cp0_biu_icg_en, + cpurst_b, + dahbl_bmu_dbus_acc_err, + dahbl_bmu_dbus_data, + dahbl_bmu_dbus_grnt, + dahbl_bmu_dbus_trans_cmplt, + dahbl_bmu_ibus_acc_err, + dahbl_bmu_ibus_data, + dahbl_bmu_ibus_grnt, + dahbl_bmu_ibus_trans_cmplt, + forever_cpuclk, + iahbl_bmu_dbus_acc_err, + iahbl_bmu_dbus_data, + iahbl_bmu_dbus_grnt, + iahbl_bmu_dbus_trans_cmplt, + iahbl_bmu_ibus_acc_err, + iahbl_bmu_ibus_data, + iahbl_bmu_ibus_grnt, + iahbl_bmu_ibus_trans_cmplt, + ifu_bmu_acc_deny, + ifu_bmu_addr, + ifu_bmu_burst, + ifu_bmu_data_req, + ifu_bmu_prot, + ifu_bmu_req, + ifu_bmu_seq, + ifu_bmu_size, + lsu_bmu_acc_deny, + lsu_bmu_addr, + lsu_bmu_burst, + lsu_bmu_lock, + lsu_bmu_lrsc, + lsu_bmu_prot, + lsu_bmu_req, + lsu_bmu_req_dp, + lsu_bmu_seq, + lsu_bmu_size, + lsu_bmu_wdata, + lsu_bmu_write, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_cpu_tcip_base, + pad_yy_icg_scan_en, + rtu_yy_xx_async_flush, + sahbl_bmu_dbus_acc_err, + sahbl_bmu_dbus_data, + sahbl_bmu_dbus_grnt, + sahbl_bmu_dbus_trans_cmplt, + sahbl_bmu_ibus_acc_err, + sahbl_bmu_ibus_data, + sahbl_bmu_ibus_grnt, + sahbl_bmu_ibus_trans_cmplt, + tcipif_bmu_dbus_acc_err, + tcipif_bmu_dbus_data, + tcipif_bmu_dbus_grnt, + tcipif_bmu_dbus_trans_cmplt, + tcipif_bmu_ibus_acc_err, + tcipif_bmu_ibus_data, + tcipif_bmu_ibus_grnt, + tcipif_bmu_ibus_trans_cmplt +); + +// &Ports; @23 +input cp0_biu_icg_en; +input cpurst_b; +input dahbl_bmu_dbus_acc_err; +input [31:0] dahbl_bmu_dbus_data; +input dahbl_bmu_dbus_grnt; +input dahbl_bmu_dbus_trans_cmplt; +input dahbl_bmu_ibus_acc_err; +input [31:0] dahbl_bmu_ibus_data; +input dahbl_bmu_ibus_grnt; +input dahbl_bmu_ibus_trans_cmplt; +input forever_cpuclk; +input iahbl_bmu_dbus_acc_err; +input [31:0] iahbl_bmu_dbus_data; +input iahbl_bmu_dbus_grnt; +input iahbl_bmu_dbus_trans_cmplt; +input iahbl_bmu_ibus_acc_err; +input [31:0] iahbl_bmu_ibus_data; +input iahbl_bmu_ibus_grnt; +input iahbl_bmu_ibus_trans_cmplt; +input ifu_bmu_acc_deny; +input [31:0] ifu_bmu_addr; +input [2 :0] ifu_bmu_burst; +input ifu_bmu_data_req; +input [3 :0] ifu_bmu_prot; +input ifu_bmu_req; +input ifu_bmu_seq; +input [1 :0] ifu_bmu_size; +input lsu_bmu_acc_deny; +input [31:0] lsu_bmu_addr; +input [2 :0] lsu_bmu_burst; +input lsu_bmu_lock; +input lsu_bmu_lrsc; +input [3 :0] lsu_bmu_prot; +input lsu_bmu_req; +input lsu_bmu_req_dp; +input lsu_bmu_seq; +input [1 :0] lsu_bmu_size; +input [31:0] lsu_bmu_wdata; +input lsu_bmu_write; +input [11:0] pad_bmu_dahbl_base; +input [11:0] pad_bmu_dahbl_mask; +input [11:0] pad_bmu_iahbl_base; +input [11:0] pad_bmu_iahbl_mask; +input [31:0] pad_cpu_tcip_base; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +input sahbl_bmu_dbus_acc_err; +input [31:0] sahbl_bmu_dbus_data; +input sahbl_bmu_dbus_grnt; +input sahbl_bmu_dbus_trans_cmplt; +input sahbl_bmu_ibus_acc_err; +input [31:0] sahbl_bmu_ibus_data; +input sahbl_bmu_ibus_grnt; +input sahbl_bmu_ibus_trans_cmplt; +input tcipif_bmu_dbus_acc_err; +input [31:0] tcipif_bmu_dbus_data; +input tcipif_bmu_dbus_grnt; +input tcipif_bmu_dbus_trans_cmplt; +input tcipif_bmu_ibus_acc_err; +input [31:0] tcipif_bmu_ibus_data; +input tcipif_bmu_ibus_grnt; +input tcipif_bmu_ibus_trans_cmplt; +output bmu_dahbl_dbus_acc_deny; +output [31:0] bmu_dahbl_dbus_addr; +output [2 :0] bmu_dahbl_dbus_burst; +output bmu_dahbl_dbus_lock; +output bmu_dahbl_dbus_lrsc; +output [3 :0] bmu_dahbl_dbus_prot; +output bmu_dahbl_dbus_req; +output bmu_dahbl_dbus_req_dp; +output bmu_dahbl_dbus_seq; +output [1 :0] bmu_dahbl_dbus_size; +output [31:0] bmu_dahbl_dbus_wdata; +output bmu_dahbl_dbus_write; +output bmu_dahbl_ibus_acc_deny; +output [31:0] bmu_dahbl_ibus_addr; +output [2 :0] bmu_dahbl_ibus_burst; +output [3 :0] bmu_dahbl_ibus_prot; +output bmu_dahbl_ibus_req; +output bmu_dahbl_ibus_req_dp; +output bmu_dahbl_ibus_seq; +output [1 :0] bmu_dahbl_ibus_size; +output [3 :0] bmu_dtu_debug_info; +output bmu_iahbl_dbus_acc_deny; +output [31:0] bmu_iahbl_dbus_addr; +output [2 :0] bmu_iahbl_dbus_burst; +output bmu_iahbl_dbus_lock; +output bmu_iahbl_dbus_lrsc; +output [3 :0] bmu_iahbl_dbus_prot; +output bmu_iahbl_dbus_req; +output bmu_iahbl_dbus_req_dp; +output bmu_iahbl_dbus_seq; +output [1 :0] bmu_iahbl_dbus_size; +output [31:0] bmu_iahbl_dbus_wdata; +output bmu_iahbl_dbus_write; +output bmu_iahbl_ibus_acc_deny; +output [31:0] bmu_iahbl_ibus_addr; +output [2 :0] bmu_iahbl_ibus_burst; +output [3 :0] bmu_iahbl_ibus_prot; +output bmu_iahbl_ibus_req; +output bmu_iahbl_ibus_req_dp; +output bmu_iahbl_ibus_seq; +output [1 :0] bmu_iahbl_ibus_size; +output bmu_ifu_acc_err; +output bmu_ifu_grant; +output [31:0] bmu_ifu_rdata; +output bmu_ifu_trans_cmplt; +output bmu_lsu_acc_err; +output bmu_lsu_grant; +output [31:0] bmu_lsu_rdata; +output bmu_lsu_trans_cmplt; +output bmu_sahbl_dbus_acc_deny; +output [31:0] bmu_sahbl_dbus_addr; +output [2 :0] bmu_sahbl_dbus_burst; +output bmu_sahbl_dbus_lock; +output bmu_sahbl_dbus_lrsc; +output [3 :0] bmu_sahbl_dbus_prot; +output bmu_sahbl_dbus_req; +output bmu_sahbl_dbus_req_dp; +output bmu_sahbl_dbus_seq; +output [1 :0] bmu_sahbl_dbus_size; +output [31:0] bmu_sahbl_dbus_wdata; +output bmu_sahbl_dbus_write; +output bmu_sahbl_ibus_acc_deny; +output [31:0] bmu_sahbl_ibus_addr; +output [2 :0] bmu_sahbl_ibus_burst; +output [3 :0] bmu_sahbl_ibus_prot; +output bmu_sahbl_ibus_req; +output bmu_sahbl_ibus_req_dp; +output bmu_sahbl_ibus_seq; +output [1 :0] bmu_sahbl_ibus_size; +output bmu_tcipif_dbus_acc_deny; +output [31:0] bmu_tcipif_dbus_addr; +output bmu_tcipif_dbus_req; +output bmu_tcipif_dbus_req_dp; +output [1 :0] bmu_tcipif_dbus_size; +output bmu_tcipif_dbus_supv_mode; +output [31:0] bmu_tcipif_dbus_wdata; +output bmu_tcipif_dbus_write; +output bmu_tcipif_ibus_acc_deny; +output [31:0] bmu_tcipif_ibus_addr; +output bmu_tcipif_ibus_req; +output bmu_tcipif_ibus_req_dp; +output [1 :0] bmu_tcipif_ibus_size; +output bmu_tcipif_ibus_supv_mode; +output [31:0] bmu_tcipif_ibus_wdata; +output bmu_tcipif_ibus_write; + +// &Regs; @24 + +// &Wires; @25 +wire bmu_clk; +wire bmu_clk_en; +wire bmu_dahbl_dbus_acc_deny; +wire [31:0] bmu_dahbl_dbus_addr; +wire [2 :0] bmu_dahbl_dbus_burst; +wire bmu_dahbl_dbus_lock; +wire bmu_dahbl_dbus_lrsc; +wire [3 :0] bmu_dahbl_dbus_prot; +wire bmu_dahbl_dbus_req; +wire bmu_dahbl_dbus_req_dp; +wire bmu_dahbl_dbus_seq; +wire [1 :0] bmu_dahbl_dbus_size; +wire [31:0] bmu_dahbl_dbus_wdata; +wire bmu_dahbl_dbus_write; +wire bmu_dahbl_ibus_acc_deny; +wire [31:0] bmu_dahbl_ibus_addr; +wire [2 :0] bmu_dahbl_ibus_burst; +wire [3 :0] bmu_dahbl_ibus_prot; +wire bmu_dahbl_ibus_req; +wire bmu_dahbl_ibus_req_dp; +wire bmu_dahbl_ibus_seq; +wire [1 :0] bmu_dahbl_ibus_size; +wire [31:0] bmu_dahbl_ibus_wdata; +wire bmu_dahbl_ibus_write; +wire [3 :0] bmu_dtu_debug_info; +wire bmu_iahbl_dbus_acc_deny; +wire [31:0] bmu_iahbl_dbus_addr; +wire [2 :0] bmu_iahbl_dbus_burst; +wire bmu_iahbl_dbus_lock; +wire bmu_iahbl_dbus_lrsc; +wire [3 :0] bmu_iahbl_dbus_prot; +wire bmu_iahbl_dbus_req; +wire bmu_iahbl_dbus_req_dp; +wire bmu_iahbl_dbus_seq; +wire [1 :0] bmu_iahbl_dbus_size; +wire [31:0] bmu_iahbl_dbus_wdata; +wire bmu_iahbl_dbus_write; +wire bmu_iahbl_ibus_acc_deny; +wire [31:0] bmu_iahbl_ibus_addr; +wire [2 :0] bmu_iahbl_ibus_burst; +wire [3 :0] bmu_iahbl_ibus_prot; +wire bmu_iahbl_ibus_req; +wire bmu_iahbl_ibus_req_dp; +wire bmu_iahbl_ibus_seq; +wire [1 :0] bmu_iahbl_ibus_size; +wire [31:0] bmu_iahbl_ibus_wdata; +wire bmu_iahbl_ibus_write; +wire bmu_ifu_acc_err; +wire bmu_ifu_clk_en; +wire bmu_ifu_grant; +wire [31:0] bmu_ifu_rdata; +wire bmu_ifu_trans_cmplt; +wire bmu_lsu_acc_err; +wire bmu_lsu_clk_en; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire bmu_sahbl_dbus_acc_deny; +wire [31:0] bmu_sahbl_dbus_addr; +wire [2 :0] bmu_sahbl_dbus_burst; +wire bmu_sahbl_dbus_lock; +wire bmu_sahbl_dbus_lrsc; +wire [3 :0] bmu_sahbl_dbus_prot; +wire bmu_sahbl_dbus_req; +wire bmu_sahbl_dbus_req_dp; +wire bmu_sahbl_dbus_seq; +wire [1 :0] bmu_sahbl_dbus_size; +wire [31:0] bmu_sahbl_dbus_wdata; +wire bmu_sahbl_dbus_write; +wire bmu_sahbl_ibus_acc_deny; +wire [31:0] bmu_sahbl_ibus_addr; +wire [2 :0] bmu_sahbl_ibus_burst; +wire [3 :0] bmu_sahbl_ibus_prot; +wire bmu_sahbl_ibus_req; +wire bmu_sahbl_ibus_req_dp; +wire bmu_sahbl_ibus_seq; +wire [1 :0] bmu_sahbl_ibus_size; +wire [31:0] bmu_sahbl_ibus_wdata; +wire bmu_sahbl_ibus_write; +wire bmu_tcipif_dbus_acc_deny; +wire [31:0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31:0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire bmu_tcipif_ibus_acc_deny; +wire [31:0] bmu_tcipif_ibus_addr; +wire bmu_tcipif_ibus_req; +wire bmu_tcipif_ibus_req_dp; +wire [1 :0] bmu_tcipif_ibus_size; +wire bmu_tcipif_ibus_supv_mode; +wire [31:0] bmu_tcipif_ibus_wdata; +wire bmu_tcipif_ibus_write; +wire cp0_biu_icg_en; +wire cpurst_b; +wire dahbl_bmu_dbus_acc_err; +wire [31:0] dahbl_bmu_dbus_data; +wire dahbl_bmu_dbus_grnt; +wire dahbl_bmu_dbus_trans_cmplt; +wire dahbl_bmu_ibus_acc_err; +wire [31:0] dahbl_bmu_ibus_data; +wire dahbl_bmu_ibus_grnt; +wire dahbl_bmu_ibus_trans_cmplt; +wire [1 :0] dbus_dbginfo; +wire forever_cpuclk; +wire iahbl_bmu_dbus_acc_err; +wire [31:0] iahbl_bmu_dbus_data; +wire iahbl_bmu_dbus_grnt; +wire iahbl_bmu_dbus_trans_cmplt; +wire iahbl_bmu_ibus_acc_err; +wire [31:0] iahbl_bmu_ibus_data; +wire iahbl_bmu_ibus_grnt; +wire iahbl_bmu_ibus_trans_cmplt; +wire [1 :0] ibus_dbginfo; +wire ifu_bmu_acc_deny; +wire [31:0] ifu_bmu_addr; +wire [2 :0] ifu_bmu_burst; +wire ifu_bmu_data_req; +wire [3 :0] ifu_bmu_prot; +wire ifu_bmu_req; +wire ifu_bmu_seq; +wire [1 :0] ifu_bmu_size; +wire [31:0] ifu_bmu_wdata; +wire ifu_bmu_write; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire [11:0] pad_bmu_dahbl_base; +wire [11:0] pad_bmu_dahbl_mask; +wire [11:0] pad_bmu_iahbl_base; +wire [11:0] pad_bmu_iahbl_mask; +wire [31:0] pad_cpu_tcip_base; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_async_flush; +wire sahbl_bmu_dbus_acc_err; +wire [31:0] sahbl_bmu_dbus_data; +wire sahbl_bmu_dbus_grnt; +wire sahbl_bmu_dbus_trans_cmplt; +wire sahbl_bmu_ibus_acc_err; +wire [31:0] sahbl_bmu_ibus_data; +wire sahbl_bmu_ibus_grnt; +wire sahbl_bmu_ibus_trans_cmplt; +wire tcipif_bmu_dbus_acc_err; +wire [31:0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_bmu_ibus_acc_err; +wire [31:0] tcipif_bmu_ibus_data; +wire tcipif_bmu_ibus_grnt; +wire tcipif_bmu_ibus_trans_cmplt; + + + +//========================================================== +// Instance of Gated Cell +//========================================================== +assign ifu_bmu_write = 1'b0; +assign ifu_bmu_wdata[31:0] = 32'b0; +// &Force("nonport", "bmu_dahbl_ibus_write") @33 +// &Force("nonport", "bmu_dahbl_ibus_wdata") @34 +// &Force("nonport", "bmu_iahbl_ibus_write") @35 +// &Force("nonport", "bmu_iahbl_ibus_wdata") @36 +// &Force("nonport", "bmu_sahbl_ibus_write") @37 +// &Force("nonport", "bmu_sahbl_ibus_wdata") @38 + +//assign bmu_clk_en = bmu_lsu_clk_en | bmu_had_clk_en | bmu_ifu_clk_en; +assign bmu_clk_en = bmu_lsu_clk_en | bmu_ifu_clk_en; + +// &Instance("gated_clk_cell", "x_pa_lsu_bmu_gated_clk"); @43 +gated_clk_cell x_pa_lsu_bmu_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bmu_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (bmu_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @44 +// .external_en (1'b0), @45 +// .global_en (1'b1), @46 +// .module_en (cp0_biu_icg_en), @47 +// .local_en (bmu_clk_en), @48 +// .clk_out (bmu_clk)); @49 + +// &ConnRule(s/xx/ibus/); @51 +// &ConnRule(s/tt/ifu/); @52 +// &Instance("pa_bmu_bus_if","x_pa_bmu_ibus_if"); @53 +pa_bmu_bus_if x_pa_bmu_ibus_if ( + .bmu_clk (bmu_clk ), + .bmu_dahbl_xx_acc_deny (bmu_dahbl_ibus_acc_deny ), + .bmu_dahbl_xx_addr (bmu_dahbl_ibus_addr ), + .bmu_dahbl_xx_burst (bmu_dahbl_ibus_burst ), + .bmu_dahbl_xx_prot (bmu_dahbl_ibus_prot ), + .bmu_dahbl_xx_req (bmu_dahbl_ibus_req ), + .bmu_dahbl_xx_req_dp (bmu_dahbl_ibus_req_dp ), + .bmu_dahbl_xx_seq (bmu_dahbl_ibus_seq ), + .bmu_dahbl_xx_size (bmu_dahbl_ibus_size ), + .bmu_dahbl_xx_wdata (bmu_dahbl_ibus_wdata ), + .bmu_dahbl_xx_write (bmu_dahbl_ibus_write ), + .bmu_iahbl_xx_acc_deny (bmu_iahbl_ibus_acc_deny ), + .bmu_iahbl_xx_addr (bmu_iahbl_ibus_addr ), + .bmu_iahbl_xx_burst (bmu_iahbl_ibus_burst ), + .bmu_iahbl_xx_prot (bmu_iahbl_ibus_prot ), + .bmu_iahbl_xx_req (bmu_iahbl_ibus_req ), + .bmu_iahbl_xx_req_dp (bmu_iahbl_ibus_req_dp ), + .bmu_iahbl_xx_seq (bmu_iahbl_ibus_seq ), + .bmu_iahbl_xx_size (bmu_iahbl_ibus_size ), + .bmu_iahbl_xx_wdata (bmu_iahbl_ibus_wdata ), + .bmu_iahbl_xx_write (bmu_iahbl_ibus_write ), + .bmu_sahbl_xx_acc_deny (bmu_sahbl_ibus_acc_deny ), + .bmu_sahbl_xx_addr (bmu_sahbl_ibus_addr ), + .bmu_sahbl_xx_burst (bmu_sahbl_ibus_burst ), + .bmu_sahbl_xx_prot (bmu_sahbl_ibus_prot ), + .bmu_sahbl_xx_req (bmu_sahbl_ibus_req ), + .bmu_sahbl_xx_req_dp (bmu_sahbl_ibus_req_dp ), + .bmu_sahbl_xx_seq (bmu_sahbl_ibus_seq ), + .bmu_sahbl_xx_size (bmu_sahbl_ibus_size ), + .bmu_sahbl_xx_wdata (bmu_sahbl_ibus_wdata ), + .bmu_sahbl_xx_write (bmu_sahbl_ibus_write ), + .bmu_tcipif_xx_acc_deny (bmu_tcipif_ibus_acc_deny ), + .bmu_tcipif_xx_addr (bmu_tcipif_ibus_addr ), + .bmu_tcipif_xx_req (bmu_tcipif_ibus_req ), + .bmu_tcipif_xx_req_dp (bmu_tcipif_ibus_req_dp ), + .bmu_tcipif_xx_size (bmu_tcipif_ibus_size ), + .bmu_tcipif_xx_supv_mode (bmu_tcipif_ibus_supv_mode ), + .bmu_tcipif_xx_wdata (bmu_tcipif_ibus_wdata ), + .bmu_tcipif_xx_write (bmu_tcipif_ibus_write ), + .bmu_tt_acc_err (bmu_ifu_acc_err ), + .bmu_tt_clk_en (bmu_ifu_clk_en ), + .bmu_tt_grant (bmu_ifu_grant ), + .bmu_tt_rdata (bmu_ifu_rdata ), + .bmu_tt_trans_cmplt (bmu_ifu_trans_cmplt ), + .cpurst_b (cpurst_b ), + .dahbl_bmu_xx_acc_err (dahbl_bmu_ibus_acc_err ), + .dahbl_bmu_xx_data (dahbl_bmu_ibus_data ), + .dahbl_bmu_xx_grnt (dahbl_bmu_ibus_grnt ), + .dahbl_bmu_xx_trans_cmplt (dahbl_bmu_ibus_trans_cmplt ), + .iahbl_bmu_xx_acc_err (iahbl_bmu_ibus_acc_err ), + .iahbl_bmu_xx_data (iahbl_bmu_ibus_data ), + .iahbl_bmu_xx_grnt (iahbl_bmu_ibus_grnt ), + .iahbl_bmu_xx_trans_cmplt (iahbl_bmu_ibus_trans_cmplt ), + .pad_bmu_dahbl_base (pad_bmu_dahbl_base ), + .pad_bmu_dahbl_mask (pad_bmu_dahbl_mask ), + .pad_bmu_iahbl_base (pad_bmu_iahbl_base ), + .pad_bmu_iahbl_mask (pad_bmu_iahbl_mask ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .sahbl_bmu_xx_acc_err (sahbl_bmu_ibus_acc_err ), + .sahbl_bmu_xx_data (sahbl_bmu_ibus_data ), + .sahbl_bmu_xx_grnt (sahbl_bmu_ibus_grnt ), + .sahbl_bmu_xx_trans_cmplt (sahbl_bmu_ibus_trans_cmplt ), + .tcipif_bmu_xx_acc_err (tcipif_bmu_ibus_acc_err ), + .tcipif_bmu_xx_data (tcipif_bmu_ibus_data ), + .tcipif_bmu_xx_grnt (tcipif_bmu_ibus_grnt ), + .tcipif_bmu_xx_trans_cmplt (tcipif_bmu_ibus_trans_cmplt), + .tt_bmu_acc_deny (ifu_bmu_acc_deny ), + .tt_bmu_addr (ifu_bmu_addr ), + .tt_bmu_burst (ifu_bmu_burst ), + .tt_bmu_data_req (ifu_bmu_data_req ), + .tt_bmu_prot (ifu_bmu_prot ), + .tt_bmu_req (ifu_bmu_req ), + .tt_bmu_seq (ifu_bmu_seq ), + .tt_bmu_size (ifu_bmu_size ), + .tt_bmu_wdata (ifu_bmu_wdata ), + .tt_bmu_write (ifu_bmu_write ), + .xx_dbginfo (ibus_dbginfo ) +); + + +// &Instance("pa_bmu_dbus_if","x_pa_bmu_dbus_if"); @55 +pa_bmu_dbus_if x_pa_bmu_dbus_if ( + .bmu_clk (bmu_clk ), + .bmu_dahbl_dbus_acc_deny (bmu_dahbl_dbus_acc_deny ), + .bmu_dahbl_dbus_addr (bmu_dahbl_dbus_addr ), + .bmu_dahbl_dbus_burst (bmu_dahbl_dbus_burst ), + .bmu_dahbl_dbus_lock (bmu_dahbl_dbus_lock ), + .bmu_dahbl_dbus_lrsc (bmu_dahbl_dbus_lrsc ), + .bmu_dahbl_dbus_prot (bmu_dahbl_dbus_prot ), + .bmu_dahbl_dbus_req (bmu_dahbl_dbus_req ), + .bmu_dahbl_dbus_req_dp (bmu_dahbl_dbus_req_dp ), + .bmu_dahbl_dbus_seq (bmu_dahbl_dbus_seq ), + .bmu_dahbl_dbus_size (bmu_dahbl_dbus_size ), + .bmu_dahbl_dbus_wdata (bmu_dahbl_dbus_wdata ), + .bmu_dahbl_dbus_write (bmu_dahbl_dbus_write ), + .bmu_iahbl_dbus_acc_deny (bmu_iahbl_dbus_acc_deny ), + .bmu_iahbl_dbus_addr (bmu_iahbl_dbus_addr ), + .bmu_iahbl_dbus_burst (bmu_iahbl_dbus_burst ), + .bmu_iahbl_dbus_lock (bmu_iahbl_dbus_lock ), + .bmu_iahbl_dbus_lrsc (bmu_iahbl_dbus_lrsc ), + .bmu_iahbl_dbus_prot (bmu_iahbl_dbus_prot ), + .bmu_iahbl_dbus_req (bmu_iahbl_dbus_req ), + .bmu_iahbl_dbus_req_dp (bmu_iahbl_dbus_req_dp ), + .bmu_iahbl_dbus_seq (bmu_iahbl_dbus_seq ), + .bmu_iahbl_dbus_size (bmu_iahbl_dbus_size ), + .bmu_iahbl_dbus_wdata (bmu_iahbl_dbus_wdata ), + .bmu_iahbl_dbus_write (bmu_iahbl_dbus_write ), + .bmu_lsu_acc_err (bmu_lsu_acc_err ), + .bmu_lsu_clk_en (bmu_lsu_clk_en ), + .bmu_lsu_grant (bmu_lsu_grant ), + .bmu_lsu_rdata (bmu_lsu_rdata ), + .bmu_lsu_trans_cmplt (bmu_lsu_trans_cmplt ), + .bmu_sahbl_dbus_acc_deny (bmu_sahbl_dbus_acc_deny ), + .bmu_sahbl_dbus_addr (bmu_sahbl_dbus_addr ), + .bmu_sahbl_dbus_burst (bmu_sahbl_dbus_burst ), + .bmu_sahbl_dbus_lock (bmu_sahbl_dbus_lock ), + .bmu_sahbl_dbus_lrsc (bmu_sahbl_dbus_lrsc ), + .bmu_sahbl_dbus_prot (bmu_sahbl_dbus_prot ), + .bmu_sahbl_dbus_req (bmu_sahbl_dbus_req ), + .bmu_sahbl_dbus_req_dp (bmu_sahbl_dbus_req_dp ), + .bmu_sahbl_dbus_seq (bmu_sahbl_dbus_seq ), + .bmu_sahbl_dbus_size (bmu_sahbl_dbus_size ), + .bmu_sahbl_dbus_wdata (bmu_sahbl_dbus_wdata ), + .bmu_sahbl_dbus_write (bmu_sahbl_dbus_write ), + .bmu_tcipif_dbus_acc_deny (bmu_tcipif_dbus_acc_deny ), + .bmu_tcipif_dbus_addr (bmu_tcipif_dbus_addr ), + .bmu_tcipif_dbus_req (bmu_tcipif_dbus_req ), + .bmu_tcipif_dbus_req_dp (bmu_tcipif_dbus_req_dp ), + .bmu_tcipif_dbus_size (bmu_tcipif_dbus_size ), + .bmu_tcipif_dbus_supv_mode (bmu_tcipif_dbus_supv_mode ), + .bmu_tcipif_dbus_wdata (bmu_tcipif_dbus_wdata ), + .bmu_tcipif_dbus_write (bmu_tcipif_dbus_write ), + .cpurst_b (cpurst_b ), + .dahbl_bmu_dbus_acc_err (dahbl_bmu_dbus_acc_err ), + .dahbl_bmu_dbus_data (dahbl_bmu_dbus_data ), + .dahbl_bmu_dbus_grnt (dahbl_bmu_dbus_grnt ), + .dahbl_bmu_dbus_trans_cmplt (dahbl_bmu_dbus_trans_cmplt ), + .dbus_dbginfo (dbus_dbginfo ), + .iahbl_bmu_dbus_acc_err (iahbl_bmu_dbus_acc_err ), + .iahbl_bmu_dbus_data (iahbl_bmu_dbus_data ), + .iahbl_bmu_dbus_grnt (iahbl_bmu_dbus_grnt ), + .iahbl_bmu_dbus_trans_cmplt (iahbl_bmu_dbus_trans_cmplt ), + .lsu_bmu_acc_deny (lsu_bmu_acc_deny ), + .lsu_bmu_addr (lsu_bmu_addr ), + .lsu_bmu_burst (lsu_bmu_burst ), + .lsu_bmu_lock (lsu_bmu_lock ), + .lsu_bmu_lrsc (lsu_bmu_lrsc ), + .lsu_bmu_prot (lsu_bmu_prot ), + .lsu_bmu_req (lsu_bmu_req ), + .lsu_bmu_req_dp (lsu_bmu_req_dp ), + .lsu_bmu_seq (lsu_bmu_seq ), + .lsu_bmu_size (lsu_bmu_size ), + .lsu_bmu_wdata (lsu_bmu_wdata ), + .lsu_bmu_write (lsu_bmu_write ), + .pad_bmu_dahbl_base (pad_bmu_dahbl_base ), + .pad_bmu_dahbl_mask (pad_bmu_dahbl_mask ), + .pad_bmu_iahbl_base (pad_bmu_iahbl_base ), + .pad_bmu_iahbl_mask (pad_bmu_iahbl_mask ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sahbl_bmu_dbus_acc_err (sahbl_bmu_dbus_acc_err ), + .sahbl_bmu_dbus_data (sahbl_bmu_dbus_data ), + .sahbl_bmu_dbus_grnt (sahbl_bmu_dbus_grnt ), + .sahbl_bmu_dbus_trans_cmplt (sahbl_bmu_dbus_trans_cmplt ), + .tcipif_bmu_dbus_acc_err (tcipif_bmu_dbus_acc_err ), + .tcipif_bmu_dbus_data (tcipif_bmu_dbus_data ), + .tcipif_bmu_dbus_grnt (tcipif_bmu_dbus_grnt ), + .tcipif_bmu_dbus_trans_cmplt (tcipif_bmu_dbus_trans_cmplt) +); + + +// //&ConnRule(s/xx/had/); @57 +// //&ConnRule(s/tt/had/); @58 +//&Instance("pa_bmu_bus_if","x_pa_bmu_had_if"); +//assign had_bmu_acc_deny = 1'b0; +//assign had_bmu_data_req = had_bmu_req; + +assign bmu_dtu_debug_info[3:0] = {ibus_dbginfo[1:0],dbus_dbginfo[1:0]}; +// &ModuleEnd; @64 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb.v new file mode 100644 index 0000000000000000000000000000000000000000..64c23f0c7d6b9302398e58ed51cd8a88a8d3ff94 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb.v @@ -0,0 +1,122 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @28 +module pa_clic_arb( + arb_ctrl_int_hv, + arb_ctrl_int_id, + arb_ctrl_int_il, + arb_ctrl_int_mode, + arb_ctrl_int_req_raw, + ctrl_xx_int_lv_or_mask, + kid_arb_int_all_vec, + kid_arb_int_hv, + kid_arb_int_req +); + +// &Ports; @29 +input [2 :0] ctrl_xx_int_lv_or_mask; +input [575:0] kid_arb_int_all_vec; +input [143:0] kid_arb_int_hv; +input [143:0] kid_arb_int_req; +output arb_ctrl_int_hv; +output [11 :0] arb_ctrl_int_id; +output [7 :0] arb_ctrl_int_il; +output arb_ctrl_int_mode; +output arb_ctrl_int_req_raw; + +// &Regs; @30 + +// &Wires; @31 +wire arb_ctrl_int_hv; +wire [11 :0] arb_ctrl_int_id; +wire [7 :0] arb_ctrl_int_il; +wire arb_ctrl_int_mode; +wire arb_ctrl_int_req_raw; +wire [3 :0] arb_final_int_all; +wire arb_final_int_hv; +wire [11 :0] arb_final_int_id; +wire [2 :0] arb_final_int_lv; +wire arb_final_int_mode; +wire arb_final_int_req; +wire [2 :0] ctrl_xx_int_lv_or_mask; +wire [143:0] kid_arb_int_req; + + +parameter CLICINTNUM = `CLIC_INTNUM; +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; +parameter ID_WIDTH = 12; + +// &Force("input", "kid_arb_int_all_vec"); @37 +// &Force("bus", "kid_arb_int_all_vec", (CLICINTCTLBITS+1)*(CLICINTNUM)-1, 0); @38 +// &Force("input", "kid_arb_int_hv"); &Force("bus", "kid_arb_int_hv", CLICINTNUM-1, 0); @39 +// &Force("input", "kid_arb_int_req"); &Force("bus", "kid_arb_int_req", CLICINTNUM-1, 0); @40 + +//========================================================== +// Arbiter +//========================================================== +//csky vperl_off +wire [ID_WIDTH*CLICINTNUM-1:0] id_vec; + +genvar i; +generate + for (i = 0; i < CLICINTNUM; i = i+1) + begin: GEN_ID + assign id_vec[ID_WIDTH*i+:ID_WIDTH] = $unsigned(i) & {ID_WIDTH{1'b1}}; + end +endgenerate + +pa_clic_arb_kernel #(.PRIO_WIDTH(CLICINTCTLBITS+1), .INT_NUM(CLICINTNUM)) x_pa_clic_arb_kernel ( + .id_in_vec (id_vec), + .hv_in_vec (kid_arb_int_hv), + .prio_in_vec (kid_arb_int_all_vec), + .req_in_vec (kid_arb_int_req), + .id_out (arb_final_int_id), + .hv_out (arb_final_int_hv), + .prio_out (arb_final_int_all), + .req_out (arb_final_int_req) +); +//csky vperl_on + + +// &Force("nonport", "arb_final_int_id"); @69 +// &Force("nonport", "arb_final_int_hv"); @70 +// &Force("nonport", "arb_final_int_all"); @71 +// &Force("nonport", "arb_final_int_req"); @72 + +assign arb_final_int_mode = arb_final_int_all[CLICINTCTLBITS]; +assign arb_final_int_lv[CLICINTCTLBITS-1:0] = arb_final_int_all[CLICINTCTLBITS-1:0] + | ctrl_xx_int_lv_or_mask[CLICINTCTLBITS-1:0] + & {CLICINTCTLBITS{arb_final_int_req}}; + + +//========================================================== +// Output Signal +//========================================================== +assign arb_ctrl_int_hv = arb_final_int_hv; +assign arb_ctrl_int_id[ID_WIDTH-1:0] = arb_final_int_id[ID_WIDTH-1:0]; +assign arb_ctrl_int_mode = arb_final_int_mode; +assign arb_ctrl_int_il[7:0] = {arb_final_int_lv[CLICINTCTLBITS-1:0], + {(8-CLICINTCTLBITS){arb_final_int_req}}}; + +//========================================================== +// Gate Clk Cell +//========================================================== +assign arb_ctrl_int_req_raw = |kid_arb_int_req[CLICINTNUM-1:0]; + +// &ModuleEnd; @94 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_32to1_kernel.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_32to1_kernel.v new file mode 100644 index 0000000000000000000000000000000000000000..b0c162363ccd41b2c1331d1313d31d2f1157d09e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_32to1_kernel.v @@ -0,0 +1,101 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_arb_32to1_kernel( + // input + prio_in_vec, + // output + prio_out_mid, + sel_out_onehot +); + +parameter PRIO_WIDTH = 6; +parameter INT_NUM = 32; +localparam PRIO_EXP_NUM = 1 <<< PRIO_WIDTH; + +input [PRIO_EXP_NUM*INT_NUM-1:0] prio_in_vec; +output [PRIO_EXP_NUM-1:0] prio_out_mid; +output [INT_NUM-1:0] sel_out_onehot; + +wire [PRIO_EXP_NUM*INT_NUM-1:0] prio_in_vec; +wire [PRIO_EXP_NUM-1:0] prio_out_mid; +wire [INT_NUM-1:0] sel_out_onehot; + +wire [PRIO_EXP_NUM-1:0] prio_in_2d[INT_NUM-1:0]; +wire [INT_NUM-1:0] prio_in_2d_rev[PRIO_EXP_NUM-1:0]; + +genvar i; +genvar j; +genvar k; + +//========================================================== +// Generate 2D prio +//========================================================== +generate + for (k = 0; k < INT_NUM; k = k+1) + begin: EXPEND_PRIO + assign prio_in_2d[k][PRIO_EXP_NUM-1:0] = prio_in_vec[PRIO_EXP_NUM*k+:PRIO_EXP_NUM]; + end +endgenerate + +//========================================================== +// Reverse 2D signal +//========================================================== +generate + for (i = 0; i < INT_NUM; i = i+1) begin: REVERSEI + for (j = 0; j < PRIO_EXP_NUM; j = j+1) begin: REVERSEJ + assign prio_in_2d_rev[j][i] = prio_in_2d[i][j]; + end + end +endgenerate + +wire [PRIO_EXP_NUM-1:0] high_prio_onehot; +wire [PRIO_EXP_NUM-1:0] prio_out; +//========================================================== +// Do or to sel +//========================================================== +generate + for (i = 0; i < PRIO_EXP_NUM; i = i+1) begin: OR_SEL + assign prio_out[i] = |prio_in_2d_rev[i][INT_NUM-1:0]; + end +endgenerate + +assign prio_out_mid[PRIO_EXP_NUM-1:0] = prio_out[PRIO_EXP_NUM-1:0]; + +pa_clic_ff1_onehot #(PRIO_EXP_NUM) x_pa_clic_high_prio( + .data_in (prio_out), + .ff1_out_onehot (high_prio_onehot) +); + +wire [PRIO_EXP_NUM-1:0] prio_after_mask_2d[INT_NUM-1:0]; +wire [INT_NUM-1:0] int_hit_prio; +generate + for (k = 0; k < INT_NUM; k = k+1) + begin: PRIO_MASK + assign prio_after_mask_2d[k][PRIO_EXP_NUM-1:0] = prio_in_2d[k][PRIO_EXP_NUM-1:0] & high_prio_onehot[PRIO_EXP_NUM-1:0]; + assign int_hit_prio[k] = |prio_after_mask_2d[k][PRIO_EXP_NUM-1:0]; + end +endgenerate + +wire [INT_NUM-1:0] int_sel_onehot; + +pa_clic_ff1_onehot #(INT_NUM) x_pa_clic_num( + .data_in (int_hit_prio), + .ff1_out_onehot (int_sel_onehot) +); + +assign sel_out_onehot[INT_NUM-1:0] = int_sel_onehot[INT_NUM-1:0]; + +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_kernel.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_kernel.v new file mode 100644 index 0000000000000000000000000000000000000000..9820e1f836e647ba01edab795936ce1f17c8e8c5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_arb_kernel.v @@ -0,0 +1,182 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_arb_kernel( + // input + id_in_vec, + hv_in_vec, + prio_in_vec, + req_in_vec, + // output + id_out, + hv_out, + prio_out, + req_out +); + +parameter PRIO_WIDTH = 6; +parameter INT_NUM = 64; +parameter NUM_PER_GROUP = 16; + +parameter ID_WIDTH = 12; +parameter PRIO_EXP_NUM = 1 <<< PRIO_WIDTH; +parameter GROUP_NUM = (INT_NUM-1) / NUM_PER_GROUP + 1; +parameter ALL_ARB_WIDTH = PRIO_WIDTH*GROUP_NUM*NUM_PER_GROUP; +parameter ALL_EXP_WIDTH = PRIO_EXP_NUM*GROUP_NUM*NUM_PER_GROUP; +parameter ALL_ID_WIDTH = ID_WIDTH*GROUP_NUM*NUM_PER_GROUP; +parameter ALL_INT_WIDTH = GROUP_NUM*NUM_PER_GROUP; + +input [ID_WIDTH*INT_NUM-1:0] id_in_vec; +input [INT_NUM-1:0] hv_in_vec; +input [PRIO_WIDTH*INT_NUM-1:0] prio_in_vec; +input [INT_NUM-1:0] req_in_vec; +output [ID_WIDTH-1:0] id_out; +output hv_out; +output [PRIO_WIDTH-1:0] prio_out; +output req_out; + +wire [ID_WIDTH*INT_NUM-1:0] id_in_vec; +wire [INT_NUM-1:0] hv_in_vec; +wire [PRIO_WIDTH*INT_NUM-1:0] prio_in_vec; +wire [INT_NUM-1:0] req_in_vec; +wire [ID_WIDTH-1:0] id_out; +wire hv_out; +wire [PRIO_WIDTH-1:0] prio_out; +wire req_out; + +//========================================================== +// Expand Priority +//========================================================== +wire [PRIO_EXP_NUM*INT_NUM-1:0] prio_expand_vec; + +pa_clic_expand #(PRIO_WIDTH, INT_NUM) x_pa_clic_prio_expand( + .data_in_vec (prio_in_vec), + .expand_out_vec (prio_expand_vec) +); + +//========================================================== +// Padding +//========================================================== +wire [ALL_EXP_WIDTH:0] prio_expand_vec_padding; +assign prio_expand_vec_padding[ALL_EXP_WIDTH:0] = {{(ALL_EXP_WIDTH-PRIO_EXP_NUM*INT_NUM+1){1'b0}}, + prio_expand_vec[PRIO_EXP_NUM*INT_NUM-1:0]}; + +wire [ALL_ARB_WIDTH:0] prio_in_vec_padding; +assign prio_in_vec_padding[ALL_ARB_WIDTH:0] = {{(ALL_ARB_WIDTH-PRIO_WIDTH*INT_NUM+1){1'b0}}, + prio_in_vec[PRIO_WIDTH*INT_NUM-1:0]}; + +wire [ALL_ID_WIDTH:0] id_vec_padding; +assign id_vec_padding[ALL_ID_WIDTH:0] = {{(ALL_ID_WIDTH-ID_WIDTH*INT_NUM+1){1'b0}}, + id_in_vec[ID_WIDTH*INT_NUM-1:0]}; + +wire [ALL_INT_WIDTH:0] hv_vec_padding; +assign hv_vec_padding[ALL_INT_WIDTH:0] = {{(ALL_INT_WIDTH-INT_NUM+1){1'b0}}, hv_in_vec[INT_NUM-1:0]}; + +wire [ALL_INT_WIDTH:0] req_vec_padding; +assign req_vec_padding[ALL_INT_WIDTH:0] = {{(ALL_INT_WIDTH-INT_NUM+1){1'b0}}, req_in_vec[INT_NUM-1:0]}; + +//========================================================== +// 1st Stage Arbiter & Select +//========================================================== +wire [PRIO_EXP_NUM*GROUP_NUM-1:0] prio_out_mid_1st; +wire [NUM_PER_GROUP*GROUP_NUM-1:0] sel_out_onehot_1st; + +wire [PRIO_WIDTH*GROUP_NUM-1:0] sel_out_prio_vec_1st; +wire [ID_WIDTH*GROUP_NUM-1:0] sel_out_id_vec_1st; + +wire [GROUP_NUM-1:0] sel_out_hv_vec_1st; +wire [GROUP_NUM-1:0] sel_out_req_vec_1st; + +genvar i; + +generate +for (i = 0; i < GROUP_NUM; i = i+1) +begin: GROUP_X +//---------------------------------------------------------- +// Arbiter +//---------------------------------------------------------- + pa_clic_arb_32to1_kernel #(PRIO_WIDTH, NUM_PER_GROUP) x_pa_clic_arb_1st_round( + .prio_in_vec (prio_expand_vec_padding[(PRIO_EXP_NUM*NUM_PER_GROUP)*i+:(PRIO_EXP_NUM*NUM_PER_GROUP)]), + .prio_out_mid (prio_out_mid_1st[PRIO_EXP_NUM*i+:PRIO_EXP_NUM]), + .sel_out_onehot (sel_out_onehot_1st[NUM_PER_GROUP*i+:NUM_PER_GROUP]) + ); + +//---------------------------------------------------------- +// Select Priority +//---------------------------------------------------------- + pa_clic_sel #(PRIO_WIDTH, NUM_PER_GROUP) x_pa_clic_lv_sel_1st_round( + .data_in (prio_in_vec_padding[(PRIO_WIDTH*NUM_PER_GROUP)*i+:(PRIO_WIDTH*NUM_PER_GROUP)]), + .sel_in_onehot (sel_out_onehot_1st[NUM_PER_GROUP*i+:NUM_PER_GROUP]), + .data_out (sel_out_prio_vec_1st[PRIO_WIDTH*i+:PRIO_WIDTH]) + ); + +//---------------------------------------------------------- +// Select ID +//---------------------------------------------------------- + pa_clic_sel #(ID_WIDTH, NUM_PER_GROUP) x_pa_clic_id_sel_1st_round( + .data_in (id_vec_padding[(ID_WIDTH*NUM_PER_GROUP)*i+:(ID_WIDTH*NUM_PER_GROUP)]), + .sel_in_onehot (sel_out_onehot_1st[NUM_PER_GROUP*i+:NUM_PER_GROUP]), + .data_out (sel_out_id_vec_1st[ID_WIDTH*i+:ID_WIDTH]) + ); + +//---------------------------------------------------------- +// Select hv & req +//---------------------------------------------------------- + assign sel_out_hv_vec_1st[i] = |(sel_out_onehot_1st[NUM_PER_GROUP*i+:NUM_PER_GROUP] & hv_vec_padding[NUM_PER_GROUP*i+:NUM_PER_GROUP]); + assign sel_out_req_vec_1st[i] = |(sel_out_onehot_1st[NUM_PER_GROUP*i+:NUM_PER_GROUP] & req_vec_padding[NUM_PER_GROUP*i+:NUM_PER_GROUP]); + +end +endgenerate + +//========================================================== +// 2nd Stage Arbiter & Select +//========================================================== +//---------------------------------------------------------- +// Arbiter +//---------------------------------------------------------- +wire [PRIO_EXP_NUM-1:0] prio_out_mid_2nd; +wire [GROUP_NUM-1:0] sel_out_2nd_round; + +pa_clic_arb_32to1_kernel #(PRIO_WIDTH, GROUP_NUM) x_pa_clic_arb_2nd_round( + .prio_in_vec (prio_out_mid_1st), + .prio_out_mid (prio_out_mid_2nd), // Not Use. + .sel_out_onehot (sel_out_2nd_round) +); + +//---------------------------------------------------------- +// Select Priority +//---------------------------------------------------------- +pa_clic_sel #(PRIO_WIDTH, GROUP_NUM) x_pa_clic_lv_sel_2nd_round( + .data_in (sel_out_prio_vec_1st), + .sel_in_onehot (sel_out_2nd_round), + .data_out (prio_out) +); + +//---------------------------------------------------------- +// Select ID +//---------------------------------------------------------- +pa_clic_sel #(ID_WIDTH, GROUP_NUM) x_pa_clic_id_sel_2nd_round( + .data_in (sel_out_id_vec_1st), + .sel_in_onehot (sel_out_2nd_round), + .data_out (id_out) +); + +//---------------------------------------------------------- +// Select hv & req +//---------------------------------------------------------- +assign hv_out = |(sel_out_hv_vec_1st[GROUP_NUM-1:0] & sel_out_2nd_round[GROUP_NUM-1:0]); +assign req_out = |(sel_out_req_vec_1st[GROUP_NUM-1:0] & sel_out_2nd_round[GROUP_NUM-1:0]); + +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_busif.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_busif.v new file mode 100644 index 0000000000000000000000000000000000000000..5b2598a065e49bbb044ee13fdad49373e1bae198 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_busif.v @@ -0,0 +1,272 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_busif( + busif_ctrl_cliccfg_sel, + busif_ctrl_clicinfo_sel, + busif_ctrl_mintthresh_sel, + busif_kid_clicintattr_sel, + busif_kid_clicintctl_sel, + busif_kid_clicintie_sel, + busif_kid_clicintip_sel, + busif_kid_wdata, + busif_xx_write_vld, + clic_clk, + clic_clk_en, + clic_tcipif_cmplt, + clic_tcipif_rdata, + cpurst_b, + ctrl_busif_cliccfg_val, + ctrl_busif_clicinfo_val, + ctrl_busif_mintthresh_val, + ifu_clic_warm_up, + kid_busif_rdata_vec, + pad_yy_icg_scan_en, + pad_yy_scan_mode, + tcipif_clic_addr, + tcipif_clic_sel, + tcipif_clic_size, + tcipif_clic_wdata, + tcipif_clic_write +); + +// &Ports; @24 +input clic_clk; +input clic_clk_en; +input cpurst_b; +input [31 :0] ctrl_busif_cliccfg_val; +input [31 :0] ctrl_busif_clicinfo_val; +input [31 :0] ctrl_busif_mintthresh_val; +input ifu_clic_warm_up; +input [4607:0] kid_busif_rdata_vec; +input pad_yy_icg_scan_en; +input pad_yy_scan_mode; +input [15 :0] tcipif_clic_addr; +input tcipif_clic_sel; +input [1 :0] tcipif_clic_size; +input [31 :0] tcipif_clic_wdata; +input tcipif_clic_write; +output busif_ctrl_cliccfg_sel; +output busif_ctrl_clicinfo_sel; +output busif_ctrl_mintthresh_sel; +output [143 :0] busif_kid_clicintattr_sel; +output [143 :0] busif_kid_clicintctl_sel; +output [143 :0] busif_kid_clicintie_sel; +output [143 :0] busif_kid_clicintip_sel; +output [31 :0] busif_kid_wdata; +output busif_xx_write_vld; +output clic_tcipif_cmplt; +output [31 :0] clic_tcipif_rdata; + +// &Regs; @25 +reg [15 :0] busif_addr; +reg [3 :0] busif_kid_reg_sel; +reg busif_sel; +reg [1 :0] busif_size; +reg [31 :0] busif_wdata; +reg busif_write; +reg [31 :0] clic_tcipif_rdata_test_point; + +// &Wires; @26 +wire busif_cmplt; +wire busif_ctrl_cliccfg_sel; +wire busif_ctrl_clicinfo_sel; +wire busif_ctrl_mintthresh_sel; +wire [143 :0] busif_kid_sel; +wire [31 :0] busif_kid_wdata; +wire busif_read_vld; +wire busif_sel_updt; +wire busif_xx_write_vld; +wire clic_clk; +wire clic_clk_en; +wire [15 :0] clic_kid_base; +wire clic_tcipif_cmplt; +wire [31 :0] clic_tcipif_rdata; +wire [31 :0] clic_tcipif_rdata_pre; +wire cliccfg_sel; +wire clicinfo_sel; +wire cpurst_b; +wire [31 :0] ctrl_busif_cliccfg_val; +wire [31 :0] ctrl_busif_clicinfo_val; +wire [31 :0] ctrl_busif_mintthresh_val; +wire [31 :0] kid_busif_rdata; +wire mintthresh_sel; +wire pad_yy_icg_scan_en; +wire pad_yy_scan_mode; +wire tcip_clk; +wire tcip_clk_en; +wire [15 :0] tcipif_clic_addr; +wire tcipif_clic_sel; +wire [1 :0] tcipif_clic_size; +wire [31 :0] tcipif_clic_wdata; +wire tcipif_clic_write; + + +parameter CLICINTNUM = `CLIC_INTNUM; + +parameter CLICCFG_BASE = 16'h0000; +parameter CLICINFO_BASE = 16'h0004; +parameter MINTTHRESH_BASE = 16'h0008; + +parameter CLICKID_BASE = 16'h1000; + +assign clic_kid_base[15:0] = CLICKID_BASE; +// &Force("nonport", "clic_kid_base"); @37 + +assign busif_sel_updt = busif_sel ^ tcipif_clic_sel; +always @ (posedge tcip_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + busif_sel <= 1'b0; + end + else if (busif_sel) begin + busif_sel <= 1'b0; + end + else if (busif_sel_updt) begin + busif_sel <= tcipif_clic_sel; + end +end + +always @ (posedge tcip_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + busif_addr[15:0] <= 16'b0; + busif_write <= 1'b0; + busif_size[1:0] <= 2'b0; + busif_wdata[31:0] <= 32'b0; + end + else if (tcipif_clic_sel) begin + busif_addr[15:0] <= tcipif_clic_addr[15:0]; + busif_write <= tcipif_clic_write; + busif_size[1:0] <= tcipif_clic_size[1:0]; + busif_wdata[31:0] <= tcipif_clic_wdata[31:0]; + end +end + +assign tcip_clk_en = tcipif_clic_sel + || busif_sel_updt; +// &Instance("gated_clk_cell", "x_tcip_clk"); @72 +gated_clk_cell x_tcip_clk ( + .clk_in (clic_clk ), + .clk_out (tcip_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (tcip_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (clic_clk), @73 +// .external_en (1'b0), @74 +// .global_en (1'b1), @75 +// .module_en (1'b0), @76 +// .local_en (tcip_clk_en), @77 +// .clk_out (tcip_clk)); @78 + +// &Force("input", "ifu_clic_warm_up"); @87 + +assign cliccfg_sel = busif_addr[15:0] == CLICCFG_BASE; +assign clicinfo_sel = busif_addr[15:0] == CLICINFO_BASE; +assign mintthresh_sel = busif_addr[15:0] == MINTTHRESH_BASE; +assign busif_ctrl_cliccfg_sel = cliccfg_sel; +assign busif_ctrl_clicinfo_sel = clicinfo_sel; +assign busif_ctrl_mintthresh_sel = mintthresh_sel; + +assign busif_cmplt = busif_sel; +assign clic_tcipif_cmplt = busif_cmplt && clic_clk_en; +assign busif_kid_wdata[31:0] = busif_wdata[31:0]; + +// &CombBeg; @100 +always @( busif_addr[1:0] + or busif_size[1:0]) +begin + case({busif_addr[1:0], busif_size[1:0]}) + 4'b00_00: busif_kid_reg_sel[3:0] = 4'b0001; // Byte + 4'b01_00: busif_kid_reg_sel[3:0] = 4'b0010; + 4'b10_00: busif_kid_reg_sel[3:0] = 4'b0100; + 4'b11_00: busif_kid_reg_sel[3:0] = 4'b1000; // Half word + 4'b00_01: busif_kid_reg_sel[3:0] = 4'b0011; + 4'b10_01: busif_kid_reg_sel[3:0] = 4'b1100; + 4'b00_10: busif_kid_reg_sel[3:0] = 4'b1111; + default: busif_kid_reg_sel[3:0] = 4'b0000; + endcase +// &CombEnd; @111 +end +// &Force("nonport", "busif_kid_reg_sel"); @112 +// &Force("nonport", "busif_kid_sel"); @113 + +// &Force("output", "busif_kid_clicintip_sel"); @115 +// &Force("output", "busif_kid_clicintie_sel"); @116 +// &Force("output", "busif_kid_clicintattr_sel"); @117 +// &Force("output", "busif_kid_clicintctl_sel"); @118 +// &Force("bus", "busif_kid_clicintip_sel", CLICINTNUM-1, 0); @119 +// &Force("bus", "busif_kid_clicintie_sel", CLICINTNUM-1, 0); @120 +// &Force("bus", "busif_kid_clicintattr_sel", CLICINTNUM-1, 0); @121 +// &Force("bus", "busif_kid_clicintctl_sel", CLICINTNUM-1, 0); @122 + +//csky vperl_off +wire [CLICINTNUM-1:0] busif_kid_clicintip_sel; +wire [CLICINTNUM-1:0] busif_kid_clicintie_sel; +wire [CLICINTNUM-1:0] busif_kid_clicintattr_sel; +wire [CLICINTNUM-1:0] busif_kid_clicintctl_sel; + +genvar i; +generate +for (i = 0; i < CLICINTNUM; i = i+1) +begin: BUSIF_KID + assign busif_kid_sel[i] = (busif_addr[15:2] - clic_kid_base[15:2]) == $unsigned(i); + assign busif_kid_clicintip_sel[i] = busif_kid_sel[i] && busif_kid_reg_sel[0]; + assign busif_kid_clicintie_sel[i] = busif_kid_sel[i] && busif_kid_reg_sel[1]; + assign busif_kid_clicintattr_sel[i] = busif_kid_sel[i] && busif_kid_reg_sel[2]; + assign busif_kid_clicintctl_sel[i] = busif_kid_sel[i] && busif_kid_reg_sel[3]; +end +endgenerate +//csky vperl_on + +assign busif_xx_write_vld = busif_sel && busif_write; +assign busif_read_vld = busif_sel && !busif_write; +//========================================================== +// Read Sel +//========================================================== +// &Force("input", "kid_busif_rdata_vec"); @148 +// &Force("bus", "kid_busif_rdata_vec", (CLICINTNUM)*32-1, 0); @149 +// &Force("nonport", "kid_busif_rdata"); @150 +//csky vperl_off +pa_clic_sel #(32, CLICINTNUM) x_pa_clic_kid_rdata_sel( + .data_in (kid_busif_rdata_vec), + .sel_in_onehot (busif_kid_sel), + .data_out (kid_busif_rdata) +); +//csky vperl_on + +assign clic_tcipif_rdata_pre[31:0] = {{32{cliccfg_sel}} & ctrl_busif_cliccfg_val[31:0] + | {32{clicinfo_sel}} & ctrl_busif_clicinfo_val[31:0] + | {32{mintthresh_sel}} & ctrl_busif_mintthresh_val[31:0] + | {32{|busif_kid_sel[CLICINTNUM-1:0]}} & kid_busif_rdata[31:0]} + & {32{busif_read_vld}}; +assign clic_tcipif_rdata[31:0] = pad_yy_scan_mode ? clic_tcipif_rdata_test_point[31:0] : clic_tcipif_rdata_pre[31:0]; + +always @(posedge clic_clk or negedge cpurst_b) +begin + if(!cpurst_b) begin + clic_tcipif_rdata_test_point[31:0] <= 32'b0; + end + else begin + clic_tcipif_rdata_test_point[31:0] <= clic_tcipif_rdata_pre[31:0]; + end +end +// &ModuleEnd; @175 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_cpuif_2cycle.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_cpuif_2cycle.v new file mode 100644 index 0000000000000000000000000000000000000000..9c5a5dbb6865969951a5dfe07844c2ad808ee210 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_cpuif_2cycle.v @@ -0,0 +1,180 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_clic_cpuif_2cycle( + clic_clk_en, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + clic_int_hv, + clic_int_id, + clic_int_il_raw, + clic_int_priv, + cpu_clic_curid, + cpu_clic_int_exit, + cpu_int_exit, + cpurst_b, + ctrl_kid_ack_int, + forever_cpuclk, + pad_yy_icg_scan_en +); + + +// &Ports; @25 +input clic_clk_en; +input clic_int_hv; +input [11 :0] clic_int_id; +input [7 :0] clic_int_il_raw; +input [1 :0] clic_int_priv; +input [11 :0] cpu_clic_curid; +input cpu_clic_int_exit; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output clic_cpu_int_hv; +output [11 :0] clic_cpu_int_id; +output [7 :0] clic_cpu_int_il; +output [1 :0] clic_cpu_int_priv; +output cpu_int_exit; +output [143:0] ctrl_kid_ack_int; + +// &Regs; @26 +reg clic_int_en; +reg [11 :0] cpuif_curid; +reg cpuif_exit; + +// &Wires; @27 +wire clic_clk_en; +wire clic_clk_en_f; +wire clic_cpu_int_hv; +wire [11 :0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire clic_int_hv; +wire [11 :0] clic_int_id; +wire [7 :0] clic_int_il; +wire [7 :0] clic_int_il_raw; +wire [1 :0] clic_int_priv; +wire [11 :0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire [11 :0] cpu_curid; +wire cpu_int_exit; +wire cpuif_clk; +wire cpuif_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire if_clic_en; +wire pad_yy_icg_scan_en; + + +parameter CLICINTNUM = `CLIC_INTNUM; +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; +parameter ID_WIDTH = 12; + +//========================================================== +// Int Exit +//========================================================== +assign cpu_int_exit = cpuif_exit || cpu_clic_int_exit; +// &Force("output", "cpu_int_exit"); @37 +always @ (posedge cpuif_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cpuif_exit <= 1'b0; + else + cpuif_exit <= cpu_clic_int_exit; +end + +always @ (posedge cpuif_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cpuif_curid[ID_WIDTH-1:0] <= {ID_WIDTH{1'b0}}; + else if (cpu_clic_int_exit) + cpuif_curid[ID_WIDTH-1:0] <= cpu_clic_curid[ID_WIDTH-1:0]; +end + +assign cpu_curid[ID_WIDTH-1:0] = cpuif_exit ? cpuif_curid[ID_WIDTH-1:0] + : cpu_clic_curid[ID_WIDTH-1:0]; + +// &Force("output", "ctrl_kid_ack_int"); &Force("bus", "ctrl_kid_ack_int", CLICINTNUM-1, 0); @57 +// &Force("nonport", "cpu_curid"); @58 + +//csky vperl_off +wire [CLICINTNUM-1:0] ctrl_kid_ack_sel; +wire [CLICINTNUM-1:0] ctrl_kid_ack_int; + +genvar i; +generate +for (i = 0; i < CLICINTNUM; i = i+1) +begin: KID_ACK + assign ctrl_kid_ack_sel[i] = cpu_curid[ID_WIDTH-1:0] == ($unsigned(i) & {ID_WIDTH{1'b1}}); + assign ctrl_kid_ack_int[i] = ctrl_kid_ack_sel[i] && cpu_int_exit; +end +endgenerate +//csky vperl_on + +//========================================================== +// Output Interface +//========================================================== +assign clic_int_il[7:0] = {8{if_clic_en}} & clic_int_il_raw[7:0]; +// ATTENTION: Only in 2 cycle, clic_clk_en_f = !clic_clk_en. +assign clic_clk_en_f = !clic_clk_en; +assign if_clic_en = clic_clk_en_f || clic_int_en; + +always @ (posedge cpuif_clk or negedge cpurst_b) +begin + if (!cpurst_b) + clic_int_en <= 1'b0; + else if (cpu_clic_int_exit) + clic_int_en <= 1'b0; + else + clic_int_en <= |clic_int_il[7:0]; +end + +assign clic_cpu_int_hv = clic_int_hv; +assign clic_cpu_int_id[ID_WIDTH-1:0] = clic_int_id[ID_WIDTH-1:0]; +assign clic_cpu_int_priv[1:0] = clic_int_priv[1:0]; +assign clic_cpu_int_il[7:0] = clic_int_il[7:0]; + +//========================================================== +// ICG +//========================================================== +assign cpuif_clk_en = |clic_int_il_raw[7:0] + || cpuif_exit + || clic_int_en; +// &Instance("gated_clk_cell", "x_cpuif_clk"); @103 +gated_clk_cell x_cpuif_clk ( + .clk_in (forever_cpuclk ), + .clk_out (cpuif_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (cpuif_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @104 +// .external_en (1'b0), @105 +// .global_en (1'b1), @106 +// .module_en (1'b0), @107 +// .local_en (cpuif_clk_en), @108 +// .clk_out (cpuif_clk)); @109 + +// &ModuleEnd; @111 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..6e77a2711f1c30b970f64ba15250e43b668c5e7e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ctrl.v @@ -0,0 +1,352 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_ctrl( + arb_ctrl_int_hv, + arb_ctrl_int_id, + arb_ctrl_int_il, + arb_ctrl_int_mode, + arb_ctrl_int_req_raw, + busif_ctrl_cliccfg_sel, + busif_ctrl_clicinfo_sel, + busif_ctrl_mintthresh_sel, + busif_kid_wdata, + busif_xx_write_vld, + clic_clk, + clic_clk_en, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + clicreg_clk, + cpu_clic_curid, + cpu_clic_int_exit, + cpu_clic_mode, + cpurst_b, + ctrl_busif_cliccfg_val, + ctrl_busif_clicinfo_val, + ctrl_busif_mintthresh_val, + ctrl_clicreg_en, + ctrl_kid_ack_int, + ctrl_xx_int_lv_or_mask, + ctrl_xx_mode_or_mask, + forever_cpuclk, + pad_yy_icg_scan_en +); + +// &Ports; @23 +input arb_ctrl_int_hv; +input [11 :0] arb_ctrl_int_id; +input [7 :0] arb_ctrl_int_il; +input arb_ctrl_int_mode; +input arb_ctrl_int_req_raw; +input busif_ctrl_cliccfg_sel; +input busif_ctrl_clicinfo_sel; +input busif_ctrl_mintthresh_sel; +input [31 :0] busif_kid_wdata; +input busif_xx_write_vld; +input clic_clk; +input clic_clk_en; +input clicreg_clk; +input [11 :0] cpu_clic_curid; +input cpu_clic_int_exit; +input [1 :0] cpu_clic_mode; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output clic_cpu_int_hv; +output [11 :0] clic_cpu_int_id; +output [7 :0] clic_cpu_int_il; +output [1 :0] clic_cpu_int_priv; +output [31 :0] ctrl_busif_cliccfg_val; +output [31 :0] ctrl_busif_clicinfo_val; +output [31 :0] ctrl_busif_mintthresh_val; +output ctrl_clicreg_en; +output [143:0] ctrl_kid_ack_int; +output [2 :0] ctrl_xx_int_lv_or_mask; +output ctrl_xx_mode_or_mask; + +// &Regs; @24 +reg clic_int_hv; +reg [11 :0] clic_int_id; +reg [7 :0] clic_int_il_raw; +reg [1 :0] clic_int_priv; +reg [3 :0] cliccfg_nlbits; +reg [7 :0] mintthresh_mth; + +// &Wires; @25 +wire arb_ctrl_int_hv; +wire [11 :0] arb_ctrl_int_id; +wire [7 :0] arb_ctrl_int_il; +wire arb_ctrl_int_mode; +wire arb_ctrl_int_req_raw; +wire busif_ctrl_cliccfg_sel; +wire busif_ctrl_mintthresh_sel; +wire [31 :0] busif_kid_wdata; +wire busif_xx_write_vld; +wire clic_clk; +wire clic_clk_en; +wire clic_cpu_int_hv; +wire [11 :0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire [1 :0] cliccfg_nmbits; +wire cliccfg_nmbits_0; +wire cliccfg_nvbits; +wire [31 :0] cliccfg_reg; +wire [7 :0] cliccfg_updt_val; +wire [3 :0] clicinfo_arch_ver; +wire [3 :0] clicinfo_clicintctlbits; +wire [3 :0] clicinfo_impl_ver; +wire [12 :0] clicinfo_num_int; +wire [31 :0] clicinfo_reg; +wire clicreg_clk; +wire [11 :0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire [1 :0] cpu_clic_mode; +wire cpu_int_exit; +wire cpurst_b; +wire [31 :0] ctrl_busif_cliccfg_val; +wire [31 :0] ctrl_busif_clicinfo_val; +wire [31 :0] ctrl_busif_mintthresh_val; +wire ctrl_cliccfg_updt_vld; +wire ctrl_clicreg_en; +wire ctrl_int_gt_thresh; +wire [143:0] ctrl_kid_ack_int; +wire ctrl_mintthresh_updt_vld; +wire ctrl_mode_vld; +wire [7 :0] ctrl_thresh; +wire ctrl_write_vld; +wire ctrl_xx_mode_or_mask; +wire forever_cpuclk; +wire [7 :0] mintthresh_hth; +wire [31 :0] mintthresh_reg; +wire [7 :0] mintthresh_sth; +wire [31 :0] mintthresh_updt_val; +wire [7 :0] mintthresh_uth; +wire out_clk; +wire out_clk_en; +wire pad_yy_icg_scan_en; + + +parameter CLICINTNUM = `CLIC_INTNUM; +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; +parameter ID_WIDTH = 12; + +parameter INT_MODE_U = 1'b0; +parameter INT_MODE_M = 1'b1; +parameter CPU_MODE_U = 2'b00; +parameter CPU_MODE_M = 2'b11; + +//========================================================== +// Rename Input +//========================================================== +assign cliccfg_updt_val[7:0] = busif_kid_wdata[7:0]; +// assign clicinfo_updt_val[31:0] = busif_kid_wdata[31:0]; +assign mintthresh_updt_val[31:0] = busif_kid_wdata[31:0]; + + +//========================================================== +// Write Vld +//========================================================== +assign ctrl_mode_vld = cpu_clic_mode[1:0] == CPU_MODE_M; +assign ctrl_write_vld = busif_xx_write_vld && ctrl_mode_vld; +assign ctrl_cliccfg_updt_vld = ctrl_write_vld && busif_ctrl_cliccfg_sel; +// &Force("input", "busif_ctrl_clicinfo_sel"); @50 +// assign ctrl_clicinfo_updt_vld = ctrl_write_vld && busif_ctrl_clicinfo_sel; +assign ctrl_mintthresh_updt_vld = ctrl_write_vld && busif_ctrl_mintthresh_sel; + +//========================================================== +// CLICCFG +//========================================================== +always @ (posedge clicreg_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cliccfg_nlbits[3:0] <= 4'b0; + else if (ctrl_cliccfg_updt_vld) + cliccfg_nlbits[3:0] <= cliccfg_updt_val[4] ? 4'd8 : cliccfg_updt_val[4:1]; // if nlbits > 8, it will be 8. + else + cliccfg_nlbits[3:0] <= cliccfg_nlbits[3:0]; +end + +assign cliccfg_nmbits_0 = 1'b0; +assign ctrl_xx_mode_or_mask = !cliccfg_nmbits_0; + +// cliccfg_nmbits only can be 0/1 so [1] is not use. +assign cliccfg_nmbits[1:0] = {1'b0, cliccfg_nmbits_0}; +assign cliccfg_nvbits = 1'b1; +assign cliccfg_reg[31:0] = {25'b0, + cliccfg_nmbits[1:0], + cliccfg_nlbits[3:0], + cliccfg_nvbits}; + + + +//========================================================== +// CLICINFO +//========================================================== +//csky vperl_off +assign clicinfo_clicintctlbits[3:0] = $unsigned(CLICINTCTLBITS) & 4'hf; +assign clicinfo_arch_ver[3:0] = 4'b0; +assign clicinfo_impl_ver[3:0] = 4'b0; +assign clicinfo_num_int[12:0] = $unsigned(CLICINTNUM) & 13'h1fff; +//csky vperl_on +// &Force("nonport", "clicinfo_clicintctlbits"); @101 +// &Force("nonport", "clicinfo_arch_ver"); @102 +// &Force("nonport", "clicinfo_impl_ver"); @103 +// &Force("nonport", "clicinfo_num_int"); @104 + +assign clicinfo_reg[31:0] = {7'b0, + clicinfo_clicintctlbits[3:0], + clicinfo_arch_ver[3:0], + clicinfo_impl_ver[3:0], + clicinfo_num_int[12:0]}; + + +//========================================================== +// MINTTHRESH +//========================================================== +always @ (posedge clicreg_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + mintthresh_mth[7:0] <= 8'b0; + // mintthresh_hth[7:0] <= 8'b0; + // mintthresh_sth[7:0] <= 8'b0; + end + else if (ctrl_mintthresh_updt_vld) begin + mintthresh_mth[7:0] <= mintthresh_updt_val[31:24]; + // mintthresh_hth[7:0] <= mintthresh_updt_val[23:16]; + // mintthresh_sth[7:0] <= mintthresh_updt_val[15:8]; + end + else begin + mintthresh_mth[7:0] <= mintthresh_mth[7:0]; + // mintthresh_hth[7:0] <= mintthresh_hth[7:0]; + // mintthresh_sth[7:0] <= mintthresh_sth[7:0]; + end +end + +assign mintthresh_uth[7:0] = 8'b0; + +assign mintthresh_hth[7:0] = 8'b0; +assign mintthresh_sth[7:0] = 8'b0; + +assign mintthresh_reg[31:0] = {mintthresh_mth[7:0], + mintthresh_hth[7:0], + mintthresh_sth[7:0], + mintthresh_uth[7:0]}; + + +//========================================================== +// For Gate Clk Cell +//========================================================== +assign ctrl_clicreg_en = ctrl_mintthresh_updt_vld || ctrl_cliccfg_updt_vld; +//========================================================== +// To busif +//========================================================== +// &Force("output", "ctrl_xx_int_lv_or_mask"); &Force("bus", "ctrl_xx_int_lv_or_mask", CLICINTCTLBITS-1, 0); @165 +//csky vperl_off +wire [CLICINTCTLBITS-1:0] ctrl_xx_int_lv_or_mask; + +genvar i; +generate +for (i = 0; i < CLICINTCTLBITS; i = i+1) +begin: LEVEL_MASK + assign ctrl_xx_int_lv_or_mask[CLICINTCTLBITS-1-i] = !(($unsigned(i) & {4'hf}) < cliccfg_nlbits[3:0]); +end +endgenerate +//csky vperl_on + +//========================================================== +// To busif +//========================================================== +assign ctrl_busif_cliccfg_val[31:0] = cliccfg_reg[31:0] & {32{ctrl_mode_vld}}; +assign ctrl_busif_clicinfo_val[31:0] = clicinfo_reg[31:0] & {32{ctrl_mode_vld}}; +assign ctrl_busif_mintthresh_val[31:0] = mintthresh_reg[31:0] & {32{ctrl_mode_vld}}; + +//========================================================== +// Final judge mintthresh +//========================================================== +assign ctrl_thresh[7:0] = arb_ctrl_int_mode == INT_MODE_M ? mintthresh_mth[7:0] + : mintthresh_uth[7:0]; +assign ctrl_int_gt_thresh = ctrl_thresh[7:0] < arb_ctrl_int_il[7:0]; + +always @ (posedge out_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + clic_int_hv <= 1'b0; + clic_int_id[ID_WIDTH-1:0] <= {ID_WIDTH{1'b0}}; + clic_int_priv[1:0] <= 2'b0; + clic_int_il_raw[7:0] <= 8'b0; + end + else if (cpu_int_exit) begin + clic_int_hv <= 1'b0; + clic_int_id[ID_WIDTH-1:0] <= {ID_WIDTH{1'b0}}; + clic_int_priv[1:0] <= 2'b0; + clic_int_il_raw[7:0] <= 8'b0; + end + else if (out_clk_en) begin + clic_int_hv <= arb_ctrl_int_hv; + clic_int_id[ID_WIDTH-1:0] <= arb_ctrl_int_id[ID_WIDTH-1:0]; + clic_int_priv[1:0] <= {2{arb_ctrl_int_mode}}; + clic_int_il_raw[7:0] <= {8{ctrl_int_gt_thresh}} & arb_ctrl_int_il[7:0]; + end +end + +assign out_clk_en = arb_ctrl_int_req_raw + || |clic_int_il_raw[7:0]; + +// &Instance("gated_clk_cell", "x_out_clk"); @217 +gated_clk_cell x_out_clk ( + .clk_in (clic_clk ), + .clk_out (out_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (out_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (clic_clk), @218 +// .external_en (1'b0), @219 +// .global_en (1'b1), @220 +// .module_en (1'b0), @221 +// .local_en (out_clk_en), @222 +// .clk_out (out_clk)); @223 + +// &Instance("pa_clic_cpuif_2cycle"); @226 +pa_clic_cpuif_2cycle x_pa_clic_cpuif_2cycle ( + .clic_clk_en (clic_clk_en ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .clic_int_hv (clic_int_hv ), + .clic_int_id (clic_int_id ), + .clic_int_il_raw (clic_int_il_raw ), + .clic_int_priv (clic_int_priv ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpu_int_exit (cpu_int_exit ), + .cpurst_b (cpurst_b ), + .ctrl_kid_ack_int (ctrl_kid_ack_int ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_clic_cpuif"); @228 + +// &ModuleEnd; @231 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_expand.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_expand.v new file mode 100644 index 0000000000000000000000000000000000000000..27504d9a793fe4c74ed6e769fc67ea7af402c766 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_expand.v @@ -0,0 +1,42 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_expand( + // input + data_in_vec, + // output + expand_out_vec +); + +parameter WIDTH = 6; +parameter NUM = 32; +localparam EXP_WIDTH = 1 <<< WIDTH; + +input [WIDTH*NUM-1:0] data_in_vec; +output [EXP_WIDTH*NUM-1:0] expand_out_vec; + +wire [WIDTH*NUM-1:0] data_in_vec; +wire [EXP_WIDTH*NUM-1:0] expand_out_vec; + +genvar i; + +generate + for (i = 0; i < NUM; i = i+1) + begin: EXPAND + assign expand_out_vec[EXP_WIDTH*i+:EXP_WIDTH] = {{EXP_WIDTH-1{1'b0}}, 1'b1} << data_in_vec[WIDTH*i+:WIDTH]; + end +endgenerate + +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ff1_onehot.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ff1_onehot.v new file mode 100644 index 0000000000000000000000000000000000000000..b8eea4107a7c801e2ff6450e913092c008e7b512 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_ff1_onehot.v @@ -0,0 +1,40 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_ff1_onehot( + data_in, + ff1_out_onehot +); + +parameter WIDTH = 32; + +input [WIDTH-1:0] data_in; +output [WIDTH-1:0] ff1_out_onehot; + +wire [WIDTH:0] ff1_tmp; + +assign ff1_tmp[WIDTH] = 1'b0; +genvar i; + +generate + for (i = 0; i < WIDTH; i = i+1) + begin: FF1_ONEHOT + assign ff1_tmp[i] = data_in[i] || ff1_tmp[i+1]; + end +endgenerate + +assign ff1_out_onehot[WIDTH-1:0] = ff1_tmp[WIDTH:1] ^ ff1_tmp[WIDTH-1:0]; + +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid.v new file mode 100644 index 0000000000000000000000000000000000000000..838835904fdb273256a2623b655c4771f970619c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid.v @@ -0,0 +1,379 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_kid( + busif_kid_clicintattr_sel, + busif_kid_clicintctl_sel, + busif_kid_clicintie_sel, + busif_kid_clicintip_sel, + busif_kid_wdata, + busif_xx_write_vld, + clic_clk, + cpu_clic_mode, + cpurst_b, + ctrl_kid_ack_int, + ctrl_xx_mode_or_mask, + forever_cpuclk, + kid_arb_int_all, + kid_arb_int_hv, + kid_arb_int_req, + kid_busif_rdata, + kid_int_vld, + pad_yy_icg_scan_en +); + +// &Ports; @23 +input busif_kid_clicintattr_sel; +input busif_kid_clicintctl_sel; +input busif_kid_clicintie_sel; +input busif_kid_clicintip_sel; +input [31:0] busif_kid_wdata; +input busif_xx_write_vld; +input clic_clk; +input [1 :0] cpu_clic_mode; +input cpurst_b; +input ctrl_kid_ack_int; +input ctrl_xx_mode_or_mask; +input forever_cpuclk; +input kid_int_vld; +input pad_yy_icg_scan_en; +output [3 :0] kid_arb_int_all; +output kid_arb_int_hv; +output kid_arb_int_req; +output [31:0] kid_busif_rdata; + +// &Regs; @24 +reg clicintattr_shv; +reg [1 :0] clicintattr_trig; +reg int_enable; +reg int_pending; +reg int_pending_updt_val; +reg [2 :0] int_prio; +reg int_vld_ff_1; +reg int_vld_ff_2; + +// &Wires; @25 +wire busif_kid_clicintattr_sel; +wire busif_kid_clicintctl_sel; +wire busif_kid_clicintie_sel; +wire busif_kid_clicintip_sel; +wire [31:0] busif_kid_wdata; +wire busif_xx_write_vld; +wire clic_clk; +wire clic_kid_clk; +wire clic_kid_clk_en; +wire [1 :0] clicintattr_mode; +wire [7 :0] clicintattr_reg; +wire [7 :0] clicintattr_updt_val; +wire clicintattr_updt_vld; +wire [7 :0] clicintctl_reg; +wire [7 :0] clicintctl_updt_val; +wire clicintctl_updt_vld; +wire [7 :0] clicintie_reg; +wire clicintie_updt_vld; +wire [7 :0] clicintip_reg; +wire [1 :0] cpu_clic_mode; +wire cpurst_b; +wire ctrl_kid_ack_int; +wire forever_cpuclk; +wire int_enable_updt_val; +wire int_level; +wire int_neg_pulse; +wire int_neg_pulse_1; +wire int_neg_pulse_2; +wire int_pending_clear; +wire int_pending_set; +wire int_pending_updt_val_raw; +wire int_pending_updt_vld; +wire int_pos_pulse; +wire int_pos_pulse_1; +wire int_pos_pulse_2; +wire int_pulse; +wire int_vld; +wire [3 :0] kid_arb_int_all; +wire kid_arb_int_hv; +wire kid_arb_int_req; +wire [31:0] kid_busif_rdata; +wire kid_ctrl_clicintattr_en; +wire kid_ctrl_clicintctl_en; +wire kid_ctrl_clicintie_en; +wire kid_ctrl_clicintip_en; +wire kid_int_mode; +wire kid_int_vld; +wire kid_mode_vld; +wire kid_sample_clk; +wire kid_sample_clk_en; +wire kid_write_vld; +wire pad_yy_icg_scan_en; +wire sw_clear_pending; +wire sw_set_pending; + + +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; + +parameter INT_MODE_U = 1'b0; +parameter INT_MODE_M = 1'b1; +parameter CPU_MODE_U = 2'b00; +parameter CPU_MODE_M = 2'b11; + +//========================================================== +// Rename Input +//========================================================== +assign int_pending_updt_val_raw = busif_kid_wdata[0]; +assign int_enable_updt_val = busif_kid_wdata[8]; +assign clicintattr_updt_val[7:0] = busif_kid_wdata[23:16]; +assign clicintctl_updt_val[7:0] = busif_kid_wdata[31:24]; + +assign int_vld = kid_int_vld; + + +//========================================================== +// kid mode Vld +//========================================================== +// if cpu mode is M, all is vld. +// if cpu mode is U, only U mode int is vld. +assign kid_mode_vld = cpu_clic_mode[1:0] == CPU_MODE_M + || cpu_clic_mode[1:0] == CPU_MODE_U && kid_int_mode == INT_MODE_U; + +//========================================================== +// Write Vld +//========================================================== +assign kid_write_vld = busif_xx_write_vld && kid_mode_vld; +assign sw_set_pending = kid_write_vld && busif_kid_clicintip_sel && int_pending_updt_val_raw; +assign sw_clear_pending = kid_write_vld && busif_kid_clicintip_sel && !int_pending_updt_val_raw; +assign clicintie_updt_vld = kid_write_vld && busif_kid_clicintie_sel; +assign clicintattr_updt_vld = kid_write_vld && busif_kid_clicintattr_sel; +assign clicintctl_updt_vld = kid_write_vld && busif_kid_clicintctl_sel; + +//------------------------------------------------ +// Interrupt Sample +//------------------------------------------------ +assign kid_sample_clk_en = int_vld ^ int_vld_ff_1 + || int_vld_ff_1 ^ int_vld_ff_2; + +always@(posedge kid_sample_clk or negedge cpurst_b) +begin + if(!cpurst_b) begin + int_vld_ff_1 <= 1'b0; + int_vld_ff_2 <= 1'b0; + end + else begin + int_vld_ff_1 <= int_vld; + int_vld_ff_2 <= int_vld_ff_1; + end +end + +assign int_level = int_vld_ff_1; + +assign int_pos_pulse_1 = int_vld && !int_vld_ff_1; +assign int_neg_pulse_1 = !int_vld && int_vld_ff_1; + +assign int_pos_pulse_2 = int_vld_ff_1 && !int_vld_ff_2; +assign int_neg_pulse_2 = !int_vld_ff_1 && int_vld_ff_2; + +assign int_pos_pulse = int_pos_pulse_1 || int_pos_pulse_2; +assign int_neg_pulse = int_neg_pulse_1 || int_neg_pulse_2; +//=========================================================== +// interrupt control/status register +//=========================================================== + +//------------------------------------------------ +// security bit +//------------------------------------------------ +// assign op_en = 1'b1; +// // &Force("input","ctl_xx_prot_sec"); @130 +// // &Force("input","int_sec_updt_val"); @131 + +//========================================================== +// CLICINTIP +//========================================================== +assign int_pulse = clicintattr_trig[1:0] == 2'b01 && int_pos_pulse + || clicintattr_trig[1:0] == 2'b11 && int_neg_pulse; + +assign int_pending_set = int_pulse || sw_set_pending; +assign int_pending_clear = ctrl_kid_ack_int || sw_clear_pending; + +assign int_pending_updt_vld = int_pending_set || int_pending_clear; + +// assign kid_ctrl_clicintip_en = !int_pending & int_pending_set || +// int_pending & int_pending_clear & !int_pending_set; +assign kid_ctrl_clicintip_en = int_pending_set + || int_pending + || !clicintattr_trig[0] && (int_pending ^ int_level); + + +// &CombBeg; @152 +always @( int_pending_clear + or int_pending + or int_pending_set) +begin +if (int_pending_set) + int_pending_updt_val = 1'b1; +else if (int_pending_clear) + int_pending_updt_val = 1'b0; +else + int_pending_updt_val = int_pending; +// &CombEnd; @159 +end + +always@(posedge clic_kid_clk or negedge cpurst_b) +begin + if (!cpurst_b) + int_pending <= 1'b0; + else if (!clicintattr_trig[0]) + int_pending <= int_level; + else if (int_pending_updt_vld) + int_pending <= int_pending_updt_val; + else + int_pending <= int_pending; +end +assign clicintip_reg[7:0] = {7'b0, int_pending}; +//========================================================== +// CLICINTIE +//========================================================== +// assign int_enable_updt_vld = op_en && clicintie_updt_vld; +assign kid_ctrl_clicintie_en = clicintie_updt_vld; + +always@(posedge clic_kid_clk or negedge cpurst_b) +begin + if(!cpurst_b) + int_enable <= 1'b0; + else if (clicintie_updt_vld) + int_enable <= int_enable_updt_val; + else + int_enable <= int_enable; +end +assign clicintie_reg[7:0] = {7'b0, int_enable}; +//========================================================== +// CLICINTATTR +//========================================================== +assign kid_ctrl_clicintattr_en = clicintattr_updt_vld; + +always @ (posedge clic_kid_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + clicintattr_trig[1:0] <= 2'b0; + clicintattr_shv <= 1'b0; + end + else if (clicintattr_updt_vld) begin + clicintattr_trig[1:0] <= clicintattr_updt_val[2:1]; + clicintattr_shv <= clicintattr_updt_val[0]; + end + else begin + clicintattr_trig[1:0] <= clicintattr_trig[1:0]; + clicintattr_shv <= clicintattr_shv; + end +end +// &Force("input", "ctrl_xx_mode_or_mask"); @225 +assign clicintattr_mode[1:0] = 2'b11; +assign kid_int_mode = 1'b1; + +assign clicintattr_reg[7:0] = {clicintattr_mode[1:0], + 3'b0, + clicintattr_trig[1:0], + clicintattr_shv}; + + +//========================================================== +// CLICINTCTL +//========================================================== +assign kid_ctrl_clicintctl_en = clicintctl_updt_vld; + +always@(posedge clic_kid_clk or negedge cpurst_b) +begin + if(!cpurst_b) + int_prio[CLICINTCTLBITS-1:0] <= {CLICINTCTLBITS{1'b0}}; + else if (clicintctl_updt_vld) + int_prio[CLICINTCTLBITS-1:0] <= clicintctl_updt_val[7:8-CLICINTCTLBITS]; + else + int_prio[CLICINTCTLBITS-1:0] <= int_prio[CLICINTCTLBITS-1:0]; +end + +assign clicintctl_reg[7:0] = {int_prio[CLICINTCTLBITS-1:0], + {(8-CLICINTCTLBITS){1'b1}}}; + + +//========================================================== +// Read Data +//========================================================== +assign kid_busif_rdata[31:0] = {({8{busif_kid_clicintctl_sel}} & clicintctl_reg[7:0]), + ({8{busif_kid_clicintattr_sel}} & clicintattr_reg[7:0]), + ({8{busif_kid_clicintie_sel}} & clicintie_reg[7:0]), + ({8{busif_kid_clicintip_sel}} & clicintip_reg[7:0])} + & {32{kid_mode_vld}}; + + +//========================================================== +// OUTPUT +//========================================================== +// TO arbiter +//------------------------------------------------ + +assign kid_arb_int_req = int_enable & int_pending; +// &Force("output", "kid_arb_int_req"); @272 +assign kid_arb_int_hv = clicintattr_shv; +// int_all has three field: +// [CLICINTCTLBITS]: mode +// [CLICINTCTLBITS-1: CLICINTCTLBITS-1-nlbits]: int level +// [CLICINTCTLBITS-2-nlbits]: prio level +assign kid_arb_int_all[CLICINTCTLBITS:0] = {kid_int_mode, + int_prio[CLICINTCTLBITS-1:0]} + & {(CLICINTCTLBITS+1){kid_arb_int_req}}; +// assign kid_arb_int_sec = 1'b0; + +assign clic_kid_clk_en = kid_ctrl_clicintip_en + || kid_ctrl_clicintie_en + || kid_ctrl_clicintattr_en + || kid_ctrl_clicintctl_en; + +// &Instance("gated_clk_cell", "x_clic_kid_clk"); @292 +gated_clk_cell x_clic_kid_clk ( + .clk_in (clic_clk ), + .clk_out (clic_kid_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (clic_kid_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (clic_clk), @293 +// .external_en (1'b0), @294 +// .global_en (1'b1), @295 +// .module_en (1'b0), @296 +// .local_en (clic_kid_clk_en), @297 +// .clk_out (clic_kid_clk)); @298 + +// &Instance("gated_clk_cell", "x_kid_sample_clk"); @300 +gated_clk_cell x_kid_sample_clk ( + .clk_in (forever_cpuclk ), + .clk_out (kid_sample_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (kid_sample_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @301 +// .external_en (1'b0), @302 +// .global_en (1'b1), @303 +// .module_en (1'b0), @304 +// .local_en (kid_sample_clk_en), @305 +// .clk_out (kid_sample_clk)); @306 + +// &ModuleEnd; @308 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid_dummy.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid_dummy.v new file mode 100644 index 0000000000000000000000000000000000000000..2525c76c0eff5789820e8d765d6cdf798f94b809 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_kid_dummy.v @@ -0,0 +1,47 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_kid_dummy( + kid_arb_int_all, + kid_arb_int_hv, + kid_arb_int_req, + kid_busif_rdata +); + +// &Ports; @23 +output [3 :0] kid_arb_int_all; +output kid_arb_int_hv; +output kid_arb_int_req; +output [31:0] kid_busif_rdata; + +// &Regs; @24 + +// &Wires; @25 +wire [3 :0] kid_arb_int_all; +wire kid_arb_int_hv; +wire kid_arb_int_req; +wire [31:0] kid_busif_rdata; + + +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; + +assign kid_arb_int_all[CLICINTCTLBITS:0] = {CLICINTCTLBITS+1{1'b0}}; +assign kid_arb_int_hv = 1'b0; +assign kid_arb_int_req = 1'b0; +assign kid_busif_rdata[31:0] = 32'b0; + +// &ModuleEnd; @34 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_sel.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_sel.v new file mode 100644 index 0000000000000000000000000000000000000000..647ac973a25d29971d7ec292432f637d27161e12 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_sel.v @@ -0,0 +1,68 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clic_sel( + // input + data_in, + sel_in_onehot, + // output + data_out +); + +parameter DATA_WIDTH = 32; +parameter SEL_NUM = 256; + +input [DATA_WIDTH*SEL_NUM-1:0] data_in; +input [SEL_NUM-1:0] sel_in_onehot; + +output [DATA_WIDTH-1:0] data_out; + +wire [DATA_WIDTH-1:0] data_in_2d[SEL_NUM-1:0]; +wire [SEL_NUM-1:0] data_in_2d_rev[DATA_WIDTH-1:0]; +wire [DATA_WIDTH-1:0] data_out; + +//========================================================== +// Generate 2D signal +//========================================================== +genvar i; +genvar j; + +generate + for (i = 0; i < SEL_NUM; i = i+1) begin: EXPAND + assign data_in_2d[i][DATA_WIDTH-1:0] = data_in[i*DATA_WIDTH+:DATA_WIDTH] & {DATA_WIDTH{sel_in_onehot[i]}}; + end +endgenerate + +//========================================================== +// Reverse 2D signal +//========================================================== +generate + for (i = 0; i < SEL_NUM; i = i+1) begin: REVERSEI + for (j = 0; j < DATA_WIDTH; j = j+1) begin: REVERSEJ + assign data_in_2d_rev[j][i] = data_in_2d[i][j]; + end + end +endgenerate + +//========================================================== +// Do or to sel +//========================================================== +generate + for (i = 0; i < DATA_WIDTH; i = i+1) begin: OR_SEL + assign data_out[i] = |data_in_2d_rev[i][SEL_NUM-1:0]; + end +endgenerate + + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_top.v new file mode 100644 index 0000000000000000000000000000000000000000..e558e271f72aa50eb4f5c53750e24ba31d7ec9b8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clic/rtl/pa_clic_top.v @@ -0,0 +1,343 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @27 +module pa_clic_top( + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + clic_tcipif_cmplt, + clic_tcipif_rdata, + clint_cpu_me_int, + clint_cpu_ms_int, + clint_cpu_mt_int, + cpu_clic_curid, + cpu_clic_int_exit, + cpu_clic_mode, + cpurst_b, + forever_cpuclk, + ifu_clic_warm_up, + pad_clic_int_vld, + pad_yy_dft_clk_rst_b, + pad_yy_icg_scan_en, + pad_yy_scan_mode, + tcipif_clic_addr, + tcipif_clic_sel, + tcipif_clic_size, + tcipif_clic_wdata, + tcipif_clic_write +); + +// &Ports; @28 +input clint_cpu_me_int; +input clint_cpu_ms_int; +input clint_cpu_mt_int; +input [11 :0] cpu_clic_curid; +input cpu_clic_int_exit; +input [1 :0] cpu_clic_mode; +input cpurst_b; +input forever_cpuclk; +input ifu_clic_warm_up; +input [127 :0] pad_clic_int_vld; +input pad_yy_dft_clk_rst_b; +input pad_yy_icg_scan_en; +input pad_yy_scan_mode; +input [15 :0] tcipif_clic_addr; +input tcipif_clic_sel; +input [1 :0] tcipif_clic_size; +input [31 :0] tcipif_clic_wdata; +input tcipif_clic_write; +output clic_cpu_int_hv; +output [11 :0] clic_cpu_int_id; +output [7 :0] clic_cpu_int_il; +output [1 :0] clic_cpu_int_priv; +output clic_tcipif_cmplt; +output [31 :0] clic_tcipif_rdata; + +// &Regs; @29 +reg clic_clk_en_raw; +reg clic_test_point; + +// &Wires; @30 +wire arb_ctrl_int_hv; +wire [11 :0] arb_ctrl_int_id; +wire [7 :0] arb_ctrl_int_il; +wire arb_ctrl_int_mode; +wire arb_ctrl_int_req_raw; +wire busif_ctrl_cliccfg_sel; +wire busif_ctrl_clicinfo_sel; +wire busif_ctrl_mintthresh_sel; +wire [143 :0] busif_kid_clicintattr_sel; +wire [143 :0] busif_kid_clicintctl_sel; +wire [143 :0] busif_kid_clicintie_sel; +wire [143 :0] busif_kid_clicintip_sel; +wire [31 :0] busif_kid_wdata; +wire busif_xx_write_vld; +wire clic_clk; +wire clic_clk_en; +wire clic_cpu_int_hv; +wire [11 :0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire clic_rst_b; +wire clic_tcipif_cmplt; +wire [31 :0] clic_tcipif_rdata; +wire clicreg_clk; +wire clint_cpu_me_int; +wire clint_cpu_ms_int; +wire clint_cpu_mt_int; +wire [11 :0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire [1 :0] cpu_clic_mode; +wire cpurst_b; +wire [31 :0] ctrl_busif_cliccfg_val; +wire [31 :0] ctrl_busif_clicinfo_val; +wire [31 :0] ctrl_busif_mintthresh_val; +wire ctrl_clicreg_en; +wire [143 :0] ctrl_kid_ack_int; +wire [2 :0] ctrl_xx_int_lv_or_mask; +wire ctrl_xx_mode_or_mask; +wire forever_cpuclk; +wire ifu_clic_warm_up; +wire [575 :0] kid_arb_int_all_vec; +wire [143 :0] kid_arb_int_hv; +wire [143 :0] kid_arb_int_req; +wire [4607:0] kid_busif_rdata_vec; +wire [143 :0] kid_int_vld; +wire [127 :0] pad_clic_int_vld; +wire pad_yy_dft_clk_rst_b; +wire pad_yy_icg_scan_en; +wire pad_yy_scan_mode; +wire [15 :0] tcipif_clic_addr; +wire tcipif_clic_sel; +wire [1 :0] tcipif_clic_size; +wire [31 :0] tcipif_clic_wdata; +wire tcipif_clic_write; + + +parameter CLICINTNUM = `CLIC_INTNUM; +parameter CLICINTCTLBITS = `CLIC_INTCTLBITS; + +// &Instance("pa_clic_arb"); @35 +pa_clic_arb x_pa_clic_arb ( + .arb_ctrl_int_hv (arb_ctrl_int_hv ), + .arb_ctrl_int_id (arb_ctrl_int_id ), + .arb_ctrl_int_il (arb_ctrl_int_il ), + .arb_ctrl_int_mode (arb_ctrl_int_mode ), + .arb_ctrl_int_req_raw (arb_ctrl_int_req_raw ), + .ctrl_xx_int_lv_or_mask (ctrl_xx_int_lv_or_mask), + .kid_arb_int_all_vec (kid_arb_int_all_vec ), + .kid_arb_int_hv (kid_arb_int_hv ), + .kid_arb_int_req (kid_arb_int_req ) +); + +// &Instance("pa_clic_busif"); @36 +pa_clic_busif x_pa_clic_busif ( + .busif_ctrl_cliccfg_sel (busif_ctrl_cliccfg_sel ), + .busif_ctrl_clicinfo_sel (busif_ctrl_clicinfo_sel ), + .busif_ctrl_mintthresh_sel (busif_ctrl_mintthresh_sel), + .busif_kid_clicintattr_sel (busif_kid_clicintattr_sel), + .busif_kid_clicintctl_sel (busif_kid_clicintctl_sel ), + .busif_kid_clicintie_sel (busif_kid_clicintie_sel ), + .busif_kid_clicintip_sel (busif_kid_clicintip_sel ), + .busif_kid_wdata (busif_kid_wdata ), + .busif_xx_write_vld (busif_xx_write_vld ), + .clic_clk (clic_clk ), + .clic_clk_en (clic_clk_en ), + .clic_tcipif_cmplt (clic_tcipif_cmplt ), + .clic_tcipif_rdata (clic_tcipif_rdata ), + .cpurst_b (cpurst_b ), + .ctrl_busif_cliccfg_val (ctrl_busif_cliccfg_val ), + .ctrl_busif_clicinfo_val (ctrl_busif_clicinfo_val ), + .ctrl_busif_mintthresh_val (ctrl_busif_mintthresh_val), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .kid_busif_rdata_vec (kid_busif_rdata_vec ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .tcipif_clic_addr (tcipif_clic_addr ), + .tcipif_clic_sel (tcipif_clic_sel ), + .tcipif_clic_size (tcipif_clic_size ), + .tcipif_clic_wdata (tcipif_clic_wdata ), + .tcipif_clic_write (tcipif_clic_write ) +); + +// &Instance("pa_clic_ctrl"); @37 +pa_clic_ctrl x_pa_clic_ctrl ( + .arb_ctrl_int_hv (arb_ctrl_int_hv ), + .arb_ctrl_int_id (arb_ctrl_int_id ), + .arb_ctrl_int_il (arb_ctrl_int_il ), + .arb_ctrl_int_mode (arb_ctrl_int_mode ), + .arb_ctrl_int_req_raw (arb_ctrl_int_req_raw ), + .busif_ctrl_cliccfg_sel (busif_ctrl_cliccfg_sel ), + .busif_ctrl_clicinfo_sel (busif_ctrl_clicinfo_sel ), + .busif_ctrl_mintthresh_sel (busif_ctrl_mintthresh_sel), + .busif_kid_wdata (busif_kid_wdata ), + .busif_xx_write_vld (busif_xx_write_vld ), + .clic_clk (clic_clk ), + .clic_clk_en (clic_clk_en ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .clicreg_clk (clicreg_clk ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpu_clic_mode (cpu_clic_mode ), + .cpurst_b (cpurst_b ), + .ctrl_busif_cliccfg_val (ctrl_busif_cliccfg_val ), + .ctrl_busif_clicinfo_val (ctrl_busif_clicinfo_val ), + .ctrl_busif_mintthresh_val (ctrl_busif_mintthresh_val), + .ctrl_clicreg_en (ctrl_clicreg_en ), + .ctrl_kid_ack_int (ctrl_kid_ack_int ), + .ctrl_xx_int_lv_or_mask (ctrl_xx_int_lv_or_mask ), + .ctrl_xx_mode_or_mask (ctrl_xx_mode_or_mask ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +assign kid_int_vld[CLICINTNUM-1:16] = pad_clic_int_vld[CLICINTNUM-17:0]; +// &Force("input", "pad_clic_int_vld"); &Force("bus", "pad_clic_int_vld", CLICINTNUM-17, 0); @41 +assign kid_int_vld[15:0] = {3'b0, 1'b0, // clic software int + clint_cpu_me_int, 3'b0, + clint_cpu_mt_int, 3'b0, + clint_cpu_ms_int, 3'b0}; +// &Force("nonport", "kid_int_vld"); @47 + +// &Force("nonport", "kid_busif_rdata_bus"); @49 +// &Force("nonport", "busif_kid_clicintattr_sel"); @50 +// &Force("nonport", "busif_kid_clicintctl_sel"); @51 +// &Force("nonport", "busif_kid_clicintie_sel"); @52 +// &Force("nonport", "busif_kid_clicintip_sel"); @53 +// &Force("nonport", "ctrl_kid_ack_int"); @54 +// &Force("nonport", "ctrl_kid_int_exit_gate"); @55 +// &Force("nonport", "ctrl_xx_mode_or_mask"); @56 +// &Force("nonport", "kid_arb_int_all_vec"); @57 +// &Force("nonport", "kid_arb_int_hv"); @58 +// &Force("nonport", "kid_arb_int_req"); @59 +// &Force("nonport", "kid_busif_rdata_vec"); @60 +//csky vperl_off +genvar i; +generate +for (i = 0; i < CLICINTNUM; i = i+1) +begin: INT_KID + case(i) + 0, 1, 2, + 4, 5, 6, + 8, 9, 10, + 13, 14, 15: + begin: KID_DUMMY + pa_clic_kid_dummy x_pa_clic_kid( + .kid_arb_int_all (kid_arb_int_all_vec[(CLICINTCTLBITS+1)*i+:(CLICINTCTLBITS+1)]), + .kid_arb_int_hv (kid_arb_int_hv[i]), + .kid_arb_int_req (kid_arb_int_req[i]), + .kid_busif_rdata (kid_busif_rdata_vec[32*i+:32]) + ); + end + default: + begin: KID_TRUE + pa_clic_kid x_pa_clic_kid( + .busif_kid_clicintattr_sel (busif_kid_clicintattr_sel[i]), + .busif_kid_clicintctl_sel (busif_kid_clicintctl_sel[i]), + .busif_kid_clicintie_sel (busif_kid_clicintie_sel[i]), + .busif_kid_clicintip_sel (busif_kid_clicintip_sel[i]), + .busif_kid_wdata (busif_kid_wdata), + .busif_xx_write_vld (busif_xx_write_vld), + .clic_clk (clic_clk), + .cpu_clic_mode (cpu_clic_mode), + .cpurst_b (cpurst_b), + .ctrl_kid_ack_int (ctrl_kid_ack_int[i]), + .ctrl_xx_mode_or_mask (ctrl_xx_mode_or_mask), + .forever_cpuclk (forever_cpuclk), + .kid_arb_int_all (kid_arb_int_all_vec[(CLICINTCTLBITS+1)*i+:(CLICINTCTLBITS+1)]), + .kid_arb_int_hv (kid_arb_int_hv[i]), + .kid_arb_int_req (kid_arb_int_req[i]), + .kid_busif_rdata (kid_busif_rdata_vec[32*i+:32]), + .kid_int_vld (kid_int_vld[i]), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) + ); + end + endcase +end +endgenerate +//csky vperl_on + +assign clic_rst_b = pad_yy_scan_mode ? pad_yy_dft_clk_rst_b : cpurst_b; + +always @ (posedge forever_cpuclk or negedge clic_rst_b) +begin + if (!clic_rst_b) begin + clic_clk_en_raw <= 1'b0; + end + else begin + clic_clk_en_raw <= !clic_clk_en_raw; + end +end + +always @ (posedge forever_cpuclk or negedge cpurst_b) +begin + if (!cpurst_b) begin + clic_test_point <= 1'b0; + end + else begin + clic_test_point <= 1'b1; + end +end + + +assign clic_clk_en = pad_yy_scan_mode ? clic_test_point : clic_clk_en_raw; + +// &Force("nonport", "clic_clk"); @134 +BUFGCE clic_clk_buf +(.O (clic_clk), + .I (forever_cpuclk), + .CE (clic_clk_en_raw) +); +// &Instance("gated_clk_cell", "x_clic_clk"); @141 +// &Connect(.clk_in (forever_cpuclk), @142 +// .external_en (1'b0), @143 +// .global_en (1'b1), @144 +// .module_en (1'b0), @145 +// .local_en (clic_clk_en_raw), @146 +// .clk_out (clic_clk), @147 +// .pad_yy_icg_scan_en (1'b0)); @148 + +//========================================================== +// Gate Clk Cell +//========================================================== + +// &Instance("gated_clk_cell", "x_clicreg_clk"); @160 +gated_clk_cell x_clicreg_clk ( + .clk_in (clic_clk ), + .clk_out (clicreg_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ctrl_clicreg_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (clic_clk), @161 +// .external_en (1'b0), @162 +// .global_en (1'b1), @163 +// .module_en (1'b0), @164 +// .local_en (ctrl_clicreg_en), @165 +// .clk_out (clicreg_clk)); @166 + +// &ModuleEnd; @168 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_busif.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_busif.v new file mode 100644 index 0000000000000000000000000000000000000000..d4b05ae80be2b24a0231f9ccc142655cf7e9ac2d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_busif.v @@ -0,0 +1,114 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clint_busif( + busif_regs_msip_sel, + busif_regs_mtimecmp_hi_sel, + busif_regs_mtimecmp_lo_sel, + busif_regs_wdata, + busif_regs_write_vld, + clint_tcipif_cmplt, + clint_tcipif_rdata, + msip_value, + mtime_hi_value, + mtime_lo_value, + mtimecmp_hi_value, + mtimecmp_lo_value, + tcipif_clint_addr, + tcipif_clint_sel, + tcipif_clint_wdata, + tcipif_clint_write +); + +// &Ports; @23 +input [31:0] msip_value; +input [31:0] mtime_hi_value; +input [31:0] mtime_lo_value; +input [31:0] mtimecmp_hi_value; +input [31:0] mtimecmp_lo_value; +input [15:0] tcipif_clint_addr; +input tcipif_clint_sel; +input [31:0] tcipif_clint_wdata; +input tcipif_clint_write; +output busif_regs_msip_sel; +output busif_regs_mtimecmp_hi_sel; +output busif_regs_mtimecmp_lo_sel; +output [31:0] busif_regs_wdata; +output busif_regs_write_vld; +output clint_tcipif_cmplt; +output [31:0] clint_tcipif_rdata; + +// &Regs; @24 + +// &Wires; @25 +wire busif_read_vld; +wire busif_regs_msip_sel; +wire busif_regs_mtimecmp_hi_sel; +wire busif_regs_mtimecmp_lo_sel; +wire [31:0] busif_regs_wdata; +wire busif_regs_write_vld; +wire clint_tcipif_cmplt; +wire [31:0] clint_tcipif_rdata; +wire msip_sel; +wire [31:0] msip_value; +wire mtime_hi_sel; +wire [31:0] mtime_hi_value; +wire mtime_lo_sel; +wire [31:0] mtime_lo_value; +wire mtimecmp_hi_sel; +wire [31:0] mtimecmp_hi_value; +wire mtimecmp_lo_sel; +wire [31:0] mtimecmp_lo_value; +wire [15:0] tcipif_clint_addr; +wire tcipif_clint_sel; +wire [31:0] tcipif_clint_wdata; +wire tcipif_clint_write; + + +parameter MSIP = 16'h0000; + +parameter MTIMECMPLO = 16'h4000; +parameter MTIMECMPHI = 16'h4004; + +parameter MTIMELO = 16'hbff8; +parameter MTIMEHI = 16'hbffc; + +assign msip_sel = tcipif_clint_addr[15:0] == MSIP; +assign mtimecmp_lo_sel = tcipif_clint_addr[15:0] == MTIMECMPLO; +assign mtimecmp_hi_sel = tcipif_clint_addr[15:0] == MTIMECMPHI; +assign mtime_lo_sel = tcipif_clint_addr[15:0] == MTIMELO; +assign mtime_hi_sel = tcipif_clint_addr[15:0] == MTIMEHI; + +assign busif_regs_msip_sel = msip_sel; +assign busif_regs_mtimecmp_lo_sel = mtimecmp_lo_sel; +assign busif_regs_mtimecmp_hi_sel = mtimecmp_hi_sel; + +assign clint_tcipif_cmplt = tcipif_clint_sel; + +assign busif_regs_write_vld = tcipif_clint_sel && tcipif_clint_write; +assign busif_read_vld = tcipif_clint_sel && !tcipif_clint_write; + +assign clint_tcipif_rdata[31:0] = ({32{msip_sel}} & msip_value[31:0] + | {32{mtimecmp_lo_sel}} & mtimecmp_lo_value[31:0] + | {32{mtimecmp_hi_sel}} & mtimecmp_hi_value[31:0] + | {32{mtime_lo_sel}} & mtime_lo_value[31:0] + | {32{mtime_hi_sel}} & mtime_hi_value[31:0]) + & {32{busif_read_vld}}; + +assign busif_regs_wdata[31:0] = tcipif_clint_wdata[31:0]; + +// &ModuleEnd; @59 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_regs.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_regs.v new file mode 100644 index 0000000000000000000000000000000000000000..8845cb5f1a0c50a370017119d41249df72dad70e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_regs.v @@ -0,0 +1,153 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clint_regs( + busif_regs_msip_sel, + busif_regs_mtimecmp_hi_sel, + busif_regs_mtimecmp_lo_sel, + busif_regs_wdata, + busif_regs_write_vld, + clint_clk, + clint_cpu_me_int, + clint_cpu_ms_int, + clint_cpu_mt_int, + cpu_clint_mode, + cpurst_b, + msip_value, + mtime_hi_value, + mtime_lo_value, + mtimecmp_hi_value, + mtimecmp_lo_value, + sysio_clint_me_int, + sysio_clint_mtime +); + +// &Ports; @23 +input busif_regs_msip_sel; +input busif_regs_mtimecmp_hi_sel; +input busif_regs_mtimecmp_lo_sel; +input [31:0] busif_regs_wdata; +input busif_regs_write_vld; +input clint_clk; +input [1 :0] cpu_clint_mode; +input cpurst_b; +input sysio_clint_me_int; +input [63:0] sysio_clint_mtime; +output clint_cpu_me_int; +output clint_cpu_ms_int; +output clint_cpu_mt_int; +output [31:0] msip_value; +output [31:0] mtime_hi_value; +output [31:0] mtime_lo_value; +output [31:0] mtimecmp_hi_value; +output [31:0] mtimecmp_lo_value; + +// &Regs; @24 +reg msip_en; +reg [31:0] mtimecmp_hi; +reg [31:0] mtimecmp_lo; + +// &Wires; @25 +wire busif_regs_msip_sel; +wire busif_regs_mtimecmp_hi_sel; +wire busif_regs_mtimecmp_lo_sel; +wire [31:0] busif_regs_wdata; +wire busif_regs_write_vld; +wire clint_clk; +wire clint_cpu_me_int; +wire clint_cpu_ms_int; +wire clint_cpu_mt_int; +wire [1 :0] cpu_clint_mode; +wire cpu_is_m_mode; +wire cpurst_b; +wire mregs_write_vld; +wire [31:0] msip_value; +wire [31:0] mtime_hi_value; +wire [31:0] mtime_lo_value; +wire [31:0] mtimecmp_hi_value; +wire [31:0] mtimecmp_lo_value; +wire sysio_clint_me_int; +wire [63:0] sysio_clint_mtime; + + +parameter CPU_M_MODE = 2'b11; + +//========================================================== +// Write Ctrl +//========================================================== +assign cpu_is_m_mode = cpu_clint_mode[1:0] == CPU_M_MODE; + +assign mregs_write_vld = busif_regs_write_vld && cpu_is_m_mode; + +//========================================================== +// Regs +//========================================================== +//----------------- MSIP --------------- +always @ (posedge clint_clk or negedge cpurst_b) +begin + if (!cpurst_b) + msip_en <= 1'b0; + else if (mregs_write_vld && busif_regs_msip_sel) + msip_en <= busif_regs_wdata[0]; + else + msip_en <= msip_en; +end +assign msip_value[31:0] = {31'b0, msip_en}; + + +//------------- MTIMECMP_LO ------------ +always @ (posedge clint_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mtimecmp_lo[31:0] <= 32'hffffffff; + else if (mregs_write_vld && busif_regs_mtimecmp_lo_sel) + mtimecmp_lo[31:0] <= busif_regs_wdata[31:0]; + else + mtimecmp_lo[31:0] <= mtimecmp_lo[31:0]; +end +assign mtimecmp_lo_value[31:0] = mtimecmp_lo[31:0]; + + +//------------- MTIMECMP_HI ------------ +always @ (posedge clint_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mtimecmp_hi[31:0] <= 32'hffffffff; + else if (mregs_write_vld && busif_regs_mtimecmp_hi_sel) + mtimecmp_hi[31:0] <= busif_regs_wdata[31:0]; + else + mtimecmp_hi[31:0] <= mtimecmp_hi[31:0]; +end +assign mtimecmp_hi_value[31:0] = mtimecmp_hi[31:0]; + + +//--------------- MTIME_LOW ------------ +assign mtime_lo_value[31:0] = sysio_clint_mtime[31:0]; + +//--------------- MTIME_HI ------------- +assign mtime_hi_value[31:0] = sysio_clint_mtime[63:32]; + + +//========================================================== +// CLINT Output Signal +//========================================================== +assign clint_cpu_ms_int = msip_en; +assign clint_cpu_mt_int = !({mtimecmp_hi[31:0], mtimecmp_lo[31:0]} + > sysio_clint_mtime[63:0]); +assign clint_cpu_me_int = sysio_clint_me_int; + +// &ModuleEnd; @93 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_top.v new file mode 100644 index 0000000000000000000000000000000000000000..6d9a33b2c8f177a81eece2926d335298600decf9 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clint/rtl/pa_clint_top.v @@ -0,0 +1,149 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_clint_top( + clint_cpu_me_int, + clint_cpu_ms_int, + clint_cpu_mt_int, + clint_tcipif_cmplt, + clint_tcipif_rdata, + cpu_clint_mode, + cpurst_b, + forever_cpuclk, + pad_yy_icg_scan_en, + sysio_clint_me_int, + sysio_clint_mtime, + tcipif_clint_addr, + tcipif_clint_sel, + tcipif_clint_wdata, + tcipif_clint_write +); + +// &Ports; @23 +input [1 :0] cpu_clint_mode; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input sysio_clint_me_int; +input [63:0] sysio_clint_mtime; +input [15:0] tcipif_clint_addr; +input tcipif_clint_sel; +input [31:0] tcipif_clint_wdata; +input tcipif_clint_write; +output clint_cpu_me_int; +output clint_cpu_ms_int; +output clint_cpu_mt_int; +output clint_tcipif_cmplt; +output [31:0] clint_tcipif_rdata; + +// &Regs; @24 + +// &Wires; @25 +wire busif_regs_msip_sel; +wire busif_regs_mtimecmp_hi_sel; +wire busif_regs_mtimecmp_lo_sel; +wire [31:0] busif_regs_wdata; +wire busif_regs_write_vld; +wire clint_clk; +wire clint_clk_en; +wire clint_cpu_me_int; +wire clint_cpu_ms_int; +wire clint_cpu_mt_int; +wire clint_tcipif_cmplt; +wire [31:0] clint_tcipif_rdata; +wire [1 :0] cpu_clint_mode; +wire cpurst_b; +wire forever_cpuclk; +wire [31:0] msip_value; +wire [31:0] mtime_hi_value; +wire [31:0] mtime_lo_value; +wire [31:0] mtimecmp_hi_value; +wire [31:0] mtimecmp_lo_value; +wire pad_yy_icg_scan_en; +wire sysio_clint_me_int; +wire [63:0] sysio_clint_mtime; +wire [15:0] tcipif_clint_addr; +wire tcipif_clint_sel; +wire [31:0] tcipif_clint_wdata; +wire tcipif_clint_write; + + +// &Instance("pa_clint_regs"); @27 +pa_clint_regs x_pa_clint_regs ( + .busif_regs_msip_sel (busif_regs_msip_sel ), + .busif_regs_mtimecmp_hi_sel (busif_regs_mtimecmp_hi_sel), + .busif_regs_mtimecmp_lo_sel (busif_regs_mtimecmp_lo_sel), + .busif_regs_wdata (busif_regs_wdata ), + .busif_regs_write_vld (busif_regs_write_vld ), + .clint_clk (clint_clk ), + .clint_cpu_me_int (clint_cpu_me_int ), + .clint_cpu_ms_int (clint_cpu_ms_int ), + .clint_cpu_mt_int (clint_cpu_mt_int ), + .cpu_clint_mode (cpu_clint_mode ), + .cpurst_b (cpurst_b ), + .msip_value (msip_value ), + .mtime_hi_value (mtime_hi_value ), + .mtime_lo_value (mtime_lo_value ), + .mtimecmp_hi_value (mtimecmp_hi_value ), + .mtimecmp_lo_value (mtimecmp_lo_value ), + .sysio_clint_me_int (sysio_clint_me_int ), + .sysio_clint_mtime (sysio_clint_mtime ) +); + +// &Instance("pa_clint_busif"); @28 +pa_clint_busif x_pa_clint_busif ( + .busif_regs_msip_sel (busif_regs_msip_sel ), + .busif_regs_mtimecmp_hi_sel (busif_regs_mtimecmp_hi_sel), + .busif_regs_mtimecmp_lo_sel (busif_regs_mtimecmp_lo_sel), + .busif_regs_wdata (busif_regs_wdata ), + .busif_regs_write_vld (busif_regs_write_vld ), + .clint_tcipif_cmplt (clint_tcipif_cmplt ), + .clint_tcipif_rdata (clint_tcipif_rdata ), + .msip_value (msip_value ), + .mtime_hi_value (mtime_hi_value ), + .mtime_lo_value (mtime_lo_value ), + .mtimecmp_hi_value (mtimecmp_hi_value ), + .mtimecmp_lo_value (mtimecmp_lo_value ), + .tcipif_clint_addr (tcipif_clint_addr ), + .tcipif_clint_sel (tcipif_clint_sel ), + .tcipif_clint_wdata (tcipif_clint_wdata ), + .tcipif_clint_write (tcipif_clint_write ) +); + + +assign clint_clk_en = tcipif_clint_sel; +// &Instance("gated_clk_cell", "x_clint_gateclk"); @31 +gated_clk_cell x_clint_gateclk ( + .clk_in (forever_cpuclk ), + .clk_out (clint_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (clint_clk_en ), + .module_en (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @32 +// .external_en(1'b0 ), @33 +// .global_en (1'b1 ), @34 +// .module_en (1'b0 ), @35 +// .local_en (clint_clk_en ), @36 +// .clk_out (clint_clk ) @37 +// ); @38 + + +// &ModuleEnd; @41 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/gated_clk_cell.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/gated_clk_cell.v new file mode 100644 index 0000000000000000000000000000000000000000..c0e20e79e1014aaeb63c73db85ad14608a4c2913 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/gated_clk_cell.v @@ -0,0 +1,50 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module gated_clk_cell( + clk_in, + global_en, + module_en, + local_en, + external_en, + pad_yy_icg_scan_en, + clk_out +); + +input clk_in; +input global_en; +input module_en; +input local_en; +input external_en; +input pad_yy_icg_scan_en; +output clk_out; + +wire clk_en_bf_latch; +wire SE; + +assign clk_en_bf_latch = (global_en && (module_en || local_en)) || external_en ; + +// SE driven from primary input, held constant +assign SE = pad_yy_icg_scan_en; + +// // &Connect( .clk_in (clk_in), @50 +// // .SE (SE), @51 +// // .external_en (clk_en_bf_latch), @52 +// // .clk_out (clk_out) @53 +// // ) ; @54 + +assign clk_out = clk_in; + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clk_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clk_top.v new file mode 100644 index 0000000000000000000000000000000000000000..4d279652784920d62e9f4fdc30b326cc370584d6 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clk_top.v @@ -0,0 +1,52 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_clk_top( + clk_en, + clk_en_f, + forever_cpuclk, + pll_core_cpuclk +); + +// &Ports; @24 +input clk_en; +input pll_core_cpuclk; +output clk_en_f; +output forever_cpuclk; + +// &Regs; @25 +reg clk_en_f; + +// &Wires; @26 +wire clk_en; +wire forever_cpuclk; +wire pll_core_cpuclk; + + +//assign forever_jtgclk = pad_had_jtg_tclk; +assign forever_cpuclk = pll_core_cpuclk; +// &Force("output","forever_cpuclk"); @30 +// &Force("output", "axim_clk_en_f"); @32 +always@(posedge forever_cpuclk) +begin + clk_en_f <= clk_en; +end + + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clkrst_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clkrst_top.v new file mode 100644 index 0000000000000000000000000000000000000000..84988932a52fe72b86446b61f62889bb9a265abc --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/clk/rtl/pa_clkrst_top.v @@ -0,0 +1,92 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_clkrst_top( + clk_en, + clk_en_f, + cpurst_b, + forever_cpuclk, + pad_cpu_rst_b, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + pll_core_cpuclk, + sync_sys_apb_rst_b, + sys_apb_clk, + sys_apb_rst_b +); + +// &Ports; @23 +input clk_en; +input pad_cpu_rst_b; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input pll_core_cpuclk; +input sys_apb_clk; +input sys_apb_rst_b; +output clk_en_f; +output cpurst_b; +output forever_cpuclk; +output sync_sys_apb_rst_b; + +// &Regs; @24 + +// &Wires; @25 +wire clk_en; +wire clk_en_f; +wire cpurst_b; +wire forever_cpuclk; +wire pad_cpu_rst_b; +wire pad_yy_scan_mode; +wire pad_yy_scan_rst_b; +wire pll_core_cpuclk; +wire sync_sys_apb_rst_b; +wire sys_apb_clk; +wire sys_apb_rst_b; + + +// &Force("output", "forever_cpuclk"); @27 + +//---------------------------------------------------------- +// clock top +//---------------------------------------------------------- +// &Instance("pa_clk_top"); @32 +pa_clk_top x_pa_clk_top ( + .clk_en (clk_en ), + .clk_en_f (clk_en_f ), + .forever_cpuclk (forever_cpuclk ), + .pll_core_cpuclk (pll_core_cpuclk) +); + + +//---------------------------------------------------------- +// reset top +//---------------------------------------------------------- +// &Instance("pa_rst_top"); @37 +pa_rst_top x_pa_rst_top ( + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .pad_yy_scan_rst_b (pad_yy_scan_rst_b ), + .sync_sys_apb_rst_b (sync_sys_apb_rst_b), + .sys_apb_clk (sys_apb_clk ), + .sys_apb_rst_b (sys_apb_rst_b ) +); + +// &ModuleEnd; @38 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/common/rtl/BUFGCE.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/common/rtl/BUFGCE.v new file mode 100644 index 0000000000000000000000000000000000000000..393a7c5b1e7c69b26d90108af32082ce381371d8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/common/rtl/BUFGCE.v @@ -0,0 +1,40 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module BUFGCE( + I, + CE, + O +); + +input I; +input CE ; +output O; + +reg clk_en_af_latch; +always @(I or CE) +begin + if(!I) + clk_en_af_latch <= CE; +end + +reg clk_en ; +always @ (clk_en_af_latch ) +begin + clk_en <= clk_en_af_latch; +end +assign O = I && clk_en ; + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_csr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_csr.v new file mode 100644 index 0000000000000000000000000000000000000000..478482d67ed57939cfffdd437a0bb5c55583a82f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_csr.v @@ -0,0 +1,874 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_ext_csr( + cp0_biu_icg_en, + cp0_dtu_icg_en, + cp0_dtu_pcfifo_frz, + cp0_fpu_icg_en, + cp0_hpcp_icg_en, + cp0_idu_icg_en, + cp0_idu_spec_push_en, + cp0_idu_swap_sp_en, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_btb_clr, + cp0_ifu_btb_en, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_ifu_ras_en, + cp0_ifu_rst_inv_done, + cp0_iu_icg_en, + cp0_lsu_dcache_en, + cp0_lsu_dcache_wa, + cp0_lsu_dcache_wb, + cp0_lsu_icc_addr, + cp0_lsu_icc_op, + cp0_lsu_icc_req, + cp0_lsu_icc_type, + cp0_lsu_icg_en, + cp0_pmp_icg_en, + cp0_rtu_icg_en, + cp0_rtu_in_expt, + cp0_rtu_wfe_en, + cp0_xx_async_expt_en, + cpurst_b, + ext_inst_ifu_icc_addr, + ext_inst_ifu_icc_req, + ext_inst_ifu_icc_type, + ext_inst_ifu_inv_done, + ext_inst_lsu_icc_addr, + ext_inst_lsu_icc_done, + ext_inst_lsu_icc_op, + ext_inst_lsu_icc_req, + ext_inst_lsu_icc_type, + forever_cpuclk, + ifu_cp0_bht_inv_done, + ifu_cp0_icache_inv_done, + ifu_cp0_rst_inv_req, + inv_sm_clk, + iui_regs_inst_mret, + iui_regs_wdata, + iui_regs_wdata_srst, + lsu_cp0_icc_done, + mexstatus_local_en, + mexstatus_value, + mhcr_local_en, + mhcr_value, + mhint2_local_en, + mhint2_value, + mhint_local_en, + mhint_value, + mraddr_value, + pad_yy_icg_scan_en, + regs_clk, + regs_cpu_in_int, + regs_cpu_in_nmi, + regs_flush_clk, + regs_special_lpmd, + regs_spswap_en, + regs_srst_srst_vld, + regs_srst_srstmd, + rst_top_op_done, + rtu_cp0_bus_error, + rtu_cp0_lockup_clr, + rtu_cp0_lockup_vld, + rtu_cp0_nmi_vld, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vld, + special_dcache_clean, + special_icache_inv, + special_icache_inv_done, + special_regs_clk_en, + special_regs_inv_sm_clk_en, + sysio_cp0_clkratio, + sysio_cp0_rst_addr +); + +// &Ports; @24 +input cpurst_b; +input [31:0] ext_inst_ifu_icc_addr; +input ext_inst_ifu_icc_req; +input ext_inst_ifu_icc_type; +input [31:0] ext_inst_lsu_icc_addr; +input [1 :0] ext_inst_lsu_icc_op; +input ext_inst_lsu_icc_req; +input [1 :0] ext_inst_lsu_icc_type; +input forever_cpuclk; +input ifu_cp0_bht_inv_done; +input ifu_cp0_icache_inv_done; +input ifu_cp0_rst_inv_req; +input iui_regs_inst_mret; +input [31:0] iui_regs_wdata; +input [1 :0] iui_regs_wdata_srst; +input lsu_cp0_icc_done; +input mexstatus_local_en; +input mhcr_local_en; +input mhint2_local_en; +input mhint_local_en; +input pad_yy_icg_scan_en; +input regs_clk; +input regs_cpu_in_int; +input regs_flush_clk; +input rtu_cp0_bus_error; +input rtu_cp0_lockup_clr; +input rtu_cp0_lockup_vld; +input rtu_cp0_nmi_vld; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input rtu_yy_xx_expt_vld; +input special_dcache_clean; +input special_icache_inv; +input special_regs_clk_en; +input special_regs_inv_sm_clk_en; +input [2 :0] sysio_cp0_clkratio; +input [31:0] sysio_cp0_rst_addr; +output cp0_biu_icg_en; +output cp0_dtu_icg_en; +output cp0_dtu_pcfifo_frz; +output cp0_fpu_icg_en; +output cp0_hpcp_icg_en; +output cp0_idu_icg_en; +output cp0_idu_spec_push_en; +output cp0_idu_swap_sp_en; +output cp0_ifu_bht_en; +output cp0_ifu_bht_inv; +output cp0_ifu_btb_clr; +output cp0_ifu_btb_en; +output cp0_ifu_icache_en; +output [31:0] cp0_ifu_icache_inv_addr; +output cp0_ifu_icache_inv_req; +output cp0_ifu_icache_inv_type; +output cp0_ifu_icg_en; +output cp0_ifu_ras_en; +output cp0_ifu_rst_inv_done; +output cp0_iu_icg_en; +output cp0_lsu_dcache_en; +output cp0_lsu_dcache_wa; +output cp0_lsu_dcache_wb; +output [31:0] cp0_lsu_icc_addr; +output [1 :0] cp0_lsu_icc_op; +output cp0_lsu_icc_req; +output [1 :0] cp0_lsu_icc_type; +output cp0_lsu_icg_en; +output cp0_pmp_icg_en; +output cp0_rtu_icg_en; +output cp0_rtu_in_expt; +output cp0_rtu_wfe_en; +output cp0_xx_async_expt_en; +output ext_inst_ifu_inv_done; +output ext_inst_lsu_icc_done; +output inv_sm_clk; +output [31:0] mexstatus_value; +output [31:0] mhcr_value; +output [31:0] mhint2_value; +output [31:0] mhint_value; +output [31:0] mraddr_value; +output regs_cpu_in_nmi; +output [1 :0] regs_special_lpmd; +output regs_spswap_en; +output regs_srst_srst_vld; +output [1 :0] regs_srst_srstmd; +output rst_top_op_done; +output special_icache_inv_done; + +// &Regs; @25 +reg bpe; +reg de; +reg ie; +reg l0btb; +reg mexstatus_bus_err; +reg mexstatus_expt; +reg mexstatus_lockup; +reg [1 :0] mexstatus_lpmd; +reg mexstatus_nmi; +reg [1 :0] mexstatus_rstmd; +reg mexstatus_spswapen; +reg mexstatus_spushen; +reg mexstatus_wfeen; +reg mhint_aee; +reg [8 :0] module_icg_en; +reg pcfifo_freeze; +reg rs; +reg [1 :0] rst_bht_inv; +reg [1 :0] rst_bht_inv_nxt; +reg [1 :0] rst_cache_inv; +reg [1 :0] rst_cache_inv_nxt; +reg [1 :0] rst_dcache_inv; +reg [1 :0] rst_dcache_inv_nxt; +reg [1 :0] rst_icache_inv; +reg [1 :0] rst_icache_inv_nxt; +reg wa; +reg wb; + +// &Wires; @26 +wire [1 :0] amr; +wire bht_inv_req; +wire bht_rst_inv_req; +wire [2 :0] clk_ratio; +wire cp0_biu_icg_en; +wire cp0_dtu_icg_en; +wire cp0_dtu_pcfifo_frz; +wire cp0_fpu_icg_en; +wire cp0_hpcp_icg_en; +wire cp0_idu_icg_en; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_ifu_ras_en; +wire cp0_ifu_rst_inv_done; +wire cp0_iu_icg_en; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_dcache_wb; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire cp0_pmp_icg_en; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_expt; +wire cp0_rtu_wfe_en; +wire cp0_xx_async_expt_en; +wire cpurst_b; +wire [1 :0] dcache_pref_dist; +wire dcache_pref_en; +wire dcache_rst_inv_req; +wire ext_ifu_inv_done; +wire [31:0] ext_inst_ifu_icc_addr; +wire ext_inst_ifu_icc_req; +wire ext_inst_ifu_icc_type; +wire ext_inst_ifu_inv_done; +wire [31:0] ext_inst_lsu_icc_addr; +wire ext_inst_lsu_icc_done; +wire [1 :0] ext_inst_lsu_icc_op; +wire ext_inst_lsu_icc_req; +wire [1 :0] ext_inst_lsu_icc_type; +wire forever_cpuclk; +wire icache_inv_req; +wire icache_rst_inv_req; +wire ifu_cp0_bht_inv_done; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_rst_inv_req; +wire inst_dcache_op; +wire inst_icache_op; +wire inv_sm_clk; +wire inv_sm_clk_en; +wire iui_regs_inst_mret; +wire [31:0] iui_regs_wdata; +wire [1 :0] iui_regs_wdata_srst; +wire lsu_cp0_icc_done; +wire mexstatus_local_en; +wire [31:0] mexstatus_value; +wire mhcr_local_en; +wire [31:0] mhcr_value; +wire mhint2_local_en; +wire [31:0] mhint2_value; +wire mhint_local_en; +wire [31:0] mhint_value; +wire [31:0] mraddr_value; +wire pad_yy_icg_scan_en; +wire regs_clk; +wire regs_cpu_in_int; +wire regs_cpu_in_nmi; +wire regs_doing_inv; +wire regs_flush_clk; +wire [1 :0] regs_special_lpmd; +wire regs_spswap_en; +wire regs_srst_srst_vld; +wire [1 :0] regs_srst_srstmd; +wire rst_inv_done; +wire rst_top_op_done; +wire [1 :0] rstmd_in; +wire rtu_cp0_bus_error; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_cp0_nmi_vld; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire rtu_yy_xx_expt_vld; +wire special_dcache_clean; +wire special_icache_inv; +wire special_icache_inv_done; +wire special_regs_clk_en; +wire special_regs_inv_sm_clk_en; +wire srst_vld; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; + + +// &Force("bus", "iui_regs_wdata", 31, 0); @28 +//========================================================== +// Define the MHCR register +// Machine Hardwire Control Register +// 32-bit Machine Mode Read/Write +// the definiton for MHSR register is listed as follows +//========================================================== +assign clk_ratio[2:0] = sysio_cp0_clkratio[2:0]; + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + l0btb <= 1'b0; + bpe <= 1'b0; + rs <= 1'b0; + end + else if (mhcr_local_en) begin + l0btb <= iui_regs_wdata[12]; + bpe <= iui_regs_wdata[5]; + rs <= iui_regs_wdata[4]; + end + else begin + l0btb <= l0btb; + bpe <= bpe; + rs <= rs; + end +end + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + wa <= 1'b0; + wb <= 1'b0; + de <= 1'b0; + end + else if (mhcr_local_en) begin + wa <= iui_regs_wdata[3]; + wb <= iui_regs_wdata[2]; + de <= iui_regs_wdata[1]; + end + else begin + wa <= wa; + wb <= wb; + de <= de; + end +end + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ie <= 1'b0; + else if (mhcr_local_en) + ie <= iui_regs_wdata[0]; + else + ie <= ie; +end + +assign mhcr_value[31:0] = {13'b0, clk_ratio[2:0], 3'b0, l0btb, // [31:12] + 6'b0, bpe, rs, wa, wb, de, ie}; // [11:0] + + +//========================================================== +// Define the MHINT register +// Machine Register +// 32-bit Machine Mode Read/Write +// the definiton for MHSR register is listed as follows +//========================================================== + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + mhint_aee <= 1'b0; + end + else if (mhint_local_en) begin + mhint_aee <= iui_regs_wdata[20]; + end + else begin + mhint_aee <= mhint_aee; + end +end +assign dcache_pref_dist[1:0] = 2'b0; +assign amr[1:0] = 2'b0; +assign dcache_pref_en = 1'b0; + + + + +assign mhint_value[31:0] = {7'b0,pcfifo_freeze,3'b0, mhint_aee,5'b0,dcache_pref_dist[1:0],8'b0,amr[1:0], dcache_pref_en, 2'b0}; + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + pcfifo_freeze <= 1'b0; + else if(mhint_local_en) + pcfifo_freeze <= iui_regs_wdata[24]; + else + pcfifo_freeze <= pcfifo_freeze; +end + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) begin + module_icg_en[8:0] <= 9'b0; + end + else if(mhint2_local_en) begin + module_icg_en[8:0] <= iui_regs_wdata[22:14]; + end + else begin + module_icg_en[8:0] <= module_icg_en[8:0]; + end +end + +assign mhint2_value[31:0] = {9'b0, + module_icg_en[8:0], 14'b0}; +//for ifu control +assign cp0_ifu_icg_en = module_icg_en[0]; +assign cp0_idu_icg_en = module_icg_en[1]; +assign cp0_iu_icg_en = module_icg_en[2]; +assign cp0_hpcp_icg_en = module_icg_en[2]; +assign cp0_lsu_icg_en = module_icg_en[3]; +assign cp0_pmp_icg_en = module_icg_en[4]; +assign cp0_biu_icg_en = module_icg_en[5]; +assign cp0_rtu_icg_en = module_icg_en[6]; +assign cp0_fpu_icg_en = module_icg_en[7]; +assign cp0_dtu_icg_en = module_icg_en[8]; +//========================================================== +// Define the MRADDR register +// Machine Register +// 32-bit Machine Mode Read/Write +// the definiton for MRADDR register is listed as follows +//========================================================== +assign mraddr_value[31:0] = sysio_cp0_rst_addr[31:0]; + +//========================================================== +// Define the MEXSTATUS register +// Machine Register +// 32-bit Machine Mode Read/Write +// the definiton for MEXSTATUS register is listed as follows +//========================================================== +assign rstmd_in[1:0] = &iui_regs_wdata_srst[1:0] ? 2'b0 : iui_regs_wdata_srst[1:0]; +// Use individed signal to opt timing. + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + mexstatus_rstmd[1:0] <= 2'b0; + mexstatus_lpmd[1:0] <= 2'b0; + mexstatus_wfeen <= 1'b1; + end + else if (mexstatus_local_en) begin + mexstatus_rstmd[1:0] <= rstmd_in[1:0]; + mexstatus_lpmd[1:0] <= {1'b0, iui_regs_wdata[2]}; + mexstatus_wfeen <= iui_regs_wdata[4]; + end +end +assign srst_vld = mexstatus_local_en && |rstmd_in[1:0]; + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + mexstatus_spushen <= 1'b0; + mexstatus_spswapen <= 1'b0; + end + else if (mexstatus_local_en) begin + mexstatus_spushen <= iui_regs_wdata[16]; + mexstatus_spswapen <= iui_regs_wdata[17]; + end +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mexstatus_expt <= 1'b0; + else if (mexstatus_local_en && rtu_yy_xx_dbgon) + mexstatus_expt <= iui_regs_wdata[5]; + else if (rtu_cp0_lockup_clr) + mexstatus_expt <= 1'b0; + else if (rtu_yy_xx_expt_vld && !rtu_yy_xx_expt_int && !rtu_cp0_nmi_vld) + mexstatus_expt <= 1'b1; + else if (iui_regs_inst_mret && !mexstatus_nmi && !regs_cpu_in_int) + mexstatus_expt <= 1'b0; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mexstatus_nmi <= 1'b0; + else if (mexstatus_local_en && rtu_yy_xx_dbgon) + mexstatus_nmi <= iui_regs_wdata[7]; + else if (rtu_cp0_lockup_clr) + mexstatus_nmi <= 1'b0; + else if (rtu_cp0_nmi_vld) + mexstatus_nmi <= 1'b1; + else if (iui_regs_inst_mret) + mexstatus_nmi <= 1'b0; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mexstatus_bus_err <= 1'b0; + else if (rtu_yy_xx_expt_vld && !rtu_yy_xx_expt_int) + mexstatus_bus_err <= rtu_cp0_bus_error; + else if (mexstatus_local_en) + mexstatus_bus_err <= iui_regs_wdata[8]; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mexstatus_lockup <= 1'b0; + else if (rtu_cp0_lockup_clr) + mexstatus_lockup <= 1'b0; + else if (rtu_cp0_lockup_vld) + mexstatus_lockup <= 1'b1; +end + +assign mexstatus_value[31:0] = {14'b0, mexstatus_spswapen, mexstatus_spushen, + 7'b0, mexstatus_bus_err, mexstatus_nmi, mexstatus_lockup, mexstatus_expt, + mexstatus_wfeen, mexstatus_lpmd[1:0], mexstatus_rstmd[1:0]}; + +// MNMICAUSE, MNMIPC is in trap_csr. + +//========================================================== +// CP0 Extension CSR Module +//========================================================== +assign inv_sm_clk_en = regs_doing_inv + || special_regs_inv_sm_clk_en + || inst_dcache_op + || icache_inv_req; + +// &Instance("gated_clk_cell", "x_inv_sm_gated_clk"); @307 +gated_clk_cell x_inv_sm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (inv_sm_clk ), + .external_en (1'b0 ), + .global_en (special_regs_clk_en), + .local_en (1'b0 ), + .module_en (inv_sm_clk_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @308 +// .external_en (1'b0), @309 +// .global_en (special_regs_clk_en), @310 +// .module_en (inv_sm_clk_en), @311 +// .local_en (1'b0), @312 +// .clk_out (inv_sm_clk)); @313 +// &Force("output", "inv_sm_clk"); @314 + +parameter RST_IDLE = 2'b00; +parameter RST_WFC = 2'b01; +parameter RST_DONE = 2'b10; +//========================================================== +// FSM of reset cache inv cctl logic +//========================================================== +always @(posedge inv_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + rst_cache_inv[1:0] <= RST_IDLE; + else + rst_cache_inv[1:0] <= rst_cache_inv_nxt[1:0]; +end + +// &CombBeg; @330 +always @( rst_cache_inv + or rst_inv_done + or ifu_cp0_rst_inv_req) +begin +case(rst_cache_inv) + RST_IDLE: + begin + if(ifu_cp0_rst_inv_req) + rst_cache_inv_nxt[1:0] = RST_WFC; + else + rst_cache_inv_nxt[1:0] = RST_IDLE; + end + RST_WFC: + begin + if(rst_inv_done) + rst_cache_inv_nxt[1:0] = RST_IDLE; + else + rst_cache_inv_nxt[1:0] = RST_WFC; + end + default: + begin + rst_cache_inv_nxt[1:0] = RST_IDLE; + end +endcase +// &CombEnd; @351 +end + +assign rst_inv_done = rst_icache_inv[1:0] == RST_IDLE && + rst_dcache_inv[1:0] == RST_IDLE && + rst_bht_inv[1:0] == RST_IDLE; +assign cp0_ifu_rst_inv_done = rst_cache_inv[1:0] == RST_IDLE && !ifu_cp0_rst_inv_req; + +//========================================================== +// ICache Operation +//========================================================== +assign inst_icache_op = ext_inst_ifu_icc_req + || special_icache_inv; + +assign icache_inv_req = (ifu_cp0_rst_inv_req | inst_icache_op) & (rst_bht_inv[1:0] == RST_IDLE); + +always @(posedge inv_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + rst_icache_inv[1:0] <= RST_IDLE; + else + rst_icache_inv[1:0] <= rst_icache_inv_nxt[1:0]; +end + +// &CombBeg; @374 +always @( rst_icache_inv + or ext_ifu_inv_done + or ifu_cp0_icache_inv_done + or icache_inv_req) +begin +case(rst_icache_inv) + RST_IDLE: + begin + if(icache_inv_req) + rst_icache_inv_nxt[1:0] = RST_WFC; + else + rst_icache_inv_nxt[1:0] = RST_IDLE; + end + RST_WFC: + begin + if(ifu_cp0_icache_inv_done) + rst_icache_inv_nxt[1:0] = RST_DONE; + else + rst_icache_inv_nxt[1:0] = RST_WFC; + end + RST_DONE: + if (ext_ifu_inv_done) + rst_icache_inv_nxt[1:0] = RST_IDLE; + else + rst_icache_inv_nxt[1:0] = RST_DONE; + default: + begin + rst_icache_inv_nxt[1:0] = RST_IDLE; + end +endcase +// &CombEnd; @400 +end + +//assign icache_sm_idle = rst_icache_inv[1:0] == RST_IDLE; +//assign icache_sm_done = rst_icache_inv[1:0] == RST_DONE; +//assign icache_op_done = icache_sm_idle & ~icache_inv_req | +// icache_sm_done; + +assign bht_inv_req = (ifu_cp0_rst_inv_req | inst_icache_op) & (rst_icache_inv[1:0] == RST_IDLE); + +always @(posedge inv_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + rst_bht_inv[1:0] <= RST_IDLE; + else + rst_bht_inv[1:0] <= rst_bht_inv_nxt[1:0]; +end + +// &CombBeg; @417 +always @( bht_inv_req + or ext_ifu_inv_done + or ifu_cp0_bht_inv_done + or rst_bht_inv) +begin +case(rst_bht_inv) + RST_IDLE: + begin + if(bht_inv_req) + rst_bht_inv_nxt[1:0] = RST_WFC; + else + rst_bht_inv_nxt[1:0] = RST_IDLE; + end + RST_WFC: + begin + if(ifu_cp0_bht_inv_done) + rst_bht_inv_nxt[1:0] = RST_DONE; + else + rst_bht_inv_nxt[1:0] = RST_WFC; + end + RST_DONE: + if (ext_ifu_inv_done) + rst_bht_inv_nxt[1:0] = RST_IDLE; + else + rst_bht_inv_nxt[1:0] = RST_DONE; + default: + begin + rst_bht_inv_nxt[1:0] = RST_IDLE; + end +endcase +// &CombEnd; @443 +end +//assign bht_sm_idle = rst_bht_inv[1:0] == RST_IDLE; +//assign bht_sm_done = rst_bht_inv[1:0] == RST_DONE; +//assign bht_op_done = bht_sm_idle & ~bht_inv_req | +// bht_sm_done; +//========================================================== +// DCache Operation +//========================================================== +assign inst_dcache_op = ext_inst_lsu_icc_req + || special_dcache_clean; + +always @(posedge inv_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + rst_dcache_inv[1:0] <= RST_IDLE; + else + rst_dcache_inv[1:0] <= rst_dcache_inv_nxt[1:0]; +end + +// &CombBeg; @462 +always @( inst_dcache_op + or rst_dcache_inv + or ifu_cp0_rst_inv_req + or lsu_cp0_icc_done) +begin +case(rst_dcache_inv) + RST_IDLE: + begin + if(ifu_cp0_rst_inv_req) + rst_dcache_inv_nxt[1:0] = RST_WFC; + else if (inst_dcache_op) + rst_dcache_inv_nxt[1:0] = RST_WFC; + else + rst_dcache_inv_nxt[1:0] = RST_IDLE; + end + RST_WFC: + begin + if(lsu_cp0_icc_done) + rst_dcache_inv_nxt[1:0] = RST_DONE; + else + rst_dcache_inv_nxt[1:0] = RST_WFC; + end + RST_DONE: + rst_dcache_inv_nxt[1:0] = RST_IDLE; + default: + begin + rst_dcache_inv_nxt[1:0] = RST_IDLE; + end +endcase +// &CombEnd; @487 +end + +//assign dcache_sm_idle = rst_dcache_inv[1:0] == RST_IDLE; +//assign dcache_sm_done = rst_dcache_inv[1:0] == RST_DONE; +//assign dcache_op_done = dcache_sm_idle & ~dcache_inv_req | +// dcache_sm_done; + +assign regs_doing_inv = ifu_cp0_rst_inv_req + || !rst_inv_done + || rst_dcache_inv[1:0] != RST_IDLE + || rst_icache_inv[1:0] != RST_IDLE + || rst_bht_inv[1:0] != RST_IDLE + || rst_cache_inv[1:0] != RST_IDLE; + +assign ext_ifu_inv_done = rst_bht_inv[1:0] == RST_DONE + && rst_icache_inv[1:0] == RST_DONE; + +assign ext_inst_ifu_inv_done = ext_ifu_inv_done; +assign special_icache_inv_done = ext_ifu_inv_done; +assign ext_inst_lsu_icc_done = rst_dcache_inv[1:0] == RST_WFC && lsu_cp0_icc_done + || rst_dcache_inv[1:0] == RST_IDLE && !inst_dcache_op; + +assign icache_rst_inv_req = rst_icache_inv[1:0] == RST_WFC; +assign bht_rst_inv_req = rst_bht_inv[1:0] == RST_WFC; +assign dcache_rst_inv_req = rst_dcache_inv[1:0] == RST_WFC; + +assign cp0_lsu_icc_req = dcache_rst_inv_req; +assign cp0_lsu_icc_type[1:0] = ext_inst_lsu_icc_req ? ext_inst_lsu_icc_type[1:0] + : 2'b0; +assign cp0_lsu_icc_addr[31:0] = ext_inst_lsu_icc_req ? ext_inst_lsu_icc_addr[31:0] + : 32'b0; +assign cp0_lsu_icc_op[1:0] = ext_inst_lsu_icc_req ? ext_inst_lsu_icc_op[1:0] + : special_dcache_clean ? 2'b10 // Clean Dcache + : 2'b01; // Inv Dcache + +assign cp0_ifu_btb_clr = 1'b0; +assign cp0_ifu_btb_en = l0btb; +assign cp0_ifu_bht_inv = bht_rst_inv_req; +assign cp0_ifu_bht_en = bpe; +assign cp0_ifu_ras_en = rs; + + +// &Force("nonport", "cp0_ifu_btb_clr"); @531 +// &Force("nonport", "cp0_ifu_btb_en"); @532 + +// &Force("nonport", "cp0_ifu_bht_inv"); @537 +// &Force("nonport", "cp0_ifu_bht_en"); @538 + +// &Force("nonport", "cp0_ifu_ras_en"); @543 + + + + +//========================================================== +// Rename for Output +//========================================================== +// Output to LSU +assign cp0_lsu_dcache_en = de; +assign cp0_lsu_dcache_wb = wb; +assign cp0_lsu_dcache_wa = wa; + +assign cp0_ifu_icache_en = ie; +assign cp0_ifu_icache_inv_req = icache_rst_inv_req; +assign cp0_ifu_icache_inv_type = ext_inst_ifu_icc_req ? ext_inst_ifu_icc_type + : 1'b0; +assign cp0_ifu_icache_inv_addr[31:0] = ext_inst_ifu_icc_addr[31:0]; +// &Force("nonport", "icache_rst_inv_req"); @572 + +// AEE means Accurated Expt, So Async Expt is !mhint_aee. +assign cp0_xx_async_expt_en = !mhint_aee; + +//========================================================== +// Output for CP0 +//========================================================== +assign regs_special_lpmd[1:0] = mexstatus_lpmd[1:0]; +assign regs_srst_srstmd[1:0] = mexstatus_rstmd[1:0]; +assign regs_srst_srst_vld = srst_vld; +assign regs_spswap_en = mexstatus_spswapen; +assign regs_cpu_in_nmi = mexstatus_nmi; + +//========================================================== +// Output for RTU +//========================================================== +assign cp0_rtu_wfe_en = mexstatus_wfeen; +assign cp0_rtu_in_expt = mexstatus_expt; + +//========================================================== +// Output for IDU +//========================================================== +assign cp0_idu_spec_push_en = mexstatus_spushen; +assign cp0_idu_swap_sp_en = mexstatus_spswapen; + +//output to dbg infor +assign rst_top_op_done = rst_inv_done; +//---------------------------------------------------------- +// For DTU +//---------------------------------------------------------- +//assign cp0_dtu_icg_en = module_icg_en[8]; + +assign cp0_dtu_pcfifo_frz = pcfifo_freeze; +// &ModuleEnd; @607 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_inst.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_inst.v new file mode 100644 index 0000000000000000000000000000000000000000..62936591e8cf486d967ea43ea02ab8d4111e5775 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_ext_inst.v @@ -0,0 +1,163 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_ext_inst( + ext_inst_ifu_icc_addr, + ext_inst_ifu_icc_req, + ext_inst_ifu_icc_type, + ext_inst_ifu_inv_done, + ext_inst_lsu_icc_addr, + ext_inst_lsu_icc_done, + ext_inst_lsu_icc_op, + ext_inst_lsu_icc_req, + ext_inst_lsu_icc_type, + ext_iui_cache_stall, + ext_iui_expt_vld, + iui_ext_inst_cache, + iui_ext_inst_imm, + iui_ext_inst_rs1 +); + +// &Ports; @24 +input ext_inst_ifu_inv_done; +input ext_inst_lsu_icc_done; +input iui_ext_inst_cache; +input [11:0] iui_ext_inst_imm; +input [31:0] iui_ext_inst_rs1; +output [31:0] ext_inst_ifu_icc_addr; +output ext_inst_ifu_icc_req; +output ext_inst_ifu_icc_type; +output [31:0] ext_inst_lsu_icc_addr; +output [1 :0] ext_inst_lsu_icc_op; +output ext_inst_lsu_icc_req; +output [1 :0] ext_inst_lsu_icc_type; +output ext_iui_cache_stall; +output ext_iui_expt_vld; + +// &Regs; @25 +reg [1 :0] inst_dst; +reg [1 :0] inst_type; + +// &Wires; @26 +wire cache_inst_illegal; +wire [1 :0] cache_inst_op; +wire cache_inst_rs1; +wire [2 :0] cache_inst_type; +wire [31:0] ext_inst_ifu_icc_addr; +wire ext_inst_ifu_icc_req; +wire ext_inst_ifu_icc_type; +wire ext_inst_ifu_inv_done; +wire [31:0] ext_inst_lsu_icc_addr; +wire ext_inst_lsu_icc_done; +wire [1 :0] ext_inst_lsu_icc_op; +wire ext_inst_lsu_icc_req; +wire [1 :0] ext_inst_lsu_icc_type; +wire ext_iui_cache_stall; +wire ext_iui_expt_vld; +wire iui_ext_inst_cache; +wire [11:0] iui_ext_inst_imm; +wire [31:0] iui_ext_inst_rs1; + + +parameter CPU_MODE_U = 2'b00; + +parameter NOP = 2'b00, + DCHE = 2'b01, + ICHE = 2'b10; + +parameter CACHE_ALL = 2'b0, + CACHE_SETWAY = 2'b01, + CACHE_PA = 2'b10; + +//========================================================== +// Cache Inst Decode +//========================================================== +assign cache_inst_op[1:0] = iui_ext_inst_imm[1:0]; +assign cache_inst_type[2:0] = iui_ext_inst_imm[4:2]; +assign cache_inst_rs1 = iui_ext_inst_imm[5]; +// &Force("bus", "iui_ext_inst_imm", 11, 0); @44 + +// &CombBeg; @46 +always @( cache_inst_rs1 + or cache_inst_type[2:0]) +begin + case({cache_inst_rs1, cache_inst_type[2:0]}) + 4'b0_000: begin + inst_dst[1:0] = DCHE; + inst_type[1:0] = CACHE_ALL; + end + 4'b1_000: begin + inst_dst[1:0] = DCHE; + inst_type[1:0] = CACHE_SETWAY; + end + 4'b1_001: begin + inst_dst[1:0] = NOP; + inst_type[1:0] = CACHE_ALL; + end + 4'b1_010: begin + inst_dst[1:0] = DCHE; + inst_type[1:0] = CACHE_PA; + end + 4'b0_100: begin + inst_dst[1:0] = ICHE; + inst_type[1:0] = CACHE_ALL; + end + 4'b1_110: begin + inst_dst[1:0] = ICHE; + inst_type[1:0] = CACHE_PA; + end + 4'b1_100: begin + inst_dst[1:0] = NOP; + inst_type[1:0] = CACHE_ALL; + end + 4'b0_101: begin + inst_dst[1:0] = NOP; + inst_type[1:0] = CACHE_ALL; + end + default: begin + inst_dst[1:0] = NOP; + inst_type[1:0] = CACHE_ALL; + end + endcase +// &CombEnd; @85 +end + +// assign cache_inst_illegal = cp0_yy_priv_mode[1:0] == CPU_MODE_U; +assign cache_inst_illegal = 1'b0; // Now illegal judge is in ID. + +assign ext_iui_expt_vld = cache_inst_illegal; +assign ext_iui_cache_stall = inst_dst[1] && !ext_inst_ifu_inv_done + || inst_dst[0] && !ext_inst_lsu_icc_done; + +//========================================================== +// Dcache inst +//========================================================== +assign ext_inst_lsu_icc_req = iui_ext_inst_cache && inst_dst[0] && !cache_inst_illegal; +assign ext_inst_lsu_icc_type[1:0] = inst_type[1:0]; +assign ext_inst_lsu_icc_op[1:0] = {cache_inst_op[0], cache_inst_op[1]}; +assign ext_inst_lsu_icc_addr[31:0] = iui_ext_inst_rs1[31:0]; + +//========================================================== +// Icache inst +//========================================================== +assign ext_inst_ifu_icc_req = iui_ext_inst_cache && inst_dst[1] && !cache_inst_illegal; +assign ext_inst_ifu_icc_type = inst_type[1]; +assign ext_inst_ifu_icc_addr[31:0] = iui_ext_inst_rs1[31:0]; + +// &ModuleEnd; @111 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_float_csr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_float_csr.v new file mode 100644 index 0000000000000000000000000000000000000000..7d3861f9fa7d15fe71d016e41614c20947035ce3 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_float_csr.v @@ -0,0 +1,174 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_float_csr( + cp0_fpu_xx_dqnan, + cp0_fpu_xx_rm, + cp0_idu_rm, + cpurst_b, + fcsr_local_en, + fcsr_value, + fflags_clk, + fflags_local_en, + fflags_value, + fpu_cp0_fflags_updt, + fpu_cp0_wb_fflags, + fpu_cp0_wb_fflags_updt, + frm_local_en, + frm_value, + fxcr_local_en, + fxcr_value, + iui_regs_wdata, + regs_clk +); + +// &Ports; @24 +input cpurst_b; +input fcsr_local_en; +input fflags_clk; +input fflags_local_en; +input [4 :0] fpu_cp0_wb_fflags; +input fpu_cp0_wb_fflags_updt; +input frm_local_en; +input fxcr_local_en; +input [31:0] iui_regs_wdata; +input regs_clk; +output cp0_fpu_xx_dqnan; +output [2 :0] cp0_fpu_xx_rm; +output [2 :0] cp0_idu_rm; +output [31:0] fcsr_value; +output [31:0] fflags_value; +output fpu_cp0_fflags_updt; +output [31:0] frm_value; +output [31:0] fxcr_value; + +// &Regs; @25 +reg [4 :0] fcsr_fflags; +reg [2 :0] fcsr_frm; +reg fxcr_dqnan; +reg fxcr_fe; + +// &Wires; @26 +wire cp0_fpu_xx_dqnan; +wire [2 :0] cp0_fpu_xx_rm; +wire [2 :0] cp0_idu_rm; +wire cpurst_b; +wire fcsr_local_en; +wire [31:0] fcsr_value; +wire fflags_clk; +wire fflags_local_en; +wire [31:0] fflags_value; +wire [4 :0] fpu_cp0_fflags; +wire fpu_cp0_fflags_updt; +wire [4 :0] fpu_cp0_wb_fflags; +wire fpu_cp0_wb_fflags_updt; +wire frm_local_en; +wire [31:0] frm_value; +wire fxcr_local_en; +wire [31:0] fxcr_value; +wire [31:0] iui_regs_wdata; +wire regs_clk; + + +// &Force("bus", "iui_regs_wdata", 31, 0); @28 + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + fcsr_frm[2:0] <= 3'b0; + end + else if (fcsr_local_en) begin + fcsr_frm[2:0] <= iui_regs_wdata[7:5]; + end + else if (frm_local_en) begin + fcsr_frm[2:0] <= iui_regs_wdata[2:0]; + end + else if (fxcr_local_en) begin + fcsr_frm[2:0] <= iui_regs_wdata[26:24]; + end + else begin + fcsr_frm[2:0] <= fcsr_frm[2:0]; + end +end + +assign frm_value[31:0] = {29'b0, fcsr_frm[2:0]}; + +always @ (posedge fflags_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + fcsr_fflags[4:0] <= 5'b0; + end + else if (fcsr_local_en) begin + fcsr_fflags[4:0] <= iui_regs_wdata[4:0]; + end + else if (fflags_local_en) begin + fcsr_fflags[4:0] <= iui_regs_wdata[4:0]; + end + else if (fxcr_local_en) begin + fcsr_fflags[4:0] <= iui_regs_wdata[4:0]; + end + else if (fpu_cp0_fflags_updt) begin + fcsr_fflags[4:0] <= fcsr_fflags[4:0] | fpu_cp0_fflags[4:0]; + end + else begin + fcsr_fflags[4:0] <= fcsr_fflags[4:0]; + end +end + +assign fpu_cp0_fflags_updt = fpu_cp0_wb_fflags_updt; +// &Force("output","fpu_cp0_fflags_updt"); @74 +assign fpu_cp0_fflags[4:0] = fpu_cp0_wb_fflags[4:0]; +assign fflags_value[31:0] = {27'b0, fcsr_fflags[4:0]}; +assign fcsr_value[31:0] = {24'b0, fcsr_frm[2:0], fcsr_fflags[4:0]}; + +always @ (posedge fflags_clk or negedge cpurst_b) +begin + if (!cpurst_b) + fxcr_fe <= 1'b0; + else if (fxcr_local_en) + fxcr_fe <= iui_regs_wdata[5]; + else if (fpu_cp0_fflags_updt) + fxcr_fe <= fxcr_fe || (|fpu_cp0_fflags[4:0]); + else + fxcr_fe <= fxcr_fe; +end + +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) + fxcr_dqnan <= 1'b0; + else if (fxcr_local_en) + fxcr_dqnan <= iui_regs_wdata[23]; + else + fxcr_dqnan <= fxcr_dqnan; +end + +assign fxcr_value[31:0] = {5'b0, fcsr_frm[2:0], fxcr_dqnan, 17'b0, fxcr_fe, fcsr_fflags[4:0]}; + + + +//========================================================== +// Output Signal +//========================================================== +assign cp0_fpu_xx_rm[2:0] = fcsr_frm[2:0]; +assign cp0_fpu_xx_dqnan = fxcr_dqnan; + +assign cp0_idu_rm[2:0] = fcsr_frm[2:0]; + +// &ModuleEnd; @113 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_info_csr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_info_csr.v new file mode 100644 index 0000000000000000000000000000000000000000..7df9118bc8ebc371fcedd3a16b5c8401db7157e2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_info_csr.v @@ -0,0 +1,294 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_info_csr( + cpurst_b, + iui_regs_inst_csr, + marchid_value, + mcpuid_local_en, + mcpuid_value, + mhartid_value, + mimpid_value, + mvendorid_value, + regs_clk +); + +// &Ports; @24 +input cpurst_b; +input iui_regs_inst_csr; +input mcpuid_local_en; +input regs_clk; +output [31:0] marchid_value; +output [31:0] mcpuid_value; +output [31:0] mhartid_value; +output [31:0] mimpid_value; +output [31:0] mvendorid_value; + +// &Regs; @25 +reg [31:0] cpuid_value; +reg [1 :0] index; + +// &Wires; @26 +wire [31:0] cpuid_index0_value; +wire [31:0] cpuid_index1_value; +wire [31:0] cpuid_index2_value; +wire cpurst_b; +wire index_max; +wire [1 :0] index_next_val; +wire iui_regs_inst_csr; +wire [31:0] marchid_value; +wire mcpuid_local_en; +wire [31:0] mcpuid_value; +wire [31:0] mhartid_value; +wire [31:0] mimpid_value; +wire [31:0] mvendorid_value; +wire regs_clk; + + +//========================================================== +// Machine Information CSR Module +// 1. RISC-V Priviledge 1.11 Information Group +// 2. RISC-V Priviledge 1.11 Basic Counters +// 3. T-Head CPU Information Extension +//========================================================== +//---------------------------------------------------------- +// 1. RISC-V Priviledge 1.11 Information Group +//---------------------------------------------------------- + +//========================================================== +// Define the MVENDORID Register +//========================================================== +// Machine Vendor ID Register +// 32-bit readonly +// Providing the JEDEC ID of T-Head +//========================================================== +assign mvendorid_value[31:0] = 32'h5B7; + +//========================================================== +// Define the MARCHID Register +//========================================================== +// Machine Architecture ID Register +// 32-bit readonly +// *Currently not implemented, need to be defined +//========================================================== +assign marchid_value[31:0] = 32'b0; + +//========================================================== +// Define the MIMPID Register +//========================================================== +// Machine Implementation ID Register +// 32-bit readonly +// Providing the implementation ID of the version of core +// *Currently not implemented, need to be defined +//========================================================== +assign mimpid_value[31:0] = 32'b0; + +//========================================================== +// Define the MHARTID Register +//========================================================== +// Machine Hart ID Register +// 32-bit readonly +// Providing the Hart ID of the current core +// For single core only, fix to 32'b0 +//========================================================== +assign mhartid_value[31:0] = 32'b0; + +//---------------------------------------------------------- +// 2. RISC-V Priviledge 1.11 Basic Counters +//---------------------------------------------------------- +// mcycle, minstret now in HPCP. + +//---------------------------------------------------------- +// 3. T-Head CPU Information Extension +//---------------------------------------------------------- + +//========================================================== +// Define the cpuid register +//========================================================== + +//---------------------------------------------------------- +// Index Register +//---------------------------------------------------------- +assign index_max = (index[1:0] == 2'd2); +assign index_next_val[1:0] = (index_max) ? 2'd0 + : index[1:0] + 2'd1; + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + index[1:0] <= 2'b0; + end + else if (iui_regs_inst_csr && mcpuid_local_en) + begin + index[1:0] <= index_next_val[1:0]; + end + else + begin + index[1:0] <= index[1:0]; + end +end + +//---------------------------------------------------------- +// Implement of cpuid register +//---------------------------------------------------------- +// &CombBeg; @115 +always @( cpuid_index1_value[31:0] + or cpuid_index0_value[31:0] + or index[1:0] + or cpuid_index2_value[31:0]) +begin + case(index[1:0]) + 2'b00 : cpuid_value[31:0] = cpuid_index0_value[31:0]; + 2'b01 : cpuid_value[31:0] = cpuid_index1_value[31:0]; + 2'b10 : cpuid_value[31:0] = cpuid_index2_value[31:0]; + default : cpuid_value[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @122 +end + +//--------------------------------------------------------- +// Index 0 +//--------------------------------------------------------- + assign cpuid_index0_value[31:28] = 4'b0000; + +//------------------------------------------------ +// Arch +//------------------------------------------------ + assign cpuid_index0_value[27:26] = 2'b10; // CSKY V3 instruction set + +//------------------------------------------------ +// Family +//------------------------------------------------ + assign cpuid_index0_value[25:22] = 4'b0000; // E Series + +//------------------------------------------------ +// Class +//------------------------------------------------ + assign cpuid_index0_value[21:18] = 4'b0100; // E906 + +//------------------------------------------------ +// Model +//------------------------------------------------ + assign cpuid_index0_value[17:11] = 7'b0; + + assign cpuid_index0_value[9] = 1'b0; + + assign cpuid_index0_value[8] = 1'b1; + + assign cpuid_index0_value[10] = 1'b0; +//------------------------------------------------ +// ISA Revision +//------------------------------------------------ + assign cpuid_index0_value[7:3] = 5'b00001; + +//------------------------------------------------ +// Version +//------------------------------------------------ + assign cpuid_index0_value[2:0] = 3'b101; //CPID Rev.5 + +//--------------------------------------------------------- +// Index 1 +//--------------------------------------------------------- + assign cpuid_index1_value[31:28] = 4'b0001; + +//------------------------------------------------ +// Revision +//------------------------------------------------ + assign cpuid_index1_value[27:24] = `REVISION; + +//------------------------------------------------ +// Sub Revision +//------------------------------------------------ + assign cpuid_index1_value[23:18] = `SUB_VERSION; + +//------------------------------------------------ +// Patch +//------------------------------------------------ + assign cpuid_index1_value[17:12] = `PATCH; + +//------------------------------------------------ +// PRODUCT ID +//------------------------------------------------ + assign cpuid_index1_value[11:0] = `PRODUCT_ID; + +//------------------------------------------------ +// Index 2 +//------------------------------------------------ + assign cpuid_index2_value[31:28] = 4'b0010; + +//------------------------------------------------ +// IBUS +//------------------------------------------------ + assign cpuid_index2_value[27:26] = 2'b01; + +//------------------------------------------------ +// DBUS +//------------------------------------------------ + assign cpuid_index2_value[25:24] = 2'b01; + +//------------------------------------------------ +// SBUS +//------------------------------------------------ + assign cpuid_index2_value[23:21] = 3'b001; + +//------------------------------------------------ +// BTB +//------------------------------------------------ + assign cpuid_index2_value[20:19] = 2'b01; + +//------------------------------------------------ +// BHT +//------------------------------------------------ + assign cpuid_index2_value[18:16] = 3'b011; + +//------------------------------------------------ +// INTC +//------------------------------------------------ + assign cpuid_index2_value[15:12] = 4'b1111; + +//------------------------------------------------ +// DCACHE Todo +//------------------------------------------------ + assign cpuid_index2_value[11:9] = 3'b100; + +//------------------------------------------------ +// ICACHE +//------------------------------------------------ + assign cpuid_index2_value[8:6] = 3'b100; + +//------------------------------------------------ +// PMP zone size +//------------------------------------------------ + assign cpuid_index2_value[5:3] = 3'b111; // 4B + +//------------------------------------------------ +// MGU zone num +//------------------------------------------------ + assign cpuid_index2_value[2:0] = 3'b011; +assign mcpuid_value[31:0] = cpuid_value[31:0]; + + +//========================================================== +// Rename for Output +//========================================================== + +//assign info_csr_cpuid0_value[31:0] = cpuid_index0_value[31:0]; + +// &ModuleEnd; @365 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_iui.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_iui.v new file mode 100644 index 0000000000000000000000000000000000000000..339db127bd6c3b74b1303de6137b8a9cae921f0f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_iui.v @@ -0,0 +1,606 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_iui( + cp0_dtu_addr, + cp0_dtu_rreg, + cp0_dtu_wdata, + cp0_dtu_wreg, + cp0_idu_ex1_stall, + cp0_iu_adder_borrow_in, + cp0_iu_adder_borrow_vld, + cp0_rtu_ex1_chgflw_pc, + cp0_rtu_ex1_chgflw_vld, + cp0_rtu_ex1_cmplt, + cp0_rtu_ex1_cmplt_dp, + cp0_rtu_ex1_dret, + cp0_rtu_ex1_ebreak, + cp0_rtu_ex1_expt_inst, + cp0_rtu_ex1_expt_tval, + cp0_rtu_ex1_expt_vec, + cp0_rtu_ex1_flush, + cp0_rtu_ex1_halt_info, + cp0_rtu_ex1_inst_len, + cp0_rtu_ex1_inst_vld, + cp0_rtu_ex1_ipush_spec_fail, + cp0_rtu_ex1_mret, + cp0_rtu_ex1_split_inst, + cp0_rtu_ex1_tail_fail, + cp0_rtu_wb_data, + cp0_rtu_wb_preg, + cp0_rtu_wb_vld, + cpurst_b, + ext_iui_cache_stall, + ext_iui_expt_vld, + idu_cp0_ex1_cmplt_dp_sel, + idu_cp0_ex1_dst_idx, + idu_cp0_ex1_dst_vld, + idu_cp0_ex1_expt_high, + idu_cp0_ex1_expt_type, + idu_cp0_ex1_expt_vld, + idu_cp0_ex1_func, + idu_cp0_ex1_gateclk_sel, + idu_cp0_ex1_halt_info, + idu_cp0_ex1_inst_len, + idu_cp0_ex1_ipush_spec_fail, + idu_cp0_ex1_opcode, + idu_cp0_ex1_rs1, + idu_cp0_ex1_rs2, + idu_cp0_ex1_sel, + idu_cp0_ex1_split_inst, + idu_cp0_ex1_tail_fail, + ifu_cp0_warm_up, + iu_cp0_ex1_borrow_expt_pc, + iui_csr_wen_f, + iui_ext_inst_cache, + iui_ext_inst_imm, + iui_ext_inst_rs1, + iui_regs_csr_mnxti_vld, + iui_regs_csr_wen, + iui_regs_imm, + iui_regs_inst_csr, + iui_regs_inst_mret, + iui_regs_wdata, + iui_regs_wdata_mie, + iui_regs_wdata_rs1, + iui_regs_wdata_srst, + iui_special_ecall, + iui_special_fence, + iui_special_fencei, + iui_special_int_vld, + iui_special_sync, + iui_special_synci, + iui_special_wfi, + regs_clk, + regs_iui_expt_vld, + regs_iui_mepc, + regs_iui_mie, + regs_iui_mnxti_sel, + regs_iui_mstatus, + regs_iui_pm, + regs_iui_rdata, + rtu_cp0_wk_int, + rtu_yy_xx_dbgon, + special_iui_expt_vld, + special_iui_stall, + srst_iui_stall +); + +// &Ports; @24 +input cpurst_b; +input ext_iui_cache_stall; +input ext_iui_expt_vld; +input idu_cp0_ex1_cmplt_dp_sel; +input [5 :0] idu_cp0_ex1_dst_idx; +input idu_cp0_ex1_dst_vld; +input idu_cp0_ex1_expt_high; +input idu_cp0_ex1_expt_type; +input idu_cp0_ex1_expt_vld; +input [19:0] idu_cp0_ex1_func; +input idu_cp0_ex1_gateclk_sel; +input [14:0] idu_cp0_ex1_halt_info; +input idu_cp0_ex1_inst_len; +input idu_cp0_ex1_ipush_spec_fail; +input [31:0] idu_cp0_ex1_opcode; +input [31:0] idu_cp0_ex1_rs1; +input [11:0] idu_cp0_ex1_rs2; +input idu_cp0_ex1_sel; +input idu_cp0_ex1_split_inst; +input idu_cp0_ex1_tail_fail; +input ifu_cp0_warm_up; +input [31:0] iu_cp0_ex1_borrow_expt_pc; +input regs_clk; +input regs_iui_expt_vld; +input [31:0] regs_iui_mepc; +input regs_iui_mie; +input regs_iui_mnxti_sel; +input [31:0] regs_iui_mstatus; +input [1 :0] regs_iui_pm; +input [31:0] regs_iui_rdata; +input rtu_cp0_wk_int; +input rtu_yy_xx_dbgon; +input special_iui_expt_vld; +input special_iui_stall; +input srst_iui_stall; +output [11:0] cp0_dtu_addr; +output cp0_dtu_rreg; +output [31:0] cp0_dtu_wdata; +output cp0_dtu_wreg; +output cp0_idu_ex1_stall; +output cp0_iu_adder_borrow_in; +output cp0_iu_adder_borrow_vld; +output [30:0] cp0_rtu_ex1_chgflw_pc; +output cp0_rtu_ex1_chgflw_vld; +output cp0_rtu_ex1_cmplt; +output cp0_rtu_ex1_cmplt_dp; +output cp0_rtu_ex1_dret; +output cp0_rtu_ex1_ebreak; +output cp0_rtu_ex1_expt_inst; +output [31:0] cp0_rtu_ex1_expt_tval; +output [3 :0] cp0_rtu_ex1_expt_vec; +output cp0_rtu_ex1_flush; +output [14:0] cp0_rtu_ex1_halt_info; +output cp0_rtu_ex1_inst_len; +output cp0_rtu_ex1_inst_vld; +output cp0_rtu_ex1_ipush_spec_fail; +output cp0_rtu_ex1_mret; +output cp0_rtu_ex1_split_inst; +output cp0_rtu_ex1_tail_fail; +output [31:0] cp0_rtu_wb_data; +output [5 :0] cp0_rtu_wb_preg; +output cp0_rtu_wb_vld; +output iui_csr_wen_f; +output iui_ext_inst_cache; +output [11:0] iui_ext_inst_imm; +output [31:0] iui_ext_inst_rs1; +output iui_regs_csr_mnxti_vld; +output iui_regs_csr_wen; +output [11:0] iui_regs_imm; +output iui_regs_inst_csr; +output iui_regs_inst_mret; +output [31:0] iui_regs_wdata; +output iui_regs_wdata_mie; +output [31:0] iui_regs_wdata_rs1; +output [1 :0] iui_regs_wdata_srst; +output iui_special_ecall; +output iui_special_fence; +output iui_special_fencei; +output iui_special_int_vld; +output iui_special_sync; +output iui_special_synci; +output iui_special_wfi; + +// &Regs; @25 +reg iui_csr_wen_f; +reg [31:0] iui_expt_tval; +reg [3 :0] iui_expt_vec; + +// &Wires; @26 +wire [11:0] cp0_dtu_addr; +wire cp0_dtu_rreg; +wire [31:0] cp0_dtu_wdata; +wire cp0_dtu_wreg; +wire cp0_idu_ex1_stall; +wire cp0_iu_adder_borrow_in; +wire cp0_iu_adder_borrow_vld; +wire [30:0] cp0_rtu_ex1_chgflw_pc; +wire cp0_rtu_ex1_chgflw_vld; +wire cp0_rtu_ex1_cmplt; +wire cp0_rtu_ex1_cmplt_dp; +wire cp0_rtu_ex1_dret; +wire cp0_rtu_ex1_ebreak; +wire cp0_rtu_ex1_expt_inst; +wire [31:0] cp0_rtu_ex1_expt_tval; +wire [3 :0] cp0_rtu_ex1_expt_vec; +wire cp0_rtu_ex1_flush; +wire [14:0] cp0_rtu_ex1_halt_info; +wire cp0_rtu_ex1_inst_len; +wire cp0_rtu_ex1_inst_vld; +wire cp0_rtu_ex1_ipush_spec_fail; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_ex1_split_inst; +wire cp0_rtu_ex1_tail_fail; +wire [31:0] cp0_rtu_wb_data; +wire [5 :0] cp0_rtu_wb_preg; +wire cp0_rtu_wb_vld; +wire cpurst_b; +wire ext_iui_cache_stall; +wire ext_iui_expt_vld; +wire idu_cp0_ex1_cmplt_dp_sel; +wire [5 :0] idu_cp0_ex1_dst_idx; +wire idu_cp0_ex1_dst_vld; +wire idu_cp0_ex1_expt_high; +wire idu_cp0_ex1_expt_type; +wire idu_cp0_ex1_expt_vld; +wire [19:0] idu_cp0_ex1_func; +wire idu_cp0_ex1_gateclk_sel; +wire [14:0] idu_cp0_ex1_halt_info; +wire idu_cp0_ex1_inst_len; +wire idu_cp0_ex1_ipush_spec_fail; +wire [31:0] idu_cp0_ex1_opcode; +wire [31:0] idu_cp0_ex1_rs1; +wire [11:0] idu_cp0_ex1_rs2; +wire idu_cp0_ex1_sel; +wire idu_cp0_ex1_split_inst; +wire idu_cp0_ex1_tail_fail; +wire [31:0] iu_cp0_ex1_borrow_expt_pc; +wire iui_accflt_expt_vld; +wire iui_cancel; +wire [31:0] iui_chgflw_pc; +wire iui_chgflw_vld; +wire iui_csr_expt_vld; +wire [31:0] iui_csr_mstatus; +wire [31:0] iui_csr_rdata; +wire iui_csr_umode_inv; +wire [31:0] iui_csr_wdata; +wire [31:0] iui_csr_wdata_mstatus; +wire iui_csr_wen; +wire iui_csr_wen_vld; +wire iui_csr_write_inv; +wire [31:0] iui_csrrc_rs1; +wire [31:0] iui_csrrc_rs1_mstatus; +wire [31:0] iui_csrrs_rs1; +wire [31:0] iui_csrrs_rs1_mstatus; +wire [31:0] iui_csrrw_rs1; +wire iui_ebreak_expt_vld; +wire iui_expt_vld; +wire iui_ext_inst_cache; +wire [11:0] iui_ext_inst_imm; +wire [31:0] iui_ext_inst_rs1; +wire iui_illegal_expt_vld; +wire iui_inst_cache; +wire iui_inst_cmplt; +wire iui_inst_csr; +wire [2 :0] iui_inst_csr_func; +wire iui_inst_dret; +wire [5 :0] iui_inst_dst_idx; +wire iui_inst_dst_vld; +wire iui_inst_ebrek; +wire iui_inst_ecall; +wire iui_inst_fence; +wire iui_inst_fenci; +wire iui_inst_flush; +wire [5 :0] iui_inst_func; +wire [14:0] iui_inst_halt_info; +wire [11:0] iui_inst_imm; +wire iui_inst_ipush_spec_fail; +wire iui_inst_mret; +wire iui_inst_mret_vld; +wire [31:0] iui_inst_opcode; +wire [31:0] iui_inst_rs1; +wire iui_inst_split_inst; +wire iui_inst_stall; +wire [4 :0] iui_inst_sub_func; +wire iui_inst_sync; +wire iui_inst_synci; +wire iui_inst_tail_fail; +wire iui_inst_vld; +wire iui_inst_wfi; +wire iui_mecall_expt_vld; +wire iui_mret_umode_inv; +wire iui_regs_csr_mnxti_vld; +wire iui_regs_csr_wen; +wire [11:0] iui_regs_imm; +wire iui_regs_inst_csr; +wire iui_regs_inst_mret; +wire [31:0] iui_regs_wdata; +wire iui_regs_wdata_mie; +wire [31:0] iui_regs_wdata_rs1; +wire [1 :0] iui_regs_wdata_srst; +wire iui_special_ebrek; +wire iui_special_ecall; +wire iui_special_fence; +wire iui_special_fencei; +wire iui_special_int_vld; +wire iui_special_sync; +wire iui_special_synci; +wire iui_special_wfi; +wire iui_uecall_expt_vld; +wire iui_wfi_umode_inv; +wire regs_clk; +wire regs_iui_expt_vld; +wire [31:0] regs_iui_mepc; +wire regs_iui_mie; +wire regs_iui_mnxti_sel; +wire [31:0] regs_iui_mstatus; +wire [1 :0] regs_iui_pm; +wire [31:0] regs_iui_rdata; +wire rtu_cp0_wk_int; +wire rtu_yy_xx_dbgon; +wire special_iui_expt_vld; +wire special_iui_stall; +wire srst_iui_stall; + + +//========================================================== +// CP0 IUI Module +// 1. Prepare CSR and Special Inst Information +// 2. Generate Retire and Exception Signals +//========================================================== + +//------------------------------------------------ +// 1. Prepare CSR and Special Inst Information +// a. Get the instruction functions +// b. Generate CSR Inst Information +// c. Generate Special Inst Information +//------------------------------------------------ +// &Force("bus","idu_cp0_ex1_func",19,0); @40 +// a. Get the instruction functions +assign iui_inst_vld = idu_cp0_ex1_gateclk_sel && !idu_cp0_ex1_expt_vld && !iui_cancel; +assign iui_inst_func[5:0] = idu_cp0_ex1_func[10:5]; +assign iui_inst_sub_func[4:0] = idu_cp0_ex1_func[4:0]; +assign iui_inst_dst_vld = idu_cp0_ex1_gateclk_sel && idu_cp0_ex1_dst_vld; +assign iui_inst_dst_idx[5:0] = idu_cp0_ex1_dst_idx[5:0]; +// &Force("bus", "idu_cp0_ex1_dst_idx", 5, 0); @47 +assign iui_inst_rs1[31:0] = idu_cp0_ex1_rs1[31:0]; +assign iui_inst_imm[11:0] = {12{idu_cp0_ex1_gateclk_sel}} & idu_cp0_ex1_rs2[11:0]; +assign iui_inst_opcode[31:0] = {32{idu_cp0_ex1_gateclk_sel}} & idu_cp0_ex1_opcode[31:0]; +assign iui_inst_halt_info[`TDT_HINFO_WIDTH-1:0] = + {`TDT_HINFO_WIDTH{idu_cp0_ex1_gateclk_sel}} & idu_cp0_ex1_halt_info[`TDT_HINFO_WIDTH-1:0]; +assign iui_inst_ipush_spec_fail = idu_cp0_ex1_ipush_spec_fail; +assign iui_inst_tail_fail = idu_cp0_ex1_tail_fail; +assign iui_inst_split_inst = idu_cp0_ex1_split_inst; +// b. Generate CSR Inst Information +// CSR Write Enable +assign iui_inst_csr = iui_inst_vld && iui_inst_func[0]; +assign iui_csr_wen = iui_inst_vld && iui_inst_func[0] + && !iui_inst_sub_func[3]; +// &Force("input","ifu_cp0_warm_up"); @61 +always @ (posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) + iui_csr_wen_f <= 1'b0; + else if (iui_regs_csr_wen && iui_inst_stall) + iui_csr_wen_f <= 1'b1; + else + iui_csr_wen_f <= 1'b0; +end + +assign iui_csr_wen_vld = iui_regs_csr_wen && !iui_csr_wen_f + && !iui_csr_expt_vld; +// &Force("output","iui_csr_wen_f"); @75 +// &Force("input","regs_clk"); @78 +// CSR Func 0:CSRRW, 1: CSRRS, 2: CSRRC +assign iui_inst_csr_func[2:0] = {3{idu_cp0_ex1_func[5]}} + & idu_cp0_ex1_func[2:0]; + +// CSR write data prepare +assign iui_csr_rdata[31:0] = regs_iui_rdata[31:0]; +assign iui_csrrw_rs1[31:0] = iui_inst_rs1[31:0]; +assign iui_csrrs_rs1[31:0] = iui_csr_rdata[31:0] | iui_inst_rs1[31:0]; +assign iui_csrrc_rs1[31:0] = iui_csr_rdata[31:0] & (~iui_inst_rs1[31:0]); + +assign iui_csr_wdata[31:0] = {32{iui_inst_csr_func[0]}} & iui_csrrw_rs1[31:0] + | {32{iui_inst_csr_func[1]}} & iui_csrrs_rs1[31:0] + | {32{iui_inst_csr_func[2]}} & iui_csrrc_rs1[31:0]; +assign iui_regs_csr_mnxti_vld = !(iui_inst_rs1[31:0] == 32'b0 && (iui_inst_csr_func[1] + || iui_inst_csr_func[2])); + +assign iui_csr_mstatus[31:0] = regs_iui_mstatus[31:0]; +assign iui_csrrs_rs1_mstatus[31:0] = iui_csr_mstatus[31:0] | iui_inst_rs1[31:0]; +assign iui_csrrc_rs1_mstatus[31:0] = iui_csr_mstatus[31:0] & (~iui_inst_rs1[31:0]); + +assign iui_csr_wdata_mstatus[31:0] = {32{iui_inst_csr_func[0]}} & iui_csrrw_rs1[31:0] + | {32{iui_inst_csr_func[1]}} & iui_csrrs_rs1_mstatus[31:0] + | {32{iui_inst_csr_func[2]}} & iui_csrrc_rs1_mstatus[31:0]; + +assign iui_regs_wdata_srst[1:0] = {2{|iui_inst_csr_func[1:0]}} & iui_inst_rs1[1:0]; // srst[1:0] is always 2'b0. +assign iui_regs_wdata_mie = iui_inst_csr_func[0] && iui_inst_rs1[3] + || iui_inst_csr_func[1] && (regs_iui_mie || iui_inst_rs1[3]) + || iui_inst_csr_func[2] && (regs_iui_mie && !iui_inst_rs1[3]); +// mie is mstatus[3]. + +// c. Generate Special Inst Information +assign iui_inst_fence = iui_inst_vld && iui_inst_func[1] + && iui_inst_sub_func[0]; +assign iui_inst_fenci = iui_inst_vld && iui_inst_func[1] + && iui_inst_sub_func[1]; +assign iui_inst_sync = iui_inst_vld && iui_inst_func[1] + && iui_inst_sub_func[2]; +assign iui_inst_synci = iui_inst_vld && iui_inst_func[1] + && iui_inst_sub_func[3]; +assign iui_inst_ecall = iui_inst_vld && iui_inst_func[2] + && iui_inst_sub_func[0] && !rtu_yy_xx_dbgon; +assign iui_inst_ebrek = iui_inst_vld && iui_inst_func[2] + && iui_inst_sub_func[1]; +assign iui_inst_mret = iui_inst_vld && iui_inst_func[2] + && iui_inst_sub_func[2]&& !rtu_yy_xx_dbgon; +assign iui_inst_wfi = iui_inst_vld && iui_inst_func[2] + && iui_inst_sub_func[3] && !rtu_yy_xx_dbgon; +assign iui_inst_cache = iui_inst_vld && iui_inst_func[2] + && iui_inst_sub_func[4]; + +assign iui_inst_dret = iui_inst_vld && iui_inst_sub_func[1] + && iui_inst_func[4] && rtu_yy_xx_dbgon; +//------------------------------------------------ +// 2. Generate Retire and Exception Signals +// a. Inst Complete +// b. Inst Exception +// c. Change Flow +//------------------------------------------------ + +// a. Inst Complete +// Inst Complete except for WFI stall +// assign iui_inst_cmplt = idu_cp0_ex1_sel && (!special_iui_stall +// || iui_inst_cache && ext_iui_cache_stall); +assign iui_inst_cmplt = idu_cp0_ex1_sel && !iui_inst_stall; +assign iui_inst_stall = iui_inst_cache && ext_iui_cache_stall + || srst_iui_stall + || special_iui_stall; + +assign iui_inst_flush = iui_inst_cmplt && !(iui_inst_func[0] && iui_inst_sub_func[3] + || iui_inst_fence || iui_inst_sync) + && !idu_cp0_ex1_expt_vld + && !iui_cancel; + + +// b. Inst Exception +// Invalid operation when write read-only regs +assign iui_csr_write_inv = iui_csr_wen && iui_inst_imm[11:10] == 2'b11; +assign iui_csr_umode_inv = regs_iui_pm[1:0] == 2'b00 && !rtu_yy_xx_dbgon + && iui_inst_csr && iui_inst_imm[9:8] != 2'b00; +assign iui_mret_umode_inv = regs_iui_pm[1:0] == 2'b00 && iui_inst_mret && !rtu_yy_xx_dbgon; +assign iui_wfi_umode_inv = regs_iui_pm[1:0] == 2'b00 && iui_inst_wfi && !rtu_yy_xx_dbgon; +assign iui_csr_expt_vld = iui_csr_write_inv || iui_csr_umode_inv + || iui_inst_csr && regs_iui_expt_vld + || iui_inst_cache && ext_iui_expt_vld; +assign iui_expt_vld = (idu_cp0_ex1_expt_vld + || iui_csr_expt_vld + || iui_mret_umode_inv + || iui_wfi_umode_inv + || special_iui_expt_vld) + && idu_cp0_ex1_gateclk_sel; +assign iui_cancel = iui_inst_halt_info[`TDT_HINFO_CANCEL] + && idu_cp0_ex1_gateclk_sel; +//// Generate iui int vector +//assign iui_int_vld = |regs_iui_int_sel[2:0]; +//&CombBeg; +//casez(regs_iui_int_sel[2:0]) +// 3'b1?? : iui_int_vec[3:0] = 4'd11; +// 3'b01? : iui_int_vec[3:0] = 4'd7; +// 3'b001 : iui_int_vec[3:0] = 4'd3; +// default : iui_int_vec[3:0] = 3'bx; +//endcase +//&CombEnd; + +// Generate iui expt vector +assign iui_accflt_expt_vld = idu_cp0_ex1_expt_vld && idu_cp0_ex1_expt_type; +assign iui_illegal_expt_vld = idu_cp0_ex1_expt_vld && !idu_cp0_ex1_expt_type + || iui_csr_expt_vld + || iui_mret_umode_inv + || iui_wfi_umode_inv; +assign iui_mecall_expt_vld = iui_inst_ecall && regs_iui_pm[1:0] == 2'b11; +assign iui_uecall_expt_vld = iui_inst_ecall && regs_iui_pm[1:0] == 2'b00; +assign iui_ebreak_expt_vld = iui_inst_ebrek; + +// &CombBeg; @193 +always @( iui_illegal_expt_vld + or iui_uecall_expt_vld + or iui_mecall_expt_vld + or iui_ebreak_expt_vld + or iui_accflt_expt_vld) +begin + if(iui_accflt_expt_vld) + iui_expt_vec[3:0] = 4'd1; + else if(iui_illegal_expt_vld) + iui_expt_vec[3:0] = 4'd2; + else if(iui_mecall_expt_vld) + iui_expt_vec[3:0] = 4'd11; + else if(iui_uecall_expt_vld) + iui_expt_vec[3:0] = 4'd8; + else if(iui_ebreak_expt_vld) + iui_expt_vec[3:0] = 4'd3; + else + iui_expt_vec[3:0] = 4'd0; +// &CombEnd; @206 +end + +//assign iui_ex1_pc[31:0] = {`PA_WIDTH{idu_cp0_ex1_gateclk_sel}} & iu_cp0_ex1_cur_pc[31:0]; +//assign iui_ex1_expt_pc[31:0] = iui_ex1_pc[31:0] +// + {{(`PA_WIDTH-2){1'b0}}, idu_cp0_ex1_expt_high, 1'b0}; +assign cp0_iu_adder_borrow_vld = idu_cp0_ex1_gateclk_sel & (iui_accflt_expt_vld | iui_cancel); +assign cp0_iu_adder_borrow_in = idu_cp0_ex1_expt_high; +// &CombBeg; @213 +always @( iui_cancel + or iui_inst_opcode[31:0] + or iu_cp0_ex1_borrow_expt_pc[31:0] + or iui_accflt_expt_vld) +begin + if (iui_accflt_expt_vld || iui_cancel) + iui_expt_tval[31:0] = iu_cp0_ex1_borrow_expt_pc[31:0]; + else + iui_expt_tval[31:0] = {iui_inst_opcode[31:0]}; +// &CombEnd; @218 +end + + +// c. Change Flow +assign iui_inst_mret_vld = iui_inst_mret && !iui_mret_umode_inv; +assign iui_chgflw_vld = iui_inst_mret_vld && !iui_cancel; +assign iui_chgflw_pc[31:0] = regs_iui_mepc[31:0]; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to Regs +assign iui_regs_imm[11:0] = iui_inst_imm[11:0]; +// &Force("output","iui_regs_csr_wen"); @232 +assign iui_regs_csr_wen = iui_csr_wen && !iui_csr_expt_vld; +assign iui_regs_wdata[31:0] = regs_iui_mnxti_sel ? iui_csr_wdata_mstatus[31:0] + : iui_csr_wdata[31:0]; +assign iui_regs_wdata_rs1[31:0] = iui_csrrw_rs1[31:0]; +assign iui_regs_inst_csr = iui_inst_csr && !iui_csr_expt_vld; +assign iui_regs_inst_mret = iui_inst_mret_vld; +// &Force("output","iui_regs_inst_csr"); @241 +// Output to Regs +assign iui_special_fence = iui_inst_fence; +assign iui_special_fencei = iui_inst_fenci; +assign iui_special_sync = iui_inst_sync; +assign iui_special_synci = iui_inst_synci; +assign iui_special_ecall = iui_inst_ecall; +assign iui_special_ebrek = iui_inst_ebrek; +assign iui_special_wfi = iui_inst_wfi && !iui_wfi_umode_inv; +assign iui_special_int_vld = rtu_cp0_wk_int; +// Output to ext +assign iui_ext_inst_imm[11:0] = iui_inst_imm[11:0]; +assign iui_ext_inst_cache = iui_inst_cache; +assign iui_ext_inst_rs1[31:0] = iui_inst_rs1[31:0]; + +// Output to RTU +assign cp0_rtu_ex1_cmplt = iui_inst_cmplt; +assign cp0_rtu_ex1_cmplt_dp = idu_cp0_ex1_cmplt_dp_sel; +assign cp0_rtu_ex1_flush = iui_inst_flush; +assign cp0_idu_ex1_stall = iui_inst_stall; + +assign cp0_rtu_ex1_inst_vld = idu_cp0_ex1_gateclk_sel; +assign cp0_rtu_ex1_expt_inst = iui_expt_vld; +assign cp0_rtu_ex1_expt_vec[3:0] = iui_expt_vec[3:0]; + +assign cp0_rtu_ex1_chgflw_vld = iui_chgflw_vld; +assign cp0_rtu_ex1_chgflw_pc[30:0] = iui_chgflw_pc[31:1]; + +assign cp0_rtu_wb_vld = iui_inst_cmplt && iui_inst_dst_vld && !iui_expt_vld & ~iui_cancel; +assign cp0_rtu_wb_preg[5:0] = {iui_inst_dst_idx[5:0]}; +assign cp0_rtu_wb_data[31:0] = iui_expt_vld ? idu_cp0_ex1_opcode[31:0] + : regs_iui_rdata[31:0]; + +//assign cp0_rtu_ex1_inst_bkpt[8:0] = idu_cp0_ex1_inst_bkpt[8:0]; + +assign cp0_rtu_ex1_mret = iui_inst_mret_vld; +assign cp0_rtu_ex1_dret = iui_inst_dret; +assign cp0_rtu_ex1_ebreak = iui_special_ebrek; +assign cp0_rtu_ex1_ipush_spec_fail = iui_inst_ipush_spec_fail; +assign cp0_rtu_ex1_tail_fail = iui_inst_tail_fail; +assign cp0_rtu_ex1_split_inst = iui_inst_split_inst; +assign cp0_rtu_ex1_expt_tval[31:0] = iui_expt_tval[31:0]; +assign cp0_rtu_ex1_inst_len = idu_cp0_ex1_inst_len; +assign cp0_rtu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0] = iui_inst_halt_info[`TDT_HINFO_WIDTH-1:0]; +// Output to Sysio +// +//---------------------------------------------------------- +// For DTU +//---------------------------------------------------------- +assign cp0_dtu_wreg = iui_csr_wen_vld; +assign cp0_dtu_rreg = iui_regs_inst_csr; +assign cp0_dtu_addr[11:0] = iui_inst_imm[11:0]; +assign cp0_dtu_wdata[31:0] = iui_csr_wdata[31:0]; + + +// &ModuleEnd; @304 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_regs.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_regs.v new file mode 100644 index 0000000000000000000000000000000000000000..e2c0b3534d28955db8e7678c6f538d09c84cf730 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_regs.v @@ -0,0 +1,1931 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_regs( + cp0_biu_icg_en, + cp0_dtu_icg_en, + cp0_dtu_int_id, + cp0_dtu_mexpt_vld, + cp0_dtu_pcfifo_frz, + cp0_fpu_icg_en, + cp0_fpu_xx_dqnan, + cp0_fpu_xx_rm, + cp0_hpcp_icg_en, + cp0_hpcp_index, + cp0_hpcp_pmdm, + cp0_hpcp_pmdu, + cp0_hpcp_wdata, + cp0_hpcp_wreg, + cp0_idu_fs, + cp0_idu_icg_en, + cp0_idu_mcause, + cp0_idu_mepc, + cp0_idu_rm, + cp0_idu_sp_use_scratch, + cp0_idu_sp_wdata, + cp0_idu_sp_wen, + cp0_idu_sp_wen_gate, + cp0_idu_spec_push_en, + cp0_idu_swap_sp_en, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_btb_clr, + cp0_ifu_btb_en, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_ifu_mtvec, + cp0_ifu_ras_en, + cp0_ifu_rst_inv_done, + cp0_iu_icg_en, + cp0_lsu_dcache_en, + cp0_lsu_dcache_wa, + cp0_lsu_dcache_wb, + cp0_lsu_icc_addr, + cp0_lsu_icc_op, + cp0_lsu_icc_req, + cp0_lsu_icc_type, + cp0_lsu_icg_en, + cp0_lsu_mm, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cp0_pmp_csr_sel, + cp0_pmp_csr_wen, + cp0_pmp_icg_en, + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_pmp_updt_data, + cp0_rtu_icg_en, + cp0_rtu_in_expt, + cp0_rtu_in_nmi, + cp0_rtu_int_level, + cp0_rtu_int_mode, + cp0_rtu_mie, + cp0_rtu_mnxti_vld, + cp0_rtu_mpil, + cp0_rtu_pm_bypass, + cp0_rtu_tail_int_hv, + cp0_rtu_tail_int_id, + cp0_rtu_wfe_en, + cp0_xx_async_expt_en, + cp0_yy_cskyisaee, + cp0_yy_mach_mode, + cp0_yy_priv_mode, + cpurst_b, + dtu_cp0_dcsr_mprven, + dtu_cp0_dcsr_prv, + dtu_cp0_rdata, + ext_inst_ifu_icc_addr, + ext_inst_ifu_icc_req, + ext_inst_ifu_icc_type, + ext_inst_ifu_inv_done, + ext_inst_lsu_icc_addr, + ext_inst_lsu_icc_done, + ext_inst_lsu_icc_op, + ext_inst_lsu_icc_req, + ext_inst_lsu_icc_type, + forever_cpuclk, + fpu_cp0_wb_fflags, + fpu_cp0_wb_fflags_updt, + hpcp_cp0_data, + idu_cp0_id_tail_vld, + idu_cp0_ipop_data, + idu_cp0_mcause_wen, + idu_cp0_mepc_wen, + idu_cp0_sp_reg, + idu_cp0_sp_swap_pending, + idu_cp0_sp_swap_req, + idu_cp0_sp_swap_req_gate, + idu_yy_xx_tail_ack, + ifu_cp0_bht_inv_done, + ifu_cp0_icache_inv_done, + ifu_cp0_rst_inv_req, + ifu_cp0_vec_err, + ifu_cp0_vec_succeed, + inv_sm_clk, + iui_csr_wen_f, + iui_regs_csr_mnxti_vld, + iui_regs_csr_wen, + iui_regs_imm, + iui_regs_inst_csr, + iui_regs_inst_mret, + iui_regs_wdata, + iui_regs_wdata_mie, + iui_regs_wdata_rs1, + iui_regs_wdata_srst, + lsu_cp0_icc_done, + pad_yy_icg_scan_en, + pmp_cp0_data, + regs_clk, + regs_iui_expt_vld, + regs_iui_mepc, + regs_iui_mie, + regs_iui_mnxti_sel, + regs_iui_mstatus, + regs_iui_pm, + regs_iui_rdata, + regs_special_lpmd, + regs_srst_srst_vld, + regs_srst_srstmd, + rst_top_op_done, + rtu_cp0_bus_error, + rtu_cp0_epc, + rtu_cp0_exit_debug, + rtu_cp0_fp_dirty_vld, + rtu_cp0_int_level, + rtu_cp0_lockup_clr, + rtu_cp0_lockup_vld, + rtu_cp0_mie_en, + rtu_cp0_mie_gateclk_en, + rtu_cp0_mnxti_pending_vld, + rtu_cp0_nmi_vld, + rtu_cp0_pending_int_hv, + rtu_cp0_pending_int_id, + rtu_cp0_pending_int_level, + rtu_cp0_tval, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + special_dcache_clean, + special_icache_inv, + special_icache_inv_done, + special_regs_clk_en, + special_regs_inv_sm_clk_en, + sysio_cp0_clkratio, + sysio_cp0_rst_addr, + tcip_cp0_clic_base +); + +// &Ports; @24 +input cpurst_b; +input dtu_cp0_dcsr_mprven; +input [1 :0] dtu_cp0_dcsr_prv; +input [31:0] dtu_cp0_rdata; +input [31:0] ext_inst_ifu_icc_addr; +input ext_inst_ifu_icc_req; +input ext_inst_ifu_icc_type; +input [31:0] ext_inst_lsu_icc_addr; +input [1 :0] ext_inst_lsu_icc_op; +input ext_inst_lsu_icc_req; +input [1 :0] ext_inst_lsu_icc_type; +input forever_cpuclk; +input [4 :0] fpu_cp0_wb_fflags; +input fpu_cp0_wb_fflags_updt; +input [31:0] hpcp_cp0_data; +input idu_cp0_id_tail_vld; +input [31:0] idu_cp0_ipop_data; +input idu_cp0_mcause_wen; +input idu_cp0_mepc_wen; +input [31:0] idu_cp0_sp_reg; +input idu_cp0_sp_swap_pending; +input idu_cp0_sp_swap_req; +input idu_cp0_sp_swap_req_gate; +input idu_yy_xx_tail_ack; +input ifu_cp0_bht_inv_done; +input ifu_cp0_icache_inv_done; +input ifu_cp0_rst_inv_req; +input ifu_cp0_vec_err; +input ifu_cp0_vec_succeed; +input iui_csr_wen_f; +input iui_regs_csr_mnxti_vld; +input iui_regs_csr_wen; +input [11:0] iui_regs_imm; +input iui_regs_inst_csr; +input iui_regs_inst_mret; +input [31:0] iui_regs_wdata; +input iui_regs_wdata_mie; +input [31:0] iui_regs_wdata_rs1; +input [1 :0] iui_regs_wdata_srst; +input lsu_cp0_icc_done; +input pad_yy_icg_scan_en; +input [31:0] pmp_cp0_data; +input rtu_cp0_bus_error; +input [31:0] rtu_cp0_epc; +input rtu_cp0_exit_debug; +input rtu_cp0_fp_dirty_vld; +input [7 :0] rtu_cp0_int_level; +input rtu_cp0_lockup_clr; +input rtu_cp0_lockup_vld; +input rtu_cp0_mie_en; +input rtu_cp0_mie_gateclk_en; +input rtu_cp0_mnxti_pending_vld; +input rtu_cp0_nmi_vld; +input rtu_cp0_pending_int_hv; +input [11:0] rtu_cp0_pending_int_id; +input [7 :0] rtu_cp0_pending_int_level; +input [31:0] rtu_cp0_tval; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input [11:0] rtu_yy_xx_expt_vec; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_int_hv; +input rtu_yy_xx_tail_int_vld; +input special_dcache_clean; +input special_icache_inv; +input special_regs_clk_en; +input special_regs_inv_sm_clk_en; +input [2 :0] sysio_cp0_clkratio; +input [31:0] sysio_cp0_rst_addr; +input [31:0] tcip_cp0_clic_base; +output cp0_biu_icg_en; +output cp0_dtu_icg_en; +output [11:0] cp0_dtu_int_id; +output cp0_dtu_mexpt_vld; +output cp0_dtu_pcfifo_frz; +output cp0_fpu_icg_en; +output cp0_fpu_xx_dqnan; +output [2 :0] cp0_fpu_xx_rm; +output cp0_hpcp_icg_en; +output [11:0] cp0_hpcp_index; +output cp0_hpcp_pmdm; +output cp0_hpcp_pmdu; +output [31:0] cp0_hpcp_wdata; +output cp0_hpcp_wreg; +output [1 :0] cp0_idu_fs; +output cp0_idu_icg_en; +output [31:0] cp0_idu_mcause; +output [31:0] cp0_idu_mepc; +output [2 :0] cp0_idu_rm; +output cp0_idu_sp_use_scratch; +output [31:0] cp0_idu_sp_wdata; +output cp0_idu_sp_wen; +output cp0_idu_sp_wen_gate; +output cp0_idu_spec_push_en; +output cp0_idu_swap_sp_en; +output cp0_ifu_bht_en; +output cp0_ifu_bht_inv; +output cp0_ifu_btb_clr; +output cp0_ifu_btb_en; +output cp0_ifu_icache_en; +output [31:0] cp0_ifu_icache_inv_addr; +output cp0_ifu_icache_inv_req; +output cp0_ifu_icache_inv_type; +output cp0_ifu_icg_en; +output [31:0] cp0_ifu_mtvec; +output cp0_ifu_ras_en; +output cp0_ifu_rst_inv_done; +output cp0_iu_icg_en; +output cp0_lsu_dcache_en; +output cp0_lsu_dcache_wa; +output cp0_lsu_dcache_wb; +output [31:0] cp0_lsu_icc_addr; +output [1 :0] cp0_lsu_icc_op; +output cp0_lsu_icc_req; +output [1 :0] cp0_lsu_icc_type; +output cp0_lsu_icg_en; +output cp0_lsu_mm; +output [31:0] cp0_pad_mcause; +output [31:0] cp0_pad_mintstatus; +output [31:0] cp0_pad_mstatus; +output [19:0] cp0_pmp_csr_sel; +output cp0_pmp_csr_wen; +output cp0_pmp_icg_en; +output [1 :0] cp0_pmp_mstatus_mpp; +output cp0_pmp_mstatus_mprv; +output [31:0] cp0_pmp_updt_data; +output cp0_rtu_icg_en; +output cp0_rtu_in_expt; +output cp0_rtu_in_nmi; +output [7 :0] cp0_rtu_int_level; +output [1 :0] cp0_rtu_int_mode; +output cp0_rtu_mie; +output cp0_rtu_mnxti_vld; +output [7 :0] cp0_rtu_mpil; +output [1 :0] cp0_rtu_pm_bypass; +output cp0_rtu_tail_int_hv; +output [11:0] cp0_rtu_tail_int_id; +output cp0_rtu_wfe_en; +output cp0_xx_async_expt_en; +output cp0_yy_cskyisaee; +output cp0_yy_mach_mode; +output [1 :0] cp0_yy_priv_mode; +output ext_inst_ifu_inv_done; +output ext_inst_lsu_icc_done; +output inv_sm_clk; +output regs_clk; +output regs_iui_expt_vld; +output [31:0] regs_iui_mepc; +output regs_iui_mie; +output regs_iui_mnxti_sel; +output [31:0] regs_iui_mstatus; +output [1 :0] regs_iui_pm; +output [31:0] regs_iui_rdata; +output [1 :0] regs_special_lpmd; +output regs_srst_srst_vld; +output [1 :0] regs_srst_srstmd; +output rst_top_op_done; +output special_icache_inv_done; + +// &Regs; @25 +reg [31:0] regs_csr_rdata; +reg regs_ext_imm_inv; +reg regs_imm_inv; + +// &Wires; @26 +wire cp0_biu_icg_en; +wire cp0_dtu_icg_en; +wire [11:0] cp0_dtu_int_id; +wire cp0_dtu_mexpt_vld; +wire cp0_dtu_pcfifo_frz; +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire [2 :0] cp0_fpu_xx_rm; +wire cp0_hpcp_icg_en; +wire [11:0] cp0_hpcp_index; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [31:0] cp0_hpcp_wdata; +wire cp0_hpcp_wreg; +wire [1 :0] cp0_idu_fs; +wire cp0_idu_icg_en; +wire [31:0] cp0_idu_mcause; +wire [31:0] cp0_idu_mepc; +wire [2 :0] cp0_idu_rm; +wire cp0_idu_sp_use_scratch; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire [31:0] cp0_ifu_mtvec; +wire cp0_ifu_ras_en; +wire cp0_ifu_rst_inv_done; +wire cp0_iu_icg_en; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_dcache_wb; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire cp0_lsu_mm; +wire [31:0] cp0_pad_mcause; +wire [31:0] cp0_pad_mintstatus; +wire [31:0] cp0_pad_mstatus; +wire [19:0] cp0_pmp_csr_sel; +wire cp0_pmp_csr_wen; +wire cp0_pmp_icg_en; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire [31:0] cp0_pmp_updt_data; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_expt; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire [1 :0] cp0_rtu_int_mode; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire cp0_rtu_wfe_en; +wire cp0_xx_async_expt_en; +wire cp0_yy_cskyisaee; +wire cp0_yy_mach_mode; +wire [1 :0] cp0_yy_priv_mode; +wire cpurst_b; +wire dtu_cp0_dcsr_mprven; +wire [1 :0] dtu_cp0_dcsr_prv; +wire [31:0] dtu_cp0_rdata; +wire [31:0] ext_inst_ifu_icc_addr; +wire ext_inst_ifu_icc_req; +wire ext_inst_ifu_icc_type; +wire ext_inst_ifu_inv_done; +wire [31:0] ext_inst_lsu_icc_addr; +wire ext_inst_lsu_icc_done; +wire [1 :0] ext_inst_lsu_icc_op; +wire ext_inst_lsu_icc_req; +wire [1 :0] ext_inst_lsu_icc_type; +wire fcsr_local_en; +wire [31:0] fcsr_value; +wire fflags_clk; +wire fflags_clk_en; +wire fflags_local_en; +wire [31:0] fflags_value; +wire forever_cpuclk; +wire fpu_cp0_fflags_updt; +wire [4 :0] fpu_cp0_wb_fflags; +wire fpu_cp0_wb_fflags_updt; +wire frm_local_en; +wire [31:0] frm_value; +wire fs_dirty_upd; +wire fxcr_local_en; +wire [31:0] fxcr_value; +wire [31:0] hpcp_cp0_data; +wire idu_cp0_id_tail_vld; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire idu_yy_xx_tail_ack; +wire ifu_cp0_bht_inv_done; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_rst_inv_req; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire inv_sm_clk; +wire iu_cp0_wb_ov_updt; +wire iui_csr_wen_f; +wire iui_regs_csr_mnxti_vld; +wire iui_regs_csr_wen; +wire [11:0] iui_regs_imm; +wire iui_regs_inst_csr; +wire iui_regs_inst_mret; +wire [31:0] iui_regs_wdata; +wire iui_regs_wdata_mie; +wire [31:0] iui_regs_wdata_rs1; +wire [1 :0] iui_regs_wdata_srst; +wire lsu_cp0_icc_done; +wire [31:0] marchid_value; +wire mcause_local_en; +wire [31:0] mcause_value; +wire [31:0] mclicbase_value; +wire mcnten_local_en; +wire [31:0] mcnten_value; +wire mcpuid_local_en; +wire [31:0] mcpuid_value; +wire [31:0] medeleg_value; +wire mepc_local_en; +wire [31:0] mepc_value; +wire mexstatus_local_en; +wire [31:0] mexstatus_value; +wire [31:0] mhartid_value; +wire mhcr_local_en; +wire [31:0] mhcr_value; +wire mhint2_local_en; +wire [31:0] mhint2_value; +wire mhint_local_en; +wire [31:0] mhint_value; +wire [31:0] mideleg_value; +wire [31:0] mie_value; +wire [31:0] mimpid_value; +wire [31:0] mintstatus_value; +wire [31:0] mip_value; +wire [31:0] misa_value; +wire mnmicause_local_en; +wire [31:0] mnmicause_value; +wire mnmipc_local_en; +wire [31:0] mnmipc_value; +wire mnxti_local_en; +wire [31:0] mnxti_value; +wire [31:0] mraddr_value; +wire mscratch_local_en; +wire [31:0] mscratch_value; +wire mscratchcsw_local_en; +wire [31:0] mscratchcsw_value; +wire mscratchcswl_local_en; +wire [31:0] mscratchcswl_value; +wire mstatus_local_en; +wire [31:0] mstatus_value; +wire mtval_local_en; +wire [31:0] mtval_value; +wire mtvec_local_en; +wire [29:0] mtvec_rslt; +wire [31:0] mtvec_value; +wire mtvt_local_en; +wire [31:0] mtvt_value; +wire [31:0] mvendorid_value; +wire mxstatus_local_en; +wire [31:0] mxstatus_value; +wire pad_yy_icg_scan_en; +wire [31:0] pmp_cp0_data; +wire regs_clk; +wire regs_cpu_in_int; +wire regs_cpu_in_nmi; +wire [11:0] regs_csr_imm; +wire regs_csr_wen; +wire regs_flush_clk; +wire regs_flush_icg_en; +wire regs_fs_off; +wire regs_icg_en; +wire regs_iui_expt_vld; +wire [31:0] regs_iui_mepc; +wire regs_iui_mie; +wire regs_iui_mnxti_sel; +wire [31:0] regs_iui_mstatus; +wire [1 :0] regs_iui_pm; +wire [31:0] regs_iui_rdata; +wire regs_mach_mode; +wire [1 :0] regs_special_lpmd; +wire regs_spswap_en; +wire regs_srst_srst_vld; +wire [1 :0] regs_srst_srstmd; +wire regs_swap_int_sp_en_gate; +wire rst_top_op_done; +wire rtu_cp0_bus_error; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire rtu_cp0_fp_dirty_vld; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_cp0_mie_en; +wire rtu_cp0_mie_gateclk_en; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_nmi_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire [31:0] rtu_cp0_tval; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire special_dcache_clean; +wire special_icache_inv; +wire special_icache_inv_done; +wire special_regs_clk_en; +wire special_regs_inv_sm_clk_en; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; +wire [31:0] tcip_cp0_clic_base; +wire [1 :0] trap_csr_pm; +wire vxsat_local_en; + + +//========================================================== +// Control Register Module +// 1. Instance ICG Cell +// 1. CSR Address List +// 2. Instance CSR Group Sub-Modules +// 3. CSR Write Port +// 4. CSR Read Port +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +// Clock is on when inst csr or expt vld +// Todo: split cpuid index clk +//------------------------------------------------ +assign regs_icg_en = iui_regs_csr_wen || iui_csr_wen_f + || iui_regs_inst_csr && mcpuid_local_en; // cpuid index +// &Force("output","cp0_iu_icg_en"); @44 +// &Instance("gated_clk_cell", "x_cp0_regs_icg_cell"); @45 +gated_clk_cell x_cp0_regs_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (regs_clk ), + .external_en (1'b0 ), + .global_en (special_regs_clk_en), + .local_en (regs_icg_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @46 +// .external_en (1'b0), @47 +// .global_en (special_regs_clk_en), @48 +// .module_en (cp0_iu_icg_en), @49 +// .local_en (regs_icg_en), @50 +// .clk_out (regs_clk)); @51 +// &Force("output", "regs_clk"); @52 +assign regs_flush_icg_en = iui_regs_inst_csr + || iui_regs_inst_mret + || rtu_cp0_exit_debug + || rtu_yy_xx_expt_vld + || rtu_yy_xx_tail_int_vld + || idu_cp0_id_tail_vld + || ifu_cp0_vec_succeed + || ifu_cp0_vec_err + || rtu_cp0_lockup_vld + || rtu_cp0_lockup_clr + || rtu_cp0_mie_gateclk_en + || idu_cp0_mepc_wen + || idu_cp0_mcause_wen + || idu_yy_xx_tail_ack + || regs_swap_int_sp_en_gate; +// &Instance("gated_clk_cell", "x_cp0_regs_flush_icg_cell"); @68 +gated_clk_cell x_cp0_regs_flush_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (regs_flush_clk ), + .external_en (1'b0 ), + .global_en (special_regs_clk_en), + .local_en (regs_flush_icg_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @69 +// .external_en (1'b0), @70 +// .global_en (special_regs_clk_en), @71 +// .module_en (cp0_iu_icg_en), @72 +// .local_en (regs_flush_icg_en), @73 +// .clk_out (regs_flush_clk)); @74 + +//------------------------------------------------ +// 1. CSR Address List +// a. Machine Level Normal CSRs +// b. Machine Level CLIC CSRs +// c. T-Head Extension CSRs +//------------------------------------------------ + +// a. Machine Level CSRs +// Machine Information Registers +parameter MVENDORID = 12'hF11; +parameter MARCHID = 12'hF12; +parameter MIMPID = 12'hF13; +parameter MHARTID = 12'hF14; + +// Machine Trap Setup +parameter MSTATUS = 12'h300; +parameter MISA = 12'h301; +parameter MEDELEG = 12'h302; +parameter MIDELEG = 12'h303; +parameter MIE = 12'h304; +parameter MTVEC = 12'h305; +parameter MCNTEN = 12'h306; +parameter MTVT = 12'h307; + +// Machine Trap Handling +parameter MSCRATCH = 12'h340; +parameter MEPC = 12'h341; +parameter MCAUSE = 12'h342; +parameter MTVAL = 12'h343; +parameter MIP = 12'h344; +parameter MNXTI = 12'h345; +parameter MINTSTATUS = 12'h346; +parameter MSCRATCHCSW = 12'h348; +parameter MSCRATCHCSWL = 12'h349; +parameter MCLICBASE = 12'h350; + + +// Machine Protection and Translation +parameter PMPCFG0 = 12'h3A0; +parameter PMPCFG1 = 12'h3A1; +parameter PMPCFG2 = 12'h3A2; +parameter PMPCFG3 = 12'h3A3; +parameter PMPADDR0 = 12'h3B0; +parameter PMPADDR1 = 12'h3B1; +parameter PMPADDR2 = 12'h3B2; +parameter PMPADDR3 = 12'h3B3; +parameter PMPADDR4 = 12'h3B4; +parameter PMPADDR5 = 12'h3B5; +parameter PMPADDR6 = 12'h3B6; +parameter PMPADDR7 = 12'h3B7; +parameter PMPADDR8 = 12'h3B8; +parameter PMPADDR9 = 12'h3B9; +parameter PMPADDR10 = 12'h3BA; +parameter PMPADDR11 = 12'h3BB; +parameter PMPADDR12 = 12'h3BC; +parameter PMPADDR13 = 12'h3BD; +parameter PMPADDR14 = 12'h3BE; +parameter PMPADDR15 = 12'h3BF; + +// Performance Monitor Regs +// Machine Counter Setup +parameter MCNTINHBT = 12'h320; +parameter MHPMEVT3 = 12'h323; +parameter MHPMEVT4 = 12'h324; +parameter MHPMEVT5 = 12'h325; +parameter MHPMEVT6 = 12'h326; +parameter MHPMEVT7 = 12'h327; +parameter MHPMEVT8 = 12'h328; +parameter MHPMEVT9 = 12'h329; +parameter MHPMEVT10 = 12'h32A; +parameter MHPMEVT11 = 12'h32B; +parameter MHPMEVT12 = 12'h32C; +parameter MHPMEVT13 = 12'h32D; +parameter MHPMEVT14 = 12'h32E; +parameter MHPMEVT15 = 12'h32F; +parameter MHPMEVT16 = 12'h330; +parameter MHPMEVT17 = 12'h331; +parameter MHPMEVT18 = 12'h332; +parameter MHPMEVT19 = 12'h333; +parameter MHPMEVT20 = 12'h334; +parameter MHPMEVT21 = 12'h335; +parameter MHPMEVT22 = 12'h336; +parameter MHPMEVT23 = 12'h337; +parameter MHPMEVT24 = 12'h338; +parameter MHPMEVT25 = 12'h339; +parameter MHPMEVT26 = 12'h33A; +parameter MHPMEVT27 = 12'h33B; +parameter MHPMEVT28 = 12'h33C; +parameter MHPMEVT29 = 12'h33D; +parameter MHPMEVT30 = 12'h33E; +parameter MHPMEVT31 = 12'h33F; + +// Machine Counters/Timers +// Low +parameter MCYCLE = 12'hB00; +parameter MINSTRET = 12'hB02; +parameter MHPMCNT3 = 12'hB03; +parameter MHPMCNT4 = 12'hB04; +parameter MHPMCNT5 = 12'hB05; +parameter MHPMCNT6 = 12'hB06; +parameter MHPMCNT7 = 12'hB07; +parameter MHPMCNT8 = 12'hB08; +parameter MHPMCNT9 = 12'hB09; +parameter MHPMCNT10 = 12'hB0A; +parameter MHPMCNT11 = 12'hB0B; +parameter MHPMCNT12 = 12'hB0C; +parameter MHPMCNT13 = 12'hB0D; +parameter MHPMCNT14 = 12'hB0E; +parameter MHPMCNT15 = 12'hB0F; +parameter MHPMCNT16 = 12'hB10; +parameter MHPMCNT17 = 12'hB11; +parameter MHPMCNT18 = 12'hB12; +parameter MHPMCNT19 = 12'hB13; +parameter MHPMCNT20 = 12'hB14; +parameter MHPMCNT21 = 12'hB15; +parameter MHPMCNT22 = 12'hB16; +parameter MHPMCNT23 = 12'hB17; +parameter MHPMCNT24 = 12'hB18; +parameter MHPMCNT25 = 12'hB19; +parameter MHPMCNT26 = 12'hB1A; +parameter MHPMCNT27 = 12'hB1B; +parameter MHPMCNT28 = 12'hB1C; +parameter MHPMCNT29 = 12'hB1D; +parameter MHPMCNT30 = 12'hB1E; +parameter MHPMCNT31 = 12'hB1F; +// High +parameter MCYCLEH = 12'hB80; +parameter MINSTRETH = 12'hB82; +parameter MHPMCNT3H = 12'hB83; +parameter MHPMCNT4H = 12'hB84; +parameter MHPMCNT5H = 12'hB85; +parameter MHPMCNT6H = 12'hB86; +parameter MHPMCNT7H = 12'hB87; +parameter MHPMCNT8H = 12'hB88; +parameter MHPMCNT9H = 12'hB89; +parameter MHPMCNT10H = 12'hB8A; +parameter MHPMCNT11H = 12'hB8B; +parameter MHPMCNT12H = 12'hB8C; +parameter MHPMCNT13H = 12'hB8D; +parameter MHPMCNT14H = 12'hB8E; +parameter MHPMCNT15H = 12'hB8F; +parameter MHPMCNT16H = 12'hB90; +parameter MHPMCNT17H = 12'hB91; +parameter MHPMCNT18H = 12'hB92; +parameter MHPMCNT19H = 12'hB93; +parameter MHPMCNT20H = 12'hB94; +parameter MHPMCNT21H = 12'hB95; +parameter MHPMCNT22H = 12'hB96; +parameter MHPMCNT23H = 12'hB97; +parameter MHPMCNT24H = 12'hB98; +parameter MHPMCNT25H = 12'hB99; +parameter MHPMCNT26H = 12'hB9A; +parameter MHPMCNT27H = 12'hB9B; +parameter MHPMCNT28H = 12'hB9C; +parameter MHPMCNT29H = 12'hB9D; +parameter MHPMCNT30H = 12'hB9E; +parameter MHPMCNT31H = 12'hB9F; + +// User Counters/Timers +// Low +parameter CYCLE = 12'hC00; +parameter REG_TIME = 12'hC01; +parameter INSTRET = 12'hC02; +parameter HPMCNT3 = 12'hC03; +parameter HPMCNT4 = 12'hC04; +parameter HPMCNT5 = 12'hC05; +parameter HPMCNT6 = 12'hC06; +parameter HPMCNT7 = 12'hC07; +parameter HPMCNT8 = 12'hC08; +parameter HPMCNT9 = 12'hC09; +parameter HPMCNT10 = 12'hC0A; +parameter HPMCNT11 = 12'hC0B; +parameter HPMCNT12 = 12'hC0C; +parameter HPMCNT13 = 12'hC0D; +parameter HPMCNT14 = 12'hC0E; +parameter HPMCNT15 = 12'hC0F; +parameter HPMCNT16 = 12'hC10; +parameter HPMCNT17 = 12'hC11; +parameter HPMCNT18 = 12'hC12; +parameter HPMCNT19 = 12'hC13; +parameter HPMCNT20 = 12'hC14; +parameter HPMCNT21 = 12'hC15; +parameter HPMCNT22 = 12'hC16; +parameter HPMCNT23 = 12'hC17; +parameter HPMCNT24 = 12'hC18; +parameter HPMCNT25 = 12'hC19; +parameter HPMCNT26 = 12'hC1A; +parameter HPMCNT27 = 12'hC1B; +parameter HPMCNT28 = 12'hC1C; +parameter HPMCNT29 = 12'hC1D; +parameter HPMCNT30 = 12'hC1E; +parameter HPMCNT31 = 12'hC1F; +// High +parameter CYCLEH = 12'hC80; +parameter REG_TIMEH = 12'hC81; +parameter INSTRETH = 12'hC82; +parameter HPMCNT3H = 12'hC83; +parameter HPMCNT4H = 12'hC84; +parameter HPMCNT5H = 12'hC85; +parameter HPMCNT6H = 12'hC86; +parameter HPMCNT7H = 12'hC87; +parameter HPMCNT8H = 12'hC88; +parameter HPMCNT9H = 12'hC89; +parameter HPMCNT10H = 12'hC8A; +parameter HPMCNT11H = 12'hC8B; +parameter HPMCNT12H = 12'hC8C; +parameter HPMCNT13H = 12'hC8D; +parameter HPMCNT14H = 12'hC8E; +parameter HPMCNT15H = 12'hC8F; +parameter HPMCNT16H = 12'hC90; +parameter HPMCNT17H = 12'hC91; +parameter HPMCNT18H = 12'hC92; +parameter HPMCNT19H = 12'hC93; +parameter HPMCNT20H = 12'hC94; +parameter HPMCNT21H = 12'hC95; +parameter HPMCNT22H = 12'hC96; +parameter HPMCNT23H = 12'hC97; +parameter HPMCNT24H = 12'hC98; +parameter HPMCNT25H = 12'hC99; +parameter HPMCNT26H = 12'hC9A; +parameter HPMCNT27H = 12'hC9B; +parameter HPMCNT28H = 12'hC9C; +parameter HPMCNT29H = 12'hC9D; +parameter HPMCNT30H = 12'hC9E; +parameter HPMCNT31H = 12'hC9F; + +// User Floating-Point +parameter FFLAGS = 12'h001; +parameter FRM = 12'h002; +parameter FCSR = 12'h003; +parameter FXCR = 12'h800; // T-Head Extension + +//DSP and vector +parameter VXSAT = 12'h009; + +// c. T-Head Extension CSRs +// Processor Control and Status Extension; M-Mode +parameter MXSTATUS = 12'h7C0; +parameter MHCR = 12'h7C1; +parameter MHINT = 12'h7C5; +parameter MHINT2 = 12'h7CC; +// Processor ID Extension; M-Mode +parameter MCPUID = 12'hFC0; + +parameter MRADDR = 12'h7E0; +parameter MEXSTATUS = 12'h7E1; +parameter MNMICAUSE = 12'h7E2; +parameter MNMIPC = 12'h7E3; +//---------------------------------------------------------- +// Debug CSRs +//---------------------------------------------------------- +parameter DCSR = 12'h7B0; +parameter DPC = 12'h7B1; +parameter DSCRATCH0 = 12'h7B2; +parameter DSCRATCH1 = 12'h7B3; + +//---------------------------------------------------------- +// Trigger CSRs +//---------------------------------------------------------- +parameter TSELECT = 12'h7A0; +parameter TDATA1 = 12'h7A1; +parameter TDATA2 = 12'h7A2; +parameter TDATA3 = 12'h7A3; +parameter TINFO = 12'h7A4; +parameter TCONTROL = 12'h7A5; +parameter MCONTEXT = 12'h7A8; +parameter SCONTEXT = 12'h7AA; + +//-----------Debug Extension ----------- +parameter MHALTCAUSE = 12'hFE0; +parameter MDBGINFO = 12'hFE1; +parameter MPCFIFO = 12'hFE2; + +//------------------------------------------------ +// 2. Instance CSR Group Sub-Modules +//------------------------------------------------ + +// Machine Information & Counter Registers +// &Instance("pa_cp0_info_csr", "x_pa_cp0_info_csr"); @354 +pa_cp0_info_csr x_pa_cp0_info_csr ( + .cpurst_b (cpurst_b ), + .iui_regs_inst_csr (iui_regs_inst_csr), + .marchid_value (marchid_value ), + .mcpuid_local_en (mcpuid_local_en ), + .mcpuid_value (mcpuid_value ), + .mhartid_value (mhartid_value ), + .mimpid_value (mimpid_value ), + .mvendorid_value (mvendorid_value ), + .regs_clk (regs_clk ) +); + + +// Machine Trap Setup & Handling Registers +// &Instance("pa_cp0_trap_csr", "x_pa_cp0_trap_csr"); @357 +pa_cp0_trap_csr x_pa_cp0_trap_csr ( + .cp0_dtu_int_id (cp0_dtu_int_id ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_hpcp_pmdm (cp0_hpcp_pmdm ), + .cp0_hpcp_pmdu (cp0_hpcp_pmdu ), + .cp0_idu_fs (cp0_idu_fs ), + .cp0_idu_mcause (cp0_idu_mcause ), + .cp0_idu_mepc (cp0_idu_mepc ), + .cp0_idu_sp_use_scratch (cp0_idu_sp_use_scratch ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_idu_sp_wen (cp0_idu_sp_wen ), + .cp0_idu_sp_wen_gate (cp0_idu_sp_wen_gate ), + .cp0_lsu_mm (cp0_lsu_mm ), + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_rtu_int_level (cp0_rtu_int_level ), + .cp0_rtu_int_mode (cp0_rtu_int_mode ), + .cp0_rtu_mie (cp0_rtu_mie ), + .cp0_rtu_mnxti_vld (cp0_rtu_mnxti_vld ), + .cp0_rtu_mpil (cp0_rtu_mpil ), + .cp0_rtu_pm_bypass (cp0_rtu_pm_bypass ), + .cp0_rtu_tail_int_hv (cp0_rtu_tail_int_hv ), + .cp0_rtu_tail_int_id (cp0_rtu_tail_int_id ), + .cp0_yy_cskyisaee (cp0_yy_cskyisaee ), + .cpurst_b (cpurst_b ), + .dtu_cp0_dcsr_mprven (dtu_cp0_dcsr_mprven ), + .dtu_cp0_dcsr_prv (dtu_cp0_dcsr_prv ), + .fcsr_local_en (fcsr_local_en ), + .fflags_clk (fflags_clk ), + .fflags_local_en (fflags_local_en ), + .fpu_cp0_wb_fflags_updt (fpu_cp0_wb_fflags_updt ), + .frm_local_en (frm_local_en ), + .fs_dirty_upd (fs_dirty_upd ), + .fxcr_local_en (fxcr_local_en ), + .idu_cp0_id_tail_vld (idu_cp0_id_tail_vld ), + .idu_cp0_ipop_data (idu_cp0_ipop_data ), + .idu_cp0_mcause_wen (idu_cp0_mcause_wen ), + .idu_cp0_mepc_wen (idu_cp0_mepc_wen ), + .idu_cp0_sp_reg (idu_cp0_sp_reg ), + .idu_cp0_sp_swap_pending (idu_cp0_sp_swap_pending ), + .idu_cp0_sp_swap_req (idu_cp0_sp_swap_req ), + .idu_cp0_sp_swap_req_gate (idu_cp0_sp_swap_req_gate ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_cp0_vec_err (ifu_cp0_vec_err ), + .ifu_cp0_vec_succeed (ifu_cp0_vec_succeed ), + .iui_regs_inst_mret (iui_regs_inst_mret ), + .iui_regs_wdata (iui_regs_wdata ), + .iui_regs_wdata_mie (iui_regs_wdata_mie ), + .iui_regs_wdata_rs1 (iui_regs_wdata_rs1 ), + .mcause_local_en (mcause_local_en ), + .mcause_value (mcause_value ), + .mclicbase_value (mclicbase_value ), + .mcnten_local_en (mcnten_local_en ), + .mcnten_value (mcnten_value ), + .medeleg_value (medeleg_value ), + .mepc_local_en (mepc_local_en ), + .mepc_value (mepc_value ), + .mideleg_value (mideleg_value ), + .mie_value (mie_value ), + .mintstatus_value (mintstatus_value ), + .mip_value (mip_value ), + .misa_value (misa_value ), + .mnmicause_local_en (mnmicause_local_en ), + .mnmicause_value (mnmicause_value ), + .mnmipc_local_en (mnmipc_local_en ), + .mnmipc_value (mnmipc_value ), + .mnxti_local_en (mnxti_local_en ), + .mnxti_value (mnxti_value ), + .mscratch_local_en (mscratch_local_en ), + .mscratch_value (mscratch_value ), + .mscratchcsw_local_en (mscratchcsw_local_en ), + .mscratchcsw_value (mscratchcsw_value ), + .mscratchcswl_local_en (mscratchcswl_local_en ), + .mscratchcswl_value (mscratchcswl_value ), + .mstatus_local_en (mstatus_local_en ), + .mstatus_value (mstatus_value ), + .mtval_local_en (mtval_local_en ), + .mtval_value (mtval_value ), + .mtvec_local_en (mtvec_local_en ), + .mtvec_rslt (mtvec_rslt ), + .mtvec_value (mtvec_value ), + .mtvt_local_en (mtvt_local_en ), + .mtvt_value (mtvt_value ), + .mxstatus_local_en (mxstatus_local_en ), + .mxstatus_value (mxstatus_value ), + .regs_clk (regs_clk ), + .regs_cpu_in_int (regs_cpu_in_int ), + .regs_cpu_in_nmi (regs_cpu_in_nmi ), + .regs_flush_clk (regs_flush_clk ), + .regs_fs_off (regs_fs_off ), + .regs_iui_mie (regs_iui_mie ), + .regs_spswap_en (regs_spswap_en ), + .regs_swap_int_sp_en_gate (regs_swap_int_sp_en_gate ), + .rtu_cp0_epc (rtu_cp0_epc ), + .rtu_cp0_exit_debug (rtu_cp0_exit_debug ), + .rtu_cp0_fp_dirty_vld (rtu_cp0_fp_dirty_vld ), + .rtu_cp0_int_level (rtu_cp0_int_level ), + .rtu_cp0_mie_en (rtu_cp0_mie_en ), + .rtu_cp0_mnxti_pending_vld (rtu_cp0_mnxti_pending_vld), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_cp0_pending_int_hv (rtu_cp0_pending_int_hv ), + .rtu_cp0_pending_int_id (rtu_cp0_pending_int_id ), + .rtu_cp0_pending_int_level (rtu_cp0_pending_int_level), + .rtu_cp0_tval (rtu_cp0_tval ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ), + .trap_csr_pm (trap_csr_pm ) +); + + +// Machine Extension Registers +// &Instance("pa_cp0_ext_csr", "x_pa_cp0_ext_csr"); @360 +pa_cp0_ext_csr x_pa_cp0_ext_csr ( + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_spec_push_en (cp0_idu_spec_push_en ), + .cp0_idu_swap_sp_en (cp0_idu_swap_sp_en ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_btb_clr (cp0_ifu_btb_clr ), + .cp0_ifu_btb_en (cp0_ifu_btb_en ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr ), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_ras_en (cp0_ifu_ras_en ), + .cp0_ifu_rst_inv_done (cp0_ifu_rst_inv_done ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_lsu_dcache_en (cp0_lsu_dcache_en ), + .cp0_lsu_dcache_wa (cp0_lsu_dcache_wa ), + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_icc_addr (cp0_lsu_icc_addr ), + .cp0_lsu_icc_op (cp0_lsu_icc_op ), + .cp0_lsu_icc_req (cp0_lsu_icc_req ), + .cp0_lsu_icc_type (cp0_lsu_icc_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_expt (cp0_rtu_in_expt ), + .cp0_rtu_wfe_en (cp0_rtu_wfe_en ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cpurst_b (cpurst_b ), + .ext_inst_ifu_icc_addr (ext_inst_ifu_icc_addr ), + .ext_inst_ifu_icc_req (ext_inst_ifu_icc_req ), + .ext_inst_ifu_icc_type (ext_inst_ifu_icc_type ), + .ext_inst_ifu_inv_done (ext_inst_ifu_inv_done ), + .ext_inst_lsu_icc_addr (ext_inst_lsu_icc_addr ), + .ext_inst_lsu_icc_done (ext_inst_lsu_icc_done ), + .ext_inst_lsu_icc_op (ext_inst_lsu_icc_op ), + .ext_inst_lsu_icc_req (ext_inst_lsu_icc_req ), + .ext_inst_lsu_icc_type (ext_inst_lsu_icc_type ), + .forever_cpuclk (forever_cpuclk ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done ), + .ifu_cp0_rst_inv_req (ifu_cp0_rst_inv_req ), + .inv_sm_clk (inv_sm_clk ), + .iui_regs_inst_mret (iui_regs_inst_mret ), + .iui_regs_wdata (iui_regs_wdata ), + .iui_regs_wdata_srst (iui_regs_wdata_srst ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .mexstatus_local_en (mexstatus_local_en ), + .mexstatus_value (mexstatus_value ), + .mhcr_local_en (mhcr_local_en ), + .mhcr_value (mhcr_value ), + .mhint2_local_en (mhint2_local_en ), + .mhint2_value (mhint2_value ), + .mhint_local_en (mhint_local_en ), + .mhint_value (mhint_value ), + .mraddr_value (mraddr_value ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .regs_clk (regs_clk ), + .regs_cpu_in_int (regs_cpu_in_int ), + .regs_cpu_in_nmi (regs_cpu_in_nmi ), + .regs_flush_clk (regs_flush_clk ), + .regs_special_lpmd (regs_special_lpmd ), + .regs_spswap_en (regs_spswap_en ), + .regs_srst_srst_vld (regs_srst_srst_vld ), + .regs_srst_srstmd (regs_srst_srstmd ), + .rst_top_op_done (rst_top_op_done ), + .rtu_cp0_bus_error (rtu_cp0_bus_error ), + .rtu_cp0_lockup_clr (rtu_cp0_lockup_clr ), + .rtu_cp0_lockup_vld (rtu_cp0_lockup_vld ), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .special_dcache_clean (special_dcache_clean ), + .special_icache_inv (special_icache_inv ), + .special_icache_inv_done (special_icache_inv_done ), + .special_regs_clk_en (special_regs_clk_en ), + .special_regs_inv_sm_clk_en (special_regs_inv_sm_clk_en), + .sysio_cp0_clkratio (sysio_cp0_clkratio ), + .sysio_cp0_rst_addr (sysio_cp0_rst_addr ) +); + + +// Floating-Point Registers +// &Instance("pa_cp0_float_csr", "x_pa_cp0_float_csr"); @364 +pa_cp0_float_csr x_pa_cp0_float_csr ( + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .cp0_fpu_xx_rm (cp0_fpu_xx_rm ), + .cp0_idu_rm (cp0_idu_rm ), + .cpurst_b (cpurst_b ), + .fcsr_local_en (fcsr_local_en ), + .fcsr_value (fcsr_value ), + .fflags_clk (fflags_clk ), + .fflags_local_en (fflags_local_en ), + .fflags_value (fflags_value ), + .fpu_cp0_fflags_updt (fpu_cp0_fflags_updt ), + .fpu_cp0_wb_fflags (fpu_cp0_wb_fflags ), + .fpu_cp0_wb_fflags_updt (fpu_cp0_wb_fflags_updt), + .frm_local_en (frm_local_en ), + .frm_value (frm_value ), + .fxcr_local_en (fxcr_local_en ), + .fxcr_value (fxcr_value ), + .iui_regs_wdata (iui_regs_wdata ), + .regs_clk (regs_clk ) +); + +assign fflags_clk_en = fflags_local_en + || fcsr_local_en + || fxcr_local_en + || vxsat_local_en + || fpu_cp0_fflags_updt + || iu_cp0_wb_ov_updt + || fs_dirty_upd + || iui_regs_inst_csr; +// &Instance("gated_clk_cell", "x_fflags_clk"); @375 +gated_clk_cell x_fflags_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fflags_clk ), + .external_en (1'b0 ), + .global_en (special_regs_clk_en), + .local_en (fflags_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @376 +// .external_en (1'b0), @377 +// .global_en (special_regs_clk_en), @378 +// .module_en (cp0_iu_icg_en), @379 +// .local_en (fflags_clk_en), @380 +// .clk_out (fflags_clk)); @381 +assign vxsat_local_en = 1'b0; +assign iu_cp0_wb_ov_updt = 1'b0; + +// &Instance("gated_clk_cell", "x_fflags_clk"); @394 +// &Connect(.clk_in (forever_cpuclk), @395 +// .external_en (1'b0), @396 +// .global_en (special_regs_clk_en), @397 +// .module_en (cp0_iu_icg_en), @398 +// .local_en (fflags_clk_en), @399 +// .clk_out (fflags_clk)); @400 + + + + + +// &Instance("pa_cp0_other_csr", "x_pa_cp0_other_csr"); @411 +//------------------------------------------------ +// 3. CSR Write Port +// a. Illegal Access +// b. CSR Write decode +//------------------------------------------------ +assign regs_mach_mode = trap_csr_pm[1:0] == 2'b11; + +// a. Illegal Access +assign regs_csr_imm[11:0] = iui_regs_imm[11:0]; + +// Qualify CSR Imm Addr +// &CombBeg; @424 +always @( regs_fs_off + or mcnten_value[9:0] + or mcnten_value[31:24] + or mcnten_value[25:7] + or regs_ext_imm_inv + or rtu_yy_xx_dbgon + or regs_csr_imm[11:0] + or trap_csr_pm[1:0]) +begin + casez(regs_csr_imm[11:0]) + MVENDORID : regs_imm_inv = 1'b0; + MARCHID : regs_imm_inv = 1'b0; + MIMPID : regs_imm_inv = 1'b0; + MHARTID : regs_imm_inv = 1'b0; + + MSTATUS : regs_imm_inv = 1'b0; + MISA : regs_imm_inv = 1'b0; + MIE : regs_imm_inv = 1'b0; + MEDELEG : regs_imm_inv = 1'b0; + MIDELEG : regs_imm_inv = 1'b0; + MTVEC : regs_imm_inv = 1'b0; + MCNTEN : regs_imm_inv = 1'b0; + MTVT : regs_imm_inv = 1'b0; + + MSCRATCH : regs_imm_inv = 1'b0; + MEPC : regs_imm_inv = 1'b0; + MCAUSE : regs_imm_inv = 1'b0; + MTVAL : regs_imm_inv = 1'b0; + MIP : regs_imm_inv = 1'b0; + MNXTI : regs_imm_inv = 1'b0; + MINTSTATUS : regs_imm_inv = 1'b0; + MSCRATCHCSW : regs_imm_inv = 1'b0; + MSCRATCHCSWL : regs_imm_inv = 1'b0; + MCLICBASE : regs_imm_inv = 1'b0; + + // HPCP + MCNTINHBT : regs_imm_inv = 1'b0; + MHPMEVT3 : regs_imm_inv = 1'b0; + MHPMEVT4 : regs_imm_inv = 1'b0; + MHPMEVT5 : regs_imm_inv = 1'b0; + MHPMEVT6 : regs_imm_inv = 1'b0; + MHPMEVT7 : regs_imm_inv = 1'b0; + MHPMEVT8 : regs_imm_inv = 1'b0; + MHPMEVT9 : regs_imm_inv = 1'b0; + MHPMEVT10 : regs_imm_inv = 1'b0; + MHPMEVT11 : regs_imm_inv = 1'b0; + MHPMEVT12 : regs_imm_inv = 1'b0; + MHPMEVT13 : regs_imm_inv = 1'b0; + MHPMEVT14 : regs_imm_inv = 1'b0; + MHPMEVT15 : regs_imm_inv = 1'b0; + MHPMEVT16 : regs_imm_inv = 1'b0; + MHPMEVT17 : regs_imm_inv = 1'b0; + MHPMEVT18 : regs_imm_inv = 1'b0; + MHPMEVT19 : regs_imm_inv = 1'b0; + MHPMEVT20 : regs_imm_inv = 1'b0; + MHPMEVT21 : regs_imm_inv = 1'b0; + MHPMEVT22 : regs_imm_inv = 1'b0; + MHPMEVT23 : regs_imm_inv = 1'b0; + MHPMEVT24 : regs_imm_inv = 1'b0; + MHPMEVT25 : regs_imm_inv = 1'b0; + MHPMEVT26 : regs_imm_inv = 1'b0; + MHPMEVT27 : regs_imm_inv = 1'b0; + MHPMEVT28 : regs_imm_inv = 1'b0; + MHPMEVT29 : regs_imm_inv = 1'b0; + MHPMEVT30 : regs_imm_inv = 1'b0; + MHPMEVT31 : regs_imm_inv = 1'b0; + + MCYCLE : regs_imm_inv = 1'b0; + MINSTRET : regs_imm_inv = 1'b0; + MHPMCNT3 : regs_imm_inv = 1'b0; + MHPMCNT4 : regs_imm_inv = 1'b0; + MHPMCNT5 : regs_imm_inv = 1'b0; + MHPMCNT6 : regs_imm_inv = 1'b0; + MHPMCNT7 : regs_imm_inv = 1'b0; + MHPMCNT8 : regs_imm_inv = 1'b0; + MHPMCNT9 : regs_imm_inv = 1'b0; + MHPMCNT10 : regs_imm_inv = 1'b0; + MHPMCNT11 : regs_imm_inv = 1'b0; + MHPMCNT12 : regs_imm_inv = 1'b0; + MHPMCNT13 : regs_imm_inv = 1'b0; + MHPMCNT14 : regs_imm_inv = 1'b0; + MHPMCNT15 : regs_imm_inv = 1'b0; + MHPMCNT16 : regs_imm_inv = 1'b0; + MHPMCNT17 : regs_imm_inv = 1'b0; + MHPMCNT18 : regs_imm_inv = 1'b0; + MHPMCNT19 : regs_imm_inv = 1'b0; + MHPMCNT20 : regs_imm_inv = 1'b0; + MHPMCNT21 : regs_imm_inv = 1'b0; + MHPMCNT22 : regs_imm_inv = 1'b0; + MHPMCNT23 : regs_imm_inv = 1'b0; + MHPMCNT24 : regs_imm_inv = 1'b0; + MHPMCNT25 : regs_imm_inv = 1'b0; + MHPMCNT26 : regs_imm_inv = 1'b0; + MHPMCNT27 : regs_imm_inv = 1'b0; + MHPMCNT28 : regs_imm_inv = 1'b0; + MHPMCNT29 : regs_imm_inv = 1'b0; + MHPMCNT30 : regs_imm_inv = 1'b0; + MHPMCNT31 : regs_imm_inv = 1'b0; + + MCYCLEH : regs_imm_inv = 1'b0; + MINSTRETH : regs_imm_inv = 1'b0; + MHPMCNT3H : regs_imm_inv = 1'b0; + MHPMCNT4H : regs_imm_inv = 1'b0; + MHPMCNT5H : regs_imm_inv = 1'b0; + MHPMCNT6H : regs_imm_inv = 1'b0; + MHPMCNT7H : regs_imm_inv = 1'b0; + MHPMCNT8H : regs_imm_inv = 1'b0; + MHPMCNT9H : regs_imm_inv = 1'b0; + MHPMCNT10H : regs_imm_inv = 1'b0; + MHPMCNT11H : regs_imm_inv = 1'b0; + MHPMCNT12H : regs_imm_inv = 1'b0; + MHPMCNT13H : regs_imm_inv = 1'b0; + MHPMCNT14H : regs_imm_inv = 1'b0; + MHPMCNT15H : regs_imm_inv = 1'b0; + MHPMCNT16H : regs_imm_inv = 1'b0; + MHPMCNT17H : regs_imm_inv = 1'b0; + MHPMCNT18H : regs_imm_inv = 1'b0; + MHPMCNT19H : regs_imm_inv = 1'b0; + MHPMCNT20H : regs_imm_inv = 1'b0; + MHPMCNT21H : regs_imm_inv = 1'b0; + MHPMCNT22H : regs_imm_inv = 1'b0; + MHPMCNT23H : regs_imm_inv = 1'b0; + MHPMCNT24H : regs_imm_inv = 1'b0; + MHPMCNT25H : regs_imm_inv = 1'b0; + MHPMCNT26H : regs_imm_inv = 1'b0; + MHPMCNT27H : regs_imm_inv = 1'b0; + MHPMCNT28H : regs_imm_inv = 1'b0; + MHPMCNT29H : regs_imm_inv = 1'b0; + MHPMCNT30H : regs_imm_inv = 1'b0; + MHPMCNT31H : regs_imm_inv = 1'b0; + + CYCLE : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[0]); + REG_TIME : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[1]); + INSTRET : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[2]); + HPMCNT3 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[3]); + HPMCNT4 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[4]); + HPMCNT5 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[5]); + HPMCNT6 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[6]); + HPMCNT7 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[7]); + HPMCNT8 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[8]); + HPMCNT9 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[9]); + HPMCNT10 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[10]); + HPMCNT11 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[11]); + HPMCNT12 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[12]); + HPMCNT13 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[13]); + HPMCNT14 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[14]); + HPMCNT15 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[15]); + HPMCNT16 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[16]); + HPMCNT17 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[17]); + HPMCNT18 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[18]); + HPMCNT19 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[19]); + HPMCNT20 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[20]); + HPMCNT21 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[21]); + HPMCNT22 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[22]); + HPMCNT23 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[23]); + HPMCNT24 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[24]); + HPMCNT25 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[25]); + HPMCNT26 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[26]); + HPMCNT27 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[27]); + HPMCNT28 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[28]); + HPMCNT29 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[29]); + HPMCNT30 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[30]); + HPMCNT31 : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[31]); + + CYCLEH : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[0]); + REG_TIMEH : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[1]); + INSTRETH : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[2]); + HPMCNT3H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[3]); + HPMCNT4H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[4]); + HPMCNT5H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[5]); + HPMCNT6H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[6]); + HPMCNT7H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[7]); + HPMCNT8H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[8]); + HPMCNT9H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[9]); + HPMCNT10H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[10]); + HPMCNT11H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[11]); + HPMCNT12H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[12]); + HPMCNT13H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[13]); + HPMCNT14H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[14]); + HPMCNT15H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[15]); + HPMCNT16H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[16]); + HPMCNT17H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[17]); + HPMCNT18H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[18]); + HPMCNT19H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[19]); + HPMCNT20H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[20]); + HPMCNT21H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[21]); + HPMCNT22H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[22]); + HPMCNT23H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[23]); + HPMCNT24H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[24]); + HPMCNT25H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[25]); + HPMCNT26H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[26]); + HPMCNT27H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[27]); + HPMCNT28H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[28]); + HPMCNT29H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[29]); + HPMCNT30H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[30]); + HPMCNT31H : regs_imm_inv = !(trap_csr_pm[1:0] == 2'b11 || mcnten_value[31]); + + PMPCFG0 : regs_imm_inv = 1'b0; + PMPADDR0 : regs_imm_inv = 1'b0; + PMPADDR1 : regs_imm_inv = 1'b0; + PMPADDR2 : regs_imm_inv = 1'b0; + PMPADDR3 : regs_imm_inv = 1'b0; + PMPCFG1 : regs_imm_inv = 1'b0; + PMPADDR4 : regs_imm_inv = 1'b0; + PMPADDR5 : regs_imm_inv = 1'b0; + PMPADDR6 : regs_imm_inv = 1'b0; + PMPADDR7 : regs_imm_inv = 1'b0; + PMPCFG2 : regs_imm_inv = 1'b0; + PMPADDR8 : regs_imm_inv = 1'b0; + PMPADDR9 : regs_imm_inv = 1'b0; + PMPADDR10 : regs_imm_inv = 1'b0; + PMPADDR11 : regs_imm_inv = 1'b0; + PMPCFG3 : regs_imm_inv = 1'b0; + PMPADDR12 : regs_imm_inv = 1'b0; + PMPADDR13 : regs_imm_inv = 1'b0; + PMPADDR14 : regs_imm_inv = 1'b0; + PMPADDR15 : regs_imm_inv = 1'b0; + + FFLAGS : regs_imm_inv = regs_fs_off; + FRM : regs_imm_inv = regs_fs_off; + FCSR : regs_imm_inv = regs_fs_off; + + + +//---------------------------------------------------------- +// Debug CSRs +//---------------------------------------------------------- + DCSR, + DPC, + DSCRATCH0, + DSCRATCH1 : regs_imm_inv = !rtu_yy_xx_dbgon; + +//---------------------------------------------------------- +// Trigger CSRs +//---------------------------------------------------------- + TSELECT, + TDATA1, + TDATA2, + TDATA3, + TINFO, + TCONTROL, + MCONTEXT: regs_imm_inv = 1'b0; + +//---------------------------------------------------------- +// M-Mode Extension CSRs +//---------------------------------------------------------- +// 0x7C0-0x7FF + 12'b0111_11??_????, +// 0xBC0-0xBFF + 12'b1011_11??_????, +// 0xFC0-0xFFF + 12'b1111_11??_????: regs_imm_inv = regs_ext_imm_inv; + +//---------------------------------------------------------- +// S-Mode Extension CSRs +//---------------------------------------------------------- +// 0x5C0-0x5FF + 12'b0101_11??_????, +// 0x9C0-0x9FF + 12'b1001_11??_????, +// 0xDC0-0xDFF + 12'b1101_11??_????: regs_imm_inv = regs_ext_imm_inv; + +//---------------------------------------------------------- +// U-Mode Extension CSRs +//---------------------------------------------------------- +// 0x800-0x8FF + 12'b1000_????_????, +// 0xCC0-0xCFF + 12'b1100_11??_????: regs_imm_inv = regs_ext_imm_inv; + + + default : regs_imm_inv = 1'b1; + endcase +// &CombEnd; @703 +end + +//========================================================== +// Extension CSRs Invalid +//========================================================== +// &CombBeg; @708 +always @( regs_fs_off + or regs_csr_imm[11:0]) +begin + case(regs_csr_imm[11:0]) +//---------------------------------------------------------- +// M-Mode T-Head Extension CSRs +//---------------------------------------------------------- +// Processor Control and Status Extension + MXSTATUS : regs_ext_imm_inv = 1'b0; + MHCR : regs_ext_imm_inv = 1'b0; + MHINT : regs_ext_imm_inv = 1'b0; + MHINT2 : regs_ext_imm_inv = 1'b0; + + MRADDR : regs_ext_imm_inv = 1'b0; + MEXSTATUS : regs_ext_imm_inv = 1'b0; + MNMICAUSE : regs_ext_imm_inv = 1'b0; + MNMIPC : regs_ext_imm_inv = 1'b0; + FXCR : regs_ext_imm_inv = regs_fs_off; + MHALTCAUSE, + MDBGINFO, + MPCFIFO : regs_ext_imm_inv = 1'b0; + default : regs_ext_imm_inv = 1'b0; + endcase +// &CombEnd; @733 +end + + + + +// b. CSR Write decode +assign regs_csr_wen = iui_regs_csr_wen; + +assign mcpuid_local_en = regs_csr_imm[11:0] == MCPUID; + +assign mstatus_local_en = regs_csr_wen && regs_csr_imm[11:0] == MSTATUS; +assign mtvec_local_en = regs_csr_wen && regs_csr_imm[11:0] == MTVEC; +assign mcnten_local_en = regs_csr_wen && regs_csr_imm[11:0] == MCNTEN; +assign mtvt_local_en = regs_csr_wen && regs_csr_imm[11:0] == MTVT; + +assign mscratch_local_en = regs_csr_wen && regs_csr_imm[11:0] == MSCRATCH; +assign mepc_local_en = regs_csr_wen && regs_csr_imm[11:0] == MEPC; +assign mcause_local_en = regs_csr_wen && regs_csr_imm[11:0] == MCAUSE; +assign mtval_local_en = regs_csr_wen && regs_csr_imm[11:0] == MTVAL; +assign mnxti_local_en = regs_csr_wen && regs_csr_imm[11:0] == MNXTI + && iui_regs_csr_mnxti_vld; +assign regs_iui_mnxti_sel = regs_csr_wen && regs_csr_imm[11:0] == MNXTI; +assign mscratchcsw_local_en = regs_csr_wen && regs_csr_imm[11:0] == MSCRATCHCSW; +assign mscratchcswl_local_en = regs_csr_wen && regs_csr_imm[11:0] == MSCRATCHCSWL; + +assign fflags_local_en = regs_csr_wen && regs_csr_imm[11:0] == FFLAGS; +assign frm_local_en = regs_csr_wen && regs_csr_imm[11:0] == FRM; +assign fcsr_local_en = regs_csr_wen && regs_csr_imm[11:0] == FCSR; +assign fxcr_local_en = regs_csr_wen && regs_csr_imm[11:0] == FXCR; + + +assign mxstatus_local_en = regs_csr_wen && regs_csr_imm[11:0] == MXSTATUS; +assign mhcr_local_en = regs_csr_wen && regs_csr_imm[11:0] == MHCR; +assign mhint_local_en = regs_csr_wen && regs_csr_imm[11:0] == MHINT; +assign mhint2_local_en = regs_csr_wen && regs_csr_imm[11:0] == MHINT2; + +assign mexstatus_local_en = regs_csr_wen && regs_csr_imm[11:0] == MEXSTATUS; +assign mnmicause_local_en = regs_csr_wen && regs_csr_imm[11:0] == MNMICAUSE; +assign mnmipc_local_en = regs_csr_wen && regs_csr_imm[11:0] == MNMIPC; + +//------------------------------------------------ +// 4. CSR Read Port +//------------------------------------------------ + +// &CombBeg; @790 +always @( mnmicause_value[31:0] + or mtval_value[31:0] + or dtu_cp0_rdata[31:0] + or mstatus_value[31:0] + or mhcr_value[31:0] + or mideleg_value[31:0] + or mraddr_value[31:0] + or mscratch_value[31:0] + or mip_value[31:0] + or mcause_value[31:0] + or mcnten_value[31:0] + or mscratchcswl_value[31:0] + or pmp_cp0_data[31:0] + or marchid_value[31:0] + or mepc_value[31:0] + or mexstatus_value[31:0] + or medeleg_value[31:0] + or mscratchcsw_value[31:0] + or mtvec_value[31:0] + or mnmipc_value[31:0] + or hpcp_cp0_data[31:0] + or misa_value[31:0] + or mhartid_value[31:0] + or mie_value[31:0] + or regs_csr_imm[11:0] + or mhint_value[31:0] + or mcpuid_value[31:0] + or mhint2_value[31:0] + or mimpid_value[31:0] + or fxcr_value[31:0] + or fflags_value[31:0] + or mintstatus_value[31:0] + or mtvt_value[31:0] + or mvendorid_value[31:0] + or mnxti_value[31:0] + or frm_value[31:0] + or mxstatus_value[31:0] + or mclicbase_value[31:0] + or fcsr_value[31:0]) +begin + case(regs_csr_imm[11:0]) + MVENDORID : regs_csr_rdata[31:0] = mvendorid_value[31:0]; + MARCHID : regs_csr_rdata[31:0] = marchid_value[31:0]; + MIMPID : regs_csr_rdata[31:0] = mimpid_value[31:0]; + MHARTID : regs_csr_rdata[31:0] = mhartid_value[31:0]; + + MCPUID : regs_csr_rdata[31:0] = mcpuid_value[31:0]; + + MSTATUS : regs_csr_rdata[31:0] = mstatus_value[31:0]; + MISA : regs_csr_rdata[31:0] = misa_value[31:0]; + MEDELEG : regs_csr_rdata[31:0] = medeleg_value[31:0]; + MIDELEG : regs_csr_rdata[31:0] = mideleg_value[31:0]; + MIE : regs_csr_rdata[31:0] = mie_value[31:0]; + MTVEC : regs_csr_rdata[31:0] = mtvec_value[31:0]; + MCNTEN : regs_csr_rdata[31:0] = mcnten_value[31:0]; + MTVT : regs_csr_rdata[31:0] = mtvt_value[31:0]; + + MSCRATCH : regs_csr_rdata[31:0] = mscratch_value[31:0]; + MEPC : regs_csr_rdata[31:0] = mepc_value[31:0]; + MCAUSE : regs_csr_rdata[31:0] = mcause_value[31:0]; + MTVAL : regs_csr_rdata[31:0] = mtval_value[31:0]; + MIP : regs_csr_rdata[31:0] = mip_value[31:0]; + MNXTI : regs_csr_rdata[31:0] = mnxti_value[31:0]; + MINTSTATUS : regs_csr_rdata[31:0] = mintstatus_value[31:0]; + MSCRATCHCSW : regs_csr_rdata[31:0] = mscratchcsw_value[31:0]; + MSCRATCHCSWL : regs_csr_rdata[31:0] = mscratchcswl_value[31:0]; + MCLICBASE : regs_csr_rdata[31:0] = mclicbase_value[31:0]; + + // HPCP + MCNTINHBT, + MHPMEVT3, + MHPMEVT4, + MHPMEVT5, + MHPMEVT6, + MHPMEVT7, + MHPMEVT8, + MHPMEVT9, + MHPMEVT10, + MHPMEVT11, + MHPMEVT12, + MHPMEVT13, + MHPMEVT14, + MHPMEVT15, + MHPMEVT16, + MHPMEVT17, + MHPMEVT18, + MHPMEVT19, + MHPMEVT20, + MHPMEVT21, + MHPMEVT22, + MHPMEVT23, + MHPMEVT24, + MHPMEVT25, + MHPMEVT26, + MHPMEVT27, + MHPMEVT28, + MHPMEVT29, + MHPMEVT30, + MHPMEVT31, + MCYCLE, + MINSTRET, + MHPMCNT3, + MHPMCNT4, + MHPMCNT5, + MHPMCNT6, + MHPMCNT7, + MHPMCNT8, + MHPMCNT9, + MHPMCNT10, + MHPMCNT11, + MHPMCNT12, + MHPMCNT13, + MHPMCNT14, + MHPMCNT15, + MHPMCNT16, + MHPMCNT17, + MHPMCNT18, + MHPMCNT19, + MHPMCNT20, + MHPMCNT21, + MHPMCNT22, + MHPMCNT23, + MHPMCNT24, + MHPMCNT25, + MHPMCNT26, + MHPMCNT27, + MHPMCNT28, + MHPMCNT29, + MHPMCNT30, + MHPMCNT31, + MCYCLEH, + MINSTRETH, + MHPMCNT3H, + MHPMCNT4H, + MHPMCNT5H, + MHPMCNT6H, + MHPMCNT7H, + MHPMCNT8H, + MHPMCNT9H, + MHPMCNT10H, + MHPMCNT11H, + MHPMCNT12H, + MHPMCNT13H, + MHPMCNT14H, + MHPMCNT15H, + MHPMCNT16H, + MHPMCNT17H, + MHPMCNT18H, + MHPMCNT19H, + MHPMCNT20H, + MHPMCNT21H, + MHPMCNT22H, + MHPMCNT23H, + MHPMCNT24H, + MHPMCNT25H, + MHPMCNT26H, + MHPMCNT27H, + MHPMCNT28H, + MHPMCNT29H, + MHPMCNT30H, + MHPMCNT31H, + CYCLE, + REG_TIME, + INSTRET, + HPMCNT3, + HPMCNT4, + HPMCNT5, + HPMCNT6, + HPMCNT7, + HPMCNT8, + HPMCNT9, + HPMCNT10, + HPMCNT11, + HPMCNT12, + HPMCNT13, + HPMCNT14, + HPMCNT15, + HPMCNT16, + HPMCNT17, + HPMCNT18, + HPMCNT19, + HPMCNT20, + HPMCNT21, + HPMCNT22, + HPMCNT23, + HPMCNT24, + HPMCNT25, + HPMCNT26, + HPMCNT27, + HPMCNT28, + HPMCNT29, + HPMCNT30, + HPMCNT31, + CYCLEH, + REG_TIMEH, + INSTRETH, + HPMCNT3H, + HPMCNT4H, + HPMCNT5H, + HPMCNT6H, + HPMCNT7H, + HPMCNT8H, + HPMCNT9H, + HPMCNT10H, + HPMCNT11H, + HPMCNT12H, + HPMCNT13H, + HPMCNT14H, + HPMCNT15H, + HPMCNT16H, + HPMCNT17H, + HPMCNT18H, + HPMCNT19H, + HPMCNT20H, + HPMCNT21H, + HPMCNT22H, + HPMCNT23H, + HPMCNT24H, + HPMCNT25H, + HPMCNT26H, + HPMCNT27H, + HPMCNT28H, + HPMCNT29H, + HPMCNT30H, + HPMCNT31H: regs_csr_rdata[31:0] = hpcp_cp0_data[31:0]; + + MXSTATUS : regs_csr_rdata[31:0] = mxstatus_value[31:0]; + MHCR : regs_csr_rdata[31:0] = mhcr_value[31:0]; + MHINT : regs_csr_rdata[31:0] = mhint_value[31:0]; + MHINT2 : regs_csr_rdata[31:0] = mhint2_value[31:0]; + + MRADDR : regs_csr_rdata[31:0] = mraddr_value[31:0]; + MEXSTATUS : regs_csr_rdata[31:0] = mexstatus_value[31:0]; + MNMICAUSE : regs_csr_rdata[31:0] = mnmicause_value[31:0]; + MNMIPC : regs_csr_rdata[31:0] = mnmipc_value[31:0]; + + PMPCFG0 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPCFG1 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPCFG2 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPCFG3 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR0 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR1 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR2 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR3 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR4 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR5 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR6 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR7 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR8 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR9 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR10 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR11 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR12 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR13 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR14 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + PMPADDR15 : regs_csr_rdata[31:0] = pmp_cp0_data[31:0]; + + FFLAGS : regs_csr_rdata[31:0] = fflags_value[31:0]; + FRM : regs_csr_rdata[31:0] = frm_value[31:0]; + FCSR : regs_csr_rdata[31:0] = fcsr_value[31:0]; + FXCR : regs_csr_rdata[31:0] = fxcr_value[31:0]; + +//---------------------------------------------------------- +// Debug CSRs +//---------------------------------------------------------- + DCSR, + DPC, + DSCRATCH0, + DSCRATCH1 : regs_csr_rdata[31:0] = dtu_cp0_rdata[31:0]; +//---------------------------------------------------------- +// Trigger CSRs +//---------------------------------------------------------- + TSELECT, + TDATA1, + TDATA2, + TDATA3, + TINFO, + TCONTROL, + MCONTEXT : regs_csr_rdata[31:0] = dtu_cp0_rdata[31:0]; +//------------Debug Extension----------- + MHALTCAUSE, + MDBGINFO, + MPCFIFO : regs_csr_rdata[31:0] = dtu_cp0_rdata[31:0]; + //MTVT : regs_csr_rdata[31:0] = mtvt_value[31:0]; + //MNXTI : regs_csr_rdata[31:0] = mnxti_value[31:0]; + //MINTSTATUS: regs_csr_rdata[31:0] = mintstatus_value[31:0]; + default : regs_csr_rdata[31:0] = 32'b0; + endcase +// &CombEnd; @1050 +end + +//========================================================== +// Rename for Output +//========================================================== + +// Output to IUI +assign regs_iui_expt_vld = regs_imm_inv; +assign regs_iui_rdata[31:0] = regs_csr_rdata[31:0]; +assign regs_iui_mepc[31:0] = mepc_value[31:0]; +assign regs_iui_pm[1:0] = trap_csr_pm[1:0]; +assign regs_iui_mstatus[31:0] = mstatus_value[31:0]; + +// Output to IFU +assign cp0_ifu_mtvec[31:0] = {mtvec_rslt[29:0], 2'b0}; + +// Output to PMP +// Todo +assign cp0_pmp_csr_sel[0] = regs_csr_imm[11:0] == PMPCFG0; +assign cp0_pmp_csr_sel[1] = regs_csr_imm[11:0] == PMPCFG1; +assign cp0_pmp_csr_sel[2] = regs_csr_imm[11:0] == PMPCFG2; +assign cp0_pmp_csr_sel[3] = regs_csr_imm[11:0] == PMPCFG3; +assign cp0_pmp_csr_sel[4] = regs_csr_imm[11:0] == PMPADDR0; +assign cp0_pmp_csr_sel[5] = regs_csr_imm[11:0] == PMPADDR1; +assign cp0_pmp_csr_sel[6] = regs_csr_imm[11:0] == PMPADDR2; +assign cp0_pmp_csr_sel[7] = regs_csr_imm[11:0] == PMPADDR3; +assign cp0_pmp_csr_sel[8] = regs_csr_imm[11:0] == PMPADDR4; +assign cp0_pmp_csr_sel[9] = regs_csr_imm[11:0] == PMPADDR5; +assign cp0_pmp_csr_sel[10] = regs_csr_imm[11:0] == PMPADDR6; +assign cp0_pmp_csr_sel[11] = regs_csr_imm[11:0] == PMPADDR7; +assign cp0_pmp_csr_sel[12] = regs_csr_imm[11:0] == PMPADDR8; +assign cp0_pmp_csr_sel[13] = regs_csr_imm[11:0] == PMPADDR9; +assign cp0_pmp_csr_sel[14] = regs_csr_imm[11:0] == PMPADDR10; +assign cp0_pmp_csr_sel[15] = regs_csr_imm[11:0] == PMPADDR11; +assign cp0_pmp_csr_sel[16] = regs_csr_imm[11:0] == PMPADDR12; +assign cp0_pmp_csr_sel[17] = regs_csr_imm[11:0] == PMPADDR13; +assign cp0_pmp_csr_sel[18] = regs_csr_imm[11:0] == PMPADDR14; +assign cp0_pmp_csr_sel[19] = regs_csr_imm[11:0] == PMPADDR15; +assign cp0_pmp_csr_wen = regs_csr_wen; +assign cp0_pmp_updt_data[31:0] = iui_regs_wdata[31:0]; + +//========================================================== +// Output to HPCP +//========================================================== +assign cp0_hpcp_index[11:0] = regs_csr_imm[11:0]; +assign cp0_hpcp_wdata[31:0] = iui_regs_wdata[31:0]; +assign cp0_hpcp_wreg = regs_csr_wen; + +// Output to HAD +// //&Force("input", "had_cp0_mcause_data"); @1101 +// //&Force("bus", "had_cp0_mcause_data", 31, 0); @1102 +//assign cp0_had_mcause_data[31:0] = mcause_value[31:0]; +//assign cp0_had_cpuid_idx0[31:0] = info_csr_cpuid0_value[31:0]; + +// Todo +assign cp0_yy_priv_mode[1:0] = trap_csr_pm[1:0]; +assign cp0_yy_mach_mode = regs_mach_mode; +assign cp0_pad_mintstatus[31:0] = mintstatus_value[31:0]; +assign cp0_pad_mstatus[31:0] = mstatus_value[31:0]; +assign cp0_pad_mcause[31:0] = mcause_value[31:0]; + +// &Force("input","dtu_cp0_rdata"); @1117 +// &Force("bus","dtu_cp0_rdata",31,0); @1118 +// &ModuleEnd; @1120 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_special.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_special.v new file mode 100644 index 0000000000000000000000000000000000000000..34471eaf7452a88c8c5336d8e2218101444ad2c6 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_special.v @@ -0,0 +1,438 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_special( + cp0_ifu_in_lpmd, + cp0_ifu_lpmd_req, + cp0_lsu_fence_req, + cp0_lsu_sync_req, + cp0_sysio_ipend_b, + cp0_sysio_lpmd_b, + cp0_yy_clk_en, + cpurst_b, + dtu_cp0_wake_up, + fence_top_cur_state, + forever_cpuclk, + ifu_cp0_lpmd_ack, + inv_sm_clk, + iui_special_ecall, + iui_special_fence, + iui_special_fencei, + iui_special_int_vld, + iui_special_sync, + iui_special_synci, + iui_special_wfi, + lpmd_top_cur_state, + lsu_cp0_fence_ack, + lsu_cp0_icc_done, + lsu_cp0_sync_ack, + pad_yy_icg_scan_en, + regs_special_lpmd, + rtu_yy_xx_dbgon, + rtu_yy_xx_flush, + special_dcache_clean, + special_icache_inv, + special_icache_inv_done, + special_iui_expt_vld, + special_iui_stall, + special_regs_clk_en, + special_regs_inv_sm_clk_en, + srst_in_wait_state, + srst_sm_clk, + srst_special_srst_sm_clk_en +); + +// &Ports; @24 +input cpurst_b; +input dtu_cp0_wake_up; +input forever_cpuclk; +input ifu_cp0_lpmd_ack; +input inv_sm_clk; +input iui_special_ecall; +input iui_special_fence; +input iui_special_fencei; +input iui_special_int_vld; +input iui_special_sync; +input iui_special_synci; +input iui_special_wfi; +input lsu_cp0_fence_ack; +input lsu_cp0_icc_done; +input lsu_cp0_sync_ack; +input pad_yy_icg_scan_en; +input [1:0] regs_special_lpmd; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_flush; +input special_icache_inv_done; +input srst_in_wait_state; +input srst_special_srst_sm_clk_en; +output cp0_ifu_in_lpmd; +output cp0_ifu_lpmd_req; +output cp0_lsu_fence_req; +output cp0_lsu_sync_req; +output cp0_sysio_ipend_b; +output [1:0] cp0_sysio_lpmd_b; +output cp0_yy_clk_en; +output [2:0] fence_top_cur_state; +output [1:0] lpmd_top_cur_state; +output special_dcache_clean; +output special_icache_inv; +output special_iui_expt_vld; +output special_iui_stall; +output special_regs_clk_en; +output special_regs_inv_sm_clk_en; +output srst_sm_clk; + +// &Regs; @25 +reg [1:0] cur_state; +reg [1:0] lpmd_b; +reg [1:0] next_state; +reg [2:0] spec_cur_state; +reg [2:0] spec_nxt_state; + +// &Wires; @26 +wire cp0_ifu_in_lpmd; +wire cp0_ifu_lpmd_req; +wire cp0_lsu_fence_req; +wire cp0_lsu_sync_req; +wire cp0_sysio_ipend_b; +wire [1:0] cp0_sysio_lpmd_b; +wire cp0_yy_clk_en; +wire cpu_in_lpmd; +wire cpu_in_lpmd_core_view; +wire cpurst_b; +wire dtu_cp0_wake_up; +wire fence_lsu_cmplt; +wire [2:0] fence_top_cur_state; +wire forever_cpuclk; +wire ifu_cp0_lpmd_ack; +wire inv_sm_clk; +wire iui_special_ecall; +wire iui_special_fence; +wire iui_special_fencei; +wire iui_special_int_vld; +wire iui_special_sync; +wire iui_special_synci; +wire iui_special_wfi; +wire lpmd_ack; +wire lpmd_clk; +wire lpmd_clk_en; +wire lpmd_in_wait_state; +wire lpmd_sm_clk; +wire lpmd_sm_icg_en; +wire lpmd_stall; +wire lpmd_start; +wire [1:0] lpmd_top_cur_state; +wire lsu_cp0_fence_ack; +wire lsu_cp0_icc_done; +wire lsu_cp0_sync_ack; +wire pad_yy_icg_scan_en; +wire [1:0] regs_special_lpmd; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_flush; +wire spcial_fence_sync; +wire spec_inst_vld; +wire special_dcache_clean; +wire special_fence_req; +wire special_icache_inv; +wire special_icache_inv_done; +wire special_iui_expt_vld; +wire special_iui_stall; +wire special_regs_clk_en; +wire special_regs_inv_sm_clk_en; +wire special_sm_stall; +wire srst_in_wait_state; +wire srst_sm_clk; +wire srst_special_srst_sm_clk_en; +wire sync_lsu_cmplt; + + + + +//========================================================== +// Special Inst Module +// 1. Instance ICG cell +// 2. Low Power Mode Maintainment +// 3. Other Special Inst Execution +//========================================================== + +parameter IDLE = 2'b00; +parameter WFACK = 2'b01; +parameter WFCPLT = 2'b11; +parameter CPLT = 2'b10; +//------------------------------------------------ +// 1. Instance ICG cell +//------------------------------------------------ +assign lpmd_sm_icg_en = iui_special_wfi || (cur_state[1:0] != IDLE) + || srst_special_srst_sm_clk_en; +// &Instance("gated_clk_cell", "x_lpmd_sm_gated_clk"); @46 +gated_clk_cell x_lpmd_sm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lpmd_sm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (1'b0 ), + .module_en (lpmd_sm_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @47 +// .external_en (1'b0), @48 +// .global_en (1'b1), @49 +// .module_en (lpmd_sm_icg_en), @50 +// .local_en (1'b0), @51 +// .clk_out (lpmd_sm_clk)); @52 + +assign srst_sm_clk = lpmd_sm_clk; + +assign lpmd_clk_en = dtu_cp0_wake_up || iui_special_int_vld + || rtu_yy_xx_dbgon || lpmd_start; + +// &Instance("gated_clk_cell", "x_lpmd_gated_clk"); @59 +gated_clk_cell x_lpmd_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lpmd_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (1'b0 ), + .module_en (lpmd_clk_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @60 +// .external_en (1'b0), @61 +// .global_en (1'b1), @62 +// .module_en (lpmd_clk_en), @63 +// .local_en (1'b0), @64 +// .clk_out (lpmd_clk)); @65 + +//------------------------------------------------ +// 2. Low Power Mode Maintainment +//------------------------------------------------ +//----------------------------------------------------- +// Request the BIU to enter low power mode and do +// not accept any more transaction from IFU or LSU +//----------------------------------------------------- +//-------------------FSM of lpmd req logic----------------- +// State Description: +// IDLE : no lpmd instruction (wait,stop,doze) +// WFACK : request sysio and wait for sysio ack +// the lpmd request +//----------------------------------------------------- + +always @(posedge lpmd_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + cur_state[1:0] <= IDLE; + else if(rtu_yy_xx_flush) + cur_state[1:0] <= IDLE; + else + cur_state[1:0] <= next_state[1:0]; +end +// &CombBeg; @90 +always @( cur_state[1:0] + or lpmd_start + or iui_special_wfi + or cpu_in_lpmd) +begin + case(cur_state[1:0]) + IDLE : if(iui_special_wfi) + next_state[1:0] = WFACK; + else + next_state[1:0] = IDLE; + WFACK : if(lpmd_start) + next_state[1:0] = WFCPLT; + else + next_state[1:0] = WFACK; + WFCPLT : if(!cpu_in_lpmd) + next_state[1:0] = CPLT; + else + next_state[1:0] = WFCPLT; + CPLT : next_state[1:0] = IDLE; + default : next_state[1:0] = IDLE; + endcase +// &CombEnd; @107 +end + +assign lpmd_in_wait_state = (cur_state[1:0] == WFACK); + +//-------------------control signal by lpmd FSM------------- +assign lpmd_stall = (cur_state[1:0] == IDLE) && iui_special_wfi + || (cur_state[1:0] == WFACK) + || (cur_state[1:0] == WFCPLT); +//----------------------------------------------------- +// lpmd request ack +//----------------------------------------------------- +assign lpmd_ack = ifu_cp0_lpmd_ack & lsu_cp0_sync_ack; +assign lpmd_start = lpmd_ack; + +//----------------------------------------------------- +// Send lpmd bits to BIU and HAD, when +// cp0 can enter low power mode (get sysio_cp0_no_op) +//----------------------------------------------------- +always @(posedge lpmd_clk or negedge cpurst_b) +begin + if(!cpurst_b) + lpmd_b[1:0] <= 2'b11; + else if((dtu_cp0_wake_up || iui_special_int_vld)&& cpu_in_lpmd + || rtu_yy_xx_dbgon) + lpmd_b[1:0] <= 2'b11; + else if(lpmd_start && !cpu_in_lpmd) + begin + lpmd_b[1:0] <= regs_special_lpmd[1:0]; + end + else + lpmd_b[1:0] <= lpmd_b[1:0]; +end + +//the cpu condsider both pm bit in cp0(cpu view) and sysio(soc view) +//assign sys_lpmd_b[1:0] = sysio_cp0_sys_view_lpmd_b[1:0]; +//assign cpu_in_lpmd_sys_view = !(sys_lpmd_b[1] & sys_lpmd_b[0]); +assign cpu_in_lpmd_core_view = !(lpmd_b[1] & lpmd_b[0]); +assign cpu_in_lpmd = cpu_in_lpmd_core_view; + +//------------------------------------------------ +// 3. Other Special Inst Execution +//------------------------------------------------ +// FENCE, FENCE.I, SYNC, SYNC.I state machine. +assign spec_inst_vld = iui_special_fence + || iui_special_fencei + || iui_special_sync + || iui_special_synci; + +parameter SPEC_IDLE = 3'b000, + SPEC_FENC = 3'b001, + SPEC_CDCA = 3'b010, + SPEC_IICA = 3'b011, + SPEC_CMPLT= 3'b100; + +always @ (posedge inv_sm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + spec_cur_state[2:0] <= SPEC_IDLE; + else + spec_cur_state[2:0] <= spec_nxt_state[2:0]; +end + +assign fence_lsu_cmplt = lsu_cp0_fence_ack & iui_special_fence; +assign sync_lsu_cmplt = lsu_cp0_sync_ack & (iui_special_sync | iui_special_synci); +assign spcial_fence_sync = iui_special_fence || iui_special_sync || iui_special_synci; +// &CombBeg; @172 +always @( iui_special_fencei + or sync_lsu_cmplt + or spec_cur_state + or spcial_fence_sync + or fence_lsu_cmplt + or lsu_cp0_icc_done + or special_icache_inv_done) +begin + case(spec_cur_state) + SPEC_IDLE: + if (iui_special_fencei) + spec_nxt_state[2:0] = SPEC_CDCA; + else if(spcial_fence_sync) + spec_nxt_state[2:0] = SPEC_FENC; + else + spec_nxt_state[2:0] = SPEC_IDLE; + SPEC_FENC: + if(spcial_fence_sync) + if(sync_lsu_cmplt || fence_lsu_cmplt) + spec_nxt_state[2:0] = SPEC_CMPLT; + else + spec_nxt_state[2:0] = SPEC_FENC; + else + spec_nxt_state[2:0] = SPEC_CMPLT; + SPEC_CDCA: + if (iui_special_fencei) + if (lsu_cp0_icc_done) + spec_nxt_state[2:0] = SPEC_IICA; + else + spec_nxt_state[2:0] = SPEC_CDCA; + else + spec_nxt_state[2:0] = SPEC_CMPLT; + SPEC_IICA: + if (iui_special_fencei) + if (special_icache_inv_done) + spec_nxt_state[2:0] = SPEC_CMPLT; + else + spec_nxt_state[2:0] = SPEC_IICA; + else + spec_nxt_state[2:0] = SPEC_CMPLT; + SPEC_CMPLT: + spec_nxt_state[2:0] = SPEC_IDLE; + default: + spec_nxt_state[2:0] = SPEC_IDLE; + endcase +// &CombEnd; @210 +end + +assign special_fence_req = spec_cur_state[2:0] == SPEC_FENC; +assign special_dcache_clean = spec_cur_state[2:0] == SPEC_CDCA; +assign special_icache_inv = spec_cur_state[2:0] == SPEC_IICA; + +//assign special_fence_done = spec_cur_state[1:0] == SPEC_FENC && lsu_xx_no_op; +//assign special_fencei_done = spec_cur_state[1:0] == SPEC_IICA && special_icache_inv_done; +//assign special_sync_done = spec_cur_state[1:0] == SPEC_FENC && lsu_xx_no_op; +//assign special_synci_done = spec_cur_state[1:0] == SPEC_FENC && lsu_xx_no_op; +// &Force("output","special_dcache_clean"); @220 +// &Force("output","special_icache_inv"); @221 +assign special_sm_stall = spec_cur_state[2:0] == SPEC_IDLE && spec_inst_vld + || special_fence_req + || special_dcache_clean + || special_icache_inv; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to IUI +assign special_iui_expt_vld = iui_special_ecall; +assign special_iui_stall = lpmd_stall + || special_sm_stall; +assign special_regs_clk_en = !cpu_in_lpmd; +assign special_regs_inv_sm_clk_en = spec_cur_state[2:0] != SPEC_IDLE + || spec_inst_vld; + +// Output to IFU +assign cp0_ifu_lpmd_req = lpmd_in_wait_state; +assign cp0_ifu_in_lpmd = cpu_in_lpmd; + +// Output to LSU +assign cp0_lsu_fence_req = special_fence_req && (iui_special_fence); +assign cp0_lsu_sync_req = lpmd_in_wait_state || // low power req + srst_in_wait_state || // srst req + special_fence_req && (iui_special_sync || iui_special_synci); + +// Output to RTU +//assign cp0_rtu_ex1_inst_ebreak = iui_special_ebrek; + +// Output to HAD +//assign cp0_had_lpmd_b[1:0] = lpmd_b[1:0]; + +// Output to SYSIO +assign cp0_sysio_lpmd_b[1:0] = lpmd_b[1:0]; +assign cp0_sysio_ipend_b = !iui_special_int_vld; + +// Output to Global Clock Enable +assign cp0_yy_clk_en = !cpu_in_lpmd; + +//debug infor +assign lpmd_top_cur_state[1:0] = cur_state[1:0]; +assign fence_top_cur_state[2:0] = spec_cur_state[2:0]; + +// &ModuleEnd; @274 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_srst.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_srst.v new file mode 100644 index 0000000000000000000000000000000000000000..fb5db7c2cda4556d9ba7bafb79fd76d47f1910b8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_srst.v @@ -0,0 +1,159 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_srst( + cp0_ifu_srst_mask, + cp0_ifu_srst_req, + cp0_sysio_srst, + cpurst_b, + ifu_cp0_srst_ack, + lsu_cp0_sync_ack, + regs_srst_srst_vld, + regs_srst_srstmd, + rtu_yy_xx_dbgon, + rtu_yy_xx_flush, + srst_in_wait_state, + srst_iui_stall, + srst_sm_clk, + srst_special_srst_sm_clk_en, + sysio_cp0_clk_en +); + +// &Ports; @24 +input cpurst_b; +input ifu_cp0_srst_ack; +input lsu_cp0_sync_ack; +input regs_srst_srst_vld; +input [1:0] regs_srst_srstmd; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_flush; +input srst_sm_clk; +input sysio_cp0_clk_en; +output cp0_ifu_srst_mask; +output cp0_ifu_srst_req; +output [1:0] cp0_sysio_srst; +output srst_in_wait_state; +output srst_iui_stall; +output srst_special_srst_sm_clk_en; + +// &Regs; @25 +reg [1:0] cur_state; +reg [1:0] next_state; + +// &Wires; @26 +wire cp0_ifu_srst_mask; +wire cp0_ifu_srst_req; +wire [1:0] cp0_sysio_srst; +wire cpurst_b; +wire ifu_cp0_srst_ack; +wire lsu_cp0_sync_ack; +wire regs_srst_srst_vld; +wire [1:0] regs_srst_srstmd; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_flush; +wire srst_ack; +wire srst_cmplt; +wire srst_in_wait_state; +wire srst_iui_stall; +wire srst_sm_clk; +wire srst_sm_clk_en; +wire srst_special_srst_sm_clk_en; +wire sysio_cp0_clk_en; + + +parameter IDLE = 2'b00; +parameter WFACK = 2'b01; +parameter WFCPLT = 2'b10; +parameter WFRST = 2'b11; + +//========================================================== +// Instance of Gated Cell +//========================================================== +assign srst_sm_clk_en = regs_srst_srst_vld || (cur_state[1:0] != IDLE); + +//----------------------------------------------------- +// Request the BIU to enter low power mode and do +// not accept any more transaction from IFU or LSU +//----------------------------------------------------- + +//-------------------FSM of srst req logic----------------- +// State Description: +// IDLE : no srst instruction (wait,stop,doze) +// WFACK : request sysio and wait for sysio ack +// the srst request +//----------------------------------------------------- + +always @(posedge srst_sm_clk or negedge cpurst_b) +begin + if(!cpurst_b) + cur_state[1:0] <= IDLE; + else if(rtu_yy_xx_flush) + cur_state[1:0] <= IDLE; + else + cur_state[1:0] <= next_state[1:0]; +end + +// &CombBeg; @60 +always @( cur_state[1:0] + or regs_srst_srst_vld + or sysio_cp0_clk_en + or srst_ack) +begin + case(cur_state[1:0]) + IDLE : if(regs_srst_srst_vld) + next_state[1:0] = WFACK; + else + next_state[1:0] = IDLE; + WFACK : if(srst_ack) + next_state[1:0] = WFCPLT; + else + next_state[1:0] = WFACK; + WFCPLT : if(sysio_cp0_clk_en) + next_state[1:0] = WFRST; + else + next_state[1:0] = WFCPLT; + WFRST : next_state[1:0] = WFRST; + default: next_state[1:0] = IDLE; + endcase +// &CombEnd; @77 +end + +assign srst_in_wait_state = (cur_state[1:0] == WFACK); +assign srst_cmplt = (cur_state[1:0] == WFCPLT); + + +//-------------------control signal by srst FSM------------- +assign srst_iui_stall = (cur_state[1:0] == IDLE) && regs_srst_srst_vld + || (cur_state[1:0] != IDLE); + +assign cp0_ifu_srst_req = srst_in_wait_state; +// assign cp0_cache_srst_req = srst_in_wait_state; +// &Force("output","srst_in_wait_state"); @94 +//----------------------------------------------------- +// srst request ack +//----------------------------------------------------- +assign srst_ack = (ifu_cp0_srst_ack && lsu_cp0_sync_ack) + || rtu_yy_xx_dbgon; +assign cp0_sysio_srst[1:0] = {2{srst_cmplt && sysio_cp0_clk_en}} & regs_srst_srstmd[1:0]; + +assign cp0_ifu_srst_mask = (cur_state[1:0] == WFCPLT) || (cur_state[1:0] == WFRST); + +assign srst_special_srst_sm_clk_en = srst_sm_clk_en; + +// &ModuleEnd; @106 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_top.v new file mode 100644 index 0000000000000000000000000000000000000000..669a73d7dc5a29cf130a5cd12f2a0f1bb682eee5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_top.v @@ -0,0 +1,1000 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_top( + cp0_biu_icg_en, + cp0_dtu_addr, + cp0_dtu_debug_info, + cp0_dtu_icg_en, + cp0_dtu_int_id, + cp0_dtu_mexpt_vld, + cp0_dtu_pcfifo_frz, + cp0_dtu_rreg, + cp0_dtu_wdata, + cp0_dtu_wreg, + cp0_fpu_icg_en, + cp0_fpu_xx_dqnan, + cp0_fpu_xx_rm, + cp0_hpcp_icg_en, + cp0_hpcp_index, + cp0_hpcp_pmdm, + cp0_hpcp_pmdu, + cp0_hpcp_wdata, + cp0_hpcp_wreg, + cp0_idu_ex1_stall, + cp0_idu_fs, + cp0_idu_icg_en, + cp0_idu_mcause, + cp0_idu_mepc, + cp0_idu_rm, + cp0_idu_sp_use_scratch, + cp0_idu_sp_wdata, + cp0_idu_sp_wen, + cp0_idu_sp_wen_gate, + cp0_idu_spec_push_en, + cp0_idu_swap_sp_en, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_btb_clr, + cp0_ifu_btb_en, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_ifu_in_lpmd, + cp0_ifu_lpmd_req, + cp0_ifu_mtvec, + cp0_ifu_ras_en, + cp0_ifu_rst_inv_done, + cp0_ifu_srst_mask, + cp0_ifu_srst_req, + cp0_iu_adder_borrow_in, + cp0_iu_adder_borrow_vld, + cp0_iu_icg_en, + cp0_lsu_dcache_en, + cp0_lsu_dcache_wa, + cp0_lsu_dcache_wb, + cp0_lsu_fence_req, + cp0_lsu_icc_addr, + cp0_lsu_icc_op, + cp0_lsu_icc_req, + cp0_lsu_icc_type, + cp0_lsu_icg_en, + cp0_lsu_mm, + cp0_lsu_sync_req, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cp0_pmp_csr_sel, + cp0_pmp_csr_wen, + cp0_pmp_icg_en, + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_pmp_updt_data, + cp0_rtu_ex1_chgflw_pc, + cp0_rtu_ex1_chgflw_vld, + cp0_rtu_ex1_cmplt, + cp0_rtu_ex1_cmplt_dp, + cp0_rtu_ex1_dret, + cp0_rtu_ex1_ebreak, + cp0_rtu_ex1_expt_inst, + cp0_rtu_ex1_expt_tval, + cp0_rtu_ex1_expt_vec, + cp0_rtu_ex1_flush, + cp0_rtu_ex1_halt_info, + cp0_rtu_ex1_inst_len, + cp0_rtu_ex1_inst_vld, + cp0_rtu_ex1_ipush_spec_fail, + cp0_rtu_ex1_mret, + cp0_rtu_ex1_split_inst, + cp0_rtu_ex1_tail_fail, + cp0_rtu_icg_en, + cp0_rtu_in_expt, + cp0_rtu_in_nmi, + cp0_rtu_int_level, + cp0_rtu_int_mode, + cp0_rtu_mie, + cp0_rtu_mnxti_vld, + cp0_rtu_mpil, + cp0_rtu_pm_bypass, + cp0_rtu_tail_int_hv, + cp0_rtu_tail_int_id, + cp0_rtu_wb_data, + cp0_rtu_wb_preg, + cp0_rtu_wb_vld, + cp0_rtu_wfe_en, + cp0_sysio_ipend_b, + cp0_sysio_lpmd_b, + cp0_sysio_srst, + cp0_xx_async_expt_en, + cp0_yy_clk_en, + cp0_yy_cskyisaee, + cp0_yy_mach_mode, + cp0_yy_priv_mode, + cpurst_b, + dtu_cp0_dcsr_mprven, + dtu_cp0_dcsr_prv, + dtu_cp0_rdata, + dtu_cp0_wake_up, + forever_cpuclk, + fpu_cp0_wb_fflags, + fpu_cp0_wb_fflags_updt, + hpcp_cp0_data, + idu_cp0_ex1_cmplt_dp_sel, + idu_cp0_ex1_dst_idx, + idu_cp0_ex1_dst_vld, + idu_cp0_ex1_expt_high, + idu_cp0_ex1_expt_type, + idu_cp0_ex1_expt_vld, + idu_cp0_ex1_func, + idu_cp0_ex1_gateclk_sel, + idu_cp0_ex1_halt_info, + idu_cp0_ex1_inst_len, + idu_cp0_ex1_ipush_spec_fail, + idu_cp0_ex1_opcode, + idu_cp0_ex1_rs1, + idu_cp0_ex1_rs2, + idu_cp0_ex1_sel, + idu_cp0_ex1_split_inst, + idu_cp0_ex1_tail_fail, + idu_cp0_id_tail_vld, + idu_cp0_ipop_data, + idu_cp0_mcause_wen, + idu_cp0_mepc_wen, + idu_cp0_sp_reg, + idu_cp0_sp_swap_pending, + idu_cp0_sp_swap_req, + idu_cp0_sp_swap_req_gate, + idu_yy_xx_tail_ack, + ifu_cp0_bht_inv_done, + ifu_cp0_icache_inv_done, + ifu_cp0_lpmd_ack, + ifu_cp0_rst_inv_req, + ifu_cp0_srst_ack, + ifu_cp0_vec_err, + ifu_cp0_vec_succeed, + ifu_cp0_warm_up, + iu_cp0_ex1_borrow_expt_pc, + lsu_cp0_fence_ack, + lsu_cp0_icc_done, + lsu_cp0_sync_ack, + pad_yy_icg_scan_en, + pmp_cp0_data, + rtu_cp0_bus_error, + rtu_cp0_epc, + rtu_cp0_exit_debug, + rtu_cp0_fp_dirty_vld, + rtu_cp0_int_level, + rtu_cp0_lockup_clr, + rtu_cp0_lockup_vld, + rtu_cp0_mie_en, + rtu_cp0_mie_gateclk_en, + rtu_cp0_mnxti_pending_vld, + rtu_cp0_nmi_vld, + rtu_cp0_pending_int_hv, + rtu_cp0_pending_int_id, + rtu_cp0_pending_int_level, + rtu_cp0_tval, + rtu_cp0_wk_int, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_flush, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + sysio_cp0_clk_en, + sysio_cp0_clkratio, + sysio_cp0_rst_addr, + tcip_cp0_clic_base +); + +// &Ports; @24 +input cpurst_b; +input dtu_cp0_dcsr_mprven; +input [1 :0] dtu_cp0_dcsr_prv; +input [31:0] dtu_cp0_rdata; +input dtu_cp0_wake_up; +input forever_cpuclk; +input [4 :0] fpu_cp0_wb_fflags; +input fpu_cp0_wb_fflags_updt; +input [31:0] hpcp_cp0_data; +input idu_cp0_ex1_cmplt_dp_sel; +input [5 :0] idu_cp0_ex1_dst_idx; +input idu_cp0_ex1_dst_vld; +input idu_cp0_ex1_expt_high; +input idu_cp0_ex1_expt_type; +input idu_cp0_ex1_expt_vld; +input [19:0] idu_cp0_ex1_func; +input idu_cp0_ex1_gateclk_sel; +input [14:0] idu_cp0_ex1_halt_info; +input idu_cp0_ex1_inst_len; +input idu_cp0_ex1_ipush_spec_fail; +input [31:0] idu_cp0_ex1_opcode; +input [31:0] idu_cp0_ex1_rs1; +input [11:0] idu_cp0_ex1_rs2; +input idu_cp0_ex1_sel; +input idu_cp0_ex1_split_inst; +input idu_cp0_ex1_tail_fail; +input idu_cp0_id_tail_vld; +input [31:0] idu_cp0_ipop_data; +input idu_cp0_mcause_wen; +input idu_cp0_mepc_wen; +input [31:0] idu_cp0_sp_reg; +input idu_cp0_sp_swap_pending; +input idu_cp0_sp_swap_req; +input idu_cp0_sp_swap_req_gate; +input idu_yy_xx_tail_ack; +input ifu_cp0_bht_inv_done; +input ifu_cp0_icache_inv_done; +input ifu_cp0_lpmd_ack; +input ifu_cp0_rst_inv_req; +input ifu_cp0_srst_ack; +input ifu_cp0_vec_err; +input ifu_cp0_vec_succeed; +input ifu_cp0_warm_up; +input [31:0] iu_cp0_ex1_borrow_expt_pc; +input lsu_cp0_fence_ack; +input lsu_cp0_icc_done; +input lsu_cp0_sync_ack; +input pad_yy_icg_scan_en; +input [31:0] pmp_cp0_data; +input rtu_cp0_bus_error; +input [31:0] rtu_cp0_epc; +input rtu_cp0_exit_debug; +input rtu_cp0_fp_dirty_vld; +input [7 :0] rtu_cp0_int_level; +input rtu_cp0_lockup_clr; +input rtu_cp0_lockup_vld; +input rtu_cp0_mie_en; +input rtu_cp0_mie_gateclk_en; +input rtu_cp0_mnxti_pending_vld; +input rtu_cp0_nmi_vld; +input rtu_cp0_pending_int_hv; +input [11:0] rtu_cp0_pending_int_id; +input [7 :0] rtu_cp0_pending_int_level; +input [31:0] rtu_cp0_tval; +input rtu_cp0_wk_int; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input [11:0] rtu_yy_xx_expt_vec; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_flush; +input rtu_yy_xx_int_hv; +input rtu_yy_xx_tail_int_vld; +input sysio_cp0_clk_en; +input [2 :0] sysio_cp0_clkratio; +input [31:0] sysio_cp0_rst_addr; +input [31:0] tcip_cp0_clic_base; +output cp0_biu_icg_en; +output [11:0] cp0_dtu_addr; +output [5 :0] cp0_dtu_debug_info; +output cp0_dtu_icg_en; +output [11:0] cp0_dtu_int_id; +output cp0_dtu_mexpt_vld; +output cp0_dtu_pcfifo_frz; +output cp0_dtu_rreg; +output [31:0] cp0_dtu_wdata; +output cp0_dtu_wreg; +output cp0_fpu_icg_en; +output cp0_fpu_xx_dqnan; +output [2 :0] cp0_fpu_xx_rm; +output cp0_hpcp_icg_en; +output [11:0] cp0_hpcp_index; +output cp0_hpcp_pmdm; +output cp0_hpcp_pmdu; +output [31:0] cp0_hpcp_wdata; +output cp0_hpcp_wreg; +output cp0_idu_ex1_stall; +output [1 :0] cp0_idu_fs; +output cp0_idu_icg_en; +output [31:0] cp0_idu_mcause; +output [31:0] cp0_idu_mepc; +output [2 :0] cp0_idu_rm; +output cp0_idu_sp_use_scratch; +output [31:0] cp0_idu_sp_wdata; +output cp0_idu_sp_wen; +output cp0_idu_sp_wen_gate; +output cp0_idu_spec_push_en; +output cp0_idu_swap_sp_en; +output cp0_ifu_bht_en; +output cp0_ifu_bht_inv; +output cp0_ifu_btb_clr; +output cp0_ifu_btb_en; +output cp0_ifu_icache_en; +output [31:0] cp0_ifu_icache_inv_addr; +output cp0_ifu_icache_inv_req; +output cp0_ifu_icache_inv_type; +output cp0_ifu_icg_en; +output cp0_ifu_in_lpmd; +output cp0_ifu_lpmd_req; +output [31:0] cp0_ifu_mtvec; +output cp0_ifu_ras_en; +output cp0_ifu_rst_inv_done; +output cp0_ifu_srst_mask; +output cp0_ifu_srst_req; +output cp0_iu_adder_borrow_in; +output cp0_iu_adder_borrow_vld; +output cp0_iu_icg_en; +output cp0_lsu_dcache_en; +output cp0_lsu_dcache_wa; +output cp0_lsu_dcache_wb; +output cp0_lsu_fence_req; +output [31:0] cp0_lsu_icc_addr; +output [1 :0] cp0_lsu_icc_op; +output cp0_lsu_icc_req; +output [1 :0] cp0_lsu_icc_type; +output cp0_lsu_icg_en; +output cp0_lsu_mm; +output cp0_lsu_sync_req; +output [31:0] cp0_pad_mcause; +output [31:0] cp0_pad_mintstatus; +output [31:0] cp0_pad_mstatus; +output [19:0] cp0_pmp_csr_sel; +output cp0_pmp_csr_wen; +output cp0_pmp_icg_en; +output [1 :0] cp0_pmp_mstatus_mpp; +output cp0_pmp_mstatus_mprv; +output [31:0] cp0_pmp_updt_data; +output [30:0] cp0_rtu_ex1_chgflw_pc; +output cp0_rtu_ex1_chgflw_vld; +output cp0_rtu_ex1_cmplt; +output cp0_rtu_ex1_cmplt_dp; +output cp0_rtu_ex1_dret; +output cp0_rtu_ex1_ebreak; +output cp0_rtu_ex1_expt_inst; +output [31:0] cp0_rtu_ex1_expt_tval; +output [3 :0] cp0_rtu_ex1_expt_vec; +output cp0_rtu_ex1_flush; +output [14:0] cp0_rtu_ex1_halt_info; +output cp0_rtu_ex1_inst_len; +output cp0_rtu_ex1_inst_vld; +output cp0_rtu_ex1_ipush_spec_fail; +output cp0_rtu_ex1_mret; +output cp0_rtu_ex1_split_inst; +output cp0_rtu_ex1_tail_fail; +output cp0_rtu_icg_en; +output cp0_rtu_in_expt; +output cp0_rtu_in_nmi; +output [7 :0] cp0_rtu_int_level; +output [1 :0] cp0_rtu_int_mode; +output cp0_rtu_mie; +output cp0_rtu_mnxti_vld; +output [7 :0] cp0_rtu_mpil; +output [1 :0] cp0_rtu_pm_bypass; +output cp0_rtu_tail_int_hv; +output [11:0] cp0_rtu_tail_int_id; +output [31:0] cp0_rtu_wb_data; +output [5 :0] cp0_rtu_wb_preg; +output cp0_rtu_wb_vld; +output cp0_rtu_wfe_en; +output cp0_sysio_ipend_b; +output [1 :0] cp0_sysio_lpmd_b; +output [1 :0] cp0_sysio_srst; +output cp0_xx_async_expt_en; +output cp0_yy_clk_en; +output cp0_yy_cskyisaee; +output cp0_yy_mach_mode; +output [1 :0] cp0_yy_priv_mode; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_biu_icg_en; +wire [11:0] cp0_dtu_addr; +wire [5 :0] cp0_dtu_debug_info; +wire cp0_dtu_icg_en; +wire [11:0] cp0_dtu_int_id; +wire cp0_dtu_mexpt_vld; +wire cp0_dtu_pcfifo_frz; +wire cp0_dtu_rreg; +wire [31:0] cp0_dtu_wdata; +wire cp0_dtu_wreg; +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire [2 :0] cp0_fpu_xx_rm; +wire cp0_hpcp_icg_en; +wire [11:0] cp0_hpcp_index; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [31:0] cp0_hpcp_wdata; +wire cp0_hpcp_wreg; +wire cp0_idu_ex1_stall; +wire [1 :0] cp0_idu_fs; +wire cp0_idu_icg_en; +wire [31:0] cp0_idu_mcause; +wire [31:0] cp0_idu_mepc; +wire [2 :0] cp0_idu_rm; +wire cp0_idu_sp_use_scratch; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_ifu_in_lpmd; +wire cp0_ifu_lpmd_req; +wire [31:0] cp0_ifu_mtvec; +wire cp0_ifu_ras_en; +wire cp0_ifu_rst_inv_done; +wire cp0_ifu_srst_mask; +wire cp0_ifu_srst_req; +wire cp0_iu_adder_borrow_in; +wire cp0_iu_adder_borrow_vld; +wire cp0_iu_icg_en; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_dcache_wb; +wire cp0_lsu_fence_req; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire cp0_lsu_mm; +wire cp0_lsu_sync_req; +wire [31:0] cp0_pad_mcause; +wire [31:0] cp0_pad_mintstatus; +wire [31:0] cp0_pad_mstatus; +wire [19:0] cp0_pmp_csr_sel; +wire cp0_pmp_csr_wen; +wire cp0_pmp_icg_en; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire [31:0] cp0_pmp_updt_data; +wire [30:0] cp0_rtu_ex1_chgflw_pc; +wire cp0_rtu_ex1_chgflw_vld; +wire cp0_rtu_ex1_cmplt; +wire cp0_rtu_ex1_cmplt_dp; +wire cp0_rtu_ex1_dret; +wire cp0_rtu_ex1_ebreak; +wire cp0_rtu_ex1_expt_inst; +wire [31:0] cp0_rtu_ex1_expt_tval; +wire [3 :0] cp0_rtu_ex1_expt_vec; +wire cp0_rtu_ex1_flush; +wire [14:0] cp0_rtu_ex1_halt_info; +wire cp0_rtu_ex1_inst_len; +wire cp0_rtu_ex1_inst_vld; +wire cp0_rtu_ex1_ipush_spec_fail; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_ex1_split_inst; +wire cp0_rtu_ex1_tail_fail; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_expt; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire [1 :0] cp0_rtu_int_mode; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire [31:0] cp0_rtu_wb_data; +wire [5 :0] cp0_rtu_wb_preg; +wire cp0_rtu_wb_vld; +wire cp0_rtu_wfe_en; +wire cp0_sysio_ipend_b; +wire [1 :0] cp0_sysio_lpmd_b; +wire [1 :0] cp0_sysio_srst; +wire cp0_xx_async_expt_en; +wire cp0_yy_clk_en; +wire cp0_yy_cskyisaee; +wire cp0_yy_mach_mode; +wire [1 :0] cp0_yy_priv_mode; +wire cpurst_b; +wire dtu_cp0_dcsr_mprven; +wire [1 :0] dtu_cp0_dcsr_prv; +wire [31:0] dtu_cp0_rdata; +wire dtu_cp0_wake_up; +wire [31:0] ext_inst_ifu_icc_addr; +wire ext_inst_ifu_icc_req; +wire ext_inst_ifu_icc_type; +wire ext_inst_ifu_inv_done; +wire [31:0] ext_inst_lsu_icc_addr; +wire ext_inst_lsu_icc_done; +wire [1 :0] ext_inst_lsu_icc_op; +wire ext_inst_lsu_icc_req; +wire [1 :0] ext_inst_lsu_icc_type; +wire ext_iui_cache_stall; +wire ext_iui_expt_vld; +wire [2 :0] fence_top_cur_state; +wire forever_cpuclk; +wire [4 :0] fpu_cp0_wb_fflags; +wire fpu_cp0_wb_fflags_updt; +wire [31:0] hpcp_cp0_data; +wire idu_cp0_ex1_cmplt_dp_sel; +wire [5 :0] idu_cp0_ex1_dst_idx; +wire idu_cp0_ex1_dst_vld; +wire idu_cp0_ex1_expt_high; +wire idu_cp0_ex1_expt_type; +wire idu_cp0_ex1_expt_vld; +wire [19:0] idu_cp0_ex1_func; +wire idu_cp0_ex1_gateclk_sel; +wire [14:0] idu_cp0_ex1_halt_info; +wire idu_cp0_ex1_inst_len; +wire idu_cp0_ex1_ipush_spec_fail; +wire [31:0] idu_cp0_ex1_opcode; +wire [31:0] idu_cp0_ex1_rs1; +wire [11:0] idu_cp0_ex1_rs2; +wire idu_cp0_ex1_sel; +wire idu_cp0_ex1_split_inst; +wire idu_cp0_ex1_tail_fail; +wire idu_cp0_id_tail_vld; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire idu_yy_xx_tail_ack; +wire ifu_cp0_bht_inv_done; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_lpmd_ack; +wire ifu_cp0_rst_inv_req; +wire ifu_cp0_srst_ack; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire ifu_cp0_warm_up; +wire inv_sm_clk; +wire [31:0] iu_cp0_ex1_borrow_expt_pc; +wire iui_csr_wen_f; +wire iui_ext_inst_cache; +wire [11:0] iui_ext_inst_imm; +wire [31:0] iui_ext_inst_rs1; +wire iui_regs_csr_mnxti_vld; +wire iui_regs_csr_wen; +wire [11:0] iui_regs_imm; +wire iui_regs_inst_csr; +wire iui_regs_inst_mret; +wire [31:0] iui_regs_wdata; +wire iui_regs_wdata_mie; +wire [31:0] iui_regs_wdata_rs1; +wire [1 :0] iui_regs_wdata_srst; +wire iui_special_ecall; +wire iui_special_fence; +wire iui_special_fencei; +wire iui_special_int_vld; +wire iui_special_sync; +wire iui_special_synci; +wire iui_special_wfi; +wire [1 :0] lpmd_top_cur_state; +wire lsu_cp0_fence_ack; +wire lsu_cp0_icc_done; +wire lsu_cp0_sync_ack; +wire pad_yy_icg_scan_en; +wire [31:0] pmp_cp0_data; +wire regs_clk; +wire regs_iui_expt_vld; +wire [31:0] regs_iui_mepc; +wire regs_iui_mie; +wire regs_iui_mnxti_sel; +wire [31:0] regs_iui_mstatus; +wire [1 :0] regs_iui_pm; +wire [31:0] regs_iui_rdata; +wire [1 :0] regs_special_lpmd; +wire regs_srst_srst_vld; +wire [1 :0] regs_srst_srstmd; +wire rst_top_op_done; +wire rtu_cp0_bus_error; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire rtu_cp0_fp_dirty_vld; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_cp0_mie_en; +wire rtu_cp0_mie_gateclk_en; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_nmi_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire [31:0] rtu_cp0_tval; +wire rtu_cp0_wk_int; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire special_dcache_clean; +wire special_icache_inv; +wire special_icache_inv_done; +wire special_iui_expt_vld; +wire special_iui_stall; +wire special_regs_clk_en; +wire special_regs_inv_sm_clk_en; +wire srst_in_wait_state; +wire srst_iui_stall; +wire srst_sm_clk; +wire srst_special_srst_sm_clk_en; +wire sysio_cp0_clk_en; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; +wire [31:0] tcip_cp0_clic_base; + + +//========================================================== +// CP0 TOP Module +//========================================================== + +//------------------------------------------------ +// Instance all the submodules +//------------------------------------------------ + +// Instruction Unified Interface Module +// &Instance("pa_cp0_iui", "x_pa_cp0_iui"); @37 +pa_cp0_iui x_pa_cp0_iui ( + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_dtu_wreg (cp0_dtu_wreg ), + .cp0_idu_ex1_stall (cp0_idu_ex1_stall ), + .cp0_iu_adder_borrow_in (cp0_iu_adder_borrow_in ), + .cp0_iu_adder_borrow_vld (cp0_iu_adder_borrow_vld ), + .cp0_rtu_ex1_chgflw_pc (cp0_rtu_ex1_chgflw_pc ), + .cp0_rtu_ex1_chgflw_vld (cp0_rtu_ex1_chgflw_vld ), + .cp0_rtu_ex1_cmplt (cp0_rtu_ex1_cmplt ), + .cp0_rtu_ex1_cmplt_dp (cp0_rtu_ex1_cmplt_dp ), + .cp0_rtu_ex1_dret (cp0_rtu_ex1_dret ), + .cp0_rtu_ex1_ebreak (cp0_rtu_ex1_ebreak ), + .cp0_rtu_ex1_expt_inst (cp0_rtu_ex1_expt_inst ), + .cp0_rtu_ex1_expt_tval (cp0_rtu_ex1_expt_tval ), + .cp0_rtu_ex1_expt_vec (cp0_rtu_ex1_expt_vec ), + .cp0_rtu_ex1_flush (cp0_rtu_ex1_flush ), + .cp0_rtu_ex1_halt_info (cp0_rtu_ex1_halt_info ), + .cp0_rtu_ex1_inst_len (cp0_rtu_ex1_inst_len ), + .cp0_rtu_ex1_inst_vld (cp0_rtu_ex1_inst_vld ), + .cp0_rtu_ex1_ipush_spec_fail (cp0_rtu_ex1_ipush_spec_fail), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_ex1_split_inst (cp0_rtu_ex1_split_inst ), + .cp0_rtu_ex1_tail_fail (cp0_rtu_ex1_tail_fail ), + .cp0_rtu_wb_data (cp0_rtu_wb_data ), + .cp0_rtu_wb_preg (cp0_rtu_wb_preg ), + .cp0_rtu_wb_vld (cp0_rtu_wb_vld ), + .cpurst_b (cpurst_b ), + .ext_iui_cache_stall (ext_iui_cache_stall ), + .ext_iui_expt_vld (ext_iui_expt_vld ), + .idu_cp0_ex1_cmplt_dp_sel (idu_cp0_ex1_cmplt_dp_sel ), + .idu_cp0_ex1_dst_idx (idu_cp0_ex1_dst_idx ), + .idu_cp0_ex1_dst_vld (idu_cp0_ex1_dst_vld ), + .idu_cp0_ex1_expt_high (idu_cp0_ex1_expt_high ), + .idu_cp0_ex1_expt_type (idu_cp0_ex1_expt_type ), + .idu_cp0_ex1_expt_vld (idu_cp0_ex1_expt_vld ), + .idu_cp0_ex1_func (idu_cp0_ex1_func ), + .idu_cp0_ex1_gateclk_sel (idu_cp0_ex1_gateclk_sel ), + .idu_cp0_ex1_halt_info (idu_cp0_ex1_halt_info ), + .idu_cp0_ex1_inst_len (idu_cp0_ex1_inst_len ), + .idu_cp0_ex1_ipush_spec_fail (idu_cp0_ex1_ipush_spec_fail), + .idu_cp0_ex1_opcode (idu_cp0_ex1_opcode ), + .idu_cp0_ex1_rs1 (idu_cp0_ex1_rs1 ), + .idu_cp0_ex1_rs2 (idu_cp0_ex1_rs2 ), + .idu_cp0_ex1_sel (idu_cp0_ex1_sel ), + .idu_cp0_ex1_split_inst (idu_cp0_ex1_split_inst ), + .idu_cp0_ex1_tail_fail (idu_cp0_ex1_tail_fail ), + .ifu_cp0_warm_up (ifu_cp0_warm_up ), + .iu_cp0_ex1_borrow_expt_pc (iu_cp0_ex1_borrow_expt_pc ), + .iui_csr_wen_f (iui_csr_wen_f ), + .iui_ext_inst_cache (iui_ext_inst_cache ), + .iui_ext_inst_imm (iui_ext_inst_imm ), + .iui_ext_inst_rs1 (iui_ext_inst_rs1 ), + .iui_regs_csr_mnxti_vld (iui_regs_csr_mnxti_vld ), + .iui_regs_csr_wen (iui_regs_csr_wen ), + .iui_regs_imm (iui_regs_imm ), + .iui_regs_inst_csr (iui_regs_inst_csr ), + .iui_regs_inst_mret (iui_regs_inst_mret ), + .iui_regs_wdata (iui_regs_wdata ), + .iui_regs_wdata_mie (iui_regs_wdata_mie ), + .iui_regs_wdata_rs1 (iui_regs_wdata_rs1 ), + .iui_regs_wdata_srst (iui_regs_wdata_srst ), + .iui_special_ecall (iui_special_ecall ), + .iui_special_fence (iui_special_fence ), + .iui_special_fencei (iui_special_fencei ), + .iui_special_int_vld (iui_special_int_vld ), + .iui_special_sync (iui_special_sync ), + .iui_special_synci (iui_special_synci ), + .iui_special_wfi (iui_special_wfi ), + .regs_clk (regs_clk ), + .regs_iui_expt_vld (regs_iui_expt_vld ), + .regs_iui_mepc (regs_iui_mepc ), + .regs_iui_mie (regs_iui_mie ), + .regs_iui_mnxti_sel (regs_iui_mnxti_sel ), + .regs_iui_mstatus (regs_iui_mstatus ), + .regs_iui_pm (regs_iui_pm ), + .regs_iui_rdata (regs_iui_rdata ), + .rtu_cp0_wk_int (rtu_cp0_wk_int ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .special_iui_expt_vld (special_iui_expt_vld ), + .special_iui_stall (special_iui_stall ), + .srst_iui_stall (srst_iui_stall ) +); + + +// Regs Module +// &Instance("pa_cp0_regs", "x_pa_cp0_regs"); @40 +pa_cp0_regs x_pa_cp0_regs ( + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_int_id (cp0_dtu_int_id ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .cp0_fpu_xx_rm (cp0_fpu_xx_rm ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cp0_hpcp_index (cp0_hpcp_index ), + .cp0_hpcp_pmdm (cp0_hpcp_pmdm ), + .cp0_hpcp_pmdu (cp0_hpcp_pmdu ), + .cp0_hpcp_wdata (cp0_hpcp_wdata ), + .cp0_hpcp_wreg (cp0_hpcp_wreg ), + .cp0_idu_fs (cp0_idu_fs ), + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_mcause (cp0_idu_mcause ), + .cp0_idu_mepc (cp0_idu_mepc ), + .cp0_idu_rm (cp0_idu_rm ), + .cp0_idu_sp_use_scratch (cp0_idu_sp_use_scratch ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_idu_sp_wen (cp0_idu_sp_wen ), + .cp0_idu_sp_wen_gate (cp0_idu_sp_wen_gate ), + .cp0_idu_spec_push_en (cp0_idu_spec_push_en ), + .cp0_idu_swap_sp_en (cp0_idu_swap_sp_en ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_btb_clr (cp0_ifu_btb_clr ), + .cp0_ifu_btb_en (cp0_ifu_btb_en ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr ), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_mtvec (cp0_ifu_mtvec ), + .cp0_ifu_ras_en (cp0_ifu_ras_en ), + .cp0_ifu_rst_inv_done (cp0_ifu_rst_inv_done ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_lsu_dcache_en (cp0_lsu_dcache_en ), + .cp0_lsu_dcache_wa (cp0_lsu_dcache_wa ), + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_icc_addr (cp0_lsu_icc_addr ), + .cp0_lsu_icc_op (cp0_lsu_icc_op ), + .cp0_lsu_icc_req (cp0_lsu_icc_req ), + .cp0_lsu_icc_type (cp0_lsu_icc_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_lsu_mm (cp0_lsu_mm ), + .cp0_pad_mcause (cp0_pad_mcause ), + .cp0_pad_mintstatus (cp0_pad_mintstatus ), + .cp0_pad_mstatus (cp0_pad_mstatus ), + .cp0_pmp_csr_sel (cp0_pmp_csr_sel ), + .cp0_pmp_csr_wen (cp0_pmp_csr_wen ), + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv ), + .cp0_pmp_updt_data (cp0_pmp_updt_data ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_expt (cp0_rtu_in_expt ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_rtu_int_level (cp0_rtu_int_level ), + .cp0_rtu_int_mode (cp0_rtu_int_mode ), + .cp0_rtu_mie (cp0_rtu_mie ), + .cp0_rtu_mnxti_vld (cp0_rtu_mnxti_vld ), + .cp0_rtu_mpil (cp0_rtu_mpil ), + .cp0_rtu_pm_bypass (cp0_rtu_pm_bypass ), + .cp0_rtu_tail_int_hv (cp0_rtu_tail_int_hv ), + .cp0_rtu_tail_int_id (cp0_rtu_tail_int_id ), + .cp0_rtu_wfe_en (cp0_rtu_wfe_en ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_cskyisaee (cp0_yy_cskyisaee ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .dtu_cp0_dcsr_mprven (dtu_cp0_dcsr_mprven ), + .dtu_cp0_dcsr_prv (dtu_cp0_dcsr_prv ), + .dtu_cp0_rdata (dtu_cp0_rdata ), + .ext_inst_ifu_icc_addr (ext_inst_ifu_icc_addr ), + .ext_inst_ifu_icc_req (ext_inst_ifu_icc_req ), + .ext_inst_ifu_icc_type (ext_inst_ifu_icc_type ), + .ext_inst_ifu_inv_done (ext_inst_ifu_inv_done ), + .ext_inst_lsu_icc_addr (ext_inst_lsu_icc_addr ), + .ext_inst_lsu_icc_done (ext_inst_lsu_icc_done ), + .ext_inst_lsu_icc_op (ext_inst_lsu_icc_op ), + .ext_inst_lsu_icc_req (ext_inst_lsu_icc_req ), + .ext_inst_lsu_icc_type (ext_inst_lsu_icc_type ), + .forever_cpuclk (forever_cpuclk ), + .fpu_cp0_wb_fflags (fpu_cp0_wb_fflags ), + .fpu_cp0_wb_fflags_updt (fpu_cp0_wb_fflags_updt ), + .hpcp_cp0_data (hpcp_cp0_data ), + .idu_cp0_id_tail_vld (idu_cp0_id_tail_vld ), + .idu_cp0_ipop_data (idu_cp0_ipop_data ), + .idu_cp0_mcause_wen (idu_cp0_mcause_wen ), + .idu_cp0_mepc_wen (idu_cp0_mepc_wen ), + .idu_cp0_sp_reg (idu_cp0_sp_reg ), + .idu_cp0_sp_swap_pending (idu_cp0_sp_swap_pending ), + .idu_cp0_sp_swap_req (idu_cp0_sp_swap_req ), + .idu_cp0_sp_swap_req_gate (idu_cp0_sp_swap_req_gate ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done ), + .ifu_cp0_rst_inv_req (ifu_cp0_rst_inv_req ), + .ifu_cp0_vec_err (ifu_cp0_vec_err ), + .ifu_cp0_vec_succeed (ifu_cp0_vec_succeed ), + .inv_sm_clk (inv_sm_clk ), + .iui_csr_wen_f (iui_csr_wen_f ), + .iui_regs_csr_mnxti_vld (iui_regs_csr_mnxti_vld ), + .iui_regs_csr_wen (iui_regs_csr_wen ), + .iui_regs_imm (iui_regs_imm ), + .iui_regs_inst_csr (iui_regs_inst_csr ), + .iui_regs_inst_mret (iui_regs_inst_mret ), + .iui_regs_wdata (iui_regs_wdata ), + .iui_regs_wdata_mie (iui_regs_wdata_mie ), + .iui_regs_wdata_rs1 (iui_regs_wdata_rs1 ), + .iui_regs_wdata_srst (iui_regs_wdata_srst ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_cp0_data (pmp_cp0_data ), + .regs_clk (regs_clk ), + .regs_iui_expt_vld (regs_iui_expt_vld ), + .regs_iui_mepc (regs_iui_mepc ), + .regs_iui_mie (regs_iui_mie ), + .regs_iui_mnxti_sel (regs_iui_mnxti_sel ), + .regs_iui_mstatus (regs_iui_mstatus ), + .regs_iui_pm (regs_iui_pm ), + .regs_iui_rdata (regs_iui_rdata ), + .regs_special_lpmd (regs_special_lpmd ), + .regs_srst_srst_vld (regs_srst_srst_vld ), + .regs_srst_srstmd (regs_srst_srstmd ), + .rst_top_op_done (rst_top_op_done ), + .rtu_cp0_bus_error (rtu_cp0_bus_error ), + .rtu_cp0_epc (rtu_cp0_epc ), + .rtu_cp0_exit_debug (rtu_cp0_exit_debug ), + .rtu_cp0_fp_dirty_vld (rtu_cp0_fp_dirty_vld ), + .rtu_cp0_int_level (rtu_cp0_int_level ), + .rtu_cp0_lockup_clr (rtu_cp0_lockup_clr ), + .rtu_cp0_lockup_vld (rtu_cp0_lockup_vld ), + .rtu_cp0_mie_en (rtu_cp0_mie_en ), + .rtu_cp0_mie_gateclk_en (rtu_cp0_mie_gateclk_en ), + .rtu_cp0_mnxti_pending_vld (rtu_cp0_mnxti_pending_vld ), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_cp0_pending_int_hv (rtu_cp0_pending_int_hv ), + .rtu_cp0_pending_int_id (rtu_cp0_pending_int_id ), + .rtu_cp0_pending_int_level (rtu_cp0_pending_int_level ), + .rtu_cp0_tval (rtu_cp0_tval ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .special_dcache_clean (special_dcache_clean ), + .special_icache_inv (special_icache_inv ), + .special_icache_inv_done (special_icache_inv_done ), + .special_regs_clk_en (special_regs_clk_en ), + .special_regs_inv_sm_clk_en (special_regs_inv_sm_clk_en), + .sysio_cp0_clkratio (sysio_cp0_clkratio ), + .sysio_cp0_rst_addr (sysio_cp0_rst_addr ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ) +); + +// &Force("output","cp0_iu_icg_en"); @41 +// Special Inst module +// &Instance("pa_cp0_special", "x_pa_cp0_special"); @43 +pa_cp0_special x_pa_cp0_special ( + .cp0_ifu_in_lpmd (cp0_ifu_in_lpmd ), + .cp0_ifu_lpmd_req (cp0_ifu_lpmd_req ), + .cp0_lsu_fence_req (cp0_lsu_fence_req ), + .cp0_lsu_sync_req (cp0_lsu_sync_req ), + .cp0_sysio_ipend_b (cp0_sysio_ipend_b ), + .cp0_sysio_lpmd_b (cp0_sysio_lpmd_b ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dtu_cp0_wake_up (dtu_cp0_wake_up ), + .fence_top_cur_state (fence_top_cur_state ), + .forever_cpuclk (forever_cpuclk ), + .ifu_cp0_lpmd_ack (ifu_cp0_lpmd_ack ), + .inv_sm_clk (inv_sm_clk ), + .iui_special_ecall (iui_special_ecall ), + .iui_special_fence (iui_special_fence ), + .iui_special_fencei (iui_special_fencei ), + .iui_special_int_vld (iui_special_int_vld ), + .iui_special_sync (iui_special_sync ), + .iui_special_synci (iui_special_synci ), + .iui_special_wfi (iui_special_wfi ), + .lpmd_top_cur_state (lpmd_top_cur_state ), + .lsu_cp0_fence_ack (lsu_cp0_fence_ack ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .lsu_cp0_sync_ack (lsu_cp0_sync_ack ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .regs_special_lpmd (regs_special_lpmd ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .special_dcache_clean (special_dcache_clean ), + .special_icache_inv (special_icache_inv ), + .special_icache_inv_done (special_icache_inv_done ), + .special_iui_expt_vld (special_iui_expt_vld ), + .special_iui_stall (special_iui_stall ), + .special_regs_clk_en (special_regs_clk_en ), + .special_regs_inv_sm_clk_en (special_regs_inv_sm_clk_en ), + .srst_in_wait_state (srst_in_wait_state ), + .srst_sm_clk (srst_sm_clk ), + .srst_special_srst_sm_clk_en (srst_special_srst_sm_clk_en) +); + + +// Extension Inst +// &Instance("pa_cp0_ext_inst"); @46 +pa_cp0_ext_inst x_pa_cp0_ext_inst ( + .ext_inst_ifu_icc_addr (ext_inst_ifu_icc_addr), + .ext_inst_ifu_icc_req (ext_inst_ifu_icc_req ), + .ext_inst_ifu_icc_type (ext_inst_ifu_icc_type), + .ext_inst_ifu_inv_done (ext_inst_ifu_inv_done), + .ext_inst_lsu_icc_addr (ext_inst_lsu_icc_addr), + .ext_inst_lsu_icc_done (ext_inst_lsu_icc_done), + .ext_inst_lsu_icc_op (ext_inst_lsu_icc_op ), + .ext_inst_lsu_icc_req (ext_inst_lsu_icc_req ), + .ext_inst_lsu_icc_type (ext_inst_lsu_icc_type), + .ext_iui_cache_stall (ext_iui_cache_stall ), + .ext_iui_expt_vld (ext_iui_expt_vld ), + .iui_ext_inst_cache (iui_ext_inst_cache ), + .iui_ext_inst_imm (iui_ext_inst_imm ), + .iui_ext_inst_rs1 (iui_ext_inst_rs1 ) +); + +// &Force("output", "cp0_yy_priv_mode"); @47 + +// &Instance("pa_cp0_srst"); @49 +pa_cp0_srst x_pa_cp0_srst ( + .cp0_ifu_srst_mask (cp0_ifu_srst_mask ), + .cp0_ifu_srst_req (cp0_ifu_srst_req ), + .cp0_sysio_srst (cp0_sysio_srst ), + .cpurst_b (cpurst_b ), + .ifu_cp0_srst_ack (ifu_cp0_srst_ack ), + .lsu_cp0_sync_ack (lsu_cp0_sync_ack ), + .regs_srst_srst_vld (regs_srst_srst_vld ), + .regs_srst_srstmd (regs_srst_srstmd ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .srst_in_wait_state (srst_in_wait_state ), + .srst_iui_stall (srst_iui_stall ), + .srst_sm_clk (srst_sm_clk ), + .srst_special_srst_sm_clk_en (srst_special_srst_sm_clk_en), + .sysio_cp0_clk_en (sysio_cp0_clk_en ) +); + + +assign cp0_dtu_debug_info[5:0] = {lpmd_top_cur_state[1:0], + fence_top_cur_state[2:0], + rst_top_op_done}; + +//assign cp0_had_pcfifo_wen = 1'b1; + + + + + +// &ModuleEnd; @158 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_trap_csr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_trap_csr.v new file mode 100644 index 0000000000000000000000000000000000000000..d603c4a1f75584a213b057338f814eeb3252035c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cp0/rtl/pa_cp0_trap_csr.v @@ -0,0 +1,1210 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_cp0_trap_csr( + cp0_dtu_int_id, + cp0_dtu_mexpt_vld, + cp0_hpcp_pmdm, + cp0_hpcp_pmdu, + cp0_idu_fs, + cp0_idu_mcause, + cp0_idu_mepc, + cp0_idu_sp_use_scratch, + cp0_idu_sp_wdata, + cp0_idu_sp_wen, + cp0_idu_sp_wen_gate, + cp0_lsu_mm, + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_rtu_in_nmi, + cp0_rtu_int_level, + cp0_rtu_int_mode, + cp0_rtu_mie, + cp0_rtu_mnxti_vld, + cp0_rtu_mpil, + cp0_rtu_pm_bypass, + cp0_rtu_tail_int_hv, + cp0_rtu_tail_int_id, + cp0_yy_cskyisaee, + cpurst_b, + dtu_cp0_dcsr_mprven, + dtu_cp0_dcsr_prv, + fcsr_local_en, + fflags_clk, + fflags_local_en, + fpu_cp0_wb_fflags_updt, + frm_local_en, + fs_dirty_upd, + fxcr_local_en, + idu_cp0_id_tail_vld, + idu_cp0_ipop_data, + idu_cp0_mcause_wen, + idu_cp0_mepc_wen, + idu_cp0_sp_reg, + idu_cp0_sp_swap_pending, + idu_cp0_sp_swap_req, + idu_cp0_sp_swap_req_gate, + idu_yy_xx_tail_ack, + ifu_cp0_vec_err, + ifu_cp0_vec_succeed, + iui_regs_inst_mret, + iui_regs_wdata, + iui_regs_wdata_mie, + iui_regs_wdata_rs1, + mcause_local_en, + mcause_value, + mclicbase_value, + mcnten_local_en, + mcnten_value, + medeleg_value, + mepc_local_en, + mepc_value, + mideleg_value, + mie_value, + mintstatus_value, + mip_value, + misa_value, + mnmicause_local_en, + mnmicause_value, + mnmipc_local_en, + mnmipc_value, + mnxti_local_en, + mnxti_value, + mscratch_local_en, + mscratch_value, + mscratchcsw_local_en, + mscratchcsw_value, + mscratchcswl_local_en, + mscratchcswl_value, + mstatus_local_en, + mstatus_value, + mtval_local_en, + mtval_value, + mtvec_local_en, + mtvec_rslt, + mtvec_value, + mtvt_local_en, + mtvt_value, + mxstatus_local_en, + mxstatus_value, + regs_clk, + regs_cpu_in_int, + regs_cpu_in_nmi, + regs_flush_clk, + regs_fs_off, + regs_iui_mie, + regs_spswap_en, + regs_swap_int_sp_en_gate, + rtu_cp0_epc, + rtu_cp0_exit_debug, + rtu_cp0_fp_dirty_vld, + rtu_cp0_int_level, + rtu_cp0_mie_en, + rtu_cp0_mnxti_pending_vld, + rtu_cp0_nmi_vld, + rtu_cp0_pending_int_hv, + rtu_cp0_pending_int_id, + rtu_cp0_pending_int_level, + rtu_cp0_tval, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + tcip_cp0_clic_base, + trap_csr_pm +); + +// &Ports; @24 +input cpurst_b; +input dtu_cp0_dcsr_mprven; +input [1 :0] dtu_cp0_dcsr_prv; +input fcsr_local_en; +input fflags_clk; +input fflags_local_en; +input fpu_cp0_wb_fflags_updt; +input frm_local_en; +input fxcr_local_en; +input idu_cp0_id_tail_vld; +input [31:0] idu_cp0_ipop_data; +input idu_cp0_mcause_wen; +input idu_cp0_mepc_wen; +input [31:0] idu_cp0_sp_reg; +input idu_cp0_sp_swap_pending; +input idu_cp0_sp_swap_req; +input idu_cp0_sp_swap_req_gate; +input idu_yy_xx_tail_ack; +input ifu_cp0_vec_err; +input ifu_cp0_vec_succeed; +input iui_regs_inst_mret; +input [31:0] iui_regs_wdata; +input iui_regs_wdata_mie; +input [31:0] iui_regs_wdata_rs1; +input mcause_local_en; +input mcnten_local_en; +input mepc_local_en; +input mnmicause_local_en; +input mnmipc_local_en; +input mnxti_local_en; +input mscratch_local_en; +input mscratchcsw_local_en; +input mscratchcswl_local_en; +input mstatus_local_en; +input mtval_local_en; +input mtvec_local_en; +input mtvt_local_en; +input mxstatus_local_en; +input regs_clk; +input regs_cpu_in_nmi; +input regs_flush_clk; +input regs_spswap_en; +input [31:0] rtu_cp0_epc; +input rtu_cp0_exit_debug; +input rtu_cp0_fp_dirty_vld; +input [7 :0] rtu_cp0_int_level; +input rtu_cp0_mie_en; +input rtu_cp0_mnxti_pending_vld; +input rtu_cp0_nmi_vld; +input rtu_cp0_pending_int_hv; +input [11:0] rtu_cp0_pending_int_id; +input [7 :0] rtu_cp0_pending_int_level; +input [31:0] rtu_cp0_tval; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input [11:0] rtu_yy_xx_expt_vec; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_int_hv; +input rtu_yy_xx_tail_int_vld; +input [31:0] tcip_cp0_clic_base; +output [11:0] cp0_dtu_int_id; +output cp0_dtu_mexpt_vld; +output cp0_hpcp_pmdm; +output cp0_hpcp_pmdu; +output [1 :0] cp0_idu_fs; +output [31:0] cp0_idu_mcause; +output [31:0] cp0_idu_mepc; +output cp0_idu_sp_use_scratch; +output [31:0] cp0_idu_sp_wdata; +output cp0_idu_sp_wen; +output cp0_idu_sp_wen_gate; +output cp0_lsu_mm; +output [1 :0] cp0_pmp_mstatus_mpp; +output cp0_pmp_mstatus_mprv; +output cp0_rtu_in_nmi; +output [7 :0] cp0_rtu_int_level; +output [1 :0] cp0_rtu_int_mode; +output cp0_rtu_mie; +output cp0_rtu_mnxti_vld; +output [7 :0] cp0_rtu_mpil; +output [1 :0] cp0_rtu_pm_bypass; +output cp0_rtu_tail_int_hv; +output [11:0] cp0_rtu_tail_int_id; +output cp0_yy_cskyisaee; +output fs_dirty_upd; +output [31:0] mcause_value; +output [31:0] mclicbase_value; +output [31:0] mcnten_value; +output [31:0] medeleg_value; +output [31:0] mepc_value; +output [31:0] mideleg_value; +output [31:0] mie_value; +output [31:0] mintstatus_value; +output [31:0] mip_value; +output [31:0] misa_value; +output [31:0] mnmicause_value; +output [31:0] mnmipc_value; +output [31:0] mnxti_value; +output [31:0] mscratch_value; +output [31:0] mscratchcsw_value; +output [31:0] mscratchcswl_value; +output [31:0] mstatus_value; +output [31:0] mtval_value; +output [29:0] mtvec_rslt; +output [31:0] mtvec_value; +output [31:0] mtvt_value; +output [31:0] mxstatus_value; +output regs_cpu_in_int; +output regs_fs_off; +output regs_iui_mie; +output regs_swap_int_sp_en_gate; +output [1 :0] trap_csr_pm; + +// &Regs; @25 +reg cskyisaee; +reg [1 :0] fs; +reg m_intr; +reg [11:0] m_vector; +reg [11:0] m_vector_tail; +reg mcnten_hpm13; +reg mcnten_hpm14; +reg mcnten_hpm15; +reg mcnten_hpm16; +reg mcnten_hpm17; +reg mcnten_hpm3; +reg mcnten_hpm4; +reg mcnten_hpm8; +reg mcnten_hpm9; +reg [2 :0] mcnten_reg; +reg [31:0] mepc_reg; +reg mie_bit; +reg [7 :0] mil; +reg [7 :0] mil_tail; +reg minhv; +reg minhv_tail; +reg mm; +reg mpie; +reg [7 :0] mpil; +reg [1 :0] mpp; +reg mprv; +reg [31:0] mscratch; +reg [31:0] mtval_data; +reg [29:0] mtvec_base; +reg [25:0] mtvt_base; +reg nmi_intr; +reg nmi_mpie; +reg [1 :0] nmi_mpp; +reg [30:0] nmi_pc_31_1; +reg [11:0] nmi_vector; +reg [1 :0] pm; +reg pmdm; +reg pmdu; + +// &Wires; @26 +wire [11:0] cp0_dtu_int_id; +wire cp0_dtu_mexpt_vld; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [1 :0] cp0_idu_fs; +wire [31:0] cp0_idu_mcause; +wire [31:0] cp0_idu_mepc; +wire cp0_idu_sp_use_scratch; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_lsu_mm; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire [1 :0] cp0_rtu_int_mode; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire cp0_yy_cskyisaee; +wire cpurst_b; +wire [3 :0] dsp_m_value; +wire dtu_cp0_dcsr_mprven; +wire [1 :0] dtu_cp0_dcsr_prv; +wire [25:0] extensions; +wire fcsr_local_en; +wire fflags_clk; +wire fflags_local_en; +wire fpu_cp0_wb_fflags_updt; +wire frm_local_en; +wire fs_dirty_upd; +wire fs_off; +wire fxcr_local_en; +wire hw_vector_clic_on; +wire idu_cp0_id_tail_vld; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire idu_yy_xx_tail_ack; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire int_mret_vld; +wire ipush_sp_use_mscratch; +wire iui_regs_inst_mret; +wire [31:0] iui_regs_wdata; +wire iui_regs_wdata_mie; +wire [31:0] iui_regs_wdata_rs1; +wire [31:0] mcause_bypass_value; +wire mcause_local_en; +wire [31:0] mcause_spec_value; +wire [31:0] mcause_value; +wire [31:0] mclicbase_value; +wire [28:0] mcnten_hpm; +wire mcnten_local_en; +wire [31:0] mcnten_value; +wire [31:0] medeleg_value; +wire mepc_local_en; +wire [31:0] mepc_value; +wire [31:0] mideleg_value; +wire mie_valid; +wire [31:0] mie_value; +wire [7 :0] mil_val; +wire [31:0] mintstatus_value; +wire [31:0] mip_value; +wire [31:0] misa_value; +wire mnmicause_local_en; +wire [31:0] mnmicause_value; +wire mnmipc_local_en; +wire [31:0] mnmipc_value; +wire mnxti_local_en; +wire [29:0] mnxti_pending_addr; +wire [31:0] mnxti_value; +wire mnxti_vld_int_pending; +wire mscratch_local_en; +wire mscratch_swap_int_sp_en; +wire mscratch_swap_int_sp_en_gate; +wire [31:0] mscratch_value; +wire mscratchcsw_local_en; +wire mscratchcsw_swap_en; +wire [31:0] mscratchcsw_value; +wire mscratchcswl_local_en; +wire mscratchcswl_swap_en; +wire [31:0] mscratchcswl_value; +wire mstatus_local_en; +wire [31:0] mstatus_value; +wire mtval_local_en; +wire [31:0] mtval_value; +wire mtvec_local_en; +wire [1 :0] mtvec_mode; +wire [29:0] mtvec_rslt; +wire mtvec_rslt_use_base; +wire [31:0] mtvec_value; +wire mtvt_local_en; +wire [31:0] mtvt_value; +wire [1 :0] mxl; +wire mxstatus_local_en; +wire [31:0] mxstatus_value; +wire [7 :0] opt_value; +wire [1 :0] pm_bypass; +wire regs_clk; +wire regs_cpu_in_int; +wire regs_cpu_in_nmi; +wire regs_flush_clk; +wire regs_fs_off; +wire regs_inst_nmi_mret; +wire regs_iui_mie; +wire regs_spswap_en; +wire regs_swap_int_sp_en_gate; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire rtu_cp0_fp_dirty_vld; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_mie_en; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_nmi_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire [31:0] rtu_cp0_tval; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire sd; +wire [7 :0] spec_mil; +wire [7 :0] spec_mpil; +wire swap_int_sp; +wire [31:0] tcip_cp0_clic_base; +wire [1 :0] trap_csr_pm; +wire [29:0] vec_adder_vbr; +wire [11:0] vec_adder_vec; +wire [1 :0] xs; + + +//========================================================== +// Trap Setup and Handling CSR Module +// 1. Trap Setup CSRs +// 2. Trap Handling CSRs +//========================================================== + +//---------------------------------------------------------- +// 1. Trap Setup CSRs +//---------------------------------------------------------- +//========================================================== +// Define the MSTATUS register +//========================================================== +// Machine Status Register +// 32-bit Machine Mode Read/Write +// Providing the CPU Status +// the definiton for MSTATUS register is listed as follows +// ======================================================== +// |31|30 22|21| 20| 19| 18| 17 |16 15| +// +--+-----+-----+-----+---+---+--+---+---+---+----+-----+ +// |SD| Res | Res |MPRV| Res | +// ======================================================== +// ======================================================== +// |14 13|12 11|10 9| 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | +// +-----+-----+----+---+----+---+----+---+---+---+---+---+ +// | FS | MPP | Res|Res|MPIE|Res| Res|Res|MIE|Res|Res|Res| +// ======================================================== +assign sd = fs[1:0] == 2'b11 || xs[1:0] == 2'b11; + +assign xs[1:0] = 2'b0; + +assign fs_dirty_upd = (rtu_cp0_fp_dirty_vld || fpu_cp0_wb_fflags_updt) + && (fs[1:0] == 2'b1 || fs[1:0] == 2'b10); +// &Force("output", "fs_dirty_upd"); @61 + +always @(posedge fflags_clk or negedge cpurst_b) +begin + if(!cpurst_b) + fs[1:0] <= 2'b0; + else if(mstatus_local_en || mnxti_local_en) + fs[1:0] <= iui_regs_wdata[14:13]; + else if(fcsr_local_en || frm_local_en || fflags_local_en || fxcr_local_en) + fs[1:0] <= 2'b11; + else if(fs_dirty_upd) + fs[1:0] <= 2'b11; + else + fs[1:0] <= fs[1:0]; +end + +assign fs_off = fs[1:0] == 2'b00; + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + mprv <= 1'b0; + end + else if(mstatus_local_en || mnxti_local_en) + begin + mprv <= iui_regs_wdata[17]; + end + else + begin + mprv <= mprv; + end +end + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mpp[1:0] <= 2'b11; + else if(rtu_yy_xx_expt_vld) + mpp[1:0] <= pm_bypass[1:0]; + else if(regs_inst_nmi_mret) + mpp[1:0] <= nmi_mpp[1:0]; + else if(iui_regs_inst_mret) + mpp[1:0] <= 2'b00; + else if(mstatus_local_en || mnxti_local_en) + mpp[1:0] <= iui_regs_wdata[12:11]; + else if(mcause_local_en) + mpp[1:0] <= iui_regs_wdata[29:28]; + else if(idu_cp0_mcause_wen) + mpp[1:0] <= idu_cp0_ipop_data[29:28]; + else + mpp[1:0] <= mpp[1:0]; +end + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mpie <= 1'b0; + else if(rtu_yy_xx_expt_vld) + mpie <= mie_valid; + else if(regs_inst_nmi_mret) + mpie <= nmi_mpie; + else if(iui_regs_inst_mret) + mpie <= 1'b1; + else if(mstatus_local_en || mnxti_local_en) + mpie <= iui_regs_wdata[7]; + else if(mcause_local_en) + mpie <= iui_regs_wdata[27]; + else if(idu_cp0_mcause_wen) + mpie <= idu_cp0_ipop_data[27]; + else + mpie <= mpie; +end + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mie_bit <= 1'b0; + else if(rtu_yy_xx_expt_vld) + mie_bit <= 1'b0; + else if(iui_regs_inst_mret) + mie_bit <= mpie; + else if(mstatus_local_en || mnxti_local_en) + mie_bit <= iui_regs_wdata_mie; + else if(rtu_cp0_mie_en) + mie_bit <= 1'b1; + else + mie_bit <= mie_bit; +end +assign regs_iui_mie = mie_bit; + +assign mie_valid = (mstatus_local_en || mnxti_local_en) ? iui_regs_wdata_mie + : iui_regs_inst_mret ? mpie : mie_bit; +assign mstatus_value[31:0] = {sd, 13'b0, mprv, xs[1:0], fs[1:0], + mpp[1:0], 3'b0, mpie, 3'b0, mie_bit, 3'b0}; + + +//========================================================== +// Define the MISA register +// Machine Status Register +// 32-bit Machine Mode Read/Write +// Providing the ISA extension infor of the current core +// the definiton for MISA register is listed as follows +//========================================================== +// [31:30] [29:26] [25:0] +// MXL Reserved Extensions +// RV32, MXL is 1. +assign mxl[1:0] = 2'b01; + +// RV32 IMA(FD)C (G) + S Mode + U mode + Non-Standard Ex +// [23] [20] [18] [15] [12] [8] [5] [3] [2] [0] +// X U S P M I F D C A +assign opt_value[7:0] = {4'b0010, 4'b0101}; + +assign dsp_m_value[3:0] = 4'b0001; + +assign extensions[25:0] = {2'b0, 4'b1001, 4'b0000, dsp_m_value[3:0], + 4'b0001, opt_value[7:0]}; +assign misa_value[31:0] = {mxl[1:0], 4'b0, extensions[25:0]}; + + +//========================================================== +// Define the MEDELEG register +// Machine Exception Delegation Register +// 64-bit Machine Mode Read/Write +// Providing the Exception Delegation Status +// the definiton for MEDELEG register is listed as follows +// * Currently not implemented +//========================================================== +assign medeleg_value[31:0] = 32'b0; + + +//========================================================== +// Define the MIDELEG register +// Machine Interrupt Delegation Register +// 64-bit Machine Mode Read/Write +// Providing the Interrupt Delegation Status +// the definiton for MEDELEG register is listed as follows +// * Currently not implemented +//========================================================== +assign mideleg_value[31:0] = 32'b0; + + +//========================================================== +// Define the MIE register +// Machine Interrupt Enable Register +// 31-bit Machine Mode Read/Write +// Providing the Interrupt Local Enable of the current core +// *Hardware to zero when CLIC MODE +// the definiton for MIE register is listed as follows +//========================================================== +assign mie_value[31:0] = 32'b0; + + +//========================================================== +// Define the MTVEC register +// Machine Trap Vector Register +// 31-bit Machine Mode Read/Write +// Providing the Trap Vector Base and Mode +// the definiton for MTVEC register is listed as follows +//========================================================== +assign mtvec_mode[1:0] = 2'b11; + +// Generate the valid vector address +assign vec_adder_vec[11:0] = m_vector[11:0]; + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mtvec_base[29:0] <= 30'b0; + else if(mtvec_local_en) + mtvec_base[29:0] <= {iui_regs_wdata[31:6], 4'b0}; + else + mtvec_base[29:0] <= mtvec_base[29:0]; +end + +assign mtvec_value[31:0] = {mtvec_base[29:0], mtvec_mode[1:0]}; + +assign vec_adder_vbr[29:0] = mtvt_value[31:2] + {18'b0, vec_adder_vec[11:0]}; +assign mtvec_rslt_use_base = !minhv || !m_intr; // Non-Vec mode or expt + +assign mtvec_rslt[29:0] = mtvec_rslt_use_base ? mtvec_base[29:0] + : vec_adder_vbr[29:0]; + + + +//========================================================== +// Define the MCNTEN register +// Machine Trap Vector Register +// 31-bit Machine Mode Read/Write +// Providing the Trap Vector Base and Mode +// the definiton for MTVEC register is listed as follows +// IR, TM, CY +//========================================================== +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mcnten_reg[2:0] <= 3'b0; + else if(mcnten_local_en) + mcnten_reg[2:0] <= iui_regs_wdata[2:0]; + else + mcnten_reg[2:0] <= mcnten_reg[2:0]; +end + +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) begin + mcnten_hpm3 <= 1'b0; + mcnten_hpm4 <= 1'b0; + mcnten_hpm8 <= 1'b0; + mcnten_hpm9 <= 1'b0; + mcnten_hpm13 <= 1'b0; + mcnten_hpm14 <= 1'b0; + mcnten_hpm15 <= 1'b0; + mcnten_hpm16 <= 1'b0; + mcnten_hpm17 <= 1'b0; + end + else if(mcnten_local_en) begin + mcnten_hpm3 <= iui_regs_wdata[3]; + mcnten_hpm4 <= iui_regs_wdata[4]; + mcnten_hpm8 <= iui_regs_wdata[8]; + mcnten_hpm9 <= iui_regs_wdata[9]; + mcnten_hpm13 <= iui_regs_wdata[13]; + mcnten_hpm14 <= iui_regs_wdata[14]; + mcnten_hpm15 <= iui_regs_wdata[15]; + mcnten_hpm16 <= iui_regs_wdata[16]; + mcnten_hpm17 <= iui_regs_wdata[17]; + end +end + +assign mcnten_hpm[28:0] = {14'b0, mcnten_hpm17, mcnten_hpm16, mcnten_hpm15, + mcnten_hpm14, mcnten_hpm13, 3'b0, mcnten_hpm9, + mcnten_hpm8, 3'b0, mcnten_hpm4, mcnten_hpm3}; + +assign mcnten_value[31:0] = {mcnten_hpm[28:0], mcnten_reg[2:0]}; + + +//========================================================== +// Define the MTVEC register +// Machine Trap Vector Register +// 31-bit Machine Mode Read/Write +// Providing the Base Addres of Trap Vector Table +// the definiton for MTVEC register is listed as follows +//========================================================== +always @(posedge regs_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mtvt_base[25:0] <= 26'b0; + else if(mtvt_local_en) + mtvt_base[25:0] <= iui_regs_wdata[31:6]; + else + mtvt_base[25:0] <= mtvt_base[25:0]; +end + +assign mtvt_value[31:0] = {mtvt_base[25:0], 6'b0}; +// &Force("output", "mtvt_value"); @392 + +//========================================================== +// Define the MSCRATCH register +// Machine Scratch Register +// 31-bit Machine Mode Read/Write +// Providing the Software Scratch register +// the definiton for MSCRATCH register is listed as follows +//========================================================== +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mscratch[31:0] <= 32'b0; + else if(mscratch_local_en) + mscratch[31:0] <= iui_regs_wdata[31:0]; + else if(mscratch_swap_int_sp_en) + mscratch[31:0] <= idu_cp0_sp_reg[31:0]; + else if(mscratchcsw_swap_en || mscratchcswl_swap_en) + mscratch[31:0] <= iui_regs_wdata[31:0]; + else + mscratch[31:0] <= mscratch[31:0]; +end +assign mscratch_value[31:0] = mscratch[31:0]; + + +//========================================================== +// Define the MEPC register +// Machine Exception PC Register +// 32-bit Machine Mode Read/Write +// Providing the Machine Exception PC Register +// the definiton for MEPC register is listed as follows +//========================================================== +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mepc_reg[31:0] <= 32'b0; + else if(rtu_yy_xx_expt_vld) + mepc_reg[31:0] <= rtu_cp0_epc[31:0]; + else if(regs_inst_nmi_mret) + mepc_reg[31:0] <= {nmi_pc_31_1[30:0], 1'b0}; + else if(mepc_local_en) + mepc_reg[31:0] <= {iui_regs_wdata[31:1], 1'b0}; + else if(idu_cp0_mepc_wen) + mepc_reg[31:0] <= {idu_cp0_ipop_data[31:1], 1'b0}; + else + mepc_reg[31:0] <= mepc_reg[31:0]; +end +// &Force("bus", "idu_cp0_ipop_data", 31, 0); @441 + +assign mepc_value[31:0] = mepc_reg[31:0]; + + +//========================================================== +// Define the MCAUSE register +// Machine CAUSE Register +// 32-bit Machine Mode Read/Write +// Providing the Machine Trap Cause register +// the definiton for MCAUSE register is listed as follows +//========================================================== +// &Force("output", "mcause_value"); @453 +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + m_intr <= 1'b0; + else if(rtu_yy_xx_expt_vld) + m_intr <= rtu_yy_xx_expt_int; + else if(regs_inst_nmi_mret) + m_intr <= nmi_intr; + else if(mcause_local_en) + m_intr <= iui_regs_wdata[31]; + else if(idu_cp0_mcause_wen) + m_intr <= idu_cp0_ipop_data[31]; + else if(rtu_yy_xx_tail_int_vld || idu_yy_xx_tail_ack) + // rtu_yy_xx_tail_int_vld is for vector addr. and it will be overwrite + // immidately + m_intr <= 1'b1; + else + m_intr <= m_intr; +end + +assign int_mret_vld = iui_regs_inst_mret && m_intr; + +assign hw_vector_clic_on = (mtvec_mode[1:0] == 2'b11 && rtu_yy_xx_int_hv) + && rtu_yy_xx_expt_int && rtu_yy_xx_expt_vld; +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + minhv <= 1'b0; + else if(mtvec_mode[1] == 1'b0) // Orignal vec mode + minhv <= 1'b0; + else if(mcause_local_en) + minhv <= iui_regs_wdata[30]; + else if(idu_cp0_mcause_wen) + minhv <= idu_cp0_ipop_data[30]; + else if(hw_vector_clic_on) // CLIC mode + minhv <= 1'b1; + else if(rtu_yy_xx_tail_int_vld) + minhv <= mtvec_mode[1:0] == 2'b11 && minhv_tail; + else if(ifu_cp0_vec_succeed) + minhv <= 1'b0; +end + +// minhv_tail is for clic tail_ack to judge last int is hv or non-hv. +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + minhv_tail <= 1'b0; + else if(mtvec_mode[1] == 1'b0) // Orignal vec mode + minhv_tail <= 1'b0; + else if(idu_cp0_id_tail_vld) + minhv_tail <= rtu_cp0_pending_int_hv; +end + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mpil[7:0] <= 8'b0; + else if(mtvec_mode[1] == 1'b0) + mpil[7:0] <= 8'b0; + else if(rtu_yy_xx_expt_int) + mpil[7:0] <= mil_val[7:0]; + else if(mcause_local_en) + mpil[7:0] <= iui_regs_wdata[23:16]; + else if(idu_cp0_mcause_wen) + mpil[7:0] <= idu_cp0_ipop_data[23:16]; + else + mpil[7:0] <= mpil[7:0]; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + m_vector_tail[11:0] <= 12'b0; + else if (idu_cp0_id_tail_vld) + m_vector_tail[11:0] <= rtu_cp0_pending_int_id[11:0]; +end + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + m_vector[11:0] <= 12'b0; + else if(rtu_yy_xx_expt_vld) + m_vector[11:0] <= rtu_yy_xx_expt_vec[11:0]; + else if(ifu_cp0_vec_err) + m_vector[11:0] <= 12'd1; + else if(regs_inst_nmi_mret) + m_vector[11:0] <= nmi_vector[11:0]; + else if(mcause_local_en) + m_vector[11:0] <= iui_regs_wdata[11:0]; + else if(idu_cp0_mcause_wen) + m_vector[11:0] <= idu_cp0_ipop_data[11:0]; + else if(mnxti_local_en && mnxti_vld_int_pending) + m_vector[11:0] <= rtu_cp0_pending_int_id[11:0]; + else if(rtu_yy_xx_tail_int_vld || idu_yy_xx_tail_ack) + // rtu_yy_xx_tail_int_vld is for vector addr. and it will be overwrite + // immidately + m_vector[11:0] <= m_vector_tail[11:0]; + else + m_vector[11:0] <= m_vector[11:0]; +end + +assign mcause_value[31:0] = mtvec_mode[1] ? + {m_intr, minhv, mpp[1:0], mpie, 3'b0, + mpil[7:0], 4'b0, m_vector[11:0]} + : {m_intr, 27'b0, m_vector[3:0]}; +assign mcause_spec_value[31:0] = {m_intr, 1'b0, mpp[1:0], mpie, 3'b0, + mpil[7:0], 4'b0, m_vector[11:0]}; +assign mcause_bypass_value[31:0] = {1'b1, 1'b0, pm[1:0], mie_bit, 3'b0, + mil[7:0], 4'b0, rtu_yy_xx_expt_vec[11:0]}; + +assign regs_inst_nmi_mret = iui_regs_inst_mret && regs_cpu_in_nmi; +//========================================================== +// Define the MTVAL register +// Machine Trap value Register +// 32-bit Machine Mode Read/Write +// Providing the trap value register +// the definiton for MTVAL register is listed as follows +//========================================================== + +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mtval_data[31:0] <= 32'b0; + else if(rtu_yy_xx_expt_vld && !rtu_cp0_nmi_vld) + mtval_data[31:0] <= rtu_cp0_tval[31:0]; + else if(ifu_cp0_vec_err) + mtval_data[31:0] <= {vec_adder_vbr[29:0], 2'b0}; + else if(mtval_local_en) + mtval_data[31:0] <= iui_regs_wdata[31:0]; + else + mtval_data[31:0] <= mtval_data[31:0]; +end +assign mtval_value[31:0] = mtval_data[31:0]; + + +//========================================================== +// Define the MIP register +// Machine Interrupt Pending Register +// 32-bit Machine Mode Read/Write +// Providing the Interrupt Pending of the current core +// the definiton for MIP register is listed as follows +//========================================================== +assign mip_value[31:0] = 32'b0; + + +//========================================================== +// Define the MNXTI register +// Machine Next Interrupt Handler Address and Interrupt +// -Enable CSR +// 32-bit Machine Mode Read/Write +// Providing the Next Interrupt Information +// the definiton for MIP register is listed as follows +//========================================================== +assign mnxti_vld_int_pending = rtu_cp0_mnxti_pending_vld; +assign mnxti_pending_addr[29:0] = mtvt_value[31:2] + {18'b0, rtu_cp0_pending_int_id[11:0]}; +assign mnxti_value[31:0] = mnxti_vld_int_pending ? {mnxti_pending_addr[29:0], 2'b0} + : 32'b0; + +//========================================================== +// Define the MINTSTATUS register +// Machine Interrupt Status Register +// 32-bit Machine Mode Read/Write +// Providing the Interrupt Pending Level Status +// the definiton for MIP register is listed as follows +//========================================================== +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mil_tail[7:0] <= 8'b0; + else if (idu_cp0_id_tail_vld) + mil_tail[7:0] <= rtu_cp0_pending_int_level[7:0]; +end +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mil[7:0] <= 8'b0; + else if(!mtvec_mode[1]) + mil[7:0] <= 8'b0; + else if(rtu_yy_xx_expt_int && rtu_yy_xx_expt_vld) + mil[7:0] <= rtu_cp0_int_level[7:0]; + else if(int_mret_vld) + mil[7:0] <= mpil[7:0]; + else if(mnxti_local_en && mnxti_vld_int_pending) + mil[7:0] <= rtu_cp0_pending_int_level[7:0]; + else if(idu_yy_xx_tail_ack) + mil[7:0] <= mil_tail[7:0]; + else + mil[7:0] <= mil[7:0]; +end +assign mintstatus_value[31:0] = {mil[7:0], 24'b0}; + +assign mil_val[7:0] = int_mret_vld ? mpil[7:0] : mil[7:0]; + + +//========================================================== +// Define the MSCRATCHCSW register +// Machine Scratch Swap Register +// 32-bit Machine Mode Read/Write +// Providing the optional Swap Scratch Register +// the definiton for MIP register is listed as follows +//========================================================== +assign mscratchcsw_swap_en = mscratchcsw_local_en && mpp[1:0] != pm[1:0]; +assign mscratchcsw_value[31:0] = mscratchcsw_swap_en ? mscratch[31:0] + : iui_regs_wdata_rs1[31:0]; + + +//========================================================== +// Define the MSCRATCHCSWL register +// Machine Scratch Swap Register for interrupt Levels +// 32-bit Machine Mode Read/Write +// Providing the optional Swap Scratch Register for Levels +// the definiton for MIP register is listed as follows +//========================================================== +assign spec_mil[7:0] = rtu_yy_xx_expt_int ? rtu_cp0_int_level[7:0] : mil[7:0]; +assign spec_mpil[7:0] = rtu_yy_xx_expt_int ? mil[7:0] : mpil[7:0]; + +assign swap_int_sp = (spec_mil[7:0] == 8'b0) ^ (spec_mpil[7:0] == 8'b0); +assign mscratchcswl_swap_en = mscratchcswl_local_en && swap_int_sp; +assign mscratchcswl_value[31:0] = mscratchcswl_swap_en ? mscratch[31:0] + : iui_regs_wdata_rs1[31:0]; + +assign ipush_sp_use_mscratch = (rtu_yy_xx_expt_int || idu_cp0_sp_swap_pending) + && swap_int_sp && regs_spswap_en; + +assign mscratch_swap_int_sp_en = (idu_cp0_sp_swap_req + || int_mret_vld) + && regs_spswap_en && swap_int_sp; +assign mscratch_swap_int_sp_en_gate = (idu_cp0_sp_swap_req_gate + || int_mret_vld) + && regs_spswap_en && swap_int_sp; +assign regs_swap_int_sp_en_gate = mscratch_swap_int_sp_en_gate; + + + +//========================================================== +// Define the MCLICBASE register +// Machine Interrupt Pending Register +// 32-bit Machine Mode Read/Write +// Providing the Base Address of CLIC Memory Map Region +// the definiton for MIP register is listed as follows +//========================================================== +assign mclicbase_value[31:0] = tcip_cp0_clic_base[31:0]; + + +//========================================================== +// Define the MXSTATUS register +// Machine Extension Status register +// 32-bit Machine Mode Read/Write +// Providing the C-SKY Extension Status of the current core +// the definiton for MXSTATUS register is listed as follows +//========================================================== +always @(posedge regs_flush_clk or negedge cpurst_b) +begin + if(!cpurst_b) + pm[1:0] <= 2'b11; + else if(rtu_cp0_exit_debug) + pm[1:0] <= dtu_cp0_dcsr_prv[1:0]; + else if(rtu_yy_xx_expt_vld) + pm[1:0] <= 2'b11; + else if(iui_regs_inst_mret) + pm[1:0] <= mpp[1:0]; + else + pm[1:0] <= pm[1:0]; +end + +assign pm_bypass[1:0] = iui_regs_inst_mret ? mpp[1:0] + : pm[1:0]; + +always @(posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mm <= 1'b1; + else if(mxstatus_local_en) + mm <= iui_regs_wdata[15]; + else + mm <= mm; +end + +always @(posedge regs_clk or negedge cpurst_b) +begin + if (!cpurst_b) + begin + cskyisaee <= 1'b1; + pmdm <= 1'b0; + pmdu <= 1'b0; + end + else if(mxstatus_local_en) + begin + cskyisaee <= iui_regs_wdata[22]; + pmdm <= iui_regs_wdata[13]; + pmdu <= iui_regs_wdata[10]; + end + else + begin + cskyisaee <= cskyisaee; + pmdm <= pmdm; + pmdu <= pmdu; + end +end +assign mxstatus_value[31:0] = {pm[1:0], 7'b0, cskyisaee, 4'b0, + 1'b0, 1'b0, mm, 1'b0, pmdm, + 2'b0, pmdu, 2'b0, 8'b0}; + +//========================================================== +// Define the MNMICAUSE register +// Machine Extension Status register +// 32-bit Machine Mode Read/Write +// Providing the C-SKY Extension Status of the current core +// the definiton for MXSTATUS register is listed as follows +//========================================================== +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nmi_intr <= 1'b0; + else if (rtu_cp0_nmi_vld) + nmi_intr <= m_intr; + else if (mnmicause_local_en) + nmi_intr <= iui_regs_wdata[31]; + else + nmi_intr <= nmi_intr; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nmi_mpp[1:0] <= 2'b0; + else if (rtu_cp0_nmi_vld) + nmi_mpp[1:0] <= mpp[1:0]; + else if (regs_inst_nmi_mret) + nmi_mpp[1:0] <= 2'b0; + else if (mnmicause_local_en) + nmi_mpp[1:0] <= iui_regs_wdata[29:28]; + else + nmi_mpp[1:0] <= nmi_mpp[1:0]; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nmi_mpie <= 1'b0; + else if (rtu_cp0_nmi_vld) + nmi_mpie <= mpie; + else if (regs_inst_nmi_mret) + nmi_mpie <= 1'b1; + else if (mnmicause_local_en) + nmi_mpie <= iui_regs_wdata[27]; + else + nmi_mpie <= nmi_mpie; +end + +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nmi_vector[11:0] <= 12'b0; + else if (rtu_cp0_nmi_vld) + nmi_vector[11:0] <= m_vector[11:0]; + else if (mnmicause_local_en) + nmi_vector[11:0] <= iui_regs_wdata[11:0]; + else + nmi_vector[11:0] <= nmi_vector[11:0]; +end + +assign mnmicause_value[31:0] = {nmi_intr, 1'b0, nmi_mpp[1:0], nmi_mpie, + 3'b0, 8'b0, 4'b0, nmi_vector[11:0]}; + +//========================================================== +// Define the MNMIPC register +// Machine Extension Status register +// 32-bit Machine Mode Read/Write +// Providing the C-SKY Extension Status of the current core +// the definiton for MXSTATUS register is listed as follows +//========================================================== +always @ (posedge regs_flush_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nmi_pc_31_1[30:0] <= 31'b0; + else if (mnmipc_local_en) + nmi_pc_31_1[30:0] <= iui_regs_wdata[31:1]; + else if (rtu_cp0_nmi_vld) + nmi_pc_31_1[30:0] <= mepc_reg[31:1]; + else + nmi_pc_31_1[30:0] <= nmi_pc_31_1[30:0]; +end + +assign mnmipc_value[31:0] = {nmi_pc_31_1[30:0], 1'b0}; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to CP0 +assign regs_cpu_in_int = m_intr; +assign trap_csr_pm[1:0] = pm[1:0]; + +// Output to RTU +assign cp0_dtu_int_id[11:0] = m_vector_tail[11:0]; +assign cp0_rtu_tail_int_id[11:0] = m_vector_tail[11:0]; +assign cp0_rtu_tail_int_hv = minhv_tail; +assign cp0_rtu_int_level[7:0] = mil_val[7:0]; +assign cp0_rtu_int_mode[1:0] = mtvec_mode[1:0]; +assign cp0_rtu_mpil[7:0] = mpil[7:0]; +assign cp0_rtu_mnxti_vld = mnxti_local_en && mnxti_vld_int_pending; +assign cp0_rtu_mie = mie_valid; +assign cp0_rtu_pm_bypass[1:0] = pm_bypass[1:0]; +assign cp0_rtu_in_nmi = regs_cpu_in_nmi; + +assign cp0_yy_cskyisaee = cskyisaee; +assign cp0_lsu_mm = mm; + +assign cp0_pmp_mstatus_mprv = rtu_yy_xx_dbgon ? dtu_cp0_dcsr_mprven && mprv : mprv; +assign cp0_pmp_mstatus_mpp[1:0] = mpp[1:0]; +// &Force("input","dtu_cp0_dcsr_mprven"); @929 + +assign cp0_idu_fs[1:0] = fs[1:0]; +assign regs_fs_off = fs_off; + +assign cp0_dtu_mexpt_vld = rtu_yy_xx_expt_vld; + +assign cp0_idu_sp_wen = mscratch_swap_int_sp_en; +assign cp0_idu_sp_wen_gate = mscratch_swap_int_sp_en_gate; +assign cp0_idu_sp_use_scratch = ipush_sp_use_mscratch; +assign cp0_idu_sp_wdata[31:0] = mscratch[31:0]; +assign cp0_idu_mepc[31:0] = rtu_yy_xx_expt_int ? rtu_cp0_epc[31:0] : mepc_reg[31:0]; +assign cp0_idu_mcause[31:0] = rtu_yy_xx_expt_int ? mcause_bypass_value[31:0] : mcause_spec_value[31:0]; + +assign cp0_hpcp_pmdm = pmdm; +assign cp0_hpcp_pmdu = pmdu; + + +// &ModuleEnd; @958 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/cpu_cfig.h b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/cpu_cfig.h new file mode 100644 index 0000000000000000000000000000000000000000..b46523bf07fd5d5c197d3d4986c05ea59ba1409b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/cpu_cfig.h @@ -0,0 +1,674 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + + + + + + + + + + + + + + + + + + + + +`define PRODUCT_ID 12'h000 + + + + + +`define RESET_VAL 16'hABCD + + + + +`define E906 + + + + + +`ifdef E906 +`define REVISION 4'd2 +`define SUB_VERSION 6'd2 +`define PATCH 6'd2 +`endif + + + + + + + + +`define FPGA + + + + + + + + + + + + + + + + +`define NEW_DFT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`define BHT +`ifdef BHT + //`define BHT_2K + //`define BHT_4K + `define BHT_8K + //`define BHT_16K +`endif + + + + +`define BTB + + + + +`define RAS + + + + +`define CLIC_MODE + + + + + + + + + + + + + +`define HARDWARE_STACK + + + + + + + + + +`define LS_MISALIGN + + + + +`define FPU + + +`ifdef FPU_DOUBLE + `define FLEN 64 +`else + `define FLEN 32 +`endif + + + + + + + + + + + + +`ifdef E906 + `define IAHB_LITE + `define DAHB_LITE +`endif + +`ifdef IAHB_LITE + //`define FLOP_OUT_IBUS + `define IBUS_32 +`endif + +`ifdef DAHB_LITE + //`define FLOP_OUT_DBUS + `define DBUS_32 +`endif + + + + + + +`define SYS_AHB_LITE +`define BIU_32 + + + + +`define FLOP_OUT_BIU + + + + +`define PMP + +`ifdef PMP + //`define PMP_REGION_4 + `define PMP_REGION_8 + //`define PMP_REGION_12 + //`define PMP_REGION_16 +`endif + + + + + +`define ICACHE +`define DCACHE + +`ifdef ICACHE + + + + `define ICACHE_16K + +`endif + + + +`ifdef DCACHE + + + //`define DCACHE_8K + `define DCACHE_16K + + +`endif + + + + +`define TCIPIF + +`define DYNAMIC_SYSMAP + +`ifdef CLIC_MODE + // Attention: + // 1. EXT_INT_NUM *MUST* > 0. + // 2. If you don't want to use extensional clic int, use //`define EXT_INT_NUM rather than change EXT_INT_NUM to 0. + // 3. If EXT_INT_NUM > 48, you need define CLIC_2_CYCLES unless the timing is loose. + // 4. Don't change definition of CLIC_INTNUM. + + `define CLIC_2_CYCLES + //`define U_MODE_INT + `define CLIC_INTCTLBITS 3 + `define EXT_INT_NUM 128 + + `ifdef EXT_INT_NUM + `define CLIC_INTNUM `EXT_INT_NUM+16 + `else + `define CLIC_INTNUM 16 + `endif +`endif + + + + + + + + + + +`define PMU + + + + +`define THEAD_IP + + + + +`define TDT_DEBUG + + + + + + + + + + + + +`define TDT_DM_PB_EN + + + + +`ifdef TDT_DM_PB_EN + `define TDT_DM_IEBREAK + `define TDT_DM_PB_SIZE 2 +`endif + + + + + + + + + +`ifdef TDT_DM_EXT_TRIGGER_EN + //`define TDT_DM_EXTHALTTRI_4 + //`define TDT_DM_EXTHALTTRI_3 + //`define TDT_DM_EXTHALTTRI_2 + `define TDT_DM_EXTHALTTRI_1 + + //`define TDT_DM_EXTRESUMETRI_4 + //`define TDT_DM_EXTRESUMETRI_3 + //`define TDT_DM_EXTRESUMETRI_2 + `define TDT_DM_EXTRESUMETRI_1 +`endif + + + + + +`define TDT_DM_NEXTDM_BA 32'h00000000 + + + + + + + + + + +`define TDT_TM_TYPICAL + + + + + + +`define TDT_DEBUG_PCFIFO + + +`ifdef TDT_DEBUG_PCFIFO + `define TDT_DEBUG_PCFIFO_8_ENTRY + //`define TDT_DEBUG_PCFIFO_16_ENTRY +`endif + + + + +`define TDT_DEBUG_INFO + + + + + +`define TDT_SYSAPB_ASYNC_CLK + + + + + + + + + +`ifdef BHT_2K + `define BHT_IDX_WIDTH 7 +`endif + +`ifdef BHT_4K + `define BHT_IDX_WIDTH 8 +`endif + +`ifdef BHT_8K + `define BHT_IDX_WIDTH 9 +`endif + +`ifdef BHT_16K + `define BHT_IDX_WIDTH 10 +`endif + + + + + + +`ifdef E906 + `define AHB_LITE +`endif + + + + + + + +`ifdef PMP_REGION_2 + `define REGION_ENTRY0 + `define REGION_ENTRY1 +`endif + +`ifdef PMP_REGION_4 + `define REGION_ENTRY0 + `define REGION_ENTRY1 + `define REGION_ENTRY2 + `define REGION_ENTRY3 +`endif + +`ifdef PMP_REGION_8 + `define REGION_ENTRY0 + `define REGION_ENTRY1 + `define REGION_ENTRY2 + `define REGION_ENTRY3 + `define REGION_ENTRY4 + `define REGION_ENTRY5 + `define REGION_ENTRY6 + `define REGION_ENTRY7 +`endif + +`ifdef PMP_REGION_12 + `define REGION_ENTRY0 + `define REGION_ENTRY1 + `define REGION_ENTRY2 + `define REGION_ENTRY3 + `define REGION_ENTRY4 + `define REGION_ENTRY5 + `define REGION_ENTRY6 + `define REGION_ENTRY7 + `define REGION_ENTRY8 + `define REGION_ENTRY9 + `define REGION_ENTRY10 + `define REGION_ENTRY11 +`endif + +`ifdef PMP_REGION_16 + `define REGION_ENTRY0 + `define REGION_ENTRY1 + `define REGION_ENTRY2 + `define REGION_ENTRY3 + `define REGION_ENTRY4 + `define REGION_ENTRY5 + `define REGION_ENTRY6 + `define REGION_ENTRY7 + `define REGION_ENTRY8 + `define REGION_ENTRY9 + `define REGION_ENTRY10 + `define REGION_ENTRY11 + `define REGION_ENTRY12 + `define REGION_ENTRY13 + `define REGION_ENTRY14 + `define REGION_ENTRY15 +`endif + + + + + +`ifdef ICACHE_2K + `define I_TAG_INDEX_WIDTH 5 + `define I_TAG_TAG_WIDTH 22 +`endif + +`ifdef ICACHE_4K + `define I_TAG_INDEX_WIDTH 6 + `define I_TAG_TAG_WIDTH 21 +`endif + +`ifdef ICACHE_8K + `define I_TAG_INDEX_WIDTH 7 + `define I_TAG_TAG_WIDTH 20 +`endif + +`ifdef ICACHE_16K + `define I_TAG_INDEX_WIDTH 8 + `define I_TAG_TAG_WIDTH 19 +`endif + +`ifdef ICACHE_32K + `define I_TAG_INDEX_WIDTH 9 + `define I_TAG_TAG_WIDTH 18 +`endif + +`ifdef ICACHE_64K + `define I_TAG_INDEX_WIDTH 10 + `define I_TAG_TAG_WIDTH 17 +`endif + + + + + +`ifdef DCACHE_2K + `define D_TAG_INDEX_WIDTH 5 + `define D_TAG_TAG_WIDTH 22 + `define D_DATA_INDEX_WIDTH 7 +`endif + +`ifdef DCACHE_4K + `define D_TAG_INDEX_WIDTH 6 + `define D_TAG_TAG_WIDTH 21 + `define D_DATA_INDEX_WIDTH 8 +`endif + +`ifdef DCACHE_8K + `define D_TAG_INDEX_WIDTH 7 + `define D_TAG_TAG_WIDTH 20 + `define D_DATA_INDEX_WIDTH 9 +`endif + +`ifdef DCACHE_16K + `define D_TAG_INDEX_WIDTH 8 + `define D_TAG_TAG_WIDTH 19 + `define D_DATA_INDEX_WIDTH 10 +`endif + +`ifdef DCACHE_32K + `define D_TAG_INDEX_WIDTH 9 + `define D_TAG_TAG_WIDTH 18 + `define D_DATA_INDEX_WIDTH 11 +`endif + +`ifdef DCACHE_64K + `define D_TAG_INDEX_WIDTH 10 + `define D_TAG_TAG_WIDTH 17 + `define D_DATA_INDEX_WIDTH 12 +`endif + + + +`ifdef IAHBL_ICACHE_2K + `define IC_TAG_TAG_LENGTH 22 + `define IC_TAG_LINE_LENGTH 47 + `define IC_TAG_INDEX_LENGTH 5 + `define IC_DATA_INDEX_LENGTH 8 +`endif + +`ifdef IAHBL_ICACHE_4K + `define IC_TAG_TAG_LENGTH 21 + `define IC_TAG_LINE_LENGTH 45 + `define IC_TAG_INDEX_LENGTH 6 + `define IC_DATA_INDEX_LENGTH 9 +`endif + +`ifdef IAHBL_ICACHE_8K + `define IC_TAG_TAG_LENGTH 20 + `define IC_TAG_LINE_LENGTH 43 + `define IC_TAG_INDEX_LENGTH 7 + `define IC_DATA_INDEX_LENGTH 10 +`endif + +`ifdef IAHBL_ICACHE_16K + `define IC_TAG_TAG_LENGTH 19 + `define IC_TAG_LINE_LENGTH 41 + `define IC_TAG_INDEX_LENGTH 8 + `define IC_DATA_INDEX_LENGTH 11 +`endif + +`ifdef IAHBL_ICACHE_32K + `define IC_TAG_TAG_LENGTH 18 + `define IC_TAG_LINE_LENGTH 39 + `define IC_TAG_INDEX_LENGTH 9 + `define IC_DATA_INDEX_LENGTH 12 +`endif + +`ifdef IAHBL_ICACHE_64K + `define IC_TAG_TAG_LENGTH 17 + `define IC_TAG_LINE_LENGTH 37 + `define IC_TAG_INDEX_LENGTH 10 + `define IC_DATA_INDEX_LENGTH 13 +`endif + + + + + + +`ifdef TDT_DM_SBA + `ifdef E907 + `define TDT_DM_SBA_AXI + `endif + `ifdef E906 + `define TDT_DM_SBA_AHB + `endif +`endif + + + + + + + + + + + + + +`define PA_WIDTH 32 +`define VA_WIDTH 31 + + + + + +`define INDEPENDENT_AXI_SLAVE_ENV +`define INDEPENDENT_AXI_SLAVE_64 +`define AXI_SLV_AGENT_NUM 2 + + + + + +`define TDT_DM_CORE_RV32 + +`define TDT_DM_CORE_NSCRATCH 4'h2 + + + + + + +`ifdef TDT_DM_SBA + //`define TDT_DM_SBA_DW_128 + `ifdef TDT_DM_SBA_AXI + `define TDT_DM_SBA_DW_64 + `endif + `ifdef TDT_DM_SBA_AHB + `define TDT_DM_SBA_DW_32 + `endif + + `ifdef TDT_DM_SBA_AHB + `define TDT_DM_SBAW `PA_WIDTH + `else + `define TDT_DM_SBAW `PA_WIDTH + `endif +`endif + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/openE906.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/openE906.v new file mode 100644 index 0000000000000000000000000000000000000000..62de219652376f2cf2bcfc8a74d072d245b4f5d4 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/openE906.v @@ -0,0 +1,725 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @33 +module openE906( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hlock, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwdata, + biu_pad_hwrite, + clk_en, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cpu_pad_dfs_ack, + cpu_pad_halted, + cpu_pad_lockup, + cpu_pad_soft_rst, + dahbl_pad_haddr, + dahbl_pad_hburst, + dahbl_pad_hlock, + dahbl_pad_hprot, + dahbl_pad_hsize, + dahbl_pad_htrans, + dahbl_pad_hwdata, + dahbl_pad_hwrite, + iahbl_pad_haddr, + iahbl_pad_hburst, + iahbl_pad_hlock, + iahbl_pad_hprot, + iahbl_pad_hsize, + iahbl_pad_htrans, + iahbl_pad_hwdata, + iahbl_pad_hwrite, + pad_biu_hrdata, + pad_biu_hready, + pad_biu_hresp, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_clic_int_vld, + pad_cpu_dfs_req, + pad_cpu_ext_int_b, + pad_cpu_nmi, + pad_cpu_rst_addr, + pad_cpu_rst_b, + pad_cpu_sys_cnt, + pad_cpu_sysmap_addr0, + pad_cpu_sysmap_addr0_attr, + pad_cpu_sysmap_addr1, + pad_cpu_sysmap_addr1_attr, + pad_cpu_sysmap_addr2, + pad_cpu_sysmap_addr2_attr, + pad_cpu_sysmap_addr3, + pad_cpu_sysmap_addr3_attr, + pad_cpu_sysmap_addr4, + pad_cpu_sysmap_addr4_attr, + pad_cpu_sysmap_addr5, + pad_cpu_sysmap_addr5_attr, + pad_cpu_sysmap_addr6, + pad_cpu_sysmap_addr6_attr, + pad_cpu_sysmap_addr7, + pad_cpu_sysmap_addr7_attr, + pad_cpu_tcip_base, + pad_cpu_wakeup_event, + pad_dahbl_hrdata, + pad_dahbl_hready, + pad_dahbl_hresp, + pad_iahbl_hrdata, + pad_iahbl_hready, + pad_iahbl_hresp, + pad_tdt_dm_core_unavail, + pad_yy_dft_clk_rst_b, + pad_yy_icg_scan_en, + pad_yy_scan_enable, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + pll_core_cpuclk, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld, + sys_apb_clk, + sys_apb_rst_b, + sysio_pad_lpmd_b, + tdt_dm_pad_hartreset_n, + tdt_dm_pad_ndmreset_n, + tdt_dmi_paddr, + tdt_dmi_penable, + tdt_dmi_prdata, + tdt_dmi_pready, + tdt_dmi_psel, + tdt_dmi_pslverr, + tdt_dmi_pwdata, + tdt_dmi_pwrite +); + +// &Ports("compare", "../../../gen_rtl/cpu/rtl/pa_cpu_top_golden_port.v"); @34 +input clk_en; +input [31 :0] pad_biu_hrdata; +input pad_biu_hready; +input pad_biu_hresp; +input [11 :0] pad_bmu_dahbl_base; +input [11 :0] pad_bmu_dahbl_mask; +input [11 :0] pad_bmu_iahbl_base; +input [11 :0] pad_bmu_iahbl_mask; +input [127:0] pad_clic_int_vld; +input pad_cpu_dfs_req; +input pad_cpu_ext_int_b; +input pad_cpu_nmi; +input [31 :0] pad_cpu_rst_addr; +input pad_cpu_rst_b; +input [63 :0] pad_cpu_sys_cnt; +input [19 :0] pad_cpu_sysmap_addr0; +input [2 :0] pad_cpu_sysmap_addr0_attr; +input [19 :0] pad_cpu_sysmap_addr1; +input [2 :0] pad_cpu_sysmap_addr1_attr; +input [19 :0] pad_cpu_sysmap_addr2; +input [2 :0] pad_cpu_sysmap_addr2_attr; +input [19 :0] pad_cpu_sysmap_addr3; +input [2 :0] pad_cpu_sysmap_addr3_attr; +input [19 :0] pad_cpu_sysmap_addr4; +input [2 :0] pad_cpu_sysmap_addr4_attr; +input [19 :0] pad_cpu_sysmap_addr5; +input [2 :0] pad_cpu_sysmap_addr5_attr; +input [19 :0] pad_cpu_sysmap_addr6; +input [2 :0] pad_cpu_sysmap_addr6_attr; +input [19 :0] pad_cpu_sysmap_addr7; +input [2 :0] pad_cpu_sysmap_addr7_attr; +input [31 :0] pad_cpu_tcip_base; +input pad_cpu_wakeup_event; +input [31 :0] pad_dahbl_hrdata; +input pad_dahbl_hready; +input pad_dahbl_hresp; +input [31 :0] pad_iahbl_hrdata; +input pad_iahbl_hready; +input pad_iahbl_hresp; +input pad_tdt_dm_core_unavail; +input pad_yy_dft_clk_rst_b; +input pad_yy_icg_scan_en; +input pad_yy_scan_enable; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input pll_core_cpuclk; +input sys_apb_clk; +input sys_apb_rst_b; +input [11 :0] tdt_dmi_paddr; +input tdt_dmi_penable; +input tdt_dmi_psel; +input [31 :0] tdt_dmi_pwdata; +input tdt_dmi_pwrite; +output [31 :0] biu_pad_haddr; +output [2 :0] biu_pad_hburst; +output biu_pad_hlock; +output [3 :0] biu_pad_hprot; +output [2 :0] biu_pad_hsize; +output [1 :0] biu_pad_htrans; +output [31 :0] biu_pad_hwdata; +output biu_pad_hwrite; +output [31 :0] cp0_pad_mcause; +output [31 :0] cp0_pad_mintstatus; +output [31 :0] cp0_pad_mstatus; +output cpu_pad_dfs_ack; +output cpu_pad_halted; +output cpu_pad_lockup; +output [1 :0] cpu_pad_soft_rst; +output [31 :0] dahbl_pad_haddr; +output [2 :0] dahbl_pad_hburst; +output dahbl_pad_hlock; +output [3 :0] dahbl_pad_hprot; +output [2 :0] dahbl_pad_hsize; +output [1 :0] dahbl_pad_htrans; +output [31 :0] dahbl_pad_hwdata; +output dahbl_pad_hwrite; +output [31 :0] iahbl_pad_haddr; +output [2 :0] iahbl_pad_hburst; +output iahbl_pad_hlock; +output [3 :0] iahbl_pad_hprot; +output [2 :0] iahbl_pad_hsize; +output [1 :0] iahbl_pad_htrans; +output [31 :0] iahbl_pad_hwdata; +output iahbl_pad_hwrite; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31 :0] rtu_pad_retire_pc; +output [31 :0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31 :0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31 :0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31 :0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; +output [1 :0] sysio_pad_lpmd_b; +output tdt_dm_pad_hartreset_n; +output tdt_dm_pad_ndmreset_n; +output [31 :0] tdt_dmi_prdata; +output tdt_dmi_pready; +output tdt_dmi_pslverr; + +//&Ports; +// &Regs; @36 + +// &Wires; @37 +wire [31 :0] biu_pad_haddr; +wire [2 :0] biu_pad_hburst; +wire biu_pad_hlock; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire [31 :0] biu_pad_hwdata; +wire biu_pad_hwrite; +wire bmu_tcipif_dbus_acc_deny; +wire [31 :0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31 :0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire bmu_tcipif_ibus_acc_deny; +wire [31 :0] bmu_tcipif_ibus_addr; +wire bmu_tcipif_ibus_req; +wire bmu_tcipif_ibus_req_dp; +wire [1 :0] bmu_tcipif_ibus_size; +wire bmu_tcipif_ibus_supv_mode; +wire [31 :0] bmu_tcipif_ibus_wdata; +wire bmu_tcipif_ibus_write; +wire clic_cpu_int_hv; +wire [11 :0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire clk_en; +wire clk_en_f; +wire cp0_biu_icg_en; +wire [31 :0] cp0_pad_mcause; +wire [31 :0] cp0_pad_mintstatus; +wire [31 :0] cp0_pad_mstatus; +wire [1 :0] cp0_yy_priv_mode; +wire [11 :0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpu_pad_dfs_ack; +wire cpu_pad_halted; +wire cpu_pad_lockup; +wire [1 :0] cpu_pad_soft_rst; +wire cpurst_b; +wire [31 :0] dahbl_pad_haddr; +wire [2 :0] dahbl_pad_hburst; +wire dahbl_pad_hlock; +wire [3 :0] dahbl_pad_hprot; +wire [2 :0] dahbl_pad_hsize; +wire [1 :0] dahbl_pad_htrans; +wire [31 :0] dahbl_pad_hwdata; +wire dahbl_pad_hwrite; +wire dtu_tdt_dm_halted; +wire dtu_tdt_dm_havereset; +wire dtu_tdt_dm_itr_done; +wire dtu_tdt_dm_retire_debug_expt_vld; +wire [31 :0] dtu_tdt_dm_rx_data; +wire dtu_tdt_dm_wr_ready; +wire forever_cpuclk; +wire [31 :0] iahbl_pad_haddr; +wire [2 :0] iahbl_pad_hburst; +wire iahbl_pad_hlock; +wire [3 :0] iahbl_pad_hprot; +wire [2 :0] iahbl_pad_hsize; +wire [1 :0] iahbl_pad_htrans; +wire [31 :0] iahbl_pad_hwdata; +wire iahbl_pad_hwrite; +wire ifu_clic_warm_up; +wire [31 :0] pad_biu_hrdata; +wire pad_biu_hready; +wire pad_biu_hresp; +wire [11 :0] pad_bmu_dahbl_base; +wire [11 :0] pad_bmu_dahbl_mask; +wire [11 :0] pad_bmu_iahbl_base; +wire [11 :0] pad_bmu_iahbl_mask; +wire [127:0] pad_clic_int_vld; +wire pad_cpu_dfs_req; +wire pad_cpu_ext_int_b; +wire pad_cpu_nmi; +wire [31 :0] pad_cpu_rst_addr; +wire pad_cpu_rst_b; +wire [63 :0] pad_cpu_sys_cnt; +wire [19 :0] pad_cpu_sysmap_addr0; +wire [2 :0] pad_cpu_sysmap_addr0_attr; +wire [19 :0] pad_cpu_sysmap_addr1; +wire [2 :0] pad_cpu_sysmap_addr1_attr; +wire [19 :0] pad_cpu_sysmap_addr2; +wire [2 :0] pad_cpu_sysmap_addr2_attr; +wire [19 :0] pad_cpu_sysmap_addr3; +wire [2 :0] pad_cpu_sysmap_addr3_attr; +wire [19 :0] pad_cpu_sysmap_addr4; +wire [2 :0] pad_cpu_sysmap_addr4_attr; +wire [19 :0] pad_cpu_sysmap_addr5; +wire [2 :0] pad_cpu_sysmap_addr5_attr; +wire [19 :0] pad_cpu_sysmap_addr6; +wire [2 :0] pad_cpu_sysmap_addr6_attr; +wire [19 :0] pad_cpu_sysmap_addr7; +wire [2 :0] pad_cpu_sysmap_addr7_attr; +wire [31 :0] pad_cpu_tcip_base; +wire pad_cpu_wakeup_event; +wire [31 :0] pad_dahbl_hrdata; +wire pad_dahbl_hready; +wire pad_dahbl_hresp; +wire [31 :0] pad_iahbl_hrdata; +wire pad_iahbl_hready; +wire pad_iahbl_hresp; +wire pad_tdt_dm_core_unavail; +wire pad_yy_dft_clk_rst_b; +wire pad_yy_icg_scan_en; +wire pad_yy_scan_mode; +wire pad_yy_scan_rst_b; +wire pll_core_cpuclk; +wire rtu_pad_inst_retire; +wire rtu_pad_inst_split; +wire [31 :0] rtu_pad_retire_pc; +wire [31 :0] rtu_pad_wb0_data; +wire [5 :0] rtu_pad_wb0_preg; +wire rtu_pad_wb0_vld; +wire [31 :0] rtu_pad_wb1_data; +wire [5 :0] rtu_pad_wb1_preg; +wire rtu_pad_wb1_vld; +wire [31 :0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +wire [4 :0] rtu_pad_wb_freg; +wire [31 :0] rtu_pad_wb_freg_data; +wire rtu_pad_wb_freg_vld; +wire rtu_yy_xx_dbgon; +wire sync_sys_apb_rst_b; +wire sys_apb_clk; +wire sys_apb_rst_b; +wire sysio_clint_me_int; +wire [63 :0] sysio_clint_mtime; +wire [1 :0] sysio_pad_lpmd_b; +wire sysmap_tcipif_cmplt; +wire [31 :0] sysmap_tcipif_rdata; +wire [31 :0] tcip_cp0_clic_base; +wire tcipif_bmu_dbus_acc_err; +wire [31 :0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_bmu_ibus_acc_err; +wire [31 :0] tcipif_bmu_ibus_data; +wire tcipif_bmu_ibus_grnt; +wire tcipif_bmu_ibus_trans_cmplt; +wire [15 :0] tcipif_sysmap_addr; +wire tcipif_sysmap_sel; +wire [31 :0] tcipif_sysmap_wdata; +wire tcipif_sysmap_write; +wire tdt_dm_dtu_ack_havereset; +wire tdt_dm_dtu_async_halt_req; +wire tdt_dm_dtu_halt_on_reset; +wire tdt_dm_dtu_halt_req; +wire [1 :0] tdt_dm_dtu_halt_req_cause; +wire [31 :0] tdt_dm_dtu_itr; +wire tdt_dm_dtu_itr_vld; +wire tdt_dm_dtu_resume_req; +wire [31 :0] tdt_dm_dtu_wdata; +wire [1 :0] tdt_dm_dtu_wr_flg; +wire tdt_dm_dtu_wr_vld; +wire tdt_dm_pad_hartreset_n; +wire tdt_dm_pad_ndmreset_n; +wire [11 :0] tdt_dmi_paddr; +wire tdt_dmi_penable; +wire [31 :0] tdt_dmi_prdata; +wire tdt_dmi_pready; +wire tdt_dmi_psel; +wire tdt_dmi_pslverr; +wire [31 :0] tdt_dmi_pwdata; +wire tdt_dmi_pwrite; + + +// &Force("input","pad_yy_scan_enable"); @39 +//========================================================== +// Instance 906 core top module +//========================================================== +// &Instance("pa_core_top"); @43 +pa_core_top x_pa_core_top ( + .biu_pad_haddr (biu_pad_haddr ), + .biu_pad_hburst (biu_pad_hburst ), + .biu_pad_hlock (biu_pad_hlock ), + .biu_pad_hprot (biu_pad_hprot ), + .biu_pad_hsize (biu_pad_hsize ), + .biu_pad_htrans (biu_pad_htrans ), + .biu_pad_hwdata (biu_pad_hwdata ), + .biu_pad_hwrite (biu_pad_hwrite ), + .bmu_tcipif_dbus_acc_deny (bmu_tcipif_dbus_acc_deny ), + .bmu_tcipif_dbus_addr (bmu_tcipif_dbus_addr ), + .bmu_tcipif_dbus_req (bmu_tcipif_dbus_req ), + .bmu_tcipif_dbus_req_dp (bmu_tcipif_dbus_req_dp ), + .bmu_tcipif_dbus_size (bmu_tcipif_dbus_size ), + .bmu_tcipif_dbus_supv_mode (bmu_tcipif_dbus_supv_mode ), + .bmu_tcipif_dbus_wdata (bmu_tcipif_dbus_wdata ), + .bmu_tcipif_dbus_write (bmu_tcipif_dbus_write ), + .bmu_tcipif_ibus_acc_deny (bmu_tcipif_ibus_acc_deny ), + .bmu_tcipif_ibus_addr (bmu_tcipif_ibus_addr ), + .bmu_tcipif_ibus_req (bmu_tcipif_ibus_req ), + .bmu_tcipif_ibus_req_dp (bmu_tcipif_ibus_req_dp ), + .bmu_tcipif_ibus_size (bmu_tcipif_ibus_size ), + .bmu_tcipif_ibus_supv_mode (bmu_tcipif_ibus_supv_mode ), + .bmu_tcipif_ibus_wdata (bmu_tcipif_ibus_wdata ), + .bmu_tcipif_ibus_write (bmu_tcipif_ibus_write ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .clk_en_f (clk_en_f ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_pad_mcause (cp0_pad_mcause ), + .cp0_pad_mintstatus (cp0_pad_mintstatus ), + .cp0_pad_mstatus (cp0_pad_mstatus ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpu_pad_dfs_ack (cpu_pad_dfs_ack ), + .cpu_pad_halted (cpu_pad_halted ), + .cpu_pad_lockup (cpu_pad_lockup ), + .cpu_pad_soft_rst (cpu_pad_soft_rst ), + .cpurst_b (cpurst_b ), + .dahbl_pad_haddr (dahbl_pad_haddr ), + .dahbl_pad_hburst (dahbl_pad_hburst ), + .dahbl_pad_hlock (dahbl_pad_hlock ), + .dahbl_pad_hprot (dahbl_pad_hprot ), + .dahbl_pad_hsize (dahbl_pad_hsize ), + .dahbl_pad_htrans (dahbl_pad_htrans ), + .dahbl_pad_hwdata (dahbl_pad_hwdata ), + .dahbl_pad_hwrite (dahbl_pad_hwrite ), + .dtu_tdt_dm_halted (dtu_tdt_dm_halted ), + .dtu_tdt_dm_havereset (dtu_tdt_dm_havereset ), + .dtu_tdt_dm_itr_done (dtu_tdt_dm_itr_done ), + .dtu_tdt_dm_retire_debug_expt_vld (dtu_tdt_dm_retire_debug_expt_vld), + .dtu_tdt_dm_rx_data (dtu_tdt_dm_rx_data ), + .dtu_tdt_dm_wr_ready (dtu_tdt_dm_wr_ready ), + .forever_cpuclk (forever_cpuclk ), + .iahbl_pad_haddr (iahbl_pad_haddr ), + .iahbl_pad_hburst (iahbl_pad_hburst ), + .iahbl_pad_hlock (iahbl_pad_hlock ), + .iahbl_pad_hprot (iahbl_pad_hprot ), + .iahbl_pad_hsize (iahbl_pad_hsize ), + .iahbl_pad_htrans (iahbl_pad_htrans ), + .iahbl_pad_hwdata (iahbl_pad_hwdata ), + .iahbl_pad_hwrite (iahbl_pad_hwrite ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .pad_biu_hrdata (pad_biu_hrdata ), + .pad_biu_hready (pad_biu_hready ), + .pad_biu_hresp (pad_biu_hresp ), + .pad_bmu_dahbl_base (pad_bmu_dahbl_base ), + .pad_bmu_dahbl_mask (pad_bmu_dahbl_mask ), + .pad_bmu_iahbl_base (pad_bmu_iahbl_base ), + .pad_bmu_iahbl_mask (pad_bmu_iahbl_mask ), + .pad_cpu_dfs_req (pad_cpu_dfs_req ), + .pad_cpu_ext_int_b (pad_cpu_ext_int_b ), + .pad_cpu_nmi (pad_cpu_nmi ), + .pad_cpu_rst_addr (pad_cpu_rst_addr ), + .pad_cpu_sys_cnt (pad_cpu_sys_cnt ), + .pad_cpu_sysmap_addr0 (pad_cpu_sysmap_addr0 ), + .pad_cpu_sysmap_addr0_attr (pad_cpu_sysmap_addr0_attr ), + .pad_cpu_sysmap_addr1 (pad_cpu_sysmap_addr1 ), + .pad_cpu_sysmap_addr1_attr (pad_cpu_sysmap_addr1_attr ), + .pad_cpu_sysmap_addr2 (pad_cpu_sysmap_addr2 ), + .pad_cpu_sysmap_addr2_attr (pad_cpu_sysmap_addr2_attr ), + .pad_cpu_sysmap_addr3 (pad_cpu_sysmap_addr3 ), + .pad_cpu_sysmap_addr3_attr (pad_cpu_sysmap_addr3_attr ), + .pad_cpu_sysmap_addr4 (pad_cpu_sysmap_addr4 ), + .pad_cpu_sysmap_addr4_attr (pad_cpu_sysmap_addr4_attr ), + .pad_cpu_sysmap_addr5 (pad_cpu_sysmap_addr5 ), + .pad_cpu_sysmap_addr5_attr (pad_cpu_sysmap_addr5_attr ), + .pad_cpu_sysmap_addr6 (pad_cpu_sysmap_addr6 ), + .pad_cpu_sysmap_addr6_attr (pad_cpu_sysmap_addr6_attr ), + .pad_cpu_sysmap_addr7 (pad_cpu_sysmap_addr7 ), + .pad_cpu_sysmap_addr7_attr (pad_cpu_sysmap_addr7_attr ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .pad_cpu_wakeup_event (pad_cpu_wakeup_event ), + .pad_dahbl_hrdata (pad_dahbl_hrdata ), + .pad_dahbl_hready (pad_dahbl_hready ), + .pad_dahbl_hresp (pad_dahbl_hresp ), + .pad_iahbl_hrdata (pad_iahbl_hrdata ), + .pad_iahbl_hready (pad_iahbl_hready ), + .pad_iahbl_hresp (pad_iahbl_hresp ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_pad_inst_retire (rtu_pad_inst_retire ), + .rtu_pad_inst_split (rtu_pad_inst_split ), + .rtu_pad_retire_pc (rtu_pad_retire_pc ), + .rtu_pad_wb0_data (rtu_pad_wb0_data ), + .rtu_pad_wb0_preg (rtu_pad_wb0_preg ), + .rtu_pad_wb0_vld (rtu_pad_wb0_vld ), + .rtu_pad_wb1_data (rtu_pad_wb1_data ), + .rtu_pad_wb1_preg (rtu_pad_wb1_preg ), + .rtu_pad_wb1_vld (rtu_pad_wb1_vld ), + .rtu_pad_wb2_data (rtu_pad_wb2_data ), + .rtu_pad_wb2_preg (rtu_pad_wb2_preg ), + .rtu_pad_wb2_vld (rtu_pad_wb2_vld ), + .rtu_pad_wb_freg (rtu_pad_wb_freg ), + .rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), + .rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sys_apb_clk (sys_apb_clk ), + .sys_apb_rst_b (sync_sys_apb_rst_b ), + .sysio_clint_me_int (sysio_clint_me_int ), + .sysio_clint_mtime (sysio_clint_mtime ), + .sysio_pad_lpmd_b (sysio_pad_lpmd_b ), + .sysmap_tcipif_cmplt (sysmap_tcipif_cmplt ), + .sysmap_tcipif_rdata (sysmap_tcipif_rdata ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ), + .tcipif_bmu_dbus_acc_err (tcipif_bmu_dbus_acc_err ), + .tcipif_bmu_dbus_data (tcipif_bmu_dbus_data ), + .tcipif_bmu_dbus_grnt (tcipif_bmu_dbus_grnt ), + .tcipif_bmu_dbus_trans_cmplt (tcipif_bmu_dbus_trans_cmplt ), + .tcipif_bmu_ibus_acc_err (tcipif_bmu_ibus_acc_err ), + .tcipif_bmu_ibus_data (tcipif_bmu_ibus_data ), + .tcipif_bmu_ibus_grnt (tcipif_bmu_ibus_grnt ), + .tcipif_bmu_ibus_trans_cmplt (tcipif_bmu_ibus_trans_cmplt ), + .tcipif_sysmap_addr (tcipif_sysmap_addr ), + .tcipif_sysmap_sel (tcipif_sysmap_sel ), + .tcipif_sysmap_wdata (tcipif_sysmap_wdata ), + .tcipif_sysmap_write (tcipif_sysmap_write ), + .tdt_dm_dtu_ack_havereset (tdt_dm_dtu_ack_havereset ), + .tdt_dm_dtu_async_halt_req (tdt_dm_dtu_async_halt_req ), + .tdt_dm_dtu_halt_on_reset (tdt_dm_dtu_halt_on_reset ), + .tdt_dm_dtu_halt_req (tdt_dm_dtu_halt_req ), + .tdt_dm_dtu_itr (tdt_dm_dtu_itr ), + .tdt_dm_dtu_itr_vld (tdt_dm_dtu_itr_vld ), + .tdt_dm_dtu_resume_req (tdt_dm_dtu_resume_req ), + .tdt_dm_dtu_wdata (tdt_dm_dtu_wdata ), + .tdt_dm_dtu_wr_flg (tdt_dm_dtu_wr_flg ), + .tdt_dm_dtu_wr_vld (tdt_dm_dtu_wr_vld ) +); + +// &Connect(.sys_apb_rst_b (sync_sys_apb_rst_b)); @44 + +//========================================================== +// TDT +//========================================================== +// &Instance("tdt_top"); @50 +tdt_top x_tdt_top ( + .ciu_rst_b (cpurst_b ), + .dtu_tdt_dm_halted (dtu_tdt_dm_halted ), + .dtu_tdt_dm_havereset (dtu_tdt_dm_havereset ), + .dtu_tdt_dm_itr_done (dtu_tdt_dm_itr_done ), + .dtu_tdt_dm_retire_debug_expt_vld (dtu_tdt_dm_retire_debug_expt_vld), + .dtu_tdt_dm_rx_data (dtu_tdt_dm_rx_data ), + .dtu_tdt_dm_wr_ready (dtu_tdt_dm_wr_ready ), + .forever_cpuclk (forever_cpuclk ), + .pad_tdt_dm_core_unavail (pad_tdt_dm_core_unavail ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .pad_yy_scan_rst_b (pad_yy_scan_rst_b ), + .sys_apb_clk (sys_apb_clk ), + .sys_apb_rst_b (sync_sys_apb_rst_b ), + .sys_bus_clk_en (clk_en_f ), + .tdt_dm_dtu_ack_havereset (tdt_dm_dtu_ack_havereset ), + .tdt_dm_dtu_async_halt_req (tdt_dm_dtu_async_halt_req ), + .tdt_dm_dtu_halt_on_reset (tdt_dm_dtu_halt_on_reset ), + .tdt_dm_dtu_halt_req (tdt_dm_dtu_halt_req ), + .tdt_dm_dtu_halt_req_cause (tdt_dm_dtu_halt_req_cause ), + .tdt_dm_dtu_itr (tdt_dm_dtu_itr ), + .tdt_dm_dtu_itr_vld (tdt_dm_dtu_itr_vld ), + .tdt_dm_dtu_resume_req (tdt_dm_dtu_resume_req ), + .tdt_dm_dtu_wdata (tdt_dm_dtu_wdata ), + .tdt_dm_dtu_wr_flg (tdt_dm_dtu_wr_flg ), + .tdt_dm_dtu_wr_vld (tdt_dm_dtu_wr_vld ), + .tdt_dm_pad_hartreset_n (tdt_dm_pad_hartreset_n ), + .tdt_dm_pad_ndmreset_n (tdt_dm_pad_ndmreset_n ), + .tdt_dmi_paddr (tdt_dmi_paddr ), + .tdt_dmi_penable (tdt_dmi_penable ), + .tdt_dmi_prdata (tdt_dmi_prdata ), + .tdt_dmi_pready (tdt_dmi_pready ), + .tdt_dmi_psel (tdt_dmi_psel ), + .tdt_dmi_pslverr (tdt_dmi_pslverr ), + .tdt_dmi_pwdata (tdt_dmi_pwdata ), + .tdt_dmi_pwrite (tdt_dmi_pwrite ) +); + +// &Connect(.ciu_rst_b (cpurst_b)); @51 +// &Connect(.sys_apb_clk (sys_apb_clk)); @52 +// &Connect(.sys_apb_rst_b (sync_sys_apb_rst_b)); @53 +// &Connect(.sys_bus_clk_en (axim_clk_en_f)); @55 +// &Connect(.sys_bus_clk_en (clk_en_f)); @57 +//scan chain +//make sure whether to delete this pin +// &Force("nonport", "tdt_dm_dtu_halt_req_cause"); @61 +// &Instance("tdt_top_dummy"); @63 +// &Connect(.ciu_rst_b (cpurst_b)); @64 +// &Connect(.sys_apb_clk (sys_apb_clk)); @65 +// &Connect(.sys_apb_rst_b (sys_apb_rst_b)); @66 +// &Connect(.sys_bus_clk_en (1'b0)); @67 +// &Force("nonport", "tdt_dm_dtu_halt_req_cause"); @69 +//========================================================== +// Instance CLOCK and RST module +//========================================================== +// &Instance("pa_clkrst_top"); @74 +pa_clkrst_top x_pa_clkrst_top ( + .clk_en (clk_en ), + .clk_en_f (clk_en_f ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .pad_yy_scan_rst_b (pad_yy_scan_rst_b ), + .pll_core_cpuclk (pll_core_cpuclk ), + .sync_sys_apb_rst_b (sync_sys_apb_rst_b), + .sys_apb_clk (sys_apb_clk ), + .sys_apb_rst_b (sys_apb_rst_b ) +); + + +//========================================================== +// Instance TCIPIF module +//========================================================== +// &Instance("pa_tcipif_top"); @80 +pa_tcipif_top x_pa_tcipif_top ( + .bmu_tcipif_dbus_acc_deny (bmu_tcipif_dbus_acc_deny ), + .bmu_tcipif_dbus_addr (bmu_tcipif_dbus_addr ), + .bmu_tcipif_dbus_req (bmu_tcipif_dbus_req ), + .bmu_tcipif_dbus_req_dp (bmu_tcipif_dbus_req_dp ), + .bmu_tcipif_dbus_size (bmu_tcipif_dbus_size ), + .bmu_tcipif_dbus_supv_mode (bmu_tcipif_dbus_supv_mode ), + .bmu_tcipif_dbus_wdata (bmu_tcipif_dbus_wdata ), + .bmu_tcipif_dbus_write (bmu_tcipif_dbus_write ), + .bmu_tcipif_ibus_acc_deny (bmu_tcipif_ibus_acc_deny ), + .bmu_tcipif_ibus_addr (bmu_tcipif_ibus_addr ), + .bmu_tcipif_ibus_req (bmu_tcipif_ibus_req ), + .bmu_tcipif_ibus_req_dp (bmu_tcipif_ibus_req_dp ), + .bmu_tcipif_ibus_size (bmu_tcipif_ibus_size ), + .bmu_tcipif_ibus_supv_mode (bmu_tcipif_ibus_supv_mode ), + .bmu_tcipif_ibus_wdata (bmu_tcipif_ibus_wdata ), + .bmu_tcipif_ibus_write (bmu_tcipif_ibus_write ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .pad_clic_int_vld (pad_clic_int_vld ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .pad_yy_dft_clk_rst_b (pad_yy_dft_clk_rst_b ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sysio_clint_me_int (sysio_clint_me_int ), + .sysio_clint_mtime (sysio_clint_mtime ), + .sysmap_tcipif_cmplt (sysmap_tcipif_cmplt ), + .sysmap_tcipif_rdata (sysmap_tcipif_rdata ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ), + .tcipif_bmu_dbus_acc_err (tcipif_bmu_dbus_acc_err ), + .tcipif_bmu_dbus_data (tcipif_bmu_dbus_data ), + .tcipif_bmu_dbus_grnt (tcipif_bmu_dbus_grnt ), + .tcipif_bmu_dbus_trans_cmplt (tcipif_bmu_dbus_trans_cmplt), + .tcipif_bmu_ibus_acc_err (tcipif_bmu_ibus_acc_err ), + .tcipif_bmu_ibus_data (tcipif_bmu_ibus_data ), + .tcipif_bmu_ibus_grnt (tcipif_bmu_ibus_grnt ), + .tcipif_bmu_ibus_trans_cmplt (tcipif_bmu_ibus_trans_cmplt), + .tcipif_sysmap_addr (tcipif_sysmap_addr ), + .tcipif_sysmap_sel (tcipif_sysmap_sel ), + .tcipif_sysmap_wdata (tcipif_sysmap_wdata ), + .tcipif_sysmap_write (tcipif_sysmap_write ) +); + +// &Instance("pa_tcipif_top_dummy"); @82 + + +// &Force("input", "pad_cpu_nmi"); @90 +// &Force("input", "pad_cpu_rst_addr"); &Force("bus", "pad_cpu_rst_addr", 31, 0); @91 +// &Force("input", "pad_cpu_wakeup_event"); @92 + +// &Force("nonport", "sysio_pad_srst"); @94 + +// &Force("output","biu_pad_arvalid"); @98 +// &Force("output","biu_pad_rready"); @99 +// &Force("output","biu_pad_awvalid"); @100 +// &Force("output","biu_pad_bready"); @101 +// &Force("output","cpu_pad_dfs_ack"); @102 +// &Force("output","pahbl_pad_htrans"); @103 +// &Force("input","pad_biu_arready"); @104 +// &Force("input","pad_biu_rvalid"); @105 +// &Force("input","pad_biu_rlast"); @106 +// &Force("input","pad_pahbl_hready"); @107 +// &Force("input","pad_biu_bvalid"); @108 +// &Force("input","pad_biu_awready"); @109 +// &Force("nonport","fencei_icache_inv_done"); @184 +// &Force("nonport","lpmd_all_done"); @185 +// &Force("nonport","srst_special_srst_cmplt"); @186 + +// &ModuleEnd; @191 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core.v new file mode 100644 index 0000000000000000000000000000000000000000..45cc972bcbcb661580f20d3da9f7c7c5221c1df7 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core.v @@ -0,0 +1,2198 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @23 + +// &ModuleBeg; @25 +module pa_core( + bmu_ifu_acc_err, + bmu_ifu_grant, + bmu_ifu_rdata, + bmu_ifu_trans_cmplt, + bmu_lsu_acc_err, + bmu_lsu_grant, + bmu_lsu_rdata, + bmu_lsu_trans_cmplt, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + cp0_biu_icg_en, + cp0_dtu_addr, + cp0_dtu_debug_info, + cp0_dtu_icg_en, + cp0_dtu_int_id, + cp0_dtu_mexpt_vld, + cp0_dtu_pcfifo_frz, + cp0_dtu_rreg, + cp0_dtu_wdata, + cp0_dtu_wreg, + cp0_hpcp_icg_en, + cp0_hpcp_index, + cp0_hpcp_pmdm, + cp0_hpcp_pmdu, + cp0_hpcp_wdata, + cp0_hpcp_wreg, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cp0_pmp_csr_sel, + cp0_pmp_csr_wen, + cp0_pmp_icg_en, + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_pmp_updt_data, + cp0_sysio_ipend_b, + cp0_sysio_lpmd_b, + cp0_sysio_srst, + cp0_yy_clk_en, + cp0_yy_mach_mode, + cp0_yy_priv_mode, + cpu_clic_curid, + cpu_clic_int_exit, + cpurst_b, + dtu_cp0_dcsr_mprven, + dtu_cp0_dcsr_prv, + dtu_cp0_rdata, + dtu_cp0_wake_up, + dtu_ifu_debug_inst, + dtu_ifu_debug_inst_vld, + dtu_ifu_halt_info0, + dtu_ifu_halt_info1, + dtu_ifu_halt_info_vld, + dtu_ifu_halt_on_reset, + dtu_lsu_addr_trig_en, + dtu_lsu_data_trig_en, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + dtu_rtu_async_halt_req, + dtu_rtu_dpc, + dtu_rtu_ebreak_action, + dtu_rtu_int_mask, + dtu_rtu_pending_tval, + dtu_rtu_resume_req, + dtu_rtu_step_en, + dtu_rtu_sync_flush, + dtu_rtu_sync_halt_req, + forever_cpuclk, + fpu_dtu_debug_info, + hpcp_cp0_data, + idu_dtu_debug_info, + idu_dtu_fpr_info, + idu_yy_xx_tail_ack, + ifu_bmu_acc_deny, + ifu_bmu_addr, + ifu_bmu_burst, + ifu_bmu_data_req, + ifu_bmu_prot, + ifu_bmu_req, + ifu_bmu_seq, + ifu_bmu_size, + ifu_clic_warm_up, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_debug_info, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ifu_dtu_exe_data0, + ifu_dtu_exe_data1, + ifu_hpcp_icache_access, + ifu_hpcp_icache_miss, + ifu_pmp_addr, + ifu_pmp_machine_mode, + ifu_sysmap_pa, + ifu_sysmap_rst_sample, + iu_dtu_debug_info, + iu_hpcp_inst_bht_mispred, + iu_hpcp_inst_condbr, + iu_hpcp_inst_condbr_gate, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_bmu_acc_deny, + lsu_bmu_addr, + lsu_bmu_burst, + lsu_bmu_lock, + lsu_bmu_lrsc, + lsu_bmu_prot, + lsu_bmu_req, + lsu_bmu_req_dp, + lsu_bmu_seq, + lsu_bmu_size, + lsu_bmu_wdata, + lsu_bmu_write, + lsu_dtu_debug_info, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + lsu_dtu_ldst_type, + lsu_dtu_mem_access_size, + lsu_hpcp_cache_read_access, + lsu_hpcp_cache_read_access_gate, + lsu_hpcp_cache_read_miss, + lsu_hpcp_cache_read_miss_gate, + lsu_hpcp_cache_write_access, + lsu_hpcp_cache_write_access_gate, + lsu_hpcp_cache_write_miss, + lsu_hpcp_cache_write_miss_gate, + lsu_hpcp_inst_store, + lsu_hpcp_inst_store_gate, + lsu_pmp_addr, + lsu_pmp_write, + lsu_sysmap_pa, + lsu_xx_flush, + lsu_xx_warm_up, + pad_yy_icg_scan_en, + pmp_cp0_data, + pmp_ifu_acc_deny, + pmp_lsu_acc_deny, + rtu_dtu_debug_info, + rtu_dtu_dpc, + rtu_dtu_halt_ack, + rtu_dtu_nmi_pending, + rtu_dtu_pending_ack, + rtu_dtu_retire_chgflw, + rtu_dtu_retire_debug_expt_vld, + rtu_dtu_retire_halt_info, + rtu_dtu_retire_mret, + rtu_dtu_retire_next_pc, + rtu_dtu_retire_vld, + rtu_dtu_tval, + rtu_hpcp_retire_inst_vld, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld, + rtu_sysio_halted, + rtu_sysio_lockup_on, + rtu_yy_xx_async_flush, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + sysio_cp0_clk_en, + sysio_cp0_clkratio, + sysio_cp0_rst_addr, + sysio_ifu_rst_addr, + sysio_ifu_rst_addr_done, + sysio_iu_rst_addr, + sysio_rtu_nmi_int, + sysio_rtu_wk_event, + sysio_xx_halt_req, + sysmap_ifu_flg, + sysmap_lsu_flg, + tcip_cp0_clic_base +); + +// &Ports; @26 +input bmu_ifu_acc_err; +input bmu_ifu_grant; +input [31:0] bmu_ifu_rdata; +input bmu_ifu_trans_cmplt; +input bmu_lsu_acc_err; +input bmu_lsu_grant; +input [31:0] bmu_lsu_rdata; +input bmu_lsu_trans_cmplt; +input clic_cpu_int_hv; +input [11:0] clic_cpu_int_id; +input [7 :0] clic_cpu_int_il; +input [1 :0] clic_cpu_int_priv; +input cpurst_b; +input dtu_cp0_dcsr_mprven; +input [1 :0] dtu_cp0_dcsr_prv; +input [31:0] dtu_cp0_rdata; +input dtu_cp0_wake_up; +input [31:0] dtu_ifu_debug_inst; +input dtu_ifu_debug_inst_vld; +input [14:0] dtu_ifu_halt_info0; +input [14:0] dtu_ifu_halt_info1; +input dtu_ifu_halt_info_vld; +input dtu_ifu_halt_on_reset; +input dtu_lsu_addr_trig_en; +input dtu_lsu_data_trig_en; +input [14:0] dtu_lsu_halt_info; +input dtu_lsu_halt_info_vld; +input dtu_rtu_async_halt_req; +input [31:0] dtu_rtu_dpc; +input dtu_rtu_ebreak_action; +input dtu_rtu_int_mask; +input [31:0] dtu_rtu_pending_tval; +input dtu_rtu_resume_req; +input dtu_rtu_step_en; +input dtu_rtu_sync_flush; +input dtu_rtu_sync_halt_req; +input forever_cpuclk; +input [31:0] hpcp_cp0_data; +input pad_yy_icg_scan_en; +input [31:0] pmp_cp0_data; +input pmp_ifu_acc_deny; +input pmp_lsu_acc_deny; +input sysio_cp0_clk_en; +input [2 :0] sysio_cp0_clkratio; +input [31:0] sysio_cp0_rst_addr; +input [31:0] sysio_ifu_rst_addr; +input sysio_ifu_rst_addr_done; +input [31:0] sysio_iu_rst_addr; +input sysio_rtu_nmi_int; +input sysio_rtu_wk_event; +input sysio_xx_halt_req; +input [4 :0] sysmap_ifu_flg; +input [4 :0] sysmap_lsu_flg; +input [31:0] tcip_cp0_clic_base; +output cp0_biu_icg_en; +output [11:0] cp0_dtu_addr; +output [5 :0] cp0_dtu_debug_info; +output cp0_dtu_icg_en; +output [11:0] cp0_dtu_int_id; +output cp0_dtu_mexpt_vld; +output cp0_dtu_pcfifo_frz; +output cp0_dtu_rreg; +output [31:0] cp0_dtu_wdata; +output cp0_dtu_wreg; +output cp0_hpcp_icg_en; +output [11:0] cp0_hpcp_index; +output cp0_hpcp_pmdm; +output cp0_hpcp_pmdu; +output [31:0] cp0_hpcp_wdata; +output cp0_hpcp_wreg; +output [31:0] cp0_pad_mcause; +output [31:0] cp0_pad_mintstatus; +output [31:0] cp0_pad_mstatus; +output [19:0] cp0_pmp_csr_sel; +output cp0_pmp_csr_wen; +output cp0_pmp_icg_en; +output [1 :0] cp0_pmp_mstatus_mpp; +output cp0_pmp_mstatus_mprv; +output [31:0] cp0_pmp_updt_data; +output cp0_sysio_ipend_b; +output [1 :0] cp0_sysio_lpmd_b; +output [1 :0] cp0_sysio_srst; +output cp0_yy_clk_en; +output cp0_yy_mach_mode; +output [1 :0] cp0_yy_priv_mode; +output [11:0] cpu_clic_curid; +output cpu_clic_int_exit; +output [7 :0] fpu_dtu_debug_info; +output [21:0] idu_dtu_debug_info; +output [95:0] idu_dtu_fpr_info; +output idu_yy_xx_tail_ack; +output ifu_bmu_acc_deny; +output [31:0] ifu_bmu_addr; +output [2 :0] ifu_bmu_burst; +output ifu_bmu_data_req; +output [3 :0] ifu_bmu_prot; +output ifu_bmu_req; +output ifu_bmu_seq; +output [1 :0] ifu_bmu_size; +output ifu_clic_warm_up; +output ifu_dtu_addr_vld0; +output ifu_dtu_addr_vld1; +output ifu_dtu_data_vld0; +output ifu_dtu_data_vld1; +output [26:0] ifu_dtu_debug_info; +output [31:0] ifu_dtu_exe_addr0; +output [31:0] ifu_dtu_exe_addr1; +output [31:0] ifu_dtu_exe_data0; +output [31:0] ifu_dtu_exe_data1; +output ifu_hpcp_icache_access; +output ifu_hpcp_icache_miss; +output [31:0] ifu_pmp_addr; +output ifu_pmp_machine_mode; +output [31:0] ifu_sysmap_pa; +output ifu_sysmap_rst_sample; +output [8 :0] iu_dtu_debug_info; +output iu_hpcp_inst_bht_mispred; +output iu_hpcp_inst_condbr; +output iu_hpcp_inst_condbr_gate; +output lsu_biu_amo_pmp_deny; +output lsu_biu_async_expt_ack; +output lsu_bmu_acc_deny; +output [31:0] lsu_bmu_addr; +output [2 :0] lsu_bmu_burst; +output lsu_bmu_lock; +output lsu_bmu_lrsc; +output [3 :0] lsu_bmu_prot; +output lsu_bmu_req; +output lsu_bmu_req_dp; +output lsu_bmu_seq; +output [1 :0] lsu_bmu_size; +output [31:0] lsu_bmu_wdata; +output lsu_bmu_write; +output [78:0] lsu_dtu_debug_info; +output [14:0] lsu_dtu_halt_info; +output lsu_dtu_last_check; +output [31:0] lsu_dtu_ldst_addr; +output lsu_dtu_ldst_addr_vld; +output [7 :0] lsu_dtu_ldst_bytes_vld; +output [31:0] lsu_dtu_ldst_data; +output lsu_dtu_ldst_data_vld; +output [1 :0] lsu_dtu_ldst_type; +output [1 :0] lsu_dtu_mem_access_size; +output lsu_hpcp_cache_read_access; +output lsu_hpcp_cache_read_access_gate; +output lsu_hpcp_cache_read_miss; +output lsu_hpcp_cache_read_miss_gate; +output lsu_hpcp_cache_write_access; +output lsu_hpcp_cache_write_access_gate; +output lsu_hpcp_cache_write_miss; +output lsu_hpcp_cache_write_miss_gate; +output lsu_hpcp_inst_store; +output lsu_hpcp_inst_store_gate; +output [31:0] lsu_pmp_addr; +output lsu_pmp_write; +output [31:0] lsu_sysmap_pa; +output lsu_xx_flush; +output lsu_xx_warm_up; +output [13:0] rtu_dtu_debug_info; +output [31:0] rtu_dtu_dpc; +output rtu_dtu_halt_ack; +output rtu_dtu_nmi_pending; +output rtu_dtu_pending_ack; +output rtu_dtu_retire_chgflw; +output rtu_dtu_retire_debug_expt_vld; +output [14:0] rtu_dtu_retire_halt_info; +output rtu_dtu_retire_mret; +output [31:0] rtu_dtu_retire_next_pc; +output rtu_dtu_retire_vld; +output [31:0] rtu_dtu_tval; +output rtu_hpcp_retire_inst_vld; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31:0] rtu_pad_retire_pc; +output [31:0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31:0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31:0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31:0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; +output rtu_sysio_halted; +output rtu_sysio_lockup_on; +output rtu_yy_xx_async_flush; +output rtu_yy_xx_dbgon; +output rtu_yy_xx_expt_int; +output [11:0] rtu_yy_xx_expt_vec; +output rtu_yy_xx_expt_vld; + +// &Regs; @27 + +// &Wires; @28 +wire bmu_ifu_acc_err; +wire bmu_ifu_grant; +wire [31:0] bmu_ifu_rdata; +wire bmu_ifu_trans_cmplt; +wire bmu_lsu_acc_err; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire clic_cpu_int_hv; +wire [11:0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire cp0_biu_icg_en; +wire [11:0] cp0_dtu_addr; +wire [5 :0] cp0_dtu_debug_info; +wire cp0_dtu_icg_en; +wire [11:0] cp0_dtu_int_id; +wire cp0_dtu_mexpt_vld; +wire cp0_dtu_pcfifo_frz; +wire cp0_dtu_rreg; +wire [31:0] cp0_dtu_wdata; +wire cp0_dtu_wreg; +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire [2 :0] cp0_fpu_xx_rm; +wire cp0_hpcp_icg_en; +wire [11:0] cp0_hpcp_index; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [31:0] cp0_hpcp_wdata; +wire cp0_hpcp_wreg; +wire cp0_idu_ex1_stall; +wire [1 :0] cp0_idu_fs; +wire cp0_idu_icg_en; +wire [31:0] cp0_idu_mcause; +wire [31:0] cp0_idu_mepc; +wire [2 :0] cp0_idu_rm; +wire cp0_idu_sp_use_scratch; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_ifu_in_lpmd; +wire cp0_ifu_lpmd_req; +wire [31:0] cp0_ifu_mtvec; +wire cp0_ifu_ras_en; +wire cp0_ifu_rst_inv_done; +wire cp0_ifu_srst_mask; +wire cp0_ifu_srst_req; +wire cp0_iu_adder_borrow_in; +wire cp0_iu_adder_borrow_vld; +wire cp0_iu_icg_en; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_dcache_wb; +wire cp0_lsu_fence_req; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire cp0_lsu_mm; +wire cp0_lsu_sync_req; +wire [31:0] cp0_pad_mcause; +wire [31:0] cp0_pad_mintstatus; +wire [31:0] cp0_pad_mstatus; +wire [19:0] cp0_pmp_csr_sel; +wire cp0_pmp_csr_wen; +wire cp0_pmp_icg_en; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire [31:0] cp0_pmp_updt_data; +wire [30:0] cp0_rtu_ex1_chgflw_pc; +wire cp0_rtu_ex1_chgflw_vld; +wire cp0_rtu_ex1_cmplt; +wire cp0_rtu_ex1_cmplt_dp; +wire cp0_rtu_ex1_dret; +wire cp0_rtu_ex1_ebreak; +wire cp0_rtu_ex1_expt_inst; +wire [31:0] cp0_rtu_ex1_expt_tval; +wire [3 :0] cp0_rtu_ex1_expt_vec; +wire cp0_rtu_ex1_flush; +wire [14:0] cp0_rtu_ex1_halt_info; +wire cp0_rtu_ex1_inst_len; +wire cp0_rtu_ex1_inst_vld; +wire cp0_rtu_ex1_ipush_spec_fail; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_ex1_split_inst; +wire cp0_rtu_ex1_tail_fail; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_expt; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire [1 :0] cp0_rtu_int_mode; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire [31:0] cp0_rtu_wb_data; +wire [5 :0] cp0_rtu_wb_preg; +wire cp0_rtu_wb_vld; +wire cp0_rtu_wfe_en; +wire cp0_sysio_ipend_b; +wire [1 :0] cp0_sysio_lpmd_b; +wire [1 :0] cp0_sysio_srst; +wire cp0_xx_async_expt_en; +wire cp0_yy_clk_en; +wire cp0_yy_cskyisaee; +wire cp0_yy_mach_mode; +wire [1 :0] cp0_yy_priv_mode; +wire [11:0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpurst_b; +wire dtu_cp0_dcsr_mprven; +wire [1 :0] dtu_cp0_dcsr_prv; +wire [31:0] dtu_cp0_rdata; +wire dtu_cp0_wake_up; +wire [31:0] dtu_ifu_debug_inst; +wire dtu_ifu_debug_inst_vld; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire dtu_ifu_halt_info_vld; +wire dtu_ifu_halt_on_reset; +wire dtu_lsu_addr_trig_en; +wire dtu_lsu_data_trig_en; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire dtu_rtu_async_halt_req; +wire [31:0] dtu_rtu_dpc; +wire dtu_rtu_ebreak_action; +wire dtu_rtu_int_mask; +wire [31:0] dtu_rtu_pending_tval; +wire dtu_rtu_resume_req; +wire dtu_rtu_step_en; +wire dtu_rtu_sync_flush; +wire dtu_rtu_sync_halt_req; +wire forever_cpuclk; +wire [4 :0] fpu_cp0_wb_fflags; +wire fpu_cp0_wb_fflags_updt; +wire [7 :0] fpu_dtu_debug_info; +wire fpu_gated_cpuclk; +wire fpu_gated_cpuclk_en; +wire fpu_idu_ex1_stall; +wire [31:0] fpu_idu_fwd_data; +wire [4 :0] fpu_idu_fwd_freg; +wire fpu_idu_fwd_vld; +wire fpu_iu_ex1_cmplt; +wire fpu_iu_ex1_cmplt_dp; +wire [31:0] fpu_rtu_fgpr_wb_data; +wire [4 :0] fpu_rtu_fgpr_wb_reg; +wire fpu_rtu_fgpr_wb_vld; +wire [31:0] fpu_rtu_wb_data; +wire [5 :0] fpu_rtu_wb_preg; +wire fpu_rtu_wb_vld; +wire fpu_wb_float_fflags_updt; +wire fpu_xx_no_op; +wire [31:0] hpcp_cp0_data; +wire idu_cp0_ex1_cmplt_dp_sel; +wire [5 :0] idu_cp0_ex1_dst_idx; +wire idu_cp0_ex1_dst_vld; +wire idu_cp0_ex1_expt_high; +wire idu_cp0_ex1_expt_type; +wire idu_cp0_ex1_expt_vld; +wire [19:0] idu_cp0_ex1_func; +wire idu_cp0_ex1_gateclk_sel; +wire [14:0] idu_cp0_ex1_halt_info; +wire idu_cp0_ex1_inst_len; +wire idu_cp0_ex1_ipush_spec_fail; +wire [31:0] idu_cp0_ex1_opcode; +wire [31:0] idu_cp0_ex1_rs1; +wire [11:0] idu_cp0_ex1_rs2; +wire idu_cp0_ex1_sel; +wire idu_cp0_ex1_split_inst; +wire idu_cp0_ex1_tail_fail; +wire idu_cp0_id_tail_vld; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire [21:0] idu_dtu_debug_info; +wire [95:0] idu_dtu_fpr_info; +wire idu_fpu_ex1_cmplt_dp_sel; +wire [4 :0] idu_fpu_ex1_dst_freg; +wire idu_fpu_ex1_dst_freg_vld; +wire [4 :0] idu_fpu_ex1_dst_preg; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire idu_fpu_ex1_gateclk_vld; +wire idu_fpu_ex1_inst_vld; +wire [2 :0] idu_fpu_ex1_rm; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire [31:0] idu_fpu_ex1_srcf2; +wire [31:0] idu_fpu_ex1_srci; +wire idu_ifu_id_stall; +wire idu_ifu_tail_vld; +wire idu_ifu_tail_vld_gate; +wire [31:0] idu_ifu_x1; +wire [31:0] idu_iu_ex1_ag_imm; +wire idu_iu_ex1_alu_cmplt_dp_sel; +wire idu_iu_ex1_alu_gateclk_sel; +wire idu_iu_ex1_alu_sel; +wire [1 :0] idu_iu_ex1_bht_pred; +wire idu_iu_ex1_bju_cmplt_dp_sel; +wire idu_iu_ex1_bju_depd_lsu_src0; +wire idu_iu_ex1_bju_depd_lsu_src1; +wire idu_iu_ex1_bju_gateclk_sel; +wire idu_iu_ex1_bju_sel; +wire idu_iu_ex1_bju_use_pc; +wire idu_iu_ex1_div_cmplt_dp_sel; +wire idu_iu_ex1_div_gateclk_sel; +wire idu_iu_ex1_div_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_len; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_ipop_int_mask; +wire idu_iu_ex1_ipush_mie_en; +wire idu_iu_ex1_ipush_spec_fail; +wire idu_iu_ex1_mul_cmplt_dp_sel; +wire idu_iu_ex1_mul_gateclk_sel; +wire idu_iu_ex1_mul_high_sel; +wire idu_iu_ex1_mul_sel; +wire idu_iu_ex1_rd_pair; +wire idu_iu_ex1_split; +wire [31:0] idu_iu_ex1_src0; +wire [5 :0] idu_iu_ex1_src0_reg; +wire [31:0] idu_iu_ex1_src1; +wire [5 :0] idu_iu_ex1_src1_reg; +wire [31:0] idu_iu_ex1_src2; +wire idu_iu_ex1_tail_int_vld; +wire idu_iu_ex1_wb_vld; +wire idu_iu_tail_fail; +wire idu_iu_tail_fail_gate; +wire [31:0] idu_lsu_ex1_ag_imm; +wire [31:0] idu_lsu_ex1_base; +wire idu_lsu_ex1_base_sel; +wire idu_lsu_ex1_base_wb; +wire [31:0] idu_lsu_ex1_data; +wire [5 :0] idu_lsu_ex1_dest_reg; +wire idu_lsu_ex1_dest_vld; +wire idu_lsu_ex1_dp_sel; +wire idu_lsu_ex1_fls; +wire [3 :0] idu_lsu_ex1_func; +wire idu_lsu_ex1_gateclk_sel; +wire [14:0] idu_lsu_ex1_halt_info; +wire idu_lsu_ex1_ipop_int_mask; +wire idu_lsu_ex1_ipush_spec; +wire idu_lsu_ex1_length; +wire idu_lsu_ex1_offset_sel; +wire idu_lsu_ex1_sel; +wire idu_lsu_ex1_sign_extend; +wire [1 :0] idu_lsu_ex1_size; +wire idu_lsu_ex1_split; +wire [5 :0] idu_lsu_ex1_src0_reg; +wire idu_lsu_ex1_src1_depd; +wire [5 :0] idu_lsu_ex1_src1_reg; +wire idu_yy_xx_tail_ack; +wire ifu_bmu_acc_deny; +wire [31:0] ifu_bmu_addr; +wire [2 :0] ifu_bmu_burst; +wire ifu_bmu_data_req; +wire [3 :0] ifu_bmu_prot; +wire ifu_bmu_req; +wire ifu_bmu_seq; +wire [1 :0] ifu_bmu_size; +wire ifu_clic_warm_up; +wire ifu_cp0_bht_inv_done; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_lpmd_ack; +wire ifu_cp0_rst_inv_req; +wire ifu_cp0_srst_ack; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire ifu_cp0_warm_up; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [26:0] ifu_dtu_debug_info; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire [31:0] ifu_dtu_exe_data0; +wire [31:0] ifu_dtu_exe_data1; +wire ifu_fpu_warm_up; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire ifu_idu_chgflw_flush; +wire ifu_idu_id_expt_high; +wire ifu_idu_id_expt_vld; +wire [14:0] ifu_idu_id_halt_info; +wire [31:0] ifu_idu_id_inst; +wire ifu_idu_id_inst_vld; +wire [1 :0] ifu_idu_id_pred_taken; +wire ifu_idu_warm_up; +wire [31:0] ifu_iu_chgflw_pc; +wire ifu_iu_chgflw_vld; +wire [31:0] ifu_iu_ex1_pc_pred; +wire ifu_iu_reset_vld; +wire ifu_iu_warm_up; +wire ifu_lsu_warm_up; +wire [31:0] ifu_pmp_addr; +wire ifu_pmp_machine_mode; +wire ifu_rtu_lockup_ack; +wire ifu_rtu_reset_halt_req; +wire ifu_rtu_warm_up; +wire [31:0] ifu_sysmap_pa; +wire ifu_sysmap_rst_sample; +wire ifu_xx_in_warm_up; +wire [31:0] iu_cp0_ex1_borrow_expt_pc; +wire [8 :0] iu_dtu_debug_info; +wire iu_hpcp_inst_bht_mispred; +wire iu_hpcp_inst_condbr; +wire iu_hpcp_inst_condbr_gate; +wire iu_idu_bju_global_stall; +wire iu_idu_bju_stall; +wire [31:0] iu_idu_ex1_fwd_data; +wire [5 :0] iu_idu_ex1_fwd_preg; +wire iu_idu_ex1_fwd_vld; +wire [31:0] iu_idu_ex1_src1_update_value; +wire iu_idu_ex1_stall; +wire iu_idu_ex2_div_vld; +wire [31:0] iu_idu_ex2_fwd_data0; +wire [31:0] iu_idu_ex2_fwd_data1; +wire [5 :0] iu_idu_ex2_fwd_preg0; +wire [5 :0] iu_idu_ex2_fwd_preg1; +wire iu_idu_ex2_fwd_vld0; +wire iu_idu_ex2_fwd_vld1; +wire iu_idu_ex2_inst_vld; +wire iu_idu_ex2_rd_pair; +wire iu_idu_id_stall; +wire [31:0] iu_ifu_bht_cur_pc; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire iu_ifu_ind_link_vld; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire [31:0] iu_ifu_tar_pc; +wire iu_ifu_tar_pc_vld; +wire iu_ifu_tar_pc_vld_gate; +wire [31:0] iu_lsu_ex1_lsi_rst; +wire iu_lsu_ex2_wb0_grant; +wire iu_rtu_ex1_bju_branch_inst; +wire iu_rtu_ex1_bju_cmplt; +wire iu_rtu_ex1_bju_cmplt_dp; +wire [30:0] iu_rtu_ex1_bju_cur_pc; +wire iu_rtu_ex1_bju_inst_len; +wire iu_rtu_ex1_bju_inst_vld; +wire iu_rtu_ex1_bju_split_inst; +wire iu_rtu_ex1_cmplt; +wire iu_rtu_ex1_cmplt_dp; +wire iu_rtu_ex1_inst_len; +wire iu_rtu_ex1_inst_vld; +wire iu_rtu_ex1_ipop_int_mask; +wire iu_rtu_ex1_ipush_mie_en; +wire iu_rtu_ex1_ipush_spec_fail; +wire [30:0] iu_rtu_ex1_next_pc; +wire iu_rtu_ex1_split_inst; +wire iu_rtu_ex1_tail_int_vld; +wire iu_rtu_ex2_bju_flush; +wire [30:0] iu_rtu_ex2_bju_next_pc; +wire iu_rtu_ex2_bju_next_pc_vld; +wire [31:0] iu_rtu_wb0_data; +wire [5 :0] iu_rtu_wb0_preg; +wire iu_rtu_wb0_vld; +wire iu_xx_no_op; +wire iu_yy_xx_cancel; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire lsu_cp0_fence_ack; +wire lsu_cp0_icc_done; +wire lsu_cp0_sync_ack; +wire [78:0] lsu_dtu_debug_info; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [1 :0] lsu_dtu_ldst_type; +wire [1 :0] lsu_dtu_mem_access_size; +wire lsu_hpcp_cache_read_access; +wire lsu_hpcp_cache_read_access_gate; +wire lsu_hpcp_cache_read_miss; +wire lsu_hpcp_cache_read_miss_gate; +wire lsu_hpcp_cache_write_access; +wire lsu_hpcp_cache_write_access_gate; +wire lsu_hpcp_cache_write_miss; +wire lsu_hpcp_cache_write_miss_gate; +wire lsu_hpcp_inst_store; +wire lsu_hpcp_inst_store_gate; +wire [14:0] lsu_idu_ex1_halt_info; +wire lsu_idu_ex1_halt_info_update_en; +wire lsu_idu_ex1_src1_update_en; +wire lsu_idu_ex1_src1_update_en_gate; +wire lsu_idu_ex1_stall; +wire [31:0] lsu_idu_ex2_ffwd_data; +wire lsu_idu_ex2_ffwd_vld; +wire [31:0] lsu_idu_ex2_fwd_data; +wire [4 :0] lsu_idu_ex2_fwd_freg; +wire [5 :0] lsu_idu_ex2_fwd_preg; +wire lsu_idu_ex2_fwd_vld; +wire [31:0] lsu_idu_ex3_ffwd_data; +wire lsu_idu_ex3_ffwd_vld; +wire [31:0] lsu_idu_ex3_fwd_data; +wire [4 :0] lsu_idu_ex3_fwd_freg; +wire [5 :0] lsu_idu_ex3_fwd_preg; +wire lsu_idu_ex3_fwd_vld; +wire lsu_idu_global_stall; +wire [31:0] lsu_idu_update_addr; +wire lsu_idu_update_en; +wire lsu_idu_update_en_gate; +wire [31:0] lsu_idu_update_offset; +wire lsu_iu_ex1_base_wb; +wire lsu_iu_ex1_src1_sel; +wire [31:0] lsu_iu_ex2_data; +wire lsu_iu_ex2_data_vld; +wire [5 :0] lsu_iu_ex2_dest_reg; +wire [5 :0] lsu_iu_ex2_lsi_dst_preg; +wire [31:0] lsu_iu_ex2_lsi_rslt; +wire lsu_iu_ex2_lsi_rslt_vld; +wire [31:0] lsu_pmp_addr; +wire lsu_pmp_write; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_async_ld_inst; +wire [31:0] lsu_rtu_async_tval; +wire lsu_rtu_ex1_cmplt; +wire lsu_rtu_ex1_cmplt_dp; +wire [14:0] lsu_rtu_ex1_halt_info; +wire lsu_rtu_ex1_inst_len; +wire lsu_rtu_ex1_inst_vld; +wire lsu_rtu_ex1_ipop_int_mask; +wire lsu_rtu_ex1_ipush_spec_inst; +wire lsu_rtu_ex1_split_inst; +wire lsu_rtu_ex2_bus_err; +wire lsu_rtu_ex2_expt_inst; +wire [3 :0] lsu_rtu_ex2_expt_vec; +wire lsu_rtu_ex2_stall; +wire [31:0] lsu_rtu_ex2_tval; +wire [31:0] lsu_rtu_fgpr_wb_data; +wire [4 :0] lsu_rtu_fgpr_wb_reg; +wire lsu_rtu_fgpr_wb_vld; +wire lsu_rtu_sync_ack; +wire [31:0] lsu_rtu_wb_data; +wire [5 :0] lsu_rtu_wb_preg; +wire lsu_rtu_wb_vld; +wire [31:0] lsu_sysmap_pa; +wire lsu_xx_flush; +wire lsu_xx_no_op; +wire lsu_xx_warm_up; +wire pad_yy_icg_scan_en; +wire [31:0] pmp_cp0_data; +wire pmp_ifu_acc_deny; +wire pmp_lsu_acc_deny; +wire rtu_cp0_bus_error; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire rtu_cp0_fp_dirty_vld; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_cp0_mie_en; +wire rtu_cp0_mie_gateclk_en; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_nmi_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire [31:0] rtu_cp0_tval; +wire rtu_cp0_wk_int; +wire [13:0] rtu_dtu_debug_info; +wire [31:0] rtu_dtu_dpc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_nmi_pending; +wire rtu_dtu_pending_ack; +wire rtu_dtu_retire_chgflw; +wire rtu_dtu_retire_debug_expt_vld; +wire [14:0] rtu_dtu_retire_halt_info; +wire rtu_dtu_retire_mret; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; +wire [31:0] rtu_dtu_tval; +wire rtu_fpu_fgpr_wb_grant; +wire rtu_fpu_wb_grant; +wire rtu_hpcp_retire_inst_vld; +wire rtu_idu_ex1_int_dis_stall_gateclk_req; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_ex2_ipush_spec_inst_expt_vld; +wire rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +wire [31:0] rtu_idu_fgpr_wb_data; +wire rtu_idu_fgpr_wb_flsu_vld; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire rtu_idu_flush_fe; +wire rtu_idu_flush_stall; +wire rtu_idu_id_tail_int_vld; +wire rtu_idu_inst_retire; +wire rtu_idu_late_flush; +wire [31:0] rtu_idu_wb0_data; +wire rtu_idu_wb0_fpu_vld; +wire [5 :0] rtu_idu_wb0_preg; +wire rtu_idu_wb0_vld; +wire [31:0] rtu_idu_wb1_data; +wire rtu_idu_wb1_lsu_vld; +wire [5 :0] rtu_idu_wb1_preg; +wire rtu_idu_wb1_vld; +wire [31:0] rtu_idu_wb2_data; +wire [5 :0] rtu_idu_wb2_preg; +wire rtu_idu_wb2_vld; +wire [31:0] rtu_ifu_chgflw_pc; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_dbg_mask; +wire rtu_ifu_flush_fe; +wire rtu_ifu_lockup_expt_vld; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire [31:0] rtu_iu_bju_ex2_cur_pc; +wire rtu_iu_ex1_cmplt_dp_vld; +wire rtu_iu_ex1_cmplt_inst_len; +wire rtu_iu_ex1_cmplt_split_inst; +wire rtu_iu_ex1_cmplt_vld; +wire rtu_iu_pending_spec_expt_vld; +wire rtu_iu_pending_spec_halt_info_vld; +wire rtu_lsu_async_expt_ack; +wire rtu_lsu_expt_ack; +wire rtu_lsu_expt_exit; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_lsu_inst_retire; +wire rtu_lsu_sync_req; +wire [31:0] rtu_lsu_wb1_data; +wire rtu_lsu_wb1_lsu_vld; +wire [5 :0] rtu_lsu_wb1_preg; +wire rtu_pad_inst_retire; +wire rtu_pad_inst_split; +wire [31:0] rtu_pad_retire_pc; +wire [31:0] rtu_pad_wb0_data; +wire [5 :0] rtu_pad_wb0_preg; +wire rtu_pad_wb0_vld; +wire [31:0] rtu_pad_wb1_data; +wire [5 :0] rtu_pad_wb1_preg; +wire rtu_pad_wb1_vld; +wire [31:0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +wire [4 :0] rtu_pad_wb_freg; +wire [31:0] rtu_pad_wb_freg_data; +wire rtu_pad_wb_freg_vld; +wire rtu_sysio_halted; +wire rtu_sysio_lockup_on; +wire rtu_xx_ex1_stall; +wire rtu_xx_no_op; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire sysio_cp0_clk_en; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; +wire [31:0] sysio_ifu_rst_addr; +wire sysio_ifu_rst_addr_done; +wire [31:0] sysio_iu_rst_addr; +wire sysio_rtu_nmi_int; +wire sysio_rtu_wk_event; +wire sysio_xx_halt_req; +wire [4 :0] sysmap_ifu_flg; +wire [4 :0] sysmap_lsu_flg; +wire [31:0] tcip_cp0_clic_base; + + +//========================================================== +// Instance IFU module +//========================================================== +// &Instance("pa_ifu_top"); @33 +pa_ifu_top x_pa_ifu_top ( + .bmu_ifu_acc_err (bmu_ifu_acc_err ), + .bmu_ifu_grant (bmu_ifu_grant ), + .bmu_ifu_rdata (bmu_ifu_rdata ), + .bmu_ifu_trans_cmplt (bmu_ifu_trans_cmplt ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_btb_clr (cp0_ifu_btb_clr ), + .cp0_ifu_btb_en (cp0_ifu_btb_en ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_in_lpmd (cp0_ifu_in_lpmd ), + .cp0_ifu_lpmd_req (cp0_ifu_lpmd_req ), + .cp0_ifu_mtvec (cp0_ifu_mtvec ), + .cp0_ifu_ras_en (cp0_ifu_ras_en ), + .cp0_ifu_rst_inv_done (cp0_ifu_rst_inv_done ), + .cp0_ifu_srst_mask (cp0_ifu_srst_mask ), + .cp0_ifu_srst_req (cp0_ifu_srst_req ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .dtu_ifu_debug_inst (dtu_ifu_debug_inst ), + .dtu_ifu_debug_inst_vld (dtu_ifu_debug_inst_vld ), + .dtu_ifu_halt_info0 (dtu_ifu_halt_info0 ), + .dtu_ifu_halt_info1 (dtu_ifu_halt_info1 ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .dtu_ifu_halt_on_reset (dtu_ifu_halt_on_reset ), + .forever_cpuclk (forever_cpuclk ), + .idu_ifu_id_stall (idu_ifu_id_stall ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .idu_ifu_tail_vld_gate (idu_ifu_tail_vld_gate ), + .idu_ifu_x1 (idu_ifu_x1 ), + .ifu_bmu_acc_deny (ifu_bmu_acc_deny ), + .ifu_bmu_addr (ifu_bmu_addr ), + .ifu_bmu_burst (ifu_bmu_burst ), + .ifu_bmu_data_req (ifu_bmu_data_req ), + .ifu_bmu_prot (ifu_bmu_prot ), + .ifu_bmu_req (ifu_bmu_req ), + .ifu_bmu_seq (ifu_bmu_seq ), + .ifu_bmu_size (ifu_bmu_size ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done), + .ifu_cp0_lpmd_ack (ifu_cp0_lpmd_ack ), + .ifu_cp0_rst_inv_req (ifu_cp0_rst_inv_req ), + .ifu_cp0_srst_ack (ifu_cp0_srst_ack ), + .ifu_cp0_vec_err (ifu_cp0_vec_err ), + .ifu_cp0_vec_succeed (ifu_cp0_vec_succeed ), + .ifu_cp0_warm_up (ifu_cp0_warm_up ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_debug_info (ifu_dtu_debug_info ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ifu_dtu_exe_data0 (ifu_dtu_exe_data0 ), + .ifu_dtu_exe_data1 (ifu_dtu_exe_data1 ), + .ifu_fpu_warm_up (ifu_fpu_warm_up ), + .ifu_hpcp_icache_access (ifu_hpcp_icache_access ), + .ifu_hpcp_icache_miss (ifu_hpcp_icache_miss ), + .ifu_idu_chgflw_flush (ifu_idu_chgflw_flush ), + .ifu_idu_id_expt_high (ifu_idu_id_expt_high ), + .ifu_idu_id_expt_vld (ifu_idu_id_expt_vld ), + .ifu_idu_id_halt_info (ifu_idu_id_halt_info ), + .ifu_idu_id_inst (ifu_idu_id_inst ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .ifu_idu_id_pred_taken (ifu_idu_id_pred_taken ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .ifu_iu_chgflw_pc (ifu_iu_chgflw_pc ), + .ifu_iu_chgflw_vld (ifu_iu_chgflw_vld ), + .ifu_iu_ex1_pc_pred (ifu_iu_ex1_pc_pred ), + .ifu_iu_reset_vld (ifu_iu_reset_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .ifu_pmp_addr (ifu_pmp_addr ), + .ifu_pmp_machine_mode (ifu_pmp_machine_mode ), + .ifu_rtu_lockup_ack (ifu_rtu_lockup_ack ), + .ifu_rtu_reset_halt_req (ifu_rtu_reset_halt_req ), + .ifu_rtu_warm_up (ifu_rtu_warm_up ), + .ifu_sysmap_pa (ifu_sysmap_pa ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .ifu_xx_in_warm_up (ifu_xx_in_warm_up ), + .iu_ifu_bht_cur_pc (iu_ifu_bht_cur_pc ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate), + .iu_ifu_bht_pred (iu_ifu_bht_pred ), + .iu_ifu_bht_taken (iu_ifu_bht_taken ), + .iu_ifu_br_vld (iu_ifu_br_vld ), + .iu_ifu_br_vld_gate (iu_ifu_br_vld_gate ), + .iu_ifu_ind_link_vld (iu_ifu_ind_link_vld ), + .iu_ifu_link_vld (iu_ifu_link_vld ), + .iu_ifu_link_vld_gate (iu_ifu_link_vld_gate ), + .iu_ifu_pc_mispred (iu_ifu_pc_mispred ), + .iu_ifu_pc_mispred_gate (iu_ifu_pc_mispred_gate ), + .iu_ifu_ret_vld (iu_ifu_ret_vld ), + .iu_ifu_ret_vld_gate (iu_ifu_ret_vld_gate ), + .iu_ifu_tar_pc (iu_ifu_tar_pc ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .iu_ifu_tar_pc_vld_gate (iu_ifu_tar_pc_vld_gate ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .rtu_ifu_chgflw_pc (rtu_ifu_chgflw_pc ), + .rtu_ifu_chgflw_vld (rtu_ifu_chgflw_vld ), + .rtu_ifu_dbg_mask (rtu_ifu_dbg_mask ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_ifu_lockup_expt_vld (rtu_ifu_lockup_expt_vld), + .rtu_ifu_lockup_mask (rtu_ifu_lockup_mask ), + .rtu_ifu_lockup_req (rtu_ifu_lockup_req ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .sysio_ifu_rst_addr (sysio_ifu_rst_addr ), + .sysio_ifu_rst_addr_done (sysio_ifu_rst_addr_done), + .sysio_xx_halt_req (sysio_xx_halt_req ), + .sysmap_ifu_flg (sysmap_ifu_flg ) +); + + +//========================================================== +// Instance IDU module +//========================================================== +// &Instance("pa_idu_top"); @38 +pa_idu_top x_pa_idu_top ( + .cp0_idu_ex1_stall (cp0_idu_ex1_stall ), + .cp0_idu_fs (cp0_idu_fs ), + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_mcause (cp0_idu_mcause ), + .cp0_idu_mepc (cp0_idu_mepc ), + .cp0_idu_rm (cp0_idu_rm ), + .cp0_idu_sp_use_scratch (cp0_idu_sp_use_scratch ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_idu_sp_wen (cp0_idu_sp_wen ), + .cp0_idu_sp_wen_gate (cp0_idu_sp_wen_gate ), + .cp0_idu_spec_push_en (cp0_idu_spec_push_en ), + .cp0_idu_swap_sp_en (cp0_idu_swap_sp_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_cskyisaee (cp0_yy_cskyisaee ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .fpu_idu_ex1_stall (fpu_idu_ex1_stall ), + .fpu_idu_fwd_data (fpu_idu_fwd_data ), + .fpu_idu_fwd_freg (fpu_idu_fwd_freg ), + .fpu_idu_fwd_vld (fpu_idu_fwd_vld ), + .fpu_xx_no_op (fpu_xx_no_op ), + .idu_cp0_ex1_cmplt_dp_sel (idu_cp0_ex1_cmplt_dp_sel ), + .idu_cp0_ex1_dst_idx (idu_cp0_ex1_dst_idx ), + .idu_cp0_ex1_dst_vld (idu_cp0_ex1_dst_vld ), + .idu_cp0_ex1_expt_high (idu_cp0_ex1_expt_high ), + .idu_cp0_ex1_expt_type (idu_cp0_ex1_expt_type ), + .idu_cp0_ex1_expt_vld (idu_cp0_ex1_expt_vld ), + .idu_cp0_ex1_func (idu_cp0_ex1_func ), + .idu_cp0_ex1_gateclk_sel (idu_cp0_ex1_gateclk_sel ), + .idu_cp0_ex1_halt_info (idu_cp0_ex1_halt_info ), + .idu_cp0_ex1_inst_len (idu_cp0_ex1_inst_len ), + .idu_cp0_ex1_ipush_spec_fail (idu_cp0_ex1_ipush_spec_fail ), + .idu_cp0_ex1_opcode (idu_cp0_ex1_opcode ), + .idu_cp0_ex1_rs1 (idu_cp0_ex1_rs1 ), + .idu_cp0_ex1_rs2 (idu_cp0_ex1_rs2 ), + .idu_cp0_ex1_sel (idu_cp0_ex1_sel ), + .idu_cp0_ex1_split_inst (idu_cp0_ex1_split_inst ), + .idu_cp0_ex1_tail_fail (idu_cp0_ex1_tail_fail ), + .idu_cp0_id_tail_vld (idu_cp0_id_tail_vld ), + .idu_cp0_ipop_data (idu_cp0_ipop_data ), + .idu_cp0_mcause_wen (idu_cp0_mcause_wen ), + .idu_cp0_mepc_wen (idu_cp0_mepc_wen ), + .idu_cp0_sp_reg (idu_cp0_sp_reg ), + .idu_cp0_sp_swap_pending (idu_cp0_sp_swap_pending ), + .idu_cp0_sp_swap_req (idu_cp0_sp_swap_req ), + .idu_cp0_sp_swap_req_gate (idu_cp0_sp_swap_req_gate ), + .idu_dtu_debug_info (idu_dtu_debug_info ), + .idu_dtu_fpr_info (idu_dtu_fpr_info ), + .idu_fpu_ex1_cmplt_dp_sel (idu_fpu_ex1_cmplt_dp_sel ), + .idu_fpu_ex1_dst_freg (idu_fpu_ex1_dst_freg ), + .idu_fpu_ex1_dst_freg_vld (idu_fpu_ex1_dst_freg_vld ), + .idu_fpu_ex1_dst_preg (idu_fpu_ex1_dst_preg ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .idu_fpu_ex1_func (idu_fpu_ex1_func ), + .idu_fpu_ex1_gateclk_vld (idu_fpu_ex1_gateclk_vld ), + .idu_fpu_ex1_inst_vld (idu_fpu_ex1_inst_vld ), + .idu_fpu_ex1_rm (idu_fpu_ex1_rm ), + .idu_fpu_ex1_srcf0 (idu_fpu_ex1_srcf0 ), + .idu_fpu_ex1_srcf1 (idu_fpu_ex1_srcf1 ), + .idu_fpu_ex1_srcf2 (idu_fpu_ex1_srcf2 ), + .idu_fpu_ex1_srci (idu_fpu_ex1_srci ), + .idu_ifu_id_stall (idu_ifu_id_stall ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .idu_ifu_tail_vld_gate (idu_ifu_tail_vld_gate ), + .idu_ifu_x1 (idu_ifu_x1 ), + .idu_iu_ex1_ag_imm (idu_iu_ex1_ag_imm ), + .idu_iu_ex1_alu_cmplt_dp_sel (idu_iu_ex1_alu_cmplt_dp_sel ), + .idu_iu_ex1_alu_gateclk_sel (idu_iu_ex1_alu_gateclk_sel ), + .idu_iu_ex1_alu_sel (idu_iu_ex1_alu_sel ), + .idu_iu_ex1_bht_pred (idu_iu_ex1_bht_pred ), + .idu_iu_ex1_bju_cmplt_dp_sel (idu_iu_ex1_bju_cmplt_dp_sel ), + .idu_iu_ex1_bju_depd_lsu_src0 (idu_iu_ex1_bju_depd_lsu_src0 ), + .idu_iu_ex1_bju_depd_lsu_src1 (idu_iu_ex1_bju_depd_lsu_src1 ), + .idu_iu_ex1_bju_gateclk_sel (idu_iu_ex1_bju_gateclk_sel ), + .idu_iu_ex1_bju_sel (idu_iu_ex1_bju_sel ), + .idu_iu_ex1_bju_use_pc (idu_iu_ex1_bju_use_pc ), + .idu_iu_ex1_div_cmplt_dp_sel (idu_iu_ex1_div_cmplt_dp_sel ), + .idu_iu_ex1_div_gateclk_sel (idu_iu_ex1_div_gateclk_sel ), + .idu_iu_ex1_div_sel (idu_iu_ex1_div_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_len (idu_iu_ex1_inst_len ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_ipop_int_mask (idu_iu_ex1_ipop_int_mask ), + .idu_iu_ex1_ipush_mie_en (idu_iu_ex1_ipush_mie_en ), + .idu_iu_ex1_ipush_spec_fail (idu_iu_ex1_ipush_spec_fail ), + .idu_iu_ex1_mul_cmplt_dp_sel (idu_iu_ex1_mul_cmplt_dp_sel ), + .idu_iu_ex1_mul_gateclk_sel (idu_iu_ex1_mul_gateclk_sel ), + .idu_iu_ex1_mul_high_sel (idu_iu_ex1_mul_high_sel ), + .idu_iu_ex1_mul_sel (idu_iu_ex1_mul_sel ), + .idu_iu_ex1_rd_pair (idu_iu_ex1_rd_pair ), + .idu_iu_ex1_split (idu_iu_ex1_split ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src0_reg (idu_iu_ex1_src0_reg ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_src1_reg (idu_iu_ex1_src1_reg ), + .idu_iu_ex1_src2 (idu_iu_ex1_src2 ), + .idu_iu_ex1_tail_int_vld (idu_iu_ex1_tail_int_vld ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .idu_iu_tail_fail (idu_iu_tail_fail ), + .idu_iu_tail_fail_gate (idu_iu_tail_fail_gate ), + .idu_lsu_ex1_ag_imm (idu_lsu_ex1_ag_imm ), + .idu_lsu_ex1_base (idu_lsu_ex1_base ), + .idu_lsu_ex1_base_sel (idu_lsu_ex1_base_sel ), + .idu_lsu_ex1_base_wb (idu_lsu_ex1_base_wb ), + .idu_lsu_ex1_data (idu_lsu_ex1_data ), + .idu_lsu_ex1_dest_reg (idu_lsu_ex1_dest_reg ), + .idu_lsu_ex1_dest_vld (idu_lsu_ex1_dest_vld ), + .idu_lsu_ex1_dp_sel (idu_lsu_ex1_dp_sel ), + .idu_lsu_ex1_fls (idu_lsu_ex1_fls ), + .idu_lsu_ex1_func (idu_lsu_ex1_func ), + .idu_lsu_ex1_gateclk_sel (idu_lsu_ex1_gateclk_sel ), + .idu_lsu_ex1_halt_info (idu_lsu_ex1_halt_info ), + .idu_lsu_ex1_ipop_int_mask (idu_lsu_ex1_ipop_int_mask ), + .idu_lsu_ex1_ipush_spec (idu_lsu_ex1_ipush_spec ), + .idu_lsu_ex1_length (idu_lsu_ex1_length ), + .idu_lsu_ex1_offset_sel (idu_lsu_ex1_offset_sel ), + .idu_lsu_ex1_sel (idu_lsu_ex1_sel ), + .idu_lsu_ex1_sign_extend (idu_lsu_ex1_sign_extend ), + .idu_lsu_ex1_size (idu_lsu_ex1_size ), + .idu_lsu_ex1_split (idu_lsu_ex1_split ), + .idu_lsu_ex1_src0_reg (idu_lsu_ex1_src0_reg ), + .idu_lsu_ex1_src1_depd (idu_lsu_ex1_src1_depd ), + .idu_lsu_ex1_src1_reg (idu_lsu_ex1_src1_reg ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_idu_chgflw_flush (ifu_idu_chgflw_flush ), + .ifu_idu_id_expt_high (ifu_idu_id_expt_high ), + .ifu_idu_id_expt_vld (ifu_idu_id_expt_vld ), + .ifu_idu_id_halt_info (ifu_idu_id_halt_info ), + .ifu_idu_id_inst (ifu_idu_id_inst ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .ifu_idu_id_pred_taken (ifu_idu_id_pred_taken ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .iu_idu_bju_global_stall (iu_idu_bju_global_stall ), + .iu_idu_bju_stall (iu_idu_bju_stall ), + .iu_idu_ex1_fwd_data (iu_idu_ex1_fwd_data ), + .iu_idu_ex1_fwd_preg (iu_idu_ex1_fwd_preg ), + .iu_idu_ex1_fwd_vld (iu_idu_ex1_fwd_vld ), + .iu_idu_ex1_src1_update_value (iu_idu_ex1_src1_update_value ), + .iu_idu_ex1_stall (iu_idu_ex1_stall ), + .iu_idu_ex2_div_vld (iu_idu_ex2_div_vld ), + .iu_idu_ex2_fwd_data0 (iu_idu_ex2_fwd_data0 ), + .iu_idu_ex2_fwd_data1 (iu_idu_ex2_fwd_data1 ), + .iu_idu_ex2_fwd_preg0 (iu_idu_ex2_fwd_preg0 ), + .iu_idu_ex2_fwd_preg1 (iu_idu_ex2_fwd_preg1 ), + .iu_idu_ex2_fwd_vld0 (iu_idu_ex2_fwd_vld0 ), + .iu_idu_ex2_fwd_vld1 (iu_idu_ex2_fwd_vld1 ), + .iu_idu_ex2_inst_vld (iu_idu_ex2_inst_vld ), + .iu_idu_ex2_rd_pair (iu_idu_ex2_rd_pair ), + .iu_idu_id_stall (iu_idu_id_stall ), + .iu_xx_no_op (iu_xx_no_op ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .lsu_idu_ex1_halt_info (lsu_idu_ex1_halt_info ), + .lsu_idu_ex1_halt_info_update_en (lsu_idu_ex1_halt_info_update_en ), + .lsu_idu_ex1_src1_update_en (lsu_idu_ex1_src1_update_en ), + .lsu_idu_ex1_src1_update_en_gate (lsu_idu_ex1_src1_update_en_gate ), + .lsu_idu_ex1_stall (lsu_idu_ex1_stall ), + .lsu_idu_ex2_ffwd_data (lsu_idu_ex2_ffwd_data ), + .lsu_idu_ex2_ffwd_vld (lsu_idu_ex2_ffwd_vld ), + .lsu_idu_ex2_fwd_data (lsu_idu_ex2_fwd_data ), + .lsu_idu_ex2_fwd_freg (lsu_idu_ex2_fwd_freg ), + .lsu_idu_ex2_fwd_preg (lsu_idu_ex2_fwd_preg ), + .lsu_idu_ex2_fwd_vld (lsu_idu_ex2_fwd_vld ), + .lsu_idu_ex3_ffwd_data (lsu_idu_ex3_ffwd_data ), + .lsu_idu_ex3_ffwd_vld (lsu_idu_ex3_ffwd_vld ), + .lsu_idu_ex3_fwd_data (lsu_idu_ex3_fwd_data ), + .lsu_idu_ex3_fwd_freg (lsu_idu_ex3_fwd_freg ), + .lsu_idu_ex3_fwd_preg (lsu_idu_ex3_fwd_preg ), + .lsu_idu_ex3_fwd_vld (lsu_idu_ex3_fwd_vld ), + .lsu_idu_global_stall (lsu_idu_global_stall ), + .lsu_idu_update_addr (lsu_idu_update_addr ), + .lsu_idu_update_en (lsu_idu_update_en ), + .lsu_idu_update_en_gate (lsu_idu_update_en_gate ), + .lsu_idu_update_offset (lsu_idu_update_offset ), + .lsu_xx_no_op (lsu_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_ex1_int_dis_stall_gateclk_req (rtu_idu_ex1_int_dis_stall_gateclk_req ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req ), + .rtu_idu_ex2_ipush_spec_inst_expt_vld (rtu_idu_ex2_ipush_spec_inst_expt_vld ), + .rtu_idu_ex2_ipush_spec_inst_halt_info_vld (rtu_idu_ex2_ipush_spec_inst_halt_info_vld), + .rtu_idu_fgpr_wb_data (rtu_idu_fgpr_wb_data ), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_fgpr_wb_reg (rtu_idu_fgpr_wb_reg ), + .rtu_idu_fgpr_wb_vld (rtu_idu_fgpr_wb_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_flush_stall (rtu_idu_flush_stall ), + .rtu_idu_id_tail_int_vld (rtu_idu_id_tail_int_vld ), + .rtu_idu_inst_retire (rtu_idu_inst_retire ), + .rtu_idu_late_flush (rtu_idu_late_flush ), + .rtu_idu_wb0_data (rtu_idu_wb0_data ), + .rtu_idu_wb0_fpu_vld (rtu_idu_wb0_fpu_vld ), + .rtu_idu_wb0_preg (rtu_idu_wb0_preg ), + .rtu_idu_wb0_vld (rtu_idu_wb0_vld ), + .rtu_idu_wb1_data (rtu_idu_wb1_data ), + .rtu_idu_wb1_lsu_vld (rtu_idu_wb1_lsu_vld ), + .rtu_idu_wb1_preg (rtu_idu_wb1_preg ), + .rtu_idu_wb1_vld (rtu_idu_wb1_vld ), + .rtu_idu_wb2_data (rtu_idu_wb2_data ), + .rtu_idu_wb2_preg (rtu_idu_wb2_preg ), + .rtu_idu_wb2_vld (rtu_idu_wb2_vld ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_xx_no_op (rtu_xx_no_op ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + + +//========================================================== +// Instance IU module +//========================================================== +// &Instance("pa_iu_top"); @43 +pa_iu_top x_pa_iu_top ( + .cp0_iu_adder_borrow_in (cp0_iu_adder_borrow_in ), + .cp0_iu_adder_borrow_vld (cp0_iu_adder_borrow_vld ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .fpu_iu_ex1_cmplt (fpu_iu_ex1_cmplt ), + .fpu_iu_ex1_cmplt_dp (fpu_iu_ex1_cmplt_dp ), + .idu_iu_ex1_ag_imm (idu_iu_ex1_ag_imm ), + .idu_iu_ex1_alu_cmplt_dp_sel (idu_iu_ex1_alu_cmplt_dp_sel ), + .idu_iu_ex1_alu_gateclk_sel (idu_iu_ex1_alu_gateclk_sel ), + .idu_iu_ex1_alu_sel (idu_iu_ex1_alu_sel ), + .idu_iu_ex1_bht_pred (idu_iu_ex1_bht_pred ), + .idu_iu_ex1_bju_cmplt_dp_sel (idu_iu_ex1_bju_cmplt_dp_sel ), + .idu_iu_ex1_bju_depd_lsu_src0 (idu_iu_ex1_bju_depd_lsu_src0 ), + .idu_iu_ex1_bju_depd_lsu_src1 (idu_iu_ex1_bju_depd_lsu_src1 ), + .idu_iu_ex1_bju_gateclk_sel (idu_iu_ex1_bju_gateclk_sel ), + .idu_iu_ex1_bju_sel (idu_iu_ex1_bju_sel ), + .idu_iu_ex1_bju_use_pc (idu_iu_ex1_bju_use_pc ), + .idu_iu_ex1_div_cmplt_dp_sel (idu_iu_ex1_div_cmplt_dp_sel ), + .idu_iu_ex1_div_gateclk_sel (idu_iu_ex1_div_gateclk_sel ), + .idu_iu_ex1_div_sel (idu_iu_ex1_div_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_len (idu_iu_ex1_inst_len ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_ipop_int_mask (idu_iu_ex1_ipop_int_mask ), + .idu_iu_ex1_ipush_mie_en (idu_iu_ex1_ipush_mie_en ), + .idu_iu_ex1_ipush_spec_fail (idu_iu_ex1_ipush_spec_fail ), + .idu_iu_ex1_mul_cmplt_dp_sel (idu_iu_ex1_mul_cmplt_dp_sel ), + .idu_iu_ex1_mul_gateclk_sel (idu_iu_ex1_mul_gateclk_sel ), + .idu_iu_ex1_mul_high_sel (idu_iu_ex1_mul_high_sel ), + .idu_iu_ex1_mul_sel (idu_iu_ex1_mul_sel ), + .idu_iu_ex1_rd_pair (idu_iu_ex1_rd_pair ), + .idu_iu_ex1_split (idu_iu_ex1_split ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src0_reg (idu_iu_ex1_src0_reg ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_src1_reg (idu_iu_ex1_src1_reg ), + .idu_iu_ex1_src2 (idu_iu_ex1_src2 ), + .idu_iu_ex1_tail_int_vld (idu_iu_ex1_tail_int_vld ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .idu_iu_tail_fail (idu_iu_tail_fail ), + .idu_iu_tail_fail_gate (idu_iu_tail_fail_gate ), + .ifu_iu_chgflw_pc (ifu_iu_chgflw_pc ), + .ifu_iu_chgflw_vld (ifu_iu_chgflw_vld ), + .ifu_iu_ex1_pc_pred (ifu_iu_ex1_pc_pred ), + .ifu_iu_reset_vld (ifu_iu_reset_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .iu_cp0_ex1_borrow_expt_pc (iu_cp0_ex1_borrow_expt_pc ), + .iu_dtu_debug_info (iu_dtu_debug_info ), + .iu_hpcp_inst_bht_mispred (iu_hpcp_inst_bht_mispred ), + .iu_hpcp_inst_condbr (iu_hpcp_inst_condbr ), + .iu_hpcp_inst_condbr_gate (iu_hpcp_inst_condbr_gate ), + .iu_idu_bju_global_stall (iu_idu_bju_global_stall ), + .iu_idu_bju_stall (iu_idu_bju_stall ), + .iu_idu_ex1_fwd_data (iu_idu_ex1_fwd_data ), + .iu_idu_ex1_fwd_preg (iu_idu_ex1_fwd_preg ), + .iu_idu_ex1_fwd_vld (iu_idu_ex1_fwd_vld ), + .iu_idu_ex1_src1_update_value (iu_idu_ex1_src1_update_value ), + .iu_idu_ex1_stall (iu_idu_ex1_stall ), + .iu_idu_ex2_div_vld (iu_idu_ex2_div_vld ), + .iu_idu_ex2_fwd_data0 (iu_idu_ex2_fwd_data0 ), + .iu_idu_ex2_fwd_data1 (iu_idu_ex2_fwd_data1 ), + .iu_idu_ex2_fwd_preg0 (iu_idu_ex2_fwd_preg0 ), + .iu_idu_ex2_fwd_preg1 (iu_idu_ex2_fwd_preg1 ), + .iu_idu_ex2_fwd_vld0 (iu_idu_ex2_fwd_vld0 ), + .iu_idu_ex2_fwd_vld1 (iu_idu_ex2_fwd_vld1 ), + .iu_idu_ex2_inst_vld (iu_idu_ex2_inst_vld ), + .iu_idu_ex2_rd_pair (iu_idu_ex2_rd_pair ), + .iu_idu_id_stall (iu_idu_id_stall ), + .iu_ifu_bht_cur_pc (iu_ifu_bht_cur_pc ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate ), + .iu_ifu_bht_pred (iu_ifu_bht_pred ), + .iu_ifu_bht_taken (iu_ifu_bht_taken ), + .iu_ifu_br_vld (iu_ifu_br_vld ), + .iu_ifu_br_vld_gate (iu_ifu_br_vld_gate ), + .iu_ifu_ind_link_vld (iu_ifu_ind_link_vld ), + .iu_ifu_link_vld (iu_ifu_link_vld ), + .iu_ifu_link_vld_gate (iu_ifu_link_vld_gate ), + .iu_ifu_pc_mispred (iu_ifu_pc_mispred ), + .iu_ifu_pc_mispred_gate (iu_ifu_pc_mispred_gate ), + .iu_ifu_ret_vld (iu_ifu_ret_vld ), + .iu_ifu_ret_vld_gate (iu_ifu_ret_vld_gate ), + .iu_ifu_tar_pc (iu_ifu_tar_pc ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .iu_ifu_tar_pc_vld_gate (iu_ifu_tar_pc_vld_gate ), + .iu_lsu_ex1_lsi_rst (iu_lsu_ex1_lsi_rst ), + .iu_lsu_ex2_wb0_grant (iu_lsu_ex2_wb0_grant ), + .iu_rtu_ex1_bju_branch_inst (iu_rtu_ex1_bju_branch_inst ), + .iu_rtu_ex1_bju_cmplt (iu_rtu_ex1_bju_cmplt ), + .iu_rtu_ex1_bju_cmplt_dp (iu_rtu_ex1_bju_cmplt_dp ), + .iu_rtu_ex1_bju_cur_pc (iu_rtu_ex1_bju_cur_pc ), + .iu_rtu_ex1_bju_inst_len (iu_rtu_ex1_bju_inst_len ), + .iu_rtu_ex1_bju_inst_vld (iu_rtu_ex1_bju_inst_vld ), + .iu_rtu_ex1_bju_split_inst (iu_rtu_ex1_bju_split_inst ), + .iu_rtu_ex1_cmplt (iu_rtu_ex1_cmplt ), + .iu_rtu_ex1_cmplt_dp (iu_rtu_ex1_cmplt_dp ), + .iu_rtu_ex1_inst_len (iu_rtu_ex1_inst_len ), + .iu_rtu_ex1_inst_vld (iu_rtu_ex1_inst_vld ), + .iu_rtu_ex1_ipop_int_mask (iu_rtu_ex1_ipop_int_mask ), + .iu_rtu_ex1_ipush_mie_en (iu_rtu_ex1_ipush_mie_en ), + .iu_rtu_ex1_ipush_spec_fail (iu_rtu_ex1_ipush_spec_fail ), + .iu_rtu_ex1_next_pc (iu_rtu_ex1_next_pc ), + .iu_rtu_ex1_split_inst (iu_rtu_ex1_split_inst ), + .iu_rtu_ex1_tail_int_vld (iu_rtu_ex1_tail_int_vld ), + .iu_rtu_ex2_bju_flush (iu_rtu_ex2_bju_flush ), + .iu_rtu_ex2_bju_next_pc (iu_rtu_ex2_bju_next_pc ), + .iu_rtu_ex2_bju_next_pc_vld (iu_rtu_ex2_bju_next_pc_vld ), + .iu_rtu_wb0_data (iu_rtu_wb0_data ), + .iu_rtu_wb0_preg (iu_rtu_wb0_preg ), + .iu_rtu_wb0_vld (iu_rtu_wb0_vld ), + .iu_xx_no_op (iu_xx_no_op ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .lsu_iu_ex1_base_wb (lsu_iu_ex1_base_wb ), + .lsu_iu_ex1_src1_sel (lsu_iu_ex1_src1_sel ), + .lsu_iu_ex2_data (lsu_iu_ex2_data ), + .lsu_iu_ex2_data_vld (lsu_iu_ex2_data_vld ), + .lsu_iu_ex2_dest_reg (lsu_iu_ex2_dest_reg ), + .lsu_iu_ex2_lsi_dst_preg (lsu_iu_ex2_lsi_dst_preg ), + .lsu_iu_ex2_lsi_rslt (lsu_iu_ex2_lsi_rslt ), + .lsu_iu_ex2_lsi_rslt_vld (lsu_iu_ex2_lsi_rslt_vld ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_iu_bju_ex2_cur_pc (rtu_iu_bju_ex2_cur_pc ), + .rtu_iu_ex1_cmplt_dp_vld (rtu_iu_ex1_cmplt_dp_vld ), + .rtu_iu_ex1_cmplt_inst_len (rtu_iu_ex1_cmplt_inst_len ), + .rtu_iu_ex1_cmplt_split_inst (rtu_iu_ex1_cmplt_split_inst ), + .rtu_iu_ex1_cmplt_vld (rtu_iu_ex1_cmplt_vld ), + .rtu_iu_pending_spec_expt_vld (rtu_iu_pending_spec_expt_vld ), + .rtu_iu_pending_spec_halt_info_vld (rtu_iu_pending_spec_halt_info_vld), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .sysio_iu_rst_addr (sysio_iu_rst_addr ) +); + + +// //&Force("output", "iu_xx_no_op"); @45 + +//========================================================== +// Instance LSU module +//========================================================== +// &Instance("pa_axi_lsu_top", "x_pa_lsu_top"); @51 +// &Instance("pa_lsu_top"); @53 +pa_lsu_top x_pa_lsu_top ( + .bmu_lsu_acc_err (bmu_lsu_acc_err ), + .bmu_lsu_grant (bmu_lsu_grant ), + .bmu_lsu_rdata (bmu_lsu_rdata ), + .bmu_lsu_trans_cmplt (bmu_lsu_trans_cmplt ), + .cp0_lsu_dcache_en (cp0_lsu_dcache_en ), + .cp0_lsu_dcache_wa (cp0_lsu_dcache_wa ), + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_fence_req (cp0_lsu_fence_req ), + .cp0_lsu_icc_addr (cp0_lsu_icc_addr ), + .cp0_lsu_icc_op (cp0_lsu_icc_op ), + .cp0_lsu_icc_req (cp0_lsu_icc_req ), + .cp0_lsu_icc_type (cp0_lsu_icc_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_lsu_mm (cp0_lsu_mm ), + .cp0_lsu_sync_req (cp0_lsu_sync_req ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .dtu_lsu_addr_trig_en (dtu_lsu_addr_trig_en ), + .dtu_lsu_data_trig_en (dtu_lsu_data_trig_en ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .forever_cpuclk (forever_cpuclk ), + .idu_lsu_ex1_ag_imm (idu_lsu_ex1_ag_imm ), + .idu_lsu_ex1_base (idu_lsu_ex1_base ), + .idu_lsu_ex1_base_sel (idu_lsu_ex1_base_sel ), + .idu_lsu_ex1_base_wb (idu_lsu_ex1_base_wb ), + .idu_lsu_ex1_data (idu_lsu_ex1_data ), + .idu_lsu_ex1_dest_reg (idu_lsu_ex1_dest_reg ), + .idu_lsu_ex1_dest_vld (idu_lsu_ex1_dest_vld ), + .idu_lsu_ex1_dp_sel (idu_lsu_ex1_dp_sel ), + .idu_lsu_ex1_fls (idu_lsu_ex1_fls ), + .idu_lsu_ex1_func (idu_lsu_ex1_func ), + .idu_lsu_ex1_gateclk_sel (idu_lsu_ex1_gateclk_sel ), + .idu_lsu_ex1_halt_info (idu_lsu_ex1_halt_info ), + .idu_lsu_ex1_ipop_int_mask (idu_lsu_ex1_ipop_int_mask ), + .idu_lsu_ex1_ipush_spec (idu_lsu_ex1_ipush_spec ), + .idu_lsu_ex1_length (idu_lsu_ex1_length ), + .idu_lsu_ex1_offset_sel (idu_lsu_ex1_offset_sel ), + .idu_lsu_ex1_sel (idu_lsu_ex1_sel ), + .idu_lsu_ex1_sign_extend (idu_lsu_ex1_sign_extend ), + .idu_lsu_ex1_size (idu_lsu_ex1_size ), + .idu_lsu_ex1_split (idu_lsu_ex1_split ), + .idu_lsu_ex1_src0_reg (idu_lsu_ex1_src0_reg ), + .idu_lsu_ex1_src1_depd (idu_lsu_ex1_src1_depd ), + .idu_lsu_ex1_src1_reg (idu_lsu_ex1_src1_reg ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .iu_lsu_ex1_lsi_rst (iu_lsu_ex1_lsi_rst ), + .iu_lsu_ex2_wb0_grant (iu_lsu_ex2_wb0_grant ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_bmu_acc_deny (lsu_bmu_acc_deny ), + .lsu_bmu_addr (lsu_bmu_addr ), + .lsu_bmu_burst (lsu_bmu_burst ), + .lsu_bmu_lock (lsu_bmu_lock ), + .lsu_bmu_lrsc (lsu_bmu_lrsc ), + .lsu_bmu_prot (lsu_bmu_prot ), + .lsu_bmu_req (lsu_bmu_req ), + .lsu_bmu_req_dp (lsu_bmu_req_dp ), + .lsu_bmu_seq (lsu_bmu_seq ), + .lsu_bmu_size (lsu_bmu_size ), + .lsu_bmu_wdata (lsu_bmu_wdata ), + .lsu_bmu_write (lsu_bmu_write ), + .lsu_cp0_fence_ack (lsu_cp0_fence_ack ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .lsu_cp0_sync_ack (lsu_cp0_sync_ack ), + .lsu_dtu_debug_info (lsu_dtu_debug_info ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .lsu_dtu_ldst_type (lsu_dtu_ldst_type ), + .lsu_dtu_mem_access_size (lsu_dtu_mem_access_size ), + .lsu_hpcp_cache_read_access (lsu_hpcp_cache_read_access ), + .lsu_hpcp_cache_read_access_gate (lsu_hpcp_cache_read_access_gate ), + .lsu_hpcp_cache_read_miss (lsu_hpcp_cache_read_miss ), + .lsu_hpcp_cache_read_miss_gate (lsu_hpcp_cache_read_miss_gate ), + .lsu_hpcp_cache_write_access (lsu_hpcp_cache_write_access ), + .lsu_hpcp_cache_write_access_gate (lsu_hpcp_cache_write_access_gate), + .lsu_hpcp_cache_write_miss (lsu_hpcp_cache_write_miss ), + .lsu_hpcp_cache_write_miss_gate (lsu_hpcp_cache_write_miss_gate ), + .lsu_hpcp_inst_store (lsu_hpcp_inst_store ), + .lsu_hpcp_inst_store_gate (lsu_hpcp_inst_store_gate ), + .lsu_idu_ex1_halt_info (lsu_idu_ex1_halt_info ), + .lsu_idu_ex1_halt_info_update_en (lsu_idu_ex1_halt_info_update_en ), + .lsu_idu_ex1_src1_update_en (lsu_idu_ex1_src1_update_en ), + .lsu_idu_ex1_src1_update_en_gate (lsu_idu_ex1_src1_update_en_gate ), + .lsu_idu_ex1_stall (lsu_idu_ex1_stall ), + .lsu_idu_ex2_ffwd_data (lsu_idu_ex2_ffwd_data ), + .lsu_idu_ex2_ffwd_vld (lsu_idu_ex2_ffwd_vld ), + .lsu_idu_ex2_fwd_data (lsu_idu_ex2_fwd_data ), + .lsu_idu_ex2_fwd_freg (lsu_idu_ex2_fwd_freg ), + .lsu_idu_ex2_fwd_preg (lsu_idu_ex2_fwd_preg ), + .lsu_idu_ex2_fwd_vld (lsu_idu_ex2_fwd_vld ), + .lsu_idu_ex3_ffwd_data (lsu_idu_ex3_ffwd_data ), + .lsu_idu_ex3_ffwd_vld (lsu_idu_ex3_ffwd_vld ), + .lsu_idu_ex3_fwd_data (lsu_idu_ex3_fwd_data ), + .lsu_idu_ex3_fwd_freg (lsu_idu_ex3_fwd_freg ), + .lsu_idu_ex3_fwd_preg (lsu_idu_ex3_fwd_preg ), + .lsu_idu_ex3_fwd_vld (lsu_idu_ex3_fwd_vld ), + .lsu_idu_global_stall (lsu_idu_global_stall ), + .lsu_idu_update_addr (lsu_idu_update_addr ), + .lsu_idu_update_en (lsu_idu_update_en ), + .lsu_idu_update_en_gate (lsu_idu_update_en_gate ), + .lsu_idu_update_offset (lsu_idu_update_offset ), + .lsu_iu_ex1_base_wb (lsu_iu_ex1_base_wb ), + .lsu_iu_ex1_src1_sel (lsu_iu_ex1_src1_sel ), + .lsu_iu_ex2_data (lsu_iu_ex2_data ), + .lsu_iu_ex2_data_vld (lsu_iu_ex2_data_vld ), + .lsu_iu_ex2_dest_reg (lsu_iu_ex2_dest_reg ), + .lsu_iu_ex2_lsi_dst_preg (lsu_iu_ex2_lsi_dst_preg ), + .lsu_iu_ex2_lsi_rslt (lsu_iu_ex2_lsi_rslt ), + .lsu_iu_ex2_lsi_rslt_vld (lsu_iu_ex2_lsi_rslt_vld ), + .lsu_pmp_addr (lsu_pmp_addr ), + .lsu_pmp_write (lsu_pmp_write ), + .lsu_rtu_async_expt_vld (lsu_rtu_async_expt_vld ), + .lsu_rtu_async_ld_inst (lsu_rtu_async_ld_inst ), + .lsu_rtu_async_tval (lsu_rtu_async_tval ), + .lsu_rtu_ex1_cmplt (lsu_rtu_ex1_cmplt ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .lsu_rtu_ex1_halt_info (lsu_rtu_ex1_halt_info ), + .lsu_rtu_ex1_inst_len (lsu_rtu_ex1_inst_len ), + .lsu_rtu_ex1_inst_vld (lsu_rtu_ex1_inst_vld ), + .lsu_rtu_ex1_ipop_int_mask (lsu_rtu_ex1_ipop_int_mask ), + .lsu_rtu_ex1_ipush_spec_inst (lsu_rtu_ex1_ipush_spec_inst ), + .lsu_rtu_ex1_split_inst (lsu_rtu_ex1_split_inst ), + .lsu_rtu_ex2_bus_err (lsu_rtu_ex2_bus_err ), + .lsu_rtu_ex2_expt_inst (lsu_rtu_ex2_expt_inst ), + .lsu_rtu_ex2_expt_vec (lsu_rtu_ex2_expt_vec ), + .lsu_rtu_ex2_stall (lsu_rtu_ex2_stall ), + .lsu_rtu_ex2_tval (lsu_rtu_ex2_tval ), + .lsu_rtu_fgpr_wb_data (lsu_rtu_fgpr_wb_data ), + .lsu_rtu_fgpr_wb_reg (lsu_rtu_fgpr_wb_reg ), + .lsu_rtu_fgpr_wb_vld (lsu_rtu_fgpr_wb_vld ), + .lsu_rtu_sync_ack (lsu_rtu_sync_ack ), + .lsu_rtu_wb_data (lsu_rtu_wb_data ), + .lsu_rtu_wb_preg (lsu_rtu_wb_preg ), + .lsu_rtu_wb_vld (lsu_rtu_wb_vld ), + .lsu_sysmap_pa (lsu_sysmap_pa ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_no_op (lsu_xx_no_op ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_lsu_acc_deny (pmp_lsu_acc_deny ), + .rtu_lsu_async_expt_ack (rtu_lsu_async_expt_ack ), + .rtu_lsu_expt_ack (rtu_lsu_expt_ack ), + .rtu_lsu_expt_exit (rtu_lsu_expt_exit ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_lsu_inst_retire (rtu_lsu_inst_retire ), + .rtu_lsu_sync_req (rtu_lsu_sync_req ), + .rtu_lsu_wb1_data (rtu_lsu_wb1_data ), + .rtu_lsu_wb1_lsu_vld (rtu_lsu_wb1_lsu_vld ), + .rtu_lsu_wb1_preg (rtu_lsu_wb1_preg ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .sysmap_lsu_flg (sysmap_lsu_flg ) +); + + +// //&Force("output", "lsu_xx_no_op"); @56 + +//========================================================== +// Instance CP0 sub module +//========================================================== +// &Instance("pa_cp0_top"); @61 +pa_cp0_top x_pa_cp0_top ( + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_debug_info (cp0_dtu_debug_info ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_int_id (cp0_dtu_int_id ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_dtu_wreg (cp0_dtu_wreg ), + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .cp0_fpu_xx_rm (cp0_fpu_xx_rm ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cp0_hpcp_index (cp0_hpcp_index ), + .cp0_hpcp_pmdm (cp0_hpcp_pmdm ), + .cp0_hpcp_pmdu (cp0_hpcp_pmdu ), + .cp0_hpcp_wdata (cp0_hpcp_wdata ), + .cp0_hpcp_wreg (cp0_hpcp_wreg ), + .cp0_idu_ex1_stall (cp0_idu_ex1_stall ), + .cp0_idu_fs (cp0_idu_fs ), + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_mcause (cp0_idu_mcause ), + .cp0_idu_mepc (cp0_idu_mepc ), + .cp0_idu_rm (cp0_idu_rm ), + .cp0_idu_sp_use_scratch (cp0_idu_sp_use_scratch ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_idu_sp_wen (cp0_idu_sp_wen ), + .cp0_idu_sp_wen_gate (cp0_idu_sp_wen_gate ), + .cp0_idu_spec_push_en (cp0_idu_spec_push_en ), + .cp0_idu_swap_sp_en (cp0_idu_swap_sp_en ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_btb_clr (cp0_ifu_btb_clr ), + .cp0_ifu_btb_en (cp0_ifu_btb_en ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr ), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_in_lpmd (cp0_ifu_in_lpmd ), + .cp0_ifu_lpmd_req (cp0_ifu_lpmd_req ), + .cp0_ifu_mtvec (cp0_ifu_mtvec ), + .cp0_ifu_ras_en (cp0_ifu_ras_en ), + .cp0_ifu_rst_inv_done (cp0_ifu_rst_inv_done ), + .cp0_ifu_srst_mask (cp0_ifu_srst_mask ), + .cp0_ifu_srst_req (cp0_ifu_srst_req ), + .cp0_iu_adder_borrow_in (cp0_iu_adder_borrow_in ), + .cp0_iu_adder_borrow_vld (cp0_iu_adder_borrow_vld ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_lsu_dcache_en (cp0_lsu_dcache_en ), + .cp0_lsu_dcache_wa (cp0_lsu_dcache_wa ), + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_fence_req (cp0_lsu_fence_req ), + .cp0_lsu_icc_addr (cp0_lsu_icc_addr ), + .cp0_lsu_icc_op (cp0_lsu_icc_op ), + .cp0_lsu_icc_req (cp0_lsu_icc_req ), + .cp0_lsu_icc_type (cp0_lsu_icc_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_lsu_mm (cp0_lsu_mm ), + .cp0_lsu_sync_req (cp0_lsu_sync_req ), + .cp0_pad_mcause (cp0_pad_mcause ), + .cp0_pad_mintstatus (cp0_pad_mintstatus ), + .cp0_pad_mstatus (cp0_pad_mstatus ), + .cp0_pmp_csr_sel (cp0_pmp_csr_sel ), + .cp0_pmp_csr_wen (cp0_pmp_csr_wen ), + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv ), + .cp0_pmp_updt_data (cp0_pmp_updt_data ), + .cp0_rtu_ex1_chgflw_pc (cp0_rtu_ex1_chgflw_pc ), + .cp0_rtu_ex1_chgflw_vld (cp0_rtu_ex1_chgflw_vld ), + .cp0_rtu_ex1_cmplt (cp0_rtu_ex1_cmplt ), + .cp0_rtu_ex1_cmplt_dp (cp0_rtu_ex1_cmplt_dp ), + .cp0_rtu_ex1_dret (cp0_rtu_ex1_dret ), + .cp0_rtu_ex1_ebreak (cp0_rtu_ex1_ebreak ), + .cp0_rtu_ex1_expt_inst (cp0_rtu_ex1_expt_inst ), + .cp0_rtu_ex1_expt_tval (cp0_rtu_ex1_expt_tval ), + .cp0_rtu_ex1_expt_vec (cp0_rtu_ex1_expt_vec ), + .cp0_rtu_ex1_flush (cp0_rtu_ex1_flush ), + .cp0_rtu_ex1_halt_info (cp0_rtu_ex1_halt_info ), + .cp0_rtu_ex1_inst_len (cp0_rtu_ex1_inst_len ), + .cp0_rtu_ex1_inst_vld (cp0_rtu_ex1_inst_vld ), + .cp0_rtu_ex1_ipush_spec_fail (cp0_rtu_ex1_ipush_spec_fail), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_ex1_split_inst (cp0_rtu_ex1_split_inst ), + .cp0_rtu_ex1_tail_fail (cp0_rtu_ex1_tail_fail ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_expt (cp0_rtu_in_expt ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_rtu_int_level (cp0_rtu_int_level ), + .cp0_rtu_int_mode (cp0_rtu_int_mode ), + .cp0_rtu_mie (cp0_rtu_mie ), + .cp0_rtu_mnxti_vld (cp0_rtu_mnxti_vld ), + .cp0_rtu_mpil (cp0_rtu_mpil ), + .cp0_rtu_pm_bypass (cp0_rtu_pm_bypass ), + .cp0_rtu_tail_int_hv (cp0_rtu_tail_int_hv ), + .cp0_rtu_tail_int_id (cp0_rtu_tail_int_id ), + .cp0_rtu_wb_data (cp0_rtu_wb_data ), + .cp0_rtu_wb_preg (cp0_rtu_wb_preg ), + .cp0_rtu_wb_vld (cp0_rtu_wb_vld ), + .cp0_rtu_wfe_en (cp0_rtu_wfe_en ), + .cp0_sysio_ipend_b (cp0_sysio_ipend_b ), + .cp0_sysio_lpmd_b (cp0_sysio_lpmd_b ), + .cp0_sysio_srst (cp0_sysio_srst ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_cskyisaee (cp0_yy_cskyisaee ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .dtu_cp0_dcsr_mprven (dtu_cp0_dcsr_mprven ), + .dtu_cp0_dcsr_prv (dtu_cp0_dcsr_prv ), + .dtu_cp0_rdata (dtu_cp0_rdata ), + .dtu_cp0_wake_up (dtu_cp0_wake_up ), + .forever_cpuclk (forever_cpuclk ), + .fpu_cp0_wb_fflags (fpu_cp0_wb_fflags ), + .fpu_cp0_wb_fflags_updt (fpu_cp0_wb_fflags_updt ), + .hpcp_cp0_data (hpcp_cp0_data ), + .idu_cp0_ex1_cmplt_dp_sel (idu_cp0_ex1_cmplt_dp_sel ), + .idu_cp0_ex1_dst_idx (idu_cp0_ex1_dst_idx ), + .idu_cp0_ex1_dst_vld (idu_cp0_ex1_dst_vld ), + .idu_cp0_ex1_expt_high (idu_cp0_ex1_expt_high ), + .idu_cp0_ex1_expt_type (idu_cp0_ex1_expt_type ), + .idu_cp0_ex1_expt_vld (idu_cp0_ex1_expt_vld ), + .idu_cp0_ex1_func (idu_cp0_ex1_func ), + .idu_cp0_ex1_gateclk_sel (idu_cp0_ex1_gateclk_sel ), + .idu_cp0_ex1_halt_info (idu_cp0_ex1_halt_info ), + .idu_cp0_ex1_inst_len (idu_cp0_ex1_inst_len ), + .idu_cp0_ex1_ipush_spec_fail (idu_cp0_ex1_ipush_spec_fail), + .idu_cp0_ex1_opcode (idu_cp0_ex1_opcode ), + .idu_cp0_ex1_rs1 (idu_cp0_ex1_rs1 ), + .idu_cp0_ex1_rs2 (idu_cp0_ex1_rs2 ), + .idu_cp0_ex1_sel (idu_cp0_ex1_sel ), + .idu_cp0_ex1_split_inst (idu_cp0_ex1_split_inst ), + .idu_cp0_ex1_tail_fail (idu_cp0_ex1_tail_fail ), + .idu_cp0_id_tail_vld (idu_cp0_id_tail_vld ), + .idu_cp0_ipop_data (idu_cp0_ipop_data ), + .idu_cp0_mcause_wen (idu_cp0_mcause_wen ), + .idu_cp0_mepc_wen (idu_cp0_mepc_wen ), + .idu_cp0_sp_reg (idu_cp0_sp_reg ), + .idu_cp0_sp_swap_pending (idu_cp0_sp_swap_pending ), + .idu_cp0_sp_swap_req (idu_cp0_sp_swap_req ), + .idu_cp0_sp_swap_req_gate (idu_cp0_sp_swap_req_gate ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done ), + .ifu_cp0_lpmd_ack (ifu_cp0_lpmd_ack ), + .ifu_cp0_rst_inv_req (ifu_cp0_rst_inv_req ), + .ifu_cp0_srst_ack (ifu_cp0_srst_ack ), + .ifu_cp0_vec_err (ifu_cp0_vec_err ), + .ifu_cp0_vec_succeed (ifu_cp0_vec_succeed ), + .ifu_cp0_warm_up (ifu_cp0_warm_up ), + .iu_cp0_ex1_borrow_expt_pc (iu_cp0_ex1_borrow_expt_pc ), + .lsu_cp0_fence_ack (lsu_cp0_fence_ack ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .lsu_cp0_sync_ack (lsu_cp0_sync_ack ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_cp0_data (pmp_cp0_data ), + .rtu_cp0_bus_error (rtu_cp0_bus_error ), + .rtu_cp0_epc (rtu_cp0_epc ), + .rtu_cp0_exit_debug (rtu_cp0_exit_debug ), + .rtu_cp0_fp_dirty_vld (rtu_cp0_fp_dirty_vld ), + .rtu_cp0_int_level (rtu_cp0_int_level ), + .rtu_cp0_lockup_clr (rtu_cp0_lockup_clr ), + .rtu_cp0_lockup_vld (rtu_cp0_lockup_vld ), + .rtu_cp0_mie_en (rtu_cp0_mie_en ), + .rtu_cp0_mie_gateclk_en (rtu_cp0_mie_gateclk_en ), + .rtu_cp0_mnxti_pending_vld (rtu_cp0_mnxti_pending_vld ), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_cp0_pending_int_hv (rtu_cp0_pending_int_hv ), + .rtu_cp0_pending_int_id (rtu_cp0_pending_int_id ), + .rtu_cp0_pending_int_level (rtu_cp0_pending_int_level ), + .rtu_cp0_tval (rtu_cp0_tval ), + .rtu_cp0_wk_int (rtu_cp0_wk_int ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .sysio_cp0_clk_en (sysio_cp0_clk_en ), + .sysio_cp0_clkratio (sysio_cp0_clkratio ), + .sysio_cp0_rst_addr (sysio_cp0_rst_addr ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ) +); + +// &Force("output", "cp0_yy_priv_mode"); @62 +// &Force("output", "cp0_yy_clk_en"); @64 +// &Force("output", "cp0_yy_mach_mode"); @65 +// &Force("output", "cp0_yy_clk_en"); @68 +// &Force("output", "cp0_yy_clk_en"); @71 + +//========================================================== +// Instance RTU module +//========================================================== +// &Instance("pa_rtu_top"); @79 +pa_rtu_top x_pa_rtu_top ( + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .cp0_rtu_ex1_chgflw_pc (cp0_rtu_ex1_chgflw_pc ), + .cp0_rtu_ex1_chgflw_vld (cp0_rtu_ex1_chgflw_vld ), + .cp0_rtu_ex1_cmplt (cp0_rtu_ex1_cmplt ), + .cp0_rtu_ex1_cmplt_dp (cp0_rtu_ex1_cmplt_dp ), + .cp0_rtu_ex1_dret (cp0_rtu_ex1_dret ), + .cp0_rtu_ex1_ebreak (cp0_rtu_ex1_ebreak ), + .cp0_rtu_ex1_expt_inst (cp0_rtu_ex1_expt_inst ), + .cp0_rtu_ex1_expt_tval (cp0_rtu_ex1_expt_tval ), + .cp0_rtu_ex1_expt_vec (cp0_rtu_ex1_expt_vec ), + .cp0_rtu_ex1_flush (cp0_rtu_ex1_flush ), + .cp0_rtu_ex1_halt_info (cp0_rtu_ex1_halt_info ), + .cp0_rtu_ex1_inst_len (cp0_rtu_ex1_inst_len ), + .cp0_rtu_ex1_inst_vld (cp0_rtu_ex1_inst_vld ), + .cp0_rtu_ex1_ipush_spec_fail (cp0_rtu_ex1_ipush_spec_fail ), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_ex1_split_inst (cp0_rtu_ex1_split_inst ), + .cp0_rtu_ex1_tail_fail (cp0_rtu_ex1_tail_fail ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_expt (cp0_rtu_in_expt ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_rtu_int_level (cp0_rtu_int_level ), + .cp0_rtu_int_mode (cp0_rtu_int_mode ), + .cp0_rtu_mie (cp0_rtu_mie ), + .cp0_rtu_mnxti_vld (cp0_rtu_mnxti_vld ), + .cp0_rtu_mpil (cp0_rtu_mpil ), + .cp0_rtu_pm_bypass (cp0_rtu_pm_bypass ), + .cp0_rtu_tail_int_hv (cp0_rtu_tail_int_hv ), + .cp0_rtu_tail_int_id (cp0_rtu_tail_int_id ), + .cp0_rtu_wb_data (cp0_rtu_wb_data ), + .cp0_rtu_wb_preg (cp0_rtu_wb_preg ), + .cp0_rtu_wb_vld (cp0_rtu_wb_vld ), + .cp0_rtu_wfe_en (cp0_rtu_wfe_en ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpurst_b (cpurst_b ), + .dtu_rtu_async_halt_req (dtu_rtu_async_halt_req ), + .dtu_rtu_dpc (dtu_rtu_dpc ), + .dtu_rtu_ebreak_action (dtu_rtu_ebreak_action ), + .dtu_rtu_int_mask (dtu_rtu_int_mask ), + .dtu_rtu_pending_tval (dtu_rtu_pending_tval ), + .dtu_rtu_resume_req (dtu_rtu_resume_req ), + .dtu_rtu_step_en (dtu_rtu_step_en ), + .dtu_rtu_sync_flush (dtu_rtu_sync_flush ), + .dtu_rtu_sync_halt_req (dtu_rtu_sync_halt_req ), + .forever_cpuclk (forever_cpuclk ), + .fpu_rtu_fgpr_wb_data (fpu_rtu_fgpr_wb_data ), + .fpu_rtu_fgpr_wb_reg (fpu_rtu_fgpr_wb_reg ), + .fpu_rtu_fgpr_wb_vld (fpu_rtu_fgpr_wb_vld ), + .fpu_rtu_wb_data (fpu_rtu_wb_data ), + .fpu_rtu_wb_preg (fpu_rtu_wb_preg ), + .fpu_rtu_wb_vld (fpu_rtu_wb_vld ), + .fpu_xx_no_op (fpu_xx_no_op ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_rtu_lockup_ack (ifu_rtu_lockup_ack ), + .ifu_rtu_reset_halt_req (ifu_rtu_reset_halt_req ), + .ifu_rtu_warm_up (ifu_rtu_warm_up ), + .iu_rtu_ex1_bju_branch_inst (iu_rtu_ex1_bju_branch_inst ), + .iu_rtu_ex1_bju_cmplt (iu_rtu_ex1_bju_cmplt ), + .iu_rtu_ex1_bju_cmplt_dp (iu_rtu_ex1_bju_cmplt_dp ), + .iu_rtu_ex1_bju_cur_pc (iu_rtu_ex1_bju_cur_pc ), + .iu_rtu_ex1_bju_inst_len (iu_rtu_ex1_bju_inst_len ), + .iu_rtu_ex1_bju_inst_vld (iu_rtu_ex1_bju_inst_vld ), + .iu_rtu_ex1_bju_split_inst (iu_rtu_ex1_bju_split_inst ), + .iu_rtu_ex1_cmplt (iu_rtu_ex1_cmplt ), + .iu_rtu_ex1_cmplt_dp (iu_rtu_ex1_cmplt_dp ), + .iu_rtu_ex1_inst_len (iu_rtu_ex1_inst_len ), + .iu_rtu_ex1_inst_vld (iu_rtu_ex1_inst_vld ), + .iu_rtu_ex1_ipop_int_mask (iu_rtu_ex1_ipop_int_mask ), + .iu_rtu_ex1_ipush_mie_en (iu_rtu_ex1_ipush_mie_en ), + .iu_rtu_ex1_ipush_spec_fail (iu_rtu_ex1_ipush_spec_fail ), + .iu_rtu_ex1_next_pc (iu_rtu_ex1_next_pc ), + .iu_rtu_ex1_split_inst (iu_rtu_ex1_split_inst ), + .iu_rtu_ex1_tail_int_vld (iu_rtu_ex1_tail_int_vld ), + .iu_rtu_ex2_bju_flush (iu_rtu_ex2_bju_flush ), + .iu_rtu_ex2_bju_next_pc (iu_rtu_ex2_bju_next_pc ), + .iu_rtu_ex2_bju_next_pc_vld (iu_rtu_ex2_bju_next_pc_vld ), + .iu_rtu_wb0_data (iu_rtu_wb0_data ), + .iu_rtu_wb0_preg (iu_rtu_wb0_preg ), + .iu_rtu_wb0_vld (iu_rtu_wb0_vld ), + .iu_xx_no_op (iu_xx_no_op ), + .lsu_rtu_async_expt_vld (lsu_rtu_async_expt_vld ), + .lsu_rtu_async_ld_inst (lsu_rtu_async_ld_inst ), + .lsu_rtu_async_tval (lsu_rtu_async_tval ), + .lsu_rtu_ex1_cmplt (lsu_rtu_ex1_cmplt ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .lsu_rtu_ex1_halt_info (lsu_rtu_ex1_halt_info ), + .lsu_rtu_ex1_inst_len (lsu_rtu_ex1_inst_len ), + .lsu_rtu_ex1_inst_vld (lsu_rtu_ex1_inst_vld ), + .lsu_rtu_ex1_ipop_int_mask (lsu_rtu_ex1_ipop_int_mask ), + .lsu_rtu_ex1_ipush_spec_inst (lsu_rtu_ex1_ipush_spec_inst ), + .lsu_rtu_ex1_split_inst (lsu_rtu_ex1_split_inst ), + .lsu_rtu_ex2_bus_err (lsu_rtu_ex2_bus_err ), + .lsu_rtu_ex2_expt_inst (lsu_rtu_ex2_expt_inst ), + .lsu_rtu_ex2_expt_vec (lsu_rtu_ex2_expt_vec ), + .lsu_rtu_ex2_stall (lsu_rtu_ex2_stall ), + .lsu_rtu_ex2_tval (lsu_rtu_ex2_tval ), + .lsu_rtu_fgpr_wb_data (lsu_rtu_fgpr_wb_data ), + .lsu_rtu_fgpr_wb_reg (lsu_rtu_fgpr_wb_reg ), + .lsu_rtu_fgpr_wb_vld (lsu_rtu_fgpr_wb_vld ), + .lsu_rtu_sync_ack (lsu_rtu_sync_ack ), + .lsu_rtu_wb_data (lsu_rtu_wb_data ), + .lsu_rtu_wb_preg (lsu_rtu_wb_preg ), + .lsu_rtu_wb_vld (lsu_rtu_wb_vld ), + .lsu_xx_no_op (lsu_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_cp0_bus_error (rtu_cp0_bus_error ), + .rtu_cp0_epc (rtu_cp0_epc ), + .rtu_cp0_exit_debug (rtu_cp0_exit_debug ), + .rtu_cp0_fp_dirty_vld (rtu_cp0_fp_dirty_vld ), + .rtu_cp0_int_level (rtu_cp0_int_level ), + .rtu_cp0_lockup_clr (rtu_cp0_lockup_clr ), + .rtu_cp0_lockup_vld (rtu_cp0_lockup_vld ), + .rtu_cp0_mie_en (rtu_cp0_mie_en ), + .rtu_cp0_mie_gateclk_en (rtu_cp0_mie_gateclk_en ), + .rtu_cp0_mnxti_pending_vld (rtu_cp0_mnxti_pending_vld ), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_cp0_pending_int_hv (rtu_cp0_pending_int_hv ), + .rtu_cp0_pending_int_id (rtu_cp0_pending_int_id ), + .rtu_cp0_pending_int_level (rtu_cp0_pending_int_level ), + .rtu_cp0_tval (rtu_cp0_tval ), + .rtu_cp0_wk_int (rtu_cp0_wk_int ), + .rtu_dtu_debug_info (rtu_dtu_debug_info ), + .rtu_dtu_dpc (rtu_dtu_dpc ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_nmi_pending (rtu_dtu_nmi_pending ), + .rtu_dtu_pending_ack (rtu_dtu_pending_ack ), + .rtu_dtu_retire_chgflw (rtu_dtu_retire_chgflw ), + .rtu_dtu_retire_debug_expt_vld (rtu_dtu_retire_debug_expt_vld ), + .rtu_dtu_retire_halt_info (rtu_dtu_retire_halt_info ), + .rtu_dtu_retire_mret (rtu_dtu_retire_mret ), + .rtu_dtu_retire_next_pc (rtu_dtu_retire_next_pc ), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ), + .rtu_dtu_tval (rtu_dtu_tval ), + .rtu_fpu_fgpr_wb_grant (rtu_fpu_fgpr_wb_grant ), + .rtu_fpu_wb_grant (rtu_fpu_wb_grant ), + .rtu_hpcp_retire_inst_vld (rtu_hpcp_retire_inst_vld ), + .rtu_idu_ex1_int_dis_stall_gateclk_req (rtu_idu_ex1_int_dis_stall_gateclk_req ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req ), + .rtu_idu_ex2_ipush_spec_inst_expt_vld (rtu_idu_ex2_ipush_spec_inst_expt_vld ), + .rtu_idu_ex2_ipush_spec_inst_halt_info_vld (rtu_idu_ex2_ipush_spec_inst_halt_info_vld), + .rtu_idu_fgpr_wb_data (rtu_idu_fgpr_wb_data ), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_fgpr_wb_reg (rtu_idu_fgpr_wb_reg ), + .rtu_idu_fgpr_wb_vld (rtu_idu_fgpr_wb_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_flush_stall (rtu_idu_flush_stall ), + .rtu_idu_id_tail_int_vld (rtu_idu_id_tail_int_vld ), + .rtu_idu_inst_retire (rtu_idu_inst_retire ), + .rtu_idu_late_flush (rtu_idu_late_flush ), + .rtu_idu_wb0_data (rtu_idu_wb0_data ), + .rtu_idu_wb0_fpu_vld (rtu_idu_wb0_fpu_vld ), + .rtu_idu_wb0_preg (rtu_idu_wb0_preg ), + .rtu_idu_wb0_vld (rtu_idu_wb0_vld ), + .rtu_idu_wb1_data (rtu_idu_wb1_data ), + .rtu_idu_wb1_lsu_vld (rtu_idu_wb1_lsu_vld ), + .rtu_idu_wb1_preg (rtu_idu_wb1_preg ), + .rtu_idu_wb1_vld (rtu_idu_wb1_vld ), + .rtu_idu_wb2_data (rtu_idu_wb2_data ), + .rtu_idu_wb2_preg (rtu_idu_wb2_preg ), + .rtu_idu_wb2_vld (rtu_idu_wb2_vld ), + .rtu_ifu_chgflw_pc (rtu_ifu_chgflw_pc ), + .rtu_ifu_chgflw_vld (rtu_ifu_chgflw_vld ), + .rtu_ifu_dbg_mask (rtu_ifu_dbg_mask ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_ifu_lockup_expt_vld (rtu_ifu_lockup_expt_vld ), + .rtu_ifu_lockup_mask (rtu_ifu_lockup_mask ), + .rtu_ifu_lockup_req (rtu_ifu_lockup_req ), + .rtu_iu_bju_ex2_cur_pc (rtu_iu_bju_ex2_cur_pc ), + .rtu_iu_ex1_cmplt_dp_vld (rtu_iu_ex1_cmplt_dp_vld ), + .rtu_iu_ex1_cmplt_inst_len (rtu_iu_ex1_cmplt_inst_len ), + .rtu_iu_ex1_cmplt_split_inst (rtu_iu_ex1_cmplt_split_inst ), + .rtu_iu_ex1_cmplt_vld (rtu_iu_ex1_cmplt_vld ), + .rtu_iu_pending_spec_expt_vld (rtu_iu_pending_spec_expt_vld ), + .rtu_iu_pending_spec_halt_info_vld (rtu_iu_pending_spec_halt_info_vld ), + .rtu_lsu_async_expt_ack (rtu_lsu_async_expt_ack ), + .rtu_lsu_expt_ack (rtu_lsu_expt_ack ), + .rtu_lsu_expt_exit (rtu_lsu_expt_exit ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_lsu_inst_retire (rtu_lsu_inst_retire ), + .rtu_lsu_sync_req (rtu_lsu_sync_req ), + .rtu_lsu_wb1_data (rtu_lsu_wb1_data ), + .rtu_lsu_wb1_lsu_vld (rtu_lsu_wb1_lsu_vld ), + .rtu_lsu_wb1_preg (rtu_lsu_wb1_preg ), + .rtu_pad_inst_retire (rtu_pad_inst_retire ), + .rtu_pad_inst_split (rtu_pad_inst_split ), + .rtu_pad_retire_pc (rtu_pad_retire_pc ), + .rtu_pad_wb0_data (rtu_pad_wb0_data ), + .rtu_pad_wb0_preg (rtu_pad_wb0_preg ), + .rtu_pad_wb0_vld (rtu_pad_wb0_vld ), + .rtu_pad_wb1_data (rtu_pad_wb1_data ), + .rtu_pad_wb1_preg (rtu_pad_wb1_preg ), + .rtu_pad_wb1_vld (rtu_pad_wb1_vld ), + .rtu_pad_wb2_data (rtu_pad_wb2_data ), + .rtu_pad_wb2_preg (rtu_pad_wb2_preg ), + .rtu_pad_wb2_vld (rtu_pad_wb2_vld ), + .rtu_pad_wb_freg (rtu_pad_wb_freg ), + .rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), + .rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ), + .rtu_sysio_halted (rtu_sysio_halted ), + .rtu_sysio_lockup_on (rtu_sysio_lockup_on ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_xx_no_op (rtu_xx_no_op ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .sysio_rtu_nmi_int (sysio_rtu_nmi_int ), + .sysio_rtu_wk_event (sysio_rtu_wk_event ) +); + + +// &Force("output", "rtu_yy_xx_dbgon"); @81 +// &Force("output", "rtu_yy_xx_expt_vld"); @82 +// &Force("output", "rtu_yy_xx_expt_int"); @83 +// &Force("output", "rtu_yy_xx_expt_vec"); @84 +// &Force("output", "idu_yy_xx_tail_ack"); @85 +// &Force("output", "rtu_yy_xx_async_flush"); @88 + +// &Instance("pa_fpu_top"); @92 +pa_fpu_top x_pa_fpu_top ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .cp0_fpu_xx_rm (cp0_fpu_xx_rm ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (fpu_gated_cpuclk ), + .fpu_cp0_wb_fflags (fpu_cp0_wb_fflags ), + .fpu_cp0_wb_fflags_updt (fpu_cp0_wb_fflags_updt ), + .fpu_dtu_debug_info (fpu_dtu_debug_info ), + .fpu_idu_ex1_stall (fpu_idu_ex1_stall ), + .fpu_idu_fwd_data (fpu_idu_fwd_data ), + .fpu_idu_fwd_freg (fpu_idu_fwd_freg ), + .fpu_idu_fwd_vld (fpu_idu_fwd_vld ), + .fpu_iu_ex1_cmplt (fpu_iu_ex1_cmplt ), + .fpu_iu_ex1_cmplt_dp (fpu_iu_ex1_cmplt_dp ), + .fpu_rtu_fgpr_wb_data (fpu_rtu_fgpr_wb_data ), + .fpu_rtu_fgpr_wb_reg (fpu_rtu_fgpr_wb_reg ), + .fpu_rtu_fgpr_wb_vld (fpu_rtu_fgpr_wb_vld ), + .fpu_rtu_wb_data (fpu_rtu_wb_data ), + .fpu_rtu_wb_preg (fpu_rtu_wb_preg ), + .fpu_rtu_wb_vld (fpu_rtu_wb_vld ), + .fpu_wb_float_fflags_updt (fpu_wb_float_fflags_updt), + .fpu_xx_no_op (fpu_xx_no_op ), + .idu_fpu_ex1_cmplt_dp_sel (idu_fpu_ex1_cmplt_dp_sel), + .idu_fpu_ex1_dst_freg (idu_fpu_ex1_dst_freg ), + .idu_fpu_ex1_dst_freg_vld (idu_fpu_ex1_dst_freg_vld), + .idu_fpu_ex1_dst_preg (idu_fpu_ex1_dst_preg ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .idu_fpu_ex1_func (idu_fpu_ex1_func ), + .idu_fpu_ex1_gateclk_vld (idu_fpu_ex1_gateclk_vld ), + .idu_fpu_ex1_inst_vld (idu_fpu_ex1_inst_vld ), + .idu_fpu_ex1_rm (idu_fpu_ex1_rm ), + .idu_fpu_ex1_srcf0 (idu_fpu_ex1_srcf0 ), + .idu_fpu_ex1_srcf1 (idu_fpu_ex1_srcf1 ), + .idu_fpu_ex1_srcf2 (idu_fpu_ex1_srcf2 ), + .idu_fpu_ex1_srci (idu_fpu_ex1_srci ), + .ifu_fpu_warm_up (ifu_fpu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_fpu_fgpr_wb_grant (rtu_fpu_fgpr_wb_grant ), + .rtu_fpu_wb_grant (rtu_fpu_wb_grant ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + +// &Connect(.forever_cpuclk (fpu_gated_cpuclk)); @93 + +assign fpu_gated_cpuclk_en = !fpu_xx_no_op + || fpu_wb_float_fflags_updt +// || rtu_fpu_frbus_wb_vld + || ifu_xx_in_warm_up; +// &Instance("gated_clk_cell", "x_cp0_fpu_cpuclk"); @99 +gated_clk_cell x_cp0_fpu_cpuclk ( + .clk_in (forever_cpuclk ), + .clk_out (fpu_gated_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fpu_gated_cpuclk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @100 +// .external_en (1'b0), @101 +// .global_en (cp0_yy_clk_en), @102 +// .module_en (cp0_fpu_icg_en), @103 +// .local_en (fpu_gated_cpuclk_en), @104 +// .clk_out (fpu_gated_cpuclk)); @105 + +// &ModuleEnd; @108 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core_top.v new file mode 100644 index 0000000000000000000000000000000000000000..dc64e8f83de8695baec4420223573d1e24944b2d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_core_top.v @@ -0,0 +1,1536 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_core_top( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hlock, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwdata, + biu_pad_hwrite, + bmu_tcipif_dbus_acc_deny, + bmu_tcipif_dbus_addr, + bmu_tcipif_dbus_req, + bmu_tcipif_dbus_req_dp, + bmu_tcipif_dbus_size, + bmu_tcipif_dbus_supv_mode, + bmu_tcipif_dbus_wdata, + bmu_tcipif_dbus_write, + bmu_tcipif_ibus_acc_deny, + bmu_tcipif_ibus_addr, + bmu_tcipif_ibus_req, + bmu_tcipif_ibus_req_dp, + bmu_tcipif_ibus_size, + bmu_tcipif_ibus_supv_mode, + bmu_tcipif_ibus_wdata, + bmu_tcipif_ibus_write, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + clk_en_f, + cp0_biu_icg_en, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cp0_yy_priv_mode, + cpu_clic_curid, + cpu_clic_int_exit, + cpu_pad_dfs_ack, + cpu_pad_halted, + cpu_pad_lockup, + cpu_pad_soft_rst, + cpurst_b, + dahbl_pad_haddr, + dahbl_pad_hburst, + dahbl_pad_hlock, + dahbl_pad_hprot, + dahbl_pad_hsize, + dahbl_pad_htrans, + dahbl_pad_hwdata, + dahbl_pad_hwrite, + dtu_tdt_dm_halted, + dtu_tdt_dm_havereset, + dtu_tdt_dm_itr_done, + dtu_tdt_dm_retire_debug_expt_vld, + dtu_tdt_dm_rx_data, + dtu_tdt_dm_wr_ready, + forever_cpuclk, + iahbl_pad_haddr, + iahbl_pad_hburst, + iahbl_pad_hlock, + iahbl_pad_hprot, + iahbl_pad_hsize, + iahbl_pad_htrans, + iahbl_pad_hwdata, + iahbl_pad_hwrite, + ifu_clic_warm_up, + pad_biu_hrdata, + pad_biu_hready, + pad_biu_hresp, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_cpu_dfs_req, + pad_cpu_ext_int_b, + pad_cpu_nmi, + pad_cpu_rst_addr, + pad_cpu_sys_cnt, + pad_cpu_sysmap_addr0, + pad_cpu_sysmap_addr0_attr, + pad_cpu_sysmap_addr1, + pad_cpu_sysmap_addr1_attr, + pad_cpu_sysmap_addr2, + pad_cpu_sysmap_addr2_attr, + pad_cpu_sysmap_addr3, + pad_cpu_sysmap_addr3_attr, + pad_cpu_sysmap_addr4, + pad_cpu_sysmap_addr4_attr, + pad_cpu_sysmap_addr5, + pad_cpu_sysmap_addr5_attr, + pad_cpu_sysmap_addr6, + pad_cpu_sysmap_addr6_attr, + pad_cpu_sysmap_addr7, + pad_cpu_sysmap_addr7_attr, + pad_cpu_tcip_base, + pad_cpu_wakeup_event, + pad_dahbl_hrdata, + pad_dahbl_hready, + pad_dahbl_hresp, + pad_iahbl_hrdata, + pad_iahbl_hready, + pad_iahbl_hresp, + pad_yy_icg_scan_en, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld, + rtu_yy_xx_dbgon, + sys_apb_clk, + sys_apb_rst_b, + sysio_clint_me_int, + sysio_clint_mtime, + sysio_pad_lpmd_b, + sysmap_tcipif_cmplt, + sysmap_tcipif_rdata, + tcip_cp0_clic_base, + tcipif_bmu_dbus_acc_err, + tcipif_bmu_dbus_data, + tcipif_bmu_dbus_grnt, + tcipif_bmu_dbus_trans_cmplt, + tcipif_bmu_ibus_acc_err, + tcipif_bmu_ibus_data, + tcipif_bmu_ibus_grnt, + tcipif_bmu_ibus_trans_cmplt, + tcipif_sysmap_addr, + tcipif_sysmap_sel, + tcipif_sysmap_wdata, + tcipif_sysmap_write, + tdt_dm_dtu_ack_havereset, + tdt_dm_dtu_async_halt_req, + tdt_dm_dtu_halt_on_reset, + tdt_dm_dtu_halt_req, + tdt_dm_dtu_itr, + tdt_dm_dtu_itr_vld, + tdt_dm_dtu_resume_req, + tdt_dm_dtu_wdata, + tdt_dm_dtu_wr_flg, + tdt_dm_dtu_wr_vld +); + +// &Ports; @26 +input clic_cpu_int_hv; +input [11:0] clic_cpu_int_id; +input [7 :0] clic_cpu_int_il; +input [1 :0] clic_cpu_int_priv; +input clk_en_f; +input cpurst_b; +input forever_cpuclk; +input [31:0] pad_biu_hrdata; +input pad_biu_hready; +input pad_biu_hresp; +input [11:0] pad_bmu_dahbl_base; +input [11:0] pad_bmu_dahbl_mask; +input [11:0] pad_bmu_iahbl_base; +input [11:0] pad_bmu_iahbl_mask; +input pad_cpu_dfs_req; +input pad_cpu_ext_int_b; +input pad_cpu_nmi; +input [31:0] pad_cpu_rst_addr; +input [63:0] pad_cpu_sys_cnt; +input [19:0] pad_cpu_sysmap_addr0; +input [2 :0] pad_cpu_sysmap_addr0_attr; +input [19:0] pad_cpu_sysmap_addr1; +input [2 :0] pad_cpu_sysmap_addr1_attr; +input [19:0] pad_cpu_sysmap_addr2; +input [2 :0] pad_cpu_sysmap_addr2_attr; +input [19:0] pad_cpu_sysmap_addr3; +input [2 :0] pad_cpu_sysmap_addr3_attr; +input [19:0] pad_cpu_sysmap_addr4; +input [2 :0] pad_cpu_sysmap_addr4_attr; +input [19:0] pad_cpu_sysmap_addr5; +input [2 :0] pad_cpu_sysmap_addr5_attr; +input [19:0] pad_cpu_sysmap_addr6; +input [2 :0] pad_cpu_sysmap_addr6_attr; +input [19:0] pad_cpu_sysmap_addr7; +input [2 :0] pad_cpu_sysmap_addr7_attr; +input [31:0] pad_cpu_tcip_base; +input pad_cpu_wakeup_event; +input [31:0] pad_dahbl_hrdata; +input pad_dahbl_hready; +input pad_dahbl_hresp; +input [31:0] pad_iahbl_hrdata; +input pad_iahbl_hready; +input pad_iahbl_hresp; +input pad_yy_icg_scan_en; +input sys_apb_clk; +input sys_apb_rst_b; +input [31:0] tcip_cp0_clic_base; +input tcipif_bmu_dbus_acc_err; +input [31:0] tcipif_bmu_dbus_data; +input tcipif_bmu_dbus_grnt; +input tcipif_bmu_dbus_trans_cmplt; +input tcipif_bmu_ibus_acc_err; +input [31:0] tcipif_bmu_ibus_data; +input tcipif_bmu_ibus_grnt; +input tcipif_bmu_ibus_trans_cmplt; +input [15:0] tcipif_sysmap_addr; +input tcipif_sysmap_sel; +input [31:0] tcipif_sysmap_wdata; +input tcipif_sysmap_write; +input tdt_dm_dtu_ack_havereset; +input tdt_dm_dtu_async_halt_req; +input tdt_dm_dtu_halt_on_reset; +input tdt_dm_dtu_halt_req; +input [31:0] tdt_dm_dtu_itr; +input tdt_dm_dtu_itr_vld; +input tdt_dm_dtu_resume_req; +input [31:0] tdt_dm_dtu_wdata; +input [1 :0] tdt_dm_dtu_wr_flg; +input tdt_dm_dtu_wr_vld; +output [31:0] biu_pad_haddr; +output [2 :0] biu_pad_hburst; +output biu_pad_hlock; +output [3 :0] biu_pad_hprot; +output [2 :0] biu_pad_hsize; +output [1 :0] biu_pad_htrans; +output [31:0] biu_pad_hwdata; +output biu_pad_hwrite; +output bmu_tcipif_dbus_acc_deny; +output [31:0] bmu_tcipif_dbus_addr; +output bmu_tcipif_dbus_req; +output bmu_tcipif_dbus_req_dp; +output [1 :0] bmu_tcipif_dbus_size; +output bmu_tcipif_dbus_supv_mode; +output [31:0] bmu_tcipif_dbus_wdata; +output bmu_tcipif_dbus_write; +output bmu_tcipif_ibus_acc_deny; +output [31:0] bmu_tcipif_ibus_addr; +output bmu_tcipif_ibus_req; +output bmu_tcipif_ibus_req_dp; +output [1 :0] bmu_tcipif_ibus_size; +output bmu_tcipif_ibus_supv_mode; +output [31:0] bmu_tcipif_ibus_wdata; +output bmu_tcipif_ibus_write; +output cp0_biu_icg_en; +output [31:0] cp0_pad_mcause; +output [31:0] cp0_pad_mintstatus; +output [31:0] cp0_pad_mstatus; +output [1 :0] cp0_yy_priv_mode; +output [11:0] cpu_clic_curid; +output cpu_clic_int_exit; +output cpu_pad_dfs_ack; +output cpu_pad_halted; +output cpu_pad_lockup; +output [1 :0] cpu_pad_soft_rst; +output [31:0] dahbl_pad_haddr; +output [2 :0] dahbl_pad_hburst; +output dahbl_pad_hlock; +output [3 :0] dahbl_pad_hprot; +output [2 :0] dahbl_pad_hsize; +output [1 :0] dahbl_pad_htrans; +output [31:0] dahbl_pad_hwdata; +output dahbl_pad_hwrite; +output dtu_tdt_dm_halted; +output dtu_tdt_dm_havereset; +output dtu_tdt_dm_itr_done; +output dtu_tdt_dm_retire_debug_expt_vld; +output [31:0] dtu_tdt_dm_rx_data; +output dtu_tdt_dm_wr_ready; +output [31:0] iahbl_pad_haddr; +output [2 :0] iahbl_pad_hburst; +output iahbl_pad_hlock; +output [3 :0] iahbl_pad_hprot; +output [2 :0] iahbl_pad_hsize; +output [1 :0] iahbl_pad_htrans; +output [31:0] iahbl_pad_hwdata; +output iahbl_pad_hwrite; +output ifu_clic_warm_up; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31:0] rtu_pad_retire_pc; +output [31:0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31:0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31:0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31:0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; +output rtu_yy_xx_dbgon; +output sysio_clint_me_int; +output [63:0] sysio_clint_mtime; +output [1 :0] sysio_pad_lpmd_b; +output sysmap_tcipif_cmplt; +output [31:0] sysmap_tcipif_rdata; + +// &Regs; @27 + +// &Wires; @28 +wire [31:0] biu_pad_haddr; +wire [2 :0] biu_pad_hburst; +wire biu_pad_hlock; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire [31:0] biu_pad_hwdata; +wire biu_pad_hwrite; +wire biu_sysio_idle; +wire bmu_dahbl_dbus_acc_deny; +wire [31:0] bmu_dahbl_dbus_addr; +wire [2 :0] bmu_dahbl_dbus_burst; +wire bmu_dahbl_dbus_lock; +wire bmu_dahbl_dbus_lrsc; +wire [3 :0] bmu_dahbl_dbus_prot; +wire bmu_dahbl_dbus_req; +wire bmu_dahbl_dbus_req_dp; +wire bmu_dahbl_dbus_seq; +wire [1 :0] bmu_dahbl_dbus_size; +wire [31:0] bmu_dahbl_dbus_wdata; +wire bmu_dahbl_dbus_write; +wire bmu_dahbl_ibus_acc_deny; +wire [31:0] bmu_dahbl_ibus_addr; +wire [2 :0] bmu_dahbl_ibus_burst; +wire [3 :0] bmu_dahbl_ibus_prot; +wire bmu_dahbl_ibus_req; +wire bmu_dahbl_ibus_req_dp; +wire bmu_dahbl_ibus_seq; +wire [1 :0] bmu_dahbl_ibus_size; +wire [3 :0] bmu_dtu_debug_info; +wire bmu_iahbl_dbus_acc_deny; +wire [31:0] bmu_iahbl_dbus_addr; +wire [2 :0] bmu_iahbl_dbus_burst; +wire bmu_iahbl_dbus_lock; +wire bmu_iahbl_dbus_lrsc; +wire [3 :0] bmu_iahbl_dbus_prot; +wire bmu_iahbl_dbus_req; +wire bmu_iahbl_dbus_req_dp; +wire bmu_iahbl_dbus_seq; +wire [1 :0] bmu_iahbl_dbus_size; +wire [31:0] bmu_iahbl_dbus_wdata; +wire bmu_iahbl_dbus_write; +wire bmu_iahbl_ibus_acc_deny; +wire [31:0] bmu_iahbl_ibus_addr; +wire [2 :0] bmu_iahbl_ibus_burst; +wire [3 :0] bmu_iahbl_ibus_prot; +wire bmu_iahbl_ibus_req; +wire bmu_iahbl_ibus_req_dp; +wire bmu_iahbl_ibus_seq; +wire [1 :0] bmu_iahbl_ibus_size; +wire bmu_ifu_acc_err; +wire bmu_ifu_grant; +wire [31:0] bmu_ifu_rdata; +wire bmu_ifu_trans_cmplt; +wire bmu_lsu_acc_err; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire bmu_sahbl_dbus_acc_deny; +wire [31:0] bmu_sahbl_dbus_addr; +wire [2 :0] bmu_sahbl_dbus_burst; +wire bmu_sahbl_dbus_lock; +wire bmu_sahbl_dbus_lrsc; +wire [3 :0] bmu_sahbl_dbus_prot; +wire bmu_sahbl_dbus_req; +wire bmu_sahbl_dbus_req_dp; +wire bmu_sahbl_dbus_seq; +wire [1 :0] bmu_sahbl_dbus_size; +wire [31:0] bmu_sahbl_dbus_wdata; +wire bmu_sahbl_dbus_write; +wire bmu_sahbl_ibus_acc_deny; +wire [31:0] bmu_sahbl_ibus_addr; +wire [2 :0] bmu_sahbl_ibus_burst; +wire [3 :0] bmu_sahbl_ibus_prot; +wire bmu_sahbl_ibus_req; +wire bmu_sahbl_ibus_req_dp; +wire bmu_sahbl_ibus_seq; +wire [1 :0] bmu_sahbl_ibus_size; +wire bmu_tcipif_dbus_acc_deny; +wire [31:0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31:0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire bmu_tcipif_ibus_acc_deny; +wire [31:0] bmu_tcipif_ibus_addr; +wire bmu_tcipif_ibus_req; +wire bmu_tcipif_ibus_req_dp; +wire [1 :0] bmu_tcipif_ibus_size; +wire bmu_tcipif_ibus_supv_mode; +wire [31:0] bmu_tcipif_ibus_wdata; +wire bmu_tcipif_ibus_write; +wire clic_cpu_int_hv; +wire [11:0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire clk_en_f; +wire cp0_biu_icg_en; +wire [11:0] cp0_dtu_addr; +wire [5 :0] cp0_dtu_debug_info; +wire cp0_dtu_icg_en; +wire [11:0] cp0_dtu_int_id; +wire cp0_dtu_mexpt_vld; +wire cp0_dtu_pcfifo_frz; +wire cp0_dtu_rreg; +wire [31:0] cp0_dtu_wdata; +wire cp0_dtu_wreg; +wire cp0_hpcp_icg_en; +wire [11:0] cp0_hpcp_index; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [31:0] cp0_hpcp_wdata; +wire cp0_hpcp_wreg; +wire [31:0] cp0_pad_mcause; +wire [31:0] cp0_pad_mintstatus; +wire [31:0] cp0_pad_mstatus; +wire [19:0] cp0_pmp_csr_sel; +wire cp0_pmp_csr_wen; +wire cp0_pmp_icg_en; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire [31:0] cp0_pmp_updt_data; +wire cp0_sysio_ipend_b; +wire [1 :0] cp0_sysio_lpmd_b; +wire [1 :0] cp0_sysio_srst; +wire cp0_yy_clk_en; +wire cp0_yy_mach_mode; +wire [1 :0] cp0_yy_priv_mode; +wire [11:0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpu_pad_dfs_ack; +wire cpu_pad_halted; +wire cpu_pad_lockup; +wire [1 :0] cpu_pad_soft_rst; +wire cpurst_b; +wire dahbl_bmu_dbus_acc_err; +wire [31:0] dahbl_bmu_dbus_data; +wire dahbl_bmu_dbus_grnt; +wire dahbl_bmu_dbus_trans_cmplt; +wire dahbl_bmu_ibus_acc_err; +wire [31:0] dahbl_bmu_ibus_data; +wire dahbl_bmu_ibus_grnt; +wire dahbl_bmu_ibus_trans_cmplt; +wire [10:0] dahbl_dtu_debug_info; +wire [31:0] dahbl_pad_haddr; +wire [2 :0] dahbl_pad_hburst; +wire dahbl_pad_hlock; +wire [3 :0] dahbl_pad_hprot; +wire [2 :0] dahbl_pad_hsize; +wire [1 :0] dahbl_pad_htrans; +wire [31:0] dahbl_pad_hwdata; +wire dahbl_pad_hwrite; +wire dahbl_sysio_idle; +wire dtu_cp0_dcsr_mprven; +wire [1 :0] dtu_cp0_dcsr_prv; +wire [31:0] dtu_cp0_rdata; +wire dtu_cp0_wake_up; +wire dtu_hpcp_dcsr_stopcount; +wire [31:0] dtu_ifu_debug_inst; +wire dtu_ifu_debug_inst_vld; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire dtu_ifu_halt_info_vld; +wire dtu_ifu_halt_on_reset; +wire dtu_lsu_addr_trig_en; +wire dtu_lsu_data_trig_en; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire dtu_rtu_async_halt_req; +wire [31:0] dtu_rtu_dpc; +wire dtu_rtu_ebreak_action; +wire dtu_rtu_int_mask; +wire [31:0] dtu_rtu_pending_tval; +wire dtu_rtu_resume_req; +wire dtu_rtu_step_en; +wire dtu_rtu_sync_flush; +wire dtu_rtu_sync_halt_req; +wire dtu_tdt_dm_halted; +wire dtu_tdt_dm_havereset; +wire dtu_tdt_dm_itr_done; +wire dtu_tdt_dm_retire_debug_expt_vld; +wire [31:0] dtu_tdt_dm_rx_data; +wire dtu_tdt_dm_wr_ready; +wire forever_cpuclk; +wire [7 :0] fpu_dtu_debug_info; +wire [31:0] hpcp_cp0_data; +wire iahbl_bmu_dbus_acc_err; +wire [31:0] iahbl_bmu_dbus_data; +wire iahbl_bmu_dbus_grnt; +wire iahbl_bmu_dbus_trans_cmplt; +wire iahbl_bmu_ibus_acc_err; +wire [31:0] iahbl_bmu_ibus_data; +wire iahbl_bmu_ibus_grnt; +wire iahbl_bmu_ibus_trans_cmplt; +wire [10:0] iahbl_dtu_debug_info; +wire [31:0] iahbl_pad_haddr; +wire [2 :0] iahbl_pad_hburst; +wire iahbl_pad_hlock; +wire [3 :0] iahbl_pad_hprot; +wire [2 :0] iahbl_pad_hsize; +wire [1 :0] iahbl_pad_htrans; +wire [31:0] iahbl_pad_hwdata; +wire iahbl_pad_hwrite; +wire iahbl_sysio_idle; +wire [21:0] idu_dtu_debug_info; +wire [95:0] idu_dtu_fpr_info; +wire idu_yy_xx_tail_ack; +wire ifu_bmu_acc_deny; +wire [31:0] ifu_bmu_addr; +wire [2 :0] ifu_bmu_burst; +wire ifu_bmu_data_req; +wire [3 :0] ifu_bmu_prot; +wire ifu_bmu_req; +wire ifu_bmu_seq; +wire [1 :0] ifu_bmu_size; +wire ifu_clic_warm_up; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [26:0] ifu_dtu_debug_info; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire [31:0] ifu_dtu_exe_data0; +wire [31:0] ifu_dtu_exe_data1; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire [31:0] ifu_pmp_addr; +wire ifu_pmp_machine_mode; +wire [31:0] ifu_sysmap_pa; +wire ifu_sysmap_rst_sample; +wire [8 :0] iu_dtu_debug_info; +wire iu_hpcp_inst_bht_mispred; +wire iu_hpcp_inst_condbr; +wire iu_hpcp_inst_condbr_gate; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire [78:0] lsu_dtu_debug_info; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [1 :0] lsu_dtu_ldst_type; +wire [1 :0] lsu_dtu_mem_access_size; +wire lsu_hpcp_cache_read_access; +wire lsu_hpcp_cache_read_access_gate; +wire lsu_hpcp_cache_read_miss; +wire lsu_hpcp_cache_read_miss_gate; +wire lsu_hpcp_cache_write_access; +wire lsu_hpcp_cache_write_access_gate; +wire lsu_hpcp_cache_write_miss; +wire lsu_hpcp_cache_write_miss_gate; +wire lsu_hpcp_inst_store; +wire lsu_hpcp_inst_store_gate; +wire [31:0] lsu_pmp_addr; +wire lsu_pmp_write; +wire [31:0] lsu_sysmap_pa; +wire lsu_xx_flush; +wire lsu_xx_warm_up; +wire [31:0] pad_biu_hrdata; +wire pad_biu_hready; +wire pad_biu_hresp; +wire [11:0] pad_bmu_dahbl_base; +wire [11:0] pad_bmu_dahbl_mask; +wire [11:0] pad_bmu_iahbl_base; +wire [11:0] pad_bmu_iahbl_mask; +wire pad_cpu_dfs_req; +wire pad_cpu_ext_int_b; +wire pad_cpu_nmi; +wire [31:0] pad_cpu_rst_addr; +wire [63:0] pad_cpu_sys_cnt; +wire [19:0] pad_cpu_sysmap_addr0; +wire [2 :0] pad_cpu_sysmap_addr0_attr; +wire [19:0] pad_cpu_sysmap_addr1; +wire [2 :0] pad_cpu_sysmap_addr1_attr; +wire [19:0] pad_cpu_sysmap_addr2; +wire [2 :0] pad_cpu_sysmap_addr2_attr; +wire [19:0] pad_cpu_sysmap_addr3; +wire [2 :0] pad_cpu_sysmap_addr3_attr; +wire [19:0] pad_cpu_sysmap_addr4; +wire [2 :0] pad_cpu_sysmap_addr4_attr; +wire [19:0] pad_cpu_sysmap_addr5; +wire [2 :0] pad_cpu_sysmap_addr5_attr; +wire [19:0] pad_cpu_sysmap_addr6; +wire [2 :0] pad_cpu_sysmap_addr6_attr; +wire [19:0] pad_cpu_sysmap_addr7; +wire [2 :0] pad_cpu_sysmap_addr7_attr; +wire [31:0] pad_cpu_tcip_base; +wire pad_cpu_wakeup_event; +wire [31:0] pad_dahbl_hrdata; +wire pad_dahbl_hready; +wire pad_dahbl_hresp; +wire [31:0] pad_iahbl_hrdata; +wire pad_iahbl_hready; +wire pad_iahbl_hresp; +wire pad_yy_icg_scan_en; +wire [31:0] pmp_cp0_data; +wire pmp_ifu_acc_deny; +wire pmp_lsu_acc_deny; +wire [13:0] rtu_dtu_debug_info; +wire [31:0] rtu_dtu_dpc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_nmi_pending; +wire rtu_dtu_pending_ack; +wire rtu_dtu_retire_chgflw; +wire rtu_dtu_retire_debug_expt_vld; +wire [14:0] rtu_dtu_retire_halt_info; +wire rtu_dtu_retire_mret; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; +wire [31:0] rtu_dtu_tval; +wire rtu_hpcp_retire_inst_vld; +wire rtu_pad_inst_retire; +wire rtu_pad_inst_split; +wire [31:0] rtu_pad_retire_pc; +wire [31:0] rtu_pad_wb0_data; +wire [5 :0] rtu_pad_wb0_preg; +wire rtu_pad_wb0_vld; +wire [31:0] rtu_pad_wb1_data; +wire [5 :0] rtu_pad_wb1_preg; +wire rtu_pad_wb1_vld; +wire [31:0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +wire [4 :0] rtu_pad_wb_freg; +wire [31:0] rtu_pad_wb_freg_data; +wire rtu_pad_wb_freg_vld; +wire rtu_sysio_halted; +wire rtu_sysio_lockup_on; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire sahbl_bmu_dbus_acc_err; +wire [31:0] sahbl_bmu_dbus_data; +wire sahbl_bmu_dbus_grnt; +wire sahbl_bmu_dbus_trans_cmplt; +wire sahbl_bmu_ibus_acc_err; +wire [31:0] sahbl_bmu_ibus_data; +wire sahbl_bmu_ibus_grnt; +wire sahbl_bmu_ibus_trans_cmplt; +wire [10:0] sahbl_dtu_debug_info; +wire sys_apb_clk; +wire sys_apb_rst_b; +wire sysio_clint_me_int; +wire [63:0] sysio_clint_mtime; +wire sysio_cp0_clk_en; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; +wire [63:0] sysio_hpcp_time; +wire [31:0] sysio_ifu_rst_addr; +wire sysio_ifu_rst_addr_done; +wire [31:0] sysio_iu_rst_addr; +wire [1 :0] sysio_pad_lpmd_b; +wire sysio_rtu_nmi_int; +wire sysio_rtu_wk_event; +wire sysio_xx_halt_req; +wire [4 :0] sysmap_ifu_flg; +wire [4 :0] sysmap_lsu_flg; +wire sysmap_tcipif_cmplt; +wire [31:0] sysmap_tcipif_rdata; +wire [31:0] tcip_cp0_clic_base; +wire tcipif_bmu_dbus_acc_err; +wire [31:0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_bmu_ibus_acc_err; +wire [31:0] tcipif_bmu_ibus_data; +wire tcipif_bmu_ibus_grnt; +wire tcipif_bmu_ibus_trans_cmplt; +wire [15:0] tcipif_sysmap_addr; +wire tcipif_sysmap_sel; +wire [31:0] tcipif_sysmap_wdata; +wire tcipif_sysmap_write; +wire tdt_dm_dtu_ack_havereset; +wire tdt_dm_dtu_async_halt_req; +wire tdt_dm_dtu_halt_on_reset; +wire tdt_dm_dtu_halt_req; +wire [31:0] tdt_dm_dtu_itr; +wire tdt_dm_dtu_itr_vld; +wire tdt_dm_dtu_resume_req; +wire [31:0] tdt_dm_dtu_wdata; +wire [1 :0] tdt_dm_dtu_wr_flg; +wire tdt_dm_dtu_wr_vld; + + + +//========================================================== +// Instance 906 core module +//========================================================== +// &Instance("pa_core"); @34 +pa_core x_pa_core ( + .bmu_ifu_acc_err (bmu_ifu_acc_err ), + .bmu_ifu_grant (bmu_ifu_grant ), + .bmu_ifu_rdata (bmu_ifu_rdata ), + .bmu_ifu_trans_cmplt (bmu_ifu_trans_cmplt ), + .bmu_lsu_acc_err (bmu_lsu_acc_err ), + .bmu_lsu_grant (bmu_lsu_grant ), + .bmu_lsu_rdata (bmu_lsu_rdata ), + .bmu_lsu_trans_cmplt (bmu_lsu_trans_cmplt ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_debug_info (cp0_dtu_debug_info ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_int_id (cp0_dtu_int_id ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_dtu_wreg (cp0_dtu_wreg ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cp0_hpcp_index (cp0_hpcp_index ), + .cp0_hpcp_pmdm (cp0_hpcp_pmdm ), + .cp0_hpcp_pmdu (cp0_hpcp_pmdu ), + .cp0_hpcp_wdata (cp0_hpcp_wdata ), + .cp0_hpcp_wreg (cp0_hpcp_wreg ), + .cp0_pad_mcause (cp0_pad_mcause ), + .cp0_pad_mintstatus (cp0_pad_mintstatus ), + .cp0_pad_mstatus (cp0_pad_mstatus ), + .cp0_pmp_csr_sel (cp0_pmp_csr_sel ), + .cp0_pmp_csr_wen (cp0_pmp_csr_wen ), + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv ), + .cp0_pmp_updt_data (cp0_pmp_updt_data ), + .cp0_sysio_ipend_b (cp0_sysio_ipend_b ), + .cp0_sysio_lpmd_b (cp0_sysio_lpmd_b ), + .cp0_sysio_srst (cp0_sysio_srst ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpurst_b (cpurst_b ), + .dtu_cp0_dcsr_mprven (dtu_cp0_dcsr_mprven ), + .dtu_cp0_dcsr_prv (dtu_cp0_dcsr_prv ), + .dtu_cp0_rdata (dtu_cp0_rdata ), + .dtu_cp0_wake_up (dtu_cp0_wake_up ), + .dtu_ifu_debug_inst (dtu_ifu_debug_inst ), + .dtu_ifu_debug_inst_vld (dtu_ifu_debug_inst_vld ), + .dtu_ifu_halt_info0 (dtu_ifu_halt_info0 ), + .dtu_ifu_halt_info1 (dtu_ifu_halt_info1 ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .dtu_ifu_halt_on_reset (dtu_ifu_halt_on_reset ), + .dtu_lsu_addr_trig_en (dtu_lsu_addr_trig_en ), + .dtu_lsu_data_trig_en (dtu_lsu_data_trig_en ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .dtu_rtu_async_halt_req (dtu_rtu_async_halt_req ), + .dtu_rtu_dpc (dtu_rtu_dpc ), + .dtu_rtu_ebreak_action (dtu_rtu_ebreak_action ), + .dtu_rtu_int_mask (dtu_rtu_int_mask ), + .dtu_rtu_pending_tval (dtu_rtu_pending_tval ), + .dtu_rtu_resume_req (dtu_rtu_resume_req ), + .dtu_rtu_step_en (dtu_rtu_step_en ), + .dtu_rtu_sync_flush (dtu_rtu_sync_flush ), + .dtu_rtu_sync_halt_req (dtu_rtu_sync_halt_req ), + .forever_cpuclk (forever_cpuclk ), + .fpu_dtu_debug_info (fpu_dtu_debug_info ), + .hpcp_cp0_data (hpcp_cp0_data ), + .idu_dtu_debug_info (idu_dtu_debug_info ), + .idu_dtu_fpr_info (idu_dtu_fpr_info ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_bmu_acc_deny (ifu_bmu_acc_deny ), + .ifu_bmu_addr (ifu_bmu_addr ), + .ifu_bmu_burst (ifu_bmu_burst ), + .ifu_bmu_data_req (ifu_bmu_data_req ), + .ifu_bmu_prot (ifu_bmu_prot ), + .ifu_bmu_req (ifu_bmu_req ), + .ifu_bmu_seq (ifu_bmu_seq ), + .ifu_bmu_size (ifu_bmu_size ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_debug_info (ifu_dtu_debug_info ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ifu_dtu_exe_data0 (ifu_dtu_exe_data0 ), + .ifu_dtu_exe_data1 (ifu_dtu_exe_data1 ), + .ifu_hpcp_icache_access (ifu_hpcp_icache_access ), + .ifu_hpcp_icache_miss (ifu_hpcp_icache_miss ), + .ifu_pmp_addr (ifu_pmp_addr ), + .ifu_pmp_machine_mode (ifu_pmp_machine_mode ), + .ifu_sysmap_pa (ifu_sysmap_pa ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .iu_dtu_debug_info (iu_dtu_debug_info ), + .iu_hpcp_inst_bht_mispred (iu_hpcp_inst_bht_mispred ), + .iu_hpcp_inst_condbr (iu_hpcp_inst_condbr ), + .iu_hpcp_inst_condbr_gate (iu_hpcp_inst_condbr_gate ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_bmu_acc_deny (lsu_bmu_acc_deny ), + .lsu_bmu_addr (lsu_bmu_addr ), + .lsu_bmu_burst (lsu_bmu_burst ), + .lsu_bmu_lock (lsu_bmu_lock ), + .lsu_bmu_lrsc (lsu_bmu_lrsc ), + .lsu_bmu_prot (lsu_bmu_prot ), + .lsu_bmu_req (lsu_bmu_req ), + .lsu_bmu_req_dp (lsu_bmu_req_dp ), + .lsu_bmu_seq (lsu_bmu_seq ), + .lsu_bmu_size (lsu_bmu_size ), + .lsu_bmu_wdata (lsu_bmu_wdata ), + .lsu_bmu_write (lsu_bmu_write ), + .lsu_dtu_debug_info (lsu_dtu_debug_info ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .lsu_dtu_ldst_type (lsu_dtu_ldst_type ), + .lsu_dtu_mem_access_size (lsu_dtu_mem_access_size ), + .lsu_hpcp_cache_read_access (lsu_hpcp_cache_read_access ), + .lsu_hpcp_cache_read_access_gate (lsu_hpcp_cache_read_access_gate ), + .lsu_hpcp_cache_read_miss (lsu_hpcp_cache_read_miss ), + .lsu_hpcp_cache_read_miss_gate (lsu_hpcp_cache_read_miss_gate ), + .lsu_hpcp_cache_write_access (lsu_hpcp_cache_write_access ), + .lsu_hpcp_cache_write_access_gate (lsu_hpcp_cache_write_access_gate), + .lsu_hpcp_cache_write_miss (lsu_hpcp_cache_write_miss ), + .lsu_hpcp_cache_write_miss_gate (lsu_hpcp_cache_write_miss_gate ), + .lsu_hpcp_inst_store (lsu_hpcp_inst_store ), + .lsu_hpcp_inst_store_gate (lsu_hpcp_inst_store_gate ), + .lsu_pmp_addr (lsu_pmp_addr ), + .lsu_pmp_write (lsu_pmp_write ), + .lsu_sysmap_pa (lsu_sysmap_pa ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_cp0_data (pmp_cp0_data ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .pmp_lsu_acc_deny (pmp_lsu_acc_deny ), + .rtu_dtu_debug_info (rtu_dtu_debug_info ), + .rtu_dtu_dpc (rtu_dtu_dpc ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_nmi_pending (rtu_dtu_nmi_pending ), + .rtu_dtu_pending_ack (rtu_dtu_pending_ack ), + .rtu_dtu_retire_chgflw (rtu_dtu_retire_chgflw ), + .rtu_dtu_retire_debug_expt_vld (rtu_dtu_retire_debug_expt_vld ), + .rtu_dtu_retire_halt_info (rtu_dtu_retire_halt_info ), + .rtu_dtu_retire_mret (rtu_dtu_retire_mret ), + .rtu_dtu_retire_next_pc (rtu_dtu_retire_next_pc ), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ), + .rtu_dtu_tval (rtu_dtu_tval ), + .rtu_hpcp_retire_inst_vld (rtu_hpcp_retire_inst_vld ), + .rtu_pad_inst_retire (rtu_pad_inst_retire ), + .rtu_pad_inst_split (rtu_pad_inst_split ), + .rtu_pad_retire_pc (rtu_pad_retire_pc ), + .rtu_pad_wb0_data (rtu_pad_wb0_data ), + .rtu_pad_wb0_preg (rtu_pad_wb0_preg ), + .rtu_pad_wb0_vld (rtu_pad_wb0_vld ), + .rtu_pad_wb1_data (rtu_pad_wb1_data ), + .rtu_pad_wb1_preg (rtu_pad_wb1_preg ), + .rtu_pad_wb1_vld (rtu_pad_wb1_vld ), + .rtu_pad_wb2_data (rtu_pad_wb2_data ), + .rtu_pad_wb2_preg (rtu_pad_wb2_preg ), + .rtu_pad_wb2_vld (rtu_pad_wb2_vld ), + .rtu_pad_wb_freg (rtu_pad_wb_freg ), + .rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), + .rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ), + .rtu_sysio_halted (rtu_sysio_halted ), + .rtu_sysio_lockup_on (rtu_sysio_lockup_on ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .sysio_cp0_clk_en (sysio_cp0_clk_en ), + .sysio_cp0_clkratio (sysio_cp0_clkratio ), + .sysio_cp0_rst_addr (sysio_cp0_rst_addr ), + .sysio_ifu_rst_addr (sysio_ifu_rst_addr ), + .sysio_ifu_rst_addr_done (sysio_ifu_rst_addr_done ), + .sysio_iu_rst_addr (sysio_iu_rst_addr ), + .sysio_rtu_nmi_int (sysio_rtu_nmi_int ), + .sysio_rtu_wk_event (sysio_rtu_wk_event ), + .sysio_xx_halt_req (sysio_xx_halt_req ), + .sysmap_ifu_flg (sysmap_ifu_flg ), + .sysmap_lsu_flg (sysmap_lsu_flg ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ) +); + +// &Connect( @35 +// .had_yy_xx_exit_dbg (had_core_exit_dbg ), @36 +// ); @37 +// //&Force("output", "cp0_yy_mach_mode"); @38 +// &Force("output", "rtu_yy_xx_dbgon"); @39 +// &Force("output", "cp0_biu_icg_en"); @40 +// //&Force("output", "rtu_yy_xx_async_flush"); @41 + +//========================================================== +// Instance PMP module +//========================================================== +// &Instance("pa_pmp_top"); @47 +pa_pmp_top x_pa_pmp_top ( + .cp0_pmp_csr_sel (cp0_pmp_csr_sel ), + .cp0_pmp_csr_wen (cp0_pmp_csr_wen ), + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv), + .cp0_pmp_updt_data (cp0_pmp_updt_data ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_pmp_addr (ifu_pmp_addr ), + .ifu_pmp_machine_mode (ifu_pmp_machine_mode), + .lsu_pmp_addr (lsu_pmp_addr ), + .lsu_pmp_write (lsu_pmp_write ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_cp0_data (pmp_cp0_data ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .pmp_lsu_acc_deny (pmp_lsu_acc_deny ) +); + +// &Force("nonport", "ifu_pmp_addr"); &Force("bus", "ifu_pmp_addr", 31, 0); @49 +// &Force("nonport", "ifu_pmp_machine_mode"); @50 +// &Force("nonport", "lsu_pmp_addr"); &Force("bus", "lsu_pmp_addr", 31, 0); @51 +// &Force("nonport", "lsu_pmp_write"); @52 + +//========================================================== +// Instance SYSMAP module +//========================================================== +// &Instance("pa_sysmap_top"); @63 +pa_sysmap_top x_pa_sysmap_top ( + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_sysmap_pa (ifu_sysmap_pa ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .lsu_sysmap_pa (lsu_sysmap_pa ), + .pad_cpu_sysmap_addr0 (pad_cpu_sysmap_addr0 ), + .pad_cpu_sysmap_addr0_attr (pad_cpu_sysmap_addr0_attr), + .pad_cpu_sysmap_addr1 (pad_cpu_sysmap_addr1 ), + .pad_cpu_sysmap_addr1_attr (pad_cpu_sysmap_addr1_attr), + .pad_cpu_sysmap_addr2 (pad_cpu_sysmap_addr2 ), + .pad_cpu_sysmap_addr2_attr (pad_cpu_sysmap_addr2_attr), + .pad_cpu_sysmap_addr3 (pad_cpu_sysmap_addr3 ), + .pad_cpu_sysmap_addr3_attr (pad_cpu_sysmap_addr3_attr), + .pad_cpu_sysmap_addr4 (pad_cpu_sysmap_addr4 ), + .pad_cpu_sysmap_addr4_attr (pad_cpu_sysmap_addr4_attr), + .pad_cpu_sysmap_addr5 (pad_cpu_sysmap_addr5 ), + .pad_cpu_sysmap_addr5_attr (pad_cpu_sysmap_addr5_attr), + .pad_cpu_sysmap_addr6 (pad_cpu_sysmap_addr6 ), + .pad_cpu_sysmap_addr6_attr (pad_cpu_sysmap_addr6_attr), + .pad_cpu_sysmap_addr7 (pad_cpu_sysmap_addr7 ), + .pad_cpu_sysmap_addr7_attr (pad_cpu_sysmap_addr7_attr), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .sysmap_ifu_flg (sysmap_ifu_flg ), + .sysmap_lsu_flg (sysmap_lsu_flg ), + .sysmap_tcipif_cmplt (sysmap_tcipif_cmplt ), + .sysmap_tcipif_rdata (sysmap_tcipif_rdata ), + .tcipif_sysmap_addr (tcipif_sysmap_addr ), + .tcipif_sysmap_sel (tcipif_sysmap_sel ), + .tcipif_sysmap_wdata (tcipif_sysmap_wdata ), + .tcipif_sysmap_write (tcipif_sysmap_write ) +); + + +//========================================================== +// Instance BMU module +//========================================================== +// &Instance("pa_biu_top"); @70 +// &Instance("pa_bmu_top"); @72 +pa_bmu_top x_pa_bmu_top ( + .bmu_dahbl_dbus_acc_deny (bmu_dahbl_dbus_acc_deny ), + .bmu_dahbl_dbus_addr (bmu_dahbl_dbus_addr ), + .bmu_dahbl_dbus_burst (bmu_dahbl_dbus_burst ), + .bmu_dahbl_dbus_lock (bmu_dahbl_dbus_lock ), + .bmu_dahbl_dbus_lrsc (bmu_dahbl_dbus_lrsc ), + .bmu_dahbl_dbus_prot (bmu_dahbl_dbus_prot ), + .bmu_dahbl_dbus_req (bmu_dahbl_dbus_req ), + .bmu_dahbl_dbus_req_dp (bmu_dahbl_dbus_req_dp ), + .bmu_dahbl_dbus_seq (bmu_dahbl_dbus_seq ), + .bmu_dahbl_dbus_size (bmu_dahbl_dbus_size ), + .bmu_dahbl_dbus_wdata (bmu_dahbl_dbus_wdata ), + .bmu_dahbl_dbus_write (bmu_dahbl_dbus_write ), + .bmu_dahbl_ibus_acc_deny (bmu_dahbl_ibus_acc_deny ), + .bmu_dahbl_ibus_addr (bmu_dahbl_ibus_addr ), + .bmu_dahbl_ibus_burst (bmu_dahbl_ibus_burst ), + .bmu_dahbl_ibus_prot (bmu_dahbl_ibus_prot ), + .bmu_dahbl_ibus_req (bmu_dahbl_ibus_req ), + .bmu_dahbl_ibus_req_dp (bmu_dahbl_ibus_req_dp ), + .bmu_dahbl_ibus_seq (bmu_dahbl_ibus_seq ), + .bmu_dahbl_ibus_size (bmu_dahbl_ibus_size ), + .bmu_dtu_debug_info (bmu_dtu_debug_info ), + .bmu_iahbl_dbus_acc_deny (bmu_iahbl_dbus_acc_deny ), + .bmu_iahbl_dbus_addr (bmu_iahbl_dbus_addr ), + .bmu_iahbl_dbus_burst (bmu_iahbl_dbus_burst ), + .bmu_iahbl_dbus_lock (bmu_iahbl_dbus_lock ), + .bmu_iahbl_dbus_lrsc (bmu_iahbl_dbus_lrsc ), + .bmu_iahbl_dbus_prot (bmu_iahbl_dbus_prot ), + .bmu_iahbl_dbus_req (bmu_iahbl_dbus_req ), + .bmu_iahbl_dbus_req_dp (bmu_iahbl_dbus_req_dp ), + .bmu_iahbl_dbus_seq (bmu_iahbl_dbus_seq ), + .bmu_iahbl_dbus_size (bmu_iahbl_dbus_size ), + .bmu_iahbl_dbus_wdata (bmu_iahbl_dbus_wdata ), + .bmu_iahbl_dbus_write (bmu_iahbl_dbus_write ), + .bmu_iahbl_ibus_acc_deny (bmu_iahbl_ibus_acc_deny ), + .bmu_iahbl_ibus_addr (bmu_iahbl_ibus_addr ), + .bmu_iahbl_ibus_burst (bmu_iahbl_ibus_burst ), + .bmu_iahbl_ibus_prot (bmu_iahbl_ibus_prot ), + .bmu_iahbl_ibus_req (bmu_iahbl_ibus_req ), + .bmu_iahbl_ibus_req_dp (bmu_iahbl_ibus_req_dp ), + .bmu_iahbl_ibus_seq (bmu_iahbl_ibus_seq ), + .bmu_iahbl_ibus_size (bmu_iahbl_ibus_size ), + .bmu_ifu_acc_err (bmu_ifu_acc_err ), + .bmu_ifu_grant (bmu_ifu_grant ), + .bmu_ifu_rdata (bmu_ifu_rdata ), + .bmu_ifu_trans_cmplt (bmu_ifu_trans_cmplt ), + .bmu_lsu_acc_err (bmu_lsu_acc_err ), + .bmu_lsu_grant (bmu_lsu_grant ), + .bmu_lsu_rdata (bmu_lsu_rdata ), + .bmu_lsu_trans_cmplt (bmu_lsu_trans_cmplt ), + .bmu_sahbl_dbus_acc_deny (bmu_sahbl_dbus_acc_deny ), + .bmu_sahbl_dbus_addr (bmu_sahbl_dbus_addr ), + .bmu_sahbl_dbus_burst (bmu_sahbl_dbus_burst ), + .bmu_sahbl_dbus_lock (bmu_sahbl_dbus_lock ), + .bmu_sahbl_dbus_lrsc (bmu_sahbl_dbus_lrsc ), + .bmu_sahbl_dbus_prot (bmu_sahbl_dbus_prot ), + .bmu_sahbl_dbus_req (bmu_sahbl_dbus_req ), + .bmu_sahbl_dbus_req_dp (bmu_sahbl_dbus_req_dp ), + .bmu_sahbl_dbus_seq (bmu_sahbl_dbus_seq ), + .bmu_sahbl_dbus_size (bmu_sahbl_dbus_size ), + .bmu_sahbl_dbus_wdata (bmu_sahbl_dbus_wdata ), + .bmu_sahbl_dbus_write (bmu_sahbl_dbus_write ), + .bmu_sahbl_ibus_acc_deny (bmu_sahbl_ibus_acc_deny ), + .bmu_sahbl_ibus_addr (bmu_sahbl_ibus_addr ), + .bmu_sahbl_ibus_burst (bmu_sahbl_ibus_burst ), + .bmu_sahbl_ibus_prot (bmu_sahbl_ibus_prot ), + .bmu_sahbl_ibus_req (bmu_sahbl_ibus_req ), + .bmu_sahbl_ibus_req_dp (bmu_sahbl_ibus_req_dp ), + .bmu_sahbl_ibus_seq (bmu_sahbl_ibus_seq ), + .bmu_sahbl_ibus_size (bmu_sahbl_ibus_size ), + .bmu_tcipif_dbus_acc_deny (bmu_tcipif_dbus_acc_deny ), + .bmu_tcipif_dbus_addr (bmu_tcipif_dbus_addr ), + .bmu_tcipif_dbus_req (bmu_tcipif_dbus_req ), + .bmu_tcipif_dbus_req_dp (bmu_tcipif_dbus_req_dp ), + .bmu_tcipif_dbus_size (bmu_tcipif_dbus_size ), + .bmu_tcipif_dbus_supv_mode (bmu_tcipif_dbus_supv_mode ), + .bmu_tcipif_dbus_wdata (bmu_tcipif_dbus_wdata ), + .bmu_tcipif_dbus_write (bmu_tcipif_dbus_write ), + .bmu_tcipif_ibus_acc_deny (bmu_tcipif_ibus_acc_deny ), + .bmu_tcipif_ibus_addr (bmu_tcipif_ibus_addr ), + .bmu_tcipif_ibus_req (bmu_tcipif_ibus_req ), + .bmu_tcipif_ibus_req_dp (bmu_tcipif_ibus_req_dp ), + .bmu_tcipif_ibus_size (bmu_tcipif_ibus_size ), + .bmu_tcipif_ibus_supv_mode (bmu_tcipif_ibus_supv_mode ), + .bmu_tcipif_ibus_wdata (bmu_tcipif_ibus_wdata ), + .bmu_tcipif_ibus_write (bmu_tcipif_ibus_write ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbl_bmu_dbus_acc_err (dahbl_bmu_dbus_acc_err ), + .dahbl_bmu_dbus_data (dahbl_bmu_dbus_data ), + .dahbl_bmu_dbus_grnt (dahbl_bmu_dbus_grnt ), + .dahbl_bmu_dbus_trans_cmplt (dahbl_bmu_dbus_trans_cmplt ), + .dahbl_bmu_ibus_acc_err (dahbl_bmu_ibus_acc_err ), + .dahbl_bmu_ibus_data (dahbl_bmu_ibus_data ), + .dahbl_bmu_ibus_grnt (dahbl_bmu_ibus_grnt ), + .dahbl_bmu_ibus_trans_cmplt (dahbl_bmu_ibus_trans_cmplt ), + .forever_cpuclk (forever_cpuclk ), + .iahbl_bmu_dbus_acc_err (iahbl_bmu_dbus_acc_err ), + .iahbl_bmu_dbus_data (iahbl_bmu_dbus_data ), + .iahbl_bmu_dbus_grnt (iahbl_bmu_dbus_grnt ), + .iahbl_bmu_dbus_trans_cmplt (iahbl_bmu_dbus_trans_cmplt ), + .iahbl_bmu_ibus_acc_err (iahbl_bmu_ibus_acc_err ), + .iahbl_bmu_ibus_data (iahbl_bmu_ibus_data ), + .iahbl_bmu_ibus_grnt (iahbl_bmu_ibus_grnt ), + .iahbl_bmu_ibus_trans_cmplt (iahbl_bmu_ibus_trans_cmplt ), + .ifu_bmu_acc_deny (ifu_bmu_acc_deny ), + .ifu_bmu_addr (ifu_bmu_addr ), + .ifu_bmu_burst (ifu_bmu_burst ), + .ifu_bmu_data_req (ifu_bmu_data_req ), + .ifu_bmu_prot (ifu_bmu_prot ), + .ifu_bmu_req (ifu_bmu_req ), + .ifu_bmu_seq (ifu_bmu_seq ), + .ifu_bmu_size (ifu_bmu_size ), + .lsu_bmu_acc_deny (lsu_bmu_acc_deny ), + .lsu_bmu_addr (lsu_bmu_addr ), + .lsu_bmu_burst (lsu_bmu_burst ), + .lsu_bmu_lock (lsu_bmu_lock ), + .lsu_bmu_lrsc (lsu_bmu_lrsc ), + .lsu_bmu_prot (lsu_bmu_prot ), + .lsu_bmu_req (lsu_bmu_req ), + .lsu_bmu_req_dp (lsu_bmu_req_dp ), + .lsu_bmu_seq (lsu_bmu_seq ), + .lsu_bmu_size (lsu_bmu_size ), + .lsu_bmu_wdata (lsu_bmu_wdata ), + .lsu_bmu_write (lsu_bmu_write ), + .pad_bmu_dahbl_base (pad_bmu_dahbl_base ), + .pad_bmu_dahbl_mask (pad_bmu_dahbl_mask ), + .pad_bmu_iahbl_base (pad_bmu_iahbl_base ), + .pad_bmu_iahbl_mask (pad_bmu_iahbl_mask ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sahbl_bmu_dbus_acc_err (sahbl_bmu_dbus_acc_err ), + .sahbl_bmu_dbus_data (sahbl_bmu_dbus_data ), + .sahbl_bmu_dbus_grnt (sahbl_bmu_dbus_grnt ), + .sahbl_bmu_dbus_trans_cmplt (sahbl_bmu_dbus_trans_cmplt ), + .sahbl_bmu_ibus_acc_err (sahbl_bmu_ibus_acc_err ), + .sahbl_bmu_ibus_data (sahbl_bmu_ibus_data ), + .sahbl_bmu_ibus_grnt (sahbl_bmu_ibus_grnt ), + .sahbl_bmu_ibus_trans_cmplt (sahbl_bmu_ibus_trans_cmplt ), + .tcipif_bmu_dbus_acc_err (tcipif_bmu_dbus_acc_err ), + .tcipif_bmu_dbus_data (tcipif_bmu_dbus_data ), + .tcipif_bmu_dbus_grnt (tcipif_bmu_dbus_grnt ), + .tcipif_bmu_dbus_trans_cmplt (tcipif_bmu_dbus_trans_cmplt), + .tcipif_bmu_ibus_acc_err (tcipif_bmu_ibus_acc_err ), + .tcipif_bmu_ibus_data (tcipif_bmu_ibus_data ), + .tcipif_bmu_ibus_grnt (tcipif_bmu_ibus_grnt ), + .tcipif_bmu_ibus_trans_cmplt (tcipif_bmu_ibus_trans_cmplt) +); + + +//========================================================== +// Instance BIU module +//========================================================== +// &ConnRule(s/sahbl_pad/biu_pad/); @77 +// &ConnRule(s/pad_sahbl/pad_biu/); @78 +// &Instance("pa_sahbl_top"); @79 +pa_sahbl_top x_pa_sahbl_top ( + .bmu_sahbl_dbus_acc_deny (bmu_sahbl_dbus_acc_deny ), + .bmu_sahbl_dbus_addr (bmu_sahbl_dbus_addr ), + .bmu_sahbl_dbus_burst (bmu_sahbl_dbus_burst ), + .bmu_sahbl_dbus_lock (bmu_sahbl_dbus_lock ), + .bmu_sahbl_dbus_lrsc (bmu_sahbl_dbus_lrsc ), + .bmu_sahbl_dbus_prot (bmu_sahbl_dbus_prot ), + .bmu_sahbl_dbus_req (bmu_sahbl_dbus_req ), + .bmu_sahbl_dbus_req_dp (bmu_sahbl_dbus_req_dp ), + .bmu_sahbl_dbus_seq (bmu_sahbl_dbus_seq ), + .bmu_sahbl_dbus_size (bmu_sahbl_dbus_size ), + .bmu_sahbl_dbus_wdata (bmu_sahbl_dbus_wdata ), + .bmu_sahbl_dbus_write (bmu_sahbl_dbus_write ), + .bmu_sahbl_ibus_acc_deny (bmu_sahbl_ibus_acc_deny ), + .bmu_sahbl_ibus_addr (bmu_sahbl_ibus_addr ), + .bmu_sahbl_ibus_burst (bmu_sahbl_ibus_burst ), + .bmu_sahbl_ibus_prot (bmu_sahbl_ibus_prot ), + .bmu_sahbl_ibus_req (bmu_sahbl_ibus_req ), + .bmu_sahbl_ibus_req_dp (bmu_sahbl_ibus_req_dp ), + .bmu_sahbl_ibus_seq (bmu_sahbl_ibus_seq ), + .bmu_sahbl_ibus_size (bmu_sahbl_ibus_size ), + .clk_en_f (clk_en_f ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_sahbl_hrdata (pad_biu_hrdata ), + .pad_sahbl_hready (pad_biu_hready ), + .pad_sahbl_hresp (pad_biu_hresp ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .sahbl_bmu_dbus_acc_err (sahbl_bmu_dbus_acc_err ), + .sahbl_bmu_dbus_data (sahbl_bmu_dbus_data ), + .sahbl_bmu_dbus_grnt (sahbl_bmu_dbus_grnt ), + .sahbl_bmu_dbus_trans_cmplt (sahbl_bmu_dbus_trans_cmplt), + .sahbl_bmu_ibus_acc_err (sahbl_bmu_ibus_acc_err ), + .sahbl_bmu_ibus_data (sahbl_bmu_ibus_data ), + .sahbl_bmu_ibus_grnt (sahbl_bmu_ibus_grnt ), + .sahbl_bmu_ibus_trans_cmplt (sahbl_bmu_ibus_trans_cmplt), + .sahbl_dtu_debug_info (sahbl_dtu_debug_info ), + .sahbl_pad_haddr (biu_pad_haddr ), + .sahbl_pad_hburst (biu_pad_hburst ), + .sahbl_pad_hlock (biu_pad_hlock ), + .sahbl_pad_hprot (biu_pad_hprot ), + .sahbl_pad_hsize (biu_pad_hsize ), + .sahbl_pad_htrans (biu_pad_htrans ), + .sahbl_pad_hwdata (biu_pad_hwdata ), + .sahbl_pad_hwrite (biu_pad_hwrite ), + .sahbl_sysio_idle (biu_sysio_idle ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + +// &Connect(.sahbl_sysio_idle (biu_sysio_idle)); @80 + +//========================================================== +// Instance IAHBLite module +//========================================================== +// &Instance("pa_iahbl_top"); @86 +pa_iahbl_top x_pa_iahbl_top ( + .bmu_iahbl_dbus_acc_deny (bmu_iahbl_dbus_acc_deny ), + .bmu_iahbl_dbus_addr (bmu_iahbl_dbus_addr ), + .bmu_iahbl_dbus_burst (bmu_iahbl_dbus_burst ), + .bmu_iahbl_dbus_lock (bmu_iahbl_dbus_lock ), + .bmu_iahbl_dbus_lrsc (bmu_iahbl_dbus_lrsc ), + .bmu_iahbl_dbus_prot (bmu_iahbl_dbus_prot ), + .bmu_iahbl_dbus_req (bmu_iahbl_dbus_req ), + .bmu_iahbl_dbus_req_dp (bmu_iahbl_dbus_req_dp ), + .bmu_iahbl_dbus_seq (bmu_iahbl_dbus_seq ), + .bmu_iahbl_dbus_size (bmu_iahbl_dbus_size ), + .bmu_iahbl_dbus_wdata (bmu_iahbl_dbus_wdata ), + .bmu_iahbl_dbus_write (bmu_iahbl_dbus_write ), + .bmu_iahbl_ibus_acc_deny (bmu_iahbl_ibus_acc_deny ), + .bmu_iahbl_ibus_addr (bmu_iahbl_ibus_addr ), + .bmu_iahbl_ibus_burst (bmu_iahbl_ibus_burst ), + .bmu_iahbl_ibus_prot (bmu_iahbl_ibus_prot ), + .bmu_iahbl_ibus_req (bmu_iahbl_ibus_req ), + .bmu_iahbl_ibus_req_dp (bmu_iahbl_ibus_req_dp ), + .bmu_iahbl_ibus_seq (bmu_iahbl_ibus_seq ), + .bmu_iahbl_ibus_size (bmu_iahbl_ibus_size ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .iahbl_bmu_dbus_acc_err (iahbl_bmu_dbus_acc_err ), + .iahbl_bmu_dbus_data (iahbl_bmu_dbus_data ), + .iahbl_bmu_dbus_grnt (iahbl_bmu_dbus_grnt ), + .iahbl_bmu_dbus_trans_cmplt (iahbl_bmu_dbus_trans_cmplt), + .iahbl_bmu_ibus_acc_err (iahbl_bmu_ibus_acc_err ), + .iahbl_bmu_ibus_data (iahbl_bmu_ibus_data ), + .iahbl_bmu_ibus_grnt (iahbl_bmu_ibus_grnt ), + .iahbl_bmu_ibus_trans_cmplt (iahbl_bmu_ibus_trans_cmplt), + .iahbl_dtu_debug_info (iahbl_dtu_debug_info ), + .iahbl_pad_haddr (iahbl_pad_haddr ), + .iahbl_pad_hburst (iahbl_pad_hburst ), + .iahbl_pad_hlock (iahbl_pad_hlock ), + .iahbl_pad_hprot (iahbl_pad_hprot ), + .iahbl_pad_hsize (iahbl_pad_hsize ), + .iahbl_pad_htrans (iahbl_pad_htrans ), + .iahbl_pad_hwdata (iahbl_pad_hwdata ), + .iahbl_pad_hwrite (iahbl_pad_hwrite ), + .iahbl_sysio_idle (iahbl_sysio_idle ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_iahbl_hrdata (pad_iahbl_hrdata ), + .pad_iahbl_hready (pad_iahbl_hready ), + .pad_iahbl_hresp (pad_iahbl_hresp ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + + +//========================================================== +// Instance DAHBLite module +//========================================================== +// &Instance("pa_dahbl_top"); @96 +pa_dahbl_top x_pa_dahbl_top ( + .bmu_dahbl_dbus_acc_deny (bmu_dahbl_dbus_acc_deny ), + .bmu_dahbl_dbus_addr (bmu_dahbl_dbus_addr ), + .bmu_dahbl_dbus_burst (bmu_dahbl_dbus_burst ), + .bmu_dahbl_dbus_lock (bmu_dahbl_dbus_lock ), + .bmu_dahbl_dbus_lrsc (bmu_dahbl_dbus_lrsc ), + .bmu_dahbl_dbus_prot (bmu_dahbl_dbus_prot ), + .bmu_dahbl_dbus_req (bmu_dahbl_dbus_req ), + .bmu_dahbl_dbus_req_dp (bmu_dahbl_dbus_req_dp ), + .bmu_dahbl_dbus_seq (bmu_dahbl_dbus_seq ), + .bmu_dahbl_dbus_size (bmu_dahbl_dbus_size ), + .bmu_dahbl_dbus_wdata (bmu_dahbl_dbus_wdata ), + .bmu_dahbl_dbus_write (bmu_dahbl_dbus_write ), + .bmu_dahbl_ibus_acc_deny (bmu_dahbl_ibus_acc_deny ), + .bmu_dahbl_ibus_addr (bmu_dahbl_ibus_addr ), + .bmu_dahbl_ibus_burst (bmu_dahbl_ibus_burst ), + .bmu_dahbl_ibus_prot (bmu_dahbl_ibus_prot ), + .bmu_dahbl_ibus_req (bmu_dahbl_ibus_req ), + .bmu_dahbl_ibus_req_dp (bmu_dahbl_ibus_req_dp ), + .bmu_dahbl_ibus_seq (bmu_dahbl_ibus_seq ), + .bmu_dahbl_ibus_size (bmu_dahbl_ibus_size ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbl_bmu_dbus_acc_err (dahbl_bmu_dbus_acc_err ), + .dahbl_bmu_dbus_data (dahbl_bmu_dbus_data ), + .dahbl_bmu_dbus_grnt (dahbl_bmu_dbus_grnt ), + .dahbl_bmu_dbus_trans_cmplt (dahbl_bmu_dbus_trans_cmplt), + .dahbl_bmu_ibus_acc_err (dahbl_bmu_ibus_acc_err ), + .dahbl_bmu_ibus_data (dahbl_bmu_ibus_data ), + .dahbl_bmu_ibus_grnt (dahbl_bmu_ibus_grnt ), + .dahbl_bmu_ibus_trans_cmplt (dahbl_bmu_ibus_trans_cmplt), + .dahbl_dtu_debug_info (dahbl_dtu_debug_info ), + .dahbl_pad_haddr (dahbl_pad_haddr ), + .dahbl_pad_hburst (dahbl_pad_hburst ), + .dahbl_pad_hlock (dahbl_pad_hlock ), + .dahbl_pad_hprot (dahbl_pad_hprot ), + .dahbl_pad_hsize (dahbl_pad_hsize ), + .dahbl_pad_htrans (dahbl_pad_htrans ), + .dahbl_pad_hwdata (dahbl_pad_hwdata ), + .dahbl_pad_hwrite (dahbl_pad_hwrite ), + .dahbl_sysio_idle (dahbl_sysio_idle ), + .forever_cpuclk (forever_cpuclk ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_xx_flush (lsu_xx_flush ), + .lsu_xx_warm_up (lsu_xx_warm_up ), + .pad_dahbl_hrdata (pad_dahbl_hrdata ), + .pad_dahbl_hready (pad_dahbl_hready ), + .pad_dahbl_hresp (pad_dahbl_hresp ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + + +//========================================================== +// Instance HPCP module +//========================================================== +// &Force("output", "cp0_yy_priv_mode"); @106 +// &Instance("pa_hpcp_top"); @107 +pa_hpcp_top x_pa_hpcp_top ( + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cp0_hpcp_index (cp0_hpcp_index ), + .cp0_hpcp_pmdm (cp0_hpcp_pmdm ), + .cp0_hpcp_pmdu (cp0_hpcp_pmdu ), + .cp0_hpcp_wdata (cp0_hpcp_wdata ), + .cp0_hpcp_wreg (cp0_hpcp_wreg ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .dtu_hpcp_dcsr_stopcount (dtu_hpcp_dcsr_stopcount ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_cp0_data (hpcp_cp0_data ), + .ifu_hpcp_icache_access (ifu_hpcp_icache_access ), + .ifu_hpcp_icache_miss (ifu_hpcp_icache_miss ), + .iu_hpcp_inst_bht_mispred (iu_hpcp_inst_bht_mispred ), + .iu_hpcp_inst_condbr (iu_hpcp_inst_condbr ), + .iu_hpcp_inst_condbr_gate (iu_hpcp_inst_condbr_gate ), + .lsu_hpcp_cache_read_access (lsu_hpcp_cache_read_access ), + .lsu_hpcp_cache_read_access_gate (lsu_hpcp_cache_read_access_gate ), + .lsu_hpcp_cache_read_miss (lsu_hpcp_cache_read_miss ), + .lsu_hpcp_cache_read_miss_gate (lsu_hpcp_cache_read_miss_gate ), + .lsu_hpcp_cache_write_access (lsu_hpcp_cache_write_access ), + .lsu_hpcp_cache_write_access_gate (lsu_hpcp_cache_write_access_gate), + .lsu_hpcp_cache_write_miss (lsu_hpcp_cache_write_miss ), + .lsu_hpcp_cache_write_miss_gate (lsu_hpcp_cache_write_miss_gate ), + .lsu_hpcp_inst_store (lsu_hpcp_inst_store ), + .lsu_hpcp_inst_store_gate (lsu_hpcp_inst_store_gate ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_hpcp_retire_inst_vld (rtu_hpcp_retire_inst_vld ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sysio_hpcp_time (sysio_hpcp_time ) +); + + +//========================================================== +// Instance SYSTEM IO module +//========================================================== +// &Instance("pa_sys_io","x_pa_sys_io"); @112 +pa_sys_io x_pa_sys_io ( + .biu_sysio_idle (biu_sysio_idle ), + .clk_en (clk_en_f ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cp0_sysio_ipend_b (cp0_sysio_ipend_b ), + .cp0_sysio_lpmd_b (cp0_sysio_lpmd_b ), + .cp0_sysio_srst (cp0_sysio_srst ), + .cpu_pad_dfs_ack (cpu_pad_dfs_ack ), + .cpu_pad_halted (cpu_pad_halted ), + .cpu_pad_lockup (cpu_pad_lockup ), + .cpu_pad_soft_rst (cpu_pad_soft_rst ), + .cpurst_b (cpurst_b ), + .dahbl_sysio_idle (dahbl_sysio_idle ), + .dtu_cp0_wake_up (dtu_cp0_wake_up ), + .forever_cpuclk (forever_cpuclk ), + .iahbl_sysio_idle (iahbl_sysio_idle ), + .pad_cpu_dfs_req (pad_cpu_dfs_req ), + .pad_cpu_ext_int_b (pad_cpu_ext_int_b ), + .pad_cpu_nmi (pad_cpu_nmi ), + .pad_cpu_rst_addr (pad_cpu_rst_addr ), + .pad_cpu_sys_cnt (pad_cpu_sys_cnt ), + .pad_cpu_wakeup_event (pad_cpu_wakeup_event ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_sysio_halted (rtu_sysio_halted ), + .rtu_sysio_lockup_on (rtu_sysio_lockup_on ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sysio_clint_me_int (sysio_clint_me_int ), + .sysio_clint_mtime (sysio_clint_mtime ), + .sysio_cp0_clk_en (sysio_cp0_clk_en ), + .sysio_cp0_clkratio (sysio_cp0_clkratio ), + .sysio_cp0_rst_addr (sysio_cp0_rst_addr ), + .sysio_hpcp_time (sysio_hpcp_time ), + .sysio_ifu_rst_addr (sysio_ifu_rst_addr ), + .sysio_ifu_rst_addr_done (sysio_ifu_rst_addr_done), + .sysio_iu_rst_addr (sysio_iu_rst_addr ), + .sysio_pad_lpmd_b (sysio_pad_lpmd_b ), + .sysio_rtu_nmi_int (sysio_rtu_nmi_int ), + .sysio_rtu_wk_event (sysio_rtu_wk_event ), + .sysio_xx_halt_req (sysio_xx_halt_req ) +); + +// &Connect(.clk_en (clk_en_f)); @113 + +//========================================================== +// Instance DTU module +//========================================================== +// &Instance("pa_dtu_top"); @119 +pa_dtu_top x_pa_dtu_top ( + .bmu_dtu_debug_info (bmu_dtu_debug_info ), + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_debug_info (cp0_dtu_debug_info ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_int_id (cp0_dtu_int_id ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_dtu_wreg (cp0_dtu_wreg ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .dahbl_dtu_debug_info (dahbl_dtu_debug_info ), + .dtu_cp0_dcsr_mprven (dtu_cp0_dcsr_mprven ), + .dtu_cp0_dcsr_prv (dtu_cp0_dcsr_prv ), + .dtu_cp0_rdata (dtu_cp0_rdata ), + .dtu_cp0_wake_up (dtu_cp0_wake_up ), + .dtu_hpcp_dcsr_stopcount (dtu_hpcp_dcsr_stopcount ), + .dtu_ifu_debug_inst (dtu_ifu_debug_inst ), + .dtu_ifu_debug_inst_vld (dtu_ifu_debug_inst_vld ), + .dtu_ifu_halt_info0 (dtu_ifu_halt_info0 ), + .dtu_ifu_halt_info1 (dtu_ifu_halt_info1 ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .dtu_ifu_halt_on_reset (dtu_ifu_halt_on_reset ), + .dtu_lsu_addr_trig_en (dtu_lsu_addr_trig_en ), + .dtu_lsu_data_trig_en (dtu_lsu_data_trig_en ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .dtu_rtu_async_halt_req (dtu_rtu_async_halt_req ), + .dtu_rtu_dpc (dtu_rtu_dpc ), + .dtu_rtu_ebreak_action (dtu_rtu_ebreak_action ), + .dtu_rtu_int_mask (dtu_rtu_int_mask ), + .dtu_rtu_pending_tval (dtu_rtu_pending_tval ), + .dtu_rtu_resume_req (dtu_rtu_resume_req ), + .dtu_rtu_step_en (dtu_rtu_step_en ), + .dtu_rtu_sync_flush (dtu_rtu_sync_flush ), + .dtu_rtu_sync_halt_req (dtu_rtu_sync_halt_req ), + .dtu_tdt_dm_halted (dtu_tdt_dm_halted ), + .dtu_tdt_dm_havereset (dtu_tdt_dm_havereset ), + .dtu_tdt_dm_itr_done (dtu_tdt_dm_itr_done ), + .dtu_tdt_dm_retire_debug_expt_vld (dtu_tdt_dm_retire_debug_expt_vld), + .dtu_tdt_dm_rx_data (dtu_tdt_dm_rx_data ), + .dtu_tdt_dm_wr_ready (dtu_tdt_dm_wr_ready ), + .forever_cpuclk (forever_cpuclk ), + .fpu_dtu_debug_info (fpu_dtu_debug_info ), + .iahbl_dtu_debug_info (iahbl_dtu_debug_info ), + .idu_dtu_debug_info (idu_dtu_debug_info ), + .idu_dtu_fpr_info (idu_dtu_fpr_info ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_debug_info (ifu_dtu_debug_info ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ifu_dtu_exe_data0 (ifu_dtu_exe_data0 ), + .ifu_dtu_exe_data1 (ifu_dtu_exe_data1 ), + .iu_dtu_debug_info (iu_dtu_debug_info ), + .lsu_dtu_debug_info (lsu_dtu_debug_info ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .lsu_dtu_ldst_type (lsu_dtu_ldst_type ), + .lsu_dtu_mem_access_size (lsu_dtu_mem_access_size ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_dtu_debug_info (rtu_dtu_debug_info ), + .rtu_dtu_dpc (rtu_dtu_dpc ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_nmi_pending (rtu_dtu_nmi_pending ), + .rtu_dtu_pending_ack (rtu_dtu_pending_ack ), + .rtu_dtu_retire_chgflw (rtu_dtu_retire_chgflw ), + .rtu_dtu_retire_debug_expt_vld (rtu_dtu_retire_debug_expt_vld ), + .rtu_dtu_retire_halt_info (rtu_dtu_retire_halt_info ), + .rtu_dtu_retire_mret (rtu_dtu_retire_mret ), + .rtu_dtu_retire_next_pc (rtu_dtu_retire_next_pc ), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ), + .rtu_dtu_tval (rtu_dtu_tval ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .sahbl_dtu_debug_info (sahbl_dtu_debug_info ), + .sys_apb_clk (sys_apb_clk ), + .sys_apb_rst_b (sys_apb_rst_b ), + .tdt_dm_dtu_ack_havereset (tdt_dm_dtu_ack_havereset ), + .tdt_dm_dtu_async_halt_req (tdt_dm_dtu_async_halt_req ), + .tdt_dm_dtu_halt_on_reset (tdt_dm_dtu_halt_on_reset ), + .tdt_dm_dtu_halt_req (tdt_dm_dtu_halt_req ), + .tdt_dm_dtu_itr (tdt_dm_dtu_itr ), + .tdt_dm_dtu_itr_vld (tdt_dm_dtu_itr_vld ), + .tdt_dm_dtu_resume_req (tdt_dm_dtu_resume_req ), + .tdt_dm_dtu_wdata (tdt_dm_dtu_wdata ), + .tdt_dm_dtu_wr_flg (tdt_dm_dtu_wr_flg ), + .tdt_dm_dtu_wr_vld (tdt_dm_dtu_wr_vld ) +); + +// &Instance("pa_dtu_top_dummy"); @121 + +// &ModuleEnd; @124 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_cpu_top_golden_port.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_cpu_top_golden_port.v new file mode 100644 index 0000000000000000000000000000000000000000..e4a26119584b5a7e98e593a7abc96d139bde9b5c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_cpu_top_golden_port.v @@ -0,0 +1,491 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_cpu_top_golden_port( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hlock, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwdata, + biu_pad_hwrite, + clk_en, + cp0_pad_mcause, + cp0_pad_mintstatus, + cp0_pad_mstatus, + cpu_pad_dfs_ack, + cpu_pad_halted, + cpu_pad_lockup, + cpu_pad_soft_rst, + dahbl_pad_haddr, + dahbl_pad_hburst, + dahbl_pad_hlock, + dahbl_pad_hprot, + dahbl_pad_hsize, + dahbl_pad_htrans, + dahbl_pad_hwdata, + dahbl_pad_hwrite, + iahbl_pad_haddr, + iahbl_pad_hburst, + iahbl_pad_hlock, + iahbl_pad_hprot, + iahbl_pad_hsize, + iahbl_pad_htrans, + iahbl_pad_hwdata, + iahbl_pad_hwrite, + pad_biu_hrdata, + pad_biu_hready, + pad_biu_hresp, + pad_bmu_dahbl_base, + pad_bmu_dahbl_mask, + pad_bmu_iahbl_base, + pad_bmu_iahbl_mask, + pad_clic_int_vld, + pad_cpu_dfs_req, + pad_cpu_ext_int_b, + pad_cpu_nmi, + pad_cpu_rst_addr, + pad_cpu_rst_b, + pad_cpu_sys_cnt, + pad_cpu_sysmap_addr0, + pad_cpu_sysmap_addr0_attr, + pad_cpu_sysmap_addr1, + pad_cpu_sysmap_addr1_attr, + pad_cpu_sysmap_addr2, + pad_cpu_sysmap_addr2_attr, + pad_cpu_sysmap_addr3, + pad_cpu_sysmap_addr3_attr, + pad_cpu_sysmap_addr4, + pad_cpu_sysmap_addr4_attr, + pad_cpu_sysmap_addr5, + pad_cpu_sysmap_addr5_attr, + pad_cpu_sysmap_addr6, + pad_cpu_sysmap_addr6_attr, + pad_cpu_sysmap_addr7, + pad_cpu_sysmap_addr7_attr, + pad_cpu_tcip_base, + pad_cpu_wakeup_event, + pad_dahbl_hrdata, + pad_dahbl_hready, + pad_dahbl_hresp, + pad_iahbl_hrdata, + pad_iahbl_hready, + pad_iahbl_hresp, + pad_tdt_dm_core_unavail, + pad_yy_dft_clk_rst_b, + pad_yy_icg_scan_en, + pad_yy_scan_enable, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + pll_core_cpuclk, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld, + sys_apb_clk, + sys_apb_rst_b, + sysio_pad_lpmd_b, + tdt_dm_pad_hartreset_n, + tdt_dm_pad_ndmreset_n, + tdt_dmi_paddr, + tdt_dmi_penable, + tdt_dmi_prdata, + tdt_dmi_pready, + tdt_dmi_psel, + tdt_dmi_pslverr, + tdt_dmi_pwdata, + tdt_dmi_pwrite +); + +// &Ports @3 +input clk_en; +input [31 :0] pad_biu_hrdata; +input pad_biu_hready; +input pad_biu_hresp; +input [11 :0] pad_bmu_dahbl_base; +input [11 :0] pad_bmu_dahbl_mask; +input [11 :0] pad_bmu_iahbl_base; +input [11 :0] pad_bmu_iahbl_mask; +input [127:0] pad_clic_int_vld; +input pad_cpu_dfs_req; +input pad_cpu_ext_int_b; +input pad_cpu_nmi; +input [31 :0] pad_cpu_rst_addr; +input pad_cpu_rst_b; +input [63 :0] pad_cpu_sys_cnt; +input [19 :0] pad_cpu_sysmap_addr0; +input [2 :0] pad_cpu_sysmap_addr0_attr; +input [19 :0] pad_cpu_sysmap_addr1; +input [2 :0] pad_cpu_sysmap_addr1_attr; +input [19 :0] pad_cpu_sysmap_addr2; +input [2 :0] pad_cpu_sysmap_addr2_attr; +input [19 :0] pad_cpu_sysmap_addr3; +input [2 :0] pad_cpu_sysmap_addr3_attr; +input [19 :0] pad_cpu_sysmap_addr4; +input [2 :0] pad_cpu_sysmap_addr4_attr; +input [19 :0] pad_cpu_sysmap_addr5; +input [2 :0] pad_cpu_sysmap_addr5_attr; +input [19 :0] pad_cpu_sysmap_addr6; +input [2 :0] pad_cpu_sysmap_addr6_attr; +input [19 :0] pad_cpu_sysmap_addr7; +input [2 :0] pad_cpu_sysmap_addr7_attr; +input [31 :0] pad_cpu_tcip_base; +input pad_cpu_wakeup_event; +input [31 :0] pad_dahbl_hrdata; +input pad_dahbl_hready; +input pad_dahbl_hresp; +input [31 :0] pad_iahbl_hrdata; +input pad_iahbl_hready; +input pad_iahbl_hresp; +input pad_tdt_dm_core_unavail; +input pad_yy_dft_clk_rst_b; +input pad_yy_icg_scan_en; +input pad_yy_scan_enable; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input pll_core_cpuclk; +input sys_apb_clk; +input sys_apb_rst_b; +input [11 :0] tdt_dmi_paddr; +input tdt_dmi_penable; +input tdt_dmi_psel; +input [31 :0] tdt_dmi_pwdata; +input tdt_dmi_pwrite; +output [31 :0] biu_pad_haddr; +output [2 :0] biu_pad_hburst; +output biu_pad_hlock; +output [3 :0] biu_pad_hprot; +output [2 :0] biu_pad_hsize; +output [1 :0] biu_pad_htrans; +output [31 :0] biu_pad_hwdata; +output biu_pad_hwrite; +output [31 :0] cp0_pad_mcause; +output [31 :0] cp0_pad_mintstatus; +output [31 :0] cp0_pad_mstatus; +output cpu_pad_dfs_ack; +output cpu_pad_halted; +output cpu_pad_lockup; +output [1 :0] cpu_pad_soft_rst; +output [31 :0] dahbl_pad_haddr; +output [2 :0] dahbl_pad_hburst; +output dahbl_pad_hlock; +output [3 :0] dahbl_pad_hprot; +output [2 :0] dahbl_pad_hsize; +output [1 :0] dahbl_pad_htrans; +output [31 :0] dahbl_pad_hwdata; +output dahbl_pad_hwrite; +output [31 :0] iahbl_pad_haddr; +output [2 :0] iahbl_pad_hburst; +output iahbl_pad_hlock; +output [3 :0] iahbl_pad_hprot; +output [2 :0] iahbl_pad_hsize; +output [1 :0] iahbl_pad_htrans; +output [31 :0] iahbl_pad_hwdata; +output iahbl_pad_hwrite; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31 :0] rtu_pad_retire_pc; +output [31 :0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31 :0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31 :0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31 :0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; +output [1 :0] sysio_pad_lpmd_b; +output tdt_dm_pad_hartreset_n; +output tdt_dm_pad_ndmreset_n; +output [31 :0] tdt_dmi_prdata; +output tdt_dmi_pready; +output tdt_dmi_pslverr; + + +// &Force("input", "pad_yy_scan_mode"); @5 +// &Force("input", "pad_yy_scan_enable"); @6 +// &Force("input", "pad_yy_scan_rst_b"); @8 +// &Force("input", "pad_yy_icg_scan_en"); @9 +// &Force("input", "pad_yy_gate_clk_en_b"); @11 +// &Force("input","mem_cfg_in"); &Force("bus", "mem_cfg_in",`MEM_CFG_IN_WIDTH-1,0); @15 + +// &Force("input","mem_cfg_in"); &Force("bus", "mem_cfg_in",`MEM_CFG_IN_WIDTH-1,0); @21 + +// &Force("input","mem_cfg_in"); &Force("bus", "mem_cfg_in",`MEM_CFG_IN_WIDTH-1,0); @27 + +// &Force("input", "clk_en"); @33 +// &Force("input", "ilite_clk_en"); @36 +// &Force("input", "dlite_clk_en"); @39 +// &Force("input", "pad_bmu_dahbl_base"); &Force("bus", "pad_bmu_dahbl_base", 11, 0); @43 +// &Force("input", "pad_bmu_dahbl_mask"); &Force("bus", "pad_bmu_dahbl_mask", 11, 0); @44 +// &Force("input", "pad_dahbl_hrdata"); &Force("bus", "pad_dahbl_hrdata", 31, 0); @45 +// &Force("input", "pad_dahbl_hready"); @46 +// &Force("input", "pad_dahbl_hresp"); @47 +// &Force("output", "dahbl_pad_haddr"); &Force("bus", "dahbl_pad_haddr",31,0); @48 +// &Force("output", "dahbl_pad_hburst"); &Force("bus", "dahbl_pad_hburst",2,0); @49 +// &Force("output", "dahbl_pad_hprot"); &Force("bus", "dahbl_pad_hprot",3,0); @50 +// &Force("output", "dahbl_pad_hsize"); &Force("bus", "dahbl_pad_hsize",2,0); @51 +// &Force("output", "dahbl_pad_htrans"); &Force("bus", "dahbl_pad_htrans",1,0); @52 +// &Force("output", "dahbl_pad_hwdata"); &Force("bus", "dahbl_pad_hwdata",31,0); @53 +// &Force("output", "dahbl_pad_hwrite"); @54 +// &Force("output", "dahbl_pad_hlock"); @55 +// &Force("input", "pad_bmu_iahbl_base"); &Force("bus", "pad_bmu_iahbl_base", 11, 0); @58 +// &Force("input", "pad_bmu_iahbl_mask"); &Force("bus", "pad_bmu_iahbl_mask", 11, 0); @59 +// &Force("input", "pad_iahbl_hrdata"); &Force("bus", "pad_iahbl_hrdata", 31, 0); @60 +// &Force("input", "pad_iahbl_hready"); @61 +// &Force("input", "pad_iahbl_hresp"); @62 +// &Force("output", "iahbl_pad_haddr"); &Force("bus", "iahbl_pad_haddr",31,0); @63 +// &Force("output", "iahbl_pad_hburst"); &Force("bus", "iahbl_pad_hburst",2,0); @64 +// &Force("output", "iahbl_pad_hprot"); &Force("bus", "iahbl_pad_hprot",3,0); @65 +// &Force("output", "iahbl_pad_hsize"); &Force("bus", "iahbl_pad_hsize",2,0); @66 +// &Force("output", "iahbl_pad_htrans"); &Force("bus", "iahbl_pad_htrans",1,0); @67 +// &Force("output", "iahbl_pad_hwdata"); &Force("bus", "iahbl_pad_hwdata",31,0); @68 +// &Force("output", "iahbl_pad_hwrite"); @69 +// &Force("output", "iahbl_pad_hlock"); @70 + +// &Force("input", "pad_cpu_dfs_req"); @73 +// &Force("output", "cpu_pad_dfs_ack"); @74 + +// &Force("input", "axim_clk_en"); @78 +// &Force("input", "pad_biu_arready"); @79 +// &Force("input", "pad_biu_awready"); @80 +// &Force("input", "pad_biu_wready"); @81 +// &Force("input", "pad_biu_rvalid"); @82 +// &Force("input", "pad_biu_rlast"); @83 +// &Force("input", "pad_biu_rid"); &Force("bus", "pad_biu_rid",7,0); @84 +// &Force("input", "pad_biu_rresp"); &Force("bus", "pad_biu_rresp",1,0); @85 +// &Force("input", "pad_biu_rdata"); &Force("bus", "pad_biu_rdata",63,0); @86 +// &Force("input", "pad_biu_bvalid"); @87 +// &Force("input", "pad_biu_bid"); &Force("bus", "pad_biu_bid",7,0); @88 +// &Force("input", "pad_biu_bresp"); &Force("bus", "pad_biu_bresp",1,0); @89 +// &Force("input", "pad_cpu_tcip_base"); &Force("bus", "pad_cpu_tcip_base",31,0); @90 +// &Force("output", "biu_pad_araddr"); &Force("bus", "biu_pad_araddr",31,0); @92 +// &Force("output", "biu_pad_arburst"); &Force("bus", "biu_pad_arburst",1,0); @93 +// &Force("output", "biu_pad_arcache"); &Force("bus", "biu_pad_arcache",3,0); @94 +// &Force("output", "biu_pad_arid"); &Force("bus", "biu_pad_arid",7,0); @95 +// &Force("output", "biu_pad_arlen"); &Force("bus", "biu_pad_arlen",7,0); @96 +// &Force("output", "biu_pad_arlock"); @97 +// &Force("output", "biu_pad_arprot"); &Force("bus", "biu_pad_arprot",2,0); @98 +// &Force("output", "biu_pad_arsize"); &Force("bus", "biu_pad_arsize",2,0); @99 +// &Force("output", "biu_pad_arvalid"); @100 +// &Force("output", "biu_pad_awaddr"); &Force("bus", "biu_pad_awaddr",31,0); @101 +// &Force("output", "biu_pad_awburst"); &Force("bus", "biu_pad_awburst",1,0); @102 +// &Force("output", "biu_pad_awcache"); &Force("bus", "biu_pad_awcache",3,0); @103 +// &Force("output", "biu_pad_awid"); &Force("bus", "biu_pad_awid",7,0); @104 +// &Force("output", "biu_pad_awlen"); &Force("bus", "biu_pad_awlen",7,0); @105 +// &Force("output", "biu_pad_awlock"); @106 +// &Force("output", "biu_pad_awprot"); &Force("bus", "biu_pad_awprot",2,0); @107 +// &Force("output", "biu_pad_awsize"); &Force("bus", "biu_pad_awsize",2,0); @108 +// &Force("output", "biu_pad_awvalid"); @109 +// &Force("output", "biu_pad_bready"); @110 +// &Force("output", "biu_pad_rready"); @111 +// &Force("output", "biu_pad_wdata"); &Force("bus", "biu_pad_wdata",63,0); @112 +// &Force("output", "biu_pad_wlast"); @113 +// &Force("output", "biu_pad_wstrb"); &Force("bus", "biu_pad_wstrb",7,0); @114 +// &Force("output", "biu_pad_wvalid"); @115 +// &Force("input", "pahbl_clk_en"); @118 +// &Force("input", "pad_cpu_pahbl_base"); &Force("bus", "pad_cpu_pahbl_base", 11, 0); @119 +// &Force("input", "pad_cpu_pahbl_mask"); &Force("bus", "pad_cpu_pahbl_mask", 11, 0); @120 +// &Force("input", "pad_pahbl_hrdata"); &Force("bus", "pad_pahbl_hrdata", 31, 0); @121 +// &Force("input", "pad_pahbl_hready"); @122 +// &Force("input", "pad_pahbl_hresp"); @123 +// &Force("input", "pad_pahbl_hexok"); @124 +// &Force("output", "pahbl_pad_haddr"); &Force("bus", "pahbl_pad_haddr",31,0); @125 +// &Force("output", "pahbl_pad_hburst"); &Force("bus", "pahbl_pad_hburst",2,0); @126 +// &Force("output", "pahbl_pad_hprot"); &Force("bus", "pahbl_pad_hprot",6,0); @127 +// &Force("output", "pahbl_pad_hsize"); &Force("bus", "pahbl_pad_hsize",2,0); @128 +// &Force("output", "pahbl_pad_htrans"); &Force("bus", "pahbl_pad_htrans",1,0); @129 +// &Force("output", "pahbl_pad_hwdata"); &Force("bus", "pahbl_pad_hwdata",31,0); @130 +// &Force("output", "pahbl_pad_hwrite"); @131 +// &Force("output", "pahbl_pad_hmastlock"); @132 +// &Force("output", "pahbl_pad_hmaster"); &Force("bus", "pahbl_pad_hmaster",3,0); @133 +// &Force("output", "pahbl_pad_hexcl"); @134 +// &Force("output", "pahbl_pad_hnonsec"); @135 +// &Force("input", "pad_biu_hrdata"); &Force("bus", "pad_biu_hrdata", 31, 0); @138 +// &Force("input", "pad_biu_hready"); @139 +// &Force("input", "pad_biu_hresp"); @140 +// &Force("input", "pad_cpu_tcip_base"); &Force("bus", "pad_cpu_tcip_base",31,0); @141 + +// &Force("output", "biu_pad_haddr"); &Force("bus", "biu_pad_haddr",31,0); @143 +// &Force("output", "biu_pad_hburst"); &Force("bus", "biu_pad_hburst",2,0); @144 +// &Force("output", "biu_pad_hprot"); &Force("bus", "biu_pad_hprot",3,0); @145 +// &Force("output", "biu_pad_hsize"); &Force("bus", "biu_pad_hsize",2,0); @146 +// &Force("output", "biu_pad_htrans"); &Force("bus", "biu_pad_htrans",1,0); @147 +// &Force("output", "biu_pad_hwdata"); &Force("bus", "biu_pad_hwdata",31,0); @148 +// &Force("output", "biu_pad_hwrite"); @149 +// &Force("output", "biu_pad_hlock"); @150 + +// &Force("input", "pll_core_cpuclk"); @153 +// &Force("input", "pad_cpu_rst_b"); @154 +// &Force("input", "pad_cpu_sys_cnt"); &Force("bus", "pad_cpu_sys_cnt", 63, 0); @155 +// &Force("output", "cpu_pad_soft_rst"); &Force("bus", "cpu_pad_soft_rst", 1, 0); @156 +// &Force("output", "cpu_pad_lockup"); @157 +// &Force("output", "cpu_pad_halted"); @158 +// &Force("input", "pad_cpu_nmi"); @159 +// &Force("input", "pad_cpu_rst_addr"); &Force("bus", "pad_cpu_rst_addr", 31, 0); @160 +// &Force("input", "pad_cpu_wakeup_event"); @161 + +//========================================================== +// TDT Ports +//========================================================== +// &Force("input","tdt_dmi_paddr"); &Force("bus","tdt_dmi_paddr",11,0); @166 +// &Force("input","tdt_dmi_pwrite"); @167 +// &Force("input","tdt_dmi_psel"); @169 +// &Force("input","tdt_dmi_psel"); &Force("bus","tdt_dmi_psel",`TDT_COMP_NUM-1,0); @171 +// &Force("input","tdt_dmi_penable"); @173 +// &Force("input","tdt_dmi_pwdata"); &Force("bus","tdt_dmi_pwdata",31,0); @174 +// &Force("output","tdt_dmi_prdata"); &Force("bus","tdt_dmi_prdata",`TDT_COMP_NUM*32-1,0); @175 +// &Force("output","tdt_dmi_pready"); @177 +// &Force("output","tdt_dmi_pslverr"); @178 +// &Force("output","tdt_dmi_pready"); &Force("bus","tdt_dmi_pready",`TDT_COMP_NUM-1,0); @180 +// &Force("output","tdt_dmi_pslverr"); &Force("bus","tdt_dmi_pslverr",`TDT_COMP_NUM-1,0); @181 +// &Force("output","tdt_dm_pad_ndmreset_n"); @183 + +// &Force("output","tdt_dm_pad_hartreset_n"); @186 +// &Force("input","pad_tdt_dm_core_unavail"); @187 +// &Force("output","tdt_dm_pad_hartreset_n"); &Force("bus","tdt_dm_pad_hartreset_n",`TDT_DM_CORE_NUM-1,0); @189 +// &Force("input","pad_tdt_dm_core_unavail"); &Force("bus","pad_tdt_dm_core_unavail",`TDT_DM_CORE_NUM-1,0); @190 + +// &Force("input","sys_apb_rst_b"); @193 + +// &Force("input","sys_apb_clk"); @195 +// &Force("input","sys_apb_clk_en"); @198 + +// &Force("input","pad_tdt_dm_halt_req"); &Force("bus","pad_tdt_dm_halt_req",`TDT_DM_EXTHALTTRI_NUM-1,0); @202 +// &Force("input","pad_tdt_dm_resume_req"); &Force("bus","pad_tdt_dm_resume_req",`TDT_DM_EXTRESUMETRI_NUM-1,0); @203 +// &Force("output","tdt_dm_pad_halt_req"); &Force("bus","tdt_dm_pad_halt_req",`TDT_DM_EXTHALTTRI_NUM-1,0); @204 +// &Force("output","tdt_dm_pad_resume_req"); &Force("bus","tdt_dm_pad_resume_req",`TDT_DM_EXTRESUMETRI_NUM-1,0); @205 + +// &Force("output","tdt_dm_pad_awid"); &Force("bus","tdt_dm_pad_awid",3,0); @209 +// &Force("output","tdt_dm_pad_awaddr"); &Force("bus","tdt_dm_pad_awaddr",`TDT_DM_SBAW-1,0); @210 +// &Force("output","tdt_dm_pad_awlen"); &Force("bus","tdt_dm_pad_awlen",3,0); @211 +// &Force("output","tdt_dm_pad_awsize"); &Force("bus","tdt_dm_pad_awsize",2,0); @212 +// &Force("output","tdt_dm_pad_awvalid"); @213 +// &Force("input","pad_tdt_dm_awready"); @214 +// &Force("output","tdt_dm_pad_wdata"); &Force("bus","tdt_dm_pad_wdata",`TDT_DM_SBA_DW-1,0); @215 +// &Force("output","tdt_dm_pad_wvalid"); @216 +// &Force("output","tdt_dm_pad_wlast"); @217 +// &Force("output","tdt_dm_pad_wstrb"); &Force("bus","tdt_dm_pad_wstrb",`TDT_DM_SBA_BW-1,0); @218 +// &Force("input","pad_tdt_dm_wready"); @219 +// &Force("output","tdt_dm_pad_bready"); @220 +// &Force("input","pad_tdt_dm_bid"); &Force("bus","pad_tdt_dm_bid",3,0); @221 +// &Force("input","pad_tdt_dm_bresp"); &Force("bus","pad_tdt_dm_bresp",1,0); @222 +// &Force("input","pad_tdt_dm_bvalid"); @223 +// &Force("output","tdt_dm_pad_arid"); &Force("bus","tdt_dm_pad_arid",3,0); @225 +// &Force("output","tdt_dm_pad_araddr"); &Force("bus","tdt_dm_pad_araddr",`TDT_DM_SBAW-1,0); @226 +// &Force("output","tdt_dm_pad_arlen"); &Force("bus","tdt_dm_pad_arlen",3,0); @227 +// &Force("output","tdt_dm_pad_arsize"); &Force("bus","tdt_dm_pad_arsize",2,0); @228 +// &Force("output","tdt_dm_pad_arvalid"); @229 +// &Force("input","pad_tdt_dm_arready"); @230 +// &Force("input","pad_tdt_dm_rid"); &Force("bus","pad_tdt_dm_rid",3,0); @232 +// &Force("input","pad_tdt_dm_rdata"); &Force("bus","pad_tdt_dm_rdata",`TDT_DM_SBA_DW-1,0); @233 +// &Force("input","pad_tdt_dm_rvalid"); @234 +// &Force("input","pad_tdt_dm_rlast"); @235 +// &Force("input","pad_tdt_dm_rresp"); &Force("bus","pad_tdt_dm_rresp",1,0); @236 +// &Force("output","tdt_dm_pad_rready"); @238 +// &Force("output","tdt_dm_pad_awburst"); &Force("bus","tdt_dm_pad_awburst",1,0); @240 +// &Force("output","tdt_dm_pad_awcache"); &Force("bus","tdt_dm_pad_awcache",3,0); @241 +// &Force("output","tdt_dm_pad_awlock"); @242 +// &Force("output","tdt_dm_pad_awprot"); &Force("bus","tdt_dm_pad_awprot",2,0); @243 +// &Force("output","tdt_dm_pad_arburst"); &Force("bus","tdt_dm_pad_arburst",1,0); @244 +// &Force("output","tdt_dm_pad_arcache"); &Force("bus","tdt_dm_pad_arcache",3,0); @245 +// &Force("output","tdt_dm_pad_arlock"); @246 +// &Force("output","tdt_dm_pad_arprot"); &Force("bus","tdt_dm_pad_arprot",2,0); @247 +// &Force("output","tdt_dm_pad_htrans"); &Force("bus","tdt_dm_pad_htrans",1,0); @250 +// &Force("output","tdt_dm_pad_haddr"); &Force("bus","tdt_dm_pad_haddr",`TDT_DM_SBAW-1,0); @251 +// &Force("output","tdt_dm_pad_hwrite"); @252 +// &Force("output","tdt_dm_pad_hburst"); &Force("bus","tdt_dm_pad_hburst",2,0); @253 +// &Force("output","tdt_dm_pad_hsize"); &Force("bus","tdt_dm_pad_hsize",2,0); @254 +// &Force("output","tdt_dm_pad_hwdata"); @255 +// &Force("output","tdt_dm_pad_hprot"); &Force("bus","tdt_dm_pad_hprot",3,0); @256 +// &Force("output","tdt_dm_pad_hmastlock"); &Force("bus","tdt_dm_pad_hwdata",`TDT_DM_SBA_DW-1,0); @257 +// &Force("input","pad_tdt_dm_hrdata"); &Force("bus","pad_tdt_dm_hrdata",`TDT_DM_SBA_DW-1,0); @258 +// &Force("input","pad_tdt_dm_hready"); @259 +// &Force("input","pad_tdt_dm_hresp"); @260 + +// &Force("output", "rtu_pad_inst_retire"); @263 +// &Force("output", "rtu_pad_inst_split"); @264 +// &Force("output", "rtu_pad_retire_pc"); &Force("bus", "rtu_pad_retire_pc", 31, 0); @265 +// &Force("output", "rtu_pad_wb0_data"); &Force("bus", "rtu_pad_wb0_data", 31, 0); @266 +// &Force("output", "rtu_pad_wb0_preg"); &Force("bus", "rtu_pad_wb0_preg", 5, 0); @267 +// &Force("output", "rtu_pad_wb0_vld"); @268 +// &Force("output", "rtu_pad_wb1_data"); &Force("bus", "rtu_pad_wb1_data", 31, 0); @269 +// &Force("output", "rtu_pad_wb1_preg"); &Force("bus", "rtu_pad_wb1_preg", 5, 0); @270 +// &Force("output", "rtu_pad_wb1_vld"); @271 +// &Force("output", "rtu_pad_wb2_data"); &Force("bus", "rtu_pad_wb2_data", 31, 0); @272 +// &Force("output", "rtu_pad_wb2_preg"); &Force("bus", "rtu_pad_wb2_preg", 5, 0); @273 +// &Force("output", "rtu_pad_wb2_vld"); @274 +// &Force("output", "lsu_pad_sc_pass"); @276 +// &Force("output", "cp0_pad_mcause"); &Force("bus", "cp0_pad_mcause", 31, 0); @278 +// &Force("output", "cp0_pad_mstatus"); &Force("bus", "cp0_pad_mstatus", 31, 0); @279 + +// &Force("output","sysio_pad_lpmd_b"); &Force("bus", "sysio_pad_lpmd_b", 1, 0); @281 +//========================================================== +// CLIC Ports +//========================================================== +// &Force("output", "cp0_pad_mintstatus"); &Force("bus", "cp0_pad_mintstatus", 31, 0); @286 +// &Force("input", "pad_clic_int_vld"); &Force("bus", "pad_clic_int_vld", `CLIC_INTNUM-1-16, 0); @288 + +//========================================================== +// CLINT Ports +//========================================================== +// &Force("input", "pad_cpu_ext_int_b"); @295 + +// &Force("input","pad_yy_dft_clk_rst_b"); @298 + +//========================================================== +// FPU Ports +//========================================================== +// &Force("output", "rtu_pad_wb_freg_vld"); @305 +// &Force("output", "rtu_pad_wb_freg"); &Force("bus", "rtu_pad_wb_freg", 4, 0); @306 +// &Force("output", "rtu_pad_wb_freg_data"); &Force("bus", "rtu_pad_wb_freg_data", 63, 0); @308 +// &Force("output", "rtu_pad_wb_freg_data"); &Force("bus", "rtu_pad_wb_freg_data", 31, 0); @310 + +// &Force("input","pad_cpu_sysmap_addr0"); &Force("bus","pad_cpu_sysmap_addr0",19,0); @314 +// &Force("input","pad_cpu_sysmap_addr1"); &Force("bus","pad_cpu_sysmap_addr1",19,0); @315 +// &Force("input","pad_cpu_sysmap_addr2"); &Force("bus","pad_cpu_sysmap_addr2",19,0); @316 +// &Force("input","pad_cpu_sysmap_addr3"); &Force("bus","pad_cpu_sysmap_addr3",19,0); @317 +// &Force("input","pad_cpu_sysmap_addr4"); &Force("bus","pad_cpu_sysmap_addr4",19,0); @318 +// &Force("input","pad_cpu_sysmap_addr5"); &Force("bus","pad_cpu_sysmap_addr5",19,0); @319 +// &Force("input","pad_cpu_sysmap_addr6"); &Force("bus","pad_cpu_sysmap_addr6",19,0); @320 +// &Force("input","pad_cpu_sysmap_addr7"); &Force("bus","pad_cpu_sysmap_addr7",19,0); @321 +// &Force("input","pad_cpu_sysmap_addr0_attr"); &Force("bus","pad_cpu_sysmap_addr0_attr",2,0); @322 +// &Force("input","pad_cpu_sysmap_addr1_attr"); &Force("bus","pad_cpu_sysmap_addr1_attr",2,0); @323 +// &Force("input","pad_cpu_sysmap_addr2_attr"); &Force("bus","pad_cpu_sysmap_addr2_attr",2,0); @324 +// &Force("input","pad_cpu_sysmap_addr3_attr"); &Force("bus","pad_cpu_sysmap_addr3_attr",2,0); @325 +// &Force("input","pad_cpu_sysmap_addr4_attr"); &Force("bus","pad_cpu_sysmap_addr4_attr",2,0); @326 +// &Force("input","pad_cpu_sysmap_addr5_attr"); &Force("bus","pad_cpu_sysmap_addr5_attr",2,0); @327 +// &Force("input","pad_cpu_sysmap_addr6_attr"); &Force("bus","pad_cpu_sysmap_addr6_attr",2,0); @328 +// &Force("input","pad_cpu_sysmap_addr7_attr"); &Force("bus","pad_cpu_sysmap_addr7_attr",2,0); @329 + +// &ModuleEnd @331 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_sys_io.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_sys_io.v new file mode 100644 index 0000000000000000000000000000000000000000..b23308f2ba0ee1973b10a6eea8fa10710d2c4440 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/cpu/rtl/pa_sys_io.v @@ -0,0 +1,391 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_sys_io( + biu_sysio_idle, + clk_en, + cp0_biu_icg_en, + cp0_sysio_ipend_b, + cp0_sysio_lpmd_b, + cp0_sysio_srst, + cpu_pad_dfs_ack, + cpu_pad_halted, + cpu_pad_lockup, + cpu_pad_soft_rst, + cpurst_b, + dahbl_sysio_idle, + dtu_cp0_wake_up, + forever_cpuclk, + iahbl_sysio_idle, + pad_cpu_dfs_req, + pad_cpu_ext_int_b, + pad_cpu_nmi, + pad_cpu_rst_addr, + pad_cpu_sys_cnt, + pad_cpu_wakeup_event, + pad_yy_icg_scan_en, + rtu_sysio_halted, + rtu_sysio_lockup_on, + rtu_yy_xx_dbgon, + sysio_clint_me_int, + sysio_clint_mtime, + sysio_cp0_clk_en, + sysio_cp0_clkratio, + sysio_cp0_rst_addr, + sysio_hpcp_time, + sysio_ifu_rst_addr, + sysio_ifu_rst_addr_done, + sysio_iu_rst_addr, + sysio_pad_lpmd_b, + sysio_rtu_nmi_int, + sysio_rtu_wk_event, + sysio_xx_halt_req +); + +// &Ports; @24 +input biu_sysio_idle; +input clk_en; +input cp0_biu_icg_en; +input cp0_sysio_ipend_b; +input [1 :0] cp0_sysio_lpmd_b; +input [1 :0] cp0_sysio_srst; +input cpurst_b; +input dahbl_sysio_idle; +input dtu_cp0_wake_up; +input forever_cpuclk; +input iahbl_sysio_idle; +input pad_cpu_dfs_req; +input pad_cpu_ext_int_b; +input pad_cpu_nmi; +input [31:0] pad_cpu_rst_addr; +input [63:0] pad_cpu_sys_cnt; +input pad_cpu_wakeup_event; +input pad_yy_icg_scan_en; +input rtu_sysio_halted; +input rtu_sysio_lockup_on; +input rtu_yy_xx_dbgon; +output cpu_pad_dfs_ack; +output cpu_pad_halted; +output cpu_pad_lockup; +output [1 :0] cpu_pad_soft_rst; +output sysio_clint_me_int; +output [63:0] sysio_clint_mtime; +output sysio_cp0_clk_en; +output [2 :0] sysio_cp0_clkratio; +output [31:0] sysio_cp0_rst_addr; +output [63:0] sysio_hpcp_time; +output [31:0] sysio_ifu_rst_addr; +output sysio_ifu_rst_addr_done; +output [31:0] sysio_iu_rst_addr; +output [1 :0] sysio_pad_lpmd_b; +output sysio_rtu_nmi_int; +output sysio_rtu_wk_event; +output sysio_xx_halt_req; + +// &Regs; @25 +reg [63:0] ccvr; +reg cpu_ext_int_b; +reg cpu_nmi; +reg [30:0] cpu_rst_addr_31; +reg cpu_wk_event; +reg pad_cpu_halt_ff1; +reg pad_cpu_halt_ff2; +reg sysio_pad_dbg_b; +reg sysio_pad_halted; +reg sysio_pad_ipend_b; +reg sysio_pad_lockup; +reg [1 :0] sysio_pad_lpmd_b; +reg [1 :0] sysio_pad_srst; +reg sysio_pad_wakeup_b; + +// &Wires; @26 +wire biu_sysio_idle; +wire ccvr_h_clk; +wire ccvr_h_clk_en; +wire ccvr_h_updt; +wire clk_en; +wire cp0_biu_icg_en; +wire cp0_sysio_ipend_b; +wire [1 :0] cp0_sysio_lpmd_b; +wire [1 :0] cp0_sysio_srst; +wire cpu_pad_dfs_ack; +wire cpu_pad_halted; +wire cpu_pad_lockup; +wire [1 :0] cpu_pad_soft_rst; +wire [31:0] cpu_rst_addr; +wire cpu_wake_up_b; +wire cpurst_b; +wire dahbl_sysio_idle; +wire dtu_cp0_wake_up; +wire forever_cpuclk; +wire halt_clk; +wire halt_clk_en; +wire iahbl_sysio_idle; +wire pad_cpu_dfs_req; +wire pad_cpu_ext_int_b; +wire pad_cpu_nmi; +wire [31:0] pad_cpu_rst_addr; +wire [63:0] pad_cpu_sys_cnt; +wire pad_cpu_wakeup_event; +wire [2 :0] pad_sysio_clkratio; +wire pad_yy_icg_scan_en; +wire rtu_sysio_halted; +wire rtu_sysio_lockup_on; +wire rtu_yy_xx_dbgon; +wire sample_clk; +wire sysio_clint_me_int; +wire [63:0] sysio_clint_mtime; +wire sysio_cp0_clk_en; +wire [2 :0] sysio_cp0_clkratio; +wire [31:0] sysio_cp0_rst_addr; +wire [63:0] sysio_hpcp_time; +wire [31:0] sysio_ifu_rst_addr; +wire sysio_ifu_rst_addr_done; +wire [31:0] sysio_iu_rst_addr; +wire sysio_lpmd_gated_clk; +wire sysio_lpmd_gated_en; +wire sysio_rst_addr_neq; +wire sysio_rtu_nmi_int; +wire sysio_rtu_wk_event; +wire sysio_xx_halt_req; + + +// &Instance("gated_clk_cell", "x_pa_gated_sysio_lpmd_cpuclk_cell"); @31 +gated_clk_cell x_pa_gated_sysio_lpmd_cpuclk_cell ( + .clk_in (forever_cpuclk ), + .clk_out (sysio_lpmd_gated_clk), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (sysio_lpmd_gated_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk ), @32 +// .global_en (1'b1 ), @33 +// .module_en (cp0_biu_icg_en ), @34 +// .local_en (sysio_lpmd_gated_en ), @35 +// .external_en(1'b0 ), @36 +// .clk_out (sysio_lpmd_gated_clk )); @37 + +assign sysio_lpmd_gated_en = ((sysio_pad_dbg_b ^ (~rtu_yy_xx_dbgon)) || + |(sysio_pad_lpmd_b[1:0] ^ cp0_sysio_lpmd_b[1:0]) || + (sysio_pad_ipend_b ^ cp0_sysio_ipend_b) || + (sysio_pad_wakeup_b ^ cpu_wake_up_b) || + |(sysio_pad_srst[1:0] ^ cp0_sysio_srst[1:0]) || + (sysio_pad_lockup ^ rtu_sysio_lockup_on) || + (rtu_sysio_halted ^ sysio_pad_halted) || + (pad_cpu_ext_int_b ^ cpu_ext_int_b) || + (pad_cpu_nmi ^ cpu_nmi) || + (pad_cpu_wakeup_event ^ cpu_wk_event) || + sysio_rst_addr_neq) + && clk_en; + +//========================================= +// input port +//========================================= +//synchronize signal +assign pad_sysio_clkratio[2:0] = 3'b0; +assign sysio_cp0_clkratio[2:0] = pad_sysio_clkratio[2:0]; + +assign halt_clk_en = pad_cpu_halt_ff1 ^ pad_cpu_dfs_req | + pad_cpu_halt_ff2 ^ pad_cpu_halt_ff1; + +// &Instance("gated_clk_cell", "x_pa_halt_clk"); @62 +gated_clk_cell x_pa_halt_clk ( + .clk_in (forever_cpuclk ), + .clk_out (halt_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (halt_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @63 +// .external_en (1'b0), @64 +// .global_en (1'b1), @65 +// .module_en (cp0_biu_icg_en), @66 +// .local_en (halt_clk_en), @67 +// .clk_out (halt_clk)); @68 + +always @ (posedge halt_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pad_cpu_halt_ff1 <= 1'b0; + pad_cpu_halt_ff2 <= 1'b0; + end + else + begin + pad_cpu_halt_ff1 <= pad_cpu_dfs_req; + pad_cpu_halt_ff2 <= pad_cpu_halt_ff1; + end +end + +assign cpu_pad_dfs_ack = iahbl_sysio_idle && dahbl_sysio_idle && biu_sysio_idle + && pad_cpu_halt_ff2; + +assign sysio_xx_halt_req = pad_cpu_halt_ff2; + +assign ccvr_h_updt = |(ccvr[63:12] ^ pad_cpu_sys_cnt[63:12]) && clk_en; +always @ (posedge ccvr_h_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ccvr[63:12] <= 52'b0; + else if (ccvr_h_updt) + ccvr[63:12] <= pad_cpu_sys_cnt[63:12]; + else + ccvr[63:12] <= ccvr[63:12]; +end + +assign ccvr_h_clk_en = ccvr_h_updt; +// &Instance("gated_clk_cell", "x_pa_ccvr_h_clk"); @106 +gated_clk_cell x_pa_ccvr_h_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ccvr_h_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ccvr_h_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @107 +// .external_en (1'b0), @108 +// .global_en (1'b1), @109 +// .module_en (cp0_biu_icg_en), @110 +// .local_en (ccvr_h_clk_en), @111 +// .clk_out (ccvr_h_clk)); @112 + +always @ (posedge sample_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ccvr[11:0] <= 12'b0; + else if (clk_en) + ccvr[11:0] <= pad_cpu_sys_cnt[11:0]; + else + ccvr[11:0] <= ccvr[11:0]; +end + +assign sysio_clint_mtime[63:0] = ccvr[63:0]; +assign sysio_hpcp_time[63:0] = ccvr[63:0]; + +always @ (posedge sysio_lpmd_gated_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cpu_rst_addr_31[30:0] <= 31'b0; + else if (clk_en) + cpu_rst_addr_31[30:0] <= pad_cpu_rst_addr[31:1]; + else + cpu_rst_addr_31[30:0] <= cpu_rst_addr_31[30:0]; +end +assign cpu_rst_addr[31:0] = {cpu_rst_addr_31[30:0], 1'b0}; +assign sysio_rst_addr_neq = cpu_rst_addr_31[30:0] != pad_cpu_rst_addr[31:1]; +// &Force("bus", "pad_cpu_rst_addr", 31, 0); @143 +assign sysio_ifu_rst_addr_done = !sysio_rst_addr_neq; + +assign sysio_cp0_rst_addr[31:0] = cpu_rst_addr[31:0]; +assign sysio_ifu_rst_addr[31:0] = cpu_rst_addr[31:0]; +assign sysio_iu_rst_addr[31:0] = cpu_rst_addr[31:0]; + +always @ (posedge sysio_lpmd_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) begin + cpu_ext_int_b <= 1'b1; + cpu_nmi <= 1'b0; + cpu_wk_event <= 1'b0; + end + else if(clk_en) begin + cpu_ext_int_b <= pad_cpu_ext_int_b; + cpu_nmi <= pad_cpu_nmi; + cpu_wk_event <= pad_cpu_wakeup_event; + end + else begin + cpu_ext_int_b <= cpu_ext_int_b; + cpu_nmi <= cpu_nmi; + cpu_wk_event <= cpu_wk_event; + end +end + +assign sysio_clint_me_int = !cpu_ext_int_b; +assign sysio_rtu_nmi_int = cpu_nmi; +assign sysio_rtu_wk_event = cpu_wk_event; + +// &Instance("gated_clk_cell", "x_pa_sample_clk"); @173 +gated_clk_cell x_pa_sample_clk ( + .clk_in (forever_cpuclk ), + .clk_out (sample_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @174 +// .external_en (1'b0 ), @175 +// .global_en (1'b1 ), @176 +// .module_en (cp0_biu_icg_en), @177 +// .local_en (clk_en ), @178 +// .clk_out (sample_clk ) @179 +// ); @180 + +//========================================= +// output port +//========================================= +// &Force("output","sysio_pad_ipend_b"); @185 +// &Force("output","sysio_pad_dbg_b"); @186 +// &Force("output","sysio_pad_lpmd_b"); @187 +// &Force("output","sysio_pad_wakeup_b"); @188 + +assign cpu_wake_up_b = cp0_sysio_ipend_b && !dtu_cp0_wake_up; + +always @(posedge sysio_lpmd_gated_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + sysio_pad_dbg_b <= 1'b1; + sysio_pad_lpmd_b[1:0] <= 2'b11; + sysio_pad_ipend_b <= 1'b0; + sysio_pad_wakeup_b <= 1'b0; + sysio_pad_srst[1:0] <= 2'b0; + sysio_pad_lockup <= 1'b0; + sysio_pad_halted <= 1'b0; + end + else if(clk_en) + begin + sysio_pad_dbg_b <= ~rtu_yy_xx_dbgon; + sysio_pad_lpmd_b[1:0] <= cp0_sysio_lpmd_b[1:0]; + sysio_pad_ipend_b <= cp0_sysio_ipend_b; + sysio_pad_wakeup_b <= cpu_wake_up_b; + sysio_pad_srst[1:0] <= cp0_sysio_srst[1:0]; + sysio_pad_lockup <= rtu_sysio_lockup_on; + sysio_pad_halted <= rtu_sysio_halted; + end +end +// &Force("nonport", "sysio_pad_dbg_b"); @215 +// &Force("nonport", "sysio_pad_ipend_b"); @216 +// &Force("nonport", "sysio_pad_wakeup_b"); @217 +assign sysio_cp0_clk_en = clk_en; + + +assign cpu_pad_soft_rst[1:0] = sysio_pad_srst[1:0]; +assign cpu_pad_lockup = sysio_pad_lockup; +assign cpu_pad_halted = sysio_pad_halted; + +// &ModuleEnd; @225 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc.v new file mode 100644 index 0000000000000000000000000000000000000000..f788a24d6dc39932c402ca8cd25f30cb99eab71c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc.v @@ -0,0 +1,583 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_cdc( + async_halt_req_wakeup, + cp0_yy_clk_en, + cpurst_b, + dscratch0, + dtu_ifu_debug_inst, + dtu_ifu_debug_inst_vld, + dtu_ifu_halt_on_reset, + dtu_rtu_async_halt_req, + dtu_rtu_resume_req, + dtu_rtu_sync_halt_req, + dtu_tdt_dm_halted, + dtu_tdt_dm_havereset, + dtu_tdt_dm_itr_done, + dtu_tdt_dm_retire_debug_expt_vld, + dtu_tdt_dm_rx_data, + dtu_tdt_dm_wr_ready, + forever_cpuclk, + latest_pc, + pad_yy_icg_scan_en, + rtu_dtu_retire_debug_expt_vld, + rtu_dtu_retire_vld, + rtu_yy_xx_dbgon, + sys_apb_clk, + sys_apb_rst_b, + tdt_dm_dtu_ack_havereset, + tdt_dm_dtu_async_halt_req, + tdt_dm_dtu_halt_on_reset, + tdt_dm_dtu_halt_req, + tdt_dm_dtu_itr, + tdt_dm_dtu_itr_vld, + tdt_dm_dtu_resume_req, + tdt_dm_dtu_wdata, + tdt_dm_dtu_wr_flg, + tdt_dm_dtu_wr_vld, + tdt_dm_wdata, + tdt_dm_wr_flg, + tdt_dm_wr_vld +); + +// &Ports; @24 +input cp0_yy_clk_en; +input cpurst_b; +input [31:0] dscratch0; +input forever_cpuclk; +input [31:0] latest_pc; +input pad_yy_icg_scan_en; +input rtu_dtu_retire_debug_expt_vld; +input rtu_dtu_retire_vld; +input rtu_yy_xx_dbgon; +input sys_apb_clk; +input sys_apb_rst_b; +input tdt_dm_dtu_ack_havereset; +input tdt_dm_dtu_async_halt_req; +input tdt_dm_dtu_halt_on_reset; +input tdt_dm_dtu_halt_req; +input [31:0] tdt_dm_dtu_itr; +input tdt_dm_dtu_itr_vld; +input tdt_dm_dtu_resume_req; +input [31:0] tdt_dm_dtu_wdata; +input [1 :0] tdt_dm_dtu_wr_flg; +input tdt_dm_dtu_wr_vld; +output async_halt_req_wakeup; +output [31:0] dtu_ifu_debug_inst; +output dtu_ifu_debug_inst_vld; +output dtu_ifu_halt_on_reset; +output dtu_rtu_async_halt_req; +output dtu_rtu_resume_req; +output dtu_rtu_sync_halt_req; +output dtu_tdt_dm_halted; +output dtu_tdt_dm_havereset; +output dtu_tdt_dm_itr_done; +output dtu_tdt_dm_retire_debug_expt_vld; +output [31:0] dtu_tdt_dm_rx_data; +output dtu_tdt_dm_wr_ready; +output [31:0] tdt_dm_wdata; +output [1 :0] tdt_dm_wr_flg; +output tdt_dm_wr_vld; + +// &Regs; @25 +reg [1 :0] cur_state; +reg debug_inst_vld_pulse_f; +reg [31:0] dm_rdata; +reg [31:0] dm_rdata_reg; +reg dtu_havereset; +reg dtu_rtu_async_halt_req_lvl_f; +reg dtu_rtu_async_halt_req_lvl_ff; +reg dtu_tdt_dm_wr_ready; +reg [31:0] itr_reg; +reg [1 :0] next_state; +reg rtu_yy_xx_dbgon_reg; +reg [31:0] rx_data; +reg [31:0] tdt_dm_wdata; +reg [1 :0] tdt_dm_wr_flg; +reg tdt_dm_wr_vld_f; +reg tdt_dm_wr_vld_pulse_f; + +// &Wires; @26 +wire async_halt_req_wakeup; +wire cp0_yy_clk_en; +wire cpurst_b; +wire debug_inst_vld_pulse; +wire [31:0] dscratch0; +wire dtu_cdc_clk; +wire [31:0] dtu_ifu_debug_inst; +wire dtu_ifu_debug_inst_vld; +wire dtu_ifu_halt_on_reset; +wire dtu_rtu_async_halt_req; +wire dtu_rtu_async_halt_req_lvl; +wire dtu_rtu_resume_req; +wire dtu_rtu_sync_halt_req; +wire dtu_tdt_dm_halted; +wire dtu_tdt_dm_havereset; +wire dtu_tdt_dm_itr_done; +wire dtu_tdt_dm_retire_debug_expt_vld; +wire [31:0] dtu_tdt_dm_rx_data; +wire dtu_tdt_dm_wr_ready_pulse; +wire forever_cpuclk; +wire [31:0] latest_pc; +wire [31:0] latest_pc_for_dm; +wire pad_yy_icg_scan_en; +wire rtu_dtu_retire_debug_expt_vld; +wire rtu_dtu_retire_vld; +wire rtu_dtu_retire_vld_dbgon; +wire rtu_yy_xx_dbgon; +wire sys_apb_clk; +wire sys_apb_rst_b; +wire tdt_dm_ack_havereset; +wire tdt_dm_dtu_ack_havereset; +wire tdt_dm_dtu_async_halt_req; +wire tdt_dm_dtu_halt_on_reset; +wire tdt_dm_dtu_halt_req; +wire [31:0] tdt_dm_dtu_itr; +wire tdt_dm_dtu_itr_vld; +wire tdt_dm_dtu_resume_req; +wire [31:0] tdt_dm_dtu_wdata; +wire [1 :0] tdt_dm_dtu_wr_flg; +wire tdt_dm_dtu_wr_vld; +wire tdt_dm_wr_vld; +wire tdt_dm_wr_vld_pulse; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; + +//state machine parameter +parameter IDLE = 2'b00; +parameter PULSE = 2'b01; +parameter HAVE_RESET = 2'b10; +parameter PENDING = 2'b11; + +//=============================================================== +// CDC of DM to DTU +//=============================================================== +//tdt_dm_dtu_halt_req to dtu_rtu_sync_halt_req +// &Instance("pa_dtu_cdc_lvl","x_pa_tdt_dm_dtu_halt_req_cdc"); @42 +pa_dtu_cdc_lvl x_pa_tdt_dm_dtu_halt_req_cdc ( + .clk (forever_cpuclk ), + .dst_lvl (dtu_rtu_sync_halt_req), + .rst_b (cpurst_b ), + .src_lvl (tdt_dm_dtu_halt_req ) +); + +// &Connect(.clk (forever_cpuclk), @43 +// .rst_b (cpurst_b), @44 +// .src_lvl (tdt_dm_dtu_halt_req), @45 +// .dst_lvl (dtu_rtu_sync_halt_req)); @46 + +//tdt_dm_dtu_async_halt_req to dtu_rtu_async_halt_req +// &Instance("pa_dtu_cdc_lvl","x_pa_tdt_dm_dtu_async_halt_req_cdc"); @49 +pa_dtu_cdc_lvl x_pa_tdt_dm_dtu_async_halt_req_cdc ( + .clk (forever_cpuclk ), + .dst_lvl (dtu_rtu_async_halt_req_lvl), + .rst_b (cpurst_b ), + .src_lvl (tdt_dm_dtu_async_halt_req ) +); + +// &Connect(.clk (forever_cpuclk), @50 +// .rst_b (cpurst_b), @51 +// .src_lvl (tdt_dm_dtu_async_halt_req), @52 +// .dst_lvl (dtu_rtu_async_halt_req_lvl)); @53 + +always @(posedge forever_cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + dtu_rtu_async_halt_req_lvl_f <= 1'b0; + dtu_rtu_async_halt_req_lvl_ff <= 1'b0; + end + else + begin + dtu_rtu_async_halt_req_lvl_f <= dtu_rtu_async_halt_req_lvl; + dtu_rtu_async_halt_req_lvl_ff <= dtu_rtu_async_halt_req_lvl_f; + end +end + +assign async_halt_req_wakeup = dtu_rtu_async_halt_req_lvl && !dtu_rtu_async_halt_req_lvl_f; +assign dtu_rtu_async_halt_req = dtu_rtu_async_halt_req_lvl_f && !dtu_rtu_async_halt_req_lvl_ff; + +//tdt_dm_dtu_halt_on_reset to dtu_ifu_halt_on_reset +// &Instance("pa_dtu_cdc_lvl","x_pa_tdt_dm_dtu_halt_on_reset_cdc"); @73 +pa_dtu_cdc_lvl x_pa_tdt_dm_dtu_halt_on_reset_cdc ( + .clk (dtu_cdc_clk ), + .dst_lvl (dtu_ifu_halt_on_reset ), + .rst_b (cpurst_b ), + .src_lvl (tdt_dm_dtu_halt_on_reset) +); + +// &Connect(.clk (dtu_cdc_clk), @74 +// .rst_b (cpurst_b), @75 +// .src_lvl (tdt_dm_dtu_halt_on_reset), @76 +// .dst_lvl (dtu_ifu_halt_on_reset)); @77 + +//tdt_dm_dtu_resume_req(pulse) to dtu_rtu_resume_req(pulse) +// &Instance("pa_dtu_cdc_pulse","x_pa_dtu_rtu_resume_req_cdc"); @80 +pa_dtu_cdc_pulse x_pa_dtu_rtu_resume_req_cdc ( + .dst_clk (dtu_cdc_clk ), + .dst_pulse (dtu_rtu_resume_req ), + .dst_rst_b (cpurst_b ), + .src_clk (sys_apb_clk ), + .src_pulse (tdt_dm_dtu_resume_req), + .src_rst_b (sys_apb_rst_b ) +); + +// &Connect(.src_clk (sys_apb_clk), @81 +// .src_rst_b (sys_apb_rst_b), @82 +// .dst_clk(dtu_cdc_clk), @83 +// .dst_rst_b(cpurst_b), @84 +// .src_pulse(tdt_dm_dtu_resume_req), @85 +// .dst_pulse(dtu_rtu_resume_req)); @86 + +//tdt_dm_dtu_ack_havereset(pulse) to tdt_dm_ack_havereset(pulse) +// &Instance("pa_dtu_cdc_pulse","x_pa_tdt_dm_dtu_ack_havereset_cdc"); @89 +pa_dtu_cdc_pulse x_pa_tdt_dm_dtu_ack_havereset_cdc ( + .dst_clk (dtu_cdc_clk ), + .dst_pulse (tdt_dm_ack_havereset ), + .dst_rst_b (cpurst_b ), + .src_clk (sys_apb_clk ), + .src_pulse (tdt_dm_dtu_ack_havereset), + .src_rst_b (sys_apb_rst_b ) +); + +// &Connect(.src_clk (sys_apb_clk), @90 +// .src_rst_b (sys_apb_rst_b), @91 +// .dst_clk(dtu_cdc_clk), @92 +// .dst_rst_b(cpurst_b), @93 +// .src_pulse(tdt_dm_dtu_ack_havereset), @94 +// .dst_pulse(tdt_dm_ack_havereset)); @95 + +//tdt_dm_dtu_itr_vld(pulse) to dtu_ifu_debug_inst_vld(pulse) +//tdt_dm_dtu_itr(32 bit) to dtu_ifu_debug_inst(32 bit) +// &Instance("pa_dtu_cdc_pulse","x_pa_tdt_dm_dtu_itr_vld_cdc"); @99 +pa_dtu_cdc_pulse x_pa_tdt_dm_dtu_itr_vld_cdc ( + .dst_clk (dtu_cdc_clk ), + .dst_pulse (debug_inst_vld_pulse), + .dst_rst_b (cpurst_b ), + .src_clk (sys_apb_clk ), + .src_pulse (tdt_dm_dtu_itr_vld ), + .src_rst_b (sys_apb_rst_b ) +); + +// &Connect(.src_clk (sys_apb_clk), @100 +// .src_rst_b (sys_apb_rst_b), @101 +// .dst_clk(dtu_cdc_clk), @102 +// .dst_rst_b(cpurst_b), @103 +// .src_pulse(tdt_dm_dtu_itr_vld), @104 +// .dst_pulse(debug_inst_vld_pulse)); @105 + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + debug_inst_vld_pulse_f <= 1'b0; + else + debug_inst_vld_pulse_f <= debug_inst_vld_pulse; +end +assign dtu_ifu_debug_inst_vld = debug_inst_vld_pulse_f; + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + itr_reg[31:0] <= 32'b0; + else if(debug_inst_vld_pulse) + itr_reg[31:0] <= tdt_dm_dtu_itr[31:0]; +end +assign dtu_ifu_debug_inst[31:0] = itr_reg[31:0]; + +//tdt_dm_dtu_wr_vld +//tdt_dm_dtu_wr_flg +//tdt_dm_dtu_wdata +// &Instance("pa_dtu_cdc_pulse","x_pa_tdt_dm_dtu_wr_vld_cdc"); @128 +pa_dtu_cdc_pulse x_pa_tdt_dm_dtu_wr_vld_cdc ( + .dst_clk (dtu_cdc_clk ), + .dst_pulse (tdt_dm_wr_vld_pulse), + .dst_rst_b (cpurst_b ), + .src_clk (sys_apb_clk ), + .src_pulse (tdt_dm_dtu_wr_vld ), + .src_rst_b (sys_apb_rst_b ) +); + +// &Connect(.src_clk (sys_apb_clk), @129 +// .src_rst_b (sys_apb_rst_b), @130 +// .dst_clk(dtu_cdc_clk), @131 +// .dst_rst_b(cpurst_b), @132 +// .src_pulse(tdt_dm_dtu_wr_vld), @133 +// .dst_pulse(tdt_dm_wr_vld_pulse)); @134 + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdt_dm_wr_vld_pulse_f <= 1'b0; + else + tdt_dm_wr_vld_pulse_f <= tdt_dm_wr_vld_pulse; +end +assign tdt_dm_wr_vld = tdt_dm_wr_vld_pulse_f; +// &Force("output","tdt_dm_wr_vld"); @144 +//when cpuclk = abp_clk, dtu_tdt_dm_wr_ready need wait dtu_tdt_dm_rx_data for a cycle +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdt_dm_wr_vld_f <= 1'b0; + else + tdt_dm_wr_vld_f <= tdt_dm_wr_vld; +end + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdt_dm_wr_flg[1:0] <= 2'b0; + else if(tdt_dm_wr_vld_pulse) + tdt_dm_wr_flg[1:0] <= tdt_dm_dtu_wr_flg[1:0]; +end +// &Force("output","tdt_dm_wr_flg");&Force("bus","tdt_dm_wr_flg",1,0); @161 + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdt_dm_wdata[XLEN-1:0] <= {XLEN{1'b0}}; + else if(tdt_dm_wr_vld_pulse) + tdt_dm_wdata[XLEN-1:0] <= tdt_dm_dtu_wdata[XLEN-1:0]; +end + +//sample last_pc_for_dm +assign latest_pc_for_dm[`PA_WIDTH-1:0] = latest_pc[`PA_WIDTH-1:0]; + +//read data for dm +// &CombBeg; @179 +always @( dscratch0[31:0] + or latest_pc_for_dm[31:0] + or tdt_dm_wr_flg[1:0]) +begin +case(tdt_dm_wr_flg[1:0]) + 2'b00:dm_rdata[XLEN-1:0] = dscratch0[XLEN-1:0]; + 2'b01:dm_rdata[XLEN-1:0] = {XLEN{1'b0}}; + 2'b10:dm_rdata[XLEN-1:0] = latest_pc_for_dm[`PA_WIDTH-1:0]; + 2'b11:dm_rdata[XLEN-1:0] = {XLEN{1'b0}}; + default:dm_rdata[XLEN-1:0] = {XLEN{1'bx}}; +endcase +// &CombEnd; @187 +end +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dm_rdata_reg[XLEN-1:0] <= {XLEN{1'b0}}; + else if(tdt_dm_wr_vld) + dm_rdata_reg[XLEN-1:0] <= dm_rdata[XLEN-1:0]; +end + + //=============================================================== +// CDC of DTU to DM +//================================================================ +//rtu_yy_xx_dbgon to dtu_tdt_dm_halted +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + rtu_yy_xx_dbgon_reg <= 1'b0; + else + rtu_yy_xx_dbgon_reg <= rtu_yy_xx_dbgon; +end +// &Instance("pa_dtu_cdc_lvl","x_pa_dtu_tdt_dm_halted_cdc"); @207 +pa_dtu_cdc_lvl x_pa_dtu_tdt_dm_halted_cdc ( + .clk (sys_apb_clk ), + .dst_lvl (dtu_tdt_dm_halted ), + .rst_b (sys_apb_rst_b ), + .src_lvl (rtu_yy_xx_dbgon_reg) +); + +// &Connect(.clk (sys_apb_clk), @208 +// .rst_b (sys_apb_rst_b), @209 +// .src_lvl (rtu_yy_xx_dbgon_reg), @210 +// .dst_lvl (dtu_tdt_dm_halted)); @211 + +//rtu_dtu_retire_vld(pluse) to dtu_tdt_dm_itr_done(pluse) +assign rtu_dtu_retire_vld_dbgon = rtu_dtu_retire_vld && rtu_yy_xx_dbgon; +// &Instance("pa_dtu_cdc_pulse","x_pa_dtu_tdt_dm_itr_done_cdc"); @215 +pa_dtu_cdc_pulse x_pa_dtu_tdt_dm_itr_done_cdc ( + .dst_clk (sys_apb_clk ), + .dst_pulse (dtu_tdt_dm_itr_done ), + .dst_rst_b (sys_apb_rst_b ), + .src_clk (dtu_cdc_clk ), + .src_pulse (rtu_dtu_retire_vld_dbgon), + .src_rst_b (cpurst_b ) +); + +// &Connect(.src_clk (dtu_cdc_clk), @216 +// .src_rst_b (cpurst_b), @217 +// .dst_clk(sys_apb_clk), @218 +// .dst_rst_b(sys_apb_rst_b), @219 +// .src_pulse(rtu_dtu_retire_vld_dbgon), @220 +// .dst_pulse(dtu_tdt_dm_itr_done)); @221 + +//rtu_dtu_retire_debug_expt_vld(pulse) to dtu_tdt_dm_retire_debug_expt_vld(pulse) +// &Instance("pa_dtu_cdc_pulse","x_pa_dtu_tdt_dm_retire_debug_expt_vld_cdc"); @224 +pa_dtu_cdc_pulse x_pa_dtu_tdt_dm_retire_debug_expt_vld_cdc ( + .dst_clk (sys_apb_clk ), + .dst_pulse (dtu_tdt_dm_retire_debug_expt_vld), + .dst_rst_b (sys_apb_rst_b ), + .src_clk (dtu_cdc_clk ), + .src_pulse (rtu_dtu_retire_debug_expt_vld ), + .src_rst_b (cpurst_b ) +); + +// &Connect(.src_clk (dtu_cdc_clk), @225 +// .src_rst_b (cpurst_b), @226 +// .dst_clk(sys_apb_clk), @227 +// .dst_rst_b(sys_apb_rst_b), @228 +// .src_pulse(rtu_dtu_retire_debug_expt_vld), @229 +// .dst_pulse(dtu_tdt_dm_retire_debug_expt_vld)); @230 + +//dtu_tdt_dm_wr_ready +//dtu_tdt_dm_Rx_data +// &Instance("pa_dtu_cdc_pulse","x_pa_dtu_tdt_dm_wr_ready_cdc"); @234 +pa_dtu_cdc_pulse x_pa_dtu_tdt_dm_wr_ready_cdc ( + .dst_clk (sys_apb_clk ), + .dst_pulse (dtu_tdt_dm_wr_ready_pulse), + .dst_rst_b (sys_apb_rst_b ), + .src_clk (dtu_cdc_clk ), + .src_pulse (tdt_dm_wr_vld_f ), + .src_rst_b (cpurst_b ) +); + +// &Connect(.src_clk (dtu_cdc_clk), @235 +// .src_rst_b (cpurst_b), @236 +// .dst_clk(sys_apb_clk), @237 +// .dst_rst_b(sys_apb_rst_b), @238 +// .src_pulse(tdt_dm_wr_vld_f), @239 +// .dst_pulse(dtu_tdt_dm_wr_ready_pulse)); @240 + +always @(posedge sys_apb_clk or negedge sys_apb_rst_b) +begin + if(!sys_apb_rst_b) + dtu_tdt_dm_wr_ready <= 1'b0; + else + dtu_tdt_dm_wr_ready <= dtu_tdt_dm_wr_ready_pulse; +end + +always @(posedge sys_apb_clk or negedge sys_apb_rst_b) +begin + if(!sys_apb_rst_b) + rx_data[XLEN-1:0] <= {XLEN{1'b0}}; + else if(dtu_tdt_dm_wr_ready_pulse) + rx_data[XLEN-1:0] <= dm_rdata_reg[XLEN-1:0]; +end +assign dtu_tdt_dm_rx_data[XLEN-1:0] = rx_data[XLEN-1:0]; + +//generate dtu_tdt_dm_havereset(lvl) when cpurst_b switch to 1 +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + cur_state[1:0] <= IDLE; + else + cur_state[1:0] <= next_state[1:0]; +end + +// &CombBeg; @268 +always @( cur_state[1:0] + or tdt_dm_ack_havereset) +begin + case(cur_state[1:0]) + IDLE: next_state[1:0] = PULSE; + PULSE: next_state[1:0] = HAVE_RESET; + HAVE_RESET: if(tdt_dm_ack_havereset) + next_state[1:0] = PENDING; + else + next_state[1:0] = HAVE_RESET; + PENDING: next_state[1:0] = PENDING; + default: next_state[1:0] = IDLE; + endcase +// &CombEnd; @279 +end + +always @(posedge dtu_cdc_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dtu_havereset <= 1'b0; + else + dtu_havereset <= cur_state[1:0] == HAVE_RESET; +end + +// &Instance("pa_dtu_cdc_lvl","x_pa_dtu_tdt_dm_havereset_cdc"); @289 +pa_dtu_cdc_lvl x_pa_dtu_tdt_dm_havereset_cdc ( + .clk (sys_apb_clk ), + .dst_lvl (dtu_tdt_dm_havereset), + .rst_b (sys_apb_rst_b ), + .src_lvl (dtu_havereset ) +); + +// &Connect(.clk (sys_apb_clk), @290 +// .rst_b (sys_apb_rst_b), @291 +// .src_lvl (dtu_havereset), @292 +// .dst_lvl (dtu_tdt_dm_havereset)); @293 + +// &Force("output","dtu_rtu_resume_req"); @349 +// &Force("output","dtu_ifu_debug_inst_vld"); @373 +// &Force("output","tdt_dm_wr_vld"); @395 +// &Force("output","tdt_dm_wr_flg");&Force("bus","tdt_dm_wr_flg",1,0); @412 +// &CombBeg; @430 +// &CombEnd; @438 +// &Instance("pa_dtu_cdc_pulse_div_fast_to_slow","x_pa_dtu_tdt_dm_itr_done_cdc"); @467 +// &Connect(.src_clk (dtu_cdc_clk), @468 +// .src_rst_b (cpurst_b), @469 +// .clk_en(sys_apb_clk_en), @470 +// .modify(itr_done_modify), @471 +// .src_pulse(rtu_dtu_retire_vld_dbgon), @472 +// .dst_pulse(dtu_tdt_dm_itr_done)); @473 +// &Force("nonport","itr_done_modify"); @474 +// &Instance("pa_dtu_cdc_pulse_div_fast_to_slow","x_pa_dtu_tdt_dm_retire_debug_expt_vld_cdc"); @477 +// &Connect(.src_clk (dtu_cdc_clk), @478 +// .src_rst_b (cpurst_b), @479 +// .clk_en(sys_apb_clk_en), @480 +// .modify(retire_debug_expt_vld_modify), @481 +// .src_pulse(rtu_dtu_retire_debug_expt_vld), @482 +// .dst_pulse(dtu_tdt_dm_retire_debug_expt_vld)); @483 +// &Force("nonport","retire_debug_expt_vld_modify"); @484 +// &Instance("pa_dtu_cdc_pulse_div_fast_to_slow","x_pa_dtu_tdt_dm_wr_ready_cdc"); @488 +// &Connect(.src_clk (dtu_cdc_clk), @489 +// .src_rst_b (cpurst_b), @490 +// .clk_en(sys_apb_clk_en), @491 +// .modify(wr_ready_modify), @492 +// .src_pulse(tdt_dm_wr_vld_f), @493 +// .dst_pulse(dtu_tdt_dm_wr_ready)); @494 +// &CombBeg; @514 +// &CombEnd; @525 + +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @544 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dtu_cdc_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (1'b1 ), + .module_en (1'b1 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @545 +// .external_en (1'b0), @546 +// .global_en (cp0_yy_clk_en), @547 +// //.module_en (cp0_dtu_icg_en), @548 +// .module_en (1'b1), @549 +// .local_en (1'b1), @550 +// .clk_out (dtu_cdc_clk)); @551 + + +// &ModuleEnd; @560 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_lvl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_lvl.v new file mode 100644 index 0000000000000000000000000000000000000000..a95d98196f0966f716618bb9f612b53bfd5b2082 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_lvl.v @@ -0,0 +1,60 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_dtu_cdc_lvl( + clk, + dst_lvl, + rst_b, + src_lvl +); + +// &Ports; @21 +input clk; +input rst_b; +input src_lvl; +output dst_lvl; + +// &Regs; @22 +reg sync1; +reg sync2; +reg sync3; + +// &Wires; @23 +wire clk; +wire dst_lvl; +wire rst_b; +wire src_lvl; + + +always @(posedge clk or negedge rst_b) +begin + if(!rst_b) + begin + sync1 <= 1'b0; + sync2 <= 1'b0; + sync3 <= 1'b0; + end + else + begin + sync1 <= src_lvl; + sync2 <= sync1; + sync3 <= sync2; + end +end +assign dst_lvl = sync3; + +// &ModuleEnd; @42 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_pulse.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_pulse.v new file mode 100644 index 0000000000000000000000000000000000000000..819e141ff0ee8c2a11c9d026349308900774b223 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cdc_pulse.v @@ -0,0 +1,105 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_dtu_cdc_pulse( + dst_clk, + dst_pulse, + dst_rst_b, + src_clk, + src_pulse, + src_rst_b +); + +// &Ports; @21 +input dst_clk; +input dst_rst_b; +input src_clk; +input src_pulse; +input src_rst_b; +output dst_pulse; + +// &Regs; @22 +reg dst_sync1; +reg dst_sync2; +reg dst_sync3; +reg dst_sync4; +reg src_lvl; +reg src_sync1; +reg src_sync2; +reg src_sync3; +reg src_sync4; + +// &Wires; @23 +wire clear_src_lvl; +wire dst_clk; +wire dst_pulse; +wire dst_rst_b; +wire src_clk; +wire src_pulse; +wire src_rst_b; + + +always @(posedge src_clk or negedge src_rst_b) +begin + if(!src_rst_b) + src_lvl <= 1'b0; + else if(src_pulse) + src_lvl <= 1'b1; + else if(clear_src_lvl) + src_lvl <= 1'b0; +end + +always @(posedge dst_clk or negedge dst_rst_b) +begin + if(!dst_rst_b) + begin + dst_sync1 <= 1'b0; + dst_sync2 <= 1'b0; + dst_sync3 <= 1'b0; + dst_sync4 <= 1'b0; + end + else + begin + dst_sync1 <= src_lvl; + dst_sync2 <= dst_sync1; + dst_sync3 <= dst_sync2; + dst_sync4 <= dst_sync3; + end +end + +always @(posedge src_clk or negedge src_rst_b) +begin + if(!src_rst_b) + begin + src_sync1 <= 1'b0; + src_sync2 <= 1'b0; + src_sync3 <= 1'b0; + src_sync4 <= 1'b0; + end + else + begin + src_sync1 <= dst_sync3; + src_sync2 <= src_sync1; + src_sync3 <= src_sync2; + src_sync4 <= src_sync3; + end +end +assign clear_src_lvl = src_sync3 && !src_sync4; + +assign dst_pulse = dst_sync3 && !dst_sync4; + +// &ModuleEnd; @74 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cfig.h b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cfig.h new file mode 100644 index 0000000000000000000000000000000000000000..2d0cd2fc39156f8179c0d0acaec6e3b219475c09 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_cfig.h @@ -0,0 +1,517 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +//---------------------Minimum Define----------------------- +`ifdef TDT_TM_MINIMUM +//mcontrol trigger legal number is 0/1/2/3/4/5/6/7/8, there is +//no mcontrol when define "TDT_TM_MCONTROL_TRI_NUM_0" +//`define TDT_TM_MCONTROL_TRI_NUM_0 +`define TDT_TM_MCONTROL_TRI_NUM_1 +//`define TDT_TM_MCONTROL_TRI_NUM_2 +//`define TDT_TM_MCONTROL_TRI_NUM_3 +//`define TDT_TM_MCONTROL_TRI_NUM_4 +//`define TDT_TM_MCONTROL_TRI_NUM_5 +//`define TDT_TM_MCONTROL_TRI_NUM_6 +//`define TDT_TM_MCONTROL_TRI_NUM_7 +//`define TDT_TM_MCONTROL_TRI_NUM_8 + +//`define TDT_TM_MCONTROL_CHAIN + +//mcontrol trigger configuration +//when MCONTROL_TRI_NUM >= 1, macros of MCONTROL0 are used +`define TDT_TM_MCONTROL0_EXE +//`define TDT_TM_MCONTROL0_LDST +`define TDT_TM_MCONTROL0_ADDR +//`define TDT_TM_MCONTROL0_DATA +`define TDT_TM_MCONTROL0_MATCH_TYP0 +//`define TDT_TM_MCONTROL0_MATCH_TYP1 +//`define TDT_TM_MCONTROL0_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 2, macros of MCONTROL1 are used +//`define TDT_TM_MCONTROL1_EXE +//`define TDT_TM_MCONTROL1_LDST +//`define TDT_TM_MCONTROL1_ADDR +//`define TDT_TM_MCONTROL1_DATA +//`define TDT_TM_MCONTROL1_MATCH_TYP0 +//`define TDT_TM_MCONTROL1_MATCH_TYP1 +//`define TDT_TM_MCONTROL1_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 3, macros of MCONTROL2 are used +//`define TDT_TM_MCONTROL2_EXE +//`define TDT_TM_MCONTROL2_LDST +//`define TDT_TM_MCONTROL2_ADDR +//`define TDT_TM_MCONTROL2_DATA +//`define TDT_TM_MCONTROL2_MATCH_TYP0 +//`define TDT_TM_MCONTROL2_MATCH_TYP1 +//`define TDT_TM_MCONTROL2_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 4, macros of MCONTROL3 are used +//`define TDT_TM_MCONTROL3_EXE +//`define TDT_TM_MCONTROL3_LDST +//`define TDT_TM_MCONTROL3_ADDR +//`define TDT_TM_MCONTROL3_DATA +//`define TDT_TM_MCONTROL3_MATCH_TYP0 +//`define TDT_TM_MCONTROL3_MATCH_TYP1 +//`define TDT_TM_MCONTROL3_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 5, macros of MCONTROL4 are used +//`define TDT_TM_MCONTROL4_EXE +//`define TDT_TM_MCONTROL4_LDST +//`define TDT_TM_MCONTROL4_ADDR +//`define TDT_TM_MCONTROL4_DATA +//`define TDT_TM_MCONTROL4_MATCH_TYP0 +//`define TDT_TM_MCONTROL4_MATCH_TYP1 +//`define TDT_TM_MCONTROL4_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 6, macros of MCONTROL5 are used +//`define TDT_TM_MCONTROL5_EXE +//`define TDT_TM_MCONTROL5_LDST +//`define TDT_TM_MCONTROL5_ADDR +//`define TDT_TM_MCONTROL5_DATA +//`define TDT_TM_MCONTROL5_MATCH_TYP0 +//`define TDT_TM_MCONTROL5_MATCH_TYP1 +//`define TDT_TM_MCONTROL5_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 7, macros of MCONTROL6 are used +//`define TDT_TM_MCONTROL6_EXE +//`define TDT_TM_MCONTROL6_LDST +//`define TDT_TM_MCONTROL6_ADDR +//`define TDT_TM_MCONTROL6_DATA +//`define TDT_TM_MCONTROL6_MATCH_TYP0 +//`define TDT_TM_MCONTROL6_MATCH_TYP1 +//`define TDT_TM_MCONTROL6_MATCH_TYP2 + +//when MCONTROL_TRI_NUM = 8, macros of MCONTROL7 are used +//`define TDT_TM_MCONTROL7_EXE +//`define TDT_TM_MCONTROL7_LDST +//`define TDT_TM_MCONTROL7_ADDR +//`define TDT_TM_MCONTROL7_DATA +//`define TDT_TM_MCONTROL7_MATCH_TYP0 +//`define TDT_TM_MCONTROL7_MATCH_TYP1 +//`define TDT_TM_MCONTROL7_MATCH_TYP2 + +//icount/int/expt shared trigger legal number is 0/1/2, there is +//no icount/int/expt shared trigger when define "TDT_TM_OTHER_TRI_NUM_0" +`define TDT_TM_OTHER_TRI_NUM_0 +//`define TDT_TM_OTHER_TRI_NUM_1 +//`define TDT_TM_OTHER_TRI_NUM_2 +`endif + +//---------------------Typical Define----------------------- +`ifdef TDT_TM_TYPICAL +//mcontrol trigger legal number is 0/1/2/3/4/5/6/7/8, there is +//no mcontrol when define "TDT_TM_MCONTROL_TRI_NUM_0" +//`define TDT_TM_MCONTROL_TRI_NUM_0 +//`define TDT_TM_MCONTROL_TRI_NUM_1 +//`define TDT_TM_MCONTROL_TRI_NUM_2 +`define TDT_TM_MCONTROL_TRI_NUM_3 +//`define TDT_TM_MCONTROL_TRI_NUM_4 +//`define TDT_TM_MCONTROL_TRI_NUM_5 +//`define TDT_TM_MCONTROL_TRI_NUM_6 +//`define TDT_TM_MCONTROL_TRI_NUM_7 +//`define TDT_TM_MCONTROL_TRI_NUM_8 + +//`define TDT_TM_MCONTROL_CHAIN + +//mcontrol trigger configuration +//when MCONTROL_TRI_NUM >= 1, macros of MCONTROL0 are used +`define TDT_TM_MCONTROL0_EXE +`define TDT_TM_MCONTROL0_LDST +`define TDT_TM_MCONTROL0_ADDR +//`define TDT_TM_MCONTROL0_DATA +`define TDT_TM_MCONTROL0_MATCH_TYP0 +//`define TDT_TM_MCONTROL0_MATCH_TYP1 +//`define TDT_TM_MCONTROL0_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 2, macros of MCONTROL1 are used +`define TDT_TM_MCONTROL1_EXE +`define TDT_TM_MCONTROL1_LDST +`define TDT_TM_MCONTROL1_ADDR +//`define TDT_TM_MCONTROL1_DATA +`define TDT_TM_MCONTROL1_MATCH_TYP0 +//`define TDT_TM_MCONTROL1_MATCH_TYP1 +//`define TDT_TM_MCONTROL1_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 3, macros of MCONTROL2 are used +`define TDT_TM_MCONTROL2_EXE +`define TDT_TM_MCONTROL2_LDST +`define TDT_TM_MCONTROL2_ADDR +//`define TDT_TM_MCONTROL2_DATA +`define TDT_TM_MCONTROL2_MATCH_TYP0 +//`define TDT_TM_MCONTROL2_MATCH_TYP1 +//`define TDT_TM_MCONTROL2_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 4, macros of MCONTROL3 are used +//`define TDT_TM_MCONTROL3_EXE +//`define TDT_TM_MCONTROL3_LDST +//`define TDT_TM_MCONTROL3_ADDR +//`define TDT_TM_MCONTROL3_DATA +//`define TDT_TM_MCONTROL3_MATCH_TYP0 +//`define TDT_TM_MCONTROL3_MATCH_TYP1 +//`define TDT_TM_MCONTROL3_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 5, macros of MCONTROL4 are used +//`define TDT_TM_MCONTROL4_EXE +//`define TDT_TM_MCONTROL4_LDST +//`define TDT_TM_MCONTROL4_ADDR +//`define TDT_TM_MCONTROL4_DATA +//`define TDT_TM_MCONTROL4_MATCH_TYP0 +//`define TDT_TM_MCONTROL4_MATCH_TYP1 +//`define TDT_TM_MCONTROL4_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 6, macros of MCONTROL5 are used +//`define TDT_TM_MCONTROL5_EXE +//`define TDT_TM_MCONTROL5_LDST +//`define TDT_TM_MCONTROL5_ADDR +//`define TDT_TM_MCONTROL5_DATA +//`define TDT_TM_MCONTROL5_MATCH_TYP0 +//`define TDT_TM_MCONTROL5_MATCH_TYP1 +//`define TDT_TM_MCONTROL5_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 7, macros of MCONTROL6 are used +//`define TDT_TM_MCONTROL6_EXE +//`define TDT_TM_MCONTROL6_LDST +//`define TDT_TM_MCONTROL6_ADDR +//`define TDT_TM_MCONTROL6_DATA +//`define TDT_TM_MCONTROL6_MATCH_TYP0 +//`define TDT_TM_MCONTROL6_MATCH_TYP1 +//`define TDT_TM_MCONTROL6_MATCH_TYP2 + +//when MCONTROL_TRI_NUM = 8, macros of MCONTROL7 are used +//`define TDT_TM_MCONTROL7_EXE +//`define TDT_TM_MCONTROL7_LDST +//`define TDT_TM_MCONTROL7_ADDR +//`define TDT_TM_MCONTROL7_DATA +//`define TDT_TM_MCONTROL7_MATCH_TYP0 +//`define TDT_TM_MCONTROL7_MATCH_TYP1 +//`define TDT_TM_MCONTROL7_MATCH_TYP2 + +//icount/int/expt shared trigger legal number is 0/1/2, there is +//no icount/int/expt shared trigger when define "TDT_TM_OTHER_TRI_NUM_0" +`define TDT_TM_OTHER_TRI_NUM_0 +//`define TDT_TM_OTHER_TRI_NUM_1 +//`define TDT_TM_OTHER_TRI_NUM_2 +`endif + +//---------------------Maximum Define----------------------- +`ifdef TDT_TM_MAXIMUM +//mcontrol trigger legal number is 0/1/2/3/4/5/6/7/8, there is +//no mcontrol when define "TDT_TM_MCONTROL_TRI_NUM_0" +//`define TDT_TM_MCONTROL_TRI_NUM_0 +//`define TDT_TM_MCONTROL_TRI_NUM_1 +//`define TDT_TM_MCONTROL_TRI_NUM_2 +//`define TDT_TM_MCONTROL_TRI_NUM_3 +//`define TDT_TM_MCONTROL_TRI_NUM_4 +//`define TDT_TM_MCONTROL_TRI_NUM_5 +//`define TDT_TM_MCONTROL_TRI_NUM_6 +//`define TDT_TM_MCONTROL_TRI_NUM_7 +`define TDT_TM_MCONTROL_TRI_NUM_8 + +`define TDT_TM_MCONTROL_CHAIN + +//mcontrol trigger configuration +//when MCONTROL_TRI_NUM >= 1, macros of MCONTROL0 are used +`define TDT_TM_MCONTROL0_EXE +`define TDT_TM_MCONTROL0_LDST +`define TDT_TM_MCONTROL0_ADDR +`define TDT_TM_MCONTROL0_DATA +//`define TDT_TM_MCONTROL0_MATCH_TYP0 +//`define TDT_TM_MCONTROL0_MATCH_TYP1 +`define TDT_TM_MCONTROL0_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 2, macros of MCONTROL1 are used +`define TDT_TM_MCONTROL1_EXE +`define TDT_TM_MCONTROL1_LDST +`define TDT_TM_MCONTROL1_ADDR +`define TDT_TM_MCONTROL1_DATA +//`define TDT_TM_MCONTROL1_MATCH_TYP0 +//`define TDT_TM_MCONTROL1_MATCH_TYP1 +`define TDT_TM_MCONTROL1_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 3, macros of MCONTROL2 are used +`define TDT_TM_MCONTROL2_EXE +`define TDT_TM_MCONTROL2_LDST +`define TDT_TM_MCONTROL2_ADDR +`define TDT_TM_MCONTROL2_DATA +//`define TDT_TM_MCONTROL2_MATCH_TYP0 +//`define TDT_TM_MCONTROL2_MATCH_TYP1 +`define TDT_TM_MCONTROL2_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 4, macros of MCONTROL3 are used +`define TDT_TM_MCONTROL3_EXE +`define TDT_TM_MCONTROL3_LDST +`define TDT_TM_MCONTROL3_ADDR +`define TDT_TM_MCONTROL3_DATA +//`define TDT_TM_MCONTROL3_MATCH_TYP0 +//`define TDT_TM_MCONTROL3_MATCH_TYP1 +`define TDT_TM_MCONTROL3_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 5, macros of MCONTROL4 are used +`define TDT_TM_MCONTROL4_EXE +`define TDT_TM_MCONTROL4_LDST +`define TDT_TM_MCONTROL4_ADDR +`define TDT_TM_MCONTROL4_DATA +//`define TDT_TM_MCONTROL4_MATCH_TYP0 +//`define TDT_TM_MCONTROL4_MATCH_TYP1 +`define TDT_TM_MCONTROL4_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 6, macros of MCONTROL5 are used +`define TDT_TM_MCONTROL5_EXE +`define TDT_TM_MCONTROL5_LDST +`define TDT_TM_MCONTROL5_ADDR +`define TDT_TM_MCONTROL5_DATA +//`define TDT_TM_MCONTROL5_MATCH_TYP0 +//`define TDT_TM_MCONTROL5_MATCH_TYP1 +`define TDT_TM_MCONTROL5_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 7, macros of MCONTROL6 are used +`define TDT_TM_MCONTROL6_EXE +`define TDT_TM_MCONTROL6_LDST +`define TDT_TM_MCONTROL6_ADDR +`define TDT_TM_MCONTROL6_DATA +//`define TDT_TM_MCONTROL6_MATCH_TYP0 +//`define TDT_TM_MCONTROL6_MATCH_TYP1 +`define TDT_TM_MCONTROL6_MATCH_TYP2 + +//when MCONTROL_TRI_NUM = 8, macros of MCONTROL7 are used +`define TDT_TM_MCONTROL7_EXE +`define TDT_TM_MCONTROL7_LDST +`define TDT_TM_MCONTROL7_ADDR +`define TDT_TM_MCONTROL7_DATA +//`define TDT_TM_MCONTROL7_MATCH_TYP0 +//`define TDT_TM_MCONTROL7_MATCH_TYP1 +`define TDT_TM_MCONTROL7_MATCH_TYP2 + +//icount/int/expt shared trigger legal number is 0/1/2, there is +//no icount/int/expt shared trigger when define "TDT_TM_OTHER_TRI_NUM_0" +//`define TDT_TM_OTHER_TRI_NUM_0 +//`define TDT_TM_OTHER_TRI_NUM_1 +`define TDT_TM_OTHER_TRI_NUM_2 +`endif + +//---------------------Self Define----------------------- +`ifdef TDT_TM_SELF_DEF +//mcontrol trigger legal number is 0/1/2/3/4/5/6/7/8, there is +//no mcontrol when define "TDT_TM_MCONTROL_TRI_NUM_0" +//`define TDT_TM_MCONTROL_TRI_NUM_0 +//`define TDT_TM_MCONTROL_TRI_NUM_1 +//`define TDT_TM_MCONTROL_TRI_NUM_2 +`define TDT_TM_MCONTROL_TRI_NUM_3 +//`define TDT_TM_MCONTROL_TRI_NUM_4 +//`define TDT_TM_MCONTROL_TRI_NUM_5 +//`define TDT_TM_MCONTROL_TRI_NUM_6 +//`define TDT_TM_MCONTROL_TRI_NUM_7 +//`define TDT_TM_MCONTROL_TRI_NUM_8 + +//`define TDT_TM_MCONTROL_CHAIN + +//mcontrol trigger configuration +//when MCONTROL_TRI_NUM >= 1, macros of MCONTROL0 are used +`define TDT_TM_MCONTROL0_EXE +`define TDT_TM_MCONTROL0_LDST +`define TDT_TM_MCONTROL0_ADDR +//`define TDT_TM_MCONTROL0_DATA +`define TDT_TM_MCONTROL0_MATCH_TYP0 +//`define TDT_TM_MCONTROL0_MATCH_TYP1 +//`define TDT_TM_MCONTROL0_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 2, macros of MCONTROL1 are used +`define TDT_TM_MCONTROL1_EXE +`define TDT_TM_MCONTROL1_LDST +`define TDT_TM_MCONTROL1_ADDR +//`define TDT_TM_MCONTROL1_DATA +`define TDT_TM_MCONTROL1_MATCH_TYP0 +//`define TDT_TM_MCONTROL1_MATCH_TYP1 +//`define TDT_TM_MCONTROL1_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 3, macros of MCONTROL2 are used +`define TDT_TM_MCONTROL2_EXE +`define TDT_TM_MCONTROL2_LDST +`define TDT_TM_MCONTROL2_ADDR +//`define TDT_TM_MCONTROL2_DATA +`define TDT_TM_MCONTROL2_MATCH_TYP0 +//`define TDT_TM_MCONTROL2_MATCH_TYP1 +//`define TDT_TM_MCONTROL2_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 4, macros of MCONTROL3 are used +//`define TDT_TM_MCONTROL3_EXE +//`define TDT_TM_MCONTROL3_LDST +//`define TDT_TM_MCONTROL3_ADDR +//`define TDT_TM_MCONTROL3_DATA +//`define TDT_TM_MCONTROL3_MATCH_TYP0 +//`define TDT_TM_MCONTROL3_MATCH_TYP1 +//`define TDT_TM_MCONTROL3_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 5, macros of MCONTROL4 are used +//`define TDT_TM_MCONTROL4_EXE +//`define TDT_TM_MCONTROL4_LDST +//`define TDT_TM_MCONTROL4_ADDR +//`define TDT_TM_MCONTROL4_DATA +//`define TDT_TM_MCONTROL4_MATCH_TYP0 +//`define TDT_TM_MCONTROL4_MATCH_TYP1 +//`define TDT_TM_MCONTROL4_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 6, macros of MCONTROL5 are used +//`define TDT_TM_MCONTROL5_EXE +//`define TDT_TM_MCONTROL5_LDST +//`define TDT_TM_MCONTROL5_ADDR +//`define TDT_TM_MCONTROL5_DATA +//`define TDT_TM_MCONTROL5_MATCH_TYP0 +//`define TDT_TM_MCONTROL5_MATCH_TYP1 +//`define TDT_TM_MCONTROL5_MATCH_TYP2 + +//when MCONTROL_TRI_NUM >= 7, macros of MCONTROL6 are used +//`define TDT_TM_MCONTROL6_EXE +//`define TDT_TM_MCONTROL6_LDST +//`define TDT_TM_MCONTROL6_ADDR +//`define TDT_TM_MCONTROL6_DATA +//`define TDT_TM_MCONTROL6_MATCH_TYP0 +//`define TDT_TM_MCONTROL6_MATCH_TYP1 +//`define TDT_TM_MCONTROL6_MATCH_TYP2 + +//when MCONTROL_TRI_NUM = 8, macros of MCONTROL7 are used +//`define TDT_TM_MCONTROL7_EXE +//`define TDT_TM_MCONTROL7_LDST +//`define TDT_TM_MCONTROL7_ADDR +//`define TDT_TM_MCONTROL7_DATA +//`define TDT_TM_MCONTROL7_MATCH_TYP0 +//`define TDT_TM_MCONTROL7_MATCH_TYP1 +//`define TDT_TM_MCONTROL7_MATCH_TYP2 + +//icount/int/expt shared trigger legal number is 0/1/2, there is +//no icount/int/expt shared trigger when define "TDT_TM_OTHER_TRI_NUM_0" +`define TDT_TM_OTHER_TRI_NUM_0 +//`define TDT_TM_OTHER_TRI_NUM_1 +//`define TDT_TM_OTHER_TRI_NUM_2 +`endif + +//--------------------------------------------------------- +// TM Trigger Number Configuration +//--------------------------------------------------------- +`ifdef TDT_TM_OTHER_TRI_NUM_0 + `define TDT_TM_OTHER_TRI_NUM 0 +`else + `ifdef TDT_TM_OTHER_TRI_NUM_1 + `define TDT_TM_OTHER_TRI_NUM 1 + `else + `ifdef TDT_TM_OTHER_TRI_NUM_2 + `define TDT_TM_OTHER_TRI_NUM 2 + `endif + `endif +`endif + +`ifdef TDT_TM_MCONTROL_TRI_NUM_0 + `define TDT_TM_MCONTROL_TRI_NUM 0 +`else + `ifdef TDT_TM_MCONTROL_TRI_NUM_1 + `define TDT_TM_MCONTROL_TRI_NUM 1 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_2 + `define TDT_TM_MCONTROL_TRI_NUM 2 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_3 + `define TDT_TM_MCONTROL_TRI_NUM 3 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_4 + `define TDT_TM_MCONTROL_TRI_NUM 4 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_5 + `define TDT_TM_MCONTROL_TRI_NUM 5 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_6 + `define TDT_TM_MCONTROL_TRI_NUM 6 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_7 + `define TDT_TM_MCONTROL_TRI_NUM 7 + `else + `ifdef TDT_TM_MCONTROL_TRI_NUM_8 + `define TDT_TM_MCONTROL_TRI_NUM 8 + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif +`endif + +`ifdef TDT_TM_MCONTROL_TRI_NUM_0 + `ifdef TDT_TM_OTHER_TRI_NUM_1 + `define TDT_TM_SINGLE_TRI + `endif +`else + `ifdef TDT_TM_MCONTROL_TRI_NUM_1 + `ifdef TDT_TM_OTHER_TRI_NUM_0 + `define TDT_TM_SINGLE_TRI + `endif + `endif +`endif + +//========================================================== +// DTU Configuration +//========================================================== +//--------------------------------------------------------- +// TM Trigger Configuration +//--------------------------------------------------------- +`define TDT_TM_TRIGGER_NUM `TDT_TM_MCONTROL_TRI_NUM + `TDT_TM_OTHER_TRI_NUM + +//---------------------------------------------------------- +// HALT INFO Define +//---------------------------------------------------------- +`define TDT_HINFO_WIDTH `TDT_HINFO_TRIGGER + 1 + +`define TDT_HINFO_TRIGGER `TDT_HINFO_CAUSE + `TDT_TM_TRIGGER_NUM +`define TDT_HINFO_CAUSE `TDT_HINFO_PENDING_HALT + 4 +`define TDT_HINFO_PENDING_HALT `TDT_HINFO_TIMING + 1 +`define TDT_HINFO_TIMING `TDT_HINFO_ACTION01 + 1 +`define TDT_HINFO_ACTION01 `TDT_HINFO_ACTION + 1 +`define TDT_HINFO_ACTION `TDT_HINFO_CHAIN + 1 +`define TDT_HINFO_CHAIN `TDT_HINFO_LDST + 1 +`define TDT_HINFO_LDST `TDT_HINFO_MATCH + 1 +`define TDT_HINFO_MATCH `TDT_HINFO_CANCEL + 1 +`define TDT_HINFO_CANCEL 0 + +//---------------------------------------------------------- +// DTU Define +//---------------------------------------------------------- + +`define TDT_DM_CORE_HALF_XLEN 16 + +`define HALF_PA_WIDTH 16 + +//debuginfo define +`ifdef AXI + `define TDT_DBGINFO_WIDTH 278 + `define TDT_DBGINFO_DEPTH 10 +`else + `define TDT_DBGINFO_WIDTH 298 + `define TDT_DBGINFO_DEPTH 11 +`endif + +//pcfifo define +`ifdef TDT_DEBUG_PCFIFO_8_ENTRY + `define TDT_PCFIFO_DEPTH 8 + `define TDT_PCFIFO_PTR_WIDTH 3 +`else + `ifdef TDT_DEBUG_PCFIFO_16_ENTRY + `define TDT_PCFIFO_DEPTH 16 + `define TDT_PCFIFO_PTR_WIDTH 4 + `endif +`endif + +//for fix tselect trigger number legalization(to fix lint warning) +`define MCONTROL_NUM 4'd`TDT_TM_MCONTROL_TRI_NUM +`define IIE_NUM 4'd`TDT_TM_OTHER_TRI_NUM diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..6e283d2dcd06dcb13d7e01cb66940eac7a53c10f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_ctrl.v @@ -0,0 +1,674 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_ctrl( + async_halt_req_wakeup, + bmu_dtu_debug_info, + cp0_dtu_addr, + cp0_dtu_debug_info, + cp0_dtu_icg_en, + cp0_dtu_mexpt_vld, + cp0_dtu_pcfifo_frz, + cp0_dtu_rreg, + cp0_dtu_wdata, + cp0_dtu_wreg, + cp0_yy_clk_en, + cp0_yy_priv_mode, + cpurst_b, + dahbl_dtu_debug_info, + dcsr_mprven, + dcsr_prv, + dcsr_step, + dcsr_stopcount, + dpc, + dscratch0, + dtu_cp0_rdata, + dtu_ifu_halt_info0, + dtu_ifu_halt_info1, + dtu_ifu_halt_info_vld, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + dtu_rtu_async_halt_req, + dtu_rtu_pending_tval, + dtu_rtu_sync_halt_req, + ebreak_action, + forever_cpuclk, + fpu_dtu_debug_info, + iahbl_dtu_debug_info, + icount_enable, + idu_dtu_debug_info, + idu_dtu_fpr_info, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_debug_info, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ifu_dtu_exe_data0, + ifu_dtu_exe_data1, + int_mask, + iu_dtu_debug_info, + latest_pc, + ldst_addr_mcontrol, + ldst_data_mcontrol, + low_power_wakeup, + lsu_dtu_debug_info, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + lsu_dtu_ldst_type, + lsu_dtu_mem_access_size, + pad_yy_icg_scan_en, + rtu_dtu_debug_info, + rtu_dtu_dpc, + rtu_dtu_halt_ack, + rtu_dtu_nmi_pending, + rtu_dtu_pending_ack, + rtu_dtu_retire_chgflw, + rtu_dtu_retire_halt_info, + rtu_dtu_retire_mret, + rtu_dtu_retire_next_pc, + rtu_dtu_retire_vld, + rtu_dtu_tval, + rtu_yy_xx_dbgon, + sahbl_dtu_debug_info, + tdt_dm_wdata, + tdt_dm_wr_flg, + tdt_dm_wr_vld +); + +// &Ports; @24 +input async_halt_req_wakeup; +input [3 :0] bmu_dtu_debug_info; +input [11:0] cp0_dtu_addr; +input [5 :0] cp0_dtu_debug_info; +input cp0_dtu_icg_en; +input cp0_dtu_mexpt_vld; +input cp0_dtu_pcfifo_frz; +input cp0_dtu_rreg; +input [31:0] cp0_dtu_wdata; +input cp0_dtu_wreg; +input cp0_yy_clk_en; +input [1 :0] cp0_yy_priv_mode; +input cpurst_b; +input [10:0] dahbl_dtu_debug_info; +input dtu_rtu_async_halt_req; +input dtu_rtu_sync_halt_req; +input forever_cpuclk; +input [7 :0] fpu_dtu_debug_info; +input [10:0] iahbl_dtu_debug_info; +input [21:0] idu_dtu_debug_info; +input [95:0] idu_dtu_fpr_info; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [26:0] ifu_dtu_debug_info; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input [31:0] ifu_dtu_exe_data0; +input [31:0] ifu_dtu_exe_data1; +input [8 :0] iu_dtu_debug_info; +input [78:0] lsu_dtu_debug_info; +input [14:0] lsu_dtu_halt_info; +input lsu_dtu_last_check; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input [1 :0] lsu_dtu_ldst_type; +input [1 :0] lsu_dtu_mem_access_size; +input pad_yy_icg_scan_en; +input [13:0] rtu_dtu_debug_info; +input [31:0] rtu_dtu_dpc; +input rtu_dtu_halt_ack; +input rtu_dtu_nmi_pending; +input rtu_dtu_pending_ack; +input rtu_dtu_retire_chgflw; +input [14:0] rtu_dtu_retire_halt_info; +input rtu_dtu_retire_mret; +input [31:0] rtu_dtu_retire_next_pc; +input rtu_dtu_retire_vld; +input [31:0] rtu_dtu_tval; +input rtu_yy_xx_dbgon; +input [10:0] sahbl_dtu_debug_info; +input [31:0] tdt_dm_wdata; +input [1 :0] tdt_dm_wr_flg; +input tdt_dm_wr_vld; +output dcsr_mprven; +output [1 :0] dcsr_prv; +output dcsr_step; +output dcsr_stopcount; +output [31:0] dpc; +output [31:0] dscratch0; +output [31:0] dtu_cp0_rdata; +output [14:0] dtu_ifu_halt_info0; +output [14:0] dtu_ifu_halt_info1; +output dtu_ifu_halt_info_vld; +output [14:0] dtu_lsu_halt_info; +output dtu_lsu_halt_info_vld; +output [31:0] dtu_rtu_pending_tval; +output ebreak_action; +output icount_enable; +output int_mask; +output [31:0] latest_pc; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output low_power_wakeup; + +// &Regs; @25 +reg [2 :0] dcsr_cause; +reg dcsr_ebreakm; +reg dcsr_ebreaku; +reg dcsr_mprven; +reg [1 :0] dcsr_prv; +reg dcsr_step; +reg dcsr_stepie; +reg dcsr_stopcount; +reg [31:0] dpc; +reg [31:0] dscratch0; +reg [31:0] dscratch1; +reg [31:0] dtu_cp0_rdata; +reg [3 :0] haltcause; + +// &Wires; @26 +wire async_halt_req_wakeup; +wire [3 :0] bmu_dtu_debug_info; +wire [11:0] cp0_dtu_addr; +wire [5 :0] cp0_dtu_debug_info; +wire cp0_dtu_icg_en; +wire cp0_dtu_mexpt_vld; +wire cp0_dtu_pcfifo_frz; +wire cp0_dtu_rreg; +wire [31:0] cp0_dtu_wdata; +wire cp0_dtu_wreg; +wire cp0_write_dcsr; +wire cp0_write_dpc; +wire cp0_write_dscratch0; +wire cp0_write_dscratch1; +wire cp0_yy_clk_en; +wire [1 :0] cp0_yy_priv_mode; +wire cpurst_b; +wire [10:0] dahbl_dtu_debug_info; +wire [31:0] dbgfifo_regs_data; +wire [31:0] dcsr; +wire dcsr_dpc_haltcause_clk; +wire dcsr_dpc_haltcause_clk_en; +wire dcsr_nmip; +wire [3 :0] dcsr_xdebugver; +wire dscratch01_clk; +wire dscratch01_clk_en; +wire [3 :0] dtu_cause; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire dtu_ifu_halt_info_vld; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire dtu_rtu_async_halt_req; +wire [31:0] dtu_rtu_pending_tval; +wire dtu_rtu_sync_halt_req; +wire ebreak_action; +wire forever_cpuclk; +wire [7 :0] fpu_dtu_debug_info; +wire [10:0] iahbl_dtu_debug_info; +wire icount_enable; +wire [21:0] idu_dtu_debug_info; +wire [95:0] idu_dtu_fpr_info; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [26:0] ifu_dtu_debug_info; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire [31:0] ifu_dtu_exe_data0; +wire [31:0] ifu_dtu_exe_data1; +wire int_mask; +wire [8 :0] iu_dtu_debug_info; +wire [31:0] latest_pc; +wire ldst_addr_mcontrol; +wire ldst_data_mcontrol; +wire low_power_wakeup; +wire [78:0] lsu_dtu_debug_info; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [1 :0] lsu_dtu_ldst_type; +wire [1 :0] lsu_dtu_mem_access_size; +wire [31:0] mcontext; +wire pad_yy_icg_scan_en; +wire [31:0] pcfifo_regs_data; +wire pending_halt; +wire [13:0] rtu_dtu_debug_info; +wire [31:0] rtu_dtu_dpc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_nmi_pending; +wire rtu_dtu_pending_ack; +wire rtu_dtu_retire_chgflw; +wire [14:0] rtu_dtu_retire_halt_info; +wire rtu_dtu_retire_mret; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; +wire [31:0] rtu_dtu_tval; +wire rtu_yy_xx_dbgon; +wire [10:0] sahbl_dtu_debug_info; +wire [31:0] tcontrol; +wire [31:0] tdata1; +wire [31:0] tdata2; +wire [31:0] tdata3; +wire [31:0] tdt_dm_wdata; +wire [1 :0] tdt_dm_wr_flg; +wire tdt_dm_wr_vld; +wire tdt_dm_write_dscratch0; +wire [31:0] tinfo; +wire [31:0] tselect; +wire updata_tval; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; + +//dcsr parameter +parameter PRV = 1; +parameter STEP = 2; +parameter MPRVEN = 4; +//parameter DCSR_CAUSE = 8; +//parameter STOPTIME = 9; +parameter STOPCOUNT = 10; +parameter STEPIE = 11; +parameter EBREAKU = 12; +parameter EBREAKS = 13; +parameter EBREAKM = 15; + +//=============================================================== +//Core Debug Register +// +//dcsr, dpc, dscratch0, dscratch1, hatlcause, dbginfo, pcfifo +//=============================================================== + +//core csr and write req +assign cp0_write_dcsr = cp0_dtu_wreg && cp0_dtu_addr[11:0] == 12'h7b0 && rtu_yy_xx_dbgon; +assign cp0_write_dpc = cp0_dtu_wreg && cp0_dtu_addr[11:0] == 12'h7b1 && rtu_yy_xx_dbgon; +assign cp0_write_dscratch0 = cp0_dtu_wreg && cp0_dtu_addr[11:0] == 12'h7b2 && rtu_yy_xx_dbgon; +assign cp0_write_dscratch1 = cp0_dtu_wreg && cp0_dtu_addr[11:0] == 12'h7b3 && rtu_yy_xx_dbgon; +assign tdt_dm_write_dscratch0 = tdt_dm_wr_vld && tdt_dm_wr_flg[1:0] == 2'b01 && rtu_yy_xx_dbgon; + +//=============================================================== +// Define the DCSR +//=============================================================== +assign dcsr_nmip = rtu_dtu_nmi_pending;//nmip +assign dcsr_xdebugver[3:0] = 4'b0100;//xdebugver + +always @(posedge dcsr_dpc_haltcause_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + dcsr_step <= 1'b0; + dcsr_mprven <= 1'b0; + dcsr_stopcount <= 1'b0; + dcsr_stepie <= 1'b0; + dcsr_ebreaku <= 1'b0; + //dcsr_ebreaks <= 1'b0; + dcsr_ebreakm <= 1'b0; + end + else if(cp0_write_dcsr) + begin + dcsr_step <= cp0_dtu_wdata[STEP]; + dcsr_mprven <= cp0_dtu_wdata[MPRVEN]; + dcsr_stopcount <= cp0_dtu_wdata[STOPCOUNT]; + dcsr_stepie <= cp0_dtu_wdata[STEPIE]; + dcsr_ebreaku <= cp0_dtu_wdata[EBREAKU]; + //dcsr_ebreaks <= cp0_dtu_wdata[EBREAKS]; + dcsr_ebreakm <= cp0_dtu_wdata[EBREAKM]; + end +end +// &Force("output","dcsr_mprven"); @85 +// &Force("output","dcsr_stopcount"); @86 +// &Force("output","dcsr_step"); @87 + +always @(posedge dcsr_dpc_haltcause_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dcsr_prv[1:0] <= 2'b0; + else if(rtu_dtu_halt_ack) + dcsr_prv[1:0] <= cp0_yy_priv_mode[1:0]; + else if(cp0_write_dcsr) + dcsr_prv[1:0] <= cp0_dtu_wdata[PRV:0]; +end +// &Force("output","dcsr_prv"); @98 + +always @(posedge dcsr_dpc_haltcause_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dcsr_cause[2:0] <= 3'b0; + else if(rtu_dtu_halt_ack) + dcsr_cause[2:0] <= dtu_cause[2:0]; +end + +assign dcsr[31:0] ={dcsr_xdebugver[3:0],{12{1'b0}},dcsr_ebreakm,1'b0,1'b0,dcsr_ebreaku, + dcsr_stepie,dcsr_stopcount,1'b0,dcsr_cause[2:0],1'b0,dcsr_mprven, + dcsr_nmip,dcsr_step,dcsr_prv[1:0]}; +//generate int_mask and ebreak_action for rtu +assign int_mask = dcsr_step && !dcsr_stepie; +assign ebreak_action = cp0_yy_priv_mode[1:0] == 2'b00 && dcsr_ebreaku || + //cp0_yy_priv_mode[1:0] == 2'b01 && dcsr_ebreaks || + cp0_yy_priv_mode[1:0] == 2'b11 && dcsr_ebreakm; + +//=============================================================== +// Define the DPC +//=============================================================== +always @(posedge dcsr_dpc_haltcause_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dpc[XLEN-1:0] <= {XLEN{1'b0}}; + else if(cp0_write_dpc) + dpc[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; + else if(rtu_dtu_halt_ack) + dpc[XLEN-1:0] <= rtu_dtu_dpc[XLEN-1:0]; +end +// &Force("output","dpc"); @129 + +//=============================================================== +// Define the DSCRATCH0 +//=============================================================== +always @(posedge dscratch01_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dscratch0[XLEN-1:0] <= {XLEN{1'b0}}; + else if(updata_tval) + dscratch0[XLEN-1:0] <= rtu_dtu_tval[XLEN-1:0]; + else if(cp0_write_dscratch0) + dscratch0[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; + else if(tdt_dm_write_dscratch0) + dscratch0[XLEN-1:0] <= tdt_dm_wdata[XLEN-1:0]; +end +// &Force("output","dscratch0"); @145 +assign dtu_rtu_pending_tval[XLEN-1:0] = dscratch0[XLEN-1:0]; +//=============================================================== +// Define the DSCRATCH1 +//=============================================================== +always @(posedge dscratch01_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dscratch1[XLEN-1:0] <= {XLEN{1'b0}}; + else if(cp0_write_dscratch1) + dscratch1[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; +end + +//=============================================================== +// Define the HALTCAUSE +//=============================================================== +always @(posedge dcsr_dpc_haltcause_clk or negedge cpurst_b) +begin + if(!cpurst_b) + haltcause[3:0] <= {4{1'b0}}; + else if(rtu_dtu_halt_ack) + haltcause[3:0] <= dtu_cause[3:0]; +end + +//=============================================================== +// Define the pcfifo +//=============================================================== +// &Instance("pa_dtu_pcfifo"); @173 +pa_dtu_pcfifo x_pa_dtu_pcfifo ( + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_pcfifo_frz (cp0_dtu_pcfifo_frz ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .latest_pc (latest_pc ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcfifo_regs_data (pcfifo_regs_data ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_retire_chgflw (rtu_dtu_retire_chgflw ), + .rtu_dtu_retire_next_pc (rtu_dtu_retire_next_pc), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ) +); + +// &Force("input","cp0_dtu_pcfifo_frz"); @175 +// &Force("input","rtu_dtu_retire_chgflw"); @176 +// &Force("input","rtu_dtu_retire_next_pc");&Force("bus","rtu_dtu_retire_next_pc",`PA_WIDTH-1,0); @177 + +//=============================================================== +// Define the dbginfo +//=============================================================== +// &Instance("pa_dtu_dbginfo"); @184 +pa_dtu_dbginfo x_pa_dtu_dbginfo ( + .bmu_dtu_debug_info (bmu_dtu_debug_info ), + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_debug_info (cp0_dtu_debug_info ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_rreg (cp0_dtu_rreg ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dahbl_dtu_debug_info (dahbl_dtu_debug_info ), + .dbgfifo_regs_data (dbgfifo_regs_data ), + .dtu_rtu_async_halt_req (dtu_rtu_async_halt_req), + .forever_cpuclk (forever_cpuclk ), + .fpu_dtu_debug_info (fpu_dtu_debug_info ), + .iahbl_dtu_debug_info (iahbl_dtu_debug_info ), + .idu_dtu_debug_info (idu_dtu_debug_info ), + .idu_dtu_fpr_info (idu_dtu_fpr_info ), + .ifu_dtu_debug_info (ifu_dtu_debug_info ), + .iu_dtu_debug_info (iu_dtu_debug_info ), + .lsu_dtu_debug_info (lsu_dtu_debug_info ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_dtu_debug_info (rtu_dtu_debug_info ), + .sahbl_dtu_debug_info (sahbl_dtu_debug_info ) +); + +// &Force("input","pahbl_dtu_debug_info");&Force("bus","pahbl_dtu_debug_info",6,0); @187 +// &Force("input","biu_dtu_debug_info");&Force("bus","biu_dtu_debug_info",9,0); @188 +// &Force("input","sahbl_dtu_debug_info");&Force("bus","sahbl_dtu_debug_info",10,0); @190 +// &Force("input","dahbl_dtu_debug_info");&Force("bus","dahbl_dtu_debug_info",10,0); @191 +// &Force("input","iahbl_dtu_debug_info");&Force("bus","iahbl_dtu_debug_info",10,0); @192 +// &Force("input","bmu_dtu_debug_info");&Force("bus","bmu_dtu_debug_info",3,0); @193 +// &Force("input","idu_dtu_fpr_info");&Force("bus","idu_dtu_fpr_info",95,0); @195 +// &Force("input","fpu_dtu_debug_info");&Force("bus","fpu_dtu_debug_info",7,0); @197 +// &Force("input","cp0_dtu_debug_info");&Force("bus","cp0_dtu_debug_info",5,0); @200 +// &Force("input","rtu_dtu_debug_info");&Force("bus","rtu_dtu_debug_info",13,0); @201 +// &Force("input","iu_dtu_debug_info");&Force("bus","iu_dtu_debug_info",8,0); @202 +// &Force("input","lsu_dtu_debug_info");&Force("bus","lsu_dtu_debug_info",78,0); @203 +// &Force("input","idu_dtu_debug_info");&Force("bus","idu_dtu_debug_info",21,0); @204 +// &Force("input","ifu_dtu_debug_info");&Force("bus","ifu_dtu_debug_info",26,0); @205 +//csr and read req + +//=============================================================== +// Define the Trigger Module +//=============================================================== +// &Instance("pa_dtu_trigger_module"); @212 +pa_dtu_trigger_module x_pa_dtu_trigger_module ( + .cp0_dtu_addr (cp0_dtu_addr ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_mexpt_vld (cp0_dtu_mexpt_vld ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_dtu_wreg (cp0_dtu_wreg ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_priv_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .dtu_cause (dtu_cause ), + .dtu_ifu_halt_info0 (dtu_ifu_halt_info0 ), + .dtu_ifu_halt_info1 (dtu_ifu_halt_info1 ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .forever_cpuclk (forever_cpuclk ), + .icount_enable (icount_enable ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ifu_dtu_exe_data0 (ifu_dtu_exe_data0 ), + .ifu_dtu_exe_data1 (ifu_dtu_exe_data1 ), + .ldst_addr_mcontrol (ldst_addr_mcontrol ), + .ldst_data_mcontrol (ldst_data_mcontrol ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .lsu_dtu_ldst_type (lsu_dtu_ldst_type ), + .lsu_dtu_mem_access_size (lsu_dtu_mem_access_size ), + .mcontext (mcontext ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pending_halt (pending_halt ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_pending_ack (rtu_dtu_pending_ack ), + .rtu_dtu_retire_halt_info (rtu_dtu_retire_halt_info), + .rtu_dtu_retire_mret (rtu_dtu_retire_mret ), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .tcontrol (tcontrol ), + .tdata1 (tdata1 ), + .tdata2 (tdata2 ), + .tdata3 (tdata3 ), + .tinfo (tinfo ), + .tselect (tselect ), + .updata_tval (updata_tval ) +); + + +// &CombBeg; @214 +always @( dpc[31:0] + or tdata1[31:0] + or tinfo[31:0] + or dbgfifo_regs_data[31:0] + or dcsr[31:0] + or tdata2[31:0] + or cp0_dtu_addr[11:0] + or haltcause[3:0] + or dscratch0[31:0] + or tselect[31:0] + or pcfifo_regs_data[31:0] + or tdata3[31:0] + or tcontrol[31:0] + or dscratch1[31:0] + or mcontext[31:0]) +begin +case(cp0_dtu_addr[11:0]) + 12'h7a0: + dtu_cp0_rdata[XLEN-1:0] = tselect[XLEN-1:0]; + 12'h7a1: + dtu_cp0_rdata[XLEN-1:0] = tdata1[XLEN-1:0]; + 12'h7a2: + dtu_cp0_rdata[XLEN-1:0] = tdata2[XLEN-1:0]; + 12'h7a3: + dtu_cp0_rdata[XLEN-1:0] = tdata3[XLEN-1:0]; + 12'h7a4: + dtu_cp0_rdata[XLEN-1:0] = tinfo[XLEN-1:0]; + 12'h7a5: + dtu_cp0_rdata[XLEN-1:0] = tcontrol[XLEN-1:0]; + 12'h7a8: + dtu_cp0_rdata[XLEN-1:0] = mcontext[XLEN-1:0]; + + 12'h7b0: + dtu_cp0_rdata[XLEN-1:0] = dcsr[31:0]; + 12'h7b1: + dtu_cp0_rdata[XLEN-1:0] = dpc[XLEN-1:0]; + 12'h7b2: + dtu_cp0_rdata[XLEN-1:0] = dscratch0[XLEN-1:0]; + 12'h7b3: + dtu_cp0_rdata[XLEN-1:0] = dscratch1[XLEN-1:0]; + 12'hfe0: + dtu_cp0_rdata[XLEN-1:0] = {{XLEN-4{1'b0}},haltcause[3:0]}; + + 12'hfe1: + dtu_cp0_rdata[XLEN-1:0] = dbgfifo_regs_data[XLEN-1:0]; + + 12'hfe2: + dtu_cp0_rdata[XLEN-1:0] = pcfifo_regs_data[XLEN-1:0]; + + default: + dtu_cp0_rdata[XLEN-1:0] = {XLEN{1'bx}}; +endcase +// &CombEnd; @295 +end + +//low power wakeup +assign low_power_wakeup = dtu_rtu_sync_halt_req || + async_halt_req_wakeup || + dcsr_step || + pending_halt; + +//========================================================== +// gate clk +//========================================================== +//make dcsr, dpc, haltcause a gated clk cell +assign dcsr_dpc_haltcause_clk_en = rtu_dtu_halt_ack || + cp0_write_dcsr || + cp0_write_dpc; +// &Instance("gated_clk_cell", "x_dcsr_dpc_haltcause_reg_gated_clk"); @310 +gated_clk_cell x_dcsr_dpc_haltcause_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dcsr_dpc_haltcause_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (dcsr_dpc_haltcause_clk_en), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @311 +// .external_en (1'b0), @312 +// .global_en (cp0_yy_clk_en), @313 +// .module_en (cp0_dtu_icg_en), @314 +// .local_en (dcsr_dpc_haltcause_clk_en), @315 +// //.local_en (1'b1), @316 +// .clk_out (dcsr_dpc_haltcause_clk)); @317 + +//make dscratch0, dscratch1 a gated clk cell +assign dscratch01_clk_en = cp0_write_dscratch0 || tdt_dm_write_dscratch0 || updata_tval || + cp0_write_dscratch1; +// &Instance("gated_clk_cell", "x_dscratch01_reg_gated_clk"); @322 +gated_clk_cell x_dscratch01_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dscratch01_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (dscratch01_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @323 +// .external_en (1'b0), @324 +// .global_en (cp0_yy_clk_en), @325 +// .module_en (cp0_dtu_icg_en), @326 +// .local_en (dscratch01_clk_en), @327 +// //.local_en (1'b1), @328 +// .clk_out (dscratch01_clk)); @329 + + +// &ModuleEnd; @338 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_dbginfo.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_dbginfo.v new file mode 100644 index 0000000000000000000000000000000000000000..fbbda8f7b19837d05e40a932e104640239d44e2d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_dbginfo.v @@ -0,0 +1,207 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_dbginfo( + bmu_dtu_debug_info, + cp0_dtu_addr, + cp0_dtu_debug_info, + cp0_dtu_icg_en, + cp0_dtu_rreg, + cp0_yy_clk_en, + cpurst_b, + dahbl_dtu_debug_info, + dbgfifo_regs_data, + dtu_rtu_async_halt_req, + forever_cpuclk, + fpu_dtu_debug_info, + iahbl_dtu_debug_info, + idu_dtu_debug_info, + idu_dtu_fpr_info, + ifu_dtu_debug_info, + iu_dtu_debug_info, + lsu_dtu_debug_info, + pad_yy_icg_scan_en, + rtu_dtu_debug_info, + sahbl_dtu_debug_info +); + +// &Ports; @24 +input [3 :0] bmu_dtu_debug_info; +input [11 :0] cp0_dtu_addr; +input [5 :0] cp0_dtu_debug_info; +input cp0_dtu_icg_en; +input cp0_dtu_rreg; +input cp0_yy_clk_en; +input cpurst_b; +input [10 :0] dahbl_dtu_debug_info; +input dtu_rtu_async_halt_req; +input forever_cpuclk; +input [7 :0] fpu_dtu_debug_info; +input [10 :0] iahbl_dtu_debug_info; +input [21 :0] idu_dtu_debug_info; +input [95 :0] idu_dtu_fpr_info; +input [26 :0] ifu_dtu_debug_info; +input [8 :0] iu_dtu_debug_info; +input [78 :0] lsu_dtu_debug_info; +input pad_yy_icg_scan_en; +input [13 :0] rtu_dtu_debug_info; +input [10 :0] sahbl_dtu_debug_info; +output [31 :0] dbgfifo_regs_data; + +// &Regs; @25 +reg [3 :0] dbg_rptr; +reg [297:0] xx_dbg_info_reg; + +// &Wires; @26 +wire [3 :0] bmu_dtu_debug_info; +wire [11 :0] cp0_dtu_addr; +wire [5 :0] cp0_dtu_debug_info; +wire cp0_dtu_icg_en; +wire cp0_dtu_rreg; +wire cp0_read_dbginfo; +wire cp0_yy_clk_en; +wire cpurst_b; +wire [10 :0] dahbl_dtu_debug_info; +wire dbg_info_record; +wire [31 :0] dbgfifo_regs_data; +wire dbginfo_clk; +wire dbginfo_clk_en; +wire [31 :0] dbginfo_out; +wire dtu_rtu_async_halt_req; +wire forever_cpuclk; +wire [7 :0] fpu_dtu_debug_info; +wire [10 :0] iahbl_dtu_debug_info; +wire [21 :0] idu_dtu_debug_info; +wire [95 :0] idu_dtu_fpr_info; +wire [26 :0] ifu_dtu_debug_info; +wire [8 :0] iu_dtu_debug_info; +wire [78 :0] lsu_dtu_debug_info; +wire pad_yy_icg_scan_en; +wire [13 :0] rtu_dtu_debug_info; +wire [10 :0] sahbl_dtu_debug_info; +wire [297:0] xx_dbg_info; +wire [307:0] xx_dbg_info_reg_padding; + + +parameter DBG_INFO_WIDTH = `TDT_DBGINFO_WIDTH; +parameter DBG_WIDTH = `TDT_DM_CORE_MAX_XLEN; +parameter DBGINFO_RPTR_WIDTH = 4; +parameter DBGINFO_READ_WIDTH = 28; +parameter DBGINFO_DEPTH = `TDT_DBGINFO_DEPTH; + +//========================================================== +// DBGINFO FIFO Read +//========================================================== +//csky vperl_off +wire [DBGINFO_READ_WIDTH -1:0] dbginfo_reg[DBGINFO_DEPTH-1:0]; + +genvar i; + +generate + for (i = 0; i < DBGINFO_DEPTH; i = i+1) + begin: DBG_FIFO + assign dbginfo_reg[i][DBGINFO_READ_WIDTH -1:0] = xx_dbg_info_reg_padding[DBGINFO_READ_WIDTH *i+DBGINFO_READ_WIDTH-1:DBGINFO_READ_WIDTH *i]; + end +endgenerate +//vperl_on + +assign dbginfo_out[DBG_WIDTH-1:0] = {dbginfo_reg[dbg_rptr[DBGINFO_RPTR_WIDTH-1:0]][DBGINFO_READ_WIDTH-1:0],dbg_rptr[DBGINFO_RPTR_WIDTH-1:0]}; + +//csky vperl_on +// &Force("nonport","dbginfo_out"); @53 +assign dbgfifo_regs_data[DBG_WIDTH -1:0] = dbginfo_out[DBG_WIDTH-1:0]; + +assign cp0_read_dbginfo = cp0_dtu_rreg && cp0_dtu_addr[11:0] == 12'hfe1; +//========================================================== +// DBGINFO FIFO Write +//========================================================== +assign dbg_info_record = dtu_rtu_async_halt_req; + + +assign xx_dbg_info[DBG_INFO_WIDTH-1:0] = { + idu_dtu_fpr_info[95:0], + fpu_dtu_debug_info[7:0], + cp0_dtu_debug_info[5:0], + rtu_dtu_debug_info[13:0], + iu_dtu_debug_info[8:0], + sahbl_dtu_debug_info[10:0], + dahbl_dtu_debug_info[10:0], + iahbl_dtu_debug_info[10:0], + bmu_dtu_debug_info[3:0], + lsu_dtu_debug_info[78:0], + idu_dtu_debug_info[21:0], + ifu_dtu_debug_info[26:0] +}; + + +always @ (posedge dbginfo_clk or negedge cpurst_b) +begin + if (!cpurst_b) + xx_dbg_info_reg[DBG_INFO_WIDTH-1:0] <= {DBG_INFO_WIDTH{1'b0}}; + else if (dbg_info_record) + xx_dbg_info_reg[DBG_INFO_WIDTH-1:0] <= xx_dbg_info[DBG_INFO_WIDTH-1:0]; +end + +assign xx_dbg_info_reg_padding[DBGINFO_READ_WIDTH *DBGINFO_DEPTH-1:0] = { + {(DBGINFO_READ_WIDTH *DBGINFO_DEPTH-DBG_INFO_WIDTH){1'b0}}, + xx_dbg_info_reg[DBG_INFO_WIDTH-1:0] + }; +// &Force("nonport", "xx_dbg_info_reg"); @111 +// &Force("nonport", "xx_dbg_info_reg_padding"); @112 + +//========================================================== +// DBGINFO FIFO Read Pointer +//========================================================== +always @ (posedge dbginfo_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dbg_rptr[DBGINFO_RPTR_WIDTH-1:0] <= {DBGINFO_RPTR_WIDTH{1'b0}}; + else if (cp0_read_dbginfo && dbg_rptr[DBGINFO_RPTR_WIDTH-1:0] == 4'd10) + dbg_rptr[DBGINFO_RPTR_WIDTH-1:0] <= {DBGINFO_RPTR_WIDTH{1'b0}}; + else if (cp0_read_dbginfo) + dbg_rptr[DBGINFO_RPTR_WIDTH-1:0] <= dbg_rptr[DBGINFO_RPTR_WIDTH-1:0] + 1'b1; +end + +//========================================================== +// gate clk +//========================================================== +assign dbginfo_clk_en = dtu_rtu_async_halt_req || + cp0_read_dbginfo; +// &Force("nonport","dbginfo_clk_en"); @136 + +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @138 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dbginfo_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (dbginfo_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @139 +// .external_en (1'b0), @140 +// .global_en (cp0_yy_clk_en), @141 +// .module_en (cp0_dtu_icg_en), @142 +// .local_en (dbginfo_clk_en), @143 +// //.local_en (1'b1), @144 +// .clk_out (dbginfo_clk)); @145 + +// &ModuleEnd; @147 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_m_iie_all.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_m_iie_all.v new file mode 100644 index 0000000000000000000000000000000000000000..1f3ac92341f6fd9001097693455d6e9de85a233b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_m_iie_all.v @@ -0,0 +1,925 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_m_iie_all( + cp0_dtu_icg_en, + cp0_dtu_mexpt_vld, + cp0_dtu_wdata, + cp0_write_mcontext, + cp0_write_tcontrol, + cp0_write_tdata1, + cp0_write_tdata2, + cp0_write_tdata3, + cp0_write_tselect, + cp0_yy_clk_en, + cpurst_b, + dtu_cause, + dtu_ifu_halt_info0, + dtu_ifu_halt_info1, + dtu_ifu_halt_info_vld, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + exe0_16bit, + exe0_32bit, + exe1_16bit, + exe1_32bit, + forever_cpuclk, + icount_enable, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ldst_16bit, + ldst_32bit, + ldst_8bit, + ldst_addr_mcontrol, + ldst_data_mcontrol, + load_addr_vld, + load_data_vld, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + m_mode, + mcontext, + pad_yy_icg_scan_en, + pending_halt, + rtu_dtu_halt_ack, + rtu_dtu_pending_ack, + rtu_dtu_retire_halt_info, + rtu_dtu_retire_mret, + rtu_dtu_retire_vld, + rtu_yy_xx_dbgon, + store_addr_vld, + store_data_vld, + tcontrol, + tdata1, + tdata2, + tdata3, + tinfo, + tselect, + u_mode, + updata_tval +); + +// &Ports; @24 +input cp0_dtu_icg_en; +input cp0_dtu_mexpt_vld; +input [31:0] cp0_dtu_wdata; +input cp0_write_mcontext; +input cp0_write_tcontrol; +input cp0_write_tdata1; +input cp0_write_tdata2; +input cp0_write_tdata3; +input cp0_write_tselect; +input cp0_yy_clk_en; +input cpurst_b; +input exe0_16bit; +input exe0_32bit; +input exe1_16bit; +input exe1_32bit; +input forever_cpuclk; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input ldst_16bit; +input ldst_32bit; +input ldst_8bit; +input load_addr_vld; +input load_data_vld; +input [14:0] lsu_dtu_halt_info; +input lsu_dtu_last_check; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input m_mode; +input pad_yy_icg_scan_en; +input rtu_dtu_halt_ack; +input rtu_dtu_pending_ack; +input [14:0] rtu_dtu_retire_halt_info; +input rtu_dtu_retire_mret; +input rtu_dtu_retire_vld; +input rtu_yy_xx_dbgon; +input store_addr_vld; +input store_data_vld; +input u_mode; +output [3 :0] dtu_cause; +output [14:0] dtu_ifu_halt_info0; +output [14:0] dtu_ifu_halt_info1; +output dtu_ifu_halt_info_vld; +output [14:0] dtu_lsu_halt_info; +output dtu_lsu_halt_info_vld; +output icount_enable; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output [31:0] mcontext; +output pending_halt; +output [31:0] tcontrol; +output [31:0] tdata1; +output [31:0] tdata2; +output [31:0] tdata3; +output [31:0] tinfo; +output [31:0] tselect; +output updata_tval; + +// &Regs; @25 +reg [3 :0] dtu_cause; +reg [5 :0] mcontext_lowbits; +reg mpte_reg; +reg mte_reg; +reg pending_halt; +reg record_action01_reg; +reg record_action_reg; +reg [3 :0] record_cause_reg; +reg [2 :0] record_hit_reg; +reg record_ldst_reg; +reg retire_action01; +reg [31:0] tdata1; +reg [31:0] tdata2; +reg [31:0] tdata3; +reg [31:0] tinfo; +reg [2 :0] triggers_hit; +reg [3 :0] tselect_lowbits; +reg [9 :0] tselect_wr_en; + +// &Wires; @26 +wire [2 :0] action0_match_trigger; +wire [2 :0] action0_mcontrol; +wire [2 :0] action0_triggers; +wire [2 :0] action1_match_trigger; +wire [2 :0] action1_mcontrol; +wire [2 :0] action1_triggers; +wire clear_action01_reg; +wire clear_record; +wire cp0_dtu_icg_en; +wire cp0_dtu_mexpt_vld; +wire [31:0] cp0_dtu_wdata; +wire cp0_write_mcontext; +wire cp0_write_tcontrol; +wire cp0_write_tdata1; +wire cp0_write_tdata2; +wire cp0_write_tdata3; +wire cp0_write_tselect; +wire cp0_yy_clk_en; +wire cpurst_b; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire dtu_ifu_halt_info_vld; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire exe0_16bit; +wire exe0_32bit; +wire exe1_16bit; +wire exe1_32bit; +wire forever_cpuclk; +wire generate_pending_halt; +wire generate_retire_action01; +wire generate_timing0; +wire give_action01_halt_info; +wire icount_enable; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire iie_pending_halt; +wire ldst_16bit; +wire ldst_32bit; +wire ldst_8bit; +wire ldst_addr_mcontrol; +wire ldst_data_mcontrol; +wire load_addr_vld; +wire load_data_vld; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [31:0] m0_tdata1; +wire [31:0] m0_tdata2; +wire [31:0] m0_tdata3; +wire [31:0] m0_tinfo; +wire [31:0] m1_tdata1; +wire [31:0] m1_tdata2; +wire [31:0] m1_tdata3; +wire [31:0] m1_tinfo; +wire [31:0] m2_tdata1; +wire [31:0] m2_tdata2; +wire [31:0] m2_tdata3; +wire [31:0] m2_tinfo; +wire [31:0] m3_tdata1; +wire [31:0] m3_tdata2; +wire [31:0] m3_tdata3; +wire [31:0] m3_tinfo; +wire [31:0] m4_tdata1; +wire [31:0] m4_tdata2; +wire [31:0] m4_tdata3; +wire [31:0] m4_tinfo; +wire [31:0] m5_tdata1; +wire [31:0] m5_tdata2; +wire [31:0] m5_tdata3; +wire [31:0] m5_tinfo; +wire [31:0] m6_tdata1; +wire [31:0] m6_tdata2; +wire [31:0] m6_tdata3; +wire [31:0] m6_tinfo; +wire [31:0] m7_tdata1; +wire [31:0] m7_tdata2; +wire [31:0] m7_tdata3; +wire [31:0] m7_tinfo; +wire m_iie_clk; +wire m_iie_clk_en; +wire m_mode; +wire [31:0] mcontext; +wire [14:0] mcontrol_halt_info0; +wire [14:0] mcontrol_halt_info1; +wire [2 :0] mcontrol_hit; +wire other_pending_halt; +wire pad_yy_icg_scan_en; +wire pending_halt_action; +wire [2 :0] pending_halt_hit; +wire penging_halt_action01; +wire record_aciton01; +wire record_action; +wire [3 :0] record_cause; +wire [14:0] record_halt_info; +wire [2 :0] record_hit; +wire record_ldst; +wire record_match; +wire record_pending_halt; +wire [3 :0] rtu_cause; +wire rtu_dtu_halt_ack; +wire rtu_dtu_pending_ack; +wire [14:0] rtu_dtu_retire_halt_info; +wire rtu_dtu_retire_mret; +wire rtu_dtu_retire_vld; +wire rtu_pending_ack; +wire rtu_pending_halt; +wire [14:0] rtu_retire_halt_info; +wire rtu_yy_xx_dbgon; +wire store_addr_vld; +wire store_data_vld; +wire [31:0] tcontrol; +wire timing0_mcontrol_match; +wire [2 :0] triggers_match; +wire [31:0] tselect; +wire u_mode; +wire updata_tval; +wire use_record_halt_info; +wire wdata_bigger_than_trigger_num; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; + +parameter TRIGGER_NUM = `MCONTROL_NUM + `IIE_NUM - 4'd1; + +//tcontrol parameter +parameter MPTE = 7; +parameter MTE = 3; +//========================================================= +// tselect write +//========================================================= +//tselect write. When wdata > TRIGGER_NUM, write TRIGGER_NUM to tselsect. + +assign wdata_bigger_than_trigger_num = cp0_dtu_wdata[3:0] >= TRIGGER_NUM || (|cp0_dtu_wdata[XLEN-1:4]); + +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tselect_lowbits[3:0] <= 4'b0; + else if(cp0_write_tselect && wdata_bigger_than_trigger_num) + tselect_lowbits[3:0] <= TRIGGER_NUM; + else if(cp0_write_tselect && !wdata_bigger_than_trigger_num) + tselect_lowbits[3:0] <= cp0_dtu_wdata[3:0]; +end +assign tselect[XLEN-1:0] = {{XLEN-4{1'b0}},tselect_lowbits[3:0]}; +// &Force("output","tselect");&Force("bus","tselect",XLEN-1,0); @69 + +//select trigger +// &CombBeg; @72 +always @( tselect[3:0]) +begin +case(tselect[3:0]) + 4'b0000:tselect_wr_en[9:0] = 10'b0000000001; + 4'b0001:tselect_wr_en[9:0] = 10'b0000000010; + 4'b0010:tselect_wr_en[9:0] = 10'b0000000100; + 4'b0011:tselect_wr_en[9:0] = 10'b0000001000; + 4'b0100:tselect_wr_en[9:0] = 10'b0000010000; + 4'b0101:tselect_wr_en[9:0] = 10'b0000100000; + 4'b0110:tselect_wr_en[9:0] = 10'b0001000000; + 4'b0111:tselect_wr_en[9:0] = 10'b0010000000; + 4'b1000:tselect_wr_en[9:0] = 10'b0100000000; + 4'b1001:tselect_wr_en[9:0] = 10'b1000000000; + default:tselect_wr_en[9:0] = {10{1'bx}}; +endcase +// &CombEnd; @86 +end + +//========================================================= +// trigger csr read +//========================================================= +// &CombBeg; @91 +always @( tselect[3:0] + or m1_tinfo[31:0] + or m2_tinfo[31:0] + or m3_tdata1[31:0] + or m3_tdata2[31:0] + or m7_tinfo[31:0] + or m6_tdata3[31:0] + or m0_tinfo[31:0] + or m6_tdata2[31:0] + or m3_tdata3[31:0] + or m5_tinfo[31:0] + or m5_tdata1[31:0] + or m0_tdata1[31:0] + or m7_tdata1[31:0] + or m4_tdata1[31:0] + or m2_tdata1[31:0] + or m5_tdata2[31:0] + or m6_tinfo[31:0] + or m1_tdata3[31:0] + or m7_tdata3[31:0] + or m5_tdata3[31:0] + or m2_tdata2[31:0] + or m3_tinfo[31:0] + or m1_tdata1[31:0] + or m6_tdata1[31:0] + or m4_tdata2[31:0] + or m2_tdata3[31:0] + or m4_tinfo[31:0] + or m0_tdata2[31:0] + or m7_tdata2[31:0] + or m1_tdata2[31:0] + or m0_tdata3[31:0] + or m4_tdata3[31:0]) +begin +// &Force("nonport","m0_tdata1");&Force("nonport","m0_tdata2"); @125 +// &Force("nonport","m0_tdata3");&Force("nonport","m0_tinfo"); @126 +// &Force("nonport","m0_tdata1");&Force("nonport","m0_tdata2"); @143 +// &Force("nonport","m0_tdata3");&Force("nonport","m0_tinfo"); @144 +// &Force("nonport","m1_tdata1");&Force("nonport","m1_tdata2"); @145 +// &Force("nonport","m1_tdata3");&Force("nonport","m1_tinfo"); @146 + +// &Force("nonport","m1_tdata1");&Force("nonport","m1_tdata2"); @240 +// &Force("nonport","m1_tdata3");&Force("nonport","m1_tinfo"); @241 +// &Force("nonport","m1_tdata1");&Force("nonport","m1_tdata2"); @258 +// &Force("nonport","m1_tdata3");&Force("nonport","m1_tinfo"); @259 +// &Force("nonport","m2_tdata1");&Force("nonport","m2_tdata2"); @260 +// &Force("nonport","m2_tdata3");&Force("nonport","m2_tinfo"); @261 + +// &Force("nonport","m2_tdata1");&Force("nonport","m2_tdata2"); @355 +// &Force("nonport","m2_tdata3");&Force("nonport","m2_tinfo"); @356 +// &Force("nonport","m2_tdata1");&Force("nonport","m2_tdata2"); @373 +// &Force("nonport","m2_tdata3");&Force("nonport","m2_tinfo"); @374 +// &Force("nonport","m3_tdata1");&Force("nonport","m3_tdata2"); @375 +// &Force("nonport","m3_tdata3");&Force("nonport","m3_tinfo"); @376 + +case(tselect[3:0]) + 4'b0000: + begin + tdata1[XLEN-1:0] = m0_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m0_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m0_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m0_tinfo[XLEN-1:0]; + end + 4'b0001: + begin + tdata1[XLEN-1:0] = m1_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m1_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m1_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m1_tinfo[XLEN-1:0]; + end + 4'b0010: + begin + tdata1[XLEN-1:0] = m2_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m2_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m2_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m2_tinfo[XLEN-1:0]; + end + 4'b0011: + begin + tdata1[XLEN-1:0] = m3_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m3_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m3_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m3_tinfo[XLEN-1:0]; + end + 4'b0100: + begin + tdata1[XLEN-1:0] = m4_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m4_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m4_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m4_tinfo[XLEN-1:0]; + end +// &Force("nonport","m3_tdata1");&Force("nonport","m3_tdata2"); @470 +// &Force("nonport","m3_tdata3");&Force("nonport","m3_tinfo"); @471 +// &Force("nonport","m3_tdata1");&Force("nonport","m3_tdata2"); @488 +// &Force("nonport","m3_tdata3");&Force("nonport","m3_tinfo"); @489 +// &Force("nonport","m4_tdata1");&Force("nonport","m4_tdata2"); @490 +// &Force("nonport","m4_tdata3");&Force("nonport","m4_tinfo"); @491 + 4'b0101: + begin + tdata1[XLEN-1:0] = m5_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m5_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m5_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m5_tinfo[XLEN-1:0]; + end + 4'b0110: + begin + tdata1[XLEN-1:0] = m6_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m6_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m6_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m6_tinfo[XLEN-1:0]; + end + 4'b0111: + begin + tdata1[XLEN-1:0] = m7_tdata1[XLEN-1:0]; + tdata2[XLEN-1:0] = m7_tdata2[XLEN-1:0]; + tdata3[XLEN-1:0] = m7_tdata3[XLEN-1:0]; + tinfo[XLEN-1:0] = m7_tinfo[XLEN-1:0]; + end + default: + begin + tdata1[XLEN-1:0] = {XLEN{1'bx}}; + tdata2[XLEN-1:0] = {XLEN{1'bx}}; + tdata3[XLEN-1:0] = {XLEN{1'bx}}; + tinfo[XLEN-1:0] = {XLEN{1'bx}}; + end +endcase + +// &Force("nonport","m4_tdata1");&Force("nonport","m4_tdata2"); @585 +// &Force("nonport","m4_tdata3");&Force("nonport","m4_tinfo"); @586 +// &Force("nonport","m4_tdata1");&Force("nonport","m4_tdata2"); @603 +// &Force("nonport","m4_tdata3");&Force("nonport","m4_tinfo"); @604 +// &Force("nonport","m5_tdata1");&Force("nonport","m5_tdata2"); @605 +// &Force("nonport","m5_tdata3");&Force("nonport","m5_tinfo"); @606 + +// &Force("nonport","m5_tdata1");&Force("nonport","m5_tdata2"); @700 +// &Force("nonport","m5_tdata3");&Force("nonport","m5_tinfo"); @701 +// &Force("nonport","m5_tdata1");&Force("nonport","m5_tdata2"); @718 +// &Force("nonport","m5_tdata3");&Force("nonport","m5_tinfo"); @719 +// &Force("nonport","m6_tdata1");&Force("nonport","m6_tdata2"); @720 +// &Force("nonport","m6_tdata3");&Force("nonport","m6_tinfo"); @721 + +// &Force("nonport","m6_tdata1");&Force("nonport","m6_tdata2"); @815 +// &Force("nonport","m6_tdata3");&Force("nonport","m6_tinfo"); @816 +// &Force("nonport","m6_tdata1");&Force("nonport","m6_tdata2"); @833 +// &Force("nonport","m6_tdata3");&Force("nonport","m6_tinfo"); @834 +// &Force("nonport","m7_tdata1");&Force("nonport","m7_tdata2"); @835 +// &Force("nonport","m7_tdata3");&Force("nonport","m7_tinfo"); @836 +// &Force("nonport","m7_tdata1");&Force("nonport","m7_tdata2"); @915 +// &Force("nonport","m7_tdata3");&Force("nonport","m7_tinfo"); @916 +// &Force("nonport","m7_tdata1");&Force("nonport","m7_tdata2"); @933 +// &Force("nonport","m7_tdata3");&Force("nonport","m7_tinfo"); @934 + +// &CombEnd; @1038 +end +//========================================================= +// trigger instance +//========================================================= +//--------------mcontrol instance-------------------------- +// &Instance("pa_dtu_mcontrol_output_select"); @1043 +pa_dtu_mcontrol_output_select x_pa_dtu_mcontrol_output_select ( + .action0_mcontrol (action0_mcontrol ), + .action1_mcontrol (action1_mcontrol ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_write_tdata1 (cp0_write_tdata1 ), + .cp0_write_tdata2 (cp0_write_tdata2 ), + .cp0_write_tdata3 (cp0_write_tdata3 ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .exe0_16bit (exe0_16bit ), + .exe0_32bit (exe0_32bit ), + .exe1_16bit (exe1_16bit ), + .exe1_32bit (exe1_32bit ), + .forever_cpuclk (forever_cpuclk ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ldst_16bit (ldst_16bit ), + .ldst_32bit (ldst_32bit ), + .ldst_8bit (ldst_8bit ), + .ldst_addr_mcontrol (ldst_addr_mcontrol ), + .ldst_data_mcontrol (ldst_data_mcontrol ), + .load_addr_vld (load_addr_vld ), + .load_data_vld (load_data_vld ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .m0_tdata1 (m0_tdata1 ), + .m0_tdata2 (m0_tdata2 ), + .m0_tdata3 (m0_tdata3 ), + .m0_tinfo (m0_tinfo ), + .m1_tdata1 (m1_tdata1 ), + .m1_tdata2 (m1_tdata2 ), + .m1_tdata3 (m1_tdata3 ), + .m1_tinfo (m1_tinfo ), + .m2_tdata1 (m2_tdata1 ), + .m2_tdata2 (m2_tdata2 ), + .m2_tdata3 (m2_tdata3 ), + .m2_tinfo (m2_tinfo ), + .m3_tdata1 (m3_tdata1 ), + .m3_tdata2 (m3_tdata2 ), + .m3_tdata3 (m3_tdata3 ), + .m3_tinfo (m3_tinfo ), + .m4_tdata1 (m4_tdata1 ), + .m4_tdata2 (m4_tdata2 ), + .m4_tdata3 (m4_tdata3 ), + .m4_tinfo (m4_tinfo ), + .m5_tdata1 (m5_tdata1 ), + .m5_tdata2 (m5_tdata2 ), + .m5_tdata3 (m5_tdata3 ), + .m5_tinfo (m5_tinfo ), + .m6_tdata1 (m6_tdata1 ), + .m6_tdata2 (m6_tdata2 ), + .m6_tdata3 (m6_tdata3 ), + .m6_tinfo (m6_tinfo ), + .m7_tdata1 (m7_tdata1 ), + .m7_tdata2 (m7_tdata2 ), + .m7_tdata3 (m7_tdata3 ), + .m7_tinfo (m7_tinfo ), + .m_mode (m_mode ), + .mcontext (mcontext ), + .mcontrol_halt_info0 (mcontrol_halt_info0 ), + .mcontrol_halt_info1 (mcontrol_halt_info1 ), + .mcontrol_hit (mcontrol_hit ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .store_addr_vld (store_addr_vld ), + .store_data_vld (store_data_vld ), + .tcontrol (tcontrol ), + .tselect_wr_en (tselect_wr_en ), + .u_mode (u_mode ) +); + + +//--------------iie trigger instance-------------------------- +// &Instance("pa_dtu_iie_trigger","x_pa_dtu_iie_trigger_0"); @1047 +// &Connect( @1048 +// .trigger_selected(tselect_wr_en[`TDT_TM_MCONTROL_TRI_NUM]), @1049 +// .set_trigger_hit(iie_hit), @1050 +// .exception_codes_onehot(exception_codes_onehot), @1051 +// .icount_enable (iie0_icount_enable), @1052 +// .tdata1_action0 (iie0_tdata1_action0), @1053 +// .tdata1_action1 (iie0_tdata1_action1), @1054 +// .trigger_match (iie0_match) @1055 +// .tdata1 (iie0_tdata1), @1056 +// .tdata2 (iie0_tdata2), @1057 +// .tdata3 (iie0_tdata3), @1058 +// .tinfo (iie0_tinfo)); @1059 +// &Force("input","rtu_yy_xx_expt_vec");&Force("bus","rtu_yy_xx_expt_vec",11,0); @1072 +// &Force("input","cp0_dtu_int_id");&Force("bus","cp0_dtu_int_id",11,0); @1073 + +// &Instance("pa_dtu_iie_trigger","x_pa_dtu_iie_trigger_0"); @1077 +// &Connect( @1078 +// .trigger_selected(tselect_wr_en[`TDT_TM_MCONTROL_TRI_NUM]), @1079 +// .set_trigger_hit(iie_hit[0]), @1080 +// .exception_codes_onehot(exception_codes_onehot), @1081 +// .icount_enable (iie0_icount_enable), @1082 +// .tdata1_action0 (iie0_tdata1_action0), @1083 +// .tdata1_action1 (iie0_tdata1_action1), @1084 +// .trigger_match (iie0_match) @1085 +// .tdata1 (iie0_tdata1), @1086 +// .tdata2 (iie0_tdata2), @1087 +// .tdata3 (iie0_tdata3), @1088 +// .tinfo (iie0_tinfo)); @1089 +// &Instance("pa_dtu_iie_trigger","x_pa_dtu_iie_trigger_1"); @1091 +// &Connect( @1092 +// .trigger_selected(tselect_wr_en[`TDT_TM_MCONTROL_TRI_NUM + 1]), @1093 +// .set_trigger_hit(iie_hit[1]), @1094 +// .exception_codes_onehot(exception_codes_onehot), @1095 +// .icount_enable (iie1_icount_enable), @1096 +// .tdata1_action0 (iie1_tdata1_action0), @1097 +// .tdata1_action1 (iie1_tdata1_action1), @1098 +// .trigger_match (iie1_match) @1099 +// .tdata1 (iie1_tdata1), @1100 +// .tdata2 (iie1_tdata2), @1101 +// .tdata3 (iie1_tdata3), @1102 +// .tinfo (iie1_tinfo)); @1103 +// &Force("input","rtu_yy_xx_expt_vec");&Force("bus","rtu_yy_xx_expt_vec",11,0); @1115 +// &Force("input","cp0_dtu_int_id");&Force("bus","cp0_dtu_int_id",11,0); @1116 +//-------tcontrol,mcontext for triggers--------- +//write tcontrol +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + mte_reg <= 1'b0; + mpte_reg <= 1'b0; + end + else if(cp0_dtu_mexpt_vld && rtu_dtu_retire_mret && rtu_dtu_retire_vld) + begin + mte_reg <= 1'b0; + mpte_reg <= mpte_reg; + end + else if(cp0_dtu_mexpt_vld)//A trap into m mode is taken, set MPTE to MTE,set MTE to 0. + begin + mte_reg <= 1'b0; + mpte_reg <= mte_reg; + end + else if(rtu_dtu_retire_mret && rtu_dtu_retire_vld)//mret is executed, set MTE to MPTE. + begin + mte_reg <= mpte_reg; + mpte_reg <= mpte_reg; + end + else if(cp0_write_tcontrol) + begin + mte_reg <= cp0_dtu_wdata[MTE]; + mpte_reg <= cp0_dtu_wdata[MPTE]; + end +end +assign tcontrol[XLEN-1:0] = {{XLEN-8{1'b0}},mpte_reg,{3{1'b0}},mte_reg,{3{1'b0}}}; +// &Force("output","tcontrol");&Force("bus","tcontrol",XLEN-1,0); @1149 +//write mcontext +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + mcontext_lowbits[5:0] <= 6'b0; + else if(cp0_write_mcontext) + mcontext_lowbits[5:0] <= cp0_dtu_wdata[5:0]; +end +assign mcontext[XLEN-1:0] = {{XLEN-6{1'b0}},mcontext_lowbits[5:0]}; +// &Force("output","mcontext");&Force("bus","mcontext",XLEN-1,0); @1159 + +//========================================================= +// mcontrol hit info from rtu +//========================================================= +// &Force("input","rtu_dtu_retire_halt_info");&Force("bus","rtu_dtu_retire_halt_info",`TDT_HINFO_WIDTH-1,0); @1164 +assign rtu_retire_halt_info[`TDT_HINFO_WIDTH-1:0] = (rtu_dtu_retire_vld || rtu_dtu_halt_ack) ? + rtu_dtu_retire_halt_info[`TDT_HINFO_WIDTH-1:0] : + {`TDT_HINFO_WIDTH{1'b0}}; +assign timing0_mcontrol_match = rtu_retire_halt_info[`TDT_HINFO_MATCH] && + !rtu_retire_halt_info[`TDT_HINFO_CHAIN] && + !rtu_retire_halt_info[`TDT_HINFO_TIMING]; +assign rtu_pending_ack = rtu_dtu_pending_ack; +assign rtu_pending_halt = rtu_retire_halt_info[`TDT_HINFO_PENDING_HALT]; +assign generate_timing0 = rtu_dtu_halt_ack || timing0_mcontrol_match; + +assign triggers_match[`TDT_TM_TRIGGER_NUM-1:0] = + rtu_retire_halt_info[`TDT_HINFO_TRIGGER:`TDT_HINFO_TRIGGER-`TDT_TM_MCONTROL_TRI_NUM-`TDT_TM_OTHER_TRI_NUM+1]; + + assign action1_triggers[`TDT_TM_TRIGGER_NUM-1:0] = action1_mcontrol[`TDT_TM_MCONTROL_TRI_NUM-1:0]; + assign action0_triggers[`TDT_TM_TRIGGER_NUM-1:0] = action0_mcontrol[`TDT_TM_MCONTROL_TRI_NUM-1:0]; + +assign action1_match_trigger[`TDT_TM_TRIGGER_NUM-1:0] = triggers_match[`TDT_TM_TRIGGER_NUM-1:0] & action1_triggers[`TDT_TM_TRIGGER_NUM-1:0]; +assign action0_match_trigger[`TDT_TM_TRIGGER_NUM-1:0] = triggers_match[`TDT_TM_TRIGGER_NUM-1:0] & action0_triggers[`TDT_TM_TRIGGER_NUM-1:0]; + +//trigger hit +// &CombBeg; @1230 +// &CombEnd; @1237 +// &CombBeg; @1239 +always @( generate_timing0 + or action0_match_trigger[2:0] + or triggers_match[2:0] + or rtu_retire_halt_info[5]) +begin +if(generate_timing0 && !rtu_retire_halt_info[`TDT_HINFO_ACTION01]) + triggers_hit[`TDT_TM_TRIGGER_NUM-1:0] = triggers_match[`TDT_TM_TRIGGER_NUM-1:0]; +else if(generate_timing0 && rtu_retire_halt_info[`TDT_HINFO_ACTION01]) + triggers_hit[`TDT_TM_TRIGGER_NUM-1:0] = action0_match_trigger[`TDT_TM_TRIGGER_NUM-1:0]; +else + triggers_hit[`TDT_TM_TRIGGER_NUM-1:0] = {`TDT_TM_TRIGGER_NUM{1'b0}}; +// &CombEnd; @1246 +end + +//mcontrol hit +assign mcontrol_hit[`TDT_TM_MCONTROL_TRI_NUM-1:0] = triggers_hit[`TDT_TM_TRIGGER_NUM-1:`TDT_TM_TRIGGER_NUM-`TDT_TM_MCONTROL_TRI_NUM]; + +//iie trigger hit +//&CombBeg; +// if(rtu_pending_ack) +// mcontrol_hit[`TDT_TM_MCONTROL_TRI_NUM-1:0] = pending_halt_mhit_reg[`TDT_TM_MCONTROL_TRI_NUM-1:0]; +// else if(generate_timing0 && !rtu_retire_halt_info[`TDT_HINFO_ACTION01]) +// mcontrol_hit[`TDT_TM_MCONTROL_TRI_NUM-1:0] = mcontrols_match[`TDT_TM_MCONTROL_TRI_NUM-1:0]; +// else if(generate_timing0 && rtu_retire_halt_info[`TDT_HINFO_ACTION01]) +// mcontrol_hit[`TDT_TM_MCONTROL_TRI_NUM-1:0] = action1_match_trigger[`TDT_TM_MCONTROL_TRI_NUM-1:0]; +// else +// mcontrol_hit[`TDT_TM_MCONTROL_TRI_NUM-1:0] = {`TDT_TM_MCONTROL_TRI_NUM{1'b0}}; +//&CombEnd; +//iie trigger hit +//&CombBeg; +// if(rtu_pending_ack) +// iie_hit[`TDT_TM_OTHER_TRI_NUM-1:0] = pending_halt_iie_hit_reg[`TDT_TM_OTHER_TRI_NUM-1:0]; +// else +// iie_hit[`TDT_TM_OTHER_TRI_NUM-1:0]= {`TDT_TM_OTHER_TRI_NUM{1'b0}}; +//&CombEnd; +//========================================================= +// updata pending tval +//========================================================= + assign updata_tval = rtu_retire_halt_info[`TDT_HINFO_MATCH] && + !rtu_retire_halt_info[`TDT_HINFO_CHAIN] && + rtu_retire_halt_info[`TDT_HINFO_TIMING] && + !rtu_retire_halt_info[`TDT_HINFO_ACTION]; + +//always @(posedge m_iie_clk or negedge cpurst_b) +//begin +// if(!cpurst_b) +// pending_tval[XLEN-1:0] <= {XLEN{1'b0}}; +// else if(updata_tval) +// pending_tval[XLEN-1:0] <= rtu_dtu_tval[XLEN-1:0]; +//end +//assign dtu_rtu_pending_tval[XLEN-1:0] = pending_tval[XLEN-1:0]; + +//========================================================= +// cause +//========================================================= +assign rtu_cause[3:0] = rtu_retire_halt_info[`TDT_HINFO_CAUSE:`TDT_HINFO_CAUSE-3]; + +// &CombBeg; @1334 +always @( rtu_cause[3:0] + or rtu_dtu_halt_ack) +begin + if(rtu_dtu_halt_ack) + dtu_cause[3:0] = rtu_cause[3:0]; + else + dtu_cause[3:0] = rtu_cause[3:0]; +// &CombEnd; @1344 +end +// &Force("output","dtu_cause"); @1345 +//========================================================= +// pending halt +//========================================================= +//icount_enable for rtu +assign icount_enable = 1'b0; + +//assign step_match = dcsr_step && rtu_dtu_retire_step_fire; +//pending halt source + +assign iie_pending_halt = 1'b0; +//assign step_pending_halt = !generate_timing0 && step_match; +assign other_pending_halt = rtu_pending_halt;//include mcontrol pending, and other pending +assign generate_pending_halt = iie_pending_halt || other_pending_halt; + +//pending halt flg +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + pending_halt <= 1'b0; + else if(generate_pending_halt) + pending_halt <= 1'b1; + else if(rtu_pending_ack) + pending_halt <= 1'b0; +end +// &Force("output","pending_halt"); @1382 + +//action select +assign pending_halt_action = rtu_retire_halt_info[`TDT_HINFO_ACTION]; +assign penging_halt_action01 = rtu_retire_halt_info[`TDT_HINFO_ACTION01]; +//assign pending_halt_ldst = rtu_retire_halt_info[`TDT_HINFO_LDST]; +//pending halt info record + assign pending_halt_hit[`TDT_TM_TRIGGER_NUM-1:0] = triggers_match[`TDT_TM_TRIGGER_NUM-1:`TDT_TM_TRIGGER_NUM-`TDT_TM_MCONTROL_TRI_NUM]; +//========================================================= +// retire action01 +//========================================================= +//retire action01 source +assign generate_retire_action01 = generate_timing0 && rtu_retire_halt_info[`TDT_HINFO_ACTION01]; + +//retire action01 flg +assign clear_action01_reg = rtu_yy_xx_dbgon && retire_action01;//(ifu_dtu_addr_vld0 || ifu_dtu_data_vld0 || ifu_dtu_addr_vld1 || ifu_dtu_data_vld1); +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + retire_action01 <= 1'b0; + else if(generate_retire_action01) + retire_action01 <= 1'b1; + else if(clear_action01_reg) + retire_action01 <= 1'b0; +end +assign give_action01_halt_info = retire_action01 && !rtu_yy_xx_dbgon; + +//record hatl_info of pending halt and action01 +assign record_hit[`TDT_TM_TRIGGER_NUM-1:0] = generate_pending_halt ? pending_halt_hit[`TDT_TM_TRIGGER_NUM-1:0] : + action1_match_trigger[`TDT_TM_TRIGGER_NUM-1:0]; +assign record_action = generate_pending_halt ? pending_halt_action : 1'b1; +assign record_aciton01 = generate_pending_halt ? penging_halt_action01 : 1'b0; +assign record_ldst = rtu_retire_halt_info[`TDT_HINFO_LDST]; +assign record_cause[3:0] = dtu_cause[3:0]; +assign clear_record = pending_halt && rtu_pending_ack || + clear_action01_reg; + +always @(posedge m_iie_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + record_hit_reg[`TDT_TM_TRIGGER_NUM-1:0] <= {`TDT_TM_TRIGGER_NUM{1'b0}}; + record_action_reg <= 1'b0; + record_action01_reg <= 1'b0; + record_ldst_reg <= 1'b0; + record_cause_reg[3:0] <= 4'b0; + end + else if(generate_pending_halt || generate_retire_action01) + begin + record_hit_reg[`TDT_TM_TRIGGER_NUM-1:0] <= record_hit[`TDT_TM_TRIGGER_NUM-1:0]; + record_action_reg <= record_action; + record_action01_reg <= record_aciton01; + record_ldst_reg <= record_ldst; + record_cause_reg[3:0] <= record_cause[3:0]; + end + else if(clear_record) + begin + record_hit_reg[`TDT_TM_TRIGGER_NUM-1:0] <= {`TDT_TM_TRIGGER_NUM{1'b0}}; + record_action_reg <= 1'b0; + record_action01_reg <= 1'b0; + record_ldst_reg <= 1'b0; + record_cause_reg[3:0] <= 4'b0; + end +end + +assign record_match = |record_hit_reg[`TDT_TM_TRIGGER_NUM-1:0]; + +assign record_pending_halt = pending_halt || retire_action01; + +assign record_halt_info[`TDT_HINFO_WIDTH-1:0] = rtu_yy_xx_dbgon ? + {`TDT_HINFO_WIDTH{1'b0}} : + {record_hit_reg[`TDT_TM_TRIGGER_NUM-1:0],//match[7:0] + record_cause_reg[3:0],//cause + record_pending_halt, //pengding halt + 1'b0, //timing + record_action01_reg, //action01 + record_action_reg, //action + 1'b0, //chain + record_ldst_reg, //ldst + record_match, //match + 1'b1}; //cancel + + +//halt_info for ifu +assign use_record_halt_info = give_action01_halt_info || pending_halt; +assign dtu_ifu_halt_info0[`TDT_HINFO_WIDTH-1:0] = use_record_halt_info ? + record_halt_info[`TDT_HINFO_WIDTH-1:0] : + mcontrol_halt_info0[`TDT_HINFO_WIDTH-1:0]; +assign dtu_ifu_halt_info1[`TDT_HINFO_WIDTH-1:0] = use_record_halt_info ? + record_halt_info[`TDT_HINFO_WIDTH-1:0] : + mcontrol_halt_info1[`TDT_HINFO_WIDTH-1:0]; + +//========================================================== +// gate clk +//========================================================== +assign m_iie_clk_en =cp0_write_tselect || cp0_write_tcontrol || cp0_write_mcontext || + cp0_dtu_mexpt_vld || (rtu_dtu_retire_mret && rtu_dtu_retire_vld) || //cp0_dtu_mret_vld_f || + // updata_tval || + generate_pending_halt || rtu_pending_ack || + generate_retire_action01 || clear_action01_reg; +// &Force("nonport","m_iie_clk_en"); @1576 + + +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @1579 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (m_iie_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (m_iie_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @1580 +// .external_en (1'b0), @1581 +// .global_en (cp0_yy_clk_en), @1582 +// .module_en (cp0_dtu_icg_en), @1583 +// .local_en (m_iie_clk_en), @1584 +// //.local_en (1'b1), @1585 +// .clk_out (m_iie_clk)); @1586 + +// &ModuleEnd; @1599 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_0.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_0.v new file mode 100644 index 0000000000000000000000000000000000000000..40707f69ccd388befcb50f6bdf241fbe0c6bf57d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_0.v @@ -0,0 +1,1113 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_mcontrol_0( + already_match, + cp0_dtu_icg_en, + cp0_dtu_wdata, + cp0_write_tdata1, + cp0_write_tdata2, + cp0_write_tdata3, + cp0_yy_clk_en, + cpurst_b, + exe0_16bit, + exe0_32bit, + exe0_match, + exe0_may_hit, + exe1_16bit, + exe1_32bit, + exe1_match, + exe1_may_hit, + exe_mcontrol, + forever_cpuclk, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ldst_16bit, + ldst_32bit, + ldst_8bit, + ldst_addr_mcontrol, + ldst_data_mcontrol, + ldst_match, + ldst_may_hit, + ldst_mcontrol, + load_addr_vld, + load_data_vld, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + m_mode, + mcontext, + mpriority, + mpriority_after_chain, + mpriority_mask, + mpriority_mask_after_chain, + mtiming, + mtiming_after_chain, + mtiming_mask, + mtiming_mask_after_chain, + next_mpriority, + next_mpriority_mask, + next_mtiming, + next_mtiming_mask, + next_trigger_chain, + next_trigger_dmode, + pad_yy_icg_scan_en, + previous_mpriority, + previous_mpriority_mask, + previous_mtiming, + previous_mtiming_mask, + previous_trigger_chian, + previous_trigger_dmode, + rtu_yy_xx_dbgon, + set_trigger_hit, + store_addr_vld, + store_data_vld, + tcontrol, + tdata1, + tdata1_action0, + tdata1_action1, + tdata1_chain, + tdata1_dmode, + tdata1_timing, + tdata2, + tdata3, + tinfo, + trigger_selected, + u_mode +); + +// &Ports; @24 +input already_match; +input cp0_dtu_icg_en; +input [31:0] cp0_dtu_wdata; +input cp0_write_tdata1; +input cp0_write_tdata2; +input cp0_write_tdata3; +input cp0_yy_clk_en; +input cpurst_b; +input exe0_16bit; +input exe0_32bit; +input exe1_16bit; +input exe1_32bit; +input forever_cpuclk; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input ldst_16bit; +input ldst_32bit; +input ldst_8bit; +input load_addr_vld; +input load_data_vld; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input m_mode; +input [31:0] mcontext; +input [1 :0] next_mpriority; +input [1 :0] next_mpriority_mask; +input next_mtiming; +input next_mtiming_mask; +input next_trigger_chain; +input next_trigger_dmode; +input pad_yy_icg_scan_en; +input [1 :0] previous_mpriority; +input [1 :0] previous_mpriority_mask; +input previous_mtiming; +input previous_mtiming_mask; +input previous_trigger_chian; +input previous_trigger_dmode; +input rtu_yy_xx_dbgon; +input set_trigger_hit; +input store_addr_vld; +input store_data_vld; +input [31:0] tcontrol; +input trigger_selected; +input u_mode; +output exe0_match; +output exe0_may_hit; +output exe1_match; +output exe1_may_hit; +output exe_mcontrol; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output ldst_match; +output ldst_may_hit; +output ldst_mcontrol; +output [1 :0] mpriority; +output [1 :0] mpriority_after_chain; +output [1 :0] mpriority_mask; +output [1 :0] mpriority_mask_after_chain; +output mtiming; +output mtiming_after_chain; +output mtiming_mask; +output mtiming_mask_after_chain; +output [31:0] tdata1; +output tdata1_action0; +output tdata1_action1; +output tdata1_chain; +output tdata1_dmode; +output tdata1_timing; +output [31:0] tdata2; +output [31:0] tdata3; +output [31:0] tinfo; + +// &Regs; @25 +reg dmode_legal; +reg exe0_match; +reg exe1_match; +reg ldst_match; +reg [3 :0] m_mask_four_bits; +reg [7 :0] m_mask_reg; +reg match_ldst_addr; +reg [1 :0] mpriority; +reg [1 :0] mpriority_mask; +reg size1; +reg size2; +reg [31:0] size_mask; +reg tdata1_action; +reg tdata1_dmode; +reg tdata1_execute; +reg tdata1_hit; +reg tdata1_load; +reg tdata1_m; +reg [3 :0] tdata1_match; +reg [1 :0] tdata1_sizelo; +reg tdata1_store; +reg tdata1_timing; +reg tdata1_u; +reg [31:0] tdata2; +reg [7 :0] tdata2_ldst_bytes_vld_0; +reg [3 :0] tdata2_ldst_bytes_vld_for_match1_four_bits; +reg [3 :0] tdata2_ldst_bytes_vld_four_bits; +reg [7 :0] tdata2_ldst_bytes_vld_reg_0; +reg tdata3_mselect; +reg [5 :0] tdata3_mvalue; +reg write_tdata1_f; +reg write_tdata2_f; + +// &Wires; @26 +wire action_is_legal; +wire action_legal; +wire already_match; +wire bytes_vld_match; +wire cp0_dtu_icg_en; +wire [31:0] cp0_dtu_wdata; +wire cp0_write_tdata1; +wire cp0_write_tdata2; +wire cp0_write_tdata3; +wire cp0_yy_clk_en; +wire cpurst_b; +wire exe0_16bit; +wire exe0_32bit; +wire exe0_have_value_match0; +wire exe0_have_value_match1; +wire exe0_match_equal; +wire exe0_match_need_reg; +wire exe0_match_top_mbits_equal; +wire exe0_may_hit; +wire exe0_size_match; +wire exe0_type_match; +wire exe0_type_size_match; +wire [31:0] exe0_value; +wire [31:0] exe0_value_before_size_mask; +wire [7 :0] exe0_value_masked_low_8bis; +wire exe0_value_match; +wire [31:0] exe0_value_top_mbits; +wire exe1_16bit; +wire exe1_32bit; +wire exe1_have_value_match0; +wire exe1_have_value_match1; +wire exe1_match_equal; +wire exe1_match_need_reg; +wire exe1_match_top_mbits_equal; +wire exe1_may_hit; +wire exe1_size_match; +wire exe1_type_match; +wire exe1_type_size_match; +wire [31:0] exe1_value; +wire [31:0] exe1_value_before_size_mask; +wire [7 :0] exe1_value_masked_low_8bis; +wire exe1_value_match; +wire [31:0] exe1_value_top_mbits; +wire exe_addr_mcontrol; +wire exe_data_mcontrol; +wire exe_mcontrol; +wire exe_size_is_legal; +wire forever_cpuclk; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire ldst_16bit; +wire ldst_32bit; +wire ldst_8bit; +wire ldst_addr_match_equal; +wire ldst_addr_mcontrol; +wire ldst_addr_top_mbits_equal; +wire ldst_bytes_vld_equal; +wire ldst_bytes_vld_mbits_equal; +wire ldst_data_mcontrol; +wire ldst_have_value_match0; +wire ldst_have_value_match1; +wire [7 :0] ldst_m_mask; +wire ldst_match_equal; +wire ldst_match_need_reg; +wire ldst_match_top_mbits_equal; +wire ldst_may_hit; +wire ldst_mcontrol; +wire ldst_mcontrol_match; +wire ldst_size_is_legal; +wire ldst_size_match; +wire ldst_type_match; +wire ldst_type_size_match; +wire [31:0] ldst_value; +wire [31:0] ldst_value_before_size_mask; +wire ldst_value_equal; +wire [7 :0] ldst_value_masked_low_8bis; +wire ldst_value_match; +wire [31:0] ldst_value_top_mbits; +wire ldst_value_top_mbits_equal; +wire load_addr_mcontrol; +wire load_addr_vld; +wire load_data_mcontrol; +wire load_data_trigger; +wire load_data_vld; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire lsu_dtu_ldst_data_vld; +wire lsu_have_bytes_vld; +wire m_enable; +wire [7 :0] m_mask; +wire m_mode; +wire [5 :0] maskmax; +wire match_is_legal; +wire [3 :0] match_legal; +wire [31:0] mcontext; +wire mcontext_enable; +wire mcontext_must_match; +wire [1 :0] mpriority_after_chain; +wire [1 :0] mpriority_mask_after_chain; +wire ms_context_enable; +wire msu_mode_enable; +wire mtiming; +wire mtiming_after_chain; +wire mtiming_mask; +wire mtiming_mask_after_chain; +wire not_dbg_mode_enable; +wire pad_yy_icg_scan_en; +wire previous_trigger_chian; +wire previous_trigger_dmode; +wire rtu_yy_xx_dbgon; +wire set_trigger_hit; +wire size_is_legal; +wire [1 :0] size_legal; +wire store_addr_mcontrol; +wire store_addr_vld; +wire store_data_mcontrol; +wire store_data_vld; +wire [31:0] tcontrol; +wire tcontrol_enable; +wire [31:0] tdata1; +wire tdata1_action0; +wire tdata1_action1; +wire tdata1_chain; +wire tdata1_chain_for_macro; +wire tdata1_execute_for_macro; +wire tdata1_load_for_macro; +wire tdata1_matchinfo_clk; +wire tdata1_matchinfo_clk_en; +wire tdata1_select_for_macro; +wire [1 :0] tdata1_size; +wire tdata1_store_for_macro; +wire tdata23_clk; +wire tdata23_clk_en; +wire [3 :0] tdata2_4bits_value_for_m_mask; +wire [7 :0] tdata2_exe_value_masked_low_8bits; +wire [31:0] tdata2_exe_value_top_mbits; +wire [7 :0] tdata2_ldst_addr_masked_low_8bits; +wire [7 :0] tdata2_ldst_bytes_vld; +wire [7 :0] tdata2_ldst_bytes_vld_for_match1; +wire [31:0] tdata2_ldst_value_top_mbits; +wire [31:0] tdata2_value; +wire [31:0] tdata2_value_before_size_mask; +wire [31:0] tdata3; +wire tdata_writable; +wire timing_exe_or_wdata; +wire timing_legal; +wire [31:0] tinfo; +wire tri_already_match; +wire trigger_enable; +wire trigger_selected; +wire [3 :0] type_legal; +wire u_enable; +wire u_mode; +wire [1 :0] wdata_tdata1_size; +wire write_tdata1; +wire write_tdata2; +wire zero_lsb_higher_than_4; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; +//parameter (`TDT_DM_CORE_HALF_XLEN) = (`TDT_DM_CORE_HALF_XLEN); + +//tdata1 parameter +parameter TYPE_TDATA1 = XLEN-1; +parameter DMODE = XLEN-5; + +//mcontrol parameter +parameter SIZEHI = 22; +parameter HIT = 20; +parameter SELECT_TDATA1 = 19; +parameter TIMING = 18; +parameter SIZELO = 17; +parameter ACTION = 15; +parameter CHAIN = 11; +parameter MATCH = 10; +parameter M = 6; +parameter S = 4; +parameter U = 3; +parameter EXECUTE = 2; +parameter STORE = 1; +parameter LOAD = 0; + +//tdata3 parameter +parameter MVALUE = 31; +parameter MSELECT_TDATA1 = 25; + +//tcontrol parameter +//parameter MPTE = 7; +parameter MTE = 3; + +//========================================================= +// +// tdata1 wdata legalization +// +//========================================================= + +//type +assign type_legal[3:0] = 4'd2;//mcontrol type = 2 + +//dmode +// &CombBeg; @70 +always @( rtu_yy_xx_dbgon + or previous_trigger_dmode + or cp0_dtu_wdata[27] + or tdata1[27] + or previous_trigger_chian) +begin + if(!rtu_yy_xx_dbgon)//dmode only writable in debug mode + dmode_legal = tdata1[DMODE]; + else if(!previous_trigger_dmode && previous_trigger_chian) + dmode_legal = 1'b0; + else + dmode_legal = cp0_dtu_wdata[DMODE]; +// &CombEnd; @77 +end + +//--------------------------------------------------------- +// mcontrol tdata1 wdata legalization +//--------------------------------------------------------- +//size +assign wdata_tdata1_size[1:0] = cp0_dtu_wdata[SIZELO:SIZELO-1]; +assign exe_size_is_legal = cp0_dtu_wdata[EXECUTE] && (wdata_tdata1_size[1:0] == 2'd0 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3);//exe only suppurt size = 0,2,3 + +assign ldst_size_is_legal = (cp0_dtu_wdata[LOAD] || cp0_dtu_wdata[STORE]) && (wdata_tdata1_size[1:0] == 2'd0 || wdata_tdata1_size[1:0] == 2'd1 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3); +// &Force("nonport","ldst_size_is_legal"); @97 +assign size_is_legal = exe_size_is_legal || ldst_size_is_legal; +assign size_legal[1:0] = size_is_legal ? wdata_tdata1_size[1:0] : 2'b0; + +//action +assign action_is_legal = cp0_dtu_wdata[ACTION:ACTION-2] == 3'd0 && dmode_legal; +//(1)action <= 1;(2)dmode=1;action can be set to 0 or 1. +assign action_legal = action_is_legal ? cp0_dtu_wdata[ACTION-3] : 1'b0; + +//match +assign match_is_legal = cp0_dtu_wdata[MATCH:MATCH-3] == 4'd0 || cp0_dtu_wdata[MATCH:MATCH-3] == 4'd1; + +assign match_legal[3:0] = match_is_legal ? cp0_dtu_wdata[MATCH:MATCH-3] : 4'b0; + +//timing +assign load_data_trigger = 1'b0; +assign timing_exe_or_wdata = cp0_dtu_wdata[EXECUTE] ? 1'b0 : cp0_dtu_wdata[TIMING]; +assign timing_legal = load_data_trigger ? 1'b1 : timing_exe_or_wdata; + +//chain +//1.if previous trigger chain=1, this trigger chain can't set to 1. +//2.if next trigger chain=1, this trigger chain can't set to 1. +//3.if next trigger dmode =1, this write operation will set this trigger dmode to 0, +//then the write operation can't set this trigger chain to 1. +// &Force("input","previous_trigger_chian"); @146 +// &Force("input","next_trigger_chain"); @147 +// &Force("input","next_trigger_dmode"); @148 +// &Force("input","previous_trigger_chian"); @155 +// &Force("input","next_trigger_chain"); @156 +// &Force("input","next_trigger_dmode"); @157 + +//--------------------------------------------------------- +// legal tdata1 wdata +//--------------------------------------------------------- +assign maskmax[5:0] = 6'd8;//TODO + +//========================================================= +// +// write trigger CSR +// +//========================================================= + +//--------------------------------------------------------- +// write and update tdata1 +//--------------------------------------------------------- + +assign tdata_writable = !tdata1[DMODE] && (m_mode || rtu_yy_xx_dbgon) || + tdata1[DMODE] && rtu_yy_xx_dbgon; +assign write_tdata1 = cp0_write_tdata1 && trigger_selected && tdata_writable; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata1_dmode <= 1'b0; + tdata1_timing <= 1'b0; + tdata1_sizelo[1:0] <= 2'b0; + tdata1_action <= 1'b0; + tdata1_match[3:0] <= 4'b0; + tdata1_m <= 1'b0; + tdata1_u <= 1'b0; + tdata1_store <= 1'b0; + tdata1_load <= 1'b0; + tdata1_execute <= 1'b0; + end + else if(write_tdata1) + begin + tdata1_dmode <= dmode_legal; + tdata1_timing <= timing_legal; + tdata1_sizelo[1:0] <= size_legal[1:0]; + tdata1_action <= action_legal; + tdata1_match[3:0] <= match_legal[3:0]; + tdata1_m <= cp0_dtu_wdata[M]; + tdata1_u <= cp0_dtu_wdata[U]; + tdata1_store <= cp0_dtu_wdata[STORE]; + tdata1_load <= cp0_dtu_wdata[LOAD]; + tdata1_execute <= cp0_dtu_wdata[EXECUTE]; + end +end +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + size1 <= 1'b0; + size2 <= 1'b0; + end + else if(write_tdata1) + begin + size1 <= size_legal[1:0] == 2'd1; + size2 <= size_legal[1:0] == 2'd2; + end +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata1_hit <= 1'b0; + else if(set_trigger_hit) + tdata1_hit <= 1'b1; + else if(write_tdata1) + tdata1_hit <= cp0_dtu_wdata[HIT]; +end + + assign tdata1_select_for_macro = 1'b0; +assign tdata1_execute_for_macro = tdata1_execute; + assign tdata1_store_for_macro = tdata1_store; + assign tdata1_load_for_macro = tdata1_load; + +assign tdata1_chain = 1'b0; +assign tdata1_chain_for_macro = tdata1_chain; + +assign tdata1[XLEN-1:0] = {type_legal[3:0],tdata1_dmode,maskmax[5:0], + tdata1_hit,tdata1_select_for_macro,tdata1_timing,tdata1_sizelo[1:0],3'b0,tdata1_action, + tdata1_chain_for_macro,tdata1_match[3:0],tdata1_m,1'b0,1'b0,tdata1_u, + tdata1_execute_for_macro,tdata1_store_for_macro,tdata1_load_for_macro}; + +// &Force("output","tdata1");&Force("bus","tdata1",XLEN-1,0); @291 + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata1_f <= 1'b0; + else + write_tdata1_f <= write_tdata1; +end +// &Force("nonport","write_tdata1_f"); @300 +//tdata1 output +// &Force("output","tdata1_chain"); @302 +// &Force("output","tdata1_dmode"); @303 +// &Force("output","tdata1_timing"); @304 +//assign tdata1_chain = tdata1[CHAIN]; +//assign tdata1_dmode = tdata1[DMODE]; +assign tdata1_action0 = !tdata1[ACTION-3]; +assign tdata1_action1 = tdata1[ACTION-3]; +//assign tdata1_timing = tdata1[TIMING]; + +//--------------------------------------------------------- +// write tdata2 +//--------------------------------------------------------- +assign write_tdata2 = cp0_write_tdata2 && trigger_selected && tdata_writable; +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2[XLEN-1:0] <= {XLEN{1'b0}}; + else if(write_tdata2) + tdata2[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; +end +// &Force("output","tdata2");&Force("bus","tdata2",XLEN-1,0); @322 + +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata2_f <= 1'b0; + else + write_tdata2_f <= write_tdata2; +end +// &Force("nonport","write_tdata2_f"); @331 +//--------------------------------------------------------- +// write tdata3 +//--------------------------------------------------------- + +//write tdata3 +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata3_mvalue[5:0] <= 6'b0; + tdata3_mselect <= 1'b0; + end + else if(cp0_write_tdata3 && trigger_selected && tdata_writable) + begin + tdata3_mvalue[5:0] <= cp0_dtu_wdata[MVALUE:MVALUE-5]; + tdata3_mselect <= cp0_dtu_wdata[MSELECT_TDATA1]; + end +end +assign tdata3[XLEN-1:0] = {tdata3_mvalue[5:0],tdata3_mselect,25'b0}; +// &Force("output","tdata3");&Force("bus","tdata3",XLEN-1,0); @351 +//--------------------------------------------------------- +// tinfo(read only) +//--------------------------------------------------------- +assign tinfo[XLEN-1:0] = {{XLEN-3{1'b0}},3'b100}; +// &Force("output","tinfo");&Force("bus","tinfo",XLEN-1,0); @356 +//mcontrol type =2 + +//========================================================= +// +// decode +// +//========================================================= +//--------------------------------------------------------- +// trigger enable signal +//--------------------------------------------------------- +//tcontrol enable +//assign tdata1_action[3:0] = tdata1[ACTION:ACTION-3]; + +assign tcontrol_enable = !(!tcontrol[MTE] && !tdata1_action && m_mode);//!(MTE=0 && action=0 && m_mode) +// &Force("bus","tcontrol",XLEN-1,0); @371 + +//m s context enable +assign mcontext_must_match = tdata3[MSELECT_TDATA1] && m_mode; +assign mcontext_enable = mcontext_must_match ? tdata3[MVALUE:MVALUE-5] == mcontext[5:0] : 1'b1; +// &Force("bus","mcontext",XLEN-1,0); @376 + +assign ms_context_enable = mcontext_enable; +assign m_enable = tdata1[M] && m_mode; +assign u_enable = tdata1[U] && u_mode; + +assign msu_mode_enable = m_enable || u_enable; + +//trigger can't match in debug mode +assign not_dbg_mode_enable = !rtu_yy_xx_dbgon; + +//trigger enable +assign trigger_enable = tcontrol_enable && ms_context_enable && + msu_mode_enable && not_dbg_mode_enable; + +//--------------------------------------------------------- +// information for match +//--------------------------------------------------------- +//type of mcontrol +assign exe_mcontrol = tdata1[EXECUTE]; +assign ldst_mcontrol = tdata1[LOAD] || tdata1[STORE]; +// &Force("output","exe_mcontrol"); @397 +// &Force("output","ldst_mcontrol"); @398 +assign exe_addr_mcontrol = tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]; +assign exe_data_mcontrol = tdata1[EXECUTE] && tdata1[SELECT_TDATA1]; + +assign store_addr_mcontrol = tdata1[STORE] && !tdata1[SELECT_TDATA1]; +assign store_data_mcontrol = tdata1[STORE] && tdata1[SELECT_TDATA1]; +//assign load_mcontrol = tdata1[LOAD]; +//assign ldst_mcontrol = store_mcontrol && load_mcontrol; +assign load_addr_mcontrol = tdata1[LOAD] && !tdata1[SELECT_TDATA1]; +assign load_data_mcontrol = tdata1[LOAD] && tdata1[SELECT_TDATA1]; + +assign ldst_addr_mcontrol = store_addr_mcontrol || load_addr_mcontrol; +assign ldst_data_mcontrol = store_data_mcontrol || load_data_mcontrol; +//priorty +// &CombBeg; @414 +always @( tdata1[2] + or tdata1[19]) +begin + if(tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b10; + mpriority_mask[1:0] = 2'b00; + end + else if(tdata1[EXECUTE] && tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b01; + mpriority_mask[1:0] = 2'b10; + end + else//ldst mcontrol or no mcontrol + begin + mpriority[1:0] = 2'b00; + mpriority_mask[1:0] = 2'b11; + end +// &CombEnd; @430 +end +//mtiming +assign mtiming = !tdata1[TIMING]; +assign mtiming_mask = tdata1[TIMING]; +// &Force("output","mpriority");&Force("bus","mpriority",1,0); @434 +// &Force("output","mpriority_mask");&Force("bus","mpriority_mask",1,0); @435 +// &Force("output","mtiming"); @436 +// &Force("output","mtiming_mask"); @437 + +// &CombBeg; @443 +// &CombEnd; @459 +// &CombBeg; @463 +// &CombEnd; @479 +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @480 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @481 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @482 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @483 +// &Force("input","previous_mtiming"); @484 +// &Force("input","previous_mtiming_mask"); @485 +// &Force("input","next_mtiming"); @486 +// &Force("input","next_mtiming_mask"); @487 +assign mpriority_after_chain[1:0] = mpriority[1:0]; +assign mpriority_mask_after_chain[1:0]= mpriority_mask[1:0]; +assign mtiming_after_chain = mtiming; +assign mtiming_mask_after_chain = mtiming_mask; +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @493 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @494 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @495 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @496 +// &Force("input","previous_mtiming"); @497 +// &Force("input","previous_mtiming_mask"); @498 +// &Force("input","next_mtiming"); @499 +// &Force("input","next_mtiming_mask"); @500 + +//size +assign tdata1_size[1:0] = tdata1[SIZELO:SIZELO-1]; + +//assign size_mask_63_32 = !(size1 || size2 || size3); +//assign size_mask_31_16 = !(size1 || size2); +//assign size_mask_15_8 = !size1; +//assign size_mask[XLEN-1:0] = {{32{size_mask_63_32}},{16{size_mask_31_16}},{8{size_mask_15_8}},{8{1'b1}}}; +// &CombBeg; @510 +always @( size1 + or size2) +begin + if(size1) + size_mask[XLEN-1:0] = 32'h0000_00ff; + else if(size2) + size_mask[XLEN-1:0] = 32'h0000_ffff; + else + size_mask[XLEN-1:0] = 32'hffff_ffff; +// &CombEnd; @517 +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + match_ldst_addr <= 1'b0; + else if(!tdata1[SELECT_TDATA1] && (tdata1[LOAD] || tdata1[STORE])) + match_ldst_addr <= 1'b1; + else if(tdata1[LOAD] || tdata1[STORE] || tdata1[EXECUTE]) + match_ldst_addr <= 1'b0; +end + +//tdata2 need to be masked off by size +assign tdata2_value_before_size_mask[XLEN-1:0] = {tdata2[XLEN-1:3], tdata2[2:0] & {3{!match_ldst_addr}}}; +assign tdata2_value[XLEN-1:0] = tdata2_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//translate tdata2[23:20] to bytes_vld. when select = 0, match = 4. +//tdata2_ldst_value_lower_half == ldst_value_lower_half & tdata2_exe_value_upper_half +//tdata2_ldst_bytes_vld == lsu_dtu_ldst_bytes_vld & tdata2_ldst_bytes_vld_for_match4 + + //tdata2[3:0] generate low_bytes_vld +// &CombBeg; @558 +always @( tdata2[1:0]) +begin + case(tdata2[1:0]) + 2'b00: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0001; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b0011; + end + 2'b01: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0010; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + 2'b10: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0100; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1100; + end + 2'b11: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b1000; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + default: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = {4{1'bx}}; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = {4{1'bx}}; + end + endcase +// &CombEnd; @611 +end +assign tdata2_ldst_bytes_vld[7:0] = tdata2[2] ? {tdata2_ldst_bytes_vld_four_bits[3:0],4'b0} : {4'b0,tdata2_ldst_bytes_vld_four_bits[3:0]}; +assign tdata2_ldst_bytes_vld_for_match1[7:0] = tdata2[2] ? {{4{tdata2[1] && tdata2[0]}},tdata2_ldst_bytes_vld_for_match1_four_bits[3:0]} : + {tdata2_ldst_bytes_vld_for_match1_four_bits[3:0],{4{tdata2[1] && tdata2[0]}}}; +//when tdata2[1] && tdata2[0] = 1, bytes_vld_for_match1 should be 8'bff no matter what tdata2[2] is + +// &CombBeg; @625 +// &CombEnd; @642 + +// &CombBeg; @645 +always @( tdata2_ldst_bytes_vld_for_match1[7:0] + or tdata2_ldst_bytes_vld[7:0] + or tdata1[10:7]) +begin + case(tdata1[MATCH:MATCH-3]) + 4'd0:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld[7:0]; + 4'd1:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld_for_match1[7:0]; + default:tdata2_ldst_bytes_vld_0[7:0] = {8{1'bx}}; + endcase +// &CombEnd; @661 +end + +//when match = 4, need reg_0 and reg_1 both. +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2_ldst_bytes_vld_reg_0[7:0] <= 8'b0; + else if(tdata1[STORE] && !tdata1[SELECT_TDATA1] || tdata1[LOAD] && !tdata1[SELECT_TDATA1]) + tdata2_ldst_bytes_vld_reg_0[7:0] <= tdata2_ldst_bytes_vld_0[7:0]; +end + +//----------------------maksed value for match = 1------------------------------------ +assign zero_lsb_higher_than_4 = tdata2[3:0] == 4'b1111; +assign tdata2_4bits_value_for_m_mask[3:0] = zero_lsb_higher_than_4 ? tdata2[7:4] : tdata2[3:0]; +// &CombBeg; @677 +always @( tdata2_4bits_value_for_m_mask[3:0]) +begin + //m_mask and ldst_addr_mask(maskmax = 8). the low 4 bit of ldst addr are 0 + casez(tdata2_4bits_value_for_m_mask[3:0]) + 4'b???0:m_mask_four_bits[3:0] = 4'b1110; + 4'b??01:m_mask_four_bits[3:0] = 4'b1100; + 4'b?011:m_mask_four_bits[3:0] = 4'b1000; + 4'b0111:m_mask_four_bits[3:0] = 4'b0000; + 4'b1111:m_mask_four_bits[3:0] = 4'b0000; + default:m_mask_four_bits[3:0] = {4{1'bx}}; + endcase +// &CombEnd; @687 +end + +assign m_mask[7:0] = zero_lsb_higher_than_4 ? {m_mask_four_bits[3:0],4'b0} : {4'b1111,m_mask_four_bits[3:0]}; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + m_mask_reg[7:0] <= 8'b11111111; + else if(tdata1[MATCH:MATCH-3] == 4'b1) + m_mask_reg[7:0] <= m_mask[7:0]; +end + +//exe top M bits +assign tdata2_exe_value_masked_low_8bits[7:0] = tdata2_value[7:0] & m_mask_reg[7:0]; +assign tdata2_exe_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_exe_value_masked_low_8bits[7:0]}; + +//ldst top M bits +assign ldst_m_mask[7:0] = tdata1[SELECT_TDATA1] ? m_mask_reg[7:0] : {m_mask_reg[7:3],3'b0}; +assign tdata2_ldst_addr_masked_low_8bits[7:0] = tdata2_value[7:0] & ldst_m_mask[7:0]; +assign tdata2_ldst_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_ldst_addr_masked_low_8bits[7:0]}; + +//========================================================= +// +// exe0 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe0 type match and size match +//--------------------------------------------------------- +assign exe0_type_match = ifu_dtu_addr_vld0 && exe_addr_mcontrol || ifu_dtu_data_vld0 && exe_data_mcontrol; +assign exe0_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe0_16bit || + tdata1_size[1:0] == 2'd3 && exe0_32bit || (ifu_dtu_addr_vld0 && !ifu_dtu_data_vld0); +assign exe0_type_size_match = exe0_type_match && exe0_size_match && trigger_enable; +//--------------------------------------------------------- +// exe0 value match +//--------------------------------------------------------- +//value for exe0 trigger match +assign exe0_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr0[`PA_WIDTH-1:0]; +assign exe0_value[XLEN-1:0] = exe0_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe0_value_masked_low_8bis[7:0] = exe0_value[7:0] & m_mask_reg[7:0]; +assign exe0_value_top_mbits[XLEN-1:0] = {exe0_value[XLEN-1:8],exe0_value_masked_low_8bis[7:0]}; + +//value match +assign exe0_match_equal = exe0_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe0_match_top_mbits_equal = exe0_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + +assign exe0_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe0_match_equal; +assign exe0_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe0_match_top_mbits_equal; + +assign exe0_value_match = exe0_have_value_match0 || exe0_have_value_match1; +//--------------------------------------------------------- +// exe0 match result +//--------------------------------------------------------- +assign exe0_match_need_reg = exe0_value_match && exe0_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe0_match <= 1'b0; + else + exe0_match <= exe0_match_need_reg; +end +// &Force("output","exe0_match"); @820 + +assign exe0_may_hit = exe0_value_match;// && ifu_dtu_addr_vld0; + +//========================================================= +// +// exe1 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe1 type match and size match +//--------------------------------------------------------- +assign exe1_type_match = ifu_dtu_addr_vld1 && exe_addr_mcontrol || ifu_dtu_data_vld1 && exe_data_mcontrol; +assign exe1_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe1_16bit || + tdata1_size[1:0] == 2'd3 && exe1_32bit || (ifu_dtu_addr_vld1 && !ifu_dtu_data_vld1); +assign exe1_type_size_match = exe1_type_match && exe1_size_match && trigger_enable; +//--------------------------------------------------------- +// exe1 value match +//--------------------------------------------------------- +//value for exe1 trigger match +assign exe1_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr1[`PA_WIDTH-1:0]; +assign exe1_value[XLEN-1:0] = exe1_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe1_value_masked_low_8bis[7:0] = exe1_value[7:0] & m_mask_reg[7:0]; +assign exe1_value_top_mbits[XLEN-1:0] = {exe1_value[XLEN-1:8],exe1_value_masked_low_8bis[7:0]}; + +//value match +assign exe1_match_equal = exe1_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe1_match_top_mbits_equal = exe1_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + + +assign exe1_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe1_match_equal; +assign exe1_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe1_match_top_mbits_equal; + +assign exe1_value_match = exe1_have_value_match0 || exe1_have_value_match1; +//--------------------------------------------------------- +// exe1 match result +//--------------------------------------------------------- +assign exe1_match_need_reg = exe1_value_match && exe1_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe1_match <= 1'b0; + else + exe1_match <= exe1_match_need_reg; +end +// &Force("output","exe1_match"); @916 + +assign exe1_may_hit = exe1_value_match;// && ifu_dtu_addr_vld1; +// &Force("input","exe0_16bit"); @920 +// &Force("input","exe0_32bit"); @921 +// &Force("input","exe1_16bit"); @922 +// &Force("input","exe1_32bit"); @923 +// &Force("input","ifu_dtu_addr_vld0"); @924 +// &Force("input","ifu_dtu_addr_vld1"); @925 +// &Force("input","ifu_dtu_data_vld0"); @926 +// &Force("input","ifu_dtu_data_vld1"); @927 +// &Force("input","ifu_dtu_exe_addr0");&Force("bus","ifu_dtu_exe_addr0",`PA_WIDTH-1,0); @928 +// &Force("input","ifu_dtu_exe_addr1");&Force("bus","ifu_dtu_exe_addr1",`PA_WIDTH-1,0); @929 +// &Force("input","ifu_dtu_exe_data0");&Force("bus","ifu_dtu_exe_data0",31,0); @930 +// &Force("input","ifu_dtu_exe_data1");&Force("bus","ifu_dtu_exe_data1",31,0); @931 +// &Force("output","exe0_match"); @932 +// &Force("output","exe1_match"); @933 + +//========================================================= +// +// ldst match logic +// +//========================================================= +//--------------------------------------------------------- +// ldst type match and size match +//--------------------------------------------------------- +assign ldst_type_match = store_addr_vld && store_addr_mcontrol || + store_data_vld && store_data_mcontrol || + load_addr_vld && load_addr_mcontrol || + load_data_vld && load_data_mcontrol; +assign ldst_size_match = tdata1_size[1:0] == 2'd0 || size1 && ldst_8bit || + size2 && ldst_16bit || tdata1_size[1:0] == 2'd3 && ldst_32bit; +assign ldst_type_size_match = ldst_type_match && ldst_size_match && trigger_enable; + +//--------------------------------------------------------- +// ldst value match +//--------------------------------------------------------- +//value for ldst trigger match +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @963 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @964 +assign ldst_value_before_size_mask[XLEN-1:0] = {lsu_dtu_ldst_addr[`PA_WIDTH-1:3],3'b0}; + +assign ldst_value[XLEN-1:0] = ldst_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//masked value +assign ldst_value_masked_low_8bis[7:0] = ldst_value[7:0] & ldst_m_mask[7:0]; +assign ldst_value_top_mbits[XLEN-1:0] = {ldst_value[XLEN-1:8],ldst_value_masked_low_8bis[7:0]}; + +//value match +assign lsu_have_bytes_vld = |lsu_dtu_ldst_bytes_vld[7:0]; +// &Force("nonport","lsu_have_bytes_vld"); @990 +assign bytes_vld_match = |(lsu_dtu_ldst_bytes_vld[7:0] & tdata2_ldst_bytes_vld_reg_0[7:0]); +//match = 0 +assign ldst_value_equal = ldst_value[XLEN-1:0] == tdata2_value[XLEN-1:0]; +assign ldst_bytes_vld_equal = bytes_vld_match; +assign ldst_addr_match_equal = ldst_bytes_vld_equal && ldst_value_equal; +assign ldst_match_equal = ldst_addr_match_equal; + +//match = 1 +assign ldst_value_top_mbits_equal = ldst_value_top_mbits[XLEN-1:0] == tdata2_ldst_value_top_mbits[XLEN-1:0]; +assign ldst_bytes_vld_mbits_equal = bytes_vld_match; +assign ldst_addr_top_mbits_equal = ldst_value_top_mbits_equal && ldst_bytes_vld_mbits_equal; +assign ldst_match_top_mbits_equal = ldst_addr_top_mbits_equal; + + + + +assign ldst_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && ldst_match_equal; +assign ldst_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && ldst_match_top_mbits_equal; + +assign ldst_value_match = ldst_have_value_match0 || ldst_have_value_match1; +//--------------------------------------------------------- +// ldst match result +//--------------------------------------------------------- +assign tri_already_match = already_match && (lsu_dtu_ldst_addr_vld || lsu_dtu_ldst_data_vld); +assign ldst_mcontrol_match = ldst_value_match && ldst_type_size_match; +assign ldst_match_need_reg = ldst_mcontrol_match || tri_already_match; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ldst_match <= 1'b0; + else + ldst_match <= ldst_match_need_reg; +end +// &Force("output","ldst_match"); @1176 +//assign ldst_may_hit = ldst_cycle2_cannot_match ? 1'b0 : ldst_match_need_reg; +assign ldst_may_hit = ldst_match_need_reg;//ldst_value_match || tri_already_match; +// &Force("input","already_match"); @1180 +// &Force("input","ldst_8bit"); @1181 +// &Force("input","ldst_16bit"); @1182 +// &Force("input","ldst_32bit"); @1183 +// &Force("input","store_addr_vld"); @1184 +// &Force("input","store_data_vld"); @1185 +// &Force("input","load_addr_vld"); @1186 +// &Force("input","load_data_vld"); @1187 +// &Force("input","lsu_dtu_ldst_addr_vld"); @1188 +// &Force("input","lsu_dtu_ldst_data_vld"); @1189 +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @1190 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @1191 +// &Force("input","lsu_dtu_ldst_bytes_vld");&Force("bus","lsu_dtu_ldst_bytes_vld",7,0); @1192 +// &Force("output","ldst_match"); @1193 + +//========================================================== +// gate clk +//========================================================== +assign tdata1_matchinfo_clk_en = trigger_selected && + (cp0_write_tdata1 || write_tdata2_f || write_tdata1_f) || + exe0_match_need_reg || exe0_match || + exe1_match_need_reg || exe1_match || + ldst_match_need_reg || ldst_match || + set_trigger_hit; +// &Instance("gated_clk_cell", "x_tdata1_matchinfo_reg_gated_clk"); @1208 +gated_clk_cell x_tdata1_matchinfo_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata1_matchinfo_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata1_matchinfo_clk_en), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @1209 +// .external_en (1'b0), @1210 +// .global_en (cp0_yy_clk_en), @1211 +// .module_en (cp0_dtu_icg_en), @1212 +// .local_en (tdata1_matchinfo_clk_en), @1213 +// //.local_en (1'b1), @1214 +// .clk_out (tdata1_matchinfo_clk)); @1215 + +//make tdata2, tdata3 a gated clk cell +assign tdata23_clk_en = trigger_selected && (cp0_write_tdata2 || cp0_write_tdata3 || write_tdata2_f); +// &Instance("gated_clk_cell", "x_tdata23_reg_gated_clk"); @1219 +gated_clk_cell x_tdata23_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata23_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata23_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @1220 +// .external_en (1'b0), @1221 +// .global_en (cp0_yy_clk_en), @1222 +// .module_en (cp0_dtu_icg_en), @1223 +// .local_en (tdata23_clk_en), @1224 +// //.local_en (1'b1), @1225 +// .clk_out (tdata23_clk)); @1226 +// &ModuleEnd; @1227 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_1.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_1.v new file mode 100644 index 0000000000000000000000000000000000000000..b8aea664b6e653a5833a6e43d2dbfaad11df5131 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_1.v @@ -0,0 +1,1113 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_mcontrol_1( + already_match, + cp0_dtu_icg_en, + cp0_dtu_wdata, + cp0_write_tdata1, + cp0_write_tdata2, + cp0_write_tdata3, + cp0_yy_clk_en, + cpurst_b, + exe0_16bit, + exe0_32bit, + exe0_match, + exe0_may_hit, + exe1_16bit, + exe1_32bit, + exe1_match, + exe1_may_hit, + exe_mcontrol, + forever_cpuclk, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ldst_16bit, + ldst_32bit, + ldst_8bit, + ldst_addr_mcontrol, + ldst_data_mcontrol, + ldst_match, + ldst_may_hit, + ldst_mcontrol, + load_addr_vld, + load_data_vld, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + m_mode, + mcontext, + mpriority, + mpriority_after_chain, + mpriority_mask, + mpriority_mask_after_chain, + mtiming, + mtiming_after_chain, + mtiming_mask, + mtiming_mask_after_chain, + next_mpriority, + next_mpriority_mask, + next_mtiming, + next_mtiming_mask, + next_trigger_chain, + next_trigger_dmode, + pad_yy_icg_scan_en, + previous_mpriority, + previous_mpriority_mask, + previous_mtiming, + previous_mtiming_mask, + previous_trigger_chian, + previous_trigger_dmode, + rtu_yy_xx_dbgon, + set_trigger_hit, + store_addr_vld, + store_data_vld, + tcontrol, + tdata1, + tdata1_action0, + tdata1_action1, + tdata1_chain, + tdata1_dmode, + tdata1_timing, + tdata2, + tdata3, + tinfo, + trigger_selected, + u_mode +); + +// &Ports; @24 +input already_match; +input cp0_dtu_icg_en; +input [31:0] cp0_dtu_wdata; +input cp0_write_tdata1; +input cp0_write_tdata2; +input cp0_write_tdata3; +input cp0_yy_clk_en; +input cpurst_b; +input exe0_16bit; +input exe0_32bit; +input exe1_16bit; +input exe1_32bit; +input forever_cpuclk; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input ldst_16bit; +input ldst_32bit; +input ldst_8bit; +input load_addr_vld; +input load_data_vld; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input m_mode; +input [31:0] mcontext; +input [1 :0] next_mpriority; +input [1 :0] next_mpriority_mask; +input next_mtiming; +input next_mtiming_mask; +input next_trigger_chain; +input next_trigger_dmode; +input pad_yy_icg_scan_en; +input [1 :0] previous_mpriority; +input [1 :0] previous_mpriority_mask; +input previous_mtiming; +input previous_mtiming_mask; +input previous_trigger_chian; +input previous_trigger_dmode; +input rtu_yy_xx_dbgon; +input set_trigger_hit; +input store_addr_vld; +input store_data_vld; +input [31:0] tcontrol; +input trigger_selected; +input u_mode; +output exe0_match; +output exe0_may_hit; +output exe1_match; +output exe1_may_hit; +output exe_mcontrol; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output ldst_match; +output ldst_may_hit; +output ldst_mcontrol; +output [1 :0] mpriority; +output [1 :0] mpriority_after_chain; +output [1 :0] mpriority_mask; +output [1 :0] mpriority_mask_after_chain; +output mtiming; +output mtiming_after_chain; +output mtiming_mask; +output mtiming_mask_after_chain; +output [31:0] tdata1; +output tdata1_action0; +output tdata1_action1; +output tdata1_chain; +output tdata1_dmode; +output tdata1_timing; +output [31:0] tdata2; +output [31:0] tdata3; +output [31:0] tinfo; + +// &Regs; @25 +reg dmode_legal; +reg exe0_match; +reg exe1_match; +reg ldst_match; +reg [3 :0] m_mask_four_bits; +reg [7 :0] m_mask_reg; +reg match_ldst_addr; +reg [1 :0] mpriority; +reg [1 :0] mpriority_mask; +reg size1; +reg size2; +reg [31:0] size_mask; +reg tdata1_action; +reg tdata1_dmode; +reg tdata1_execute; +reg tdata1_hit; +reg tdata1_load; +reg tdata1_m; +reg [3 :0] tdata1_match; +reg [1 :0] tdata1_sizelo; +reg tdata1_store; +reg tdata1_timing; +reg tdata1_u; +reg [31:0] tdata2; +reg [7 :0] tdata2_ldst_bytes_vld_0; +reg [3 :0] tdata2_ldst_bytes_vld_for_match1_four_bits; +reg [3 :0] tdata2_ldst_bytes_vld_four_bits; +reg [7 :0] tdata2_ldst_bytes_vld_reg_0; +reg tdata3_mselect; +reg [5 :0] tdata3_mvalue; +reg write_tdata1_f; +reg write_tdata2_f; + +// &Wires; @26 +wire action_is_legal; +wire action_legal; +wire already_match; +wire bytes_vld_match; +wire cp0_dtu_icg_en; +wire [31:0] cp0_dtu_wdata; +wire cp0_write_tdata1; +wire cp0_write_tdata2; +wire cp0_write_tdata3; +wire cp0_yy_clk_en; +wire cpurst_b; +wire exe0_16bit; +wire exe0_32bit; +wire exe0_have_value_match0; +wire exe0_have_value_match1; +wire exe0_match_equal; +wire exe0_match_need_reg; +wire exe0_match_top_mbits_equal; +wire exe0_may_hit; +wire exe0_size_match; +wire exe0_type_match; +wire exe0_type_size_match; +wire [31:0] exe0_value; +wire [31:0] exe0_value_before_size_mask; +wire [7 :0] exe0_value_masked_low_8bis; +wire exe0_value_match; +wire [31:0] exe0_value_top_mbits; +wire exe1_16bit; +wire exe1_32bit; +wire exe1_have_value_match0; +wire exe1_have_value_match1; +wire exe1_match_equal; +wire exe1_match_need_reg; +wire exe1_match_top_mbits_equal; +wire exe1_may_hit; +wire exe1_size_match; +wire exe1_type_match; +wire exe1_type_size_match; +wire [31:0] exe1_value; +wire [31:0] exe1_value_before_size_mask; +wire [7 :0] exe1_value_masked_low_8bis; +wire exe1_value_match; +wire [31:0] exe1_value_top_mbits; +wire exe_addr_mcontrol; +wire exe_data_mcontrol; +wire exe_mcontrol; +wire exe_size_is_legal; +wire forever_cpuclk; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire ldst_16bit; +wire ldst_32bit; +wire ldst_8bit; +wire ldst_addr_match_equal; +wire ldst_addr_mcontrol; +wire ldst_addr_top_mbits_equal; +wire ldst_bytes_vld_equal; +wire ldst_bytes_vld_mbits_equal; +wire ldst_data_mcontrol; +wire ldst_have_value_match0; +wire ldst_have_value_match1; +wire [7 :0] ldst_m_mask; +wire ldst_match_equal; +wire ldst_match_need_reg; +wire ldst_match_top_mbits_equal; +wire ldst_may_hit; +wire ldst_mcontrol; +wire ldst_mcontrol_match; +wire ldst_size_is_legal; +wire ldst_size_match; +wire ldst_type_match; +wire ldst_type_size_match; +wire [31:0] ldst_value; +wire [31:0] ldst_value_before_size_mask; +wire ldst_value_equal; +wire [7 :0] ldst_value_masked_low_8bis; +wire ldst_value_match; +wire [31:0] ldst_value_top_mbits; +wire ldst_value_top_mbits_equal; +wire load_addr_mcontrol; +wire load_addr_vld; +wire load_data_mcontrol; +wire load_data_trigger; +wire load_data_vld; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire lsu_dtu_ldst_data_vld; +wire lsu_have_bytes_vld; +wire m_enable; +wire [7 :0] m_mask; +wire m_mode; +wire [5 :0] maskmax; +wire match_is_legal; +wire [3 :0] match_legal; +wire [31:0] mcontext; +wire mcontext_enable; +wire mcontext_must_match; +wire [1 :0] mpriority_after_chain; +wire [1 :0] mpriority_mask_after_chain; +wire ms_context_enable; +wire msu_mode_enable; +wire mtiming; +wire mtiming_after_chain; +wire mtiming_mask; +wire mtiming_mask_after_chain; +wire not_dbg_mode_enable; +wire pad_yy_icg_scan_en; +wire previous_trigger_chian; +wire previous_trigger_dmode; +wire rtu_yy_xx_dbgon; +wire set_trigger_hit; +wire size_is_legal; +wire [1 :0] size_legal; +wire store_addr_mcontrol; +wire store_addr_vld; +wire store_data_mcontrol; +wire store_data_vld; +wire [31:0] tcontrol; +wire tcontrol_enable; +wire [31:0] tdata1; +wire tdata1_action0; +wire tdata1_action1; +wire tdata1_chain; +wire tdata1_chain_for_macro; +wire tdata1_execute_for_macro; +wire tdata1_load_for_macro; +wire tdata1_matchinfo_clk; +wire tdata1_matchinfo_clk_en; +wire tdata1_select_for_macro; +wire [1 :0] tdata1_size; +wire tdata1_store_for_macro; +wire tdata23_clk; +wire tdata23_clk_en; +wire [3 :0] tdata2_4bits_value_for_m_mask; +wire [7 :0] tdata2_exe_value_masked_low_8bits; +wire [31:0] tdata2_exe_value_top_mbits; +wire [7 :0] tdata2_ldst_addr_masked_low_8bits; +wire [7 :0] tdata2_ldst_bytes_vld; +wire [7 :0] tdata2_ldst_bytes_vld_for_match1; +wire [31:0] tdata2_ldst_value_top_mbits; +wire [31:0] tdata2_value; +wire [31:0] tdata2_value_before_size_mask; +wire [31:0] tdata3; +wire tdata_writable; +wire timing_exe_or_wdata; +wire timing_legal; +wire [31:0] tinfo; +wire tri_already_match; +wire trigger_enable; +wire trigger_selected; +wire [3 :0] type_legal; +wire u_enable; +wire u_mode; +wire [1 :0] wdata_tdata1_size; +wire write_tdata1; +wire write_tdata2; +wire zero_lsb_higher_than_4; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; +//parameter (`TDT_DM_CORE_HALF_XLEN) = (`TDT_DM_CORE_HALF_XLEN); + +//tdata1 parameter +parameter TYPE_TDATA1 = XLEN-1; +parameter DMODE = XLEN-5; + +//mcontrol parameter +parameter SIZEHI = 22; +parameter HIT = 20; +parameter SELECT_TDATA1 = 19; +parameter TIMING = 18; +parameter SIZELO = 17; +parameter ACTION = 15; +parameter CHAIN = 11; +parameter MATCH = 10; +parameter M = 6; +parameter S = 4; +parameter U = 3; +parameter EXECUTE = 2; +parameter STORE = 1; +parameter LOAD = 0; + +//tdata3 parameter +parameter MVALUE = 31; +parameter MSELECT_TDATA1 = 25; + +//tcontrol parameter +//parameter MPTE = 7; +parameter MTE = 3; + +//========================================================= +// +// tdata1 wdata legalization +// +//========================================================= + +//type +assign type_legal[3:0] = 4'd2;//mcontrol type = 2 + +//dmode +// &CombBeg; @70 +always @( rtu_yy_xx_dbgon + or previous_trigger_dmode + or cp0_dtu_wdata[27] + or tdata1[27] + or previous_trigger_chian) +begin + if(!rtu_yy_xx_dbgon)//dmode only writable in debug mode + dmode_legal = tdata1[DMODE]; + else if(!previous_trigger_dmode && previous_trigger_chian) + dmode_legal = 1'b0; + else + dmode_legal = cp0_dtu_wdata[DMODE]; +// &CombEnd; @77 +end + +//--------------------------------------------------------- +// mcontrol tdata1 wdata legalization +//--------------------------------------------------------- +//size +assign wdata_tdata1_size[1:0] = cp0_dtu_wdata[SIZELO:SIZELO-1]; +assign exe_size_is_legal = cp0_dtu_wdata[EXECUTE] && (wdata_tdata1_size[1:0] == 2'd0 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3);//exe only suppurt size = 0,2,3 + +assign ldst_size_is_legal = (cp0_dtu_wdata[LOAD] || cp0_dtu_wdata[STORE]) && (wdata_tdata1_size[1:0] == 2'd0 || wdata_tdata1_size[1:0] == 2'd1 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3); +// &Force("nonport","ldst_size_is_legal"); @97 +assign size_is_legal = exe_size_is_legal || ldst_size_is_legal; +assign size_legal[1:0] = size_is_legal ? wdata_tdata1_size[1:0] : 2'b0; + +//action +assign action_is_legal = cp0_dtu_wdata[ACTION:ACTION-2] == 3'd0 && dmode_legal; +//(1)action <= 1;(2)dmode=1;action can be set to 0 or 1. +assign action_legal = action_is_legal ? cp0_dtu_wdata[ACTION-3] : 1'b0; + +//match +assign match_is_legal = cp0_dtu_wdata[MATCH:MATCH-3] == 4'd0 || cp0_dtu_wdata[MATCH:MATCH-3] == 4'd1; + +assign match_legal[3:0] = match_is_legal ? cp0_dtu_wdata[MATCH:MATCH-3] : 4'b0; + +//timing +assign load_data_trigger = 1'b0; +assign timing_exe_or_wdata = cp0_dtu_wdata[EXECUTE] ? 1'b0 : cp0_dtu_wdata[TIMING]; +assign timing_legal = load_data_trigger ? 1'b1 : timing_exe_or_wdata; + +//chain +//1.if previous trigger chain=1, this trigger chain can't set to 1. +//2.if next trigger chain=1, this trigger chain can't set to 1. +//3.if next trigger dmode =1, this write operation will set this trigger dmode to 0, +//then the write operation can't set this trigger chain to 1. +// &Force("input","previous_trigger_chian"); @146 +// &Force("input","next_trigger_chain"); @147 +// &Force("input","next_trigger_dmode"); @148 +// &Force("input","previous_trigger_chian"); @155 +// &Force("input","next_trigger_chain"); @156 +// &Force("input","next_trigger_dmode"); @157 + +//--------------------------------------------------------- +// legal tdata1 wdata +//--------------------------------------------------------- +assign maskmax[5:0] = 6'd8;//TODO + +//========================================================= +// +// write trigger CSR +// +//========================================================= + +//--------------------------------------------------------- +// write and update tdata1 +//--------------------------------------------------------- + +assign tdata_writable = !tdata1[DMODE] && (m_mode || rtu_yy_xx_dbgon) || + tdata1[DMODE] && rtu_yy_xx_dbgon; +assign write_tdata1 = cp0_write_tdata1 && trigger_selected && tdata_writable; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata1_dmode <= 1'b0; + tdata1_timing <= 1'b0; + tdata1_sizelo[1:0] <= 2'b0; + tdata1_action <= 1'b0; + tdata1_match[3:0] <= 4'b0; + tdata1_m <= 1'b0; + tdata1_u <= 1'b0; + tdata1_store <= 1'b0; + tdata1_load <= 1'b0; + tdata1_execute <= 1'b0; + end + else if(write_tdata1) + begin + tdata1_dmode <= dmode_legal; + tdata1_timing <= timing_legal; + tdata1_sizelo[1:0] <= size_legal[1:0]; + tdata1_action <= action_legal; + tdata1_match[3:0] <= match_legal[3:0]; + tdata1_m <= cp0_dtu_wdata[M]; + tdata1_u <= cp0_dtu_wdata[U]; + tdata1_store <= cp0_dtu_wdata[STORE]; + tdata1_load <= cp0_dtu_wdata[LOAD]; + tdata1_execute <= cp0_dtu_wdata[EXECUTE]; + end +end +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + size1 <= 1'b0; + size2 <= 1'b0; + end + else if(write_tdata1) + begin + size1 <= size_legal[1:0] == 2'd1; + size2 <= size_legal[1:0] == 2'd2; + end +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata1_hit <= 1'b0; + else if(set_trigger_hit) + tdata1_hit <= 1'b1; + else if(write_tdata1) + tdata1_hit <= cp0_dtu_wdata[HIT]; +end + + assign tdata1_select_for_macro = 1'b0; +assign tdata1_execute_for_macro = tdata1_execute; + assign tdata1_store_for_macro = tdata1_store; + assign tdata1_load_for_macro = tdata1_load; + +assign tdata1_chain = 1'b0; +assign tdata1_chain_for_macro = tdata1_chain; + +assign tdata1[XLEN-1:0] = {type_legal[3:0],tdata1_dmode,maskmax[5:0], + tdata1_hit,tdata1_select_for_macro,tdata1_timing,tdata1_sizelo[1:0],3'b0,tdata1_action, + tdata1_chain_for_macro,tdata1_match[3:0],tdata1_m,1'b0,1'b0,tdata1_u, + tdata1_execute_for_macro,tdata1_store_for_macro,tdata1_load_for_macro}; + +// &Force("output","tdata1");&Force("bus","tdata1",XLEN-1,0); @291 + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata1_f <= 1'b0; + else + write_tdata1_f <= write_tdata1; +end +// &Force("nonport","write_tdata1_f"); @300 +//tdata1 output +// &Force("output","tdata1_chain"); @302 +// &Force("output","tdata1_dmode"); @303 +// &Force("output","tdata1_timing"); @304 +//assign tdata1_chain = tdata1[CHAIN]; +//assign tdata1_dmode = tdata1[DMODE]; +assign tdata1_action0 = !tdata1[ACTION-3]; +assign tdata1_action1 = tdata1[ACTION-3]; +//assign tdata1_timing = tdata1[TIMING]; + +//--------------------------------------------------------- +// write tdata2 +//--------------------------------------------------------- +assign write_tdata2 = cp0_write_tdata2 && trigger_selected && tdata_writable; +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2[XLEN-1:0] <= {XLEN{1'b0}}; + else if(write_tdata2) + tdata2[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; +end +// &Force("output","tdata2");&Force("bus","tdata2",XLEN-1,0); @322 + +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata2_f <= 1'b0; + else + write_tdata2_f <= write_tdata2; +end +// &Force("nonport","write_tdata2_f"); @331 +//--------------------------------------------------------- +// write tdata3 +//--------------------------------------------------------- + +//write tdata3 +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata3_mvalue[5:0] <= 6'b0; + tdata3_mselect <= 1'b0; + end + else if(cp0_write_tdata3 && trigger_selected && tdata_writable) + begin + tdata3_mvalue[5:0] <= cp0_dtu_wdata[MVALUE:MVALUE-5]; + tdata3_mselect <= cp0_dtu_wdata[MSELECT_TDATA1]; + end +end +assign tdata3[XLEN-1:0] = {tdata3_mvalue[5:0],tdata3_mselect,25'b0}; +// &Force("output","tdata3");&Force("bus","tdata3",XLEN-1,0); @351 +//--------------------------------------------------------- +// tinfo(read only) +//--------------------------------------------------------- +assign tinfo[XLEN-1:0] = {{XLEN-3{1'b0}},3'b100}; +// &Force("output","tinfo");&Force("bus","tinfo",XLEN-1,0); @356 +//mcontrol type =2 + +//========================================================= +// +// decode +// +//========================================================= +//--------------------------------------------------------- +// trigger enable signal +//--------------------------------------------------------- +//tcontrol enable +//assign tdata1_action[3:0] = tdata1[ACTION:ACTION-3]; + +assign tcontrol_enable = !(!tcontrol[MTE] && !tdata1_action && m_mode);//!(MTE=0 && action=0 && m_mode) +// &Force("bus","tcontrol",XLEN-1,0); @371 + +//m s context enable +assign mcontext_must_match = tdata3[MSELECT_TDATA1] && m_mode; +assign mcontext_enable = mcontext_must_match ? tdata3[MVALUE:MVALUE-5] == mcontext[5:0] : 1'b1; +// &Force("bus","mcontext",XLEN-1,0); @376 + +assign ms_context_enable = mcontext_enable; +assign m_enable = tdata1[M] && m_mode; +assign u_enable = tdata1[U] && u_mode; + +assign msu_mode_enable = m_enable || u_enable; + +//trigger can't match in debug mode +assign not_dbg_mode_enable = !rtu_yy_xx_dbgon; + +//trigger enable +assign trigger_enable = tcontrol_enable && ms_context_enable && + msu_mode_enable && not_dbg_mode_enable; + +//--------------------------------------------------------- +// information for match +//--------------------------------------------------------- +//type of mcontrol +assign exe_mcontrol = tdata1[EXECUTE]; +assign ldst_mcontrol = tdata1[LOAD] || tdata1[STORE]; +// &Force("output","exe_mcontrol"); @397 +// &Force("output","ldst_mcontrol"); @398 +assign exe_addr_mcontrol = tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]; +assign exe_data_mcontrol = tdata1[EXECUTE] && tdata1[SELECT_TDATA1]; + +assign store_addr_mcontrol = tdata1[STORE] && !tdata1[SELECT_TDATA1]; +assign store_data_mcontrol = tdata1[STORE] && tdata1[SELECT_TDATA1]; +//assign load_mcontrol = tdata1[LOAD]; +//assign ldst_mcontrol = store_mcontrol && load_mcontrol; +assign load_addr_mcontrol = tdata1[LOAD] && !tdata1[SELECT_TDATA1]; +assign load_data_mcontrol = tdata1[LOAD] && tdata1[SELECT_TDATA1]; + +assign ldst_addr_mcontrol = store_addr_mcontrol || load_addr_mcontrol; +assign ldst_data_mcontrol = store_data_mcontrol || load_data_mcontrol; +//priorty +// &CombBeg; @414 +always @( tdata1[2] + or tdata1[19]) +begin + if(tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b10; + mpriority_mask[1:0] = 2'b00; + end + else if(tdata1[EXECUTE] && tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b01; + mpriority_mask[1:0] = 2'b10; + end + else//ldst mcontrol or no mcontrol + begin + mpriority[1:0] = 2'b00; + mpriority_mask[1:0] = 2'b11; + end +// &CombEnd; @430 +end +//mtiming +assign mtiming = !tdata1[TIMING]; +assign mtiming_mask = tdata1[TIMING]; +// &Force("output","mpriority");&Force("bus","mpriority",1,0); @434 +// &Force("output","mpriority_mask");&Force("bus","mpriority_mask",1,0); @435 +// &Force("output","mtiming"); @436 +// &Force("output","mtiming_mask"); @437 + +// &CombBeg; @443 +// &CombEnd; @459 +// &CombBeg; @463 +// &CombEnd; @479 +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @480 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @481 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @482 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @483 +// &Force("input","previous_mtiming"); @484 +// &Force("input","previous_mtiming_mask"); @485 +// &Force("input","next_mtiming"); @486 +// &Force("input","next_mtiming_mask"); @487 +assign mpriority_after_chain[1:0] = mpriority[1:0]; +assign mpriority_mask_after_chain[1:0]= mpriority_mask[1:0]; +assign mtiming_after_chain = mtiming; +assign mtiming_mask_after_chain = mtiming_mask; +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @493 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @494 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @495 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @496 +// &Force("input","previous_mtiming"); @497 +// &Force("input","previous_mtiming_mask"); @498 +// &Force("input","next_mtiming"); @499 +// &Force("input","next_mtiming_mask"); @500 + +//size +assign tdata1_size[1:0] = tdata1[SIZELO:SIZELO-1]; + +//assign size_mask_63_32 = !(size1 || size2 || size3); +//assign size_mask_31_16 = !(size1 || size2); +//assign size_mask_15_8 = !size1; +//assign size_mask[XLEN-1:0] = {{32{size_mask_63_32}},{16{size_mask_31_16}},{8{size_mask_15_8}},{8{1'b1}}}; +// &CombBeg; @510 +always @( size1 + or size2) +begin + if(size1) + size_mask[XLEN-1:0] = 32'h0000_00ff; + else if(size2) + size_mask[XLEN-1:0] = 32'h0000_ffff; + else + size_mask[XLEN-1:0] = 32'hffff_ffff; +// &CombEnd; @517 +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + match_ldst_addr <= 1'b0; + else if(!tdata1[SELECT_TDATA1] && (tdata1[LOAD] || tdata1[STORE])) + match_ldst_addr <= 1'b1; + else if(tdata1[LOAD] || tdata1[STORE] || tdata1[EXECUTE]) + match_ldst_addr <= 1'b0; +end + +//tdata2 need to be masked off by size +assign tdata2_value_before_size_mask[XLEN-1:0] = {tdata2[XLEN-1:3], tdata2[2:0] & {3{!match_ldst_addr}}}; +assign tdata2_value[XLEN-1:0] = tdata2_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//translate tdata2[23:20] to bytes_vld. when select = 0, match = 4. +//tdata2_ldst_value_lower_half == ldst_value_lower_half & tdata2_exe_value_upper_half +//tdata2_ldst_bytes_vld == lsu_dtu_ldst_bytes_vld & tdata2_ldst_bytes_vld_for_match4 + + //tdata2[3:0] generate low_bytes_vld +// &CombBeg; @558 +always @( tdata2[1:0]) +begin + case(tdata2[1:0]) + 2'b00: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0001; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b0011; + end + 2'b01: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0010; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + 2'b10: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0100; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1100; + end + 2'b11: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b1000; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + default: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = {4{1'bx}}; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = {4{1'bx}}; + end + endcase +// &CombEnd; @611 +end +assign tdata2_ldst_bytes_vld[7:0] = tdata2[2] ? {tdata2_ldst_bytes_vld_four_bits[3:0],4'b0} : {4'b0,tdata2_ldst_bytes_vld_four_bits[3:0]}; +assign tdata2_ldst_bytes_vld_for_match1[7:0] = tdata2[2] ? {{4{tdata2[1] && tdata2[0]}},tdata2_ldst_bytes_vld_for_match1_four_bits[3:0]} : + {tdata2_ldst_bytes_vld_for_match1_four_bits[3:0],{4{tdata2[1] && tdata2[0]}}}; +//when tdata2[1] && tdata2[0] = 1, bytes_vld_for_match1 should be 8'bff no matter what tdata2[2] is + +// &CombBeg; @625 +// &CombEnd; @642 + +// &CombBeg; @645 +always @( tdata2_ldst_bytes_vld_for_match1[7:0] + or tdata2_ldst_bytes_vld[7:0] + or tdata1[10:7]) +begin + case(tdata1[MATCH:MATCH-3]) + 4'd0:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld[7:0]; + 4'd1:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld_for_match1[7:0]; + default:tdata2_ldst_bytes_vld_0[7:0] = {8{1'bx}}; + endcase +// &CombEnd; @661 +end + +//when match = 4, need reg_0 and reg_1 both. +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2_ldst_bytes_vld_reg_0[7:0] <= 8'b0; + else if(tdata1[STORE] && !tdata1[SELECT_TDATA1] || tdata1[LOAD] && !tdata1[SELECT_TDATA1]) + tdata2_ldst_bytes_vld_reg_0[7:0] <= tdata2_ldst_bytes_vld_0[7:0]; +end + +//----------------------maksed value for match = 1------------------------------------ +assign zero_lsb_higher_than_4 = tdata2[3:0] == 4'b1111; +assign tdata2_4bits_value_for_m_mask[3:0] = zero_lsb_higher_than_4 ? tdata2[7:4] : tdata2[3:0]; +// &CombBeg; @677 +always @( tdata2_4bits_value_for_m_mask[3:0]) +begin + //m_mask and ldst_addr_mask(maskmax = 8). the low 4 bit of ldst addr are 0 + casez(tdata2_4bits_value_for_m_mask[3:0]) + 4'b???0:m_mask_four_bits[3:0] = 4'b1110; + 4'b??01:m_mask_four_bits[3:0] = 4'b1100; + 4'b?011:m_mask_four_bits[3:0] = 4'b1000; + 4'b0111:m_mask_four_bits[3:0] = 4'b0000; + 4'b1111:m_mask_four_bits[3:0] = 4'b0000; + default:m_mask_four_bits[3:0] = {4{1'bx}}; + endcase +// &CombEnd; @687 +end + +assign m_mask[7:0] = zero_lsb_higher_than_4 ? {m_mask_four_bits[3:0],4'b0} : {4'b1111,m_mask_four_bits[3:0]}; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + m_mask_reg[7:0] <= 8'b11111111; + else if(tdata1[MATCH:MATCH-3] == 4'b1) + m_mask_reg[7:0] <= m_mask[7:0]; +end + +//exe top M bits +assign tdata2_exe_value_masked_low_8bits[7:0] = tdata2_value[7:0] & m_mask_reg[7:0]; +assign tdata2_exe_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_exe_value_masked_low_8bits[7:0]}; + +//ldst top M bits +assign ldst_m_mask[7:0] = tdata1[SELECT_TDATA1] ? m_mask_reg[7:0] : {m_mask_reg[7:3],3'b0}; +assign tdata2_ldst_addr_masked_low_8bits[7:0] = tdata2_value[7:0] & ldst_m_mask[7:0]; +assign tdata2_ldst_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_ldst_addr_masked_low_8bits[7:0]}; + +//========================================================= +// +// exe0 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe0 type match and size match +//--------------------------------------------------------- +assign exe0_type_match = ifu_dtu_addr_vld0 && exe_addr_mcontrol || ifu_dtu_data_vld0 && exe_data_mcontrol; +assign exe0_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe0_16bit || + tdata1_size[1:0] == 2'd3 && exe0_32bit || (ifu_dtu_addr_vld0 && !ifu_dtu_data_vld0); +assign exe0_type_size_match = exe0_type_match && exe0_size_match && trigger_enable; +//--------------------------------------------------------- +// exe0 value match +//--------------------------------------------------------- +//value for exe0 trigger match +assign exe0_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr0[`PA_WIDTH-1:0]; +assign exe0_value[XLEN-1:0] = exe0_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe0_value_masked_low_8bis[7:0] = exe0_value[7:0] & m_mask_reg[7:0]; +assign exe0_value_top_mbits[XLEN-1:0] = {exe0_value[XLEN-1:8],exe0_value_masked_low_8bis[7:0]}; + +//value match +assign exe0_match_equal = exe0_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe0_match_top_mbits_equal = exe0_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + +assign exe0_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe0_match_equal; +assign exe0_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe0_match_top_mbits_equal; + +assign exe0_value_match = exe0_have_value_match0 || exe0_have_value_match1; +//--------------------------------------------------------- +// exe0 match result +//--------------------------------------------------------- +assign exe0_match_need_reg = exe0_value_match && exe0_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe0_match <= 1'b0; + else + exe0_match <= exe0_match_need_reg; +end +// &Force("output","exe0_match"); @820 + +assign exe0_may_hit = exe0_value_match;// && ifu_dtu_addr_vld0; + +//========================================================= +// +// exe1 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe1 type match and size match +//--------------------------------------------------------- +assign exe1_type_match = ifu_dtu_addr_vld1 && exe_addr_mcontrol || ifu_dtu_data_vld1 && exe_data_mcontrol; +assign exe1_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe1_16bit || + tdata1_size[1:0] == 2'd3 && exe1_32bit || (ifu_dtu_addr_vld1 && !ifu_dtu_data_vld1); +assign exe1_type_size_match = exe1_type_match && exe1_size_match && trigger_enable; +//--------------------------------------------------------- +// exe1 value match +//--------------------------------------------------------- +//value for exe1 trigger match +assign exe1_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr1[`PA_WIDTH-1:0]; +assign exe1_value[XLEN-1:0] = exe1_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe1_value_masked_low_8bis[7:0] = exe1_value[7:0] & m_mask_reg[7:0]; +assign exe1_value_top_mbits[XLEN-1:0] = {exe1_value[XLEN-1:8],exe1_value_masked_low_8bis[7:0]}; + +//value match +assign exe1_match_equal = exe1_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe1_match_top_mbits_equal = exe1_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + + +assign exe1_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe1_match_equal; +assign exe1_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe1_match_top_mbits_equal; + +assign exe1_value_match = exe1_have_value_match0 || exe1_have_value_match1; +//--------------------------------------------------------- +// exe1 match result +//--------------------------------------------------------- +assign exe1_match_need_reg = exe1_value_match && exe1_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe1_match <= 1'b0; + else + exe1_match <= exe1_match_need_reg; +end +// &Force("output","exe1_match"); @916 + +assign exe1_may_hit = exe1_value_match;// && ifu_dtu_addr_vld1; +// &Force("input","exe0_16bit"); @920 +// &Force("input","exe0_32bit"); @921 +// &Force("input","exe1_16bit"); @922 +// &Force("input","exe1_32bit"); @923 +// &Force("input","ifu_dtu_addr_vld0"); @924 +// &Force("input","ifu_dtu_addr_vld1"); @925 +// &Force("input","ifu_dtu_data_vld0"); @926 +// &Force("input","ifu_dtu_data_vld1"); @927 +// &Force("input","ifu_dtu_exe_addr0");&Force("bus","ifu_dtu_exe_addr0",`PA_WIDTH-1,0); @928 +// &Force("input","ifu_dtu_exe_addr1");&Force("bus","ifu_dtu_exe_addr1",`PA_WIDTH-1,0); @929 +// &Force("input","ifu_dtu_exe_data0");&Force("bus","ifu_dtu_exe_data0",31,0); @930 +// &Force("input","ifu_dtu_exe_data1");&Force("bus","ifu_dtu_exe_data1",31,0); @931 +// &Force("output","exe0_match"); @932 +// &Force("output","exe1_match"); @933 + +//========================================================= +// +// ldst match logic +// +//========================================================= +//--------------------------------------------------------- +// ldst type match and size match +//--------------------------------------------------------- +assign ldst_type_match = store_addr_vld && store_addr_mcontrol || + store_data_vld && store_data_mcontrol || + load_addr_vld && load_addr_mcontrol || + load_data_vld && load_data_mcontrol; +assign ldst_size_match = tdata1_size[1:0] == 2'd0 || size1 && ldst_8bit || + size2 && ldst_16bit || tdata1_size[1:0] == 2'd3 && ldst_32bit; +assign ldst_type_size_match = ldst_type_match && ldst_size_match && trigger_enable; + +//--------------------------------------------------------- +// ldst value match +//--------------------------------------------------------- +//value for ldst trigger match +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @963 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @964 +assign ldst_value_before_size_mask[XLEN-1:0] = {lsu_dtu_ldst_addr[`PA_WIDTH-1:3],3'b0}; + +assign ldst_value[XLEN-1:0] = ldst_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//masked value +assign ldst_value_masked_low_8bis[7:0] = ldst_value[7:0] & ldst_m_mask[7:0]; +assign ldst_value_top_mbits[XLEN-1:0] = {ldst_value[XLEN-1:8],ldst_value_masked_low_8bis[7:0]}; + +//value match +assign lsu_have_bytes_vld = |lsu_dtu_ldst_bytes_vld[7:0]; +// &Force("nonport","lsu_have_bytes_vld"); @990 +assign bytes_vld_match = |(lsu_dtu_ldst_bytes_vld[7:0] & tdata2_ldst_bytes_vld_reg_0[7:0]); +//match = 0 +assign ldst_value_equal = ldst_value[XLEN-1:0] == tdata2_value[XLEN-1:0]; +assign ldst_bytes_vld_equal = bytes_vld_match; +assign ldst_addr_match_equal = ldst_bytes_vld_equal && ldst_value_equal; +assign ldst_match_equal = ldst_addr_match_equal; + +//match = 1 +assign ldst_value_top_mbits_equal = ldst_value_top_mbits[XLEN-1:0] == tdata2_ldst_value_top_mbits[XLEN-1:0]; +assign ldst_bytes_vld_mbits_equal = bytes_vld_match; +assign ldst_addr_top_mbits_equal = ldst_value_top_mbits_equal && ldst_bytes_vld_mbits_equal; +assign ldst_match_top_mbits_equal = ldst_addr_top_mbits_equal; + + + + +assign ldst_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && ldst_match_equal; +assign ldst_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && ldst_match_top_mbits_equal; + +assign ldst_value_match = ldst_have_value_match0 || ldst_have_value_match1; +//--------------------------------------------------------- +// ldst match result +//--------------------------------------------------------- +assign tri_already_match = already_match && (lsu_dtu_ldst_addr_vld || lsu_dtu_ldst_data_vld); +assign ldst_mcontrol_match = ldst_value_match && ldst_type_size_match; +assign ldst_match_need_reg = ldst_mcontrol_match || tri_already_match; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ldst_match <= 1'b0; + else + ldst_match <= ldst_match_need_reg; +end +// &Force("output","ldst_match"); @1176 +//assign ldst_may_hit = ldst_cycle2_cannot_match ? 1'b0 : ldst_match_need_reg; +assign ldst_may_hit = ldst_match_need_reg;//ldst_value_match || tri_already_match; +// &Force("input","already_match"); @1180 +// &Force("input","ldst_8bit"); @1181 +// &Force("input","ldst_16bit"); @1182 +// &Force("input","ldst_32bit"); @1183 +// &Force("input","store_addr_vld"); @1184 +// &Force("input","store_data_vld"); @1185 +// &Force("input","load_addr_vld"); @1186 +// &Force("input","load_data_vld"); @1187 +// &Force("input","lsu_dtu_ldst_addr_vld"); @1188 +// &Force("input","lsu_dtu_ldst_data_vld"); @1189 +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @1190 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @1191 +// &Force("input","lsu_dtu_ldst_bytes_vld");&Force("bus","lsu_dtu_ldst_bytes_vld",7,0); @1192 +// &Force("output","ldst_match"); @1193 + +//========================================================== +// gate clk +//========================================================== +assign tdata1_matchinfo_clk_en = trigger_selected && + (cp0_write_tdata1 || write_tdata2_f || write_tdata1_f) || + exe0_match_need_reg || exe0_match || + exe1_match_need_reg || exe1_match || + ldst_match_need_reg || ldst_match || + set_trigger_hit; +// &Instance("gated_clk_cell", "x_tdata1_matchinfo_reg_gated_clk"); @1208 +gated_clk_cell x_tdata1_matchinfo_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata1_matchinfo_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata1_matchinfo_clk_en), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @1209 +// .external_en (1'b0), @1210 +// .global_en (cp0_yy_clk_en), @1211 +// .module_en (cp0_dtu_icg_en), @1212 +// .local_en (tdata1_matchinfo_clk_en), @1213 +// //.local_en (1'b1), @1214 +// .clk_out (tdata1_matchinfo_clk)); @1215 + +//make tdata2, tdata3 a gated clk cell +assign tdata23_clk_en = trigger_selected && (cp0_write_tdata2 || cp0_write_tdata3 || write_tdata2_f); +// &Instance("gated_clk_cell", "x_tdata23_reg_gated_clk"); @1219 +gated_clk_cell x_tdata23_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata23_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata23_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @1220 +// .external_en (1'b0), @1221 +// .global_en (cp0_yy_clk_en), @1222 +// .module_en (cp0_dtu_icg_en), @1223 +// .local_en (tdata23_clk_en), @1224 +// //.local_en (1'b1), @1225 +// .clk_out (tdata23_clk)); @1226 +// &ModuleEnd; @1227 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_2.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_2.v new file mode 100644 index 0000000000000000000000000000000000000000..9ca4954aa22ee7e8f9d3026fbb5aef0714850dc6 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_2.v @@ -0,0 +1,1113 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_mcontrol_2( + already_match, + cp0_dtu_icg_en, + cp0_dtu_wdata, + cp0_write_tdata1, + cp0_write_tdata2, + cp0_write_tdata3, + cp0_yy_clk_en, + cpurst_b, + exe0_16bit, + exe0_32bit, + exe0_match, + exe0_may_hit, + exe1_16bit, + exe1_32bit, + exe1_match, + exe1_may_hit, + exe_mcontrol, + forever_cpuclk, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ldst_16bit, + ldst_32bit, + ldst_8bit, + ldst_addr_mcontrol, + ldst_data_mcontrol, + ldst_match, + ldst_may_hit, + ldst_mcontrol, + load_addr_vld, + load_data_vld, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + m_mode, + mcontext, + mpriority, + mpriority_after_chain, + mpriority_mask, + mpriority_mask_after_chain, + mtiming, + mtiming_after_chain, + mtiming_mask, + mtiming_mask_after_chain, + next_mpriority, + next_mpriority_mask, + next_mtiming, + next_mtiming_mask, + next_trigger_chain, + next_trigger_dmode, + pad_yy_icg_scan_en, + previous_mpriority, + previous_mpriority_mask, + previous_mtiming, + previous_mtiming_mask, + previous_trigger_chian, + previous_trigger_dmode, + rtu_yy_xx_dbgon, + set_trigger_hit, + store_addr_vld, + store_data_vld, + tcontrol, + tdata1, + tdata1_action0, + tdata1_action1, + tdata1_chain, + tdata1_dmode, + tdata1_timing, + tdata2, + tdata3, + tinfo, + trigger_selected, + u_mode +); + +// &Ports; @24 +input already_match; +input cp0_dtu_icg_en; +input [31:0] cp0_dtu_wdata; +input cp0_write_tdata1; +input cp0_write_tdata2; +input cp0_write_tdata3; +input cp0_yy_clk_en; +input cpurst_b; +input exe0_16bit; +input exe0_32bit; +input exe1_16bit; +input exe1_32bit; +input forever_cpuclk; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input ldst_16bit; +input ldst_32bit; +input ldst_8bit; +input load_addr_vld; +input load_data_vld; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input m_mode; +input [31:0] mcontext; +input [1 :0] next_mpriority; +input [1 :0] next_mpriority_mask; +input next_mtiming; +input next_mtiming_mask; +input next_trigger_chain; +input next_trigger_dmode; +input pad_yy_icg_scan_en; +input [1 :0] previous_mpriority; +input [1 :0] previous_mpriority_mask; +input previous_mtiming; +input previous_mtiming_mask; +input previous_trigger_chian; +input previous_trigger_dmode; +input rtu_yy_xx_dbgon; +input set_trigger_hit; +input store_addr_vld; +input store_data_vld; +input [31:0] tcontrol; +input trigger_selected; +input u_mode; +output exe0_match; +output exe0_may_hit; +output exe1_match; +output exe1_may_hit; +output exe_mcontrol; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output ldst_match; +output ldst_may_hit; +output ldst_mcontrol; +output [1 :0] mpriority; +output [1 :0] mpriority_after_chain; +output [1 :0] mpriority_mask; +output [1 :0] mpriority_mask_after_chain; +output mtiming; +output mtiming_after_chain; +output mtiming_mask; +output mtiming_mask_after_chain; +output [31:0] tdata1; +output tdata1_action0; +output tdata1_action1; +output tdata1_chain; +output tdata1_dmode; +output tdata1_timing; +output [31:0] tdata2; +output [31:0] tdata3; +output [31:0] tinfo; + +// &Regs; @25 +reg dmode_legal; +reg exe0_match; +reg exe1_match; +reg ldst_match; +reg [3 :0] m_mask_four_bits; +reg [7 :0] m_mask_reg; +reg match_ldst_addr; +reg [1 :0] mpriority; +reg [1 :0] mpriority_mask; +reg size1; +reg size2; +reg [31:0] size_mask; +reg tdata1_action; +reg tdata1_dmode; +reg tdata1_execute; +reg tdata1_hit; +reg tdata1_load; +reg tdata1_m; +reg [3 :0] tdata1_match; +reg [1 :0] tdata1_sizelo; +reg tdata1_store; +reg tdata1_timing; +reg tdata1_u; +reg [31:0] tdata2; +reg [7 :0] tdata2_ldst_bytes_vld_0; +reg [3 :0] tdata2_ldst_bytes_vld_for_match1_four_bits; +reg [3 :0] tdata2_ldst_bytes_vld_four_bits; +reg [7 :0] tdata2_ldst_bytes_vld_reg_0; +reg tdata3_mselect; +reg [5 :0] tdata3_mvalue; +reg write_tdata1_f; +reg write_tdata2_f; + +// &Wires; @26 +wire action_is_legal; +wire action_legal; +wire already_match; +wire bytes_vld_match; +wire cp0_dtu_icg_en; +wire [31:0] cp0_dtu_wdata; +wire cp0_write_tdata1; +wire cp0_write_tdata2; +wire cp0_write_tdata3; +wire cp0_yy_clk_en; +wire cpurst_b; +wire exe0_16bit; +wire exe0_32bit; +wire exe0_have_value_match0; +wire exe0_have_value_match1; +wire exe0_match_equal; +wire exe0_match_need_reg; +wire exe0_match_top_mbits_equal; +wire exe0_may_hit; +wire exe0_size_match; +wire exe0_type_match; +wire exe0_type_size_match; +wire [31:0] exe0_value; +wire [31:0] exe0_value_before_size_mask; +wire [7 :0] exe0_value_masked_low_8bis; +wire exe0_value_match; +wire [31:0] exe0_value_top_mbits; +wire exe1_16bit; +wire exe1_32bit; +wire exe1_have_value_match0; +wire exe1_have_value_match1; +wire exe1_match_equal; +wire exe1_match_need_reg; +wire exe1_match_top_mbits_equal; +wire exe1_may_hit; +wire exe1_size_match; +wire exe1_type_match; +wire exe1_type_size_match; +wire [31:0] exe1_value; +wire [31:0] exe1_value_before_size_mask; +wire [7 :0] exe1_value_masked_low_8bis; +wire exe1_value_match; +wire [31:0] exe1_value_top_mbits; +wire exe_addr_mcontrol; +wire exe_data_mcontrol; +wire exe_mcontrol; +wire exe_size_is_legal; +wire forever_cpuclk; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire ldst_16bit; +wire ldst_32bit; +wire ldst_8bit; +wire ldst_addr_match_equal; +wire ldst_addr_mcontrol; +wire ldst_addr_top_mbits_equal; +wire ldst_bytes_vld_equal; +wire ldst_bytes_vld_mbits_equal; +wire ldst_data_mcontrol; +wire ldst_have_value_match0; +wire ldst_have_value_match1; +wire [7 :0] ldst_m_mask; +wire ldst_match_equal; +wire ldst_match_need_reg; +wire ldst_match_top_mbits_equal; +wire ldst_may_hit; +wire ldst_mcontrol; +wire ldst_mcontrol_match; +wire ldst_size_is_legal; +wire ldst_size_match; +wire ldst_type_match; +wire ldst_type_size_match; +wire [31:0] ldst_value; +wire [31:0] ldst_value_before_size_mask; +wire ldst_value_equal; +wire [7 :0] ldst_value_masked_low_8bis; +wire ldst_value_match; +wire [31:0] ldst_value_top_mbits; +wire ldst_value_top_mbits_equal; +wire load_addr_mcontrol; +wire load_addr_vld; +wire load_data_mcontrol; +wire load_data_trigger; +wire load_data_vld; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire lsu_dtu_ldst_data_vld; +wire lsu_have_bytes_vld; +wire m_enable; +wire [7 :0] m_mask; +wire m_mode; +wire [5 :0] maskmax; +wire match_is_legal; +wire [3 :0] match_legal; +wire [31:0] mcontext; +wire mcontext_enable; +wire mcontext_must_match; +wire [1 :0] mpriority_after_chain; +wire [1 :0] mpriority_mask_after_chain; +wire ms_context_enable; +wire msu_mode_enable; +wire mtiming; +wire mtiming_after_chain; +wire mtiming_mask; +wire mtiming_mask_after_chain; +wire not_dbg_mode_enable; +wire pad_yy_icg_scan_en; +wire previous_trigger_chian; +wire previous_trigger_dmode; +wire rtu_yy_xx_dbgon; +wire set_trigger_hit; +wire size_is_legal; +wire [1 :0] size_legal; +wire store_addr_mcontrol; +wire store_addr_vld; +wire store_data_mcontrol; +wire store_data_vld; +wire [31:0] tcontrol; +wire tcontrol_enable; +wire [31:0] tdata1; +wire tdata1_action0; +wire tdata1_action1; +wire tdata1_chain; +wire tdata1_chain_for_macro; +wire tdata1_execute_for_macro; +wire tdata1_load_for_macro; +wire tdata1_matchinfo_clk; +wire tdata1_matchinfo_clk_en; +wire tdata1_select_for_macro; +wire [1 :0] tdata1_size; +wire tdata1_store_for_macro; +wire tdata23_clk; +wire tdata23_clk_en; +wire [3 :0] tdata2_4bits_value_for_m_mask; +wire [7 :0] tdata2_exe_value_masked_low_8bits; +wire [31:0] tdata2_exe_value_top_mbits; +wire [7 :0] tdata2_ldst_addr_masked_low_8bits; +wire [7 :0] tdata2_ldst_bytes_vld; +wire [7 :0] tdata2_ldst_bytes_vld_for_match1; +wire [31:0] tdata2_ldst_value_top_mbits; +wire [31:0] tdata2_value; +wire [31:0] tdata2_value_before_size_mask; +wire [31:0] tdata3; +wire tdata_writable; +wire timing_exe_or_wdata; +wire timing_legal; +wire [31:0] tinfo; +wire tri_already_match; +wire trigger_enable; +wire trigger_selected; +wire [3 :0] type_legal; +wire u_enable; +wire u_mode; +wire [1 :0] wdata_tdata1_size; +wire write_tdata1; +wire write_tdata2; +wire zero_lsb_higher_than_4; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; +//parameter (`TDT_DM_CORE_HALF_XLEN) = (`TDT_DM_CORE_HALF_XLEN); + +//tdata1 parameter +parameter TYPE_TDATA1 = XLEN-1; +parameter DMODE = XLEN-5; + +//mcontrol parameter +parameter SIZEHI = 22; +parameter HIT = 20; +parameter SELECT_TDATA1 = 19; +parameter TIMING = 18; +parameter SIZELO = 17; +parameter ACTION = 15; +parameter CHAIN = 11; +parameter MATCH = 10; +parameter M = 6; +parameter S = 4; +parameter U = 3; +parameter EXECUTE = 2; +parameter STORE = 1; +parameter LOAD = 0; + +//tdata3 parameter +parameter MVALUE = 31; +parameter MSELECT_TDATA1 = 25; + +//tcontrol parameter +//parameter MPTE = 7; +parameter MTE = 3; + +//========================================================= +// +// tdata1 wdata legalization +// +//========================================================= + +//type +assign type_legal[3:0] = 4'd2;//mcontrol type = 2 + +//dmode +// &CombBeg; @70 +always @( rtu_yy_xx_dbgon + or previous_trigger_dmode + or cp0_dtu_wdata[27] + or tdata1[27] + or previous_trigger_chian) +begin + if(!rtu_yy_xx_dbgon)//dmode only writable in debug mode + dmode_legal = tdata1[DMODE]; + else if(!previous_trigger_dmode && previous_trigger_chian) + dmode_legal = 1'b0; + else + dmode_legal = cp0_dtu_wdata[DMODE]; +// &CombEnd; @77 +end + +//--------------------------------------------------------- +// mcontrol tdata1 wdata legalization +//--------------------------------------------------------- +//size +assign wdata_tdata1_size[1:0] = cp0_dtu_wdata[SIZELO:SIZELO-1]; +assign exe_size_is_legal = cp0_dtu_wdata[EXECUTE] && (wdata_tdata1_size[1:0] == 2'd0 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3);//exe only suppurt size = 0,2,3 + +assign ldst_size_is_legal = (cp0_dtu_wdata[LOAD] || cp0_dtu_wdata[STORE]) && (wdata_tdata1_size[1:0] == 2'd0 || wdata_tdata1_size[1:0] == 2'd1 || + wdata_tdata1_size[1:0] == 2'd2 || wdata_tdata1_size[1:0] == 2'd3); +// &Force("nonport","ldst_size_is_legal"); @97 +assign size_is_legal = exe_size_is_legal || ldst_size_is_legal; +assign size_legal[1:0] = size_is_legal ? wdata_tdata1_size[1:0] : 2'b0; + +//action +assign action_is_legal = cp0_dtu_wdata[ACTION:ACTION-2] == 3'd0 && dmode_legal; +//(1)action <= 1;(2)dmode=1;action can be set to 0 or 1. +assign action_legal = action_is_legal ? cp0_dtu_wdata[ACTION-3] : 1'b0; + +//match +assign match_is_legal = cp0_dtu_wdata[MATCH:MATCH-3] == 4'd0 || cp0_dtu_wdata[MATCH:MATCH-3] == 4'd1; + +assign match_legal[3:0] = match_is_legal ? cp0_dtu_wdata[MATCH:MATCH-3] : 4'b0; + +//timing +assign load_data_trigger = 1'b0; +assign timing_exe_or_wdata = cp0_dtu_wdata[EXECUTE] ? 1'b0 : cp0_dtu_wdata[TIMING]; +assign timing_legal = load_data_trigger ? 1'b1 : timing_exe_or_wdata; + +//chain +//1.if previous trigger chain=1, this trigger chain can't set to 1. +//2.if next trigger chain=1, this trigger chain can't set to 1. +//3.if next trigger dmode =1, this write operation will set this trigger dmode to 0, +//then the write operation can't set this trigger chain to 1. +// &Force("input","previous_trigger_chian"); @146 +// &Force("input","next_trigger_chain"); @147 +// &Force("input","next_trigger_dmode"); @148 +// &Force("input","previous_trigger_chian"); @155 +// &Force("input","next_trigger_chain"); @156 +// &Force("input","next_trigger_dmode"); @157 + +//--------------------------------------------------------- +// legal tdata1 wdata +//--------------------------------------------------------- +assign maskmax[5:0] = 6'd8;//TODO + +//========================================================= +// +// write trigger CSR +// +//========================================================= + +//--------------------------------------------------------- +// write and update tdata1 +//--------------------------------------------------------- + +assign tdata_writable = !tdata1[DMODE] && (m_mode || rtu_yy_xx_dbgon) || + tdata1[DMODE] && rtu_yy_xx_dbgon; +assign write_tdata1 = cp0_write_tdata1 && trigger_selected && tdata_writable; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata1_dmode <= 1'b0; + tdata1_timing <= 1'b0; + tdata1_sizelo[1:0] <= 2'b0; + tdata1_action <= 1'b0; + tdata1_match[3:0] <= 4'b0; + tdata1_m <= 1'b0; + tdata1_u <= 1'b0; + tdata1_store <= 1'b0; + tdata1_load <= 1'b0; + tdata1_execute <= 1'b0; + end + else if(write_tdata1) + begin + tdata1_dmode <= dmode_legal; + tdata1_timing <= timing_legal; + tdata1_sizelo[1:0] <= size_legal[1:0]; + tdata1_action <= action_legal; + tdata1_match[3:0] <= match_legal[3:0]; + tdata1_m <= cp0_dtu_wdata[M]; + tdata1_u <= cp0_dtu_wdata[U]; + tdata1_store <= cp0_dtu_wdata[STORE]; + tdata1_load <= cp0_dtu_wdata[LOAD]; + tdata1_execute <= cp0_dtu_wdata[EXECUTE]; + end +end +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + size1 <= 1'b0; + size2 <= 1'b0; + end + else if(write_tdata1) + begin + size1 <= size_legal[1:0] == 2'd1; + size2 <= size_legal[1:0] == 2'd2; + end +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata1_hit <= 1'b0; + else if(set_trigger_hit) + tdata1_hit <= 1'b1; + else if(write_tdata1) + tdata1_hit <= cp0_dtu_wdata[HIT]; +end + + assign tdata1_select_for_macro = 1'b0; +assign tdata1_execute_for_macro = tdata1_execute; + assign tdata1_store_for_macro = tdata1_store; + assign tdata1_load_for_macro = tdata1_load; + +assign tdata1_chain = 1'b0; +assign tdata1_chain_for_macro = tdata1_chain; + +assign tdata1[XLEN-1:0] = {type_legal[3:0],tdata1_dmode,maskmax[5:0], + tdata1_hit,tdata1_select_for_macro,tdata1_timing,tdata1_sizelo[1:0],3'b0,tdata1_action, + tdata1_chain_for_macro,tdata1_match[3:0],tdata1_m,1'b0,1'b0,tdata1_u, + tdata1_execute_for_macro,tdata1_store_for_macro,tdata1_load_for_macro}; + +// &Force("output","tdata1");&Force("bus","tdata1",XLEN-1,0); @291 + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata1_f <= 1'b0; + else + write_tdata1_f <= write_tdata1; +end +// &Force("nonport","write_tdata1_f"); @300 +//tdata1 output +// &Force("output","tdata1_chain"); @302 +// &Force("output","tdata1_dmode"); @303 +// &Force("output","tdata1_timing"); @304 +//assign tdata1_chain = tdata1[CHAIN]; +//assign tdata1_dmode = tdata1[DMODE]; +assign tdata1_action0 = !tdata1[ACTION-3]; +assign tdata1_action1 = tdata1[ACTION-3]; +//assign tdata1_timing = tdata1[TIMING]; + +//--------------------------------------------------------- +// write tdata2 +//--------------------------------------------------------- +assign write_tdata2 = cp0_write_tdata2 && trigger_selected && tdata_writable; +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2[XLEN-1:0] <= {XLEN{1'b0}}; + else if(write_tdata2) + tdata2[XLEN-1:0] <= cp0_dtu_wdata[XLEN-1:0]; +end +// &Force("output","tdata2");&Force("bus","tdata2",XLEN-1,0); @322 + +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + write_tdata2_f <= 1'b0; + else + write_tdata2_f <= write_tdata2; +end +// &Force("nonport","write_tdata2_f"); @331 +//--------------------------------------------------------- +// write tdata3 +//--------------------------------------------------------- + +//write tdata3 +always @(posedge tdata23_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + tdata3_mvalue[5:0] <= 6'b0; + tdata3_mselect <= 1'b0; + end + else if(cp0_write_tdata3 && trigger_selected && tdata_writable) + begin + tdata3_mvalue[5:0] <= cp0_dtu_wdata[MVALUE:MVALUE-5]; + tdata3_mselect <= cp0_dtu_wdata[MSELECT_TDATA1]; + end +end +assign tdata3[XLEN-1:0] = {tdata3_mvalue[5:0],tdata3_mselect,25'b0}; +// &Force("output","tdata3");&Force("bus","tdata3",XLEN-1,0); @351 +//--------------------------------------------------------- +// tinfo(read only) +//--------------------------------------------------------- +assign tinfo[XLEN-1:0] = {{XLEN-3{1'b0}},3'b100}; +// &Force("output","tinfo");&Force("bus","tinfo",XLEN-1,0); @356 +//mcontrol type =2 + +//========================================================= +// +// decode +// +//========================================================= +//--------------------------------------------------------- +// trigger enable signal +//--------------------------------------------------------- +//tcontrol enable +//assign tdata1_action[3:0] = tdata1[ACTION:ACTION-3]; + +assign tcontrol_enable = !(!tcontrol[MTE] && !tdata1_action && m_mode);//!(MTE=0 && action=0 && m_mode) +// &Force("bus","tcontrol",XLEN-1,0); @371 + +//m s context enable +assign mcontext_must_match = tdata3[MSELECT_TDATA1] && m_mode; +assign mcontext_enable = mcontext_must_match ? tdata3[MVALUE:MVALUE-5] == mcontext[5:0] : 1'b1; +// &Force("bus","mcontext",XLEN-1,0); @376 + +assign ms_context_enable = mcontext_enable; +assign m_enable = tdata1[M] && m_mode; +assign u_enable = tdata1[U] && u_mode; + +assign msu_mode_enable = m_enable || u_enable; + +//trigger can't match in debug mode +assign not_dbg_mode_enable = !rtu_yy_xx_dbgon; + +//trigger enable +assign trigger_enable = tcontrol_enable && ms_context_enable && + msu_mode_enable && not_dbg_mode_enable; + +//--------------------------------------------------------- +// information for match +//--------------------------------------------------------- +//type of mcontrol +assign exe_mcontrol = tdata1[EXECUTE]; +assign ldst_mcontrol = tdata1[LOAD] || tdata1[STORE]; +// &Force("output","exe_mcontrol"); @397 +// &Force("output","ldst_mcontrol"); @398 +assign exe_addr_mcontrol = tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]; +assign exe_data_mcontrol = tdata1[EXECUTE] && tdata1[SELECT_TDATA1]; + +assign store_addr_mcontrol = tdata1[STORE] && !tdata1[SELECT_TDATA1]; +assign store_data_mcontrol = tdata1[STORE] && tdata1[SELECT_TDATA1]; +//assign load_mcontrol = tdata1[LOAD]; +//assign ldst_mcontrol = store_mcontrol && load_mcontrol; +assign load_addr_mcontrol = tdata1[LOAD] && !tdata1[SELECT_TDATA1]; +assign load_data_mcontrol = tdata1[LOAD] && tdata1[SELECT_TDATA1]; + +assign ldst_addr_mcontrol = store_addr_mcontrol || load_addr_mcontrol; +assign ldst_data_mcontrol = store_data_mcontrol || load_data_mcontrol; +//priorty +// &CombBeg; @414 +always @( tdata1[2] + or tdata1[19]) +begin + if(tdata1[EXECUTE] && !tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b10; + mpriority_mask[1:0] = 2'b00; + end + else if(tdata1[EXECUTE] && tdata1[SELECT_TDATA1]) + begin + mpriority[1:0] = 2'b01; + mpriority_mask[1:0] = 2'b10; + end + else//ldst mcontrol or no mcontrol + begin + mpriority[1:0] = 2'b00; + mpriority_mask[1:0] = 2'b11; + end +// &CombEnd; @430 +end +//mtiming +assign mtiming = !tdata1[TIMING]; +assign mtiming_mask = tdata1[TIMING]; +// &Force("output","mpriority");&Force("bus","mpriority",1,0); @434 +// &Force("output","mpriority_mask");&Force("bus","mpriority_mask",1,0); @435 +// &Force("output","mtiming"); @436 +// &Force("output","mtiming_mask"); @437 + +// &CombBeg; @443 +// &CombEnd; @459 +// &CombBeg; @463 +// &CombEnd; @479 +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @480 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @481 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @482 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @483 +// &Force("input","previous_mtiming"); @484 +// &Force("input","previous_mtiming_mask"); @485 +// &Force("input","next_mtiming"); @486 +// &Force("input","next_mtiming_mask"); @487 +assign mpriority_after_chain[1:0] = mpriority[1:0]; +assign mpriority_mask_after_chain[1:0]= mpriority_mask[1:0]; +assign mtiming_after_chain = mtiming; +assign mtiming_mask_after_chain = mtiming_mask; +// &Force("input","previous_mpriority");&Force("bus","previous_mpriority",1,0); @493 +// &Force("input","previous_mpriority_mask");&Force("bus","previous_mpriority_mask",1,0); @494 +// &Force("input","next_mpriority");&Force("bus","next_mpriority",1,0); @495 +// &Force("input","next_mpriority_mask");&Force("bus","next_mpriority_mask",1,0); @496 +// &Force("input","previous_mtiming"); @497 +// &Force("input","previous_mtiming_mask"); @498 +// &Force("input","next_mtiming"); @499 +// &Force("input","next_mtiming_mask"); @500 + +//size +assign tdata1_size[1:0] = tdata1[SIZELO:SIZELO-1]; + +//assign size_mask_63_32 = !(size1 || size2 || size3); +//assign size_mask_31_16 = !(size1 || size2); +//assign size_mask_15_8 = !size1; +//assign size_mask[XLEN-1:0] = {{32{size_mask_63_32}},{16{size_mask_31_16}},{8{size_mask_15_8}},{8{1'b1}}}; +// &CombBeg; @510 +always @( size1 + or size2) +begin + if(size1) + size_mask[XLEN-1:0] = 32'h0000_00ff; + else if(size2) + size_mask[XLEN-1:0] = 32'h0000_ffff; + else + size_mask[XLEN-1:0] = 32'hffff_ffff; +// &CombEnd; @517 +end + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + match_ldst_addr <= 1'b0; + else if(!tdata1[SELECT_TDATA1] && (tdata1[LOAD] || tdata1[STORE])) + match_ldst_addr <= 1'b1; + else if(tdata1[LOAD] || tdata1[STORE] || tdata1[EXECUTE]) + match_ldst_addr <= 1'b0; +end + +//tdata2 need to be masked off by size +assign tdata2_value_before_size_mask[XLEN-1:0] = {tdata2[XLEN-1:3], tdata2[2:0] & {3{!match_ldst_addr}}}; +assign tdata2_value[XLEN-1:0] = tdata2_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//translate tdata2[23:20] to bytes_vld. when select = 0, match = 4. +//tdata2_ldst_value_lower_half == ldst_value_lower_half & tdata2_exe_value_upper_half +//tdata2_ldst_bytes_vld == lsu_dtu_ldst_bytes_vld & tdata2_ldst_bytes_vld_for_match4 + + //tdata2[3:0] generate low_bytes_vld +// &CombBeg; @558 +always @( tdata2[1:0]) +begin + case(tdata2[1:0]) + 2'b00: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0001; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b0011; + end + 2'b01: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0010; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + 2'b10: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b0100; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1100; + end + 2'b11: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = 4'b1000; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = 4'b1111; + end + default: + begin + tdata2_ldst_bytes_vld_four_bits[3:0] = {4{1'bx}}; + tdata2_ldst_bytes_vld_for_match1_four_bits[3:0] = {4{1'bx}}; + end + endcase +// &CombEnd; @611 +end +assign tdata2_ldst_bytes_vld[7:0] = tdata2[2] ? {tdata2_ldst_bytes_vld_four_bits[3:0],4'b0} : {4'b0,tdata2_ldst_bytes_vld_four_bits[3:0]}; +assign tdata2_ldst_bytes_vld_for_match1[7:0] = tdata2[2] ? {{4{tdata2[1] && tdata2[0]}},tdata2_ldst_bytes_vld_for_match1_four_bits[3:0]} : + {tdata2_ldst_bytes_vld_for_match1_four_bits[3:0],{4{tdata2[1] && tdata2[0]}}}; +//when tdata2[1] && tdata2[0] = 1, bytes_vld_for_match1 should be 8'bff no matter what tdata2[2] is + +// &CombBeg; @625 +// &CombEnd; @642 + +// &CombBeg; @645 +always @( tdata2_ldst_bytes_vld_for_match1[7:0] + or tdata2_ldst_bytes_vld[7:0] + or tdata1[10:7]) +begin + case(tdata1[MATCH:MATCH-3]) + 4'd0:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld[7:0]; + 4'd1:tdata2_ldst_bytes_vld_0[7:0] = tdata2_ldst_bytes_vld_for_match1[7:0]; + default:tdata2_ldst_bytes_vld_0[7:0] = {8{1'bx}}; + endcase +// &CombEnd; @661 +end + +//when match = 4, need reg_0 and reg_1 both. +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tdata2_ldst_bytes_vld_reg_0[7:0] <= 8'b0; + else if(tdata1[STORE] && !tdata1[SELECT_TDATA1] || tdata1[LOAD] && !tdata1[SELECT_TDATA1]) + tdata2_ldst_bytes_vld_reg_0[7:0] <= tdata2_ldst_bytes_vld_0[7:0]; +end + +//----------------------maksed value for match = 1------------------------------------ +assign zero_lsb_higher_than_4 = tdata2[3:0] == 4'b1111; +assign tdata2_4bits_value_for_m_mask[3:0] = zero_lsb_higher_than_4 ? tdata2[7:4] : tdata2[3:0]; +// &CombBeg; @677 +always @( tdata2_4bits_value_for_m_mask[3:0]) +begin + //m_mask and ldst_addr_mask(maskmax = 8). the low 4 bit of ldst addr are 0 + casez(tdata2_4bits_value_for_m_mask[3:0]) + 4'b???0:m_mask_four_bits[3:0] = 4'b1110; + 4'b??01:m_mask_four_bits[3:0] = 4'b1100; + 4'b?011:m_mask_four_bits[3:0] = 4'b1000; + 4'b0111:m_mask_four_bits[3:0] = 4'b0000; + 4'b1111:m_mask_four_bits[3:0] = 4'b0000; + default:m_mask_four_bits[3:0] = {4{1'bx}}; + endcase +// &CombEnd; @687 +end + +assign m_mask[7:0] = zero_lsb_higher_than_4 ? {m_mask_four_bits[3:0],4'b0} : {4'b1111,m_mask_four_bits[3:0]}; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + m_mask_reg[7:0] <= 8'b11111111; + else if(tdata1[MATCH:MATCH-3] == 4'b1) + m_mask_reg[7:0] <= m_mask[7:0]; +end + +//exe top M bits +assign tdata2_exe_value_masked_low_8bits[7:0] = tdata2_value[7:0] & m_mask_reg[7:0]; +assign tdata2_exe_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_exe_value_masked_low_8bits[7:0]}; + +//ldst top M bits +assign ldst_m_mask[7:0] = tdata1[SELECT_TDATA1] ? m_mask_reg[7:0] : {m_mask_reg[7:3],3'b0}; +assign tdata2_ldst_addr_masked_low_8bits[7:0] = tdata2_value[7:0] & ldst_m_mask[7:0]; +assign tdata2_ldst_value_top_mbits[XLEN-1:0] = {tdata2_value[XLEN-1:8],tdata2_ldst_addr_masked_low_8bits[7:0]}; + +//========================================================= +// +// exe0 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe0 type match and size match +//--------------------------------------------------------- +assign exe0_type_match = ifu_dtu_addr_vld0 && exe_addr_mcontrol || ifu_dtu_data_vld0 && exe_data_mcontrol; +assign exe0_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe0_16bit || + tdata1_size[1:0] == 2'd3 && exe0_32bit || (ifu_dtu_addr_vld0 && !ifu_dtu_data_vld0); +assign exe0_type_size_match = exe0_type_match && exe0_size_match && trigger_enable; +//--------------------------------------------------------- +// exe0 value match +//--------------------------------------------------------- +//value for exe0 trigger match +assign exe0_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr0[`PA_WIDTH-1:0]; +assign exe0_value[XLEN-1:0] = exe0_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe0_value_masked_low_8bis[7:0] = exe0_value[7:0] & m_mask_reg[7:0]; +assign exe0_value_top_mbits[XLEN-1:0] = {exe0_value[XLEN-1:8],exe0_value_masked_low_8bis[7:0]}; + +//value match +assign exe0_match_equal = exe0_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe0_match_top_mbits_equal = exe0_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + +assign exe0_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe0_match_equal; +assign exe0_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe0_match_top_mbits_equal; + +assign exe0_value_match = exe0_have_value_match0 || exe0_have_value_match1; +//--------------------------------------------------------- +// exe0 match result +//--------------------------------------------------------- +assign exe0_match_need_reg = exe0_value_match && exe0_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe0_match <= 1'b0; + else + exe0_match <= exe0_match_need_reg; +end +// &Force("output","exe0_match"); @820 + +assign exe0_may_hit = exe0_value_match;// && ifu_dtu_addr_vld0; + +//========================================================= +// +// exe1 match logic +// +//========================================================= +//--------------------------------------------------------- +// exe1 type match and size match +//--------------------------------------------------------- +assign exe1_type_match = ifu_dtu_addr_vld1 && exe_addr_mcontrol || ifu_dtu_data_vld1 && exe_data_mcontrol; +assign exe1_size_match = tdata1_size[1:0] == 2'd0 || size2 && exe1_16bit || + tdata1_size[1:0] == 2'd3 && exe1_32bit || (ifu_dtu_addr_vld1 && !ifu_dtu_data_vld1); +assign exe1_type_size_match = exe1_type_match && exe1_size_match && trigger_enable; +//--------------------------------------------------------- +// exe1 value match +//--------------------------------------------------------- +//value for exe1 trigger match +assign exe1_value_before_size_mask[XLEN-1:0] = ifu_dtu_exe_addr1[`PA_WIDTH-1:0]; +assign exe1_value[XLEN-1:0] = exe1_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; +assign exe1_value_masked_low_8bis[7:0] = exe1_value[7:0] & m_mask_reg[7:0]; +assign exe1_value_top_mbits[XLEN-1:0] = {exe1_value[XLEN-1:8],exe1_value_masked_low_8bis[7:0]}; + +//value match +assign exe1_match_equal = exe1_value[XLEN-1:0] == tdata2_value[XLEN-1:0];//match = 0 +assign exe1_match_top_mbits_equal = exe1_value_top_mbits[XLEN-1:0] == tdata2_exe_value_top_mbits[XLEN-1:0];//match = 1 + + +assign exe1_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && exe1_match_equal; +assign exe1_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && exe1_match_top_mbits_equal; + +assign exe1_value_match = exe1_have_value_match0 || exe1_have_value_match1; +//--------------------------------------------------------- +// exe1 match result +//--------------------------------------------------------- +assign exe1_match_need_reg = exe1_value_match && exe1_type_size_match; +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe1_match <= 1'b0; + else + exe1_match <= exe1_match_need_reg; +end +// &Force("output","exe1_match"); @916 + +assign exe1_may_hit = exe1_value_match;// && ifu_dtu_addr_vld1; +// &Force("input","exe0_16bit"); @920 +// &Force("input","exe0_32bit"); @921 +// &Force("input","exe1_16bit"); @922 +// &Force("input","exe1_32bit"); @923 +// &Force("input","ifu_dtu_addr_vld0"); @924 +// &Force("input","ifu_dtu_addr_vld1"); @925 +// &Force("input","ifu_dtu_data_vld0"); @926 +// &Force("input","ifu_dtu_data_vld1"); @927 +// &Force("input","ifu_dtu_exe_addr0");&Force("bus","ifu_dtu_exe_addr0",`PA_WIDTH-1,0); @928 +// &Force("input","ifu_dtu_exe_addr1");&Force("bus","ifu_dtu_exe_addr1",`PA_WIDTH-1,0); @929 +// &Force("input","ifu_dtu_exe_data0");&Force("bus","ifu_dtu_exe_data0",31,0); @930 +// &Force("input","ifu_dtu_exe_data1");&Force("bus","ifu_dtu_exe_data1",31,0); @931 +// &Force("output","exe0_match"); @932 +// &Force("output","exe1_match"); @933 + +//========================================================= +// +// ldst match logic +// +//========================================================= +//--------------------------------------------------------- +// ldst type match and size match +//--------------------------------------------------------- +assign ldst_type_match = store_addr_vld && store_addr_mcontrol || + store_data_vld && store_data_mcontrol || + load_addr_vld && load_addr_mcontrol || + load_data_vld && load_data_mcontrol; +assign ldst_size_match = tdata1_size[1:0] == 2'd0 || size1 && ldst_8bit || + size2 && ldst_16bit || tdata1_size[1:0] == 2'd3 && ldst_32bit; +assign ldst_type_size_match = ldst_type_match && ldst_size_match && trigger_enable; + +//--------------------------------------------------------- +// ldst value match +//--------------------------------------------------------- +//value for ldst trigger match +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @963 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @964 +assign ldst_value_before_size_mask[XLEN-1:0] = {lsu_dtu_ldst_addr[`PA_WIDTH-1:3],3'b0}; + +assign ldst_value[XLEN-1:0] = ldst_value_before_size_mask[XLEN-1:0] & size_mask[XLEN-1:0]; + +//masked value +assign ldst_value_masked_low_8bis[7:0] = ldst_value[7:0] & ldst_m_mask[7:0]; +assign ldst_value_top_mbits[XLEN-1:0] = {ldst_value[XLEN-1:8],ldst_value_masked_low_8bis[7:0]}; + +//value match +assign lsu_have_bytes_vld = |lsu_dtu_ldst_bytes_vld[7:0]; +// &Force("nonport","lsu_have_bytes_vld"); @990 +assign bytes_vld_match = |(lsu_dtu_ldst_bytes_vld[7:0] & tdata2_ldst_bytes_vld_reg_0[7:0]); +//match = 0 +assign ldst_value_equal = ldst_value[XLEN-1:0] == tdata2_value[XLEN-1:0]; +assign ldst_bytes_vld_equal = bytes_vld_match; +assign ldst_addr_match_equal = ldst_bytes_vld_equal && ldst_value_equal; +assign ldst_match_equal = ldst_addr_match_equal; + +//match = 1 +assign ldst_value_top_mbits_equal = ldst_value_top_mbits[XLEN-1:0] == tdata2_ldst_value_top_mbits[XLEN-1:0]; +assign ldst_bytes_vld_mbits_equal = bytes_vld_match; +assign ldst_addr_top_mbits_equal = ldst_value_top_mbits_equal && ldst_bytes_vld_mbits_equal; +assign ldst_match_top_mbits_equal = ldst_addr_top_mbits_equal; + + + + +assign ldst_have_value_match0 = tdata1[MATCH:MATCH-3] == 4'd0 && ldst_match_equal; +assign ldst_have_value_match1 = tdata1[MATCH:MATCH-3] == 4'd1 && ldst_match_top_mbits_equal; + +assign ldst_value_match = ldst_have_value_match0 || ldst_have_value_match1; +//--------------------------------------------------------- +// ldst match result +//--------------------------------------------------------- +assign tri_already_match = already_match && (lsu_dtu_ldst_addr_vld || lsu_dtu_ldst_data_vld); +assign ldst_mcontrol_match = ldst_value_match && ldst_type_size_match; +assign ldst_match_need_reg = ldst_mcontrol_match || tri_already_match; + +always @(posedge tdata1_matchinfo_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ldst_match <= 1'b0; + else + ldst_match <= ldst_match_need_reg; +end +// &Force("output","ldst_match"); @1176 +//assign ldst_may_hit = ldst_cycle2_cannot_match ? 1'b0 : ldst_match_need_reg; +assign ldst_may_hit = ldst_match_need_reg;//ldst_value_match || tri_already_match; +// &Force("input","already_match"); @1180 +// &Force("input","ldst_8bit"); @1181 +// &Force("input","ldst_16bit"); @1182 +// &Force("input","ldst_32bit"); @1183 +// &Force("input","store_addr_vld"); @1184 +// &Force("input","store_data_vld"); @1185 +// &Force("input","load_addr_vld"); @1186 +// &Force("input","load_data_vld"); @1187 +// &Force("input","lsu_dtu_ldst_addr_vld"); @1188 +// &Force("input","lsu_dtu_ldst_data_vld"); @1189 +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @1190 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @1191 +// &Force("input","lsu_dtu_ldst_bytes_vld");&Force("bus","lsu_dtu_ldst_bytes_vld",7,0); @1192 +// &Force("output","ldst_match"); @1193 + +//========================================================== +// gate clk +//========================================================== +assign tdata1_matchinfo_clk_en = trigger_selected && + (cp0_write_tdata1 || write_tdata2_f || write_tdata1_f) || + exe0_match_need_reg || exe0_match || + exe1_match_need_reg || exe1_match || + ldst_match_need_reg || ldst_match || + set_trigger_hit; +// &Instance("gated_clk_cell", "x_tdata1_matchinfo_reg_gated_clk"); @1208 +gated_clk_cell x_tdata1_matchinfo_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata1_matchinfo_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata1_matchinfo_clk_en), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @1209 +// .external_en (1'b0), @1210 +// .global_en (cp0_yy_clk_en), @1211 +// .module_en (cp0_dtu_icg_en), @1212 +// .local_en (tdata1_matchinfo_clk_en), @1213 +// //.local_en (1'b1), @1214 +// .clk_out (tdata1_matchinfo_clk)); @1215 + +//make tdata2, tdata3 a gated clk cell +assign tdata23_clk_en = trigger_selected && (cp0_write_tdata2 || cp0_write_tdata3 || write_tdata2_f); +// &Instance("gated_clk_cell", "x_tdata23_reg_gated_clk"); @1219 +gated_clk_cell x_tdata23_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tdata23_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tdata23_clk_en ), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @1220 +// .external_en (1'b0), @1221 +// .global_en (cp0_yy_clk_en), @1222 +// .module_en (cp0_dtu_icg_en), @1223 +// .local_en (tdata23_clk_en), @1224 +// //.local_en (1'b1), @1225 +// .clk_out (tdata23_clk)); @1226 +// &ModuleEnd; @1227 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_output_select.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_output_select.v new file mode 100644 index 0000000000000000000000000000000000000000..6ff7e6e260ef1d17905889090e01d03fbf44ba40 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_mcontrol_output_select.v @@ -0,0 +1,3450 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_mcontrol_output_select( + action0_mcontrol, + action1_mcontrol, + cp0_dtu_icg_en, + cp0_dtu_wdata, + cp0_write_tdata1, + cp0_write_tdata2, + cp0_write_tdata3, + cp0_yy_clk_en, + cpurst_b, + dtu_ifu_halt_info_vld, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + exe0_16bit, + exe0_32bit, + exe1_16bit, + exe1_32bit, + forever_cpuclk, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ldst_16bit, + ldst_32bit, + ldst_8bit, + ldst_addr_mcontrol, + ldst_data_mcontrol, + load_addr_vld, + load_data_vld, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + m0_tdata1, + m0_tdata2, + m0_tdata3, + m0_tinfo, + m1_tdata1, + m1_tdata2, + m1_tdata3, + m1_tinfo, + m2_tdata1, + m2_tdata2, + m2_tdata3, + m2_tinfo, + m3_tdata1, + m3_tdata2, + m3_tdata3, + m3_tinfo, + m4_tdata1, + m4_tdata2, + m4_tdata3, + m4_tinfo, + m5_tdata1, + m5_tdata2, + m5_tdata3, + m5_tinfo, + m6_tdata1, + m6_tdata2, + m6_tdata3, + m6_tinfo, + m7_tdata1, + m7_tdata2, + m7_tdata3, + m7_tinfo, + m_mode, + mcontext, + mcontrol_halt_info0, + mcontrol_halt_info1, + mcontrol_hit, + pad_yy_icg_scan_en, + rtu_yy_xx_dbgon, + store_addr_vld, + store_data_vld, + tcontrol, + tselect_wr_en, + u_mode +); + +// &Ports; @24 +input cp0_dtu_icg_en; +input [31:0] cp0_dtu_wdata; +input cp0_write_tdata1; +input cp0_write_tdata2; +input cp0_write_tdata3; +input cp0_yy_clk_en; +input cpurst_b; +input exe0_16bit; +input exe0_32bit; +input exe1_16bit; +input exe1_32bit; +input forever_cpuclk; +input ifu_dtu_addr_vld0; +input ifu_dtu_addr_vld1; +input ifu_dtu_data_vld0; +input ifu_dtu_data_vld1; +input [31:0] ifu_dtu_exe_addr0; +input [31:0] ifu_dtu_exe_addr1; +input ldst_16bit; +input ldst_32bit; +input ldst_8bit; +input load_addr_vld; +input load_data_vld; +input [14:0] lsu_dtu_halt_info; +input lsu_dtu_last_check; +input [31:0] lsu_dtu_ldst_addr; +input lsu_dtu_ldst_addr_vld; +input [7 :0] lsu_dtu_ldst_bytes_vld; +input [31:0] lsu_dtu_ldst_data; +input lsu_dtu_ldst_data_vld; +input m_mode; +input [31:0] mcontext; +input [2 :0] mcontrol_hit; +input pad_yy_icg_scan_en; +input rtu_yy_xx_dbgon; +input store_addr_vld; +input store_data_vld; +input [31:0] tcontrol; +input [9 :0] tselect_wr_en; +input u_mode; +output [2 :0] action0_mcontrol; +output [2 :0] action1_mcontrol; +output dtu_ifu_halt_info_vld; +output [14:0] dtu_lsu_halt_info; +output dtu_lsu_halt_info_vld; +output ldst_addr_mcontrol; +output ldst_data_mcontrol; +output [31:0] m0_tdata1; +output [31:0] m0_tdata2; +output [31:0] m0_tdata3; +output [31:0] m0_tinfo; +output [31:0] m1_tdata1; +output [31:0] m1_tdata2; +output [31:0] m1_tdata3; +output [31:0] m1_tinfo; +output [31:0] m2_tdata1; +output [31:0] m2_tdata2; +output [31:0] m2_tdata3; +output [31:0] m2_tinfo; +output [31:0] m3_tdata1; +output [31:0] m3_tdata2; +output [31:0] m3_tdata3; +output [31:0] m3_tinfo; +output [31:0] m4_tdata1; +output [31:0] m4_tdata2; +output [31:0] m4_tdata3; +output [31:0] m4_tinfo; +output [31:0] m5_tdata1; +output [31:0] m5_tdata2; +output [31:0] m5_tdata3; +output [31:0] m5_tinfo; +output [31:0] m6_tdata1; +output [31:0] m6_tdata2; +output [31:0] m6_tdata3; +output [31:0] m6_tinfo; +output [31:0] m7_tdata1; +output [31:0] m7_tdata2; +output [31:0] m7_tdata3; +output [31:0] m7_tinfo; +output [14:0] mcontrol_halt_info0; +output [14:0] mcontrol_halt_info1; + +// &Regs; @25 +reg cp0_write_tdata1_f; +reg exe_cycle2_cannot_hit; +reg ldst_cancel; +reg ldst_cycle2_cannot_hit; +reg [7 :0] ldst_match; +reg lsu_dtu_last_check_f; +reg need_match_store_data_t0_trigger_f; +reg [1 :0] x_phigher_than_m0_reg_lowbits; +reg [1 :0] x_phigher_than_m1_reg_lowbits; +reg [1 :0] x_phigher_than_m2_reg_lowbits; +reg [1 :0] x_thigher_than_m0_reg_lowbits; +reg [1 :0] x_thigher_than_m1_reg_lowbits; +reg [1 :0] x_thigher_than_m2_reg_lowbits; + +// &Wires; @26 +wire [2 :0] action0_mcontrol; +wire [2 :0] action1_mcontrol; +wire [2 :0] already_match; +wire chain0_timing0_match; +wire chain1_timing0_match; +wire chain2_timing0_match; +wire chain3_timing0_match; +wire chain4_timing0_match; +wire chain5_timing0_match; +wire chain6_timing0_match; +wire cp0_dtu_icg_en; +wire [31:0] cp0_dtu_wdata; +wire cp0_write_tdata1; +wire cp0_write_tdata2; +wire cp0_write_tdata3; +wire cp0_yy_clk_en; +wire cpurst_b; +wire dtu_ifu_halt_info_vld; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire exe0_16bit; +wire exe0_32bit; +wire exe0_action; +wire exe0_action0; +wire exe0_action01; +wire exe0_action1; +wire [7 :0] exe0_after_chain_match; +wire exe0_after_chain_match0; +wire exe0_after_chain_match1; +wire exe0_after_chain_match2; +wire exe0_after_chain_match3; +wire exe0_after_chain_match4; +wire exe0_after_chain_match5; +wire exe0_after_chain_match6; +wire exe0_after_chain_match7; +wire exe0_cancel; +wire exe0_chain; +wire exe0_chain_cancel; +wire exe0_have_match; +wire [7 :0] exe0_match; +wire exe0_may_hit; +wire exe0_single_mcontrol_cancel; +wire exe0_timing; +wire exe1_16bit; +wire exe1_32bit; +wire exe1_action; +wire exe1_action0; +wire exe1_action01; +wire exe1_action1; +wire [7 :0] exe1_after_chain_match; +wire exe1_after_chain_match0; +wire exe1_after_chain_match1; +wire exe1_after_chain_match2; +wire exe1_after_chain_match3; +wire exe1_after_chain_match4; +wire exe1_after_chain_match5; +wire exe1_after_chain_match6; +wire exe1_after_chain_match7; +wire exe1_cancel; +wire exe1_chain; +wire exe1_chain_cancel; +wire exe1_have_match; +wire [7 :0] exe1_match; +wire exe1_may_hit; +wire exe1_single_mcontrol_cancel; +wire exe1_timing; +wire exe_may_hit; +wire forever_cpuclk; +wire have_store_data_timing0; +wire have_timing0_match; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire ldst_16bit; +wire ldst_32bit; +wire ldst_8bit; +wire ldst_action; +wire ldst_action0; +wire ldst_action01; +wire ldst_action1; +wire ldst_addr_mcontrol; +wire [7 :0] ldst_after_chain_match; +wire ldst_after_chain_match0; +wire ldst_after_chain_match1; +wire ldst_after_chain_match2; +wire ldst_after_chain_match3; +wire ldst_after_chain_match4; +wire ldst_after_chain_match5; +wire ldst_after_chain_match6; +wire ldst_after_chain_match7; +wire ldst_chain0_match; +wire ldst_chain1_match; +wire ldst_chain2_match; +wire ldst_chain3_match; +wire ldst_chain4_match; +wire ldst_chain5_match; +wire ldst_chain6_match; +wire ldst_data_mcontrol; +wire ldst_have_match; +wire ldst_may_hit; +wire ldst_mcontrol0_single_match; +wire ldst_mcontrol0_timing0_match; +wire ldst_mcontrol1_single_match; +wire ldst_mcontrol1_timing0_match; +wire ldst_mcontrol2_single_match; +wire ldst_mcontrol2_timing0_match; +wire ldst_mcontrol3_single_match; +wire ldst_mcontrol3_timing0_match; +wire ldst_mcontrol4_single_match; +wire ldst_mcontrol4_timing0_match; +wire ldst_mcontrol5_single_match; +wire ldst_mcontrol5_timing0_match; +wire ldst_mcontrol6_single_match; +wire ldst_mcontrol6_timing0_match; +wire ldst_mcontrol7_single_match; +wire ldst_mcontrol7_timing0_match; +wire ldst_timing; +wire load_addr_vld; +wire load_data_vld; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire m0_exe0_action0; +wire m0_exe0_action1; +wire m0_exe0_can_match; +wire m0_exe0_match; +wire m0_exe1_action0; +wire m0_exe1_action1; +wire m0_exe1_can_match; +wire m0_exe1_match; +wire m0_ldst_action0; +wire m0_ldst_action1; +wire m0_ldst_can_match; +wire m0_ldst_match; +wire m0_ldst_timing; +wire m0_mtiming; +wire m0_mtiming_mask; +wire m0_phigher_than_m1; +wire m0_phigher_than_m2; +wire m0_phigher_than_m3; +wire m0_phigher_than_m4; +wire m0_phigher_than_m5; +wire m0_phigher_than_m6; +wire m0_phigher_than_m7; +wire [1 :0] m0_priority; +wire [1 :0] m0_priority_mask; +wire [31:0] m0_tdata1; +wire [31:0] m0_tdata2; +wire [31:0] m0_tdata3; +wire m0_thigher_than_m1; +wire m0_thigher_than_m2; +wire m0_thigher_than_m3; +wire m0_thigher_than_m4; +wire m0_thigher_than_m5; +wire m0_thigher_than_m6; +wire m0_thigher_than_m7; +wire [31:0] m0_tinfo; +wire m1_exe0_action0; +wire m1_exe0_action1; +wire m1_exe0_can_match; +wire m1_exe0_match; +wire m1_exe1_action0; +wire m1_exe1_action1; +wire m1_exe1_can_match; +wire m1_exe1_match; +wire m1_ldst_action0; +wire m1_ldst_action1; +wire m1_ldst_can_match; +wire m1_ldst_match; +wire m1_ldst_timing; +wire m1_mtiming; +wire m1_mtiming_mask; +wire m1_phigher_than_m0; +wire m1_phigher_than_m2; +wire m1_phigher_than_m3; +wire m1_phigher_than_m4; +wire m1_phigher_than_m5; +wire m1_phigher_than_m6; +wire m1_phigher_than_m7; +wire [1 :0] m1_priority; +wire [1 :0] m1_priority_mask; +wire [31:0] m1_tdata1; +wire [31:0] m1_tdata2; +wire [31:0] m1_tdata3; +wire m1_thigher_than_m0; +wire m1_thigher_than_m2; +wire m1_thigher_than_m3; +wire m1_thigher_than_m4; +wire m1_thigher_than_m5; +wire m1_thigher_than_m6; +wire m1_thigher_than_m7; +wire [31:0] m1_tinfo; +wire m2_exe0_action0; +wire m2_exe0_action1; +wire m2_exe0_can_match; +wire m2_exe0_match; +wire m2_exe1_action0; +wire m2_exe1_action1; +wire m2_exe1_can_match; +wire m2_exe1_match; +wire m2_ldst_action0; +wire m2_ldst_action1; +wire m2_ldst_can_match; +wire m2_ldst_match; +wire m2_ldst_timing; +wire m2_mtiming; +wire m2_mtiming_mask; +wire m2_phigher_than_m0; +wire m2_phigher_than_m1; +wire m2_phigher_than_m3; +wire m2_phigher_than_m4; +wire m2_phigher_than_m5; +wire m2_phigher_than_m6; +wire m2_phigher_than_m7; +wire [1 :0] m2_priority; +wire [1 :0] m2_priority_mask; +wire [31:0] m2_tdata1; +wire [31:0] m2_tdata2; +wire [31:0] m2_tdata3; +wire m2_thigher_than_m0; +wire m2_thigher_than_m1; +wire m2_thigher_than_m3; +wire m2_thigher_than_m4; +wire m2_thigher_than_m5; +wire m2_thigher_than_m6; +wire m2_thigher_than_m7; +wire [31:0] m2_tinfo; +wire m3_exe0_action0; +wire m3_exe0_action1; +wire m3_exe0_can_match; +wire m3_exe0_match; +wire m3_exe1_action0; +wire m3_exe1_action1; +wire m3_exe1_can_match; +wire m3_exe1_match; +wire m3_ldst_action0; +wire m3_ldst_action1; +wire m3_ldst_can_match; +wire m3_ldst_match; +wire m3_ldst_timing; +wire m3_mtiming; +wire m3_mtiming_mask; +wire m3_phigher_than_m0; +wire m3_phigher_than_m1; +wire m3_phigher_than_m2; +wire m3_phigher_than_m4; +wire m3_phigher_than_m5; +wire m3_phigher_than_m6; +wire m3_phigher_than_m7; +wire [1 :0] m3_priority; +wire [1 :0] m3_priority_mask; +wire [31:0] m3_tdata1; +wire [31:0] m3_tdata2; +wire [31:0] m3_tdata3; +wire m3_thigher_than_m0; +wire m3_thigher_than_m1; +wire m3_thigher_than_m2; +wire m3_thigher_than_m4; +wire m3_thigher_than_m5; +wire m3_thigher_than_m6; +wire m3_thigher_than_m7; +wire [31:0] m3_tinfo; +wire m4_exe0_action0; +wire m4_exe0_action1; +wire m4_exe0_can_match; +wire m4_exe0_match; +wire m4_exe1_action0; +wire m4_exe1_action1; +wire m4_exe1_can_match; +wire m4_exe1_match; +wire m4_ldst_action0; +wire m4_ldst_action1; +wire m4_ldst_can_match; +wire m4_ldst_match; +wire m4_ldst_timing; +wire m4_mtiming; +wire m4_mtiming_mask; +wire m4_phigher_than_m0; +wire m4_phigher_than_m1; +wire m4_phigher_than_m2; +wire m4_phigher_than_m3; +wire m4_phigher_than_m5; +wire m4_phigher_than_m6; +wire m4_phigher_than_m7; +wire [1 :0] m4_priority; +wire [1 :0] m4_priority_mask; +wire [31:0] m4_tdata1; +wire [31:0] m4_tdata2; +wire [31:0] m4_tdata3; +wire m4_thigher_than_m0; +wire m4_thigher_than_m1; +wire m4_thigher_than_m2; +wire m4_thigher_than_m3; +wire m4_thigher_than_m5; +wire m4_thigher_than_m6; +wire m4_thigher_than_m7; +wire [31:0] m4_tinfo; +wire m5_exe0_action0; +wire m5_exe0_action1; +wire m5_exe0_can_match; +wire m5_exe0_match; +wire m5_exe1_action0; +wire m5_exe1_action1; +wire m5_exe1_can_match; +wire m5_exe1_match; +wire m5_ldst_action0; +wire m5_ldst_action1; +wire m5_ldst_can_match; +wire m5_ldst_match; +wire m5_ldst_timing; +wire m5_mtiming; +wire m5_mtiming_mask; +wire m5_phigher_than_m0; +wire m5_phigher_than_m1; +wire m5_phigher_than_m2; +wire m5_phigher_than_m3; +wire m5_phigher_than_m4; +wire m5_phigher_than_m6; +wire m5_phigher_than_m7; +wire [1 :0] m5_priority; +wire [1 :0] m5_priority_mask; +wire [31:0] m5_tdata1; +wire [31:0] m5_tdata2; +wire [31:0] m5_tdata3; +wire m5_thigher_than_m0; +wire m5_thigher_than_m1; +wire m5_thigher_than_m2; +wire m5_thigher_than_m3; +wire m5_thigher_than_m4; +wire m5_thigher_than_m6; +wire m5_thigher_than_m7; +wire [31:0] m5_tinfo; +wire m6_exe0_action0; +wire m6_exe0_action1; +wire m6_exe0_can_match; +wire m6_exe0_match; +wire m6_exe1_action0; +wire m6_exe1_action1; +wire m6_exe1_can_match; +wire m6_exe1_match; +wire m6_ldst_action0; +wire m6_ldst_action1; +wire m6_ldst_can_match; +wire m6_ldst_match; +wire m6_ldst_timing; +wire m6_mtiming; +wire m6_mtiming_mask; +wire m6_phigher_than_m0; +wire m6_phigher_than_m1; +wire m6_phigher_than_m2; +wire m6_phigher_than_m3; +wire m6_phigher_than_m4; +wire m6_phigher_than_m5; +wire m6_phigher_than_m7; +wire [1 :0] m6_priority; +wire [1 :0] m6_priority_mask; +wire [31:0] m6_tdata1; +wire [31:0] m6_tdata2; +wire [31:0] m6_tdata3; +wire m6_thigher_than_m0; +wire m6_thigher_than_m1; +wire m6_thigher_than_m2; +wire m6_thigher_than_m3; +wire m6_thigher_than_m4; +wire m6_thigher_than_m5; +wire m6_thigher_than_m7; +wire [31:0] m6_tinfo; +wire m7_exe0_action0; +wire m7_exe0_action1; +wire m7_exe0_can_match; +wire m7_exe0_match; +wire m7_exe1_action0; +wire m7_exe1_action1; +wire m7_exe1_can_match; +wire m7_exe1_match; +wire m7_ldst_action0; +wire m7_ldst_action1; +wire m7_ldst_can_match; +wire m7_ldst_match; +wire m7_ldst_timing; +wire m7_mtiming; +wire m7_mtiming_mask; +wire m7_phigher_than_m0; +wire m7_phigher_than_m1; +wire m7_phigher_than_m2; +wire m7_phigher_than_m3; +wire m7_phigher_than_m4; +wire m7_phigher_than_m5; +wire m7_phigher_than_m6; +wire [1 :0] m7_priority; +wire [1 :0] m7_priority_mask; +wire [31:0] m7_tdata1; +wire [31:0] m7_tdata2; +wire [31:0] m7_tdata3; +wire m7_thigher_than_m0; +wire m7_thigher_than_m1; +wire m7_thigher_than_m2; +wire m7_thigher_than_m3; +wire m7_thigher_than_m4; +wire m7_thigher_than_m5; +wire m7_thigher_than_m6; +wire [31:0] m7_tinfo; +wire m_mode; +wire [31:0] mcontext; +wire mcontrol0_action0; +wire mcontrol0_action1; +wire mcontrol0_chain; +wire mcontrol0_dmode; +wire mcontrol0_exe0_match; +wire mcontrol0_exe0_may_hit; +wire mcontrol0_exe1_match; +wire mcontrol0_exe1_may_hit; +wire mcontrol0_is_exe; +wire mcontrol0_is_ldst; +wire mcontrol0_is_ldst_addr; +wire mcontrol0_is_ldst_data; +wire mcontrol0_ldst_match; +wire mcontrol0_ldst_may_hit; +wire mcontrol0_mtiming; +wire mcontrol0_mtiming_mask; +wire [1 :0] mcontrol0_priority; +wire [1 :0] mcontrol0_priority_mask; +wire mcontrol0_store_data_timing0; +wire mcontrol0_timing; +wire mcontrol1_action0; +wire mcontrol1_action1; +wire mcontrol1_chain; +wire mcontrol1_dmode; +wire mcontrol1_exe0_match; +wire mcontrol1_exe0_may_hit; +wire mcontrol1_exe1_match; +wire mcontrol1_exe1_may_hit; +wire mcontrol1_is_exe; +wire mcontrol1_is_ldst; +wire mcontrol1_is_ldst_addr; +wire mcontrol1_is_ldst_data; +wire mcontrol1_ldst_match; +wire mcontrol1_ldst_may_hit; +wire mcontrol1_mtiming; +wire mcontrol1_mtiming_mask; +wire [1 :0] mcontrol1_priority; +wire [1 :0] mcontrol1_priority_mask; +wire mcontrol1_store_data_timing0; +wire mcontrol1_timing; +wire mcontrol2_action0; +wire mcontrol2_action1; +wire mcontrol2_chain; +wire mcontrol2_dmode; +wire mcontrol2_exe0_match; +wire mcontrol2_exe0_may_hit; +wire mcontrol2_exe1_match; +wire mcontrol2_exe1_may_hit; +wire mcontrol2_is_exe; +wire mcontrol2_is_ldst; +wire mcontrol2_is_ldst_addr; +wire mcontrol2_is_ldst_data; +wire mcontrol2_ldst_match; +wire mcontrol2_ldst_may_hit; +wire mcontrol2_mtiming; +wire mcontrol2_mtiming_mask; +wire [1 :0] mcontrol2_priority; +wire [1 :0] mcontrol2_priority_mask; +wire mcontrol2_store_data_timing0; +wire mcontrol2_timing; +wire mcontrol3_action0; +wire mcontrol3_action1; +wire mcontrol3_exe0_match; +wire mcontrol3_exe1_match; +wire mcontrol3_is_ldst; +wire mcontrol3_is_ldst_data; +wire mcontrol3_ldst_match; +wire mcontrol3_store_data_timing0; +wire mcontrol3_timing; +wire mcontrol4_action0; +wire mcontrol4_action1; +wire mcontrol4_exe0_match; +wire mcontrol4_exe1_match; +wire mcontrol4_is_ldst; +wire mcontrol4_is_ldst_data; +wire mcontrol4_ldst_match; +wire mcontrol4_store_data_timing0; +wire mcontrol4_timing; +wire mcontrol5_action0; +wire mcontrol5_action1; +wire mcontrol5_exe0_match; +wire mcontrol5_exe1_match; +wire mcontrol5_is_ldst; +wire mcontrol5_is_ldst_data; +wire mcontrol5_ldst_match; +wire mcontrol5_store_data_timing0; +wire mcontrol5_timing; +wire mcontrol6_action0; +wire mcontrol6_action1; +wire mcontrol6_exe0_match; +wire mcontrol6_exe1_match; +wire mcontrol6_is_ldst; +wire mcontrol6_is_ldst_data; +wire mcontrol6_ldst_match; +wire mcontrol6_store_data_timing0; +wire mcontrol6_timing; +wire mcontrol7_action0; +wire mcontrol7_action1; +wire mcontrol7_exe0_match; +wire mcontrol7_exe1_match; +wire mcontrol7_is_ldst; +wire mcontrol7_is_ldst_data; +wire mcontrol7_ldst_match; +wire mcontrol7_store_data_timing0; +wire mcontrol7_timing; +wire [14:0] mcontrol_halt_info0; +wire [14:0] mcontrol_halt_info1; +wire [2 :0] mcontrol_hit; +wire mcontrol_output_clk; +wire mcontrol_output_clk_en; +wire need_match_store_data_t0_trigger; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_dbgon; +wire store_addr_vld; +wire store_data_vld; +wire [31:0] tcontrol; +wire [7 :0] timing0_match; +wire [9 :0] tselect_wr_en; +wire u_mode; +wire [6 :0] x_phigher_than_m0; +wire [6 :0] x_phigher_than_m0_reg; +wire [6 :0] x_phigher_than_m1; +wire [6 :0] x_phigher_than_m1_reg; +wire [6 :0] x_phigher_than_m2; +wire [6 :0] x_phigher_than_m2_reg; +wire [6 :0] x_phigher_than_m3; +wire [6 :0] x_phigher_than_m3_reg; +wire [6 :0] x_phigher_than_m4; +wire [6 :0] x_phigher_than_m4_reg; +wire [6 :0] x_phigher_than_m5; +wire [6 :0] x_phigher_than_m5_reg; +wire [6 :0] x_phigher_than_m6; +wire [6 :0] x_phigher_than_m6_reg; +wire [6 :0] x_phigher_than_m7; +wire [6 :0] x_phigher_than_m7_reg; +wire [6 :0] x_thigher_than_m0; +wire [6 :0] x_thigher_than_m0_reg; +wire [6 :0] x_thigher_than_m1; +wire [6 :0] x_thigher_than_m1_reg; +wire [6 :0] x_thigher_than_m2; +wire [6 :0] x_thigher_than_m2_reg; +wire [6 :0] x_thigher_than_m3; +wire [6 :0] x_thigher_than_m3_reg; +wire [6 :0] x_thigher_than_m4; +wire [6 :0] x_thigher_than_m4_reg; +wire [6 :0] x_thigher_than_m5; +wire [6 :0] x_thigher_than_m5_reg; +wire [6 :0] x_thigher_than_m6; +wire [6 :0] x_thigher_than_m6_reg; +wire [6 :0] x_thigher_than_m7; +wire [6 :0] x_thigher_than_m7_reg; + + +//XLEN +parameter XLEN = `TDT_DM_CORE_MAX_XLEN; + +// &Force("input","ifu_dtu_exe_addr0");&Force("bus","ifu_dtu_exe_addr0",`PA_WIDTH-1,0); @32 +// &Force("input","ifu_dtu_exe_data0");&Force("bus","ifu_dtu_exe_data0",31,0); @33 +// &Force("input","ifu_dtu_exe_addr1");&Force("bus","ifu_dtu_exe_addr1",`PA_WIDTH-1,0); @34 +// &Force("input","ifu_dtu_exe_data1");&Force("bus","ifu_dtu_exe_data1",31,0); @35 +// &Force("input","lsu_dtu_halt_info");&Force("bus","lsu_dtu_halt_info",`TDT_HINFO_WIDTH-1,0); @37 +// &Force("input","lsu_dtu_ldst_addr");&Force("bus","lsu_dtu_ldst_addr",`PA_WIDTH-1,0); @38 +// &Force("input","lsu_dtu_ldst_addr_vld"); @39 +// &Force("input","lsu_dtu_ldst_bytes_vld");&Force("bus","lsu_dtu_ldst_bytes_vld",7,0); @40 +// &Force("input","lsu_dtu_ldst_data");&Force("bus","lsu_dtu_ldst_data",XLEN-1,0); @41 +// &Force("input","lsu_dtu_ldst_data_vld"); @42 +// &Force("input","lsu_dtu_ldst_type");&Force("bus","lsu_dtu_ldst_type",1,0); @43 +// &Force("input","lsu_dtu_mem_access_size");&Force("bus","lsu_dtu_mem_access_size",1,0); @44 +// &Force("input","lsu_dtu_last_check"); @45 +// &Force("output","mcontrol_halt_info0");&Force("bus","mcontrol_halt_info0",`TDT_HINFO_WIDTH-1,0); @47 +// &Force("output","mcontrol_halt_info1");&Force("bus","mcontrol_halt_info1",`TDT_HINFO_WIDTH-1,0); @48 + +//========================================================= +// +// Instance mcontrol +// +//========================================================= +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @106 +// &Connect( @107 +// .trigger_selected (tselect_wr_en[0]), @108 +// .set_trigger_hit (mcontrol_hit), @109 +// .already_match (already_match), @110 +// .previous_trigger_chian (1'b0), @111 +// .previous_trigger_dmode (1'b0), @112 +// .next_trigger_chain (1'b0), @113 +// .next_trigger_dmode (1'b0), @114 +// .tdata1_chain (mcontrol0_chain), @115 +// .tdata1_dmode (mcontrol0_dmode), @116 +// .tdata1_action0 (mcontrol0_action0), @117 +// .tdata1_action1 (mcontrol0_action1), @118 +// .tdata1_timing (mcontrol0_timing), @119 +// .exe_mcontrol (mcontrol0_is_exe), @120 +// .ldst_mcontrol (mcontrol0_is_ldst), @121 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @122 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @123 +// .mpriority (mcontrol0_priority), @124 +// .mpriority_mask (mcontrol0_priority_mask), @125 +// .mtiming (mcontrol0_mtiming), @126 +// .mtiming_mask (mcontrol0_mtiming_mask), @127 +// .next_mpriority (2'b10), @128 +// .next_mpriority_mask (2'b00), @129 +// .next_mtiming (1'b1), @130 +// .next_mtiming_mask (1'b0), @131 +// .previous_mpriority (2'b10), @132 +// .previous_mpriority_mask (2'b00), @133 +// .previous_mtiming (1'b1), @134 +// .previous_mtiming_mask (1'b0), @135 +// .mpriority_after_chain (m0_priority), @136 +// .mpriority_mask_after_chain (m0_priority_mask), @137 +// .mtiming_after_chain (m0_mtiming), @138 +// .mtiming_mask_after_chain (m0_mtiming_mask), @139 +// .exe0_match (mcontrol0_exe0_match), @140 +// .exe1_match (mcontrol0_exe1_match), @141 +// .ldst_match (mcontrol0_ldst_match), @142 +// .tdata1 (m0_tdata1), @143 +// .tdata2 (m0_tdata2), @144 +// .tdata3 (m0_tdata3), @145 +// .tinfo (m0_tinfo), @146 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @147 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @148 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @149 +// &Force("bus","tselect_wr_en",9,0); @185 +// &Force("nonport","mcontrol0_chain"); @186 +// &Force("nonport","mcontrol0_dmode"); @187 +// &Force("nonport","mcontrol0_mtiming"); @188 +// &Force("nonport","mcontrol0_mtiming_mask"); @189 +// &Force("nonport","mcontrol0_priority"); @190 +// &Force("nonport","mcontrol0_priority_mask"); @191 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @195 +// &Connect( @196 +// .trigger_selected (tselect_wr_en[0]), @197 +// .set_trigger_hit (mcontrol_hit[0]), @198 +// .already_match (already_match[0]), @199 +// .previous_trigger_chian (1'b0), @200 +// .previous_trigger_dmode (1'b0), @201 +// .next_trigger_chain (mcontrol1_chain), @202 +// .next_trigger_dmode (mcontrol1_dmode), @203 +// .tdata1_chain (mcontrol0_chain), @204 +// .tdata1_dmode (mcontrol0_dmode), @205 +// .tdata1_action0 (mcontrol0_action0), @206 +// .tdata1_action1 (mcontrol0_action1), @207 +// .tdata1_timing (mcontrol0_timing), @208 +// .exe_mcontrol (mcontrol0_is_exe), @209 +// .ldst_mcontrol (mcontrol0_is_ldst), @210 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @211 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @212 +// .mpriority (mcontrol0_priority), @213 +// .mpriority_mask (mcontrol0_priority_mask), @214 +// .mtiming (mcontrol0_mtiming), @215 +// .mtiming_mask (mcontrol0_mtiming_mask), @216 +// .next_mpriority (mcontrol1_priority), @217 +// .next_mpriority_mask (mcontrol1_priority_mask), @218 +// .next_mtiming (mcontrol1_mtiming), @219 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @220 +// .previous_mpriority (2'b10), @221 +// .previous_mpriority_mask (2'b00), @222 +// .previous_mtiming (1'b1), @223 +// .previous_mtiming_mask (1'b0), @224 +// .mpriority_after_chain (m0_priority), @225 +// .mpriority_mask_after_chain (m0_priority_mask), @226 +// .mtiming_after_chain (m0_mtiming), @227 +// .mtiming_mask_after_chain (m0_mtiming_mask), @228 +// .exe0_match (mcontrol0_exe0_match), @229 +// .exe1_match (mcontrol0_exe1_match), @230 +// .ldst_match (mcontrol0_ldst_match), @231 +// .tdata1 (m0_tdata1), @232 +// .tdata2 (m0_tdata2), @233 +// .tdata3 (m0_tdata3), @234 +// .tinfo (m0_tinfo), @235 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @236 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @237 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @238 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @240 +// &Connect( @241 +// .trigger_selected (tselect_wr_en[1]), @242 +// .set_trigger_hit (mcontrol_hit[1]), @243 +// .already_match (already_match[1]), @244 +// .previous_trigger_chian (mcontrol0_chain), @245 +// .previous_trigger_dmode (mcontrol0_dmode), @246 +// .next_trigger_chain (1'b0), @247 +// .next_trigger_dmode (1'b0), @248 +// .tdata1_chain (mcontrol1_chain), @249 +// .tdata1_dmode (mcontrol1_dmode), @250 +// .tdata1_action0 (mcontrol1_action0), @251 +// .tdata1_action1 (mcontrol1_action1), @252 +// .tdata1_timing (mcontrol1_timing), @253 +// .exe_mcontrol (mcontrol1_is_exe), @254 +// .ldst_mcontrol (mcontrol1_is_ldst), @255 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @256 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @257 +// .mpriority (mcontrol1_priority), @258 +// .mpriority_mask (mcontrol1_priority_mask), @259 +// .mtiming (mcontrol1_mtiming), @260 +// .mtiming_mask (mcontrol1_mtiming_mask), @261 +// .next_mpriority (2'b10), @262 +// .next_mpriority_mask (2'b00), @263 +// .next_mtiming (1'b1), @264 +// .next_mtiming_mask (1'b0), @265 +// .previous_mpriority (mcontrol0_priority), @266 +// .previous_mpriority_mask (mcontrol0_priority_mask), @267 +// .previous_mtiming (mcontrol0_mtiming), @268 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @269 +// .mpriority_after_chain (m1_priority), @270 +// .mpriority_mask_after_chain (m1_priority_mask), @271 +// .mtiming_after_chain (m1_mtiming), @272 +// .mtiming_mask_after_chain (m1_mtiming_mask), @273 +// .exe0_match (mcontrol1_exe0_match), @274 +// .exe1_match (mcontrol1_exe1_match), @275 +// .ldst_match (mcontrol1_ldst_match), @276 +// .tdata1 (m1_tdata1), @277 +// .tdata2 (m1_tdata2), @278 +// .tdata3 (m1_tdata3), @279 +// .tinfo (m1_tinfo), @280 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @281 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @282 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @283 +// &Force("bus","tselect_wr_en",9,0); @314 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @318 +pa_dtu_mcontrol_0 x_pa_dtu_mcontrol_0 ( + .already_match (already_match[0] ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_write_tdata1 (cp0_write_tdata1 ), + .cp0_write_tdata2 (cp0_write_tdata2 ), + .cp0_write_tdata3 (cp0_write_tdata3 ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .exe0_16bit (exe0_16bit ), + .exe0_32bit (exe0_32bit ), + .exe0_match (mcontrol0_exe0_match ), + .exe0_may_hit (mcontrol0_exe0_may_hit ), + .exe1_16bit (exe1_16bit ), + .exe1_32bit (exe1_32bit ), + .exe1_match (mcontrol0_exe1_match ), + .exe1_may_hit (mcontrol0_exe1_may_hit ), + .exe_mcontrol (mcontrol0_is_exe ), + .forever_cpuclk (forever_cpuclk ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ldst_16bit (ldst_16bit ), + .ldst_32bit (ldst_32bit ), + .ldst_8bit (ldst_8bit ), + .ldst_addr_mcontrol (mcontrol0_is_ldst_addr ), + .ldst_data_mcontrol (mcontrol0_is_ldst_data ), + .ldst_match (mcontrol0_ldst_match ), + .ldst_may_hit (mcontrol0_ldst_may_hit ), + .ldst_mcontrol (mcontrol0_is_ldst ), + .load_addr_vld (load_addr_vld ), + .load_data_vld (load_data_vld ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .m_mode (m_mode ), + .mcontext (mcontext ), + .mpriority (mcontrol0_priority ), + .mpriority_after_chain (m0_priority ), + .mpriority_mask (mcontrol0_priority_mask ), + .mpriority_mask_after_chain (m0_priority_mask ), + .mtiming (mcontrol0_mtiming ), + .mtiming_after_chain (m0_mtiming ), + .mtiming_mask (mcontrol0_mtiming_mask ), + .mtiming_mask_after_chain (m0_mtiming_mask ), + .next_mpriority (mcontrol1_priority ), + .next_mpriority_mask (mcontrol1_priority_mask ), + .next_mtiming (mcontrol1_mtiming ), + .next_mtiming_mask (mcontrol1_mtiming_mask ), + .next_trigger_chain (mcontrol1_chain ), + .next_trigger_dmode (mcontrol1_dmode ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .previous_mpriority (2'b10 ), + .previous_mpriority_mask (2'b00 ), + .previous_mtiming (1'b1 ), + .previous_mtiming_mask (1'b0 ), + .previous_trigger_chian (1'b0 ), + .previous_trigger_dmode (1'b0 ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .set_trigger_hit (mcontrol_hit[0] ), + .store_addr_vld (store_addr_vld ), + .store_data_vld (store_data_vld ), + .tcontrol (tcontrol ), + .tdata1 (m0_tdata1 ), + .tdata1_action0 (mcontrol0_action0 ), + .tdata1_action1 (mcontrol0_action1 ), + .tdata1_chain (mcontrol0_chain ), + .tdata1_dmode (mcontrol0_dmode ), + .tdata1_timing (mcontrol0_timing ), + .tdata2 (m0_tdata2 ), + .tdata3 (m0_tdata3 ), + .tinfo (m0_tinfo ), + .trigger_selected (tselect_wr_en[0] ), + .u_mode (u_mode ) +); + +// &Connect( @319 +// .trigger_selected (tselect_wr_en[0]), @320 +// .set_trigger_hit (mcontrol_hit[0]), @321 +// .already_match (already_match[0]), @322 +// .previous_trigger_chian (1'b0), @323 +// .previous_trigger_dmode (1'b0), @324 +// .next_trigger_chain (mcontrol1_chain), @325 +// .next_trigger_dmode (mcontrol1_dmode), @326 +// .tdata1_chain (mcontrol0_chain), @327 +// .tdata1_dmode (mcontrol0_dmode), @328 +// .tdata1_action0 (mcontrol0_action0), @329 +// .tdata1_action1 (mcontrol0_action1), @330 +// .tdata1_timing (mcontrol0_timing), @331 +// .exe_mcontrol (mcontrol0_is_exe), @332 +// .ldst_mcontrol (mcontrol0_is_ldst), @333 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @334 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @335 +// .mpriority (mcontrol0_priority), @336 +// .mpriority_mask (mcontrol0_priority_mask), @337 +// .mtiming (mcontrol0_mtiming), @338 +// .mtiming_mask (mcontrol0_mtiming_mask), @339 +// .next_mpriority (mcontrol1_priority), @340 +// .next_mpriority_mask (mcontrol1_priority_mask), @341 +// .next_mtiming (mcontrol1_mtiming), @342 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @343 +// .previous_mpriority (2'b10), @344 +// .previous_mpriority_mask (2'b00), @345 +// .previous_mtiming (1'b1), @346 +// .previous_mtiming_mask (1'b0), @347 +// .mpriority_after_chain (m0_priority), @348 +// .mpriority_mask_after_chain (m0_priority_mask), @349 +// .mtiming_after_chain (m0_mtiming), @350 +// .mtiming_mask_after_chain (m0_mtiming_mask), @351 +// .exe0_match (mcontrol0_exe0_match), @352 +// .exe1_match (mcontrol0_exe1_match), @353 +// .ldst_match (mcontrol0_ldst_match), @354 +// .tdata1 (m0_tdata1), @355 +// .tdata2 (m0_tdata2), @356 +// .tdata3 (m0_tdata3), @357 +// .tinfo (m0_tinfo), @358 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @359 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @360 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @361 + +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @363 +pa_dtu_mcontrol_1 x_pa_dtu_mcontrol_1 ( + .already_match (already_match[1] ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_write_tdata1 (cp0_write_tdata1 ), + .cp0_write_tdata2 (cp0_write_tdata2 ), + .cp0_write_tdata3 (cp0_write_tdata3 ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .exe0_16bit (exe0_16bit ), + .exe0_32bit (exe0_32bit ), + .exe0_match (mcontrol1_exe0_match ), + .exe0_may_hit (mcontrol1_exe0_may_hit ), + .exe1_16bit (exe1_16bit ), + .exe1_32bit (exe1_32bit ), + .exe1_match (mcontrol1_exe1_match ), + .exe1_may_hit (mcontrol1_exe1_may_hit ), + .exe_mcontrol (mcontrol1_is_exe ), + .forever_cpuclk (forever_cpuclk ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ldst_16bit (ldst_16bit ), + .ldst_32bit (ldst_32bit ), + .ldst_8bit (ldst_8bit ), + .ldst_addr_mcontrol (mcontrol1_is_ldst_addr ), + .ldst_data_mcontrol (mcontrol1_is_ldst_data ), + .ldst_match (mcontrol1_ldst_match ), + .ldst_may_hit (mcontrol1_ldst_may_hit ), + .ldst_mcontrol (mcontrol1_is_ldst ), + .load_addr_vld (load_addr_vld ), + .load_data_vld (load_data_vld ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .m_mode (m_mode ), + .mcontext (mcontext ), + .mpriority (mcontrol1_priority ), + .mpriority_after_chain (m1_priority ), + .mpriority_mask (mcontrol1_priority_mask ), + .mpriority_mask_after_chain (m1_priority_mask ), + .mtiming (mcontrol1_mtiming ), + .mtiming_after_chain (m1_mtiming ), + .mtiming_mask (mcontrol1_mtiming_mask ), + .mtiming_mask_after_chain (m1_mtiming_mask ), + .next_mpriority (mcontrol2_priority ), + .next_mpriority_mask (mcontrol2_priority_mask ), + .next_mtiming (mcontrol2_mtiming ), + .next_mtiming_mask (mcontrol2_mtiming_mask ), + .next_trigger_chain (mcontrol2_chain ), + .next_trigger_dmode (mcontrol2_dmode ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .previous_mpriority (mcontrol0_priority ), + .previous_mpriority_mask (mcontrol0_priority_mask ), + .previous_mtiming (mcontrol0_mtiming ), + .previous_mtiming_mask (mcontrol0_mtiming_mask ), + .previous_trigger_chian (mcontrol0_chain ), + .previous_trigger_dmode (mcontrol0_dmode ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .set_trigger_hit (mcontrol_hit[1] ), + .store_addr_vld (store_addr_vld ), + .store_data_vld (store_data_vld ), + .tcontrol (tcontrol ), + .tdata1 (m1_tdata1 ), + .tdata1_action0 (mcontrol1_action0 ), + .tdata1_action1 (mcontrol1_action1 ), + .tdata1_chain (mcontrol1_chain ), + .tdata1_dmode (mcontrol1_dmode ), + .tdata1_timing (mcontrol1_timing ), + .tdata2 (m1_tdata2 ), + .tdata3 (m1_tdata3 ), + .tinfo (m1_tinfo ), + .trigger_selected (tselect_wr_en[1] ), + .u_mode (u_mode ) +); + +// &Connect( @364 +// .trigger_selected (tselect_wr_en[1]), @365 +// .set_trigger_hit (mcontrol_hit[1]), @366 +// .already_match (already_match[1]), @367 +// .previous_trigger_chian (mcontrol0_chain), @368 +// .previous_trigger_dmode (mcontrol0_dmode), @369 +// .next_trigger_chain (mcontrol2_chain), @370 +// .next_trigger_dmode (mcontrol2_dmode), @371 +// .tdata1_chain (mcontrol1_chain), @372 +// .tdata1_dmode (mcontrol1_dmode), @373 +// .tdata1_action0 (mcontrol1_action0), @374 +// .tdata1_action1 (mcontrol1_action1), @375 +// .tdata1_timing (mcontrol1_timing), @376 +// .exe_mcontrol (mcontrol1_is_exe), @377 +// .ldst_mcontrol (mcontrol1_is_ldst), @378 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @379 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @380 +// .mpriority (mcontrol1_priority), @381 +// .mpriority_mask (mcontrol1_priority_mask), @382 +// .mtiming (mcontrol1_mtiming), @383 +// .mtiming_mask (mcontrol1_mtiming_mask), @384 +// .next_mpriority (mcontrol2_priority), @385 +// .next_mpriority_mask (mcontrol2_priority_mask), @386 +// .next_mtiming (mcontrol2_mtiming), @387 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @388 +// .previous_mpriority (mcontrol0_priority), @389 +// .previous_mpriority_mask (mcontrol0_priority_mask), @390 +// .previous_mtiming (mcontrol0_mtiming), @391 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @392 +// .mpriority_after_chain (m1_priority), @393 +// .mpriority_mask_after_chain (m1_priority_mask), @394 +// .mtiming_after_chain (m1_mtiming), @395 +// .mtiming_mask_after_chain (m1_mtiming_mask), @396 +// .exe0_match (mcontrol1_exe0_match), @397 +// .exe1_match (mcontrol1_exe1_match), @398 +// .ldst_match (mcontrol1_ldst_match), @399 +// .tdata1 (m1_tdata1), @400 +// .tdata2 (m1_tdata2), @401 +// .tdata3 (m1_tdata3), @402 +// .tinfo (m1_tinfo), @403 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @404 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @405 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @406 + +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @408 +pa_dtu_mcontrol_2 x_pa_dtu_mcontrol_2 ( + .already_match (already_match[2] ), + .cp0_dtu_icg_en (cp0_dtu_icg_en ), + .cp0_dtu_wdata (cp0_dtu_wdata ), + .cp0_write_tdata1 (cp0_write_tdata1 ), + .cp0_write_tdata2 (cp0_write_tdata2 ), + .cp0_write_tdata3 (cp0_write_tdata3 ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .exe0_16bit (exe0_16bit ), + .exe0_32bit (exe0_32bit ), + .exe0_match (mcontrol2_exe0_match ), + .exe0_may_hit (mcontrol2_exe0_may_hit ), + .exe1_16bit (exe1_16bit ), + .exe1_32bit (exe1_32bit ), + .exe1_match (mcontrol2_exe1_match ), + .exe1_may_hit (mcontrol2_exe1_may_hit ), + .exe_mcontrol (mcontrol2_is_exe ), + .forever_cpuclk (forever_cpuclk ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ldst_16bit (ldst_16bit ), + .ldst_32bit (ldst_32bit ), + .ldst_8bit (ldst_8bit ), + .ldst_addr_mcontrol (mcontrol2_is_ldst_addr ), + .ldst_data_mcontrol (mcontrol2_is_ldst_data ), + .ldst_match (mcontrol2_ldst_match ), + .ldst_may_hit (mcontrol2_ldst_may_hit ), + .ldst_mcontrol (mcontrol2_is_ldst ), + .load_addr_vld (load_addr_vld ), + .load_data_vld (load_data_vld ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .m_mode (m_mode ), + .mcontext (mcontext ), + .mpriority (mcontrol2_priority ), + .mpriority_after_chain (m2_priority ), + .mpriority_mask (mcontrol2_priority_mask ), + .mpriority_mask_after_chain (m2_priority_mask ), + .mtiming (mcontrol2_mtiming ), + .mtiming_after_chain (m2_mtiming ), + .mtiming_mask (mcontrol2_mtiming_mask ), + .mtiming_mask_after_chain (m2_mtiming_mask ), + .next_mpriority (2'b10 ), + .next_mpriority_mask (2'b00 ), + .next_mtiming (1'b0 ), + .next_mtiming_mask (1'b0 ), + .next_trigger_chain (1'b0 ), + .next_trigger_dmode (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .previous_mpriority (mcontrol1_priority ), + .previous_mpriority_mask (mcontrol1_priority_mask ), + .previous_mtiming (mcontrol1_mtiming ), + .previous_mtiming_mask (mcontrol1_mtiming_mask ), + .previous_trigger_chian (mcontrol1_chain ), + .previous_trigger_dmode (mcontrol1_dmode ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .set_trigger_hit (mcontrol_hit[2] ), + .store_addr_vld (store_addr_vld ), + .store_data_vld (store_data_vld ), + .tcontrol (tcontrol ), + .tdata1 (m2_tdata1 ), + .tdata1_action0 (mcontrol2_action0 ), + .tdata1_action1 (mcontrol2_action1 ), + .tdata1_chain (mcontrol2_chain ), + .tdata1_dmode (mcontrol2_dmode ), + .tdata1_timing (mcontrol2_timing ), + .tdata2 (m2_tdata2 ), + .tdata3 (m2_tdata3 ), + .tinfo (m2_tinfo ), + .trigger_selected (tselect_wr_en[2] ), + .u_mode (u_mode ) +); + +// &Connect( @409 +// .trigger_selected (tselect_wr_en[2]), @410 +// .set_trigger_hit (mcontrol_hit[2]), @411 +// .already_match (already_match[2]), @412 +// .previous_trigger_chian (mcontrol1_chain), @413 +// .previous_trigger_dmode (mcontrol1_dmode), @414 +// .next_trigger_chain (1'b0), @415 +// .next_trigger_dmode (1'b0), @416 +// .tdata1_chain (mcontrol2_chain), @417 +// .tdata1_dmode (mcontrol2_dmode), @418 +// .tdata1_action0 (mcontrol2_action0), @419 +// .tdata1_action1 (mcontrol2_action1), @420 +// .tdata1_timing (mcontrol2_timing), @421 +// .exe_mcontrol (mcontrol2_is_exe), @422 +// .ldst_mcontrol (mcontrol2_is_ldst), @423 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @424 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @425 +// .mpriority (mcontrol2_priority), @426 +// .mpriority_mask (mcontrol2_priority_mask), @427 +// .mtiming (mcontrol2_mtiming), @428 +// .mtiming_mask (mcontrol2_mtiming_mask), @429 +// .next_mpriority (2'b10), @430 +// .next_mpriority_mask (2'b00), @431 +// .next_mtiming (1'b0), @432 +// .next_mtiming_mask (1'b0), @433 +// .previous_mpriority (mcontrol1_priority), @434 +// .previous_mpriority_mask (mcontrol1_priority_mask), @435 +// .previous_mtiming (mcontrol1_mtiming), @436 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @437 +// .mpriority_after_chain (m2_priority), @438 +// .mpriority_mask_after_chain (m2_priority_mask), @439 +// .mtiming_after_chain (m2_mtiming), @440 +// .mtiming_mask_after_chain (m2_mtiming_mask), @441 +// .exe0_match (mcontrol2_exe0_match), @442 +// .exe1_match (mcontrol2_exe1_match), @443 +// .ldst_match (mcontrol2_ldst_match), @444 +// .tdata1 (m2_tdata1), @445 +// .tdata2 (m2_tdata2), @446 +// .tdata3 (m2_tdata3), @447 +// .tinfo (m2_tinfo), @448 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @449 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @450 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @451 + +assign m3_tdata1[XLEN-1:0] = {XLEN{1'b1}}; +assign m3_tdata2[XLEN-1:0] = {XLEN{1'b1}}; +assign m3_tdata3[XLEN-1:0] = {XLEN{1'b1}}; +assign m3_tinfo[XLEN-1:0] = {XLEN{1'b1}}; + +assign m4_tdata1[XLEN-1:0] = {XLEN{1'b1}}; +assign m4_tdata2[XLEN-1:0] = {XLEN{1'b1}}; +assign m4_tdata3[XLEN-1:0] = {XLEN{1'b1}}; +assign m4_tinfo[XLEN-1:0] = {XLEN{1'b1}}; + +assign m5_tdata1[XLEN-1:0] = {XLEN{1'b1}}; +assign m5_tdata2[XLEN-1:0] = {XLEN{1'b1}}; +assign m5_tdata3[XLEN-1:0] = {XLEN{1'b1}}; +assign m5_tinfo[XLEN-1:0] = {XLEN{1'b1}}; + +assign m6_tdata1[XLEN-1:0] = {XLEN{1'b1}}; +assign m6_tdata2[XLEN-1:0] = {XLEN{1'b1}}; +assign m6_tdata3[XLEN-1:0] = {XLEN{1'b1}}; +assign m6_tinfo[XLEN-1:0] = {XLEN{1'b1}}; + +assign m7_tdata1[XLEN-1:0] = {XLEN{1'b1}}; +assign m7_tdata2[XLEN-1:0] = {XLEN{1'b1}}; +assign m7_tdata3[XLEN-1:0] = {XLEN{1'b1}}; +assign m7_tinfo[XLEN-1:0] = {XLEN{1'b1}}; +// &Force("bus","tselect_wr_en",9,0); @477 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @481 +// &Connect( @482 +// .trigger_selected (tselect_wr_en[0]), @483 +// .set_trigger_hit (mcontrol_hit[0]), @484 +// .already_match (already_match[0]), @485 +// .previous_trigger_chian (1'b0), @486 +// .previous_trigger_dmode (1'b0), @487 +// .next_trigger_chain (mcontrol1_chain), @488 +// .next_trigger_dmode (mcontrol1_dmode), @489 +// .tdata1_chain (mcontrol0_chain), @490 +// .tdata1_dmode (mcontrol0_dmode), @491 +// .tdata1_action0 (mcontrol0_action0), @492 +// .tdata1_action1 (mcontrol0_action1), @493 +// .tdata1_timing (mcontrol0_timing), @494 +// .exe_mcontrol (mcontrol0_is_exe), @495 +// .ldst_mcontrol (mcontrol0_is_ldst), @496 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @497 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @498 +// .mpriority (mcontrol0_priority), @499 +// .mpriority_mask (mcontrol0_priority_mask), @500 +// .mtiming (mcontrol0_mtiming), @501 +// .mtiming_mask (mcontrol0_mtiming_mask), @502 +// .next_mpriority (mcontrol1_priority), @503 +// .next_mpriority_mask (mcontrol1_priority_mask), @504 +// .next_mtiming (mcontrol1_mtiming), @505 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @506 +// .previous_mpriority (2'b10), @507 +// .previous_mpriority_mask (2'b00), @508 +// .previous_mtiming (1'b1), @509 +// .previous_mtiming_mask (1'b0), @510 +// .mpriority_after_chain (m0_priority), @511 +// .mpriority_mask_after_chain (m0_priority_mask), @512 +// .mtiming_after_chain (m0_mtiming), @513 +// .mtiming_mask_after_chain (m0_mtiming_mask), @514 +// .exe0_match (mcontrol0_exe0_match), @515 +// .exe1_match (mcontrol0_exe1_match), @516 +// .ldst_match (mcontrol0_ldst_match), @517 +// .tdata1 (m0_tdata1), @518 +// .tdata2 (m0_tdata2), @519 +// .tdata3 (m0_tdata3), @520 +// .tinfo (m0_tinfo), @521 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @522 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @523 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @524 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @526 +// &Connect( @527 +// .trigger_selected (tselect_wr_en[1]), @528 +// .set_trigger_hit (mcontrol_hit[1]), @529 +// .already_match (already_match[1]), @530 +// .previous_trigger_chian (mcontrol0_chain), @531 +// .previous_trigger_dmode (mcontrol0_dmode), @532 +// .next_trigger_chain (mcontrol2_chain), @533 +// .next_trigger_dmode (mcontrol2_dmode), @534 +// .tdata1_chain (mcontrol1_chain), @535 +// .tdata1_dmode (mcontrol1_dmode), @536 +// .tdata1_action0 (mcontrol1_action0), @537 +// .tdata1_action1 (mcontrol1_action1), @538 +// .tdata1_timing (mcontrol1_timing), @539 +// .exe_mcontrol (mcontrol1_is_exe), @540 +// .ldst_mcontrol (mcontrol1_is_ldst), @541 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @542 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @543 +// .mpriority (mcontrol1_priority), @544 +// .mpriority_mask (mcontrol1_priority_mask), @545 +// .mtiming (mcontrol1_mtiming), @546 +// .mtiming_mask (mcontrol1_mtiming_mask), @547 +// .next_mpriority (mcontrol2_priority), @548 +// .next_mpriority_mask (mcontrol2_priority_mask), @549 +// .next_mtiming (mcontrol2_mtiming), @550 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @551 +// .previous_mpriority (mcontrol0_priority), @552 +// .previous_mpriority_mask (mcontrol0_priority_mask), @553 +// .previous_mtiming (mcontrol0_mtiming), @554 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @555 +// .mpriority_after_chain (m1_priority), @556 +// .mpriority_mask_after_chain (m1_priority_mask), @557 +// .mtiming_after_chain (m1_mtiming), @558 +// .mtiming_mask_after_chain (m1_mtiming_mask), @559 +// .exe0_match (mcontrol1_exe0_match), @560 +// .exe1_match (mcontrol1_exe1_match), @561 +// .ldst_match (mcontrol1_ldst_match), @562 +// .tdata1 (m1_tdata1), @563 +// .tdata2 (m1_tdata2), @564 +// .tdata3 (m1_tdata3), @565 +// .tinfo (m1_tinfo), @566 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @567 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @568 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @569 +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @571 +// &Connect( @572 +// .trigger_selected (tselect_wr_en[2]), @573 +// .set_trigger_hit (mcontrol_hit[2]), @574 +// .already_match (already_match[2]), @575 +// .previous_trigger_chian (mcontrol1_chain), @576 +// .previous_trigger_dmode (mcontrol1_dmode), @577 +// .next_trigger_chain (mcontrol3_chain), @578 +// .next_trigger_dmode (mcontrol3_dmode), @579 +// .tdata1_chain (mcontrol2_chain), @580 +// .tdata1_dmode (mcontrol2_dmode), @581 +// .tdata1_action0 (mcontrol2_action0), @582 +// .tdata1_action1 (mcontrol2_action1), @583 +// .tdata1_timing (mcontrol2_timing), @584 +// .exe_mcontrol (mcontrol2_is_exe), @585 +// .ldst_mcontrol (mcontrol2_is_ldst), @586 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @587 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @588 +// .mpriority (mcontrol2_priority), @589 +// .mpriority_mask (mcontrol2_priority_mask), @590 +// .mtiming (mcontrol2_mtiming), @591 +// .mtiming_mask (mcontrol2_mtiming_mask), @592 +// .next_mpriority (mcontrol3_priority), @593 +// .next_mpriority_mask (mcontrol3_priority_mask), @594 +// .next_mtiming (mcontrol3_mtiming), @595 +// .next_mtiming_mask (mcontrol3_mtiming_mask), @596 +// .previous_mpriority (mcontrol1_priority), @597 +// .previous_mpriority_mask (mcontrol1_priority_mask), @598 +// .previous_mtiming (mcontrol1_mtiming), @599 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @600 +// .mpriority_after_chain (m2_priority), @601 +// .mpriority_mask_after_chain (m2_priority_mask), @602 +// .mtiming_after_chain (m2_mtiming), @603 +// .mtiming_mask_after_chain (m2_mtiming_mask), @604 +// .exe0_match (mcontrol2_exe0_match), @605 +// .exe1_match (mcontrol2_exe1_match), @606 +// .ldst_match (mcontrol2_ldst_match), @607 +// .tdata1 (m2_tdata1), @608 +// .tdata2 (m2_tdata2), @609 +// .tdata3 (m2_tdata3), @610 +// .tinfo (m2_tinfo), @611 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @612 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @613 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @614 +// &Instance("pa_dtu_mcontrol_3","x_pa_dtu_mcontrol_3"); @616 +// &Connect( @617 +// .trigger_selected (tselect_wr_en[3]), @618 +// .set_trigger_hit (mcontrol_hit[3]), @619 +// .already_match (already_match[3]), @620 +// .previous_trigger_chian (mcontrol2_chain), @621 +// .previous_trigger_dmode (mcontrol2_dmode), @622 +// .next_trigger_chain (1'b0), @623 +// .next_trigger_dmode (1'b0), @624 +// .tdata1_chain (mcontrol3_chain), @625 +// .tdata1_dmode (mcontrol3_dmode), @626 +// .tdata1_action0 (mcontrol3_action0), @627 +// .tdata1_action1 (mcontrol3_action1), @628 +// .tdata1_timing (mcontrol3_timing), @629 +// .exe_mcontrol (mcontrol3_is_exe), @630 +// .ldst_mcontrol (mcontrol3_is_ldst), @631 +// .ldst_addr_mcontrol (mcontrol3_is_ldst_addr), @632 +// .ldst_data_mcontrol (mcontrol3_is_ldst_data), @633 +// .mpriority (mcontrol3_priority), @634 +// .mpriority_mask (mcontrol3_priority_mask), @635 +// .mtiming (mcontrol3_mtiming), @636 +// .mtiming_mask (mcontrol3_mtiming_mask), @637 +// .next_mpriority (2'b10), @638 +// .next_mpriority_mask (2'b00), @639 +// .next_mtiming (1'b1), @640 +// .next_mtiming_mask (1'b0), @641 +// .previous_mpriority (mcontrol2_priority), @642 +// .previous_mpriority_mask (mcontrol2_priority_mask), @643 +// .previous_mtiming (mcontrol2_mtiming), @644 +// .previous_mtiming_mask (mcontrol2_mtiming_mask), @645 +// .mpriority_after_chain (m3_priority), @646 +// .mpriority_mask_after_chain (m3_priority_mask), @647 +// .mtiming_after_chain (m3_mtiming), @648 +// .mtiming_mask_after_chain (m3_mtiming_mask), @649 +// .exe0_match (mcontrol3_exe0_match), @650 +// .exe1_match (mcontrol3_exe1_match), @651 +// .ldst_match (mcontrol3_ldst_match), @652 +// .tdata1 (m3_tdata1), @653 +// .tdata2 (m3_tdata2), @654 +// .tdata3 (m3_tdata3), @655 +// .tinfo (m3_tinfo), @656 +// .ldst_may_hit (mcontrol3_ldst_may_hit), @657 +// .exe0_may_hit (mcontrol3_exe0_may_hit), @658 +// .exe1_may_hit (mcontrol3_exe1_may_hit)); @659 +// &Force("bus","tselect_wr_en",9,0); @680 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @684 +// &Connect( @685 +// .trigger_selected (tselect_wr_en[0]), @686 +// .set_trigger_hit (mcontrol_hit[0]), @687 +// .already_match (already_match[0]), @688 +// .previous_trigger_chian (1'b0), @689 +// .previous_trigger_dmode (1'b0), @690 +// .next_trigger_chain (mcontrol1_chain), @691 +// .next_trigger_dmode (mcontrol1_dmode), @692 +// .tdata1_chain (mcontrol0_chain), @693 +// .tdata1_dmode (mcontrol0_dmode), @694 +// .tdata1_action0 (mcontrol0_action0), @695 +// .tdata1_action1 (mcontrol0_action1), @696 +// .tdata1_timing (mcontrol0_timing), @697 +// .exe_mcontrol (mcontrol0_is_exe), @698 +// .ldst_mcontrol (mcontrol0_is_ldst), @699 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @700 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @701 +// .mpriority (mcontrol0_priority), @702 +// .mpriority_mask (mcontrol0_priority_mask), @703 +// .mtiming (mcontrol0_mtiming), @704 +// .mtiming_mask (mcontrol0_mtiming_mask), @705 +// .next_mpriority (mcontrol1_priority), @706 +// .next_mpriority_mask (mcontrol1_priority_mask), @707 +// .next_mtiming (mcontrol1_mtiming), @708 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @709 +// .previous_mpriority (2'b10), @710 +// .previous_mpriority_mask (2'b00), @711 +// .previous_mtiming (1'b1), @712 +// .previous_mtiming_mask (1'b0), @713 +// .mpriority_after_chain (m0_priority), @714 +// .mpriority_mask_after_chain (m0_priority_mask), @715 +// .mtiming_after_chain (m0_mtiming), @716 +// .mtiming_mask_after_chain (m0_mtiming_mask), @717 +// .exe0_match (mcontrol0_exe0_match), @718 +// .exe1_match (mcontrol0_exe1_match), @719 +// .ldst_match (mcontrol0_ldst_match), @720 +// .tdata1 (m0_tdata1), @721 +// .tdata2 (m0_tdata2), @722 +// .tdata3 (m0_tdata3), @723 +// .tinfo (m0_tinfo), @724 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @725 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @726 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @727 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @729 +// &Connect( @730 +// .trigger_selected (tselect_wr_en[1]), @731 +// .set_trigger_hit (mcontrol_hit[1]), @732 +// .already_match (already_match[1]), @733 +// .previous_trigger_chian (mcontrol0_chain), @734 +// .previous_trigger_dmode (mcontrol0_dmode), @735 +// .next_trigger_chain (mcontrol2_chain), @736 +// .next_trigger_dmode (mcontrol2_dmode), @737 +// .tdata1_chain (mcontrol1_chain), @738 +// .tdata1_dmode (mcontrol1_dmode), @739 +// .tdata1_action0 (mcontrol1_action0), @740 +// .tdata1_action1 (mcontrol1_action1), @741 +// .tdata1_timing (mcontrol1_timing), @742 +// .exe_mcontrol (mcontrol1_is_exe), @743 +// .ldst_mcontrol (mcontrol1_is_ldst), @744 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @745 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @746 +// .mpriority (mcontrol1_priority), @747 +// .mpriority_mask (mcontrol1_priority_mask), @748 +// .mtiming (mcontrol1_mtiming), @749 +// .mtiming_mask (mcontrol1_mtiming_mask), @750 +// .next_mpriority (mcontrol2_priority), @751 +// .next_mpriority_mask (mcontrol2_priority_mask), @752 +// .next_mtiming (mcontrol2_mtiming), @753 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @754 +// .previous_mpriority (mcontrol0_priority), @755 +// .previous_mpriority_mask (mcontrol0_priority_mask), @756 +// .previous_mtiming (mcontrol0_mtiming), @757 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @758 +// .mpriority_after_chain (m1_priority), @759 +// .mpriority_mask_after_chain (m1_priority_mask), @760 +// .mtiming_after_chain (m1_mtiming), @761 +// .mtiming_mask_after_chain (m1_mtiming_mask), @762 +// .exe0_match (mcontrol1_exe0_match), @763 +// .exe1_match (mcontrol1_exe1_match), @764 +// .ldst_match (mcontrol1_ldst_match), @765 +// .tdata1 (m1_tdata1), @766 +// .tdata2 (m1_tdata2), @767 +// .tdata3 (m1_tdata3), @768 +// .tinfo (m1_tinfo), @769 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @770 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @771 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @772 +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @774 +// &Connect( @775 +// .trigger_selected (tselect_wr_en[2]), @776 +// .set_trigger_hit (mcontrol_hit[2]), @777 +// .already_match (already_match[2]), @778 +// .previous_trigger_chian (mcontrol1_chain), @779 +// .previous_trigger_dmode (mcontrol1_dmode), @780 +// .next_trigger_chain (mcontrol3_chain), @781 +// .next_trigger_dmode (mcontrol3_dmode), @782 +// .tdata1_chain (mcontrol2_chain), @783 +// .tdata1_dmode (mcontrol2_dmode), @784 +// .tdata1_action0 (mcontrol2_action0), @785 +// .tdata1_action1 (mcontrol2_action1), @786 +// .tdata1_timing (mcontrol2_timing), @787 +// .exe_mcontrol (mcontrol2_is_exe), @788 +// .ldst_mcontrol (mcontrol2_is_ldst), @789 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @790 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @791 +// .mpriority (mcontrol2_priority), @792 +// .mpriority_mask (mcontrol2_priority_mask), @793 +// .mtiming (mcontrol2_mtiming), @794 +// .mtiming_mask (mcontrol2_mtiming_mask), @795 +// .next_mpriority (mcontrol3_priority), @796 +// .next_mpriority_mask (mcontrol3_priority_mask), @797 +// .next_mtiming (mcontrol3_mtiming), @798 +// .next_mtiming_mask (mcontrol3_mtiming_mask), @799 +// .previous_mpriority (mcontrol1_priority), @800 +// .previous_mpriority_mask (mcontrol1_priority_mask), @801 +// .previous_mtiming (mcontrol1_mtiming), @802 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @803 +// .mpriority_after_chain (m2_priority), @804 +// .mpriority_mask_after_chain (m2_priority_mask), @805 +// .mtiming_after_chain (m2_mtiming), @806 +// .mtiming_mask_after_chain (m2_mtiming_mask), @807 +// .exe0_match (mcontrol2_exe0_match), @808 +// .exe1_match (mcontrol2_exe1_match), @809 +// .ldst_match (mcontrol2_ldst_match), @810 +// .tdata1 (m2_tdata1), @811 +// .tdata2 (m2_tdata2), @812 +// .tdata3 (m2_tdata3), @813 +// .tinfo (m2_tinfo), @814 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @815 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @816 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @817 +// &Instance("pa_dtu_mcontrol_3","x_pa_dtu_mcontrol_3"); @819 +// &Connect( @820 +// .trigger_selected (tselect_wr_en[3]), @821 +// .set_trigger_hit (mcontrol_hit[3]), @822 +// .already_match (already_match[3]), @823 +// .previous_trigger_chian (mcontrol2_chain), @824 +// .previous_trigger_dmode (mcontrol2_dmode), @825 +// .next_trigger_chain (mcontrol4_chain), @826 +// .next_trigger_dmode (mcontrol4_dmode), @827 +// .tdata1_chain (mcontrol3_chain), @828 +// .tdata1_dmode (mcontrol3_dmode), @829 +// .tdata1_action0 (mcontrol3_action0), @830 +// .tdata1_action1 (mcontrol3_action1), @831 +// .tdata1_timing (mcontrol3_timing), @832 +// .exe_mcontrol (mcontrol3_is_exe), @833 +// .ldst_mcontrol (mcontrol3_is_ldst), @834 +// .ldst_addr_mcontrol (mcontrol3_is_ldst_addr), @835 +// .ldst_data_mcontrol (mcontrol3_is_ldst_data), @836 +// .mpriority (mcontrol3_priority), @837 +// .mpriority_mask (mcontrol3_priority_mask), @838 +// .mtiming (mcontrol3_mtiming), @839 +// .mtiming_mask (mcontrol3_mtiming_mask), @840 +// .next_mpriority (mcontrol4_priority), @841 +// .next_mpriority_mask (mcontrol4_priority_mask), @842 +// .next_mtiming (mcontrol4_mtiming), @843 +// .next_mtiming_mask (mcontrol4_mtiming_mask), @844 +// .previous_mpriority (mcontrol2_priority), @845 +// .previous_mpriority_mask (mcontrol2_priority_mask), @846 +// .previous_mtiming (mcontrol2_mtiming), @847 +// .previous_mtiming_mask (mcontrol2_mtiming_mask), @848 +// .mpriority_after_chain (m3_priority), @849 +// .mpriority_mask_after_chain (m3_priority_mask), @850 +// .mtiming_after_chain (m3_mtiming), @851 +// .mtiming_mask_after_chain (m3_mtiming_mask), @852 +// .exe0_match (mcontrol3_exe0_match), @853 +// .exe1_match (mcontrol3_exe1_match), @854 +// .ldst_match (mcontrol3_ldst_match), @855 +// .tdata1 (m3_tdata1), @856 +// .tdata2 (m3_tdata2), @857 +// .tdata3 (m3_tdata3), @858 +// .tinfo (m3_tinfo), @859 +// .ldst_may_hit (mcontrol3_ldst_may_hit), @860 +// .exe0_may_hit (mcontrol3_exe0_may_hit), @861 +// .exe1_may_hit (mcontrol3_exe1_may_hit)); @862 +// &Instance("pa_dtu_mcontrol_4","x_pa_dtu_mcontrol_4"); @864 +// &Connect( @865 +// .trigger_selected (tselect_wr_en[4]), @866 +// .set_trigger_hit (mcontrol_hit[4]), @867 +// .already_match (already_match[4]), @868 +// .previous_trigger_chian (mcontrol3_chain), @869 +// .previous_trigger_dmode (mcontrol3_dmode), @870 +// .next_trigger_chain (1'b0), @871 +// .next_trigger_dmode (1'b0), @872 +// .tdata1_chain (mcontrol4_chain), @873 +// .tdata1_dmode (mcontrol4_dmode), @874 +// .tdata1_action0 (mcontrol4_action0), @875 +// .tdata1_action1 (mcontrol4_action1), @876 +// .tdata1_timing (mcontrol4_timing), @877 +// .exe_mcontrol (mcontrol4_is_exe), @878 +// .ldst_mcontrol (mcontrol4_is_ldst), @879 +// .ldst_addr_mcontrol (mcontrol4_is_ldst_addr), @880 +// .ldst_data_mcontrol (mcontrol4_is_ldst_data), @881 +// .mpriority (mcontrol4_priority), @882 +// .mpriority_mask (mcontrol4_priority_mask), @883 +// .mtiming (mcontrol4_mtiming), @884 +// .mtiming_mask (mcontrol4_mtiming_mask), @885 +// .next_mpriority (2'b10), @886 +// .next_mpriority_mask (2'b00), @887 +// .next_mtiming (1'b1), @888 +// .next_mtiming_mask (1'b0), @889 +// .previous_mpriority (mcontrol3_priority), @890 +// .previous_mpriority_mask (mcontrol3_priority_mask), @891 +// .previous_mtiming (mcontrol3_mtiming), @892 +// .previous_mtiming_mask (mcontrol3_mtiming_mask), @893 +// .mpriority_after_chain (m4_priority), @894 +// .mpriority_mask_after_chain (m4_priority_mask), @895 +// .mtiming_after_chain (m4_mtiming), @896 +// .mtiming_mask_after_chain (m4_mtiming_mask), @897 +// .exe0_match (mcontrol4_exe0_match), @898 +// .exe1_match (mcontrol4_exe1_match), @899 +// .ldst_match (mcontrol4_ldst_match), @900 +// .tdata1 (m4_tdata1), @901 +// .tdata2 (m4_tdata2), @902 +// .tdata3 (m4_tdata3), @903 +// .tinfo (m4_tinfo), @904 +// .ldst_may_hit (mcontrol4_ldst_may_hit), @905 +// .exe0_may_hit (mcontrol4_exe0_may_hit), @906 +// .exe1_may_hit (mcontrol4_exe1_may_hit)); @907 +// &Force("bus","tselect_wr_en",9,0); @923 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @927 +// &Connect( @928 +// .trigger_selected (tselect_wr_en[0]), @929 +// .set_trigger_hit (mcontrol_hit[0]), @930 +// .already_match (already_match[0]), @931 +// .previous_trigger_chian (1'b0), @932 +// .previous_trigger_dmode (1'b0), @933 +// .next_trigger_chain (mcontrol1_chain), @934 +// .next_trigger_dmode (mcontrol1_dmode), @935 +// .tdata1_chain (mcontrol0_chain), @936 +// .tdata1_dmode (mcontrol0_dmode), @937 +// .tdata1_action0 (mcontrol0_action0), @938 +// .tdata1_action1 (mcontrol0_action1), @939 +// .tdata1_timing (mcontrol0_timing), @940 +// .exe_mcontrol (mcontrol0_is_exe), @941 +// .ldst_mcontrol (mcontrol0_is_ldst), @942 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @943 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @944 +// .mpriority (mcontrol0_priority), @945 +// .mpriority_mask (mcontrol0_priority_mask), @946 +// .mtiming (mcontrol0_mtiming), @947 +// .mtiming_mask (mcontrol0_mtiming_mask), @948 +// .next_mpriority (mcontrol1_priority), @949 +// .next_mpriority_mask (mcontrol1_priority_mask), @950 +// .next_mtiming (mcontrol1_mtiming), @951 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @952 +// .previous_mpriority (2'b10), @953 +// .previous_mpriority_mask (2'b00), @954 +// .previous_mtiming (1'b1), @955 +// .previous_mtiming_mask (1'b0), @956 +// .mpriority_after_chain (m0_priority), @957 +// .mpriority_mask_after_chain (m0_priority_mask), @958 +// .mtiming_after_chain (m0_mtiming), @959 +// .mtiming_mask_after_chain (m0_mtiming_mask), @960 +// .exe0_match (mcontrol0_exe0_match), @961 +// .exe1_match (mcontrol0_exe1_match), @962 +// .ldst_match (mcontrol0_ldst_match), @963 +// .tdata1 (m0_tdata1), @964 +// .tdata2 (m0_tdata2), @965 +// .tdata3 (m0_tdata3), @966 +// .tinfo (m0_tinfo), @967 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @968 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @969 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @970 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @972 +// &Connect( @973 +// .trigger_selected (tselect_wr_en[1]), @974 +// .set_trigger_hit (mcontrol_hit[1]), @975 +// .already_match (already_match[1]), @976 +// .previous_trigger_chian (mcontrol0_chain), @977 +// .previous_trigger_dmode (mcontrol0_dmode), @978 +// .next_trigger_chain (mcontrol2_chain), @979 +// .next_trigger_dmode (mcontrol2_dmode), @980 +// .tdata1_chain (mcontrol1_chain), @981 +// .tdata1_dmode (mcontrol1_dmode), @982 +// .tdata1_action0 (mcontrol1_action0), @983 +// .tdata1_action1 (mcontrol1_action1), @984 +// .tdata1_timing (mcontrol1_timing), @985 +// .exe_mcontrol (mcontrol1_is_exe), @986 +// .ldst_mcontrol (mcontrol1_is_ldst), @987 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @988 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @989 +// .mpriority (mcontrol1_priority), @990 +// .mpriority_mask (mcontrol1_priority_mask), @991 +// .mtiming (mcontrol1_mtiming), @992 +// .mtiming_mask (mcontrol1_mtiming_mask), @993 +// .next_mpriority (mcontrol2_priority), @994 +// .next_mpriority_mask (mcontrol2_priority_mask), @995 +// .next_mtiming (mcontrol2_mtiming), @996 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @997 +// .previous_mpriority (mcontrol0_priority), @998 +// .previous_mpriority_mask (mcontrol0_priority_mask), @999 +// .previous_mtiming (mcontrol0_mtiming), @1000 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @1001 +// .mpriority_after_chain (m1_priority), @1002 +// .mpriority_mask_after_chain (m1_priority_mask), @1003 +// .mtiming_after_chain (m1_mtiming), @1004 +// .mtiming_mask_after_chain (m1_mtiming_mask), @1005 +// .exe0_match (mcontrol1_exe0_match), @1006 +// .exe1_match (mcontrol1_exe1_match), @1007 +// .ldst_match (mcontrol1_ldst_match), @1008 +// .tdata1 (m1_tdata1), @1009 +// .tdata2 (m1_tdata2), @1010 +// .tdata3 (m1_tdata3), @1011 +// .tinfo (m1_tinfo), @1012 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @1013 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @1014 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @1015 +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @1017 +// &Connect( @1018 +// .trigger_selected (tselect_wr_en[2]), @1019 +// .set_trigger_hit (mcontrol_hit[2]), @1020 +// .already_match (already_match[2]), @1021 +// .previous_trigger_chian (mcontrol1_chain), @1022 +// .previous_trigger_dmode (mcontrol1_dmode), @1023 +// .next_trigger_chain (mcontrol3_chain), @1024 +// .next_trigger_dmode (mcontrol3_dmode), @1025 +// .tdata1_chain (mcontrol2_chain), @1026 +// .tdata1_dmode (mcontrol2_dmode), @1027 +// .tdata1_action0 (mcontrol2_action0), @1028 +// .tdata1_action1 (mcontrol2_action1), @1029 +// .tdata1_timing (mcontrol2_timing), @1030 +// .exe_mcontrol (mcontrol2_is_exe), @1031 +// .ldst_mcontrol (mcontrol2_is_ldst), @1032 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @1033 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @1034 +// .mpriority (mcontrol2_priority), @1035 +// .mpriority_mask (mcontrol2_priority_mask), @1036 +// .mtiming (mcontrol2_mtiming), @1037 +// .mtiming_mask (mcontrol2_mtiming_mask), @1038 +// .next_mpriority (mcontrol3_priority), @1039 +// .next_mpriority_mask (mcontrol3_priority_mask), @1040 +// .next_mtiming (mcontrol3_mtiming), @1041 +// .next_mtiming_mask (mcontrol3_mtiming_mask), @1042 +// .previous_mpriority (mcontrol1_priority), @1043 +// .previous_mpriority_mask (mcontrol1_priority_mask), @1044 +// .previous_mtiming (mcontrol1_mtiming), @1045 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @1046 +// .mpriority_after_chain (m2_priority), @1047 +// .mpriority_mask_after_chain (m2_priority_mask), @1048 +// .mtiming_after_chain (m2_mtiming), @1049 +// .mtiming_mask_after_chain (m2_mtiming_mask), @1050 +// .exe0_match (mcontrol2_exe0_match), @1051 +// .exe1_match (mcontrol2_exe1_match), @1052 +// .ldst_match (mcontrol2_ldst_match), @1053 +// .tdata1 (m2_tdata1), @1054 +// .tdata2 (m2_tdata2), @1055 +// .tdata3 (m2_tdata3), @1056 +// .tinfo (m2_tinfo), @1057 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @1058 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @1059 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @1060 +// &Instance("pa_dtu_mcontrol_3","x_pa_dtu_mcontrol_3"); @1062 +// &Connect( @1063 +// .trigger_selected (tselect_wr_en[3]), @1064 +// .set_trigger_hit (mcontrol_hit[3]), @1065 +// .already_match (already_match[3]), @1066 +// .previous_trigger_chian (mcontrol2_chain), @1067 +// .previous_trigger_dmode (mcontrol2_dmode), @1068 +// .next_trigger_chain (mcontrol4_chain), @1069 +// .next_trigger_dmode (mcontrol4_dmode), @1070 +// .tdata1_chain (mcontrol3_chain), @1071 +// .tdata1_dmode (mcontrol3_dmode), @1072 +// .tdata1_action0 (mcontrol3_action0), @1073 +// .tdata1_action1 (mcontrol3_action1), @1074 +// .tdata1_timing (mcontrol3_timing), @1075 +// .exe_mcontrol (mcontrol3_is_exe), @1076 +// .ldst_mcontrol (mcontrol3_is_ldst), @1077 +// .ldst_addr_mcontrol (mcontrol3_is_ldst_addr), @1078 +// .ldst_data_mcontrol (mcontrol3_is_ldst_data), @1079 +// .mpriority (mcontrol3_priority), @1080 +// .mpriority_mask (mcontrol3_priority_mask), @1081 +// .mtiming (mcontrol3_mtiming), @1082 +// .mtiming_mask (mcontrol3_mtiming_mask), @1083 +// .next_mpriority (mcontrol4_priority), @1084 +// .next_mpriority_mask (mcontrol4_priority_mask), @1085 +// .next_mtiming (mcontrol4_mtiming), @1086 +// .next_mtiming_mask (mcontrol4_mtiming_mask), @1087 +// .previous_mpriority (mcontrol2_priority), @1088 +// .previous_mpriority_mask (mcontrol2_priority_mask), @1089 +// .previous_mtiming (mcontrol2_mtiming), @1090 +// .previous_mtiming_mask (mcontrol2_mtiming_mask), @1091 +// .mpriority_after_chain (m3_priority), @1092 +// .mpriority_mask_after_chain (m3_priority_mask), @1093 +// .mtiming_after_chain (m3_mtiming), @1094 +// .mtiming_mask_after_chain (m3_mtiming_mask), @1095 +// .exe0_match (mcontrol3_exe0_match), @1096 +// .exe1_match (mcontrol3_exe1_match), @1097 +// .ldst_match (mcontrol3_ldst_match), @1098 +// .tdata1 (m3_tdata1), @1099 +// .tdata2 (m3_tdata2), @1100 +// .tdata3 (m3_tdata3), @1101 +// .tinfo (m3_tinfo), @1102 +// .ldst_may_hit (mcontrol3_ldst_may_hit), @1103 +// .exe0_may_hit (mcontrol3_exe0_may_hit), @1104 +// .exe1_may_hit (mcontrol3_exe1_may_hit)); @1105 +// &Instance("pa_dtu_mcontrol_4","x_pa_dtu_mcontrol_4"); @1107 +// &Connect( @1108 +// .trigger_selected (tselect_wr_en[4]), @1109 +// .set_trigger_hit (mcontrol_hit[4]), @1110 +// .already_match (already_match[4]), @1111 +// .previous_trigger_chian (mcontrol3_chain), @1112 +// .previous_trigger_dmode (mcontrol3_dmode), @1113 +// .next_trigger_chain (mcontrol5_chain), @1114 +// .next_trigger_dmode (mcontrol5_dmode), @1115 +// .tdata1_chain (mcontrol4_chain), @1116 +// .tdata1_dmode (mcontrol4_dmode), @1117 +// .tdata1_action0 (mcontrol4_action0), @1118 +// .tdata1_action1 (mcontrol4_action1), @1119 +// .tdata1_timing (mcontrol4_timing), @1120 +// .exe_mcontrol (mcontrol4_is_exe), @1121 +// .ldst_mcontrol (mcontrol4_is_ldst), @1122 +// .ldst_addr_mcontrol (mcontrol4_is_ldst_addr), @1123 +// .ldst_data_mcontrol (mcontrol4_is_ldst_data), @1124 +// .mpriority (mcontrol4_priority), @1125 +// .mpriority_mask (mcontrol4_priority_mask), @1126 +// .mtiming (mcontrol4_mtiming), @1127 +// .mtiming_mask (mcontrol4_mtiming_mask), @1128 +// .next_mpriority (mcontrol5_priority), @1129 +// .next_mpriority_mask (mcontrol5_priority_mask), @1130 +// .next_mtiming (mcontrol5_mtiming), @1131 +// .next_mtiming_mask (mcontrol5_mtiming_mask), @1132 +// .previous_mpriority (mcontrol3_priority), @1133 +// .previous_mpriority_mask (mcontrol3_priority_mask), @1134 +// .previous_mtiming (mcontrol3_mtiming), @1135 +// .previous_mtiming_mask (mcontrol3_mtiming_mask), @1136 +// .mpriority_after_chain (m4_priority), @1137 +// .mpriority_mask_after_chain (m4_priority_mask), @1138 +// .mtiming_after_chain (m4_mtiming), @1139 +// .mtiming_mask_after_chain (m4_mtiming_mask), @1140 +// .exe0_match (mcontrol4_exe0_match), @1141 +// .exe1_match (mcontrol4_exe1_match), @1142 +// .ldst_match (mcontrol4_ldst_match), @1143 +// .tdata1 (m4_tdata1), @1144 +// .tdata2 (m4_tdata2), @1145 +// .tdata3 (m4_tdata3), @1146 +// .tinfo (m4_tinfo), @1147 +// .ldst_may_hit (mcontrol4_ldst_may_hit), @1148 +// .exe0_may_hit (mcontrol4_exe0_may_hit), @1149 +// .exe1_may_hit (mcontrol4_exe1_may_hit)); @1150 +// &Instance("pa_dtu_mcontrol_5","x_pa_dtu_mcontrol_5"); @1152 +// &Connect( @1153 +// .trigger_selected (tselect_wr_en[5]), @1154 +// .set_trigger_hit (mcontrol_hit[5]), @1155 +// .already_match (already_match[5]), @1156 +// .previous_trigger_chian (mcontrol4_chain), @1157 +// .previous_trigger_dmode (mcontrol4_dmode), @1158 +// .next_trigger_chain (1'b0), @1159 +// .next_trigger_dmode (1'b0), @1160 +// .tdata1_chain (mcontrol5_chain), @1161 +// .tdata1_dmode (mcontrol5_dmode), @1162 +// .tdata1_action0 (mcontrol5_action0), @1163 +// .tdata1_action1 (mcontrol5_action1), @1164 +// .tdata1_timing (mcontrol5_timing), @1165 +// .exe_mcontrol (mcontrol5_is_exe), @1166 +// .ldst_mcontrol (mcontrol5_is_ldst), @1167 +// .ldst_addr_mcontrol (mcontrol5_is_ldst_addr), @1168 +// .ldst_data_mcontrol (mcontrol5_is_ldst_data), @1169 +// .mpriority (mcontrol5_priority), @1170 +// .mpriority_mask (mcontrol5_priority_mask), @1171 +// .mtiming (mcontrol5_mtiming), @1172 +// .mtiming_mask (mcontrol5_mtiming_mask), @1173 +// .next_mpriority (2'b10), @1174 +// .next_mpriority_mask (2'b00), @1175 +// .next_mtiming (1'b1), @1176 +// .next_mtiming_mask (1'b0), @1177 +// .previous_mpriority (mcontrol4_priority), @1178 +// .previous_mpriority_mask (mcontrol4_priority_mask), @1179 +// .previous_mtiming (mcontrol4_mtiming), @1180 +// .previous_mtiming_mask (mcontrol4_mtiming_mask), @1181 +// .mpriority_after_chain (m5_priority), @1182 +// .mpriority_mask_after_chain (m5_priority_mask), @1183 +// .mtiming_after_chain (m5_mtiming), @1184 +// .mtiming_mask_after_chain (m5_mtiming_mask), @1185 +// .exe0_match (mcontrol5_exe0_match), @1186 +// .exe1_match (mcontrol5_exe1_match), @1187 +// .ldst_match (mcontrol5_ldst_match), @1188 +// .tdata1 (m5_tdata1), @1189 +// .tdata2 (m5_tdata2), @1190 +// .tdata3 (m5_tdata3), @1191 +// .tinfo (m5_tinfo), @1192 +// .ldst_may_hit (mcontrol5_ldst_may_hit), @1193 +// .exe0_may_hit (mcontrol5_exe0_may_hit), @1194 +// .exe1_may_hit (mcontrol5_exe1_may_hit)); @1195 +// &Force("bus","tselect_wr_en",9,0); @1206 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @1210 +// &Connect( @1211 +// .trigger_selected (tselect_wr_en[0]), @1212 +// .set_trigger_hit (mcontrol_hit[0]), @1213 +// .already_match (already_match[0]), @1214 +// .previous_trigger_chian (1'b0), @1215 +// .previous_trigger_dmode (1'b0), @1216 +// .next_trigger_chain (mcontrol1_chain), @1217 +// .next_trigger_dmode (mcontrol1_dmode), @1218 +// .tdata1_chain (mcontrol0_chain), @1219 +// .tdata1_dmode (mcontrol0_dmode), @1220 +// .tdata1_action0 (mcontrol0_action0), @1221 +// .tdata1_action1 (mcontrol0_action1), @1222 +// .tdata1_timing (mcontrol0_timing), @1223 +// .exe_mcontrol (mcontrol0_is_exe), @1224 +// .ldst_mcontrol (mcontrol0_is_ldst), @1225 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @1226 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @1227 +// .mpriority (mcontrol0_priority), @1228 +// .mpriority_mask (mcontrol0_priority_mask), @1229 +// .mtiming (mcontrol0_mtiming), @1230 +// .mtiming_mask (mcontrol0_mtiming_mask), @1231 +// .next_mpriority (mcontrol1_priority), @1232 +// .next_mpriority_mask (mcontrol1_priority_mask), @1233 +// .next_mtiming (mcontrol1_mtiming), @1234 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @1235 +// .previous_mpriority (2'b10), @1236 +// .previous_mpriority_mask (2'b00), @1237 +// .previous_mtiming (1'b1), @1238 +// .previous_mtiming_mask (1'b0), @1239 +// .mpriority_after_chain (m0_priority), @1240 +// .mpriority_mask_after_chain (m0_priority_mask), @1241 +// .mtiming_after_chain (m0_mtiming), @1242 +// .mtiming_mask_after_chain (m0_mtiming_mask), @1243 +// .exe0_match (mcontrol0_exe0_match), @1244 +// .exe1_match (mcontrol0_exe1_match), @1245 +// .ldst_match (mcontrol0_ldst_match), @1246 +// .tdata1 (m0_tdata1), @1247 +// .tdata2 (m0_tdata2), @1248 +// .tdata3 (m0_tdata3), @1249 +// .tinfo (m0_tinfo), @1250 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @1251 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @1252 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @1253 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @1255 +// &Connect( @1256 +// .trigger_selected (tselect_wr_en[1]), @1257 +// .set_trigger_hit (mcontrol_hit[1]), @1258 +// .already_match (already_match[1]), @1259 +// .previous_trigger_chian (mcontrol0_chain), @1260 +// .previous_trigger_dmode (mcontrol0_dmode), @1261 +// .next_trigger_chain (mcontrol2_chain), @1262 +// .next_trigger_dmode (mcontrol2_dmode), @1263 +// .tdata1_chain (mcontrol1_chain), @1264 +// .tdata1_dmode (mcontrol1_dmode), @1265 +// .tdata1_action0 (mcontrol1_action0), @1266 +// .tdata1_action1 (mcontrol1_action1), @1267 +// .tdata1_timing (mcontrol1_timing), @1268 +// .exe_mcontrol (mcontrol1_is_exe), @1269 +// .ldst_mcontrol (mcontrol1_is_ldst), @1270 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @1271 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @1272 +// .mpriority (mcontrol1_priority), @1273 +// .mpriority_mask (mcontrol1_priority_mask), @1274 +// .mtiming (mcontrol1_mtiming), @1275 +// .mtiming_mask (mcontrol1_mtiming_mask), @1276 +// .next_mpriority (mcontrol2_priority), @1277 +// .next_mpriority_mask (mcontrol2_priority_mask), @1278 +// .next_mtiming (mcontrol2_mtiming), @1279 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @1280 +// .previous_mpriority (mcontrol0_priority), @1281 +// .previous_mpriority_mask (mcontrol0_priority_mask), @1282 +// .previous_mtiming (mcontrol0_mtiming), @1283 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @1284 +// .mpriority_after_chain (m1_priority), @1285 +// .mpriority_mask_after_chain (m1_priority_mask), @1286 +// .mtiming_after_chain (m1_mtiming), @1287 +// .mtiming_mask_after_chain (m1_mtiming_mask), @1288 +// .exe0_match (mcontrol1_exe0_match), @1289 +// .exe1_match (mcontrol1_exe1_match), @1290 +// .ldst_match (mcontrol1_ldst_match), @1291 +// .tdata1 (m1_tdata1), @1292 +// .tdata2 (m1_tdata2), @1293 +// .tdata3 (m1_tdata3), @1294 +// .tinfo (m1_tinfo), @1295 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @1296 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @1297 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @1298 +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @1300 +// &Connect( @1301 +// .trigger_selected (tselect_wr_en[2]), @1302 +// .set_trigger_hit (mcontrol_hit[2]), @1303 +// .already_match (already_match[2]), @1304 +// .previous_trigger_chian (mcontrol1_chain), @1305 +// .previous_trigger_dmode (mcontrol1_dmode), @1306 +// .next_trigger_chain (mcontrol3_chain), @1307 +// .next_trigger_dmode (mcontrol3_dmode), @1308 +// .tdata1_chain (mcontrol2_chain), @1309 +// .tdata1_dmode (mcontrol2_dmode), @1310 +// .tdata1_action0 (mcontrol2_action0), @1311 +// .tdata1_action1 (mcontrol2_action1), @1312 +// .tdata1_timing (mcontrol2_timing), @1313 +// .exe_mcontrol (mcontrol2_is_exe), @1314 +// .ldst_mcontrol (mcontrol2_is_ldst), @1315 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @1316 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @1317 +// .mpriority (mcontrol2_priority), @1318 +// .mpriority_mask (mcontrol2_priority_mask), @1319 +// .mtiming (mcontrol2_mtiming), @1320 +// .mtiming_mask (mcontrol2_mtiming_mask), @1321 +// .next_mpriority (mcontrol3_priority), @1322 +// .next_mpriority_mask (mcontrol3_priority_mask), @1323 +// .next_mtiming (mcontrol3_mtiming), @1324 +// .next_mtiming_mask (mcontrol3_mtiming_mask), @1325 +// .previous_mpriority (mcontrol1_priority), @1326 +// .previous_mpriority_mask (mcontrol1_priority_mask), @1327 +// .previous_mtiming (mcontrol1_mtiming), @1328 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @1329 +// .mpriority_after_chain (m2_priority), @1330 +// .mpriority_mask_after_chain (m2_priority_mask), @1331 +// .mtiming_after_chain (m2_mtiming), @1332 +// .mtiming_mask_after_chain (m2_mtiming_mask), @1333 +// .exe0_match (mcontrol2_exe0_match), @1334 +// .exe1_match (mcontrol2_exe1_match), @1335 +// .ldst_match (mcontrol2_ldst_match), @1336 +// .tdata1 (m2_tdata1), @1337 +// .tdata2 (m2_tdata2), @1338 +// .tdata3 (m2_tdata3), @1339 +// .tinfo (m2_tinfo), @1340 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @1341 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @1342 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @1343 +// &Instance("pa_dtu_mcontrol_3","x_pa_dtu_mcontrol_3"); @1345 +// &Connect( @1346 +// .trigger_selected (tselect_wr_en[3]), @1347 +// .set_trigger_hit (mcontrol_hit[3]), @1348 +// .already_match (already_match[3]), @1349 +// .previous_trigger_chian (mcontrol2_chain), @1350 +// .previous_trigger_dmode (mcontrol2_dmode), @1351 +// .next_trigger_chain (mcontrol4_chain), @1352 +// .next_trigger_dmode (mcontrol4_dmode), @1353 +// .tdata1_chain (mcontrol3_chain), @1354 +// .tdata1_dmode (mcontrol3_dmode), @1355 +// .tdata1_action0 (mcontrol3_action0), @1356 +// .tdata1_action1 (mcontrol3_action1), @1357 +// .tdata1_timing (mcontrol3_timing), @1358 +// .exe_mcontrol (mcontrol3_is_exe), @1359 +// .ldst_mcontrol (mcontrol3_is_ldst), @1360 +// .ldst_addr_mcontrol (mcontrol3_is_ldst_addr), @1361 +// .ldst_data_mcontrol (mcontrol3_is_ldst_data), @1362 +// .mpriority (mcontrol3_priority), @1363 +// .mpriority_mask (mcontrol3_priority_mask), @1364 +// .mtiming (mcontrol3_mtiming), @1365 +// .mtiming_mask (mcontrol3_mtiming_mask), @1366 +// .next_mpriority (mcontrol4_priority), @1367 +// .next_mpriority_mask (mcontrol4_priority_mask), @1368 +// .next_mtiming (mcontrol4_mtiming), @1369 +// .next_mtiming_mask (mcontrol4_mtiming_mask), @1370 +// .previous_mpriority (mcontrol2_priority), @1371 +// .previous_mpriority_mask (mcontrol2_priority_mask), @1372 +// .previous_mtiming (mcontrol2_mtiming), @1373 +// .previous_mtiming_mask (mcontrol2_mtiming_mask), @1374 +// .mpriority_after_chain (m3_priority), @1375 +// .mpriority_mask_after_chain (m3_priority_mask), @1376 +// .mtiming_after_chain (m3_mtiming), @1377 +// .mtiming_mask_after_chain (m3_mtiming_mask), @1378 +// .exe0_match (mcontrol3_exe0_match), @1379 +// .exe1_match (mcontrol3_exe1_match), @1380 +// .ldst_match (mcontrol3_ldst_match), @1381 +// .tdata1 (m3_tdata1), @1382 +// .tdata2 (m3_tdata2), @1383 +// .tdata3 (m3_tdata3), @1384 +// .tinfo (m3_tinfo), @1385 +// .ldst_may_hit (mcontrol3_ldst_may_hit), @1386 +// .exe0_may_hit (mcontrol3_exe0_may_hit), @1387 +// .exe1_may_hit (mcontrol3_exe1_may_hit)); @1388 +// &Instance("pa_dtu_mcontrol_4","x_pa_dtu_mcontrol_4"); @1390 +// &Connect( @1391 +// .trigger_selected (tselect_wr_en[4]), @1392 +// .set_trigger_hit (mcontrol_hit[4]), @1393 +// .already_match (already_match[4]), @1394 +// .previous_trigger_chian (mcontrol3_chain), @1395 +// .previous_trigger_dmode (mcontrol3_dmode), @1396 +// .next_trigger_chain (mcontrol5_chain), @1397 +// .next_trigger_dmode (mcontrol5_dmode), @1398 +// .tdata1_chain (mcontrol4_chain), @1399 +// .tdata1_dmode (mcontrol4_dmode), @1400 +// .tdata1_action0 (mcontrol4_action0), @1401 +// .tdata1_action1 (mcontrol4_action1), @1402 +// .tdata1_timing (mcontrol4_timing), @1403 +// .exe_mcontrol (mcontrol4_is_exe), @1404 +// .ldst_mcontrol (mcontrol4_is_ldst), @1405 +// .ldst_addr_mcontrol (mcontrol4_is_ldst_addr), @1406 +// .ldst_data_mcontrol (mcontrol4_is_ldst_data), @1407 +// .mpriority (mcontrol4_priority), @1408 +// .mpriority_mask (mcontrol4_priority_mask), @1409 +// .mtiming (mcontrol4_mtiming), @1410 +// .mtiming_mask (mcontrol4_mtiming_mask), @1411 +// .next_mpriority (mcontrol5_priority), @1412 +// .next_mpriority_mask (mcontrol5_priority_mask), @1413 +// .next_mtiming (mcontrol5_mtiming), @1414 +// .next_mtiming_mask (mcontrol5_mtiming_mask), @1415 +// .previous_mpriority (mcontrol3_priority), @1416 +// .previous_mpriority_mask (mcontrol3_priority_mask), @1417 +// .previous_mtiming (mcontrol3_mtiming), @1418 +// .previous_mtiming_mask (mcontrol3_mtiming_mask), @1419 +// .mpriority_after_chain (m4_priority), @1420 +// .mpriority_mask_after_chain (m4_priority_mask), @1421 +// .mtiming_after_chain (m4_mtiming), @1422 +// .mtiming_mask_after_chain (m4_mtiming_mask), @1423 +// .exe0_match (mcontrol4_exe0_match), @1424 +// .exe1_match (mcontrol4_exe1_match), @1425 +// .ldst_match (mcontrol4_ldst_match), @1426 +// .tdata1 (m4_tdata1), @1427 +// .tdata2 (m4_tdata2), @1428 +// .tdata3 (m4_tdata3), @1429 +// .tinfo (m4_tinfo), @1430 +// .ldst_may_hit (mcontrol4_ldst_may_hit), @1431 +// .exe0_may_hit (mcontrol4_exe0_may_hit), @1432 +// .exe1_may_hit (mcontrol4_exe1_may_hit)); @1433 +// &Instance("pa_dtu_mcontrol_5","x_pa_dtu_mcontrol_5"); @1435 +// &Connect( @1436 +// .trigger_selected (tselect_wr_en[5]), @1437 +// .set_trigger_hit (mcontrol_hit[5]), @1438 +// .already_match (already_match[5]), @1439 +// .previous_trigger_chian (mcontrol4_chain), @1440 +// .previous_trigger_dmode (mcontrol4_dmode), @1441 +// .next_trigger_chain (mcontrol6_chain), @1442 +// .next_trigger_dmode (mcontrol6_dmode), @1443 +// .tdata1_chain (mcontrol5_chain), @1444 +// .tdata1_dmode (mcontrol5_dmode), @1445 +// .tdata1_action0 (mcontrol5_action0), @1446 +// .tdata1_action1 (mcontrol5_action1), @1447 +// .tdata1_timing (mcontrol5_timing), @1448 +// .exe_mcontrol (mcontrol5_is_exe), @1449 +// .ldst_mcontrol (mcontrol5_is_ldst), @1450 +// .ldst_addr_mcontrol (mcontrol5_is_ldst_addr), @1451 +// .ldst_data_mcontrol (mcontrol5_is_ldst_data), @1452 +// .mpriority (mcontrol5_priority), @1453 +// .mpriority_mask (mcontrol5_priority_mask), @1454 +// .mtiming (mcontrol5_mtiming), @1455 +// .mtiming_mask (mcontrol5_mtiming_mask), @1456 +// .next_mpriority (mcontrol6_priority), @1457 +// .next_mpriority_mask (mcontrol6_priority_mask), @1458 +// .next_mtiming (mcontrol6_mtiming), @1459 +// .next_mtiming_mask (mcontrol6_mtiming_mask), @1460 +// .previous_mpriority (mcontrol4_priority), @1461 +// .previous_mpriority_mask (mcontrol4_priority_mask), @1462 +// .previous_mtiming (mcontrol4_mtiming), @1463 +// .previous_mtiming_mask (mcontrol4_mtiming_mask), @1464 +// .mpriority_after_chain (m5_priority), @1465 +// .mpriority_mask_after_chain (m5_priority_mask), @1466 +// .mtiming_after_chain (m5_mtiming), @1467 +// .mtiming_mask_after_chain (m5_mtiming_mask), @1468 +// .exe0_match (mcontrol5_exe0_match), @1469 +// .exe1_match (mcontrol5_exe1_match), @1470 +// .ldst_match (mcontrol5_ldst_match), @1471 +// .tdata1 (m5_tdata1), @1472 +// .tdata2 (m5_tdata2), @1473 +// .tdata3 (m5_tdata3), @1474 +// .tinfo (m5_tinfo), @1475 +// .ldst_may_hit (mcontrol5_ldst_may_hit), @1476 +// .exe0_may_hit (mcontrol5_exe0_may_hit), @1477 +// .exe1_may_hit (mcontrol5_exe1_may_hit)); @1478 +// &Instance("pa_dtu_mcontrol_6","x_pa_dtu_mcontrol_6"); @1480 +// &Connect( @1481 +// .trigger_selected (tselect_wr_en[6]), @1482 +// .set_trigger_hit (mcontrol_hit[6]), @1483 +// .already_match (already_match[6]), @1484 +// .previous_trigger_chian (mcontrol5_chain), @1485 +// .previous_trigger_dmode (mcontrol5_dmode), @1486 +// .next_trigger_chain (1'b0), @1487 +// .next_trigger_dmode (1'b0), @1488 +// .tdata1_chain (mcontrol6_chain), @1489 +// .tdata1_dmode (mcontrol6_dmode), @1490 +// .tdata1_action0 (mcontrol6_action0), @1491 +// .tdata1_action1 (mcontrol6_action1), @1492 +// .tdata1_timing (mcontrol6_timing), @1493 +// .exe_mcontrol (mcontrol6_is_exe), @1494 +// .ldst_mcontrol (mcontrol6_is_ldst), @1495 +// .ldst_addr_mcontrol (mcontrol6_is_ldst_addr), @1496 +// .ldst_data_mcontrol (mcontrol6_is_ldst_data), @1497 +// .mpriority (mcontrol6_priority), @1498 +// .mpriority_mask (mcontrol6_priority_mask), @1499 +// .mtiming (mcontrol6_mtiming), @1500 +// .mtiming_mask (mcontrol6_mtiming_mask), @1501 +// .next_mpriority (2'b10), @1502 +// .next_mpriority_mask (2'b00), @1503 +// .next_mtiming (1'b1), @1504 +// .next_mtiming_mask (1'b0), @1505 +// .previous_mpriority (mcontrol5_priority), @1506 +// .previous_mpriority_mask (mcontrol5_priority_mask), @1507 +// .previous_mtiming (mcontrol5_mtiming), @1508 +// .previous_mtiming_mask (mcontrol5_mtiming_mask), @1509 +// .mpriority_after_chain (m6_priority), @1510 +// .mpriority_mask_after_chain (m6_priority_mask), @1511 +// .mtiming_after_chain (m6_mtiming), @1512 +// .mtiming_mask_after_chain (m6_mtiming_mask), @1513 +// .exe0_match (mcontrol6_exe0_match), @1514 +// .exe1_match (mcontrol6_exe1_match), @1515 +// .ldst_match (mcontrol6_ldst_match), @1516 +// .tdata1 (m6_tdata1), @1517 +// .tdata2 (m6_tdata2), @1518 +// .tdata3 (m6_tdata3), @1519 +// .tinfo (m6_tinfo), @1520 +// .ldst_may_hit (mcontrol6_ldst_may_hit), @1521 +// .exe0_may_hit (mcontrol6_exe0_may_hit), @1522 +// .exe1_may_hit (mcontrol6_exe1_may_hit)); @1523 +// &Force("bus","tselect_wr_en",9,0); @1529 + +// &Instance("pa_dtu_mcontrol_0","x_pa_dtu_mcontrol_0"); @1533 +// &Connect( @1534 +// .trigger_selected (tselect_wr_en[0]), @1535 +// .set_trigger_hit (mcontrol_hit[0]), @1536 +// .already_match (already_match[0]), @1537 +// .previous_trigger_chian (1'b0), @1538 +// .previous_trigger_dmode (1'b0), @1539 +// .next_trigger_chain (mcontrol1_chain), @1540 +// .next_trigger_dmode (mcontrol1_dmode), @1541 +// .tdata1_chain (mcontrol0_chain), @1542 +// .tdata1_dmode (mcontrol0_dmode), @1543 +// .tdata1_action0 (mcontrol0_action0), @1544 +// .tdata1_action1 (mcontrol0_action1), @1545 +// .tdata1_timing (mcontrol0_timing), @1546 +// .exe_mcontrol (mcontrol0_is_exe), @1547 +// .ldst_mcontrol (mcontrol0_is_ldst), @1548 +// .ldst_addr_mcontrol (mcontrol0_is_ldst_addr), @1549 +// .ldst_data_mcontrol (mcontrol0_is_ldst_data), @1550 +// .mpriority (mcontrol0_priority), @1551 +// .mpriority_mask (mcontrol0_priority_mask), @1552 +// .mtiming (mcontrol0_mtiming), @1553 +// .mtiming_mask (mcontrol0_mtiming_mask), @1554 +// .next_mpriority (mcontrol1_priority), @1555 +// .next_mpriority_mask (mcontrol1_priority_mask), @1556 +// .next_mtiming (mcontrol1_mtiming), @1557 +// .next_mtiming_mask (mcontrol1_mtiming_mask), @1558 +// .previous_mpriority (2'b10), @1559 +// .previous_mpriority_mask (2'b00), @1560 +// .previous_mtiming (1'b1), @1561 +// .previous_mtiming_mask (1'b0), @1562 +// .mpriority_after_chain (m0_priority), @1563 +// .mpriority_mask_after_chain (m0_priority_mask), @1564 +// .mtiming_after_chain (m0_mtiming), @1565 +// .mtiming_mask_after_chain (m0_mtiming_mask), @1566 +// .exe0_match (mcontrol0_exe0_match), @1567 +// .exe1_match (mcontrol0_exe1_match), @1568 +// .ldst_match (mcontrol0_ldst_match), @1569 +// .tdata1 (m0_tdata1), @1570 +// .tdata2 (m0_tdata2), @1571 +// .tdata3 (m0_tdata3), @1572 +// .tinfo (m0_tinfo), @1573 +// .ldst_may_hit (mcontrol0_ldst_may_hit), @1574 +// .exe0_may_hit (mcontrol0_exe0_may_hit), @1575 +// .exe1_may_hit (mcontrol0_exe1_may_hit)); @1576 +// &Instance("pa_dtu_mcontrol_1","x_pa_dtu_mcontrol_1"); @1578 +// &Connect( @1579 +// .trigger_selected (tselect_wr_en[1]), @1580 +// .set_trigger_hit (mcontrol_hit[1]), @1581 +// .already_match (already_match[1]), @1582 +// .previous_trigger_chian (mcontrol0_chain), @1583 +// .previous_trigger_dmode (mcontrol0_dmode), @1584 +// .next_trigger_chain (mcontrol2_chain), @1585 +// .next_trigger_dmode (mcontrol2_dmode), @1586 +// .tdata1_chain (mcontrol1_chain), @1587 +// .tdata1_dmode (mcontrol1_dmode), @1588 +// .tdata1_action0 (mcontrol1_action0), @1589 +// .tdata1_action1 (mcontrol1_action1), @1590 +// .tdata1_timing (mcontrol1_timing), @1591 +// .exe_mcontrol (mcontrol1_is_exe), @1592 +// .ldst_mcontrol (mcontrol1_is_ldst), @1593 +// .ldst_addr_mcontrol (mcontrol1_is_ldst_addr), @1594 +// .ldst_data_mcontrol (mcontrol1_is_ldst_data), @1595 +// .mpriority (mcontrol1_priority), @1596 +// .mpriority_mask (mcontrol1_priority_mask), @1597 +// .mtiming (mcontrol1_mtiming), @1598 +// .mtiming_mask (mcontrol1_mtiming_mask), @1599 +// .next_mpriority (mcontrol2_priority), @1600 +// .next_mpriority_mask (mcontrol2_priority_mask), @1601 +// .next_mtiming (mcontrol2_mtiming), @1602 +// .next_mtiming_mask (mcontrol2_mtiming_mask), @1603 +// .previous_mpriority (mcontrol0_priority), @1604 +// .previous_mpriority_mask (mcontrol0_priority_mask), @1605 +// .previous_mtiming (mcontrol0_mtiming), @1606 +// .previous_mtiming_mask (mcontrol0_mtiming_mask), @1607 +// .mpriority_after_chain (m1_priority), @1608 +// .mpriority_mask_after_chain (m1_priority_mask), @1609 +// .mtiming_after_chain (m1_mtiming), @1610 +// .mtiming_mask_after_chain (m1_mtiming_mask), @1611 +// .exe0_match (mcontrol1_exe0_match), @1612 +// .exe1_match (mcontrol1_exe1_match), @1613 +// .ldst_match (mcontrol1_ldst_match), @1614 +// .tdata1 (m1_tdata1), @1615 +// .tdata2 (m1_tdata2), @1616 +// .tdata3 (m1_tdata3), @1617 +// .tinfo (m1_tinfo), @1618 +// .ldst_may_hit (mcontrol1_ldst_may_hit), @1619 +// .exe0_may_hit (mcontrol1_exe0_may_hit), @1620 +// .exe1_may_hit (mcontrol1_exe1_may_hit)); @1621 +// &Instance("pa_dtu_mcontrol_2","x_pa_dtu_mcontrol_2"); @1623 +// &Connect( @1624 +// .trigger_selected (tselect_wr_en[2]), @1625 +// .set_trigger_hit (mcontrol_hit[2]), @1626 +// .already_match (already_match[2]), @1627 +// .previous_trigger_chian (mcontrol1_chain), @1628 +// .previous_trigger_dmode (mcontrol1_dmode), @1629 +// .next_trigger_chain (mcontrol3_chain), @1630 +// .next_trigger_dmode (mcontrol3_dmode), @1631 +// .tdata1_chain (mcontrol2_chain), @1632 +// .tdata1_dmode (mcontrol2_dmode), @1633 +// .tdata1_action0 (mcontrol2_action0), @1634 +// .tdata1_action1 (mcontrol2_action1), @1635 +// .tdata1_timing (mcontrol2_timing), @1636 +// .exe_mcontrol (mcontrol2_is_exe), @1637 +// .ldst_mcontrol (mcontrol2_is_ldst), @1638 +// .ldst_addr_mcontrol (mcontrol2_is_ldst_addr), @1639 +// .ldst_data_mcontrol (mcontrol2_is_ldst_data), @1640 +// .mpriority (mcontrol2_priority), @1641 +// .mpriority_mask (mcontrol2_priority_mask), @1642 +// .mtiming (mcontrol2_mtiming), @1643 +// .mtiming_mask (mcontrol2_mtiming_mask), @1644 +// .next_mpriority (mcontrol3_priority), @1645 +// .next_mpriority_mask (mcontrol3_priority_mask), @1646 +// .next_mtiming (mcontrol3_mtiming), @1647 +// .next_mtiming_mask (mcontrol3_mtiming_mask), @1648 +// .previous_mpriority (mcontrol1_priority), @1649 +// .previous_mpriority_mask (mcontrol1_priority_mask), @1650 +// .previous_mtiming (mcontrol1_mtiming), @1651 +// .previous_mtiming_mask (mcontrol1_mtiming_mask), @1652 +// .mpriority_after_chain (m2_priority), @1653 +// .mpriority_mask_after_chain (m2_priority_mask), @1654 +// .mtiming_after_chain (m2_mtiming), @1655 +// .mtiming_mask_after_chain (m2_mtiming_mask), @1656 +// .exe0_match (mcontrol2_exe0_match), @1657 +// .exe1_match (mcontrol2_exe1_match), @1658 +// .ldst_match (mcontrol2_ldst_match), @1659 +// .tdata1 (m2_tdata1), @1660 +// .tdata2 (m2_tdata2), @1661 +// .tdata3 (m2_tdata3), @1662 +// .tinfo (m2_tinfo), @1663 +// .ldst_may_hit (mcontrol2_ldst_may_hit), @1664 +// .exe0_may_hit (mcontrol2_exe0_may_hit), @1665 +// .exe1_may_hit (mcontrol2_exe1_may_hit)); @1666 +// &Instance("pa_dtu_mcontrol_3","x_pa_dtu_mcontrol_3"); @1668 +// &Connect( @1669 +// .trigger_selected (tselect_wr_en[3]), @1670 +// .set_trigger_hit (mcontrol_hit[3]), @1671 +// .already_match (already_match[3]), @1672 +// .previous_trigger_chian (mcontrol2_chain), @1673 +// .previous_trigger_dmode (mcontrol2_dmode), @1674 +// .next_trigger_chain (mcontrol4_chain), @1675 +// .next_trigger_dmode (mcontrol4_dmode), @1676 +// .tdata1_chain (mcontrol3_chain), @1677 +// .tdata1_dmode (mcontrol3_dmode), @1678 +// .tdata1_action0 (mcontrol3_action0), @1679 +// .tdata1_action1 (mcontrol3_action1), @1680 +// .tdata1_timing (mcontrol3_timing), @1681 +// .exe_mcontrol (mcontrol3_is_exe), @1682 +// .ldst_mcontrol (mcontrol3_is_ldst), @1683 +// .ldst_addr_mcontrol (mcontrol3_is_ldst_addr), @1684 +// .ldst_data_mcontrol (mcontrol3_is_ldst_data), @1685 +// .mpriority (mcontrol3_priority), @1686 +// .mpriority_mask (mcontrol3_priority_mask), @1687 +// .mtiming (mcontrol3_mtiming), @1688 +// .mtiming_mask (mcontrol3_mtiming_mask), @1689 +// .next_mpriority (mcontrol4_priority), @1690 +// .next_mpriority_mask (mcontrol4_priority_mask), @1691 +// .next_mtiming (mcontrol4_mtiming), @1692 +// .next_mtiming_mask (mcontrol4_mtiming_mask), @1693 +// .previous_mpriority (mcontrol2_priority), @1694 +// .previous_mpriority_mask (mcontrol2_priority_mask), @1695 +// .previous_mtiming (mcontrol2_mtiming), @1696 +// .previous_mtiming_mask (mcontrol2_mtiming_mask), @1697 +// .mpriority_after_chain (m3_priority), @1698 +// .mpriority_mask_after_chain (m3_priority_mask), @1699 +// .mtiming_after_chain (m3_mtiming), @1700 +// .mtiming_mask_after_chain (m3_mtiming_mask), @1701 +// .exe0_match (mcontrol3_exe0_match), @1702 +// .exe1_match (mcontrol3_exe1_match), @1703 +// .ldst_match (mcontrol3_ldst_match), @1704 +// .tdata1 (m3_tdata1), @1705 +// .tdata2 (m3_tdata2), @1706 +// .tdata3 (m3_tdata3), @1707 +// .tinfo (m3_tinfo), @1708 +// .ldst_may_hit (mcontrol3_ldst_may_hit), @1709 +// .exe0_may_hit (mcontrol3_exe0_may_hit), @1710 +// .exe1_may_hit (mcontrol3_exe1_may_hit)); @1711 +// &Instance("pa_dtu_mcontrol_4","x_pa_dtu_mcontrol_4"); @1713 +// &Connect( @1714 +// .trigger_selected (tselect_wr_en[4]), @1715 +// .set_trigger_hit (mcontrol_hit[4]), @1716 +// .already_match (already_match[4]), @1717 +// .previous_trigger_chian (mcontrol3_chain), @1718 +// .previous_trigger_dmode (mcontrol3_dmode), @1719 +// .next_trigger_chain (mcontrol5_chain), @1720 +// .next_trigger_dmode (mcontrol5_dmode), @1721 +// .tdata1_chain (mcontrol4_chain), @1722 +// .tdata1_dmode (mcontrol4_dmode), @1723 +// .tdata1_action0 (mcontrol4_action0), @1724 +// .tdata1_action1 (mcontrol4_action1), @1725 +// .tdata1_timing (mcontrol4_timing), @1726 +// .exe_mcontrol (mcontrol4_is_exe), @1727 +// .ldst_mcontrol (mcontrol4_is_ldst), @1728 +// .ldst_addr_mcontrol (mcontrol4_is_ldst_addr), @1729 +// .ldst_data_mcontrol (mcontrol4_is_ldst_data), @1730 +// .mpriority (mcontrol4_priority), @1731 +// .mpriority_mask (mcontrol4_priority_mask), @1732 +// .mtiming (mcontrol4_mtiming), @1733 +// .mtiming_mask (mcontrol4_mtiming_mask), @1734 +// .next_mpriority (mcontrol5_priority), @1735 +// .next_mpriority_mask (mcontrol5_priority_mask), @1736 +// .next_mtiming (mcontrol5_mtiming), @1737 +// .next_mtiming_mask (mcontrol5_mtiming_mask), @1738 +// .previous_mpriority (mcontrol3_priority), @1739 +// .previous_mpriority_mask (mcontrol3_priority_mask), @1740 +// .previous_mtiming (mcontrol3_mtiming), @1741 +// .previous_mtiming_mask (mcontrol3_mtiming_mask), @1742 +// .mpriority_after_chain (m4_priority), @1743 +// .mpriority_mask_after_chain (m4_priority_mask), @1744 +// .mtiming_after_chain (m4_mtiming), @1745 +// .mtiming_mask_after_chain (m4_mtiming_mask), @1746 +// .exe0_match (mcontrol4_exe0_match), @1747 +// .exe1_match (mcontrol4_exe1_match), @1748 +// .ldst_match (mcontrol4_ldst_match), @1749 +// .tdata1 (m4_tdata1), @1750 +// .tdata2 (m4_tdata2), @1751 +// .tdata3 (m4_tdata3), @1752 +// .tinfo (m4_tinfo), @1753 +// .ldst_may_hit (mcontrol4_ldst_may_hit), @1754 +// .exe0_may_hit (mcontrol4_exe0_may_hit), @1755 +// .exe1_may_hit (mcontrol4_exe1_may_hit)); @1756 +// &Instance("pa_dtu_mcontrol_5","x_pa_dtu_mcontrol_5"); @1758 +// &Connect( @1759 +// .trigger_selected (tselect_wr_en[5]), @1760 +// .set_trigger_hit (mcontrol_hit[5]), @1761 +// .already_match (already_match[5]), @1762 +// .previous_trigger_chian (mcontrol4_chain), @1763 +// .previous_trigger_dmode (mcontrol4_dmode), @1764 +// .next_trigger_chain (mcontrol6_chain), @1765 +// .next_trigger_dmode (mcontrol6_dmode), @1766 +// .tdata1_chain (mcontrol5_chain), @1767 +// .tdata1_dmode (mcontrol5_dmode), @1768 +// .tdata1_action0 (mcontrol5_action0), @1769 +// .tdata1_action1 (mcontrol5_action1), @1770 +// .tdata1_timing (mcontrol5_timing), @1771 +// .exe_mcontrol (mcontrol5_is_exe), @1772 +// .ldst_mcontrol (mcontrol5_is_ldst), @1773 +// .ldst_addr_mcontrol (mcontrol5_is_ldst_addr), @1774 +// .ldst_data_mcontrol (mcontrol5_is_ldst_data), @1775 +// .mpriority (mcontrol5_priority), @1776 +// .mpriority_mask (mcontrol5_priority_mask), @1777 +// .mtiming (mcontrol5_mtiming), @1778 +// .mtiming_mask (mcontrol5_mtiming_mask), @1779 +// .next_mpriority (mcontrol6_priority), @1780 +// .next_mpriority_mask (mcontrol6_priority_mask), @1781 +// .next_mtiming (mcontrol6_mtiming), @1782 +// .next_mtiming_mask (mcontrol6_mtiming_mask), @1783 +// .previous_mpriority (mcontrol4_priority), @1784 +// .previous_mpriority_mask (mcontrol4_priority_mask), @1785 +// .previous_mtiming (mcontrol4_mtiming), @1786 +// .previous_mtiming_mask (mcontrol4_mtiming_mask), @1787 +// .mpriority_after_chain (m5_priority), @1788 +// .mpriority_mask_after_chain (m5_priority_mask), @1789 +// .mtiming_after_chain (m5_mtiming), @1790 +// .mtiming_mask_after_chain (m5_mtiming_mask), @1791 +// .exe0_match (mcontrol5_exe0_match), @1792 +// .exe1_match (mcontrol5_exe1_match), @1793 +// .ldst_match (mcontrol5_ldst_match), @1794 +// .tdata1 (m5_tdata1), @1795 +// .tdata2 (m5_tdata2), @1796 +// .tdata3 (m5_tdata3), @1797 +// .tinfo (m5_tinfo), @1798 +// .ldst_may_hit (mcontrol5_ldst_may_hit), @1799 +// .exe0_may_hit (mcontrol5_exe0_may_hit), @1800 +// .exe1_may_hit (mcontrol5_exe1_may_hit)); @1801 +// &Instance("pa_dtu_mcontrol_6","x_pa_dtu_mcontrol_6"); @1803 +// &Connect( @1804 +// .trigger_selected (tselect_wr_en[6]), @1805 +// .set_trigger_hit (mcontrol_hit[6]), @1806 +// .already_match (already_match[6]), @1807 +// .previous_trigger_chian (mcontrol5_chain), @1808 +// .previous_trigger_dmode (mcontrol5_dmode), @1809 +// .next_trigger_chain (mcontrol7_chain), @1810 +// .next_trigger_dmode (mcontrol7_dmode), @1811 +// .tdata1_chain (mcontrol6_chain), @1812 +// .tdata1_dmode (mcontrol6_dmode), @1813 +// .tdata1_action0 (mcontrol6_action0), @1814 +// .tdata1_action1 (mcontrol6_action1), @1815 +// .tdata1_timing (mcontrol6_timing), @1816 +// .exe_mcontrol (mcontrol6_is_exe), @1817 +// .ldst_mcontrol (mcontrol6_is_ldst), @1818 +// .ldst_addr_mcontrol (mcontrol6_is_ldst_addr), @1819 +// .ldst_data_mcontrol (mcontrol6_is_ldst_data), @1820 +// .mpriority (mcontrol6_priority), @1821 +// .mpriority_mask (mcontrol6_priority_mask), @1822 +// .mtiming (mcontrol6_mtiming), @1823 +// .mtiming_mask (mcontrol6_mtiming_mask), @1824 +// .next_mpriority (mcontrol7_priority), @1825 +// .next_mpriority_mask (mcontrol7_priority_mask), @1826 +// .next_mtiming (mcontrol7_mtiming), @1827 +// .next_mtiming_mask (mcontrol7_mtiming_mask), @1828 +// .previous_mpriority (mcontrol5_priority), @1829 +// .previous_mpriority_mask (mcontrol5_priority_mask), @1830 +// .previous_mtiming (mcontrol5_mtiming), @1831 +// .previous_mtiming_mask (mcontrol5_mtiming_mask), @1832 +// .mpriority_after_chain (m6_priority), @1833 +// .mpriority_mask_after_chain (m6_priority_mask), @1834 +// .mtiming_after_chain (m6_mtiming), @1835 +// .mtiming_mask_after_chain (m6_mtiming_mask), @1836 +// .exe0_match (mcontrol6_exe0_match), @1837 +// .exe1_match (mcontrol6_exe1_match), @1838 +// .ldst_match (mcontrol6_ldst_match), @1839 +// .tdata1 (m6_tdata1), @1840 +// .tdata2 (m6_tdata2), @1841 +// .tdata3 (m6_tdata3), @1842 +// .tinfo (m6_tinfo), @1843 +// .ldst_may_hit (mcontrol6_ldst_may_hit), @1844 +// .exe0_may_hit (mcontrol6_exe0_may_hit), @1845 +// .exe1_may_hit (mcontrol6_exe1_may_hit)); @1846 +// &Instance("pa_dtu_mcontrol_7","x_pa_dtu_mcontrol_7"); @1848 +// &Connect( @1849 +// .trigger_selected (tselect_wr_en[7]), @1850 +// .set_trigger_hit (mcontrol_hit[7]), @1851 +// .already_match (already_match[7]), @1852 +// .previous_trigger_chian (mcontrol6_chain), @1853 +// .previous_trigger_dmode (mcontrol6_dmode), @1854 +// .next_trigger_chain (1'b1), @1855 +// .next_trigger_dmode (1'b0), @1856 +// .tdata1_chain (mcontrol7_chain), @1857 +// .tdata1_dmode (mcontrol7_dmode), @1858 +// .tdata1_action0 (mcontrol7_action0), @1859 +// .tdata1_action1 (mcontrol7_action1), @1860 +// .tdata1_timing (mcontrol7_timing), @1861 +// .exe_mcontrol (mcontrol7_is_exe), @1862 +// .ldst_mcontrol (mcontrol7_is_ldst), @1863 +// .ldst_addr_mcontrol (mcontrol7_is_ldst_addr), @1864 +// .ldst_data_mcontrol (mcontrol7_is_ldst_data), @1865 +// .mpriority (mcontrol7_priority), @1866 +// .mpriority_mask (mcontrol7_priority_mask), @1867 +// .mtiming (mcontrol7_mtiming), @1868 +// .mtiming_mask (mcontrol7_mtiming_mask), @1869 +// .next_mpriority (2'b10), @1870 +// .next_mpriority_mask (2'b00), @1871 +// .next_mtiming (1'b1), @1872 +// .next_mtiming_mask (1'b0), @1873 +// .previous_mpriority (mcontrol6_priority), @1874 +// .previous_mpriority_mask (mcontrol6_priority_mask), @1875 +// .previous_mtiming (mcontrol6_mtiming), @1876 +// .previous_mtiming_mask (mcontrol6_mtiming_mask), @1877 +// .mpriority_after_chain (m7_priority), @1878 +// .mpriority_mask_after_chain (m7_priority_mask), @1879 +// .mtiming_after_chain (m7_mtiming), @1880 +// .mtiming_mask_after_chain (m7_mtiming_mask), @1881 +// .exe0_match (mcontrol7_exe0_match), @1882 +// .exe1_match (mcontrol7_exe1_match), @1883 +// .ldst_match (mcontrol7_ldst_match), @1884 +// .tdata1 (m7_tdata1), @1885 +// .tdata2 (m7_tdata2), @1886 +// .tdata3 (m7_tdata3), @1887 +// .tinfo (m7_tinfo), @1888 +// .ldst_may_hit (mcontrol7_ldst_may_hit), @1889 +// .exe0_may_hit (mcontrol7_exe0_may_hit), @1890 +// .exe1_may_hit (mcontrol7_exe1_may_hit)); @1891 +// &Force("bus","tselect_wr_en",9,0); @1892 +//========================================================= +// +// generate information +// +//========================================================= +// &Force("bus","lsu_dtu_halt_info",`TDT_HINFO_WIDTH-1,0); @1901 +assign already_match[2:0] = lsu_dtu_halt_info[`TDT_HINFO_TRIGGER:`TDT_HINFO_TRIGGER-2]; +assign action0_mcontrol[`TDT_TM_MCONTROL_TRI_NUM-1:0] = {mcontrol2_action0, + mcontrol1_action0,mcontrol0_action0}; +assign action1_mcontrol[`TDT_TM_MCONTROL_TRI_NUM-1:0] = {mcontrol2_action1, + mcontrol1_action1,mcontrol0_action1}; +assign ldst_addr_mcontrol = mcontrol0_is_ldst_addr || mcontrol1_is_ldst_addr || mcontrol2_is_ldst_addr; +assign ldst_data_mcontrol = mcontrol0_is_ldst_data || mcontrol1_is_ldst_data || mcontrol2_is_ldst_data; +assign exe0_may_hit = mcontrol0_exe0_may_hit || mcontrol1_exe0_may_hit || mcontrol2_exe0_may_hit; +assign exe1_may_hit = mcontrol0_exe1_may_hit || mcontrol1_exe1_may_hit || mcontrol2_exe1_may_hit; +assign exe_may_hit = exe0_may_hit && ifu_dtu_addr_vld0 || exe1_may_hit && ifu_dtu_addr_vld1; +assign ldst_may_hit = mcontrol0_ldst_may_hit || mcontrol1_ldst_may_hit || mcontrol2_ldst_may_hit; +//assign exe_clcye1_hit_vld_need_reg = exe0_may_hit && (ifu_dtu_addr_vld0 || ifu_dtu_data_vld0) || +// exe1_may_hit && (ifu_dtu_addr_vld1 || ifu_dtu_data_vld1); +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + exe_cycle2_cannot_hit <= 1'b0; + else if(exe_cycle2_cannot_hit) + exe_cycle2_cannot_hit <= 1'b0; + else if(exe_may_hit) + exe_cycle2_cannot_hit <= 1'b1; +end +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ldst_cycle2_cannot_hit <= 1'b0; + else if(ldst_cycle2_cannot_hit) + ldst_cycle2_cannot_hit <= 1'b0; + else if(ldst_may_hit) + ldst_cycle2_cannot_hit <= 1'b1; +end + +assign dtu_ifu_halt_info_vld = exe_cycle2_cannot_hit || !exe_may_hit; +assign dtu_lsu_halt_info_vld = ldst_cycle2_cannot_hit || !ldst_may_hit; +//----------------------chain info------------------------- +// &Force("nonport","mcontrol0_is_exe");&Force("nonport","mcontrol1_is_exe"); @2198 +// &Force("nonport","mcontrol2_is_exe");&Force("nonport","mcontrol3_is_exe"); @2199 +// &Force("nonport","mcontrol4_is_exe");&Force("nonport","mcontrol5_is_exe"); @2200 +// &Force("nonport","mcontrol6_is_exe");&Force("nonport","mcontrol7_is_exe"); @2201 + assign mcontrol3_is_ldst =1'b0; + assign mcontrol4_is_ldst =1'b0; + assign mcontrol5_is_ldst =1'b0; + assign mcontrol6_is_ldst =1'b0; + assign mcontrol7_is_ldst =1'b0; +//----------------------priority and timing info------------------------- +//higher priority + assign m3_priority[1:0] =2'b00; + assign m3_priority_mask[1:0] =2'b11; + assign m4_priority[1:0] =2'b00; + assign m4_priority_mask[1:0] =2'b11; + assign m5_priority[1:0] =2'b00; + assign m5_priority_mask[1:0] =2'b11; + assign m6_priority[1:0] =2'b00; + assign m6_priority_mask[1:0] =2'b11; + assign m7_priority[1:0] =2'b00; + assign m7_priority_mask[1:0] =2'b11; + +assign m1_phigher_than_m0 = |(m0_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m0 = |(m0_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m0 = |(m0_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m0 = |(m0_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m0 = |(m0_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m0 = |(m0_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m0 = |(m0_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m0[6:0] = {m7_phigher_than_m0,m6_phigher_than_m0,m5_phigher_than_m0, + m4_phigher_than_m0,m3_phigher_than_m0,m2_phigher_than_m0, + m1_phigher_than_m0}; + +assign m0_phigher_than_m1 = |(m1_priority_mask[1:0] & m0_priority[1:0]); +assign m2_phigher_than_m1 = |(m1_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m1 = |(m1_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m1 = |(m1_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m1 = |(m1_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m1 = |(m1_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m1 = |(m1_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m1[6:0] = {m7_phigher_than_m1,m6_phigher_than_m1,m5_phigher_than_m1, + m4_phigher_than_m1,m3_phigher_than_m1,m2_phigher_than_m1, + m0_phigher_than_m1}; + +assign m0_phigher_than_m2 = |(m2_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m2 = |(m2_priority_mask[1:0] & m1_priority[1:0]); +assign m3_phigher_than_m2 = |(m2_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m2 = |(m2_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m2 = |(m2_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m2 = |(m2_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m2 = |(m2_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m2[6:0] = {m7_phigher_than_m2,m6_phigher_than_m2,m5_phigher_than_m2, + m4_phigher_than_m2,m3_phigher_than_m2,m1_phigher_than_m2, + m0_phigher_than_m2}; + +assign m0_phigher_than_m3 = |(m3_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m3 = |(m3_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m3 = |(m3_priority_mask[1:0] & m2_priority[1:0]); +assign m4_phigher_than_m3 = |(m3_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m3 = |(m3_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m3 = |(m3_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m3 = |(m3_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m3[6:0] = {m7_phigher_than_m3,m6_phigher_than_m3,m5_phigher_than_m3, + m4_phigher_than_m3,m2_phigher_than_m3,m1_phigher_than_m3, + m0_phigher_than_m3}; + +assign m0_phigher_than_m4 = |(m4_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m4 = |(m4_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m4 = |(m4_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m4 = |(m4_priority_mask[1:0] & m3_priority[1:0]); +assign m5_phigher_than_m4 = |(m4_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m4 = |(m4_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m4 = |(m4_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m4[6:0] = {m7_phigher_than_m4,m6_phigher_than_m4,m5_phigher_than_m4, + m3_phigher_than_m4,m2_phigher_than_m4,m1_phigher_than_m4, + m0_phigher_than_m4}; + +assign m0_phigher_than_m5 = |(m5_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m5 = |(m5_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m5 = |(m5_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m5 = |(m5_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m5 = |(m5_priority_mask[1:0] & m4_priority[1:0]); +assign m6_phigher_than_m5 = |(m5_priority_mask[1:0] & m6_priority[1:0]); +assign m7_phigher_than_m5 = |(m5_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m5[6:0] = {m7_phigher_than_m5,m6_phigher_than_m5,m4_phigher_than_m5, + m3_phigher_than_m5,m2_phigher_than_m5,m1_phigher_than_m5, + m0_phigher_than_m5}; + +assign m0_phigher_than_m6 = |(m6_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m6 = |(m6_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m6 = |(m6_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m6 = |(m6_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m6 = |(m6_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m6 = |(m6_priority_mask[1:0] & m5_priority[1:0]); +assign m7_phigher_than_m6 = |(m6_priority_mask[1:0] & m7_priority[1:0]); +assign x_phigher_than_m6[6:0] = {m7_phigher_than_m6,m5_phigher_than_m6,m4_phigher_than_m6, + m3_phigher_than_m6,m2_phigher_than_m6,m1_phigher_than_m6, + m0_phigher_than_m6}; + +assign m0_phigher_than_m7 = |(m7_priority_mask[1:0] & m0_priority[1:0]); +assign m1_phigher_than_m7 = |(m7_priority_mask[1:0] & m1_priority[1:0]); +assign m2_phigher_than_m7 = |(m7_priority_mask[1:0] & m2_priority[1:0]); +assign m3_phigher_than_m7 = |(m7_priority_mask[1:0] & m3_priority[1:0]); +assign m4_phigher_than_m7 = |(m7_priority_mask[1:0] & m4_priority[1:0]); +assign m5_phigher_than_m7 = |(m7_priority_mask[1:0] & m5_priority[1:0]); +assign m6_phigher_than_m7 = |(m7_priority_mask[1:0] & m6_priority[1:0]); +assign x_phigher_than_m7[6:0] = {m6_phigher_than_m7,m5_phigher_than_m7,m4_phigher_than_m7, + m3_phigher_than_m7,m2_phigher_than_m7,m1_phigher_than_m7, + m0_phigher_than_m7}; + +//higher timing + assign m3_mtiming =1'b0; + assign m3_mtiming_mask =1'b1; + assign m4_mtiming =1'b0; + assign m4_mtiming_mask =1'b1; + assign m5_mtiming =1'b0; + assign m5_mtiming_mask =1'b1; + assign m6_mtiming =1'b0; + assign m6_mtiming_mask =1'b1; + assign m7_mtiming =1'b0; + assign m7_mtiming_mask =1'b1; + +assign m1_thigher_than_m0 = m0_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m0 = m0_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m0 = m0_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m0 = m0_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m0 = m0_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m0 = m0_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m0 = m0_mtiming_mask & m7_mtiming; +assign x_thigher_than_m0[6:0] = {m7_thigher_than_m0,m6_thigher_than_m0,m5_thigher_than_m0, + m4_thigher_than_m0,m3_thigher_than_m0,m2_thigher_than_m0, + m1_thigher_than_m0}; + +assign m0_thigher_than_m1 = m1_mtiming_mask & m0_mtiming; +assign m2_thigher_than_m1 = m1_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m1 = m1_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m1 = m1_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m1 = m1_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m1 = m1_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m1 = m1_mtiming_mask & m7_mtiming; +assign x_thigher_than_m1[6:0] = {m7_thigher_than_m1,m6_thigher_than_m1,m5_thigher_than_m1, + m4_thigher_than_m1,m3_thigher_than_m1,m2_thigher_than_m1, + m0_thigher_than_m1}; + +assign m0_thigher_than_m2 = m2_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m2 = m2_mtiming_mask & m1_mtiming; +assign m3_thigher_than_m2 = m2_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m2 = m2_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m2 = m2_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m2 = m2_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m2 = m2_mtiming_mask & m7_mtiming; +assign x_thigher_than_m2[6:0] = {m7_thigher_than_m2,m6_thigher_than_m2,m5_thigher_than_m2, + m4_thigher_than_m2,m3_thigher_than_m2,m1_thigher_than_m2, + m0_thigher_than_m2}; + +assign m0_thigher_than_m3 = m3_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m3 = m3_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m3 = m3_mtiming_mask & m2_mtiming; +assign m4_thigher_than_m3 = m3_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m3 = m3_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m3 = m3_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m3 = m3_mtiming_mask & m7_mtiming; +assign x_thigher_than_m3[6:0] = {m7_thigher_than_m3,m6_thigher_than_m3,m5_thigher_than_m3, + m4_thigher_than_m3,m2_thigher_than_m3,m1_thigher_than_m3, + m0_thigher_than_m3}; + +assign m0_thigher_than_m4 = m4_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m4 = m4_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m4 = m4_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m4 = m4_mtiming_mask & m3_mtiming; +assign m5_thigher_than_m4 = m4_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m4 = m4_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m4 = m4_mtiming_mask & m7_mtiming; +assign x_thigher_than_m4[6:0] = {m7_thigher_than_m4,m6_thigher_than_m4,m5_thigher_than_m4, + m3_thigher_than_m4,m2_thigher_than_m4,m1_thigher_than_m4, + m0_thigher_than_m4}; + +assign m0_thigher_than_m5 = m5_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m5 = m5_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m5 = m5_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m5 = m5_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m5 = m5_mtiming_mask & m4_mtiming; +assign m6_thigher_than_m5 = m5_mtiming_mask & m6_mtiming; +assign m7_thigher_than_m5 = m5_mtiming_mask & m7_mtiming; +assign x_thigher_than_m5[6:0] = {m7_thigher_than_m5,m6_thigher_than_m5,m4_thigher_than_m5, + m3_thigher_than_m5,m2_thigher_than_m5,m1_thigher_than_m5, + m0_thigher_than_m5}; + +assign m0_thigher_than_m6 = m6_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m6 = m6_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m6 = m6_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m6 = m6_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m6 = m6_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m6 = m6_mtiming_mask & m5_mtiming; +assign m7_thigher_than_m6 = m6_mtiming_mask & m7_mtiming; +assign x_thigher_than_m6[6:0] = {m7_thigher_than_m6,m5_thigher_than_m6,m4_thigher_than_m6, + m3_thigher_than_m6,m2_thigher_than_m6,m1_thigher_than_m6, + m0_thigher_than_m6}; + +assign m0_thigher_than_m7 = m7_mtiming_mask & m0_mtiming; +assign m1_thigher_than_m7 = m7_mtiming_mask & m1_mtiming; +assign m2_thigher_than_m7 = m7_mtiming_mask & m2_mtiming; +assign m3_thigher_than_m7 = m7_mtiming_mask & m3_mtiming; +assign m4_thigher_than_m7 = m7_mtiming_mask & m4_mtiming; +assign m5_thigher_than_m7 = m7_mtiming_mask & m5_mtiming; +assign m6_thigher_than_m7 = m7_mtiming_mask & m6_mtiming; +assign x_thigher_than_m7[6:0] = {m6_thigher_than_m7,m5_thigher_than_m7,m4_thigher_than_m7, + m3_thigher_than_m7,m2_thigher_than_m7,m1_thigher_than_m7, + m0_thigher_than_m7}; +//record phigher and thigher info in register +// &Force("nonport","x_phigher_than_m0");&Force("nonport","x_thigher_than_m0"); @2567 +// &Force("nonport","x_phigher_than_m1");&Force("nonport","x_thigher_than_m1"); @2568 +// &Force("nonport","x_phigher_than_m2");&Force("nonport","x_thigher_than_m2"); @2569 +// &Force("nonport","x_phigher_than_m3");&Force("nonport","x_thigher_than_m3"); @2570 +// &Force("nonport","x_phigher_than_m4");&Force("nonport","x_thigher_than_m4"); @2571 +// &Force("nonport","x_phigher_than_m5");&Force("nonport","x_thigher_than_m5"); @2572 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2573 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2574 +// &Force("nonport","x_phigher_than_m2");&Force("nonport","x_thigher_than_m2"); @2593 +// &Force("nonport","x_phigher_than_m3");&Force("nonport","x_thigher_than_m3"); @2594 +// &Force("nonport","x_phigher_than_m4");&Force("nonport","x_thigher_than_m4"); @2595 +// &Force("nonport","x_phigher_than_m5");&Force("nonport","x_thigher_than_m5"); @2596 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2597 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2598 +// &Force("nonport","x_phigher_than_m3");&Force("nonport","x_thigher_than_m3"); @2636 +// &Force("nonport","x_phigher_than_m4");&Force("nonport","x_thigher_than_m4"); @2637 +// &Force("nonport","x_phigher_than_m5");&Force("nonport","x_thigher_than_m5"); @2638 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2639 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2640 +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + x_phigher_than_m0_reg_lowbits[1:0] <= 2'b0; + x_phigher_than_m1_reg_lowbits[1:0] <= 2'b0; + x_phigher_than_m2_reg_lowbits[1:0] <= 2'b0; + + x_thigher_than_m0_reg_lowbits[1:0] <= 2'b0; + x_thigher_than_m1_reg_lowbits[1:0] <= 2'b0; + x_thigher_than_m2_reg_lowbits[1:0] <= 2'b0; + end + else if(cp0_write_tdata1_f) + begin + x_phigher_than_m0_reg_lowbits[1:0] <= x_phigher_than_m0[1:0]; + x_phigher_than_m1_reg_lowbits[1:0] <= x_phigher_than_m1[1:0]; + x_phigher_than_m2_reg_lowbits[1:0] <= x_phigher_than_m2[1:0]; + + x_thigher_than_m0_reg_lowbits[1:0] <= x_thigher_than_m0[1:0]; + x_thigher_than_m1_reg_lowbits[1:0] <= x_thigher_than_m1[1:0]; + x_thigher_than_m2_reg_lowbits[1:0] <= x_thigher_than_m2[1:0]; + end +end +assign x_phigher_than_m0_reg[6:0] = {5'b0,x_phigher_than_m0_reg_lowbits[1:0]}; +assign x_thigher_than_m0_reg[6:0] = {5'b0,x_thigher_than_m0_reg_lowbits[1:0]}; +assign x_phigher_than_m1_reg[6:0] = {5'b0,x_phigher_than_m1_reg_lowbits[1:0]}; +assign x_thigher_than_m1_reg[6:0] = {5'b0,x_thigher_than_m1_reg_lowbits[1:0]}; +assign x_phigher_than_m2_reg[6:0] = {5'b0,x_phigher_than_m2_reg_lowbits[1:0]}; +assign x_thigher_than_m2_reg[6:0] = {5'b0,x_thigher_than_m2_reg_lowbits[1:0]}; +assign x_phigher_than_m3_reg[6:0] = 7'b0; +assign x_thigher_than_m3_reg[6:0] = 7'b0; +assign x_phigher_than_m4_reg[6:0] = 7'b0; +assign x_thigher_than_m4_reg[6:0] = 7'b0; +assign x_phigher_than_m5_reg[6:0] = 7'b0; +assign x_thigher_than_m5_reg[6:0] = 7'b0; +assign x_phigher_than_m6_reg[6:0] = 7'b0; +assign x_thigher_than_m6_reg[6:0] = 7'b0; +assign x_phigher_than_m7_reg[6:0] = 7'b0; +assign x_thigher_than_m7_reg[6:0] = 7'b0; +// &Force("nonport","x_phigher_than_m4");&Force("nonport","x_thigher_than_m4"); @2682 +// &Force("nonport","x_phigher_than_m5");&Force("nonport","x_thigher_than_m5"); @2683 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2684 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2685 +// &Force("nonport","x_phigher_than_m5");&Force("nonport","x_thigher_than_m5"); @2731 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2732 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2733 +// &Force("nonport","x_phigher_than_m6");&Force("nonport","x_thigher_than_m6"); @2783 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2784 +// &Force("nonport","x_phigher_than_m7");&Force("nonport","x_thigher_than_m7"); @2838 + +//========================================================= +// +// output select +// +//========================================================= + assign mcontrol3_exe0_match = 1'b0; + assign mcontrol3_exe1_match = 1'b0; + assign mcontrol3_ldst_match = 1'b0; + assign mcontrol3_action0 = 1'b0; + assign mcontrol3_action1 = 1'b0; + assign mcontrol3_timing = 1'b0; + assign mcontrol3_is_ldst_data =1'b0; + assign mcontrol4_exe0_match = 1'b0; + assign mcontrol4_exe1_match = 1'b0; + assign mcontrol4_ldst_match = 1'b0; + assign mcontrol4_action0 = 1'b0; + assign mcontrol4_action1 = 1'b0; + assign mcontrol4_timing = 1'b0; + assign mcontrol4_is_ldst_data =1'b0; + assign mcontrol5_exe0_match = 1'b0; + assign mcontrol5_exe1_match = 1'b0; + assign mcontrol5_ldst_match = 1'b0; + assign mcontrol5_action0 = 1'b0; + assign mcontrol5_action1 = 1'b0; + assign mcontrol5_timing = 1'b0; + assign mcontrol5_is_ldst_data =1'b0; + assign mcontrol6_exe0_match = 1'b0; + assign mcontrol6_exe1_match = 1'b0; + assign mcontrol6_ldst_match = 1'b0; + assign mcontrol6_action0 = 1'b0; + assign mcontrol6_action1 = 1'b0; + assign mcontrol6_timing = 1'b0; + assign mcontrol6_is_ldst_data =1'b0; + assign mcontrol7_exe0_match = 1'b0; + assign mcontrol7_exe1_match = 1'b0; + assign mcontrol7_ldst_match = 1'b0; + assign mcontrol7_action0 = 1'b0; + assign mcontrol7_action1 = 1'b0; + assign mcontrol7_timing = 1'b0; + assign mcontrol7_is_ldst_data =1'b0; + +//--------------------------------------------------------- +// exe0 output select logic +//--------------------------------------------------------- +//chain match logic +assign exe0_single_mcontrol_cancel = mcontrol0_exe0_match || mcontrol1_exe0_match || mcontrol2_exe0_match || mcontrol3_exe0_match || + mcontrol4_exe0_match || mcontrol5_exe0_match || mcontrol6_exe0_match || mcontrol7_exe0_match; +assign exe0_chain_cancel = 1'b0; + +assign exe0_after_chain_match0 = mcontrol0_exe0_match; +assign exe0_after_chain_match1 = mcontrol1_exe0_match; +assign exe0_after_chain_match2 = mcontrol2_exe0_match; +assign exe0_after_chain_match3 = mcontrol3_exe0_match; +assign exe0_after_chain_match4 = mcontrol4_exe0_match; +assign exe0_after_chain_match5 = mcontrol5_exe0_match; +assign exe0_after_chain_match6 = mcontrol6_exe0_match; +assign exe0_after_chain_match7 = mcontrol7_exe0_match; +assign exe0_after_chain_match[7:0] ={exe0_after_chain_match7,exe0_after_chain_match6, + exe0_after_chain_match5,exe0_after_chain_match4, + exe0_after_chain_match3,exe0_after_chain_match2, + exe0_after_chain_match1,exe0_after_chain_match0}; +//priority select logic +assign m0_exe0_can_match = !(|(x_phigher_than_m0_reg[6:0] & exe0_after_chain_match[7:1])); +assign m1_exe0_can_match = !(|(x_phigher_than_m1_reg[6:0] & {exe0_after_chain_match[7:2],exe0_after_chain_match[0]})); +assign m2_exe0_can_match = !(|(x_phigher_than_m2_reg[6:0] & {exe0_after_chain_match[7:3],exe0_after_chain_match[1:0]})); +assign m3_exe0_can_match = !(|(x_phigher_than_m3_reg[6:0] & {exe0_after_chain_match[7:4],exe0_after_chain_match[2:0]})); +assign m4_exe0_can_match = !(|(x_phigher_than_m4_reg[6:0] & {exe0_after_chain_match[7:5],exe0_after_chain_match[3:0]})); +assign m5_exe0_can_match = !(|(x_phigher_than_m5_reg[6:0] & {exe0_after_chain_match[7:6],exe0_after_chain_match[4:0]})); +assign m6_exe0_can_match = !(|(x_phigher_than_m6_reg[6:0] & {exe0_after_chain_match[7],exe0_after_chain_match[5:0]})); +assign m7_exe0_can_match = !(|(x_phigher_than_m7_reg[6:0] & exe0_after_chain_match[6:0])); + +assign m0_exe0_match = m0_exe0_can_match && exe0_after_chain_match0; +assign m1_exe0_match = m1_exe0_can_match && exe0_after_chain_match1; +assign m2_exe0_match = m2_exe0_can_match && exe0_after_chain_match2; +assign m3_exe0_match = m3_exe0_can_match && exe0_after_chain_match3; +assign m4_exe0_match = m4_exe0_can_match && exe0_after_chain_match4; +assign m5_exe0_match = m5_exe0_can_match && exe0_after_chain_match5; +assign m6_exe0_match = m6_exe0_can_match && exe0_after_chain_match6; +assign m7_exe0_match = m7_exe0_can_match && exe0_after_chain_match7; + +//output select +//match +assign exe0_match[7:0] = {m7_exe0_match,m6_exe0_match,m5_exe0_match,m4_exe0_match, + m3_exe0_match,m2_exe0_match,m1_exe0_match,m0_exe0_match}; +assign exe0_have_match = exe0_cancel; +//chain +assign exe0_chain = 1'b0; +//action0 +assign m0_exe0_action0 = m0_exe0_match && mcontrol0_action0; +assign m1_exe0_action0 = m1_exe0_match && mcontrol1_action0; +assign m2_exe0_action0 = m2_exe0_match && mcontrol2_action0; +assign m3_exe0_action0 = m3_exe0_match && mcontrol3_action0; +assign m4_exe0_action0 = m4_exe0_match && mcontrol4_action0; +assign m5_exe0_action0 = m5_exe0_match && mcontrol5_action0; +assign m6_exe0_action0 = m6_exe0_match && mcontrol6_action0; +assign m7_exe0_action0 = m7_exe0_match && mcontrol7_action0; +assign exe0_action0 = m7_exe0_action0 || m6_exe0_action0 || m5_exe0_action0 || m4_exe0_action0 || + m3_exe0_action0 || m2_exe0_action0 || m1_exe0_action0 || m0_exe0_action0; + +//action1 +assign m0_exe0_action1 = m0_exe0_match && mcontrol0_action1; +assign m1_exe0_action1 = m1_exe0_match && mcontrol1_action1; +assign m2_exe0_action1 = m2_exe0_match && mcontrol2_action1; +assign m3_exe0_action1 = m3_exe0_match && mcontrol3_action1; +assign m4_exe0_action1 = m4_exe0_match && mcontrol4_action1; +assign m5_exe0_action1 = m5_exe0_match && mcontrol5_action1; +assign m6_exe0_action1 = m6_exe0_match && mcontrol6_action1; +assign m7_exe0_action1 = m7_exe0_match && mcontrol7_action1; +assign exe0_action1 = m7_exe0_action1 || m6_exe0_action1 || m5_exe0_action1 || m4_exe0_action1 || + m3_exe0_action1 || m2_exe0_action1 || m1_exe0_action1 || m0_exe0_action1; + +assign exe0_action = !exe0_action0 && exe0_action1; +assign exe0_action01 = exe0_action0 && exe0_action1; + +//timing +assign exe0_timing = 1'b0; + +//cancel +assign exe0_cancel = exe0_single_mcontrol_cancel || exe0_chain_cancel; + +assign mcontrol_halt_info0[`TDT_HINFO_WIDTH-1:0] = {exe0_match[`TDT_TM_MCONTROL_TRI_NUM-1:0],4'd2,1'b0, + exe0_timing,exe0_action01,exe0_action, + exe0_chain,1'b0,exe0_have_match,exe0_cancel}; + +//--------------------------------------------------------- +// exe1 output select logic +//--------------------------------------------------------- +//chain match logic +assign exe1_single_mcontrol_cancel = mcontrol0_exe1_match || mcontrol1_exe1_match || mcontrol2_exe1_match || mcontrol3_exe1_match || + mcontrol4_exe1_match || mcontrol5_exe1_match || mcontrol6_exe1_match || mcontrol7_exe1_match; +assign exe1_chain_cancel = 1'b0; + +assign exe1_after_chain_match0 = mcontrol0_exe1_match; +assign exe1_after_chain_match1 = mcontrol1_exe1_match; +assign exe1_after_chain_match2 = mcontrol2_exe1_match; +assign exe1_after_chain_match3 = mcontrol3_exe1_match; +assign exe1_after_chain_match4 = mcontrol4_exe1_match; +assign exe1_after_chain_match5 = mcontrol5_exe1_match; +assign exe1_after_chain_match6 = mcontrol6_exe1_match; +assign exe1_after_chain_match7 = mcontrol7_exe1_match; +assign exe1_after_chain_match[7:0] ={exe1_after_chain_match7,exe1_after_chain_match6, + exe1_after_chain_match5,exe1_after_chain_match4, + exe1_after_chain_match3,exe1_after_chain_match2, + exe1_after_chain_match1,exe1_after_chain_match0}; +//priority select logic +assign m0_exe1_can_match = !(|(x_phigher_than_m0_reg[6:0] & exe1_after_chain_match[7:1])); +assign m1_exe1_can_match = !(|(x_phigher_than_m1_reg[6:0] & {exe1_after_chain_match[7:2],exe1_after_chain_match[0]})); +assign m2_exe1_can_match = !(|(x_phigher_than_m2_reg[6:0] & {exe1_after_chain_match[7:3],exe1_after_chain_match[1:0]})); +assign m3_exe1_can_match = !(|(x_phigher_than_m3_reg[6:0] & {exe1_after_chain_match[7:4],exe1_after_chain_match[2:0]})); +assign m4_exe1_can_match = !(|(x_phigher_than_m4_reg[6:0] & {exe1_after_chain_match[7:5],exe1_after_chain_match[3:0]})); +assign m5_exe1_can_match = !(|(x_phigher_than_m5_reg[6:0] & {exe1_after_chain_match[7:6],exe1_after_chain_match[4:0]})); +assign m6_exe1_can_match = !(|(x_phigher_than_m6_reg[6:0] & {exe1_after_chain_match[7],exe1_after_chain_match[5:0]})); +assign m7_exe1_can_match = !(|(x_phigher_than_m7_reg[6:0] & exe1_after_chain_match[6:0])); + +assign m0_exe1_match = m0_exe1_can_match && exe1_after_chain_match0; +assign m1_exe1_match = m1_exe1_can_match && exe1_after_chain_match1; +assign m2_exe1_match = m2_exe1_can_match && exe1_after_chain_match2; +assign m3_exe1_match = m3_exe1_can_match && exe1_after_chain_match3; +assign m4_exe1_match = m4_exe1_can_match && exe1_after_chain_match4; +assign m5_exe1_match = m5_exe1_can_match && exe1_after_chain_match5; +assign m6_exe1_match = m6_exe1_can_match && exe1_after_chain_match6; +assign m7_exe1_match = m7_exe1_can_match && exe1_after_chain_match7; + +//output select +//match +assign exe1_match[7:0] = {m7_exe1_match,m6_exe1_match,m5_exe1_match,m4_exe1_match, + m3_exe1_match,m2_exe1_match,m1_exe1_match,m0_exe1_match}; +assign exe1_have_match = exe1_cancel; +//chain +assign exe1_chain = 1'b0; +//action0 +assign m0_exe1_action0 = m0_exe1_match && mcontrol0_action0; +assign m1_exe1_action0 = m1_exe1_match && mcontrol1_action0; +assign m2_exe1_action0 = m2_exe1_match && mcontrol2_action0; +assign m3_exe1_action0 = m3_exe1_match && mcontrol3_action0; +assign m4_exe1_action0 = m4_exe1_match && mcontrol4_action0; +assign m5_exe1_action0 = m5_exe1_match && mcontrol5_action0; +assign m6_exe1_action0 = m6_exe1_match && mcontrol6_action0; +assign m7_exe1_action0 = m7_exe1_match && mcontrol7_action0; +assign exe1_action0 = m7_exe1_action0 || m6_exe1_action0 || m5_exe1_action0 || m4_exe1_action0 || + m3_exe1_action0 || m2_exe1_action0 || m1_exe1_action0 || m0_exe1_action0; + +//action1 +assign m0_exe1_action1 = m0_exe1_match && mcontrol0_action1; +assign m1_exe1_action1 = m1_exe1_match && mcontrol1_action1; +assign m2_exe1_action1 = m2_exe1_match && mcontrol2_action1; +assign m3_exe1_action1 = m3_exe1_match && mcontrol3_action1; +assign m4_exe1_action1 = m4_exe1_match && mcontrol4_action1; +assign m5_exe1_action1 = m5_exe1_match && mcontrol5_action1; +assign m6_exe1_action1 = m6_exe1_match && mcontrol6_action1; +assign m7_exe1_action1 = m7_exe1_match && mcontrol7_action1; +assign exe1_action1 = m7_exe1_action1 || m6_exe1_action1 || m5_exe1_action1 || m4_exe1_action1 || + m3_exe1_action1 || m2_exe1_action1 || m1_exe1_action1 || m0_exe1_action1; + +assign exe1_action = !exe1_action0 && exe1_action1; +assign exe1_action01 = exe1_action0 && exe1_action1; + +//timing +assign exe1_timing = 1'b0; + +//cancel +assign exe1_cancel = exe1_single_mcontrol_cancel || exe1_chain_cancel; + +assign mcontrol_halt_info1[`TDT_HINFO_WIDTH-1:0] = {exe1_match[`TDT_TM_MCONTROL_TRI_NUM-1:0],4'd2,1'b0, + exe1_timing,exe1_action01,exe1_action, + exe1_chain,1'b0,exe1_have_match,exe1_cancel}; + +//--------------------------------------------------------- +// ldst output select logic +//--------------------------------------------------------- +assign mcontrol0_store_data_timing0 = mcontrol0_is_ldst_data && !mcontrol0_timing; +assign mcontrol1_store_data_timing0 = mcontrol1_is_ldst_data && !mcontrol1_timing; +assign mcontrol2_store_data_timing0 = mcontrol2_is_ldst_data && !mcontrol2_timing; +assign mcontrol3_store_data_timing0 = mcontrol3_is_ldst_data && !mcontrol3_timing; +assign mcontrol4_store_data_timing0 = mcontrol4_is_ldst_data && !mcontrol4_timing; +assign mcontrol5_store_data_timing0 = mcontrol5_is_ldst_data && !mcontrol5_timing; +assign mcontrol6_store_data_timing0 = mcontrol6_is_ldst_data && !mcontrol6_timing; +assign mcontrol7_store_data_timing0 = mcontrol7_is_ldst_data && !mcontrol7_timing; +assign have_store_data_timing0 = mcontrol0_store_data_timing0 || mcontrol1_store_data_timing0 || + mcontrol2_store_data_timing0 || mcontrol3_store_data_timing0 || + mcontrol4_store_data_timing0 || mcontrol5_store_data_timing0 || + mcontrol6_store_data_timing0 || mcontrol7_store_data_timing0; + +//chain match logic +assign ldst_mcontrol0_single_match = mcontrol0_ldst_match; +assign ldst_mcontrol1_single_match = mcontrol1_ldst_match; +assign ldst_mcontrol2_single_match = mcontrol2_ldst_match; +assign ldst_mcontrol3_single_match = mcontrol3_ldst_match; +assign ldst_mcontrol4_single_match = mcontrol4_ldst_match; +assign ldst_mcontrol5_single_match = mcontrol5_ldst_match; +assign ldst_mcontrol6_single_match = mcontrol6_ldst_match; +assign ldst_mcontrol7_single_match = mcontrol7_ldst_match; + +assign ldst_chain0_match = 1'b0; +assign ldst_chain1_match = 1'b0; +assign ldst_chain2_match = 1'b0; +assign ldst_chain3_match = 1'b0; +assign ldst_chain4_match = 1'b0; +assign ldst_chain5_match = 1'b0; +assign ldst_chain6_match = 1'b0; + +assign ldst_after_chain_match0 = mcontrol0_ldst_match; +assign ldst_after_chain_match1 = mcontrol1_ldst_match; +assign ldst_after_chain_match2 = mcontrol2_ldst_match; +assign ldst_after_chain_match3 = mcontrol3_ldst_match; +assign ldst_after_chain_match4 = mcontrol4_ldst_match; +assign ldst_after_chain_match5 = mcontrol5_ldst_match; +assign ldst_after_chain_match6 = mcontrol6_ldst_match; +assign ldst_after_chain_match7 = mcontrol7_ldst_match; +assign ldst_after_chain_match[7:0] ={ldst_after_chain_match7,ldst_after_chain_match6, + ldst_after_chain_match5,ldst_after_chain_match4, + ldst_after_chain_match3,ldst_after_chain_match2, + ldst_after_chain_match1,ldst_after_chain_match0}; +//timing0 match +assign ldst_mcontrol0_timing0_match = !mcontrol0_timing && ldst_mcontrol0_single_match; +assign ldst_mcontrol1_timing0_match = !mcontrol1_timing && ldst_mcontrol1_single_match; +assign ldst_mcontrol2_timing0_match = !mcontrol2_timing && ldst_mcontrol2_single_match; +assign ldst_mcontrol3_timing0_match = !mcontrol3_timing && ldst_mcontrol3_single_match; +assign ldst_mcontrol4_timing0_match = !mcontrol4_timing && ldst_mcontrol4_single_match; +assign ldst_mcontrol5_timing0_match = !mcontrol5_timing && ldst_mcontrol5_single_match; +assign ldst_mcontrol6_timing0_match = !mcontrol6_timing && ldst_mcontrol6_single_match; +assign ldst_mcontrol7_timing0_match = !mcontrol7_timing && ldst_mcontrol7_single_match; + +assign chain0_timing0_match = (mcontrol0_is_ldst ? !mcontrol0_timing : !mcontrol1_timing) && ldst_chain0_match; +assign chain1_timing0_match = (mcontrol1_is_ldst ? !mcontrol1_timing : !mcontrol2_timing) && ldst_chain1_match; +assign chain2_timing0_match = (mcontrol2_is_ldst ? !mcontrol2_timing : !mcontrol3_timing) && ldst_chain2_match; +assign chain3_timing0_match = (mcontrol3_is_ldst ? !mcontrol3_timing : !mcontrol4_timing) && ldst_chain3_match; +assign chain4_timing0_match = (mcontrol4_is_ldst ? !mcontrol4_timing : !mcontrol5_timing) && ldst_chain4_match; +assign chain5_timing0_match = (mcontrol5_is_ldst ? !mcontrol5_timing : !mcontrol6_timing) && ldst_chain5_match; +assign chain6_timing0_match = (mcontrol6_is_ldst ? !mcontrol6_timing : !mcontrol7_timing) && ldst_chain6_match; +// &Force("nonport","mcontrol7_is_ldst"); @3561 + +assign timing0_match[7:0] = {ldst_mcontrol7_timing0_match || chain6_timing0_match, + ldst_mcontrol6_timing0_match || chain6_timing0_match || chain5_timing0_match, + ldst_mcontrol5_timing0_match || chain5_timing0_match || chain4_timing0_match, + ldst_mcontrol4_timing0_match || chain4_timing0_match || chain3_timing0_match, + ldst_mcontrol3_timing0_match || chain3_timing0_match || chain2_timing0_match, + ldst_mcontrol2_timing0_match || chain2_timing0_match || chain1_timing0_match, + ldst_mcontrol1_timing0_match || chain1_timing0_match || chain0_timing0_match, + ldst_mcontrol0_timing0_match || chain0_timing0_match}; + +assign have_timing0_match = |timing0_match[7:0]; + +//priority select logic +assign m0_ldst_can_match = !(|(x_thigher_than_m0_reg[6:0] & ldst_after_chain_match[7:1])); +assign m1_ldst_can_match = !(|(x_thigher_than_m1_reg[6:0] & {ldst_after_chain_match[7:2],ldst_after_chain_match[0]})); +assign m2_ldst_can_match = !(|(x_thigher_than_m2_reg[6:0] & {ldst_after_chain_match[7:3],ldst_after_chain_match[1:0]})); +assign m3_ldst_can_match = !(|(x_thigher_than_m3_reg[6:0] & {ldst_after_chain_match[7:4],ldst_after_chain_match[2:0]})); +assign m4_ldst_can_match = !(|(x_thigher_than_m4_reg[6:0] & {ldst_after_chain_match[7:5],ldst_after_chain_match[3:0]})); +assign m5_ldst_can_match = !(|(x_thigher_than_m5_reg[6:0] & {ldst_after_chain_match[7:6],ldst_after_chain_match[4:0]})); +assign m6_ldst_can_match = !(|(x_thigher_than_m6_reg[6:0] & {ldst_after_chain_match[7],ldst_after_chain_match[5:0]})); +assign m7_ldst_can_match = !(|(x_thigher_than_m7_reg[6:0] & ldst_after_chain_match[6:0])); + +assign m0_ldst_match = m0_ldst_can_match && ldst_after_chain_match[0]; +assign m1_ldst_match = m1_ldst_can_match && ldst_after_chain_match[1]; +assign m2_ldst_match = m2_ldst_can_match && ldst_after_chain_match[2]; +assign m3_ldst_match = m3_ldst_can_match && ldst_after_chain_match[3]; +assign m4_ldst_match = m4_ldst_can_match && ldst_after_chain_match[4]; +assign m5_ldst_match = m5_ldst_can_match && ldst_after_chain_match[5]; +assign m6_ldst_match = m6_ldst_can_match && ldst_after_chain_match[6]; +assign m7_ldst_match = m7_ldst_can_match && ldst_after_chain_match[7]; + +//output select +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + lsu_dtu_last_check_f <= 1'b0; + else if(lsu_dtu_last_check) + lsu_dtu_last_check_f <= 1'b1; + else if(lsu_dtu_last_check_f) + lsu_dtu_last_check_f <= 1'b0; +end + +assign need_match_store_data_t0_trigger = have_store_data_timing0 && store_addr_vld; +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + need_match_store_data_t0_trigger_f <= 1'b0; + else if(need_match_store_data_t0_trigger) + need_match_store_data_t0_trigger_f <= 1'b1; + else if(need_match_store_data_t0_trigger_f) + need_match_store_data_t0_trigger_f <= 1'b0; +end + +//match +// &CombBeg; @3616 +always @( mcontrol5_ldst_match + or mcontrol4_ldst_match + or m1_ldst_match + or need_match_store_data_t0_trigger_f + or m0_ldst_match + or lsu_dtu_last_check_f + or m6_ldst_match + or mcontrol6_ldst_match + or mcontrol1_ldst_match + or mcontrol3_ldst_match + or m5_ldst_match + or m3_ldst_match + or timing0_match[7:0] + or m4_ldst_match + or have_timing0_match + or m7_ldst_match + or mcontrol0_ldst_match + or m2_ldst_match + or mcontrol7_ldst_match + or mcontrol2_ldst_match) +begin +if(lsu_dtu_last_check_f) + ldst_match[7:0] = {m7_ldst_match,m6_ldst_match,m5_ldst_match,m4_ldst_match, + m3_ldst_match,m2_ldst_match,m1_ldst_match,m0_ldst_match}; +else if(have_timing0_match && !need_match_store_data_t0_trigger_f) + ldst_match[7:0] = timing0_match[7:0]; +else + ldst_match[7:0] = {mcontrol7_ldst_match,mcontrol6_ldst_match,mcontrol5_ldst_match,mcontrol4_ldst_match, + mcontrol3_ldst_match,mcontrol2_ldst_match,mcontrol1_ldst_match,mcontrol0_ldst_match}; +// &CombEnd; @3625 +end + +assign ldst_have_match = |ldst_after_chain_match[7:0]; + +//action0 +assign m0_ldst_action0 = m0_ldst_match && mcontrol0_action0; +assign m1_ldst_action0 = m1_ldst_match && mcontrol1_action0; +assign m2_ldst_action0 = m2_ldst_match && mcontrol2_action0; +assign m3_ldst_action0 = m3_ldst_match && mcontrol3_action0; +assign m4_ldst_action0 = m4_ldst_match && mcontrol4_action0; +assign m5_ldst_action0 = m5_ldst_match && mcontrol5_action0; +assign m6_ldst_action0 = m6_ldst_match && mcontrol6_action0; +assign m7_ldst_action0 = m7_ldst_match && mcontrol7_action0; +assign ldst_action0 = m7_ldst_action0 || m6_ldst_action0 || m5_ldst_action0 || m4_ldst_action0 || + m3_ldst_action0 || m2_ldst_action0 || m1_ldst_action0 || m0_ldst_action0; + +//action1 +assign m0_ldst_action1 = m0_ldst_match && mcontrol0_action1; +assign m1_ldst_action1 = m1_ldst_match && mcontrol1_action1; +assign m2_ldst_action1 = m2_ldst_match && mcontrol2_action1; +assign m3_ldst_action1 = m3_ldst_match && mcontrol3_action1; +assign m4_ldst_action1 = m4_ldst_match && mcontrol4_action1; +assign m5_ldst_action1 = m5_ldst_match && mcontrol5_action1; +assign m6_ldst_action1 = m6_ldst_match && mcontrol6_action1; +assign m7_ldst_action1 = m7_ldst_match && mcontrol7_action1; +assign ldst_action1 = m7_ldst_action1 || m6_ldst_action1 || m5_ldst_action1 || m4_ldst_action1 || + m3_ldst_action1 || m2_ldst_action1 || m1_ldst_action1 || m0_ldst_action1; + +assign ldst_action = !ldst_action0 && ldst_action1; +assign ldst_action01 = ldst_action0 && ldst_action1; + +//timing +assign m0_ldst_timing = m0_ldst_match && mcontrol0_timing; +assign m1_ldst_timing = m1_ldst_match && mcontrol1_timing; +assign m2_ldst_timing = m2_ldst_match && mcontrol2_timing; +assign m3_ldst_timing = m3_ldst_match && mcontrol3_timing; +assign m4_ldst_timing = m4_ldst_match && mcontrol4_timing; +assign m5_ldst_timing = m5_ldst_match && mcontrol5_timing; +assign m6_ldst_timing = m6_ldst_match && mcontrol6_timing; +assign m7_ldst_timing = m7_ldst_match && mcontrol7_timing; +assign ldst_timing = m7_ldst_timing || m6_ldst_timing || m5_ldst_timing || m4_ldst_timing || + m3_ldst_timing || m2_ldst_timing || m1_ldst_timing || m0_ldst_timing; + +//cancel +// &CombBeg; @3669 +always @( lsu_dtu_last_check_f + or need_match_store_data_t0_trigger_f + or ldst_have_match + or have_timing0_match + or ldst_timing) +begin +//assign ldst_cancel = !ldst_timing && ldst_have_match; +if(lsu_dtu_last_check_f) + ldst_cancel = !ldst_timing && ldst_have_match; +else if(have_timing0_match && !need_match_store_data_t0_trigger_f) + ldst_cancel = 1'b1; +else + ldst_cancel = 1'b0; +// &CombEnd; @3677 +end + +assign dtu_lsu_halt_info[`TDT_HINFO_WIDTH-1:0] = {ldst_match[`TDT_TM_MCONTROL_TRI_NUM-1:0],4'd2,1'b0, + ldst_timing,ldst_action01,ldst_action, + 1'b0,1'b1,ldst_have_match,ldst_cancel}; + + + +//========================================================== +// gate clk +//========================================================== +always @(posedge mcontrol_output_clk or negedge cpurst_b) +begin + if(!cpurst_b) + cp0_write_tdata1_f <= 1'b0; + else + cp0_write_tdata1_f <= cp0_write_tdata1; +end +// &Force("nonport","cp0_write_tdata1_f"); @3704 + + +assign mcontrol_output_clk_en = cp0_write_tdata1 || cp0_write_tdata1_f || + exe_may_hit || ldst_may_hit || + exe_cycle2_cannot_hit || ldst_cycle2_cannot_hit || + lsu_dtu_last_check || lsu_dtu_last_check_f || + need_match_store_data_t0_trigger || need_match_store_data_t0_trigger_f; +// &Force("nonport","mcontrol_output_clk_en"); @3712 + +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @3714 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mcontrol_output_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (mcontrol_output_clk_en), + .module_en (cp0_dtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @3715 +// .external_en (1'b0), @3716 +// .global_en (cp0_yy_clk_en), @3717 +// .module_en (cp0_dtu_icg_en), @3718 +// .local_en (mcontrol_output_clk_en), @3719 +// //.local_en (1'b1), @3720 +// .clk_out (mcontrol_output_clk)); @3721 + + + +// &ModuleEnd; @3740 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_pcfifo.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_pcfifo.v new file mode 100644 index 0000000000000000000000000000000000000000..ec52baa337aad557d6a30db3a5488bc98d2e8f13 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/dtu/rtl/pa_dtu_pcfifo.v @@ -0,0 +1,217 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_dtu_pcfifo( + cp0_dtu_addr, + cp0_dtu_icg_en, + cp0_dtu_pcfifo_frz, + cp0_dtu_rreg, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + latest_pc, + pad_yy_icg_scan_en, + pcfifo_regs_data, + rtu_dtu_halt_ack, + rtu_dtu_retire_chgflw, + rtu_dtu_retire_next_pc, + rtu_dtu_retire_vld +); + +// &Ports; @24 +input [11:0] cp0_dtu_addr; +input cp0_dtu_icg_en; +input cp0_dtu_pcfifo_frz; +input cp0_dtu_rreg; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input rtu_dtu_halt_ack; +input rtu_dtu_retire_chgflw; +input [31:0] rtu_dtu_retire_next_pc; +input rtu_dtu_retire_vld; +output [31:0] latest_pc; +output [31:0] pcfifo_regs_data; + +// &Regs; @25 +reg [2 :0] rptr; +reg [2 :0] wptr; + +// &Wires; @26 +wire [11:0] cp0_dtu_addr; +wire cp0_dtu_icg_en; +wire cp0_dtu_pcfifo_frz; +wire cp0_dtu_rreg; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_pcfifo_ren; +wire ctrl_pcfifo_wen; +wire forever_cpuclk; +wire [31:0] latest_pc; +wire [2 :0] latest_pc_ptr; +wire pad_yy_icg_scan_en; +wire pcfifo_clk; +wire pcfifo_clk_en; +wire [31:0] pcfifo_din; +wire [31:0] pcfifo_out; +wire [31:0] pcfifo_reg_latest_pc; +wire [31:0] pcfifo_reg_rptr_pc; +wire [31:0] pcfifo_regs_data; +wire read_first_pc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_retire_chgflw; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; + + +parameter DATAW = `TDT_DM_CORE_MAX_XLEN; + +parameter DEPTH = `TDT_PCFIFO_DEPTH; +parameter PTR_WIDTH = `TDT_PCFIFO_PTR_WIDTH; + +assign ctrl_pcfifo_wen = rtu_dtu_retire_vld && rtu_dtu_retire_chgflw && !cp0_dtu_pcfifo_frz; +assign ctrl_pcfifo_ren = cp0_dtu_rreg && cp0_dtu_addr[11:0] == 12'hfe2 && !cp0_dtu_pcfifo_frz; + +//========================================================== +// PCFIFO write +//========================================================== +// when a branch or jump inst retires in normal mode, +// the target pc will be pushed into pcfifo + +assign pcfifo_din[`PA_WIDTH-1:0] = rtu_dtu_retire_next_pc[`PA_WIDTH-1:0]; + +// //&Force("mem","pcfifo_reg",`PA_WIDTH-1,0,DEPTH-1,0); @44 +// //&Force("output","pcfifo_reg");&Force("bus","pcfifo_reg",`PA_WIDTH-1,0); @45 +//csky vperl_off +reg [`PA_WIDTH-1:0] pcfifo_reg [DEPTH-1:0]; + +integer i;//pcfifo entry number +always @(posedge pcfifo_clk or negedge cpurst_b) +begin + if (!cpurst_b) + begin + for (i=0; i 8'b11111110 +//UF : 1. input is not zero, and e < 381 + +// Dest is float +assign single_norm_f_all_1 = &ex2_frac[22:0]; +assign single_expnt_add = single_norm_f_all_1 && ex2_round_add; + +assign ex2_single_of = 1'b0; +assign ex2_single_uf = 1'b0; + +assign ex2_expt_of = ex2_single_of; +assign ex2_expt_uf = ex2_single_uf; +assign ex2_expt_nx_t = !ex2_x_zero; // including int nx + +assign ex2_expt_nv_f = 1'b0; + +// Dest is int +assign ex2_tosi_pos_exp_of = !ex2_expnt[8] && (ex2_expnt[7:0] > 8'd30); +assign ex2_tosi_neg_exp_of = !ex2_expnt[8] && (ex2_expnt[7:0] > 8'd31); +assign ex2_tosi_neg_exp_crit_of = ex2_expnt[8:0] == 9'd31; + +assign ex2_tosi_of = ex2_dest_si && !ex2_sign && (ex2_tosi_pos_exp_of || ex2_int_nm_result[31]); +assign ex2_tosi_uf = ex2_dest_si && ex2_sign && (ex2_tosi_neg_exp_of || ex2_tosi_neg_exp_crit_of && !ex2_int_nm_result[31]); + + +assign ex2_toui_exp_of = !ex2_expnt[8] && (ex2_expnt[7:0] > 8'd31); +assign ex2_toui_of = !ex2_dest_si && !ex2_sign && (ex2_toui_exp_of || ex2_uint_nm_result[32]); +assign ex2_toui_uf = !ex2_dest_si && ex2_sign && (!ex2_expnt[8] || ex2_round_add); + +assign ex2_expt_nv_i = ex2_tosi_of || ex2_tosi_uf || + ex2_toui_of || ex2_toui_uf; +assign ex2_expt_nv = !ex2_dest_float && ex2_expt_nv_i || ex2_expt_nv_f; + +// Finally, NX expt, here nx_t include uf +assign ex2_expt_nx = !ex2_expt_nv && (ex2_expt_of || ex2_expt_nx_t); +assign ex2_expt[3:0] = ex2_special_vld ? {ex2_special_nv,3'b0} + : {ex2_expt_nv, ex2_expt_of, ex2_expt_uf, ex2_expt_nx}; + + +//------------------------------------------------------------------------------ +// EX2 special result: +//------------------------------------------------------------------------------ +assign ex2_single_result[31:0] = ex2_src_is_0 ? 32'b0 : ex2_single_norm_result[31:0]; + + +//------------------------------------------------------------------------------ +// EX2 Merge final results: +//------------------------------------------------------------------------------ +assign ex2_float_result[31:0] = ex2_single_result[31:0]; +//int result +assign int_dest_max_si = ex2_dest_si && (ex2_tosi_of); +assign int_dest_min_si = ex2_dest_si && ex2_tosi_uf; + +assign ex2_si_result[31:0] = int_dest_max_si ? {1'b0,{31{1'b1}}} : + int_dest_min_si ? {1'b1,31'b0} + : ex2_int_nm_result[31:0]; + +assign int_dest_max_ui = !ex2_dest_si && (ex2_toui_of); +assign ex2_ui_result[31:0] = int_dest_max_ui ? {32{1'b1}} : + ex2_toui_uf ? {32{1'b0}} + : ex2_uint_nm_result[31:0]; +assign ex2_int_result[31:0] = ex2_special_vld ? ex2_int_r[31:0] : + ex2_dest_si ? ex2_si_result[31:0] + : ex2_ui_result[31:0]; + +assign ex2_dest_sel_float = ex2_dest_float ; +assign ex2_total_result[31:0] = ex2_dest_sel_float + & ~ex2_special_vld ? ex2_float_result[31:0] + : ex2_int_result[31:0]; + + +//------------------------------------------------------------------------------ +// EX2 pipedown to EX3: +//------------------------------------------------------------------------------ +always @(posedge fcnvt_ex2_pipe_clk) +begin + if(fcnvt_ex2_pipedown) + begin + ex3_expt[3:0] <= ex2_expt[3:0]; + ex3_result[31:0] <= ex2_total_result[31:0]; + ex3_dest_float <= ex2_dest_float; + ex3_special_vld <= ex2_special_vld; + ex3_fspu_vld <= ex2_fspu_vld; + end +end + + +assign fcnvt_ex3_result[31:0] = ex3_result[31:0]; +assign fcnvt_ex3_expt[4:0] = {ex3_expt[3], 1'b0, ex3_expt[2:0]}; + + +//------------------------------------------------------------------------------ +// EX3 float result rename for output: +//------------------------------------------------------------------------------ +assign fcnvt_ex3_dp_fflags[4:0] = fcnvt_ex3_expt[4:0]; +assign fcnvt_ex3_dp_rst[31:0] = fcnvt_ex3_result[31:0]; +assign fcnvt_ex3_dp_wb_vld = ex3_dest_float && ~ex3_special_vld && fcnvt_ex3_sel && falu_ctrl_xx_ex3_vld; +assign fcnvt_ex3_fspu_vld = ex3_fspu_vld; +//------------------------------------------------------------------------------ +// EX3 int result rename for output: +//------------------------------------------------------------------------------ +assign fcnvt_ex3_rtu_fflags[4:0] = fcnvt_ex3_expt[4:0]; +assign fcnvt_ex3_rtu_rst[31:0] = fcnvt_ex3_result[31:0]; +assign fcnvt_ex3_rtu_wb_vld = (!ex3_dest_float & ~ex3_special_vld | ex3_special_vld) && fcnvt_ex3_sel && falu_ctrl_xx_ex3_vld; + + + +// &ModuleEnd; @483 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/falu/rtl/pa_fspu_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/falu/rtl/pa_fspu_single.v new file mode 100644 index 0000000000000000000000000000000000000000..73d00df7c0e8885dccef04d8d8af1b292c952d88 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/falu/rtl/pa_fspu_single.v @@ -0,0 +1,234 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fspu_single( + dp_xx_ex1_id, + dp_xx_ex1_inf, + dp_xx_ex1_norm, + dp_xx_ex1_qnan, + dp_xx_ex1_snan, + dp_xx_ex1_zero, + falu_ctrl_xx_ex1_vld, + fspu_ex1_dp_fflags, + fspu_ex1_dp_special_result, + fspu_ex1_dp_special_sel, + fspu_ex1_dp_special_sign, + fspu_ex1_dp_wb_vld, + fspu_ex1_rtu_rst, + fspu_ex1_rtu_wb_vld, + fspu_ex1_rtu_wb_vld_gate, + fspu_sel, + fspu_sel_dp, + fspu_sel_gate, + idu_fpu_ex1_func, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + idu_fpu_ex1_srci +); + +// &Ports; @24 +input [2 :0] dp_xx_ex1_id; +input [2 :0] dp_xx_ex1_inf; +input [2 :0] dp_xx_ex1_norm; +input [2 :0] dp_xx_ex1_qnan; +input [2 :0] dp_xx_ex1_snan; +input [2 :0] dp_xx_ex1_zero; +input falu_ctrl_xx_ex1_vld; +input fspu_sel; +input fspu_sel_dp; +input fspu_sel_gate; +input [9 :0] idu_fpu_ex1_func; +input [31:0] idu_fpu_ex1_srcf0; +input [31:0] idu_fpu_ex1_srcf1; +input [31:0] idu_fpu_ex1_srci; +output [4 :0] fspu_ex1_dp_fflags; +output [31:0] fspu_ex1_dp_special_result; +output [7 :0] fspu_ex1_dp_special_sel; +output [2 :0] fspu_ex1_dp_special_sign; +output fspu_ex1_dp_wb_vld; +output [31:0] fspu_ex1_rtu_rst; +output fspu_ex1_rtu_wb_vld; +output fspu_ex1_rtu_wb_vld_gate; + +// &Regs; @25 + +// &Wires; @26 +wire [2 :0] dp_xx_ex1_id; +wire [2 :0] dp_xx_ex1_inf; +wire [2 :0] dp_xx_ex1_norm; +wire [2 :0] dp_xx_ex1_qnan; +wire [2 :0] dp_xx_ex1_snan; +wire [2 :0] dp_xx_ex1_zero; +wire [31:0] ex1_class_r; +wire ex1_dest_f; +wire ex1_dest_i; +wire [31:0] ex1_f_rst; +wire [31:0] ex1_fmvwx_r; +wire [31:0] ex1_fmvxw_r; +wire [31:0] ex1_fsgnj_r; +wire [31:0] ex1_fsgnjn_r; +wire [31:0] ex1_fsgnjx_r; +wire [31:0] ex1_i_rst; +wire [31:0] ex1_int_src; +wire [31:0] ex1_op0_single; +wire [31:0] ex1_op1_single; +wire ex1_op_class; +wire ex1_op_fmvwx; +wire ex1_op_fmvxw; +wire ex1_op_fsgnj; +wire ex1_op_fsgnjn; +wire ex1_op_fsgnjx; +wire [31:0] ex1_src0; +wire ex1_src0_dn; +wire ex1_src0_inf; +wire ex1_src0_norm; +wire ex1_src0_qnan; +wire ex1_src0_sign; +wire ex1_src0_snan; +wire ex1_src0_zero; +wire [31:0] ex1_src1; +wire ex1_src1_sign; +wire falu_ctrl_xx_ex1_vld; +wire [4 :0] fspu_ex1_dp_fflags; +wire [31:0] fspu_ex1_dp_special_result; +wire [7 :0] fspu_ex1_dp_special_sel; +wire [2 :0] fspu_ex1_dp_special_sign; +wire fspu_ex1_dp_wb_vld; +wire [31:0] fspu_ex1_rtu_rst; +wire fspu_ex1_rtu_wb_vld; +wire fspu_ex1_rtu_wb_vld_gate; +wire fspu_sel; +wire fspu_sel_dp; +wire fspu_sel_gate; +wire [9 :0] idu_fpu_ex1_func; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire [31:0] idu_fpu_ex1_srci; + + +// &Force("bus", "dp_xx_ex1_snan", 2, 0); @28 +// &Force("bus", "dp_xx_ex1_qnan", 2, 0); @29 +// &Force("bus", "dp_xx_ex1_norm", 2, 0); @30 +// &Force("bus", "dp_xx_ex1_zero", 2, 0); @31 +// &Force("bus", "dp_xx_ex1_inf", 2, 0); @32 +// &Force("bus", "dp_xx_ex1_id", 2, 0); @33 +// &Force("bus", "idu_fpu_ex1_func", 9, 0); @34 + + +//------------------------------------------------------------------------------ +// Interface with idu and fpu: +//------------------------------------------------------------------------------ +assign ex1_src0[31:0] = {32{fspu_sel_dp}} & idu_fpu_ex1_srcf0[31:0]; +assign ex1_src1[31:0] = {32{fspu_sel_dp}} & idu_fpu_ex1_srcf1[31:0]; +assign ex1_int_src[31:0] = idu_fpu_ex1_srci[31:0]; +//assign fspu_sel = ctrl_falu_ex1_sel && idu_fpu_ex1_func[2]; +//assign fspu_ex1_sel = fspu_sel; +assign ex1_op_fsgnjx = idu_fpu_ex1_func[6] && idu_fpu_ex1_func[4]; +assign ex1_op_fsgnjn = idu_fpu_ex1_func[6] && !idu_fpu_ex1_func[3] && !idu_fpu_ex1_func[4]; +assign ex1_op_fsgnj = idu_fpu_ex1_func[6] && idu_fpu_ex1_func[3]; +assign ex1_op_fmvwx = idu_fpu_ex1_func[7] && idu_fpu_ex1_func[3]; +assign ex1_op_fmvxw = idu_fpu_ex1_func[5] && idu_fpu_ex1_func[3]; +assign ex1_op_class = idu_fpu_ex1_func[5] && idu_fpu_ex1_func[4]; +assign ex1_dest_f = idu_fpu_ex1_func[6] || idu_fpu_ex1_func[7] && !idu_fpu_ex1_func[4]; +assign ex1_dest_i = idu_fpu_ex1_func[5] || idu_fpu_ex1_func[7] && idu_fpu_ex1_func[4]; + +assign ex1_src0_snan = dp_xx_ex1_snan[0]; +assign ex1_src0_qnan = dp_xx_ex1_qnan[0]; +assign ex1_src0_norm = dp_xx_ex1_norm[0]; +assign ex1_src0_zero = dp_xx_ex1_zero[0]; +assign ex1_src0_inf = dp_xx_ex1_inf[0]; +assign ex1_src0_dn = dp_xx_ex1_id[0]; +assign ex1_src0_sign = ex1_op0_single[31]; +assign ex1_src1_sign = ex1_op1_single[31]; + +assign ex1_op0_single[31:0] = ex1_src0[31:0]; +assign ex1_op1_single[31:0] = ex1_src1[31:0]; + + +//------------------------------------------------------------------------------ +// FCLASS Instruction: +//------------------------------------------------------------------------------ +//class: r[9:0] = {qnan, snan, +inf, +nm, +dn, +0, -0, -dn, -nm, -inf} +assign ex1_class_r[31:0] = { + 22'b0, + ex1_src0_qnan, + ex1_src0_snan, + !ex1_src0_sign && ex1_src0_inf, + !ex1_src0_sign && ex1_src0_norm && !ex1_src0_dn, + !ex1_src0_sign && ex1_src0_dn, + !ex1_src0_sign && ex1_src0_zero, + ex1_src0_sign && ex1_src0_zero, + ex1_src0_sign && ex1_src0_dn, + ex1_src0_sign && ex1_src0_norm && !ex1_src0_dn, + ex1_src0_sign && ex1_src0_inf}; + + +//------------------------------------------------------------------------------ +// FSGNJ Instruction: +//------------------------------------------------------------------------------ +//fsgnjx : r_s = s0_s ^ s1_s +//fsgnjn : r_s = ~s1_s +//fsgnj : r_s = s1_s +assign ex1_fsgnjx_r[31:0] = {ex1_src0_sign ^ ex1_src1_sign, ex1_op0_single[30:0]}; +assign ex1_fsgnjn_r[31:0] = {~ex1_src1_sign, ex1_op0_single[30:0]}; +assign ex1_fsgnj_r[31:0] = {ex1_src1_sign, ex1_op0_single[30:0]}; + + +//------------------------------------------------------------------------------ +// FMV Instruction: +//------------------------------------------------------------------------------ +//fmv.x.w : mov low 32bits float to int regsiter +//fmv.w.x : mov from int register to low 32bit float regsiter +assign ex1_fmvwx_r[31:0] = ex1_int_src[31:0]; +assign ex1_fmvxw_r[31:0] = ex1_src0[31:0]; + + +//------------------------------------------------------------------------------ +// Merge float and int result: +//------------------------------------------------------------------------------ +assign ex1_f_rst[31:0] = {32{ex1_op_fsgnjx}} & ex1_fsgnjx_r[31:0] | + {32{ex1_op_fsgnjn}} & ex1_fsgnjn_r[31:0] | + {32{ex1_op_fsgnj}} & ex1_fsgnj_r[31:0] | + {32{ex1_op_fmvwx}} & ex1_fmvwx_r[31:0]; +assign ex1_i_rst[31:0] = {32{ex1_op_fmvxw}} & ex1_fmvxw_r[31:0] | + {32{ex1_op_class}} & ex1_class_r[31:0]; + + +//------------------------------------------------------------------------------ +// Float result rename for output: +//------------------------------------------------------------------------------ +assign fspu_ex1_dp_wb_vld = fspu_sel && ex1_dest_f && falu_ctrl_xx_ex1_vld; +assign fspu_ex1_dp_special_sel[7:0] = {1'b1, 7'b0}; +assign fspu_ex1_dp_fflags[4:0] = 5'b0; + + +//------------------------------------------------------------------------------ +// Int result rename for output: +//------------------------------------------------------------------------------ +assign fspu_ex1_rtu_wb_vld = fspu_sel && ex1_dest_i && falu_ctrl_xx_ex1_vld; +assign fspu_ex1_rtu_wb_vld_gate = fspu_sel_gate && ex1_dest_i && falu_ctrl_xx_ex1_vld; + +assign fspu_ex1_rtu_rst[31:0] = ex1_i_rst[31:0]; +//assign fspu_ex1_rtu_fflags[4:0] = 5'b0; +assign fspu_ex1_dp_special_sign[2:0] = 3'b0; +assign fspu_ex1_dp_special_result[31:0] = ex1_f_rst[31:0]; + + + +// &ModuleEnd; @137 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..ce08eda94ab003cd7f8dcb42ce493372990b4ff5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ctrl.v @@ -0,0 +1,783 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_ctrl( + cp0_fpu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_fdsu_ex1_sel, + ctrl_xx_ex1_cmplt_dp, + ctrl_xx_ex1_inst_vld, + ctrl_xx_ex1_stall, + ctrl_xx_ex1_warm_up, + ctrl_xx_ex2_warm_up, + ctrl_xx_ex3_warm_up, + ex1_div, + ex1_expnt_adder_op0, + ex1_of_result_lfn, + ex1_op0_id, + ex1_op0_norm, + ex1_op1_id_vld, + ex1_op1_norm, + ex1_op1_sel, + ex1_oper_id_expnt, + ex1_oper_id_expnt_f, + ex1_pipedown, + ex1_pipedown_gate, + ex1_result_sign, + ex1_rm, + ex1_save_op0, + ex1_save_op0_gate, + ex1_sqrt, + ex1_srt_skip, + ex2_expnt_adder_op0, + ex2_of, + ex2_pipe_clk, + ex2_pipedown, + ex2_potnt_of, + ex2_potnt_uf, + ex2_result_inf, + ex2_result_lfn, + ex2_rslt_denorm, + ex2_srt_expnt_rst, + ex2_srt_first_round, + ex2_uf, + ex2_uf_srt_skip, + ex3_expnt_adjust_result, + ex3_pipedown, + ex3_rslt_denorm, + fdsu_ex1_sel, + fdsu_fpu_debug_info, + fdsu_fpu_ex1_cmplt, + fdsu_fpu_ex1_cmplt_dp, + fdsu_fpu_ex1_stall, + fdsu_fpu_no_op, + fdsu_frbus_wb_vld, + fdsu_yy_div, + fdsu_yy_expnt_rst, + fdsu_yy_of, + fdsu_yy_of_rm_lfn, + fdsu_yy_op0_norm, + fdsu_yy_op1_norm, + fdsu_yy_potnt_of, + fdsu_yy_potnt_uf, + fdsu_yy_result_inf, + fdsu_yy_result_lfn, + fdsu_yy_result_sign, + fdsu_yy_rm, + fdsu_yy_rslt_denorm, + fdsu_yy_sqrt, + fdsu_yy_uf, + fdsu_yy_wb_freg, + forever_cpuclk, + frbus_fdsu_wb_grant, + idu_fpu_ex1_dst_freg, + idu_fpu_ex1_eu_sel, + pad_yy_icg_scan_en, + rtu_xx_ex1_cancel, + rtu_xx_ex2_cancel, + rtu_yy_xx_async_flush, + rtu_yy_xx_flush, + srt_remainder_zero, + srt_sm_on +); + +// &Ports; @24 +input cp0_fpu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_fdsu_ex1_sel; +input ctrl_xx_ex1_cmplt_dp; +input ctrl_xx_ex1_inst_vld; +input ctrl_xx_ex1_stall; +input ctrl_xx_ex1_warm_up; +input ctrl_xx_ex2_warm_up; +input ctrl_xx_ex3_warm_up; +input ex1_div; +input [12:0] ex1_expnt_adder_op0; +input ex1_of_result_lfn; +input ex1_op0_id; +input ex1_op0_norm; +input ex1_op1_id_vld; +input ex1_op1_norm; +input [12:0] ex1_oper_id_expnt; +input ex1_result_sign; +input [2 :0] ex1_rm; +input ex1_sqrt; +input ex1_srt_skip; +input ex2_of; +input ex2_potnt_of; +input ex2_potnt_uf; +input ex2_result_inf; +input ex2_result_lfn; +input ex2_rslt_denorm; +input [9 :0] ex2_srt_expnt_rst; +input ex2_uf; +input ex2_uf_srt_skip; +input [9 :0] ex3_expnt_adjust_result; +input ex3_rslt_denorm; +input forever_cpuclk; +input frbus_fdsu_wb_grant; +input [4 :0] idu_fpu_ex1_dst_freg; +input [2 :0] idu_fpu_ex1_eu_sel; +input pad_yy_icg_scan_en; +input rtu_xx_ex1_cancel; +input rtu_xx_ex2_cancel; +input rtu_yy_xx_async_flush; +input rtu_yy_xx_flush; +input srt_remainder_zero; +output ex1_op1_sel; +output [12:0] ex1_oper_id_expnt_f; +output ex1_pipedown; +output ex1_pipedown_gate; +output ex1_save_op0; +output ex1_save_op0_gate; +output [9 :0] ex2_expnt_adder_op0; +output ex2_pipe_clk; +output ex2_pipedown; +output ex2_srt_first_round; +output ex3_pipedown; +output fdsu_ex1_sel; +output [4 :0] fdsu_fpu_debug_info; +output fdsu_fpu_ex1_cmplt; +output fdsu_fpu_ex1_cmplt_dp; +output fdsu_fpu_ex1_stall; +output fdsu_fpu_no_op; +output fdsu_frbus_wb_vld; +output fdsu_yy_div; +output [9 :0] fdsu_yy_expnt_rst; +output fdsu_yy_of; +output fdsu_yy_of_rm_lfn; +output fdsu_yy_op0_norm; +output fdsu_yy_op1_norm; +output fdsu_yy_potnt_of; +output fdsu_yy_potnt_uf; +output fdsu_yy_result_inf; +output fdsu_yy_result_lfn; +output fdsu_yy_result_sign; +output [2 :0] fdsu_yy_rm; +output fdsu_yy_rslt_denorm; +output fdsu_yy_sqrt; +output fdsu_yy_uf; +output [4 :0] fdsu_yy_wb_freg; +output srt_sm_on; + +// &Regs; @25 +reg ex2_srt_first_round; +reg [2 :0] fdsu_cur_state; +reg fdsu_div; +reg [9 :0] fdsu_expnt_rst; +reg [2 :0] fdsu_next_state; +reg fdsu_of; +reg fdsu_of_rm_lfn; +reg fdsu_potnt_of; +reg fdsu_potnt_uf; +reg fdsu_result_inf; +reg fdsu_result_lfn; +reg fdsu_result_sign; +reg [2 :0] fdsu_rm; +reg fdsu_sqrt; +reg fdsu_uf; +reg [4 :0] fdsu_wb_freg; +reg fdsu_yy_rslt_denorm; +reg [4 :0] srt_cnt; +reg [1 :0] wb_cur_state; +reg [1 :0] wb_nxt_state; + +// &Wires; @26 +wire cp0_fpu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_fdsu_ex1_sel; +wire ctrl_fdsu_ex1_stall; +wire ctrl_fdsu_wb_vld; +wire ctrl_iter_start; +wire ctrl_iter_start_gate; +wire ctrl_pack; +wire ctrl_result_vld; +wire ctrl_round; +wire ctrl_sm_cmplt; +wire ctrl_sm_ex1; +wire ctrl_sm_idle; +wire ctrl_sm_start; +wire ctrl_sm_start_gate; +wire ctrl_srt_idle; +wire ctrl_srt_itering; +wire ctrl_wb_idle; +wire ctrl_wb_sm_cmplt; +wire ctrl_wb_sm_ex2; +wire ctrl_wb_sm_idle; +wire ctrl_wfi2; +wire ctrl_wfwb; +wire ctrl_xx_ex1_cmplt_dp; +wire ctrl_xx_ex1_inst_vld; +wire ctrl_xx_ex1_stall; +wire ctrl_xx_ex1_warm_up; +wire ctrl_xx_ex2_warm_up; +wire ctrl_xx_ex3_warm_up; +wire ex1_div; +wire [12:0] ex1_expnt_adder_op0; +wire ex1_of_result_lfn; +wire ex1_op0_id; +wire ex1_op1_id_vld; +wire ex1_op1_sel; +wire [12:0] ex1_oper_id_expnt; +wire [12:0] ex1_oper_id_expnt_f; +wire ex1_pipe_clk; +wire ex1_pipe_clk_en; +wire ex1_pipedown; +wire ex1_pipedown_gate; +wire ex1_result_sign; +wire [2 :0] ex1_rm; +wire ex1_save_op0; +wire ex1_save_op0_gate; +wire ex1_sqrt; +wire ex1_srt_skip; +wire [4 :0] ex1_wb_freg; +wire [9 :0] ex2_expnt_adder_op0; +wire ex2_of; +wire ex2_pipe_clk; +wire ex2_pipe_clk_en; +wire ex2_pipedown; +wire ex2_potnt_of; +wire ex2_potnt_uf; +wire ex2_result_inf; +wire ex2_result_lfn; +wire ex2_rslt_denorm; +wire [9 :0] ex2_srt_expnt_rst; +wire ex2_uf; +wire ex2_uf_srt_skip; +wire [9 :0] ex3_expnt_adjust_result; +wire ex3_pipedown; +wire ex3_rslt_denorm; +wire expnt_rst_clk; +wire expnt_rst_clk_en; +wire fdsu_busy; +wire fdsu_clk; +wire fdsu_clk_en; +wire fdsu_dn_stall; +wire fdsu_ex1_inst_vld; +wire fdsu_ex1_res_vld; +wire fdsu_ex1_sel; +wire fdsu_flush; +wire [4 :0] fdsu_fpu_debug_info; +wire fdsu_fpu_ex1_cmplt; +wire fdsu_fpu_ex1_cmplt_dp; +wire fdsu_fpu_ex1_stall; +wire fdsu_fpu_no_op; +wire fdsu_frbus_wb_vld; +wire fdsu_op0_norm; +wire fdsu_op1_norm; +wire fdsu_wb_grant; +wire fdsu_yy_div; +wire [9 :0] fdsu_yy_expnt_rst; +wire fdsu_yy_of; +wire fdsu_yy_of_rm_lfn; +wire fdsu_yy_op0_norm; +wire fdsu_yy_op1_norm; +wire fdsu_yy_potnt_of; +wire fdsu_yy_potnt_uf; +wire fdsu_yy_result_inf; +wire fdsu_yy_result_lfn; +wire fdsu_yy_result_sign; +wire [2 :0] fdsu_yy_rm; +wire fdsu_yy_sqrt; +wire fdsu_yy_uf; +wire [4 :0] fdsu_yy_wb_freg; +wire forever_cpuclk; +wire frbus_fdsu_wb_grant; +wire [4 :0] idu_fpu_ex1_dst_freg; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire pad_yy_icg_scan_en; +wire rtu_xx_ex1_cancel; +wire rtu_xx_ex2_cancel; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_flush; +wire [4 :0] srt_cnt_ini; +wire srt_cnt_zero; +wire srt_last_round; +wire srt_remainder_zero; +wire srt_skip; +wire srt_sm_on; + + +//========================================================== +// Input Signal +//========================================================== +assign ex1_wb_freg[4:0] = idu_fpu_ex1_dst_freg[4:0]; +assign fdsu_ex1_inst_vld = ctrl_xx_ex1_inst_vld && ctrl_fdsu_ex1_sel; +assign fdsu_ex1_sel = idu_fpu_ex1_eu_sel[2]; +// &Force("input", "idu_fpu_ex1_eu_sel"); &Force("bus", "idu_fpu_ex1_eu_sel", 2, 0); @34 + +//========================================================== +// FDSU Main State Machine +//========================================================== +assign fdsu_ex1_res_vld = fdsu_ex1_inst_vld && ex1_srt_skip; +assign fdsu_wb_grant = frbus_fdsu_wb_grant; + +assign ctrl_iter_start = ctrl_sm_start && !fdsu_dn_stall + || ctrl_wfi2; +assign ctrl_iter_start_gate = ctrl_sm_start_gate && !fdsu_dn_stall + || ctrl_wfi2; +assign ctrl_sm_start = fdsu_ex1_inst_vld && ctrl_srt_idle + && !ex1_srt_skip; +assign ctrl_sm_start_gate = fdsu_ex1_inst_vld && ctrl_srt_idle; + +assign srt_last_round = (srt_skip || + srt_remainder_zero || + srt_cnt_zero) && + ctrl_srt_itering; +assign srt_skip = ex2_of || + ex2_uf_srt_skip; +assign srt_cnt_zero = ~|srt_cnt[4:0]; +assign fdsu_dn_stall = ctrl_sm_start && ex1_op1_id_vld; + +parameter IDLE = 3'b000; +parameter WFI2 = 3'b001; +parameter ITER = 3'b010; +parameter RND = 3'b011; +parameter PACK = 3'b100; +parameter WFWB = 3'b101; + +always @ (posedge fdsu_clk or negedge cpurst_b) +begin + if (!cpurst_b) + fdsu_cur_state[2:0] <= IDLE; + else if (fdsu_flush) + fdsu_cur_state[2:0] <= IDLE; + else + fdsu_cur_state[2:0] <= fdsu_next_state[2:0]; +end + +// &CombBeg; @76 +always @( ctrl_sm_start + or fdsu_dn_stall + or srt_last_round + or fdsu_cur_state[2:0] + or fdsu_wb_grant) +begin +case (fdsu_cur_state[2:0]) + IDLE: + begin + if (ctrl_sm_start) + if (fdsu_dn_stall) + fdsu_next_state[2:0] = WFI2; + else + fdsu_next_state[2:0] = ITER; + else + fdsu_next_state[2:0] = IDLE; + end + WFI2: + fdsu_next_state[2:0] = ITER; + ITER: + begin + if (srt_last_round) + fdsu_next_state[2:0] = RND; + else + fdsu_next_state[2:0] = ITER; + end + RND: + fdsu_next_state[2:0] = PACK; + PACK: + begin + if (fdsu_wb_grant) + if (ctrl_sm_start) + if (fdsu_dn_stall) + fdsu_next_state[2:0] = WFI2; + else + fdsu_next_state[2:0] = ITER; + else + fdsu_next_state[2:0] = IDLE; + else + fdsu_next_state[2:0] = WFWB; + end + WFWB: + begin + if (fdsu_wb_grant) + if (ctrl_sm_start) + if (fdsu_dn_stall) + fdsu_next_state[2:0] = WFI2; + else + fdsu_next_state[2:0] = ITER; + else + fdsu_next_state[2:0] = IDLE; + else + fdsu_next_state[2:0] = WFWB; + end + default: + fdsu_next_state[2:0] = IDLE; +endcase +// &CombEnd; @128 +end + +assign ctrl_sm_idle = fdsu_cur_state[2:0] == IDLE; +assign ctrl_wfi2 = fdsu_cur_state[2:0] == WFI2; +assign ctrl_srt_itering = fdsu_cur_state[2:0] == ITER; +assign ctrl_round = fdsu_cur_state[2:0] == RND; +assign ctrl_pack = fdsu_cur_state[2:0] == PACK; +assign ctrl_wfwb = fdsu_cur_state[2:0] == WFWB; + +assign ctrl_sm_cmplt = ctrl_pack || ctrl_wfwb; +assign ctrl_srt_idle = ctrl_sm_idle + || fdsu_wb_grant; +assign ctrl_sm_ex1 = ctrl_srt_idle || ctrl_wfi2; + +//========================================================== +// Iteration Counter +//========================================================== +always @ (posedge fdsu_clk) +begin + if (fdsu_flush) + srt_cnt[4:0] <= 5'b0; + else if (ctrl_iter_start) + srt_cnt[4:0] <= srt_cnt_ini[4:0]; + else if (ctrl_srt_itering) + srt_cnt[4:0] <= srt_cnt[4:0] - 5'b1; + else + srt_cnt[4:0] <= srt_cnt[4:0]; +end + +//srt_cnt_ini[4:0] +//For Double, initial is 5'b11100('d28), calculate 29 round +//For Single, initial is 5'b01110('d14), calculate 15 round +assign srt_cnt_ini[4:0] = 5'b01110; + +//fdsu srt first round signal +//For srt calculate special use +always @(posedge fdsu_clk or negedge cpurst_b) +begin + if(!cpurst_b) + ex2_srt_first_round <= 1'b0; + else if(fdsu_flush) + ex2_srt_first_round <= 1'b0; + else if(ex1_pipedown) + ex2_srt_first_round <= 1'b1; + else + ex2_srt_first_round <= 1'b0; +end + +//========================================================== +// Write Back State Machine +//========================================================== +parameter WB_IDLE = 2'b00, + WB_EX2 = 2'b10, + WB_CMPLT = 2'b01; + +always @ (posedge fdsu_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_cur_state[1:0] <= WB_IDLE; + else if (fdsu_flush) + wb_cur_state[1:0] <= WB_IDLE; + else + wb_cur_state[1:0] <= wb_nxt_state[1:0]; +end + +// &CombBeg; @215 +always @( ctrl_fdsu_wb_vld + or fdsu_dn_stall + or ctrl_xx_ex1_stall + or fdsu_ex1_inst_vld + or ctrl_iter_start + or fdsu_ex1_res_vld + or wb_cur_state[1:0]) +begin + case(wb_cur_state[1:0]) + WB_IDLE: + if (fdsu_ex1_inst_vld) + if (ctrl_xx_ex1_stall || fdsu_ex1_res_vld || fdsu_dn_stall) + wb_nxt_state[1:0] = WB_IDLE; + else + wb_nxt_state[1:0] = WB_EX2; + else + wb_nxt_state[1:0] = WB_IDLE; + WB_EX2: + // if (ctrl_xx_ex2_stall) + // wb_nxt_state[1:0] = WB_EX2; + // else + if (ctrl_fdsu_wb_vld) + if (ctrl_iter_start && !ctrl_xx_ex1_stall) + wb_nxt_state[1:0] = WB_EX2; + else + wb_nxt_state[1:0] = WB_IDLE; + else + wb_nxt_state[1:0] = WB_CMPLT; + WB_CMPLT: + if (ctrl_fdsu_wb_vld) + if (ctrl_iter_start && !ctrl_xx_ex1_stall) + wb_nxt_state[1:0] = WB_EX2; + else + wb_nxt_state[1:0] = WB_IDLE; + else + wb_nxt_state[1:0] = WB_CMPLT; + default: + wb_nxt_state[1:0] = WB_IDLE; + endcase +// &CombEnd; @247 +end + +assign ctrl_wb_idle = wb_cur_state[1:0] == WB_IDLE + || wb_cur_state[1:0] == WB_CMPLT && ctrl_fdsu_wb_vld; +assign ctrl_wb_sm_idle = wb_cur_state[1:0] == WB_IDLE; +assign ctrl_wb_sm_ex2 = wb_cur_state[1:0] == WB_EX2; +assign ctrl_wb_sm_cmplt = wb_cur_state[1:0] == WB_EX2 + || wb_cur_state[1:0] == WB_CMPLT; + +assign ctrl_result_vld = ctrl_sm_cmplt && ctrl_wb_sm_cmplt; +assign ctrl_fdsu_wb_vld = ctrl_result_vld && frbus_fdsu_wb_grant; + +assign ctrl_fdsu_ex1_stall = fdsu_ex1_inst_vld && !ctrl_sm_ex1 && !ctrl_wb_idle + || fdsu_ex1_inst_vld && fdsu_dn_stall; + +//========================================================== +// Flops +//========================================================== +always @(posedge ex1_pipe_clk) +begin + if(ex1_pipedown) + begin + fdsu_wb_freg[4:0] <= ex1_wb_freg[4:0]; + fdsu_result_sign <= ex1_result_sign; + fdsu_of_rm_lfn <= ex1_of_result_lfn; + fdsu_div <= ex1_div; + fdsu_sqrt <= ex1_sqrt; + fdsu_rm[2:0] <= ex1_rm[2:0]; + end + else + begin + fdsu_wb_freg[4:0] <= fdsu_wb_freg[4:0]; + fdsu_result_sign <= fdsu_result_sign; + fdsu_of_rm_lfn <= fdsu_of_rm_lfn; + fdsu_div <= fdsu_div; + fdsu_sqrt <= fdsu_sqrt; + fdsu_rm[2:0] <= fdsu_rm[2:0]; + end +end + +// In 906 FDSU, if one op0/1 is not norm, it will not enter EX2. +assign fdsu_op0_norm = 1'b1; +assign fdsu_op1_norm = 1'b1; +// &Force("input", "ex1_op0_norm"); @337 +// &Force("input", "ex1_op1_norm"); @338 + +// fdsu_expnt_rst is used to save: +// 1. op0 denormal expnt; +// 2. op0 expnt; +// 3. result expnt. +// &Force("bus", "ex1_oper_id_expnt", 12, 0); @378 +// &Force("bus", "ex1_expnt_adder_op0", 12, 0); @379 + + +always @ (posedge expnt_rst_clk) +begin + if (ex1_save_op0) + fdsu_expnt_rst[9:0] <= ex1_oper_id_expnt[9:0]; + else if (ex1_pipedown) + fdsu_expnt_rst[9:0] <= ex1_expnt_adder_op0[9:0]; + else if (ex2_pipedown) + fdsu_expnt_rst[9:0] <= ex2_srt_expnt_rst[9:0]; + else if (ex3_pipedown) + fdsu_expnt_rst[9:0] <= ex3_expnt_adjust_result[9:0]; + else + fdsu_expnt_rst[9:0] <= fdsu_expnt_rst[9:0]; +end + +assign ex1_oper_id_expnt_f[12:0] = {3'b1, fdsu_expnt_rst[9:0]}; + +always @ (posedge expnt_rst_clk) +begin + if (ex2_pipedown) + fdsu_yy_rslt_denorm <= ex2_rslt_denorm; + else if (ex3_pipedown) + fdsu_yy_rslt_denorm <= ex3_rslt_denorm; + else + fdsu_yy_rslt_denorm <= fdsu_yy_rslt_denorm; +end +// &Force("output", "fdsu_yy_rslt_denorm"); @440 + +// EX2 signal used in EX3 & EX4 +always @ (posedge ex2_pipe_clk) +begin + if (ex2_pipedown) + begin + fdsu_result_inf <= ex2_result_inf; + fdsu_result_lfn <= ex2_result_lfn; + fdsu_of <= ex2_of; + fdsu_uf <= ex2_uf; + fdsu_potnt_of <= ex2_potnt_of; + fdsu_potnt_uf <= ex2_potnt_uf; + end + else + begin + fdsu_result_inf <= fdsu_result_inf; + fdsu_result_lfn <= fdsu_result_lfn; + fdsu_of <= fdsu_of; + fdsu_uf <= fdsu_uf; + fdsu_potnt_of <= fdsu_potnt_of; + fdsu_potnt_uf <= fdsu_potnt_uf; + end +end + +//========================================================== +// Flush +//========================================================== +assign fdsu_flush = rtu_xx_ex1_cancel && ctrl_wb_idle + || rtu_xx_ex2_cancel && ctrl_wb_sm_ex2 + || ctrl_xx_ex1_warm_up + || rtu_yy_xx_async_flush; + +//========================================================== +// ICG +//========================================================== +assign fdsu_busy = fdsu_ex1_inst_vld + || !ctrl_sm_idle + || !ctrl_wb_sm_idle; +assign fdsu_clk_en = fdsu_busy + || !ctrl_sm_idle + || rtu_yy_xx_flush; +// &Instance("gated_clk_cell", "x_fdsu_clk"); @514 +gated_clk_cell x_fdsu_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fdsu_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fdsu_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @515 +// .external_en (1'b0), @516 +// .global_en (cp0_yy_clk_en), @517 +// .module_en (cp0_fpu_icg_en), @518 +// .local_en (fdsu_clk_en), @519 +// .clk_out (fdsu_clk)); @520 + +assign ex1_pipe_clk_en = ex1_pipedown_gate; +// &Instance("gated_clk_cell","x_ex1_pipe_clk"); @523 +gated_clk_cell x_ex1_pipe_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex1_pipe_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex1_pipe_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @524 +// .clk_out (ex1_pipe_clk),//Out Clock @525 +// .external_en (1'b0), @526 +// .global_en (cp0_yy_clk_en), @527 +// .local_en (ex1_pipe_clk_en),//Local Condition @528 +// .module_en (cp0_fpu_icg_en) @529 +// ); @530 + +assign ex2_pipe_clk_en = ex2_pipedown; +// &Instance("gated_clk_cell","x_ex2_pipe_clk"); @533 +gated_clk_cell x_ex2_pipe_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex2_pipe_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex2_pipe_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @534 +// .clk_out (ex2_pipe_clk),//Out Clock @535 +// .external_en (1'b0), @536 +// .global_en (cp0_yy_clk_en), @537 +// .local_en (ex2_pipe_clk_en),//Local Condition @538 +// .module_en (cp0_fpu_icg_en) @539 +// ); @540 +// &Force("output", "ex2_pipe_clk"); @541 + +assign expnt_rst_clk_en = ex1_save_op0_gate + || ex1_pipedown_gate + || ex2_pipedown + || ex3_pipedown; +// &Instance("gated_clk_cell", "x_expnt_rst_clk"); @547 +gated_clk_cell x_expnt_rst_clk ( + .clk_in (forever_cpuclk ), + .clk_out (expnt_rst_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (expnt_rst_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @548 +// .external_en (1'b0), @549 +// .global_en (cp0_yy_clk_en), @550 +// .module_en (cp0_fpu_icg_en), @551 +// .local_en (expnt_rst_clk_en), @552 +// .clk_out (expnt_rst_clk)); @553 + +//========================================================== +// Output Signal +//========================================================== +assign fdsu_yy_wb_freg[4:0] = fdsu_wb_freg[4:0]; +assign fdsu_yy_result_sign = fdsu_result_sign; +assign fdsu_yy_op0_norm = fdsu_op0_norm; +assign fdsu_yy_op1_norm = fdsu_op1_norm; +assign fdsu_yy_of_rm_lfn = fdsu_of_rm_lfn; +assign fdsu_yy_div = fdsu_div; +assign fdsu_yy_sqrt = fdsu_sqrt; +assign fdsu_yy_rm[2:0] = fdsu_rm[2:0]; + +assign fdsu_yy_expnt_rst[9:0] = fdsu_expnt_rst[9:0]; +assign ex2_expnt_adder_op0[9:0] = fdsu_expnt_rst[9:0]; + +assign fdsu_yy_result_inf = fdsu_result_inf; +assign fdsu_yy_result_lfn = fdsu_result_lfn; +assign fdsu_yy_of = fdsu_of; +assign fdsu_yy_uf = fdsu_uf; +assign fdsu_yy_potnt_of = fdsu_potnt_of; +assign fdsu_yy_potnt_uf = fdsu_potnt_uf; + +assign ex1_pipedown = ctrl_iter_start || ctrl_xx_ex1_warm_up; +assign ex1_pipedown_gate = ctrl_iter_start_gate || ctrl_xx_ex1_warm_up; +assign ex2_pipedown = ctrl_srt_itering && srt_last_round || ctrl_xx_ex2_warm_up; +assign ex3_pipedown = ctrl_round || ctrl_xx_ex3_warm_up; +// &Force("output", "ex1_pipedown"); @589 +// &Force("output", "ex1_pipedown_gate"); @590 +// &Force("output", "ex2_pipedown"); @591 +// &Force("output", "ex3_pipedown"); @592 + +assign srt_sm_on = ctrl_srt_itering; + +assign fdsu_fpu_ex1_cmplt = fdsu_ex1_inst_vld; +assign fdsu_fpu_ex1_cmplt_dp = ctrl_xx_ex1_cmplt_dp && idu_fpu_ex1_eu_sel[2]; +assign fdsu_fpu_ex1_stall = ctrl_fdsu_ex1_stall; +assign fdsu_frbus_wb_vld = ctrl_result_vld; +// &Force("bus","idu_fpu_ex1_eu_sel",2,0); @600 +assign fdsu_fpu_no_op = !fdsu_busy; +assign ex1_op1_sel = ctrl_wfi2; +assign ex1_save_op0 = ctrl_sm_start && ex1_op0_id && ex1_op1_id_vld; +assign ex1_save_op0_gate = ctrl_sm_start_gate && ex1_op0_id && ex1_op1_id_vld; +// &Force("output", "ex1_save_op0"); @605 +// &Force("output", "ex1_save_op0_gate"); @606 + +assign fdsu_fpu_debug_info[4:0] = {wb_cur_state[1:0], fdsu_cur_state[2:0]}; + +// &ModuleEnd; @610 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ff1.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ff1.v new file mode 100644 index 0000000000000000000000000000000000000000..b8f2dc56e44a42c99db022dbee00b3f69f4a11c1 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_ff1.v @@ -0,0 +1,163 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_ff1( + fanc_shift_num, + frac_bin_val, + frac_num +); + +// &Ports; @24 +input [51:0] frac_num; +output [51:0] fanc_shift_num; +output [12:0] frac_bin_val; + +// &Regs; @25 +reg [51:0] fanc_shift_num; +reg [12:0] frac_bin_val; + +// &Wires; @26 +wire [51:0] frac_num; + + +// &CombBeg; @28 +always @( frac_num[51:0]) +begin +casez(frac_num[51:0]) + 52'b1???????????????????????????????????????????????????: frac_bin_val[12:0] = 13'h0; + 52'b01??????????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1fff; + 52'b001?????????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ffe; + 52'b0001????????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ffd; + 52'b00001???????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ffc; + 52'b000001??????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ffb; + 52'b0000001?????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ffa; + 52'b00000001????????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff9; + 52'b000000001???????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff8; + 52'b0000000001??????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff7; + 52'b00000000001?????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff6; + 52'b000000000001????????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff5; + 52'b0000000000001???????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff4; + 52'b00000000000001??????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff3; + 52'b000000000000001?????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff2; + 52'b0000000000000001????????????????????????????????????: frac_bin_val[12:0] = 13'h1ff1; + 52'b00000000000000001???????????????????????????????????: frac_bin_val[12:0] = 13'h1ff0; + 52'b000000000000000001??????????????????????????????????: frac_bin_val[12:0] = 13'h1fef; + 52'b0000000000000000001?????????????????????????????????: frac_bin_val[12:0] = 13'h1fee; + 52'b00000000000000000001????????????????????????????????: frac_bin_val[12:0] = 13'h1fed; + 52'b000000000000000000001???????????????????????????????: frac_bin_val[12:0] = 13'h1fec; + 52'b0000000000000000000001??????????????????????????????: frac_bin_val[12:0] = 13'h1feb; + 52'b00000000000000000000001?????????????????????????????: frac_bin_val[12:0] = 13'h1fea; + 52'b000000000000000000000001????????????????????????????: frac_bin_val[12:0] = 13'h1fe9; + 52'b0000000000000000000000001???????????????????????????: frac_bin_val[12:0] = 13'h1fe8; + 52'b00000000000000000000000001??????????????????????????: frac_bin_val[12:0] = 13'h1fe7; + 52'b000000000000000000000000001?????????????????????????: frac_bin_val[12:0] = 13'h1fe6; + 52'b0000000000000000000000000001????????????????????????: frac_bin_val[12:0] = 13'h1fe5; + 52'b00000000000000000000000000001???????????????????????: frac_bin_val[12:0] = 13'h1fe4; + 52'b000000000000000000000000000001??????????????????????: frac_bin_val[12:0] = 13'h1fe3; + 52'b0000000000000000000000000000001?????????????????????: frac_bin_val[12:0] = 13'h1fe2; + 52'b00000000000000000000000000000001????????????????????: frac_bin_val[12:0] = 13'h1fe1; + 52'b000000000000000000000000000000001???????????????????: frac_bin_val[12:0] = 13'h1fe0; + 52'b0000000000000000000000000000000001??????????????????: frac_bin_val[12:0] = 13'h1fdf; + 52'b00000000000000000000000000000000001?????????????????: frac_bin_val[12:0] = 13'h1fde; + 52'b000000000000000000000000000000000001????????????????: frac_bin_val[12:0] = 13'h1fdd; + 52'b0000000000000000000000000000000000001???????????????: frac_bin_val[12:0] = 13'h1fdc; + 52'b00000000000000000000000000000000000001??????????????: frac_bin_val[12:0] = 13'h1fdb; + 52'b000000000000000000000000000000000000001?????????????: frac_bin_val[12:0] = 13'h1fda; + 52'b0000000000000000000000000000000000000001????????????: frac_bin_val[12:0] = 13'h1fd9; + 52'b00000000000000000000000000000000000000001???????????: frac_bin_val[12:0] = 13'h1fd8; + 52'b000000000000000000000000000000000000000001??????????: frac_bin_val[12:0] = 13'h1fd7; + 52'b0000000000000000000000000000000000000000001?????????: frac_bin_val[12:0] = 13'h1fd6; + 52'b00000000000000000000000000000000000000000001????????: frac_bin_val[12:0] = 13'h1fd5; + 52'b000000000000000000000000000000000000000000001???????: frac_bin_val[12:0] = 13'h1fd4; + 52'b0000000000000000000000000000000000000000000001??????: frac_bin_val[12:0] = 13'h1fd3; + 52'b00000000000000000000000000000000000000000000001?????: frac_bin_val[12:0] = 13'h1fd2; + 52'b000000000000000000000000000000000000000000000001????: frac_bin_val[12:0] = 13'h1fd1; + 52'b0000000000000000000000000000000000000000000000001???: frac_bin_val[12:0] = 13'h1fd0; + 52'b00000000000000000000000000000000000000000000000001??: frac_bin_val[12:0] = 13'h1fcf; + 52'b000000000000000000000000000000000000000000000000001?: frac_bin_val[12:0] = 13'h1fce; + 52'b0000000000000000000000000000000000000000000000000001: frac_bin_val[12:0] = 13'h1fcd; + 52'b0000000000000000000000000000000000000000000000000000: frac_bin_val[12:0] = 13'h1fcc; + default : frac_bin_val[12:0] = 13'h000; +endcase +// &CombEnd; @85 +end + +// &CombBeg; @87 +always @( frac_num[51:0]) +begin +casez(frac_num[51:0]) + 52'b1???????????????????????????????????????????????????: fanc_shift_num[51:0] = frac_num[51:0]; + 52'b01??????????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[50:0],1'b0}; + 52'b001?????????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[49:0],2'b0}; + 52'b0001????????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[48:0],3'b0}; + 52'b00001???????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[47:0],4'b0}; + 52'b000001??????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[46:0],5'b0}; + 52'b0000001?????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[45:0],6'b0}; + 52'b00000001????????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[44:0],7'b0}; + 52'b000000001???????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[43:0],8'b0}; + 52'b0000000001??????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[42:0],9'b0}; + 52'b00000000001?????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[41:0],10'b0}; + 52'b000000000001????????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[40:0],11'b0}; + 52'b0000000000001???????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[39:0],12'b0}; + 52'b00000000000001??????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[38:0],13'b0}; + 52'b000000000000001?????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[37:0],14'b0}; + 52'b0000000000000001????????????????????????????????????: fanc_shift_num[51:0] = {frac_num[36:0],15'b0}; + 52'b00000000000000001???????????????????????????????????: fanc_shift_num[51:0] = {frac_num[35:0],16'b0}; + 52'b000000000000000001??????????????????????????????????: fanc_shift_num[51:0] = {frac_num[34:0],17'b0}; + 52'b0000000000000000001?????????????????????????????????: fanc_shift_num[51:0] = {frac_num[33:0],18'b0}; + 52'b00000000000000000001????????????????????????????????: fanc_shift_num[51:0] = {frac_num[32:0],19'b0}; + 52'b000000000000000000001???????????????????????????????: fanc_shift_num[51:0] = {frac_num[31:0],20'b0}; + 52'b0000000000000000000001??????????????????????????????: fanc_shift_num[51:0] = {frac_num[30:0],21'b0}; + 52'b00000000000000000000001?????????????????????????????: fanc_shift_num[51:0] = {frac_num[29:0],22'b0}; + 52'b000000000000000000000001????????????????????????????: fanc_shift_num[51:0] = {frac_num[28:0],23'b0}; + 52'b0000000000000000000000001???????????????????????????: fanc_shift_num[51:0] = {frac_num[27:0],24'b0}; + 52'b00000000000000000000000001??????????????????????????: fanc_shift_num[51:0] = {frac_num[26:0],25'b0}; + 52'b000000000000000000000000001?????????????????????????: fanc_shift_num[51:0] = {frac_num[25:0],26'b0}; + 52'b0000000000000000000000000001????????????????????????: fanc_shift_num[51:0] = {frac_num[24:0],27'b0}; + 52'b00000000000000000000000000001???????????????????????: fanc_shift_num[51:0] = {frac_num[23:0],28'b0}; + 52'b000000000000000000000000000001??????????????????????: fanc_shift_num[51:0] = {frac_num[22:0],29'b0}; + 52'b0000000000000000000000000000001?????????????????????: fanc_shift_num[51:0] = {frac_num[21:0],30'b0}; + 52'b00000000000000000000000000000001????????????????????: fanc_shift_num[51:0] = {frac_num[20:0],31'b0}; + 52'b000000000000000000000000000000001???????????????????: fanc_shift_num[51:0] = {frac_num[19:0],32'b0}; + 52'b0000000000000000000000000000000001??????????????????: fanc_shift_num[51:0] = {frac_num[18:0],33'b0}; + 52'b00000000000000000000000000000000001?????????????????: fanc_shift_num[51:0] = {frac_num[17:0],34'b0}; + 52'b000000000000000000000000000000000001????????????????: fanc_shift_num[51:0] = {frac_num[16:0],35'b0}; + 52'b0000000000000000000000000000000000001???????????????: fanc_shift_num[51:0] = {frac_num[15:0],36'b0}; + 52'b00000000000000000000000000000000000001??????????????: fanc_shift_num[51:0] = {frac_num[14:0],37'b0}; + 52'b000000000000000000000000000000000000001?????????????: fanc_shift_num[51:0] = {frac_num[13:0],38'b0}; + 52'b0000000000000000000000000000000000000001????????????: fanc_shift_num[51:0] = {frac_num[12:0],39'b0}; + 52'b00000000000000000000000000000000000000001???????????: fanc_shift_num[51:0] = {frac_num[11:0],40'b0}; + 52'b000000000000000000000000000000000000000001??????????: fanc_shift_num[51:0] = {frac_num[10:0],41'b0}; + 52'b0000000000000000000000000000000000000000001?????????: fanc_shift_num[51:0] = {frac_num[9:0],42'b0}; + 52'b00000000000000000000000000000000000000000001????????: fanc_shift_num[51:0] = {frac_num[8:0],43'b0}; + 52'b000000000000000000000000000000000000000000001???????: fanc_shift_num[51:0] = {frac_num[7:0],44'b0}; + 52'b0000000000000000000000000000000000000000000001??????: fanc_shift_num[51:0] = {frac_num[6:0],45'b0}; + 52'b00000000000000000000000000000000000000000000001?????: fanc_shift_num[51:0] = {frac_num[5:0],46'b0}; + 52'b000000000000000000000000000000000000000000000001????: fanc_shift_num[51:0] = {frac_num[4:0],47'b0}; + 52'b0000000000000000000000000000000000000000000000001???: fanc_shift_num[51:0] = {frac_num[3:0],48'b0}; + 52'b00000000000000000000000000000000000000000000000001??: fanc_shift_num[51:0] = {frac_num[2:0],49'b0}; + 52'b000000000000000000000000000000000000000000000000001?: fanc_shift_num[51:0] = {frac_num[1:0],50'b0}; + 52'b0000000000000000000000000000000000000000000000000001: fanc_shift_num[51:0] = {frac_num[0:0],51'b0}; + 52'b0000000000000000000000000000000000000000000000000000: fanc_shift_num[51:0] = {52'b0}; + default : fanc_shift_num[51:0] = {52'b0}; +endcase +// &CombEnd; @144 +end + +// &ModuleEnd; @146 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_pack_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_pack_single.v new file mode 100644 index 0000000000000000000000000000000000000000..87139a253059706ea0e9b7bec7d695c25f3dd792 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_pack_single.v @@ -0,0 +1,275 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_pack_single( + fdsu_ex4_denorm_to_tiny_frac, + fdsu_ex4_frac, + fdsu_ex4_nx, + fdsu_ex4_potnt_norm, + fdsu_ex4_result_nor, + fdsu_frbus_data, + fdsu_frbus_fflags, + fdsu_frbus_freg, + fdsu_yy_expnt_rst, + fdsu_yy_of, + fdsu_yy_of_rm_lfn, + fdsu_yy_potnt_of, + fdsu_yy_potnt_uf, + fdsu_yy_result_inf, + fdsu_yy_result_lfn, + fdsu_yy_result_sign, + fdsu_yy_rslt_denorm, + fdsu_yy_uf, + fdsu_yy_wb_freg +); + +// &Ports; @24 +input fdsu_ex4_denorm_to_tiny_frac; +input [25:0] fdsu_ex4_frac; +input fdsu_ex4_nx; +input [1 :0] fdsu_ex4_potnt_norm; +input fdsu_ex4_result_nor; +input [9 :0] fdsu_yy_expnt_rst; +input fdsu_yy_of; +input fdsu_yy_of_rm_lfn; +input fdsu_yy_potnt_of; +input fdsu_yy_potnt_uf; +input fdsu_yy_result_inf; +input fdsu_yy_result_lfn; +input fdsu_yy_result_sign; +input fdsu_yy_rslt_denorm; +input fdsu_yy_uf; +input [4 :0] fdsu_yy_wb_freg; +output [31:0] fdsu_frbus_data; +output [4 :0] fdsu_frbus_fflags; +output [4 :0] fdsu_frbus_freg; + +// &Regs; @25 +reg [22:0] ex4_frac_23; +reg [31:0] ex4_result; +reg [22:0] ex4_single_denorm_frac; +reg [9 :0] expnt_add_op1; + +// &Wires; @26 +wire ex4_cor_nx; +wire ex4_cor_uf; +wire ex4_denorm_potnt_norm; +wire [31:0] ex4_denorm_result; +wire [9 :0] ex4_expnt_rst; +wire [4 :0] ex4_expt; +wire ex4_final_rst_norm; +wire [25:0] ex4_frac; +wire ex4_of_plus; +wire ex4_result_inf; +wire ex4_result_lfn; +wire ex4_rslt_denorm; +wire [31:0] ex4_rst_inf; +wire [31:0] ex4_rst_lfn; +wire ex4_rst_nor; +wire [31:0] ex4_rst_norm; +wire ex4_uf_plus; +wire fdsu_ex4_denorm_to_tiny_frac; +wire fdsu_ex4_dz; +wire [9 :0] fdsu_ex4_expnt_rst; +wire [25:0] fdsu_ex4_frac; +wire fdsu_ex4_nv; +wire fdsu_ex4_nx; +wire fdsu_ex4_of; +wire fdsu_ex4_of_rst_lfn; +wire [1 :0] fdsu_ex4_potnt_norm; +wire fdsu_ex4_potnt_of; +wire fdsu_ex4_potnt_uf; +wire fdsu_ex4_result_inf; +wire fdsu_ex4_result_lfn; +wire fdsu_ex4_result_nor; +wire fdsu_ex4_result_sign; +wire fdsu_ex4_rslt_denorm; +wire fdsu_ex4_uf; +wire [31:0] fdsu_frbus_data; +wire [4 :0] fdsu_frbus_fflags; +wire [4 :0] fdsu_frbus_freg; +wire [9 :0] fdsu_yy_expnt_rst; +wire fdsu_yy_of; +wire fdsu_yy_of_rm_lfn; +wire fdsu_yy_potnt_of; +wire fdsu_yy_potnt_uf; +wire fdsu_yy_result_inf; +wire fdsu_yy_result_lfn; +wire fdsu_yy_result_sign; +wire fdsu_yy_rslt_denorm; +wire fdsu_yy_uf; +wire [4 :0] fdsu_yy_wb_freg; + + +assign fdsu_ex4_result_sign = fdsu_yy_result_sign; +assign fdsu_ex4_of_rst_lfn = fdsu_yy_of_rm_lfn; +assign fdsu_ex4_result_inf = fdsu_yy_result_inf; +assign fdsu_ex4_result_lfn = fdsu_yy_result_lfn; +assign fdsu_ex4_of = fdsu_yy_of; +assign fdsu_ex4_uf = fdsu_yy_uf; +assign fdsu_ex4_potnt_of = fdsu_yy_potnt_of; +assign fdsu_ex4_potnt_uf = fdsu_yy_potnt_uf; +assign fdsu_ex4_nv = 1'b0; +assign fdsu_ex4_dz = 1'b0; +assign fdsu_ex4_expnt_rst[9:0] = fdsu_yy_expnt_rst[9:0]; +assign fdsu_ex4_rslt_denorm = fdsu_yy_rslt_denorm; +//============================EX4 STAGE===================== +assign ex4_frac[25:0] = fdsu_ex4_frac[25:0]; +//exponent adder +// &CombBeg; @43 +always @( ex4_frac[25:24]) +begin +casez(ex4_frac[25:24]) + 2'b00 : expnt_add_op1[9:0] = 10'h1ff; //the expnt sub 1 + 2'b01 : expnt_add_op1[9:0] = 10'h0; //the expnt stay the origi + 2'b1? : expnt_add_op1[9:0] = 10'h1; // the exptn add 1 + default : expnt_add_op1[9:0] = 10'b0; +endcase +// &CombEnd; @50 +end +assign ex4_expnt_rst[9:0] = fdsu_ex4_expnt_rst[9:0] + + expnt_add_op1[9:0]; + +//==========================Result Pack===================== + +// result denormal pack +// shift to the denormal number +// &CombBeg; @58 +always @( fdsu_ex4_expnt_rst[9:0] + or fdsu_ex4_denorm_to_tiny_frac + or ex4_frac[25:1]) +begin +case(fdsu_ex4_expnt_rst[9:0]) + 10'h1: ex4_single_denorm_frac[22:0] = { ex4_frac[23:1]}; //-1022 1 + 10'h0: ex4_single_denorm_frac[22:0] = { ex4_frac[24:2]}; //-1023 0 + 10'h3ff:ex4_single_denorm_frac[22:0] = { ex4_frac[25:3]}; //-1024 -1 + 10'h3fe:ex4_single_denorm_frac[22:0] = {1'b0, ex4_frac[25:4]}; //-1025 -2 + 10'h3fd:ex4_single_denorm_frac[22:0] = {2'b0, ex4_frac[25:5]}; //-1026 -3 + 10'h3fc:ex4_single_denorm_frac[22:0] = {3'b0, ex4_frac[25:6]}; //-1027 -4 + 10'h3fb:ex4_single_denorm_frac[22:0] = {4'b0, ex4_frac[25:7]}; //-1028 -5 + 10'h3fa:ex4_single_denorm_frac[22:0] = {5'b0, ex4_frac[25:8]}; //-1029 -6 + 10'h3f9:ex4_single_denorm_frac[22:0] = {6'b0, ex4_frac[25:9]}; //-1030 -7 + 10'h3f8:ex4_single_denorm_frac[22:0] = {7'b0, ex4_frac[25:10]}; //-1031 -8 + 10'h3f7:ex4_single_denorm_frac[22:0] = {8'b0, ex4_frac[25:11]}; //-1032 -9 + 10'h3f6:ex4_single_denorm_frac[22:0] = {9'b0, ex4_frac[25:12]}; //-1033 -10 + 10'h3f5:ex4_single_denorm_frac[22:0] = {10'b0,ex4_frac[25:13]}; //-1034 -11 + 10'h3f4:ex4_single_denorm_frac[22:0] = {11'b0,ex4_frac[25:14]}; //-1035 -12 + 10'h3f3:ex4_single_denorm_frac[22:0] = {12'b0,ex4_frac[25:15]}; //-1036 -13 + 10'h3f2:ex4_single_denorm_frac[22:0] = {13'b0,ex4_frac[25:16]}; // -1037 + 10'h3f1:ex4_single_denorm_frac[22:0] = {14'b0,ex4_frac[25:17]}; //-1038 + 10'h3f0:ex4_single_denorm_frac[22:0] = {15'b0,ex4_frac[25:18]}; //-1039 + 10'h3ef:ex4_single_denorm_frac[22:0] = {16'b0,ex4_frac[25:19]}; //-1040 + 10'h3ee:ex4_single_denorm_frac[22:0] = {17'b0,ex4_frac[25:20]}; //-1041 + 10'h3ed:ex4_single_denorm_frac[22:0] = {18'b0,ex4_frac[25:21]}; //-1042 + 10'h3ec:ex4_single_denorm_frac[22:0] = {19'b0,ex4_frac[25:22]}; //-1043 + 10'h3eb:ex4_single_denorm_frac[22:0] = {20'b0,ex4_frac[25:23]}; //-1044 + 10'h3ea:ex4_single_denorm_frac[22:0] = {21'b0,ex4_frac[25:24]}; //-1044 + default :ex4_single_denorm_frac[22:0] = fdsu_ex4_denorm_to_tiny_frac ? 23'b1 : 23'b0; //-1045 +endcase +// &CombEnd; @86 +end +//here when denormal number round to add1, it will become normal number +assign ex4_denorm_potnt_norm = (fdsu_ex4_potnt_norm[1] && ex4_frac[24]) || + (fdsu_ex4_potnt_norm[0] && ex4_frac[25]) ; +assign ex4_rslt_denorm = fdsu_ex4_rslt_denorm && !ex4_denorm_potnt_norm; +assign ex4_denorm_result[31:0] = {fdsu_ex4_result_sign, + 8'h0,ex4_single_denorm_frac[22:0]}; + + +//ex4 overflow/underflow plus +assign ex4_rst_nor = fdsu_ex4_result_nor; +assign ex4_of_plus = fdsu_ex4_potnt_of && + (|ex4_frac[25:24]) && + ex4_rst_nor; +assign ex4_uf_plus = fdsu_ex4_potnt_uf && + (~|ex4_frac[25:24]) && + ex4_rst_nor; +//ex4 overflow round result +assign ex4_result_lfn = (ex4_of_plus && fdsu_ex4_of_rst_lfn) || + fdsu_ex4_result_lfn; +assign ex4_result_inf = (ex4_of_plus && !fdsu_ex4_of_rst_lfn) || + fdsu_ex4_result_inf; +//Special Result Form +// result largest finity number +assign ex4_rst_lfn[31:0] = {fdsu_ex4_result_sign,8'hfe,{23{1'b1}}}; +//result infinity +assign ex4_rst_inf[31:0] = {fdsu_ex4_result_sign,8'hff,23'b0}; +//result normal +// &CombBeg; @114 +always @( ex4_frac[25:0]) +begin +casez(ex4_frac[25:24]) + 2'b00 : ex4_frac_23[22:0] = ex4_frac[22:0]; + 2'b01 : ex4_frac_23[22:0] = ex4_frac[23:1]; + 2'b1? : ex4_frac_23[22:0] = ex4_frac[24:2]; + default : ex4_frac_23[22:0] = 23'b0; +endcase +// &CombEnd; @121 +end +assign ex4_rst_norm[31:0] = {fdsu_ex4_result_sign, + ex4_expnt_rst[7:0], + ex4_frac_23[22:0]}; +assign ex4_cor_uf = (fdsu_ex4_uf && !ex4_denorm_potnt_norm || ex4_uf_plus) + && fdsu_ex4_nx; +assign ex4_cor_nx = fdsu_ex4_nx + || fdsu_ex4_of + || ex4_of_plus; + +assign ex4_expt[4:0] = { + fdsu_ex4_nv, + fdsu_ex4_dz, + fdsu_ex4_of | ex4_of_plus, + ex4_cor_uf, + ex4_cor_nx}; + +assign ex4_final_rst_norm = !ex4_result_inf && + !ex4_result_lfn && + !ex4_rslt_denorm; +// &CombBeg; @141 +always @( ex4_denorm_result[31:0] + or ex4_result_lfn + or ex4_result_inf + or ex4_final_rst_norm + or ex4_rst_norm[31:0] + or ex4_rst_lfn[31:0] + or ex4_rst_inf[31:0] + or ex4_rslt_denorm) +begin +case({ex4_rslt_denorm, + ex4_result_inf, + ex4_result_lfn, + ex4_final_rst_norm}) + 4'b1000 : ex4_result[31:0] = ex4_denorm_result[31:0]; + 4'b0100 : ex4_result[31:0] = ex4_rst_inf[31:0]; + 4'b0010 : ex4_result[31:0] = ex4_rst_lfn[31:0]; + 4'b0001 : ex4_result[31:0] = ex4_rst_norm[31:0]; + default : ex4_result[31:0] = 32'b0; +endcase +// &CombEnd; @152 +end + +//========================================================== +// Result Generate +//========================================================== +assign fdsu_frbus_freg[4:0] = fdsu_yy_wb_freg[4:0]; +assign fdsu_frbus_data[31:0] = ex4_result[31:0]; +assign fdsu_frbus_fflags[4:0] = ex4_expt[4:0]; + +// &ModuleEnd; @161 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_prepare.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_prepare.v new file mode 100644 index 0000000000000000000000000000000000000000..56d179bd5a1d426c67fc71893b87fbbd4deb26ff --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_prepare.v @@ -0,0 +1,288 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_prepare( + dp_xx_ex1_rm, + ex1_div, + ex1_divisor, + ex1_expnt_adder_op0, + ex1_expnt_adder_op1, + ex1_of_result_lfn, + ex1_op0_id, + ex1_op0_sign, + ex1_op1_id, + ex1_op1_id_vld, + ex1_op1_sel, + ex1_oper_id_expnt, + ex1_oper_id_expnt_f, + ex1_oper_id_frac, + ex1_oper_id_frac_f, + ex1_remainder, + ex1_result_sign, + ex1_rm, + ex1_sqrt, + fdsu_ex1_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1 +); + +// &Ports; @24 +input [2 :0] dp_xx_ex1_rm; +input ex1_op0_id; +input ex1_op1_id; +input ex1_op1_sel; +input [12:0] ex1_oper_id_expnt_f; +input [51:0] ex1_oper_id_frac_f; +input fdsu_ex1_sel; +input [9 :0] idu_fpu_ex1_func; +input [31:0] idu_fpu_ex1_srcf0; +input [31:0] idu_fpu_ex1_srcf1; +output ex1_div; +output [23:0] ex1_divisor; +output [12:0] ex1_expnt_adder_op0; +output [12:0] ex1_expnt_adder_op1; +output ex1_of_result_lfn; +output ex1_op0_sign; +output ex1_op1_id_vld; +output [12:0] ex1_oper_id_expnt; +output [51:0] ex1_oper_id_frac; +output [31:0] ex1_remainder; +output ex1_result_sign; +output [2 :0] ex1_rm; +output ex1_sqrt; + +// &Regs; @25 +reg [12:0] ex1_expnt_adder_op1; +reg ex1_of_result_lfn; + +// &Wires; @26 +wire div_sign; +wire [2 :0] dp_xx_ex1_rm; +wire ex1_div; +wire [52:0] ex1_div_noid_nor_srt_op0; +wire [52:0] ex1_div_noid_nor_srt_op1; +wire [52:0] ex1_div_nor_srt_op0; +wire [52:0] ex1_div_nor_srt_op1; +wire [12:0] ex1_div_op0_expnt; +wire [12:0] ex1_div_op1_expnt; +wire [52:0] ex1_div_srt_op0; +wire [52:0] ex1_div_srt_op1; +wire [23:0] ex1_divisor; +wire ex1_double; +wire [12:0] ex1_expnt_adder_op0; +wire ex1_op0_id; +wire ex1_op0_id_nor; +wire ex1_op0_sign; +wire ex1_op1_id; +wire ex1_op1_id_nor; +wire ex1_op1_id_vld; +wire ex1_op1_sel; +wire ex1_op1_sign; +wire [63:0] ex1_oper0; +wire [51:0] ex1_oper0_frac; +wire [12:0] ex1_oper0_id_expnt; +wire [51:0] ex1_oper0_id_frac; +wire [63:0] ex1_oper1; +wire [51:0] ex1_oper1_frac; +wire [12:0] ex1_oper1_id_expnt; +wire [51:0] ex1_oper1_id_frac; +wire [51:0] ex1_oper_frac; +wire [12:0] ex1_oper_id_expnt; +wire [12:0] ex1_oper_id_expnt_f; +wire [51:0] ex1_oper_id_frac; +wire [51:0] ex1_oper_id_frac_f; +wire [31:0] ex1_remainder; +wire ex1_result_sign; +wire [2 :0] ex1_rm; +wire ex1_single; +wire ex1_sqrt; +wire ex1_sqrt_expnt_odd; +wire ex1_sqrt_op0_expnt_0; +wire [12:0] ex1_sqrt_op1_expnt; +wire [52:0] ex1_sqrt_srt_op0; +wire fdsu_ex1_sel; +wire [9 :0] idu_fpu_ex1_func; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire [59:0] sqrt_remainder; +wire sqrt_sign; + + +parameter FLEN = `FLEN; + +assign ex1_sqrt = idu_fpu_ex1_func[0]; +assign ex1_div = idu_fpu_ex1_func[1]; +assign ex1_oper0[63:0] = {32'b0, idu_fpu_ex1_srcf0[FLEN-1:0] & {32{fdsu_ex1_sel}}}; +assign ex1_oper1[63:0] = {32'b0, idu_fpu_ex1_srcf1[FLEN-1:0] & {32{fdsu_ex1_sel}}}; +assign ex1_double = 1'b0; +assign ex1_single = 1'b1; +// &Force("bus", "idu_fpu_ex1_func", 9, 0); @43 +assign ex1_op0_id_nor = ex1_op0_id; +assign ex1_op1_id_nor = ex1_op1_id; + +//Sign bit prepare +assign ex1_op0_sign = ex1_double && ex1_oper0[63] + || ex1_single && ex1_oper0[31]; +assign ex1_op1_sign = ex1_double && ex1_oper1[63] + || ex1_single && ex1_oper1[31]; +assign div_sign = ex1_op0_sign ^ ex1_op1_sign; +assign sqrt_sign = ex1_op0_sign; +assign ex1_result_sign = (ex1_div) + ? div_sign + : sqrt_sign; + +//=====================find first one======================= +// this is for the denormal number +assign ex1_oper_frac[51:0] = ex1_op1_sel ? ex1_oper1_frac[51:0] + : ex1_oper0_frac[51:0]; + +// &Instance("pa_fdsu_ff1", "x_frac_expnt"); @63 +pa_fdsu_ff1 x_frac_expnt ( + .fanc_shift_num (ex1_oper_id_frac[51:0] ), + .frac_bin_val (ex1_oper_id_expnt[12:0]), + .frac_num (ex1_oper_frac[51:0] ) +); + +// &Connect(.frac_num(ex1_oper_frac[51:0])); @64 +// &Connect(.frac_bin_val(ex1_oper_id_expnt[12:0])); @65 +// &Connect(.fanc_shift_num(ex1_oper_id_frac[51:0])); @66 +// &Force("output", "ex1_oper_id_expnt"); &Force("bus", "ex1_oper_id_expnt", 12, 0); @67 +// &Force("output", "ex1_oper_id_frac"); &Force("bus", "ex1_oper_id_frac", 51, 0); @68 + +assign ex1_oper0_id_expnt[12:0] = ex1_op1_sel ? ex1_oper_id_expnt_f[12:0] + : ex1_oper_id_expnt[12:0]; +assign ex1_oper0_id_frac[51:0] = ex1_op1_sel ? ex1_oper_id_frac_f[51:0] + : ex1_oper_id_frac[51:0]; +assign ex1_oper1_id_expnt[12:0] = ex1_oper_id_expnt[12:0]; +assign ex1_oper1_id_frac[51:0] = ex1_oper_id_frac[51:0]; + +assign ex1_oper0_frac[51:0] = {52{ex1_double}} & ex1_oper0[51:0] + | {52{ex1_single}} & {ex1_oper0[22:0],29'b0}; +assign ex1_oper1_frac[51:0] = {52{ex1_double}} & ex1_oper1[51:0] + | {52{ex1_single}} & {ex1_oper1[22:0],29'b0}; + +//=====================exponent add========================= +//exponent number 0 +assign ex1_div_op0_expnt[12:0] = {13{ex1_double}} & {2'b0,ex1_oper0[62:52]} + | {13{ex1_single}} & {5'b0,ex1_oper0[30:23]}; +assign ex1_expnt_adder_op0[12:0] = ex1_op0_id_nor ? ex1_oper0_id_expnt[12:0] + : ex1_div_op0_expnt[12:0]; +//exponent number 1 +assign ex1_div_op1_expnt[12:0] = {13{ex1_double}} & {2'b0,ex1_oper1[62:52]} + | {13{ex1_single}} & {5'b0,ex1_oper1[30:23]}; +assign ex1_sqrt_op1_expnt[12:0] = {13{ex1_double}} & {3'b0,{10{1'b1}}} //'d1023 + | {13{ex1_single}} & {6'b0,{7{1'b1}}}; //'d127 +// &CombBeg; @93 +always @( ex1_oper1_id_expnt[12:0] + or ex1_div + or ex1_op1_id_nor + or ex1_sqrt_op1_expnt[12:0] + or ex1_sqrt + or ex1_div_op1_expnt[12:0]) +begin +case({ex1_div,ex1_sqrt}) + 2'b10: ex1_expnt_adder_op1[12:0] = ex1_op1_id_nor ? ex1_oper1_id_expnt[12:0] + : ex1_div_op1_expnt[12:0]; + 2'b01: ex1_expnt_adder_op1[12:0] = ex1_sqrt_op1_expnt[12:0]; + default: ex1_expnt_adder_op1[12:0] = 13'b0; +endcase +// &CombEnd; @100 +end + +//ex1_sqrt_expnt_odd +//fraction will shift left by 1 +// adder_op0/1 timing is bad. +// assign ex1_sqrt_expnt_odd = ex1_expnt_adder_op0[0] ^ ex1_expnt_adder_op1[0]; + +// sqrt_odd is only used when is sqrt. +assign ex1_sqrt_op0_expnt_0 = ex1_op0_id_nor ? ex1_oper_id_expnt[0] + : ex1_div_op0_expnt[0]; +// ex1_expnt_adder_op1 is always 1'b1, so adder_op0[0] should be 0. +assign ex1_sqrt_expnt_odd = !ex1_sqrt_op0_expnt_0; + +assign ex1_rm[2:0] = dp_xx_ex1_rm[2:0]; +//RNE : Always inc 1 because round to nearest of 1.111...11 +//RTZ : Always not inc 1 +//RUP : Always not inc 1 when posetive +//RDN : Always not inc 1 when negative +//RMM : Always inc 1 because round to max magnitude +// &CombBeg; @119 +always @( ex1_rm[2:0] + or ex1_result_sign) +begin +case(ex1_rm[2:0]) + 3'b000 : ex1_of_result_lfn = 1'b0; + 3'b001 : ex1_of_result_lfn = 1'b1; + 3'b010 : ex1_of_result_lfn = !ex1_result_sign; + 3'b011 : ex1_of_result_lfn = ex1_result_sign; + 3'b100 : ex1_of_result_lfn = 1'b0; + default: ex1_of_result_lfn = 1'b0; +endcase +// &CombEnd; @128 +end + +//EX1 Remainder +//div : 1/8 <= x < 1/4 +//sqrt : 1/16 <= x < 1/4 +assign ex1_remainder[31:0] = {32{ex1_div }} & {5'b0,ex1_div_srt_op0[52:28],2'b0} | + {32{ex1_sqrt}} & sqrt_remainder[59:28]; + +//EX1 Divisor +//1/2 <= y < 1 +assign ex1_divisor[23:0] = ex1_div_srt_op1[52:29]; + +//ex1_div_srt_op0 +assign ex1_div_srt_op0[52:0] = ex1_div_nor_srt_op0[52:0]; +//ex1_div_srt_op1 +assign ex1_div_srt_op1[52:0] = ex1_div_nor_srt_op1[52:0]; +//ex1_div_nor_srt_op0 +assign ex1_div_noid_nor_srt_op0[52:0] = {53{ex1_double}} & {1'b1,ex1_oper0[51:0]} + | {53{ex1_single}} & {1'b1,ex1_oper0[22:0],29'b0}; +assign ex1_div_nor_srt_op0[52:0] = ex1_op0_id_nor ? {ex1_oper0_id_frac[51:0],1'b0} + : ex1_div_noid_nor_srt_op0[52:0]; +//ex1_div_nor_srt_op1 +assign ex1_div_noid_nor_srt_op1[52:0] = {53{ex1_double}} & {1'b1,ex1_oper1[51:0]} + | {53{ex1_single}} & {1'b1,ex1_oper1[22:0],29'b0}; +assign ex1_div_nor_srt_op1[52:0] = ex1_op1_id_nor ? {ex1_oper1_id_frac[51:0],1'b0} + : ex1_div_noid_nor_srt_op1[52:0]; +//sqrt_remainder +assign sqrt_remainder[59:0] = (ex1_sqrt_expnt_odd) + ? {5'b0,ex1_sqrt_srt_op0[52:0],2'b0} + : {6'b0,ex1_sqrt_srt_op0[52:0],1'b0}; +//ex1_sqrt_srt_op0 +assign ex1_sqrt_srt_op0[52:0] = ex1_div_srt_op0[52:0]; + +//========================Pipe to EX2======================= +//exponent register cal result +// &Force("output", "ex1_expnt_adder_op0"); &Force("bus", "ex1_expnt_adder_op0", 12, 0); @173 +// &Force("output", "ex1_expnt_adder_op1"); &Force("bus", "ex1_expnt_adder_op1", 12, 0); @174 +// &Force("output", "ex1_double"); @175 +// &Force("output", "ex1_expnt_adder_op0"); &Force("bus", "ex1_expnt_adder_op0", 12, 0); @177 +// &Force("output", "ex1_expnt_adder_op1"); &Force("bus", "ex1_expnt_adder_op1", 12, 0); @178 +// &Force("output", "ex1_result_sign"); @180 +// &Force("output", "ex1_div"); @181 +// &Force("output", "ex1_sqrt"); @182 +// &Force("output", "ex1_rm"); &Force("bus", "ex1_rm", 2, 0); @183 +// &Force("output", "ex1_op0_sign"); @184 + +assign ex1_op1_id_vld = ex1_op1_id_nor && ex1_div; + +// &ModuleEnd; @188 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_round_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_round_single.v new file mode 100644 index 0000000000000000000000000000000000000000..7d6acbb4b39ce2c66a6a50ea6a06e517bc98a7fc --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_round_single.v @@ -0,0 +1,540 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_round_single( + cp0_fpu_icg_en, + cp0_yy_clk_en, + ex3_expnt_adjust_result, + ex3_frac_final_rst, + ex3_pipedown, + ex3_rslt_denorm, + fdsu_ex3_id_srt_skip, + fdsu_ex3_rem_sign, + fdsu_ex3_rem_zero, + fdsu_ex3_result_denorm_round_add_num, + fdsu_ex4_denorm_to_tiny_frac, + fdsu_ex4_nx, + fdsu_ex4_potnt_norm, + fdsu_ex4_result_nor, + fdsu_yy_expnt_rst, + fdsu_yy_result_inf, + fdsu_yy_result_lfn, + fdsu_yy_result_sign, + fdsu_yy_rm, + fdsu_yy_rslt_denorm, + forever_cpuclk, + pad_yy_icg_scan_en, + total_qt_rt_30 +); + +// &Ports; @24 +input cp0_fpu_icg_en; +input cp0_yy_clk_en; +input ex3_pipedown; +input fdsu_ex3_id_srt_skip; +input fdsu_ex3_rem_sign; +input fdsu_ex3_rem_zero; +input [23:0] fdsu_ex3_result_denorm_round_add_num; +input [9 :0] fdsu_yy_expnt_rst; +input fdsu_yy_result_inf; +input fdsu_yy_result_lfn; +input fdsu_yy_result_sign; +input [2 :0] fdsu_yy_rm; +input fdsu_yy_rslt_denorm; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input [29:0] total_qt_rt_30; +output [9 :0] ex3_expnt_adjust_result; +output [25:0] ex3_frac_final_rst; +output ex3_rslt_denorm; +output fdsu_ex4_denorm_to_tiny_frac; +output fdsu_ex4_nx; +output [1 :0] fdsu_ex4_potnt_norm; +output fdsu_ex4_result_nor; + +// &Regs; @25 +reg denorm_to_tiny_frac; +reg fdsu_ex4_denorm_to_tiny_frac; +reg fdsu_ex4_nx; +reg [1 :0] fdsu_ex4_potnt_norm; +reg fdsu_ex4_result_nor; +reg [25:0] frac_add1_op1; +reg frac_add_1; +reg frac_orig; +reg [25:0] frac_sub1_op1; +reg frac_sub_1; +reg [27:0] qt_result_single_denorm_for_round; +reg single_denorm_lst_frac; + +// &Wires; @26 +wire cp0_fpu_icg_en; +wire cp0_yy_clk_en; +wire ex3_denorm_eq; +wire ex3_denorm_gr; +wire ex3_denorm_lst_frac; +wire ex3_denorm_nx; +wire ex3_denorm_plus; +wire ex3_denorm_potnt_norm; +wire ex3_denorm_zero; +wire [9 :0] ex3_expnt_adjst; +wire [9 :0] ex3_expnt_adjust_result; +wire [25:0] ex3_frac_final_rst; +wire ex3_nx; +wire ex3_pipe_clk; +wire ex3_pipe_clk_en; +wire ex3_pipedown; +wire [1 :0] ex3_potnt_norm; +wire ex3_qt_eq; +wire ex3_qt_gr; +wire ex3_qt_sing_lo3_not0; +wire ex3_qt_sing_lo4_not0; +wire ex3_qt_zero; +wire ex3_rslt_denorm; +wire ex3_rst_eq_1; +wire ex3_rst_nor; +wire ex3_single_denorm_eq; +wire ex3_single_denorm_gr; +wire ex3_single_denorm_zero; +wire ex3_single_low_not_zero; +wire [9 :0] fdsu_ex3_expnt_rst; +wire fdsu_ex3_id_srt_skip; +wire fdsu_ex3_rem_sign; +wire fdsu_ex3_rem_zero; +wire [23:0] fdsu_ex3_result_denorm_round_add_num; +wire fdsu_ex3_result_inf; +wire fdsu_ex3_result_lfn; +wire fdsu_ex3_result_sign; +wire [2 :0] fdsu_ex3_rm; +wire fdsu_ex3_rslt_denorm; +wire [9 :0] fdsu_yy_expnt_rst; +wire fdsu_yy_result_inf; +wire fdsu_yy_result_lfn; +wire fdsu_yy_result_sign; +wire [2 :0] fdsu_yy_rm; +wire fdsu_yy_rslt_denorm; +wire forever_cpuclk; +wire [25:0] frac_add1_op1_with_denorm; +wire [25:0] frac_add1_rst; +wire frac_denorm_rdn_add_1; +wire frac_denorm_rdn_sub_1; +wire frac_denorm_rmm_add_1; +wire frac_denorm_rne_add_1; +wire frac_denorm_rtz_sub_1; +wire frac_denorm_rup_add_1; +wire frac_denorm_rup_sub_1; +wire [25:0] frac_final_rst; +wire frac_rdn_add_1; +wire frac_rdn_sub_1; +wire frac_rmm_add_1; +wire frac_rne_add_1; +wire frac_rtz_sub_1; +wire frac_rup_add_1; +wire frac_rup_sub_1; +wire [25:0] frac_sub1_op1_with_denorm; +wire [25:0] frac_sub1_rst; +wire pad_yy_icg_scan_en; +wire [29:0] total_qt_rt_30; + + +assign fdsu_ex3_result_sign = fdsu_yy_result_sign; +assign fdsu_ex3_expnt_rst[9:0] = fdsu_yy_expnt_rst[9:0]; +assign fdsu_ex3_result_inf = fdsu_yy_result_inf; +assign fdsu_ex3_result_lfn = fdsu_yy_result_lfn; +assign fdsu_ex3_rm[2:0] = fdsu_yy_rm[2:0]; +assign fdsu_ex3_rslt_denorm = fdsu_yy_rslt_denorm; +//=======================Round Rule========================= +//1/8 <= x < 1/4, 1/2 <= y < 1, => 1/8 < z < 1/2 +//q[29:0] represent the fraction part result of quotient, q[29] for 1/2 +//Thus the first "1" in 30 bit quotient will be in q[28] or q[27] +//For Single Float +//15 round to get 30 bit quotient, 23+1 bit as valid result, other for round +//if q[28] is 1, q[28:5] as 1.xxxx valid result, [4:0] for round +//if q[28] is 0, q[27:4] as 1.xxxx valid result, [3:0] for round +// &Force("bus","total_qt_rt_30",29,0); @42 +assign ex3_qt_sing_lo4_not0 = |total_qt_rt_30[3:0]; +assign ex3_qt_sing_lo3_not0 = |total_qt_rt_30[2:0]; +//the quotient round bits great than "10000"(ronnd bits 10..0) +assign ex3_qt_gr = (total_qt_rt_30[28]) + ? total_qt_rt_30[4] && ex3_qt_sing_lo4_not0 + : total_qt_rt_30[3] && ex3_qt_sing_lo3_not0; + +//the quotient round bits is equal to "10000"(ronnd bits 10..0) +assign ex3_qt_eq = (total_qt_rt_30[28]) + ? total_qt_rt_30[4] && !ex3_qt_sing_lo4_not0 + : total_qt_rt_30[3] && !ex3_qt_sing_lo3_not0; +//the quotient round bits is zero +assign ex3_qt_zero = (total_qt_rt_30[28]) + ? ~|total_qt_rt_30[4:0] + : ~|total_qt_rt_30[3:0]; +//quotient is 1.00000..00 need special dealt with in the following +assign ex3_rst_eq_1 = total_qt_rt_30[28] && ~|total_qt_rt_30[27:5]; +// for denormal result, first select the quotation num for rounding +// specially for the result e=-126 and e=-1022,the denorm depends on the +// MSB of the quotient +assign ex3_denorm_plus = !total_qt_rt_30[28] && (fdsu_ex3_expnt_rst[9:0] == 10'h382); +assign ex3_denorm_potnt_norm = total_qt_rt_30[28] && (fdsu_ex3_expnt_rst[9:0] == 10'h381); +assign ex3_rslt_denorm = ex3_denorm_plus || fdsu_ex3_rslt_denorm; +// &Force("output", "ex3_rslt_denorm"); @66 + +//denomal result, check for rounding further optimization can be done in +//future +// &CombBeg; @70 +always @( total_qt_rt_30[28:0] + or fdsu_ex3_expnt_rst[9:0]) +begin +case(fdsu_ex3_expnt_rst[9:0]) + 10'h382:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[4:0],23'b0}; //-126 1 + single_denorm_lst_frac = total_qt_rt_30[5]; + end//-1022 1 + 10'h381:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[5:0],22'b0}; //-127 0 + single_denorm_lst_frac = total_qt_rt_30[6]; + end//-1022 1 + 10'h380:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[6:0],21'b0}; //-128 -1 + single_denorm_lst_frac = total_qt_rt_30[7]; + end//-1022 1 + 10'h37f:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[7:0],20'b0}; //-129 -2 + single_denorm_lst_frac = total_qt_rt_30[8]; + end//-1022 1 + 10'h37e:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[8:0],19'b0}; //-130 -3 + single_denorm_lst_frac = total_qt_rt_30[9]; + end//-1022 1 + 10'h37d:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[9:0],18'b0}; //-131 -4 + single_denorm_lst_frac = total_qt_rt_30[10]; + end//-1022 1 + 10'h37c:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[10:0],17'b0}; //-132 -5 + single_denorm_lst_frac = total_qt_rt_30[11]; + end//-1022 1 + 10'h37b:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[11:0],16'b0}; //-133 -6 + single_denorm_lst_frac = total_qt_rt_30[12]; + end//-1022 1 + 10'h37a:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[12:0],15'b0}; //-134 -7 + single_denorm_lst_frac = total_qt_rt_30[13]; + end//-1022 1 + 10'h379:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[13:0],14'b0}; //-135 -8 + single_denorm_lst_frac = total_qt_rt_30[14]; + end//-1022 1 + 10'h378:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[14:0],13'b0}; //-136 -9 + single_denorm_lst_frac = total_qt_rt_30[15]; + end//-1022 1 + 10'h377:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[15:0],12'b0}; //-137 -10 + single_denorm_lst_frac = total_qt_rt_30[16]; + end//-1022 1 + 10'h376:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[16:0],11'b0}; //-138 -11 + single_denorm_lst_frac = total_qt_rt_30[17]; + end//-1022 1 + 10'h375:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[17:0],10'b0}; //-139 -12 + single_denorm_lst_frac = total_qt_rt_30[18]; + end//-1022 1 + 10'h374:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[18:0],9'b0}; //-140 -13 + single_denorm_lst_frac = total_qt_rt_30[19]; + end//-1022 1 + 10'h373:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[19:0],8'b0}; // -141 + single_denorm_lst_frac = total_qt_rt_30[20]; + end//-1022 1 + 10'h372:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[20:0],7'b0};//-142 + single_denorm_lst_frac = total_qt_rt_30[21]; + end//-1022 1 + 10'h371:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[21:0],6'b0};//-143 + single_denorm_lst_frac = total_qt_rt_30[22]; + end//-1022 1 + 10'h370:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[22:0],5'b0}; //-144 + single_denorm_lst_frac = total_qt_rt_30[23]; + end//-1022 1 + 10'h36f:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[23:0],4'b0}; //-145 + single_denorm_lst_frac = total_qt_rt_30[24]; + end//-1022 1 + 10'h36e:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[24:0],3'b0}; //-146 + single_denorm_lst_frac = total_qt_rt_30[25]; + end//-1022 1 + 10'h36d:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[25:0],2'b0}; //-147 + single_denorm_lst_frac = total_qt_rt_30[26]; + end//-1022 1 + 10'h36c:begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[26:0],1'b0}; //-148 + single_denorm_lst_frac = total_qt_rt_30[27]; + end//-1022 1 + 10'h36b: begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[27:0]}; + single_denorm_lst_frac = total_qt_rt_30[28] ; + end//-1022 1 + default: begin qt_result_single_denorm_for_round[27:0] = {total_qt_rt_30[28:1]}; + single_denorm_lst_frac = 1'b0; + end//-1022 1 +endcase +// &CombEnd; @148 +end +//rounding evaluation for single denormalize number +assign ex3_single_denorm_eq = qt_result_single_denorm_for_round[27] + && !ex3_single_low_not_zero; +assign ex3_single_low_not_zero = |qt_result_single_denorm_for_round[26:0]; +assign ex3_single_denorm_gr = qt_result_single_denorm_for_round[27] + && ex3_single_low_not_zero; +assign ex3_single_denorm_zero = !qt_result_single_denorm_for_round[27] + && !ex3_single_low_not_zero; + +//rounding check fo denormalize result +assign ex3_denorm_eq = ex3_single_denorm_eq; +assign ex3_denorm_gr = ex3_single_denorm_gr; +assign ex3_denorm_zero = ex3_single_denorm_zero; +assign ex3_denorm_lst_frac = single_denorm_lst_frac; +//Different Round Mode with different rounding rule +//Here we call rounding bit as "rb", remainder as "rem" +//RNE : +// 1.+1 : rb>10000 || rb==10000 && rem>0 +// 2. 0 : Rest Condition +// 3.-1 : Never occur +//RTZ : +// 1.+1 : Never occur +// 2. 0 : Rest Condition +// 3.-1 : rb=10000 && rem<0 +//RDN : +// 1.+1 : Q>0 Never occur ; Q<0 Rest condition +// 2. 0 : Q>0 Rest condition; Q<0 Rem<0 && rb=0 +// 3.-1 : Q>0 Rem<0 && rb=0 ; Q<0 Never occur +//RUP : +// 1.+1 : Q>0 Rest Condition; Q<0 Never occur +// 2. 0 : Q>0 Rem<0 && rb=0 ; Q<0 Rest condition +// 3.-1 : Q>0 Never occur ; Q<0 Rem<0 && rb=0 +//RMM : +// 1.+1 : rb>10000 || rb==10000 && rem>0 +// 2. 0 : Rest Condition +// 3.-1 : Never occur +assign frac_rne_add_1 = ex3_qt_gr || + (ex3_qt_eq && !fdsu_ex3_rem_sign); +assign frac_rtz_sub_1 = ex3_qt_zero && fdsu_ex3_rem_sign; +assign frac_rup_add_1 = !fdsu_ex3_result_sign && + (!ex3_qt_zero || + (!fdsu_ex3_rem_sign && !fdsu_ex3_rem_zero)); +assign frac_rup_sub_1 = fdsu_ex3_result_sign && + (ex3_qt_zero && fdsu_ex3_rem_sign); +assign frac_rdn_add_1 = fdsu_ex3_result_sign && + (!ex3_qt_zero || + (!fdsu_ex3_rem_sign && !fdsu_ex3_rem_zero)); +assign frac_rdn_sub_1 = !fdsu_ex3_result_sign && + (ex3_qt_zero && fdsu_ex3_rem_sign); +assign frac_rmm_add_1 = ex3_qt_gr || + (ex3_qt_eq && !fdsu_ex3_rem_sign); +//denormal result +assign frac_denorm_rne_add_1 = ex3_denorm_gr || + (ex3_denorm_eq && + ((fdsu_ex3_rem_zero && + ex3_denorm_lst_frac) || + (!fdsu_ex3_rem_zero && + !fdsu_ex3_rem_sign))); +assign frac_denorm_rtz_sub_1 = ex3_denorm_zero && fdsu_ex3_rem_sign; +assign frac_denorm_rup_add_1 = !fdsu_ex3_result_sign && + (!ex3_denorm_zero || + (!fdsu_ex3_rem_sign && !fdsu_ex3_rem_zero)); +assign frac_denorm_rup_sub_1 = fdsu_ex3_result_sign && + (ex3_denorm_zero && fdsu_ex3_rem_sign); +assign frac_denorm_rdn_add_1 = fdsu_ex3_result_sign && + (!ex3_denorm_zero || + (!fdsu_ex3_rem_sign && !fdsu_ex3_rem_zero)); +assign frac_denorm_rdn_sub_1 = !fdsu_ex3_result_sign && + (ex3_denorm_zero && fdsu_ex3_rem_sign); +assign frac_denorm_rmm_add_1 = ex3_denorm_gr || + (ex3_denorm_eq && !fdsu_ex3_rem_sign); + +//RM select +// &CombBeg; @222 +always @( fdsu_ex3_rm[2:0] + or frac_denorm_rdn_add_1 + or frac_rne_add_1 + or frac_denorm_rdn_sub_1 + or fdsu_ex3_result_sign + or frac_rup_add_1 + or frac_denorm_rup_sub_1 + or frac_rdn_sub_1 + or frac_rtz_sub_1 + or frac_rdn_add_1 + or fdsu_ex3_id_srt_skip + or frac_denorm_rtz_sub_1 + or ex3_rslt_denorm + or frac_rup_sub_1 + or frac_denorm_rmm_add_1 + or frac_denorm_rup_add_1 + or frac_denorm_rne_add_1 + or frac_rmm_add_1) +begin +case(fdsu_ex3_rm[2:0]) + 3'b000://round to nearst,ties to even + begin + frac_add_1 = ex3_rslt_denorm ? frac_denorm_rne_add_1 : frac_rne_add_1; + frac_sub_1 = 1'b0; + frac_orig = ex3_rslt_denorm ? !frac_denorm_rne_add_1 : !frac_rne_add_1; + denorm_to_tiny_frac = fdsu_ex3_id_srt_skip ? 1'b0 : frac_denorm_rne_add_1; + end + 3'b001:// round to 0 + begin + frac_add_1 = 1'b0; + frac_sub_1 = ex3_rslt_denorm ? frac_denorm_rtz_sub_1 : frac_rtz_sub_1; + frac_orig = ex3_rslt_denorm ? !frac_denorm_rtz_sub_1 : !frac_rtz_sub_1; + denorm_to_tiny_frac = 1'b0; + end + 3'b010://round to -inf + begin + frac_add_1 = ex3_rslt_denorm ? frac_denorm_rdn_add_1 : frac_rdn_add_1; + frac_sub_1 = ex3_rslt_denorm ? frac_denorm_rdn_sub_1 : frac_rdn_sub_1; + frac_orig = ex3_rslt_denorm ? !frac_denorm_rdn_add_1 && !frac_denorm_rdn_sub_1 + : !frac_rdn_add_1 && !frac_rdn_sub_1; + denorm_to_tiny_frac = fdsu_ex3_id_srt_skip ? fdsu_ex3_result_sign + : frac_denorm_rdn_add_1; + end + 3'b011://round to +inf + begin + frac_add_1 = ex3_rslt_denorm ? frac_denorm_rup_add_1 : frac_rup_add_1; + frac_sub_1 = ex3_rslt_denorm ? frac_denorm_rup_sub_1 : frac_rup_sub_1; + frac_orig = ex3_rslt_denorm ? !frac_denorm_rup_add_1 && !frac_denorm_rup_sub_1 + : !frac_rup_add_1 && !frac_rup_sub_1; + denorm_to_tiny_frac = fdsu_ex3_id_srt_skip ? !fdsu_ex3_result_sign + : frac_denorm_rup_add_1; + end + 3'b100://round to nearest,ties to max magnitude + begin + frac_add_1 = ex3_rslt_denorm ? frac_denorm_rmm_add_1 : frac_rmm_add_1; + frac_sub_1 = 1'b0; + frac_orig = ex3_rslt_denorm ? !frac_denorm_rmm_add_1 : !frac_rmm_add_1; + denorm_to_tiny_frac = fdsu_ex3_id_srt_skip ? 1'b0 : frac_denorm_rmm_add_1; + end + default: + begin + frac_add_1 = 1'b0; + frac_sub_1 = 1'b0; + frac_orig = 1'b0; + denorm_to_tiny_frac = 1'b0; + end +endcase +// &CombEnd; @271 +end +//Add 1 or Sub 1 constant +// &CombBeg; @273 +always @( total_qt_rt_30[28]) +begin +case(total_qt_rt_30[28]) + 1'b0: + begin + frac_add1_op1[25:0] = {2'b0,24'b1}; + frac_sub1_op1[25:0] = {2'b11,{24{1'b1}}}; + end + 1'b1: + begin + frac_add1_op1[25:0] = {25'b1,1'b0}; + frac_sub1_op1[25:0] = {{25{1'b1}},1'b0}; + end + default: + begin + frac_add1_op1[25:0] = 26'b0; + frac_sub1_op1[25:0] = 26'b0; + end +endcase +// &CombEnd; @291 +end + +//Add 1 or Sub1 final result +//Conner case when quotient is 0.010000...00 and remainder is negative, +//The real quotient is actually 0.00fff..ff, +//The final result will need to sub 1 when +//RN : Never occur +//RP : sign of quotient is - +//RM : sign of quotient is + +assign frac_add1_rst[25:0] = {1'b0,total_qt_rt_30[28:4]} + + frac_add1_op1_with_denorm[25:0]; +assign frac_add1_op1_with_denorm[25:0] = ex3_rslt_denorm ? + {1'b0,fdsu_ex3_result_denorm_round_add_num[23:0],1'b0} : + frac_add1_op1[25:0]; +assign frac_sub1_rst[25:0] = (ex3_rst_eq_1) + ? {3'b0,{23{1'b1}}} + : {1'b0,total_qt_rt_30[28:4]} + + frac_sub1_op1_with_denorm[25:0] + {25'b0, ex3_rslt_denorm}; +assign frac_sub1_op1_with_denorm[25:0] = ex3_rslt_denorm ? + ~{1'b0,fdsu_ex3_result_denorm_round_add_num[23:0],1'b0} : + frac_sub1_op1[25:0]; +assign frac_final_rst[25:0] = (frac_add1_rst[25:0] & {26{frac_add_1}}) | + (frac_sub1_rst[25:0] & {26{frac_sub_1}}) | + ({1'b0,total_qt_rt_30[28:4]} & {26{frac_orig}}); + +//===============Pipe down signal prepare=================== +// assign ex3_rst_nor = !fdsu_ex3_result_zero && +// !fdsu_ex3_result_qnan && +// !fdsu_ex3_result_inf && +// !fdsu_ex3_result_lfn; +assign ex3_rst_nor = !fdsu_ex3_result_inf && + !fdsu_ex3_result_lfn; +assign ex3_nx = ex3_rst_nor && + (!ex3_qt_zero || !fdsu_ex3_rem_zero || ex3_denorm_nx); +assign ex3_denorm_nx = ex3_rslt_denorm && (!ex3_denorm_zero || !fdsu_ex3_rem_zero); +//Adjust expnt +//Div:Actural expnt should plus 1 when op0 is id, sub 1 when op1 id +assign ex3_expnt_adjst[9:0] = 10'h7f; + +assign ex3_expnt_adjust_result[9:0] = fdsu_ex3_expnt_rst[9:0] + + ex3_expnt_adjst[9:0]; +//this information is for the packing, which determin the result is normal +//numer or not; +assign ex3_potnt_norm[1:0] = {ex3_denorm_plus,ex3_denorm_potnt_norm}; +//=======================Pipe to EX4======================== +//gate clk +// &Instance("gated_clk_cell","x_ex3_pipe_clk"); @337 +gated_clk_cell x_ex3_pipe_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex3_pipe_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex3_pipe_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @338 +// .clk_out (ex3_pipe_clk),//Out Clock @339 +// .external_en (1'b0), @340 +// .global_en (cp0_yy_clk_en), @341 +// .local_en (ex3_pipe_clk_en),//Local Condition @342 +// .module_en (cp0_fpu_icg_en) @343 +// ); @344 +assign ex3_pipe_clk_en = ex3_pipedown; + +always @(posedge ex3_pipe_clk) +begin + if(ex3_pipedown) + begin + fdsu_ex4_result_nor <= ex3_rst_nor; + fdsu_ex4_nx <= ex3_nx; + fdsu_ex4_denorm_to_tiny_frac + <= denorm_to_tiny_frac; + fdsu_ex4_potnt_norm[1:0] <= ex3_potnt_norm[1:0]; + end + else + begin + fdsu_ex4_result_nor <= fdsu_ex4_result_nor; + fdsu_ex4_nx <= fdsu_ex4_nx; + fdsu_ex4_denorm_to_tiny_frac + <= fdsu_ex4_denorm_to_tiny_frac; + fdsu_ex4_potnt_norm[1:0] <= fdsu_ex4_potnt_norm[1:0]; + end +end + +// ex3_frac Pipedown to ex4 use srt_divisor. +assign ex3_frac_final_rst[25:0] = frac_final_rst[25:0]; +// &Force("output","fdsu_ex4_result_nor"); @397 +// &Force("output","fdsu_ex4_nx"); @398 +// &Force("output","fdsu_ex4_denorm_to_tiny_frac"); @399 +// &Force("output","fdsu_ex4_potnt_norm"); @400 + + +// &ModuleEnd; @403 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_special.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_special.v new file mode 100644 index 0000000000000000000000000000000000000000..38aebd9df765f21ad400662ec06f51efd25b0d0c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_special.v @@ -0,0 +1,345 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_special( + cp0_fpu_xx_dqnan, + dp_xx_ex1_cnan, + dp_xx_ex1_id, + dp_xx_ex1_inf, + dp_xx_ex1_qnan, + dp_xx_ex1_snan, + dp_xx_ex1_zero, + ex1_div, + ex1_op0_id, + ex1_op0_norm, + ex1_op0_sign, + ex1_op1_id, + ex1_op1_norm, + ex1_result_sign, + ex1_sqrt, + ex1_srt_skip, + fdsu_fpu_ex1_fflags, + fdsu_fpu_ex1_special_sel, + fdsu_fpu_ex1_special_sign +); + +// &Ports; @24 +input cp0_fpu_xx_dqnan; +input [2:0] dp_xx_ex1_cnan; +input [2:0] dp_xx_ex1_id; +input [2:0] dp_xx_ex1_inf; +input [2:0] dp_xx_ex1_qnan; +input [2:0] dp_xx_ex1_snan; +input [2:0] dp_xx_ex1_zero; +input ex1_div; +input ex1_op0_sign; +input ex1_result_sign; +input ex1_sqrt; +output ex1_op0_id; +output ex1_op0_norm; +output ex1_op1_id; +output ex1_op1_norm; +output ex1_srt_skip; +output [4:0] fdsu_fpu_ex1_fflags; +output [7:0] fdsu_fpu_ex1_special_sel; +output [3:0] fdsu_fpu_ex1_special_sign; + +// &Regs; @25 +reg ex1_result_cnan; +reg ex1_result_qnan_op0; +reg ex1_result_qnan_op1; + +// &Wires; @26 +wire cp0_fpu_xx_dqnan; +wire [2:0] dp_xx_ex1_cnan; +wire [2:0] dp_xx_ex1_id; +wire [2:0] dp_xx_ex1_inf; +wire [2:0] dp_xx_ex1_qnan; +wire [2:0] dp_xx_ex1_snan; +wire [2:0] dp_xx_ex1_zero; +wire ex1_div; +wire ex1_div_dz; +wire ex1_div_nv; +wire ex1_div_rst_inf; +wire ex1_div_rst_qnan; +wire ex1_div_rst_zero; +wire ex1_dz; +wire [4:0] ex1_fflags; +wire ex1_nv; +wire ex1_op0_cnan; +wire ex1_op0_id; +wire ex1_op0_inf; +wire ex1_op0_is_qnan; +wire ex1_op0_is_snan; +wire ex1_op0_norm; +wire ex1_op0_qnan; +wire ex1_op0_sign; +wire ex1_op0_snan; +wire ex1_op0_tt_zero; +wire ex1_op0_zero; +wire ex1_op1_cnan; +wire ex1_op1_id; +wire ex1_op1_inf; +wire ex1_op1_is_qnan; +wire ex1_op1_is_snan; +wire ex1_op1_norm; +wire ex1_op1_qnan; +wire ex1_op1_snan; +wire ex1_op1_tt_zero; +wire ex1_op1_zero; +wire ex1_result_inf; +wire ex1_result_lfn; +wire ex1_result_qnan; +wire ex1_result_sign; +wire ex1_result_zero; +wire ex1_rst_default_qnan; +wire [7:0] ex1_special_sel; +wire [3:0] ex1_special_sign; +wire ex1_sqrt; +wire ex1_sqrt_nv; +wire ex1_sqrt_rst_inf; +wire ex1_sqrt_rst_qnan; +wire ex1_sqrt_rst_zero; +wire ex1_srt_skip; +wire [4:0] fdsu_fpu_ex1_fflags; +wire [7:0] fdsu_fpu_ex1_special_sel; +wire [3:0] fdsu_fpu_ex1_special_sign; + + +//infinity number +// &Force("bus", "dp_xx_ex1_inf", 2, 0); @29 +assign ex1_op0_inf = dp_xx_ex1_inf[0]; +assign ex1_op1_inf = dp_xx_ex1_inf[1]; + +//zero +// &Force("bus", "dp_xx_ex1_zero", 2, 0); @34 +assign ex1_op0_zero = dp_xx_ex1_zero[0]; +assign ex1_op1_zero = dp_xx_ex1_zero[1]; + +//denormalize number +// &Force("bus", "dp_xx_ex1_id", 2, 0); @39 +assign ex1_op0_id = dp_xx_ex1_id[0]; +assign ex1_op1_id = dp_xx_ex1_id[1]; + +//cNaN +// &Force("bus", "dp_xx_ex1_cnan", 2, 0); @44 +assign ex1_op0_cnan = dp_xx_ex1_cnan[0]; +assign ex1_op1_cnan = dp_xx_ex1_cnan[1]; + +//sNaN +// &Force("bus", "dp_xx_ex1_snan", 2, 0); @49 +assign ex1_op0_snan = dp_xx_ex1_snan[0]; +assign ex1_op1_snan = dp_xx_ex1_snan[1]; + +//qNaN +// &Force("bus", "dp_xx_ex1_qnan", 2, 0); @54 +assign ex1_op0_qnan = dp_xx_ex1_qnan[0]; +assign ex1_op1_qnan = dp_xx_ex1_qnan[1]; + + +//======================EX1 expt detect===================== +//ex1_id_detect +//any opration is zero +// no input denormalize exception anymore +// +//ex1_nv_detect +//div_nv +// 1.any operation is sNaN +// 2.0/0(include DN flush to zero) +// 3.inf/inf +//sqrt_nv +// 1.any operation is sNaN +// 2.operation sign is 1 && operation is not zero/qNaN +assign ex1_nv = ex1_div && ex1_div_nv || + ex1_sqrt && ex1_sqrt_nv; +//ex1_div_nv +assign ex1_div_nv = ex1_op0_snan || + ex1_op1_snan || + (ex1_op0_tt_zero && ex1_op1_tt_zero)|| + (ex1_op0_inf && ex1_op1_inf); +assign ex1_op0_tt_zero = ex1_op0_zero; +assign ex1_op1_tt_zero = ex1_op1_zero; +//ex1_sqrt_nv +assign ex1_sqrt_nv = ex1_op0_snan || + ex1_op0_sign && + (ex1_op0_norm || + ex1_op0_inf ); + +// This 'norm' also include denorm. +assign ex1_op0_norm = !ex1_op0_inf && !ex1_op0_zero && !ex1_op0_snan && !ex1_op0_qnan && !ex1_op0_cnan; +assign ex1_op1_norm = !ex1_op1_inf && !ex1_op1_zero && !ex1_op1_snan && !ex1_op1_qnan && !ex1_op1_cnan; + +//ex1_of_detect +//div_of +// 1.only detect id overflow case +//assign ex1_of = ex1_div && ex1_div_of; +//assign ex1_div_of = ex1_op1_id_fm1 && +// ex1_op0_norm && +// ex1_div_id_of; +// +////ex1_uf_detect +////div_uf +//// 1.only detect id underflow case +//assign ex1_uf = ex1_div && ex1_div_uf; +//assign ex1_div_uf = ex1_op0_id && +// ex1_op1_norm && +// ex1_div_id_uf; +//ex1_dz_detect +//div_dz +// 1.op0 is normal && op1 zero +assign ex1_dz = ex1_div && ex1_div_dz; +assign ex1_div_dz = ex1_op1_tt_zero && ex1_op0_norm; + +//===================special cal result===================== +//ex1 result is zero +//div_zero +// 1.op0 is zero && op1 is normal +// 2.op0 is zero/normal && op1 is inf +//sqrt_zero +// 1.op0 is zero +assign ex1_result_zero = ex1_div_rst_zero && ex1_div || + ex1_sqrt_rst_zero && ex1_sqrt; +assign ex1_div_rst_zero = (ex1_op0_tt_zero && ex1_op1_norm ) || + // (!ex1_expnt0_max && !ex1_op0_cnan && ex1_op1_inf); + (!ex1_op0_inf && !ex1_op0_qnan && !ex1_op0_snan && !ex1_op0_cnan && ex1_op1_inf); +assign ex1_sqrt_rst_zero = ex1_op0_tt_zero; + +//ex1 result is qNaN +//ex1_nv +//div_qnan +// 1.op0 is qnan || op1 is qnan +//sqrt_qnan +// 1.op0 is qnan +assign ex1_result_qnan = ex1_div_rst_qnan && ex1_div || + ex1_sqrt_rst_qnan && ex1_sqrt || + ex1_nv; +assign ex1_div_rst_qnan = ex1_op0_qnan || + ex1_op1_qnan; +assign ex1_sqrt_rst_qnan = ex1_op0_qnan; + +//ex1_rst_default_qnan +//0/0, inf/inf, sqrt negative should get default qNaN +assign ex1_rst_default_qnan = (ex1_div && ex1_op0_zero && ex1_op1_zero) || + (ex1_div && ex1_op0_inf && ex1_op1_inf) || + (ex1_sqrt&& ex1_op0_sign && (ex1_op0_norm || ex1_op0_inf)); + +//ex1 result is inf +//ex1_dz +// +//div_inf +// 1.op0 is inf && op1 is normal/zero +//sqrt_inf +// 1.op0 is inf +assign ex1_result_inf = ex1_div_rst_inf && ex1_div || + ex1_sqrt_rst_inf && ex1_sqrt || + ex1_dz ; +// assign ex1_div_rst_inf = ex1_op0_inf && !ex1_expnt1_max && !ex1_op1_cnan; +assign ex1_div_rst_inf = ex1_op0_inf && !ex1_op1_inf && !ex1_op1_qnan && !ex1_op1_snan && !ex1_op1_cnan; +assign ex1_sqrt_rst_inf = ex1_op0_inf && !ex1_op0_sign; + +//ex1 result is lfn +//ex1_of && round result toward not inc 1 +assign ex1_result_lfn = 1'b0; + +//Default_qnan/Standard_qnan Select +assign ex1_op0_is_snan = ex1_op0_snan; +assign ex1_op1_is_snan = ex1_op1_snan && ex1_div; +assign ex1_op0_is_qnan = ex1_op0_qnan; +assign ex1_op1_is_qnan = ex1_op1_qnan && ex1_div; + +// &CombBeg; @169 +always @( ex1_op0_is_snan + or ex1_op0_cnan + or ex1_result_qnan + or ex1_op0_is_qnan + or ex1_rst_default_qnan + or cp0_fpu_xx_dqnan + or ex1_op1_cnan + or ex1_op1_is_qnan + or ex1_op1_is_snan) +begin +if(ex1_rst_default_qnan) +begin + ex1_result_qnan_op0 = 1'b0; + ex1_result_qnan_op1 = 1'b0; + ex1_result_cnan = ex1_result_qnan; +end +else if(ex1_op0_is_snan && cp0_fpu_xx_dqnan) +begin + ex1_result_qnan_op0 = ex1_result_qnan; + ex1_result_qnan_op1 = 1'b0; + ex1_result_cnan = 1'b0; +end +else if(ex1_op1_is_snan && cp0_fpu_xx_dqnan) +begin + ex1_result_qnan_op0 = 1'b0; + ex1_result_qnan_op1 = ex1_result_qnan; + ex1_result_cnan = 1'b0; +end +else if(ex1_op0_is_qnan && cp0_fpu_xx_dqnan) +begin + ex1_result_qnan_op0 = ex1_result_qnan && !ex1_op0_cnan; + ex1_result_qnan_op1 = 1'b0; + ex1_result_cnan = ex1_result_qnan && ex1_op0_cnan; +end +else if(ex1_op1_is_qnan && cp0_fpu_xx_dqnan) +begin + ex1_result_qnan_op0 = 1'b0; + ex1_result_qnan_op1 = ex1_result_qnan && !ex1_op1_cnan; + ex1_result_cnan = ex1_result_qnan && ex1_op1_cnan; +end +else +begin + ex1_result_qnan_op0 = 1'b0; + ex1_result_qnan_op1 = 1'b0; + ex1_result_cnan = ex1_result_qnan; +end +// &CombEnd; @206 +end + + +//Special result should skip SRT logic +assign ex1_srt_skip = ex1_result_zero || + ex1_result_qnan || + ex1_result_lfn || + ex1_result_inf; +// fflags: +// NV, DZ, OF, UF, NX +assign ex1_fflags[4:0] = {ex1_nv, ex1_dz, 3'b0}; +// Special Sel[7:0]: +// qnan_src2, qnan_src1, qnan_src0, cnan, lfn, inf, zero, src2 +assign ex1_special_sel[7:0] = {1'b0, ex1_result_qnan_op1, ex1_result_qnan_op0, + ex1_result_cnan, ex1_result_lfn, ex1_result_inf, + ex1_result_zero, 1'b0}; +// Special Sign[3:0] +// lfn, inf, zero, src2 +assign ex1_special_sign[3:0] = {ex1_result_sign, ex1_result_sign, ex1_result_sign, 1'b0}; + +//========================================================== +// Output Signal +//========================================================== +assign fdsu_fpu_ex1_fflags[4:0] = ex1_fflags[4:0]; +assign fdsu_fpu_ex1_special_sel[7:0] = ex1_special_sel[7:0]; +assign fdsu_fpu_ex1_special_sign[3:0] = ex1_special_sign[3:0]; + +// &Force("output", "ex1_op0_norm"); @233 +// &Force("output", "ex1_op1_norm"); @234 + +// &ModuleEnd; @236 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_srt_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_srt_single.v new file mode 100644 index 0000000000000000000000000000000000000000..8d947f8f990846d91639b28866a7c624c7dd872e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_srt_single.v @@ -0,0 +1,824 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_srt_single( + cp0_fpu_icg_en, + cp0_yy_clk_en, + ex1_divisor, + ex1_expnt_adder_op1, + ex1_oper_id_frac, + ex1_oper_id_frac_f, + ex1_pipedown, + ex1_pipedown_gate, + ex1_remainder, + ex1_save_op0, + ex1_save_op0_gate, + ex2_expnt_adder_op0, + ex2_of, + ex2_pipe_clk, + ex2_pipedown, + ex2_potnt_of, + ex2_potnt_uf, + ex2_result_inf, + ex2_result_lfn, + ex2_rslt_denorm, + ex2_srt_expnt_rst, + ex2_srt_first_round, + ex2_uf, + ex2_uf_srt_skip, + ex3_frac_final_rst, + ex3_pipedown, + fdsu_ex3_id_srt_skip, + fdsu_ex3_rem_sign, + fdsu_ex3_rem_zero, + fdsu_ex3_result_denorm_round_add_num, + fdsu_ex4_frac, + fdsu_yy_div, + fdsu_yy_of_rm_lfn, + fdsu_yy_op0_norm, + fdsu_yy_op1_norm, + fdsu_yy_sqrt, + forever_cpuclk, + pad_yy_icg_scan_en, + srt_remainder_zero, + srt_sm_on, + total_qt_rt_30 +); + +// &Ports; @24 +input cp0_fpu_icg_en; +input cp0_yy_clk_en; +input [23:0] ex1_divisor; +input [12:0] ex1_expnt_adder_op1; +input [51:0] ex1_oper_id_frac; +input ex1_pipedown; +input ex1_pipedown_gate; +input [31:0] ex1_remainder; +input ex1_save_op0; +input ex1_save_op0_gate; +input [9 :0] ex2_expnt_adder_op0; +input ex2_pipe_clk; +input ex2_pipedown; +input ex2_srt_first_round; +input [25:0] ex3_frac_final_rst; +input ex3_pipedown; +input fdsu_yy_div; +input fdsu_yy_of_rm_lfn; +input fdsu_yy_op0_norm; +input fdsu_yy_op1_norm; +input fdsu_yy_sqrt; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input srt_sm_on; +output [51:0] ex1_oper_id_frac_f; +output ex2_of; +output ex2_potnt_of; +output ex2_potnt_uf; +output ex2_result_inf; +output ex2_result_lfn; +output ex2_rslt_denorm; +output [9 :0] ex2_srt_expnt_rst; +output ex2_uf; +output ex2_uf_srt_skip; +output fdsu_ex3_id_srt_skip; +output fdsu_ex3_rem_sign; +output fdsu_ex3_rem_zero; +output [23:0] fdsu_ex3_result_denorm_round_add_num; +output [25:0] fdsu_ex4_frac; +output srt_remainder_zero; +output [29:0] total_qt_rt_30; + +// &Regs; @25 +reg [31:0] cur_rem; +reg [7 :0] digit_bound_1; +reg [7 :0] digit_bound_2; +reg [23:0] ex2_result_denorm_round_add_num; +reg fdsu_ex3_id_srt_skip; +reg fdsu_ex3_rem_sign; +reg fdsu_ex3_rem_zero; +reg [23:0] fdsu_ex3_result_denorm_round_add_num; +reg [29:0] qt_rt_const_shift_std; +reg [7 :0] qtrt_sel_rem; +reg [31:0] rem_add1_op1; +reg [31:0] rem_add2_op1; +reg [25:0] srt_divisor; +reg [31:0] srt_remainder; +reg [29:0] total_qt_rt_30; +reg [29:0] total_qt_rt_30_next; +reg [29:0] total_qt_rt_minus_30; +reg [29:0] total_qt_rt_minus_30_next; + +// &Wires; @26 +wire [7 :0] bound1_cmp_result; +wire bound1_cmp_sign; +wire [7 :0] bound2_cmp_result; +wire bound2_cmp_sign; +wire [3 :0] bound_sel; +wire cp0_fpu_icg_en; +wire cp0_yy_clk_en; +wire [31:0] cur_doub_rem_1; +wire [31:0] cur_doub_rem_2; +wire [31:0] cur_rem_1; +wire [31:0] cur_rem_2; +wire [31:0] div_qt_1_rem_add_op1; +wire [31:0] div_qt_2_rem_add_op1; +wire [31:0] div_qt_r1_rem_add_op1; +wire [31:0] div_qt_r2_rem_add_op1; +wire [23:0] ex1_divisor; +wire ex1_ex2_pipe_clk; +wire ex1_ex2_pipe_clk_en; +wire [12:0] ex1_expnt_adder_op1; +wire [51:0] ex1_oper_id_frac; +wire [51:0] ex1_oper_id_frac_f; +wire ex1_pipedown; +wire ex1_pipedown_gate; +wire [31:0] ex1_remainder; +wire ex1_save_op0; +wire ex1_save_op0_gate; +wire ex2_div_of; +wire ex2_div_uf; +wire [9 :0] ex2_expnt_adder_op0; +wire [9 :0] ex2_expnt_adder_op1; +wire ex2_expnt_of; +wire [9 :0] ex2_expnt_result; +wire ex2_expnt_uf; +wire ex2_id_nor_srt_skip; +wire ex2_of; +wire ex2_of_plus; +wire ex2_pipe_clk; +wire ex2_pipedown; +wire ex2_potnt_of; +wire ex2_potnt_of_pre; +wire ex2_potnt_uf; +wire ex2_potnt_uf_pre; +wire ex2_result_inf; +wire ex2_result_lfn; +wire ex2_rslt_denorm; +wire [9 :0] ex2_sqrt_expnt_result; +wire [9 :0] ex2_srt_expnt_rst; +wire ex2_srt_first_round; +wire ex2_uf; +wire ex2_uf_plus; +wire ex2_uf_srt_skip; +wire [25:0] ex3_frac_final_rst; +wire ex3_pipedown; +wire fdsu_ex2_div; +wire [9 :0] fdsu_ex2_expnt_rst; +wire fdsu_ex2_of_rm_lfn; +wire fdsu_ex2_op0_norm; +wire fdsu_ex2_op1_norm; +wire fdsu_ex2_result_lfn; +wire fdsu_ex2_sqrt; +wire [25:0] fdsu_ex4_frac; +wire fdsu_yy_div; +wire fdsu_yy_of_rm_lfn; +wire fdsu_yy_op0_norm; +wire fdsu_yy_op1_norm; +wire fdsu_yy_sqrt; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; +wire qt_clk; +wire qt_clk_en; +wire [29:0] qt_rt_const_pre_sel_q1; +wire [29:0] qt_rt_const_pre_sel_q2; +wire [29:0] qt_rt_const_q1; +wire [29:0] qt_rt_const_q2; +wire [29:0] qt_rt_const_q3; +wire [29:0] qt_rt_const_shift_std_next; +wire [29:0] qt_rt_mins_const_pre_sel_q1; +wire [29:0] qt_rt_mins_const_pre_sel_q2; +wire rem_sign; +wire [31:0] sqrt_qt_1_rem_add_op1; +wire [31:0] sqrt_qt_2_rem_add_op1; +wire [31:0] sqrt_qt_r1_rem_add_op1; +wire [31:0] sqrt_qt_r2_rem_add_op1; +wire srt_div_clk; +wire srt_div_clk_en; +wire [31:0] srt_remainder_nxt; +wire [31:0] srt_remainder_shift; +wire srt_remainder_sign; +wire srt_remainder_zero; +wire srt_sm_on; +wire [29:0] total_qt_rt_pre_sel; + + +assign fdsu_ex2_div = fdsu_yy_div; +assign fdsu_ex2_sqrt = fdsu_yy_sqrt; +assign fdsu_ex2_op0_norm = fdsu_yy_op0_norm; +assign fdsu_ex2_op1_norm = fdsu_yy_op1_norm; +assign fdsu_ex2_of_rm_lfn = fdsu_yy_of_rm_lfn; +assign fdsu_ex2_result_lfn = 1'b0; + +//========================================================== +// EX2 Expnt Generate +//========================================================== +//expnt0 sub expnt1 +assign ex2_expnt_result[9:0] = ex2_expnt_adder_op0[9:0] - + ex2_expnt_adder_op1[9:0]; + +//===================sqrt exponent prepare================== +//sqrt exponent prepare +//afert E sub, div E by 2 +assign ex2_sqrt_expnt_result[9:0] = {ex2_expnt_result[9], + ex2_expnt_result[9:1]}; + +assign ex2_srt_expnt_rst[9:0] = (fdsu_ex2_sqrt) + ? ex2_sqrt_expnt_result[9:0] + : ex2_expnt_result[9:0]; +// &Force("output", "ex2_srt_expnt_rst"); &Force("bus", "ex2_srt_expnt_rst", 9, 0); @51 +assign fdsu_ex2_expnt_rst[9:0] = ex2_srt_expnt_rst[9:0]; + + +//====================EX2 Expt info========================= +//EX1 only detect of/uf under id condition +//EX2 will deal with other condition + +//When input is normal, overflow when E1-E2 > 128/1024 +assign ex2_expnt_of = ~fdsu_ex2_expnt_rst[9] && (fdsu_ex2_expnt_rst[8] + || (fdsu_ex2_expnt_rst[7] && + |fdsu_ex2_expnt_rst[6:0])); +//potential overflow when E1-E2 = 128/1024 +assign ex2_potnt_of_pre = ~fdsu_ex2_expnt_rst[9] && + ~fdsu_ex2_expnt_rst[8] && + fdsu_ex2_expnt_rst[7] && + ~|fdsu_ex2_expnt_rst[6:0]; +assign ex2_potnt_of = ex2_potnt_of_pre && + fdsu_ex2_op0_norm && + fdsu_ex2_op1_norm && + fdsu_ex2_div; + +//When input is normal, underflow when E1-E2 <= -127/-1023 +assign ex2_expnt_uf = fdsu_ex2_expnt_rst[9] &&(fdsu_ex2_expnt_rst[8:0] <= 9'h181); +//potential underflow when E1-E2 = -126/-1022 +assign ex2_potnt_uf_pre = &fdsu_ex2_expnt_rst[9:7] && + ~|fdsu_ex2_expnt_rst[6:2] && + fdsu_ex2_expnt_rst[1] && + !fdsu_ex2_expnt_rst[0]; +assign ex2_potnt_uf = (ex2_potnt_uf_pre && + fdsu_ex2_op0_norm && + fdsu_ex2_op1_norm && + fdsu_ex2_div) || + (ex2_potnt_uf_pre && + fdsu_ex2_op0_norm); + +//========================EX2 Overflow====================== +//ex2 overflow when +// 1.op0 & op1 both norm && expnt overflow +// 2.ex1_id_of +// &Force("output","ex2_of"); @91 +assign ex2_of = ex2_of_plus; +assign ex2_of_plus = ex2_div_of && fdsu_ex2_div; +assign ex2_div_of = fdsu_ex2_op0_norm && + fdsu_ex2_op1_norm && + ex2_expnt_of; + +//=======================EX2 Underflow====================== +//ex2 underflow when +// 1.op0 & op1 both norm && expnt underflow +// 2.ex1_id_uf +// and detect when to skip the srt, here, we have further optmization +assign ex2_uf = ex2_uf_plus; +assign ex2_uf_plus = ex2_div_uf && fdsu_ex2_div; +assign ex2_div_uf = fdsu_ex2_op0_norm && + fdsu_ex2_op1_norm && + ex2_expnt_uf; +assign ex2_id_nor_srt_skip = fdsu_ex2_expnt_rst[9] + && (fdsu_ex2_expnt_rst[8:0]<9'h16a); +assign ex2_uf_srt_skip = ex2_id_nor_srt_skip; +assign ex2_rslt_denorm = ex2_uf; +//===============ex2 round prepare for denormal round====== +// &CombBeg; @113 +always @( fdsu_ex2_expnt_rst[9:0]) +begin +case(fdsu_ex2_expnt_rst[9:0]) + 10'h382:ex2_result_denorm_round_add_num[23:0] = 24'h1; //-126 1 + 10'h381:ex2_result_denorm_round_add_num[23:0] = 24'h2; //-127 0 + 10'h380:ex2_result_denorm_round_add_num[23:0] = 24'h4; //-128 -1 + 10'h37f:ex2_result_denorm_round_add_num[23:0] = 24'h8; //-129 -2 + 10'h37e:ex2_result_denorm_round_add_num[23:0] = 24'h10; //-130 -3 + 10'h37d:ex2_result_denorm_round_add_num[23:0] = 24'h20; //-131 -4 + 10'h37c:ex2_result_denorm_round_add_num[23:0] = 24'h40; //-132 -5 + 10'h37b:ex2_result_denorm_round_add_num[23:0] = 24'h80; //-133 -6 + 10'h37a:ex2_result_denorm_round_add_num[23:0] = 24'h100; //-134 -7 + 10'h379:ex2_result_denorm_round_add_num[23:0] = 24'h200; //-135 -8 + 10'h378:ex2_result_denorm_round_add_num[23:0] = 24'h400; //-136 -9 + 10'h377:ex2_result_denorm_round_add_num[23:0] = 24'h800; //-137 -10 + 10'h376:ex2_result_denorm_round_add_num[23:0] = 24'h1000; //-138 -11 + 10'h375:ex2_result_denorm_round_add_num[23:0] = 24'h2000; //-139 -12 + 10'h374:ex2_result_denorm_round_add_num[23:0] = 24'h4000; //-140 -13 + 10'h373:ex2_result_denorm_round_add_num[23:0] = 24'h8000; // -141 -14 + 10'h372:ex2_result_denorm_round_add_num[23:0] = 24'h10000;//-142 -15 + 10'h371:ex2_result_denorm_round_add_num[23:0] = 24'h20000;//-143 -16 + 10'h370:ex2_result_denorm_round_add_num[23:0] = 24'h40000; //-144 -17 + 10'h36f:ex2_result_denorm_round_add_num[23:0] = 24'h80000; //-145 -18 + 10'h36e:ex2_result_denorm_round_add_num[23:0] = 24'h100000; //-146 -19 + 10'h36d:ex2_result_denorm_round_add_num[23:0] = 24'h200000; //-147 -20 + 10'h36c:ex2_result_denorm_round_add_num[23:0] = 24'h400000; //-148 -21 + 10'h36b:ex2_result_denorm_round_add_num[23:0] = 24'h800000; //-148 -22 + default: ex2_result_denorm_round_add_num[23:0] = 24'h0; // -23 +endcase +// &CombEnd; @141 +end + +//===================special result======================== +assign ex2_result_inf = ex2_of_plus && !fdsu_ex2_of_rm_lfn; +assign ex2_result_lfn = fdsu_ex2_result_lfn || + ex2_of_plus && fdsu_ex2_of_rm_lfn; + + + +//====================Pipe to EX3=========================== +always @(posedge ex1_ex2_pipe_clk) +begin + if(ex1_pipedown) + begin + fdsu_ex3_result_denorm_round_add_num[23:0] + <= {14'b0, ex1_expnt_adder_op1[9:0]}; + end + else if(ex2_pipedown) + begin + fdsu_ex3_result_denorm_round_add_num[23:0] + <= ex2_result_denorm_round_add_num[23:0]; + end + else + begin + fdsu_ex3_result_denorm_round_add_num[23:0] + <= fdsu_ex3_result_denorm_round_add_num[23:0]; + end +end +assign ex2_expnt_adder_op1 = fdsu_ex3_result_denorm_round_add_num[9:0]; +// &Force("bus", "ex1_expnt_adder_op1", 12, 0); @193 + +assign ex1_ex2_pipe_clk_en = ex1_pipedown_gate || ex2_pipedown; +// &Instance("gated_clk_cell", "x_ex1_ex2_pipe_clk"); @196 +gated_clk_cell x_ex1_ex2_pipe_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex1_ex2_pipe_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex1_ex2_pipe_clk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @197 +// .external_en (1'b0), @198 +// .global_en (cp0_yy_clk_en), @199 +// .module_en (cp0_fpu_icg_en), @200 +// .local_en (ex1_ex2_pipe_clk_en), @201 +// .clk_out (ex1_ex2_pipe_clk)); @202 + +always @(posedge ex2_pipe_clk) +begin + if(ex2_pipedown) + begin + fdsu_ex3_rem_sign <= srt_remainder_sign; + fdsu_ex3_rem_zero <= srt_remainder_zero; + fdsu_ex3_id_srt_skip <= ex2_id_nor_srt_skip; + end + else + begin + fdsu_ex3_rem_sign <= fdsu_ex3_rem_sign; + fdsu_ex3_rem_zero <= fdsu_ex3_rem_zero; + fdsu_ex3_id_srt_skip <= fdsu_ex3_id_srt_skip; + end +end + +// &Force("output","fdsu_ex3_rem_sign"); @243 +// &Force("output","fdsu_ex3_rem_zero"); @244 +// &Force("output","fdsu_ex3_result_denorm_round_add_num"); @245 +// &Force("output","fdsu_ex3_id_srt_skip"); @246 + +//========================================================== +// SRT Remainder & Divisor for Quotient/Root Generate +//========================================================== + +//===================Remainder Generate===================== +//gate clk +// &Instance("gated_clk_cell","x_srt_rem_clk"); +// // &Connect( .clk_in (forever_cpuclk), @255 +// // .clk_out (srt_rem_clk),//Out Clock @256 +// // .external_en (1'b0), @257 +// // .global_en (cp0_yy_clk_en), @258 +// // .local_en (srt_rem_clk_en),//Local Condition @259 +// // .module_en (cp0_fpu_icg_en) @260 +// // ); @261 +// assign srt_rem_clk_en = ex1_pipedown || +// srt_sm_on; + +always @(posedge qt_clk) +begin + if (ex1_pipedown) + srt_remainder[31:0] <= ex1_remainder[31:0]; + else if (srt_sm_on) + srt_remainder[31:0] <= srt_remainder_nxt[31:0]; + else + srt_remainder[31:0] <= srt_remainder[31:0]; +end + +//=====================Divisor Generate===================== +//gate clk +// &Instance("gated_clk_cell","x_srt_div_clk"); @291 +gated_clk_cell x_srt_div_clk ( + .clk_in (forever_cpuclk ), + .clk_out (srt_div_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (srt_div_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @292 +// .clk_out (srt_div_clk),//Out Clock @293 +// .external_en (1'b0), @294 +// .global_en (cp0_yy_clk_en), @295 +// .local_en (srt_div_clk_en),//Local Condition @296 +// .module_en (cp0_fpu_icg_en) @297 +// ); @298 +assign srt_div_clk_en = ex1_pipedown_gate + || ex1_save_op0_gate + || ex3_pipedown; +// final_rst saved in srt_divisor. +// srt_divisor is 26 bits, final_rst is 24 bits. +always @(posedge srt_div_clk) +begin + if (ex1_save_op0) + srt_divisor[25:0] <= {3'b0, {ex1_oper_id_frac[51:29]}}; + else if (ex1_pipedown) + srt_divisor[25:0] <= {2'b0, ex1_divisor[23:0]}; + else if (ex3_pipedown) + srt_divisor[25:0] <= ex3_frac_final_rst[25:0]; + else + srt_divisor[25:0] <= srt_divisor[25:0]; +end +assign ex1_oper_id_frac_f[51:0] = {srt_divisor[22:0], 29'b0}; +// &Force("bus", "ex1_oper_id_frac", 51, 0); @332 +assign fdsu_ex4_frac[25:0] = srt_divisor[25:0]; + +//=======================Bound Select======================= +//---------------------------------------+ +// K | 8 | 9 | 10| 11| 12| 13| 14|15,16| +//---------------------------------------+ +//32S1 | 7 | 7 | 8 | 9 | 9 | 10| 11| 12 | +//---------------------------------------+ +//32S2 | 25| 28| 31| 33| 36| 39| 41| 47 | +//---------------------------------------+ + +//bound_sel[3:0] +//For div, use divisor high four bit as K +//For sqrt, use 2qi high four bit as K next round and +// use 1010 as K first round +assign bound_sel[3:0] = (fdsu_ex2_div) + ? srt_divisor[23:20] + : (ex2_srt_first_round) + ? 4'b1010 + : total_qt_rt_30[28:25]; +//Select bound as look up table +// K = bound_sel[3:0] +//32S1 = digit_bound_1[7:0] +//32s2 = digit_bound_2[7:0] +// &CombBeg; @357 +always @( bound_sel[3:0]) +begin +case(bound_sel[3:0]) +4'b0000: //when first interation get "10", choose k=16 + begin + digit_bound_1[7:0] = 8'b11110100;//-12 + digit_bound_2[7:0] = 8'b11010001;//-47 + end +4'b1000: + begin + digit_bound_1[7:0] = 8'b11111001;//-7 + digit_bound_2[7:0] = 8'b11100111;//-25 + end +4'b1001: + begin + digit_bound_1[7:0] = 8'b11111001;//-7 + digit_bound_2[7:0] = 8'b11100100;//-28 + end +4'b1010: + begin + digit_bound_1[7:0] = 8'b11111000;//-8 + digit_bound_2[7:0] = 8'b11100001;//-31 + end +4'b1011: + begin + digit_bound_1[7:0] = 8'b11110111;//-9 + digit_bound_2[7:0] = 8'b11011111;//-33 + end +4'b1100: + begin + digit_bound_1[7:0] = 8'b11110111;//-9 + digit_bound_2[7:0] = 8'b11011100;//-36 + end +4'b1101: + begin + digit_bound_1[7:0] = 8'b11110110;//-10 + digit_bound_2[7:0] = 8'b11011001;//-39 + end +4'b1110: + begin + digit_bound_1[7:0] = 8'b11110101;//-11 + digit_bound_2[7:0] = 8'b11010111;//-41 + end +4'b1111: + begin + digit_bound_1[7:0] = 8'b11110100;//-12 + digit_bound_2[7:0] = 8'b11010001;//-47 + end +default: + begin + digit_bound_1[7:0] = 8'b11111001;//-7 + digit_bound_2[7:0] = 8'b11100111;//-25 + end +endcase +// &CombEnd; @410 +end + +//==============Prepare for quotient generate=============== +assign bound1_cmp_result[7:0] = qtrt_sel_rem[7:0] + digit_bound_1[7:0]; +assign bound2_cmp_result[7:0] = qtrt_sel_rem[7:0] + digit_bound_2[7:0]; +assign bound1_cmp_sign = bound1_cmp_result[7]; +assign bound2_cmp_sign = bound2_cmp_result[7]; +assign rem_sign = srt_remainder[29]; + +//qtrt_sel_rem is use to select quotient +//Only when sqrt first round use 8R0 select quotient(special rule) +//4R0 is used to select quotient on other condition +//For negative remaider, we use ~rem not (~rem + 1) +//Because bound1 <= rem < bound2, when positive rem +// -bound2 <= rem < -bound1, when negative rem +//Thus bound1 < -rem <= bound2, when negative rem +//Thus bound1 <= -rem-1 < bound2, when negative rem +//Thus bound1 <= ~rem < bound2, when negative rem +//srt_remainder[29] used as sign bit +// &CombBeg; @429 +always @( ex2_srt_first_round + or fdsu_ex2_sqrt + or srt_remainder[29:21]) +begin +if(ex2_srt_first_round && fdsu_ex2_sqrt) + qtrt_sel_rem[7:0] = {srt_remainder[29], srt_remainder[27:21]}; +else + qtrt_sel_rem[7:0] = srt_remainder[29] ? ~srt_remainder[29:22] + : srt_remainder[29:22]; +// &CombEnd; @435 +end + +//========================================================== +// on fly round method to generate total quotient +//========================================================== +//gate clk +// &Instance("gated_clk_cell","x_qt_clk"); @441 +gated_clk_cell x_qt_clk ( + .clk_in (forever_cpuclk ), + .clk_out (qt_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (qt_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @442 +// .clk_out (qt_clk),//Out Clock @443 +// .external_en (1'b0), @444 +// .global_en (cp0_yy_clk_en), @445 +// .local_en (qt_clk_en),//Local Condition @446 +// .module_en (cp0_fpu_icg_en) @447 +// ); @448 +assign qt_clk_en = srt_sm_on || + ex1_pipedown_gate; + +//qt_rt_const_shift_std[29:0] is const data for on fly round +// which is used to record the times of round +// +//total_qt_rt[29:0] is total quotient +//total_qt_rt_minus[29:0] is total quotient minus +// which is used to generate quotient rapidly +always @(posedge qt_clk) +begin + if(ex1_pipedown) + begin + qt_rt_const_shift_std[29:0] <= {1'b0,1'b1,28'b0}; + total_qt_rt_30[29:0] <= 30'b0; + total_qt_rt_minus_30[29:0] <= 30'b0; + end + else if(srt_sm_on) + begin + qt_rt_const_shift_std[29:0] <= qt_rt_const_shift_std_next[29:0]; + total_qt_rt_30[29:0] <= total_qt_rt_30_next[29:0]; + total_qt_rt_minus_30[29:0] <= total_qt_rt_minus_30_next[29:0]; + end + else + begin + qt_rt_const_shift_std[29:0] <= qt_rt_const_shift_std[29:0]; + total_qt_rt_30[29:0] <= total_qt_rt_30[29:0]; + total_qt_rt_minus_30[29:0] <= total_qt_rt_minus_30[29:0]; + end +end +// &Force("output","total_qt_rt_30"); @508 + +//qt_rt_const_q1/q2/q3 for shift 1/2/3 in +assign qt_rt_const_q1[29:0] = qt_rt_const_shift_std[29:0]; +assign qt_rt_const_q2[29:0] = {qt_rt_const_shift_std[28:0],1'b0}; +assign qt_rt_const_q3[29:0] = qt_rt_const_q1[29:0] | + qt_rt_const_q2[29:0]; +//qt_rt_const update value +assign qt_rt_const_shift_std_next[29:0] = {2'b0, qt_rt_const_shift_std[29:2]}; + +//========total_qt_rt & total_qt_rt_minus update value====== +//q(i+1) is the total quotient/root after the (i+1) digit +//is calculated +// q(i+1) qm(i+1) +//d(i+1)=-2 qm(i)+2*shift qm(i)+1*shift +//d(i+1)=-1 qm(i)+3*shift qm(i)+2*shift +//d(i+1)=0 q(i) qm(i)+3*shift +//d(i+1)=1 q(i)+1*shift q(i) +//d(i+1)=2 q(i)+2*shift q(i)+1*shift +//Note: +//shift = 4^(-i-1), qm(i+1)=q(i+1)-shift + +//pre select for quotient +assign total_qt_rt_pre_sel[29:0] = (rem_sign) ? + total_qt_rt_minus_30[29:0] : + total_qt_rt_30[29:0]; +//when the quotient is 2 or -2 +assign qt_rt_const_pre_sel_q2[29:0] = qt_rt_const_q2[29:0]; +assign qt_rt_mins_const_pre_sel_q2[29:0] = qt_rt_const_q1[29:0]; +//when the quotient is 1 or -1 +assign qt_rt_const_pre_sel_q1[29:0] = (rem_sign) ? + qt_rt_const_q3[29:0] ://-1 + qt_rt_const_q1[29:0]; //1 +assign qt_rt_mins_const_pre_sel_q1[29:0] = (rem_sign) ? + qt_rt_const_q2[29:0] : //-1 + 30'b0; + +//After bound compare, the final selection +// &CombBeg; @546 +always @( qt_rt_const_q3[29:0] + or qt_rt_mins_const_pre_sel_q1[29:0] + or bound1_cmp_sign + or total_qt_rt_30[29:0] + or qt_rt_mins_const_pre_sel_q2[29:0] + or total_qt_rt_minus_30[29:0] + or bound2_cmp_sign + or qt_rt_const_pre_sel_q2[29:0] + or qt_rt_const_pre_sel_q1[29:0] + or total_qt_rt_pre_sel[29:0]) +begin +casez({bound1_cmp_sign,bound2_cmp_sign}) + 2'b00:// the quotient is -2 or 2 + begin + total_qt_rt_30_next[29:0] = total_qt_rt_pre_sel[29:0] | + qt_rt_const_pre_sel_q2[29:0]; + total_qt_rt_minus_30_next[29:0] = total_qt_rt_pre_sel[29:0] | + qt_rt_mins_const_pre_sel_q2[29:0]; + end + 2'b01:// quotient is -1 or 1 + begin + total_qt_rt_30_next[29:0] = total_qt_rt_pre_sel[29:0] | + qt_rt_const_pre_sel_q1[29:0]; + total_qt_rt_minus_30_next[29:0] = total_qt_rt_pre_sel[29:0] | + qt_rt_mins_const_pre_sel_q1[29:0]; + end + 2'b1?: // quotient is 0 + begin + total_qt_rt_30_next[29:0] = total_qt_rt_30[29:0]; + total_qt_rt_minus_30_next[29:0] = total_qt_rt_minus_30[29:0] | + qt_rt_const_q3[29:0]; + end + default: + begin + total_qt_rt_30_next[29:0] = 30'b0; + total_qt_rt_minus_30_next[29:0] = 30'b0; + end +endcase +// &CombEnd; @574 +end + +//========================================================== +// on fly round method to generate cur remainder +//========================================================== +//Division emainder add value +//Quoit 1 +assign div_qt_1_rem_add_op1[31:0] = ~{3'b0,srt_divisor[23:0],5'b0}; +//Quoit 2 +assign div_qt_2_rem_add_op1[31:0] = ~{2'b0,srt_divisor[23:0],6'b0}; +//Quoit -1 +assign div_qt_r1_rem_add_op1[31:0] = {3'b0,srt_divisor[23:0],5'b0}; +//Quoit -2 +assign div_qt_r2_rem_add_op1[31:0] = {2'b0,srt_divisor[23:0],6'b0}; + +//Sqrt remainder add value op1 +//Quoit 1 +assign sqrt_qt_1_rem_add_op1[31:0] = ~({2'b0,total_qt_rt_30[29:0]} | + {3'b0,qt_rt_const_q1[29:1]}); +//Quoit 2 +assign sqrt_qt_2_rem_add_op1[31:0] = ~({1'b0,total_qt_rt_30[29:0],1'b0} | + {1'b0,qt_rt_const_q1[29:0],1'b0}); +//Quoit -1 +assign sqrt_qt_r1_rem_add_op1[31:0] = {2'b0,total_qt_rt_minus_30[29:0]} | + {1'b0,qt_rt_const_q1[29:0],1'b0} | + {2'b0,qt_rt_const_q1[29:0]} | + {3'b0,qt_rt_const_q1[29:1]}; +//Quoit -2 +assign sqrt_qt_r2_rem_add_op1[31:0] = {1'b0, + total_qt_rt_minus_30[29:0],1'b0} | + {qt_rt_const_q1[29:0],2'b0} | + {1'b0,qt_rt_const_q1[29:0],1'b0}; +//Remainder Adder select logic +// &CombBeg; @607 +always @( div_qt_2_rem_add_op1[31:0] + or sqrt_qt_r2_rem_add_op1[31:0] + or sqrt_qt_r1_rem_add_op1[31:0] + or rem_sign + or div_qt_r2_rem_add_op1[31:0] + or div_qt_1_rem_add_op1[31:0] + or sqrt_qt_2_rem_add_op1[31:0] + or fdsu_ex2_sqrt + or div_qt_r1_rem_add_op1[31:0] + or sqrt_qt_1_rem_add_op1[31:0]) +begin +case({rem_sign,fdsu_ex2_sqrt}) + 2'b01: + begin + rem_add1_op1[31:0] = sqrt_qt_1_rem_add_op1[31:0]; + rem_add2_op1[31:0] = sqrt_qt_2_rem_add_op1[31:0]; + end + 2'b00: + begin + rem_add1_op1[31:0] = div_qt_1_rem_add_op1[31:0]; + rem_add2_op1[31:0] = div_qt_2_rem_add_op1[31:0]; + end + 2'b11: + begin + rem_add1_op1[31:0] = sqrt_qt_r1_rem_add_op1[31:0]; + rem_add2_op1[31:0] = sqrt_qt_r2_rem_add_op1[31:0]; + end + 2'b10: + begin + rem_add1_op1[31:0] = div_qt_r1_rem_add_op1[31:0]; + rem_add2_op1[31:0] = div_qt_r2_rem_add_op1[31:0]; + end + default : + begin + rem_add1_op1[31:0] = 32'b0; + rem_add2_op1[31:0] = 32'b0; + end + endcase +// &CombEnd; @635 +end +assign srt_remainder_shift[31:0] = {srt_remainder[31], + srt_remainder[28:0],2'b0}; +//Remainder add +assign cur_doub_rem_1[31:0] = srt_remainder_shift[31:0] + + rem_add1_op1[31:0] + + {31'b0, ~rem_sign}; +assign cur_doub_rem_2[31:0] = srt_remainder_shift[31:0] + + rem_add2_op1[31:0] + + {31'b0, ~rem_sign}; +assign cur_rem_1[31:0] = cur_doub_rem_1[31:0]; +assign cur_rem_2[31:0] = cur_doub_rem_2[31:0]; +//Generate srt remainder update value +// &CombBeg; @648 +always @( cur_rem_2[31:0] + or bound1_cmp_sign + or srt_remainder_shift[31:0] + or bound2_cmp_sign + or cur_rem_1[31:0]) +begin +case({bound1_cmp_sign,bound2_cmp_sign}) + 2'b00: cur_rem[31:0] = cur_rem_2[31:0]; //+-2 + 2'b01: cur_rem[31:0] = cur_rem_1[31:0]; //+-1 + default: cur_rem[31:0] = srt_remainder_shift[31:0]; //0 +endcase +// &CombEnd; @654 +end +assign srt_remainder_nxt[31:0] = cur_rem[31:0]; + +//Remainder is zero signal in EX3 +assign srt_remainder_zero = ~|srt_remainder[31:0]; +// &Force("output","srt_remainder_zero"); @659 +assign srt_remainder_sign = srt_remainder[31]; + +// &Force("output", "ex2_uf"); @662 +// &ModuleEnd; @663 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..00ba00a50891f8d38205e3a7eeff84d03d794807 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fdsu/rtl/pa_fdsu_top.v @@ -0,0 +1,461 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fdsu_top( + cp0_fpu_icg_en, + cp0_fpu_xx_dqnan, + cp0_yy_clk_en, + cpurst_b, + ctrl_fdsu_ex1_sel, + ctrl_xx_ex1_cmplt_dp, + ctrl_xx_ex1_inst_vld, + ctrl_xx_ex1_stall, + ctrl_xx_ex1_warm_up, + ctrl_xx_ex2_warm_up, + ctrl_xx_ex3_warm_up, + dp_xx_ex1_cnan, + dp_xx_ex1_id, + dp_xx_ex1_inf, + dp_xx_ex1_qnan, + dp_xx_ex1_rm, + dp_xx_ex1_snan, + dp_xx_ex1_zero, + fdsu_fpu_debug_info, + fdsu_fpu_ex1_cmplt, + fdsu_fpu_ex1_cmplt_dp, + fdsu_fpu_ex1_fflags, + fdsu_fpu_ex1_special_sel, + fdsu_fpu_ex1_special_sign, + fdsu_fpu_ex1_stall, + fdsu_fpu_no_op, + fdsu_frbus_data, + fdsu_frbus_fflags, + fdsu_frbus_freg, + fdsu_frbus_wb_vld, + forever_cpuclk, + frbus_fdsu_wb_grant, + idu_fpu_ex1_dst_freg, + idu_fpu_ex1_eu_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + pad_yy_icg_scan_en, + rtu_xx_ex1_cancel, + rtu_xx_ex2_cancel, + rtu_yy_xx_async_flush, + rtu_yy_xx_flush +); + +// &Ports; @24 +input cp0_fpu_icg_en; +input cp0_fpu_xx_dqnan; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_fdsu_ex1_sel; +input ctrl_xx_ex1_cmplt_dp; +input ctrl_xx_ex1_inst_vld; +input ctrl_xx_ex1_stall; +input ctrl_xx_ex1_warm_up; +input ctrl_xx_ex2_warm_up; +input ctrl_xx_ex3_warm_up; +input [2 :0] dp_xx_ex1_cnan; +input [2 :0] dp_xx_ex1_id; +input [2 :0] dp_xx_ex1_inf; +input [2 :0] dp_xx_ex1_qnan; +input [2 :0] dp_xx_ex1_rm; +input [2 :0] dp_xx_ex1_snan; +input [2 :0] dp_xx_ex1_zero; +input forever_cpuclk; +input frbus_fdsu_wb_grant; +input [4 :0] idu_fpu_ex1_dst_freg; +input [2 :0] idu_fpu_ex1_eu_sel; +input [9 :0] idu_fpu_ex1_func; +input [31:0] idu_fpu_ex1_srcf0; +input [31:0] idu_fpu_ex1_srcf1; +input pad_yy_icg_scan_en; +input rtu_xx_ex1_cancel; +input rtu_xx_ex2_cancel; +input rtu_yy_xx_async_flush; +input rtu_yy_xx_flush; +output [4 :0] fdsu_fpu_debug_info; +output fdsu_fpu_ex1_cmplt; +output fdsu_fpu_ex1_cmplt_dp; +output [4 :0] fdsu_fpu_ex1_fflags; +output [7 :0] fdsu_fpu_ex1_special_sel; +output [3 :0] fdsu_fpu_ex1_special_sign; +output fdsu_fpu_ex1_stall; +output fdsu_fpu_no_op; +output [31:0] fdsu_frbus_data; +output [4 :0] fdsu_frbus_fflags; +output [4 :0] fdsu_frbus_freg; +output fdsu_frbus_wb_vld; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_fdsu_ex1_sel; +wire ctrl_xx_ex1_cmplt_dp; +wire ctrl_xx_ex1_inst_vld; +wire ctrl_xx_ex1_stall; +wire ctrl_xx_ex1_warm_up; +wire ctrl_xx_ex2_warm_up; +wire ctrl_xx_ex3_warm_up; +wire [2 :0] dp_xx_ex1_cnan; +wire [2 :0] dp_xx_ex1_id; +wire [2 :0] dp_xx_ex1_inf; +wire [2 :0] dp_xx_ex1_qnan; +wire [2 :0] dp_xx_ex1_rm; +wire [2 :0] dp_xx_ex1_snan; +wire [2 :0] dp_xx_ex1_zero; +wire ex1_div; +wire [23:0] ex1_divisor; +wire [12:0] ex1_expnt_adder_op0; +wire [12:0] ex1_expnt_adder_op1; +wire ex1_of_result_lfn; +wire ex1_op0_id; +wire ex1_op0_norm; +wire ex1_op0_sign; +wire ex1_op1_id; +wire ex1_op1_id_vld; +wire ex1_op1_norm; +wire ex1_op1_sel; +wire [12:0] ex1_oper_id_expnt; +wire [12:0] ex1_oper_id_expnt_f; +wire [51:0] ex1_oper_id_frac; +wire [51:0] ex1_oper_id_frac_f; +wire ex1_pipedown; +wire ex1_pipedown_gate; +wire [31:0] ex1_remainder; +wire ex1_result_sign; +wire [2 :0] ex1_rm; +wire ex1_save_op0; +wire ex1_save_op0_gate; +wire ex1_sqrt; +wire ex1_srt_skip; +wire [9 :0] ex2_expnt_adder_op0; +wire ex2_of; +wire ex2_pipe_clk; +wire ex2_pipedown; +wire ex2_potnt_of; +wire ex2_potnt_uf; +wire ex2_result_inf; +wire ex2_result_lfn; +wire ex2_rslt_denorm; +wire [9 :0] ex2_srt_expnt_rst; +wire ex2_srt_first_round; +wire ex2_uf; +wire ex2_uf_srt_skip; +wire [9 :0] ex3_expnt_adjust_result; +wire [25:0] ex3_frac_final_rst; +wire ex3_pipedown; +wire ex3_rslt_denorm; +wire fdsu_ex1_sel; +wire fdsu_ex3_id_srt_skip; +wire fdsu_ex3_rem_sign; +wire fdsu_ex3_rem_zero; +wire [23:0] fdsu_ex3_result_denorm_round_add_num; +wire fdsu_ex4_denorm_to_tiny_frac; +wire [25:0] fdsu_ex4_frac; +wire fdsu_ex4_nx; +wire [1 :0] fdsu_ex4_potnt_norm; +wire fdsu_ex4_result_nor; +wire [4 :0] fdsu_fpu_debug_info; +wire fdsu_fpu_ex1_cmplt; +wire fdsu_fpu_ex1_cmplt_dp; +wire [4 :0] fdsu_fpu_ex1_fflags; +wire [7 :0] fdsu_fpu_ex1_special_sel; +wire [3 :0] fdsu_fpu_ex1_special_sign; +wire fdsu_fpu_ex1_stall; +wire fdsu_fpu_no_op; +wire [31:0] fdsu_frbus_data; +wire [4 :0] fdsu_frbus_fflags; +wire [4 :0] fdsu_frbus_freg; +wire fdsu_frbus_wb_vld; +wire fdsu_yy_div; +wire [9 :0] fdsu_yy_expnt_rst; +wire fdsu_yy_of; +wire fdsu_yy_of_rm_lfn; +wire fdsu_yy_op0_norm; +wire fdsu_yy_op1_norm; +wire fdsu_yy_potnt_of; +wire fdsu_yy_potnt_uf; +wire fdsu_yy_result_inf; +wire fdsu_yy_result_lfn; +wire fdsu_yy_result_sign; +wire [2 :0] fdsu_yy_rm; +wire fdsu_yy_rslt_denorm; +wire fdsu_yy_sqrt; +wire fdsu_yy_uf; +wire [4 :0] fdsu_yy_wb_freg; +wire forever_cpuclk; +wire frbus_fdsu_wb_grant; +wire [4 :0] idu_fpu_ex1_dst_freg; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire pad_yy_icg_scan_en; +wire rtu_xx_ex1_cancel; +wire rtu_xx_ex2_cancel; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_flush; +wire srt_remainder_zero; +wire srt_sm_on; +wire [29:0] total_qt_rt_30; + + + +// &Instance("pa_fdsu_special"); @29 +pa_fdsu_special x_pa_fdsu_special ( + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .dp_xx_ex1_cnan (dp_xx_ex1_cnan ), + .dp_xx_ex1_id (dp_xx_ex1_id ), + .dp_xx_ex1_inf (dp_xx_ex1_inf ), + .dp_xx_ex1_qnan (dp_xx_ex1_qnan ), + .dp_xx_ex1_snan (dp_xx_ex1_snan ), + .dp_xx_ex1_zero (dp_xx_ex1_zero ), + .ex1_div (ex1_div ), + .ex1_op0_id (ex1_op0_id ), + .ex1_op0_norm (ex1_op0_norm ), + .ex1_op0_sign (ex1_op0_sign ), + .ex1_op1_id (ex1_op1_id ), + .ex1_op1_norm (ex1_op1_norm ), + .ex1_result_sign (ex1_result_sign ), + .ex1_sqrt (ex1_sqrt ), + .ex1_srt_skip (ex1_srt_skip ), + .fdsu_fpu_ex1_fflags (fdsu_fpu_ex1_fflags ), + .fdsu_fpu_ex1_special_sel (fdsu_fpu_ex1_special_sel ), + .fdsu_fpu_ex1_special_sign (fdsu_fpu_ex1_special_sign) +); + +// &Instance("pa_fdsu_prepare"); @30 +pa_fdsu_prepare x_pa_fdsu_prepare ( + .dp_xx_ex1_rm (dp_xx_ex1_rm ), + .ex1_div (ex1_div ), + .ex1_divisor (ex1_divisor ), + .ex1_expnt_adder_op0 (ex1_expnt_adder_op0), + .ex1_expnt_adder_op1 (ex1_expnt_adder_op1), + .ex1_of_result_lfn (ex1_of_result_lfn ), + .ex1_op0_id (ex1_op0_id ), + .ex1_op0_sign (ex1_op0_sign ), + .ex1_op1_id (ex1_op1_id ), + .ex1_op1_id_vld (ex1_op1_id_vld ), + .ex1_op1_sel (ex1_op1_sel ), + .ex1_oper_id_expnt (ex1_oper_id_expnt ), + .ex1_oper_id_expnt_f (ex1_oper_id_expnt_f), + .ex1_oper_id_frac (ex1_oper_id_frac ), + .ex1_oper_id_frac_f (ex1_oper_id_frac_f ), + .ex1_remainder (ex1_remainder ), + .ex1_result_sign (ex1_result_sign ), + .ex1_rm (ex1_rm ), + .ex1_sqrt (ex1_sqrt ), + .fdsu_ex1_sel (fdsu_ex1_sel ), + .idu_fpu_ex1_func (idu_fpu_ex1_func ), + .idu_fpu_ex1_srcf0 (idu_fpu_ex1_srcf0 ), + .idu_fpu_ex1_srcf1 (idu_fpu_ex1_srcf1 ) +); + +// &Instance("pa_fdsu_srt"); @32 +// &Instance("pa_fdsu_round"); @33 +// &Instance("pa_fdsu_pack"); @34 +// &Instance("pa_fdsu_srt_single", "x_pa_fdsu_srt"); @36 +pa_fdsu_srt_single x_pa_fdsu_srt ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .ex1_divisor (ex1_divisor ), + .ex1_expnt_adder_op1 (ex1_expnt_adder_op1 ), + .ex1_oper_id_frac (ex1_oper_id_frac ), + .ex1_oper_id_frac_f (ex1_oper_id_frac_f ), + .ex1_pipedown (ex1_pipedown ), + .ex1_pipedown_gate (ex1_pipedown_gate ), + .ex1_remainder (ex1_remainder ), + .ex1_save_op0 (ex1_save_op0 ), + .ex1_save_op0_gate (ex1_save_op0_gate ), + .ex2_expnt_adder_op0 (ex2_expnt_adder_op0 ), + .ex2_of (ex2_of ), + .ex2_pipe_clk (ex2_pipe_clk ), + .ex2_pipedown (ex2_pipedown ), + .ex2_potnt_of (ex2_potnt_of ), + .ex2_potnt_uf (ex2_potnt_uf ), + .ex2_result_inf (ex2_result_inf ), + .ex2_result_lfn (ex2_result_lfn ), + .ex2_rslt_denorm (ex2_rslt_denorm ), + .ex2_srt_expnt_rst (ex2_srt_expnt_rst ), + .ex2_srt_first_round (ex2_srt_first_round ), + .ex2_uf (ex2_uf ), + .ex2_uf_srt_skip (ex2_uf_srt_skip ), + .ex3_frac_final_rst (ex3_frac_final_rst ), + .ex3_pipedown (ex3_pipedown ), + .fdsu_ex3_id_srt_skip (fdsu_ex3_id_srt_skip ), + .fdsu_ex3_rem_sign (fdsu_ex3_rem_sign ), + .fdsu_ex3_rem_zero (fdsu_ex3_rem_zero ), + .fdsu_ex3_result_denorm_round_add_num (fdsu_ex3_result_denorm_round_add_num), + .fdsu_ex4_frac (fdsu_ex4_frac ), + .fdsu_yy_div (fdsu_yy_div ), + .fdsu_yy_of_rm_lfn (fdsu_yy_of_rm_lfn ), + .fdsu_yy_op0_norm (fdsu_yy_op0_norm ), + .fdsu_yy_op1_norm (fdsu_yy_op1_norm ), + .fdsu_yy_sqrt (fdsu_yy_sqrt ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .srt_remainder_zero (srt_remainder_zero ), + .srt_sm_on (srt_sm_on ), + .total_qt_rt_30 (total_qt_rt_30 ) +); + +// &Instance("pa_fdsu_round_single", "x_pa_fdsu_round"); @37 +pa_fdsu_round_single x_pa_fdsu_round ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .ex3_expnt_adjust_result (ex3_expnt_adjust_result ), + .ex3_frac_final_rst (ex3_frac_final_rst ), + .ex3_pipedown (ex3_pipedown ), + .ex3_rslt_denorm (ex3_rslt_denorm ), + .fdsu_ex3_id_srt_skip (fdsu_ex3_id_srt_skip ), + .fdsu_ex3_rem_sign (fdsu_ex3_rem_sign ), + .fdsu_ex3_rem_zero (fdsu_ex3_rem_zero ), + .fdsu_ex3_result_denorm_round_add_num (fdsu_ex3_result_denorm_round_add_num), + .fdsu_ex4_denorm_to_tiny_frac (fdsu_ex4_denorm_to_tiny_frac ), + .fdsu_ex4_nx (fdsu_ex4_nx ), + .fdsu_ex4_potnt_norm (fdsu_ex4_potnt_norm ), + .fdsu_ex4_result_nor (fdsu_ex4_result_nor ), + .fdsu_yy_expnt_rst (fdsu_yy_expnt_rst ), + .fdsu_yy_result_inf (fdsu_yy_result_inf ), + .fdsu_yy_result_lfn (fdsu_yy_result_lfn ), + .fdsu_yy_result_sign (fdsu_yy_result_sign ), + .fdsu_yy_rm (fdsu_yy_rm ), + .fdsu_yy_rslt_denorm (fdsu_yy_rslt_denorm ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .total_qt_rt_30 (total_qt_rt_30 ) +); + +// &Instance("pa_fdsu_pack_single", "x_pa_fdsu_pack"); @38 +pa_fdsu_pack_single x_pa_fdsu_pack ( + .fdsu_ex4_denorm_to_tiny_frac (fdsu_ex4_denorm_to_tiny_frac), + .fdsu_ex4_frac (fdsu_ex4_frac ), + .fdsu_ex4_nx (fdsu_ex4_nx ), + .fdsu_ex4_potnt_norm (fdsu_ex4_potnt_norm ), + .fdsu_ex4_result_nor (fdsu_ex4_result_nor ), + .fdsu_frbus_data (fdsu_frbus_data ), + .fdsu_frbus_fflags (fdsu_frbus_fflags ), + .fdsu_frbus_freg (fdsu_frbus_freg ), + .fdsu_yy_expnt_rst (fdsu_yy_expnt_rst ), + .fdsu_yy_of (fdsu_yy_of ), + .fdsu_yy_of_rm_lfn (fdsu_yy_of_rm_lfn ), + .fdsu_yy_potnt_of (fdsu_yy_potnt_of ), + .fdsu_yy_potnt_uf (fdsu_yy_potnt_uf ), + .fdsu_yy_result_inf (fdsu_yy_result_inf ), + .fdsu_yy_result_lfn (fdsu_yy_result_lfn ), + .fdsu_yy_result_sign (fdsu_yy_result_sign ), + .fdsu_yy_rslt_denorm (fdsu_yy_rslt_denorm ), + .fdsu_yy_uf (fdsu_yy_uf ), + .fdsu_yy_wb_freg (fdsu_yy_wb_freg ) +); + + +// &Instance("pa_fdsu_ctrl"); @41 +pa_fdsu_ctrl x_pa_fdsu_ctrl ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_fdsu_ex1_sel (ctrl_fdsu_ex1_sel ), + .ctrl_xx_ex1_cmplt_dp (ctrl_xx_ex1_cmplt_dp ), + .ctrl_xx_ex1_inst_vld (ctrl_xx_ex1_inst_vld ), + .ctrl_xx_ex1_stall (ctrl_xx_ex1_stall ), + .ctrl_xx_ex1_warm_up (ctrl_xx_ex1_warm_up ), + .ctrl_xx_ex2_warm_up (ctrl_xx_ex2_warm_up ), + .ctrl_xx_ex3_warm_up (ctrl_xx_ex3_warm_up ), + .ex1_div (ex1_div ), + .ex1_expnt_adder_op0 (ex1_expnt_adder_op0 ), + .ex1_of_result_lfn (ex1_of_result_lfn ), + .ex1_op0_id (ex1_op0_id ), + .ex1_op0_norm (ex1_op0_norm ), + .ex1_op1_id_vld (ex1_op1_id_vld ), + .ex1_op1_norm (ex1_op1_norm ), + .ex1_op1_sel (ex1_op1_sel ), + .ex1_oper_id_expnt (ex1_oper_id_expnt ), + .ex1_oper_id_expnt_f (ex1_oper_id_expnt_f ), + .ex1_pipedown (ex1_pipedown ), + .ex1_pipedown_gate (ex1_pipedown_gate ), + .ex1_result_sign (ex1_result_sign ), + .ex1_rm (ex1_rm ), + .ex1_save_op0 (ex1_save_op0 ), + .ex1_save_op0_gate (ex1_save_op0_gate ), + .ex1_sqrt (ex1_sqrt ), + .ex1_srt_skip (ex1_srt_skip ), + .ex2_expnt_adder_op0 (ex2_expnt_adder_op0 ), + .ex2_of (ex2_of ), + .ex2_pipe_clk (ex2_pipe_clk ), + .ex2_pipedown (ex2_pipedown ), + .ex2_potnt_of (ex2_potnt_of ), + .ex2_potnt_uf (ex2_potnt_uf ), + .ex2_result_inf (ex2_result_inf ), + .ex2_result_lfn (ex2_result_lfn ), + .ex2_rslt_denorm (ex2_rslt_denorm ), + .ex2_srt_expnt_rst (ex2_srt_expnt_rst ), + .ex2_srt_first_round (ex2_srt_first_round ), + .ex2_uf (ex2_uf ), + .ex2_uf_srt_skip (ex2_uf_srt_skip ), + .ex3_expnt_adjust_result (ex3_expnt_adjust_result), + .ex3_pipedown (ex3_pipedown ), + .ex3_rslt_denorm (ex3_rslt_denorm ), + .fdsu_ex1_sel (fdsu_ex1_sel ), + .fdsu_fpu_debug_info (fdsu_fpu_debug_info ), + .fdsu_fpu_ex1_cmplt (fdsu_fpu_ex1_cmplt ), + .fdsu_fpu_ex1_cmplt_dp (fdsu_fpu_ex1_cmplt_dp ), + .fdsu_fpu_ex1_stall (fdsu_fpu_ex1_stall ), + .fdsu_fpu_no_op (fdsu_fpu_no_op ), + .fdsu_frbus_wb_vld (fdsu_frbus_wb_vld ), + .fdsu_yy_div (fdsu_yy_div ), + .fdsu_yy_expnt_rst (fdsu_yy_expnt_rst ), + .fdsu_yy_of (fdsu_yy_of ), + .fdsu_yy_of_rm_lfn (fdsu_yy_of_rm_lfn ), + .fdsu_yy_op0_norm (fdsu_yy_op0_norm ), + .fdsu_yy_op1_norm (fdsu_yy_op1_norm ), + .fdsu_yy_potnt_of (fdsu_yy_potnt_of ), + .fdsu_yy_potnt_uf (fdsu_yy_potnt_uf ), + .fdsu_yy_result_inf (fdsu_yy_result_inf ), + .fdsu_yy_result_lfn (fdsu_yy_result_lfn ), + .fdsu_yy_result_sign (fdsu_yy_result_sign ), + .fdsu_yy_rm (fdsu_yy_rm ), + .fdsu_yy_rslt_denorm (fdsu_yy_rslt_denorm ), + .fdsu_yy_sqrt (fdsu_yy_sqrt ), + .fdsu_yy_uf (fdsu_yy_uf ), + .fdsu_yy_wb_freg (fdsu_yy_wb_freg ), + .forever_cpuclk (forever_cpuclk ), + .frbus_fdsu_wb_grant (frbus_fdsu_wb_grant ), + .idu_fpu_ex1_dst_freg (idu_fpu_ex1_dst_freg ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_xx_ex1_cancel (rtu_xx_ex1_cancel ), + .rtu_xx_ex2_cancel (rtu_xx_ex2_cancel ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .srt_remainder_zero (srt_remainder_zero ), + .srt_sm_on (srt_sm_on ) +); + + + +// &ModuleEnd; @44 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/booth_code_25_bit.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/booth_code_25_bit.v new file mode 100644 index 0000000000000000000000000000000000000000..b22c6031d014369f382afbc4b742e21518bbbcdb --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/booth_code_25_bit.v @@ -0,0 +1,100 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @21 +module booth_code_25_bit( + A, + code, + h, + product, + sn +); + +// &Ports; @22 +input [24:0] A; +input [2 :0] code; +output [1 :0] h; +output [24:0] product; +output sn; + +// &Regs; @23 +reg [1 :0] h; +reg [24:0] product; +reg sn; + +// &Wires; @24 +wire [24:0] A; +wire [2 :0] code; + + +parameter SRC_WIDTH = 25; + +// &CombBeg; @28 +always @( code[2:0] + or A[24:0]) +begin +case(code[2:0]) +3'b000 : product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'b0}}; +3'b001 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-1:0]}; +3'b010 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-1:0]}; +3'b011 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-2:0],1'b0}; +3'b100 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-2:0],1'b0}; +3'b101 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-1:0]}; +3'b110 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-1:0]}; +3'b111 : product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'b0}}; +default: product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'bx}}; +endcase +// &CombEnd; @40 +end + +// &CombBeg; @42 +always @( A[24] + or code[2:0]) +begin +case(code[2:0]) +3'b000 : sn = 1'b1; +3'b001 : sn = ~A[SRC_WIDTH-1]; +3'b010 : sn = ~A[SRC_WIDTH-1]; +3'b011 : sn = ~A[SRC_WIDTH-1]; +3'b100 : sn = A[SRC_WIDTH-1]; +3'b101 : sn = A[SRC_WIDTH-1]; +3'b110 : sn = A[SRC_WIDTH-1]; +3'b111 : sn = 1'b1; +default: sn = 1'bx; +endcase +// &CombEnd; @54 +end + +// &CombBeg; @56 +always @( code[2:0]) +begin +case(code[2:0]) +3'b000 : h[1:0] = 2'b00; +3'b001 : h[1:0] = 2'b00; +3'b010 : h[1:0] = 2'b00; +3'b011 : h[1:0] = 2'b00; +3'b100 : h[1:0] = 2'b10; +3'b101 : h[1:0] = 2'b01; +3'b110 : h[1:0] = 2'b01; +3'b111 : h[1:0] = 2'b00; +default: h[1:0] = {2{1'bx}}; +endcase +// &CombEnd; @68 +end + +// &ModuleEnd; @70 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..6d8ac2b025c138d97f8d55194bf90a9625e416d7 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ctrl.v @@ -0,0 +1,312 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_ctrl( + cp0_fpu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_dp_ex1_inst_pipe_down, + ctrl_dp_ex1_inst_vld, + ctrl_dp_ex2_inst_pipe_down, + ctrl_dp_ex2_inst_vld, + ctrl_dp_ex3_inst_pipe_down, + ctrl_dp_ex3_inst_vld, + ctrl_fmau_ex1_sel, + ctrl_fmau_ex1_sel_gate, + ctrl_xx_ex1_cmplt_dp, + ctrl_xx_ex1_stall, + ctrl_xx_ex2_cancel, + ctrl_xx_ex2_stall, + ctrl_xx_ex3_stall, + ctrl_xx_ex4_stall, + dp_ctrl_ex3_mac, + dp_xx_ex1_id, + ex1_id_reg, + ex2_special_cmplt, + fmau_fpu_ex1_cmplt, + fmau_fpu_ex1_cmplt_dp, + fmau_fpu_ex1_denorm_stall, + fmau_fpu_ex3_result_vld, + fmau_fpu_id_reg_set, + forever_cpuclk, + idu_fpu_ex1_eu_sel, + pad_yy_icg_scan_en, + rtu_xx_ex1_cancel +); + +// &Ports; @25 +input cp0_fpu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_fmau_ex1_sel; +input ctrl_fmau_ex1_sel_gate; +input ctrl_xx_ex1_cmplt_dp; +input ctrl_xx_ex1_stall; +input ctrl_xx_ex2_cancel; +input ctrl_xx_ex2_stall; +input ctrl_xx_ex3_stall; +input ctrl_xx_ex4_stall; +input dp_ctrl_ex3_mac; +input [2:0] dp_xx_ex1_id; +input ex2_special_cmplt; +input forever_cpuclk; +input [2:0] idu_fpu_ex1_eu_sel; +input pad_yy_icg_scan_en; +input rtu_xx_ex1_cancel; +output ctrl_dp_ex1_inst_pipe_down; +output ctrl_dp_ex1_inst_vld; +output ctrl_dp_ex2_inst_pipe_down; +output ctrl_dp_ex2_inst_vld; +output ctrl_dp_ex3_inst_pipe_down; +output ctrl_dp_ex3_inst_vld; +output [1:0] ex1_id_reg; +output fmau_fpu_ex1_cmplt; +output fmau_fpu_ex1_cmplt_dp; +output fmau_fpu_ex1_denorm_stall; +output fmau_fpu_ex3_result_vld; +output fmau_fpu_id_reg_set; + +// &Regs; @26 +reg [1:0] ex1_id_reg; +reg ex2_inst_vld; +reg ex3_inst_vld; +reg ex4_inst_vld; + +// &Wires; @27 +wire cp0_fpu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_dp_ex1_inst_pipe_down; +wire ctrl_dp_ex1_inst_vld; +wire ctrl_dp_ex2_inst_pipe_down; +wire ctrl_dp_ex2_inst_vld; +wire ctrl_dp_ex3_inst_pipe_down; +wire ctrl_dp_ex3_inst_vld; +wire ctrl_fmau_ex1_sel; +wire ctrl_fmau_ex1_sel_gate; +wire ctrl_xx_ex1_cmplt_dp; +wire ctrl_xx_ex1_stall; +wire ctrl_xx_ex2_cancel; +wire ctrl_xx_ex2_stall; +wire ctrl_xx_ex3_stall; +wire ctrl_xx_ex4_stall; +wire dp_ctrl_ex3_mac; +wire [2:0] dp_xx_ex1_id; +wire ex1_denormal_clk; +wire ex1_denormal_clk_en; +wire ex1_denormal_stall; +wire ex1_inst_vld; +wire ex2_ctrl_clk; +wire ex2_ctrl_clk_en; +wire ex2_special_cmplt; +wire ex3_ctrl_clk; +wire ex3_ctrl_clk_en; +wire ex4_ctrl_clk; +wire ex4_ctrl_clk_en; +wire fmau_fpu_ex1_cmplt; +wire fmau_fpu_ex1_cmplt_dp; +wire fmau_fpu_ex1_denorm_stall; +wire fmau_fpu_ex3_result_vld; +wire fmau_fpu_id_reg_set; +wire forever_cpuclk; +wire [2:0] idu_fpu_ex1_eu_sel; +wire pad_yy_icg_scan_en; +wire rtu_xx_ex1_cancel; + + +// &Depend("cpu_cfig.h"); @29 + +parameter DOUBLE_WIDTH = 64; +parameter DOUBLE_FRAC = 52; +parameter DOUBLE_EXPN = 11; + +parameter SINGLE_WIDTH = 32; +parameter SINGLE_FRAC = 23; +parameter SINGLE_EXPN = 8; + +parameter FUNC_WIDTH = 10; + +//========================================================== +// EX1 Interface +//========================================================== +assign ex1_inst_vld = ctrl_fmau_ex1_sel; + +//========================================================== +// EX1 denormal judge +//========================================================== +// &Force("bus","dp_xx_ex1_id",2,0); @49 + +assign ex1_denormal_clk_en = ctrl_fmau_ex1_sel_gate && |dp_xx_ex1_id[1:0] + || |ex1_id_reg[1:0]; + +assign ex1_denormal_stall = ex1_inst_vld && (ex1_id_reg[1:0]==2'b00) && |dp_xx_ex1_id[1:0]; + +assign fmau_fpu_ex1_denorm_stall = ex1_denormal_stall; + +assign fmau_fpu_ex1_cmplt = ex1_inst_vld && ((dp_xx_ex1_id[1:0]==2'b00) || |ex1_id_reg[1:0]); +assign fmau_fpu_ex1_cmplt_dp = ctrl_xx_ex1_cmplt_dp && idu_fpu_ex1_eu_sel[1] && ((dp_xx_ex1_id[1:0]==2'b00) || |ex1_id_reg[1:0]); +// &Force("bus","idu_fpu_ex1_eu_sel",2,0); @60 +// &Instance("gated_clk_cell", "x_ctrl_ex1_denormal_gated_clk"); @61 +gated_clk_cell x_ctrl_ex1_denormal_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex1_denormal_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex1_denormal_clk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk ), @62 +// .external_en (1'b0 ), @63 +// .global_en (cp0_yy_clk_en ), @64 +// .module_en (cp0_fpu_icg_en ), @65 +// .local_en (ex1_denormal_clk_en ), @66 +// .clk_out (ex1_denormal_clk )); @67 + +always@(posedge ex1_denormal_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ex1_id_reg[1:0] <= {2{1'b0}}; + else if(ex1_denormal_stall) + ex1_id_reg[1:0] <= dp_xx_ex1_id[1:0]; + else + ex1_id_reg[1:0] <= {2{1'b0}}; +end + +assign fmau_fpu_id_reg_set = | ex1_id_reg[1:0]; + +// &Force("output","ex1_id_reg"); @81 +//========================================================== +// EX2 inst vld ctrl +//========================================================== +assign ctrl_dp_ex1_inst_vld = ex1_inst_vld; +assign ctrl_dp_ex1_inst_pipe_down = ex1_inst_vld && !ctrl_xx_ex2_stall; + +assign ex2_ctrl_clk_en = ctrl_fmau_ex1_sel_gate || ex2_inst_vld; + +// &Instance("gated_clk_cell", "x_ctrl_ex2_gated_clk"); @90 +gated_clk_cell x_ctrl_ex2_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex2_ctrl_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex2_ctrl_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @91 +// .external_en (1'b0 ), @92 +// .global_en (cp0_yy_clk_en ), @93 +// .module_en (cp0_fpu_icg_en ), @94 +// .local_en (ex2_ctrl_clk_en ), @95 +// .clk_out (ex2_ctrl_clk )); @96 + +always@(posedge ex2_ctrl_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ex2_inst_vld <= 1'b0; + else if(ctrl_xx_ex2_cancel) + ex2_inst_vld <= 1'b0; + else if(!ctrl_xx_ex2_stall) + ex2_inst_vld <= ex1_inst_vld && !rtu_xx_ex1_cancel && !ctrl_xx_ex1_stall; + else + ex2_inst_vld <= ex2_inst_vld; +end + +//========================================================== +// EX3 inst vld ctrl +//========================================================== + +assign ctrl_dp_ex2_inst_vld = ex2_inst_vld; +assign ctrl_dp_ex2_inst_pipe_down = ex2_inst_vld && !ctrl_xx_ex3_stall && !ex2_special_cmplt; + +assign ex3_ctrl_clk_en = ex2_inst_vld || ex3_inst_vld; + +// &Instance("gated_clk_cell", "x_ctrl_ex3_gated_clk"); @119 +gated_clk_cell x_ctrl_ex3_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex3_ctrl_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex3_ctrl_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @120 +// .external_en (1'b0 ), @121 +// .global_en (cp0_yy_clk_en ), @122 +// .module_en (cp0_fpu_icg_en ), @123 +// .local_en (ex3_ctrl_clk_en ), @124 +// .clk_out (ex3_ctrl_clk )); @125 + +always@(posedge ex3_ctrl_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ex3_inst_vld <= 1'b0; + else if(!ctrl_xx_ex3_stall) + ex3_inst_vld <= ex2_inst_vld &&!ctrl_xx_ex2_cancel && !ex2_special_cmplt && !ctrl_xx_ex2_stall; + else + ex3_inst_vld <= ex3_inst_vld; +end + +assign fmau_fpu_ex3_result_vld = ex3_inst_vld && !dp_ctrl_ex3_mac; +//========================================================== +// EX4 inst vld ctrl +//========================================================== + +assign ctrl_dp_ex3_inst_vld = ex3_inst_vld && dp_ctrl_ex3_mac; +assign ctrl_dp_ex3_inst_pipe_down = ex3_inst_vld && dp_ctrl_ex3_mac && !ctrl_xx_ex4_stall; + +assign ex4_ctrl_clk_en = ex3_inst_vld || ex4_inst_vld; + +// &Instance("gated_clk_cell", "x_ctrl_ex4_gated_clk"); @147 +gated_clk_cell x_ctrl_ex4_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ex4_ctrl_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ex4_ctrl_clk_en ), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @148 +// .external_en (1'b0 ), @149 +// .global_en (cp0_yy_clk_en ), @150 +// .module_en (cp0_fpu_icg_en ), @151 +// .local_en (ex4_ctrl_clk_en ), @152 +// .clk_out (ex4_ctrl_clk )); @153 + +always@(posedge ex4_ctrl_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ex4_inst_vld <= 1'b0; + else if(!ctrl_xx_ex4_stall) + ex4_inst_vld <= ex3_inst_vld && dp_ctrl_ex3_mac && !ctrl_xx_ex3_stall; + else + ex4_inst_vld <= ex4_inst_vld; +end + +//assign fmau_fpu_ex4_result_vld = ex4_inst_vld; + +// &ModuleEnd; @167 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_dp.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_dp.v new file mode 100644 index 0000000000000000000000000000000000000000..914d4a5a6ea91fd286439d887956fa61afa7ff38 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_dp.v @@ -0,0 +1,459 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_dp( + cp0_fpu_icg_en, + cp0_fpu_xx_dqnan, + cp0_yy_clk_en, + ctrl_dp_ex1_inst_pipe_down, + ctrl_dp_ex1_inst_vld, + ctrl_dp_ex2_inst_pipe_down, + ctrl_dp_ex2_inst_vld, + ctrl_dp_ex3_inst_pipe_down, + ctrl_dp_ex3_inst_vld, + ctrl_xx_ex1_warm_up, + ctrl_xx_ex2_warm_up, + ctrl_xx_ex3_warm_up, + dp_ctrl_ex3_mac, + dp_xx_ex1_cnan, + dp_xx_ex1_inf, + dp_xx_ex1_norm, + dp_xx_ex1_qnan, + dp_xx_ex1_rm, + dp_xx_ex1_snan, + dp_xx_ex1_srcf2, + dp_xx_ex1_zero, + dp_xx_ex2_srcf2, + dp_xx_ex3_rm, + dp_xx_ex4_rm, + ex1_id_reg, + ex2_special_cmplt, + fmau_fpu_ex1_fflags, + fmau_fpu_ex1_special_sel, + fmau_fpu_ex1_special_sign, + fmau_fpu_ex3_fflags, + fmau_fpu_ex3_result, + fmau_fpu_ex4_fflags, + fmau_fpu_ex4_result, + forever_cpuclk, + idu_fpu_ex1_eu_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + pad_yy_icg_scan_en +); + +// &Ports; @25 +input cp0_fpu_icg_en; +input cp0_fpu_xx_dqnan; +input cp0_yy_clk_en; +input ctrl_dp_ex1_inst_pipe_down; +input ctrl_dp_ex1_inst_vld; +input ctrl_dp_ex2_inst_pipe_down; +input ctrl_dp_ex2_inst_vld; +input ctrl_dp_ex3_inst_pipe_down; +input ctrl_dp_ex3_inst_vld; +input ctrl_xx_ex1_warm_up; +input ctrl_xx_ex2_warm_up; +input ctrl_xx_ex3_warm_up; +input [2 :0] dp_xx_ex1_cnan; +input [2 :0] dp_xx_ex1_inf; +input [2 :0] dp_xx_ex1_norm; +input [2 :0] dp_xx_ex1_qnan; +input [2 :0] dp_xx_ex1_rm; +input [2 :0] dp_xx_ex1_snan; +input [31:0] dp_xx_ex1_srcf2; +input [2 :0] dp_xx_ex1_zero; +input [31:0] dp_xx_ex2_srcf2; +input [2 :0] dp_xx_ex3_rm; +input [2 :0] dp_xx_ex4_rm; +input [1 :0] ex1_id_reg; +input forever_cpuclk; +input [2 :0] idu_fpu_ex1_eu_sel; +input [9 :0] idu_fpu_ex1_func; +input [31:0] idu_fpu_ex1_srcf0; +input [31:0] idu_fpu_ex1_srcf1; +input pad_yy_icg_scan_en; +output dp_ctrl_ex3_mac; +output ex2_special_cmplt; +output [4 :0] fmau_fpu_ex1_fflags; +output [7 :0] fmau_fpu_ex1_special_sel; +output [3 :0] fmau_fpu_ex1_special_sign; +output [4 :0] fmau_fpu_ex3_fflags; +output [31:0] fmau_fpu_ex3_result; +output [4 :0] fmau_fpu_ex4_fflags; +output [31:0] fmau_fpu_ex4_result; + +// &Regs; @26 +reg [9 :0] ex2_expnt_2; +reg ex2_mac; +reg [9 :0] ex2_mult_expnt; +reg ex2_mult_sign; +reg ex2_special_cmplt; +reg ex2_src2_expnt_not_zero; +reg ex2_src2_sign; +reg ex3_mac; +reg [9 :0] ex3_mac_expnt; +reg [9 :0] ex3_mult_expnt; +reg ex3_mult_sign; +reg ex3_sub_vld; + +// &Wires; @27 +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire cp0_yy_clk_en; +wire ctrl_dp_ex1_inst_pipe_down; +wire ctrl_dp_ex1_inst_vld; +wire ctrl_dp_ex2_inst_pipe_down; +wire ctrl_dp_ex2_inst_vld; +wire ctrl_dp_ex3_inst_pipe_down; +wire ctrl_dp_ex3_inst_vld; +wire ctrl_xx_ex1_warm_up; +wire ctrl_xx_ex2_warm_up; +wire ctrl_xx_ex3_warm_up; +wire dp_ctrl_ex3_mac; +wire [2 :0] dp_xx_ex1_cnan; +wire [2 :0] dp_xx_ex1_inf; +wire [2 :0] dp_xx_ex1_norm; +wire [2 :0] dp_xx_ex1_qnan; +wire [2 :0] dp_xx_ex1_rm; +wire [2 :0] dp_xx_ex1_snan; +wire [31:0] dp_xx_ex1_srcf2; +wire [2 :0] dp_xx_ex1_zero; +wire [31:0] dp_xx_ex2_srcf2; +wire [2 :0] dp_xx_ex3_rm; +wire [2 :0] dp_xx_ex4_rm; +wire [2 :0] ex1_eu_sel; +wire [9 :0] ex1_expnt_0; +wire [9 :0] ex1_expnt_1; +wire [9 :0] ex1_expnt_2; +wire [9 :0] ex1_expnt_bias; +wire ex1_expnt_near_of; +wire ex1_expnt_near_uf; +wire [23:0] ex1_frac_0; +wire [23:0] ex1_frac_1; +wire [9 :0] ex1_func; +wire [1 :0] ex1_id_reg; +wire [2 :0] ex1_inst_rm; +wire ex1_mac; +wire ex1_mac_update; +wire [9 :0] ex1_mult_expnt; +wire ex1_mult_sign; +wire ex1_neg; +wire ex1_special_cmplt; +wire ex1_src2_expnt_not_zero; +wire ex1_src2_sign; +wire [31:0] ex1_srcf0; +wire [31:0] ex1_srcf1; +wire [31:0] ex1_srcf2; +wire ex1_sub; +wire ex1_sub_vld; +wire ex2_adder_0_sel_h; +wire [23:0] ex2_frac_2; +wire [9 :0] ex2_mac_expnt; +wire [47:0] ex2_mult_data; +wire [52:0] ex2_shift_data; +wire [31:0] ex2_srcf2; +wire ex2_sub_vld; +wire [2 :0] ex3_inst_rm; +wire [2 :0] ex4_inst_rm; +wire fmau_ex2_data_clk; +wire fmau_ex2_data_clk_en; +wire fmau_ex3_data_clk; +wire fmau_ex3_data_clk_en; +wire fmau_ex4_data_clk; +wire fmau_ex4_data_clk_en; +wire [4 :0] fmau_fpu_ex1_fflags; +wire [7 :0] fmau_fpu_ex1_special_sel; +wire [3 :0] fmau_fpu_ex1_special_sign; +wire [4 :0] fmau_fpu_ex3_fflags; +wire [31:0] fmau_fpu_ex3_result; +wire [4 :0] fmau_fpu_ex4_fflags; +wire [31:0] fmau_fpu_ex4_result; +wire forever_cpuclk; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire pad_yy_icg_scan_en; + + +// &Depend("cpu_cfig.h"); @29 + +parameter DOUBLE_WIDTH = 64; +parameter DOUBLE_FRAC = 52; +parameter DOUBLE_EXPN = 11; + +parameter SINGLE_WIDTH = 32; +parameter SINGLE_FRAC = 23; +parameter SINGLE_EXPN = 8; + +parameter FUNC_WIDTH = 10; + +//========================================================== +// EX1 Interface +//========================================================== +assign ex1_func[FUNC_WIDTH-1:0] = idu_fpu_ex1_func[FUNC_WIDTH-1:0]; + +assign ex1_inst_rm[2:0] = dp_xx_ex1_rm[2:0]; +//assign ex2_inst_rm[2:0] = dp_xx_ex2_rm[2:0]; +assign ex3_inst_rm[2:0] = dp_xx_ex3_rm[2:0]; +assign ex4_inst_rm[2:0] = dp_xx_ex4_rm[2:0]; + +assign ex1_srcf0[SINGLE_WIDTH-1:0] = idu_fpu_ex1_srcf0[SINGLE_WIDTH-1:0]; +assign ex1_srcf1[SINGLE_WIDTH-1:0] = idu_fpu_ex1_srcf1[SINGLE_WIDTH-1:0]; +assign ex1_srcf2[SINGLE_WIDTH-1:0] = dp_xx_ex1_srcf2[SINGLE_WIDTH-1:0]; +assign ex2_srcf2[SINGLE_WIDTH-1:0] = dp_xx_ex2_srcf2[SINGLE_WIDTH-1:0]; +assign ex1_mac = ex1_func[0]; +assign ex1_sub = ex1_func[1]; +assign ex1_neg = ex1_func[2]; + +// &Instance("pa_fmau_ex1_special_judge","x_pa_fmau_ex1_special_judge"); @70 +pa_fmau_ex1_special_judge x_pa_fmau_ex1_special_judge ( + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .dp_xx_ex1_cnan (dp_xx_ex1_cnan ), + .dp_xx_ex1_inf (dp_xx_ex1_inf ), + .dp_xx_ex1_norm (dp_xx_ex1_norm ), + .dp_xx_ex1_qnan (dp_xx_ex1_qnan ), + .dp_xx_ex1_snan (dp_xx_ex1_snan ), + .dp_xx_ex1_zero (dp_xx_ex1_zero ), + .ex1_inst_rm (ex1_inst_rm ), + .ex1_mac (ex1_mac ), + .ex1_mult_expnt (ex1_mult_expnt ), + .ex1_mult_sign (ex1_mult_sign ), + .ex1_special_cmplt (ex1_special_cmplt ), + .ex1_src2_sign (ex1_src2_sign ), + .ex1_sub_vld (ex1_sub_vld ), + .fmau_fpu_ex1_fflags (fmau_fpu_ex1_fflags ), + .fmau_fpu_ex1_special_sel (fmau_fpu_ex1_special_sel ), + .fmau_fpu_ex1_special_sign (fmau_fpu_ex1_special_sign) +); + +//========================================================== +// EX1 Fraction data path +//========================================================== +assign ex1_mac_update = ex1_mac || |ex1_id_reg[1:0] || ex1_expnt_near_uf || ex1_expnt_near_of; + +assign ex1_eu_sel[2:0] = idu_fpu_ex1_eu_sel[2:0]; +assign ex1_frac_0[SINGLE_FRAC:0] = {!ex1_id_reg[0],ex1_srcf0[SINGLE_FRAC-1:0]} & {(SINGLE_FRAC+1){ex1_eu_sel[1]}}; +assign ex1_frac_1[SINGLE_FRAC:0] = {!ex1_id_reg[1],ex1_srcf1[SINGLE_FRAC-1:0]} & {(SINGLE_FRAC+1){ex1_eu_sel[1]}}; + +// &Instance("pa_fmau_frac_mult","x_pa_fmau_frac_mult"); @88 +pa_fmau_frac_mult x_pa_fmau_frac_mult ( + .ctrl_dp_ex1_inst_pipe_down (ctrl_dp_ex1_inst_pipe_down), + .ctrl_xx_ex1_warm_up (ctrl_xx_ex1_warm_up ), + .ex1_frac_0 (ex1_frac_0 ), + .ex1_frac_1 (ex1_frac_1 ), + .ex2_mult_data (ex2_mult_data ), + .fmau_ex2_data_clk (fmau_ex2_data_clk ) +); + +//========================================================== +// EX1 Exponent data path +//========================================================== +assign ex1_expnt_0[SINGLE_EXPN+1:0] = {2'b00,ex1_srcf0[SINGLE_FRAC+SINGLE_EXPN-1:SINGLE_FRAC]}; +assign ex1_expnt_1[SINGLE_EXPN+1:0] = {2'b00,ex1_srcf1[SINGLE_FRAC+SINGLE_EXPN-1:SINGLE_FRAC]}; +assign ex1_expnt_2[SINGLE_EXPN+1:0] = ex1_src2_expnt_not_zero ? {2'b00,ex1_srcf2[SINGLE_FRAC+SINGLE_EXPN-1:SINGLE_FRAC]}:10'b00_0000_0001; + +assign ex1_src2_expnt_not_zero = |ex1_srcf2[SINGLE_FRAC+SINGLE_EXPN-1:SINGLE_FRAC]; + +assign ex1_expnt_bias[SINGLE_EXPN+1:0] = 10'b11_1000_0001; //single= -127 + +assign ex1_mult_expnt[SINGLE_EXPN+1:0] = {ex1_expnt_0[SINGLE_EXPN+1:0]} + + {ex1_expnt_1[SINGLE_EXPN+1:0]} + + {1'b0,{SINGLE_EXPN{1'b0}},ex1_id_reg[0]} + + {1'b0,{SINGLE_EXPN{1'b0}},ex1_id_reg[1]} + + ex1_expnt_bias[SINGLE_EXPN+1:0]; + +assign ex1_expnt_near_uf = ex1_mult_expnt[SINGLE_EXPN+1] || //<-127 + !(|ex1_mult_expnt[SINGLE_EXPN+1:0]); //=-127 + +assign ex1_expnt_near_of =(ex1_mult_expnt[SINGLE_EXPN+1:0]==10'b00_1111_1110); //127 + +assign ex1_mult_sign = (ex1_srcf0[SINGLE_WIDTH-1]^ex1_srcf1[SINGLE_WIDTH-1]^ex1_neg); + +assign ex1_src2_sign = (ex1_srcf2[SINGLE_WIDTH-1]^ex1_neg^ex1_sub); + +assign ex1_sub_vld = (ex1_mult_sign ^ ex1_src2_sign) && ex1_mac; + +// &Instance("pa_fmau_frac_shift","x_pa_fmau_frac_shift"); @156 +pa_fmau_frac_shift x_pa_fmau_frac_shift ( + .ctrl_dp_ex1_inst_pipe_down (ctrl_dp_ex1_inst_pipe_down), + .ctrl_xx_ex1_warm_up (ctrl_xx_ex1_warm_up ), + .ex1_expnt_2 (ex1_expnt_2 ), + .ex1_mult_expnt (ex1_mult_expnt ), + .ex2_adder_0_sel_h (ex2_adder_0_sel_h ), + .ex2_expnt_2 (ex2_expnt_2 ), + .ex2_frac_2 (ex2_frac_2 ), + .ex2_mac (ex2_mac ), + .ex2_mac_expnt (ex2_mac_expnt ), + .ex2_mult_expnt (ex2_mult_expnt ), + .ex2_shift_data (ex2_shift_data ), + .fmau_ex2_data_clk (fmau_ex2_data_clk ) +); + + +// &Instance("pa_fmau_frac_add","x_pa_fmau_frac_add"); @158 +pa_fmau_frac_add x_pa_fmau_frac_add ( + .ctrl_dp_ex2_inst_pipe_down (ctrl_dp_ex2_inst_pipe_down), + .ctrl_dp_ex3_inst_pipe_down (ctrl_dp_ex3_inst_pipe_down), + .ctrl_xx_ex2_warm_up (ctrl_xx_ex2_warm_up ), + .ctrl_xx_ex3_warm_up (ctrl_xx_ex3_warm_up ), + .ex2_adder_0_sel_h (ex2_adder_0_sel_h ), + .ex2_mac (ex2_mac ), + .ex2_mac_expnt (ex2_mac_expnt ), + .ex2_mult_data (ex2_mult_data ), + .ex2_shift_data (ex2_shift_data ), + .ex2_sub_vld (ex2_sub_vld ), + .ex3_inst_rm (ex3_inst_rm ), + .ex3_mac_expnt (ex3_mac_expnt ), + .ex3_mult_expnt (ex3_mult_expnt ), + .ex3_mult_sign (ex3_mult_sign ), + .ex3_sub_vld (ex3_sub_vld ), + .ex4_inst_rm (ex4_inst_rm ), + .fmau_ex3_data_clk (fmau_ex3_data_clk ), + .fmau_ex4_data_clk (fmau_ex4_data_clk ), + .fmau_fpu_ex3_fflags (fmau_fpu_ex3_fflags ), + .fmau_fpu_ex3_result (fmau_fpu_ex3_result ), + .fmau_fpu_ex4_fflags (fmau_fpu_ex4_fflags ), + .fmau_fpu_ex4_result (fmau_fpu_ex4_result ) +); + +//========================================================== +// EX2 Stage +//========================================================== +//---------------------------------------------------------- +// Instance of Gated Cell +//---------------------------------------------------------- +assign fmau_ex2_data_clk_en = ctrl_dp_ex1_inst_vld || ctrl_xx_ex1_warm_up; + +// &Instance("gated_clk_cell", "x_fmau_ex2_data_gated_clk"); @167 +gated_clk_cell x_fmau_ex2_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fmau_ex2_data_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fmau_ex2_data_clk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk ), @168 +// .external_en (1'b0 ), @169 +// .global_en (cp0_yy_clk_en ), @170 +// .module_en (cp0_fpu_icg_en ), @171 +// .local_en (fmau_ex2_data_clk_en), @172 +// .clk_out (fmau_ex2_data_clk )); @173 + +always @(posedge fmau_ex2_data_clk) +begin + if(ctrl_dp_ex1_inst_pipe_down || ctrl_xx_ex1_warm_up) + begin + ex2_special_cmplt <= ex1_special_cmplt; + ex2_mac <= ex1_mac_update; + ex2_mult_sign <= ex1_mult_sign; + ex2_src2_sign <= ex1_src2_sign; + ex2_src2_expnt_not_zero <= ex1_src2_expnt_not_zero; + end +end + +always @(posedge fmau_ex2_data_clk) +begin + if(ctrl_dp_ex1_inst_pipe_down || ctrl_xx_ex1_warm_up) + begin + ex2_mult_expnt[SINGLE_EXPN+1:0] <= ex1_mult_expnt[SINGLE_EXPN+1:0]; + ex2_expnt_2[SINGLE_EXPN+1:0] <= ex1_expnt_2[SINGLE_EXPN+1:0]; + end +end + +assign ex2_sub_vld = (ex2_mult_sign ^ ex2_src2_sign) && ex2_mac; + +// &CombBeg; @274 +// &CombEnd; @280 + +assign ex2_frac_2[SINGLE_FRAC:0] = {ex2_src2_expnt_not_zero,ex2_srcf2[SINGLE_FRAC-1:0]}; + +//========================================================== +// EX3 Stage +//========================================================== +assign fmau_ex3_data_clk_en = ctrl_dp_ex2_inst_vld || ctrl_xx_ex2_warm_up; + +// &Instance("gated_clk_cell", "x_fmau_ex3_data_gated_clk"); @291 +gated_clk_cell x_fmau_ex3_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fmau_ex3_data_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fmau_ex3_data_clk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk ), @292 +// .external_en (1'b0 ), @293 +// .global_en (cp0_yy_clk_en ), @294 +// .module_en (cp0_fpu_icg_en ), @295 +// .local_en (fmau_ex3_data_clk_en), @296 +// .clk_out (fmau_ex3_data_clk )); @297 + +always @(posedge fmau_ex3_data_clk) +begin + if(ctrl_dp_ex2_inst_pipe_down || ctrl_xx_ex2_warm_up) + begin + ex3_sub_vld <= ex2_sub_vld; + ex3_mac <= ex2_mac; + ex3_mult_sign <= ex2_mult_sign; + end +end + +assign dp_ctrl_ex3_mac = ex3_mac; + +always @(posedge fmau_ex3_data_clk) +begin + if(ctrl_dp_ex2_inst_pipe_down || ctrl_xx_ex2_warm_up) + begin + ex3_mult_expnt[SINGLE_EXPN+1:0] <= ex2_mult_expnt[SINGLE_EXPN+1:0]; + ex3_mac_expnt[SINGLE_EXPN+1:0] <= ex2_mac_expnt[SINGLE_EXPN+1:0]; + end +end +//========================================================== +// EX4 Stage +//========================================================== +assign fmau_ex4_data_clk_en = ctrl_dp_ex3_inst_vld || ctrl_xx_ex3_warm_up; + +// &Instance("gated_clk_cell", "x_fmau_ex4_data_gated_clk"); @397 +gated_clk_cell x_fmau_ex4_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fmau_ex4_data_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fmau_ex4_data_clk_en), + .module_en (cp0_fpu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk ), @398 +// .external_en (1'b0 ), @399 +// .global_en (cp0_yy_clk_en ), @400 +// .module_en (cp0_fpu_icg_en ), @401 +// .local_en (fmau_ex4_data_clk_en), @402 +// .clk_out (fmau_ex4_data_clk )); @403 + +// &ModuleEnd; @432 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ex1_special_judge.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ex1_special_judge.v new file mode 100644 index 0000000000000000000000000000000000000000..89e3cc9713dc685738589b1046dee941716dd151 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_ex1_special_judge.v @@ -0,0 +1,188 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_ex1_special_judge( + cp0_fpu_xx_dqnan, + dp_xx_ex1_cnan, + dp_xx_ex1_inf, + dp_xx_ex1_norm, + dp_xx_ex1_qnan, + dp_xx_ex1_snan, + dp_xx_ex1_zero, + ex1_inst_rm, + ex1_mac, + ex1_mult_expnt, + ex1_mult_sign, + ex1_special_cmplt, + ex1_src2_sign, + ex1_sub_vld, + fmau_fpu_ex1_fflags, + fmau_fpu_ex1_special_sel, + fmau_fpu_ex1_special_sign +); + +// &Ports; @25 +input cp0_fpu_xx_dqnan; +input [2:0] dp_xx_ex1_cnan; +input [2:0] dp_xx_ex1_inf; +input [2:0] dp_xx_ex1_norm; +input [2:0] dp_xx_ex1_qnan; +input [2:0] dp_xx_ex1_snan; +input [2:0] dp_xx_ex1_zero; +input [2:0] ex1_inst_rm; +input ex1_mac; +input [9:0] ex1_mult_expnt; +input ex1_mult_sign; +input ex1_src2_sign; +input ex1_sub_vld; +output ex1_special_cmplt; +output [4:0] fmau_fpu_ex1_fflags; +output [7:0] fmau_fpu_ex1_special_sel; +output [3:0] fmau_fpu_ex1_special_sign; + +// &Regs; @26 + +// &Wires; @27 +wire cp0_fpu_xx_dqnan; +wire [2:0] dp_xx_ex1_cnan; +wire [2:0] dp_xx_ex1_inf; +wire [2:0] dp_xx_ex1_norm; +wire [2:0] dp_xx_ex1_qnan; +wire [2:0] dp_xx_ex1_snan; +wire [2:0] dp_xx_ex1_zero; +wire ex1_fmau_inf_sign; +wire ex1_fmau_lfn_sign; +wire ex1_fmau_nv; +wire ex1_fmau_of; +wire ex1_fmau_result_cnan; +wire ex1_fmau_result_inf; +wire ex1_fmau_result_lfn; +wire [2:0] ex1_fmau_result_qnan; +wire ex1_fmau_result_src2; +wire ex1_fmau_result_zero; +wire ex1_fmau_src2_sign; +wire ex1_fmau_zero_sign; +wire [2:0] ex1_inst_rm; +wire ex1_mac; +wire [9:0] ex1_mult_expnt; +wire ex1_mult_sign; +wire [2:0] ex1_nv; +wire [2:0] ex1_result_qnan; +wire ex1_result_zero; +wire ex1_special_cmplt; +wire ex1_src2_sign; +wire ex1_sub_vld; +wire [4:0] fmau_fpu_ex1_fflags; +wire [7:0] fmau_fpu_ex1_special_sel; +wire [3:0] fmau_fpu_ex1_special_sign; + + +// &Depend("cpu_cfig.h"); @29 + +parameter FPU_WIDTH = 64; +parameter SINGLE_FRAC = 23; +parameter DOUBLE_FRAC = 52; +parameter SINGLE_EXPN = 8; +parameter DOUBLE_EXPN = 11; +parameter FUNC_WIDTH = 10; + +//========================================================== +// EX1 exception judge +//========================================================== + +assign ex1_nv[0] = |dp_xx_ex1_snan[2:0]; //sNan + +assign ex1_nv[1] = (dp_xx_ex1_zero[0] && dp_xx_ex1_inf[1]) //0*inf + || (dp_xx_ex1_zero[1] && dp_xx_ex1_inf[0]);//inf*0 + +assign ex1_nv[2] = (dp_xx_ex1_inf[0] && dp_xx_ex1_norm[1] && dp_xx_ex1_inf[2] && ex1_sub_vld) //inf*F -inf + || (dp_xx_ex1_inf[1] && dp_xx_ex1_norm[0] && dp_xx_ex1_inf[2] && ex1_sub_vld) //inf*F -inf + || (dp_xx_ex1_inf[0] && dp_xx_ex1_inf[1] && dp_xx_ex1_inf[2] && ex1_sub_vld); //inf*inf -inf + +assign ex1_fmau_nv = |ex1_nv[2:0]; +assign ex1_fmau_of = (ex1_mult_expnt[9 : 8] == 2'b01) && &dp_xx_ex1_norm[1:0] && (dp_xx_ex1_norm[2] || dp_xx_ex1_zero[2]) //single expt >128 + || (ex1_mult_expnt[9 : 0] == 10'b00_1111_1111) && &dp_xx_ex1_norm[1:0] && !ex1_mac; //single expt>127 +//========================================================== +// EX1 special result judge +//========================================================== +assign ex1_result_qnan[0] = dp_xx_ex1_snan[0] + || dp_xx_ex1_qnan[0] && !dp_xx_ex1_snan[1] && !dp_xx_ex1_snan[2]; + +assign ex1_result_qnan[1] = !dp_xx_ex1_snan[0] && dp_xx_ex1_snan[1] + || !dp_xx_ex1_snan[0] &&!dp_xx_ex1_qnan[0] && dp_xx_ex1_qnan[1] && !dp_xx_ex1_snan[2]; + +assign ex1_result_qnan[2] = !dp_xx_ex1_snan[0] && !dp_xx_ex1_snan[1] && dp_xx_ex1_snan[2] + || !dp_xx_ex1_snan[0] && !dp_xx_ex1_snan[1] && !dp_xx_ex1_qnan[0] && !dp_xx_ex1_qnan[1] && dp_xx_ex1_qnan[2]; + +assign ex1_fmau_result_cnan = ex1_result_qnan[0] && (dp_xx_ex1_cnan[0] || !cp0_fpu_xx_dqnan) + ||ex1_result_qnan[1] && (dp_xx_ex1_cnan[1] || !cp0_fpu_xx_dqnan) + ||ex1_result_qnan[2] && (dp_xx_ex1_cnan[2] || !cp0_fpu_xx_dqnan) + ||ex1_nv[1] && !ex1_result_qnan[2] + ||ex1_nv[2]; + +assign ex1_fmau_result_qnan[2:0] = ex1_result_qnan[2:0] &(~dp_xx_ex1_cnan[2:0]) & {3{cp0_fpu_xx_dqnan}}; + +assign ex1_result_zero = dp_xx_ex1_zero[0] && dp_xx_ex1_norm[1] && dp_xx_ex1_zero[2] + || dp_xx_ex1_zero[1] && dp_xx_ex1_norm[0] && dp_xx_ex1_zero[2] + || dp_xx_ex1_zero[0] && dp_xx_ex1_zero[1] && dp_xx_ex1_zero[2]; + +assign ex1_fmau_result_zero = ex1_result_zero; + +assign ex1_fmau_zero_sign = ex1_sub_vld ? (ex1_inst_rm[2:0]==3'b010) : ex1_mult_sign; + +assign ex1_fmau_result_inf = (|dp_xx_ex1_inf[2:0]) && !(|ex1_result_qnan[2:0]) && !ex1_nv[1] && !ex1_nv[2] + ||ex1_fmau_of && + ((ex1_inst_rm[1:0]==2'b00) + || ex1_mult_sign && (ex1_inst_rm[2:0]==3'b010) + ||!ex1_mult_sign && (ex1_inst_rm[2:0]==3'b011)); + +assign ex1_fmau_inf_sign = (|dp_xx_ex1_inf[1:0] || ex1_fmau_of) ? ex1_mult_sign : ex1_src2_sign; + +assign ex1_fmau_result_lfn = ex1_fmau_of && + ((ex1_inst_rm[2:0]==3'b001) + ||!ex1_mult_sign && (ex1_inst_rm[2:0]==3'b010) + || ex1_mult_sign && (ex1_inst_rm[2:0]==3'b011)); + +assign ex1_fmau_lfn_sign = ex1_mult_sign; + +assign ex1_fmau_result_src2 = dp_xx_ex1_zero[0] && dp_xx_ex1_norm[1] && dp_xx_ex1_norm[2] //zero * normal + || dp_xx_ex1_zero[1] && dp_xx_ex1_norm[0] && dp_xx_ex1_norm[2] + || dp_xx_ex1_zero[0] && dp_xx_ex1_zero[1] && dp_xx_ex1_norm[2]; + +assign ex1_fmau_src2_sign = ex1_src2_sign; + +assign fmau_fpu_ex1_special_sel[7:0] = {ex1_fmau_result_qnan[2:0], + ex1_fmau_result_cnan, + ex1_fmau_result_lfn, + ex1_fmau_result_inf, + ex1_fmau_result_zero, + ex1_fmau_result_src2}; + +assign fmau_fpu_ex1_special_sign[3:0]= {ex1_fmau_lfn_sign, ex1_fmau_inf_sign, ex1_fmau_zero_sign, ex1_fmau_src2_sign}; + +assign fmau_fpu_ex1_fflags[4:0] = {ex1_fmau_nv, 1'b0,ex1_fmau_of,1'b0,ex1_fmau_of}; + +assign ex1_special_cmplt =|({ex1_fmau_result_qnan[2:0], + ex1_fmau_result_cnan, + ex1_fmau_result_lfn, + ex1_fmau_result_inf, + ex1_fmau_result_zero, + ex1_fmau_result_src2}); +// &ModuleEnd; @127 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_add.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_add.v new file mode 100644 index 0000000000000000000000000000000000000000..d9c75d539b6071e40c038bb0dc1e4e3db7961e40 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_add.v @@ -0,0 +1,507 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_frac_add( + ctrl_dp_ex2_inst_pipe_down, + ctrl_dp_ex3_inst_pipe_down, + ctrl_xx_ex2_warm_up, + ctrl_xx_ex3_warm_up, + ex2_adder_0_sel_h, + ex2_mac, + ex2_mac_expnt, + ex2_mult_data, + ex2_shift_data, + ex2_sub_vld, + ex3_inst_rm, + ex3_mac_expnt, + ex3_mult_expnt, + ex3_mult_sign, + ex3_sub_vld, + ex4_inst_rm, + fmau_ex3_data_clk, + fmau_ex4_data_clk, + fmau_fpu_ex3_fflags, + fmau_fpu_ex3_result, + fmau_fpu_ex4_fflags, + fmau_fpu_ex4_result +); + +// &Ports; @25 +input ctrl_dp_ex2_inst_pipe_down; +input ctrl_dp_ex3_inst_pipe_down; +input ctrl_xx_ex2_warm_up; +input ctrl_xx_ex3_warm_up; +input ex2_adder_0_sel_h; +input ex2_mac; +input [9 :0] ex2_mac_expnt; +input [47:0] ex2_mult_data; +input [52:0] ex2_shift_data; +input ex2_sub_vld; +input [2 :0] ex3_inst_rm; +input [9 :0] ex3_mac_expnt; +input [9 :0] ex3_mult_expnt; +input ex3_mult_sign; +input ex3_sub_vld; +input [2 :0] ex4_inst_rm; +input fmau_ex3_data_clk; +input fmau_ex4_data_clk; +output [4 :0] fmau_fpu_ex3_fflags; +output [31:0] fmau_fpu_ex3_result; +output [4 :0] fmau_fpu_ex4_fflags; +output [31:0] fmau_fpu_ex4_result; + +// &Regs; @26 +reg [52:0] ex3_adder_0; +reg [52:0] ex3_adder_1; +reg [52:0] ex3_adder_result; +reg [22:0] ex3_mult_frac_result; +reg ex3_mult_rnd_in; +reg [1 :0] ex3_mult_single_gs_bit; +reg [15:0] ex3_shift_limit_low; +reg [9 :0] ex4_mac_expnt; +reg ex4_mac_expnt_neg_max; +reg [7 :0] ex4_mac_expnt_result; +reg ex4_mac_frac_not_zero; +reg [52:0] ex4_mac_frac_pre; +reg [22:0] ex4_mac_frac_result; +reg ex4_mac_rnd_in; +reg ex4_mac_shift_32_bit; +reg ex4_mac_sign; + +// &Wires; @27 +wire ctrl_dp_ex2_inst_pipe_down; +wire ctrl_dp_ex3_inst_pipe_down; +wire ctrl_xx_ex2_warm_up; +wire ctrl_xx_ex3_warm_up; +wire [52:0] ex2_adder_0; +wire [52:0] ex2_adder_0_0; +wire [52:0] ex2_adder_0_1; +wire ex2_adder_0_sel_h; +wire [52:0] ex2_adder_1; +wire ex2_adder_1_for_single_rnd_add_1; +wire ex2_adder_1_for_single_rnd_add_2; +wire [52:0] ex2_adder_1_rnd_data; +wire ex2_mac; +wire [9 :0] ex2_mac_expnt; +wire [47:0] ex2_mult_data; +wire [1 :0] ex2_mult_single_gs_bit; +wire [52:0] ex2_shift_data; +wire [15:0] ex2_shift_limit_low; +wire ex2_shift_limit_vld; +wire ex2_sub_vld; +wire [52:0] ex3_adder_0_result; +wire [52:0] ex3_adder_1_result; +wire [2 :0] ex3_adder_result_sel; +wire [2 :0] ex3_inst_rm; +wire [6 :0] ex3_lza_result; +wire [9 :0] ex3_mac_expnt; +wire [9 :0] ex3_mac_expnt_adjust; +wire ex3_mac_expnt_neg_max; +wire ex3_mac_frac_not_zero; +wire [52:0] ex3_mac_result_shift; +wire ex3_mac_sign; +wire [9 :0] ex3_mult_expnt; +wire ex3_mult_expnt_add_in; +wire [9 :0] ex3_mult_expnt_plus_1; +wire [7 :0] ex3_mult_expnt_result; +wire [1 :0] ex3_mult_frac_sel; +wire [22:0] ex3_mult_no_rnd_result; +wire ex3_mult_nx; +wire [24:0] ex3_mult_result; +wire [2 :0] ex3_mult_rnd_bit; +wire [24:0] ex3_mult_rnd_result; +wire ex3_mult_sign; +wire [31:0] ex3_mult_single_result; +wire [52:0] ex3_shift_limit; +wire [63:0] ex3_shift_limit_one_hot; +wire ex3_sub_vld; +wire ex4_early_of; +wire ex4_expnt_rnd_in; +wire [31:0] ex4_fmau_single_result; +wire [2 :0] ex4_inst_rm; +wire ex4_late_of; +wire [24:0] ex4_mac_data_for_rnd; +wire [23:0] ex4_mac_data_no_rnd; +wire ex4_mac_expnt_plus_1; +wire [2 :0] ex4_mac_expnt_sel; +wire [52:0] ex4_mac_frac; +wire [1 :0] ex4_mac_frac_sel; +wire ex4_mac_nx; +wire ex4_mac_of; +wire [24:0] ex4_mac_rnd_result; +wire ex4_mac_sign_result; +wire ex4_mac_uf; +wire ex4_of_frac_bit; +wire ex4_plus_1_of; +wire [2 :0] ex4_rnd_bit; +wire fmau_ex3_data_clk; +wire fmau_ex4_data_clk; +wire [4 :0] fmau_fpu_ex3_fflags; +wire [31:0] fmau_fpu_ex3_result; +wire [4 :0] fmau_fpu_ex4_fflags; +wire [31:0] fmau_fpu_ex4_result; + + +// &Depend("cpu_cfig.h"); @29 + +parameter DOUBLE_WIDTH= 64; +parameter DOUBLE_FRAC = 52; +parameter DOUBLE_EXPN = 11; +parameter ADD_D_WIDTH =111; + +parameter FUNC_WIDTH = 10; + +parameter SINGLE_WIDTH= 32; +parameter SINGLE_FRAC = 23; +parameter SINGLE_EXPN = 8; +parameter ADD_S_WIDTH = 53; +//================================================================== +// EX2 data prepare +//================================================================== +//case 1: E01+2>=E2 MAC +// MULT_RESULT:0|0|X|X|FRAC_H[51:0]|FRAC_L[51:0]|0|0|0 +// SRC2 0|x|FRAC[51:0]|000.........000000000000>>shift index +//case 2: E01+2 < E2 MAC +// MULT_RESULT:0|0|00...00000|0|0|X|X|FRAC_H[51:0]|S +// SRC2 0|x|FRAC[51:0]|00....0.....000000000000>>shift index +//case 3:MULT ROUNDING +// MULT_RESULT:00..........000000|0|X|X|FRAC_H[51:0]|S +// SRC2 00..........000000000000|SINGLE...OUBLE|>>shift index +// &CombBeg; @129 +// &CombEnd; @136 +// &Instance("pa_fmau_lza_double","x_pa_fmau_lza_double"); @156 +// &Connect( .summand (ex3_adder_0 ), @157 +// .addend (ex3_adder_1 ), @158 +// .sub_vld (ex3_sub_vld ), @159 +// .upper_limit (ex3_shift_limit), @160 +// .lza_result (ex3_lza_result )); @161 +// &CombBeg; @266 +// &CombEnd; @275 +// &CombBeg; @280 +// &CombEnd; @286 +// &CombBeg; @304 +// &CombEnd; @311 +// &CombBeg; @354 +// &CombEnd; @363 +// &CombBeg; @371 +// &CombEnd; @377 +//================================================================== +// EX2 data prepare +//================================================================== +//case 1: E01+2>=E2 MAC +// MULT_RESULT:0|0|X|X|FRAC_H[22:0]|FRAC_L[22:0]|0|0|0 +// SRC2 0|x|FRAC[22:0]|000.........000000000000>>shift index +//case 2: E01+2 < E2 MAC +// MULT_RESULT:0|0|00...00000|0|0|X|X|FRAC_H[22:0]|S +// SRC2 0|x|FRAC[22:0]|00....0.....000000000000>>shift index +//case 3:MULT ROUNDING +// MULT_RESULT:00..........000000|0|X|X|FRAC_H[22:0]|S +// SRC2 00..........000000000000|SINGLE...OUBLE|>>shift index + +assign ex2_adder_0_0[ADD_S_WIDTH-1:0] = {2'b00,{SINGLE_FRAC{1'b0}}, 2'b00, ex2_mult_data[2*SINGLE_FRAC+1:SINGLE_FRAC],|ex2_mult_single_gs_bit[1:0]}; +assign ex2_adder_0_1[ADD_S_WIDTH-1:0] = {2'b00, ex2_mult_data[2*SINGLE_FRAC+1:0],3'b0}; + +assign ex2_adder_0[ADD_S_WIDTH-1:0] = ex2_adder_0_sel_h ? ex2_adder_0_0[ADD_S_WIDTH-1:0] : ex2_adder_0_1[ADD_S_WIDTH-1:0]; + +assign ex2_adder_1_for_single_rnd_add_1 = !ex2_mac && !ex2_mult_data[2*SINGLE_FRAC+1]; +assign ex2_adder_1_for_single_rnd_add_2 = !ex2_mac && ex2_mult_data[2*SINGLE_FRAC+1]; + + +assign ex2_adder_1_rnd_data[ADD_S_WIDTH-1:0] = {{51{1'b0}},ex2_adder_1_for_single_rnd_add_1,{1{1'b0}} } + | {{50{1'b0}},ex2_adder_1_for_single_rnd_add_2,{2{1'b0}} }; + +assign ex2_adder_1[ADD_S_WIDTH-1:0] = ex2_sub_vld + ? ~ex2_shift_data[ADD_S_WIDTH-1:0] + : (ex2_shift_data[ADD_S_WIDTH-1:0] |ex2_adder_1_rnd_data[ADD_S_WIDTH-1:0]); + +assign ex2_mult_single_gs_bit[1:0] = {ex2_mult_data[22], |ex2_mult_data[21: 0]}; + +assign ex2_shift_limit_low[15:0] = 16'b1000_0000_0000_0000 >> ex2_mac_expnt[3:0]; +assign ex2_shift_limit_vld = (ex2_mac_expnt[9:6]==4'b0000); +//========================================================== +// EX3 data pipe +//========================================================== + +always @(posedge fmau_ex3_data_clk) +begin + if(ctrl_dp_ex2_inst_pipe_down || ctrl_xx_ex2_warm_up) + begin + ex3_mult_single_gs_bit[1:0] <= ex2_mult_single_gs_bit[1:0]; + ex3_adder_0[ADD_S_WIDTH-1:0] <= ex2_adder_0[ADD_S_WIDTH-1:0]; + ex3_adder_1[ADD_S_WIDTH-1:0] <= ex2_adder_1[ADD_S_WIDTH-1:0]; + ex3_shift_limit_low[15:0] <= ex2_shift_limit_low[15:0] & {16{ex2_shift_limit_vld}}; + end +end + +assign ex3_shift_limit_one_hot[63:0] = {ex3_shift_limit_low[15:0],{48{1'b0}} } >> {ex3_mac_expnt[5:4],4'b0}; +assign ex3_shift_limit[52:0] = ex3_shift_limit_one_hot[63:11]; +//========================================================== +// EX3 adders +//========================================================== +assign ex3_adder_0_result[ADD_S_WIDTH-1:0] = ex3_adder_0[ADD_S_WIDTH-1:0] + ex3_adder_1[ADD_S_WIDTH-1:0]; +assign ex3_adder_1_result[ADD_S_WIDTH-1:0] = ex3_adder_0[ADD_S_WIDTH-1:0] + ex3_adder_1[ADD_S_WIDTH-1:0] + 1'b1; + +assign ex3_adder_result_sel[0] = !ex3_sub_vld; +assign ex3_adder_result_sel[1] = ex3_sub_vld && ex3_adder_1_result[ADD_S_WIDTH-1]; +assign ex3_adder_result_sel[2] = ex3_sub_vld &&!ex3_adder_1_result[ADD_S_WIDTH-1]; + +// &CombBeg; @484 +always @( ex3_adder_0_result[52:0] + or ex3_adder_1_result[52:0] + or ex3_adder_result_sel[2:0]) +begin +case(ex3_adder_result_sel[2:0]) + 3'b001: ex3_adder_result[ADD_S_WIDTH-1:0] = ex3_adder_0_result[ADD_S_WIDTH-1:0]; + 3'b010: ex3_adder_result[ADD_S_WIDTH-1:0] =~ex3_adder_0_result[ADD_S_WIDTH-1:0]; + 3'b100: ex3_adder_result[ADD_S_WIDTH-1:0] = ex3_adder_1_result[ADD_S_WIDTH-1:0]; + default: ex3_adder_result[ADD_S_WIDTH-1:0] = {ADD_S_WIDTH{1'bx}}; +endcase +// &CombEnd; @491 +end + +assign ex3_mac_sign = ex3_mult_sign ^(ex3_sub_vld && ex3_adder_1_result[ADD_S_WIDTH-1]); +assign ex3_mac_frac_not_zero = |ex3_adder_result[ADD_S_WIDTH-1:0]; +//========================================================== +// EX3 early overflow judge +//========================================================== +//assign ex3_single_of = (ex3_mac_expnt[9:0]==10'b01_0000_0001) && |ex3_adder_result[ADD_S_WIDTH-1:ADD_S_WIDTH-4] //expn=130,frac=1x.xxx or 01.xxx or 00.1xxx or 00.01x +// ||(ex3_mac_expnt[9:0]==10'b01_0000_0000) && |ex3_adder_result[ADD_S_WIDTH-1:ADD_S_WIDTH-3] //expn=129,frac=1x.xxx or 01.xxx or 00.1xxx +// ||(ex3_mac_expnt[9:0]==10'b00_1111_1111) && |ex3_adder_result[ADD_S_WIDTH-1:ADD_S_WIDTH-2] //expn=128,frac=1x.xxx or 01.xxx +// ||(ex3_mac_expnt[9:0]==10'b00_1111_1110) && ex3_adder_result[ADD_S_WIDTH-1]; //expn=127, frac=1x.xxx + +//====================================================================== +// leading zero predict +//====================================================================== +// &Instance("pa_fmau_lza_single","x_pa_fmau_lza_single"); @506 +pa_fmau_lza_single x_pa_fmau_lza_single ( + .addend (ex3_adder_1 ), + .lza_result (ex3_lza_result ), + .sub_vld (ex3_sub_vld ), + .summand (ex3_adder_0 ), + .upper_limit (ex3_shift_limit) +); + +// &Connect( .summand (ex3_adder_0 ), @507 +// .addend (ex3_adder_1 ), @508 +// .sub_vld (ex3_sub_vld ), @509 +// .upper_limit (ex3_shift_limit), @510 +// .lza_result (ex3_lza_result )); @511 +//========================================================== +// EX3 result pipe down +//========================================================== + +assign ex3_mac_result_shift[ADD_S_WIDTH-1:0] = ex3_adder_result[ADD_S_WIDTH-1:0]<<{ex3_lza_result[4:0]}; +assign ex3_mac_expnt_adjust[SINGLE_EXPN+1:0] = ex3_mac_expnt[SINGLE_EXPN+1:0] -{ {4{1'b0}},ex3_lza_result[5:0]};//plus1 + +assign ex3_mac_expnt_neg_max =(ex3_mac_expnt[SINGLE_EXPN+1:0] == { {4{1'b0}},ex3_lza_result[5:0]}); + +always @(posedge fmau_ex4_data_clk) +begin + if(ctrl_dp_ex3_inst_pipe_down || ctrl_xx_ex3_warm_up) + begin + ex4_mac_expnt[SINGLE_EXPN+1:0] <= ex3_mac_expnt_adjust[SINGLE_EXPN+1:0]; + ex4_mac_frac_pre[ADD_S_WIDTH-1:0] <= ex3_mac_result_shift[ADD_S_WIDTH-1:0]; + ex4_mac_expnt_neg_max <= ex3_mac_expnt_neg_max; + ex4_mac_frac_not_zero <= ex3_mac_frac_not_zero; + ex4_mac_shift_32_bit <= ex3_lza_result[5]; + ex4_mac_sign <= ex3_mac_sign; +// ex4_single_of <= ex3_single_of; + end +end +//====================================================================== +// EX4 MAC RESULT ROUNDING +//====================================================================== +assign ex4_mac_frac[ADD_S_WIDTH-1:0] = ex4_mac_shift_32_bit ? {ex4_mac_frac_pre[ADD_S_WIDTH-33:0], {32{1'b0}} } + : ex4_mac_frac_pre[ADD_S_WIDTH- 1:0]; + +assign ex4_early_of = (ex4_mac_expnt[9 : 8]==2'b01)||(ex4_mac_expnt[9 : 0]==10'b00_1111_1111); + +assign ex4_plus_1_of=(ex4_mac_expnt[9:0] == 10'b00_1111_1110) && ex4_mac_expnt_plus_1; + +assign ex4_of_frac_bit = (ex4_inst_rm[2:0]==3'b001)//rnd to zero + ||(ex4_inst_rm[2:0]==3'b010) && !ex4_mac_sign //rnd to neg and !sign + ||(ex4_inst_rm[2:0]==3'b011) && ex4_mac_sign;//rnd to pos and sign + +assign ex4_mac_expnt_plus_1 = ex4_mac_frac[ADD_S_WIDTH-1] || ex4_mac_expnt_neg_max; + +assign ex4_mac_data_no_rnd[SINGLE_FRAC:0] =(ex4_mac_frac[ADD_S_WIDTH-1] || ex4_mac_expnt_neg_max) + ? ex4_mac_frac[ADD_S_WIDTH-1:ADD_S_WIDTH-SINGLE_FRAC-1] + : ex4_mac_frac[ADD_S_WIDTH-2:ADD_S_WIDTH-SINGLE_FRAC-2]; + + +assign ex4_mac_data_for_rnd[SINGLE_FRAC+1:0] = {1'b0, ex4_mac_data_no_rnd[SINGLE_FRAC:0]}; + +assign ex4_mac_rnd_result[SINGLE_FRAC+1:0] = ex4_mac_data_for_rnd[SINGLE_FRAC+1:0] + + { {24{1'b0}},1'b1 }; + +assign ex4_rnd_bit[2:0] = (ex4_mac_frac[ADD_S_WIDTH-1] || ex4_mac_expnt_neg_max) + ? {ex4_mac_frac[29:28],|ex4_mac_frac[27:0]} + : {ex4_mac_frac[28:27],|ex4_mac_frac[26:0]}; +// &CombBeg; @587 +always @( ex4_inst_rm[2:0] + or ex4_mac_sign + or ex4_rnd_bit[2:0]) +begin +case(ex4_inst_rm[2:0]) + 3'b000: ex4_mac_rnd_in = ex4_rnd_bit[1] && (ex4_rnd_bit[0] || ex4_rnd_bit[2]); //round to nearest even + 3'b001: ex4_mac_rnd_in = 1'b0; + 3'b010: ex4_mac_rnd_in = ex4_mac_sign && |ex4_rnd_bit[1:0]; //round to negative infinity + 3'b011: ex4_mac_rnd_in =!ex4_mac_sign && |ex4_rnd_bit[1:0]; //round to positive infinity + 3'b100: ex4_mac_rnd_in = ex4_rnd_bit[1]; +default : ex4_mac_rnd_in = 1'b0; +endcase +// &CombEnd; @596 +end + +assign ex4_mac_frac_sel[0] = ex4_mac_rnd_result[SINGLE_FRAC+1] && ex4_mac_rnd_in && !ex4_early_of && !ex4_plus_1_of; //1x.xxx after rnd,no of +assign ex4_mac_frac_sel[1] =!ex4_mac_rnd_result[SINGLE_FRAC+1] && ex4_mac_rnd_in && !ex4_early_of && !ex4_plus_1_of; //0x.xxx after rnd,no of + +// &CombBeg; @601 +always @( ex4_mac_rnd_result[23:0] + or ex4_early_of + or ex4_mac_data_no_rnd[22:0] + or ex4_mac_frac_sel[1:0] + or ex4_plus_1_of + or ex4_of_frac_bit) +begin +case(ex4_mac_frac_sel[1:0]) + 2'b01: ex4_mac_frac_result[SINGLE_FRAC-1:0] = ex4_mac_rnd_result[SINGLE_FRAC:1]; + 2'b10: ex4_mac_frac_result[SINGLE_FRAC-1:0] = ex4_mac_rnd_result[SINGLE_FRAC-1:0]; +default: ex4_mac_frac_result[SINGLE_FRAC-1:0] =(ex4_early_of || ex4_plus_1_of) ? {SINGLE_FRAC{ex4_of_frac_bit}} : ex4_mac_data_no_rnd[SINGLE_FRAC-1:0]; +endcase +// &CombEnd; @607 +end + +assign ex4_expnt_rnd_in = ex4_mac_rnd_in && + &(ex4_mac_data_for_rnd[SINGLE_FRAC-1:0]); + +assign ex4_mac_expnt_sel[2] = ex4_mac_data_no_rnd[SINGLE_FRAC] && ex4_mac_frac_not_zero && !ex4_early_of + && ex4_expnt_rnd_in && ex4_mac_expnt_plus_1 && !ex4_plus_1_of; //plus 2 + +assign ex4_mac_expnt_sel[1] = ex4_mac_data_no_rnd[SINGLE_FRAC] && ex4_mac_frac_not_zero && !ex4_early_of + &&(ex4_expnt_rnd_in ^ ex4_mac_expnt_plus_1) && !ex4_plus_1_of //plus 1 + ||!ex4_mac_data_no_rnd[SINGLE_FRAC] && ex4_mac_frac_not_zero && !ex4_early_of + && ex4_expnt_rnd_in; //plus 1 + +assign ex4_mac_expnt_sel[0] = ex4_mac_data_no_rnd[SINGLE_FRAC] && ex4_mac_frac_not_zero && !ex4_early_of + &&!ex4_expnt_rnd_in && !ex4_mac_expnt_plus_1 //plus 0 + ||!ex4_mac_data_no_rnd[SINGLE_FRAC] && ex4_mac_frac_not_zero && !ex4_early_of + &&!ex4_expnt_rnd_in; +// &CombBeg; @624 +always @( ex4_mac_expnt[7:0] + or ex4_mac_expnt_sel[2:0] + or ex4_early_of + or ex4_plus_1_of + or ex4_of_frac_bit) +begin +case(ex4_mac_expnt_sel[2:0]) + 3'b100: ex4_mac_expnt_result[SINGLE_EXPN-1:0] = ex4_mac_expnt[SINGLE_EXPN-1:0] + 8'b0000_0010; + 3'b010: ex4_mac_expnt_result[SINGLE_EXPN-1:0] = ex4_mac_expnt[SINGLE_EXPN-1:0] + 8'b0000_0001; + 3'b001: ex4_mac_expnt_result[SINGLE_EXPN-1:0] = ex4_mac_expnt[SINGLE_EXPN-1:0]; + default: ex4_mac_expnt_result[SINGLE_EXPN-1:0] =(ex4_early_of || ex4_plus_1_of) ? {{7{1'b1}},!ex4_of_frac_bit}: 8'b0000_0000; +endcase +// &CombEnd; @631 +end + + +assign ex4_mac_sign_result = ex4_mac_frac_not_zero ? ex4_mac_sign : (ex4_inst_rm[2:0]==3'b010); + +assign ex4_late_of = (ex4_mac_expnt[7:0]==8'b1111_1101) && ex4_mac_expnt_sel[2] + ||(ex4_mac_expnt[7:0]==8'b1111_1110) && ex4_mac_expnt_sel[1]; + +assign ex4_mac_of = ex4_early_of || ex4_plus_1_of || ex4_late_of; + +assign ex4_mac_uf = ex4_mac_expnt_neg_max && |ex4_rnd_bit[1:0] //inexact frac + && !ex4_expnt_rnd_in && !ex4_mac_data_no_rnd[SINGLE_FRAC]; + +assign ex4_mac_nx = |ex4_rnd_bit[1:0]; + +assign fmau_fpu_ex4_fflags[4:0] = {1'b0, 1'b0,ex4_mac_of,ex4_mac_uf,ex4_mac_nx || ex4_mac_of}; + +assign ex4_fmau_single_result[31:0] = {ex4_mac_sign_result,ex4_mac_expnt_result[7:0],ex4_mac_frac_result[22:0]}; + +assign fmau_fpu_ex4_result[31:0] = ex4_fmau_single_result[31:0]; + +//================================================================================== +// EX3 normal mult rounding:expnt= [-126/-1022,126/1022] && no denormal no overflow +//================================================================================== +assign ex3_mult_result[SINGLE_FRAC+1:0] = ex3_adder_0[SINGLE_FRAC+2:1]; + +assign ex3_mult_rnd_result[SINGLE_FRAC+1:0] = ex3_adder_0_result[SINGLE_FRAC+2:1]; + +assign ex3_mult_rnd_bit[2:0] = ex3_mult_result[SINGLE_FRAC+1] + ?{ex3_mult_result[1:0],|ex3_mult_single_gs_bit[1:0]} + :{ex3_mult_result[0], ex3_mult_single_gs_bit[1:0]}; + +// &CombBeg; @663 +always @( ex3_mult_sign + or ex3_inst_rm[2:0] + or ex3_mult_rnd_bit[2:0]) +begin +case(ex3_inst_rm[2:0]) + 3'b000: ex3_mult_rnd_in = ex3_mult_rnd_bit[1] && (ex3_mult_rnd_bit[0] || ex3_mult_rnd_bit[2]); //round to nearest even + 3'b001: ex3_mult_rnd_in = 1'b0; + 3'b010: ex3_mult_rnd_in = ex3_mult_sign && |ex3_mult_rnd_bit[1:0]; //round to negative infinity + 3'b011: ex3_mult_rnd_in =!ex3_mult_sign && |ex3_mult_rnd_bit[1:0]; //round to positive infinity + 3'b100: ex3_mult_rnd_in = ex3_mult_rnd_bit[1]; +default : ex3_mult_rnd_in = 1'b0; +endcase +// &CombEnd; @672 +end + +assign ex3_mult_frac_sel[0] = ex3_mult_rnd_result[SINGLE_FRAC+1] && ex3_mult_rnd_in; +assign ex3_mult_frac_sel[1] =!ex3_mult_rnd_result[SINGLE_FRAC+1] && ex3_mult_rnd_in; + +assign ex3_mult_no_rnd_result[SINGLE_FRAC-1:0] = ex3_mult_result[SINGLE_FRAC+1] + ? ex3_mult_result[SINGLE_FRAC:1] + : ex3_mult_result[SINGLE_FRAC-1:0]; +// &CombBeg; @680 +always @( ex3_mult_no_rnd_result[22:0] + or ex3_mult_frac_sel[1:0] + or ex3_mult_rnd_result[23:0]) +begin +case(ex3_mult_frac_sel[1:0]) + 2'b01: ex3_mult_frac_result[SINGLE_FRAC-1:0] = ex3_mult_rnd_result[SINGLE_FRAC:1]; + 2'b10: ex3_mult_frac_result[SINGLE_FRAC-1:0] = ex3_mult_rnd_result[SINGLE_FRAC-1:0]; +default: ex3_mult_frac_result[SINGLE_FRAC-1:0] = ex3_mult_no_rnd_result[SINGLE_FRAC-1:0]; +endcase +// &CombEnd; @686 +end + +assign ex3_mult_expnt_add_in = ex3_mult_result[SINGLE_FRAC+1] + || &ex3_mult_result[SINGLE_FRAC-1:0] && ex3_mult_rnd_in; + +assign ex3_mult_expnt_plus_1[SINGLE_EXPN+1:0] = ex3_mult_expnt[SINGLE_EXPN+1:0] + 1'b1; + +assign ex3_mult_expnt_result[SINGLE_EXPN-1:0] = ex3_mult_expnt_add_in + ? ex3_mult_expnt_plus_1[SINGLE_EXPN-1:0] + : ex3_mult_expnt[SINGLE_EXPN-1:0]; + +assign ex3_mult_single_result[SINGLE_WIDTH-1:0] = { ex3_mult_sign, + ex3_mult_expnt_result[SINGLE_EXPN-1:0], + ex3_mult_frac_result[SINGLE_FRAC-1:SINGLE_FRAC-SINGLE_FRAC]}; + +assign ex3_mult_nx = |ex3_mult_rnd_bit[1:0]; + +assign fmau_fpu_ex3_result[SINGLE_WIDTH-1:0] = ex3_mult_single_result[SINGLE_WIDTH-1:0]; + +assign fmau_fpu_ex3_fflags[4:0] = {4'b0,ex3_mult_nx}; + +// &ModuleEnd; @708 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_mult.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_mult.v new file mode 100644 index 0000000000000000000000000000000000000000..c963f3a3fb611813b0a678aef03d6ee812b6372a --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_mult.v @@ -0,0 +1,134 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_frac_mult( + ctrl_dp_ex1_inst_pipe_down, + ctrl_xx_ex1_warm_up, + ex1_frac_0, + ex1_frac_1, + ex2_mult_data, + fmau_ex2_data_clk +); + +// &Ports; @25 +input ctrl_dp_ex1_inst_pipe_down; +input ctrl_xx_ex1_warm_up; +input [23:0] ex1_frac_0; +input [23:0] ex1_frac_1; +input fmau_ex2_data_clk; +output [47:0] ex2_mult_data; + +// &Regs; @26 +reg [47:0] ex2_partial_result_0; +reg [47:0] ex2_partial_result_1; + +// &Wires; @27 +wire ctrl_dp_ex1_inst_pipe_down; +wire ctrl_xx_ex1_warm_up; +wire [23:0] ex1_frac_0; +wire [23:0] ex1_frac_1; +wire [49:0] ex1_partial_result_0; +wire [49:0] ex1_partial_result_1; +wire [47:0] ex2_mult_data; +wire fmau_ex2_data_clk; +wire [23:0] mult_0_0; +wire [23:0] mult_0_1; +wire [49:0] result_0_0; +wire [49:0] result_0_1; + + +// &Depend("cpu_cfig.h"); @29 + +parameter FPU_WIDTH = 64; +parameter SINGLE_FRAC = 23; +parameter DOUBLE_FRAC = 52; +parameter SINGLE_EXPN = 8; +parameter DOUBLE_EXPN = 11; +parameter FUNC_WIDTH = 10; + +//========================================================== +// EX1 data path +//========================================================== + +// &Instance("pa_fmau_multiplier_53x27_partial","multiplier_53x27"); @52 +// &Connect( @53 +// .a(mult_0_0), @54 +// .b(mult_0_1), @55 +// .out0(result_0_0), @56 +// .out1(result_0_1) @57 +// ); @58 +// &Instance("pa_fmau_multiplier_53x27_partial","multiplier_53x26"); @60 +// &Connect( @61 +// .a(mult_1_0), @62 +// .b(mult_1_1), @63 +// .out0(result_1_0), @64 +// .out1(result_1_1) @65 +// ); @66 +// &Force("bus","result_0_0",83,0); @68 +// &Force("bus","result_0_1",83,0); @69 +// &Force("bus","result_1_0",83,0); @70 +// &Force("bus","result_1_1",83,0); @71 +// &Force("nonport", "mult_0_0"); @79 +// &Force("nonport", "mult_0_1"); @80 +// &Force("nonport", "result_0_0"); @81 +// &Force("nonport", "result_0_1"); @82 +// &Force("nonport", "mult_1_0"); @92 +// &Force("nonport", "mult_1_1"); @93 +// &Force("nonport", "result_1_0"); @94 +// &Force("nonport", "result_1_1"); @95 + +assign mult_0_0[23:0] = ex1_frac_0[23:0]; +assign mult_0_1[23:0] = ex1_frac_1[23:0]; + +// &Instance("pa_fmau_multiplier_24x24_partial","multiplier_24x24"); @164 +pa_fmau_multiplier_24x24_partial multiplier_24x24 ( + .a (mult_0_0 ), + .b (mult_0_1 ), + .out0 (result_0_0), + .out1 (result_0_1) +); + +// &Connect( @165 +// .a(mult_0_0), @166 +// .b(mult_0_1), @167 +// .out0(result_0_0), @168 +// .out1(result_0_1) @169 +// ); @170 + +// &Force("nonport", "mult_0_0"); @174 +// &Force("nonport", "mult_0_1"); @175 +// &Force("nonport", "result_0_0"); @176 +// &Force("nonport", "result_0_1"); @177 +assign ex1_partial_result_0[49:0] = result_0_0[49:0]; +assign ex1_partial_result_1[49:0] = result_0_1[49:0]; + + +always@(posedge fmau_ex2_data_clk) +begin + if(ctrl_dp_ex1_inst_pipe_down || ctrl_xx_ex1_warm_up) + begin + ex2_partial_result_0[47:0] <= ex1_partial_result_0[47:0]; + ex2_partial_result_1[47:0] <= ex1_partial_result_1[47:0]; + end +end + +assign ex2_mult_data[47:0] = ex2_partial_result_0[47:0] + ex2_partial_result_1[47:0]; + +// &ModuleEnd; @220 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_shift.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_shift.v new file mode 100644 index 0000000000000000000000000000000000000000..6e9308950f69bfca070d3e643635a83e3d73a587 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_frac_shift.v @@ -0,0 +1,159 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_frac_shift( + ctrl_dp_ex1_inst_pipe_down, + ctrl_xx_ex1_warm_up, + ex1_expnt_2, + ex1_mult_expnt, + ex2_adder_0_sel_h, + ex2_expnt_2, + ex2_frac_2, + ex2_mac, + ex2_mac_expnt, + ex2_mult_expnt, + ex2_shift_data, + fmau_ex2_data_clk +); + +// &Ports; @25 +input ctrl_dp_ex1_inst_pipe_down; +input ctrl_xx_ex1_warm_up; +input [9 :0] ex1_expnt_2; +input [9 :0] ex1_mult_expnt; +input [9 :0] ex2_expnt_2; +input [23:0] ex2_frac_2; +input ex2_mac; +input [9 :0] ex2_mult_expnt; +input fmau_ex2_data_clk; +output ex2_adder_0_sel_h; +output [9 :0] ex2_mac_expnt; +output [52:0] ex2_shift_data; + +// &Regs; @26 +reg [9 :0] ex2_left_max; +reg [9 :0] ex2_mac_expnt_diff; +reg ex2_right_sel; +reg [5 :0] ex2_shift_index; + +// &Wires; @27 +wire ctrl_dp_ex1_inst_pipe_down; +wire ctrl_xx_ex1_warm_up; +wire [9 :0] ex1_expnt_2; +wire [9 :0] ex1_left_max; +wire [9 :0] ex1_mac_expnt_diff; +wire [9 :0] ex1_mult_expnt; +wire [9 :0] ex1_right_max; +wire ex1_right_sel; +wire ex2_adder_0_sel_h; +wire [23:0] ex2_data_for_shift; +wire [9 :0] ex2_expnt_2; +wire [23:0] ex2_frac_2; +wire ex2_mac; +wire [9 :0] ex2_mac_expnt; +wire [9 :0] ex2_mult_expnt; +wire [9 :0] ex2_right_max; +wire [52:0] ex2_shift_data; +wire [52:0] ex2_shift_data_out; +wire [2 :0] ex2_shift_sel; +wire fmau_ex2_data_clk; + + +// &Depend("cpu_cfig.h"); @29 + +parameter DOUBLE_WIDTH= 64; +parameter DOUBLE_FRAC = 52; +parameter DOUBLE_EXPN = 11; + +parameter SINGLE_WIDTH= 32; +parameter SINGLE_FRAC = 23; +parameter SINGLE_EXPN = 8; + +parameter FUNC_WIDTH = 10; + +//========================================================== +// EX1 data path +//========================================================== +// &CombBeg; @88 +// &CombEnd; @95 +// &Instance("pa_fmau_src2_shifter_double","x_pa_fmau_src2_shifter_double"); @107 +assign ex1_mac_expnt_diff[SINGLE_EXPN+1:0] = ex1_mult_expnt[SINGLE_EXPN+1:0] + + {{SINGLE_EXPN{1'b0}},2'b10} - + {ex1_expnt_2[SINGLE_EXPN+1:0]}; + +assign ex1_right_max[SINGLE_EXPN+1:0] = 10'b00_0011_0011;//51=2*FRAC+5 + +assign ex1_right_sel = (ex1_mac_expnt_diff[SINGLE_EXPN:0]< ex1_right_max[SINGLE_EXPN:0]); + +assign ex1_left_max[SINGLE_EXPN+1:0] = 10'b00_0001_1001 + //FRAC+2 -(-D) + + ex1_mac_expnt_diff[SINGLE_EXPN+1:0]; + +always @(posedge fmau_ex2_data_clk) +begin + if(ctrl_dp_ex1_inst_pipe_down || ctrl_xx_ex1_warm_up) + begin + ex2_mac_expnt_diff[SINGLE_EXPN+1:0]<= ex1_mac_expnt_diff[SINGLE_EXPN+1:0]; + ex2_left_max[SINGLE_EXPN+1:0] <= ex1_left_max[SINGLE_EXPN+1:0]; + ex2_right_sel <= ex1_right_sel; + end +end + +assign ex2_shift_sel[0] = !ex2_mac_expnt_diff[SINGLE_EXPN+1] && ex2_right_sel;//right shift diff +assign ex2_shift_sel[1] = !ex2_mac_expnt_diff[SINGLE_EXPN+1] && !ex2_right_sel;//right shift 2*FRAC+5 +assign ex2_shift_sel[2] = ex2_mac_expnt_diff[SINGLE_EXPN+1] && !ex2_left_max[SINGLE_EXPN+1]; //left shift FRAC+2-|diff| + +assign ex2_right_max[SINGLE_EXPN+1:0] = 10'b00_0011_0011;//51=2*FRAC+5 + +// &CombBeg; @156 +always @( ex2_left_max[5:0] + or ex2_right_max[5:0] + or ex2_mac_expnt_diff[5:0] + or ex2_shift_sel[2:0]) +begin +case(ex2_shift_sel[2:0]) + 3'b001: ex2_shift_index[5:0] = ex2_mac_expnt_diff[5:0]; + 3'b010: ex2_shift_index[5:0] = ex2_right_max[5:0]; + 3'b100: ex2_shift_index[5:0] = ex2_left_max[5:0]; + default: ex2_shift_index[5:0] = {6{1'b0}}; +endcase +// &CombEnd; @163 +end + +assign ex2_mac_expnt[SINGLE_EXPN+1:0] = ex2_mac_expnt_diff[SINGLE_EXPN+1] + ? ex2_expnt_2[SINGLE_EXPN+1:0] + { {4{1'b0}},ex2_shift_index[5:0]} + : ex2_mult_expnt[SINGLE_EXPN+1:0]+{ {SINGLE_EXPN{1'b0}},2'b10}; + +assign ex2_data_for_shift[SINGLE_FRAC:0] = ex2_frac_2[SINGLE_FRAC:0]; + +assign ex2_adder_0_sel_h = ex2_mac_expnt_diff[SINGLE_EXPN+1] || !ex2_mac; +//========================================================== +// EX2 data path +//========================================================== +// &Instance("pa_fmau_src2_shifter_single","x_pa_fmau_src2_shifter_single"); @175 +pa_fmau_src2_shifter_single x_pa_fmau_src2_shifter_single ( + .ex2_data_for_shift (ex2_data_for_shift), + .ex2_shift_data_out (ex2_shift_data_out), + .ex2_shift_index (ex2_shift_index ) +); + +assign ex2_shift_data[52:0] = ex2_shift_data_out[52:0]; + + +// &ModuleEnd; @180 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_lza_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_lza_single.v new file mode 100644 index 0000000000000000000000000000000000000000..8e0a80f6b6d048ad28729b44414ecdfed58b0195 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_lza_single.v @@ -0,0 +1,151 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fmau_lza_single( + addend, + lza_result, + sub_vld, + summand, + upper_limit +); + +// &Ports; @24 +input [52:0] addend; +input sub_vld; +input [52:0] summand; +input [52:0] upper_limit; +output [6 :0] lza_result; + +// &Regs; @25 +reg [6 :0] lza_result; + +// &Wires; @26 +wire [52:0] addend; +wire [52:0] carry_d; +wire [52:0] carry_g; +wire [52:0] carry_p; +wire [52:0] data_for_ff1; +wire [52:0] lza_precod; +wire sub_vld; +wire [52:0] summand; +wire [52:0] upper_limit; + + +parameter DATA_WIDTH = 53; +//========================================================== +// Signal Pre-encode +//========================================================== +//---------------------------------------------------------- +// Signal preparation +//---------------------------------------------------------- +// carry_p: carry propagete +// carry_g: carry generate +// carry_d: carry delete +assign carry_p[DATA_WIDTH-1:0] = summand[DATA_WIDTH-1:0] ^ addend[DATA_WIDTH-1:0]; +assign carry_g[DATA_WIDTH-1:0] = summand[DATA_WIDTH-1:0] & addend[DATA_WIDTH-1:0]; +assign carry_d[DATA_WIDTH-1:0] = ~(summand[DATA_WIDTH-1:0] | addend[DATA_WIDTH-1:0]); +//---------------------------------------------------------- +// Signal decode +//---------------------------------------------------------- +//pre-predecode for leading zero anticipation +assign lza_precod[0] = + carry_p[1] && (carry_g[0] && sub_vld || carry_d[0]) + || !carry_p[1] && (carry_d[0] && sub_vld || carry_g[0]); + +assign lza_precod[DATA_WIDTH-1] = + sub_vld && (carry_g[DATA_WIDTH-1] && !carry_d[DATA_WIDTH-2] + || carry_d[DATA_WIDTH-1] && !carry_g[DATA_WIDTH-2]) + || !sub_vld && (carry_d[DATA_WIDTH-1] && !carry_d[DATA_WIDTH-2] + || !carry_d[DATA_WIDTH-1]); + +assign lza_precod[DATA_WIDTH-2:1] = + carry_p[DATA_WIDTH-1:2] & (carry_g[DATA_WIDTH-2:1] & ~carry_d[DATA_WIDTH-3:0] + | carry_d[DATA_WIDTH-2:1] & ~carry_g[DATA_WIDTH-3:0]) + | ~carry_p[DATA_WIDTH-1:2] & (carry_g[DATA_WIDTH-2:1] & ~carry_g[DATA_WIDTH-3:0] + | carry_d[DATA_WIDTH-2:1] & ~carry_d[DATA_WIDTH-3:0]); + + +//========================================================== +// LZA coding +//========================================================== +assign data_for_ff1[DATA_WIDTH-1:0] = lza_precod[DATA_WIDTH-1:0] | upper_limit[DATA_WIDTH-1:0]; +// &CombBeg; @66 +always @( data_for_ff1[52:0]) +begin +casez(data_for_ff1[DATA_WIDTH-1:0]) + 53'b1????????????????????????????????????????????????????:lza_result[6:0] = 7'd0; + 53'b01???????????????????????????????????????????????????:lza_result[6:0] = 7'd1; + 53'b001??????????????????????????????????????????????????:lza_result[6:0] = 7'd2; + 53'b0001?????????????????????????????????????????????????:lza_result[6:0] = 7'd3; + 53'b00001????????????????????????????????????????????????:lza_result[6:0] = 7'd4; + 53'b000001???????????????????????????????????????????????:lza_result[6:0] = 7'd5; + 53'b0000001??????????????????????????????????????????????:lza_result[6:0] = 7'd6; + 53'b00000001?????????????????????????????????????????????:lza_result[6:0] = 7'd7; + 53'b000000001????????????????????????????????????????????:lza_result[6:0] = 7'd8; + 53'b0000000001???????????????????????????????????????????:lza_result[6:0] = 7'd9; + 53'b00000000001??????????????????????????????????????????:lza_result[6:0] = 7'd10; + 53'b000000000001?????????????????????????????????????????:lza_result[6:0] = 7'd11; + 53'b0000000000001????????????????????????????????????????:lza_result[6:0] = 7'd12; + 53'b00000000000001???????????????????????????????????????:lza_result[6:0] = 7'd13; + 53'b000000000000001??????????????????????????????????????:lza_result[6:0] = 7'd14; + 53'b0000000000000001?????????????????????????????????????:lza_result[6:0] = 7'd15; + 53'b00000000000000001????????????????????????????????????:lza_result[6:0] = 7'd16; + 53'b000000000000000001???????????????????????????????????:lza_result[6:0] = 7'd17; + 53'b0000000000000000001??????????????????????????????????:lza_result[6:0] = 7'd18; + 53'b00000000000000000001?????????????????????????????????:lza_result[6:0] = 7'd19; + 53'b000000000000000000001????????????????????????????????:lza_result[6:0] = 7'd20; + 53'b0000000000000000000001???????????????????????????????:lza_result[6:0] = 7'd21; + 53'b00000000000000000000001??????????????????????????????:lza_result[6:0] = 7'd22; + 53'b000000000000000000000001?????????????????????????????:lza_result[6:0] = 7'd23; + 53'b0000000000000000000000001????????????????????????????:lza_result[6:0] = 7'd24; + 53'b00000000000000000000000001???????????????????????????:lza_result[6:0] = 7'd25; + 53'b000000000000000000000000001??????????????????????????:lza_result[6:0] = 7'd26; + 53'b0000000000000000000000000001?????????????????????????:lza_result[6:0] = 7'd27; + 53'b00000000000000000000000000001????????????????????????:lza_result[6:0] = 7'd28; + 53'b000000000000000000000000000001???????????????????????:lza_result[6:0] = 7'd29; + 53'b0000000000000000000000000000001??????????????????????:lza_result[6:0] = 7'd30; + 53'b00000000000000000000000000000001?????????????????????:lza_result[6:0] = 7'd31; + 53'b000000000000000000000000000000001????????????????????:lza_result[6:0] = 7'd32; + 53'b0000000000000000000000000000000001???????????????????:lza_result[6:0] = 7'd33; + 53'b00000000000000000000000000000000001??????????????????:lza_result[6:0] = 7'd34; + 53'b000000000000000000000000000000000001?????????????????:lza_result[6:0] = 7'd35; + 53'b0000000000000000000000000000000000001????????????????:lza_result[6:0] = 7'd36; + 53'b00000000000000000000000000000000000001???????????????:lza_result[6:0] = 7'd37; + 53'b000000000000000000000000000000000000001??????????????:lza_result[6:0] = 7'd38; + 53'b0000000000000000000000000000000000000001?????????????:lza_result[6:0] = 7'd39; + 53'b00000000000000000000000000000000000000001????????????:lza_result[6:0] = 7'd40; + 53'b000000000000000000000000000000000000000001???????????:lza_result[6:0] = 7'd41; + 53'b0000000000000000000000000000000000000000001??????????:lza_result[6:0] = 7'd42; + 53'b00000000000000000000000000000000000000000001?????????:lza_result[6:0] = 7'd43; + 53'b000000000000000000000000000000000000000000001????????:lza_result[6:0] = 7'd44; + 53'b0000000000000000000000000000000000000000000001???????:lza_result[6:0] = 7'd45; + 53'b00000000000000000000000000000000000000000000001??????:lza_result[6:0] = 7'd46; + 53'b000000000000000000000000000000000000000000000001?????:lza_result[6:0] = 7'd47; + 53'b0000000000000000000000000000000000000000000000001????:lza_result[6:0] = 7'd48; + 53'b00000000000000000000000000000000000000000000000001???:lza_result[6:0] = 7'd49; + 53'b000000000000000000000000000000000000000000000000001??:lza_result[6:0] = 7'd50; + 53'b0000000000000000000000000000000000000000000000000001?:lza_result[6:0] = 7'd51; + 53'b00000000000000000000000000000000000000000000000000001:lza_result[6:0] = 7'd52; + 53'b00000000000000000000000000000000000000000000000000000:lza_result[6:0] = 7'd53; + default :lza_result[6:0] = 7'd0; +endcase +// &CombEnd; @124 +end + +// &ModuleEnd; @126 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_multiplier_24x24_partial.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_multiplier_24x24_partial.v new file mode 100644 index 0000000000000000000000000000000000000000..3524be508250b3d8a3720f0ca9e5dbd769a765a2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_multiplier_24x24_partial.v @@ -0,0 +1,444 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_fmau_multiplier_24x24_partial( + a, + b, + out0, + out1 +); + +// &Ports; @21 +input [23:0] a; +input [23:0] b; +output [49:0] out0; +output [49:0] out1; + +// &Regs; @22 + +// &Wires; @23 +wire [23:0] a; +wire [23:0] b; +wire [26:0] data_for_code; +wire [49:0] ex1_c0_0; +wire [49:0] ex1_c0_1; +wire [49:0] ex1_c0_2; +wire [49:0] ex1_c1_0; +wire [49:0] ex1_c1_1; +wire [50:0] ex1_c2_0; +wire [49:0] ex1_p0_0_0; +wire [49:0] ex1_p0_0_1; +wire [49:0] ex1_p0_0_2; +wire [49:0] ex1_p0_0_3; +wire [49:0] ex1_p0_0_cout; +wire [49:0] ex1_p0_0_xor; +wire [49:0] ex1_p0_1_0; +wire [49:0] ex1_p0_1_1; +wire [49:0] ex1_p0_1_2; +wire [49:0] ex1_p0_1_3; +wire [49:0] ex1_p0_1_cout; +wire [49:0] ex1_p0_1_xor; +wire [49:0] ex1_p0_2_0; +wire [49:0] ex1_p0_2_1; +wire [49:0] ex1_p0_2_2; +wire [49:0] ex1_p0_2_3; +wire [49:0] ex1_p0_2_cout; +wire [49:0] ex1_p0_2_xor; +wire [49:0] ex1_p0_3_0; +wire [49:0] ex1_p0_3_1; +wire [49:0] ex1_p1_0_0; +wire [49:0] ex1_p1_0_1; +wire [49:0] ex1_p1_0_2; +wire [49:0] ex1_p1_0_3; +wire [49:0] ex1_p1_0_cout; +wire [49:0] ex1_p1_0_xor; +wire [49:0] ex1_p1_1_0; +wire [49:0] ex1_p1_1_1; +wire [49:0] ex1_p1_1_2; +wire [49:0] ex1_p1_1_3; +wire [49:0] ex1_p1_1_cout; +wire [49:0] ex1_p1_1_xor; +wire [50:0] ex1_p2_0_0; +wire [50:0] ex1_p2_0_1; +wire [50:0] ex1_p2_0_2; +wire [50:0] ex1_p2_0_3; +wire [50:0] ex1_p2_0_cout; +wire [50:0] ex1_p2_0_xor; +wire [49:0] ex1_s0_0; +wire [49:0] ex1_s0_1; +wire [49:0] ex1_s0_2; +wire [49:0] ex1_s1_0; +wire [49:0] ex1_s1_1; +wire [50:0] ex1_s2_0; +wire [1 :0] h0; +wire [1 :0] h1; +wire [1 :0] h10; +wire [1 :0] h11; +wire [1 :0] h12; +wire [1 :0] h2; +wire [1 :0] h3; +wire [1 :0] h4; +wire [1 :0] h5; +wire [1 :0] h6; +wire [1 :0] h7; +wire [1 :0] h8; +wire [1 :0] h9; +wire [24:0] mult_src; +wire [24:0] multiplicand; +wire [49:0] out0; +wire [49:0] out1; +wire [24:0] part_product0; +wire [24:0] part_product1; +wire [24:0] part_product10; +wire [24:0] part_product11; +wire [24:0] part_product12; +wire [24:0] part_product2; +wire [24:0] part_product3; +wire [24:0] part_product4; +wire [24:0] part_product5; +wire [24:0] part_product6; +wire [24:0] part_product7; +wire [24:0] part_product8; +wire [24:0] part_product9; +wire [12:0] sign_not; + + +parameter SRC0_WIDTH = 25; +parameter SRC1_WIDTH = 25; +parameter DST_WIDTH = 50; + +assign multiplicand[SRC0_WIDTH-1:0] = {1'b0,a[SRC0_WIDTH-2:0]}; +assign mult_src[SRC1_WIDTH-1:0] = {1'b0,b[SRC1_WIDTH-2:0]}; + +assign data_for_code[SRC1_WIDTH+1:0] = {mult_src[SRC1_WIDTH-1],mult_src[SRC1_WIDTH-1:0],1'b0}; + + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit0"); @35 +booth_code_25_bit x_pa_booth_code_25_bit0 ( + .A (multiplicand[24:0] ), + .code (data_for_code[2:0] ), + .h (h0[1:0] ), + .product (part_product0[24:0]), + .sn (sign_not[0] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @36 +// .code(data_for_code[2:0]), @37 +// .product(part_product0[SRC0_WIDTH-1:0]), @38 +// .h(h0[1:0]), @39 +// .sn(sign_not[0])); @40 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit1"); @42 +booth_code_25_bit x_pa_booth_code_25_bit1 ( + .A (multiplicand[24:0] ), + .code (data_for_code[4:2] ), + .h (h1[1:0] ), + .product (part_product1[24:0]), + .sn (sign_not[1] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @43 +// .code(data_for_code[4:2]), @44 +// .product(part_product1[SRC0_WIDTH-1:0]), @45 +// .h(h1[1:0]), @46 +// .sn(sign_not[1])); @47 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit2"); @49 +booth_code_25_bit x_pa_booth_code_25_bit2 ( + .A (multiplicand[24:0] ), + .code (data_for_code[6:4] ), + .h (h2[1:0] ), + .product (part_product2[24:0]), + .sn (sign_not[2] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @50 +// .code(data_for_code[6:4]), @51 +// .product(part_product2[SRC0_WIDTH-1:0]), @52 +// .h(h2[1:0]), @53 +// .sn(sign_not[2])); @54 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit3"); @56 +booth_code_25_bit x_pa_booth_code_25_bit3 ( + .A (multiplicand[24:0] ), + .code (data_for_code[8:6] ), + .h (h3[1:0] ), + .product (part_product3[24:0]), + .sn (sign_not[3] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @57 +// .code(data_for_code[8:6]), @58 +// .product(part_product3[SRC0_WIDTH-1:0]), @59 +// .h(h3[1:0]), @60 +// .sn(sign_not[3])); @61 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit4"); @63 +booth_code_25_bit x_pa_booth_code_25_bit4 ( + .A (multiplicand[24:0] ), + .code (data_for_code[10:8]), + .h (h4[1:0] ), + .product (part_product4[24:0]), + .sn (sign_not[4] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @64 +// .code(data_for_code[10:8]), @65 +// .product(part_product4[SRC0_WIDTH-1:0]), @66 +// .h(h4[1:0]), @67 +// .sn(sign_not[4])); @68 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit5"); @70 +booth_code_25_bit x_pa_booth_code_25_bit5 ( + .A (multiplicand[24:0] ), + .code (data_for_code[12:10]), + .h (h5[1:0] ), + .product (part_product5[24:0] ), + .sn (sign_not[5] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @71 +// .code(data_for_code[12:10]), @72 +// .product(part_product5[SRC0_WIDTH-1:0]), @73 +// .h(h5[1:0]), @74 +// .sn(sign_not[5])); @75 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit6"); @77 +booth_code_25_bit x_pa_booth_code_25_bit6 ( + .A (multiplicand[24:0] ), + .code (data_for_code[14:12]), + .h (h6[1:0] ), + .product (part_product6[24:0] ), + .sn (sign_not[6] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @78 +// .code(data_for_code[14:12]), @79 +// .product(part_product6[SRC0_WIDTH-1:0]), @80 +// .h(h6[1:0]), @81 +// .sn(sign_not[6])); @82 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit7"); @84 +booth_code_25_bit x_pa_booth_code_25_bit7 ( + .A (multiplicand[24:0] ), + .code (data_for_code[16:14]), + .h (h7[1:0] ), + .product (part_product7[24:0] ), + .sn (sign_not[7] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @85 +// .code(data_for_code[16:14]), @86 +// .product(part_product7[SRC0_WIDTH-1:0]), @87 +// .h(h7[1:0]), @88 +// .sn(sign_not[7])); @89 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit8"); @91 +booth_code_25_bit x_pa_booth_code_25_bit8 ( + .A (multiplicand[24:0] ), + .code (data_for_code[18:16]), + .h (h8[1:0] ), + .product (part_product8[24:0] ), + .sn (sign_not[8] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @92 +// .code(data_for_code[18:16]), @93 +// .product(part_product8[SRC0_WIDTH-1:0]), @94 +// .h(h8[1:0]), @95 +// .sn(sign_not[8])); @96 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit9"); @98 +booth_code_25_bit x_pa_booth_code_25_bit9 ( + .A (multiplicand[24:0] ), + .code (data_for_code[20:18]), + .h (h9[1:0] ), + .product (part_product9[24:0] ), + .sn (sign_not[9] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @99 +// .code(data_for_code[20:18]), @100 +// .product(part_product9[SRC0_WIDTH-1:0]), @101 +// .h(h9[1:0]), @102 +// .sn(sign_not[9])); @103 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit10"); @105 +booth_code_25_bit x_pa_booth_code_25_bit10 ( + .A (multiplicand[24:0] ), + .code (data_for_code[22:20]), + .h (h10[1:0] ), + .product (part_product10[24:0]), + .sn (sign_not[10] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @106 +// .code(data_for_code[22:20]), @107 +// .product(part_product10[SRC0_WIDTH-1:0]), @108 +// .h(h10[1:0]), @109 +// .sn(sign_not[10])); @110 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit11"); @112 +booth_code_25_bit x_pa_booth_code_25_bit11 ( + .A (multiplicand[24:0] ), + .code (data_for_code[24:22]), + .h (h11[1:0] ), + .product (part_product11[24:0]), + .sn (sign_not[11] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @113 +// .code(data_for_code[24:22]), @114 +// .product(part_product11[SRC0_WIDTH-1:0]), @115 +// .h(h11[1:0]), @116 +// .sn(sign_not[11])); @117 + +// &Instance("booth_code_25_bit", "x_pa_booth_code_25_bit12"); @119 +booth_code_25_bit x_pa_booth_code_25_bit12 ( + .A (multiplicand[24:0] ), + .code (data_for_code[26:24]), + .h (h12[1:0] ), + .product (part_product12[24:0]), + .sn (sign_not[12] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @120 +// .code(data_for_code[26:24]), @121 +// .product(part_product12[SRC0_WIDTH-1:0]), @122 +// .h(h12[1:0]), @123 +// .sn(sign_not[12])); @124 + +//============================================================================= +// prepare for the the first compression +//============================================================================= + +assign ex1_p0_0_0[DST_WIDTH-1:0] = { {22{1'b0}}, sign_not[0],{2{!sign_not[0]}},part_product0[SRC0_WIDTH-1:0]}; +assign ex1_p0_0_1[DST_WIDTH-1:0] = { {21{1'b0}},1'b1, sign_not[1], part_product1[SRC0_WIDTH-1:0], h0[1:0]}; +assign ex1_p0_0_2[DST_WIDTH-1:0] = { {19{1'b0}},1'b1, sign_not[2], part_product2[SRC0_WIDTH-1:0], h1[1:0], { 2{1'b0}} }; +assign ex1_p0_0_3[DST_WIDTH-1:0] = { {17{1'b0}},1'b1, sign_not[3], part_product3[SRC0_WIDTH-1:0], h2[1:0], { 4{1'b0}} }; + +assign ex1_p0_1_0[DST_WIDTH-1:0] = { {15{1'b0}},1'b1, sign_not[4], part_product4[SRC0_WIDTH-1:0], h3[1:0], { 6{1'b0}} }; +assign ex1_p0_1_1[DST_WIDTH-1:0] = { {13{1'b0}},1'b1, sign_not[5], part_product5[SRC0_WIDTH-1:0], h4[1:0], { 8{1'b0}} }; +assign ex1_p0_1_2[DST_WIDTH-1:0] = { {11{1'b0}},1'b1, sign_not[6], part_product6[SRC0_WIDTH-1:0], h5[1:0], {10{1'b0}} }; +assign ex1_p0_1_3[DST_WIDTH-1:0] = { { 9{1'b0}},1'b1, sign_not[7], part_product7[SRC0_WIDTH-1:0], h6[1:0], {12{1'b0}} }; + +assign ex1_p0_2_0[DST_WIDTH-1:0] = { { 7{1'b0}},1'b1, sign_not[8], part_product8[SRC0_WIDTH-1:0], h7[1:0], {14{1'b0}} }; +assign ex1_p0_2_1[DST_WIDTH-1:0] = { { 5{1'b0}},1'b1, sign_not[9], part_product9[SRC0_WIDTH-1:0], h8[1:0], {16{1'b0}} }; +assign ex1_p0_2_2[DST_WIDTH-1:0] = { { 3{1'b0}},1'b1, sign_not[10], part_product10[SRC0_WIDTH-1:0],h9[1:0], {18{1'b0}} }; +assign ex1_p0_2_3[DST_WIDTH-1:0] = { { 1{1'b0}},1'b1, sign_not[11], part_product11[SRC0_WIDTH-1:0],h10[1:0],{20{1'b0}} }; + +assign ex1_p0_3_0[DST_WIDTH-1:0] = { sign_not[12], part_product12[SRC0_WIDTH-1:0],h11[1:0],{22{1'b0}} }; +assign ex1_p0_3_1[DST_WIDTH-1:0] = { {22{1'b0}}, h12[1:0],{26{1'b0}} }; + + +//=========== 14 src to 8 src==========// +assign ex1_p0_0_cout[DST_WIDTH-1:0] = (ex1_p0_0_0[DST_WIDTH-1:0] & ex1_p0_0_1[DST_WIDTH-1:0]) | + (ex1_p0_0_1[DST_WIDTH-1:0] & ex1_p0_0_2[DST_WIDTH-1:0]) | + (ex1_p0_0_0[DST_WIDTH-1:0] & ex1_p0_0_2[DST_WIDTH-1:0]) ; + +assign ex1_p0_0_xor[DST_WIDTH-1:0] = (ex1_p0_0_0[DST_WIDTH-1:0] ^ ex1_p0_0_1[DST_WIDTH-1:0]) ^ + (ex1_p0_0_2[DST_WIDTH-1:0] ^ ex1_p0_0_3[DST_WIDTH-1:0]); + +assign ex1_s0_0[DST_WIDTH-1:0] = ex1_p0_0_xor[DST_WIDTH-1:0]^ {ex1_p0_0_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c0_0[DST_WIDTH-1:0] = ex1_p0_0_xor[DST_WIDTH-1:0]& {ex1_p0_0_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p0_0_xor[DST_WIDTH-1:0]& ex1_p0_0_3[DST_WIDTH-1:0]); + +//---------------------------------------------- +assign ex1_p0_1_cout[DST_WIDTH-1:0] = (ex1_p0_1_0[DST_WIDTH-1:0] & ex1_p0_1_1[DST_WIDTH-1:0]) | + (ex1_p0_1_1[DST_WIDTH-1:0] & ex1_p0_1_2[DST_WIDTH-1:0]) | + (ex1_p0_1_0[DST_WIDTH-1:0] & ex1_p0_1_2[DST_WIDTH-1:0]) ; + +assign ex1_p0_1_xor[DST_WIDTH-1:0] = (ex1_p0_1_0[DST_WIDTH-1:0] ^ ex1_p0_1_1[DST_WIDTH-1:0]) ^ + (ex1_p0_1_2[DST_WIDTH-1:0] ^ ex1_p0_1_3[DST_WIDTH-1:0]); + +assign ex1_s0_1[DST_WIDTH-1:0] = ex1_p0_1_xor[DST_WIDTH-1:0]^ {ex1_p0_1_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c0_1[DST_WIDTH-1:0] = ex1_p0_1_xor[DST_WIDTH-1:0]& {ex1_p0_1_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p0_1_xor[DST_WIDTH-1:0]& ex1_p0_1_3[DST_WIDTH-1:0]); + +//---------------------------------------------- +assign ex1_p0_2_cout[DST_WIDTH-1:0] = (ex1_p0_2_0[DST_WIDTH-1:0] & ex1_p0_2_1[DST_WIDTH-1:0]) | + (ex1_p0_2_1[DST_WIDTH-1:0] & ex1_p0_2_2[DST_WIDTH-1:0]) | + (ex1_p0_2_0[DST_WIDTH-1:0] & ex1_p0_2_2[DST_WIDTH-1:0]) ; + +assign ex1_p0_2_xor[DST_WIDTH-1:0] = (ex1_p0_2_0[DST_WIDTH-1:0] ^ ex1_p0_2_1[DST_WIDTH-1:0]) ^ + (ex1_p0_2_2[DST_WIDTH-1:0] ^ ex1_p0_2_3[DST_WIDTH-1:0]); + +assign ex1_s0_2[DST_WIDTH-1:0] = ex1_p0_2_xor[DST_WIDTH-1:0]^ {ex1_p0_2_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c0_2[DST_WIDTH-1:0] = ex1_p0_2_xor[DST_WIDTH-1:0]& {ex1_p0_2_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p0_2_xor[DST_WIDTH-1:0]& ex1_p0_2_3[DST_WIDTH-1:0]); + +//============================================================================= +// prepare for the the second compression +//============================================================================= +assign ex1_p1_0_0[DST_WIDTH-1:0] = ex1_s0_0[DST_WIDTH-1:0]; +assign ex1_p1_0_1[DST_WIDTH-1:0] ={ex1_c0_0[DST_WIDTH-2:0],1'b0}; +assign ex1_p1_0_2[DST_WIDTH-1:0] = ex1_s0_1[DST_WIDTH-1:0]; +assign ex1_p1_0_3[DST_WIDTH-1:0] ={ex1_c0_1[DST_WIDTH-2:0],1'b0}; + +assign ex1_p1_1_0[DST_WIDTH-1:0] = ex1_s0_2[DST_WIDTH-1:0]; +assign ex1_p1_1_1[DST_WIDTH-1:0] ={ex1_c0_2[DST_WIDTH-2:0],1'b0}; +assign ex1_p1_1_2[DST_WIDTH-1:0] = ex1_p0_3_0[DST_WIDTH-1:0]; +assign ex1_p1_1_3[DST_WIDTH-1:0] = ex1_p0_3_1[DST_WIDTH-1:0]; + +//=========== 8 src to 4 src==========// +assign ex1_p1_0_cout[DST_WIDTH-1:0] = (ex1_p1_0_0[DST_WIDTH-1:0] & ex1_p1_0_1[DST_WIDTH-1:0]) | + (ex1_p1_0_1[DST_WIDTH-1:0] & ex1_p1_0_2[DST_WIDTH-1:0]) | + (ex1_p1_0_0[DST_WIDTH-1:0] & ex1_p1_0_2[DST_WIDTH-1:0]) ; + +assign ex1_p1_0_xor[DST_WIDTH-1:0] = (ex1_p1_0_0[DST_WIDTH-1:0] ^ ex1_p1_0_1[DST_WIDTH-1:0]) ^ + (ex1_p1_0_2[DST_WIDTH-1:0] ^ ex1_p1_0_3[DST_WIDTH-1:0]); + +assign ex1_s1_0[DST_WIDTH-1:0] = ex1_p1_0_xor[DST_WIDTH-1:0]^ {ex1_p1_0_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c1_0[DST_WIDTH-1:0] = ex1_p1_0_xor[DST_WIDTH-1:0]& {ex1_p1_0_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p1_0_xor[DST_WIDTH-1:0]& ex1_p1_0_3[DST_WIDTH-1:0]); +//---------------------------------------------- +assign ex1_p1_1_cout[DST_WIDTH-1:0] = (ex1_p1_1_0[DST_WIDTH-1:0] & ex1_p1_1_1[DST_WIDTH-1:0]) | + (ex1_p1_1_1[DST_WIDTH-1:0] & ex1_p1_1_2[DST_WIDTH-1:0]) | + (ex1_p1_1_0[DST_WIDTH-1:0] & ex1_p1_1_2[DST_WIDTH-1:0]) ; + +assign ex1_p1_1_xor[DST_WIDTH-1:0] = (ex1_p1_1_0[DST_WIDTH-1:0] ^ ex1_p1_1_1[DST_WIDTH-1:0]) ^ + (ex1_p1_1_2[DST_WIDTH-1:0] ^ ex1_p1_1_3[DST_WIDTH-1:0]); + +assign ex1_s1_1[DST_WIDTH-1:0] = ex1_p1_1_xor[DST_WIDTH-1:0]^ {ex1_p1_1_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c1_1[DST_WIDTH-1:0] = ex1_p1_1_xor[DST_WIDTH-1:0]& {ex1_p1_1_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p1_1_xor[DST_WIDTH-1:0]& ex1_p1_1_3[DST_WIDTH-1:0]); + +//============================================================================= +// prepare for the the third compression +//============================================================================= +assign ex1_p2_0_0[DST_WIDTH :0] ={ex1_s1_0[DST_WIDTH-1],ex1_s1_0[DST_WIDTH-1:0]}; +assign ex1_p2_0_1[DST_WIDTH :0] ={ex1_c1_0[DST_WIDTH-1:0],1'b0}; +assign ex1_p2_0_2[DST_WIDTH :0] ={ex1_s1_1[DST_WIDTH-1],ex1_s1_1[DST_WIDTH-1:0]}; +assign ex1_p2_0_3[DST_WIDTH :0] ={ex1_c1_1[DST_WIDTH-1:0],1'b0}; +//=========== 4 src to 2 src==========// +assign ex1_p2_0_cout[DST_WIDTH :0] = (ex1_p2_0_0[DST_WIDTH :0] & ex1_p2_0_1[DST_WIDTH :0]) | + (ex1_p2_0_1[DST_WIDTH :0] & ex1_p2_0_2[DST_WIDTH :0]) | + (ex1_p2_0_0[DST_WIDTH :0] & ex1_p2_0_2[DST_WIDTH :0]) ; + +assign ex1_p2_0_xor[DST_WIDTH :0] = (ex1_p2_0_0[DST_WIDTH :0] ^ ex1_p2_0_1[DST_WIDTH :0]) ^ + (ex1_p2_0_2[DST_WIDTH :0] ^ ex1_p2_0_3[DST_WIDTH :0]); + +assign ex1_s2_0[DST_WIDTH :0] = ex1_p2_0_xor[DST_WIDTH :0]^ {ex1_p2_0_cout[DST_WIDTH-1:0],1'b0}; +assign ex1_c2_0[DST_WIDTH :0] = ex1_p2_0_xor[DST_WIDTH :0]& {ex1_p2_0_cout[DST_WIDTH-1:0],1'b0}| + (~ex1_p2_0_xor[DST_WIDTH :0]& ex1_p2_0_3[DST_WIDTH :0]); + + +assign out0[DST_WIDTH-1:0] ={ex1_s2_0[DST_WIDTH-1:0]}; +assign out1[DST_WIDTH-1:0] ={ex1_c2_0[DST_WIDTH-2:0],1'b0}; + +// &ModuleEnd; @244 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_src2_shifter_single.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_src2_shifter_single.v new file mode 100644 index 0000000000000000000000000000000000000000..e6602ee89baa7760110847fe030cd0129d846dc3 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_src2_shifter_single.v @@ -0,0 +1,178 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_fmau_src2_shifter_single( + ex2_data_for_shift, + ex2_shift_data_out, + ex2_shift_index +); + +// &Ports; @25 +input [23:0] ex2_data_for_shift; +input [5 :0] ex2_shift_index; +output [52:0] ex2_shift_data_out; + +// &Regs; @26 +reg [52:0] shift_data; + +// &Wires; @27 +wire [52:0] data_for_shift; +wire [23:0] ex2_data_for_shift; +wire [52:0] ex2_shift_data_out; +wire [5 :0] ex2_shift_index; +wire [5 :0] shift_index; + + +parameter DATA_WIDTH = 53; +parameter SINGLE_FRAC = 23; + +assign data_for_shift[DATA_WIDTH-1:0] = {1'b0,ex2_data_for_shift[SINGLE_FRAC:0], {SINGLE_FRAC{1'b0}}, 5'b0}; + +assign shift_index[5:0] = ex2_shift_index[5:0]; + +// &CombBeg; @36 +always @( data_for_shift[52: 17] + or data_for_shift[52: 3] + or data_for_shift[52: 45] + or data_for_shift[52: 8] + or data_for_shift[52: 10] + or data_for_shift[52: 39] + or data_for_shift[52: 35] + or data_for_shift[52: 28] + or data_for_shift[52: 46] + or data_for_shift[52: 7] + or data_for_shift[52: 49] + or data_for_shift[52: 29] + or data_for_shift[52: 2] + or data_for_shift[52: 24] + or data_for_shift[52: 38] + or data_for_shift[52: 43] + or data_for_shift[52: 52] + or data_for_shift[52: 33] + or data_for_shift[52: 48] + or data_for_shift[52: 27] + or data_for_shift[52: 18] + or data_for_shift[52: 14] + or data_for_shift[52: 15] + or shift_index[5:0] + or data_for_shift[52: 13] + or data_for_shift[52: 5] + or data_for_shift[52: 22] + or data_for_shift[52: 23] + or data_for_shift[52: 34] + or data_for_shift[52: 37] + or data_for_shift[52: 12] + or data_for_shift[52: 40] + or data_for_shift[52: 6] + or data_for_shift[52: 25] + or data_for_shift[52: 21] + or data_for_shift[52: 31] + or data_for_shift[52: 47] + or data_for_shift[52: 19] + or data_for_shift[52: 4] + or data_for_shift[52: 32] + or data_for_shift[51:0] + or data_for_shift[52: 1] + or data_for_shift[52: 26] + or data_for_shift[52: 16] + or data_for_shift[52: 42] + or data_for_shift[52: 50] + or data_for_shift[52: 41] + or data_for_shift[52: 36] + or data_for_shift[52: 30] + or data_for_shift[52: 9] + or data_for_shift[52: 51] + or data_for_shift[52: 44] + or data_for_shift[52: 20] + or data_for_shift[52: 11]) +begin +case(shift_index[5:0]) +6'b00_0000: shift_data[DATA_WIDTH-1:0] = { data_for_shift[DATA_WIDTH-1: 1], data_for_shift[0] }; +6'b00_0001: shift_data[DATA_WIDTH-1:0] = {{ 1{1'b0}},data_for_shift[DATA_WIDTH-1: 2],|data_for_shift[1 :0]}; +6'b00_0010: shift_data[DATA_WIDTH-1:0] = {{ 2{1'b0}},data_for_shift[DATA_WIDTH-1: 3],|data_for_shift[2 :0]}; +6'b00_0011: shift_data[DATA_WIDTH-1:0] = {{ 3{1'b0}},data_for_shift[DATA_WIDTH-1: 4],|data_for_shift[3 :0]}; +6'b00_0100: shift_data[DATA_WIDTH-1:0] = {{ 4{1'b0}},data_for_shift[DATA_WIDTH-1: 5],|data_for_shift[4 :0]}; +6'b00_0101: shift_data[DATA_WIDTH-1:0] = {{ 5{1'b0}},data_for_shift[DATA_WIDTH-1: 6],|data_for_shift[5 :0]}; +6'b00_0110: shift_data[DATA_WIDTH-1:0] = {{ 6{1'b0}},data_for_shift[DATA_WIDTH-1: 7],|data_for_shift[6 :0]}; +6'b00_0111: shift_data[DATA_WIDTH-1:0] = {{ 7{1'b0}},data_for_shift[DATA_WIDTH-1: 8],|data_for_shift[7 :0]}; +6'b00_1000: shift_data[DATA_WIDTH-1:0] = {{ 8{1'b0}},data_for_shift[DATA_WIDTH-1: 9],|data_for_shift[8 :0]}; +6'b00_1001: shift_data[DATA_WIDTH-1:0] = {{ 9{1'b0}},data_for_shift[DATA_WIDTH-1: 10],|data_for_shift[9 :0]}; +6'b00_1010: shift_data[DATA_WIDTH-1:0] = {{ 10{1'b0}},data_for_shift[DATA_WIDTH-1: 11],|data_for_shift[10 :0]}; +6'b00_1011: shift_data[DATA_WIDTH-1:0] = {{ 11{1'b0}},data_for_shift[DATA_WIDTH-1: 12],|data_for_shift[11 :0]}; +6'b00_1100: shift_data[DATA_WIDTH-1:0] = {{ 12{1'b0}},data_for_shift[DATA_WIDTH-1: 13],|data_for_shift[12 :0]}; +6'b00_1101: shift_data[DATA_WIDTH-1:0] = {{ 13{1'b0}},data_for_shift[DATA_WIDTH-1: 14],|data_for_shift[13 :0]}; +6'b00_1110: shift_data[DATA_WIDTH-1:0] = {{ 14{1'b0}},data_for_shift[DATA_WIDTH-1: 15],|data_for_shift[14 :0]}; +6'b00_1111: shift_data[DATA_WIDTH-1:0] = {{ 15{1'b0}},data_for_shift[DATA_WIDTH-1: 16],|data_for_shift[15 :0]}; +6'b01_0000: shift_data[DATA_WIDTH-1:0] = {{ 16{1'b0}},data_for_shift[DATA_WIDTH-1: 17],|data_for_shift[16 :0]}; +6'b01_0001: shift_data[DATA_WIDTH-1:0] = {{ 17{1'b0}},data_for_shift[DATA_WIDTH-1: 18],|data_for_shift[17 :0]}; +6'b01_0010: shift_data[DATA_WIDTH-1:0] = {{ 18{1'b0}},data_for_shift[DATA_WIDTH-1: 19],|data_for_shift[18 :0]}; +6'b01_0011: shift_data[DATA_WIDTH-1:0] = {{ 19{1'b0}},data_for_shift[DATA_WIDTH-1: 20],|data_for_shift[19 :0]}; +6'b01_0100: shift_data[DATA_WIDTH-1:0] = {{ 20{1'b0}},data_for_shift[DATA_WIDTH-1: 21],|data_for_shift[20 :0]}; +6'b01_0101: shift_data[DATA_WIDTH-1:0] = {{ 21{1'b0}},data_for_shift[DATA_WIDTH-1: 22],|data_for_shift[21 :0]}; +6'b01_0110: shift_data[DATA_WIDTH-1:0] = {{ 22{1'b0}},data_for_shift[DATA_WIDTH-1: 23],|data_for_shift[22 :0]}; +6'b01_0111: shift_data[DATA_WIDTH-1:0] = {{ 23{1'b0}},data_for_shift[DATA_WIDTH-1: 24],|data_for_shift[23 :0]}; +6'b01_1000: shift_data[DATA_WIDTH-1:0] = {{ 24{1'b0}},data_for_shift[DATA_WIDTH-1: 25],|data_for_shift[24 :0]}; +6'b01_1001: shift_data[DATA_WIDTH-1:0] = {{ 25{1'b0}},data_for_shift[DATA_WIDTH-1: 26],|data_for_shift[25 :0]}; +6'b01_1010: shift_data[DATA_WIDTH-1:0] = {{ 26{1'b0}},data_for_shift[DATA_WIDTH-1: 27],|data_for_shift[26 :0]}; +6'b01_1011: shift_data[DATA_WIDTH-1:0] = {{ 27{1'b0}},data_for_shift[DATA_WIDTH-1: 28],|data_for_shift[27 :0]}; +6'b01_1100: shift_data[DATA_WIDTH-1:0] = {{ 28{1'b0}},data_for_shift[DATA_WIDTH-1: 29],|data_for_shift[28 :0]}; +6'b01_1101: shift_data[DATA_WIDTH-1:0] = {{ 29{1'b0}},data_for_shift[DATA_WIDTH-1: 30],|data_for_shift[29 :0]}; +6'b01_1110: shift_data[DATA_WIDTH-1:0] = {{ 30{1'b0}},data_for_shift[DATA_WIDTH-1: 31],|data_for_shift[30 :0]}; +6'b01_1111: shift_data[DATA_WIDTH-1:0] = {{ 31{1'b0}},data_for_shift[DATA_WIDTH-1: 32],|data_for_shift[31 :0]}; +6'b10_0000: shift_data[DATA_WIDTH-1:0] = {{ 32{1'b0}},data_for_shift[DATA_WIDTH-1: 33],|data_for_shift[32 :0]}; +6'b10_0001: shift_data[DATA_WIDTH-1:0] = {{ 33{1'b0}},data_for_shift[DATA_WIDTH-1: 34],|data_for_shift[33 :0]}; +6'b10_0010: shift_data[DATA_WIDTH-1:0] = {{ 34{1'b0}},data_for_shift[DATA_WIDTH-1: 35],|data_for_shift[34 :0]}; +6'b10_0011: shift_data[DATA_WIDTH-1:0] = {{ 35{1'b0}},data_for_shift[DATA_WIDTH-1: 36],|data_for_shift[35 :0]}; +6'b10_0100: shift_data[DATA_WIDTH-1:0] = {{ 36{1'b0}},data_for_shift[DATA_WIDTH-1: 37],|data_for_shift[36 :0]}; +6'b10_0101: shift_data[DATA_WIDTH-1:0] = {{ 37{1'b0}},data_for_shift[DATA_WIDTH-1: 38],|data_for_shift[37 :0]}; +6'b10_0110: shift_data[DATA_WIDTH-1:0] = {{ 38{1'b0}},data_for_shift[DATA_WIDTH-1: 39],|data_for_shift[38 :0]}; +6'b10_0111: shift_data[DATA_WIDTH-1:0] = {{ 39{1'b0}},data_for_shift[DATA_WIDTH-1: 40],|data_for_shift[39 :0]}; +6'b10_1000: shift_data[DATA_WIDTH-1:0] = {{ 40{1'b0}},data_for_shift[DATA_WIDTH-1: 41],|data_for_shift[40 :0]}; +6'b10_1001: shift_data[DATA_WIDTH-1:0] = {{ 41{1'b0}},data_for_shift[DATA_WIDTH-1: 42],|data_for_shift[41 :0]}; +6'b10_1010: shift_data[DATA_WIDTH-1:0] = {{ 42{1'b0}},data_for_shift[DATA_WIDTH-1: 43],|data_for_shift[42 :0]}; +6'b10_1011: shift_data[DATA_WIDTH-1:0] = {{ 43{1'b0}},data_for_shift[DATA_WIDTH-1: 44],|data_for_shift[43 :0]}; +6'b10_1100: shift_data[DATA_WIDTH-1:0] = {{ 44{1'b0}},data_for_shift[DATA_WIDTH-1: 45],|data_for_shift[44 :0]}; +6'b10_1101: shift_data[DATA_WIDTH-1:0] = {{ 45{1'b0}},data_for_shift[DATA_WIDTH-1: 46],|data_for_shift[45 :0]}; +6'b10_1110: shift_data[DATA_WIDTH-1:0] = {{ 46{1'b0}},data_for_shift[DATA_WIDTH-1: 47],|data_for_shift[46 :0]}; +6'b10_1111: shift_data[DATA_WIDTH-1:0] = {{ 47{1'b0}},data_for_shift[DATA_WIDTH-1: 48],|data_for_shift[47 :0]}; +6'b11_0000: shift_data[DATA_WIDTH-1:0] = {{ 48{1'b0}},data_for_shift[DATA_WIDTH-1: 49],|data_for_shift[48 :0]}; +6'b11_0001: shift_data[DATA_WIDTH-1:0] = {{ 49{1'b0}},data_for_shift[DATA_WIDTH-1: 50],|data_for_shift[49 :0]}; +6'b11_0010: shift_data[DATA_WIDTH-1:0] = {{ 50{1'b0}},data_for_shift[DATA_WIDTH-1: 51],|data_for_shift[50 :0]}; +6'b11_0011: shift_data[DATA_WIDTH-1:0] = {{ 51{1'b0}},data_for_shift[DATA_WIDTH-1: 52],|data_for_shift[51 :0]}; + default: shift_data[DATA_WIDTH-1:0] = {DATA_WIDTH{1'bx}}; +endcase +// &CombEnd; @92 +end + +assign ex2_shift_data_out[DATA_WIDTH-1:0] = shift_data[DATA_WIDTH-1:0]; + +// &ModuleEnd; @96 +endmodule + + + + + + + + + + + + + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_top.v new file mode 100644 index 0000000000000000000000000000000000000000..cd7ef7c424621c4a5e0a3f434be621e23146d1ee --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fmau/rtl/pa_fmau_top.v @@ -0,0 +1,259 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_fmau_top( + cp0_fpu_icg_en, + cp0_fpu_xx_dqnan, + cp0_yy_clk_en, + cpurst_b, + ctrl_fmau_ex1_sel, + ctrl_fmau_ex1_sel_gate, + ctrl_xx_ex1_cmplt_dp, + ctrl_xx_ex1_stall, + ctrl_xx_ex1_warm_up, + ctrl_xx_ex2_cancel, + ctrl_xx_ex2_stall, + ctrl_xx_ex2_warm_up, + ctrl_xx_ex3_stall, + ctrl_xx_ex3_warm_up, + ctrl_xx_ex4_stall, + dp_xx_ex1_cnan, + dp_xx_ex1_id, + dp_xx_ex1_inf, + dp_xx_ex1_norm, + dp_xx_ex1_qnan, + dp_xx_ex1_rm, + dp_xx_ex1_snan, + dp_xx_ex1_srcf2, + dp_xx_ex1_zero, + dp_xx_ex2_srcf2, + dp_xx_ex3_rm, + dp_xx_ex4_rm, + fmau_fpu_ex1_cmplt, + fmau_fpu_ex1_cmplt_dp, + fmau_fpu_ex1_denorm_stall, + fmau_fpu_ex1_fflags, + fmau_fpu_ex1_special_sel, + fmau_fpu_ex1_special_sign, + fmau_fpu_ex3_fflags, + fmau_fpu_ex3_result, + fmau_fpu_ex3_result_vld, + fmau_fpu_ex4_fflags, + fmau_fpu_ex4_result, + fmau_fpu_id_reg_set, + forever_cpuclk, + idu_fpu_ex1_eu_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + pad_yy_icg_scan_en, + rtu_xx_ex1_cancel +); + +// &Ports; @24 +input cp0_fpu_icg_en; +input cp0_fpu_xx_dqnan; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_fmau_ex1_sel; +input ctrl_fmau_ex1_sel_gate; +input ctrl_xx_ex1_cmplt_dp; +input ctrl_xx_ex1_stall; +input ctrl_xx_ex1_warm_up; +input ctrl_xx_ex2_cancel; +input ctrl_xx_ex2_stall; +input ctrl_xx_ex2_warm_up; +input ctrl_xx_ex3_stall; +input ctrl_xx_ex3_warm_up; +input ctrl_xx_ex4_stall; +input [2 :0] dp_xx_ex1_cnan; +input [2 :0] dp_xx_ex1_id; +input [2 :0] dp_xx_ex1_inf; +input [2 :0] dp_xx_ex1_norm; +input [2 :0] dp_xx_ex1_qnan; +input [2 :0] dp_xx_ex1_rm; +input [2 :0] dp_xx_ex1_snan; +input [31:0] dp_xx_ex1_srcf2; +input [2 :0] dp_xx_ex1_zero; +input [31:0] dp_xx_ex2_srcf2; +input [2 :0] dp_xx_ex3_rm; +input [2 :0] dp_xx_ex4_rm; +input forever_cpuclk; +input [2 :0] idu_fpu_ex1_eu_sel; +input [9 :0] idu_fpu_ex1_func; +input [31:0] idu_fpu_ex1_srcf0; +input [31:0] idu_fpu_ex1_srcf1; +input pad_yy_icg_scan_en; +input rtu_xx_ex1_cancel; +output fmau_fpu_ex1_cmplt; +output fmau_fpu_ex1_cmplt_dp; +output fmau_fpu_ex1_denorm_stall; +output [4 :0] fmau_fpu_ex1_fflags; +output [7 :0] fmau_fpu_ex1_special_sel; +output [3 :0] fmau_fpu_ex1_special_sign; +output [4 :0] fmau_fpu_ex3_fflags; +output [31:0] fmau_fpu_ex3_result; +output fmau_fpu_ex3_result_vld; +output [4 :0] fmau_fpu_ex4_fflags; +output [31:0] fmau_fpu_ex4_result; +output fmau_fpu_id_reg_set; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_fpu_icg_en; +wire cp0_fpu_xx_dqnan; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_dp_ex1_inst_pipe_down; +wire ctrl_dp_ex1_inst_vld; +wire ctrl_dp_ex2_inst_pipe_down; +wire ctrl_dp_ex2_inst_vld; +wire ctrl_dp_ex3_inst_pipe_down; +wire ctrl_dp_ex3_inst_vld; +wire ctrl_fmau_ex1_sel; +wire ctrl_fmau_ex1_sel_gate; +wire ctrl_xx_ex1_cmplt_dp; +wire ctrl_xx_ex1_stall; +wire ctrl_xx_ex1_warm_up; +wire ctrl_xx_ex2_cancel; +wire ctrl_xx_ex2_stall; +wire ctrl_xx_ex2_warm_up; +wire ctrl_xx_ex3_stall; +wire ctrl_xx_ex3_warm_up; +wire ctrl_xx_ex4_stall; +wire dp_ctrl_ex3_mac; +wire [2 :0] dp_xx_ex1_cnan; +wire [2 :0] dp_xx_ex1_id; +wire [2 :0] dp_xx_ex1_inf; +wire [2 :0] dp_xx_ex1_norm; +wire [2 :0] dp_xx_ex1_qnan; +wire [2 :0] dp_xx_ex1_rm; +wire [2 :0] dp_xx_ex1_snan; +wire [31:0] dp_xx_ex1_srcf2; +wire [2 :0] dp_xx_ex1_zero; +wire [31:0] dp_xx_ex2_srcf2; +wire [2 :0] dp_xx_ex3_rm; +wire [2 :0] dp_xx_ex4_rm; +wire [1 :0] ex1_id_reg; +wire ex2_special_cmplt; +wire fmau_fpu_ex1_cmplt; +wire fmau_fpu_ex1_cmplt_dp; +wire fmau_fpu_ex1_denorm_stall; +wire [4 :0] fmau_fpu_ex1_fflags; +wire [7 :0] fmau_fpu_ex1_special_sel; +wire [3 :0] fmau_fpu_ex1_special_sign; +wire [4 :0] fmau_fpu_ex3_fflags; +wire [31:0] fmau_fpu_ex3_result; +wire fmau_fpu_ex3_result_vld; +wire [4 :0] fmau_fpu_ex4_fflags; +wire [31:0] fmau_fpu_ex4_result; +wire fmau_fpu_id_reg_set; +wire forever_cpuclk; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire pad_yy_icg_scan_en; +wire rtu_xx_ex1_cancel; + + +// &Depend("cpu_cfig.h"); @28 + +// &Instance("pa_fmau_dp","x_pa_fmau_dp"); @30 +pa_fmau_dp x_pa_fmau_dp ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_fpu_xx_dqnan (cp0_fpu_xx_dqnan ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .ctrl_dp_ex1_inst_pipe_down (ctrl_dp_ex1_inst_pipe_down), + .ctrl_dp_ex1_inst_vld (ctrl_dp_ex1_inst_vld ), + .ctrl_dp_ex2_inst_pipe_down (ctrl_dp_ex2_inst_pipe_down), + .ctrl_dp_ex2_inst_vld (ctrl_dp_ex2_inst_vld ), + .ctrl_dp_ex3_inst_pipe_down (ctrl_dp_ex3_inst_pipe_down), + .ctrl_dp_ex3_inst_vld (ctrl_dp_ex3_inst_vld ), + .ctrl_xx_ex1_warm_up (ctrl_xx_ex1_warm_up ), + .ctrl_xx_ex2_warm_up (ctrl_xx_ex2_warm_up ), + .ctrl_xx_ex3_warm_up (ctrl_xx_ex3_warm_up ), + .dp_ctrl_ex3_mac (dp_ctrl_ex3_mac ), + .dp_xx_ex1_cnan (dp_xx_ex1_cnan ), + .dp_xx_ex1_inf (dp_xx_ex1_inf ), + .dp_xx_ex1_norm (dp_xx_ex1_norm ), + .dp_xx_ex1_qnan (dp_xx_ex1_qnan ), + .dp_xx_ex1_rm (dp_xx_ex1_rm ), + .dp_xx_ex1_snan (dp_xx_ex1_snan ), + .dp_xx_ex1_srcf2 (dp_xx_ex1_srcf2 ), + .dp_xx_ex1_zero (dp_xx_ex1_zero ), + .dp_xx_ex2_srcf2 (dp_xx_ex2_srcf2 ), + .dp_xx_ex3_rm (dp_xx_ex3_rm ), + .dp_xx_ex4_rm (dp_xx_ex4_rm ), + .ex1_id_reg (ex1_id_reg ), + .ex2_special_cmplt (ex2_special_cmplt ), + .fmau_fpu_ex1_fflags (fmau_fpu_ex1_fflags ), + .fmau_fpu_ex1_special_sel (fmau_fpu_ex1_special_sel ), + .fmau_fpu_ex1_special_sign (fmau_fpu_ex1_special_sign ), + .fmau_fpu_ex3_fflags (fmau_fpu_ex3_fflags ), + .fmau_fpu_ex3_result (fmau_fpu_ex3_result ), + .fmau_fpu_ex4_fflags (fmau_fpu_ex4_fflags ), + .fmau_fpu_ex4_result (fmau_fpu_ex4_result ), + .forever_cpuclk (forever_cpuclk ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .idu_fpu_ex1_func (idu_fpu_ex1_func ), + .idu_fpu_ex1_srcf0 (idu_fpu_ex1_srcf0 ), + .idu_fpu_ex1_srcf1 (idu_fpu_ex1_srcf1 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Instance("pa_fmau_ctrl","x_pa_fmau_ctrl"); @31 +pa_fmau_ctrl x_pa_fmau_ctrl ( + .cp0_fpu_icg_en (cp0_fpu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_dp_ex1_inst_pipe_down (ctrl_dp_ex1_inst_pipe_down), + .ctrl_dp_ex1_inst_vld (ctrl_dp_ex1_inst_vld ), + .ctrl_dp_ex2_inst_pipe_down (ctrl_dp_ex2_inst_pipe_down), + .ctrl_dp_ex2_inst_vld (ctrl_dp_ex2_inst_vld ), + .ctrl_dp_ex3_inst_pipe_down (ctrl_dp_ex3_inst_pipe_down), + .ctrl_dp_ex3_inst_vld (ctrl_dp_ex3_inst_vld ), + .ctrl_fmau_ex1_sel (ctrl_fmau_ex1_sel ), + .ctrl_fmau_ex1_sel_gate (ctrl_fmau_ex1_sel_gate ), + .ctrl_xx_ex1_cmplt_dp (ctrl_xx_ex1_cmplt_dp ), + .ctrl_xx_ex1_stall (ctrl_xx_ex1_stall ), + .ctrl_xx_ex2_cancel (ctrl_xx_ex2_cancel ), + .ctrl_xx_ex2_stall (ctrl_xx_ex2_stall ), + .ctrl_xx_ex3_stall (ctrl_xx_ex3_stall ), + .ctrl_xx_ex4_stall (ctrl_xx_ex4_stall ), + .dp_ctrl_ex3_mac (dp_ctrl_ex3_mac ), + .dp_xx_ex1_id (dp_xx_ex1_id ), + .ex1_id_reg (ex1_id_reg ), + .ex2_special_cmplt (ex2_special_cmplt ), + .fmau_fpu_ex1_cmplt (fmau_fpu_ex1_cmplt ), + .fmau_fpu_ex1_cmplt_dp (fmau_fpu_ex1_cmplt_dp ), + .fmau_fpu_ex1_denorm_stall (fmau_fpu_ex1_denorm_stall ), + .fmau_fpu_ex3_result_vld (fmau_fpu_ex3_result_vld ), + .fmau_fpu_id_reg_set (fmau_fpu_id_reg_set ), + .forever_cpuclk (forever_cpuclk ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_xx_ex1_cancel (rtu_xx_ex1_cancel ) +); + + + +// &ModuleEnd; @196 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/fpga_ram.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/fpga_ram.v new file mode 100644 index 0000000000000000000000000000000000000000..d972a57973594e8ba33bd2876f2cd3ddf20c4399 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/fpga_ram.v @@ -0,0 +1,66 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module fpga_ram( + PortAClk, + PortAAddr, + PortADataIn, + PortAWriteEnable, +// PortAChipEnable, + PortADataOut +); + +parameter DATAWIDTH = 2; +parameter ADDRWIDTH = 2; + +input PortAClk; +input [(ADDRWIDTH-1):0] PortAAddr; +input [(DATAWIDTH-1):0] PortADataIn; +input PortAWriteEnable; +//input PortAChipEnable; +output [(DATAWIDTH-1):0] PortADataOut; + +parameter MEMDEPTH = 2**(ADDRWIDTH); + +reg [(DATAWIDTH-1):0] mem [(MEMDEPTH-1):0] /* synthesis syn_ramstyle = "no_rw_check" */; +reg [(DATAWIDTH-1):0] PortADataOut; + +always @(posedge PortAClk) +begin + if(PortAWriteEnable) + begin + mem[PortAAddr] <= PortADataIn; + PortADataOut <= PortADataIn; + end + else + begin + PortADataOut <= mem[PortAAddr]; + end +end + +//wire [(DATAWIDTH-1):0] tt; +//assign t = mem[PortAAddr]; +//always @(posedge PortAClk) +//begin +// if(PortAWriteEnable) +// begin +// PortADataOut <= PortADataIn; +// end +// else +// begin +// PortADataOut <= mem[PortAAddr]; +// end +//end + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/pa_f_spsram_1024x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/pa_f_spsram_1024x32.v new file mode 100644 index 0000000000000000000000000000000000000000..66d32c6617b0d5da102cb23c9f62b6de255d2cdf --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/fpga/rtl/pa_f_spsram_1024x32.v @@ -0,0 +1,73 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_f_spsram_1024x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +parameter ADDR_WIDTH = 10; +parameter DATA_WIDTH = 32; +parameter WRAP_SIZE = 1; + +input [ADDR_WIDTH-1:0] A; +input CEN; +input CLK; +input [DATA_WIDTH-1:0] D; +input GWEN; +input [DATA_WIDTH-1:0] WEN; +output [DATA_WIDTH-1:0] Q; + +reg [ADDR_WIDTH-1:0] addr_holding; + +wire [ADDR_WIDTH-1:0] A; +wire CEN; +wire CLK; +wire [DATA_WIDTH-1:0] D; +wire GWEN; +wire [DATA_WIDTH-1:0] WEN; +wire [DATA_WIDTH-1:0] Q; +wire [ADDR_WIDTH-1:0] addr; + +always@(posedge CLK) +begin + if(!CEN) begin + addr_holding[ADDR_WIDTH-1:0] <= A[ADDR_WIDTH-1:0]; + end +end + +assign addr[ADDR_WIDTH-1:0] = CEN ? addr_holding[ADDR_WIDTH-1:0] + : A[ADDR_WIDTH-1:0]; + +wire [DATA_WIDTH-1:0] ram_wen_vec; +genvar i; +generate + for(i=0; i ex2 > wb +// Note that wb fwd is already done in gpr +// &Force("input", "iu_idu_ex1_fwd_preg"); @107 +// &Force("bus", "iu_idu_ex1_fwd_preg", 5, 0); @108 +assign dp_rs1_dep_ex1 = decd_dp_rs1_idx[5:0] == ctrl_dp_ex1_dst_preg[5:0] + & ctrl_dp_ex1_dst_preg[5:0] != 6'b0 + & ctrl_dp_ex1_dst_vld + & ~(ctrl_dp_ex1_lsu_sel & dp_ex1_func[8]) + & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs1_fwd_ex1 = dp_rs1_dep_ex1 & iu_idu_ex1_fwd_vld | dp_rs1_fwd_ex1_lsinc; + +assign dp_rs2_dep_ex1 = decd_dp_rs2_idx[5:0] == ctrl_dp_ex1_dst_preg[5:0] + & ctrl_dp_ex1_dst_preg[5:0] != 6'b0 + & ctrl_dp_ex1_dst_vld + & ~(ctrl_dp_ex1_lsu_sel & dp_ex1_func[8]) + & decd_dp_rs2_vld; +assign dp_rs2_fwd_ex1 = dp_rs2_dep_ex1 & iu_idu_ex1_fwd_vld | dp_rs2_fwd_ex1_lsinc; + +assign dp_rs3_dep_ex1 = decd_dp_rs3_idx[5:0] == ctrl_dp_ex1_dst_preg[5:0] + & ctrl_dp_ex1_dst_preg[5:0] != 6'b0 + & ctrl_dp_ex1_dst_vld + & ~(ctrl_dp_ex1_lsu_sel & dp_ex1_func[8]) + & decd_dp_rs3_vld; +assign dp_rs3_fwd_ex1 = dp_rs3_dep_ex1 & iu_idu_ex1_fwd_vld | dp_rs3_fwd_ex1_lsinc; + +// fwd from ex1 rs1 when ld/st inc vld +assign dp_rs1_dep_ex1_lsinc = decd_dp_rs1_idx[5:0] == dp_ex1_src0_reg[5:0] + & dp_ex1_src0_reg[5:0] != 6'b0 + & ctrl_dp_ex1_lsu_sel & dp_ex1_func[8] + & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs1_fwd_ex1_lsinc = dp_rs1_dep_ex1_lsinc & iu_idu_ex1_fwd_vld; + +assign dp_rs2_dep_ex1_lsinc = decd_dp_rs2_idx[5:0] == dp_ex1_src0_reg[5:0] + & dp_ex1_src0_reg[5:0] != 6'b0 + & ctrl_dp_ex1_lsu_sel & dp_ex1_func[8] + & decd_dp_rs2_vld; +assign dp_rs2_fwd_ex1_lsinc = dp_rs2_dep_ex1_lsinc & iu_idu_ex1_fwd_vld; + +assign dp_rs3_dep_ex1_lsinc = decd_dp_rs3_idx[5:0] == dp_ex1_src0_reg[5:0] + & dp_ex1_src0_reg[5:0] != 6'b0 + & ctrl_dp_ex1_lsu_sel & dp_ex1_func[8] + & decd_dp_rs3_vld; +assign dp_rs3_fwd_ex1_lsinc = dp_rs3_dep_ex1_lsinc & iu_idu_ex1_fwd_vld; + +assign dp_rs4_dep_ex1_lsinc = decd_dp_rs4_idx[5:0] == dp_ex1_src0_reg[5:0] + & dp_ex1_src0_reg[5:0] != 6'b0 + & ctrl_dp_ex1_lsu_sel & dp_ex1_func[8] + & decd_dp_rs4_vld; +assign dp_rs4_fwd_ex1_lsinc = dp_rs4_dep_ex1_lsinc & iu_idu_ex1_fwd_vld; + +// fwd ex2 lsu +assign dp_rs1_fwd_ex2_lsu = decd_dp_rs1_idx[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & decd_dp_rs1_idx[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld + & ~(dp_rs1_dep_ex1 | dp_rs1_dep_ex1_lsinc) + & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs2_fwd_ex2_lsu = decd_dp_rs2_idx[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & decd_dp_rs2_idx[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld + & ~(dp_rs2_dep_ex1 | dp_rs2_dep_ex1_lsinc | decd_dp_lsr_vld) + & decd_dp_rs2_vld; +assign dp_rs3_fwd_ex2_lsu = decd_dp_rs3_idx[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & decd_dp_rs3_idx[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld + & ~(dp_rs3_dep_ex1 | dp_rs3_fwd_ex1_lsinc) + & decd_dp_rs3_vld; + +// fwd ex2 rbus +assign dp_rs1_fwd_ex2_rbus0 = decd_dp_rs1_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0] + & iu_idu_ex2_fwd_vld0; +assign dp_rs2_fwd_ex2_rbus0 = decd_dp_rs2_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0] + & iu_idu_ex2_fwd_vld0; +assign dp_rs3_fwd_ex2_rbus0 = decd_dp_rs3_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0] + & iu_idu_ex2_fwd_vld0; +assign dp_rs1_fwd_ex2_rbus1 = decd_dp_rs1_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] + & iu_idu_ex2_fwd_vld1; +assign dp_rs2_fwd_ex2_rbus1 = decd_dp_rs2_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] + & iu_idu_ex2_fwd_vld1; +assign dp_rs3_fwd_ex2_rbus1 = decd_dp_rs3_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] + & iu_idu_ex2_fwd_vld1; +assign dp_rs1_fwd_ex2_rbus = decd_dp_rs1_idx[5:0] != 6'b0 + & (dp_rs1_fwd_ex2_rbus0 | dp_rs1_fwd_ex2_rbus1) + & ~(dp_rs1_dep_ex1 | dp_rs1_dep_ex1_lsinc) + & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs2_fwd_ex2_rbus = decd_dp_rs2_idx[5:0] != 6'b0 + & (dp_rs2_fwd_ex2_rbus0 | dp_rs2_fwd_ex2_rbus1) + & ~(dp_rs2_dep_ex1 | dp_rs2_dep_ex1_lsinc) + & decd_dp_rs2_vld; +assign dp_rs3_fwd_ex2_rbus = decd_dp_rs3_idx[5:0] != 6'b0 + & (dp_rs3_fwd_ex2_rbus0 | dp_rs3_fwd_ex2_rbus1) + & ~(dp_rs3_dep_ex1 | dp_rs3_dep_ex1_lsinc) + & decd_dp_rs3_vld; +assign dp_rs1_aft_fwd_ex2[31:0] = dp_rs1_fwd_ex2_rbus0 ? iu_idu_ex2_fwd_data0[31:0] + : iu_idu_ex2_fwd_data1[31:0]; +assign dp_rs2_aft_fwd_ex2[31:0] = dp_rs2_fwd_ex2_rbus0 ? iu_idu_ex2_fwd_data0[31:0] + : iu_idu_ex2_fwd_data1[31:0]; +assign dp_rs3_aft_fwd_ex2[31:0] = dp_rs3_fwd_ex2_rbus0 ? iu_idu_ex2_fwd_data0[31:0] + : iu_idu_ex2_fwd_data1[31:0]; + +// fwd ex3 lsu +assign dp_rs1_fwd_ex3_lsu = decd_dp_rs1_idx[5:0] == lsu_idu_ex3_fwd_preg[5:0] + & decd_dp_rs1_idx[5:0] != 6'b0 + & lsu_idu_ex3_fwd_vld + & ~(dp_rs1_dep_ex1 | dp_rs1_dep_ex1_lsinc) + & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs2_fwd_ex3_lsu = decd_dp_rs2_idx[5:0] == lsu_idu_ex3_fwd_preg[5:0] + & decd_dp_rs2_idx[5:0] != 6'b0 + & lsu_idu_ex3_fwd_vld + & ~(dp_rs2_dep_ex1 | dp_rs2_dep_ex1_lsinc) + & decd_dp_rs2_vld; +assign dp_rs3_fwd_ex3_lsu = decd_dp_rs3_idx[5:0] == lsu_idu_ex3_fwd_preg[5:0] + & decd_dp_rs3_idx[5:0] != 6'b0 + & lsu_idu_ex3_fwd_vld + & ~(dp_rs3_dep_ex1 | dp_rs3_fwd_ex1_lsinc) + & decd_dp_rs3_vld; +assign dp_rs4_fwd_ex3_lsu = decd_dp_rs4_idx[5:0] == lsu_idu_ex3_fwd_preg[5:0] + & decd_dp_rs4_idx[5:0] != 6'b0 + & lsu_idu_ex3_fwd_vld + & ~(dp_rs4_dep_ex1 | dp_rs4_fwd_ex1_lsinc) + & decd_dp_rs4_vld; + +//assign dp_rs1_fwd_ex3_fpu = decd_dp_rs1_idx[5:0] != 6'b0 +// & decd_dp_rs1_idx[5:0] == fpu_rtu_wb_preg[5:0] +// & ~(dp_rs1_dep_ex1 | dp_rs1_dep_ex1_lsinc) +// & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld) +// & fpu_rtu_wb_vld; +//assign dp_rs2_fwd_ex3_fpu = decd_dp_rs2_idx[5:0] != 6'b0 +// & decd_dp_rs2_idx[5:0] == fpu_rtu_wb_preg[5:0] +// & ~(dp_rs2_dep_ex1 | dp_rs2_dep_ex1_lsinc) +// & decd_dp_rs2_vld +// & fpu_rtu_wb_vld; +//assign dp_rs3_fwd_ex3_fpu = decd_dp_rs3_idx[5:0] != 6'b0 +// & decd_dp_rs3_idx[5:0] == fpu_rtu_wb_preg[5:0] +// & ~(dp_rs3_dep_ex1 | dp_rs3_dep_ex1_lsinc) +// & decd_dp_rs3_vld +// & fpu_rtu_wb_vld; +//assign dp_rs4_fwd_ex3_fpu = decd_dp_rs4_idx[5:0] != 6'b0 +// & decd_dp_rs4_idx[5:0] == fpu_rtu_wb_preg[5:0] +// & ~(dp_rs4_dep_ex1 | dp_rs4_dep_ex1_lsinc) +// & decd_dp_rs4_vld +// & fpu_rtu_wb_vld; +// +//assign dp_rs1_aft_fwd_ex3[31:0] = dp_rs1_fwd_ex3_lsu ? lsu_idu_ex3_fwd_data[31:0] +// : fpu_rtu_wb_data[31:0]; +//assign dp_rs2_aft_fwd_ex3[31:0] = dp_rs2_fwd_ex3_lsu ? lsu_idu_ex3_fwd_data[31:0] +// : fpu_rtu_wb_data[31:0]; +//assign dp_rs3_aft_fwd_ex3[31:0] = dp_rs3_fwd_ex3_lsu ? lsu_idu_ex3_fwd_data[31:0] +// : fpu_rtu_wb_data[31:0]; +//assign dp_rs4_aft_fwd_ex3[31:0] = dp_rs4_fwd_ex3_lsu ? lsu_idu_ex3_fwd_data[31:0] +// : fpu_rtu_wb_data[31:0]; +assign dp_rs1_aft_fwd_ex3[31:0] = lsu_idu_ex3_fwd_data[31:0]; +assign dp_rs2_aft_fwd_ex3[31:0] = lsu_idu_ex3_fwd_data[31:0]; +assign dp_rs3_aft_fwd_ex3[31:0] = lsu_idu_ex3_fwd_data[31:0]; +assign dp_rs4_aft_fwd_ex3[31:0] = lsu_idu_ex3_fwd_data[31:0]; + +assign dp_rs1_fwd_ex3 = dp_rs1_fwd_ex3_lsu;// | dp_rs1_fwd_ex3_fpu; +assign dp_rs2_fwd_ex3 = dp_rs2_fwd_ex3_lsu;// | dp_rs2_fwd_ex3_fpu; +assign dp_rs3_fwd_ex3 = dp_rs3_fwd_ex3_lsu;// | dp_rs3_fwd_ex3_fpu; +assign dp_rs4_fwd_ex3 = dp_rs4_fwd_ex3_lsu;// | dp_rs4_fwd_ex3_fpu; + +assign dp_rs4_dep_ex1 = 1'b0; +assign dp_rs4_fwd_ex1 = 1'b0; +assign dp_rs4_fwd_ex2_rbus = 1'b0; +assign dp_rs4_fwd_ex2_lsu = 1'b0; +assign dp_rs4_aft_fwd_ex2[31:0] = 32'b0; + +assign dp_rs1_aft_fwd_no_lsu[31:0] = dp_rs1_fwd_ex1 ? iu_idu_ex1_fwd_data[31:0] + : dp_rs1_fwd_ex2_rbus ? dp_rs1_aft_fwd_ex2[31:0] + : dp_rs1_fwd_ex3 ? dp_rs1_aft_fwd_ex3[31:0] + : gpr_dp_rs1[31:0]; +assign dp_rs2_aft_fwd_no_lsu[31:0] = dp_rs2_fwd_ex1 ? iu_idu_ex1_fwd_data[31:0] + : dp_rs2_fwd_ex2_rbus ? dp_rs2_aft_fwd_ex2[31:0] + : dp_rs2_fwd_ex3 ? dp_rs2_aft_fwd_ex3[31:0] + : gpr_dp_rs2[31:0]; +assign dp_rs3_aft_fwd_no_lsu[31:0] = dp_rs3_fwd_ex1 ? iu_idu_ex1_fwd_data[31:0] + : dp_rs3_fwd_ex2_rbus ? dp_rs3_aft_fwd_ex2[31:0] + : dp_rs3_fwd_ex3 ? dp_rs3_aft_fwd_ex3[31:0] + : gpr_dp_rs3[31:0]; +assign dp_rs4_aft_fwd_no_lsu[31:0] = dp_rs4_fwd_ex1 ? iu_idu_ex1_fwd_data[31:0] + : dp_rs4_fwd_ex2_rbus ? dp_rs4_aft_fwd_ex2[31:0] + : dp_rs4_fwd_ex3 ? dp_rs4_aft_fwd_ex3[31:0] + : gpr_dp_rs4[31:0]; + +// b. wbbr data and operand data selection +assign dp_rs1_aft_wbbr[31:0] = dp_rs1_aft_fwd_no_lsu[31:0]; +assign dp_rs2_aft_wbbr[31:0] = dp_rs2_aft_fwd_no_lsu[31:0]; + +// c. immediate data gpr data selection +assign dp_rs1_aft_imm[31:0] = cp0_idu_sp_use_scratch ? cp0_idu_sp_wdata[31:0] : decd_dp_csri_vld ? {27'b0, decd_dp_csri_rs1[4:0]} + : dp_rs1_aft_wbbr[31:0]; +assign dp_rs2_aft_imm[31:0] = decd_dp_imm_vld ? decd_dp_imm[31:0] + : dp_rs2_aft_wbbr[31:0]; + +assign dp_id_fin_rs1[31:0] = dp_rs1_fwd_ex2_lsu & ~dp_rs1_fwd_ex1 + & ~decd_dp_csri_vld & ~cp0_idu_sp_use_scratch + ? lsu_idu_ex2_fwd_data[31:0] + : dp_rs1_aft_imm[31:0]; + +assign dp_id_fin_rs2[31:0] = dp_rs2_fwd_ex2_lsu & ~dp_rs2_fwd_ex1 + & ~decd_dp_imm_vld + ? lsu_idu_ex2_fwd_data[31:0] + : dp_rs2_aft_imm[31:0]; + +assign dp_id_fin_rs3[31:0] = dp_rs3_fwd_ex2_lsu & ~dp_rs3_fwd_ex1 + ? lsu_idu_ex2_fwd_data[31:0] + : dp_rs3_aft_fwd_no_lsu[31:0]; + +assign dp_id_fin_rs4[31:0] = dp_rs4_fwd_ex2_lsu & ~dp_rs4_fwd_ex1 + ? lsu_idu_ex2_fwd_data[31:0] + : dp_rs4_aft_fwd_no_lsu[31:0]; + +// d. store data update when lsu ex stall and ex2 fwd hit +assign dp_rs1_stall_upd_lsu = dp_ex1_src0_reg[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & dp_ex1_src0_reg[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld; +assign dp_rs1_stall_upd = dp_rs1_stall_upd_lsu & ctrl_dp_ex1_bju_sel;// | dp_rs1_stall_upd_rbus; +assign dp_rs2_stall_upd_lsu = dp_ex1_src1_reg[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & dp_ex1_src1_reg[5:0] != 6'b0 + & (ctrl_dp_ex1_bju_sel | ctrl_dp_ex1_st_sel & ~dp_ex1_ex_st_rs2_vld) + & lsu_idu_ex2_fwd_vld; +assign dp_rs3_stall_upd = dp_ex1_src2_reg[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & dp_ex1_src2_reg[5:0] != 6'b0 + & (ctrl_dp_ex1_st_sel & dp_ex1_ex_st_rs2_vld) + & lsu_idu_ex2_fwd_vld; +assign dp_rs2_stall_upd = dp_rs2_stall_upd_lsu;// | dp_rs2_stall_upd_rbus; +assign dp_rs_upd_data[31:0] = lsu_idu_ex2_fwd_data[31:0]; + +// when fwd not vld rbus stall +// //&Force("bus", "decd_dp_unit_sel", 5, 0); @425 +assign dp_rs1_dep_ex1_pair = decd_dp_rs1_idx[5:0] == {ctrl_dp_ex1_dst_preg[5:1], 1'b1} & ctrl_dp_ex1_inst_vld + & dp_ex1_rd_pair & (decd_dp_rs1_vld | fdecd_dp_rs1_int_vld); +assign dp_rs2_dep_ex1_pair = decd_dp_rs2_idx[5:0] == {ctrl_dp_ex1_dst_preg[5:1], 1'b1} & ctrl_dp_ex1_inst_vld + & dp_ex1_rd_pair & decd_dp_rs2_vld; +assign dp_rs3_dep_ex1_pair = decd_dp_rs3_idx[5:0] == {ctrl_dp_ex1_dst_preg[5:1], 1'b1} & ctrl_dp_ex1_inst_vld + & dp_ex1_rd_pair & decd_dp_rs3_vld; +assign dp_rs4_dep_ex1_pair = decd_dp_rs4_idx[5:0] == {ctrl_dp_ex1_dst_preg[5:1], 1'b1} & ctrl_dp_ex1_inst_vld + & dp_ex1_rd_pair & decd_dp_rs4_vld; + +assign dp_rs1_dep_ex2_rbus0 = decd_dp_rs1_vld & iu_idu_ex2_inst_vld & decd_dp_rs1_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0]; +assign dp_rs1_dep_ex2_rbus1 = decd_dp_rs1_vld & iu_idu_ex2_inst_vld & decd_dp_rs1_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] & iu_idu_ex2_rd_pair; +assign dp_rs2_dep_ex2_rbus0 = decd_dp_rs2_vld & iu_idu_ex2_inst_vld & decd_dp_rs2_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0]; +assign dp_rs2_dep_ex2_rbus1 = decd_dp_rs2_vld & iu_idu_ex2_inst_vld & decd_dp_rs2_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] & iu_idu_ex2_rd_pair; +assign dp_rs3_dep_ex2_rbus0 = decd_dp_rs3_vld & iu_idu_ex2_inst_vld & decd_dp_rs3_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0]; +assign dp_rs3_dep_ex2_rbus1 = decd_dp_rs3_vld & iu_idu_ex2_inst_vld & decd_dp_rs3_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] & iu_idu_ex2_rd_pair; +assign dp_rs4_dep_ex2_rbus0 = decd_dp_rs4_vld & iu_idu_ex2_inst_vld & decd_dp_rs4_idx[5:0] == iu_idu_ex2_fwd_preg0[5:0]; +assign dp_rs4_dep_ex2_rbus1 = decd_dp_rs4_vld & iu_idu_ex2_inst_vld & decd_dp_rs4_idx[5:0] == iu_idu_ex2_fwd_preg1[5:0] & iu_idu_ex2_rd_pair; +assign dp_ex1_abnormal_sel = ctrl_dp_ex1_lsu_sel | ctrl_dp_ex1_div_sel; +assign dp_rs1_rbus_stall = ctrl_dp_ex1_inst_vld & !dp_ex1_abnormal_sel & dp_rs1_dep_ex1 ? !iu_idu_ex1_fwd_vld + : iu_idu_ex2_inst_vld & (dp_rs1_dep_ex2_rbus0 & !iu_idu_ex2_fwd_vld0 + | dp_rs1_dep_ex2_rbus1 & !iu_idu_ex2_fwd_vld1); +assign dp_rs2_rbus_stall = ctrl_dp_ex1_inst_vld & !dp_ex1_abnormal_sel & dp_rs2_dep_ex1 ? !iu_idu_ex1_fwd_vld + : iu_idu_ex2_inst_vld & (dp_rs2_dep_ex2_rbus0 & !iu_idu_ex2_fwd_vld0 + | dp_rs2_dep_ex2_rbus1 & !iu_idu_ex2_fwd_vld1); +assign dp_rs3_rbus_stall = ctrl_dp_ex1_inst_vld & !dp_ex1_abnormal_sel & dp_rs3_dep_ex1 ? !iu_idu_ex1_fwd_vld + : iu_idu_ex2_inst_vld & (dp_rs3_dep_ex2_rbus0 & !iu_idu_ex2_fwd_vld0 + | dp_rs3_dep_ex2_rbus1 & !iu_idu_ex2_fwd_vld1); +assign dp_rs4_rbus_stall = ctrl_dp_ex1_inst_vld & !dp_ex1_abnormal_sel & dp_rs4_dep_ex1 ? !iu_idu_ex1_fwd_vld + : iu_idu_ex2_inst_vld & (dp_rs4_dep_ex2_rbus0 & !iu_idu_ex2_fwd_vld0 + | dp_rs4_dep_ex2_rbus1 & !iu_idu_ex2_fwd_vld1); + +// x2 iu busy check +assign dp_x2_busy = iu_idu_ex2_inst_vld & iu_idu_ex2_fwd_preg0[5:0] == 6'h2; +assign dp_x2_busy2 = 1'b0; +assign dp_x2_waw_stall = hs_dp_sp_wb_pending & gpr_dp_id_x2_wr; + +//----------------------------------------------- +// 3. Pipeline Registers for Data Path +// a. Operation Function +// b. Operation Source +//----------------------------------------------- +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + begin + dp_ex1_func[FUNC_WIDTH-1:0] <= decd_dp_func[FUNC_WIDTH-1:0]; + dp_ex1_src0_reg[5:0] <= decd_dp_rs1_idx[5:0]; + dp_ex1_src1_reg[5:0] <= decd_dp_ex_st_rs2_vld ? decd_dp_rs3_idx[5:0] : fdecd_dp_rs2_vld ? fdecd_dp_rs2_idx[5:0] : ({6{decd_dp_rs2_vld}} + & decd_dp_rs2_idx[5:0]); + dp_ex1_src2_reg[5:0] <= decd_dp_rs3_idx[5:0]; + dp_ex1_split <= decd_dp_split; + dp_ex1_ipop_tail <= hs_dp_ipop_tail; + dp_ex1_mie_en <= hs_dp_mie_en; + dp_ex1_ipop_int_mask <= hs_dp_ipop_int_mask; + dp_ex1_ex_st_rs2_vld <= decd_dp_ex_st_rs2_vld; + end + else + begin + dp_ex1_func[FUNC_WIDTH-1:0] <= dp_ex1_func[FUNC_WIDTH-1:0]; + dp_ex1_src0_reg[5:0] <= dp_ex1_src0_reg[5:0]; + dp_ex1_src1_reg[5:0] <= dp_ex1_src1_reg[5:0]; + dp_ex1_src2_reg[5:0] <= dp_ex1_src2_reg[5:0]; + dp_ex1_split <= dp_ex1_split; + dp_ex1_mie_en <= dp_ex1_mie_en; + dp_ex1_ipop_int_mask <= dp_ex1_ipop_int_mask; + dp_ex1_ex_st_rs2_vld <= dp_ex1_ex_st_rs2_vld; + end +end + +always @ (posedge dp_rs1_cpuclk) +begin + if(ctrl_dp_pipe_down & decd_dp_rs1_vld | ifu_idu_warm_up) + dp_ex1_src0[31:0] <= dp_id_fin_rs1[31:0]; + else if(dp_rs1_stall_upd & ctrl_dp_ex1_rs1_dep) + dp_ex1_src0[31:0] <= dp_rs_upd_data[31:0]; + else if(lsu_idu_update_en) + dp_ex1_src0[31:0] <= lsu_idu_update_addr[31:0]; +end + +always @ (posedge dp_rs2_cpuclk) +begin + if(ctrl_dp_pipe_down & (decd_dp_rs2_vld | decd_dp_imm_vld) | ifu_idu_warm_up) + //if(ctrl_dp_pipe_down | ifu_idu_warm_up) + dp_ex1_src1[31:0] <= dp_id_fin_rs2[31:0]; + else if(dp_rs2_stall_upd & ctrl_dp_ex1_rs2_dep) + dp_ex1_src1[31:0] <= dp_rs_upd_data[31:0]; + else if(lsu_idu_ex1_src1_update_en) + dp_ex1_src1[31:0] <= iu_idu_ex1_src1_update_value[31:0]; + else + dp_ex1_src1[31:0] <= dp_ex1_src1[31:0]; +end + +always @ (posedge dp_rs3_cpuclk) +begin + //if(ctrl_dp_pipe_down | ifu_idu_warm_up) + if(ctrl_dp_pipe_down & decd_dp_rs3_vld | ifu_idu_warm_up) + dp_ex1_src2[31:0] <= dp_id_fin_rs3[31:0]; + else if(dp_rs3_stall_upd & ctrl_dp_ex1_rs2_dep) + dp_ex1_src2[31:0] <= dp_rs_upd_data[31:0]; + else + dp_ex1_src2[31:0] <= dp_ex1_src2[31:0]; +end + +always @ (posedge dp_cpuclk) +begin + //if(ctrl_dp_pipe_down | ifu_idu_warm_up) + if(ctrl_dp_pipe_down & decd_dp_rs4_vld | ifu_idu_warm_up) + dp_ex1_src3[31:0] <= dp_id_fin_rs4[31:0]; + else + dp_ex1_src3[31:0] <= dp_ex1_src3[31:0]; +end + +always @ (posedge dp_imm_cpuclk) +begin + if(ctrl_dp_pipe_down & decd_dp_ag_imm_vld | ifu_idu_warm_up) + begin + dp_ex1_ag_imm[31:0] <= decd_dp_ag_imm[31:0]; + end + else if(lsu_idu_update_en) + begin + dp_ex1_ag_imm[31:0] <= lsu_idu_update_offset[31:0]; + end + else + begin + dp_ex1_ag_imm[31:0] <= dp_ex1_ag_imm[31:0]; + end +end + +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + dp_ex1_mul_high_sel <= decd_dp_mul_high_sel; + else + dp_ex1_mul_high_sel <= dp_ex1_mul_high_sel; +end + +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + dp_ex1_smal_vld <= decd_dp_smal_vld; + else + dp_ex1_smal_vld <= dp_ex1_smal_vld; +end + +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + dp_ex1_rd_pair <= decd_dp_rd2_vld; + else + dp_ex1_rd_pair <= dp_ex1_rd_pair; +end + +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + begin + dp_ex1_src2_sel <= decd_dp_rs3_vld & decd_dp_lsu_sel; + end + else + begin + dp_ex1_src2_sel <= dp_ex1_src2_sel; + end +end + +always @ (posedge dp_imm_cpuclk) +begin + if(ctrl_dp_pipe_down & decd_dp_lsu_sel | ifu_idu_warm_up) + begin + dp_ex1_offset_sel <= ~decd_dp_func[9]; + end + else if(lsu_idu_update_en) + begin + dp_ex1_offset_sel <= 1'b1; + end + else + begin + dp_ex1_offset_sel <= dp_ex1_offset_sel; + end +end + +always @ (posedge dp_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + dp_ex1_ipush_spec_fail <= 1'b0; + end + else if(ctrl_dp_pipe_down) + begin + dp_ex1_ipush_spec_fail <= hs_dp_ipush_spec_fail; + end + else + begin + dp_ex1_ipush_spec_fail <= dp_ex1_ipush_spec_fail; + end +end + +always @ (posedge dp_cpuclk) +begin + if(ctrl_dp_pipe_down | ifu_idu_warm_up) + begin + dp_ex1_rs2_mepc <= hs_dp_rs2_mepc & hd_dp_rs2_sel; + dp_ex1_rs2_mcause <= hs_dp_rs2_mcause & hd_dp_rs2_sel; + end + else + begin + dp_ex1_rs2_mepc <= dp_ex1_rs2_mepc; + dp_ex1_rs2_mcause <= dp_ex1_rs2_mcause; + end +end +assign dp_ex1_st_int_wdata[31:0] = dp_ex1_rs2_mepc ? cp0_idu_mepc[31:0] : dp_ex1_rs2_mcause ? cp0_idu_mcause[31:0] + : dp_ex1_src2_sel ? dp_ex1_src2[31:0] : dp_ex1_src1[31:0]; + +//----------------------------------------------- +// 4. Rename for Output +//----------------------------------------------- +// Output to Ctrl +assign dp_ctrl_rs_norm_stall = dp_rs1_rbus_stall | dp_rs1_dep_ex1_pair + | dp_rs2_rbus_stall | dp_rs2_dep_ex1_pair + | dp_rs3_rbus_stall | dp_rs3_dep_ex1_pair + | dp_rs4_rbus_stall | dp_rs4_dep_ex1_pair + | dp_x2_waw_stall; +//assign dp_ctrl_oper_dep_ex1_dst = dp_rs2_dep_ex1 +// | dp_rd_dep_ex1; +//assign dp_ctrl_oper_dep_ex2_ld = dp_rs2_dep_ex2_ld +// | dp_rd_dep_ex2_ld; +//assign dp_ctrl_oper_dep_ex2_div = dp_rs1_dep_ex2_div | dp_rs2_dep_ex2_div +// | dp_rd_dep_ex2_div; +//assign dp_ctrl_rd_dep_ex2_iu = dp_rd_dep_ex2_iu; +//assign dp_ctrl_rs_dep_wb_iu = dp_rs1_dep_wb_iu | dp_rs2_dep_wb_iu; +//assign dp_ctrl_rd_dep_wb_iu = dp_rd_dep_wb_iu; +assign dp_ctrl_rs1_dep_ex1_dst = dp_rs1_dep_ex1; +//assign dp_ctrl_rs1_dep_ex2_ld = dp_rs1_dep_ex2_ld; +assign dp_ctrl_rs2_dep_ex1_dst = dp_rs2_dep_ex1; +assign dp_ctrl_rs3_dep_ex1_dst = dp_rs3_dep_ex1; +//assign dp_ctrl_rs2_dep_ex2_ld = dp_rs2_dep_ex2_ld; +//assign dp_ctrl_rs_dep_ex1 = dp_rs1_dep_ex1 | dp_rs2_dep_ex1 | dp_rs3_dep_ex1; +//assign dp_ctrl_rd_dep_ex1 = dp_rd_dep_ex1; +// assign dp_ctrl_stall_upd = dp_rs1_stall_upd | dp_rs2_stall_upd; +assign dp_ctrl_rs1_fwd_lsu = dp_rs1_fwd_ex2_lsu; +assign dp_ctrl_rs2_fwd_lsu = dp_rs2_fwd_ex2_lsu; +assign dp_ctrl_rs3_fwd_lsu = dp_rs3_fwd_ex2_lsu; +//assign dp_gpr_rs1_fwd = dp_rs1_fwd_ex1 | dp_rs1_fwd_ex2_rbus | dp_rs1_fwd_ex3_rbus; +//assign dp_gpr_rs2_fwd = dp_rs2_fwd_ex1 | dp_rs2_fwd_ex2_rbus | dp_rs2_fwd_ex3_rbus; +//assign dp_gpr_rs3_fwd = dp_rs3_fwd_ex1 | dp_rs3_fwd_ex2_rbus | dp_rs3_fwd_ex3_rbus; +//assign dp_gpr_rs4_fwd = dp_rs4_fwd_ex1 | dp_rs4_fwd_ex2_rbus | dp_rs4_fwd_ex3_rbus; +assign dp_gpr_rs1_fwd_lsu = dp_rs1_fwd_ex2_lsu; +assign dp_gpr_rs2_fwd_lsu = dp_rs2_fwd_ex2_lsu; +assign dp_gpr_rs3_fwd_lsu = dp_rs3_fwd_ex2_lsu; +assign dp_gpr_rs4_fwd_lsu = dp_rs4_fwd_ex2_lsu; +assign dp_gpr_rs1_fwd_div = dp_rs1_fwd_ex2_rbus & iu_idu_ex2_div_vld | dp_rs1_fwd_ex1 & ctrl_dp_ex1_div_sel; +assign dp_gpr_rs2_fwd_div = dp_rs2_fwd_ex2_rbus & iu_idu_ex2_div_vld | dp_rs2_fwd_ex1 & ctrl_dp_ex1_div_sel; +assign dp_gpr_rs3_fwd_div = dp_rs3_fwd_ex2_rbus & iu_idu_ex2_div_vld | dp_rs3_fwd_ex1 & ctrl_dp_ex1_div_sel; +assign dp_gpr_rs4_fwd_div = dp_rs4_fwd_ex2_rbus & iu_idu_ex2_div_vld | dp_rs4_fwd_ex1 & ctrl_dp_ex1_div_sel; +assign dp_gpr_x2_busy = dp_x2_busy; +assign dp_gpr_x2_busy2 = dp_x2_busy2; +assign dp_ctrl_rs1_stall_upd = dp_rs1_stall_upd; +assign dp_ctrl_rs2_stall_upd = dp_rs2_stall_upd; +assign dp_ctrl_rs3_stall_upd = dp_rs3_stall_upd; +assign dp_ctrl_ex1_ex_st_rs2_vld = dp_ex1_ex_st_rs2_vld; +assign dp_ctrl_ex1_st_vld = dp_ex1_func[0]; + +assign dp_decd_rs2_aft_fwd[31:0] = dp_rs2_aft_fwd_no_lsu[31:0]; + +// Output to IU +assign idu_iu_ex1_func[FUNC_WIDTH-1:0] = dp_ex1_func[FUNC_WIDTH-1:0]; +assign idu_iu_ex1_src0[31:0] = dp_ex1_src0[31:0]; +assign idu_iu_ex1_src1[31:0] = dp_ex1_src1[31:0]; +assign idu_iu_ex1_src2[31:0] = dp_ex1_src2[31:0]; +assign idu_iu_ex1_rd_pair = 1'b0; +assign idu_iu_ex1_ag_imm[31:0] = dp_ex1_ag_imm[31:0]; +assign idu_iu_ex1_split = dp_ex1_split; +assign idu_iu_ex1_src0_reg[5:0] = dp_ex1_src0_reg[5:0]; +assign idu_iu_ex1_src1_reg[5:0] = dp_ex1_src1_reg[5:0]; +assign idu_iu_ex1_mul_high_sel = dp_ex1_mul_high_sel; + +assign idu_fpu_ex1_srci[31:0] = dp_ex1_src0[31:0]; +assign dp_id_fp_ex1_rs2_idx[4:0] = dp_ex1_src1_reg[4:0]; + +// Output to CP0 +assign idu_cp0_ex1_func[FUNC_WIDTH-1:0] = dp_ex1_func[FUNC_WIDTH-1:0]; +assign idu_cp0_ex1_rs1[31:0] = dp_ex1_src0[31:0]; +assign idu_cp0_ex1_rs2[11:0] = dp_ex1_src1[11:0]; +assign idu_cp0_ex1_opcode[31:0] = dp_ex1_ag_imm[31:0]; +assign idu_cp0_ex1_ipush_spec_fail = dp_ex1_ipush_spec_fail; +assign idu_cp0_ex1_split_inst = dp_ex1_split; + +// Output to LSU +// Todo +assign idu_lsu_ex1_func[3:0] = dp_ex1_func[3:0]; +assign idu_lsu_ex1_size[1:0] = dp_ex1_func[6:5]; +assign idu_lsu_ex1_src0_reg[5:0] = dp_ex1_src0_reg[5:0]; +assign idu_lsu_ex1_src1_reg[5:0] = dp_ex1_src1_reg[5:0]; +assign idu_lsu_ex1_sign_extend = dp_ex1_func[7]; +assign idu_lsu_ex1_base[31:0] = dp_ex1_src0[31:0]; +assign idu_lsu_ex1_ag_imm[31:0] = dp_ex1_ag_imm[31:0]; +assign idu_lsu_ex1_base_wb = dp_ex1_func[8]; +assign idu_lsu_ex1_offset_sel = dp_ex1_offset_sel; +assign idu_lsu_ex1_split = dp_ex1_split; +assign idu_lsu_ex1_ipop_int_mask = dp_ex1_ipop_int_mask; + +assign idu_lsu_ex1_data[31:0] = ctrl_dp_ex1_fls ? id_fp_dp_srcf1[31:0] + : dp_ex1_st_int_wdata[31:0]; +// assign idu_lsu_ex1_opcode[31:0] = dp_ex1_ag_imm[31:0]; + +// Output to IFU +assign idu_ifu_tail_vld = ctrl_dp_ex1_inst_vld & dp_ex1_ipop_tail | hs_dp_ipop_tail; +assign idu_ifu_tail_vld_gate = ctrl_dp_ex1_inst_vld & dp_ex1_ipop_tail | hs_dp_ipop_tail_gate; + +// Output to RTU +assign idu_iu_ex1_ipush_spec_fail = dp_ex1_ipush_spec_fail; +assign idu_iu_ex1_tail_int_vld = dp_ex1_ipop_tail; +assign idu_iu_ex1_ipush_mie_en = dp_ex1_mie_en; +assign idu_iu_ex1_ipop_int_mask = dp_ex1_ipop_int_mask; + +// &ModuleEnd; @981 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_fpr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_fpr.v new file mode 100644 index 0000000000000000000000000000000000000000..0eb7368130ae47eb2d0b353d92b0f56f4311813c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_fpr.v @@ -0,0 +1,1539 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_fpr( + cp0_idu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_fpr_ex1_int_spec, + decd_fp_fpr_rd, + decd_fp_fpr_rd_vld, + decd_fp_fpr_rs1, + decd_fp_fpr_rs1_vld, + decd_fp_fpr_rs2, + decd_fp_fpr_rs2_vld, + decd_fp_fpr_rs3, + decd_fp_fpr_rs3_vld, + forever_cpuclk, + fpr_id_fp_rd_busy, + fpr_id_fp_rd_busy_lsu, + fpr_id_fp_rs1, + fpr_id_fp_rs1_busy, + fpr_id_fp_rs1_busy_lsu, + fpr_id_fp_rs2, + fpr_id_fp_rs2_busy, + fpr_id_fp_rs2_busy_lsu, + fpr_id_fp_rs3, + fpr_id_fp_rs3_busy, + fpr_id_fp_rs3_busy_lsu, + fpr_top_reg_busy, + fpr_top_reg_busy_div, + fpr_top_reg_busy_lsu, + id_fp_fpr_dst_freg, + id_fp_fpr_id_dst_vld, + id_fp_fpr_ld_inst, + id_fp_fpr_wr_issue, + ifu_idu_warm_up, + pad_yy_icg_scan_en, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_fgpr_wb_data, + rtu_idu_fgpr_wb_flsu_vld, + rtu_idu_fgpr_wb_reg, + rtu_idu_fgpr_wb_vld, + rtu_idu_flush_fe, + rtu_yy_xx_expt_int +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_fpr_ex1_int_spec; +input [4 :0] decd_fp_fpr_rd; +input decd_fp_fpr_rd_vld; +input [4 :0] decd_fp_fpr_rs1; +input decd_fp_fpr_rs1_vld; +input [4 :0] decd_fp_fpr_rs2; +input decd_fp_fpr_rs2_vld; +input [4 :0] decd_fp_fpr_rs3; +input decd_fp_fpr_rs3_vld; +input forever_cpuclk; +input [4 :0] id_fp_fpr_dst_freg; +input id_fp_fpr_id_dst_vld; +input id_fp_fpr_ld_inst; +input id_fp_fpr_wr_issue; +input ifu_idu_warm_up; +input pad_yy_icg_scan_en; +input rtu_idu_ex1_int_dis_stall_req; +input [31:0] rtu_idu_fgpr_wb_data; +input rtu_idu_fgpr_wb_flsu_vld; +input [4 :0] rtu_idu_fgpr_wb_reg; +input rtu_idu_fgpr_wb_vld; +input rtu_idu_flush_fe; +input rtu_yy_xx_expt_int; +output fpr_id_fp_rd_busy; +output fpr_id_fp_rd_busy_lsu; +output [31:0] fpr_id_fp_rs1; +output fpr_id_fp_rs1_busy; +output fpr_id_fp_rs1_busy_lsu; +output [31:0] fpr_id_fp_rs2; +output fpr_id_fp_rs2_busy; +output fpr_id_fp_rs2_busy_lsu; +output [31:0] fpr_id_fp_rs3; +output fpr_id_fp_rs3_busy; +output fpr_id_fp_rs3_busy_lsu; +output [31:0] fpr_top_reg_busy; +output [31:0] fpr_top_reg_busy_div; +output [31:0] fpr_top_reg_busy_lsu; + +// &Regs; @25 +reg [31:0] fpr_read_data1; +reg [31:0] fpr_read_data2; +reg [31:0] fpr_read_data3; +reg [31:0] int_clr_sel; +reg [31:0] reg_issue; +reg [31:0] reg_sel; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_fpr_ex1_int_spec; +wire ctrl_gpr_ld_inst; +wire [4 :0] decd_fp_fpr_rd; +wire decd_fp_fpr_rd_vld; +wire [4 :0] decd_fp_fpr_rs1; +wire decd_fp_fpr_rs1_vld; +wire [4 :0] decd_fp_fpr_rs2; +wire decd_fp_fpr_rs2_vld; +wire [4 :0] decd_fp_fpr_rs3; +wire decd_fp_fpr_rs3_vld; +wire forever_cpuclk; +wire [31:0] fpr_busy_div1; +wire [31:0] fpr_busy_div2; +wire [31:0] fpr_busy_div3; +wire [31:0] fpr_busy_divd; +wire [31:0] fpr_busy_lsu1; +wire [31:0] fpr_busy_lsu2; +wire [31:0] fpr_busy_lsu3; +wire [31:0] fpr_busy_lsud; +wire [31:0] fpr_busy_rslt1; +wire [31:0] fpr_busy_rslt2; +wire [31:0] fpr_busy_rslt3; +wire [31:0] fpr_busy_rsltd; +wire fpr_clk_en; +wire [31:0] fpr_fin_data1; +wire [31:0] fpr_fin_data2; +wire [31:0] fpr_fin_data3; +wire fpr_id_fp_rd_busy; +wire fpr_id_fp_rd_busy_div; +wire fpr_id_fp_rd_busy_lsu; +wire [31:0] fpr_id_fp_rs1; +wire fpr_id_fp_rs1_busy; +wire fpr_id_fp_rs1_busy_div; +wire fpr_id_fp_rs1_busy_lsu; +wire [31:0] fpr_id_fp_rs2; +wire fpr_id_fp_rs2_busy; +wire fpr_id_fp_rs2_busy_div; +wire fpr_id_fp_rs2_busy_lsu; +wire [31:0] fpr_id_fp_rs3; +wire fpr_id_fp_rs3_busy; +wire fpr_id_fp_rs3_busy_div; +wire fpr_id_fp_rs3_busy_lsu; +wire fpr_rs1_dep_wb; +wire fpr_rs2_dep_wb; +wire fpr_rs3_dep_wb; +wire fpr_sync_rst_b; +wire [31:0] fpr_top_reg_busy; +wire [31:0] fpr_top_reg_busy_div; +wire [31:0] fpr_top_reg_busy_lsu; +wire [4 :0] id_fp_fpr_dst_freg; +wire id_fp_fpr_id_dst_vld; +wire id_fp_fpr_ld_inst; +wire id_fp_fpr_wr_issue; +wire ifu_idu_warm_up; +wire [33:0] int_clr_en; +wire [4 :0] int_clr_idx; +wire pad_yy_icg_scan_en; +wire [31:0] reg_0_dout; +wire [31:0] reg_10_dout; +wire [31:0] reg_11_dout; +wire [31:0] reg_12_dout; +wire [31:0] reg_13_dout; +wire [31:0] reg_14_dout; +wire [31:0] reg_15_dout; +wire [31:0] reg_16_dout; +wire [31:0] reg_17_dout; +wire [31:0] reg_18_dout; +wire [31:0] reg_19_dout; +wire [31:0] reg_1_dout; +wire [31:0] reg_20_dout; +wire [31:0] reg_21_dout; +wire [31:0] reg_22_dout; +wire [31:0] reg_23_dout; +wire [31:0] reg_24_dout; +wire [31:0] reg_25_dout; +wire [31:0] reg_26_dout; +wire [31:0] reg_27_dout; +wire [31:0] reg_28_dout; +wire [31:0] reg_29_dout; +wire [31:0] reg_2_dout; +wire [31:0] reg_30_dout; +wire [31:0] reg_31_dout; +wire [31:0] reg_3_dout; +wire [31:0] reg_4_dout; +wire [31:0] reg_5_dout; +wire [31:0] reg_6_dout; +wire [31:0] reg_7_dout; +wire [31:0] reg_8_dout; +wire [31:0] reg_9_dout; +wire [31:0] reg_busy; +wire [31:0] reg_busy_div; +wire [31:0] reg_busy_lsu; +wire reg_in_cpuclk; +wire reg_sm_clk_en; +wire reg_sm_cpuclk; +wire [31:0] reg_write_en; +wire [31:0] reg_write_is; +wire reg_write_is_gate; +wire rtu_idu_ex1_int_dis_stall_req; +wire [31:0] rtu_idu_fgpr_wb_data; +wire rtu_idu_fgpr_wb_flsu_vld; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire rtu_idu_flush_fe; +wire rtu_yy_xx_expt_int; +wire [31:0] write_data; +wire [4 :0] write_index; + + +//========================================================== +// Integated Clock Gating Cell +//========================================================== +assign fpr_clk_en = rtu_idu_fgpr_wb_vld | ifu_idu_warm_up; +// &Instance("gated_clk_cell", "x_fpr_gated_clk"); @32 +gated_clk_cell x_fpr_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_in_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fpr_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @33 +// .external_en (1'b0), @34 +// .global_en (cp0_yy_clk_en), @35 +// .module_en ( cp0_idu_icg_en ) , @36 +// .local_en (fpr_clk_en), @37 +// .clk_out (reg_in_cpuclk)); @38 + +assign reg_sm_clk_en = reg_write_is_gate | rtu_idu_fgpr_wb_vld | rtu_idu_flush_fe | rtu_yy_xx_expt_int & ctrl_fpr_ex1_int_spec; +// &Instance("gated_clk_cell", "x_reg_sm_gated_clk"); @41 +gated_clk_cell x_reg_sm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_sm_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_sm_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @42 +// .external_en (1'b0), @43 +// .global_en (cp0_yy_clk_en), @44 +// .module_en ( cp0_idu_icg_en ) , @45 +// .local_en (reg_sm_clk_en), @46 +// .clk_out (reg_sm_cpuclk)); @47 + +parameter REG_WIDTH =`FLEN; +//========================================================= +// GRP Module +// 1. Instance all FPR modules +// 2. One write port +// 3. Three read ports +//========================================================= + +//----------------------------------------------- +// 1. Instance all FPR modules +//----------------------------------------------- +// &ConnRule(s/_x$/[0]/); @60 +// &Instance("pa_idu_reg", "x_pa_idu_freg_0"); @61 +pa_idu_reg x_pa_idu_freg_0 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[0] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[0] ), + .reg_busy_lsu_x (reg_busy_lsu[0] ), + .reg_busy_x (reg_busy[0] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[0] ), + .reg_write_is_x (reg_write_is[0] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_0_dout ) +); + +// &Connect(.x_reg_dout (reg_0_dout)); @62 + +// &ConnRule(s/_x$/[1]/); @64 +// &Instance("pa_idu_reg", "x_pa_idu_freg_1"); @65 +pa_idu_reg x_pa_idu_freg_1 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[1] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[1] ), + .reg_busy_lsu_x (reg_busy_lsu[1] ), + .reg_busy_x (reg_busy[1] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[1] ), + .reg_write_is_x (reg_write_is[1] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_1_dout ) +); + +// &Connect(.x_reg_dout (reg_1_dout)); @66 + +// &ConnRule(s/_x$/[2]/); @68 +// &Instance("pa_idu_reg", "x_pa_idu_freg_2"); @69 +pa_idu_reg x_pa_idu_freg_2 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[2] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[2] ), + .reg_busy_lsu_x (reg_busy_lsu[2] ), + .reg_busy_x (reg_busy[2] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[2] ), + .reg_write_is_x (reg_write_is[2] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_2_dout ) +); + +// &Connect(.x_reg_dout (reg_2_dout)); @70 + +// &ConnRule(s/_x$/[3]/); @72 +// &Instance("pa_idu_reg", "x_pa_idu_freg_3"); @73 +pa_idu_reg x_pa_idu_freg_3 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[3] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[3] ), + .reg_busy_lsu_x (reg_busy_lsu[3] ), + .reg_busy_x (reg_busy[3] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[3] ), + .reg_write_is_x (reg_write_is[3] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_3_dout ) +); + +// &Connect(.x_reg_dout (reg_3_dout)); @74 + +// &ConnRule(s/_x$/[4]/); @76 +// &Instance("pa_idu_reg", "x_pa_idu_freg_4"); @77 +pa_idu_reg x_pa_idu_freg_4 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[4] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[4] ), + .reg_busy_lsu_x (reg_busy_lsu[4] ), + .reg_busy_x (reg_busy[4] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[4] ), + .reg_write_is_x (reg_write_is[4] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_4_dout ) +); + +// &Connect(.x_reg_dout (reg_4_dout)); @78 + +// &ConnRule(s/_x$/[5]/); @80 +// &Instance("pa_idu_reg", "x_pa_idu_freg_5"); @81 +pa_idu_reg x_pa_idu_freg_5 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[5] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[5] ), + .reg_busy_lsu_x (reg_busy_lsu[5] ), + .reg_busy_x (reg_busy[5] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[5] ), + .reg_write_is_x (reg_write_is[5] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_5_dout ) +); + +// &Connect(.x_reg_dout (reg_5_dout)); @82 + +// &ConnRule(s/_x$/[6]/); @84 +// &Instance("pa_idu_reg", "x_pa_idu_freg_6"); @85 +pa_idu_reg x_pa_idu_freg_6 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[6] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[6] ), + .reg_busy_lsu_x (reg_busy_lsu[6] ), + .reg_busy_x (reg_busy[6] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[6] ), + .reg_write_is_x (reg_write_is[6] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_6_dout ) +); + +// &Connect(.x_reg_dout (reg_6_dout)); @86 + +// &ConnRule(s/_x$/[7]/); @88 +// &Instance("pa_idu_reg", "x_pa_idu_freg_7"); @89 +pa_idu_reg x_pa_idu_freg_7 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[7] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[7] ), + .reg_busy_lsu_x (reg_busy_lsu[7] ), + .reg_busy_x (reg_busy[7] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[7] ), + .reg_write_is_x (reg_write_is[7] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_7_dout ) +); + +// &Connect(.x_reg_dout (reg_7_dout)); @90 + +// &ConnRule(s/_x$/[8]/); @92 +// &Instance("pa_idu_reg", "x_pa_idu_freg_8"); @93 +pa_idu_reg x_pa_idu_freg_8 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[8] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[8] ), + .reg_busy_lsu_x (reg_busy_lsu[8] ), + .reg_busy_x (reg_busy[8] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[8] ), + .reg_write_is_x (reg_write_is[8] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_8_dout ) +); + +// &Connect(.x_reg_dout (reg_8_dout)); @94 + +// &ConnRule(s/_x$/[9]/); @96 +// &Instance("pa_idu_reg", "x_pa_idu_freg_9"); @97 +pa_idu_reg x_pa_idu_freg_9 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[9] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[9] ), + .reg_busy_lsu_x (reg_busy_lsu[9] ), + .reg_busy_x (reg_busy[9] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[9] ), + .reg_write_is_x (reg_write_is[9] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_9_dout ) +); + +// &Connect(.x_reg_dout (reg_9_dout)); @98 + +// &ConnRule(s/_x$/[10]/); @100 +// &Instance("pa_idu_reg", "x_pa_idu_freg_10"); @101 +pa_idu_reg x_pa_idu_freg_10 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[10] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[10] ), + .reg_busy_lsu_x (reg_busy_lsu[10] ), + .reg_busy_x (reg_busy[10] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[10] ), + .reg_write_is_x (reg_write_is[10] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_10_dout ) +); + +// &Connect(.x_reg_dout (reg_10_dout)); @102 + +// &ConnRule(s/_x$/[11]/); @104 +// &Instance("pa_idu_reg", "x_pa_idu_freg_11"); @105 +pa_idu_reg x_pa_idu_freg_11 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[11] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[11] ), + .reg_busy_lsu_x (reg_busy_lsu[11] ), + .reg_busy_x (reg_busy[11] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[11] ), + .reg_write_is_x (reg_write_is[11] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_11_dout ) +); + +// &Connect(.x_reg_dout (reg_11_dout)); @106 + +// &ConnRule(s/_x$/[12]/); @108 +// &Instance("pa_idu_reg", "x_pa_idu_freg_12"); @109 +pa_idu_reg x_pa_idu_freg_12 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[12] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[12] ), + .reg_busy_lsu_x (reg_busy_lsu[12] ), + .reg_busy_x (reg_busy[12] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[12] ), + .reg_write_is_x (reg_write_is[12] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_12_dout ) +); + +// &Connect(.x_reg_dout (reg_12_dout)); @110 + +// &ConnRule(s/_x$/[13]/); @112 +// &Instance("pa_idu_reg", "x_pa_idu_freg_13"); @113 +pa_idu_reg x_pa_idu_freg_13 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[13] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[13] ), + .reg_busy_lsu_x (reg_busy_lsu[13] ), + .reg_busy_x (reg_busy[13] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[13] ), + .reg_write_is_x (reg_write_is[13] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_13_dout ) +); + +// &Connect(.x_reg_dout (reg_13_dout)); @114 + +// &ConnRule(s/_x$/[14]/); @116 +// &Instance("pa_idu_reg", "x_pa_idu_freg_14"); @117 +pa_idu_reg x_pa_idu_freg_14 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[14] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[14] ), + .reg_busy_lsu_x (reg_busy_lsu[14] ), + .reg_busy_x (reg_busy[14] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[14] ), + .reg_write_is_x (reg_write_is[14] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_14_dout ) +); + +// &Connect(.x_reg_dout (reg_14_dout)); @118 + +// &ConnRule(s/_x$/[15]/); @120 +// &Instance("pa_idu_reg", "x_pa_idu_freg_15"); @121 +pa_idu_reg x_pa_idu_freg_15 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[15] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[15] ), + .reg_busy_lsu_x (reg_busy_lsu[15] ), + .reg_busy_x (reg_busy[15] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[15] ), + .reg_write_is_x (reg_write_is[15] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_15_dout ) +); + +// &Connect(.x_reg_dout (reg_15_dout)); @122 + +// &ConnRule(s/_x$/[16]/); @124 +// &Instance("pa_idu_reg", "x_pa_idu_freg_16"); @125 +pa_idu_reg x_pa_idu_freg_16 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[16] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[16] ), + .reg_busy_lsu_x (reg_busy_lsu[16] ), + .reg_busy_x (reg_busy[16] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[16] ), + .reg_write_is_x (reg_write_is[16] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_16_dout ) +); + +// &Connect(.x_reg_dout (reg_16_dout)); @126 + +// &ConnRule(s/_x$/[17]/); @128 +// &Instance("pa_idu_reg", "x_pa_idu_freg_17"); @129 +pa_idu_reg x_pa_idu_freg_17 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[17] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[17] ), + .reg_busy_lsu_x (reg_busy_lsu[17] ), + .reg_busy_x (reg_busy[17] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[17] ), + .reg_write_is_x (reg_write_is[17] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_17_dout ) +); + +// &Connect(.x_reg_dout (reg_17_dout)); @130 + +// &ConnRule(s/_x$/[18]/); @132 +// &Instance("pa_idu_reg", "x_pa_idu_freg_18"); @133 +pa_idu_reg x_pa_idu_freg_18 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[18] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[18] ), + .reg_busy_lsu_x (reg_busy_lsu[18] ), + .reg_busy_x (reg_busy[18] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[18] ), + .reg_write_is_x (reg_write_is[18] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_18_dout ) +); + +// &Connect(.x_reg_dout (reg_18_dout)); @134 + +// &ConnRule(s/_x$/[19]/); @136 +// &Instance("pa_idu_reg", "x_pa_idu_freg_19"); @137 +pa_idu_reg x_pa_idu_freg_19 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[19] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[19] ), + .reg_busy_lsu_x (reg_busy_lsu[19] ), + .reg_busy_x (reg_busy[19] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[19] ), + .reg_write_is_x (reg_write_is[19] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_19_dout ) +); + +// &Connect(.x_reg_dout (reg_19_dout)); @138 + +// &ConnRule(s/_x$/[20]/); @140 +// &Instance("pa_idu_reg", "x_pa_idu_freg_20"); @141 +pa_idu_reg x_pa_idu_freg_20 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[20] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[20] ), + .reg_busy_lsu_x (reg_busy_lsu[20] ), + .reg_busy_x (reg_busy[20] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[20] ), + .reg_write_is_x (reg_write_is[20] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_20_dout ) +); + +// &Connect(.x_reg_dout (reg_20_dout)); @142 + +// &ConnRule(s/_x$/[21]/); @144 +// &Instance("pa_idu_reg", "x_pa_idu_freg_21"); @145 +pa_idu_reg x_pa_idu_freg_21 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[21] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[21] ), + .reg_busy_lsu_x (reg_busy_lsu[21] ), + .reg_busy_x (reg_busy[21] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[21] ), + .reg_write_is_x (reg_write_is[21] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_21_dout ) +); + +// &Connect(.x_reg_dout (reg_21_dout)); @146 + +// &ConnRule(s/_x$/[22]/); @148 +// &Instance("pa_idu_reg", "x_pa_idu_freg_22"); @149 +pa_idu_reg x_pa_idu_freg_22 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[22] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[22] ), + .reg_busy_lsu_x (reg_busy_lsu[22] ), + .reg_busy_x (reg_busy[22] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[22] ), + .reg_write_is_x (reg_write_is[22] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_22_dout ) +); + +// &Connect(.x_reg_dout (reg_22_dout)); @150 + +// &ConnRule(s/_x$/[23]/); @152 +// &Instance("pa_idu_reg", "x_pa_idu_freg_23"); @153 +pa_idu_reg x_pa_idu_freg_23 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[23] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[23] ), + .reg_busy_lsu_x (reg_busy_lsu[23] ), + .reg_busy_x (reg_busy[23] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[23] ), + .reg_write_is_x (reg_write_is[23] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_23_dout ) +); + +// &Connect(.x_reg_dout (reg_23_dout)); @154 + +// &ConnRule(s/_x$/[24]/); @156 +// &Instance("pa_idu_reg", "x_pa_idu_freg_24"); @157 +pa_idu_reg x_pa_idu_freg_24 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[24] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[24] ), + .reg_busy_lsu_x (reg_busy_lsu[24] ), + .reg_busy_x (reg_busy[24] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[24] ), + .reg_write_is_x (reg_write_is[24] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_24_dout ) +); + +// &Connect(.x_reg_dout (reg_24_dout)); @158 + +// &ConnRule(s/_x$/[25]/); @160 +// &Instance("pa_idu_reg", "x_pa_idu_freg_25"); @161 +pa_idu_reg x_pa_idu_freg_25 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[25] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[25] ), + .reg_busy_lsu_x (reg_busy_lsu[25] ), + .reg_busy_x (reg_busy[25] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[25] ), + .reg_write_is_x (reg_write_is[25] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_25_dout ) +); + +// &Connect(.x_reg_dout (reg_25_dout)); @162 + +// &ConnRule(s/_x$/[26]/); @164 +// &Instance("pa_idu_reg", "x_pa_idu_freg_26"); @165 +pa_idu_reg x_pa_idu_freg_26 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[26] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[26] ), + .reg_busy_lsu_x (reg_busy_lsu[26] ), + .reg_busy_x (reg_busy[26] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[26] ), + .reg_write_is_x (reg_write_is[26] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_26_dout ) +); + +// &Connect(.x_reg_dout (reg_26_dout)); @166 + +// &ConnRule(s/_x$/[27]/); @168 +// &Instance("pa_idu_reg", "x_pa_idu_freg_27"); @169 +pa_idu_reg x_pa_idu_freg_27 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[27] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[27] ), + .reg_busy_lsu_x (reg_busy_lsu[27] ), + .reg_busy_x (reg_busy[27] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[27] ), + .reg_write_is_x (reg_write_is[27] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_27_dout ) +); + +// &Connect(.x_reg_dout (reg_27_dout)); @170 + +// &ConnRule(s/_x$/[28]/); @172 +// &Instance("pa_idu_reg", "x_pa_idu_freg_28"); @173 +pa_idu_reg x_pa_idu_freg_28 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[28] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[28] ), + .reg_busy_lsu_x (reg_busy_lsu[28] ), + .reg_busy_x (reg_busy[28] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[28] ), + .reg_write_is_x (reg_write_is[28] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_28_dout ) +); + +// &Connect(.x_reg_dout (reg_28_dout)); @174 + +// &ConnRule(s/_x$/[29]/); @176 +// &Instance("pa_idu_reg", "x_pa_idu_freg_29"); @177 +pa_idu_reg x_pa_idu_freg_29 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[29] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[29] ), + .reg_busy_lsu_x (reg_busy_lsu[29] ), + .reg_busy_x (reg_busy[29] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[29] ), + .reg_write_is_x (reg_write_is[29] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_29_dout ) +); + +// &Connect(.x_reg_dout (reg_29_dout)); @178 + +// &ConnRule(s/_x$/[30]/); @180 +// &Instance("pa_idu_reg", "x_pa_idu_freg_30"); @181 +pa_idu_reg x_pa_idu_freg_30 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[30] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[30] ), + .reg_busy_lsu_x (reg_busy_lsu[30] ), + .reg_busy_x (reg_busy[30] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[30] ), + .reg_write_is_x (reg_write_is[30] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_30_dout ) +); + +// &Connect(.x_reg_dout (reg_30_dout)); @182 + +// &ConnRule(s/_x$/[31]/); @184 +// &Instance("pa_idu_reg", "x_pa_idu_freg_31"); @185 +pa_idu_reg x_pa_idu_freg_31 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .int_clr_en_x (int_clr_en[31] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_div_x (reg_busy_div[31] ), + .reg_busy_lsu_x (reg_busy_lsu[31] ), + .reg_busy_x (reg_busy[31] ), + .reg_in_cpuclk (reg_in_cpuclk ), + .reg_sm_cpuclk (reg_sm_cpuclk ), + .reg_write_en_x (reg_write_en[31] ), + .reg_write_is_x (reg_write_is[31] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data (write_data ), + .x_reg_dout (reg_31_dout ) +); + +// &Connect(.x_reg_dout (reg_31_dout)); @186 + +//----------------------------------------------- +// 2. One write port +//----------------------------------------------- +assign fpr_sync_rst_b = 1'b1; +assign write_index[4:0] = rtu_idu_fgpr_wb_reg[4:0]; +assign write_data[REG_WIDTH-1:0] = {REG_WIDTH{fpr_sync_rst_b}} & rtu_idu_fgpr_wb_data[REG_WIDTH-1:0]; + +// write index decoder +// &CombBeg; @196 +always @( write_index[4:0]) +begin + reg_sel[REG_WIDTH-1:0] = {REG_WIDTH{1'b0}}; + case(write_index[4:0]) + 5'h00 : reg_sel[0] = 1'b1; + 5'h01 : reg_sel[1] = 1'b1; + 5'h02 : reg_sel[2] = 1'b1; + 5'h03 : reg_sel[3] = 1'b1; + 5'h04 : reg_sel[4] = 1'b1; + 5'h05 : reg_sel[5] = 1'b1; + 5'h06 : reg_sel[6] = 1'b1; + 5'h07 : reg_sel[7] = 1'b1; + 5'h08 : reg_sel[8] = 1'b1; + 5'h09 : reg_sel[9] = 1'b1; + 5'h0a : reg_sel[10] = 1'b1; + 5'h0b : reg_sel[11] = 1'b1; + 5'h0c : reg_sel[12] = 1'b1; + 5'h0d : reg_sel[13] = 1'b1; + 5'h0e : reg_sel[14] = 1'b1; + 5'h0f : reg_sel[15] = 1'b1; + 5'h10 : reg_sel[16] = 1'b1; + 5'h11 : reg_sel[17] = 1'b1; + 5'h12 : reg_sel[18] = 1'b1; + 5'h13 : reg_sel[19] = 1'b1; + 5'h14 : reg_sel[20] = 1'b1; + 5'h15 : reg_sel[21] = 1'b1; + 5'h16 : reg_sel[22] = 1'b1; + 5'h17 : reg_sel[23] = 1'b1; + 5'h18 : reg_sel[24] = 1'b1; + 5'h19 : reg_sel[25] = 1'b1; + 5'h1a : reg_sel[26] = 1'b1; + 5'h1b : reg_sel[27] = 1'b1; + 5'h1c : reg_sel[28] = 1'b1; + 5'h1d : reg_sel[29] = 1'b1; + 5'h1e : reg_sel[30] = 1'b1; + 5'h1f : reg_sel[31] = 1'b1; + endcase +// &CombEnd; @232 +end + +assign reg_write_en[REG_WIDTH-1:0] = reg_sel[REG_WIDTH-1:0] & {REG_WIDTH{rtu_idu_fgpr_wb_vld}} + & {REG_WIDTH{fpr_sync_rst_b}}; + +// Write Reg Issue +// write issue index decoder +// &CombBeg; @239 +always @( decd_fp_fpr_rd[4:0]) +begin + reg_issue[REG_WIDTH-1:0] = {REG_WIDTH{1'b0}}; + case(decd_fp_fpr_rd[4:0]) + 5'h00 : reg_issue[0] = 1'b1; + 5'h01 : reg_issue[1] = 1'b1; + 5'h02 : reg_issue[2] = 1'b1; + 5'h03 : reg_issue[3] = 1'b1; + 5'h04 : reg_issue[4] = 1'b1; + 5'h05 : reg_issue[5] = 1'b1; + 5'h06 : reg_issue[6] = 1'b1; + 5'h07 : reg_issue[7] = 1'b1; + 5'h08 : reg_issue[8] = 1'b1; + 5'h09 : reg_issue[9] = 1'b1; + 5'h0a : reg_issue[10] = 1'b1; + 5'h0b : reg_issue[11] = 1'b1; + 5'h0c : reg_issue[12] = 1'b1; + 5'h0d : reg_issue[13] = 1'b1; + 5'h0e : reg_issue[14] = 1'b1; + 5'h0f : reg_issue[15] = 1'b1; + 5'h10 : reg_issue[16] = 1'b1; + 5'h11 : reg_issue[17] = 1'b1; + 5'h12 : reg_issue[18] = 1'b1; + 5'h13 : reg_issue[19] = 1'b1; + 5'h14 : reg_issue[20] = 1'b1; + 5'h15 : reg_issue[21] = 1'b1; + 5'h16 : reg_issue[22] = 1'b1; + 5'h17 : reg_issue[23] = 1'b1; + 5'h18 : reg_issue[24] = 1'b1; + 5'h19 : reg_issue[25] = 1'b1; + 5'h1a : reg_issue[26] = 1'b1; + 5'h1b : reg_issue[27] = 1'b1; + 5'h1c : reg_issue[28] = 1'b1; + 5'h1d : reg_issue[29] = 1'b1; + 5'h1e : reg_issue[30] = 1'b1; + 5'h1f : reg_issue[31] = 1'b1; + endcase +// &CombEnd; @275 +end + +assign reg_write_is[REG_WIDTH-1:0] = {REG_WIDTH{id_fp_fpr_wr_issue}} & reg_issue[REG_WIDTH-1:0]; +assign reg_write_is_gate = id_fp_fpr_id_dst_vld; +assign ctrl_gpr_ld_inst = id_fp_fpr_ld_inst; + +assign int_clr_idx[4:0] = id_fp_fpr_dst_freg[4:0] & {5{rtu_yy_xx_expt_int & ctrl_fpr_ex1_int_spec}}; +// &CombBeg; @282 +always @( int_clr_idx[4:0]) +begin + int_clr_sel[31:0] = {32{1'b0}}; + case(int_clr_idx[4:0]) + 5'h00 : int_clr_sel[0] = 1'b1; + 5'h01 : int_clr_sel[1] = 1'b1; + 5'h02 : int_clr_sel[2] = 1'b1; + 5'h03 : int_clr_sel[3] = 1'b1; + 5'h04 : int_clr_sel[4] = 1'b1; + 5'h05 : int_clr_sel[5] = 1'b1; + 5'h06 : int_clr_sel[6] = 1'b1; + 5'h07 : int_clr_sel[7] = 1'b1; + 5'h08 : int_clr_sel[8] = 1'b1; + 5'h09 : int_clr_sel[9] = 1'b1; + 5'h0a : int_clr_sel[10] = 1'b1; + 5'h0b : int_clr_sel[11] = 1'b1; + 5'h0c : int_clr_sel[12] = 1'b1; + 5'h0d : int_clr_sel[13] = 1'b1; + 5'h0e : int_clr_sel[14] = 1'b1; + 5'h0f : int_clr_sel[15] = 1'b1; + 5'h10 : int_clr_sel[16] = 1'b1; + 5'h11 : int_clr_sel[17] = 1'b1; + 5'h12 : int_clr_sel[18] = 1'b1; + 5'h13 : int_clr_sel[19] = 1'b1; + 5'h14 : int_clr_sel[20] = 1'b1; + 5'h15 : int_clr_sel[21] = 1'b1; + 5'h16 : int_clr_sel[22] = 1'b1; + 5'h17 : int_clr_sel[23] = 1'b1; + 5'h18 : int_clr_sel[24] = 1'b1; + 5'h19 : int_clr_sel[25] = 1'b1; + 5'h1a : int_clr_sel[26] = 1'b1; + 5'h1b : int_clr_sel[27] = 1'b1; + 5'h1c : int_clr_sel[28] = 1'b1; + 5'h1d : int_clr_sel[29] = 1'b1; + 5'h1e : int_clr_sel[30] = 1'b1; + 5'h1f : int_clr_sel[31] = 1'b1; + endcase +// &CombEnd; @318 +end +assign int_clr_en[31:0] = {32{rtu_yy_xx_expt_int & ctrl_fpr_ex1_int_spec}} & int_clr_sel[31:0]; +assign int_clr_en[32] = 1'b0; +assign int_clr_en[33] = 1'b0; + + +//----------------------------------------------- +// 3. Two read ports +//----------------------------------------------- +// Read Port 1 for rs1 +// &CombBeg; @328 +always @( reg_28_dout[31:0] + or reg_31_dout[31:0] + or reg_18_dout[31:0] + or reg_20_dout[31:0] + or reg_7_dout[31:0] + or reg_17_dout[31:0] + or reg_21_dout[31:0] + or reg_15_dout[31:0] + or reg_22_dout[31:0] + or reg_12_dout[31:0] + or reg_24_dout[31:0] + or reg_19_dout[31:0] + or reg_27_dout[31:0] + or reg_3_dout[31:0] + or reg_30_dout[31:0] + or reg_4_dout[31:0] + or reg_23_dout[31:0] + or decd_fp_fpr_rs1[4:0] + or reg_8_dout[31:0] + or reg_9_dout[31:0] + or reg_29_dout[31:0] + or reg_1_dout[31:0] + or reg_25_dout[31:0] + or reg_26_dout[31:0] + or reg_10_dout[31:0] + or reg_6_dout[31:0] + or reg_5_dout[31:0] + or reg_13_dout[31:0] + or reg_14_dout[31:0] + or reg_16_dout[31:0] + or reg_2_dout[31:0] + or reg_0_dout[31:0] + or reg_11_dout[31:0]) +begin + case(decd_fp_fpr_rs1[4:0]) + 5'h00 : fpr_read_data1[REG_WIDTH-1:0] = reg_0_dout[REG_WIDTH-1:0]; + 5'h01 : fpr_read_data1[REG_WIDTH-1:0] = reg_1_dout[REG_WIDTH-1:0]; + 5'h02 : fpr_read_data1[REG_WIDTH-1:0] = reg_2_dout[REG_WIDTH-1:0]; + 5'h03 : fpr_read_data1[REG_WIDTH-1:0] = reg_3_dout[REG_WIDTH-1:0]; + 5'h04 : fpr_read_data1[REG_WIDTH-1:0] = reg_4_dout[REG_WIDTH-1:0]; + 5'h05 : fpr_read_data1[REG_WIDTH-1:0] = reg_5_dout[REG_WIDTH-1:0]; + 5'h06 : fpr_read_data1[REG_WIDTH-1:0] = reg_6_dout[REG_WIDTH-1:0]; + 5'h07 : fpr_read_data1[REG_WIDTH-1:0] = reg_7_dout[REG_WIDTH-1:0]; + 5'h08 : fpr_read_data1[REG_WIDTH-1:0] = reg_8_dout[REG_WIDTH-1:0]; + 5'h09 : fpr_read_data1[REG_WIDTH-1:0] = reg_9_dout[REG_WIDTH-1:0]; + 5'h0a : fpr_read_data1[REG_WIDTH-1:0] = reg_10_dout[REG_WIDTH-1:0]; + 5'h0b : fpr_read_data1[REG_WIDTH-1:0] = reg_11_dout[REG_WIDTH-1:0]; + 5'h0c : fpr_read_data1[REG_WIDTH-1:0] = reg_12_dout[REG_WIDTH-1:0]; + 5'h0d : fpr_read_data1[REG_WIDTH-1:0] = reg_13_dout[REG_WIDTH-1:0]; + 5'h0e : fpr_read_data1[REG_WIDTH-1:0] = reg_14_dout[REG_WIDTH-1:0]; + 5'h0f : fpr_read_data1[REG_WIDTH-1:0] = reg_15_dout[REG_WIDTH-1:0]; + 5'h10 : fpr_read_data1[REG_WIDTH-1:0] = reg_16_dout[REG_WIDTH-1:0]; + 5'h11 : fpr_read_data1[REG_WIDTH-1:0] = reg_17_dout[REG_WIDTH-1:0]; + 5'h12 : fpr_read_data1[REG_WIDTH-1:0] = reg_18_dout[REG_WIDTH-1:0]; + 5'h13 : fpr_read_data1[REG_WIDTH-1:0] = reg_19_dout[REG_WIDTH-1:0]; + 5'h14 : fpr_read_data1[REG_WIDTH-1:0] = reg_20_dout[REG_WIDTH-1:0]; + 5'h15 : fpr_read_data1[REG_WIDTH-1:0] = reg_21_dout[REG_WIDTH-1:0]; + 5'h16 : fpr_read_data1[REG_WIDTH-1:0] = reg_22_dout[REG_WIDTH-1:0]; + 5'h17 : fpr_read_data1[REG_WIDTH-1:0] = reg_23_dout[REG_WIDTH-1:0]; + 5'h18 : fpr_read_data1[REG_WIDTH-1:0] = reg_24_dout[REG_WIDTH-1:0]; + 5'h19 : fpr_read_data1[REG_WIDTH-1:0] = reg_25_dout[REG_WIDTH-1:0]; + 5'h1a : fpr_read_data1[REG_WIDTH-1:0] = reg_26_dout[REG_WIDTH-1:0]; + 5'h1b : fpr_read_data1[REG_WIDTH-1:0] = reg_27_dout[REG_WIDTH-1:0]; + 5'h1c : fpr_read_data1[REG_WIDTH-1:0] = reg_28_dout[REG_WIDTH-1:0]; + 5'h1d : fpr_read_data1[REG_WIDTH-1:0] = reg_29_dout[REG_WIDTH-1:0]; + 5'h1e : fpr_read_data1[REG_WIDTH-1:0] = reg_30_dout[REG_WIDTH-1:0]; + 5'h1f : fpr_read_data1[REG_WIDTH-1:0] = reg_31_dout[REG_WIDTH-1:0]; + default : fpr_read_data1[REG_WIDTH-1:0] = {REG_WIDTH{1'bx}}; + endcase +// &CombEnd; @364 +end + +// Read Port 2 for rs2 +// &CombBeg; @367 +always @( reg_28_dout[31:0] + or reg_31_dout[31:0] + or reg_18_dout[31:0] + or reg_20_dout[31:0] + or reg_7_dout[31:0] + or decd_fp_fpr_rs2[4:0] + or reg_17_dout[31:0] + or reg_21_dout[31:0] + or reg_15_dout[31:0] + or reg_22_dout[31:0] + or reg_12_dout[31:0] + or reg_24_dout[31:0] + or reg_19_dout[31:0] + or reg_27_dout[31:0] + or reg_3_dout[31:0] + or reg_30_dout[31:0] + or reg_4_dout[31:0] + or reg_23_dout[31:0] + or reg_8_dout[31:0] + or reg_9_dout[31:0] + or reg_29_dout[31:0] + or reg_1_dout[31:0] + or reg_25_dout[31:0] + or reg_10_dout[31:0] + or reg_26_dout[31:0] + or reg_6_dout[31:0] + or reg_14_dout[31:0] + or reg_13_dout[31:0] + or reg_5_dout[31:0] + or reg_16_dout[31:0] + or reg_2_dout[31:0] + or reg_0_dout[31:0] + or reg_11_dout[31:0]) +begin + case(decd_fp_fpr_rs2[4:0]) + 5'h00 : fpr_read_data2[REG_WIDTH-1:0] = reg_0_dout[REG_WIDTH-1:0]; + 5'h01 : fpr_read_data2[REG_WIDTH-1:0] = reg_1_dout[REG_WIDTH-1:0]; + 5'h02 : fpr_read_data2[REG_WIDTH-1:0] = reg_2_dout[REG_WIDTH-1:0]; + 5'h03 : fpr_read_data2[REG_WIDTH-1:0] = reg_3_dout[REG_WIDTH-1:0]; + 5'h04 : fpr_read_data2[REG_WIDTH-1:0] = reg_4_dout[REG_WIDTH-1:0]; + 5'h05 : fpr_read_data2[REG_WIDTH-1:0] = reg_5_dout[REG_WIDTH-1:0]; + 5'h06 : fpr_read_data2[REG_WIDTH-1:0] = reg_6_dout[REG_WIDTH-1:0]; + 5'h07 : fpr_read_data2[REG_WIDTH-1:0] = reg_7_dout[REG_WIDTH-1:0]; + 5'h08 : fpr_read_data2[REG_WIDTH-1:0] = reg_8_dout[REG_WIDTH-1:0]; + 5'h09 : fpr_read_data2[REG_WIDTH-1:0] = reg_9_dout[REG_WIDTH-1:0]; + 5'h0a : fpr_read_data2[REG_WIDTH-1:0] = reg_10_dout[REG_WIDTH-1:0]; + 5'h0b : fpr_read_data2[REG_WIDTH-1:0] = reg_11_dout[REG_WIDTH-1:0]; + 5'h0c : fpr_read_data2[REG_WIDTH-1:0] = reg_12_dout[REG_WIDTH-1:0]; + 5'h0d : fpr_read_data2[REG_WIDTH-1:0] = reg_13_dout[REG_WIDTH-1:0]; + 5'h0e : fpr_read_data2[REG_WIDTH-1:0] = reg_14_dout[REG_WIDTH-1:0]; + 5'h0f : fpr_read_data2[REG_WIDTH-1:0] = reg_15_dout[REG_WIDTH-1:0]; + 5'h10 : fpr_read_data2[REG_WIDTH-1:0] = reg_16_dout[REG_WIDTH-1:0]; + 5'h11 : fpr_read_data2[REG_WIDTH-1:0] = reg_17_dout[REG_WIDTH-1:0]; + 5'h12 : fpr_read_data2[REG_WIDTH-1:0] = reg_18_dout[REG_WIDTH-1:0]; + 5'h13 : fpr_read_data2[REG_WIDTH-1:0] = reg_19_dout[REG_WIDTH-1:0]; + 5'h14 : fpr_read_data2[REG_WIDTH-1:0] = reg_20_dout[REG_WIDTH-1:0]; + 5'h15 : fpr_read_data2[REG_WIDTH-1:0] = reg_21_dout[REG_WIDTH-1:0]; + 5'h16 : fpr_read_data2[REG_WIDTH-1:0] = reg_22_dout[REG_WIDTH-1:0]; + 5'h17 : fpr_read_data2[REG_WIDTH-1:0] = reg_23_dout[REG_WIDTH-1:0]; + 5'h18 : fpr_read_data2[REG_WIDTH-1:0] = reg_24_dout[REG_WIDTH-1:0]; + 5'h19 : fpr_read_data2[REG_WIDTH-1:0] = reg_25_dout[REG_WIDTH-1:0]; + 5'h1a : fpr_read_data2[REG_WIDTH-1:0] = reg_26_dout[REG_WIDTH-1:0]; + 5'h1b : fpr_read_data2[REG_WIDTH-1:0] = reg_27_dout[REG_WIDTH-1:0]; + 5'h1c : fpr_read_data2[REG_WIDTH-1:0] = reg_28_dout[REG_WIDTH-1:0]; + 5'h1d : fpr_read_data2[REG_WIDTH-1:0] = reg_29_dout[REG_WIDTH-1:0]; + 5'h1e : fpr_read_data2[REG_WIDTH-1:0] = reg_30_dout[REG_WIDTH-1:0]; + 5'h1f : fpr_read_data2[REG_WIDTH-1:0] = reg_31_dout[REG_WIDTH-1:0]; + default : fpr_read_data2[REG_WIDTH-1:0] = {REG_WIDTH{1'bx}}; + endcase +// &CombEnd; @403 +end + +// Read Port 3 for rs3 +// &CombBeg; @406 +always @( reg_28_dout[31:0] + or reg_31_dout[31:0] + or reg_18_dout[31:0] + or reg_20_dout[31:0] + or reg_7_dout[31:0] + or reg_17_dout[31:0] + or reg_21_dout[31:0] + or reg_15_dout[31:0] + or reg_22_dout[31:0] + or reg_12_dout[31:0] + or reg_24_dout[31:0] + or reg_19_dout[31:0] + or reg_27_dout[31:0] + or reg_3_dout[31:0] + or reg_30_dout[31:0] + or reg_4_dout[31:0] + or reg_23_dout[31:0] + or reg_8_dout[31:0] + or reg_9_dout[31:0] + or reg_29_dout[31:0] + or reg_1_dout[31:0] + or reg_25_dout[31:0] + or reg_10_dout[31:0] + or reg_26_dout[31:0] + or decd_fp_fpr_rs3[4:0] + or reg_6_dout[31:0] + or reg_14_dout[31:0] + or reg_13_dout[31:0] + or reg_5_dout[31:0] + or reg_16_dout[31:0] + or reg_2_dout[31:0] + or reg_0_dout[31:0] + or reg_11_dout[31:0]) +begin + case(decd_fp_fpr_rs3[4:0]) + 5'h00 : fpr_read_data3[REG_WIDTH-1:0] = reg_0_dout[REG_WIDTH-1:0]; + 5'h01 : fpr_read_data3[REG_WIDTH-1:0] = reg_1_dout[REG_WIDTH-1:0]; + 5'h02 : fpr_read_data3[REG_WIDTH-1:0] = reg_2_dout[REG_WIDTH-1:0]; + 5'h03 : fpr_read_data3[REG_WIDTH-1:0] = reg_3_dout[REG_WIDTH-1:0]; + 5'h04 : fpr_read_data3[REG_WIDTH-1:0] = reg_4_dout[REG_WIDTH-1:0]; + 5'h05 : fpr_read_data3[REG_WIDTH-1:0] = reg_5_dout[REG_WIDTH-1:0]; + 5'h06 : fpr_read_data3[REG_WIDTH-1:0] = reg_6_dout[REG_WIDTH-1:0]; + 5'h07 : fpr_read_data3[REG_WIDTH-1:0] = reg_7_dout[REG_WIDTH-1:0]; + 5'h08 : fpr_read_data3[REG_WIDTH-1:0] = reg_8_dout[REG_WIDTH-1:0]; + 5'h09 : fpr_read_data3[REG_WIDTH-1:0] = reg_9_dout[REG_WIDTH-1:0]; + 5'h0a : fpr_read_data3[REG_WIDTH-1:0] = reg_10_dout[REG_WIDTH-1:0]; + 5'h0b : fpr_read_data3[REG_WIDTH-1:0] = reg_11_dout[REG_WIDTH-1:0]; + 5'h0c : fpr_read_data3[REG_WIDTH-1:0] = reg_12_dout[REG_WIDTH-1:0]; + 5'h0d : fpr_read_data3[REG_WIDTH-1:0] = reg_13_dout[REG_WIDTH-1:0]; + 5'h0e : fpr_read_data3[REG_WIDTH-1:0] = reg_14_dout[REG_WIDTH-1:0]; + 5'h0f : fpr_read_data3[REG_WIDTH-1:0] = reg_15_dout[REG_WIDTH-1:0]; + 5'h10 : fpr_read_data3[REG_WIDTH-1:0] = reg_16_dout[REG_WIDTH-1:0]; + 5'h11 : fpr_read_data3[REG_WIDTH-1:0] = reg_17_dout[REG_WIDTH-1:0]; + 5'h12 : fpr_read_data3[REG_WIDTH-1:0] = reg_18_dout[REG_WIDTH-1:0]; + 5'h13 : fpr_read_data3[REG_WIDTH-1:0] = reg_19_dout[REG_WIDTH-1:0]; + 5'h14 : fpr_read_data3[REG_WIDTH-1:0] = reg_20_dout[REG_WIDTH-1:0]; + 5'h15 : fpr_read_data3[REG_WIDTH-1:0] = reg_21_dout[REG_WIDTH-1:0]; + 5'h16 : fpr_read_data3[REG_WIDTH-1:0] = reg_22_dout[REG_WIDTH-1:0]; + 5'h17 : fpr_read_data3[REG_WIDTH-1:0] = reg_23_dout[REG_WIDTH-1:0]; + 5'h18 : fpr_read_data3[REG_WIDTH-1:0] = reg_24_dout[REG_WIDTH-1:0]; + 5'h19 : fpr_read_data3[REG_WIDTH-1:0] = reg_25_dout[REG_WIDTH-1:0]; + 5'h1a : fpr_read_data3[REG_WIDTH-1:0] = reg_26_dout[REG_WIDTH-1:0]; + 5'h1b : fpr_read_data3[REG_WIDTH-1:0] = reg_27_dout[REG_WIDTH-1:0]; + 5'h1c : fpr_read_data3[REG_WIDTH-1:0] = reg_28_dout[REG_WIDTH-1:0]; + 5'h1d : fpr_read_data3[REG_WIDTH-1:0] = reg_29_dout[REG_WIDTH-1:0]; + 5'h1e : fpr_read_data3[REG_WIDTH-1:0] = reg_30_dout[REG_WIDTH-1:0]; + 5'h1f : fpr_read_data3[REG_WIDTH-1:0] = reg_31_dout[REG_WIDTH-1:0]; + default : fpr_read_data3[REG_WIDTH-1:0] = {REG_WIDTH{1'bx}}; + endcase +// &CombEnd; @442 +end + +assign fpr_rs1_dep_wb = decd_fp_fpr_rs1[4:0] == write_index[4:0] + & rtu_idu_fgpr_wb_vld; +assign fpr_rs2_dep_wb = decd_fp_fpr_rs2[4:0] == write_index[4:0] + & rtu_idu_fgpr_wb_vld; +assign fpr_rs3_dep_wb = decd_fp_fpr_rs3[4:0] == write_index[4:0] + & rtu_idu_fgpr_wb_vld; + +assign fpr_fin_data1[REG_WIDTH-1:0] = fpr_rs1_dep_wb ? rtu_idu_fgpr_wb_data[REG_WIDTH-1:0] + : fpr_read_data1[REG_WIDTH-1:0]; +assign fpr_fin_data2[REG_WIDTH-1:0] = fpr_rs2_dep_wb ? rtu_idu_fgpr_wb_data[REG_WIDTH-1:0] + : fpr_read_data2[REG_WIDTH-1:0]; +assign fpr_fin_data3[REG_WIDTH-1:0] = fpr_rs3_dep_wb ? rtu_idu_fgpr_wb_data[REG_WIDTH-1:0] + : fpr_read_data3[REG_WIDTH-1:0]; + +//----------------------------------------------- +// 4. Reg Busy Judge +//----------------------------------------------- +assign fpr_busy_rslt1[31:0] = reg_busy[31:0] >> decd_fp_fpr_rs1[4:0]; +assign fpr_busy_rslt2[31:0] = reg_busy[31:0] >> decd_fp_fpr_rs2[4:0]; +assign fpr_busy_rslt3[31:0] = reg_busy[31:0] >> decd_fp_fpr_rs3[4:0]; +assign fpr_busy_rsltd[31:0] = reg_busy[31:0] >> decd_fp_fpr_rd[4:0]; +assign fpr_busy_lsu1[31:0] = reg_busy_lsu[31:0] >> decd_fp_fpr_rs1[4:0]; +assign fpr_busy_lsu2[31:0] = reg_busy_lsu[31:0] >> decd_fp_fpr_rs2[4:0]; +assign fpr_busy_lsu3[31:0] = reg_busy_lsu[31:0] >> decd_fp_fpr_rs3[4:0]; +assign fpr_busy_lsud[31:0] = reg_busy_lsu[31:0] >> decd_fp_fpr_rd[4:0]; +assign fpr_busy_div1[31:0] = reg_busy_div[31:0] >> decd_fp_fpr_rs1[4:0]; +assign fpr_busy_div2[31:0] = reg_busy_div[31:0] >> decd_fp_fpr_rs2[4:0]; +assign fpr_busy_div3[31:0] = reg_busy_div[31:0] >> decd_fp_fpr_rs3[4:0]; +assign fpr_busy_divd[31:0] = reg_busy_div[31:0] >> decd_fp_fpr_rd[4:0]; + +//========================================================== +// Rename output information +//========================================================== +assign fpr_id_fp_rs1[REG_WIDTH-1:0] = fpr_fin_data1[REG_WIDTH-1:0]; +assign fpr_id_fp_rs2[REG_WIDTH-1:0] = fpr_fin_data2[REG_WIDTH-1:0]; +assign fpr_id_fp_rs3[REG_WIDTH-1:0] = fpr_fin_data3[REG_WIDTH-1:0]; + +assign fpr_id_fp_rs1_busy = fpr_busy_rslt1[0] & decd_fp_fpr_rs1_vld; +assign fpr_id_fp_rs2_busy = fpr_busy_rslt2[0] & decd_fp_fpr_rs2_vld; +assign fpr_id_fp_rs3_busy = fpr_busy_rslt3[0] & decd_fp_fpr_rs3_vld; +assign fpr_id_fp_rd_busy = fpr_busy_rsltd[0] & decd_fp_fpr_rd_vld; +assign fpr_id_fp_rs1_busy_lsu = fpr_busy_lsu1[0] & decd_fp_fpr_rs1_vld; +assign fpr_id_fp_rs2_busy_lsu = fpr_busy_lsu2[0] & decd_fp_fpr_rs2_vld; +assign fpr_id_fp_rs3_busy_lsu = fpr_busy_lsu3[0] & decd_fp_fpr_rs3_vld; +assign fpr_id_fp_rd_busy_lsu = fpr_busy_lsud[0] & decd_fp_fpr_rd_vld; + +// &Force("nonport", "fpr_id_fp_rs1_busy_div"); @490 +// &Force("nonport", "fpr_id_fp_rs2_busy_div"); @491 +// &Force("nonport", "fpr_id_fp_rs3_busy_div"); @492 +// &Force("nonport", "fpr_id_fp_rd_busy_div"); @493 +assign fpr_id_fp_rs1_busy_div = fpr_busy_div1[0] & decd_fp_fpr_rs1_vld; +assign fpr_id_fp_rs2_busy_div = fpr_busy_div2[0] & decd_fp_fpr_rs2_vld; +assign fpr_id_fp_rs3_busy_div = fpr_busy_div3[0] & decd_fp_fpr_rs3_vld; +assign fpr_id_fp_rd_busy_div = fpr_busy_divd[0] & decd_fp_fpr_rd_vld; + +assign fpr_top_reg_busy[31:0] = reg_busy[31:0]; +assign fpr_top_reg_busy_lsu[31:0] = reg_busy_lsu[31:0]; +assign fpr_top_reg_busy_div[31:0] = reg_busy_div[31:0]; + +// &ModuleEnd; @503 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_gpr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_gpr.v new file mode 100644 index 0000000000000000000000000000000000000000..f2bc2dbec3a6325e9ff349c11a46a38cf47765b3 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_gpr.v @@ -0,0 +1,2903 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_gpr( + cp0_idu_icg_en, + cp0_idu_sp_wdata, + cp0_idu_sp_wen, + cp0_idu_sp_wen_gate, + cp0_yy_clk_en, + cpurst_b, + ctrl_gpr_div_inst, + ctrl_gpr_ex1_dst_preg, + ctrl_gpr_ex1_int_spec, + ctrl_gpr_id_rd1_vld, + ctrl_gpr_id_rd2_vld, + ctrl_gpr_id_wr_idx1, + ctrl_gpr_id_wr_idx2, + ctrl_gpr_ld_inst, + ctrl_gpr_wr_issue1, + decd_gpr_dep_rs1, + decd_gpr_dep_rs2, + decd_gpr_rd1_vld, + decd_gpr_rd2_vld, + decd_gpr_rs1, + decd_gpr_rs1_vld, + decd_gpr_rs2, + decd_gpr_rs2_vld, + decd_gpr_rs3, + decd_gpr_rs3_vld, + decd_gpr_rs4, + decd_gpr_rs4_vld, + dp_gpr_rs1_fwd_div, + dp_gpr_rs1_fwd_lsu, + dp_gpr_rs2_fwd_div, + dp_gpr_rs2_fwd_lsu, + dp_gpr_rs3_fwd_div, + dp_gpr_rs3_fwd_lsu, + dp_gpr_rs4_fwd_div, + dp_gpr_rs4_fwd_lsu, + dp_gpr_x2_busy, + dp_gpr_x2_busy2, + forever_cpuclk, + gpr_ctrl_rd1_busy_div, + gpr_ctrl_rd1_busy_lsu, + gpr_ctrl_rd2_busy_div, + gpr_ctrl_rd2_busy_lsu, + gpr_ctrl_rs1_busy_div, + gpr_ctrl_rs1_busy_lsu, + gpr_ctrl_rs1_busy_lsu2, + gpr_ctrl_rs2_busy_div, + gpr_ctrl_rs2_busy_lsu, + gpr_ctrl_rs2_busy_lsu2, + gpr_ctrl_rs3_busy_div, + gpr_ctrl_rs3_busy_lsu, + gpr_ctrl_rs3_busy_lsu2, + gpr_ctrl_rs4_busy_div, + gpr_ctrl_rs4_busy_lsu, + gpr_dp_id_x2_wr, + gpr_dp_rs1, + gpr_dp_rs2, + gpr_dp_rs3, + gpr_dp_rs4, + gpr_hs_sp_busy, + gpr_hs_sp_busy2, + gpr_hs_sp_wb, + hs_gpr_wb_mask, + hs_gpr_wr_mask, + idu_cp0_ipop_data, + idu_cp0_mcause_wen, + idu_cp0_mepc_wen, + idu_cp0_sp_reg, + idu_ifu_x1, + ifu_idu_warm_up, + iu_idu_ex2_div_vld, + iu_idu_ex2_fwd_preg0, + iu_idu_ex2_fwd_vld0, + lsu_idu_ex2_fwd_preg, + lsu_idu_ex2_fwd_vld, + pad_yy_icg_scan_en, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_flush_fe, + rtu_idu_wb0_data, + rtu_idu_wb0_fpu_vld, + rtu_idu_wb0_preg, + rtu_idu_wb0_vld, + rtu_idu_wb1_data, + rtu_idu_wb1_lsu_vld, + rtu_idu_wb1_preg, + rtu_idu_wb1_vld, + rtu_idu_wb2_data, + rtu_idu_wb2_preg, + rtu_idu_wb2_vld, + rtu_yy_xx_expt_int +); + +// &Ports; @24 +input cp0_idu_icg_en; +input [31:0] cp0_idu_sp_wdata; +input cp0_idu_sp_wen; +input cp0_idu_sp_wen_gate; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_gpr_div_inst; +input [4 :0] ctrl_gpr_ex1_dst_preg; +input ctrl_gpr_ex1_int_spec; +input ctrl_gpr_id_rd1_vld; +input ctrl_gpr_id_rd2_vld; +input [5 :0] ctrl_gpr_id_wr_idx1; +input [5 :0] ctrl_gpr_id_wr_idx2; +input ctrl_gpr_ld_inst; +input ctrl_gpr_wr_issue1; +input [5 :0] decd_gpr_dep_rs1; +input [5 :0] decd_gpr_dep_rs2; +input decd_gpr_rd1_vld; +input decd_gpr_rd2_vld; +input [5 :0] decd_gpr_rs1; +input decd_gpr_rs1_vld; +input [5 :0] decd_gpr_rs2; +input decd_gpr_rs2_vld; +input [5 :0] decd_gpr_rs3; +input decd_gpr_rs3_vld; +input [5 :0] decd_gpr_rs4; +input decd_gpr_rs4_vld; +input dp_gpr_rs1_fwd_div; +input dp_gpr_rs1_fwd_lsu; +input dp_gpr_rs2_fwd_div; +input dp_gpr_rs2_fwd_lsu; +input dp_gpr_rs3_fwd_div; +input dp_gpr_rs3_fwd_lsu; +input dp_gpr_rs4_fwd_div; +input dp_gpr_rs4_fwd_lsu; +input dp_gpr_x2_busy; +input dp_gpr_x2_busy2; +input forever_cpuclk; +input hs_gpr_wb_mask; +input hs_gpr_wr_mask; +input ifu_idu_warm_up; +input iu_idu_ex2_div_vld; +input [5 :0] iu_idu_ex2_fwd_preg0; +input iu_idu_ex2_fwd_vld0; +input [5 :0] lsu_idu_ex2_fwd_preg; +input lsu_idu_ex2_fwd_vld; +input pad_yy_icg_scan_en; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_flush_fe; +input [31:0] rtu_idu_wb0_data; +input rtu_idu_wb0_fpu_vld; +input [5 :0] rtu_idu_wb0_preg; +input rtu_idu_wb0_vld; +input [31:0] rtu_idu_wb1_data; +input rtu_idu_wb1_lsu_vld; +input [5 :0] rtu_idu_wb1_preg; +input rtu_idu_wb1_vld; +input [31:0] rtu_idu_wb2_data; +input [5 :0] rtu_idu_wb2_preg; +input rtu_idu_wb2_vld; +input rtu_yy_xx_expt_int; +output gpr_ctrl_rd1_busy_div; +output gpr_ctrl_rd1_busy_lsu; +output gpr_ctrl_rd2_busy_div; +output gpr_ctrl_rd2_busy_lsu; +output gpr_ctrl_rs1_busy_div; +output gpr_ctrl_rs1_busy_lsu; +output gpr_ctrl_rs1_busy_lsu2; +output gpr_ctrl_rs2_busy_div; +output gpr_ctrl_rs2_busy_lsu; +output gpr_ctrl_rs2_busy_lsu2; +output gpr_ctrl_rs3_busy_div; +output gpr_ctrl_rs3_busy_lsu; +output gpr_ctrl_rs3_busy_lsu2; +output gpr_ctrl_rs4_busy_div; +output gpr_ctrl_rs4_busy_lsu; +output gpr_dp_id_x2_wr; +output [31:0] gpr_dp_rs1; +output [31:0] gpr_dp_rs2; +output [31:0] gpr_dp_rs3; +output [31:0] gpr_dp_rs4; +output gpr_hs_sp_busy; +output gpr_hs_sp_busy2; +output gpr_hs_sp_wb; +output [31:0] idu_cp0_ipop_data; +output idu_cp0_mcause_wen; +output idu_cp0_mepc_wen; +output [31:0] idu_cp0_sp_reg; +output [31:0] idu_ifu_x1; + +// &Regs; @25 +reg [31:0] div_fwd_sel0; +reg [31:0] fpu_fwd_sel0; +reg [2 :0] gpr_rd1_busy_st; +reg [2 :0] gpr_rd2_busy_st; +reg [31:0] gpr_read_data1; +reg [31:0] gpr_read_data2; +reg [31:0] gpr_read_data3; +reg [31:0] gpr_read_data4; +reg [2 :0] gpr_rs1_busy_st; +reg [2 :0] gpr_rs2_busy_st; +reg [2 :0] gpr_rs3_busy_st; +reg [2 :0] gpr_rs4_busy_st; +reg [31:0] reg_fwd_sel1; +reg [31:0] reg_fwd_sel2; +reg [31:0] reg_issue0; +reg [31:0] reg_sel0; +reg [31:0] reg_sel1; +reg [31:0] reg_sel2; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_gpr_div_inst; +wire [4 :0] ctrl_gpr_ex1_dst_preg; +wire ctrl_gpr_ex1_int_spec; +wire ctrl_gpr_id_rd1_vld; +wire ctrl_gpr_id_rd2_vld; +wire [5 :0] ctrl_gpr_id_wr_idx1; +wire [5 :0] ctrl_gpr_id_wr_idx2; +wire ctrl_gpr_ld_inst; +wire ctrl_gpr_wr_issue1; +wire [5 :0] decd_gpr_dep_rs1; +wire [5 :0] decd_gpr_dep_rs2; +wire decd_gpr_rd1_vld; +wire decd_gpr_rd2_vld; +wire [5 :0] decd_gpr_rs1; +wire decd_gpr_rs1_vld; +wire [5 :0] decd_gpr_rs2; +wire decd_gpr_rs2_vld; +wire [5 :0] decd_gpr_rs3; +wire decd_gpr_rs3_vld; +wire [5 :0] decd_gpr_rs4; +wire decd_gpr_rs4_vld; +wire [4 :0] div_fwd_index; +wire dp_gpr_rs1_fwd_div; +wire dp_gpr_rs1_fwd_lsu; +wire dp_gpr_rs2_fwd_div; +wire dp_gpr_rs2_fwd_lsu; +wire dp_gpr_rs3_fwd_div; +wire dp_gpr_rs3_fwd_lsu; +wire dp_gpr_rs4_fwd_div; +wire dp_gpr_rs4_fwd_lsu; +wire dp_gpr_x2_busy; +wire dp_gpr_x2_busy2; +wire forever_cpuclk; +wire [4 :0] fpu_fwd0_reg; +wire fpu_fwd0_vld; +wire [4 :0] fpu_fwd_index; +wire [4 :0] fwd_index1_sel; +wire [4 :0] fwd_index2_sel; +wire gpr_ctrl_rd1_busy_div; +wire gpr_ctrl_rd1_busy_lsu; +wire gpr_ctrl_rd2_busy_div; +wire gpr_ctrl_rd2_busy_lsu; +wire gpr_ctrl_rs1_busy_div; +wire gpr_ctrl_rs1_busy_lsu; +wire gpr_ctrl_rs1_busy_lsu2; +wire gpr_ctrl_rs2_busy_div; +wire gpr_ctrl_rs2_busy_lsu; +wire gpr_ctrl_rs2_busy_lsu2; +wire gpr_ctrl_rs3_busy_div; +wire gpr_ctrl_rs3_busy_lsu; +wire gpr_ctrl_rs3_busy_lsu2; +wire gpr_ctrl_rs4_busy_div; +wire gpr_ctrl_rs4_busy_lsu; +wire gpr_dp_id_x2_wr; +wire [31:0] gpr_dp_rs1; +wire [31:0] gpr_dp_rs2; +wire [31:0] gpr_dp_rs3; +wire [31:0] gpr_dp_rs4; +wire gpr_hs_sp_busy; +wire gpr_hs_sp_busy2; +wire gpr_hs_sp_wb; +wire gpr_rd1_busy_div; +wire gpr_rd1_busy_lsu; +wire [31:0] gpr_rd1_fwd_div; +wire gpr_rd1_fwd_lsu; +wire gpr_rd2_busy_div; +wire gpr_rd2_busy_lsu; +wire [31:0] gpr_rd2_fwd_div; +wire gpr_rd2_fwd_lsu; +wire [31:0] gpr_read_data1_after_hint; +wire [31:0] gpr_read_data2_after_hint; +wire gpr_rs1_busy_div; +wire gpr_rs1_busy_lsu; +wire [31:0] gpr_rs1_fwd_div; +wire gpr_rs2_busy_div; +wire gpr_rs2_busy_lsu; +wire [31:0] gpr_rs2_fwd_div; +wire gpr_rs3_busy_div; +wire gpr_rs3_busy_lsu; +wire [31:0] gpr_rs3_fwd_div; +wire gpr_rs4_busy_div; +wire gpr_rs4_busy_lsu; +wire [31:0] gpr_rs4_fwd_div; +wire gpr_sync_rst_b; +wire gpr_wb_sp; +wire [31:0] hint_read_data1; +wire [31:0] hint_read_data2; +wire hs_gpr_wb_mask; +wire hs_gpr_wr_mask; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire [31:0] idu_ifu_x1; +wire ifu_idu_warm_up; +wire iu_idu_ex2_div_vld; +wire [5 :0] iu_idu_ex2_fwd_preg0; +wire iu_idu_ex2_fwd_vld0; +wire [5 :0] lsu_idu_ex2_fwd_preg; +wire lsu_idu_ex2_fwd_vld; +wire pad_yy_icg_scan_en; +wire [2 :0] reg_busy_st_1; +wire [2 :0] reg_busy_st_10; +wire [2 :0] reg_busy_st_11; +wire [2 :0] reg_busy_st_12; +wire [2 :0] reg_busy_st_13; +wire [2 :0] reg_busy_st_14; +wire [2 :0] reg_busy_st_15; +wire [2 :0] reg_busy_st_16; +wire [2 :0] reg_busy_st_17; +wire [2 :0] reg_busy_st_18; +wire [2 :0] reg_busy_st_19; +wire [2 :0] reg_busy_st_2; +wire [2 :0] reg_busy_st_20; +wire [2 :0] reg_busy_st_21; +wire [2 :0] reg_busy_st_22; +wire [2 :0] reg_busy_st_23; +wire [2 :0] reg_busy_st_24; +wire [2 :0] reg_busy_st_25; +wire [2 :0] reg_busy_st_26; +wire [2 :0] reg_busy_st_27; +wire [2 :0] reg_busy_st_28; +wire [2 :0] reg_busy_st_29; +wire [2 :0] reg_busy_st_3; +wire [2 :0] reg_busy_st_30; +wire [2 :0] reg_busy_st_31; +wire [2 :0] reg_busy_st_32; +wire [2 :0] reg_busy_st_33; +wire [2 :0] reg_busy_st_4; +wire [2 :0] reg_busy_st_5; +wire [2 :0] reg_busy_st_6; +wire [2 :0] reg_busy_st_7; +wire [2 :0] reg_busy_st_8; +wire [2 :0] reg_busy_st_9; +wire [31:0] reg_dout_1; +wire [31:0] reg_dout_10; +wire [31:0] reg_dout_11; +wire [31:0] reg_dout_12; +wire [31:0] reg_dout_13; +wire [31:0] reg_dout_14; +wire [31:0] reg_dout_15; +wire [31:0] reg_dout_16; +wire [31:0] reg_dout_17; +wire [31:0] reg_dout_18; +wire [31:0] reg_dout_19; +wire [31:0] reg_dout_2; +wire [31:0] reg_dout_20; +wire [31:0] reg_dout_21; +wire [31:0] reg_dout_22; +wire [31:0] reg_dout_23; +wire [31:0] reg_dout_24; +wire [31:0] reg_dout_25; +wire [31:0] reg_dout_26; +wire [31:0] reg_dout_27; +wire [31:0] reg_dout_28; +wire [31:0] reg_dout_29; +wire [31:0] reg_dout_3; +wire [31:0] reg_dout_30; +wire [31:0] reg_dout_31; +wire [31:0] reg_dout_32; +wire [31:0] reg_dout_33; +wire [31:0] reg_dout_4; +wire [31:0] reg_dout_5; +wire [31:0] reg_dout_6; +wire [31:0] reg_dout_7; +wire [31:0] reg_dout_8; +wire [31:0] reg_dout_9; +wire [33:0] reg_fwd_en0; +wire [33:0] reg_fwd_en1; +wire [33:0] reg_fwd_en2; +wire reg_fwd_en_high0; +wire reg_fwd_en_high1; +wire reg_high_clk_en; +wire reg_high_cpuclk; +wire [1 :0] reg_hint_is0; +wire [1 :0] reg_hint_sel0; +wire [1 :0] reg_hint_sel1; +wire [4 :0] reg_issue0_sel; +wire [33:0] reg_write_en0; +wire [33:0] reg_write_en1; +wire [33:0] reg_write_en2; +wire [33:0] reg_write_en_gate0; +wire [33:0] reg_write_en_gate1; +wire [33:0] reg_write_en_gate2; +wire [1 :0] reg_write_en_hint0; +wire [1 :0] reg_write_en_hint1; +wire reg_write_en_sp; +wire reg_write_en_sp_gate; +wire [33:0] reg_write_is0; +wire [33:0] reg_write_is_gate0; +wire reg_write_is_high0; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_flush_fe; +wire [31:0] rtu_idu_wb0_data; +wire rtu_idu_wb0_fpu_vld; +wire [5 :0] rtu_idu_wb0_preg; +wire rtu_idu_wb0_vld; +wire [31:0] rtu_idu_wb1_data; +wire [5 :0] rtu_idu_wb1_preg; +wire rtu_idu_wb1_vld; +wire [31:0] rtu_idu_wb2_data; +wire [5 :0] rtu_idu_wb2_preg; +wire rtu_idu_wb2_vld; +wire rtu_yy_xx_expt_int; +wire [31:0] write_data0; +wire [31:0] write_data1; +wire [31:0] write_data2; +wire [31:0] write_data_sp; +wire [5 :0] write_index0; +wire [4 :0] write_index0_sel; +wire [5 :0] write_index1; +wire [5 :0] write_index2; + + +//========================================================= +// GRP Module +// 1. Instance all GRP modules +// 2. One write port +// 3. Two read ports +//========================================================= +assign reg_write_is_high0 = ctrl_gpr_id_rd1_vld & ctrl_gpr_id_wr_idx1[4] & ~hs_gpr_wr_mask; +//assign reg_write_is_high1 = ctrl_gpr_id_rd2_vld & ctrl_gpr_id_wr_idx2[4]; +assign reg_fwd_en_high0 = iu_idu_ex2_fwd_vld0 & iu_idu_ex2_div_vld & iu_idu_ex2_fwd_preg0[4] + | fpu_fwd0_vld & fpu_fwd0_reg[4] + | rtu_yy_xx_expt_int & ctrl_gpr_ex1_dst_preg[4]; +assign reg_fwd_en_high1 = lsu_idu_ex2_fwd_vld & lsu_idu_ex2_fwd_preg[4] + | rtu_yy_xx_expt_int & ctrl_gpr_ex1_dst_preg[4]; +assign reg_high_clk_en = reg_write_is_high0 //| reg_write_is_high1 + | reg_fwd_en_high0 | reg_fwd_en_high1 + | rtu_idu_flush_fe; +// &Instance("gated_clk_cell", "x_reg_high_gated_clk"); @44 +gated_clk_cell x_reg_high_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_high_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_high_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @45 +// .external_en (1'b0), @46 +// .global_en (cp0_yy_clk_en), @47 +// .module_en ( cp0_idu_icg_en ) , @48 +// .local_en (reg_high_clk_en), @49 +// .clk_out (reg_high_cpuclk)); @50 + +//----------------------------------------------- +// 1. Instance all GRP modules +//----------------------------------------------- +// &ConnRule(s/_x$/[1]/); @55 +// &ConnRule(s/_y$/_1/); @56 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_1"); @57 +pa_idu_reg32 x_pa_idu_reg32_1 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_1 ), + .reg_dout_y (reg_dout_1 ), + .reg_fwd_en0_x (reg_fwd_en0[1] ), + .reg_fwd_en1_x (reg_fwd_en1[1] ), + .reg_fwd_en2_x (reg_fwd_en2[1] ), + .reg_write_en0_x (reg_write_en0[1] ), + .reg_write_en1_x (reg_write_en1[1] ), + .reg_write_en2_x (reg_write_en2[1] ), + .reg_write_en_gate0_x (reg_write_en_gate0[1] ), + .reg_write_en_gate1_x (reg_write_en_gate1[1] ), + .reg_write_en_gate2_x (reg_write_en_gate2[1] ), + .reg_write_is0_x (reg_write_is0[1] ), + .reg_write_is_gate0_x (reg_write_is_gate0[1] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[2]/); @59 +// &ConnRule(s/_y$/_2/); @60 +// &Instance("pa_idu_reg_sp", "x_pa_idu_reg32_2"); @61 +pa_idu_reg_sp x_pa_idu_reg32_2 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_2 ), + .reg_dout_y (reg_dout_2 ), + .reg_fwd_en0_x (reg_fwd_en0[2] ), + .reg_fwd_en1_x (reg_fwd_en1[2] ), + .reg_fwd_en2_x (reg_fwd_en2[2] ), + .reg_write_en0_x (reg_write_en0[2] ), + .reg_write_en1_x (reg_write_en1[2] ), + .reg_write_en2_x (reg_write_en2[2] ), + .reg_write_en_gate0_x (reg_write_en_gate0[2] ), + .reg_write_en_gate1_x (reg_write_en_gate1[2] ), + .reg_write_en_gate2_x (reg_write_en_gate2[2] ), + .reg_write_en_sp (reg_write_en_sp ), + .reg_write_en_sp_gate (reg_write_en_sp_gate ), + .reg_write_is0_x (reg_write_is0[2] ), + .reg_write_is_gate0_x (reg_write_is_gate0[2] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ), + .write_data_sp (write_data_sp ) +); + + +// &ConnRule(s/_x$/[3]/); @63 +// &ConnRule(s/_y$/_3/); @64 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_3"); @65 +pa_idu_reg32 x_pa_idu_reg32_3 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_3 ), + .reg_dout_y (reg_dout_3 ), + .reg_fwd_en0_x (reg_fwd_en0[3] ), + .reg_fwd_en1_x (reg_fwd_en1[3] ), + .reg_fwd_en2_x (reg_fwd_en2[3] ), + .reg_write_en0_x (reg_write_en0[3] ), + .reg_write_en1_x (reg_write_en1[3] ), + .reg_write_en2_x (reg_write_en2[3] ), + .reg_write_en_gate0_x (reg_write_en_gate0[3] ), + .reg_write_en_gate1_x (reg_write_en_gate1[3] ), + .reg_write_en_gate2_x (reg_write_en_gate2[3] ), + .reg_write_is0_x (reg_write_is0[3] ), + .reg_write_is_gate0_x (reg_write_is_gate0[3] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[4]/); @67 +// &ConnRule(s/_y$/_4/); @68 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_4"); @69 +pa_idu_reg32 x_pa_idu_reg32_4 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_4 ), + .reg_dout_y (reg_dout_4 ), + .reg_fwd_en0_x (reg_fwd_en0[4] ), + .reg_fwd_en1_x (reg_fwd_en1[4] ), + .reg_fwd_en2_x (reg_fwd_en2[4] ), + .reg_write_en0_x (reg_write_en0[4] ), + .reg_write_en1_x (reg_write_en1[4] ), + .reg_write_en2_x (reg_write_en2[4] ), + .reg_write_en_gate0_x (reg_write_en_gate0[4] ), + .reg_write_en_gate1_x (reg_write_en_gate1[4] ), + .reg_write_en_gate2_x (reg_write_en_gate2[4] ), + .reg_write_is0_x (reg_write_is0[4] ), + .reg_write_is_gate0_x (reg_write_is_gate0[4] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[5]/); @71 +// &ConnRule(s/_y$/_5/); @72 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_5"); @73 +pa_idu_reg32 x_pa_idu_reg32_5 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_5 ), + .reg_dout_y (reg_dout_5 ), + .reg_fwd_en0_x (reg_fwd_en0[5] ), + .reg_fwd_en1_x (reg_fwd_en1[5] ), + .reg_fwd_en2_x (reg_fwd_en2[5] ), + .reg_write_en0_x (reg_write_en0[5] ), + .reg_write_en1_x (reg_write_en1[5] ), + .reg_write_en2_x (reg_write_en2[5] ), + .reg_write_en_gate0_x (reg_write_en_gate0[5] ), + .reg_write_en_gate1_x (reg_write_en_gate1[5] ), + .reg_write_en_gate2_x (reg_write_en_gate2[5] ), + .reg_write_is0_x (reg_write_is0[5] ), + .reg_write_is_gate0_x (reg_write_is_gate0[5] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[6]/); @75 +// &ConnRule(s/_y$/_6/); @76 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_6"); @77 +pa_idu_reg32 x_pa_idu_reg32_6 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_6 ), + .reg_dout_y (reg_dout_6 ), + .reg_fwd_en0_x (reg_fwd_en0[6] ), + .reg_fwd_en1_x (reg_fwd_en1[6] ), + .reg_fwd_en2_x (reg_fwd_en2[6] ), + .reg_write_en0_x (reg_write_en0[6] ), + .reg_write_en1_x (reg_write_en1[6] ), + .reg_write_en2_x (reg_write_en2[6] ), + .reg_write_en_gate0_x (reg_write_en_gate0[6] ), + .reg_write_en_gate1_x (reg_write_en_gate1[6] ), + .reg_write_en_gate2_x (reg_write_en_gate2[6] ), + .reg_write_is0_x (reg_write_is0[6] ), + .reg_write_is_gate0_x (reg_write_is_gate0[6] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[7]/); @79 +// &ConnRule(s/_y$/_7/); @80 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_7"); @81 +pa_idu_reg32 x_pa_idu_reg32_7 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_7 ), + .reg_dout_y (reg_dout_7 ), + .reg_fwd_en0_x (reg_fwd_en0[7] ), + .reg_fwd_en1_x (reg_fwd_en1[7] ), + .reg_fwd_en2_x (reg_fwd_en2[7] ), + .reg_write_en0_x (reg_write_en0[7] ), + .reg_write_en1_x (reg_write_en1[7] ), + .reg_write_en2_x (reg_write_en2[7] ), + .reg_write_en_gate0_x (reg_write_en_gate0[7] ), + .reg_write_en_gate1_x (reg_write_en_gate1[7] ), + .reg_write_en_gate2_x (reg_write_en_gate2[7] ), + .reg_write_is0_x (reg_write_is0[7] ), + .reg_write_is_gate0_x (reg_write_is_gate0[7] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[8]/); @83 +// &ConnRule(s/_y$/_8/); @84 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_8"); @85 +pa_idu_reg32 x_pa_idu_reg32_8 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_8 ), + .reg_dout_y (reg_dout_8 ), + .reg_fwd_en0_x (reg_fwd_en0[8] ), + .reg_fwd_en1_x (reg_fwd_en1[8] ), + .reg_fwd_en2_x (reg_fwd_en2[8] ), + .reg_write_en0_x (reg_write_en0[8] ), + .reg_write_en1_x (reg_write_en1[8] ), + .reg_write_en2_x (reg_write_en2[8] ), + .reg_write_en_gate0_x (reg_write_en_gate0[8] ), + .reg_write_en_gate1_x (reg_write_en_gate1[8] ), + .reg_write_en_gate2_x (reg_write_en_gate2[8] ), + .reg_write_is0_x (reg_write_is0[8] ), + .reg_write_is_gate0_x (reg_write_is_gate0[8] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[9]/); @87 +// &ConnRule(s/_y$/_9/); @88 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_9"); @89 +pa_idu_reg32 x_pa_idu_reg32_9 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_9 ), + .reg_dout_y (reg_dout_9 ), + .reg_fwd_en0_x (reg_fwd_en0[9] ), + .reg_fwd_en1_x (reg_fwd_en1[9] ), + .reg_fwd_en2_x (reg_fwd_en2[9] ), + .reg_write_en0_x (reg_write_en0[9] ), + .reg_write_en1_x (reg_write_en1[9] ), + .reg_write_en2_x (reg_write_en2[9] ), + .reg_write_en_gate0_x (reg_write_en_gate0[9] ), + .reg_write_en_gate1_x (reg_write_en_gate1[9] ), + .reg_write_en_gate2_x (reg_write_en_gate2[9] ), + .reg_write_is0_x (reg_write_is0[9] ), + .reg_write_is_gate0_x (reg_write_is_gate0[9] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[10]/); @91 +// &ConnRule(s/_y$/_10/); @92 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_10"); @93 +pa_idu_reg32 x_pa_idu_reg32_10 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_10 ), + .reg_dout_y (reg_dout_10 ), + .reg_fwd_en0_x (reg_fwd_en0[10] ), + .reg_fwd_en1_x (reg_fwd_en1[10] ), + .reg_fwd_en2_x (reg_fwd_en2[10] ), + .reg_write_en0_x (reg_write_en0[10] ), + .reg_write_en1_x (reg_write_en1[10] ), + .reg_write_en2_x (reg_write_en2[10] ), + .reg_write_en_gate0_x (reg_write_en_gate0[10] ), + .reg_write_en_gate1_x (reg_write_en_gate1[10] ), + .reg_write_en_gate2_x (reg_write_en_gate2[10] ), + .reg_write_is0_x (reg_write_is0[10] ), + .reg_write_is_gate0_x (reg_write_is_gate0[10] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[11]/); @95 +// &ConnRule(s/_y$/_11/); @96 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_11"); @97 +pa_idu_reg32 x_pa_idu_reg32_11 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_11 ), + .reg_dout_y (reg_dout_11 ), + .reg_fwd_en0_x (reg_fwd_en0[11] ), + .reg_fwd_en1_x (reg_fwd_en1[11] ), + .reg_fwd_en2_x (reg_fwd_en2[11] ), + .reg_write_en0_x (reg_write_en0[11] ), + .reg_write_en1_x (reg_write_en1[11] ), + .reg_write_en2_x (reg_write_en2[11] ), + .reg_write_en_gate0_x (reg_write_en_gate0[11] ), + .reg_write_en_gate1_x (reg_write_en_gate1[11] ), + .reg_write_en_gate2_x (reg_write_en_gate2[11] ), + .reg_write_is0_x (reg_write_is0[11] ), + .reg_write_is_gate0_x (reg_write_is_gate0[11] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[12]/); @99 +// &ConnRule(s/_y$/_12/); @100 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_12"); @101 +pa_idu_reg32 x_pa_idu_reg32_12 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_12 ), + .reg_dout_y (reg_dout_12 ), + .reg_fwd_en0_x (reg_fwd_en0[12] ), + .reg_fwd_en1_x (reg_fwd_en1[12] ), + .reg_fwd_en2_x (reg_fwd_en2[12] ), + .reg_write_en0_x (reg_write_en0[12] ), + .reg_write_en1_x (reg_write_en1[12] ), + .reg_write_en2_x (reg_write_en2[12] ), + .reg_write_en_gate0_x (reg_write_en_gate0[12] ), + .reg_write_en_gate1_x (reg_write_en_gate1[12] ), + .reg_write_en_gate2_x (reg_write_en_gate2[12] ), + .reg_write_is0_x (reg_write_is0[12] ), + .reg_write_is_gate0_x (reg_write_is_gate0[12] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[13]/); @103 +// &ConnRule(s/_y$/_13/); @104 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_13"); @105 +pa_idu_reg32 x_pa_idu_reg32_13 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_13 ), + .reg_dout_y (reg_dout_13 ), + .reg_fwd_en0_x (reg_fwd_en0[13] ), + .reg_fwd_en1_x (reg_fwd_en1[13] ), + .reg_fwd_en2_x (reg_fwd_en2[13] ), + .reg_write_en0_x (reg_write_en0[13] ), + .reg_write_en1_x (reg_write_en1[13] ), + .reg_write_en2_x (reg_write_en2[13] ), + .reg_write_en_gate0_x (reg_write_en_gate0[13] ), + .reg_write_en_gate1_x (reg_write_en_gate1[13] ), + .reg_write_en_gate2_x (reg_write_en_gate2[13] ), + .reg_write_is0_x (reg_write_is0[13] ), + .reg_write_is_gate0_x (reg_write_is_gate0[13] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[14]/); @107 +// &ConnRule(s/_y$/_14/); @108 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_14"); @109 +pa_idu_reg32 x_pa_idu_reg32_14 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_14 ), + .reg_dout_y (reg_dout_14 ), + .reg_fwd_en0_x (reg_fwd_en0[14] ), + .reg_fwd_en1_x (reg_fwd_en1[14] ), + .reg_fwd_en2_x (reg_fwd_en2[14] ), + .reg_write_en0_x (reg_write_en0[14] ), + .reg_write_en1_x (reg_write_en1[14] ), + .reg_write_en2_x (reg_write_en2[14] ), + .reg_write_en_gate0_x (reg_write_en_gate0[14] ), + .reg_write_en_gate1_x (reg_write_en_gate1[14] ), + .reg_write_en_gate2_x (reg_write_en_gate2[14] ), + .reg_write_is0_x (reg_write_is0[14] ), + .reg_write_is_gate0_x (reg_write_is_gate0[14] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[15]/); @111 +// &ConnRule(s/_y$/_15/); @112 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_15"); @113 +pa_idu_reg32 x_pa_idu_reg32_15 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_15 ), + .reg_dout_y (reg_dout_15 ), + .reg_fwd_en0_x (reg_fwd_en0[15] ), + .reg_fwd_en1_x (reg_fwd_en1[15] ), + .reg_fwd_en2_x (reg_fwd_en2[15] ), + .reg_write_en0_x (reg_write_en0[15] ), + .reg_write_en1_x (reg_write_en1[15] ), + .reg_write_en2_x (reg_write_en2[15] ), + .reg_write_en_gate0_x (reg_write_en_gate0[15] ), + .reg_write_en_gate1_x (reg_write_en_gate1[15] ), + .reg_write_en_gate2_x (reg_write_en_gate2[15] ), + .reg_write_is0_x (reg_write_is0[15] ), + .reg_write_is_gate0_x (reg_write_is_gate0[15] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[16]/); @115 +// &ConnRule(s/_y$/_16/); @116 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_16"); @117 +pa_idu_reg32 x_pa_idu_reg32_16 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_16 ), + .reg_dout_y (reg_dout_16 ), + .reg_fwd_en0_x (reg_fwd_en0[16] ), + .reg_fwd_en1_x (reg_fwd_en1[16] ), + .reg_fwd_en2_x (reg_fwd_en2[16] ), + .reg_write_en0_x (reg_write_en0[16] ), + .reg_write_en1_x (reg_write_en1[16] ), + .reg_write_en2_x (reg_write_en2[16] ), + .reg_write_en_gate0_x (reg_write_en_gate0[16] ), + .reg_write_en_gate1_x (reg_write_en_gate1[16] ), + .reg_write_en_gate2_x (reg_write_en_gate2[16] ), + .reg_write_is0_x (reg_write_is0[16] ), + .reg_write_is_gate0_x (reg_write_is_gate0[16] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[17]/); @119 +// &ConnRule(s/_y$/_17/); @120 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_17"); @121 +pa_idu_reg32_high x_pa_idu_reg32_high_17 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_17 ), + .reg_dout_y (reg_dout_17 ), + .reg_fwd_en0_x (reg_fwd_en0[17] ), + .reg_fwd_en1_x (reg_fwd_en1[17] ), + .reg_fwd_en2_x (reg_fwd_en2[17] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[17] ), + .reg_write_en1_x (reg_write_en1[17] ), + .reg_write_en2_x (reg_write_en2[17] ), + .reg_write_is0_x (reg_write_is0[17] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[18]/); @123 +// &ConnRule(s/_y$/_18/); @124 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_18"); @125 +pa_idu_reg32_high x_pa_idu_reg32_high_18 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_18 ), + .reg_dout_y (reg_dout_18 ), + .reg_fwd_en0_x (reg_fwd_en0[18] ), + .reg_fwd_en1_x (reg_fwd_en1[18] ), + .reg_fwd_en2_x (reg_fwd_en2[18] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[18] ), + .reg_write_en1_x (reg_write_en1[18] ), + .reg_write_en2_x (reg_write_en2[18] ), + .reg_write_is0_x (reg_write_is0[18] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[19]/); @127 +// &ConnRule(s/_y$/_19/); @128 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_19"); @129 +pa_idu_reg32_high x_pa_idu_reg32_high_19 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_19 ), + .reg_dout_y (reg_dout_19 ), + .reg_fwd_en0_x (reg_fwd_en0[19] ), + .reg_fwd_en1_x (reg_fwd_en1[19] ), + .reg_fwd_en2_x (reg_fwd_en2[19] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[19] ), + .reg_write_en1_x (reg_write_en1[19] ), + .reg_write_en2_x (reg_write_en2[19] ), + .reg_write_is0_x (reg_write_is0[19] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[20]/); @131 +// &ConnRule(s/_y$/_20/); @132 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_20"); @133 +pa_idu_reg32_high x_pa_idu_reg32_high_20 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_20 ), + .reg_dout_y (reg_dout_20 ), + .reg_fwd_en0_x (reg_fwd_en0[20] ), + .reg_fwd_en1_x (reg_fwd_en1[20] ), + .reg_fwd_en2_x (reg_fwd_en2[20] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[20] ), + .reg_write_en1_x (reg_write_en1[20] ), + .reg_write_en2_x (reg_write_en2[20] ), + .reg_write_is0_x (reg_write_is0[20] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[21]/); @135 +// &ConnRule(s/_y$/_21/); @136 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_21"); @137 +pa_idu_reg32_high x_pa_idu_reg32_high_21 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_21 ), + .reg_dout_y (reg_dout_21 ), + .reg_fwd_en0_x (reg_fwd_en0[21] ), + .reg_fwd_en1_x (reg_fwd_en1[21] ), + .reg_fwd_en2_x (reg_fwd_en2[21] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[21] ), + .reg_write_en1_x (reg_write_en1[21] ), + .reg_write_en2_x (reg_write_en2[21] ), + .reg_write_is0_x (reg_write_is0[21] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[22]/); @139 +// &ConnRule(s/_y$/_22/); @140 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_22"); @141 +pa_idu_reg32_high x_pa_idu_reg32_high_22 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_22 ), + .reg_dout_y (reg_dout_22 ), + .reg_fwd_en0_x (reg_fwd_en0[22] ), + .reg_fwd_en1_x (reg_fwd_en1[22] ), + .reg_fwd_en2_x (reg_fwd_en2[22] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[22] ), + .reg_write_en1_x (reg_write_en1[22] ), + .reg_write_en2_x (reg_write_en2[22] ), + .reg_write_is0_x (reg_write_is0[22] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[23]/); @143 +// &ConnRule(s/_y$/_23/); @144 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_23"); @145 +pa_idu_reg32_high x_pa_idu_reg32_high_23 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_23 ), + .reg_dout_y (reg_dout_23 ), + .reg_fwd_en0_x (reg_fwd_en0[23] ), + .reg_fwd_en1_x (reg_fwd_en1[23] ), + .reg_fwd_en2_x (reg_fwd_en2[23] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[23] ), + .reg_write_en1_x (reg_write_en1[23] ), + .reg_write_en2_x (reg_write_en2[23] ), + .reg_write_is0_x (reg_write_is0[23] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[24]/); @147 +// &ConnRule(s/_y$/_24/); @148 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_24"); @149 +pa_idu_reg32_high x_pa_idu_reg32_high_24 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_24 ), + .reg_dout_y (reg_dout_24 ), + .reg_fwd_en0_x (reg_fwd_en0[24] ), + .reg_fwd_en1_x (reg_fwd_en1[24] ), + .reg_fwd_en2_x (reg_fwd_en2[24] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[24] ), + .reg_write_en1_x (reg_write_en1[24] ), + .reg_write_en2_x (reg_write_en2[24] ), + .reg_write_is0_x (reg_write_is0[24] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[25]/); @151 +// &ConnRule(s/_y$/_25/); @152 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_25"); @153 +pa_idu_reg32_high x_pa_idu_reg32_high_25 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_25 ), + .reg_dout_y (reg_dout_25 ), + .reg_fwd_en0_x (reg_fwd_en0[25] ), + .reg_fwd_en1_x (reg_fwd_en1[25] ), + .reg_fwd_en2_x (reg_fwd_en2[25] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[25] ), + .reg_write_en1_x (reg_write_en1[25] ), + .reg_write_en2_x (reg_write_en2[25] ), + .reg_write_is0_x (reg_write_is0[25] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[26]/); @155 +// &ConnRule(s/_y$/_26/); @156 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_26"); @157 +pa_idu_reg32_high x_pa_idu_reg32_high_26 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_26 ), + .reg_dout_y (reg_dout_26 ), + .reg_fwd_en0_x (reg_fwd_en0[26] ), + .reg_fwd_en1_x (reg_fwd_en1[26] ), + .reg_fwd_en2_x (reg_fwd_en2[26] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[26] ), + .reg_write_en1_x (reg_write_en1[26] ), + .reg_write_en2_x (reg_write_en2[26] ), + .reg_write_is0_x (reg_write_is0[26] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[27]/); @159 +// &ConnRule(s/_y$/_27/); @160 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_27"); @161 +pa_idu_reg32_high x_pa_idu_reg32_high_27 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_27 ), + .reg_dout_y (reg_dout_27 ), + .reg_fwd_en0_x (reg_fwd_en0[27] ), + .reg_fwd_en1_x (reg_fwd_en1[27] ), + .reg_fwd_en2_x (reg_fwd_en2[27] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[27] ), + .reg_write_en1_x (reg_write_en1[27] ), + .reg_write_en2_x (reg_write_en2[27] ), + .reg_write_is0_x (reg_write_is0[27] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[28]/); @163 +// &ConnRule(s/_y$/_28/); @164 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_28"); @165 +pa_idu_reg32_high x_pa_idu_reg32_high_28 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_28 ), + .reg_dout_y (reg_dout_28 ), + .reg_fwd_en0_x (reg_fwd_en0[28] ), + .reg_fwd_en1_x (reg_fwd_en1[28] ), + .reg_fwd_en2_x (reg_fwd_en2[28] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[28] ), + .reg_write_en1_x (reg_write_en1[28] ), + .reg_write_en2_x (reg_write_en2[28] ), + .reg_write_is0_x (reg_write_is0[28] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[29]/); @167 +// &ConnRule(s/_y$/_29/); @168 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_29"); @169 +pa_idu_reg32_high x_pa_idu_reg32_high_29 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_29 ), + .reg_dout_y (reg_dout_29 ), + .reg_fwd_en0_x (reg_fwd_en0[29] ), + .reg_fwd_en1_x (reg_fwd_en1[29] ), + .reg_fwd_en2_x (reg_fwd_en2[29] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[29] ), + .reg_write_en1_x (reg_write_en1[29] ), + .reg_write_en2_x (reg_write_en2[29] ), + .reg_write_is0_x (reg_write_is0[29] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[30]/); @171 +// &ConnRule(s/_y$/_30/); @172 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_30"); @173 +pa_idu_reg32_high x_pa_idu_reg32_high_30 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_30 ), + .reg_dout_y (reg_dout_30 ), + .reg_fwd_en0_x (reg_fwd_en0[30] ), + .reg_fwd_en1_x (reg_fwd_en1[30] ), + .reg_fwd_en2_x (reg_fwd_en2[30] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[30] ), + .reg_write_en1_x (reg_write_en1[30] ), + .reg_write_en2_x (reg_write_en2[30] ), + .reg_write_is0_x (reg_write_is0[30] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[31]/); @175 +// &ConnRule(s/_y$/_31/); @176 +// &Instance("pa_idu_reg32_high", "x_pa_idu_reg32_high_31"); @177 +pa_idu_reg32_high x_pa_idu_reg32_high_31 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_31 ), + .reg_dout_y (reg_dout_31 ), + .reg_fwd_en0_x (reg_fwd_en0[31] ), + .reg_fwd_en1_x (reg_fwd_en1[31] ), + .reg_fwd_en2_x (reg_fwd_en2[31] ), + .reg_high_cpuclk (reg_high_cpuclk ), + .reg_write_en0_x (reg_write_en0[31] ), + .reg_write_en1_x (reg_write_en1[31] ), + .reg_write_en2_x (reg_write_en2[31] ), + .reg_write_is0_x (reg_write_is0[31] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[32]/); @179 +// &ConnRule(s/_y$/_32/); @180 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_hint_0"); @181 +pa_idu_reg32 x_pa_idu_reg32_hint_0 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_32 ), + .reg_dout_y (reg_dout_32 ), + .reg_fwd_en0_x (reg_fwd_en0[32] ), + .reg_fwd_en1_x (reg_fwd_en1[32] ), + .reg_fwd_en2_x (reg_fwd_en2[32] ), + .reg_write_en0_x (reg_write_en0[32] ), + .reg_write_en1_x (reg_write_en1[32] ), + .reg_write_en2_x (reg_write_en2[32] ), + .reg_write_en_gate0_x (reg_write_en_gate0[32] ), + .reg_write_en_gate1_x (reg_write_en_gate1[32] ), + .reg_write_en_gate2_x (reg_write_en_gate2[32] ), + .reg_write_is0_x (reg_write_is0[32] ), + .reg_write_is_gate0_x (reg_write_is_gate0[32] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +// &ConnRule(s/_x$/[33]/); @183 +// &ConnRule(s/_y$/_33/); @184 +// &Instance("pa_idu_reg32", "x_pa_idu_reg32_hint_1"); @185 +pa_idu_reg32 x_pa_idu_reg32_hint_1 ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .forever_cpuclk (forever_cpuclk ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .reg_busy_st_y (reg_busy_st_33 ), + .reg_dout_y (reg_dout_33 ), + .reg_fwd_en0_x (reg_fwd_en0[33] ), + .reg_fwd_en1_x (reg_fwd_en1[33] ), + .reg_fwd_en2_x (reg_fwd_en2[33] ), + .reg_write_en0_x (reg_write_en0[33] ), + .reg_write_en1_x (reg_write_en1[33] ), + .reg_write_en2_x (reg_write_en2[33] ), + .reg_write_en_gate0_x (reg_write_en_gate0[33] ), + .reg_write_en_gate1_x (reg_write_en_gate1[33] ), + .reg_write_en_gate2_x (reg_write_en_gate2[33] ), + .reg_write_is0_x (reg_write_is0[33] ), + .reg_write_is_gate0_x (reg_write_is_gate0[33] ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .write_data0 (write_data0 ), + .write_data1 (write_data1 ), + .write_data2 (write_data2 ) +); + + +//----------------------------------------------- +// 2. Two write port +//----------------------------------------------- +assign gpr_sync_rst_b = 1'b1; +assign write_index0[5:0] = rtu_idu_wb0_preg[5:0]; +assign write_data0[31:0] = {32{gpr_sync_rst_b}} & rtu_idu_wb0_data[31:0]; + +// &Force("input", "rtu_idu_wb1_lsu_vld"); @194 +// write index decoder +assign write_index0_sel[4:0] = rtu_idu_wb0_preg[4:0] & {5{rtu_idu_wb0_vld}}; +// &CombBeg; @197 +always @( write_index0_sel[4:0]) +begin + reg_sel0[31:0] = {32{1'b0}}; + case(write_index0_sel[4:0]) + 5'h00 : reg_sel0[0] = 1'b1; + 5'h01 : reg_sel0[1] = 1'b1; + 5'h02 : reg_sel0[2] = 1'b1; + 5'h03 : reg_sel0[3] = 1'b1; + 5'h04 : reg_sel0[4] = 1'b1; + 5'h05 : reg_sel0[5] = 1'b1; + 5'h06 : reg_sel0[6] = 1'b1; + 5'h07 : reg_sel0[7] = 1'b1; + 5'h08 : reg_sel0[8] = 1'b1; + 5'h09 : reg_sel0[9] = 1'b1; + 5'h0a : reg_sel0[10] = 1'b1; + 5'h0b : reg_sel0[11] = 1'b1; + 5'h0c : reg_sel0[12] = 1'b1; + 5'h0d : reg_sel0[13] = 1'b1; + 5'h0e : reg_sel0[14] = 1'b1; + 5'h0f : reg_sel0[15] = 1'b1; + 5'h10 : reg_sel0[16] = 1'b1; + 5'h11 : reg_sel0[17] = 1'b1; + 5'h12 : reg_sel0[18] = 1'b1; + 5'h13 : reg_sel0[19] = 1'b1; + 5'h14 : reg_sel0[20] = 1'b1; + 5'h15 : reg_sel0[21] = 1'b1; + 5'h16 : reg_sel0[22] = 1'b1; + 5'h17 : reg_sel0[23] = 1'b1; + 5'h18 : reg_sel0[24] = 1'b1; + 5'h19 : reg_sel0[25] = 1'b1; + 5'h1a : reg_sel0[26] = 1'b1; + 5'h1b : reg_sel0[27] = 1'b1; + 5'h1c : reg_sel0[28] = 1'b1; + 5'h1d : reg_sel0[29] = 1'b1; + 5'h1e : reg_sel0[30] = 1'b1; + 5'h1f : reg_sel0[31] = 1'b1; + endcase +// &CombEnd; @233 +end + +assign reg_hint_sel0[1:0] = {2{rtu_idu_wb0_preg[5]}} & (2'b1 << write_index0[0]); +assign reg_write_en_hint0[1:0] = reg_hint_sel0[1:0] & {2{rtu_idu_wb0_vld & gpr_sync_rst_b}}; + +assign reg_write_en0[31:0] = reg_sel0[31:0] & {32{rtu_idu_wb0_vld & ~write_index0[5]}} + & {32{gpr_sync_rst_b}}; +assign reg_write_en0[32] = reg_write_en_hint0[0]; +assign reg_write_en0[33] = reg_write_en_hint0[1]; +assign reg_write_en_gate0[33:0] = reg_write_en0[33:0]; + +assign write_index1[5:0] = rtu_idu_wb1_preg[5:0]; +assign write_data1[31:0] = {32{gpr_sync_rst_b}} & rtu_idu_wb1_data[31:0]; + +// write index decoder +// &CombBeg; @248 +always @( write_index1[4:0]) +begin + reg_sel1[31:0] = {32{1'b0}}; + case(write_index1[4:0]) + 5'h00 : reg_sel1[0] = 1'b1; + 5'h01 : reg_sel1[1] = 1'b1; + 5'h02 : reg_sel1[2] = 1'b1; + 5'h03 : reg_sel1[3] = 1'b1; + 5'h04 : reg_sel1[4] = 1'b1; + 5'h05 : reg_sel1[5] = 1'b1; + 5'h06 : reg_sel1[6] = 1'b1; + 5'h07 : reg_sel1[7] = 1'b1; + 5'h08 : reg_sel1[8] = 1'b1; + 5'h09 : reg_sel1[9] = 1'b1; + 5'h0a : reg_sel1[10] = 1'b1; + 5'h0b : reg_sel1[11] = 1'b1; + 5'h0c : reg_sel1[12] = 1'b1; + 5'h0d : reg_sel1[13] = 1'b1; + 5'h0e : reg_sel1[14] = 1'b1; + 5'h0f : reg_sel1[15] = 1'b1; + 5'h10 : reg_sel1[16] = 1'b1; + 5'h11 : reg_sel1[17] = 1'b1; + 5'h12 : reg_sel1[18] = 1'b1; + 5'h13 : reg_sel1[19] = 1'b1; + 5'h14 : reg_sel1[20] = 1'b1; + 5'h15 : reg_sel1[21] = 1'b1; + 5'h16 : reg_sel1[22] = 1'b1; + 5'h17 : reg_sel1[23] = 1'b1; + 5'h18 : reg_sel1[24] = 1'b1; + 5'h19 : reg_sel1[25] = 1'b1; + 5'h1a : reg_sel1[26] = 1'b1; + 5'h1b : reg_sel1[27] = 1'b1; + 5'h1c : reg_sel1[28] = 1'b1; + 5'h1d : reg_sel1[29] = 1'b1; + 5'h1e : reg_sel1[30] = 1'b1; + 5'h1f : reg_sel1[31] = 1'b1; + endcase +// &CombEnd; @284 +end + +assign reg_hint_sel1[1:0] = {2{rtu_idu_wb1_preg[5]}} & (2'b1 << write_index1[0]); +assign reg_write_en_hint1[1:0] = reg_hint_sel1[1:0] & {2{rtu_idu_wb1_vld & gpr_sync_rst_b}}; + +assign reg_write_en1[31:0] = reg_sel1[31:0] & {32{rtu_idu_wb1_vld & ~write_index1[5]}} + & {32{gpr_sync_rst_b}}; +assign reg_write_en1[32] = reg_write_en_hint1[0] & ~hs_gpr_wb_mask; +assign reg_write_en1[33] = reg_write_en_hint1[1] & ~hs_gpr_wb_mask; +assign reg_write_en_gate1[33:0] = reg_write_en1[33:0]; + +assign write_index2[5:0] = rtu_idu_wb2_preg[5:0]; +assign write_data2[31:0] = {32{gpr_sync_rst_b}} & rtu_idu_wb2_data[31:0]; + +// write index decoder +// &CombBeg; @299 +always @( write_index2[4:0]) +begin + reg_sel2[31:0] = {32{1'b0}}; + case(write_index2[4:0]) + 5'h00 : reg_sel2[0] = 1'b1; + 5'h01 : reg_sel2[1] = 1'b1; + 5'h02 : reg_sel2[2] = 1'b1; + 5'h03 : reg_sel2[3] = 1'b1; + 5'h04 : reg_sel2[4] = 1'b1; + 5'h05 : reg_sel2[5] = 1'b1; + 5'h06 : reg_sel2[6] = 1'b1; + 5'h07 : reg_sel2[7] = 1'b1; + 5'h08 : reg_sel2[8] = 1'b1; + 5'h09 : reg_sel2[9] = 1'b1; + 5'h0a : reg_sel2[10] = 1'b1; + 5'h0b : reg_sel2[11] = 1'b1; + 5'h0c : reg_sel2[12] = 1'b1; + 5'h0d : reg_sel2[13] = 1'b1; + 5'h0e : reg_sel2[14] = 1'b1; + 5'h0f : reg_sel2[15] = 1'b1; + 5'h10 : reg_sel2[16] = 1'b1; + 5'h11 : reg_sel2[17] = 1'b1; + 5'h12 : reg_sel2[18] = 1'b1; + 5'h13 : reg_sel2[19] = 1'b1; + 5'h14 : reg_sel2[20] = 1'b1; + 5'h15 : reg_sel2[21] = 1'b1; + 5'h16 : reg_sel2[22] = 1'b1; + 5'h17 : reg_sel2[23] = 1'b1; + 5'h18 : reg_sel2[24] = 1'b1; + 5'h19 : reg_sel2[25] = 1'b1; + 5'h1a : reg_sel2[26] = 1'b1; + 5'h1b : reg_sel2[27] = 1'b1; + 5'h1c : reg_sel2[28] = 1'b1; + 5'h1d : reg_sel2[29] = 1'b1; + 5'h1e : reg_sel2[30] = 1'b1; + 5'h1f : reg_sel2[31] = 1'b1; + endcase +// &CombEnd; @335 +end + +assign reg_write_en2[31:0] = reg_sel2[31:0] & {32{rtu_idu_wb2_vld & ~write_index2[5]}} + & {32{gpr_sync_rst_b}}; +assign reg_write_en2[32] = 1'b0; +assign reg_write_en2[33] = 1'b0; +assign reg_write_en_gate2[33:0] = reg_write_en2[33:0]; + +// for sp auto swap +assign reg_write_en_sp = cp0_idu_sp_wen; +assign reg_write_en_sp_gate = cp0_idu_sp_wen_gate; +assign write_data_sp[31:0] = cp0_idu_sp_wdata[31:0]; + +assign gpr_wb_sp = reg_write_en0[2] | reg_write_en1[2] | reg_write_en2[2]; + +// Write Reg Issue0 +// write issue index decoder +assign reg_issue0_sel[4:0] = ctrl_gpr_id_wr_idx1[4:0] & {5{ctrl_gpr_id_rd1_vld}}; +// &CombBeg; @353 +always @( reg_issue0_sel[4:0]) +begin + reg_issue0[31:0] = {32{1'b0}}; + case(reg_issue0_sel[4:0]) + 5'h00 : reg_issue0[0] = 1'b1; + 5'h01 : reg_issue0[1] = 1'b1; + 5'h02 : reg_issue0[2] = 1'b1; + 5'h03 : reg_issue0[3] = 1'b1; + 5'h04 : reg_issue0[4] = 1'b1; + 5'h05 : reg_issue0[5] = 1'b1; + 5'h06 : reg_issue0[6] = 1'b1; + 5'h07 : reg_issue0[7] = 1'b1; + 5'h08 : reg_issue0[8] = 1'b1; + 5'h09 : reg_issue0[9] = 1'b1; + 5'h0a : reg_issue0[10] = 1'b1; + 5'h0b : reg_issue0[11] = 1'b1; + 5'h0c : reg_issue0[12] = 1'b1; + 5'h0d : reg_issue0[13] = 1'b1; + 5'h0e : reg_issue0[14] = 1'b1; + 5'h0f : reg_issue0[15] = 1'b1; + 5'h10 : reg_issue0[16] = 1'b1; + 5'h11 : reg_issue0[17] = 1'b1; + 5'h12 : reg_issue0[18] = 1'b1; + 5'h13 : reg_issue0[19] = 1'b1; + 5'h14 : reg_issue0[20] = 1'b1; + 5'h15 : reg_issue0[21] = 1'b1; + 5'h16 : reg_issue0[22] = 1'b1; + 5'h17 : reg_issue0[23] = 1'b1; + 5'h18 : reg_issue0[24] = 1'b1; + 5'h19 : reg_issue0[25] = 1'b1; + 5'h1a : reg_issue0[26] = 1'b1; + 5'h1b : reg_issue0[27] = 1'b1; + 5'h1c : reg_issue0[28] = 1'b1; + 5'h1d : reg_issue0[29] = 1'b1; + 5'h1e : reg_issue0[30] = 1'b1; + 5'h1f : reg_issue0[31] = 1'b1; + endcase +// &CombEnd; @389 +end + +assign reg_write_is0[31:0] = {32{ctrl_gpr_wr_issue1 & ~ctrl_gpr_id_wr_idx1[5] & ~hs_gpr_wr_mask}} + & reg_issue0[31:0]; +assign reg_hint_is0[1:0] = {2{ctrl_gpr_id_wr_idx1[5]}} & (2'b1 << ctrl_gpr_id_wr_idx1[0]); +assign reg_write_is0[33:32] = {2{ctrl_gpr_wr_issue1 & ~hs_gpr_wr_mask}} & reg_hint_is0[1:0]; + +assign reg_write_is_gate0[31:0] = {32{ctrl_gpr_id_rd1_vld & ~ctrl_gpr_id_wr_idx1[5] & ~hs_gpr_wr_mask}} + & reg_issue0[31:0]; +assign reg_write_is_gate0[33:32] = {2{ctrl_gpr_id_rd1_vld & ~hs_gpr_wr_mask}} & reg_hint_is0[1:0]; + +// Write Reg Issue1 +// write issue index decoder +//assign reg_issue1_sel[4:0] = ctrl_gpr_id_wr_idx2[4:0] & {5{ctrl_gpr_id_rd2_vld}}; +//&CombBeg; +// reg_issue1[31:0] = {32{1'b0}}; +// case(reg_issue1_sel[4:0]) +// 5'h00 : reg_issue1[0] = 1'b1; +// 5'h01 : reg_issue1[1] = 1'b1; +// 5'h02 : reg_issue1[2] = 1'b1; +// 5'h03 : reg_issue1[3] = 1'b1; +// 5'h04 : reg_issue1[4] = 1'b1; +// 5'h05 : reg_issue1[5] = 1'b1; +// 5'h06 : reg_issue1[6] = 1'b1; +// 5'h07 : reg_issue1[7] = 1'b1; +// 5'h08 : reg_issue1[8] = 1'b1; +// 5'h09 : reg_issue1[9] = 1'b1; +// 5'h0a : reg_issue1[10] = 1'b1; +// 5'h0b : reg_issue1[11] = 1'b1; +// 5'h0c : reg_issue1[12] = 1'b1; +// 5'h0d : reg_issue1[13] = 1'b1; +// 5'h0e : reg_issue1[14] = 1'b1; +// 5'h0f : reg_issue1[15] = 1'b1; +// 5'h10 : reg_issue1[16] = 1'b1; +// 5'h11 : reg_issue1[17] = 1'b1; +// 5'h12 : reg_issue1[18] = 1'b1; +// 5'h13 : reg_issue1[19] = 1'b1; +// 5'h14 : reg_issue1[20] = 1'b1; +// 5'h15 : reg_issue1[21] = 1'b1; +// 5'h16 : reg_issue1[22] = 1'b1; +// 5'h17 : reg_issue1[23] = 1'b1; +// 5'h18 : reg_issue1[24] = 1'b1; +// 5'h19 : reg_issue1[25] = 1'b1; +// 5'h1a : reg_issue1[26] = 1'b1; +// 5'h1b : reg_issue1[27] = 1'b1; +// 5'h1c : reg_issue1[28] = 1'b1; +// 5'h1d : reg_issue1[29] = 1'b1; +// 5'h1e : reg_issue1[30] = 1'b1; +// 5'h1f : reg_issue1[31] = 1'b1; +// endcase +//&CombEnd; +// +//assign reg_write_is1[31:0] = {32{ctrl_gpr_wr_issue2}} & reg_issue1[31:0]; +//assign reg_write_is1[33:32] = 2'b0; +// +//assign reg_write_is_gate1[31:0] = {32{ctrl_gpr_id_rd2_vld}} & reg_issue1[31:0]; +//assign reg_write_is_gate1[33:32] = 2'b0; + +// write index decoder +// &Force("bus", "iu_idu_ex2_fwd_preg0", 5, 0); @448 +assign fpu_fwd0_vld = rtu_idu_wb0_vld & rtu_idu_wb0_fpu_vld; +assign fpu_fwd0_reg[4:0] = rtu_idu_wb0_preg[4:0]; +assign div_fwd_index[4:0] = {5{iu_idu_ex2_fwd_vld0 & iu_idu_ex2_div_vld}} & iu_idu_ex2_fwd_preg0[4:0]; +assign fpu_fwd_index[4:0] = {5{fpu_fwd0_vld}} & fpu_fwd0_reg[4:0]; +// &CombBeg; @458 +always @( div_fwd_index[4:0]) +begin + div_fwd_sel0[31:0] = {32{1'b0}}; + case(div_fwd_index[4:0]) + 5'h00 : div_fwd_sel0[0] = 1'b1; + 5'h01 : div_fwd_sel0[1] = 1'b1; + 5'h02 : div_fwd_sel0[2] = 1'b1; + 5'h03 : div_fwd_sel0[3] = 1'b1; + 5'h04 : div_fwd_sel0[4] = 1'b1; + 5'h05 : div_fwd_sel0[5] = 1'b1; + 5'h06 : div_fwd_sel0[6] = 1'b1; + 5'h07 : div_fwd_sel0[7] = 1'b1; + 5'h08 : div_fwd_sel0[8] = 1'b1; + 5'h09 : div_fwd_sel0[9] = 1'b1; + 5'h0a : div_fwd_sel0[10] = 1'b1; + 5'h0b : div_fwd_sel0[11] = 1'b1; + 5'h0c : div_fwd_sel0[12] = 1'b1; + 5'h0d : div_fwd_sel0[13] = 1'b1; + 5'h0e : div_fwd_sel0[14] = 1'b1; + 5'h0f : div_fwd_sel0[15] = 1'b1; + 5'h10 : div_fwd_sel0[16] = 1'b1; + 5'h11 : div_fwd_sel0[17] = 1'b1; + 5'h12 : div_fwd_sel0[18] = 1'b1; + 5'h13 : div_fwd_sel0[19] = 1'b1; + 5'h14 : div_fwd_sel0[20] = 1'b1; + 5'h15 : div_fwd_sel0[21] = 1'b1; + 5'h16 : div_fwd_sel0[22] = 1'b1; + 5'h17 : div_fwd_sel0[23] = 1'b1; + 5'h18 : div_fwd_sel0[24] = 1'b1; + 5'h19 : div_fwd_sel0[25] = 1'b1; + 5'h1a : div_fwd_sel0[26] = 1'b1; + 5'h1b : div_fwd_sel0[27] = 1'b1; + 5'h1c : div_fwd_sel0[28] = 1'b1; + 5'h1d : div_fwd_sel0[29] = 1'b1; + 5'h1e : div_fwd_sel0[30] = 1'b1; + 5'h1f : div_fwd_sel0[31] = 1'b1; + endcase +// &CombEnd; @494 +end +// &CombBeg; @495 +always @( fpu_fwd_index[4:0]) +begin + fpu_fwd_sel0[31:0] = {32{1'b0}}; + case(fpu_fwd_index[4:0]) + 5'h00 : fpu_fwd_sel0[0] = 1'b1; + 5'h01 : fpu_fwd_sel0[1] = 1'b1; + 5'h02 : fpu_fwd_sel0[2] = 1'b1; + 5'h03 : fpu_fwd_sel0[3] = 1'b1; + 5'h04 : fpu_fwd_sel0[4] = 1'b1; + 5'h05 : fpu_fwd_sel0[5] = 1'b1; + 5'h06 : fpu_fwd_sel0[6] = 1'b1; + 5'h07 : fpu_fwd_sel0[7] = 1'b1; + 5'h08 : fpu_fwd_sel0[8] = 1'b1; + 5'h09 : fpu_fwd_sel0[9] = 1'b1; + 5'h0a : fpu_fwd_sel0[10] = 1'b1; + 5'h0b : fpu_fwd_sel0[11] = 1'b1; + 5'h0c : fpu_fwd_sel0[12] = 1'b1; + 5'h0d : fpu_fwd_sel0[13] = 1'b1; + 5'h0e : fpu_fwd_sel0[14] = 1'b1; + 5'h0f : fpu_fwd_sel0[15] = 1'b1; + 5'h10 : fpu_fwd_sel0[16] = 1'b1; + 5'h11 : fpu_fwd_sel0[17] = 1'b1; + 5'h12 : fpu_fwd_sel0[18] = 1'b1; + 5'h13 : fpu_fwd_sel0[19] = 1'b1; + 5'h14 : fpu_fwd_sel0[20] = 1'b1; + 5'h15 : fpu_fwd_sel0[21] = 1'b1; + 5'h16 : fpu_fwd_sel0[22] = 1'b1; + 5'h17 : fpu_fwd_sel0[23] = 1'b1; + 5'h18 : fpu_fwd_sel0[24] = 1'b1; + 5'h19 : fpu_fwd_sel0[25] = 1'b1; + 5'h1a : fpu_fwd_sel0[26] = 1'b1; + 5'h1b : fpu_fwd_sel0[27] = 1'b1; + 5'h1c : fpu_fwd_sel0[28] = 1'b1; + 5'h1d : fpu_fwd_sel0[29] = 1'b1; + 5'h1e : fpu_fwd_sel0[30] = 1'b1; + 5'h1f : fpu_fwd_sel0[31] = 1'b1; + endcase +// &CombEnd; @531 +end +assign reg_fwd_en0[31:0] = div_fwd_sel0[31:0] & {32{iu_idu_ex2_fwd_vld0 & iu_idu_ex2_div_vld}} + | fpu_fwd_sel0[31:0] & {32{fpu_fwd0_vld}}; +assign reg_fwd_en0[32] = 1'b0; +assign reg_fwd_en0[33] = 1'b0; + +assign fwd_index1_sel[4:0] = lsu_idu_ex2_fwd_preg[4:0] & {5{lsu_idu_ex2_fwd_vld}}; +// &CombBeg; @538 +always @( fwd_index1_sel[4:0]) +begin + reg_fwd_sel1[31:0] = {32{1'b0}}; + case(fwd_index1_sel[4:0]) + 5'h00 : reg_fwd_sel1[0] = 1'b1; + 5'h01 : reg_fwd_sel1[1] = 1'b1; + 5'h02 : reg_fwd_sel1[2] = 1'b1; + 5'h03 : reg_fwd_sel1[3] = 1'b1; + 5'h04 : reg_fwd_sel1[4] = 1'b1; + 5'h05 : reg_fwd_sel1[5] = 1'b1; + 5'h06 : reg_fwd_sel1[6] = 1'b1; + 5'h07 : reg_fwd_sel1[7] = 1'b1; + 5'h08 : reg_fwd_sel1[8] = 1'b1; + 5'h09 : reg_fwd_sel1[9] = 1'b1; + 5'h0a : reg_fwd_sel1[10] = 1'b1; + 5'h0b : reg_fwd_sel1[11] = 1'b1; + 5'h0c : reg_fwd_sel1[12] = 1'b1; + 5'h0d : reg_fwd_sel1[13] = 1'b1; + 5'h0e : reg_fwd_sel1[14] = 1'b1; + 5'h0f : reg_fwd_sel1[15] = 1'b1; + 5'h10 : reg_fwd_sel1[16] = 1'b1; + 5'h11 : reg_fwd_sel1[17] = 1'b1; + 5'h12 : reg_fwd_sel1[18] = 1'b1; + 5'h13 : reg_fwd_sel1[19] = 1'b1; + 5'h14 : reg_fwd_sel1[20] = 1'b1; + 5'h15 : reg_fwd_sel1[21] = 1'b1; + 5'h16 : reg_fwd_sel1[22] = 1'b1; + 5'h17 : reg_fwd_sel1[23] = 1'b1; + 5'h18 : reg_fwd_sel1[24] = 1'b1; + 5'h19 : reg_fwd_sel1[25] = 1'b1; + 5'h1a : reg_fwd_sel1[26] = 1'b1; + 5'h1b : reg_fwd_sel1[27] = 1'b1; + 5'h1c : reg_fwd_sel1[28] = 1'b1; + 5'h1d : reg_fwd_sel1[29] = 1'b1; + 5'h1e : reg_fwd_sel1[30] = 1'b1; + 5'h1f : reg_fwd_sel1[31] = 1'b1; + endcase +// &CombEnd; @574 +end +assign reg_fwd_en1[31:0] = reg_fwd_sel1[31:0] & {32{lsu_idu_ex2_fwd_vld & ~lsu_idu_ex2_fwd_preg[5]}}; +assign reg_fwd_en1[32] = reg_write_en_hint1[0]; +assign reg_fwd_en1[33] = reg_write_en_hint1[1]; + +assign fwd_index2_sel[4:0] = ctrl_gpr_ex1_dst_preg[4:0] & {5{rtu_yy_xx_expt_int & ctrl_gpr_ex1_int_spec}}; +// &CombBeg; @580 +always @( fwd_index2_sel[4:0]) +begin + reg_fwd_sel2[31:0] = {32{1'b0}}; + case(fwd_index2_sel[4:0]) + 5'h00 : reg_fwd_sel2[0] = 1'b1; + 5'h01 : reg_fwd_sel2[1] = 1'b1; + 5'h02 : reg_fwd_sel2[2] = 1'b1; + 5'h03 : reg_fwd_sel2[3] = 1'b1; + 5'h04 : reg_fwd_sel2[4] = 1'b1; + 5'h05 : reg_fwd_sel2[5] = 1'b1; + 5'h06 : reg_fwd_sel2[6] = 1'b1; + 5'h07 : reg_fwd_sel2[7] = 1'b1; + 5'h08 : reg_fwd_sel2[8] = 1'b1; + 5'h09 : reg_fwd_sel2[9] = 1'b1; + 5'h0a : reg_fwd_sel2[10] = 1'b1; + 5'h0b : reg_fwd_sel2[11] = 1'b1; + 5'h0c : reg_fwd_sel2[12] = 1'b1; + 5'h0d : reg_fwd_sel2[13] = 1'b1; + 5'h0e : reg_fwd_sel2[14] = 1'b1; + 5'h0f : reg_fwd_sel2[15] = 1'b1; + 5'h10 : reg_fwd_sel2[16] = 1'b1; + 5'h11 : reg_fwd_sel2[17] = 1'b1; + 5'h12 : reg_fwd_sel2[18] = 1'b1; + 5'h13 : reg_fwd_sel2[19] = 1'b1; + 5'h14 : reg_fwd_sel2[20] = 1'b1; + 5'h15 : reg_fwd_sel2[21] = 1'b1; + 5'h16 : reg_fwd_sel2[22] = 1'b1; + 5'h17 : reg_fwd_sel2[23] = 1'b1; + 5'h18 : reg_fwd_sel2[24] = 1'b1; + 5'h19 : reg_fwd_sel2[25] = 1'b1; + 5'h1a : reg_fwd_sel2[26] = 1'b1; + 5'h1b : reg_fwd_sel2[27] = 1'b1; + 5'h1c : reg_fwd_sel2[28] = 1'b1; + 5'h1d : reg_fwd_sel2[29] = 1'b1; + 5'h1e : reg_fwd_sel2[30] = 1'b1; + 5'h1f : reg_fwd_sel2[31] = 1'b1; + endcase +// &CombEnd; @616 +end +assign reg_fwd_en2[31:0] = reg_fwd_sel2[31:0]; +assign reg_fwd_en2[32] = 1'b0; +assign reg_fwd_en2[33] = 1'b0; + +//----------------------------------------------- +// 3. Three read ports +//----------------------------------------------- +// Read Port 1 for rs1 +// &CombBeg; @625 +always @( reg_dout_4[31:0] + or reg_dout_7[31:0] + or reg_dout_3[31:0] + or reg_dout_30[31:0] + or reg_dout_5[31:0] + or reg_dout_20[31:0] + or reg_dout_22[31:0] + or reg_dout_8[31:0] + or reg_dout_28[31:0] + or reg_dout_27[31:0] + or reg_dout_12[31:0] + or reg_dout_23[31:0] + or reg_dout_19[31:0] + or reg_dout_15[31:0] + or reg_dout_2[31:0] + or reg_dout_6[31:0] + or reg_dout_1[31:0] + or reg_dout_10[31:0] + or reg_dout_26[31:0] + or reg_dout_11[31:0] + or reg_dout_18[31:0] + or reg_dout_17[31:0] + or reg_dout_25[31:0] + or reg_dout_24[31:0] + or decd_gpr_rs1[4:0] + or reg_dout_31[31:0] + or reg_dout_21[31:0] + or reg_dout_16[31:0] + or reg_dout_14[31:0] + or reg_dout_29[31:0] + or reg_dout_9[31:0] + or reg_dout_13[31:0]) +begin + case(decd_gpr_rs1[4:0]) + 5'h00 : gpr_read_data1[31:0] = {32{1'b0}}; + 5'h01 : gpr_read_data1[31:0] = reg_dout_1[31:0]; + 5'h02 : gpr_read_data1[31:0] = reg_dout_2[31:0]; + 5'h03 : gpr_read_data1[31:0] = reg_dout_3[31:0]; + 5'h04 : gpr_read_data1[31:0] = reg_dout_4[31:0]; + 5'h05 : gpr_read_data1[31:0] = reg_dout_5[31:0]; + 5'h06 : gpr_read_data1[31:0] = reg_dout_6[31:0]; + 5'h07 : gpr_read_data1[31:0] = reg_dout_7[31:0]; + 5'h08 : gpr_read_data1[31:0] = reg_dout_8[31:0]; + 5'h09 : gpr_read_data1[31:0] = reg_dout_9[31:0]; + 5'h0a : gpr_read_data1[31:0] = reg_dout_10[31:0]; + 5'h0b : gpr_read_data1[31:0] = reg_dout_11[31:0]; + 5'h0c : gpr_read_data1[31:0] = reg_dout_12[31:0]; + 5'h0d : gpr_read_data1[31:0] = reg_dout_13[31:0]; + 5'h0e : gpr_read_data1[31:0] = reg_dout_14[31:0]; + 5'h0f : gpr_read_data1[31:0] = reg_dout_15[31:0]; + 5'h10 : gpr_read_data1[31:0] = reg_dout_16[31:0]; + 5'h11 : gpr_read_data1[31:0] = reg_dout_17[31:0]; + 5'h12 : gpr_read_data1[31:0] = reg_dout_18[31:0]; + 5'h13 : gpr_read_data1[31:0] = reg_dout_19[31:0]; + 5'h14 : gpr_read_data1[31:0] = reg_dout_20[31:0]; + 5'h15 : gpr_read_data1[31:0] = reg_dout_21[31:0]; + 5'h16 : gpr_read_data1[31:0] = reg_dout_22[31:0]; + 5'h17 : gpr_read_data1[31:0] = reg_dout_23[31:0]; + 5'h18 : gpr_read_data1[31:0] = reg_dout_24[31:0]; + 5'h19 : gpr_read_data1[31:0] = reg_dout_25[31:0]; + 5'h1a : gpr_read_data1[31:0] = reg_dout_26[31:0]; + 5'h1b : gpr_read_data1[31:0] = reg_dout_27[31:0]; + 5'h1c : gpr_read_data1[31:0] = reg_dout_28[31:0]; + 5'h1d : gpr_read_data1[31:0] = reg_dout_29[31:0]; + 5'h1e : gpr_read_data1[31:0] = reg_dout_30[31:0]; + 5'h1f : gpr_read_data1[31:0] = reg_dout_31[31:0]; + default : gpr_read_data1[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @661 +end + +assign hint_read_data1[31:0] = decd_gpr_rs1[0] ? reg_dout_33[31:0] : reg_dout_32[31:0]; + +assign gpr_read_data1_after_hint[31:0] = decd_gpr_rs1[5] ? hint_read_data1[31:0] : gpr_read_data1[31:0]; + +// Read Port 2 for rs2 +// &CombBeg; @668 +always @( reg_dout_4[31:0] + or reg_dout_7[31:0] + or reg_dout_3[31:0] + or reg_dout_30[31:0] + or reg_dout_5[31:0] + or decd_gpr_rs2[4:0] + or reg_dout_20[31:0] + or reg_dout_22[31:0] + or reg_dout_8[31:0] + or reg_dout_28[31:0] + or reg_dout_27[31:0] + or reg_dout_12[31:0] + or reg_dout_23[31:0] + or reg_dout_19[31:0] + or reg_dout_15[31:0] + or reg_dout_2[31:0] + or reg_dout_6[31:0] + or reg_dout_1[31:0] + or reg_dout_10[31:0] + or reg_dout_26[31:0] + or reg_dout_11[31:0] + or reg_dout_18[31:0] + or reg_dout_17[31:0] + or reg_dout_25[31:0] + or reg_dout_24[31:0] + or reg_dout_31[31:0] + or reg_dout_16[31:0] + or reg_dout_21[31:0] + or reg_dout_14[31:0] + or reg_dout_29[31:0] + or reg_dout_9[31:0] + or reg_dout_13[31:0]) +begin + case(decd_gpr_rs2[4:0]) + 5'h00 : gpr_read_data2[31:0] = {32{1'b0}}; + 5'h01 : gpr_read_data2[31:0] = reg_dout_1[31:0]; + 5'h02 : gpr_read_data2[31:0] = reg_dout_2[31:0]; + 5'h03 : gpr_read_data2[31:0] = reg_dout_3[31:0]; + 5'h04 : gpr_read_data2[31:0] = reg_dout_4[31:0]; + 5'h05 : gpr_read_data2[31:0] = reg_dout_5[31:0]; + 5'h06 : gpr_read_data2[31:0] = reg_dout_6[31:0]; + 5'h07 : gpr_read_data2[31:0] = reg_dout_7[31:0]; + 5'h08 : gpr_read_data2[31:0] = reg_dout_8[31:0]; + 5'h09 : gpr_read_data2[31:0] = reg_dout_9[31:0]; + 5'h0a : gpr_read_data2[31:0] = reg_dout_10[31:0]; + 5'h0b : gpr_read_data2[31:0] = reg_dout_11[31:0]; + 5'h0c : gpr_read_data2[31:0] = reg_dout_12[31:0]; + 5'h0d : gpr_read_data2[31:0] = reg_dout_13[31:0]; + 5'h0e : gpr_read_data2[31:0] = reg_dout_14[31:0]; + 5'h0f : gpr_read_data2[31:0] = reg_dout_15[31:0]; + 5'h10 : gpr_read_data2[31:0] = reg_dout_16[31:0]; + 5'h11 : gpr_read_data2[31:0] = reg_dout_17[31:0]; + 5'h12 : gpr_read_data2[31:0] = reg_dout_18[31:0]; + 5'h13 : gpr_read_data2[31:0] = reg_dout_19[31:0]; + 5'h14 : gpr_read_data2[31:0] = reg_dout_20[31:0]; + 5'h15 : gpr_read_data2[31:0] = reg_dout_21[31:0]; + 5'h16 : gpr_read_data2[31:0] = reg_dout_22[31:0]; + 5'h17 : gpr_read_data2[31:0] = reg_dout_23[31:0]; + 5'h18 : gpr_read_data2[31:0] = reg_dout_24[31:0]; + 5'h19 : gpr_read_data2[31:0] = reg_dout_25[31:0]; + 5'h1a : gpr_read_data2[31:0] = reg_dout_26[31:0]; + 5'h1b : gpr_read_data2[31:0] = reg_dout_27[31:0]; + 5'h1c : gpr_read_data2[31:0] = reg_dout_28[31:0]; + 5'h1d : gpr_read_data2[31:0] = reg_dout_29[31:0]; + 5'h1e : gpr_read_data2[31:0] = reg_dout_30[31:0]; + 5'h1f : gpr_read_data2[31:0] = reg_dout_31[31:0]; + default : gpr_read_data2[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @704 +end + +assign hint_read_data2[31:0] = decd_gpr_rs2[0] ? reg_dout_33[31:0] : reg_dout_32[31:0]; + +assign gpr_read_data2_after_hint[31:0] = decd_gpr_rs2[5] ? hint_read_data2[31:0] : gpr_read_data2[31:0]; + +// Read Port 3 for rs3 +// &CombBeg; @711 +always @( reg_dout_4[31:0] + or reg_dout_7[31:0] + or reg_dout_3[31:0] + or reg_dout_30[31:0] + or reg_dout_5[31:0] + or reg_dout_20[31:0] + or reg_dout_22[31:0] + or reg_dout_8[31:0] + or reg_dout_28[31:0] + or reg_dout_27[31:0] + or reg_dout_12[31:0] + or reg_dout_23[31:0] + or reg_dout_19[31:0] + or reg_dout_15[31:0] + or reg_dout_2[31:0] + or reg_dout_6[31:0] + or reg_dout_1[31:0] + or reg_dout_10[31:0] + or reg_dout_26[31:0] + or decd_gpr_rs3[4:0] + or reg_dout_11[31:0] + or reg_dout_18[31:0] + or reg_dout_17[31:0] + or reg_dout_25[31:0] + or reg_dout_24[31:0] + or reg_dout_31[31:0] + or reg_dout_16[31:0] + or reg_dout_21[31:0] + or reg_dout_14[31:0] + or reg_dout_29[31:0] + or reg_dout_9[31:0] + or reg_dout_13[31:0]) +begin + case(decd_gpr_rs3[4:0]) + 5'h00 : gpr_read_data3[31:0] = {32{1'b0}}; + 5'h01 : gpr_read_data3[31:0] = reg_dout_1[31:0]; + 5'h02 : gpr_read_data3[31:0] = reg_dout_2[31:0]; + 5'h03 : gpr_read_data3[31:0] = reg_dout_3[31:0]; + 5'h04 : gpr_read_data3[31:0] = reg_dout_4[31:0]; + 5'h05 : gpr_read_data3[31:0] = reg_dout_5[31:0]; + 5'h06 : gpr_read_data3[31:0] = reg_dout_6[31:0]; + 5'h07 : gpr_read_data3[31:0] = reg_dout_7[31:0]; + 5'h08 : gpr_read_data3[31:0] = reg_dout_8[31:0]; + 5'h09 : gpr_read_data3[31:0] = reg_dout_9[31:0]; + 5'h0a : gpr_read_data3[31:0] = reg_dout_10[31:0]; + 5'h0b : gpr_read_data3[31:0] = reg_dout_11[31:0]; + 5'h0c : gpr_read_data3[31:0] = reg_dout_12[31:0]; + 5'h0d : gpr_read_data3[31:0] = reg_dout_13[31:0]; + 5'h0e : gpr_read_data3[31:0] = reg_dout_14[31:0]; + 5'h0f : gpr_read_data3[31:0] = reg_dout_15[31:0]; + 5'h10 : gpr_read_data3[31:0] = reg_dout_16[31:0]; + 5'h11 : gpr_read_data3[31:0] = reg_dout_17[31:0]; + 5'h12 : gpr_read_data3[31:0] = reg_dout_18[31:0]; + 5'h13 : gpr_read_data3[31:0] = reg_dout_19[31:0]; + 5'h14 : gpr_read_data3[31:0] = reg_dout_20[31:0]; + 5'h15 : gpr_read_data3[31:0] = reg_dout_21[31:0]; + 5'h16 : gpr_read_data3[31:0] = reg_dout_22[31:0]; + 5'h17 : gpr_read_data3[31:0] = reg_dout_23[31:0]; + 5'h18 : gpr_read_data3[31:0] = reg_dout_24[31:0]; + 5'h19 : gpr_read_data3[31:0] = reg_dout_25[31:0]; + 5'h1a : gpr_read_data3[31:0] = reg_dout_26[31:0]; + 5'h1b : gpr_read_data3[31:0] = reg_dout_27[31:0]; + 5'h1c : gpr_read_data3[31:0] = reg_dout_28[31:0]; + 5'h1d : gpr_read_data3[31:0] = reg_dout_29[31:0]; + 5'h1e : gpr_read_data3[31:0] = reg_dout_30[31:0]; + 5'h1f : gpr_read_data3[31:0] = reg_dout_31[31:0]; + default : gpr_read_data3[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @747 +end + +// Read Port 4 for rs4 +// &CombBeg; @750 +always @( reg_dout_4[31:0] + or reg_dout_7[31:0] + or reg_dout_3[31:0] + or reg_dout_30[31:0] + or reg_dout_5[31:0] + or reg_dout_20[31:0] + or reg_dout_22[31:0] + or reg_dout_8[31:0] + or reg_dout_28[31:0] + or reg_dout_27[31:0] + or reg_dout_12[31:0] + or reg_dout_23[31:0] + or reg_dout_19[31:0] + or reg_dout_15[31:0] + or decd_gpr_rs4[4:0] + or reg_dout_2[31:0] + or reg_dout_6[31:0] + or reg_dout_1[31:0] + or reg_dout_10[31:0] + or reg_dout_26[31:0] + or reg_dout_11[31:0] + or reg_dout_18[31:0] + or reg_dout_17[31:0] + or reg_dout_25[31:0] + or reg_dout_24[31:0] + or reg_dout_31[31:0] + or reg_dout_16[31:0] + or reg_dout_21[31:0] + or reg_dout_14[31:0] + or reg_dout_29[31:0] + or reg_dout_9[31:0] + or reg_dout_13[31:0]) +begin + case(decd_gpr_rs4[4:0]) + 5'h00 : gpr_read_data4[31:0] = {32{1'b0}}; + 5'h01 : gpr_read_data4[31:0] = reg_dout_1[31:0]; + 5'h02 : gpr_read_data4[31:0] = reg_dout_2[31:0]; + 5'h03 : gpr_read_data4[31:0] = reg_dout_3[31:0]; + 5'h04 : gpr_read_data4[31:0] = reg_dout_4[31:0]; + 5'h05 : gpr_read_data4[31:0] = reg_dout_5[31:0]; + 5'h06 : gpr_read_data4[31:0] = reg_dout_6[31:0]; + 5'h07 : gpr_read_data4[31:0] = reg_dout_7[31:0]; + 5'h08 : gpr_read_data4[31:0] = reg_dout_8[31:0]; + 5'h09 : gpr_read_data4[31:0] = reg_dout_9[31:0]; + 5'h0a : gpr_read_data4[31:0] = reg_dout_10[31:0]; + 5'h0b : gpr_read_data4[31:0] = reg_dout_11[31:0]; + 5'h0c : gpr_read_data4[31:0] = reg_dout_12[31:0]; + 5'h0d : gpr_read_data4[31:0] = reg_dout_13[31:0]; + 5'h0e : gpr_read_data4[31:0] = reg_dout_14[31:0]; + 5'h0f : gpr_read_data4[31:0] = reg_dout_15[31:0]; + 5'h10 : gpr_read_data4[31:0] = reg_dout_16[31:0]; + 5'h11 : gpr_read_data4[31:0] = reg_dout_17[31:0]; + 5'h12 : gpr_read_data4[31:0] = reg_dout_18[31:0]; + 5'h13 : gpr_read_data4[31:0] = reg_dout_19[31:0]; + 5'h14 : gpr_read_data4[31:0] = reg_dout_20[31:0]; + 5'h15 : gpr_read_data4[31:0] = reg_dout_21[31:0]; + 5'h16 : gpr_read_data4[31:0] = reg_dout_22[31:0]; + 5'h17 : gpr_read_data4[31:0] = reg_dout_23[31:0]; + 5'h18 : gpr_read_data4[31:0] = reg_dout_24[31:0]; + 5'h19 : gpr_read_data4[31:0] = reg_dout_25[31:0]; + 5'h1a : gpr_read_data4[31:0] = reg_dout_26[31:0]; + 5'h1b : gpr_read_data4[31:0] = reg_dout_27[31:0]; + 5'h1c : gpr_read_data4[31:0] = reg_dout_28[31:0]; + 5'h1d : gpr_read_data4[31:0] = reg_dout_29[31:0]; + 5'h1e : gpr_read_data4[31:0] = reg_dout_30[31:0]; + 5'h1f : gpr_read_data4[31:0] = reg_dout_31[31:0]; + default : gpr_read_data4[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @786 +end + +//assign gpr_rs1_dep_wb_lsu = decd_gpr_rs1[5:0] == write_index1[5:0] +// & decd_gpr_rs1[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +//assign gpr_rs2_dep_wb_lsu = decd_gpr_rs2[5:0] == write_index1[5:0] +// & decd_gpr_rs2[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +//assign gpr_rs3_dep_wb_lsu = decd_gpr_rs3[5:0] == write_index1[5:0] +// & decd_gpr_rs3[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +//assign gpr_rs4_dep_wb_lsu = decd_gpr_rs4[5:0] == write_index1[5:0] +// & decd_gpr_rs4[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +// +//assign gpr_rs1_dep_wb_rbus = decd_gpr_rs1[5:0] == rtu_idu_wb0_preg[5:0] +// & decd_gpr_rs1[5:0] != 6'b0 +// & rtu_idu_wb0_vld; +//assign gpr_rs2_dep_wb_rbus = decd_gpr_rs2[5:0] == rtu_idu_wb0_preg[5:0] +// & decd_gpr_rs2[5:0] != 6'b0 +// & rtu_idu_wb0_vld; +//assign gpr_rs3_dep_wb_rbus = decd_gpr_rs3[5:0] == rtu_idu_wb0_preg[5:0] +// & decd_gpr_rs3[5:0] != 6'b0 +// & rtu_idu_wb0_vld; +//assign gpr_rs4_dep_wb_rbus = decd_gpr_rs4[5:0] == rtu_idu_wb0_preg[5:0] +// & decd_gpr_rs4[5:0] != 6'b0 +// & rtu_idu_wb0_vld; +// +//assign gpr_rs1_dep_wb = gpr_rs1_dep_wb_lsu | gpr_rs1_dep_wb_rbus; +//assign gpr_rs2_dep_wb = gpr_rs2_dep_wb_lsu | gpr_rs2_dep_wb_rbus; +//assign gpr_rs3_dep_wb = gpr_rs3_dep_wb_lsu | gpr_rs3_dep_wb_rbus; +//assign gpr_rs4_dep_wb = gpr_rs3_dep_wb_lsu | gpr_rs4_dep_wb_rbus; + + +//----------------------------------------------- +// 4. Reg Busy Judge +//----------------------------------------------- +parameter IDLE = 3'b000; +parameter BUSY1 = 3'b001; +parameter BUSY_LSU1 = 3'b010; +parameter BUSY_DIV1 = 3'b011; +parameter BUSY2 = 3'b100; +parameter BUSY_LSU2 = 3'b110; +parameter BUSY_DIV2 = 3'b111; + +// &CombBeg; @831 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or decd_gpr_dep_rs1[5:0] + or reg_busy_st_21[2:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(decd_gpr_dep_rs1[5:0]) + 6'h00 : gpr_rs1_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rs1_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rs1_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rs1_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rs1_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rs1_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rs1_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rs1_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rs1_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rs1_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rs1_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rs1_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rs1_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rs1_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rs1_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rs1_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rs1_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rs1_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rs1_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rs1_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rs1_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rs1_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rs1_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rs1_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rs1_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rs1_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rs1_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rs1_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rs1_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rs1_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rs1_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rs1_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rs1_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rs1_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rs1_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @869 +end + +// &CombBeg; @871 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or reg_busy_st_21[2:0] + or decd_gpr_dep_rs2[5:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(decd_gpr_dep_rs2[5:0]) + 6'h00 : gpr_rs2_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rs2_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rs2_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rs2_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rs2_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rs2_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rs2_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rs2_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rs2_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rs2_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rs2_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rs2_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rs2_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rs2_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rs2_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rs2_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rs2_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rs2_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rs2_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rs2_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rs2_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rs2_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rs2_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rs2_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rs2_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rs2_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rs2_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rs2_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rs2_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rs2_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rs2_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rs2_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rs2_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rs2_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rs2_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @909 +end + +// &CombBeg; @911 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or reg_busy_st_21[2:0] + or decd_gpr_rs3[5:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(decd_gpr_rs3[5:0]) + 6'h00 : gpr_rs3_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rs3_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rs3_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rs3_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rs3_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rs3_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rs3_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rs3_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rs3_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rs3_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rs3_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rs3_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rs3_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rs3_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rs3_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rs3_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rs3_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rs3_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rs3_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rs3_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rs3_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rs3_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rs3_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rs3_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rs3_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rs3_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rs3_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rs3_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rs3_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rs3_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rs3_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rs3_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rs3_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rs3_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rs3_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @949 +end + +// &CombBeg; @951 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or reg_busy_st_21[2:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or decd_gpr_rs4[5:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(decd_gpr_rs4[5:0]) + 6'h00 : gpr_rs4_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rs4_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rs4_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rs4_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rs4_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rs4_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rs4_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rs4_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rs4_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rs4_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rs4_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rs4_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rs4_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rs4_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rs4_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rs4_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rs4_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rs4_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rs4_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rs4_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rs4_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rs4_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rs4_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rs4_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rs4_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rs4_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rs4_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rs4_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rs4_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rs4_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rs4_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rs4_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rs4_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rs4_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rs4_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @989 +end + +// &CombBeg; @991 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or reg_busy_st_21[2:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or ctrl_gpr_id_wr_idx1[5:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(ctrl_gpr_id_wr_idx1[5:0]) + 6'h00 : gpr_rd1_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rd1_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rd1_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rd1_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rd1_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rd1_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rd1_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rd1_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rd1_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rd1_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rd1_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rd1_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rd1_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rd1_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rd1_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rd1_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rd1_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rd1_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rd1_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rd1_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rd1_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rd1_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rd1_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rd1_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rd1_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rd1_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rd1_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rd1_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rd1_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rd1_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rd1_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rd1_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rd1_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rd1_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rd1_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @1029 +end + +// &CombBeg; @1031 +always @( reg_busy_st_19[2:0] + or reg_busy_st_31[2:0] + or reg_busy_st_9[2:0] + or reg_busy_st_21[2:0] + or reg_busy_st_16[2:0] + or reg_busy_st_14[2:0] + or reg_busy_st_33[2:0] + or reg_busy_st_25[2:0] + or reg_busy_st_15[2:0] + or reg_busy_st_26[2:0] + or reg_busy_st_20[2:0] + or reg_busy_st_17[2:0] + or reg_busy_st_1[2:0] + or reg_busy_st_32[2:0] + or reg_busy_st_18[2:0] + or reg_busy_st_5[2:0] + or reg_busy_st_22[2:0] + or reg_busy_st_27[2:0] + or reg_busy_st_29[2:0] + or reg_busy_st_13[2:0] + or ctrl_gpr_id_wr_idx2[5:0] + or reg_busy_st_24[2:0] + or reg_busy_st_23[2:0] + or reg_busy_st_2[2:0] + or reg_busy_st_30[2:0] + or reg_busy_st_7[2:0] + or reg_busy_st_6[2:0] + or reg_busy_st_28[2:0] + or reg_busy_st_10[2:0] + or reg_busy_st_11[2:0] + or reg_busy_st_8[2:0] + or reg_busy_st_3[2:0] + or reg_busy_st_4[2:0] + or reg_busy_st_12[2:0]) +begin +case(ctrl_gpr_id_wr_idx2[5:0]) + 6'h00 : gpr_rd2_busy_st[2:0] = {3{1'b0}}; + 6'h01 : gpr_rd2_busy_st[2:0] = reg_busy_st_1[2:0]; + 6'h02 : gpr_rd2_busy_st[2:0] = reg_busy_st_2[2:0]; + 6'h03 : gpr_rd2_busy_st[2:0] = reg_busy_st_3[2:0]; + 6'h04 : gpr_rd2_busy_st[2:0] = reg_busy_st_4[2:0]; + 6'h05 : gpr_rd2_busy_st[2:0] = reg_busy_st_5[2:0]; + 6'h06 : gpr_rd2_busy_st[2:0] = reg_busy_st_6[2:0]; + 6'h07 : gpr_rd2_busy_st[2:0] = reg_busy_st_7[2:0]; + 6'h08 : gpr_rd2_busy_st[2:0] = reg_busy_st_8[2:0]; + 6'h09 : gpr_rd2_busy_st[2:0] = reg_busy_st_9[2:0]; + 6'h0a : gpr_rd2_busy_st[2:0] = reg_busy_st_10[2:0]; + 6'h0b : gpr_rd2_busy_st[2:0] = reg_busy_st_11[2:0]; + 6'h0c : gpr_rd2_busy_st[2:0] = reg_busy_st_12[2:0]; + 6'h0d : gpr_rd2_busy_st[2:0] = reg_busy_st_13[2:0]; + 6'h0e : gpr_rd2_busy_st[2:0] = reg_busy_st_14[2:0]; + 6'h0f : gpr_rd2_busy_st[2:0] = reg_busy_st_15[2:0]; + 6'h10 : gpr_rd2_busy_st[2:0] = reg_busy_st_16[2:0]; + 6'h11 : gpr_rd2_busy_st[2:0] = reg_busy_st_17[2:0]; + 6'h12 : gpr_rd2_busy_st[2:0] = reg_busy_st_18[2:0]; + 6'h13 : gpr_rd2_busy_st[2:0] = reg_busy_st_19[2:0]; + 6'h14 : gpr_rd2_busy_st[2:0] = reg_busy_st_20[2:0]; + 6'h15 : gpr_rd2_busy_st[2:0] = reg_busy_st_21[2:0]; + 6'h16 : gpr_rd2_busy_st[2:0] = reg_busy_st_22[2:0]; + 6'h17 : gpr_rd2_busy_st[2:0] = reg_busy_st_23[2:0]; + 6'h18 : gpr_rd2_busy_st[2:0] = reg_busy_st_24[2:0]; + 6'h19 : gpr_rd2_busy_st[2:0] = reg_busy_st_25[2:0]; + 6'h1a : gpr_rd2_busy_st[2:0] = reg_busy_st_26[2:0]; + 6'h1b : gpr_rd2_busy_st[2:0] = reg_busy_st_27[2:0]; + 6'h1c : gpr_rd2_busy_st[2:0] = reg_busy_st_28[2:0]; + 6'h1d : gpr_rd2_busy_st[2:0] = reg_busy_st_29[2:0]; + 6'h1e : gpr_rd2_busy_st[2:0] = reg_busy_st_30[2:0]; + 6'h1f : gpr_rd2_busy_st[2:0] = reg_busy_st_31[2:0]; + 6'h20 : gpr_rd2_busy_st[2:0] = reg_busy_st_32[2:0]; + 6'h21 : gpr_rd2_busy_st[2:0] = reg_busy_st_33[2:0]; + default : gpr_rd2_busy_st[2:0] = {3{1'bx}}; +endcase +// &CombEnd; @1069 +end + +assign gpr_rd1_fwd_lsu = ctrl_gpr_id_wr_idx1[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & ctrl_gpr_id_wr_idx1[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld; +assign gpr_rd2_fwd_lsu = ctrl_gpr_id_wr_idx2[5:0] == lsu_idu_ex2_fwd_preg[5:0] + & ctrl_gpr_id_wr_idx2[5:0] != 6'b0 + & lsu_idu_ex2_fwd_vld; +//assign gpr_rd1_fwd_rbus = ctrl_gpr_id_wr_idx1[5:0] == iu_idu_ex2_fwd_preg0[5:0] +// & ctrl_gpr_id_wr_idx1[5:0] != 6'b0 +// & iu_idu_ex2_fwd_vld0; +//assign gpr_rd2_fwd_rbus = ctrl_gpr_id_wr_idx2[5:0] == iu_idu_ex2_fwd_preg0[5:0] +// & ctrl_gpr_id_wr_idx2[5:0] != 6'b0 +// & iu_idu_ex2_fwd_vld0; +//assign gpr_rd1_hit_wb_lsu = ctrl_gpr_id_wr_idx1[5:0] == write_index1[5:0] +// & ctrl_gpr_id_wr_idx1[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +//assign gpr_rd1_hit_wb_rbus = ctrl_gpr_id_wr_idx1[5:0] == write_index0[5:0] +// & ctrl_gpr_id_wr_idx1[5:0] != 6'b0 +// & rtu_idu_wb0_vld; +//assign gpr_rd2_hit_wb_lsu = ctrl_gpr_id_wr_idx2[5:0] == write_index1[5:0] +// & ctrl_gpr_id_wr_idx2[5:0] != 6'b0 +// & rtu_idu_wb1_vld; +//assign gpr_rd2_hit_wb_rbus = ctrl_gpr_id_wr_idx2[5:0] == write_index0[5:0] +// & ctrl_gpr_id_wr_idx2[5:0] != 6'b0 +// & rtu_idu_wb0_vld; + +//assign gpr_rs1_busy = gpr_rs1_busy_st[2:0] == BUSY1 & ~gpr_rs1_dep_wb & ~dp_gpr_rs1_fwd +// | gpr_rs1_busy_st[2:0] == BUSY2 & ~gpr_rs1_dep_wb & ~dp_gpr_rs1_fwd; +//assign gpr_rs2_busy = gpr_rs2_busy_st[2:0] == BUSY1 & ~gpr_rs2_dep_wb & ~dp_gpr_rs2_fwd +// | gpr_rs2_busy_st[2:0] == BUSY2 & ~gpr_rs2_dep_wb & ~dp_gpr_rs2_fwd; +//assign gpr_rs3_busy = gpr_rs3_busy_st[2:0] == BUSY1 & ~gpr_rs3_dep_wb & ~dp_gpr_rs3_fwd +// | gpr_rs3_busy_st[2:0] == BUSY2 & ~gpr_rs3_dep_wb & ~dp_gpr_rs3_fwd; +//assign gpr_rs4_busy = gpr_rs4_busy_st[2:0] == BUSY1 & ~gpr_rs4_dep_wb & ~dp_gpr_rs4_fwd +// | gpr_rs4_busy_st[2:0] == BUSY2 & ~gpr_rs4_dep_wb & ~dp_gpr_rs4_fwd; +//assign gpr_rd1_busy = gpr_rd1_busy_st[2:0] == BUSY2 & ~gpr_rd1_fwd_rbus; +//assign gpr_rd2_busy = gpr_rd2_busy_st[2:0] == BUSY2 & ~gpr_rd2_fwd_rbus; + +assign gpr_rs1_busy_lsu = gpr_rs1_busy_st[2:0] == BUSY_LSU1 & ~dp_gpr_rs1_fwd_lsu + | gpr_rs1_busy_st[2:0] == BUSY_LSU2; +assign gpr_rs2_busy_lsu = gpr_rs2_busy_st[2:0] == BUSY_LSU1 & ~dp_gpr_rs2_fwd_lsu + | gpr_rs2_busy_st[2:0] == BUSY_LSU2; +assign gpr_rs3_busy_lsu = gpr_rs3_busy_st[2:0] == BUSY_LSU1 & ~dp_gpr_rs3_fwd_lsu + | gpr_rs3_busy_st[2:0] == BUSY_LSU2; +assign gpr_rs4_busy_lsu = gpr_rs4_busy_st[2:0] == BUSY_LSU1 & ~dp_gpr_rs4_fwd_lsu + | gpr_rs4_busy_st[2:0] == BUSY_LSU2; +assign gpr_rd1_busy_lsu = gpr_rd1_busy_st[2:0] == BUSY_LSU1 & ~ctrl_gpr_ld_inst & ~gpr_rd1_fwd_lsu + | gpr_rd1_busy_st[2:0] == BUSY_LSU2 & ~(ctrl_gpr_ld_inst & gpr_rd1_fwd_lsu); +assign gpr_rd2_busy_lsu = gpr_rd2_busy_st[2:0] == BUSY_LSU1 & ~ctrl_gpr_ld_inst & ~gpr_rd2_fwd_lsu + | gpr_rd2_busy_st[2:0] == BUSY_LSU2 & ~(ctrl_gpr_ld_inst & gpr_rd2_fwd_lsu); + +assign gpr_rs1_fwd_div[31:0] = reg_fwd_en0[31:0] >> decd_gpr_rs1[4:0]; +assign gpr_rs2_fwd_div[31:0] = reg_fwd_en0[31:0] >> decd_gpr_rs2[4:0]; +assign gpr_rs3_fwd_div[31:0] = reg_fwd_en0[31:0] >> decd_gpr_rs3[4:0]; +assign gpr_rs4_fwd_div[31:0] = reg_fwd_en0[31:0] >> decd_gpr_rs4[4:0]; +assign gpr_rd1_fwd_div[31:0] = reg_fwd_en0[31:0] >> ctrl_gpr_id_wr_idx1[4:0]; +assign gpr_rd2_fwd_div[31:0] = reg_fwd_en0[31:0] >> ctrl_gpr_id_wr_idx2[4:0]; + +assign gpr_rs1_busy_div = gpr_rs1_busy_st[2:0] == BUSY_DIV1 & ~dp_gpr_rs1_fwd_div & ~gpr_rs1_fwd_div[0] + | gpr_rs1_busy_st[2:0] == BUSY_DIV2; +assign gpr_rs2_busy_div = gpr_rs2_busy_st[2:0] == BUSY_DIV1 & ~dp_gpr_rs2_fwd_div & ~gpr_rs2_fwd_div[0] + | gpr_rs2_busy_st[2:0] == BUSY_DIV2; +assign gpr_rs3_busy_div = gpr_rs3_busy_st[2:0] == BUSY_DIV1 & ~dp_gpr_rs3_fwd_div & ~gpr_rs3_fwd_div[0] + | gpr_rs3_busy_st[2:0] == BUSY_DIV2; +assign gpr_rs4_busy_div = gpr_rs4_busy_st[2:0] == BUSY_DIV1 & ~dp_gpr_rs4_fwd_div & ~gpr_rs4_fwd_div[0] + | gpr_rs4_busy_st[2:0] == BUSY_DIV2; +assign gpr_rd1_busy_div = gpr_rd1_busy_st[2:0] == BUSY_DIV1 & ~gpr_rd1_fwd_div[0] + | gpr_rd1_busy_st[2:0] == BUSY_DIV2; +assign gpr_rd2_busy_div = gpr_rd2_busy_st[2:0] == BUSY_DIV1 & ~gpr_rd2_fwd_div[0] + | gpr_rd2_busy_st[2:0] == BUSY_DIV2; + +//========================================================== +// Rename output information +//========================================================== +assign gpr_dp_rs1[31:0] = gpr_read_data1_after_hint[31:0]; +assign gpr_dp_rs2[31:0] = gpr_read_data2_after_hint[31:0]; +assign gpr_dp_rs3[31:0] = gpr_read_data3[31:0]; +assign gpr_dp_rs4[31:0] = gpr_read_data4[31:0]; +assign gpr_dp_id_x2_wr = reg_write_is_gate0[2] + | ctrl_gpr_id_rd2_vld & ctrl_gpr_id_wr_idx2[5:0] == 6'h2; + +//assign gpr_ctrl_rs1_busy = gpr_rs1_busy & decd_gpr_rs1_vld; +//assign gpr_ctrl_rs2_busy = gpr_rs2_busy & decd_gpr_rs2_vld; +//assign gpr_ctrl_rs3_busy = gpr_rs3_busy & decd_gpr_rs3_vld; +//assign gpr_ctrl_rs4_busy = gpr_rs4_busy & decd_gpr_rs4_vld; +//assign gpr_ctrl_rd1_busy = gpr_rd1_busy & decd_gpr_rd1_vld; +//assign gpr_ctrl_rd2_busy = gpr_rd2_busy & decd_gpr_rd2_vld; +assign gpr_ctrl_rs1_busy_lsu = gpr_rs1_busy_lsu & decd_gpr_rs1_vld; +assign gpr_ctrl_rs2_busy_lsu = gpr_rs2_busy_lsu & decd_gpr_rs2_vld; +assign gpr_ctrl_rs3_busy_lsu = gpr_rs3_busy_lsu & decd_gpr_rs3_vld; +assign gpr_ctrl_rs4_busy_lsu = gpr_rs4_busy_lsu & decd_gpr_rs4_vld; +assign gpr_ctrl_rd1_busy_lsu = gpr_rd1_busy_lsu & decd_gpr_rd1_vld; +assign gpr_ctrl_rd2_busy_lsu = gpr_rd2_busy_lsu & decd_gpr_rd2_vld; +assign gpr_ctrl_rs1_busy_div = gpr_rs1_busy_div & decd_gpr_rs1_vld; +assign gpr_ctrl_rs2_busy_div = gpr_rs2_busy_div & decd_gpr_rs2_vld; +assign gpr_ctrl_rs3_busy_div = gpr_rs3_busy_div & decd_gpr_rs3_vld; +assign gpr_ctrl_rs4_busy_div = gpr_rs4_busy_div & decd_gpr_rs4_vld; +assign gpr_ctrl_rd1_busy_div = gpr_rd1_busy_div & decd_gpr_rd1_vld; +assign gpr_ctrl_rd2_busy_div = gpr_rd2_busy_div & decd_gpr_rd2_vld; +assign gpr_ctrl_rs1_busy_lsu2 = gpr_rs1_busy_st[2:0] == BUSY_LSU2; +assign gpr_ctrl_rs2_busy_lsu2 = gpr_rs2_busy_st[2:0] == BUSY_LSU2; +assign gpr_ctrl_rs3_busy_lsu2 = gpr_rs3_busy_st[2:0] == BUSY_LSU2; + +assign gpr_hs_sp_wb = gpr_wb_sp; +assign gpr_hs_sp_busy = reg_busy_st_2[2:0] == BUSY_LSU1 & ~reg_fwd_en2[2] + | reg_busy_st_2[2:0] == BUSY_DIV1 & ~reg_fwd_en2[2] & ~fpu_fwd_sel0[2] + | reg_busy_st_2[2:0] == BUSY_LSU2 + | reg_busy_st_2[2:0] == BUSY_DIV2 & ~(reg_fwd_en2[2] & fpu_fwd_sel0[2]) + | dp_gpr_x2_busy; +assign gpr_hs_sp_busy2 = reg_busy_st_2[2:0] == BUSY_LSU1 & ~reg_fwd_en2[2] & dp_gpr_x2_busy + | reg_busy_st_2[2:0] == BUSY_LSU2 & ~reg_fwd_en2[2] + | dp_gpr_x2_busy2; + +assign idu_ifu_x1[31:0] = reg_dout_1[31:0]; + +assign idu_cp0_sp_reg[31:0] = gpr_wb_sp ? reg_write_en1[2] ? rtu_idu_wb1_data[31:0] : rtu_idu_wb0_data[31:0] + : reg_dout_2[31:0]; + +assign idu_cp0_mepc_wen = reg_write_en_hint1[0] & hs_gpr_wb_mask; +assign idu_cp0_mcause_wen = reg_write_en_hint1[1] & hs_gpr_wb_mask; +assign idu_cp0_ipop_data[31:0] = rtu_idu_wb1_data[31:0]; + +// &ModuleEnd; @1191 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_hs.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_hs.v new file mode 100644 index 0000000000000000000000000000000000000000..e8f86dccaf0f1317b76cad84e525ee034c3090f6 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_hs.v @@ -0,0 +1,970 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("pa_idu_cfig.h"); @23 +// &ModuleBeg; @24 +module pa_idu_hs( + cp0_idu_icg_en, + cp0_idu_spec_push_en, + cp0_idu_swap_sp_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_hs_be_idle, + ctrl_hs_bkpt_vld, + ctrl_hs_no_op, + ctrl_hs_stall, + decd_hs_ipop_vld, + decd_hs_ipush_vld, + forever_cpuclk, + gpr_hs_sp_busy, + gpr_hs_sp_busy2, + gpr_hs_sp_wb, + hd_dp_rs2_sel, + hs_ctrl_cancel, + hs_ctrl_inst_vld, + hs_ctrl_stall, + hs_decd_dp_vld, + hs_decd_dst_vld, + hs_decd_func, + hs_decd_imm, + hs_decd_imm_vld, + hs_decd_rd, + hs_decd_rs1, + hs_decd_rs1_vld, + hs_decd_rs2, + hs_decd_rs2_imm_vld, + hs_decd_rs2_vld, + hs_decd_sel, + hs_decd_split, + hs_dp_ipop_int_mask, + hs_dp_ipop_tail, + hs_dp_ipop_tail_gate, + hs_dp_ipush_spec_fail, + hs_dp_mie_en, + hs_dp_rs2_mcause, + hs_dp_rs2_mepc, + hs_dp_sp_wb_pending, + hs_fdecd_dp_vld, + hs_gpr_wb_mask, + hs_gpr_wr_mask, + idu_cp0_ex1_tail_fail, + idu_cp0_id_tail_vld, + idu_cp0_sp_swap_pending, + idu_cp0_sp_swap_req, + idu_cp0_sp_swap_req_gate, + idu_iu_tail_fail, + idu_iu_tail_fail_gate, + idu_lsu_ex1_ipush_spec, + idu_yy_xx_tail_ack, + ifu_idu_id_inst_vld, + iu_yy_xx_cancel, + pad_yy_icg_scan_en, + rtu_idu_ex2_ipush_spec_inst_expt_vld, + rtu_idu_ex2_ipush_spec_inst_halt_info_vld, + rtu_idu_flush_fe, + rtu_idu_id_tail_int_vld, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vld, + rtu_yy_xx_flush +); + +// &Ports; @25 +input cp0_idu_icg_en; +input cp0_idu_spec_push_en; +input cp0_idu_swap_sp_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_hs_be_idle; +input ctrl_hs_bkpt_vld; +input ctrl_hs_no_op; +input ctrl_hs_stall; +input decd_hs_ipop_vld; +input decd_hs_ipush_vld; +input forever_cpuclk; +input gpr_hs_sp_busy; +input gpr_hs_sp_busy2; +input gpr_hs_sp_wb; +input ifu_idu_id_inst_vld; +input iu_yy_xx_cancel; +input pad_yy_icg_scan_en; +input rtu_idu_ex2_ipush_spec_inst_expt_vld; +input rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +input rtu_idu_flush_fe; +input rtu_idu_id_tail_int_vld; +input rtu_yy_xx_expt_int; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_flush; +output hd_dp_rs2_sel; +output hs_ctrl_cancel; +output hs_ctrl_inst_vld; +output hs_ctrl_stall; +output hs_decd_dp_vld; +output hs_decd_dst_vld; +output [19:0] hs_decd_func; +output [31:0] hs_decd_imm; +output hs_decd_imm_vld; +output [5 :0] hs_decd_rd; +output [5 :0] hs_decd_rs1; +output hs_decd_rs1_vld; +output [5 :0] hs_decd_rs2; +output hs_decd_rs2_imm_vld; +output hs_decd_rs2_vld; +output [5 :0] hs_decd_sel; +output hs_decd_split; +output hs_dp_ipop_int_mask; +output hs_dp_ipop_tail; +output hs_dp_ipop_tail_gate; +output hs_dp_ipush_spec_fail; +output hs_dp_mie_en; +output hs_dp_rs2_mcause; +output hs_dp_rs2_mepc; +output hs_dp_sp_wb_pending; +output hs_fdecd_dp_vld; +output hs_gpr_wb_mask; +output hs_gpr_wr_mask; +output idu_cp0_ex1_tail_fail; +output idu_cp0_id_tail_vld; +output idu_cp0_sp_swap_pending; +output idu_cp0_sp_swap_req; +output idu_cp0_sp_swap_req_gate; +output idu_iu_tail_fail; +output idu_iu_tail_fail_gate; +output idu_lsu_ex1_ipush_spec; +output idu_yy_xx_tail_ack; + +// &Regs; @26 +reg [2 :0] ipop_cur_st; +reg [2 :0] ipop_nxt_st; +reg ipop_split_ag_imm_vld; +reg ipop_split_dst_vld; +reg [19:0] ipop_split_func; +reg [31:0] ipop_split_imm; +reg [5 :0] ipop_split_sel; +reg [2 :0] ipush_cur_st; +reg [2 :0] ipush_nxt_st; +reg ipush_spec_flag; +reg ipush_split_ag_imm_vld; +reg ipush_split_dst_vld; +reg [19:0] ipush_split_func; +reg [31:0] ipush_split_imm_pos; +reg [5 :0] ipush_split_sel; +reg [1 :0] sp_wb_nxt; +reg [1 :0] sp_wb_st; +reg [3 :0] stack_cnt; + +// &Wires; @27 +wire cnt_inc_vld; +wire cp0_idu_icg_en; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_hs_be_idle; +wire ctrl_hs_bkpt_vld; +wire ctrl_hs_no_op; +wire ctrl_hs_stall; +wire decd_hs_ipop_vld; +wire decd_hs_ipush_vld; +wire forever_cpuclk; +wire gpr_hs_sp_busy; +wire gpr_hs_sp_busy2; +wire gpr_hs_sp_wb; +wire hd_dp_rs2_sel; +wire hs_cpuclk; +wire hs_ctrl_cancel; +wire hs_ctrl_inst_vld; +wire hs_ctrl_stall; +wire hs_decd_dp_vld; +wire hs_decd_dst_vld; +wire [19:0] hs_decd_func; +wire [31:0] hs_decd_imm; +wire hs_decd_imm_vld; +wire [5 :0] hs_decd_rd; +wire [5 :0] hs_decd_rs1; +wire hs_decd_rs1_vld; +wire [5 :0] hs_decd_rs2; +wire hs_decd_rs2_imm_vld; +wire hs_decd_rs2_vld; +wire [5 :0] hs_decd_sel; +wire hs_decd_split; +wire hs_dp_ipop_int_mask; +wire hs_dp_ipop_tail; +wire hs_dp_ipop_tail_gate; +wire hs_dp_ipush_spec_fail; +wire hs_dp_mie_en; +wire hs_dp_rs2_mcause; +wire hs_dp_rs2_mepc; +wire hs_dp_sp_wb_pending; +wire hs_fdecd_dp_vld; +wire hs_flush; +wire hs_gpr_wb_mask; +wire hs_gpr_wr_mask; +wire hs_icg_en; +wire hs_id_inst_vld; +wire hs_id_ipush_vld; +wire hs_ipush_flush; +wire idu_cp0_ex1_tail_fail; +wire idu_cp0_id_tail_vld; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire idu_iu_tail_fail; +wire idu_iu_tail_fail_gate; +wire idu_lsu_ex1_ipush_spec; +wire idu_yy_xx_tail_ack; +wire ifu_idu_id_inst_vld; +wire ipop_addsp_st; +wire ipop_idle_st; +wire ipop_ldepc_st; +wire [31:0] ipop_ldgpr_imm; +wire ipop_ldgpr_st; +wire ipop_ldmce_st; +wire ipop_req_vld; +wire ipop_rs2_imm_vld; +wire ipop_rte_st; +wire ipop_split_first; +wire ipop_split_inst_vld; +wire ipop_split_last; +wire [5 :0] ipop_split_ld_rd; +wire [5 :0] ipop_split_rd; +wire [5 :0] ipop_split_rs1; +wire ipop_split_rs1_vld; +wire ipop_split_stall; +wire ipop_stall_relax; +wire ipop_tail_fail; +wire ipop_tail_hs; +wire ipop_tail_st; +wire ipop_tail_vld; +wire ipush_check_fail; +wire ipush_check_pass; +wire ipush_check_ready; +wire ipush_idle_st; +wire ipush_inst_vld; +wire ipush_mcause_rs2_vld; +wire ipush_mepc_rs2_vld; +wire ipush_req_vld; +wire ipush_rs2_imm_vld; +wire ipush_sexpt_st; +wire ipush_spec_clr; +wire ipush_spec_expt; +wire ipush_spec_vld; +wire [31:0] ipush_split_imm; +wire ipush_split_inst_vld; +wire ipush_split_last; +wire [5 :0] ipush_split_rd; +wire [5 :0] ipush_split_rs1; +wire ipush_split_rs1_vld; +wire [5 :0] ipush_split_rs2; +wire ipush_split_rs2_vld; +wire ipush_split_stall; +wire ipush_stall_relax; +wire ipush_stepc_st; +wire [31:0] ipush_stgpr_imm; +wire ipush_stgpr_st; +wire ipush_stmce_st; +wire ipush_subsp_inst_vld; +wire ipush_subsp_st; +wire iu_yy_xx_cancel; +wire pad_yy_icg_scan_en; +wire rtu_idu_ex2_ipush_spec_inst_expt_vld; +wire rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +wire rtu_idu_flush_fe; +wire rtu_idu_id_tail_int_vld; +wire rtu_yy_xx_expt_int; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire sp_cur_wb1; +wire sp_wb_pending; +wire stack_cnt_done; +wire stack_cnt_gpra; +wire stack_cnt_gprb; +wire stack_cnt_gprc; +wire stack_cnt_gprd; + + +//========================================================== +// Hardware Stack Module +// 1. Instance ICG cell +// 2. IPUSH FSM +// 3. IPUSH Spec Flag +// 4. HS Speed Up En +// 5. Stack Counter +// 6. IPOP FSM +// 7. Split Inst Generate +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG cell +//------------------------------------------------ +assign hs_icg_en = ipush_req_vld | ~ipush_idle_st + | ipop_req_vld | ~ipop_idle_st + | sp_wb_pending + | rtu_yy_xx_expt_int + | ipush_spec_flag + ; + +// &Instance("gated_clk_cell", "x_idu_hs_icg_cell"); @50 +gated_clk_cell x_idu_hs_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (hs_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (hs_icg_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @51 +// .external_en (1'b0), @52 +// .global_en (cp0_yy_clk_en), @53 +// .module_en ( cp0_idu_icg_en ) , @54 +// .local_en (hs_icg_en), @55 +// .clk_out (hs_cpuclk) @56 +// ); @57 + +//------------------------------------------------ +// 2. IPUSH FSM +// a. IPUSH_IDLE: IPUSH IDLE State +// b. `FUNC_SW_MCAUSE: Store MCAUSE Reg to Stack +// c. `FUNC_SW_GPR: Store GPR to Stack +// d. `FUNC_ADD_SP: Add Stack Pointer +//------------------------------------------------ + +parameter IPUSH_IDLE = 3'b000; +parameter ST_MEPC = 3'b001; +parameter ST_MCAUSE = 3'b010; +parameter ST_GPR = 3'b011; +parameter SPEC_EXPT = 3'b100; +parameter SUB_SP = 3'b111; + +always@(posedge hs_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ipush_cur_st[2:0] <= IPUSH_IDLE; + else if(hs_ipush_flush) + ipush_cur_st[2:0] <= IPUSH_IDLE; + else if(ipush_spec_expt) + ipush_cur_st[2:0] <= SPEC_EXPT; + else if(~ctrl_hs_stall | rtu_yy_xx_expt_int) + ipush_cur_st[2:0] <= ipush_nxt_st[2:0]; +end + +assign hs_id_inst_vld = ifu_idu_id_inst_vld & ~(rtu_idu_flush_fe | rtu_yy_xx_expt_vld); +assign hs_id_ipush_vld = decd_hs_ipush_vld & ~ctrl_hs_bkpt_vld; +assign ipush_inst_vld = rtu_yy_xx_expt_int & cp0_idu_spec_push_en & (ipop_idle_st | rtu_yy_xx_expt_vld) + | hs_id_inst_vld & hs_id_ipush_vld & ipop_idle_st; +assign ipush_req_vld = ipush_inst_vld; + +assign ipush_check_ready = hs_id_inst_vld; +assign ipush_check_pass = hs_id_inst_vld & hs_id_ipush_vld + & (ipush_stgpr_st | ipush_subsp_st); +assign ipush_check_fail = (hs_id_inst_vld & ~hs_id_ipush_vld) + & ipush_spec_flag + & (ipush_stgpr_st | ipush_subsp_st); + +assign ipush_spec_expt = (rtu_idu_ex2_ipush_spec_inst_expt_vld + | rtu_idu_ex2_ipush_spec_inst_halt_info_vld) + & !ipush_idle_st; // & !ipush_subsp_st; + +assign hs_ipush_flush = rtu_idu_flush_fe & ~ipush_spec_flag | iu_yy_xx_cancel & !ipush_spec_vld | rtu_yy_xx_flush; +assign hs_flush = hs_ipush_flush | rtu_yy_xx_expt_vld; + +// &CombBeg; @106 +always @( ctrl_hs_no_op + or ipush_check_fail + or ipush_check_ready + or ipush_inst_vld + or ipush_spec_flag + or ipush_cur_st[2:0] + or stack_cnt_done) +begin +case(ipush_cur_st[2:0]) + IPUSH_IDLE: + begin + if(ipush_inst_vld) + ipush_nxt_st[2:0] = ST_MEPC; + else + ipush_nxt_st[2:0] = IPUSH_IDLE; + end + ST_MEPC: + begin + if(ctrl_hs_no_op) + ipush_nxt_st[2:0] = ST_MCAUSE; + else + ipush_nxt_st[2:0] = ST_MEPC; + end + ST_MCAUSE: + begin + ipush_nxt_st[2:0] = ST_GPR; + end + ST_GPR: + begin + if(ipush_check_fail) + ipush_nxt_st[2:0] = IPUSH_IDLE; + else if(stack_cnt_done) + ipush_nxt_st[2:0] = SUB_SP; + else + ipush_nxt_st[2:0] = ST_GPR; + end + SUB_SP: + begin + if(ipush_spec_flag) + if(ipush_check_ready) + ipush_nxt_st[2:0] = IPUSH_IDLE; + else + ipush_nxt_st[2:0] = SUB_SP; + else + ipush_nxt_st[2:0] = IPUSH_IDLE; + end + SPEC_EXPT: + begin + ipush_nxt_st[2:0] = IPUSH_IDLE; + end + default: + begin + ipush_nxt_st[2:0] = IPUSH_IDLE; + end +endcase +// &CombEnd; @154 +end + +// ipush fsm state infor +assign ipush_idle_st = ipush_cur_st[2:0] == IPUSH_IDLE; +assign ipush_stepc_st = ipush_cur_st[2:0] == ST_MEPC; +assign ipush_stmce_st = ipush_cur_st[2:0] == ST_MCAUSE; +assign ipush_stgpr_st = ipush_cur_st[2:0] == ST_GPR; +assign ipush_subsp_st = ipush_cur_st[2:0] == SUB_SP; +assign ipush_sexpt_st = ipush_cur_st[2:0] == SPEC_EXPT; + +// //&Force("output","ipush_idle_st"); @165 +//------------------------------------------------ +// 3. IPUSH Spec Flag +//------------------------------------------------ +assign ipush_spec_vld = rtu_yy_xx_expt_int & cp0_idu_spec_push_en & (ipop_idle_st | rtu_yy_xx_expt_vld); +assign ipush_spec_clr = (ipush_check_fail | ipush_sexpt_st | ipush_subsp_st & ipush_check_ready) & ~ctrl_hs_stall; + +always@(posedge hs_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ipush_spec_flag <= 1'b0; + else if(hs_ipush_flush) + ipush_spec_flag <= 1'b0; + else if(ipush_spec_vld) + ipush_spec_flag <= 1'b1; + else if(ipush_spec_clr) + ipush_spec_flag <= 1'b0; + else + ipush_spec_flag <= ipush_spec_flag; +end + +// sp(x2) writeback pending +parameter SP_IDLE = 2'b00; +parameter SP_WB1 = 2'b01; +parameter SP_WB2 = 2'b11; + +//always@(posedge hs_cpuclk or negedge cpurst_b) +//begin +// if(~cpurst_b) +// sp_wb_pending <= 1'b0; +// else if(rtu_idu_flush_fe & ~ipush_spec_flag) +// sp_wb_pending <= 1'b0; +// else if(rtu_yy_xx_expt_vld & rtu_yy_xx_expt_int & cp0_idu_swap_sp_en) +// sp_wb_pending <= gpr_hs_sp_busy; +// else if(sp_wb_pending & gpr_hs_sp_wb) +// sp_wb_pending <= 1'b0; +// else +// sp_wb_pending <= sp_wb_pending; +//end +always@(posedge hs_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + sp_wb_st[1:0] <= SP_IDLE; + else if(rtu_idu_flush_fe & ~ipush_spec_flag | rtu_yy_xx_flush) + sp_wb_st[1:0] <= SP_IDLE; + else + sp_wb_st[1:0] <= sp_wb_nxt[1:0]; +end +// &CombBeg; @214 +always @( cp0_idu_swap_sp_en + or gpr_hs_sp_busy2 + or rtu_yy_xx_expt_vld + or gpr_hs_sp_wb + or gpr_hs_sp_busy + or rtu_yy_xx_expt_int + or sp_wb_st[1:0]) +begin +case(sp_wb_st[1:0]) + SP_IDLE: + begin + if(rtu_yy_xx_expt_vld & rtu_yy_xx_expt_int & cp0_idu_swap_sp_en) + if(gpr_hs_sp_busy2) + sp_wb_nxt[1:0] = SP_WB2; + else if(gpr_hs_sp_busy) + sp_wb_nxt[1:0] = SP_WB1; + else + sp_wb_nxt[1:0] = SP_IDLE; + else + sp_wb_nxt[1:0] = SP_IDLE; + end + SP_WB1: + begin + if(gpr_hs_sp_wb) + sp_wb_nxt[1:0] = SP_IDLE; + else + sp_wb_nxt[1:0] = SP_WB1; + end + SP_WB2: + begin + if(gpr_hs_sp_wb) + sp_wb_nxt[1:0] = SP_WB1; + else + sp_wb_nxt[1:0] = SP_WB2; + end + default: + begin + sp_wb_nxt[1:0] = SP_IDLE; + end +endcase +// &CombEnd; @247 +end + +assign sp_wb_pending = sp_wb_st[1:0] != SP_IDLE; +assign sp_cur_wb1 = sp_wb_st[1:0] == SP_WB1; + +//------------------------------------------------ +// 4. HS Speed Up En +//------------------------------------------------ +//assign ipush_spec_hs = ipush_subsp_st & ipush_spec_flag & ipush_check_ready; +assign ipop_tail_hs = ipop_tail_st & hs_id_inst_vld & hs_id_ipush_vld; + +//------------------------------------------------ +// 5. Stack Counter +//------------------------------------------------ +assign cnt_inc_vld = ipush_stgpr_st | ipop_ldgpr_st; +always@(posedge hs_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + stack_cnt[3:0] <= 4'b0; + else if(hs_flush | ipush_sexpt_st | ipush_check_fail | ipop_tail_fail) + stack_cnt[3:0] <= 4'b0; + else if(cnt_inc_vld & ~ctrl_hs_stall) + stack_cnt[3:0] <= stack_cnt[3:0] + 4'b1; + else + stack_cnt[3:0] <= stack_cnt[3:0]; +end + +assign stack_cnt_done = stack_cnt[3:0] == 4'hf; + +assign stack_cnt_gpra = stack_cnt[3:0] == 4'h0; // X1 +assign stack_cnt_gprb = stack_cnt[3:2] == 2'b00 & stack_cnt[1:0] != 2'b0; // X5~X7 +assign stack_cnt_gprc = stack_cnt[3:2] == 2'b01 // X10~X13 + | stack_cnt[3:2] == 2'b10; // X14~X17 +assign stack_cnt_gprd = stack_cnt[3:2] == 2'b11; // X28~X31 + + +//------------------------------------------------ +// 6. IPOP FSM +//------------------------------------------------ + +parameter IPOP_IDLE = 3'b000; +parameter LD_GPR = 3'b001; +parameter LD_MCAUSE = 3'b010; +parameter LD_MEPC = 3'b011; +parameter ADD_SP = 3'b100; +parameter IPOP_RTE = 3'b110; +parameter IPOP_TAIL = 3'b111; + +always@(posedge hs_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ipop_cur_st[2:0] <= IPOP_IDLE; + else if(hs_flush | rtu_idu_flush_fe) + ipop_cur_st[2:0] <= IPOP_IDLE; + else if(~ctrl_hs_stall) + ipop_cur_st[2:0] <= ipop_nxt_st[2:0]; +end + +assign ipop_req_vld = hs_id_inst_vld & decd_hs_ipop_vld & (ipush_idle_st | ipush_check_fail) & ~ctrl_hs_bkpt_vld; +assign ipop_tail_vld = rtu_idu_id_tail_int_vld & cp0_idu_spec_push_en; + +// &CombBeg; @308 +always @( ipop_cur_st[2:0] + or hs_id_ipush_vld + or ipop_tail_vld + or hs_id_inst_vld + or ipop_req_vld + or stack_cnt_done) +begin +case(ipop_cur_st[2:0]) + IPOP_IDLE: + begin + if(ipop_req_vld) + if(ipop_tail_vld) + ipop_nxt_st[2:0] = IPOP_TAIL; + else + ipop_nxt_st[2:0] = LD_GPR; + else + ipop_nxt_st[2:0] = IPOP_IDLE; + end + LD_GPR: + begin + if(stack_cnt_done) + ipop_nxt_st[2:0] = LD_MCAUSE; + else + ipop_nxt_st[2:0] = LD_GPR; + end + LD_MCAUSE: + begin + ipop_nxt_st[2:0] = LD_MEPC; + end + LD_MEPC: + begin + ipop_nxt_st[2:0] = ADD_SP; + end + ADD_SP: + begin + ipop_nxt_st[2:0] = IPOP_RTE; + end + IPOP_RTE: + begin + ipop_nxt_st[2:0] = IPOP_IDLE; + end + IPOP_TAIL: + begin + if(hs_id_inst_vld) + if(hs_id_ipush_vld) + ipop_nxt_st[2:0] = IPOP_IDLE; + else + ipop_nxt_st[2:0] = LD_GPR; + else + ipop_nxt_st[2:0] = IPOP_TAIL; + end + default: + begin + ipop_nxt_st[2:0] = IPOP_IDLE; + end +endcase +// &CombEnd; @358 +end + +// ipop fsm state infor +assign ipop_idle_st = ipop_cur_st[2:0] == IPOP_IDLE; +assign ipop_ldgpr_st = ipop_cur_st[2:0] == LD_GPR; +assign ipop_ldmce_st = ipop_cur_st[2:0] == LD_MCAUSE; +assign ipop_ldepc_st = ipop_cur_st[2:0] == LD_MEPC; +assign ipop_addsp_st = ipop_cur_st[2:0] == ADD_SP; +assign ipop_rte_st = ipop_cur_st[2:0] == IPOP_RTE; +assign ipop_tail_st = ipop_cur_st[2:0] == IPOP_TAIL; + +//assign ipop_tail_ready = ipop_tail_st & hs_id_inst_vld; +assign ipop_tail_fail = ipop_tail_st & hs_id_inst_vld & ~hs_id_ipush_vld; + +// //&Force("output","ipop_idle_st"); @373 + +//------------------------------------------------ +// 7. Split Inst Generate +// a. IPUSH split inst +// b. IPOP split inst +//------------------------------------------------ +// a. IPUSH split inst +// basic split inst infor +// &CombBeg; @383 +always @( ipush_stgpr_imm[31:0] + or ipush_cur_st[2:0]) +begin +case(ipush_cur_st[2:0]) + ST_MEPC: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipush_split_func[`FUNC_WIDTH-1:0] = `FUNC_SW; + ipush_split_ag_imm_vld = 1'b1; + ipush_split_dst_vld = 1'b0; + ipush_split_imm_pos[31:0] = 32'h4; + end + ST_MCAUSE: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipush_split_func[`FUNC_WIDTH-1:0] = `FUNC_SW; + ipush_split_ag_imm_vld = 1'b1; + ipush_split_dst_vld = 1'b0; + ipush_split_imm_pos[31:0] = 32'h8; + end + ST_GPR: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipush_split_func[`FUNC_WIDTH-1:0] = `FUNC_SW; + ipush_split_ag_imm_vld = 1'b1; + ipush_split_dst_vld = 1'b0; + ipush_split_imm_pos[31:0] = ipush_stgpr_imm[31:0]; + end + SUB_SP: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + ipush_split_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + ipush_split_ag_imm_vld = 1'b0; + ipush_split_dst_vld = 1'b1; + ipush_split_imm_pos[31:0] = 32'h48; + end + SPEC_EXPT: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + ipush_split_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + ipush_split_ag_imm_vld = 1'b0; + ipush_split_dst_vld = 1'b0; + ipush_split_imm_pos[31:0] = 32'h0; + end + default: + begin + ipush_split_sel[`SEL_WIDTH-1:0] = {`SEL_WIDTH{1'b0}}; + ipush_split_func[`FUNC_WIDTH-1:0] = {`FUNC_WIDTH{1'b0}}; + ipush_split_ag_imm_vld = 1'b0; + ipush_split_dst_vld = 1'b0; + ipush_split_imm_pos[31:0] = 32'h0; + end +endcase +// &CombEnd; @434 +end + +// operand prepare +// rs1 +assign ipush_split_rs1_vld = ~ipush_idle_st; +assign ipush_split_rs1[5:0] = 6'h2; + +// rs2 +assign ipush_split_rs2_vld = ipush_stgpr_st; +assign ipush_mepc_rs2_vld = ipush_stepc_st; +assign ipush_mcause_rs2_vld = ipush_stmce_st; +assign ipush_split_rs2[5:0] = {6{stack_cnt_gpra}} & 6'd1 + | {6{stack_cnt_gprb}} & ({2'b0, stack_cnt[3:0]} + 6'd4) + | {6{stack_cnt_gprc}} & ({2'b0, stack_cnt[3:0]} + 6'd6) + | {6{stack_cnt_gprd}} & ({2'b0, stack_cnt[3:0]} + 6'd16); + +// imm +assign ipush_rs2_imm_vld = ipush_subsp_st; +assign ipush_stgpr_imm[31:0] = {25'b0, {1'b0, stack_cnt[3:0]} + 5'b11, 2'b0}; +assign ipush_split_imm[31:0] = ~ipush_split_imm_pos[31:0] + 1'b1; + +// rd +assign ipush_split_rd[5:0] = 6'h2; + +// split inst valid +assign ipush_split_inst_vld = ipush_stepc_st & ctrl_hs_no_op + | ipush_stmce_st + | ipush_stgpr_st + | ipush_subsp_st & ipush_spec_flag & ipush_check_pass + | ipush_subsp_st & ~ipush_spec_flag + | ipush_sexpt_st; +assign ipush_subsp_inst_vld = ipush_subsp_st & ipush_spec_flag & ipush_check_pass + | ipush_subsp_st & ~ipush_spec_flag; + +// stall signal +assign ipush_stall_relax = //ipush_stgpr_st & ipush_spec_flag & ipush_check_fail + ipush_subsp_st & ipush_spec_flag & ipush_check_pass; +assign ipush_split_stall = ~ipush_idle_st & ~ipush_stall_relax; + +// split signal +//assign ipush_split_first = ipush_stepc_st; +assign ipush_split_last = ipush_subsp_st; +//assign ipush_split_swp = ipush_idle_st & rtu_yy_xx_expt_int; + +// ie enable + +// b. IPOP split inst +//assign ipop_vld = ipop_inst_vld & ~ipop_tail_vld; +// basic split inst infor +// &CombBeg; @483 +always @( ipop_cur_st[2:0] + or ipop_ldgpr_imm[31:0]) +begin +case(ipop_cur_st[2:0]) + LD_GPR: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_LW; + ipop_split_ag_imm_vld = 1'b1; + ipop_split_dst_vld = 1'b1; + ipop_split_imm[31:0] = ipop_ldgpr_imm[31:0]; + end + LD_MCAUSE: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_LW; + ipop_split_ag_imm_vld = 1'b1; + ipop_split_dst_vld = 1'b1; + ipop_split_imm[31:0] = 32'h40; + end + LD_MEPC: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_LW; + ipop_split_ag_imm_vld = 1'b1; + ipop_split_dst_vld = 1'b1; + ipop_split_imm[31:0] = 32'h44; + end + ADD_SP: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + ipop_split_ag_imm_vld = 1'b0; + ipop_split_dst_vld = 1'b1; + ipop_split_imm[31:0] = 32'h48; + end + IPOP_RTE: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_CP0; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_MRET; + ipop_split_ag_imm_vld = 1'b0; + ipop_split_dst_vld = 1'b0; + ipop_split_imm[31:0] = 32'h0; + end + IPOP_TAIL: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + ipop_split_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + ipop_split_ag_imm_vld = 1'b0; + ipop_split_dst_vld = 1'b0; + ipop_split_imm[31:0] = 32'h0; + end + default: + begin + ipop_split_sel[`SEL_WIDTH-1:0] = {`SEL_WIDTH{1'b0}}; + ipop_split_func[`FUNC_WIDTH-1:0] = {`FUNC_WIDTH{1'b0}}; + ipop_split_ag_imm_vld = 1'b0; + ipop_split_dst_vld = 1'b0; + ipop_split_imm[31:0] = 32'h0; + end +endcase +// &CombEnd; @542 +end + +// rs1 +assign ipop_split_rs1_vld = 1'b1; +assign ipop_split_rs1[5:0] = 6'h2; + +// imm +assign ipop_rs2_imm_vld = ipop_addsp_st; +assign ipop_ldgpr_imm[31:0] = {26'h0, 4'hf-stack_cnt[3:0], 2'b0}; +//assign ipop_split_imm[31:0] = ~ipop_split_imm_pos[31:0] + 1'b1; + +// rd +//assign ipop_mepc_rd_vld = ipop_ldepc_st; +//assign ipop_mcause_rd_vld = ipop_ldmce_st; +assign ipop_split_ld_rd[5:0] = {6{stack_cnt_gpra}} & 6'd1 + | {6{stack_cnt_gprb}} & ({2'b0, stack_cnt[3:0]} + 6'd4) + | {6{stack_cnt_gprc}} & ({2'b0, stack_cnt[3:0]} + 6'd6) + | {6{stack_cnt_gprd}} & ({2'b0, stack_cnt[3:0]} + 6'd16); +assign ipop_split_rd[5:0] = ipop_addsp_st ? 6'd2 : ipop_ldepc_st ? 6'h20 + : ipop_ldmce_st ? 6'h21 : ipop_split_ld_rd[5:0]; + +// split inst valid +assign ipop_split_inst_vld = ipop_ldgpr_st + | ipop_ldepc_st + | ipop_ldmce_st + | ipop_addsp_st + | ipop_rte_st; + +// stall signal +assign ipop_stall_relax = ipop_idle_st & ipop_tail_vld + | ipop_tail_hs; +assign ipop_split_stall = ~ipop_idle_st & ~ipop_stall_relax; + +// split signal +assign ipop_split_first = ipop_idle_st & ipop_req_vld; +assign ipop_split_last = ipop_rte_st & ctrl_hs_be_idle; + +//----------------------------------------------- +// 4. Rename for Output +//----------------------------------------------- +// Output to decd +assign hs_decd_dp_vld = ~ipush_idle_st // & ~ipush_check_fail + | ~ipop_idle_st; +assign hs_fdecd_dp_vld = ~ipush_idle_st // & ~ipush_check_fail + | ~ipop_idle_st; +assign hs_decd_sel[`SEL_WIDTH-1:0] = ipush_split_sel[`SEL_WIDTH-1:0] | ipop_split_sel[`SEL_WIDTH-1:0]; +assign hs_decd_func[`FUNC_WIDTH-1:0] = ipush_split_func[`FUNC_WIDTH-1:0] + | ipop_split_func[`FUNC_WIDTH-1:0]; + +assign hs_decd_rs1_vld = ipush_split_rs1_vld | ipop_split_rs1_vld; +assign hs_decd_rs1[5:0] = ipush_split_rs1[5:0] | ipop_split_rs1[5:0]; + +assign hs_decd_rs2_vld = ipush_split_rs2_vld; +assign hs_decd_rs2[5:0] = ipush_split_rs2[5:0]; + +assign hs_decd_rs2_imm_vld = ipush_rs2_imm_vld | ipop_rs2_imm_vld; +assign hs_decd_imm_vld = ipush_split_ag_imm_vld | ipop_split_ag_imm_vld; +assign hs_decd_imm[31:0] = ipop_split_imm[31:0] | ipush_split_imm[31:0]; + +assign hs_decd_dst_vld = ipush_split_dst_vld | ipop_split_dst_vld; +assign hs_decd_rd[5:0] = ipush_subsp_st ? ipush_split_rd[5:0] : ipop_split_rd[5:0]; +assign hs_decd_split = ~(ipush_split_last | ipop_split_last | ipop_tail_hs); + +// Output to ctrl +assign hs_ctrl_inst_vld = ipush_split_inst_vld | ipop_split_inst_vld; +assign hs_ctrl_stall = ipush_split_stall | ipop_split_stall; +assign hs_ctrl_cancel = ipush_idle_st & ipush_req_vld + | ipush_stepc_st & ~ctrl_hs_no_op + | ipush_check_fail + | ipush_spec_expt + | ipop_split_first & ~ipop_tail_vld + | ipop_tail_fail; +// Output to dp +assign hd_dp_rs2_sel = ~ipush_idle_st; +assign hs_dp_rs2_mepc = ipush_mepc_rs2_vld; +assign hs_dp_rs2_mcause = ipush_mcause_rs2_vld; +assign hs_dp_ipush_spec_fail = ipush_sexpt_st; +assign hs_dp_ipop_tail = ipop_split_first & ipop_tail_vld & ~ctrl_hs_stall; +assign hs_dp_ipop_tail_gate = ipop_split_first & ipop_tail_vld; +assign hs_dp_mie_en = ipush_subsp_inst_vld; +assign hs_dp_ipop_int_mask = ipop_ldgpr_st | ipop_split_first & ipop_tail_vld; +assign hs_dp_sp_wb_pending = sp_wb_pending; + +// Output to write mask +assign hs_gpr_wr_mask = ipop_ldmce_st | ipop_ldepc_st; +assign hs_gpr_wb_mask = ~ipop_idle_st; + +// Output to IFU +//assign idu_ifu_tail_vld = ipop_split_first & ipop_tail_vld; + +// Output to CP0 +//assign idu_cp0_sp_swap_en = ipush_split_swp | ipop_split_last; +assign idu_cp0_sp_swap_pending = sp_wb_pending; +assign idu_cp0_sp_swap_req = rtu_yy_xx_expt_vld & rtu_yy_xx_expt_int & cp0_idu_swap_sp_en & ~gpr_hs_sp_busy + | sp_cur_wb1 & gpr_hs_sp_wb + | sp_wb_pending & (rtu_idu_flush_fe & ~ipush_spec_flag | rtu_yy_xx_flush); +assign idu_cp0_sp_swap_req_gate = rtu_yy_xx_expt_int & cp0_idu_swap_sp_en & ~gpr_hs_sp_busy + | sp_cur_wb1 & gpr_hs_sp_wb + | sp_wb_pending & (rtu_idu_flush_fe & ~ipush_spec_flag | rtu_yy_xx_flush); + +//assign idu_cp0_sp_swap_req = (ipush_subsp_inst_vld | ipush_check_fail) & cp0_idu_swap_sp_en; +//assign idu_cp0_sp_swap_req_gate = (ipush_subsp_inst_vld | ipush_check_fail) & cp0_idu_swap_sp_en; +assign idu_cp0_id_tail_vld = ipop_split_first & ipop_tail_vld; +assign idu_yy_xx_tail_ack = ipop_tail_hs; + +// Output to RTU +assign idu_lsu_ex1_ipush_spec = ipush_spec_flag; +assign idu_cp0_ex1_tail_fail = ipop_tail_fail; + +// Output to IU +assign idu_iu_tail_fail = ipop_tail_fail; +assign idu_iu_tail_fail_gate = ipop_tail_st & ifu_idu_id_inst_vld; + +// &Force("nonport","flag"); @667 +// &Force("nonport","clk"); @668 +// &Force("nonport","rst"); @669 + +// &ModuleEnd; @678 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_id_fp.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_id_fp.v new file mode 100644 index 0000000000000000000000000000000000000000..048d54819cf6dd0435e5d8da3e9aaa96fa16960e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_id_fp.v @@ -0,0 +1,543 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_id_fp( + cp0_idu_icg_en, + cp0_yy_clk_en, + ctrl_id_fp_ex1_inst_vld, + ctrl_id_fp_ex1_lsu_sel, + ctrl_id_fp_id_expt_vld, + ctrl_id_fp_id_inst_vld, + ctrl_id_fp_id_stall, + ctrl_id_fp_pipe_down, + ctrl_id_fp_st_rs2_dep, + ctrl_id_fp_uncmit, + decd_fp_id_dp_func, + decd_fp_id_fp_dst_idx, + decd_fp_id_fp_dst_vld, + decd_fp_id_fp_inst_vld, + decd_fp_id_fp_lsu_sel, + decd_fp_id_fp_rs1_idx, + decd_fp_id_fp_rs1_vld, + decd_fp_id_fp_rs2_idx, + decd_fp_id_fp_rs2_vld, + decd_fp_id_fp_rs3_idx, + decd_fp_id_fp_rs3_vld, + decd_fp_id_fp_unit_sel, + decd_fp_id_rm, + dp_id_fp_ex1_rs2_idx, + forever_cpuclk, + fpr_id_fp_rd_busy, + fpr_id_fp_rd_busy_lsu, + fpr_id_fp_rs1, + fpr_id_fp_rs1_busy, + fpr_id_fp_rs1_busy_lsu, + fpr_id_fp_rs2, + fpr_id_fp_rs2_busy, + fpr_id_fp_rs2_busy_lsu, + fpr_id_fp_rs3, + fpr_id_fp_rs3_busy, + fpr_id_fp_rs3_busy_lsu, + fpu_idu_fwd_data, + fpu_idu_fwd_freg, + fpu_idu_fwd_vld, + id_fp_ctrl_id_stall, + id_fp_ctrl_rs2_dep_ex1_dst, + id_fp_ctrl_rs2_stall_upd, + id_fp_dp_srcf1, + id_fp_fpr_dst_freg, + id_fp_fpr_id_dst_vld, + id_fp_fpr_ld_inst, + id_fp_fpr_wr_issue, + idu_fpu_ex1_cmplt_dp_sel, + idu_fpu_ex1_dst_freg, + idu_fpu_ex1_dst_freg_vld, + idu_fpu_ex1_dst_preg, + idu_fpu_ex1_eu_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_gateclk_vld, + idu_fpu_ex1_inst_vld, + idu_fpu_ex1_rm, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + idu_fpu_ex1_srcf2, + ifu_idu_chgflw_flush, + ifu_idu_warm_up, + iu_idu_bju_global_stall, + lsu_idu_ex2_ffwd_data, + lsu_idu_ex2_ffwd_vld, + lsu_idu_ex2_fwd_freg, + lsu_idu_ex3_ffwd_data, + lsu_idu_ex3_ffwd_vld, + lsu_idu_ex3_fwd_freg, + lsu_idu_global_stall, + pad_yy_icg_scan_en, + rtu_idu_fgpr_wb_data, + rtu_idu_fgpr_wb_reg, + rtu_idu_fgpr_wb_vld, + rtu_idu_flush_fe +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input ctrl_id_fp_ex1_inst_vld; +input ctrl_id_fp_ex1_lsu_sel; +input ctrl_id_fp_id_expt_vld; +input ctrl_id_fp_id_inst_vld; +input ctrl_id_fp_id_stall; +input ctrl_id_fp_pipe_down; +input ctrl_id_fp_st_rs2_dep; +input ctrl_id_fp_uncmit; +input [9 :0] decd_fp_id_dp_func; +input [4 :0] decd_fp_id_fp_dst_idx; +input decd_fp_id_fp_dst_vld; +input decd_fp_id_fp_inst_vld; +input decd_fp_id_fp_lsu_sel; +input [4 :0] decd_fp_id_fp_rs1_idx; +input decd_fp_id_fp_rs1_vld; +input [4 :0] decd_fp_id_fp_rs2_idx; +input decd_fp_id_fp_rs2_vld; +input [4 :0] decd_fp_id_fp_rs3_idx; +input decd_fp_id_fp_rs3_vld; +input [2 :0] decd_fp_id_fp_unit_sel; +input [2 :0] decd_fp_id_rm; +input [4 :0] dp_id_fp_ex1_rs2_idx; +input forever_cpuclk; +input fpr_id_fp_rd_busy; +input fpr_id_fp_rd_busy_lsu; +input [31:0] fpr_id_fp_rs1; +input fpr_id_fp_rs1_busy; +input fpr_id_fp_rs1_busy_lsu; +input [31:0] fpr_id_fp_rs2; +input fpr_id_fp_rs2_busy; +input fpr_id_fp_rs2_busy_lsu; +input [31:0] fpr_id_fp_rs3; +input fpr_id_fp_rs3_busy; +input fpr_id_fp_rs3_busy_lsu; +input [31:0] fpu_idu_fwd_data; +input [4 :0] fpu_idu_fwd_freg; +input fpu_idu_fwd_vld; +input ifu_idu_chgflw_flush; +input ifu_idu_warm_up; +input iu_idu_bju_global_stall; +input [31:0] lsu_idu_ex2_ffwd_data; +input lsu_idu_ex2_ffwd_vld; +input [4 :0] lsu_idu_ex2_fwd_freg; +input [31:0] lsu_idu_ex3_ffwd_data; +input lsu_idu_ex3_ffwd_vld; +input [4 :0] lsu_idu_ex3_fwd_freg; +input lsu_idu_global_stall; +input pad_yy_icg_scan_en; +input [31:0] rtu_idu_fgpr_wb_data; +input [4 :0] rtu_idu_fgpr_wb_reg; +input rtu_idu_fgpr_wb_vld; +input rtu_idu_flush_fe; +output id_fp_ctrl_id_stall; +output id_fp_ctrl_rs2_dep_ex1_dst; +output id_fp_ctrl_rs2_stall_upd; +output [31:0] id_fp_dp_srcf1; +output [4 :0] id_fp_fpr_dst_freg; +output id_fp_fpr_id_dst_vld; +output id_fp_fpr_ld_inst; +output id_fp_fpr_wr_issue; +output idu_fpu_ex1_cmplt_dp_sel; +output [4 :0] idu_fpu_ex1_dst_freg; +output idu_fpu_ex1_dst_freg_vld; +output [4 :0] idu_fpu_ex1_dst_preg; +output [2 :0] idu_fpu_ex1_eu_sel; +output [9 :0] idu_fpu_ex1_func; +output idu_fpu_ex1_gateclk_vld; +output idu_fpu_ex1_inst_vld; +output [2 :0] idu_fpu_ex1_rm; +output [31:0] idu_fpu_ex1_srcf0; +output [31:0] idu_fpu_ex1_srcf1; +output [31:0] idu_fpu_ex1_srcf2; + +// &Regs; @25 +reg [4 :0] id_fp_ex1_dst_idx; +reg id_fp_ex1_dst_vld; +reg [9 :0] id_fp_ex1_func; +reg [2 :0] id_fp_ex1_rm; +reg [31:0] id_fp_ex1_src0; +reg [31:0] id_fp_ex1_src1; +reg [31:0] id_fp_ex1_src2; +reg [2 :0] id_fp_ex1_unit_sel; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire ctrl_id_fp_ex1_inst_vld; +wire ctrl_id_fp_ex1_lsu_sel; +wire ctrl_id_fp_id_expt_vld; +wire ctrl_id_fp_id_inst_vld; +wire ctrl_id_fp_id_stall; +wire ctrl_id_fp_pipe_down; +wire ctrl_id_fp_st_rs2_dep; +wire ctrl_id_fp_uncmit; +wire [9 :0] decd_fp_id_dp_func; +wire [4 :0] decd_fp_id_fp_dst_idx; +wire decd_fp_id_fp_dst_vld; +wire decd_fp_id_fp_inst_vld; +wire decd_fp_id_fp_lsu_sel; +wire [4 :0] decd_fp_id_fp_rs1_idx; +wire decd_fp_id_fp_rs1_vld; +wire [4 :0] decd_fp_id_fp_rs2_idx; +wire decd_fp_id_fp_rs2_vld; +wire [4 :0] decd_fp_id_fp_rs3_idx; +wire decd_fp_id_fp_rs3_vld; +wire [2 :0] decd_fp_id_fp_unit_sel; +wire [2 :0] decd_fp_id_rm; +wire [4 :0] dp_id_fp_ex1_rs2_idx; +wire forever_cpuclk; +wire fpr_id_fp_rd_busy; +wire fpr_id_fp_rd_busy_lsu; +wire [31:0] fpr_id_fp_rs1; +wire fpr_id_fp_rs1_busy; +wire fpr_id_fp_rs1_busy_lsu; +wire [31:0] fpr_id_fp_rs2; +wire fpr_id_fp_rs2_busy; +wire fpr_id_fp_rs2_busy_lsu; +wire [31:0] fpr_id_fp_rs3; +wire fpr_id_fp_rs3_busy; +wire fpr_id_fp_rs3_busy_lsu; +wire [31:0] fpu_idu_fwd_data; +wire [4 :0] fpu_idu_fwd_freg; +wire fpu_idu_fwd_vld; +wire id_fp_ctrl_id_stall; +wire id_fp_ctrl_rs2_dep_ex1_dst; +wire id_fp_ctrl_rs2_stall_upd; +wire id_fp_dep_ld_stall; +wire id_fp_dep_norm_stall; +wire [31:0] id_fp_dp_srcf1; +wire id_fp_ex1_inst_vld; +wire [4 :0] id_fp_fpr_dst_freg; +wire id_fp_fpr_id_dst_vld; +wire id_fp_fpr_ld_inst; +wire id_fp_fpr_wr_issue; +wire [31:0] id_fp_id_fin_rs1; +wire [31:0] id_fp_id_fin_rs2; +wire [31:0] id_fp_id_fin_rs3; +wire id_fp_id_inst_vld; +wire id_fp_id_issue_cancel; +wire id_fp_id_ld_inst; +wire id_fp_id_st_inst; +wire id_fp_id_stall; +wire id_fp_issue_stall; +wire id_fp_pipe_down; +wire [31:0] id_fp_rs1_aft_fwd_no_lsu; +wire id_fp_rs1_fwd; +wire id_fp_rs1_fwd_lsu; +wire id_fp_rs1_fwd_lsu_ex3; +wire [31:0] id_fp_rs2_aft_fwd_no_lsu; +wire id_fp_rs2_dep_ex1; +wire id_fp_rs2_fwd; +wire id_fp_rs2_fwd_lsu; +wire id_fp_rs2_fwd_lsu_ex3; +wire id_fp_rs2_stall_upd; +wire id_fp_rs2_stall_upd_fpu; +wire id_fp_rs2_stall_upd_lsu; +wire id_fp_rs2_stall_upd_wb; +wire [31:0] id_fp_rs3_aft_fwd_no_lsu; +wire id_fp_rs3_fwd; +wire id_fp_rs3_fwd_lsu; +wire id_fp_rs3_fwd_lsu_ex3; +wire id_fp_st_rs2_dep_vld; +wire [2 :0] id_fp_unit_sel; +wire idfp_cpuclk; +wire idfp_icg_en; +wire idu_fpu_ex1_cmplt_dp_sel; +wire [4 :0] idu_fpu_ex1_dst_freg; +wire idu_fpu_ex1_dst_freg_vld; +wire [4 :0] idu_fpu_ex1_dst_preg; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire idu_fpu_ex1_gateclk_vld; +wire idu_fpu_ex1_inst_vld; +wire [2 :0] idu_fpu_ex1_rm; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire [31:0] idu_fpu_ex1_srcf2; +wire ifu_idu_chgflw_flush; +wire ifu_idu_warm_up; +wire iu_idu_bju_global_stall; +wire [31:0] lsu_idu_ex2_ffwd_data; +wire lsu_idu_ex2_ffwd_vld; +wire [4 :0] lsu_idu_ex2_fwd_freg; +wire [31:0] lsu_idu_ex3_ffwd_data; +wire lsu_idu_ex3_ffwd_vld; +wire [4 :0] lsu_idu_ex3_fwd_freg; +wire lsu_idu_global_stall; +wire pad_yy_icg_scan_en; +wire [31:0] rtu_idu_fgpr_wb_data; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire rtu_idu_flush_fe; + + +parameter FUNC_WIDTH = 10; +parameter REG_WIDTH = `FLEN; + +//========================================================== +// Control Flow Module +// 1. ICG Instance +// 2. ID -> EX1 instruction unit sel +// 3. ID -> EX1 instruction destination +// 4. ID -> EX1 exception information +// 5. ID depend and stall +//========================================================== + +//----------------------------------------------- +// 1. ICG Instance +//----------------------------------------------- +//----------------------------------------------- +// 1. ICG instance +//----------------------------------------------- +assign idfp_icg_en = id_fp_id_inst_vld + | ifu_idu_warm_up + | ctrl_id_fp_st_rs2_dep; +// &Instance("gated_clk_cell", "x_idu_dp_icg_cell"); @49 +gated_clk_cell x_idu_dp_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (idfp_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (idfp_icg_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @50 +// .external_en (1'b0), @51 +// .global_en (cp0_yy_clk_en), @52 +// .module_en ( cp0_idu_icg_en ) , @53 +// .local_en (idfp_icg_en), @54 +// .clk_out (idfp_cpuclk)); @55 + +//----------------------------------------------- +// 2. EX1 instruction Infor +//----------------------------------------------- +assign id_fp_id_inst_vld = ctrl_id_fp_id_inst_vld & decd_fp_id_fp_inst_vld; +assign id_fp_pipe_down = ctrl_id_fp_pipe_down & decd_fp_id_fp_inst_vld; +assign id_fp_ex1_inst_vld = ctrl_id_fp_ex1_inst_vld; +assign id_fp_unit_sel[2:0] = ctrl_id_fp_id_expt_vld ? 3'b0 + : decd_fp_id_fp_unit_sel[2:0]; + +always @ (posedge idfp_cpuclk) +begin + if(id_fp_pipe_down | ifu_idu_warm_up) + begin + id_fp_ex1_unit_sel[2:0] <= id_fp_unit_sel[2:0]; + id_fp_ex1_func[FUNC_WIDTH-1:0] <= decd_fp_id_dp_func[FUNC_WIDTH-1:0]; + id_fp_ex1_rm[2:0] <= decd_fp_id_rm[2:0]; + id_fp_ex1_dst_vld <= decd_fp_id_fp_dst_vld; + id_fp_ex1_dst_idx[4:0] <= decd_fp_id_fp_dst_idx[4:0]; + id_fp_ex1_src0[REG_WIDTH-1:0] <= id_fp_id_fin_rs1[REG_WIDTH-1:0]; + id_fp_ex1_src2[REG_WIDTH-1:0] <= id_fp_id_fin_rs3[REG_WIDTH-1:0]; + end + else + begin + id_fp_ex1_unit_sel[2:0] <= id_fp_ex1_unit_sel[2:0]; + id_fp_ex1_func[FUNC_WIDTH-1:0] <= id_fp_ex1_func[FUNC_WIDTH-1:0]; + id_fp_ex1_rm[2:0] <= id_fp_ex1_rm[2:0]; + id_fp_ex1_dst_vld <= id_fp_ex1_dst_vld; + id_fp_ex1_dst_idx[4:0] <= id_fp_ex1_dst_idx[4:0]; + id_fp_ex1_src0[REG_WIDTH-1:0] <= id_fp_ex1_src0[REG_WIDTH-1:0]; + id_fp_ex1_src2[REG_WIDTH-1:0] <= id_fp_ex1_src2[REG_WIDTH-1:0]; + end +end + +always @ (posedge idfp_cpuclk) +begin + if(id_fp_pipe_down | ifu_idu_warm_up) + begin + id_fp_ex1_src1[REG_WIDTH-1:0] <= id_fp_id_fin_rs2[REG_WIDTH-1:0]; + end + else if(id_fp_rs2_stall_upd & ctrl_id_fp_st_rs2_dep) + begin + id_fp_ex1_src1[REG_WIDTH-1:0] <= id_fp_rs2_stall_upd_fpu ? fpu_idu_fwd_data[REG_WIDTH-1:0] + : id_fp_rs2_stall_upd_wb ? rtu_idu_fgpr_wb_data[REG_WIDTH-1:0] + : lsu_idu_ex2_ffwd_data[REG_WIDTH-1:0]; + end + else + begin + id_fp_ex1_src1[REG_WIDTH-1:0] <= id_fp_ex1_src1[REG_WIDTH-1:0]; + end +end + +//assign id_fp_ex1_falu_sel = id_fp_ex1_inst_vld & id_fp_ex1_unit_sel[0]; +//assign id_fp_ex1_fmau_sel = id_fp_ex1_inst_vld & id_fp_ex1_unit_sel[1]; +//assign id_fp_ex1_fdsu_sel = id_fp_ex1_inst_vld & id_fp_ex1_unit_sel[2]; + +//----------------------------------------------- +// 3. ID depend and stall +//----------------------------------------------- +assign id_fp_id_st_inst = decd_fp_id_fp_lsu_sel & ~decd_fp_id_fp_dst_vld; +assign id_fp_id_ld_inst = decd_fp_id_fp_lsu_sel & decd_fp_id_fp_dst_vld; + +//----------------------------------------------- +// a. forward data and fpr data selection +// b. wbbr data and operand data selection +// c. immediate data fpr data selection +//----------------------------------------------- + +// a. forward data and fpr data selection +// priority: fwd > wb +// Note that wb fwd is already done in fpr +assign id_fp_rs1_fwd = decd_fp_id_fp_rs1_idx[4:0] == fpu_idu_fwd_freg[4:0] + & decd_fp_id_fp_rs1_vld & fpu_idu_fwd_vld; +assign id_fp_rs2_fwd = decd_fp_id_fp_rs2_idx[4:0] == fpu_idu_fwd_freg[4:0] + & decd_fp_id_fp_rs2_vld & fpu_idu_fwd_vld; +assign id_fp_rs3_fwd = decd_fp_id_fp_rs3_idx[4:0] == fpu_idu_fwd_freg[4:0] + & decd_fp_id_fp_rs3_vld & fpu_idu_fwd_vld; + +// fwd flsu +assign id_fp_rs1_fwd_lsu = decd_fp_id_fp_rs1_idx[4:0] == lsu_idu_ex2_fwd_freg[4:0] + & decd_fp_id_fp_rs1_vld & lsu_idu_ex2_ffwd_vld; +assign id_fp_rs2_fwd_lsu = decd_fp_id_fp_rs2_idx[4:0] == lsu_idu_ex2_fwd_freg[4:0] + & decd_fp_id_fp_rs2_vld & lsu_idu_ex2_ffwd_vld; +assign id_fp_rs3_fwd_lsu = decd_fp_id_fp_rs3_idx[4:0] == lsu_idu_ex2_fwd_freg[4:0] + & decd_fp_id_fp_rs3_vld & lsu_idu_ex2_ffwd_vld; + +// fwd flsu +assign id_fp_rs1_fwd_lsu_ex3 = decd_fp_id_fp_rs1_idx[4:0] == lsu_idu_ex3_fwd_freg[4:0] + & decd_fp_id_fp_rs1_vld & lsu_idu_ex3_ffwd_vld; +assign id_fp_rs2_fwd_lsu_ex3 = decd_fp_id_fp_rs2_idx[4:0] == lsu_idu_ex3_fwd_freg[4:0] + & decd_fp_id_fp_rs2_vld & lsu_idu_ex3_ffwd_vld; +assign id_fp_rs3_fwd_lsu_ex3 = decd_fp_id_fp_rs3_idx[4:0] == lsu_idu_ex3_fwd_freg[4:0] + & decd_fp_id_fp_rs3_vld & lsu_idu_ex3_ffwd_vld; + +assign id_fp_rs1_aft_fwd_no_lsu[REG_WIDTH-1:0] = id_fp_rs1_fwd_lsu_ex3 ? lsu_idu_ex3_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs1_fwd ? fpu_idu_fwd_data[REG_WIDTH-1:0] + : fpr_id_fp_rs1[REG_WIDTH-1:0]; +assign id_fp_rs2_aft_fwd_no_lsu[REG_WIDTH-1:0] = id_fp_rs2_fwd_lsu_ex3 ? lsu_idu_ex3_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs2_fwd ? fpu_idu_fwd_data[REG_WIDTH-1:0] + : fpr_id_fp_rs2[REG_WIDTH-1:0]; +assign id_fp_rs3_aft_fwd_no_lsu[REG_WIDTH-1:0] = id_fp_rs3_fwd_lsu_ex3 ? lsu_idu_ex3_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs3_fwd ? fpu_idu_fwd_data[REG_WIDTH-1:0] + : fpr_id_fp_rs3[REG_WIDTH-1:0]; + +// c. final fpr data selection +assign id_fp_id_fin_rs1[REG_WIDTH-1:0] = id_fp_rs1_fwd_lsu & ~id_fp_rs1_fwd + ? lsu_idu_ex2_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs1_aft_fwd_no_lsu[REG_WIDTH-1:0]; +assign id_fp_id_fin_rs2[REG_WIDTH-1:0] = id_fp_rs2_fwd_lsu & ~id_fp_rs2_fwd + ? lsu_idu_ex2_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs2_aft_fwd_no_lsu[REG_WIDTH-1:0]; +assign id_fp_id_fin_rs3[REG_WIDTH-1:0] = id_fp_rs3_fwd_lsu & ~id_fp_rs3_fwd + ? lsu_idu_ex2_ffwd_data[REG_WIDTH-1:0] + : id_fp_rs3_aft_fwd_no_lsu[REG_WIDTH-1:0]; + +// d. store data update when lsu ex stall and ex2 fwd hit +assign id_fp_rs2_stall_upd_lsu = dp_id_fp_ex1_rs2_idx[4:0] == lsu_idu_ex2_fwd_freg[4:0] + & lsu_idu_ex2_ffwd_vld; +assign id_fp_rs2_stall_upd_fpu = dp_id_fp_ex1_rs2_idx[4:0] == fpu_idu_fwd_freg[4:0] + & fpu_idu_fwd_vld; +assign id_fp_rs2_stall_upd_wb = dp_id_fp_ex1_rs2_idx[4:0] == rtu_idu_fgpr_wb_reg[4:0] + & rtu_idu_fgpr_wb_vld; +assign id_fp_rs2_stall_upd = (id_fp_rs2_stall_upd_lsu | id_fp_rs2_stall_upd_fpu + | id_fp_rs2_stall_upd_wb) & ctrl_id_fp_ex1_lsu_sel; +assign id_fp_dep_ld_stall = (fpr_id_fp_rs1_busy_lsu & ~id_fp_rs1_fwd_lsu & ~id_fp_rs1_fwd_lsu_ex3 + | fpr_id_fp_rs2_busy_lsu & ~id_fp_rs2_fwd_lsu & ~id_fp_rs2_fwd_lsu_ex3 + | fpr_id_fp_rs3_busy_lsu & ~id_fp_rs3_fwd_lsu & ~id_fp_rs3_fwd_lsu_ex3 + | fpr_id_fp_rd_busy_lsu) + & ~id_fp_id_st_inst + & id_fp_id_inst_vld; + +// id rs depend div stall, id store inst included +// ex1 oper depend +// ex2 oper depend +//assign id_fp_dep_div_stall = (fpr_id_fp_rs1_busy_div & ~id_fp_id_fp_rs1_fwd_div +// | fpr_id_fp_rs2_busy_div & ~id_fp_id_fp_rs2_fwd_div +// | fpr_id_fp_rd_busy_div) & id_fp_id_inst_vld; + +assign id_fp_dep_norm_stall = (fpr_id_fp_rs1_busy & ~id_fp_rs1_fwd + | fpr_id_fp_rs2_busy & ~id_fp_rs2_fwd + | fpr_id_fp_rs3_busy & ~id_fp_rs3_fwd + | fpr_id_fp_rd_busy) + & ~id_fp_id_st_inst + & id_fp_id_inst_vld; + +// id store rs2 depend load +assign id_fp_rs2_dep_ex1 = decd_fp_id_fp_rs2_idx[4:0] == id_fp_ex1_dst_idx[4:0] + & decd_fp_id_fp_rs2_vld; +assign id_fp_st_rs2_dep_vld = (fpr_id_fp_rs2_busy_lsu & ~id_fp_rs2_fwd_lsu & ~id_fp_rs2_fwd_lsu_ex3 + | fpr_id_fp_rs2_busy & ~id_fp_rs2_fwd + | ctrl_id_fp_ex1_lsu_sel & id_fp_rs2_dep_ex1 + & id_fp_ex1_dst_vld) + & id_fp_id_st_inst & id_fp_id_inst_vld; + + +assign id_fp_id_issue_cancel = (id_fp_dep_ld_stall | id_fp_dep_norm_stall) + & ~id_fp_issue_stall + | rtu_idu_flush_fe; + +// Todo rtu ex1 stall only depend load +assign id_fp_issue_stall = 1'b0;//fpu_idu_ex1_stall; + +assign id_fp_id_stall = id_fp_dep_ld_stall | id_fp_dep_norm_stall | id_fp_issue_stall; + +//========================================================== +// Rename for Output +//========================================================== + +//----------------------------------------------- +// Output to IDU FPR +//----------------------------------------------- +assign id_fp_fpr_wr_issue = id_fp_id_inst_vld & id_fp_pipe_down & decd_fp_id_fp_dst_vld + & ~(rtu_idu_flush_fe | ifu_idu_chgflw_flush & ~id_fp_issue_stall + | id_fp_id_issue_cancel | ctrl_id_fp_id_stall); +assign id_fp_fpr_ld_inst = id_fp_id_ld_inst; +assign id_fp_fpr_id_dst_vld = id_fp_id_inst_vld & decd_fp_id_fp_dst_vld; +assign id_fp_fpr_dst_freg[4:0] = id_fp_ex1_dst_idx[4:0]; + +//----------------------------------------------- +// Output to IDU Ctrl +//----------------------------------------------- +assign id_fp_ctrl_id_stall = id_fp_id_stall; +assign id_fp_ctrl_rs2_dep_ex1_dst = id_fp_st_rs2_dep_vld; +assign id_fp_ctrl_rs2_stall_upd = id_fp_rs2_stall_upd & ctrl_id_fp_st_rs2_dep; + +//----------------------------------------------- +// Output to IDU DP +//----------------------------------------------- +assign id_fp_dp_srcf1[REG_WIDTH-1:0] = id_fp_ex1_src1[REG_WIDTH-1:0]; + +//----------------------------------------------- +// Output to FPU +//----------------------------------------------- +assign idu_fpu_ex1_inst_vld = id_fp_ex1_inst_vld & ~ctrl_id_fp_uncmit; +assign idu_fpu_ex1_cmplt_dp_sel = id_fp_ex1_inst_vld & ~(lsu_idu_global_stall | iu_idu_bju_global_stall); +assign idu_fpu_ex1_gateclk_vld = id_fp_ex1_inst_vld; +assign idu_fpu_ex1_eu_sel[2:0] = id_fp_ex1_unit_sel[2:0]; +assign idu_fpu_ex1_func[FUNC_WIDTH-1:0] = id_fp_ex1_func[FUNC_WIDTH-1:0]; +assign idu_fpu_ex1_rm[2:0] = id_fp_ex1_rm[2:0]; +assign idu_fpu_ex1_srcf0[REG_WIDTH-1:0] = id_fp_ex1_src0[REG_WIDTH-1:0]; +assign idu_fpu_ex1_srcf1[REG_WIDTH-1:0] = id_fp_ex1_src1[REG_WIDTH-1:0]; +assign idu_fpu_ex1_srcf2[REG_WIDTH-1:0] = id_fp_ex1_src2[REG_WIDTH-1:0]; +assign idu_fpu_ex1_dst_freg_vld = id_fp_ex1_dst_vld; +assign idu_fpu_ex1_dst_freg[4:0] = id_fp_ex1_dst_idx[4:0]; +assign idu_fpu_ex1_dst_preg[4:0] = id_fp_ex1_dst_idx[4:0]; + +//----------------------------------------------- +// Output to LSU +//----------------------------------------------- +// Todo + +// &ModuleEnd; @354 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg.v new file mode 100644 index 0000000000000000000000000000000000000000..755e2a3434201fd16806f89de59dacf9735aad8e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg.v @@ -0,0 +1,239 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_reg( + cp0_idu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_gpr_ld_inst, + ifu_idu_warm_up, + int_clr_en_x, + pad_yy_icg_scan_en, + reg_busy_div_x, + reg_busy_lsu_x, + reg_busy_x, + reg_in_cpuclk, + reg_sm_cpuclk, + reg_write_en_x, + reg_write_is_x, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_fgpr_wb_flsu_vld, + rtu_idu_flush_fe, + write_data, + x_reg_dout +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_gpr_ld_inst; +input ifu_idu_warm_up; +input int_clr_en_x; +input pad_yy_icg_scan_en; +input reg_in_cpuclk; +input reg_sm_cpuclk; +input reg_write_en_x; +input reg_write_is_x; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_fgpr_wb_flsu_vld; +input rtu_idu_flush_fe; +input [31:0] write_data; +output reg_busy_div_x; +output reg_busy_lsu_x; +output reg_busy_x; +output [31:0] x_reg_dout; + +// &Regs; @25 +reg [2 :0] reg_cur_st; +reg [2 :0] reg_nxt_st; +reg [31:0] x_reg_dout; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_gpr_ld_inst; +wire ifu_idu_warm_up; +wire int_clr_en_x; +wire pad_yy_icg_scan_en; +wire reg_busy_div_x; +wire reg_busy_lsu_x; +wire reg_busy_x; +wire reg_clk_en; +wire reg_cpuclk; +wire reg_in_cpuclk; +wire reg_sm_cpuclk; +wire reg_write_en_x; +wire reg_write_is_x; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_fgpr_wb_flsu_vld; +wire rtu_idu_flush_fe; +wire [31:0] write_data; +wire [31:0] write_in_data; +wire write_in_en; +wire write_is_en; +wire write_is_ld_en; + + +parameter REG_WIDTH = `FLEN; + +//========================================================== +// Integated Clock Gating Cell +//========================================================== +assign reg_clk_en = write_in_en; +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @34 +gated_clk_cell x_reg_gated_clk ( + .clk_in (reg_in_cpuclk ), + .clk_out (reg_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (reg_in_cpuclk), @35 +// .external_en (1'b0), @36 +// .global_en (cp0_yy_clk_en), @37 +// .module_en ( cp0_idu_icg_en ) , @38 +// .local_en (reg_clk_en), @39 +// .clk_out (reg_cpuclk)); @40 + +//assign reg_sm_clk_en = reg_write_is_gate_x | write_in_en | rtu_idu_flush_fe; +//&Instance("gated_clk_cell", "x_reg_sm_gated_clk"); +// //&Connect(.clk_in (reg_in_cpuclk), @44 +// // .external_en (1'b0), @45 +// // .global_en (cp0_yy_clk_en), @46 +// // .module_en ( cp0_idu_icg_en ) , @47 +// // .local_en (reg_sm_clk_en), @48 +// // .clk_out (reg_sm_cpuclk)); @49 + +//========================================================== +// Write Port +//========================================================== +assign write_in_en = reg_write_en_x | ifu_idu_warm_up; +assign write_is_en = reg_write_is_x & ~rtu_idu_ex1_int_dis_stall_req; +assign write_in_data[REG_WIDTH-1:0] = {REG_WIDTH{~ifu_idu_warm_up}} & write_data[REG_WIDTH-1:0]; + +assign write_is_ld_en = write_is_en & ctrl_gpr_ld_inst; + +// &Force("output", "x_reg_dout"); @60 +always @(posedge reg_cpuclk) +begin + if(write_in_en | ifu_idu_warm_up) + x_reg_dout[REG_WIDTH-1:0] <= write_in_data[REG_WIDTH-1:0]; + else + x_reg_dout[REG_WIDTH-1:0] <= x_reg_dout[REG_WIDTH-1:0]; +end + +parameter IDLE = 3'b000; +parameter BUSY1 = 3'b001; +parameter BUSY_LSU1 = 3'b010; +parameter BUSY_DIV1 = 3'b110; +parameter BUSY2 = 3'b100; +parameter BUSY_LSU2 = 3'b011; +parameter BUSY_DIV2 = 3'b111; + +always @(posedge reg_sm_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + reg_cur_st[2:0] <= IDLE; + else if(rtu_idu_flush_fe) + reg_cur_st[2:0] <= IDLE; + else + reg_cur_st[2:0] <= reg_nxt_st[2:0]; +end + +// &CombBeg; @99 +always @( reg_cur_st[2:0] + or rtu_idu_fgpr_wb_flsu_vld + or ctrl_gpr_ld_inst + or reg_write_en_x + or write_is_en + or write_is_ld_en + or int_clr_en_x) +begin +case(reg_cur_st[2:0]) + IDLE: + begin + if(write_is_en) + if(ctrl_gpr_ld_inst) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + end + BUSY1: + begin + if(reg_write_en_x | int_clr_en_x) + if(write_is_en) + if(ctrl_gpr_ld_inst) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY1; + end + BUSY_LSU1: + begin + if(reg_write_en_x & rtu_idu_fgpr_wb_flsu_vld | int_clr_en_x) + if(write_is_en) + if(ctrl_gpr_ld_inst) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else + reg_nxt_st[2:0] = BUSY_LSU1; + end + BUSY_LSU2: + begin + if(reg_write_en_x | int_clr_en_x) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY_LSU2; + end + default: + begin + reg_nxt_st[2:0] = IDLE; + end +endcase +// &CombEnd; @154 +end + +assign reg_busy_x = reg_cur_st[2:0] == BUSY1 & ~(reg_write_en_x & ~rtu_idu_fgpr_wb_flsu_vld); +assign reg_busy_lsu_x = reg_cur_st[2:0] == BUSY_LSU1 + | reg_cur_st[2:0] == BUSY_LSU2 & ~(reg_write_en_x & rtu_idu_fgpr_wb_flsu_vld); +assign reg_busy_div_x = 1'b0; + +//assign reg_fwd_en_x = reg_cur_st[2:0] == IDLE | reg_cur_st[2:0] == BUSY1 +// | reg_cur_st[2:0] == BUSY_LSU1 | reg_cur_st[2:0] == BUSY_DIV1 +// | reg_cur_st[2:0] == BUSY2; + +// &ModuleEnd; @165 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32.v new file mode 100644 index 0000000000000000000000000000000000000000..f284cf0eb03ed7af17d1499a96be9bcd65f408f8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32.v @@ -0,0 +1,326 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_reg32( + cp0_idu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_gpr_div_inst, + ctrl_gpr_ld_inst, + forever_cpuclk, + ifu_idu_warm_up, + pad_yy_icg_scan_en, + reg_busy_st_y, + reg_dout_y, + reg_fwd_en0_x, + reg_fwd_en1_x, + reg_fwd_en2_x, + reg_write_en0_x, + reg_write_en1_x, + reg_write_en2_x, + reg_write_en_gate0_x, + reg_write_en_gate1_x, + reg_write_en_gate2_x, + reg_write_is0_x, + reg_write_is_gate0_x, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_flush_fe, + write_data0, + write_data1, + write_data2 +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_gpr_div_inst; +input ctrl_gpr_ld_inst; +input forever_cpuclk; +input ifu_idu_warm_up; +input pad_yy_icg_scan_en; +input reg_fwd_en0_x; +input reg_fwd_en1_x; +input reg_fwd_en2_x; +input reg_write_en0_x; +input reg_write_en1_x; +input reg_write_en2_x; +input reg_write_en_gate0_x; +input reg_write_en_gate1_x; +input reg_write_en_gate2_x; +input reg_write_is0_x; +input reg_write_is_gate0_x; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_flush_fe; +input [31:0] write_data0; +input [31:0] write_data1; +input [31:0] write_data2; +output [2 :0] reg_busy_st_y; +output [31:0] reg_dout_y; + +// &Regs; @25 +reg [2 :0] reg_cur_st; +reg [31:0] reg_dout; +reg [2 :0] reg_nxt_st; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_gpr_div_inst; +wire ctrl_gpr_ld_inst; +wire forever_cpuclk; +wire ifu_idu_warm_up; +wire pad_yy_icg_scan_en; +wire [2 :0] reg_busy_st_y; +wire reg_clk_en; +wire reg_cpuclk; +wire [31:0] reg_dout_y; +wire reg_fwd_en0_x; +wire reg_fwd_en1_x; +wire reg_fwd_en2_x; +wire reg_sm_clk_en; +wire reg_sm_cpuclk; +wire reg_write_en0_x; +wire reg_write_en1_x; +wire reg_write_en2_x; +wire reg_write_en_gate0_x; +wire reg_write_en_gate1_x; +wire reg_write_en_gate2_x; +wire reg_write_is0_x; +wire reg_write_is_gate0_x; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_flush_fe; +wire [31:0] write_data0; +wire [31:0] write_data1; +wire [31:0] write_data2; +wire [31:0] write_in_data; +wire write_in_en; +wire write_is_div_en; +wire write_is_en; +wire write_is_ld_en; + + +//========================================================== +// Integated Clock Gating Cell +//========================================================== +assign reg_clk_en = reg_write_en_gate0_x | reg_write_en_gate1_x | reg_write_en_gate2_x | ifu_idu_warm_up; +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @32 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @33 +// .external_en (1'b0), @34 +// .global_en (cp0_yy_clk_en), @35 +// .module_en ( cp0_idu_icg_en ) , @36 +// .local_en (reg_clk_en), @37 +// .clk_out (reg_cpuclk)); @38 + +assign reg_sm_clk_en = reg_write_is_gate0_x //| reg_write_is_gate1_x + | write_in_en | rtu_idu_flush_fe; +// &Instance("gated_clk_cell", "x_reg_sm_gated_clk"); @42 +gated_clk_cell x_reg_sm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_sm_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_sm_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @43 +// .external_en (1'b0), @44 +// .global_en (cp0_yy_clk_en), @45 +// .module_en ( cp0_idu_icg_en ) , @46 +// .local_en (reg_sm_clk_en), @47 +// .clk_out (reg_sm_cpuclk)); @48 + +//========================================================== +// Write Port +//========================================================== +assign write_in_en = reg_fwd_en0_x | reg_fwd_en1_x | reg_fwd_en2_x; +assign write_is_en = reg_write_is0_x; // | reg_write_is1_x; +assign write_in_data[31:0] = reg_write_en1_x ? write_data1[31:0] + : reg_write_en2_x ? write_data2[31:0] + : reg_write_en0_x | ifu_idu_warm_up ? write_data0[31:0] + : reg_dout[31:0]; + +assign write_is_ld_en = write_is_en & ctrl_gpr_ld_inst & ~rtu_idu_ex1_int_dis_stall_req; +assign write_is_div_en = write_is_en & ctrl_gpr_div_inst & ~rtu_idu_ex1_int_dis_stall_req; + +always @(posedge reg_cpuclk) +begin + reg_dout[31:0] <= write_in_data[31:0]; +end + +parameter IDLE = 3'b000; +parameter BUSY1 = 3'b001; +parameter BUSY_LSU1 = 3'b010; +parameter BUSY_DIV1 = 3'b011; +parameter BUSY2 = 3'b100; +parameter BUSY_LSU2 = 3'b110; +parameter BUSY_DIV2 = 3'b111; + +always @(posedge reg_sm_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + reg_cur_st[2:0] <= IDLE; + else if(rtu_idu_flush_fe) + reg_cur_st[2:0] <= IDLE; + else + reg_cur_st[2:0] <= reg_nxt_st[2:0]; +end + +// &CombBeg; @96 +always @( reg_cur_st[2:0] + or reg_fwd_en2_x + or write_is_en + or write_is_div_en + or write_in_en + or reg_fwd_en1_x + or reg_fwd_en0_x + or write_is_ld_en) +begin +case(reg_cur_st[2:0]) + IDLE: + begin + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + end + BUSY1: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + end + BUSY_LSU1: + begin + if(reg_fwd_en1_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else + reg_nxt_st[2:0] = BUSY_LSU1; + end + BUSY_DIV1: + begin + if(reg_fwd_en0_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_DIV1; + end + BUSY2: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = BUSY2; + end + BUSY_DIV2: + begin + if(reg_fwd_en0_x) + if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY_DIV2; + end + BUSY_LSU2: + begin + if(reg_fwd_en1_x) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_LSU1; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY_LSU2; + end + default: + begin + reg_nxt_st[2:0] = IDLE; + end +endcase +// &CombEnd; @208 +end + +//assign reg_busy_div_x = reg_cur_st[2:0] == BUSY_DIV1 | reg_cur_st[2:0] == BUSY_DIV2; +assign reg_busy_st_y[2:0] = reg_cur_st[2:0]; +assign reg_dout_y[31:0] = write_in_data[31:0]; + +// &ModuleEnd; @214 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32_high.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32_high.v new file mode 100644 index 0000000000000000000000000000000000000000..05e03bfa75eee3c19cc5e11495e0022c0d4f14bb --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg32_high.v @@ -0,0 +1,304 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_reg32_high( + cp0_idu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_gpr_div_inst, + ctrl_gpr_ld_inst, + forever_cpuclk, + ifu_idu_warm_up, + pad_yy_icg_scan_en, + reg_busy_st_y, + reg_dout_y, + reg_fwd_en0_x, + reg_fwd_en1_x, + reg_fwd_en2_x, + reg_high_cpuclk, + reg_write_en0_x, + reg_write_en1_x, + reg_write_en2_x, + reg_write_is0_x, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_flush_fe, + write_data0, + write_data1, + write_data2 +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_gpr_div_inst; +input ctrl_gpr_ld_inst; +input forever_cpuclk; +input ifu_idu_warm_up; +input pad_yy_icg_scan_en; +input reg_fwd_en0_x; +input reg_fwd_en1_x; +input reg_fwd_en2_x; +input reg_high_cpuclk; +input reg_write_en0_x; +input reg_write_en1_x; +input reg_write_en2_x; +input reg_write_is0_x; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_flush_fe; +input [31:0] write_data0; +input [31:0] write_data1; +input [31:0] write_data2; +output [2 :0] reg_busy_st_y; +output [31:0] reg_dout_y; + +// &Regs; @25 +reg [2 :0] reg_cur_st; +reg [31:0] reg_dout; +reg [2 :0] reg_nxt_st; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_gpr_div_inst; +wire ctrl_gpr_ld_inst; +wire forever_cpuclk; +wire ifu_idu_warm_up; +wire pad_yy_icg_scan_en; +wire [2 :0] reg_busy_st_y; +wire reg_clk_en; +wire reg_cpuclk; +wire [31:0] reg_dout_y; +wire reg_fwd_en0_x; +wire reg_fwd_en1_x; +wire reg_fwd_en2_x; +wire reg_high_cpuclk; +wire reg_write_en0_x; +wire reg_write_en1_x; +wire reg_write_en2_x; +wire reg_write_is0_x; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_flush_fe; +wire [31:0] write_data0; +wire [31:0] write_data1; +wire [31:0] write_data2; +wire [31:0] write_in_data; +wire write_in_en; +wire write_is_div_en; +wire write_is_en; +wire write_is_ld_en; + + +//========================================================== +// Integated Clock Gating Cell +//========================================================== +assign reg_clk_en = reg_write_en0_x | reg_write_en1_x | reg_write_en2_x | ifu_idu_warm_up; +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @32 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @33 +// .external_en (1'b0), @34 +// .global_en (cp0_yy_clk_en), @35 +// .module_en ( cp0_idu_icg_en ) , @36 +// .local_en (reg_clk_en), @37 +// .clk_out (reg_cpuclk)); @38 + +//assign reg_sm_clk_en = reg_write_is_gate0_x | reg_write_is_gate1_x +// | write_in_en | rtu_idu_flush_fe; +//&Instance("gated_clk_cell", "x_reg_sm_gated_clk"); +// //&Connect(.clk_in (forever_cpuclk), @43 +// // .external_en (1'b0), @44 +// // .global_en (cp0_yy_clk_en), @45 +// // .module_en ( cp0_idu_icg_en ) , @46 +// // .local_en (reg_sm_clk_en), @47 +// // .clk_out (reg_sm_cpuclk)); @48 + +//========================================================== +// Write Port +//========================================================== +assign write_in_en = reg_fwd_en0_x | reg_fwd_en1_x | reg_fwd_en2_x | ifu_idu_warm_up; +assign write_is_en = reg_write_is0_x; // | reg_write_is1_x; +assign write_in_data[31:0] = reg_write_en1_x ? write_data1[31:0] + : reg_write_en2_x ? write_data2[31:0] + : reg_write_en0_x | ifu_idu_warm_up ? write_data0[31:0] + : reg_dout[31:0]; + +assign write_is_ld_en = write_is_en & ctrl_gpr_ld_inst & ~rtu_idu_ex1_int_dis_stall_req; +assign write_is_div_en = write_is_en & ctrl_gpr_div_inst & ~rtu_idu_ex1_int_dis_stall_req; + +always @(posedge reg_cpuclk) +begin + reg_dout[31:0] <= write_in_data[31:0]; +end + +parameter IDLE = 3'b000; +parameter BUSY1 = 3'b001; +parameter BUSY_LSU1 = 3'b010; +parameter BUSY_DIV1 = 3'b011; +parameter BUSY2 = 3'b100; +parameter BUSY_LSU2 = 3'b110; +parameter BUSY_DIV2 = 3'b111; + +always @(posedge reg_high_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + reg_cur_st[2:0] <= IDLE; + else if(rtu_idu_flush_fe) + reg_cur_st[2:0] <= IDLE; + else + reg_cur_st[2:0] <= reg_nxt_st[2:0]; +end + +// &CombBeg; @96 +always @( reg_cur_st[2:0] + or reg_fwd_en2_x + or write_is_en + or write_is_div_en + or write_in_en + or reg_fwd_en1_x + or reg_fwd_en0_x + or write_is_ld_en) +begin +case(reg_cur_st[2:0]) + IDLE: + begin + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + end + BUSY1: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + end + BUSY_LSU1: + begin + if(reg_fwd_en1_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else + reg_nxt_st[2:0] = BUSY_LSU1; + end + BUSY_DIV1: + begin + if(reg_fwd_en0_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_DIV1; + end + BUSY2: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = BUSY2; + end + BUSY_DIV2: + begin + if(reg_fwd_en0_x) + if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY_DIV2; + end + BUSY_LSU2: + begin + if(reg_fwd_en1_x) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_LSU1; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY_LSU2; + end + default: + begin + reg_nxt_st[2:0] = IDLE; + end +endcase +// &CombEnd; @208 +end + +assign reg_busy_st_y[2:0] = reg_cur_st[2:0]; +assign reg_dout_y[31:0] = write_in_data[31:0]; + +// &ModuleEnd; @213 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg_sp.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg_sp.v new file mode 100644 index 0000000000000000000000000000000000000000..ebef3d2c160be157f46cea9e29afef30863cba31 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_reg_sp.v @@ -0,0 +1,336 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_idu_reg_sp( + cp0_idu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_gpr_div_inst, + ctrl_gpr_ld_inst, + forever_cpuclk, + ifu_idu_warm_up, + pad_yy_icg_scan_en, + reg_busy_st_y, + reg_dout_y, + reg_fwd_en0_x, + reg_fwd_en1_x, + reg_fwd_en2_x, + reg_write_en0_x, + reg_write_en1_x, + reg_write_en2_x, + reg_write_en_gate0_x, + reg_write_en_gate1_x, + reg_write_en_gate2_x, + reg_write_en_sp, + reg_write_en_sp_gate, + reg_write_is0_x, + reg_write_is_gate0_x, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_flush_fe, + write_data0, + write_data1, + write_data2, + write_data_sp +); + +// &Ports; @24 +input cp0_idu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_gpr_div_inst; +input ctrl_gpr_ld_inst; +input forever_cpuclk; +input ifu_idu_warm_up; +input pad_yy_icg_scan_en; +input reg_fwd_en0_x; +input reg_fwd_en1_x; +input reg_fwd_en2_x; +input reg_write_en0_x; +input reg_write_en1_x; +input reg_write_en2_x; +input reg_write_en_gate0_x; +input reg_write_en_gate1_x; +input reg_write_en_gate2_x; +input reg_write_en_sp; +input reg_write_en_sp_gate; +input reg_write_is0_x; +input reg_write_is_gate0_x; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_flush_fe; +input [31:0] write_data0; +input [31:0] write_data1; +input [31:0] write_data2; +input [31:0] write_data_sp; +output [2 :0] reg_busy_st_y; +output [31:0] reg_dout_y; + +// &Regs; @25 +reg [2 :0] reg_cur_st; +reg [31:0] reg_dout; +reg [2 :0] reg_nxt_st; + +// &Wires; @26 +wire cp0_idu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_gpr_div_inst; +wire ctrl_gpr_ld_inst; +wire forever_cpuclk; +wire ifu_idu_warm_up; +wire pad_yy_icg_scan_en; +wire [2 :0] reg_busy_st_y; +wire reg_clk_en; +wire reg_cpuclk; +wire [31:0] reg_dout_y; +wire reg_fwd_en0_x; +wire reg_fwd_en1_x; +wire reg_fwd_en2_x; +wire reg_sm_clk_en; +wire reg_sm_cpuclk; +wire reg_write_en0_x; +wire reg_write_en1_x; +wire reg_write_en2_x; +wire reg_write_en_gate0_x; +wire reg_write_en_gate1_x; +wire reg_write_en_gate2_x; +wire reg_write_en_sp; +wire reg_write_en_sp_gate; +wire reg_write_is0_x; +wire reg_write_is_gate0_x; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_flush_fe; +wire [31:0] write_data0; +wire [31:0] write_data1; +wire [31:0] write_data2; +wire [31:0] write_data_sp; +wire [31:0] write_in_data; +wire write_in_en; +wire [31:0] write_in_sp_data; +wire write_is_div_en; +wire write_is_en; +wire write_is_ld_en; + + +//========================================================== +// Integated Clock Gating Cell +//========================================================== +assign reg_clk_en = reg_write_en_gate0_x | reg_write_en_gate1_x | reg_write_en_gate2_x | reg_write_en_sp_gate | ifu_idu_warm_up; +// &Instance("gated_clk_cell", "x_reg_gated_clk"); @32 +gated_clk_cell x_reg_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @33 +// .external_en (1'b0), @34 +// .global_en (cp0_yy_clk_en), @35 +// .module_en ( cp0_idu_icg_en ) , @36 +// .local_en (reg_clk_en), @37 +// .clk_out (reg_cpuclk)); @38 + +assign reg_sm_clk_en = reg_write_is_gate0_x // | reg_write_is_gate1_x + | write_in_en | rtu_idu_flush_fe; +// &Instance("gated_clk_cell", "x_reg_sm_gated_clk"); @42 +gated_clk_cell x_reg_sm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (reg_sm_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (reg_sm_clk_en ), + .module_en (cp0_idu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @43 +// .external_en (1'b0), @44 +// .global_en (cp0_yy_clk_en), @45 +// .module_en ( cp0_idu_icg_en ) , @46 +// .local_en (reg_sm_clk_en), @47 +// .clk_out (reg_sm_cpuclk)); @48 + +//========================================================== +// Write Port +//========================================================== +assign write_in_en = reg_fwd_en0_x | reg_fwd_en1_x | reg_fwd_en2_x | reg_write_en_sp | ifu_idu_warm_up; +assign write_is_en = reg_write_is0_x; // | reg_write_is1_x; +assign write_in_data[31:0] = reg_write_en1_x ? write_data1[31:0] + : reg_write_en2_x ? write_data2[31:0] + : reg_write_en0_x | ifu_idu_warm_up ? write_data0[31:0] + : reg_dout[31:0]; +assign write_in_sp_data[31:0] = reg_write_en_sp ? write_data_sp[31:0] : write_in_data[31:0]; + +assign write_is_ld_en = write_is_en & ctrl_gpr_ld_inst & ~rtu_idu_ex1_int_dis_stall_req; +assign write_is_div_en = write_is_en & ctrl_gpr_div_inst & ~rtu_idu_ex1_int_dis_stall_req; + +always @(posedge reg_cpuclk) +begin + reg_dout[31:0] <= write_in_sp_data[31:0]; +end + +parameter IDLE = 3'b000; +parameter BUSY1 = 3'b001; +parameter BUSY_LSU1 = 3'b010; +parameter BUSY_DIV1 = 3'b011; +parameter BUSY2 = 3'b100; +parameter BUSY_LSU2 = 3'b110; +parameter BUSY_DIV2 = 3'b111; + +always @(posedge reg_sm_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + reg_cur_st[2:0] <= IDLE; + else if(rtu_idu_flush_fe) + reg_cur_st[2:0] <= IDLE; + else + reg_cur_st[2:0] <= reg_nxt_st[2:0]; +end + +// &CombBeg; @97 +always @( reg_cur_st[2:0] + or reg_fwd_en2_x + or write_is_en + or write_is_div_en + or write_in_en + or reg_fwd_en1_x + or reg_fwd_en0_x + or write_is_ld_en) +begin +case(reg_cur_st[2:0]) + IDLE: + begin + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + end + BUSY1: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + end + BUSY_LSU1: + begin + if(reg_fwd_en1_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else + reg_nxt_st[2:0] = BUSY_LSU1; + end + BUSY_DIV1: + begin + if(reg_fwd_en0_x | reg_fwd_en2_x) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU1; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_DIV1; + end + BUSY2: + begin + if(write_in_en) + if(write_is_en) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY2; + else + reg_nxt_st[2:0] = BUSY1; + else + reg_nxt_st[2:0] = BUSY2; + end + BUSY_DIV2: + begin + if(reg_fwd_en0_x) + if(write_is_div_en) + reg_nxt_st[2:0] = BUSY_DIV2; + else + reg_nxt_st[2:0] = BUSY_DIV1; + else + reg_nxt_st[2:0] = BUSY_DIV2; + end + BUSY_LSU2: + begin + if(reg_fwd_en1_x) + if(write_is_ld_en) + reg_nxt_st[2:0] = BUSY_LSU2; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = IDLE; + else + reg_nxt_st[2:0] = BUSY_LSU1; + else if(reg_fwd_en2_x) + reg_nxt_st[2:0] = BUSY_LSU1; + else + reg_nxt_st[2:0] = BUSY_LSU2; + end + default: + begin + reg_nxt_st[2:0] = IDLE; + end +endcase +// &CombEnd; @209 +end + +assign reg_busy_st_y[2:0] = reg_cur_st[2:0]; +assign reg_dout_y[31:0] = write_in_data[31:0]; + +// &ModuleEnd; @214 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_split.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_split.v new file mode 100644 index 0000000000000000000000000000000000000000..7586a657117c02606422a1963f7f5156c14854e4 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_split.v @@ -0,0 +1,345 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("pa_idu_cfig.h"); @23 +// &ModuleBeg; @24 +module pa_idu_split( + cpurst_b, + ctrl_split_bkpt_vld, + ctrl_split_stall, + decd_split_dst_idx, + decd_split_opcode, + decd_split_req, + decd_split_rs1_idx, + decd_split_rs2_idx, + decd_split_rs2_vld, + idu_misc_cpuclk, + ifu_idu_chgflw_flush, + ifu_idu_id_inst_vld, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_flush_fe, + split_ctrl_cancel, + split_ctrl_icg_en, + split_ctrl_stall, + split_decd_ag_imm, + split_decd_ag_imm_vld, + split_decd_dp_sel, + split_decd_dst_idx, + split_decd_dst_vld, + split_decd_func, + split_decd_rs1_idx, + split_decd_rs1_vld, + split_decd_rs2_idx, + split_decd_rs2_imm, + split_decd_rs2_imm_vld, + split_decd_rs2_vld, + split_decd_sel, + split_decd_split, + split_top_cur_st +); + +// &Ports; @25 +input cpurst_b; +input ctrl_split_bkpt_vld; +input ctrl_split_stall; +input [4 :0] decd_split_dst_idx; +input [6 :0] decd_split_opcode; +input decd_split_req; +input [4 :0] decd_split_rs1_idx; +input [4 :0] decd_split_rs2_idx; +input decd_split_rs2_vld; +input idu_misc_cpuclk; +input ifu_idu_chgflw_flush; +input ifu_idu_id_inst_vld; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_flush_fe; +output split_ctrl_cancel; +output split_ctrl_icg_en; +output split_ctrl_stall; +output [31:0] split_decd_ag_imm; +output split_decd_ag_imm_vld; +output split_decd_dp_sel; +output [5 :0] split_decd_dst_idx; +output split_decd_dst_vld; +output [19:0] split_decd_func; +output [5 :0] split_decd_rs1_idx; +output split_decd_rs1_vld; +output [5 :0] split_decd_rs2_idx; +output [31:0] split_decd_rs2_imm; +output split_decd_rs2_imm_vld; +output split_decd_rs2_vld; +output [5 :0] split_decd_sel; +output split_decd_split; +output [2 :0] split_top_cur_st; + +// &Regs; @26 +reg [19:0] amo_alu_func; +reg [2 :0] split_cur_state; +reg [5 :0] split_decd_dst_idx; +reg split_decd_dst_vld; +reg [19:0] split_decd_func; +reg split_decd_rs2_imm_vld; +reg split_decd_rs2_vld; +reg [5 :0] split_decd_sel; +reg [2 :0] split_next_state; + +// &Wires; @27 +wire amo_inst; +wire amoswap; +wire atm_aq; +wire atm_rl; +wire cpurst_b; +wire ctrl_split_bkpt_vld; +wire ctrl_split_stall; +wire [4 :0] decd_split_dst_idx; +wire [6 :0] decd_split_opcode; +wire decd_split_req; +wire [4 :0] decd_split_rs1_idx; +wire [4 :0] decd_split_rs2_idx; +wire decd_split_rs2_vld; +wire idu_misc_cpuclk; +wire ifu_idu_chgflw_flush; +wire ifu_idu_id_inst_vld; +wire lr_inst; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_flush_fe; +wire sc_inst; +wire split_ctrl_cancel; +wire split_ctrl_icg_en; +wire split_ctrl_stall; +wire [31:0] split_decd_ag_imm; +wire split_decd_ag_imm_vld; +wire split_decd_dp_sel; +wire [5 :0] split_decd_rs1_idx; +wire split_decd_rs1_vld; +wire [5 :0] split_decd_rs2_idx; +wire [31:0] split_decd_rs2_imm; +wire split_decd_split; +wire split_req_vld; +wire [2 :0] split_top_cur_st; + + +//========================================================== +// Split Module +// 1. ICG instance +// 2. Split function decode +// 3. Split FSM +// 4. Split instruction information +// 5. Output +//========================================================== +parameter IDLE = 3'b111; +parameter FENCE_1 = 3'b000; +parameter LLSC = 3'b001; +parameter AMO_LD = 3'b010; +parameter AMO_ALU = 3'b011; +parameter AMO_ST = 3'b100; +parameter AMO_MOV = 3'b101; +parameter FENCE_2 = 3'b110; + +always @ (posedge idu_misc_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + split_cur_state[2:0] <= IDLE; + else if (rtu_idu_flush_fe | ifu_idu_chgflw_flush | rtu_idu_ex1_int_dis_stall_req) + split_cur_state[2:0] <= IDLE; + else if (~ctrl_split_stall) + split_cur_state[2:0] <= split_next_state[2:0]; + else + split_cur_state[2:0] <= split_cur_state[2:0]; +end + +assign split_req_vld = ifu_idu_id_inst_vld & decd_split_req & !ctrl_split_bkpt_vld; + +// &CombBeg; @60 +always @( split_req_vld + or split_cur_state[2:0] + or atm_aq + or amo_inst) +begin + case(split_cur_state[2:0]) + IDLE: begin + if (split_req_vld) + split_next_state[2:0] = FENCE_1; + else + split_next_state[2:0] = IDLE; + end + FENCE_1: begin + split_next_state[2:0] = amo_inst ? AMO_LD : LLSC; + end + LLSC: begin + if (atm_aq) + split_next_state[2:0] = FENCE_2; + else + split_next_state[2:0] = IDLE; + end + AMO_LD: split_next_state[2:0] = AMO_ALU; + AMO_ALU: split_next_state[2:0] = AMO_ST; + AMO_ST: split_next_state[2:0] = AMO_MOV; + AMO_MOV: begin + if (atm_aq) + split_next_state[2:0] = FENCE_2; + else + split_next_state[2:0] = IDLE; + end + FENCE_2: split_next_state[2:0] = IDLE; + default: split_next_state[2:0] = IDLE; + endcase +// &CombEnd; @89 +end + +// &Force("output","split_ctrl_stall"); @91 + +assign split_ctrl_stall = (split_cur_state[2:0] == IDLE) & split_req_vld | + (split_cur_state[2:0] == FENCE_1) | + (split_cur_state[2:0] == LLSC) & atm_aq | + (split_cur_state[2:0] == AMO_LD) | + (split_cur_state[2:0] == AMO_ALU) | + (split_cur_state[2:0] == AMO_ST) | + (split_cur_state[2:0] == AMO_MOV) & atm_aq; + +assign split_decd_split = split_ctrl_stall; +assign split_ctrl_cancel = (split_cur_state[2:0] == IDLE) & split_req_vld; +assign split_decd_dp_sel = ~(split_cur_state[2:0] == IDLE); + +// &Force("output", "split_decd_sel"); @105 +// &CombBeg; @106 +always @( atm_rl + or amo_alu_func[19:0] + or split_cur_state[2:0] + or amoswap + or decd_split_opcode[4:2] + or decd_split_dst_idx[4:0] + or decd_split_rs2_vld) +begin + case(split_cur_state[2:0]) + FENCE_1: begin + split_decd_sel[`SEL_WIDTH-1:0] = atm_rl ? `SEL_CP0 : `SEL_ALU; + split_decd_func[`FUNC_WIDTH-1:0] = atm_rl ? `FUNC_FENCE: `FUNC_ADD; + split_decd_rs2_imm_vld = atm_rl ? 1'b0 : 1'b1; + split_decd_dst_vld = atm_rl ? 1'b0 : 1'b1; + split_decd_dst_idx[5:0] = {1'b0,5'b0}; + split_decd_rs2_vld = 1'b0; + end + LLSC: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + split_decd_func[`FUNC_WIDTH-1:0] = {10'b0, 5'b00010, 1'b0,1'b0, decd_split_opcode[4:2]}; + split_decd_rs2_imm_vld = 1'b0; + split_decd_dst_vld = 1'b1; + split_decd_dst_idx[5:0] = {1'b0,decd_split_dst_idx[4:0]}; + split_decd_rs2_vld = decd_split_rs2_vld; + end + AMO_LD: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + split_decd_func[`FUNC_WIDTH-1:0] = {10'b0, 5'b00010, 1'b0,1'b0,3'b100}; + split_decd_rs2_imm_vld = 1'b0; + split_decd_dst_vld = 1'b1; + split_decd_dst_idx[5:0] = {1'b1,5'b0}; + split_decd_rs2_vld = 1'b0; + end + AMO_ALU: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + split_decd_func[`FUNC_WIDTH-1:0] = amo_alu_func[`FUNC_WIDTH-1:0]; + split_decd_rs2_imm_vld = amoswap; + split_decd_dst_vld = 1'b1; + split_decd_dst_idx[5:0] = {1'b1,5'b1}; + split_decd_rs2_vld = 1'b1; + end + AMO_ST: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_LSU; + split_decd_func[`FUNC_WIDTH-1:0] = {10'b0, 5'b00010, 1'b0,1'b0,3'b101}; + split_decd_rs2_imm_vld = 1'b0; + split_decd_dst_vld = 1'b0; + split_decd_dst_idx[5:0] = {1'b0,decd_split_dst_idx[4:0]}; + split_decd_rs2_vld = 1'b1; + end + AMO_MOV: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_ALU; + split_decd_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + split_decd_rs2_imm_vld = 1'b1; + split_decd_dst_vld = 1'b1; + split_decd_dst_idx[5:0] = {1'b0,decd_split_dst_idx[4:0]}; + split_decd_rs2_vld = 1'b0; + end + FENCE_2: begin + split_decd_sel[`SEL_WIDTH-1:0] = `SEL_CP0; + split_decd_func[`FUNC_WIDTH-1:0] = `FUNC_FENCE; + split_decd_rs2_imm_vld = 1'b0; + split_decd_dst_vld = 1'b0; + split_decd_dst_idx[5:0] = {1'b0,decd_split_dst_idx[4:0]}; + split_decd_rs2_vld = 1'b0; + end + default: begin + split_decd_sel[`SEL_WIDTH-1:0] = {`SEL_WIDTH{1'bx}}; + split_decd_func[`FUNC_WIDTH-1:0] = {`FUNC_WIDTH{1'bx}}; + split_decd_rs2_imm_vld = 1'b0; + split_decd_dst_vld = 1'b0; + split_decd_dst_idx[5:0] = {1'b0,decd_split_dst_idx[4:0]}; + split_decd_rs2_vld = 1'b0; + end + endcase +// &CombEnd; @173 +end + +assign split_decd_rs2_imm[31:0]= 32'b0; + +assign split_decd_rs2_idx[5:0] = (split_cur_state[2:0] == AMO_ST) + ? {1'b1,5'b1} + : ((split_cur_state[2:0] == AMO_ALU) + ? {1'b1, 5'b0} + : {1'b0, decd_split_rs2_idx[4:0]}); + +assign split_decd_rs1_vld = 1'b1; +assign split_decd_rs1_idx[5:0] = (split_cur_state[2:0] == AMO_ALU) + ? {1'b0, decd_split_rs2_idx[4:0]} + : ((split_cur_state[2:0] == AMO_MOV) + ? {1'b1, 5'b0} + : {1'b0, decd_split_rs1_idx[4:0]}); + +assign split_decd_ag_imm_vld = split_decd_sel[4] | + split_decd_sel[5]; +assign split_decd_ag_imm[31:0] = 32'b0; + +assign atm_aq = decd_split_opcode[1]; +assign atm_rl = decd_split_opcode[0]; +assign amoswap = decd_split_opcode[6:2] == 5'b00001; +assign lr_inst = decd_split_opcode[6:2] == 5'b00010; +assign sc_inst = decd_split_opcode[6:2] == 5'b00011; +assign amo_inst= ~(lr_inst | sc_inst); + +// &CombBeg; @201 +always @( decd_split_opcode[6:2]) +begin + case(decd_split_opcode[6:2]) + 5'b00001: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + 5'b00000: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_ADD; + 5'b00100: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_XOR; + 5'b01100: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_AND; + 5'b01000: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_OR; + 5'b10000: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_MIN; + 5'b10100: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_MAX; + 5'b11000: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_MINU; + 5'b11100: amo_alu_func[`FUNC_WIDTH-1:0] = `FUNC_MAXU; + default : amo_alu_func[`FUNC_WIDTH-1:0] = {`FUNC_WIDTH{1'bx}}; + endcase +// &CombEnd; @214 +end + +assign split_ctrl_icg_en = split_cur_state[2:0] != IDLE | split_req_vld; +assign split_top_cur_st[2:0] = split_cur_state[2:0]; + +// &ModuleEnd; @219 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..a5b57bbd56cba4dcf376606ded3351c25c9cb402 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/idu/rtl/pa_idu_top.v @@ -0,0 +1,1746 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("pa_idu_cfig.h"); @23 +// &ModuleBeg; @24 +module pa_idu_top( + cp0_idu_ex1_stall, + cp0_idu_fs, + cp0_idu_icg_en, + cp0_idu_mcause, + cp0_idu_mepc, + cp0_idu_rm, + cp0_idu_sp_use_scratch, + cp0_idu_sp_wdata, + cp0_idu_sp_wen, + cp0_idu_sp_wen_gate, + cp0_idu_spec_push_en, + cp0_idu_swap_sp_en, + cp0_yy_clk_en, + cp0_yy_cskyisaee, + cp0_yy_mach_mode, + cpurst_b, + forever_cpuclk, + fpu_idu_ex1_stall, + fpu_idu_fwd_data, + fpu_idu_fwd_freg, + fpu_idu_fwd_vld, + fpu_xx_no_op, + idu_cp0_ex1_cmplt_dp_sel, + idu_cp0_ex1_dst_idx, + idu_cp0_ex1_dst_vld, + idu_cp0_ex1_expt_high, + idu_cp0_ex1_expt_type, + idu_cp0_ex1_expt_vld, + idu_cp0_ex1_func, + idu_cp0_ex1_gateclk_sel, + idu_cp0_ex1_halt_info, + idu_cp0_ex1_inst_len, + idu_cp0_ex1_ipush_spec_fail, + idu_cp0_ex1_opcode, + idu_cp0_ex1_rs1, + idu_cp0_ex1_rs2, + idu_cp0_ex1_sel, + idu_cp0_ex1_split_inst, + idu_cp0_ex1_tail_fail, + idu_cp0_id_tail_vld, + idu_cp0_ipop_data, + idu_cp0_mcause_wen, + idu_cp0_mepc_wen, + idu_cp0_sp_reg, + idu_cp0_sp_swap_pending, + idu_cp0_sp_swap_req, + idu_cp0_sp_swap_req_gate, + idu_dtu_debug_info, + idu_dtu_fpr_info, + idu_fpu_ex1_cmplt_dp_sel, + idu_fpu_ex1_dst_freg, + idu_fpu_ex1_dst_freg_vld, + idu_fpu_ex1_dst_preg, + idu_fpu_ex1_eu_sel, + idu_fpu_ex1_func, + idu_fpu_ex1_gateclk_vld, + idu_fpu_ex1_inst_vld, + idu_fpu_ex1_rm, + idu_fpu_ex1_srcf0, + idu_fpu_ex1_srcf1, + idu_fpu_ex1_srcf2, + idu_fpu_ex1_srci, + idu_ifu_id_stall, + idu_ifu_tail_vld, + idu_ifu_tail_vld_gate, + idu_ifu_x1, + idu_iu_ex1_ag_imm, + idu_iu_ex1_alu_cmplt_dp_sel, + idu_iu_ex1_alu_gateclk_sel, + idu_iu_ex1_alu_sel, + idu_iu_ex1_bht_pred, + idu_iu_ex1_bju_cmplt_dp_sel, + idu_iu_ex1_bju_depd_lsu_src0, + idu_iu_ex1_bju_depd_lsu_src1, + idu_iu_ex1_bju_gateclk_sel, + idu_iu_ex1_bju_sel, + idu_iu_ex1_bju_use_pc, + idu_iu_ex1_div_cmplt_dp_sel, + idu_iu_ex1_div_gateclk_sel, + idu_iu_ex1_div_sel, + idu_iu_ex1_dst_preg, + idu_iu_ex1_func, + idu_iu_ex1_gateclk_vld, + idu_iu_ex1_inst_len, + idu_iu_ex1_inst_vld, + idu_iu_ex1_ipop_int_mask, + idu_iu_ex1_ipush_mie_en, + idu_iu_ex1_ipush_spec_fail, + idu_iu_ex1_mul_cmplt_dp_sel, + idu_iu_ex1_mul_gateclk_sel, + idu_iu_ex1_mul_high_sel, + idu_iu_ex1_mul_sel, + idu_iu_ex1_rd_pair, + idu_iu_ex1_split, + idu_iu_ex1_src0, + idu_iu_ex1_src0_reg, + idu_iu_ex1_src1, + idu_iu_ex1_src1_reg, + idu_iu_ex1_src2, + idu_iu_ex1_tail_int_vld, + idu_iu_ex1_wb_vld, + idu_iu_tail_fail, + idu_iu_tail_fail_gate, + idu_lsu_ex1_ag_imm, + idu_lsu_ex1_base, + idu_lsu_ex1_base_sel, + idu_lsu_ex1_base_wb, + idu_lsu_ex1_data, + idu_lsu_ex1_dest_reg, + idu_lsu_ex1_dest_vld, + idu_lsu_ex1_dp_sel, + idu_lsu_ex1_fls, + idu_lsu_ex1_func, + idu_lsu_ex1_gateclk_sel, + idu_lsu_ex1_halt_info, + idu_lsu_ex1_ipop_int_mask, + idu_lsu_ex1_ipush_spec, + idu_lsu_ex1_length, + idu_lsu_ex1_offset_sel, + idu_lsu_ex1_sel, + idu_lsu_ex1_sign_extend, + idu_lsu_ex1_size, + idu_lsu_ex1_split, + idu_lsu_ex1_src0_reg, + idu_lsu_ex1_src1_depd, + idu_lsu_ex1_src1_reg, + idu_yy_xx_tail_ack, + ifu_idu_chgflw_flush, + ifu_idu_id_expt_high, + ifu_idu_id_expt_vld, + ifu_idu_id_halt_info, + ifu_idu_id_inst, + ifu_idu_id_inst_vld, + ifu_idu_id_pred_taken, + ifu_idu_warm_up, + iu_idu_bju_global_stall, + iu_idu_bju_stall, + iu_idu_ex1_fwd_data, + iu_idu_ex1_fwd_preg, + iu_idu_ex1_fwd_vld, + iu_idu_ex1_src1_update_value, + iu_idu_ex1_stall, + iu_idu_ex2_div_vld, + iu_idu_ex2_fwd_data0, + iu_idu_ex2_fwd_data1, + iu_idu_ex2_fwd_preg0, + iu_idu_ex2_fwd_preg1, + iu_idu_ex2_fwd_vld0, + iu_idu_ex2_fwd_vld1, + iu_idu_ex2_inst_vld, + iu_idu_ex2_rd_pair, + iu_idu_id_stall, + iu_xx_no_op, + iu_yy_xx_cancel, + lsu_idu_ex1_halt_info, + lsu_idu_ex1_halt_info_update_en, + lsu_idu_ex1_src1_update_en, + lsu_idu_ex1_src1_update_en_gate, + lsu_idu_ex1_stall, + lsu_idu_ex2_ffwd_data, + lsu_idu_ex2_ffwd_vld, + lsu_idu_ex2_fwd_data, + lsu_idu_ex2_fwd_freg, + lsu_idu_ex2_fwd_preg, + lsu_idu_ex2_fwd_vld, + lsu_idu_ex3_ffwd_data, + lsu_idu_ex3_ffwd_vld, + lsu_idu_ex3_fwd_data, + lsu_idu_ex3_fwd_freg, + lsu_idu_ex3_fwd_preg, + lsu_idu_ex3_fwd_vld, + lsu_idu_global_stall, + lsu_idu_update_addr, + lsu_idu_update_en, + lsu_idu_update_en_gate, + lsu_idu_update_offset, + lsu_xx_no_op, + pad_yy_icg_scan_en, + rtu_idu_ex1_int_dis_stall_gateclk_req, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_ex2_ipush_spec_inst_expt_vld, + rtu_idu_ex2_ipush_spec_inst_halt_info_vld, + rtu_idu_fgpr_wb_data, + rtu_idu_fgpr_wb_flsu_vld, + rtu_idu_fgpr_wb_reg, + rtu_idu_fgpr_wb_vld, + rtu_idu_flush_fe, + rtu_idu_flush_stall, + rtu_idu_id_tail_int_vld, + rtu_idu_inst_retire, + rtu_idu_late_flush, + rtu_idu_wb0_data, + rtu_idu_wb0_fpu_vld, + rtu_idu_wb0_preg, + rtu_idu_wb0_vld, + rtu_idu_wb1_data, + rtu_idu_wb1_lsu_vld, + rtu_idu_wb1_preg, + rtu_idu_wb1_vld, + rtu_idu_wb2_data, + rtu_idu_wb2_preg, + rtu_idu_wb2_vld, + rtu_xx_ex1_stall, + rtu_xx_no_op, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vld, + rtu_yy_xx_flush +); + +// &Ports; @25 +input cp0_idu_ex1_stall; +input [1 :0] cp0_idu_fs; +input cp0_idu_icg_en; +input [31:0] cp0_idu_mcause; +input [31:0] cp0_idu_mepc; +input [2 :0] cp0_idu_rm; +input cp0_idu_sp_use_scratch; +input [31:0] cp0_idu_sp_wdata; +input cp0_idu_sp_wen; +input cp0_idu_sp_wen_gate; +input cp0_idu_spec_push_en; +input cp0_idu_swap_sp_en; +input cp0_yy_clk_en; +input cp0_yy_cskyisaee; +input cp0_yy_mach_mode; +input cpurst_b; +input forever_cpuclk; +input fpu_idu_ex1_stall; +input [31:0] fpu_idu_fwd_data; +input [4 :0] fpu_idu_fwd_freg; +input fpu_idu_fwd_vld; +input fpu_xx_no_op; +input ifu_idu_chgflw_flush; +input ifu_idu_id_expt_high; +input ifu_idu_id_expt_vld; +input [14:0] ifu_idu_id_halt_info; +input [31:0] ifu_idu_id_inst; +input ifu_idu_id_inst_vld; +input [1 :0] ifu_idu_id_pred_taken; +input ifu_idu_warm_up; +input iu_idu_bju_global_stall; +input iu_idu_bju_stall; +input [31:0] iu_idu_ex1_fwd_data; +input [5 :0] iu_idu_ex1_fwd_preg; +input iu_idu_ex1_fwd_vld; +input [31:0] iu_idu_ex1_src1_update_value; +input iu_idu_ex1_stall; +input iu_idu_ex2_div_vld; +input [31:0] iu_idu_ex2_fwd_data0; +input [31:0] iu_idu_ex2_fwd_data1; +input [5 :0] iu_idu_ex2_fwd_preg0; +input [5 :0] iu_idu_ex2_fwd_preg1; +input iu_idu_ex2_fwd_vld0; +input iu_idu_ex2_fwd_vld1; +input iu_idu_ex2_inst_vld; +input iu_idu_ex2_rd_pair; +input iu_idu_id_stall; +input iu_xx_no_op; +input iu_yy_xx_cancel; +input [14:0] lsu_idu_ex1_halt_info; +input lsu_idu_ex1_halt_info_update_en; +input lsu_idu_ex1_src1_update_en; +input lsu_idu_ex1_src1_update_en_gate; +input lsu_idu_ex1_stall; +input [31:0] lsu_idu_ex2_ffwd_data; +input lsu_idu_ex2_ffwd_vld; +input [31:0] lsu_idu_ex2_fwd_data; +input [4 :0] lsu_idu_ex2_fwd_freg; +input [5 :0] lsu_idu_ex2_fwd_preg; +input lsu_idu_ex2_fwd_vld; +input [31:0] lsu_idu_ex3_ffwd_data; +input lsu_idu_ex3_ffwd_vld; +input [31:0] lsu_idu_ex3_fwd_data; +input [4 :0] lsu_idu_ex3_fwd_freg; +input [5 :0] lsu_idu_ex3_fwd_preg; +input lsu_idu_ex3_fwd_vld; +input lsu_idu_global_stall; +input [31:0] lsu_idu_update_addr; +input lsu_idu_update_en; +input lsu_idu_update_en_gate; +input [31:0] lsu_idu_update_offset; +input lsu_xx_no_op; +input pad_yy_icg_scan_en; +input rtu_idu_ex1_int_dis_stall_gateclk_req; +input rtu_idu_ex1_int_dis_stall_req; +input rtu_idu_ex2_ipush_spec_inst_expt_vld; +input rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +input [31:0] rtu_idu_fgpr_wb_data; +input rtu_idu_fgpr_wb_flsu_vld; +input [4 :0] rtu_idu_fgpr_wb_reg; +input rtu_idu_fgpr_wb_vld; +input rtu_idu_flush_fe; +input rtu_idu_flush_stall; +input rtu_idu_id_tail_int_vld; +input rtu_idu_inst_retire; +input rtu_idu_late_flush; +input [31:0] rtu_idu_wb0_data; +input rtu_idu_wb0_fpu_vld; +input [5 :0] rtu_idu_wb0_preg; +input rtu_idu_wb0_vld; +input [31:0] rtu_idu_wb1_data; +input rtu_idu_wb1_lsu_vld; +input [5 :0] rtu_idu_wb1_preg; +input rtu_idu_wb1_vld; +input [31:0] rtu_idu_wb2_data; +input [5 :0] rtu_idu_wb2_preg; +input rtu_idu_wb2_vld; +input rtu_xx_ex1_stall; +input rtu_xx_no_op; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_flush; +output idu_cp0_ex1_cmplt_dp_sel; +output [5 :0] idu_cp0_ex1_dst_idx; +output idu_cp0_ex1_dst_vld; +output idu_cp0_ex1_expt_high; +output idu_cp0_ex1_expt_type; +output idu_cp0_ex1_expt_vld; +output [19:0] idu_cp0_ex1_func; +output idu_cp0_ex1_gateclk_sel; +output [14:0] idu_cp0_ex1_halt_info; +output idu_cp0_ex1_inst_len; +output idu_cp0_ex1_ipush_spec_fail; +output [31:0] idu_cp0_ex1_opcode; +output [31:0] idu_cp0_ex1_rs1; +output [11:0] idu_cp0_ex1_rs2; +output idu_cp0_ex1_sel; +output idu_cp0_ex1_split_inst; +output idu_cp0_ex1_tail_fail; +output idu_cp0_id_tail_vld; +output [31:0] idu_cp0_ipop_data; +output idu_cp0_mcause_wen; +output idu_cp0_mepc_wen; +output [31:0] idu_cp0_sp_reg; +output idu_cp0_sp_swap_pending; +output idu_cp0_sp_swap_req; +output idu_cp0_sp_swap_req_gate; +output [21:0] idu_dtu_debug_info; +output [95:0] idu_dtu_fpr_info; +output idu_fpu_ex1_cmplt_dp_sel; +output [4 :0] idu_fpu_ex1_dst_freg; +output idu_fpu_ex1_dst_freg_vld; +output [4 :0] idu_fpu_ex1_dst_preg; +output [2 :0] idu_fpu_ex1_eu_sel; +output [9 :0] idu_fpu_ex1_func; +output idu_fpu_ex1_gateclk_vld; +output idu_fpu_ex1_inst_vld; +output [2 :0] idu_fpu_ex1_rm; +output [31:0] idu_fpu_ex1_srcf0; +output [31:0] idu_fpu_ex1_srcf1; +output [31:0] idu_fpu_ex1_srcf2; +output [31:0] idu_fpu_ex1_srci; +output idu_ifu_id_stall; +output idu_ifu_tail_vld; +output idu_ifu_tail_vld_gate; +output [31:0] idu_ifu_x1; +output [31:0] idu_iu_ex1_ag_imm; +output idu_iu_ex1_alu_cmplt_dp_sel; +output idu_iu_ex1_alu_gateclk_sel; +output idu_iu_ex1_alu_sel; +output [1 :0] idu_iu_ex1_bht_pred; +output idu_iu_ex1_bju_cmplt_dp_sel; +output idu_iu_ex1_bju_depd_lsu_src0; +output idu_iu_ex1_bju_depd_lsu_src1; +output idu_iu_ex1_bju_gateclk_sel; +output idu_iu_ex1_bju_sel; +output idu_iu_ex1_bju_use_pc; +output idu_iu_ex1_div_cmplt_dp_sel; +output idu_iu_ex1_div_gateclk_sel; +output idu_iu_ex1_div_sel; +output [5 :0] idu_iu_ex1_dst_preg; +output [19:0] idu_iu_ex1_func; +output idu_iu_ex1_gateclk_vld; +output idu_iu_ex1_inst_len; +output idu_iu_ex1_inst_vld; +output idu_iu_ex1_ipop_int_mask; +output idu_iu_ex1_ipush_mie_en; +output idu_iu_ex1_ipush_spec_fail; +output idu_iu_ex1_mul_cmplt_dp_sel; +output idu_iu_ex1_mul_gateclk_sel; +output idu_iu_ex1_mul_high_sel; +output idu_iu_ex1_mul_sel; +output idu_iu_ex1_rd_pair; +output idu_iu_ex1_split; +output [31:0] idu_iu_ex1_src0; +output [5 :0] idu_iu_ex1_src0_reg; +output [31:0] idu_iu_ex1_src1; +output [5 :0] idu_iu_ex1_src1_reg; +output [31:0] idu_iu_ex1_src2; +output idu_iu_ex1_tail_int_vld; +output idu_iu_ex1_wb_vld; +output idu_iu_tail_fail; +output idu_iu_tail_fail_gate; +output [31:0] idu_lsu_ex1_ag_imm; +output [31:0] idu_lsu_ex1_base; +output idu_lsu_ex1_base_sel; +output idu_lsu_ex1_base_wb; +output [31:0] idu_lsu_ex1_data; +output [5 :0] idu_lsu_ex1_dest_reg; +output idu_lsu_ex1_dest_vld; +output idu_lsu_ex1_dp_sel; +output idu_lsu_ex1_fls; +output [3 :0] idu_lsu_ex1_func; +output idu_lsu_ex1_gateclk_sel; +output [14:0] idu_lsu_ex1_halt_info; +output idu_lsu_ex1_ipop_int_mask; +output idu_lsu_ex1_ipush_spec; +output idu_lsu_ex1_length; +output idu_lsu_ex1_offset_sel; +output idu_lsu_ex1_sel; +output idu_lsu_ex1_sign_extend; +output [1 :0] idu_lsu_ex1_size; +output idu_lsu_ex1_split; +output [5 :0] idu_lsu_ex1_src0_reg; +output idu_lsu_ex1_src1_depd; +output [5 :0] idu_lsu_ex1_src1_reg; +output idu_yy_xx_tail_ack; + +// &Regs; @26 + +// &Wires; @27 +wire cp0_idu_ex1_stall; +wire [1 :0] cp0_idu_fs; +wire cp0_idu_icg_en; +wire [31:0] cp0_idu_mcause; +wire [31:0] cp0_idu_mepc; +wire [2 :0] cp0_idu_rm; +wire cp0_idu_sp_use_scratch; +wire [31:0] cp0_idu_sp_wdata; +wire cp0_idu_sp_wen; +wire cp0_idu_sp_wen_gate; +wire cp0_idu_spec_push_en; +wire cp0_idu_swap_sp_en; +wire cp0_yy_clk_en; +wire cp0_yy_cskyisaee; +wire cp0_yy_mach_mode; +wire cpurst_b; +wire ctrl_dp_ex1_bju_sel; +wire ctrl_dp_ex1_div_sel; +wire [5 :0] ctrl_dp_ex1_dst_preg; +wire ctrl_dp_ex1_dst_vld; +wire ctrl_dp_ex1_fls; +wire ctrl_dp_ex1_inst_vld; +wire ctrl_dp_ex1_lsu_sel; +wire ctrl_dp_ex1_rs1_dep; +wire ctrl_dp_ex1_rs2_dep; +wire ctrl_dp_ex1_st_sel; +wire ctrl_dp_pipe_down; +wire ctrl_dp_pipe_down_gate; +wire ctrl_fpr_ex1_int_spec; +wire ctrl_gpr_div_inst; +wire [4 :0] ctrl_gpr_ex1_dst_preg; +wire ctrl_gpr_ex1_int_spec; +wire ctrl_gpr_id_rd1_vld; +wire ctrl_gpr_id_rd2_vld; +wire [5 :0] ctrl_gpr_id_wr_idx1; +wire [5 :0] ctrl_gpr_id_wr_idx2; +wire ctrl_gpr_ld_inst; +wire ctrl_gpr_wr_issue1; +wire ctrl_hs_be_idle; +wire ctrl_hs_bkpt_vld; +wire ctrl_hs_no_op; +wire ctrl_hs_stall; +wire ctrl_id_fp_ex1_inst_vld; +wire ctrl_id_fp_ex1_lsu_sel; +wire ctrl_id_fp_id_expt_vld; +wire ctrl_id_fp_id_inst_vld; +wire ctrl_id_fp_id_stall; +wire ctrl_id_fp_pipe_down; +wire ctrl_id_fp_st_rs2_dep; +wire ctrl_id_fp_uncmit; +wire ctrl_split_bkpt_vld; +wire ctrl_split_stall; +wire ctrl_top_bju_dep1_vld; +wire ctrl_top_bju_dep2_vld; +wire ctrl_top_cp0_stall; +wire ctrl_top_div_stall; +wire ctrl_top_ex1_fp_vld; +wire [5 :0] ctrl_top_ex1_sel; +wire ctrl_top_ex1_stall; +wire ctrl_top_ex1_vld; +wire ctrl_top_id_cancel; +wire ctrl_top_id_inst_vld; +wire ctrl_top_id_stall; +wire ctrl_top_ld_stall; +wire ctrl_top_norm_stall; +wire ctrl_top_st_dep_vld; +wire decd_ctrl_bju_use_pc; +wire [4 :0] decd_ctrl_id_func; +wire decd_ctrl_ill_expt; +wire decd_ctrl_inst_32bit; +wire [5 :0] decd_ctrl_rd1; +wire decd_ctrl_rd1_vld; +wire [5 :0] decd_ctrl_rd2; +wire decd_ctrl_rd2_vld; +wire decd_ctrl_sti_vld; +wire decd_ctrl_str_vld; +wire [5 :0] decd_ctrl_unit_sel; +wire [31:0] decd_dp_ag_imm; +wire decd_dp_ag_imm_vld; +wire [4 :0] decd_dp_csri_rs1; +wire decd_dp_csri_vld; +wire decd_dp_ex_st_rs2_vld; +wire [19:0] decd_dp_func; +wire [31:0] decd_dp_imm; +wire decd_dp_imm_vld; +wire decd_dp_lsr_vld; +wire decd_dp_lsu_sel; +wire decd_dp_mul_high_sel; +wire decd_dp_rd2_vld; +wire [5 :0] decd_dp_rs1_idx; +wire decd_dp_rs1_vld; +wire [5 :0] decd_dp_rs2_idx; +wire decd_dp_rs2_vld; +wire [5 :0] decd_dp_rs3_idx; +wire decd_dp_rs3_vld; +wire [5 :0] decd_dp_rs4_idx; +wire decd_dp_rs4_vld; +wire decd_dp_smal_vld; +wire decd_dp_split; +wire [4 :0] decd_fp_fpr_rd; +wire decd_fp_fpr_rd_vld; +wire [4 :0] decd_fp_fpr_rs1; +wire decd_fp_fpr_rs1_vld; +wire [4 :0] decd_fp_fpr_rs2; +wire decd_fp_fpr_rs2_vld; +wire [4 :0] decd_fp_fpr_rs3; +wire decd_fp_fpr_rs3_vld; +wire [9 :0] decd_fp_id_dp_func; +wire [4 :0] decd_fp_id_fp_dst_idx; +wire decd_fp_id_fp_dst_vld; +wire decd_fp_id_fp_inst_vld; +wire decd_fp_id_fp_lsu_sel; +wire [4 :0] decd_fp_id_fp_rs1_idx; +wire decd_fp_id_fp_rs1_vld; +wire [4 :0] decd_fp_id_fp_rs2_idx; +wire decd_fp_id_fp_rs2_vld; +wire [4 :0] decd_fp_id_fp_rs3_idx; +wire decd_fp_id_fp_rs3_vld; +wire [2 :0] decd_fp_id_fp_unit_sel; +wire [2 :0] decd_fp_id_rm; +wire [5 :0] decd_gpr_dep_rs1; +wire [5 :0] decd_gpr_dep_rs2; +wire decd_gpr_rd1_vld; +wire decd_gpr_rd2_vld; +wire [5 :0] decd_gpr_rs1; +wire decd_gpr_rs1_vld; +wire [5 :0] decd_gpr_rs2; +wire decd_gpr_rs2_vld; +wire [5 :0] decd_gpr_rs3; +wire decd_gpr_rs3_vld; +wire [5 :0] decd_gpr_rs4; +wire decd_gpr_rs4_vld; +wire decd_hs_ipop_vld; +wire decd_hs_ipush_vld; +wire [4 :0] decd_split_dst_idx; +wire [6 :0] decd_split_opcode; +wire decd_split_req; +wire [4 :0] decd_split_rs1_idx; +wire [4 :0] decd_split_rs2_idx; +wire decd_split_rs2_vld; +wire dp_ctrl_ex1_ex_st_rs2_vld; +wire dp_ctrl_ex1_st_vld; +wire dp_ctrl_rs1_dep_ex1_dst; +wire dp_ctrl_rs1_fwd_lsu; +wire dp_ctrl_rs1_stall_upd; +wire dp_ctrl_rs2_dep_ex1_dst; +wire dp_ctrl_rs2_fwd_lsu; +wire dp_ctrl_rs2_stall_upd; +wire dp_ctrl_rs3_dep_ex1_dst; +wire dp_ctrl_rs3_fwd_lsu; +wire dp_ctrl_rs3_stall_upd; +wire dp_ctrl_rs_norm_stall; +wire [31:0] dp_decd_rs2_aft_fwd; +wire dp_gpr_rs1_fwd_div; +wire dp_gpr_rs1_fwd_lsu; +wire dp_gpr_rs2_fwd_div; +wire dp_gpr_rs2_fwd_lsu; +wire dp_gpr_rs3_fwd_div; +wire dp_gpr_rs3_fwd_lsu; +wire dp_gpr_rs4_fwd_div; +wire dp_gpr_rs4_fwd_lsu; +wire dp_gpr_x2_busy; +wire dp_gpr_x2_busy2; +wire [4 :0] dp_id_fp_ex1_rs2_idx; +wire [5 :0] fdecd_ctrl_dst_idx; +wire fdecd_ctrl_dst_vld; +wire fdecd_ctrl_fls; +wire fdecd_ctrl_fp_inst_vld; +wire fdecd_ctrl_int_dst_vld; +wire fdecd_decd_fp_inst_vld; +wire fdecd_decd_ill_expt; +wire [31:0] fdecd_decd_imm; +wire fdecd_decd_imm_vld; +wire fdecd_decd_rd_int_vld; +wire fdecd_decd_rs1_int_vld; +wire fdecd_dp_rs1_int_vld; +wire [5 :0] fdecd_dp_rs2_idx; +wire fdecd_dp_rs2_vld; +wire forever_cpuclk; +wire fpr_id_fp_rd_busy; +wire fpr_id_fp_rd_busy_lsu; +wire [31:0] fpr_id_fp_rs1; +wire fpr_id_fp_rs1_busy; +wire fpr_id_fp_rs1_busy_lsu; +wire [31:0] fpr_id_fp_rs2; +wire fpr_id_fp_rs2_busy; +wire fpr_id_fp_rs2_busy_lsu; +wire [31:0] fpr_id_fp_rs3; +wire fpr_id_fp_rs3_busy; +wire fpr_id_fp_rs3_busy_lsu; +wire [31:0] fpr_top_reg_busy; +wire [31:0] fpr_top_reg_busy_div; +wire [31:0] fpr_top_reg_busy_lsu; +wire fpu_idu_ex1_stall; +wire [31:0] fpu_idu_fwd_data; +wire [4 :0] fpu_idu_fwd_freg; +wire fpu_idu_fwd_vld; +wire fpu_xx_no_op; +wire gpr_ctrl_rd1_busy_div; +wire gpr_ctrl_rd1_busy_lsu; +wire gpr_ctrl_rd2_busy_div; +wire gpr_ctrl_rd2_busy_lsu; +wire gpr_ctrl_rs1_busy_div; +wire gpr_ctrl_rs1_busy_lsu; +wire gpr_ctrl_rs1_busy_lsu2; +wire gpr_ctrl_rs2_busy_div; +wire gpr_ctrl_rs2_busy_lsu; +wire gpr_ctrl_rs2_busy_lsu2; +wire gpr_ctrl_rs3_busy_div; +wire gpr_ctrl_rs3_busy_lsu; +wire gpr_ctrl_rs3_busy_lsu2; +wire gpr_ctrl_rs4_busy_div; +wire gpr_ctrl_rs4_busy_lsu; +wire gpr_dp_id_x2_wr; +wire [31:0] gpr_dp_rs1; +wire [31:0] gpr_dp_rs2; +wire [31:0] gpr_dp_rs3; +wire [31:0] gpr_dp_rs4; +wire gpr_hs_sp_busy; +wire gpr_hs_sp_busy2; +wire gpr_hs_sp_wb; +wire hd_dp_rs2_sel; +wire hs_ctrl_cancel; +wire hs_ctrl_inst_vld; +wire hs_ctrl_stall; +wire hs_decd_dp_vld; +wire hs_decd_dst_vld; +wire [19:0] hs_decd_func; +wire [31:0] hs_decd_imm; +wire hs_decd_imm_vld; +wire [5 :0] hs_decd_rd; +wire [5 :0] hs_decd_rs1; +wire hs_decd_rs1_vld; +wire [5 :0] hs_decd_rs2; +wire hs_decd_rs2_imm_vld; +wire hs_decd_rs2_vld; +wire [5 :0] hs_decd_sel; +wire hs_decd_split; +wire hs_dp_ipop_int_mask; +wire hs_dp_ipop_tail; +wire hs_dp_ipop_tail_gate; +wire hs_dp_ipush_spec_fail; +wire hs_dp_mie_en; +wire hs_dp_rs2_mcause; +wire hs_dp_rs2_mepc; +wire hs_dp_sp_wb_pending; +wire hs_fdecd_dp_vld; +wire hs_gpr_wb_mask; +wire hs_gpr_wr_mask; +wire id_fp_ctrl_id_stall; +wire id_fp_ctrl_rs2_dep_ex1_dst; +wire id_fp_ctrl_rs2_stall_upd; +wire [31:0] id_fp_dp_srcf1; +wire [4 :0] id_fp_fpr_dst_freg; +wire id_fp_fpr_id_dst_vld; +wire id_fp_fpr_ld_inst; +wire id_fp_fpr_wr_issue; +wire idu_cp0_ex1_cmplt_dp_sel; +wire [5 :0] idu_cp0_ex1_dst_idx; +wire idu_cp0_ex1_dst_vld; +wire idu_cp0_ex1_expt_high; +wire idu_cp0_ex1_expt_type; +wire idu_cp0_ex1_expt_vld; +wire [19:0] idu_cp0_ex1_func; +wire idu_cp0_ex1_gateclk_sel; +wire [14:0] idu_cp0_ex1_halt_info; +wire idu_cp0_ex1_inst_len; +wire idu_cp0_ex1_ipush_spec_fail; +wire [31:0] idu_cp0_ex1_opcode; +wire [31:0] idu_cp0_ex1_rs1; +wire [11:0] idu_cp0_ex1_rs2; +wire idu_cp0_ex1_sel; +wire idu_cp0_ex1_split_inst; +wire idu_cp0_ex1_tail_fail; +wire idu_cp0_id_tail_vld; +wire [31:0] idu_cp0_ipop_data; +wire idu_cp0_mcause_wen; +wire idu_cp0_mepc_wen; +wire [31:0] idu_cp0_sp_reg; +wire idu_cp0_sp_swap_pending; +wire idu_cp0_sp_swap_req; +wire idu_cp0_sp_swap_req_gate; +wire [21:0] idu_dtu_debug_info; +wire [95:0] idu_dtu_fpr_info; +wire idu_fpu_ex1_cmplt_dp_sel; +wire [4 :0] idu_fpu_ex1_dst_freg; +wire idu_fpu_ex1_dst_freg_vld; +wire [4 :0] idu_fpu_ex1_dst_preg; +wire [2 :0] idu_fpu_ex1_eu_sel; +wire [9 :0] idu_fpu_ex1_func; +wire idu_fpu_ex1_gateclk_vld; +wire idu_fpu_ex1_inst_vld; +wire [2 :0] idu_fpu_ex1_rm; +wire [31:0] idu_fpu_ex1_srcf0; +wire [31:0] idu_fpu_ex1_srcf1; +wire [31:0] idu_fpu_ex1_srcf2; +wire [31:0] idu_fpu_ex1_srci; +wire idu_ifu_id_stall; +wire idu_ifu_tail_vld; +wire idu_ifu_tail_vld_gate; +wire [31:0] idu_ifu_x1; +wire [31:0] idu_iu_ex1_ag_imm; +wire idu_iu_ex1_alu_cmplt_dp_sel; +wire idu_iu_ex1_alu_gateclk_sel; +wire idu_iu_ex1_alu_sel; +wire [1 :0] idu_iu_ex1_bht_pred; +wire idu_iu_ex1_bju_cmplt_dp_sel; +wire idu_iu_ex1_bju_depd_lsu_src0; +wire idu_iu_ex1_bju_depd_lsu_src1; +wire idu_iu_ex1_bju_gateclk_sel; +wire idu_iu_ex1_bju_sel; +wire idu_iu_ex1_bju_use_pc; +wire idu_iu_ex1_div_cmplt_dp_sel; +wire idu_iu_ex1_div_gateclk_sel; +wire idu_iu_ex1_div_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_len; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_ipop_int_mask; +wire idu_iu_ex1_ipush_mie_en; +wire idu_iu_ex1_ipush_spec_fail; +wire idu_iu_ex1_mul_cmplt_dp_sel; +wire idu_iu_ex1_mul_gateclk_sel; +wire idu_iu_ex1_mul_high_sel; +wire idu_iu_ex1_mul_sel; +wire idu_iu_ex1_rd_pair; +wire idu_iu_ex1_split; +wire [31:0] idu_iu_ex1_src0; +wire [5 :0] idu_iu_ex1_src0_reg; +wire [31:0] idu_iu_ex1_src1; +wire [5 :0] idu_iu_ex1_src1_reg; +wire [31:0] idu_iu_ex1_src2; +wire idu_iu_ex1_tail_int_vld; +wire idu_iu_ex1_wb_vld; +wire idu_iu_tail_fail; +wire idu_iu_tail_fail_gate; +wire [31:0] idu_lsu_ex1_ag_imm; +wire [31:0] idu_lsu_ex1_base; +wire idu_lsu_ex1_base_sel; +wire idu_lsu_ex1_base_wb; +wire [31:0] idu_lsu_ex1_data; +wire [5 :0] idu_lsu_ex1_dest_reg; +wire idu_lsu_ex1_dest_vld; +wire idu_lsu_ex1_dp_sel; +wire idu_lsu_ex1_fls; +wire [3 :0] idu_lsu_ex1_func; +wire idu_lsu_ex1_gateclk_sel; +wire [14:0] idu_lsu_ex1_halt_info; +wire idu_lsu_ex1_ipop_int_mask; +wire idu_lsu_ex1_ipush_spec; +wire idu_lsu_ex1_length; +wire idu_lsu_ex1_offset_sel; +wire idu_lsu_ex1_sel; +wire idu_lsu_ex1_sign_extend; +wire [1 :0] idu_lsu_ex1_size; +wire idu_lsu_ex1_split; +wire [5 :0] idu_lsu_ex1_src0_reg; +wire idu_lsu_ex1_src1_depd; +wire [5 :0] idu_lsu_ex1_src1_reg; +wire idu_misc_cpuclk; +wire idu_yy_xx_tail_ack; +wire ifu_idu_chgflw_flush; +wire ifu_idu_id_expt_high; +wire ifu_idu_id_expt_vld; +wire [14:0] ifu_idu_id_halt_info; +wire [31:0] ifu_idu_id_inst; +wire ifu_idu_id_inst_vld; +wire [1 :0] ifu_idu_id_pred_taken; +wire ifu_idu_warm_up; +wire iu_idu_bju_global_stall; +wire iu_idu_bju_stall; +wire [31:0] iu_idu_ex1_fwd_data; +wire [5 :0] iu_idu_ex1_fwd_preg; +wire iu_idu_ex1_fwd_vld; +wire [31:0] iu_idu_ex1_src1_update_value; +wire iu_idu_ex1_stall; +wire iu_idu_ex2_div_vld; +wire [31:0] iu_idu_ex2_fwd_data0; +wire [31:0] iu_idu_ex2_fwd_data1; +wire [5 :0] iu_idu_ex2_fwd_preg0; +wire [5 :0] iu_idu_ex2_fwd_preg1; +wire iu_idu_ex2_fwd_vld0; +wire iu_idu_ex2_fwd_vld1; +wire iu_idu_ex2_inst_vld; +wire iu_idu_ex2_rd_pair; +wire iu_idu_id_stall; +wire iu_xx_no_op; +wire iu_yy_xx_cancel; +wire [14:0] lsu_idu_ex1_halt_info; +wire lsu_idu_ex1_halt_info_update_en; +wire lsu_idu_ex1_src1_update_en; +wire lsu_idu_ex1_src1_update_en_gate; +wire lsu_idu_ex1_stall; +wire [31:0] lsu_idu_ex2_ffwd_data; +wire lsu_idu_ex2_ffwd_vld; +wire [31:0] lsu_idu_ex2_fwd_data; +wire [4 :0] lsu_idu_ex2_fwd_freg; +wire [5 :0] lsu_idu_ex2_fwd_preg; +wire lsu_idu_ex2_fwd_vld; +wire [31:0] lsu_idu_ex3_ffwd_data; +wire lsu_idu_ex3_ffwd_vld; +wire [31:0] lsu_idu_ex3_fwd_data; +wire [4 :0] lsu_idu_ex3_fwd_freg; +wire [5 :0] lsu_idu_ex3_fwd_preg; +wire lsu_idu_ex3_fwd_vld; +wire lsu_idu_global_stall; +wire [31:0] lsu_idu_update_addr; +wire lsu_idu_update_en; +wire lsu_idu_update_en_gate; +wire [31:0] lsu_idu_update_offset; +wire lsu_xx_no_op; +wire pad_yy_icg_scan_en; +wire rtu_idu_ex1_int_dis_stall_gateclk_req; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_ex2_ipush_spec_inst_expt_vld; +wire rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +wire [31:0] rtu_idu_fgpr_wb_data; +wire rtu_idu_fgpr_wb_flsu_vld; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire rtu_idu_flush_fe; +wire rtu_idu_flush_stall; +wire rtu_idu_id_tail_int_vld; +wire rtu_idu_inst_retire; +wire rtu_idu_late_flush; +wire [31:0] rtu_idu_wb0_data; +wire rtu_idu_wb0_fpu_vld; +wire [5 :0] rtu_idu_wb0_preg; +wire rtu_idu_wb0_vld; +wire [31:0] rtu_idu_wb1_data; +wire rtu_idu_wb1_lsu_vld; +wire [5 :0] rtu_idu_wb1_preg; +wire rtu_idu_wb1_vld; +wire [31:0] rtu_idu_wb2_data; +wire [5 :0] rtu_idu_wb2_preg; +wire rtu_idu_wb2_vld; +wire rtu_xx_ex1_stall; +wire rtu_xx_no_op; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire split_ctrl_cancel; +wire split_ctrl_icg_en; +wire split_ctrl_stall; +wire [31:0] split_decd_ag_imm; +wire split_decd_ag_imm_vld; +wire split_decd_dp_sel; +wire [5 :0] split_decd_dst_idx; +wire split_decd_dst_vld; +wire [19:0] split_decd_func; +wire [5 :0] split_decd_rs1_idx; +wire split_decd_rs1_vld; +wire [5 :0] split_decd_rs2_idx; +wire [31:0] split_decd_rs2_imm; +wire split_decd_rs2_imm_vld; +wire split_decd_rs2_vld; +wire [5 :0] split_decd_sel; +wire split_decd_split; +wire [2 :0] split_top_cur_st; +wire [21:0] top_debug_info; +wire [95:0] top_fpr_debug_info; + + +// Decode Module +// &Instance("pa_idu_decd_dsp"); @30 +pa_idu_decd_dsp x_pa_idu_decd_dsp ( + .cp0_yy_cskyisaee (cp0_yy_cskyisaee ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .decd_ctrl_bju_use_pc (decd_ctrl_bju_use_pc ), + .decd_ctrl_id_func (decd_ctrl_id_func ), + .decd_ctrl_ill_expt (decd_ctrl_ill_expt ), + .decd_ctrl_inst_32bit (decd_ctrl_inst_32bit ), + .decd_ctrl_rd1 (decd_ctrl_rd1 ), + .decd_ctrl_rd1_vld (decd_ctrl_rd1_vld ), + .decd_ctrl_rd2 (decd_ctrl_rd2 ), + .decd_ctrl_rd2_vld (decd_ctrl_rd2_vld ), + .decd_ctrl_sti_vld (decd_ctrl_sti_vld ), + .decd_ctrl_str_vld (decd_ctrl_str_vld ), + .decd_ctrl_unit_sel (decd_ctrl_unit_sel ), + .decd_dp_ag_imm (decd_dp_ag_imm ), + .decd_dp_ag_imm_vld (decd_dp_ag_imm_vld ), + .decd_dp_csri_rs1 (decd_dp_csri_rs1 ), + .decd_dp_csri_vld (decd_dp_csri_vld ), + .decd_dp_ex_st_rs2_vld (decd_dp_ex_st_rs2_vld ), + .decd_dp_func (decd_dp_func ), + .decd_dp_imm (decd_dp_imm ), + .decd_dp_imm_vld (decd_dp_imm_vld ), + .decd_dp_lsr_vld (decd_dp_lsr_vld ), + .decd_dp_lsu_sel (decd_dp_lsu_sel ), + .decd_dp_mul_high_sel (decd_dp_mul_high_sel ), + .decd_dp_rd2_vld (decd_dp_rd2_vld ), + .decd_dp_rs1_idx (decd_dp_rs1_idx ), + .decd_dp_rs1_vld (decd_dp_rs1_vld ), + .decd_dp_rs2_idx (decd_dp_rs2_idx ), + .decd_dp_rs2_vld (decd_dp_rs2_vld ), + .decd_dp_rs3_idx (decd_dp_rs3_idx ), + .decd_dp_rs3_vld (decd_dp_rs3_vld ), + .decd_dp_rs4_idx (decd_dp_rs4_idx ), + .decd_dp_rs4_vld (decd_dp_rs4_vld ), + .decd_dp_smal_vld (decd_dp_smal_vld ), + .decd_dp_split (decd_dp_split ), + .decd_gpr_dep_rs1 (decd_gpr_dep_rs1 ), + .decd_gpr_dep_rs2 (decd_gpr_dep_rs2 ), + .decd_gpr_rd1_vld (decd_gpr_rd1_vld ), + .decd_gpr_rd2_vld (decd_gpr_rd2_vld ), + .decd_gpr_rs1 (decd_gpr_rs1 ), + .decd_gpr_rs1_vld (decd_gpr_rs1_vld ), + .decd_gpr_rs2 (decd_gpr_rs2 ), + .decd_gpr_rs2_vld (decd_gpr_rs2_vld ), + .decd_gpr_rs3 (decd_gpr_rs3 ), + .decd_gpr_rs3_vld (decd_gpr_rs3_vld ), + .decd_gpr_rs4 (decd_gpr_rs4 ), + .decd_gpr_rs4_vld (decd_gpr_rs4_vld ), + .decd_hs_ipop_vld (decd_hs_ipop_vld ), + .decd_hs_ipush_vld (decd_hs_ipush_vld ), + .decd_split_dst_idx (decd_split_dst_idx ), + .decd_split_opcode (decd_split_opcode ), + .decd_split_req (decd_split_req ), + .decd_split_rs1_idx (decd_split_rs1_idx ), + .decd_split_rs2_idx (decd_split_rs2_idx ), + .decd_split_rs2_vld (decd_split_rs2_vld ), + .dp_decd_rs2_aft_fwd (dp_decd_rs2_aft_fwd ), + .fdecd_decd_fp_inst_vld (fdecd_decd_fp_inst_vld), + .fdecd_decd_ill_expt (fdecd_decd_ill_expt ), + .fdecd_decd_imm (fdecd_decd_imm ), + .fdecd_decd_imm_vld (fdecd_decd_imm_vld ), + .fdecd_decd_rd_int_vld (fdecd_decd_rd_int_vld ), + .fdecd_decd_rs1_int_vld (fdecd_decd_rs1_int_vld), + .hs_decd_dp_vld (hs_decd_dp_vld ), + .hs_decd_dst_vld (hs_decd_dst_vld ), + .hs_decd_func (hs_decd_func ), + .hs_decd_imm (hs_decd_imm ), + .hs_decd_imm_vld (hs_decd_imm_vld ), + .hs_decd_rd (hs_decd_rd ), + .hs_decd_rs1 (hs_decd_rs1 ), + .hs_decd_rs1_vld (hs_decd_rs1_vld ), + .hs_decd_rs2 (hs_decd_rs2 ), + .hs_decd_rs2_imm_vld (hs_decd_rs2_imm_vld ), + .hs_decd_rs2_vld (hs_decd_rs2_vld ), + .hs_decd_sel (hs_decd_sel ), + .hs_decd_split (hs_decd_split ), + .ifu_idu_id_expt_vld (ifu_idu_id_expt_vld ), + .ifu_idu_id_inst (ifu_idu_id_inst ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .split_decd_ag_imm (split_decd_ag_imm ), + .split_decd_ag_imm_vld (split_decd_ag_imm_vld ), + .split_decd_dp_sel (split_decd_dp_sel ), + .split_decd_dst_idx (split_decd_dst_idx ), + .split_decd_dst_vld (split_decd_dst_vld ), + .split_decd_func (split_decd_func ), + .split_decd_rs1_idx (split_decd_rs1_idx ), + .split_decd_rs1_vld (split_decd_rs1_vld ), + .split_decd_rs2_idx (split_decd_rs2_idx ), + .split_decd_rs2_imm (split_decd_rs2_imm ), + .split_decd_rs2_imm_vld (split_decd_rs2_imm_vld), + .split_decd_rs2_vld (split_decd_rs2_vld ), + .split_decd_sel (split_decd_sel ), + .split_decd_split (split_decd_split ) +); + + +// GPR Access Module +// &Instance("pa_idu_gpr"); @33 +pa_idu_gpr x_pa_idu_gpr ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_idu_sp_wen (cp0_idu_sp_wen ), + .cp0_idu_sp_wen_gate (cp0_idu_sp_wen_gate ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ex1_dst_preg (ctrl_gpr_ex1_dst_preg ), + .ctrl_gpr_ex1_int_spec (ctrl_gpr_ex1_int_spec ), + .ctrl_gpr_id_rd1_vld (ctrl_gpr_id_rd1_vld ), + .ctrl_gpr_id_rd2_vld (ctrl_gpr_id_rd2_vld ), + .ctrl_gpr_id_wr_idx1 (ctrl_gpr_id_wr_idx1 ), + .ctrl_gpr_id_wr_idx2 (ctrl_gpr_id_wr_idx2 ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ctrl_gpr_wr_issue1 (ctrl_gpr_wr_issue1 ), + .decd_gpr_dep_rs1 (decd_gpr_dep_rs1 ), + .decd_gpr_dep_rs2 (decd_gpr_dep_rs2 ), + .decd_gpr_rd1_vld (decd_gpr_rd1_vld ), + .decd_gpr_rd2_vld (decd_gpr_rd2_vld ), + .decd_gpr_rs1 (decd_gpr_rs1 ), + .decd_gpr_rs1_vld (decd_gpr_rs1_vld ), + .decd_gpr_rs2 (decd_gpr_rs2 ), + .decd_gpr_rs2_vld (decd_gpr_rs2_vld ), + .decd_gpr_rs3 (decd_gpr_rs3 ), + .decd_gpr_rs3_vld (decd_gpr_rs3_vld ), + .decd_gpr_rs4 (decd_gpr_rs4 ), + .decd_gpr_rs4_vld (decd_gpr_rs4_vld ), + .dp_gpr_rs1_fwd_div (dp_gpr_rs1_fwd_div ), + .dp_gpr_rs1_fwd_lsu (dp_gpr_rs1_fwd_lsu ), + .dp_gpr_rs2_fwd_div (dp_gpr_rs2_fwd_div ), + .dp_gpr_rs2_fwd_lsu (dp_gpr_rs2_fwd_lsu ), + .dp_gpr_rs3_fwd_div (dp_gpr_rs3_fwd_div ), + .dp_gpr_rs3_fwd_lsu (dp_gpr_rs3_fwd_lsu ), + .dp_gpr_rs4_fwd_div (dp_gpr_rs4_fwd_div ), + .dp_gpr_rs4_fwd_lsu (dp_gpr_rs4_fwd_lsu ), + .dp_gpr_x2_busy (dp_gpr_x2_busy ), + .dp_gpr_x2_busy2 (dp_gpr_x2_busy2 ), + .forever_cpuclk (forever_cpuclk ), + .gpr_ctrl_rd1_busy_div (gpr_ctrl_rd1_busy_div ), + .gpr_ctrl_rd1_busy_lsu (gpr_ctrl_rd1_busy_lsu ), + .gpr_ctrl_rd2_busy_div (gpr_ctrl_rd2_busy_div ), + .gpr_ctrl_rd2_busy_lsu (gpr_ctrl_rd2_busy_lsu ), + .gpr_ctrl_rs1_busy_div (gpr_ctrl_rs1_busy_div ), + .gpr_ctrl_rs1_busy_lsu (gpr_ctrl_rs1_busy_lsu ), + .gpr_ctrl_rs1_busy_lsu2 (gpr_ctrl_rs1_busy_lsu2 ), + .gpr_ctrl_rs2_busy_div (gpr_ctrl_rs2_busy_div ), + .gpr_ctrl_rs2_busy_lsu (gpr_ctrl_rs2_busy_lsu ), + .gpr_ctrl_rs2_busy_lsu2 (gpr_ctrl_rs2_busy_lsu2 ), + .gpr_ctrl_rs3_busy_div (gpr_ctrl_rs3_busy_div ), + .gpr_ctrl_rs3_busy_lsu (gpr_ctrl_rs3_busy_lsu ), + .gpr_ctrl_rs3_busy_lsu2 (gpr_ctrl_rs3_busy_lsu2 ), + .gpr_ctrl_rs4_busy_div (gpr_ctrl_rs4_busy_div ), + .gpr_ctrl_rs4_busy_lsu (gpr_ctrl_rs4_busy_lsu ), + .gpr_dp_id_x2_wr (gpr_dp_id_x2_wr ), + .gpr_dp_rs1 (gpr_dp_rs1 ), + .gpr_dp_rs2 (gpr_dp_rs2 ), + .gpr_dp_rs3 (gpr_dp_rs3 ), + .gpr_dp_rs4 (gpr_dp_rs4 ), + .gpr_hs_sp_busy (gpr_hs_sp_busy ), + .gpr_hs_sp_busy2 (gpr_hs_sp_busy2 ), + .gpr_hs_sp_wb (gpr_hs_sp_wb ), + .hs_gpr_wb_mask (hs_gpr_wb_mask ), + .hs_gpr_wr_mask (hs_gpr_wr_mask ), + .idu_cp0_ipop_data (idu_cp0_ipop_data ), + .idu_cp0_mcause_wen (idu_cp0_mcause_wen ), + .idu_cp0_mepc_wen (idu_cp0_mepc_wen ), + .idu_cp0_sp_reg (idu_cp0_sp_reg ), + .idu_ifu_x1 (idu_ifu_x1 ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .iu_idu_ex2_div_vld (iu_idu_ex2_div_vld ), + .iu_idu_ex2_fwd_preg0 (iu_idu_ex2_fwd_preg0 ), + .iu_idu_ex2_fwd_vld0 (iu_idu_ex2_fwd_vld0 ), + .lsu_idu_ex2_fwd_preg (lsu_idu_ex2_fwd_preg ), + .lsu_idu_ex2_fwd_vld (lsu_idu_ex2_fwd_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_wb0_data (rtu_idu_wb0_data ), + .rtu_idu_wb0_fpu_vld (rtu_idu_wb0_fpu_vld ), + .rtu_idu_wb0_preg (rtu_idu_wb0_preg ), + .rtu_idu_wb0_vld (rtu_idu_wb0_vld ), + .rtu_idu_wb1_data (rtu_idu_wb1_data ), + .rtu_idu_wb1_lsu_vld (rtu_idu_wb1_lsu_vld ), + .rtu_idu_wb1_preg (rtu_idu_wb1_preg ), + .rtu_idu_wb1_vld (rtu_idu_wb1_vld ), + .rtu_idu_wb2_data (rtu_idu_wb2_data ), + .rtu_idu_wb2_preg (rtu_idu_wb2_preg ), + .rtu_idu_wb2_vld (rtu_idu_wb2_vld ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ) +); + + +// Control Module +// &Instance("pa_idu_ctrl"); @36 +pa_idu_ctrl x_pa_idu_ctrl ( + .cp0_idu_ex1_stall (cp0_idu_ex1_stall ), + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_dp_ex1_bju_sel (ctrl_dp_ex1_bju_sel ), + .ctrl_dp_ex1_div_sel (ctrl_dp_ex1_div_sel ), + .ctrl_dp_ex1_dst_preg (ctrl_dp_ex1_dst_preg ), + .ctrl_dp_ex1_dst_vld (ctrl_dp_ex1_dst_vld ), + .ctrl_dp_ex1_fls (ctrl_dp_ex1_fls ), + .ctrl_dp_ex1_inst_vld (ctrl_dp_ex1_inst_vld ), + .ctrl_dp_ex1_lsu_sel (ctrl_dp_ex1_lsu_sel ), + .ctrl_dp_ex1_rs1_dep (ctrl_dp_ex1_rs1_dep ), + .ctrl_dp_ex1_rs2_dep (ctrl_dp_ex1_rs2_dep ), + .ctrl_dp_ex1_st_sel (ctrl_dp_ex1_st_sel ), + .ctrl_dp_pipe_down (ctrl_dp_pipe_down ), + .ctrl_dp_pipe_down_gate (ctrl_dp_pipe_down_gate ), + .ctrl_fpr_ex1_int_spec (ctrl_fpr_ex1_int_spec ), + .ctrl_gpr_div_inst (ctrl_gpr_div_inst ), + .ctrl_gpr_ex1_dst_preg (ctrl_gpr_ex1_dst_preg ), + .ctrl_gpr_ex1_int_spec (ctrl_gpr_ex1_int_spec ), + .ctrl_gpr_id_rd1_vld (ctrl_gpr_id_rd1_vld ), + .ctrl_gpr_id_rd2_vld (ctrl_gpr_id_rd2_vld ), + .ctrl_gpr_id_wr_idx1 (ctrl_gpr_id_wr_idx1 ), + .ctrl_gpr_id_wr_idx2 (ctrl_gpr_id_wr_idx2 ), + .ctrl_gpr_ld_inst (ctrl_gpr_ld_inst ), + .ctrl_gpr_wr_issue1 (ctrl_gpr_wr_issue1 ), + .ctrl_hs_be_idle (ctrl_hs_be_idle ), + .ctrl_hs_bkpt_vld (ctrl_hs_bkpt_vld ), + .ctrl_hs_no_op (ctrl_hs_no_op ), + .ctrl_hs_stall (ctrl_hs_stall ), + .ctrl_id_fp_ex1_inst_vld (ctrl_id_fp_ex1_inst_vld ), + .ctrl_id_fp_ex1_lsu_sel (ctrl_id_fp_ex1_lsu_sel ), + .ctrl_id_fp_id_expt_vld (ctrl_id_fp_id_expt_vld ), + .ctrl_id_fp_id_inst_vld (ctrl_id_fp_id_inst_vld ), + .ctrl_id_fp_id_stall (ctrl_id_fp_id_stall ), + .ctrl_id_fp_pipe_down (ctrl_id_fp_pipe_down ), + .ctrl_id_fp_st_rs2_dep (ctrl_id_fp_st_rs2_dep ), + .ctrl_id_fp_uncmit (ctrl_id_fp_uncmit ), + .ctrl_split_bkpt_vld (ctrl_split_bkpt_vld ), + .ctrl_split_stall (ctrl_split_stall ), + .ctrl_top_bju_dep1_vld (ctrl_top_bju_dep1_vld ), + .ctrl_top_bju_dep2_vld (ctrl_top_bju_dep2_vld ), + .ctrl_top_cp0_stall (ctrl_top_cp0_stall ), + .ctrl_top_div_stall (ctrl_top_div_stall ), + .ctrl_top_ex1_fp_vld (ctrl_top_ex1_fp_vld ), + .ctrl_top_ex1_sel (ctrl_top_ex1_sel ), + .ctrl_top_ex1_stall (ctrl_top_ex1_stall ), + .ctrl_top_ex1_vld (ctrl_top_ex1_vld ), + .ctrl_top_id_cancel (ctrl_top_id_cancel ), + .ctrl_top_id_inst_vld (ctrl_top_id_inst_vld ), + .ctrl_top_id_stall (ctrl_top_id_stall ), + .ctrl_top_ld_stall (ctrl_top_ld_stall ), + .ctrl_top_norm_stall (ctrl_top_norm_stall ), + .ctrl_top_st_dep_vld (ctrl_top_st_dep_vld ), + .decd_ctrl_bju_use_pc (decd_ctrl_bju_use_pc ), + .decd_ctrl_id_func (decd_ctrl_id_func ), + .decd_ctrl_ill_expt (decd_ctrl_ill_expt ), + .decd_ctrl_inst_32bit (decd_ctrl_inst_32bit ), + .decd_ctrl_rd1 (decd_ctrl_rd1 ), + .decd_ctrl_rd1_vld (decd_ctrl_rd1_vld ), + .decd_ctrl_rd2 (decd_ctrl_rd2 ), + .decd_ctrl_rd2_vld (decd_ctrl_rd2_vld ), + .decd_ctrl_sti_vld (decd_ctrl_sti_vld ), + .decd_ctrl_str_vld (decd_ctrl_str_vld ), + .decd_ctrl_unit_sel (decd_ctrl_unit_sel ), + .dp_ctrl_ex1_ex_st_rs2_vld (dp_ctrl_ex1_ex_st_rs2_vld ), + .dp_ctrl_ex1_st_vld (dp_ctrl_ex1_st_vld ), + .dp_ctrl_rs1_dep_ex1_dst (dp_ctrl_rs1_dep_ex1_dst ), + .dp_ctrl_rs1_fwd_lsu (dp_ctrl_rs1_fwd_lsu ), + .dp_ctrl_rs1_stall_upd (dp_ctrl_rs1_stall_upd ), + .dp_ctrl_rs2_dep_ex1_dst (dp_ctrl_rs2_dep_ex1_dst ), + .dp_ctrl_rs2_fwd_lsu (dp_ctrl_rs2_fwd_lsu ), + .dp_ctrl_rs2_stall_upd (dp_ctrl_rs2_stall_upd ), + .dp_ctrl_rs3_dep_ex1_dst (dp_ctrl_rs3_dep_ex1_dst ), + .dp_ctrl_rs3_fwd_lsu (dp_ctrl_rs3_fwd_lsu ), + .dp_ctrl_rs3_stall_upd (dp_ctrl_rs3_stall_upd ), + .dp_ctrl_rs_norm_stall (dp_ctrl_rs_norm_stall ), + .fdecd_ctrl_dst_idx (fdecd_ctrl_dst_idx ), + .fdecd_ctrl_dst_vld (fdecd_ctrl_dst_vld ), + .fdecd_ctrl_fls (fdecd_ctrl_fls ), + .fdecd_ctrl_fp_inst_vld (fdecd_ctrl_fp_inst_vld ), + .fdecd_ctrl_int_dst_vld (fdecd_ctrl_int_dst_vld ), + .forever_cpuclk (forever_cpuclk ), + .fpu_idu_ex1_stall (fpu_idu_ex1_stall ), + .fpu_xx_no_op (fpu_xx_no_op ), + .gpr_ctrl_rd1_busy_div (gpr_ctrl_rd1_busy_div ), + .gpr_ctrl_rd1_busy_lsu (gpr_ctrl_rd1_busy_lsu ), + .gpr_ctrl_rd2_busy_div (gpr_ctrl_rd2_busy_div ), + .gpr_ctrl_rd2_busy_lsu (gpr_ctrl_rd2_busy_lsu ), + .gpr_ctrl_rs1_busy_div (gpr_ctrl_rs1_busy_div ), + .gpr_ctrl_rs1_busy_lsu (gpr_ctrl_rs1_busy_lsu ), + .gpr_ctrl_rs1_busy_lsu2 (gpr_ctrl_rs1_busy_lsu2 ), + .gpr_ctrl_rs2_busy_div (gpr_ctrl_rs2_busy_div ), + .gpr_ctrl_rs2_busy_lsu (gpr_ctrl_rs2_busy_lsu ), + .gpr_ctrl_rs2_busy_lsu2 (gpr_ctrl_rs2_busy_lsu2 ), + .gpr_ctrl_rs3_busy_div (gpr_ctrl_rs3_busy_div ), + .gpr_ctrl_rs3_busy_lsu (gpr_ctrl_rs3_busy_lsu ), + .gpr_ctrl_rs3_busy_lsu2 (gpr_ctrl_rs3_busy_lsu2 ), + .gpr_ctrl_rs4_busy_div (gpr_ctrl_rs4_busy_div ), + .gpr_ctrl_rs4_busy_lsu (gpr_ctrl_rs4_busy_lsu ), + .hs_ctrl_cancel (hs_ctrl_cancel ), + .hs_ctrl_inst_vld (hs_ctrl_inst_vld ), + .hs_ctrl_stall (hs_ctrl_stall ), + .id_fp_ctrl_id_stall (id_fp_ctrl_id_stall ), + .id_fp_ctrl_rs2_dep_ex1_dst (id_fp_ctrl_rs2_dep_ex1_dst ), + .id_fp_ctrl_rs2_stall_upd (id_fp_ctrl_rs2_stall_upd ), + .idu_cp0_ex1_cmplt_dp_sel (idu_cp0_ex1_cmplt_dp_sel ), + .idu_cp0_ex1_dst_idx (idu_cp0_ex1_dst_idx ), + .idu_cp0_ex1_dst_vld (idu_cp0_ex1_dst_vld ), + .idu_cp0_ex1_expt_high (idu_cp0_ex1_expt_high ), + .idu_cp0_ex1_expt_type (idu_cp0_ex1_expt_type ), + .idu_cp0_ex1_expt_vld (idu_cp0_ex1_expt_vld ), + .idu_cp0_ex1_gateclk_sel (idu_cp0_ex1_gateclk_sel ), + .idu_cp0_ex1_halt_info (idu_cp0_ex1_halt_info ), + .idu_cp0_ex1_inst_len (idu_cp0_ex1_inst_len ), + .idu_cp0_ex1_sel (idu_cp0_ex1_sel ), + .idu_ifu_id_stall (idu_ifu_id_stall ), + .idu_iu_ex1_alu_cmplt_dp_sel (idu_iu_ex1_alu_cmplt_dp_sel ), + .idu_iu_ex1_alu_gateclk_sel (idu_iu_ex1_alu_gateclk_sel ), + .idu_iu_ex1_alu_sel (idu_iu_ex1_alu_sel ), + .idu_iu_ex1_bht_pred (idu_iu_ex1_bht_pred ), + .idu_iu_ex1_bju_cmplt_dp_sel (idu_iu_ex1_bju_cmplt_dp_sel ), + .idu_iu_ex1_bju_depd_lsu_src0 (idu_iu_ex1_bju_depd_lsu_src0 ), + .idu_iu_ex1_bju_depd_lsu_src1 (idu_iu_ex1_bju_depd_lsu_src1 ), + .idu_iu_ex1_bju_gateclk_sel (idu_iu_ex1_bju_gateclk_sel ), + .idu_iu_ex1_bju_sel (idu_iu_ex1_bju_sel ), + .idu_iu_ex1_bju_use_pc (idu_iu_ex1_bju_use_pc ), + .idu_iu_ex1_div_cmplt_dp_sel (idu_iu_ex1_div_cmplt_dp_sel ), + .idu_iu_ex1_div_gateclk_sel (idu_iu_ex1_div_gateclk_sel ), + .idu_iu_ex1_div_sel (idu_iu_ex1_div_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_len (idu_iu_ex1_inst_len ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_mul_cmplt_dp_sel (idu_iu_ex1_mul_cmplt_dp_sel ), + .idu_iu_ex1_mul_gateclk_sel (idu_iu_ex1_mul_gateclk_sel ), + .idu_iu_ex1_mul_sel (idu_iu_ex1_mul_sel ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .idu_lsu_ex1_base_sel (idu_lsu_ex1_base_sel ), + .idu_lsu_ex1_dest_reg (idu_lsu_ex1_dest_reg ), + .idu_lsu_ex1_dest_vld (idu_lsu_ex1_dest_vld ), + .idu_lsu_ex1_dp_sel (idu_lsu_ex1_dp_sel ), + .idu_lsu_ex1_fls (idu_lsu_ex1_fls ), + .idu_lsu_ex1_gateclk_sel (idu_lsu_ex1_gateclk_sel ), + .idu_lsu_ex1_halt_info (idu_lsu_ex1_halt_info ), + .idu_lsu_ex1_length (idu_lsu_ex1_length ), + .idu_lsu_ex1_sel (idu_lsu_ex1_sel ), + .idu_lsu_ex1_src1_depd (idu_lsu_ex1_src1_depd ), + .idu_misc_cpuclk (idu_misc_cpuclk ), + .ifu_idu_id_expt_high (ifu_idu_id_expt_high ), + .ifu_idu_id_expt_vld (ifu_idu_id_expt_vld ), + .ifu_idu_id_halt_info (ifu_idu_id_halt_info ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .ifu_idu_id_pred_taken (ifu_idu_id_pred_taken ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .iu_idu_bju_global_stall (iu_idu_bju_global_stall ), + .iu_idu_bju_stall (iu_idu_bju_stall ), + .iu_idu_ex1_stall (iu_idu_ex1_stall ), + .iu_idu_id_stall (iu_idu_id_stall ), + .iu_xx_no_op (iu_xx_no_op ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .lsu_idu_ex1_halt_info (lsu_idu_ex1_halt_info ), + .lsu_idu_ex1_halt_info_update_en (lsu_idu_ex1_halt_info_update_en ), + .lsu_idu_ex1_stall (lsu_idu_ex1_stall ), + .lsu_idu_global_stall (lsu_idu_global_stall ), + .lsu_xx_no_op (lsu_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_ex1_int_dis_stall_gateclk_req (rtu_idu_ex1_int_dis_stall_gateclk_req), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_flush_stall (rtu_idu_flush_stall ), + .rtu_idu_inst_retire (rtu_idu_inst_retire ), + .rtu_idu_late_flush (rtu_idu_late_flush ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_xx_no_op (rtu_xx_no_op ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .split_ctrl_cancel (split_ctrl_cancel ), + .split_ctrl_icg_en (split_ctrl_icg_en ), + .split_ctrl_stall (split_ctrl_stall ) +); + + +// Datapath Module +// &Instance("pa_idu_dp"); @39 +pa_idu_dp x_pa_idu_dp ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_mcause (cp0_idu_mcause ), + .cp0_idu_mepc (cp0_idu_mepc ), + .cp0_idu_sp_use_scratch (cp0_idu_sp_use_scratch ), + .cp0_idu_sp_wdata (cp0_idu_sp_wdata ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_dp_ex1_bju_sel (ctrl_dp_ex1_bju_sel ), + .ctrl_dp_ex1_div_sel (ctrl_dp_ex1_div_sel ), + .ctrl_dp_ex1_dst_preg (ctrl_dp_ex1_dst_preg ), + .ctrl_dp_ex1_dst_vld (ctrl_dp_ex1_dst_vld ), + .ctrl_dp_ex1_fls (ctrl_dp_ex1_fls ), + .ctrl_dp_ex1_inst_vld (ctrl_dp_ex1_inst_vld ), + .ctrl_dp_ex1_lsu_sel (ctrl_dp_ex1_lsu_sel ), + .ctrl_dp_ex1_rs1_dep (ctrl_dp_ex1_rs1_dep ), + .ctrl_dp_ex1_rs2_dep (ctrl_dp_ex1_rs2_dep ), + .ctrl_dp_ex1_st_sel (ctrl_dp_ex1_st_sel ), + .ctrl_dp_pipe_down (ctrl_dp_pipe_down ), + .ctrl_dp_pipe_down_gate (ctrl_dp_pipe_down_gate ), + .decd_dp_ag_imm (decd_dp_ag_imm ), + .decd_dp_ag_imm_vld (decd_dp_ag_imm_vld ), + .decd_dp_csri_rs1 (decd_dp_csri_rs1 ), + .decd_dp_csri_vld (decd_dp_csri_vld ), + .decd_dp_ex_st_rs2_vld (decd_dp_ex_st_rs2_vld ), + .decd_dp_func (decd_dp_func ), + .decd_dp_imm (decd_dp_imm ), + .decd_dp_imm_vld (decd_dp_imm_vld ), + .decd_dp_lsr_vld (decd_dp_lsr_vld ), + .decd_dp_lsu_sel (decd_dp_lsu_sel ), + .decd_dp_mul_high_sel (decd_dp_mul_high_sel ), + .decd_dp_rd2_vld (decd_dp_rd2_vld ), + .decd_dp_rs1_idx (decd_dp_rs1_idx ), + .decd_dp_rs1_vld (decd_dp_rs1_vld ), + .decd_dp_rs2_idx (decd_dp_rs2_idx ), + .decd_dp_rs2_vld (decd_dp_rs2_vld ), + .decd_dp_rs3_idx (decd_dp_rs3_idx ), + .decd_dp_rs3_vld (decd_dp_rs3_vld ), + .decd_dp_rs4_idx (decd_dp_rs4_idx ), + .decd_dp_rs4_vld (decd_dp_rs4_vld ), + .decd_dp_smal_vld (decd_dp_smal_vld ), + .decd_dp_split (decd_dp_split ), + .dp_ctrl_ex1_ex_st_rs2_vld (dp_ctrl_ex1_ex_st_rs2_vld ), + .dp_ctrl_ex1_st_vld (dp_ctrl_ex1_st_vld ), + .dp_ctrl_rs1_dep_ex1_dst (dp_ctrl_rs1_dep_ex1_dst ), + .dp_ctrl_rs1_fwd_lsu (dp_ctrl_rs1_fwd_lsu ), + .dp_ctrl_rs1_stall_upd (dp_ctrl_rs1_stall_upd ), + .dp_ctrl_rs2_dep_ex1_dst (dp_ctrl_rs2_dep_ex1_dst ), + .dp_ctrl_rs2_fwd_lsu (dp_ctrl_rs2_fwd_lsu ), + .dp_ctrl_rs2_stall_upd (dp_ctrl_rs2_stall_upd ), + .dp_ctrl_rs3_dep_ex1_dst (dp_ctrl_rs3_dep_ex1_dst ), + .dp_ctrl_rs3_fwd_lsu (dp_ctrl_rs3_fwd_lsu ), + .dp_ctrl_rs3_stall_upd (dp_ctrl_rs3_stall_upd ), + .dp_ctrl_rs_norm_stall (dp_ctrl_rs_norm_stall ), + .dp_decd_rs2_aft_fwd (dp_decd_rs2_aft_fwd ), + .dp_gpr_rs1_fwd_div (dp_gpr_rs1_fwd_div ), + .dp_gpr_rs1_fwd_lsu (dp_gpr_rs1_fwd_lsu ), + .dp_gpr_rs2_fwd_div (dp_gpr_rs2_fwd_div ), + .dp_gpr_rs2_fwd_lsu (dp_gpr_rs2_fwd_lsu ), + .dp_gpr_rs3_fwd_div (dp_gpr_rs3_fwd_div ), + .dp_gpr_rs3_fwd_lsu (dp_gpr_rs3_fwd_lsu ), + .dp_gpr_rs4_fwd_div (dp_gpr_rs4_fwd_div ), + .dp_gpr_rs4_fwd_lsu (dp_gpr_rs4_fwd_lsu ), + .dp_gpr_x2_busy (dp_gpr_x2_busy ), + .dp_gpr_x2_busy2 (dp_gpr_x2_busy2 ), + .dp_id_fp_ex1_rs2_idx (dp_id_fp_ex1_rs2_idx ), + .fdecd_dp_rs1_int_vld (fdecd_dp_rs1_int_vld ), + .fdecd_dp_rs2_idx (fdecd_dp_rs2_idx ), + .fdecd_dp_rs2_vld (fdecd_dp_rs2_vld ), + .forever_cpuclk (forever_cpuclk ), + .gpr_dp_id_x2_wr (gpr_dp_id_x2_wr ), + .gpr_dp_rs1 (gpr_dp_rs1 ), + .gpr_dp_rs2 (gpr_dp_rs2 ), + .gpr_dp_rs3 (gpr_dp_rs3 ), + .gpr_dp_rs4 (gpr_dp_rs4 ), + .hd_dp_rs2_sel (hd_dp_rs2_sel ), + .hs_dp_ipop_int_mask (hs_dp_ipop_int_mask ), + .hs_dp_ipop_tail (hs_dp_ipop_tail ), + .hs_dp_ipop_tail_gate (hs_dp_ipop_tail_gate ), + .hs_dp_ipush_spec_fail (hs_dp_ipush_spec_fail ), + .hs_dp_mie_en (hs_dp_mie_en ), + .hs_dp_rs2_mcause (hs_dp_rs2_mcause ), + .hs_dp_rs2_mepc (hs_dp_rs2_mepc ), + .hs_dp_sp_wb_pending (hs_dp_sp_wb_pending ), + .id_fp_dp_srcf1 (id_fp_dp_srcf1 ), + .idu_cp0_ex1_func (idu_cp0_ex1_func ), + .idu_cp0_ex1_ipush_spec_fail (idu_cp0_ex1_ipush_spec_fail ), + .idu_cp0_ex1_opcode (idu_cp0_ex1_opcode ), + .idu_cp0_ex1_rs1 (idu_cp0_ex1_rs1 ), + .idu_cp0_ex1_rs2 (idu_cp0_ex1_rs2 ), + .idu_cp0_ex1_split_inst (idu_cp0_ex1_split_inst ), + .idu_fpu_ex1_srci (idu_fpu_ex1_srci ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .idu_ifu_tail_vld_gate (idu_ifu_tail_vld_gate ), + .idu_iu_ex1_ag_imm (idu_iu_ex1_ag_imm ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_ipop_int_mask (idu_iu_ex1_ipop_int_mask ), + .idu_iu_ex1_ipush_mie_en (idu_iu_ex1_ipush_mie_en ), + .idu_iu_ex1_ipush_spec_fail (idu_iu_ex1_ipush_spec_fail ), + .idu_iu_ex1_mul_high_sel (idu_iu_ex1_mul_high_sel ), + .idu_iu_ex1_rd_pair (idu_iu_ex1_rd_pair ), + .idu_iu_ex1_split (idu_iu_ex1_split ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src0_reg (idu_iu_ex1_src0_reg ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_src1_reg (idu_iu_ex1_src1_reg ), + .idu_iu_ex1_src2 (idu_iu_ex1_src2 ), + .idu_iu_ex1_tail_int_vld (idu_iu_ex1_tail_int_vld ), + .idu_lsu_ex1_ag_imm (idu_lsu_ex1_ag_imm ), + .idu_lsu_ex1_base (idu_lsu_ex1_base ), + .idu_lsu_ex1_base_wb (idu_lsu_ex1_base_wb ), + .idu_lsu_ex1_data (idu_lsu_ex1_data ), + .idu_lsu_ex1_func (idu_lsu_ex1_func ), + .idu_lsu_ex1_ipop_int_mask (idu_lsu_ex1_ipop_int_mask ), + .idu_lsu_ex1_offset_sel (idu_lsu_ex1_offset_sel ), + .idu_lsu_ex1_sign_extend (idu_lsu_ex1_sign_extend ), + .idu_lsu_ex1_size (idu_lsu_ex1_size ), + .idu_lsu_ex1_split (idu_lsu_ex1_split ), + .idu_lsu_ex1_src0_reg (idu_lsu_ex1_src0_reg ), + .idu_lsu_ex1_src1_reg (idu_lsu_ex1_src1_reg ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .iu_idu_ex1_fwd_data (iu_idu_ex1_fwd_data ), + .iu_idu_ex1_fwd_preg (iu_idu_ex1_fwd_preg ), + .iu_idu_ex1_fwd_vld (iu_idu_ex1_fwd_vld ), + .iu_idu_ex1_src1_update_value (iu_idu_ex1_src1_update_value ), + .iu_idu_ex2_div_vld (iu_idu_ex2_div_vld ), + .iu_idu_ex2_fwd_data0 (iu_idu_ex2_fwd_data0 ), + .iu_idu_ex2_fwd_data1 (iu_idu_ex2_fwd_data1 ), + .iu_idu_ex2_fwd_preg0 (iu_idu_ex2_fwd_preg0 ), + .iu_idu_ex2_fwd_preg1 (iu_idu_ex2_fwd_preg1 ), + .iu_idu_ex2_fwd_vld0 (iu_idu_ex2_fwd_vld0 ), + .iu_idu_ex2_fwd_vld1 (iu_idu_ex2_fwd_vld1 ), + .iu_idu_ex2_inst_vld (iu_idu_ex2_inst_vld ), + .iu_idu_ex2_rd_pair (iu_idu_ex2_rd_pair ), + .lsu_idu_ex1_src1_update_en (lsu_idu_ex1_src1_update_en ), + .lsu_idu_ex1_src1_update_en_gate (lsu_idu_ex1_src1_update_en_gate), + .lsu_idu_ex2_fwd_data (lsu_idu_ex2_fwd_data ), + .lsu_idu_ex2_fwd_preg (lsu_idu_ex2_fwd_preg ), + .lsu_idu_ex2_fwd_vld (lsu_idu_ex2_fwd_vld ), + .lsu_idu_ex3_fwd_data (lsu_idu_ex3_fwd_data ), + .lsu_idu_ex3_fwd_preg (lsu_idu_ex3_fwd_preg ), + .lsu_idu_ex3_fwd_vld (lsu_idu_ex3_fwd_vld ), + .lsu_idu_update_addr (lsu_idu_update_addr ), + .lsu_idu_update_en (lsu_idu_update_en ), + .lsu_idu_update_en_gate (lsu_idu_update_en_gate ), + .lsu_idu_update_offset (lsu_idu_update_offset ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// Split Module +// &Instance("pa_idu_split"); @42 +pa_idu_split x_pa_idu_split ( + .cpurst_b (cpurst_b ), + .ctrl_split_bkpt_vld (ctrl_split_bkpt_vld ), + .ctrl_split_stall (ctrl_split_stall ), + .decd_split_dst_idx (decd_split_dst_idx ), + .decd_split_opcode (decd_split_opcode ), + .decd_split_req (decd_split_req ), + .decd_split_rs1_idx (decd_split_rs1_idx ), + .decd_split_rs2_idx (decd_split_rs2_idx ), + .decd_split_rs2_vld (decd_split_rs2_vld ), + .idu_misc_cpuclk (idu_misc_cpuclk ), + .ifu_idu_chgflw_flush (ifu_idu_chgflw_flush ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .split_ctrl_cancel (split_ctrl_cancel ), + .split_ctrl_icg_en (split_ctrl_icg_en ), + .split_ctrl_stall (split_ctrl_stall ), + .split_decd_ag_imm (split_decd_ag_imm ), + .split_decd_ag_imm_vld (split_decd_ag_imm_vld ), + .split_decd_dp_sel (split_decd_dp_sel ), + .split_decd_dst_idx (split_decd_dst_idx ), + .split_decd_dst_vld (split_decd_dst_vld ), + .split_decd_func (split_decd_func ), + .split_decd_rs1_idx (split_decd_rs1_idx ), + .split_decd_rs1_vld (split_decd_rs1_vld ), + .split_decd_rs2_idx (split_decd_rs2_idx ), + .split_decd_rs2_imm (split_decd_rs2_imm ), + .split_decd_rs2_imm_vld (split_decd_rs2_imm_vld ), + .split_decd_rs2_vld (split_decd_rs2_vld ), + .split_decd_sel (split_decd_sel ), + .split_decd_split (split_decd_split ), + .split_top_cur_st (split_top_cur_st ) +); + + +// Hardware Stack Module +// &Instance("pa_idu_hs"); @46 +pa_idu_hs x_pa_idu_hs ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_idu_spec_push_en (cp0_idu_spec_push_en ), + .cp0_idu_swap_sp_en (cp0_idu_swap_sp_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_hs_be_idle (ctrl_hs_be_idle ), + .ctrl_hs_bkpt_vld (ctrl_hs_bkpt_vld ), + .ctrl_hs_no_op (ctrl_hs_no_op ), + .ctrl_hs_stall (ctrl_hs_stall ), + .decd_hs_ipop_vld (decd_hs_ipop_vld ), + .decd_hs_ipush_vld (decd_hs_ipush_vld ), + .forever_cpuclk (forever_cpuclk ), + .gpr_hs_sp_busy (gpr_hs_sp_busy ), + .gpr_hs_sp_busy2 (gpr_hs_sp_busy2 ), + .gpr_hs_sp_wb (gpr_hs_sp_wb ), + .hd_dp_rs2_sel (hd_dp_rs2_sel ), + .hs_ctrl_cancel (hs_ctrl_cancel ), + .hs_ctrl_inst_vld (hs_ctrl_inst_vld ), + .hs_ctrl_stall (hs_ctrl_stall ), + .hs_decd_dp_vld (hs_decd_dp_vld ), + .hs_decd_dst_vld (hs_decd_dst_vld ), + .hs_decd_func (hs_decd_func ), + .hs_decd_imm (hs_decd_imm ), + .hs_decd_imm_vld (hs_decd_imm_vld ), + .hs_decd_rd (hs_decd_rd ), + .hs_decd_rs1 (hs_decd_rs1 ), + .hs_decd_rs1_vld (hs_decd_rs1_vld ), + .hs_decd_rs2 (hs_decd_rs2 ), + .hs_decd_rs2_imm_vld (hs_decd_rs2_imm_vld ), + .hs_decd_rs2_vld (hs_decd_rs2_vld ), + .hs_decd_sel (hs_decd_sel ), + .hs_decd_split (hs_decd_split ), + .hs_dp_ipop_int_mask (hs_dp_ipop_int_mask ), + .hs_dp_ipop_tail (hs_dp_ipop_tail ), + .hs_dp_ipop_tail_gate (hs_dp_ipop_tail_gate ), + .hs_dp_ipush_spec_fail (hs_dp_ipush_spec_fail ), + .hs_dp_mie_en (hs_dp_mie_en ), + .hs_dp_rs2_mcause (hs_dp_rs2_mcause ), + .hs_dp_rs2_mepc (hs_dp_rs2_mepc ), + .hs_dp_sp_wb_pending (hs_dp_sp_wb_pending ), + .hs_fdecd_dp_vld (hs_fdecd_dp_vld ), + .hs_gpr_wb_mask (hs_gpr_wb_mask ), + .hs_gpr_wr_mask (hs_gpr_wr_mask ), + .idu_cp0_ex1_tail_fail (idu_cp0_ex1_tail_fail ), + .idu_cp0_id_tail_vld (idu_cp0_id_tail_vld ), + .idu_cp0_sp_swap_pending (idu_cp0_sp_swap_pending ), + .idu_cp0_sp_swap_req (idu_cp0_sp_swap_req ), + .idu_cp0_sp_swap_req_gate (idu_cp0_sp_swap_req_gate ), + .idu_iu_tail_fail (idu_iu_tail_fail ), + .idu_iu_tail_fail_gate (idu_iu_tail_fail_gate ), + .idu_lsu_ex1_ipush_spec (idu_lsu_ex1_ipush_spec ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_ex2_ipush_spec_inst_expt_vld (rtu_idu_ex2_ipush_spec_inst_expt_vld ), + .rtu_idu_ex2_ipush_spec_inst_halt_info_vld (rtu_idu_ex2_ipush_spec_inst_halt_info_vld), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_id_tail_int_vld (rtu_idu_id_tail_int_vld ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + +// &Instance("pa_idu_hs_dummy"); @48 + +// FP Decd Module +// &Instance("pa_idu_decd_fp"); @53 +pa_idu_decd_fp x_pa_idu_decd_fp ( + .cp0_idu_fs (cp0_idu_fs ), + .cp0_idu_rm (cp0_idu_rm ), + .decd_fp_fpr_rd (decd_fp_fpr_rd ), + .decd_fp_fpr_rd_vld (decd_fp_fpr_rd_vld ), + .decd_fp_fpr_rs1 (decd_fp_fpr_rs1 ), + .decd_fp_fpr_rs1_vld (decd_fp_fpr_rs1_vld ), + .decd_fp_fpr_rs2 (decd_fp_fpr_rs2 ), + .decd_fp_fpr_rs2_vld (decd_fp_fpr_rs2_vld ), + .decd_fp_fpr_rs3 (decd_fp_fpr_rs3 ), + .decd_fp_fpr_rs3_vld (decd_fp_fpr_rs3_vld ), + .decd_fp_id_dp_func (decd_fp_id_dp_func ), + .decd_fp_id_fp_dst_idx (decd_fp_id_fp_dst_idx ), + .decd_fp_id_fp_dst_vld (decd_fp_id_fp_dst_vld ), + .decd_fp_id_fp_inst_vld (decd_fp_id_fp_inst_vld), + .decd_fp_id_fp_lsu_sel (decd_fp_id_fp_lsu_sel ), + .decd_fp_id_fp_rs1_idx (decd_fp_id_fp_rs1_idx ), + .decd_fp_id_fp_rs1_vld (decd_fp_id_fp_rs1_vld ), + .decd_fp_id_fp_rs2_idx (decd_fp_id_fp_rs2_idx ), + .decd_fp_id_fp_rs2_vld (decd_fp_id_fp_rs2_vld ), + .decd_fp_id_fp_rs3_idx (decd_fp_id_fp_rs3_idx ), + .decd_fp_id_fp_rs3_vld (decd_fp_id_fp_rs3_vld ), + .decd_fp_id_fp_unit_sel (decd_fp_id_fp_unit_sel), + .decd_fp_id_rm (decd_fp_id_rm ), + .fdecd_ctrl_dst_idx (fdecd_ctrl_dst_idx ), + .fdecd_ctrl_dst_vld (fdecd_ctrl_dst_vld ), + .fdecd_ctrl_fls (fdecd_ctrl_fls ), + .fdecd_ctrl_fp_inst_vld (fdecd_ctrl_fp_inst_vld), + .fdecd_ctrl_int_dst_vld (fdecd_ctrl_int_dst_vld), + .fdecd_decd_fp_inst_vld (fdecd_decd_fp_inst_vld), + .fdecd_decd_ill_expt (fdecd_decd_ill_expt ), + .fdecd_decd_imm (fdecd_decd_imm ), + .fdecd_decd_imm_vld (fdecd_decd_imm_vld ), + .fdecd_decd_rd_int_vld (fdecd_decd_rd_int_vld ), + .fdecd_decd_rs1_int_vld (fdecd_decd_rs1_int_vld), + .fdecd_dp_rs1_int_vld (fdecd_dp_rs1_int_vld ), + .fdecd_dp_rs2_idx (fdecd_dp_rs2_idx ), + .fdecd_dp_rs2_vld (fdecd_dp_rs2_vld ), + .hs_fdecd_dp_vld (hs_fdecd_dp_vld ), + .ifu_idu_id_inst (ifu_idu_id_inst ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ) +); + + +// FP Register Module +// &Instance("pa_idu_fpr"); @56 +pa_idu_fpr x_pa_idu_fpr ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_fpr_ex1_int_spec (ctrl_fpr_ex1_int_spec ), + .decd_fp_fpr_rd (decd_fp_fpr_rd ), + .decd_fp_fpr_rd_vld (decd_fp_fpr_rd_vld ), + .decd_fp_fpr_rs1 (decd_fp_fpr_rs1 ), + .decd_fp_fpr_rs1_vld (decd_fp_fpr_rs1_vld ), + .decd_fp_fpr_rs2 (decd_fp_fpr_rs2 ), + .decd_fp_fpr_rs2_vld (decd_fp_fpr_rs2_vld ), + .decd_fp_fpr_rs3 (decd_fp_fpr_rs3 ), + .decd_fp_fpr_rs3_vld (decd_fp_fpr_rs3_vld ), + .forever_cpuclk (forever_cpuclk ), + .fpr_id_fp_rd_busy (fpr_id_fp_rd_busy ), + .fpr_id_fp_rd_busy_lsu (fpr_id_fp_rd_busy_lsu ), + .fpr_id_fp_rs1 (fpr_id_fp_rs1 ), + .fpr_id_fp_rs1_busy (fpr_id_fp_rs1_busy ), + .fpr_id_fp_rs1_busy_lsu (fpr_id_fp_rs1_busy_lsu ), + .fpr_id_fp_rs2 (fpr_id_fp_rs2 ), + .fpr_id_fp_rs2_busy (fpr_id_fp_rs2_busy ), + .fpr_id_fp_rs2_busy_lsu (fpr_id_fp_rs2_busy_lsu ), + .fpr_id_fp_rs3 (fpr_id_fp_rs3 ), + .fpr_id_fp_rs3_busy (fpr_id_fp_rs3_busy ), + .fpr_id_fp_rs3_busy_lsu (fpr_id_fp_rs3_busy_lsu ), + .fpr_top_reg_busy (fpr_top_reg_busy ), + .fpr_top_reg_busy_div (fpr_top_reg_busy_div ), + .fpr_top_reg_busy_lsu (fpr_top_reg_busy_lsu ), + .id_fp_fpr_dst_freg (id_fp_fpr_dst_freg ), + .id_fp_fpr_id_dst_vld (id_fp_fpr_id_dst_vld ), + .id_fp_fpr_ld_inst (id_fp_fpr_ld_inst ), + .id_fp_fpr_wr_issue (id_fp_fpr_wr_issue ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req), + .rtu_idu_fgpr_wb_data (rtu_idu_fgpr_wb_data ), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld ), + .rtu_idu_fgpr_wb_reg (rtu_idu_fgpr_wb_reg ), + .rtu_idu_fgpr_wb_vld (rtu_idu_fgpr_wb_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ) +); + + +// FP ID Pipe Module +// &Instance("pa_idu_id_fp"); @59 +pa_idu_id_fp x_pa_idu_id_fp ( + .cp0_idu_icg_en (cp0_idu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .ctrl_id_fp_ex1_inst_vld (ctrl_id_fp_ex1_inst_vld ), + .ctrl_id_fp_ex1_lsu_sel (ctrl_id_fp_ex1_lsu_sel ), + .ctrl_id_fp_id_expt_vld (ctrl_id_fp_id_expt_vld ), + .ctrl_id_fp_id_inst_vld (ctrl_id_fp_id_inst_vld ), + .ctrl_id_fp_id_stall (ctrl_id_fp_id_stall ), + .ctrl_id_fp_pipe_down (ctrl_id_fp_pipe_down ), + .ctrl_id_fp_st_rs2_dep (ctrl_id_fp_st_rs2_dep ), + .ctrl_id_fp_uncmit (ctrl_id_fp_uncmit ), + .decd_fp_id_dp_func (decd_fp_id_dp_func ), + .decd_fp_id_fp_dst_idx (decd_fp_id_fp_dst_idx ), + .decd_fp_id_fp_dst_vld (decd_fp_id_fp_dst_vld ), + .decd_fp_id_fp_inst_vld (decd_fp_id_fp_inst_vld ), + .decd_fp_id_fp_lsu_sel (decd_fp_id_fp_lsu_sel ), + .decd_fp_id_fp_rs1_idx (decd_fp_id_fp_rs1_idx ), + .decd_fp_id_fp_rs1_vld (decd_fp_id_fp_rs1_vld ), + .decd_fp_id_fp_rs2_idx (decd_fp_id_fp_rs2_idx ), + .decd_fp_id_fp_rs2_vld (decd_fp_id_fp_rs2_vld ), + .decd_fp_id_fp_rs3_idx (decd_fp_id_fp_rs3_idx ), + .decd_fp_id_fp_rs3_vld (decd_fp_id_fp_rs3_vld ), + .decd_fp_id_fp_unit_sel (decd_fp_id_fp_unit_sel ), + .decd_fp_id_rm (decd_fp_id_rm ), + .dp_id_fp_ex1_rs2_idx (dp_id_fp_ex1_rs2_idx ), + .forever_cpuclk (forever_cpuclk ), + .fpr_id_fp_rd_busy (fpr_id_fp_rd_busy ), + .fpr_id_fp_rd_busy_lsu (fpr_id_fp_rd_busy_lsu ), + .fpr_id_fp_rs1 (fpr_id_fp_rs1 ), + .fpr_id_fp_rs1_busy (fpr_id_fp_rs1_busy ), + .fpr_id_fp_rs1_busy_lsu (fpr_id_fp_rs1_busy_lsu ), + .fpr_id_fp_rs2 (fpr_id_fp_rs2 ), + .fpr_id_fp_rs2_busy (fpr_id_fp_rs2_busy ), + .fpr_id_fp_rs2_busy_lsu (fpr_id_fp_rs2_busy_lsu ), + .fpr_id_fp_rs3 (fpr_id_fp_rs3 ), + .fpr_id_fp_rs3_busy (fpr_id_fp_rs3_busy ), + .fpr_id_fp_rs3_busy_lsu (fpr_id_fp_rs3_busy_lsu ), + .fpu_idu_fwd_data (fpu_idu_fwd_data ), + .fpu_idu_fwd_freg (fpu_idu_fwd_freg ), + .fpu_idu_fwd_vld (fpu_idu_fwd_vld ), + .id_fp_ctrl_id_stall (id_fp_ctrl_id_stall ), + .id_fp_ctrl_rs2_dep_ex1_dst (id_fp_ctrl_rs2_dep_ex1_dst), + .id_fp_ctrl_rs2_stall_upd (id_fp_ctrl_rs2_stall_upd ), + .id_fp_dp_srcf1 (id_fp_dp_srcf1 ), + .id_fp_fpr_dst_freg (id_fp_fpr_dst_freg ), + .id_fp_fpr_id_dst_vld (id_fp_fpr_id_dst_vld ), + .id_fp_fpr_ld_inst (id_fp_fpr_ld_inst ), + .id_fp_fpr_wr_issue (id_fp_fpr_wr_issue ), + .idu_fpu_ex1_cmplt_dp_sel (idu_fpu_ex1_cmplt_dp_sel ), + .idu_fpu_ex1_dst_freg (idu_fpu_ex1_dst_freg ), + .idu_fpu_ex1_dst_freg_vld (idu_fpu_ex1_dst_freg_vld ), + .idu_fpu_ex1_dst_preg (idu_fpu_ex1_dst_preg ), + .idu_fpu_ex1_eu_sel (idu_fpu_ex1_eu_sel ), + .idu_fpu_ex1_func (idu_fpu_ex1_func ), + .idu_fpu_ex1_gateclk_vld (idu_fpu_ex1_gateclk_vld ), + .idu_fpu_ex1_inst_vld (idu_fpu_ex1_inst_vld ), + .idu_fpu_ex1_rm (idu_fpu_ex1_rm ), + .idu_fpu_ex1_srcf0 (idu_fpu_ex1_srcf0 ), + .idu_fpu_ex1_srcf1 (idu_fpu_ex1_srcf1 ), + .idu_fpu_ex1_srcf2 (idu_fpu_ex1_srcf2 ), + .ifu_idu_chgflw_flush (ifu_idu_chgflw_flush ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .iu_idu_bju_global_stall (iu_idu_bju_global_stall ), + .lsu_idu_ex2_ffwd_data (lsu_idu_ex2_ffwd_data ), + .lsu_idu_ex2_ffwd_vld (lsu_idu_ex2_ffwd_vld ), + .lsu_idu_ex2_fwd_freg (lsu_idu_ex2_fwd_freg ), + .lsu_idu_ex3_ffwd_data (lsu_idu_ex3_ffwd_data ), + .lsu_idu_ex3_ffwd_vld (lsu_idu_ex3_ffwd_vld ), + .lsu_idu_ex3_fwd_freg (lsu_idu_ex3_fwd_freg ), + .lsu_idu_global_stall (lsu_idu_global_stall ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_idu_fgpr_wb_data (rtu_idu_fgpr_wb_data ), + .rtu_idu_fgpr_wb_reg (rtu_idu_fgpr_wb_reg ), + .rtu_idu_fgpr_wb_vld (rtu_idu_fgpr_wb_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ) +); + + +assign top_debug_info[21:0] = { + ctrl_top_ex1_fp_vld, + ctrl_top_ex1_vld, + ctrl_top_ex1_stall, + ctrl_top_id_stall, + ctrl_top_id_cancel, + ctrl_top_ex1_sel[5:0], + ctrl_top_bju_dep2_vld, + ctrl_top_bju_dep1_vld, + ctrl_top_st_dep_vld, + ctrl_top_cp0_stall, + ctrl_top_div_stall, + ctrl_top_ld_stall, + ctrl_top_norm_stall, + ctrl_top_id_inst_vld, + split_top_cur_st[2:0] + }; +assign top_fpr_debug_info[95:0] = { + fpr_top_reg_busy_div[31:0], + fpr_top_reg_busy_lsu[31:0], + fpr_top_reg_busy[31:0] + }; +assign idu_dtu_debug_info[21:0] = top_debug_info[21:0]; +assign idu_dtu_fpr_info[95:0] = top_fpr_debug_info[95:0]; + +// &ModuleEnd; @150 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht.v new file mode 100644 index 0000000000000000000000000000000000000000..13f9cf88495fbc9d34f53a498056acf088ea59b9 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht.v @@ -0,0 +1,549 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_bht( + bht_id_pred_mem_taken, + bht_id_pred_rslt, + bht_top_cur_st, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + id_pred_bht_br_vld, + id_pred_bht_pc, + ifu_cp0_bht_inv_done, + iu_ifu_bht_cur_pc, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_bht_pred, + iu_ifu_bht_taken, + iu_ifu_br_vld, + iu_ifu_br_vld_gate, + pad_yy_icg_scan_en +); + +// &Ports; @24 +input cp0_ifu_bht_en; +input cp0_ifu_bht_inv; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input id_pred_bht_br_vld; +input [2 :0] id_pred_bht_pc; +input [31:0] iu_ifu_bht_cur_pc; +input iu_ifu_bht_mispred; +input iu_ifu_bht_mispred_gate; +input [1 :0] iu_ifu_bht_pred; +input iu_ifu_bht_taken; +input iu_ifu_br_vld; +input iu_ifu_br_vld_gate; +input pad_yy_icg_scan_en; +output bht_id_pred_mem_taken; +output [1 :0] bht_id_pred_rslt; +output [1 :0] bht_top_cur_st; +output ifu_cp0_bht_inv_done; + +// &Regs; @25 +reg bht_bypass_sel; +reg [15:0] bht_dout_bypass; +reg [15:0] bht_dout_ff; +reg [12:0] bht_ghr; +reg [8 :0] bht_inv_cnt; +reg [1 :0] bht_inv_cur_st; +reg [1 :0] bht_inv_nxt_st; +reg [1 :0] bht_ref_cur_st; +reg [1 :0] bht_ref_nxt_st; +reg [1 :0] bht_ref_val; +reg [12:0] bht_ref_vghr; +reg bht_upd_en; +reg [1 :0] bht_upd_val; +reg [12:0] bht_vghr; + +// &Wires; @26 +wire bht_cen; +wire bht_clk; +wire [15:0] bht_din; +wire [15:0] bht_dout; +wire [15:0] bht_dout_rslt; +wire bht_icg_en; +wire bht_id_pred_mem_taken; +wire [1 :0] bht_id_pred_rslt; +wire [8 :0] bht_idx; +wire bht_inv_clk; +wire bht_inv_done; +wire bht_inv_icg_en; +wire bht_inv_ide; +wire bht_inv_rd; +wire bht_inv_req; +wire bht_inv_wr; +wire [2 :0] bht_mem_idx; +wire [7 :0] bht_mem_way; +wire [7 :0] bht_mis_wen; +wire bht_miss_read1; +wire bht_miss_read2; +wire bht_miss_write; +wire [1 :0] bht_off_pred_rslt; +wire bht_pred_taken; +wire [1 :0] bht_sel_result; +wire [7 :0] bht_sel_way; +wire [1 :0] bht_top_cur_st; +wire [2 :0] bht_upd_idx; +wire bht_upd_vld; +wire bht_upd_write; +wire [15:0] bht_wen; +wire [15:0] bht_wr_val; +wire [1 :0] bht_wr_val_single; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire id_pred_bht_br_vld; +wire ifu_cp0_bht_inv_done; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire pad_yy_icg_scan_en; + + +parameter IDX_WIDTH = `BHT_IDX_WIDTH; +parameter HIS_WIDTH = `BHT_IDX_WIDTH+4; +parameter DATA_WIDTH = 16; + +// &Force("input", "id_pred_bht_pc"); @32 +// &Force("bus", "id_pred_bht_pc", 2, 0); @33 +// &Force("input", "iu_ifu_bht_cur_pc"); @34 +// &Force("bus", "iu_ifu_bht_cur_pc", 31, 0); @35 +//========================================================== +// Branch History Table Module +// 1. Instance ICG Cell +// 2. Implement GHR and VGHR +// 3. Implement BHT array +// 4. Generate Change Flow +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign bht_icg_en = id_pred_bht_br_vld + | iu_ifu_bht_mispred_gate + | cp0_ifu_bht_inv + | iu_ifu_br_vld_gate + | bht_miss_read2 + | bht_miss_write + | bht_inv_wr + | bht_bypass_sel + | bht_upd_vld; +// &Instance("gated_clk_cell", "x_pa_ifu_bht_icg_cell"); @56 +gated_clk_cell x_pa_ifu_bht_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (bht_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bht_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @57 +// .external_en (1'b0), @58 +// .global_en (cp0_yy_clk_en), @59 +// .module_en (cp0_ifu_icg_en), @60 +// .local_en (bht_icg_en), @61 +// .clk_out (bht_clk), @62 +// ); @63 + +assign bht_inv_icg_en = cp0_ifu_bht_inv + | ~bht_inv_ide; +// &Instance("gated_clk_cell", "x_pa_ifu_bht_inv_icg_cell"); @67 +gated_clk_cell x_pa_ifu_bht_inv_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (bht_inv_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bht_inv_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @68 +// .external_en (1'b0), @69 +// .global_en (cp0_yy_clk_en), @70 +// .module_en (cp0_ifu_icg_en), @71 +// .local_en (bht_inv_icg_en), @72 +// .clk_out (bht_inv_clk), @73 +// ); @74 +//------------------------------------------------ +// 2. Implement GHR and VGHR +//------------------------------------------------ +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_ghr[HIS_WIDTH-1:0] <= {HIS_WIDTH{1'b0}}; + else if(cp0_ifu_bht_inv) + bht_ghr[HIS_WIDTH-1:0] <= {HIS_WIDTH{1'b0}}; + else if(iu_ifu_br_vld) + bht_ghr[HIS_WIDTH-1:0] <= {bht_ghr[HIS_WIDTH-2:0], iu_ifu_bht_taken}; + else + bht_ghr[HIS_WIDTH-1:0] <= bht_ghr[HIS_WIDTH-1:0]; +end + +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_vghr[HIS_WIDTH-1:0] <= {HIS_WIDTH{1'b0}}; + else if(cp0_ifu_bht_inv) + bht_vghr[HIS_WIDTH-1:0] <= {HIS_WIDTH{1'b0}}; + else if(iu_ifu_bht_mispred) + bht_vghr[HIS_WIDTH-1:0] <= {bht_ghr[HIS_WIDTH-2:0], iu_ifu_bht_taken}; + else if(id_pred_bht_br_vld) + bht_vghr[HIS_WIDTH-1:0] <= {bht_vghr[HIS_WIDTH-2:0], bht_pred_taken}; + else + bht_vghr[HIS_WIDTH-1:0] <= bht_vghr[HIS_WIDTH-1:0]; +end + +//------------------------------------------------ +// 3. Implement BHT array +// a. Generate BHT array Request +// b. Instance BHT memory array +// c. Select BHT Output +// d. BHT Invalid Request +// e. BHT Read Request After Miss-Pred +//------------------------------------------------ + +// a. Generate BHT array Request +// Chip Enable, WEN, Index, Data In +assign bht_cen = bht_inv_req + | (id_pred_bht_br_vld + | bht_miss_read1 + | bht_miss_read2 + | bht_miss_write + | bht_upd_vld) + & cp0_ifu_bht_en; + +assign bht_mis_wen[7:0] = 8'b1 << bht_upd_idx[2:0]; +assign bht_wen[15:0] = bht_inv_wr ? 16'hffff + : bht_miss_write | bht_upd_vld ? {2{bht_mis_wen[7:0]}} + : 16'b0; + +assign bht_din[15:0] = {16{~bht_inv_req}} & bht_wr_val[15:0]; + +assign bht_idx[IDX_WIDTH-1:0] = bht_inv_req ? {IDX_WIDTH{bht_inv_wr}} & bht_inv_cnt[IDX_WIDTH-1:0] + : (bht_miss_read1 | bht_miss_read2) ? bht_ghr[HIS_WIDTH-2:3] + : bht_upd_write ? bht_ghr[HIS_WIDTH-1:4] + : (bht_miss_write | bht_upd_vld) ? bht_ref_vghr[HIS_WIDTH-1:4] + : bht_vghr[HIS_WIDTH-3:2]; + +// b. Instance BHT memory array +// &Instance("pa_ifu_bht_array", "x_pa_ifu_bht_array"); @137 +pa_ifu_bht_array x_pa_ifu_bht_array ( + .bht_cen (bht_cen ), + .bht_din (bht_din ), + .bht_dout (bht_dout ), + .bht_idx (bht_idx ), + .bht_wen (bht_wen ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + + +// c. Select BHT Output +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_bypass_sel <= 1'b0; + else if(bht_miss_write | bht_upd_vld | bht_inv_wr) + bht_bypass_sel <= 1'b1; + else if(id_pred_bht_br_vld) + bht_bypass_sel <= 1'b0; +end + +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_dout_bypass[DATA_WIDTH-1:0] <= {DATA_WIDTH{1'b0}}; + else if((bht_miss_write | bht_upd_vld) & ~bht_bypass_sel) + bht_dout_bypass[DATA_WIDTH-1:0] <= bht_dout[DATA_WIDTH-1:0]; + else if(bht_inv_wr & ~bht_bypass_sel) + bht_dout_bypass[DATA_WIDTH-1:0] <= {DATA_WIDTH{1'b0}}; +end + +assign bht_dout_rslt[DATA_WIDTH-1:0] = bht_bypass_sel ? bht_dout_bypass[DATA_WIDTH-1:0] + : bht_dout[DATA_WIDTH-1:0]; + +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_dout_ff[DATA_WIDTH-1:0] <= {DATA_WIDTH{1'b0}}; + else if(id_pred_bht_br_vld & bht_inv_ide & cp0_ifu_bht_en) + bht_dout_ff[DATA_WIDTH-1:0] <= bht_dout_rslt[DATA_WIDTH-1:0]; +end + +assign bht_sel_way[7:0] = 8'b1 << bht_vghr[2:0]; + +assign bht_sel_result[1] = |(bht_sel_way[7:0] & bht_dout_ff[15:8]); +assign bht_sel_result[0] = |(bht_sel_way[7:0] & bht_dout_ff[7:0]); + +assign bht_mem_idx[2:0] = {bht_vghr[1:0],bht_pred_taken}; + +assign bht_mem_way[7:0] = 8'b1 << bht_mem_idx[2:0]; + +assign bht_id_pred_mem_taken = cp0_ifu_bht_en & |(bht_mem_way[7:0] & bht_dout_rslt[15:8]); + +assign bht_pred_taken = bht_sel_result[1]; + +// &Force("bus", "id_pred_imm0", 31, 0); @184 +// &Force("bus", "id_pred_imm1", 31, 0); @185 +assign bht_off_pred_rslt[0] = 1'b0; +assign bht_off_pred_rslt[1] = 1'b0; + +// d. BHT Invalid Request +parameter BHT_INV_IDLE = 2'b00; +parameter BHT_INV_WRTE = 2'b10; +parameter BHT_INV_READ = 2'b11; + +// BHT Invalid FSM, for Array Invalid +// IDLE: default state +// WRTE: BHT invalid iteration state +// READ: BHT Read after invalid +always @ (posedge bht_inv_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_inv_cur_st[1:0] <= BHT_INV_IDLE; + else + bht_inv_cur_st[1:0] <= bht_inv_nxt_st[1:0]; +end + +// &CombBeg; @206 +always @( bht_inv_cur_st[1:0] + or cp0_ifu_bht_inv + or bht_inv_done) +begin +case(bht_inv_cur_st[1:0]) + BHT_INV_IDLE: + begin + if(cp0_ifu_bht_inv) + bht_inv_nxt_st[1:0] = BHT_INV_WRTE; + else + bht_inv_nxt_st[1:0] = BHT_INV_IDLE; + end + BHT_INV_WRTE: + begin + if(bht_inv_done) + bht_inv_nxt_st[1:0] = BHT_INV_READ; + else + bht_inv_nxt_st[1:0] = BHT_INV_WRTE; + end + BHT_INV_READ: + begin + bht_inv_nxt_st[1:0] = BHT_INV_IDLE; + end + default: + begin + bht_inv_nxt_st[1:0] = BHT_INV_IDLE; + end +endcase +// &CombEnd; @231 +end + +assign bht_inv_ide = bht_inv_cur_st[1:0] == BHT_INV_IDLE; +assign bht_inv_wr = bht_inv_cur_st[1:0] == BHT_INV_WRTE; +assign bht_inv_rd = bht_inv_cur_st[1:0] == BHT_INV_READ; +assign bht_inv_req = bht_inv_wr | bht_inv_rd; + +always @ (posedge bht_inv_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_inv_cnt[IDX_WIDTH-1:0] <= {IDX_WIDTH{1'b0}}; + else if(bht_inv_wr) + bht_inv_cnt[IDX_WIDTH-1:0] <= bht_inv_cnt[IDX_WIDTH-1:0] + 1'b1; + else + bht_inv_cnt[IDX_WIDTH-1:0] <= bht_inv_cnt[IDX_WIDTH-1:0]; +end + +assign bht_inv_done = bht_inv_cnt[IDX_WIDTH-1:0] == {IDX_WIDTH{1'b1}}; + +// e. BHT Read Request After Miss-Pred +// IDLE: default state, first read +// READ: BHT Second Read after Miss-Pred +// WRTE: BHT Write after Miss-Pred + +parameter BHT_REF_IDLE = 2'b00; +parameter BHT_REF_READ = 2'b01; +parameter BHT_REF_WRTE = 2'b10; +parameter BHT_REF_UPD = 2'b11; + +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + bht_ref_cur_st[1:0] <= BHT_REF_IDLE; + else + bht_ref_cur_st[1:0] <= bht_ref_nxt_st[1:0]; +end + +// &CombBeg; @268 +always @( bht_ref_cur_st[1:0] + or bht_upd_en + or iu_ifu_bht_mispred + or id_pred_bht_br_vld + or cp0_ifu_bht_en + or iu_ifu_br_vld) +begin +case(bht_ref_cur_st[1:0]) + BHT_REF_IDLE: + begin + if(iu_ifu_bht_mispred & cp0_ifu_bht_en) + bht_ref_nxt_st[1:0] = BHT_REF_READ; + else if(iu_ifu_br_vld & id_pred_bht_br_vld & bht_upd_en) + bht_ref_nxt_st[1:0] = BHT_REF_UPD; + else + bht_ref_nxt_st[1:0] = BHT_REF_IDLE; + end + BHT_REF_READ: + begin + bht_ref_nxt_st[1:0] = BHT_REF_WRTE; + end + BHT_REF_WRTE: + begin + if(~id_pred_bht_br_vld) + bht_ref_nxt_st[1:0] = BHT_REF_IDLE; + else + bht_ref_nxt_st[1:0] = BHT_REF_WRTE; + end + BHT_REF_UPD: + begin + if(~id_pred_bht_br_vld) + bht_ref_nxt_st[1:0] = BHT_REF_IDLE; + else + bht_ref_nxt_st[1:0] = BHT_REF_UPD; + end + default: + begin + bht_ref_nxt_st[1:0] = BHT_REF_IDLE; + end +endcase +// &CombEnd; @302 +end + +assign bht_miss_read1 = bht_ref_cur_st[1:0] == BHT_REF_IDLE & iu_ifu_bht_mispred; +assign bht_miss_read2 = bht_ref_cur_st[1:0] == BHT_REF_READ; +assign bht_miss_write = bht_ref_cur_st[1:0] == BHT_REF_WRTE & ~id_pred_bht_br_vld; +assign bht_upd_write = bht_ref_cur_st[1:0] == BHT_REF_IDLE & iu_ifu_br_vld + & ~iu_ifu_bht_mispred & ~id_pred_bht_br_vld & bht_upd_en; +assign bht_upd_vld = bht_upd_write | bht_ref_cur_st[1:0] == BHT_REF_UPD & ~id_pred_bht_br_vld; +assign bht_upd_idx[2:0] = bht_upd_write ? bht_ghr[2:0] : bht_ref_vghr[2:0]; + +// &CombBeg; @312 +always @( iu_ifu_bht_taken + or iu_ifu_bht_pred[1:0]) +begin +case({iu_ifu_bht_pred[1:0], iu_ifu_bht_taken}) + 3'b000: + begin + bht_upd_en = 1'b0; + bht_upd_val[1:0] = 2'b00; + end + 3'b001: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b01; + end + 3'b010: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b00; + end + 3'b011: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b10; + end + 3'b100: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b01; + end + 3'b101: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b11; + end + 3'b110: + begin + bht_upd_en = 1'b1; + bht_upd_val[1:0] = 2'b10; + end + 3'b111: + begin + bht_upd_en = 1'b0; + bht_upd_val[1:0] = 2'b11; + end + default: + begin + bht_upd_en = 1'b0; + bht_upd_val[1:0] = {2{1'bx}}; + end +endcase +// &CombEnd; @360 +end + +always @ (posedge bht_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + bht_ref_vghr[HIS_WIDTH-1:0] <= {(HIS_WIDTH){1'b0}}; + bht_ref_val[1:0] <= 2'b0; + end + else if(iu_ifu_bht_mispred | bht_upd_write) + begin + bht_ref_vghr[HIS_WIDTH-1:0] <= bht_ghr[HIS_WIDTH-1:0]; + bht_ref_val[1:0] <= bht_upd_val[1:0]; + end + else + begin + bht_ref_vghr[HIS_WIDTH-1:0] <= bht_ref_vghr[HIS_WIDTH-1:0]; + bht_ref_val[1:0] <= bht_ref_val[1:0]; + end +end + +assign bht_wr_val_single[1:0] = bht_upd_write ? bht_upd_val[1:0] : bht_ref_val[1:0]; +assign bht_wr_val[15:0] = {{8{bht_wr_val_single[1]}}, {8{bht_wr_val_single[0]}}}; + +//========================================================== +// Rename for Output +//========================================================== +// Output to top +assign bht_top_cur_st[1:0] = bht_ref_cur_st[1:0]; + +// Output to id prediction +assign bht_id_pred_rslt[1:0] = cp0_ifu_bht_en ? bht_sel_result[1:0] + : bht_off_pred_rslt[1:0]; +assign ifu_cp0_bht_inv_done = bht_inv_done; + + +// &ModuleEnd; @422 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht_array.v new file mode 100644 index 0000000000000000000000000000000000000000..a9519696bd33c090bd41d1130474f3f8bb6975f0 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_bht_array.v @@ -0,0 +1,122 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_bht_array( + bht_cen, + bht_din, + bht_dout, + bht_idx, + bht_wen, + cp0_ifu_icg_en, + cp0_yy_clk_en, + forever_cpuclk, + pad_yy_icg_scan_en +); + +// &Ports; @24 +input bht_cen; +input [15:0] bht_din; +input [8 :0] bht_idx; +input [15:0] bht_wen; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output [15:0] bht_dout; + +// &Regs; @25 + +// &Wires; @26 +wire [15:0] bht_bwen_b; +wire bht_cen; +wire bht_cen_b; +wire bht_clk; +wire [15:0] bht_din; +wire [15:0] bht_dout; +wire bht_gwen_b; +wire bht_icg_en; +wire [8 :0] bht_idx; +wire [15:0] bht_wen; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; + + +//========================================================== +// BHT Array Module +// 1. Instance ICG Cell +// 2. Instance Memory Cell +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign bht_icg_en = bht_cen; +// &Instance("gated_clk_cell", "x_bht_icg_cell"); @38 +gated_clk_cell x_bht_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (bht_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bht_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @39 +// .external_en (1'b0 ), @40 +// .global_en (cp0_yy_clk_en ), @41 +// .module_en (cp0_ifu_icg_en), @42 +// .local_en (bht_icg_en ), @43 +// .clk_out (bht_clk ) @44 +// ); @45 + +//------------------------------------------------ +// 2. Instance Memory Cell +//------------------------------------------------ +assign bht_cen_b = ~bht_cen; +assign bht_gwen_b = ~(|bht_wen[15:0]); +assign bht_bwen_b[15:0] = ~bht_wen[15:0]; + +// &Instance("pa_spsram_128x16","x_pa_spsram_128x16"); @55 +// &Instance("pa_spsram_256x16","x_pa_spsram_256x16"); @58 +// &Instance("pa_spsram_512x16","x_pa_spsram_512x16"); @61 +pa_spsram_512x16 x_pa_spsram_512x16 ( + .A (bht_idx ), + .CEN (bht_cen_b ), + .CLK (bht_clk ), + .D (bht_din ), + .GWEN (bht_gwen_b), + .Q (bht_dout ), + .WEN (bht_bwen_b) +); + +// &Instance("pa_spsram_1024x16","x_pa_spsram_1024x16"); @64 +// &Connect( @66 +// .CLK (bht_clk ), @67 +// .CEN (bht_cen_b ), @68 +// .GWEN (bht_gwen_b), @69 +// .WEN (bht_bwen_b), @70 +// .A (bht_idx ), @71 +// .D (bht_din ), @72 +// .Q (bht_dout ) @73 +// ); @74 + +// &ModuleEnd; @76 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb.v new file mode 100644 index 0000000000000000000000000000000000000000..6ad82071c2d64ba05cb8a34b92353944296c1860 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb.v @@ -0,0 +1,675 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_btb( + btb_pcgen_tar_pc, + btb_xx_chgflw_vld, + cp0_ifu_btb_clr, + cp0_ifu_btb_en, + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_btb_inst_fetch, + forever_cpuclk, + id_pred_btb_cur_pc, + id_pred_btb_mis_pred, + id_pred_btb_mis_predg, + id_pred_btb_tar_pc, + id_pred_btb_upd_vld, + id_pred_btb_upd_vldg, + ifetch_pcgen_grant, + iu_ifu_tar_pc_vld, + pad_yy_icg_scan_en, + pcgen_btb_addr, + pcgen_btb_pc +); + +// &Ports; @24 +input cp0_ifu_btb_clr; +input cp0_ifu_btb_en; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_btb_inst_fetch; +input forever_cpuclk; +input [31:0] id_pred_btb_cur_pc; +input id_pred_btb_mis_pred; +input id_pred_btb_mis_predg; +input [31:0] id_pred_btb_tar_pc; +input id_pred_btb_upd_vld; +input id_pred_btb_upd_vldg; +input ifetch_pcgen_grant; +input iu_ifu_tar_pc_vld; +input pad_yy_icg_scan_en; +input [31:0] pcgen_btb_addr; +input [31:0] pcgen_btb_pc; +output [31:0] btb_pcgen_tar_pc; +output btb_xx_chgflw_vld; + +// &Regs; @25 +reg [15:0] btb_entry_hit_flop; +reg [15:0] btb_fifo; +reg [15:0] btb_hit_tgt; +reg btb_pred_flop; + +// &Wires; @26 +wire btb_clk; +wire btb_clr_one; +wire btb_clr_oneg; +wire [15:0] btb_entry_clr; +wire [15:0] btb_entry_clrg; +wire [15:0] btb_entry_rd_hit; +wire btb_entry_replace; +wire btb_entry_replaceg; +wire [15:0] btb_entry_tgt_0; +wire [15:0] btb_entry_tgt_1; +wire [15:0] btb_entry_tgt_10; +wire [15:0] btb_entry_tgt_11; +wire [15:0] btb_entry_tgt_12; +wire [15:0] btb_entry_tgt_13; +wire [15:0] btb_entry_tgt_14; +wire [15:0] btb_entry_tgt_15; +wire [15:0] btb_entry_tgt_2; +wire [15:0] btb_entry_tgt_3; +wire [15:0] btb_entry_tgt_4; +wire [15:0] btb_entry_tgt_5; +wire [15:0] btb_entry_tgt_6; +wire [15:0] btb_entry_tgt_7; +wire [15:0] btb_entry_tgt_8; +wire [15:0] btb_entry_tgt_9; +wire [15:0] btb_entry_upd; +wire btb_entry_upd_vld; +wire btb_entry_upd_vldg; +wire [15:0] btb_entry_updg; +wire [15:0] btb_entry_wr_hit; +wire btb_flop_vld; +wire btb_icg_en; +wire [31:0] btb_pcgen_tar_pc; +wire [15:0] btb_rd_acc_tag; +wire btb_rd_hit_vld; +wire [15:0] btb_upd_tag; +wire [15:0] btb_upd_tgt; +wire [15:0] btb_wr_acc_tag; +wire btb_wr_hit_vld; +wire btb_xx_chgflw_vld; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_btb_inst_fetch; +wire forever_cpuclk; +wire [31:0] id_pred_btb_cur_pc; +wire id_pred_btb_mis_pred; +wire id_pred_btb_mis_predg; +wire [31:0] id_pred_btb_tar_pc; +wire id_pred_btb_upd_vld; +wire id_pred_btb_upd_vldg; +wire ifetch_pcgen_grant; +wire iu_ifu_tar_pc_vld; +wire pad_yy_icg_scan_en; +wire [31:0] pcgen_btb_addr; +wire [31:0] pcgen_btb_pc; + + +parameter BTB_ADDR_WIDTH = 16; +//========================================================== +// Branch Target Buffer Module +// Register Structure +// 1. Instance ICG Cells +// 2. Instance Buffer Entries +// 3. BTB Write Port +// 4. BTB Read Port +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cells +//------------------------------------------------ +assign btb_icg_en = btb_entry_upd_vldg + //| btb_flop_vld + | ctrl_btb_inst_fetch + | iu_ifu_tar_pc_vld + | btb_clr_oneg + | btb_pred_flop; + +// &Instance("gated_clk_cell", "x_btb_icg_cell"); @49 +gated_clk_cell x_btb_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (btb_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (btb_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @50 +// .external_en(1'b0 ), @51 +// .global_en (cp0_yy_clk_en ), @52 +// .module_en (cp0_ifu_icg_en), @53 +// .local_en (btb_icg_en ), @54 +// .clk_out (btb_clk ) @55 +// ); @56 + +//------------------------------------------------ +// 2. Instance Buffer Entries +//------------------------------------------------ +parameter ENTRY_NUM = 16; + +// &ConnRule(s/_x$/[0]/); @63 +// &ConnRule(s/_y$/_0/); @64 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry0"); @65 +pa_ifu_btb_entry x_pa_ifu_btb_entry0 ( + .btb_entry_clr_x (btb_entry_clr[0] ), + .btb_entry_clrg_x (btb_entry_clrg[0] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[0]), + .btb_entry_tgt_y (btb_entry_tgt_0 ), + .btb_entry_upd_x (btb_entry_upd[0] ), + .btb_entry_updg_x (btb_entry_updg[0] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[0]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[1]/); @67 +// &ConnRule(s/_y$/_1/); @68 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry1"); @69 +pa_ifu_btb_entry x_pa_ifu_btb_entry1 ( + .btb_entry_clr_x (btb_entry_clr[1] ), + .btb_entry_clrg_x (btb_entry_clrg[1] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[1]), + .btb_entry_tgt_y (btb_entry_tgt_1 ), + .btb_entry_upd_x (btb_entry_upd[1] ), + .btb_entry_updg_x (btb_entry_updg[1] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[1]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[2]/); @71 +// &ConnRule(s/_y$/_2/); @72 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry2"); @73 +pa_ifu_btb_entry x_pa_ifu_btb_entry2 ( + .btb_entry_clr_x (btb_entry_clr[2] ), + .btb_entry_clrg_x (btb_entry_clrg[2] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[2]), + .btb_entry_tgt_y (btb_entry_tgt_2 ), + .btb_entry_upd_x (btb_entry_upd[2] ), + .btb_entry_updg_x (btb_entry_updg[2] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[2]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[3]/); @75 +// &ConnRule(s/_y$/_3/); @76 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry3"); @77 +pa_ifu_btb_entry x_pa_ifu_btb_entry3 ( + .btb_entry_clr_x (btb_entry_clr[3] ), + .btb_entry_clrg_x (btb_entry_clrg[3] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[3]), + .btb_entry_tgt_y (btb_entry_tgt_3 ), + .btb_entry_upd_x (btb_entry_upd[3] ), + .btb_entry_updg_x (btb_entry_updg[3] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[3]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[4]/); @79 +// &ConnRule(s/_y$/_4/); @80 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry4"); @81 +pa_ifu_btb_entry x_pa_ifu_btb_entry4 ( + .btb_entry_clr_x (btb_entry_clr[4] ), + .btb_entry_clrg_x (btb_entry_clrg[4] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[4]), + .btb_entry_tgt_y (btb_entry_tgt_4 ), + .btb_entry_upd_x (btb_entry_upd[4] ), + .btb_entry_updg_x (btb_entry_updg[4] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[4]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[5]/); @83 +// &ConnRule(s/_y$/_5/); @84 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry5"); @85 +pa_ifu_btb_entry x_pa_ifu_btb_entry5 ( + .btb_entry_clr_x (btb_entry_clr[5] ), + .btb_entry_clrg_x (btb_entry_clrg[5] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[5]), + .btb_entry_tgt_y (btb_entry_tgt_5 ), + .btb_entry_upd_x (btb_entry_upd[5] ), + .btb_entry_updg_x (btb_entry_updg[5] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[5]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[6]/); @87 +// &ConnRule(s/_y$/_6/); @88 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry6"); @89 +pa_ifu_btb_entry x_pa_ifu_btb_entry6 ( + .btb_entry_clr_x (btb_entry_clr[6] ), + .btb_entry_clrg_x (btb_entry_clrg[6] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[6]), + .btb_entry_tgt_y (btb_entry_tgt_6 ), + .btb_entry_upd_x (btb_entry_upd[6] ), + .btb_entry_updg_x (btb_entry_updg[6] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[6]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[7]/); @91 +// &ConnRule(s/_y$/_7/); @92 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry7"); @93 +pa_ifu_btb_entry x_pa_ifu_btb_entry7 ( + .btb_entry_clr_x (btb_entry_clr[7] ), + .btb_entry_clrg_x (btb_entry_clrg[7] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[7]), + .btb_entry_tgt_y (btb_entry_tgt_7 ), + .btb_entry_upd_x (btb_entry_upd[7] ), + .btb_entry_updg_x (btb_entry_updg[7] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[7]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[8]/); @95 +// &ConnRule(s/_y$/_8/); @96 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry8"); @97 +pa_ifu_btb_entry x_pa_ifu_btb_entry8 ( + .btb_entry_clr_x (btb_entry_clr[8] ), + .btb_entry_clrg_x (btb_entry_clrg[8] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[8]), + .btb_entry_tgt_y (btb_entry_tgt_8 ), + .btb_entry_upd_x (btb_entry_upd[8] ), + .btb_entry_updg_x (btb_entry_updg[8] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[8]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[9]/); @99 +// &ConnRule(s/_y$/_9/); @100 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry9"); @101 +pa_ifu_btb_entry x_pa_ifu_btb_entry9 ( + .btb_entry_clr_x (btb_entry_clr[9] ), + .btb_entry_clrg_x (btb_entry_clrg[9] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[9]), + .btb_entry_tgt_y (btb_entry_tgt_9 ), + .btb_entry_upd_x (btb_entry_upd[9] ), + .btb_entry_updg_x (btb_entry_updg[9] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[9]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[10]/); @103 +// &ConnRule(s/_y$/_10/); @104 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry10"); @105 +pa_ifu_btb_entry x_pa_ifu_btb_entry10 ( + .btb_entry_clr_x (btb_entry_clr[10] ), + .btb_entry_clrg_x (btb_entry_clrg[10] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[10]), + .btb_entry_tgt_y (btb_entry_tgt_10 ), + .btb_entry_upd_x (btb_entry_upd[10] ), + .btb_entry_updg_x (btb_entry_updg[10] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[10]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[11]/); @107 +// &ConnRule(s/_y$/_11/); @108 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry11"); @109 +pa_ifu_btb_entry x_pa_ifu_btb_entry11 ( + .btb_entry_clr_x (btb_entry_clr[11] ), + .btb_entry_clrg_x (btb_entry_clrg[11] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[11]), + .btb_entry_tgt_y (btb_entry_tgt_11 ), + .btb_entry_upd_x (btb_entry_upd[11] ), + .btb_entry_updg_x (btb_entry_updg[11] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[11]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[12]/); @111 +// &ConnRule(s/_y$/_12/); @112 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry12"); @113 +pa_ifu_btb_entry x_pa_ifu_btb_entry12 ( + .btb_entry_clr_x (btb_entry_clr[12] ), + .btb_entry_clrg_x (btb_entry_clrg[12] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[12]), + .btb_entry_tgt_y (btb_entry_tgt_12 ), + .btb_entry_upd_x (btb_entry_upd[12] ), + .btb_entry_updg_x (btb_entry_updg[12] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[12]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[13]/); @115 +// &ConnRule(s/_y$/_13/); @116 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry13"); @117 +pa_ifu_btb_entry x_pa_ifu_btb_entry13 ( + .btb_entry_clr_x (btb_entry_clr[13] ), + .btb_entry_clrg_x (btb_entry_clrg[13] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[13]), + .btb_entry_tgt_y (btb_entry_tgt_13 ), + .btb_entry_upd_x (btb_entry_upd[13] ), + .btb_entry_updg_x (btb_entry_updg[13] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[13]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[14]/); @119 +// &ConnRule(s/_y$/_14/); @120 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry14"); @121 +pa_ifu_btb_entry x_pa_ifu_btb_entry14 ( + .btb_entry_clr_x (btb_entry_clr[14] ), + .btb_entry_clrg_x (btb_entry_clrg[14] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[14]), + .btb_entry_tgt_y (btb_entry_tgt_14 ), + .btb_entry_upd_x (btb_entry_upd[14] ), + .btb_entry_updg_x (btb_entry_updg[14] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[14]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/_x$/[15]/); @123 +// &ConnRule(s/_y$/_15/); @124 +// &Instance("pa_ifu_btb_entry","x_pa_ifu_btb_entry15"); @125 +pa_ifu_btb_entry x_pa_ifu_btb_entry15 ( + .btb_entry_clr_x (btb_entry_clr[15] ), + .btb_entry_clrg_x (btb_entry_clrg[15] ), + .btb_entry_rd_hit_x (btb_entry_rd_hit[15]), + .btb_entry_tgt_y (btb_entry_tgt_15 ), + .btb_entry_upd_x (btb_entry_upd[15] ), + .btb_entry_updg_x (btb_entry_updg[15] ), + .btb_entry_wr_hit_x (btb_entry_wr_hit[15]), + .btb_rd_acc_tag (btb_rd_acc_tag ), + .btb_upd_tag (btb_upd_tag ), + .btb_upd_tgt (btb_upd_tgt ), + .btb_wr_acc_tag (btb_wr_acc_tag ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +//------------------------------------------------ +// 3. BTB Write Port +// a. Clear all entries on btb clr request +// b. Update entry depending on fifo bit +//------------------------------------------------ +// a. Clear all entries on btb clr request +// Clear Corresponding entry on mis-pred +assign btb_clr_one = id_pred_btb_mis_pred & cp0_ifu_btb_en & btb_wr_hit_vld; +assign btb_clr_oneg = id_pred_btb_mis_predg & cp0_ifu_btb_en & btb_wr_hit_vld; +assign btb_entry_clr[15:0] = {16{btb_clr_one}} & btb_entry_wr_hit[15:0] + | {16{cp0_ifu_btb_clr}}; +assign btb_entry_clrg[15:0] = {16{btb_clr_oneg}} & btb_entry_wr_hit[15:0] + | {16{cp0_ifu_btb_clr}}; + +// b. Update entry depending on fifo bit +assign btb_entry_upd_vld = id_pred_btb_upd_vld & cp0_ifu_btb_en; +assign btb_entry_upd_vldg = id_pred_btb_upd_vldg & cp0_ifu_btb_en; + +always @(posedge btb_clk or negedge cpurst_b) +begin + if(~cpurst_b) + btb_fifo[15:0] <= 16'b1; + else if(btb_entry_upd_vld & ~btb_wr_hit_vld) + btb_fifo[15:0] <= {btb_fifo[14:0], btb_fifo[15]}; + else if(btb_clr_one) + btb_fifo[15:0] <= btb_entry_wr_hit[15:0]; + else + btb_fifo[15:0] <= btb_fifo[15:0]; +end +// &Force("bus", "idu_iu_ex1_cur_pc", 31, 0); @156 +assign btb_entry_replace = btb_entry_upd_vld & btb_wr_hit_vld; +assign btb_entry_replaceg = btb_entry_upd_vldg & btb_wr_hit_vld; +assign btb_entry_upd[15:0] = btb_entry_replace + ? btb_entry_wr_hit[15:0] + : {16{btb_entry_upd_vld}} & btb_fifo[15:0]; +assign btb_entry_updg[15:0] = btb_entry_replaceg + ? btb_entry_wr_hit[15:0] + : {16{btb_entry_upd_vldg}} & btb_fifo[15:0]; + +// update next word when unaligned 32-bit inst +// &Force("bus", "id_pred_btb_cur_pc", 31, 0); @167 +// &Force("bus", "id_pred_btb_tar_pc", 31, 0); @168 +assign btb_upd_tag[BTB_ADDR_WIDTH-1:0] = id_pred_btb_cur_pc[BTB_ADDR_WIDTH-1:0]; + +assign btb_upd_tgt[BTB_ADDR_WIDTH-1:0] = id_pred_btb_tar_pc[BTB_ADDR_WIDTH-1:0]; + +//------------------------------------------------ +// 3. BTB Read Port +//------------------------------------------------ +//assign btb_acc_tag[BTB_ADDR_WIDTH-1:0] = btb_entry_upd_vld | id_pred_btb_mis_pred +// ? btb_upd_tag[BTB_ADDR_WIDTH-1:0] : pcgen_btb_pc[BTB_ADDR_WIDTH-1:0]; +assign btb_rd_acc_tag[BTB_ADDR_WIDTH-1:0] = pcgen_btb_pc[BTB_ADDR_WIDTH-1:0]; +assign btb_wr_acc_tag[BTB_ADDR_WIDTH-1:0] = btb_upd_tag[BTB_ADDR_WIDTH-1:0]; + +assign btb_rd_hit_vld = |btb_entry_rd_hit[15:0]; +assign btb_wr_hit_vld = |btb_entry_wr_hit[15:0]; +assign btb_flop_vld = ctrl_btb_inst_fetch & btb_rd_hit_vld + & ~id_pred_btb_upd_vld & ~id_pred_btb_mis_pred; + +always @ (posedge btb_clk or negedge cpurst_b) +begin + if(~cpurst_b) + btb_entry_hit_flop[15:0] <= 16'b0; + else if(btb_flop_vld & ifetch_pcgen_grant) + btb_entry_hit_flop[15:0] <= btb_entry_rd_hit[15:0]; +end + +// &CombBeg; @194 +always @( btb_entry_tgt_10[15:0] + or btb_entry_tgt_2[15:0] + or btb_entry_tgt_9[15:0] + or btb_entry_tgt_5[15:0] + or btb_entry_tgt_3[15:0] + or btb_entry_tgt_14[15:0] + or btb_entry_tgt_13[15:0] + or btb_entry_tgt_7[15:0] + or btb_entry_tgt_0[15:0] + or btb_entry_tgt_4[15:0] + or btb_entry_tgt_8[15:0] + or btb_entry_tgt_12[15:0] + or btb_entry_tgt_6[15:0] + or btb_entry_tgt_11[15:0] + or btb_entry_tgt_1[15:0] + or btb_entry_tgt_15[15:0] + or btb_entry_hit_flop[15:0]) +begin +case(btb_entry_hit_flop[15:0]) + 16'b0000000000000001: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_0[BTB_ADDR_WIDTH-1:0]; + 16'b0000000000000010: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_1[BTB_ADDR_WIDTH-1:0]; + 16'b0000000000000100: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_2[BTB_ADDR_WIDTH-1:0]; + 16'b0000000000001000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_3[BTB_ADDR_WIDTH-1:0]; + 16'b0000000000010000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_4[BTB_ADDR_WIDTH-1:0]; + 16'b0000000000100000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_5[BTB_ADDR_WIDTH-1:0]; + 16'b0000000001000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_6[BTB_ADDR_WIDTH-1:0]; + 16'b0000000010000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_7[BTB_ADDR_WIDTH-1:0]; + 16'b0000000100000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_8[BTB_ADDR_WIDTH-1:0]; + 16'b0000001000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_9[BTB_ADDR_WIDTH-1:0]; + 16'b0000010000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_10[BTB_ADDR_WIDTH-1:0]; + 16'b0000100000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_11[BTB_ADDR_WIDTH-1:0]; + 16'b0001000000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_12[BTB_ADDR_WIDTH-1:0]; + 16'b0010000000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_13[BTB_ADDR_WIDTH-1:0]; + 16'b0100000000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_14[BTB_ADDR_WIDTH-1:0]; + 16'b1000000000000000: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = btb_entry_tgt_15[BTB_ADDR_WIDTH-1:0]; + default: btb_hit_tgt[BTB_ADDR_WIDTH-1:0] = {BTB_ADDR_WIDTH{1'bx}}; +endcase +// &CombEnd; @214 +end + +always @(posedge btb_clk or negedge cpurst_b) +begin + if(~cpurst_b) + btb_pred_flop <= 1'b0; + else if(iu_ifu_tar_pc_vld & cp0_ifu_btb_en) + btb_pred_flop <= 1'b0; + else if(btb_flop_vld & ifetch_pcgen_grant & cp0_ifu_btb_en) + btb_pred_flop <= 1'b1; + else + btb_pred_flop <= 1'b0; +end + +//========================================================== +// Rename for Output +//========================================================== + +// Output to pcgen +// &Force("bus", "pcgen_btb_pc", 31, 0); @233 +// &Force("bus", "pcgen_btb_addr", 31, 0); @234 +assign btb_xx_chgflw_vld = btb_pred_flop; +assign btb_pcgen_tar_pc[31:0] = {pcgen_btb_addr[31:BTB_ADDR_WIDTH], btb_hit_tgt[BTB_ADDR_WIDTH-1:0]}; + + + +// &ModuleEnd; @267 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..1aa68d91bd66b246750a7c5cf95e46abd31d3d73 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_btb_entry.v @@ -0,0 +1,164 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_btb_entry( + btb_entry_clr_x, + btb_entry_clrg_x, + btb_entry_rd_hit_x, + btb_entry_tgt_y, + btb_entry_upd_x, + btb_entry_updg_x, + btb_entry_wr_hit_x, + btb_rd_acc_tag, + btb_upd_tag, + btb_upd_tgt, + btb_wr_acc_tag, + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + pad_yy_icg_scan_en +); + +// &Ports; @24 +input btb_entry_clr_x; +input btb_entry_clrg_x; +input btb_entry_upd_x; +input btb_entry_updg_x; +input [15:0] btb_rd_acc_tag; +input [15:0] btb_upd_tag; +input [15:0] btb_upd_tgt; +input [15:0] btb_wr_acc_tag; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output btb_entry_rd_hit_x; +output [15:0] btb_entry_tgt_y; +output btb_entry_wr_hit_x; + +// &Regs; @25 +reg [15:0] btb_tag; +reg [15:0] btb_tgt; +reg btb_vld; + +// &Wires; @26 +wire btb_entry_clk; +wire btb_entry_clr_x; +wire btb_entry_clrg_x; +wire btb_entry_rd_hit_x; +wire [15:0] btb_entry_tgt_y; +wire btb_entry_upd_x; +wire btb_entry_updg_x; +wire btb_entry_wr_hit_x; +wire [15:0] btb_rd_acc_tag; +wire btb_rd_hit; +wire [15:0] btb_upd_tag; +wire [15:0] btb_upd_tgt; +wire [15:0] btb_wr_acc_tag; +wire btb_wr_hit; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry_clk_en; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; + + +//========================================================== +// BTB Entry Module +// 1. Instance ICG Cell +// 2. Entry Valid +// 3. Entry Content +// 4. Entry Hit +//========================================================== +parameter BTB_ADDR_WIDTH = 16; +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign entry_clk_en = btb_entry_clrg_x + | btb_entry_updg_x; +// &Instance("gated_clk_cell", "x_btb_entry_icg_cell"); @41 +gated_clk_cell x_btb_entry_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (btb_entry_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (entry_clk_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @42 +// .external_en(1'b0 ), @43 +// .global_en (cp0_yy_clk_en ), @44 +// .module_en (cp0_ifu_icg_en), @45 +// .local_en (entry_clk_en ), @46 +// .clk_out (btb_entry_clk ) @47 +// ); @48 + +//------------------------------------------------ +// 2. Entry Valid +//------------------------------------------------ +always @(posedge btb_entry_clk or negedge cpurst_b) +begin + if(~cpurst_b) + btb_vld <= 1'b0; + else if(btb_entry_clr_x) + btb_vld <= 1'b0; + else if(btb_entry_upd_x) + btb_vld <= 1'b1; +end + +//------------------------------------------------ +// 3. Entry Content +//------------------------------------------------ +always @(posedge btb_entry_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + btb_tag[BTB_ADDR_WIDTH-1:0] <= {BTB_ADDR_WIDTH{1'b0}}; + btb_tgt[BTB_ADDR_WIDTH-1:0] <= {BTB_ADDR_WIDTH{1'b0}}; + end + else if(btb_entry_upd_x) + begin + btb_tag[BTB_ADDR_WIDTH-1:0] <= btb_upd_tag[BTB_ADDR_WIDTH-1:0]; + btb_tgt[BTB_ADDR_WIDTH-1:0] <= btb_upd_tgt[BTB_ADDR_WIDTH-1:0]; + end +end + +//------------------------------------------------ +// 4. Entry Hit +//------------------------------------------------ +assign btb_rd_hit = btb_tag[BTB_ADDR_WIDTH-1:0] == btb_rd_acc_tag[BTB_ADDR_WIDTH-1:0] + & btb_vld; +assign btb_wr_hit = btb_tag[BTB_ADDR_WIDTH-1:0] == btb_wr_acc_tag[BTB_ADDR_WIDTH-1:0] + & btb_vld; + +//========================================================== +// Rename for Output +//========================================================== + +assign btb_entry_rd_hit_x = btb_rd_hit; +assign btb_entry_wr_hit_x = btb_wr_hit; +assign btb_entry_tgt_y[BTB_ADDR_WIDTH-1:0] = btb_tgt[BTB_ADDR_WIDTH-1:0]; + + +// &ModuleEnd; @108 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..4bd05b64cdf1e2f462ced056cc152ffd0bcf3ec3 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ctrl.v @@ -0,0 +1,157 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ctrl( + cp0_ifu_in_lpmd, + cp0_ifu_lpmd_req, + cp0_ifu_srst_mask, + cp0_ifu_srst_req, + ctrl_btb_inst_fetch, + ctrl_ibuf_pop_en, + ctrl_ifetch_req_abort, + ctrl_ifetch_req_vld, + ctrl_pcgen_inst_vld, + ctrl_pcgen_pipedown, + ibuf_ctrl_inst_fetch, + id_pred_ctrl_stall, + idu_ifu_id_stall, + idu_ifu_tail_vld, + ifetch_ctrl_inst_vld, + pcgen_ctrl_chgflw_vld, + rtu_ifu_dbg_mask, + rtu_ifu_flush_fe, + rtu_ifu_lockup_mask, + rtu_ifu_lockup_req, + rtu_yy_xx_dbgon, + rtu_yy_xx_tail_int_vld, + sysio_xx_halt_req, + vec_ctrl_reset_mask, + vec_ctrl_seq_mask +); + +// &Ports; @24 +input cp0_ifu_in_lpmd; +input cp0_ifu_lpmd_req; +input cp0_ifu_srst_mask; +input cp0_ifu_srst_req; +input ibuf_ctrl_inst_fetch; +input id_pred_ctrl_stall; +input idu_ifu_id_stall; +input idu_ifu_tail_vld; +input ifetch_ctrl_inst_vld; +input pcgen_ctrl_chgflw_vld; +input rtu_ifu_dbg_mask; +input rtu_ifu_flush_fe; +input rtu_ifu_lockup_mask; +input rtu_ifu_lockup_req; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_tail_int_vld; +input sysio_xx_halt_req; +input vec_ctrl_reset_mask; +input vec_ctrl_seq_mask; +output ctrl_btb_inst_fetch; +output ctrl_ibuf_pop_en; +output ctrl_ifetch_req_abort; +output ctrl_ifetch_req_vld; +output ctrl_pcgen_inst_vld; +output ctrl_pcgen_pipedown; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_ifu_in_lpmd; +wire cp0_ifu_lpmd_req; +wire cp0_ifu_srst_mask; +wire cp0_ifu_srst_req; +wire ctrl_btb_inst_fetch; +wire ctrl_ibuf_pop_en; +wire ctrl_if_abort; +wire ctrl_if_pipedown; +wire ctrl_ifetch_req_abort; +wire ctrl_ifetch_req_vld; +wire ctrl_inst_fetch; +wire ctrl_pcgen_inst_vld; +wire ctrl_pcgen_pipedown; +wire ibuf_ctrl_inst_fetch; +wire id_pred_ctrl_stall; +wire idu_ifu_id_stall; +wire idu_ifu_tail_vld; +wire ifetch_ctrl_inst_vld; +wire pcgen_ctrl_chgflw_vld; +wire rtu_ifu_dbg_mask; +wire rtu_ifu_flush_fe; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_tail_int_vld; +wire sysio_xx_halt_req; +wire vec_ctrl_reset_mask; +wire vec_ctrl_seq_mask; + + +//========================================================== +// IFU Control Module +// 1. Inst Fetch Requet Valid Signal +// 2. Inst Fetch Stage Pipe Signal +// 3. Flush Signal for IFU modules +//========================================================== + +//------------------------------------------------ +// 1. Inst Fetch Requet Valid Signal +// a. Fetch inst when chgflw or I-buf fetch +// b. Not fetch when lpmd or debug on +//------------------------------------------------ +assign ctrl_inst_fetch = ibuf_ctrl_inst_fetch + & ~(cp0_ifu_in_lpmd | cp0_ifu_lpmd_req) + & ~rtu_yy_xx_dbgon + & ~vec_ctrl_reset_mask + & ~cp0_ifu_srst_req + & ~cp0_ifu_srst_mask + & ~rtu_ifu_lockup_req + & ~rtu_ifu_lockup_mask + & ~rtu_ifu_dbg_mask + & ~sysio_xx_halt_req + & ~vec_ctrl_seq_mask; + +//------------------------------------------------ +// 2. Inst Fetch Stage Pipedown Signal +//------------------------------------------------ +assign ctrl_if_pipedown = ifetch_ctrl_inst_vld & ~id_pred_ctrl_stall; + +//------------------------------------------------ +// 3. Flush Signal for IFU modules +//------------------------------------------------ +assign ctrl_if_abort = rtu_ifu_flush_fe | pcgen_ctrl_chgflw_vld | idu_ifu_tail_vld | rtu_yy_xx_tail_int_vld; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to I-Buf +assign ctrl_ibuf_pop_en = ~idu_ifu_id_stall; + +assign ctrl_ifetch_req_vld = ctrl_inst_fetch; +assign ctrl_ifetch_req_abort = ctrl_if_abort; + +assign ctrl_pcgen_pipedown = ctrl_if_pipedown; +assign ctrl_pcgen_inst_vld = ifetch_ctrl_inst_vld; + +assign ctrl_btb_inst_fetch = ctrl_inst_fetch; + +// &ModuleEnd; @79 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf.v new file mode 100644 index 0000000000000000000000000000000000000000..4e76c169b5bdfaca113a3f28948f726f26afc849 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf.v @@ -0,0 +1,1278 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_ifu_ibuf( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_ibuf_pop_en, + dtu_ifu_debug_inst, + dtu_ifu_debug_inst_vld, + dtu_ifu_halt_info_vld, + forever_cpuclk, + ibuf_ctrl_inst_fetch, + ibuf_id_pred_hungry, + ibuf_ipack_stall, + ibuf_pred_stall, + ibuf_top_id_stall, + ibuf_top_vld_num, + id_pred_ibuf_br_taken0, + id_pred_ibuf_br_taken1, + id_pred_ibuf_chgflw_vld0, + id_pred_ibuf_halt_info0, + id_pred_ibuf_halt_info1, + idu_ifu_id_stall, + idu_ifu_tail_vld, + idu_ifu_tail_vld_gate, + ifetch_ibuf_idle, + ifetch_xx_not_busy, + ifu_idu_id_expt_high, + ifu_idu_id_expt_vld, + ifu_idu_id_halt_info, + ifu_idu_id_inst, + ifu_idu_id_inst_vld, + ifu_idu_id_pred_taken, + ipack_ibuf_acc_err, + ipack_ibuf_inst, + ipack_ibuf_inst_all, + ipack_ibuf_inst_empty, + ipack_ibuf_inst_full, + ipack_ibuf_inst_one, + ipack_ibuf_inst_one_raw, + ipack_ibuf_inst_two, + ipack_ibuf_inst_vld, + ipack_ibuf_inst_vld_raw, + pad_yy_icg_scan_en, + pcgen_ibuf_chgflw_vld, + rtu_ifu_flush_fe, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_vld, + rtu_yy_xx_tail_int_vld, + vec_ibuf_warm_up +); + +// &Ports; @25 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_ibuf_pop_en; +input [31:0] dtu_ifu_debug_inst; +input dtu_ifu_debug_inst_vld; +input dtu_ifu_halt_info_vld; +input forever_cpuclk; +input [1 :0] id_pred_ibuf_br_taken0; +input [1 :0] id_pred_ibuf_br_taken1; +input id_pred_ibuf_chgflw_vld0; +input [14:0] id_pred_ibuf_halt_info0; +input [14:0] id_pred_ibuf_halt_info1; +input idu_ifu_id_stall; +input idu_ifu_tail_vld; +input idu_ifu_tail_vld_gate; +input ifetch_ibuf_idle; +input ifetch_xx_not_busy; +input [2 :0] ipack_ibuf_acc_err; +input [47:0] ipack_ibuf_inst; +input ipack_ibuf_inst_all; +input ipack_ibuf_inst_empty; +input ipack_ibuf_inst_full; +input ipack_ibuf_inst_one; +input ipack_ibuf_inst_one_raw; +input ipack_ibuf_inst_two; +input ipack_ibuf_inst_vld; +input ipack_ibuf_inst_vld_raw; +input pad_yy_icg_scan_en; +input pcgen_ibuf_chgflw_vld; +input rtu_ifu_flush_fe; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_tail_int_vld; +input vec_ibuf_warm_up; +output ibuf_ctrl_inst_fetch; +output ibuf_id_pred_hungry; +output ibuf_ipack_stall; +output ibuf_pred_stall; +output ibuf_top_id_stall; +output [2 :0] ibuf_top_vld_num; +output ifu_idu_id_expt_high; +output ifu_idu_id_expt_vld; +output [14:0] ifu_idu_id_halt_info; +output [31:0] ifu_idu_id_inst; +output ifu_idu_id_inst_vld; +output [1 :0] ifu_idu_id_pred_taken; + +// &Regs; @26 +reg [5 :0] pop0; +reg pop0_acc_err; +reg [14:0] pop0_halt_info; +reg [15:0] pop0_inst; +reg [1 :0] pop0_pred_taken; +reg [5 :0] pop0_shift; +reg pop0_vld; +reg pop1_acc_err; +reg [14:0] pop1_halt_info; +reg [15:0] pop1_inst; +reg [1 :0] pop1_pred_taken; +reg pop1_vld; +reg [5 :0] push0; +reg [5 :0] push0_shift; + +// &Wires; @27 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_ibuf_pop_en; +wire dtu_create0_en; +wire dtu_create1_en; +wire [31:0] dtu_ifu_debug_inst; +wire dtu_ifu_debug_inst_vld; +wire dtu_ifu_halt_info_vld; +wire entry0_acc_err; +wire entry0_create0_data_en; +wire entry0_create0_en; +wire entry0_create1_data_en; +wire entry0_create1_en; +wire entry0_create2_data_en; +wire entry0_create2_en; +wire [14:0] entry0_halt_info; +wire [15:0] entry0_inst; +wire [1 :0] entry0_pred_taken; +wire entry0_retire0_en; +wire entry0_retire1_en; +wire entry0_vld; +wire entry1_acc_err; +wire entry1_create0_data_en; +wire entry1_create0_en; +wire entry1_create1_data_en; +wire entry1_create1_en; +wire entry1_create2_data_en; +wire entry1_create2_en; +wire [14:0] entry1_halt_info; +wire [15:0] entry1_inst; +wire [1 :0] entry1_pred_taken; +wire entry1_retire0_en; +wire entry1_retire1_en; +wire entry1_vld; +wire entry2_acc_err; +wire entry2_create0_data_en; +wire entry2_create0_en; +wire entry2_create1_data_en; +wire entry2_create1_en; +wire entry2_create2_data_en; +wire entry2_create2_en; +wire [14:0] entry2_halt_info; +wire [15:0] entry2_inst; +wire [1 :0] entry2_pred_taken; +wire entry2_retire0_en; +wire entry2_retire1_en; +wire entry2_vld; +wire entry3_acc_err; +wire entry3_create0_data_en; +wire entry3_create0_en; +wire entry3_create1_data_en; +wire entry3_create1_en; +wire entry3_create2_data_en; +wire entry3_create2_en; +wire [14:0] entry3_halt_info; +wire [15:0] entry3_inst; +wire [1 :0] entry3_pred_taken; +wire entry3_retire0_en; +wire entry3_retire1_en; +wire entry3_vld; +wire entry4_acc_err; +wire entry4_create0_data_en; +wire entry4_create0_en; +wire entry4_create1_data_en; +wire entry4_create1_en; +wire entry4_create2_data_en; +wire entry4_create2_en; +wire [14:0] entry4_halt_info; +wire [15:0] entry4_inst; +wire [1 :0] entry4_pred_taken; +wire entry4_retire0_en; +wire entry4_retire1_en; +wire entry4_vld; +wire entry5_acc_err; +wire entry5_create0_data_en; +wire entry5_create0_en; +wire entry5_create1_data_en; +wire entry5_create1_en; +wire entry5_create2_data_en; +wire entry5_create2_en; +wire [14:0] entry5_halt_info; +wire [15:0] entry5_inst; +wire [1 :0] entry5_pred_taken; +wire entry5_retire0_en; +wire entry5_retire1_en; +wire entry5_vld; +wire forever_cpuclk; +wire ibuf_cpuclk; +wire ibuf_create0_acc_err; +wire ibuf_create0_data_en; +wire ibuf_create0_en; +wire [14:0] ibuf_create0_halt_info; +wire [15:0] ibuf_create0_inst; +wire [1 :0] ibuf_create0_pred_taken; +wire ibuf_create1_acc_err; +wire ibuf_create1_data_en; +wire ibuf_create1_en; +wire [14:0] ibuf_create1_halt_info; +wire [15:0] ibuf_create1_inst; +wire [1 :0] ibuf_create1_pred_taken; +wire ibuf_create2_acc_err; +wire ibuf_create2_data_en; +wire ibuf_create2_en; +wire [14:0] ibuf_create2_halt_info; +wire [15:0] ibuf_create2_inst; +wire [1 :0] ibuf_create2_pred_taken; +wire ibuf_ctrl_inst_fetch; +wire ibuf_empty; +wire ibuf_entry_stall; +wire ibuf_fetch_empty; +wire ibuf_fetch_five; +wire ibuf_fetch_four; +wire ibuf_fetch_three; +wire ibuf_fetch_two; +wire ibuf_five_avalbe; +wire ibuf_flush_en; +wire ibuf_flush_en_gate; +wire ibuf_four_avalbe; +wire ibuf_full; +wire ibuf_icg_en; +wire ibuf_id_pred_hungry; +wire ibuf_inst32; +wire ibuf_inst_32_vld; +wire ibuf_inst_fetch; +wire ibuf_ipack_stall; +wire ibuf_one_avalbe; +wire ibuf_pred_stall; +wire ibuf_retire0_en; +wire ibuf_retire0_en_vld; +wire ibuf_retire1_en; +wire ibuf_stall; +wire ibuf_three_avalbe; +wire ibuf_top_id_stall; +wire [2 :0] ibuf_top_vld_num; +wire ibuf_two_avalbe; +wire [2 :0] ibuf_vld_num; +wire [1 :0] id_pred_ibuf_br_taken0; +wire [1 :0] id_pred_ibuf_br_taken1; +wire id_pred_ibuf_chgflw_vld0; +wire [14:0] id_pred_ibuf_halt_info0; +wire [14:0] id_pred_ibuf_halt_info1; +wire idu_ifu_id_stall; +wire idu_ifu_tail_vld; +wire idu_ifu_tail_vld_gate; +wire ifetch_ibuf_idle; +wire ifetch_xx_not_busy; +wire ifu_idu_id_expt_high; +wire ifu_idu_id_expt_vld; +wire [14:0] ifu_idu_id_halt_info; +wire [31:0] ifu_idu_id_inst; +wire ifu_idu_id_inst_vld; +wire [1 :0] ifu_idu_id_pred_taken; +wire ipack_bypass_vld; +wire ipack_create0_data_en; +wire ipack_create0_en; +wire ipack_create1_data_en; +wire ipack_create1_en; +wire ipack_expt_high; +wire [2 :0] ipack_ibuf_acc_err; +wire [47:0] ipack_ibuf_inst; +wire ipack_ibuf_inst_all; +wire ipack_ibuf_inst_empty; +wire ipack_ibuf_inst_full; +wire ipack_ibuf_inst_one; +wire ipack_ibuf_inst_one_raw; +wire ipack_ibuf_inst_two; +wire ipack_ibuf_inst_vld; +wire ipack_ibuf_inst_vld_raw; +wire ipack_inst_32; +wire pad_yy_icg_scan_en; +wire pcgen_ibuf_chgflw_vld; +wire pop0_inst_32; +wire [5 :0] pop1; +wire pop_entry0_acc_err; +wire pop_entry0_create_acc_err; +wire pop_entry0_create_data_en; +wire pop_entry0_create_en; +wire [14:0] pop_entry0_create_halt_info; +wire [15:0] pop_entry0_create_inst; +wire [1 :0] pop_entry0_create_pred_taken; +wire [14:0] pop_entry0_halt_info; +wire [15:0] pop_entry0_inst; +wire [1 :0] pop_entry0_pred_taken; +wire pop_entry0_retire_en; +wire pop_entry0_vld; +wire pop_entry1_acc_err; +wire pop_entry1_create_acc_err; +wire pop_entry1_create_data_en; +wire pop_entry1_create_en; +wire [14:0] pop_entry1_create_halt_info; +wire [15:0] pop_entry1_create_inst; +wire [1 :0] pop_entry1_create_pred_taken; +wire [14:0] pop_entry1_halt_info; +wire [15:0] pop_entry1_inst; +wire [1 :0] pop_entry1_pred_taken; +wire pop_entry1_retire_en; +wire pop_entry1_vld; +wire pop_entry_acc_err; +wire pop_entry_expt_high; +wire [14:0] pop_entry_halt_info; +wire [31:0] pop_entry_inst; +wire [1 :0] pop_entry_pred_taken; +wire pop_entry_vld; +wire [5 :0] push0_bypass; +wire [5 :0] push1; +wire [5 :0] push1_bypass; +wire [5 :0] push2; +wire [5 :0] push2_bypass; +wire rtu_ifu_flush_fe; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_tail_int_vld; +wire vec_ibuf_warm_up; + + +//========================================================== +// Instruction Buffer Module +// 1. Instance ICG cells +// 2. Instance I-Buffer Entries +// 3. I-Buffer Read Port +// 4. I-Buffer Write Port +// 5. Valid Instruction Generation +// 6. I-Buffer Pop Entry +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG cells +//------------------------------------------------ +assign ibuf_icg_en = ~ibuf_empty + | pop0_vld + | pop_entry_vld + | ibuf_flush_en_gate + | ipack_ibuf_inst_vld + | dtu_create0_en; +// &Instance("gated_clk_cell", "x_ifu_ibuf_icg_cell"); @48 +gated_clk_cell x_ifu_ibuf_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (ibuf_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ibuf_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @49 +// .external_en (1'b0), @50 +// .global_en (cp0_yy_clk_en), @51 +// .module_en (cp0_ifu_icg_en), @52 +// .local_en (ibuf_icg_en), @53 +// .clk_out (ibuf_cpuclk) @54 +// ); @55 + +//------------------------------------------------ +// 2. Instance I-Buffer Entries +//------------------------------------------------ +parameter ENTRY_NUM = 6; + +// &ConnRule(s/ibuf_entry/entry0/); @62 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry0"); @63 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry0 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry0_acc_err ), + .ibuf_entry_create0_data_en (entry0_create0_data_en ), + .ibuf_entry_create0_en (entry0_create0_en ), + .ibuf_entry_create1_data_en (entry0_create1_data_en ), + .ibuf_entry_create1_en (entry0_create1_en ), + .ibuf_entry_create2_data_en (entry0_create2_data_en ), + .ibuf_entry_create2_en (entry0_create2_en ), + .ibuf_entry_halt_info (entry0_halt_info ), + .ibuf_entry_inst (entry0_inst ), + .ibuf_entry_pred_taken (entry0_pred_taken ), + .ibuf_entry_retire0_en (entry0_retire0_en ), + .ibuf_entry_retire1_en (entry0_retire1_en ), + .ibuf_entry_vld (entry0_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/entry1/); @65 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry1"); @66 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry1 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry1_acc_err ), + .ibuf_entry_create0_data_en (entry1_create0_data_en ), + .ibuf_entry_create0_en (entry1_create0_en ), + .ibuf_entry_create1_data_en (entry1_create1_data_en ), + .ibuf_entry_create1_en (entry1_create1_en ), + .ibuf_entry_create2_data_en (entry1_create2_data_en ), + .ibuf_entry_create2_en (entry1_create2_en ), + .ibuf_entry_halt_info (entry1_halt_info ), + .ibuf_entry_inst (entry1_inst ), + .ibuf_entry_pred_taken (entry1_pred_taken ), + .ibuf_entry_retire0_en (entry1_retire0_en ), + .ibuf_entry_retire1_en (entry1_retire1_en ), + .ibuf_entry_vld (entry1_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/entry2/); @68 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry2"); @69 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry2 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry2_acc_err ), + .ibuf_entry_create0_data_en (entry2_create0_data_en ), + .ibuf_entry_create0_en (entry2_create0_en ), + .ibuf_entry_create1_data_en (entry2_create1_data_en ), + .ibuf_entry_create1_en (entry2_create1_en ), + .ibuf_entry_create2_data_en (entry2_create2_data_en ), + .ibuf_entry_create2_en (entry2_create2_en ), + .ibuf_entry_halt_info (entry2_halt_info ), + .ibuf_entry_inst (entry2_inst ), + .ibuf_entry_pred_taken (entry2_pred_taken ), + .ibuf_entry_retire0_en (entry2_retire0_en ), + .ibuf_entry_retire1_en (entry2_retire1_en ), + .ibuf_entry_vld (entry2_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/entry3/); @71 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry3"); @72 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry3 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry3_acc_err ), + .ibuf_entry_create0_data_en (entry3_create0_data_en ), + .ibuf_entry_create0_en (entry3_create0_en ), + .ibuf_entry_create1_data_en (entry3_create1_data_en ), + .ibuf_entry_create1_en (entry3_create1_en ), + .ibuf_entry_create2_data_en (entry3_create2_data_en ), + .ibuf_entry_create2_en (entry3_create2_en ), + .ibuf_entry_halt_info (entry3_halt_info ), + .ibuf_entry_inst (entry3_inst ), + .ibuf_entry_pred_taken (entry3_pred_taken ), + .ibuf_entry_retire0_en (entry3_retire0_en ), + .ibuf_entry_retire1_en (entry3_retire1_en ), + .ibuf_entry_vld (entry3_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/entry4/); @74 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry4"); @75 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry4 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry4_acc_err ), + .ibuf_entry_create0_data_en (entry4_create0_data_en ), + .ibuf_entry_create0_en (entry4_create0_en ), + .ibuf_entry_create1_data_en (entry4_create1_data_en ), + .ibuf_entry_create1_en (entry4_create1_en ), + .ibuf_entry_create2_data_en (entry4_create2_data_en ), + .ibuf_entry_create2_en (entry4_create2_en ), + .ibuf_entry_halt_info (entry4_halt_info ), + .ibuf_entry_inst (entry4_inst ), + .ibuf_entry_pred_taken (entry4_pred_taken ), + .ibuf_entry_retire0_en (entry4_retire0_en ), + .ibuf_entry_retire1_en (entry4_retire1_en ), + .ibuf_entry_vld (entry4_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/entry5/); @77 +// &Instance("pa_ifu_ibuf_entry","x_pa_ifu_ibuf_entry5"); @78 +pa_ifu_ibuf_entry x_pa_ifu_ibuf_entry5 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_create0_acc_err (ibuf_create0_acc_err ), + .ibuf_create0_halt_info (ibuf_create0_halt_info ), + .ibuf_create0_inst (ibuf_create0_inst ), + .ibuf_create0_pred_taken (ibuf_create0_pred_taken ), + .ibuf_create1_acc_err (ibuf_create1_acc_err ), + .ibuf_create1_halt_info (ibuf_create1_halt_info ), + .ibuf_create1_inst (ibuf_create1_inst ), + .ibuf_create1_pred_taken (ibuf_create1_pred_taken ), + .ibuf_create2_acc_err (ibuf_create2_acc_err ), + .ibuf_create2_halt_info (ibuf_create2_halt_info ), + .ibuf_create2_inst (ibuf_create2_inst ), + .ibuf_create2_pred_taken (ibuf_create2_pred_taken ), + .ibuf_entry_acc_err (entry5_acc_err ), + .ibuf_entry_create0_data_en (entry5_create0_data_en ), + .ibuf_entry_create0_en (entry5_create0_en ), + .ibuf_entry_create1_data_en (entry5_create1_data_en ), + .ibuf_entry_create1_en (entry5_create1_en ), + .ibuf_entry_create2_data_en (entry5_create2_data_en ), + .ibuf_entry_create2_en (entry5_create2_en ), + .ibuf_entry_halt_info (entry5_halt_info ), + .ibuf_entry_inst (entry5_inst ), + .ibuf_entry_pred_taken (entry5_pred_taken ), + .ibuf_entry_retire0_en (entry5_retire0_en ), + .ibuf_entry_retire1_en (entry5_retire1_en ), + .ibuf_entry_vld (entry5_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +//------------------------------------------------ +// 3. I-Buffer Read Port +// a. Retire Information out of Instruction Buffer +//------------------------------------------------ +// a. Retire Information out of Instruction Buffer +// The instruction will be retired in inst buf when +// it can be piped down to ID stage +assign ibuf_retire0_en = pop0_vld & ctrl_ibuf_pop_en; +assign ibuf_retire1_en = ibuf_inst32 & ctrl_ibuf_pop_en; + +assign ibuf_retire0_en_vld = ibuf_retire0_en; +assign ibuf_inst_32_vld = ibuf_inst32; + +assign ibuf_flush_en = rtu_ifu_flush_fe | pcgen_ibuf_chgflw_vld | idu_ifu_tail_vld | rtu_yy_xx_tail_int_vld | rtu_yy_xx_expt_vld; +assign ibuf_flush_en_gate = rtu_ifu_flush_fe | pcgen_ibuf_chgflw_vld | idu_ifu_tail_vld_gate | rtu_yy_xx_tail_int_vld | rtu_yy_xx_expt_vld; + +//pop0 +always @(posedge ibuf_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + pop0[ENTRY_NUM-1:0] <= {{(ENTRY_NUM-1){1'b0}}, 1'b1}; + else if(ibuf_flush_en) + pop0[ENTRY_NUM-1:0] <= pop0[ENTRY_NUM-1:0]; + else if(ibuf_retire0_en_vld) + pop0[ENTRY_NUM-1:0] <= pop0_shift[ENTRY_NUM-1:0]; +end + +// &CombBeg; @107 +always @( pop0[5:0] + or ibuf_inst_32_vld) +begin + if(ibuf_inst_32_vld) + pop0_shift[ENTRY_NUM-1:0] = {pop0[ENTRY_NUM-3:0], + pop0[ENTRY_NUM-1:ENTRY_NUM-2]}; + else + pop0_shift[ENTRY_NUM-1:0] = {pop0[ENTRY_NUM-2:0], + pop0[ENTRY_NUM-1]}; +// &CombEnd; @114 +end + +//retire0 +assign {entry5_retire0_en, + entry4_retire0_en, + entry3_retire0_en, + entry2_retire0_en, + entry1_retire0_en, + entry0_retire0_en} = pop0[ENTRY_NUM-1:0] & {ENTRY_NUM{ibuf_retire0_en}}; + +//pop1 +assign pop1[ENTRY_NUM-1:0] = {pop0[ENTRY_NUM-2:0], + pop0[ENTRY_NUM-1]}; + +//retire1 +assign {entry5_retire1_en, + entry4_retire1_en, + entry3_retire1_en, + entry2_retire1_en, + entry1_retire1_en, + entry0_retire1_en} = pop1[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_retire1_en}}; + +// &CombBeg; @137 +always @( entry1_halt_info[14:0] + or entry3_acc_err + or entry1_vld + or entry1_acc_err + or entry2_inst[15:0] + or entry5_inst[15:0] + or entry4_acc_err + or entry3_halt_info[14:0] + or entry0_acc_err + or entry4_pred_taken[1:0] + or entry4_halt_info[14:0] + or entry0_pred_taken[1:0] + or entry5_acc_err + or entry5_vld + or entry2_halt_info[14:0] + or entry4_inst[15:0] + or entry2_vld + or entry0_vld + or entry5_halt_info[14:0] + or entry1_inst[15:0] + or entry3_vld + or entry5_pred_taken[1:0] + or entry4_vld + or entry2_acc_err + or entry3_inst[15:0] + or pop0[5:0] + or entry0_halt_info[14:0] + or entry2_pred_taken[1:0] + or entry3_pred_taken[1:0] + or entry1_pred_taken[1:0] + or entry0_inst[15:0]) +begin + case(pop0[ENTRY_NUM-1:0]) + 6'b0001: + begin + pop0_vld = entry0_vld; + pop0_inst[15:0] = entry0_inst[15:0]; + pop0_pred_taken[1:0] = entry0_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry0_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry0_acc_err; + end + 6'b0010: + begin + pop0_vld = entry1_vld; + pop0_inst[15:0] = entry1_inst[15:0]; + pop0_pred_taken[1:0] = entry1_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry1_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry1_acc_err; + end + 6'b0100: + begin + pop0_vld = entry2_vld; + pop0_inst[15:0] = entry2_inst[15:0]; + pop0_pred_taken[1:0] = entry2_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry2_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry2_acc_err; + end + 6'b1000: + begin + pop0_vld = entry3_vld; + pop0_inst[15:0] = entry3_inst[15:0]; + pop0_pred_taken[1:0] = entry3_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry3_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry3_acc_err; + end + 6'b10000: + begin + pop0_vld = entry4_vld; + pop0_inst[15:0] = entry4_inst[15:0]; + pop0_pred_taken[1:0] = entry4_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry4_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry4_acc_err; + end + 6'b100000: + begin + pop0_vld = entry5_vld; + pop0_inst[15:0] = entry5_inst[15:0]; + pop0_pred_taken[1:0] = entry5_pred_taken[1:0]; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = entry5_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop0_acc_err = entry5_acc_err; + end + default: + begin + pop0_vld = 1'bx; + pop0_inst[15:0] = {16{1'bx}}; + pop0_pred_taken[1:0] = {2{1'bx}}; + pop0_halt_info[`TDT_HINFO_WIDTH-1:0] = {`TDT_HINFO_WIDTH{1'bx}}; + pop0_acc_err = 1'bx; + end + endcase +// &CombEnd; @196 +end + +//The information which is index by pop1 pointer +// &CombBeg; @199 +always @( entry1_halt_info[14:0] + or entry3_acc_err + or entry1_vld + or entry1_acc_err + or entry2_inst[15:0] + or entry5_inst[15:0] + or entry4_acc_err + or entry3_halt_info[14:0] + or entry0_acc_err + or entry4_pred_taken[1:0] + or entry4_halt_info[14:0] + or entry0_pred_taken[1:0] + or entry5_acc_err + or entry5_vld + or entry2_halt_info[14:0] + or entry4_inst[15:0] + or entry2_vld + or entry0_vld + or entry5_halt_info[14:0] + or entry1_inst[15:0] + or entry3_vld + or entry5_pred_taken[1:0] + or entry4_vld + or entry2_acc_err + or entry3_inst[15:0] + or entry0_halt_info[14:0] + or pop1[5:0] + or entry2_pred_taken[1:0] + or entry3_pred_taken[1:0] + or entry1_pred_taken[1:0] + or entry0_inst[15:0]) +begin + case(pop1[ENTRY_NUM-1:0]) + 6'b0001: + begin + pop1_vld = entry0_vld; + pop1_inst[15:0] = entry0_inst[15:0]; + pop1_pred_taken[1:0] = entry0_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry0_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry0_acc_err; + end + 6'b0010: + begin + pop1_vld = entry1_vld; + pop1_inst[15:0] = entry1_inst[15:0]; + pop1_pred_taken[1:0] = entry1_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry1_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry1_acc_err; + end + 6'b0100: + begin + pop1_vld = entry2_vld; + pop1_inst[15:0] = entry2_inst[15:0]; + pop1_pred_taken[1:0] = entry2_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry2_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry2_acc_err; + end + 6'b1000: + begin + pop1_vld = entry3_vld; + pop1_inst[15:0] = entry3_inst[15:0]; + pop1_pred_taken[1:0] = entry3_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry3_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry3_acc_err; + end + 6'b10000: + begin + pop1_vld = entry4_vld; + pop1_inst[15:0] = entry4_inst[15:0]; + pop1_pred_taken[1:0] = entry4_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry4_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry4_acc_err; + end + 6'b100000: + begin + pop1_vld = entry5_vld; + pop1_inst[15:0] = entry5_inst[15:0]; + pop1_pred_taken[1:0] = entry5_pred_taken[1:0]; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = entry5_halt_info[`TDT_HINFO_WIDTH-1:0]; + pop1_acc_err = entry5_acc_err; + end + default: + begin + pop1_vld = 1'bx; + pop1_inst[15:0] = {16{1'bx}}; + pop1_pred_taken[1:0] = {2{1'bx}}; + pop1_halt_info[`TDT_HINFO_WIDTH-1:0] = {`TDT_HINFO_WIDTH{1'bx}}; + pop1_acc_err = 1'bx; + end + endcase +// &CombEnd; @258 +end + +//------------------------------------------------ +// 4. I-Buffer Write Port +// a. Create Information into I-Buffer +// b. Generate Entry Create Signal for Each Entry +// c. Generate Entry Create Instruction +//------------------------------------------------ +// a. Create Information into I-Buffer +// the create0 signal +assign ipack_bypass_vld = ibuf_empty & ipack_ibuf_inst_vld; +assign ipack_create0_en = ipack_ibuf_inst_vld + & ~(ibuf_empty & + (ipack_ibuf_inst_two & ~pop_entry_vld & ~idu_ifu_id_stall + | ipack_ibuf_inst_one & ~pop_entry_vld + | ipack_ibuf_inst_one & ~idu_ifu_id_stall + | ipack_inst_32 & ~ipack_ibuf_inst_all & ~pop_entry_vld + | ipack_inst_32 & ~ipack_ibuf_inst_all & ~idu_ifu_id_stall)); + +assign ipack_create0_data_en = ipack_ibuf_inst_vld_raw & ~ibuf_entry_stall + & (~ibuf_empty | pop_entry_vld | ipack_ibuf_inst_two); +assign dtu_create0_en = rtu_yy_xx_dbgon & dtu_ifu_debug_inst_vld; + +assign ibuf_create0_en = ipack_create0_en | dtu_create0_en; +assign ibuf_create0_data_en = ipack_create0_data_en | dtu_create0_en; + +// &Force("bus", "dtu_ifu_debug_inst", 31, 0); @284 +// the create1 signal +assign ipack_create1_en = ipack_ibuf_inst_vld & ~ipack_ibuf_inst_one + & (~ibuf_empty | idu_ifu_id_stall & pop_entry_vld); +assign ipack_create1_data_en = ipack_ibuf_inst_vld_raw & ~ibuf_entry_stall & ~ipack_ibuf_inst_one + & (~ibuf_empty | pop_entry_vld); +assign dtu_create1_en = dtu_create0_en & dtu_ifu_debug_inst[1:0] == 2'b11; + +assign ibuf_create1_en = ipack_create1_en | dtu_create1_en; +assign ibuf_create1_data_en = ipack_create1_data_en | dtu_create1_en; + +// the create2 signal +assign ibuf_create2_en = ipack_ibuf_inst_vld & ipack_ibuf_inst_all + & ~id_pred_ibuf_chgflw_vld0 + & (~ibuf_empty | idu_ifu_id_stall & pop_entry_vld); +assign ibuf_create2_data_en = ipack_ibuf_inst_vld_raw & ~ibuf_entry_stall & ipack_ibuf_inst_all + & ~id_pred_ibuf_chgflw_vld0 + & (~ibuf_empty | pop_entry_vld); + +// b. Generate Entry Create Signal for Each Entry +//push0 +always @(posedge ibuf_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + push0[ENTRY_NUM-1:0] <= {{(ENTRY_NUM-1){1'b0}}, 1'b1}; + else if(ibuf_flush_en) + push0[ENTRY_NUM-1:0] <= pop0[ENTRY_NUM-1:0]; + else if(ibuf_create0_en) + push0[ENTRY_NUM-1:0] <= push0_shift[ENTRY_NUM-1:0]; +end + +// &CombBeg; @315 +always @( push0[5:0] + or ibuf_create1_en + or ibuf_create2_en) +begin + if(ibuf_create2_en) + push0_shift[ENTRY_NUM-1:0] = {push0[ENTRY_NUM-4:0], + push0[ENTRY_NUM-1:ENTRY_NUM-3]}; + else if(ibuf_create1_en) + push0_shift[ENTRY_NUM-1:0] = {push0[ENTRY_NUM-3:0], + push0[ENTRY_NUM-1:ENTRY_NUM-2]}; + else + push0_shift[ENTRY_NUM-1:0] = {push0[ENTRY_NUM-2:0], + push0[ENTRY_NUM-1]}; +// &CombEnd; @325 +end + +assign push0_bypass[ENTRY_NUM-1:0] = push0[ENTRY_NUM-1:0]; + +//create0 +assign {entry5_create0_en, + entry4_create0_en, + entry3_create0_en, + entry2_create0_en, + entry1_create0_en, + entry0_create0_en} = push0_bypass[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create0_en}}; + +assign {entry5_create0_data_en, + entry4_create0_data_en, + entry3_create0_data_en, + entry2_create0_data_en, + entry1_create0_data_en, + entry0_create0_data_en} = push0[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create0_data_en}}; + +//push1 +assign push1[ENTRY_NUM-1:0] = {push0[ENTRY_NUM-2:0], + push0[ENTRY_NUM-1]}; + +//push1 +assign push1_bypass[ENTRY_NUM-1:0] = {push0_bypass[ENTRY_NUM-2:0], + push0_bypass[ENTRY_NUM-1]}; + +//create1 +assign {entry5_create1_en, + entry4_create1_en, + entry3_create1_en, + entry2_create1_en, + entry1_create1_en, + entry0_create1_en} = push1_bypass[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create1_en}}; + +assign {entry5_create1_data_en, + entry4_create1_data_en, + entry3_create1_data_en, + entry2_create1_data_en, + entry1_create1_data_en, + entry0_create1_data_en} = push1[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create1_data_en}}; + +//push2 +assign push2[ENTRY_NUM-1:0] = {push0[ENTRY_NUM-3:0], + push0[ENTRY_NUM-1:ENTRY_NUM-2]}; + +//push2 +assign push2_bypass[ENTRY_NUM-1:0] = {push0_bypass[ENTRY_NUM-3:0], + push0_bypass[ENTRY_NUM-1:ENTRY_NUM-2]}; + +//create1 +assign {entry5_create2_en, + entry4_create2_en, + entry3_create2_en, + entry2_create2_en, + entry1_create2_en, + entry0_create2_en} = push2_bypass[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create2_en}}; + +assign {entry5_create2_data_en, + entry4_create2_data_en, + entry3_create2_data_en, + entry2_create2_data_en, + entry1_create2_data_en, + entry0_create2_data_en} = push2[ENTRY_NUM-1:0] & + {ENTRY_NUM{ibuf_create2_data_en}}; + +// c. Generate Entry Create Instruction +assign ipack_inst_32 = ipack_ibuf_inst[1:0] == 2'b11; +assign ibuf_create0_inst[15:0] = // create dtu low inst when dbg on + rtu_yy_xx_dbgon ? dtu_ifu_debug_inst[15:0] + // create ipack up inst when pop entry + // empty and ipack full + : ipack_ibuf_inst_full & (~pop_entry_vld + | ~idu_ifu_id_stall & ibuf_empty) + ? ipack_ibuf_inst[47:32] + // create ipack high inst when pop entry + // empty and ipack first 16-bit + : ipack_ibuf_inst_two & ~ipack_inst_32 + & (~pop_entry_vld | ~idu_ifu_id_stall & ibuf_empty) + ? ipack_ibuf_inst[31:16] + : ipack_ibuf_inst[15:0]; +assign ibuf_create1_inst[15:0] = // create dtu high inst when dbg on + rtu_yy_xx_dbgon ? dtu_ifu_debug_inst[31:16] + : ipack_ibuf_inst[31:16]; +assign ibuf_create2_inst[15:0] = ipack_ibuf_inst[47:32]; + +assign ibuf_create0_pred_taken[1:0] = ipack_ibuf_inst_two + & (~pop_entry_vld | ~idu_ifu_id_stall & ibuf_empty) + ? id_pred_ibuf_br_taken1[1:0] + : id_pred_ibuf_br_taken0[1:0]; +assign ibuf_create1_pred_taken[1:0] = id_pred_ibuf_br_taken1[1:0]; +assign ibuf_create2_pred_taken[1:0] = id_pred_ibuf_br_taken1[1:0]; + +assign ibuf_create0_halt_info[`TDT_HINFO_WIDTH-1:0] = ipack_ibuf_inst_two + & (~pop_entry_vld | ~idu_ifu_id_stall & ibuf_empty) + ? id_pred_ibuf_halt_info1[`TDT_HINFO_WIDTH-1:0] + : id_pred_ibuf_halt_info0[`TDT_HINFO_WIDTH-1:0]; +assign ibuf_create1_halt_info[`TDT_HINFO_WIDTH-1:0] = id_pred_ibuf_halt_info1[`TDT_HINFO_WIDTH-1:0]; +assign ibuf_create2_halt_info[`TDT_HINFO_WIDTH-1:0] = id_pred_ibuf_halt_info1[`TDT_HINFO_WIDTH-1:0]; + +assign ibuf_create0_acc_err = ipack_ibuf_acc_err[0]; +assign ibuf_create1_acc_err = ipack_ibuf_acc_err[1]; +assign ibuf_create2_acc_err = ipack_ibuf_acc_err[2]; + +//------------------------------------------------ +// 5. Valid Instruction Generation +// a. The I-Buffer status signal +// b. The Valid Instruction +//------------------------------------------------ +// a. The I-Buffer status signal +//------------------------------------------------ +assign ibuf_vld_num[2:0] = {2'b0, entry0_vld} + + {2'b0, entry1_vld} + + {2'b0, entry2_vld} + + {2'b0, entry3_vld} + + {2'b0, entry4_vld} + + {2'b0, entry5_vld}; + +assign ibuf_full = ibuf_vld_num[2:0] == 3'b110; +assign ibuf_one_avalbe = ibuf_vld_num[2:0] == 3'b101; +assign ibuf_two_avalbe = ibuf_vld_num[2:0] == 3'b100; +assign ibuf_three_avalbe = ibuf_vld_num[2:0] == 3'b011; +assign ibuf_four_avalbe = ibuf_vld_num[2:0] == 3'b010; +assign ibuf_five_avalbe = ibuf_vld_num[2:0] == 3'b001; +//assign ibuf_empty = ibuf_vld_num[2:0] == 3'b000; +assign ibuf_empty = ~(entry0_vld | entry1_vld | entry2_vld + | entry3_vld | entry4_vld | entry5_vld); + +assign ibuf_entry_stall = ibuf_full & ipack_ibuf_inst_vld_raw + | ibuf_one_avalbe & ipack_ibuf_inst_vld_raw + & ~ipack_ibuf_inst_one_raw + | ibuf_two_avalbe & ipack_ibuf_inst_full; +assign ibuf_stall = ibuf_entry_stall | ~dtu_ifu_halt_info_vld & ipack_ibuf_inst_vld_raw; + +assign ibuf_fetch_empty = ibuf_empty; +assign ibuf_fetch_five = ibuf_five_avalbe; +assign ibuf_fetch_four = ibuf_four_avalbe + & ~(ipack_ibuf_inst_full + & ~ifetch_ibuf_idle); +assign ibuf_fetch_three = ibuf_three_avalbe + & (ifetch_ibuf_idle + | ifetch_xx_not_busy & + ~ipack_ibuf_inst_vld_raw); +assign ibuf_fetch_two = ibuf_two_avalbe + & (ifetch_ibuf_idle + & ~ipack_ibuf_inst_full + | ifetch_xx_not_busy & + ipack_ibuf_inst_empty); +assign ibuf_inst_fetch = ibuf_fetch_empty + | ibuf_fetch_five + | ibuf_fetch_four + | ibuf_fetch_three + | ibuf_fetch_two; +//assign ibuf_inst_fetch = 1'b1; + +//------------------------------------------------ +// b. The Valid Instruction +//------------------------------------------------ +assign pop0_inst_32 = pop0_inst[1:0] == 2'b11; +assign ibuf_inst32 = pop0_vld & pop1_vld & pop0_inst_32; + +// &Force("nonport", "pop1_pred_taken"); @491 +// &Force("nonport", "pop1_halt_info"); @492 + +//------------------------------------------------ +// 6. I-Buffer Pop Entry +//------------------------------------------------ +// a. entry instance +//------------------------------------------------ +// &ConnRule(s/ibuf_entry/pop_entry0/); @499 +// &Instance("pa_ifu_ibuf_pop_entry","x_pa_ifu_ibuf_pop_entry0"); @500 +pa_ifu_ibuf_pop_entry x_pa_ifu_ibuf_pop_entry0 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_entry_acc_err (pop_entry0_acc_err ), + .ibuf_entry_create_acc_err (pop_entry0_create_acc_err ), + .ibuf_entry_create_data_en (pop_entry0_create_data_en ), + .ibuf_entry_create_en (pop_entry0_create_en ), + .ibuf_entry_create_halt_info (pop_entry0_create_halt_info ), + .ibuf_entry_create_inst (pop_entry0_create_inst ), + .ibuf_entry_create_pred_taken (pop_entry0_create_pred_taken), + .ibuf_entry_halt_info (pop_entry0_halt_info ), + .ibuf_entry_inst (pop_entry0_inst ), + .ibuf_entry_pred_taken (pop_entry0_pred_taken ), + .ibuf_entry_retire_en (pop_entry0_retire_en ), + .ibuf_entry_vld (pop_entry0_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// &ConnRule(s/ibuf_entry/pop_entry1/); @502 +// &Instance("pa_ifu_ibuf_pop_entry","x_pa_ifu_ibuf_pop_entry1"); @503 +pa_ifu_ibuf_pop_entry x_pa_ifu_ibuf_pop_entry1 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_cpuclk (ibuf_cpuclk ), + .ibuf_entry_acc_err (pop_entry1_acc_err ), + .ibuf_entry_create_acc_err (pop_entry1_create_acc_err ), + .ibuf_entry_create_data_en (pop_entry1_create_data_en ), + .ibuf_entry_create_en (pop_entry1_create_en ), + .ibuf_entry_create_halt_info (pop_entry1_create_halt_info ), + .ibuf_entry_create_inst (pop_entry1_create_inst ), + .ibuf_entry_create_pred_taken (pop_entry1_create_pred_taken), + .ibuf_entry_halt_info (pop_entry1_halt_info ), + .ibuf_entry_inst (pop_entry1_inst ), + .ibuf_entry_pred_taken (pop_entry1_pred_taken ), + .ibuf_entry_retire_en (pop_entry1_retire_en ), + .ibuf_entry_vld (pop_entry1_vld ), + .ibuf_flush_en (ibuf_flush_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +//------------------------------------------------ +// b. entry create +//------------------------------------------------ +// create entry 0 when: +// 1. ibuf retire0 vld +// 2. ipack bypass vld and id stall +// 3. ipack bypass vld and pop entry inst vld +// 4. ipack bypass vld and ipack two inst vld +assign pop_entry0_create_en = ibuf_retire0_en + | ipack_bypass_vld & ~pop_entry_vld & idu_ifu_id_stall + | ipack_bypass_vld & ~pop_entry_vld & ipack_ibuf_inst_two + | ipack_bypass_vld & pop_entry_vld & ~idu_ifu_id_stall; +assign pop_entry0_create_data_en = pop0_vld | ipack_bypass_vld; + +// create entry 1 when: +// 1. ibuf retire1 vld +// 2. ipack bypass vld and id stall and ipack inst 32 +// 3. ipack bypass vld and pop entry vld and ipack inst 32 +assign pop_entry1_create_en = ibuf_retire1_en + | ipack_bypass_vld & ipack_inst_32 & ~pop_entry_vld & idu_ifu_id_stall + | ipack_bypass_vld & ipack_inst_32 & pop_entry_vld & ~idu_ifu_id_stall; +assign pop_entry1_create_data_en = ibuf_inst32 | ipack_bypass_vld & ipack_inst_32; + +// create content +// inst code +assign pop_entry0_create_inst[15:0] = pop0_vld ? pop0_inst[15:0] + : idu_ifu_id_stall | pop_entry_vld + ? ipack_ibuf_inst[15:0] + : ipack_inst_32 ? ipack_ibuf_inst[47:32] + : ipack_ibuf_inst[31:16]; +assign pop_entry1_create_inst[15:0] = pop1_vld ? pop1_inst[15:0] : ipack_ibuf_inst[31:16]; + +// pred taken +assign pop_entry0_create_pred_taken[1:0] = pop0_vld ? pop0_pred_taken[1:0] + : idu_ifu_id_stall | pop_entry_vld ? id_pred_ibuf_br_taken0[1:0] + : id_pred_ibuf_br_taken1[1:0]; +assign pop_entry1_create_pred_taken[1:0] = 2'b0; + +// inst bkpt +assign pop_entry0_create_halt_info[`TDT_HINFO_WIDTH-1:0] = pop0_vld ? pop0_halt_info[`TDT_HINFO_WIDTH-1:0] + : idu_ifu_id_stall | pop_entry_vld ? id_pred_ibuf_halt_info0[`TDT_HINFO_WIDTH-1:0] + : id_pred_ibuf_halt_info1[`TDT_HINFO_WIDTH-1:0]; +assign pop_entry1_create_halt_info[`TDT_HINFO_WIDTH-1:0] = {`TDT_HINFO_WIDTH{1'b0}}; + +// acc err +assign pop_entry0_create_acc_err = pop0_vld ? pop0_acc_err + : idu_ifu_id_stall | pop_entry_vld ? ipack_ibuf_acc_err[0] + : ipack_ibuf_acc_err[1]; +assign pop_entry1_create_acc_err = pop1_vld ? pop1_acc_err : ipack_ibuf_acc_err[1]; + +// page fault + +assign ipack_expt_high = ipack_inst_32 & ~ipack_ibuf_acc_err[0] & ipack_ibuf_acc_err[1]; + +//------------------------------------------------ +// c. entry retire +//------------------------------------------------ +assign pop_entry0_retire_en = ctrl_ibuf_pop_en; +assign pop_entry1_retire_en = ctrl_ibuf_pop_en; + +//------------------------------------------------ +// d. entry output +//------------------------------------------------ +assign pop_entry_vld = pop_entry0_vld; +assign pop_entry_inst[31:0] = {pop_entry1_inst[15:0], pop_entry0_inst[15:0]}; +assign pop_entry_pred_taken[1:0] = pop_entry0_pred_taken[1:0] | pop_entry1_pred_taken[1:0]; +assign pop_entry_halt_info[`TDT_HINFO_WIDTH-1:0] = pop_entry0_halt_info[`TDT_HINFO_WIDTH-1:0] | pop_entry1_halt_info[`TDT_HINFO_WIDTH-1:0]; +assign pop_entry_acc_err = pop_entry0_acc_err | pop_entry1_vld & pop_entry1_acc_err; +assign pop_entry_expt_high = ~pop_entry0_acc_err & pop_entry1_vld & pop_entry1_acc_err; +//========================================================== +// Rename for Output +//========================================================== + +// Output to ctrl +assign ibuf_ctrl_inst_fetch = ibuf_inst_fetch & ~ibuf_stall; + +// Output to ipack +assign ibuf_ipack_stall = ibuf_stall; + +// Output to ipack +assign ibuf_pred_stall = ibuf_stall; +assign ibuf_id_pred_hungry = ibuf_empty | ibuf_five_avalbe | ibuf_four_avalbe; + +// Output to top +assign ibuf_top_vld_num[2:0] = ibuf_vld_num[2:0]; +assign ibuf_top_id_stall = idu_ifu_id_stall; +//assign ibuf_top_pop_entry_vld = pop_entry_vld; + +// Output to IDU +assign ifu_idu_id_inst_vld = pop_entry_vld | ipack_ibuf_inst_vld & dtu_ifu_halt_info_vld; +assign ifu_idu_id_inst[31:0] = pop_entry_vld ? pop_entry_inst[31:0] + : ipack_ibuf_inst[31:0]; +assign ifu_idu_id_pred_taken[1:0] = pop_entry_vld ? pop_entry_pred_taken[1:0] + : id_pred_ibuf_br_taken0[1:0]; +assign ifu_idu_id_halt_info[`TDT_HINFO_WIDTH-1:0] = pop_entry_vld ? pop_entry_halt_info[`TDT_HINFO_WIDTH-1:0] + : id_pred_ibuf_halt_info0[`TDT_HINFO_WIDTH-1:0]; +assign ifu_idu_id_expt_vld = pop_entry_vld ? pop_entry_acc_err + : |ipack_ibuf_acc_err[1:0]; +assign ifu_idu_id_expt_high = pop_entry_vld ? pop_entry_expt_high + : ipack_expt_high; +// &Force("outout", "ifu_idu_id_inst"); @612 +// &Force("outout", "ifu_idu_id_inst_vld"); @613 + +// &ModuleEnd; @640 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..06d11d86243b1665385077af7182759ef93f292d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_entry.v @@ -0,0 +1,279 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ibuf_entry( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ibuf_cpuclk, + ibuf_create0_acc_err, + ibuf_create0_halt_info, + ibuf_create0_inst, + ibuf_create0_pred_taken, + ibuf_create1_acc_err, + ibuf_create1_halt_info, + ibuf_create1_inst, + ibuf_create1_pred_taken, + ibuf_create2_acc_err, + ibuf_create2_halt_info, + ibuf_create2_inst, + ibuf_create2_pred_taken, + ibuf_entry_acc_err, + ibuf_entry_create0_data_en, + ibuf_entry_create0_en, + ibuf_entry_create1_data_en, + ibuf_entry_create1_en, + ibuf_entry_create2_data_en, + ibuf_entry_create2_en, + ibuf_entry_halt_info, + ibuf_entry_inst, + ibuf_entry_pred_taken, + ibuf_entry_retire0_en, + ibuf_entry_retire1_en, + ibuf_entry_vld, + ibuf_flush_en, + pad_yy_icg_scan_en, + vec_ibuf_warm_up +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ibuf_cpuclk; +input ibuf_create0_acc_err; +input [14:0] ibuf_create0_halt_info; +input [15:0] ibuf_create0_inst; +input [1 :0] ibuf_create0_pred_taken; +input ibuf_create1_acc_err; +input [14:0] ibuf_create1_halt_info; +input [15:0] ibuf_create1_inst; +input [1 :0] ibuf_create1_pred_taken; +input ibuf_create2_acc_err; +input [14:0] ibuf_create2_halt_info; +input [15:0] ibuf_create2_inst; +input [1 :0] ibuf_create2_pred_taken; +input ibuf_entry_create0_data_en; +input ibuf_entry_create0_en; +input ibuf_entry_create1_data_en; +input ibuf_entry_create1_en; +input ibuf_entry_create2_data_en; +input ibuf_entry_create2_en; +input ibuf_entry_retire0_en; +input ibuf_entry_retire1_en; +input ibuf_flush_en; +input pad_yy_icg_scan_en; +input vec_ibuf_warm_up; +output ibuf_entry_acc_err; +output [14:0] ibuf_entry_halt_info; +output [15:0] ibuf_entry_inst; +output [1 :0] ibuf_entry_pred_taken; +output ibuf_entry_vld; + +// &Regs; @25 +reg entry_acc_err; +reg [14:0] entry_halt_info; +reg [15:0] entry_inst; +reg [1 :0] entry_pred_taken; +reg entry_vld; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry_acc_err_upd; +wire entry_cpuclk; +wire entry_create; +wire entry_data_create; +wire [14:0] entry_halt_info_upd; +wire entry_icg_create; +wire entry_icg_en; +wire [15:0] entry_inst_upd; +wire [1 :0] entry_pred_taken_upd; +wire entry_retire; +wire forever_cpuclk; +wire ibuf_cpuclk; +wire ibuf_create0_acc_err; +wire [14:0] ibuf_create0_halt_info; +wire [15:0] ibuf_create0_inst; +wire [1 :0] ibuf_create0_pred_taken; +wire ibuf_create1_acc_err; +wire [14:0] ibuf_create1_halt_info; +wire [15:0] ibuf_create1_inst; +wire [1 :0] ibuf_create1_pred_taken; +wire ibuf_create2_acc_err; +wire [14:0] ibuf_create2_halt_info; +wire [15:0] ibuf_create2_inst; +wire [1 :0] ibuf_create2_pred_taken; +wire ibuf_entry_acc_err; +wire ibuf_entry_create0_data_en; +wire ibuf_entry_create0_en; +wire ibuf_entry_create1_data_en; +wire ibuf_entry_create1_en; +wire ibuf_entry_create2_data_en; +wire ibuf_entry_create2_en; +wire [14:0] ibuf_entry_halt_info; +wire [15:0] ibuf_entry_inst; +wire [1 :0] ibuf_entry_pred_taken; +wire ibuf_entry_retire0_en; +wire ibuf_entry_retire1_en; +wire ibuf_entry_vld; +wire ibuf_flush_en; +wire pad_yy_icg_scan_en; +wire vec_ibuf_warm_up; + + +//========================================================== +// Instruction Buffer Entry Module +// 1. Instance ICG cell +// 2. Entry Content +//========================================================== + +//------------------------------------------------ +// 1. Instace ICG cell +//------------------------------------------------ +assign entry_icg_create = ibuf_entry_create0_data_en + | ibuf_entry_create1_data_en + | ibuf_entry_create2_data_en; +assign entry_icg_en = entry_icg_create | vec_ibuf_warm_up; +// &Instance("gated_clk_cell", "x_ibuf_data_icg_cell"); @41 +gated_clk_cell x_ibuf_data_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (entry_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (entry_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @42 +// .external_en (1'b0), @43 +// .global_en (cp0_yy_clk_en), @44 +// .module_en (cp0_ifu_icg_en), @45 +// .local_en (entry_icg_en), @46 +// .clk_out (entry_cpuclk)); @47 + +//------------------------------------------------ +// 2. Entry Content +// a. Entry Create and Retire Signal +// b. Entry Valid Signal +// c. Entry Instruction +//------------------------------------------------ +// a. Entry Create and Retire Signal +assign entry_create = ibuf_entry_create0_en | ibuf_entry_create1_en + | ibuf_entry_create2_en; +assign entry_data_create = ibuf_entry_create0_en + | ibuf_entry_create1_en + | ibuf_entry_create2_en; +assign entry_retire = ibuf_entry_retire0_en | ibuf_entry_retire1_en; + +// b. Entry Valid Signal +always @(posedge ibuf_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_vld <= 1'b0; + else if(ibuf_flush_en) + entry_vld <= 1'b0; + else if(entry_create) + entry_vld <= 1'b1; + else if(entry_retire) + entry_vld <= 1'b0; + else + entry_vld <= entry_vld; +end + +// c. Entry Instruction +assign entry_inst_upd[15:0] = + {16{ibuf_entry_create0_data_en}} & ibuf_create0_inst[15:0] + | {16{ibuf_entry_create1_data_en}} & ibuf_create1_inst[15:0] + | {16{ibuf_entry_create2_data_en}} & ibuf_create2_inst[15:0]; + +always @(posedge entry_cpuclk) +begin + if(entry_data_create | vec_ibuf_warm_up) + entry_inst[15:0] <= entry_inst_upd[15:0]; + else + entry_inst[15:0] <= entry_inst[15:0]; +end + +//========================================================== +// Instruction Predict Taken +//========================================================== +assign entry_pred_taken_upd[1:0] = + {2{ibuf_entry_create0_data_en}} & ibuf_create0_pred_taken[1:0] + | {2{ibuf_entry_create1_data_en}} & ibuf_create1_pred_taken[1:0] + | {2{ibuf_entry_create2_data_en}} & ibuf_create2_pred_taken[1:0]; + +assign entry_halt_info_upd[`TDT_HINFO_WIDTH-1:0] = + {`TDT_HINFO_WIDTH{ibuf_entry_create0_data_en}} & ibuf_create0_halt_info[`TDT_HINFO_WIDTH-1:0] + | {`TDT_HINFO_WIDTH{ibuf_entry_create1_data_en}} & ibuf_create1_halt_info[`TDT_HINFO_WIDTH-1:0] + | {`TDT_HINFO_WIDTH{ibuf_entry_create2_data_en}} & ibuf_create2_halt_info[`TDT_HINFO_WIDTH-1:0]; + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_pred_taken[1:0] <= 2'b0; + else if(entry_data_create) + entry_pred_taken[1:0] <= entry_pred_taken_upd[1:0]; + else + entry_pred_taken[1:0] <= entry_pred_taken[1:0]; +end + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + else if(entry_data_create) + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= entry_halt_info_upd[`TDT_HINFO_WIDTH-1:0]; + else + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= entry_halt_info[`TDT_HINFO_WIDTH-1:0]; +end + +//========================================================== +// Instruction Bus Access Error +//========================================================== +assign entry_acc_err_upd = ibuf_entry_create0_data_en & ibuf_create0_acc_err + | ibuf_entry_create1_data_en & ibuf_create1_acc_err + | ibuf_entry_create2_data_en & ibuf_create2_acc_err; + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_acc_err <= 1'b0; + else if(entry_data_create) + entry_acc_err <= entry_acc_err_upd; + else + entry_acc_err <= entry_acc_err; +end + +//========================================================== +// Rename for Output +//========================================================== + +assign ibuf_entry_vld = entry_vld; +assign ibuf_entry_inst[15:0] = entry_inst[15:0]; +assign ibuf_entry_pred_taken[1:0] = entry_pred_taken[1:0]; +assign ibuf_entry_halt_info[`TDT_HINFO_WIDTH-1:0] = entry_halt_info[`TDT_HINFO_WIDTH-1:0]; +assign ibuf_entry_acc_err = entry_acc_err; + + +// &ModuleEnd; @165 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_pop_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_pop_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..aefd4e86593cc5a5cc5e69ff676874b902fd577e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ibuf_pop_entry.v @@ -0,0 +1,220 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ibuf_pop_entry( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ibuf_cpuclk, + ibuf_entry_acc_err, + ibuf_entry_create_acc_err, + ibuf_entry_create_data_en, + ibuf_entry_create_en, + ibuf_entry_create_halt_info, + ibuf_entry_create_inst, + ibuf_entry_create_pred_taken, + ibuf_entry_halt_info, + ibuf_entry_inst, + ibuf_entry_pred_taken, + ibuf_entry_retire_en, + ibuf_entry_vld, + ibuf_flush_en, + pad_yy_icg_scan_en, + vec_ibuf_warm_up +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ibuf_cpuclk; +input ibuf_entry_create_acc_err; +input ibuf_entry_create_data_en; +input ibuf_entry_create_en; +input [14:0] ibuf_entry_create_halt_info; +input [15:0] ibuf_entry_create_inst; +input [1 :0] ibuf_entry_create_pred_taken; +input ibuf_entry_retire_en; +input ibuf_flush_en; +input pad_yy_icg_scan_en; +input vec_ibuf_warm_up; +output ibuf_entry_acc_err; +output [14:0] ibuf_entry_halt_info; +output [15:0] ibuf_entry_inst; +output [1 :0] ibuf_entry_pred_taken; +output ibuf_entry_vld; + +// &Regs; @25 +reg entry_acc_err; +reg [14:0] entry_halt_info; +reg [15:0] entry_inst; +reg [1 :0] entry_pred_taken; +reg entry_vld; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry_acc_err_upd; +wire entry_cpuclk; +wire entry_create; +wire entry_data_create; +wire [14:0] entry_halt_info_upd; +wire entry_icg_en; +wire [15:0] entry_inst_upd; +wire [1 :0] entry_pred_taken_upd; +wire entry_retire; +wire forever_cpuclk; +wire ibuf_cpuclk; +wire ibuf_entry_acc_err; +wire ibuf_entry_create_acc_err; +wire ibuf_entry_create_data_en; +wire ibuf_entry_create_en; +wire [14:0] ibuf_entry_create_halt_info; +wire [15:0] ibuf_entry_create_inst; +wire [1 :0] ibuf_entry_create_pred_taken; +wire [14:0] ibuf_entry_halt_info; +wire [15:0] ibuf_entry_inst; +wire [1 :0] ibuf_entry_pred_taken; +wire ibuf_entry_retire_en; +wire ibuf_entry_vld; +wire ibuf_flush_en; +wire pad_yy_icg_scan_en; +wire vec_ibuf_warm_up; + + +//========================================================== +// Instruction Buffer Entry Module +// 1. Instance ICG cell +// 2. Entry Content +//========================================================== + +//------------------------------------------------ +// 1. Instace ICG cell +//------------------------------------------------ +assign entry_icg_en = ibuf_entry_create_data_en | vec_ibuf_warm_up; +// &Instance("gated_clk_cell", "x_ibuf_data_icg_cell"); @38 +gated_clk_cell x_ibuf_data_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (entry_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (entry_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @39 +// .external_en (1'b0), @40 +// .global_en (cp0_yy_clk_en), @41 +// .module_en (cp0_ifu_icg_en), @42 +// .local_en (entry_icg_en), @43 +// .clk_out (entry_cpuclk)); @44 + +//------------------------------------------------ +// 2. Entry Content +// a. Entry Create and Retire Signal +// b. Entry Valid Signal +// c. Entry Instruction +//------------------------------------------------ +// a. Entry Create and Retire Signal +assign entry_create = ibuf_entry_create_en; +assign entry_data_create = ibuf_entry_create_en; +assign entry_retire = ibuf_entry_retire_en; + +// b. Entry Valid Signal +always @(posedge ibuf_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_vld <= 1'b0; + else if(ibuf_flush_en) + entry_vld <= 1'b0; + else if(entry_create) + entry_vld <= 1'b1; + else if(entry_retire) + entry_vld <= 1'b0; + else + entry_vld <= entry_vld; +end + +// c. Entry Instruction +assign entry_inst_upd[15:0] = ibuf_entry_create_inst[15:0]; + +always @(posedge entry_cpuclk) +begin + if(entry_data_create | vec_ibuf_warm_up) + entry_inst[15:0] <= entry_inst_upd[15:0]; + else + entry_inst[15:0] <= entry_inst[15:0]; +end + +//========================================================== +// Instruction Predict Taken +//========================================================== +assign entry_pred_taken_upd[1:0] = ibuf_entry_create_pred_taken[1:0]; + +assign entry_halt_info_upd[`TDT_HINFO_WIDTH-1:0] = ibuf_entry_create_halt_info[`TDT_HINFO_WIDTH-1:0]; + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_pred_taken[1:0] <= 2'b0; + else if(entry_data_create) + entry_pred_taken[1:0] <= entry_pred_taken_upd[1:0]; + else + entry_pred_taken[1:0] <= entry_pred_taken[1:0]; +end + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + else if(entry_data_create) + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= entry_halt_info_upd[`TDT_HINFO_WIDTH-1:0]; + else + entry_halt_info[`TDT_HINFO_WIDTH-1:0] <= entry_halt_info[`TDT_HINFO_WIDTH-1:0]; +end + +//========================================================== +// Instruction Bus Access Error +//========================================================== +assign entry_acc_err_upd = ibuf_entry_create_acc_err; + +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_acc_err <= 1'b0; + else if(entry_data_create) + entry_acc_err <= entry_acc_err_upd; + else + entry_acc_err <= entry_acc_err; +end + +//========================================================== +// Rename for Output +//========================================================== +assign ibuf_entry_vld = entry_vld; +assign ibuf_entry_inst[15:0] = entry_inst[15:0]; +assign ibuf_entry_pred_taken[1:0] = entry_pred_taken[1:0]; +assign ibuf_entry_halt_info[`TDT_HINFO_WIDTH-1:0] = entry_halt_info[`TDT_HINFO_WIDTH-1:0]; +assign ibuf_entry_acc_err = entry_acc_err; + +// &ModuleEnd; @146 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache.v new file mode 100644 index 0000000000000000000000000000000000000000..773b418cdeef60a3718441ac84af817e7f825873 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache.v @@ -0,0 +1,1124 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_icache( + bmu_ifu_acc_err, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_ifetch_req_abort, + ctrl_ifetch_req_vld, + forever_cpuclk, + ibus_icache_cmplt, + ibus_icache_data, + ibus_icache_error, + ibus_icache_grant, + ibus_icache_not_busy, + ibus_icache_uc_cmplt, + ibus_icache_unalign, + ibus_trans_abort, + icache_ibus_acc_deny, + icache_ibus_addr, + icache_ibus_burst, + icache_ibus_data_req, + icache_ibus_prot, + icache_ibus_req, + icache_ibus_seq, + icache_ifetch_addr, + icache_ifetch_error, + icache_ifetch_grant, + icache_ifetch_idle, + icache_ifetch_inst, + icache_ifetch_inst_vld, + icache_ifetch_inst_vld_gate, + icache_ifetch_mach_mode, + icache_ifetch_not_busy, + icache_ifetch_rd_addr, + icache_ifetch_uc_sel, + icache_ifetch_unalign, + icache_ifetch_vec_data_cmplt, + icache_top_abort, + icache_top_rd_vld, + icache_top_ref_st, + icache_top_uc_st, + ifetch_outstanding, + ifetch_req_addr, + ifetch_req_ca, + ifetch_req_prot, + ifu_cp0_icache_inv_done, + ifu_hpcp_icache_access, + ifu_hpcp_icache_miss, + pad_yy_icg_scan_en, + pcgen_ifetch_chgflw_vld, + pcgen_ifetch_seq_addr, + pmp_ifu_acc_deny, + vec_ifetch_data_fetch +); + +// &Ports; @24 +input bmu_ifu_acc_err; +input cp0_ifu_icache_en; +input [31:0] cp0_ifu_icache_inv_addr; +input cp0_ifu_icache_inv_req; +input cp0_ifu_icache_inv_type; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_ifetch_req_abort; +input ctrl_ifetch_req_vld; +input forever_cpuclk; +input ibus_icache_cmplt; +input [31:0] ibus_icache_data; +input ibus_icache_error; +input ibus_icache_grant; +input ibus_icache_not_busy; +input ibus_icache_uc_cmplt; +input ibus_icache_unalign; +input ibus_trans_abort; +input ifetch_outstanding; +input [31:0] ifetch_req_addr; +input ifetch_req_ca; +input [3 :0] ifetch_req_prot; +input pad_yy_icg_scan_en; +input pcgen_ifetch_chgflw_vld; +input [31:0] pcgen_ifetch_seq_addr; +input pmp_ifu_acc_deny; +input vec_ifetch_data_fetch; +output icache_ibus_acc_deny; +output [31:0] icache_ibus_addr; +output [2 :0] icache_ibus_burst; +output icache_ibus_data_req; +output [3 :0] icache_ibus_prot; +output icache_ibus_req; +output icache_ibus_seq; +output [31:0] icache_ifetch_addr; +output icache_ifetch_error; +output icache_ifetch_grant; +output icache_ifetch_idle; +output [31:0] icache_ifetch_inst; +output icache_ifetch_inst_vld; +output icache_ifetch_inst_vld_gate; +output icache_ifetch_mach_mode; +output icache_ifetch_not_busy; +output [31:0] icache_ifetch_rd_addr; +output icache_ifetch_uc_sel; +output icache_ifetch_unalign; +output icache_ifetch_vec_data_cmplt; +output icache_top_abort; +output icache_top_rd_vld; +output [1 :0] icache_top_ref_st; +output icache_top_uc_st; +output ifu_cp0_icache_inv_done; +output ifu_hpcp_icache_access; +output ifu_hpcp_icache_miss; + +// &Regs; @25 +reg [26:0] buf_hit_tag; +reg buf_hit_way; +reg direct_sel; +reg [31:0] icache_addr_ff; +reg icache_ca_ff; +reg icache_deny; +reg icache_en; +reg icache_en_f; +reg [31:0] icache_rd_addr; +reg [3 :0] icache_rd_prot; +reg icache_rd_vld; +reg [31:0] icache_refill_addr; +reg icache_refill_fifo; +reg [3 :0] icache_refill_prot; +reg icache_vec_data; +reg [9 :0] inv_cnt; +reg [1 :0] inv_cur_st; +reg [1 :0] inv_nxt_st; +reg [1 :0] ipa_way_sel; +reg [2 :0] ref_cnt; +reg [1 :0] ref_cur_st; +reg [1 :0] ref_nxt_st; +reg ref_vld; +reg [31:0] refill_data; +reg refill_data_abort; +reg [2 :0] req_cnt; +reg tag_hit_vld; +reg uc_cur_st; +reg uc_nxt_st; + +// &Wires; @26 +wire addr_equal; +wire bmu_ifu_acc_err; +wire buf_clr_en; +wire buf_hit_upd; +wire buf_rfl_upd; +wire buf_upd_en; +wire cen_mask_vld; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_ifetch_req_abort; +wire ctrl_ifetch_req_vld; +wire forever_cpuclk; +wire hit_clk; +wire [26:0] hit_tag; +wire hit_way; +wire ibus_icache_cmplt; +wire [31:0] ibus_icache_data; +wire ibus_icache_error; +wire ibus_icache_grant; +wire ibus_icache_not_busy; +wire ibus_icache_uc_cmplt; +wire ibus_icache_unalign; +wire ibus_trans_abort; +wire icache_addr_clk; +wire icache_addr_icg_en; +wire icache_bypass_vld; +wire [21:0] icache_cmp_tag; +wire [21:0] icache_cmp_tag_fin; +wire icache_cmplt; +wire [31:0] icache_data0_dout; +wire [31:0] icache_data1_dout; +wire [1 :0] icache_data_cen; +wire [31:0] icache_data_din; +wire [12:0] icache_data_idx; +wire icache_data_req; +wire [1 :0] icache_data_wen; +wire icache_hit; +wire icache_hit0; +wire icache_hit1; +wire [31:0] icache_hit_inst; +wire icache_hit_vld; +wire icache_ibus_acc_deny; +wire [31:0] icache_ibus_addr; +wire [2 :0] icache_ibus_burst; +wire icache_ibus_data_req; +wire [3 :0] icache_ibus_prot; +wire icache_ibus_req; +wire icache_ibus_seq; +wire [31:0] icache_ifetch_addr; +wire icache_ifetch_error; +wire icache_ifetch_grant; +wire icache_ifetch_idle; +wire [31:0] icache_ifetch_inst; +wire icache_ifetch_inst_vld; +wire icache_ifetch_inst_vld_gate; +wire icache_ifetch_mach_mode; +wire icache_ifetch_not_busy; +wire [31:0] icache_ifetch_rd_addr; +wire icache_ifetch_uc_sel; +wire icache_ifetch_unalign; +wire icache_ifetch_vec_data_cmplt; +wire icache_inv_clk; +wire [46:0] icache_inv_din; +wire icache_inv_done; +wire icache_inv_icg_en; +wire [9 :0] icache_inv_idx; +wire icache_inv_rd; +wire icache_inv_req; +wire [2 :0] icache_inv_wen; +wire icache_inv_wt; +wire [31:0] icache_miss_addr; +wire [3 :0] icache_miss_prot; +wire icache_miss_req; +wire icache_rd_clk; +wire [12:0] icache_rd_data_idx; +wire icache_rd_icg_en; +wire icache_rd_req; +wire icache_rd_req_data; +wire [9 :0] icache_rd_tag_idx; +wire icache_refdp_clk; +wire icache_refdp_icg_en; +wire icache_reffsm_clk; +wire icache_reffsm_icg_en; +wire icache_refill_ca; +wire icache_req; +wire icache_req_vld; +wire icache_tag_cen; +wire [46:0] icache_tag_din; +wire [46:0] icache_tag_dout; +wire icache_tag_fifo; +wire [9 :0] icache_tag_idx; +wire [21:0] icache_tag_way0_dout; +wire icache_tag_way0_vld; +wire [21:0] icache_tag_way1_dout; +wire icache_tag_way1_vld; +wire [2 :0] icache_tag_wen; +wire icache_top_abort; +wire icache_top_rd_vld; +wire [1 :0] icache_top_ref_st; +wire icache_top_uc_st; +wire icache_uc_data_req; +wire icache_uc_req; +wire icache_uc_sel; +wire icache_way0_hit; +wire icache_way1_hit; +wire [12:0] icache_wr_data_idx; +wire icache_wr_data_req; +wire ifetch_outstanding; +wire [31:0] ifetch_req_addr; +wire ifetch_req_ca; +wire [3 :0] ifetch_req_prot; +wire ifu_cp0_icache_inv_done; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire inv_cnt_en; +wire [9 :0] inv_cnt_inc; +wire inv_fsm_idle; +wire inv_fsm_write; +wire inv_tag_wen; +wire inv_type_pa; +wire [1 :0] inv_way_sel; +wire pad_yy_icg_scan_en; +wire pcgen_ifetch_chgflw_vld; +wire [31:0] pcgen_ifetch_seq_addr; +wire pmp_ifu_acc_deny; +wire ref_cnt_done; +wire [2 :0] ref_cnt_inc; +wire ref_fsm_idle; +wire ref_fsm_ref; +wire ref_fsm_req; +wire ref_fsm_wfc; +wire ref_rdy; +wire [31:0] refill_addr; +wire [31:0] refill_icache_addr; +wire [31:0] refill_icache_data; +wire refill_icache_done; +wire refill_icache_fifo; +wire refill_icache_init; +wire refill_icache_req; +wire [46:0] refill_inv_tag_din; +wire [9 :0] refill_inv_tag_idx; +wire refill_inv_tag_req; +wire [2 :0] refill_inv_tag_wen; +wire [46:0] refill_tag_din; +wire [2 :0] refill_tag_wen; +wire refill_tag_wr; +wire [31:0] req_addr; +wire req_cnt_done; +wire tag_hit_clk_en; +wire uc_fsm_idle; +wire uc_fsm_wfc; +wire vec_ifetch_data_fetch; + + +//========================================================== +// Instruction Cache Module +// 1. Instance ICG cell +// 2. I-Cache Request Generation +// 3. Instance I-Cache Array +// 4. I-Cache Hit Judge and Data Select +// 5. I-Cache Refill Control +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG cell +//------------------------------------------------ +assign icache_rd_icg_en = icache_rd_req & ref_rdy + | direct_sel; +// &Instance("gated_clk_cell", "x_ifu_icache_rd_icg_cell"); @42 +gated_clk_cell x_ifu_icache_rd_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_rd_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_rd_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @43 +// .external_en (1'b0), @44 +// .global_en (cp0_yy_clk_en), @45 +// .module_en (cp0_ifu_icg_en), @46 +// .local_en (icache_rd_icg_en), @47 +// .clk_out (icache_rd_clk) @48 +// ); @49 + +assign icache_refdp_icg_en = icache_miss_req & ref_fsm_idle; +// &Instance("gated_clk_cell", "x_ifu_icache_refdp_icg_cell"); @52 +gated_clk_cell x_ifu_icache_refdp_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_refdp_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_refdp_icg_en), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @53 +// .external_en (1'b0), @54 +// .global_en (cp0_yy_clk_en), @55 +// .module_en (cp0_ifu_icg_en), @56 +// .local_en (icache_refdp_icg_en), @57 +// .clk_out (icache_refdp_clk) @58 +// ); @59 + +assign icache_reffsm_icg_en = icache_miss_req | ~ref_fsm_idle + | icache_uc_req | ~uc_fsm_idle; +// &Instance("gated_clk_cell", "x_ifu_icache_reffsm_icg_cell"); @63 +gated_clk_cell x_ifu_icache_reffsm_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_reffsm_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_reffsm_icg_en), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @64 +// .external_en (1'b0), @65 +// .global_en (cp0_yy_clk_en), @66 +// .module_en (cp0_ifu_icg_en), @67 +// .local_en (icache_reffsm_icg_en), @68 +// .clk_out (icache_reffsm_clk) @69 +// ); @70 + +assign icache_addr_icg_en = icache_rd_req_data + | icache_uc_data_req; +// &Instance("gated_clk_cell", "x_ifu_icache_addr_icg_cell"); @74 +gated_clk_cell x_ifu_icache_addr_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_addr_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_addr_icg_en), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @75 +// .external_en (1'b0), @76 +// .global_en (cp0_yy_clk_en), @77 +// .module_en (cp0_ifu_icg_en), @78 +// .local_en (icache_addr_icg_en), @79 +// .clk_out (icache_addr_clk) @80 +// ); @81 + +assign icache_inv_icg_en = ~inv_fsm_idle; +// &Instance("gated_clk_cell", "x_ifu_icache_inv_icg_cell"); @84 +gated_clk_cell x_ifu_icache_inv_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_inv_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_inv_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @85 +// .external_en (1'b0), @86 +// .global_en (cp0_yy_clk_en), @87 +// .module_en (cp0_ifu_icg_en), @88 +// .local_en (icache_inv_icg_en), @89 +// .clk_out (icache_inv_clk) @90 +// ); @91 + +//------------------------------------------------ +// 2. I-Cache Request Generation +// a. I-Cache Read Request +// b. I-Cache Write Request +// c. I-Cache Tag hit buffer +// d. I-Cache Request +//------------------------------------------------ + +// a. I-Cache Read Request +// Generate Chip Enable and Index + +// Read Chip Enable +// request valid when i-cache enable and sysmap cacheable +assign icache_req_vld = (ctrl_ifetch_req_vld | vec_ifetch_data_fetch) + & inv_fsm_idle & ref_fsm_idle & uc_fsm_idle; +assign icache_rd_req = icache_req_vld & ifetch_req_ca & cp0_ifu_icache_en; +assign icache_rd_req_data = icache_req_vld & icache_ca_ff; +assign icache_uc_req = (ctrl_ifetch_req_vld | vec_ifetch_data_fetch) + & inv_fsm_idle & ref_fsm_idle & ~icache_rd_vld + & ~(ifetch_req_ca & cp0_ifu_icache_en); +assign icache_uc_data_req = (ctrl_ifetch_req_vld | vec_ifetch_data_fetch) + & inv_fsm_idle & ref_fsm_idle & ~icache_rd_vld; +assign icache_uc_sel = inv_fsm_idle & ref_fsm_idle & ~icache_rd_vld + & ~(ifetch_req_ca & cp0_ifu_icache_en) + | uc_fsm_wfc; + +// Read Index +// calculate icache read index depending on cache capcity +// cache line size: 32-Bytes +// 2KB: tag index: addr[10:5], data index: addr[10:2] +// 4KB: tag index: addr[11:5], data index: addr[11:2] +// ... +// 64KB: tag index: addr[15:5], data index: addr[15:2] +assign icache_rd_tag_idx[9:0] = ifetch_req_addr[14:5]; +assign icache_rd_data_idx[12:0] = ifetch_req_addr[14:2]; + +// b. I-Cache Write Request +// Generate Chip Enable, Index + +// Write Chip Enable +// request valid when invalid request or refill request +assign refill_tag_wr = refill_icache_req & + (refill_icache_done | refill_icache_init); +assign refill_tag_wen[2:0] = {3{refill_tag_wr}} & {refill_icache_init, + icache_refill_fifo, + ~icache_refill_fifo}; +assign refill_tag_din[46:0] = {~refill_icache_fifo, + refill_icache_done, refill_icache_addr[31:10], + refill_icache_done, refill_icache_addr[31:10]}; + +assign refill_inv_tag_req = refill_tag_wr | icache_inv_req; +assign refill_inv_tag_wen[2:0] = icache_inv_req ? icache_inv_wen[2:0] + : refill_tag_wen[2:0]; +assign refill_inv_tag_idx[9:0] = icache_inv_req ? icache_inv_idx[9:0] + : refill_icache_addr[14:5]; +assign refill_inv_tag_din[46:0] = icache_inv_req ? icache_inv_din[46:0] + : refill_tag_din[46:0]; + +assign icache_wr_data_req = refill_icache_req; +assign icache_wr_data_idx[12:0] = refill_icache_addr[14:2]; + +// c. I-Cache Tag hit buffer +// Tag Hit Buffer for cache memory low power +// including buffer valid, hit tag, hit way +// Instance ICG +assign tag_hit_clk_en = buf_upd_en | buf_clr_en; +// &Instance("gated_clk_cell","x_gated_hit_clk_cell"); @159 +gated_clk_cell x_gated_hit_clk_cell ( + .clk_in (forever_cpuclk ), + .clk_out (hit_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (tag_hit_clk_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @160 +// .global_en (cp0_yy_clk_en ), @161 +// .module_en (cp0_ifu_icg_en), @162 +// .local_en (tag_hit_clk_en), @163 +// .external_en(1'b0 ), @164 +// .clk_out (hit_clk )); @165 + +// buffer update: +// update when refill final or read hit +assign buf_rfl_upd = refill_icache_req & refill_icache_done; +assign buf_hit_upd = icache_rd_vld & ~direct_sel + & (icache_way1_hit | icache_way0_hit); + +// buf update when refill last or hit valid +assign buf_upd_en = buf_rfl_upd | buf_hit_upd; + +// buf clear when refill first req or invalid one req or invalid all last +assign buf_clr_en = refill_icache_req & refill_icache_init | cp0_ifu_icache_inv_req; + + +always @ (posedge hit_clk or negedge cpurst_b) +begin + if(~cpurst_b) + tag_hit_vld <= 1'b0; + else if(buf_clr_en) + tag_hit_vld <= 1'b0; + else if(buf_upd_en) + tag_hit_vld <= 1'b1; + else + tag_hit_vld <= tag_hit_vld; +end + +always @ (posedge icache_rd_clk or negedge cpurst_b) +begin + if(~cpurst_b) + direct_sel <= 1'b0; + else if(icache_rd_req & ref_rdy & cen_mask_vld) + direct_sel <= 1'b1; + else if(direct_sel) + direct_sel <= 1'b0; + else + direct_sel <= direct_sel; +end + +assign hit_tag[26:0] = buf_rfl_upd ? refill_icache_addr[31:5] : icache_rd_addr[31:5]; +assign hit_way = buf_rfl_upd ? icache_data_wen[1] : icache_way1_hit; +always @ (posedge hit_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + buf_hit_tag[26:0] <= 27'b0; + buf_hit_way <= 1'b0; + end + else if(buf_upd_en) + begin + buf_hit_tag[26:0] <= hit_tag[26:0]; + buf_hit_way <= hit_way; + end +end + +assign addr_equal = pcgen_ifetch_seq_addr[31:5] == buf_hit_tag[26:0]; + +assign cen_mask_vld = tag_hit_vld & addr_equal & ~pcgen_ifetch_chgflw_vld & ~buf_upd_en; + +// d. I-Cache Request +// Generate Chip Enable, Write Enable, Index, Tag In and Data In +// request priority : refill > inv > cache_rd + +assign icache_tag_cen = icache_rd_req_data & ~cen_mask_vld + | refill_inv_tag_req; +assign icache_tag_wen[2:0] = icache_rd_req_data ? 3'b0 : refill_inv_tag_wen[2:0]; +assign icache_tag_idx[9:0] = icache_rd_req_data ? icache_rd_tag_idx[9:0] + : refill_inv_tag_idx[9:0]; +assign icache_tag_din[46:0] = refill_inv_tag_din[46:0]; + +//data ram access +assign icache_data_cen[1:0] = {(cen_mask_vld ? buf_hit_way : icache_rd_req_data) + | icache_data_wen[1], + (cen_mask_vld ? ~buf_hit_way : icache_rd_req_data) + | icache_data_wen[0]}; +assign icache_data_wen[1:0] = {icache_wr_data_req & icache_refill_fifo, + icache_wr_data_req & ~icache_refill_fifo}; +assign icache_data_idx[12:0] = icache_rd_req_data ? icache_rd_data_idx[12:0] + : icache_wr_data_idx[12:0]; +assign icache_data_din[31:0] = refill_icache_data[31:0]; + +//------------------------------------------------ +// 3. Instance I-Cache Array +//------------------------------------------------ +// &Instance("pa_ifu_icache_tag_array", "x_pa_ifu_icache_tag_array"); @249 +pa_ifu_icache_tag_array x_pa_ifu_icache_tag_array ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .forever_cpuclk (forever_cpuclk ), + .icache_tag_cen (icache_tag_cen ), + .icache_tag_din (icache_tag_din ), + .icache_tag_dout (icache_tag_dout ), + .icache_tag_idx (icache_tag_idx ), + .icache_tag_wen (icache_tag_wen ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_ifu_icache_data_array", "x_pa_ifu_icache_data_array"); @250 +pa_ifu_icache_data_array x_pa_ifu_icache_data_array ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .forever_cpuclk (forever_cpuclk ), + .icache_data0_dout (icache_data0_dout ), + .icache_data1_dout (icache_data1_dout ), + .icache_data_cen (icache_data_cen ), + .icache_data_din (icache_data_din ), + .icache_data_idx (icache_data_idx ), + .icache_data_wen (icache_data_wen ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + + +//------------------------------------------------ +// 4. I-Cache Hit Judge and Data Select +// a. Cache Tag and Data output +// b. Cache Tag Compare +// c. Cache Data Select +// d. Cache Miss Generation +//------------------------------------------------ + +// a. Cache Tag and Data output +assign icache_tag_fifo = icache_tag_dout[46]; +assign icache_tag_way1_vld = icache_tag_dout[45]; +assign icache_tag_way1_dout[21:0] = icache_tag_dout[44:23]; +assign icache_tag_way0_vld = icache_tag_dout[22]; +assign icache_tag_way0_dout[21:0] = icache_tag_dout[21:0]; + +// b. Cache Tag Compare +always @ (posedge forever_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + icache_rd_vld <= 1'b0; + else if(icache_rd_req & ref_rdy & icache_ca_ff) + icache_rd_vld <= 1'b1; + else + icache_rd_vld <= 1'b0; +end +assign icache_ifetch_idle = ~icache_rd_vld & ref_fsm_idle + & uc_fsm_idle; + +always @ (posedge icache_rd_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + icache_rd_addr[31:0] <= 32'b0; + icache_rd_prot[3:0] <= 4'b0; + icache_vec_data <= 1'b0; + icache_en <= 1'b0; + icache_deny <= 1'b0; + end + else if(icache_rd_req & ref_rdy & icache_ca_ff) + begin + icache_rd_addr[31:0] <= ifetch_req_addr[31:0]; + icache_rd_prot[3:0] <= ifetch_req_prot[3:0]; + icache_vec_data <= vec_ifetch_data_fetch; + icache_en <= cp0_ifu_icache_en; + icache_deny <= pmp_ifu_acc_deny; + end + else + begin + icache_rd_addr[31:0] <= icache_rd_addr[31:0]; + icache_rd_prot[3:0] <= icache_rd_prot[3:0]; + icache_vec_data <= icache_vec_data; + icache_en <= icache_en; + icache_deny <= icache_deny; + end +end +always @ (posedge icache_rd_clk or negedge cpurst_b) +begin + if(~cpurst_b) + icache_ca_ff <= 1'b0; + else if(icache_rd_req) + icache_ca_ff <= ifetch_req_ca & cp0_ifu_icache_en; + else + icache_ca_ff <= icache_ca_ff; +end +// &Force("nonport", "icache_cmp_tag"); @316 +// &Force("nonport", "icache_cmp_tag_fin"); @317 +// &Force("nonport", "icache_inv_done"); @318 +// &Force("nonport", "inv_cnt_inc"); @319 +// &Force("bus", "pcgen_ifetch_seq_addr", 31, 0); @320 + +assign icache_cmp_tag[21:0] = inv_tag_wen ? cp0_ifu_icache_inv_addr[31:10] : icache_rd_addr[31:10]; +//csky vperl_off +`ifdef ICACHE_2K +assign icache_cmp_tag_fin[21:0] = icache_cmp_tag[21:0]; +`else +assign icache_cmp_tag_fin[21:0] = {{(22-`I_TAG_TAG_WIDTH){1'b0}}, + icache_cmp_tag[21:22-`I_TAG_TAG_WIDTH]}; + +`endif +//csky vperl_on +assign icache_way1_hit = {icache_tag_way1_vld, icache_tag_way1_dout[21:0]} + == {1'b1, icache_cmp_tag_fin[21:0]}; +assign icache_way0_hit = {icache_tag_way0_vld, icache_tag_way0_dout[21:0]} + == {1'b1, icache_cmp_tag_fin[21:0]}; + +assign icache_hit = (icache_way1_hit | icache_way0_hit) & icache_en + | icache_deny | direct_sel; + +assign icache_hit_vld = icache_hit & icache_rd_vld; +assign icache_hit1 = direct_sel ? buf_hit_way : icache_way1_hit; +assign icache_hit0 = direct_sel ? ~buf_hit_way : icache_way0_hit; +assign icache_hit_inst[31:0] = {32{icache_hit1}} & icache_data1_dout[31:0] + | {32{icache_hit0}} & icache_data0_dout[31:0]; + +// d. Cache Miss Generation +assign icache_miss_req = ~icache_hit & icache_rd_vld; +assign icache_miss_addr[31:0] = icache_rd_addr[31:0]; +assign icache_miss_prot[3:0] = icache_rd_prot[3:0]; + +//------------------------------------------------ +// 5. I-Cache Refill Control +// a. Refill control to ibus +// b. Refill Request to icache +//------------------------------------------------ + +// a. Refill control to ibus +always @ (posedge icache_refdp_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + icache_refill_addr[31:0] <= 32'b0; + icache_refill_fifo <= 1'b0; + icache_refill_prot[3:0] <= 4'b0; + icache_en_f <= 1'b0; + end + else if(icache_miss_req & ref_fsm_idle) + begin + icache_refill_addr[31:0] <= {icache_miss_addr[31:1], 1'b0}; + icache_refill_fifo <= icache_tag_fifo; + icache_refill_prot[3:0] <= icache_miss_prot[3:0]; + icache_en_f <= icache_en; + end +end +assign icache_refill_ca = icache_refill_prot[3] & icache_en_f; + +// Refill FSM +// including IDLE state, wait for data state, +parameter IDLE = 2'b00, + REQ = 2'b01, + WFC = 2'b10, + RFL = 2'b11; + +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ref_cur_st[1:0] <= IDLE; + else + ref_cur_st[1:0] <= ref_nxt_st[1:0]; +end + +// &CombBeg; @392 +always @( icache_refill_ca + or ref_cnt_done + or ibus_icache_error + or icache_miss_req + or ref_cur_st[1:0] + or ibus_icache_cmplt + or ibus_icache_grant) +begin +case(ref_cur_st[1:0]) + IDLE: + begin + if(icache_miss_req) + ref_nxt_st[1:0] = REQ; + else + ref_nxt_st[1:0] = IDLE; + end + REQ: + begin + if (ibus_icache_grant) + ref_nxt_st[1:0] = WFC; + else + ref_nxt_st[1:0] = REQ; + end + WFC: + begin + if(ibus_icache_cmplt) + if(ibus_icache_error) + ref_nxt_st[1:0] = IDLE; + else + ref_nxt_st[1:0] = icache_refill_ca ? RFL : IDLE; + else + ref_nxt_st[1:0] = WFC; + end + RFL: + begin + if(ref_cnt_done | ibus_icache_error) + ref_nxt_st[1:0] = IDLE; + else + ref_nxt_st[1:0] = RFL; + end + default: + begin + ref_nxt_st[1:0] = IDLE; + end +endcase +// &CombEnd; @430 +end + +// state information +assign ref_fsm_idle = ref_cur_st[1:0] == IDLE; +assign ref_fsm_req = ref_cur_st[1:0] == REQ; +assign ref_fsm_wfc = ref_cur_st[1:0] == WFC; +assign ref_fsm_ref = ref_cur_st[1:0] == RFL; + +//refill abort +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + refill_data_abort <= 1'b0; + else if (ctrl_ifetch_req_abort & !ref_rdy) + refill_data_abort <= 1'b1; + else if (ref_fsm_idle & icache_miss_req) + refill_data_abort <= 1'b0; +end + +// request counter +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + req_cnt[2:0] <= 3'b000; + else if(ref_fsm_idle & icache_miss_req) + req_cnt[2:0] <= icache_miss_addr[4:2]; + else if(icache_req & ibus_icache_grant & icache_refill_ca) + req_cnt[2:0] <= req_cnt[2:0] + 3'b001; + else + req_cnt[2:0] <= req_cnt[2:0]; +end + +// req done when req_cnt wrap back to miss req addr +assign req_cnt_done = req_cnt[2:0] == icache_refill_addr[4:2]; +assign req_addr[31:0] = {icache_refill_addr[31:5], req_cnt[2:0], 2'b00}; + +//refill valid +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ref_vld <= 1'b0; + else if (ref_fsm_ref | ref_fsm_wfc & icache_refill_ca) + ref_vld <= ibus_icache_cmplt & ~ibus_icache_error; +end + +// refill address gen +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ref_cnt[2:0] <= 3'b000; + else if(ref_fsm_idle & icache_miss_req) + ref_cnt[2:0] <= icache_miss_addr[4:2]; + else if(ref_fsm_ref & ibus_icache_cmplt & ~ibus_icache_error) + ref_cnt[2:0] <= ref_cnt_inc[2:0]; + else + ref_cnt[2:0] <= ref_cnt[2:0]; +end + +assign ref_cnt_inc[2:0] = ref_cnt[2:0] + 3'b001; + +assign ref_cnt_done = ref_cnt_inc[2:0] == icache_miss_addr[4:2]; + +assign refill_addr[31:0] = {icache_refill_addr[31:5], ref_cnt[2:0], 2'b0}; + +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + refill_data[31:0] <= 32'b0; + else if (ibus_icache_cmplt & ~ibus_icache_error) + refill_data[31:0] <= ibus_icache_data[31:0]; +end + +// Un-Cache FSM +// including IDLE state, wait for data state, +parameter UIDLE = 1'b0, + UWFC = 1'b1; + +always @ (posedge icache_reffsm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + uc_cur_st <= UIDLE; + else + uc_cur_st <= uc_nxt_st; +end + +// &CombBeg; @515 +always @( bmu_ifu_acc_err + or ibus_icache_uc_cmplt + or ifetch_outstanding + or icache_uc_req + or uc_cur_st) +begin +case(uc_cur_st) + UIDLE: + begin + if(icache_uc_req) + uc_nxt_st = UWFC; + else + uc_nxt_st = UIDLE; + end + UWFC: + begin + if(ibus_icache_uc_cmplt) + if(bmu_ifu_acc_err) + uc_nxt_st = UIDLE; + else if(icache_uc_req) + uc_nxt_st = UWFC; + else if(~ifetch_outstanding) + uc_nxt_st = UIDLE; + else + uc_nxt_st = UWFC; + else + uc_nxt_st = UWFC; + end + default: + begin + uc_nxt_st = UIDLE; + end +endcase +// &CombEnd; @543 +end + +assign uc_fsm_idle = uc_cur_st == UIDLE; +assign uc_fsm_wfc = uc_cur_st == UWFC; + +always @ (posedge icache_addr_clk or negedge cpurst_b) +begin + if(~cpurst_b) + icache_addr_ff[31:0] <= 32'b0; + else if(icache_rd_req | icache_uc_req) + icache_addr_ff[31:0] <= ifetch_req_addr[31:0]; +end + +// refill ibus request +assign icache_req = ref_fsm_req + | ref_fsm_wfc & icache_refill_ca + | ref_fsm_ref & ~req_cnt_done + | icache_uc_req; + +assign icache_data_req = ref_fsm_req + | ref_fsm_wfc & icache_refill_ca + | ref_fsm_ref & ~req_cnt_done + | icache_uc_data_req; + +assign icache_ibus_req = icache_req; +assign icache_ibus_data_req = icache_data_req; +assign icache_ibus_addr[31:0] = ref_fsm_idle ? ifetch_req_addr[31:0] + : req_addr[31:0]; +assign icache_ibus_prot[3:0] = ref_fsm_idle ? ifetch_req_prot[3:0] + : icache_refill_prot[3:0]; +assign icache_ibus_seq = ref_fsm_wfc & icache_refill_ca + | ref_fsm_ref & ~req_cnt_done; +assign icache_ibus_burst[2:0] = ref_fsm_idle ? 3'b000 : 3'b100; +assign icache_ibus_acc_deny = ref_fsm_idle & pmp_ifu_acc_deny; + +// refill icache request +assign refill_icache_req = ref_fsm_ref & ref_vld; +assign refill_icache_init = ref_cnt[2:0] == icache_miss_addr[4:2]; +assign refill_icache_done = ref_cnt_done; +assign refill_icache_addr[31:0] = refill_addr[31:0]; +assign refill_icache_fifo = icache_refill_fifo; +assign refill_icache_data[31:0] = refill_data[31:0]; + +// icache result to ifetch +assign icache_cmplt = ref_fsm_wfc & ibus_icache_cmplt & ~refill_data_abort; +assign icache_bypass_vld = icache_cmplt // & ~icache_vec_data + | uc_fsm_wfc & ibus_icache_cmplt; +assign icache_ifetch_inst_vld = icache_bypass_vld | icache_hit_vld;// & ~icache_vec_data; +assign icache_ifetch_inst_vld_gate = icache_bypass_vld | icache_rd_vld; +assign icache_ifetch_inst[31:0] = icache_bypass_vld ? ibus_icache_data[31:0] + : icache_hit_inst[31:0]; +assign icache_ifetch_error = icache_bypass_vld ? ibus_icache_error + : icache_deny; +assign icache_ifetch_unalign = icache_bypass_vld ? uc_fsm_wfc ? ibus_icache_unalign + : icache_refill_addr[1] + : icache_rd_addr[1]; +assign icache_ifetch_grant = ref_rdy & icache_rd_req & icache_ca_ff + | icache_uc_req & ibus_icache_grant + | icache_uc_sel & ifetch_outstanding & ibus_icache_grant; +assign ref_rdy = ref_fsm_idle & ~icache_miss_req; +assign icache_ifetch_vec_data_cmplt = (icache_cmplt | icache_hit_vld) & icache_vec_data + | uc_fsm_wfc & ibus_icache_cmplt; + +assign icache_ifetch_rd_addr[31:0] = ifetch_req_addr[31:0]; +assign icache_ifetch_addr[31:0] = icache_addr_ff[31:0]; +assign icache_ifetch_mach_mode = ifetch_req_prot[1]; +assign icache_ifetch_not_busy = (~ref_fsm_idle | icache_rd_vld) & ~ibus_trans_abort + | ibus_icache_not_busy; +assign icache_ifetch_uc_sel = uc_fsm_wfc; + +// e. ICache Invalid Request +parameter INV_IDLE = 2'b00; +parameter INV_WRTE = 2'b10; +parameter INV_READ = 2'b01; +parameter INV_FLOP = 2'b11; + +// Invalid FSM, for Array Invalid +// IDLE: default state +// WRTE: invalid iteration state +always @ (posedge icache_inv_clk or negedge cpurst_b) +begin + if(~cpurst_b) + inv_cur_st[1:0] <= INV_IDLE; + else + inv_cur_st[1:0] <= inv_nxt_st[1:0]; +end + +assign inv_type_pa = cp0_ifu_icache_inv_type; + +// &CombBeg; @632 +always @( inv_type_pa + or inv_cur_st[1:0] + or cp0_ifu_icache_inv_req + or ref_rdy + or icache_inv_done) +begin +case(inv_cur_st[1:0]) + INV_IDLE: begin + if(cp0_ifu_icache_inv_req & ref_rdy) + inv_nxt_st[1:0] = inv_type_pa ? INV_READ : INV_WRTE; + else + inv_nxt_st[1:0] = INV_IDLE; + end + INV_WRTE: begin + if(icache_inv_done) + inv_nxt_st[1:0] = INV_IDLE; + else + inv_nxt_st[1:0] = INV_WRTE; + end + INV_READ: inv_nxt_st[1:0] = INV_FLOP; + INV_FLOP: inv_nxt_st[1:0] = INV_WRTE; + default: inv_nxt_st[1:0] = INV_IDLE; +endcase +// &CombEnd; @650 +end + +assign inv_fsm_idle = inv_cur_st[1:0] == INV_IDLE & ~cp0_ifu_icache_inv_req; +assign inv_fsm_write = inv_cur_st[1:0] == INV_WRTE; +assign inv_tag_wen = inv_cur_st[1:0] == INV_FLOP; + +always @ (posedge icache_inv_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ipa_way_sel[1:0] <= 2'b0; + else if (inv_tag_wen) + ipa_way_sel[1:0] <= {icache_way1_hit,icache_way0_hit}; +end + +assign inv_way_sel[1:0] = inv_type_pa ? ipa_way_sel[1:0] : 2'b11; + +assign icache_inv_rd = inv_cur_st[1:0] == INV_READ; +assign icache_inv_wt = inv_fsm_write & (|inv_way_sel[1:0]); + +assign icache_inv_req = icache_inv_rd | icache_inv_wt; +assign icache_inv_wen[2:0] = {3{icache_inv_wt}} + & {~inv_type_pa, inv_way_sel[1:0]}; +assign icache_inv_din[46:0] = {1'b1, 46'b0}; +assign icache_inv_idx[9:0] = inv_type_pa ? cp0_ifu_icache_inv_addr[14:5] + : inv_cnt[9:0]; + +assign inv_cnt_en = inv_fsm_write & ~inv_type_pa; + +always @ (posedge icache_inv_clk or negedge cpurst_b) +begin + if(~cpurst_b) + inv_cnt[9:0] <= {10{1'b0}}; + else if(inv_cnt_en) + inv_cnt[9:0] <= inv_cnt_inc[9:0]; + else + inv_cnt[9:0] <= inv_cnt[9:0]; +end + +//csky vperl_off +`ifdef ICACHE_64K +assign inv_cnt_inc[9:0] = inv_cnt[9:0] + 1'b1; +`else +assign inv_cnt_inc[9:0] = {{(10-`I_TAG_INDEX_WIDTH){1'b0}}, + inv_cnt[`I_TAG_INDEX_WIDTH-1:0] + 1'b1}; +`endif +assign icache_inv_done = inv_type_pa & inv_fsm_write | + ~inv_type_pa & inv_cnt_inc[`I_TAG_INDEX_WIDTH-1:0] + == {`I_TAG_INDEX_WIDTH{1'b0}}; +//csky vperl_on +assign ifu_cp0_icache_inv_done = icache_inv_done; + +//========================================================== +// Rename for Output +//========================================================== +// &Force("input", "cp0_ifu_icache_inv_addr"); @704 +// &Force("bus", "cp0_ifu_icache_inv_addr", 31, 0); @705 +//assign cp0_ifu_icache_inv_addr[31:0] = 32'b0; + +// Output to HPCP +assign ifu_hpcp_icache_access = icache_rd_vld & ref_fsm_idle; +assign ifu_hpcp_icache_miss = icache_miss_req; + +// Output to top +assign icache_top_rd_vld = icache_rd_vld; +assign icache_top_ref_st[1:0] = ref_cur_st[1:0]; +assign icache_top_abort = refill_data_abort; +assign icache_top_uc_st = uc_cur_st; + +// &ModuleEnd; @718 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_data_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_data_array.v new file mode 100644 index 0000000000000000000000000000000000000000..7d9e9c2415b219d3f7278fd8059f1f9df1a8030c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_data_array.v @@ -0,0 +1,166 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module pa_ifu_icache_data_array( + cp0_yy_clk_en, + cp0_ifu_icg_en, + forever_cpuclk, + icache_data0_dout, + icache_data1_dout, + icache_data_cen, + icache_data_din, + icache_data_idx, + icache_data_wen, + pad_yy_icg_scan_en +); + +input cp0_yy_clk_en; +input cp0_ifu_icg_en; +input forever_cpuclk; +input [1 :0] icache_data_cen; +input [31:0] icache_data_din; +input [12:0] icache_data_idx; +input [1 :0] icache_data_wen; +input pad_yy_icg_scan_en; +output [31:0] icache_data0_dout; +output [31:0] icache_data1_dout; + +wire cp0_yy_clk_en; +wire cp0_ifu_icg_en; +wire forever_cpuclk; +wire [31:0] icache_data0_bwen_b; +wire icache_data0_cen_b; +wire icache_data0_clk; +wire [31:0] icache_data0_dout; +wire icache_data0_gwen_b; +wire icache_data0_icg_en; +wire [31:0] icache_data1_bwen_b; +wire icache_data1_cen_b; +wire icache_data1_clk; +wire [31:0] icache_data1_dout; +wire icache_data1_gwen_b; +wire icache_data1_icg_en; +wire [1 :0] icache_data_cen; +wire [31:0] icache_data_din; +wire [12:0] icache_data_idx; +wire [1 :0] icache_data_wen; +wire pad_yy_icg_scan_en; + + +//========================================================== +// Icache Data Array Module +// 1. Instance ICG Cell +// 2. Transmit Port Signals +// 3. Instance Memory Cell +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign icache_data1_icg_en = icache_data_cen[1]; +gated_clk_cell x_icache_data1_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_data1_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_data1_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +assign icache_data0_icg_en = icache_data_cen[0]; +gated_clk_cell x_icache_data0_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_data0_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_data0_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +assign icache_data1_cen_b = ~icache_data_cen[1]; +assign icache_data1_gwen_b = ~icache_data_wen[1]; +assign icache_data1_bwen_b[31:0] = ~{32{icache_data_wen[1]}}; + +assign icache_data0_cen_b = ~icache_data_cen[0]; +assign icache_data0_gwen_b = ~icache_data_wen[0]; +assign icache_data0_bwen_b[31:0] = ~{32{icache_data_wen[0]}}; + +//csky vperl_off +`ifdef ICACHE_2K +pa_spsram_256x32 x_pa_spsram_256x32_1 +`endif +`ifdef ICACHE_4K +pa_spsram_512x32 x_pa_spsram_512x32_1 +`endif +`ifdef ICACHE_8K +pa_spsram_1024x32 x_pa_spsram_1024x32_1 +`endif +`ifdef ICACHE_16K +pa_spsram_2048x32 x_pa_spsram_2048x32_1 +`endif +`ifdef ICACHE_32K +pa_spsram_4096x32 x_pa_spsram_4096x32_1 +`endif +`ifdef ICACHE_64K +pa_spsram_8192x32 x_pa_spsram_8192x32_1 +`endif +( + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .A (icache_data_idx[`I_TAG_INDEX_WIDTH+2:0]), + .CEN (icache_data1_cen_b ), + .CLK (icache_data1_clk ), + .D (icache_data_din ), + .GWEN (icache_data1_gwen_b ), + .Q (icache_data1_dout ), + .WEN (icache_data1_bwen_b ) +); + +`ifdef ICACHE_2K +pa_spsram_256x32 x_pa_spsram_256x32_0 +`endif +`ifdef ICACHE_4K +pa_spsram_512x32 x_pa_spsram_512x32_0 +`endif +`ifdef ICACHE_8K +pa_spsram_1024x32 x_pa_spsram_1024x32_0 +`endif +`ifdef ICACHE_16K +pa_spsram_2048x32 x_pa_spsram_2048x32_0 +`endif +`ifdef ICACHE_32K +pa_spsram_4096x32 x_pa_spsram_4096x32_0 +`endif +`ifdef ICACHE_64K +pa_spsram_8192x32 x_pa_spsram_8192x32_0 +`endif +( + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .A (icache_data_idx[`I_TAG_INDEX_WIDTH+2:0]), + .CEN (icache_data0_cen_b ), + .CLK (icache_data0_clk ), + .D (icache_data_din ), + .GWEN (icache_data0_gwen_b ), + .Q (icache_data0_dout ), + .WEN (icache_data0_bwen_b ) +); +//csky vperl_on + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_tag_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_tag_array.v new file mode 100644 index 0000000000000000000000000000000000000000..6c6046827d299cd0bf0a5644c0bb984aecc03a50 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_icache_tag_array.v @@ -0,0 +1,164 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module pa_ifu_icache_tag_array( + cp0_yy_clk_en, + cp0_ifu_icg_en, + forever_cpuclk, + icache_tag_cen, + icache_tag_din, + icache_tag_dout, + icache_tag_idx, + icache_tag_wen, + pad_yy_icg_scan_en +); + +input cp0_yy_clk_en; +input cp0_ifu_icg_en; +input forever_cpuclk; +input icache_tag_cen; +input [46:0] icache_tag_din; +input [9 :0] icache_tag_idx; +input [2 :0] icache_tag_wen; +input pad_yy_icg_scan_en; +output [46:0] icache_tag_dout; + +wire cp0_yy_clk_en; +wire cp0_ifu_icg_en; +wire forever_cpuclk; +wire [46:0] icache_tag_bwen; +wire [46:0] icache_tag_bwen_b; +wire icache_tag_cen; +wire icache_tag_cen_b; +wire icache_tag_clk; +wire [46:0] icache_tag_din; +wire [46:0] icache_tag_din_fin; +wire [46:0] icache_tag_dout; +wire [46:0] icache_tag_dout_raw; +wire icache_tag_gwen; +wire icache_tag_gwen_b; +wire icache_tag_icg_en; +wire [9 :0] icache_tag_idx; +wire [2 :0] icache_tag_wen; +wire pad_yy_icg_scan_en; + +//========================================================== +// Icache Tag Array Module +// 1. Instance ICG Cell +// 2. Transmit Port Signals +// 3. Instance Memory Cell +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign icache_tag_icg_en = icache_tag_cen; +// &Instance("gated_clk_cell", "x_icache_tag_icg_cell"); @92 +gated_clk_cell x_icache_tag_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (icache_tag_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (icache_tag_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk ), @93 +// .external_en(1'b0 ), @94 +// .global_en (cp0_yy_clk_en ), @95 +// .module_en (cp0_ifu_icg_en ), @96 +// .local_en (icache_tag_icg_en), @97 +// .clk_out (icache_tag_clk ) @98 +// ); @99 + +//------------------------------------------------ +// 2. Transmit Port Signals +//------------------------------------------------ +assign icache_tag_gwen = |icache_tag_wen[2:0]; +//csky vperl_off +`ifdef ICACHE_2K +assign icache_tag_bwen[46:0] = { + { {icache_tag_wen[2]}}, //fifo + {(`I_TAG_TAG_WIDTH+1){icache_tag_wen[1]}}, //way1 + {(`I_TAG_TAG_WIDTH+1){icache_tag_wen[0]}} //way0 + }; +assign icache_tag_dout[46:0] = icache_tag_dout_raw[46:0]; +`else +assign icache_tag_bwen[46:0] = { {2*(22-`I_TAG_TAG_WIDTH){1'b0}}, + { {icache_tag_wen[2]}}, //fifo + {(`I_TAG_TAG_WIDTH+1){icache_tag_wen[1]}}, //way1 + {(`I_TAG_TAG_WIDTH+1){icache_tag_wen[0]}} //way0 + }; +assign icache_tag_dout[46:0] = { + icache_tag_dout_raw[2*`I_TAG_TAG_WIDTH+2:2*`I_TAG_TAG_WIDTH+1], + {(22-`I_TAG_TAG_WIDTH){1'b0}}, + icache_tag_dout_raw[2*`I_TAG_TAG_WIDTH:`I_TAG_TAG_WIDTH], + {(22-`I_TAG_TAG_WIDTH){1'b0}}, + icache_tag_dout_raw[`I_TAG_TAG_WIDTH-1:0] + }; + +assign icache_tag_dout_raw[46:2*`I_TAG_TAG_WIDTH+3] = {(44-2*`I_TAG_TAG_WIDTH){1'b0}}; +assign icache_tag_din_fin[46:2*`I_TAG_TAG_WIDTH+3] = {(44-2*`I_TAG_TAG_WIDTH){1'b0}}; +`endif +//csky vperl_on +assign icache_tag_cen_b = ~icache_tag_cen; +assign icache_tag_gwen_b = ~icache_tag_gwen; +assign icache_tag_bwen_b[46:0] = ~icache_tag_bwen[46:0]; +assign icache_tag_din_fin[2*`I_TAG_TAG_WIDTH+2:0] = + {icache_tag_din[46:45-`I_TAG_TAG_WIDTH], + icache_tag_din[22:22-`I_TAG_TAG_WIDTH] + }; + +//------------------------------------------------ +// 3. Instance Memory Cell +//------------------------------------------------ +//csky vperl_off +`ifdef ICACHE_2K +pa_spsram_32x47 x_pa_spsram_32x47 +`endif +`ifdef ICACHE_4K +pa_spsram_64x45 x_pa_spsram_64x45 +`endif +`ifdef ICACHE_8K +pa_spsram_128x43 x_pa_spsram_128x43 +`endif +`ifdef ICACHE_16K +pa_spsram_256x41 x_pa_spsram_256x41 +`endif +`ifdef ICACHE_32K +pa_spsram_512x39 x_pa_spsram_512x39 +`endif +`ifdef ICACHE_64K +pa_spsram_1024x37 x_pa_spsram_1024x37 +`endif +( + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .CLK (icache_tag_clk ), + .CEN (icache_tag_cen_b ), + .GWEN (icache_tag_gwen_b ), + .WEN (icache_tag_bwen_b[2*`I_TAG_TAG_WIDTH+2:0]), + .A (icache_tag_idx[`I_TAG_INDEX_WIDTH-1:0]), + .D (icache_tag_din_fin[2*`I_TAG_TAG_WIDTH+2:0]), + .Q (icache_tag_dout_raw[2*`I_TAG_TAG_WIDTH+2:0]) +); +//csky vperl_on + +// &ModuleEnd; @175 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_id_pred.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_id_pred.v new file mode 100644 index 0000000000000000000000000000000000000000..ad24a9c4fda76e548279f8d19ceae0ca34395243 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_id_pred.v @@ -0,0 +1,841 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_ifu_id_pred( + bht_top_cur_st, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_icg_en, + cp0_ifu_ras_en, + cp0_yy_clk_en, + cpurst_b, + dtu_ifu_halt_info0, + dtu_ifu_halt_info1, + forever_cpuclk, + ibuf_id_pred_hungry, + ibuf_ipack_stall, + ibuf_pred_stall, + id_pred_btb_cur_pc, + id_pred_btb_mis_pred, + id_pred_btb_mis_predg, + id_pred_btb_tar_pc, + id_pred_btb_upd_vld, + id_pred_btb_upd_vldg, + id_pred_ctrl_stall, + id_pred_ibuf_br_taken0, + id_pred_ibuf_br_taken1, + id_pred_ibuf_chgflw_vld0, + id_pred_ibuf_halt_info0, + id_pred_ibuf_halt_info1, + id_pred_ipack_chgflw_vld0, + id_pred_ipack_delay_stall, + id_pred_ipack_mask, + id_pred_ipack_ret_stall, + id_pred_pcgen_chgflw_pc, + id_pred_pcgen_chgflw_vld, + id_pred_pcgen_inst_vld, + idu_ifu_x1, + ifu_cp0_bht_inv_done, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ifu_dtu_exe_data0, + ifu_dtu_exe_data1, + ifu_iu_ex1_pc_pred, + ipack_id_pred_h0_create, + ipack_id_pred_h0_vld, + ipack_id_pred_inst0, + ipack_id_pred_inst0_expt, + ipack_id_pred_inst0_vld, + ipack_id_pred_inst1, + ipack_id_pred_inst1_expt, + ipack_id_pred_inst1_vld, + ipack_id_pred_new_vld, + ipack_id_pred_unalign, + iu_ifu_bht_cur_pc, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_bht_pred, + iu_ifu_bht_taken, + iu_ifu_br_vld, + iu_ifu_br_vld_gate, + iu_ifu_ind_link_vld, + iu_ifu_link_vld, + iu_ifu_link_vld_gate, + iu_ifu_pc_mispred, + iu_ifu_pc_mispred_gate, + iu_ifu_ret_vld, + iu_ifu_ret_vld_gate, + iu_yy_xx_cancel, + pad_yy_icg_scan_en, + pcgen_id_pred_btb_tar_pc, + pcgen_id_pred_btb_tar_vld, + pcgen_id_pred_flush_vld, + pcgen_id_pred_idpc, + pcgen_id_pred_ifpc, + pred_top_delay_chgflw, + pred_top_ras_st, + rtu_ifu_flush_fe +); + +// &Ports; @25 +input cp0_ifu_bht_en; +input cp0_ifu_bht_inv; +input cp0_ifu_icg_en; +input cp0_ifu_ras_en; +input cp0_yy_clk_en; +input cpurst_b; +input [14:0] dtu_ifu_halt_info0; +input [14:0] dtu_ifu_halt_info1; +input forever_cpuclk; +input ibuf_id_pred_hungry; +input ibuf_ipack_stall; +input ibuf_pred_stall; +input [31:0] idu_ifu_x1; +input ipack_id_pred_h0_create; +input ipack_id_pred_h0_vld; +input [31:0] ipack_id_pred_inst0; +input ipack_id_pred_inst0_expt; +input ipack_id_pred_inst0_vld; +input [15:0] ipack_id_pred_inst1; +input ipack_id_pred_inst1_expt; +input ipack_id_pred_inst1_vld; +input ipack_id_pred_new_vld; +input ipack_id_pred_unalign; +input [31:0] iu_ifu_bht_cur_pc; +input iu_ifu_bht_mispred; +input iu_ifu_bht_mispred_gate; +input [1 :0] iu_ifu_bht_pred; +input iu_ifu_bht_taken; +input iu_ifu_br_vld; +input iu_ifu_br_vld_gate; +input iu_ifu_ind_link_vld; +input iu_ifu_link_vld; +input iu_ifu_link_vld_gate; +input iu_ifu_pc_mispred; +input iu_ifu_pc_mispred_gate; +input iu_ifu_ret_vld; +input iu_ifu_ret_vld_gate; +input iu_yy_xx_cancel; +input pad_yy_icg_scan_en; +input [31:0] pcgen_id_pred_btb_tar_pc; +input pcgen_id_pred_btb_tar_vld; +input pcgen_id_pred_flush_vld; +input [31:0] pcgen_id_pred_idpc; +input [31:0] pcgen_id_pred_ifpc; +input rtu_ifu_flush_fe; +output [1 :0] bht_top_cur_st; +output [31:0] id_pred_btb_cur_pc; +output id_pred_btb_mis_pred; +output id_pred_btb_mis_predg; +output [31:0] id_pred_btb_tar_pc; +output id_pred_btb_upd_vld; +output id_pred_btb_upd_vldg; +output id_pred_ctrl_stall; +output [1 :0] id_pred_ibuf_br_taken0; +output [1 :0] id_pred_ibuf_br_taken1; +output id_pred_ibuf_chgflw_vld0; +output [14:0] id_pred_ibuf_halt_info0; +output [14:0] id_pred_ibuf_halt_info1; +output id_pred_ipack_chgflw_vld0; +output id_pred_ipack_delay_stall; +output id_pred_ipack_mask; +output id_pred_ipack_ret_stall; +output [31:0] id_pred_pcgen_chgflw_pc; +output id_pred_pcgen_chgflw_vld; +output id_pred_pcgen_inst_vld; +output ifu_cp0_bht_inv_done; +output ifu_dtu_addr_vld0; +output ifu_dtu_addr_vld1; +output ifu_dtu_data_vld0; +output ifu_dtu_data_vld1; +output [31:0] ifu_dtu_exe_addr0; +output [31:0] ifu_dtu_exe_addr1; +output [31:0] ifu_dtu_exe_data0; +output [31:0] ifu_dtu_exe_data1; +output [31:0] ifu_iu_ex1_pc_pred; +output pred_top_delay_chgflw; +output pred_top_ras_st; + +// &Regs; @26 +reg [31:0] chgflw_pc; +reg delay_chgflw; +reg h0_br_vld; +reg [31:0] id_pred_cur_pc; +reg [31:0] id_pred_h0_pc; +reg [1 :0] ras_cur_st; +reg [1 :0] ras_nxt_st; +reg [31:0] ras_pred_pc; + +// &Wires; @27 +wire bht_id_pred_mem_taken; +wire [1 :0] bht_id_pred_rslt; +wire [1 :0] bht_top_cur_st; +wire btb_mis_pred; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_icg_en; +wire cp0_ifu_ras_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire forever_cpuclk; +wire ibuf_id_pred_hungry; +wire ibuf_ipack_stall; +wire ibuf_pred_stall; +wire id_pred_bht_br_vld; +wire [2 :0] id_pred_bht_pc; +wire [31:0] id_pred_br_imm; +wire [1 :0] id_pred_br_rslt0; +wire [1 :0] id_pred_br_rslt1; +wire id_pred_br_sel1; +wire id_pred_br_taken; +wire id_pred_br_taken0; +wire id_pred_br_taken1; +wire [31:0] id_pred_br_tar; +wire id_pred_br_vld0; +wire id_pred_br_vld1; +wire id_pred_br_vld1_raw; +wire [31:0] id_pred_btb_cur_pc; +wire id_pred_btb_mis_pred; +wire id_pred_btb_mis_predg; +wire [31:0] id_pred_btb_tar_pc; +wire id_pred_btb_upd_vld; +wire id_pred_btb_upd_vldg; +wire id_pred_chgflw; +wire id_pred_chgflw_fin; +wire [31:0] id_pred_chgflw_fin_tar; +wire [31:0] id_pred_chgflw_fin_tar1; +wire [31:0] id_pred_chgflw_tar; +wire id_pred_chgflw_vld; +wire id_pred_chgflw_vld0; +wire id_pred_chgflw_vld1; +wire id_pred_clk; +wire id_pred_ctrl_stall; +wire id_pred_delay_br; +wire id_pred_delay_br1; +wire id_pred_delay_br_raw; +wire [1 :0] id_pred_ibuf_br_taken0; +wire [1 :0] id_pred_ibuf_br_taken1; +wire id_pred_ibuf_chgflw_vld0; +wire [14:0] id_pred_ibuf_halt_info0; +wire [14:0] id_pred_ibuf_halt_info1; +wire id_pred_icg_en; +wire [31:0] id_pred_idpc; +wire [31:0] id_pred_imm0; +wire [31:0] id_pred_imm1; +wire id_pred_ind_link_vld0; +wire id_pred_ind_link_vld1; +wire id_pred_inst0_32; +wire id_pred_inst0_bjtype; +wire [31:0] id_pred_inst0_bkpt_pc; +wire id_pred_inst0_taken; +wire [31:0] id_pred_inst1_bkpt_pc; +wire id_pred_inst1_taken; +wire id_pred_ipack_chgflw_vld0; +wire id_pred_ipack_delay_stall; +wire id_pred_ipack_mask; +wire id_pred_ipack_ret_stall; +wire id_pred_jmp_vld0; +wire id_pred_jmp_vld1; +wire id_pred_link_vld0; +wire id_pred_link_vld1; +wire [31:0] id_pred_nxt_offset; +wire [31:0] id_pred_nxt_pc; +wire [31:0] id_pred_pcgen_chgflw_pc; +wire id_pred_pcgen_chgflw_vld; +wire id_pred_pcgen_inst_vld; +wire id_pred_ras_ind_link; +wire id_pred_ras_ind_link_vld; +wire [23:0] id_pred_ras_link_pc; +wire id_pred_ras_link_vld; +wire id_pred_ras_link_vld0; +wire id_pred_ras_link_vld1; +wire id_pred_ras_ret_chgflw; +wire id_pred_ras_ret_req; +wire id_pred_ras_ret_req1; +wire id_pred_ras_ret_vld; +wire id_pred_ras_ret_vld0; +wire id_pred_ras_ret_vld1; +wire id_pred_ras_sel1; +wire [31:0] id_pred_ras_tar; +wire id_pred_ret_stall; +wire id_pred_ret_vld0; +wire id_pred_ret_vld1; +wire id_ras_clk; +wire id_ras_icg_en; +wire ifu_cp0_bht_inv_done; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire [31:0] ifu_dtu_exe_data0; +wire [31:0] ifu_dtu_exe_data1; +wire [31:0] ifu_iu_ex1_pc_pred; +wire ipack_id_pred_h0_create; +wire ipack_id_pred_h0_vld; +wire [31:0] ipack_id_pred_inst0; +wire ipack_id_pred_inst0_expt; +wire ipack_id_pred_inst0_vld; +wire [15:0] ipack_id_pred_inst1; +wire ipack_id_pred_inst1_expt; +wire ipack_id_pred_inst1_vld; +wire ipack_id_pred_new_vld; +wire ipack_id_pred_unalign; +wire [31:0] iu_ifu_bht_cur_pc; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire iu_ifu_ind_link_vld; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire iu_yy_xx_cancel; +wire pad_yy_icg_scan_en; +wire [31:0] pcgen_id_pred_btb_tar_pc; +wire pcgen_id_pred_btb_tar_vld; +wire pcgen_id_pred_flush_vld; +wire [31:0] pcgen_id_pred_idpc; +wire [31:0] pcgen_id_pred_ifpc; +wire pred_top_delay_chgflw; +wire pred_top_ras_st; +wire ras_cur_jalr; +wire ras_cur_ret; +wire [23:0] ras_id_pred_tar_pc; +wire [23:0] ras_link_offset; +wire ras_pred_pc_update; +wire rtu_ifu_flush_fe; + + +//========================================================== +// ID Stage Predication Module +// 1. Instance ICG Cell +// 2. ID Pre-decode for prediction +// 3. Current PC Generation +// 4. Branch Taken Result +// 5. RAS Target Result +// 6. ID Prediction Address Generation +// 7. Inst bkpt judgement +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign id_pred_icg_en = ipack_id_pred_h0_create | h0_br_vld + | id_pred_br_vld0 | id_pred_chgflw + | delay_chgflw; + +// &Instance("gated_clk_cell", "x_pa_ifu_id_pred_icg_cell"); @47 +gated_clk_cell x_pa_ifu_id_pred_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (id_pred_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (id_pred_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @48 +// .external_en (1'b0), @49 +// .global_en (cp0_yy_clk_en), @50 +// .module_en (cp0_ifu_icg_en), @51 +// .local_en (id_pred_icg_en), @52 +// .clk_out (id_pred_clk) @53 +// ); @54 + +assign id_ras_icg_en = pcgen_id_pred_flush_vld + | id_pred_ras_ret_chgflw + | id_pred_ras_ind_link + | iu_ifu_ret_vld + | ras_cur_ret + | ras_cur_jalr; +// &Instance("gated_clk_cell", "x_pa_ifu_id_ras_icg_cell"); @62 +gated_clk_cell x_pa_ifu_id_ras_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (id_ras_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (id_ras_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @63 +// .external_en (1'b0), @64 +// .global_en (cp0_yy_clk_en), @65 +// .module_en (cp0_ifu_icg_en), @66 +// .local_en (id_ras_icg_en), @67 +// .clk_out (id_ras_clk) @68 +// ); @69 + +//------------------------------------------------ +// 2. ID Pre-decode for prediction +//------------------------------------------------ +// &Instance("pa_ifu_pre_decd", "x_pa_ifu_pre_decd"); @74 +pa_ifu_pre_decd x_pa_ifu_pre_decd ( + .id_pred_br_vld0 (id_pred_br_vld0 ), + .id_pred_br_vld1 (id_pred_br_vld1 ), + .id_pred_br_vld1_raw (id_pred_br_vld1_raw ), + .id_pred_imm0 (id_pred_imm0 ), + .id_pred_imm1 (id_pred_imm1 ), + .id_pred_ind_link_vld0 (id_pred_ind_link_vld0 ), + .id_pred_ind_link_vld1 (id_pred_ind_link_vld1 ), + .id_pred_inst0_32 (id_pred_inst0_32 ), + .id_pred_jmp_vld0 (id_pred_jmp_vld0 ), + .id_pred_jmp_vld1 (id_pred_jmp_vld1 ), + .id_pred_link_vld0 (id_pred_link_vld0 ), + .id_pred_link_vld1 (id_pred_link_vld1 ), + .id_pred_ret_vld0 (id_pred_ret_vld0 ), + .id_pred_ret_vld1 (id_pred_ret_vld1 ), + .ipack_id_pred_inst0 (ipack_id_pred_inst0 ), + .ipack_id_pred_inst0_vld (ipack_id_pred_inst0_vld), + .ipack_id_pred_inst1 (ipack_id_pred_inst1 ), + .ipack_id_pred_inst1_vld (ipack_id_pred_inst1_vld) +); + + +//------------------------------------------------ +// 3. Current PC Generation +//------------------------------------------------ +assign id_pred_idpc[31:0] = pcgen_id_pred_idpc[31:0]; + +always @ (posedge id_pred_clk or negedge cpurst_b) +begin + if(~cpurst_b) + id_pred_h0_pc[31:0] <= 32'b0; + else if(ipack_id_pred_h0_create) + id_pred_h0_pc[31:0] <= {id_pred_idpc[31:2], 2'b10}; + else + id_pred_h0_pc[31:0] <= id_pred_h0_pc[31:0]; +end + +//&CombBeg; +//if(id_pred_br_taken0 & ~delay_chgflw) +// if(ipack_id_pred_h0_vld) +// id_pred_cur_pc[31:0] = id_pred_h0_pc[31:0]; +// else +// id_pred_cur_pc[31:0] = id_pred_idpc[31:0]; +//else if(id_pred_br_taken1 | id_pred_ras_sel1 | delay_chgflw) +// id_pred_cur_pc[31:0] = {id_pred_idpc[31:2], 2'b10}; +//else if(ipack_id_pred_h0_vld)// & ~ipack_id_pred_inst_full) +// id_pred_cur_pc[31:0] = id_pred_h0_pc[31:0]; +//else +// id_pred_cur_pc[31:0] = id_pred_idpc[31:0]; +//&CombEnd; +// &CombBeg; @104 +always @( id_pred_br_taken0 + or id_pred_h0_pc[31:0] + or id_pred_delay_br_raw + or delay_chgflw + or id_pred_br_sel1 + or id_pred_ras_sel1 + or id_pred_idpc[31:0] + or id_pred_link_vld0 + or ipack_id_pred_h0_vld) +begin + if(id_pred_br_taken0 & ~delay_chgflw | id_pred_link_vld0) + if(ipack_id_pred_h0_vld) + id_pred_cur_pc[31:0] = id_pred_h0_pc[31:0]; + else + id_pred_cur_pc[31:0] = id_pred_idpc[31:0]; + else if(id_pred_br_sel1 | id_pred_ras_sel1 | id_pred_delay_br_raw | delay_chgflw) + id_pred_cur_pc[31:0] = {id_pred_idpc[31:2], 2'b10}; + else + id_pred_cur_pc[31:0] = id_pred_idpc[31:0]; +// &CombEnd; @114 +end + + +assign id_pred_nxt_offset[31:0] = (ipack_id_pred_unalign | id_pred_delay_br_raw) ? 32'h2 : 32'h4; +assign id_pred_nxt_pc[31:0] = id_pred_cur_pc[31:0] + id_pred_nxt_offset[31:0]; + +//------------------------------------------------ +// 4. Branch Taken Result +// a. BHT Access Signal +// b. Instance BHT +// c. BHT Result +//------------------------------------------------ +// a. BHT Access Signal +assign id_pred_bht_br_vld = (id_pred_br_vld0 | id_pred_br_vld1) + & ~ibuf_ipack_stall; + +always @ (posedge id_pred_clk or negedge cpurst_b) +begin + if(~cpurst_b) + h0_br_vld <= 1'b0; + else if(pcgen_id_pred_flush_vld) + h0_br_vld <= 1'b0; + else if(ipack_id_pred_h0_create) + h0_br_vld <= id_pred_br_vld1_raw; + else if(h0_br_vld & ~ibuf_ipack_stall) + h0_br_vld <= 1'b0; + else + h0_br_vld <= h0_br_vld; +end + +assign id_pred_bht_pc[2:0] = h0_br_vld ? id_pred_h0_pc[3:1] + : (ipack_id_pred_unalign | ~id_pred_br_vld0) ? {id_pred_idpc[3:2], 1'b1} + : id_pred_idpc[3:1]; + +//assign id_pred_bht_mem_pc[2:0] = {id_pred_idpc[3:2], 1'b1}; + +// b. Instance BHT +// &Instance("pa_ifu_bht", "x_pa_ifu_bht"); @152 +pa_ifu_bht x_pa_ifu_bht ( + .bht_id_pred_mem_taken (bht_id_pred_mem_taken ), + .bht_id_pred_rslt (bht_id_pred_rslt ), + .bht_top_cur_st (bht_top_cur_st ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .id_pred_bht_br_vld (id_pred_bht_br_vld ), + .id_pred_bht_pc (id_pred_bht_pc ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .iu_ifu_bht_cur_pc (iu_ifu_bht_cur_pc ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate), + .iu_ifu_bht_pred (iu_ifu_bht_pred ), + .iu_ifu_bht_taken (iu_ifu_bht_taken ), + .iu_ifu_br_vld (iu_ifu_br_vld ), + .iu_ifu_br_vld_gate (iu_ifu_br_vld_gate ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Force("nonport", "id_pred_br_vld1_raw"); @154 +// &Force("input", "ipack_id_pred_new_vld"); @155 +// &Force("input", "iu_ifu_bht_mispred"); @156 +// &Force("input", "iu_ifu_bht_mispred_gate"); @157 +// &Force("input", "iu_ifu_br_vld"); @158 +// &Force("input", "iu_ifu_br_vld_gate"); @159 +// &Force("input", "iu_ifu_bht_cur_pc"); &Force("bus", "iu_ifu_bht_cur_pc", 31, 0); @160 +// &Force("input", "iu_ifu_bht_taken"); @161 +// &Force("input", "iu_ifu_bht_pred"); &Force("bus", "iu_ifu_bht_pred", 1, 0); @162 +assign id_pred_delay_br_raw = id_pred_br_vld0 && !bht_id_pred_rslt[1] + && id_pred_br_vld1; + +assign id_pred_delay_br = id_pred_br_vld0 & ~bht_id_pred_rslt[1] + & (id_pred_br_vld1 & (bht_id_pred_mem_taken + | ipack_id_pred_new_vld) + | id_pred_ret_vld1) + & ~ibuf_ipack_stall; + +assign id_pred_delay_br1 = id_pred_chgflw + & ~ibuf_ipack_stall; +//assign id_pred_delay_br1= id_pred_br_vld0 & ~bht_id_pred_rslt[1] +// & id_pred_br_vld1; +always @ (posedge id_pred_clk or negedge cpurst_b) +begin + if(~cpurst_b) + delay_chgflw <= 1'b0; + else if(pcgen_id_pred_flush_vld) + delay_chgflw <= 1'b0; + else if(id_pred_delay_br | id_pred_delay_br1) + delay_chgflw <= 1'b1; + else if(delay_chgflw & ~ibuf_ipack_stall) + delay_chgflw <= 1'b0; + else + delay_chgflw <= delay_chgflw; +end +always @ (posedge id_pred_clk or negedge cpurst_b) +begin + if(~cpurst_b) + chgflw_pc[31:0] <= 32'b0; + else if(id_pred_delay_br | id_pred_delay_br1) + chgflw_pc[31:0] <= id_pred_chgflw_fin_tar1[31:0]; +end + +// c. BHT Result +// all branch and jump taken result +assign id_pred_inst0_bjtype = id_pred_br_vld0 | id_pred_jmp_vld0; +assign id_pred_inst0_taken = id_pred_br_vld0 & bht_id_pred_rslt[1] + | id_pred_jmp_vld0; +assign id_pred_inst1_taken = ~id_pred_br_vld0 + & id_pred_br_vld1 & bht_id_pred_rslt[1] + | ~id_pred_inst0_taken & id_pred_br_vld0 + & id_pred_br_vld1 & bht_id_pred_mem_taken + | ~id_pred_inst0_taken & id_pred_jmp_vld1; +assign id_pred_br_taken0 = id_pred_inst0_taken; +assign id_pred_br_taken1 = id_pred_inst1_taken; +assign id_pred_br_taken = (id_pred_br_taken0 | id_pred_br_taken1) & ~delay_chgflw; + +assign id_pred_br_sel1 = id_pred_inst1_taken & ~id_pred_ras_link_vld0; + +assign id_pred_br_imm[31:0] = id_pred_inst0_taken ? id_pred_imm0[31:0] + : id_pred_imm1[31:0]; +assign id_pred_br_tar[31:0] = id_pred_cur_pc[31:0] + id_pred_br_imm[31:0]; +assign id_pred_br_rslt0[1:0] = {2{id_pred_br_vld0}} & bht_id_pred_rslt[1:0]; +assign id_pred_br_rslt1[1:0] = {2{id_pred_br_vld1 & ~id_pred_inst0_bjtype}} & bht_id_pred_rslt[1:0]; + +//------------------------------------------------ +// 5. RAS Target Result +// a. RAS Access Signal +// b. Instance RAS +// c. RAS Result +// d. RAS Stall FSM +//------------------------------------------------ + +// a. RAS Access Signal +assign id_pred_ras_link_vld0 = id_pred_link_vld0; +assign id_pred_ras_link_vld1 = id_pred_link_vld1 & ~id_pred_inst0_taken; +assign id_pred_ras_link_vld = (id_pred_ras_link_vld0 | id_pred_ras_link_vld1) + & cp0_ifu_ras_en + & ~ras_cur_jalr + & ~ibuf_ipack_stall; + +assign id_pred_ras_ret_vld0 = id_pred_ret_vld0; +assign id_pred_ras_ret_vld1 = id_pred_ret_vld1 & ~id_pred_inst0_bjtype; +assign id_pred_ras_ret_req1 = id_pred_ret_vld1 & ~id_pred_inst0_taken; +assign id_pred_ras_ret_chgflw = (id_pred_ras_ret_vld0 | id_pred_ras_ret_vld1); +assign id_pred_ras_ret_req = (id_pred_ras_ret_vld0 | id_pred_ras_ret_req1); + //& cp0_ifu_ras_en; // & ~ibuf_ipack_stall; +assign id_pred_ras_sel1 = id_pred_ras_link_vld1 & ~id_pred_ras_link_vld0; + +assign id_pred_ras_ret_vld = id_pred_ras_ret_chgflw & ~ras_cur_jalr & ~ibuf_ipack_stall; + +assign id_pred_ras_ind_link = (id_pred_ind_link_vld0 | id_pred_ind_link_vld1); +assign id_pred_ras_ind_link_vld = (id_pred_ind_link_vld0 + | id_pred_ind_link_vld1 & ~id_pred_inst0_taken) + & ~ibuf_ipack_stall + & cp0_ifu_ras_en; + +assign ras_link_offset[23:0] = id_pred_ras_link_vld0 & id_pred_inst0_32 + ? 24'h4 : 24'h2; + +assign id_pred_ras_link_pc[23:0] = id_pred_cur_pc[23:0] + ras_link_offset[23:0]; + +// b. Instance RAS +// &Instance("pa_ifu_ras", "x_pa_ifu_ras"); @267 +pa_ifu_ras x_pa_ifu_ras ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .id_pred_ras_link_pc (id_pred_ras_link_pc ), + .id_pred_ras_link_vld (id_pred_ras_link_vld ), + .id_pred_ras_ret_vld (id_pred_ras_ret_vld ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate), + .iu_ifu_link_vld (iu_ifu_link_vld ), + .iu_ifu_link_vld_gate (iu_ifu_link_vld_gate ), + .iu_ifu_pc_mispred (iu_ifu_pc_mispred ), + .iu_ifu_pc_mispred_gate (iu_ifu_pc_mispred_gate ), + .iu_ifu_ret_vld (iu_ifu_ret_vld ), + .iu_ifu_ret_vld_gate (iu_ifu_ret_vld_gate ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .ras_cur_ret (ras_cur_ret ), + .ras_id_pred_tar_pc (ras_id_pred_tar_pc ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ) +); + + +// c. RAS Result +// &Force("input", "idu_ifu_x1"); @270 +// &Force("bus", "idu_ifu_x1", 31, 0); @271 +assign id_pred_ras_tar[31:0] = {id_pred_idpc[31:24], ras_id_pred_tar_pc[23:0]}; + +// &Force("nonport", "id_pred_inst0_32"); @277 +// &Force("nonport", "id_pred_ras_link_vld"); @278 +// &Force("input", "iu_ifu_ret_vld"); @279 +// &Force("input", "iu_ifu_ret_vld_gate"); @280 +// &Force("input", "iu_ifu_link_vld"); @281 +// &Force("input", "iu_ifu_link_vld_gate"); @282 +// &Force("input", "iu_ifu_ind_link_vld"); @283 +// &Force("input", "iu_ifu_pc_mispred"); @284 +// &Force("input", "iu_ifu_pc_mispred_gate"); @285 + +// d. RAS Stall FSM +parameter RAS_IDLE = 2'b00; +parameter RAS_RET = 2'b01; +parameter RAS_JALR = 2'b11; + +always @ (posedge id_ras_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ras_cur_st[1:0] <= RAS_IDLE; + else if(pcgen_id_pred_flush_vld | rtu_ifu_flush_fe) + ras_cur_st[1:0] <= RAS_IDLE; + else + ras_cur_st[1:0] <= ras_nxt_st[1:0]; +end + +// &CombBeg; @306 +always @( id_pred_ras_ind_link_vld + or iu_ifu_ret_vld + or iu_ifu_ind_link_vld + or ras_cur_st[1:0] + or id_pred_ras_ret_vld) +begin +case(ras_cur_st[1:0]) + RAS_IDLE: + if(id_pred_ras_ret_vld) + ras_nxt_st[1:0] = RAS_RET; + else if(id_pred_ras_ind_link_vld) + ras_nxt_st[1:0] = RAS_JALR; + else + ras_nxt_st[1:0] = RAS_IDLE; + RAS_RET: + if(iu_ifu_ret_vld) + ras_nxt_st[1:0] = RAS_IDLE; + else + ras_nxt_st[1:0] = RAS_RET; + RAS_JALR: + if(iu_ifu_ind_link_vld) + ras_nxt_st[1:0] = RAS_IDLE; + else + ras_nxt_st[1:0] = RAS_JALR; + default: + ras_nxt_st[1:0] = RAS_IDLE; +endcase +// &CombEnd; @328 +end + +assign ras_cur_ret = ras_cur_st[1:0] == RAS_RET; +assign ras_cur_jalr = ras_cur_st[1:0] == RAS_JALR; +assign id_pred_ret_stall = ras_cur_ret & id_pred_ras_ret_vld + | ras_cur_jalr; + +assign ras_pred_pc_update = id_pred_ras_ret_vld & ras_cur_st[1:0] == RAS_IDLE; +always @ (posedge id_ras_clk or negedge cpurst_b) +begin + if(~cpurst_b) + ras_pred_pc[31:0] <= 32'b0; + else if(ras_pred_pc_update) + ras_pred_pc[31:0] <= id_pred_ras_tar[31:0]; + else + ras_pred_pc[31:0] <= ras_pred_pc[31:0]; +end + +//------------------------------------------------ +// 6. ID Prediction Address Generation +// a. ID Prediction Change Flow +// b. IF Miss-Prediction Judgement +//------------------------------------------------ +assign id_pred_chgflw_vld0 = id_pred_br_taken0 | id_pred_ras_ret_vld0; +assign id_pred_chgflw_vld1 = id_pred_br_taken1 | id_pred_ras_ret_req1; +assign id_pred_chgflw_vld = id_pred_chgflw_vld0 | id_pred_chgflw_vld1; +assign id_pred_chgflw_tar[31:0] = id_pred_ras_ret_req ? id_pred_ras_tar[31:0] + : id_pred_br_tar[31:0]; + +// b. IF Miss-Prediction Judgement +assign btb_mis_pred = (id_pred_br_tar[31:0] + != pcgen_id_pred_btb_tar_pc[31:0] + | ~id_pred_chgflw_vld) & pcgen_id_pred_btb_tar_vld + & (ipack_id_pred_inst0_vld + | ipack_id_pred_inst1_vld); +// TODO: btb pc whole compare +// &Force("input", "pcgen_id_pred_btb_tar_pc"); @364 +// &Force("bus", "pcgen_id_pred_btb_tar_pc", 31, 0); @365 +//assign btb_mis_pred = ~id_pred_br_taken & pcgen_id_pred_btb_tar_vld +// & (ipack_id_pred_inst0_vld +// | ipack_id_pred_inst1_vld); + +assign id_pred_chgflw = (pcgen_id_pred_btb_tar_vld ? btb_mis_pred + : id_pred_br_taken) + ;// | id_pred_ras_ret_vld;// | delay_chgflw; +assign id_pred_chgflw_fin = id_pred_ras_ret_chgflw | delay_chgflw; +assign id_pred_chgflw_fin_tar1[31:0] = id_pred_chgflw_vld + ? id_pred_chgflw_tar[31:0] + : id_pred_nxt_pc[31:0]; +assign id_pred_chgflw_fin_tar[31:0] = delay_chgflw ? chgflw_pc[31:0] + : id_pred_ras_tar[31:0]; + +//------------------------------------------------ +// 7. Inst bkpt judgement +//------------------------------------------------ +assign id_pred_inst0_bkpt_pc[31:0] = ipack_id_pred_h0_vld ? id_pred_h0_pc[31:0] + : id_pred_idpc[31:0]; +assign id_pred_inst1_bkpt_pc[31:0] = {id_pred_idpc[31:2], 2'b10}; + +assign ifu_dtu_addr_vld0 = ipack_id_pred_inst0_vld; +assign ifu_dtu_data_vld0 = ipack_id_pred_inst0_vld & ~ipack_id_pred_inst0_expt; +assign ifu_dtu_exe_addr0[31:0] = id_pred_inst0_bkpt_pc[31:0]; +assign ifu_dtu_exe_data0[31:0] = ipack_id_pred_inst0[31:0]; + +assign ifu_dtu_addr_vld1 = ipack_id_pred_inst1_vld; +assign ifu_dtu_data_vld1 = ipack_id_pred_inst1_vld & ~ipack_id_pred_inst1_expt; +assign ifu_dtu_exe_addr1[31:0] = id_pred_inst1_bkpt_pc[31:0]; +assign ifu_dtu_exe_data1[31:0] = {16'b0, ipack_id_pred_inst1[15:0]}; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to pcgen +assign id_pred_pcgen_chgflw_vld = id_pred_chgflw_fin; +assign id_pred_pcgen_inst_vld = (ipack_id_pred_inst0_vld + | ipack_id_pred_inst1_vld) & ~ibuf_ipack_stall; +assign id_pred_pcgen_chgflw_pc[31:0] = id_pred_chgflw_fin_tar[31:0]; + +// Output to ipack +assign id_pred_ipack_chgflw_vld0 = id_pred_chgflw_vld0; + +// Output to ibuf +assign id_pred_ibuf_chgflw_vld0 = id_pred_chgflw_vld0; +assign id_pred_ibuf_br_taken0[1:0] = id_pred_br_rslt0[1:0]; +assign id_pred_ibuf_br_taken1[1:0] = id_pred_br_rslt1[1:0]; +assign id_pred_ibuf_halt_info0[`TDT_HINFO_WIDTH-1:0] = dtu_ifu_halt_info0[`TDT_HINFO_WIDTH-1:0]; +assign id_pred_ibuf_halt_info1[`TDT_HINFO_WIDTH-1:0] = dtu_ifu_halt_info1[`TDT_HINFO_WIDTH-1:0]; +assign id_pred_ipack_ret_stall = id_pred_ret_stall; +assign id_pred_ipack_delay_stall = id_pred_delay_br; +assign id_pred_ipack_mask = id_pred_delay_br1; + +// Output to ctrl +assign id_pred_ctrl_stall = id_pred_ret_stall | id_pred_delay_br | id_pred_delay_br1 | ibuf_pred_stall; + +// Output to top +assign pred_top_delay_chgflw = delay_chgflw; +assign pred_top_ras_st = ras_cur_st[0]; + +// &Force("bus", "pcgen_id_pred_ifpc", 31, 0); @427 +// Output to btb +assign id_pred_btb_upd_vld = id_pred_br_taken & ~btb_mis_pred + & ibuf_id_pred_hungry; +assign id_pred_btb_upd_vldg = id_pred_br_taken + & ibuf_id_pred_hungry; +assign id_pred_btb_mis_pred = btb_mis_pred; +assign id_pred_btb_mis_predg = pcgen_id_pred_btb_tar_vld + & (ipack_id_pred_inst0_vld + | ipack_id_pred_inst1_vld); +assign id_pred_btb_cur_pc[31:0] = ipack_id_pred_unalign ? {pcgen_id_pred_ifpc[31:2], 2'b0} + : {id_pred_idpc[31:2], 2'b0}; +assign id_pred_btb_tar_pc[31:0] = id_pred_br_tar[31:0]; +// &Force("input", "ibuf_id_pred_hungry"); @442 +// &Force("input", "pcgen_id_pred_ifpc"); @443 + +// Output to IU +assign ifu_iu_ex1_pc_pred[31:0] = ras_pred_pc[31:0]; + +// &ModuleEnd; @449 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ifetch.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ifetch.v new file mode 100644 index 0000000000000000000000000000000000000000..c2dd652ab32597a475bc9dbd792b58132eb00aa8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ifetch.v @@ -0,0 +1,757 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ifetch( + bmu_ifu_acc_err, + bmu_ifu_grant, + bmu_ifu_rdata, + bmu_ifu_trans_cmplt, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_ifu_lpmd_req, + cp0_ifu_srst_req, + cp0_yy_clk_en, + cp0_yy_mach_mode, + cpurst_b, + ctrl_ifetch_req_abort, + ctrl_ifetch_req_vld, + forever_cpuclk, + icache_top_abort, + icache_top_rd_vld, + icache_top_ref_st, + icache_top_uc_st, + ifetch_ctrl_inst_vld, + ifetch_ibuf_idle, + ifetch_ipack_acc_err, + ifetch_ipack_inst, + ifetch_ipack_inst_vld, + ifetch_ipack_inst_vld_gate, + ifetch_ipack_unalign, + ifetch_pcgen_addr, + ifetch_pcgen_data, + ifetch_pcgen_grant, + ifetch_pcgen_grant_dp, + ifetch_top_abt_st, + ifetch_top_cur_st, + ifetch_vec_acc_err, + ifetch_vec_cmplt, + ifetch_vec_grant, + ifetch_vec_idle, + ifetch_xx_not_busy, + ifu_bmu_acc_deny, + ifu_bmu_addr, + ifu_bmu_burst, + ifu_bmu_data_req, + ifu_bmu_prot, + ifu_bmu_req, + ifu_bmu_seq, + ifu_bmu_size, + ifu_cp0_icache_inv_done, + ifu_cp0_lpmd_ack, + ifu_cp0_srst_ack, + ifu_hpcp_icache_access, + ifu_hpcp_icache_miss, + ifu_pmp_addr, + ifu_pmp_machine_mode, + ifu_rtu_lockup_ack, + ifu_sysmap_pa, + pad_yy_icg_scan_en, + pcgen_ifetch_addr, + pcgen_ifetch_chgflw_vld, + pcgen_ifetch_ifpc, + pcgen_ifetch_seq_addr, + pmp_ifu_acc_deny, + rtu_ifu_lockup_mask, + rtu_ifu_lockup_req, + rtu_yy_xx_dbgon, + sysmap_ifu_flg, + vec_ifetch_data_fetch +); + +// &Ports; @24 +input bmu_ifu_acc_err; +input bmu_ifu_grant; +input [31:0] bmu_ifu_rdata; +input bmu_ifu_trans_cmplt; +input cp0_ifu_icache_en; +input [31:0] cp0_ifu_icache_inv_addr; +input cp0_ifu_icache_inv_req; +input cp0_ifu_icache_inv_type; +input cp0_ifu_icg_en; +input cp0_ifu_lpmd_req; +input cp0_ifu_srst_req; +input cp0_yy_clk_en; +input cp0_yy_mach_mode; +input cpurst_b; +input ctrl_ifetch_req_abort; +input ctrl_ifetch_req_vld; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input [31:0] pcgen_ifetch_addr; +input pcgen_ifetch_chgflw_vld; +input [31:0] pcgen_ifetch_ifpc; +input [31:0] pcgen_ifetch_seq_addr; +input pmp_ifu_acc_deny; +input rtu_ifu_lockup_mask; +input rtu_ifu_lockup_req; +input rtu_yy_xx_dbgon; +input [4 :0] sysmap_ifu_flg; +input vec_ifetch_data_fetch; +output icache_top_abort; +output icache_top_rd_vld; +output [1 :0] icache_top_ref_st; +output icache_top_uc_st; +output ifetch_ctrl_inst_vld; +output ifetch_ibuf_idle; +output ifetch_ipack_acc_err; +output [31:0] ifetch_ipack_inst; +output ifetch_ipack_inst_vld; +output ifetch_ipack_inst_vld_gate; +output ifetch_ipack_unalign; +output [31:0] ifetch_pcgen_addr; +output [31:0] ifetch_pcgen_data; +output ifetch_pcgen_grant; +output ifetch_pcgen_grant_dp; +output [1 :0] ifetch_top_abt_st; +output [2 :0] ifetch_top_cur_st; +output ifetch_vec_acc_err; +output ifetch_vec_cmplt; +output ifetch_vec_grant; +output ifetch_vec_idle; +output ifetch_xx_not_busy; +output ifu_bmu_acc_deny; +output [31:0] ifu_bmu_addr; +output [2 :0] ifu_bmu_burst; +output ifu_bmu_data_req; +output [3 :0] ifu_bmu_prot; +output ifu_bmu_req; +output ifu_bmu_seq; +output [1 :0] ifu_bmu_size; +output ifu_cp0_icache_inv_done; +output ifu_cp0_lpmd_ack; +output ifu_cp0_srst_ack; +output ifu_hpcp_icache_access; +output ifu_hpcp_icache_miss; +output [31:0] ifu_pmp_addr; +output ifu_pmp_machine_mode; +output ifu_rtu_lockup_ack; +output [31:0] ifu_sysmap_pa; + +// &Regs; @25 +reg [1 :0] abort_cur_st; +reg [1 :0] abort_nxt_st; +reg [2 :0] cur_st; +reg ibus_deny_reg; +reg ibus_unalign_reg; +reg [2 :0] nxt_st; + +// &Wires; @26 +wire bmu_ifu_acc_err; +wire bmu_ifu_grant; +wire [31:0] bmu_ifu_rdata; +wire bmu_ifu_trans_cmplt; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_ifu_lpmd_req; +wire cp0_ifu_srst_req; +wire cp0_yy_clk_en; +wire cp0_yy_mach_mode; +wire cpurst_b; +wire ctrl_ifetch_req_abort; +wire ctrl_ifetch_req_vld; +wire flop_out_bus; +wire forever_cpuclk; +wire ibus_abort_trig; +wire [31:0] ibus_data; +wire ibus_data_req_vld; +wire ibus_icache_cmplt; +wire [31:0] ibus_icache_data; +wire ibus_icache_error; +wire ibus_icache_grant; +wire ibus_icache_not_busy; +wire ibus_icache_uc_cmplt; +wire ibus_icache_unalign; +wire ibus_inst_data_req; +wire ibus_inst_req; +wire ibus_req; +wire [31:0] ibus_req_addr; +wire [2 :0] ibus_req_burst; +wire ibus_req_cmplt; +wire ibus_req_deny; +wire ibus_req_err; +wire [3 :0] ibus_req_prot; +wire ibus_req_seq; +wire [1 :0] ibus_req_size; +wire ibus_req_vld; +wire ibus_trans_abort; +wire ibusif_idle_st; +wire icache_ibus_acc_deny; +wire [31:0] icache_ibus_addr; +wire [2 :0] icache_ibus_burst; +wire icache_ibus_data_req; +wire [3 :0] icache_ibus_prot; +wire icache_ibus_req; +wire icache_ibus_seq; +wire [31:0] icache_ifetch_addr; +wire icache_ifetch_error; +wire icache_ifetch_grant; +wire icache_ifetch_idle; +wire [31:0] icache_ifetch_inst; +wire icache_ifetch_inst_vld; +wire icache_ifetch_inst_vld_gate; +wire icache_ifetch_mach_mode; +wire icache_ifetch_not_busy; +wire [31:0] icache_ifetch_rd_addr; +wire icache_ifetch_uc_sel; +wire icache_ifetch_unalign; +wire icache_ifetch_vec_data_cmplt; +wire icache_top_abort; +wire icache_top_rd_vld; +wire [1 :0] icache_top_ref_st; +wire icache_top_uc_st; +wire ifetch_cpuclk; +wire ifetch_ctrl_inst_vld; +wire ifetch_ibuf_idle; +wire ifetch_icg_en; +wire ifetch_inst_vld; +wire ifetch_ipack_acc_err; +wire [31:0] ifetch_ipack_inst; +wire ifetch_ipack_inst_vld; +wire ifetch_ipack_inst_vld_gate; +wire ifetch_ipack_unalign; +wire ifetch_outstanding; +wire [31:0] ifetch_pcgen_addr; +wire [31:0] ifetch_pcgen_data; +wire ifetch_pcgen_grant; +wire ifetch_pcgen_grant_dp; +wire [31:0] ifetch_req_addr; +wire ifetch_req_buf; +wire ifetch_req_ca; +wire [4 :0] ifetch_req_flg; +wire [3 :0] ifetch_req_prot; +wire [1 :0] ifetch_top_abt_st; +wire [2 :0] ifetch_top_cur_st; +wire ifetch_vec_acc_err; +wire ifetch_vec_cmplt; +wire ifetch_vec_grant; +wire ifetch_vec_idle; +wire ifetch_xx_not_busy; +wire ifu_bmu_acc_deny; +wire [31:0] ifu_bmu_addr; +wire [2 :0] ifu_bmu_burst; +wire ifu_bmu_data_req; +wire [3 :0] ifu_bmu_prot; +wire ifu_bmu_req; +wire ifu_bmu_seq; +wire [1 :0] ifu_bmu_size; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_lpmd_ack; +wire ifu_cp0_srst_ack; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire [31:0] ifu_pmp_addr; +wire ifu_pmp_machine_mode; +wire ifu_rtu_lockup_ack; +wire [31:0] ifu_sysmap_pa; +wire pad_yy_icg_scan_en; +wire [31:0] pcgen_ifetch_addr; +wire pcgen_ifetch_chgflw_vld; +wire [31:0] pcgen_ifetch_seq_addr; +wire pmp_ifu_acc_deny; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire rtu_yy_xx_dbgon; +wire [4 :0] sysmap_ifu_flg; +wire trans_abort; +wire vec_ifetch_data_fetch; + + +//========================================================== +// Instruction Fetch Module +// 1. Instance ICG cell +// 2. I-Fetch Common Signals +// 3. Instance I-Cache +// 4. I-Bus Access Interface +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG cell +//------------------------------------------------ +assign ifetch_icg_en = ibus_req_vld + | ~ibusif_idle_st; +// &Instance("gated_clk_cell", "x_ifu_ifetch_icg_cell"); @41 +gated_clk_cell x_ifu_ifetch_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (ifetch_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ifetch_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @42 +// .external_en (1'b0), @43 +// .global_en (cp0_yy_clk_en), @44 +// .module_en (cp0_ifu_icg_en), @45 +// .local_en (ifetch_icg_en), @46 +// .clk_out (ifetch_cpuclk) @47 +// ); @48 + +//------------------------------------------------ +// 2. I-Fetch Common Signals +//------------------------------------------------ +assign ifetch_req_addr[31:0] = pcgen_ifetch_addr[31:0]; +assign ifetch_req_flg[4:0] = sysmap_ifu_flg[4:0]; + +assign ifetch_req_ca = ifetch_req_flg[3]; +assign ifetch_req_buf = ifetch_req_flg[2]; +assign ifetch_req_prot[3:0] = {ifetch_req_ca, ifetch_req_buf, + cp0_yy_mach_mode, 1'b0}; +//------------------------------------------------ +// 3. Instance I-Cache +//------------------------------------------------ +// &Instance("pa_ifu_icache", "x_pa_ifu_icache"); @64 +pa_ifu_icache x_pa_ifu_icache ( + .bmu_ifu_acc_err (bmu_ifu_acc_err ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr ), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_ifetch_req_abort (ctrl_ifetch_req_abort ), + .ctrl_ifetch_req_vld (ctrl_ifetch_req_vld ), + .forever_cpuclk (forever_cpuclk ), + .ibus_icache_cmplt (ibus_icache_cmplt ), + .ibus_icache_data (ibus_icache_data ), + .ibus_icache_error (ibus_icache_error ), + .ibus_icache_grant (ibus_icache_grant ), + .ibus_icache_not_busy (ibus_icache_not_busy ), + .ibus_icache_uc_cmplt (ibus_icache_uc_cmplt ), + .ibus_icache_unalign (ibus_icache_unalign ), + .ibus_trans_abort (ibus_trans_abort ), + .icache_ibus_acc_deny (icache_ibus_acc_deny ), + .icache_ibus_addr (icache_ibus_addr ), + .icache_ibus_burst (icache_ibus_burst ), + .icache_ibus_data_req (icache_ibus_data_req ), + .icache_ibus_prot (icache_ibus_prot ), + .icache_ibus_req (icache_ibus_req ), + .icache_ibus_seq (icache_ibus_seq ), + .icache_ifetch_addr (icache_ifetch_addr ), + .icache_ifetch_error (icache_ifetch_error ), + .icache_ifetch_grant (icache_ifetch_grant ), + .icache_ifetch_idle (icache_ifetch_idle ), + .icache_ifetch_inst (icache_ifetch_inst ), + .icache_ifetch_inst_vld (icache_ifetch_inst_vld ), + .icache_ifetch_inst_vld_gate (icache_ifetch_inst_vld_gate ), + .icache_ifetch_mach_mode (icache_ifetch_mach_mode ), + .icache_ifetch_not_busy (icache_ifetch_not_busy ), + .icache_ifetch_rd_addr (icache_ifetch_rd_addr ), + .icache_ifetch_uc_sel (icache_ifetch_uc_sel ), + .icache_ifetch_unalign (icache_ifetch_unalign ), + .icache_ifetch_vec_data_cmplt (icache_ifetch_vec_data_cmplt), + .icache_top_abort (icache_top_abort ), + .icache_top_rd_vld (icache_top_rd_vld ), + .icache_top_ref_st (icache_top_ref_st ), + .icache_top_uc_st (icache_top_uc_st ), + .ifetch_outstanding (ifetch_outstanding ), + .ifetch_req_addr (ifetch_req_addr ), + .ifetch_req_ca (ifetch_req_ca ), + .ifetch_req_prot (ifetch_req_prot ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done ), + .ifu_hpcp_icache_access (ifu_hpcp_icache_access ), + .ifu_hpcp_icache_miss (ifu_hpcp_icache_miss ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_ifetch_chgflw_vld (pcgen_ifetch_chgflw_vld ), + .pcgen_ifetch_seq_addr (pcgen_ifetch_seq_addr ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .vec_ifetch_data_fetch (vec_ifetch_data_fetch ) +); + +assign ibus_req_vld = icache_ibus_req; +assign ibus_data_req_vld = icache_ibus_data_req; +assign ibus_req_addr[31:0] = icache_ibus_addr[31:0]; +assign ibus_req_prot[3:0] = icache_ibus_prot[3:0]; +assign ibus_req_size[1:0] = 2'b10; +assign ibus_req_seq = icache_ibus_seq; +assign ibus_req_burst[2:0] = icache_ibus_burst[2:0]; +assign ibus_req_deny = icache_ibus_acc_deny; + +//assign ibus_req_vld = cp0_ifu_icache_en ? icache_ibus_req +// : ctrl_ifetch_req_vld; +//assign ibus_req_addr[31:0] = cp0_ifu_icache_en ? icache_ibus_addr[31:0] +// : ifetch_req_addr[31:0]; +//assign ibus_req_size[1:0] = 2'b10; +//assign ibus_req_prot[3:0] = cp0_ifu_icache_en ? icache_ibus_prot[3:0] +// : ifetch_req_prot[3:0]; + +assign ibus_icache_grant = bmu_ifu_grant; +assign ibus_icache_cmplt = ibus_req_cmplt;// & ~rtu_yy_xx_dbgon; +assign ibus_icache_error = ibus_req_err | ibus_req_cmplt & ibus_deny_reg; +assign ibus_icache_data[31:0] = ibus_data[31:0]; +assign ibus_icache_unalign = ibus_unalign_reg; +assign ibus_icache_not_busy = cur_st[0]; +//------------------------------------------------ +// 4. I-Bus Access Interface +// a. I-Bus Interface FSM +// b. I-Bus Request Handshake +//------------------------------------------------ + +// a. I-Bus Interface FSM +// State Statement: +// IDLE: Default State, wait for ibus req +// WFG: Grant State, wait for i-bus grant +// WFC: Complete State, wait for i-bus cmplt +// ABT: Abort State, wait for useless i-bus cmplt +parameter IDLE = 3'b001, + WFG1 = 3'b010, + WFD1 = 3'b011, + WFD1WFG2 = 3'b000, + WFD1WFD2 = 3'b110; + +parameter ABORT_IDLE = 2'b00, + ABORT_VLD1 = 2'b10, + ABORT_VLD2 = 2'b11; + +assign flop_out_bus = 1'b1; + +assign ibus_data[31:0] = bmu_ifu_rdata[31:0]; +//{bmu_ifu_rdata[31:16], ibus_unalign_reg +// ? bmu_ifu_rdata[31:16] : bmu_ifu_rdata[15:0]}; + +// FSM Sequential Logic +always @(posedge ifetch_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + cur_st[2:0] <= IDLE; + else + cur_st[2:0] <= nxt_st[2:0]; +end + +// FSM Output Logic +// &CombBeg; @136 +always @( bmu_ifu_trans_cmplt + or bmu_ifu_acc_err + or ibus_req_vld + or flop_out_bus + or cur_st + or bmu_ifu_grant) +begin +case(cur_st) +IDLE: +begin + if(ibus_req_vld) + begin + if(bmu_ifu_grant) + nxt_st[2:0] = WFD1; + else + nxt_st[2:0] = WFG1; + end + else + nxt_st[2:0] = IDLE; +end +WFG1: +begin + if(bmu_ifu_grant) + nxt_st[2:0] = WFD1; + else + nxt_st[2:0] = WFG1; +end +WFD1: +begin + if(bmu_ifu_trans_cmplt) + begin + if(ibus_req_vld) + begin + if(bmu_ifu_grant) + nxt_st[2:0] = WFD1; + else + nxt_st[2:0] = WFG1; + end + else + nxt_st[2:0] = IDLE; + end + else if(ibus_req_vld & flop_out_bus) + begin //flop out bus can grant 2 outstanding inst fetch + if(bmu_ifu_grant) + nxt_st[2:0] = WFD1WFD2; + else + nxt_st[2:0] = WFD1WFG2; + end + else if(ibus_req_vld) + nxt_st[2:0] = WFD1WFG2; + else + nxt_st[2:0] = WFD1; +end +WFD1WFG2: +begin + if(bmu_ifu_trans_cmplt) + begin + if(bmu_ifu_grant) + nxt_st[2:0] = WFD1; + else if(bmu_ifu_acc_err) + nxt_st[2:0] = IDLE; + else + nxt_st[2:0] = WFG1; + end + else + begin + if(bmu_ifu_grant & flop_out_bus) + nxt_st[2:0] = WFD1WFD2; + else + nxt_st[2:0] = WFD1WFG2; + end +end +WFD1WFD2: +begin + if(bmu_ifu_trans_cmplt) + nxt_st[2:0] = WFD1; + else + nxt_st[2:0] = WFD1WFD2; +end +default: +begin + nxt_st[2:0] = IDLE; +end +endcase +// &CombEnd; @214 +end + +assign ibusif_idle_st = (cur_st[2:0] == IDLE); + +assign ibus_req_cmplt = ((cur_st[2:0] == WFD1) + | (cur_st[2:0] == WFD1WFG2) + | (cur_st[2:0] == WFD1WFD2) + ) & bmu_ifu_trans_cmplt + & ~ibus_trans_abort; +assign ibus_req_err = ((cur_st[2:0] == WFD1) + | (cur_st[2:0] == WFD1WFG2) + | (cur_st[2:0] == WFD1WFD2) + ) & bmu_ifu_acc_err; +assign ibus_inst_req = (cur_st[2:0] == IDLE) + & ibus_req_vld + | (cur_st[2:0] == WFG1) + | (cur_st[2:0] == WFD1) + & ibus_req_vld + | (cur_st[2:0] == WFD1WFG2); +assign ibus_inst_data_req = (cur_st[2:0] == IDLE) + & ibus_data_req_vld + | (cur_st[2:0] == WFG1) + | (cur_st[2:0] == WFD1) + & ibus_data_req_vld + | (cur_st[2:0] == WFD1WFG2); + +assign ifetch_outstanding = cur_st[2:0] == WFG1 | cur_st[2:0] == WFD1WFG2 | cur_st[2:0] == WFD1WFD2; + +assign trans_abort = icache_ifetch_uc_sel & ctrl_ifetch_req_abort; +assign ibus_icache_uc_cmplt = ((cur_st[2:0] == WFD1) + | (cur_st[2:0] == WFD1WFG2) + | (cur_st[2:0] == WFD1WFD2) + ) & bmu_ifu_trans_cmplt; + +always @(posedge ifetch_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ibus_deny_reg <= 1'b0; + else if(bmu_ifu_grant) + ibus_deny_reg <= ibus_req_deny; + else if(ibus_req_cmplt) + ibus_deny_reg <= 1'b0; +end +assign ibus_abort_trig = ((cur_st[2:0] == WFD1) + & ~bmu_ifu_trans_cmplt + | (cur_st[2:0] == WFG1) + | (cur_st[2:0] == WFD1WFG2) + & ~bmu_ifu_acc_err) + & trans_abort; + +//assign ibus_no_outstanding = (cur_st[2:0] == IDLE) +// | (cur_st[2:0] == WFG1) +// | (cur_st[2:0] == WFD1) +// & bmu_ifu_trans_cmplt +// | (cur_st[2:0] == WFD1WFG2) +// & bmu_ifu_trans_cmplt; +// +//assign ibus_prot_buf = ((cur_st[2:0] == IDLE) | (cur_st[2:0] == WFD1)) +// & ((nxt_st == WFG1) | (nxt_st == WFD1WFG2)); +// +//assign ibus_prot_buf_sel = (cur_st[2:0] == WFG1) | (cur_st[2:0] == WFD1WFG2); + + +//the abort SM +always @(posedge ifetch_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + abort_cur_st[1:0] <= ABORT_IDLE; + else + abort_cur_st[1:0] <= abort_nxt_st[1:0]; +end + +// &CombBeg; @290 +always @( cur_st[2:0] + or bmu_ifu_trans_cmplt + or bmu_ifu_acc_err + or abort_cur_st[1:0] + or ibus_abort_trig) +begin +case(abort_cur_st[1:0]) +ABORT_IDLE: +begin + if(ibus_abort_trig) + if(cur_st[2:0] == WFD1WFG2 & ~bmu_ifu_trans_cmplt) + abort_nxt_st[1:0] = ABORT_VLD2; + else + abort_nxt_st[1:0] = ABORT_VLD1; + else + abort_nxt_st[1:0] = ABORT_IDLE; +end +ABORT_VLD1: +begin + if(ibus_abort_trig) begin + if(cur_st[2:0] == WFD1WFG2 & ~bmu_ifu_trans_cmplt) + abort_nxt_st[1:0] = ABORT_VLD2; + else + abort_nxt_st[1:0] = ABORT_VLD1; + end + else if(bmu_ifu_trans_cmplt) + abort_nxt_st[1:0] = ABORT_IDLE; + else + abort_nxt_st[1:0] = ABORT_VLD1; +end +ABORT_VLD2: +begin + if(bmu_ifu_trans_cmplt) + if(bmu_ifu_acc_err) + abort_nxt_st[1:0] = ABORT_IDLE; + else + abort_nxt_st[1:0] = ABORT_VLD1; + else + abort_nxt_st[1:0] = ABORT_VLD2; +end +default: +begin + abort_nxt_st[1:0] = ABORT_IDLE; +end +endcase +// &CombEnd; @330 +end + +assign ibus_trans_abort = (abort_cur_st[1:0] != ABORT_IDLE); + +// b. I-Bus Request Handshake +assign ibus_req = ibus_inst_req; + +// 3. I-Bus Fetch Unalign +//When the requset address is not word aligned, only half of +//the word fed back will be creat into instruction buffer. +always @(posedge ifetch_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ibus_unalign_reg <= 1'b0; + else if(bmu_ifu_grant) + ibus_unalign_reg <= ibus_req_addr[1]; + else if(ibus_req_cmplt) + ibus_unalign_reg <= 1'b0; +end + +//========================================================== +// Rename for Output +//========================================================== + +// Output to I-Bus +assign ifu_bmu_req = ibus_req; +assign ifu_bmu_data_req = ibus_inst_data_req; +// Todo +assign ifu_bmu_seq = ibus_req_seq; +assign ifu_bmu_burst[2:0] = ibus_req_burst[2:0]; +assign ifu_bmu_acc_deny = ibus_req_deny; +assign ifu_bmu_addr[31:0] = {ibus_req_addr[31:2], 2'b0}; +assign ifu_bmu_size[1:0] = ibus_req_size[1:0]; +assign ifu_bmu_prot[3:0] = ibus_req_prot[3:0]; + +// Output to I-Buffer +// TODO: uncacheable +assign ifetch_inst_vld = icache_ifetch_inst_vld & ~rtu_yy_xx_dbgon + & ~rtu_ifu_lockup_mask; +assign ifetch_ipack_inst_vld = ifetch_inst_vld; +assign ifetch_ipack_inst_vld_gate = icache_ifetch_inst_vld_gate; +assign ifetch_ipack_acc_err = icache_ifetch_error; +assign ifetch_ipack_inst[31:0] = icache_ifetch_inst[31:0]; +assign ifetch_ipack_unalign = icache_ifetch_unalign; +assign ifetch_ctrl_inst_vld = ifetch_inst_vld; +assign ifetch_ibuf_idle = icache_ifetch_idle; +assign ifetch_vec_idle = icache_ifetch_idle & ibusif_idle_st; +assign ifetch_xx_not_busy = icache_ifetch_not_busy; +assign ifetch_pcgen_grant = icache_ifetch_grant; +assign ifetch_pcgen_data[31:0] = icache_ifetch_inst[31:0]; +assign ifetch_pcgen_addr[31:0] = icache_ifetch_addr[31:0]; +assign ifetch_vec_grant = icache_ifetch_grant; +assign ifetch_vec_cmplt = icache_ifetch_vec_data_cmplt; +assign ifetch_vec_acc_err = icache_ifetch_error; + +// Output to CP0 +assign ifu_cp0_lpmd_ack = cp0_ifu_lpmd_req & ibusif_idle_st & icache_ifetch_idle; +assign ifu_cp0_srst_ack = cp0_ifu_srst_req & ibusif_idle_st & icache_ifetch_idle; +assign ifu_rtu_lockup_ack = rtu_ifu_lockup_req & ibusif_idle_st & icache_ifetch_idle; + +//assign ifetch_inst_vld = (cp0_ifu_icache_en ? icache_ifetch_inst_vld +// : ibus_req_cmplt) +// & ~rtu_yy_xx_dbgon; +//assign ifetch_ipack_inst_vld = ifetch_inst_vld; +//assign ifetch_ipack_acc_err = cp0_ifu_icache_en ? icache_ifetch_error +// : ibus_req_err; +//assign ifetch_ipack_inst[31:0] = cp0_ifu_icache_en ? icache_ifetch_inst[31:0] +// : ibus_data[31:0]; +//assign ifetch_ipack_unalign = cp0_ifu_icache_en ? icache_ifetch_unalign +// : ibus_unalign_reg; +//assign ifetch_ctrl_inst_vld = ifetch_inst_vld; +// +//assign ifetch_pcgen_grant = cp0_ifu_icache_en ? icache_ifetch_grant +// : bmu_ifu_grant; +//assign ifetch_ibuf_idle = cp0_ifu_icache_en ? icache_ifetch_idle +// : ibusif_idle_st; +//assign ifetch_xx_not_busy = cp0_ifu_icache_en ? 1'b1 +// : ~ibus_busy; + +// Output to top +assign ifetch_top_cur_st[2:0] = cur_st[2:0]; +assign ifetch_top_abt_st[1:0] = abort_cur_st[1:0]; + +assign ifetch_pcgen_grant_dp = ctrl_ifetch_req_vld + | vec_ifetch_data_fetch + | ifetch_outstanding; + +// Output to PMP +assign ifu_pmp_addr[31:0] = icache_ifetch_rd_addr[31:0]; +assign ifu_pmp_machine_mode = icache_ifetch_mach_mode; +// &Force("input","pcgen_ifetch_ifpc"); @471 +// &Force("bus","pcgen_ifetch_ifpc",31,0); @472 + +// Output to Sysmap +assign ifu_sysmap_pa[31:0] = ifetch_req_addr[31:0]; + +// &ModuleEnd; @481 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack.v new file mode 100644 index 0000000000000000000000000000000000000000..dade6659aad3bb3e66660f651513afc155fa8024 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack.v @@ -0,0 +1,494 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ipack( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ibuf_ipack_stall, + id_pred_ipack_chgflw_vld0, + id_pred_ipack_delay_stall, + id_pred_ipack_mask, + id_pred_ipack_ret_stall, + idu_ifu_tail_vld, + ifetch_ipack_acc_err, + ifetch_ipack_inst, + ifetch_ipack_inst_vld, + ifetch_ipack_inst_vld_gate, + ifetch_ipack_unalign, + ipack_ibuf_acc_err, + ipack_ibuf_inst, + ipack_ibuf_inst_all, + ipack_ibuf_inst_empty, + ipack_ibuf_inst_full, + ipack_ibuf_inst_one, + ipack_ibuf_inst_one_raw, + ipack_ibuf_inst_two, + ipack_ibuf_inst_vld, + ipack_ibuf_inst_vld_raw, + ipack_id_pred_h0_create, + ipack_id_pred_h0_vld, + ipack_id_pred_inst0, + ipack_id_pred_inst0_expt, + ipack_id_pred_inst0_vld, + ipack_id_pred_inst1, + ipack_id_pred_inst1_expt, + ipack_id_pred_inst1_vld, + ipack_id_pred_new_vld, + ipack_id_pred_unalign, + ipack_pcgen_reissue, + ipack_pcgen_reissue_gate, + ipack_top_entry0_vld, + ipack_top_entry1_vld, + ipack_top_entry2_vld, + iu_ifu_tar_pc_vld, + pad_yy_icg_scan_en, + pcgen_ipack_chgflw_vld, + rtu_ifu_chgflw_vld, + rtu_ifu_flush_fe, + rtu_yy_xx_expt_vld, + rtu_yy_xx_tail_int_vld, + vec_ipack_inst_mask +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ibuf_ipack_stall; +input id_pred_ipack_chgflw_vld0; +input id_pred_ipack_delay_stall; +input id_pred_ipack_mask; +input id_pred_ipack_ret_stall; +input idu_ifu_tail_vld; +input ifetch_ipack_acc_err; +input [31:0] ifetch_ipack_inst; +input ifetch_ipack_inst_vld; +input ifetch_ipack_inst_vld_gate; +input ifetch_ipack_unalign; +input iu_ifu_tar_pc_vld; +input pad_yy_icg_scan_en; +input pcgen_ipack_chgflw_vld; +input rtu_ifu_chgflw_vld; +input rtu_ifu_flush_fe; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_tail_int_vld; +input vec_ipack_inst_mask; +output [2 :0] ipack_ibuf_acc_err; +output [47:0] ipack_ibuf_inst; +output ipack_ibuf_inst_all; +output ipack_ibuf_inst_empty; +output ipack_ibuf_inst_full; +output ipack_ibuf_inst_one; +output ipack_ibuf_inst_one_raw; +output ipack_ibuf_inst_two; +output ipack_ibuf_inst_vld; +output ipack_ibuf_inst_vld_raw; +output ipack_id_pred_h0_create; +output ipack_id_pred_h0_vld; +output [31:0] ipack_id_pred_inst0; +output ipack_id_pred_inst0_expt; +output ipack_id_pred_inst0_vld; +output [15:0] ipack_id_pred_inst1; +output ipack_id_pred_inst1_expt; +output ipack_id_pred_inst1_vld; +output ipack_id_pred_new_vld; +output ipack_id_pred_unalign; +output ipack_pcgen_reissue; +output ipack_pcgen_reissue_gate; +output ipack_top_entry0_vld; +output ipack_top_entry1_vld; +output ipack_top_entry2_vld; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry0_acc_err; +wire entry0_create_en; +wire entry0_create_icg_en; +wire [15:0] entry0_inst; +wire entry0_retire_en; +wire entry0_upd_acc_err; +wire [15:0] entry0_upd_inst; +wire entry0_vld; +wire entry1_acc_err; +wire entry1_create_en; +wire entry1_create_icg_en; +wire [15:0] entry1_inst; +wire entry1_retire_en; +wire entry1_upd_acc_err; +wire [15:0] entry1_upd_inst; +wire entry1_vld; +wire entry2_acc_err; +wire entry2_create_en; +wire entry2_create_icg_en; +wire [15:0] entry2_inst; +wire entry2_retire_en; +wire entry2_upd_acc_err; +wire [15:0] entry2_upd_inst; +wire entry2_vld; +wire forever_cpuclk; +wire h0_vld; +wire h1_16bit_vld; +wire h1_32bit_vld; +wire h2_16bit_vld; +wire h2_32bit_vld; +wire ibuf_ipack_stall; +wire id_pred_ipack_chgflw_vld0; +wire id_pred_ipack_delay_stall; +wire id_pred_ipack_mask; +wire id_pred_ipack_ret_stall; +wire idu_ifu_tail_vld; +wire ifetch_inst_vld; +wire ifetch_ipack_acc_err; +wire [31:0] ifetch_ipack_inst; +wire ifetch_ipack_inst_vld; +wire ifetch_ipack_inst_vld_gate; +wire ifetch_ipack_unalign; +wire ipack_acc_err0; +wire ipack_acc_err1; +wire ipack_acc_err2; +wire ipack_align_create; +wire ipack_all_vld; +wire ipack_buf_flush; +wire ipack_buf_stall; +wire ipack_cpuclk; +wire ipack_empty; +wire [31:0] ipack_first_inst; +wire ipack_first_vld; +wire ipack_full; +wire [2 :0] ipack_ibuf_acc_err; +wire [47:0] ipack_ibuf_inst; +wire ipack_ibuf_inst_all; +wire ipack_ibuf_inst_empty; +wire ipack_ibuf_inst_full; +wire ipack_ibuf_inst_one; +wire ipack_ibuf_inst_one_raw; +wire ipack_ibuf_inst_two; +wire ipack_ibuf_inst_vld; +wire ipack_ibuf_inst_vld_raw; +wire ipack_icg_en; +wire ipack_id_pred_h0_create; +wire ipack_id_pred_h0_vld; +wire [31:0] ipack_id_pred_inst0; +wire ipack_id_pred_inst0_expt; +wire ipack_id_pred_inst0_vld; +wire [15:0] ipack_id_pred_inst1; +wire ipack_id_pred_inst1_expt; +wire ipack_id_pred_inst1_vld; +wire ipack_id_pred_new_vld; +wire ipack_id_pred_unalign; +wire ipack_one_16bit_raw; +wire ipack_one_16bit_vld; +wire ipack_pcgen_reissue; +wire ipack_pcgen_reissue_gate; +wire [47:0] ipack_retire_inst; +wire ipack_retire_one; +wire ipack_retire_vld; +wire [15:0] ipack_secnd_inst; +wire ipack_secnd_vld; +wire ipack_top_entry0_vld; +wire ipack_top_entry1_vld; +wire ipack_top_entry2_vld; +wire iu_ifu_tar_pc_vld; +wire pad_yy_icg_scan_en; +wire pcgen_ipack_chgflw_vld; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_flush_fe; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_tail_int_vld; +wire vec_ipack_inst_mask; + + +//========================================================== +// Instruction Package Module +// 1. Instance ICG Cell +// 2. Instruction Package Buffer to ID stage +// 3. Generate Valid Instruction +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign ipack_icg_en = ifetch_ipack_inst_vld_gate + | ~ipack_empty; +// &Instance("gated_clk_cell", "x_pa_ifu_ipack_icg_cell"); @40 +gated_clk_cell x_pa_ifu_ipack_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (ipack_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ipack_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @41 +// .clk_out (ipack_cpuclk), @42 +// .external_en (1'b0), @43 +// .global_en (cp0_yy_clk_en), @44 +// .module_en (cp0_ifu_icg_en), @45 +// .local_en (ipack_icg_en) @46 +// ); @47 + +//------------------------------------------------ +// 2. Instruction Package Buffer Implementation +// a. Flush Condition +// b. Create Condition +// c. Retire Condition +// d. Instance Instruction Package Buffer Entry +//------------------------------------------------ + +// a. Flush Condition +assign ipack_buf_flush = rtu_ifu_flush_fe | iu_ifu_tar_pc_vld | rtu_yy_xx_expt_vld + | rtu_ifu_chgflw_vld | idu_ifu_tail_vld | rtu_yy_xx_tail_int_vld; +assign ifetch_inst_vld = ifetch_ipack_inst_vld & ~pcgen_ipack_chgflw_vld & ~vec_ipack_inst_mask & ~id_pred_ipack_mask; +// b. Create Condition +assign ipack_align_create = ifetch_inst_vld & ~ifetch_ipack_unalign; +//assign ipack_unalign_create = ifetch_inst_vld & ifetch_ipack_unalign; +assign ipack_buf_stall = id_pred_ipack_ret_stall | ibuf_ipack_stall + ; //| id_pred_ipack_delay_stall; + +assign entry0_create_en = (~entry1_vld & h2_32bit_vld + | ~h0_vld & h1_16bit_vld & h2_32bit_vld + | h0_vld & entry1_vld & h2_32bit_vld) + & ~id_pred_ipack_chgflw_vld0 + & ~ipack_buf_stall; +assign entry1_create_en = ipack_align_create + & ~((entry1_vld |h2_16bit_vld) & ipack_buf_stall) + & ~id_pred_ipack_delay_stall; +assign entry2_create_en = ifetch_inst_vld + & ~(entry2_vld & ipack_buf_stall) + & ~id_pred_ipack_delay_stall; +assign entry0_create_icg_en = ~entry1_vld & h2_32bit_vld + | ~h0_vld & h1_16bit_vld & h2_32bit_vld + | h0_vld & entry1_vld & h2_32bit_vld; +assign entry1_create_icg_en = ipack_align_create; +assign entry2_create_icg_en = ifetch_inst_vld; + +// create inst +assign entry0_upd_inst[15:0] = entry2_inst[15:0]; +assign entry1_upd_inst[15:0] = ifetch_ipack_inst[15:0]; +assign entry2_upd_inst[15:0] = ifetch_ipack_inst[31:16]; + +// create acc err +assign entry0_upd_acc_err = entry2_acc_err; +assign entry1_upd_acc_err = ifetch_ipack_acc_err; +assign entry2_upd_acc_err = ifetch_ipack_acc_err; + +// c. Retire Condition +assign entry0_retire_en = ~ipack_buf_stall & entry1_vld; +assign entry1_retire_en = ~ipack_buf_stall; +assign entry2_retire_en = ~ipack_buf_stall & ~id_pred_ipack_delay_stall; + +// d. Instance Instruction Package Buffer Entry +// &ConnRule(s/ipack_entry/entry0/); @100 +// &Instance("pa_ifu_ipack_entry","x_pa_ifu_ipack_entry0"); @101 +pa_ifu_ipack_entry x_pa_ifu_ipack_entry0 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ipack_buf_flush (ipack_buf_flush ), + .ipack_cpuclk (ipack_cpuclk ), + .ipack_entry_acc_err (entry0_acc_err ), + .ipack_entry_create_en (entry0_create_en ), + .ipack_entry_create_icg_en (entry0_create_icg_en ), + .ipack_entry_inst (entry0_inst ), + .ipack_entry_retire_en (entry0_retire_en ), + .ipack_entry_upd_acc_err (entry0_upd_acc_err ), + .ipack_entry_upd_inst (entry0_upd_inst ), + .ipack_entry_vld (entry0_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/ipack_entry/entry1/); @103 +// &Instance("pa_ifu_ipack_entry","x_pa_ifu_ipack_entry1"); @104 +pa_ifu_ipack_entry x_pa_ifu_ipack_entry1 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ipack_buf_flush (ipack_buf_flush ), + .ipack_cpuclk (ipack_cpuclk ), + .ipack_entry_acc_err (entry1_acc_err ), + .ipack_entry_create_en (entry1_create_en ), + .ipack_entry_create_icg_en (entry1_create_icg_en ), + .ipack_entry_inst (entry1_inst ), + .ipack_entry_retire_en (entry1_retire_en ), + .ipack_entry_upd_acc_err (entry1_upd_acc_err ), + .ipack_entry_upd_inst (entry1_upd_inst ), + .ipack_entry_vld (entry1_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +// &ConnRule(s/ipack_entry/entry2/); @106 +// &Instance("pa_ifu_ipack_entry","x_pa_ifu_ipack_entry2"); @107 +pa_ifu_ipack_entry x_pa_ifu_ipack_entry2 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ipack_buf_flush (ipack_buf_flush ), + .ipack_cpuclk (ipack_cpuclk ), + .ipack_entry_acc_err (entry2_acc_err ), + .ipack_entry_create_en (entry2_create_en ), + .ipack_entry_create_icg_en (entry2_create_icg_en ), + .ipack_entry_inst (entry2_inst ), + .ipack_entry_retire_en (entry2_retire_en ), + .ipack_entry_upd_acc_err (entry2_upd_acc_err ), + .ipack_entry_upd_inst (entry2_upd_inst ), + .ipack_entry_vld (entry2_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +//------------------------------------------------ +// 3. Generate Valid Instruction +// a. Instruction Length Judgement +// b. Valid Instruction Package +// c. Instruction Access Error for I-Buffer +//------------------------------------------------ + +// a. Instruction Length Judgement +assign h0_vld = entry0_vld & entry0_inst[1:0] == 2'b11; + +assign h1_16bit_vld = entry1_vld & entry1_inst[1:0] != 2'b11; +assign h1_32bit_vld = entry1_vld & entry1_inst[1:0] == 2'b11; + +assign h2_16bit_vld = entry2_vld & entry2_inst[1:0] != 2'b11; +assign h2_32bit_vld = entry2_vld & entry2_inst[1:0] == 2'b11 + & ~id_pred_ipack_chgflw_vld0; + +// b. Valid Instruction Package +// Generate Empty Statu for Prediction +assign ipack_empty = ~entry0_vld & ~entry1_vld & ~entry2_vld; +assign ipack_full = entry0_vld & entry1_vld & entry2_vld;// & entry2_inst[1:0] != 2'b11; + +// Generate First Valid Inst for Prediction +assign ipack_first_vld = entry1_vld | ~h0_vld & h2_16bit_vld; +assign ipack_first_inst[31:0] = entry0_vld ? {entry1_inst[15:0], entry0_inst[15:0]} + : entry1_vld ? {entry2_inst[15:0], entry1_inst[15:0]} + : {entry2_inst[15:0], entry2_inst[15:0]}; +// Generate Second Valid Inst for Prediction +assign ipack_secnd_vld = (h0_vld | h1_16bit_vld) & h2_16bit_vld; + //& ~id_pred_ipack_chgflw_vld0; +assign ipack_secnd_inst[15:0] = entry2_inst[15:0]; + +// Generate I-Pack Retire Number for I-Buffer +// 1 16-bit Inst Valid +assign ipack_one_16bit_vld = ~h0_vld & h1_16bit_vld & ~(h2_16bit_vld + & ~id_pred_ipack_chgflw_vld0 + & ~id_pred_ipack_delay_stall) + | ~entry1_vld & h2_16bit_vld; +assign ipack_one_16bit_raw = ~h0_vld & h1_16bit_vld & ~(h2_16bit_vld + & ~id_pred_ipack_chgflw_vld0) + | ~entry1_vld & h2_16bit_vld; + +//// 1 32-bit Inst Valid +//assign ipack_one_32bit_vld = ~h0_vld & h1_32bit_vld & entry2_vld +// | h0_vld & entry1_vld & h2_32bit_vld; +// +//// 2 16-bit Inst Valid +//assign ipack_two_16bit_vld = ~h0_vld & h1_16bit_vld & h2_16bit_vld; + +// 1 16-bit and 1 32-bit Inst Valid +assign ipack_all_vld = h0_vld & entry1_vld & h2_16bit_vld + & ~id_pred_ipack_chgflw_vld0 + & ~id_pred_ipack_delay_stall; + +//assign ipack_entry_all_vld = h0_vld & entry1_vld & h2_16bit_vld; + +// Retire Number for I-Buffer +assign ipack_retire_vld = entry1_vld | h2_16bit_vld; +assign ipack_retire_one = ipack_one_16bit_vld; +//assign ipack_retire_two = ipack_one_32bit_vld | ipack_two_16bit_vld; + +// Retire Inst for I-Buffer +assign ipack_retire_inst[47:0] = {entry2_inst[15:0], ipack_first_inst[31:0]}; + +// c. Instruction Access Error for I-Buffer +assign ipack_acc_err0 = ~h0_vld & h1_16bit_vld & entry1_acc_err + | ~h0_vld & h1_32bit_vld & entry1_acc_err + | ~entry1_vld & h2_16bit_vld & entry2_acc_err + | h0_vld & entry1_vld & entry0_acc_err; +assign ipack_acc_err1 = ~h0_vld & h1_32bit_vld & entry2_vld + & entry2_acc_err + | ~h0_vld & h1_16bit_vld & h2_16bit_vld + & entry2_acc_err + | h0_vld & entry1_vld & entry1_acc_err; +assign ipack_acc_err2 = h0_vld & entry1_vld & h2_16bit_vld + & entry2_acc_err; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to id pred +assign ipack_id_pred_inst0_vld = ipack_first_vld;// & ~ibuf_ipack_stall; +assign ipack_id_pred_inst0[31:0] = ipack_first_inst[31:0]; +assign ipack_id_pred_inst0_expt = ipack_acc_err0 + | ~h0_vld & h1_32bit_vld & entry2_vld & entry2_acc_err + | h0_vld & entry1_vld & entry1_acc_err; + +assign ipack_id_pred_inst1_vld = ipack_secnd_vld;// & ~ibuf_ipack_stall; +assign ipack_id_pred_inst1[15:0] = ipack_secnd_inst[15:0]; +assign ipack_id_pred_inst1_expt = ipack_acc_err2 + | ~h0_vld & h1_16bit_vld & h2_16bit_vld & entry2_acc_err; + +assign ipack_id_pred_h0_create = entry0_create_en; +assign ipack_id_pred_h0_vld = h0_vld; +assign ipack_id_pred_unalign = ~entry1_vld & h2_16bit_vld; +//assign ipack_id_pred_inst_full = ipack_full; + +assign ipack_id_pred_new_vld = ifetch_ipack_inst_vld; + +// Output to ibuf +assign ipack_ibuf_inst_vld = ipack_retire_vld & ~ipack_buf_stall; +assign ipack_ibuf_inst_vld_raw = ipack_retire_vld; +assign ipack_ibuf_inst_one = ipack_retire_one; +assign ipack_ibuf_inst_one_raw = ipack_one_16bit_raw; +assign ipack_ibuf_inst_two = ipack_secnd_vld + & ~id_pred_ipack_chgflw_vld0 + & ~id_pred_ipack_delay_stall; +assign ipack_ibuf_inst_all = ipack_all_vld; +//assign ipack_ibuf_first_16 = ~h0_vld & h1_16bit_vld; +assign ipack_ibuf_inst[47:0] = ipack_retire_inst[47:0]; +assign ipack_ibuf_acc_err[2:0] = {ipack_acc_err2,ipack_acc_err1,ipack_acc_err0}; +assign ipack_ibuf_inst_empty = ipack_empty; +assign ipack_ibuf_inst_full = ipack_full; +//assign ipack_ibuf_entry_all = ipack_entry_all_vld; + +assign ipack_pcgen_reissue = ibuf_ipack_stall & ifetch_ipack_inst_vld; +assign ipack_pcgen_reissue_gate = ibuf_ipack_stall; + +// Output to top +assign ipack_top_entry0_vld = entry0_vld; +assign ipack_top_entry1_vld = entry1_vld; +assign ipack_top_entry2_vld = entry2_vld; + + +// &ModuleEnd; @252 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..d00fbe57ec49d99637822d7034e8454ca2988a6e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ipack_entry.v @@ -0,0 +1,160 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ipack_entry( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ipack_buf_flush, + ipack_cpuclk, + ipack_entry_acc_err, + ipack_entry_create_en, + ipack_entry_create_icg_en, + ipack_entry_inst, + ipack_entry_retire_en, + ipack_entry_upd_acc_err, + ipack_entry_upd_inst, + ipack_entry_vld, + pad_yy_icg_scan_en +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ipack_buf_flush; +input ipack_cpuclk; +input ipack_entry_create_en; +input ipack_entry_create_icg_en; +input ipack_entry_retire_en; +input ipack_entry_upd_acc_err; +input [15:0] ipack_entry_upd_inst; +input pad_yy_icg_scan_en; +output ipack_entry_acc_err; +output [15:0] ipack_entry_inst; +output ipack_entry_vld; + +// &Regs; @25 +reg entry_acc_err; +reg [15:0] entry_inst; +reg entry_vld; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry_cpuclk; +wire entry_icg_en; +wire forever_cpuclk; +wire ipack_buf_flush; +wire ipack_cpuclk; +wire ipack_entry_acc_err; +wire ipack_entry_create_en; +wire ipack_entry_create_icg_en; +wire [15:0] ipack_entry_inst; +wire ipack_entry_retire_en; +wire ipack_entry_upd_acc_err; +wire [15:0] ipack_entry_upd_inst; +wire ipack_entry_vld; +wire pad_yy_icg_scan_en; + + +//========================================================== +// Instruction Package Buffer Entry Module +// 1. Instance ICG cell +// 2. Entry Content +//========================================================== + +//------------------------------------------------ +// 1. Instace ICG cell +//------------------------------------------------ +assign entry_icg_en = ipack_entry_create_icg_en; +// &Instance("gated_clk_cell", "x_ipack_data_icg_cell"); @38 +gated_clk_cell x_ipack_data_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (entry_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (entry_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @39 +// .external_en (1'b0), @40 +// .global_en (cp0_yy_clk_en), @41 +// .module_en (cp0_ifu_icg_en), @42 +// .local_en (entry_icg_en), @43 +// .clk_out (entry_cpuclk)); @44 + +//------------------------------------------------ +// 2. Entry Content +// a. Entry Valid Signal +// b. Entry Instruction +//------------------------------------------------ +// a. Entry Valid Signal +always @(posedge ipack_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_vld <= 1'b0; + else if(ipack_buf_flush) + entry_vld <= 1'b0; + else if(ipack_entry_create_en) + entry_vld <= 1'b1; + else if(ipack_entry_retire_en) + entry_vld <= 1'b0; + else + entry_vld <= entry_vld; +end + +// b. Entry Instruction +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_inst[15:0] <= 16'b0; + else if(ipack_entry_create_en) + entry_inst[15:0] <= ipack_entry_upd_inst[15:0]; + else + entry_inst[15:0] <= entry_inst[15:0]; +end + +//========================================================== +// Instruction Bus Access Error +//========================================================== +always @(posedge entry_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + entry_acc_err <= 1'b0; + else if(ipack_entry_create_en) + entry_acc_err <= ipack_entry_upd_acc_err; + else + entry_acc_err <= entry_acc_err; +end + +//========================================================== +// Rename for Output +//========================================================== + +assign ipack_entry_vld = entry_vld; +assign ipack_entry_inst[15:0] = entry_inst[15:0]; +assign ipack_entry_acc_err = entry_acc_err; + +// &ModuleEnd; @98 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pcgen.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pcgen.v new file mode 100644 index 0000000000000000000000000000000000000000..9f228c85a1e8e87c34b51928e429ca6d5e7e4125 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pcgen.v @@ -0,0 +1,481 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_pcgen( + btb_pcgen_tar_pc, + btb_xx_chgflw_vld, + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + ctrl_pcgen_inst_vld, + ctrl_pcgen_pipedown, + forever_cpuclk, + id_pred_pcgen_chgflw_pc, + id_pred_pcgen_chgflw_vld, + id_pred_pcgen_inst_vld, + ifetch_pcgen_addr, + ifetch_pcgen_data, + ifetch_pcgen_grant, + ifetch_pcgen_grant_dp, + ifetch_xx_not_busy, + ifu_idu_chgflw_flush, + ifu_iu_chgflw_pc, + ifu_iu_chgflw_vld, + ipack_pcgen_reissue, + ipack_pcgen_reissue_gate, + iu_ifu_tar_pc, + iu_ifu_tar_pc_vld, + iu_ifu_tar_pc_vld_gate, + pad_yy_icg_scan_en, + pcgen_btb_addr, + pcgen_btb_pc, + pcgen_ctrl_chgflw_vld, + pcgen_ibuf_chgflw_vld, + pcgen_id_pred_btb_tar_pc, + pcgen_id_pred_btb_tar_vld, + pcgen_id_pred_flush_vld, + pcgen_id_pred_idpc, + pcgen_id_pred_ifpc, + pcgen_ifetch_addr, + pcgen_ifetch_chgflw_vld, + pcgen_ifetch_ifpc, + pcgen_ifetch_seq_addr, + pcgen_ipack_chgflw_vld, + pcgen_top_btb_tar_vld, + pcgen_top_buf_chgflw, + rtu_ifu_chgflw_pc, + rtu_ifu_chgflw_vld, + rtu_ifu_flush_fe, + sysio_ifu_rst_addr, + vec_pcgen_chgflw_vld, + vec_pcgen_idle, + vec_pcgen_inst_fetch, + vec_pcgen_iu_chgflw, + vec_pcgen_pc_flop, + vec_pcgen_rst_vld, + vec_pcgen_tar_pc +); + +// &Ports; @24 +input [31:0] btb_pcgen_tar_pc; +input btb_xx_chgflw_vld; +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input ctrl_pcgen_inst_vld; +input ctrl_pcgen_pipedown; +input forever_cpuclk; +input [31:0] id_pred_pcgen_chgflw_pc; +input id_pred_pcgen_chgflw_vld; +input id_pred_pcgen_inst_vld; +input [31:0] ifetch_pcgen_addr; +input [31:0] ifetch_pcgen_data; +input ifetch_pcgen_grant; +input ifetch_pcgen_grant_dp; +input ifetch_xx_not_busy; +input ipack_pcgen_reissue; +input ipack_pcgen_reissue_gate; +input [31:0] iu_ifu_tar_pc; +input iu_ifu_tar_pc_vld; +input iu_ifu_tar_pc_vld_gate; +input pad_yy_icg_scan_en; +input [31:0] rtu_ifu_chgflw_pc; +input rtu_ifu_chgflw_vld; +input rtu_ifu_flush_fe; +input [31:0] sysio_ifu_rst_addr; +input vec_pcgen_chgflw_vld; +input vec_pcgen_idle; +input vec_pcgen_inst_fetch; +input vec_pcgen_iu_chgflw; +input vec_pcgen_pc_flop; +input vec_pcgen_rst_vld; +input [31:0] vec_pcgen_tar_pc; +output ifu_idu_chgflw_flush; +output [31:0] ifu_iu_chgflw_pc; +output ifu_iu_chgflw_vld; +output [31:0] pcgen_btb_addr; +output [31:0] pcgen_btb_pc; +output pcgen_ctrl_chgflw_vld; +output pcgen_ibuf_chgflw_vld; +output [31:0] pcgen_id_pred_btb_tar_pc; +output pcgen_id_pred_btb_tar_vld; +output pcgen_id_pred_flush_vld; +output [31:0] pcgen_id_pred_idpc; +output [31:0] pcgen_id_pred_ifpc; +output [31:0] pcgen_ifetch_addr; +output pcgen_ifetch_chgflw_vld; +output [31:0] pcgen_ifetch_ifpc; +output [31:0] pcgen_ifetch_seq_addr; +output pcgen_ipack_chgflw_vld; +output pcgen_top_btb_tar_vld; +output pcgen_top_buf_chgflw; + +// &Regs; @25 +reg [31:0] btb_tar_pc; +reg btb_tar_vld; +reg [31:0] pcgen_addr; +reg pcgen_buf_chgflw; +reg [31:0] pcgen_delay_pc; +reg [31:0] pcgen_idpc; +reg [31:0] pcgen_ifpc; +reg [31:0] pcgen_pc; + +// &Wires; @26 +wire btb_chgflw_vld; +wire [31:0] btb_pcgen_tar_pc; +wire btb_tar_clk; +wire btb_tar_icg_en; +wire btb_xx_chgflw_vld; +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire ctrl_pcgen_inst_vld; +wire ctrl_pcgen_pipedown; +wire forever_cpuclk; +wire [31:0] id_pred_pcgen_chgflw_pc; +wire id_pred_pcgen_chgflw_vld; +wire id_pred_pcgen_inst_vld; +wire [31:0] ifetch_pcgen_addr; +wire [31:0] ifetch_pcgen_data; +wire ifetch_pcgen_grant; +wire ifetch_pcgen_grant_dp; +wire ifetch_xx_not_busy; +wire ifpc_updt_en; +wire ifu_idu_chgflw_flush; +wire [31:0] ifu_iu_chgflw_pc; +wire ifu_iu_chgflw_vld; +wire ipack_pcgen_reissue; +wire ipack_pcgen_reissue_gate; +wire [31:0] iu_ifu_tar_pc; +wire iu_ifu_tar_pc_vld; +wire iu_ifu_tar_pc_vld_gate; +wire pad_yy_icg_scan_en; +wire [31:0] pcgen_addr_inc; +wire [31:0] pcgen_btb_addr; +wire [31:0] pcgen_btb_pc; +wire pcgen_chgflw_vld; +wire pcgen_chgflw_vld_gate; +wire pcgen_cpuclk; +wire pcgen_ctrl_chgflw_vld; +wire [31:0] pcgen_fetch_pc; +wire pcgen_flush_vld; +wire pcgen_ibuf_chgflw_vld; +wire pcgen_icg_en; +wire [31:0] pcgen_id_pred_btb_tar_pc; +wire pcgen_id_pred_btb_tar_vld; +wire pcgen_id_pred_flush_vld; +wire [31:0] pcgen_id_pred_idpc; +wire [31:0] pcgen_id_pred_ifpc; +wire pcgen_idpc_clk; +wire [31:0] pcgen_ifetch_addr; +wire pcgen_ifetch_chgflw_vld; +wire [31:0] pcgen_ifetch_ifpc; +wire [31:0] pcgen_ifetch_seq_addr; +wire pcgen_ipack_chgflw_vld; +wire pcgen_top_btb_tar_vld; +wire pcgen_top_buf_chgflw; +wire [31:0] rtu_ifu_chgflw_pc; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_flush_fe; +wire [31:0] sysio_ifu_rst_addr; +wire vec_pcgen_chgflw_vld; +wire vec_pcgen_inst_fetch; +wire vec_pcgen_iu_chgflw; +wire vec_pcgen_pc_flop; +wire vec_pcgen_rst_vld; +wire [31:0] vec_pcgen_tar_pc; + + +//========================================================== +// PC Generator Module +// 1. ICG Instance +// 2. Judge the priority of PC sources +// 3. IF PC Maintain +// 4. ID PC Maintain +//========================================================== + +//------------------------------------------------ +// 1. ICG Instance +//------------------------------------------------ +assign pcgen_icg_en = pcgen_chgflw_vld_gate + | ifetch_pcgen_grant_dp + | pcgen_buf_chgflw + | ipack_pcgen_reissue_gate + | vec_pcgen_rst_vld + | vec_pcgen_pc_flop; +// &Instance("gated_clk_cell", "x_ifu_pcgen_icg_cell"); @45 +gated_clk_cell x_ifu_pcgen_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (pcgen_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (pcgen_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @46 +// .external_en (1'b0), @47 +// .global_en (cp0_yy_clk_en), @48 +// .module_en (cp0_ifu_icg_en), @49 +// .local_en (pcgen_icg_en), @50 +// .clk_out (pcgen_cpuclk) @51 +// ); @52 + +assign btb_tar_icg_en = btb_tar_vld | btb_xx_chgflw_vld; +// &Instance("gated_clk_cell", "x_ifu_pcgen_btb_tar_icg_cell"); @55 +gated_clk_cell x_ifu_pcgen_btb_tar_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (btb_tar_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (btb_tar_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @56 +// .external_en (1'b0), @57 +// .global_en (cp0_yy_clk_en), @58 +// .module_en (cp0_ifu_icg_en), @59 +// .local_en (btb_tar_icg_en), @60 +// .clk_out (btb_tar_clk) @61 +// ); @62 + +// &Instance("gated_clk_cell", "x_ifu_pcgen_idpc_icg_cell"); @64 +gated_clk_cell x_ifu_pcgen_idpc_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (pcgen_idpc_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ctrl_pcgen_inst_vld), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @65 +// .external_en (1'b0), @66 +// .global_en (cp0_yy_clk_en), @67 +// .module_en (cp0_ifu_icg_en), @68 +// .local_en (ctrl_pcgen_inst_vld), @69 +// .clk_out (pcgen_idpc_clk) @70 +// ); @71 + +//------------------------------------------------ +// 2. Judge the priority of PC sources +// HAD > Vector > BJU > RAS > BHT > BTB > Inc +// Todo: Parallel Case? +//------------------------------------------------ +// &CombBeg; @78 +always @( vec_pcgen_tar_pc[31:0] + or iu_ifu_tar_pc[31:0] + or rtu_ifu_chgflw_pc[31:0] + or vec_pcgen_chgflw_vld + or rtu_ifu_chgflw_vld) +begin + if(vec_pcgen_chgflw_vld) + pcgen_delay_pc[31:0] = vec_pcgen_tar_pc[31:0]; + else if(rtu_ifu_chgflw_vld) + pcgen_delay_pc[31:0] = rtu_ifu_chgflw_pc[31:0]; + else// if(iu_ifu_tar_pc_vld) + pcgen_delay_pc[31:0] = iu_ifu_tar_pc[31:0]; +// &CombEnd; @85 +end + +// &CombBeg; @87 +always @( id_pred_pcgen_chgflw_pc[31:0] + or id_pred_pcgen_chgflw_vld + or pcgen_addr[31:0] + or btb_pcgen_tar_pc[31:0] + or pcgen_ifpc[31:0] + or pcgen_buf_chgflw + or btb_xx_chgflw_vld) +begin + if(pcgen_buf_chgflw) + pcgen_pc[31:0] = pcgen_ifpc[31:0]; + else if(id_pred_pcgen_chgflw_vld) + pcgen_pc[31:0] = id_pred_pcgen_chgflw_pc[31:0]; + else if(btb_xx_chgflw_vld) + pcgen_pc[31:0] = btb_pcgen_tar_pc[31:0]; + else + pcgen_pc[31:0] = pcgen_addr[31:0]; +// &CombEnd; @96 +end + +assign pcgen_flush_vld = rtu_ifu_chgflw_vld + | vec_pcgen_chgflw_vld + | iu_ifu_tar_pc_vld; +assign pcgen_chgflw_vld = pcgen_flush_vld + | id_pred_pcgen_chgflw_vld + | btb_xx_chgflw_vld; +assign pcgen_chgflw_vld_gate = rtu_ifu_chgflw_vld + | vec_pcgen_chgflw_vld + | iu_ifu_tar_pc_vld_gate + | id_pred_pcgen_chgflw_vld + | btb_xx_chgflw_vld; + +always @ (posedge pcgen_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + pcgen_addr[31:0] <= 32'b0; + else if(vec_pcgen_rst_vld) + pcgen_addr[31:0] <= sysio_ifu_rst_addr[31:0]; + else if(pcgen_chgflw_vld & ~ifetch_pcgen_grant & ifetch_xx_not_busy) + pcgen_addr[31:0] <= pcgen_pc[31:0]; + else if(vec_pcgen_pc_flop) + pcgen_addr[31:0] <= ifetch_pcgen_data[31:0]; + else if(ipack_pcgen_reissue) + pcgen_addr[31:0] <= ifetch_pcgen_addr[31:0]; + else if(pcgen_buf_chgflw & ~ifetch_pcgen_grant & ifetch_xx_not_busy) + pcgen_addr[31:0] <= pcgen_ifpc[31:0]; + else if(ifetch_pcgen_grant) + pcgen_addr[31:0] <= pcgen_addr_inc[31:0]; + else + pcgen_addr[31:0] <= pcgen_addr[31:0]; +end + +assign pcgen_addr_inc[31:0] = {pcgen_pc[31:2], 2'b0} + 32'h4; + +assign pcgen_fetch_pc[31:0] = ifetch_xx_not_busy ? pcgen_pc[31:0] + : pcgen_addr[31:0]; +//assign pcgen_fetch_pc[31:0] = pcgen_pc[31:0]; + +//------------------------------------------------ +// 3. IF PC Maintain +//------------------------------------------------ +always @ (posedge pcgen_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + pcgen_buf_chgflw <= 1'b0; + else if(ifpc_updt_en)// & ~ifetch_xx_not_busy) + pcgen_buf_chgflw <= 1'b1; + else if(ifetch_xx_not_busy & pcgen_buf_chgflw) + pcgen_buf_chgflw <= 1'b0; +end + +assign ifpc_updt_en = pcgen_flush_vld + | id_pred_pcgen_chgflw_vld & ~ifetch_xx_not_busy; +always @ (posedge pcgen_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + pcgen_ifpc[31:0] <= 32'b0; + else if(pcgen_flush_vld) + pcgen_ifpc[31:0] <= pcgen_delay_pc[31:0]; + else if(ifpc_updt_en)// & ~ifetch_xx_not_busy) + pcgen_ifpc[31:0] <= pcgen_pc[31:0]; + else if(ifetch_pcgen_grant) + pcgen_ifpc[31:0] <= pcgen_pc[31:0]; + else + pcgen_ifpc[31:0] <= pcgen_ifpc[31:0]; +end + +assign pcgen_ifetch_ifpc[31:0] = pcgen_ifpc[31:0]; + +//------------------------------------------------ +// 4. ID PC Maintain +// Todo: Reduce Resources +//------------------------------------------------ +always @ (posedge pcgen_idpc_clk or negedge cpurst_b) +begin + if(~cpurst_b) + pcgen_idpc[31:0] <= 32'b0; + else if(ctrl_pcgen_pipedown) + pcgen_idpc[31:0] <= pcgen_ifpc[31:0]; + else + pcgen_idpc[31:0] <= pcgen_idpc[31:0]; +end + +//------------------------------------------------ +// 5. BTB Target PC +//------------------------------------------------ +assign btb_chgflw_vld = ~pcgen_flush_vld & ~rtu_ifu_flush_fe + & ~id_pred_pcgen_chgflw_vld & ~pcgen_buf_chgflw + & btb_xx_chgflw_vld; +always @ (posedge btb_tar_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + btb_tar_vld <= 1'b0; + btb_tar_pc[31:0] <= 32'b0; + end + else if(pcgen_flush_vld | id_pred_pcgen_chgflw_vld | rtu_ifu_flush_fe) + begin + btb_tar_vld <= 1'b0; + btb_tar_pc[31:0] <= btb_tar_pc[31:0]; + end + else if(btb_chgflw_vld) + begin + btb_tar_vld <= 1'b1; + btb_tar_pc[31:0] <= btb_pcgen_tar_pc[31:0]; + end + else if(btb_tar_vld & id_pred_pcgen_inst_vld) + begin + btb_tar_vld <= 1'b0; + btb_tar_pc[31:0] <= btb_tar_pc[31:0]; + end +end + +//========================================================== +// Rename for Output +//========================================================== + +// Output to ifetch +assign pcgen_ifetch_addr[31:0] = pcgen_fetch_pc[31:0]; +assign pcgen_ifetch_seq_addr[31:0] = pcgen_addr[31:0]; +assign pcgen_ifetch_chgflw_vld = pcgen_buf_chgflw + | id_pred_pcgen_chgflw_vld + | btb_xx_chgflw_vld; + +// Output to ctrl +assign pcgen_ctrl_chgflw_vld = pcgen_flush_vld | pcgen_buf_chgflw | id_pred_pcgen_chgflw_vld; + +// Output to BTB +assign pcgen_btb_pc[31:0] = pcgen_fetch_pc[31:0]; +assign pcgen_btb_addr[31:0] = pcgen_addr[31:0]; + +// Output to ipack +assign pcgen_ipack_chgflw_vld = pcgen_flush_vld | pcgen_buf_chgflw | id_pred_pcgen_chgflw_vld; + +// Output to ibuf +assign pcgen_ibuf_chgflw_vld = pcgen_flush_vld; + +// Output to top +assign pcgen_top_buf_chgflw = pcgen_buf_chgflw; +assign pcgen_top_btb_tar_vld = btb_tar_vld; + +// Output to ID Prediction +assign pcgen_id_pred_ifpc[31:0] = pcgen_ifpc[31:0]; +assign pcgen_id_pred_idpc[31:0] = pcgen_idpc[31:0]; +assign pcgen_id_pred_btb_tar_vld = btb_tar_vld; +assign pcgen_id_pred_btb_tar_pc[31:0] = btb_tar_pc[31:0]; +assign pcgen_id_pred_flush_vld = pcgen_flush_vld; + +// Output to IDU +assign ifu_idu_chgflw_flush = iu_ifu_tar_pc_vld; +//assign ifu_idu_id_pc[31:0] = pcgen_idpc[31:0]; + +assign ifu_iu_chgflw_vld = rtu_ifu_chgflw_vld + | vec_pcgen_iu_chgflw; +assign ifu_iu_chgflw_pc[31:0] = vec_pcgen_inst_fetch ? pcgen_addr[31:0] + : pcgen_delay_pc[31:0]; + +// &Force("input", "vec_pcgen_idle"); @259 +// &Force("nonport", "rst_done"); @261 + +// &ModuleEnd; @291 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pre_decd.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pre_decd.v new file mode 100644 index 0000000000000000000000000000000000000000..e8406ebed1ac38c0fc7b0880c22797d06bf8dc1a --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_pre_decd.v @@ -0,0 +1,232 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_pre_decd( + id_pred_br_vld0, + id_pred_br_vld1, + id_pred_br_vld1_raw, + id_pred_imm0, + id_pred_imm1, + id_pred_ind_link_vld0, + id_pred_ind_link_vld1, + id_pred_inst0_32, + id_pred_jmp_vld0, + id_pred_jmp_vld1, + id_pred_link_vld0, + id_pred_link_vld1, + id_pred_ret_vld0, + id_pred_ret_vld1, + ipack_id_pred_inst0, + ipack_id_pred_inst0_vld, + ipack_id_pred_inst1, + ipack_id_pred_inst1_vld +); + +// &Ports; @24 +input [31:0] ipack_id_pred_inst0; +input ipack_id_pred_inst0_vld; +input [15:0] ipack_id_pred_inst1; +input ipack_id_pred_inst1_vld; +output id_pred_br_vld0; +output id_pred_br_vld1; +output id_pred_br_vld1_raw; +output [31:0] id_pred_imm0; +output [31:0] id_pred_imm1; +output id_pred_ind_link_vld0; +output id_pred_ind_link_vld1; +output id_pred_inst0_32; +output id_pred_jmp_vld0; +output id_pred_jmp_vld1; +output id_pred_link_vld0; +output id_pred_link_vld1; +output id_pred_ret_vld0; +output id_pred_ret_vld1; + +// &Regs; @25 + +// &Wires; @26 +wire [31:0] btype_imm; +wire btype_vld; +wire btype_vld1; +wire [31:0] cbtype_imm0; +wire [31:0] cbtype_imm1; +wire cbtype_vld0; +wire cbtype_vld1; +wire cjlrtype_vld0; +wire cjlrtype_vld1; +wire cjltype_vld0; +wire cjltype_vld1; +wire cjrtype_vld0; +wire cjrtype_vld1; +wire [31:0] cjtype_imm0; +wire [31:0] cjtype_imm1; +wire cjtype_vld0; +wire cjtype_vld1; +wire id_pred_br_vld0; +wire id_pred_br_vld1; +wire id_pred_br_vld1_raw; +wire [31:0] id_pred_imm0; +wire [31:0] id_pred_imm1; +wire id_pred_ind_link_vld0; +wire id_pred_ind_link_vld1; +wire id_pred_inst0_32; +wire id_pred_jmp_vld0; +wire id_pred_jmp_vld1; +wire id_pred_link_vld0; +wire id_pred_link_vld1; +wire id_pred_ret_vld0; +wire id_pred_ret_vld1; +wire [31:0] inst0; +wire [31:0] inst0_imm; +wire [15:0] inst1; +wire [31:0] inst1_imm; +wire [31:0] ipack_id_pred_inst0; +wire ipack_id_pred_inst0_vld; +wire [15:0] ipack_id_pred_inst1; +wire ipack_id_pred_inst1_vld; +wire jlrtype_vld; +wire jltype_vld; +wire jrtype_vld; +wire [31:0] jtype_imm; +wire jtype_vld; + + +//========================================================== +// Pre-Decode Module +// 1. First Inst Decode +// 2. Second Inst Decode +//========================================================== + +//------------------------------------------------ +// 1. First Inst Decode +// a. 32-bit Decode, Branch, Jal and Jalr X1 +// b. 16-bit Decode, Branch, Jal and Jalr X1 +//------------------------------------------------ + +assign inst0[31:0] = ipack_id_pred_inst0[31:0]; +assign inst1[15:0] = ipack_id_pred_inst1[15:0]; + +// a. 32-bit Decode, Jal, Branch and Jalr X1 + +// B-Type: BEQ BNE BLT BGE BLTU BGEU +assign btype_vld = inst0[6:0] == 7'b1100011; +assign btype_imm[31:0] = {{20{inst0[31]}}, inst0[7], inst0[30:25], + inst0[11:8], 1'b0}; + +// J-Type: JAL +assign jtype_vld = inst0[6:0] == 7'b1101111; +assign jtype_imm[31:0] = {{12{inst0[31]}}, inst0[19:12], inst0[20], + inst0[30:21], 1'b0}; + +// Jr-Type: JALR X1 +assign jrtype_vld = inst0[6:0] == 7'b1100111 & inst0[19:15] == 5'b1 + //& inst0[31:20] == 12'b0 & inst0[11:7] != 5'b1; + & inst0[11:7] != 5'b1; + +// TODO: JALR JL +assign jltype_vld = jtype_vld & inst0[11:7] == 5'b1; +assign jlrtype_vld = inst0[6:0] == 7'b1100111 & inst0[11:7] == 5'b1; + +// b. 16-bit Decode, Branch, Jal and Jalr X1 + +// CB-Type: C.BEQZ C.BNEZ +assign cbtype_vld0 = {inst0[15:13], inst0[1:0]} == 5'b11001 | + {inst0[15:13], inst0[1:0]} == 5'b11101; +assign cbtype_imm0[31:0] = {{24{inst0[12]}}, inst0[6:5], inst0[2], + inst0[11:10], inst0[4:3], 1'b0}; + +// CJ-Type: C.J C.JAL +assign cjtype_vld0 = {inst0[14:13], inst0[1:0]} == 4'b0101; +assign cjtype_imm0[31:0] = {{21{inst0[12]}}, inst0[8], inst0[10:9], + inst0[6], inst0[7], inst0[2], inst0[11], + inst0[5:3], 1'b0}; + +// CJr-Type: C.JR X1 +assign cjrtype_vld0 = inst0[6:0] == 7'b10 & inst0[15:12] == 4'b1000 + & inst0[11:7] == 5'b1; + +// Imm for Inst0 +assign inst0_imm[31:0] = {32{ btype_vld}} & btype_imm[31:0] | + {32{ jtype_vld}} & jtype_imm[31:0] | + {32{cbtype_vld0}} & cbtype_imm0[31:0] | + {32{cjtype_vld0}} & cjtype_imm0[31:0] ; + +// TODO +assign cjltype_vld0 = cjtype_vld0 & ~inst0[15]; + +// CJlr-Type: C.JALR X1 +assign cjlrtype_vld0 = inst0[6:0] == 7'b10 & inst0[15:12] == 4'b1001 + & inst0[11:7] != 5'b0; + +//------------------------------------------------ +// 2. Second Inst Decode +// 16-bit Decode, Jal, Branch and Jalr X1 +//------------------------------------------------ + +assign btype_vld1 = inst1[6:0] == 7'b1100011; +// 16-bit Decode, Jal, Branch and Jalr X1 +// CB-Type: C.BEQZ C.BNEZ +assign cbtype_vld1 = {inst1[15:13], inst1[1:0]} == 5'b11001 | + {inst1[15:13], inst1[1:0]} == 5'b11101; +assign cbtype_imm1[31:0] = {{24{inst1[12]}}, inst1[6:5], inst1[2], + inst1[11:10], inst1[4:3], 1'b0}; + +// CJ-Type: C.J C.JAL +assign cjtype_vld1 = {inst1[14:13], inst1[1:0]} == 4'b0101; +assign cjtype_imm1[31:0] = {{21{inst1[12]}}, inst1[8], inst1[10:9], + inst1[6], inst1[7], inst1[2], inst1[11], + inst1[5:3], 1'b0}; + +// CJr-Type: C.JR X1 +assign cjrtype_vld1 = inst1[6:0] == 7'b10 & inst1[15:12] == 4'b1000 + & inst1[11:7] == 5'b1; + +// TODO +assign cjltype_vld1 = cjtype_vld1 & ~inst1[15]; + +// CJr-Type: C.JALR X1 +assign cjlrtype_vld1 = inst1[6:0] == 7'b10 & inst1[15:12] == 4'b1001 + & inst1[11:7] != 5'b0; + +// Imm for Inst1 +assign inst1_imm[31:0] = {32{cbtype_vld1}} & cbtype_imm1[31:0] | + {32{cjtype_vld1}} & cjtype_imm1[31:0] ; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to id prediction +assign id_pred_br_vld0 = ipack_id_pred_inst0_vld & (btype_vld | cbtype_vld0); +assign id_pred_jmp_vld0 = ipack_id_pred_inst0_vld & (jtype_vld | cjtype_vld0); +assign id_pred_link_vld0 = ipack_id_pred_inst0_vld & (jltype_vld | jlrtype_vld | cjltype_vld0 | cjlrtype_vld0); +assign id_pred_ret_vld0 = ipack_id_pred_inst0_vld & (jrtype_vld | cjrtype_vld0); +assign id_pred_imm0[31:0] = inst0_imm[31:0]; +assign id_pred_inst0_32 = inst0[1:0] == 2'b11; +assign id_pred_ind_link_vld0 = ipack_id_pred_inst0_vld & (jlrtype_vld | cjlrtype_vld0); + +assign id_pred_br_vld1 = ipack_id_pred_inst1_vld & (btype_vld1 | cbtype_vld1); +assign id_pred_br_vld1_raw = btype_vld1 | cbtype_vld1; +assign id_pred_jmp_vld1 = ipack_id_pred_inst1_vld & (cjtype_vld1); +assign id_pred_link_vld1 = ipack_id_pred_inst1_vld & (cjltype_vld1 | cjlrtype_vld1); +assign id_pred_ret_vld1 = ipack_id_pred_inst1_vld & (cjrtype_vld1); +assign id_pred_imm1[31:0] = inst1_imm[31:0]; +assign id_pred_ind_link_vld1 = ipack_id_pred_inst1_vld & cjlrtype_vld1; + +// &ModuleEnd; @150 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras.v new file mode 100644 index 0000000000000000000000000000000000000000..65e5eded94034e688ed264fbb82fe6b85ec4592b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras.v @@ -0,0 +1,269 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ras( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + id_pred_ras_link_pc, + id_pred_ras_link_vld, + id_pred_ras_ret_vld, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_link_vld, + iu_ifu_link_vld_gate, + iu_ifu_pc_mispred, + iu_ifu_pc_mispred_gate, + iu_ifu_ret_vld, + iu_ifu_ret_vld_gate, + iu_yy_xx_cancel, + pad_yy_icg_scan_en, + ras_cur_ret, + ras_id_pred_tar_pc, + rtu_ifu_flush_fe +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input [23:0] id_pred_ras_link_pc; +input id_pred_ras_link_vld; +input id_pred_ras_ret_vld; +input iu_ifu_bht_mispred; +input iu_ifu_bht_mispred_gate; +input iu_ifu_link_vld; +input iu_ifu_link_vld_gate; +input iu_ifu_pc_mispred; +input iu_ifu_pc_mispred_gate; +input iu_ifu_ret_vld; +input iu_ifu_ret_vld_gate; +input iu_yy_xx_cancel; +input pad_yy_icg_scan_en; +input ras_cur_ret; +input rtu_ifu_flush_fe; +output [23:0] ras_id_pred_tar_pc; + +// &Regs; @25 +reg [3 :0] ras_bju; +reg [3 :0] ras_pop; +reg [23:0] ras_tar_pc; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire [23:0] entry0_pc; +wire entry0_upd; +wire [23:0] entry1_pc; +wire entry1_upd; +wire [23:0] entry2_pc; +wire entry2_upd; +wire [23:0] entry3_pc; +wire entry3_upd; +wire forever_cpuclk; +wire [23:0] id_pred_ras_link_pc; +wire id_pred_ras_link_vld; +wire id_pred_ras_ret_vld; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire iu_yy_xx_cancel; +wire pad_yy_icg_scan_en; +wire ras_cpuclk; +wire ras_cur_ret; +wire ras_icg_en; +wire [23:0] ras_id_pred_tar_pc; +wire [23:0] ras_upd_pc; +wire rtu_ifu_flush_fe; + + +//========================================================== +// Return Address Stack Module +// 1. Instance ICG Cell +// 2. Instance RAS Entries +// 3. RAS Read Port +// 4. RAS Write Port +// 5. Generate Change Flow +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign ras_icg_en = id_pred_ras_ret_vld + | id_pred_ras_link_vld + | rtu_ifu_flush_fe | iu_ifu_bht_mispred_gate | iu_ifu_pc_mispred_gate + | iu_ifu_link_vld_gate | iu_ifu_ret_vld_gate | iu_yy_xx_cancel; +// &Instance("gated_clk_cell", "x_pa_ifu_ras_icg_cell"); @44 +gated_clk_cell x_pa_ifu_ras_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (ras_cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (ras_icg_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @45 +// .external_en (1'b0), @46 +// .global_en (cp0_yy_clk_en), @47 +// .module_en (cp0_ifu_icg_en), @48 +// .local_en (ras_icg_en), @49 +// .clk_out (ras_cpuclk) @50 +// ); @51 + +//------------------------------------------------ +// 2. Instance RAS Entries +//------------------------------------------------ +parameter ENTRY_NUM = 4; + +// &ConnRule(s/ras_entry/entry0/); @58 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry0"); @59 +pa_ifu_ras_entry x_pa_ifu_ras_entry0 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .ras_entry_pc (entry0_pc ), + .ras_entry_upd (entry0_upd ), + .ras_upd_pc (ras_upd_pc ) +); + + +// &ConnRule(s/ras_entry/entry1/); @61 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry1"); @62 +pa_ifu_ras_entry x_pa_ifu_ras_entry1 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .ras_entry_pc (entry1_pc ), + .ras_entry_upd (entry1_upd ), + .ras_upd_pc (ras_upd_pc ) +); + + +// &ConnRule(s/ras_entry/entry2/); @64 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry2"); @65 +pa_ifu_ras_entry x_pa_ifu_ras_entry2 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .ras_entry_pc (entry2_pc ), + .ras_entry_upd (entry2_upd ), + .ras_upd_pc (ras_upd_pc ) +); + + +// &ConnRule(s/ras_entry/entry3/); @67 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry3"); @68 +pa_ifu_ras_entry x_pa_ifu_ras_entry3 ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .ras_entry_pc (entry3_pc ), + .ras_entry_upd (entry3_upd ), + .ras_upd_pc (ras_upd_pc ) +); + + +// &ConnRule(s/ras_entry/entry4/); @71 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry4"); @72 +// &ConnRule(s/ras_entry/entry5/); @74 +// &Instance("pa_ifu_ras_entry","x_pa_ifu_ras_entry5"); @75 + +//------------------------------------------------ +// 3. RAS Read Port +//------------------------------------------------ +always@(posedge ras_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ras_pop[ENTRY_NUM-1:0] <= {{ENTRY_NUM-1{1'b0}}, 1'b1}; + else if(rtu_ifu_flush_fe | iu_ifu_bht_mispred | iu_ifu_pc_mispred & !iu_ifu_link_vld | iu_yy_xx_cancel & iu_ifu_ret_vld) + ras_pop[ENTRY_NUM-1:0] <= ras_bju[ENTRY_NUM-1:0]; + else if(id_pred_ras_link_vld) + ras_pop[ENTRY_NUM-1:0] <= {ras_pop[0], ras_pop[ENTRY_NUM-1:1]}; + else if(id_pred_ras_ret_vld & ~ras_cur_ret) + ras_pop[ENTRY_NUM-1:0] <= {ras_pop[ENTRY_NUM-2:0], ras_pop[ENTRY_NUM-1]}; + else + ras_pop[ENTRY_NUM-1:0] <= ras_pop[ENTRY_NUM-1:0]; +end + +always@(posedge ras_cpuclk or negedge cpurst_b) +begin + if(~cpurst_b) + ras_bju[ENTRY_NUM-1:0] <= {{ENTRY_NUM-1{1'b0}}, 1'b1}; + else if(iu_ifu_link_vld & ~rtu_ifu_flush_fe) + ras_bju[ENTRY_NUM-1:0] <= {ras_bju[0], ras_bju[ENTRY_NUM-1:1]}; + else if(iu_ifu_ret_vld & ~rtu_ifu_flush_fe) + ras_bju[ENTRY_NUM-1:0] <= {ras_bju[ENTRY_NUM-2:0], ras_bju[ENTRY_NUM-1]}; + else + ras_bju[ENTRY_NUM-1:0] <= ras_bju[ENTRY_NUM-1:0]; +end + +// &CombBeg; @108 +// &CombEnd; @118 +// &CombBeg; @120 +always @( entry0_pc[23:0] + or ras_pop[3:0] + or entry3_pc[23:0] + or entry2_pc[23:0] + or entry1_pc[23:0]) +begin +case(ras_pop[3:0]) + 4'b0001: ras_tar_pc[23:0] = entry0_pc[23:0]; + 4'b0010: ras_tar_pc[23:0] = entry1_pc[23:0]; + 4'b0100: ras_tar_pc[23:0] = entry2_pc[23:0]; + 4'b1000: ras_tar_pc[23:0] = entry3_pc[23:0]; + default: ras_tar_pc[23:0] = {24{1'bx}}; +endcase +// &CombEnd; @128 +end + +//------------------------------------------------ +// 4. RAS Write Port +//------------------------------------------------ +assign entry3_upd = id_pred_ras_link_vld & ras_pop[0]; +assign entry2_upd = id_pred_ras_link_vld & ras_pop[3]; +assign entry1_upd = id_pred_ras_link_vld & ras_pop[2]; +assign entry0_upd = id_pred_ras_link_vld & ras_pop[1]; +assign ras_upd_pc[23:0] = id_pred_ras_link_pc[23:0]; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to id prediction +assign ras_id_pred_tar_pc[23:0] = ras_tar_pc[23:0]; + +// &ModuleEnd; @153 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..d9c6bb3959886b06b2cec6c5ad2dac8aa08766da --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_ras_entry.v @@ -0,0 +1,112 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_ras_entry( + cp0_ifu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + pad_yy_icg_scan_en, + ras_entry_pc, + ras_entry_upd, + ras_upd_pc +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input ras_entry_upd; +input [23:0] ras_upd_pc; +output [23:0] ras_entry_pc; + +// &Regs; @25 +reg [23:0] entry_pc; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire entry_clk; +wire entry_clk_en; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; +wire [23:0] ras_entry_pc; +wire ras_entry_upd; +wire [23:0] ras_upd_pc; + + +//========================================================== +// IFU Ras Entry Module +// 1. Instance ICG Cell +// 2. Entry PC +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign entry_clk_en = ras_entry_upd; +// &Instance("gated_clk_cell", "x_ras_entry_icg_cell"); @38 +gated_clk_cell x_ras_entry_icg_cell ( + .clk_in (forever_cpuclk ), + .clk_out (entry_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (entry_clk_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @39 +// .external_en (1'b0), @40 +// .global_en (cp0_yy_clk_en), @41 +// .module_en (cp0_ifu_icg_en), @42 +// .local_en (entry_clk_en), @43 +// .clk_out (entry_clk) @44 +// ); @45 + +//------------------------------------------------ +// 2. Entry PC +//------------------------------------------------ +always @(posedge entry_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + entry_pc[23:0] <= 24'b0; + end + else if(ras_entry_upd) + begin + entry_pc[23:0] <= ras_upd_pc[23:0]; + end + else + begin + entry_pc[23:0] <= entry_pc[23:0]; + end +end + + +//========================================================== +// Rename for Output +//========================================================== +assign ras_entry_pc[23:0] = entry_pc[23:0]; + + +// &ModuleEnd; @73 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..e59a6cd52ebec32f4b8225430e818699c25b9772 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_top.v @@ -0,0 +1,957 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_top( + bmu_ifu_acc_err, + bmu_ifu_grant, + bmu_ifu_rdata, + bmu_ifu_trans_cmplt, + cp0_ifu_bht_en, + cp0_ifu_bht_inv, + cp0_ifu_btb_clr, + cp0_ifu_btb_en, + cp0_ifu_icache_en, + cp0_ifu_icache_inv_addr, + cp0_ifu_icache_inv_req, + cp0_ifu_icache_inv_type, + cp0_ifu_icg_en, + cp0_ifu_in_lpmd, + cp0_ifu_lpmd_req, + cp0_ifu_mtvec, + cp0_ifu_ras_en, + cp0_ifu_rst_inv_done, + cp0_ifu_srst_mask, + cp0_ifu_srst_req, + cp0_yy_clk_en, + cp0_yy_mach_mode, + cpurst_b, + dtu_ifu_debug_inst, + dtu_ifu_debug_inst_vld, + dtu_ifu_halt_info0, + dtu_ifu_halt_info1, + dtu_ifu_halt_info_vld, + dtu_ifu_halt_on_reset, + forever_cpuclk, + idu_ifu_id_stall, + idu_ifu_tail_vld, + idu_ifu_tail_vld_gate, + idu_ifu_x1, + ifu_bmu_acc_deny, + ifu_bmu_addr, + ifu_bmu_burst, + ifu_bmu_data_req, + ifu_bmu_prot, + ifu_bmu_req, + ifu_bmu_seq, + ifu_bmu_size, + ifu_clic_warm_up, + ifu_cp0_bht_inv_done, + ifu_cp0_icache_inv_done, + ifu_cp0_lpmd_ack, + ifu_cp0_rst_inv_req, + ifu_cp0_srst_ack, + ifu_cp0_vec_err, + ifu_cp0_vec_succeed, + ifu_cp0_warm_up, + ifu_dtu_addr_vld0, + ifu_dtu_addr_vld1, + ifu_dtu_data_vld0, + ifu_dtu_data_vld1, + ifu_dtu_debug_info, + ifu_dtu_exe_addr0, + ifu_dtu_exe_addr1, + ifu_dtu_exe_data0, + ifu_dtu_exe_data1, + ifu_fpu_warm_up, + ifu_hpcp_icache_access, + ifu_hpcp_icache_miss, + ifu_idu_chgflw_flush, + ifu_idu_id_expt_high, + ifu_idu_id_expt_vld, + ifu_idu_id_halt_info, + ifu_idu_id_inst, + ifu_idu_id_inst_vld, + ifu_idu_id_pred_taken, + ifu_idu_warm_up, + ifu_iu_chgflw_pc, + ifu_iu_chgflw_vld, + ifu_iu_ex1_pc_pred, + ifu_iu_reset_vld, + ifu_iu_warm_up, + ifu_lsu_warm_up, + ifu_pmp_addr, + ifu_pmp_machine_mode, + ifu_rtu_lockup_ack, + ifu_rtu_reset_halt_req, + ifu_rtu_warm_up, + ifu_sysmap_pa, + ifu_sysmap_rst_sample, + ifu_xx_in_warm_up, + iu_ifu_bht_cur_pc, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_bht_pred, + iu_ifu_bht_taken, + iu_ifu_br_vld, + iu_ifu_br_vld_gate, + iu_ifu_ind_link_vld, + iu_ifu_link_vld, + iu_ifu_link_vld_gate, + iu_ifu_pc_mispred, + iu_ifu_pc_mispred_gate, + iu_ifu_ret_vld, + iu_ifu_ret_vld_gate, + iu_ifu_tar_pc, + iu_ifu_tar_pc_vld, + iu_ifu_tar_pc_vld_gate, + iu_yy_xx_cancel, + pad_yy_icg_scan_en, + pmp_ifu_acc_deny, + rtu_ifu_chgflw_pc, + rtu_ifu_chgflw_vld, + rtu_ifu_dbg_mask, + rtu_ifu_flush_fe, + rtu_ifu_lockup_expt_vld, + rtu_ifu_lockup_mask, + rtu_ifu_lockup_req, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vld, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + sysio_ifu_rst_addr, + sysio_ifu_rst_addr_done, + sysio_xx_halt_req, + sysmap_ifu_flg +); + +// &Ports; @24 +input bmu_ifu_acc_err; +input bmu_ifu_grant; +input [31:0] bmu_ifu_rdata; +input bmu_ifu_trans_cmplt; +input cp0_ifu_bht_en; +input cp0_ifu_bht_inv; +input cp0_ifu_btb_clr; +input cp0_ifu_btb_en; +input cp0_ifu_icache_en; +input [31:0] cp0_ifu_icache_inv_addr; +input cp0_ifu_icache_inv_req; +input cp0_ifu_icache_inv_type; +input cp0_ifu_icg_en; +input cp0_ifu_in_lpmd; +input cp0_ifu_lpmd_req; +input [31:0] cp0_ifu_mtvec; +input cp0_ifu_ras_en; +input cp0_ifu_rst_inv_done; +input cp0_ifu_srst_mask; +input cp0_ifu_srst_req; +input cp0_yy_clk_en; +input cp0_yy_mach_mode; +input cpurst_b; +input [31:0] dtu_ifu_debug_inst; +input dtu_ifu_debug_inst_vld; +input [14:0] dtu_ifu_halt_info0; +input [14:0] dtu_ifu_halt_info1; +input dtu_ifu_halt_info_vld; +input dtu_ifu_halt_on_reset; +input forever_cpuclk; +input idu_ifu_id_stall; +input idu_ifu_tail_vld; +input idu_ifu_tail_vld_gate; +input [31:0] idu_ifu_x1; +input [31:0] iu_ifu_bht_cur_pc; +input iu_ifu_bht_mispred; +input iu_ifu_bht_mispred_gate; +input [1 :0] iu_ifu_bht_pred; +input iu_ifu_bht_taken; +input iu_ifu_br_vld; +input iu_ifu_br_vld_gate; +input iu_ifu_ind_link_vld; +input iu_ifu_link_vld; +input iu_ifu_link_vld_gate; +input iu_ifu_pc_mispred; +input iu_ifu_pc_mispred_gate; +input iu_ifu_ret_vld; +input iu_ifu_ret_vld_gate; +input [31:0] iu_ifu_tar_pc; +input iu_ifu_tar_pc_vld; +input iu_ifu_tar_pc_vld_gate; +input iu_yy_xx_cancel; +input pad_yy_icg_scan_en; +input pmp_ifu_acc_deny; +input [31:0] rtu_ifu_chgflw_pc; +input rtu_ifu_chgflw_vld; +input rtu_ifu_dbg_mask; +input rtu_ifu_flush_fe; +input rtu_ifu_lockup_expt_vld; +input rtu_ifu_lockup_mask; +input rtu_ifu_lockup_req; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_int_hv; +input rtu_yy_xx_tail_int_vld; +input [31:0] sysio_ifu_rst_addr; +input sysio_ifu_rst_addr_done; +input sysio_xx_halt_req; +input [4 :0] sysmap_ifu_flg; +output ifu_bmu_acc_deny; +output [31:0] ifu_bmu_addr; +output [2 :0] ifu_bmu_burst; +output ifu_bmu_data_req; +output [3 :0] ifu_bmu_prot; +output ifu_bmu_req; +output ifu_bmu_seq; +output [1 :0] ifu_bmu_size; +output ifu_clic_warm_up; +output ifu_cp0_bht_inv_done; +output ifu_cp0_icache_inv_done; +output ifu_cp0_lpmd_ack; +output ifu_cp0_rst_inv_req; +output ifu_cp0_srst_ack; +output ifu_cp0_vec_err; +output ifu_cp0_vec_succeed; +output ifu_cp0_warm_up; +output ifu_dtu_addr_vld0; +output ifu_dtu_addr_vld1; +output ifu_dtu_data_vld0; +output ifu_dtu_data_vld1; +output [26:0] ifu_dtu_debug_info; +output [31:0] ifu_dtu_exe_addr0; +output [31:0] ifu_dtu_exe_addr1; +output [31:0] ifu_dtu_exe_data0; +output [31:0] ifu_dtu_exe_data1; +output ifu_fpu_warm_up; +output ifu_hpcp_icache_access; +output ifu_hpcp_icache_miss; +output ifu_idu_chgflw_flush; +output ifu_idu_id_expt_high; +output ifu_idu_id_expt_vld; +output [14:0] ifu_idu_id_halt_info; +output [31:0] ifu_idu_id_inst; +output ifu_idu_id_inst_vld; +output [1 :0] ifu_idu_id_pred_taken; +output ifu_idu_warm_up; +output [31:0] ifu_iu_chgflw_pc; +output ifu_iu_chgflw_vld; +output [31:0] ifu_iu_ex1_pc_pred; +output ifu_iu_reset_vld; +output ifu_iu_warm_up; +output ifu_lsu_warm_up; +output [31:0] ifu_pmp_addr; +output ifu_pmp_machine_mode; +output ifu_rtu_lockup_ack; +output ifu_rtu_reset_halt_req; +output ifu_rtu_warm_up; +output [31:0] ifu_sysmap_pa; +output ifu_sysmap_rst_sample; +output ifu_xx_in_warm_up; + +// &Regs; @25 + +// &Wires; @26 +wire [1 :0] bht_top_cur_st; +wire bmu_ifu_acc_err; +wire bmu_ifu_grant; +wire [31:0] bmu_ifu_rdata; +wire bmu_ifu_trans_cmplt; +wire [31:0] btb_pcgen_tar_pc; +wire btb_xx_chgflw_vld; +wire cp0_ifu_bht_en; +wire cp0_ifu_bht_inv; +wire cp0_ifu_btb_clr; +wire cp0_ifu_btb_en; +wire cp0_ifu_icache_en; +wire [31:0] cp0_ifu_icache_inv_addr; +wire cp0_ifu_icache_inv_req; +wire cp0_ifu_icache_inv_type; +wire cp0_ifu_icg_en; +wire cp0_ifu_in_lpmd; +wire cp0_ifu_lpmd_req; +wire [31:0] cp0_ifu_mtvec; +wire cp0_ifu_ras_en; +wire cp0_ifu_rst_inv_done; +wire cp0_ifu_srst_mask; +wire cp0_ifu_srst_req; +wire cp0_yy_clk_en; +wire cp0_yy_mach_mode; +wire cpurst_b; +wire ctrl_btb_inst_fetch; +wire ctrl_ibuf_pop_en; +wire ctrl_ifetch_req_abort; +wire ctrl_ifetch_req_vld; +wire ctrl_pcgen_inst_vld; +wire ctrl_pcgen_pipedown; +wire [31:0] dtu_ifu_debug_inst; +wire dtu_ifu_debug_inst_vld; +wire [14:0] dtu_ifu_halt_info0; +wire [14:0] dtu_ifu_halt_info1; +wire dtu_ifu_halt_info_vld; +wire dtu_ifu_halt_on_reset; +wire forever_cpuclk; +wire ibuf_ctrl_inst_fetch; +wire ibuf_id_pred_hungry; +wire ibuf_ipack_stall; +wire ibuf_pred_stall; +wire ibuf_top_id_stall; +wire [2 :0] ibuf_top_vld_num; +wire icache_top_abort; +wire icache_top_rd_vld; +wire [1 :0] icache_top_ref_st; +wire icache_top_uc_st; +wire [31:0] id_pred_btb_cur_pc; +wire id_pred_btb_mis_pred; +wire id_pred_btb_mis_predg; +wire [31:0] id_pred_btb_tar_pc; +wire id_pred_btb_upd_vld; +wire id_pred_btb_upd_vldg; +wire id_pred_ctrl_stall; +wire [1 :0] id_pred_ibuf_br_taken0; +wire [1 :0] id_pred_ibuf_br_taken1; +wire id_pred_ibuf_chgflw_vld0; +wire [14:0] id_pred_ibuf_halt_info0; +wire [14:0] id_pred_ibuf_halt_info1; +wire id_pred_ipack_chgflw_vld0; +wire id_pred_ipack_delay_stall; +wire id_pred_ipack_mask; +wire id_pred_ipack_ret_stall; +wire [31:0] id_pred_pcgen_chgflw_pc; +wire id_pred_pcgen_chgflw_vld; +wire id_pred_pcgen_inst_vld; +wire idu_ifu_id_stall; +wire idu_ifu_tail_vld; +wire idu_ifu_tail_vld_gate; +wire [31:0] idu_ifu_x1; +wire ifetch_ctrl_inst_vld; +wire ifetch_ibuf_idle; +wire ifetch_ipack_acc_err; +wire [31:0] ifetch_ipack_inst; +wire ifetch_ipack_inst_vld; +wire ifetch_ipack_inst_vld_gate; +wire ifetch_ipack_unalign; +wire [31:0] ifetch_pcgen_addr; +wire [31:0] ifetch_pcgen_data; +wire ifetch_pcgen_grant; +wire ifetch_pcgen_grant_dp; +wire [1 :0] ifetch_top_abt_st; +wire [2 :0] ifetch_top_cur_st; +wire ifetch_vec_acc_err; +wire ifetch_vec_cmplt; +wire ifetch_vec_grant; +wire ifetch_vec_idle; +wire ifetch_xx_not_busy; +wire ifu_bmu_acc_deny; +wire [31:0] ifu_bmu_addr; +wire [2 :0] ifu_bmu_burst; +wire ifu_bmu_data_req; +wire [3 :0] ifu_bmu_prot; +wire ifu_bmu_req; +wire ifu_bmu_seq; +wire [1 :0] ifu_bmu_size; +wire ifu_clic_warm_up; +wire ifu_cp0_bht_inv_done; +wire ifu_cp0_icache_inv_done; +wire ifu_cp0_lpmd_ack; +wire ifu_cp0_rst_inv_req; +wire ifu_cp0_srst_ack; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire ifu_cp0_warm_up; +wire ifu_dtu_addr_vld0; +wire ifu_dtu_addr_vld1; +wire ifu_dtu_data_vld0; +wire ifu_dtu_data_vld1; +wire [26:0] ifu_dtu_debug_info; +wire [31:0] ifu_dtu_exe_addr0; +wire [31:0] ifu_dtu_exe_addr1; +wire [31:0] ifu_dtu_exe_data0; +wire [31:0] ifu_dtu_exe_data1; +wire ifu_fpu_warm_up; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire ifu_idu_chgflw_flush; +wire ifu_idu_id_expt_high; +wire ifu_idu_id_expt_vld; +wire [14:0] ifu_idu_id_halt_info; +wire [31:0] ifu_idu_id_inst; +wire ifu_idu_id_inst_vld; +wire [1 :0] ifu_idu_id_pred_taken; +wire ifu_idu_warm_up; +wire [31:0] ifu_iu_chgflw_pc; +wire ifu_iu_chgflw_vld; +wire [31:0] ifu_iu_ex1_pc_pred; +wire ifu_iu_reset_vld; +wire ifu_iu_warm_up; +wire ifu_lsu_warm_up; +wire [31:0] ifu_pmp_addr; +wire ifu_pmp_machine_mode; +wire ifu_rtu_lockup_ack; +wire ifu_rtu_reset_halt_req; +wire ifu_rtu_warm_up; +wire [31:0] ifu_sysmap_pa; +wire ifu_sysmap_rst_sample; +wire ifu_xx_in_warm_up; +wire [2 :0] ipack_ibuf_acc_err; +wire [47:0] ipack_ibuf_inst; +wire ipack_ibuf_inst_all; +wire ipack_ibuf_inst_empty; +wire ipack_ibuf_inst_full; +wire ipack_ibuf_inst_one; +wire ipack_ibuf_inst_one_raw; +wire ipack_ibuf_inst_two; +wire ipack_ibuf_inst_vld; +wire ipack_ibuf_inst_vld_raw; +wire ipack_id_pred_h0_create; +wire ipack_id_pred_h0_vld; +wire [31:0] ipack_id_pred_inst0; +wire ipack_id_pred_inst0_expt; +wire ipack_id_pred_inst0_vld; +wire [15:0] ipack_id_pred_inst1; +wire ipack_id_pred_inst1_expt; +wire ipack_id_pred_inst1_vld; +wire ipack_id_pred_new_vld; +wire ipack_id_pred_unalign; +wire ipack_pcgen_reissue; +wire ipack_pcgen_reissue_gate; +wire ipack_top_entry0_vld; +wire ipack_top_entry1_vld; +wire ipack_top_entry2_vld; +wire [31:0] iu_ifu_bht_cur_pc; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire iu_ifu_ind_link_vld; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire [31:0] iu_ifu_tar_pc; +wire iu_ifu_tar_pc_vld; +wire iu_ifu_tar_pc_vld_gate; +wire iu_yy_xx_cancel; +wire pad_yy_icg_scan_en; +wire [31:0] pcgen_btb_addr; +wire [31:0] pcgen_btb_pc; +wire pcgen_ctrl_chgflw_vld; +wire pcgen_ibuf_chgflw_vld; +wire [31:0] pcgen_id_pred_btb_tar_pc; +wire pcgen_id_pred_btb_tar_vld; +wire pcgen_id_pred_flush_vld; +wire [31:0] pcgen_id_pred_idpc; +wire [31:0] pcgen_id_pred_ifpc; +wire [31:0] pcgen_ifetch_addr; +wire pcgen_ifetch_chgflw_vld; +wire [31:0] pcgen_ifetch_ifpc; +wire [31:0] pcgen_ifetch_seq_addr; +wire pcgen_ipack_chgflw_vld; +wire pcgen_top_btb_tar_vld; +wire pcgen_top_buf_chgflw; +wire pmp_ifu_acc_deny; +wire pred_top_delay_chgflw; +wire pred_top_ras_st; +wire [31:0] rtu_ifu_chgflw_pc; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_dbg_mask; +wire rtu_ifu_flush_fe; +wire rtu_ifu_lockup_expt_vld; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire [31:0] sysio_ifu_rst_addr; +wire sysio_ifu_rst_addr_done; +wire sysio_xx_halt_req; +wire [4 :0] sysmap_ifu_flg; +wire vec_ctrl_reset_mask; +wire vec_ctrl_seq_mask; +wire vec_ibuf_warm_up; +wire vec_ifetch_data_fetch; +wire vec_ipack_inst_mask; +wire vec_pcgen_chgflw_vld; +wire vec_pcgen_idle; +wire vec_pcgen_inst_fetch; +wire vec_pcgen_iu_chgflw; +wire vec_pcgen_pc_flop; +wire vec_pcgen_rst_vld; +wire [31:0] vec_pcgen_tar_pc; +wire [3 :0] vec_top_cur_st; + + +// PC-Generation Module +// &Instance("pa_ifu_pcgen"); @29 +pa_ifu_pcgen x_pa_ifu_pcgen ( + .btb_pcgen_tar_pc (btb_pcgen_tar_pc ), + .btb_xx_chgflw_vld (btb_xx_chgflw_vld ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_pcgen_inst_vld (ctrl_pcgen_inst_vld ), + .ctrl_pcgen_pipedown (ctrl_pcgen_pipedown ), + .forever_cpuclk (forever_cpuclk ), + .id_pred_pcgen_chgflw_pc (id_pred_pcgen_chgflw_pc ), + .id_pred_pcgen_chgflw_vld (id_pred_pcgen_chgflw_vld ), + .id_pred_pcgen_inst_vld (id_pred_pcgen_inst_vld ), + .ifetch_pcgen_addr (ifetch_pcgen_addr ), + .ifetch_pcgen_data (ifetch_pcgen_data ), + .ifetch_pcgen_grant (ifetch_pcgen_grant ), + .ifetch_pcgen_grant_dp (ifetch_pcgen_grant_dp ), + .ifetch_xx_not_busy (ifetch_xx_not_busy ), + .ifu_idu_chgflw_flush (ifu_idu_chgflw_flush ), + .ifu_iu_chgflw_pc (ifu_iu_chgflw_pc ), + .ifu_iu_chgflw_vld (ifu_iu_chgflw_vld ), + .ipack_pcgen_reissue (ipack_pcgen_reissue ), + .ipack_pcgen_reissue_gate (ipack_pcgen_reissue_gate ), + .iu_ifu_tar_pc (iu_ifu_tar_pc ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .iu_ifu_tar_pc_vld_gate (iu_ifu_tar_pc_vld_gate ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_btb_addr (pcgen_btb_addr ), + .pcgen_btb_pc (pcgen_btb_pc ), + .pcgen_ctrl_chgflw_vld (pcgen_ctrl_chgflw_vld ), + .pcgen_ibuf_chgflw_vld (pcgen_ibuf_chgflw_vld ), + .pcgen_id_pred_btb_tar_pc (pcgen_id_pred_btb_tar_pc ), + .pcgen_id_pred_btb_tar_vld (pcgen_id_pred_btb_tar_vld), + .pcgen_id_pred_flush_vld (pcgen_id_pred_flush_vld ), + .pcgen_id_pred_idpc (pcgen_id_pred_idpc ), + .pcgen_id_pred_ifpc (pcgen_id_pred_ifpc ), + .pcgen_ifetch_addr (pcgen_ifetch_addr ), + .pcgen_ifetch_chgflw_vld (pcgen_ifetch_chgflw_vld ), + .pcgen_ifetch_ifpc (pcgen_ifetch_ifpc ), + .pcgen_ifetch_seq_addr (pcgen_ifetch_seq_addr ), + .pcgen_ipack_chgflw_vld (pcgen_ipack_chgflw_vld ), + .pcgen_top_btb_tar_vld (pcgen_top_btb_tar_vld ), + .pcgen_top_buf_chgflw (pcgen_top_buf_chgflw ), + .rtu_ifu_chgflw_pc (rtu_ifu_chgflw_pc ), + .rtu_ifu_chgflw_vld (rtu_ifu_chgflw_vld ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .sysio_ifu_rst_addr (sysio_ifu_rst_addr ), + .vec_pcgen_chgflw_vld (vec_pcgen_chgflw_vld ), + .vec_pcgen_idle (vec_pcgen_idle ), + .vec_pcgen_inst_fetch (vec_pcgen_inst_fetch ), + .vec_pcgen_iu_chgflw (vec_pcgen_iu_chgflw ), + .vec_pcgen_pc_flop (vec_pcgen_pc_flop ), + .vec_pcgen_rst_vld (vec_pcgen_rst_vld ), + .vec_pcgen_tar_pc (vec_pcgen_tar_pc ) +); + + +// Instruction-Fetch Module +// &Instance("pa_ifu_ifetch_axi"); @33 +// &Instance("pa_ifu_ifetch"); @35 +pa_ifu_ifetch x_pa_ifu_ifetch ( + .bmu_ifu_acc_err (bmu_ifu_acc_err ), + .bmu_ifu_grant (bmu_ifu_grant ), + .bmu_ifu_rdata (bmu_ifu_rdata ), + .bmu_ifu_trans_cmplt (bmu_ifu_trans_cmplt ), + .cp0_ifu_icache_en (cp0_ifu_icache_en ), + .cp0_ifu_icache_inv_addr (cp0_ifu_icache_inv_addr ), + .cp0_ifu_icache_inv_req (cp0_ifu_icache_inv_req ), + .cp0_ifu_icache_inv_type (cp0_ifu_icache_inv_type ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_lpmd_req (cp0_ifu_lpmd_req ), + .cp0_ifu_srst_req (cp0_ifu_srst_req ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .ctrl_ifetch_req_abort (ctrl_ifetch_req_abort ), + .ctrl_ifetch_req_vld (ctrl_ifetch_req_vld ), + .forever_cpuclk (forever_cpuclk ), + .icache_top_abort (icache_top_abort ), + .icache_top_rd_vld (icache_top_rd_vld ), + .icache_top_ref_st (icache_top_ref_st ), + .icache_top_uc_st (icache_top_uc_st ), + .ifetch_ctrl_inst_vld (ifetch_ctrl_inst_vld ), + .ifetch_ibuf_idle (ifetch_ibuf_idle ), + .ifetch_ipack_acc_err (ifetch_ipack_acc_err ), + .ifetch_ipack_inst (ifetch_ipack_inst ), + .ifetch_ipack_inst_vld (ifetch_ipack_inst_vld ), + .ifetch_ipack_inst_vld_gate (ifetch_ipack_inst_vld_gate), + .ifetch_ipack_unalign (ifetch_ipack_unalign ), + .ifetch_pcgen_addr (ifetch_pcgen_addr ), + .ifetch_pcgen_data (ifetch_pcgen_data ), + .ifetch_pcgen_grant (ifetch_pcgen_grant ), + .ifetch_pcgen_grant_dp (ifetch_pcgen_grant_dp ), + .ifetch_top_abt_st (ifetch_top_abt_st ), + .ifetch_top_cur_st (ifetch_top_cur_st ), + .ifetch_vec_acc_err (ifetch_vec_acc_err ), + .ifetch_vec_cmplt (ifetch_vec_cmplt ), + .ifetch_vec_grant (ifetch_vec_grant ), + .ifetch_vec_idle (ifetch_vec_idle ), + .ifetch_xx_not_busy (ifetch_xx_not_busy ), + .ifu_bmu_acc_deny (ifu_bmu_acc_deny ), + .ifu_bmu_addr (ifu_bmu_addr ), + .ifu_bmu_burst (ifu_bmu_burst ), + .ifu_bmu_data_req (ifu_bmu_data_req ), + .ifu_bmu_prot (ifu_bmu_prot ), + .ifu_bmu_req (ifu_bmu_req ), + .ifu_bmu_seq (ifu_bmu_seq ), + .ifu_bmu_size (ifu_bmu_size ), + .ifu_cp0_icache_inv_done (ifu_cp0_icache_inv_done ), + .ifu_cp0_lpmd_ack (ifu_cp0_lpmd_ack ), + .ifu_cp0_srst_ack (ifu_cp0_srst_ack ), + .ifu_hpcp_icache_access (ifu_hpcp_icache_access ), + .ifu_hpcp_icache_miss (ifu_hpcp_icache_miss ), + .ifu_pmp_addr (ifu_pmp_addr ), + .ifu_pmp_machine_mode (ifu_pmp_machine_mode ), + .ifu_rtu_lockup_ack (ifu_rtu_lockup_ack ), + .ifu_sysmap_pa (ifu_sysmap_pa ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_ifetch_addr (pcgen_ifetch_addr ), + .pcgen_ifetch_chgflw_vld (pcgen_ifetch_chgflw_vld ), + .pcgen_ifetch_ifpc (pcgen_ifetch_ifpc ), + .pcgen_ifetch_seq_addr (pcgen_ifetch_seq_addr ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .rtu_ifu_lockup_mask (rtu_ifu_lockup_mask ), + .rtu_ifu_lockup_req (rtu_ifu_lockup_req ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sysmap_ifu_flg (sysmap_ifu_flg ), + .vec_ifetch_data_fetch (vec_ifetch_data_fetch ) +); + + +// L0-BTB Module +// &Instance("pa_ifu_btb"); @39 +pa_ifu_btb x_pa_ifu_btb ( + .btb_pcgen_tar_pc (btb_pcgen_tar_pc ), + .btb_xx_chgflw_vld (btb_xx_chgflw_vld ), + .cp0_ifu_btb_clr (cp0_ifu_btb_clr ), + .cp0_ifu_btb_en (cp0_ifu_btb_en ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_btb_inst_fetch (ctrl_btb_inst_fetch ), + .forever_cpuclk (forever_cpuclk ), + .id_pred_btb_cur_pc (id_pred_btb_cur_pc ), + .id_pred_btb_mis_pred (id_pred_btb_mis_pred ), + .id_pred_btb_mis_predg (id_pred_btb_mis_predg), + .id_pred_btb_tar_pc (id_pred_btb_tar_pc ), + .id_pred_btb_upd_vld (id_pred_btb_upd_vld ), + .id_pred_btb_upd_vldg (id_pred_btb_upd_vldg ), + .ifetch_pcgen_grant (ifetch_pcgen_grant ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_btb_addr (pcgen_btb_addr ), + .pcgen_btb_pc (pcgen_btb_pc ) +); + + +// Instruction Package Module +// &Instance("pa_ifu_ipack"); @42 +pa_ifu_ipack x_pa_ifu_ipack ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_ipack_stall (ibuf_ipack_stall ), + .id_pred_ipack_chgflw_vld0 (id_pred_ipack_chgflw_vld0 ), + .id_pred_ipack_delay_stall (id_pred_ipack_delay_stall ), + .id_pred_ipack_mask (id_pred_ipack_mask ), + .id_pred_ipack_ret_stall (id_pred_ipack_ret_stall ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .ifetch_ipack_acc_err (ifetch_ipack_acc_err ), + .ifetch_ipack_inst (ifetch_ipack_inst ), + .ifetch_ipack_inst_vld (ifetch_ipack_inst_vld ), + .ifetch_ipack_inst_vld_gate (ifetch_ipack_inst_vld_gate), + .ifetch_ipack_unalign (ifetch_ipack_unalign ), + .ipack_ibuf_acc_err (ipack_ibuf_acc_err ), + .ipack_ibuf_inst (ipack_ibuf_inst ), + .ipack_ibuf_inst_all (ipack_ibuf_inst_all ), + .ipack_ibuf_inst_empty (ipack_ibuf_inst_empty ), + .ipack_ibuf_inst_full (ipack_ibuf_inst_full ), + .ipack_ibuf_inst_one (ipack_ibuf_inst_one ), + .ipack_ibuf_inst_one_raw (ipack_ibuf_inst_one_raw ), + .ipack_ibuf_inst_two (ipack_ibuf_inst_two ), + .ipack_ibuf_inst_vld (ipack_ibuf_inst_vld ), + .ipack_ibuf_inst_vld_raw (ipack_ibuf_inst_vld_raw ), + .ipack_id_pred_h0_create (ipack_id_pred_h0_create ), + .ipack_id_pred_h0_vld (ipack_id_pred_h0_vld ), + .ipack_id_pred_inst0 (ipack_id_pred_inst0 ), + .ipack_id_pred_inst0_expt (ipack_id_pred_inst0_expt ), + .ipack_id_pred_inst0_vld (ipack_id_pred_inst0_vld ), + .ipack_id_pred_inst1 (ipack_id_pred_inst1 ), + .ipack_id_pred_inst1_expt (ipack_id_pred_inst1_expt ), + .ipack_id_pred_inst1_vld (ipack_id_pred_inst1_vld ), + .ipack_id_pred_new_vld (ipack_id_pred_new_vld ), + .ipack_id_pred_unalign (ipack_id_pred_unalign ), + .ipack_pcgen_reissue (ipack_pcgen_reissue ), + .ipack_pcgen_reissue_gate (ipack_pcgen_reissue_gate ), + .ipack_top_entry0_vld (ipack_top_entry0_vld ), + .ipack_top_entry1_vld (ipack_top_entry1_vld ), + .ipack_top_entry2_vld (ipack_top_entry2_vld ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_ipack_chgflw_vld (pcgen_ipack_chgflw_vld ), + .rtu_ifu_chgflw_vld (rtu_ifu_chgflw_vld ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .vec_ipack_inst_mask (vec_ipack_inst_mask ) +); + + +// Instruction Buffer Module +// &Instance("pa_ifu_ibuf"); @45 +pa_ifu_ibuf x_pa_ifu_ibuf ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .ctrl_ibuf_pop_en (ctrl_ibuf_pop_en ), + .dtu_ifu_debug_inst (dtu_ifu_debug_inst ), + .dtu_ifu_debug_inst_vld (dtu_ifu_debug_inst_vld ), + .dtu_ifu_halt_info_vld (dtu_ifu_halt_info_vld ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_ctrl_inst_fetch (ibuf_ctrl_inst_fetch ), + .ibuf_id_pred_hungry (ibuf_id_pred_hungry ), + .ibuf_ipack_stall (ibuf_ipack_stall ), + .ibuf_pred_stall (ibuf_pred_stall ), + .ibuf_top_id_stall (ibuf_top_id_stall ), + .ibuf_top_vld_num (ibuf_top_vld_num ), + .id_pred_ibuf_br_taken0 (id_pred_ibuf_br_taken0 ), + .id_pred_ibuf_br_taken1 (id_pred_ibuf_br_taken1 ), + .id_pred_ibuf_chgflw_vld0 (id_pred_ibuf_chgflw_vld0), + .id_pred_ibuf_halt_info0 (id_pred_ibuf_halt_info0 ), + .id_pred_ibuf_halt_info1 (id_pred_ibuf_halt_info1 ), + .idu_ifu_id_stall (idu_ifu_id_stall ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .idu_ifu_tail_vld_gate (idu_ifu_tail_vld_gate ), + .ifetch_ibuf_idle (ifetch_ibuf_idle ), + .ifetch_xx_not_busy (ifetch_xx_not_busy ), + .ifu_idu_id_expt_high (ifu_idu_id_expt_high ), + .ifu_idu_id_expt_vld (ifu_idu_id_expt_vld ), + .ifu_idu_id_halt_info (ifu_idu_id_halt_info ), + .ifu_idu_id_inst (ifu_idu_id_inst ), + .ifu_idu_id_inst_vld (ifu_idu_id_inst_vld ), + .ifu_idu_id_pred_taken (ifu_idu_id_pred_taken ), + .ipack_ibuf_acc_err (ipack_ibuf_acc_err ), + .ipack_ibuf_inst (ipack_ibuf_inst ), + .ipack_ibuf_inst_all (ipack_ibuf_inst_all ), + .ipack_ibuf_inst_empty (ipack_ibuf_inst_empty ), + .ipack_ibuf_inst_full (ipack_ibuf_inst_full ), + .ipack_ibuf_inst_one (ipack_ibuf_inst_one ), + .ipack_ibuf_inst_one_raw (ipack_ibuf_inst_one_raw ), + .ipack_ibuf_inst_two (ipack_ibuf_inst_two ), + .ipack_ibuf_inst_vld (ipack_ibuf_inst_vld ), + .ipack_ibuf_inst_vld_raw (ipack_ibuf_inst_vld_raw ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_ibuf_chgflw_vld (pcgen_ibuf_chgflw_vld ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ) +); + + +// Control Module +// &Instance("pa_ifu_ctrl"); @48 +pa_ifu_ctrl x_pa_ifu_ctrl ( + .cp0_ifu_in_lpmd (cp0_ifu_in_lpmd ), + .cp0_ifu_lpmd_req (cp0_ifu_lpmd_req ), + .cp0_ifu_srst_mask (cp0_ifu_srst_mask ), + .cp0_ifu_srst_req (cp0_ifu_srst_req ), + .ctrl_btb_inst_fetch (ctrl_btb_inst_fetch ), + .ctrl_ibuf_pop_en (ctrl_ibuf_pop_en ), + .ctrl_ifetch_req_abort (ctrl_ifetch_req_abort ), + .ctrl_ifetch_req_vld (ctrl_ifetch_req_vld ), + .ctrl_pcgen_inst_vld (ctrl_pcgen_inst_vld ), + .ctrl_pcgen_pipedown (ctrl_pcgen_pipedown ), + .ibuf_ctrl_inst_fetch (ibuf_ctrl_inst_fetch ), + .id_pred_ctrl_stall (id_pred_ctrl_stall ), + .idu_ifu_id_stall (idu_ifu_id_stall ), + .idu_ifu_tail_vld (idu_ifu_tail_vld ), + .ifetch_ctrl_inst_vld (ifetch_ctrl_inst_vld ), + .pcgen_ctrl_chgflw_vld (pcgen_ctrl_chgflw_vld ), + .rtu_ifu_dbg_mask (rtu_ifu_dbg_mask ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_ifu_lockup_mask (rtu_ifu_lockup_mask ), + .rtu_ifu_lockup_req (rtu_ifu_lockup_req ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld), + .sysio_xx_halt_req (sysio_xx_halt_req ), + .vec_ctrl_reset_mask (vec_ctrl_reset_mask ), + .vec_ctrl_seq_mask (vec_ctrl_seq_mask ) +); + + +// ID Stage Prediction Module +// &Instance("pa_ifu_id_pred"); @51 +pa_ifu_id_pred x_pa_ifu_id_pred ( + .bht_top_cur_st (bht_top_cur_st ), + .cp0_ifu_bht_en (cp0_ifu_bht_en ), + .cp0_ifu_bht_inv (cp0_ifu_bht_inv ), + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_ras_en (cp0_ifu_ras_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dtu_ifu_halt_info0 (dtu_ifu_halt_info0 ), + .dtu_ifu_halt_info1 (dtu_ifu_halt_info1 ), + .forever_cpuclk (forever_cpuclk ), + .ibuf_id_pred_hungry (ibuf_id_pred_hungry ), + .ibuf_ipack_stall (ibuf_ipack_stall ), + .ibuf_pred_stall (ibuf_pred_stall ), + .id_pred_btb_cur_pc (id_pred_btb_cur_pc ), + .id_pred_btb_mis_pred (id_pred_btb_mis_pred ), + .id_pred_btb_mis_predg (id_pred_btb_mis_predg ), + .id_pred_btb_tar_pc (id_pred_btb_tar_pc ), + .id_pred_btb_upd_vld (id_pred_btb_upd_vld ), + .id_pred_btb_upd_vldg (id_pred_btb_upd_vldg ), + .id_pred_ctrl_stall (id_pred_ctrl_stall ), + .id_pred_ibuf_br_taken0 (id_pred_ibuf_br_taken0 ), + .id_pred_ibuf_br_taken1 (id_pred_ibuf_br_taken1 ), + .id_pred_ibuf_chgflw_vld0 (id_pred_ibuf_chgflw_vld0 ), + .id_pred_ibuf_halt_info0 (id_pred_ibuf_halt_info0 ), + .id_pred_ibuf_halt_info1 (id_pred_ibuf_halt_info1 ), + .id_pred_ipack_chgflw_vld0 (id_pred_ipack_chgflw_vld0), + .id_pred_ipack_delay_stall (id_pred_ipack_delay_stall), + .id_pred_ipack_mask (id_pred_ipack_mask ), + .id_pred_ipack_ret_stall (id_pred_ipack_ret_stall ), + .id_pred_pcgen_chgflw_pc (id_pred_pcgen_chgflw_pc ), + .id_pred_pcgen_chgflw_vld (id_pred_pcgen_chgflw_vld ), + .id_pred_pcgen_inst_vld (id_pred_pcgen_inst_vld ), + .idu_ifu_x1 (idu_ifu_x1 ), + .ifu_cp0_bht_inv_done (ifu_cp0_bht_inv_done ), + .ifu_dtu_addr_vld0 (ifu_dtu_addr_vld0 ), + .ifu_dtu_addr_vld1 (ifu_dtu_addr_vld1 ), + .ifu_dtu_data_vld0 (ifu_dtu_data_vld0 ), + .ifu_dtu_data_vld1 (ifu_dtu_data_vld1 ), + .ifu_dtu_exe_addr0 (ifu_dtu_exe_addr0 ), + .ifu_dtu_exe_addr1 (ifu_dtu_exe_addr1 ), + .ifu_dtu_exe_data0 (ifu_dtu_exe_data0 ), + .ifu_dtu_exe_data1 (ifu_dtu_exe_data1 ), + .ifu_iu_ex1_pc_pred (ifu_iu_ex1_pc_pred ), + .ipack_id_pred_h0_create (ipack_id_pred_h0_create ), + .ipack_id_pred_h0_vld (ipack_id_pred_h0_vld ), + .ipack_id_pred_inst0 (ipack_id_pred_inst0 ), + .ipack_id_pred_inst0_expt (ipack_id_pred_inst0_expt ), + .ipack_id_pred_inst0_vld (ipack_id_pred_inst0_vld ), + .ipack_id_pred_inst1 (ipack_id_pred_inst1 ), + .ipack_id_pred_inst1_expt (ipack_id_pred_inst1_expt ), + .ipack_id_pred_inst1_vld (ipack_id_pred_inst1_vld ), + .ipack_id_pred_new_vld (ipack_id_pred_new_vld ), + .ipack_id_pred_unalign (ipack_id_pred_unalign ), + .iu_ifu_bht_cur_pc (iu_ifu_bht_cur_pc ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate ), + .iu_ifu_bht_pred (iu_ifu_bht_pred ), + .iu_ifu_bht_taken (iu_ifu_bht_taken ), + .iu_ifu_br_vld (iu_ifu_br_vld ), + .iu_ifu_br_vld_gate (iu_ifu_br_vld_gate ), + .iu_ifu_ind_link_vld (iu_ifu_ind_link_vld ), + .iu_ifu_link_vld (iu_ifu_link_vld ), + .iu_ifu_link_vld_gate (iu_ifu_link_vld_gate ), + .iu_ifu_pc_mispred (iu_ifu_pc_mispred ), + .iu_ifu_pc_mispred_gate (iu_ifu_pc_mispred_gate ), + .iu_ifu_ret_vld (iu_ifu_ret_vld ), + .iu_ifu_ret_vld_gate (iu_ifu_ret_vld_gate ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pcgen_id_pred_btb_tar_pc (pcgen_id_pred_btb_tar_pc ), + .pcgen_id_pred_btb_tar_vld (pcgen_id_pred_btb_tar_vld), + .pcgen_id_pred_flush_vld (pcgen_id_pred_flush_vld ), + .pcgen_id_pred_idpc (pcgen_id_pred_idpc ), + .pcgen_id_pred_ifpc (pcgen_id_pred_ifpc ), + .pred_top_delay_chgflw (pred_top_delay_chgflw ), + .pred_top_ras_st (pred_top_ras_st ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ) +); + + +// Vector Module +// &Instance("pa_ifu_vec"); @54 +pa_ifu_vec x_pa_ifu_vec ( + .cp0_ifu_icg_en (cp0_ifu_icg_en ), + .cp0_ifu_mtvec (cp0_ifu_mtvec ), + .cp0_ifu_rst_inv_done (cp0_ifu_rst_inv_done ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dtu_ifu_halt_on_reset (dtu_ifu_halt_on_reset ), + .forever_cpuclk (forever_cpuclk ), + .ifetch_vec_acc_err (ifetch_vec_acc_err ), + .ifetch_vec_cmplt (ifetch_vec_cmplt ), + .ifetch_vec_grant (ifetch_vec_grant ), + .ifetch_vec_idle (ifetch_vec_idle ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .ifu_cp0_rst_inv_req (ifu_cp0_rst_inv_req ), + .ifu_cp0_vec_err (ifu_cp0_vec_err ), + .ifu_cp0_vec_succeed (ifu_cp0_vec_succeed ), + .ifu_cp0_warm_up (ifu_cp0_warm_up ), + .ifu_fpu_warm_up (ifu_fpu_warm_up ), + .ifu_idu_warm_up (ifu_idu_warm_up ), + .ifu_iu_reset_vld (ifu_iu_reset_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .ifu_rtu_reset_halt_req (ifu_rtu_reset_halt_req ), + .ifu_rtu_warm_up (ifu_rtu_warm_up ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .ifu_xx_in_warm_up (ifu_xx_in_warm_up ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_ifu_lockup_expt_vld (rtu_ifu_lockup_expt_vld), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ), + .sysio_ifu_rst_addr_done (sysio_ifu_rst_addr_done), + .vec_ctrl_reset_mask (vec_ctrl_reset_mask ), + .vec_ctrl_seq_mask (vec_ctrl_seq_mask ), + .vec_ibuf_warm_up (vec_ibuf_warm_up ), + .vec_ifetch_data_fetch (vec_ifetch_data_fetch ), + .vec_ipack_inst_mask (vec_ipack_inst_mask ), + .vec_pcgen_chgflw_vld (vec_pcgen_chgflw_vld ), + .vec_pcgen_idle (vec_pcgen_idle ), + .vec_pcgen_inst_fetch (vec_pcgen_inst_fetch ), + .vec_pcgen_iu_chgflw (vec_pcgen_iu_chgflw ), + .vec_pcgen_pc_flop (vec_pcgen_pc_flop ), + .vec_pcgen_rst_vld (vec_pcgen_rst_vld ), + .vec_pcgen_tar_pc (vec_pcgen_tar_pc ), + .vec_top_cur_st (vec_top_cur_st ) +); + + +assign ifu_dtu_debug_info[26:0] = { + bht_top_cur_st[1:0], + pred_top_ras_st, + pred_top_delay_chgflw, + ibuf_top_id_stall, + ibuf_top_vld_num[2:0], + ipack_top_entry2_vld, + ipack_top_entry1_vld, + ipack_top_entry0_vld, + icache_top_uc_st, + icache_top_abort, + icache_top_ref_st[1:0], + icache_top_rd_vld, + ifetch_top_abt_st[1:0], + ifetch_top_cur_st[2:0], + pcgen_top_btb_tar_vld, + pcgen_top_buf_chgflw, + vec_top_cur_st[3:0] + }; + + +// &ModuleEnd; @253 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_vec.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_vec.v new file mode 100644 index 0000000000000000000000000000000000000000..0605ce48ad67ca1848341028204b9e29d2d1f930 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_ifu_vec.v @@ -0,0 +1,505 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_ifu_vec( + cp0_ifu_icg_en, + cp0_ifu_mtvec, + cp0_ifu_rst_inv_done, + cp0_yy_clk_en, + cpurst_b, + dtu_ifu_halt_on_reset, + forever_cpuclk, + ifetch_vec_acc_err, + ifetch_vec_cmplt, + ifetch_vec_grant, + ifetch_vec_idle, + ifu_clic_warm_up, + ifu_cp0_rst_inv_req, + ifu_cp0_vec_err, + ifu_cp0_vec_succeed, + ifu_cp0_warm_up, + ifu_fpu_warm_up, + ifu_idu_warm_up, + ifu_iu_reset_vld, + ifu_iu_warm_up, + ifu_lsu_warm_up, + ifu_rtu_reset_halt_req, + ifu_rtu_warm_up, + ifu_sysmap_rst_sample, + ifu_xx_in_warm_up, + pad_yy_icg_scan_en, + rtu_ifu_lockup_expt_vld, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vld, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + sysio_ifu_rst_addr_done, + vec_ctrl_reset_mask, + vec_ctrl_seq_mask, + vec_ibuf_warm_up, + vec_ifetch_data_fetch, + vec_ipack_inst_mask, + vec_pcgen_chgflw_vld, + vec_pcgen_idle, + vec_pcgen_inst_fetch, + vec_pcgen_iu_chgflw, + vec_pcgen_pc_flop, + vec_pcgen_rst_vld, + vec_pcgen_tar_pc, + vec_top_cur_st +); + +// &Ports; @24 +input cp0_ifu_icg_en; +input [31:0] cp0_ifu_mtvec; +input cp0_ifu_rst_inv_done; +input cp0_yy_clk_en; +input cpurst_b; +input dtu_ifu_halt_on_reset; +input forever_cpuclk; +input ifetch_vec_acc_err; +input ifetch_vec_cmplt; +input ifetch_vec_grant; +input ifetch_vec_idle; +input pad_yy_icg_scan_en; +input rtu_ifu_lockup_expt_vld; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_expt_int; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_int_hv; +input rtu_yy_xx_tail_int_vld; +input sysio_ifu_rst_addr_done; +output ifu_clic_warm_up; +output ifu_cp0_rst_inv_req; +output ifu_cp0_vec_err; +output ifu_cp0_vec_succeed; +output ifu_cp0_warm_up; +output ifu_fpu_warm_up; +output ifu_idu_warm_up; +output ifu_iu_reset_vld; +output ifu_iu_warm_up; +output ifu_lsu_warm_up; +output ifu_rtu_reset_halt_req; +output ifu_rtu_warm_up; +output ifu_sysmap_rst_sample; +output ifu_xx_in_warm_up; +output vec_ctrl_reset_mask; +output vec_ctrl_seq_mask; +output vec_ibuf_warm_up; +output vec_ifetch_data_fetch; +output vec_ipack_inst_mask; +output vec_pcgen_chgflw_vld; +output vec_pcgen_idle; +output vec_pcgen_inst_fetch; +output vec_pcgen_iu_chgflw; +output vec_pcgen_pc_flop; +output vec_pcgen_rst_vld; +output [31:0] vec_pcgen_tar_pc; +output [3 :0] vec_top_cur_st; + +// &Regs; @25 +reg [3 :0] vec_cur_state; +reg [3 :0] vec_next_state; +reg vector_rst_inv_ff; +reg [2 :0] warm_up_cnt; + +// &Wires; @26 +wire cp0_ifu_icg_en; +wire [31:0] cp0_ifu_mtvec; +wire cp0_ifu_rst_inv_done; +wire cp0_yy_clk_en; +wire cpurst_b; +wire dtu_ifu_halt_on_reset; +wire forever_cpuclk; +wire ifetch_vec_acc_err; +wire ifetch_vec_cmplt; +wire ifetch_vec_grant; +wire ifetch_vec_idle; +wire ifu_clic_warm_up; +wire ifu_cp0_rst_inv_req; +wire ifu_cp0_vec_err; +wire ifu_cp0_vec_succeed; +wire ifu_cp0_warm_up; +wire ifu_fpu_warm_up; +wire ifu_idu_warm_up; +wire ifu_iu_reset_vld; +wire ifu_iu_warm_up; +wire ifu_lsu_warm_up; +wire ifu_rtu_reset_halt_req; +wire ifu_rtu_warm_up; +wire ifu_sysmap_rst_sample; +wire ifu_xx_in_warm_up; +wire ifu_xx_warm_up_clk; +wire pad_yy_icg_scan_en; +wire rtu_ifu_lockup_expt_vld; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire sysio_ifu_rst_addr_done; +wire [31:0] vec_chgflw_pc; +wire vec_chgflw_vld; +wire vec_ctrl_reset_mask; +wire vec_ctrl_seq_mask; +wire vec_data_fetch; +wire vec_err_occur; +wire vec_ibuf_warm_up; +wire vec_ifetch_data_fetch; +wire vec_inst_fetch; +wire vec_ipack_inst_mask; +wire vec_pc_flop; +wire vec_pcgen_chgflw_vld; +wire vec_pcgen_idle; +wire vec_pcgen_inst_fetch; +wire vec_pcgen_iu_chgflw; +wire vec_pcgen_pc_flop; +wire vec_pcgen_rst_vld; +wire [31:0] vec_pcgen_tar_pc; +wire vec_rst_inv_req; +wire vec_seq_mask; +wire vec_sm_clk; +wire vec_sm_clk_en; +wire vec_sm_idle; +wire vec_sm_pcload; +wire vec_sm_reset; +wire vec_sm_vec_cmpt; +wire vec_sm_vec_err; +wire vec_sm_vec_pcg; +wire vec_sm_vec_prep; +wire vec_sm_vec_req; +wire vec_sm_vec_wfc; +wire vec_sm_warm_up; +wire [3 :0] vec_top_cur_st; +wire vec_warm_up_clk_en; +wire warm_up_cnt_done; + + +//========================================================== +// Branch History Table Module +// 1. Instance ICG Cell +// 2. Vector FSM +// 3. Reset Invalid Control +// 4. Generate Change Flow for non-vec and vec pc fetch +// 5. Generate vec table data fetch +// 6. Vector Error Handling +//========================================================== + +//------------------------------------------------ +// 1. Instance ICG Cell +//------------------------------------------------ +assign vec_sm_clk_en = rtu_yy_xx_expt_vld + | rtu_yy_xx_tail_int_vld + | ~vec_sm_idle + | rtu_yy_xx_dbgon + | vector_rst_inv_ff; + +// &Instance("gated_clk_cell","x_ifu_vec_sm_clk"); @47 +gated_clk_cell x_ifu_vec_sm_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vec_sm_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (vec_sm_clk_en ), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @48 +// .clk_out (vec_sm_clk), @49 +// .external_en (1'b0), @50 +// .global_en (cp0_yy_clk_en), @51 +// .local_en (vec_sm_clk_en), @52 +// .module_en (cp0_ifu_icg_en) @53 +// ); @54 + +assign vec_warm_up_clk_en = vec_sm_warm_up; +// &Instance("gated_clk_cell","x_ifu_warm_up_clk"); @57 +gated_clk_cell x_ifu_warm_up_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ifu_xx_warm_up_clk), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (vec_warm_up_clk_en), + .module_en (cp0_ifu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( .clk_in (forever_cpuclk), @58 +// .clk_out (ifu_xx_warm_up_clk), @59 +// .external_en (1'b0), @60 +// .global_en (cp0_yy_clk_en), @61 +// .local_en (vec_warm_up_clk_en), @62 +// .module_en (cp0_ifu_icg_en) @63 +// ); @64 + +//------------------------------------------------ +// 2. Vector FSM +// a. parameter define +// b. FSM implemetation +// c. FSM state signals +//------------------------------------------------ + +// a. parameter define +parameter RESET = 4'b0001; +parameter IDLE = 4'b0000; +parameter PC_LOAD = 4'b0010; +parameter VEC_LOAD = 4'b0011; +parameter VEC_PREP = 4'b0100; +parameter VEC_PCG = 4'b1100; +parameter VEC_REQ = 4'b0101; +parameter VEC_WFC = 4'b0110; +parameter VEC_CMPT = 4'b0111; +parameter VEC_ERR = 4'b1000; +parameter WARM_UP = 4'b1001; +parameter HALT = 4'b1010; + +// b. FSM implemetation +// State Description: +// RESET : Reset logic, for memory initial invalidation +// IDLE : Wait for rtu expt signal & send physical address req +// PC_LOAD : Deal with NON-VEC expt and Vector-INT inst fetch +// VEC_PREP : Vector table address acquire prepare +// VEC_PCG : Vector table address sync pcgen +// VEC_REQ : Vector table address acquire request +// VEC_WFC : Vector table address result waiting +// VEC_CMPT : Vector table address complete and start fetching inst. +// VEC_ERR : Vector table address error handling + +always @(posedge vec_sm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + vec_cur_state[3:0] <= RESET; + else if(rtu_yy_xx_dbgon) + vec_cur_state[3:0] <= IDLE; + else + vec_cur_state[3:0] <= vec_next_state[3:0]; +end + +// &CombBeg; @109 +always @( vec_cur_state[3:0] + or rtu_yy_xx_tail_int_vld + or rtu_yy_xx_expt_vld + or warm_up_cnt_done + or sysio_ifu_rst_addr_done + or dtu_ifu_halt_on_reset + or ifetch_vec_grant + or rtu_yy_xx_int_hv + or rtu_ifu_lockup_expt_vld + or cp0_ifu_rst_inv_done + or rtu_yy_xx_expt_int + or ifetch_vec_acc_err + or ifetch_vec_idle + or ifetch_vec_cmplt) +begin +case(vec_cur_state[3:0]) + RESET: + if(cp0_ifu_rst_inv_done & sysio_ifu_rst_addr_done) + vec_next_state[3:0] = WARM_UP; + else + vec_next_state[3:0] = RESET; + WARM_UP: + if(warm_up_cnt_done) + if(dtu_ifu_halt_on_reset) + vec_next_state[3:0] = HALT; + else + vec_next_state[3:0] = IDLE; + else + vec_next_state[3:0] = WARM_UP; + HALT: + vec_next_state[3:0] = IDLE; + IDLE: + if(rtu_yy_xx_expt_vld & ~rtu_ifu_lockup_expt_vld) + if(rtu_yy_xx_expt_int & rtu_yy_xx_int_hv) + vec_next_state[3:0] = VEC_PREP; + else + vec_next_state[3:0] = PC_LOAD; + else if(rtu_yy_xx_tail_int_vld) + if(rtu_yy_xx_int_hv) + vec_next_state[3:0] = VEC_PREP; + else + vec_next_state[3:0] = PC_LOAD; + else + vec_next_state[3:0] = IDLE; + PC_LOAD: + vec_next_state[3:0] = IDLE; + VEC_PREP: + if(ifetch_vec_idle) + vec_next_state[3:0] = VEC_PCG; + else + vec_next_state[3:0] = VEC_PREP; + VEC_PCG: + vec_next_state[3:0] = VEC_REQ; + VEC_REQ: + if(ifetch_vec_grant) + vec_next_state[3:0] = VEC_WFC; + else + vec_next_state[3:0] = VEC_REQ; + VEC_WFC: + if(ifetch_vec_cmplt) + if(ifetch_vec_acc_err) + vec_next_state[3:0] = VEC_ERR; + else + vec_next_state[3:0] = VEC_CMPT; + else + vec_next_state[3:0] = VEC_WFC; + VEC_CMPT: + vec_next_state[3:0] = IDLE; + VEC_ERR: + vec_next_state[3:0] = IDLE; + default: + vec_next_state[3:0] = IDLE; +endcase +// &CombEnd; @175 +end + +// c. FSM state signals +assign vec_sm_reset = vec_cur_state[3:0] == RESET; +assign vec_sm_warm_up = vec_cur_state[3:0] == WARM_UP; +assign vec_sm_idle = vec_cur_state[3:0] == IDLE; +assign vec_sm_pcload = vec_cur_state[3:0] == PC_LOAD; +assign vec_sm_vec_prep = vec_cur_state[3:0] == VEC_PREP; +assign vec_sm_vec_pcg = vec_cur_state[3:0] == VEC_PCG; +assign vec_sm_vec_req = vec_cur_state[3:0] == VEC_REQ; +assign vec_sm_vec_wfc = vec_cur_state[3:0] == VEC_WFC; +assign vec_sm_vec_cmpt = vec_cur_state[3:0] == VEC_CMPT; +assign vec_sm_vec_err = vec_cur_state[3:0] == VEC_ERR; + +//------------------------------------------------ +// 3. Reset Invalid Control +//------------------------------------------------ +// record reset state to generation a pulse req +always @(posedge vec_sm_clk or negedge cpurst_b) +begin + if(~cpurst_b) + vector_rst_inv_ff <= 1'b0; + else + vector_rst_inv_ff <= vec_sm_reset; +end + +assign vec_rst_inv_req = vec_sm_reset & ~vector_rst_inv_ff; + +always @(posedge ifu_xx_warm_up_clk or negedge cpurst_b) +begin + if(~cpurst_b) + warm_up_cnt[2:0] <= 3'b0; + else if(vec_sm_warm_up) + warm_up_cnt[2:0] <= warm_up_cnt[2:0] + 3'b1; + else + warm_up_cnt[2:0] <= warm_up_cnt[2:0]; +end + +assign warm_up_cnt_done = warm_up_cnt[2:0] == 3'b111; + +//------------------------------------------------ +// 4. Generate Change Flow for non-vec and vec pc fetch +//------------------------------------------------ +// chgflw vld when expt vld or pc load or vector error +assign vec_chgflw_vld = vec_sm_pcload; +assign vec_chgflw_pc[31:0] = cp0_ifu_mtvec[31:0]; + +//------------------------------------------------ +// 5. Generate vec table data fetch +// a. Update pcgen addr flop on vector prepare +// b. Mask ibuf inst fetch on vector prepare +// c. Date fetch request on vector request +// d. Flop chgflw pc on vector complete +// e. Vec Error Occur +//------------------------------------------------ + +// a. Update pcgen addr flop +//assign vec_addr_updt = vec_sm_vec_req ; + +// b. Mask ibuf sequential inst fetch +assign vec_seq_mask = vec_sm_vec_req | vec_sm_vec_wfc | vec_sm_vec_prep | vec_sm_vec_pcg; + +// c. Date fetch request on vector request +assign vec_data_fetch = vec_sm_vec_req; + +// d. Flop chgflw pc on vector complete +assign vec_pc_flop = vec_sm_vec_wfc & ifetch_vec_cmplt + & ~ifetch_vec_acc_err; + +// e. Chgflw pc to bju pcgen and fetch inst. +assign vec_inst_fetch = vec_sm_vec_cmpt; + +// e. Vec Error Occur +assign vec_err_occur = vec_sm_vec_wfc & ifetch_vec_cmplt + & ifetch_vec_acc_err; + +//========================================================== +// Rename for Output +//========================================================== + +// Output to pcgen +assign vec_pcgen_iu_chgflw = vec_chgflw_vld | vec_inst_fetch + | vec_sm_vec_err; + +assign vec_pcgen_chgflw_vld = vec_chgflw_vld | vec_sm_vec_pcg + | vec_sm_vec_err; +//assign vec_pcgen_addr_updt = vec_addr_updt; +assign vec_pcgen_inst_fetch = vec_inst_fetch; +assign vec_pcgen_pc_flop = vec_pc_flop; +assign vec_pcgen_rst_vld = vec_sm_reset; +assign vec_pcgen_tar_pc[31:0] = vec_chgflw_pc[31:0]; +assign vec_pcgen_idle = vec_sm_idle; + +// Output to ctrl +assign vec_ctrl_reset_mask = vec_sm_reset | vec_sm_warm_up; +assign vec_ctrl_seq_mask = vec_seq_mask; + +// Output to ifetch +assign vec_ifetch_data_fetch = vec_data_fetch; + +// Output to ibuf +assign vec_ibuf_warm_up = vec_sm_warm_up; + +// Output to vec +assign vec_ipack_inst_mask = vec_seq_mask; + +// Output to top +assign vec_top_cur_st[3:0] = vec_cur_state[3:0]; + +// Output to idu +assign ifu_idu_warm_up = vec_sm_warm_up; +assign ifu_iu_warm_up = vec_sm_warm_up; +assign ifu_lsu_warm_up = vec_sm_warm_up; +assign ifu_cp0_warm_up = vec_sm_warm_up; +assign ifu_rtu_warm_up = vec_sm_warm_up; +assign ifu_clic_warm_up = vec_sm_warm_up; + +// Output to IU +assign ifu_iu_reset_vld = vec_sm_reset; + +// Output to CP0 +assign ifu_cp0_rst_inv_req = vec_rst_inv_req; + +// Output to PMP +assign ifu_sysmap_rst_sample = vec_rst_inv_req; +// Output to rtu +assign ifu_rtu_reset_halt_req = vec_cur_state[3:0] == HALT; + +assign ifu_cp0_vec_succeed = vec_pc_flop; +assign ifu_cp0_vec_err = vec_err_occur; + +assign ifu_xx_in_warm_up = vec_sm_warm_up; +assign ifu_fpu_warm_up = vec_sm_warm_up; + +// &ModuleEnd; @321 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_1024x37.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_1024x37.v new file mode 100644 index 0000000000000000000000000000000000000000..5089e9d1a1e3f5422eedcc3304c9117af7f79ad2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_1024x37.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_1024x37( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [9 :0] A; +input CEN; +input CLK; +input [36:0] D; +input GWEN; +input [36:0] WEN; +output [36:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [9 :0] A; +wire CEN; +wire CLK; +wire [36:0] D; +wire GWEN; +wire [36:0] Q; +wire [36:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 10; +parameter DATA_WIDTH = 37; +parameter WE_WIDTH = 37; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + + //******************************************************** + //* FPGA memory * + //******************************************************** +// &Instance("pa_f_spsram_1024x37"); @43 +pa_f_spsram_1024x37 x_pa_f_spsram_1024x37 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_1024x37"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_128x43.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_128x43.v new file mode 100644 index 0000000000000000000000000000000000000000..ff328a7a0b09261f65bb542bc778086579431b51 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_128x43.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_128x43( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [6 :0] A; +input CEN; +input CLK; +input [42:0] D; +input GWEN; +input [42:0] WEN; +output [42:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [6 :0] A; +wire CEN; +wire CLK; +wire [42:0] D; +wire GWEN; +wire [42:0] Q; +wire [42:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 7; +parameter DATA_WIDTH = 43; +parameter WE_WIDTH = 43; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + + //******************************************************** + //* FPGA memory * + //******************************************************** +// &Instance("pa_f_spsram_128x43"); @43 +pa_f_spsram_128x43 x_pa_f_spsram_128x43 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_128x43"); @49 +// &Instance("pa_gsmc_spsram_128x43"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_256x41.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_256x41.v new file mode 100644 index 0000000000000000000000000000000000000000..704832c605637be7db12a62c3fc4ea581d2314d1 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_256x41.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_256x41( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [7 :0] A; +input CEN; +input CLK; +input [40:0] D; +input GWEN; +input [40:0] WEN; +output [40:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [7 :0] A; +wire CEN; +wire CLK; +wire [40:0] D; +wire GWEN; +wire [40:0] Q; +wire [40:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 8; +parameter DATA_WIDTH = 41; +parameter WE_WIDTH = 41; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + + //******************************************************** + //* FPGA memory * + //******************************************************** +// &Instance("pa_f_spsram_256x41"); @43 +pa_f_spsram_256x41 x_pa_f_spsram_256x41 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_256x41"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_32x47.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_32x47.v new file mode 100644 index 0000000000000000000000000000000000000000..562bb71b06f9bc1b3bedfac3126566a96833aae3 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_32x47.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_32x47( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [4 :0] A; +input CEN; +input CLK; +input [46:0] D; +input GWEN; +input [46:0] WEN; +output [46:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [4 :0] A; +wire CEN; +wire CLK; +wire [46:0] D; +wire GWEN; +wire [46:0] Q; +wire [46:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 5; +parameter DATA_WIDTH = 47; +parameter WE_WIDTH = 47; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_32x47"); @43 +pa_f_spsram_32x47 x_pa_f_spsram_32x47 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_32x47"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x16.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x16.v new file mode 100644 index 0000000000000000000000000000000000000000..6876b87027b4749da9060c9329a340c1ae2105ec --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x16.v @@ -0,0 +1,81 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_512x16( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [8 :0] A; +input CEN; +input CLK; +input [15:0] D; +input GWEN; +input [15:0] WEN; +output [15:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [8 :0] A; +wire CEN; +wire CLK; +wire [15:0] D; +wire GWEN; +wire [15:0] Q; +wire [15:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 9; +parameter DATA_WIDTH = 16; +parameter WE_WIDTH = 16; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + + //******************************************************** + //* FPGA memory * + //******************************************************** +// &Instance("pa_f_spsram_512x16"); @43 +pa_f_spsram_512x16 x_pa_f_spsram_512x16 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_512x16"); @49 +// &Instance("pa_gsmc_spsram_512x16"); @55 +// &Instance("pa_umc_spsram_512x16"); @67 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x39.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x39.v new file mode 100644 index 0000000000000000000000000000000000000000..c8fbcfdacd022e4686f4f09e3b231b88f08dfbcf --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x39.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_512x39( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [8 :0] A; +input CEN; +input CLK; +input [38:0] D; +input GWEN; +input [38:0] WEN; +output [38:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [8 :0] A; +wire CEN; +wire CLK; +wire [38:0] D; +wire GWEN; +wire [38:0] Q; +wire [38:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 9; +parameter DATA_WIDTH = 39; +parameter WE_WIDTH = 39; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_512x39"); @43 +pa_f_spsram_512x39 x_pa_f_spsram_512x39 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_512x39"); @49 +// &Instance("pa_umc_spsram_512x39"); @61 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x4.v new file mode 100644 index 0000000000000000000000000000000000000000..c3b0a9edc31ece5576c03ab0eb2998827b7dc234 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_512x4.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_512x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [8:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [8:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 9; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + + //******************************************************** + //* FPGA memory * + //******************************************************** +// &Instance("pa_f_spsram_512x4"); @43 +pa_f_spsram_512x4 x_pa_f_spsram_512x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_512x4"); @49 +// &Instance("pa_umc_spsram_512x4"); @61 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_64x45.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_64x45.v new file mode 100644 index 0000000000000000000000000000000000000000..4c2e0655e7fb1d38575064151a8d521e52598cd1 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/ifu/rtl/pa_spsram_64x45.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_64x45( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [5 :0] A; +input CEN; +input CLK; +input [44:0] D; +input GWEN; +input [44:0] WEN; +output [44:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [5 :0] A; +wire CEN; +wire CLK; +wire [44:0] D; +wire GWEN; +wire [44:0] Q; +wire [44:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 6; +parameter DATA_WIDTH = 45; +parameter WE_WIDTH = 45; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_64x45"); @43 +pa_f_spsram_64x45 x_pa_f_spsram_64x45 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_64x45"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/booth_code_33_bit.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/booth_code_33_bit.v new file mode 100644 index 0000000000000000000000000000000000000000..0d4d7a77feffe12f4985dc6650078730eca1317c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/booth_code_33_bit.v @@ -0,0 +1,100 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @21 +module booth_code_33_bit( + A, + code, + h, + product, + sn +); + +// &Ports; @22 +input [32:0] A; +input [2 :0] code; +output [1 :0] h; +output [32:0] product; +output sn; + +// &Regs; @23 +reg [1 :0] h; +reg [32:0] product; +reg sn; + +// &Wires; @24 +wire [32:0] A; +wire [2 :0] code; + + +parameter SRC_WIDTH = 33; + +// &CombBeg; @28 +always @( A[32:0] + or code[2:0]) +begin +case(code[2:0]) +3'b000 : product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'b0}}; +3'b001 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-1:0]}; +3'b010 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-1:0]}; +3'b011 : product[SRC_WIDTH-1:0] = {A[SRC_WIDTH-2:0],1'b0}; +3'b100 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-2:0],1'b0}; +3'b101 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-1:0]}; +3'b110 : product[SRC_WIDTH-1:0] = {~A[SRC_WIDTH-1:0]}; +3'b111 : product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'b0}}; +default: product[SRC_WIDTH-1:0] = {SRC_WIDTH{1'bx}}; +endcase +// &CombEnd; @40 +end + +// &CombBeg; @42 +always @( A[32] + or code[2:0]) +begin +case(code[2:0]) +3'b000 : sn = 1'b1; +3'b001 : sn = ~A[SRC_WIDTH-1]; +3'b010 : sn = ~A[SRC_WIDTH-1]; +3'b011 : sn = ~A[SRC_WIDTH-1]; +3'b100 : sn = A[SRC_WIDTH-1]; +3'b101 : sn = A[SRC_WIDTH-1]; +3'b110 : sn = A[SRC_WIDTH-1]; +3'b111 : sn = 1'b1; +default: sn = 1'bx; +endcase +// &CombEnd; @54 +end + +// &CombBeg; @56 +always @( code[2:0]) +begin +case(code[2:0]) +3'b000 : h[1:0] = 2'b00; +3'b001 : h[1:0] = 2'b00; +3'b010 : h[1:0] = 2'b00; +3'b011 : h[1:0] = 2'b00; +3'b100 : h[1:0] = 2'b10; +3'b101 : h[1:0] = 2'b01; +3'b110 : h[1:0] = 2'b01; +3'b111 : h[1:0] = 2'b00; +default: h[1:0] = {2{1'bx}}; +endcase +// &CombEnd; @68 +end + +// &ModuleEnd; @70 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/multiplier_33x33_partial.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/multiplier_33x33_partial.v new file mode 100644 index 0000000000000000000000000000000000000000..72b933f857605ef7cc8dd979bd5667c4807dd422 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/multiplier_33x33_partial.v @@ -0,0 +1,624 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module multiplier_33x33_partial( + mult_round, + mult_sub, + multiplicand, + multiplier, + result_0, + result_1 +); + +// &Ports; @21 +input [31:0] mult_round; +input mult_sub; +input [32:0] multiplicand; +input [32:0] multiplier; +output [68:0] result_0; +output [68:0] result_1; + +// &Regs; @22 + +// &Wires; @23 +wire [65:0] data_for_acc; +wire [34:0] data_for_code; +wire [65:0] ex1_c0_0; +wire [65:0] ex1_c0_1; +wire [65:0] ex1_c0_2; +wire [65:0] ex1_c0_3; +wire [65:0] ex1_c0_4; +wire [65:0] ex1_c0_5; +wire [65:0] ex1_c1_0; +wire [65:0] ex1_c1_1; +wire [65:0] ex1_c1_2; +wire [65:0] ex1_p0_0_0; +wire [65:0] ex1_p0_0_1; +wire [65:0] ex1_p0_0_2; +wire [65:0] ex1_p0_0_3; +wire [65:0] ex1_p0_0_cout; +wire [65:0] ex1_p0_0_xor; +wire [65:0] ex1_p0_1_0; +wire [65:0] ex1_p0_1_1; +wire [65:0] ex1_p0_1_2; +wire [65:0] ex1_p0_2_0; +wire [65:0] ex1_p0_2_1; +wire [65:0] ex1_p0_2_2; +wire [65:0] ex1_p0_3_0; +wire [65:0] ex1_p0_3_1; +wire [65:0] ex1_p0_3_2; +wire [65:0] ex1_p0_4_0; +wire [65:0] ex1_p0_4_1; +wire [65:0] ex1_p0_4_2; +wire [65:0] ex1_p0_5_0; +wire [65:0] ex1_p0_5_1; +wire [65:0] ex1_p0_5_2; +wire [65:0] ex1_p1_0_0; +wire [65:0] ex1_p1_0_1; +wire [65:0] ex1_p1_0_2; +wire [65:0] ex1_p1_0_3; +wire [65:0] ex1_p1_0_cout; +wire [65:0] ex1_p1_0_xor; +wire [65:0] ex1_p1_1_0; +wire [65:0] ex1_p1_1_1; +wire [65:0] ex1_p1_1_2; +wire [65:0] ex1_p1_1_3; +wire [65:0] ex1_p1_1_cout; +wire [65:0] ex1_p1_1_xor; +wire [65:0] ex1_p1_2_0; +wire [65:0] ex1_p1_2_1; +wire [65:0] ex1_p1_2_2; +wire [65:0] ex1_p1_2_3; +wire [65:0] ex1_p1_2_cout; +wire [65:0] ex1_p1_2_xor; +wire [66:0] ex1_p2_0_0; +wire [66:0] ex1_p2_0_1; +wire [66:0] ex1_p2_0_2; +wire [66:0] ex1_p2_1_0; +wire [66:0] ex1_p2_1_1; +wire [66:0] ex1_p2_1_2; +wire [65:0] ex1_s0_0; +wire [65:0] ex1_s0_1; +wire [65:0] ex1_s0_2; +wire [65:0] ex1_s0_3; +wire [65:0] ex1_s0_4; +wire [65:0] ex1_s0_5; +wire [65:0] ex1_s1_0; +wire [65:0] ex1_s1_1; +wire [65:0] ex1_s1_2; +wire [66:0] ex2_c2_0; +wire [66:0] ex2_c2_1; +wire [67:0] ex2_c3_0; +wire [66:0] ex2_p2_0_0; +wire [66:0] ex2_p2_0_1; +wire [66:0] ex2_p2_0_2; +wire [66:0] ex2_p2_1_0; +wire [66:0] ex2_p2_1_1; +wire [66:0] ex2_p2_1_2; +wire [67:0] ex2_p3_0_0; +wire [67:0] ex2_p3_0_1; +wire [67:0] ex2_p3_0_2; +wire [67:0] ex2_p3_0_3; +wire [67:0] ex2_p3_0_cout; +wire [67:0] ex2_p3_0_xor; +wire [66:0] ex2_s2_0; +wire [66:0] ex2_s2_1; +wire [67:0] ex2_s3_0; +wire [1 :0] h0; +wire [1 :0] h1; +wire [1 :0] h10; +wire [1 :0] h11; +wire [1 :0] h12; +wire [1 :0] h13; +wire [1 :0] h14; +wire [1 :0] h15; +wire [1 :0] h16; +wire [1 :0] h2; +wire [1 :0] h3; +wire [1 :0] h4; +wire [1 :0] h5; +wire [1 :0] h6; +wire [1 :0] h7; +wire [1 :0] h8; +wire [1 :0] h9; +wire [31:0] mult_round; +wire [32:0] mult_src; +wire mult_sub; +wire [32:0] multiplicand; +wire [32:0] multiplier; +wire [32:0] part_product0; +wire [32:0] part_product1; +wire [32:0] part_product10; +wire [32:0] part_product11; +wire [32:0] part_product12; +wire [32:0] part_product13; +wire [32:0] part_product14; +wire [32:0] part_product15; +wire [32:0] part_product16; +wire [32:0] part_product2; +wire [32:0] part_product3; +wire [32:0] part_product4; +wire [32:0] part_product5; +wire [32:0] part_product6; +wire [32:0] part_product7; +wire [32:0] part_product8; +wire [32:0] part_product9; +wire [68:0] result_0; +wire [68:0] result_1; +wire [16:0] sign_not; + + +parameter SRC0_WIDTH = 33; +parameter SRC1_WIDTH = 33; +parameter DST_WIDTH = 66; + +assign mult_src[SRC1_WIDTH-1:0] = mult_sub ? (~multiplier[SRC1_WIDTH-1:0]):multiplier[SRC1_WIDTH-1:0]; + +assign data_for_code[SRC1_WIDTH+1:0] = {mult_src[SRC1_WIDTH-1],mult_src[SRC1_WIDTH-1:0],1'b0}; + +assign data_for_acc[DST_WIDTH-1:0] = mult_sub ? + {{SRC1_WIDTH{multiplicand[SRC0_WIDTH-1]}},multiplicand[SRC0_WIDTH-1:0]} : + {DST_WIDTH{1'b0}}; + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit0"); @37 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit0 ( + .A (multiplicand[32:0] ), + .code (data_for_code[2:0] ), + .h (h0[1:0] ), + .product (part_product0[32:0]), + .sn (sign_not[0] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @38 +// .code(data_for_code[2:0]), @39 +// .product(part_product0[SRC0_WIDTH-1:0]), @40 +// .h(h0[1:0]), @41 +// .sn(sign_not[0])); @42 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit1"); @44 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit1 ( + .A (multiplicand[32:0] ), + .code (data_for_code[4:2] ), + .h (h1[1:0] ), + .product (part_product1[32:0]), + .sn (sign_not[1] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @45 +// .code(data_for_code[4:2]), @46 +// .product(part_product1[SRC0_WIDTH-1:0]), @47 +// .h(h1[1:0]), @48 +// .sn(sign_not[1])); @49 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit2"); @51 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit2 ( + .A (multiplicand[32:0] ), + .code (data_for_code[6:4] ), + .h (h2[1:0] ), + .product (part_product2[32:0]), + .sn (sign_not[2] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @52 +// .code(data_for_code[6:4]), @53 +// .product(part_product2[SRC0_WIDTH-1:0]), @54 +// .h(h2[1:0]), @55 +// .sn(sign_not[2])); @56 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit3"); @58 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit3 ( + .A (multiplicand[32:0] ), + .code (data_for_code[8:6] ), + .h (h3[1:0] ), + .product (part_product3[32:0]), + .sn (sign_not[3] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @59 +// .code(data_for_code[8:6]), @60 +// .product(part_product3[SRC0_WIDTH-1:0]), @61 +// .h(h3[1:0]), @62 +// .sn(sign_not[3])); @63 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit4"); @65 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit4 ( + .A (multiplicand[32:0] ), + .code (data_for_code[10:8]), + .h (h4[1:0] ), + .product (part_product4[32:0]), + .sn (sign_not[4] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @66 +// .code(data_for_code[10:8]), @67 +// .product(part_product4[SRC0_WIDTH-1:0]), @68 +// .h(h4[1:0]), @69 +// .sn(sign_not[4])); @70 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit5"); @72 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit5 ( + .A (multiplicand[32:0] ), + .code (data_for_code[12:10]), + .h (h5[1:0] ), + .product (part_product5[32:0] ), + .sn (sign_not[5] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @73 +// .code(data_for_code[12:10]), @74 +// .product(part_product5[SRC0_WIDTH-1:0]), @75 +// .h(h5[1:0]), @76 +// .sn(sign_not[5])); @77 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit6"); @79 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit6 ( + .A (multiplicand[32:0] ), + .code (data_for_code[14:12]), + .h (h6[1:0] ), + .product (part_product6[32:0] ), + .sn (sign_not[6] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @80 +// .code(data_for_code[14:12]), @81 +// .product(part_product6[SRC0_WIDTH-1:0]), @82 +// .h(h6[1:0]), @83 +// .sn(sign_not[6])); @84 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit7"); @86 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit7 ( + .A (multiplicand[32:0] ), + .code (data_for_code[16:14]), + .h (h7[1:0] ), + .product (part_product7[32:0] ), + .sn (sign_not[7] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @87 +// .code(data_for_code[16:14]), @88 +// .product(part_product7[SRC0_WIDTH-1:0]), @89 +// .h(h7[1:0]), @90 +// .sn(sign_not[7])); @91 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit8"); @93 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit8 ( + .A (multiplicand[32:0] ), + .code (data_for_code[18:16]), + .h (h8[1:0] ), + .product (part_product8[32:0] ), + .sn (sign_not[8] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @94 +// .code(data_for_code[18:16]), @95 +// .product(part_product8[SRC0_WIDTH-1:0]), @96 +// .h(h8[1:0]), @97 +// .sn(sign_not[8])); @98 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit9"); @100 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit9 ( + .A (multiplicand[32:0] ), + .code (data_for_code[20:18]), + .h (h9[1:0] ), + .product (part_product9[32:0] ), + .sn (sign_not[9] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @101 +// .code(data_for_code[20:18]), @102 +// .product(part_product9[SRC0_WIDTH-1:0]), @103 +// .h(h9[1:0]), @104 +// .sn(sign_not[9])); @105 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit10"); @107 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit10 ( + .A (multiplicand[32:0] ), + .code (data_for_code[22:20]), + .h (h10[1:0] ), + .product (part_product10[32:0]), + .sn (sign_not[10] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @108 +// .code(data_for_code[22:20]), @109 +// .product(part_product10[SRC0_WIDTH-1:0]), @110 +// .h(h10[1:0]), @111 +// .sn(sign_not[10])); @112 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit11"); @114 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit11 ( + .A (multiplicand[32:0] ), + .code (data_for_code[24:22]), + .h (h11[1:0] ), + .product (part_product11[32:0]), + .sn (sign_not[11] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @115 +// .code(data_for_code[24:22]), @116 +// .product(part_product11[SRC0_WIDTH-1:0]), @117 +// .h(h11[1:0]), @118 +// .sn(sign_not[11])); @119 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit12"); @121 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit12 ( + .A (multiplicand[32:0] ), + .code (data_for_code[26:24]), + .h (h12[1:0] ), + .product (part_product12[32:0]), + .sn (sign_not[12] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @122 +// .code(data_for_code[26:24]), @123 +// .product(part_product12[SRC0_WIDTH-1:0]), @124 +// .h(h12[1:0]), @125 +// .sn(sign_not[12])); @126 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit13"); @128 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit13 ( + .A (multiplicand[32:0] ), + .code (data_for_code[28:26]), + .h (h13[1:0] ), + .product (part_product13[32:0]), + .sn (sign_not[13] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @129 +// .code(data_for_code[28:26]), @130 +// .product(part_product13[SRC0_WIDTH-1:0]), @131 +// .h(h13[1:0]), @132 +// .sn(sign_not[13])); @133 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit14"); @135 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit14 ( + .A (multiplicand[32:0] ), + .code (data_for_code[30:28]), + .h (h14[1:0] ), + .product (part_product14[32:0]), + .sn (sign_not[14] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @136 +// .code(data_for_code[30:28]), @137 +// .product(part_product14[SRC0_WIDTH-1:0]), @138 +// .h(h14[1:0]), @139 +// .sn(sign_not[14])); @140 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit15"); @142 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit15 ( + .A (multiplicand[32:0] ), + .code (data_for_code[32:30]), + .h (h15[1:0] ), + .product (part_product15[32:0]), + .sn (sign_not[15] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @143 +// .code(data_for_code[32:30]), @144 +// .product(part_product15[SRC0_WIDTH-1:0]), @145 +// .h(h15[1:0]), @146 +// .sn(sign_not[15])); @147 + +// &Instance("booth_code_33_bit", "x_pa_dsp_mult_booth_code_33_bit16"); @149 +booth_code_33_bit x_pa_dsp_mult_booth_code_33_bit16 ( + .A (multiplicand[32:0] ), + .code (data_for_code[34:32]), + .h (h16[1:0] ), + .product (part_product16[32:0]), + .sn (sign_not[16] ) +); + +// &Connect(.A(multiplicand[SRC0_WIDTH-1:0]), @150 +// .code(data_for_code[34:32]), @151 +// .product(part_product16[SRC0_WIDTH-1:0]), @152 +// .h(h16[1:0]), @153 +// .sn(sign_not[16])); @154 + +//============================================================================= +// prepare for the the first compression +//============================================================================= + +assign ex1_p0_0_0[DST_WIDTH-1:0] = data_for_acc[DST_WIDTH-1:0]; +assign ex1_p0_0_1[DST_WIDTH-1:0] = { {30{1'b0}}, sign_not[0],{2{!sign_not[0]}},part_product0[SRC0_WIDTH-1:0]}; +assign ex1_p0_0_2[DST_WIDTH-1:0] = { {29{1'b0}},1'b1, sign_not[1], part_product1[SRC0_WIDTH-1:0], h0[1:0]}; +assign ex1_p0_0_3[DST_WIDTH-1:0] = { {SRC0_WIDTH-1{1'b0}}, h16[1:0],mult_round[31:0]}; + +assign ex1_p0_1_0[DST_WIDTH-1:0] = { {27{1'b0}},1'b1, sign_not[2], part_product2[SRC0_WIDTH-1:0], h1[1:0], { 2{1'b0}} }; +assign ex1_p0_1_1[DST_WIDTH-1:0] = { {25{1'b0}},1'b1, sign_not[3], part_product3[SRC0_WIDTH-1:0], h2[1:0], { 4{1'b0}} }; +assign ex1_p0_1_2[DST_WIDTH-1:0] = { {23{1'b0}},1'b1, sign_not[4], part_product4[SRC0_WIDTH-1:0], h3[1:0], { 6{1'b0}} }; + +assign ex1_p0_2_0[DST_WIDTH-1:0] = { {21{1'b0}},1'b1, sign_not[5], part_product5[SRC0_WIDTH-1:0], h4[1:0], { 8{1'b0}} }; +assign ex1_p0_2_1[DST_WIDTH-1:0] = { {19{1'b0}},1'b1, sign_not[6], part_product6[SRC0_WIDTH-1:0], h5[1:0], {10{1'b0}} }; +assign ex1_p0_2_2[DST_WIDTH-1:0] = { {17{1'b0}},1'b1, sign_not[7], part_product7[SRC0_WIDTH-1:0], h6[1:0], {12{1'b0}} }; + +assign ex1_p0_3_0[DST_WIDTH-1:0] = { {15{1'b0}},1'b1, sign_not[8], part_product8[SRC0_WIDTH-1:0], h7[1:0], {14{1'b0}} }; +assign ex1_p0_3_1[DST_WIDTH-1:0] = { {13{1'b0}},1'b1, sign_not[9], part_product9[SRC0_WIDTH-1:0], h8[1:0], {16{1'b0}} }; +assign ex1_p0_3_2[DST_WIDTH-1:0] = { {11{1'b0}},1'b1, sign_not[10], part_product10[SRC0_WIDTH-1:0],h9[1:0], {18{1'b0}} }; + +assign ex1_p0_4_0[DST_WIDTH-1:0] = { { 9{1'b0}},1'b1, sign_not[11], part_product11[SRC0_WIDTH-1:0],h10[1:0],{20{1'b0}} }; +assign ex1_p0_4_1[DST_WIDTH-1:0] = { { 7{1'b0}},1'b1, sign_not[12], part_product12[SRC0_WIDTH-1:0],h11[1:0],{22{1'b0}} }; +assign ex1_p0_4_2[DST_WIDTH-1:0] = { { 5{1'b0}},1'b1, sign_not[13], part_product13[SRC0_WIDTH-1:0],h12[1:0],{24{1'b0}} }; + +assign ex1_p0_5_0[DST_WIDTH-1:0] = { { 3{1'b0}},1'b1, sign_not[14], part_product14[SRC0_WIDTH-1:0],h13[1:0],{26{1'b0}} }; +assign ex1_p0_5_1[DST_WIDTH-1:0] = { { 1{1'b0}},1'b1, sign_not[15], part_product15[SRC0_WIDTH-1:0],h14[1:0],{28{1'b0}} }; +assign ex1_p0_5_2[DST_WIDTH-1:0] = { sign_not[16], part_product16[SRC0_WIDTH-1:0],h15[1:0],{30{1'b0}} }; + + +//=========== 19 src to 12 src==========// +assign ex1_p0_0_cout[DST_WIDTH-1:0] = (ex1_p0_0_0[DST_WIDTH-1:0] & ex1_p0_0_1[DST_WIDTH-1:0]) | + (ex1_p0_0_1[DST_WIDTH-1:0] & ex1_p0_0_2[DST_WIDTH-1:0]) | + (ex1_p0_0_0[DST_WIDTH-1:0] & ex1_p0_0_2[DST_WIDTH-1:0]) ; + +assign ex1_p0_0_xor[DST_WIDTH-1:0] = (ex1_p0_0_0[DST_WIDTH-1:0] ^ ex1_p0_0_1[DST_WIDTH-1:0]) ^ + (ex1_p0_0_2[DST_WIDTH-1:0] ^ ex1_p0_0_3[DST_WIDTH-1:0]); + +assign ex1_s0_0[DST_WIDTH-1:0] = ex1_p0_0_xor[DST_WIDTH-1:0]^ {ex1_p0_0_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c0_0[DST_WIDTH-1:0] = ex1_p0_0_xor[DST_WIDTH-1:0]& {ex1_p0_0_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p0_0_xor[DST_WIDTH-1:0]& ex1_p0_0_3[DST_WIDTH-1:0]); + +assign ex1_s0_1[DST_WIDTH-1:0] = ex1_p0_1_0[DST_WIDTH-1:0] ^ + ex1_p0_1_1[DST_WIDTH-1:0] ^ + ex1_p0_1_2[DST_WIDTH-1:0]; + +assign ex1_c0_1[DST_WIDTH-1:0] = ex1_p0_1_0[DST_WIDTH-1:0] & ex1_p0_1_1[DST_WIDTH-1:0] | + ex1_p0_1_0[DST_WIDTH-1:0] & ex1_p0_1_2[DST_WIDTH-1:0] | + ex1_p0_1_1[DST_WIDTH-1:0] & ex1_p0_1_2[DST_WIDTH-1:0]; + +assign ex1_s0_2[DST_WIDTH-1:0] = ex1_p0_2_0[DST_WIDTH-1:0] ^ + ex1_p0_2_1[DST_WIDTH-1:0] ^ + ex1_p0_2_2[DST_WIDTH-1:0]; + +assign ex1_c0_2[DST_WIDTH-1:0] = ex1_p0_2_0[DST_WIDTH-1:0] & ex1_p0_2_1[DST_WIDTH-1:0] | + ex1_p0_2_0[DST_WIDTH-1:0] & ex1_p0_2_2[DST_WIDTH-1:0] | + ex1_p0_2_1[DST_WIDTH-1:0] & ex1_p0_2_2[DST_WIDTH-1:0]; + +assign ex1_s0_3[DST_WIDTH-1:0] = ex1_p0_3_0[DST_WIDTH-1:0] ^ + ex1_p0_3_1[DST_WIDTH-1:0] ^ + ex1_p0_3_2[DST_WIDTH-1:0]; + +assign ex1_c0_3[DST_WIDTH-1:0] = ex1_p0_3_0[DST_WIDTH-1:0] & ex1_p0_3_1[DST_WIDTH-1:0] | + ex1_p0_3_0[DST_WIDTH-1:0] & ex1_p0_3_2[DST_WIDTH-1:0] | + ex1_p0_3_1[DST_WIDTH-1:0] & ex1_p0_3_2[DST_WIDTH-1:0]; + +assign ex1_s0_4[DST_WIDTH-1:0] = ex1_p0_4_0[DST_WIDTH-1:0] ^ + ex1_p0_4_1[DST_WIDTH-1:0] ^ + ex1_p0_4_2[DST_WIDTH-1:0]; + +assign ex1_c0_4[DST_WIDTH-1:0] = ex1_p0_4_0[DST_WIDTH-1:0] & ex1_p0_4_1[DST_WIDTH-1:0] | + ex1_p0_4_0[DST_WIDTH-1:0] & ex1_p0_4_2[DST_WIDTH-1:0] | + ex1_p0_4_1[DST_WIDTH-1:0] & ex1_p0_4_2[DST_WIDTH-1:0]; + +assign ex1_s0_5[DST_WIDTH-1:0] = ex1_p0_5_0[DST_WIDTH-1:0] ^ + ex1_p0_5_1[DST_WIDTH-1:0] ^ + ex1_p0_5_2[DST_WIDTH-1:0]; + +assign ex1_c0_5[DST_WIDTH-1:0] = ex1_p0_5_0[DST_WIDTH-1:0] & ex1_p0_5_1[DST_WIDTH-1:0] | + ex1_p0_5_0[DST_WIDTH-1:0] & ex1_p0_5_2[DST_WIDTH-1:0] | + ex1_p0_5_1[DST_WIDTH-1:0] & ex1_p0_5_2[DST_WIDTH-1:0]; +//============================================================================= +// prepare for the the second compression +//============================================================================= +assign ex1_p1_0_0[DST_WIDTH-1:0] = ex1_s0_0[DST_WIDTH-1:0]; +assign ex1_p1_0_1[DST_WIDTH-1:0] ={ex1_c0_0[DST_WIDTH-2:0],1'b0}; +assign ex1_p1_0_2[DST_WIDTH-1:0] = ex1_s0_1[DST_WIDTH-1:0]; +assign ex1_p1_0_3[DST_WIDTH-1:0] ={ex1_c0_1[DST_WIDTH-2:0],1'b0}; + +assign ex1_p1_1_0[DST_WIDTH-1:0] = ex1_s0_2[DST_WIDTH-1:0]; +assign ex1_p1_1_1[DST_WIDTH-1:0] ={ex1_c0_2[DST_WIDTH-2:0],1'b0}; +assign ex1_p1_1_2[DST_WIDTH-1:0] = ex1_s0_3[DST_WIDTH-1:0]; +assign ex1_p1_1_3[DST_WIDTH-1:0] ={ex1_c0_3[DST_WIDTH-2:0],1'b0}; + +assign ex1_p1_2_0[DST_WIDTH-1:0] = ex1_s0_4[DST_WIDTH-1:0]; +assign ex1_p1_2_1[DST_WIDTH-1:0] ={ex1_c0_4[DST_WIDTH-2:0],1'b0}; +assign ex1_p1_2_2[DST_WIDTH-1:0] = ex1_s0_5[DST_WIDTH-1:0]; +assign ex1_p1_2_3[DST_WIDTH-1:0] ={ex1_c0_5[DST_WIDTH-2:0],1'b0}; + +//=========== 12 src to 6 src==========// +assign ex1_p1_0_cout[DST_WIDTH-1:0] = (ex1_p1_0_0[DST_WIDTH-1:0] & ex1_p1_0_1[DST_WIDTH-1:0]) | + (ex1_p1_0_1[DST_WIDTH-1:0] & ex1_p1_0_2[DST_WIDTH-1:0]) | + (ex1_p1_0_0[DST_WIDTH-1:0] & ex1_p1_0_2[DST_WIDTH-1:0]) ; + +assign ex1_p1_0_xor[DST_WIDTH-1:0] = (ex1_p1_0_0[DST_WIDTH-1:0] ^ ex1_p1_0_1[DST_WIDTH-1:0]) ^ + (ex1_p1_0_2[DST_WIDTH-1:0] ^ ex1_p1_0_3[DST_WIDTH-1:0]); + +assign ex1_s1_0[DST_WIDTH-1:0] = ex1_p1_0_xor[DST_WIDTH-1:0]^ {ex1_p1_0_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c1_0[DST_WIDTH-1:0] = ex1_p1_0_xor[DST_WIDTH-1:0]& {ex1_p1_0_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p1_0_xor[DST_WIDTH-1:0]& ex1_p1_0_3[DST_WIDTH-1:0]); +//---------------------------------------------- +assign ex1_p1_1_cout[DST_WIDTH-1:0] = (ex1_p1_1_0[DST_WIDTH-1:0] & ex1_p1_1_1[DST_WIDTH-1:0]) | + (ex1_p1_1_1[DST_WIDTH-1:0] & ex1_p1_1_2[DST_WIDTH-1:0]) | + (ex1_p1_1_0[DST_WIDTH-1:0] & ex1_p1_1_2[DST_WIDTH-1:0]) ; + +assign ex1_p1_1_xor[DST_WIDTH-1:0] = (ex1_p1_1_0[DST_WIDTH-1:0] ^ ex1_p1_1_1[DST_WIDTH-1:0]) ^ + (ex1_p1_1_2[DST_WIDTH-1:0] ^ ex1_p1_1_3[DST_WIDTH-1:0]); + +assign ex1_s1_1[DST_WIDTH-1:0] = ex1_p1_1_xor[DST_WIDTH-1:0]^ {ex1_p1_1_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c1_1[DST_WIDTH-1:0] = ex1_p1_1_xor[DST_WIDTH-1:0]& {ex1_p1_1_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p1_1_xor[DST_WIDTH-1:0]& ex1_p1_1_3[DST_WIDTH-1:0]); +//---------------------------------------------- +assign ex1_p1_2_cout[DST_WIDTH-1:0] = (ex1_p1_2_0[DST_WIDTH-1:0] & ex1_p1_2_1[DST_WIDTH-1:0]) | + (ex1_p1_2_1[DST_WIDTH-1:0] & ex1_p1_2_2[DST_WIDTH-1:0]) | + (ex1_p1_2_0[DST_WIDTH-1:0] & ex1_p1_2_2[DST_WIDTH-1:0]) ; + +assign ex1_p1_2_xor[DST_WIDTH-1:0] = (ex1_p1_2_0[DST_WIDTH-1:0] ^ ex1_p1_2_1[DST_WIDTH-1:0]) ^ + (ex1_p1_2_2[DST_WIDTH-1:0] ^ ex1_p1_2_3[DST_WIDTH-1:0]); + +assign ex1_s1_2[DST_WIDTH-1:0] = ex1_p1_2_xor[DST_WIDTH-1:0]^ {ex1_p1_2_cout[DST_WIDTH-2:0],1'b0}; +assign ex1_c1_2[DST_WIDTH-1:0] = ex1_p1_2_xor[DST_WIDTH-1:0]& {ex1_p1_2_cout[DST_WIDTH-2:0],1'b0}| + (~ex1_p1_2_xor[DST_WIDTH-1:0]& ex1_p1_2_3[DST_WIDTH-1:0]); + +//============================================================================= +// prepare for the the third compression +//============================================================================= +assign ex1_p2_0_0[DST_WIDTH:0] ={ex1_s1_0[DST_WIDTH-1],ex1_s1_0[DST_WIDTH-1:0]}; //all valid +assign ex1_p2_0_1[DST_WIDTH:0] ={ex1_c1_0[DST_WIDTH-1:0],1'b0}; //all valid +assign ex1_p2_0_2[DST_WIDTH:0] ={ex1_s1_1[DST_WIDTH-1],ex1_s1_1[DST_WIDTH-1:0]}; //11-bit 8-bit + +assign ex1_p2_1_0[DST_WIDTH:0] ={ex1_c1_1[DST_WIDTH-1:0],1'b0}; //11-bit 8-bit +assign ex1_p2_1_1[DST_WIDTH:0] ={ex1_s1_2[DST_WIDTH-1],ex1_s1_2[DST_WIDTH-1:0]}; //0-bit 20-bit +assign ex1_p2_1_2[DST_WIDTH:0] ={ex1_c1_2[DST_WIDTH-1:0],1'b0}; //0-bit 20-bit + +assign ex2_p2_0_0[DST_WIDTH:0] = ex1_p2_0_0[DST_WIDTH:0]; +assign ex2_p2_0_1[DST_WIDTH:0] = ex1_p2_0_1[DST_WIDTH:0]; +assign ex2_p2_0_2[DST_WIDTH:0] = ex1_p2_0_2[DST_WIDTH:0]; +assign ex2_p2_1_0[DST_WIDTH:0] = ex1_p2_1_0[DST_WIDTH:0]; +assign ex2_p2_1_1[DST_WIDTH:0] = ex1_p2_1_1[DST_WIDTH:0]; +assign ex2_p2_1_2[DST_WIDTH:0] = ex1_p2_1_2[DST_WIDTH:0]; + +//=========== 6 src to 4 src==========// +assign ex2_s2_0[DST_WIDTH:0] = ex2_p2_0_0[DST_WIDTH:0] ^ + ex2_p2_0_1[DST_WIDTH:0] ^ + ex2_p2_0_2[DST_WIDTH:0]; + +assign ex2_c2_0[DST_WIDTH:0] = ex2_p2_0_0[DST_WIDTH:0] & ex2_p2_0_1[DST_WIDTH:0] | + ex2_p2_0_0[DST_WIDTH:0] & ex2_p2_0_2[DST_WIDTH:0] | + ex2_p2_0_1[DST_WIDTH:0] & ex2_p2_0_2[DST_WIDTH:0]; + +assign ex2_s2_1[DST_WIDTH:0] = ex2_p2_1_0[DST_WIDTH:0] ^ + ex2_p2_1_1[DST_WIDTH:0] ^ + ex2_p2_1_2[DST_WIDTH:0]; + +assign ex2_c2_1[DST_WIDTH:0] = ex2_p2_1_0[DST_WIDTH:0] & ex2_p2_1_1[DST_WIDTH:0] | + ex2_p2_1_0[DST_WIDTH:0] & ex2_p2_1_2[DST_WIDTH:0] | + ex2_p2_1_1[DST_WIDTH:0] & ex2_p2_1_2[DST_WIDTH:0]; + +//============================================================================= +// prepare for the fourth compression +//============================================================================= +assign ex2_p3_0_0[DST_WIDTH+1:0] ={ex2_s2_0[DST_WIDTH],ex2_s2_0[DST_WIDTH:0]}; //0_1_6 +assign ex2_p3_0_1[DST_WIDTH+1:0] ={ex2_c2_0[DST_WIDTH:0],1'b0}; +assign ex2_p3_0_2[DST_WIDTH+1:0] ={ex2_s2_1[DST_WIDTH],ex2_s2_1[DST_WIDTH:0]}; +assign ex2_p3_0_3[DST_WIDTH+1:0] ={ex2_c2_1[DST_WIDTH:0],1'b0}; //24_35_36 + +//=========== 4 src to 2 src==========// +assign ex2_p3_0_cout[DST_WIDTH+1:0] = (ex2_p3_0_0[DST_WIDTH+1:0] & ex2_p3_0_1[DST_WIDTH+1:0]) | + (ex2_p3_0_1[DST_WIDTH+1:0] & ex2_p3_0_2[DST_WIDTH+1:0]) | + (ex2_p3_0_0[DST_WIDTH+1:0] & ex2_p3_0_2[DST_WIDTH+1:0]) ; + +assign ex2_p3_0_xor[DST_WIDTH+1:0] = (ex2_p3_0_0[DST_WIDTH+1:0] ^ ex2_p3_0_1[DST_WIDTH+1:0]) ^ + (ex2_p3_0_2[DST_WIDTH+1:0] ^ ex2_p3_0_3[DST_WIDTH+1:0]); + +assign ex2_s3_0[DST_WIDTH+1:0] = ex2_p3_0_xor[DST_WIDTH+1:0]^ {ex2_p3_0_cout[DST_WIDTH:0],1'b0}; +assign ex2_c3_0[DST_WIDTH+1:0] = ex2_p3_0_xor[DST_WIDTH+1:0]& {ex2_p3_0_cout[DST_WIDTH:0],1'b0}| + (~ex2_p3_0_xor[DST_WIDTH+1:0]& ex2_p3_0_3[DST_WIDTH+1:0]); + +assign result_0[DST_WIDTH+2:0] ={ex2_s3_0[DST_WIDTH+1],ex2_s3_0[DST_WIDTH+1:0]}; +assign result_1[DST_WIDTH+2:0] ={ex2_c3_0[DST_WIDTH+1],ex2_c3_0[DST_WIDTH:0],1'b0}; + +// &ModuleEnd; @347 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_addr_gen.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_addr_gen.v new file mode 100644 index 0000000000000000000000000000000000000000..586ea54f71ed73f45d163efaf89322368e788ace --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_addr_gen.v @@ -0,0 +1,119 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_addr_gen( + ag_bju_pc, + ag_dp_ex1_dst_preg, + ag_dp_ex1_fwd_data, + ag_dp_ex1_fwd_vld, + idu_iu_ex1_ag_imm, + idu_iu_ex1_bju_sel, + idu_iu_ex1_bju_use_pc, + idu_iu_ex1_src0, + iu_ex1_cur_pc, + iu_idu_ex1_src1_update_value, + iu_lsu_ex1_lsi_rst, + lsu_iu_ex1_base_wb, + lsu_iu_ex1_src1_sel +); + +// &Ports; @24 +input [31:0] idu_iu_ex1_ag_imm; +input idu_iu_ex1_bju_sel; +input idu_iu_ex1_bju_use_pc; +input [31:0] idu_iu_ex1_src0; +input [31:0] iu_ex1_cur_pc; +input lsu_iu_ex1_base_wb; +input lsu_iu_ex1_src1_sel; +output [31:0] ag_bju_pc; +output [5 :0] ag_dp_ex1_dst_preg; +output [31:0] ag_dp_ex1_fwd_data; +output ag_dp_ex1_fwd_vld; +output [31:0] iu_idu_ex1_src1_update_value; +output [31:0] iu_lsu_ex1_lsi_rst; + +// &Regs; @25 + +// &Wires; @26 +wire [31:0] ag_adder_res; +wire [31:0] ag_adder_rs1; +wire [31:0] ag_adder_rs1_raw; +wire [31:0] ag_adder_rs2; +wire [31:0] ag_bju_pc; +wire [5 :0] ag_dp_ex1_dst_preg; +wire [31:0] ag_dp_ex1_fwd_data; +wire ag_dp_ex1_fwd_vld; +wire ag_rs1_use_pc; +wire [31:0] idu_iu_ex1_ag_imm; +wire idu_iu_ex1_bju_sel; +wire idu_iu_ex1_bju_use_pc; +wire [31:0] idu_iu_ex1_src0; +wire [31:0] iu_ex1_cur_pc; +wire [31:0] iu_idu_ex1_src1_update_value; +wire [31:0] iu_lsu_ex1_lsi_rst; +wire lsu_iu_ex1_base_wb; + + +//========================================================== +// Address Generator +//========================================================== +// Address Generator generate address for: +// 1. jump, branch inst; +// 2. auipc inst; +// 3. LSU address. + +//---------------------------------------------------------- +// BJU Address Generator +//---------------------------------------------------------- +//----------- Oper Prepare ------------- +// branch inst, auipc inst use pc as rs1. +assign ag_adder_rs1_raw[31:0] = {32{idu_iu_ex1_bju_sel || lsu_iu_ex1_base_wb}} & idu_iu_ex1_src0[31:0]; +// idu_iu_ex1_bju_use_pc will be set when ex1_bju_sel. +assign ag_rs1_use_pc = idu_iu_ex1_bju_use_pc; +assign ag_adder_rs1[31:0] = ag_rs1_use_pc ? {iu_ex1_cur_pc[31:1], 1'b0} + : ag_adder_rs1_raw[31:0]; + +// &Force("bus", "iu_ex1_cur_pc", 31, 0); @53 + +// dcache_pa inst's address is in rs1. rs2 should be zero rather than ag_imm, +// which is opcode for illegal inst expt. +assign ag_adder_rs2[31:0] = {32{idu_iu_ex1_bju_sel || lsu_iu_ex1_base_wb}} & idu_iu_ex1_ag_imm[31:0]; + +//-------------- Adder ----------------- +assign ag_adder_res[31:0] = ag_adder_rs1[31:0] + ag_adder_rs2[31:0]; + +//---------- Rename for output --------- +assign ag_bju_pc[31:0] = {ag_adder_res[31:1], 1'b0}; + +assign iu_idu_ex1_src1_update_value[31:0] = ag_adder_res[31:0]; + +assign iu_lsu_ex1_lsi_rst[31:0] = ag_dp_ex1_fwd_data[31:0]; + +// &Force("output", "ag_dp_ex1_fwd_data"); @75 +// &Force("bus", "idu_iu_ex1_src0_reg", 5, 0); @84 +// &Force("input", "lsu_iu_ex1_lsi_dp"); @90 +// &Force("input", "lsu_iu_ex1_lsi_dst_reg"); @91 +// &Force("bus", "lsu_iu_ex1_lsi_dst_reg", 5, 0); @92 +// &Force("input", "lsu_iu_ex1_src1_sel"); @94 +assign ag_dp_ex1_fwd_vld = 1'b0; +assign ag_dp_ex1_dst_preg[5:0] = {6{1'bx}}; +assign ag_dp_ex1_fwd_data[31:0] = {32{1'bx}}; + + +// &ModuleEnd; @102 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_alu.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_alu.v new file mode 100644 index 0000000000000000000000000000000000000000..06f160138931c28cd316845d8f08d5338a608596 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_alu.v @@ -0,0 +1,410 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_iu_alu( + alu_dp_ex1_cmplt, + alu_dp_ex1_cmplt_dp, + alu_dp_ex1_fwd_vld, + alu_dp_ex1_rslt, + dp_xx_ex1_stall, + idu_iu_ex1_alu_cmplt_dp_sel, + idu_iu_ex1_alu_gateclk_sel, + idu_iu_ex1_alu_sel, + idu_iu_ex1_func, + idu_iu_ex1_inst_vld, + idu_iu_ex1_src0, + idu_iu_ex1_src1 +); + +// &Ports; @26 +input dp_xx_ex1_stall; +input idu_iu_ex1_alu_cmplt_dp_sel; +input idu_iu_ex1_alu_gateclk_sel; +input idu_iu_ex1_alu_sel; +input [19:0] idu_iu_ex1_func; +input idu_iu_ex1_inst_vld; +input [31:0] idu_iu_ex1_src0; +input [31:0] idu_iu_ex1_src1; +output alu_dp_ex1_cmplt; +output alu_dp_ex1_cmplt_dp; +output alu_dp_ex1_fwd_vld; +output [31:0] alu_dp_ex1_rslt; + +// &Regs; @27 +reg [31:0] alu_shifter_res_raw; + +// &Wires; @28 +wire [31:0] alu_adder_add_res; +wire alu_adder_c_in; +wire alu_adder_c_out_raw; +wire [31:0] alu_adder_comp_res; +wire alu_adder_comp_rslt; +wire [31:0] alu_adder_minmax_res; +wire alu_adder_oper_add; +wire alu_adder_oper_addsl; +wire alu_adder_oper_comp; +wire alu_adder_oper_max; +wire alu_adder_oper_minmax; +wire alu_adder_oper_signed; +wire [31:0] alu_adder_res; +wire [31:0] alu_adder_res_raw; +wire alu_adder_res_signed_lt; +wire alu_adder_res_unsigned_lt; +wire [31:0] alu_adder_rs1; +wire [31:0] alu_adder_rs2; +wire [31:0] alu_adder_rs2_raw; +wire [31:0] alu_adder_rs2_shift; +wire alu_adder_sel; +wire [31:0] alu_adder_slt_res; +wire [4 :0] alu_adder_sub_func; +wire [31:0] alu_bitop_rst; +wire alu_dp_ex1_cmplt; +wire alu_dp_ex1_cmplt_dp; +wire alu_dp_ex1_fwd_vld; +wire [31:0] alu_dp_ex1_rslt; +wire [31:0] alu_logic_and_res; +wire [31:0] alu_logic_or_res; +wire [31:0] alu_logic_res; +wire [31:0] alu_logic_rs1; +wire [31:0] alu_logic_rs2; +wire [31:0] alu_logic_rs2_raw; +wire alu_logic_sel; +wire [4 :0] alu_logic_sub_func; +wire [31:0] alu_logic_xor_res; +wire alu_minmax_sel_rs1; +wire [31:0] alu_pack_encry_rst; +wire [31:0] alu_pack_mov_rst; +wire alu_pack_pack_inst; +wire [31:0] alu_pack_rs1; +wire [31:0] alu_pack_rs2; +wire [31:0] alu_pack_rst; +wire alu_pack_sel; +wire [4 :0] alu_pack_sub_func; +wire [31:0] alu_packh_rst; +wire [31:0] alu_packhl_rst; +wire [31:0] alu_packl_rst; +wire [31:0] alu_res; +wire [4 :0] alu_sel; +wire alu_shifter_dir_right; +wire [31:0] alu_shifter_ext_rst; +wire alu_shifter_inst_ext; +wire alu_shifter_inst_sll; +wire alu_shifter_inst_sra; +wire [31:0] alu_shifter_res; +wire [31:0] alu_shifter_res_raw_rev; +wire [31:0] alu_shifter_res_tmp; +wire [31:0] alu_shifter_rs1; +wire [31:0] alu_shifter_rs1_raw; +wire [31:0] alu_shifter_rs1_raw_rev; +wire [9 :0] alu_shifter_rs2; +wire alu_shifter_sel; +wire alu_shifter_shift_in; +wire [4 :0] alu_shifter_sub_func; +wire dp_xx_ex1_stall; +wire idu_iu_ex1_alu_cmplt_dp_sel; +wire idu_iu_ex1_alu_sel; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_inst_vld; +wire [31:0] idu_iu_ex1_src0; +wire [31:0] idu_iu_ex1_src1; + + +// &Force("bus","idu_iu_ex1_func",19,0); @30 +assign alu_sel[4:0] = idu_iu_ex1_func[9:5] & {5{idu_iu_ex1_alu_sel}}; +//========================================================== +// Adder +//========================================================== +//----------- Operation Type ----------- +// &Force("bus", "idu_iu_ex1_ag_imm", 31, 0); @36 +assign alu_adder_sel = alu_sel[0]; +assign alu_adder_rs1[31:0] = {32{alu_adder_sel}} & idu_iu_ex1_src0[31:0]; +assign alu_adder_rs2_raw[31:0] = {32{alu_adder_sel}} & idu_iu_ex1_src1[31:0]; +assign alu_adder_sub_func[4:0] = { 5{alu_adder_sel}} & idu_iu_ex1_func[4:0]; + +assign alu_adder_oper_add = alu_adder_sub_func[0]; // sub_func[0]: 0-add, 1-sub. +assign alu_adder_oper_comp = alu_adder_sub_func[1]; // sub_func[1]: 0-compare, 1-arithmetic. +assign alu_adder_oper_minmax = alu_adder_sub_func[2]; // sub_func[2]: 0-not min_max, 1-min_max. +assign alu_adder_oper_max = alu_adder_sub_func[3]; // sub_func[3]: 0-min, 1-max. +assign alu_adder_oper_signed = alu_adder_sub_func[4]; // sub_func[4]: 0-unsigned compare, 1-signed compare. +assign alu_adder_oper_addsl = 1'b0; +assign alu_adder_rs2_shift[31:0] = 32'b0; + +// &Force("input","idu_iu_ex1_alu_gateclk_sel"); @57 +//---------- Operand Generate ---------- +// If operation is not add (sub, compare), rs2 = ~rs2 + 1. +// ADDSL : rs2 : rs2_raw >> imm2 + +assign alu_adder_rs2[31:0] = alu_adder_oper_addsl ? alu_adder_rs2_shift[31:0] : + alu_adder_oper_add ? alu_adder_rs2_raw[31:0] + : ~alu_adder_rs2_raw[31:0]; +assign alu_adder_c_in = !alu_adder_oper_add; + + +//------------- Main Adder ------------- +assign {alu_adder_c_out_raw, alu_adder_res_raw[31:0]} = + {1'b0, alu_adder_rs1[31:0]} + {1'b0, alu_adder_rs2[31:0]} + {32'b0, alu_adder_c_in}; + +//---------- Result Generate ----------- +assign alu_adder_res_signed_lt = + (alu_adder_rs1[31] & alu_adder_rs2[31]) + | ((alu_adder_rs1[31] ^ alu_adder_rs2[31]) & alu_adder_res_raw[31]); +assign alu_adder_res_unsigned_lt = !alu_adder_c_out_raw; + +// alu_adder_comp_rslt means rs1 < rs2. +assign alu_adder_comp_rslt = alu_adder_oper_signed ? alu_adder_res_signed_lt + : alu_adder_res_unsigned_lt; + +assign alu_adder_add_res[31:0] = alu_adder_res_raw[31:0]; +assign alu_adder_comp_res[31:0] = alu_adder_oper_minmax ? alu_adder_minmax_res[31:0] + : alu_adder_slt_res[31:0]; + +assign alu_adder_slt_res[31:0] = {31'b0, alu_adder_comp_rslt}; + +assign alu_minmax_sel_rs1 = alu_adder_oper_max ^ alu_adder_comp_rslt; + +assign alu_adder_minmax_res[31:0] = alu_minmax_sel_rs1 ? alu_adder_rs1[31:0] + : alu_adder_rs2_raw[31:0]; + +assign alu_adder_res[31:0] = alu_adder_oper_comp ? alu_adder_comp_res[31:0] + : alu_adder_add_res[31:0]; + +//========================================================== +// Shifter +//========================================================== +// Only have one RIGHT-SHIFTER, which shift-in can be either 0 or 1. +assign alu_shifter_sel = alu_sel[1]; +assign alu_shifter_rs1_raw[31:0] = {32{alu_shifter_sel}} & idu_iu_ex1_src0[31:0]; +assign alu_shifter_rs2[9:0] = { 10{alu_shifter_sel}} & idu_iu_ex1_src1[9:0]; +assign alu_shifter_sub_func[4:0] = { 5{alu_shifter_sel}} & idu_iu_ex1_func[4:0]; + +assign alu_shifter_inst_sll = alu_shifter_sub_func[0] && !alu_shifter_sub_func[4]; +//assign alu_shifter_inst_srl = alu_shifter_sub_func[1]; +assign alu_shifter_inst_sra = alu_shifter_sub_func[2]; +//assign alu_shifter_inst_srri = 1'b0; +assign alu_shifter_inst_ext = 1'b0; +// &Force("nonport", "alu_shifter_inst_sll"); @115 + +assign alu_shifter_dir_right = !alu_shifter_inst_sll; + +// Reversal LEFT-SHIFT oprand. +assign alu_shifter_rs1_raw_rev[31:0] = {alu_shifter_rs1_raw[0], alu_shifter_rs1_raw[1], + alu_shifter_rs1_raw[2], alu_shifter_rs1_raw[3], + alu_shifter_rs1_raw[4], alu_shifter_rs1_raw[5], + alu_shifter_rs1_raw[6], alu_shifter_rs1_raw[7], + alu_shifter_rs1_raw[8], alu_shifter_rs1_raw[9], + alu_shifter_rs1_raw[10], alu_shifter_rs1_raw[11], + alu_shifter_rs1_raw[12], alu_shifter_rs1_raw[13], + alu_shifter_rs1_raw[14], alu_shifter_rs1_raw[15], + alu_shifter_rs1_raw[16], alu_shifter_rs1_raw[17], + alu_shifter_rs1_raw[18], alu_shifter_rs1_raw[19], + alu_shifter_rs1_raw[20], alu_shifter_rs1_raw[21], + alu_shifter_rs1_raw[22], alu_shifter_rs1_raw[23], + alu_shifter_rs1_raw[24], alu_shifter_rs1_raw[25], + alu_shifter_rs1_raw[26], alu_shifter_rs1_raw[27], + alu_shifter_rs1_raw[28], alu_shifter_rs1_raw[29], + alu_shifter_rs1_raw[30], alu_shifter_rs1_raw[31]}; + +assign alu_shifter_rs1[31:0] = alu_shifter_dir_right ? alu_shifter_rs1_raw[31:0] + : alu_shifter_rs1_raw_rev[31:0]; + +assign alu_shifter_shift_in = alu_shifter_inst_sra && alu_shifter_rs1_raw[31]; + +// &CombBeg; @147 +// &CombEnd; @183 +// &CombBeg; @185 +// &CombEnd; @221 +//-------------- Right Shifter---------- + +// &CombBeg; @237 +always @( alu_shifter_rs2[4:0] + or alu_shifter_rs1[31:0] + or alu_shifter_shift_in) +begin + case(alu_shifter_rs2[4:0]) + 5'b00000: + alu_shifter_res_raw[31:0] = alu_shifter_rs1[31:0]; + 5'b00001: + alu_shifter_res_raw[31:0] = {{ 1{alu_shifter_shift_in}}, alu_shifter_rs1[31:1]}; + 5'b00010: + alu_shifter_res_raw[31:0] = {{ 2{alu_shifter_shift_in}}, alu_shifter_rs1[31:2]}; + 5'b00011: + alu_shifter_res_raw[31:0] = {{ 3{alu_shifter_shift_in}}, alu_shifter_rs1[31:3]}; + 5'b00100: + alu_shifter_res_raw[31:0] = {{ 4{alu_shifter_shift_in}}, alu_shifter_rs1[31:4]}; + 5'b00101: + alu_shifter_res_raw[31:0] = {{ 5{alu_shifter_shift_in}}, alu_shifter_rs1[31:5]}; + 5'b00110: + alu_shifter_res_raw[31:0] = {{ 6{alu_shifter_shift_in}}, alu_shifter_rs1[31:6]}; + 5'b00111: + alu_shifter_res_raw[31:0] = {{ 7{alu_shifter_shift_in}}, alu_shifter_rs1[31:7]}; + 5'b01000: + alu_shifter_res_raw[31:0] = {{ 8{alu_shifter_shift_in}}, alu_shifter_rs1[31:8]}; + 5'b01001: + alu_shifter_res_raw[31:0] = {{ 9{alu_shifter_shift_in}}, alu_shifter_rs1[31:9]}; + 5'b01010: + alu_shifter_res_raw[31:0] = {{10{alu_shifter_shift_in}}, alu_shifter_rs1[31:10]}; + 5'b01011: + alu_shifter_res_raw[31:0] = {{11{alu_shifter_shift_in}}, alu_shifter_rs1[31:11]}; + 5'b01100: + alu_shifter_res_raw[31:0] = {{12{alu_shifter_shift_in}}, alu_shifter_rs1[31:12]}; + 5'b01101: + alu_shifter_res_raw[31:0] = {{13{alu_shifter_shift_in}}, alu_shifter_rs1[31:13]}; + 5'b01110: + alu_shifter_res_raw[31:0] = {{14{alu_shifter_shift_in}}, alu_shifter_rs1[31:14]}; + 5'b01111: + alu_shifter_res_raw[31:0] = {{15{alu_shifter_shift_in}}, alu_shifter_rs1[31:15]}; + 5'b10000: + alu_shifter_res_raw[31:0] = {{16{alu_shifter_shift_in}}, alu_shifter_rs1[31:16]}; + 5'b10001: + alu_shifter_res_raw[31:0] = {{17{alu_shifter_shift_in}}, alu_shifter_rs1[31:17]}; + 5'b10010: + alu_shifter_res_raw[31:0] = {{18{alu_shifter_shift_in}}, alu_shifter_rs1[31:18]}; + 5'b10011: + alu_shifter_res_raw[31:0] = {{19{alu_shifter_shift_in}}, alu_shifter_rs1[31:19]}; + 5'b10100: + alu_shifter_res_raw[31:0] = {{20{alu_shifter_shift_in}}, alu_shifter_rs1[31:20]}; + 5'b10101: + alu_shifter_res_raw[31:0] = {{21{alu_shifter_shift_in}}, alu_shifter_rs1[31:21]}; + 5'b10110: + alu_shifter_res_raw[31:0] = {{22{alu_shifter_shift_in}}, alu_shifter_rs1[31:22]}; + 5'b10111: + alu_shifter_res_raw[31:0] = {{23{alu_shifter_shift_in}}, alu_shifter_rs1[31:23]}; + 5'b11000: + alu_shifter_res_raw[31:0] = {{24{alu_shifter_shift_in}}, alu_shifter_rs1[31:24]}; + 5'b11001: + alu_shifter_res_raw[31:0] = {{25{alu_shifter_shift_in}}, alu_shifter_rs1[31:25]}; + 5'b11010: + alu_shifter_res_raw[31:0] = {{26{alu_shifter_shift_in}}, alu_shifter_rs1[31:26]}; + 5'b11011: + alu_shifter_res_raw[31:0] = {{27{alu_shifter_shift_in}}, alu_shifter_rs1[31:27]}; + 5'b11100: + alu_shifter_res_raw[31:0] = {{28{alu_shifter_shift_in}}, alu_shifter_rs1[31:28]}; + 5'b11101: + alu_shifter_res_raw[31:0] = {{29{alu_shifter_shift_in}}, alu_shifter_rs1[31:29]}; + 5'b11110: + alu_shifter_res_raw[31:0] = {{30{alu_shifter_shift_in}}, alu_shifter_rs1[31:30]}; + 5'b11111: + alu_shifter_res_raw[31:0] = {{31{alu_shifter_shift_in}}, alu_shifter_rs1[31]}; + default: + alu_shifter_res_raw[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @306 +end + +assign alu_shifter_ext_rst[31:0] = 32'b0; + +// Reversal LEFT-SHIFT result. +assign alu_shifter_res_raw_rev[31:0] = {alu_shifter_res_raw[0], alu_shifter_res_raw[1], + alu_shifter_res_raw[2], alu_shifter_res_raw[3], + alu_shifter_res_raw[4], alu_shifter_res_raw[5], + alu_shifter_res_raw[6], alu_shifter_res_raw[7], + alu_shifter_res_raw[8], alu_shifter_res_raw[9], + alu_shifter_res_raw[10], alu_shifter_res_raw[11], + alu_shifter_res_raw[12], alu_shifter_res_raw[13], + alu_shifter_res_raw[14], alu_shifter_res_raw[15], + alu_shifter_res_raw[16], alu_shifter_res_raw[17], + alu_shifter_res_raw[18], alu_shifter_res_raw[19], + alu_shifter_res_raw[20], alu_shifter_res_raw[21], + alu_shifter_res_raw[22], alu_shifter_res_raw[23], + alu_shifter_res_raw[24], alu_shifter_res_raw[25], + alu_shifter_res_raw[26], alu_shifter_res_raw[27], + alu_shifter_res_raw[28], alu_shifter_res_raw[29], + alu_shifter_res_raw[30], alu_shifter_res_raw[31]}; + +assign alu_shifter_res_tmp[31:0] = alu_shifter_dir_right ? alu_shifter_res_raw[31:0] + : alu_shifter_res_raw_rev[31:0]; + +assign alu_shifter_res[31:0] = alu_shifter_inst_ext ? alu_shifter_ext_rst[31:0] : alu_shifter_res_tmp[31:0]; + +//========================================================== +// Logic +//========================================================== +assign alu_logic_sel = alu_sel[2]; +assign alu_logic_rs1[31:0] = {32{alu_logic_sel}} & idu_iu_ex1_src0[31:0]; +assign alu_logic_rs2_raw[31:0] = {32{alu_logic_sel}} & idu_iu_ex1_src1[31:0]; + +// Sub function: +// 0 - and; +// 1 - or; +// 2 - xor. +assign alu_logic_sub_func[4:0] = { 5{alu_logic_sel}} & idu_iu_ex1_func[4:0]; + +assign alu_logic_rs2[31:0] = alu_logic_rs2_raw[31:0]; + +assign alu_logic_and_res[31:0] = alu_logic_rs1[31:0] & alu_logic_rs2[31:0]; +assign alu_logic_or_res[31:0] = alu_logic_rs1[31:0] | alu_logic_rs2[31:0]; +assign alu_logic_xor_res[31:0] = alu_logic_rs1[31:0] ^ alu_logic_rs2[31:0]; + +//-------------- Logic Mux ------------- +assign alu_logic_res[31:0] = {32{alu_logic_sub_func[0]}} & alu_logic_and_res[31:0] + | {32{alu_logic_sub_func[1]}} & alu_logic_or_res[31:0] + | {32{alu_logic_sub_func[2]}} & alu_logic_xor_res[31:0]; + +//========================================================== +// PACK +//========================================================== +assign alu_pack_sel = alu_sel[3]; +assign alu_pack_sub_func[4:0] = {5{alu_pack_sel}} & idu_iu_ex1_func[4:0]; + +assign alu_pack_rs1[31:0] = {32{alu_pack_sel}} & idu_iu_ex1_src0[31:0]; +assign alu_pack_rs2[31:0] = {32{alu_pack_sel}} & idu_iu_ex1_src1[31:0]; +assign alu_pack_pack_inst = |alu_pack_sub_func[2:0]; + +// &Force("nonport", "alu_pack_rs1"); @372 +// &Force("nonport", "alu_pack_rs2"); @373 + +assign alu_packl_rst[31:0] = 32'b0; +assign alu_packh_rst[31:0] = 32'b0; +assign alu_packhl_rst[31:0] = 32'b0; +//-------------- Pack Mux ------------- +assign alu_pack_encry_rst[31:0] = {32{alu_pack_sub_func[0]}} & alu_packl_rst[31:0] | + {32{alu_pack_sub_func[1]}} & alu_packh_rst[31:0] | + {32{alu_pack_sub_func[2]}} & alu_packhl_rst[31:0]; + +assign alu_pack_mov_rst[31:0] = 32'b0; +assign alu_pack_rst[31:0] = alu_pack_pack_inst ? alu_pack_encry_rst[31:0] : alu_pack_mov_rst[31:0]; + +//========================================================== +// BITOP +//========================================================== +// &CombBeg; @418 +// &CombEnd; @454 +// &CombBeg; @461 +// &CombEnd; @497 +assign alu_bitop_rst[31:0] = 32'b0; + + +//========================================================== +// ALU Mux +//========================================================== +assign alu_res[31:0] = alu_adder_res[31:0] + | alu_shifter_res[31:0] + | alu_logic_res[31:0] + | alu_pack_rst[31:0] + | alu_bitop_rst[31:0]; + + +//========================================================== +// Output for RTU +//========================================================== + +assign alu_dp_ex1_fwd_vld = (|alu_sel[4:0]) & idu_iu_ex1_alu_cmplt_dp_sel; +assign alu_dp_ex1_cmplt = idu_iu_ex1_inst_vld && (|alu_sel[4:0]) && (~dp_xx_ex1_stall); +assign alu_dp_ex1_cmplt_dp = idu_iu_ex1_alu_cmplt_dp_sel; +assign alu_dp_ex1_rslt[31:0] = alu_res[31:0]; + +// &ModuleEnd; @548 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_bju.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_bju.v new file mode 100644 index 0000000000000000000000000000000000000000..b50d6a503c1274ad4ee7f95b9c026cacfd8cb2a2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_bju.v @@ -0,0 +1,856 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_bju( + ag_bju_pc, + bju_dp_ex1_cmplt_dp, + bju_dp_ex1_rslt, + bju_dp_ex1_rslt_vld, + bju_dp_ex1_stall, + bju_dp_no_op, + bju_iu_debug_info, + cp0_iu_adder_borrow_in, + cp0_iu_adder_borrow_vld, + cp0_iu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + idu_iu_ex1_bht_pred, + idu_iu_ex1_bju_cmplt_dp_sel, + idu_iu_ex1_bju_depd_lsu_src0, + idu_iu_ex1_bju_depd_lsu_src1, + idu_iu_ex1_bju_gateclk_sel, + idu_iu_ex1_bju_sel, + idu_iu_ex1_dst_preg, + idu_iu_ex1_func, + idu_iu_ex1_gateclk_vld, + idu_iu_ex1_inst_len, + idu_iu_ex1_inst_vld, + idu_iu_ex1_split, + idu_iu_ex1_src0, + idu_iu_ex1_src0_reg, + idu_iu_ex1_src1, + idu_iu_ex1_src1_reg, + idu_iu_ex1_wb_vld, + idu_iu_tail_fail, + idu_iu_tail_fail_gate, + ifu_iu_chgflw_pc, + ifu_iu_chgflw_vld, + ifu_iu_ex1_pc_pred, + ifu_iu_reset_vld, + ifu_iu_warm_up, + iu_cp0_ex1_borrow_expt_pc, + iu_ex1_cur_pc, + iu_hpcp_inst_bht_mispred, + iu_hpcp_inst_condbr, + iu_hpcp_inst_condbr_gate, + iu_idu_bju_global_stall, + iu_idu_bju_stall, + iu_ifu_bht_cur_pc, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_bht_pred, + iu_ifu_bht_taken, + iu_ifu_br_vld, + iu_ifu_br_vld_gate, + iu_ifu_ind_link_vld, + iu_ifu_link_vld, + iu_ifu_link_vld_gate, + iu_ifu_pc_mispred, + iu_ifu_pc_mispred_gate, + iu_ifu_ret_vld, + iu_ifu_ret_vld_gate, + iu_ifu_tar_pc, + iu_ifu_tar_pc_vld, + iu_ifu_tar_pc_vld_gate, + iu_rtu_ex1_bju_branch_inst, + iu_rtu_ex1_bju_cmplt, + iu_rtu_ex1_bju_cmplt_dp, + iu_rtu_ex1_bju_cur_pc, + iu_rtu_ex1_bju_inst_len, + iu_rtu_ex1_bju_inst_vld, + iu_rtu_ex1_bju_split_inst, + iu_rtu_ex1_next_pc, + iu_rtu_ex2_bju_flush, + iu_rtu_ex2_bju_next_pc, + iu_rtu_ex2_bju_next_pc_vld, + iu_yy_xx_cancel, + lsu_iu_ex2_data, + lsu_iu_ex2_data_vld, + lsu_iu_ex2_dest_reg, + pad_yy_icg_scan_en, + rtu_iu_bju_ex2_cur_pc, + rtu_iu_ex1_cmplt_dp_vld, + rtu_iu_ex1_cmplt_inst_len, + rtu_iu_ex1_cmplt_split_inst, + rtu_iu_ex1_cmplt_vld, + rtu_xx_ex1_stall, + sysio_iu_rst_addr +); + +// &Ports; @24 +input [31:0] ag_bju_pc; +input cp0_iu_adder_borrow_in; +input cp0_iu_adder_borrow_vld; +input cp0_iu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input [1 :0] idu_iu_ex1_bht_pred; +input idu_iu_ex1_bju_cmplt_dp_sel; +input idu_iu_ex1_bju_depd_lsu_src0; +input idu_iu_ex1_bju_depd_lsu_src1; +input idu_iu_ex1_bju_gateclk_sel; +input idu_iu_ex1_bju_sel; +input [5 :0] idu_iu_ex1_dst_preg; +input [19:0] idu_iu_ex1_func; +input idu_iu_ex1_gateclk_vld; +input idu_iu_ex1_inst_len; +input idu_iu_ex1_inst_vld; +input idu_iu_ex1_split; +input [31:0] idu_iu_ex1_src0; +input [5 :0] idu_iu_ex1_src0_reg; +input [31:0] idu_iu_ex1_src1; +input [5 :0] idu_iu_ex1_src1_reg; +input idu_iu_ex1_wb_vld; +input idu_iu_tail_fail; +input idu_iu_tail_fail_gate; +input [31:0] ifu_iu_chgflw_pc; +input ifu_iu_chgflw_vld; +input [31:0] ifu_iu_ex1_pc_pred; +input ifu_iu_reset_vld; +input ifu_iu_warm_up; +input [31:0] lsu_iu_ex2_data; +input lsu_iu_ex2_data_vld; +input [5 :0] lsu_iu_ex2_dest_reg; +input pad_yy_icg_scan_en; +input [31:0] rtu_iu_bju_ex2_cur_pc; +input rtu_iu_ex1_cmplt_dp_vld; +input rtu_iu_ex1_cmplt_inst_len; +input rtu_iu_ex1_cmplt_split_inst; +input rtu_iu_ex1_cmplt_vld; +input rtu_xx_ex1_stall; +input [31:0] sysio_iu_rst_addr; +output bju_dp_ex1_cmplt_dp; +output [31:0] bju_dp_ex1_rslt; +output bju_dp_ex1_rslt_vld; +output bju_dp_ex1_stall; +output bju_dp_no_op; +output [3 :0] bju_iu_debug_info; +output [31:0] iu_cp0_ex1_borrow_expt_pc; +output [31:0] iu_ex1_cur_pc; +output iu_hpcp_inst_bht_mispred; +output iu_hpcp_inst_condbr; +output iu_hpcp_inst_condbr_gate; +output iu_idu_bju_global_stall; +output iu_idu_bju_stall; +output [31:0] iu_ifu_bht_cur_pc; +output iu_ifu_bht_mispred; +output iu_ifu_bht_mispred_gate; +output [1 :0] iu_ifu_bht_pred; +output iu_ifu_bht_taken; +output iu_ifu_br_vld; +output iu_ifu_br_vld_gate; +output iu_ifu_ind_link_vld; +output iu_ifu_link_vld; +output iu_ifu_link_vld_gate; +output iu_ifu_pc_mispred; +output iu_ifu_pc_mispred_gate; +output iu_ifu_ret_vld; +output iu_ifu_ret_vld_gate; +output [31:0] iu_ifu_tar_pc; +output iu_ifu_tar_pc_vld; +output iu_ifu_tar_pc_vld_gate; +output iu_rtu_ex1_bju_branch_inst; +output iu_rtu_ex1_bju_cmplt; +output iu_rtu_ex1_bju_cmplt_dp; +output [30:0] iu_rtu_ex1_bju_cur_pc; +output iu_rtu_ex1_bju_inst_len; +output iu_rtu_ex1_bju_inst_vld; +output iu_rtu_ex1_bju_split_inst; +output [30:0] iu_rtu_ex1_next_pc; +output iu_rtu_ex2_bju_flush; +output [30:0] iu_rtu_ex2_bju_next_pc; +output iu_rtu_ex2_bju_next_pc_vld; +output iu_yy_xx_cancel; + +// &Regs; @25 +reg bju_cur_state; +reg [1 :0] bju_ex2_bht_pred; +reg [3 :0] bju_ex2_func_4_1; +reg bju_ex2_inst_len; +reg [31:0] bju_ex2_not_pred_pc; +reg [31:0] bju_ex2_src0; +reg [31:0] bju_ex2_src1; +reg bju_next_state; +reg [30:0] bju_pcgen_pc_31; +reg bju_ras_mispred_vld; + +// &Wires; @26 +wire [31:0] ag_bju_pc; +wire [31:0] bju_ag_tar_pc; +wire bju_ag_tar_pc_sel; +wire [31:0] bju_auipc_res; +wire bju_beq_taken; +wire [31:0] bju_bht_cur_pc; +wire bju_bht_mispred; +wire bju_bht_mispred_gate; +wire [1 :0] bju_bht_pred; +wire bju_bht_taken; +wire bju_blt_taken; +wire bju_br_jalr_clk; +wire bju_br_jalr_clk_en; +wire bju_br_vld; +wire bju_br_vld_gate; +wire bju_clk; +wire bju_clk_en; +wire bju_cond_br_taken; +wire bju_cond_br_taken_raw; +wire bju_cond_sel; +wire bju_dp_ex1_cmplt_dp; +wire [31:0] bju_dp_ex1_rslt; +wire bju_dp_ex1_rslt_vld; +wire bju_dp_ex1_stall; +wire bju_dp_no_op; +wire bju_ex1_auipc_sel; +wire bju_ex1_bht_mispred; +wire bju_ex1_bht_mispred_gate; +wire bju_ex1_cond_sel; +wire bju_ex1_depd_lsu; +wire bju_ex1_depd_lsu_cmplt; +wire bju_ex1_depd_lsu_fwd_vld; +wire bju_ex1_depd_lsu_fwd_vld_gate; +wire bju_ex1_depd_lsu_src0; +wire bju_ex1_depd_lsu_src1; +wire [7 :0] bju_ex1_func; +wire bju_ex1_inst_cmplt; +wire bju_ex1_inst_cmplt_dp; +wire bju_ex1_no_depd_lsu_cmplt; +wire bju_ex1_no_depd_lsu_cmplt_gate; +wire [31:0] bju_ex1_not_pred_pc; +wire [31:0] bju_ex1_src0; +wire [31:0] bju_ex1_src1; +wire bju_ex1_tar_pc_vld; +wire bju_ex1_tar_pc_vld_gate; +wire bju_ex1_uncond_sel; +wire bju_ex2_bht_mispred; +wire [31:0] bju_ex2_chgflw_pc; +wire bju_ex2_chgflw_vld; +wire [4 :0] bju_func; +wire bju_fwd_clk; +wire bju_fwd_clk_en; +wire bju_hi_clk; +wire bju_hi_clk_en; +wire bju_hi_updt; +wire [31:0] bju_inc_pc; +wire [30:0] bju_inc_pc_31_1; +wire bju_ind_link_vld; +wire bju_inst_jalr; +wire bju_is_ex1; +wire bju_is_ex2; +wire [3 :0] bju_iu_debug_info; +wire bju_link_vld; +wire bju_link_vld_raw; +wire [31:0] bju_next_pc; +wire bju_pc_cmp_fail; +wire bju_pc_mispred; +wire bju_pc_mispred_raw; +wire [31:0] bju_pcgen_pc; +wire bju_ras_clk; +wire bju_ras_clk_en; +wire bju_ras_pc_mispred_set; +wire bju_ras_pc_mispred_set_gate; +wire bju_ret_vld; +wire bju_ret_vld_raw; +wire bju_rs1_lt_rs2; +wire bju_rs1_lt_rs2_signed; +wire [31:0] bju_src0; +wire [31:0] bju_src1; +wire bju_src_dst_reg_equal; +wire cp0_iu_adder_borrow_in; +wire cp0_iu_adder_borrow_vld; +wire cp0_iu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire [1 :0] idu_iu_ex1_bht_pred; +wire idu_iu_ex1_bju_cmplt_dp_sel; +wire idu_iu_ex1_bju_depd_lsu_src0; +wire idu_iu_ex1_bju_depd_lsu_src1; +wire idu_iu_ex1_bju_gateclk_sel; +wire idu_iu_ex1_bju_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_len; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_split; +wire [31:0] idu_iu_ex1_src0; +wire [5 :0] idu_iu_ex1_src0_reg; +wire [31:0] idu_iu_ex1_src1; +wire idu_iu_ex1_wb_vld; +wire idu_iu_tail_fail; +wire idu_iu_tail_fail_gate; +wire [31:0] ifu_iu_chgflw_pc; +wire ifu_iu_chgflw_vld; +wire [31:0] ifu_iu_ex1_pc_pred; +wire ifu_iu_reset_vld; +wire ifu_iu_warm_up; +wire [31:0] iu_cp0_ex1_borrow_expt_pc; +wire [31:0] iu_ex1_cur_pc; +wire iu_hpcp_inst_bht_mispred; +wire iu_hpcp_inst_condbr; +wire iu_hpcp_inst_condbr_gate; +wire iu_idu_bju_global_stall; +wire iu_idu_bju_stall; +wire [31:0] iu_ifu_bht_cur_pc; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire iu_ifu_ind_link_vld; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire [31:0] iu_ifu_tar_pc; +wire iu_ifu_tar_pc_vld; +wire iu_ifu_tar_pc_vld_gate; +wire iu_rtu_ex1_bju_branch_inst; +wire iu_rtu_ex1_bju_cmplt; +wire iu_rtu_ex1_bju_cmplt_dp; +wire [30:0] iu_rtu_ex1_bju_cur_pc; +wire iu_rtu_ex1_bju_inst_len; +wire iu_rtu_ex1_bju_inst_vld; +wire iu_rtu_ex1_bju_split_inst; +wire [30:0] iu_rtu_ex1_next_pc; +wire iu_rtu_ex2_bju_flush; +wire [30:0] iu_rtu_ex2_bju_next_pc; +wire iu_rtu_ex2_bju_next_pc_vld; +wire iu_yy_xx_cancel; +wire [31:0] lsu_iu_ex2_data; +wire lsu_iu_ex2_data_vld; +wire pad_yy_icg_scan_en; +wire [1 :0] pc_inc_in; +wire pcgen_pipedown; +wire [31:0] rtu_iu_bju_ex2_cur_pc; +wire rtu_iu_ex1_cmplt_dp_vld; +wire rtu_iu_ex1_cmplt_inst_len; +wire rtu_iu_ex1_cmplt_split_inst; +wire rtu_iu_ex1_cmplt_vld; +wire rtu_xx_ex1_stall; +wire [31:0] sysio_iu_rst_addr; + + +// &Force("bus", "idu_iu_ex1_func", 19, 0); @28 +//========================================================== +// Operand Prepare +//========================================================== +assign bju_ex1_func[7:0] = { 8{idu_iu_ex1_bju_sel}} & idu_iu_ex1_func[7:0]; +assign bju_ex1_uncond_sel = bju_ex1_func[5]; +assign bju_ex1_cond_sel = bju_ex1_func[6]; +assign bju_ex1_auipc_sel = bju_ex1_func[7]; +// operand mux +assign bju_ex1_src0[31:0] = {32{idu_iu_ex1_bju_sel}} & idu_iu_ex1_src0[31:0]; +assign bju_ex1_src1[31:0] = {32{idu_iu_ex1_bju_sel}} & idu_iu_ex1_src1[31:0]; + +assign bju_ex1_depd_lsu_src0 = idu_iu_ex1_bju_depd_lsu_src0 && bju_ex1_cond_sel; //cond branch inst +assign bju_ex1_depd_lsu_src1 = idu_iu_ex1_bju_depd_lsu_src1 && bju_ex1_cond_sel; + +assign bju_ex1_depd_lsu = bju_ex1_depd_lsu_src0 || bju_ex1_depd_lsu_src1; + +// ex1 inst vld will be clear when ex1 depd lsu or bju_in_ex2. +assign bju_ex1_no_depd_lsu_cmplt = idu_iu_ex1_inst_vld && idu_iu_ex1_bju_sel && !bju_ex1_depd_lsu; +assign bju_ex1_no_depd_lsu_cmplt_gate = idu_iu_ex1_bju_gateclk_sel && !bju_ex1_depd_lsu; + +assign bju_ex1_depd_lsu_cmplt = idu_iu_ex1_inst_vld && bju_ex1_depd_lsu && lsu_iu_ex2_data_vld; +assign bju_ex1_depd_lsu_fwd_vld = bju_ex1_depd_lsu_cmplt; +// gate signal is for ICG. +assign bju_ex1_depd_lsu_fwd_vld_gate = idu_iu_ex1_gateclk_vld && bju_ex1_depd_lsu && lsu_iu_ex2_data_vld; + + +//========================================================== +// BJU State Machine +//========================================================== +// bju_ex2 only occur when bju depd load. +parameter BJU_EX1 = 1'b0; +parameter BJU_EX2 = 1'b1; + +always @ (posedge bju_clk or negedge cpurst_b) +begin + if (!cpurst_b) + bju_cur_state <= BJU_EX1; + else + bju_cur_state <= bju_next_state; +end + +// &CombBeg; @70 +always @( bju_ex1_depd_lsu_fwd_vld + or bju_cur_state) +begin + case(bju_cur_state) + BJU_EX1: + if (bju_ex1_depd_lsu_fwd_vld) + bju_next_state = BJU_EX2; + else + bju_next_state = BJU_EX1; + BJU_EX2: + bju_next_state = BJU_EX1; + default: + bju_next_state = BJU_EX1; + endcase +// &CombEnd; @82 +end + +assign bju_is_ex1 = bju_cur_state == BJU_EX1; +assign bju_is_ex2 = bju_cur_state == BJU_EX2; + +// this signal for bju no op +assign bju_dp_no_op = !bju_is_ex2 & !bju_ras_mispred_vld; +//========================================================== +// EX1 to EX2 flop +//========================================================== +always @ (posedge bju_fwd_clk) +begin + if (bju_ex1_depd_lsu_fwd_vld || ifu_iu_warm_up) begin + bju_ex2_func_4_1[3:0] <= bju_ex1_func[4:1]; + bju_ex2_inst_len <= idu_iu_ex1_inst_len; + bju_ex2_bht_pred[1:0] <= idu_iu_ex1_bht_pred[1:0]; + end +end + +always @ (posedge bju_br_jalr_clk) +begin + if (bju_ex1_depd_lsu_fwd_vld || bju_ras_pc_mispred_set || ifu_iu_warm_up) begin + bju_ex2_not_pred_pc[31:0] <= bju_ex1_not_pred_pc[31:0]; + end +end + + +always @ (posedge bju_fwd_clk) +begin + if (bju_ex1_depd_lsu_fwd_vld && idu_iu_ex1_bju_depd_lsu_src0) begin + bju_ex2_src0[31:0] <= lsu_iu_ex2_data[31:0]; + end + else if (bju_ex1_depd_lsu_fwd_vld && !idu_iu_ex1_bju_depd_lsu_src0 || ifu_iu_warm_up) begin + bju_ex2_src0[31:0] <= bju_ex1_src0[31:0]; + end +end + +always @ (posedge bju_fwd_clk) +begin + if (bju_ex1_depd_lsu_fwd_vld && idu_iu_ex1_bju_depd_lsu_src1) begin + bju_ex2_src1[31:0] <= lsu_iu_ex2_data[31:0]; + end + else if (bju_ex1_depd_lsu_fwd_vld && !idu_iu_ex1_bju_depd_lsu_src1 || ifu_iu_warm_up) begin + bju_ex2_src1[31:0] <= bju_ex1_src1[31:0]; + end +end + +assign bju_ex2_chgflw_vld = bju_ex2_bht_mispred; +assign bju_ex2_chgflw_pc[31:0] = bju_ex2_not_pred_pc[31:0]; + +//========================================================== +// EX1/EX2 Select +//========================================================== +assign bju_func[4:0] = bju_is_ex1 ? bju_ex1_func[4:0] + : {bju_ex2_func_4_1[3:0], 1'b0}; +assign bju_src0[31:0] = bju_is_ex1 ? bju_ex1_src0[31:0] + : bju_ex2_src0[31:0]; +assign bju_src1[31:0] = bju_is_ex1 ? bju_ex1_src1[31:0] + : bju_ex2_src1[31:0]; +assign bju_bht_pred[1:0] = bju_is_ex1 ? idu_iu_ex1_bht_pred[1:0] + : bju_ex2_bht_pred[1:0]; +//========================================================== +// Inc PC +//========================================================== +// note: the CP0 ifu access fault expt will borrow this adder for the expt +// tval +assign pc_inc_in[1:0] = cp0_iu_adder_borrow_vld ? {1'b0,cp0_iu_adder_borrow_in} + : {rtu_iu_ex1_cmplt_inst_len, !rtu_iu_ex1_cmplt_inst_len}; +assign bju_inc_pc_31_1[30:0] = bju_pcgen_pc[31:1] + {29'b0, pc_inc_in[1:0]}; +assign bju_inc_pc[31:0] = {bju_inc_pc_31_1[30:0], 1'b0}; +assign iu_cp0_ex1_borrow_expt_pc[31:0] = {bju_inc_pc_31_1[30:0],1'b0}; +//========================================================== +// AUIPC +//========================================================== +assign bju_auipc_res[31:0] = ag_bju_pc[31:0]; + +//========================================================== +// Un-condition Branch & Jump +//========================================================== +assign bju_inst_jalr = bju_ex1_uncond_sel & bju_ex1_func[2]; + +//------------ From Addr_gen ----------- +assign bju_ag_tar_pc[31:0] = ag_bju_pc[31:0]; + + +//========================================================== +// Condition Branch +//========================================================== +assign bju_cond_sel = bju_ex1_cond_sel || bju_is_ex2; + +assign bju_beq_taken = bju_src0[31:0] == bju_src1[31:0]; +assign bju_rs1_lt_rs2 = bju_src0[31:0] < bju_src1[31:0]; +assign bju_rs1_lt_rs2_signed = bju_src0[31] && bju_src1[31] && bju_rs1_lt_rs2 + || bju_src0[31] && !bju_src1[31] + || !bju_src0[31] && !bju_src1[31] && bju_rs1_lt_rs2; +assign bju_blt_taken = bju_func[4] ? bju_rs1_lt_rs2_signed + : bju_rs1_lt_rs2; + + +assign bju_cond_br_taken_raw = (bju_beq_taken ^ bju_func[3]) & bju_func[2] // beq and bne taken + | (bju_blt_taken ^ bju_func[3]) & bju_func[1]; // blt/bltu and bge/bgeu taken +assign bju_cond_br_taken = bju_ex1_no_depd_lsu_cmplt || bju_is_ex2 ? bju_cond_br_taken_raw + : idu_iu_ex1_bht_pred[1]; + +//========================================================== +// Next PC +//========================================================== +assign bju_ag_tar_pc_sel = bju_ex1_cond_sel && bju_cond_br_taken + || bju_ex1_uncond_sel; +assign bju_next_pc[31:0] = bju_ag_tar_pc_sel ? bju_ag_tar_pc[31:0] + : bju_inc_pc[31:0]; +//========================================================== +// Branch & Jump Inst target PC +//========================================================== +// BHT predict result is in pred[1]. +// 0-untaken, 1-taken. +assign bju_ex1_not_pred_pc[31:0] = bju_bht_pred[1] ? bju_inc_pc[31:0] + : bju_ag_tar_pc[31:0]; + +//------------- BHT Mispred ------------ +assign bju_ex1_bht_mispred = bju_ex1_cond_sel && (bju_cond_br_taken_raw ^ bju_bht_pred[1]) && + bju_ex1_no_depd_lsu_cmplt; + +assign bju_ex1_bht_mispred_gate = bju_ex1_cond_sel && (bju_cond_br_taken_raw ^ bju_bht_pred[1]) && + bju_ex1_no_depd_lsu_cmplt_gate; + +assign bju_ex2_bht_mispred = bju_is_ex2 && (bju_cond_br_taken_raw ^ bju_bht_pred[1]); + +assign bju_br_vld = bju_cond_sel && (bju_ex1_no_depd_lsu_cmplt || bju_is_ex2); +assign bju_br_vld_gate = bju_cond_sel && (bju_ex1_no_depd_lsu_cmplt_gate || bju_is_ex2); +assign bju_bht_taken = bju_cond_sel && bju_cond_br_taken; + +// &Force("bus", "idu_iu_ex1_dst_preg", 5, 0); @270 +// &Force("bus", "idu_iu_ex1_src0_reg", 5, 0); @271 + +//------------- PC Mispred ------------- +// bju_pc_cmp_fail will set ex2_chgflw because of timing. +assign bju_pc_cmp_fail = bju_inst_jalr + && idu_iu_ex1_src0_reg[4:0] == 5'b1 + && (bju_src_dst_reg_equal || bju_ag_tar_pc[31:0] != ifu_iu_ex1_pc_pred[31:0]); + +assign bju_ras_pc_mispred_set = idu_iu_ex1_inst_vld & idu_iu_ex1_bju_sel & bju_pc_cmp_fail; +assign bju_ras_pc_mispred_set_gate = idu_iu_ex1_gateclk_vld & idu_iu_ex1_bju_sel & bju_pc_cmp_fail; + +always@ (posedge bju_ras_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bju_ras_mispred_vld <= 1'b0; + else if(bju_ras_pc_mispred_set) + bju_ras_mispred_vld <= 1'b1; + else + bju_ras_mispred_vld <= 1'b0; +end + +assign bju_pc_mispred_raw = bju_inst_jalr && + idu_iu_ex1_src0_reg[4:0] != 5'b1; + +assign bju_pc_mispred = bju_pc_mispred_raw && idu_iu_ex1_inst_vld; + +assign bju_ex1_tar_pc_vld = bju_ex1_bht_mispred || bju_pc_mispred; +assign bju_ex1_tar_pc_vld_gate = bju_ex1_bht_mispred_gate || bju_pc_mispred_raw; + +assign bju_bht_mispred = bju_ex1_bht_mispred || bju_ex2_bht_mispred; +assign bju_bht_mispred_gate = bju_ex1_bht_mispred_gate || bju_ex2_bht_mispred; + +assign bju_src_dst_reg_equal = (idu_iu_ex1_src0_reg[5:0] == idu_iu_ex1_dst_preg[5:0]) && idu_iu_ex1_wb_vld; +assign bju_ret_vld_raw = idu_iu_ex1_src0_reg[4:0] == 5'b1 && bju_inst_jalr && !bju_src_dst_reg_equal; +assign bju_ret_vld = idu_iu_ex1_inst_vld && bju_ret_vld_raw; +assign bju_link_vld_raw = idu_iu_ex1_dst_preg[4:0] == 5'b1 && bju_ex1_uncond_sel && idu_iu_ex1_wb_vld; +assign bju_link_vld = idu_iu_ex1_inst_vld && bju_link_vld_raw; +assign bju_ind_link_vld = idu_iu_ex1_inst_vld && bju_link_vld_raw && bju_inst_jalr; + +assign bju_ex1_inst_cmplt = |bju_ex1_func[7:5] && (bju_ex1_no_depd_lsu_cmplt || + bju_ex1_depd_lsu_cmplt); +assign bju_ex1_inst_cmplt_dp = |bju_ex1_func[7:5] && idu_iu_ex1_bju_cmplt_dp_sel; + +//========================================================== +// PC Generator +//========================================================== +assign pcgen_pipedown = !rtu_xx_ex1_stall; + +// &Force("bus", "sysio_iu_rst_addr", 31, 0); @319 +// &Force("bus", "ifu_iu_chgflw_pc", 31, 0); @320 +// bju_pcgen_pc_31[10:0] == pcgen_pc[11:1] +always @ (posedge bju_clk) +begin + if (ifu_iu_reset_vld) + bju_pcgen_pc_31[10:0] <= sysio_iu_rst_addr[11:1]; + else if (ifu_iu_chgflw_vld) + bju_pcgen_pc_31[10:0] <= ifu_iu_chgflw_pc[11:1]; + else if (idu_iu_tail_fail) + bju_pcgen_pc_31[10:0] <= rtu_iu_bju_ex2_cur_pc[11:1]; + else if (rtu_iu_ex1_cmplt_vld && pcgen_pipedown && !rtu_iu_ex1_cmplt_split_inst) + bju_pcgen_pc_31[10:0] <= bju_next_pc[11:1]; +end + +// bju_pcgen_pc_31[30:11] == pcgen_pc[31:12] +always @ (posedge bju_hi_clk) +begin + if (ifu_iu_reset_vld) + bju_pcgen_pc_31[30:11] <= sysio_iu_rst_addr[31:12]; + else if (ifu_iu_chgflw_vld) + bju_pcgen_pc_31[30:11] <= ifu_iu_chgflw_pc[31:12]; + else if (idu_iu_tail_fail) + bju_pcgen_pc_31[30:11] <= rtu_iu_bju_ex2_cur_pc[31:12]; + else if (rtu_iu_ex1_cmplt_vld && pcgen_pipedown && !rtu_iu_ex1_cmplt_split_inst) + bju_pcgen_pc_31[30:11] <= bju_next_pc[31:12]; +end + +assign bju_pcgen_pc[31:0] = {bju_pcgen_pc_31[30:0], 1'b0}; + +assign bju_hi_updt = bju_pcgen_pc[31:12] != bju_next_pc[31:12]; + +assign iu_ex1_cur_pc[31:0] = bju_pcgen_pc[31:0]; +assign bju_bht_cur_pc[31:0] = bju_is_ex1 ? bju_pcgen_pc[31:0] + : rtu_iu_bju_ex2_cur_pc[31:0]; +//========================================================== +// BJU gateclk +//========================================================== +// bju_clk include: +// 1. bju_pcgen; +// 2. bju PMU counter; +// 3. tar_pc_vld_mask. + +assign bju_clk_en = ifu_iu_chgflw_vld + || idu_iu_ex1_gateclk_vld + || bju_is_ex2 + || idu_iu_tail_fail_gate + || rtu_iu_ex1_cmplt_dp_vld + || ifu_iu_warm_up + || ifu_iu_reset_vld; + +// &Instance("gated_clk_cell", "x_bju_clk"); @402 +gated_clk_cell x_bju_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bju_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bju_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @403 +// .external_en (1'b0), @404 +// .global_en (cp0_yy_clk_en), @405 +// .module_en (cp0_iu_icg_en), @406 +// .local_en (bju_clk_en), @407 +// .clk_out (bju_clk)); @408 + +assign bju_hi_clk_en = ifu_iu_chgflw_vld + || idu_iu_ex1_gateclk_vld && bju_hi_updt + || idu_iu_tail_fail_gate + || rtu_iu_ex1_cmplt_dp_vld + || ifu_iu_warm_up + || ifu_iu_reset_vld; + +assign bju_ras_clk_en = bju_ras_pc_mispred_set_gate + || ifu_iu_warm_up + || bju_ras_mispred_vld; + +assign bju_br_jalr_clk_en = bju_ras_pc_mispred_set_gate + || bju_ex1_depd_lsu_fwd_vld_gate + || ifu_iu_warm_up; + +// &Instance("gated_clk_cell", "x_bju_hi_clk"); @425 +gated_clk_cell x_bju_hi_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bju_hi_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bju_hi_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @426 +// .external_en (1'b0), @427 +// .global_en (cp0_yy_clk_en), @428 +// .module_en (cp0_iu_icg_en), @429 +// .local_en (bju_hi_clk_en), @430 +// .clk_out (bju_hi_clk)); @431 + +assign bju_fwd_clk_en = bju_ex1_depd_lsu_fwd_vld_gate + || ifu_iu_warm_up; + +// &Instance("gated_clk_cell", "x_bju_fwd_clk"); @436 +gated_clk_cell x_bju_fwd_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bju_fwd_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bju_fwd_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @437 +// .external_en (1'b0), @438 +// .global_en (cp0_yy_clk_en), @439 +// .module_en (cp0_iu_icg_en), @440 +// .local_en (bju_fwd_clk_en), @441 +// .clk_out (bju_fwd_clk)); @442 + +// &Instance("gated_clk_cell", "x_bju_ras_clk"); @444 +gated_clk_cell x_bju_ras_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bju_ras_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bju_ras_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @445 +// .external_en (1'b0), @446 +// .global_en (cp0_yy_clk_en), @447 +// .module_en (cp0_iu_icg_en), @448 +// .local_en (bju_ras_clk_en), @449 +// .clk_out (bju_ras_clk)); @450 + +// &Instance("gated_clk_cell", "x_bju_br_jalr_clk"); @452 +gated_clk_cell x_bju_br_jalr_clk ( + .clk_in (forever_cpuclk ), + .clk_out (bju_br_jalr_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (bju_br_jalr_clk_en), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @453 +// .external_en (1'b0), @454 +// .global_en (cp0_yy_clk_en), @455 +// .module_en (cp0_iu_icg_en), @456 +// .local_en (bju_br_jalr_clk_en), @457 +// .clk_out (bju_br_jalr_clk)); @458 + + +//========================================================== +// STALL +//========================================================== +assign bju_dp_ex1_stall = idu_iu_ex1_bju_gateclk_sel && bju_ex1_depd_lsu && !bju_ex1_depd_lsu_fwd_vld || + idu_iu_ex1_bju_gateclk_sel && bju_is_ex2; + + +assign iu_idu_bju_global_stall = 1'b0; +assign iu_idu_bju_stall = bju_is_ex2; +//========================================================== +// OUTPUT SIGNAL +//========================================================== + +//---------------------------------------------------------- +// IFU SIGNAL +//---------------------------------------------------------- +assign iu_ifu_tar_pc_vld = bju_ex1_tar_pc_vld || bju_ex2_bht_mispred || bju_ras_mispred_vld; +assign iu_ifu_tar_pc_vld_gate = bju_ex1_tar_pc_vld_gate || bju_ex2_bht_mispred || bju_ras_mispred_vld; +assign iu_ifu_tar_pc[31:0] = (bju_ex2_bht_mispred || bju_ras_mispred_vld) ? bju_ex2_not_pred_pc[31:0] : + bju_next_pc[31:0]; + +assign iu_yy_xx_cancel = bju_ex1_tar_pc_vld || bju_ex2_bht_mispred || bju_ras_mispred_vld; +//---------------- BHT ----------------- +assign iu_ifu_br_vld = bju_br_vld; +assign iu_ifu_br_vld_gate = bju_br_vld_gate; +assign iu_ifu_bht_cur_pc[31:0] = bju_bht_cur_pc[31:0]; +assign iu_ifu_bht_taken = bju_bht_taken; +assign iu_ifu_bht_pred[1:0] = bju_bht_pred[1:0]; +assign iu_ifu_bht_mispred = bju_bht_mispred; +assign iu_ifu_bht_mispred_gate = bju_bht_mispred_gate; + +//---------------- RAS ----------------- +assign iu_ifu_ret_vld = bju_ret_vld; +assign iu_ifu_ret_vld_gate = bju_ret_vld_raw; +assign iu_ifu_link_vld = bju_link_vld; +assign iu_ifu_ind_link_vld = bju_ind_link_vld; +assign iu_ifu_link_vld_gate = bju_link_vld_raw; +assign iu_ifu_pc_mispred = bju_pc_mispred; +assign iu_ifu_pc_mispred_gate = bju_pc_mispred_raw; + + +assign bju_iu_debug_info[3:0] = {1'b0, bju_cur_state, bju_ras_mispred_vld, bju_bht_mispred}; + +//========================================================== +// CP0 +//========================================================== +//assign iu_cp0_ex1_cur_pc[31:0] = bju_pcgen_pc[31:0]; + +//========================================================== +// IU Ctrl Signal +//========================================================== +assign bju_dp_ex1_cmplt_dp = bju_ex1_inst_cmplt_dp; +assign bju_dp_ex1_rslt_vld = (bju_ex1_uncond_sel || bju_ex1_auipc_sel) + && idu_iu_ex1_wb_vld && idu_iu_ex1_inst_vld; +assign bju_dp_ex1_rslt[31:0] = bju_ex1_auipc_sel ? bju_auipc_res[31:0] + : bju_inc_pc[31:0]; +//========================================================== +// RTU Signal +//========================================================== +assign iu_rtu_ex1_bju_inst_vld = idu_iu_ex1_gateclk_vld && idu_iu_ex1_bju_sel || bju_is_ex2 ; + +assign iu_rtu_ex1_bju_cmplt = bju_ex1_inst_cmplt; +assign iu_rtu_ex1_bju_cmplt_dp = bju_ex1_inst_cmplt_dp; +assign iu_rtu_ex1_bju_inst_len = bju_is_ex2 ? bju_ex2_inst_len : idu_iu_ex1_inst_len; + +assign iu_rtu_ex1_next_pc[30:0] = bju_next_pc[31:1]; +assign iu_rtu_ex1_bju_cur_pc[30:0] = bju_pcgen_pc[31:1]; + +assign iu_rtu_ex1_bju_split_inst = idu_iu_ex1_split; +assign iu_rtu_ex1_bju_branch_inst = |bju_ex1_func[7:5] && !bju_ex1_auipc_sel; + +assign iu_rtu_ex2_bju_next_pc_vld = bju_ex2_chgflw_vld; +assign iu_rtu_ex2_bju_next_pc[30:0] = bju_ex2_chgflw_pc [31:1]; +assign iu_rtu_ex2_bju_flush = bju_ras_mispred_vld | bju_ex2_chgflw_vld; + +//========================================================== +// HPCP Signal +//========================================================== +assign iu_hpcp_inst_condbr = bju_ex1_cond_sel && bju_ex1_inst_cmplt; +assign iu_hpcp_inst_condbr_gate = bju_ex1_cond_sel && bju_ex1_inst_cmplt_dp; +assign iu_hpcp_inst_bht_mispred = bju_bht_mispred; + +//========================================================== +//random signals compared with e907 +// &Force("input","idu_iu_ex1_src1_reg"); @545 +// &Force("input","lsu_iu_ex2_dest_reg"); @546 + +// &Force("bus", "idu_iu_ex1_src1_reg", 5, 0); @548 +// &Force("bus", "lsu_iu_ex2_dest_reg", 5, 0); @549 +//========================================================== +// + +// &ModuleEnd; @666 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..c0845479a8a832abf94673171d8123f2b7039ece --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_ctrl.v @@ -0,0 +1,692 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_ctrl( + ag_dp_ex1_dst_preg, + ag_dp_ex1_fwd_data, + ag_dp_ex1_fwd_vld, + alu_dp_ex1_cmplt, + alu_dp_ex1_cmplt_dp, + alu_dp_ex1_fwd_vld, + alu_dp_ex1_rslt, + bju_dp_ex1_cmplt_dp, + bju_dp_ex1_rslt, + bju_dp_ex1_rslt_vld, + bju_dp_ex1_stall, + bju_dp_no_op, + cp0_iu_icg_en, + cp0_yy_clk_en, + cpurst_b, + div_ctrl_itering, + div_dp_ex1_cmplt, + div_dp_ex1_cmplt_dp, + div_dp_ex1_fwd_data, + div_dp_ex1_fwd_vld, + div_dp_ex1_stall, + div_dp_ex2_dst_preg, + div_dp_ex2_rslt, + div_dp_ex2_rslt_vld, + dp_xx_ex1_stall, + dp_xx_ex2_stall, + forever_cpuclk, + fpu_iu_ex1_cmplt, + fpu_iu_ex1_cmplt_dp, + idu_iu_ex1_alu_sel, + idu_iu_ex1_dst_preg, + idu_iu_ex1_gateclk_vld, + idu_iu_ex1_inst_len, + idu_iu_ex1_inst_vld, + idu_iu_ex1_ipop_int_mask, + idu_iu_ex1_ipush_mie_en, + idu_iu_ex1_ipush_spec_fail, + idu_iu_ex1_mul_sel, + idu_iu_ex1_rd_pair, + idu_iu_ex1_split, + idu_iu_ex1_tail_int_vld, + idu_iu_ex1_wb_vld, + ifu_iu_warm_up, + iu_ex2_div_grant, + iu_idu_ex1_fwd_data, + iu_idu_ex1_fwd_preg, + iu_idu_ex1_fwd_vld, + iu_idu_ex1_stall, + iu_idu_ex2_div_vld, + iu_idu_ex2_fwd_data0, + iu_idu_ex2_fwd_data1, + iu_idu_ex2_fwd_preg0, + iu_idu_ex2_fwd_preg1, + iu_idu_ex2_fwd_vld0, + iu_idu_ex2_fwd_vld1, + iu_idu_ex2_inst_vld, + iu_idu_ex2_rd_pair, + iu_idu_id_stall, + iu_lsu_ex2_wb0_grant, + iu_rtu_ex1_cmplt, + iu_rtu_ex1_cmplt_dp, + iu_rtu_ex1_inst_len, + iu_rtu_ex1_inst_vld, + iu_rtu_ex1_ipop_int_mask, + iu_rtu_ex1_ipush_mie_en, + iu_rtu_ex1_ipush_spec_fail, + iu_rtu_ex1_split_inst, + iu_rtu_ex1_tail_int_vld, + iu_rtu_wb0_data, + iu_rtu_wb0_preg, + iu_rtu_wb0_vld, + iu_xx_no_op, + lsu_iu_ex2_lsi_dst_preg, + lsu_iu_ex2_lsi_rslt, + lsu_iu_ex2_lsi_rslt_vld, + lsu_rtu_ex1_cmplt_dp, + mul_dp_ex1_cmplt, + mul_dp_ex1_cmplt_dp, + mul_dp_ex2_inst_vld, + mul_dp_ex2_rslt0, + mul_dp_ex2_rslt0_vld, + pad_yy_icg_scan_en, + rtu_iu_pending_spec_expt_vld, + rtu_iu_pending_spec_halt_info_vld, + rtu_yy_xx_flush +); + +// &Ports; @24 +input [5 :0] ag_dp_ex1_dst_preg; +input [31:0] ag_dp_ex1_fwd_data; +input ag_dp_ex1_fwd_vld; +input alu_dp_ex1_cmplt; +input alu_dp_ex1_cmplt_dp; +input alu_dp_ex1_fwd_vld; +input [31:0] alu_dp_ex1_rslt; +input bju_dp_ex1_cmplt_dp; +input [31:0] bju_dp_ex1_rslt; +input bju_dp_ex1_rslt_vld; +input bju_dp_ex1_stall; +input bju_dp_no_op; +input cp0_iu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input div_ctrl_itering; +input div_dp_ex1_cmplt; +input div_dp_ex1_cmplt_dp; +input [31:0] div_dp_ex1_fwd_data; +input div_dp_ex1_fwd_vld; +input div_dp_ex1_stall; +input [5 :0] div_dp_ex2_dst_preg; +input [31:0] div_dp_ex2_rslt; +input div_dp_ex2_rslt_vld; +input forever_cpuclk; +input fpu_iu_ex1_cmplt; +input fpu_iu_ex1_cmplt_dp; +input idu_iu_ex1_alu_sel; +input [5 :0] idu_iu_ex1_dst_preg; +input idu_iu_ex1_gateclk_vld; +input idu_iu_ex1_inst_len; +input idu_iu_ex1_inst_vld; +input idu_iu_ex1_ipop_int_mask; +input idu_iu_ex1_ipush_mie_en; +input idu_iu_ex1_ipush_spec_fail; +input idu_iu_ex1_mul_sel; +input idu_iu_ex1_rd_pair; +input idu_iu_ex1_split; +input idu_iu_ex1_tail_int_vld; +input idu_iu_ex1_wb_vld; +input ifu_iu_warm_up; +input [5 :0] lsu_iu_ex2_lsi_dst_preg; +input [31:0] lsu_iu_ex2_lsi_rslt; +input lsu_iu_ex2_lsi_rslt_vld; +input lsu_rtu_ex1_cmplt_dp; +input mul_dp_ex1_cmplt; +input mul_dp_ex1_cmplt_dp; +input mul_dp_ex2_inst_vld; +input [31:0] mul_dp_ex2_rslt0; +input mul_dp_ex2_rslt0_vld; +input pad_yy_icg_scan_en; +input rtu_iu_pending_spec_expt_vld; +input rtu_iu_pending_spec_halt_info_vld; +input rtu_yy_xx_flush; +output dp_xx_ex1_stall; +output dp_xx_ex2_stall; +output iu_ex2_div_grant; +output [31:0] iu_idu_ex1_fwd_data; +output [5 :0] iu_idu_ex1_fwd_preg; +output iu_idu_ex1_fwd_vld; +output iu_idu_ex1_stall; +output iu_idu_ex2_div_vld; +output [31:0] iu_idu_ex2_fwd_data0; +output [31:0] iu_idu_ex2_fwd_data1; +output [5 :0] iu_idu_ex2_fwd_preg0; +output [5 :0] iu_idu_ex2_fwd_preg1; +output iu_idu_ex2_fwd_vld0; +output iu_idu_ex2_fwd_vld1; +output iu_idu_ex2_inst_vld; +output iu_idu_ex2_rd_pair; +output iu_idu_id_stall; +output iu_lsu_ex2_wb0_grant; +output iu_rtu_ex1_cmplt; +output iu_rtu_ex1_cmplt_dp; +output iu_rtu_ex1_inst_len; +output iu_rtu_ex1_inst_vld; +output iu_rtu_ex1_ipop_int_mask; +output iu_rtu_ex1_ipush_mie_en; +output iu_rtu_ex1_ipush_spec_fail; +output iu_rtu_ex1_split_inst; +output iu_rtu_ex1_tail_int_vld; +output [31:0] iu_rtu_wb0_data; +output [5 :0] iu_rtu_wb0_preg; +output iu_rtu_wb0_vld; +output iu_xx_no_op; + +// &Regs; @25 +reg [31:0] iu_ex1_fwd_data; +reg [5 :0] iu_ex1_fwd_preg; +reg iu_ex1_fwd_vld; +reg [5 :0] iu_ex2_ex1_dst_preg; +reg iu_ex2_ex1_ov_flag; +reg [31:0] iu_ex2_ex1_rslt; +reg iu_ex2_ex1_rslt_vld; +reg [31:0] iu_ex2_fwd_data0; +reg [5 :0] iu_ex2_fwd_preg; +reg iu_ex2_rd_pair; + +// &Wires; @26 +wire [5 :0] ag_dp_ex1_dst_preg; +wire [31:0] ag_dp_ex1_fwd_data; +wire ag_dp_ex1_fwd_vld; +wire alu_dp_ex1_borrow_vld; +wire alu_dp_ex1_cmplt; +wire alu_dp_ex1_cmplt_dp; +wire alu_dp_ex1_fwd_vld; +wire alu_dp_ex1_ov_flag; +wire [31:0] alu_dp_ex1_rslt; +wire alu_dp_ex1_rslt_vld; +wire [31:0] alu_dp_ex2_rslt0; +wire alu_dp_ex2_rslt0_vld; +wire [31:0] alu_dp_ex2_rslt1; +wire alu_dp_ex2_rslt1_vld; +wire bju_dp_ex1_cmplt_dp; +wire [31:0] bju_dp_ex1_rslt; +wire bju_dp_ex1_rslt_vld; +wire bju_dp_ex1_stall; +wire bju_dp_no_op; +wire cp0_iu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire div_ctrl_itering; +wire div_dp_ex1_cmplt; +wire div_dp_ex1_cmplt_dp; +wire [31:0] div_dp_ex1_fwd_data; +wire div_dp_ex1_fwd_vld; +wire div_dp_ex1_stall; +wire [5 :0] div_dp_ex2_dst_preg; +wire [31:0] div_dp_ex2_rslt; +wire div_dp_ex2_rslt_vld; +wire dp_xx_ex1_stall; +wire dp_xx_ex2_stall; +wire forever_cpuclk; +wire fpu_iu_ex1_cmplt; +wire fpu_iu_ex1_cmplt_dp; +wire idu_iu_ex1_alu_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_len; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_ipop_int_mask; +wire idu_iu_ex1_ipush_mie_en; +wire idu_iu_ex1_ipush_spec_fail; +wire idu_iu_ex1_mul_sel; +wire idu_iu_ex1_rd_pair; +wire idu_iu_ex1_split; +wire idu_iu_ex1_tail_int_vld; +wire idu_iu_ex1_wb_vld; +wire ifu_iu_warm_up; +wire iu_ctrl_clk; +wire iu_ctrl_clk_en; +wire iu_ex1_fwd_dp_clk; +wire iu_ex1_fwd_dp_clk_en; +wire [4 :0] iu_ex1_fwd_sel; +wire iu_ex1_inst_pipe_down; +wire iu_ex1_no_op; +wire iu_ex1_rslt_pipe_down; +wire iu_ex1_rslt_vld; +wire iu_ex2_div_data_vld; +wire iu_ex2_div_grant; +wire [31:0] iu_ex2_fwd_data1; +wire iu_ex2_fwd_vld0; +wire iu_ex2_inst_vld; +wire iu_ex2_lsu_data_vld; +wire iu_ex2_lsu_grant; +wire iu_ex2_no_op; +wire [4 :0] iu_ex2_rslt_sel; +wire iu_ex3_no_op; +wire [31:0] iu_idu_ex1_fwd_data; +wire [5 :0] iu_idu_ex1_fwd_preg; +wire iu_idu_ex1_fwd_vld; +wire iu_idu_ex1_stall; +wire iu_idu_ex2_div_vld; +wire [31:0] iu_idu_ex2_fwd_data0; +wire [31:0] iu_idu_ex2_fwd_data1; +wire [5 :0] iu_idu_ex2_fwd_preg0; +wire [5 :0] iu_idu_ex2_fwd_preg1; +wire iu_idu_ex2_fwd_vld0; +wire iu_idu_ex2_fwd_vld1; +wire iu_idu_ex2_inst_vld; +wire iu_idu_ex2_rd_pair; +wire iu_idu_id_stall; +wire iu_lsu_ex2_wb0_grant; +wire iu_rtu_ex1_cmplt; +wire iu_rtu_ex1_cmplt_dp; +wire iu_rtu_ex1_inst_len; +wire iu_rtu_ex1_inst_vld; +wire iu_rtu_ex1_ipop_int_mask; +wire iu_rtu_ex1_ipush_mie_en; +wire iu_rtu_ex1_ipush_spec_fail; +wire iu_rtu_ex1_split_inst; +wire iu_rtu_ex1_tail_int_vld; +wire [31:0] iu_rtu_wb0_data; +wire [5 :0] iu_rtu_wb0_preg; +wire iu_rtu_wb0_vld; +wire iu_xx_no_op; +wire [5 :0] lsu_iu_ex2_lsi_dst_preg; +wire [31:0] lsu_iu_ex2_lsi_rslt; +wire lsu_iu_ex2_lsi_rslt_vld; +wire lsu_rtu_ex1_cmplt_dp; +wire mul_dp_ex1_cmplt; +wire mul_dp_ex1_cmplt_dp; +wire mul_dp_ex2_inst_vld; +wire [31:0] mul_dp_ex2_rslt0; +wire mul_dp_ex2_rslt0_vld; +wire [31:0] mul_dp_ex2_rslt1; +wire mul_dp_ex2_rslt1_vld; +wire pad_yy_icg_scan_en; +wire rtu_iu_pending_spec_expt_vld; +wire rtu_iu_pending_spec_halt_info_vld; +wire rtu_yy_xx_flush; + + +// &Force("output","iu_rtu_wb0_vld"); @28 +// &Force("output","iu_rtu_wb0_preg"); @29 +// &Force("output","iu_idu_ex2_fwd_vld0"); @30 +// &Force("output","iu_idu_ex2_fwd_data0"); @31 +// &Force("output","iu_idu_ex2_fwd_preg0"); @32 +// &Force("output","iu_ex2_div_grant"); @33 +// &Force("output","iu_idu_ex2_fwd_vld1"); @34 +// &Force("noport", "iu_ex2_ex1_ov_flag"); @35 +//======================================================================= +// Fwd Datapath +//======================================================================= + +assign alu_dp_ex1_borrow_vld = 1'b0; +assign alu_dp_ex1_ov_flag = 1'b0; +assign alu_dp_ex1_rslt_vld = idu_iu_ex1_inst_vld & + idu_iu_ex1_alu_sel & + idu_iu_ex1_wb_vld; +assign alu_dp_ex2_rslt0_vld = 1'b0; +assign alu_dp_ex2_rslt1_vld = 1'b0; +assign alu_dp_ex2_rslt0[31:0] = 32'b0; +assign alu_dp_ex2_rslt1[31:0] = 32'b0; + +assign mul_dp_ex2_rslt1_vld = 1'b0; +assign mul_dp_ex2_rslt1[31:0] = 32'b0; +//--------- EX1 Result Mux ------------- +//Ex1 fwd data srcs: lsu/alu/bju/div +//mul fwd preg for idu without data +assign iu_ex1_fwd_sel[4:0] = {lsu_rtu_ex1_cmplt_dp, + alu_dp_ex1_cmplt_dp , + bju_dp_ex1_cmplt_dp , + mul_dp_ex1_cmplt_dp , + div_dp_ex1_cmplt_dp }; + +assign iu_ex1_rslt_vld = (bju_dp_ex1_rslt_vld | alu_dp_ex1_rslt_vld) & + (~(rtu_iu_pending_spec_expt_vld | rtu_iu_pending_spec_halt_info_vld)); +// &CombBeg @71 +always @( ag_dp_ex1_fwd_data[31:0] + or div_dp_ex1_fwd_data[31:0] + or bju_dp_ex1_rslt_vld + or ag_dp_ex1_fwd_vld + or alu_dp_ex1_fwd_vld + or iu_ex1_fwd_sel[4:0] + or ag_dp_ex1_dst_preg[5:0] + or bju_dp_ex1_rslt[31:0] + or alu_dp_ex1_rslt[31:0] + or div_dp_ex1_fwd_vld + or idu_iu_ex1_dst_preg[5:0]) +begin + case (iu_ex1_fwd_sel[4:0]) + 5'b00001: // From DIV + begin + iu_ex1_fwd_vld = div_dp_ex1_fwd_vld; + iu_ex1_fwd_preg[5:0] = idu_iu_ex1_dst_preg[5:0]; + iu_ex1_fwd_data[31:0] = div_dp_ex1_fwd_data[31:0]; + end + 5'b00010: // From MUL + begin + iu_ex1_fwd_vld = 1'b0; + iu_ex1_fwd_preg[5:0] = idu_iu_ex1_dst_preg[5:0]; + iu_ex1_fwd_data[31:0] = alu_dp_ex1_rslt[31:0]; + end + 5'b00100: // From BJU + begin + iu_ex1_fwd_vld = bju_dp_ex1_rslt_vld; + iu_ex1_fwd_preg[5:0] = idu_iu_ex1_dst_preg[5:0]; + iu_ex1_fwd_data[31:0] = bju_dp_ex1_rslt[31:0]; + end + 5'b01000: // From ALU + begin + iu_ex1_fwd_vld = alu_dp_ex1_fwd_vld; + iu_ex1_fwd_preg[5:0] = idu_iu_ex1_dst_preg[5:0]; + iu_ex1_fwd_data[31:0] = alu_dp_ex1_rslt[31:0]; + end + 5'b10000: // From LSU + begin + iu_ex1_fwd_vld = ag_dp_ex1_fwd_vld; + iu_ex1_fwd_preg[5:0] = ag_dp_ex1_dst_preg[5:0]; + iu_ex1_fwd_data[31:0] = ag_dp_ex1_fwd_data[31:0]; + end + default: + begin + iu_ex1_fwd_vld = 1'b0; + iu_ex1_fwd_preg[5:0] = {6{1'bx}}; + iu_ex1_fwd_data[31:0] = {32{1'bx}}; + end + endcase +// &CombEnd @110 +end + +//--------- EX2 Result Mux ------------- +//priority: iu > lsu_lsi > div, no grant with ex3 stall +//warning: ex3 wb mul should be considered +assign iu_ex2_inst_vld = alu_dp_ex2_rslt0_vld | + mul_dp_ex2_inst_vld | + iu_ex2_ex1_rslt_vld; + +assign iu_ex2_div_grant = (~iu_ex2_inst_vld) & + (~lsu_iu_ex2_lsi_rslt_vld); + +assign iu_ex2_lsu_grant = (~iu_ex2_inst_vld); + +assign iu_ex2_div_data_vld = div_dp_ex2_rslt_vld & + iu_ex2_div_grant; + +assign iu_ex2_lsu_data_vld = lsu_iu_ex2_lsi_rslt_vld & + iu_ex2_lsu_grant; +//Ex2 fwd data src: ex1 pipe rslt/div/mul/alu +//limit: mul/alu must fwd wb1 with wb0 fwd vld +assign iu_ex2_rslt_sel[4:0] = {iu_ex2_lsu_data_vld , + mul_dp_ex2_rslt0_vld, + alu_dp_ex2_rslt0_vld, + iu_ex2_ex1_rslt_vld , + iu_ex2_div_data_vld }; +assign iu_ex2_fwd_vld0 = |iu_ex2_rslt_sel[4:0]; +// &CombBeg @137 +always @( lsu_iu_ex2_lsi_dst_preg[5:0] + or div_dp_ex2_dst_preg[5:0] + or iu_ex2_rslt_sel[4:0] + or iu_ex2_ex1_dst_preg[5:0] + or lsu_iu_ex2_lsi_rslt[31:0] + or iu_ex2_ex1_rslt[31:0] + or alu_dp_ex2_rslt0[31:0] + or div_dp_ex2_rslt[31:0] + or mul_dp_ex2_rslt0[31:0]) +begin + case(iu_ex2_rslt_sel[4:0]) + 5'b00001: // From DIV + begin + iu_ex2_fwd_data0[31:0] = div_dp_ex2_rslt[31:0]; + iu_ex2_fwd_preg[5:0] = div_dp_ex2_dst_preg[5:0]; + end + 5'b00010: // From Ex1 + begin + iu_ex2_fwd_data0[31:0] = iu_ex2_ex1_rslt[31:0]; + iu_ex2_fwd_preg[5:0] = iu_ex2_ex1_dst_preg[5:0]; + end + 5'b00100: // From ALU + begin + iu_ex2_fwd_data0[31:0] = alu_dp_ex2_rslt0[31:0]; + iu_ex2_fwd_preg[5:0] = iu_ex2_ex1_dst_preg[5:0]; + end + 5'b01000: // From MUL + begin + iu_ex2_fwd_data0[31:0] = mul_dp_ex2_rslt0[31:0]; + iu_ex2_fwd_preg[5:0] = iu_ex2_ex1_dst_preg[5:0]; + end + 5'b10000: // From LSU + begin + iu_ex2_fwd_data0[31:0] = lsu_iu_ex2_lsi_rslt[31:0]; + iu_ex2_fwd_preg[5:0] = lsu_iu_ex2_lsi_dst_preg[5:0]; + end + default: + begin + iu_ex2_fwd_data0[31:0] = {32{1'bx}}; + iu_ex2_fwd_preg[5:0] = iu_ex2_ex1_dst_preg[5:0]; + end + endcase +// &CombEnd @170 +end + +assign iu_ex2_fwd_data1[31:0] = {32{mul_dp_ex2_rslt1_vld}} & mul_dp_ex2_rslt1[31:0] | + {32{alu_dp_ex2_rslt1_vld}} & alu_dp_ex2_rslt1[31:0]; +//--------- EX3 Result Mux ------------- +//Ex2 fwd src: ex2-ex3/mul +// &CombBeg @181 +// &CombEnd @196 +//======================================================================= +// Pipeline +//======================================================================= +//--------- Ex1-Ex2 Pipe reg ------------- +// &Instance("gated_clk_cell", "x_iu_ex1_fwd_dp_clk"); @206 +gated_clk_cell x_iu_ex1_fwd_dp_clk ( + .clk_in (forever_cpuclk ), + .clk_out (iu_ex1_fwd_dp_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (iu_ex1_fwd_dp_clk_en), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @207 +// .external_en (1'b0), @208 +// .global_en (cp0_yy_clk_en), @209 +// .module_en (cp0_iu_icg_en), @210 +// .local_en (iu_ex1_fwd_dp_clk_en), @211 +// .clk_out (iu_ex1_fwd_dp_clk)); @212 + +//pipe register shared by result and preg pipe +assign iu_ex1_rslt_pipe_down = iu_ex1_rslt_vld | alu_dp_ex1_borrow_vld; + +assign iu_ex1_inst_pipe_down = idu_iu_ex1_inst_vld & + (idu_iu_ex1_mul_sel | + idu_iu_ex1_alu_sel); +assign iu_ex1_fwd_dp_clk_en = iu_ex1_rslt_pipe_down | iu_ex1_inst_pipe_down + | ifu_iu_warm_up; + +always@(posedge iu_ex1_fwd_dp_clk) +begin + if( iu_ex1_rslt_pipe_down | iu_ex1_inst_pipe_down | ifu_iu_warm_up) + begin + iu_ex2_ex1_dst_preg[5:0] <= iu_ex1_fwd_preg[5:0]; + iu_ex2_rd_pair <= idu_iu_ex1_rd_pair; + end + else + begin + iu_ex2_ex1_dst_preg[5:0] <= iu_ex2_ex1_dst_preg[5:0]; + iu_ex2_rd_pair <= iu_ex2_rd_pair; + end +end + + +always@(posedge iu_ex1_fwd_dp_clk) +begin + if( iu_ex1_rslt_pipe_down | ifu_iu_warm_up) + begin + iu_ex2_ex1_rslt[31:0] <= iu_ex1_fwd_data[31:0]; + iu_ex2_ex1_ov_flag <= alu_dp_ex1_ov_flag; + end + else + begin + iu_ex2_ex1_rslt[31:0] <= iu_ex2_ex1_rslt[31:0]; + iu_ex2_ex1_ov_flag <= iu_ex2_ex1_ov_flag; + end +end + +//--------- Ex2-Ex3 Pipe reg ------------- +// &Instance("gated_clk_cell", "x_iu_ex2_fwd0_dp_clk"); @301 +// &Connect(.clk_in (forever_cpuclk), @302 +// .external_en (1'b0), @303 +// .global_en (cp0_yy_clk_en), @304 +// .module_en (cp0_iu_icg_en), @305 +// .local_en (iu_ex2_fwd0_dp_clk_en), @306 +// .clk_out (iu_ex2_fwd0_dp_clk)); @307 +// &Instance("gated_clk_cell", "x_iu_ex2_fwd1_dp_clk"); @380 +// &Connect(.clk_in (forever_cpuclk), @381 +// .external_en (1'b0), @382 +// .global_en (cp0_yy_clk_en), @383 +// .module_en (cp0_iu_icg_en), @384 +// .local_en (iu_ex2_fwd1_dp_clk_en), @385 +// .clk_out (iu_ex2_fwd1_dp_clk)); @386 + +// &Instance("gated_clk_cell", "x_iu_wb_ov_dp_clk"); @425 +// &Connect(.clk_in (forever_cpuclk), @426 +// .external_en (1'b0), @427 +// .global_en (cp0_yy_clk_en), @428 +// .module_en (cp0_iu_icg_en), @429 +// .local_en (iu_wb_ov_dp_clk_en), @430 +// .clk_out (iu_wb_ov_dp_clk)); @431 +//---------------------------------------------------------- +// Ctrl Signal +//---------------------------------------------------------- +assign iu_ctrl_clk_en = idu_iu_ex1_gateclk_vld | + iu_idu_ex2_fwd_vld0 | + iu_ex2_ex1_rslt_vld | + rtu_yy_xx_flush; + +// &Instance("gated_clk_cell", "x_iu_ctrl_clk"); @494 +gated_clk_cell x_iu_ctrl_clk ( + .clk_in (forever_cpuclk ), + .clk_out (iu_ctrl_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (iu_ctrl_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @495 +// .external_en (1'b0), @496 +// .global_en (cp0_yy_clk_en), @497 +// .module_en (cp0_iu_icg_en), @498 +// .local_en (iu_ctrl_clk_en), @499 +// .clk_out (iu_ctrl_clk)); @500 + + +always@(posedge iu_ctrl_clk or negedge cpurst_b) +begin + if (~cpurst_b) + begin + iu_ex2_ex1_rslt_vld <= 1'b0; + end + else if (rtu_yy_xx_flush) + begin + iu_ex2_ex1_rslt_vld <= 1'b0; + end + else if (iu_ex1_rslt_vld) + begin + iu_ex2_ex1_rslt_vld <= 1'b1; + end + else + begin + iu_ex2_ex1_rslt_vld <= 1'b0; + end +end + + +//========================================================== +// Signal for RTU +//========================================================== +//--------- cmplt---- ------------- +assign iu_rtu_ex1_cmplt = alu_dp_ex1_cmplt | mul_dp_ex1_cmplt | + div_dp_ex1_cmplt | fpu_iu_ex1_cmplt; +assign iu_rtu_ex1_cmplt_dp = alu_dp_ex1_cmplt_dp | mul_dp_ex1_cmplt_dp | + div_dp_ex1_cmplt_dp | fpu_iu_ex1_cmplt_dp; + +assign iu_rtu_ex1_split_inst = idu_iu_ex1_split; +assign iu_rtu_ex1_ipop_int_mask = idu_iu_ex1_ipop_int_mask & alu_dp_ex1_cmplt_dp; +assign iu_rtu_ex1_ipush_mie_en = idu_iu_ex1_ipush_mie_en & alu_dp_ex1_cmplt_dp & + (~(rtu_iu_pending_spec_expt_vld | rtu_iu_pending_spec_halt_info_vld)); +assign iu_rtu_ex1_tail_int_vld = idu_iu_ex1_tail_int_vld & alu_dp_ex1_cmplt_dp; +assign iu_rtu_ex1_ipush_spec_fail = idu_iu_ex1_ipush_spec_fail & alu_dp_ex1_cmplt_dp; +assign iu_rtu_ex1_inst_len = idu_iu_ex1_inst_len; +assign iu_rtu_ex1_inst_vld = idu_iu_ex1_gateclk_vld; +//--------- Wb Result ------------- +assign iu_rtu_wb0_vld = iu_idu_ex2_fwd_vld0; +assign iu_rtu_wb0_preg[5:0] = iu_idu_ex2_fwd_preg0[5:0]; +assign iu_rtu_wb0_data[31:0] = iu_idu_ex2_fwd_data0[31:0]; + +//========================================================== +// Signal for IDU +//========================================================== +assign iu_ex1_no_op = ~idu_iu_ex1_inst_vld; +assign iu_ex2_no_op = ~(iu_ex2_fwd_vld0 | mul_dp_ex2_inst_vld); +assign iu_ex3_no_op = 1'b1; + +assign iu_xx_no_op = iu_ex1_no_op & + iu_ex2_no_op & + iu_ex3_no_op & + bju_dp_no_op & + (~div_ctrl_itering); + +assign iu_idu_ex1_stall = div_dp_ex1_stall | bju_dp_ex1_stall ; + +assign iu_idu_id_stall = 1'b0; +assign iu_idu_ex1_fwd_vld = iu_ex1_fwd_vld; +assign iu_idu_ex1_fwd_data[31:0] = iu_ex1_fwd_data[31:0]; +assign iu_idu_ex1_fwd_preg[5:0] = iu_ex1_fwd_preg[5:0]; + +assign iu_idu_ex2_inst_vld = iu_ex2_inst_vld; +assign iu_idu_ex2_rd_pair = iu_ex2_rd_pair; +assign iu_idu_ex2_div_vld = iu_ex2_div_data_vld; +assign iu_idu_ex2_fwd_vld0 = iu_ex2_fwd_vld0; +assign iu_idu_ex2_fwd_data0[31:0] = iu_ex2_fwd_data0[31:0]; +assign iu_idu_ex2_fwd_preg0[5:0] = iu_ex2_fwd_preg[5:0]; +assign iu_idu_ex2_fwd_vld1 = mul_dp_ex2_rslt1_vld | alu_dp_ex2_rslt1_vld; +assign iu_idu_ex2_fwd_data1[31:0] = iu_ex2_fwd_data1[31:0]; + +assign iu_idu_ex2_fwd_preg1[5:0] = 6'b0; +//========================================================== +// signals for cp0 +//========================================================== + +//assign iu_cp0_wb_fflags_updt = iu_wb_fflags_updt; +//assign iu_cp0_wb_fflags[4:0] = iu_wb_fflags[4:0]; +//========================================================== +// IU internal signals +//========================================================== +assign dp_xx_ex2_stall = 1'b0; +assign dp_xx_ex1_stall = 1'b0; + +// &Force("nonport","dp_alu_ex2_rslt"); @707 +//========================================================== +// signals for LSU +//========================================================== +assign iu_lsu_ex2_wb0_grant = lsu_iu_ex2_lsi_rslt_vld & iu_ex2_lsu_grant; + +// &Force("input", "idu_iu_ex1_bju_gateclk_sel"); @718 +// &Force("input", "idu_iu_ex1_div_sel"); @719 +// &Force("nonport", "rtu_flush_ff"); @720 +// &ModuleEnd; @885 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div.v new file mode 100644 index 0000000000000000000000000000000000000000..75abf903bcabd2c96adf32550b2adf8f5490cd11 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div.v @@ -0,0 +1,774 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_div( + cp0_iu_icg_en, + cp0_yy_clk_en, + cpurst_b, + div_ctrl_itering, + div_dp_ex1_cmplt, + div_dp_ex1_cmplt_dp, + div_dp_ex1_fwd_data, + div_dp_ex1_fwd_vld, + div_dp_ex1_stall, + div_dp_ex2_dst_preg, + div_dp_ex2_rslt, + div_dp_ex2_rslt_vld, + div_iu_debug_info, + forever_cpuclk, + idu_iu_ex1_div_cmplt_dp_sel, + idu_iu_ex1_div_gateclk_sel, + idu_iu_ex1_div_sel, + idu_iu_ex1_dst_preg, + idu_iu_ex1_func, + idu_iu_ex1_inst_vld, + idu_iu_ex1_src0, + idu_iu_ex1_src1, + idu_iu_ex1_wb_vld, + ifu_iu_warm_up, + iu_ex2_div_grant, + pad_yy_icg_scan_en, + rtu_yy_xx_async_flush +); + +// &Ports; @24 +input cp0_iu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input idu_iu_ex1_div_cmplt_dp_sel; +input idu_iu_ex1_div_gateclk_sel; +input idu_iu_ex1_div_sel; +input [5 :0] idu_iu_ex1_dst_preg; +input [19:0] idu_iu_ex1_func; +input idu_iu_ex1_inst_vld; +input [31:0] idu_iu_ex1_src0; +input [31:0] idu_iu_ex1_src1; +input idu_iu_ex1_wb_vld; +input ifu_iu_warm_up; +input iu_ex2_div_grant; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +output div_ctrl_itering; +output div_dp_ex1_cmplt; +output div_dp_ex1_cmplt_dp; +output [31:0] div_dp_ex1_fwd_data; +output div_dp_ex1_fwd_vld; +output div_dp_ex1_stall; +output [5 :0] div_dp_ex2_dst_preg; +output [31:0] div_dp_ex2_rslt; +output div_dp_ex2_rslt_vld; +output [4 :0] div_iu_debug_info; + +// &Regs; @25 +reg [2 :0] div_cur_state; +reg [31:0] div_dividend_raw; +reg div_divisor_31; +reg [31:0] div_divisor_reg; +reg [4 :0] div_dst_preg; +reg [3 :0] div_ex1_res_onehot_flop; +reg [4 :0] div_ff1_res_pos; +reg [2 :0] div_next_state; +reg div_oper_is_signed_flop; +reg [31:0] div_quotient_reg; +reg [31:0] div_remainder_reg; +reg div_res_sel_quotient_flop; +reg [31:0] div_special_res_quotient; +reg [31:0] div_special_res_remainder; +reg div_special_res_vld; + +// &Wires; @26 +wire cp0_iu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire [31:0] div_abnormal_quotient; +wire [31:0] div_abnormal_remainder; +wire [31:0] div_abnormal_res; +wire div_abnormal_res_vld; +wire [31:0] div_abs_res; +wire [31:0] div_abs_src; +wire div_buffer_update; +wire div_clk; +wire div_clk_en; +wire div_clk_en_raw; +wire div_cmplt; +wire div_ctrl_itering; +wire [31:0] div_dividend; +wire div_dividend_31; +wire div_dividend_eq0; +wire [31:0] div_dividend_eq0_quotient; +wire [31:0] div_dividend_eq0_remainder; +wire div_dividend_hit_buffer; +wire [31:0] div_divisor; +wire div_divisor_eq0; +wire [31:0] div_divisor_eq0_quotient; +wire [31:0] div_divisor_eq0_remainder; +wire div_divisor_hit_buffer; +wire [31:0] div_divisor_raw; +wire div_divisor_raw_is_neg; +wire div_dp_ex1_cmplt; +wire div_dp_ex1_cmplt_dp; +wire [31:0] div_dp_ex1_fwd_data; +wire div_dp_ex1_fwd_vld; +wire div_dp_ex1_stall; +wire [5 :0] div_dp_ex2_dst_preg; +wire [31:0] div_dp_ex2_rslt; +wire div_dp_ex2_rslt_vld; +wire [31:0] div_ex1_res; +wire [3 :0] div_ex1_res_onehot; +wire div_ex1_res_vld; +wire div_ex1_res_vld_raw; +wire div_ex1_stall; +wire div_ex2_enable_wb; +wire [31:0] div_ex2_res; +wire div_ex2_res_vld; +wire div_ex2_res_vld_raw; +wire [4 :0] div_ff1_res; +wire [4 :0] div_ff1_res_neg; +wire [31:0] div_ff1_src; +wire div_flush; +wire div_flush_buffer; +wire div_hit_buffer; +wire [31:0] div_hit_buffer_res; +wire div_hit_buffer_res_vld; +wire div_inst_vld; +wire div_is_idle; +wire div_is_signed; +wire div_iter_cmplt; +wire div_iter_start; +wire div_iterating; +wire [4 :0] div_iu_debug_info; +wire [31:0] div_normal_quotient; +wire [31:0] div_normal_remainder; +wire div_not_cmplt; +wire div_oper_is_signed; +wire div_preg_updt_vld; +wire div_prepare_src0; +wire div_prepare_src1; +wire [31:0] div_quotient_reg_updt; +wire [31:0] div_quotient_res; +wire [31:0] div_remainder_reg_updt; +wire [31:0] div_remainder_res; +wire div_res_overflow; +wire [31:0] div_res_overflow_quotient; +wire [31:0] div_res_overflow_remainder; +wire div_res_quotient_neg; +wire div_res_remainder_neg; +wire div_res_sel_quotient; +wire div_signed_hit_buffer; +wire [31:0] div_special_res; +wire div_special_res_vld_update; +wire div_src_is_neg; +wire [4 :0] div_sub_func; +wire div_wfwb; +wire forever_cpuclk; +wire idu_iu_ex1_div_cmplt_dp_sel; +wire idu_iu_ex1_div_gateclk_sel; +wire idu_iu_ex1_div_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_inst_vld; +wire [31:0] idu_iu_ex1_src0; +wire [31:0] idu_iu_ex1_src1; +wire idu_iu_ex1_wb_vld; +wire ifu_iu_warm_up; +wire iu_ex2_div_grant; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_async_flush; + + +// &Force("bus", "idu_iu_ex1_func", 19, 0); @28 + +assign div_inst_vld = idu_iu_ex1_inst_vld && idu_iu_ex1_div_sel; +assign div_sub_func[4:0] = {5{idu_iu_ex1_div_gateclk_sel}} & idu_iu_ex1_func[4:0]; +assign div_oper_is_signed = div_sub_func[0] || div_sub_func[2]; +assign div_res_sel_quotient = div_sub_func[0] || div_sub_func[1]; + +assign div_dividend[31:0] = {32{idu_iu_ex1_div_gateclk_sel}} & idu_iu_ex1_src0[31:0]; +assign div_divisor[31:0] = {32{idu_iu_ex1_div_gateclk_sel}} & idu_iu_ex1_src1[31:0]; + +assign div_preg_updt_vld = idu_iu_ex1_div_gateclk_sel & ~div_ex1_stall; +// &Force("bus", "idu_iu_ex1_dst_preg", 5, 0); @39 +always @ (posedge div_clk) +begin + if (ifu_iu_warm_up) + div_dst_preg[4:0] <= 5'b0; + else if (div_preg_updt_vld) + div_dst_preg[4:0] <= idu_iu_ex1_dst_preg[4:0]; + else + div_dst_preg[4:0] <= div_dst_preg[4:0]; +end + +//========================================================== +// DIV Main State Machine +//========================================================== +parameter IDLE = 3'b000, + WFI2 = 3'b001, + ITER = 3'b010, + CMPLT = 3'b011, + WFWB = 3'b100; // EX2 stall set and must wait for wb. + +always @ (posedge div_clk or negedge cpurst_b) +begin + if (!cpurst_b) + div_cur_state[2:0] <= IDLE; + else if (div_flush) + div_cur_state[2:0] <= IDLE; + else + div_cur_state[2:0] <= div_next_state[2:0]; +end + +// &CombBeg; @83 +always @( div_iter_start + or div_ex2_enable_wb + or div_cur_state[2:0] + or div_ex1_res_vld + or div_iter_cmplt) +begin +case (div_cur_state[2:0]) + IDLE: + begin + if (div_iter_start) + div_next_state[2:0] = WFI2; + else if(div_ex1_res_vld) + div_next_state[2:0] = WFWB; + else + div_next_state[2:0] = IDLE; + end + WFI2: + div_next_state[2:0] = ITER; + ITER: + begin + if (div_iter_cmplt) + div_next_state[2:0] = CMPLT; + else + div_next_state[2:0] = ITER; + end + CMPLT: + begin + if (div_ex2_enable_wb) + if (div_iter_start) + div_next_state[2:0] = WFI2; + else if (div_ex1_res_vld) + div_next_state[2:0] = WFWB; + else + div_next_state[2:0] = IDLE; + else + div_next_state[2:0] = WFWB; + end + WFWB: + begin + if (div_ex2_enable_wb) + if (div_iter_start) + div_next_state[2:0] = WFI2; + else if (div_ex1_res_vld) + div_next_state[2:0] = WFWB; + else + div_next_state[2:0] = IDLE; + else + div_next_state[2:0] = WFWB; + end + default: + div_next_state[2:0] = IDLE; +endcase +// &CombEnd; @130 +end + + +assign div_is_idle = div_cur_state[2:0] == IDLE + || div_ex2_res_vld; // Next state will be IDLE; +assign div_iter_start = div_inst_vld && !div_ex1_res_vld_raw; +assign div_prepare_src0 = div_is_idle && div_iter_start; +assign div_prepare_src1 = div_cur_state[2:0] == WFI2; +assign div_iterating = div_cur_state[2:0] == ITER; +assign div_cmplt = div_cur_state[2:0] == CMPLT; +assign div_wfwb = div_cur_state[2:0] == WFWB; + +//========================================================== +// Special Result Judgement +//========================================================== +// Judge if abnormal result or not @ IDLE +assign div_dividend_eq0 = div_dividend[31:0] == 32'b0; +assign div_dividend_eq0_quotient[31:0] = 32'b0; +assign div_dividend_eq0_remainder[31:0] = 32'b0; + +assign div_divisor_eq0 = div_divisor[31:0] == 32'b0; +assign div_divisor_eq0_quotient[31:0] = 32'hffff_ffff; +assign div_divisor_eq0_remainder[31:0] = div_dividend[31:0]; + +assign div_res_overflow = div_oper_is_signed + && (div_dividend[31:0] == 32'h8000_0000) + && (div_divisor[31:0] == 32'hffff_ffff); +assign div_res_overflow_quotient[31:0] = 32'h8000_0000; +assign div_res_overflow_remainder[31:0] = 32'b0; + +assign div_abnormal_res_vld = div_dividend_eq0 + || div_divisor_eq0 + || div_res_overflow; +assign div_abnormal_quotient[31:0] = {32{div_dividend_eq0}} & div_dividend_eq0_quotient[31:0] + | {32{div_divisor_eq0}} & div_divisor_eq0_quotient[31:0] + | {32{div_res_overflow}} & div_res_overflow_quotient[31:0]; +assign div_abnormal_remainder[31:0] = {32{div_dividend_eq0}} & div_dividend_eq0_remainder[31:0] + | {32{div_divisor_eq0}} & div_divisor_eq0_remainder[31:0] + | {32{div_res_overflow}} & div_res_overflow_remainder[31:0]; +assign div_abnormal_res[31:0] = div_res_sel_quotient ? div_abnormal_quotient[31:0] + : div_abnormal_remainder[31:0]; + +assign div_hit_buffer_res_vld = div_hit_buffer & ~div_abnormal_res_vld; +assign div_hit_buffer_res[31:0] = div_res_sel_quotient ? div_quotient_res[31:0] + : div_remainder_res[31:0]; + +assign div_ex1_res_vld_raw = (div_abnormal_res_vld || div_hit_buffer_res_vld) + && div_is_idle; +assign div_ex1_res[31:0] = div_abnormal_res_vld ? div_abnormal_res[31:0] + : div_hit_buffer_res[31:0]; +assign div_ex1_res_vld = div_ex1_res_vld_raw && div_inst_vld; +assign div_ex1_res_onehot[3:0] = {div_hit_buffer_res_vld, + div_dividend_eq0 && !div_divisor_eq0, + div_divisor_eq0, + div_res_overflow}; + +always @(posedge div_clk) +begin + if (ifu_iu_warm_up) begin + div_ex1_res_onehot_flop[3:0] <= 4'b0; + end + else if (div_ex1_res_vld)begin + div_ex1_res_onehot_flop[3:0] <= div_ex1_res_onehot[3:0]; + end +end + +assign div_special_res_vld_update = div_is_idle && div_inst_vld; +assign div_buffer_update = div_is_idle && div_inst_vld; +always @(posedge div_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + div_special_res_vld <= 1'b0; + end + else if (div_special_res_vld_update)begin + div_special_res_vld <= div_ex1_res_vld_raw; + end +end + +// &CombBeg; @222 +always @( div_ex1_res_onehot_flop[3:0] + or div_quotient_res[31:0]) +begin + case(div_ex1_res_onehot_flop[3:0]) + 4'b0001 : div_special_res_quotient[31:0] = 32'h8000_0000; + 4'b0010 : div_special_res_quotient[31:0] = 32'hffff_ffff; + 4'b0100 : div_special_res_quotient[31:0] = 32'b0; + 4'b1000 : div_special_res_quotient[31:0] = div_quotient_res[31:0]; + default: div_special_res_quotient[31:0] = {32{1'bx}}; + endcase +// &CombEnd @230 +end + +// &CombBeg; @232 +always @( div_dividend_raw[31:0] + or div_ex1_res_onehot_flop[3:0] + or div_remainder_res[31:0]) +begin + case(div_ex1_res_onehot_flop[3:0]) + 4'b0001 : div_special_res_remainder[31:0] = 32'b0; + 4'b0010 : div_special_res_remainder[31:0] = div_dividend_raw[31:0]; + 4'b0100 : div_special_res_remainder[31:0] = 32'b0; + 4'b1000 : div_special_res_remainder[31:0] = div_remainder_res[31:0]; + default: div_special_res_remainder[31:0] = {32{1'bx}}; + endcase +// &CombEnd @240 +end + +assign div_special_res[31:0] = div_res_sel_quotient_flop ? div_special_res_quotient[31:0] + : div_special_res_remainder[31:0]; + +//========================================================== +// Abs and FF1 +//========================================================== +// Calculate ABS and find first 1 @ IDLE and WFI2 +// div_prepare_src0 is dirty. Must use other signal as ctrl signal. +assign div_abs_src[31:0] = div_prepare_src1 ? div_divisor_reg[31:0] + : div_dividend[31:0]; + +assign div_is_signed = div_prepare_src1 ? div_oper_is_signed_flop + : div_oper_is_signed; + +assign div_src_is_neg = div_is_signed ? div_abs_src[31] + : 1'b0; + +assign div_abs_res[31:0] = div_src_is_neg ? ~div_abs_src[31:0] + 32'b1 + : div_abs_src[31:0]; + +assign div_ff1_src[31:0] = div_abs_src[31:0]; +// &CombBeg; @263 +always @( div_ff1_src[31:0]) +begin + casez (div_ff1_src[31:0]) + 32'b1???????????????????????????????: div_ff1_res_pos[4:0] = 5'd31; + 32'b01??????????????????????????????: div_ff1_res_pos[4:0] = 5'd30; + 32'b001?????????????????????????????: div_ff1_res_pos[4:0] = 5'd29; + 32'b0001????????????????????????????: div_ff1_res_pos[4:0] = 5'd28; + 32'b00001???????????????????????????: div_ff1_res_pos[4:0] = 5'd27; + 32'b000001??????????????????????????: div_ff1_res_pos[4:0] = 5'd26; + 32'b0000001?????????????????????????: div_ff1_res_pos[4:0] = 5'd25; + 32'b00000001????????????????????????: div_ff1_res_pos[4:0] = 5'd24; + 32'b000000001???????????????????????: div_ff1_res_pos[4:0] = 5'd23; + 32'b0000000001??????????????????????: div_ff1_res_pos[4:0] = 5'd22; + 32'b00000000001?????????????????????: div_ff1_res_pos[4:0] = 5'd21; + 32'b000000000001????????????????????: div_ff1_res_pos[4:0] = 5'd20; + 32'b0000000000001???????????????????: div_ff1_res_pos[4:0] = 5'd19; + 32'b00000000000001??????????????????: div_ff1_res_pos[4:0] = 5'd18; + 32'b000000000000001?????????????????: div_ff1_res_pos[4:0] = 5'd17; + 32'b0000000000000001????????????????: div_ff1_res_pos[4:0] = 5'd16; + 32'b00000000000000001???????????????: div_ff1_res_pos[4:0] = 5'd15; + 32'b000000000000000001??????????????: div_ff1_res_pos[4:0] = 5'd14; + 32'b0000000000000000001?????????????: div_ff1_res_pos[4:0] = 5'd13; + 32'b00000000000000000001????????????: div_ff1_res_pos[4:0] = 5'd12; + 32'b000000000000000000001???????????: div_ff1_res_pos[4:0] = 5'd11; + 32'b0000000000000000000001??????????: div_ff1_res_pos[4:0] = 5'd10; + 32'b00000000000000000000001?????????: div_ff1_res_pos[4:0] = 5'd9; + 32'b000000000000000000000001????????: div_ff1_res_pos[4:0] = 5'd8; + 32'b0000000000000000000000001???????: div_ff1_res_pos[4:0] = 5'd7; + 32'b00000000000000000000000001??????: div_ff1_res_pos[4:0] = 5'd6; + 32'b000000000000000000000000001?????: div_ff1_res_pos[4:0] = 5'd5; + 32'b0000000000000000000000000001????: div_ff1_res_pos[4:0] = 5'd4; + 32'b00000000000000000000000000001???: div_ff1_res_pos[4:0] = 5'd3; + 32'b000000000000000000000000000001??: div_ff1_res_pos[4:0] = 5'd2; + 32'b0000000000000000000000000000001?: div_ff1_res_pos[4:0] = 5'd1; + 32'b00000000000000000000000000000001: div_ff1_res_pos[4:0] = 5'd0; + 32'b00000000000000000000000000000000: div_ff1_res_pos[4:0] = 5'd0; // In div, src eq 0 is meanless, don't care. + default: div_ff1_res_pos[4:0] = {5{1'bx}}; + endcase +// &CombEnd; @300 +end + +//---------------------------------------------------------- +// Negetive FF1 +//---------------------------------------------------------- +assign div_ff1_res_neg[4:0] = + {5{ div_ff1_src[31] && !div_ff1_src[30] && !(|div_ff1_src[29:0])}} & 5'd31 +| {5{ div_ff1_src[31] && !div_ff1_src[30] && (|div_ff1_src[29:0])}} & 5'd30 +| {5{(&div_ff1_src[31:30]) && !div_ff1_src[29] && !(|div_ff1_src[28:0])}} & 5'd30 +| {5{(&div_ff1_src[31:30]) && !div_ff1_src[29] && (|div_ff1_src[28:0])}} & 5'd29 +| {5{(&div_ff1_src[31:29]) && !div_ff1_src[28] && !(|div_ff1_src[27:0])}} & 5'd29 +| {5{(&div_ff1_src[31:29]) && !div_ff1_src[28] && (|div_ff1_src[27:0])}} & 5'd28 +| {5{(&div_ff1_src[31:28]) && !div_ff1_src[27] && !(|div_ff1_src[26:0])}} & 5'd28 +| {5{(&div_ff1_src[31:28]) && !div_ff1_src[27] && (|div_ff1_src[26:0])}} & 5'd27 +| {5{(&div_ff1_src[31:27]) && !div_ff1_src[26] && !(|div_ff1_src[25:0])}} & 5'd27 +| {5{(&div_ff1_src[31:27]) && !div_ff1_src[26] && (|div_ff1_src[25:0])}} & 5'd26 +| {5{(&div_ff1_src[31:26]) && !div_ff1_src[25] && !(|div_ff1_src[24:0])}} & 5'd26 +| {5{(&div_ff1_src[31:26]) && !div_ff1_src[25] && (|div_ff1_src[24:0])}} & 5'd25 +| {5{(&div_ff1_src[31:25]) && !div_ff1_src[24] && !(|div_ff1_src[23:0])}} & 5'd25 +| {5{(&div_ff1_src[31:25]) && !div_ff1_src[24] && (|div_ff1_src[23:0])}} & 5'd24 +| {5{(&div_ff1_src[31:24]) && !div_ff1_src[23] && !(|div_ff1_src[22:0])}} & 5'd24 +| {5{(&div_ff1_src[31:24]) && !div_ff1_src[23] && (|div_ff1_src[22:0])}} & 5'd23 +| {5{(&div_ff1_src[31:23]) && !div_ff1_src[22] && !(|div_ff1_src[21:0])}} & 5'd23 +| {5{(&div_ff1_src[31:23]) && !div_ff1_src[22] && (|div_ff1_src[21:0])}} & 5'd22 +| {5{(&div_ff1_src[31:22]) && !div_ff1_src[21] && !(|div_ff1_src[20:0])}} & 5'd22 +| {5{(&div_ff1_src[31:22]) && !div_ff1_src[21] && (|div_ff1_src[20:0])}} & 5'd21 +| {5{(&div_ff1_src[31:21]) && !div_ff1_src[20] && !(|div_ff1_src[19:0])}} & 5'd21 +| {5{(&div_ff1_src[31:21]) && !div_ff1_src[20] && (|div_ff1_src[19:0])}} & 5'd20 +| {5{(&div_ff1_src[31:20]) && !div_ff1_src[19] && !(|div_ff1_src[18:0])}} & 5'd20 +| {5{(&div_ff1_src[31:20]) && !div_ff1_src[19] && (|div_ff1_src[18:0])}} & 5'd19 +| {5{(&div_ff1_src[31:19]) && !div_ff1_src[18] && !(|div_ff1_src[17:0])}} & 5'd19 +| {5{(&div_ff1_src[31:19]) && !div_ff1_src[18] && (|div_ff1_src[17:0])}} & 5'd18 +| {5{(&div_ff1_src[31:18]) && !div_ff1_src[17] && !(|div_ff1_src[16:0])}} & 5'd18 +| {5{(&div_ff1_src[31:18]) && !div_ff1_src[17] && (|div_ff1_src[16:0])}} & 5'd17 +| {5{(&div_ff1_src[31:17]) && !div_ff1_src[16] && !(|div_ff1_src[15:0])}} & 5'd17 +| {5{(&div_ff1_src[31:17]) && !div_ff1_src[16] && (|div_ff1_src[15:0])}} & 5'd16 +| {5{(&div_ff1_src[31:16]) && !div_ff1_src[15] && !(|div_ff1_src[14:0])}} & 5'd16 +| {5{(&div_ff1_src[31:16]) && !div_ff1_src[15] && (|div_ff1_src[14:0])}} & 5'd15 +| {5{(&div_ff1_src[31:15]) && !div_ff1_src[14] && !(|div_ff1_src[13:0])}} & 5'd15 +| {5{(&div_ff1_src[31:15]) && !div_ff1_src[14] && (|div_ff1_src[13:0])}} & 5'd14 +| {5{(&div_ff1_src[31:14]) && !div_ff1_src[13] && !(|div_ff1_src[12:0])}} & 5'd14 +| {5{(&div_ff1_src[31:14]) && !div_ff1_src[13] && (|div_ff1_src[12:0])}} & 5'd13 +| {5{(&div_ff1_src[31:13]) && !div_ff1_src[12] && !(|div_ff1_src[11:0])}} & 5'd13 +| {5{(&div_ff1_src[31:13]) && !div_ff1_src[12] && (|div_ff1_src[11:0])}} & 5'd12 +| {5{(&div_ff1_src[31:12]) && !div_ff1_src[11] && !(|div_ff1_src[10:0])}} & 5'd12 +| {5{(&div_ff1_src[31:12]) && !div_ff1_src[11] && (|div_ff1_src[10:0])}} & 5'd11 +| {5{(&div_ff1_src[31:11]) && !div_ff1_src[10] && !(|div_ff1_src[9:0])}} & 5'd11 +| {5{(&div_ff1_src[31:11]) && !div_ff1_src[10] && (|div_ff1_src[9:0])}} & 5'd10 +| {5{(&div_ff1_src[31:10]) && !div_ff1_src[9] && !(|div_ff1_src[8:0])}} & 5'd10 +| {5{(&div_ff1_src[31:10]) && !div_ff1_src[9] && (|div_ff1_src[8:0])}} & 5'd9 +| {5{(&div_ff1_src[31:9]) && !div_ff1_src[8] && !(|div_ff1_src[7:0])}} & 5'd9 +| {5{(&div_ff1_src[31:9]) && !div_ff1_src[8] && (|div_ff1_src[7:0])}} & 5'd8 +| {5{(&div_ff1_src[31:8]) && !div_ff1_src[7] && !(|div_ff1_src[6:0])}} & 5'd8 +| {5{(&div_ff1_src[31:8]) && !div_ff1_src[7] && (|div_ff1_src[6:0])}} & 5'd7 +| {5{(&div_ff1_src[31:7]) && !div_ff1_src[6] && !(|div_ff1_src[5:0])}} & 5'd7 +| {5{(&div_ff1_src[31:7]) && !div_ff1_src[6] && (|div_ff1_src[5:0])}} & 5'd6 +| {5{(&div_ff1_src[31:6]) && !div_ff1_src[5] && !(|div_ff1_src[4:0])}} & 5'd6 +| {5{(&div_ff1_src[31:6]) && !div_ff1_src[5] && (|div_ff1_src[4:0])}} & 5'd5 +| {5{(&div_ff1_src[31:5]) && !div_ff1_src[4] && !(|div_ff1_src[3:0])}} & 5'd5 +| {5{(&div_ff1_src[31:5]) && !div_ff1_src[4] && (|div_ff1_src[3:0])}} & 5'd4 +| {5{(&div_ff1_src[31:4]) && !div_ff1_src[3] && !(|div_ff1_src[2:0])}} & 5'd4 +| {5{(&div_ff1_src[31:4]) && !div_ff1_src[3] && (|div_ff1_src[2:0])}} & 5'd3 +| {5{(&div_ff1_src[31:3]) && !div_ff1_src[2] && !(|div_ff1_src[1:0])}} & 5'd3 +| {5{(&div_ff1_src[31:3]) && !div_ff1_src[2] && (|div_ff1_src[1:0])}} & 5'd2 +| {5{(&div_ff1_src[31:2]) && !div_ff1_src[1] && !div_ff1_src[0]}} & 5'd2 +| {5{(&div_ff1_src[31:2]) && !div_ff1_src[1] && div_ff1_src[0]}} & 5'd1 +| {5{(&div_ff1_src[31:1]) && !div_ff1_src[0]}} & 5'd1 +| {5{(&div_ff1_src[31:0])}} & 5'd0; + +assign div_ff1_res[4:0] = div_src_is_neg ? div_ff1_res_neg[4:0] + : div_ff1_res_pos[4:0]; + + +always @ (posedge div_clk) +begin + if (ifu_iu_warm_up) begin + div_oper_is_signed_flop <= 1'b0; + div_res_sel_quotient_flop <= 1'b0; + // div_dividend_31 <= 1'b0; + div_divisor_31 <= 1'b0; + end + else if (div_buffer_update || div_ex1_res_vld) begin + div_oper_is_signed_flop <= div_oper_is_signed; + div_res_sel_quotient_flop <= div_res_sel_quotient; + // div_dividend_31 <= div_dividend[31]; + div_divisor_31 <= div_divisor[31]; + end +end + +assign div_dividend_31 = div_dividend_raw[31]; + +assign div_res_quotient_neg = div_oper_is_signed_flop && (div_dividend_31 ^ div_divisor_31); +assign div_res_remainder_neg = div_oper_is_signed_flop && div_dividend_31; + +// Save div_divisor @ WFI2, hold the value @ ITERdiv_ex1_res_vld +// divisor_raw will be saved in div_divisor_reg after DIV_CMPLT. +always @ (posedge div_clk) +begin + if (ifu_iu_warm_up) + div_divisor_reg[31:0] <= 32'b0; + else if (div_buffer_update) + div_divisor_reg[31:0] <= div_divisor[31:0]; + else if (div_prepare_src1) + div_divisor_reg[31:0] <= div_abs_res[31:0]; + else if (div_iter_cmplt) + div_divisor_reg[31:0] <= div_divisor_raw[31:0]; +end + +assign div_divisor_raw_is_neg = div_oper_is_signed_flop && div_divisor_31; +assign div_divisor_raw[31:0] = div_divisor_raw_is_neg ? ~div_divisor_reg[31:0] + 32'b1 + : div_divisor_reg[31:0]; + +// Save the initial value @ IDLE, change the value @ITER +always @ (posedge div_clk) +begin + if (ifu_iu_warm_up) begin + div_quotient_reg[31:0] <= 32'b0; + div_remainder_reg[31:0] <= 32'b0; + end + else if (div_prepare_src0) begin + div_quotient_reg[31:0] <= 32'b0; + div_remainder_reg[31:0] <= div_abs_res[31:0]; + end + else if (div_cmplt) begin + div_quotient_reg[31:0] <= div_normal_quotient[31:0]; + div_remainder_reg[31:0] <= div_normal_remainder[31:0]; + end + else if (div_iterating) begin + div_quotient_reg[31:0] <= div_quotient_reg_updt[31:0]; + div_remainder_reg[31:0] <= div_remainder_reg_updt[31:0]; + end +end + +// Do iteration compare @ ITER. +// &Instance("pa_iu_div_shift_kernel", "x_pa_iu_div_kernel"); +// &Instance("pa_iu_div_shift2_kernel", "x_pa_iu_div_kernel"); @500 +pa_iu_div_shift2_kernel x_pa_iu_div_kernel ( + .cpurst_b (cpurst_b ), + .div_clk (div_clk ), + .div_divisor_reg (div_divisor_reg ), + .div_ff1_res (div_ff1_res ), + .div_flush (div_flush ), + .div_iter_cmplt (div_iter_cmplt ), + .div_iterating (div_iterating ), + .div_prepare_src0 (div_prepare_src0 ), + .div_prepare_src1 (div_prepare_src1 ), + .div_quotient_reg (div_quotient_reg ), + .div_quotient_reg_updt (div_quotient_reg_updt ), + .div_remainder_reg (div_remainder_reg ), + .div_remainder_reg_updt (div_remainder_reg_updt) +); + +// &Instance("pa_iu_div_srt_kernel", "x_pa_iu_div_kernel"); + +assign div_normal_quotient[31:0] = div_res_quotient_neg ? ~div_quotient_reg[31:0] + 32'b1 + : div_quotient_reg[31:0]; +assign div_normal_remainder[31:0] = div_res_remainder_neg ? ~div_remainder_reg[31:0] + 32'b1 + : div_remainder_reg[31:0]; + +assign div_quotient_res[31:0] = div_cmplt ? div_normal_quotient[31:0] + : div_quotient_reg[31:0]; +assign div_remainder_res[31:0] = div_cmplt ? div_normal_remainder[31:0] + : div_remainder_reg[31:0]; + + +assign div_ex2_enable_wb = iu_ex2_div_grant; +assign div_ex2_res_vld_raw = (div_cmplt || div_wfwb); // div main state. +assign div_ex2_res_vld = div_ex2_res_vld_raw && iu_ex2_div_grant; +assign div_ex2_res[31:0] = div_res_sel_quotient_flop ? div_quotient_res[31:0] + : div_remainder_res[31:0]; + + +//========================================================== +// WriteBack State Machine +//========================================================== +//parameter WB_IDLE = 2'b00, +// WB_EX2 = 2'b10, +// WB_CMPLT = 2'b01; +// +//always @ (posedge div_clk or negedge cpurst_b) +//begin +// if (!cpurst_b) +// wb_cur_state[1:0] <= WB_IDLE; +// else if (div_flush) +// wb_cur_state[1:0] <= WB_IDLE; +// else +// wb_cur_state[1:0] <= wb_nxt_state[1:0]; +//end +// +//&CombBeg; +// case(wb_cur_state) +// WB_IDLE: +// if (div_inst_vld) +// if (dp_xx_ex2_stall) +// wb_nxt_state = WB_IDLE; +// else +// wb_nxt_state = WB_EX2; +// else +// wb_nxt_state = WB_IDLE; +// WB_EX2: +// if (dp_xx_ex2_stall) +// wb_nxt_state = WB_EX2; +// else +// if (div_ex2_res_vld) +// if (div_iter_start && !dp_xx_ex2_stall) +// wb_nxt_state = WB_EX2; +// else +// wb_nxt_state = WB_IDLE; +// else +// wb_nxt_state = WB_CMPLT; +// WB_CMPLT: +// if (div_ex2_res_vld) +// if (div_iter_start && !dp_xx_ex2_stall) +// wb_nxt_state = WB_EX2; +// else +// wb_nxt_state = WB_IDLE; +// else +// wb_nxt_state = WB_CMPLT; +// default: +// wb_nxt_state = WB_IDLE; +// endcase +//&CombEnd; +// +//assign div_wb_sm_idle = wb_cur_state == WB_IDLE +// || wb_cur_state == WB_CMPLT && div_ex2_res_vld; +//assign div_wb_sm_ex2 = wb_cur_state == WB_EX2; +//assign div_wb_sm_cmplt = wb_cur_state == WB_EX2 +// || wb_cur_state == WB_CMPLT; +// +//========================================================== +// Output for IU ctrl +//========================================================== +assign div_dp_ex1_cmplt = div_inst_vld && (~div_ex1_stall); +assign div_dp_ex1_cmplt_dp = idu_iu_ex1_div_cmplt_dp_sel; +// &Force("output", "div_dp_ex1_cmplt_dp"); @583 +assign div_dp_ex1_fwd_vld = div_ex1_res_vld_raw && div_dp_ex1_cmplt_dp & idu_iu_ex1_wb_vld; +assign div_dp_ex1_fwd_data[31:0] = div_ex1_res[31:0]; + +assign div_dp_ex2_rslt_vld = div_ex2_res_vld_raw; +assign div_dp_ex2_rslt[31:0] = div_special_res_vld ? div_special_res[31:0] : div_ex2_res[31:0]; +assign div_dp_ex2_dst_preg[5:0] = {1'b0,div_dst_preg[4:0]}; +//========================================================== +// DIV stall +//========================================================== +//-------------- To IDU ---------------- +// assign iu_idu_div_ex1_data_vld = div_ex1_res_vld; +// assign iu_idu_div_data_vld = div_ex2_res_vld; +// assign iu_idu_div_dest_vld = div_cur_state != IDLE; +// assign iu_idu_div_dest_preg[5:0] = {1'b0, (idu_iu_ex1_div_sel ? idu_iu_ex1_dst_preg[4:0] +// : div_dst_preg[4:0])}; + +//-------------- To RTU ---------------- +assign div_ex1_stall = idu_iu_ex1_div_gateclk_sel && !div_is_idle; +assign div_dp_ex1_stall = div_ex1_stall; + +//========================================================== +// DIV flush +//========================================================== +assign div_flush = rtu_yy_xx_async_flush; +assign div_not_cmplt = div_flush && (div_cur_state[2:0] != IDLE || div_prepare_src0); +assign div_flush_buffer = div_not_cmplt || ifu_iu_warm_up; + +//========================================================== +// DIV buffer +//========================================================== +// DIV Has one buffer for div fuse and speed up calculation +always @ (posedge div_clk) +begin + if (div_flush_buffer) + div_dividend_raw[31:0] <= 32'b0; + else if (div_buffer_update) + div_dividend_raw[31:0] <= div_dividend[31:0]; +end + +assign div_dividend_hit_buffer = div_dividend_raw[31:0] == div_dividend[31:0]; +assign div_divisor_hit_buffer = div_divisor_reg[31:0] == div_divisor[31:0]; +assign div_signed_hit_buffer = div_oper_is_signed_flop == div_oper_is_signed; + +assign div_hit_buffer = div_dividend_hit_buffer + && div_divisor_hit_buffer + && div_signed_hit_buffer; + +//========================================================== +// Gate Cell +//========================================================== +assign div_clk_en_raw = idu_iu_ex1_div_gateclk_sel || (div_cur_state[2:0] != IDLE); +assign div_ctrl_itering = !div_is_idle; + +//========================================================== +// DIV gateclk +//========================================================== +assign div_clk_en = div_clk_en_raw + || ifu_iu_warm_up; + +// &Instance("gated_clk_cell", "x_div_clk"); @655 +gated_clk_cell x_div_clk ( + .clk_in (forever_cpuclk ), + .clk_out (div_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (div_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @656 +// .external_en (1'b0), @657 +// .global_en (cp0_yy_clk_en), @658 +// .module_en (cp0_iu_icg_en), @659 +// .local_en (div_clk_en), @660 +// .clk_out (div_clk)); @661 + + +assign div_iu_debug_info[4:0] = {2'b0, div_cur_state[2:0]}; + +// &ModuleEnd; @666 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div_shift2_kernel.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div_shift2_kernel.v new file mode 100644 index 0000000000000000000000000000000000000000..e08e46f7c30a189b968bf765965fab33fbbfc2af --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_div_shift2_kernel.v @@ -0,0 +1,175 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_div_shift2_kernel( + cpurst_b, + div_clk, + div_divisor_reg, + div_ff1_res, + div_flush, + div_iter_cmplt, + div_iterating, + div_prepare_src0, + div_prepare_src1, + div_quotient_reg, + div_quotient_reg_updt, + div_remainder_reg, + div_remainder_reg_updt +); + +// &Ports; @24 +input cpurst_b; +input div_clk; +input [31:0] div_divisor_reg; +input [4 :0] div_ff1_res; +input div_flush; +input div_iterating; +input div_prepare_src0; +input div_prepare_src1; +input [31:0] div_quotient_reg; +input [31:0] div_remainder_reg; +output div_iter_cmplt; +output [31:0] div_quotient_reg_updt; +output [31:0] div_remainder_reg_updt; + +// &Regs; @25 +reg [4 :0] div_iter_count; +reg [31:0] div_remainder_reg_updt; +reg [1 :0] div_shift_in; + +// &Wires; @26 +wire cpurst_b; +wire div_clk; +wire [33:0] div_divisor_01; +wire [33:0] div_divisor_10; +wire [31:0] div_divisor_reg; +wire [4 :0] div_ff1_res; +wire div_flush; +wire div_iter_cmplt; +wire [4 :0] div_iter_count_updt; +wire div_iter_count_updt_0; +wire [4 :0] div_iter_sub; +wire div_iterating; +wire div_prepare_src0; +wire div_prepare_src1; +wire [31:0] div_quotient_reg; +wire [31:0] div_quotient_reg_updt; +wire div_remainder_lt_divisor_01; +wire div_remainder_lt_divisor_10; +wire div_remainder_lt_divisor_11; +wire [31:0] div_remainder_reg; +wire div_suber_c1_01; +wire div_suber_c1_10; +wire div_suber_c1_11; +wire [33:0] div_suber_res1_01; +wire [33:0] div_suber_res1_10; +wire [33:0] div_suber_res1_11; + + +//========================================================== +// 2bit Shift Kernel +//========================================================== +// This is shift kernel of divider. +// Each iter product 2-bit result. + +// &Force("bus", "div_quotient_reg", 31, 0); @34 +//---------------------------------------------------------- +// Iteration Counter +//---------------------------------------------------------- +// Calculate iterations @ WFI2, Decrease iterations @ ITER. +assign div_iter_sub[4:0] = div_prepare_src1 ? div_ff1_res[4:0] + : div_iterating ? 5'b10 + : 5'b0; + +assign div_iter_count_updt_0 = div_iter_count[4:0] < div_iter_sub[4:0]; +assign div_iter_count_updt[4:0] = div_iter_count_updt_0 ? 5'b0 + : div_iter_count[4:0] - div_iter_sub[4:0]; + +always @ (posedge div_clk or negedge cpurst_b) +begin + if (!cpurst_b) + div_iter_count[4:0] <= 5'b0; + else if (div_flush) + div_iter_count[4:0] <= 5'b0; + else if (div_prepare_src0) + div_iter_count[4:0] <= div_ff1_res[4:0]; + else if (div_prepare_src1 || div_iterating) + div_iter_count[4:0] <= div_iter_count_updt[4:0]; +end + +assign div_iter_cmplt = div_iterating && (div_iter_count[4:0] == 5'b0 + || div_iter_count[4:0] == 5'b1); +// &Force("output", "div_iter_cmplt"); @61 + +//---------------------------------------------------------- +// Calcuate Interation +//---------------------------------------------------------- +// Do iteration compare @ ITER. +// Using divisor x1, x2, x3 compare with remainder to get shift_in and new remainder. +assign div_divisor_01[33:0] = {2'b0, div_divisor_reg[31:0]} << {div_iter_count[4:1], 1'b0}; +assign div_divisor_10[33:0] = {1'b0, div_divisor_reg[31:0], 1'b0} << {div_iter_count[4:1], 1'b0}; +///assign div_divisor_11[33:0] = div_divisor_01[33:0] + div_divisor_10[33:0]; + +assign {div_suber_c1_01, div_suber_res1_01[33:0]} = {3'b0, div_remainder_reg[31:0]} - {1'b0, div_divisor_01[33:0]}; +assign {div_suber_c1_10, div_suber_res1_10[33:0]} = {3'b0, div_remainder_reg[31:0]} - {1'b0, div_divisor_10[33:0]}; +assign {div_suber_c1_11, div_suber_res1_11[33:0]} = {3'b0, div_remainder_reg[31:0]} - {1'b0, div_divisor_01[33:0]} - {1'b0, div_divisor_10[33:0]}; +assign div_remainder_lt_divisor_01 = div_suber_c1_01; +assign div_remainder_lt_divisor_10 = div_suber_c1_10; +assign div_remainder_lt_divisor_11 = div_suber_c1_11; + +//---------------------------------------------------------- +// Generate Iteration Results +//---------------------------------------------------------- +// &CombBeg; @82 +always @( div_remainder_lt_divisor_01 + or div_remainder_lt_divisor_10 + or div_remainder_lt_divisor_11) +begin + casez({div_remainder_lt_divisor_01, div_remainder_lt_divisor_10, div_remainder_lt_divisor_11}) + 3'b1??: div_shift_in[1:0] = 2'b00; + 3'b01?: div_shift_in[1:0] = 2'b01; + 3'b001: div_shift_in[1:0] = 2'b10; + 3'b000: div_shift_in[1:0] = 2'b11; + default: div_shift_in[1:0] = {2{1'bx}}; + endcase +// &CombEnd; @90 +end + +assign div_quotient_reg_updt[31:0] = {div_quotient_reg[29:0], div_shift_in[1:0]}; + +// &CombBeg; @94 +always @( div_remainder_reg[31:0] + or div_suber_res1_10[31:0] + or div_suber_res1_01[31:0] + or div_remainder_lt_divisor_01 + or div_remainder_lt_divisor_10 + or div_suber_res1_11[31:0] + or div_remainder_lt_divisor_11) +begin + casez({div_remainder_lt_divisor_01, div_remainder_lt_divisor_10, div_remainder_lt_divisor_11}) + 3'b1??: div_remainder_reg_updt[31:0] = div_remainder_reg[31:0]; + 3'b01?: div_remainder_reg_updt[31:0] = div_suber_res1_01[31:0]; + 3'b001: div_remainder_reg_updt[31:0] = div_suber_res1_10[31:0]; + 3'b000: div_remainder_reg_updt[31:0] = div_suber_res1_11[31:0]; + default: div_remainder_reg_updt[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @102 +end + +// &ModuleEnd; @104 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_mul.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_mul.v new file mode 100644 index 0000000000000000000000000000000000000000..822f6560b5b5090f4e20abec301e83ece5a2813c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_mul.v @@ -0,0 +1,305 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_mul( + cp0_iu_icg_en, + cp0_yy_clk_en, + cpurst_b, + dp_xx_ex1_stall, + dp_xx_ex2_stall, + forever_cpuclk, + idu_iu_ex1_func, + idu_iu_ex1_gateclk_vld, + idu_iu_ex1_inst_vld, + idu_iu_ex1_mul_cmplt_dp_sel, + idu_iu_ex1_mul_gateclk_sel, + idu_iu_ex1_mul_high_sel, + idu_iu_ex1_mul_sel, + idu_iu_ex1_src0, + idu_iu_ex1_src1, + idu_iu_ex1_src2, + ifu_iu_warm_up, + mul_dp_ex1_cmplt, + mul_dp_ex1_cmplt_dp, + mul_dp_ex2_inst_vld, + mul_dp_ex2_rslt0, + mul_dp_ex2_rslt0_vld, + pad_yy_icg_scan_en +); + +// &Ports; @24 +input cp0_iu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input dp_xx_ex1_stall; +input dp_xx_ex2_stall; +input forever_cpuclk; +input [19:0] idu_iu_ex1_func; +input idu_iu_ex1_gateclk_vld; +input idu_iu_ex1_inst_vld; +input idu_iu_ex1_mul_cmplt_dp_sel; +input idu_iu_ex1_mul_gateclk_sel; +input idu_iu_ex1_mul_high_sel; +input idu_iu_ex1_mul_sel; +input [31:0] idu_iu_ex1_src0; +input [31:0] idu_iu_ex1_src1; +input [31:0] idu_iu_ex1_src2; +input ifu_iu_warm_up; +input pad_yy_icg_scan_en; +output mul_dp_ex1_cmplt; +output mul_dp_ex1_cmplt_dp; +output mul_dp_ex2_inst_vld; +output [31:0] mul_dp_ex2_rslt0; +output mul_dp_ex2_rslt0_vld; + +// &Regs; @25 +reg mul_ex2_inst_vld; +reg mul_ex2_result_low; +reg [67:0] mul_ex2_wb_res_0; +reg [67:0] mul_ex2_wb_res_1; + +// &Wires; @26 +wire cp0_iu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire dp_xx_ex1_stall; +wire dp_xx_ex2_stall; +wire forever_cpuclk; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_mul_cmplt_dp_sel; +wire idu_iu_ex1_mul_gateclk_sel; +wire idu_iu_ex1_mul_sel; +wire [31:0] idu_iu_ex1_src0; +wire [31:0] idu_iu_ex1_src1; +wire ifu_iu_warm_up; +wire mul_clk; +wire mul_clk_en; +wire mul_dp_ex1_cmplt; +wire mul_dp_ex1_cmplt_dp; +wire mul_dp_ex2_inst_vld; +wire [31:0] mul_dp_ex2_rslt0; +wire mul_dp_ex2_rslt0_vld; +wire mul_ex1_ctrl_clk; +wire mul_ex1_ctrl_clk_en; +wire mul_ex1_gateclk_inst_vld; +wire mul_ex1_inst_vld; +wire mul_ex1_wb_pipe_down; +wire mul_gateclk_sel; +wire mul_high_clk; +wire mul_high_clk_en; +wire mul_inst_mul; +wire [31:0] mul_res; +wire [67:0] mul_res_raw; +wire [32:0] mul_rs1; +wire [16:0] mul_rs1_high; +wire [15:0] mul_rs1_low; +wire mul_rs1_signed; +wire [32:0] mul_rs1_tmp0; +wire [32:0] mul_rs2; +wire [16:0] mul_rs2_high; +wire [15:0] mul_rs2_low; +wire mul_rs2_signed; +wire mul_sel; +wire [31:0] mult_round; +wire mult_sub; +wire [32:0] multiplicand; +wire [32:0] multiplier; +wire pad_yy_icg_scan_en; +wire [68:0] result_0; +wire [68:0] result_1; + + +assign mul_sel = idu_iu_ex1_mul_sel; +assign mul_gateclk_sel = idu_iu_ex1_mul_gateclk_sel; +// &Force("bus", "idu_iu_ex1_func", 19, 0); @30 +// &Force("bus", "idu_iu_ex1_src0", 31, 0); @31 +// &Force("bus", "idu_iu_ex1_src1", 31, 0); @32 +assign mul_inst_mul = idu_iu_ex1_func[2]; + +assign mul_rs1_signed = idu_iu_ex1_func[0]; +assign mul_rs2_signed = idu_iu_ex1_func[1]; + +// &Force("input", "idu_iu_ex1_mul_high_sel"); @54 +// &Force("input", "idu_iu_ex1_src2"); &Force("bus", "idu_iu_ex1_src2", 31, 0); @55 +assign mul_rs1_high[16:0] = {(mul_rs1_signed && idu_iu_ex1_src0[31]), idu_iu_ex1_src0[31:16]} & {17{mul_gateclk_sel}}; +assign mul_rs2_high[16:0] = {(mul_rs2_signed && idu_iu_ex1_src1[31]), idu_iu_ex1_src1[31:16]} & {17{mul_gateclk_sel}}; +assign mul_rs1_low[15:0] = idu_iu_ex1_src0[15:0] & {16{mul_gateclk_sel}}; +assign mul_rs2_low[15:0] = idu_iu_ex1_src1[15:0] & {16{mul_gateclk_sel}}; + + + +assign mul_rs1_tmp0[32:0] = {mul_rs1_high[16:0], mul_rs1_low[15:0]}; +assign mul_rs2[32:0] = {mul_rs2_high[16:0], mul_rs2_low[15:0]}; + +assign mul_rs1[32:0] = mul_rs1_tmp0[32:0]; + +assign multiplicand[32:0] = mul_rs1[32:0]; +assign multiplier[32:0] = mul_rs2[32:0]; + +//========================================================== +// 32x32 Multiplication +//========================================================== +//---------------------------------------------------------- +// 1st Cycle +//---------------------------------------------------------- +// 1st cycle use DW partical multiplication to get two result. + +// &Force("nonport", "multiplicand"); @88 +// &Force("nonport", "multiplier"); @89 +// &Force("nonport", "result_0"); @90 +// &Force("nonport", "result_1"); @91 +// &Instance("multiplier_33x33_partial"); @93 +multiplier_33x33_partial x_multiplier_33x33_partial ( + .mult_round (mult_round ), + .mult_sub (mult_sub ), + .multiplicand (multiplicand), + .multiplier (multiplier ), + .result_0 (result_0 ), + .result_1 (result_1 ) +); + +assign mult_round[31:0] = 32'd0; +assign mult_sub = 1'b0; +// &Force("bus", "result_0", 68, 0); @96 +// &Force("bus", "result_1", 68, 0); @97 + + +//---------------------------------------------------------- +// 2nd Cycle +//---------------------------------------------------------- +assign mul_ex1_gateclk_inst_vld = (idu_iu_ex1_mul_gateclk_sel & idu_iu_ex1_gateclk_vld); +assign mul_ex1_inst_vld = (idu_iu_ex1_mul_sel & idu_iu_ex1_inst_vld); +assign mul_ex1_ctrl_clk_en = mul_ex1_gateclk_inst_vld | mul_ex2_inst_vld; + +// &Instance("gated_clk_cell", "x_mul_ex1_ctrl_gated_clk"); @116 +gated_clk_cell x_mul_ex1_ctrl_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mul_ex1_ctrl_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (mul_ex1_ctrl_clk_en), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @117 +// .external_en (1'b0), @118 +// .global_en (cp0_yy_clk_en), @119 +// .module_en (cp0_iu_icg_en), @120 +// .local_en (mul_ex1_ctrl_clk_en), @121 +// .clk_out (mul_ex1_ctrl_clk)); @122 + +always@(posedge mul_ex1_ctrl_clk or negedge cpurst_b) +begin + if(~cpurst_b) + begin + mul_ex2_inst_vld <= 1'b0; + end + else if(mul_ex1_inst_vld) + begin + mul_ex2_inst_vld <= 1'b1; + end + else + begin + mul_ex2_inst_vld <= 1'b0; + end +end +// 2nd cycle add two result generated in 1st cycle, and get final result. +assign mul_ex1_wb_pipe_down = !dp_xx_ex2_stall; + +always @ (posedge mul_clk) +begin + if (mul_gateclk_sel && mul_ex1_wb_pipe_down || ifu_iu_warm_up) begin + //mul_ex2_wb_preg_4_0[4:0] <= idu_iu_ex1_dst_preg[4:0]; + mul_ex2_wb_res_0[31:0] <= result_0[31:0]; + mul_ex2_wb_res_1[31:0] <= result_1[31:0]; + mul_ex2_result_low <= mul_inst_mul; + end +end +// &Force("bus", "idu_iu_ex1_dst_preg", 5, 0); @177 + +// if result is low 32-bits, high 32-bits will not changed. +always @ (posedge mul_high_clk) +begin + if (mul_gateclk_sel && mul_ex1_wb_pipe_down && !mul_inst_mul || ifu_iu_warm_up) begin + mul_ex2_wb_res_0[67:32] <= result_0[67:32]; + mul_ex2_wb_res_1[67:32] <= result_1[67:32]; + end +end + +assign mul_res_raw[67:0] = mul_ex2_wb_res_0[67:0] + mul_ex2_wb_res_1[67:0]; + +//---------- Select High / Low ----------- +assign mul_res[31:0] = {32{ mul_ex2_result_low}} & mul_res_raw[31:0] + | {32{!mul_ex2_result_low}} & mul_res_raw[63:32]; + +//========================================================== +// Gate Clk Cell +//========================================================== +assign mul_clk_en = mul_gateclk_sel + || ifu_iu_warm_up; +// &Instance("gated_clk_cell", "x_mul_clk"); @217 +gated_clk_cell x_mul_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mul_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (mul_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @218 +// .external_en (1'b0), @219 +// .global_en (cp0_yy_clk_en), @220 +// .module_en (cp0_iu_icg_en), @221 +// .local_en (mul_clk_en), @222 +// .clk_out (mul_clk)); @223 + +assign mul_high_clk_en = mul_gateclk_sel && !mul_inst_mul + || ifu_iu_warm_up; +// &Instance("gated_clk_cell", "x_mul_high_clk"); @227 +gated_clk_cell x_mul_high_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mul_high_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (mul_high_clk_en ), + .module_en (cp0_iu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @228 +// .external_en (1'b0), @229 +// .global_en (cp0_yy_clk_en), @230 +// .module_en (cp0_iu_icg_en), @231 +// .local_en (mul_high_clk_en), @232 +// .clk_out (mul_high_clk)); @233 + +//========================================================== +// Output for IU ctrl +//========================================================== +assign mul_dp_ex1_cmplt = idu_iu_ex1_inst_vld && mul_sel && (~dp_xx_ex1_stall); +assign mul_dp_ex1_cmplt_dp = idu_iu_ex1_mul_cmplt_dp_sel; +assign mul_dp_ex2_rslt0[31:0] = mul_res[31:0]; +assign mul_dp_ex2_rslt0_vld = mul_ex2_inst_vld; +assign mul_dp_ex2_inst_vld = mul_ex2_inst_vld; +// &ModuleEnd; @243 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..6fbe9e6dc370a9a1395ccfe3f64694c8f2ab9940 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/iu/rtl/pa_iu_top.v @@ -0,0 +1,757 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_iu_top( + cp0_iu_adder_borrow_in, + cp0_iu_adder_borrow_vld, + cp0_iu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + fpu_iu_ex1_cmplt, + fpu_iu_ex1_cmplt_dp, + idu_iu_ex1_ag_imm, + idu_iu_ex1_alu_cmplt_dp_sel, + idu_iu_ex1_alu_gateclk_sel, + idu_iu_ex1_alu_sel, + idu_iu_ex1_bht_pred, + idu_iu_ex1_bju_cmplt_dp_sel, + idu_iu_ex1_bju_depd_lsu_src0, + idu_iu_ex1_bju_depd_lsu_src1, + idu_iu_ex1_bju_gateclk_sel, + idu_iu_ex1_bju_sel, + idu_iu_ex1_bju_use_pc, + idu_iu_ex1_div_cmplt_dp_sel, + idu_iu_ex1_div_gateclk_sel, + idu_iu_ex1_div_sel, + idu_iu_ex1_dst_preg, + idu_iu_ex1_func, + idu_iu_ex1_gateclk_vld, + idu_iu_ex1_inst_len, + idu_iu_ex1_inst_vld, + idu_iu_ex1_ipop_int_mask, + idu_iu_ex1_ipush_mie_en, + idu_iu_ex1_ipush_spec_fail, + idu_iu_ex1_mul_cmplt_dp_sel, + idu_iu_ex1_mul_gateclk_sel, + idu_iu_ex1_mul_high_sel, + idu_iu_ex1_mul_sel, + idu_iu_ex1_rd_pair, + idu_iu_ex1_split, + idu_iu_ex1_src0, + idu_iu_ex1_src0_reg, + idu_iu_ex1_src1, + idu_iu_ex1_src1_reg, + idu_iu_ex1_src2, + idu_iu_ex1_tail_int_vld, + idu_iu_ex1_wb_vld, + idu_iu_tail_fail, + idu_iu_tail_fail_gate, + ifu_iu_chgflw_pc, + ifu_iu_chgflw_vld, + ifu_iu_ex1_pc_pred, + ifu_iu_reset_vld, + ifu_iu_warm_up, + iu_cp0_ex1_borrow_expt_pc, + iu_dtu_debug_info, + iu_hpcp_inst_bht_mispred, + iu_hpcp_inst_condbr, + iu_hpcp_inst_condbr_gate, + iu_idu_bju_global_stall, + iu_idu_bju_stall, + iu_idu_ex1_fwd_data, + iu_idu_ex1_fwd_preg, + iu_idu_ex1_fwd_vld, + iu_idu_ex1_src1_update_value, + iu_idu_ex1_stall, + iu_idu_ex2_div_vld, + iu_idu_ex2_fwd_data0, + iu_idu_ex2_fwd_data1, + iu_idu_ex2_fwd_preg0, + iu_idu_ex2_fwd_preg1, + iu_idu_ex2_fwd_vld0, + iu_idu_ex2_fwd_vld1, + iu_idu_ex2_inst_vld, + iu_idu_ex2_rd_pair, + iu_idu_id_stall, + iu_ifu_bht_cur_pc, + iu_ifu_bht_mispred, + iu_ifu_bht_mispred_gate, + iu_ifu_bht_pred, + iu_ifu_bht_taken, + iu_ifu_br_vld, + iu_ifu_br_vld_gate, + iu_ifu_ind_link_vld, + iu_ifu_link_vld, + iu_ifu_link_vld_gate, + iu_ifu_pc_mispred, + iu_ifu_pc_mispred_gate, + iu_ifu_ret_vld, + iu_ifu_ret_vld_gate, + iu_ifu_tar_pc, + iu_ifu_tar_pc_vld, + iu_ifu_tar_pc_vld_gate, + iu_lsu_ex1_lsi_rst, + iu_lsu_ex2_wb0_grant, + iu_rtu_ex1_bju_branch_inst, + iu_rtu_ex1_bju_cmplt, + iu_rtu_ex1_bju_cmplt_dp, + iu_rtu_ex1_bju_cur_pc, + iu_rtu_ex1_bju_inst_len, + iu_rtu_ex1_bju_inst_vld, + iu_rtu_ex1_bju_split_inst, + iu_rtu_ex1_cmplt, + iu_rtu_ex1_cmplt_dp, + iu_rtu_ex1_inst_len, + iu_rtu_ex1_inst_vld, + iu_rtu_ex1_ipop_int_mask, + iu_rtu_ex1_ipush_mie_en, + iu_rtu_ex1_ipush_spec_fail, + iu_rtu_ex1_next_pc, + iu_rtu_ex1_split_inst, + iu_rtu_ex1_tail_int_vld, + iu_rtu_ex2_bju_flush, + iu_rtu_ex2_bju_next_pc, + iu_rtu_ex2_bju_next_pc_vld, + iu_rtu_wb0_data, + iu_rtu_wb0_preg, + iu_rtu_wb0_vld, + iu_xx_no_op, + iu_yy_xx_cancel, + lsu_iu_ex1_base_wb, + lsu_iu_ex1_src1_sel, + lsu_iu_ex2_data, + lsu_iu_ex2_data_vld, + lsu_iu_ex2_dest_reg, + lsu_iu_ex2_lsi_dst_preg, + lsu_iu_ex2_lsi_rslt, + lsu_iu_ex2_lsi_rslt_vld, + lsu_rtu_ex1_cmplt_dp, + pad_yy_icg_scan_en, + rtu_iu_bju_ex2_cur_pc, + rtu_iu_ex1_cmplt_dp_vld, + rtu_iu_ex1_cmplt_inst_len, + rtu_iu_ex1_cmplt_split_inst, + rtu_iu_ex1_cmplt_vld, + rtu_iu_pending_spec_expt_vld, + rtu_iu_pending_spec_halt_info_vld, + rtu_xx_ex1_stall, + rtu_yy_xx_async_flush, + rtu_yy_xx_flush, + sysio_iu_rst_addr +); + +// &Ports; @24 +input cp0_iu_adder_borrow_in; +input cp0_iu_adder_borrow_vld; +input cp0_iu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input fpu_iu_ex1_cmplt; +input fpu_iu_ex1_cmplt_dp; +input [31:0] idu_iu_ex1_ag_imm; +input idu_iu_ex1_alu_cmplt_dp_sel; +input idu_iu_ex1_alu_gateclk_sel; +input idu_iu_ex1_alu_sel; +input [1 :0] idu_iu_ex1_bht_pred; +input idu_iu_ex1_bju_cmplt_dp_sel; +input idu_iu_ex1_bju_depd_lsu_src0; +input idu_iu_ex1_bju_depd_lsu_src1; +input idu_iu_ex1_bju_gateclk_sel; +input idu_iu_ex1_bju_sel; +input idu_iu_ex1_bju_use_pc; +input idu_iu_ex1_div_cmplt_dp_sel; +input idu_iu_ex1_div_gateclk_sel; +input idu_iu_ex1_div_sel; +input [5 :0] idu_iu_ex1_dst_preg; +input [19:0] idu_iu_ex1_func; +input idu_iu_ex1_gateclk_vld; +input idu_iu_ex1_inst_len; +input idu_iu_ex1_inst_vld; +input idu_iu_ex1_ipop_int_mask; +input idu_iu_ex1_ipush_mie_en; +input idu_iu_ex1_ipush_spec_fail; +input idu_iu_ex1_mul_cmplt_dp_sel; +input idu_iu_ex1_mul_gateclk_sel; +input idu_iu_ex1_mul_high_sel; +input idu_iu_ex1_mul_sel; +input idu_iu_ex1_rd_pair; +input idu_iu_ex1_split; +input [31:0] idu_iu_ex1_src0; +input [5 :0] idu_iu_ex1_src0_reg; +input [31:0] idu_iu_ex1_src1; +input [5 :0] idu_iu_ex1_src1_reg; +input [31:0] idu_iu_ex1_src2; +input idu_iu_ex1_tail_int_vld; +input idu_iu_ex1_wb_vld; +input idu_iu_tail_fail; +input idu_iu_tail_fail_gate; +input [31:0] ifu_iu_chgflw_pc; +input ifu_iu_chgflw_vld; +input [31:0] ifu_iu_ex1_pc_pred; +input ifu_iu_reset_vld; +input ifu_iu_warm_up; +input lsu_iu_ex1_base_wb; +input lsu_iu_ex1_src1_sel; +input [31:0] lsu_iu_ex2_data; +input lsu_iu_ex2_data_vld; +input [5 :0] lsu_iu_ex2_dest_reg; +input [5 :0] lsu_iu_ex2_lsi_dst_preg; +input [31:0] lsu_iu_ex2_lsi_rslt; +input lsu_iu_ex2_lsi_rslt_vld; +input lsu_rtu_ex1_cmplt_dp; +input pad_yy_icg_scan_en; +input [31:0] rtu_iu_bju_ex2_cur_pc; +input rtu_iu_ex1_cmplt_dp_vld; +input rtu_iu_ex1_cmplt_inst_len; +input rtu_iu_ex1_cmplt_split_inst; +input rtu_iu_ex1_cmplt_vld; +input rtu_iu_pending_spec_expt_vld; +input rtu_iu_pending_spec_halt_info_vld; +input rtu_xx_ex1_stall; +input rtu_yy_xx_async_flush; +input rtu_yy_xx_flush; +input [31:0] sysio_iu_rst_addr; +output [31:0] iu_cp0_ex1_borrow_expt_pc; +output [8 :0] iu_dtu_debug_info; +output iu_hpcp_inst_bht_mispred; +output iu_hpcp_inst_condbr; +output iu_hpcp_inst_condbr_gate; +output iu_idu_bju_global_stall; +output iu_idu_bju_stall; +output [31:0] iu_idu_ex1_fwd_data; +output [5 :0] iu_idu_ex1_fwd_preg; +output iu_idu_ex1_fwd_vld; +output [31:0] iu_idu_ex1_src1_update_value; +output iu_idu_ex1_stall; +output iu_idu_ex2_div_vld; +output [31:0] iu_idu_ex2_fwd_data0; +output [31:0] iu_idu_ex2_fwd_data1; +output [5 :0] iu_idu_ex2_fwd_preg0; +output [5 :0] iu_idu_ex2_fwd_preg1; +output iu_idu_ex2_fwd_vld0; +output iu_idu_ex2_fwd_vld1; +output iu_idu_ex2_inst_vld; +output iu_idu_ex2_rd_pair; +output iu_idu_id_stall; +output [31:0] iu_ifu_bht_cur_pc; +output iu_ifu_bht_mispred; +output iu_ifu_bht_mispred_gate; +output [1 :0] iu_ifu_bht_pred; +output iu_ifu_bht_taken; +output iu_ifu_br_vld; +output iu_ifu_br_vld_gate; +output iu_ifu_ind_link_vld; +output iu_ifu_link_vld; +output iu_ifu_link_vld_gate; +output iu_ifu_pc_mispred; +output iu_ifu_pc_mispred_gate; +output iu_ifu_ret_vld; +output iu_ifu_ret_vld_gate; +output [31:0] iu_ifu_tar_pc; +output iu_ifu_tar_pc_vld; +output iu_ifu_tar_pc_vld_gate; +output [31:0] iu_lsu_ex1_lsi_rst; +output iu_lsu_ex2_wb0_grant; +output iu_rtu_ex1_bju_branch_inst; +output iu_rtu_ex1_bju_cmplt; +output iu_rtu_ex1_bju_cmplt_dp; +output [30:0] iu_rtu_ex1_bju_cur_pc; +output iu_rtu_ex1_bju_inst_len; +output iu_rtu_ex1_bju_inst_vld; +output iu_rtu_ex1_bju_split_inst; +output iu_rtu_ex1_cmplt; +output iu_rtu_ex1_cmplt_dp; +output iu_rtu_ex1_inst_len; +output iu_rtu_ex1_inst_vld; +output iu_rtu_ex1_ipop_int_mask; +output iu_rtu_ex1_ipush_mie_en; +output iu_rtu_ex1_ipush_spec_fail; +output [30:0] iu_rtu_ex1_next_pc; +output iu_rtu_ex1_split_inst; +output iu_rtu_ex1_tail_int_vld; +output iu_rtu_ex2_bju_flush; +output [30:0] iu_rtu_ex2_bju_next_pc; +output iu_rtu_ex2_bju_next_pc_vld; +output [31:0] iu_rtu_wb0_data; +output [5 :0] iu_rtu_wb0_preg; +output iu_rtu_wb0_vld; +output iu_xx_no_op; +output iu_yy_xx_cancel; + +// &Regs; @25 + +// &Wires; @26 +wire [31:0] ag_bju_pc; +wire [5 :0] ag_dp_ex1_dst_preg; +wire [31:0] ag_dp_ex1_fwd_data; +wire ag_dp_ex1_fwd_vld; +wire alu_dp_ex1_cmplt; +wire alu_dp_ex1_cmplt_dp; +wire alu_dp_ex1_fwd_vld; +wire [31:0] alu_dp_ex1_rslt; +wire bju_dp_ex1_cmplt_dp; +wire [31:0] bju_dp_ex1_rslt; +wire bju_dp_ex1_rslt_vld; +wire bju_dp_ex1_stall; +wire bju_dp_no_op; +wire [3 :0] bju_iu_debug_info; +wire cp0_iu_adder_borrow_in; +wire cp0_iu_adder_borrow_vld; +wire cp0_iu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire div_ctrl_itering; +wire div_dp_ex1_cmplt; +wire div_dp_ex1_cmplt_dp; +wire [31:0] div_dp_ex1_fwd_data; +wire div_dp_ex1_fwd_vld; +wire div_dp_ex1_stall; +wire [5 :0] div_dp_ex2_dst_preg; +wire [31:0] div_dp_ex2_rslt; +wire div_dp_ex2_rslt_vld; +wire [4 :0] div_iu_debug_info; +wire dp_xx_ex1_stall; +wire dp_xx_ex2_stall; +wire forever_cpuclk; +wire fpu_iu_ex1_cmplt; +wire fpu_iu_ex1_cmplt_dp; +wire [31:0] idu_iu_ex1_ag_imm; +wire idu_iu_ex1_alu_cmplt_dp_sel; +wire idu_iu_ex1_alu_gateclk_sel; +wire idu_iu_ex1_alu_sel; +wire [1 :0] idu_iu_ex1_bht_pred; +wire idu_iu_ex1_bju_cmplt_dp_sel; +wire idu_iu_ex1_bju_depd_lsu_src0; +wire idu_iu_ex1_bju_depd_lsu_src1; +wire idu_iu_ex1_bju_gateclk_sel; +wire idu_iu_ex1_bju_sel; +wire idu_iu_ex1_bju_use_pc; +wire idu_iu_ex1_div_cmplt_dp_sel; +wire idu_iu_ex1_div_gateclk_sel; +wire idu_iu_ex1_div_sel; +wire [5 :0] idu_iu_ex1_dst_preg; +wire [19:0] idu_iu_ex1_func; +wire idu_iu_ex1_gateclk_vld; +wire idu_iu_ex1_inst_len; +wire idu_iu_ex1_inst_vld; +wire idu_iu_ex1_ipop_int_mask; +wire idu_iu_ex1_ipush_mie_en; +wire idu_iu_ex1_ipush_spec_fail; +wire idu_iu_ex1_mul_cmplt_dp_sel; +wire idu_iu_ex1_mul_gateclk_sel; +wire idu_iu_ex1_mul_high_sel; +wire idu_iu_ex1_mul_sel; +wire idu_iu_ex1_rd_pair; +wire idu_iu_ex1_split; +wire [31:0] idu_iu_ex1_src0; +wire [5 :0] idu_iu_ex1_src0_reg; +wire [31:0] idu_iu_ex1_src1; +wire [5 :0] idu_iu_ex1_src1_reg; +wire [31:0] idu_iu_ex1_src2; +wire idu_iu_ex1_tail_int_vld; +wire idu_iu_ex1_wb_vld; +wire idu_iu_tail_fail; +wire idu_iu_tail_fail_gate; +wire [31:0] ifu_iu_chgflw_pc; +wire ifu_iu_chgflw_vld; +wire [31:0] ifu_iu_ex1_pc_pred; +wire ifu_iu_reset_vld; +wire ifu_iu_warm_up; +wire [31:0] iu_cp0_ex1_borrow_expt_pc; +wire [8 :0] iu_dtu_debug_info; +wire [31:0] iu_ex1_cur_pc; +wire iu_ex2_div_grant; +wire iu_hpcp_inst_bht_mispred; +wire iu_hpcp_inst_condbr; +wire iu_hpcp_inst_condbr_gate; +wire iu_idu_bju_global_stall; +wire iu_idu_bju_stall; +wire [31:0] iu_idu_ex1_fwd_data; +wire [5 :0] iu_idu_ex1_fwd_preg; +wire iu_idu_ex1_fwd_vld; +wire [31:0] iu_idu_ex1_src1_update_value; +wire iu_idu_ex1_stall; +wire iu_idu_ex2_div_vld; +wire [31:0] iu_idu_ex2_fwd_data0; +wire [31:0] iu_idu_ex2_fwd_data1; +wire [5 :0] iu_idu_ex2_fwd_preg0; +wire [5 :0] iu_idu_ex2_fwd_preg1; +wire iu_idu_ex2_fwd_vld0; +wire iu_idu_ex2_fwd_vld1; +wire iu_idu_ex2_inst_vld; +wire iu_idu_ex2_rd_pair; +wire iu_idu_id_stall; +wire [31:0] iu_ifu_bht_cur_pc; +wire iu_ifu_bht_mispred; +wire iu_ifu_bht_mispred_gate; +wire [1 :0] iu_ifu_bht_pred; +wire iu_ifu_bht_taken; +wire iu_ifu_br_vld; +wire iu_ifu_br_vld_gate; +wire iu_ifu_ind_link_vld; +wire iu_ifu_link_vld; +wire iu_ifu_link_vld_gate; +wire iu_ifu_pc_mispred; +wire iu_ifu_pc_mispred_gate; +wire iu_ifu_ret_vld; +wire iu_ifu_ret_vld_gate; +wire [31:0] iu_ifu_tar_pc; +wire iu_ifu_tar_pc_vld; +wire iu_ifu_tar_pc_vld_gate; +wire [31:0] iu_lsu_ex1_lsi_rst; +wire iu_lsu_ex2_wb0_grant; +wire iu_rtu_ex1_bju_branch_inst; +wire iu_rtu_ex1_bju_cmplt; +wire iu_rtu_ex1_bju_cmplt_dp; +wire [30:0] iu_rtu_ex1_bju_cur_pc; +wire iu_rtu_ex1_bju_inst_len; +wire iu_rtu_ex1_bju_inst_vld; +wire iu_rtu_ex1_bju_split_inst; +wire iu_rtu_ex1_cmplt; +wire iu_rtu_ex1_cmplt_dp; +wire iu_rtu_ex1_inst_len; +wire iu_rtu_ex1_inst_vld; +wire iu_rtu_ex1_ipop_int_mask; +wire iu_rtu_ex1_ipush_mie_en; +wire iu_rtu_ex1_ipush_spec_fail; +wire [30:0] iu_rtu_ex1_next_pc; +wire iu_rtu_ex1_split_inst; +wire iu_rtu_ex1_tail_int_vld; +wire iu_rtu_ex2_bju_flush; +wire [30:0] iu_rtu_ex2_bju_next_pc; +wire iu_rtu_ex2_bju_next_pc_vld; +wire [31:0] iu_rtu_wb0_data; +wire [5 :0] iu_rtu_wb0_preg; +wire iu_rtu_wb0_vld; +wire iu_xx_no_op; +wire iu_yy_xx_cancel; +wire lsu_iu_ex1_base_wb; +wire lsu_iu_ex1_src1_sel; +wire [31:0] lsu_iu_ex2_data; +wire lsu_iu_ex2_data_vld; +wire [5 :0] lsu_iu_ex2_dest_reg; +wire [5 :0] lsu_iu_ex2_lsi_dst_preg; +wire [31:0] lsu_iu_ex2_lsi_rslt; +wire lsu_iu_ex2_lsi_rslt_vld; +wire lsu_rtu_ex1_cmplt_dp; +wire mul_dp_ex1_cmplt; +wire mul_dp_ex1_cmplt_dp; +wire mul_dp_ex2_inst_vld; +wire [31:0] mul_dp_ex2_rslt0; +wire mul_dp_ex2_rslt0_vld; +wire pad_yy_icg_scan_en; +wire [31:0] rtu_iu_bju_ex2_cur_pc; +wire rtu_iu_ex1_cmplt_dp_vld; +wire rtu_iu_ex1_cmplt_inst_len; +wire rtu_iu_ex1_cmplt_split_inst; +wire rtu_iu_ex1_cmplt_vld; +wire rtu_iu_pending_spec_expt_vld; +wire rtu_iu_pending_spec_halt_info_vld; +wire rtu_xx_ex1_stall; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_flush; +wire [31:0] sysio_iu_rst_addr; + + +//TODO +// &Force("output", "iu_rtu_ex1_bju_cmplt"); @29 + +// &Instance("pa_iu_dsp_alu"); @32 +// &Instance("pa_iu_alu"); @34 +pa_iu_alu x_pa_iu_alu ( + .alu_dp_ex1_cmplt (alu_dp_ex1_cmplt ), + .alu_dp_ex1_cmplt_dp (alu_dp_ex1_cmplt_dp ), + .alu_dp_ex1_fwd_vld (alu_dp_ex1_fwd_vld ), + .alu_dp_ex1_rslt (alu_dp_ex1_rslt ), + .dp_xx_ex1_stall (dp_xx_ex1_stall ), + .idu_iu_ex1_alu_cmplt_dp_sel (idu_iu_ex1_alu_cmplt_dp_sel), + .idu_iu_ex1_alu_gateclk_sel (idu_iu_ex1_alu_gateclk_sel ), + .idu_iu_ex1_alu_sel (idu_iu_ex1_alu_sel ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ) +); + + +// &Instance("pa_iu_div"); @37 +pa_iu_div x_pa_iu_div ( + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .div_ctrl_itering (div_ctrl_itering ), + .div_dp_ex1_cmplt (div_dp_ex1_cmplt ), + .div_dp_ex1_cmplt_dp (div_dp_ex1_cmplt_dp ), + .div_dp_ex1_fwd_data (div_dp_ex1_fwd_data ), + .div_dp_ex1_fwd_vld (div_dp_ex1_fwd_vld ), + .div_dp_ex1_stall (div_dp_ex1_stall ), + .div_dp_ex2_dst_preg (div_dp_ex2_dst_preg ), + .div_dp_ex2_rslt (div_dp_ex2_rslt ), + .div_dp_ex2_rslt_vld (div_dp_ex2_rslt_vld ), + .div_iu_debug_info (div_iu_debug_info ), + .forever_cpuclk (forever_cpuclk ), + .idu_iu_ex1_div_cmplt_dp_sel (idu_iu_ex1_div_cmplt_dp_sel), + .idu_iu_ex1_div_gateclk_sel (idu_iu_ex1_div_gateclk_sel ), + .idu_iu_ex1_div_sel (idu_iu_ex1_div_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .iu_ex2_div_grant (iu_ex2_div_grant ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ) +); + + +// &Instance("pa_axi_iu_bju"); @40 +// &Instance("pa_iu_bju"); @42 +pa_iu_bju x_pa_iu_bju ( + .ag_bju_pc (ag_bju_pc ), + .bju_dp_ex1_cmplt_dp (bju_dp_ex1_cmplt_dp ), + .bju_dp_ex1_rslt (bju_dp_ex1_rslt ), + .bju_dp_ex1_rslt_vld (bju_dp_ex1_rslt_vld ), + .bju_dp_ex1_stall (bju_dp_ex1_stall ), + .bju_dp_no_op (bju_dp_no_op ), + .bju_iu_debug_info (bju_iu_debug_info ), + .cp0_iu_adder_borrow_in (cp0_iu_adder_borrow_in ), + .cp0_iu_adder_borrow_vld (cp0_iu_adder_borrow_vld ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .idu_iu_ex1_bht_pred (idu_iu_ex1_bht_pred ), + .idu_iu_ex1_bju_cmplt_dp_sel (idu_iu_ex1_bju_cmplt_dp_sel ), + .idu_iu_ex1_bju_depd_lsu_src0 (idu_iu_ex1_bju_depd_lsu_src0), + .idu_iu_ex1_bju_depd_lsu_src1 (idu_iu_ex1_bju_depd_lsu_src1), + .idu_iu_ex1_bju_gateclk_sel (idu_iu_ex1_bju_gateclk_sel ), + .idu_iu_ex1_bju_sel (idu_iu_ex1_bju_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_len (idu_iu_ex1_inst_len ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_split (idu_iu_ex1_split ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src0_reg (idu_iu_ex1_src0_reg ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_src1_reg (idu_iu_ex1_src1_reg ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .idu_iu_tail_fail (idu_iu_tail_fail ), + .idu_iu_tail_fail_gate (idu_iu_tail_fail_gate ), + .ifu_iu_chgflw_pc (ifu_iu_chgflw_pc ), + .ifu_iu_chgflw_vld (ifu_iu_chgflw_vld ), + .ifu_iu_ex1_pc_pred (ifu_iu_ex1_pc_pred ), + .ifu_iu_reset_vld (ifu_iu_reset_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .iu_cp0_ex1_borrow_expt_pc (iu_cp0_ex1_borrow_expt_pc ), + .iu_ex1_cur_pc (iu_ex1_cur_pc ), + .iu_hpcp_inst_bht_mispred (iu_hpcp_inst_bht_mispred ), + .iu_hpcp_inst_condbr (iu_hpcp_inst_condbr ), + .iu_hpcp_inst_condbr_gate (iu_hpcp_inst_condbr_gate ), + .iu_idu_bju_global_stall (iu_idu_bju_global_stall ), + .iu_idu_bju_stall (iu_idu_bju_stall ), + .iu_ifu_bht_cur_pc (iu_ifu_bht_cur_pc ), + .iu_ifu_bht_mispred (iu_ifu_bht_mispred ), + .iu_ifu_bht_mispred_gate (iu_ifu_bht_mispred_gate ), + .iu_ifu_bht_pred (iu_ifu_bht_pred ), + .iu_ifu_bht_taken (iu_ifu_bht_taken ), + .iu_ifu_br_vld (iu_ifu_br_vld ), + .iu_ifu_br_vld_gate (iu_ifu_br_vld_gate ), + .iu_ifu_ind_link_vld (iu_ifu_ind_link_vld ), + .iu_ifu_link_vld (iu_ifu_link_vld ), + .iu_ifu_link_vld_gate (iu_ifu_link_vld_gate ), + .iu_ifu_pc_mispred (iu_ifu_pc_mispred ), + .iu_ifu_pc_mispred_gate (iu_ifu_pc_mispred_gate ), + .iu_ifu_ret_vld (iu_ifu_ret_vld ), + .iu_ifu_ret_vld_gate (iu_ifu_ret_vld_gate ), + .iu_ifu_tar_pc (iu_ifu_tar_pc ), + .iu_ifu_tar_pc_vld (iu_ifu_tar_pc_vld ), + .iu_ifu_tar_pc_vld_gate (iu_ifu_tar_pc_vld_gate ), + .iu_rtu_ex1_bju_branch_inst (iu_rtu_ex1_bju_branch_inst ), + .iu_rtu_ex1_bju_cmplt (iu_rtu_ex1_bju_cmplt ), + .iu_rtu_ex1_bju_cmplt_dp (iu_rtu_ex1_bju_cmplt_dp ), + .iu_rtu_ex1_bju_cur_pc (iu_rtu_ex1_bju_cur_pc ), + .iu_rtu_ex1_bju_inst_len (iu_rtu_ex1_bju_inst_len ), + .iu_rtu_ex1_bju_inst_vld (iu_rtu_ex1_bju_inst_vld ), + .iu_rtu_ex1_bju_split_inst (iu_rtu_ex1_bju_split_inst ), + .iu_rtu_ex1_next_pc (iu_rtu_ex1_next_pc ), + .iu_rtu_ex2_bju_flush (iu_rtu_ex2_bju_flush ), + .iu_rtu_ex2_bju_next_pc (iu_rtu_ex2_bju_next_pc ), + .iu_rtu_ex2_bju_next_pc_vld (iu_rtu_ex2_bju_next_pc_vld ), + .iu_yy_xx_cancel (iu_yy_xx_cancel ), + .lsu_iu_ex2_data (lsu_iu_ex2_data ), + .lsu_iu_ex2_data_vld (lsu_iu_ex2_data_vld ), + .lsu_iu_ex2_dest_reg (lsu_iu_ex2_dest_reg ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_iu_bju_ex2_cur_pc (rtu_iu_bju_ex2_cur_pc ), + .rtu_iu_ex1_cmplt_dp_vld (rtu_iu_ex1_cmplt_dp_vld ), + .rtu_iu_ex1_cmplt_inst_len (rtu_iu_ex1_cmplt_inst_len ), + .rtu_iu_ex1_cmplt_split_inst (rtu_iu_ex1_cmplt_split_inst ), + .rtu_iu_ex1_cmplt_vld (rtu_iu_ex1_cmplt_vld ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .sysio_iu_rst_addr (sysio_iu_rst_addr ) +); + + +// &Instance("pa_iu_addr_gen"); @45 +pa_iu_addr_gen x_pa_iu_addr_gen ( + .ag_bju_pc (ag_bju_pc ), + .ag_dp_ex1_dst_preg (ag_dp_ex1_dst_preg ), + .ag_dp_ex1_fwd_data (ag_dp_ex1_fwd_data ), + .ag_dp_ex1_fwd_vld (ag_dp_ex1_fwd_vld ), + .idu_iu_ex1_ag_imm (idu_iu_ex1_ag_imm ), + .idu_iu_ex1_bju_sel (idu_iu_ex1_bju_sel ), + .idu_iu_ex1_bju_use_pc (idu_iu_ex1_bju_use_pc ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .iu_ex1_cur_pc (iu_ex1_cur_pc ), + .iu_idu_ex1_src1_update_value (iu_idu_ex1_src1_update_value), + .iu_lsu_ex1_lsi_rst (iu_lsu_ex1_lsi_rst ), + .lsu_iu_ex1_base_wb (lsu_iu_ex1_base_wb ), + .lsu_iu_ex1_src1_sel (lsu_iu_ex1_src1_sel ) +); + + +// &Instance("pa_iu_ctrl"); @47 +pa_iu_ctrl x_pa_iu_ctrl ( + .ag_dp_ex1_dst_preg (ag_dp_ex1_dst_preg ), + .ag_dp_ex1_fwd_data (ag_dp_ex1_fwd_data ), + .ag_dp_ex1_fwd_vld (ag_dp_ex1_fwd_vld ), + .alu_dp_ex1_cmplt (alu_dp_ex1_cmplt ), + .alu_dp_ex1_cmplt_dp (alu_dp_ex1_cmplt_dp ), + .alu_dp_ex1_fwd_vld (alu_dp_ex1_fwd_vld ), + .alu_dp_ex1_rslt (alu_dp_ex1_rslt ), + .bju_dp_ex1_cmplt_dp (bju_dp_ex1_cmplt_dp ), + .bju_dp_ex1_rslt (bju_dp_ex1_rslt ), + .bju_dp_ex1_rslt_vld (bju_dp_ex1_rslt_vld ), + .bju_dp_ex1_stall (bju_dp_ex1_stall ), + .bju_dp_no_op (bju_dp_no_op ), + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .div_ctrl_itering (div_ctrl_itering ), + .div_dp_ex1_cmplt (div_dp_ex1_cmplt ), + .div_dp_ex1_cmplt_dp (div_dp_ex1_cmplt_dp ), + .div_dp_ex1_fwd_data (div_dp_ex1_fwd_data ), + .div_dp_ex1_fwd_vld (div_dp_ex1_fwd_vld ), + .div_dp_ex1_stall (div_dp_ex1_stall ), + .div_dp_ex2_dst_preg (div_dp_ex2_dst_preg ), + .div_dp_ex2_rslt (div_dp_ex2_rslt ), + .div_dp_ex2_rslt_vld (div_dp_ex2_rslt_vld ), + .dp_xx_ex1_stall (dp_xx_ex1_stall ), + .dp_xx_ex2_stall (dp_xx_ex2_stall ), + .forever_cpuclk (forever_cpuclk ), + .fpu_iu_ex1_cmplt (fpu_iu_ex1_cmplt ), + .fpu_iu_ex1_cmplt_dp (fpu_iu_ex1_cmplt_dp ), + .idu_iu_ex1_alu_sel (idu_iu_ex1_alu_sel ), + .idu_iu_ex1_dst_preg (idu_iu_ex1_dst_preg ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_len (idu_iu_ex1_inst_len ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_ipop_int_mask (idu_iu_ex1_ipop_int_mask ), + .idu_iu_ex1_ipush_mie_en (idu_iu_ex1_ipush_mie_en ), + .idu_iu_ex1_ipush_spec_fail (idu_iu_ex1_ipush_spec_fail ), + .idu_iu_ex1_mul_sel (idu_iu_ex1_mul_sel ), + .idu_iu_ex1_rd_pair (idu_iu_ex1_rd_pair ), + .idu_iu_ex1_split (idu_iu_ex1_split ), + .idu_iu_ex1_tail_int_vld (idu_iu_ex1_tail_int_vld ), + .idu_iu_ex1_wb_vld (idu_iu_ex1_wb_vld ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .iu_ex2_div_grant (iu_ex2_div_grant ), + .iu_idu_ex1_fwd_data (iu_idu_ex1_fwd_data ), + .iu_idu_ex1_fwd_preg (iu_idu_ex1_fwd_preg ), + .iu_idu_ex1_fwd_vld (iu_idu_ex1_fwd_vld ), + .iu_idu_ex1_stall (iu_idu_ex1_stall ), + .iu_idu_ex2_div_vld (iu_idu_ex2_div_vld ), + .iu_idu_ex2_fwd_data0 (iu_idu_ex2_fwd_data0 ), + .iu_idu_ex2_fwd_data1 (iu_idu_ex2_fwd_data1 ), + .iu_idu_ex2_fwd_preg0 (iu_idu_ex2_fwd_preg0 ), + .iu_idu_ex2_fwd_preg1 (iu_idu_ex2_fwd_preg1 ), + .iu_idu_ex2_fwd_vld0 (iu_idu_ex2_fwd_vld0 ), + .iu_idu_ex2_fwd_vld1 (iu_idu_ex2_fwd_vld1 ), + .iu_idu_ex2_inst_vld (iu_idu_ex2_inst_vld ), + .iu_idu_ex2_rd_pair (iu_idu_ex2_rd_pair ), + .iu_idu_id_stall (iu_idu_id_stall ), + .iu_lsu_ex2_wb0_grant (iu_lsu_ex2_wb0_grant ), + .iu_rtu_ex1_cmplt (iu_rtu_ex1_cmplt ), + .iu_rtu_ex1_cmplt_dp (iu_rtu_ex1_cmplt_dp ), + .iu_rtu_ex1_inst_len (iu_rtu_ex1_inst_len ), + .iu_rtu_ex1_inst_vld (iu_rtu_ex1_inst_vld ), + .iu_rtu_ex1_ipop_int_mask (iu_rtu_ex1_ipop_int_mask ), + .iu_rtu_ex1_ipush_mie_en (iu_rtu_ex1_ipush_mie_en ), + .iu_rtu_ex1_ipush_spec_fail (iu_rtu_ex1_ipush_spec_fail ), + .iu_rtu_ex1_split_inst (iu_rtu_ex1_split_inst ), + .iu_rtu_ex1_tail_int_vld (iu_rtu_ex1_tail_int_vld ), + .iu_rtu_wb0_data (iu_rtu_wb0_data ), + .iu_rtu_wb0_preg (iu_rtu_wb0_preg ), + .iu_rtu_wb0_vld (iu_rtu_wb0_vld ), + .iu_xx_no_op (iu_xx_no_op ), + .lsu_iu_ex2_lsi_dst_preg (lsu_iu_ex2_lsi_dst_preg ), + .lsu_iu_ex2_lsi_rslt (lsu_iu_ex2_lsi_rslt ), + .lsu_iu_ex2_lsi_rslt_vld (lsu_iu_ex2_lsi_rslt_vld ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .mul_dp_ex1_cmplt (mul_dp_ex1_cmplt ), + .mul_dp_ex1_cmplt_dp (mul_dp_ex1_cmplt_dp ), + .mul_dp_ex2_inst_vld (mul_dp_ex2_inst_vld ), + .mul_dp_ex2_rslt0 (mul_dp_ex2_rslt0 ), + .mul_dp_ex2_rslt0_vld (mul_dp_ex2_rslt0_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_iu_pending_spec_expt_vld (rtu_iu_pending_spec_expt_vld ), + .rtu_iu_pending_spec_halt_info_vld (rtu_iu_pending_spec_halt_info_vld), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + + +// &Instance("pa_iu_dsp_mulu"); @50 +// &Instance("pa_iu_mul"); @52 +pa_iu_mul x_pa_iu_mul ( + .cp0_iu_icg_en (cp0_iu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dp_xx_ex1_stall (dp_xx_ex1_stall ), + .dp_xx_ex2_stall (dp_xx_ex2_stall ), + .forever_cpuclk (forever_cpuclk ), + .idu_iu_ex1_func (idu_iu_ex1_func ), + .idu_iu_ex1_gateclk_vld (idu_iu_ex1_gateclk_vld ), + .idu_iu_ex1_inst_vld (idu_iu_ex1_inst_vld ), + .idu_iu_ex1_mul_cmplt_dp_sel (idu_iu_ex1_mul_cmplt_dp_sel), + .idu_iu_ex1_mul_gateclk_sel (idu_iu_ex1_mul_gateclk_sel ), + .idu_iu_ex1_mul_high_sel (idu_iu_ex1_mul_high_sel ), + .idu_iu_ex1_mul_sel (idu_iu_ex1_mul_sel ), + .idu_iu_ex1_src0 (idu_iu_ex1_src0 ), + .idu_iu_ex1_src1 (idu_iu_ex1_src1 ), + .idu_iu_ex1_src2 (idu_iu_ex1_src2 ), + .ifu_iu_warm_up (ifu_iu_warm_up ), + .mul_dp_ex1_cmplt (mul_dp_ex1_cmplt ), + .mul_dp_ex1_cmplt_dp (mul_dp_ex1_cmplt_dp ), + .mul_dp_ex2_inst_vld (mul_dp_ex2_inst_vld ), + .mul_dp_ex2_rslt0 (mul_dp_ex2_rslt0 ), + .mul_dp_ex2_rslt0_vld (mul_dp_ex2_rslt0_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + + +assign iu_dtu_debug_info[8:0] = {bju_iu_debug_info[3:0], div_iu_debug_info[4:0]}; + + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_data_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_data_array.v new file mode 100644 index 0000000000000000000000000000000000000000..032a26aa9937c63d3bd2d34c5adfd899a4fdedde --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_data_array.v @@ -0,0 +1,99 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module pa_dcache_data_array( + forever_cpuclk, + cp0_lsu_icg_en, + pad_yy_icg_scan_en, + data_clk_en, + data_cen, + data_wen, + data_din, + data_idx, + data_gwen, + data_dout +); + +input forever_cpuclk; +input cp0_lsu_icg_en; +input pad_yy_icg_scan_en; +input data_clk_en; +input data_cen; +input [11:0] data_idx; +input data_gwen; +input [31:0] data_wen; +input [31:0] data_din; +output [31:0] data_dout; + +wire forever_cpuclk; +wire cp0_lsu_icg_en; +wire pad_yy_icg_scan_en; +wire data_clk_en; +wire data_cen; +wire [11:0] data_idx; +wire data_gwen; +wire [31:0] data_wen; +wire [31:0] data_din; +wire [31:0] data_dout; +wire data_clk; + + //========================================================== +// Instance of Gated Cell +//========================================================== +gated_clk_cell x_dcache_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (data_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (data_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); +//csky vperl_off +//========================================================== +// Instance dcache array +//========================================================== +`ifdef DCACHE_2K +pa_spsram_128x32 x_pa_spsram_128x32 ( +`endif +`ifdef DCACHE_4K +pa_spsram_256x32 x_pa_spsram_256x32 ( +`endif +`ifdef DCACHE_8K +pa_spsram_512x32 x_pa_spsram_512x32 ( +`endif +`ifdef DCACHE_16K +pa_spsram_1024x32 x_pa_spsram_1024x32 ( +`endif +`ifdef DCACHE_32K +pa_spsram_2048x32 x_pa_spsram_2048x32 ( +`endif +`ifdef DCACHE_64K +pa_spsram_4096x32 x_pa_spsram_4096x32 ( +`endif + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .A (data_idx[`D_DATA_INDEX_WIDTH-1:0]), + .CEN (data_cen ), + .CLK (data_clk ), + .GWEN (data_gwen ), + .D (data_din ), + .Q (data_dout ), + .WEN (data_wen ) +); +//csky vperl_on +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_dirty_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_dirty_array.v new file mode 100644 index 0000000000000000000000000000000000000000..180c6927633988ad5fe8a0f4fec910f3eebd857a --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_dirty_array.v @@ -0,0 +1,108 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 +// &Depend("pa_spsram_32x4.vp"); @19 +// &Depend("pa_spsram_64x4.vp"); @20 +// &Depend("pa_spsram_128x4.vp"); @21 +// &Depend("pa_spsram_256x4.vp"); @22 +// &Depend("pa_spsram_512x4.vp"); @23 +// &Depend("pa_spsram_1024x4.vp"); @24 +// &Depend("gated_clk_cell.vp"); @25 + +module pa_dcache_dirty_array( + forever_cpuclk, + cp0_lsu_icg_en, + pad_yy_icg_scan_en, + dirty_clk_en, + dirty_cen, + dirty_wen, + dirty_din, + dirty_idx, + dirty_gwen, + dirty_dout +); + +input forever_cpuclk; +input cp0_lsu_icg_en; +input pad_yy_icg_scan_en; +input dirty_clk_en; +input dirty_cen; +input [9:0] dirty_idx; +input dirty_gwen; +input [3:0] dirty_wen; +input [3:0] dirty_din; +output [3:0] dirty_dout; + +wire forever_cpuclk; +wire cp0_lsu_icg_en; +wire pad_yy_icg_scan_en; +wire dirty_clk_en; +wire dirty_cen; +wire [9:0] dirty_idx; +wire dirty_gwen; +wire [3:0] dirty_wen; +wire [3:0] dirty_din; +wire [3:0] dirty_dout; +wire dirty_clk; + + //========================================================== +// Instance of Gated Cell +//========================================================== +gated_clk_cell x_dcache_dirty_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dirty_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dirty_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); +//csky vperl_off +//========================================================== +// Instance dcache array +//========================================================== +`ifdef DCACHE_2K +pa_spsram_32x4 x_pa_spsram_32x4 ( +`endif +`ifdef DCACHE_4K +pa_spsram_64x4 x_pa_spsram_64x4 ( +`endif +`ifdef DCACHE_8K +pa_spsram_128x4 x_pa_spsram_128x4 ( +`endif +`ifdef DCACHE_16K +pa_spsram_256x4 x_pa_spsram_256x4 ( +`endif +`ifdef DCACHE_32K +pa_spsram_512x4 x_pa_spsram_512x4 ( +`endif +`ifdef DCACHE_64K +pa_spsram_1024x4 x_pa_spsram_1024x4 ( +`endif + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .A (dirty_idx[`D_TAG_INDEX_WIDTH-1:0]), + .CEN (dirty_cen ), + .CLK (dirty_clk ), + .GWEN (dirty_gwen ), + .D (dirty_din ), + .Q (dirty_dout ), + .WEN (dirty_wen ) +); +//csky vperl_on +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_tag_array.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_tag_array.v new file mode 100644 index 0000000000000000000000000000000000000000..9365732bfb4c9a0cafbe644c092263159dc3aaf1 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_tag_array.v @@ -0,0 +1,124 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 +// &Depend("pa_spsram_32x46.vp"); @19 +// &Depend("pa_spsram_64x44.vp"); @20 +// &Depend("pa_spsram_128x42.vp"); @21 +// &Depend("pa_spsram_256x40.vp"); @22 +// &Depend("pa_spsram_512x38.vp"); @23 +// &Depend("pa_spsram_1024x36.vp"); @24 +// &Depend("gated_clk_cell.vp"); @25 + +module pa_dcache_tag_array( + forever_cpuclk, + cp0_lsu_icg_en, + pad_yy_icg_scan_en, + tag_clk_en, + tag_cen, + tag_wen, + tag_din, + tag_idx, + tag_gwen, + tag_dout +); + +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +input forever_cpuclk; +input cp0_lsu_icg_en; +input pad_yy_icg_scan_en; +input tag_clk_en; +input tag_cen; +input [45:0] tag_wen; +input [45:0] tag_din; +input [9:0] tag_idx; +input tag_gwen; +output [45:0] tag_dout; + +wire forever_cpuclk; +wire cp0_lsu_icg_en; +wire pad_yy_icg_scan_en; +wire tag_clk_en; +wire tag_cen; +wire [45:0] tag_wen; +wire [45:0] tag_din; +wire [9:0] tag_idx; +wire tag_gwen; +wire [45:0] tag_dout; +wire tag_clk; + +wire [2*D_TAG_TAG_LEN+1:0] tag_wen_raw; +wire [2*D_TAG_TAG_LEN+1:0] tag_din_raw; +wire [2*D_TAG_TAG_LEN+1:0] tag_dout_raw; + +assign tag_wen_raw[2*D_TAG_TAG_LEN+1:0] = {tag_wen[45], tag_wen[23+D_TAG_TAG_LEN-1:23], + tag_wen[22], tag_wen[D_TAG_TAG_LEN-1:0]}; + +assign tag_din_raw[2*D_TAG_TAG_LEN+1:0] = {tag_din[45], tag_din[23+D_TAG_TAG_LEN-1:23], + tag_din[22], tag_din[D_TAG_TAG_LEN-1:0]}; + +assign tag_dout[45:0] = {tag_dout_raw[2*D_TAG_TAG_LEN+1], {(22-D_TAG_TAG_LEN){1'b0}}, tag_dout_raw[2*D_TAG_TAG_LEN:D_TAG_TAG_LEN+1], + tag_dout_raw[D_TAG_TAG_LEN], {(22-D_TAG_TAG_LEN){1'b0}}, tag_dout_raw[D_TAG_TAG_LEN-1:0]}; + + //========================================================== +// Instance of Gated Cell +//========================================================== +gated_clk_cell x_dcache_tag_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tag_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (tag_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); +//csky vperl_off +//========================================================== +// Instance dcache array +//========================================================== +`ifdef DCACHE_2K +pa_spsram_32x46 x_pa_spsram_32x46 ( +`endif +`ifdef DCACHE_4K +pa_spsram_64x44 x_pa_spsram_64x44 ( +`endif +`ifdef DCACHE_8K +pa_spsram_128x42 x_pa_spsram_128x42 ( +`endif +`ifdef DCACHE_16K +pa_spsram_256x40 x_pa_spsram_256x40 ( +`endif +`ifdef DCACHE_32K +pa_spsram_512x38 x_pa_spsram_512x38 ( +`endif +`ifdef DCACHE_64K +pa_spsram_1024x36 x_pa_spsram_1024x36 ( +`endif + `ifdef MEM_CFG_IN + .mem_cfg_in (mem_cfg_in ), + `endif + .A (tag_idx[D_TAG_INDEX_LEN-1:0]), + .CEN (tag_cen ), + .CLK (tag_clk ), + .GWEN (tag_gwen ), + .D (tag_din_raw[2*D_TAG_TAG_LEN+1:0]), + .Q (tag_dout_raw[2*D_TAG_TAG_LEN+1:0]), + .WEN (tag_wen_raw[2*D_TAG_TAG_LEN+1:0]) +); +//csky vperl_on +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_top.v new file mode 100644 index 0000000000000000000000000000000000000000..4681dd35637ba8e7b2a502ce7ec3bcf9ece616b8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_dcache_top.v @@ -0,0 +1,292 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_dcache_top( + cp0_lsu_icg_en, + dcache_data_cen_way0_bank0, + dcache_data_cen_way0_bank1, + dcache_data_cen_way1_bank0, + dcache_data_cen_way1_bank1, + dcache_data_din, + dcache_data_dout_way0, + dcache_data_dout_way1, + dcache_data_idx, + dcache_data_wen, + dcache_dirty_cen, + dcache_dirty_din, + dcache_dirty_dout, + dcache_dirty_idx, + dcache_dirty_wen, + dcache_tag_cen, + dcache_tag_din, + dcache_tag_dout, + dcache_tag_idx, + dcache_tag_wen, + forever_cpuclk, + pad_yy_icg_scan_en +); + +// &Ports; @21 +input cp0_lsu_icg_en; +input dcache_data_cen_way0_bank0; +input dcache_data_cen_way0_bank1; +input dcache_data_cen_way1_bank0; +input dcache_data_cen_way1_bank1; +input [63:0] dcache_data_din; +input [11:0] dcache_data_idx; +input [3 :0] dcache_data_wen; +input dcache_dirty_cen; +input [2 :0] dcache_dirty_din; +input [9 :0] dcache_dirty_idx; +input [2 :0] dcache_dirty_wen; +input dcache_tag_cen; +input [22:0] dcache_tag_din; +input [9 :0] dcache_tag_idx; +input [1 :0] dcache_tag_wen; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output [63:0] dcache_data_dout_way0; +output [63:0] dcache_data_dout_way1; +output [2 :0] dcache_dirty_dout; +output [45:0] dcache_tag_dout; + +// &Regs; @22 + +// &Wires; @23 +wire cp0_lsu_icg_en; +wire dcache_data_cen00; +wire dcache_data_cen01; +wire dcache_data_cen10; +wire dcache_data_cen11; +wire dcache_data_cen_way0_bank0; +wire dcache_data_cen_way0_bank1; +wire dcache_data_cen_way1_bank0; +wire dcache_data_cen_way1_bank1; +wire dcache_data_clk_en00; +wire dcache_data_clk_en01; +wire dcache_data_clk_en10; +wire dcache_data_clk_en11; +wire [63:0] dcache_data_din; +wire [63:0] dcache_data_dout_way0; +wire [63:0] dcache_data_dout_way1; +wire dcache_data_gwen_t0; +wire dcache_data_gwen_t1; +wire [11:0] dcache_data_idx; +wire [3 :0] dcache_data_wen; +wire [31:0] dcache_data_wen_t0; +wire [31:0] dcache_data_wen_t1; +wire dcache_dirty_cen; +wire dcache_dirty_clk_en; +wire [2 :0] dcache_dirty_din; +wire [3 :0] dcache_dirty_din_t; +wire [2 :0] dcache_dirty_dout; +wire [3 :0] dcache_dirty_dout_t; +wire dcache_dirty_gwen; +wire [9 :0] dcache_dirty_idx; +wire [2 :0] dcache_dirty_wen; +wire [3 :0] dcache_dirty_wen_t; +wire dcache_tag_cen; +wire dcache_tag_clk_en; +wire [22:0] dcache_tag_din; +wire [45:0] dcache_tag_din_t; +wire [45:0] dcache_tag_dout; +wire dcache_tag_gwen; +wire [9 :0] dcache_tag_idx; +wire [1 :0] dcache_tag_wen; +wire [45:0] dcache_tag_wen_t; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; + + + +assign dcache_tag_clk_en = !dcache_tag_cen; +assign dcache_tag_gwen = &dcache_tag_wen[1:0]; +assign dcache_tag_din_t[45:0] = {2{dcache_tag_din[22:0]}}; +assign dcache_tag_wen_t[45:0] = {{23{dcache_tag_wen[1]}}, + {23{dcache_tag_wen[0]}}}; + +// &Instance("pa_dcache_tag_array", "x_pa_dcache_tag_array"); @32 +pa_dcache_tag_array x_pa_dcache_tag_array ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .tag_cen (dcache_tag_cen ), + .tag_clk_en (dcache_tag_clk_en ), + .tag_din (dcache_tag_din_t ), + .tag_dout (dcache_tag_dout ), + .tag_gwen (dcache_tag_gwen ), + .tag_idx (dcache_tag_idx ), + .tag_wen (dcache_tag_wen_t ) +); + +// &Connect( @33 +// .tag_clk_en (dcache_tag_clk_en ), @34 +// .tag_cen (dcache_tag_cen ), @35 +// .tag_wen (dcache_tag_wen_t ), @36 +// .tag_din (dcache_tag_din_t ), @37 +// .tag_idx (dcache_tag_idx ), @38 +// .tag_gwen (dcache_tag_gwen ), @39 +// .tag_dout (dcache_tag_dout )); @40 + +assign dcache_dirty_clk_en = !dcache_dirty_cen; +assign dcache_dirty_gwen = &dcache_dirty_wen[2:0]; +assign dcache_dirty_wen_t[3:0] = {dcache_dirty_wen[2],dcache_dirty_wen[2:0]}; +assign dcache_dirty_din_t[3:0] = {1'b0,dcache_dirty_din[2:0]}; +assign dcache_dirty_dout[2:0] = dcache_dirty_dout_t[2:0]; + +// &Instance("pa_dcache_dirty_array", "x_pa_dcache_dirty_array"); @48 +pa_dcache_dirty_array x_pa_dcache_dirty_array ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .dirty_cen (dcache_dirty_cen ), + .dirty_clk_en (dcache_dirty_clk_en), + .dirty_din (dcache_dirty_din_t ), + .dirty_dout (dcache_dirty_dout_t), + .dirty_gwen (dcache_dirty_gwen ), + .dirty_idx (dcache_dirty_idx ), + .dirty_wen (dcache_dirty_wen_t ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect( @49 +// .dirty_clk_en (dcache_dirty_clk_en ), @50 +// .dirty_cen (dcache_dirty_cen ), @51 +// .dirty_wen (dcache_dirty_wen_t ), @52 +// .dirty_din (dcache_dirty_din_t ), @53 +// .dirty_idx (dcache_dirty_idx ), @54 +// .dirty_gwen (dcache_dirty_gwen ), @55 +// .dirty_dout (dcache_dirty_dout_t )); @56 + +assign dcache_data_gwen_t0 = &dcache_data_wen[3:0]; +assign dcache_data_wen_t0[31:0] = {{8{dcache_data_wen[3]}}, + {8{dcache_data_wen[2]}}, + {8{dcache_data_wen[1]}}, + {8{dcache_data_wen[0]}}}; + +assign dcache_data_gwen_t1 = dcache_data_gwen_t0; +assign dcache_data_wen_t1[31:0] = dcache_data_wen_t0[31:0]; + +assign dcache_data_clk_en00 = !dcache_data_cen_way0_bank0; +assign dcache_data_cen00 = dcache_data_cen_way0_bank0; + +// &Instance("pa_dcache_data_array", "x_pa_dcache_data_array_way0_bank0"); @78 +pa_dcache_data_array x_pa_dcache_data_array_way0_bank0 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .data_cen (dcache_data_cen00 ), + .data_clk_en (dcache_data_clk_en00 ), + .data_din (dcache_data_din[31:0] ), + .data_dout (dcache_data_dout_way0[31:0]), + .data_gwen (dcache_data_gwen_t0 ), + .data_idx (dcache_data_idx ), + .data_wen (dcache_data_wen_t0 ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect( @79 +// .data_clk_en (dcache_data_clk_en00 ), @80 +// .data_cen (dcache_data_cen00 ), @81 +// .data_wen (dcache_data_wen_t0 ), @82 +// .data_din (dcache_data_din[31:0] ), @83 +// .data_idx (dcache_data_idx ), @84 +// .data_gwen (dcache_data_gwen_t0 ), @85 +// .data_dout (dcache_data_dout_way0[31:0])); @86 + +assign dcache_data_clk_en01 = !dcache_data_cen_way0_bank1; +assign dcache_data_cen01 = dcache_data_cen_way0_bank1; + +// &Instance("pa_dcache_data_array", "x_pa_dcache_data_array_way0_bank1"); @91 +pa_dcache_data_array x_pa_dcache_data_array_way0_bank1 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .data_cen (dcache_data_cen01 ), + .data_clk_en (dcache_data_clk_en01 ), + .data_din (dcache_data_din[63:32] ), + .data_dout (dcache_data_dout_way0[63:32]), + .data_gwen (dcache_data_gwen_t1 ), + .data_idx (dcache_data_idx ), + .data_wen (dcache_data_wen_t1 ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect( @92 +// .data_clk_en (dcache_data_clk_en01 ), @93 +// .data_cen (dcache_data_cen01 ), @94 +// .data_wen (dcache_data_wen_t1 ), @95 +// .data_din (dcache_data_din[63:32] ), @96 +// .data_idx (dcache_data_idx ), @97 +// .data_gwen (dcache_data_gwen_t1 ), @98 +// .data_dout (dcache_data_dout_way0[63:32])); @99 + + +assign dcache_data_clk_en10 = !dcache_data_cen_way1_bank0; +assign dcache_data_cen10 = dcache_data_cen_way1_bank0; + +// &Instance("pa_dcache_data_array", "x_pa_dcache_data_array_way1_bank0"); @105 +pa_dcache_data_array x_pa_dcache_data_array_way1_bank0 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .data_cen (dcache_data_cen10 ), + .data_clk_en (dcache_data_clk_en10 ), + .data_din (dcache_data_din[31:0] ), + .data_dout (dcache_data_dout_way1[31:0]), + .data_gwen (dcache_data_gwen_t0 ), + .data_idx (dcache_data_idx ), + .data_wen (dcache_data_wen_t0 ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect( @106 +// .data_clk_en (dcache_data_clk_en10 ), @107 +// .data_cen (dcache_data_cen10 ), @108 +// .data_wen (dcache_data_wen_t0 ), @109 +// .data_din (dcache_data_din[31:0] ), @110 +// .data_idx (dcache_data_idx ), @111 +// .data_gwen (dcache_data_gwen_t0 ), @112 +// .data_dout (dcache_data_dout_way1[31:0])); @113 + +assign dcache_data_clk_en11 = !dcache_data_cen_way1_bank1; +assign dcache_data_cen11 = dcache_data_cen_way1_bank1; + +// &Instance("pa_dcache_data_array", "x_pa_dcache_data_array_way1_bank1"); @118 +pa_dcache_data_array x_pa_dcache_data_array_way1_bank1 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .data_cen (dcache_data_cen11 ), + .data_clk_en (dcache_data_clk_en11 ), + .data_din (dcache_data_din[63:32] ), + .data_dout (dcache_data_dout_way1[63:32]), + .data_gwen (dcache_data_gwen_t1 ), + .data_idx (dcache_data_idx ), + .data_wen (dcache_data_wen_t1 ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect( @119 +// .data_clk_en (dcache_data_clk_en11 ), @120 +// .data_cen (dcache_data_cen11 ), @121 +// .data_wen (dcache_data_wen_t1 ), @122 +// .data_din (dcache_data_din[63:32] ), @123 +// .data_idx (dcache_data_idx ), @124 +// .data_gwen (dcache_data_gwen_t1 ), @125 +// .data_dout (dcache_data_dout_way1[63:32])); @126 + +// &ModuleEnd; @128 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ag.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ag.v new file mode 100644 index 0000000000000000000000000000000000000000..953affa189b591e2b98238a796814b70cbd43aa4 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ag.v @@ -0,0 +1,1990 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @19 + +// &ModuleBeg; @21 +module pa_lsu_ag( + ag_dc_addr, + ag_dc_buf, + ag_dc_bytes_vld, + ag_dc_ca, + ag_dc_dcache_grant, + ag_dc_dest_reg, + ag_dc_fls, + ag_dc_func, + ag_dc_inst_vld, + ag_dc_inst_vld_gate, + ag_dc_lm_pass, + ag_dc_mach_mode, + ag_dc_ori_size, + ag_dc_pmp_expt, + ag_dc_sign_ext, + ag_dc_size, + ag_dc_so, + ag_dc_split, + ag_dc_split_first, + ag_dc_split_last, + ag_dc_src1_depd, + ag_dc_src1_reg, + ag_dc_st_data, + ag_dc_wdata_shift, + ag_dtu_addr, + ag_dtu_addr_ready, + ag_dtu_amo_type, + ag_dtu_bytes_vld, + ag_dtu_data, + ag_dtu_data_chk_mask, + ag_dtu_data_vld, + ag_dtu_halt_info, + ag_dtu_mem_access_size, + ag_dtu_pipe_down, + ag_dtu_req, + ag_dtu_req_gate, + ag_dtu_split_last, + ag_dtu_st_type, + ag_ncb_addr, + ag_ncb_inst_vld, + ag_ncb_inst_vld_dp, + ag_ncb_src1_reg, + ag_ncb_st_data, + ag_xx_inst_abort, + ag_xx_split_done, + arb_icc_data_grant, + arb_rdl_grant, + arb_stb_xx_grant, + cp0_lsu_icg_en, + cp0_lsu_mm, + cp0_xx_async_expt_en, + cp0_yy_mach_mode, + cpurst_b, + da_xx_fwd_data, + da_xx_fwd_fls, + da_xx_fwd_preg, + da_xx_fwd_vld, + dc_ag_async_expt_vld, + dc_ag_async_ld_inst, + dc_ag_async_mtval, + dc_ag_cache_stall, + dc_ag_dcache_addr, + dc_ag_dcache_req, + dc_ag_dcache_size, + dc_ag_empty, + dc_ag_func, + dc_ag_pmp_ld_inst, + dc_ag_pmp_mtval, + dc_ag_stall, + dcache_data_cen_way0_bank0, + dcache_data_cen_way0_bank1, + dcache_data_cen_way1_bank0, + dcache_data_cen_way1_bank1, + dcache_data_din, + dcache_data_idx, + dcache_data_wen, + dcache_dirty_cen, + dcache_dirty_din, + dcache_dirty_idx, + dcache_dirty_wen, + dcache_tag_cen, + dcache_tag_din, + dcache_tag_idx, + dcache_tag_wen, + dtif_ag_cmplt_ready, + dtif_ag_fsm_idle, + dtif_ag_halt_info, + dtif_ag_halt_info_up, + dtif_ag_pipedown_mask, + dtif_ag_stall, + forever_cpuclk, + icc_arb_data_bank, + icc_arb_data_din, + icc_arb_data_idx, + icc_arb_data_req, + icc_arb_data_way, + icc_arb_data_wen, + icc_arb_dirty_din, + icc_arb_dirty_idx, + icc_arb_dirty_req, + icc_arb_dirty_wen, + icc_arb_tag_din, + icc_arb_tag_idx, + icc_arb_tag_req, + icc_arb_tag_wen, + idu_lsu_ex1_ag_imm, + idu_lsu_ex1_base, + idu_lsu_ex1_base_sel, + idu_lsu_ex1_base_wb, + idu_lsu_ex1_data, + idu_lsu_ex1_dest_reg, + idu_lsu_ex1_dest_vld, + idu_lsu_ex1_dp_sel, + idu_lsu_ex1_fls, + idu_lsu_ex1_func, + idu_lsu_ex1_gateclk_sel, + idu_lsu_ex1_halt_info, + idu_lsu_ex1_ipop_int_mask, + idu_lsu_ex1_ipush_spec, + idu_lsu_ex1_length, + idu_lsu_ex1_offset_sel, + idu_lsu_ex1_sel, + idu_lsu_ex1_sign_extend, + idu_lsu_ex1_size, + idu_lsu_ex1_split, + idu_lsu_ex1_src0_reg, + idu_lsu_ex1_src1_depd, + idu_lsu_ex1_src1_reg, + ifu_lsu_warm_up, + iu_lsu_ex1_lsi_rst, + iu_lsu_ex2_wb0_grant, + lfb_arb_data_bank, + lfb_arb_data_din, + lfb_arb_data_idx, + lfb_arb_data_req, + lfb_arb_data_way, + lfb_arb_data_wen, + lfb_arb_dcache_sel, + lfb_arb_dirty_din, + lfb_arb_dirty_idx, + lfb_arb_dirty_req, + lfb_arb_dirty_wen, + lfb_arb_tag_din, + lfb_arb_tag_idx, + lfb_arb_tag_req, + lfb_arb_tag_wen, + lm_clr, + lm_lr_bus, + lm_pass, + lm_sc_bus, + lm_set, + lm_set_gate, + lsu_acc_fault_vld, + lsu_biu_async_expt_ack, + lsu_dtu_ex2_expt_vld, + lsu_ex2_stall_final, + lsu_hpcp_inst_store, + lsu_hpcp_inst_store_gate, + lsu_idu_ex1_halt_info, + lsu_idu_ex1_halt_info_update_en, + lsu_idu_ex1_src1_update_en, + lsu_idu_ex1_src1_update_en_gate, + lsu_idu_ex1_stall, + lsu_idu_global_stall, + lsu_idu_update_addr, + lsu_idu_update_en, + lsu_idu_update_en_gate, + lsu_idu_update_offset, + lsu_iu_ex1_base_wb, + lsu_iu_ex1_src1_sel, + lsu_iu_ex2_lsi_dst_preg, + lsu_iu_ex2_lsi_rslt, + lsu_iu_ex2_lsi_rslt_vld, + lsu_pmp_addr, + lsu_pmp_write, + lsu_rtu_async_expt_vld, + lsu_rtu_async_ld_inst, + lsu_rtu_async_tval, + lsu_rtu_ex1_cmplt, + lsu_rtu_ex1_cmplt_dp, + lsu_rtu_ex1_halt_info, + lsu_rtu_ex1_inst_len, + lsu_rtu_ex1_inst_vld, + lsu_rtu_ex1_ipop_int_mask, + lsu_rtu_ex1_ipush_spec_inst, + lsu_rtu_ex1_split_inst, + lsu_rtu_ex2_bus_err, + lsu_rtu_ex2_expt_inst, + lsu_rtu_ex2_expt_vec, + lsu_rtu_ex2_tval, + lsu_sysmap_pa, + ncb_ag_async_expt_vld, + ncb_ag_async_ld_inst, + ncb_ag_async_mtval, + ncb_ag_pmp_ld_inst, + ncb_ag_pmp_mtval, + ncb_ag_stall, + ncb_xx_no_op, + pad_yy_icg_scan_en, + pmp_lsu_acc_deny, + rdl_arb_data_bank, + rdl_arb_data_din, + rdl_arb_data_idx, + rdl_arb_data_req, + rdl_arb_data_way, + rdl_arb_data_wen, + rdl_arb_dcache_sel, + rdl_arb_dirty_din, + rdl_arb_dirty_idx, + rdl_arb_dirty_req, + rdl_arb_dirty_wen, + rdl_arb_tag_din, + rdl_arb_tag_idx, + rdl_arb_tag_req, + rdl_arb_tag_wen, + rtu_lsu_async_expt_ack, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_lsu_inst_retire, + rtu_lsu_wb1_data, + rtu_lsu_wb1_lsu_vld, + rtu_lsu_wb1_preg, + rtu_xx_ex1_stall, + rtu_yy_xx_dbgon, + stb_arb_data_bank, + stb_arb_data_din, + stb_arb_data_idx, + stb_arb_data_req, + stb_arb_data_way, + stb_arb_data_wen, + stb_arb_dcache_sel, + stb_arb_dirty_din, + stb_arb_dirty_idx, + stb_arb_dirty_req, + stb_arb_dirty_wen, + sysmap_lsu_flg +); + +// &Ports; @22 +input cp0_lsu_icg_en; +input cp0_lsu_mm; +input cp0_xx_async_expt_en; +input cp0_yy_mach_mode; +input cpurst_b; +input [31:0] da_xx_fwd_data; +input da_xx_fwd_fls; +input [5 :0] da_xx_fwd_preg; +input da_xx_fwd_vld; +input dc_ag_async_expt_vld; +input dc_ag_async_ld_inst; +input [31:0] dc_ag_async_mtval; +input dc_ag_cache_stall; +input [31:0] dc_ag_dcache_addr; +input dc_ag_dcache_req; +input [1 :0] dc_ag_dcache_size; +input dc_ag_empty; +input [3 :0] dc_ag_func; +input dc_ag_pmp_ld_inst; +input [31:0] dc_ag_pmp_mtval; +input dc_ag_stall; +input dtif_ag_cmplt_ready; +input dtif_ag_fsm_idle; +input [14:0] dtif_ag_halt_info; +input dtif_ag_halt_info_up; +input dtif_ag_pipedown_mask; +input dtif_ag_stall; +input forever_cpuclk; +input [1 :0] icc_arb_data_bank; +input [63:0] icc_arb_data_din; +input [11:0] icc_arb_data_idx; +input icc_arb_data_req; +input [1 :0] icc_arb_data_way; +input [3 :0] icc_arb_data_wen; +input [2 :0] icc_arb_dirty_din; +input [9 :0] icc_arb_dirty_idx; +input icc_arb_dirty_req; +input [2 :0] icc_arb_dirty_wen; +input [22:0] icc_arb_tag_din; +input [9 :0] icc_arb_tag_idx; +input icc_arb_tag_req; +input [1 :0] icc_arb_tag_wen; +input [31:0] idu_lsu_ex1_ag_imm; +input [31:0] idu_lsu_ex1_base; +input idu_lsu_ex1_base_sel; +input idu_lsu_ex1_base_wb; +input [31:0] idu_lsu_ex1_data; +input [5 :0] idu_lsu_ex1_dest_reg; +input idu_lsu_ex1_dest_vld; +input idu_lsu_ex1_dp_sel; +input idu_lsu_ex1_fls; +input [3 :0] idu_lsu_ex1_func; +input idu_lsu_ex1_gateclk_sel; +input [14:0] idu_lsu_ex1_halt_info; +input idu_lsu_ex1_ipop_int_mask; +input idu_lsu_ex1_ipush_spec; +input idu_lsu_ex1_length; +input idu_lsu_ex1_offset_sel; +input idu_lsu_ex1_sel; +input idu_lsu_ex1_sign_extend; +input [1 :0] idu_lsu_ex1_size; +input idu_lsu_ex1_split; +input [5 :0] idu_lsu_ex1_src0_reg; +input idu_lsu_ex1_src1_depd; +input [5 :0] idu_lsu_ex1_src1_reg; +input ifu_lsu_warm_up; +input [31:0] iu_lsu_ex1_lsi_rst; +input iu_lsu_ex2_wb0_grant; +input [1 :0] lfb_arb_data_bank; +input [63:0] lfb_arb_data_din; +input [11:0] lfb_arb_data_idx; +input lfb_arb_data_req; +input [1 :0] lfb_arb_data_way; +input [3 :0] lfb_arb_data_wen; +input lfb_arb_dcache_sel; +input [2 :0] lfb_arb_dirty_din; +input [9 :0] lfb_arb_dirty_idx; +input lfb_arb_dirty_req; +input [2 :0] lfb_arb_dirty_wen; +input [22:0] lfb_arb_tag_din; +input [9 :0] lfb_arb_tag_idx; +input lfb_arb_tag_req; +input [1 :0] lfb_arb_tag_wen; +input lm_pass; +input lsu_ex2_stall_final; +input ncb_ag_async_expt_vld; +input ncb_ag_async_ld_inst; +input [31:0] ncb_ag_async_mtval; +input ncb_ag_pmp_ld_inst; +input [31:0] ncb_ag_pmp_mtval; +input ncb_ag_stall; +input ncb_xx_no_op; +input pad_yy_icg_scan_en; +input pmp_lsu_acc_deny; +input [1 :0] rdl_arb_data_bank; +input [63:0] rdl_arb_data_din; +input [11:0] rdl_arb_data_idx; +input rdl_arb_data_req; +input [1 :0] rdl_arb_data_way; +input [3 :0] rdl_arb_data_wen; +input rdl_arb_dcache_sel; +input [2 :0] rdl_arb_dirty_din; +input [9 :0] rdl_arb_dirty_idx; +input rdl_arb_dirty_req; +input [2 :0] rdl_arb_dirty_wen; +input [22:0] rdl_arb_tag_din; +input [9 :0] rdl_arb_tag_idx; +input rdl_arb_tag_req; +input [1 :0] rdl_arb_tag_wen; +input rtu_lsu_async_expt_ack; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_lsu_inst_retire; +input [31:0] rtu_lsu_wb1_data; +input rtu_lsu_wb1_lsu_vld; +input [5 :0] rtu_lsu_wb1_preg; +input rtu_xx_ex1_stall; +input rtu_yy_xx_dbgon; +input [1 :0] stb_arb_data_bank; +input [63:0] stb_arb_data_din; +input [11:0] stb_arb_data_idx; +input stb_arb_data_req; +input [1 :0] stb_arb_data_way; +input [3 :0] stb_arb_data_wen; +input stb_arb_dcache_sel; +input [2 :0] stb_arb_dirty_din; +input [9 :0] stb_arb_dirty_idx; +input stb_arb_dirty_req; +input [2 :0] stb_arb_dirty_wen; +input [4 :0] sysmap_lsu_flg; +output [31:0] ag_dc_addr; +output ag_dc_buf; +output [3 :0] ag_dc_bytes_vld; +output ag_dc_ca; +output ag_dc_dcache_grant; +output [5 :0] ag_dc_dest_reg; +output ag_dc_fls; +output [3 :0] ag_dc_func; +output ag_dc_inst_vld; +output ag_dc_inst_vld_gate; +output ag_dc_lm_pass; +output ag_dc_mach_mode; +output [1 :0] ag_dc_ori_size; +output ag_dc_pmp_expt; +output ag_dc_sign_ext; +output [1 :0] ag_dc_size; +output ag_dc_so; +output ag_dc_split; +output ag_dc_split_first; +output ag_dc_split_last; +output ag_dc_src1_depd; +output [5 :0] ag_dc_src1_reg; +output [31:0] ag_dc_st_data; +output [2 :0] ag_dc_wdata_shift; +output [31:0] ag_dtu_addr; +output ag_dtu_addr_ready; +output ag_dtu_amo_type; +output [7 :0] ag_dtu_bytes_vld; +output [31:0] ag_dtu_data; +output ag_dtu_data_chk_mask; +output ag_dtu_data_vld; +output [14:0] ag_dtu_halt_info; +output [1 :0] ag_dtu_mem_access_size; +output ag_dtu_pipe_down; +output ag_dtu_req; +output ag_dtu_req_gate; +output ag_dtu_split_last; +output ag_dtu_st_type; +output [31:0] ag_ncb_addr; +output ag_ncb_inst_vld; +output ag_ncb_inst_vld_dp; +output [5 :0] ag_ncb_src1_reg; +output [31:0] ag_ncb_st_data; +output ag_xx_inst_abort; +output ag_xx_split_done; +output arb_icc_data_grant; +output arb_rdl_grant; +output arb_stb_xx_grant; +output dcache_data_cen_way0_bank0; +output dcache_data_cen_way0_bank1; +output dcache_data_cen_way1_bank0; +output dcache_data_cen_way1_bank1; +output [63:0] dcache_data_din; +output [11:0] dcache_data_idx; +output [3 :0] dcache_data_wen; +output dcache_dirty_cen; +output [2 :0] dcache_dirty_din; +output [9 :0] dcache_dirty_idx; +output [2 :0] dcache_dirty_wen; +output dcache_tag_cen; +output [22:0] dcache_tag_din; +output [9 :0] dcache_tag_idx; +output [1 :0] dcache_tag_wen; +output lm_clr; +output [33:0] lm_lr_bus; +output [33:0] lm_sc_bus; +output lm_set; +output lm_set_gate; +output lsu_acc_fault_vld; +output lsu_biu_async_expt_ack; +output lsu_dtu_ex2_expt_vld; +output lsu_hpcp_inst_store; +output lsu_hpcp_inst_store_gate; +output [14:0] lsu_idu_ex1_halt_info; +output lsu_idu_ex1_halt_info_update_en; +output lsu_idu_ex1_src1_update_en; +output lsu_idu_ex1_src1_update_en_gate; +output lsu_idu_ex1_stall; +output lsu_idu_global_stall; +output [31:0] lsu_idu_update_addr; +output lsu_idu_update_en; +output lsu_idu_update_en_gate; +output [31:0] lsu_idu_update_offset; +output lsu_iu_ex1_base_wb; +output lsu_iu_ex1_src1_sel; +output [5 :0] lsu_iu_ex2_lsi_dst_preg; +output [31:0] lsu_iu_ex2_lsi_rslt; +output lsu_iu_ex2_lsi_rslt_vld; +output [31:0] lsu_pmp_addr; +output lsu_pmp_write; +output lsu_rtu_async_expt_vld; +output lsu_rtu_async_ld_inst; +output [31:0] lsu_rtu_async_tval; +output lsu_rtu_ex1_cmplt; +output lsu_rtu_ex1_cmplt_dp; +output [14:0] lsu_rtu_ex1_halt_info; +output lsu_rtu_ex1_inst_len; +output lsu_rtu_ex1_inst_vld; +output lsu_rtu_ex1_ipop_int_mask; +output lsu_rtu_ex1_ipush_spec_inst; +output lsu_rtu_ex1_split_inst; +output lsu_rtu_ex2_bus_err; +output lsu_rtu_ex2_expt_inst; +output [3 :0] lsu_rtu_ex2_expt_vec; +output [31:0] lsu_rtu_ex2_tval; +output [31:0] lsu_sysmap_pa; + +// &Regs; @23 +reg [2 :0] ag_addr_ff; +reg [3 :0] ag_bytes_vld; +reg ag_expt_ff; +reg [3 :0] ag_expt_vec_ff; +reg [5 :0] ag_lsi_dst_ff; +reg ag_lsi_ff; +reg [31:0] ag_lsi_rst_ff; +reg ag_misalign; +reg [31:0] ag_mtval_ff; +reg async_cur_state; +reg async_ld_inst_f; +reg [31:0] async_mtval_f; +reg async_next_state; +reg debug_mode_async_err; +reg [1 :0] pmp_cur_state; +reg [1 :0] pmp_next_state; +reg split_acc_deny; +reg split_acc_deny_ff; +reg [2 :0] split_cur_state; +reg [2 :0] split_next_state; +reg split_pmp_ld_inst; +reg [31:0] split_pmp_mtval; +reg [2 :0] split_wdata_shift; +reg target_ca_ff; + +// &Wires; @24 +wire acc_deny_vld; +wire [31:0] ag_addr; +wire [1 :0] ag_arb_data_bank; +wire [63:0] ag_arb_data_din; +wire [11:0] ag_arb_data_idx; +wire ag_arb_data_req; +wire ag_arb_data_req_dp; +wire [3 :0] ag_arb_data_wen; +wire [2 :0] ag_arb_dirty_din; +wire [9 :0] ag_arb_dirty_idx; +wire ag_arb_dirty_req; +wire ag_arb_dirty_req_dp; +wire [2 :0] ag_arb_dirty_wen; +wire [22:0] ag_arb_tag_din; +wire [9 :0] ag_arb_tag_idx; +wire ag_arb_tag_req; +wire ag_arb_tag_req_dp; +wire [1 :0] ag_arb_tag_wen; +wire ag_clk; +wire ag_clk_en; +wire [31:0] ag_dc_addr; +wire ag_dc_buf; +wire [3 :0] ag_dc_bytes_vld; +wire ag_dc_ca; +wire ag_dc_dcache_grant; +wire [5 :0] ag_dc_dest_reg; +wire ag_dc_fls; +wire [3 :0] ag_dc_func; +wire ag_dc_inst_vld; +wire ag_dc_inst_vld_gate; +wire ag_dc_lm_pass; +wire ag_dc_mach_mode; +wire ag_dc_misalign; +wire [1 :0] ag_dc_ori_size; +wire ag_dc_pmp_expt; +wire ag_dc_sign_ext; +wire [1 :0] ag_dc_size; +wire ag_dc_so; +wire ag_dc_split; +wire ag_dc_split_first; +wire ag_dc_split_last; +wire ag_dc_src1_depd; +wire [5 :0] ag_dc_src1_reg; +wire [31:0] ag_dc_st_data; +wire [2 :0] ag_dc_wdata_shift; +wire ag_dt_cancel; +wire [31:0] ag_dtu_addr; +wire ag_dtu_addr_ready; +wire ag_dtu_amo_type; +wire [7 :0] ag_dtu_bytes_vld; +wire [31:0] ag_dtu_data; +wire ag_dtu_data_chk_mask; +wire ag_dtu_data_vld; +wire [14:0] ag_dtu_halt_info; +wire [1 :0] ag_dtu_mem_access_size; +wire ag_dtu_pipe_down; +wire ag_dtu_req; +wire ag_dtu_req_gate; +wire ag_dtu_split_last; +wire ag_dtu_st_type; +wire ag_expt_clr; +wire ag_expt_mask; +wire ag_expt_save; +wire [3 :0] ag_expt_vec; +wire ag_expt_vld; +wire ag_fwd_fpu; +wire [31:0] ag_fwd_fpu_data; +wire ag_fwd_lsu; +wire ag_inst_atomic; +wire ag_inst_dca; +wire ag_inst_dca_st; +wire ag_inst_ld; +wire ag_inst_st; +wire ag_inst_vld; +wire ag_inst_vld_aft_cancel; +wire ag_inst_vld_dp; +wire ag_last_inst; +wire ag_lr_inst; +wire ag_lsi_save; +wire ag_lsi_save_dp; +wire ag_lsi_stall; +wire ag_misalign_final; +wire ag_mls; +wire [31:0] ag_mtval; +wire [31:0] ag_ncb_addr; +wire ag_ncb_inst_vld; +wire ag_ncb_inst_vld_dp; +wire [5 :0] ag_ncb_src1_reg; +wire [31:0] ag_ncb_st_data; +wire ag_sc_inst; +wire ag_self_stall; +wire ag_size_dw; +wire ag_size_half; +wire ag_size_word; +wire ag_split_req; +wire ag_split_req_gate; +wire ag_split_sel; +wire [31:0] ag_st_fwd_data; +wire ag_st_fwd_vld; +wire ag_stall; +wire ag_stall_final; +wire ag_stall_raw; +wire ag_t1_save; +wire ag_xx_inst_abort; +wire ag_xx_split_done; +wire arb_ag_grant; +wire arb_icc_data_grant; +wire arb_rdl_grant; +wire arb_stb_xx_grant; +wire async_expt_vld; +wire async_expt_vld_f; +wire async_ld_inst; +wire [31:0] async_mtval; +wire cp0_lsu_icg_en; +wire cp0_lsu_mm; +wire cp0_xx_async_expt_en; +wire cp0_yy_mach_mode; +wire cpurst_b; +wire [31:0] da_xx_fwd_data; +wire da_xx_fwd_fls; +wire [5 :0] da_xx_fwd_preg; +wire da_xx_fwd_vld; +wire dc_ag_async_expt_vld; +wire dc_ag_async_ld_inst; +wire [31:0] dc_ag_async_mtval; +wire dc_ag_cache_stall; +wire [31:0] dc_ag_dcache_addr; +wire dc_ag_dcache_req; +wire [1 :0] dc_ag_dcache_size; +wire dc_ag_empty; +wire [3 :0] dc_ag_func; +wire dc_ag_pmp_ld_inst; +wire [31:0] dc_ag_pmp_mtval; +wire dc_ag_stall; +wire dcache_data_cen_way0_bank0; +wire dcache_data_cen_way0_bank1; +wire dcache_data_cen_way1_bank0; +wire dcache_data_cen_way1_bank1; +wire [63:0] dcache_data_din; +wire [11:0] dcache_data_idx; +wire [3 :0] dcache_data_wen; +wire dcache_dirty_cen; +wire [2 :0] dcache_dirty_din; +wire [9 :0] dcache_dirty_idx; +wire [2 :0] dcache_dirty_wen; +wire [12:0] dcache_index; +wire [1 :0] dcache_size; +wire dcache_tag_cen; +wire [22:0] dcache_tag_din; +wire [9 :0] dcache_tag_idx; +wire [1 :0] dcache_tag_wen; +wire dtif_ag_cmplt_ready; +wire dtif_ag_fsm_idle; +wire [14:0] dtif_ag_halt_info; +wire dtif_ag_halt_info_up; +wire dtif_ag_pipedown_mask; +wire dtif_ag_stall; +wire ex2_expt_vld; +wire ex2_sync_acc_fault_ld; +wire [31:0] ex2_sync_expt_tval; +wire [3 :0] ex2_sync_expt_vec; +wire ex2_sync_expt_vld; +wire expt_clk; +wire expt_clk_en; +wire expt_ff_clk; +wire expt_ff_clk_en; +wire forever_cpuclk; +wire [1 :0] icc_arb_data_bank; +wire [63:0] icc_arb_data_din; +wire [11:0] icc_arb_data_idx; +wire icc_arb_data_req; +wire [1 :0] icc_arb_data_way; +wire [3 :0] icc_arb_data_wen; +wire [2 :0] icc_arb_dirty_din; +wire [9 :0] icc_arb_dirty_idx; +wire icc_arb_dirty_req; +wire [2 :0] icc_arb_dirty_wen; +wire [22:0] icc_arb_tag_din; +wire [9 :0] icc_arb_tag_idx; +wire icc_arb_tag_req; +wire [1 :0] icc_arb_tag_wen; +wire [31:0] idu_lsu_ex1_ag_imm; +wire [31:0] idu_lsu_ex1_base; +wire idu_lsu_ex1_base_sel; +wire idu_lsu_ex1_base_wb; +wire [31:0] idu_lsu_ex1_data; +wire [5 :0] idu_lsu_ex1_dest_reg; +wire idu_lsu_ex1_dp_sel; +wire idu_lsu_ex1_fls; +wire [3 :0] idu_lsu_ex1_func; +wire idu_lsu_ex1_gateclk_sel; +wire [14:0] idu_lsu_ex1_halt_info; +wire idu_lsu_ex1_ipop_int_mask; +wire idu_lsu_ex1_ipush_spec; +wire idu_lsu_ex1_length; +wire idu_lsu_ex1_offset_sel; +wire idu_lsu_ex1_sel; +wire idu_lsu_ex1_sign_extend; +wire [1 :0] idu_lsu_ex1_size; +wire idu_lsu_ex1_split; +wire [5 :0] idu_lsu_ex1_src0_reg; +wire idu_lsu_ex1_src1_depd; +wire [5 :0] idu_lsu_ex1_src1_reg; +wire ifu_lsu_warm_up; +wire [31:0] iu_lsu_ex1_lsi_rst; +wire iu_lsu_ex2_wb0_grant; +wire [1 :0] lfb_arb_data_bank; +wire [63:0] lfb_arb_data_din; +wire [11:0] lfb_arb_data_idx; +wire lfb_arb_data_req; +wire [1 :0] lfb_arb_data_way; +wire [3 :0] lfb_arb_data_wen; +wire lfb_arb_dcache_sel; +wire [2 :0] lfb_arb_dirty_din; +wire [9 :0] lfb_arb_dirty_idx; +wire lfb_arb_dirty_req; +wire [2 :0] lfb_arb_dirty_wen; +wire [22:0] lfb_arb_tag_din; +wire [9 :0] lfb_arb_tag_idx; +wire lfb_arb_tag_req; +wire [1 :0] lfb_arb_tag_wen; +wire lm_clr; +wire [33:0] lm_lr_bus; +wire lm_pass; +wire [33:0] lm_sc_bus; +wire lm_set; +wire lm_set_gate; +wire lsi_clk; +wire lsi_clk_en; +wire lsi_expt_cancel; +wire lsi_wb_grant; +wire lsu_acc_fault_vld; +wire lsu_biu_async_expt_ack; +wire lsu_dtu_ex2_expt_vld; +wire lsu_ex1_dp_sel; +wire lsu_ex1_sel; +wire lsu_ex2_stall_final; +wire lsu_hpcp_inst_store; +wire lsu_hpcp_inst_store_gate; +wire [14:0] lsu_idu_ex1_halt_info; +wire lsu_idu_ex1_halt_info_update_en; +wire lsu_idu_ex1_src1_update_en; +wire lsu_idu_ex1_src1_update_en_gate; +wire lsu_idu_ex1_stall; +wire lsu_idu_global_stall; +wire [31:0] lsu_idu_update_addr; +wire lsu_idu_update_en; +wire lsu_idu_update_en_gate; +wire [31:0] lsu_idu_update_offset; +wire lsu_iu_ex1_base_wb; +wire lsu_iu_ex1_src1_sel; +wire [5 :0] lsu_iu_ex2_lsi_dst_preg; +wire [31:0] lsu_iu_ex2_lsi_rslt; +wire lsu_iu_ex2_lsi_rslt_vld; +wire [31:0] lsu_pmp_addr; +wire lsu_pmp_write; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_async_ld_inst; +wire [31:0] lsu_rtu_async_tval; +wire lsu_rtu_ex1_cmplt; +wire lsu_rtu_ex1_cmplt_dp; +wire [14:0] lsu_rtu_ex1_halt_info; +wire lsu_rtu_ex1_inst_len; +wire lsu_rtu_ex1_inst_vld; +wire lsu_rtu_ex1_ipop_int_mask; +wire lsu_rtu_ex1_ipush_spec_inst; +wire lsu_rtu_ex1_split_inst; +wire lsu_rtu_ex2_bus_err; +wire lsu_rtu_ex2_expt_inst; +wire [3 :0] lsu_rtu_ex2_expt_vec; +wire [31:0] lsu_rtu_ex2_tval; +wire lsu_rtu_pmp_deny; +wire [31:0] lsu_sysmap_pa; +wire [3 :0] misalign_expt_vec; +wire ncb_ag_async_expt_vld; +wire ncb_ag_async_ld_inst; +wire [31:0] ncb_ag_async_mtval; +wire ncb_ag_pmp_ld_inst; +wire [31:0] ncb_ag_pmp_mtval; +wire ncb_ag_stall; +wire ncb_xx_no_op; +wire pad_yy_icg_scan_en; +wire pmp_deny_ld_inst; +wire pmp_deny_ld_inst_ex2; +wire [31:0] pmp_deny_mtval; +wire [31:0] pmp_deny_mtval_ex2; +wire pmp_lsu_acc_deny; +wire pmp_mtval_from_async; +wire pmp_mtval_from_split; +wire pmp_mtval_save_en; +wire [1 :0] rdl_arb_data_bank; +wire [63:0] rdl_arb_data_din; +wire [11:0] rdl_arb_data_idx; +wire rdl_arb_data_req; +wire [1 :0] rdl_arb_data_way; +wire [3 :0] rdl_arb_data_wen; +wire rdl_arb_dcache_sel; +wire [2 :0] rdl_arb_dirty_din; +wire [9 :0] rdl_arb_dirty_idx; +wire rdl_arb_dirty_req; +wire [2 :0] rdl_arb_dirty_wen; +wire [22:0] rdl_arb_tag_din; +wire [9 :0] rdl_arb_tag_idx; +wire rdl_arb_tag_req; +wire [1 :0] rdl_arb_tag_wen; +wire rtu_lsu_async_expt_ack; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_lsu_inst_retire; +wire rtu_sync_ack; +wire rtu_xx_ex1_stall; +wire rtu_yy_xx_dbgon; +wire [2 :0] size_onehot; +wire split_acc_clk_en; +wire split_acc_deny_vld; +wire split_busy; +wire split_clk; +wire split_clk_en; +wire split_cur_abort; +wire split_cur_busy; +wire split_cur_first; +wire split_cur_forth; +wire split_cur_secd; +wire split_cur_thrd; +wire split_err_clk; +wire split_first; +wire [1 :0] split_first_size; +wire split_first_size_half; +wire split_first_size_word; +wire split_flush; +wire [1 :0] split_forth_size; +wire split_last; +wire split_secd_last; +wire [1 :0] split_secd_size; +wire split_secd_size_byte; +wire split_secd_size_word; +wire [1 :0] split_size; +wire split_thrd_last; +wire [1 :0] split_thrd_size; +wire split_thrd_size_byte; +wire split_thrd_size_word; +wire [31:0] st_ex1_data; +wire [1 :0] stb_arb_data_bank; +wire [63:0] stb_arb_data_din; +wire [11:0] stb_arb_data_idx; +wire stb_arb_data_req; +wire [1 :0] stb_arb_data_way; +wire [3 :0] stb_arb_data_wen; +wire stb_arb_dcache_sel; +wire [2 :0] stb_arb_dirty_din; +wire [9 :0] stb_arb_dirty_idx; +wire stb_arb_dirty_req; +wire [2 :0] stb_arb_dirty_wen; +wire sync_bus_err; +wire [4 :0] sysmap_lsu_flg; +wire target_ca; +wire [2 :0] update_offset; +wire [2 :0] wdata_shift; + + +parameter DATAW = `FLEN; + +parameter S_BYTE = 2'b00; +parameter S_HALF = 2'b01; +parameter S_WORD = 2'b10; +parameter S_DWORD = 2'b11; + +// &Force("output", "ag_dc_addr"); @33 +// &Force("output", "ag_dc_func"); @34 +// &Force("output", "ag_dc_size"); @35 +// &Force("input", "idu_lsu_ex1_dest_vld"); @36 + +//============================================================================== +// address generator +//============================================================================== +assign ag_addr[31:0] = ({32{idu_lsu_ex1_base_sel}} & idu_lsu_ex1_base[31:0]) + + ({32{idu_lsu_ex1_offset_sel}} & idu_lsu_ex1_ag_imm[31:0]); + +assign lsu_iu_ex1_base_wb = lsu_ex1_dp_sel & idu_lsu_ex1_base_wb; + +//================================================ +//base update ld/st reuse src1 to +//save its original address if unalign +//================================================ +assign lsu_iu_ex1_src1_sel = !split_cur_first & idu_lsu_ex1_base_wb; +assign lsu_idu_ex1_src1_update_en = split_cur_first & ag_split_req & idu_lsu_ex1_base_wb & !ag_stall; +assign lsu_idu_ex1_src1_update_en_gate = split_cur_first & ag_split_req_gate & idu_lsu_ex1_base_wb; + +//================================================ +// address and offset update to IDU +//================================================ +assign lsu_idu_update_en = !ag_stall & + (split_cur_first & ag_split_req | + split_cur_busy & !split_last); +assign lsu_idu_update_en_gate = split_cur_first & ag_split_req_gate | + split_cur_busy & !split_last; + +assign update_offset[2:0] = (split_size[1:0] == S_BYTE) + ? 3'b1 + : ((split_size[1:0] == S_HALF) ? 3'b010 : 3'b100); + +assign lsu_idu_update_addr[31:0] = ag_addr[31:0]; +assign lsu_idu_update_offset[31:0] = {29'b0,update_offset[2:0]}; + + +assign lsu_idu_global_stall = 1'b0; +assign lsu_idu_ex1_stall = lsu_ex1_sel & ag_stall_final; + +//================================================ +// lsi borrow +//================================================ +//for timing and lsi,now lsu borrow iu wb in ex2 stage +assign lsi_clk_en = ag_inst_vld_dp + & idu_lsu_ex1_base_wb + | ifu_lsu_warm_up + | ag_lsi_ff; + +// &Instance("gated_clk_cell", "x_pa_lsu_lsi_gated_clk"); @93 +gated_clk_cell x_pa_lsu_lsi_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lsi_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (lsi_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @94 +// .external_en (1'b0), @95 +// .global_en (1'b1), @96 +// .module_en (cp0_lsu_icg_en), @97 +// .local_en (lsi_clk_en), @98 +// .clk_out (lsi_clk)); @99 + +assign ag_lsi_save = ag_inst_vld + & idu_lsu_ex1_base_wb + & !ag_stall_final; + +assign ag_lsi_save_dp = ag_inst_vld_dp + & idu_lsu_ex1_base_wb + & !ag_lsi_stall; + +assign lsi_expt_cancel = ex2_expt_vld; +assign lsi_wb_grant = iu_lsu_ex2_wb0_grant; + +always@(posedge lsi_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ag_lsi_ff <= 1'b0; + else if (ag_lsi_save) + ag_lsi_ff <= 1'b1; + else if (lsi_expt_cancel | lsi_wb_grant) + ag_lsi_ff <= 1'b0; +end + +always@(posedge lsi_clk) +begin + if (ag_lsi_save_dp | ifu_lsu_warm_up) + begin + ag_lsi_dst_ff[5:0] <= idu_lsu_ex1_src0_reg[5:0]; + ag_lsi_rst_ff[31:0] <= iu_lsu_ex1_lsi_rst[31:0]; + end +end + +//when multi lsi,may trigger ag stall +assign ag_lsi_stall = ag_lsi_ff + & !(lsi_expt_cancel | lsi_wb_grant) + & idu_lsu_ex1_base_wb; + +assign ag_self_stall = ag_lsi_stall | dtif_ag_stall; + +assign lsu_iu_ex2_lsi_rslt_vld = ag_lsi_ff & !lsu_ex2_stall_final & !lsi_expt_cancel; +assign lsu_iu_ex2_lsi_dst_preg[5:0]= ag_lsi_dst_ff[5:0]; +assign lsu_iu_ex2_lsi_rslt[31:0] = ag_lsi_rst_ff[31:0]; +//================================================ +// request information to DC +//================================================ +assign lsu_ex1_sel = idu_lsu_ex1_sel | split_cur_busy; +assign lsu_ex1_dp_sel = idu_lsu_ex1_dp_sel | split_cur_busy; + +assign ag_inst_vld = lsu_ex1_sel & !acc_deny_vld;// & !async_expt_vld_f; +assign ag_inst_vld_dp = lsu_ex1_dp_sel & !acc_deny_vld; +assign ag_inst_vld_aft_cancel = ag_inst_vld & + !ag_dt_cancel & + !ag_dc_misalign; + +assign ag_dc_addr[31:0] = ag_addr[31:0] & {32{target_ca_ff}}; +assign ag_ncb_addr[31:0] = ag_addr[31:0] & {32{!target_ca_ff}}; +assign ag_dc_func[3:0] = idu_lsu_ex1_func[3:0]; +assign ag_mls = idu_lsu_ex1_split; +assign ag_dc_fls = idu_lsu_ex1_fls; + +assign ag_dc_split = ag_split_sel; +assign ag_dc_split_last = split_last; +assign ag_dc_split_first = split_first; +assign ag_dc_size[1:0] = split_size[1:0];// : idu_lsu_ex1_size[1:0]; +assign ag_dc_ori_size[1:0] = idu_lsu_ex1_size[1:0]; +assign ag_dc_sign_ext = idu_lsu_ex1_sign_extend; +assign ag_dc_dest_reg[5:0] = idu_lsu_ex1_dest_reg[5:0]; +assign ag_dc_src1_depd = idu_lsu_ex1_src1_depd & !ag_st_fwd_vld; +assign ag_dc_src1_reg[5:0] = idu_lsu_ex1_src1_reg[5:0] & {6{target_ca_ff}}; +assign ag_ncb_src1_reg[5:0] = idu_lsu_ex1_src1_reg[5:0] & {6{!target_ca_ff}}; +assign ag_dc_st_data[DATAW-1:0] = st_ex1_data[DATAW-1:0] & {DATAW{target_ca_ff}}; +assign ag_ncb_st_data[DATAW-1:0] = st_ex1_data[DATAW-1:0] & {DATAW{!target_ca_ff}}; + +// &Force("input", "rtu_lsu_wb1_lsu_vld"); @199 +// &Force("input", "rtu_lsu_wb1_data"); @200 +// &Force("input", "rtu_lsu_wb1_preg"); @201 +// &Force("bus", "rtu_lsu_wb1_preg",5,0); @202 +// &Force("bus", "rtu_lsu_wb1_data",31,0); @203 +//assign ag_depd_ex2 = lsu_xx_ex2_data_vld & +// (idu_lsu_ex1_fls == lsu_xx_ex2_fls) & +// (idu_lsu_ex1_src1_reg[5:0] == lsu_xx_ex2_preg[5:0]); +assign ag_fwd_lsu = da_xx_fwd_vld + & (idu_lsu_ex1_fls == da_xx_fwd_fls) + & (idu_lsu_ex1_src1_reg[5:0] == da_xx_fwd_preg[5:0]); + +assign ag_fwd_fpu = rtu_lsu_fgpr_wb_vld & idu_lsu_ex1_fls & + (idu_lsu_ex1_src1_reg[4:0] == rtu_lsu_fgpr_wb_reg[4:0]); +assign ag_fwd_fpu_data[DATAW-1:0] = rtu_lsu_fgpr_wb_data[DATAW-1:0]; + +assign ag_st_fwd_vld = idu_lsu_ex1_src1_depd & (ag_fwd_lsu | ag_fwd_fpu); + +assign ag_st_fwd_data[DATAW-1:0] = ag_fwd_lsu + ? da_xx_fwd_data[DATAW-1:0] + : ag_fwd_fpu_data[DATAW-1:0]; + +assign st_ex1_data[DATAW-1:0] = ag_st_fwd_vld ? ag_st_fwd_data[DATAW-1:0] : idu_lsu_ex1_data[DATAW-1:0]; + + +assign ag_dc_wdata_shift[2:0] = wdata_shift[2:0]; + +// &CombBeg; @231 +always @( ag_addr[1:0] + or ag_dc_size[1:0]) +begin + casez({ag_dc_size[1:0],ag_addr[1:0]}) + 4'b0000: ag_bytes_vld[3:0] = 4'b0001; + 4'b0001: ag_bytes_vld[3:0] = 4'b0010; + 4'b0010: ag_bytes_vld[3:0] = 4'b0100; + 4'b0011: ag_bytes_vld[3:0] = 4'b1000; + 4'b0100: ag_bytes_vld[3:0] = 4'b0011; + 4'b0110: ag_bytes_vld[3:0] = 4'b1100; + 4'b1?00: ag_bytes_vld[3:0] = 4'b1111; + default: ag_bytes_vld[3:0] = 4'b1111; + endcase +// &CombEnd; @242 +end + +assign ag_dc_bytes_vld[3:0] = ag_bytes_vld[3:0]; + +//================================================ +// memory bkpt +//================================================ +// &Force("nonport", "ag_inst_st"); @249 +// &Force("nonport", "ag_inst_ld"); @250 +assign ag_inst_st = !ag_dc_func[3] & ag_dc_func[0]; +assign ag_inst_ld = !ag_dc_func[3] & !ag_dc_func[0]; +//req info +assign ag_dtu_req = ag_inst_vld + & !ag_expt_mask + & !ag_dc_func[3]; +assign ag_dtu_req_gate = ag_inst_vld_dp + & !ag_expt_mask + & !ag_dc_func[3]; +assign ag_dtu_addr_ready = 1'b1; +assign ag_dtu_data_vld = ag_inst_vld + & ag_inst_st + & !idu_lsu_ex1_src1_depd; +assign ag_dtu_addr[31:0] = ag_addr[31:0]; +assign ag_dtu_bytes_vld[7:0] = (ag_dc_size[1:0] == 2'b11) + ? 8'hff + : ag_addr[2] + ? {ag_bytes_vld[3:0],4'b0} + : {4'b0,ag_bytes_vld[3:0]}; +assign ag_dtu_data[31:0] = st_ex1_data[31:0]; + +assign ag_dtu_halt_info[`TDT_HINFO_WIDTH-1:0] = idu_lsu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0]; + +//lsu inst info +assign ag_dtu_st_type = ag_inst_st; +assign ag_dtu_amo_type = 1'b0; +assign ag_dtu_mem_access_size[1:0] = ag_dc_size[1:0]; +assign ag_dtu_split_last = ag_last_inst; +assign ag_dtu_data_chk_mask = (ag_dc_size[1:0] == 2'b11) + | ag_split_sel & ag_inst_ld & !split_last + | split_last & ag_inst_st; + +//cmplt and pipe info +assign ag_dtu_pipe_down = ag_inst_vld + & !split_cur_abort + & !ag_stall; + +assign lsu_idu_ex1_halt_info_update_en = dtif_ag_halt_info_up; +assign lsu_idu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0] = dtif_ag_halt_info[`TDT_HINFO_WIDTH-1:0]; + +assign ag_dt_cancel = idu_lsu_ex1_halt_info[`TDT_HINFO_CANCEL]; + +//================================================ +// to PMP +//================================================ +assign lsu_pmp_write = ag_inst_st; +assign lsu_pmp_addr[31:0] = ag_addr[31:0]; +assign ag_dc_pmp_expt = pmp_lsu_acc_deny; + +//================================================ +//sysmap +//[4:0]: Strong Order, Cacheable, Bufferable, Shareable, Security +//================================================ +// &Force("bus","sysmap_lsu_flg",4,0); @316 +// &Force("output", "ag_dc_ca"); @317 +// &Force("output", "ag_dc_so"); @318 +// &Force("output", "ag_dc_mach_mode"); @319 + +assign lsu_sysmap_pa[31:0] = ag_addr[31:0]; +assign ag_dc_ca = sysmap_lsu_flg[3]; +assign ag_dc_buf = sysmap_lsu_flg[2]; +assign ag_dc_so = sysmap_lsu_flg[4]; + +assign ag_dc_mach_mode = cp0_yy_mach_mode; + +//================================================ +// PMP DENY +//================================================ +//acc_deny_vld to indicate the instruction with pmp_deny, so it is set +//when cmplt, and clear when retired. +parameter PMP_IDLE = 2'b00; +parameter PMP_LAST = 2'b10; +parameter PMP_SPLIT = 2'b11; +parameter PMP_STALL = 2'b01; + +always@(posedge ag_clk or negedge cpurst_b) +begin + if (!cpurst_b) + pmp_cur_state[1:0] <= PMP_IDLE; + else + pmp_cur_state[1:0] <= pmp_next_state[1:0]; +end + +// &CombBeg; @347 +always @( ag_inst_vld_aft_cancel + or split_acc_deny_vld + or ag_stall_final + or pmp_lsu_acc_deny + or pmp_cur_state[1:0] + or lsu_ex2_stall_final) +begin + case(pmp_cur_state[1:0]) + PMP_IDLE: begin + if (!ag_stall_final & ag_inst_vld_aft_cancel) begin + if (split_acc_deny_vld) + pmp_next_state[1:0] = PMP_SPLIT; + else if (pmp_lsu_acc_deny) + pmp_next_state[1:0] = PMP_LAST; + else + pmp_next_state[1:0] = PMP_IDLE; + end + else + pmp_next_state[1:0] = PMP_IDLE; + end + PMP_SPLIT:begin + if (lsu_ex2_stall_final) + pmp_next_state[1:0] = PMP_STALL; + else + pmp_next_state[1:0] = PMP_IDLE; + end + PMP_LAST:begin + if (lsu_ex2_stall_final) + pmp_next_state[1:0] = PMP_STALL; + else + pmp_next_state[1:0] = PMP_IDLE; + end + PMP_STALL:begin + if (!lsu_ex2_stall_final) + pmp_next_state[1:0] = PMP_IDLE; + else + pmp_next_state[1:0] = PMP_STALL; + end + default: pmp_next_state[1:0] = PMP_IDLE; + endcase +// &CombEnd; @381 +end + +assign acc_deny_vld = pmp_cur_state[1:0] != PMP_IDLE; +assign pmp_mtval_from_split = pmp_cur_state[1:0] == PMP_SPLIT; +assign pmp_mtval_from_async = pmp_cur_state[1:0] == PMP_STALL; + +assign pmp_mtval_save_en = (pmp_cur_state[1:0] == PMP_SPLIT | + pmp_cur_state[1:0] == PMP_LAST); + +assign pmp_deny_mtval_ex2[31:0] = dc_ag_empty ? ncb_ag_pmp_mtval[31:0] : dc_ag_pmp_mtval[31:0]; +assign pmp_deny_ld_inst_ex2 = dc_ag_empty ? ncb_ag_pmp_ld_inst : dc_ag_pmp_ld_inst; + +assign pmp_deny_mtval[31:0] = pmp_mtval_from_split ? split_pmp_mtval[31:0] : pmp_deny_mtval_ex2[31:0]; +assign pmp_deny_ld_inst = pmp_mtval_from_split ? split_pmp_ld_inst : pmp_deny_ld_inst_ex2; + +assign ag_clk_en = idu_lsu_ex1_gateclk_sel | acc_deny_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_ag_gated_clk"); @397 +gated_clk_cell x_pa_lsu_ag_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ag_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ag_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @398 +// .external_en (1'b0), @399 +// .global_en (1'b1), @400 +// .module_en (cp0_lsu_icg_en ), @401 +// .local_en (ag_clk_en), @402 +// .clk_out (ag_clk)); @403 +// &Instance("gated_clk_cell", "x_pa_lsu_ag_gated_clk"); @412 +// &Connect(.clk_in (forever_cpuclk), @413 +// .external_en (1'b0), @414 +// .global_en (1'b1), @415 +// .module_en (cp0_lsu_icg_en ), @416 +// .local_en (ag_clk_en), @417 +// .clk_out (ag_clk)); @418 + +assign lsu_rtu_pmp_deny = acc_deny_vld & !async_expt_vld_f; + +//================================================ +// async exception +//================================================ +assign expt_clk_en = async_expt_vld | async_expt_vld_f | pmp_mtval_save_en | debug_mode_async_err; +// &Instance("gated_clk_cell", "x_pa_lsu_expt_gated_clk"); @428 +gated_clk_cell x_pa_lsu_expt_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (expt_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (expt_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @429 +// .external_en (1'b0), @430 +// .global_en (1'b1), @431 +// .module_en (cp0_lsu_icg_en ), @432 +// .local_en (expt_clk_en), @433 +// .clk_out (expt_clk)); @434 + +assign async_expt_vld = ncb_ag_async_expt_vld | dc_ag_async_expt_vld; +assign async_mtval[31:0] = ncb_ag_async_expt_vld ? ncb_ag_async_mtval[31:0] + : dc_ag_async_mtval[31:0]; +assign async_ld_inst = ncb_ag_async_expt_vld ? ncb_ag_async_ld_inst + : dc_ag_async_ld_inst; + +parameter ASYNC_IDLE = 1'b0; +parameter ASYNC_VLD = 1'b1; + +always@(posedge expt_clk or negedge cpurst_b) +begin + if (!cpurst_b) + async_cur_state <= ASYNC_IDLE; + else + async_cur_state <= async_next_state; +end + +// &CombBeg; @453 +always @( async_cur_state + or async_expt_vld + or rtu_sync_ack + or rtu_yy_xx_dbgon + or rtu_lsu_async_expt_ack) +begin + case (async_cur_state) + ASYNC_IDLE: begin + if (async_expt_vld & !rtu_yy_xx_dbgon) + async_next_state = ASYNC_VLD; + else + async_next_state = ASYNC_IDLE; + end + ASYNC_VLD: begin + if (rtu_lsu_async_expt_ack & !rtu_yy_xx_dbgon | rtu_sync_ack) + async_next_state = ASYNC_IDLE; + else + async_next_state = ASYNC_VLD; + end + default: async_next_state = ASYNC_IDLE; + endcase +// &CombEnd; @469 +end + +assign lsu_biu_async_expt_ack = rtu_lsu_async_expt_ack; + +assign async_expt_vld_f = async_cur_state == ASYNC_VLD; + +always@(posedge expt_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + async_mtval_f[31:0] <= 32'b0; + async_ld_inst_f <= 1'b0; + end + else if (async_expt_vld & (!async_expt_vld_f | rtu_lsu_async_expt_ack & !rtu_yy_xx_dbgon | rtu_sync_ack)) begin + async_mtval_f[31:0] <= async_mtval[31:0]; + async_ld_inst_f <= async_ld_inst; + end + else if (pmp_mtval_save_en & lsu_ex2_stall_final & !async_expt_vld_f) begin + async_mtval_f[31:0] <= pmp_deny_mtval[31:0]; + async_ld_inst_f <= pmp_deny_ld_inst; + end +end + +assign lsu_acc_fault_vld = async_expt_vld_f; + +//----------------------async expt on debug--------------------------------------- +//when dbgon, async_expt req should use seperate signal +//async_expt info in debug mode is not needed +always@(posedge expt_clk or negedge cpurst_b) +begin + if (!cpurst_b) + debug_mode_async_err <= 1'b0; + else if (rtu_yy_xx_dbgon & async_expt_vld) + debug_mode_async_err <= 1'b1; + else if (!rtu_yy_xx_dbgon | rtu_lsu_async_expt_ack & rtu_yy_xx_dbgon) + debug_mode_async_err <= 1'b0; +end + +//----------------------async expt return------------------------------- +assign lsu_rtu_async_expt_vld = async_expt_vld_f & (cp0_xx_async_expt_en | !async_ld_inst_f) & !rtu_yy_xx_dbgon + | debug_mode_async_err & rtu_yy_xx_dbgon; +assign lsu_rtu_async_tval[31:0] = (async_expt_vld_f | pmp_mtval_from_async) ? async_mtval_f[31:0] : pmp_deny_mtval[31:0]; +assign lsu_rtu_async_ld_inst = (async_expt_vld_f | pmp_mtval_from_async) ? async_ld_inst_f : pmp_deny_ld_inst; +//================================================ +// expt return +//================================================ +assign expt_ff_clk_en = ifu_lsu_warm_up | ag_expt_ff | idu_lsu_ex1_gateclk_sel | ex2_sync_expt_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_expt_ff_gated_clk"); @515 +gated_clk_cell x_pa_lsu_expt_ff_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (expt_ff_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (expt_ff_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @516 +// .external_en (1'b0), @517 +// .global_en (1'b1), @518 +// .module_en (cp0_lsu_icg_en), @519 +// .local_en (expt_ff_clk_en), @520 +// .clk_out (expt_ff_clk) ); @521 + +//for timing,now expt returns in ex2 +assign ag_expt_vld = ag_inst_vld & (ag_dc_misalign | ag_dt_cancel); +assign ag_expt_vec[3:0] = misalign_expt_vec[3:0]; +//assign ag_inst_ld = !ag_dc_func[0] & !ag_dc_func[3]; +assign ag_mtval[31:0] = ag_dt_cancel & idu_lsu_ex1_split + ? {32{1'b0}} + : ag_addr[31:0]; + +assign ag_expt_mask = ag_expt_ff & !split_cur_first; + +assign ag_expt_save = ag_expt_vld + & !ag_expt_mask; +assign ag_expt_clr = ag_inst_vld + & !ag_expt_mask + & !dtif_ag_pipedown_mask + & !ag_stall; + +assign ag_t1_save = dtif_ag_halt_info_up + & dtif_ag_halt_info[`TDT_HINFO_MATCH] + & !idu_lsu_ex1_halt_info[`TDT_HINFO_MATCH]; + +always@(posedge expt_ff_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ag_expt_ff <= 1'b0; + else if(ag_expt_save | ex2_sync_expt_vld & !ag_expt_ff) + ag_expt_ff <= 1'b1; + else if(ag_expt_clr) + ag_expt_ff <= 1'b0; +end + +always@(posedge expt_ff_clk) +begin + if (ag_expt_save | ag_t1_save | ifu_lsu_warm_up) + begin + ag_expt_vec_ff[3:0] <= ag_expt_vec[3:0]; + ag_mtval_ff[31:0] <= ag_mtval[31:0]; + end + else if (ex2_sync_expt_vld & !ag_expt_ff) + begin + ag_expt_vec_ff[3:0] <= ex2_sync_expt_vec[3:0]; + ag_mtval_ff[31:0] <= ex2_sync_expt_tval[31:0]; + end +end + +assign sync_bus_err = async_expt_vld_f & !cp0_xx_async_expt_en & async_ld_inst_f; + +assign ex2_sync_expt_vld = ag_expt_ff + | lsu_rtu_pmp_deny + | sync_bus_err; + +assign ex2_sync_acc_fault_ld = lsu_rtu_pmp_deny & !pmp_mtval_from_async + ? pmp_deny_ld_inst + : async_ld_inst_f; + +assign ex2_sync_expt_vec[3:0] = ag_expt_ff + ? ag_expt_vec_ff[3:0] + : ex2_sync_acc_fault_ld + ? 4'd5 + : 4'd7; + +//for t1,ag_tval should be default +assign ex2_sync_expt_tval[31:0] = lsu_rtu_pmp_deny & !pmp_mtval_from_async + ? pmp_deny_mtval[31:0] + : (async_expt_vld_f | lsu_rtu_pmp_deny) & !ag_expt_ff + ? async_mtval_f[31:0] + : ag_mtval_ff[31:0]; + + +assign lsu_rtu_ex2_expt_inst = ex2_sync_expt_vld; +assign lsu_rtu_ex2_bus_err = sync_bus_err; +assign lsu_rtu_ex2_expt_vec[3:0] = ex2_sync_expt_vec[3:0]; +assign lsu_rtu_ex2_tval[31:0] = ex2_sync_expt_tval[31:0]; + +assign ex2_expt_vld = ag_expt_ff | lsu_rtu_pmp_deny | async_expt_vld_f; + +assign lsu_dtu_ex2_expt_vld = ex2_expt_vld; + +//for rtu ack +assign rtu_sync_ack = rtu_lsu_inst_retire & sync_bus_err; +//================================================ +// local monitor +//================================================ +// &Force("output", "ag_dc_lm_pass"); @626 +assign ag_lr_inst = ag_dc_func[3:0] == 4'b0010; +assign ag_sc_inst = ag_dc_func[3:0] == 4'b0011; +assign ag_inst_atomic = |ag_dc_func[2:1] & !ag_dc_func[3]; +assign lm_set = ag_inst_vld_aft_cancel & ag_lr_inst & !ag_stall; +assign lm_clr = ag_inst_vld_aft_cancel & ag_inst_atomic & !ag_lr_inst & !ag_stall; +assign lm_set_gate = ag_inst_vld_dp & ag_lr_inst; +assign lm_lr_bus[33:0] = {ag_addr[31:0], ag_dc_size[1:0]} & {34{ag_lr_inst}}; +assign lm_sc_bus[33:0] = {ag_addr[31:0], ag_dc_size[1:0]} & {34{ag_sc_inst}}; +assign ag_dc_lm_pass = ag_sc_inst & lm_pass; + +//============================================================================== +// split for misalign +//============================================================================== + +//================================================ +// misalign +//================================================ +// &CombBeg; @647 +always @( idu_lsu_ex1_size[1:0] + or ag_addr[2:0]) +begin + case(idu_lsu_ex1_size[1:0]) + S_HALF : ag_misalign = ag_addr[0]; + S_WORD : ag_misalign = |ag_addr[1:0]; + S_DWORD: ag_misalign = |ag_addr[2:0]; + default : ag_misalign = 1'b0; + endcase +// &CombEnd; @654 +end + +assign ag_misalign_final = ag_misalign & ( + !cp0_lsu_mm | + ag_dc_so | + ag_dc_func[2] | ag_dc_func[1] | ag_mls); + +assign ag_dc_misalign = split_cur_first & !ag_dc_func[3] & ag_misalign_final | + !split_cur_first & ag_dc_so & !split_acc_deny; + +// &Force("nonport", "ag_mls"); @666 + +assign misalign_expt_vec[3:0] = (ag_dc_func[2] | ag_dc_func[1] | ag_dc_func[0]) ? 4'b0110 : 4'b0100; + +//================================================ +// split fsm +//================================================ +parameter S_FIRST = 3'b000; +parameter S_SECD = 3'b001; +parameter S_THIRD = 3'b010; +parameter S_FOURTH = 3'b011; +parameter S_ABORT = 3'b100; + +assign split_flush = split_cur_busy & !split_last & !ag_stall & + (pmp_lsu_acc_deny | ag_dc_so | ag_dt_cancel); + +always@(posedge split_clk or negedge cpurst_b) +begin + if (!cpurst_b) + split_cur_state[2:0] <= S_FIRST; + else if (split_flush) + split_cur_state[2:0] <= S_ABORT; + else + split_cur_state[2:0] <= split_next_state[2:0]; +end + +assign ag_split_req = ag_inst_vld & !ag_dc_func[3] & + ag_misalign & !ag_misalign_final; +assign ag_split_req_gate = ag_inst_vld_dp & !ag_dc_func[3] & + ag_misalign; + +// &CombBeg; @700 +always @( split_cur_state[2:0] + or split_secd_last + or ag_dt_cancel + or ag_split_req + or split_thrd_last + or pmp_lsu_acc_deny + or ag_stall + or dtif_ag_pipedown_mask) +begin + case(split_cur_state[2:0]) + S_FIRST: begin + if (ag_split_req & !ag_stall & !ag_dt_cancel & !dtif_ag_pipedown_mask) + split_next_state[2:0] = pmp_lsu_acc_deny ? S_ABORT : S_SECD; + else + split_next_state[2:0] = S_FIRST; + end + S_SECD: begin + if (!ag_stall) begin + if (split_secd_last) + split_next_state[2:0] = S_FIRST; + else + split_next_state[2:0] = S_THIRD; + end + else + split_next_state[2:0] = S_SECD; + end + S_THIRD:begin + if (!ag_stall) begin + if (split_thrd_last) + split_next_state[2:0] = S_FIRST; + else + split_next_state[2:0] = S_FOURTH; + end + else + split_next_state[2:0] = S_THIRD; + end + S_FOURTH:begin + if (!ag_stall) + split_next_state[2:0] = S_FIRST; + else + split_next_state[2:0] = S_FOURTH; + end + S_ABORT:begin + if (!ag_stall) + split_next_state[2:0] = S_FIRST; + else + split_next_state[2:0] = S_ABORT; + end + default:split_next_state[2:0] = S_FIRST; + endcase +// &CombEnd; @742 +end + +assign split_cur_first = split_cur_state[2:0] == S_FIRST; +assign split_cur_secd = split_cur_state[2:0] == S_SECD; +assign split_cur_thrd = split_cur_state[2:0] == S_THIRD; +assign split_cur_forth = split_cur_state[2:0] == S_FOURTH; +assign split_cur_abort = split_cur_state[2:0] == S_ABORT; + +assign split_cur_busy = split_cur_secd | + split_cur_thrd | + split_cur_forth; + +assign ag_split_sel = split_cur_first & ag_split_req | + split_cur_busy; + +assign split_last = split_cur_secd & split_secd_last | + split_cur_thrd & split_thrd_last | + split_cur_forth; +assign split_first = split_cur_first; + +assign split_secd_last = ag_size_half | + ag_size_word & !ag_addr_ff[0] | + ag_size_dw & !ag_addr_ff[1] & !ag_addr_ff[0]; +assign split_thrd_last = ag_size_word | + ag_size_dw & !ag_addr_ff[0]; + +//================================================ +// split size +//================================================ +assign ag_size_half = idu_lsu_ex1_size[1:0] == S_HALF; +assign ag_size_word = idu_lsu_ex1_size[1:0] == S_WORD; +assign ag_size_dw = idu_lsu_ex1_size[1:0] == S_DWORD; + +assign split_first_size_half = ag_size_word & !ag_addr[0] | + ag_size_dw & ag_addr[1] & !ag_addr[0]; +assign split_first_size_word = ag_size_dw & (ag_addr[2:0] == 3'b100); +assign split_first_size[1:0] = ag_misalign + ? (split_first_size_word ? S_WORD + : (split_first_size_half ? S_HALF : S_BYTE)) + : idu_lsu_ex1_size[1:0]; + +assign split_secd_size_byte = ag_size_half & ag_addr_ff[0]; +assign split_secd_size_word = ag_size_dw & (ag_addr_ff[1:0] != 2'b01); +assign split_secd_size[1:0] = split_secd_size_byte + ? S_BYTE + : split_secd_size_word ? S_WORD : S_HALF; + +assign split_thrd_size_byte = ag_size_word; +assign split_thrd_size_word = ag_size_dw & (ag_addr_ff[1:0] == 2'b01); +assign split_thrd_size[1:0] = split_thrd_size_word + ? S_WORD + : (split_thrd_size_byte ? S_BYTE : S_HALF); + +assign split_forth_size[1:0] = S_BYTE; +assign split_size[1:0] = {2{split_cur_first}} & split_first_size[1:0] | + {2{split_cur_secd}} & split_secd_size[1:0] | + {2{split_cur_thrd}} & split_thrd_size[1:0] | + {2{split_cur_forth}} & split_forth_size[1:0]; + +always@(posedge split_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ag_addr_ff[2:0] <= 3'b0; + else if (split_cur_first & ag_split_req & !ag_stall) + ag_addr_ff[2:0] <= ag_addr[2:0]; +end + +//================================================ +// data_abort to preceding load +//================================================ +//when there is a pmp_deny or misalign_extp in split and a load request has already +//been processed in DC or NCB, inst_abort should be generated to abort the request. +//================================================ +//pmp_deny or misalign is valid when in +//1.split_first: since no actual request is sent to DC, so there is no need to abort; +//2.split_busy: +// a)split_last: directly set inst_abort to flush MB FSM. +// b)!split_last: split_fsm jump to S_ABORT state, and then abort MB. +assign ag_xx_inst_abort = split_cur_abort | split_last & (pmp_lsu_acc_deny | ag_dc_so | ag_dt_cancel); + +//================================================ +// split_done +//================================================ +//to avoid abort other normal loads, implement split done +//1.in split last, there is no pmp_deny or misalign, split_done is valid + +assign ag_xx_split_done = split_last & !ag_stall & !pmp_lsu_acc_deny & !ag_dc_so & !ag_dt_cancel; + +//================================================ +// split_acc_deny +//================================================ +always@(posedge split_clk or negedge cpurst_b) +begin + if (!cpurst_b) + split_acc_deny <= 1'b0; + else if (!ag_stall & ag_split_sel & ag_inst_vld_aft_cancel & !split_last) + split_acc_deny <= pmp_lsu_acc_deny; + else if (!ag_stall_final & ag_inst_vld_aft_cancel & split_acc_deny_vld) + split_acc_deny <= 1'b0; +end + +assign split_acc_deny_vld = split_cur_abort & split_acc_deny; + +always@(posedge split_clk or negedge cpurst_b) +begin + if (!cpurst_b) + split_acc_deny_ff <= 1'b0; + else if (split_acc_deny_vld ^ split_acc_deny_ff) + split_acc_deny_ff <= split_acc_deny_vld; +end + +always@(posedge split_err_clk) +begin + if (!split_acc_deny_ff & split_acc_deny_vld | ifu_lsu_warm_up) begin + split_pmp_mtval[31:0] <= pmp_deny_mtval_ex2[31:0]; + split_pmp_ld_inst <= pmp_deny_ld_inst_ex2; + end +end + +assign split_acc_clk_en = split_acc_deny_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_split_err_gated_clk"); @877 +gated_clk_cell x_pa_lsu_split_err_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (split_err_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (split_acc_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @878 +// .external_en (1'b0), @879 +// .global_en (1'b1), @880 +// .module_en (cp0_lsu_icg_en ), @881 +// .local_en (split_acc_clk_en), @882 +// .clk_out (split_err_clk)); @883 + +//================================================ +// ICG +//================================================ +assign split_clk_en = ag_split_req_gate | !split_cur_first; + +// &Instance("gated_clk_cell", "x_pa_lsu_ag_split_gated_clk"); @893 +gated_clk_cell x_pa_lsu_ag_split_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (split_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (split_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @894 +// .external_en (1'b0), @895 +// .global_en (1'b1), @896 +// .module_en (cp0_lsu_icg_en ), @897 +// .local_en (split_clk_en), @898 +// .clk_out (split_clk)); @899 + +//================================================ +// memory data bkpt +//================================================ + + +//================================================ +// store wdata shift +//================================================ +assign size_onehot[2:0] = ag_dc_size[1:0] == S_BYTE + ? 3'b001 + : ag_dc_size[1:0] == S_HALF ? 3'b010 : 3'b100; + +always@(posedge split_clk or negedge cpurst_b) +begin + if (!cpurst_b) + split_wdata_shift[2:0] <= 3'b0; + else if (!ag_stall & ag_split_sel) + split_wdata_shift[2:0] <= wdata_shift[2:0] + size_onehot[2:0]; +end + +//assign split_wdata_shift_inc[2:0] = wdata_shift[2:0] + size_onehot[2:0]; + +assign wdata_shift[2:0] = split_cur_first + ? 3'b000 + : split_wdata_shift[2:0]; + + + +//============================================================================== +// Fast complete to RTU +//============================================================================== +// &Force("output", "lsu_rtu_ex1_cmplt"); @942 +assign target_ca = ag_dc_ca;// & cp0_lsu_dcache_en | ag_dc_func[3]; +always@(posedge ag_clk or negedge cpurst_b) +begin + if (!cpurst_b) + target_ca_ff <= 1'b0; + else if (lsu_ex1_sel) + target_ca_ff <= target_ca; +end + + +assign ag_dc_inst_vld = ag_inst_vld & target_ca & target_ca_ff & + !split_cur_abort & + !ag_dc_misalign & + !ag_dt_cancel & + !dtif_ag_pipedown_mask & + !ag_self_stall & + !lsu_ex2_stall_final & + arb_ag_grant & ncb_xx_no_op; + +assign ag_dc_inst_vld_gate = ag_inst_vld_dp & target_ca_ff & + !split_cur_abort & + arb_ag_grant & ncb_xx_no_op; + +// ag_ncb_inst_vld_dp can't be masked by misalign +assign ag_ncb_inst_vld = ag_inst_vld & !target_ca & !target_ca_ff & + !split_cur_abort & + !ag_dc_misalign & + !ag_dt_cancel & + !dtif_ag_pipedown_mask & + !ag_self_stall & + !lsu_ex2_stall_final & + dc_ag_empty; + +assign ag_ncb_inst_vld_dp = ag_inst_vld_dp & !target_ca_ff & + !split_cur_abort & + !lsu_ex2_stall_final & + dc_ag_empty; + +//assign ag_ncb_ca_req = ag_inst_vld & target_ca; + +assign ag_stall_raw = target_ca ? (dc_ag_stall | ag_self_stall | !arb_ag_grant | !target_ca_ff | !ncb_xx_no_op) + : (ncb_ag_stall | ag_self_stall | target_ca_ff | !dc_ag_empty ); +assign ag_stall = ag_stall_raw | rtu_xx_ex1_stall; + +assign split_busy = split_cur_first & ag_split_req | + split_cur_busy & !split_last; +assign ag_last_inst = !split_busy; + +assign ag_stall_final = !ag_last_inst + | !dtif_ag_fsm_idle & !dtif_ag_cmplt_ready + | ag_stall; + +//assign lsu_rtu_ex1_stall = idu_lsu_ex1_sel & ag_stall_final; +assign lsu_rtu_ex1_cmplt = lsu_ex1_sel & !ag_stall_final; +assign lsu_rtu_ex1_cmplt_dp = lsu_ex1_dp_sel; + +assign lsu_rtu_ex1_inst_vld = idu_lsu_ex1_gateclk_sel; +assign lsu_rtu_ex1_inst_len = idu_lsu_ex1_length; +assign lsu_rtu_ex1_split_inst = idu_lsu_ex1_split; +assign lsu_rtu_ex1_ipush_spec_inst = idu_lsu_ex1_ipush_spec; +assign lsu_rtu_ex1_ipop_int_mask = idu_lsu_ex1_ipop_int_mask; + +assign lsu_rtu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0] = idu_lsu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0]; + +//============================================================================== +// D-CACHE Interface +//============================================================================== +// &Force("bus","dc_ag_dcache_addr",31,0); @1020 +// &Force("bus","dc_ag_func",3,0); @1021 + +parameter D_DATA_INDEX_LEN = `D_DATA_INDEX_WIDTH; +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +assign dcache_size[1:0] + = dc_ag_dcache_req + ? dc_ag_dcache_size[1:0] + : ag_dc_size[1:0]; +assign dcache_index[12:0] + = dc_ag_dcache_req + ? dc_ag_dcache_addr[14:2] + : ag_dc_addr[14:2]; +assign ag_inst_dca_st = dc_ag_dcache_req + ? (dc_ag_func[3] | dc_ag_func[0]) + : (ag_dc_func[3] | ag_dc_func[0]); +assign ag_inst_dca = dc_ag_dcache_req + ? dc_ag_func[3] + : ag_dc_func[3]; + +assign ag_arb_tag_req = dc_ag_dcache_req | + ag_inst_vld & target_ca_ff & !dc_ag_cache_stall; +assign ag_arb_tag_req_dp = ag_arb_tag_req; +assign ag_arb_tag_wen[1:0] = 2'b0; +assign ag_arb_tag_din[22:0] = 23'b0; +assign ag_arb_tag_idx[9:0] = dcache_index[12:3]; + +assign ag_arb_dirty_req = ag_arb_tag_req & ag_inst_dca; +assign ag_arb_dirty_req_dp = ag_arb_tag_req_dp & ag_inst_dca; +assign ag_arb_dirty_wen[2:0] = 3'b0; +assign ag_arb_dirty_din[2:0] = 3'b0; +assign ag_arb_dirty_idx[9:0] = dcache_index[12:3]; + +assign ag_arb_data_req = ag_arb_tag_req & !ag_inst_dca_st; +assign ag_arb_data_req_dp = ag_arb_tag_req_dp & !ag_inst_dca_st; +assign ag_arb_data_wen[3:0] = 4'b0; +assign ag_arb_data_din[63:0] = 64'b0; +assign ag_arb_data_idx[11:0] = dcache_index[12:1]; +assign ag_arb_data_bank[1] = dcache_size[1:0] == 2'b11 | dcache_index[0]; +assign ag_arb_data_bank[0] = dcache_size[1:0] == 2'b11 | ~dcache_index[0]; +assign ag_dc_dcache_grant = arb_ag_grant; + +// &Instance("pa_lsu_arb", "x_pa_lsu_arb"); @1064 +pa_lsu_arb x_pa_lsu_arb ( + .ag_arb_data_bank (ag_arb_data_bank ), + .ag_arb_data_din (ag_arb_data_din ), + .ag_arb_data_idx (ag_arb_data_idx ), + .ag_arb_data_req (ag_arb_data_req ), + .ag_arb_data_req_dp (ag_arb_data_req_dp ), + .ag_arb_data_wen (ag_arb_data_wen ), + .ag_arb_dirty_din (ag_arb_dirty_din ), + .ag_arb_dirty_idx (ag_arb_dirty_idx ), + .ag_arb_dirty_req (ag_arb_dirty_req ), + .ag_arb_dirty_req_dp (ag_arb_dirty_req_dp ), + .ag_arb_dirty_wen (ag_arb_dirty_wen ), + .ag_arb_tag_din (ag_arb_tag_din ), + .ag_arb_tag_idx (ag_arb_tag_idx ), + .ag_arb_tag_req (ag_arb_tag_req ), + .ag_arb_tag_wen (ag_arb_tag_wen ), + .arb_ag_grant (arb_ag_grant ), + .arb_icc_data_grant (arb_icc_data_grant ), + .arb_rdl_grant (arb_rdl_grant ), + .arb_stb_xx_grant (arb_stb_xx_grant ), + .dcache_data_cen_way0_bank0 (dcache_data_cen_way0_bank0), + .dcache_data_cen_way0_bank1 (dcache_data_cen_way0_bank1), + .dcache_data_cen_way1_bank0 (dcache_data_cen_way1_bank0), + .dcache_data_cen_way1_bank1 (dcache_data_cen_way1_bank1), + .dcache_data_din (dcache_data_din ), + .dcache_data_idx (dcache_data_idx ), + .dcache_data_wen (dcache_data_wen ), + .dcache_dirty_cen (dcache_dirty_cen ), + .dcache_dirty_din (dcache_dirty_din ), + .dcache_dirty_idx (dcache_dirty_idx ), + .dcache_dirty_wen (dcache_dirty_wen ), + .dcache_tag_cen (dcache_tag_cen ), + .dcache_tag_din (dcache_tag_din ), + .dcache_tag_idx (dcache_tag_idx ), + .dcache_tag_wen (dcache_tag_wen ), + .icc_arb_data_bank (icc_arb_data_bank ), + .icc_arb_data_din (icc_arb_data_din ), + .icc_arb_data_idx (icc_arb_data_idx ), + .icc_arb_data_req (icc_arb_data_req ), + .icc_arb_data_way (icc_arb_data_way ), + .icc_arb_data_wen (icc_arb_data_wen ), + .icc_arb_dirty_din (icc_arb_dirty_din ), + .icc_arb_dirty_idx (icc_arb_dirty_idx ), + .icc_arb_dirty_req (icc_arb_dirty_req ), + .icc_arb_dirty_wen (icc_arb_dirty_wen ), + .icc_arb_tag_din (icc_arb_tag_din ), + .icc_arb_tag_idx (icc_arb_tag_idx ), + .icc_arb_tag_req (icc_arb_tag_req ), + .icc_arb_tag_wen (icc_arb_tag_wen ), + .lfb_arb_data_bank (lfb_arb_data_bank ), + .lfb_arb_data_din (lfb_arb_data_din ), + .lfb_arb_data_idx (lfb_arb_data_idx ), + .lfb_arb_data_req (lfb_arb_data_req ), + .lfb_arb_data_way (lfb_arb_data_way ), + .lfb_arb_data_wen (lfb_arb_data_wen ), + .lfb_arb_dcache_sel (lfb_arb_dcache_sel ), + .lfb_arb_dirty_din (lfb_arb_dirty_din ), + .lfb_arb_dirty_idx (lfb_arb_dirty_idx ), + .lfb_arb_dirty_req (lfb_arb_dirty_req ), + .lfb_arb_dirty_wen (lfb_arb_dirty_wen ), + .lfb_arb_tag_din (lfb_arb_tag_din ), + .lfb_arb_tag_idx (lfb_arb_tag_idx ), + .lfb_arb_tag_req (lfb_arb_tag_req ), + .lfb_arb_tag_wen (lfb_arb_tag_wen ), + .rdl_arb_data_bank (rdl_arb_data_bank ), + .rdl_arb_data_din (rdl_arb_data_din ), + .rdl_arb_data_idx (rdl_arb_data_idx ), + .rdl_arb_data_req (rdl_arb_data_req ), + .rdl_arb_data_way (rdl_arb_data_way ), + .rdl_arb_data_wen (rdl_arb_data_wen ), + .rdl_arb_dcache_sel (rdl_arb_dcache_sel ), + .rdl_arb_dirty_din (rdl_arb_dirty_din ), + .rdl_arb_dirty_idx (rdl_arb_dirty_idx ), + .rdl_arb_dirty_req (rdl_arb_dirty_req ), + .rdl_arb_dirty_wen (rdl_arb_dirty_wen ), + .rdl_arb_tag_din (rdl_arb_tag_din ), + .rdl_arb_tag_idx (rdl_arb_tag_idx ), + .rdl_arb_tag_req (rdl_arb_tag_req ), + .rdl_arb_tag_wen (rdl_arb_tag_wen ), + .stb_arb_data_bank (stb_arb_data_bank ), + .stb_arb_data_din (stb_arb_data_din ), + .stb_arb_data_idx (stb_arb_data_idx ), + .stb_arb_data_req (stb_arb_data_req ), + .stb_arb_data_way (stb_arb_data_way ), + .stb_arb_data_wen (stb_arb_data_wen ), + .stb_arb_dcache_sel (stb_arb_dcache_sel ), + .stb_arb_dirty_din (stb_arb_dirty_din ), + .stb_arb_dirty_idx (stb_arb_dirty_idx ), + .stb_arb_dirty_req (stb_arb_dirty_req ), + .stb_arb_dirty_wen (stb_arb_dirty_wen ) +); + + + +//================================================ +// PMU +//================================================ +assign lsu_hpcp_inst_store = ag_inst_vld & ag_inst_st; +assign lsu_hpcp_inst_store_gate = ag_inst_vld_dp & ag_inst_st; + +// &ModuleEnd; @1079 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_arb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_arb.v new file mode 100644 index 0000000000000000000000000000000000000000..6916053d4f55e70da941ccadd3c588eb32407d33 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_arb.v @@ -0,0 +1,518 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_arb( + ag_arb_data_bank, + ag_arb_data_din, + ag_arb_data_idx, + ag_arb_data_req, + ag_arb_data_req_dp, + ag_arb_data_wen, + ag_arb_dirty_din, + ag_arb_dirty_idx, + ag_arb_dirty_req, + ag_arb_dirty_req_dp, + ag_arb_dirty_wen, + ag_arb_tag_din, + ag_arb_tag_idx, + ag_arb_tag_req, + ag_arb_tag_wen, + arb_ag_grant, + arb_icc_data_grant, + arb_rdl_grant, + arb_stb_xx_grant, + dcache_data_cen_way0_bank0, + dcache_data_cen_way0_bank1, + dcache_data_cen_way1_bank0, + dcache_data_cen_way1_bank1, + dcache_data_din, + dcache_data_idx, + dcache_data_wen, + dcache_dirty_cen, + dcache_dirty_din, + dcache_dirty_idx, + dcache_dirty_wen, + dcache_tag_cen, + dcache_tag_din, + dcache_tag_idx, + dcache_tag_wen, + icc_arb_data_bank, + icc_arb_data_din, + icc_arb_data_idx, + icc_arb_data_req, + icc_arb_data_way, + icc_arb_data_wen, + icc_arb_dirty_din, + icc_arb_dirty_idx, + icc_arb_dirty_req, + icc_arb_dirty_wen, + icc_arb_tag_din, + icc_arb_tag_idx, + icc_arb_tag_req, + icc_arb_tag_wen, + lfb_arb_data_bank, + lfb_arb_data_din, + lfb_arb_data_idx, + lfb_arb_data_req, + lfb_arb_data_way, + lfb_arb_data_wen, + lfb_arb_dcache_sel, + lfb_arb_dirty_din, + lfb_arb_dirty_idx, + lfb_arb_dirty_req, + lfb_arb_dirty_wen, + lfb_arb_tag_din, + lfb_arb_tag_idx, + lfb_arb_tag_req, + lfb_arb_tag_wen, + rdl_arb_data_bank, + rdl_arb_data_din, + rdl_arb_data_idx, + rdl_arb_data_req, + rdl_arb_data_way, + rdl_arb_data_wen, + rdl_arb_dcache_sel, + rdl_arb_dirty_din, + rdl_arb_dirty_idx, + rdl_arb_dirty_req, + rdl_arb_dirty_wen, + rdl_arb_tag_din, + rdl_arb_tag_idx, + rdl_arb_tag_req, + rdl_arb_tag_wen, + stb_arb_data_bank, + stb_arb_data_din, + stb_arb_data_idx, + stb_arb_data_req, + stb_arb_data_way, + stb_arb_data_wen, + stb_arb_dcache_sel, + stb_arb_dirty_din, + stb_arb_dirty_idx, + stb_arb_dirty_req, + stb_arb_dirty_wen +); + +// &Ports; @21 +input [1 :0] ag_arb_data_bank; +input [63:0] ag_arb_data_din; +input [11:0] ag_arb_data_idx; +input ag_arb_data_req; +input ag_arb_data_req_dp; +input [3 :0] ag_arb_data_wen; +input [2 :0] ag_arb_dirty_din; +input [9 :0] ag_arb_dirty_idx; +input ag_arb_dirty_req; +input ag_arb_dirty_req_dp; +input [2 :0] ag_arb_dirty_wen; +input [22:0] ag_arb_tag_din; +input [9 :0] ag_arb_tag_idx; +input ag_arb_tag_req; +input [1 :0] ag_arb_tag_wen; +input [1 :0] icc_arb_data_bank; +input [63:0] icc_arb_data_din; +input [11:0] icc_arb_data_idx; +input icc_arb_data_req; +input [1 :0] icc_arb_data_way; +input [3 :0] icc_arb_data_wen; +input [2 :0] icc_arb_dirty_din; +input [9 :0] icc_arb_dirty_idx; +input icc_arb_dirty_req; +input [2 :0] icc_arb_dirty_wen; +input [22:0] icc_arb_tag_din; +input [9 :0] icc_arb_tag_idx; +input icc_arb_tag_req; +input [1 :0] icc_arb_tag_wen; +input [1 :0] lfb_arb_data_bank; +input [63:0] lfb_arb_data_din; +input [11:0] lfb_arb_data_idx; +input lfb_arb_data_req; +input [1 :0] lfb_arb_data_way; +input [3 :0] lfb_arb_data_wen; +input lfb_arb_dcache_sel; +input [2 :0] lfb_arb_dirty_din; +input [9 :0] lfb_arb_dirty_idx; +input lfb_arb_dirty_req; +input [2 :0] lfb_arb_dirty_wen; +input [22:0] lfb_arb_tag_din; +input [9 :0] lfb_arb_tag_idx; +input lfb_arb_tag_req; +input [1 :0] lfb_arb_tag_wen; +input [1 :0] rdl_arb_data_bank; +input [63:0] rdl_arb_data_din; +input [11:0] rdl_arb_data_idx; +input rdl_arb_data_req; +input [1 :0] rdl_arb_data_way; +input [3 :0] rdl_arb_data_wen; +input rdl_arb_dcache_sel; +input [2 :0] rdl_arb_dirty_din; +input [9 :0] rdl_arb_dirty_idx; +input rdl_arb_dirty_req; +input [2 :0] rdl_arb_dirty_wen; +input [22:0] rdl_arb_tag_din; +input [9 :0] rdl_arb_tag_idx; +input rdl_arb_tag_req; +input [1 :0] rdl_arb_tag_wen; +input [1 :0] stb_arb_data_bank; +input [63:0] stb_arb_data_din; +input [11:0] stb_arb_data_idx; +input stb_arb_data_req; +input [1 :0] stb_arb_data_way; +input [3 :0] stb_arb_data_wen; +input stb_arb_dcache_sel; +input [2 :0] stb_arb_dirty_din; +input [9 :0] stb_arb_dirty_idx; +input stb_arb_dirty_req; +input [2 :0] stb_arb_dirty_wen; +output arb_ag_grant; +output arb_icc_data_grant; +output arb_rdl_grant; +output arb_stb_xx_grant; +output dcache_data_cen_way0_bank0; +output dcache_data_cen_way0_bank1; +output dcache_data_cen_way1_bank0; +output dcache_data_cen_way1_bank1; +output [63:0] dcache_data_din; +output [11:0] dcache_data_idx; +output [3 :0] dcache_data_wen; +output dcache_dirty_cen; +output [2 :0] dcache_dirty_din; +output [9 :0] dcache_dirty_idx; +output [2 :0] dcache_dirty_wen; +output dcache_tag_cen; +output [22:0] dcache_tag_din; +output [9 :0] dcache_tag_idx; +output [1 :0] dcache_tag_wen; + +// &Regs; @22 +reg [1 :0] dcache_data_bank; +reg [63:0] dcache_data_din; +reg [11:0] dcache_data_idx; +reg [1 :0] dcache_data_way; +reg [3 :0] dcache_data_wen; +reg [2 :0] dcache_dirty_din; +reg [9 :0] dcache_dirty_idx; +reg [2 :0] dcache_dirty_wen; +reg [22:0] dcache_tag_din; +reg [9 :0] dcache_tag_idx; +reg [1 :0] dcache_tag_wen; + +// &Wires; @23 +wire [1 :0] ag_arb_data_bank; +wire [63:0] ag_arb_data_din; +wire [11:0] ag_arb_data_idx; +wire ag_arb_data_req; +wire ag_arb_data_req_dp; +wire [3 :0] ag_arb_data_wen; +wire [2 :0] ag_arb_dirty_din; +wire [9 :0] ag_arb_dirty_idx; +wire ag_arb_dirty_req; +wire ag_arb_dirty_req_dp; +wire [2 :0] ag_arb_dirty_wen; +wire [22:0] ag_arb_tag_din; +wire [9 :0] ag_arb_tag_idx; +wire ag_arb_tag_req; +wire [1 :0] ag_arb_tag_wen; +wire ag_data_dirty_sel; +wire arb_ag_grant; +wire arb_icc_data_grant; +wire arb_rdl_grant; +wire arb_stb_xx_grant; +wire dcache_data_cen_way0_bank0; +wire dcache_data_cen_way0_bank1; +wire dcache_data_cen_way1_bank0; +wire dcache_data_cen_way1_bank1; +wire dcache_data_req; +wire [4 :0] dcache_data_sel; +wire dcache_dirty_cen; +wire [3 :0] dcache_dirty_sel; +wire dcache_tag_cen; +wire [2 :0] dcache_tag_sel; +wire [1 :0] icc_arb_data_bank; +wire [63:0] icc_arb_data_din; +wire [11:0] icc_arb_data_idx; +wire icc_arb_data_req; +wire [1 :0] icc_arb_data_way; +wire [3 :0] icc_arb_data_wen; +wire [2 :0] icc_arb_dirty_din; +wire [9 :0] icc_arb_dirty_idx; +wire icc_arb_dirty_req; +wire [2 :0] icc_arb_dirty_wen; +wire [22:0] icc_arb_tag_din; +wire [9 :0] icc_arb_tag_idx; +wire icc_arb_tag_req; +wire [1 :0] icc_arb_tag_wen; +wire [1 :0] lfb_arb_data_bank; +wire [63:0] lfb_arb_data_din; +wire [11:0] lfb_arb_data_idx; +wire lfb_arb_data_req; +wire [1 :0] lfb_arb_data_way; +wire [3 :0] lfb_arb_data_wen; +wire lfb_arb_dcache_sel; +wire [2 :0] lfb_arb_dirty_din; +wire [9 :0] lfb_arb_dirty_idx; +wire lfb_arb_dirty_req; +wire [2 :0] lfb_arb_dirty_wen; +wire [22:0] lfb_arb_tag_din; +wire [9 :0] lfb_arb_tag_idx; +wire lfb_arb_tag_req; +wire [1 :0] lfb_arb_tag_wen; +wire [1 :0] rdl_arb_data_bank; +wire [63:0] rdl_arb_data_din; +wire [11:0] rdl_arb_data_idx; +wire rdl_arb_data_req; +wire [1 :0] rdl_arb_data_way; +wire [3 :0] rdl_arb_data_wen; +wire rdl_arb_dcache_sel; +wire [2 :0] rdl_arb_dirty_din; +wire [9 :0] rdl_arb_dirty_idx; +wire rdl_arb_dirty_req; +wire [2 :0] rdl_arb_dirty_wen; +wire [22:0] rdl_arb_tag_din; +wire [9 :0] rdl_arb_tag_idx; +wire rdl_arb_tag_req; +wire [1 :0] rdl_arb_tag_wen; +wire [1 :0] stb_arb_data_bank; +wire [63:0] stb_arb_data_din; +wire [11:0] stb_arb_data_idx; +wire stb_arb_data_req; +wire [1 :0] stb_arb_data_way; +wire [3 :0] stb_arb_data_wen; +wire stb_arb_dcache_sel; +wire [2 :0] stb_arb_dirty_din; +wire [9 :0] stb_arb_dirty_idx; +wire stb_arb_dirty_req; +wire [2 :0] stb_arb_dirty_wen; + + +parameter D_DATA_INDEX_LEN = `D_DATA_INDEX_WIDTH; +parameter D_TAG_TAG_WIDTH = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +assign ag_data_dirty_sel = ag_arb_data_req_dp | ag_arb_dirty_req_dp; + +assign arb_ag_grant = ~(lfb_arb_dcache_sel | rdl_arb_dcache_sel); +assign arb_icc_data_grant = 1'b1; +assign arb_rdl_grant = 1'b1; +assign arb_stb_xx_grant = ~(lfb_arb_dcache_sel | rdl_arb_dcache_sel | + ag_data_dirty_sel); + +assign dcache_tag_cen = ~(ag_arb_tag_req | + lfb_arb_tag_req | + rdl_arb_tag_req | + icc_arb_tag_req); + +assign dcache_tag_sel[2:0] = {rdl_arb_dcache_sel, + lfb_arb_dcache_sel, + ag_arb_tag_req}; + +// &CombBeg; @46 +always @( ag_arb_tag_din[22:0] + or rdl_arb_tag_idx[9:0] + or dcache_tag_sel[2:0] + or icc_arb_tag_wen[1:0] + or icc_arb_tag_din[22:0] + or lfb_arb_tag_din[22:0] + or ag_arb_tag_idx[9:0] + or icc_arb_tag_idx[9:0] + or lfb_arb_tag_idx[9:0] + or lfb_arb_tag_wen[1:0] + or rdl_arb_tag_wen[1:0] + or rdl_arb_tag_din[22:0] + or ag_arb_tag_wen[1:0]) +begin + casez (dcache_tag_sel[2:0]) + 3'b1?? : begin + dcache_tag_wen[1:0] = ~rdl_arb_tag_wen[1:0]; + dcache_tag_din[22:0] = rdl_arb_tag_din[22:0]; + dcache_tag_idx[9:0] = rdl_arb_tag_idx[9:0]; + end + 3'b01? : begin + dcache_tag_wen[1:0] = ~lfb_arb_tag_wen[1:0]; + dcache_tag_din[22:0] = lfb_arb_tag_din[22:0]; + dcache_tag_idx[9:0] = lfb_arb_tag_idx[9:0]; + end + 3'b001 : begin + dcache_tag_wen[1:0] = ~ag_arb_tag_wen[1:0]; + dcache_tag_din[22:0] = ag_arb_tag_din[22:0]; + dcache_tag_idx[9:0] = ag_arb_tag_idx[9:0]; + end + default: begin + dcache_tag_wen[1:0] = ~icc_arb_tag_wen[1:0]; + dcache_tag_din[22:0] = icc_arb_tag_din[22:0]; + dcache_tag_idx[9:0] = icc_arb_tag_idx[9:0]; + end + endcase +// &CombEnd; @69 +end + +assign dcache_dirty_cen = ~(lfb_arb_dirty_req | + rdl_arb_dirty_req | + stb_arb_dirty_req | + ag_arb_dirty_req | + icc_arb_dirty_req); + +assign dcache_dirty_sel[3:0] = {rdl_arb_dcache_sel, + lfb_arb_dcache_sel, + ag_arb_dirty_req, + stb_arb_dcache_sel}; + +// &CombBeg; @82 +always @( rdl_arb_dirty_wen[2:0] + or rdl_arb_dirty_din[2:0] + or icc_arb_dirty_din[2:0] + or ag_arb_dirty_wen[2:0] + or rdl_arb_dirty_idx[9:0] + or stb_arb_dirty_din[2:0] + or icc_arb_dirty_wen[2:0] + or lfb_arb_dirty_din[2:0] + or dcache_dirty_sel[3:0] + or ag_arb_dirty_din[2:0] + or lfb_arb_dirty_idx[9:0] + or ag_arb_dirty_idx[9:0] + or stb_arb_dirty_wen[2:0] + or icc_arb_dirty_idx[9:0] + or lfb_arb_dirty_wen[2:0] + or stb_arb_dirty_idx[9:0]) +begin + casez (dcache_dirty_sel[3:0]) + 4'b1???: begin + dcache_dirty_wen[2:0] = ~rdl_arb_dirty_wen[2:0]; + dcache_dirty_din[2:0] = rdl_arb_dirty_din[2:0]; + dcache_dirty_idx[9:0] = rdl_arb_dirty_idx[9:0]; + end + 4'b01??: begin + dcache_dirty_wen[2:0] = ~lfb_arb_dirty_wen[2:0]; + dcache_dirty_din[2:0] = lfb_arb_dirty_din[2:0]; + dcache_dirty_idx[9:0] = lfb_arb_dirty_idx[9:0]; + end + 4'b001?: begin + dcache_dirty_wen[2:0] = ~ag_arb_dirty_wen[2:0]; + dcache_dirty_din[2:0] = ag_arb_dirty_din[2:0]; + dcache_dirty_idx[9:0] = ag_arb_dirty_idx[9:0]; + end + 4'b0001: begin + dcache_dirty_wen[2:0] = ~stb_arb_dirty_wen[2:0]; + dcache_dirty_din[2:0] = stb_arb_dirty_din[2:0]; + dcache_dirty_idx[9:0] = stb_arb_dirty_idx[9:0]; + end + default: begin + dcache_dirty_wen[2:0] = ~icc_arb_dirty_wen[2:0]; + dcache_dirty_din[2:0] = icc_arb_dirty_din[2:0]; + dcache_dirty_idx[9:0] = icc_arb_dirty_idx[9:0]; + end + endcase +// &CombEnd; @110 +end + +assign dcache_data_req = rdl_arb_data_req | + lfb_arb_data_req | + ag_arb_data_req | + stb_arb_data_req | + icc_arb_data_req; + +assign dcache_data_cen_way0_bank0 = ~(dcache_data_req & dcache_data_way[0] & dcache_data_bank[0]); +assign dcache_data_cen_way0_bank1 = ~(dcache_data_req & dcache_data_way[0] & dcache_data_bank[1]); +assign dcache_data_cen_way1_bank0 = ~(dcache_data_req & dcache_data_way[1] & dcache_data_bank[0]); +assign dcache_data_cen_way1_bank1 = ~(dcache_data_req & dcache_data_way[1] & dcache_data_bank[1]); + +assign dcache_data_sel[4:0] = {rdl_arb_dcache_sel, + lfb_arb_dcache_sel, + ag_data_dirty_sel, + stb_arb_dcache_sel, + icc_arb_data_req}; + +// &CombBeg; @129 +always @( icc_arb_data_way[1:0] + or lfb_arb_data_idx[11:0] + or ag_arb_data_bank[1:0] + or stb_arb_data_way[1:0] + or ag_arb_data_din[63:0] + or dcache_data_sel[4:0] + or rdl_arb_data_idx[11:0] + or lfb_arb_data_bank[1:0] + or ag_arb_data_idx[11:0] + or icc_arb_data_bank[1:0] + or lfb_arb_data_wen[3:0] + or icc_arb_data_din[63:0] + or icc_arb_data_wen[3:0] + or stb_arb_data_bank[1:0] + or rdl_arb_data_way[1:0] + or rdl_arb_data_wen[3:0] + or rdl_arb_data_bank[1:0] + or ag_arb_data_wen[3:0] + or stb_arb_data_wen[3:0] + or icc_arb_data_idx[11:0] + or stb_arb_data_idx[11:0] + or rdl_arb_data_din[63:0] + or lfb_arb_data_din[63:0] + or stb_arb_data_din[63:0] + or lfb_arb_data_way[1:0]) +begin + casez (dcache_data_sel[4:0]) + 5'b1????:begin + dcache_data_way[1:0] = rdl_arb_data_way[1:0]; + dcache_data_bank[1:0] = rdl_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~rdl_arb_data_wen[3:0]; + dcache_data_din[63:0] = rdl_arb_data_din[63:0]; + dcache_data_idx[11:0] = rdl_arb_data_idx[11:0]; + end + 5'b01???:begin + dcache_data_way[1:0] = lfb_arb_data_way[1:0]; + dcache_data_bank[1:0] = lfb_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~lfb_arb_data_wen[3:0]; + dcache_data_din[63:0] = lfb_arb_data_din[63:0]; + dcache_data_idx[11:0] = lfb_arb_data_idx[11:0]; + end + 5'b001??:begin + dcache_data_way[1:0] = 2'b11; + dcache_data_bank[1:0] = ag_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~ag_arb_data_wen[3:0]; + dcache_data_din[63:0] = ag_arb_data_din[63:0]; + dcache_data_idx[11:0] = ag_arb_data_idx[11:0]; + end + 5'b0001?:begin + dcache_data_way[1:0] = stb_arb_data_way[1:0]; + dcache_data_bank[1:0] = stb_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~stb_arb_data_wen[3:0]; + dcache_data_din[63:0] = stb_arb_data_din[63:0]; + dcache_data_idx[11:0] = stb_arb_data_idx[11:0]; + end + 5'b00001:begin + dcache_data_way[1:0] = icc_arb_data_way[1:0]; + dcache_data_bank[1:0] = icc_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~icc_arb_data_wen[3:0]; + dcache_data_din[63:0] = icc_arb_data_din[63:0]; + dcache_data_idx[11:0] = icc_arb_data_idx[11:0]; + end + default:begin + dcache_data_way[1:0] = 2'b11; + dcache_data_bank[1:0] = ag_arb_data_bank[1:0]; + dcache_data_wen[3:0] = ~ag_arb_data_wen[3:0]; + dcache_data_din[63:0] = ag_arb_data_din[63:0]; + dcache_data_idx[11:0] = ag_arb_data_idx[11:0]; + end + endcase +// &CombEnd; @174 +end + + +// &ModuleEnd; @177 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dahbif.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dahbif.v new file mode 100644 index 0000000000000000000000000000000000000000..9ef4fa30708e03674bb061c9e04239754e70d121 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dahbif.v @@ -0,0 +1,576 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_dahbif( + bmu_lsu_acc_err, + bmu_lsu_grant, + bmu_lsu_rdata, + bmu_lsu_trans_cmplt, + cp0_lsu_icg_en, + cpurst_b, + dahbif_dbginfo, + dahbif_lfb_acc_err, + dahbif_lfb_cmplt, + dahbif_lfb_data, + dahbif_lfb_grant, + dahbif_ncb_acc_err, + dahbif_ncb_cmplt, + dahbif_ncb_data, + dahbif_ncb_grant, + dahbif_ncb_grant_2, + dahbif_stb_acc_ecc, + dahbif_stb_cmplt, + dahbif_stb_grant, + dahbif_stb_grant_2, + dahbif_vb_acc_ecc, + dahbif_vb_cmplt, + dahbif_vb_grant, + forever_cpuclk, + lfb_dahbif_addr, + lfb_dahbif_burst, + lfb_dahbif_lock, + lfb_dahbif_lr_inst, + lfb_dahbif_prot, + lfb_dahbif_req, + lfb_dahbif_size, + lsu_bmu_acc_deny, + lsu_bmu_addr, + lsu_bmu_burst, + lsu_bmu_lock, + lsu_bmu_lrsc, + lsu_bmu_prot, + lsu_bmu_req, + lsu_bmu_req_dp, + lsu_bmu_seq, + lsu_bmu_size, + lsu_bmu_wdata, + lsu_bmu_write, + ncb_dahbif_acc_deny, + ncb_dahbif_lock, + ncb_dahbif_lrsc, + ncb_dahbif_ncb_wb_addr, + ncb_dahbif_ncb_wb_sel, + ncb_dahbif_prot, + ncb_dahbif_req, + ncb_dahbif_req_dp, + ncb_dahbif_size, + ncb_dahbif_uc_ld_addr, + ncb_dahbif_wdata, + ncb_dahbif_write, + pad_yy_icg_scan_en, + rtu_yy_xx_async_flush, + stb_dahbif_addr, + stb_dahbif_data, + stb_dahbif_lock, + stb_dahbif_prot, + stb_dahbif_req, + stb_dahbif_sc_inst, + stb_dahbif_size, + vb_dahbif_addr, + vb_dahbif_data, + vb_dahbif_prot, + vb_dahbif_req +); + +// &Ports; @21 +input bmu_lsu_acc_err; +input bmu_lsu_grant; +input [31:0] bmu_lsu_rdata; +input bmu_lsu_trans_cmplt; +input cp0_lsu_icg_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] lfb_dahbif_addr; +input [2 :0] lfb_dahbif_burst; +input lfb_dahbif_lock; +input lfb_dahbif_lr_inst; +input [3 :0] lfb_dahbif_prot; +input lfb_dahbif_req; +input [1 :0] lfb_dahbif_size; +input ncb_dahbif_acc_deny; +input ncb_dahbif_lock; +input ncb_dahbif_lrsc; +input [31:0] ncb_dahbif_ncb_wb_addr; +input ncb_dahbif_ncb_wb_sel; +input [3 :0] ncb_dahbif_prot; +input ncb_dahbif_req; +input ncb_dahbif_req_dp; +input [1 :0] ncb_dahbif_size; +input [31:0] ncb_dahbif_uc_ld_addr; +input [31:0] ncb_dahbif_wdata; +input ncb_dahbif_write; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +input [31:0] stb_dahbif_addr; +input [31:0] stb_dahbif_data; +input stb_dahbif_lock; +input [3 :0] stb_dahbif_prot; +input stb_dahbif_req; +input stb_dahbif_sc_inst; +input [1 :0] stb_dahbif_size; +input [31:0] vb_dahbif_addr; +input [31:0] vb_dahbif_data; +input [3 :0] vb_dahbif_prot; +input vb_dahbif_req; +output [4 :0] dahbif_dbginfo; +output dahbif_lfb_acc_err; +output dahbif_lfb_cmplt; +output [31:0] dahbif_lfb_data; +output dahbif_lfb_grant; +output dahbif_ncb_acc_err; +output dahbif_ncb_cmplt; +output [31:0] dahbif_ncb_data; +output dahbif_ncb_grant; +output dahbif_ncb_grant_2; +output dahbif_stb_acc_ecc; +output dahbif_stb_cmplt; +output dahbif_stb_grant; +output dahbif_stb_grant_2; +output dahbif_vb_acc_ecc; +output dahbif_vb_cmplt; +output dahbif_vb_grant; +output lsu_bmu_acc_deny; +output [31:0] lsu_bmu_addr; +output [2 :0] lsu_bmu_burst; +output lsu_bmu_lock; +output lsu_bmu_lrsc; +output [3 :0] lsu_bmu_prot; +output lsu_bmu_req; +output lsu_bmu_req_dp; +output lsu_bmu_seq; +output [1 :0] lsu_bmu_size; +output [31:0] lsu_bmu_wdata; +output lsu_bmu_write; + +// &Regs; @22 +reg [1 :0] dahbif_cur_state; +reg [1 :0] dahbif_next_state; +reg [2 :0] data_cnt; +reg [31:0] req_addr; +reg [2 :0] req_burst; +reg [2 :0] req_burst_ff; +reg [2 :0] req_cnt; +reg req_lock; +reg req_lrsc; +reg [2 :0] req_offset_ff; +reg [3 :0] req_prot; +reg [3 :0] req_sel; +reg [1 :0] req_size; +reg req_write; + +// &Wires; @23 +wire bmu_lsu_acc_err; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire ca_req_vld; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire dahbif_clk_en; +wire dahbif_cur_busy; +wire [4 :0] dahbif_dbginfo; +wire dahbif_fsm_clk; +wire dahbif_lfb_acc_err; +wire dahbif_lfb_cmplt; +wire [31:0] dahbif_lfb_data; +wire dahbif_lfb_grant; +wire dahbif_ncb_acc_err; +wire dahbif_ncb_cmplt; +wire [31:0] dahbif_ncb_data; +wire dahbif_ncb_grant; +wire dahbif_ncb_grant_2; +wire dahbif_stb_acc_ecc; +wire dahbif_stb_cmplt; +wire dahbif_stb_grant; +wire dahbif_stb_grant_2; +wire dahbif_vb_acc_ecc; +wire dahbif_vb_cmplt; +wire dahbif_vb_grant; +wire [2 :0] data_cnt_inc; +wire data_cnt_inc_en; +wire data_cnt_start; +wire data_last; +wire forever_cpuclk; +wire [31:0] lfb_dahbif_addr; +wire [2 :0] lfb_dahbif_burst; +wire lfb_dahbif_lock; +wire lfb_dahbif_lr_inst; +wire [3 :0] lfb_dahbif_prot; +wire lfb_dahbif_req; +wire [1 :0] lfb_dahbif_size; +wire lfb_req; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire ncb_dahbif_acc_deny; +wire ncb_dahbif_lock; +wire ncb_dahbif_lrsc; +wire [31:0] ncb_dahbif_ncb_wb_addr; +wire ncb_dahbif_ncb_wb_sel; +wire [3 :0] ncb_dahbif_prot; +wire ncb_dahbif_req; +wire ncb_dahbif_req_dp; +wire [1 :0] ncb_dahbif_size; +wire [31:0] ncb_dahbif_uc_ld_addr; +wire [31:0] ncb_dahbif_wdata; +wire ncb_dahbif_write; +wire ncb_req; +wire pad_yy_icg_scan_en; +wire req_acc_deny; +wire [31:0] req_addr_post; +wire req_burst_vld; +wire req_burst_vld_ff; +wire req_cnt_init; +wire req_create_en; +wire req_done; +wire req_first; +wire req_idle; +wire req_idle_dp; +wire req_inc2_ff; +wire [2 :0] req_offset; +wire [3 :0] req_sel_final; +wire req_seq; +wire [3 :0] req_valid; +wire [3 :0] req_valid_dp; +wire req_vld; +wire req_vld_dp; +wire [31:0] req_wdata; +wire rtu_yy_xx_async_flush; +wire [31:0] stb_dahbif_addr; +wire [31:0] stb_dahbif_data; +wire stb_dahbif_lock; +wire [3 :0] stb_dahbif_prot; +wire stb_dahbif_req; +wire stb_dahbif_sc_inst; +wire [1 :0] stb_dahbif_size; +wire stb_req; +wire [31:0] vb_dahbif_addr; +wire [31:0] vb_dahbif_data; +wire [3 :0] vb_dahbif_prot; +wire vb_dahbif_req; +wire vb_req; + + +parameter REQ = 2'b00; +parameter WFG = 2'b01; +parameter WFC = 2'b10; + +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dahbif_cur_state[1:0] <= REQ; + else if (rtu_yy_xx_async_flush) + dahbif_cur_state[1:0] <= REQ; + else + dahbif_cur_state[1:0] <= dahbif_next_state[1:0]; +end + +// &CombBeg; @39 +always @( req_vld + or dahbif_cur_state[1:0] + or bmu_lsu_grant + or bmu_lsu_acc_err + or bmu_lsu_trans_cmplt + or data_last) +begin + case(dahbif_cur_state[1:0]) + REQ: begin + if (req_vld) + dahbif_next_state[1:0] = bmu_lsu_grant ? WFC : WFG; + else + dahbif_next_state[1:0] = REQ; + end + WFG: begin + if (bmu_lsu_grant) + dahbif_next_state[1:0] = WFC; + else + dahbif_next_state[1:0] = WFG; + end + WFC: begin + if (bmu_lsu_trans_cmplt & data_last & !bmu_lsu_acc_err) + dahbif_next_state[1:0] = req_vld ? (bmu_lsu_grant ? WFC : WFG) + : REQ; + else if (bmu_lsu_trans_cmplt & bmu_lsu_acc_err) + dahbif_next_state[1:0] = REQ; + else + dahbif_next_state[1:0] = WFC; + end + default: dahbif_next_state[1:0] = REQ; + endcase +// &CombEnd; @64 +end + +assign dahbif_cur_busy = dahbif_cur_state[1:0] != REQ; + +assign req_vld = vb_dahbif_req | lfb_dahbif_req | stb_dahbif_req | ncb_dahbif_req; +assign req_vld_dp = vb_dahbif_req | lfb_dahbif_req | stb_dahbif_req | ncb_dahbif_req_dp; + +//burst request: +//for condition1:cmplt but no next request grant, data_last is valid but req_done not valid +//for condition2:grant two requests but no cmplt, req_done is valid but data_last not valid. +// fsm should wait last data cmplt can recevie new request. +assign req_idle_dp = (dahbif_cur_state[1:0] == REQ) | + (dahbif_cur_state[1:0] == WFC) & req_done & data_last; + +assign req_idle = (dahbif_cur_state[1:0] == REQ) | + (dahbif_cur_state[1:0] == WFC) & bmu_lsu_trans_cmplt & req_done & data_last; + +assign req_create_en = req_vld & req_idle; + +assign req_first = req_idle | (dahbif_cur_state[1:0] == WFG); + +//------------------------------------------------ +// req_sel +//------------------------------------------------ +assign lfb_req = lfb_dahbif_req; +assign vb_req = !lfb_dahbif_req & vb_dahbif_req; +assign stb_req = !lfb_dahbif_req & !vb_dahbif_req & stb_dahbif_req; +assign ncb_req = ncb_dahbif_req; + +assign req_valid[3:0] = {ncb_req,stb_req,lfb_req,vb_req}; + +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_sel[3:0] <= 4'b0; + else if (req_create_en) + req_sel[3:0] <= req_valid[3:0]; +end + +//------------------------------------------------ +// req_burst_ff +//------------------------------------------------ +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_burst_ff[2:0] <= 3'b000; + else if (req_create_en) + req_burst_ff[2:0] <= req_burst[2:0]; +end + +assign req_burst_vld_ff = req_burst_ff[2:0] != 3'b000; +assign req_inc2_ff = req_burst_ff[2:0] == 3'b001; + +//------------------------------------------------ +//req_cnt and req_done +//------------------------------------------------ +assign req_cnt_init = req_create_en & req_burst_vld; + +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_cnt[2:0] <= 3'b000; + else if (req_cnt_init) + req_cnt[2:0] <= bmu_lsu_grant ? 3'b001 : 3'b000; + else if (dahbif_cur_busy & bmu_lsu_grant & req_burst_vld_ff) + req_cnt[2:0] <= req_cnt[2:0] + 3'b001; + else if (bmu_lsu_acc_err) + req_cnt[2:0] <= 3'b000; +end + +assign req_done = !req_burst_vld_ff | (req_cnt[2:0] == 3'b000) | req_inc2_ff & (req_cnt[2:0] == 3'b010); +assign req_seq = req_burst_vld_ff & (req_cnt[2:0] != 3'b000); + +//------------------------------------------------ +// data_cnt and data_last +//------------------------------------------------ +assign data_cnt_start = req_create_en; +assign data_cnt_inc_en = (dahbif_cur_state[1:0] == WFC) & bmu_lsu_trans_cmplt; + +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + data_cnt[2:0] <= 3'b000; + else if (data_cnt_start) + data_cnt[2:0] <= req_burst_vld ? 3'b000 : 3'b111; + else if (data_cnt_inc_en) + data_cnt[2:0] <= data_cnt_inc[2:0]; +end + +assign data_cnt_inc[2:0] = data_cnt[2:0] + 3'b001; +assign data_last = req_inc2_ff ? (data_cnt[2:0] == 3'b001) : (data_cnt[2:0] == 3'b111); + +//------------------------------------------------ +//req_offset +//------------------------------------------------ +always@(posedge dahbif_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_offset_ff[2:0] <= 3'b000; + else if (req_create_en) + req_offset_ff[2:0] <= bmu_lsu_grant ? (req_addr_post[4:2] + 3'b001) : req_addr_post[4:2]; + else if (dahbif_cur_busy & bmu_lsu_grant & req_burst_vld_ff) + req_offset_ff[2:0] <= req_offset_ff[2:0] + 3'b001; +end + +assign req_offset[2:0] = req_idle_dp + ? req_addr_post[4:2] + : req_offset_ff[2:0]; + +//------------------------------------------------ +// requset select +//------------------------------------------------ +assign req_valid_dp[3:0] = {ncb_dahbif_req_dp,stb_req,lfb_req,vb_req}; +assign req_sel_final[3:0] = req_idle_dp ? req_valid_dp[3:0] : req_sel[3:0]; + +// &CombBeg; @179 +always @( lfb_dahbif_addr[31:0] + or stb_dahbif_prot[3:0] + or stb_dahbif_addr[31:0] + or lfb_dahbif_lock + or ncb_dahbif_lock + or req_sel_final[2:0] + or ncb_dahbif_lrsc + or stb_dahbif_lock + or ncb_dahbif_size[1:0] + or lfb_dahbif_burst[2:0] + or ncb_dahbif_prot[3:0] + or stb_dahbif_sc_inst + or ncb_dahbif_ncb_wb_addr[31:0] + or lfb_dahbif_prot[3:0] + or lfb_dahbif_lr_inst + or ncb_dahbif_write + or stb_dahbif_size[1:0] + or lfb_dahbif_size[1:0] + or vb_dahbif_addr[31:0] + or vb_dahbif_prot[3:0]) +begin + case(req_sel_final[2:0]) + 3'b001: begin + req_addr[31:0] = vb_dahbif_addr[31:0]; + req_prot[3:0] = vb_dahbif_prot[3:0]; + req_size[1:0] = 2'b10; + req_write = 1'b1; + req_burst[2:0] = 3'b101; //INCR8 + req_lock = 1'b0; + req_lrsc = 1'b0; + end + 3'b010: begin + req_addr[31:0] = lfb_dahbif_addr[31:0]; + req_prot[3:0] = lfb_dahbif_prot[3:0]; + req_size[1:0] = lfb_dahbif_size[1:0]; + req_write = 1'b0; + req_burst[2:0] = lfb_dahbif_burst[2:0]; + req_lock = lfb_dahbif_lock; + req_lrsc = lfb_dahbif_lr_inst; + end + 3'b100: begin + req_addr[31:0] = stb_dahbif_addr[31:0]; + req_prot[3:0] = stb_dahbif_prot[3:0]; + req_size[1:0] = stb_dahbif_size[1:0]; + req_write = 1'b1; + req_burst[2:0] = (stb_dahbif_size[1:0] == 2'b11) ? 3'b001 : 3'b000; + req_lock = stb_dahbif_lock; + req_lrsc = stb_dahbif_sc_inst; + end + default:begin + req_addr[31:0] = ncb_dahbif_ncb_wb_addr[31:0]; + req_prot[3:0] = ncb_dahbif_prot[3:0]; + req_size[1:0] = ncb_dahbif_size[1:0]; + req_write = ncb_dahbif_write; + req_burst[2:0] = (ncb_dahbif_size[1:0] == 2'b11) ? 3'b001 : 3'b000; + req_lock = ncb_dahbif_lock; + req_lrsc = ncb_dahbif_lrsc; + end + endcase +// &CombEnd; @218 +end + +assign req_burst_vld = req_burst[2:0] != 3'b000; + +assign ca_req_vld = |req_sel_final[2:0]; +assign req_addr_post[31:0] = ca_req_vld | ncb_dahbif_ncb_wb_sel + ? req_addr[31:0] + : ncb_dahbif_uc_ld_addr[31:0]; +assign req_acc_deny = !ca_req_vld & ncb_dahbif_acc_deny; + +assign req_wdata[31:0] = {32{req_sel[0]}} & vb_dahbif_data[31:0] | + {32{req_sel[2]}} & stb_dahbif_data[31:0] | + {32{req_sel[3]}} & ncb_dahbif_wdata[31:0]; + +assign lsu_bmu_req = req_idle_dp & req_vld | + (dahbif_cur_state[1:0] == WFG) | + (dahbif_cur_state[1:0] ==WFC) & !req_done; +assign lsu_bmu_req_dp = req_idle_dp & req_vld_dp | + (dahbif_cur_state[1:0] == WFG) | + (dahbif_cur_state[1:0] ==WFC) & !req_done; +assign lsu_bmu_write = req_write; +assign lsu_bmu_addr[31:0] = {req_addr_post[31:5], req_offset[2:0], req_addr_post[1:0]} ; +assign lsu_bmu_prot[3:0] = req_prot[3:0]; +assign lsu_bmu_size[1:0] = (req_size[1:0] == 2'b11) ? 2'b10 : req_size[1:0]; +assign lsu_bmu_wdata[31:0]= req_wdata[31:0]; +assign lsu_bmu_acc_deny = req_acc_deny; +assign lsu_bmu_lock = req_lock; +assign lsu_bmu_lrsc = req_lrsc; +assign lsu_bmu_seq = (dahbif_cur_state[1:0] ==WFC) & req_seq; +assign lsu_bmu_burst[2:0] = req_burst[2] ? req_burst[2:0] : 3'b000; + +assign dahbif_ncb_grant = req_sel_final[3] & req_first & bmu_lsu_grant; +assign dahbif_ncb_grant_2 = req_sel_final[3] & !req_first & bmu_lsu_grant; +assign dahbif_ncb_cmplt = req_sel[3] & bmu_lsu_trans_cmplt; +assign dahbif_ncb_acc_err = req_sel[3] & bmu_lsu_acc_err; +assign dahbif_ncb_data[31:0] = bmu_lsu_rdata[31:0]; + +assign dahbif_stb_grant = req_sel_final[2] & req_first & bmu_lsu_grant; +assign dahbif_stb_grant_2 = req_sel_final[2] & !req_first & bmu_lsu_grant; +assign dahbif_stb_cmplt = req_sel[2] & bmu_lsu_trans_cmplt; +assign dahbif_stb_acc_ecc = req_sel[2] & bmu_lsu_acc_err; + +assign dahbif_lfb_grant = req_sel_final[1] & req_first & bmu_lsu_grant; +assign dahbif_lfb_cmplt = req_sel[1] & bmu_lsu_trans_cmplt; +assign dahbif_lfb_acc_err = req_sel[1] & bmu_lsu_acc_err; +assign dahbif_lfb_data[31:0] = bmu_lsu_rdata[31:0]; + +assign dahbif_vb_grant = req_sel_final[0] & req_first & bmu_lsu_grant; +assign dahbif_vb_cmplt = req_sel[0] & bmu_lsu_trans_cmplt; +assign dahbif_vb_acc_ecc = req_sel[0] & bmu_lsu_acc_err; + +assign dahbif_clk_en = req_vld_dp | ~(dahbif_cur_state[1:0] == REQ); +// &Instance("gated_clk_cell", "x_pa_lsu_dahbif_gated_clk"); @270 +gated_clk_cell x_pa_lsu_dahbif_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dahbif_fsm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dahbif_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @271 +// .external_en (1'b0), @272 +// .global_en (1'b1), @273 +// .module_en (cp0_lsu_icg_en ), @274 +// .local_en (dahbif_clk_en), @275 +// .clk_out (dahbif_fsm_clk)); @276 + +assign dahbif_dbginfo[4:0] = {req_cnt[2:0],dahbif_cur_state[1:0]}; + +// &ModuleEnd; @280 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dc.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dc.v new file mode 100644 index 0000000000000000000000000000000000000000..2cbf02b979ed4b4b4e2a609f2fd65981f0708c87 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dc.v @@ -0,0 +1,1090 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_dc( + ag_dc_addr, + ag_dc_buf, + ag_dc_bytes_vld, + ag_dc_ca, + ag_dc_dcache_grant, + ag_dc_dest_reg, + ag_dc_fls, + ag_dc_func, + ag_dc_inst_vld, + ag_dc_inst_vld_gate, + ag_dc_lm_pass, + ag_dc_mach_mode, + ag_dc_ori_size, + ag_dc_pmp_expt, + ag_dc_sign_ext, + ag_dc_size, + ag_dc_split, + ag_dc_split_first, + ag_dc_split_last, + ag_dc_src1_depd, + ag_dc_src1_reg, + ag_dc_st_data, + ag_dc_wdata_shift, + cp0_lsu_dcache_en, + cp0_lsu_dcache_wa, + cp0_lsu_icg_en, + cpurst_b, + da_xx_fwd_data, + da_xx_fwd_fls, + da_xx_fwd_preg, + da_xx_fwd_vld, + dc_ag_async_expt_vld, + dc_ag_async_ld_inst, + dc_ag_async_mtval, + dc_ag_cache_stall, + dc_ag_dcache_addr, + dc_ag_dcache_req, + dc_ag_dcache_size, + dc_ag_func, + dc_ag_pmp_ld_inst, + dc_ag_pmp_mtval, + dc_ag_stall, + dc_dbginfo, + dc_icc_way0_data, + dc_icc_way0_dirty, + dc_icc_way0_tag, + dc_icc_way1_data, + dc_icc_way1_dirty, + dc_icc_way1_tag, + dc_idle, + dc_lfb_addr, + dc_lfb_buf, + dc_lfb_ca, + dc_lfb_ca_raw, + dc_lfb_create_en, + dc_lfb_create_en_gate, + dc_lfb_inst_ld, + dc_lfb_lock_trans, + dc_lfb_lr_inst, + dc_lfb_mach_mode, + dc_lfb_size, + dc_rdl_fifo, + dc_rdl_way0_data, + dc_rdl_way0_dirty, + dc_rdl_way0_tag, + dc_rdl_way0_vld, + dc_rdl_way1_data, + dc_rdl_way1_dirty, + dc_rdl_way1_tag, + dc_rdl_way1_vld, + dc_stb_addr, + dc_stb_attr, + dc_stb_bytes_vld, + dc_stb_cache_hit, + dc_stb_create_en, + dc_stb_create_en_gate, + dc_stb_data, + dc_stb_dcache_dirty, + dc_stb_dcache_inst, + dc_stb_dcache_type, + dc_stb_dcache_way, + dc_stb_fls, + dc_stb_lock_trans, + dc_stb_sc_inst, + dc_stb_shift, + dc_stb_size, + dc_stb_split_first, + dc_stb_src1_depd, + dc_stb_src1_reg, + dc_stb_wait_lfb, + dc_vb_st_amold, + dc_xx_addr, + dc_xx_bytes_vld, + dcache_data_dout_way0, + dcache_data_dout_way1, + dcache_dirty_dout, + dcache_tag_dout, + forever_cpuclk, + ifu_lsu_warm_up, + lfb_dc_async_expt, + lfb_dc_busy, + lfb_dc_hit_idx, + lfb_dc_ld_cmplt, + lfb_dc_ld_data, + lfb_dc_ld_data_vld, + lfb_dc_pop_en, + lsu_hpcp_cache_read_access, + lsu_hpcp_cache_read_access_gate, + lsu_hpcp_cache_read_miss, + lsu_hpcp_cache_read_miss_gate, + lsu_hpcp_cache_write_access, + lsu_hpcp_cache_write_access_gate, + lsu_hpcp_cache_write_miss, + lsu_hpcp_cache_write_miss_gate, + lsu_mb_ex2_ca_addr_2, + lsu_mb_ex2_ca_bytes_vld, + lsu_mb_ex2_ca_data, + lsu_mb_ex2_ca_data_vld, + lsu_mb_ex2_ca_data_vld_gate, + lsu_mb_ex2_ca_dest_reg, + lsu_mb_ex2_ca_fld, + lsu_mb_ex2_ca_fls, + lsu_mb_ex2_ca_lock, + lsu_mb_ex2_ca_sc_data_vld, + lsu_mb_ex2_ca_sign_ext, + lsu_mb_ex2_ca_size, + lsu_mb_ex2_ca_split, + lsu_mb_ex2_ca_split_last, + lsu_mb_ex2_ca_stall, + lsu_top_dc_vld, + lsu_xx_ex2_ca_flush, + pad_yy_icg_scan_en, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_yy_xx_async_flush, + stb_dc_async_expt, + stb_dc_busy, + stb_dc_full, + stb_dc_hit_addr, + stb_dc_hit_dca, + stb_dc_hit_idx, + stb_dc_ld_data, + stb_dc_ld_fwd_vld, + stb_dc_mtval, + stb_dc_multi_or_part_hit, + stb_dc_pop_en, + vb_dc_hit_dirty, + vb_dc_ld_data, + vb_dc_ld_fwd_vld, + vb_dc_pop_en +); + +// &Ports; @21 +input [31:0] ag_dc_addr; +input ag_dc_buf; +input [3 :0] ag_dc_bytes_vld; +input ag_dc_ca; +input ag_dc_dcache_grant; +input [5 :0] ag_dc_dest_reg; +input ag_dc_fls; +input [3 :0] ag_dc_func; +input ag_dc_inst_vld; +input ag_dc_inst_vld_gate; +input ag_dc_lm_pass; +input ag_dc_mach_mode; +input [1 :0] ag_dc_ori_size; +input ag_dc_pmp_expt; +input ag_dc_sign_ext; +input [1 :0] ag_dc_size; +input ag_dc_split; +input ag_dc_split_first; +input ag_dc_split_last; +input ag_dc_src1_depd; +input [5 :0] ag_dc_src1_reg; +input [31:0] ag_dc_st_data; +input [2 :0] ag_dc_wdata_shift; +input cp0_lsu_dcache_en; +input cp0_lsu_dcache_wa; +input cp0_lsu_icg_en; +input cpurst_b; +input [31:0] da_xx_fwd_data; +input da_xx_fwd_fls; +input [5 :0] da_xx_fwd_preg; +input da_xx_fwd_vld; +input [63:0] dcache_data_dout_way0; +input [63:0] dcache_data_dout_way1; +input [2 :0] dcache_dirty_dout; +input [45:0] dcache_tag_dout; +input forever_cpuclk; +input ifu_lsu_warm_up; +input lfb_dc_async_expt; +input lfb_dc_busy; +input lfb_dc_hit_idx; +input lfb_dc_ld_cmplt; +input [31:0] lfb_dc_ld_data; +input lfb_dc_ld_data_vld; +input lfb_dc_pop_en; +input pad_yy_icg_scan_en; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_yy_xx_async_flush; +input stb_dc_async_expt; +input stb_dc_busy; +input stb_dc_full; +input stb_dc_hit_addr; +input stb_dc_hit_dca; +input stb_dc_hit_idx; +input [31:0] stb_dc_ld_data; +input stb_dc_ld_fwd_vld; +input [31:0] stb_dc_mtval; +input stb_dc_multi_or_part_hit; +input stb_dc_pop_en; +input vb_dc_hit_dirty; +input [31:0] vb_dc_ld_data; +input vb_dc_ld_fwd_vld; +input vb_dc_pop_en; +output dc_ag_async_expt_vld; +output dc_ag_async_ld_inst; +output [31:0] dc_ag_async_mtval; +output dc_ag_cache_stall; +output [31:0] dc_ag_dcache_addr; +output dc_ag_dcache_req; +output [1 :0] dc_ag_dcache_size; +output [3 :0] dc_ag_func; +output dc_ag_pmp_ld_inst; +output [31:0] dc_ag_pmp_mtval; +output dc_ag_stall; +output [14:0] dc_dbginfo; +output [63:0] dc_icc_way0_data; +output dc_icc_way0_dirty; +output [21:0] dc_icc_way0_tag; +output [63:0] dc_icc_way1_data; +output dc_icc_way1_dirty; +output [21:0] dc_icc_way1_tag; +output dc_idle; +output [31:0] dc_lfb_addr; +output dc_lfb_buf; +output dc_lfb_ca; +output dc_lfb_ca_raw; +output dc_lfb_create_en; +output dc_lfb_create_en_gate; +output dc_lfb_inst_ld; +output dc_lfb_lock_trans; +output dc_lfb_lr_inst; +output dc_lfb_mach_mode; +output [1 :0] dc_lfb_size; +output dc_rdl_fifo; +output [63:0] dc_rdl_way0_data; +output dc_rdl_way0_dirty; +output [21:0] dc_rdl_way0_tag; +output dc_rdl_way0_vld; +output [63:0] dc_rdl_way1_data; +output dc_rdl_way1_dirty; +output [21:0] dc_rdl_way1_tag; +output dc_rdl_way1_vld; +output [31:0] dc_stb_addr; +output [2 :0] dc_stb_attr; +output [3 :0] dc_stb_bytes_vld; +output dc_stb_cache_hit; +output dc_stb_create_en; +output dc_stb_create_en_gate; +output [31:0] dc_stb_data; +output dc_stb_dcache_dirty; +output dc_stb_dcache_inst; +output [1 :0] dc_stb_dcache_type; +output dc_stb_dcache_way; +output dc_stb_fls; +output dc_stb_lock_trans; +output dc_stb_sc_inst; +output [2 :0] dc_stb_shift; +output [1 :0] dc_stb_size; +output dc_stb_split_first; +output dc_stb_src1_depd; +output [4 :0] dc_stb_src1_reg; +output dc_stb_wait_lfb; +output dc_vb_st_amold; +output [31:0] dc_xx_addr; +output [7 :0] dc_xx_bytes_vld; +output lsu_hpcp_cache_read_access; +output lsu_hpcp_cache_read_access_gate; +output lsu_hpcp_cache_read_miss; +output lsu_hpcp_cache_read_miss_gate; +output lsu_hpcp_cache_write_access; +output lsu_hpcp_cache_write_access_gate; +output lsu_hpcp_cache_write_miss; +output lsu_hpcp_cache_write_miss_gate; +output lsu_mb_ex2_ca_addr_2; +output [3 :0] lsu_mb_ex2_ca_bytes_vld; +output [31:0] lsu_mb_ex2_ca_data; +output lsu_mb_ex2_ca_data_vld; +output lsu_mb_ex2_ca_data_vld_gate; +output [5 :0] lsu_mb_ex2_ca_dest_reg; +output lsu_mb_ex2_ca_fld; +output lsu_mb_ex2_ca_fls; +output lsu_mb_ex2_ca_lock; +output lsu_mb_ex2_ca_sc_data_vld; +output lsu_mb_ex2_ca_sign_ext; +output [1 :0] lsu_mb_ex2_ca_size; +output lsu_mb_ex2_ca_split; +output lsu_mb_ex2_ca_split_last; +output lsu_mb_ex2_ca_stall; +output lsu_top_dc_vld; +output lsu_xx_ex2_ca_flush; + +// &Regs; @22 +reg [31:0] dc_addr; +reg dc_buf; +reg [3 :0] dc_bytes_vld; +reg dc_ca; +reg [2 :0] dc_cur_state; +reg [5 :0] dc_dest_reg; +reg dc_ex2_stall; +reg dc_fls; +reg [3 :0] dc_func; +reg dc_lm_pass; +reg dc_mach_mode; +reg [2 :0] dc_next_state; +reg [1 :0] dc_ori_size; +reg dc_pmp_deny; +reg dc_sign_ext; +reg [1 :0] dc_size; +reg dc_split; +reg dc_split_first; +reg dc_split_last; +reg dc_src1_depd; +reg [5 :0] dc_src1_reg; +reg [31:0] dc_st_data_pre; +reg [2 :0] dc_wdata_shift; + +// &Wires; @23 +wire [31:0] ag_dc_addr; +wire ag_dc_buf; +wire [3 :0] ag_dc_bytes_vld; +wire ag_dc_ca; +wire ag_dc_create_vld; +wire ag_dc_dcache_grant; +wire [5 :0] ag_dc_dest_reg; +wire ag_dc_fls; +wire [3 :0] ag_dc_func; +wire ag_dc_inst_vld; +wire ag_dc_inst_vld_gate; +wire ag_dc_lm_pass; +wire ag_dc_mach_mode; +wire [1 :0] ag_dc_ori_size; +wire ag_dc_pmp_expt; +wire ag_dc_sign_ext; +wire [1 :0] ag_dc_size; +wire ag_dc_split; +wire ag_dc_split_first; +wire ag_dc_split_last; +wire ag_dc_src1_depd; +wire [5 :0] ag_dc_src1_reg; +wire ag_dc_st_create_vld; +wire [31:0] ag_dc_st_data; +wire [2 :0] ag_dc_wdata_shift; +wire ag_ld_inst; +wire ag_st_inst; +wire async_expt_vld; +wire async_ld_inst; +wire [31:0] async_mtval; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire [31:0] da_xx_fwd_data; +wire da_xx_fwd_fls; +wire [5 :0] da_xx_fwd_preg; +wire da_xx_fwd_vld; +wire dc_ag_async_expt_vld; +wire dc_ag_async_ld_inst; +wire [31:0] dc_ag_async_mtval; +wire dc_ag_cache_stall; +wire [31:0] dc_ag_dcache_addr; +wire dc_ag_dcache_req; +wire [1 :0] dc_ag_dcache_size; +wire [3 :0] dc_ag_func; +wire dc_ag_pmp_ld_inst; +wire [31:0] dc_ag_pmp_mtval; +wire dc_ag_stall; +wire [2 :0] dc_attr; +wire dc_ca_after; +wire dc_cache_hit; +wire dc_cache_hit_raw; +wire dc_clk; +wire dc_clk_en; +wire dc_cmplt; +wire dc_data_sel; +wire [14:0] dc_dbginfo; +wire dc_dca_inst; +wire dc_dcache_reply; +wire dc_dp_clk; +wire dc_dp_clk_en; +wire dc_expt_vld; +wire dc_fld_inst; +wire dc_fwd_fwb; +wire dc_fwd_lsu; +wire [63:0] dc_icc_way0_data; +wire dc_icc_way0_dirty; +wire [21:0] dc_icc_way0_tag; +wire [63:0] dc_icc_way1_data; +wire dc_icc_way1_dirty; +wire [21:0] dc_icc_way1_tag; +wire dc_idle; +wire dc_inst_vld; +wire dc_ld_cmplt; +wire [31:0] dc_ld_data_from_dcache; +wire [31:0] dc_ld_data_fwd; +wire dc_ld_data_vld; +wire dc_ld_fwd_sel; +wire dc_ld_inst; +wire dc_ld_reply; +wire [31:0] dc_lfb_addr; +wire dc_lfb_buf; +wire dc_lfb_ca; +wire dc_lfb_ca_raw; +wire dc_lfb_create_en; +wire dc_lfb_create_en_gate; +wire dc_lfb_inst_ld; +wire dc_lfb_lock_trans; +wire dc_lfb_lr_inst; +wire dc_lfb_mach_mode; +wire [1 :0] dc_lfb_size; +wire dc_lock_trans; +wire dc_lr_inst; +wire dc_rdl_fifo; +wire [63:0] dc_rdl_way0_data; +wire dc_rdl_way0_dirty; +wire [21:0] dc_rdl_way0_tag; +wire dc_rdl_way0_vld; +wire [63:0] dc_rdl_way1_data; +wire dc_rdl_way1_dirty; +wire [21:0] dc_rdl_way1_tag; +wire dc_rdl_way1_vld; +wire dc_reply; +wire dc_sc_data_sel; +wire dc_sc_data_vld; +wire dc_sc_inst; +wire dc_st_alct; +wire dc_st_cmplt; +wire dc_st_dp_clk; +wire dc_st_dp_clk_en; +wire [31:0] dc_st_fwd_data; +wire dc_st_fwd_vld; +wire dc_st_inst; +wire [31:0] dc_st_rdata; +wire dc_st_reply; +wire [31:0] dc_st_wdata; +wire dc_stage_pipedown; +wire dc_stage_vld; +wire [31:0] dc_stb_addr; +wire [2 :0] dc_stb_attr; +wire [3 :0] dc_stb_bytes_vld; +wire dc_stb_cache_hit; +wire dc_stb_create_en; +wire dc_stb_create_en_gate; +wire [31:0] dc_stb_data; +wire dc_stb_dcache_dirty; +wire dc_stb_dcache_inst; +wire [1 :0] dc_stb_dcache_type; +wire dc_stb_dcache_way; +wire dc_stb_fls; +wire dc_stb_lock_trans; +wire dc_stb_sc_inst; +wire [2 :0] dc_stb_shift; +wire [1 :0] dc_stb_size; +wire dc_stb_split_first; +wire dc_stb_src1_depd; +wire [4 :0] dc_stb_src1_reg; +wire dc_stb_wait_lfb; +wire dc_vb_st_amold; +wire dc_wakeup; +wire [31:0] dc_way0_data_dout; +wire [31:0] dc_way1_data_dout; +wire [31:0] dc_xx_addr; +wire [7 :0] dc_xx_bytes_vld; +wire [63:0] dcache_data_dout_way0; +wire [63:0] dcache_data_dout_way1; +wire [2 :0] dcache_dirty_dout; +wire dcache_hit_way; +wire dcache_hit_way_dirty; +wire [45:0] dcache_tag_dout; +wire fifo; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire ld_fwd_vld; +wire lfb_data_sel; +wire lfb_dc_async_expt; +wire lfb_dc_busy; +wire [31:0] lfb_dc_data; +wire lfb_dc_hit_idx; +wire lfb_dc_ld_cmplt; +wire [31:0] lfb_dc_ld_data; +wire lfb_dc_ld_data_vld; +wire lfb_dc_pop_en; +wire lfb_dc_sc_ldfwd_sel; +wire [31:0] lsu_ex2_data; +wire lsu_ex2_data_vld; +wire lsu_hpcp_cache_read_access; +wire lsu_hpcp_cache_read_access_gate; +wire lsu_hpcp_cache_read_miss; +wire lsu_hpcp_cache_read_miss_gate; +wire lsu_hpcp_cache_write_access; +wire lsu_hpcp_cache_write_access_gate; +wire lsu_hpcp_cache_write_miss; +wire lsu_hpcp_cache_write_miss_gate; +wire lsu_mb_ex2_ca_addr_2; +wire [3 :0] lsu_mb_ex2_ca_bytes_vld; +wire [31:0] lsu_mb_ex2_ca_data; +wire lsu_mb_ex2_ca_data_vld; +wire lsu_mb_ex2_ca_data_vld_gate; +wire [5 :0] lsu_mb_ex2_ca_dest_reg; +wire lsu_mb_ex2_ca_fld; +wire lsu_mb_ex2_ca_fls; +wire lsu_mb_ex2_ca_lock; +wire lsu_mb_ex2_ca_sc_data_vld; +wire lsu_mb_ex2_ca_sign_ext; +wire [1 :0] lsu_mb_ex2_ca_size; +wire lsu_mb_ex2_ca_split; +wire lsu_mb_ex2_ca_split_last; +wire lsu_mb_ex2_ca_stall; +wire lsu_top_dc_vld; +wire lsu_xx_ex2_ca_flush; +wire pad_yy_icg_scan_en; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_yy_xx_async_flush; +wire stb_dc_async_expt; +wire stb_dc_busy; +wire stb_dc_full; +wire stb_dc_hit_addr; +wire stb_dc_hit_dca; +wire stb_dc_hit_idx; +wire [31:0] stb_dc_ld_data; +wire stb_dc_ld_fwd_vld; +wire [31:0] stb_dc_mtval; +wire stb_dc_multi_or_part_hit; +wire stb_dc_pop_en; +wire vb_dc_hit_dirty; +wire [31:0] vb_dc_ld_data; +wire vb_dc_ld_fwd_vld; +wire vb_dc_pop_en; +wire [63:0] way0_data_dout; +wire way0_dirty; +wire way0_tag_hit; +wire way0_tag_vld; +wire [63:0] way1_data_dout; +wire way1_dirty; +wire way1_tag_hit; +wire way1_tag_vld; + + +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter DATAW = `FLEN; + +//================================================ +// Interface to dcache +//================================================ +assign way0_dirty = dcache_dirty_dout[0]; +assign way1_dirty = dcache_dirty_dout[1]; +assign fifo = dcache_dirty_dout[2]; + +assign way0_tag_vld = dcache_tag_dout[22]; +assign way1_tag_vld = dcache_tag_dout[45]; + +assign way0_data_dout[63:0] = dcache_data_dout_way0[63:0]; +assign way1_data_dout[63:0] = dcache_data_dout_way1[63:0]; + +//================================================ +// to DC +//================================================ +assign dc_way0_data_dout[31:0] = dc_addr[2] ? way0_data_dout[63:32] : way0_data_dout[31:0]; +assign dc_way1_data_dout[31:0] = dc_addr[2] ? way1_data_dout[63:32] : way1_data_dout[31:0]; +//================================================ +// to ICC +//================================================ +assign dc_icc_way0_dirty = way0_tag_vld & way0_dirty; +assign dc_icc_way1_dirty = way1_tag_vld & way1_dirty; +assign dc_icc_way0_data[63:0] = way0_data_dout[63:0]; +assign dc_icc_way1_data[63:0] = way1_data_dout[63:0]; +assign dc_icc_way0_tag[21:0] = dcache_tag_dout[21:0]; +assign dc_icc_way1_tag[21:0] = dcache_tag_dout[44:23]; + +//================================================ +// to RDL +//================================================ +assign dc_rdl_way0_vld = way0_tag_vld; +assign dc_rdl_way1_vld = way1_tag_vld; +assign dc_rdl_way0_dirty = way0_dirty; +assign dc_rdl_way1_dirty = way1_dirty; +assign dc_rdl_fifo = fifo; +assign dc_rdl_way0_data[63:0] = way0_data_dout[63:0]; +assign dc_rdl_way1_data[63:0] = way1_data_dout[63:0]; +assign dc_rdl_way0_tag[21:0] = dcache_tag_dout[21:0]; +assign dc_rdl_way1_tag[21:0] = dcache_tag_dout[44:23]; + +//============================================================================== +// DC pipeline +//============================================================================== +parameter IDLE = 3'b000; +parameter DCS = 3'b001; +parameter FRZ = 3'b010; +parameter REPLY = 3'b011; +parameter WFC = 3'b100; + +always@(posedge dc_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dc_cur_state[2:0] <= IDLE; + else if (rtu_yy_xx_async_flush) + dc_cur_state[2:0] <= IDLE; + else + dc_cur_state[2:0] <= dc_next_state[2:0]; +end + +// &CombBeg; @93 +always @( ag_dc_dcache_grant + or dc_cur_state[2:0] + or dc_wakeup + or dc_reply + or lfb_dc_ld_cmplt + or ag_dc_inst_vld + or dc_cmplt) +begin + case(dc_cur_state[2:0]) + IDLE: begin + if (ag_dc_inst_vld) + dc_next_state[2:0] = DCS; + else + dc_next_state[2:0] = IDLE; + end + DCS: begin + if (dc_cmplt) + dc_next_state[2:0] = ag_dc_inst_vld ? DCS : IDLE; + else if (dc_reply & !dc_wakeup) + dc_next_state[2:0] = FRZ; + else if (dc_reply) + dc_next_state[2:0] = REPLY; + else + dc_next_state[2:0] = WFC; + end + WFC: begin + if (lfb_dc_ld_cmplt) + dc_next_state[2:0] = ag_dc_inst_vld ? DCS : IDLE; + else + dc_next_state[2:0] = WFC; + end + FRZ: begin + if (dc_wakeup) + dc_next_state[2:0] = REPLY; + else + dc_next_state[2:0] = FRZ; + end + REPLY: begin + if(ag_dc_dcache_grant) + dc_next_state[2:0] = DCS; + else + dc_next_state[2:0] = REPLY; + end + default: dc_next_state[2:0] = IDLE; + endcase +// &CombEnd; @131 +end + + +assign dc_stage_vld =!(dc_cur_state[2:0] == IDLE); +assign dc_inst_vld = (dc_cur_state[2:0] == DCS) & !dc_pmp_deny; +assign dc_expt_vld = (dc_cur_state[2:0] == DCS) & dc_pmp_deny; + +assign dc_stage_pipedown = (dc_cur_state[2:0] == IDLE) | + (dc_cur_state[2:0] == DCS) & dc_cmplt | + (dc_cur_state[2:0] == WFC) & lfb_dc_ld_cmplt; +assign dc_idle = !dc_stage_vld; + +assign lsu_xx_ex2_ca_flush = dc_expt_vld & dc_func[3:0] == 4'b0101; + +//---------------------------- +//dc stall +//---------------------------- +assign dc_ag_stall = !dc_stage_pipedown; +assign dc_ag_cache_stall = dc_cur_state[2:0] == FRZ | + dc_cur_state[2:0] == REPLY | + dc_cur_state[2:0] == WFC & !lfb_dc_ld_cmplt; +//assign lsu_mb_ex2_ca_stall = !dc_stage_pipedown;// & (!cp0_xx_async_expt_en | dc_lock_trans); +assign lsu_mb_ex2_ca_lock = dc_lock_trans; +//assign lsu_mb_ex2_ca_vld = dc_stage_vld; + +//for timing, cut ex2 stall +always@(posedge dc_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dc_ex2_stall <= 1'b0; + else if (rtu_yy_xx_async_flush) + dc_ex2_stall <= 1'b0; + else if (ag_dc_inst_vld) + dc_ex2_stall <= 1'b1; + else if (dc_stage_pipedown) + dc_ex2_stall <= 1'b0; +end + +assign lsu_mb_ex2_ca_stall = dc_ex2_stall; + +//---------------------------- +//dc req dcache +//---------------------------- +assign dc_ag_dcache_req = dc_cur_state[2:0] == REPLY; +assign dc_ag_dcache_addr[31:0] = dc_addr[31:0]; +assign dc_ag_dcache_size[1:0] = dc_size[1:0]; +assign dc_ag_func[3:0] = dc_func[3:0]; + +//---------------------------- +// for pmp deny +//---------------------------- +assign dc_ag_pmp_mtval[31:0] = dc_addr[31:0]; +assign dc_ag_pmp_ld_inst = (dc_func[3:0] == 4'b0000) | dc_func[3]; +//========================================================== +// DC STAGE information create +//========================================================== + +assign ag_dc_create_vld = dc_stage_pipedown & ag_dc_inst_vld; + +always@(posedge dc_dp_clk) +begin + if (ag_dc_create_vld | ifu_lsu_warm_up) begin + dc_addr[31:0] <= ag_dc_addr[31:0]; + dc_func[3:0] <= ag_dc_func[3:0]; + dc_fls <= ag_dc_fls; + dc_size[1:0] <= ag_dc_size[1:0]; + dc_ori_size[1:0] <= ag_dc_ori_size[1:0]; + dc_sign_ext <= ag_dc_sign_ext; + dc_dest_reg[5:0] <= ag_dc_dest_reg[5:0]; + dc_ca <= ag_dc_ca; + dc_buf <= ag_dc_buf; + dc_mach_mode <= ag_dc_mach_mode; + dc_bytes_vld[3:0]<= ag_dc_bytes_vld[3:0]; + dc_pmp_deny <= ag_dc_pmp_expt; + dc_split <= ag_dc_split; + dc_split_last <= ag_dc_split_last; + dc_split_first <= ag_dc_split_first; + end +end + +assign ag_st_inst = !ag_dc_func[3] & ag_dc_func[0]; +assign ag_dc_st_create_vld = ag_dc_create_vld & ag_st_inst; + +always@(posedge dc_st_dp_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dc_lm_pass <= 1'b0; + else if (ag_dc_st_create_vld & ag_dc_func[1]) + dc_lm_pass <= ag_dc_lm_pass; +end + +assign dc_fwd_lsu = da_xx_fwd_vld + & (dc_fls == da_xx_fwd_fls) + & (dc_src1_reg[5:0] == da_xx_fwd_preg[5:0]); + +assign dc_fwd_fwb = rtu_lsu_fgpr_wb_vld & dc_fls & + (dc_src1_reg[4:0] == rtu_lsu_fgpr_wb_reg[4:0]); + +assign dc_st_fwd_vld = dc_stage_vld & dc_src1_depd & (dc_fwd_fwb | dc_fwd_lsu); +assign dc_st_fwd_data[DATAW-1:0] = dc_fwd_lsu ? da_xx_fwd_data[DATAW-1:0] : rtu_lsu_fgpr_wb_data[DATAW-1:0]; + +always@(posedge dc_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dc_src1_depd <= 1'b0; + else if (ag_dc_st_create_vld) + dc_src1_depd <= ag_dc_src1_depd; + else if (dc_st_fwd_vld) + dc_src1_depd <= 1'b0; +end + +always@(posedge dc_st_dp_clk) +begin + if (ag_dc_st_create_vld | ifu_lsu_warm_up)begin + dc_src1_reg[5:0] <= ag_dc_src1_reg[5:0]; + dc_wdata_shift[2:0] <= ag_dc_wdata_shift[2:0]; + end +end + +always@(posedge dc_st_dp_clk) +begin + if (ag_dc_st_create_vld | ifu_lsu_warm_up) + dc_st_data_pre[DATAW-1:0] <= ag_dc_st_data[DATAW-1:0]; + else if (dc_st_fwd_vld) + dc_st_data_pre[DATAW-1:0] <= dc_st_fwd_data[DATAW-1:0]; +end + +assign dc_st_wdata[DATAW-1:0] = dc_st_fwd_vld ? dc_st_fwd_data[DATAW-1:0] : dc_st_data_pre[DATAW-1:0]; + +//================================================ +// TAG COMPARE +//================================================ +assign way0_tag_hit = (dcache_tag_dout[D_TAG_TAG_LEN-1:0] == dc_addr[31:31-D_TAG_TAG_LEN+1]) & way0_tag_vld & dc_ca; +assign way1_tag_hit = (dcache_tag_dout[23+D_TAG_TAG_LEN-1:23] == dc_addr[31:31-D_TAG_TAG_LEN+1]) & way1_tag_vld & dc_ca; + +//for dcache va op, but st should not access dirty ,dcache should access +//dirty, so dcache and stb can not process in paralle. +assign dcache_hit_way_dirty = way0_tag_hit & way0_dirty | way1_tag_hit & way1_dirty; +assign dcache_hit_way = way1_tag_hit; + +assign dc_cache_hit_raw = way0_tag_hit | way1_tag_hit; +assign dc_cache_hit = dc_cache_hit_raw & cp0_lsu_dcache_en; + +//================================================ +// LD DATA SEL and Align +//================================================ +//data from cache +assign dc_ld_data_from_dcache[DATAW-1:0] = {DATAW{way0_tag_hit & dc_ld_inst}} & dc_way0_data_dout[DATAW-1:0] | + {DATAW{way1_tag_hit & dc_ld_inst}} & dc_way1_data_dout[DATAW-1:0]; + +//data forward from VB or STB +assign dc_ld_data_fwd[DATAW-1:0] = vb_dc_ld_fwd_vld ? vb_dc_ld_data[DATAW-1:0] : stb_dc_ld_data[DATAW-1:0]; +assign ld_fwd_vld = vb_dc_ld_fwd_vld | stb_dc_ld_fwd_vld; + +//================================================ +// st data +//================================================ +assign dc_st_rdata[DATAW-1:0] = dc_lm_pass ? {DATAW{1'b0}} : {{(DATAW-1){1'b0}}, 1'b1}; + +//================================================ +// data forward and complete +//================================================ +//func[3]:dcache,[2]:atomic; [1]:exclusive;[0]:ld/st +assign dc_ld_inst = !dc_func[0] & !dc_func[3]; +assign dc_st_inst = dc_func[0] & !dc_func[3]; +assign dc_dca_inst = dc_func[3]; +assign dc_lr_inst = dc_ld_inst & dc_func[1]; +assign dc_sc_inst = dc_st_inst & dc_func[1]; +assign dc_fld_inst = dc_ld_inst & dc_fls & (dc_size[1:0] == 2'b11); +assign dc_lock_trans = !dc_func[3] & (|dc_func[2:1]); + +assign dc_ld_data_vld = dc_ld_cmplt; +assign dc_sc_data_vld = dc_inst_vld & !dc_st_reply & dc_sc_inst; + +assign lfb_data_sel = dc_cur_state[2:0] == WFC; +assign dc_data_sel = dc_cur_state[2:0] == DCS; +assign dc_sc_data_sel = dc_data_sel & dc_sc_inst; +assign dc_ld_fwd_sel = dc_data_sel & dc_ld_inst & ld_fwd_vld; + +assign lfb_dc_sc_ldfwd_sel = lfb_data_sel | dc_sc_data_sel | dc_ld_fwd_sel; +assign lfb_dc_data[DATAW-1:0] = {DATAW{lfb_data_sel}} & lfb_dc_ld_data[DATAW-1:0] | + {DATAW{dc_sc_data_sel}} & dc_st_rdata[DATAW-1:0] | + {DATAW{dc_ld_fwd_sel}} & dc_ld_data_fwd[DATAW-1:0]; + +assign lsu_ex2_data_vld = dc_ld_data_vld | lfb_dc_ld_data_vld | dc_sc_data_vld ; +assign lsu_ex2_data[DATAW-1:0] = lfb_dc_sc_ldfwd_sel ? lfb_dc_data[DATAW-1:0] : dc_ld_data_from_dcache[DATAW-1:0]; + +assign lsu_mb_ex2_ca_data_vld = lsu_ex2_data_vld; +assign lsu_mb_ex2_ca_data_vld_gate = dc_inst_vld & (dc_ld_inst | dc_sc_inst) | lfb_dc_ld_data_vld; +assign lsu_mb_ex2_ca_data[DATAW-1:0] = lsu_ex2_data[DATAW-1:0]; +assign lsu_mb_ex2_ca_dest_reg[5:0] = dc_dest_reg[5:0]; +assign lsu_mb_ex2_ca_fls = dc_fls; +assign lsu_mb_ex2_ca_fld = dc_fld_inst; +assign lsu_mb_ex2_ca_sc_data_vld = dc_sc_inst; +assign lsu_mb_ex2_ca_split = dc_split; +assign lsu_mb_ex2_ca_split_last = dc_split_last; +assign lsu_mb_ex2_ca_bytes_vld[3:0] = dc_bytes_vld[3:0]; +assign lsu_mb_ex2_ca_sign_ext = dc_sign_ext; +assign lsu_mb_ex2_ca_addr_2 = dc_addr[2]; +assign lsu_mb_ex2_ca_size[1:0] = dc_ori_size[1:0]; +// &Force("nonport","dc_ori_size"); @406 + +//assign lsu_mb_ex2_ca_ld_vld = dc_stage_vld & dc_ld_inst; + +assign lsu_top_dc_vld = dc_stage_vld; +//dc_cmplt +assign dc_ld_cmplt = dc_inst_vld & !dc_ld_reply & + dc_ld_inst & (dc_cache_hit | vb_dc_ld_fwd_vld); +assign dc_st_cmplt = dc_inst_vld & + (dc_st_inst & !dc_st_reply | + dc_dca_inst & !dc_dcache_reply); + +assign dc_cmplt = dc_ld_cmplt | + dc_st_cmplt | + dc_expt_vld; + +//async exception +assign async_expt_vld = stb_dc_async_expt | + lfb_dc_async_expt & dc_split_first; + +assign async_mtval[31:0] = {32{stb_dc_async_expt}} & stb_dc_mtval[31:0] | + {32{lfb_dc_async_expt}} & dc_addr[31:0]; + +assign async_ld_inst = lfb_dc_async_expt & dc_ld_inst & !dc_lock_trans; + +assign dc_ag_async_expt_vld = async_expt_vld; +assign dc_ag_async_mtval[31:0] = async_mtval[31:0]; +assign dc_ag_async_ld_inst = async_ld_inst; + +//================================================ +// lfb create +//================================================ +assign dc_lfb_create_en = dc_inst_vld & + !dc_reply & + !dc_cache_hit & + (dc_ld_inst & ~vb_dc_ld_fwd_vld | + dc_st_inst & dc_st_alct); // | dc_amo_ld + +assign dc_lfb_create_en_gate + = dc_inst_vld & + !dc_cache_hit & + (dc_ld_inst | + dc_st_inst & dc_st_alct); // | dc_amo_ld + +assign dc_lfb_addr[31:0] = dc_addr[31:0]; +assign dc_lfb_size[1:0] = dc_size[1:0]; +assign dc_lfb_ca = dc_ca_after & !dc_lock_trans; +assign dc_lfb_ca_raw = dc_ca; +assign dc_lfb_buf = dc_buf; +assign dc_lfb_mach_mode = dc_mach_mode; +assign dc_lfb_lock_trans = dc_lock_trans; +assign dc_lfb_inst_ld = dc_ld_inst; +assign dc_lfb_lr_inst = dc_lr_inst; + +//================================================ +// stb create_en +//================================================ +assign dc_stb_create_en = dc_inst_vld & !dc_reply & + (dc_st_inst & !dc_sc_inst | + dc_dca_inst & dc_cache_hit_raw | + dc_sc_inst & dc_lm_pass); +assign dc_stb_create_en_gate = dc_inst_vld & + (dc_st_inst & !dc_sc_inst | + dc_dca_inst | + dc_sc_inst & dc_lm_pass); + +assign dc_ca_after = dc_ca & cp0_lsu_dcache_en; +assign dc_st_alct = dc_ca_after & cp0_lsu_dcache_wa & !dc_lock_trans; +assign dc_attr[2:0] = {dc_ca, dc_buf, dc_mach_mode}; + +assign dc_stb_addr[31:0] = dc_addr[31:0]; +assign dc_stb_size[1:0] = dc_size[1:0]; +assign dc_stb_dcache_inst = dc_dca_inst; +assign dc_stb_dcache_type[1:0]= dc_func[1:0]; +assign dc_stb_bytes_vld[3:0] = dc_bytes_vld[3:0]; +assign dc_stb_attr[2:0] = dc_attr[2:0]; +assign dc_stb_wait_lfb = dc_st_alct & !dc_cache_hit; +assign dc_stb_cache_hit = dc_cache_hit; +assign dc_stb_dcache_way = dcache_hit_way; +assign dc_stb_dcache_dirty = dcache_hit_way_dirty; +assign dc_stb_lock_trans = dc_lock_trans; +assign dc_stb_sc_inst = dc_sc_inst; +assign dc_stb_src1_depd = dc_src1_depd & !dc_st_fwd_vld; +assign dc_stb_data[DATAW-1:0]= dc_st_wdata[DATAW-1:0]; +assign dc_stb_shift[2:0] = dc_wdata_shift[2:0]; +assign dc_stb_src1_reg[4:0] = dc_src1_reg[4:0]; +assign dc_stb_fls = dc_fls; +assign dc_stb_split_first = dc_split_first; + +//================================================ +// dc_reply +//================================================ +assign dc_ld_reply = lfb_dc_busy & !dc_cache_hit | + lfb_dc_hit_idx | + stb_dc_multi_or_part_hit | + stb_dc_hit_dca | + stb_dc_hit_idx & !dc_cache_hit | + // dc_amo_ld & vb_dc_hit_dirty | + dc_lock_trans & (lfb_dc_busy | stb_dc_busy); + +assign dc_st_reply = lfb_dc_busy & !dc_cache_hit | + lfb_dc_hit_idx | + vb_dc_hit_dirty | + stb_dc_full | + stb_dc_hit_dca | + stb_dc_hit_addr | + dc_st_alct & !dc_cache_hit & stb_dc_hit_idx; + +assign dc_dcache_reply = lfb_dc_busy & !dc_cache_hit_raw | + (stb_dc_full | stb_dc_hit_idx) & dc_cache_hit_raw; + +assign dc_reply = dc_ld_inst & dc_ld_reply | + dc_st_inst & dc_st_reply | + dc_dca_inst & dc_dcache_reply; + +assign dc_wakeup = vb_dc_pop_en | + stb_dc_pop_en | + lfb_dc_pop_en | lfb_dc_ld_cmplt; + +//================================================ +// address for dependency check +//================================================ + +assign dc_xx_addr[31:0] = dc_addr[31:0]; +assign dc_xx_bytes_vld[7:0] = (dc_size[1:0] == 2'b11) + ? {dc_bytes_vld[3:0],dc_bytes_vld[3:0]} + : (dc_addr[2] ? {dc_bytes_vld[3:0], 4'b0000} + : {4'b0000, dc_bytes_vld[3:0]}); +assign dc_vb_st_amold = dc_st_inst;// | dc_amo_ld; + +assign dc_clk_en = ag_dc_inst_vld_gate | dc_stage_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_dc_gated_clk"); @539 +gated_clk_cell x_pa_lsu_dc_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dc_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dc_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @540 +// .external_en (1'b0), @541 +// .global_en (1'b1), @542 +// .module_en (cp0_lsu_icg_en ), @543 +// .local_en (dc_clk_en), @544 +// .clk_out (dc_clk)); @545 + +assign dc_dp_clk_en = ag_dc_inst_vld_gate | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_dc_dp_gated_clk"); @548 +gated_clk_cell x_pa_lsu_dc_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dc_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dc_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @549 +// .external_en (1'b0), @550 +// .global_en (1'b1), @551 +// .module_en (cp0_lsu_icg_en ), @552 +// .local_en (dc_dp_clk_en), @553 +// .clk_out (dc_dp_clk)); @554 + +assign dc_st_dp_clk_en = ag_dc_inst_vld_gate & ag_st_inst | dc_st_fwd_vld | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_dc_st_dp_gated_clk"); @557 +gated_clk_cell x_pa_lsu_dc_st_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dc_st_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dc_st_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @558 +// .external_en (1'b0), @559 +// .global_en (1'b1), @560 +// .module_en (cp0_lsu_icg_en ), @561 +// .local_en (dc_st_dp_clk_en), @562 +// .clk_out (dc_st_dp_clk)); @563 + +assign dc_dbginfo[14:0] = {dc_func[3:0],dc_src1_reg[5:0], dc_src1_depd, stb_dc_hit_addr, dc_cur_state[2:0]}; + +//================================================ +// PMU +//================================================ +// &Force("output","dc_lfb_create_en"); @571 +// &Force("output","dc_stb_create_en"); @572 +assign ag_ld_inst = !ag_dc_func[3] & !ag_dc_func[0]; +assign lsu_hpcp_cache_read_access = ag_dc_create_vld & ag_ld_inst; +assign lsu_hpcp_cache_read_miss = dc_lfb_create_en & dc_ld_inst; +assign lsu_hpcp_cache_write_access = ag_dc_create_vld & ag_st_inst; +assign lsu_hpcp_cache_write_miss = dc_stb_create_en & !dc_cache_hit & dc_st_inst; +assign lsu_hpcp_cache_read_access_gate = ag_dc_inst_vld_gate & ag_ld_inst; +assign lsu_hpcp_cache_read_miss_gate = dc_inst_vld & dc_ld_inst; +assign lsu_hpcp_cache_write_access_gate = ag_dc_inst_vld_gate & ag_st_inst; +assign lsu_hpcp_cache_write_miss_gate = dc_inst_vld & dc_st_inst; +// &ModuleEnd; @592 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dtif.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dtif.v new file mode 100644 index 0000000000000000000000000000000000000000..7d53c2b97b28d0e0e78bf2990e778d106179644d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_dtif.v @@ -0,0 +1,567 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// //&Depend("pa_dtu_cfig.h"); @18 +// &Depend("cpu_cfig.h"); @19 + +// &ModuleBeg; @21 +module pa_lsu_dtif( + ag_dtu_addr, + ag_dtu_addr_ready, + ag_dtu_amo_type, + ag_dtu_bytes_vld, + ag_dtu_data, + ag_dtu_data_chk_mask, + ag_dtu_data_vld, + ag_dtu_halt_info, + ag_dtu_mem_access_size, + ag_dtu_pipe_down, + ag_dtu_req, + ag_dtu_req_gate, + ag_dtu_split_last, + ag_dtu_st_type, + cp0_lsu_icg_en, + cpurst_b, + da_dtu_data, + da_dtu_data_expt_vld, + da_dtu_data_vld, + dtif_ag_cmplt_ready, + dtif_ag_fsm_idle, + dtif_ag_halt_info, + dtif_ag_halt_info_up, + dtif_ag_pipedown_mask, + dtif_ag_stall, + dtu_lsu_addr_trig_en, + dtu_lsu_data_trig_en, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + forever_cpuclk, + ifu_lsu_warm_up, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + lsu_dtu_ldst_type, + lsu_dtu_mem_access_size, + pad_yy_icg_scan_en, + rtu_yy_xx_flush +); + +// &Ports; @22 +input [31:0] ag_dtu_addr; +input ag_dtu_addr_ready; +input ag_dtu_amo_type; +input [7 :0] ag_dtu_bytes_vld; +input [31:0] ag_dtu_data; +input ag_dtu_data_chk_mask; +input ag_dtu_data_vld; +input [14:0] ag_dtu_halt_info; +input [1 :0] ag_dtu_mem_access_size; +input ag_dtu_pipe_down; +input ag_dtu_req; +input ag_dtu_req_gate; +input ag_dtu_split_last; +input ag_dtu_st_type; +input cp0_lsu_icg_en; +input cpurst_b; +input [31:0] da_dtu_data; +input da_dtu_data_expt_vld; +input da_dtu_data_vld; +input dtu_lsu_addr_trig_en; +input dtu_lsu_data_trig_en; +input [14:0] dtu_lsu_halt_info; +input dtu_lsu_halt_info_vld; +input forever_cpuclk; +input ifu_lsu_warm_up; +input pad_yy_icg_scan_en; +input rtu_yy_xx_flush; +output dtif_ag_cmplt_ready; +output dtif_ag_fsm_idle; +output [14:0] dtif_ag_halt_info; +output dtif_ag_halt_info_up; +output dtif_ag_pipedown_mask; +output dtif_ag_stall; +output [14:0] lsu_dtu_halt_info; +output lsu_dtu_last_check; +output [31:0] lsu_dtu_ldst_addr; +output lsu_dtu_ldst_addr_vld; +output [7 :0] lsu_dtu_ldst_bytes_vld; +output [31:0] lsu_dtu_ldst_data; +output lsu_dtu_ldst_data_vld; +output [1 :0] lsu_dtu_ldst_type; +output [1 :0] lsu_dtu_mem_access_size; + +// &Regs; @23 +reg [1 :0] dt_addr_access_size_ff; +reg dt_addr_chk_last_ff; +reg [31:0] dt_addr_ff; +reg [1 :0] dt_addr_ldst_type_ff; +reg [7 :0] dt_bytes_vld_ff; +reg [2 :0] dt_cur_state; +reg [1 :0] dt_data_access_size_ff; +reg dt_data_chk_last_ff; +reg [31:0] dt_data_ff; +reg [2 :0] dt_next_state; +reg dt_rdata_vld; +reg dt_wait_state; + +// &Wires; @24 +wire addr_chk_en; +wire addr_trig_en; +wire [31:0] ag_dtu_addr; +wire ag_dtu_addr_ready; +wire ag_dtu_amo_type; +wire [7 :0] ag_dtu_bytes_vld; +wire [31:0] ag_dtu_data; +wire ag_dtu_data_chk_mask; +wire ag_dtu_data_vld; +wire [14:0] ag_dtu_halt_info; +wire [1 :0] ag_dtu_mem_access_size; +wire ag_dtu_pipe_down; +wire ag_dtu_req; +wire ag_dtu_req_gate; +wire ag_dtu_split_last; +wire ag_dtu_st_type; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire [31:0] da_dtu_data; +wire da_dtu_data_expt_vld; +wire da_dtu_data_vld; +wire data_chk_en; +wire data_trig_en; +wire [1 :0] dt_access_size; +wire dt_addr_clk; +wire dt_addr_clk_en; +wire dt_addr_req; +wire dt_addr_start; +wire dt_cmplt_ready; +wire dt_data_clk; +wire dt_data_clk_en; +wire [1 :0] dt_data_ldst_type; +wire dt_data_req; +wire dt_data_start; +wire dt_data_vld; +wire dt_fsm_addr_chk; +wire dt_fsm_chk; +wire dt_fsm_clk; +wire dt_fsm_clk_en; +wire dt_fsm_data_chk; +wire dt_fsm_idle; +wire dt_fsm_wait_cmplt; +wire dt_fsm_wait_data; +wire dt_last_check; +wire [1 :0] dt_ldst_type; +wire dt_pipedown_mask; +wire dt_stall; +wire dt_start_gate; +wire dtif_ag_cmplt_ready; +wire dtif_ag_fsm_idle; +wire [14:0] dtif_ag_halt_info; +wire dtif_ag_halt_info_up; +wire dtif_ag_pipedown_mask; +wire dtif_ag_stall; +wire dtu_halt_info_vld; +wire dtu_lsu_addr_trig_en; +wire dtu_lsu_data_trig_en; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire forever_cpuclk; +wire [14:0] halt_info; +wire ifu_lsu_warm_up; +wire [31:0] lsu_addr; +wire lsu_addr_chk_last; +wire [1 :0] lsu_addr_ldst_type; +wire lsu_addr_up; +wire lsu_addr_vld; +wire lsu_addr_vld_gate; +wire lsu_amo_type; +wire [7 :0] lsu_bytes_vld; +wire [31:0] lsu_data; +wire lsu_data_chk_last; +wire lsu_data_chk_mask; +wire lsu_data_expt_vld; +wire lsu_data_up; +wire lsu_data_vld; +wire lsu_data_vld_gate; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [1 :0] lsu_dtu_ldst_type; +wire [1 :0] lsu_dtu_mem_access_size; +wire [14:0] lsu_halt_info; +wire [1 :0] lsu_mem_access_size; +wire lsu_pipe_down; +wire lsu_req; +wire lsu_req_gate; +wire lsu_split_last; +wire lsu_st_type; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_flush; + + +parameter S_BYTE = 2'b00, + S_HALF = 2'b01, + S_WORD = 2'b10, + S_DWORD = 2'b11; +//================================================ +// input interface +//================================================ +//------------------from dtu---------------------- +assign halt_info[`TDT_HINFO_WIDTH-1:0] = dtu_lsu_halt_info[`TDT_HINFO_WIDTH-1:0]; + +assign addr_trig_en = dtu_lsu_addr_trig_en; +assign data_trig_en = dtu_lsu_data_trig_en; + +//for timing +assign dtu_halt_info_vld = dtu_lsu_halt_info_vld; + +//------------------from lsu---------------------- +//req info +assign lsu_req = ag_dtu_req; +assign lsu_req_gate = ag_dtu_req_gate; +assign lsu_addr_vld = ag_dtu_req & ag_dtu_addr_ready; +assign lsu_addr_vld_gate = ag_dtu_req_gate; +assign lsu_data_vld = ag_dtu_data_vld | da_dtu_data_vld; +assign lsu_data_vld_gate = ag_dtu_data_vld | da_dtu_data_vld; +assign lsu_data_expt_vld = da_dtu_data_expt_vld; + +assign lsu_addr[31:0] = ag_dtu_addr[31:0]; +assign lsu_bytes_vld[7:0] = ag_dtu_bytes_vld[7:0]; + +assign lsu_data[31:0] = da_dtu_data_vld + ? da_dtu_data[31:0] + : ag_dtu_data[31:0]; + +assign lsu_halt_info[`TDT_HINFO_WIDTH-1:0] = ag_dtu_halt_info[`TDT_HINFO_WIDTH-1:0]; + +//lsu inst info +assign lsu_st_type = ag_dtu_st_type; +assign lsu_amo_type = ag_dtu_amo_type; +assign lsu_mem_access_size[1:0] = ag_dtu_mem_access_size[1:0]; +assign lsu_split_last = ag_dtu_split_last; +assign lsu_data_chk_mask = ag_dtu_data_chk_mask; + +//cmplt and pipe info +assign lsu_pipe_down = ag_dtu_pipe_down; + +//================================================ +// ICG +//================================================ +assign dt_fsm_clk_en = dt_start_gate | !dt_fsm_idle; + +// &Instance("gated_clk_cell", "x_pa_lsu_dtif_fsm_gated_clk"); @76 +gated_clk_cell x_pa_lsu_dtif_fsm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dt_fsm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dt_fsm_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @77 +// .external_en (1'b0), @78 +// .global_en (1'b1), @79 +// .module_en (cp0_lsu_icg_en), @80 +// .local_en (dt_fsm_clk_en), @81 +// .clk_out (dt_fsm_clk)); @82 + +assign dt_addr_clk_en = dt_fsm_idle & lsu_addr_vld_gate + | ifu_lsu_warm_up; + +// &Instance("gated_clk_cell", "x_pa_lsu_dtif_addr_gated_clk"); @87 +gated_clk_cell x_pa_lsu_dtif_addr_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dt_addr_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dt_addr_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @88 +// .external_en (1'b0), @89 +// .global_en (1'b1), @90 +// .module_en (cp0_lsu_icg_en), @91 +// .local_en (dt_addr_clk_en), @92 +// .clk_out (dt_addr_clk)); @93 + +assign dt_data_clk_en = dt_fsm_wait_data & lsu_data_vld_gate + | ifu_lsu_warm_up; + +// &Instance("gated_clk_cell", "x_pa_lsu_dtif_data_gated_clk"); @98 +gated_clk_cell x_pa_lsu_dtif_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (dt_data_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (dt_data_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @99 +// .external_en (1'b0), @100 +// .global_en (1'b1), @101 +// .module_en (cp0_lsu_icg_en), @102 +// .local_en (dt_data_clk_en), @103 +// .clk_out (dt_data_clk)); @104 + +//================================================ +// FSM +//================================================ +parameter IDLE = 3'b000; +parameter ADDR_CHK = 3'b001; +parameter DATA_CHK = 3'b010; +parameter WAIT_DATA = 3'b011; +parameter WAIT_PIPE = 3'b100; +parameter WAIT_CMPLT = 3'b101; + +always@(posedge dt_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dt_cur_state[2:0] <= IDLE; + else if (rtu_yy_xx_flush) + dt_cur_state[2:0] <= IDLE; + else + dt_cur_state[2:0] <= dt_next_state[2:0]; +end + +// &CombBeg; @126 +always @( lsu_st_type + or dt_data_vld + or lsu_pipe_down + or lsu_data_vld + or dt_cur_state[2:0] + or dt_addr_start + or lsu_split_last + or data_chk_en + or lsu_data_expt_vld + or dt_data_start) +begin + case(dt_cur_state[2:0]) + IDLE:begin + if (dt_addr_start) + dt_next_state[2:0] = ADDR_CHK; + else if (dt_data_start & lsu_st_type) + dt_next_state[2:0] = WAIT_DATA; + else if (dt_data_start & !lsu_st_type) + dt_next_state[2:0] = WAIT_PIPE; + else + dt_next_state[2:0] = IDLE; + end + ADDR_CHK:begin + if (dt_data_vld & lsu_split_last & !data_chk_en) + dt_next_state[2:0] = WAIT_CMPLT; + else if (dt_data_vld & data_chk_en & lsu_st_type) + dt_next_state[2:0] = WAIT_DATA; + else if(dt_data_vld) + dt_next_state[2:0] = WAIT_PIPE; + else + dt_next_state[2:0] = ADDR_CHK; + end + DATA_CHK:begin + if (dt_data_vld & lsu_split_last) + dt_next_state[2:0] = WAIT_CMPLT; + else if(dt_data_vld) + dt_next_state[2:0] = WAIT_PIPE; + else + dt_next_state[2:0] = DATA_CHK; + end + WAIT_DATA:begin + if (lsu_data_vld) + dt_next_state[2:0] = DATA_CHK; + else if (lsu_data_expt_vld & !lsu_st_type) + dt_next_state[2:0] = WAIT_CMPLT; + else + dt_next_state[2:0] = WAIT_DATA; + end + WAIT_PIPE:begin + if (lsu_pipe_down & !lsu_st_type & data_chk_en) + dt_next_state[2:0] = WAIT_DATA; + else if (lsu_pipe_down) + dt_next_state[2:0] = IDLE; + else + dt_next_state[2:0] = WAIT_PIPE; + end + WAIT_CMPLT:begin + if (lsu_pipe_down) + dt_next_state[2:0] = IDLE; + else + dt_next_state[2:0] = WAIT_CMPLT; + end + default:dt_next_state[2:0] = IDLE; + endcase +// &CombEnd; @180 +end +//================================================ +// FSM ctrl +//================================================ +//fsm start +//for lsu split inst,should check addr multi,but data only once +//ld chk at last split while st chk at first split +//for vector,not check data for current model +assign data_chk_en = data_trig_en & !lsu_data_chk_mask; +assign addr_chk_en = addr_trig_en; + +assign dt_addr_start = lsu_addr_vld & addr_chk_en; +assign dt_data_start = lsu_req & data_chk_en & !addr_chk_en; + +assign dt_start_gate = lsu_req_gate & (addr_trig_en | data_trig_en); + +//check +//assign dtu_cancel = dtu_halt_info_vld & halt_info[`TDT_HINFO_CANCEL]; + +//================================================ +// FSM output +//================================================ +assign dt_fsm_idle = (dt_cur_state[2:0] == IDLE); +assign dt_fsm_addr_chk = (dt_cur_state[2:0] == ADDR_CHK); +assign dt_fsm_data_chk = (dt_cur_state[2:0] == DATA_CHK); +assign dt_fsm_wait_data = (dt_cur_state[2:0] == WAIT_DATA); +assign dt_fsm_wait_cmplt = (dt_cur_state[2:0] == WAIT_CMPLT); + +//---------for lsu ag-------------------- +assign dt_stall = dt_fsm_idle + & lsu_req_gate + & (addr_chk_en | data_chk_en) + | dt_fsm_addr_chk + | dt_fsm_data_chk + | dt_fsm_wait_data; + +assign dt_cmplt_ready = dt_fsm_wait_cmplt; + +//for ld data check,we must pipedown first then cmplt +//hence we need pipedown_mask here +assign dt_pipedown_mask = dt_fsm_wait_cmplt + & data_chk_en + & !lsu_st_type; + +//---------for dtu----------------------- +//for timing,flop addr and data before req +assign lsu_addr_up = dt_fsm_idle & dt_addr_start; +assign lsu_data_up = dt_fsm_wait_data & lsu_data_vld; + +assign lsu_addr_chk_last = lsu_split_last & !data_chk_en; +assign lsu_data_chk_last = !addr_chk_en | !lsu_st_type | lsu_split_last; + +always@(posedge dt_addr_clk) +begin + if (lsu_addr_up | ifu_lsu_warm_up) + begin + dt_addr_ff[31:0] <= lsu_addr[31:0]; + dt_bytes_vld_ff[7:0] <= lsu_bytes_vld[7:0]; + dt_addr_ldst_type_ff[1:0] <= lsu_addr_ldst_type[1:0]; + dt_addr_access_size_ff[1:0] <= lsu_mem_access_size[1:0]; + dt_addr_chk_last_ff <= lsu_addr_chk_last; + end +end + +always@(posedge dt_data_clk) +begin + if (lsu_data_up | ifu_lsu_warm_up) + begin + dt_rdata_vld <= da_dtu_data_vld; + dt_data_ff[31:0] <= lsu_data[31:0]; + dt_data_access_size_ff[1:0] <= lsu_mem_access_size[1:0]; + dt_data_chk_last_ff <= lsu_data_chk_last; + end +end + +//for timing,use dtu halt_info_vld to indicate 1 or more cycles +assign dt_fsm_chk = dt_fsm_addr_chk | dt_fsm_data_chk; + +always@(posedge dt_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dt_wait_state <= 1'b0; + else if(rtu_yy_xx_flush | dt_fsm_chk & dtu_halt_info_vld) + dt_wait_state <= 1'b0; + else if (dt_fsm_chk & !dtu_halt_info_vld) + dt_wait_state <= 1'b1; +end + +assign dt_data_vld = dtu_halt_info_vld; + +//req ctrl +assign dt_addr_req = dt_fsm_addr_chk & !dt_wait_state; +assign dt_data_req = dt_fsm_data_chk & !dt_wait_state; + +//for amo,when req addr,should use both ldst type +//when req data,should check st or ld data seperately +assign lsu_addr_ldst_type[1:0] = lsu_amo_type + ? 2'b11 + : {!lsu_st_type,lsu_st_type}; + +assign dt_data_ldst_type[1:0] = {dt_rdata_vld,!dt_rdata_vld}; + +assign dt_ldst_type[1:0] = dt_addr_req + ? dt_addr_ldst_type_ff[1:0] + : dt_data_ldst_type[1:0]; +assign dt_access_size[1:0] = dt_addr_req + ? dt_addr_access_size_ff[1:0] + : dt_data_access_size_ff[1:0]; + +//for dtu match maintenance +assign dt_last_check = dt_addr_req + & dt_addr_chk_last_ff + | dt_data_req + & dt_data_chk_last_ff; + +//================================================ +// output interface +//================================================ +//------------------for ag ctrl------------------- +//cmplt/pipe stall +assign dtif_ag_stall = dt_stall; +assign dtif_ag_cmplt_ready = dt_cmplt_ready; +assign dtif_ag_fsm_idle = dt_fsm_idle; +assign dtif_ag_pipedown_mask = dt_pipedown_mask; + +//half info +assign dtif_ag_halt_info_up = (dt_fsm_addr_chk | dt_fsm_data_chk) + & dt_data_vld; +assign dtif_ag_halt_info[`TDT_HINFO_WIDTH-1:0] = halt_info[`TDT_HINFO_WIDTH-1:0]; + +//other +//trig_en prevent fast cmplt +//assign dtif_ag_trig_en = addr_chk_en | data_chk_en; + +//------------------for dtu----------------------- +assign lsu_dtu_ldst_addr_vld = dt_addr_req; +assign lsu_dtu_ldst_type[1:0] = dt_ldst_type[1:0]; +assign lsu_dtu_ldst_addr[31:0] = dt_addr_ff[31:0]; +assign lsu_dtu_ldst_bytes_vld[7:0] = dt_bytes_vld_ff[7:0]; +assign lsu_dtu_mem_access_size[1:0] = dt_access_size[1:0]; +assign lsu_dtu_ldst_data_vld = dt_data_req; +assign lsu_dtu_ldst_data[31:0] = dt_data_ff[31:0]; +assign lsu_dtu_last_check = dt_last_check; + +assign lsu_dtu_halt_info[`TDT_HINFO_WIDTH-1:0] = lsu_halt_info[`TDT_HINFO_WIDTH-1:0]; + + +// &ModuleEnd; @370 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_icc.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_icc.v new file mode 100644 index 0000000000000000000000000000000000000000..b9bb4acac3cfb7f4ed5053670b13e9e3d70e7101 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_icc.v @@ -0,0 +1,506 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_icc( + arb_icc_data_grant, + cp0_lsu_icc_addr, + cp0_lsu_icc_op, + cp0_lsu_icc_req, + cp0_lsu_icc_type, + cp0_lsu_icg_en, + cpurst_b, + dc_icc_way0_data, + dc_icc_way0_dirty, + dc_icc_way0_tag, + dc_icc_way1_data, + dc_icc_way1_dirty, + dc_icc_way1_tag, + forever_cpuclk, + icc_arb_data_bank, + icc_arb_data_din, + icc_arb_data_idx, + icc_arb_data_req, + icc_arb_data_way, + icc_arb_data_wen, + icc_arb_dirty_din, + icc_arb_dirty_idx, + icc_arb_dirty_req, + icc_arb_dirty_wen, + icc_arb_tag_din, + icc_arb_tag_idx, + icc_arb_tag_req, + icc_arb_tag_wen, + icc_vb_addr, + icc_vb_clr_vld, + icc_vb_create_en, + icc_vb_data, + icc_vb_data_cnt, + icc_vb_data_create, + icc_vb_line_dirty, + icc_xx_idle, + ifu_lsu_warm_up, + lsu_cp0_icc_done, + pad_yy_icg_scan_en, + vb_icc_empty, + vb_icc_grant +); + +// &Ports; @21 +input arb_icc_data_grant; +input [31:0] cp0_lsu_icc_addr; +input [1 :0] cp0_lsu_icc_op; +input cp0_lsu_icc_req; +input [1 :0] cp0_lsu_icc_type; +input cp0_lsu_icg_en; +input cpurst_b; +input [63:0] dc_icc_way0_data; +input dc_icc_way0_dirty; +input [21:0] dc_icc_way0_tag; +input [63:0] dc_icc_way1_data; +input dc_icc_way1_dirty; +input [21:0] dc_icc_way1_tag; +input forever_cpuclk; +input ifu_lsu_warm_up; +input pad_yy_icg_scan_en; +input vb_icc_empty; +input vb_icc_grant; +output [1 :0] icc_arb_data_bank; +output [63:0] icc_arb_data_din; +output [11:0] icc_arb_data_idx; +output icc_arb_data_req; +output [1 :0] icc_arb_data_way; +output [3 :0] icc_arb_data_wen; +output [2 :0] icc_arb_dirty_din; +output [9 :0] icc_arb_dirty_idx; +output icc_arb_dirty_req; +output [2 :0] icc_arb_dirty_wen; +output [22:0] icc_arb_tag_din; +output [9 :0] icc_arb_tag_idx; +output icc_arb_tag_req; +output [1 :0] icc_arb_tag_wen; +output [26:0] icc_vb_addr; +output icc_vb_clr_vld; +output icc_vb_create_en; +output [63:0] icc_vb_data; +output [1 :0] icc_vb_data_cnt; +output icc_vb_data_create; +output icc_vb_line_dirty; +output icc_xx_idle; +output lsu_cp0_icc_done; + +// &Regs; @22 +reg [1 :0] data_offset; +reg [1 :0] data_offset_f; +reg [9 :0] icc_cnt; +reg [3 :0] icc_cur_state; +reg icc_data_vld; +reg icc_data_way0; +reg [3 :0] icc_next_state; +reg [21:0] way1_tag; + +// &Wires; @23 +wire all_dirty; +wire arb_icc_data_grant; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire [9 :0] cp0_set; +wire [1 :0] cp0_way; +wire cpurst_b; +wire data_rd_last; +wire [63:0] dc_icc_way0_data; +wire dc_icc_way0_dirty; +wire [21:0] dc_icc_way0_tag; +wire [63:0] dc_icc_way1_data; +wire dc_icc_way1_dirty; +wire [21:0] dc_icc_way1_tag; +wire dirty_wen; +wire fifo_wen; +wire forever_cpuclk; +wire [1 :0] icc_arb_data_bank; +wire [63:0] icc_arb_data_din; +wire [11:0] icc_arb_data_idx; +wire icc_arb_data_req; +wire [1 :0] icc_arb_data_way; +wire [3 :0] icc_arb_data_wen; +wire [2 :0] icc_arb_dirty_din; +wire [9 :0] icc_arb_dirty_idx; +wire icc_arb_dirty_req; +wire [2 :0] icc_arb_dirty_wen; +wire [22:0] icc_arb_tag_din; +wire [9 :0] icc_arb_tag_idx; +wire icc_arb_tag_req; +wire [1 :0] icc_arb_tag_wen; +wire icc_clk; +wire icc_clk_en; +wire icc_cnt_done; +wire icc_cnt_en; +wire icc_cnt_start; +wire icc_cur_clr_vb; +wire icc_cur_data; +wire icc_cur_data0; +wire icc_cur_data1; +wire icc_cur_inv_all; +wire icc_cur_tag_rd; +wire icc_cur_tag_wt; +wire icc_cur_wfvb; +wire icc_cur_wfvb0; +wire icc_cur_wfvb1; +wire icc_fsm_clk; +wire icc_fsm_clk_en; +wire icc_req_cln; +wire icc_req_inv; +wire icc_req_vld; +wire [26:0] icc_vb_addr; +wire icc_vb_clr_vld; +wire icc_vb_create_en; +wire [63:0] icc_vb_data; +wire [1 :0] icc_vb_data_cnt; +wire icc_vb_data_create; +wire icc_vb_line_dirty; +wire icc_xx_idle; +wire ifu_lsu_warm_up; +wire inv_all_setway; +wire line_dirty; +wire lsu_cp0_icc_done; +wire lsu_icc_no_op; +wire pad_yy_icg_scan_en; +wire setway_dirty; +wire [9 :0] tag_idx; +wire tag_wen; +wire type_all; +wire type_setway; +wire vb_icc_empty; +wire vb_icc_grant; +wire way0_dirty; +wire way1_dirty; +wire [1 :0] way_sel; + + +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +parameter ICC_IDLE = 4'b0000; +parameter ICC_TAG_RD = 4'b0001; +parameter ICC_TAG_WEN = 4'b0010; +parameter ICC_TAG_WT = 4'b0011; +parameter ICC_CHECK = 4'b0100; +parameter ICC_WFVB_W0 = 4'b0101; +parameter ICC_DATA_W0 = 4'b0110; +parameter ICC_WFVB_W1 = 4'b0111; +parameter ICC_DATA_W1 = 4'b1000; +parameter ICC_INV_ALL = 4'b1001; +parameter ICC_CLR_VB = 4'b1010; + +parameter ICC_ALL = 2'b00; +parameter SETWAY = 2'b01; +parameter VA = 2'b10; + +always@(posedge icc_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + icc_cur_state[3:0] <= ICC_IDLE; + else + icc_cur_state[3:0] <= icc_next_state[3:0]; +end + +assign icc_req_vld = cp0_lsu_icc_req; + +assign icc_req_inv = cp0_lsu_icc_op[0]; +assign icc_req_cln = cp0_lsu_icc_op[1]; +//assign icc_req_icln = icc_req_inv & icc_req_cln; + +assign type_all = cp0_lsu_icc_type[1:0] == ICC_ALL; +assign type_setway = cp0_lsu_icc_type[1:0] == SETWAY; + +assign inv_all_setway = icc_req_inv & !icc_req_cln & (type_all | type_setway); + +assign lsu_icc_no_op = 1'b1; + +// &CombBeg; @68 +always @( inv_all_setway + or data_rd_last + or type_all + or icc_cnt_done + or way1_dirty + or icc_req_vld + or icc_req_cln + or icc_cur_state[3:0] + or way0_dirty + or vb_icc_empty + or lsu_icc_no_op + or line_dirty + or vb_icc_grant) +begin + case (icc_cur_state[3:0]) + ICC_IDLE: begin + if (icc_req_vld & lsu_icc_no_op) + icc_next_state[3:0] = inv_all_setway ? ICC_INV_ALL : ICC_TAG_RD; + else + icc_next_state[3:0] = ICC_IDLE; + end + ICC_INV_ALL: begin + if (icc_cnt_done) + icc_next_state[3:0] = ICC_CLR_VB; + else + icc_next_state[3:0] = ICC_INV_ALL; + end + ICC_TAG_RD: begin + icc_next_state[3:0] = ICC_TAG_WEN; + end + ICC_TAG_WEN: begin + icc_next_state[3:0] = ICC_CHECK; + end + ICC_CHECK: begin + if (icc_req_cln & line_dirty) + icc_next_state[3:0] = way0_dirty ? ICC_WFVB_W0 : ICC_WFVB_W1; + else + icc_next_state[3:0] = ICC_TAG_WT; + end + ICC_WFVB_W0: begin + if (vb_icc_grant) + icc_next_state[3:0] = ICC_DATA_W0; + else + icc_next_state[3:0] = ICC_WFVB_W0; + end + ICC_DATA_W0: begin + if (data_rd_last) + icc_next_state[3:0] = (type_all & way1_dirty) ? ICC_WFVB_W1 : ICC_TAG_WT; + else + icc_next_state[3:0] = ICC_DATA_W0; + end + ICC_WFVB_W1: begin + if (vb_icc_grant) + icc_next_state[3:0] = ICC_DATA_W1; + else + icc_next_state[3:0] = ICC_WFVB_W1; + end + ICC_DATA_W1: begin + if (data_rd_last) + icc_next_state[3:0] = ICC_TAG_WT; + else + icc_next_state[3:0] = ICC_DATA_W1; + end + ICC_TAG_WT: begin + if (icc_cnt_done) + icc_next_state[3:0] = ICC_CLR_VB; + else + icc_next_state[3:0] = ICC_TAG_RD; + end + ICC_CLR_VB: begin + if (vb_icc_empty) + icc_next_state[3:0] = ICC_IDLE; + else + icc_next_state[3:0] = ICC_CLR_VB; + end + default: icc_next_state[3:0] = ICC_IDLE; + endcase +// &CombEnd; @132 +end + +assign icc_xx_idle = icc_cur_state[3:0] == ICC_IDLE; +assign icc_cur_wfvb0 = icc_cur_state[3:0] == ICC_WFVB_W0; +assign icc_cur_data0 = icc_cur_state[3:0] == ICC_DATA_W0; +assign icc_cur_wfvb1 = icc_cur_state[3:0] == ICC_WFVB_W1; +assign icc_cur_data1 = icc_cur_state[3:0] == ICC_DATA_W1; +assign icc_cur_inv_all = icc_cur_state[3:0] == ICC_INV_ALL; +assign icc_cur_tag_rd = icc_cur_state[3:0] == ICC_TAG_RD; +assign icc_cur_tag_wt = icc_cur_state[3:0] == ICC_TAG_WT; +assign icc_cur_clr_vb = icc_cur_state[3:0] == ICC_CLR_VB; + +assign icc_cur_wfvb = icc_cur_wfvb0 | icc_cur_wfvb1; +assign icc_cur_data = icc_cur_data0 | icc_cur_data1; + +assign icc_cnt_en = icc_cur_inv_all | icc_cur_tag_wt; + +assign icc_cnt_start = (icc_cur_state[3:0] == ICC_IDLE) & icc_req_vld; + +always@(posedge icc_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + icc_cnt[9:0] <= 10'b0; + else if (icc_cnt_start) + icc_cnt[9:0] <= type_all ? {10{1'b1}} : {10{1'b0}}; + else if (icc_cnt_en) + icc_cnt[9:0] <= icc_cnt[9:0] - 10'b1; +end + +assign icc_cnt_done = icc_cnt[D_TAG_INDEX_LEN-1:0] == {D_TAG_INDEX_LEN{1'b0}}; + +assign lsu_cp0_icc_done = vb_icc_empty & icc_cur_clr_vb; + +//================================================ +// dcache request +//================================================ +// &Force("bus","cp0_lsu_icc_addr",31,0); @168 +assign cp0_way[1:0] = {cp0_lsu_icc_addr[31],~cp0_lsu_icc_addr[31]}; +assign cp0_set[9:0] = cp0_lsu_icc_addr[14:5]; + +assign way_sel[1:0] = type_setway ? cp0_way[1:0] : 2'b11; + +assign way0_dirty = dc_icc_way0_dirty & way_sel[0]; +assign way1_dirty = dc_icc_way1_dirty & way_sel[1]; +assign all_dirty = way0_dirty | way1_dirty; +assign setway_dirty = |(cp0_way[1:0] & {way1_dirty, way0_dirty}); +assign line_dirty = type_all ? all_dirty : setway_dirty; + +assign tag_idx[9:0] = type_setway + ? cp0_set[9:0] + : icc_cnt[9:0]; + +//tag_req +assign tag_wen = icc_cur_inv_all | + icc_cur_tag_wt & icc_req_inv; + +assign icc_arb_tag_req = tag_wen | + icc_cur_tag_rd; + +assign icc_arb_tag_wen[1:0] = {2{tag_wen}} & way_sel[1:0]; +assign icc_arb_tag_din[22:0] = 23'b0; +assign icc_arb_tag_idx[9:0] = tag_idx[9:0]; + +//dirty_req +assign dirty_wen = icc_cur_inv_all & type_all | + icc_cur_tag_wt & icc_req_cln; + +assign fifo_wen = type_all & icc_req_inv & dirty_wen; + +assign icc_arb_dirty_req = dirty_wen | + icc_cur_tag_rd; + +assign icc_arb_dirty_wen[2:0] = {fifo_wen, {2{dirty_wen}} & way_sel[1:0]}; +assign icc_arb_dirty_din[2:0] = 3'b0; +assign icc_arb_dirty_idx[9:0] = tag_idx[9:0]; + +//data_req +assign icc_arb_data_req = icc_cur_data; +assign icc_arb_data_way[1:0] = way_sel[1:0]; +assign icc_arb_data_wen[3:0] = 4'b0; +assign icc_arb_data_din[63:0] = 64'b0; +assign icc_arb_data_idx[11:0] = {tag_idx[9:0],data_offset[1:0]}; +assign icc_arb_data_bank[1:0] = 2'b11; + +//assign icc_arb_dcache_sel = icc_cur_data | icc_cur_inv_all | icc_cur_tag_wt | icc_cur_tag_rd; + + +//================================================ +// VB request +//================================================ + +always@(posedge icc_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + icc_data_vld <= 1'b0; + else + icc_data_vld <= arb_icc_data_grant & icc_cur_data; +end + +always@(posedge icc_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + icc_data_way0 <= 1'b0; + else if (vb_icc_grant & icc_cur_wfvb0) + icc_data_way0 <= 1'b1; + else if (vb_icc_grant & icc_cur_wfvb1) + icc_data_way0 <= 1'b0; +end + +always@(posedge icc_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + data_offset[1:0] <= 2'b0; + data_offset_f[1:0] <= 2'b0; + end + else if (icc_cur_wfvb & vb_icc_grant) begin + data_offset[1:0] <= 2'b0; + data_offset_f[1:0] <= 2'b0; + end + else if (icc_cur_data) begin + data_offset[1:0] <= data_offset[1:0] + 2'b1; + data_offset_f[1:0] <= data_offset[1:0]; + end +end + +assign data_rd_last = data_offset[1:0] == 2'b11; + +// &Force("bus", "dc_icc_way0_tag", 21,0); @263 +// &Force("bus", "dc_icc_way1_tag", 21,0); @264 + +always@(posedge icc_clk) +begin + if (ifu_lsu_warm_up) + way1_tag[21:0] <= {22{1'b0}}; + else if ((icc_cur_state[3:0] == ICC_TAG_WEN) & way1_dirty) + way1_tag[21:0] <= dc_icc_way1_tag[21:0]; +end + +assign icc_vb_create_en = icc_cur_wfvb; +assign icc_vb_addr[26:0] = icc_cur_wfvb0 ? {dc_icc_way0_tag[D_TAG_TAG_LEN-1:0], tag_idx[D_TAG_INDEX_LEN-1:0]} + : {way1_tag[D_TAG_TAG_LEN-1:0], tag_idx[D_TAG_INDEX_LEN-1:0]}; + +assign icc_vb_data_create = icc_data_vld; +assign icc_vb_data[63:0] = icc_data_way0 ? dc_icc_way0_data[63:0] : dc_icc_way1_data[63:0]; +assign icc_vb_line_dirty = 1'b1; +assign icc_vb_data_cnt[1:0] = data_offset_f[1:0]; + +assign icc_vb_clr_vld = icc_cur_clr_vb; + +assign icc_fsm_clk_en = icc_req_vld | !(icc_cur_state[3:0] == ICC_IDLE); +// &Instance("gated_clk_cell", "x_icc_fsm_gated_clk"); @298 +gated_clk_cell x_icc_fsm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (icc_fsm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (icc_fsm_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @299 +// .external_en (1'b0), @300 +// .global_en (1'b1), @301 +// .module_en (cp0_lsu_icg_en ), @302 +// .local_en (icc_fsm_clk_en), @303 +// .clk_out (icc_fsm_clk)); @304 + +assign icc_clk_en = (icc_cur_state[3:0] == ICC_TAG_WEN) & way1_dirty | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_icc_dp_gated_clk"); @307 +gated_clk_cell x_icc_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (icc_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (icc_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @308 +// .external_en (1'b0), @309 +// .global_en (1'b1), @310 +// .module_en (cp0_lsu_icg_en ), @311 +// .local_en (icc_clk_en), @312 +// .clk_out (icc_clk)); @313 + +// &ModuleEnd; @315 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lfb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lfb.v new file mode 100644 index 0000000000000000000000000000000000000000..ebdcbc7074fd938a46e8a85abff1677995be275d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lfb.v @@ -0,0 +1,648 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_lfb( + cp0_lsu_icg_en, + cpurst_b, + dahbif_lfb_acc_err, + dahbif_lfb_cmplt, + dahbif_lfb_data, + dahbif_lfb_grant, + dc_lfb_addr, + dc_lfb_buf, + dc_lfb_ca, + dc_lfb_ca_raw, + dc_lfb_create_en, + dc_lfb_create_en_gate, + dc_lfb_inst_ld, + dc_lfb_lock_trans, + dc_lfb_lr_inst, + dc_lfb_mach_mode, + dc_lfb_size, + dc_xx_addr, + forever_cpuclk, + ifu_lsu_warm_up, + lfb_arb_data_bank, + lfb_arb_data_din, + lfb_arb_data_idx, + lfb_arb_data_req, + lfb_arb_data_way, + lfb_arb_data_wen, + lfb_arb_dcache_sel, + lfb_arb_dirty_din, + lfb_arb_dirty_idx, + lfb_arb_dirty_req, + lfb_arb_dirty_wen, + lfb_arb_tag_din, + lfb_arb_tag_idx, + lfb_arb_tag_req, + lfb_arb_tag_wen, + lfb_dahbif_addr, + lfb_dahbif_burst, + lfb_dahbif_lock, + lfb_dahbif_lr_inst, + lfb_dahbif_prot, + lfb_dahbif_req, + lfb_dahbif_size, + lfb_dbginfo, + lfb_dc_async_expt, + lfb_dc_busy, + lfb_dc_hit_idx, + lfb_dc_ld_cmplt, + lfb_dc_ld_data, + lfb_dc_ld_data_vld, + lfb_dc_pop_en, + lfb_rdl_index, + lfb_rdl_start, + lfb_rdl_start_gate, + lfb_stb_done, + lfb_stb_err, + lfb_stb_fifo, + lfb_stb_fifo_update, + lfb_xx_idle, + pad_yy_icg_scan_en, + rdl_lfb_done, + rdl_lfb_fifo, + rdl_lfb_fifo_save, + rdl_lfb_grant, + rtu_yy_xx_async_flush +); + +// &Ports; @21 +input cp0_lsu_icg_en; +input cpurst_b; +input dahbif_lfb_acc_err; +input dahbif_lfb_cmplt; +input [31:0] dahbif_lfb_data; +input dahbif_lfb_grant; +input [31:0] dc_lfb_addr; +input dc_lfb_buf; +input dc_lfb_ca; +input dc_lfb_ca_raw; +input dc_lfb_create_en; +input dc_lfb_create_en_gate; +input dc_lfb_inst_ld; +input dc_lfb_lock_trans; +input dc_lfb_lr_inst; +input dc_lfb_mach_mode; +input [1 :0] dc_lfb_size; +input [31:0] dc_xx_addr; +input forever_cpuclk; +input ifu_lsu_warm_up; +input pad_yy_icg_scan_en; +input rdl_lfb_done; +input rdl_lfb_fifo; +input rdl_lfb_fifo_save; +input rdl_lfb_grant; +input rtu_yy_xx_async_flush; +output [1 :0] lfb_arb_data_bank; +output [63:0] lfb_arb_data_din; +output [11:0] lfb_arb_data_idx; +output lfb_arb_data_req; +output [1 :0] lfb_arb_data_way; +output [3 :0] lfb_arb_data_wen; +output lfb_arb_dcache_sel; +output [2 :0] lfb_arb_dirty_din; +output [9 :0] lfb_arb_dirty_idx; +output lfb_arb_dirty_req; +output [2 :0] lfb_arb_dirty_wen; +output [22:0] lfb_arb_tag_din; +output [9 :0] lfb_arb_tag_idx; +output lfb_arb_tag_req; +output [1 :0] lfb_arb_tag_wen; +output [31:0] lfb_dahbif_addr; +output [2 :0] lfb_dahbif_burst; +output lfb_dahbif_lock; +output lfb_dahbif_lr_inst; +output [3 :0] lfb_dahbif_prot; +output lfb_dahbif_req; +output [1 :0] lfb_dahbif_size; +output [3 :0] lfb_dbginfo; +output lfb_dc_async_expt; +output lfb_dc_busy; +output lfb_dc_hit_idx; +output lfb_dc_ld_cmplt; +output [31:0] lfb_dc_ld_data; +output lfb_dc_ld_data_vld; +output lfb_dc_pop_en; +output [9 :0] lfb_rdl_index; +output lfb_rdl_start; +output lfb_rdl_start_gate; +output lfb_stb_done; +output lfb_stb_err; +output lfb_stb_fifo; +output lfb_stb_fifo_update; +output lfb_xx_idle; + +// &Regs; @22 +reg [31:0] lfb_addr; +reg lfb_buf; +reg lfb_ca; +reg lfb_cmplt; +reg [2 :0] lfb_cur_state; +reg [31:0] lfb_data; +reg lfb_fifo; +reg lfb_ld; +reg lfb_lock; +reg lfb_lr; +reg lfb_mach_mode; +reg [2 :0] lfb_next_state; +reg lfb_prot_ca; +reg [1 :0] lfb_size; +reg [3 :0] ref_cur_state; +reg [3 :0] ref_next_state; +reg refill_vld; + +// &Wires; @23 +wire cp0_lsu_icg_en; +wire cpurst_b; +wire dahbif_lfb_acc_err; +wire dahbif_lfb_cmplt; +wire [31:0] dahbif_lfb_data; +wire dahbif_lfb_grant; +wire [31:0] dc_lfb_addr; +wire dc_lfb_buf; +wire dc_lfb_ca; +wire dc_lfb_ca_raw; +wire dc_lfb_create_en; +wire dc_lfb_create_en_gate; +wire dc_lfb_inst_ld; +wire dc_lfb_lock_trans; +wire dc_lfb_lr_inst; +wire dc_lfb_mach_mode; +wire [1 :0] dc_lfb_size; +wire [31:0] dc_xx_addr; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire [1 :0] lfb_arb_data_bank; +wire [63:0] lfb_arb_data_din; +wire [11:0] lfb_arb_data_idx; +wire lfb_arb_data_req; +wire [1 :0] lfb_arb_data_way; +wire [3 :0] lfb_arb_data_wen; +wire lfb_arb_dcache_sel; +wire [2 :0] lfb_arb_dirty_din; +wire [9 :0] lfb_arb_dirty_idx; +wire lfb_arb_dirty_req; +wire [2 :0] lfb_arb_dirty_wen; +wire [22:0] lfb_arb_tag_din; +wire [9 :0] lfb_arb_tag_idx; +wire lfb_arb_tag_req; +wire [1 :0] lfb_arb_tag_wen; +wire lfb_cur_idle; +wire [31:0] lfb_dahbif_addr; +wire [2 :0] lfb_dahbif_burst; +wire lfb_dahbif_lock; +wire lfb_dahbif_lr_inst; +wire [3 :0] lfb_dahbif_prot; +wire lfb_dahbif_req; +wire [1 :0] lfb_dahbif_size; +wire lfb_data_clk; +wire lfb_data_clk_en; +wire [3 :0] lfb_dbginfo; +wire lfb_dc_async_expt; +wire lfb_dc_busy; +wire lfb_dc_hit_idx; +wire lfb_dc_ld_cmplt; +wire [31:0] lfb_dc_ld_data; +wire lfb_dc_ld_data_vld; +wire lfb_dc_pop_en; +wire lfb_dp_clk; +wire lfb_dp_clk_en; +wire lfb_fld_inst; +wire lfb_fsm_clk; +wire lfb_fsm_clk_en; +wire [2 :0] lfb_offset; +wire [9 :0] lfb_rdl_index; +wire lfb_rdl_start; +wire lfb_rdl_start_gate; +wire lfb_stb_done; +wire lfb_stb_err; +wire lfb_stb_fifo; +wire lfb_stb_fifo_update; +wire lfb_xx_idle; +wire pad_yy_icg_scan_en; +wire rdl_lfb_done; +wire rdl_lfb_fifo; +wire rdl_lfb_fifo_save; +wire rdl_lfb_grant; +wire refill_done; +wire refill_err; +wire refill_first; +wire refill_idle; +wire refill_start; +wire rtu_yy_xx_async_flush; +wire vld_set; + + +parameter D_DATA_INDEX_LEN = `D_DATA_INDEX_WIDTH; +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +//================================================ +// LFB FSM +//================================================ +parameter LFB_IDLE = 3'b000; +parameter LFB_RDL = 3'b001; +parameter LFB_REQ = 3'b010; +parameter LFB_WFC = 3'b011; +parameter LFB_REF = 3'b100; +parameter LFB_WRDL = 3'b101; +parameter LFB_WFC2 = 3'b110; + +always@(posedge lfb_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + lfb_cur_state[2:0] <= LFB_IDLE; + else if (rtu_yy_xx_async_flush) + lfb_cur_state[2:0] <= LFB_IDLE; + else + lfb_cur_state[2:0] <= lfb_next_state[2:0]; +end + +// &CombBeg; @50 +always @( dc_lfb_ca + or rdl_lfb_done + or dahbif_lfb_acc_err + or lfb_cur_state[2:0] + or lfb_fld_inst + or dahbif_lfb_cmplt + or rdl_lfb_grant + or refill_done + or dc_lfb_create_en + or dahbif_lfb_grant + or lfb_ca) +begin + case(lfb_cur_state[2:0]) + LFB_IDLE: begin + if (dc_lfb_create_en)begin + if (dc_lfb_ca) + lfb_next_state[2:0] = rdl_lfb_grant ? LFB_RDL : LFB_WRDL; + else + lfb_next_state[2:0] = LFB_REQ; + end + else + lfb_next_state[2:0] = LFB_IDLE; + end + LFB_WRDL: begin + if (rdl_lfb_grant) + lfb_next_state[2:0] = LFB_RDL; + else + lfb_next_state[2:0] = LFB_WRDL; + end + LFB_RDL: begin + if (rdl_lfb_done) + lfb_next_state[2:0] = LFB_REQ; + else + lfb_next_state[2:0] = LFB_RDL; + end + LFB_REQ: begin + if (dahbif_lfb_grant) + lfb_next_state[2:0] = LFB_WFC; + else + lfb_next_state[2:0] = LFB_REQ; + end + LFB_WFC: begin + if (dahbif_lfb_cmplt) + lfb_next_state[2:0] = (!lfb_ca & lfb_fld_inst & !dahbif_lfb_acc_err) ? LFB_WFC2 : LFB_REF; + else + lfb_next_state[2:0] = LFB_WFC; + end + LFB_WFC2: begin + if (dahbif_lfb_cmplt) + lfb_next_state[2:0] = LFB_REF; + else + lfb_next_state[2:0] = LFB_WFC2; + end + LFB_REF: begin + if (!lfb_ca | refill_done) + lfb_next_state[2:0] = LFB_IDLE; + else + lfb_next_state[2:0] = LFB_REF; + end + default: lfb_next_state[2:0] = LFB_IDLE; + endcase +// &CombEnd; @100 +end + +assign lfb_rdl_start = dc_lfb_create_en & dc_lfb_ca | + (lfb_cur_state[2:0] == LFB_WRDL); + +assign lfb_rdl_start_gate = dc_lfb_create_en_gate & dc_lfb_ca | + (lfb_cur_state[2:0] == LFB_WRDL); + +assign lfb_stb_done = (lfb_cur_state[2:0] == LFB_REF) & refill_done; +assign lfb_stb_err = (lfb_cur_state[2:0] == LFB_REF) & refill_err; + +assign lfb_cur_idle = lfb_cur_state[2:0] == LFB_IDLE; +assign lfb_dc_busy = !lfb_cur_idle; +assign lfb_xx_idle = lfb_cur_idle; + +assign lfb_dc_hit_idx = (dc_xx_addr[D_TAG_INDEX_LEN+4:5] == lfb_addr[D_TAG_INDEX_LEN+4:5]) & + !lfb_cur_idle & lfb_ca; + +// &Force("bus","dc_xx_addr",31,0); @118 + +assign lfb_dc_pop_en = (lfb_cur_state[2:0] == LFB_REF) & (!lfb_ca | refill_done); + +always@(posedge lfb_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + lfb_fifo <= 1'b0; + else if (rdl_lfb_fifo_save) + lfb_fifo <= rdl_lfb_fifo; +end + +assign lfb_stb_fifo_update = rdl_lfb_fifo_save; +assign lfb_stb_fifo = rdl_lfb_fifo; + +//================================================ +// refill FSM +//================================================ +assign refill_start = (lfb_cur_state[2:0] == LFB_WFC) & dahbif_lfb_cmplt & lfb_ca; + +parameter REF_IDLE = 4'b1000; +parameter REF_FIRST = 4'b0000; +parameter REF_SECND = 4'b0001; +parameter REF_THIRD = 4'b0010; +parameter REF_FOUR = 4'b0011; +parameter REF_FIVE = 4'b0100; +parameter REF_SIX = 4'b0101; +parameter REF_SEVEN = 4'b0110; +parameter REF_EIGHT = 4'b0111; +parameter REF_ERR = 4'b1001; + +always@(posedge lfb_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ref_cur_state[3:0] <= REF_IDLE; + else if (rtu_yy_xx_async_flush) + ref_cur_state[3:0] <= REF_IDLE; + else + ref_cur_state[3:0] <= ref_next_state[3:0]; +end + +// &CombBeg; @159 +always @( dahbif_lfb_acc_err + or ref_cur_state[3:0] + or dahbif_lfb_cmplt + or refill_start) +begin + case(ref_cur_state[3:0]) + REF_IDLE: begin + if (refill_start) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_FIRST; + else + ref_next_state[3:0] = REF_IDLE; + end + REF_FIRST: begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_SECND; + else + ref_next_state[3:0] = REF_FIRST; + end + REF_SECND: begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_THIRD; + else + ref_next_state[3:0] = REF_SECND; + end + REF_THIRD: begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_FOUR; + else + ref_next_state[3:0] = REF_THIRD; + end + REF_FOUR: begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_FIVE; + else + ref_next_state[3:0] = REF_FOUR; + end + REF_FIVE: begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_SIX; + else + ref_next_state[3:0] = REF_FIVE; + end + REF_SIX : begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_SEVEN; + else + ref_next_state[3:0] = REF_SIX; + end + REF_SEVEN:begin + if (dahbif_lfb_cmplt) + ref_next_state[3:0] = dahbif_lfb_acc_err ? REF_ERR : REF_EIGHT; + else + ref_next_state[3:0] = REF_SEVEN; + end + REF_EIGHT: begin + ref_next_state[3:0] = REF_IDLE; + end + REF_ERR: begin + ref_next_state[3:0] = REF_IDLE; + end + default: ref_next_state[3:0] = REF_IDLE; + endcase +// &CombEnd; @217 +end + +always@(posedge lfb_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + refill_vld <= 1'b0; + else if (((lfb_cur_state[2:0] == LFB_REF) | (lfb_cur_state[2:0] == LFB_WFC)) & lfb_ca) + refill_vld <= dahbif_lfb_cmplt & !dahbif_lfb_acc_err; +end + +assign refill_idle = ref_cur_state[3:0] == REF_IDLE; +assign refill_first = ref_cur_state[3:0] == REF_FIRST; +assign refill_done = (ref_cur_state[3:0] == REF_EIGHT) | + (ref_cur_state[3:0] == REF_ERR); +assign refill_err = (ref_cur_state[3:0] == REF_ERR); +assign vld_set = (ref_cur_state[3:0] == REF_EIGHT); + +assign lfb_arb_tag_req = ((ref_cur_state[3:0] == REF_FIRST) | + (ref_cur_state[3:0] == REF_EIGHT)) & refill_vld; +assign lfb_arb_tag_wen[1:0] = {lfb_fifo, !lfb_fifo}; +assign lfb_arb_tag_din[22:0] = {vld_set,{(22-D_TAG_TAG_LEN){1'b0}}, lfb_addr[31:D_TAG_INDEX_LEN+5]}; +assign lfb_arb_tag_idx[9:0] = lfb_addr[14:5]; + +assign lfb_arb_dirty_req = (ref_cur_state[3:0] == REF_EIGHT) & refill_vld; +assign lfb_arb_dirty_wen[2:0] = {1'b1, lfb_fifo, !lfb_fifo}; +assign lfb_arb_dirty_din[2:0] = {!lfb_fifo,2'b0}; +assign lfb_arb_dirty_idx[9:0] = lfb_addr[14:5]; + +// &Force("output", "lfb_arb_dcache_sel"); @249 + +assign lfb_arb_data_req = lfb_arb_dcache_sel & refill_vld; +assign lfb_arb_data_way[1:0] = {lfb_fifo, !lfb_fifo}; +assign lfb_arb_data_bank[1:0] = {lfb_offset[0], !lfb_offset[0]}; +assign lfb_arb_data_wen[3:0] = 4'b1111; +assign lfb_arb_data_din[63:0] = {lfb_data[31:0],lfb_data[31:0]}; +assign lfb_arb_data_idx[11:0] = {lfb_addr[14:5], lfb_offset[2:1]}; +assign lfb_offset[2:0] = lfb_addr[4:2] + ref_cur_state[2:0]; +assign lfb_arb_dcache_sel = !(ref_cur_state[3:0] == REF_IDLE | ref_cur_state[3:0] == REF_ERR) ; + +//================================================ +// Request bus +//================================================ +assign lfb_dahbif_req = (lfb_cur_state[2:0] == LFB_REQ); +assign lfb_dahbif_addr[31:0] = lfb_ca ? {lfb_addr[31:2],2'b00} : lfb_addr[31:0]; +assign lfb_dahbif_size[1:0] = lfb_ca ? 2'b10 : lfb_size[1:0]; +assign lfb_dahbif_prot[3:0] = {lfb_prot_ca,lfb_buf,lfb_mach_mode,1'b1}; +assign lfb_dahbif_lock = lfb_lock; +assign lfb_dahbif_lr_inst = lfb_lr; +assign lfb_dahbif_burst[2:0] = lfb_ca ? 3'b100 : (lfb_fld_inst ? 3'b001 : 3'b000); //WRAP8 + +//================================================ +// LFB content +//================================================ + +always@(posedge lfb_dp_clk) +begin + if (dc_lfb_create_en | ifu_lsu_warm_up) begin + lfb_addr[31:0] <= dc_lfb_addr[31:0]; + lfb_ca <= dc_lfb_ca; + lfb_prot_ca <= dc_lfb_ca_raw; + lfb_buf <= dc_lfb_buf; + lfb_mach_mode <= dc_lfb_mach_mode; + lfb_size[1:0] <= dc_lfb_size[1:0]; + lfb_lock <= dc_lfb_lock_trans; + lfb_ld <= dc_lfb_inst_ld; + lfb_lr <= dc_lfb_lr_inst; + end +end + +assign lfb_fld_inst = lfb_ld & lfb_size[1:0] == 2'b11; + + +always@(posedge lfb_data_clk) +begin + if (dahbif_lfb_cmplt & !dahbif_lfb_acc_err | ifu_lsu_warm_up) + lfb_data[31:0] <= dahbif_lfb_data[31:0]; +end + +assign lfb_dc_ld_data[31:0] = lfb_data[31:0]; + +assign lfb_rdl_index[9:0] = (lfb_cur_state[2:0] == LFB_WRDL) + ? lfb_addr[14:5] + : dc_lfb_addr[14:5]; + +//================================================ +// CMPLT and data vld +//================================================ + +always@(posedge lfb_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + lfb_cmplt <= 1'b0; + else if (dahbif_lfb_cmplt & lfb_ld & + (lfb_fld_inst & lfb_ca & (refill_idle & refill_start & dahbif_lfb_acc_err | refill_first) | + !lfb_fld_inst & (lfb_cur_state[2:0] == LFB_WFC) | + lfb_fld_inst & !lfb_ca & ((lfb_cur_state[2:0] == LFB_WFC) & dahbif_lfb_acc_err | + (lfb_cur_state[2:0] == LFB_WFC2)))) + lfb_cmplt <= 1'b1; + else + lfb_cmplt <= 1'b0; +end + +assign lfb_dc_ld_cmplt = lfb_cmplt; +assign lfb_dc_ld_data_vld = lfb_cmplt; + +assign lfb_dc_async_expt = dahbif_lfb_cmplt & dahbif_lfb_acc_err & lfb_ld; + + +//========================================================== +// gated cell +//========================================================== +assign lfb_fsm_clk_en = dc_lfb_create_en_gate | + lfb_cmplt | + !(lfb_cur_state[2:0] == LFB_IDLE) | + !(ref_cur_state[3:0] == REF_IDLE); + +// &Instance("gated_clk_cell", "x_pa_lsu_lfb_fsm_gated_clk"); @396 +gated_clk_cell x_pa_lsu_lfb_fsm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lfb_fsm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (lfb_fsm_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @397 +// .external_en (1'b0), @398 +// .global_en (1'b1), @399 +// .module_en (cp0_lsu_icg_en ), @400 +// .local_en (lfb_fsm_clk_en), @401 +// .clk_out (lfb_fsm_clk)); @402 + +assign lfb_dp_clk_en = dc_lfb_create_en_gate | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_lfb_dp_gated_clk"); @405 +gated_clk_cell x_pa_lsu_lfb_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lfb_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (lfb_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @406 +// .external_en (1'b0), @407 +// .global_en (1'b1), @408 +// .module_en (cp0_lsu_icg_en ), @409 +// .local_en (lfb_dp_clk_en), @410 +// .clk_out (lfb_dp_clk)); @411 + +assign lfb_data_clk_en = dahbif_lfb_cmplt & !dahbif_lfb_acc_err | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_lfb_data_gated_clk"); @414 +gated_clk_cell x_pa_lsu_lfb_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lfb_data_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (lfb_data_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @415 +// .external_en (1'b0), @416 +// .global_en (1'b1), @417 +// .module_en (cp0_lsu_icg_en ), @418 +// .local_en (lfb_data_clk_en), @419 +// .clk_out (lfb_data_clk)); @420 + +// &Instance("gated_clk_cell", "x_pa_lsu_lfb_data_ff_gated_clk"); @424 +// &Connect(.clk_in (forever_cpuclk), @425 +// .external_en (1'b0), @426 +// .global_en (1'b1), @427 +// .module_en (cp0_lsu_icg_en ), @428 +// .local_en (lfb_data_ff_clk_en), @429 +// .clk_out (lfb_data_ff_clk)); @430 + +assign lfb_dbginfo[3:0] = {refill_vld,lfb_cur_state[2:0]}; +// &ModuleEnd; @434 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lm.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lm.v new file mode 100644 index 0000000000000000000000000000000000000000..3981febb5f8c995f3cebb70fca4ca93964a07347 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_lm.v @@ -0,0 +1,141 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_lm( + cp0_lsu_icg_en, + cpurst_b, + forever_cpuclk, + ifu_lsu_warm_up, + lm_clr, + lm_lr_bus, + lm_pass, + lm_sc_bus, + lm_set, + lm_set_gate, + pad_yy_icg_scan_en, + rtu_lsu_expt_ack, + rtu_lsu_expt_exit +); + +// &Ports; @21 +input cp0_lsu_icg_en; +input cpurst_b; +input forever_cpuclk; +input ifu_lsu_warm_up; +input lm_clr; +input [33:0] lm_lr_bus; +input [33:0] lm_sc_bus; +input lm_set; +input lm_set_gate; +input pad_yy_icg_scan_en; +input rtu_lsu_expt_ack; +input rtu_lsu_expt_exit; +output lm_pass; + +// &Regs; @22 +reg [33:0] lm_bus_f; +reg lm_cur_state; +reg lm_next_state; + +// &Wires; @23 +wire cp0_lsu_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire lm_clk; +wire lm_clk_en; +wire lm_clr; +wire [33:0] lm_lr_bus; +wire lm_pass; +wire [33:0] lm_sc_bus; +wire lm_set; +wire lm_set_gate; +wire pad_yy_icg_scan_en; +wire rtu_lsu_expt_ack; +wire rtu_lsu_expt_exit; + + +parameter LM_OPEN = 1'b0; +parameter LM_EXCL = 1'b1; + +always@(posedge lm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + lm_cur_state <= LM_OPEN; + else + lm_cur_state <= lm_next_state; +end + +// &CombBeg; @36 +always @( rtu_lsu_expt_ack + or lm_clr + or lm_cur_state + or lm_set + or rtu_lsu_expt_exit) +begin + case (lm_cur_state) + LM_OPEN:begin + if (lm_set & !rtu_lsu_expt_ack & !rtu_lsu_expt_exit) + lm_next_state = LM_EXCL; + else + lm_next_state = LM_OPEN; + end + LM_EXCL:begin + if (rtu_lsu_expt_ack | rtu_lsu_expt_exit | lm_clr) + lm_next_state = LM_OPEN; + else + lm_next_state = LM_EXCL; + end + default: lm_next_state = LM_OPEN; + endcase +// &CombEnd; @52 +end + +always@(posedge lm_clk) +begin + if (ifu_lsu_warm_up) + lm_bus_f[33:0] <= 34'b0; + else if (lm_set) + lm_bus_f[33:0] <= lm_lr_bus[33:0]; +end + +assign lm_pass = lm_cur_state & (lm_bus_f[33:0] == lm_sc_bus[33:0]); + +assign lm_clk_en = lm_set_gate | (lm_cur_state == LM_EXCL) | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_lm_gated_clk"); @77 +gated_clk_cell x_pa_lsu_lm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (lm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (lm_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @78 +// .external_en (1'b0), @79 +// .global_en (1'b1), @80 +// .module_en (cp0_lsu_icg_en ), @81 +// .local_en (lm_clk_en), @82 +// .clk_out (lm_clk)); @83 + +// &ModuleEnd; @85 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ncb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ncb.v new file mode 100644 index 0000000000000000000000000000000000000000..1999362f80bb54ce7bdbfec9ab3fab2184e79cf5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_ncb.v @@ -0,0 +1,1254 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @19 +module pa_lsu_ncb( + ag_dc_buf, + ag_dc_bytes_vld, + ag_dc_ca, + ag_dc_dest_reg, + ag_dc_fls, + ag_dc_func, + ag_dc_lm_pass, + ag_dc_mach_mode, + ag_dc_ori_size, + ag_dc_pmp_expt, + ag_dc_sign_ext, + ag_dc_size, + ag_dc_so, + ag_dc_split, + ag_dc_split_first, + ag_dc_split_last, + ag_dc_src1_depd, + ag_dc_wdata_shift, + ag_ncb_addr, + ag_ncb_inst_vld, + ag_ncb_inst_vld_dp, + ag_ncb_src1_reg, + ag_ncb_st_data, + cp0_lsu_icg_en, + cp0_xx_async_expt_en, + cpurst_b, + da_xx_fwd_data, + da_xx_fwd_fls, + da_xx_fwd_preg, + da_xx_fwd_vld, + dahbif_ncb_acc_err, + dahbif_ncb_cmplt, + dahbif_ncb_data, + dahbif_ncb_grant, + dahbif_ncb_grant_2, + forever_cpuclk, + ifu_lsu_warm_up, + lsu_biu_amo_pmp_deny, + lsu_mb_ex2_uc_addr_2, + lsu_mb_ex2_uc_bytes_vld, + lsu_mb_ex2_uc_data, + lsu_mb_ex2_uc_data_vld, + lsu_mb_ex2_uc_data_vld_gate, + lsu_mb_ex2_uc_dest_reg, + lsu_mb_ex2_uc_fld, + lsu_mb_ex2_uc_fls, + lsu_mb_ex2_uc_lock, + lsu_mb_ex2_uc_sc_data_vld, + lsu_mb_ex2_uc_sign_ext, + lsu_mb_ex2_uc_size, + lsu_mb_ex2_uc_split, + lsu_mb_ex2_uc_split_last, + lsu_mb_ex2_uc_stall, + lsu_xx_ex2_uc_flush, + ncb_ag_async_expt_vld, + ncb_ag_async_ld_inst, + ncb_ag_async_mtval, + ncb_ag_pmp_ld_inst, + ncb_ag_pmp_mtval, + ncb_ag_stall, + ncb_dahbif_acc_deny, + ncb_dahbif_lock, + ncb_dahbif_lrsc, + ncb_dahbif_ncb_wb_addr, + ncb_dahbif_ncb_wb_sel, + ncb_dahbif_prot, + ncb_dahbif_req, + ncb_dahbif_req_dp, + ncb_dahbif_size, + ncb_dahbif_uc_ld_addr, + ncb_dahbif_wdata, + ncb_dahbif_write, + ncb_dbginfo, + ncb_xx_no_op, + pad_yy_icg_scan_en, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_lsu_sync_req, + rtu_yy_xx_async_flush +); + +// &Ports; @20 +input ag_dc_buf; +input [3 :0] ag_dc_bytes_vld; +input ag_dc_ca; +input [5 :0] ag_dc_dest_reg; +input ag_dc_fls; +input [3 :0] ag_dc_func; +input ag_dc_lm_pass; +input ag_dc_mach_mode; +input [1 :0] ag_dc_ori_size; +input ag_dc_pmp_expt; +input ag_dc_sign_ext; +input [1 :0] ag_dc_size; +input ag_dc_so; +input ag_dc_split; +input ag_dc_split_first; +input ag_dc_split_last; +input ag_dc_src1_depd; +input [2 :0] ag_dc_wdata_shift; +input [31:0] ag_ncb_addr; +input ag_ncb_inst_vld; +input ag_ncb_inst_vld_dp; +input [5 :0] ag_ncb_src1_reg; +input [31:0] ag_ncb_st_data; +input cp0_lsu_icg_en; +input cp0_xx_async_expt_en; +input cpurst_b; +input [31:0] da_xx_fwd_data; +input da_xx_fwd_fls; +input [5 :0] da_xx_fwd_preg; +input da_xx_fwd_vld; +input dahbif_ncb_acc_err; +input dahbif_ncb_cmplt; +input [31:0] dahbif_ncb_data; +input dahbif_ncb_grant; +input dahbif_ncb_grant_2; +input forever_cpuclk; +input ifu_lsu_warm_up; +input pad_yy_icg_scan_en; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_lsu_sync_req; +input rtu_yy_xx_async_flush; +output lsu_biu_amo_pmp_deny; +output lsu_mb_ex2_uc_addr_2; +output [3 :0] lsu_mb_ex2_uc_bytes_vld; +output [31:0] lsu_mb_ex2_uc_data; +output lsu_mb_ex2_uc_data_vld; +output lsu_mb_ex2_uc_data_vld_gate; +output [5 :0] lsu_mb_ex2_uc_dest_reg; +output lsu_mb_ex2_uc_fld; +output lsu_mb_ex2_uc_fls; +output lsu_mb_ex2_uc_lock; +output lsu_mb_ex2_uc_sc_data_vld; +output lsu_mb_ex2_uc_sign_ext; +output [1 :0] lsu_mb_ex2_uc_size; +output lsu_mb_ex2_uc_split; +output lsu_mb_ex2_uc_split_last; +output lsu_mb_ex2_uc_stall; +output lsu_xx_ex2_uc_flush; +output ncb_ag_async_expt_vld; +output ncb_ag_async_ld_inst; +output [31:0] ncb_ag_async_mtval; +output ncb_ag_pmp_ld_inst; +output [31:0] ncb_ag_pmp_mtval; +output ncb_ag_stall; +output ncb_dahbif_acc_deny; +output ncb_dahbif_lock; +output ncb_dahbif_lrsc; +output [31:0] ncb_dahbif_ncb_wb_addr; +output ncb_dahbif_ncb_wb_sel; +output [3 :0] ncb_dahbif_prot; +output ncb_dahbif_req; +output ncb_dahbif_req_dp; +output [1 :0] ncb_dahbif_size; +output [31:0] ncb_dahbif_uc_ld_addr; +output [31:0] ncb_dahbif_wdata; +output ncb_dahbif_write; +output [10:0] ncb_dbginfo; +output ncb_xx_no_op; + +// &Regs; @21 +reg [1 :0] bytes_vld_decode; +reg data_last; +reg [1 :0] nc_cur_state; +reg [1 :0] nc_next_state; +reg [31:0] ncb_addr; +reg [3 :0] ncb_bytes_vld; +reg [5 :0] ncb_dest_reg; +reg ncb_fls; +reg ncb_ld_inst; +reg ncb_lock; +reg ncb_lrsc; +reg [1 :0] ncb_ori_size; +reg ncb_pmp_expt; +reg [3 :0] ncb_prot; +reg ncb_sign_ext; +reg [1 :0] ncb_size; +reg ncb_split; +reg ncb_split_first; +reg ncb_split_last; +reg req_cnt; +reg uc_ex2_stall; +reg wb_addr_pmp_deny; +reg wb_addr_pop_ptr; +reg wb_addr_sc_fail; +reg wb_create_ptr; +reg wb_data_pop_ptr; +reg [31:0] wb_dbus_addr; +reg [5 :0] wb_dbus_dest_preg; +reg wb_dbus_fls; +reg wb_dbus_lock; +reg wb_dbus_lrsc; +reg [3 :0] wb_dbus_prot; +reg wb_dbus_req; +reg [1 :0] wb_dbus_size; +reg [31:0] wb_dbus_wdata_pre; + +// &Wires; @22 +wire ag_dc_buf; +wire [3 :0] ag_dc_bytes_vld; +wire ag_dc_ca; +wire [5 :0] ag_dc_dest_reg; +wire ag_dc_fls; +wire [3 :0] ag_dc_func; +wire ag_dc_lm_pass; +wire ag_dc_mach_mode; +wire [1 :0] ag_dc_ori_size; +wire ag_dc_pmp_expt; +wire ag_dc_sign_ext; +wire [1 :0] ag_dc_size; +wire ag_dc_so; +wire ag_dc_split; +wire ag_dc_split_first; +wire ag_dc_split_last; +wire ag_dc_src1_depd; +wire [2 :0] ag_dc_wdata_shift; +wire ag_dca_inst; +wire ag_ld_hit_wb; +wire ag_ld_hit_wb_f; +wire ag_ld_inst; +wire ag_ld_req; +wire ag_ld_req_dp; +wire ag_ld_sel; +wire ag_lock_inst; +wire ag_lr_inst; +wire ag_lrsc_inst; +wire [31:0] ag_ncb_addr; +wire ag_ncb_inst_vld; +wire ag_ncb_inst_vld_dp; +wire [5 :0] ag_ncb_src1_reg; +wire [31:0] ag_ncb_st_data; +wire [3 :0] ag_prot; +wire ag_sc_inst; +wire ag_st_inst; +wire ag_st_req; +wire ag_st_req_dp; +wire block_acc_en; +wire cp0_lsu_icg_en; +wire cp0_xx_async_expt_en; +wire cpurst_b; +wire [31:0] da_xx_fwd_data; +wire da_xx_fwd_fls; +wire [5 :0] da_xx_fwd_preg; +wire da_xx_fwd_vld; +wire dahbif_ncb_acc_err; +wire dahbif_ncb_cmplt; +wire [31:0] dahbif_ncb_data; +wire dahbif_ncb_grant; +wire dahbif_ncb_grant_2; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire [31:0] ld_data; +wire [1 :0] ld_hit_wb; +wire [1 :0] ld_hit_wb_f; +wire ld_sc_pass_data_vld; +wire ld_sc_pass_data_vld_gate; +wire ld_stall; +wire ld_stall_dp; +wire lock_stall; +wire lock_stall_dp; +wire lsu_biu_amo_pmp_deny; +wire lsu_ex2_addr_2; +wire [3 :0] lsu_ex2_bytes_vld; +wire lsu_ex2_data_vld; +wire lsu_ex2_data_vld_gate; +wire [5 :0] lsu_ex2_dest_reg; +wire lsu_ex2_fld; +wire lsu_ex2_fls; +wire lsu_ex2_lock; +wire lsu_ex2_sign_ext; +wire [1 :0] lsu_ex2_size; +wire lsu_ex2_split; +wire lsu_ex2_split_last; +wire lsu_mb_ex2_uc_addr_2; +wire [3 :0] lsu_mb_ex2_uc_bytes_vld; +wire [31:0] lsu_mb_ex2_uc_data; +wire lsu_mb_ex2_uc_data_vld; +wire lsu_mb_ex2_uc_data_vld_gate; +wire [5 :0] lsu_mb_ex2_uc_dest_reg; +wire lsu_mb_ex2_uc_fld; +wire lsu_mb_ex2_uc_fls; +wire lsu_mb_ex2_uc_lock; +wire lsu_mb_ex2_uc_sc_data_vld; +wire lsu_mb_ex2_uc_sign_ext; +wire [1 :0] lsu_mb_ex2_uc_size; +wire lsu_mb_ex2_uc_split; +wire lsu_mb_ex2_uc_split_last; +wire lsu_mb_ex2_uc_stall; +wire lsu_xx_ex2_uc_flush; +wire [31:0] nc_addr; +wire nc_burst; +wire [3 :0] nc_bytes_vld; +wire nc_cur_err; +wire nc_cur_rdy; +wire nc_cur_rdy_dp; +wire nc_cur_wfc; +wire nc_cur_wfg; +wire [5 :0] nc_dest_reg; +wire nc_fls; +wire nc_ld; +wire nc_lock; +wire nc_lrsc; +wire [1 :0] nc_ori_size; +wire nc_pmp_expt; +wire [3 :0] nc_prot; +wire nc_req_vld; +wire nc_req_vld_dp; +wire nc_sign_ext; +wire [1 :0] nc_size; +wire nc_split; +wire nc_split_first; +wire nc_split_last; +wire nc_st; +wire ncb_ag_async_expt_vld; +wire ncb_ag_async_ld_inst; +wire [31:0] ncb_ag_async_mtval; +wire ncb_ag_pmp_ld_inst; +wire [31:0] ncb_ag_pmp_mtval; +wire ncb_ag_stall; +wire ncb_burst; +wire ncb_clk; +wire ncb_clk_en; +wire ncb_cmplt; +wire ncb_cmplt_norm; +wire ncb_create_en; +wire ncb_create_en_gate; +wire ncb_dahbif_acc_deny; +wire ncb_dahbif_lock; +wire ncb_dahbif_lrsc; +wire [31:0] ncb_dahbif_ncb_wb_addr; +wire ncb_dahbif_ncb_wb_sel; +wire [3 :0] ncb_dahbif_prot; +wire ncb_dahbif_req; +wire ncb_dahbif_req_dp; +wire [1 :0] ncb_dahbif_size; +wire [31:0] ncb_dahbif_uc_ld_addr; +wire [31:0] ncb_dahbif_wdata; +wire ncb_dahbif_write; +wire [10:0] ncb_dbginfo; +wire ncb_dp_clk; +wire ncb_dp_clk_en; +wire ncb_fld; +wire ncb_idle; +wire ncb_ld_create_en; +wire ncb_ld_create_en_gate; +wire ncb_ld_dp_clk; +wire ncb_ld_dp_clk_en; +wire ncb_sc_inst; +wire ncb_st_inst; +wire ncb_vld; +wire ncb_wb_cmplt; +wire ncb_wb_grant; +wire ncb_xx_no_op; +wire pad_yy_icg_scan_en; +wire req_done; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_lsu_sync_req; +wire rtu_yy_xx_async_flush; +wire [31:0] sc_data; +wire [1 :0] shift_from_bytes; +wire st_stall; +wire st_stall_dp; +wire [1 :0] wb_addr_pop_en; +wire wb_addr_pop_vld; +wire wb_clk; +wire wb_clk_en; +wire [31:0] wb_create_addr; +wire wb_create_buf; +wire [7 :0] wb_create_bytes_vld; +wire wb_create_ca; +wire [31:0] wb_create_data; +wire [5 :0] wb_create_dest_preg; +wire wb_create_dw; +wire [1 :0] wb_create_en; +wire [1 :0] wb_create_en_dp; +wire wb_create_fls; +wire wb_create_lock; +wire wb_create_mach_mode; +wire wb_create_pmp_deny; +wire wb_create_sc_fail; +wire wb_create_sc_inst; +wire [3 :0] wb_create_shift; +wire [2 :0] wb_create_shift_raw; +wire [1 :0] wb_create_size; +wire wb_create_so; +wire wb_create_split_first; +wire wb_create_src1_depd; +wire [5 :0] wb_create_src1_reg; +wire wb_create_vld; +wire wb_create_vld_dp; +wire wb_data_entry_vld; +wire wb_data_pmp_deny; +wire [1 :0] wb_data_pop_en; +wire wb_data_pop_vld; +wire wb_data_sc_fail; +wire wb_dbus_req_vld; +wire wb_dbus_split_first; +wire [31:0] wb_dbus_wdata; +wire wb_empty; +wire [31:0] wb_entry0_addr; +wire [2 :0] wb_entry0_dbginfo; +wire [5 :0] wb_entry0_dest_preg; +wire [3 :0] wb_entry0_prot; +wire [2 :0] wb_entry0_shift; +wire [1 :0] wb_entry0_size; +wire [31:0] wb_entry0_wdata; +wire [31:0] wb_entry1_addr; +wire [2 :0] wb_entry1_dbginfo; +wire [5 :0] wb_entry1_dest_preg; +wire [3 :0] wb_entry1_prot; +wire [2 :0] wb_entry1_shift; +wire [1 :0] wb_entry1_size; +wire [31:0] wb_entry1_wdata; +wire [1 :0] wb_entry_addr_vld; +wire [1 :0] wb_entry_data_vld; +wire [1 :0] wb_entry_fls; +wire [1 :0] wb_entry_lock; +wire [1 :0] wb_entry_lrsc; +wire [1 :0] wb_entry_pmp_deny; +wire [1 :0] wb_entry_sc_fail; +wire [1 :0] wb_entry_split_first; +wire [1 :0] wb_entry_vld; +wire wb_full; +wire wb_lock; +wire [31:0] wb_pmp_addr; +wire wb_pmp_deny; +wire wb_req_vld; +wire wb_sc_fail_vld; +wire wb_sc_req; +wire wb_so; +wire [1 :0] wb_so_req; +wire [31:0] wb_wdata; +wire [2 :0] wb_wdata_shift; + + +parameter DATAW = `FLEN; +//====================================== +// NCB STALL +//====================================== +// &Force("bus","ag_dc_func",3,0); @28 + +assign block_acc_en = !cp0_xx_async_expt_en | ncb_lock; +assign ag_ld_hit_wb = |ld_hit_wb[1:0]; +assign ag_ld_hit_wb_f = |ld_hit_wb_f[1:0]; +assign wb_so = |wb_so_req[1:0]; +assign wb_pmp_deny = |(wb_entry_vld[1:0] & wb_entry_pmp_deny[1:0]); +assign wb_lock = |(wb_entry_vld[1:0] & wb_entry_lock[1:0]); + +assign ag_st_inst = ag_dc_func[0] & !ag_dc_func[3]; +assign ag_ld_inst = !ag_dc_func[0] & !ag_dc_func[3]; +assign ag_lock_inst = !ag_dc_func[3] & (ag_dc_func[1] | ag_dc_func[2]); + +//1,AG is amo.ld/st or lr/sr -> ag_inst_lock +// lock should wait all preceeding requests done + +assign lock_stall = !nc_cur_rdy | !wb_empty; +assign lock_stall_dp = !nc_cur_rdy_dp | !wb_empty; + +//2.AG is normal load +// a)nc_fsm_busy +// b)wb has higher priority +// i) address hit wb +// ii) wb request with pmp_deny, or request if amo.st or sc, or request address is strong order + +assign ld_stall = ag_ld_hit_wb_f | ag_ld_hit_wb | + wb_pmp_deny | wb_lock | wb_so; + +assign ld_stall_dp = ag_ld_hit_wb_f | + wb_pmp_deny | wb_lock | wb_so; + +// 3.AG is normal store +// a) wb full +// b) wb request with pmp_deny or wb request is amo.st or sc +// c) for precise exception, to make sure that no followed store has been created into WB +// when ncb return access error, store must not be created into WB until ncb_ld is empty + +assign st_stall = wb_full | + wb_pmp_deny | wb_lock | + block_acc_en & !nc_cur_rdy; + +assign st_stall_dp = wb_full | + wb_pmp_deny | wb_lock | + block_acc_en & !nc_cur_rdy_dp; + +//ncb_ag_stall +assign ncb_ag_stall = ag_lock_inst + ? lock_stall + : (ag_st_inst ? st_stall + : (!nc_cur_rdy | ld_stall)); + +assign ncb_xx_no_op = ncb_idle & wb_empty; + + +//============================================================================== +// write buffer for store +//============================================================================== +assign ag_st_req = ag_ncb_inst_vld & ag_st_inst & + (ag_lock_inst & !lock_stall | + !ag_lock_inst & !st_stall); + +assign ag_st_req_dp = ag_ncb_inst_vld_dp & ag_st_inst & + (ag_lock_inst & !lock_stall_dp | + !ag_lock_inst & !st_stall_dp); + +//================================================ +// write buffer: create pointer +//================================================ + +assign wb_create_vld = ag_st_req; +assign wb_create_vld_dp = ag_st_req_dp; + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_create_ptr <= 1'b0; + else if (rtu_yy_xx_async_flush) + wb_create_ptr <= 1'b0; + else if (wb_create_vld) + wb_create_ptr <= ~wb_create_ptr; +end + +assign wb_create_en[1:0] = {wb_create_ptr,~wb_create_ptr} & {2{wb_create_vld}}; +assign wb_create_en_dp[1:0] = {wb_create_ptr,~wb_create_ptr} & {2{wb_create_vld_dp}}; +assign wb_create_addr[31:0] = ag_ncb_addr[31:0]; +assign wb_create_size[1:0] = ag_dc_size[1:0]; +assign wb_create_ca = ag_dc_ca; +assign wb_create_buf = ag_dc_buf; +assign wb_create_so = ag_dc_so; +assign wb_create_mach_mode = ag_dc_mach_mode; +assign wb_create_lock = ag_dc_func[2] | ag_dc_func[1]; +assign wb_create_sc_inst = ag_dc_func[1]; +assign wb_create_pmp_deny = ag_dc_pmp_expt; +assign wb_create_sc_fail = ag_sc_inst & !ag_dc_lm_pass; +assign wb_create_dest_preg[5:0] = ag_dc_dest_reg[5:0]; +assign wb_create_fls = ag_dc_fls; +assign wb_create_split_first = ag_dc_split_first; + +assign wb_create_dw = ag_dc_size[1:0] == 2'b11; +assign wb_create_bytes_vld[7:0] = ag_ncb_addr[2] + ? {ag_dc_bytes_vld[3:0],4'b0000} + : {{4{wb_create_dw}}, ag_dc_bytes_vld[3:0]}; + +assign wb_create_src1_reg[5:0] = ag_ncb_src1_reg[5:0]; +assign wb_create_src1_depd = ag_dc_src1_depd; +assign wb_create_data[DATAW-1:0]= ag_ncb_st_data[DATAW-1:0]; + +// &CombBeg; @135 +always @( ag_dc_bytes_vld[3:0]) +begin + casez(ag_dc_bytes_vld[3:0]) + 4'b???1: bytes_vld_decode[1:0] = 2'b00; + 4'b??10: bytes_vld_decode[1:0] = 2'b01; + 4'b?100: bytes_vld_decode[1:0] = 2'b10; + 4'b1000: bytes_vld_decode[1:0] = 2'b11; + default: bytes_vld_decode[1:0] = 2'b00; + endcase +// &CombEnd; @143 +end + +// &Force("bus","ag_dc_wdata_shift",2,0); @153 +assign shift_from_bytes[1:0] = bytes_vld_decode[1:0]; +assign wb_create_shift_raw[2:0] = {1'b0,shift_from_bytes[1:0]} + (3'b100 - {1'b0,ag_dc_wdata_shift[1:0]}); +assign wb_create_shift[1:0] = wb_create_shift_raw[1:0]; +assign wb_create_shift[3:2] = 2'b0; + +//wb_full +assign wb_full = &(wb_entry_vld[1:0] & ~wb_data_pop_en[1:0]); +assign wb_empty = !(|wb_entry_vld[1:0]); + +//================================================ +// address pop ptr +//================================================ +assign wb_addr_pop_vld = ncb_wb_grant | + wb_dbus_req & (wb_addr_pmp_deny | wb_addr_sc_fail); + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_addr_pop_ptr <= 1'b0; + else if (rtu_yy_xx_async_flush) + wb_addr_pop_ptr <= 1'b0; + else if (wb_addr_pop_vld) + wb_addr_pop_ptr <= ~wb_addr_pop_ptr; +end + +assign wb_addr_pop_en[1:0] = {wb_addr_pop_ptr,~wb_addr_pop_ptr} & {2{wb_addr_pop_vld}}; + +// &CombBeg; @182 +always @( wb_entry_addr_vld[1:0] + or wb_entry_sc_fail[1:0] + or wb_entry_lrsc[1:0] + or wb_entry_fls[1:0] + or wb_entry1_dest_preg[5:0] + or wb_addr_pop_ptr + or wb_entry0_prot[3:0] + or wb_entry1_prot[3:0] + or wb_entry0_addr[31:0] + or wb_entry1_size[1:0] + or wb_entry0_dest_preg[5:0] + or wb_entry_lock[1:0] + or wb_entry0_size[1:0] + or wb_entry1_addr[31:0] + or wb_entry_pmp_deny[1:0]) +begin + case(wb_addr_pop_ptr) + 1'b0 : begin + wb_dbus_req = wb_entry_addr_vld[0]; + wb_dbus_addr[31:0] = wb_entry0_addr[31:0]; + wb_dbus_prot[3:0] = wb_entry0_prot[3:0]; + wb_dbus_size[1:0] = wb_entry0_size[1:0]; + wb_dbus_fls = wb_entry_fls[0]; + wb_dbus_lock = wb_entry_lock[0]; + wb_dbus_lrsc = wb_entry_lrsc[0]; + wb_addr_pmp_deny = wb_entry_pmp_deny[0]; + wb_addr_sc_fail = wb_entry_sc_fail[0]; + wb_dbus_dest_preg[5:0] = wb_entry0_dest_preg[5:0]; + end + 1'b1 : begin + wb_dbus_req = wb_entry_addr_vld[1]; + wb_dbus_addr[31:0] = wb_entry1_addr[31:0]; + wb_dbus_prot[3:0] = wb_entry1_prot[3:0]; + wb_dbus_size[1:0] = wb_entry1_size[1:0]; + wb_dbus_fls = wb_entry_fls[1]; + wb_dbus_lock = wb_entry_lock[1]; + wb_dbus_lrsc = wb_entry_lrsc[1]; + wb_addr_pmp_deny = wb_entry_pmp_deny[1]; + wb_addr_sc_fail = wb_entry_sc_fail[1]; + wb_dbus_dest_preg[5:0] = wb_entry1_dest_preg[5:0]; + end + default:begin + wb_dbus_req = 1'b0; + wb_dbus_addr[31:0] = {32{1'bx}}; + wb_dbus_prot[3:0] = {4{1'bx}}; + wb_dbus_size[1:0] = {2{1'bx}}; + wb_dbus_fls = 1'bx; + wb_dbus_lock = 1'bx; + wb_dbus_lrsc = 1'bx; + wb_addr_pmp_deny = 1'bx; + wb_addr_sc_fail = 1'bx; + wb_dbus_dest_preg[5:0] = {6{1'bx}}; + end + endcase +// &CombEnd; @221 +end + +assign wb_dbus_split_first = wb_entry_split_first[wb_addr_pop_ptr]; + +assign wb_dbus_req_vld = wb_dbus_req & !wb_addr_pmp_deny & !wb_addr_sc_fail; + +//================================================ +// data pop ptr +//================================================ +assign wb_data_pop_vld = ncb_wb_cmplt | + wb_data_entry_vld & (wb_data_pmp_deny | wb_data_sc_fail); + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_data_pop_ptr <= 1'b0; + else if (rtu_yy_xx_async_flush) + wb_data_pop_ptr <= 1'b0; + else if (wb_data_pop_vld) + wb_data_pop_ptr <= ~wb_data_pop_ptr; +end + +assign wb_data_pop_en[1:0] = {wb_data_pop_ptr, ~wb_data_pop_ptr} & {2{wb_data_pop_vld}}; + +assign wb_data_entry_vld = wb_entry_data_vld[wb_data_pop_ptr]; +assign wb_data_pmp_deny = wb_entry_pmp_deny[wb_data_pop_ptr]; +assign wb_data_sc_fail = wb_entry_sc_fail[wb_data_pop_ptr]; +assign wb_wdata[DATAW-1:0] = wb_data_pop_ptr ? wb_entry1_wdata[DATAW-1:0] : wb_entry0_wdata[DATAW-1:0]; +assign wb_wdata_shift[2:0] = wb_data_pop_ptr ? wb_entry1_shift[2:0] : wb_entry0_shift[2:0]; + +// &CombBeg; @252 +// &CombEnd; @264 +// &CombBeg; @271 +always @( wb_wdata[31:0] + or wb_wdata_shift[1:0]) +begin + case(wb_wdata_shift[1:0]) + 2'b00: wb_dbus_wdata_pre[31:0] = wb_wdata[31:0]; + 2'b01: wb_dbus_wdata_pre[31:0] = {wb_wdata[23:0], wb_wdata[31:24]}; + 2'b10: wb_dbus_wdata_pre[31:0] = {wb_wdata[15:0], wb_wdata[31:16]}; + 2'b11: wb_dbus_wdata_pre[31:0] = {wb_wdata[7:0], wb_wdata[31:8]}; + default: wb_dbus_wdata_pre[31:0] = wb_wdata[31:0]; + endcase +// &CombEnd; @279 +end + +assign wb_dbus_wdata[31:0] = wb_dbus_wdata_pre[31:0]; + + +//============================================================================== +// NCB +//============================================================================== +assign ag_lr_inst = ag_dc_func[1] & !ag_dc_func[0]; +assign ag_sc_inst = ag_dc_func[1] & ag_dc_func[0]; +assign ag_lrsc_inst = ag_lr_inst | ag_sc_inst; +assign ag_dca_inst = ag_dc_func[3]; + +assign ag_prot[3:0] = {ag_dc_ca, ag_dc_buf, ag_dc_mach_mode, 1'b1}; + +assign ag_ld_req = ag_ncb_inst_vld & ag_ld_inst & + (ag_lock_inst & wb_empty | + !ag_lock_inst & !ld_stall); + +assign ag_ld_req_dp = ag_ncb_inst_vld_dp & (ag_ld_inst | ag_dca_inst) & + !rtu_lsu_sync_req & + (ag_lock_inst & wb_empty | + !ag_lock_inst & !ld_stall_dp); + +//================================================ +// request arbitration +//================================================ + +assign ag_ld_sel = ag_ld_req_dp & nc_cur_rdy_dp | ifu_lsu_warm_up; + +assign wb_req_vld = !ag_ld_sel & wb_dbus_req_vld; + +assign nc_req_vld = ag_ld_sel ? ag_ld_req : wb_req_vld; +assign nc_req_vld_dp = ag_ld_sel | wb_req_vld; +assign nc_addr[31:0] = ag_ld_sel ? ag_ncb_addr[31:0] : wb_dbus_addr[31:0]; +assign nc_size[1:0] = ag_ld_sel ? ag_dc_size[1:0] : wb_dbus_size[1:0]; +assign nc_ori_size[1:0] = ag_ld_sel ? ag_dc_ori_size[1:0] : wb_dbus_size[1:0]; +assign nc_fls = ag_ld_sel ? ag_dc_fls : wb_dbus_fls; +assign nc_prot[3:0] = ag_ld_sel ? ag_prot[3:0] : wb_dbus_prot[3:0]; +assign nc_lock = ag_ld_sel ? ag_lock_inst : wb_dbus_lock; +assign nc_lrsc = ag_ld_sel ? ag_lrsc_inst : wb_dbus_lrsc; +assign nc_pmp_expt = ag_ld_sel & ag_dc_pmp_expt; +assign nc_ld = ag_ld_sel; +assign nc_st =!ag_ld_sel; +assign nc_split = ag_ld_sel & ag_dc_split; +assign nc_split_last = ag_ld_sel & ag_dc_split_last; +assign nc_split_first = ag_ld_sel ? ag_dc_split_first : wb_dbus_split_first; + +assign nc_sign_ext = ag_ld_sel & ag_dc_sign_ext; +assign nc_dest_reg[5:0] = ag_ld_sel ? ag_dc_dest_reg[5:0] : wb_dbus_dest_preg[5:0]; +assign nc_bytes_vld[3:0] = {4{ag_ld_sel}} & ag_dc_bytes_vld[3:0]; + +assign ncb_wb_grant = nc_cur_rdy & wb_req_vld; +assign ncb_wb_cmplt = ncb_st_inst & ncb_cmplt; + +//========================================================== +// NCB REQ BUS FSM +//========================================================== +parameter NC_REQ = 2'b00; +parameter NC_WFG = 2'b01; +parameter NC_WFC = 2'b10; +parameter NC_ERR = 2'b11; + +always@(posedge ncb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + nc_cur_state[1:0] <= NC_REQ; + else if (rtu_yy_xx_async_flush) + nc_cur_state[1:0] <= NC_REQ; + else + nc_cur_state[1:0] <= nc_next_state[1:0]; +end + +// &CombBeg; @353 +always @( nc_cur_state[1:0] + or nc_req_vld + or data_last + or dahbif_ncb_cmplt + or dahbif_ncb_acc_err + or dahbif_ncb_grant) +begin + case(nc_cur_state[1:0]) + NC_REQ: begin + if (nc_req_vld) + nc_next_state[1:0] = dahbif_ncb_grant ? NC_WFC : NC_WFG; + else + nc_next_state[1:0] = NC_REQ; + end + NC_WFG: begin + if (dahbif_ncb_grant) + nc_next_state[1:0] = NC_WFC; + else + nc_next_state[1:0] = NC_WFG; + end + NC_WFC: begin + if (dahbif_ncb_acc_err) + nc_next_state[1:0] = NC_ERR; + else if (dahbif_ncb_cmplt & data_last & nc_req_vld) + nc_next_state[1:0] = dahbif_ncb_grant ? NC_WFC : NC_WFG; + else if (dahbif_ncb_cmplt & data_last) + nc_next_state[1:0] = NC_REQ; + else + nc_next_state[1:0] = NC_WFC; + end + NC_ERR: begin + nc_next_state[1:0] = NC_REQ; + end + default: nc_next_state[1:0] = NC_REQ; + endcase +// &CombEnd; @382 +end + +assign ncb_cmplt_norm = nc_cur_wfc & + dahbif_ncb_cmplt & data_last & + !dahbif_ncb_acc_err; + +assign ncb_cmplt = ncb_cmplt_norm | nc_cur_err; + +assign nc_cur_rdy = ncb_idle | ncb_cmplt_norm; +assign nc_cur_rdy_dp = ncb_idle | nc_cur_wfc & data_last & req_done; + +assign nc_cur_wfg = nc_cur_state[1:0] == NC_WFG; +assign nc_cur_wfc = nc_cur_state[1:0] == NC_WFC; +assign nc_cur_err = nc_cur_state[1:0] == NC_ERR; +assign ncb_idle = nc_cur_state[1:0] == NC_REQ; +assign ncb_vld = !ncb_idle; + +always@(posedge ncb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + data_last <= 1'b0; + else if (ncb_dahbif_req & dahbif_ncb_grant) + data_last <= !nc_burst; + else if (dahbif_ncb_cmplt) + data_last <= 1'b1; +end + +always@(posedge ncb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_cnt <= 1'b0; + else if (ncb_dahbif_req) + req_cnt <= dahbif_ncb_grant ? 1'b1 : 1'b0; + else if (!ncb_idle & dahbif_ncb_grant_2 & ncb_burst) + req_cnt <= ~req_cnt; +end + +assign req_done = ~ncb_burst | ~req_cnt; + +//====================================== +// request address and control +//====================================== +//ncb should not be updated when req is granted by dahbif, since information +//like split or preg, size and so on should be used when it return data to RTU + +assign ncb_create_en = nc_cur_rdy & nc_req_vld_dp; +assign ncb_create_en_gate = nc_cur_rdy_dp & nc_req_vld_dp; + +always@(posedge ncb_dp_clk or negedge cpurst_b) +begin + if (!cpurst_b) + ncb_addr[31:0] <= 32'b0; + else if (ncb_create_en) + ncb_addr[31:0] <= nc_addr[31:0]; +end + +always@(posedge ncb_dp_clk) +begin + if (ncb_create_en | ifu_lsu_warm_up) begin + ncb_size[1:0] <= nc_size[1:0]; + ncb_ori_size[1:0] <= nc_ori_size[1:0]; + ncb_fls <= nc_fls; + ncb_prot[3:0] <= nc_prot[3:0]; + ncb_lock <= nc_lock; + ncb_lrsc <= nc_lrsc; + ncb_ld_inst <= nc_ld; + ncb_pmp_expt <= nc_pmp_expt; + ncb_split <= nc_split; + ncb_split_first <= nc_split_first; + end +end + +assign ncb_ld_create_en = nc_cur_rdy & + (ag_ld_sel | wb_req_vld & wb_dbus_lrsc); +assign ncb_ld_create_en_gate = nc_cur_rdy_dp & + (ag_ld_sel | wb_req_vld & wb_dbus_lrsc); + +always@(posedge ncb_ld_dp_clk) +begin + if (ncb_ld_create_en | ifu_lsu_warm_up) begin + ncb_sign_ext <= nc_sign_ext; + ncb_dest_reg[5:0] <= nc_dest_reg[5:0]; + ncb_bytes_vld[3:0]<= nc_bytes_vld[3:0]; + ncb_split_last <= nc_split_last; + end +end + +// &Force("output", "ncb_dahbif_size"); @517 +assign nc_burst = ncb_dahbif_size[1:0] == 2'b11; +assign ncb_burst = ncb_size[1:0] == 2'b11; + + +assign ncb_st_inst = !ncb_ld_inst; +assign ncb_sc_inst = ncb_st_inst & ncb_lrsc; + +//====================================== +// LSU BMU +//====================================== +// &Force("output", "ncb_dahbif_req"); @528 + +assign ncb_dahbif_req_dp = nc_cur_wfg | nc_cur_rdy_dp & nc_req_vld_dp; +assign ncb_dahbif_req = nc_cur_wfg | nc_cur_rdy_dp & nc_req_vld; +assign ncb_dahbif_write = nc_cur_rdy_dp ? nc_st : ncb_st_inst; +assign ncb_dahbif_prot[3:0] = nc_cur_rdy_dp ? nc_prot[3:0] : ncb_prot[3:0]; +assign ncb_dahbif_size[1:0] = nc_cur_rdy_dp ? nc_size[1:0] : ncb_size[1:0]; +assign ncb_dahbif_lock = nc_cur_rdy_dp ? nc_lock : ncb_lock; +assign ncb_dahbif_lrsc = nc_cur_rdy_dp ? nc_lrsc : ncb_lrsc; +assign ncb_dahbif_acc_deny = nc_cur_rdy_dp ? nc_pmp_expt : ncb_pmp_expt; +assign ncb_dahbif_wdata[31:0] = wb_dbus_wdata[31:0]; + +//for address timing +assign ncb_dahbif_ncb_wb_sel = !ag_ld_sel | !nc_cur_rdy_dp; +assign ncb_dahbif_ncb_wb_addr[31:0] = nc_cur_rdy_dp ? wb_dbus_addr[31:0] : ncb_addr[31:0]; +assign ncb_dahbif_uc_ld_addr[31:0] = ag_ncb_addr[31:0]; + +//to biu, for pmp_deny timing, lock_fsm in BIU will start up, even when there +//is pmp deny, which will be flushed when this amo.ld is granted from biu. +assign lsu_biu_amo_pmp_deny = !ncb_idle & ncb_lock & !ncb_lrsc & ncb_pmp_expt; + +//====================================== +// LSU RTU DATA +//====================================== +// &Instance("gated_clk_cell", "x_pa_lsu_ncb_rdata_gated_clk"); @554 +// &Connect(.clk_in (forever_cpuclk), @555 +// .external_en (1'b0), @556 +// .global_en (1'b1), @557 +// .module_en (cp0_lsu_icg_en ), @558 +// .local_en (ncb_rdata_clk_en), @559 +// .clk_out (ncb_rdata_clk)); @560 +assign ncb_fld = 1'b0; +assign ld_data[31:0] = dahbif_ncb_data[31:0]; + +assign wb_sc_req = |(wb_entry_vld[1:0] & wb_entry_lrsc[1:0]); +assign wb_sc_fail_vld = wb_data_entry_vld & wb_data_sc_fail & ncb_idle & !wb_data_pmp_deny; + +assign sc_data[DATAW-1:0] = wb_sc_fail_vld + ? {{(DATAW-1){1'b0}},1'b1} + : {DATAW{1'b0}}; + +assign ld_sc_pass_data_vld = (ncb_ld_inst | ncb_sc_inst) & + !ncb_pmp_expt & ncb_cmplt; +assign ld_sc_pass_data_vld_gate = (ncb_ld_inst | ncb_sc_inst) & + !ncb_pmp_expt & (nc_cur_wfc | nc_cur_err); + +assign lsu_ex2_data_vld = ld_sc_pass_data_vld | wb_sc_fail_vld; +assign lsu_ex2_data_vld_gate = ld_sc_pass_data_vld_gate | wb_sc_fail_vld; + +assign lsu_ex2_dest_reg[5:0] = (wb_sc_req & ncb_idle) ? wb_dbus_dest_preg[5:0] : ncb_dest_reg[5:0]; +assign lsu_ex2_fls = (wb_sc_req & ncb_idle) ? wb_dbus_fls : ncb_fls; +assign lsu_ex2_fld = (wb_sc_req & ncb_idle) ? 1'b0 : ncb_fld; +assign lsu_ex2_split = (wb_sc_req & ncb_idle) ? 1'b0 : ncb_split; +assign lsu_ex2_split_last = (wb_sc_req & ncb_idle) ? 1'b0 : ncb_split_last; +assign lsu_ex2_bytes_vld[3:0] = (wb_sc_req & ncb_idle) ? 4'b1111 : ncb_bytes_vld[3:0]; +assign lsu_ex2_sign_ext = (wb_sc_req & ncb_idle) ? 1'b0 : ncb_sign_ext; +assign lsu_ex2_addr_2 = (wb_sc_req & ncb_idle) ? wb_dbus_addr[2] : ncb_addr[2]; +assign lsu_ex2_lock = ncb_lock; +assign lsu_ex2_size[1:0] = (wb_sc_req & ncb_idle) ? 2'b10 : ncb_ori_size[1:0]; +// &Force("nonport", "ncb_ori_size"); @614 + +assign lsu_mb_ex2_uc_data_vld = lsu_ex2_data_vld; +assign lsu_mb_ex2_uc_data_vld_gate = lsu_ex2_data_vld_gate; +assign lsu_mb_ex2_uc_data[DATAW-1:0] = wb_sc_req ? sc_data[DATAW-1:0] : ld_data[DATAW-1:0]; +assign lsu_mb_ex2_uc_sc_data_vld = wb_sc_req; +//assign lsu_mb_ex2_uc_ld_data[DATAW-1:0] = ld_data[DATAW-1:0]; +//assign lsu_mb_ex2_uc_sc_data[DATAW-1:0] = sc_data[DATAW-1:0]; +assign lsu_mb_ex2_uc_dest_reg[5:0] = lsu_ex2_dest_reg[5:0]; +assign lsu_mb_ex2_uc_fls = lsu_ex2_fls; +assign lsu_mb_ex2_uc_fld = lsu_ex2_fld; +assign lsu_mb_ex2_uc_split = lsu_ex2_split; +assign lsu_mb_ex2_uc_split_last = lsu_ex2_split_last; +assign lsu_mb_ex2_uc_bytes_vld[3:0] = lsu_ex2_bytes_vld[3:0]; +assign lsu_mb_ex2_uc_sign_ext = lsu_ex2_sign_ext; +assign lsu_mb_ex2_uc_size[1:0] = lsu_ex2_size[1:0]; +assign lsu_mb_ex2_uc_addr_2 = lsu_ex2_addr_2; +assign lsu_mb_ex2_uc_lock = lsu_ex2_lock; +assign lsu_xx_ex2_uc_flush = wb_dbus_req & wb_addr_pmp_deny; +//assign lsu_mb_ex2_uc_ld_vld = ncb_vld & ncb_ld_inst; + +//====================================== +// async exception +//====================================== +assign ncb_ag_async_expt_vld = dahbif_ncb_acc_err & ncb_split_first; +assign ncb_ag_async_mtval[31:0] = ncb_addr[31:0]; +assign ncb_ag_async_ld_inst = ncb_ld_inst & !ncb_lock; + +//====================================== +// pmp_deny mtval +//====================================== +assign wb_pmp_addr[31:0] = {32{wb_entry_vld[1] & wb_entry_pmp_deny[1]}} & wb_entry1_addr[31:0] | + {32{wb_entry_vld[0] & wb_entry_pmp_deny[0]}} & wb_entry0_addr[31:0]; +//assign ncb_pmp_deny = ncb_vld & ncb_pmp_expt; +assign ncb_ag_pmp_mtval[31:0] = wb_pmp_deny ? wb_pmp_addr[31:0] : ncb_addr[31:0]; +assign ncb_ag_pmp_ld_inst = wb_pmp_deny ? 1'b0 : ncb_ld_inst & !ncb_lock; +//====================================== +//ex2 stall +//====================================== +//assign lsu_mb_ex2_uc_stall = ncb_ld_inst & +// (nc_cur_wfg | +// nc_cur_wfc & (!data_last | +// !dahbif_ncb_cmplt | +// dahbif_ncb_acc_err)); + +//assign lsu_mb_ex2_uc_vld = ncb_ld_inst & +// (nc_cur_wfg | nc_cur_wfc); + +//for timing, cut ex2 stall +always@(posedge ncb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + uc_ex2_stall <= 1'b0; + else if (rtu_yy_xx_async_flush) + uc_ex2_stall <= 1'b0; + else if (nc_req_vld & nc_ld) + uc_ex2_stall <= 1'b1; + else if (ncb_cmplt) + uc_ex2_stall <= 1'b0; +end + +assign lsu_mb_ex2_uc_stall = uc_ex2_stall; + +//====================================== +// ICG +//====================================== +assign ncb_clk_en = ag_ncb_inst_vld_dp | ncb_vld | (|wb_entry_vld[1:0]); +// &Instance("gated_clk_cell", "x_pa_lsu_ncb_gated_clk"); @685 +gated_clk_cell x_pa_lsu_ncb_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ncb_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ncb_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @686 +// .external_en (1'b0), @687 +// .global_en (1'b1), @688 +// .module_en (cp0_lsu_icg_en ), @689 +// .local_en (ncb_clk_en), @690 +// .clk_out (ncb_clk)); @691 + +assign ncb_dp_clk_en = ncb_create_en_gate | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_ncb_dp_gated_clk"); @694 +gated_clk_cell x_pa_lsu_ncb_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ncb_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ncb_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @695 +// .external_en (1'b0), @696 +// .global_en (1'b1), @697 +// .module_en (cp0_lsu_icg_en ), @698 +// .local_en (ncb_dp_clk_en), @699 +// .clk_out (ncb_dp_clk)); @700 + +assign ncb_ld_dp_clk_en = ncb_ld_create_en_gate | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_ncb_ld_dp_gated_clk"); @703 +gated_clk_cell x_pa_lsu_ncb_ld_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (ncb_ld_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (ncb_ld_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @704 +// .external_en (1'b0), @705 +// .global_en (1'b1), @706 +// .module_en (cp0_lsu_icg_en ), @707 +// .local_en (ncb_ld_dp_clk_en), @708 +// .clk_out (ncb_ld_dp_clk)); @709 + +assign wb_clk_en = wb_create_vld_dp | (|wb_entry_vld[1:0]) | rtu_yy_xx_async_flush; +// &Instance("gated_clk_cell", "x_pa_lsu_wb_ctrl_gated_clk"); @712 +gated_clk_cell x_pa_lsu_wb_ctrl_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (wb_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (wb_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @713 +// .external_en (1'b0), @714 +// .global_en (1'b1), @715 +// .module_en (cp0_lsu_icg_en ), @716 +// .local_en (wb_clk_en), @717 +// .clk_out (wb_clk)); @718 + +// &ConnRule(s/_x$/[0]/); @720 +// &ConnRule(s/entryx/entry0/); @721 +// &Instance("pa_lsu_wb_entry","x_pa_lsu_wb_entry_0"); @722 +pa_lsu_wb_entry x_pa_lsu_wb_entry_0 ( + .ag_ld_inst (ag_ld_inst ), + .ag_ncb_inst_vld_dp (ag_ncb_inst_vld_dp ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .da_xx_fwd_data (da_xx_fwd_data ), + .da_xx_fwd_fls (da_xx_fwd_fls ), + .da_xx_fwd_preg (da_xx_fwd_preg ), + .da_xx_fwd_vld (da_xx_fwd_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .ld_hit_wb_f_x (ld_hit_wb_f[0] ), + .ld_hit_wb_x (ld_hit_wb[0] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .wb_addr_pop_en_x (wb_addr_pop_en[0] ), + .wb_clk (wb_clk ), + .wb_create_addr (wb_create_addr ), + .wb_create_buf (wb_create_buf ), + .wb_create_bytes_vld (wb_create_bytes_vld ), + .wb_create_ca (wb_create_ca ), + .wb_create_data (wb_create_data ), + .wb_create_dest_preg (wb_create_dest_preg ), + .wb_create_en_dp_x (wb_create_en_dp[0] ), + .wb_create_en_x (wb_create_en[0] ), + .wb_create_fls (wb_create_fls ), + .wb_create_lock (wb_create_lock ), + .wb_create_mach_mode (wb_create_mach_mode ), + .wb_create_pmp_deny (wb_create_pmp_deny ), + .wb_create_sc_fail (wb_create_sc_fail ), + .wb_create_sc_inst (wb_create_sc_inst ), + .wb_create_shift (wb_create_shift ), + .wb_create_size (wb_create_size ), + .wb_create_so (wb_create_so ), + .wb_create_split_first (wb_create_split_first ), + .wb_create_src1_depd (wb_create_src1_depd ), + .wb_create_src1_reg (wb_create_src1_reg ), + .wb_data_pop_en_x (wb_data_pop_en[0] ), + .wb_entry_addr_vld_x (wb_entry_addr_vld[0] ), + .wb_entry_data_vld_x (wb_entry_data_vld[0] ), + .wb_entry_fls_x (wb_entry_fls[0] ), + .wb_entry_lock_x (wb_entry_lock[0] ), + .wb_entry_lrsc_x (wb_entry_lrsc[0] ), + .wb_entry_pmp_deny_x (wb_entry_pmp_deny[0] ), + .wb_entry_sc_fail_x (wb_entry_sc_fail[0] ), + .wb_entry_split_first_x (wb_entry_split_first[0]), + .wb_entry_vld_x (wb_entry_vld[0] ), + .wb_entryx_addr (wb_entry0_addr ), + .wb_entryx_dbginfo (wb_entry0_dbginfo ), + .wb_entryx_dest_preg (wb_entry0_dest_preg ), + .wb_entryx_prot (wb_entry0_prot ), + .wb_entryx_shift (wb_entry0_shift ), + .wb_entryx_size (wb_entry0_size ), + .wb_entryx_wdata (wb_entry0_wdata ), + .wb_so_req_x (wb_so_req[0] ) +); + + +// &ConnRule(s/_x$/[1]/); @724 +// &ConnRule(s/entryx/entry1/); @725 +// &Instance("pa_lsu_wb_entry","x_pa_lsu_wb_entry_1"); @726 +pa_lsu_wb_entry x_pa_lsu_wb_entry_1 ( + .ag_ld_inst (ag_ld_inst ), + .ag_ncb_inst_vld_dp (ag_ncb_inst_vld_dp ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .da_xx_fwd_data (da_xx_fwd_data ), + .da_xx_fwd_fls (da_xx_fwd_fls ), + .da_xx_fwd_preg (da_xx_fwd_preg ), + .da_xx_fwd_vld (da_xx_fwd_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .ld_hit_wb_f_x (ld_hit_wb_f[1] ), + .ld_hit_wb_x (ld_hit_wb[1] ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .wb_addr_pop_en_x (wb_addr_pop_en[1] ), + .wb_clk (wb_clk ), + .wb_create_addr (wb_create_addr ), + .wb_create_buf (wb_create_buf ), + .wb_create_bytes_vld (wb_create_bytes_vld ), + .wb_create_ca (wb_create_ca ), + .wb_create_data (wb_create_data ), + .wb_create_dest_preg (wb_create_dest_preg ), + .wb_create_en_dp_x (wb_create_en_dp[1] ), + .wb_create_en_x (wb_create_en[1] ), + .wb_create_fls (wb_create_fls ), + .wb_create_lock (wb_create_lock ), + .wb_create_mach_mode (wb_create_mach_mode ), + .wb_create_pmp_deny (wb_create_pmp_deny ), + .wb_create_sc_fail (wb_create_sc_fail ), + .wb_create_sc_inst (wb_create_sc_inst ), + .wb_create_shift (wb_create_shift ), + .wb_create_size (wb_create_size ), + .wb_create_so (wb_create_so ), + .wb_create_split_first (wb_create_split_first ), + .wb_create_src1_depd (wb_create_src1_depd ), + .wb_create_src1_reg (wb_create_src1_reg ), + .wb_data_pop_en_x (wb_data_pop_en[1] ), + .wb_entry_addr_vld_x (wb_entry_addr_vld[1] ), + .wb_entry_data_vld_x (wb_entry_data_vld[1] ), + .wb_entry_fls_x (wb_entry_fls[1] ), + .wb_entry_lock_x (wb_entry_lock[1] ), + .wb_entry_lrsc_x (wb_entry_lrsc[1] ), + .wb_entry_pmp_deny_x (wb_entry_pmp_deny[1] ), + .wb_entry_sc_fail_x (wb_entry_sc_fail[1] ), + .wb_entry_split_first_x (wb_entry_split_first[1]), + .wb_entry_vld_x (wb_entry_vld[1] ), + .wb_entryx_addr (wb_entry1_addr ), + .wb_entryx_dbginfo (wb_entry1_dbginfo ), + .wb_entryx_dest_preg (wb_entry1_dest_preg ), + .wb_entryx_prot (wb_entry1_prot ), + .wb_entryx_shift (wb_entry1_shift ), + .wb_entryx_size (wb_entry1_size ), + .wb_entryx_wdata (wb_entry1_wdata ), + .wb_so_req_x (wb_so_req[1] ) +); + + +assign ncb_dbginfo[10:0] = {wb_data_pop_ptr,wb_addr_pop_ptr,wb_create_ptr, + wb_entry1_dbginfo[2:0],wb_entry0_dbginfo[2:0],nc_cur_state[1:0]}; + +// &ModuleEnd; @731 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_rdl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_rdl.v new file mode 100644 index 0000000000000000000000000000000000000000..9693f62f3c0da567b965444b841e57b1ceba4a8c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_rdl.v @@ -0,0 +1,522 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_rdl( + arb_rdl_grant, + cp0_lsu_icg_en, + cpurst_b, + dc_rdl_fifo, + dc_rdl_way0_data, + dc_rdl_way0_dirty, + dc_rdl_way0_tag, + dc_rdl_way0_vld, + dc_rdl_way1_data, + dc_rdl_way1_dirty, + dc_rdl_way1_tag, + dc_rdl_way1_vld, + forever_cpuclk, + ifu_lsu_warm_up, + lfb_rdl_index, + lfb_rdl_start, + lfb_rdl_start_gate, + pad_yy_icg_scan_en, + rdl_arb_data_bank, + rdl_arb_data_din, + rdl_arb_data_idx, + rdl_arb_data_req, + rdl_arb_data_way, + rdl_arb_data_wen, + rdl_arb_dcache_sel, + rdl_arb_dirty_din, + rdl_arb_dirty_idx, + rdl_arb_dirty_req, + rdl_arb_dirty_wen, + rdl_arb_tag_din, + rdl_arb_tag_idx, + rdl_arb_tag_req, + rdl_arb_tag_wen, + rdl_dbginfo, + rdl_lfb_done, + rdl_lfb_fifo, + rdl_lfb_fifo_save, + rdl_lfb_grant, + rdl_stb_cmplt_id, + rdl_stb_dca_cmplt, + rdl_stb_dca_grant, + rdl_vb_addr, + rdl_vb_create_en, + rdl_vb_data, + rdl_vb_data_cnt, + rdl_vb_data_create, + rdl_vb_line_dirty, + rdl_vb_warm_up, + rtu_yy_xx_async_flush, + stb_rdl_addr, + stb_rdl_dca_type, + stb_rdl_dirty, + stb_rdl_id, + stb_rdl_start, + stb_rdl_way, + vb_rdl_grant +); + +// &Ports; @21 +input arb_rdl_grant; +input cp0_lsu_icg_en; +input cpurst_b; +input dc_rdl_fifo; +input [63:0] dc_rdl_way0_data; +input dc_rdl_way0_dirty; +input [21:0] dc_rdl_way0_tag; +input dc_rdl_way0_vld; +input [63:0] dc_rdl_way1_data; +input dc_rdl_way1_dirty; +input [21:0] dc_rdl_way1_tag; +input dc_rdl_way1_vld; +input forever_cpuclk; +input ifu_lsu_warm_up; +input [9 :0] lfb_rdl_index; +input lfb_rdl_start; +input lfb_rdl_start_gate; +input pad_yy_icg_scan_en; +input rtu_yy_xx_async_flush; +input [26:0] stb_rdl_addr; +input [1 :0] stb_rdl_dca_type; +input stb_rdl_dirty; +input [1 :0] stb_rdl_id; +input stb_rdl_start; +input stb_rdl_way; +input vb_rdl_grant; +output [1 :0] rdl_arb_data_bank; +output [63:0] rdl_arb_data_din; +output [11:0] rdl_arb_data_idx; +output rdl_arb_data_req; +output [1 :0] rdl_arb_data_way; +output [3 :0] rdl_arb_data_wen; +output rdl_arb_dcache_sel; +output [2 :0] rdl_arb_dirty_din; +output [9 :0] rdl_arb_dirty_idx; +output rdl_arb_dirty_req; +output [2 :0] rdl_arb_dirty_wen; +output [22:0] rdl_arb_tag_din; +output [9 :0] rdl_arb_tag_idx; +output rdl_arb_tag_req; +output [1 :0] rdl_arb_tag_wen; +output [2 :0] rdl_dbginfo; +output rdl_lfb_done; +output rdl_lfb_fifo; +output rdl_lfb_fifo_save; +output rdl_lfb_grant; +output [1 :0] rdl_stb_cmplt_id; +output rdl_stb_dca_cmplt; +output rdl_stb_dca_grant; +output [26:0] rdl_vb_addr; +output rdl_vb_create_en; +output [63:0] rdl_vb_data; +output [1 :0] rdl_vb_data_cnt; +output rdl_vb_data_create; +output rdl_vb_line_dirty; +output rdl_vb_warm_up; + +// &Regs; @22 +reg [1 :0] dca_id; +reg dca_sel; +reg [1 :0] dca_type; +reg pf_cache_hit_ff; +reg [1 :0] rdl_cnt; +reg [1 :0] rdl_cnt_f; +reg [2 :0] rdl_cur_state; +reg rdl_data_vld; +reg [2 :0] rdl_next_state; +reg replace_dirty; +reg replace_fifo; +reg [9 :0] replace_index; +reg [21:0] replace_tag; +reg replace_vld; + +// &Wires; @23 +wire arb_rdl_grant; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire data_rd_done; +wire dc_rdl_fifo; +wire [63:0] dc_rdl_way0_data; +wire dc_rdl_way0_dirty; +wire [21:0] dc_rdl_way0_tag; +wire dc_rdl_way0_vld; +wire [63:0] dc_rdl_way1_data; +wire dc_rdl_way1_dirty; +wire [21:0] dc_rdl_way1_tag; +wire dc_rdl_way1_vld; +wire dca_cln; +wire dca_inv; +wire dirty_clr; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire [9 :0] lfb_rdl_index; +wire lfb_rdl_start; +wire lfb_rdl_start_gate; +wire lfb_tag_wen; +wire [63:0] line_data; +wire line_dirty; +wire [21:0] line_tag; +wire line_vld; +wire pad_yy_icg_scan_en; +wire pf_cache_hit; +wire rdl_addr_clk; +wire rdl_addr_clk_en; +wire [1 :0] rdl_arb_data_bank; +wire [63:0] rdl_arb_data_din; +wire [11:0] rdl_arb_data_idx; +wire rdl_arb_data_req; +wire [1 :0] rdl_arb_data_way; +wire [3 :0] rdl_arb_data_wen; +wire rdl_arb_dcache_sel; +wire [2 :0] rdl_arb_dirty_din; +wire [9 :0] rdl_arb_dirty_idx; +wire rdl_arb_dirty_req; +wire [2 :0] rdl_arb_dirty_wen; +wire [22:0] rdl_arb_tag_din; +wire [9 :0] rdl_arb_tag_idx; +wire rdl_arb_tag_req; +wire [1 :0] rdl_arb_tag_wen; +wire rdl_cnt_last; +wire rdl_cur_check; +wire rdl_cur_data; +wire rdl_cur_data_grnt; +wire rdl_cur_idle; +wire rdl_cur_inv; +wire [2 :0] rdl_dbginfo; +wire rdl_fsm_clk; +wire rdl_fsm_clk_en; +wire rdl_lfb_done; +wire rdl_lfb_fifo; +wire rdl_lfb_fifo_save; +wire rdl_lfb_grant; +wire rdl_line_inv; +wire rdl_line_rd; +wire rdl_replace_clk; +wire rdl_replace_clk_en; +wire [1 :0] rdl_stb_cmplt_id; +wire rdl_stb_dca_cmplt; +wire rdl_stb_dca_grant; +wire [26:0] rdl_vb_addr; +wire rdl_vb_create_en; +wire [63:0] rdl_vb_data; +wire [1 :0] rdl_vb_data_cnt; +wire rdl_vb_data_create; +wire rdl_vb_line_dirty; +wire rdl_vb_warm_up; +wire rtu_yy_xx_async_flush; +wire [26:0] stb_rdl_addr; +wire [1 :0] stb_rdl_dca_type; +wire stb_rdl_dirty; +wire [1 :0] stb_rdl_id; +wire stb_rdl_start; +wire [21:0] stb_rdl_tag; +wire stb_rdl_way; +wire tag_inv; +wire tag_rd; +wire vb_rdl_grant; + + +parameter D_DATA_INDEX_LEN = `D_DATA_INDEX_WIDTH; +parameter D_TAG_TAG_LEN = `D_TAG_TAG_WIDTH; +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; + +//================================================ +// RDL FSM +//================================================ +parameter RDL_IDLE = 3'b000; +parameter RDL_CHECK = 3'b001; +parameter RDL_DATA = 3'b010; +parameter RDL_LAST = 3'b011; +parameter RDL_TAG_RD = 3'b100; +parameter RDL_TAG_WT = 3'b101; +parameter RDL_INV = 3'b110; + +always@(posedge rdl_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + rdl_cur_state[2:0] <= RDL_IDLE; + else if (rtu_yy_xx_async_flush) + rdl_cur_state[2:0] <= RDL_IDLE; + else + rdl_cur_state[2:0] <= rdl_next_state[2:0]; +end + +// &CombBeg; @60 +always @( data_rd_done + or arb_rdl_grant + or rdl_cur_state[2:0] + or rdl_line_inv + or dca_sel + or vb_rdl_grant + or rdl_line_rd + or lfb_rdl_start + or stb_rdl_start) +begin + case(rdl_cur_state[2:0]) + RDL_IDLE: begin + if (stb_rdl_start) + rdl_next_state[2:0] = RDL_CHECK; + else if (lfb_rdl_start) + rdl_next_state[2:0] = RDL_TAG_RD; + else + rdl_next_state[2:0] = RDL_IDLE; + end + RDL_TAG_RD: begin + if (arb_rdl_grant) + rdl_next_state[2:0] = RDL_TAG_WT; + else + rdl_next_state[2:0] = RDL_TAG_RD; + end + RDL_TAG_WT: begin + rdl_next_state[2:0] = RDL_CHECK; + end + RDL_CHECK: begin + if (rdl_line_rd) + rdl_next_state[2:0] = vb_rdl_grant ? RDL_DATA : RDL_CHECK; + else if (rdl_line_inv) + rdl_next_state[2:0] = RDL_INV; + else + rdl_next_state[2:0] = RDL_IDLE; + end + RDL_DATA:begin + if (data_rd_done) + rdl_next_state[2:0] = dca_sel ? RDL_INV : RDL_LAST; + else + rdl_next_state[2:0] = RDL_DATA; + end + RDL_INV:begin + if (arb_rdl_grant) + rdl_next_state[2:0] = RDL_IDLE; + else + rdl_next_state[2:0] = RDL_INV; + end + RDL_LAST: + rdl_next_state[2:0] = RDL_IDLE; + default: rdl_next_state[2:0] = RDL_IDLE; + endcase +// &CombEnd; @103 +end + +assign rdl_cur_idle = rdl_cur_state[2:0] == RDL_IDLE; +assign rdl_cur_data = rdl_cur_state[2:0] == RDL_DATA; +assign rdl_cur_check = rdl_cur_state[2:0] == RDL_CHECK; + +assign rdl_lfb_grant = !stb_rdl_start & rdl_cur_idle; +assign rdl_lfb_done = rdl_cur_check & !dca_sel & (!replace_vld | pf_cache_hit_ff) | + rdl_cur_data & !dca_sel & data_rd_done; + + +assign rdl_stb_dca_grant = rdl_cur_idle; +assign rdl_stb_dca_cmplt = (rdl_cur_state[2:0] == RDL_INV) | + (rdl_cur_state[2:0] == RDL_CHECK) & dca_sel & !rdl_line_rd & !rdl_line_inv; +assign rdl_stb_cmplt_id[1:0] = dca_id[1:0]; + +assign rdl_cur_data_grnt = arb_rdl_grant & rdl_cur_data; + +always@(posedge rdl_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + rdl_cnt[1:0] <= 2'b00; + rdl_cnt_f[1:0] <= 2'b00; + end + else if (rdl_cur_data_grnt) begin + rdl_cnt[1:0] <= rdl_cnt[1:0] + 2'b01; + rdl_cnt_f[1:0] <= rdl_cnt[1:0]; + end +end + +assign rdl_cnt_last = rdl_cnt[1:0] == 2'b11; +assign data_rd_done = rdl_cnt_last & arb_rdl_grant; + +always@(posedge rdl_fsm_clk or negedge cpurst_b) +begin + if (!cpurst_b) + rdl_data_vld <= 1'b0; + else + rdl_data_vld <= rdl_cur_data_grnt; +end + +//================================================ +// RDL content +//================================================ +//-----------for pfb hit check------------------ +// &Force("bus", "lfb_rdl_tag",21,0); @152 +assign pf_cache_hit = 1'b0; + +assign line_vld = dc_rdl_fifo ? dc_rdl_way1_vld : dc_rdl_way0_vld; +assign line_dirty = dc_rdl_fifo ? dc_rdl_way1_dirty : dc_rdl_way0_dirty; +assign line_tag[21:0] = dc_rdl_fifo ? dc_rdl_way1_tag[21:0] : dc_rdl_way0_tag[21:0]; +assign line_data[63:0] = replace_fifo ? dc_rdl_way1_data[63:0] : dc_rdl_way0_data[63:0]; + +assign stb_rdl_tag[21:0] = {{22-D_TAG_TAG_LEN{1'b0}}, stb_rdl_addr[26:D_TAG_INDEX_LEN]}; + +always@(posedge rdl_addr_clk) +begin + if (stb_rdl_start & rdl_cur_idle | ifu_lsu_warm_up) begin + dca_sel <= 1'b1; + dca_type[1:0] <= stb_rdl_dca_type[1:0]; + dca_id[1:0] <= stb_rdl_id[1:0]; + replace_index[9:0] <= stb_rdl_addr[9:0]; + end + else if (lfb_rdl_start & rdl_cur_idle) begin + dca_sel <= 1'b0; + dca_type[1:0] <= 2'b0; + dca_id[1:0] <= 2'b0; + replace_index[9:0] <= lfb_rdl_index[9:0]; + end +end + +assign dca_cln = dca_type[1]; +assign dca_inv = dca_type[0]; + +assign lfb_tag_wen = rdl_cur_state[2:0] == RDL_TAG_WT; + +always@(posedge rdl_replace_clk) +begin + if (stb_rdl_start & rdl_cur_idle | ifu_lsu_warm_up) begin + replace_vld <= 1'b1; + replace_fifo <= stb_rdl_way; + replace_dirty <= stb_rdl_dirty; + replace_tag[21:0] <= stb_rdl_tag[21:0]; + pf_cache_hit_ff <= 1'b0; + end + else if (lfb_tag_wen) begin + replace_vld <= line_vld; + replace_fifo <= dc_rdl_fifo; + replace_dirty <= line_dirty; + replace_tag[21:0] <= line_tag[21:0]; + pf_cache_hit_ff <= pf_cache_hit; + end +end + +assign rdl_line_rd = dca_sel & dca_cln & replace_dirty | + !dca_sel & replace_vld & !pf_cache_hit_ff; + +assign rdl_line_inv = dca_sel & dca_inv & replace_vld; + +assign rdl_lfb_fifo_save = lfb_tag_wen; +assign rdl_lfb_fifo = dc_rdl_fifo; + +//================================================ +// request cache +//================================================ +// &Force("output", "rdl_arb_tag_wen"); @291 + +assign rdl_cur_inv = (rdl_cur_state[2:0] == RDL_INV); +assign tag_inv = rdl_cur_inv & dca_inv; +assign tag_rd = rdl_cur_state[2:0] == RDL_TAG_RD; +assign dirty_clr = rdl_cur_inv; + +assign rdl_arb_tag_req = tag_rd | tag_inv; +assign rdl_arb_tag_wen[1:0] = {2{tag_inv}} & {replace_fifo,~replace_fifo}; +assign rdl_arb_tag_din[22:0] = {1'b0,22'b0}; +assign rdl_arb_tag_idx[9:0] = replace_index[9:0]; + +assign rdl_arb_dirty_req = tag_rd | dirty_clr; +assign rdl_arb_dirty_wen[2:0] = {1'b0,{2{dirty_clr}} & {replace_fifo,~replace_fifo}}; +assign rdl_arb_dirty_din[2:0] = 3'b0; +assign rdl_arb_dirty_idx[9:0] = replace_index[9:0]; + +assign rdl_arb_data_req = rdl_cur_data; +assign rdl_arb_data_way[1:0] = {replace_fifo,~replace_fifo}; +assign rdl_arb_data_bank[1:0] = 2'b11; +assign rdl_arb_data_wen[3:0] = 4'b0; +assign rdl_arb_data_din[63:0] = 64'b0; +assign rdl_arb_data_idx[11:0] = {replace_index[9:0],rdl_cnt[1:0]}; + +assign rdl_arb_dcache_sel = rdl_cur_data | rdl_cur_inv | tag_rd; + +//================================================ +// request VB +//================================================ + +assign rdl_vb_create_en = rdl_cur_check & rdl_line_rd; +assign rdl_vb_addr[26:0] = {replace_tag[D_TAG_TAG_LEN-1:0], replace_index[D_TAG_INDEX_LEN-1:0]}; +assign rdl_vb_line_dirty = replace_dirty; +assign rdl_vb_data_create = rdl_data_vld; +assign rdl_vb_data_cnt[1:0] = rdl_cnt_f[1:0]; +assign rdl_vb_data[63:0] = line_data[63:0]; +assign rdl_vb_warm_up = ifu_lsu_warm_up; + +assign rdl_fsm_clk_en = lfb_rdl_start_gate | stb_rdl_start | !(rdl_cur_state[2:0] == RDL_IDLE) | rdl_data_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_rdl_fsm_gated_clk"); @330 +gated_clk_cell x_pa_lsu_rdl_fsm_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (rdl_fsm_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (rdl_fsm_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @331 +// .external_en (1'b0), @332 +// .global_en (1'b1), @333 +// .module_en (cp0_lsu_icg_en ), @334 +// .local_en (rdl_fsm_clk_en), @335 +// .clk_out (rdl_fsm_clk)); @336 + +assign rdl_addr_clk_en = lfb_rdl_start_gate | stb_rdl_start | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_rdl_addr_gated_clk"); @339 +gated_clk_cell x_pa_lsu_rdl_addr_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (rdl_addr_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (rdl_addr_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @340 +// .external_en (1'b0), @341 +// .global_en (1'b1), @342 +// .module_en (cp0_lsu_icg_en ), @343 +// .local_en (rdl_addr_clk_en), @344 +// .clk_out (rdl_addr_clk)); @345 + +assign rdl_replace_clk_en = lfb_tag_wen | stb_rdl_start | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_rdl_replace_gated_clk"); @348 +gated_clk_cell x_pa_lsu_rdl_replace_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (rdl_replace_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (rdl_replace_clk_en), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @349 +// .external_en (1'b0), @350 +// .global_en (1'b1), @351 +// .module_en (cp0_lsu_icg_en ), @352 +// .local_en (rdl_replace_clk_en), @353 +// .clk_out (rdl_replace_clk)); @354 + +assign rdl_dbginfo[2:0] = rdl_cur_state[2:0]; + +// &ModuleEnd; @358 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb.v new file mode 100644 index 0000000000000000000000000000000000000000..5f083f000e7f5a2fa5ccf6ff1927f63396b2ee10 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb.v @@ -0,0 +1,812 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_stb( + arb_stb_xx_grant, + cp0_lsu_dcache_wb, + cp0_lsu_icg_en, + cpurst_b, + dahbif_stb_acc_ecc, + dahbif_stb_cmplt, + dahbif_stb_grant, + dahbif_stb_grant_2, + dc_stb_addr, + dc_stb_attr, + dc_stb_bytes_vld, + dc_stb_cache_hit, + dc_stb_create_en, + dc_stb_create_en_gate, + dc_stb_data, + dc_stb_dcache_dirty, + dc_stb_dcache_inst, + dc_stb_dcache_type, + dc_stb_dcache_way, + dc_stb_fls, + dc_stb_lock_trans, + dc_stb_sc_inst, + dc_stb_shift, + dc_stb_size, + dc_stb_split_first, + dc_stb_src1_depd, + dc_stb_src1_reg, + dc_stb_wait_lfb, + dc_xx_addr, + dc_xx_bytes_vld, + forever_cpuclk, + ifu_lsu_warm_up, + lfb_stb_done, + lfb_stb_err, + lfb_stb_fifo, + lfb_stb_fifo_update, + lfb_xx_idle, + pad_yy_icg_scan_en, + rdl_stb_cmplt_id, + rdl_stb_dca_cmplt, + rdl_stb_dca_grant, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_yy_xx_async_flush, + stb_arb_data_bank, + stb_arb_data_din, + stb_arb_data_idx, + stb_arb_data_req, + stb_arb_data_way, + stb_arb_data_wen, + stb_arb_dcache_sel, + stb_arb_dirty_din, + stb_arb_dirty_idx, + stb_arb_dirty_req, + stb_arb_dirty_wen, + stb_dahbif_addr, + stb_dahbif_data, + stb_dahbif_lock, + stb_dahbif_prot, + stb_dahbif_req, + stb_dahbif_sc_inst, + stb_dahbif_size, + stb_dbginfo, + stb_dc_async_expt, + stb_dc_busy, + stb_dc_full, + stb_dc_hit_addr, + stb_dc_hit_dca, + stb_dc_hit_idx, + stb_dc_ld_data, + stb_dc_ld_fwd_vld, + stb_dc_mtval, + stb_dc_multi_or_part_hit, + stb_dc_pop_en, + stb_idle, + stb_rdl_addr, + stb_rdl_dca_type, + stb_rdl_dirty, + stb_rdl_id, + stb_rdl_start, + stb_rdl_way +); + +// &Ports; @21 +input arb_stb_xx_grant; +input cp0_lsu_dcache_wb; +input cp0_lsu_icg_en; +input cpurst_b; +input dahbif_stb_acc_ecc; +input dahbif_stb_cmplt; +input dahbif_stb_grant; +input dahbif_stb_grant_2; +input [31:0] dc_stb_addr; +input [2 :0] dc_stb_attr; +input [3 :0] dc_stb_bytes_vld; +input dc_stb_cache_hit; +input dc_stb_create_en; +input dc_stb_create_en_gate; +input [31:0] dc_stb_data; +input dc_stb_dcache_dirty; +input dc_stb_dcache_inst; +input [1 :0] dc_stb_dcache_type; +input dc_stb_dcache_way; +input dc_stb_fls; +input dc_stb_lock_trans; +input dc_stb_sc_inst; +input [2 :0] dc_stb_shift; +input [1 :0] dc_stb_size; +input dc_stb_split_first; +input dc_stb_src1_depd; +input [4 :0] dc_stb_src1_reg; +input dc_stb_wait_lfb; +input [31:0] dc_xx_addr; +input [7 :0] dc_xx_bytes_vld; +input forever_cpuclk; +input ifu_lsu_warm_up; +input lfb_stb_done; +input lfb_stb_err; +input lfb_stb_fifo; +input lfb_stb_fifo_update; +input lfb_xx_idle; +input pad_yy_icg_scan_en; +input [1 :0] rdl_stb_cmplt_id; +input rdl_stb_dca_cmplt; +input rdl_stb_dca_grant; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_yy_xx_async_flush; +output [1 :0] stb_arb_data_bank; +output [63:0] stb_arb_data_din; +output [11:0] stb_arb_data_idx; +output stb_arb_data_req; +output [1 :0] stb_arb_data_way; +output [3 :0] stb_arb_data_wen; +output stb_arb_dcache_sel; +output [2 :0] stb_arb_dirty_din; +output [9 :0] stb_arb_dirty_idx; +output stb_arb_dirty_req; +output [2 :0] stb_arb_dirty_wen; +output [31:0] stb_dahbif_addr; +output [31:0] stb_dahbif_data; +output stb_dahbif_lock; +output [3 :0] stb_dahbif_prot; +output stb_dahbif_req; +output stb_dahbif_sc_inst; +output [1 :0] stb_dahbif_size; +output [23:0] stb_dbginfo; +output stb_dc_async_expt; +output stb_dc_busy; +output stb_dc_full; +output stb_dc_hit_addr; +output stb_dc_hit_dca; +output stb_dc_hit_idx; +output [31:0] stb_dc_ld_data; +output stb_dc_ld_fwd_vld; +output [31:0] stb_dc_mtval; +output stb_dc_multi_or_part_hit; +output stb_dc_pop_en; +output stb_idle; +output [26:0] stb_rdl_addr; +output [1 :0] stb_rdl_dca_type; +output stb_rdl_dirty; +output [1 :0] stb_rdl_id; +output stb_rdl_start; +output stb_rdl_way; + +// &Regs; @22 +reg [1 :0] biu_wdata_sel; +reg [1 :0] bytes_vld_decode; +reg data_last; +reg req_burst_vld; +reg req_cnt; +reg stb_create_ptr; +reg [1 :0] wb_cur_state; +reg [1 :0] wb_next_state; +reg [1 :0] wb_req_sel; + +// &Wires; @23 +wire arb_stb_xx_grant; +wire [1 :0] biu_sel; +wire cp0_lsu_dcache_wb; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire dahbif_stb_acc_ecc; +wire dahbif_stb_cmplt; +wire dahbif_stb_grant; +wire dahbif_stb_grant_2; +wire [11:0] data_index; +wire [1 :0] dc_hit_stb_addr; +wire [1 :0] dc_hit_stb_dca; +wire [1 :0] dc_hit_stb_full; +wire [1 :0] dc_hit_stb_index; +wire [1 :0] dc_hit_stb_part; +wire [31:0] dc_stb_addr; +wire [2 :0] dc_stb_attr; +wire [3 :0] dc_stb_bytes_vld; +wire dc_stb_cache_hit; +wire dc_stb_create_en; +wire dc_stb_create_en_gate; +wire [31:0] dc_stb_data; +wire dc_stb_dcache_dirty; +wire dc_stb_dcache_inst; +wire [1 :0] dc_stb_dcache_type; +wire dc_stb_dcache_way; +wire dc_stb_fls; +wire dc_stb_lock_trans; +wire dc_stb_sc_inst; +wire [2 :0] dc_stb_shift; +wire [1 :0] dc_stb_size; +wire dc_stb_split_first; +wire dc_stb_src1_depd; +wire [4 :0] dc_stb_src1_reg; +wire dc_stb_wait_lfb; +wire [31:0] dc_xx_addr; +wire [7 :0] dc_xx_bytes_vld; +wire [1 :0] dca_sel; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire lfb_stb_done; +wire lfb_stb_err; +wire lfb_stb_fifo; +wire lfb_stb_fifo_update; +wire lfb_xx_idle; +wire pad_yy_icg_scan_en; +wire [1 :0] rdl_sel; +wire [1 :0] rdl_stb_cmplt_id; +wire rdl_stb_dca_cmplt; +wire rdl_stb_dca_grant; +wire req_done; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_yy_xx_async_flush; +wire [2 :0] shift_from_bytes; +wire [31:0] stb_arb_data; +wire [1 :0] stb_arb_data_bank; +wire [63:0] stb_arb_data_din; +wire [11:0] stb_arb_data_idx; +wire stb_arb_data_req; +wire [1 :0] stb_arb_data_way; +wire [3 :0] stb_arb_data_wen; +wire stb_arb_dcache_sel; +wire [2 :0] stb_arb_dirty_din; +wire [9 :0] stb_arb_dirty_idx; +wire stb_arb_dirty_req; +wire [2 :0] stb_arb_dirty_wen; +wire stb_biu_req_vld; +wire [1 :0] stb_biu_sel; +wire stb_clk; +wire stb_clk_en; +wire [31:0] stb_create_addr; +wire stb_create_age; +wire [2 :0] stb_create_attr; +wire [3 :0] stb_create_bytes_vld; +wire [31:0] stb_create_data; +wire stb_create_dca_inst; +wire [1 :0] stb_create_dca_type; +wire stb_create_dirty; +wire [1 :0] stb_create_en; +wire [1 :0] stb_create_en_gate; +wire stb_create_fls; +wire stb_create_lock; +wire stb_create_sc_inst; +wire [3 :0] stb_create_shift; +wire [2 :0] stb_create_shift_raw; +wire [1 :0] stb_create_size; +wire stb_create_split_first; +wire stb_create_src1_depd; +wire [4 :0] stb_create_src1_reg; +wire stb_create_wait_lfb; +wire stb_create_way; +wire stb_create_wt_ca; +wire [31:0] stb_dahbif_addr; +wire [31:0] stb_dahbif_data; +wire stb_dahbif_lock; +wire [3 :0] stb_dahbif_prot; +wire stb_dahbif_req; +wire stb_dahbif_sc_inst; +wire [1 :0] stb_dahbif_size; +wire [23:0] stb_dbginfo; +wire stb_dc_async_expt; +wire stb_dc_busy; +wire stb_dc_full; +wire stb_dc_hit_addr; +wire stb_dc_hit_dca; +wire stb_dc_hit_idx; +wire [31:0] stb_dc_ld_data; +wire stb_dc_ld_fwd_vld; +wire [31:0] stb_dc_mtval; +wire stb_dc_multi_or_part_hit; +wire stb_dc_pop_en; +wire [1 :0] stb_dca_done; +wire [1 :0] stb_dca_grant; +wire stb_dca_req; +wire [31:0] stb_entry0_addr; +wire [1 :0] stb_entry0_bank; +wire [3 :0] stb_entry0_bytes_vld; +wire [31:0] stb_entry0_data; +wire [10:0] stb_entry0_dbginfo; +wire [1 :0] stb_entry0_dca_type; +wire [3 :0] stb_entry0_prot; +wire [1 :0] stb_entry0_size; +wire [31:0] stb_entry1_addr; +wire [1 :0] stb_entry1_bank; +wire [3 :0] stb_entry1_bytes_vld; +wire [31:0] stb_entry1_data; +wire [10:0] stb_entry1_dbginfo; +wire [1 :0] stb_entry1_dca_type; +wire [3 :0] stb_entry1_prot; +wire [1 :0] stb_entry1_size; +wire [1 :0] stb_entry_age; +wire [1 :0] stb_entry_biu_req; +wire [1 :0] stb_entry_burst; +wire [1 :0] stb_entry_busy; +wire [1 :0] stb_entry_data_vld; +wire [1 :0] stb_entry_dcache_req; +wire [1 :0] stb_entry_dirty; +wire [1 :0] stb_entry_lock; +wire [1 :0] stb_entry_pop_vld; +wire [1 :0] stb_entry_rdl_req; +wire [1 :0] stb_entry_sc_inst; +wire [1 :0] stb_entry_split_first; +wire [1 :0] stb_entry_vld; +wire [1 :0] stb_entry_vld_dp; +wire [1 :0] stb_entry_way; +wire stb_hit_way1; +wire stb_idle; +wire stb_pop_vld; +wire [31:0] stb_pop_wdata; +wire [26:0] stb_rdl_addr; +wire [1 :0] stb_rdl_dca_type; +wire stb_rdl_dirty; +wire [1 :0] stb_rdl_id; +wire stb_rdl_start; +wire stb_rdl_way; +wire stb_req_burst; +wire stb_split_first; +wire [1 :0] stb_wbus_cmplt; +wire [1 :0] stb_wbus_grant; +wire [1 :0] stb_wca_grant; +wire wb_cur_idle; + + +parameter STB_ENTRY = 2; +parameter DATAW = `FLEN; + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_create_ptr <= 1'b0; + else if (dc_stb_create_en) + stb_create_ptr <= ~stb_create_ptr; +end + +assign stb_create_en[1:0] = {stb_create_ptr,~stb_create_ptr} & {2{dc_stb_create_en}}; +assign stb_create_en_gate[1:0] = {stb_create_ptr,~stb_create_ptr} & {2{dc_stb_create_en_gate}}; + +assign stb_create_addr[31:0] = dc_stb_addr[31:0]; +assign stb_create_size[1:0] = dc_stb_size[1:0]; +assign stb_create_data[DATAW-1:0]= dc_stb_data[DATAW-1:0]; +assign stb_create_dca_inst = dc_stb_dcache_inst; +assign stb_create_dca_type[1:0] = dc_stb_dcache_type[1:0]; +assign stb_create_bytes_vld[3:0] = dc_stb_bytes_vld[3:0]; +assign stb_create_attr[2:0] = dc_stb_attr[2:0]; +assign stb_create_way = dc_stb_dcache_way; +assign stb_create_dirty = dc_stb_dcache_dirty; +assign stb_create_lock = dc_stb_lock_trans; +assign stb_create_sc_inst = dc_stb_sc_inst; +assign stb_create_src1_depd = dc_stb_src1_depd; +assign stb_create_src1_reg[4:0] = dc_stb_src1_reg[4:0]; +assign stb_create_fls = dc_stb_fls; +assign stb_create_wait_lfb = dc_stb_wait_lfb; +assign stb_create_wt_ca = dc_stb_cache_hit; +assign stb_create_age = |(stb_entry_vld[STB_ENTRY-1:0]); +assign stb_create_split_first = dc_stb_split_first; + +// &CombBeg; @58 +always @( dc_stb_bytes_vld[3:0]) +begin + casez(dc_stb_bytes_vld[3:0]) + 4'b???1: bytes_vld_decode[1:0] = 2'b00; + 4'b??10: bytes_vld_decode[1:0] = 2'b01; + 4'b?100: bytes_vld_decode[1:0] = 2'b10; + 4'b1000: bytes_vld_decode[1:0] = 2'b11; + default: bytes_vld_decode[1:0] = 2'b00; + endcase +// &CombEnd; @66 +end + +// &Force("bus","dc_stb_shift",2,0); @76 +assign shift_from_bytes[2:0] = {1'b0,bytes_vld_decode[1:0]}; +assign stb_create_shift_raw[2:0] = {1'b0,shift_from_bytes[1:0]} + (3'b100 - {1'b0,dc_stb_shift[1:0]}); +assign stb_create_shift[1:0] = stb_create_shift_raw[1:0]; +assign stb_create_shift[3:2] = 2'b0; + +assign stb_pop_vld = |(stb_entry_pop_vld[STB_ENTRY-1:0]); + +//================================================ +// depedency to DC +//================================================ +// &Force("output", "stb_dc_busy"); @88 +assign stb_dc_full = |({stb_create_ptr,~stb_create_ptr} & stb_entry_busy[1:0]); +assign stb_dc_busy = |(stb_entry_busy[1:0]); +assign stb_idle = !stb_dc_busy; + +assign stb_dc_multi_or_part_hit = (|(dc_hit_stb_part[STB_ENTRY-1:0])) | + (&(dc_hit_stb_full[STB_ENTRY-1:0])) | + (|(dc_hit_stb_full[STB_ENTRY-1:0] & ~stb_entry_data_vld[STB_ENTRY-1:0])); +assign stb_dc_hit_dca = |(dc_hit_stb_dca[STB_ENTRY-1:0]); +assign stb_dc_hit_idx = |(dc_hit_stb_index[STB_ENTRY-1:0]); +assign stb_dc_hit_addr = |(dc_hit_stb_addr[STB_ENTRY-1:0]); +assign stb_dc_pop_en = stb_pop_vld; +assign stb_dc_ld_fwd_vld = |(dc_hit_stb_full[STB_ENTRY-1:0] & stb_entry_data_vld[STB_ENTRY-1:0]); +assign stb_dc_ld_data[DATAW-1:0]= {DATAW{dc_hit_stb_full[0]}} & stb_entry0_data[DATAW-1:0] | + {DATAW{dc_hit_stb_full[1]}} & stb_entry1_data[DATAW-1:0]; + +//================================================ +// dcache request +//================================================ +assign dca_sel[1] = stb_entry_dcache_req[1] & (!stb_entry_dcache_req[0] | !stb_entry_age[1]); +assign dca_sel[0] = stb_entry_dcache_req[0] & (!stb_entry_dcache_req[1] | !stb_entry_age[0]); + +assign stb_dca_req = |stb_entry_dcache_req[STB_ENTRY-1:0]; +assign data_index[11:0] = {12{dca_sel[1]}} & stb_entry1_addr[14:3] | + {12{dca_sel[0]}} & stb_entry0_addr[14:3]; + +assign stb_hit_way1 = |(dca_sel[1:0] & stb_entry_way[1:0]); + +assign stb_arb_dirty_req = stb_dca_req; +assign stb_arb_dirty_wen[2:0] = {1'b0, stb_hit_way1, ~stb_hit_way1}; +assign stb_arb_dirty_din[2:0] = 3'b111; +assign stb_arb_dirty_idx[9:0] = data_index[11:2]; + +assign stb_arb_data_req = stb_dca_req; +assign stb_arb_data_way[1:0] = {stb_hit_way1, ~stb_hit_way1}; +assign stb_arb_data_idx[11:0] = data_index[11:0]; +assign stb_arb_data_wen[3:0] = {4{dca_sel[1]}} & stb_entry1_bytes_vld[3:0] | + {4{dca_sel[0]}} & stb_entry0_bytes_vld[3:0]; +assign stb_arb_data[DATAW-1:0]= {DATAW{dca_sel[1]}} & stb_entry1_data[DATAW-1:0] | + {DATAW{dca_sel[0]}} & stb_entry0_data[DATAW-1:0]; +assign stb_arb_data_bank[1:0] = {2{dca_sel[1]}} & stb_entry1_bank[1:0] | + {2{dca_sel[0]}} & stb_entry0_bank[1:0]; + +assign stb_arb_data_din[63:0] = {stb_arb_data[31:0],stb_arb_data[31:0]}; +assign stb_arb_dcache_sel = stb_dca_req; + +assign stb_wca_grant[1:0] = dca_sel[1:0] & {2{arb_stb_xx_grant}}; + +//================================================ +// biu request +//================================================ +parameter WB_IDLE = 2'b00; +parameter WB_WFG = 2'b01; +parameter WB_WFC = 2'b10; + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_cur_state[1:0] <= WB_IDLE; + else if(rtu_yy_xx_async_flush) + wb_cur_state[1:0] <= WB_IDLE; + else + wb_cur_state[1:0] <= wb_next_state[1:0]; +end + +assign stb_biu_req_vld = |stb_entry_biu_req[1:0]; + +// &CombBeg; @159 +always @( dahbif_stb_grant + or dahbif_stb_cmplt + or stb_biu_req_vld + or dahbif_stb_acc_ecc + or data_last + or wb_cur_state[1:0]) +begin + case (wb_cur_state[1:0]) + WB_IDLE: begin + if (stb_biu_req_vld) + wb_next_state[1:0] = dahbif_stb_grant ? WB_WFC : WB_WFG; + else + wb_next_state[1:0] = WB_IDLE; + end + WB_WFG: begin + if (dahbif_stb_grant) + wb_next_state[1:0] = WB_WFC; + else + wb_next_state[1:0] = WB_WFG; + end + WB_WFC: begin + if (dahbif_stb_cmplt & !dahbif_stb_acc_ecc & data_last & stb_biu_req_vld) + wb_next_state[1:0] = dahbif_stb_grant ? WB_WFC : WB_WFG; + else if (dahbif_stb_cmplt & (data_last | dahbif_stb_acc_ecc)) + wb_next_state[1:0] = WB_IDLE; + else + wb_next_state[1:0] = WB_WFC; + end + default: wb_next_state[1:0] = WB_IDLE; + endcase +// &CombEnd; @183 +end + +assign wb_cur_idle = wb_cur_state[1:0] == WB_IDLE | + wb_cur_state[1:0] == WB_WFC & data_last & req_done; + +assign stb_biu_sel[1] = stb_entry_biu_req[1] & (!stb_entry_biu_req[0] | !stb_entry_age[1]); +assign stb_biu_sel[0] = stb_entry_biu_req[0] & (!stb_entry_biu_req[1] | !stb_entry_age[0]); + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_req_sel[1:0] <= 2'b0; + else if (wb_cur_idle & stb_biu_req_vld) + wb_req_sel[1:0] <= stb_biu_sel[1:0]; +end + +assign biu_sel[1:0] = wb_cur_idle ? stb_biu_sel[1:0] : wb_req_sel[1:0]; + +assign stb_dahbif_req = |(biu_sel[1:0] & stb_entry_biu_req[STB_ENTRY-1:0]); +assign stb_dahbif_addr[31:0] = {32{biu_sel[1]}} & stb_entry1_addr[31:0] | + {32{biu_sel[0]}} & stb_entry0_addr[31:0]; +assign stb_dahbif_size[1:0] = {2{biu_sel[1]}} & stb_entry1_size[1:0] | + {2{biu_sel[0]}} & stb_entry0_size[1:0]; +assign stb_dahbif_prot[3:0] = {4{biu_sel[1]}} & stb_entry1_prot[3:0] | + {4{biu_sel[0]}} & stb_entry0_prot[3:0]; +assign stb_dahbif_lock = |(biu_sel[1:0] & stb_entry_lock[1:0]); +assign stb_dahbif_sc_inst = |(biu_sel[1:0] & stb_entry_sc_inst[1:0]); + +// &Force("output", "stb_dahbif_req"); @211 +//====================================== +// data_last +//====================================== +assign stb_req_burst = |(biu_sel[1:0] & stb_entry_burst[1:0]); + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + data_last <= 1'b0; + else if (dahbif_stb_grant) + data_last <= !stb_req_burst; + else if (dahbif_stb_cmplt) + data_last <= 1'b1; +end + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_cnt <= 1'b0; + else if (stb_dahbif_req & stb_req_burst) + req_cnt <= dahbif_stb_grant ? 1'b1 : 1'b0; + else if (!wb_cur_idle & dahbif_stb_grant_2 & req_burst_vld) + req_cnt <= ~req_cnt; +end + +assign req_done = !req_burst_vld | !req_cnt; + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_burst_vld <= 1'b0; + else if (dahbif_stb_grant) + req_burst_vld <= stb_req_burst; +end + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + biu_wdata_sel[1:0] <= 2'b00; + else if (dahbif_stb_grant) + biu_wdata_sel[1:0] <= biu_sel[1:0]; +end + +assign stb_pop_wdata[DATAW-1:0] = {DATAW{biu_wdata_sel[1]}} & stb_entry1_data[DATAW-1:0] | + {DATAW{biu_wdata_sel[0]}} & stb_entry0_data[DATAW-1:0]; + +assign stb_dahbif_data[31:0] = stb_pop_wdata[31:0]; + +//====================================== +// grant and cmplt to STB +//====================================== +assign stb_wbus_grant[1:0] = biu_sel[1:0] & {2{dahbif_stb_grant}}; +assign stb_wbus_cmplt[1:0] = biu_wdata_sel[1:0] & {2{dahbif_stb_cmplt & (data_last | dahbif_stb_acc_ecc)}}; + +assign stb_dc_async_expt = dahbif_stb_cmplt & dahbif_stb_acc_ecc & stb_split_first; +assign stb_split_first = |(biu_wdata_sel[1:0] & stb_entry_split_first[1:0]); +assign stb_dc_mtval[31:0] = {32{biu_wdata_sel[1]}} & stb_entry1_addr[31:0] | + {32{biu_wdata_sel[0]}} & stb_entry0_addr[31:0]; + +//================================================ +// request RDL +//================================================ +assign rdl_sel[1] = stb_entry_rdl_req[1] & (!stb_entry_rdl_req[0] | !stb_entry_age[1]); +assign rdl_sel[0] = stb_entry_rdl_req[0] & (!stb_entry_rdl_req[1] | !stb_entry_age[0]); + +assign stb_rdl_start = |stb_entry_rdl_req[1:0]; +assign stb_rdl_addr[26:0] = {27{rdl_sel[1]}} & stb_entry1_addr[31:5] | + {27{rdl_sel[0]}} & stb_entry0_addr[31:5]; +assign stb_rdl_dirty = |(rdl_sel[1:0] & stb_entry_dirty[1:0]); +assign stb_rdl_way = |(rdl_sel[1:0] & stb_entry_way[1:0]); +assign stb_rdl_id[1:0] = rdl_sel[1:0]; +assign stb_rdl_dca_type[1:0] = {2{rdl_sel[1]}} & stb_entry1_dca_type[1:0] | + {2{rdl_sel[0]}} & stb_entry0_dca_type[1:0]; + +assign stb_dca_grant[1:0] = {2{rdl_stb_dca_grant}} & rdl_sel[1:0]; +assign stb_dca_done[1:0] = {2{rdl_stb_dca_cmplt}} & rdl_stb_cmplt_id[1:0]; + +// &ConnRule(s/_x$/[0]/); @297 +// &ConnRule(s/entryx/entry0/); @298 +// &Instance("pa_lsu_stb_entry","x_pa_lsu_stb_entry_0"); @299 +pa_lsu_stb_entry x_pa_lsu_stb_entry_0 ( + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_hit_stb_addr_x (dc_hit_stb_addr[0] ), + .dc_hit_stb_dca_x (dc_hit_stb_dca[0] ), + .dc_hit_stb_full_x (dc_hit_stb_full[0] ), + .dc_hit_stb_index_x (dc_hit_stb_index[0] ), + .dc_hit_stb_part_x (dc_hit_stb_part[0] ), + .dc_xx_addr (dc_xx_addr ), + .dc_xx_bytes_vld (dc_xx_bytes_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_stb_done (lfb_stb_done ), + .lfb_stb_err (lfb_stb_err ), + .lfb_stb_fifo (lfb_stb_fifo ), + .lfb_stb_fifo_update (lfb_stb_fifo_update ), + .lfb_xx_idle (lfb_xx_idle ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .stb_clk (stb_clk ), + .stb_create_addr (stb_create_addr ), + .stb_create_age (stb_create_age ), + .stb_create_attr (stb_create_attr ), + .stb_create_bytes_vld (stb_create_bytes_vld ), + .stb_create_data (stb_create_data ), + .stb_create_dca_inst (stb_create_dca_inst ), + .stb_create_dca_type (stb_create_dca_type ), + .stb_create_dirty (stb_create_dirty ), + .stb_create_en_gate_x (stb_create_en_gate[0] ), + .stb_create_en_x (stb_create_en[0] ), + .stb_create_fls (stb_create_fls ), + .stb_create_lock (stb_create_lock ), + .stb_create_sc_inst (stb_create_sc_inst ), + .stb_create_shift (stb_create_shift ), + .stb_create_size (stb_create_size ), + .stb_create_split_first (stb_create_split_first ), + .stb_create_src1_depd (stb_create_src1_depd ), + .stb_create_src1_reg (stb_create_src1_reg ), + .stb_create_wait_lfb (stb_create_wait_lfb ), + .stb_create_way (stb_create_way ), + .stb_create_wt_ca (stb_create_wt_ca ), + .stb_dca_done_x (stb_dca_done[0] ), + .stb_dca_grant_x (stb_dca_grant[0] ), + .stb_entry_age_x (stb_entry_age[0] ), + .stb_entry_biu_req_x (stb_entry_biu_req[0] ), + .stb_entry_burst_x (stb_entry_burst[0] ), + .stb_entry_busy_x (stb_entry_busy[0] ), + .stb_entry_data_vld_x (stb_entry_data_vld[0] ), + .stb_entry_dcache_req_x (stb_entry_dcache_req[0] ), + .stb_entry_dirty_x (stb_entry_dirty[0] ), + .stb_entry_lock_x (stb_entry_lock[0] ), + .stb_entry_pop_vld_x (stb_entry_pop_vld[0] ), + .stb_entry_rdl_req_x (stb_entry_rdl_req[0] ), + .stb_entry_sc_inst_x (stb_entry_sc_inst[0] ), + .stb_entry_split_first_x (stb_entry_split_first[0]), + .stb_entry_vld_dp_x (stb_entry_vld_dp[0] ), + .stb_entry_vld_x (stb_entry_vld[0] ), + .stb_entry_way_x (stb_entry_way[0] ), + .stb_entryx_addr (stb_entry0_addr ), + .stb_entryx_bank (stb_entry0_bank ), + .stb_entryx_bytes_vld (stb_entry0_bytes_vld ), + .stb_entryx_data (stb_entry0_data ), + .stb_entryx_dbginfo (stb_entry0_dbginfo ), + .stb_entryx_dca_type (stb_entry0_dca_type ), + .stb_entryx_prot (stb_entry0_prot ), + .stb_entryx_size (stb_entry0_size ), + .stb_pop_vld (stb_pop_vld ), + .stb_wbus_cmplt_x (stb_wbus_cmplt[0] ), + .stb_wbus_grant_x (stb_wbus_grant[0] ), + .stb_wca_grant_x (stb_wca_grant[0] ) +); + + +// &ConnRule(s/_x$/[1]/); @301 +// &ConnRule(s/entryx/entry1/); @302 +// &Instance("pa_lsu_stb_entry","x_pa_lsu_stb_entry_1"); @303 +pa_lsu_stb_entry x_pa_lsu_stb_entry_1 ( + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_hit_stb_addr_x (dc_hit_stb_addr[1] ), + .dc_hit_stb_dca_x (dc_hit_stb_dca[1] ), + .dc_hit_stb_full_x (dc_hit_stb_full[1] ), + .dc_hit_stb_index_x (dc_hit_stb_index[1] ), + .dc_hit_stb_part_x (dc_hit_stb_part[1] ), + .dc_xx_addr (dc_xx_addr ), + .dc_xx_bytes_vld (dc_xx_bytes_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_stb_done (lfb_stb_done ), + .lfb_stb_err (lfb_stb_err ), + .lfb_stb_fifo (lfb_stb_fifo ), + .lfb_stb_fifo_update (lfb_stb_fifo_update ), + .lfb_xx_idle (lfb_xx_idle ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .stb_clk (stb_clk ), + .stb_create_addr (stb_create_addr ), + .stb_create_age (stb_create_age ), + .stb_create_attr (stb_create_attr ), + .stb_create_bytes_vld (stb_create_bytes_vld ), + .stb_create_data (stb_create_data ), + .stb_create_dca_inst (stb_create_dca_inst ), + .stb_create_dca_type (stb_create_dca_type ), + .stb_create_dirty (stb_create_dirty ), + .stb_create_en_gate_x (stb_create_en_gate[1] ), + .stb_create_en_x (stb_create_en[1] ), + .stb_create_fls (stb_create_fls ), + .stb_create_lock (stb_create_lock ), + .stb_create_sc_inst (stb_create_sc_inst ), + .stb_create_shift (stb_create_shift ), + .stb_create_size (stb_create_size ), + .stb_create_split_first (stb_create_split_first ), + .stb_create_src1_depd (stb_create_src1_depd ), + .stb_create_src1_reg (stb_create_src1_reg ), + .stb_create_wait_lfb (stb_create_wait_lfb ), + .stb_create_way (stb_create_way ), + .stb_create_wt_ca (stb_create_wt_ca ), + .stb_dca_done_x (stb_dca_done[1] ), + .stb_dca_grant_x (stb_dca_grant[1] ), + .stb_entry_age_x (stb_entry_age[1] ), + .stb_entry_biu_req_x (stb_entry_biu_req[1] ), + .stb_entry_burst_x (stb_entry_burst[1] ), + .stb_entry_busy_x (stb_entry_busy[1] ), + .stb_entry_data_vld_x (stb_entry_data_vld[1] ), + .stb_entry_dcache_req_x (stb_entry_dcache_req[1] ), + .stb_entry_dirty_x (stb_entry_dirty[1] ), + .stb_entry_lock_x (stb_entry_lock[1] ), + .stb_entry_pop_vld_x (stb_entry_pop_vld[1] ), + .stb_entry_rdl_req_x (stb_entry_rdl_req[1] ), + .stb_entry_sc_inst_x (stb_entry_sc_inst[1] ), + .stb_entry_split_first_x (stb_entry_split_first[1]), + .stb_entry_vld_dp_x (stb_entry_vld_dp[1] ), + .stb_entry_vld_x (stb_entry_vld[1] ), + .stb_entry_way_x (stb_entry_way[1] ), + .stb_entryx_addr (stb_entry1_addr ), + .stb_entryx_bank (stb_entry1_bank ), + .stb_entryx_bytes_vld (stb_entry1_bytes_vld ), + .stb_entryx_data (stb_entry1_data ), + .stb_entryx_dbginfo (stb_entry1_dbginfo ), + .stb_entryx_dca_type (stb_entry1_dca_type ), + .stb_entryx_prot (stb_entry1_prot ), + .stb_entryx_size (stb_entry1_size ), + .stb_pop_vld (stb_pop_vld ), + .stb_wbus_cmplt_x (stb_wbus_cmplt[1] ), + .stb_wbus_grant_x (stb_wbus_grant[1] ), + .stb_wca_grant_x (stb_wca_grant[1] ) +); + + +assign stb_clk_en = dc_stb_create_en_gate | stb_entry_vld_dp[0] | stb_entry_vld_dp[1]; + +// &Instance("gated_clk_cell", "x_pa_lsu_stb_gated_clk"); @307 +gated_clk_cell x_pa_lsu_stb_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (stb_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (stb_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @308 +// .external_en (1'b0), @309 +// .global_en (1'b1), @310 +// .module_en (cp0_lsu_icg_en ), @311 +// .local_en (stb_clk_en), @312 +// .clk_out (stb_clk)); @313 + +assign stb_dbginfo[23:0] = {stb_entry1_dbginfo[10:0],stb_entry0_dbginfo[10:0],wb_cur_state[1:0]}; + +// &ModuleEnd; @317 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..4ef966e6f6155b41c80b2d572a920731be563322 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_stb_entry.v @@ -0,0 +1,622 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_stb_entry( + cp0_lsu_dcache_wb, + cp0_lsu_icg_en, + cpurst_b, + dc_hit_stb_addr_x, + dc_hit_stb_dca_x, + dc_hit_stb_full_x, + dc_hit_stb_index_x, + dc_hit_stb_part_x, + dc_xx_addr, + dc_xx_bytes_vld, + forever_cpuclk, + ifu_lsu_warm_up, + lfb_stb_done, + lfb_stb_err, + lfb_stb_fifo, + lfb_stb_fifo_update, + lfb_xx_idle, + pad_yy_icg_scan_en, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_yy_xx_async_flush, + stb_clk, + stb_create_addr, + stb_create_age, + stb_create_attr, + stb_create_bytes_vld, + stb_create_data, + stb_create_dca_inst, + stb_create_dca_type, + stb_create_dirty, + stb_create_en_gate_x, + stb_create_en_x, + stb_create_fls, + stb_create_lock, + stb_create_sc_inst, + stb_create_shift, + stb_create_size, + stb_create_split_first, + stb_create_src1_depd, + stb_create_src1_reg, + stb_create_wait_lfb, + stb_create_way, + stb_create_wt_ca, + stb_dca_done_x, + stb_dca_grant_x, + stb_entry_age_x, + stb_entry_biu_req_x, + stb_entry_burst_x, + stb_entry_busy_x, + stb_entry_data_vld_x, + stb_entry_dcache_req_x, + stb_entry_dirty_x, + stb_entry_lock_x, + stb_entry_pop_vld_x, + stb_entry_rdl_req_x, + stb_entry_sc_inst_x, + stb_entry_split_first_x, + stb_entry_vld_dp_x, + stb_entry_vld_x, + stb_entry_way_x, + stb_entryx_addr, + stb_entryx_bank, + stb_entryx_bytes_vld, + stb_entryx_data, + stb_entryx_dbginfo, + stb_entryx_dca_type, + stb_entryx_prot, + stb_entryx_size, + stb_pop_vld, + stb_wbus_cmplt_x, + stb_wbus_grant_x, + stb_wca_grant_x +); + +// &Ports; @21 +input cp0_lsu_dcache_wb; +input cp0_lsu_icg_en; +input cpurst_b; +input [31:0] dc_xx_addr; +input [7 :0] dc_xx_bytes_vld; +input forever_cpuclk; +input ifu_lsu_warm_up; +input lfb_stb_done; +input lfb_stb_err; +input lfb_stb_fifo; +input lfb_stb_fifo_update; +input lfb_xx_idle; +input pad_yy_icg_scan_en; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_yy_xx_async_flush; +input stb_clk; +input [31:0] stb_create_addr; +input stb_create_age; +input [2 :0] stb_create_attr; +input [3 :0] stb_create_bytes_vld; +input [31:0] stb_create_data; +input stb_create_dca_inst; +input [1 :0] stb_create_dca_type; +input stb_create_dirty; +input stb_create_en_gate_x; +input stb_create_en_x; +input stb_create_fls; +input stb_create_lock; +input stb_create_sc_inst; +input [3 :0] stb_create_shift; +input [1 :0] stb_create_size; +input stb_create_split_first; +input stb_create_src1_depd; +input [4 :0] stb_create_src1_reg; +input stb_create_wait_lfb; +input stb_create_way; +input stb_create_wt_ca; +input stb_dca_done_x; +input stb_dca_grant_x; +input stb_pop_vld; +input stb_wbus_cmplt_x; +input stb_wbus_grant_x; +input stb_wca_grant_x; +output dc_hit_stb_addr_x; +output dc_hit_stb_dca_x; +output dc_hit_stb_full_x; +output dc_hit_stb_index_x; +output dc_hit_stb_part_x; +output stb_entry_age_x; +output stb_entry_biu_req_x; +output stb_entry_burst_x; +output stb_entry_busy_x; +output stb_entry_data_vld_x; +output stb_entry_dcache_req_x; +output stb_entry_dirty_x; +output stb_entry_lock_x; +output stb_entry_pop_vld_x; +output stb_entry_rdl_req_x; +output stb_entry_sc_inst_x; +output stb_entry_split_first_x; +output stb_entry_vld_dp_x; +output stb_entry_vld_x; +output stb_entry_way_x; +output [31:0] stb_entryx_addr; +output [1 :0] stb_entryx_bank; +output [3 :0] stb_entryx_bytes_vld; +output [31:0] stb_entryx_data; +output [10:0] stb_entryx_dbginfo; +output [1 :0] stb_entryx_dca_type; +output [3 :0] stb_entryx_prot; +output [1 :0] stb_entryx_size; + +// &Regs; @22 +reg stb_age; +reg [3 :0] stb_cur_state; +reg [31:0] stb_data_align; +reg [31:0] stb_entry_addr; +reg [2 :0] stb_entry_attr; +reg [3 :0] stb_entry_bytes_vld; +reg [31:0] stb_entry_data; +reg [1 :0] stb_entry_dca_type; +reg stb_entry_dirty; +reg stb_entry_fls; +reg stb_entry_lock; +reg stb_entry_sc_inst; +reg [2 :0] stb_entry_shift; +reg [1 :0] stb_entry_size; +reg stb_entry_split_first; +reg [4 :0] stb_entry_src1_reg; +reg stb_entry_way; +reg stb_entry_wb; +reg stb_entry_wt_ca; +reg [3 :0] stb_next_state; +reg stb_src1_depd; + +// &Wires; @23 +wire cp0_lsu_dcache_wb; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire dc_hit_stb_addr; +wire dc_hit_stb_addr_x; +wire dc_hit_stb_bytes; +wire dc_hit_stb_bytes_full; +wire dc_hit_stb_dca_x; +wire dc_hit_stb_dword; +wire dc_hit_stb_full_x; +wire dc_hit_stb_index_x; +wire dc_hit_stb_line; +wire dc_hit_stb_part_x; +wire [31:0] dc_xx_addr; +wire [7 :0] dc_xx_bytes_vld; +wire forever_cpuclk; +wire ifu_lsu_warm_up; +wire lfb_stb_done; +wire lfb_stb_err; +wire lfb_stb_fifo; +wire lfb_stb_fifo_update; +wire lfb_xx_idle; +wire pad_yy_icg_scan_en; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_yy_xx_async_flush; +wire [7 :0] stb_bytes_vld_extend; +wire stb_clk; +wire [31:0] stb_create_addr; +wire stb_create_age; +wire [2 :0] stb_create_attr; +wire [3 :0] stb_create_bytes_vld; +wire [31:0] stb_create_data; +wire stb_create_dca_inst; +wire [1 :0] stb_create_dca_type; +wire stb_create_dirty; +wire stb_create_en; +wire stb_create_en_gate_x; +wire stb_create_en_x; +wire stb_create_fls; +wire stb_create_lock; +wire stb_create_sc_inst; +wire [3 :0] stb_create_shift; +wire [1 :0] stb_create_size; +wire stb_create_split_first; +wire stb_create_src1_depd; +wire [4 :0] stb_create_src1_reg; +wire stb_create_wait_lfb; +wire stb_create_way; +wire stb_create_wt_ca; +wire stb_cur_idle; +wire stb_cur_rdl; +wire stb_cur_wbus; +wire stb_cur_wca; +wire stb_cur_wfc; +wire stb_cur_wlfb; +wire stb_cur_wrdl; +wire stb_dca_done_x; +wire stb_dca_grant_x; +wire stb_dp_clk; +wire stb_dp_clk_en; +wire stb_entry_age_x; +wire stb_entry_biu_req_x; +wire stb_entry_burst_x; +wire stb_entry_busy_x; +wire stb_entry_data_vld_x; +wire stb_entry_dca_inst; +wire stb_entry_dcache_req_x; +wire stb_entry_dirty_x; +wire stb_entry_dw; +wire stb_entry_lock_x; +wire stb_entry_pop_vld_x; +wire stb_entry_rdl_req_x; +wire stb_entry_sc_inst_x; +wire stb_entry_split_first_x; +wire stb_entry_src1_depd; +wire stb_entry_vld_dp_x; +wire stb_entry_vld_x; +wire stb_entry_way_x; +wire [31:0] stb_entryx_addr; +wire [1 :0] stb_entryx_bank; +wire [3 :0] stb_entryx_bytes_vld; +wire [31:0] stb_entryx_data; +wire [10:0] stb_entryx_dbginfo; +wire [1 :0] stb_entryx_dca_type; +wire [3 :0] stb_entryx_prot; +wire [1 :0] stb_entryx_size; +wire [31:0] stb_fwd_data; +wire stb_fwd_fwb; +wire stb_fwd_vld; +wire stb_pop_vld; +wire stb_vld; +wire stb_wbus_cmplt_x; +wire stb_wbus_grant_x; +wire stb_wca_grant_x; +wire stb_wdata_clk; +wire stb_wdata_clk_en; + + +parameter D_TAG_INDEX_LEN = `D_TAG_INDEX_WIDTH; +parameter DATAW = `FLEN; +parameter STB_IDLE = 4'b0000; +parameter STB_WLFB = 4'b0001; +parameter STB_WCA = 4'b0010; +parameter STB_WFC = 4'b0011; +parameter STB_RDL = 4'b0100; +parameter STB_WRDL = 4'b0101; +parameter STB_WBUS = 4'b1000; +parameter STB_WFD = 4'b0110; + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_cur_state[3:0] <= STB_IDLE; + else if (rtu_yy_xx_async_flush) + stb_cur_state[3:0] <= STB_IDLE; + else + stb_cur_state[3:0] <= stb_next_state[3:0]; +end + +assign stb_create_en = stb_create_en_x; + +// &CombBeg; @48 +always @( stb_fwd_vld + or stb_entry_wb + or stb_wbus_grant_x + or stb_cur_state[3:0] + or stb_create_en + or stb_entry_src1_depd + or stb_dca_done_x + or stb_entry_wt_ca + or stb_wca_grant_x + or stb_dca_grant_x + or stb_create_dca_inst + or stb_create_wt_ca + or lfb_stb_err + or stb_create_wait_lfb + or lfb_stb_done + or stb_create_src1_depd + or stb_wbus_cmplt_x) +begin + case(stb_cur_state[3:0]) + STB_IDLE: begin + if (stb_create_en) begin + if (stb_create_dca_inst) + stb_next_state[3:0] = STB_RDL; + else if (stb_create_wait_lfb) + stb_next_state[3:0] = STB_WLFB; + else if (!stb_create_src1_depd) + stb_next_state[3:0] = stb_create_wt_ca ? STB_WCA : STB_WBUS; + else + stb_next_state[3:0] = STB_WFD; + end + else + stb_next_state[3:0] = STB_IDLE; + end + STB_WFD: begin + if (stb_fwd_vld) + stb_next_state[3:0] = stb_entry_wt_ca ? STB_WCA : STB_WBUS; + else + stb_next_state[3:0] = STB_WFD; + end + STB_RDL: begin + if (stb_dca_grant_x) + stb_next_state[3:0] = STB_WRDL; + else + stb_next_state[3:0] = STB_RDL; + end + STB_WRDL: begin + if (stb_dca_done_x) + stb_next_state[3:0] = STB_IDLE; + else + stb_next_state[3:0] = STB_WRDL; + end + STB_WLFB: begin + if (lfb_stb_done & !stb_entry_src1_depd) + stb_next_state[3:0] = lfb_stb_err ? STB_WBUS : STB_WCA; + else if (lfb_stb_done & stb_entry_src1_depd) + stb_next_state[3:0] = STB_WFD; + else + stb_next_state[3:0] = STB_WLFB; + end + STB_WCA: begin + if (stb_wca_grant_x) + stb_next_state[3:0] = stb_entry_wb ? STB_IDLE : STB_WBUS; + else + stb_next_state[3:0] = STB_WCA; + end + STB_WBUS: begin + if (stb_wbus_grant_x) + stb_next_state[3:0] = STB_WFC; + else + stb_next_state[3:0] = STB_WBUS; + end + STB_WFC: begin + if (stb_wbus_cmplt_x) + stb_next_state[3:0] = STB_IDLE; + else + stb_next_state[3:0] = STB_WFC; + end + default: stb_next_state[3:0] = STB_IDLE; + endcase +// &CombEnd; @110 +end + +assign stb_cur_idle = stb_cur_state[3:0] == STB_IDLE; +assign stb_cur_rdl = stb_cur_state[3:0] == STB_RDL; +assign stb_cur_wrdl = stb_cur_state[3:0] == STB_WRDL; +assign stb_cur_wlfb = stb_cur_state[3:0] == STB_WLFB; +assign stb_cur_wca = stb_cur_state[3:0] == STB_WCA; +assign stb_cur_wbus = stb_cur_state[3]; //STB_WBUS; +assign stb_cur_wfc = stb_cur_state[3:0] == STB_WFC; + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_entry_wt_ca <= 1'b0; + else if (stb_create_en) + stb_entry_wt_ca <= stb_create_wt_ca; + else if (stb_cur_wlfb & lfb_stb_done) + stb_entry_wt_ca <= lfb_stb_err ? 1'b0 : 1'b1; +end + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_entry_way <= 1'b0; + else if (stb_create_en) + stb_entry_way <= stb_create_way; + else if (lfb_stb_fifo_update & stb_cur_wlfb) + stb_entry_way <= lfb_stb_fifo; +end + +always@(posedge stb_dp_clk) +begin + if (stb_create_en | ifu_lsu_warm_up) begin + stb_entry_addr[31:0] <= stb_create_addr[31:0]; + stb_entry_dca_type[1:0] <= stb_create_dca_type[1:0]; + stb_entry_dirty <= stb_create_dirty; + end +end + +// &Force("bus","stb_create_shift",3,0); @165 +always@(posedge stb_dp_clk) +begin + if (stb_create_en & !stb_create_dca_inst | ifu_lsu_warm_up) begin + stb_entry_bytes_vld[3:0] <= stb_create_bytes_vld[3:0]; + stb_entry_size[1:0] <= stb_create_size[1:0]; + stb_entry_attr[2:0] <= stb_create_attr[2:0]; + stb_entry_wb <= cp0_lsu_dcache_wb; + stb_entry_lock <= stb_create_lock; + stb_entry_sc_inst <= stb_create_sc_inst; + stb_entry_src1_reg[4:0] <= stb_create_src1_reg[4:0]; + stb_entry_fls <= stb_create_fls; + stb_entry_shift[2:0] <= stb_create_shift[2:0]; + stb_entry_split_first <= stb_create_split_first; + end +end + +assign stb_fwd_fwb = rtu_lsu_fgpr_wb_vld & stb_entry_fls & + (stb_entry_src1_reg[4:0] == rtu_lsu_fgpr_wb_reg[4:0]); + +assign stb_fwd_vld = stb_src1_depd & stb_fwd_fwb; +assign stb_fwd_data[DATAW-1:0] + = rtu_lsu_fgpr_wb_data[DATAW-1:0]; +// &Force("nonport","stb_entry_fls"); @220 +// &Force("nonport","stb_entry_src1_reg"); @221 + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_src1_depd <= 1'b0; + else if (stb_create_en) + stb_src1_depd <= stb_create_src1_depd; + else if (stb_fwd_vld) + stb_src1_depd <= 1'b0; +end + +assign stb_entry_src1_depd = stb_src1_depd & !stb_fwd_vld; + +always@(posedge stb_wdata_clk) +begin + if (stb_create_en & !stb_create_dca_inst | ifu_lsu_warm_up) + stb_entry_data[DATAW-1:0] <= stb_create_data[DATAW-1:0]; + else if (stb_fwd_vld) + stb_entry_data[DATAW-1:0] <= stb_fwd_data[DATAW-1:0]; +end + +always@(posedge stb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + stb_age <= 1'b0; + else if (stb_create_en) + stb_age <= stb_create_age; + else if (stb_pop_vld) + stb_age <= 1'b0; +end + +// &Force("output","stb_entry_pop_vld_x"); @270 + +assign stb_entry_vld_x = !stb_cur_idle & !stb_entry_pop_vld_x; +assign stb_entry_busy_x = !stb_cur_idle; +assign stb_entry_pop_vld_x = stb_cur_wca & stb_wca_grant_x & stb_entry_wb | + stb_cur_wfc & stb_wbus_cmplt_x | + stb_cur_wrdl & stb_dca_done_x; +assign stb_entry_age_x = stb_age; + +assign stb_entry_dcache_req_x = stb_cur_wca; +assign stb_entry_biu_req_x = stb_cur_wbus; + +assign stb_entryx_addr[31:0] = stb_entry_addr[31:0]; +assign stb_entryx_dca_type[1:0] = stb_entry_dca_type[1:0]; +assign stb_entryx_bytes_vld[3:0] = stb_entry_bytes_vld[3:0]; +assign stb_entryx_size[1:0] = stb_entry_size[1:0]; +assign stb_entryx_prot[3:0] = {stb_entry_attr[2:0], 1'b1}; +assign stb_entry_way_x = stb_entry_way; +assign stb_entry_lock_x = stb_entry_lock; +assign stb_entry_sc_inst_x = stb_entry_sc_inst; +assign stb_entryx_bank[1] = stb_entry_addr[2] | (stb_entry_size[1:0] == 2'b11); +assign stb_entryx_bank[0] = !stb_entry_addr[2] | (stb_entry_size[1:0] == 2'b11); +assign stb_entry_burst_x = (stb_entry_size[1:0] == 2'b11); +assign stb_entry_data_vld_x = !stb_src1_depd; +assign stb_entry_split_first_x = stb_entry_split_first; + +// &CombBeg; @297 +// &CombEnd; @309 +// &CombBeg; @311 +always @( stb_entry_data[31:0] + or stb_entry_shift[1:0]) +begin + case(stb_entry_shift[1:0]) + 2'b00: stb_data_align[31:0] = stb_entry_data[31:0]; + 2'b01: stb_data_align[31:0] = {stb_entry_data[23:0],stb_entry_data[31:24]}; + 2'b10: stb_data_align[31:0] = {stb_entry_data[15:0],stb_entry_data[31:16]}; + 2'b11: stb_data_align[31:0] = {stb_entry_data[7:0], stb_entry_data[31:8]}; + default: stb_data_align[31:0] = stb_entry_data[31:0]; + endcase +// &CombEnd; @319 +end + +assign stb_entryx_data[DATAW-1:0] = stb_data_align[DATAW-1:0]; + +//================================================ +// dcache inst request RDL +//================================================ +assign stb_entry_rdl_req_x = stb_cur_rdl & lfb_xx_idle; +assign stb_entry_dirty_x = stb_entry_dirty; + +//================================================ +// dependency check +//================================================ +// &Force("bus","dc_xx_addr",31,0); @333 +assign stb_entry_dw = stb_entry_size[1:0] == 2'b11; +assign stb_bytes_vld_extend[7:0] = stb_entry_addr[2] ? {stb_entry_bytes_vld[3:0], 4'b0000} + : {{4{stb_entry_dw}},stb_entry_bytes_vld[3:0]}; + +assign stb_vld = !stb_cur_idle; +assign dc_hit_stb_line = (dc_xx_addr[31:5] == stb_entry_addr[31:5]) & + stb_vld; +assign dc_hit_stb_dword = (dc_xx_addr[4:3] == stb_entry_addr[4:3]); + +assign dc_hit_stb_addr = dc_hit_stb_line & dc_hit_stb_dword; +assign dc_hit_stb_bytes_full = (dc_xx_bytes_vld[7:0] == stb_bytes_vld_extend[7:0]); +assign dc_hit_stb_bytes = |(dc_xx_bytes_vld[7:0] & stb_bytes_vld_extend[7:0]); + +assign stb_entry_dca_inst = stb_cur_rdl | stb_cur_wrdl; + +assign dc_hit_stb_addr_x = dc_hit_stb_addr & stb_src1_depd; +assign dc_hit_stb_full_x = dc_hit_stb_addr & dc_hit_stb_bytes_full; +assign dc_hit_stb_part_x = dc_hit_stb_addr & dc_hit_stb_bytes & !dc_hit_stb_bytes_full; +assign dc_hit_stb_dca_x = dc_hit_stb_line & stb_entry_dca_inst; + +assign dc_hit_stb_index_x = (dc_xx_addr[D_TAG_INDEX_LEN+4:5] == stb_entry_addr[D_TAG_INDEX_LEN+4:5]) & + stb_vld; + +assign stb_entry_vld_dp_x = stb_vld; + +//================================================ +// ICG +//================================================ +assign stb_dp_clk_en = stb_create_en_gate_x | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_stb_dp_gated_clk"); @363 +gated_clk_cell x_pa_lsu_stb_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (stb_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (stb_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @364 +// .external_en (1'b0), @365 +// .global_en (1'b1), @366 +// .module_en (cp0_lsu_icg_en ), @367 +// .local_en (stb_dp_clk_en), @368 +// .clk_out (stb_dp_clk)); @369 + +assign stb_wdata_clk_en = stb_create_en_gate_x | stb_fwd_vld | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_stb_wdata_gated_clk"); @372 +gated_clk_cell x_pa_lsu_stb_wdata_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (stb_wdata_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (stb_wdata_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @373 +// .external_en (1'b0), @374 +// .global_en (1'b1), @375 +// .module_en (cp0_lsu_icg_en ), @376 +// .local_en (stb_wdata_clk_en), @377 +// .clk_out (stb_wdata_clk)); @378 + +assign stb_entryx_dbginfo[10:0] = {stb_entry_src1_reg[4:0], + stb_entry_fls, + stb_src1_depd, + stb_cur_state[3:0]}; + +// &ModuleEnd; @385 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..1128084946d6ac52679eff5209bae110197e3b77 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_top.v @@ -0,0 +1,2310 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_top( + bmu_lsu_acc_err, + bmu_lsu_grant, + bmu_lsu_rdata, + bmu_lsu_trans_cmplt, + cp0_lsu_dcache_en, + cp0_lsu_dcache_wa, + cp0_lsu_dcache_wb, + cp0_lsu_fence_req, + cp0_lsu_icc_addr, + cp0_lsu_icc_op, + cp0_lsu_icc_req, + cp0_lsu_icc_type, + cp0_lsu_icg_en, + cp0_lsu_mm, + cp0_lsu_sync_req, + cp0_xx_async_expt_en, + cp0_yy_mach_mode, + cpurst_b, + dtu_lsu_addr_trig_en, + dtu_lsu_data_trig_en, + dtu_lsu_halt_info, + dtu_lsu_halt_info_vld, + forever_cpuclk, + idu_lsu_ex1_ag_imm, + idu_lsu_ex1_base, + idu_lsu_ex1_base_sel, + idu_lsu_ex1_base_wb, + idu_lsu_ex1_data, + idu_lsu_ex1_dest_reg, + idu_lsu_ex1_dest_vld, + idu_lsu_ex1_dp_sel, + idu_lsu_ex1_fls, + idu_lsu_ex1_func, + idu_lsu_ex1_gateclk_sel, + idu_lsu_ex1_halt_info, + idu_lsu_ex1_ipop_int_mask, + idu_lsu_ex1_ipush_spec, + idu_lsu_ex1_length, + idu_lsu_ex1_offset_sel, + idu_lsu_ex1_sel, + idu_lsu_ex1_sign_extend, + idu_lsu_ex1_size, + idu_lsu_ex1_split, + idu_lsu_ex1_src0_reg, + idu_lsu_ex1_src1_depd, + idu_lsu_ex1_src1_reg, + ifu_lsu_warm_up, + iu_lsu_ex1_lsi_rst, + iu_lsu_ex2_wb0_grant, + lsu_biu_amo_pmp_deny, + lsu_biu_async_expt_ack, + lsu_bmu_acc_deny, + lsu_bmu_addr, + lsu_bmu_burst, + lsu_bmu_lock, + lsu_bmu_lrsc, + lsu_bmu_prot, + lsu_bmu_req, + lsu_bmu_req_dp, + lsu_bmu_seq, + lsu_bmu_size, + lsu_bmu_wdata, + lsu_bmu_write, + lsu_cp0_fence_ack, + lsu_cp0_icc_done, + lsu_cp0_sync_ack, + lsu_dtu_debug_info, + lsu_dtu_halt_info, + lsu_dtu_last_check, + lsu_dtu_ldst_addr, + lsu_dtu_ldst_addr_vld, + lsu_dtu_ldst_bytes_vld, + lsu_dtu_ldst_data, + lsu_dtu_ldst_data_vld, + lsu_dtu_ldst_type, + lsu_dtu_mem_access_size, + lsu_hpcp_cache_read_access, + lsu_hpcp_cache_read_access_gate, + lsu_hpcp_cache_read_miss, + lsu_hpcp_cache_read_miss_gate, + lsu_hpcp_cache_write_access, + lsu_hpcp_cache_write_access_gate, + lsu_hpcp_cache_write_miss, + lsu_hpcp_cache_write_miss_gate, + lsu_hpcp_inst_store, + lsu_hpcp_inst_store_gate, + lsu_idu_ex1_halt_info, + lsu_idu_ex1_halt_info_update_en, + lsu_idu_ex1_src1_update_en, + lsu_idu_ex1_src1_update_en_gate, + lsu_idu_ex1_stall, + lsu_idu_ex2_ffwd_data, + lsu_idu_ex2_ffwd_vld, + lsu_idu_ex2_fwd_data, + lsu_idu_ex2_fwd_freg, + lsu_idu_ex2_fwd_preg, + lsu_idu_ex2_fwd_vld, + lsu_idu_ex3_ffwd_data, + lsu_idu_ex3_ffwd_vld, + lsu_idu_ex3_fwd_data, + lsu_idu_ex3_fwd_freg, + lsu_idu_ex3_fwd_preg, + lsu_idu_ex3_fwd_vld, + lsu_idu_global_stall, + lsu_idu_update_addr, + lsu_idu_update_en, + lsu_idu_update_en_gate, + lsu_idu_update_offset, + lsu_iu_ex1_base_wb, + lsu_iu_ex1_src1_sel, + lsu_iu_ex2_data, + lsu_iu_ex2_data_vld, + lsu_iu_ex2_dest_reg, + lsu_iu_ex2_lsi_dst_preg, + lsu_iu_ex2_lsi_rslt, + lsu_iu_ex2_lsi_rslt_vld, + lsu_pmp_addr, + lsu_pmp_write, + lsu_rtu_async_expt_vld, + lsu_rtu_async_ld_inst, + lsu_rtu_async_tval, + lsu_rtu_ex1_cmplt, + lsu_rtu_ex1_cmplt_dp, + lsu_rtu_ex1_halt_info, + lsu_rtu_ex1_inst_len, + lsu_rtu_ex1_inst_vld, + lsu_rtu_ex1_ipop_int_mask, + lsu_rtu_ex1_ipush_spec_inst, + lsu_rtu_ex1_split_inst, + lsu_rtu_ex2_bus_err, + lsu_rtu_ex2_expt_inst, + lsu_rtu_ex2_expt_vec, + lsu_rtu_ex2_stall, + lsu_rtu_ex2_tval, + lsu_rtu_fgpr_wb_data, + lsu_rtu_fgpr_wb_reg, + lsu_rtu_fgpr_wb_vld, + lsu_rtu_sync_ack, + lsu_rtu_wb_data, + lsu_rtu_wb_preg, + lsu_rtu_wb_vld, + lsu_sysmap_pa, + lsu_xx_flush, + lsu_xx_no_op, + lsu_xx_warm_up, + pad_yy_icg_scan_en, + pmp_lsu_acc_deny, + rtu_lsu_async_expt_ack, + rtu_lsu_expt_ack, + rtu_lsu_expt_exit, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_lsu_inst_retire, + rtu_lsu_sync_req, + rtu_lsu_wb1_data, + rtu_lsu_wb1_lsu_vld, + rtu_lsu_wb1_preg, + rtu_xx_ex1_stall, + rtu_yy_xx_async_flush, + rtu_yy_xx_dbgon, + rtu_yy_xx_flush, + sysmap_lsu_flg +); + +// &Ports; @21 +input bmu_lsu_acc_err; +input bmu_lsu_grant; +input [31:0] bmu_lsu_rdata; +input bmu_lsu_trans_cmplt; +input cp0_lsu_dcache_en; +input cp0_lsu_dcache_wa; +input cp0_lsu_dcache_wb; +input cp0_lsu_fence_req; +input [31:0] cp0_lsu_icc_addr; +input [1 :0] cp0_lsu_icc_op; +input cp0_lsu_icc_req; +input [1 :0] cp0_lsu_icc_type; +input cp0_lsu_icg_en; +input cp0_lsu_mm; +input cp0_lsu_sync_req; +input cp0_xx_async_expt_en; +input cp0_yy_mach_mode; +input cpurst_b; +input dtu_lsu_addr_trig_en; +input dtu_lsu_data_trig_en; +input [14:0] dtu_lsu_halt_info; +input dtu_lsu_halt_info_vld; +input forever_cpuclk; +input [31:0] idu_lsu_ex1_ag_imm; +input [31:0] idu_lsu_ex1_base; +input idu_lsu_ex1_base_sel; +input idu_lsu_ex1_base_wb; +input [31:0] idu_lsu_ex1_data; +input [5 :0] idu_lsu_ex1_dest_reg; +input idu_lsu_ex1_dest_vld; +input idu_lsu_ex1_dp_sel; +input idu_lsu_ex1_fls; +input [3 :0] idu_lsu_ex1_func; +input idu_lsu_ex1_gateclk_sel; +input [14:0] idu_lsu_ex1_halt_info; +input idu_lsu_ex1_ipop_int_mask; +input idu_lsu_ex1_ipush_spec; +input idu_lsu_ex1_length; +input idu_lsu_ex1_offset_sel; +input idu_lsu_ex1_sel; +input idu_lsu_ex1_sign_extend; +input [1 :0] idu_lsu_ex1_size; +input idu_lsu_ex1_split; +input [5 :0] idu_lsu_ex1_src0_reg; +input idu_lsu_ex1_src1_depd; +input [5 :0] idu_lsu_ex1_src1_reg; +input ifu_lsu_warm_up; +input [31:0] iu_lsu_ex1_lsi_rst; +input iu_lsu_ex2_wb0_grant; +input pad_yy_icg_scan_en; +input pmp_lsu_acc_deny; +input rtu_lsu_async_expt_ack; +input rtu_lsu_expt_ack; +input rtu_lsu_expt_exit; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_lsu_inst_retire; +input rtu_lsu_sync_req; +input [31:0] rtu_lsu_wb1_data; +input rtu_lsu_wb1_lsu_vld; +input [5 :0] rtu_lsu_wb1_preg; +input rtu_xx_ex1_stall; +input rtu_yy_xx_async_flush; +input rtu_yy_xx_dbgon; +input rtu_yy_xx_flush; +input [4 :0] sysmap_lsu_flg; +output lsu_biu_amo_pmp_deny; +output lsu_biu_async_expt_ack; +output lsu_bmu_acc_deny; +output [31:0] lsu_bmu_addr; +output [2 :0] lsu_bmu_burst; +output lsu_bmu_lock; +output lsu_bmu_lrsc; +output [3 :0] lsu_bmu_prot; +output lsu_bmu_req; +output lsu_bmu_req_dp; +output lsu_bmu_seq; +output [1 :0] lsu_bmu_size; +output [31:0] lsu_bmu_wdata; +output lsu_bmu_write; +output lsu_cp0_fence_ack; +output lsu_cp0_icc_done; +output lsu_cp0_sync_ack; +output [78:0] lsu_dtu_debug_info; +output [14:0] lsu_dtu_halt_info; +output lsu_dtu_last_check; +output [31:0] lsu_dtu_ldst_addr; +output lsu_dtu_ldst_addr_vld; +output [7 :0] lsu_dtu_ldst_bytes_vld; +output [31:0] lsu_dtu_ldst_data; +output lsu_dtu_ldst_data_vld; +output [1 :0] lsu_dtu_ldst_type; +output [1 :0] lsu_dtu_mem_access_size; +output lsu_hpcp_cache_read_access; +output lsu_hpcp_cache_read_access_gate; +output lsu_hpcp_cache_read_miss; +output lsu_hpcp_cache_read_miss_gate; +output lsu_hpcp_cache_write_access; +output lsu_hpcp_cache_write_access_gate; +output lsu_hpcp_cache_write_miss; +output lsu_hpcp_cache_write_miss_gate; +output lsu_hpcp_inst_store; +output lsu_hpcp_inst_store_gate; +output [14:0] lsu_idu_ex1_halt_info; +output lsu_idu_ex1_halt_info_update_en; +output lsu_idu_ex1_src1_update_en; +output lsu_idu_ex1_src1_update_en_gate; +output lsu_idu_ex1_stall; +output [31:0] lsu_idu_ex2_ffwd_data; +output lsu_idu_ex2_ffwd_vld; +output [31:0] lsu_idu_ex2_fwd_data; +output [4 :0] lsu_idu_ex2_fwd_freg; +output [5 :0] lsu_idu_ex2_fwd_preg; +output lsu_idu_ex2_fwd_vld; +output [31:0] lsu_idu_ex3_ffwd_data; +output lsu_idu_ex3_ffwd_vld; +output [31:0] lsu_idu_ex3_fwd_data; +output [4 :0] lsu_idu_ex3_fwd_freg; +output [5 :0] lsu_idu_ex3_fwd_preg; +output lsu_idu_ex3_fwd_vld; +output lsu_idu_global_stall; +output [31:0] lsu_idu_update_addr; +output lsu_idu_update_en; +output lsu_idu_update_en_gate; +output [31:0] lsu_idu_update_offset; +output lsu_iu_ex1_base_wb; +output lsu_iu_ex1_src1_sel; +output [31:0] lsu_iu_ex2_data; +output lsu_iu_ex2_data_vld; +output [5 :0] lsu_iu_ex2_dest_reg; +output [5 :0] lsu_iu_ex2_lsi_dst_preg; +output [31:0] lsu_iu_ex2_lsi_rslt; +output lsu_iu_ex2_lsi_rslt_vld; +output [31:0] lsu_pmp_addr; +output lsu_pmp_write; +output lsu_rtu_async_expt_vld; +output lsu_rtu_async_ld_inst; +output [31:0] lsu_rtu_async_tval; +output lsu_rtu_ex1_cmplt; +output lsu_rtu_ex1_cmplt_dp; +output [14:0] lsu_rtu_ex1_halt_info; +output lsu_rtu_ex1_inst_len; +output lsu_rtu_ex1_inst_vld; +output lsu_rtu_ex1_ipop_int_mask; +output lsu_rtu_ex1_ipush_spec_inst; +output lsu_rtu_ex1_split_inst; +output lsu_rtu_ex2_bus_err; +output lsu_rtu_ex2_expt_inst; +output [3 :0] lsu_rtu_ex2_expt_vec; +output lsu_rtu_ex2_stall; +output [31:0] lsu_rtu_ex2_tval; +output [31:0] lsu_rtu_fgpr_wb_data; +output [4 :0] lsu_rtu_fgpr_wb_reg; +output lsu_rtu_fgpr_wb_vld; +output lsu_rtu_sync_ack; +output [31:0] lsu_rtu_wb_data; +output [5 :0] lsu_rtu_wb_preg; +output lsu_rtu_wb_vld; +output [31:0] lsu_sysmap_pa; +output lsu_xx_flush; +output lsu_xx_no_op; +output lsu_xx_warm_up; + +// &Regs; @22 +reg [31:0] da_data; +reg [5 :0] da_dest_reg; +reg da_fls; +reg da_fls_double; +reg da_inst_vld; +reg da_sc_inst; +reg [31:0] data_align; +reg [31:0] data_align_ext; +reg [3 :0] mb_bytes_vld; +reg mb_cur_state; +reg [31:0] mb_data; +reg [5 :0] mb_dest_reg; +reg mb_fls; +reg mb_flw; +reg mb_next_state; +reg mb_sign_ext; +reg [1 :0] mb_size; +reg mb_split_checked; + +// &Wires; @23 +wire [31:0] ag_dc_addr; +wire ag_dc_buf; +wire [3 :0] ag_dc_bytes_vld; +wire ag_dc_ca; +wire ag_dc_dcache_grant; +wire [5 :0] ag_dc_dest_reg; +wire ag_dc_fls; +wire [3 :0] ag_dc_func; +wire ag_dc_inst_vld; +wire ag_dc_inst_vld_gate; +wire ag_dc_lm_pass; +wire ag_dc_mach_mode; +wire [1 :0] ag_dc_ori_size; +wire ag_dc_pmp_expt; +wire ag_dc_sign_ext; +wire [1 :0] ag_dc_size; +wire ag_dc_so; +wire ag_dc_split; +wire ag_dc_split_first; +wire ag_dc_split_last; +wire ag_dc_src1_depd; +wire [5 :0] ag_dc_src1_reg; +wire [31:0] ag_dc_st_data; +wire [2 :0] ag_dc_wdata_shift; +wire [31:0] ag_dtu_addr; +wire ag_dtu_addr_ready; +wire ag_dtu_amo_type; +wire [7 :0] ag_dtu_bytes_vld; +wire [31:0] ag_dtu_data; +wire ag_dtu_data_chk_mask; +wire ag_dtu_data_vld; +wire [14:0] ag_dtu_halt_info; +wire [1 :0] ag_dtu_mem_access_size; +wire ag_dtu_pipe_down; +wire ag_dtu_req; +wire ag_dtu_req_gate; +wire ag_dtu_split_last; +wire ag_dtu_st_type; +wire [31:0] ag_ncb_addr; +wire ag_ncb_inst_vld; +wire ag_ncb_inst_vld_dp; +wire [5 :0] ag_ncb_src1_reg; +wire [31:0] ag_ncb_st_data; +wire ag_xx_inst_abort; +wire ag_xx_split_done; +wire arb_icc_data_grant; +wire arb_rdl_grant; +wire arb_stb_xx_grant; +wire bmu_lsu_acc_err; +wire bmu_lsu_grant; +wire [31:0] bmu_lsu_rdata; +wire bmu_lsu_trans_cmplt; +wire [3 :0] bytes_vld; +wire cp0_lsu_dcache_en; +wire cp0_lsu_dcache_wa; +wire cp0_lsu_dcache_wb; +wire cp0_lsu_fence_req; +wire [31:0] cp0_lsu_icc_addr; +wire [1 :0] cp0_lsu_icc_op; +wire cp0_lsu_icc_req; +wire [1 :0] cp0_lsu_icc_type; +wire cp0_lsu_icg_en; +wire cp0_lsu_mm; +wire cp0_xx_async_expt_en; +wire cp0_yy_mach_mode; +wire cpurst_b; +wire da_clk; +wire da_clk_en; +wire da_data_vld; +wire da_dp_clk; +wire da_dp_clk_en; +wire [31:0] da_dtu_data; +wire da_dtu_data_expt_vld; +wire da_dtu_data_vld; +wire [31:0] da_xx_fwd_data; +wire da_xx_fwd_fls; +wire [5 :0] da_xx_fwd_preg; +wire da_xx_fwd_vld; +wire da_xx_no_op; +wire [4 :0] dahbif_dbginfo; +wire dahbif_lfb_acc_err; +wire dahbif_lfb_cmplt; +wire [31:0] dahbif_lfb_data; +wire dahbif_lfb_grant; +wire dahbif_ncb_acc_err; +wire dahbif_ncb_cmplt; +wire [31:0] dahbif_ncb_data; +wire dahbif_ncb_grant; +wire dahbif_ncb_grant_2; +wire dahbif_stb_acc_ecc; +wire dahbif_stb_cmplt; +wire dahbif_stb_grant; +wire dahbif_stb_grant_2; +wire dahbif_vb_acc_ecc; +wire dahbif_vb_cmplt; +wire dahbif_vb_grant; +wire [31:0] data; +wire dc_ag_async_expt_vld; +wire dc_ag_async_ld_inst; +wire [31:0] dc_ag_async_mtval; +wire dc_ag_cache_stall; +wire [31:0] dc_ag_dcache_addr; +wire dc_ag_dcache_req; +wire [1 :0] dc_ag_dcache_size; +wire dc_ag_empty; +wire [3 :0] dc_ag_func; +wire dc_ag_pmp_ld_inst; +wire [31:0] dc_ag_pmp_mtval; +wire dc_ag_stall; +wire [31:0] dc_da_data; +wire dc_da_data_vld; +wire dc_da_data_vld_dp; +wire [5 :0] dc_da_dest_reg; +wire dc_da_fls; +wire dc_da_fls_double; +wire dc_da_sc_data_vld; +wire [14:0] dc_dbginfo; +wire [63:0] dc_icc_way0_data; +wire dc_icc_way0_dirty; +wire [21:0] dc_icc_way0_tag; +wire [63:0] dc_icc_way1_data; +wire dc_icc_way1_dirty; +wire [21:0] dc_icc_way1_tag; +wire dc_idle; +wire [31:0] dc_lfb_addr; +wire dc_lfb_buf; +wire dc_lfb_ca; +wire dc_lfb_ca_raw; +wire dc_lfb_create_en; +wire dc_lfb_create_en_gate; +wire dc_lfb_inst_ld; +wire dc_lfb_lock_trans; +wire dc_lfb_lr_inst; +wire dc_lfb_mach_mode; +wire [1 :0] dc_lfb_size; +wire dc_rdl_fifo; +wire [63:0] dc_rdl_way0_data; +wire dc_rdl_way0_dirty; +wire [21:0] dc_rdl_way0_tag; +wire dc_rdl_way0_vld; +wire [63:0] dc_rdl_way1_data; +wire dc_rdl_way1_dirty; +wire [21:0] dc_rdl_way1_tag; +wire dc_rdl_way1_vld; +wire [31:0] dc_stb_addr; +wire [2 :0] dc_stb_attr; +wire [3 :0] dc_stb_bytes_vld; +wire dc_stb_cache_hit; +wire dc_stb_create_en; +wire dc_stb_create_en_gate; +wire [31:0] dc_stb_data; +wire dc_stb_dcache_dirty; +wire dc_stb_dcache_inst; +wire [1 :0] dc_stb_dcache_type; +wire dc_stb_dcache_way; +wire dc_stb_fls; +wire dc_stb_lock_trans; +wire dc_stb_sc_inst; +wire [2 :0] dc_stb_shift; +wire [1 :0] dc_stb_size; +wire dc_stb_split_first; +wire dc_stb_src1_depd; +wire [4 :0] dc_stb_src1_reg; +wire dc_stb_wait_lfb; +wire dc_vb_st_amold; +wire [31:0] dc_xx_addr; +wire [7 :0] dc_xx_bytes_vld; +wire dcache_data_cen_way0_bank0; +wire dcache_data_cen_way0_bank1; +wire dcache_data_cen_way1_bank0; +wire dcache_data_cen_way1_bank1; +wire [63:0] dcache_data_din; +wire [63:0] dcache_data_dout_way0; +wire [63:0] dcache_data_dout_way1; +wire [11:0] dcache_data_idx; +wire [3 :0] dcache_data_wen; +wire dcache_dirty_cen; +wire [2 :0] dcache_dirty_din; +wire [2 :0] dcache_dirty_dout; +wire [9 :0] dcache_dirty_idx; +wire [2 :0] dcache_dirty_wen; +wire dcache_tag_cen; +wire [22:0] dcache_tag_din; +wire [45:0] dcache_tag_dout; +wire [9 :0] dcache_tag_idx; +wire [1 :0] dcache_tag_wen; +wire [5 :0] dest_reg; +wire dtif_ag_cmplt_ready; +wire dtif_ag_fsm_idle; +wire [14:0] dtif_ag_halt_info; +wire dtif_ag_halt_info_up; +wire dtif_ag_pipedown_mask; +wire dtif_ag_stall; +wire dtu_lsu_addr_trig_en; +wire dtu_lsu_data_trig_en; +wire [14:0] dtu_lsu_halt_info; +wire dtu_lsu_halt_info_vld; +wire fls; +wire flw; +wire forever_cpuclk; +wire [1 :0] icc_arb_data_bank; +wire [63:0] icc_arb_data_din; +wire [11:0] icc_arb_data_idx; +wire icc_arb_data_req; +wire [1 :0] icc_arb_data_way; +wire [3 :0] icc_arb_data_wen; +wire [2 :0] icc_arb_dirty_din; +wire [9 :0] icc_arb_dirty_idx; +wire icc_arb_dirty_req; +wire [2 :0] icc_arb_dirty_wen; +wire [22:0] icc_arb_tag_din; +wire [9 :0] icc_arb_tag_idx; +wire icc_arb_tag_req; +wire [1 :0] icc_arb_tag_wen; +wire [26:0] icc_vb_addr; +wire icc_vb_clr_vld; +wire icc_vb_create_en; +wire [63:0] icc_vb_data; +wire [1 :0] icc_vb_data_cnt; +wire icc_vb_data_create; +wire icc_vb_line_dirty; +wire icc_xx_idle; +wire [31:0] idu_lsu_ex1_ag_imm; +wire [31:0] idu_lsu_ex1_base; +wire idu_lsu_ex1_base_sel; +wire idu_lsu_ex1_base_wb; +wire [31:0] idu_lsu_ex1_data; +wire [5 :0] idu_lsu_ex1_dest_reg; +wire idu_lsu_ex1_dest_vld; +wire idu_lsu_ex1_dp_sel; +wire idu_lsu_ex1_fls; +wire [3 :0] idu_lsu_ex1_func; +wire idu_lsu_ex1_gateclk_sel; +wire [14:0] idu_lsu_ex1_halt_info; +wire idu_lsu_ex1_ipop_int_mask; +wire idu_lsu_ex1_ipush_spec; +wire idu_lsu_ex1_length; +wire idu_lsu_ex1_offset_sel; +wire idu_lsu_ex1_sel; +wire idu_lsu_ex1_sign_extend; +wire [1 :0] idu_lsu_ex1_size; +wire idu_lsu_ex1_split; +wire [5 :0] idu_lsu_ex1_src0_reg; +wire idu_lsu_ex1_src1_depd; +wire [5 :0] idu_lsu_ex1_src1_reg; +wire ifu_lsu_warm_up; +wire [31:0] iu_lsu_ex1_lsi_rst; +wire iu_lsu_ex2_wb0_grant; +wire [1 :0] lfb_arb_data_bank; +wire [63:0] lfb_arb_data_din; +wire [11:0] lfb_arb_data_idx; +wire lfb_arb_data_req; +wire [1 :0] lfb_arb_data_way; +wire [3 :0] lfb_arb_data_wen; +wire lfb_arb_dcache_sel; +wire [2 :0] lfb_arb_dirty_din; +wire [9 :0] lfb_arb_dirty_idx; +wire lfb_arb_dirty_req; +wire [2 :0] lfb_arb_dirty_wen; +wire [22:0] lfb_arb_tag_din; +wire [9 :0] lfb_arb_tag_idx; +wire lfb_arb_tag_req; +wire [1 :0] lfb_arb_tag_wen; +wire [31:0] lfb_dahbif_addr; +wire [2 :0] lfb_dahbif_burst; +wire lfb_dahbif_lock; +wire lfb_dahbif_lr_inst; +wire [3 :0] lfb_dahbif_prot; +wire lfb_dahbif_req; +wire [1 :0] lfb_dahbif_size; +wire [3 :0] lfb_dbginfo; +wire lfb_dc_async_expt; +wire lfb_dc_busy; +wire lfb_dc_hit_idx; +wire lfb_dc_ld_cmplt; +wire [31:0] lfb_dc_ld_data; +wire lfb_dc_ld_data_vld; +wire lfb_dc_pop_en; +wire [9 :0] lfb_rdl_index; +wire lfb_rdl_start; +wire lfb_rdl_start_gate; +wire lfb_stb_done; +wire lfb_stb_err; +wire lfb_stb_fifo; +wire lfb_stb_fifo_update; +wire lfb_xx_idle; +wire lm_clr; +wire [33:0] lm_lr_bus; +wire lm_pass; +wire [33:0] lm_sc_bus; +wire lm_set; +wire lm_set_gate; +wire lsu_acc_fault_vld; +wire lsu_biu_amo_pmp_deny; +wire lsu_biu_async_expt_ack; +wire lsu_bmu_acc_deny; +wire [31:0] lsu_bmu_addr; +wire [2 :0] lsu_bmu_burst; +wire lsu_bmu_lock; +wire lsu_bmu_lrsc; +wire [3 :0] lsu_bmu_prot; +wire lsu_bmu_req; +wire lsu_bmu_req_dp; +wire lsu_bmu_seq; +wire [1 :0] lsu_bmu_size; +wire [31:0] lsu_bmu_wdata; +wire lsu_bmu_write; +wire lsu_cp0_fence_ack; +wire lsu_cp0_icc_done; +wire lsu_cp0_sync_ack; +wire [78:0] lsu_dtu_debug_info; +wire lsu_dtu_ex2_expt_vld; +wire [14:0] lsu_dtu_halt_info; +wire lsu_dtu_last_check; +wire [31:0] lsu_dtu_ldst_addr; +wire lsu_dtu_ldst_addr_vld; +wire [7 :0] lsu_dtu_ldst_bytes_vld; +wire [31:0] lsu_dtu_ldst_data; +wire lsu_dtu_ldst_data_vld; +wire [1 :0] lsu_dtu_ldst_type; +wire [1 :0] lsu_dtu_mem_access_size; +wire lsu_ex2_addr_2; +wire [3 :0] lsu_ex2_bytes_vld; +wire [3 :0] lsu_ex2_bytes_vld_ext; +wire lsu_ex2_checked; +wire [31:0] lsu_ex2_data; +wire lsu_ex2_data_vld; +wire lsu_ex2_data_vld_gate; +wire [5 :0] lsu_ex2_dest_reg; +wire lsu_ex2_fld; +wire lsu_ex2_fls; +wire lsu_ex2_flw; +wire lsu_ex2_lock; +wire lsu_ex2_sc_data_vld; +wire lsu_ex2_sign_ext; +wire [1 :0] lsu_ex2_size; +wire lsu_ex2_split; +wire lsu_ex2_split_last; +wire lsu_ex2_stall; +wire lsu_ex2_stall_final; +wire lsu_hpcp_cache_read_access; +wire lsu_hpcp_cache_read_access_gate; +wire lsu_hpcp_cache_read_miss; +wire lsu_hpcp_cache_read_miss_gate; +wire lsu_hpcp_cache_write_access; +wire lsu_hpcp_cache_write_access_gate; +wire lsu_hpcp_cache_write_miss; +wire lsu_hpcp_cache_write_miss_gate; +wire lsu_hpcp_inst_store; +wire lsu_hpcp_inst_store_gate; +wire [14:0] lsu_idu_ex1_halt_info; +wire lsu_idu_ex1_halt_info_update_en; +wire lsu_idu_ex1_src1_update_en; +wire lsu_idu_ex1_src1_update_en_gate; +wire lsu_idu_ex1_stall; +wire [31:0] lsu_idu_ex2_ffwd_data; +wire lsu_idu_ex2_ffwd_vld; +wire [31:0] lsu_idu_ex2_fwd_data; +wire [4 :0] lsu_idu_ex2_fwd_freg; +wire [5 :0] lsu_idu_ex2_fwd_preg; +wire lsu_idu_ex2_fwd_vld; +wire [31:0] lsu_idu_ex3_ffwd_data; +wire lsu_idu_ex3_ffwd_vld; +wire [31:0] lsu_idu_ex3_fwd_data; +wire [4 :0] lsu_idu_ex3_fwd_freg; +wire [5 :0] lsu_idu_ex3_fwd_preg; +wire lsu_idu_ex3_fwd_vld; +wire lsu_idu_global_stall; +wire [31:0] lsu_idu_update_addr; +wire lsu_idu_update_en; +wire lsu_idu_update_en_gate; +wire [31:0] lsu_idu_update_offset; +wire lsu_iu_ex1_base_wb; +wire lsu_iu_ex1_src1_sel; +wire [31:0] lsu_iu_ex2_data; +wire lsu_iu_ex2_data_vld; +wire [5 :0] lsu_iu_ex2_dest_reg; +wire [5 :0] lsu_iu_ex2_lsi_dst_preg; +wire [31:0] lsu_iu_ex2_lsi_rslt; +wire lsu_iu_ex2_lsi_rslt_vld; +wire lsu_mb_ex2_ca_addr_2; +wire [3 :0] lsu_mb_ex2_ca_bytes_vld; +wire [31:0] lsu_mb_ex2_ca_data; +wire lsu_mb_ex2_ca_data_vld; +wire lsu_mb_ex2_ca_data_vld_gate; +wire [5 :0] lsu_mb_ex2_ca_dest_reg; +wire lsu_mb_ex2_ca_fld; +wire lsu_mb_ex2_ca_fls; +wire lsu_mb_ex2_ca_lock; +wire lsu_mb_ex2_ca_sc_data_vld; +wire lsu_mb_ex2_ca_sign_ext; +wire [1 :0] lsu_mb_ex2_ca_size; +wire lsu_mb_ex2_ca_split; +wire lsu_mb_ex2_ca_split_last; +wire lsu_mb_ex2_ca_stall; +wire lsu_mb_ex2_uc_addr_2; +wire [3 :0] lsu_mb_ex2_uc_bytes_vld; +wire [31:0] lsu_mb_ex2_uc_data; +wire lsu_mb_ex2_uc_data_vld; +wire lsu_mb_ex2_uc_data_vld_gate; +wire [5 :0] lsu_mb_ex2_uc_dest_reg; +wire lsu_mb_ex2_uc_fld; +wire lsu_mb_ex2_uc_fls; +wire lsu_mb_ex2_uc_lock; +wire lsu_mb_ex2_uc_sc_data_vld; +wire lsu_mb_ex2_uc_sign_ext; +wire [1 :0] lsu_mb_ex2_uc_size; +wire lsu_mb_ex2_uc_split; +wire lsu_mb_ex2_uc_split_last; +wire lsu_mb_ex2_uc_stall; +wire [31:0] lsu_pmp_addr; +wire lsu_pmp_write; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_async_ld_inst; +wire [31:0] lsu_rtu_async_tval; +wire lsu_rtu_ex1_cmplt; +wire lsu_rtu_ex1_cmplt_dp; +wire [14:0] lsu_rtu_ex1_halt_info; +wire lsu_rtu_ex1_inst_len; +wire lsu_rtu_ex1_inst_vld; +wire lsu_rtu_ex1_ipop_int_mask; +wire lsu_rtu_ex1_ipush_spec_inst; +wire lsu_rtu_ex1_split_inst; +wire lsu_rtu_ex2_bus_err; +wire [31:0] lsu_rtu_ex2_data; +wire lsu_rtu_ex2_data_vld; +wire lsu_rtu_ex2_data_vld_gate; +wire [5 :0] lsu_rtu_ex2_dest_reg; +wire lsu_rtu_ex2_expt_inst; +wire [3 :0] lsu_rtu_ex2_expt_vec; +wire lsu_rtu_ex2_fls; +wire lsu_rtu_ex2_stall; +wire [31:0] lsu_rtu_ex2_tval; +wire [31:0] lsu_rtu_fgpr_wb_data; +wire [4 :0] lsu_rtu_fgpr_wb_reg; +wire lsu_rtu_fgpr_wb_vld; +wire lsu_rtu_sync_ack; +wire [31:0] lsu_rtu_wb_data; +wire [5 :0] lsu_rtu_wb_preg; +wire lsu_rtu_wb_vld; +wire [31:0] lsu_sysmap_pa; +wire lsu_top_dc_vld; +wire lsu_xx_ex2_ca_flush; +wire lsu_xx_ex2_uc_flush; +wire lsu_xx_flush; +wire lsu_xx_no_op; +wire lsu_xx_warm_up; +wire mb_clk; +wire mb_clk_en; +wire mb_create_en; +wire [31:0] mb_data_bits_vld; +wire mb_data_clk; +wire mb_data_clk_en; +wire mb_data_create_en; +wire mb_dp_clk; +wire mb_dp_clk_en; +wire ncb_ag_async_expt_vld; +wire ncb_ag_async_ld_inst; +wire [31:0] ncb_ag_async_mtval; +wire ncb_ag_pmp_ld_inst; +wire [31:0] ncb_ag_pmp_mtval; +wire ncb_ag_stall; +wire ncb_dahbif_acc_deny; +wire ncb_dahbif_lock; +wire ncb_dahbif_lrsc; +wire [31:0] ncb_dahbif_ncb_wb_addr; +wire ncb_dahbif_ncb_wb_sel; +wire [3 :0] ncb_dahbif_prot; +wire ncb_dahbif_req; +wire ncb_dahbif_req_dp; +wire [1 :0] ncb_dahbif_size; +wire [31:0] ncb_dahbif_uc_ld_addr; +wire [31:0] ncb_dahbif_wdata; +wire ncb_dahbif_write; +wire [10:0] ncb_dbginfo; +wire ncb_xx_no_op; +wire pad_yy_icg_scan_en; +wire pmp_lsu_acc_deny; +wire [1 :0] rdl_arb_data_bank; +wire [63:0] rdl_arb_data_din; +wire [11:0] rdl_arb_data_idx; +wire rdl_arb_data_req; +wire [1 :0] rdl_arb_data_way; +wire [3 :0] rdl_arb_data_wen; +wire rdl_arb_dcache_sel; +wire [2 :0] rdl_arb_dirty_din; +wire [9 :0] rdl_arb_dirty_idx; +wire rdl_arb_dirty_req; +wire [2 :0] rdl_arb_dirty_wen; +wire [22:0] rdl_arb_tag_din; +wire [9 :0] rdl_arb_tag_idx; +wire rdl_arb_tag_req; +wire [1 :0] rdl_arb_tag_wen; +wire [2 :0] rdl_dbginfo; +wire rdl_lfb_done; +wire rdl_lfb_fifo; +wire rdl_lfb_fifo_save; +wire rdl_lfb_grant; +wire [1 :0] rdl_stb_cmplt_id; +wire rdl_stb_dca_cmplt; +wire rdl_stb_dca_grant; +wire [26:0] rdl_vb_addr; +wire rdl_vb_create_en; +wire [63:0] rdl_vb_data; +wire [1 :0] rdl_vb_data_cnt; +wire rdl_vb_data_create; +wire rdl_vb_line_dirty; +wire rdl_vb_warm_up; +wire rtu_lsu_async_expt_ack; +wire rtu_lsu_expt_ack; +wire rtu_lsu_expt_exit; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_lsu_inst_retire; +wire rtu_lsu_sync_req; +wire [31:0] rtu_lsu_wb1_data; +wire rtu_lsu_wb1_lsu_vld; +wire [5 :0] rtu_lsu_wb1_preg; +wire rtu_xx_ex1_stall; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_flush; +wire sign_ext; +wire [1 :0] size; +wire [1 :0] stb_arb_data_bank; +wire [63:0] stb_arb_data_din; +wire [11:0] stb_arb_data_idx; +wire stb_arb_data_req; +wire [1 :0] stb_arb_data_way; +wire [3 :0] stb_arb_data_wen; +wire stb_arb_dcache_sel; +wire [2 :0] stb_arb_dirty_din; +wire [9 :0] stb_arb_dirty_idx; +wire stb_arb_dirty_req; +wire [2 :0] stb_arb_dirty_wen; +wire [31:0] stb_dahbif_addr; +wire [31:0] stb_dahbif_data; +wire stb_dahbif_lock; +wire [3 :0] stb_dahbif_prot; +wire stb_dahbif_req; +wire stb_dahbif_sc_inst; +wire [1 :0] stb_dahbif_size; +wire [23:0] stb_dbginfo; +wire stb_dc_async_expt; +wire stb_dc_busy; +wire stb_dc_full; +wire stb_dc_hit_addr; +wire stb_dc_hit_dca; +wire stb_dc_hit_idx; +wire [31:0] stb_dc_ld_data; +wire stb_dc_ld_fwd_vld; +wire [31:0] stb_dc_mtval; +wire stb_dc_multi_or_part_hit; +wire stb_dc_pop_en; +wire stb_idle; +wire [26:0] stb_rdl_addr; +wire [1 :0] stb_rdl_dca_type; +wire stb_rdl_dirty; +wire [1 :0] stb_rdl_id; +wire stb_rdl_start; +wire stb_rdl_way; +wire [4 :0] sysmap_lsu_flg; +wire [31:0] vb_dahbif_addr; +wire [31:0] vb_dahbif_data; +wire [3 :0] vb_dahbif_prot; +wire vb_dahbif_req; +wire [7 :0] vb_dbginfo; +wire vb_dc_hit_dirty; +wire [31:0] vb_dc_ld_data; +wire vb_dc_ld_fwd_vld; +wire vb_dc_pop_en; +wire vb_icc_empty; +wire vb_icc_grant; +wire vb_idle; +wire vb_rdl_grant; +wire vb_wb_idle; + + +parameter DATAW = `FLEN; + +// &Instance("pa_lsu_ag", "x_pa_lsu_ag"); @27 +pa_lsu_ag x_pa_lsu_ag ( + .ag_dc_addr (ag_dc_addr ), + .ag_dc_buf (ag_dc_buf ), + .ag_dc_bytes_vld (ag_dc_bytes_vld ), + .ag_dc_ca (ag_dc_ca ), + .ag_dc_dcache_grant (ag_dc_dcache_grant ), + .ag_dc_dest_reg (ag_dc_dest_reg ), + .ag_dc_fls (ag_dc_fls ), + .ag_dc_func (ag_dc_func ), + .ag_dc_inst_vld (ag_dc_inst_vld ), + .ag_dc_inst_vld_gate (ag_dc_inst_vld_gate ), + .ag_dc_lm_pass (ag_dc_lm_pass ), + .ag_dc_mach_mode (ag_dc_mach_mode ), + .ag_dc_ori_size (ag_dc_ori_size ), + .ag_dc_pmp_expt (ag_dc_pmp_expt ), + .ag_dc_sign_ext (ag_dc_sign_ext ), + .ag_dc_size (ag_dc_size ), + .ag_dc_so (ag_dc_so ), + .ag_dc_split (ag_dc_split ), + .ag_dc_split_first (ag_dc_split_first ), + .ag_dc_split_last (ag_dc_split_last ), + .ag_dc_src1_depd (ag_dc_src1_depd ), + .ag_dc_src1_reg (ag_dc_src1_reg ), + .ag_dc_st_data (ag_dc_st_data ), + .ag_dc_wdata_shift (ag_dc_wdata_shift ), + .ag_dtu_addr (ag_dtu_addr ), + .ag_dtu_addr_ready (ag_dtu_addr_ready ), + .ag_dtu_amo_type (ag_dtu_amo_type ), + .ag_dtu_bytes_vld (ag_dtu_bytes_vld ), + .ag_dtu_data (ag_dtu_data ), + .ag_dtu_data_chk_mask (ag_dtu_data_chk_mask ), + .ag_dtu_data_vld (ag_dtu_data_vld ), + .ag_dtu_halt_info (ag_dtu_halt_info ), + .ag_dtu_mem_access_size (ag_dtu_mem_access_size ), + .ag_dtu_pipe_down (ag_dtu_pipe_down ), + .ag_dtu_req (ag_dtu_req ), + .ag_dtu_req_gate (ag_dtu_req_gate ), + .ag_dtu_split_last (ag_dtu_split_last ), + .ag_dtu_st_type (ag_dtu_st_type ), + .ag_ncb_addr (ag_ncb_addr ), + .ag_ncb_inst_vld (ag_ncb_inst_vld ), + .ag_ncb_inst_vld_dp (ag_ncb_inst_vld_dp ), + .ag_ncb_src1_reg (ag_ncb_src1_reg ), + .ag_ncb_st_data (ag_ncb_st_data ), + .ag_xx_inst_abort (ag_xx_inst_abort ), + .ag_xx_split_done (ag_xx_split_done ), + .arb_icc_data_grant (arb_icc_data_grant ), + .arb_rdl_grant (arb_rdl_grant ), + .arb_stb_xx_grant (arb_stb_xx_grant ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_lsu_mm (cp0_lsu_mm ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .cpurst_b (cpurst_b ), + .da_xx_fwd_data (da_xx_fwd_data ), + .da_xx_fwd_fls (da_xx_fwd_fls ), + .da_xx_fwd_preg (da_xx_fwd_preg ), + .da_xx_fwd_vld (da_xx_fwd_vld ), + .dc_ag_async_expt_vld (dc_ag_async_expt_vld ), + .dc_ag_async_ld_inst (dc_ag_async_ld_inst ), + .dc_ag_async_mtval (dc_ag_async_mtval ), + .dc_ag_cache_stall (dc_ag_cache_stall ), + .dc_ag_dcache_addr (dc_ag_dcache_addr ), + .dc_ag_dcache_req (dc_ag_dcache_req ), + .dc_ag_dcache_size (dc_ag_dcache_size ), + .dc_ag_empty (dc_ag_empty ), + .dc_ag_func (dc_ag_func ), + .dc_ag_pmp_ld_inst (dc_ag_pmp_ld_inst ), + .dc_ag_pmp_mtval (dc_ag_pmp_mtval ), + .dc_ag_stall (dc_ag_stall ), + .dcache_data_cen_way0_bank0 (dcache_data_cen_way0_bank0 ), + .dcache_data_cen_way0_bank1 (dcache_data_cen_way0_bank1 ), + .dcache_data_cen_way1_bank0 (dcache_data_cen_way1_bank0 ), + .dcache_data_cen_way1_bank1 (dcache_data_cen_way1_bank1 ), + .dcache_data_din (dcache_data_din ), + .dcache_data_idx (dcache_data_idx ), + .dcache_data_wen (dcache_data_wen ), + .dcache_dirty_cen (dcache_dirty_cen ), + .dcache_dirty_din (dcache_dirty_din ), + .dcache_dirty_idx (dcache_dirty_idx ), + .dcache_dirty_wen (dcache_dirty_wen ), + .dcache_tag_cen (dcache_tag_cen ), + .dcache_tag_din (dcache_tag_din ), + .dcache_tag_idx (dcache_tag_idx ), + .dcache_tag_wen (dcache_tag_wen ), + .dtif_ag_cmplt_ready (dtif_ag_cmplt_ready ), + .dtif_ag_fsm_idle (dtif_ag_fsm_idle ), + .dtif_ag_halt_info (dtif_ag_halt_info ), + .dtif_ag_halt_info_up (dtif_ag_halt_info_up ), + .dtif_ag_pipedown_mask (dtif_ag_pipedown_mask ), + .dtif_ag_stall (dtif_ag_stall ), + .forever_cpuclk (forever_cpuclk ), + .icc_arb_data_bank (icc_arb_data_bank ), + .icc_arb_data_din (icc_arb_data_din ), + .icc_arb_data_idx (icc_arb_data_idx ), + .icc_arb_data_req (icc_arb_data_req ), + .icc_arb_data_way (icc_arb_data_way ), + .icc_arb_data_wen (icc_arb_data_wen ), + .icc_arb_dirty_din (icc_arb_dirty_din ), + .icc_arb_dirty_idx (icc_arb_dirty_idx ), + .icc_arb_dirty_req (icc_arb_dirty_req ), + .icc_arb_dirty_wen (icc_arb_dirty_wen ), + .icc_arb_tag_din (icc_arb_tag_din ), + .icc_arb_tag_idx (icc_arb_tag_idx ), + .icc_arb_tag_req (icc_arb_tag_req ), + .icc_arb_tag_wen (icc_arb_tag_wen ), + .idu_lsu_ex1_ag_imm (idu_lsu_ex1_ag_imm ), + .idu_lsu_ex1_base (idu_lsu_ex1_base ), + .idu_lsu_ex1_base_sel (idu_lsu_ex1_base_sel ), + .idu_lsu_ex1_base_wb (idu_lsu_ex1_base_wb ), + .idu_lsu_ex1_data (idu_lsu_ex1_data ), + .idu_lsu_ex1_dest_reg (idu_lsu_ex1_dest_reg ), + .idu_lsu_ex1_dest_vld (idu_lsu_ex1_dest_vld ), + .idu_lsu_ex1_dp_sel (idu_lsu_ex1_dp_sel ), + .idu_lsu_ex1_fls (idu_lsu_ex1_fls ), + .idu_lsu_ex1_func (idu_lsu_ex1_func ), + .idu_lsu_ex1_gateclk_sel (idu_lsu_ex1_gateclk_sel ), + .idu_lsu_ex1_halt_info (idu_lsu_ex1_halt_info ), + .idu_lsu_ex1_ipop_int_mask (idu_lsu_ex1_ipop_int_mask ), + .idu_lsu_ex1_ipush_spec (idu_lsu_ex1_ipush_spec ), + .idu_lsu_ex1_length (idu_lsu_ex1_length ), + .idu_lsu_ex1_offset_sel (idu_lsu_ex1_offset_sel ), + .idu_lsu_ex1_sel (idu_lsu_ex1_sel ), + .idu_lsu_ex1_sign_extend (idu_lsu_ex1_sign_extend ), + .idu_lsu_ex1_size (idu_lsu_ex1_size ), + .idu_lsu_ex1_split (idu_lsu_ex1_split ), + .idu_lsu_ex1_src0_reg (idu_lsu_ex1_src0_reg ), + .idu_lsu_ex1_src1_depd (idu_lsu_ex1_src1_depd ), + .idu_lsu_ex1_src1_reg (idu_lsu_ex1_src1_reg ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .iu_lsu_ex1_lsi_rst (iu_lsu_ex1_lsi_rst ), + .iu_lsu_ex2_wb0_grant (iu_lsu_ex2_wb0_grant ), + .lfb_arb_data_bank (lfb_arb_data_bank ), + .lfb_arb_data_din (lfb_arb_data_din ), + .lfb_arb_data_idx (lfb_arb_data_idx ), + .lfb_arb_data_req (lfb_arb_data_req ), + .lfb_arb_data_way (lfb_arb_data_way ), + .lfb_arb_data_wen (lfb_arb_data_wen ), + .lfb_arb_dcache_sel (lfb_arb_dcache_sel ), + .lfb_arb_dirty_din (lfb_arb_dirty_din ), + .lfb_arb_dirty_idx (lfb_arb_dirty_idx ), + .lfb_arb_dirty_req (lfb_arb_dirty_req ), + .lfb_arb_dirty_wen (lfb_arb_dirty_wen ), + .lfb_arb_tag_din (lfb_arb_tag_din ), + .lfb_arb_tag_idx (lfb_arb_tag_idx ), + .lfb_arb_tag_req (lfb_arb_tag_req ), + .lfb_arb_tag_wen (lfb_arb_tag_wen ), + .lm_clr (lm_clr ), + .lm_lr_bus (lm_lr_bus ), + .lm_pass (lm_pass ), + .lm_sc_bus (lm_sc_bus ), + .lm_set (lm_set ), + .lm_set_gate (lm_set_gate ), + .lsu_acc_fault_vld (lsu_acc_fault_vld ), + .lsu_biu_async_expt_ack (lsu_biu_async_expt_ack ), + .lsu_dtu_ex2_expt_vld (lsu_dtu_ex2_expt_vld ), + .lsu_ex2_stall_final (lsu_ex2_stall_final ), + .lsu_hpcp_inst_store (lsu_hpcp_inst_store ), + .lsu_hpcp_inst_store_gate (lsu_hpcp_inst_store_gate ), + .lsu_idu_ex1_halt_info (lsu_idu_ex1_halt_info ), + .lsu_idu_ex1_halt_info_update_en (lsu_idu_ex1_halt_info_update_en), + .lsu_idu_ex1_src1_update_en (lsu_idu_ex1_src1_update_en ), + .lsu_idu_ex1_src1_update_en_gate (lsu_idu_ex1_src1_update_en_gate), + .lsu_idu_ex1_stall (lsu_idu_ex1_stall ), + .lsu_idu_global_stall (lsu_idu_global_stall ), + .lsu_idu_update_addr (lsu_idu_update_addr ), + .lsu_idu_update_en (lsu_idu_update_en ), + .lsu_idu_update_en_gate (lsu_idu_update_en_gate ), + .lsu_idu_update_offset (lsu_idu_update_offset ), + .lsu_iu_ex1_base_wb (lsu_iu_ex1_base_wb ), + .lsu_iu_ex1_src1_sel (lsu_iu_ex1_src1_sel ), + .lsu_iu_ex2_lsi_dst_preg (lsu_iu_ex2_lsi_dst_preg ), + .lsu_iu_ex2_lsi_rslt (lsu_iu_ex2_lsi_rslt ), + .lsu_iu_ex2_lsi_rslt_vld (lsu_iu_ex2_lsi_rslt_vld ), + .lsu_pmp_addr (lsu_pmp_addr ), + .lsu_pmp_write (lsu_pmp_write ), + .lsu_rtu_async_expt_vld (lsu_rtu_async_expt_vld ), + .lsu_rtu_async_ld_inst (lsu_rtu_async_ld_inst ), + .lsu_rtu_async_tval (lsu_rtu_async_tval ), + .lsu_rtu_ex1_cmplt (lsu_rtu_ex1_cmplt ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .lsu_rtu_ex1_halt_info (lsu_rtu_ex1_halt_info ), + .lsu_rtu_ex1_inst_len (lsu_rtu_ex1_inst_len ), + .lsu_rtu_ex1_inst_vld (lsu_rtu_ex1_inst_vld ), + .lsu_rtu_ex1_ipop_int_mask (lsu_rtu_ex1_ipop_int_mask ), + .lsu_rtu_ex1_ipush_spec_inst (lsu_rtu_ex1_ipush_spec_inst ), + .lsu_rtu_ex1_split_inst (lsu_rtu_ex1_split_inst ), + .lsu_rtu_ex2_bus_err (lsu_rtu_ex2_bus_err ), + .lsu_rtu_ex2_expt_inst (lsu_rtu_ex2_expt_inst ), + .lsu_rtu_ex2_expt_vec (lsu_rtu_ex2_expt_vec ), + .lsu_rtu_ex2_tval (lsu_rtu_ex2_tval ), + .lsu_sysmap_pa (lsu_sysmap_pa ), + .ncb_ag_async_expt_vld (ncb_ag_async_expt_vld ), + .ncb_ag_async_ld_inst (ncb_ag_async_ld_inst ), + .ncb_ag_async_mtval (ncb_ag_async_mtval ), + .ncb_ag_pmp_ld_inst (ncb_ag_pmp_ld_inst ), + .ncb_ag_pmp_mtval (ncb_ag_pmp_mtval ), + .ncb_ag_stall (ncb_ag_stall ), + .ncb_xx_no_op (ncb_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pmp_lsu_acc_deny (pmp_lsu_acc_deny ), + .rdl_arb_data_bank (rdl_arb_data_bank ), + .rdl_arb_data_din (rdl_arb_data_din ), + .rdl_arb_data_idx (rdl_arb_data_idx ), + .rdl_arb_data_req (rdl_arb_data_req ), + .rdl_arb_data_way (rdl_arb_data_way ), + .rdl_arb_data_wen (rdl_arb_data_wen ), + .rdl_arb_dcache_sel (rdl_arb_dcache_sel ), + .rdl_arb_dirty_din (rdl_arb_dirty_din ), + .rdl_arb_dirty_idx (rdl_arb_dirty_idx ), + .rdl_arb_dirty_req (rdl_arb_dirty_req ), + .rdl_arb_dirty_wen (rdl_arb_dirty_wen ), + .rdl_arb_tag_din (rdl_arb_tag_din ), + .rdl_arb_tag_idx (rdl_arb_tag_idx ), + .rdl_arb_tag_req (rdl_arb_tag_req ), + .rdl_arb_tag_wen (rdl_arb_tag_wen ), + .rtu_lsu_async_expt_ack (rtu_lsu_async_expt_ack ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_lsu_inst_retire (rtu_lsu_inst_retire ), + .rtu_lsu_wb1_data (rtu_lsu_wb1_data ), + .rtu_lsu_wb1_lsu_vld (rtu_lsu_wb1_lsu_vld ), + .rtu_lsu_wb1_preg (rtu_lsu_wb1_preg ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .stb_arb_data_bank (stb_arb_data_bank ), + .stb_arb_data_din (stb_arb_data_din ), + .stb_arb_data_idx (stb_arb_data_idx ), + .stb_arb_data_req (stb_arb_data_req ), + .stb_arb_data_way (stb_arb_data_way ), + .stb_arb_data_wen (stb_arb_data_wen ), + .stb_arb_dcache_sel (stb_arb_dcache_sel ), + .stb_arb_dirty_din (stb_arb_dirty_din ), + .stb_arb_dirty_idx (stb_arb_dirty_idx ), + .stb_arb_dirty_req (stb_arb_dirty_req ), + .stb_arb_dirty_wen (stb_arb_dirty_wen ), + .sysmap_lsu_flg (sysmap_lsu_flg ) +); + +// &Instance("pa_lsu_lm", "x_pa_lsu_lm"); @28 +pa_lsu_lm x_pa_lsu_lm ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lm_clr (lm_clr ), + .lm_lr_bus (lm_lr_bus ), + .lm_pass (lm_pass ), + .lm_sc_bus (lm_sc_bus ), + .lm_set (lm_set ), + .lm_set_gate (lm_set_gate ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .rtu_lsu_expt_ack (rtu_lsu_expt_ack ), + .rtu_lsu_expt_exit (rtu_lsu_expt_exit ) +); + +// &Instance("pa_lsu_ncb", "x_pa_lsu_ncb"); @29 +pa_lsu_ncb x_pa_lsu_ncb ( + .ag_dc_buf (ag_dc_buf ), + .ag_dc_bytes_vld (ag_dc_bytes_vld ), + .ag_dc_ca (ag_dc_ca ), + .ag_dc_dest_reg (ag_dc_dest_reg ), + .ag_dc_fls (ag_dc_fls ), + .ag_dc_func (ag_dc_func ), + .ag_dc_lm_pass (ag_dc_lm_pass ), + .ag_dc_mach_mode (ag_dc_mach_mode ), + .ag_dc_ori_size (ag_dc_ori_size ), + .ag_dc_pmp_expt (ag_dc_pmp_expt ), + .ag_dc_sign_ext (ag_dc_sign_ext ), + .ag_dc_size (ag_dc_size ), + .ag_dc_so (ag_dc_so ), + .ag_dc_split (ag_dc_split ), + .ag_dc_split_first (ag_dc_split_first ), + .ag_dc_split_last (ag_dc_split_last ), + .ag_dc_src1_depd (ag_dc_src1_depd ), + .ag_dc_wdata_shift (ag_dc_wdata_shift ), + .ag_ncb_addr (ag_ncb_addr ), + .ag_ncb_inst_vld (ag_ncb_inst_vld ), + .ag_ncb_inst_vld_dp (ag_ncb_inst_vld_dp ), + .ag_ncb_src1_reg (ag_ncb_src1_reg ), + .ag_ncb_st_data (ag_ncb_st_data ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cpurst_b (cpurst_b ), + .da_xx_fwd_data (da_xx_fwd_data ), + .da_xx_fwd_fls (da_xx_fwd_fls ), + .da_xx_fwd_preg (da_xx_fwd_preg ), + .da_xx_fwd_vld (da_xx_fwd_vld ), + .dahbif_ncb_acc_err (dahbif_ncb_acc_err ), + .dahbif_ncb_cmplt (dahbif_ncb_cmplt ), + .dahbif_ncb_data (dahbif_ncb_data ), + .dahbif_ncb_grant (dahbif_ncb_grant ), + .dahbif_ncb_grant_2 (dahbif_ncb_grant_2 ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lsu_biu_amo_pmp_deny (lsu_biu_amo_pmp_deny ), + .lsu_mb_ex2_uc_addr_2 (lsu_mb_ex2_uc_addr_2 ), + .lsu_mb_ex2_uc_bytes_vld (lsu_mb_ex2_uc_bytes_vld ), + .lsu_mb_ex2_uc_data (lsu_mb_ex2_uc_data ), + .lsu_mb_ex2_uc_data_vld (lsu_mb_ex2_uc_data_vld ), + .lsu_mb_ex2_uc_data_vld_gate (lsu_mb_ex2_uc_data_vld_gate), + .lsu_mb_ex2_uc_dest_reg (lsu_mb_ex2_uc_dest_reg ), + .lsu_mb_ex2_uc_fld (lsu_mb_ex2_uc_fld ), + .lsu_mb_ex2_uc_fls (lsu_mb_ex2_uc_fls ), + .lsu_mb_ex2_uc_lock (lsu_mb_ex2_uc_lock ), + .lsu_mb_ex2_uc_sc_data_vld (lsu_mb_ex2_uc_sc_data_vld ), + .lsu_mb_ex2_uc_sign_ext (lsu_mb_ex2_uc_sign_ext ), + .lsu_mb_ex2_uc_size (lsu_mb_ex2_uc_size ), + .lsu_mb_ex2_uc_split (lsu_mb_ex2_uc_split ), + .lsu_mb_ex2_uc_split_last (lsu_mb_ex2_uc_split_last ), + .lsu_mb_ex2_uc_stall (lsu_mb_ex2_uc_stall ), + .lsu_xx_ex2_uc_flush (lsu_xx_ex2_uc_flush ), + .ncb_ag_async_expt_vld (ncb_ag_async_expt_vld ), + .ncb_ag_async_ld_inst (ncb_ag_async_ld_inst ), + .ncb_ag_async_mtval (ncb_ag_async_mtval ), + .ncb_ag_pmp_ld_inst (ncb_ag_pmp_ld_inst ), + .ncb_ag_pmp_mtval (ncb_ag_pmp_mtval ), + .ncb_ag_stall (ncb_ag_stall ), + .ncb_dahbif_acc_deny (ncb_dahbif_acc_deny ), + .ncb_dahbif_lock (ncb_dahbif_lock ), + .ncb_dahbif_lrsc (ncb_dahbif_lrsc ), + .ncb_dahbif_ncb_wb_addr (ncb_dahbif_ncb_wb_addr ), + .ncb_dahbif_ncb_wb_sel (ncb_dahbif_ncb_wb_sel ), + .ncb_dahbif_prot (ncb_dahbif_prot ), + .ncb_dahbif_req (ncb_dahbif_req ), + .ncb_dahbif_req_dp (ncb_dahbif_req_dp ), + .ncb_dahbif_size (ncb_dahbif_size ), + .ncb_dahbif_uc_ld_addr (ncb_dahbif_uc_ld_addr ), + .ncb_dahbif_wdata (ncb_dahbif_wdata ), + .ncb_dahbif_write (ncb_dahbif_write ), + .ncb_dbginfo (ncb_dbginfo ), + .ncb_xx_no_op (ncb_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_lsu_sync_req (rtu_lsu_sync_req ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ) +); + +// &Force("output", "lsu_xx_no_op"); @30 +assign lsu_xx_no_op = dc_idle & lfb_xx_idle & stb_idle & vb_idle & vb_wb_idle & icc_xx_idle & ncb_xx_no_op & da_xx_no_op; +assign lsu_xx_warm_up = ifu_lsu_warm_up; + +assign lsu_cp0_fence_ack = lsu_xx_no_op; +assign lsu_cp0_sync_ack = lsu_xx_no_op; +assign lsu_rtu_sync_ack = lsu_xx_no_op; + +assign dc_ag_empty = dc_idle & lfb_xx_idle & stb_idle & icc_xx_idle & vb_wb_idle; +// &Instance("pa_lsu_dc", "x_pa_lsu_dc"); @40 +pa_lsu_dc x_pa_lsu_dc ( + .ag_dc_addr (ag_dc_addr ), + .ag_dc_buf (ag_dc_buf ), + .ag_dc_bytes_vld (ag_dc_bytes_vld ), + .ag_dc_ca (ag_dc_ca ), + .ag_dc_dcache_grant (ag_dc_dcache_grant ), + .ag_dc_dest_reg (ag_dc_dest_reg ), + .ag_dc_fls (ag_dc_fls ), + .ag_dc_func (ag_dc_func ), + .ag_dc_inst_vld (ag_dc_inst_vld ), + .ag_dc_inst_vld_gate (ag_dc_inst_vld_gate ), + .ag_dc_lm_pass (ag_dc_lm_pass ), + .ag_dc_mach_mode (ag_dc_mach_mode ), + .ag_dc_ori_size (ag_dc_ori_size ), + .ag_dc_pmp_expt (ag_dc_pmp_expt ), + .ag_dc_sign_ext (ag_dc_sign_ext ), + .ag_dc_size (ag_dc_size ), + .ag_dc_split (ag_dc_split ), + .ag_dc_split_first (ag_dc_split_first ), + .ag_dc_split_last (ag_dc_split_last ), + .ag_dc_src1_depd (ag_dc_src1_depd ), + .ag_dc_src1_reg (ag_dc_src1_reg ), + .ag_dc_st_data (ag_dc_st_data ), + .ag_dc_wdata_shift (ag_dc_wdata_shift ), + .cp0_lsu_dcache_en (cp0_lsu_dcache_en ), + .cp0_lsu_dcache_wa (cp0_lsu_dcache_wa ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .da_xx_fwd_data (da_xx_fwd_data ), + .da_xx_fwd_fls (da_xx_fwd_fls ), + .da_xx_fwd_preg (da_xx_fwd_preg ), + .da_xx_fwd_vld (da_xx_fwd_vld ), + .dc_ag_async_expt_vld (dc_ag_async_expt_vld ), + .dc_ag_async_ld_inst (dc_ag_async_ld_inst ), + .dc_ag_async_mtval (dc_ag_async_mtval ), + .dc_ag_cache_stall (dc_ag_cache_stall ), + .dc_ag_dcache_addr (dc_ag_dcache_addr ), + .dc_ag_dcache_req (dc_ag_dcache_req ), + .dc_ag_dcache_size (dc_ag_dcache_size ), + .dc_ag_func (dc_ag_func ), + .dc_ag_pmp_ld_inst (dc_ag_pmp_ld_inst ), + .dc_ag_pmp_mtval (dc_ag_pmp_mtval ), + .dc_ag_stall (dc_ag_stall ), + .dc_dbginfo (dc_dbginfo ), + .dc_icc_way0_data (dc_icc_way0_data ), + .dc_icc_way0_dirty (dc_icc_way0_dirty ), + .dc_icc_way0_tag (dc_icc_way0_tag ), + .dc_icc_way1_data (dc_icc_way1_data ), + .dc_icc_way1_dirty (dc_icc_way1_dirty ), + .dc_icc_way1_tag (dc_icc_way1_tag ), + .dc_idle (dc_idle ), + .dc_lfb_addr (dc_lfb_addr ), + .dc_lfb_buf (dc_lfb_buf ), + .dc_lfb_ca (dc_lfb_ca ), + .dc_lfb_ca_raw (dc_lfb_ca_raw ), + .dc_lfb_create_en (dc_lfb_create_en ), + .dc_lfb_create_en_gate (dc_lfb_create_en_gate ), + .dc_lfb_inst_ld (dc_lfb_inst_ld ), + .dc_lfb_lock_trans (dc_lfb_lock_trans ), + .dc_lfb_lr_inst (dc_lfb_lr_inst ), + .dc_lfb_mach_mode (dc_lfb_mach_mode ), + .dc_lfb_size (dc_lfb_size ), + .dc_rdl_fifo (dc_rdl_fifo ), + .dc_rdl_way0_data (dc_rdl_way0_data ), + .dc_rdl_way0_dirty (dc_rdl_way0_dirty ), + .dc_rdl_way0_tag (dc_rdl_way0_tag ), + .dc_rdl_way0_vld (dc_rdl_way0_vld ), + .dc_rdl_way1_data (dc_rdl_way1_data ), + .dc_rdl_way1_dirty (dc_rdl_way1_dirty ), + .dc_rdl_way1_tag (dc_rdl_way1_tag ), + .dc_rdl_way1_vld (dc_rdl_way1_vld ), + .dc_stb_addr (dc_stb_addr ), + .dc_stb_attr (dc_stb_attr ), + .dc_stb_bytes_vld (dc_stb_bytes_vld ), + .dc_stb_cache_hit (dc_stb_cache_hit ), + .dc_stb_create_en (dc_stb_create_en ), + .dc_stb_create_en_gate (dc_stb_create_en_gate ), + .dc_stb_data (dc_stb_data ), + .dc_stb_dcache_dirty (dc_stb_dcache_dirty ), + .dc_stb_dcache_inst (dc_stb_dcache_inst ), + .dc_stb_dcache_type (dc_stb_dcache_type ), + .dc_stb_dcache_way (dc_stb_dcache_way ), + .dc_stb_fls (dc_stb_fls ), + .dc_stb_lock_trans (dc_stb_lock_trans ), + .dc_stb_sc_inst (dc_stb_sc_inst ), + .dc_stb_shift (dc_stb_shift ), + .dc_stb_size (dc_stb_size ), + .dc_stb_split_first (dc_stb_split_first ), + .dc_stb_src1_depd (dc_stb_src1_depd ), + .dc_stb_src1_reg (dc_stb_src1_reg ), + .dc_stb_wait_lfb (dc_stb_wait_lfb ), + .dc_vb_st_amold (dc_vb_st_amold ), + .dc_xx_addr (dc_xx_addr ), + .dc_xx_bytes_vld (dc_xx_bytes_vld ), + .dcache_data_dout_way0 (dcache_data_dout_way0 ), + .dcache_data_dout_way1 (dcache_data_dout_way1 ), + .dcache_dirty_dout (dcache_dirty_dout ), + .dcache_tag_dout (dcache_tag_dout ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_dc_async_expt (lfb_dc_async_expt ), + .lfb_dc_busy (lfb_dc_busy ), + .lfb_dc_hit_idx (lfb_dc_hit_idx ), + .lfb_dc_ld_cmplt (lfb_dc_ld_cmplt ), + .lfb_dc_ld_data (lfb_dc_ld_data ), + .lfb_dc_ld_data_vld (lfb_dc_ld_data_vld ), + .lfb_dc_pop_en (lfb_dc_pop_en ), + .lsu_hpcp_cache_read_access (lsu_hpcp_cache_read_access ), + .lsu_hpcp_cache_read_access_gate (lsu_hpcp_cache_read_access_gate ), + .lsu_hpcp_cache_read_miss (lsu_hpcp_cache_read_miss ), + .lsu_hpcp_cache_read_miss_gate (lsu_hpcp_cache_read_miss_gate ), + .lsu_hpcp_cache_write_access (lsu_hpcp_cache_write_access ), + .lsu_hpcp_cache_write_access_gate (lsu_hpcp_cache_write_access_gate), + .lsu_hpcp_cache_write_miss (lsu_hpcp_cache_write_miss ), + .lsu_hpcp_cache_write_miss_gate (lsu_hpcp_cache_write_miss_gate ), + .lsu_mb_ex2_ca_addr_2 (lsu_mb_ex2_ca_addr_2 ), + .lsu_mb_ex2_ca_bytes_vld (lsu_mb_ex2_ca_bytes_vld ), + .lsu_mb_ex2_ca_data (lsu_mb_ex2_ca_data ), + .lsu_mb_ex2_ca_data_vld (lsu_mb_ex2_ca_data_vld ), + .lsu_mb_ex2_ca_data_vld_gate (lsu_mb_ex2_ca_data_vld_gate ), + .lsu_mb_ex2_ca_dest_reg (lsu_mb_ex2_ca_dest_reg ), + .lsu_mb_ex2_ca_fld (lsu_mb_ex2_ca_fld ), + .lsu_mb_ex2_ca_fls (lsu_mb_ex2_ca_fls ), + .lsu_mb_ex2_ca_lock (lsu_mb_ex2_ca_lock ), + .lsu_mb_ex2_ca_sc_data_vld (lsu_mb_ex2_ca_sc_data_vld ), + .lsu_mb_ex2_ca_sign_ext (lsu_mb_ex2_ca_sign_ext ), + .lsu_mb_ex2_ca_size (lsu_mb_ex2_ca_size ), + .lsu_mb_ex2_ca_split (lsu_mb_ex2_ca_split ), + .lsu_mb_ex2_ca_split_last (lsu_mb_ex2_ca_split_last ), + .lsu_mb_ex2_ca_stall (lsu_mb_ex2_ca_stall ), + .lsu_top_dc_vld (lsu_top_dc_vld ), + .lsu_xx_ex2_ca_flush (lsu_xx_ex2_ca_flush ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .stb_dc_async_expt (stb_dc_async_expt ), + .stb_dc_busy (stb_dc_busy ), + .stb_dc_full (stb_dc_full ), + .stb_dc_hit_addr (stb_dc_hit_addr ), + .stb_dc_hit_dca (stb_dc_hit_dca ), + .stb_dc_hit_idx (stb_dc_hit_idx ), + .stb_dc_ld_data (stb_dc_ld_data ), + .stb_dc_ld_fwd_vld (stb_dc_ld_fwd_vld ), + .stb_dc_mtval (stb_dc_mtval ), + .stb_dc_multi_or_part_hit (stb_dc_multi_or_part_hit ), + .stb_dc_pop_en (stb_dc_pop_en ), + .vb_dc_hit_dirty (vb_dc_hit_dirty ), + .vb_dc_ld_data (vb_dc_ld_data ), + .vb_dc_ld_fwd_vld (vb_dc_ld_fwd_vld ), + .vb_dc_pop_en (vb_dc_pop_en ) +); + +// &Instance("pa_lsu_icc", "x_pa_lsu_icc"); @41 +pa_lsu_icc x_pa_lsu_icc ( + .arb_icc_data_grant (arb_icc_data_grant), + .cp0_lsu_icc_addr (cp0_lsu_icc_addr ), + .cp0_lsu_icc_op (cp0_lsu_icc_op ), + .cp0_lsu_icc_req (cp0_lsu_icc_req ), + .cp0_lsu_icc_type (cp0_lsu_icc_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_icc_way0_data (dc_icc_way0_data ), + .dc_icc_way0_dirty (dc_icc_way0_dirty ), + .dc_icc_way0_tag (dc_icc_way0_tag ), + .dc_icc_way1_data (dc_icc_way1_data ), + .dc_icc_way1_dirty (dc_icc_way1_dirty ), + .dc_icc_way1_tag (dc_icc_way1_tag ), + .forever_cpuclk (forever_cpuclk ), + .icc_arb_data_bank (icc_arb_data_bank ), + .icc_arb_data_din (icc_arb_data_din ), + .icc_arb_data_idx (icc_arb_data_idx ), + .icc_arb_data_req (icc_arb_data_req ), + .icc_arb_data_way (icc_arb_data_way ), + .icc_arb_data_wen (icc_arb_data_wen ), + .icc_arb_dirty_din (icc_arb_dirty_din ), + .icc_arb_dirty_idx (icc_arb_dirty_idx ), + .icc_arb_dirty_req (icc_arb_dirty_req ), + .icc_arb_dirty_wen (icc_arb_dirty_wen ), + .icc_arb_tag_din (icc_arb_tag_din ), + .icc_arb_tag_idx (icc_arb_tag_idx ), + .icc_arb_tag_req (icc_arb_tag_req ), + .icc_arb_tag_wen (icc_arb_tag_wen ), + .icc_vb_addr (icc_vb_addr ), + .icc_vb_clr_vld (icc_vb_clr_vld ), + .icc_vb_create_en (icc_vb_create_en ), + .icc_vb_data (icc_vb_data ), + .icc_vb_data_cnt (icc_vb_data_cnt ), + .icc_vb_data_create (icc_vb_data_create), + .icc_vb_line_dirty (icc_vb_line_dirty ), + .icc_xx_idle (icc_xx_idle ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lsu_cp0_icc_done (lsu_cp0_icc_done ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .vb_icc_empty (vb_icc_empty ), + .vb_icc_grant (vb_icc_grant ) +); + +// &Instance("pa_lsu_lfb", "x_pa_lsu_lfb"); @42 +pa_lsu_lfb x_pa_lsu_lfb ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbif_lfb_acc_err (dahbif_lfb_acc_err ), + .dahbif_lfb_cmplt (dahbif_lfb_cmplt ), + .dahbif_lfb_data (dahbif_lfb_data ), + .dahbif_lfb_grant (dahbif_lfb_grant ), + .dc_lfb_addr (dc_lfb_addr ), + .dc_lfb_buf (dc_lfb_buf ), + .dc_lfb_ca (dc_lfb_ca ), + .dc_lfb_ca_raw (dc_lfb_ca_raw ), + .dc_lfb_create_en (dc_lfb_create_en ), + .dc_lfb_create_en_gate (dc_lfb_create_en_gate), + .dc_lfb_inst_ld (dc_lfb_inst_ld ), + .dc_lfb_lock_trans (dc_lfb_lock_trans ), + .dc_lfb_lr_inst (dc_lfb_lr_inst ), + .dc_lfb_mach_mode (dc_lfb_mach_mode ), + .dc_lfb_size (dc_lfb_size ), + .dc_xx_addr (dc_xx_addr ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_arb_data_bank (lfb_arb_data_bank ), + .lfb_arb_data_din (lfb_arb_data_din ), + .lfb_arb_data_idx (lfb_arb_data_idx ), + .lfb_arb_data_req (lfb_arb_data_req ), + .lfb_arb_data_way (lfb_arb_data_way ), + .lfb_arb_data_wen (lfb_arb_data_wen ), + .lfb_arb_dcache_sel (lfb_arb_dcache_sel ), + .lfb_arb_dirty_din (lfb_arb_dirty_din ), + .lfb_arb_dirty_idx (lfb_arb_dirty_idx ), + .lfb_arb_dirty_req (lfb_arb_dirty_req ), + .lfb_arb_dirty_wen (lfb_arb_dirty_wen ), + .lfb_arb_tag_din (lfb_arb_tag_din ), + .lfb_arb_tag_idx (lfb_arb_tag_idx ), + .lfb_arb_tag_req (lfb_arb_tag_req ), + .lfb_arb_tag_wen (lfb_arb_tag_wen ), + .lfb_dahbif_addr (lfb_dahbif_addr ), + .lfb_dahbif_burst (lfb_dahbif_burst ), + .lfb_dahbif_lock (lfb_dahbif_lock ), + .lfb_dahbif_lr_inst (lfb_dahbif_lr_inst ), + .lfb_dahbif_prot (lfb_dahbif_prot ), + .lfb_dahbif_req (lfb_dahbif_req ), + .lfb_dahbif_size (lfb_dahbif_size ), + .lfb_dbginfo (lfb_dbginfo ), + .lfb_dc_async_expt (lfb_dc_async_expt ), + .lfb_dc_busy (lfb_dc_busy ), + .lfb_dc_hit_idx (lfb_dc_hit_idx ), + .lfb_dc_ld_cmplt (lfb_dc_ld_cmplt ), + .lfb_dc_ld_data (lfb_dc_ld_data ), + .lfb_dc_ld_data_vld (lfb_dc_ld_data_vld ), + .lfb_dc_pop_en (lfb_dc_pop_en ), + .lfb_rdl_index (lfb_rdl_index ), + .lfb_rdl_start (lfb_rdl_start ), + .lfb_rdl_start_gate (lfb_rdl_start_gate ), + .lfb_stb_done (lfb_stb_done ), + .lfb_stb_err (lfb_stb_err ), + .lfb_stb_fifo (lfb_stb_fifo ), + .lfb_stb_fifo_update (lfb_stb_fifo_update ), + .lfb_xx_idle (lfb_xx_idle ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_lfb_done (rdl_lfb_done ), + .rdl_lfb_fifo (rdl_lfb_fifo ), + .rdl_lfb_fifo_save (rdl_lfb_fifo_save ), + .rdl_lfb_grant (rdl_lfb_grant ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush) +); + +// &Instance("pa_lsu_rdl", "x_pa_lsu_rdl"); @43 +pa_lsu_rdl x_pa_lsu_rdl ( + .arb_rdl_grant (arb_rdl_grant ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_rdl_fifo (dc_rdl_fifo ), + .dc_rdl_way0_data (dc_rdl_way0_data ), + .dc_rdl_way0_dirty (dc_rdl_way0_dirty ), + .dc_rdl_way0_tag (dc_rdl_way0_tag ), + .dc_rdl_way0_vld (dc_rdl_way0_vld ), + .dc_rdl_way1_data (dc_rdl_way1_data ), + .dc_rdl_way1_dirty (dc_rdl_way1_dirty ), + .dc_rdl_way1_tag (dc_rdl_way1_tag ), + .dc_rdl_way1_vld (dc_rdl_way1_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_rdl_index (lfb_rdl_index ), + .lfb_rdl_start (lfb_rdl_start ), + .lfb_rdl_start_gate (lfb_rdl_start_gate ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_arb_data_bank (rdl_arb_data_bank ), + .rdl_arb_data_din (rdl_arb_data_din ), + .rdl_arb_data_idx (rdl_arb_data_idx ), + .rdl_arb_data_req (rdl_arb_data_req ), + .rdl_arb_data_way (rdl_arb_data_way ), + .rdl_arb_data_wen (rdl_arb_data_wen ), + .rdl_arb_dcache_sel (rdl_arb_dcache_sel ), + .rdl_arb_dirty_din (rdl_arb_dirty_din ), + .rdl_arb_dirty_idx (rdl_arb_dirty_idx ), + .rdl_arb_dirty_req (rdl_arb_dirty_req ), + .rdl_arb_dirty_wen (rdl_arb_dirty_wen ), + .rdl_arb_tag_din (rdl_arb_tag_din ), + .rdl_arb_tag_idx (rdl_arb_tag_idx ), + .rdl_arb_tag_req (rdl_arb_tag_req ), + .rdl_arb_tag_wen (rdl_arb_tag_wen ), + .rdl_dbginfo (rdl_dbginfo ), + .rdl_lfb_done (rdl_lfb_done ), + .rdl_lfb_fifo (rdl_lfb_fifo ), + .rdl_lfb_fifo_save (rdl_lfb_fifo_save ), + .rdl_lfb_grant (rdl_lfb_grant ), + .rdl_stb_cmplt_id (rdl_stb_cmplt_id ), + .rdl_stb_dca_cmplt (rdl_stb_dca_cmplt ), + .rdl_stb_dca_grant (rdl_stb_dca_grant ), + .rdl_vb_addr (rdl_vb_addr ), + .rdl_vb_create_en (rdl_vb_create_en ), + .rdl_vb_data (rdl_vb_data ), + .rdl_vb_data_cnt (rdl_vb_data_cnt ), + .rdl_vb_data_create (rdl_vb_data_create ), + .rdl_vb_line_dirty (rdl_vb_line_dirty ), + .rdl_vb_warm_up (rdl_vb_warm_up ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush), + .stb_rdl_addr (stb_rdl_addr ), + .stb_rdl_dca_type (stb_rdl_dca_type ), + .stb_rdl_dirty (stb_rdl_dirty ), + .stb_rdl_id (stb_rdl_id ), + .stb_rdl_start (stb_rdl_start ), + .stb_rdl_way (stb_rdl_way ), + .vb_rdl_grant (vb_rdl_grant ) +); + +// &Instance("pa_lsu_stb", "x_pa_lsu_stb"); @44 +pa_lsu_stb x_pa_lsu_stb ( + .arb_stb_xx_grant (arb_stb_xx_grant ), + .cp0_lsu_dcache_wb (cp0_lsu_dcache_wb ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbif_stb_acc_ecc (dahbif_stb_acc_ecc ), + .dahbif_stb_cmplt (dahbif_stb_cmplt ), + .dahbif_stb_grant (dahbif_stb_grant ), + .dahbif_stb_grant_2 (dahbif_stb_grant_2 ), + .dc_stb_addr (dc_stb_addr ), + .dc_stb_attr (dc_stb_attr ), + .dc_stb_bytes_vld (dc_stb_bytes_vld ), + .dc_stb_cache_hit (dc_stb_cache_hit ), + .dc_stb_create_en (dc_stb_create_en ), + .dc_stb_create_en_gate (dc_stb_create_en_gate ), + .dc_stb_data (dc_stb_data ), + .dc_stb_dcache_dirty (dc_stb_dcache_dirty ), + .dc_stb_dcache_inst (dc_stb_dcache_inst ), + .dc_stb_dcache_type (dc_stb_dcache_type ), + .dc_stb_dcache_way (dc_stb_dcache_way ), + .dc_stb_fls (dc_stb_fls ), + .dc_stb_lock_trans (dc_stb_lock_trans ), + .dc_stb_sc_inst (dc_stb_sc_inst ), + .dc_stb_shift (dc_stb_shift ), + .dc_stb_size (dc_stb_size ), + .dc_stb_split_first (dc_stb_split_first ), + .dc_stb_src1_depd (dc_stb_src1_depd ), + .dc_stb_src1_reg (dc_stb_src1_reg ), + .dc_stb_wait_lfb (dc_stb_wait_lfb ), + .dc_xx_addr (dc_xx_addr ), + .dc_xx_bytes_vld (dc_xx_bytes_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lfb_stb_done (lfb_stb_done ), + .lfb_stb_err (lfb_stb_err ), + .lfb_stb_fifo (lfb_stb_fifo ), + .lfb_stb_fifo_update (lfb_stb_fifo_update ), + .lfb_xx_idle (lfb_xx_idle ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_stb_cmplt_id (rdl_stb_cmplt_id ), + .rdl_stb_dca_cmplt (rdl_stb_dca_cmplt ), + .rdl_stb_dca_grant (rdl_stb_dca_grant ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .stb_arb_data_bank (stb_arb_data_bank ), + .stb_arb_data_din (stb_arb_data_din ), + .stb_arb_data_idx (stb_arb_data_idx ), + .stb_arb_data_req (stb_arb_data_req ), + .stb_arb_data_way (stb_arb_data_way ), + .stb_arb_data_wen (stb_arb_data_wen ), + .stb_arb_dcache_sel (stb_arb_dcache_sel ), + .stb_arb_dirty_din (stb_arb_dirty_din ), + .stb_arb_dirty_idx (stb_arb_dirty_idx ), + .stb_arb_dirty_req (stb_arb_dirty_req ), + .stb_arb_dirty_wen (stb_arb_dirty_wen ), + .stb_dahbif_addr (stb_dahbif_addr ), + .stb_dahbif_data (stb_dahbif_data ), + .stb_dahbif_lock (stb_dahbif_lock ), + .stb_dahbif_prot (stb_dahbif_prot ), + .stb_dahbif_req (stb_dahbif_req ), + .stb_dahbif_sc_inst (stb_dahbif_sc_inst ), + .stb_dahbif_size (stb_dahbif_size ), + .stb_dbginfo (stb_dbginfo ), + .stb_dc_async_expt (stb_dc_async_expt ), + .stb_dc_busy (stb_dc_busy ), + .stb_dc_full (stb_dc_full ), + .stb_dc_hit_addr (stb_dc_hit_addr ), + .stb_dc_hit_dca (stb_dc_hit_dca ), + .stb_dc_hit_idx (stb_dc_hit_idx ), + .stb_dc_ld_data (stb_dc_ld_data ), + .stb_dc_ld_fwd_vld (stb_dc_ld_fwd_vld ), + .stb_dc_mtval (stb_dc_mtval ), + .stb_dc_multi_or_part_hit (stb_dc_multi_or_part_hit), + .stb_dc_pop_en (stb_dc_pop_en ), + .stb_idle (stb_idle ), + .stb_rdl_addr (stb_rdl_addr ), + .stb_rdl_dca_type (stb_rdl_dca_type ), + .stb_rdl_dirty (stb_rdl_dirty ), + .stb_rdl_id (stb_rdl_id ), + .stb_rdl_start (stb_rdl_start ), + .stb_rdl_way (stb_rdl_way ) +); + +// &Instance("pa_lsu_vb", "x_pa_lsu_vb"); @45 +pa_lsu_vb x_pa_lsu_vb ( + .cp0_lsu_fence_req (cp0_lsu_fence_req ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbif_vb_acc_ecc (dahbif_vb_acc_ecc ), + .dahbif_vb_cmplt (dahbif_vb_cmplt ), + .dahbif_vb_grant (dahbif_vb_grant ), + .dc_vb_st_amold (dc_vb_st_amold ), + .dc_xx_addr (dc_xx_addr ), + .forever_cpuclk (forever_cpuclk ), + .icc_vb_addr (icc_vb_addr ), + .icc_vb_clr_vld (icc_vb_clr_vld ), + .icc_vb_create_en (icc_vb_create_en ), + .icc_vb_data (icc_vb_data ), + .icc_vb_data_cnt (icc_vb_data_cnt ), + .icc_vb_data_create (icc_vb_data_create ), + .icc_vb_line_dirty (icc_vb_line_dirty ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_vb_addr (rdl_vb_addr ), + .rdl_vb_create_en (rdl_vb_create_en ), + .rdl_vb_data (rdl_vb_data ), + .rdl_vb_data_cnt (rdl_vb_data_cnt ), + .rdl_vb_data_create (rdl_vb_data_create ), + .rdl_vb_line_dirty (rdl_vb_line_dirty ), + .rdl_vb_warm_up (rdl_vb_warm_up ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush), + .vb_dahbif_addr (vb_dahbif_addr ), + .vb_dahbif_data (vb_dahbif_data ), + .vb_dahbif_prot (vb_dahbif_prot ), + .vb_dahbif_req (vb_dahbif_req ), + .vb_dbginfo (vb_dbginfo ), + .vb_dc_hit_dirty (vb_dc_hit_dirty ), + .vb_dc_ld_data (vb_dc_ld_data ), + .vb_dc_ld_fwd_vld (vb_dc_ld_fwd_vld ), + .vb_dc_pop_en (vb_dc_pop_en ), + .vb_icc_empty (vb_icc_empty ), + .vb_icc_grant (vb_icc_grant ), + .vb_idle (vb_idle ), + .vb_rdl_grant (vb_rdl_grant ), + .vb_wb_idle (vb_wb_idle ) +); + +// &Instance("pa_dcache_top", "x_pa_dcache_top"); @46 +pa_dcache_top x_pa_dcache_top ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .dcache_data_cen_way0_bank0 (dcache_data_cen_way0_bank0), + .dcache_data_cen_way0_bank1 (dcache_data_cen_way0_bank1), + .dcache_data_cen_way1_bank0 (dcache_data_cen_way1_bank0), + .dcache_data_cen_way1_bank1 (dcache_data_cen_way1_bank1), + .dcache_data_din (dcache_data_din ), + .dcache_data_dout_way0 (dcache_data_dout_way0 ), + .dcache_data_dout_way1 (dcache_data_dout_way1 ), + .dcache_data_idx (dcache_data_idx ), + .dcache_data_wen (dcache_data_wen ), + .dcache_dirty_cen (dcache_dirty_cen ), + .dcache_dirty_din (dcache_dirty_din ), + .dcache_dirty_dout (dcache_dirty_dout ), + .dcache_dirty_idx (dcache_dirty_idx ), + .dcache_dirty_wen (dcache_dirty_wen ), + .dcache_tag_cen (dcache_tag_cen ), + .dcache_tag_din (dcache_tag_din ), + .dcache_tag_dout (dcache_tag_dout ), + .dcache_tag_idx (dcache_tag_idx ), + .dcache_tag_wen (dcache_tag_wen ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Instance("pa_lsu_dahbif", "x_pa_lsu_dahbif"); @47 +pa_lsu_dahbif x_pa_lsu_dahbif ( + .bmu_lsu_acc_err (bmu_lsu_acc_err ), + .bmu_lsu_grant (bmu_lsu_grant ), + .bmu_lsu_rdata (bmu_lsu_rdata ), + .bmu_lsu_trans_cmplt (bmu_lsu_trans_cmplt ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dahbif_dbginfo (dahbif_dbginfo ), + .dahbif_lfb_acc_err (dahbif_lfb_acc_err ), + .dahbif_lfb_cmplt (dahbif_lfb_cmplt ), + .dahbif_lfb_data (dahbif_lfb_data ), + .dahbif_lfb_grant (dahbif_lfb_grant ), + .dahbif_ncb_acc_err (dahbif_ncb_acc_err ), + .dahbif_ncb_cmplt (dahbif_ncb_cmplt ), + .dahbif_ncb_data (dahbif_ncb_data ), + .dahbif_ncb_grant (dahbif_ncb_grant ), + .dahbif_ncb_grant_2 (dahbif_ncb_grant_2 ), + .dahbif_stb_acc_ecc (dahbif_stb_acc_ecc ), + .dahbif_stb_cmplt (dahbif_stb_cmplt ), + .dahbif_stb_grant (dahbif_stb_grant ), + .dahbif_stb_grant_2 (dahbif_stb_grant_2 ), + .dahbif_vb_acc_ecc (dahbif_vb_acc_ecc ), + .dahbif_vb_cmplt (dahbif_vb_cmplt ), + .dahbif_vb_grant (dahbif_vb_grant ), + .forever_cpuclk (forever_cpuclk ), + .lfb_dahbif_addr (lfb_dahbif_addr ), + .lfb_dahbif_burst (lfb_dahbif_burst ), + .lfb_dahbif_lock (lfb_dahbif_lock ), + .lfb_dahbif_lr_inst (lfb_dahbif_lr_inst ), + .lfb_dahbif_prot (lfb_dahbif_prot ), + .lfb_dahbif_req (lfb_dahbif_req ), + .lfb_dahbif_size (lfb_dahbif_size ), + .lsu_bmu_acc_deny (lsu_bmu_acc_deny ), + .lsu_bmu_addr (lsu_bmu_addr ), + .lsu_bmu_burst (lsu_bmu_burst ), + .lsu_bmu_lock (lsu_bmu_lock ), + .lsu_bmu_lrsc (lsu_bmu_lrsc ), + .lsu_bmu_prot (lsu_bmu_prot ), + .lsu_bmu_req (lsu_bmu_req ), + .lsu_bmu_req_dp (lsu_bmu_req_dp ), + .lsu_bmu_seq (lsu_bmu_seq ), + .lsu_bmu_size (lsu_bmu_size ), + .lsu_bmu_wdata (lsu_bmu_wdata ), + .lsu_bmu_write (lsu_bmu_write ), + .ncb_dahbif_acc_deny (ncb_dahbif_acc_deny ), + .ncb_dahbif_lock (ncb_dahbif_lock ), + .ncb_dahbif_lrsc (ncb_dahbif_lrsc ), + .ncb_dahbif_ncb_wb_addr (ncb_dahbif_ncb_wb_addr), + .ncb_dahbif_ncb_wb_sel (ncb_dahbif_ncb_wb_sel ), + .ncb_dahbif_prot (ncb_dahbif_prot ), + .ncb_dahbif_req (ncb_dahbif_req ), + .ncb_dahbif_req_dp (ncb_dahbif_req_dp ), + .ncb_dahbif_size (ncb_dahbif_size ), + .ncb_dahbif_uc_ld_addr (ncb_dahbif_uc_ld_addr ), + .ncb_dahbif_wdata (ncb_dahbif_wdata ), + .ncb_dahbif_write (ncb_dahbif_write ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .stb_dahbif_addr (stb_dahbif_addr ), + .stb_dahbif_data (stb_dahbif_data ), + .stb_dahbif_lock (stb_dahbif_lock ), + .stb_dahbif_prot (stb_dahbif_prot ), + .stb_dahbif_req (stb_dahbif_req ), + .stb_dahbif_sc_inst (stb_dahbif_sc_inst ), + .stb_dahbif_size (stb_dahbif_size ), + .vb_dahbif_addr (vb_dahbif_addr ), + .vb_dahbif_data (vb_dahbif_data ), + .vb_dahbif_prot (vb_dahbif_prot ), + .vb_dahbif_req (vb_dahbif_req ) +); + +// &Instance("pa_lsu_dc_dummy","x_pa_lsu_dc_dummy"); @49 +// &Instance("pa_lsu_dahbif_uc","x_pa_lsu_dahbif"); @50 +// &Force("input", "cp0_lsu_icc_addr"); &Force("bus", "cp0_lsu_icc_addr", 31, 0); @51 +// &Force("input", "cp0_lsu_icc_op"); &Force("bus", "cp0_lsu_icc_op", 1, 0); @52 +// &Force("input", "cp0_lsu_icc_req"); @53 +// &Force("input", "cp0_lsu_icc_type"); &Force("bus", "cp0_lsu_icc_type", 1, 0); @54 +// &Force("input", "cp0_lsu_fence_req"); @55 +// &Force("input", "cp0_lsu_sync_req"); @58 +// &Force("input", "rtu_lsu_sync_req"); @59 + +// &Instance("pa_lsu_dtif", "x_pa_lsu_dtif"); @62 +pa_lsu_dtif x_pa_lsu_dtif ( + .ag_dtu_addr (ag_dtu_addr ), + .ag_dtu_addr_ready (ag_dtu_addr_ready ), + .ag_dtu_amo_type (ag_dtu_amo_type ), + .ag_dtu_bytes_vld (ag_dtu_bytes_vld ), + .ag_dtu_data (ag_dtu_data ), + .ag_dtu_data_chk_mask (ag_dtu_data_chk_mask ), + .ag_dtu_data_vld (ag_dtu_data_vld ), + .ag_dtu_halt_info (ag_dtu_halt_info ), + .ag_dtu_mem_access_size (ag_dtu_mem_access_size ), + .ag_dtu_pipe_down (ag_dtu_pipe_down ), + .ag_dtu_req (ag_dtu_req ), + .ag_dtu_req_gate (ag_dtu_req_gate ), + .ag_dtu_split_last (ag_dtu_split_last ), + .ag_dtu_st_type (ag_dtu_st_type ), + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .da_dtu_data (da_dtu_data ), + .da_dtu_data_expt_vld (da_dtu_data_expt_vld ), + .da_dtu_data_vld (da_dtu_data_vld ), + .dtif_ag_cmplt_ready (dtif_ag_cmplt_ready ), + .dtif_ag_fsm_idle (dtif_ag_fsm_idle ), + .dtif_ag_halt_info (dtif_ag_halt_info ), + .dtif_ag_halt_info_up (dtif_ag_halt_info_up ), + .dtif_ag_pipedown_mask (dtif_ag_pipedown_mask ), + .dtif_ag_stall (dtif_ag_stall ), + .dtu_lsu_addr_trig_en (dtu_lsu_addr_trig_en ), + .dtu_lsu_data_trig_en (dtu_lsu_data_trig_en ), + .dtu_lsu_halt_info (dtu_lsu_halt_info ), + .dtu_lsu_halt_info_vld (dtu_lsu_halt_info_vld ), + .forever_cpuclk (forever_cpuclk ), + .ifu_lsu_warm_up (ifu_lsu_warm_up ), + .lsu_dtu_halt_info (lsu_dtu_halt_info ), + .lsu_dtu_last_check (lsu_dtu_last_check ), + .lsu_dtu_ldst_addr (lsu_dtu_ldst_addr ), + .lsu_dtu_ldst_addr_vld (lsu_dtu_ldst_addr_vld ), + .lsu_dtu_ldst_bytes_vld (lsu_dtu_ldst_bytes_vld ), + .lsu_dtu_ldst_data (lsu_dtu_ldst_data ), + .lsu_dtu_ldst_data_vld (lsu_dtu_ldst_data_vld ), + .lsu_dtu_ldst_type (lsu_dtu_ldst_type ), + .lsu_dtu_mem_access_size (lsu_dtu_mem_access_size), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + +// &Force("nonport", "ag_dbginfo"); @64 +// &Force("nonport", "dc_dbginfo"); @65 +// &Force("nonport", "lfb_dbginfo"); @66 +// &Force("nonport", "rdl_dbginfo"); @67 +// &Force("nonport", "stb_dbginfo"); @68 +// &Force("nonport", "vb_dbginfo"); @69 +// &Force("nonport", "lsu_dtu_debug_info"); @70 + +// &Force("output","lsu_xx_warm_up"); @73 +// //&Force("output","lsu_rtu_ex2_data_vld_gate"); @74 + +parameter S_BYTE = 2'b00; +parameter S_HALF = 2'b01; + +//============================================================================== +// DATA MERGE BUFFER FOR SPLIT +//============================================================================== +//VB or STQ generate async_expt should flush mb_cur_state. +parameter MB_IDLE = 1'b0; +parameter MB_BUSY = 1'b1; + +always@(posedge mb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mb_cur_state <= MB_IDLE; + else if (rtu_lsu_async_expt_ack) + mb_cur_state <= MB_IDLE; + else + mb_cur_state <= mb_next_state; +end + +// &CombBeg; @97 +always @( lsu_ex2_data_vld + or mb_cur_state + or lsu_ex2_split + or lsu_ex2_split_last + or ag_xx_inst_abort + or mb_split_checked) +begin + case(mb_cur_state) + MB_IDLE : begin + if (lsu_ex2_data_vld & lsu_ex2_split & !lsu_ex2_split_last & !ag_xx_inst_abort) + mb_next_state = MB_BUSY; + else + mb_next_state = MB_IDLE; + end + MB_BUSY : begin + if (lsu_ex2_data_vld & lsu_ex2_split_last | + ag_xx_inst_abort & !mb_split_checked) + mb_next_state = MB_IDLE; + else + mb_next_state = MB_BUSY; + end + default: mb_next_state = MB_IDLE; + endcase +// &CombEnd; @114 +end + +assign lsu_ex2_checked = !lsu_ex2_split | lsu_ex2_split_last; +assign mb_create_en = lsu_ex2_data_vld & lsu_ex2_split & !mb_cur_state; + +always@(posedge mb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mb_split_checked <= 1'b0; + else if (ag_xx_split_done) + mb_split_checked <= 1'b1; + else if (mb_create_en) + mb_split_checked <= lsu_ex2_checked; +end + +always@(posedge mb_dp_clk) +begin + if (mb_create_en | lsu_xx_warm_up) begin + mb_fls <= lsu_ex2_fls; + mb_flw <= lsu_ex2_flw; + mb_sign_ext <= lsu_ex2_sign_ext; + mb_size[1:0] <= lsu_ex2_size[1:0]; + mb_dest_reg[5:0] <= lsu_ex2_dest_reg[5:0]; + mb_bytes_vld[3:0] <= lsu_ex2_bytes_vld_ext[3:0]; + end +end + +assign mb_data_create_en = lsu_ex2_data_vld & lsu_ex2_split & !lsu_ex2_split_last; + +always@(posedge mb_data_clk or negedge cpurst_b) +begin + if (!cpurst_b) + mb_data[DATAW-1:0] <= {DATAW{1'b0}}; + else if (mb_data_create_en) + mb_data[DATAW-1:0] <= data[DATAW-1:0]; +end + + +assign data[DATAW-1:0] = mb_data_bits_vld[DATAW-1:0] & lsu_ex2_data[DATAW-1:0] | + ~mb_data_bits_vld[DATAW-1:0] & mb_data[DATAW-1:0] & {DATAW{mb_cur_state}}; +assign mb_data_bits_vld[31:0] = {{8{lsu_ex2_bytes_vld_ext[3]}}, + {8{lsu_ex2_bytes_vld_ext[2]}}, + {8{lsu_ex2_bytes_vld_ext[1]}}, + {8{lsu_ex2_bytes_vld_ext[0]}}}; +assign bytes_vld[3:0] = mb_cur_state ? mb_bytes_vld[3:0] : lsu_ex2_bytes_vld_ext[3:0]; +assign sign_ext = mb_cur_state ? mb_sign_ext : lsu_ex2_sign_ext; +assign size[1:0] = mb_cur_state ? mb_size[1:0] : lsu_ex2_size[1:0]; +assign flw = mb_cur_state ? mb_flw : lsu_ex2_flw; +assign fls = mb_cur_state ? mb_fls : lsu_ex2_fls; +assign dest_reg[5:0] = mb_cur_state ? mb_dest_reg[5:0] : lsu_ex2_dest_reg[5:0]; +// &Force("input","cp0_lsu_mm"); @222 + +//input +assign lsu_ex2_stall = lsu_mb_ex2_ca_stall | lsu_mb_ex2_uc_stall; +assign lsu_ex2_data_vld = lsu_mb_ex2_uc_data_vld | lsu_mb_ex2_ca_data_vld; +assign lsu_ex2_data_vld_gate = lsu_mb_ex2_uc_data_vld_gate | lsu_mb_ex2_ca_data_vld_gate; +assign lsu_ex2_split = lsu_top_dc_vld ? lsu_mb_ex2_ca_split : lsu_mb_ex2_uc_split; +assign lsu_ex2_split_last = lsu_top_dc_vld ? lsu_mb_ex2_ca_split_last : lsu_mb_ex2_uc_split_last; +assign lsu_ex2_fls = lsu_top_dc_vld ? lsu_mb_ex2_ca_fls : lsu_mb_ex2_uc_fls; +assign lsu_ex2_fld = lsu_top_dc_vld ? lsu_mb_ex2_ca_fld : lsu_mb_ex2_uc_fld; +assign lsu_ex2_sc_data_vld = lsu_top_dc_vld ? lsu_mb_ex2_ca_sc_data_vld : lsu_mb_ex2_uc_sc_data_vld; +assign lsu_ex2_sign_ext = lsu_top_dc_vld ? lsu_mb_ex2_ca_sign_ext : lsu_mb_ex2_uc_sign_ext; +assign lsu_ex2_size[1:0] = lsu_top_dc_vld ? lsu_mb_ex2_ca_size[1:0] : lsu_mb_ex2_uc_size[1:0]; +assign lsu_ex2_dest_reg[5:0] = lsu_top_dc_vld ? lsu_mb_ex2_ca_dest_reg[5:0] : lsu_mb_ex2_uc_dest_reg[5:0]; +assign lsu_ex2_addr_2 = lsu_top_dc_vld ? lsu_mb_ex2_ca_addr_2 : lsu_mb_ex2_uc_addr_2; +assign lsu_ex2_bytes_vld[3:0] = lsu_top_dc_vld ? lsu_mb_ex2_ca_bytes_vld[3:0] : lsu_mb_ex2_uc_bytes_vld[3:0]; +assign lsu_ex2_data[DATAW-1:0] = lsu_top_dc_vld ? lsu_mb_ex2_ca_data[DATAW-1:0] : lsu_mb_ex2_uc_data[DATAW-1:0]; +assign lsu_ex2_lock = lsu_top_dc_vld ? lsu_mb_ex2_ca_lock : lsu_mb_ex2_uc_lock; +//assign lsu_ex2_vld = lsu_top_dc_vld ? lsu_mb_ex2_ca_vld : lsu_mb_ex2_uc_vld; + +assign lsu_ex2_flw = lsu_ex2_fls & lsu_ex2_size[1:0] == 2'b10; +// &CombBeg; @251 +// &CombEnd; @263 +// &Force("nonport", "lsu_ex2_addr_2"); @265 +// &Force("nonport", "lsu_ex2_fld"); @266 +assign lsu_ex2_bytes_vld_ext[3:0] = lsu_ex2_bytes_vld[3:0]; + +// &CombBeg; @269 +always @( bytes_vld[3:0] + or data[31:0]) +begin + casez(bytes_vld[3:0]) + 4'b???1 : data_align[31:0] = data[31:0]; + 4'b??10 : data_align[31:0] = {data[7:0], data[31:8]}; + 4'b?100 : data_align[31:0] = {data[15:0],data[31:16]}; + 4'b1000 : data_align[31:0] = {data[23:0],data[31:24]}; + default : data_align[31:0] = data[31:0]; + endcase +// &CombEnd; @277 +end + +// &CombBeg; @280 +always @( size[1:0] + or data_align[31:0] + or sign_ext) +begin + case({sign_ext, size[1:0]}) + {1'b0,S_BYTE} : data_align_ext[31:0] = {24'b0,data_align[7:0]}; + {1'b0,S_HALF} : data_align_ext[31:0] = {16'b0,data_align[15:0]}; + {1'b1,S_BYTE} : data_align_ext[31:0] = {{24{data_align[7]}},data_align[7:0]}; + {1'b1,S_HALF} : data_align_ext[31:0] = {{16{data_align[15]}},data_align[15:0]}; + default : data_align_ext[31:0] = data_align[31:0]; + endcase +// &CombEnd; @288 +end + + +assign lsu_rtu_ex2_data_vld = lsu_ex2_data_vld & (!lsu_ex2_split | lsu_ex2_split_last) & + (cp0_xx_async_expt_en | !lsu_acc_fault_vld); +assign lsu_rtu_ex2_data_vld_gate = lsu_ex2_data_vld_gate & (!lsu_ex2_split | lsu_ex2_split_last); +assign lsu_rtu_ex2_data[31:0] = data_align_ext[31:0]; +assign lsu_rtu_ex2_dest_reg[5:0] = dest_reg[5:0]; +assign lsu_rtu_ex2_fls = fls; +//assign lsu_rtu_ex2_single = flw; + +assign lsu_xx_flush = lsu_xx_ex2_ca_flush | lsu_xx_ex2_uc_flush; + +//----------------------------------------------- +// da stage +//----------------------------------------------- +assign dc_da_data_vld = lsu_rtu_ex2_data_vld; +assign dc_da_data_vld_dp = lsu_rtu_ex2_data_vld_gate; +assign dc_da_fls = lsu_rtu_ex2_fls; +assign dc_da_fls_double = lsu_rtu_ex2_fls & !flw; +assign dc_da_sc_data_vld = lsu_ex2_sc_data_vld; +assign dc_da_dest_reg[5:0] = lsu_rtu_ex2_dest_reg[5:0]; +assign dc_da_data[DATAW-1:0] = lsu_rtu_ex2_data[DATAW-1:0]; + +always@(posedge da_clk or negedge cpurst_b) +begin + if (!cpurst_b) + da_inst_vld <= 1'b0; + else if (rtu_yy_xx_async_flush) + da_inst_vld <= 1'b0; + else if (dc_da_data_vld) + da_inst_vld <= 1'b1; + else if (da_inst_vld) + da_inst_vld <= 1'b0; +end + +always@(posedge da_dp_clk) +begin + if (dc_da_data_vld_dp | ifu_lsu_warm_up) begin + da_fls <= dc_da_fls; + da_fls_double <= dc_da_fls_double; + da_sc_inst <= dc_da_sc_data_vld; + da_dest_reg[5:0] <= dc_da_dest_reg[5:0]; + da_data[DATAW-1:0] <= dc_da_data[DATAW-1:0]; + end +end + +assign da_data_vld = da_inst_vld; +assign da_xx_no_op = !da_inst_vld; +//----------------------------------------------- +// DA Internal FWD +//----------------------------------------------- +assign da_xx_fwd_vld = da_data_vld; +assign da_xx_fwd_fls = da_fls; +assign da_xx_fwd_preg[5:0] = da_dest_reg[5:0]; +assign da_xx_fwd_data[DATAW-1:0] = da_data[DATAW-1:0]; +//----------------------------------------------- +// to IDU +//----------------------------------------------- +assign lsu_idu_ex2_fwd_vld = lsu_rtu_ex2_data_vld & !lsu_rtu_ex2_fls; +assign lsu_idu_ex2_fwd_preg[5:0] = lsu_rtu_ex2_dest_reg[5:0]; +assign lsu_idu_ex2_fwd_data[31:0] = lsu_rtu_ex2_data[31:0]; + +assign lsu_idu_ex3_fwd_vld = da_data_vld & !da_fls; +assign lsu_idu_ex3_fwd_preg[5:0] = da_dest_reg[5:0]; +assign lsu_idu_ex3_fwd_data[31:0] = da_data[31:0]; + +assign lsu_idu_ex2_ffwd_vld = lsu_rtu_ex2_data_vld & lsu_rtu_ex2_fls; +assign lsu_idu_ex2_fwd_freg[4:0] = lsu_rtu_ex2_dest_reg[4:0]; +assign lsu_idu_ex2_ffwd_data[DATAW-1:0] = lsu_rtu_ex2_data[DATAW-1:0]; + +assign lsu_idu_ex3_ffwd_vld = da_data_vld & da_fls; +assign lsu_idu_ex3_fwd_freg[4:0] = da_dest_reg[4:0]; +assign lsu_idu_ex3_ffwd_data[DATAW-1:0] = da_data[DATAW-1:0]; + +//----------------------------------------------- +// to IU +//----------------------------------------------- +assign lsu_iu_ex2_data_vld = lsu_rtu_ex2_data_vld & !lsu_rtu_ex2_fls; +assign lsu_iu_ex2_dest_reg[5:0] = lsu_rtu_ex2_dest_reg[5:0]; +assign lsu_iu_ex2_data[31:0] = lsu_rtu_ex2_data[31:0]; +//----------------------------------------------- +// to dtif +//----------------------------------------------- +assign da_dtu_data_vld = da_data_vld & !da_fls_double & !da_sc_inst; +assign da_dtu_data_expt_vld = lsu_dtu_ex2_expt_vld; +assign da_dtu_data[31:0] = da_data[31:0]; +// &Force("nonport","lsu_dtu_ex2_expt_vld"); @402 +// &Force("nonport","da_fls_double"); @403 +// &Force("nonport","da_sc_inst"); @404 +//----------------------------------------------- +// to RTU +//----------------------------------------------- +assign lsu_rtu_wb_vld = da_data_vld & !da_fls; +assign lsu_rtu_wb_preg[5:0] = da_dest_reg[5:0]; +assign lsu_rtu_wb_data[31:0] = da_data[31:0]; + +assign lsu_rtu_fgpr_wb_vld = da_data_vld & da_fls; +assign lsu_rtu_fgpr_wb_reg[4:0] = da_dest_reg[4:0]; +assign lsu_rtu_fgpr_wb_data[DATAW-1:0] = da_data[DATAW-1:0]; + +//----------------------rtu expt return------------------------------- +assign lsu_ex2_stall_final = lsu_ex2_stall & + (!lsu_ex2_split | lsu_ex2_split_last) & + (!cp0_xx_async_expt_en | lsu_ex2_lock); + +assign lsu_rtu_ex2_stall = lsu_ex2_stall_final; +//assign lsu_rtu_ex2_stall_gate = lsu_ex2_vld & +// (!cp0_xx_async_expt_en | lsu_ex2_lock); + + +// &Force("output","lsu_rtu_async_expt_vld"); @429 +// //&Force("output","lsu_rtu_ex2_data_vld"); @430 +// //&Force("output","lsu_rtu_ex2_dest_reg"); @431 +// //&Force("output","lsu_rtu_ex2_data"); @432 +// //&Force("output","lsu_rtu_ex2_fls"); @434 + +// &Force("nonport","lsu_rtu_ex2_single"); @439 +// &Force("nonport","flw"); @440 + + +assign lsu_dtu_debug_info[78:0] = {8'b0, + dahbif_dbginfo[4:0], + ncb_dbginfo[10:0], + vb_dbginfo[7:0], + stb_dbginfo[23:0], + rdl_dbginfo[2:0], + lfb_dbginfo[3:0], + dc_dbginfo[14:0], + idu_lsu_ex1_sel}; + +//================================================ +// ICG +//================================================ +assign mb_clk_en = lsu_ex2_data_vld_gate & lsu_ex2_split | mb_cur_state; +// &Instance("gated_clk_cell", "x_pa_lsu_mb_ctrl_gated_clk"); @468 +gated_clk_cell x_pa_lsu_mb_ctrl_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mb_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (mb_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @469 +// .external_en (1'b0), @470 +// .global_en (1'b1), @471 +// .module_en (cp0_lsu_icg_en ), @472 +// .local_en (mb_clk_en), @473 +// .clk_out (mb_clk)); @474 + +assign mb_dp_clk_en = lsu_ex2_data_vld_gate & lsu_ex2_split & !mb_cur_state | lsu_xx_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_mb_dp_gated_clk"); @477 +gated_clk_cell x_pa_lsu_mb_dp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mb_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (mb_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @478 +// .external_en (1'b0), @479 +// .global_en (1'b1), @480 +// .module_en (cp0_lsu_icg_en ), @481 +// .local_en (mb_dp_clk_en), @482 +// .clk_out (mb_dp_clk)); @483 + +assign mb_data_clk_en = lsu_ex2_data_vld_gate & lsu_ex2_split; +// &Instance("gated_clk_cell", "x_pa_lsu_mb_data_gated_clk"); @486 +gated_clk_cell x_pa_lsu_mb_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (mb_data_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (mb_data_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @487 +// .external_en (1'b0), @488 +// .global_en (1'b1), @489 +// .module_en (cp0_lsu_icg_en ), @490 +// .local_en (mb_data_clk_en), @491 +// .clk_out (mb_data_clk)); @492 +// &Force("nonport","lsu_ex2_data_vld_gate"); @494 + +assign da_clk_en = dc_da_data_vld_dp | ifu_lsu_warm_up | da_inst_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_da_gated_clk"); @498 +gated_clk_cell x_pa_lsu_da_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (da_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (da_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @499 +// .external_en (1'b0), @500 +// .global_en (1'b1), @501 +// .module_en (cp0_lsu_icg_en), @502 +// .local_en (da_clk_en), @503 +// .clk_out (da_clk)); @504 + +assign da_dp_clk_en = dc_da_data_vld_dp | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_da_data_gated_clk"); @507 +gated_clk_cell x_pa_lsu_da_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (da_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (da_dp_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @508 +// .external_en (1'b0), @509 +// .global_en (1'b1), @510 +// .module_en (cp0_lsu_icg_en), @511 +// .local_en (da_dp_clk_en), @512 +// .clk_out (da_dp_clk)); @513 + + + + +// &ModuleEnd; @574 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb.v new file mode 100644 index 0000000000000000000000000000000000000000..d1a2608e62bc245cf9b2ae37de9036aff0b41114 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb.v @@ -0,0 +1,481 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_vb( + cp0_lsu_fence_req, + cp0_lsu_icg_en, + cpurst_b, + dahbif_vb_acc_ecc, + dahbif_vb_cmplt, + dahbif_vb_grant, + dc_vb_st_amold, + dc_xx_addr, + forever_cpuclk, + icc_vb_addr, + icc_vb_clr_vld, + icc_vb_create_en, + icc_vb_data, + icc_vb_data_cnt, + icc_vb_data_create, + icc_vb_line_dirty, + pad_yy_icg_scan_en, + rdl_vb_addr, + rdl_vb_create_en, + rdl_vb_data, + rdl_vb_data_cnt, + rdl_vb_data_create, + rdl_vb_line_dirty, + rdl_vb_warm_up, + rtu_yy_xx_async_flush, + vb_dahbif_addr, + vb_dahbif_data, + vb_dahbif_prot, + vb_dahbif_req, + vb_dbginfo, + vb_dc_hit_dirty, + vb_dc_ld_data, + vb_dc_ld_fwd_vld, + vb_dc_pop_en, + vb_icc_empty, + vb_icc_grant, + vb_idle, + vb_rdl_grant, + vb_wb_idle +); + +// &Ports; @21 +input cp0_lsu_fence_req; +input cp0_lsu_icg_en; +input cpurst_b; +input dahbif_vb_acc_ecc; +input dahbif_vb_cmplt; +input dahbif_vb_grant; +input dc_vb_st_amold; +input [31 :0] dc_xx_addr; +input forever_cpuclk; +input [26 :0] icc_vb_addr; +input icc_vb_clr_vld; +input icc_vb_create_en; +input [63 :0] icc_vb_data; +input [1 :0] icc_vb_data_cnt; +input icc_vb_data_create; +input icc_vb_line_dirty; +input pad_yy_icg_scan_en; +input [26 :0] rdl_vb_addr; +input rdl_vb_create_en; +input [63 :0] rdl_vb_data; +input [1 :0] rdl_vb_data_cnt; +input rdl_vb_data_create; +input rdl_vb_line_dirty; +input rdl_vb_warm_up; +input rtu_yy_xx_async_flush; +output [31 :0] vb_dahbif_addr; +output [31 :0] vb_dahbif_data; +output [3 :0] vb_dahbif_prot; +output vb_dahbif_req; +output [7 :0] vb_dbginfo; +output vb_dc_hit_dirty; +output [31 :0] vb_dc_ld_data; +output vb_dc_ld_fwd_vld; +output vb_dc_pop_en; +output vb_icc_empty; +output vb_icc_grant; +output vb_idle; +output vb_rdl_grant; +output vb_wb_idle; + +// &Regs; @22 +reg [26 :0] vb_addr; +reg [31 :0] vb_dahbif_data; +reg [2 :0] vb_data_cnt; +reg [1 :0] vb_data_sel; +reg vb_lru; +reg [1 :0] wb_cur_state; +reg [1 :0] wb_next_state; + +// &Wires; @23 +wire bus_vb_acc_ecc; +wire bus_vb_cmplt; +wire bus_vb_grant; +wire cp0_lsu_fence_req; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire dahbif_vb_acc_ecc; +wire dahbif_vb_cmplt; +wire dahbif_vb_grant; +wire dc_vb_st_amold; +wire [31 :0] dc_xx_addr; +wire forever_cpuclk; +wire [26 :0] icc_vb_addr; +wire icc_vb_clr_vld; +wire icc_vb_create_en; +wire [63 :0] icc_vb_data; +wire [1 :0] icc_vb_data_cnt; +wire icc_vb_data_create; +wire icc_vb_line_dirty; +wire pad_yy_icg_scan_en; +wire [26 :0] rdl_vb_addr; +wire rdl_vb_create_en; +wire [63 :0] rdl_vb_data; +wire [1 :0] rdl_vb_data_cnt; +wire rdl_vb_data_create; +wire rdl_vb_line_dirty; +wire rdl_vb_warm_up; +wire rtu_yy_xx_async_flush; +wire [1 :0] vb_addr_sel; +wire vb_biu_req_vld; +wire vb_clk; +wire vb_clk_en; +wire [1 :0] vb_clr_en; +wire vb_clr_vld; +wire vb_cmplt_last; +wire vb_cnt_last; +wire [26 :0] vb_create_addr; +wire [63 :0] vb_create_data; +wire [1 :0] vb_create_data_cnt; +wire vb_create_data_vld; +wire [1 :0] vb_create_en; +wire vb_create_line_dirty; +wire [1 :0] vb_create_ptr; +wire vb_create_vld; +wire [31 :0] vb_dahbif_addr; +wire [3 :0] vb_dahbif_prot; +wire vb_dahbif_req; +wire [255:0] vb_data; +wire [2 :0] vb_data_cnt_inc; +wire [7 :0] vb_dbginfo; +wire vb_dc_hit_dirty; +wire [31 :0] vb_dc_ld_data; +wire vb_dc_ld_fwd_vld; +wire vb_dc_pop_en; +wire [26 :0] vb_entry0_addr; +wire [255:0] vb_entry0_data; +wire [2 :0] vb_entry0_dbginfo; +wire [31 :0] vb_entry0_fwd_data; +wire [26 :0] vb_entry1_addr; +wire [255:0] vb_entry1_data; +wire [2 :0] vb_entry1_dbginfo; +wire [31 :0] vb_entry1_fwd_data; +wire [1 :0] vb_entry_biu_req; +wire [1 :0] vb_entry_vld; +wire vb_full; +wire [1 :0] vb_fwd_vld; +wire [1 :0] vb_hit_dirty; +wire vb_icc_empty; +wire vb_icc_grant; +wire vb_idle; +wire [1 :0] vb_pop_en; +wire vb_rdl_grant; +wire [1 :0] vb_wb_cmplt; +wire [1 :0] vb_wb_grant; +wire vb_wb_idle; +wire wb_cur_idle; +wire wb_cur_wfc; +wire wb_cur_wfg; + + +parameter DATAW = `FLEN; +//================================================ +// vb create ptr +//================================================ +assign vb_create_vld = (rdl_vb_create_en | icc_vb_create_en) & !vb_full; + +always@(posedge vb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + vb_lru <= 1'b0; + else if (vb_create_vld) + vb_lru <= ~vb_lru; + else if (vb_fwd_vld[0]) + vb_lru <= 1'b1; + else if (vb_fwd_vld[1]) + vb_lru <= 1'b0; +end + +assign vb_create_ptr[1:0] = vb_full ? {vb_lru,!vb_lru} + : {vb_entry_vld[0],!vb_entry_vld[0]}; + +assign vb_create_en[1:0] = vb_create_ptr[1:0] & {2{vb_create_vld}}; +assign vb_full = &vb_entry_vld[1:0]; + +assign vb_clr_vld = rdl_vb_create_en & vb_full | icc_vb_create_en; +assign vb_clr_en[1:0] = {2{cp0_lsu_fence_req | icc_vb_clr_vld}} | {2{vb_clr_vld}} & vb_create_ptr[1:0]; +assign vb_rdl_grant = !vb_full; +assign vb_icc_grant = !rdl_vb_create_en & !vb_full; + +assign vb_create_addr[26:0] = rdl_vb_warm_up + ? 27'b0 + : rdl_vb_create_en ? rdl_vb_addr[26:0] : icc_vb_addr[26:0]; +assign vb_create_line_dirty = rdl_vb_warm_up + ? 1'b0 + : rdl_vb_create_en ? rdl_vb_line_dirty : icc_vb_line_dirty; + +assign vb_create_data_vld = rdl_vb_data_create | icc_vb_data_create; +assign vb_create_data[63:0] = rdl_vb_warm_up + ? 64'b0 + : (rdl_vb_data_create ? rdl_vb_data[63:0] : icc_vb_data[63:0]); +assign vb_create_data_cnt[1:0] = rdl_vb_data_create ? rdl_vb_data_cnt[1:0] : icc_vb_data_cnt[1:0]; + +assign vb_idle = !cp0_lsu_fence_req & wb_cur_idle & !vb_biu_req_vld | + cp0_lsu_fence_req & (!(|vb_entry_vld[1:0])); + +assign vb_icc_empty = !(|vb_entry_vld[1:0]); + +assign vb_wb_idle = wb_cur_idle; +//================================================ +// vb request dahbif +//================================================ +parameter WB_IDLE = 2'b01; +parameter WB_WFG = 2'b10; +parameter WB_WFC = 2'b00; + +assign vb_biu_req_vld = |vb_entry_biu_req[1:0]; + +always@(posedge vb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_cur_state[1:0] <= WB_IDLE; + else if (rtu_yy_xx_async_flush) + wb_cur_state[1:0] <= WB_IDLE; + else + wb_cur_state[1:0] <= wb_next_state[1:0]; +end + +// &CombBeg; @106 +always @( vb_cmplt_last + or bus_vb_grant + or wb_cur_state[1:0] + or vb_biu_req_vld) +begin + case (wb_cur_state[1:0]) + WB_IDLE: begin + if (vb_biu_req_vld) + wb_next_state[1:0] = bus_vb_grant ? WB_WFC : WB_WFG; + else + wb_next_state[1:0] = WB_IDLE; + end + WB_WFG: begin + if (bus_vb_grant) + wb_next_state[1:0] = WB_WFC; + else + wb_next_state[1:0] = WB_WFG; + end + WB_WFC: begin + if (vb_cmplt_last) + wb_next_state[1:0] = WB_IDLE; + else + wb_next_state[1:0] = WB_WFC; + end + default: wb_next_state[1:0] = WB_IDLE; + endcase +// &CombEnd; @128 +end + +assign wb_cur_idle = wb_cur_state[0]; //WB_IDLE; +assign wb_cur_wfc = wb_cur_state[1:0] == WB_WFC; +assign wb_cur_wfg = wb_cur_state[1:0] == WB_WFG; + +always@(posedge vb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + vb_data_sel[1:0] <= 2'b0; + else if (rtu_yy_xx_async_flush) + vb_data_sel[1:0] <= 2'b0; + else if (wb_cur_idle & vb_biu_req_vld) + vb_data_sel[1:0] <= {vb_entry_biu_req[1] & !vb_entry_biu_req[0],vb_entry_biu_req[0]}; + else if (wb_cur_wfc & vb_cmplt_last) + vb_data_sel[1:0] <= 2'b0; +end + +assign vb_addr_sel[1] = wb_cur_idle & !vb_entry_biu_req[0] | vb_data_sel[1]; +assign vb_addr_sel[0] = wb_cur_idle & vb_entry_biu_req[0] | vb_data_sel[0]; + +always@(posedge vb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + vb_data_cnt[2:0] <= 3'b0; + else if (bus_vb_grant) + vb_data_cnt[2:0] <= 3'b0; + else if (bus_vb_cmplt) + vb_data_cnt[2:0] <= bus_vb_acc_ecc ? 3'b111 : vb_data_cnt_inc[2:0]; +end + +assign vb_data_cnt_inc[2:0] = vb_data_cnt[2:0] + 3'b1; + +assign vb_cnt_last = (vb_data_cnt[2:0] == 3'b111); +assign vb_cmplt_last = bus_vb_cmplt & vb_cnt_last; + +// &CombBeg; @180 +always @( vb_entry0_addr[26:0] + or vb_addr_sel[1:0] + or vb_entry1_addr[26:0]) +begin + case(vb_addr_sel[1:0]) + 2'b01: vb_addr[26:0] = vb_entry0_addr[26:0]; + 2'b10: vb_addr[26:0] = vb_entry1_addr[26:0]; + default:vb_addr[26:0] = {27{1'bx}}; + endcase +// &CombEnd; @186 +end + +assign vb_data[255:0] = {256{vb_data_sel[1]}} & vb_entry1_data[255:0] | + {256{vb_data_sel[0]}} & vb_entry0_data[255:0]; + +//----------------------------------------------- +// bus interface +//----------------------------------------------- +//-----------------bus req---------------------- +// &CombBeg; @213 +// &CombEnd; @221 +assign vb_dahbif_req = vb_biu_req_vld & wb_cur_idle | wb_cur_wfg; +assign vb_dahbif_addr[31:0] = {vb_addr[26:0],5'b0}; +assign vb_dahbif_prot[3:0] = {1'b1,1'b1,1'b1,1'b1}; + +// &CombBeg; @233 +always @( vb_data[255:0] + or vb_data_cnt[2:0]) +begin + case (vb_data_cnt[2:0]) + 3'b000: vb_dahbif_data[31:0] = vb_data[31:0]; + 3'b001: vb_dahbif_data[31:0] = vb_data[63:32]; + 3'b010: vb_dahbif_data[31:0] = vb_data[95:64]; + 3'b011: vb_dahbif_data[31:0] = vb_data[127:96]; + 3'b100: vb_dahbif_data[31:0] = vb_data[159:128]; + 3'b101: vb_dahbif_data[31:0] = vb_data[191:160]; + 3'b110: vb_dahbif_data[31:0] = vb_data[223:192]; + 3'b111: vb_dahbif_data[31:0] = vb_data[255:224]; + default:vb_dahbif_data[31:0] = {32{1'bx}}; + endcase +// &CombEnd; @245 +end + +//-----------------bus resp---------------------- +assign bus_vb_grant = dahbif_vb_grant; +assign bus_vb_cmplt = dahbif_vb_cmplt; +assign bus_vb_acc_ecc = dahbif_vb_acc_ecc; + +//================================================ +// to VB entry +//================================================ + +assign vb_wb_grant[1:0] = {2{bus_vb_grant}} & vb_addr_sel[1:0]; +assign vb_wb_cmplt[1:0] = {2{vb_cmplt_last}} & vb_data_sel[1:0]; + +//================================================ +// ld fwd VB +//================================================ + +assign vb_dc_ld_fwd_vld = |vb_fwd_vld[1:0]; +assign vb_dc_ld_data[DATAW-1:0] = {DATAW{vb_fwd_vld[1]}} & vb_entry1_fwd_data[DATAW-1:0] | + {DATAW{vb_fwd_vld[0]}} & vb_entry0_fwd_data[DATAW-1:0]; +assign vb_dc_pop_en = |vb_pop_en[1:0]; +assign vb_dc_hit_dirty = |vb_hit_dirty[1:0]; + +// &ConnRule(s/_x$/[0]/); @281 +// &ConnRule(s/entryx/entry0/); @282 +// &Instance("pa_lsu_vb_entry","x_pa_lsu_vb_entry_0"); @283 +pa_lsu_vb_entry x_pa_lsu_vb_entry_0 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_vb_st_amold (dc_vb_st_amold ), + .dc_xx_addr (dc_xx_addr ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_vb_warm_up (rdl_vb_warm_up ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush), + .vb_clk (vb_clk ), + .vb_clr_en_x (vb_clr_en[0] ), + .vb_create_addr (vb_create_addr ), + .vb_create_data (vb_create_data ), + .vb_create_data_cnt (vb_create_data_cnt ), + .vb_create_data_vld (vb_create_data_vld ), + .vb_create_en_x (vb_create_en[0] ), + .vb_create_line_dirty (vb_create_line_dirty ), + .vb_entry_biu_req_x (vb_entry_biu_req[0] ), + .vb_entry_vld_x (vb_entry_vld[0] ), + .vb_entryx_addr (vb_entry0_addr ), + .vb_entryx_data (vb_entry0_data ), + .vb_entryx_dbginfo (vb_entry0_dbginfo ), + .vb_entryx_fwd_data (vb_entry0_fwd_data ), + .vb_fwd_vld_x (vb_fwd_vld[0] ), + .vb_hit_dirty_x (vb_hit_dirty[0] ), + .vb_pop_en_x (vb_pop_en[0] ), + .vb_wb_cmplt_x (vb_wb_cmplt[0] ), + .vb_wb_grant_x (vb_wb_grant[0] ) +); + + +// &ConnRule(s/_x$/[1]/); @285 +// &ConnRule(s/entryx/entry1/); @286 +// &Instance("pa_lsu_vb_entry","x_pa_lsu_vb_entry_1"); @287 +pa_lsu_vb_entry x_pa_lsu_vb_entry_1 ( + .cp0_lsu_icg_en (cp0_lsu_icg_en ), + .cpurst_b (cpurst_b ), + .dc_vb_st_amold (dc_vb_st_amold ), + .dc_xx_addr (dc_xx_addr ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rdl_vb_warm_up (rdl_vb_warm_up ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush), + .vb_clk (vb_clk ), + .vb_clr_en_x (vb_clr_en[1] ), + .vb_create_addr (vb_create_addr ), + .vb_create_data (vb_create_data ), + .vb_create_data_cnt (vb_create_data_cnt ), + .vb_create_data_vld (vb_create_data_vld ), + .vb_create_en_x (vb_create_en[1] ), + .vb_create_line_dirty (vb_create_line_dirty ), + .vb_entry_biu_req_x (vb_entry_biu_req[1] ), + .vb_entry_vld_x (vb_entry_vld[1] ), + .vb_entryx_addr (vb_entry1_addr ), + .vb_entryx_data (vb_entry1_data ), + .vb_entryx_dbginfo (vb_entry1_dbginfo ), + .vb_entryx_fwd_data (vb_entry1_fwd_data ), + .vb_fwd_vld_x (vb_fwd_vld[1] ), + .vb_hit_dirty_x (vb_hit_dirty[1] ), + .vb_pop_en_x (vb_pop_en[1] ), + .vb_wb_cmplt_x (vb_wb_cmplt[1] ), + .vb_wb_grant_x (vb_wb_grant[1] ) +); + + +assign vb_clk_en = vb_create_vld | vb_entry_vld[0] | vb_entry_vld[1]; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_gated_clk"); @290 +gated_clk_cell x_pa_lsu_vb_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @291 +// .external_en (1'b0), @292 +// .global_en (1'b1), @293 +// .module_en (cp0_lsu_icg_en ), @294 +// .local_en (vb_clk_en), @295 +// .clk_out (vb_clk)); @296 + +assign vb_dbginfo[7:0] = {vb_entry1_dbginfo[2:0], vb_entry0_dbginfo[2:0], wb_cur_state[1:0]}; + +// &ModuleEnd; @300 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..164120d715a4b8d391413fca89e5c8f682f13724 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_vb_entry.v @@ -0,0 +1,388 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h"); @18 + +// &ModuleBeg; @20 +module pa_lsu_vb_entry( + cp0_lsu_icg_en, + cpurst_b, + dc_vb_st_amold, + dc_xx_addr, + forever_cpuclk, + pad_yy_icg_scan_en, + rdl_vb_warm_up, + rtu_yy_xx_async_flush, + vb_clk, + vb_clr_en_x, + vb_create_addr, + vb_create_data, + vb_create_data_cnt, + vb_create_data_vld, + vb_create_en_x, + vb_create_line_dirty, + vb_entry_biu_req_x, + vb_entry_vld_x, + vb_entryx_addr, + vb_entryx_data, + vb_entryx_dbginfo, + vb_entryx_fwd_data, + vb_fwd_vld_x, + vb_hit_dirty_x, + vb_pop_en_x, + vb_wb_cmplt_x, + vb_wb_grant_x +); + +// &Ports; @21 +input cp0_lsu_icg_en; +input cpurst_b; +input dc_vb_st_amold; +input [31 :0] dc_xx_addr; +input forever_cpuclk; +input pad_yy_icg_scan_en; +input rdl_vb_warm_up; +input rtu_yy_xx_async_flush; +input vb_clk; +input vb_clr_en_x; +input [26 :0] vb_create_addr; +input [63 :0] vb_create_data; +input [1 :0] vb_create_data_cnt; +input vb_create_data_vld; +input vb_create_en_x; +input vb_create_line_dirty; +input vb_wb_cmplt_x; +input vb_wb_grant_x; +output vb_entry_biu_req_x; +output vb_entry_vld_x; +output [26 :0] vb_entryx_addr; +output [255:0] vb_entryx_data; +output [2 :0] vb_entryx_dbginfo; +output [31 :0] vb_entryx_fwd_data; +output vb_fwd_vld_x; +output vb_hit_dirty_x; +output vb_pop_en_x; + +// &Regs; @22 +reg [2 :0] vb_cur_state; +reg [26 :0] vb_entry_addr; +reg [63 :0] vb_entry_data0; +reg [63 :0] vb_entry_data1; +reg [63 :0] vb_entry_data2; +reg [63 :0] vb_entry_data3; +reg vb_entry_dirty; +reg [63 :0] vb_fwd_data; +reg [2 :0] vb_next_state; + +// &Wires; @23 +wire cp0_lsu_icg_en; +wire cpurst_b; +wire [29 :0] dc_addr; +wire dc_hit_vb; +wire dc_st_hit_vb; +wire dc_vb_st_amold; +wire [31 :0] dc_xx_addr; +wire forever_cpuclk; +wire pad_yy_icg_scan_en; +wire rdl_vb_warm_up; +wire rtu_yy_xx_async_flush; +wire vb_addr_clk; +wire vb_addr_clk_en; +wire vb_clk; +wire vb_clr_en_x; +wire [26 :0] vb_create_addr; +wire [63 :0] vb_create_data; +wire [1 :0] vb_create_data_cnt; +wire vb_create_data_vld; +wire vb_create_en_x; +wire vb_create_line_dirty; +wire vb_data0_clk; +wire vb_data0_clk_en; +wire vb_data1_clk; +wire vb_data1_clk_en; +wire vb_data2_clk; +wire vb_data2_clk_en; +wire vb_data3_clk; +wire vb_data3_clk_en; +wire [3 :0] vb_data_create; +wire [3 :0] vb_data_create_en; +wire vb_data_create_last; +wire vb_data_create_vld; +wire vb_entry_biu_req_x; +wire vb_entry_vld_x; +wire [26 :0] vb_entryx_addr; +wire [255:0] vb_entryx_data; +wire [2 :0] vb_entryx_dbginfo; +wire [31 :0] vb_entryx_fwd_data; +wire vb_fsm_rdy; +wire vb_fwd_vld_x; +wire vb_hit_dirty_x; +wire vb_pop_en_x; +wire vb_wb_cmplt_x; +wire vb_wb_grant_x; + + +parameter VB_IDLE = 3'b000; +parameter VB_RFC = 3'b001; +parameter VB_RDY = 3'b010; +parameter VB_WFC = 3'b011; +parameter VB_WB = 3'b100; + +always@(posedge vb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + vb_cur_state[2:0] <= VB_IDLE; + else if (rtu_yy_xx_async_flush) + vb_cur_state[2:0] <= VB_IDLE; + else + vb_cur_state[2:0] <= vb_next_state[2:0]; +end + +// &CombBeg; @51 +always @( vb_create_en_x + or dc_st_hit_vb + or vb_wb_cmplt_x + or vb_clr_en_x + or vb_entry_dirty + or vb_cur_state[2:0] + or vb_wb_grant_x + or vb_data_create_last) +begin + case(vb_cur_state[2:0]) + VB_IDLE: begin + if (vb_create_en_x) + vb_next_state[2:0] = VB_RFC; + else + vb_next_state[2:0] = VB_IDLE; + end + VB_RFC: begin + if (vb_data_create_last) + vb_next_state[2:0] = VB_RDY; + else + vb_next_state[2:0] = VB_RFC; + end + VB_RDY: begin + if (vb_clr_en_x | dc_st_hit_vb) + vb_next_state[2:0] = vb_entry_dirty ? VB_WB : VB_IDLE; + else + vb_next_state[2:0] = VB_RDY; + end + VB_WB: begin + if (vb_wb_grant_x) + vb_next_state[2:0] = VB_WFC; + else + vb_next_state[2:0] = VB_WB; + end + VB_WFC: begin + if (vb_wb_cmplt_x) + vb_next_state[2:0] = VB_IDLE; + else + vb_next_state[2:0] = VB_WFC; + end + default: vb_next_state[2:0] = VB_IDLE; + endcase +// &CombEnd; @85 +end + +assign vb_fsm_rdy = (vb_cur_state[2:0] == VB_RDY) | (vb_cur_state[2:0] == VB_WB) | (vb_cur_state[2:0] == VB_WFC); +assign vb_entry_vld_x = !(vb_cur_state[2:0] == VB_IDLE); +assign vb_pop_en_x = (vb_cur_state[2:0] == VB_WFC) & vb_wb_cmplt_x | + (vb_cur_state[2:0] == VB_RDY) & (vb_clr_en_x | dc_st_hit_vb) & !vb_entry_dirty; + +//================================================ +// bus request +//================================================ +assign vb_entry_biu_req_x = vb_cur_state[2];//VB_WB +assign vb_entryx_addr[26:0] = vb_entry_addr[26:0]; +assign vb_entryx_data[255:0] = {vb_entry_data3[63:0], + vb_entry_data2[63:0], + vb_entry_data1[63:0], + vb_entry_data0[63:0]}; + +//================================================ +// VB entry content +//================================================ +// &Force("bus","dc_xx_addr",31,0); @105 +assign dc_addr[29:0] = dc_xx_addr[31:2] & {30{vb_fsm_rdy}}; +assign dc_hit_vb = dc_addr[29:3] == vb_entry_addr[26:0]; + +assign dc_st_hit_vb = dc_hit_vb & dc_vb_st_amold; + +always@(posedge vb_addr_clk) +begin + if (vb_create_en_x | rdl_vb_warm_up) begin + vb_entry_addr[26:0] <= vb_create_addr[26:0]; + vb_entry_dirty <= vb_create_line_dirty; + end +end + +assign vb_data_create_last = vb_data_create_en[3]; + +assign vb_data_create_vld = (vb_cur_state[2:0] == VB_RFC) & vb_create_data_vld; +assign vb_data_create[3:0] = (4'b1 << vb_create_data_cnt[1:0]); +assign vb_data_create_en[3:0] = vb_data_create[3:0] & {4{vb_data_create_vld}}; + +always@(posedge vb_data0_clk) +begin + if (vb_data_create_en[0] | rdl_vb_warm_up) + vb_entry_data0[63:0] <= vb_create_data[63:0]; +end + +always@(posedge vb_data1_clk) +begin + if (vb_data_create_en[1] | rdl_vb_warm_up) + vb_entry_data1[63:0] <= vb_create_data[63:0]; +end + +always@(posedge vb_data2_clk) +begin + if (vb_data_create_en[2] | rdl_vb_warm_up) + vb_entry_data2[63:0] <= vb_create_data[63:0]; +end + +always@(posedge vb_data3_clk) +begin + if (vb_data_create_en[3] | rdl_vb_warm_up) + vb_entry_data3[63:0] <= vb_create_data[63:0]; +end + +// &Force("bus","pfb_xx_pa",31,0); @207 +//================================================ +// ld fwd VB +//================================================ +assign vb_fwd_vld_x = dc_hit_vb & vb_fsm_rdy; + +// &CombBeg; @216 +always @( dc_addr[2:1] + or vb_entry_data0[63:0] + or vb_entry_data2[63:0] + or vb_entry_data3[63:0] + or vb_entry_data1[63:0]) +begin + case(dc_addr[2:1]) + 2'b00: vb_fwd_data[63:0] = vb_entry_data0[63:0]; + 2'b01: vb_fwd_data[63:0] = vb_entry_data1[63:0]; + 2'b10: vb_fwd_data[63:0] = vb_entry_data2[63:0]; + 2'b11: vb_fwd_data[63:0] = vb_entry_data3[63:0]; + default:vb_fwd_data[63:0] = {64{1'bx}}; + endcase +// &CombEnd; @224 +end + +assign vb_entryx_fwd_data[31:0] = dc_addr[0] ? vb_fwd_data[63:32] : vb_fwd_data[31:0]; + +assign vb_hit_dirty_x = dc_hit_vb & vb_fsm_rdy & vb_entry_dirty; + +assign vb_addr_clk_en = vb_create_en_x | rdl_vb_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_addr_gated_clk"); @239 +gated_clk_cell x_pa_lsu_vb_addr_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_addr_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_addr_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @240 +// .external_en (1'b0), @241 +// .global_en (1'b1), @242 +// .module_en (cp0_lsu_icg_en ), @243 +// .local_en (vb_addr_clk_en), @244 +// .clk_out (vb_addr_clk)); @245 + +assign vb_data3_clk_en = vb_data_create_en[3] | rdl_vb_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_data3_gated_clk"); @248 +gated_clk_cell x_pa_lsu_vb_data3_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_data3_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_data3_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @249 +// .external_en (1'b0), @250 +// .global_en (1'b1), @251 +// .module_en (cp0_lsu_icg_en ), @252 +// .local_en (vb_data3_clk_en), @253 +// .clk_out (vb_data3_clk)); @254 + +assign vb_data2_clk_en = vb_data_create_en[2] | rdl_vb_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_data2_gated_clk"); @257 +gated_clk_cell x_pa_lsu_vb_data2_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_data2_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_data2_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @258 +// .external_en (1'b0), @259 +// .global_en (1'b1), @260 +// .module_en (cp0_lsu_icg_en ), @261 +// .local_en (vb_data2_clk_en), @262 +// .clk_out (vb_data2_clk)); @263 + +assign vb_data1_clk_en = vb_data_create_en[1] | rdl_vb_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_data1_gated_clk"); @266 +gated_clk_cell x_pa_lsu_vb_data1_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_data1_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_data1_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @267 +// .external_en (1'b0), @268 +// .global_en (1'b1), @269 +// .module_en (cp0_lsu_icg_en ), @270 +// .local_en (vb_data1_clk_en), @271 +// .clk_out (vb_data1_clk)); @272 + +assign vb_data0_clk_en = vb_data_create_en[0] | rdl_vb_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_vb_data0_gated_clk"); @275 +gated_clk_cell x_pa_lsu_vb_data0_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (vb_data0_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (vb_data0_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @276 +// .external_en (1'b0), @277 +// .global_en (1'b1), @278 +// .module_en (cp0_lsu_icg_en ), @279 +// .local_en (vb_data0_clk_en), @280 +// .clk_out (vb_data0_clk)); @281 + +assign vb_entryx_dbginfo[2:0] = vb_cur_state[2:0]; + +// &ModuleEnd; @285 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_wb_entry.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_wb_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..c01ba03016b424723615e91792b3dbc3aea6f84c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_lsu_wb_entry.v @@ -0,0 +1,422 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @19 +module pa_lsu_wb_entry( + ag_ld_inst, + ag_ncb_inst_vld_dp, + cp0_lsu_icg_en, + cpurst_b, + da_xx_fwd_data, + da_xx_fwd_fls, + da_xx_fwd_preg, + da_xx_fwd_vld, + forever_cpuclk, + ifu_lsu_warm_up, + ld_hit_wb_f_x, + ld_hit_wb_x, + pad_yy_icg_scan_en, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_yy_xx_async_flush, + wb_addr_pop_en_x, + wb_clk, + wb_create_addr, + wb_create_buf, + wb_create_bytes_vld, + wb_create_ca, + wb_create_data, + wb_create_dest_preg, + wb_create_en_dp_x, + wb_create_en_x, + wb_create_fls, + wb_create_lock, + wb_create_mach_mode, + wb_create_pmp_deny, + wb_create_sc_fail, + wb_create_sc_inst, + wb_create_shift, + wb_create_size, + wb_create_so, + wb_create_split_first, + wb_create_src1_depd, + wb_create_src1_reg, + wb_data_pop_en_x, + wb_entry_addr_vld_x, + wb_entry_data_vld_x, + wb_entry_fls_x, + wb_entry_lock_x, + wb_entry_lrsc_x, + wb_entry_pmp_deny_x, + wb_entry_sc_fail_x, + wb_entry_split_first_x, + wb_entry_vld_x, + wb_entryx_addr, + wb_entryx_dbginfo, + wb_entryx_dest_preg, + wb_entryx_prot, + wb_entryx_shift, + wb_entryx_size, + wb_entryx_wdata, + wb_so_req_x +); + +// &Ports; @20 +input ag_ld_inst; +input ag_ncb_inst_vld_dp; +input cp0_lsu_icg_en; +input cpurst_b; +input [31:0] da_xx_fwd_data; +input da_xx_fwd_fls; +input [5 :0] da_xx_fwd_preg; +input da_xx_fwd_vld; +input forever_cpuclk; +input ifu_lsu_warm_up; +input pad_yy_icg_scan_en; +input [31:0] rtu_lsu_fgpr_wb_data; +input [4 :0] rtu_lsu_fgpr_wb_reg; +input rtu_lsu_fgpr_wb_vld; +input rtu_yy_xx_async_flush; +input wb_addr_pop_en_x; +input wb_clk; +input [31:0] wb_create_addr; +input wb_create_buf; +input [7 :0] wb_create_bytes_vld; +input wb_create_ca; +input [31:0] wb_create_data; +input [5 :0] wb_create_dest_preg; +input wb_create_en_dp_x; +input wb_create_en_x; +input wb_create_fls; +input wb_create_lock; +input wb_create_mach_mode; +input wb_create_pmp_deny; +input wb_create_sc_fail; +input wb_create_sc_inst; +input [3 :0] wb_create_shift; +input [1 :0] wb_create_size; +input wb_create_so; +input wb_create_split_first; +input wb_create_src1_depd; +input [5 :0] wb_create_src1_reg; +input wb_data_pop_en_x; +output ld_hit_wb_f_x; +output ld_hit_wb_x; +output wb_entry_addr_vld_x; +output wb_entry_data_vld_x; +output wb_entry_fls_x; +output wb_entry_lock_x; +output wb_entry_lrsc_x; +output wb_entry_pmp_deny_x; +output wb_entry_sc_fail_x; +output wb_entry_split_first_x; +output wb_entry_vld_x; +output [31:0] wb_entryx_addr; +output [2 :0] wb_entryx_dbginfo; +output [5 :0] wb_entryx_dest_preg; +output [3 :0] wb_entryx_prot; +output [2 :0] wb_entryx_shift; +output [1 :0] wb_entryx_size; +output [31:0] wb_entryx_wdata; +output wb_so_req_x; + +// &Regs; @21 +reg req_mask_f; +reg [31:0] wb_entry_addr; +reg wb_entry_addr_vld; +reg wb_entry_buf; +reg [3 :0] wb_entry_bytes_vld; +reg wb_entry_ca; +reg [5 :0] wb_entry_dest_preg; +reg wb_entry_fls; +reg wb_entry_lock; +reg wb_entry_mach_mode; +reg wb_entry_pmp_deny; +reg wb_entry_sc_fail; +reg wb_entry_sc_inst; +reg [2 :0] wb_entry_shift; +reg [1 :0] wb_entry_size; +reg wb_entry_so; +reg wb_entry_split_first; +reg wb_entry_src1_depd; +reg [5 :0] wb_entry_src1_reg; +reg wb_entry_vld; +reg [31:0] wb_entry_wdata; + +// &Wires; @22 +wire ag_addr_hit; +wire ag_ld_inst; +wire ag_ncb_inst_vld_dp; +wire bytes_vld_hit; +wire cp0_lsu_icg_en; +wire cpurst_b; +wire [31:0] da_xx_fwd_data; +wire da_xx_fwd_fls; +wire [5 :0] da_xx_fwd_preg; +wire da_xx_fwd_vld; +wire forever_cpuclk; +wire [31:0] fwd_data; +wire fwd_fpu; +wire [31:0] fwd_fpu_data; +wire fwd_lsu; +wire fwd_vld; +wire ifu_lsu_warm_up; +wire ld_hit_wb_f_x; +wire ld_hit_wb_x; +wire pad_yy_icg_scan_en; +wire req_mask; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_yy_xx_async_flush; +wire wb_addr_pop_en_x; +wire wb_clk; +wire [31:0] wb_create_addr; +wire wb_create_buf; +wire [7 :0] wb_create_bytes_vld; +wire wb_create_ca; +wire [31:0] wb_create_data; +wire [5 :0] wb_create_dest_preg; +wire wb_create_en_dp_x; +wire wb_create_en_x; +wire wb_create_fls; +wire wb_create_lock; +wire wb_create_mach_mode; +wire wb_create_pmp_deny; +wire wb_create_sc_fail; +wire wb_create_sc_inst; +wire [3 :0] wb_create_shift; +wire [1 :0] wb_create_size; +wire wb_create_so; +wire wb_create_split_first; +wire wb_create_src1_depd; +wire [5 :0] wb_create_src1_reg; +wire wb_data_clk; +wire wb_data_clk_en; +wire wb_data_pop_en_x; +wire wb_entry_addr_vld_x; +wire [7 :0] wb_entry_bytes_vld_ext; +wire wb_entry_clk; +wire wb_entry_clk_en; +wire wb_entry_data_vld_x; +wire wb_entry_dw; +wire wb_entry_fls_x; +wire wb_entry_lock_x; +wire wb_entry_lrsc_x; +wire wb_entry_pmp_deny_x; +wire wb_entry_sc_fail_x; +wire wb_entry_split_first_x; +wire wb_entry_vld_x; +wire [31:0] wb_entryx_addr; +wire [2 :0] wb_entryx_dbginfo; +wire [5 :0] wb_entryx_dest_preg; +wire [3 :0] wb_entryx_prot; +wire [2 :0] wb_entryx_shift; +wire [1 :0] wb_entryx_size; +wire [31:0] wb_entryx_wdata; +wire wb_so_req_x; + + +parameter DATAW = `FLEN; + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_entry_vld <= 1'b0; + else if (rtu_yy_xx_async_flush) + wb_entry_vld <= 1'b0; + else if (wb_create_en_x) + wb_entry_vld <= 1'b1; + else if (wb_data_pop_en_x) + wb_entry_vld <= 1'b0; +end + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_entry_addr_vld <= 1'b0; + else if (rtu_yy_xx_async_flush) + wb_entry_addr_vld <= 1'b0; + else if (wb_create_en_x) + wb_entry_addr_vld <= 1'b1; + else if (wb_addr_pop_en_x) + wb_entry_addr_vld <= 1'b0; +end + +// &Force("bus", "wb_create_shift",3,0); @50 +always@(posedge wb_entry_clk) +begin + if (wb_create_en_dp_x | ifu_lsu_warm_up) begin + wb_entry_addr[31:0] <= wb_create_addr[31:0]; + wb_entry_size[1:0] <= wb_create_size[1:0]; + wb_entry_fls <= wb_create_fls; + wb_entry_ca <= wb_create_ca; + wb_entry_buf <= wb_create_buf; + wb_entry_so <= wb_create_so; + wb_entry_mach_mode <= wb_create_mach_mode; + wb_entry_lock <= wb_create_lock; + wb_entry_sc_inst <= wb_create_sc_inst; + wb_entry_pmp_deny <= wb_create_pmp_deny; + wb_entry_sc_fail <= wb_create_sc_fail; + wb_entry_dest_preg[5:0] <= wb_create_dest_preg[5:0]; + wb_entry_src1_reg[5:0] <= wb_create_src1_reg[5:0]; + wb_entry_shift[2:0] <= wb_create_shift[2:0]; + wb_entry_split_first <= wb_create_split_first; + end +end + +// &CombBeg; @112 +always @( wb_entry_addr[1:0] + or wb_entry_size[1:0]) +begin + casez({wb_entry_size[1:0],wb_entry_addr[1:0]}) + 4'b0000: wb_entry_bytes_vld[3:0] = 4'b0001; + 4'b0001: wb_entry_bytes_vld[3:0] = 4'b0010; + 4'b0010: wb_entry_bytes_vld[3:0] = 4'b0100; + 4'b0011: wb_entry_bytes_vld[3:0] = 4'b1000; + 4'b0100: wb_entry_bytes_vld[3:0] = 4'b0011; + 4'b0110: wb_entry_bytes_vld[3:0] = 4'b1100; + 4'b1?00: wb_entry_bytes_vld[3:0] = 4'b1111; + default: wb_entry_bytes_vld[3:0] = 4'b1111; + endcase +// &CombEnd; @123 +end + +assign wb_entry_dw = wb_entry_size[1:0] == 2'b11; + +assign wb_entry_bytes_vld_ext[7:0] = wb_entry_addr[2] + ? {wb_entry_bytes_vld[3:0], 4'b0000} + : {{4{wb_entry_dw}},wb_entry_bytes_vld[3:0]}; + +//assign depd_ex2 = lsu_xx_ex2_data_vld & +// (wb_entry_fls == lsu_xx_ex2_fls) & +// (wb_entry_src1_reg[5:0] == lsu_xx_ex2_preg[5:0]); +assign fwd_lsu = da_xx_fwd_vld & +// !depd_ex2 & + (wb_entry_fls == da_xx_fwd_fls) & + (wb_entry_src1_reg[5:0] == da_xx_fwd_preg[5:0]); + +assign fwd_fpu = rtu_lsu_fgpr_wb_vld & wb_entry_fls & + (wb_entry_src1_reg[4:0] == rtu_lsu_fgpr_wb_reg[4:0]); +assign fwd_fpu_data[DATAW-1:0] + = rtu_lsu_fgpr_wb_data[DATAW-1:0]; +assign fwd_vld = wb_entry_vld & wb_entry_src1_depd & (fwd_lsu | fwd_fpu); +assign fwd_data[DATAW-1:0] = fwd_lsu + ? da_xx_fwd_data[DATAW-1:0] + : fwd_fpu_data[DATAW-1:0]; + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + wb_entry_src1_depd <= 1'b0; + else if (wb_create_en_dp_x) + wb_entry_src1_depd <= wb_create_src1_depd; + else if (fwd_vld) + wb_entry_src1_depd <= 1'b0; +end + +always@(posedge wb_data_clk) +begin + if (wb_create_en_dp_x | ifu_lsu_warm_up) + wb_entry_wdata[DATAW-1:0] <= wb_create_data[DATAW-1:0]; + else if (fwd_vld) + wb_entry_wdata[DATAW-1:0] <= fwd_data[DATAW-1:0]; +end + +//output +assign wb_entry_vld_x = wb_entry_vld; +assign wb_entry_addr_vld_x = wb_entry_addr_vld & !wb_entry_src1_depd; +assign wb_entry_data_vld_x = wb_entry_vld & !wb_entry_src1_depd; +assign wb_entryx_addr[31:0] = wb_entry_addr[31:0]; +assign wb_entryx_size[1:0] = wb_entry_size[1:0]; +assign wb_entry_fls_x = wb_entry_fls; +assign wb_entry_lock_x = wb_entry_lock; +assign wb_entry_lrsc_x = wb_entry_sc_inst; +assign wb_entryx_prot[3:0] = {wb_entry_ca,wb_entry_buf,wb_entry_mach_mode,1'b1}; +assign wb_entry_pmp_deny_x = wb_entry_pmp_deny; +assign wb_entry_sc_fail_x = wb_entry_sc_fail; +assign wb_so_req_x = wb_entry_addr_vld & wb_entry_so; +assign wb_entry_split_first_x = wb_entry_split_first; + +assign wb_entryx_wdata[DATAW-1:0] = wb_entry_wdata[DATAW-1:0]; +assign wb_entryx_dest_preg[5:0] = wb_entry_dest_preg[5:0]; +assign wb_entryx_shift[2:0] = wb_entry_shift[2:0]; + +// //&Force("bus","ag_ncb_addr",31,0); @202 +assign ag_addr_hit = wb_create_addr[31:3] == wb_entry_addr[31:3]; +assign bytes_vld_hit = |(wb_create_bytes_vld[7:0] & wb_entry_bytes_vld_ext[7:0]); + +assign req_mask = wb_entry_addr_vld & ag_ncb_inst_vld_dp & ag_ld_inst & ag_addr_hit & bytes_vld_hit; + +always@(posedge wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + req_mask_f <= 1'b0; + else if (wb_create_en_dp_x) + req_mask_f <= 1'b0; + else if (wb_addr_pop_en_x) + req_mask_f <= 1'b0; + else if (req_mask) + req_mask_f <= 1'b1; +end + +assign ld_hit_wb_x = wb_entry_addr_vld & !req_mask_f & ag_ld_inst & ag_addr_hit & bytes_vld_hit; +assign ld_hit_wb_f_x = wb_entry_addr_vld & req_mask_f; + +assign wb_entry_clk_en = wb_create_en_dp_x | ifu_lsu_warm_up; +// &Instance("gated_clk_cell", "x_pa_lsu_wb_entry_gated_clk"); @224 +gated_clk_cell x_pa_lsu_wb_entry_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (wb_entry_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (wb_entry_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @225 +// .external_en (1'b0), @226 +// .global_en (1'b1), @227 +// .module_en (cp0_lsu_icg_en ), @228 +// .local_en (wb_entry_clk_en), @229 +// .clk_out (wb_entry_clk)); @230 + +assign wb_data_clk_en = wb_create_en_dp_x | ifu_lsu_warm_up | fwd_vld; +// &Instance("gated_clk_cell", "x_pa_lsu_wb_data_gated_clk"); @233 +gated_clk_cell x_pa_lsu_wb_data_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (wb_data_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (wb_data_clk_en ), + .module_en (cp0_lsu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @234 +// .external_en (1'b0), @235 +// .global_en (1'b1), @236 +// .module_en (cp0_lsu_icg_en ), @237 +// .local_en (wb_data_clk_en), @238 +// .clk_out (wb_data_clk)); @239 + +assign wb_entryx_dbginfo[2:0] = {req_mask_f,wb_entry_addr_vld,wb_entry_vld}; + +// &ModuleEnd; @243 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x32.v new file mode 100644 index 0000000000000000000000000000000000000000..004dcf760665091eae36e2bdca1825c307705ba6 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x32.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_1024x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [9 :0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [9 :0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 10; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_1024x32"); @43 +pa_f_spsram_1024x32 x_pa_f_spsram_1024x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_1024x32"); @49 +// &Instance("pa_gsmc_spsram_1024x32"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x36.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x36.v new file mode 100644 index 0000000000000000000000000000000000000000..80d5b5fe67994ef0fc502b5b76769c24db6532cd --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x36.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_1024x36( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [9 :0] A; +input CEN; +input CLK; +input [35:0] D; +input GWEN; +input [35:0] WEN; +output [35:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [9 :0] A; +wire CEN; +wire CLK; +wire [35:0] D; +wire GWEN; +wire [35:0] Q; +wire [35:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 10; +parameter DATA_WIDTH = 36; +parameter WE_WIDTH = 36; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_1024x36"); @43 +pa_f_spsram_1024x36 x_pa_f_spsram_1024x36 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_1024x36"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x4.v new file mode 100644 index 0000000000000000000000000000000000000000..8deb6c855a208dc03064ee5259eb28ba58bdceec --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_1024x4.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_1024x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [9:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [9:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 10; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_1024x4"); @43 +pa_f_spsram_1024x4 x_pa_f_spsram_1024x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_1024x4"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x32.v new file mode 100644 index 0000000000000000000000000000000000000000..34d9f169b0f5bddf3e2e546e902b4a3bd9787af5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x32.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_128x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [6 :0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [6 :0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 7; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_128x32"); @43 +pa_f_spsram_128x32 x_pa_f_spsram_128x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_128x32"); @49 +// &Instance("pa_gsmc_spsram_128x32"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x4.v new file mode 100644 index 0000000000000000000000000000000000000000..11bfdb650767c9bcc498f923f76462587cedf64d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x4.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_128x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [6:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [6:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 7; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_128x4"); @43 +pa_f_spsram_128x4 x_pa_f_spsram_128x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_128x4"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x42.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x42.v new file mode 100644 index 0000000000000000000000000000000000000000..8055f3b6ca8afb5d6d81e3638047db2ccb34df4c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_128x42.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_128x42( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [6 :0] A; +input CEN; +input CLK; +input [41:0] D; +input GWEN; +input [41:0] WEN; +output [41:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [6 :0] A; +wire CEN; +wire CLK; +wire [41:0] D; +wire GWEN; +wire [41:0] Q; +wire [41:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 7; +parameter DATA_WIDTH = 42; +parameter WE_WIDTH = 42; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_128x42"); @43 +pa_f_spsram_128x42 x_pa_f_spsram_128x42 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_128x42"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_2048x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_2048x32.v new file mode 100644 index 0000000000000000000000000000000000000000..f7e60df42eb4cd686bb1bfbbccd9e2549bda0fa4 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_2048x32.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_2048x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [10:0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [10:0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 11; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_2048x32"); @43 +pa_f_spsram_2048x32 x_pa_f_spsram_2048x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_2048x32"); @49 +// &Instance("pa_umc_spsram_2048x32"); @61 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x32.v new file mode 100644 index 0000000000000000000000000000000000000000..42ff2e46447a401be7cfebdf6e1ac79db7f378cf --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x32.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_256x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [7 :0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [7 :0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 8; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_256x32"); @43 +pa_f_spsram_256x32 x_pa_f_spsram_256x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_256x32"); @49 +// &Instance("pa_gsmc_spsram_256x32"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x4.v new file mode 100644 index 0000000000000000000000000000000000000000..e8bb677fa89799c4082f9e4057518edab4ca5608 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x4.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_256x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [7:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [7:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 8; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_256x4"); @43 +pa_f_spsram_256x4 x_pa_f_spsram_256x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_256x4"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x40.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x40.v new file mode 100644 index 0000000000000000000000000000000000000000..64cd4636050badc9b0785040b7d38cd1cc42e384 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_256x40.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_256x40( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [7 :0] A; +input CEN; +input CLK; +input [39:0] D; +input GWEN; +input [39:0] WEN; +output [39:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [7 :0] A; +wire CEN; +wire CLK; +wire [39:0] D; +wire GWEN; +wire [39:0] Q; +wire [39:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 8; +parameter DATA_WIDTH = 40; +parameter WE_WIDTH = 40; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_256x40"); @43 +pa_f_spsram_256x40 x_pa_f_spsram_256x40 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_256x40"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x4.v new file mode 100644 index 0000000000000000000000000000000000000000..cbb0fdaba04fc2b0aaa67ff7562b3b46c929692d --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x4.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_32x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [4:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [4:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 5; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_32x4"); @43 +pa_f_spsram_32x4 x_pa_f_spsram_32x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_32x4"); @49 +// &Instance("pa_gsmc_spsram_32x4"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x46.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x46.v new file mode 100644 index 0000000000000000000000000000000000000000..1476975bb748ba7b9e23db97081fb2e74a83fc6a --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_32x46.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_32x46( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [4 :0] A; +input CEN; +input CLK; +input [45:0] D; +input GWEN; +input [45:0] WEN; +output [45:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [4 :0] A; +wire CEN; +wire CLK; +wire [45:0] D; +wire GWEN; +wire [45:0] Q; +wire [45:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 5; +parameter DATA_WIDTH = 46; +parameter WE_WIDTH = 46; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_32x46"); @43 +pa_f_spsram_32x46 x_pa_f_spsram_32x46 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_32x46"); @49 +// &Instance("pa_gsmc_spsram_32x46"); @55 + +// &ModuleEnd; @71 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_4096x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_4096x32.v new file mode 100644 index 0000000000000000000000000000000000000000..6202c74c4e42b2295e032e2116e4ee3fd60a2532 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_4096x32.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_4096x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [11:0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [11:0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 12; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_4096x32"); @43 +pa_f_spsram_4096x32 x_pa_f_spsram_4096x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_4096x32"); @49 +// &Instance("pa_umc_spsram_4096x32"); @61 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x32.v new file mode 100644 index 0000000000000000000000000000000000000000..de133ec3c30e7ad7486e785cffa735c89829081e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x32.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_512x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [8 :0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [8 :0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 9; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_512x32"); @43 +pa_f_spsram_512x32 x_pa_f_spsram_512x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_512x32"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x38.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x38.v new file mode 100644 index 0000000000000000000000000000000000000000..8d713e8d9068752ae3d69e514e8fb6bd3a60cc27 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_512x38.v @@ -0,0 +1,80 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_512x38( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [8 :0] A; +input CEN; +input CLK; +input [37:0] D; +input GWEN; +input [37:0] WEN; +output [37:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [8 :0] A; +wire CEN; +wire CLK; +wire [37:0] D; +wire GWEN; +wire [37:0] Q; +wire [37:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 9; +parameter DATA_WIDTH = 38; +parameter WE_WIDTH = 38; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_512x38"); @43 +pa_f_spsram_512x38 x_pa_f_spsram_512x38 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_512x38"); @49 +// &Instance("pa_umc_spsram_512x38"); @61 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x4.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x4.v new file mode 100644 index 0000000000000000000000000000000000000000..fdd2b5fd6d6f23c23ed5e75a473e91a527b88e32 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x4.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_64x4( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [5:0] A; +input CEN; +input CLK; +input [3:0] D; +input GWEN; +input [3:0] WEN; +output [3:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [5:0] A; +wire CEN; +wire CLK; +wire [3:0] D; +wire GWEN; +wire [3:0] Q; +wire [3:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 6; +parameter DATA_WIDTH = 4; +parameter WE_WIDTH = 4; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_64x4"); @43 +pa_f_spsram_64x4 x_pa_f_spsram_64x4 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_64x4"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x44.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x44.v new file mode 100644 index 0000000000000000000000000000000000000000..71799948284cce516427ff435e5fb2096b436244 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_64x44.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_64x44( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [5 :0] A; +input CEN; +input CLK; +input [43:0] D; +input GWEN; +input [43:0] WEN; +output [43:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [5 :0] A; +wire CEN; +wire CLK; +wire [43:0] D; +wire GWEN; +wire [43:0] Q; +wire [43:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 6; +parameter DATA_WIDTH = 44; +parameter WE_WIDTH = 44; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_64x44"); @43 +pa_f_spsram_64x44 x_pa_f_spsram_64x44 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + +// &Instance("pa_tsmc_spsram_64x44"); @49 + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_8192x32.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_8192x32.v new file mode 100644 index 0000000000000000000000000000000000000000..4f6af5fdc3f379f6c111e6a21da393cb58370842 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/lsu/rtl/pa_spsram_8192x32.v @@ -0,0 +1,78 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_spsram_8192x32( + A, + CEN, + CLK, + D, + GWEN, + Q, + WEN +); + +// &Ports; @23 +input [12:0] A; +input CEN; +input CLK; +input [31:0] D; +input GWEN; +input [31:0] WEN; +output [31:0] Q; + +// &Regs; @24 + +// &Wires; @25 +wire [12:0] A; +wire CEN; +wire CLK; +wire [31:0] D; +wire GWEN; +wire [31:0] Q; +wire [31:0] WEN; + + +//********************************************************** +// Parameter Definition +//********************************************************** +parameter ADDR_WIDTH = 13; +parameter DATA_WIDTH = 32; +parameter WE_WIDTH = 32; + +// &Force("bus","Q",DATA_WIDTH-1,0); @34 +// &Force("bus","WEN",WE_WIDTH-1,0); @35 +// &Force("bus","A",ADDR_WIDTH-1,0); @36 +// &Force("bus","D",DATA_WIDTH-1,0); @37 + +// //******************************************************** +// //* FPGA memory * +// //******************************************************** +// &Instance("pa_f_spsram_8192x32"); @43 +pa_f_spsram_8192x32 x_pa_f_spsram_8192x32 ( + .A (A ), + .CEN (CEN ), + .CLK (CLK ), + .D (D ), + .GWEN (GWEN), + .Q (Q ), + .WEN (WEN ) +); + + +// &ModuleEnd; @65 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_acc_arb.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_acc_arb.v new file mode 100644 index 0000000000000000000000000000000000000000..79c116f4c8e878127d4abf195e7d2c3a29b3da63 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_acc_arb.v @@ -0,0 +1,322 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_pmp_acc_arb( + ifu_acc_machine_mode, + ifu_acc_user_mode, + ifu_access_deny_region, + ifu_access_no_hit_deny, + lsu_acc_machine_mode, + lsu_acc_user_mode, + lsu_access_deny_region, + lsu_access_no_hit_deny, + lsu_pmp_is_st, + regs_comp_excut0, + regs_comp_excut1, + regs_comp_excut2, + regs_comp_excut3, + regs_comp_excut4, + regs_comp_excut5, + regs_comp_excut6, + regs_comp_excut7, + regs_comp_lock0, + regs_comp_lock1, + regs_comp_lock2, + regs_comp_lock3, + regs_comp_lock4, + regs_comp_lock5, + regs_comp_lock6, + regs_comp_lock7, + regs_comp_read0, + regs_comp_read1, + regs_comp_read2, + regs_comp_read3, + regs_comp_read4, + regs_comp_read5, + regs_comp_read6, + regs_comp_read7, + regs_comp_write0, + regs_comp_write1, + regs_comp_write2, + regs_comp_write3, + regs_comp_write4, + regs_comp_write5, + regs_comp_write6, + regs_comp_write7 +); + +// &Ports; @25 +input ifu_acc_machine_mode; +input ifu_acc_user_mode; +input lsu_acc_machine_mode; +input lsu_acc_user_mode; +input lsu_pmp_is_st; +input regs_comp_excut0; +input regs_comp_excut1; +input regs_comp_excut2; +input regs_comp_excut3; +input regs_comp_excut4; +input regs_comp_excut5; +input regs_comp_excut6; +input regs_comp_excut7; +input regs_comp_lock0; +input regs_comp_lock1; +input regs_comp_lock2; +input regs_comp_lock3; +input regs_comp_lock4; +input regs_comp_lock5; +input regs_comp_lock6; +input regs_comp_lock7; +input regs_comp_read0; +input regs_comp_read1; +input regs_comp_read2; +input regs_comp_read3; +input regs_comp_read4; +input regs_comp_read5; +input regs_comp_read6; +input regs_comp_read7; +input regs_comp_write0; +input regs_comp_write1; +input regs_comp_write2; +input regs_comp_write3; +input regs_comp_write4; +input regs_comp_write5; +input regs_comp_write6; +input regs_comp_write7; +output [7:0] ifu_access_deny_region; +output ifu_access_no_hit_deny; +output [7:0] lsu_access_deny_region; +output lsu_access_no_hit_deny; + +// &Regs; @26 + +// &Wires; @27 +wire ifu_acc_machine_mode; +wire ifu_acc_user_mode; +wire ifu_access_deny0; +wire ifu_access_deny1; +wire ifu_access_deny2; +wire ifu_access_deny3; +wire ifu_access_deny4; +wire ifu_access_deny5; +wire ifu_access_deny6; +wire ifu_access_deny7; +wire [7:0] ifu_access_deny_region; +wire ifu_access_no_hit_deny; +wire lsu_acc_machine_mode; +wire lsu_acc_user_mode; +wire lsu_access_deny0; +wire lsu_access_deny1; +wire lsu_access_deny2; +wire lsu_access_deny3; +wire lsu_access_deny4; +wire lsu_access_deny5; +wire lsu_access_deny6; +wire lsu_access_deny7; +wire [7:0] lsu_access_deny_region; +wire lsu_access_no_hit_deny; +wire lsu_pmp_is_st; +wire regs_comp_excut0; +wire regs_comp_excut1; +wire regs_comp_excut2; +wire regs_comp_excut3; +wire regs_comp_excut4; +wire regs_comp_excut5; +wire regs_comp_excut6; +wire regs_comp_excut7; +wire regs_comp_lock0; +wire regs_comp_lock1; +wire regs_comp_lock2; +wire regs_comp_lock3; +wire regs_comp_lock4; +wire regs_comp_lock5; +wire regs_comp_lock6; +wire regs_comp_lock7; +wire regs_comp_read0; +wire regs_comp_read1; +wire regs_comp_read2; +wire regs_comp_read3; +wire regs_comp_read4; +wire regs_comp_read5; +wire regs_comp_read6; +wire regs_comp_read7; +wire regs_comp_write0; +wire regs_comp_write1; +wire regs_comp_write2; +wire regs_comp_write3; +wire regs_comp_write4; +wire regs_comp_write5; +wire regs_comp_write6; +wire regs_comp_write7; + + + + +//----------------------------------------- +// Checks the access attribute with no entry hit +//----------------------------------------- +assign ifu_access_no_hit_deny = ifu_acc_user_mode; +assign lsu_access_no_hit_deny = lsu_acc_user_mode; + +//----------------------------------------- +// Checks the access attribute of region 0 +//----------------------------------------- +//IFU deny will be generated when: +//1. ifu access in machine mode: +//(1) PMP entry is locked +//(2) PMP entry is not executeable +//2. ifu access in user mode: +//(2) PMP entry is not executeable +assign ifu_access_deny_region[0] = ifu_access_deny0; +assign ifu_access_deny0 = ifu_acc_machine_mode && regs_comp_lock0 && !regs_comp_excut0 + || ifu_acc_user_mode && !regs_comp_excut0; + +//LSU deny will be generated when: +//1.lsu access in machine mode: +//(1) PMP entry is locked +//(2) access is load and PMP entry is not readable +// access is store and PMP entry is not writeable +//2.lsu access in user mode: +//(1) access is load and PMP entry is not readable +// access is store and PMP entry is not writeable +assign lsu_access_deny_region[0] = lsu_access_deny0; +assign lsu_access_deny0 = lsu_acc_machine_mode && regs_comp_lock0 + && (lsu_pmp_is_st && !regs_comp_write0 + || !lsu_pmp_is_st && !regs_comp_read0) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write0 + || !lsu_pmp_is_st && !regs_comp_read0); + +//----------------------------------------- +// Checks the access attribute of region 1 +//----------------------------------------- +assign ifu_access_deny_region[1] = ifu_access_deny1; +assign lsu_access_deny_region[1] = lsu_access_deny1; +assign ifu_access_deny1 = ifu_acc_machine_mode && regs_comp_lock1 && !regs_comp_excut1 + || ifu_acc_user_mode && !regs_comp_excut1; + +assign lsu_access_deny1 = lsu_acc_machine_mode && regs_comp_lock1 + && (lsu_pmp_is_st && !regs_comp_write1 + || !lsu_pmp_is_st && !regs_comp_read1) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write1 + || !lsu_pmp_is_st && !regs_comp_read1); + +//----------------------------------------- +// Checks the access attribute of region 2 +//----------------------------------------- +assign ifu_access_deny_region[2] = ifu_access_deny2; +assign lsu_access_deny_region[2] = lsu_access_deny2; +assign ifu_access_deny2 = ifu_acc_machine_mode && regs_comp_lock2 && !regs_comp_excut2 + || ifu_acc_user_mode && !regs_comp_excut2; + +assign lsu_access_deny2 = lsu_acc_machine_mode && regs_comp_lock2 + && (lsu_pmp_is_st && !regs_comp_write2 + || !lsu_pmp_is_st && !regs_comp_read2) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write2 + || !lsu_pmp_is_st && !regs_comp_read2); + +//----------------------------------------- +// Checks the access attribute of region 3 +//----------------------------------------- +assign ifu_access_deny_region[3] = ifu_access_deny3; +assign lsu_access_deny_region[3] = lsu_access_deny3; + +assign ifu_access_deny3 = ifu_acc_machine_mode && regs_comp_lock3 && !regs_comp_excut3 + || ifu_acc_user_mode && !regs_comp_excut3; + +assign lsu_access_deny3 = lsu_acc_machine_mode && regs_comp_lock3 + && (lsu_pmp_is_st && !regs_comp_write3 + || !lsu_pmp_is_st && !regs_comp_read3) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write3 + || !lsu_pmp_is_st && !regs_comp_read3); + +//----------------------------------------- +// Checks the access attribute of region 4 +//----------------------------------------- +assign ifu_access_deny_region[4] = ifu_access_deny4; +assign lsu_access_deny_region[4] = lsu_access_deny4; + +assign ifu_access_deny4 = ifu_acc_machine_mode && regs_comp_lock4 && !regs_comp_excut4 + || ifu_acc_user_mode && !regs_comp_excut4; + +assign lsu_access_deny4 = lsu_acc_machine_mode && regs_comp_lock4 + && (lsu_pmp_is_st && !regs_comp_write4 + || !lsu_pmp_is_st && !regs_comp_read4) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write4 + || !lsu_pmp_is_st && !regs_comp_read4); + +//----------------------------------------- +// Checks the access attribute of region 5 +//----------------------------------------- +assign ifu_access_deny_region[5] = ifu_access_deny5; +assign lsu_access_deny_region[5] = lsu_access_deny5; + +assign ifu_access_deny5 = ifu_acc_machine_mode && regs_comp_lock5 && !regs_comp_excut5 + || ifu_acc_user_mode && !regs_comp_excut5; + +assign lsu_access_deny5 = lsu_acc_machine_mode && regs_comp_lock5 + && (lsu_pmp_is_st && !regs_comp_write5 + || !lsu_pmp_is_st && !regs_comp_read5) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write5 + || !lsu_pmp_is_st && !regs_comp_read5); + +//----------------------------------------- +// Checks the access attribute of region 6 +//----------------------------------------- +assign ifu_access_deny_region[6] = ifu_access_deny6; +assign lsu_access_deny_region[6] = lsu_access_deny6; + +assign ifu_access_deny6 = ifu_acc_machine_mode && regs_comp_lock6 && !regs_comp_excut6 + || ifu_acc_user_mode && !regs_comp_excut6; + +assign lsu_access_deny6 = lsu_acc_machine_mode && regs_comp_lock6 + && (lsu_pmp_is_st && !regs_comp_write6 + || !lsu_pmp_is_st && !regs_comp_read6) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write6 + || !lsu_pmp_is_st && !regs_comp_read6); + +//----------------------------------------- +// Checks the access attribute of region 7 +//----------------------------------------- +assign ifu_access_deny_region[7] = ifu_access_deny7; +assign lsu_access_deny_region[7] = lsu_access_deny7; + +assign ifu_access_deny7 = ifu_acc_machine_mode && regs_comp_lock7 && !regs_comp_excut7 + || ifu_acc_user_mode && !regs_comp_excut7; + +assign lsu_access_deny7 = lsu_acc_machine_mode && regs_comp_lock7 + && (lsu_pmp_is_st && !regs_comp_write7 + || !lsu_pmp_is_st && !regs_comp_read7) + || lsu_acc_user_mode + && (lsu_pmp_is_st && !regs_comp_write7 + || !lsu_pmp_is_st && !regs_comp_read7); + + + + + + + + + +// &ModuleEnd; @483 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_comp_hit.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_comp_hit.v new file mode 100644 index 0000000000000000000000000000000000000000..4101d7f9308c2a73dc2f11466870a820f9046832 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_comp_hit.v @@ -0,0 +1,169 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_pmp_comp_hit( + addr_match_mode, + ifu_acc_addr, + ifu_addr_ge_bottom, + ifu_addr_ge_pmpaddr, + lsu_4k_cross, + lsu_acc_addr, + lsu_addr_ge_bottom, + lsu_addr_ge_pmpaddr, + pmp_ifu_hit, + pmp_lsu_hit, + pmpaddr +); + +// &Ports; @25 +input [1 :0] addr_match_mode; +input [31:0] ifu_acc_addr; +input ifu_addr_ge_bottom; +input [31:0] lsu_acc_addr; +input lsu_addr_ge_bottom; +input [25:0] pmpaddr; +output ifu_addr_ge_pmpaddr; +output lsu_4k_cross; +output lsu_addr_ge_pmpaddr; +output pmp_ifu_hit; +output pmp_lsu_hit; + +// &Regs; @26 +reg [31:0] addr_mask; +reg pmp_ifu_hit; +reg pmp_lsu_hit; + +// &Wires; @27 +wire [1 :0] addr_match_mode; +wire [31:0] ifu_acc_addr; +wire ifu_addr_ge_bottom; +wire ifu_addr_ge_pmpaddr; +wire ifu_addr_ls_top; +wire [25:0] ifu_comp_adder; +wire ifu_napot_addr_match; +wire ifu_tor_addr_match; +wire lsu_4k_cross; +wire [31:0] lsu_acc_addr; +wire lsu_addr_ge_bottom; +wire lsu_addr_ge_pmpaddr; +wire lsu_addr_ls_top; +wire [25:0] lsu_comp_adder; +wire lsu_napot_addr_match; +wire lsu_tor_addr_match; +wire [25:0] pmpaddr; + + +// &Force("bus","ifu_acc_addr",31,0); @29 +// &Force("bus","lsu_acc_addr",31,0); @30 +//========================================================== +// Address Matching Logic +//========================================================== +//Compare access address by four address-matching mode,and +//generate address hit information +// &CombBeg; @36 +always @( ifu_tor_addr_match + or addr_match_mode[1:0] + or ifu_napot_addr_match) +begin + case(addr_match_mode[1:0]) + 2'b00: pmp_ifu_hit = 1'b0; //OFF + 2'b01: pmp_ifu_hit = ifu_tor_addr_match; //TOR +// 2'b10: pmp_ifu_hit = ifu_na4_addr_match; //NA4 + 2'b11: pmp_ifu_hit = ifu_napot_addr_match; //NAPOT + default: pmp_ifu_hit = 1'b0; + endcase +// &CombEnd; @44 +end + +// &CombBeg; @46 +always @( lsu_tor_addr_match + or addr_match_mode[1:0] + or lsu_napot_addr_match) +begin + case(addr_match_mode[1:0]) + 2'b00: pmp_lsu_hit = 1'b0; //OFF + 2'b01: pmp_lsu_hit = lsu_tor_addr_match; //TOR +// 2'b10: pmp_lsu_hit = lsu_na4_addr_match; //NA4 + 2'b11: pmp_lsu_hit = lsu_napot_addr_match; //NAPOT + default: pmp_lsu_hit = 1'b0; + endcase +// &CombEnd; @54 +end + +// IFU +// 1. TOR mode : pmpaddr[i-1]<= addr < pmpaddr[i] +assign ifu_comp_adder[25:0] = {1'b0,ifu_acc_addr[31:7]} - {1'b0,pmpaddr[25:1]}; +assign ifu_addr_ls_top = ifu_comp_adder[25]; +assign ifu_addr_ge_pmpaddr = !ifu_comp_adder[25]; +assign ifu_tor_addr_match = ifu_addr_ge_bottom && ifu_addr_ls_top; + +// 2. NAPOT : addr &addr_mask == pmpaddr & addr_mask +assign ifu_napot_addr_match = (addr_mask[31:7] & ifu_acc_addr[31:7]) == (addr_mask[31:7] & pmpaddr[25:1]); + +// LSU +// 1. TOR mode : pmpaddr[i-1]<= addr < pmpaddr[i] +assign lsu_comp_adder[25:0] = {1'b0,lsu_acc_addr[31:7]} - {1'b0,pmpaddr[25:1]}; +assign lsu_addr_ls_top = lsu_comp_adder[25]; +assign lsu_addr_ge_pmpaddr = ~lsu_comp_adder[25]; +assign lsu_tor_addr_match = lsu_addr_ge_bottom && lsu_addr_ls_top; + +// 2. NAPOT : addr & addr_mask == pmpaddr & addr_mask +assign lsu_napot_addr_match = (addr_mask[31:7] & lsu_acc_addr[31:7]) == (addr_mask[31:7] & pmpaddr[25:1]); + +// dummy port +assign lsu_4k_cross = 1'b0; + +//---------------------------------------------------------- +//Generate the address mask for the addr come from ifu or iu +//register the addr mask signal to avoid timing violation +//---------------------------------------------------------- +// &CombBeg; @107 +always @( pmpaddr[25:0]) +begin + casez(pmpaddr[25:0]) + 26'b??_????_????_????_????_????_???0 : addr_mask[31:0] = 32'hffffff80; //128B + 26'b??_????_????_????_????_????_??01 : addr_mask[31:0] = 32'hffffff00; //256B + 26'b??_????_????_????_????_????_?011 : addr_mask[31:0] = 32'hfffffe00; //512B + 26'b??_????_????_????_????_????_0111 : addr_mask[31:0] = 32'hfffffc00; //1KB + 26'b??_????_????_????_????_???0_1111 : addr_mask[31:0] = 32'hfffff800; //2KB + 26'b??_????_????_????_????_??01_1111 : addr_mask[31:0] = 32'hfffff000; //4KB + 26'b??_????_????_????_????_?011_1111 : addr_mask[31:0] = 32'hffffe000; //8KB + 26'b??_????_????_????_????_0111_1111 : addr_mask[31:0] = 32'hffffc000; //16KB + 26'b??_????_????_????_???0_1111_1111 : addr_mask[31:0] = 32'hffff8000; //32KB + 26'b??_????_????_????_??01_1111_1111 : addr_mask[31:0] = 32'hffff0000; //64KB + 26'b??_????_????_????_?011_1111_1111 : addr_mask[31:0] = 32'hfffe0000; //128KB + 26'b??_????_????_????_0111_1111_1111 : addr_mask[31:0] = 32'hfffc0000; //256KB + 26'b??_????_????_???0_1111_1111_1111 : addr_mask[31:0] = 32'hfff80000; //512KB + 26'b??_????_????_??01_1111_1111_1111 : addr_mask[31:0] = 32'hfff00000; //1M + 26'b??_????_????_?011_1111_1111_1111 : addr_mask[31:0] = 32'hffe00000; //2M + 26'b??_????_????_0111_1111_1111_1111 : addr_mask[31:0] = 32'hffc00000; //4M + 26'b??_????_???0_1111_1111_1111_1111 : addr_mask[31:0] = 32'hff800000; //8M + 26'b??_????_??01_1111_1111_1111_1111 : addr_mask[31:0] = 32'hff000000; //16M + 26'b??_????_?011_1111_1111_1111_1111 : addr_mask[31:0] = 32'hfe000000; //32M + 26'b??_????_0111_1111_1111_1111_1111 : addr_mask[31:0] = 32'hfc000000; //64M + 26'b??_???0_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'hf8000000; //128M + 26'b??_??01_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'hf0000000; //256M + 26'b??_?011_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'he0000000; //512M + 26'b??_0111_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'hc0000000; //1G + 26'b?0_1111_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'h80000000; //2G + 26'b01_1111_1111_1111_1111_1111_1111 : addr_mask[31:0] = 32'h00000000; //4G + default : addr_mask[31:0] = 32'b0; + endcase +// &CombEnd; @137 +end + +// &ModuleEnd; @139 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_enc.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_enc.v new file mode 100644 index 0000000000000000000000000000000000000000..6485e0e6462258ae8452c57a6f7dd74a1f8832be --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_enc.v @@ -0,0 +1,338 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_pmp_enc( + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_yy_mach_mode, + ifu_pmp_machine_mode, + lsu_4k_cross, + lsu_pmp_write, + pmp_entry_lock, + pmp_ifu_acc_deny, + pmp_ifu_hit, + pmp_lsu_acc_deny, + pmp_lsu_hit, + regs_comp_excut0, + regs_comp_excut1, + regs_comp_excut2, + regs_comp_excut3, + regs_comp_excut4, + regs_comp_excut5, + regs_comp_excut6, + regs_comp_excut7, + regs_comp_lock0, + regs_comp_lock1, + regs_comp_lock10, + regs_comp_lock11, + regs_comp_lock12, + regs_comp_lock13, + regs_comp_lock14, + regs_comp_lock15, + regs_comp_lock2, + regs_comp_lock3, + regs_comp_lock4, + regs_comp_lock5, + regs_comp_lock6, + regs_comp_lock7, + regs_comp_lock8, + regs_comp_lock9, + regs_comp_read0, + regs_comp_read1, + regs_comp_read2, + regs_comp_read3, + regs_comp_read4, + regs_comp_read5, + regs_comp_read6, + regs_comp_read7, + regs_comp_write0, + regs_comp_write1, + regs_comp_write2, + regs_comp_write3, + regs_comp_write4, + regs_comp_write5, + regs_comp_write6, + regs_comp_write7 +); + +// &Ports; @24 +input [1 :0] cp0_pmp_mstatus_mpp; +input cp0_pmp_mstatus_mprv; +input cp0_yy_mach_mode; +input ifu_pmp_machine_mode; +input [15:0] lsu_4k_cross; +input lsu_pmp_write; +input [7 :0] pmp_ifu_hit; +input [7 :0] pmp_lsu_hit; +input regs_comp_excut0; +input regs_comp_excut1; +input regs_comp_excut2; +input regs_comp_excut3; +input regs_comp_excut4; +input regs_comp_excut5; +input regs_comp_excut6; +input regs_comp_excut7; +input regs_comp_lock0; +input regs_comp_lock1; +input regs_comp_lock10; +input regs_comp_lock11; +input regs_comp_lock12; +input regs_comp_lock13; +input regs_comp_lock14; +input regs_comp_lock15; +input regs_comp_lock2; +input regs_comp_lock3; +input regs_comp_lock4; +input regs_comp_lock5; +input regs_comp_lock6; +input regs_comp_lock7; +input regs_comp_lock8; +input regs_comp_lock9; +input regs_comp_read0; +input regs_comp_read1; +input regs_comp_read2; +input regs_comp_read3; +input regs_comp_read4; +input regs_comp_read5; +input regs_comp_read6; +input regs_comp_read7; +input regs_comp_write0; +input regs_comp_write1; +input regs_comp_write2; +input regs_comp_write3; +input regs_comp_write4; +input regs_comp_write5; +input regs_comp_write6; +input regs_comp_write7; +output [15:0] pmp_entry_lock; +output pmp_ifu_acc_deny; +output pmp_lsu_acc_deny; + +// &Regs; @25 +reg ifu_access_deny; +reg lsu_access_deny; + +// &Wires; @26 +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire cp0_yy_mach_mode; +wire ifu_acc_machine_mode; +wire ifu_acc_user_mode; +wire [7 :0] ifu_access_deny_region; +wire ifu_access_no_hit_deny; +wire ifu_pmp_machine_mode; +wire lsu_acc_machine_mode; +wire lsu_acc_user_mode; +wire [7 :0] lsu_access_deny_region; +wire lsu_access_no_hit_deny; +wire lsu_pmp_write; +wire [15:0] pmp_entry_lock; +wire pmp_ifu_acc_deny; +wire [7 :0] pmp_ifu_hit; +wire pmp_lsu_acc_deny; +wire [7 :0] pmp_lsu_hit; +wire regs_comp_excut0; +wire regs_comp_excut1; +wire regs_comp_excut2; +wire regs_comp_excut3; +wire regs_comp_excut4; +wire regs_comp_excut5; +wire regs_comp_excut6; +wire regs_comp_excut7; +wire regs_comp_lock0; +wire regs_comp_lock1; +wire regs_comp_lock10; +wire regs_comp_lock11; +wire regs_comp_lock12; +wire regs_comp_lock13; +wire regs_comp_lock14; +wire regs_comp_lock15; +wire regs_comp_lock2; +wire regs_comp_lock3; +wire regs_comp_lock4; +wire regs_comp_lock5; +wire regs_comp_lock6; +wire regs_comp_lock7; +wire regs_comp_lock8; +wire regs_comp_lock9; +wire regs_comp_read0; +wire regs_comp_read1; +wire regs_comp_read2; +wire regs_comp_read3; +wire regs_comp_read4; +wire regs_comp_read5; +wire regs_comp_read6; +wire regs_comp_read7; +wire regs_comp_write0; +wire regs_comp_write1; +wire regs_comp_write2; +wire regs_comp_write3; +wire regs_comp_write4; +wire regs_comp_write5; +wire regs_comp_write6; +wire regs_comp_write7; + + +//---------------------------------------------------------- +// region access arbitor +//---------------------------------------------------------- +//========================================================== +// Attribute Matching Logic +//========================================================== +//------------------------------------------- +// Check the access attribute of each region +//------------------------------------------- +assign lsu_acc_machine_mode = cp0_yy_mach_mode && !cp0_pmp_mstatus_mprv + || (cp0_pmp_mstatus_mpp[1:0] == 2'b11) && cp0_pmp_mstatus_mprv; + +assign lsu_acc_user_mode = !cp0_yy_mach_mode && !cp0_pmp_mstatus_mprv + || (cp0_pmp_mstatus_mpp[1:0] == 2'b00) && cp0_pmp_mstatus_mprv; + +//when bmu not grant,acc machine mode and secure mode should not change +assign ifu_acc_machine_mode = ifu_pmp_machine_mode; +assign ifu_acc_user_mode = !ifu_pmp_machine_mode; + +// &Instance("pa_pmp_acc_arb","x_pa_pmp_acc_arb"); @67 +pa_pmp_acc_arb x_pa_pmp_acc_arb ( + .ifu_acc_machine_mode (ifu_acc_machine_mode ), + .ifu_acc_user_mode (ifu_acc_user_mode ), + .ifu_access_deny_region (ifu_access_deny_region), + .ifu_access_no_hit_deny (ifu_access_no_hit_deny), + .lsu_acc_machine_mode (lsu_acc_machine_mode ), + .lsu_acc_user_mode (lsu_acc_user_mode ), + .lsu_access_deny_region (lsu_access_deny_region), + .lsu_access_no_hit_deny (lsu_access_no_hit_deny), + .lsu_pmp_is_st (lsu_pmp_write ), + .regs_comp_excut0 (regs_comp_excut0 ), + .regs_comp_excut1 (regs_comp_excut1 ), + .regs_comp_excut2 (regs_comp_excut2 ), + .regs_comp_excut3 (regs_comp_excut3 ), + .regs_comp_excut4 (regs_comp_excut4 ), + .regs_comp_excut5 (regs_comp_excut5 ), + .regs_comp_excut6 (regs_comp_excut6 ), + .regs_comp_excut7 (regs_comp_excut7 ), + .regs_comp_lock0 (regs_comp_lock0 ), + .regs_comp_lock1 (regs_comp_lock1 ), + .regs_comp_lock2 (regs_comp_lock2 ), + .regs_comp_lock3 (regs_comp_lock3 ), + .regs_comp_lock4 (regs_comp_lock4 ), + .regs_comp_lock5 (regs_comp_lock5 ), + .regs_comp_lock6 (regs_comp_lock6 ), + .regs_comp_lock7 (regs_comp_lock7 ), + .regs_comp_read0 (regs_comp_read0 ), + .regs_comp_read1 (regs_comp_read1 ), + .regs_comp_read2 (regs_comp_read2 ), + .regs_comp_read3 (regs_comp_read3 ), + .regs_comp_read4 (regs_comp_read4 ), + .regs_comp_read5 (regs_comp_read5 ), + .regs_comp_read6 (regs_comp_read6 ), + .regs_comp_read7 (regs_comp_read7 ), + .regs_comp_write0 (regs_comp_write0 ), + .regs_comp_write1 (regs_comp_write1 ), + .regs_comp_write2 (regs_comp_write2 ), + .regs_comp_write3 (regs_comp_write3 ), + .regs_comp_write4 (regs_comp_write4 ), + .regs_comp_write5 (regs_comp_write5 ), + .regs_comp_write6 (regs_comp_write6 ), + .regs_comp_write7 (regs_comp_write7 ) +); + +// &Connect( @68 +// .lsu_pmp_is_st (lsu_pmp_write) @69 +// ); @70 + +// &CombBeg; @76 +// &CombEnd; @83 +// &CombBeg; @85 +// &CombEnd; @92 + +// &CombBeg; @99 +// &CombEnd; @108 +// &CombBeg; @110 +// &CombEnd; @119 + +//---------------------------------------------------------- +//priority encoder for access_deny +//---------------------------------------------------------- +// &CombBeg; @126 +always @( ifu_access_deny_region[7:4] + or ifu_access_no_hit_deny + or ifu_access_deny_region[3:0] + or pmp_ifu_hit[7:0]) +begin + casez(pmp_ifu_hit[7:0]) + 8'b???????1 : ifu_access_deny = ifu_access_deny_region[0]; + 8'b??????10 : ifu_access_deny = ifu_access_deny_region[1]; + 8'b?????100 : ifu_access_deny = ifu_access_deny_region[2]; + 8'b????1000 : ifu_access_deny = ifu_access_deny_region[3]; + 8'b???10000 : ifu_access_deny = ifu_access_deny_region[4]; + 8'b??100000 : ifu_access_deny = ifu_access_deny_region[5]; + 8'b?1000000 : ifu_access_deny = ifu_access_deny_region[6]; + 8'b10000000 : ifu_access_deny = ifu_access_deny_region[7]; + 8'b00000000 : ifu_access_deny = ifu_access_no_hit_deny; + default : ifu_access_deny = 1'bx; +endcase +// &CombEnd; @139 +end + +// &CombBeg; @141 +always @( lsu_access_deny_region[7:4] + or pmp_lsu_hit[7:0] + or lsu_access_no_hit_deny + or lsu_access_deny_region[3:0]) +begin + casez(pmp_lsu_hit[7:0]) + 8'b???????1 : lsu_access_deny = lsu_access_deny_region[0]; + 8'b??????10 : lsu_access_deny = lsu_access_deny_region[1]; + 8'b?????100 : lsu_access_deny = lsu_access_deny_region[2]; + 8'b????1000 : lsu_access_deny = lsu_access_deny_region[3]; + 8'b???10000 : lsu_access_deny = lsu_access_deny_region[4]; + 8'b??100000 : lsu_access_deny = lsu_access_deny_region[5]; + 8'b?1000000 : lsu_access_deny = lsu_access_deny_region[6]; + 8'b10000000 : lsu_access_deny = lsu_access_deny_region[7]; + 8'b00000000 : lsu_access_deny = lsu_access_no_hit_deny; + default : lsu_access_deny = 1'bx; +endcase +// &CombEnd; @154 +end + +// &CombBeg; @161 +// &CombEnd; @178 +// &CombBeg; @180 +// &CombEnd; @197 + +// &CombBeg; @204 +// &CombEnd; @225 +// &CombBeg; @227 +// &CombEnd; @248 + +assign pmp_entry_lock[15:0] = { + regs_comp_lock15, regs_comp_lock14, regs_comp_lock13, regs_comp_lock12, + regs_comp_lock11, regs_comp_lock10, regs_comp_lock9, regs_comp_lock8, + regs_comp_lock7, regs_comp_lock6, regs_comp_lock5, regs_comp_lock4, + regs_comp_lock3, regs_comp_lock2, regs_comp_lock1, regs_comp_lock0 + }; +// &Force("input", "lsu_4k_cross"); @261 +// &Force("bus", "lsu_4k_cross", 15, 0); @262 + +//---------------------------------------------------------- +// Interface to Bus Matrix Unit +assign pmp_ifu_acc_deny = ifu_access_deny; +assign pmp_lsu_acc_deny = lsu_access_deny; + + +// &ModuleEnd; @271 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_regs.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_regs.v new file mode 100644 index 0000000000000000000000000000000000000000..c23164df670a3532bf84e28356189a54c8ddd682 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_regs.v @@ -0,0 +1,922 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_pmp_regs( + cp0_pmp_csr_sel, + cp0_pmp_updt_data, + cp0_yy_secu_mode_aft_dbg, + cpuclk, + cpurst_b, + pmp_cp0_data, + pmp_csr_wen, + pmpaddr0_value, + pmpaddr1_value, + pmpaddr2_value, + pmpaddr3_value, + pmpaddr4_value, + pmpaddr5_value, + pmpaddr6_value, + pmpaddr7_value, + regs_comp_addr_mode0, + regs_comp_addr_mode1, + regs_comp_addr_mode2, + regs_comp_addr_mode3, + regs_comp_addr_mode4, + regs_comp_addr_mode5, + regs_comp_addr_mode6, + regs_comp_addr_mode7, + regs_comp_excut0, + regs_comp_excut1, + regs_comp_excut2, + regs_comp_excut3, + regs_comp_excut4, + regs_comp_excut5, + regs_comp_excut6, + regs_comp_excut7, + regs_comp_lock0, + regs_comp_lock1, + regs_comp_lock10, + regs_comp_lock11, + regs_comp_lock12, + regs_comp_lock13, + regs_comp_lock14, + regs_comp_lock15, + regs_comp_lock2, + regs_comp_lock3, + regs_comp_lock4, + regs_comp_lock5, + regs_comp_lock6, + regs_comp_lock7, + regs_comp_lock8, + regs_comp_lock9, + regs_comp_read0, + regs_comp_read1, + regs_comp_read2, + regs_comp_read3, + regs_comp_read4, + regs_comp_read5, + regs_comp_read6, + regs_comp_read7, + regs_comp_write0, + regs_comp_write1, + regs_comp_write2, + regs_comp_write3, + regs_comp_write4, + regs_comp_write5, + regs_comp_write6, + regs_comp_write7 +); + +// &Ports; @24 +input [19:0] cp0_pmp_csr_sel; +input [31:0] cp0_pmp_updt_data; +input cp0_yy_secu_mode_aft_dbg; +input cpuclk; +input cpurst_b; +input [19:0] pmp_csr_wen; +output [31:0] pmp_cp0_data; +output [25:0] pmpaddr0_value; +output [25:0] pmpaddr1_value; +output [25:0] pmpaddr2_value; +output [25:0] pmpaddr3_value; +output [25:0] pmpaddr4_value; +output [25:0] pmpaddr5_value; +output [25:0] pmpaddr6_value; +output [25:0] pmpaddr7_value; +output [1 :0] regs_comp_addr_mode0; +output [1 :0] regs_comp_addr_mode1; +output [1 :0] regs_comp_addr_mode2; +output [1 :0] regs_comp_addr_mode3; +output [1 :0] regs_comp_addr_mode4; +output [1 :0] regs_comp_addr_mode5; +output [1 :0] regs_comp_addr_mode6; +output [1 :0] regs_comp_addr_mode7; +output regs_comp_excut0; +output regs_comp_excut1; +output regs_comp_excut2; +output regs_comp_excut3; +output regs_comp_excut4; +output regs_comp_excut5; +output regs_comp_excut6; +output regs_comp_excut7; +output regs_comp_lock0; +output regs_comp_lock1; +output regs_comp_lock10; +output regs_comp_lock11; +output regs_comp_lock12; +output regs_comp_lock13; +output regs_comp_lock14; +output regs_comp_lock15; +output regs_comp_lock2; +output regs_comp_lock3; +output regs_comp_lock4; +output regs_comp_lock5; +output regs_comp_lock6; +output regs_comp_lock7; +output regs_comp_lock8; +output regs_comp_lock9; +output regs_comp_read0; +output regs_comp_read1; +output regs_comp_read2; +output regs_comp_read3; +output regs_comp_read4; +output regs_comp_read5; +output regs_comp_read6; +output regs_comp_read7; +output regs_comp_write0; +output regs_comp_write1; +output regs_comp_write2; +output regs_comp_write3; +output regs_comp_write4; +output regs_comp_write5; +output regs_comp_write6; +output regs_comp_write7; + +// &Regs; @25 +reg [1 :0] pmp0cfg_addr_mode; +reg pmp0cfg_executeable; +reg pmp0cfg_lock; +reg pmp0cfg_readable; +reg pmp0cfg_writable; +reg [1 :0] pmp1cfg_addr_mode; +reg pmp1cfg_executeable; +reg pmp1cfg_lock; +reg pmp1cfg_readable; +reg pmp1cfg_writable; +reg [1 :0] pmp2cfg_addr_mode; +reg pmp2cfg_executeable; +reg pmp2cfg_lock; +reg pmp2cfg_readable; +reg pmp2cfg_writable; +reg [1 :0] pmp3cfg_addr_mode; +reg pmp3cfg_executeable; +reg pmp3cfg_lock; +reg pmp3cfg_readable; +reg pmp3cfg_writable; +reg [1 :0] pmp4cfg_addr_mode; +reg pmp4cfg_executeable; +reg pmp4cfg_lock; +reg pmp4cfg_readable; +reg pmp4cfg_writable; +reg [1 :0] pmp5cfg_addr_mode; +reg pmp5cfg_executeable; +reg pmp5cfg_lock; +reg pmp5cfg_readable; +reg pmp5cfg_writable; +reg [1 :0] pmp6cfg_addr_mode; +reg pmp6cfg_executeable; +reg pmp6cfg_lock; +reg pmp6cfg_readable; +reg pmp6cfg_writable; +reg [1 :0] pmp7cfg_addr_mode; +reg pmp7cfg_executeable; +reg pmp7cfg_lock; +reg pmp7cfg_readable; +reg pmp7cfg_writable; +reg [25:0] pmpaddr0_value; +reg [25:0] pmpaddr1_value; +reg [25:0] pmpaddr2_value; +reg [25:0] pmpaddr3_value; +reg [25:0] pmpaddr4_value; +reg [25:0] pmpaddr5_value; +reg [25:0] pmpaddr6_value; +reg [25:0] pmpaddr7_value; + +// &Wires; @26 +wire [19:0] cp0_pmp_csr_sel; +wire [31:0] cp0_pmp_updt_data; +wire cp0_yy_secu_mode_aft_dbg; +wire cpuclk; +wire cpurst_b; +wire [1 :0] pmp0cfg_mode; +wire [1 :0] pmp10cfg_mode; +wire [1 :0] pmp11cfg_mode; +wire [1 :0] pmp12cfg_mode; +wire [1 :0] pmp13cfg_mode; +wire [1 :0] pmp14cfg_mode; +wire [1 :0] pmp15cfg_mode; +wire [1 :0] pmp1cfg_mode; +wire [1 :0] pmp2cfg_mode; +wire [1 :0] pmp3cfg_mode; +wire [1 :0] pmp4cfg_mode; +wire [1 :0] pmp5cfg_mode; +wire [1 :0] pmp6cfg_mode; +wire [1 :0] pmp7cfg_mode; +wire [1 :0] pmp8cfg_mode; +wire [1 :0] pmp9cfg_mode; +wire [31:0] pmp_cp0_data; +wire [19:0] pmp_csr_wen; +wire pmp_updt_pmp0cfg; +wire pmp_updt_pmp1cfg; +wire pmp_updt_pmp2cfg; +wire pmp_updt_pmp3cfg; +wire pmp_updt_pmp4cfg; +wire pmp_updt_pmp5cfg; +wire pmp_updt_pmp6cfg; +wire pmp_updt_pmp7cfg; +wire pmp_updt_pmpaddr0; +wire pmp_updt_pmpaddr1; +wire pmp_updt_pmpaddr2; +wire pmp_updt_pmpaddr3; +wire pmp_updt_pmpaddr4; +wire pmp_updt_pmpaddr5; +wire pmp_updt_pmpaddr6; +wire pmp_updt_pmpaddr7; +wire [4 :0] pmpaddr0_low; +wire [4 :0] pmpaddr10_low; +wire [25:0] pmpaddr10_value; +wire [4 :0] pmpaddr11_low; +wire [25:0] pmpaddr11_value; +wire [4 :0] pmpaddr12_low; +wire [25:0] pmpaddr12_value; +wire [4 :0] pmpaddr13_low; +wire [25:0] pmpaddr13_value; +wire [4 :0] pmpaddr14_low; +wire [25:0] pmpaddr14_value; +wire [4 :0] pmpaddr15_low; +wire [25:0] pmpaddr15_value; +wire [4 :0] pmpaddr1_low; +wire [4 :0] pmpaddr2_low; +wire [4 :0] pmpaddr3_low; +wire [4 :0] pmpaddr4_low; +wire [4 :0] pmpaddr5_low; +wire [4 :0] pmpaddr6_low; +wire [4 :0] pmpaddr7_low; +wire [4 :0] pmpaddr8_low; +wire [25:0] pmpaddr8_value; +wire [4 :0] pmpaddr9_low; +wire [25:0] pmpaddr9_value; +wire [31:0] pmpcfg0_value; +wire [31:0] pmpcfg1_value; +wire [31:0] pmpcfg2_value; +wire [31:0] pmpcfg3_value; +wire pmpteecfg_s0; +wire pmpteecfg_s1; +wire pmpteecfg_s2; +wire pmpteecfg_s3; +wire pmpteecfg_s4; +wire pmpteecfg_s5; +wire pmpteecfg_s6; +wire pmpteecfg_s7; +wire [1 :0] regs_comp_addr_mode0; +wire [1 :0] regs_comp_addr_mode1; +wire [1 :0] regs_comp_addr_mode2; +wire [1 :0] regs_comp_addr_mode3; +wire [1 :0] regs_comp_addr_mode4; +wire [1 :0] regs_comp_addr_mode5; +wire [1 :0] regs_comp_addr_mode6; +wire [1 :0] regs_comp_addr_mode7; +wire regs_comp_excut0; +wire regs_comp_excut1; +wire regs_comp_excut2; +wire regs_comp_excut3; +wire regs_comp_excut4; +wire regs_comp_excut5; +wire regs_comp_excut6; +wire regs_comp_excut7; +wire regs_comp_lock0; +wire regs_comp_lock1; +wire regs_comp_lock10; +wire regs_comp_lock11; +wire regs_comp_lock12; +wire regs_comp_lock13; +wire regs_comp_lock14; +wire regs_comp_lock15; +wire regs_comp_lock2; +wire regs_comp_lock3; +wire regs_comp_lock4; +wire regs_comp_lock5; +wire regs_comp_lock6; +wire regs_comp_lock7; +wire regs_comp_lock8; +wire regs_comp_lock9; +wire regs_comp_read0; +wire regs_comp_read1; +wire regs_comp_read2; +wire regs_comp_read3; +wire regs_comp_read4; +wire regs_comp_read5; +wire regs_comp_read6; +wire regs_comp_read7; +wire regs_comp_write0; +wire regs_comp_write1; +wire regs_comp_write2; +wire regs_comp_write3; +wire regs_comp_write4; +wire regs_comp_write5; +wire regs_comp_write6; +wire regs_comp_write7; + + +parameter ADDR_WIDTH = 25+1; + +assign regs_comp_read0 = pmp0cfg_readable; +assign regs_comp_write0 = pmp0cfg_writable; +assign regs_comp_excut0 = pmp0cfg_executeable; +assign regs_comp_addr_mode0[1:0] = pmp0cfg_mode[1:0]; +assign regs_comp_lock0 = pmp0cfg_lock; + +assign regs_comp_read1 = pmp1cfg_readable; +assign regs_comp_write1 = pmp1cfg_writable; +assign regs_comp_excut1 = pmp1cfg_executeable; +assign regs_comp_addr_mode1[1:0] = pmp1cfg_mode[1:0]; +assign regs_comp_lock1 = pmp1cfg_lock; + +assign regs_comp_read2 = pmp2cfg_readable; +assign regs_comp_write2 = pmp2cfg_writable; +assign regs_comp_excut2 = pmp2cfg_executeable; +assign regs_comp_addr_mode2[1:0] = pmp2cfg_mode[1:0]; +assign regs_comp_lock2 = pmp2cfg_lock; + +assign regs_comp_read3 = pmp3cfg_readable; +assign regs_comp_write3 = pmp3cfg_writable; +assign regs_comp_excut3 = pmp3cfg_executeable; +assign regs_comp_addr_mode3[1:0] = pmp3cfg_mode[1:0]; +assign regs_comp_lock3 = pmp3cfg_lock; + +assign regs_comp_read4 = pmp4cfg_readable; +assign regs_comp_write4 = pmp4cfg_writable; +assign regs_comp_excut4 = pmp4cfg_executeable; +assign regs_comp_addr_mode4[1:0] = pmp4cfg_mode[1:0]; +assign regs_comp_lock4 = pmp4cfg_lock; + +assign regs_comp_read5 = pmp5cfg_readable; +assign regs_comp_write5 = pmp5cfg_writable; +assign regs_comp_excut5 = pmp5cfg_executeable; +assign regs_comp_addr_mode5[1:0] = pmp5cfg_mode[1:0]; +assign regs_comp_lock5 = pmp5cfg_lock; + +assign regs_comp_read6 = pmp6cfg_readable; +assign regs_comp_write6 = pmp6cfg_writable; +assign regs_comp_excut6 = pmp6cfg_executeable; +assign regs_comp_addr_mode6[1:0] = pmp6cfg_mode[1:0]; +assign regs_comp_lock6 = pmp6cfg_lock; + +assign regs_comp_read7 = pmp7cfg_readable; +assign regs_comp_write7 = pmp7cfg_writable; +assign regs_comp_excut7 = pmp7cfg_executeable; +assign regs_comp_addr_mode7[1:0] = pmp7cfg_mode[1:0]; +assign regs_comp_lock7 = pmp7cfg_lock; + + + + + + + + + +//========================================================== +// PMP Entry Configuration Register +//========================================================== +//------------------------------------------------ +//pmpcfg0 register +//------------------------------------------------ +assign pmp_updt_pmp0cfg = pmp_csr_wen[0] && !pmp0cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp0cfg_readable <= 1'b0; + pmp0cfg_writable <= 1'b0; + pmp0cfg_executeable <= 1'b0; + pmp0cfg_addr_mode[1:0] <= 2'b0; + pmp0cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp0cfg && (!pmpteecfg_s0 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp0cfg_readable <= cp0_pmp_updt_data[0]; + pmp0cfg_writable <= cp0_pmp_updt_data[1]; + pmp0cfg_executeable <= cp0_pmp_updt_data[2]; + pmp0cfg_addr_mode[1:0] <= cp0_pmp_updt_data[4:3]; + pmp0cfg_lock <= cp0_pmp_updt_data[7]; + end + else + begin + pmp0cfg_readable <= pmp0cfg_readable; + pmp0cfg_writable <= pmp0cfg_writable; + pmp0cfg_executeable <= pmp0cfg_executeable; + pmp0cfg_addr_mode[1:0] <= pmp0cfg_addr_mode[1:0]; + pmp0cfg_lock <= pmp0cfg_lock; + end +end +assign pmp0cfg_mode[1:0] = pmp0cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp0cfg_addr_mode[1:0]; + +assign pmp_updt_pmp1cfg = pmp_csr_wen[0] && !pmp1cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp1cfg_readable <= 1'b0; + pmp1cfg_writable <= 1'b0; + pmp1cfg_executeable <= 1'b0; + pmp1cfg_addr_mode[1:0] <= 2'b0; + pmp1cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp1cfg && (!pmpteecfg_s1 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp1cfg_readable <= cp0_pmp_updt_data[8]; + pmp1cfg_writable <= cp0_pmp_updt_data[9]; + pmp1cfg_executeable <= cp0_pmp_updt_data[10]; + pmp1cfg_addr_mode[1:0] <= cp0_pmp_updt_data[12:11]; + pmp1cfg_lock <= cp0_pmp_updt_data[15]; + end + else + begin + pmp1cfg_readable <= pmp1cfg_readable; + pmp1cfg_writable <= pmp1cfg_writable; + pmp1cfg_executeable <= pmp1cfg_executeable; + pmp1cfg_addr_mode[1:0] <= pmp1cfg_addr_mode[1:0]; + pmp1cfg_lock <= pmp1cfg_lock; + end +end +assign pmp1cfg_mode[1:0] = pmp1cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp1cfg_addr_mode[1:0]; + +assign pmp_updt_pmp2cfg = pmp_csr_wen[0] && !pmp2cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp2cfg_readable <= 1'b0; + pmp2cfg_writable <= 1'b0; + pmp2cfg_executeable <= 1'b0; + pmp2cfg_addr_mode[1:0] <= 2'b0; + pmp2cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp2cfg && (!pmpteecfg_s2 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp2cfg_readable <= cp0_pmp_updt_data[16]; + pmp2cfg_writable <= cp0_pmp_updt_data[17]; + pmp2cfg_executeable <= cp0_pmp_updt_data[18]; + pmp2cfg_addr_mode[1:0] <= cp0_pmp_updt_data[20:19]; + pmp2cfg_lock <= cp0_pmp_updt_data[23]; + end + else + begin + pmp2cfg_readable <= pmp2cfg_readable; + pmp2cfg_writable <= pmp2cfg_writable; + pmp2cfg_executeable <= pmp2cfg_executeable; + pmp2cfg_addr_mode[1:0] <= pmp2cfg_addr_mode[1:0]; + pmp2cfg_lock <= pmp2cfg_lock; + end +end +assign pmp2cfg_mode[1:0] = pmp2cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp2cfg_addr_mode[1:0]; + +assign pmp_updt_pmp3cfg = pmp_csr_wen[0] && !pmp3cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp3cfg_readable <= 1'b0; + pmp3cfg_writable <= 1'b0; + pmp3cfg_executeable <= 1'b0; + pmp3cfg_addr_mode[1:0] <= 2'b0; + pmp3cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp3cfg && (!pmpteecfg_s3 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp3cfg_readable <= cp0_pmp_updt_data[24]; + pmp3cfg_writable <= cp0_pmp_updt_data[25]; + pmp3cfg_executeable <= cp0_pmp_updt_data[26]; + pmp3cfg_addr_mode[1:0] <= cp0_pmp_updt_data[28:27]; + pmp3cfg_lock <= cp0_pmp_updt_data[31]; + end + else + begin + pmp3cfg_readable <= pmp3cfg_readable; + pmp3cfg_writable <= pmp3cfg_writable; + pmp3cfg_executeable <= pmp3cfg_executeable; + pmp3cfg_addr_mode[1:0] <= pmp3cfg_addr_mode[1:0]; + pmp3cfg_lock <= pmp3cfg_lock; + end +end +assign pmp3cfg_mode[1:0] = pmp3cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp3cfg_addr_mode[1:0]; + +//------------------------------------------------ +//pmpcfg1 register +//------------------------------------------------ +assign pmp_updt_pmp4cfg = pmp_csr_wen[1] && !pmp4cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp4cfg_readable <= 1'b0; + pmp4cfg_writable <= 1'b0; + pmp4cfg_executeable <= 1'b0; + pmp4cfg_addr_mode[1:0] <= 2'b0; + pmp4cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp4cfg && (!pmpteecfg_s4 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp4cfg_readable <= cp0_pmp_updt_data[0]; + pmp4cfg_writable <= cp0_pmp_updt_data[1]; + pmp4cfg_executeable <= cp0_pmp_updt_data[2]; + pmp4cfg_addr_mode[1:0] <= cp0_pmp_updt_data[4:3]; + pmp4cfg_lock <= cp0_pmp_updt_data[7]; + end + else + begin + pmp4cfg_readable <= pmp4cfg_readable; + pmp4cfg_writable <= pmp4cfg_writable; + pmp4cfg_executeable <= pmp4cfg_executeable; + pmp4cfg_addr_mode[1:0] <= pmp4cfg_addr_mode[1:0]; + pmp4cfg_lock <= pmp4cfg_lock; + end +end +assign pmp4cfg_mode[1:0] = pmp4cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp4cfg_addr_mode[1:0]; + +assign pmp_updt_pmp5cfg = pmp_csr_wen[1] && !pmp5cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp5cfg_readable <= 1'b0; + pmp5cfg_writable <= 1'b0; + pmp5cfg_executeable <= 1'b0; + pmp5cfg_addr_mode[1:0] <= 2'b0; + pmp5cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp5cfg && (!pmpteecfg_s5 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp5cfg_readable <= cp0_pmp_updt_data[8]; + pmp5cfg_writable <= cp0_pmp_updt_data[9]; + pmp5cfg_executeable <= cp0_pmp_updt_data[10]; + pmp5cfg_addr_mode[1:0] <= cp0_pmp_updt_data[12:11]; + pmp5cfg_lock <= cp0_pmp_updt_data[15]; + end + else + begin + pmp5cfg_readable <= pmp5cfg_readable; + pmp5cfg_writable <= pmp5cfg_writable; + pmp5cfg_executeable <= pmp5cfg_executeable; + pmp5cfg_addr_mode[1:0] <= pmp5cfg_addr_mode[1:0]; + pmp5cfg_lock <= pmp5cfg_lock; + end +end +assign pmp5cfg_mode[1:0] = pmp5cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp5cfg_addr_mode[1:0]; + +assign pmp_updt_pmp6cfg = pmp_csr_wen[1] && !pmp6cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp6cfg_readable <= 1'b0; + pmp6cfg_writable <= 1'b0; + pmp6cfg_executeable <= 1'b0; + pmp6cfg_addr_mode[1:0] <= 2'b0; + pmp6cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp6cfg && (!pmpteecfg_s6 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp6cfg_readable <= cp0_pmp_updt_data[16]; + pmp6cfg_writable <= cp0_pmp_updt_data[17]; + pmp6cfg_executeable <= cp0_pmp_updt_data[18]; + pmp6cfg_addr_mode[1:0] <= cp0_pmp_updt_data[20:19]; + pmp6cfg_lock <= cp0_pmp_updt_data[23]; + end + else + begin + pmp6cfg_readable <= pmp6cfg_readable; + pmp6cfg_writable <= pmp6cfg_writable; + pmp6cfg_executeable <= pmp6cfg_executeable; + pmp6cfg_addr_mode[1:0] <= pmp6cfg_addr_mode[1:0]; + pmp6cfg_lock <= pmp6cfg_lock; + end +end +assign pmp6cfg_mode[1:0] = pmp6cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp6cfg_addr_mode[1:0]; + +assign pmp_updt_pmp7cfg = pmp_csr_wen[1] && !pmp7cfg_lock; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + pmp7cfg_readable <= 1'b0; + pmp7cfg_writable <= 1'b0; + pmp7cfg_executeable <= 1'b0; + pmp7cfg_addr_mode[1:0] <= 2'b0; + pmp7cfg_lock <= 1'b0; + end + else if(pmp_updt_pmp7cfg && (!pmpteecfg_s7 || cp0_yy_secu_mode_aft_dbg)) + begin + pmp7cfg_readable <= cp0_pmp_updt_data[24]; + pmp7cfg_writable <= cp0_pmp_updt_data[25]; + pmp7cfg_executeable <= cp0_pmp_updt_data[26]; + pmp7cfg_addr_mode[1:0] <= cp0_pmp_updt_data[28:27]; + pmp7cfg_lock <= cp0_pmp_updt_data[31]; + end + else + begin + pmp7cfg_readable <= pmp7cfg_readable; + pmp7cfg_writable <= pmp7cfg_writable; + pmp7cfg_executeable <= pmp7cfg_executeable; + pmp7cfg_addr_mode[1:0] <= pmp7cfg_addr_mode[1:0]; + pmp7cfg_lock <= pmp7cfg_lock; + end +end +assign pmp7cfg_mode[1:0] = pmp7cfg_addr_mode[1:0] == 2'b10 ? 2'b00 : pmp7cfg_addr_mode[1:0]; + +//------------------------------------------------ +//pmpcfg2 register +//------------------------------------------------ +assign pmp8cfg_mode[1:0] = 2'b00; +assign regs_comp_lock8 = 1'b0; + +assign pmp9cfg_mode[1:0] = 2'b00; +assign regs_comp_lock9 = 1'b0; + +assign pmp10cfg_mode[1:0] = 2'b00; +assign regs_comp_lock10 = 1'b0; + +assign pmp11cfg_mode[1:0] = 2'b00; +assign regs_comp_lock11 = 1'b0; + +//------------------------------------------------ +//pmpcfg3 register +//------------------------------------------------ +assign pmp12cfg_mode[1:0] = 2'b00; +assign regs_comp_lock12 = 1'b0; + +assign pmp13cfg_mode[1:0] = 2'b00; +assign regs_comp_lock13 = 1'b0; + +assign pmp14cfg_mode[1:0] = 2'b00; +assign regs_comp_lock14 = 1'b0; + +assign pmp15cfg_mode[1:0] = 2'b00; +assign regs_comp_lock15 = 1'b0; + + + +assign pmpcfg0_value[31:0] = {pmp3cfg_lock,2'b0,pmp3cfg_mode[1:0],pmp3cfg_executeable,pmp3cfg_writable,pmp3cfg_readable, + pmp2cfg_lock,2'b0,pmp2cfg_mode[1:0],pmp2cfg_executeable,pmp2cfg_writable,pmp2cfg_readable, + pmp1cfg_lock,2'b0,pmp1cfg_mode[1:0],pmp1cfg_executeable,pmp1cfg_writable,pmp1cfg_readable, + pmp0cfg_lock,2'b0,pmp0cfg_mode[1:0],pmp0cfg_executeable,pmp0cfg_writable,pmp0cfg_readable}; +assign pmpcfg1_value[31:0] = {pmp7cfg_lock,2'b0,pmp7cfg_mode[1:0],pmp7cfg_executeable,pmp7cfg_writable,pmp7cfg_readable, + pmp6cfg_lock,2'b0,pmp6cfg_mode[1:0],pmp6cfg_executeable,pmp6cfg_writable,pmp6cfg_readable, + pmp5cfg_lock,2'b0,pmp5cfg_mode[1:0],pmp5cfg_executeable,pmp5cfg_writable,pmp5cfg_readable, + pmp4cfg_lock,2'b0,pmp4cfg_mode[1:0],pmp4cfg_executeable,pmp4cfg_writable,pmp4cfg_readable}; +assign pmpcfg2_value[31:0] = 32'b0; +assign pmpcfg3_value[31:0] = 32'b0; + + + + + +//========================================================== +// PMP Entry Address Register +//========================================================== +//------------------------------------------------ +//pmpaddr0 register +//------------------------------------------------ +assign pmp_updt_pmpaddr0 = pmp_csr_wen[4] && !pmpcfg0_value[7] && !(pmpcfg0_value[15] && (pmpcfg0_value[12:11] == 2'b01)) ; +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr0_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr0 && (!pmpteecfg_s0 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr0_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr0_value[ADDR_WIDTH-1:0] <= pmpaddr0_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr0_value"); @866 + +assign pmp_updt_pmpaddr1 = pmp_csr_wen[5] && !pmpcfg0_value[15] && !(pmpcfg0_value[23] && (pmpcfg0_value[20:19] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr1_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr1 && (!pmpteecfg_s1 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr1_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr1_value[ADDR_WIDTH-1:0] <= pmpaddr1_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr1_value"); @882 + +assign pmp_updt_pmpaddr2 = pmp_csr_wen[6] && !pmpcfg0_value[23] && !(pmpcfg0_value[31] && (pmpcfg0_value[28:27] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr2_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr2 && (!pmpteecfg_s2 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr2_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr2_value[ADDR_WIDTH-1:0] <= pmpaddr2_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr2_value"); @898 + +assign pmp_updt_pmpaddr3 = pmp_csr_wen[7] && !pmpcfg0_value[31] && !(pmpcfg1_value[7] && (pmpcfg1_value[4:3] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr3_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr3 && (!pmpteecfg_s3 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr3_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr3_value[ADDR_WIDTH-1:0] <= pmpaddr3_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr3_value"); @914 + +assign pmp_updt_pmpaddr4 = pmp_csr_wen[8] && !pmpcfg1_value[7] && !(pmpcfg1_value[15] && (pmpcfg1_value[12:11] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr4_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr4 && (!pmpteecfg_s4 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr4_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr4_value[ADDR_WIDTH-1:0] <= pmpaddr4_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr4_value"); @930 + +assign pmp_updt_pmpaddr5 = pmp_csr_wen[9] && !pmpcfg1_value[15] && !(pmpcfg1_value[23] && (pmpcfg1_value[20:19] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr5_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr5 && (!pmpteecfg_s5 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr5_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr5_value[ADDR_WIDTH-1:0] <= pmpaddr5_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr5_value"); @946 + +assign pmp_updt_pmpaddr6 = pmp_csr_wen[10] && !pmpcfg1_value[23] && !(pmpcfg1_value[31] && (pmpcfg1_value[28:27] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr6_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr6 && (!pmpteecfg_s6 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr6_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr6_value[ADDR_WIDTH-1:0] <= pmpaddr6_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr6_value"); @962 + +assign pmp_updt_pmpaddr7 = pmp_csr_wen[11] && !pmpcfg1_value[31] && !(pmpcfg2_value[7] && (pmpcfg2_value[4:3] == 2'b01)); +always @(posedge cpuclk or negedge cpurst_b) +begin + if(!cpurst_b) + pmpaddr7_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(pmp_updt_pmpaddr7 && (!pmpteecfg_s7 || cp0_yy_secu_mode_aft_dbg)) + pmpaddr7_value[ADDR_WIDTH-1:0] <= cp0_pmp_updt_data[ADDR_WIDTH+3:4]; + else + pmpaddr7_value[ADDR_WIDTH-1:0] <= pmpaddr7_value[ADDR_WIDTH-1:0]; +end +// &Force("output","pmpaddr7_value"); @978 + +// &Force("output","pmpaddr8_value"); @994 +assign pmpaddr8_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr9_value"); @1010 +assign pmpaddr9_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr10_value"); @1026 +assign pmpaddr10_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr11_value"); @1042 +assign pmpaddr11_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + + +// &Force("output","pmpaddr12_value"); @1059 +assign pmpaddr12_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr13_value"); @1075 +assign pmpaddr13_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr14_value"); @1091 +assign pmpaddr14_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +// &Force("output","pmpaddr15_value"); @1107 +assign pmpaddr15_value[ADDR_WIDTH-1:0] = {ADDR_WIDTH{1'b0}}; + +//========================================================== +// PMP Entry TEE Configuration Register +//========================================================== +//------------------------------------------------ +//pmpteecfg[0] register +//------------------------------------------------ +assign pmpteecfg_s0 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[1] register +//------------------------------------------------ +assign pmpteecfg_s1 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[2] register +//------------------------------------------------ +assign pmpteecfg_s2 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[3] register +//------------------------------------------------ +assign pmpteecfg_s3 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[4] register +//------------------------------------------------ +assign pmpteecfg_s4 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[5] register +//------------------------------------------------ +assign pmpteecfg_s5 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[6] register +//------------------------------------------------ +assign pmpteecfg_s6 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[7] register +//------------------------------------------------ +assign pmpteecfg_s7 = 1'b0; + +//------------------------------------------------ +//pmpteecfg[8] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[9] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[10] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[11] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[12] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[13] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[14] register +//------------------------------------------------ + +//------------------------------------------------ +//pmpteecfg[15] register +//------------------------------------------------ + +// &Force("nonport","pmpteecfg_value"); @1504 +assign pmpaddr0_low[4:0] = pmp0cfg_mode[1] ? {pmpaddr0_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr1_low[4:0] = pmp1cfg_mode[1] ? {pmpaddr1_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr2_low[4:0] = pmp2cfg_mode[1] ? {pmpaddr2_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr3_low[4:0] = pmp3cfg_mode[1] ? {pmpaddr3_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr4_low[4:0] = pmp4cfg_mode[1] ? {pmpaddr4_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr5_low[4:0] = pmp5cfg_mode[1] ? {pmpaddr5_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr6_low[4:0] = pmp6cfg_mode[1] ? {pmpaddr6_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr7_low[4:0] = pmp7cfg_mode[1] ? {pmpaddr7_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr8_low[4:0] = pmp8cfg_mode[1] ? {pmpaddr8_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr9_low[4:0] = pmp9cfg_mode[1] ? {pmpaddr9_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr10_low[4:0] = pmp10cfg_mode[1] ? {pmpaddr10_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr11_low[4:0] = pmp11cfg_mode[1] ? {pmpaddr11_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr12_low[4:0] = pmp12cfg_mode[1] ? {pmpaddr12_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr13_low[4:0] = pmp13cfg_mode[1] ? {pmpaddr13_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr14_low[4:0] = pmp14cfg_mode[1] ? {pmpaddr14_value[0], 4'hf} : {5{1'b0}}; +assign pmpaddr15_low[4:0] = pmp15cfg_mode[1] ? {pmpaddr15_value[0], 4'hf} : {5{1'b0}}; + + +// &Force("bus", "pmp_csr_wen", 19, 0); @1620 +assign pmp_cp0_data[31:0] = {32{cp0_pmp_csr_sel[0]}} & pmpcfg0_value[31:0] + | {32{cp0_pmp_csr_sel[1]}} & pmpcfg1_value[31:0] + | {32{cp0_pmp_csr_sel[2]}} & pmpcfg2_value[31:0] + | {32{cp0_pmp_csr_sel[3]}} & pmpcfg3_value[31:0] + | {32{cp0_pmp_csr_sel[4]}} & {{2{1'b0}}, pmpaddr0_value[ADDR_WIDTH-1:1], pmpaddr0_low[4:0]} + | {32{cp0_pmp_csr_sel[5]}} & {{2{1'b0}}, pmpaddr1_value[ADDR_WIDTH-1:1], pmpaddr1_low[4:0]} + | {32{cp0_pmp_csr_sel[6]}} & {{2{1'b0}}, pmpaddr2_value[ADDR_WIDTH-1:1], pmpaddr2_low[4:0]} + | {32{cp0_pmp_csr_sel[7]}} & {{2{1'b0}}, pmpaddr3_value[ADDR_WIDTH-1:1], pmpaddr3_low[4:0]} + | {32{cp0_pmp_csr_sel[8]}} & {{2{1'b0}}, pmpaddr4_value[ADDR_WIDTH-1:1], pmpaddr4_low[4:0]} + | {32{cp0_pmp_csr_sel[9]}} & {{2{1'b0}}, pmpaddr5_value[ADDR_WIDTH-1:1], pmpaddr5_low[4:0]} + | {32{cp0_pmp_csr_sel[10]}} & {{2{1'b0}}, pmpaddr6_value[ADDR_WIDTH-1:1], pmpaddr6_low[4:0]} + | {32{cp0_pmp_csr_sel[11]}} & {{2{1'b0}}, pmpaddr7_value[ADDR_WIDTH-1:1], pmpaddr7_low[4:0]} + | {32{cp0_pmp_csr_sel[12]}} & {{2{1'b0}}, pmpaddr8_value[ADDR_WIDTH-1:1], pmpaddr8_low[4:0]} + | {32{cp0_pmp_csr_sel[13]}} & {{2{1'b0}}, pmpaddr9_value[ADDR_WIDTH-1:1], pmpaddr9_low[4:0]} + | {32{cp0_pmp_csr_sel[14]}} & {{2{1'b0}}, pmpaddr10_value[ADDR_WIDTH-1:1], pmpaddr10_low[4:0]} + | {32{cp0_pmp_csr_sel[15]}} & {{2{1'b0}}, pmpaddr11_value[ADDR_WIDTH-1:1], pmpaddr11_low[4:0]} + | {32{cp0_pmp_csr_sel[16]}} & {{2{1'b0}}, pmpaddr12_value[ADDR_WIDTH-1:1], pmpaddr12_low[4:0]} + | {32{cp0_pmp_csr_sel[17]}} & {{2{1'b0}}, pmpaddr13_value[ADDR_WIDTH-1:1], pmpaddr13_low[4:0]} + | {32{cp0_pmp_csr_sel[18]}} & {{2{1'b0}}, pmpaddr14_value[ADDR_WIDTH-1:1], pmpaddr14_low[4:0]} + | {32{cp0_pmp_csr_sel[19]}} & {{2{1'b0}}, pmpaddr15_value[ADDR_WIDTH-1:1], pmpaddr15_low[4:0]}; + +// &ModuleEnd; @1643 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_top.v new file mode 100644 index 0000000000000000000000000000000000000000..9a1de2454479ebc2b597f34d7f9f131959464101 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmp/rtl/pa_pmp_top.v @@ -0,0 +1,642 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_pmp_top( + cp0_pmp_csr_sel, + cp0_pmp_csr_wen, + cp0_pmp_icg_en, + cp0_pmp_mstatus_mpp, + cp0_pmp_mstatus_mprv, + cp0_pmp_updt_data, + cp0_yy_clk_en, + cp0_yy_mach_mode, + cpurst_b, + forever_cpuclk, + ifu_pmp_addr, + ifu_pmp_machine_mode, + lsu_pmp_addr, + lsu_pmp_write, + pad_yy_icg_scan_en, + pmp_cp0_data, + pmp_ifu_acc_deny, + pmp_lsu_acc_deny +); + +// &Ports; @25 +input [19:0] cp0_pmp_csr_sel; +input cp0_pmp_csr_wen; +input cp0_pmp_icg_en; +input [1 :0] cp0_pmp_mstatus_mpp; +input cp0_pmp_mstatus_mprv; +input [31:0] cp0_pmp_updt_data; +input cp0_yy_clk_en; +input cp0_yy_mach_mode; +input cpurst_b; +input forever_cpuclk; +input [31:0] ifu_pmp_addr; +input ifu_pmp_machine_mode; +input [31:0] lsu_pmp_addr; +input lsu_pmp_write; +input pad_yy_icg_scan_en; +output [31:0] pmp_cp0_data; +output pmp_ifu_acc_deny; +output pmp_lsu_acc_deny; + +// &Regs; @26 + +// &Wires; @27 +wire [19:0] cp0_pmp_csr_sel; +wire cp0_pmp_csr_wen; +wire cp0_pmp_icg_en; +wire [1 :0] cp0_pmp_mstatus_mpp; +wire cp0_pmp_mstatus_mprv; +wire [31:0] cp0_pmp_updt_data; +wire cp0_yy_clk_en; +wire cp0_yy_mach_mode; +wire cp0_yy_secu_mode_aft_dbg; +wire cpuclk; +wire cpurst_b; +wire forever_cpuclk; +wire [7 :0] ifu_addr_ge_bottom; +wire [31:0] ifu_pmp_addr; +wire ifu_pmp_machine_mode; +wire [15:0] lsu_4k_cross; +wire [7 :0] lsu_addr_ge_bottom; +wire [31:0] lsu_pmp_addr; +wire lsu_pmp_write; +wire pad_yy_icg_scan_en; +wire [31:0] pmp_cp0_data; +wire [19:0] pmp_csr_wen; +wire [15:0] pmp_entry_lock; +wire pmp_ifu_acc_deny; +wire [7 :0] pmp_ifu_hit; +wire pmp_lsu_acc_deny; +wire [7 :0] pmp_lsu_hit; +wire [25:0] pmpaddr0_value; +wire [25:0] pmpaddr1_value; +wire [25:0] pmpaddr2_value; +wire [25:0] pmpaddr3_value; +wire [25:0] pmpaddr4_value; +wire [25:0] pmpaddr5_value; +wire [25:0] pmpaddr6_value; +wire [25:0] pmpaddr7_value; +wire [1 :0] regs_comp_addr_mode0; +wire [1 :0] regs_comp_addr_mode1; +wire [1 :0] regs_comp_addr_mode2; +wire [1 :0] regs_comp_addr_mode3; +wire [1 :0] regs_comp_addr_mode4; +wire [1 :0] regs_comp_addr_mode5; +wire [1 :0] regs_comp_addr_mode6; +wire [1 :0] regs_comp_addr_mode7; +wire regs_comp_excut0; +wire regs_comp_excut1; +wire regs_comp_excut2; +wire regs_comp_excut3; +wire regs_comp_excut4; +wire regs_comp_excut5; +wire regs_comp_excut6; +wire regs_comp_excut7; +wire regs_comp_lock0; +wire regs_comp_lock1; +wire regs_comp_lock10; +wire regs_comp_lock11; +wire regs_comp_lock12; +wire regs_comp_lock13; +wire regs_comp_lock14; +wire regs_comp_lock15; +wire regs_comp_lock2; +wire regs_comp_lock3; +wire regs_comp_lock4; +wire regs_comp_lock5; +wire regs_comp_lock6; +wire regs_comp_lock7; +wire regs_comp_lock8; +wire regs_comp_lock9; +wire regs_comp_read0; +wire regs_comp_read1; +wire regs_comp_read2; +wire regs_comp_read3; +wire regs_comp_read4; +wire regs_comp_read5; +wire regs_comp_read6; +wire regs_comp_read7; +wire regs_comp_write0; +wire regs_comp_write1; +wire regs_comp_write2; +wire regs_comp_write3; +wire regs_comp_write4; +wire regs_comp_write5; +wire regs_comp_write6; +wire regs_comp_write7; +wire wr_pmp_regs; + + + + +assign pmp_csr_wen[19:0] = cp0_pmp_csr_sel[19:0] & {20{cp0_pmp_csr_wen}}; + +assign cp0_yy_secu_mode_aft_dbg = 1'b0; + +assign wr_pmp_regs = |pmp_csr_wen[19:0]; +// &Instance("gated_clk_cell", "x_pmp_gated_clk"); @49 +gated_clk_cell x_pmp_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (cpuclk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (wr_pmp_regs ), + .module_en (cp0_pmp_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect( @50 +// .clk_in (forever_cpuclk), @51 +// .global_en (cp0_yy_clk_en ), @52 +// .module_en (cp0_pmp_icg_en), @53 +// .local_en (wr_pmp_regs ), @54 +// .external_en (1'b0 ), @55 +// .clk_out (cpuclk ), @56 +// ); @57 + +// &Instance("pa_pmp_enc"); @59 +pa_pmp_enc x_pa_pmp_enc ( + .cp0_pmp_mstatus_mpp (cp0_pmp_mstatus_mpp ), + .cp0_pmp_mstatus_mprv (cp0_pmp_mstatus_mprv), + .cp0_yy_mach_mode (cp0_yy_mach_mode ), + .ifu_pmp_machine_mode (ifu_pmp_machine_mode), + .lsu_4k_cross (lsu_4k_cross ), + .lsu_pmp_write (lsu_pmp_write ), + .pmp_entry_lock (pmp_entry_lock ), + .pmp_ifu_acc_deny (pmp_ifu_acc_deny ), + .pmp_ifu_hit (pmp_ifu_hit ), + .pmp_lsu_acc_deny (pmp_lsu_acc_deny ), + .pmp_lsu_hit (pmp_lsu_hit ), + .regs_comp_excut0 (regs_comp_excut0 ), + .regs_comp_excut1 (regs_comp_excut1 ), + .regs_comp_excut2 (regs_comp_excut2 ), + .regs_comp_excut3 (regs_comp_excut3 ), + .regs_comp_excut4 (regs_comp_excut4 ), + .regs_comp_excut5 (regs_comp_excut5 ), + .regs_comp_excut6 (regs_comp_excut6 ), + .regs_comp_excut7 (regs_comp_excut7 ), + .regs_comp_lock0 (regs_comp_lock0 ), + .regs_comp_lock1 (regs_comp_lock1 ), + .regs_comp_lock10 (regs_comp_lock10 ), + .regs_comp_lock11 (regs_comp_lock11 ), + .regs_comp_lock12 (regs_comp_lock12 ), + .regs_comp_lock13 (regs_comp_lock13 ), + .regs_comp_lock14 (regs_comp_lock14 ), + .regs_comp_lock15 (regs_comp_lock15 ), + .regs_comp_lock2 (regs_comp_lock2 ), + .regs_comp_lock3 (regs_comp_lock3 ), + .regs_comp_lock4 (regs_comp_lock4 ), + .regs_comp_lock5 (regs_comp_lock5 ), + .regs_comp_lock6 (regs_comp_lock6 ), + .regs_comp_lock7 (regs_comp_lock7 ), + .regs_comp_lock8 (regs_comp_lock8 ), + .regs_comp_lock9 (regs_comp_lock9 ), + .regs_comp_read0 (regs_comp_read0 ), + .regs_comp_read1 (regs_comp_read1 ), + .regs_comp_read2 (regs_comp_read2 ), + .regs_comp_read3 (regs_comp_read3 ), + .regs_comp_read4 (regs_comp_read4 ), + .regs_comp_read5 (regs_comp_read5 ), + .regs_comp_read6 (regs_comp_read6 ), + .regs_comp_read7 (regs_comp_read7 ), + .regs_comp_write0 (regs_comp_write0 ), + .regs_comp_write1 (regs_comp_write1 ), + .regs_comp_write2 (regs_comp_write2 ), + .regs_comp_write3 (regs_comp_write3 ), + .regs_comp_write4 (regs_comp_write4 ), + .regs_comp_write5 (regs_comp_write5 ), + .regs_comp_write6 (regs_comp_write6 ), + .regs_comp_write7 (regs_comp_write7 ) +); + +// &Instance("pa_pmp_regs"); @60 +pa_pmp_regs x_pa_pmp_regs ( + .cp0_pmp_csr_sel (cp0_pmp_csr_sel ), + .cp0_pmp_updt_data (cp0_pmp_updt_data ), + .cp0_yy_secu_mode_aft_dbg (cp0_yy_secu_mode_aft_dbg), + .cpuclk (cpuclk ), + .cpurst_b (cpurst_b ), + .pmp_cp0_data (pmp_cp0_data ), + .pmp_csr_wen (pmp_csr_wen ), + .pmpaddr0_value (pmpaddr0_value ), + .pmpaddr1_value (pmpaddr1_value ), + .pmpaddr2_value (pmpaddr2_value ), + .pmpaddr3_value (pmpaddr3_value ), + .pmpaddr4_value (pmpaddr4_value ), + .pmpaddr5_value (pmpaddr5_value ), + .pmpaddr6_value (pmpaddr6_value ), + .pmpaddr7_value (pmpaddr7_value ), + .regs_comp_addr_mode0 (regs_comp_addr_mode0 ), + .regs_comp_addr_mode1 (regs_comp_addr_mode1 ), + .regs_comp_addr_mode2 (regs_comp_addr_mode2 ), + .regs_comp_addr_mode3 (regs_comp_addr_mode3 ), + .regs_comp_addr_mode4 (regs_comp_addr_mode4 ), + .regs_comp_addr_mode5 (regs_comp_addr_mode5 ), + .regs_comp_addr_mode6 (regs_comp_addr_mode6 ), + .regs_comp_addr_mode7 (regs_comp_addr_mode7 ), + .regs_comp_excut0 (regs_comp_excut0 ), + .regs_comp_excut1 (regs_comp_excut1 ), + .regs_comp_excut2 (regs_comp_excut2 ), + .regs_comp_excut3 (regs_comp_excut3 ), + .regs_comp_excut4 (regs_comp_excut4 ), + .regs_comp_excut5 (regs_comp_excut5 ), + .regs_comp_excut6 (regs_comp_excut6 ), + .regs_comp_excut7 (regs_comp_excut7 ), + .regs_comp_lock0 (regs_comp_lock0 ), + .regs_comp_lock1 (regs_comp_lock1 ), + .regs_comp_lock10 (regs_comp_lock10 ), + .regs_comp_lock11 (regs_comp_lock11 ), + .regs_comp_lock12 (regs_comp_lock12 ), + .regs_comp_lock13 (regs_comp_lock13 ), + .regs_comp_lock14 (regs_comp_lock14 ), + .regs_comp_lock15 (regs_comp_lock15 ), + .regs_comp_lock2 (regs_comp_lock2 ), + .regs_comp_lock3 (regs_comp_lock3 ), + .regs_comp_lock4 (regs_comp_lock4 ), + .regs_comp_lock5 (regs_comp_lock5 ), + .regs_comp_lock6 (regs_comp_lock6 ), + .regs_comp_lock7 (regs_comp_lock7 ), + .regs_comp_lock8 (regs_comp_lock8 ), + .regs_comp_lock9 (regs_comp_lock9 ), + .regs_comp_read0 (regs_comp_read0 ), + .regs_comp_read1 (regs_comp_read1 ), + .regs_comp_read2 (regs_comp_read2 ), + .regs_comp_read3 (regs_comp_read3 ), + .regs_comp_read4 (regs_comp_read4 ), + .regs_comp_read5 (regs_comp_read5 ), + .regs_comp_read6 (regs_comp_read6 ), + .regs_comp_read7 (regs_comp_read7 ), + .regs_comp_write0 (regs_comp_write0 ), + .regs_comp_write1 (regs_comp_write1 ), + .regs_comp_write2 (regs_comp_write2 ), + .regs_comp_write3 (regs_comp_write3 ), + .regs_comp_write4 (regs_comp_write4 ), + .regs_comp_write5 (regs_comp_write5 ), + .regs_comp_write6 (regs_comp_write6 ), + .regs_comp_write7 (regs_comp_write7 ) +); + + +// &Force("bus","ifu_pmp_addr",31,0); @62 +// &Force("bus","lsu_pmp_addr",31,0); @63 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_0"); @66 +pa_pmp_comp_hit x_pa_pmp_comp_hit_0 ( + .addr_match_mode (regs_comp_addr_mode0[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (1'b1 ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[0] ), + .lsu_4k_cross (lsu_4k_cross[0] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (1'b1 ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[0] ), + .pmp_ifu_hit (pmp_ifu_hit[0] ), + .pmp_lsu_hit (pmp_lsu_hit[0] ), + .pmpaddr (pmpaddr0_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode0[1:0]), @67 +// .pmpaddr (pmpaddr0_value[25:0] ), @68 +// .ifu_addr_ge_bottom (1'b1 ), @69 +// .lsu_addr_ge_bottom (1'b1 ), @70 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @71 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @72 +// .pmp_ifu_hit (pmp_ifu_hit[0] ), @73 +// .pmp_lsu_hit (pmp_lsu_hit[0] ), @74 +// .lsu_4k_cross (lsu_4k_cross[0] ), @75 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[0] ), @76 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[0] ) @77 +// ); @78 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_1"); @82 +pa_pmp_comp_hit x_pa_pmp_comp_hit_1 ( + .addr_match_mode (regs_comp_addr_mode1[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[0] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[1] ), + .lsu_4k_cross (lsu_4k_cross[1] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[0] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[1] ), + .pmp_ifu_hit (pmp_ifu_hit[1] ), + .pmp_lsu_hit (pmp_lsu_hit[1] ), + .pmpaddr (pmpaddr1_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode1[1:0]), @83 +// .pmpaddr (pmpaddr1_value[25:0] ), @84 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[0] ), @85 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[0] ), @86 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @87 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @88 +// .lsu_4k_cross (lsu_4k_cross[1] ), @89 +// .pmp_ifu_hit (pmp_ifu_hit[1] ), @90 +// .pmp_lsu_hit (pmp_lsu_hit[1] ), @91 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[1] ), @92 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[1] ) @93 +// ); @94 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_2"); @98 +pa_pmp_comp_hit x_pa_pmp_comp_hit_2 ( + .addr_match_mode (regs_comp_addr_mode2[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[1] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[2] ), + .lsu_4k_cross (lsu_4k_cross[2] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[1] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[2] ), + .pmp_ifu_hit (pmp_ifu_hit[2] ), + .pmp_lsu_hit (pmp_lsu_hit[2] ), + .pmpaddr (pmpaddr2_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode2[1:0]), @99 +// .pmpaddr (pmpaddr2_value[25:0] ), @100 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[1] ), @101 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[1] ), @102 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @103 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @104 +// .lsu_4k_cross (lsu_4k_cross[2] ), @105 +// .pmp_ifu_hit (pmp_ifu_hit[2] ), @106 +// .pmp_lsu_hit (pmp_lsu_hit[2] ), @107 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[2] ), @108 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[2] ) @109 +// ); @110 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_3"); @114 +pa_pmp_comp_hit x_pa_pmp_comp_hit_3 ( + .addr_match_mode (regs_comp_addr_mode3[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[2] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[3] ), + .lsu_4k_cross (lsu_4k_cross[3] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[2] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[3] ), + .pmp_ifu_hit (pmp_ifu_hit[3] ), + .pmp_lsu_hit (pmp_lsu_hit[3] ), + .pmpaddr (pmpaddr3_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode3[1:0]), @115 +// .pmpaddr (pmpaddr3_value[25:0] ), @116 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[2] ), @117 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[2] ), @118 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @119 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @120 +// .lsu_4k_cross (lsu_4k_cross[3] ), @121 +// .pmp_ifu_hit (pmp_ifu_hit[3] ), @122 +// .pmp_lsu_hit (pmp_lsu_hit[3] ), @123 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[3] ), @124 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[3] ) @125 +// ); @126 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_4"); @130 +pa_pmp_comp_hit x_pa_pmp_comp_hit_4 ( + .addr_match_mode (regs_comp_addr_mode4[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[3] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[4] ), + .lsu_4k_cross (lsu_4k_cross[4] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[3] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[4] ), + .pmp_ifu_hit (pmp_ifu_hit[4] ), + .pmp_lsu_hit (pmp_lsu_hit[4] ), + .pmpaddr (pmpaddr4_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode4[1:0]), @131 +// .pmpaddr (pmpaddr4_value[25:0] ), @132 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[3] ), @133 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[3] ), @134 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @135 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @136 +// .lsu_4k_cross (lsu_4k_cross[4] ), @137 +// .pmp_ifu_hit (pmp_ifu_hit[4] ), @138 +// .pmp_lsu_hit (pmp_lsu_hit[4] ), @139 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[4] ), @140 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[4] ) @141 +// ); @142 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_5"); @146 +pa_pmp_comp_hit x_pa_pmp_comp_hit_5 ( + .addr_match_mode (regs_comp_addr_mode5[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[4] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[5] ), + .lsu_4k_cross (lsu_4k_cross[5] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[4] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[5] ), + .pmp_ifu_hit (pmp_ifu_hit[5] ), + .pmp_lsu_hit (pmp_lsu_hit[5] ), + .pmpaddr (pmpaddr5_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode5[1:0]), @147 +// .pmpaddr (pmpaddr5_value[25:0] ), @148 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[4] ), @149 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[4] ), @150 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @151 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @152 +// .lsu_4k_cross (lsu_4k_cross[5] ), @153 +// .pmp_ifu_hit (pmp_ifu_hit[5] ), @154 +// .pmp_lsu_hit (pmp_lsu_hit[5] ), @155 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[5] ), @156 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[5] ) @157 +// ); @158 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_6"); @162 +pa_pmp_comp_hit x_pa_pmp_comp_hit_6 ( + .addr_match_mode (regs_comp_addr_mode6[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[5] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[6] ), + .lsu_4k_cross (lsu_4k_cross[6] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[5] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[6] ), + .pmp_ifu_hit (pmp_ifu_hit[6] ), + .pmp_lsu_hit (pmp_lsu_hit[6] ), + .pmpaddr (pmpaddr6_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode6[1:0]), @163 +// .pmpaddr (pmpaddr6_value[25:0] ), @164 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[5] ), @165 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[5] ), @166 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @167 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @168 +// .lsu_4k_cross (lsu_4k_cross[6] ), @169 +// .pmp_ifu_hit (pmp_ifu_hit[6] ), @170 +// .pmp_lsu_hit (pmp_lsu_hit[6] ), @171 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[6] ), @172 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[6] ) @173 +// ); @174 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_7"); @178 +pa_pmp_comp_hit x_pa_pmp_comp_hit_7 ( + .addr_match_mode (regs_comp_addr_mode7[1:0]), + .ifu_acc_addr (ifu_pmp_addr[31:0] ), + .ifu_addr_ge_bottom (ifu_addr_ge_bottom[6] ), + .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[7] ), + .lsu_4k_cross (lsu_4k_cross[7] ), + .lsu_acc_addr (lsu_pmp_addr[31:0] ), + .lsu_addr_ge_bottom (lsu_addr_ge_bottom[6] ), + .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[7] ), + .pmp_ifu_hit (pmp_ifu_hit[7] ), + .pmp_lsu_hit (pmp_lsu_hit[7] ), + .pmpaddr (pmpaddr7_value[25:0] ) +); + +// &Connect(.addr_match_mode (regs_comp_addr_mode7[1:0]), @179 +// .pmpaddr (pmpaddr7_value[25:0] ), @180 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[6] ), @181 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[6] ), @182 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @183 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @184 +// .lsu_4k_cross (lsu_4k_cross[7] ), @185 +// .pmp_ifu_hit (pmp_ifu_hit[7] ), @186 +// .pmp_lsu_hit (pmp_lsu_hit[7] ), @187 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[7] ), @188 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[7] ) @189 +// ); @190 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_8"); @194 +// &Connect(.addr_match_mode (regs_comp_addr_mode8[1:0]), @195 +// .pmpaddr (pmpaddr8_value[25:0] ), @196 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[7] ), @197 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[7] ), @198 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @199 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @200 +// .lsu_4k_cross (lsu_4k_cross[8] ), @201 +// .pmp_ifu_hit (pmp_ifu_hit[8] ), @202 +// .pmp_lsu_hit (pmp_lsu_hit[8] ), @203 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[8] ), @204 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[8] ) @205 +// ); @206 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_9"); @210 +// &Connect(.addr_match_mode (regs_comp_addr_mode9[1:0]), @211 +// .pmpaddr (pmpaddr9_value[25:0] ), @212 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[8] ), @213 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[8] ), @214 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @215 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @216 +// .lsu_4k_cross (lsu_4k_cross[9] ), @217 +// .pmp_ifu_hit (pmp_ifu_hit[9] ), @218 +// .pmp_lsu_hit (pmp_lsu_hit[9] ), @219 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[9] ), @220 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[9] ) @221 +// ); @222 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_10"); @226 +// &Connect(.addr_match_mode (regs_comp_addr_mode10[1:0]), @227 +// .pmpaddr (pmpaddr10_value[25:0] ), @228 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[9] ), @229 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[9] ), @230 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @231 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @232 +// .lsu_4k_cross (lsu_4k_cross[10] ), @233 +// .pmp_ifu_hit (pmp_ifu_hit[10] ), @234 +// .pmp_lsu_hit (pmp_lsu_hit[10] ), @235 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[10] ), @236 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[10] ) @237 +// ); @238 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_11"); @242 +// &Connect(.addr_match_mode (regs_comp_addr_mode11[1:0]), @243 +// .pmpaddr (pmpaddr11_value[25:0] ), @244 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[10] ), @245 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[10] ), @246 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @247 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @248 +// .lsu_4k_cross (lsu_4k_cross[11] ), @249 +// .pmp_ifu_hit (pmp_ifu_hit[11] ), @250 +// .pmp_lsu_hit (pmp_lsu_hit[11] ), @251 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[11] ), @252 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[11] ) @253 +// ); @254 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_12"); @258 +// &Connect(.addr_match_mode (regs_comp_addr_mode12[1:0]), @259 +// .pmpaddr (pmpaddr12_value[25:0] ), @260 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[11] ), @261 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[11] ), @262 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @263 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @264 +// .lsu_4k_cross (lsu_4k_cross[12] ), @265 +// .pmp_ifu_hit (pmp_ifu_hit[12] ), @266 +// .pmp_lsu_hit (pmp_lsu_hit[12] ), @267 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[12] ), @268 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[12] ) @269 +// ); @270 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_13"); @274 +// &Connect(.addr_match_mode (regs_comp_addr_mode13[1:0]), @275 +// .pmpaddr (pmpaddr13_value[25:0] ), @276 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[12] ), @277 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[12] ), @278 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @279 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @280 +// .lsu_4k_cross (lsu_4k_cross[13] ), @281 +// .pmp_ifu_hit (pmp_ifu_hit[13] ), @282 +// .pmp_lsu_hit (pmp_lsu_hit[13] ), @283 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[13] ), @284 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[13] ) @285 +// ); @286 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_14"); @290 +// &Connect(.addr_match_mode (regs_comp_addr_mode14[1:0]), @291 +// .pmpaddr (pmpaddr14_value[25:0] ), @292 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[13] ), @293 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[13] ), @294 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @295 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @296 +// .lsu_4k_cross (lsu_4k_cross[14] ), @297 +// .pmp_ifu_hit (pmp_ifu_hit[14] ), @298 +// .pmp_lsu_hit (pmp_lsu_hit[14] ), @299 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[14] ), @300 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[14] ) @301 +// ); @302 + +// &Instance("pa_pmp_comp_hit", "x_pa_pmp_comp_hit_15"); @306 +// &Connect(.addr_match_mode (regs_comp_addr_mode15[1:0]), @307 +// .pmpaddr (pmpaddr15_value[25:0] ), @308 +// .ifu_addr_ge_bottom (ifu_addr_ge_bottom[14] ), @309 +// .lsu_addr_ge_bottom (lsu_addr_ge_bottom[14] ), @310 +// .ifu_acc_addr (ifu_pmp_addr[31:0] ), @311 +// .lsu_acc_addr (lsu_pmp_addr[31:0] ), @312 +// .lsu_4k_cross (lsu_4k_cross[15] ), @313 +// .pmp_ifu_hit (pmp_ifu_hit[15] ), @314 +// .pmp_lsu_hit (pmp_lsu_hit[15] ), @315 +// .ifu_addr_ge_pmpaddr (ifu_addr_ge_bottom[15] ), @316 +// .lsu_addr_ge_pmpaddr (lsu_addr_ge_bottom[15] ) @317 +// ); @318 + +assign lsu_4k_cross[15:12] = 4'b0; + assign lsu_4k_cross[11:8] = 4'b0; +// &Force("nonport", "pmp_entry_lock"); @334 + + +// &ModuleEnd; @366 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_cnt.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_cnt.v new file mode 100644 index 0000000000000000000000000000000000000000..1544596a758b12331aa593939bca38d0f2db2cc4 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_cnt.v @@ -0,0 +1,109 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_hpcp_cnt( + clk_en, + cnt_adder, + cnt_en, + cnt_hwen, + cnt_output, + cnt_wen, + cp0_hpcp_icg_en, + cpurst_b, + forever_cpuclk, + hpcp_wdata, + pad_yy_icg_scan_en +); + +// &Ports; @23 +input clk_en; +input cnt_adder; +input cnt_en; +input cnt_hwen; +input cnt_wen; +input cp0_hpcp_icg_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] hpcp_wdata; +input pad_yy_icg_scan_en; +output [63:0] cnt_output; + +// &Regs; @24 +reg [63:0] counter; + +// &Wires @25 +wire clk_en; +wire cnt_adder; +wire cnt_clk; +wire cnt_en; +wire cnt_hwen; +wire [63:0] cnt_output; +wire cnt_wen; +wire [63:0] counter_adder; +wire cp0_hpcp_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire [31:0] hpcp_wdata; +wire pad_yy_icg_scan_en; + + +//========================================================== +// Instance of Gated Cell +//========================================================== +// &Instance("gated_clk_cell", "x_gated_clk"); @30 +gated_clk_cell x_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (cnt_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (clk_en ), + .module_en (cp0_hpcp_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @31 +// .external_en (1'b0), @32 +// .global_en (1'b1), @33 +// .module_en (cp0_hpcp_icg_en), @34 +// .local_en (clk_en), @35 +// .clk_out (cnt_clk)); @36 + +//========================================================== +// Implementation of counter +//========================================================== +always @(posedge cnt_clk or negedge cpurst_b) +begin + if(!cpurst_b) + counter[63:0] <= 64'b0; + else if(cnt_wen) + counter[63:0] <= {counter[63:32], hpcp_wdata[31:0]}; + else if(cnt_hwen) + counter[63:0] <= {hpcp_wdata[31:0], counter[31:0]}; + else if(cnt_en) //if gateclk is not immplented + counter[63:0] <= counter_adder[63:0]; + else + counter[63:0] <= counter[63:0]; +end + +assign counter_adder[63:0] = counter[63:0] + {63'b0, cnt_adder}; + +//output +assign cnt_output[63:0] = counter[63:0]; + +// &ModuleEnd; @60 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_event.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_event.v new file mode 100644 index 0000000000000000000000000000000000000000..54276213d8b249fe8bbef0a69068738415312a00 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_event.v @@ -0,0 +1,94 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_hpcp_event( + clk_en, + cnt_output, + cnt_wen, + cp0_hpcp_icg_en, + cpurst_b, + forever_cpuclk, + hpcp_wdata, + pad_yy_icg_scan_en +); + +// &Ports; @23 +input clk_en; +input cnt_wen; +input cp0_hpcp_icg_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] hpcp_wdata; +input pad_yy_icg_scan_en; +output [31:0] cnt_output; + +// &Regs; @24 +reg [4 :0] counter; + +// &Wires @25 +wire clk_en; +wire cnt_clk; +wire [31:0] cnt_output; +wire cnt_wen; +wire cp0_hpcp_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire [31:0] hpcp_wdata; +wire pad_yy_icg_scan_en; + + +// &Force("bus","hpcp_wdata",31,0); @27 +//========================================================== +// Instance of Gated Cell +//========================================================== +// &Instance("gated_clk_cell", "x_gated_clk"); @31 +gated_clk_cell x_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (cnt_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (clk_en ), + .module_en (cp0_hpcp_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @32 +// .external_en (1'b0), @33 +// .global_en (1'b1), @34 +// .module_en (cp0_hpcp_icg_en), @35 +// .local_en (clk_en), @36 +// .clk_out (cnt_clk)); @37 + +//========================================================== +// Implementation of counter +//========================================================== +always @(posedge cnt_clk or negedge cpurst_b) +begin + if(!cpurst_b) + counter[4:0] <= 5'b0; + else if(cnt_wen) + counter[4:0] <= hpcp_wdata[4:0]; + else + counter[4:0] <= counter[4:0]; +end + +//output +assign cnt_output[31:0] = {27'b0, counter[4:0]}; + +// &ModuleEnd; @55 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_top.v new file mode 100644 index 0000000000000000000000000000000000000000..ce1733834ac92ab40dcba149ad2e1ea66fe153cb --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/pmu/rtl/pa_hpcp_top.v @@ -0,0 +1,1203 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_hpcp_top( + cp0_hpcp_icg_en, + cp0_hpcp_index, + cp0_hpcp_pmdm, + cp0_hpcp_pmdu, + cp0_hpcp_wdata, + cp0_hpcp_wreg, + cp0_yy_priv_mode, + cpurst_b, + dtu_hpcp_dcsr_stopcount, + forever_cpuclk, + hpcp_cp0_data, + ifu_hpcp_icache_access, + ifu_hpcp_icache_miss, + iu_hpcp_inst_bht_mispred, + iu_hpcp_inst_condbr, + iu_hpcp_inst_condbr_gate, + lsu_hpcp_cache_read_access, + lsu_hpcp_cache_read_access_gate, + lsu_hpcp_cache_read_miss, + lsu_hpcp_cache_read_miss_gate, + lsu_hpcp_cache_write_access, + lsu_hpcp_cache_write_access_gate, + lsu_hpcp_cache_write_miss, + lsu_hpcp_cache_write_miss_gate, + lsu_hpcp_inst_store, + lsu_hpcp_inst_store_gate, + pad_yy_icg_scan_en, + rtu_hpcp_retire_inst_vld, + rtu_yy_xx_dbgon, + sysio_hpcp_time +); + +// &Ports; @23 +input cp0_hpcp_icg_en; +input [11:0] cp0_hpcp_index; +input cp0_hpcp_pmdm; +input cp0_hpcp_pmdu; +input [31:0] cp0_hpcp_wdata; +input cp0_hpcp_wreg; +input [1 :0] cp0_yy_priv_mode; +input cpurst_b; +input dtu_hpcp_dcsr_stopcount; +input forever_cpuclk; +input ifu_hpcp_icache_access; +input ifu_hpcp_icache_miss; +input iu_hpcp_inst_bht_mispred; +input iu_hpcp_inst_condbr; +input iu_hpcp_inst_condbr_gate; +input lsu_hpcp_cache_read_access; +input lsu_hpcp_cache_read_access_gate; +input lsu_hpcp_cache_read_miss; +input lsu_hpcp_cache_read_miss_gate; +input lsu_hpcp_cache_write_access; +input lsu_hpcp_cache_write_access_gate; +input lsu_hpcp_cache_write_miss; +input lsu_hpcp_cache_write_miss_gate; +input lsu_hpcp_inst_store; +input lsu_hpcp_inst_store_gate; +input pad_yy_icg_scan_en; +input rtu_hpcp_retire_inst_vld; +input rtu_yy_xx_dbgon; +input [63:0] sysio_hpcp_time; +output [31:0] hpcp_cp0_data; + +// &Regs; @24 +reg cy; +reg [31:0] data_out; +reg [27:0] hpm; +reg ir; + +// &Wires @25 +wire bht_mispred; +wire cnt_mode_dis; +wire cp0_hpcp_icg_en; +wire [11:0] cp0_hpcp_index; +wire cp0_hpcp_pmdm; +wire cp0_hpcp_pmdu; +wire [31:0] cp0_hpcp_wdata; +wire cp0_hpcp_wreg; +wire [1 :0] cp0_yy_priv_mode; +wire cpurst_b; +wire debug_mode_en; +wire dtu_hpcp_dcsr_stopcount; +wire forever_cpuclk; +wire [31:0] hpcp_cp0_data; +wire hpcp_ifu_icache_access; +wire hpcp_ifu_icache_miss; +wire hpcp_lsu_dcache_read_access; +wire hpcp_lsu_dcache_read_access_gate; +wire hpcp_lsu_dcache_read_miss; +wire hpcp_lsu_dcache_read_miss_gate; +wire hpcp_lsu_dcache_write_access; +wire hpcp_lsu_dcache_write_access_gate; +wire hpcp_lsu_dcache_write_miss; +wire hpcp_lsu_dcache_write_miss_gate; +wire hpcp_retire_bht_mispred; +wire hpcp_retire_inst_condbr; +wire hpcp_retire_inst_condbr_gate; +wire hpcp_retire_inst_store; +wire hpcp_retire_inst_store_gate; +wire hpcp_retire_inst_vld; +wire [31:0] hpcp_wdata; +wire ifu_hpcp_icache_access; +wire ifu_hpcp_icache_miss; +wire inhibt_clk; +wire inst_condbr; +wire inst_condbr_gate; +wire inst_store; +wire inst_store_gate; +wire iu_hpcp_inst_bht_mispred; +wire iu_hpcp_inst_condbr; +wire iu_hpcp_inst_condbr_gate; +wire lsu_hpcp_cache_read_access; +wire lsu_hpcp_cache_read_access_gate; +wire lsu_hpcp_cache_read_miss; +wire lsu_hpcp_cache_read_miss_gate; +wire lsu_hpcp_cache_write_access; +wire lsu_hpcp_cache_write_access_gate; +wire lsu_hpcp_cache_write_miss; +wire lsu_hpcp_cache_write_miss_gate; +wire lsu_hpcp_inst_store; +wire lsu_hpcp_inst_store_gate; +wire [31:0] mcntinhbt_value; +wire mcntinhbt_wen; +wire mcycle_clk_en; +wire mcycle_cnt_en; +wire mcycle_en; +wire [63:0] mcycle_value; +wire mcycle_wen; +wire mcycleh_wen; +wire mhpmcnt13_adder; +wire mhpmcnt13_clk_en; +wire mhpmcnt13_cnt_en; +wire mhpmcnt13_cnt_en_gate; +wire mhpmcnt13_en; +wire [63:0] mhpmcnt13_value; +wire mhpmcnt13_wen; +wire mhpmcnt13h_wen; +wire mhpmcnt14_adder; +wire mhpmcnt14_clk_en; +wire mhpmcnt14_cnt_en; +wire mhpmcnt14_cnt_en_gate; +wire mhpmcnt14_en; +wire [63:0] mhpmcnt14_value; +wire mhpmcnt14_wen; +wire mhpmcnt14h_wen; +wire mhpmcnt15_adder; +wire mhpmcnt15_clk_en; +wire mhpmcnt15_cnt_en; +wire mhpmcnt15_cnt_en_gate; +wire mhpmcnt15_en; +wire [63:0] mhpmcnt15_value; +wire mhpmcnt15_wen; +wire mhpmcnt15h_wen; +wire mhpmcnt16_adder; +wire mhpmcnt16_clk_en; +wire mhpmcnt16_cnt_en; +wire mhpmcnt16_cnt_en_gate; +wire mhpmcnt16_en; +wire [63:0] mhpmcnt16_value; +wire mhpmcnt16_wen; +wire mhpmcnt16h_wen; +wire mhpmcnt17_adder; +wire mhpmcnt17_clk_en; +wire mhpmcnt17_cnt_en; +wire mhpmcnt17_cnt_en_gate; +wire mhpmcnt17_en; +wire [63:0] mhpmcnt17_value; +wire mhpmcnt17_wen; +wire mhpmcnt17h_wen; +wire mhpmcnt3_adder; +wire mhpmcnt3_clk_en; +wire mhpmcnt3_cnt_en; +wire mhpmcnt3_en; +wire [63:0] mhpmcnt3_value; +wire mhpmcnt3_wen; +wire mhpmcnt3h_wen; +wire mhpmcnt4_adder; +wire mhpmcnt4_clk_en; +wire mhpmcnt4_cnt_en; +wire mhpmcnt4_en; +wire [63:0] mhpmcnt4_value; +wire mhpmcnt4_wen; +wire mhpmcnt4h_wen; +wire mhpmcnt8_adder; +wire mhpmcnt8_clk_en; +wire mhpmcnt8_cnt_en; +wire mhpmcnt8_en; +wire [63:0] mhpmcnt8_value; +wire mhpmcnt8_wen; +wire mhpmcnt8h_wen; +wire mhpmcnt9_adder; +wire mhpmcnt9_clk_en; +wire mhpmcnt9_cnt_en; +wire mhpmcnt9_cnt_en_gate; +wire mhpmcnt9_en; +wire [63:0] mhpmcnt9_value; +wire mhpmcnt9_wen; +wire mhpmcnt9h_wen; +wire mhpmevt13_clk_en; +wire [31:0] mhpmevt13_value; +wire mhpmevt13_wen; +wire mhpmevt14_clk_en; +wire [31:0] mhpmevt14_value; +wire mhpmevt14_wen; +wire mhpmevt15_clk_en; +wire [31:0] mhpmevt15_value; +wire mhpmevt15_wen; +wire mhpmevt16_clk_en; +wire [31:0] mhpmevt16_value; +wire mhpmevt16_wen; +wire mhpmevt17_clk_en; +wire [31:0] mhpmevt17_value; +wire mhpmevt17_wen; +wire mhpmevt3_clk_en; +wire [31:0] mhpmevt3_value; +wire mhpmevt3_wen; +wire mhpmevt4_clk_en; +wire [31:0] mhpmevt4_value; +wire mhpmevt4_wen; +wire mhpmevt8_clk_en; +wire [31:0] mhpmevt8_value; +wire mhpmevt8_wen; +wire mhpmevt9_clk_en; +wire [31:0] mhpmevt9_value; +wire mhpmevt9_wen; +wire minstret_adder; +wire minstret_clk_en; +wire minstret_cnt_en; +wire minstret_en; +wire [63:0] minstret_value; +wire minstret_wen; +wire minstreth_wen; +wire pad_yy_icg_scan_en; +wire rtu_hpcp_retire_inst_vld; +wire rtu_yy_xx_dbgon; +wire [63:0] sysio_hpcp_time; + + + +// performance monitor regs list in E906 +// Machine Counter Setup +parameter MCNTINHBT = 12'h320; +parameter MHPMEVT3 = 12'h323; +parameter MHPMEVT4 = 12'h324; +parameter MHPMEVT5 = 12'h325; +parameter MHPMEVT6 = 12'h326; +parameter MHPMEVT7 = 12'h327; +parameter MHPMEVT8 = 12'h328; +parameter MHPMEVT9 = 12'h329; +parameter MHPMEVT10 = 12'h32A; +parameter MHPMEVT11 = 12'h32B; +parameter MHPMEVT12 = 12'h32C; +parameter MHPMEVT13 = 12'h32D; +parameter MHPMEVT14 = 12'h32E; +parameter MHPMEVT15 = 12'h32F; +parameter MHPMEVT16 = 12'h330; +parameter MHPMEVT17 = 12'h331; +parameter MHPMEVT18 = 12'h332; +parameter MHPMEVT19 = 12'h333; +parameter MHPMEVT20 = 12'h334; +parameter MHPMEVT21 = 12'h335; +parameter MHPMEVT22 = 12'h336; +parameter MHPMEVT23 = 12'h337; +parameter MHPMEVT24 = 12'h338; +parameter MHPMEVT25 = 12'h339; +parameter MHPMEVT26 = 12'h33A; +parameter MHPMEVT27 = 12'h33B; +parameter MHPMEVT28 = 12'h33C; +parameter MHPMEVT29 = 12'h33D; +parameter MHPMEVT30 = 12'h33E; +parameter MHPMEVT31 = 12'h33F; +parameter MCNTWEN = 12'h7C9; + +// Machine Counters/Timers +parameter MCYCLE = 12'hB00; +parameter MINSTRET = 12'hB02; +parameter MHPMCNT3 = 12'hB03; +parameter MHPMCNT4 = 12'hB04; +parameter MHPMCNT5 = 12'hB05; +parameter MHPMCNT6 = 12'hB06; +parameter MHPMCNT7 = 12'hB07; +parameter MHPMCNT8 = 12'hB08; +parameter MHPMCNT9 = 12'hB09; +parameter MHPMCNT10 = 12'hB0A; +parameter MHPMCNT11 = 12'hB0B; +parameter MHPMCNT12 = 12'hB0C; +parameter MHPMCNT13 = 12'hB0D; +parameter MHPMCNT14 = 12'hB0E; +parameter MHPMCNT15 = 12'hB0F; +parameter MHPMCNT16 = 12'hB10; +parameter MHPMCNT17 = 12'hB11; +parameter MHPMCNT18 = 12'hB12; +parameter MHPMCNT19 = 12'hB13; +parameter MHPMCNT20 = 12'hB14; +parameter MHPMCNT21 = 12'hB15; +parameter MHPMCNT22 = 12'hB16; +parameter MHPMCNT23 = 12'hB17; +parameter MHPMCNT24 = 12'hB18; +parameter MHPMCNT25 = 12'hB19; +parameter MHPMCNT26 = 12'hB1A; +parameter MHPMCNT27 = 12'hB1B; +parameter MHPMCNT28 = 12'hB1C; +parameter MHPMCNT29 = 12'hB1D; +parameter MHPMCNT30 = 12'hB1E; +parameter MHPMCNT31 = 12'hB1F; + +parameter MCYCLEH = 12'hB80; +parameter MINSTRETH = 12'hB82; +parameter MHPMCNT3H = 12'hB83; +parameter MHPMCNT4H = 12'hB84; +parameter MHPMCNT5H = 12'hB85; +parameter MHPMCNT6H = 12'hB86; +parameter MHPMCNT7H = 12'hB87; +parameter MHPMCNT8H = 12'hB88; +parameter MHPMCNT9H = 12'hB89; +parameter MHPMCNT10H = 12'hB8A; +parameter MHPMCNT11H = 12'hB8B; +parameter MHPMCNT12H = 12'hB8C; +parameter MHPMCNT13H = 12'hB8D; +parameter MHPMCNT14H = 12'hB8E; +parameter MHPMCNT15H = 12'hB8F; +parameter MHPMCNT16H = 12'hB90; +parameter MHPMCNT17H = 12'hB91; +parameter MHPMCNT18H = 12'hB92; +parameter MHPMCNT19H = 12'hB93; +parameter MHPMCNT20H = 12'hB94; +parameter MHPMCNT21H = 12'hB95; +parameter MHPMCNT22H = 12'hB96; +parameter MHPMCNT23H = 12'hB97; +parameter MHPMCNT24H = 12'hB98; +parameter MHPMCNT25H = 12'hB99; +parameter MHPMCNT26H = 12'hB9A; +parameter MHPMCNT27H = 12'hB9B; +parameter MHPMCNT28H = 12'hB9C; +parameter MHPMCNT29H = 12'hB9D; +parameter MHPMCNT30H = 12'hB9E; +parameter MHPMCNT31H = 12'hB9F; + +// User Counters/Timers +parameter CYCLE = 12'hC00; +parameter REG_TIME = 12'hC01; +parameter INSTRET = 12'hC02; +parameter HPMCNT3 = 12'hC03; +parameter HPMCNT4 = 12'hC04; +parameter HPMCNT5 = 12'hC05; +parameter HPMCNT6 = 12'hC06; +parameter HPMCNT7 = 12'hC07; +parameter HPMCNT8 = 12'hC08; +parameter HPMCNT9 = 12'hC09; +parameter HPMCNT10 = 12'hC0A; +parameter HPMCNT11 = 12'hC0B; +parameter HPMCNT12 = 12'hC0C; +parameter HPMCNT13 = 12'hC0D; +parameter HPMCNT14 = 12'hC0E; +parameter HPMCNT15 = 12'hC0F; +parameter HPMCNT16 = 12'hC10; +parameter HPMCNT17 = 12'hC11; +parameter HPMCNT18 = 12'hC12; +parameter HPMCNT19 = 12'hC13; +parameter HPMCNT20 = 12'hC14; +parameter HPMCNT21 = 12'hC15; +parameter HPMCNT22 = 12'hC16; +parameter HPMCNT23 = 12'hC17; +parameter HPMCNT24 = 12'hC18; +parameter HPMCNT25 = 12'hC19; +parameter HPMCNT26 = 12'hC1A; +parameter HPMCNT27 = 12'hC1B; +parameter HPMCNT28 = 12'hC1C; +parameter HPMCNT29 = 12'hC1D; +parameter HPMCNT30 = 12'hC1E; +parameter HPMCNT31 = 12'hC1F; + +parameter CYCLEH = 12'hC80; +parameter REG_TIMEH = 12'hC81; +parameter INSTRETH = 12'hC82; +parameter HPMCNT3H = 12'hC83; +parameter HPMCNT4H = 12'hC84; +parameter HPMCNT5H = 12'hC85; +parameter HPMCNT6H = 12'hC86; +parameter HPMCNT7H = 12'hC87; +parameter HPMCNT8H = 12'hC88; +parameter HPMCNT9H = 12'hC89; +parameter HPMCNT10H = 12'hC8A; +parameter HPMCNT11H = 12'hC8B; +parameter HPMCNT12H = 12'hC8C; +parameter HPMCNT13H = 12'hC8D; +parameter HPMCNT14H = 12'hC8E; +parameter HPMCNT15H = 12'hC8F; +parameter HPMCNT16H = 12'hC90; +parameter HPMCNT17H = 12'hC91; +parameter HPMCNT18H = 12'hC92; +parameter HPMCNT19H = 12'hC93; +parameter HPMCNT20H = 12'hC94; +parameter HPMCNT21H = 12'hC95; +parameter HPMCNT22H = 12'hC96; +parameter HPMCNT23H = 12'hC97; +parameter HPMCNT24H = 12'hC98; +parameter HPMCNT25H = 12'hC99; +parameter HPMCNT26H = 12'hC9A; +parameter HPMCNT27H = 12'hC9B; +parameter HPMCNT28H = 12'hC9C; +parameter HPMCNT29H = 12'hC9D; +parameter HPMCNT30H = 12'hC9E; +parameter HPMCNT31H = 12'hC9F; + +//============================================================================== +// Write signal +//============================================================================== +//machine mode counter inhibit +assign mcntinhbt_wen = (cp0_hpcp_index[11:0] == MCNTINHBT ) && cp0_hpcp_wreg; + +//Now hpmevent can only write leagal data,that is : 0 or corresponding data +assign mhpmevt3_wen = (cp0_hpcp_index[11:0] == MHPMEVT3 ) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd1)); +assign mhpmevt4_wen = (cp0_hpcp_index[11:0] == MHPMEVT4 ) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd2)); +assign mhpmevt8_wen = (cp0_hpcp_index[11:0] == MHPMEVT8 ) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd6)); +assign mhpmevt9_wen = (cp0_hpcp_index[11:0] == MHPMEVT9 ) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd7)); +assign mhpmevt13_wen = (cp0_hpcp_index[11:0] == MHPMEVT13) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd11)); +assign mhpmevt14_wen = (cp0_hpcp_index[11:0] == MHPMEVT14) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd12)); +assign mhpmevt15_wen = (cp0_hpcp_index[11:0] == MHPMEVT15) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd13)); +assign mhpmevt16_wen = (cp0_hpcp_index[11:0] == MHPMEVT16) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd14)); +assign mhpmevt17_wen = (cp0_hpcp_index[11:0] == MHPMEVT17) && cp0_hpcp_wreg + && ((cp0_hpcp_wdata[4:0] == 5'b0) || (cp0_hpcp_wdata[4:0] == 5'd15)); + +// conter write enable signal +assign mcycle_wen = (cp0_hpcp_index[11:0] == MCYCLE) && cp0_hpcp_wreg; +assign minstret_wen = (cp0_hpcp_index[11:0] == MINSTRET) && cp0_hpcp_wreg; +assign mhpmcnt3_wen = (cp0_hpcp_index[11:0] == MHPMCNT3) && cp0_hpcp_wreg && (mhpmevt3_value[4:0] == 5'b00001); +assign mhpmcnt4_wen = (cp0_hpcp_index[11:0] == MHPMCNT4) && cp0_hpcp_wreg && (mhpmevt4_value[4:0] == 5'b00010); +assign mhpmcnt8_wen = (cp0_hpcp_index[11:0] == MHPMCNT8) && cp0_hpcp_wreg && (mhpmevt8_value[4:0] == 5'b00110); +assign mhpmcnt9_wen = (cp0_hpcp_index[11:0] == MHPMCNT9) && cp0_hpcp_wreg && (mhpmevt9_value[4:0] == 5'b00111); +assign mhpmcnt13_wen = (cp0_hpcp_index[11:0] == MHPMCNT13) && cp0_hpcp_wreg && (mhpmevt13_value[4:0] == 5'b01011); +assign mhpmcnt14_wen = (cp0_hpcp_index[11:0] == MHPMCNT14) && cp0_hpcp_wreg && (mhpmevt14_value[4:0] == 5'b01100); +assign mhpmcnt15_wen = (cp0_hpcp_index[11:0] == MHPMCNT15) && cp0_hpcp_wreg && (mhpmevt15_value[4:0] == 5'b01101); +assign mhpmcnt16_wen = (cp0_hpcp_index[11:0] == MHPMCNT16) && cp0_hpcp_wreg && (mhpmevt16_value[4:0] == 5'b01110); +assign mhpmcnt17_wen = (cp0_hpcp_index[11:0] == MHPMCNT17) && cp0_hpcp_wreg && (mhpmevt17_value[4:0] == 5'b01111); + +assign mcycleh_wen = (cp0_hpcp_index[11:0] == MCYCLEH) && cp0_hpcp_wreg; +assign minstreth_wen = (cp0_hpcp_index[11:0] == MINSTRETH) && cp0_hpcp_wreg; +assign mhpmcnt3h_wen = (cp0_hpcp_index[11:0] == MHPMCNT3H) && cp0_hpcp_wreg && (mhpmevt3_value[4:0] == 5'b00001); +assign mhpmcnt4h_wen = (cp0_hpcp_index[11:0] == MHPMCNT4H) && cp0_hpcp_wreg && (mhpmevt4_value[4:0] == 5'b00010); +assign mhpmcnt8h_wen = (cp0_hpcp_index[11:0] == MHPMCNT8H) && cp0_hpcp_wreg && (mhpmevt8_value[4:0] == 5'b00110); +assign mhpmcnt9h_wen = (cp0_hpcp_index[11:0] == MHPMCNT9H) && cp0_hpcp_wreg && (mhpmevt9_value[4:0] == 5'b00111); +assign mhpmcnt13h_wen = (cp0_hpcp_index[11:0] == MHPMCNT13H) && cp0_hpcp_wreg && (mhpmevt13_value[4:0] == 5'b01011); +assign mhpmcnt14h_wen = (cp0_hpcp_index[11:0] == MHPMCNT14H) && cp0_hpcp_wreg && (mhpmevt14_value[4:0] == 5'b01100); +assign mhpmcnt15h_wen = (cp0_hpcp_index[11:0] == MHPMCNT15H) && cp0_hpcp_wreg && (mhpmevt15_value[4:0] == 5'b01101); +assign mhpmcnt16h_wen = (cp0_hpcp_index[11:0] == MHPMCNT16H) && cp0_hpcp_wreg && (mhpmevt16_value[4:0] == 5'b01110); +assign mhpmcnt17h_wen = (cp0_hpcp_index[11:0] == MHPMCNT17H) && cp0_hpcp_wreg && (mhpmevt17_value[4:0] == 5'b01111); + +//============================================================================== +// Counter Control Signals +//============================================================================== +//when user/supervisor/machine counter disable,counter can not count +assign cnt_mode_dis = (cp0_yy_priv_mode[1:0] == 2'b11) && cp0_hpcp_pmdm + || (cp0_yy_priv_mode[1:0] == 2'b00) && cp0_hpcp_pmdu; + +assign debug_mode_en = !rtu_yy_xx_dbgon || !dtu_hpcp_dcsr_stopcount; +// enable counter +assign mcycle_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[0]; +assign minstret_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[2]; +assign mhpmcnt3_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[3] && (mhpmevt3_value[4:0] == 5'b00001); +assign mhpmcnt4_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[4] && (mhpmevt4_value[4:0] == 5'b00010); +assign mhpmcnt8_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[8] && (mhpmevt8_value[4:0] == 5'b00110); +assign mhpmcnt9_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[9] && (mhpmevt9_value[4:0] == 5'b00111); +assign mhpmcnt13_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[13] && (mhpmevt13_value[4:0] == 5'b01011); +assign mhpmcnt14_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[14] && (mhpmevt14_value[4:0] == 5'b01100); +assign mhpmcnt15_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[15] && (mhpmevt15_value[4:0] == 5'b01101); +assign mhpmcnt16_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[16] && (mhpmevt16_value[4:0] == 5'b01110); +assign mhpmcnt17_en = debug_mode_en && !cnt_mode_dis && !mcntinhbt_value[17] && (mhpmevt17_value[4:0] == 5'b01111); + +//counter count enable signal +assign mcycle_cnt_en = mcycle_en; +assign minstret_cnt_en = minstret_en && hpcp_retire_inst_vld; +assign mhpmcnt3_cnt_en = mhpmcnt3_en && hpcp_ifu_icache_access; +assign mhpmcnt4_cnt_en = mhpmcnt4_en && hpcp_ifu_icache_miss; +assign mhpmcnt8_cnt_en = mhpmcnt8_en && bht_mispred; +assign mhpmcnt9_cnt_en = mhpmcnt9_en && inst_condbr; +assign mhpmcnt13_cnt_en = mhpmcnt13_en && inst_store; +assign mhpmcnt14_cnt_en = mhpmcnt14_en && hpcp_lsu_dcache_read_access; +assign mhpmcnt15_cnt_en = mhpmcnt15_en && hpcp_lsu_dcache_read_miss; +assign mhpmcnt16_cnt_en = mhpmcnt16_en && hpcp_lsu_dcache_write_access; +assign mhpmcnt17_cnt_en = mhpmcnt17_en && hpcp_lsu_dcache_write_miss; + +assign mhpmcnt9_cnt_en_gate = mhpmcnt9_en && inst_condbr_gate; +assign mhpmcnt13_cnt_en_gate = mhpmcnt13_en && inst_store_gate; +assign mhpmcnt14_cnt_en_gate = mhpmcnt14_en && hpcp_lsu_dcache_read_access_gate; +assign mhpmcnt15_cnt_en_gate = mhpmcnt15_en && hpcp_lsu_dcache_read_miss_gate; +assign mhpmcnt16_cnt_en_gate = mhpmcnt16_en && hpcp_lsu_dcache_write_access_gate; +assign mhpmcnt17_cnt_en_gate = mhpmcnt17_en && hpcp_lsu_dcache_write_miss_gate; +//========================================================== +// Event Signals Rename +//========================================================== +assign hpcp_retire_inst_vld = rtu_hpcp_retire_inst_vld; +assign hpcp_retire_inst_condbr = iu_hpcp_inst_condbr; +assign hpcp_retire_bht_mispred = iu_hpcp_inst_bht_mispred; +assign hpcp_retire_inst_store = lsu_hpcp_inst_store; +assign hpcp_ifu_icache_access = ifu_hpcp_icache_access; +assign hpcp_ifu_icache_miss = ifu_hpcp_icache_miss; +assign hpcp_lsu_dcache_read_access = lsu_hpcp_cache_read_access; +assign hpcp_lsu_dcache_read_miss = lsu_hpcp_cache_read_miss; +assign hpcp_lsu_dcache_write_access = lsu_hpcp_cache_write_access; +assign hpcp_lsu_dcache_write_miss = lsu_hpcp_cache_write_miss; + +assign hpcp_retire_inst_condbr_gate = iu_hpcp_inst_condbr_gate; +assign hpcp_retire_inst_store_gate = lsu_hpcp_inst_store_gate; +assign hpcp_lsu_dcache_read_access_gate = lsu_hpcp_cache_read_access_gate; +assign hpcp_lsu_dcache_read_miss_gate = lsu_hpcp_cache_read_miss_gate; +assign hpcp_lsu_dcache_write_access_gate = lsu_hpcp_cache_write_access_gate; +assign hpcp_lsu_dcache_write_miss_gate = lsu_hpcp_cache_write_miss_gate; +//========================================================== +// Clk Enable of Gated Cell +//========================================================== +assign mhpmevt3_clk_en = mhpmevt3_wen; +assign mhpmevt4_clk_en = mhpmevt4_wen; +assign mhpmevt8_clk_en = mhpmevt8_wen; +assign mhpmevt9_clk_en = mhpmevt9_wen; +assign mhpmevt13_clk_en = mhpmevt13_wen; +assign mhpmevt14_clk_en = mhpmevt14_wen; +assign mhpmevt15_clk_en = mhpmevt15_wen; +assign mhpmevt16_clk_en = mhpmevt16_wen; +assign mhpmevt17_clk_en = mhpmevt17_wen; +assign mcycle_clk_en = mcycle_cnt_en || mcycle_wen ; +assign minstret_clk_en = minstret_cnt_en || minstret_wen ; +assign mhpmcnt3_clk_en = mhpmcnt3_cnt_en || mhpmcnt3_wen ; +assign mhpmcnt4_clk_en = mhpmcnt4_cnt_en || mhpmcnt4_wen ; +assign mhpmcnt8_clk_en = mhpmcnt8_cnt_en || mhpmcnt8_wen ; +assign mhpmcnt9_clk_en = mhpmcnt9_cnt_en_gate || mhpmcnt9_wen ; +assign mhpmcnt13_clk_en = mhpmcnt13_cnt_en_gate || mhpmcnt13_wen; +assign mhpmcnt14_clk_en = mhpmcnt14_cnt_en_gate || mhpmcnt14_wen; +assign mhpmcnt15_clk_en = mhpmcnt15_cnt_en_gate || mhpmcnt15_wen; +assign mhpmcnt16_clk_en = mhpmcnt16_cnt_en_gate || mhpmcnt16_wen; +assign mhpmcnt17_clk_en = mhpmcnt17_cnt_en_gate || mhpmcnt17_wen; + +//data prepare +assign hpcp_wdata[31:0] = cp0_hpcp_wdata[31:0]; + +//========================================================== +// Control Registers +//========================================================== +// &Instance("gated_clk_cell", "x_inhibt_gated_clk"); @335 +gated_clk_cell x_inhibt_gated_clk ( + .clk_in (forever_cpuclk ), + .clk_out (inhibt_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (mcntinhbt_wen ), + .module_en (cp0_hpcp_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @336 +// .external_en (1'b0), @337 +// .global_en (1'b1), @338 +// .module_en (cp0_hpcp_icg_en), @339 +// .local_en (mcntinhbt_wen), @340 +// .clk_out (inhibt_clk)); @341 + +//========================================================== +// MCOUNTINHIBIT - Machine Counter-Inhibit Register +//========================================================== +// +----+----+----+-----------+---+---+---+---+---+---+ +// | 31 | 30 | 29 | 28:6 | 5 | 4 | 3 | 2 | 1 | 0 | +// +----+----+----+-----------+---+---+---+---+---+---+ +// | | | | | | | | | +// | | | | | | | | +---- CY +// | | | | | | | +-------- 0 +// | | | | | | +------------ IR +// | | | | | +---------------- HPM3 +// | | | | +-------------------- HPM4 +// | | | +------------------------ HPM5 +// | | + --------------------------------------- HPM29 +// | +--------------------------------------------- HPM30 +// +-------------------------------------------------- HPPM31 + +assign mcntinhbt_value[31:0] = {1'b0, hpm[27:0], ir, 1'b0, cy}; + +//===================================== +// HPM31~3/IR/CY bit in mnountinhibt +//===================================== +always @(posedge inhibt_clk or negedge cpurst_b) +begin + if(!cpurst_b) + begin + ir <= 1'b0; + cy <= 1'b0; + end + else if(mcntinhbt_wen) + begin + ir <= hpcp_wdata[2]; + cy <= hpcp_wdata[0]; + end + else + begin + ir <= ir; + cy <= cy; + end +end + +always @(posedge inhibt_clk or negedge cpurst_b) +begin + if(!cpurst_b) + hpm[27:0] <= 28'b0; + else if(mcntinhbt_wen) + hpm[27:0] <= hpcp_wdata[30:3]; + else + hpm[27:0] <= hpm[27:0]; +end +//========================================================== +// Configure Registers +//========================================================== + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent3"); @402 +pa_hpcp_event x_hpcp_mhpmevent3 ( + .clk_en (mhpmevt3_clk_en ), + .cnt_output (mhpmevt3_value ), + .cnt_wen (mhpmevt3_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent3"); @404 +// &Connect(.clk_en (mhpmevt3_clk_en), @406 +// .cnt_wen (mhpmevt3_wen), @407 +// .cnt_output (mhpmevt3_value)); @408 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent4"); @411 +pa_hpcp_event x_hpcp_mhpmevent4 ( + .clk_en (mhpmevt4_clk_en ), + .cnt_output (mhpmevt4_value ), + .cnt_wen (mhpmevt4_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent4"); @413 +// &Connect(.clk_en (mhpmevt4_clk_en), @415 +// .cnt_wen (mhpmevt4_wen), @416 +// .cnt_output (mhpmevt4_value)); @417 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent8"); @420 +pa_hpcp_event x_hpcp_mhpmevent8 ( + .clk_en (mhpmevt8_clk_en ), + .cnt_output (mhpmevt8_value ), + .cnt_wen (mhpmevt8_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent8"); @422 +// &Connect(.clk_en (mhpmevt8_clk_en), @424 +// .cnt_wen (mhpmevt8_wen), @425 +// .cnt_output (mhpmevt8_value)); @426 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent9"); @429 +pa_hpcp_event x_hpcp_mhpmevent9 ( + .clk_en (mhpmevt9_clk_en ), + .cnt_output (mhpmevt9_value ), + .cnt_wen (mhpmevt9_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent9"); @431 +// &Connect(.clk_en (mhpmevt9_clk_en), @433 +// .cnt_wen (mhpmevt9_wen), @434 +// .cnt_output (mhpmevt9_value)); @435 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent13"); @438 +pa_hpcp_event x_hpcp_mhpmevent13 ( + .clk_en (mhpmevt13_clk_en ), + .cnt_output (mhpmevt13_value ), + .cnt_wen (mhpmevt13_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent13"); @440 +// &Connect(.clk_en (mhpmevt13_clk_en), @442 +// .cnt_wen (mhpmevt13_wen), @443 +// .cnt_output (mhpmevt13_value)); @444 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent14"); @447 +pa_hpcp_event x_hpcp_mhpmevent14 ( + .clk_en (mhpmevt14_clk_en ), + .cnt_output (mhpmevt14_value ), + .cnt_wen (mhpmevt14_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent14"); @449 +// &Connect(.clk_en (mhpmevt14_clk_en), @451 +// .cnt_wen (mhpmevt14_wen), @452 +// .cnt_output (mhpmevt14_value)); @453 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent15"); @456 +pa_hpcp_event x_hpcp_mhpmevent15 ( + .clk_en (mhpmevt15_clk_en ), + .cnt_output (mhpmevt15_value ), + .cnt_wen (mhpmevt15_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent15"); @458 +// &Connect(.clk_en (mhpmevt15_clk_en), @460 +// .cnt_wen (mhpmevt15_wen), @461 +// .cnt_output (mhpmevt15_value)); @462 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent16"); @465 +pa_hpcp_event x_hpcp_mhpmevent16 ( + .clk_en (mhpmevt16_clk_en ), + .cnt_output (mhpmevt16_value ), + .cnt_wen (mhpmevt16_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent16"); @467 +// &Connect(.clk_en (mhpmevt16_clk_en), @469 +// .cnt_wen (mhpmevt16_wen), @470 +// .cnt_output (mhpmevt16_value)); @471 + +// &Instance("pa_hpcp_event", "x_hpcp_mhpmevent17"); @474 +pa_hpcp_event x_hpcp_mhpmevent17 ( + .clk_en (mhpmevt17_clk_en ), + .cnt_output (mhpmevt17_value ), + .cnt_wen (mhpmevt17_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_event_dummy", "x_hpcp_mhpmevent17"); @476 +// &Connect(.clk_en (mhpmevt17_clk_en), @478 +// .cnt_wen (mhpmevt17_wen), @479 +// .cnt_output (mhpmevt17_value)); @480 + +//========================================================== +// Cycle and Counters +//========================================================== +// Cycle counter +// &Instance("pa_hpcp_cnt", "x_hpcp_mcycle"); @486 +pa_hpcp_cnt x_hpcp_mcycle ( + .clk_en (mcycle_clk_en ), + .cnt_adder (1'b1 ), + .cnt_en (mcycle_cnt_en ), + .cnt_hwen (mcycleh_wen ), + .cnt_output (mcycle_value ), + .cnt_wen (mcycle_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_en (mcycle_clk_en), @487 +// .cnt_en (mcycle_cnt_en), @488 +// .cnt_wen (mcycle_wen), @489 +// .cnt_hwen (mcycleh_wen), @490 +// .cnt_adder (1'b1), @491 +// .cnt_output (mcycle_value)); @492 + +// Instruction Retire counter +// Event counter 0x2: total instruction counter +assign minstret_adder = hpcp_retire_inst_vld; +// &Instance("pa_hpcp_cnt", "x_hpcp_minstret"); @497 +pa_hpcp_cnt x_hpcp_minstret ( + .clk_en (minstret_clk_en ), + .cnt_adder (minstret_adder ), + .cnt_en (minstret_cnt_en ), + .cnt_hwen (minstreth_wen ), + .cnt_output (minstret_value ), + .cnt_wen (minstret_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_en (minstret_clk_en), @498 +// .cnt_en (minstret_cnt_en), @499 +// .cnt_wen (minstret_wen), @500 +// .cnt_hwen (minstreth_wen), @501 +// .cnt_adder (minstret_adder), @502 +// .cnt_output (minstret_value)); @503 + +// mhpmcnt3: L1 icache access counter +assign mhpmcnt3_adder = hpcp_ifu_icache_access; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt3"); @508 +pa_hpcp_cnt x_hpcp_mhpmcnt3 ( + .clk_en (mhpmcnt3_clk_en ), + .cnt_adder (mhpmcnt3_adder ), + .cnt_en (mhpmcnt3_cnt_en ), + .cnt_hwen (mhpmcnt3h_wen ), + .cnt_output (mhpmcnt3_value ), + .cnt_wen (mhpmcnt3_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt3"); @510 +// &Connect(.clk_en (mhpmcnt3_clk_en), @512 +// .cnt_en (mhpmcnt3_cnt_en), @513 +// .cnt_wen (mhpmcnt3_wen), @514 +// .cnt_hwen (mhpmcnt3h_wen), @515 +// .cnt_adder (mhpmcnt3_adder), @516 +// .cnt_output (mhpmcnt3_value)); @517 + +// mhpmcnt4: L1 icache miss counter +assign mhpmcnt4_adder = hpcp_ifu_icache_miss; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt4"); @522 +pa_hpcp_cnt x_hpcp_mhpmcnt4 ( + .clk_en (mhpmcnt4_clk_en ), + .cnt_adder (mhpmcnt4_adder ), + .cnt_en (mhpmcnt4_cnt_en ), + .cnt_hwen (mhpmcnt4h_wen ), + .cnt_output (mhpmcnt4_value ), + .cnt_wen (mhpmcnt4_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt4"); @524 +// &Connect(.clk_en (mhpmcnt4_clk_en), @526 +// .cnt_en (mhpmcnt4_cnt_en), @527 +// .cnt_wen (mhpmcnt4_wen), @528 +// .cnt_hwen (mhpmcnt4h_wen), @529 +// .cnt_adder (mhpmcnt4_adder), @530 +// .cnt_output (mhpmcnt4_value)); @531 + +// mhpmcnt8:Conditional Branch Mispredict counter +assign bht_mispred = hpcp_retire_bht_mispred; +assign mhpmcnt8_adder = bht_mispred; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt8"); @537 +pa_hpcp_cnt x_hpcp_mhpmcnt8 ( + .clk_en (mhpmcnt8_clk_en ), + .cnt_adder (mhpmcnt8_adder ), + .cnt_en (mhpmcnt8_cnt_en ), + .cnt_hwen (mhpmcnt8h_wen ), + .cnt_output (mhpmcnt8_value ), + .cnt_wen (mhpmcnt8_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt8"); @539 +// &Connect(.clk_en (mhpmcnt8_clk_en), @541 +// .cnt_en (mhpmcnt8_cnt_en), @542 +// .cnt_wen (mhpmcnt8_wen), @543 +// .cnt_hwen (mhpmcnt8h_wen), @544 +// .cnt_adder (mhpmcnt8_adder), @545 +// .cnt_output (mhpmcnt8_value)); @546 + +// mhpmcnt9:Conditional Branch Instruction counter +assign inst_condbr = hpcp_retire_inst_condbr; +assign inst_condbr_gate = hpcp_retire_inst_condbr_gate; +assign mhpmcnt9_adder = inst_condbr; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt9"); @553 +pa_hpcp_cnt x_hpcp_mhpmcnt9 ( + .clk_en (mhpmcnt9_clk_en ), + .cnt_adder (mhpmcnt9_adder ), + .cnt_en (mhpmcnt9_cnt_en ), + .cnt_hwen (mhpmcnt9h_wen ), + .cnt_output (mhpmcnt9_value ), + .cnt_wen (mhpmcnt9_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt9"); @555 +// &Connect(.clk_en (mhpmcnt9_clk_en), @557 +// .cnt_en (mhpmcnt9_cnt_en), @558 +// .cnt_wen (mhpmcnt9_wen), @559 +// .cnt_hwen (mhpmcnt9h_wen), @560 +// .cnt_adder (mhpmcnt9_adder), @561 +// .cnt_output (mhpmcnt9_value)); @562 + +// mhpmcnt13: Store Instruction counter +assign inst_store = hpcp_retire_inst_store; +assign inst_store_gate = hpcp_retire_inst_store_gate; +assign mhpmcnt13_adder = inst_store; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt13"); @569 +pa_hpcp_cnt x_hpcp_mhpmcnt13 ( + .clk_en (mhpmcnt13_clk_en ), + .cnt_adder (mhpmcnt13_adder ), + .cnt_en (mhpmcnt13_cnt_en ), + .cnt_hwen (mhpmcnt13h_wen ), + .cnt_output (mhpmcnt13_value ), + .cnt_wen (mhpmcnt13_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt13"); @571 +// &Connect(.clk_en (mhpmcnt13_clk_en), @573 +// .cnt_en (mhpmcnt13_cnt_en), @574 +// .cnt_wen (mhpmcnt13_wen), @575 +// .cnt_hwen (mhpmcnt13h_wen), @576 +// .cnt_adder (mhpmcnt13_adder), @577 +// .cnt_output (mhpmcnt13_value)); @578 + +// mhpmcnt14: LSU read access counter +assign mhpmcnt14_adder = hpcp_lsu_dcache_read_access; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt14"); @583 +pa_hpcp_cnt x_hpcp_mhpmcnt14 ( + .clk_en (mhpmcnt14_clk_en ), + .cnt_adder (mhpmcnt14_adder ), + .cnt_en (mhpmcnt14_cnt_en ), + .cnt_hwen (mhpmcnt14h_wen ), + .cnt_output (mhpmcnt14_value ), + .cnt_wen (mhpmcnt14_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt14"); @585 +// &Connect(.clk_en (mhpmcnt14_clk_en), @587 +// .cnt_en (mhpmcnt14_cnt_en), @588 +// .cnt_wen (mhpmcnt14_wen), @589 +// .cnt_hwen (mhpmcnt14h_wen), @590 +// .cnt_adder (mhpmcnt14_adder), @591 +// .cnt_output (mhpmcnt14_value)); @592 + +// mhpmcnt15: LSU read miss counter +assign mhpmcnt15_adder = hpcp_lsu_dcache_read_miss; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt15"); @597 +pa_hpcp_cnt x_hpcp_mhpmcnt15 ( + .clk_en (mhpmcnt15_clk_en ), + .cnt_adder (mhpmcnt15_adder ), + .cnt_en (mhpmcnt15_cnt_en ), + .cnt_hwen (mhpmcnt15h_wen ), + .cnt_output (mhpmcnt15_value ), + .cnt_wen (mhpmcnt15_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt15"); @599 +// &Connect(.clk_en (mhpmcnt15_clk_en), @601 +// .cnt_en (mhpmcnt15_cnt_en), @602 +// .cnt_wen (mhpmcnt15_wen), @603 +// .cnt_hwen (mhpmcnt15h_wen), @604 +// .cnt_adder (mhpmcnt15_adder), @605 +// .cnt_output (mhpmcnt15_value)); @606 + +// mhpmcnt16: LSU write access counter +assign mhpmcnt16_adder = hpcp_lsu_dcache_write_access; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt16"); @611 +pa_hpcp_cnt x_hpcp_mhpmcnt16 ( + .clk_en (mhpmcnt16_clk_en ), + .cnt_adder (mhpmcnt16_adder ), + .cnt_en (mhpmcnt16_cnt_en ), + .cnt_hwen (mhpmcnt16h_wen ), + .cnt_output (mhpmcnt16_value ), + .cnt_wen (mhpmcnt16_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt16"); @613 +// &Connect(.clk_en (mhpmcnt16_clk_en), @615 +// .cnt_en (mhpmcnt16_cnt_en), @616 +// .cnt_wen (mhpmcnt16_wen), @617 +// .cnt_hwen (mhpmcnt16h_wen), @618 +// .cnt_adder (mhpmcnt16_adder), @619 +// .cnt_output (mhpmcnt16_value)); @620 + +// mhpmcnt17: LSU write miss counter +assign mhpmcnt17_adder = hpcp_lsu_dcache_write_miss; +// &Instance("pa_hpcp_cnt", "x_hpcp_mhpmcnt17"); @625 +pa_hpcp_cnt x_hpcp_mhpmcnt17 ( + .clk_en (mhpmcnt17_clk_en ), + .cnt_adder (mhpmcnt17_adder ), + .cnt_en (mhpmcnt17_cnt_en ), + .cnt_hwen (mhpmcnt17h_wen ), + .cnt_output (mhpmcnt17_value ), + .cnt_wen (mhpmcnt17_wen ), + .cp0_hpcp_icg_en (cp0_hpcp_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .hpcp_wdata (hpcp_wdata ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Instance("pa_hpcp_cnt_dummy", "x_hpcp_mhpmcnt17"); @627 +// &Connect(.clk_en (mhpmcnt17_clk_en), @629 +// .cnt_en (mhpmcnt17_cnt_en), @630 +// .cnt_wen (mhpmcnt17_wen), @631 +// .cnt_hwen (mhpmcnt17h_wen), @632 +// .cnt_adder (mhpmcnt17_adder), @633 +// .cnt_output (mhpmcnt17_value)); @634 + +//========================================================== +// Read Operation +//========================================================== +// &CombBeg; @639 +always @( mhpmcnt14_value[63:0] + or mhpmevt16_value[31:0] + or mhpmcnt9_value[63:0] + or mhpmevt13_value[31:0] + or mhpmevt4_value[31:0] + or sysio_hpcp_time[63:0] + or mcntinhbt_value[31:0] + or mcycle_value[63:0] + or cp0_hpcp_index[11:0] + or mhpmcnt4_value[63:0] + or mhpmevt3_value[31:0] + or mhpmcnt16_value[63:0] + or mhpmevt15_value[31:0] + or mhpmevt9_value[31:0] + or mhpmcnt17_value[63:0] + or minstret_value[63:0] + or mhpmcnt15_value[63:0] + or mhpmcnt8_value[63:0] + or mhpmcnt13_value[63:0] + or mhpmcnt3_value[63:0] + or mhpmevt14_value[31:0] + or mhpmevt8_value[31:0] + or mhpmevt17_value[31:0]) +begin + case(cp0_hpcp_index[11:0]) + MCNTINHBT : data_out[31:0] = mcntinhbt_value[31:0]; + MHPMEVT3 : data_out[31:0] = mhpmevt3_value[31:0]; + MHPMEVT4 : data_out[31:0] = mhpmevt4_value[31:0]; + MHPMEVT8 : data_out[31:0] = mhpmevt8_value[31:0]; + MHPMEVT9 : data_out[31:0] = mhpmevt9_value[31:0]; + MHPMEVT13 : data_out[31:0] = mhpmevt13_value[31:0]; + MHPMEVT14 : data_out[31:0] = mhpmevt14_value[31:0]; + MHPMEVT15 : data_out[31:0] = mhpmevt15_value[31:0]; + MHPMEVT16 : data_out[31:0] = mhpmevt16_value[31:0]; + MHPMEVT17 : data_out[31:0] = mhpmevt17_value[31:0]; + + MCYCLE : data_out[31:0] = mcycle_value[31:0]; + MINSTRET : data_out[31:0] = minstret_value[31:0]; + MHPMCNT3 : data_out[31:0] = mhpmcnt3_value[31:0]; + MHPMCNT4 : data_out[31:0] = mhpmcnt4_value[31:0]; + MHPMCNT8 : data_out[31:0] = mhpmcnt8_value[31:0]; + MHPMCNT9 : data_out[31:0] = mhpmcnt9_value[31:0]; + MHPMCNT13 : data_out[31:0] = mhpmcnt13_value[31:0]; + MHPMCNT14 : data_out[31:0] = mhpmcnt14_value[31:0]; + MHPMCNT15 : data_out[31:0] = mhpmcnt15_value[31:0]; + MHPMCNT16 : data_out[31:0] = mhpmcnt16_value[31:0]; + MHPMCNT17 : data_out[31:0] = mhpmcnt17_value[31:0]; + + MCYCLEH : data_out[31:0] = mcycle_value[63:32]; + MINSTRETH : data_out[31:0] = minstret_value[63:32]; + MHPMCNT3H : data_out[31:0] = mhpmcnt3_value[63:32]; + MHPMCNT4H : data_out[31:0] = mhpmcnt4_value[63:32]; + MHPMCNT8H : data_out[31:0] = mhpmcnt8_value[63:32]; + MHPMCNT9H : data_out[31:0] = mhpmcnt9_value[63:32]; + MHPMCNT13H : data_out[31:0] = mhpmcnt13_value[63:32]; + MHPMCNT14H : data_out[31:0] = mhpmcnt14_value[63:32]; + MHPMCNT15H : data_out[31:0] = mhpmcnt15_value[63:32]; + MHPMCNT16H : data_out[31:0] = mhpmcnt16_value[63:32]; + MHPMCNT17H : data_out[31:0] = mhpmcnt17_value[63:32]; + + CYCLE : data_out[31:0] = mcycle_value[31:0]; + REG_TIME : data_out[31:0] = sysio_hpcp_time[31:0]; + INSTRET : data_out[31:0] = minstret_value[31:0]; + HPMCNT3 : data_out[31:0] = mhpmcnt3_value[31:0]; + HPMCNT4 : data_out[31:0] = mhpmcnt4_value[31:0]; + HPMCNT8 : data_out[31:0] = mhpmcnt8_value[31:0]; + HPMCNT9 : data_out[31:0] = mhpmcnt9_value[31:0]; + HPMCNT13 : data_out[31:0] = mhpmcnt13_value[31:0]; + HPMCNT14 : data_out[31:0] = mhpmcnt14_value[31:0]; + HPMCNT15 : data_out[31:0] = mhpmcnt15_value[31:0]; + HPMCNT16 : data_out[31:0] = mhpmcnt16_value[31:0]; + HPMCNT17 : data_out[31:0] = mhpmcnt17_value[31:0]; + + CYCLEH : data_out[31:0] = mcycle_value[63:32]; + REG_TIMEH : data_out[31:0] = sysio_hpcp_time[63:32]; + INSTRETH : data_out[31:0] = minstret_value[63:32]; + HPMCNT3H : data_out[31:0] = mhpmcnt3_value[63:32]; + HPMCNT4H : data_out[31:0] = mhpmcnt4_value[63:32]; + HPMCNT8H : data_out[31:0] = mhpmcnt8_value[63:32]; + HPMCNT9H : data_out[31:0] = mhpmcnt9_value[63:32]; + HPMCNT13H : data_out[31:0] = mhpmcnt13_value[63:32]; + HPMCNT14H : data_out[31:0] = mhpmcnt14_value[63:32]; + HPMCNT15H : data_out[31:0] = mhpmcnt15_value[63:32]; + HPMCNT16H : data_out[31:0] = mhpmcnt16_value[63:32]; + HPMCNT17H : data_out[31:0] = mhpmcnt17_value[63:32]; + default : data_out[31:0] = 32'b0; + endcase +// &CombEnd; @703 +end + +//========================================================== +// Output to CP0 +//========================================================== +assign hpcp_cp0_data[31:0] = data_out[31:0]; + +//========================================================== +// Output to IFU +//========================================================== +//assign hpcp_ifu_cnt_en = mhpmcnt3_en +// || mhpmcnt4_en; + +//========================================================== +// Output to IDU +//========================================================== +//assign hpcp_idu_cnt_en = mhpmcnt22_en +// || mhpmcnt23_en +// || mhpmcnt24_en; + +//========================================================== +// Output to RTU +//========================================================== +//assign hpcp_rtu_cnt_en = minstret_en +// || mhpmcnt8_en +// || mhpmcnt9_en +// || mhpmcnt13_en; + +//========================================================== +// Output to LSU +//========================================================== +//assign hpcp_lsu_cnt_en = mhpmcnt14_en +// || mhpmcnt15_en +// || mhpmcnt16_en +// || mhpmcnt17_en; + + +// &ModuleEnd; @740 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rst/rtl/pa_rst_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rst/rtl/pa_rst_top.v new file mode 100644 index 0000000000000000000000000000000000000000..a13cd9014384e4ba52dc161d1f2272318dc67157 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rst/rtl/pa_rst_top.v @@ -0,0 +1,97 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module pa_rst_top( + cpurst_b, + forever_cpuclk, + pad_cpu_rst_b, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + sync_sys_apb_rst_b, + sys_apb_clk, + sys_apb_rst_b +); + +// &Ports; @23 +input forever_cpuclk; +input pad_cpu_rst_b; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input sys_apb_clk; +input sys_apb_rst_b; +output cpurst_b; +output sync_sys_apb_rst_b; + +// &Regs; @24 +reg ciu_rst_ff_1st; +reg ciu_rst_ff_2nd; +reg ciu_rst_ff_3rd; +reg sys_apb_rst_ff_1st; + +// &Wires; @25 +wire async_apb_rst_b; +wire async_ciu_rst_b; +wire cpurst_b; +wire forever_cpuclk; +wire pad_cpu_rst_b; +wire pad_yy_scan_mode; +wire pad_yy_scan_rst_b; +wire sync_sys_apb_rst_b; +wire sys_apb_clk; +wire sys_apb_rst_b; + + +assign async_ciu_rst_b = pad_cpu_rst_b;// & !pad_yy_mbist_mode; + +always @(posedge forever_cpuclk or negedge async_ciu_rst_b) +begin + if (!async_ciu_rst_b) + begin + ciu_rst_ff_1st <= 1'b0; + ciu_rst_ff_2nd <= 1'b0; + ciu_rst_ff_3rd <= 1'b0; + end + else + begin + ciu_rst_ff_1st <= 1'b1; + ciu_rst_ff_2nd <= ciu_rst_ff_1st; + ciu_rst_ff_3rd <= ciu_rst_ff_2nd; + end +end + +assign cpurst_b = pad_yy_scan_mode ? pad_yy_scan_rst_b : ciu_rst_ff_3rd; +//assign hadrst_b = pad_yy_scan_mode ? pad_yy_scan_rst_b : pad_had_rst_b; +//assign trst_b = pad_yy_scan_mode ? pad_yy_scan_rst_b : pad_had_jtg_trst_b; + + +assign async_apb_rst_b = sys_apb_rst_b;// & !pad_yy_mbist_mode; + +always @(posedge sys_apb_clk or negedge async_apb_rst_b) +begin + if (!async_apb_rst_b) + sys_apb_rst_ff_1st <= 1'b0; + else + sys_apb_rst_ff_1st <= 1'b1; +end + + +assign sync_sys_apb_rst_b = pad_yy_scan_mode ? pad_yy_scan_rst_b : sys_apb_rst_ff_1st; + + +// &ModuleEnd; @77 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_cbus.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_cbus.v new file mode 100644 index 0000000000000000000000000000000000000000..b754b3e752ddaaac8dd9cdcfa105866933c9dc8f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_cbus.v @@ -0,0 +1,972 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("pa_dtu_cfig.h"); @23 +// &Depend("cpu_cfig.h"); @24 + +// &ModuleBeg; @26 +module pa_rtu_cbus( + cbus_int_ex1_split_inst, + cbus_int_ipop_int_mask, + cbus_int_ipush_mie_en, + cbus_retire_ex2_chgflw_vld, + cbus_retire_ex2_cur_pc, + cbus_retire_ex2_expt_inst, + cbus_retire_ex2_flush, + cbus_retire_ex2_halt_info, + cbus_retire_ex2_inst_branch, + cbus_retire_ex2_inst_dret, + cbus_retire_ex2_inst_ebreak, + cbus_retire_ex2_inst_int, + cbus_retire_ex2_inst_mret, + cbus_retire_ex2_inst_nmi, + cbus_retire_ex2_inst_tail_int, + cbus_retire_ex2_inst_vld, + cbus_retire_ex2_int_hv, + cbus_retire_ex2_int_lv, + cbus_retire_ex2_ipop_int_mask, + cbus_retire_ex2_may_debug, + cbus_retire_ex2_next_pc, + cbus_retire_ex2_split_inst, + cbus_retire_ex2_tail_spec_inst, + cbus_retire_ex2_trap_vec, + cbus_retire_ex2_tval, + cbus_top_ex2_inst_vld, + cbus_top_ex2_uncommit_stall, + cp0_rtu_ex1_chgflw_pc, + cp0_rtu_ex1_chgflw_vld, + cp0_rtu_ex1_cmplt, + cp0_rtu_ex1_cmplt_dp, + cp0_rtu_ex1_dret, + cp0_rtu_ex1_ebreak, + cp0_rtu_ex1_expt_inst, + cp0_rtu_ex1_expt_tval, + cp0_rtu_ex1_expt_vec, + cp0_rtu_ex1_flush, + cp0_rtu_ex1_halt_info, + cp0_rtu_ex1_inst_len, + cp0_rtu_ex1_inst_vld, + cp0_rtu_ex1_ipush_spec_fail, + cp0_rtu_ex1_mret, + cp0_rtu_ex1_split_inst, + cp0_rtu_ex1_tail_fail, + cp0_rtu_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ifu_rtu_warm_up, + int_cbus_ex1_int_vld, + int_cbus_ex1_nmi_req, + int_cbus_int_hv, + int_xx_int_id, + int_xx_int_lv, + iu_rtu_ex1_bju_branch_inst, + iu_rtu_ex1_bju_cmplt, + iu_rtu_ex1_bju_cmplt_dp, + iu_rtu_ex1_bju_cur_pc, + iu_rtu_ex1_bju_inst_len, + iu_rtu_ex1_bju_inst_vld, + iu_rtu_ex1_bju_split_inst, + iu_rtu_ex1_cmplt, + iu_rtu_ex1_cmplt_dp, + iu_rtu_ex1_inst_len, + iu_rtu_ex1_inst_vld, + iu_rtu_ex1_ipop_int_mask, + iu_rtu_ex1_ipush_mie_en, + iu_rtu_ex1_ipush_spec_fail, + iu_rtu_ex1_next_pc, + iu_rtu_ex1_split_inst, + iu_rtu_ex1_tail_int_vld, + iu_rtu_ex2_bju_flush, + iu_rtu_ex2_bju_next_pc, + iu_rtu_ex2_bju_next_pc_vld, + lsu_rtu_async_expt_vld, + lsu_rtu_ex1_cmplt, + lsu_rtu_ex1_cmplt_dp, + lsu_rtu_ex1_halt_info, + lsu_rtu_ex1_inst_len, + lsu_rtu_ex1_inst_vld, + lsu_rtu_ex1_ipop_int_mask, + lsu_rtu_ex1_ipush_spec_inst, + lsu_rtu_ex1_split_inst, + lsu_rtu_ex2_expt_inst, + lsu_rtu_ex2_expt_vec, + lsu_rtu_ex2_tval, + pad_yy_icg_scan_en, + retire_cbus_debug_may_spec_fail, + retire_cbus_ex2_stall, + retire_cbus_flush_stall, + rtu_cp0_mie_en, + rtu_cp0_mie_gateclk_en, + rtu_idu_ex1_int_dis_stall_gateclk_req, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_ex2_ipush_spec_inst_expt_vld, + rtu_idu_ex2_ipush_spec_inst_halt_info_vld, + rtu_iu_bju_ex2_cur_pc, + rtu_iu_ex1_cmplt_dp_vld, + rtu_iu_ex1_cmplt_inst_len, + rtu_iu_ex1_cmplt_split_inst, + rtu_iu_ex1_cmplt_vld, + rtu_iu_pending_spec_expt_vld, + rtu_iu_pending_spec_halt_info_vld, + rtu_xx_ex1_stall, + rtu_yy_xx_flush +); + +// &Ports; @27 +input [30:0] cp0_rtu_ex1_chgflw_pc; +input cp0_rtu_ex1_chgflw_vld; +input cp0_rtu_ex1_cmplt; +input cp0_rtu_ex1_cmplt_dp; +input cp0_rtu_ex1_dret; +input cp0_rtu_ex1_ebreak; +input cp0_rtu_ex1_expt_inst; +input [31:0] cp0_rtu_ex1_expt_tval; +input [3 :0] cp0_rtu_ex1_expt_vec; +input cp0_rtu_ex1_flush; +input [14:0] cp0_rtu_ex1_halt_info; +input cp0_rtu_ex1_inst_len; +input cp0_rtu_ex1_inst_vld; +input cp0_rtu_ex1_ipush_spec_fail; +input cp0_rtu_ex1_mret; +input cp0_rtu_ex1_split_inst; +input cp0_rtu_ex1_tail_fail; +input cp0_rtu_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ifu_rtu_warm_up; +input int_cbus_ex1_int_vld; +input int_cbus_ex1_nmi_req; +input int_cbus_int_hv; +input [11:0] int_xx_int_id; +input [7 :0] int_xx_int_lv; +input iu_rtu_ex1_bju_branch_inst; +input iu_rtu_ex1_bju_cmplt; +input iu_rtu_ex1_bju_cmplt_dp; +input [30:0] iu_rtu_ex1_bju_cur_pc; +input iu_rtu_ex1_bju_inst_len; +input iu_rtu_ex1_bju_inst_vld; +input iu_rtu_ex1_bju_split_inst; +input iu_rtu_ex1_cmplt; +input iu_rtu_ex1_cmplt_dp; +input iu_rtu_ex1_inst_len; +input iu_rtu_ex1_inst_vld; +input iu_rtu_ex1_ipop_int_mask; +input iu_rtu_ex1_ipush_mie_en; +input iu_rtu_ex1_ipush_spec_fail; +input [30:0] iu_rtu_ex1_next_pc; +input iu_rtu_ex1_split_inst; +input iu_rtu_ex1_tail_int_vld; +input iu_rtu_ex2_bju_flush; +input [30:0] iu_rtu_ex2_bju_next_pc; +input iu_rtu_ex2_bju_next_pc_vld; +input lsu_rtu_async_expt_vld; +input lsu_rtu_ex1_cmplt; +input lsu_rtu_ex1_cmplt_dp; +input [14:0] lsu_rtu_ex1_halt_info; +input lsu_rtu_ex1_inst_len; +input lsu_rtu_ex1_inst_vld; +input lsu_rtu_ex1_ipop_int_mask; +input lsu_rtu_ex1_ipush_spec_inst; +input lsu_rtu_ex1_split_inst; +input lsu_rtu_ex2_expt_inst; +input [3 :0] lsu_rtu_ex2_expt_vec; +input [31:0] lsu_rtu_ex2_tval; +input pad_yy_icg_scan_en; +input retire_cbus_debug_may_spec_fail; +input retire_cbus_ex2_stall; +input retire_cbus_flush_stall; +input rtu_yy_xx_flush; +output cbus_int_ex1_split_inst; +output cbus_int_ipop_int_mask; +output cbus_int_ipush_mie_en; +output cbus_retire_ex2_chgflw_vld; +output [31:0] cbus_retire_ex2_cur_pc; +output cbus_retire_ex2_expt_inst; +output cbus_retire_ex2_flush; +output [14:0] cbus_retire_ex2_halt_info; +output cbus_retire_ex2_inst_branch; +output cbus_retire_ex2_inst_dret; +output cbus_retire_ex2_inst_ebreak; +output cbus_retire_ex2_inst_int; +output cbus_retire_ex2_inst_mret; +output cbus_retire_ex2_inst_nmi; +output cbus_retire_ex2_inst_tail_int; +output cbus_retire_ex2_inst_vld; +output cbus_retire_ex2_int_hv; +output [7 :0] cbus_retire_ex2_int_lv; +output cbus_retire_ex2_ipop_int_mask; +output cbus_retire_ex2_may_debug; +output [31:0] cbus_retire_ex2_next_pc; +output cbus_retire_ex2_split_inst; +output cbus_retire_ex2_tail_spec_inst; +output [11:0] cbus_retire_ex2_trap_vec; +output [31:0] cbus_retire_ex2_tval; +output cbus_top_ex2_inst_vld; +output cbus_top_ex2_uncommit_stall; +output rtu_cp0_mie_en; +output rtu_cp0_mie_gateclk_en; +output rtu_idu_ex1_int_dis_stall_gateclk_req; +output rtu_idu_ex1_int_dis_stall_req; +output rtu_idu_ex2_ipush_spec_inst_expt_vld; +output rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +output [31:0] rtu_iu_bju_ex2_cur_pc; +output rtu_iu_ex1_cmplt_dp_vld; +output rtu_iu_ex1_cmplt_inst_len; +output rtu_iu_ex1_cmplt_split_inst; +output rtu_iu_ex1_cmplt_vld; +output rtu_iu_pending_spec_expt_vld; +output rtu_iu_pending_spec_halt_info_vld; +output rtu_xx_ex1_stall; + +// &Regs; @28 +reg [11:0] cbus_ex1_trap_vec; +reg [31:0] cbus_ex1_tval; +reg cbus_ex2_chgflw_vld; +reg [30:0] cbus_ex2_cur_pc; +reg cbus_ex2_dret; +reg cbus_ex2_ebreak; +reg cbus_ex2_expt_inst; +reg cbus_ex2_flush; +reg [14:0] cbus_ex2_halt_info; +reg cbus_ex2_inst_branch; +reg cbus_ex2_inst_int; +reg cbus_ex2_inst_tail_int; +reg [3 :0] cbus_ex2_inst_type; +reg cbus_ex2_inst_vld; +reg cbus_ex2_int_hv; +reg [7 :0] cbus_ex2_int_lv; +reg cbus_ex2_ipop_int_mask; +reg cbus_ex2_ipush_spec_inst; +reg cbus_ex2_may_debug; +reg cbus_ex2_may_spec_fail; +reg cbus_ex2_mret; +reg [30:0] cbus_ex2_next_pc; +reg cbus_ex2_nmi; +reg cbus_ex2_pending_spec_expt; +reg cbus_ex2_pending_spec_halt_info; +reg [14:0] cbus_ex2_pending_spec_halt_info_data; +reg cbus_ex2_split_inst; +reg cbus_ex2_tail_spec_inst; +reg [11:0] cbus_ex2_trap_vec; +reg [31:0] cbus_ex2_tval; + +// &Wires; @29 +wire [3 :0] cbus_cmplt; +wire [3 :0] cbus_cmplt_dp; +wire cbus_cmplt_dp_vld; +wire cbus_cmplt_vld; +wire cbus_ex1_chgflw_vld; +wire [30:0] cbus_ex1_cur_pc; +wire cbus_ex1_dret; +wire cbus_ex1_ebreak; +wire cbus_ex1_expt_inst; +wire [3 :0] cbus_ex1_expt_vec; +wire cbus_ex1_flush; +wire [14:0] cbus_ex1_halt_info; +wire [3 :0] cbus_ex1_inst; +wire cbus_ex1_inst_branch; +wire cbus_ex1_inst_int; +wire cbus_ex1_inst_len; +wire cbus_ex1_inst_tail_int; +wire cbus_ex1_inst_vld; +wire cbus_ex1_int_hv; +wire [7 :0] cbus_ex1_int_lv; +wire [11:0] cbus_ex1_int_vec; +wire cbus_ex1_ipop_int_mask; +wire cbus_ex1_ipush_mie_en; +wire cbus_ex1_ipush_mie_gateclk_en; +wire cbus_ex1_ipush_spec_fail; +wire cbus_ex1_ipush_spec_inst; +wire cbus_ex1_may_spec_fail; +wire cbus_ex1_may_spec_fail_debug; +wire cbus_ex1_mret; +wire [30:0] cbus_ex1_next_pc; +wire cbus_ex1_nmi; +wire cbus_ex1_pending_spec_expt_clr; +wire cbus_ex1_pending_spec_halt_info_clr; +wire cbus_ex1_split_inst; +wire cbus_ex1_tail_fail; +wire cbus_ex1_tail_int_vld; +wire cbus_ex1_tail_spec_inst; +wire cbus_ex2_pending_spec_expt_set; +wire cbus_ex2_pending_spec_halt_info_set; +wire cbus_ex2_uncommit_stall; +wire cbus_int_ex1_split_inst; +wire cbus_int_ipop_int_mask; +wire cbus_int_ipush_mie_en; +wire cbus_retire_ex2_chgflw_vld; +wire [31:0] cbus_retire_ex2_cur_pc; +wire cbus_retire_ex2_expt_inst; +wire cbus_retire_ex2_flush; +wire [14:0] cbus_retire_ex2_halt_info; +wire cbus_retire_ex2_inst_branch; +wire cbus_retire_ex2_inst_dret; +wire cbus_retire_ex2_inst_ebreak; +wire cbus_retire_ex2_inst_int; +wire cbus_retire_ex2_inst_mret; +wire cbus_retire_ex2_inst_nmi; +wire cbus_retire_ex2_inst_tail_int; +wire cbus_retire_ex2_inst_vld; +wire cbus_retire_ex2_int_hv; +wire [7 :0] cbus_retire_ex2_int_lv; +wire cbus_retire_ex2_ipop_int_mask; +wire cbus_retire_ex2_may_debug; +wire [31:0] cbus_retire_ex2_next_pc; +wire cbus_retire_ex2_split_inst; +wire cbus_retire_ex2_tail_spec_inst; +wire [11:0] cbus_retire_ex2_trap_vec; +wire [31:0] cbus_retire_ex2_tval; +wire cbus_top_ex2_inst_vld; +wire cbus_top_ex2_uncommit_stall; +wire [30:0] cp0_rtu_ex1_chgflw_pc; +wire cp0_rtu_ex1_chgflw_vld; +wire cp0_rtu_ex1_cmplt; +wire cp0_rtu_ex1_cmplt_dp; +wire cp0_rtu_ex1_dret; +wire cp0_rtu_ex1_ebreak; +wire cp0_rtu_ex1_expt_inst; +wire [31:0] cp0_rtu_ex1_expt_tval; +wire [3 :0] cp0_rtu_ex1_expt_vec; +wire cp0_rtu_ex1_flush; +wire [14:0] cp0_rtu_ex1_halt_info; +wire cp0_rtu_ex1_inst_len; +wire cp0_rtu_ex1_inst_vld; +wire cp0_rtu_ex1_ipush_spec_fail; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_ex1_split_inst; +wire cp0_rtu_ex1_tail_fail; +wire cp0_rtu_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire ifu_rtu_warm_up; +wire int_cbus_ex1_int_vld; +wire int_cbus_ex1_nmi_req; +wire int_cbus_int_hv; +wire [11:0] int_xx_int_id; +wire [7 :0] int_xx_int_lv; +wire iu_rtu_ex1_bju_branch_inst; +wire iu_rtu_ex1_bju_cmplt; +wire iu_rtu_ex1_bju_cmplt_dp; +wire [30:0] iu_rtu_ex1_bju_cur_pc; +wire iu_rtu_ex1_bju_inst_len; +wire iu_rtu_ex1_bju_inst_vld; +wire iu_rtu_ex1_bju_split_inst; +wire iu_rtu_ex1_cmplt; +wire iu_rtu_ex1_cmplt_dp; +wire iu_rtu_ex1_inst_len; +wire iu_rtu_ex1_inst_vld; +wire iu_rtu_ex1_ipop_int_mask; +wire iu_rtu_ex1_ipush_mie_en; +wire iu_rtu_ex1_ipush_spec_fail; +wire [30:0] iu_rtu_ex1_next_pc; +wire iu_rtu_ex1_split_inst; +wire iu_rtu_ex1_tail_int_vld; +wire iu_rtu_ex2_bju_flush; +wire [30:0] iu_rtu_ex2_bju_next_pc; +wire iu_rtu_ex2_bju_next_pc_vld; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_ex1_cmplt; +wire lsu_rtu_ex1_cmplt_dp; +wire [14:0] lsu_rtu_ex1_halt_info; +wire lsu_rtu_ex1_inst_len; +wire lsu_rtu_ex1_inst_vld; +wire lsu_rtu_ex1_ipop_int_mask; +wire lsu_rtu_ex1_ipush_spec_inst; +wire lsu_rtu_ex1_split_inst; +wire lsu_rtu_ex2_expt_inst; +wire [3 :0] lsu_rtu_ex2_expt_vec; +wire [31:0] lsu_rtu_ex2_tval; +wire pad_yy_icg_scan_en; +wire retire_cbus_debug_may_spec_fail; +wire retire_cbus_ex2_stall; +wire retire_cbus_flush_stall; +wire retire_ex2_clk; +wire retire_ex2_clk_en; +wire retire_ex2_expt_clk; +wire retire_ex2_expt_clk_en; +wire rtu_cp0_mie_en; +wire rtu_cp0_mie_gateclk_en; +wire rtu_idu_ex1_int_dis_stall_gateclk_req; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_ex2_ipush_spec_inst_expt_vld; +wire rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +wire [31:0] rtu_iu_bju_ex2_cur_pc; +wire rtu_iu_ex1_cmplt_dp_vld; +wire rtu_iu_ex1_cmplt_inst_len; +wire rtu_iu_ex1_cmplt_split_inst; +wire rtu_iu_ex1_cmplt_vld; +wire rtu_iu_pending_spec_expt_vld; +wire rtu_iu_pending_spec_halt_info_vld; +wire rtu_xx_ex1_stall; +wire rtu_yy_xx_flush; + + +//========================================================== +// Parameters +//========================================================== +parameter IU = 0; +parameter BJU = 1; +parameter LSU = 2; +parameter CP0 = 3; + +//========================================================== +// Complete Bus +//========================================================== +//---------------------------------------------------------- +// Valid Signals +//---------------------------------------------------------- +assign cbus_cmplt[IU] = iu_rtu_ex1_cmplt; +assign cbus_cmplt[BJU] = iu_rtu_ex1_bju_cmplt; +assign cbus_cmplt[LSU] = lsu_rtu_ex1_cmplt; +assign cbus_cmplt[CP0] = cp0_rtu_ex1_cmplt; + +assign cbus_cmplt_dp[IU] = iu_rtu_ex1_cmplt_dp; +assign cbus_cmplt_dp[BJU] = iu_rtu_ex1_bju_cmplt_dp; +assign cbus_cmplt_dp[LSU] = lsu_rtu_ex1_cmplt_dp; +assign cbus_cmplt_dp[CP0] = cp0_rtu_ex1_cmplt_dp; + +assign cbus_ex1_inst[IU] = iu_rtu_ex1_inst_vld; +assign cbus_ex1_inst[BJU] = iu_rtu_ex1_bju_inst_vld; +assign cbus_ex1_inst[LSU] = lsu_rtu_ex1_inst_vld; +assign cbus_ex1_inst[CP0] = cp0_rtu_ex1_inst_vld; + +// &Force("nonport","cbus_ex1_inst_vld"); @60 +assign cbus_cmplt_vld = |cbus_cmplt[3:0]; +assign cbus_cmplt_dp_vld = |cbus_cmplt_dp[3:0]; +assign cbus_ex1_inst_vld = |cbus_ex1_inst[3:0]; + +assign rtu_iu_ex1_cmplt_vld = cbus_cmplt_vld && !retire_cbus_ex2_stall; +assign rtu_iu_ex1_cmplt_dp_vld = cbus_cmplt_dp_vld; + +//---------------------------------------------------------- +// PC and Change Flow +//---------------------------------------------------------- +assign cbus_ex1_cur_pc[30:0] = iu_rtu_ex1_bju_cur_pc[30:0]; + +//bju change flow pc will be muxed in EX2 due to timing +assign cbus_ex1_chgflw_vld = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_chgflw_vld; + +// //&Force("bus","iu_rtu_ex1_next_pc",31,0); @77 +assign cbus_ex1_next_pc[30:0] = + cbus_ex1_chgflw_vld ? cp0_rtu_ex1_chgflw_pc[30:0] + : iu_rtu_ex1_next_pc[30:0]; + +//---------------------------------------------------------- +// Instruction Type +//---------------------------------------------------------- +assign cbus_ex1_split_inst = + cbus_cmplt_dp[IU] && iu_rtu_ex1_split_inst + || cbus_cmplt_dp[BJU] && iu_rtu_ex1_bju_split_inst + || cbus_cmplt_dp[LSU] && lsu_rtu_ex1_split_inst + || cbus_cmplt_dp[CP0] && cp0_rtu_ex1_split_inst; + +assign cbus_ex1_inst_len = + cbus_cmplt_dp[IU] && iu_rtu_ex1_inst_len + || cbus_cmplt_dp[BJU] && iu_rtu_ex1_bju_inst_len + || cbus_cmplt_dp[LSU] && lsu_rtu_ex1_inst_len + || cbus_cmplt_dp[CP0] && cp0_rtu_ex1_inst_len; + +assign cbus_ex1_inst_branch = + cbus_cmplt_dp[BJU] && iu_rtu_ex1_bju_branch_inst; + +assign cbus_ex1_mret = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_mret; + +assign cbus_ex1_ebreak = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_ebreak; + +assign cbus_ex1_dret = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_dret; + +assign cbus_ex1_flush = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_flush; + +assign cbus_int_ex1_split_inst = cbus_ex1_split_inst; +assign rtu_iu_ex1_cmplt_inst_len = cbus_ex1_inst_len; +assign rtu_iu_ex1_cmplt_split_inst = cbus_ex1_split_inst; + +//---------------------------------------------------------- +// Debug Info +//---------------------------------------------------------- +assign cbus_ex1_halt_info[`TDT_HINFO_WIDTH-1:0] = + {`TDT_HINFO_WIDTH{cbus_cmplt_dp[LSU]}} & lsu_rtu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0] + | {`TDT_HINFO_WIDTH{cbus_cmplt_dp[CP0]}} & cp0_rtu_ex1_halt_info[`TDT_HINFO_WIDTH-1:0]; + +//---------------------------------------------------------- +// Exception +//---------------------------------------------------------- +//lsu expt will be muxed in EX2 +assign cbus_ex1_expt_inst = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_expt_inst; + +assign cbus_ex1_expt_vec[3:0] = + {4{cbus_cmplt_dp[CP0]}} & cp0_rtu_ex1_expt_vec[3:0]; + +// &CombBeg; @133 +always @( lsu_rtu_ex2_tval[31:0] + or cbus_ex2_tval[31:0] + or cbus_ex2_inst_type[2] + or cbus_cmplt_dp[3] + or cp0_rtu_ex1_expt_tval[31:0] + or cbus_ex2_inst_int) +begin + if(cbus_cmplt_dp[CP0]) + cbus_ex1_tval[31:0] = cp0_rtu_ex1_expt_tval[31:0]; + //if lsu inst generate pending expt, save lsu expt info for new + //spec inst pending expt which may not be lsu inst (cannot mux expt + //info from lsu) + else if(cbus_ex2_inst_type[LSU] && !cbus_ex2_inst_int) + cbus_ex1_tval[31:0] = lsu_rtu_ex2_tval[31:0]; + //if no expt inst cmplt, hold expt info for spec inst pending expt + else + cbus_ex1_tval[31:0] = cbus_ex2_tval[31:0]; +// &CombEnd; @144 +end + +//---------------------------------------------------------- +// Interrupt +//---------------------------------------------------------- +assign cbus_ex1_inst_int = int_cbus_ex1_int_vld; +assign cbus_ex1_nmi = int_cbus_ex1_nmi_req; +assign cbus_ex1_int_vec[11:0] = int_xx_int_id[11:0]; +assign cbus_ex1_int_hv = int_cbus_int_hv; +assign cbus_ex1_int_lv[7:0] = int_xx_int_lv[7:0]; + +// &CombBeg; @155 +always @( lsu_rtu_ex2_expt_vec[3:0] + or cbus_ex1_expt_inst + or cbus_ex2_inst_type[2] + or cbus_ex2_trap_vec[11:0] + or cbus_ex1_expt_vec[3:0] + or cbus_ex1_inst_int + or cbus_ex1_int_vec[11:0] + or cbus_ex2_inst_int) +begin + if(cbus_ex1_inst_int) + cbus_ex1_trap_vec[11:0] = cbus_ex1_int_vec[11:0]; + else if(cbus_ex1_expt_inst) + cbus_ex1_trap_vec[11:0] = {8'b0, cbus_ex1_expt_vec[3:0]}; + //if lsu inst generate pending expt, save lsu expt info for new + //spec inst pending expt which may not be lsu inst (cannot mux expt + //info from lsu) + else if(cbus_ex2_inst_type[LSU] && !cbus_ex2_inst_int) + cbus_ex1_trap_vec[11:0] = {8'b0, lsu_rtu_ex2_expt_vec[3:0]}; + //if no expt inst cmplt, hold expt info for spec inst pending expt + else + cbus_ex1_trap_vec[11:0] = cbus_ex2_trap_vec[11:0]; +// &CombEnd; @168 +end + +//---------------------------------------------------------- +// Tail Inst and Int +//---------------------------------------------------------- +//if spec inst generate exception, pending this exception +//and take no action when retire +assign cbus_ex1_ipush_spec_inst = + cbus_cmplt_dp[LSU] && lsu_rtu_ex1_ipush_spec_inst; + +//clear pending spec inst exception and take no action when retire +assign cbus_ex1_ipush_spec_fail = + cbus_cmplt_dp[CP0] & cp0_rtu_ex1_ipush_spec_fail + | cbus_cmplt_dp[IU] & iu_rtu_ex1_ipush_spec_fail; + +//freeze pc and take no action when retire +assign cbus_ex1_tail_fail = + cbus_cmplt_dp[CP0] && cp0_rtu_ex1_tail_fail; + +assign cbus_ex1_tail_int_vld = + cbus_cmplt_dp[IU] && iu_rtu_ex1_tail_int_vld; + +assign cbus_ex1_ipop_int_mask = + cbus_cmplt_dp[IU] && iu_rtu_ex1_ipop_int_mask + || cbus_cmplt_dp[LSU] && lsu_rtu_ex1_ipop_int_mask; + +assign cbus_ex1_ipush_mie_en = + cbus_cmplt_dp[IU] && iu_rtu_ex1_ipush_mie_en; + +assign cbus_ex1_ipush_mie_gateclk_en = + cbus_ex1_inst[IU] && iu_rtu_ex1_ipush_mie_en; + +assign cbus_ex1_inst_tail_int = cbus_ex1_tail_int_vld + && !cbus_ex1_nmi + && !cbus_ex1_inst_int; + +//take no action when retire: +//ignore any (async/sync) exception, interrupt and debug +assign cbus_ex1_tail_spec_inst = cbus_ex1_ipush_spec_inst + || cbus_ex1_ipush_spec_fail + || cbus_ex1_tail_fail; + +//if committed inst could cmplt in ex1 stage +assign rtu_cp0_mie_en = cbus_cmplt_vld + && cbus_ex1_ipush_mie_en; +// && !retire_xx_ex2_expt_raw; + +assign rtu_cp0_mie_gateclk_en = cbus_ex1_inst_vld + && cbus_ex1_ipush_mie_gateclk_en; +// && !retire_xx_ex2_expt_raw; + +//output to int +assign cbus_int_ipush_mie_en = cbus_ex1_ipush_mie_en; +assign cbus_int_ipop_int_mask = cbus_ex1_ipop_int_mask; + +//========================================================== +// EX1 May spec fail Signal +//========================================================== +assign cbus_ex1_may_spec_fail_debug = cbus_ex1_halt_info[`TDT_HINFO_MATCH] + || cbus_ex1_halt_info[`TDT_HINFO_PENDING_HALT] + || cbus_ex1_halt_info[`TDT_HINFO_CANCEL] + || cbus_ex1_ebreak; +//if ex1 instruction may produce speculation fail +//rtu should stall ex1 through uncommit stall when at ex2 stage +assign cbus_ex1_may_spec_fail = cbus_ex1_expt_inst + || cbus_ex1_flush + || cbus_ex1_may_spec_fail_debug + || cbus_ex1_chgflw_vld; + +//========================================================== +// EX2 Retire Info +//========================================================== +//---------------------------------------------------------- +// Gated Cell +//---------------------------------------------------------- +assign retire_ex2_clk_en = ifu_rtu_warm_up + || cbus_cmplt_dp_vld + || cbus_ex2_inst_vld + || cbus_ex2_pending_spec_expt + || cbus_ex2_pending_spec_halt_info; +// &Instance("gated_clk_cell", "x_retire_ex2_clk"); @248 +gated_clk_cell x_retire_ex2_clk ( + .clk_in (forever_cpuclk ), + .clk_out (retire_ex2_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (retire_ex2_clk_en ), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @249 +// .external_en (1'b0), @250 +// .global_en (cp0_yy_clk_en), @251 +// .module_en (cp0_rtu_icg_en), @252 +// .local_en (retire_ex2_clk_en), @253 +// .clk_out (retire_ex2_clk)); @254 + +assign retire_ex2_expt_clk_en = cbus_ex1_expt_inst + || cbus_ex1_inst_int + || cbus_ex1_halt_info[`TDT_HINFO_MATCH] + || cbus_ex1_halt_info[`TDT_HINFO_PENDING_HALT] + || cbus_ex1_halt_info[`TDT_HINFO_CANCEL] + || cbus_ex1_ebreak + || cbus_ex2_expt_inst + || cbus_retire_ex2_expt_inst; +// &Instance("gated_clk_cell", "x_retire_ex2_expt_clk"); @264 +gated_clk_cell x_retire_ex2_expt_clk ( + .clk_in (forever_cpuclk ), + .clk_out (retire_ex2_expt_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (retire_ex2_expt_clk_en), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ) +); + +// &Connect(.clk_in (forever_cpuclk), @265 +// .external_en (1'b0), @266 +// .global_en (cp0_yy_clk_en), @267 +// .module_en (cp0_rtu_icg_en), @268 +// .local_en (retire_ex2_expt_clk_en), @269 +// .clk_out (retire_ex2_expt_clk)); @270 + +//---------------------------------------------------------- +// Retire inst valid +//---------------------------------------------------------- +always @ (posedge retire_ex2_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + cbus_ex2_inst_vld <= 1'b0; + cbus_ex2_inst_type[3:0] <= 4'b0; + cbus_ex2_may_spec_fail <= 1'b0; + end + else if(!retire_cbus_ex2_stall) begin + cbus_ex2_inst_vld <= cbus_cmplt_vld; + cbus_ex2_inst_type[3:0] <= cbus_cmplt[3:0]; + cbus_ex2_may_spec_fail <= cbus_ex1_may_spec_fail; + end +end + +//---------------------------------------------------------- +// Retire inst information +//---------------------------------------------------------- +always @ (posedge retire_ex2_clk) +begin + if(ifu_rtu_warm_up || !retire_cbus_ex2_stall) begin + cbus_ex2_chgflw_vld <= cbus_ex1_chgflw_vld; + cbus_ex2_split_inst <= cbus_ex1_split_inst; + cbus_ex2_inst_branch <= cbus_ex1_inst_branch; + cbus_ex2_mret <= cbus_ex1_mret; + cbus_ex2_ebreak <= cbus_ex1_ebreak; + cbus_ex2_dret <= cbus_ex1_dret; + cbus_ex2_inst_int <= cbus_ex1_inst_int; + cbus_ex2_nmi <= cbus_ex1_nmi; + cbus_ex2_int_hv <= cbus_ex1_int_hv; + cbus_ex2_int_lv[7:0] <= cbus_ex1_int_lv[7:0]; + cbus_ex2_inst_tail_int <= cbus_ex1_inst_tail_int; + cbus_ex2_ipush_spec_inst <= cbus_ex1_ipush_spec_inst; + cbus_ex2_tail_spec_inst <= cbus_ex1_tail_spec_inst; + cbus_ex2_ipop_int_mask <= cbus_ex1_ipop_int_mask; + cbus_ex2_may_debug <= cbus_ex1_may_spec_fail_debug; + cbus_ex2_halt_info[`TDT_HINFO_WIDTH-1:0] <= + cbus_ex1_halt_info[`TDT_HINFO_WIDTH-1:0]; + end +end + +//reset expt inst and expt vector for less x: +//ex1 trap vec is ex2 trap vec when no expt +//avoid long x before expt inst +always @ (posedge retire_ex2_expt_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + cbus_ex2_expt_inst <= 1'b0; + cbus_ex2_tval[31:0] <= 32'b0; + cbus_ex2_trap_vec[11:0] <= 12'b0; + end + else if(!retire_cbus_ex2_stall) begin + cbus_ex2_expt_inst <= cbus_ex1_expt_inst; + cbus_ex2_tval[31:0] <= cbus_ex1_tval[31:0]; + cbus_ex2_trap_vec[11:0] <= cbus_ex1_trap_vec[11:0]; + end +end + +always @ (posedge retire_ex2_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cbus_ex2_flush <= 1'b0; + else if(!retire_cbus_ex2_stall) + cbus_ex2_flush <= cbus_ex1_flush; + //flush vld may be 0 when ex2 stall, rtu should save flush vld value + else if(cbus_ex2_inst_type[BJU] && iu_rtu_ex2_bju_flush) + cbus_ex2_flush <= 1'b1; +end + +//tail fail should hold pc value +always @ (posedge retire_ex2_clk) +begin + if(ifu_rtu_warm_up) + cbus_ex2_cur_pc[30:0] <= cbus_ex1_cur_pc[30:0]; + else if(cbus_ex1_tail_fail) + cbus_ex2_cur_pc[30:0] <= cbus_ex2_cur_pc[30:0]; + else if(!retire_cbus_ex2_stall && cbus_cmplt_dp_vld) + cbus_ex2_cur_pc[30:0] <= cbus_ex1_cur_pc[30:0]; +end + +//tail fail should hold pc value +always @ (posedge retire_ex2_clk) +begin + if(ifu_rtu_warm_up) + cbus_ex2_next_pc[30:0] <= cbus_ex1_next_pc[30:0]; + else if(cbus_ex1_tail_fail) + cbus_ex2_next_pc[30:0] <= cbus_ex2_next_pc[30:0]; + else if(!retire_cbus_ex2_stall) + cbus_ex2_next_pc[30:0] <= cbus_ex1_next_pc[30:0]; + //next pc vld may be 0 when ex2 stall, rtu should save next pc value + else if(cbus_ex2_inst_type[BJU] && iu_rtu_ex2_bju_next_pc_vld) + cbus_ex2_next_pc[30:0] <= iu_rtu_ex2_bju_next_pc[30:0]; +end + +//output to bju +assign rtu_iu_bju_ex2_cur_pc[31:0] = {cbus_ex2_cur_pc[30:0], 1'b0}; + +//---------------------------------------------------------- +// Output to Retire +//---------------------------------------------------------- +// &Force("output","cbus_retire_ex2_inst_nmi"); @448 +assign cbus_retire_ex2_inst_vld = cbus_ex2_inst_vld; +assign cbus_retire_ex2_cur_pc[31:0] = {cbus_ex2_cur_pc[30:0], 1'b0}; +assign cbus_retire_ex2_split_inst = cbus_ex2_split_inst; +assign cbus_retire_ex2_inst_branch = cbus_ex2_inst_branch; +assign cbus_retire_ex2_inst_mret = cbus_ex2_mret; +assign cbus_retire_ex2_inst_ebreak = cbus_ex2_ebreak; +assign cbus_retire_ex2_inst_dret = cbus_ex2_dret; +assign cbus_retire_ex2_inst_int = cbus_ex2_inst_int; +assign cbus_retire_ex2_chgflw_vld = cbus_ex2_chgflw_vld; +assign cbus_retire_ex2_inst_nmi = cbus_ex2_nmi; +assign cbus_retire_ex2_int_hv = cbus_ex2_int_hv; +assign cbus_retire_ex2_int_lv[7:0] = cbus_ex2_int_lv[7:0]; +assign cbus_retire_ex2_inst_tail_int = cbus_ex2_inst_tail_int; +assign cbus_retire_ex2_tail_spec_inst = cbus_ex2_tail_spec_inst; +assign cbus_retire_ex2_ipop_int_mask = cbus_ex2_ipop_int_mask; +assign cbus_retire_ex2_may_debug = cbus_ex2_may_debug; + +assign cbus_top_ex2_inst_vld = cbus_ex2_inst_vld; + +//---------------------------------------------------------- +// Halt Info MUX +//---------------------------------------------------------- +assign cbus_retire_ex2_halt_info[`TDT_HINFO_WIDTH-1:0] = + cbus_ex2_pending_spec_halt_info && !cbus_ex2_ipush_spec_inst + ? cbus_ex2_pending_spec_halt_info_data[`TDT_HINFO_WIDTH-1:0] + : cbus_ex2_halt_info[`TDT_HINFO_WIDTH-1:0]; + +//---------------------------------------------------------- +// BJU EX2 flush MUX +//---------------------------------------------------------- +assign cbus_retire_ex2_flush = cbus_ex2_inst_type[BJU] + ? cbus_ex2_flush || iu_rtu_ex2_bju_flush + : cbus_ex2_flush; + +//---------------------------------------------------------- +// BJU EX2 next PC MUX +//---------------------------------------------------------- +assign cbus_retire_ex2_next_pc[31:0] = cbus_ex2_inst_type[BJU] + && iu_rtu_ex2_bju_next_pc_vld + ? {iu_rtu_ex2_bju_next_pc[30:0], 1'b0} + : {cbus_ex2_next_pc[30:0], 1'b0}; + +//---------------------------------------------------------- +// LSU EX2 Exception MUX +//---------------------------------------------------------- +//mux with lsu ex2 exception signals +//lsu will hold expt info when ex2 stall (no new lsu inst cmplt) +//so do not need to save lsu ex2 expt info when ex2 stall +// &Force("output","cbus_retire_ex2_expt_inst"); @497 +//assign cbus_retire_ex2_expt_inst = cbus_ex2_inst_type[LSU] +// ? lsu_rtu_ex2_expt_inst +// : cbus_ex2_expt_inst; +assign cbus_retire_ex2_expt_inst = cbus_ex2_pending_spec_expt + && !cbus_ex2_ipush_spec_inst + || (cbus_ex2_inst_type[LSU] + ? lsu_rtu_ex2_expt_inst + : cbus_ex2_expt_inst); +assign cbus_retire_ex2_trap_vec[11:0] = cbus_ex2_inst_type[LSU] && !cbus_ex2_inst_int + ? {8'b0, lsu_rtu_ex2_expt_vec[3:0]} + : cbus_ex2_trap_vec[11:0]; +assign cbus_retire_ex2_tval[31:0] = cbus_ex2_inst_type[LSU] && !cbus_ex2_inst_int + ? lsu_rtu_ex2_tval[31:0] + : cbus_ex2_tval[31:0]; + +//========================================================== +// Pending Exception for spec inst +//========================================================== +//if spec inst retire with exception, pending this exception +assign cbus_ex2_pending_spec_expt_set = cbus_ex2_inst_vld + && !retire_cbus_ex2_stall + && cbus_ex2_ipush_spec_inst + && cbus_retire_ex2_expt_inst; +assign rtu_idu_ex2_ipush_spec_inst_expt_vld = cbus_ex2_pending_spec_expt_set; +////clear pending exception when ex1 spec fail or ex2 non spec inst retire +assign cbus_ex1_pending_spec_expt_clr = cbus_cmplt_vld + && !retire_cbus_ex2_stall + && cbus_ex1_ipush_spec_fail + || cbus_ex2_inst_vld + && !retire_cbus_ex2_stall + && !cbus_ex2_ipush_spec_inst + && cbus_ex2_pending_spec_expt; + +always @ (posedge retire_ex2_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cbus_ex2_pending_spec_expt <= 1'b0; + else if (cbus_ex1_pending_spec_expt_clr || rtu_yy_xx_flush) + cbus_ex2_pending_spec_expt <= 1'b0; + else if (cbus_ex2_pending_spec_expt_set) + cbus_ex2_pending_spec_expt <= 1'b1; +end + +assign rtu_iu_pending_spec_expt_vld = cbus_ex2_pending_spec_expt; + +//========================================================== +// Pending Halt Info for spec inst +//========================================================== +//if spec inst retire with t0 halt req / expt trigger match, +//pending its halt info +assign cbus_ex2_pending_spec_halt_info_set = cbus_ex2_inst_vld + && !retire_cbus_ex2_stall + && cbus_ex2_ipush_spec_inst + && !cbus_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && cbus_ex2_halt_info[`TDT_HINFO_MATCH] + && !cbus_ex2_halt_info[`TDT_HINFO_CHAIN] + && !cbus_ex2_halt_info[`TDT_HINFO_TIMING]; +assign rtu_idu_ex2_ipush_spec_inst_halt_info_vld = cbus_ex2_pending_spec_halt_info_set; +////clear pending exception when ex1 spec fail or ex2 non spec inst retire +assign cbus_ex1_pending_spec_halt_info_clr = cbus_cmplt_vld + && !retire_cbus_ex2_stall + && cbus_ex1_ipush_spec_fail + || cbus_ex2_inst_vld + && !retire_cbus_ex2_stall + && !cbus_ex2_ipush_spec_inst + && cbus_ex2_pending_spec_halt_info; + +always @ (posedge retire_ex2_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + cbus_ex2_pending_spec_halt_info <= 1'b0; + cbus_ex2_pending_spec_halt_info_data[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + end + else if (cbus_ex1_pending_spec_halt_info_clr || rtu_yy_xx_flush) begin + cbus_ex2_pending_spec_halt_info <= 1'b0; + cbus_ex2_pending_spec_halt_info_data[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + end + else if (cbus_ex2_pending_spec_halt_info_set) begin + cbus_ex2_pending_spec_halt_info <= 1'b1; + cbus_ex2_pending_spec_halt_info_data[`TDT_HINFO_WIDTH-1:0] <= cbus_ex2_halt_info[`TDT_HINFO_WIDTH-1:0]; + end +end + +assign rtu_iu_pending_spec_halt_info_vld = cbus_ex2_pending_spec_halt_info; + +//========================================================== +// RTU Complete Bus Stall +//========================================================== +//if ex1 instruction may produce speculation fail +//rtu should stall ex1 through uncommit stall when ex2 +//when bju change flow inst results spec fail, rtu should +//stall when ex2 +assign cbus_ex2_uncommit_stall = cbus_ex2_inst_vld + && (cbus_ex2_may_spec_fail + || cbus_ex2_chgflw_vld + || cbus_retire_ex2_expt_inst + || cbus_retire_ex2_inst_nmi + || lsu_rtu_async_expt_vld) + || retire_cbus_flush_stall + || retire_cbus_debug_may_spec_fail + || iu_rtu_ex2_bju_flush; +assign cbus_top_ex2_uncommit_stall = cbus_ex2_uncommit_stall; + +//rtu ex1 stall: stall IDU EX1 inst sel, stall EU cmplt +assign rtu_xx_ex1_stall = cbus_ex2_uncommit_stall + || retire_cbus_ex2_stall; +////if ex1 inst valid and may retire with interrupt, id stage +////should be stalled to prevent newer spec fail inst modify +////write back table state +//assign rtu_idu_ex1_int_stall = cbus_ex1_inst_vld +// && cbus_ex1_inst_int; +//if ex1 inst pipedown with int, stall dispatch until int change flow +assign rtu_idu_ex1_int_dis_stall_req = cbus_cmplt_vld + && !retire_cbus_ex2_stall + && cbus_ex1_inst_int; +assign rtu_idu_ex1_int_dis_stall_gateclk_req = cbus_cmplt_dp_vld + && cbus_ex1_inst_int; + + +// &ModuleEnd; @617 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_int.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_int.v new file mode 100644 index 0000000000000000000000000000000000000000..6a77421a0745ca3803d0a98eb77eb9813c9d4290 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_int.v @@ -0,0 +1,386 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_rtu_int( + cbus_int_ex1_split_inst, + cbus_int_ipop_int_mask, + cbus_int_ipush_mie_en, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + cp0_rtu_ex1_mret, + cp0_rtu_icg_en, + cp0_rtu_in_nmi, + cp0_rtu_int_level, + cp0_rtu_int_mode, + cp0_rtu_mie, + cp0_rtu_mnxti_vld, + cp0_rtu_mpil, + cp0_rtu_pm_bypass, + cp0_rtu_tail_int_hv, + cp0_rtu_tail_int_id, + cp0_rtu_wfe_en, + cpu_clic_curid, + cpu_clic_int_exit, + cpurst_b, + dtu_rtu_int_mask, + forever_cpuclk, + idu_yy_xx_tail_ack, + int_cbus_ex1_int_vld, + int_cbus_ex1_nmi_req, + int_cbus_int_hv, + int_lockup_nmi_req, + int_retire_pending_int_hv, + int_top_nmi_req, + int_xx_int_id, + int_xx_int_lv, + pad_yy_icg_scan_en, + retire_int_nmi_ack, + retire_xx_ex2_expt_raw, + rtu_cp0_mnxti_pending_vld, + rtu_cp0_pending_int_hv, + rtu_cp0_pending_int_id, + rtu_cp0_pending_int_level, + rtu_cp0_wk_int, + rtu_dtu_nmi_pending, + rtu_idu_id_tail_int_vld, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_int_hv, + sysio_rtu_nmi_int, + sysio_rtu_wk_event +); + +// &Ports; @24 +input cbus_int_ex1_split_inst; +input cbus_int_ipop_int_mask; +input cbus_int_ipush_mie_en; +input clic_cpu_int_hv; +input [11:0] clic_cpu_int_id; +input [7 :0] clic_cpu_int_il; +input [1 :0] clic_cpu_int_priv; +input cp0_rtu_ex1_mret; +input cp0_rtu_icg_en; +input cp0_rtu_in_nmi; +input [7 :0] cp0_rtu_int_level; +input [1 :0] cp0_rtu_int_mode; +input cp0_rtu_mie; +input cp0_rtu_mnxti_vld; +input [7 :0] cp0_rtu_mpil; +input [1 :0] cp0_rtu_pm_bypass; +input cp0_rtu_tail_int_hv; +input [11:0] cp0_rtu_tail_int_id; +input cp0_rtu_wfe_en; +input cpurst_b; +input dtu_rtu_int_mask; +input forever_cpuclk; +input idu_yy_xx_tail_ack; +input pad_yy_icg_scan_en; +input retire_int_nmi_ack; +input retire_xx_ex2_expt_raw; +input rtu_yy_xx_expt_int; +input [11:0] rtu_yy_xx_expt_vec; +input rtu_yy_xx_expt_vld; +input rtu_yy_xx_int_hv; +input sysio_rtu_nmi_int; +input sysio_rtu_wk_event; +output [11:0] cpu_clic_curid; +output cpu_clic_int_exit; +output int_cbus_ex1_int_vld; +output int_cbus_ex1_nmi_req; +output int_cbus_int_hv; +output int_lockup_nmi_req; +output int_retire_pending_int_hv; +output int_top_nmi_req; +output [11:0] int_xx_int_id; +output [7 :0] int_xx_int_lv; +output rtu_cp0_mnxti_pending_vld; +output rtu_cp0_pending_int_hv; +output [11:0] rtu_cp0_pending_int_id; +output [7 :0] rtu_cp0_pending_int_level; +output rtu_cp0_wk_int; +output rtu_dtu_nmi_pending; +output rtu_idu_id_tail_int_vld; + +// &Regs; @25 +reg cpu_nmi_int_f; +reg cpu_wk_event_f1; +reg cpu_wk_event_f2; +reg int_nmi_req_raw; + +// &Wires; @26 +wire cbus_int_ex1_split_inst; +wire cbus_int_ipop_int_mask; +wire cbus_int_ipush_mie_en; +wire clic_cpu_int_hv; +wire [11:0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire cp0_rtu_wfe_en; +wire [11:0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpu_nmi_vld; +wire cpurst_b; +wire dtu_rtu_int_mask; +wire flop_clk; +wire flop_clk_en; +wire forever_cpuclk; +wire idu_yy_xx_tail_ack; +wire int_cbus_ex1_int_vld; +wire int_cbus_ex1_nmi_req; +wire int_cbus_int_hv; +wire int_clic_gt_cur; +wire int_clic_gt_cur_pm; +wire int_clic_gt_pre; +wire int_clic_hv; +wire [11:0] int_clic_id; +wire [7 :0] int_clic_int_level; +wire [1 :0] int_clic_int_mode; +wire [7 :0] int_cur_int_level; +wire int_ex1_int_vld; +wire int_ex1_nmi_vld; +wire int_global_mie; +wire int_id_tail_vld; +wire int_lockup_nmi_req; +wire int_mask; +wire int_nhv_int_ack; +wire int_nmi_req; +wire int_pending_vld; +wire [7 :0] int_pre_int_level; +wire int_retire_pending_int_hv; +wire int_top_nmi_req; +wire int_vld; +wire int_vld_raw; +wire int_wk_event_vld; +wire [11:0] int_xx_int_id; +wire [7 :0] int_xx_int_lv; +wire mnxti_pending_vld; +wire pad_yy_icg_scan_en; +wire retire_int_nmi_ack; +wire retire_xx_ex2_expt_raw; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire rtu_cp0_wk_int; +wire rtu_dtu_nmi_pending; +wire rtu_idu_id_tail_int_vld; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_int_hv; +wire sysio_rtu_nmi_int; +wire sysio_rtu_wk_event; + + +parameter CPU_MODE_M = 2'b11; +parameter CPU_MODE_U = 2'b00; + +assign int_global_mie = cp0_rtu_mie + || cbus_int_ipush_mie_en && !retire_xx_ex2_expt_raw; +//========================================================== +// Input from CLIC +//========================================================== +assign int_clic_id[11:0] = clic_cpu_int_id[11:0]; +assign int_clic_int_level[7:0] = clic_cpu_int_il[7:0]; +assign int_clic_int_mode[1:0] = clic_cpu_int_priv[1:0]; +assign int_clic_hv = clic_cpu_int_hv; + +//========================================================== +// Input from CP0 +//========================================================== +assign int_cur_int_level[7:0] = cp0_rtu_int_level[7:0]; +// &Force("input", "cp0_rtu_int_mode"); &Force("bus", "cp0_rtu_int_mode", 1, 0); @46 +// assign int_cur_int_mode[1:0] = cp0_rtu_int_mode[1:0]; + +assign int_pre_int_level[7:0] = cp0_rtu_mpil[7:0]; + +assign int_nhv_int_ack = cp0_rtu_mnxti_vld; +//========================================================== +// Judge Int +//========================================================== +assign int_clic_gt_cur = int_clic_int_level[7:0] > int_cur_int_level[7:0]; +assign int_clic_gt_cur_pm = (int_clic_int_level[7:0] != 8'b0) + && (cp0_rtu_pm_bypass[1:0] != CPU_MODE_M); +assign int_vld_raw = (int_clic_gt_cur // clic int must be M mode int. + || int_clic_gt_cur_pm) //PM < M + && int_clic_int_mode[1:0] == CPU_MODE_M; // Only support M int. + +//========================================================== +// Judge Int Pending +//========================================================== +// Using MNXTI cpu must be in M-mode. +assign int_clic_gt_pre = int_clic_int_level[7:0] > int_pre_int_level[7:0]; +assign int_pending_vld = int_clic_gt_pre + && int_clic_int_mode[1:0] == CPU_MODE_M; +assign mnxti_pending_vld = int_pending_vld && !int_clic_hv; + +//========================================================== +// Prepare Interrupt Source +//========================================================== +assign int_vld = int_vld_raw && (int_global_mie + || cp0_rtu_pm_bypass[1:0] != CPU_MODE_M); +// if idu_rtu_ex1_ipop_int_mask is 1'b1, ipop can ack int. +assign int_ex1_int_vld = int_vld + && (!cbus_int_ex1_split_inst || cbus_int_ipop_int_mask) + && !dtu_rtu_int_mask + && !int_mask; +//assign int_ex1_int_vld_gate = int_vld_raw +// && (!cbus_int_ex1_split_inst || idu_rtu_ex1_ipop_int_mask) +// && !dtu_rtu_int_mask +// && !int_mask; +// int can't be ack when in nmi. +assign int_mask = cp0_rtu_in_nmi && !cp0_rtu_ex1_mret; + +//========================================================== +// Tail-Chain Judge +//========================================================== +assign int_id_tail_vld = int_pending_vld && !int_clic_gt_cur + && cp0_rtu_mie + && !dtu_rtu_int_mask + && !int_mask; + + +//========================================================== +// Prepare NMI Source +//========================================================== +always @ (posedge flop_clk or negedge cpurst_b) +begin + if (!cpurst_b) + cpu_nmi_int_f <= 1'b0; + else + cpu_nmi_int_f <= sysio_rtu_nmi_int; +end + +assign cpu_nmi_vld = !cpu_nmi_int_f && sysio_rtu_nmi_int; + +always @ (posedge flop_clk or negedge cpurst_b) +begin + if (!cpurst_b) + int_nmi_req_raw <= 1'b0; + else if (cpu_nmi_vld) + int_nmi_req_raw <= 1'b1; + else if (retire_int_nmi_ack) + int_nmi_req_raw <= 1'b0; +end + +assign int_top_nmi_req = int_nmi_req_raw; + +assign int_nmi_req = int_nmi_req_raw && !(cp0_rtu_in_nmi && !cp0_rtu_ex1_mret); +assign int_ex1_nmi_vld = int_nmi_req + && !dtu_rtu_int_mask + && !cbus_int_ex1_split_inst; + +//========================================================== +// Prepare WFE Source +//========================================================== +always @ (posedge flop_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + cpu_wk_event_f1 <= 1'b0; + cpu_wk_event_f2 <= 1'b0; + end + else begin + cpu_wk_event_f1 <= sysio_rtu_wk_event; + cpu_wk_event_f2 <= cpu_wk_event_f1; + end +end + +assign int_wk_event_vld = !cpu_wk_event_f2 && cpu_wk_event_f1; + +assign flop_clk_en = cpu_nmi_int_f ^ sysio_rtu_nmi_int + || cpu_wk_event_f1 ^ sysio_rtu_wk_event + || cpu_wk_event_f2 ^ cpu_wk_event_f1 + || cpu_nmi_vld + || int_nmi_req_raw; +// &Instance("gated_clk_cell", "x_flop_clk"); @149 +gated_clk_cell x_flop_clk ( + .clk_in (forever_cpuclk ), + .clk_out (flop_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (flop_clk_en ), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @150 +// .external_en (1'b0), @151 +// .global_en (1'b1), @152 +// .module_en (cp0_rtu_icg_en), @153 +// .local_en (flop_clk_en), @154 +// .clk_out (flop_clk)); @155 + +//========================================================== +// Output to RTU +//========================================================== +assign int_cbus_ex1_nmi_req = int_ex1_nmi_vld; +assign int_cbus_ex1_int_vld = int_ex1_int_vld && !int_ex1_nmi_vld; +//assign int_cbus_ex1_int_vld_gate = int_ex1_int_vld_gate && !int_ex1_nmi_vld; +assign int_cbus_int_hv = int_clic_hv; +assign int_retire_pending_int_hv = int_clic_hv; +assign int_xx_int_id[11:0] = int_clic_id[11:0]; +assign int_xx_int_lv[7:0] = int_clic_int_level[7:0]; +assign int_lockup_nmi_req = int_nmi_req; +// TODO int mode +//========================================================== +// Output to CP0 +//========================================================== +assign rtu_cp0_wk_int = int_vld_raw + || |int_clic_int_level[7:0] && cp0_rtu_wfe_en + || int_wk_event_vld && cp0_rtu_wfe_en + || int_nmi_req; +assign rtu_cp0_mnxti_pending_vld = mnxti_pending_vld; +assign rtu_cp0_pending_int_id[11:0] = int_clic_id[11:0]; +assign rtu_cp0_pending_int_level[7:0] = int_clic_int_level[7:0]; +assign rtu_cp0_pending_int_hv = int_clic_hv; + +//========================================================== +// Output to CLIC +//========================================================== +assign cpu_clic_curid[11:0] = idu_yy_xx_tail_ack ? cp0_rtu_tail_int_id[11:0] + : rtu_yy_xx_expt_vld && rtu_yy_xx_expt_int ? rtu_yy_xx_expt_vec[11:0] + : int_clic_id[11:0]; +assign cpu_clic_int_exit = idu_yy_xx_tail_ack && cp0_rtu_tail_int_hv // tail_int (hv) ack + || rtu_yy_xx_expt_vld && rtu_yy_xx_expt_int && rtu_yy_xx_int_hv // normal hv-int ack + || int_nhv_int_ack; // non-hv int ack + +//========================================================== +// Output to IDU +//========================================================== +assign rtu_idu_id_tail_int_vld = int_id_tail_vld; + +//========================================================== +// Output to DTU +//========================================================== +assign rtu_dtu_nmi_pending = int_nmi_req_raw; + +// &ModuleEnd @207 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_lockup.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_lockup.v new file mode 100644 index 0000000000000000000000000000000000000000..3a2d6d1023e7e39d7395ff0b1d48869fdddfa408 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_lockup.v @@ -0,0 +1,214 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_rtu_lockup( + cp0_rtu_in_expt, + cp0_rtu_in_nmi, + cpurst_b, + ifu_rtu_lockup_ack, + int_lockup_nmi_req, + lockup_clk, + lockup_clk_en, + lockup_retire_dbg_vld, + lockup_retire_nmi_vld, + lockup_top_cur_st, + retire_lockup_dbg_req, + retire_lockup_dbgon, + retire_lockup_expt_vld, + retire_lockup_nmi_exit, + retire_lockup_retire_pc, + retire_lockup_retire_vld, + rtu_cp0_lockup_clr, + rtu_cp0_lockup_vld, + rtu_ifu_lockup_expt_vld, + rtu_ifu_lockup_mask, + rtu_ifu_lockup_req, + rtu_sysio_lockup_on +); + +// &Ports; @24 +input cp0_rtu_in_expt; +input cp0_rtu_in_nmi; +input cpurst_b; +input ifu_rtu_lockup_ack; +input int_lockup_nmi_req; +input lockup_clk; +input retire_lockup_dbg_req; +input retire_lockup_dbgon; +input retire_lockup_expt_vld; +input retire_lockup_nmi_exit; +input [31:0] retire_lockup_retire_pc; +input retire_lockup_retire_vld; +output lockup_clk_en; +output lockup_retire_dbg_vld; +output lockup_retire_nmi_vld; +output [2 :0] lockup_top_cur_st; +output rtu_cp0_lockup_clr; +output rtu_cp0_lockup_vld; +output rtu_ifu_lockup_expt_vld; +output rtu_ifu_lockup_mask; +output rtu_ifu_lockup_req; +output rtu_sysio_lockup_on; + +// &Regs; @25 +reg [2 :0] lockup_cur_st; +reg [2 :0] lockup_nxt_st; + +// &Wires; @26 +wire cp0_rtu_in_expt; +wire cp0_rtu_in_nmi; +wire cpurst_b; +wire ifu_rtu_lockup_ack; +wire int_lockup_nmi_req; +wire lock_up_ack; +wire lock_up_en; +wire lock_up_vld; +wire lockup_clk; +wire lockup_clk_en; +wire lockup_on; +wire lockup_retire_dbg_vld; +wire lockup_retire_nmi_vld; +wire [2 :0] lockup_top_cur_st; +wire retire_lockup_dbg_req; +wire retire_lockup_dbgon; +wire retire_lockup_expt_vld; +wire retire_lockup_nmi_exit; +wire [31:0] retire_lockup_retire_pc; +wire retire_lockup_retire_vld; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_ifu_lockup_expt_vld; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire rtu_sysio_lockup_on; + + +// lock up module +// 1. Lock up valid when expt vld in a expt handler, ecall and ebreak excluded +// 2. Lock up will wait IFU empty and mask IFU fetch +// 3. Lock up can react debug and nmi + +assign lock_up_en = 1'b1; + +assign lock_up_vld = (cp0_rtu_in_expt || cp0_rtu_in_nmi) + && retire_lockup_expt_vld + && lock_up_en + && !lockup_on; + +// Lock up state machine +parameter IDLE = 3'b000; +parameter WFLU = 3'b001; +parameter LKUP = 3'b010; +parameter LKNMI = 3'b100; +parameter LKDBG = 3'b101; + +always @ (posedge lockup_clk or negedge cpurst_b) +begin + if(!cpurst_b) + lockup_cur_st[2:0] <= IDLE; + else + lockup_cur_st[2:0] <= lockup_nxt_st[2:0]; +end + +// &CombBeg; @55 +always @( cp0_rtu_in_nmi + or retire_lockup_nmi_exit + or lock_up_vld + or lock_up_ack + or retire_lockup_retire_pc[31:0] + or retire_lockup_retire_vld + or int_lockup_nmi_req + or retire_lockup_dbgon + or lockup_cur_st[2:0]) +begin +case(lockup_cur_st[2:0]) + IDLE: + begin + if(lock_up_vld) + lockup_nxt_st[2:0] = WFLU; + else + lockup_nxt_st[2:0] = IDLE; + end + WFLU: + begin + if(lock_up_ack) + lockup_nxt_st[2:0] = LKUP; + else + lockup_nxt_st[2:0] = WFLU; + end + LKUP: + begin + if(retire_lockup_dbgon) + lockup_nxt_st[2:0] = LKDBG; + else if(int_lockup_nmi_req && !cp0_rtu_in_nmi) + lockup_nxt_st[2:0] = LKNMI; + else + lockup_nxt_st[2:0] = LKUP; + end + LKNMI: + begin + if(retire_lockup_nmi_exit || lock_up_vld) + lockup_nxt_st[2:0] = WFLU; + else + lockup_nxt_st[2:0] = LKNMI; + end + LKDBG: + begin + if(retire_lockup_retire_vld && !retire_lockup_dbgon) + if (retire_lockup_retire_pc[31:0] == 32'hEFFF_FFFC) + lockup_nxt_st[2:0] = WFLU; + else + lockup_nxt_st[2:0] = IDLE; + else + lockup_nxt_st[2:0] = LKDBG; + end + default: + begin + lockup_nxt_st[2:0] = IDLE; + end +endcase +// &CombEnd; @102 +end + +assign lock_up_ack = ifu_rtu_lockup_ack; + +assign lockup_on = lockup_cur_st[2:0] == LKUP; + +assign rtu_ifu_lockup_req = lockup_cur_st[2:0] == WFLU; + +assign lockup_top_cur_st[2:0] = lockup_cur_st[2:0]; + +assign rtu_ifu_lockup_expt_vld = lock_up_vld; +assign lockup_retire_nmi_vld = lockup_on && int_lockup_nmi_req && !cp0_rtu_in_nmi; +assign lockup_retire_dbg_vld = lockup_on && retire_lockup_dbg_req; + +assign rtu_cp0_lockup_vld = lockup_cur_st[2:0] == WFLU && lock_up_ack; +assign rtu_cp0_lockup_clr = retire_lockup_retire_vld && !retire_lockup_dbgon + && retire_lockup_retire_pc[31:0] != 32'hEFFF_FFFC + && lockup_cur_st[2:0] == LKDBG; + +assign rtu_ifu_lockup_mask = lockup_cur_st[2:0] == WFLU || lockup_on; +assign rtu_sysio_lockup_on = lockup_on; + +assign lockup_clk_en = lockup_cur_st[2:0] != IDLE + || lock_up_vld; + + +// &ModuleEnd; @137 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_rbus.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_rbus.v new file mode 100644 index 0000000000000000000000000000000000000000..512dd4b82135db8b787933d23776b818855c689c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_rbus.v @@ -0,0 +1,522 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_rtu_rbus( + cp0_rtu_icg_en, + cp0_rtu_wb_data, + cp0_rtu_wb_preg, + cp0_rtu_wb_vld, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + fpu_rtu_fgpr_wb_data, + fpu_rtu_fgpr_wb_reg, + fpu_rtu_fgpr_wb_vld, + fpu_rtu_wb_data, + fpu_rtu_wb_preg, + fpu_rtu_wb_vld, + ifu_rtu_warm_up, + iu_rtu_wb0_data, + iu_rtu_wb0_preg, + iu_rtu_wb0_vld, + lsu_rtu_fgpr_wb_data, + lsu_rtu_fgpr_wb_reg, + lsu_rtu_fgpr_wb_vld, + lsu_rtu_wb_data, + lsu_rtu_wb_preg, + lsu_rtu_wb_vld, + pad_yy_icg_scan_en, + rbus_top_fpu_wb_stall, + rbus_top_iu_wb_stall, + rtu_cp0_fp_dirty_vld, + rtu_fpu_fgpr_wb_grant, + rtu_fpu_wb_grant, + rtu_idu_fgpr_wb_data, + rtu_idu_fgpr_wb_flsu_vld, + rtu_idu_fgpr_wb_reg, + rtu_idu_fgpr_wb_vld, + rtu_idu_wb0_data, + rtu_idu_wb0_fpu_vld, + rtu_idu_wb0_preg, + rtu_idu_wb0_vld, + rtu_idu_wb1_data, + rtu_idu_wb1_lsu_vld, + rtu_idu_wb1_preg, + rtu_idu_wb1_vld, + rtu_idu_wb2_data, + rtu_idu_wb2_preg, + rtu_idu_wb2_vld, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_lsu_wb1_data, + rtu_lsu_wb1_lsu_vld, + rtu_lsu_wb1_preg, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld +); + +// &Ports; @24 +input cp0_rtu_icg_en; +input [31:0] cp0_rtu_wb_data; +input [5 :0] cp0_rtu_wb_preg; +input cp0_rtu_wb_vld; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] fpu_rtu_fgpr_wb_data; +input [4 :0] fpu_rtu_fgpr_wb_reg; +input fpu_rtu_fgpr_wb_vld; +input [31:0] fpu_rtu_wb_data; +input [5 :0] fpu_rtu_wb_preg; +input fpu_rtu_wb_vld; +input ifu_rtu_warm_up; +input [31:0] iu_rtu_wb0_data; +input [5 :0] iu_rtu_wb0_preg; +input iu_rtu_wb0_vld; +input [31:0] lsu_rtu_fgpr_wb_data; +input [4 :0] lsu_rtu_fgpr_wb_reg; +input lsu_rtu_fgpr_wb_vld; +input [31:0] lsu_rtu_wb_data; +input [5 :0] lsu_rtu_wb_preg; +input lsu_rtu_wb_vld; +input pad_yy_icg_scan_en; +output rbus_top_fpu_wb_stall; +output rbus_top_iu_wb_stall; +output rtu_cp0_fp_dirty_vld; +output rtu_fpu_fgpr_wb_grant; +output rtu_fpu_wb_grant; +output [31:0] rtu_idu_fgpr_wb_data; +output rtu_idu_fgpr_wb_flsu_vld; +output [4 :0] rtu_idu_fgpr_wb_reg; +output rtu_idu_fgpr_wb_vld; +output [31:0] rtu_idu_wb0_data; +output rtu_idu_wb0_fpu_vld; +output [5 :0] rtu_idu_wb0_preg; +output rtu_idu_wb0_vld; +output [31:0] rtu_idu_wb1_data; +output rtu_idu_wb1_lsu_vld; +output [5 :0] rtu_idu_wb1_preg; +output rtu_idu_wb1_vld; +output [31:0] rtu_idu_wb2_data; +output [5 :0] rtu_idu_wb2_preg; +output rtu_idu_wb2_vld; +output [31:0] rtu_lsu_fgpr_wb_data; +output [4 :0] rtu_lsu_fgpr_wb_reg; +output rtu_lsu_fgpr_wb_vld; +output [31:0] rtu_lsu_wb1_data; +output rtu_lsu_wb1_lsu_vld; +output [5 :0] rtu_lsu_wb1_preg; +output [31:0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31:0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31:0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31:0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; + +// &Regs; @25 +reg [31:0] rbus_wb_fgpr_flop_data; +reg [4 :0] rbus_wb_fgpr_flop_reg; +reg rbus_wb_fgpr_flop_vld; +reg [31:0] rbus_wb_wb0_data; +reg rbus_wb_wb0_fpu_vld; +reg [5 :0] rbus_wb_wb0_preg; +reg rbus_wb_wb0_vld; + +// &Wires; @26 +wire cp0_rtu_icg_en; +wire [31:0] cp0_rtu_wb_data; +wire [5 :0] cp0_rtu_wb_preg; +wire cp0_rtu_wb_vld; +wire cp0_yy_clk_en; +wire cpurst_b; +wire fgpr_wb_clk; +wire fgpr_wb_clk_en; +wire forever_cpuclk; +wire [31:0] fpu_rtu_fgpr_wb_data; +wire [4 :0] fpu_rtu_fgpr_wb_reg; +wire fpu_rtu_fgpr_wb_vld; +wire [31:0] fpu_rtu_wb_data; +wire [5 :0] fpu_rtu_wb_preg; +wire fpu_rtu_wb_vld; +wire ifu_rtu_warm_up; +wire [31:0] iu_rtu_wb0_data; +wire [5 :0] iu_rtu_wb0_preg; +wire iu_rtu_wb0_vld; +wire [31:0] lsu_rtu_fgpr_wb_data; +wire [4 :0] lsu_rtu_fgpr_wb_reg; +wire lsu_rtu_fgpr_wb_vld; +wire [31:0] lsu_rtu_wb_data; +wire [5 :0] lsu_rtu_wb_preg; +wire lsu_rtu_wb_vld; +wire pad_yy_icg_scan_en; +wire rbus_cp0_wb_vld; +wire [31:0] rbus_fgpr_wb_data; +wire [4 :0] rbus_fgpr_wb_reg; +wire rbus_fgpr_wb_vld; +wire rbus_fpu_wb_grant; +wire rbus_fpu_wb_vld; +wire rbus_iu_wb0_vld; +wire rbus_lsu_wb_vld; +wire rbus_top_fpu_wb_stall; +wire rbus_top_iu_wb_stall; +wire [31:0] rbus_wb0_data; +wire [5 :0] rbus_wb0_preg; +wire rbus_wb0_vld; +wire [31:0] rbus_wb_fgpr_wb_data; +wire [4 :0] rbus_wb_fgpr_wb_reg; +wire rbus_wb_fgpr_wb_stall; +wire rbus_wb_fgpr_wb_vld; +wire [31:0] rbus_wb_wb0_with_fpu_data; +wire rbus_wb_wb0_with_fpu_fpu_vld; +wire [5 :0] rbus_wb_wb0_with_fpu_preg; +wire rbus_wb_wb0_with_fpu_vld; +wire [31:0] rbus_wb_wb1_data; +wire [5 :0] rbus_wb_wb1_preg; +wire rbus_wb_wb1_vld; +wire rtu_cp0_fp_dirty_vld; +wire rtu_fpu_fgpr_wb_grant; +wire rtu_fpu_wb_grant; +wire [31:0] rtu_idu_fgpr_wb_data; +wire rtu_idu_fgpr_wb_flsu_vld; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire [31:0] rtu_idu_wb0_data; +wire rtu_idu_wb0_fpu_vld; +wire [5 :0] rtu_idu_wb0_preg; +wire rtu_idu_wb0_vld; +wire [31:0] rtu_idu_wb1_data; +wire rtu_idu_wb1_lsu_vld; +wire [5 :0] rtu_idu_wb1_preg; +wire rtu_idu_wb1_vld; +wire [31:0] rtu_idu_wb2_data; +wire [5 :0] rtu_idu_wb2_preg; +wire rtu_idu_wb2_vld; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire [31:0] rtu_lsu_wb1_data; +wire rtu_lsu_wb1_lsu_vld; +wire [5 :0] rtu_lsu_wb1_preg; +wire [31:0] rtu_pad_wb0_data; +wire [5 :0] rtu_pad_wb0_preg; +wire rtu_pad_wb0_vld; +wire [31:0] rtu_pad_wb1_data; +wire [5 :0] rtu_pad_wb1_preg; +wire rtu_pad_wb1_vld; +wire [31:0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +wire [4 :0] rtu_pad_wb_freg; +wire [31:0] rtu_pad_wb_freg_data; +wire rtu_pad_wb_freg_vld; +wire wb0_clk; +wire wb0_clk_en; + + +//========================================================== +// Write Back Source +//========================================================== +//---------------------------------------------------------- +// Priority +//---------------------------------------------------------- +//Write Port Priority: +//IU > FPU +//FPU share rbus WB stage wb0 +assign rbus_fpu_wb_grant = !rbus_wb_wb0_vld; + +assign rtu_fpu_wb_grant = rbus_fpu_wb_grant; + +assign rbus_top_iu_wb_stall = 1'b0; +assign rbus_top_fpu_wb_stall = !rbus_fpu_wb_grant; + +//---------------------------------------------------------- +// wb control signals +//---------------------------------------------------------- +assign rbus_iu_wb0_vld = iu_rtu_wb0_vld; +assign rbus_lsu_wb_vld = lsu_rtu_wb_vld; +assign rbus_fpu_wb_vld = fpu_rtu_wb_vld && rbus_fpu_wb_grant; +assign rbus_cp0_wb_vld = cp0_rtu_wb_vld; + +//========================================================== +// Integer Write Back 0 +//========================================================== + +//---------------------------------------------------------- +// Result MUX +//---------------------------------------------------------- +assign rbus_wb0_vld = + rbus_iu_wb0_vld + || rbus_cp0_wb_vld; + +assign rbus_wb0_preg[5:0] = + {6{rbus_iu_wb0_vld}} & iu_rtu_wb0_preg[5:0] + | {6{rbus_cp0_wb_vld}} & cp0_rtu_wb_preg[5:0]; + +assign rbus_wb0_data[31:0] = + {32{rbus_iu_wb0_vld}} & iu_rtu_wb0_data[31:0] + | {32{rbus_cp0_wb_vld}} & cp0_rtu_wb_data[31:0]; + + +//---------------------------------------------------------- +// Write Back Register +//---------------------------------------------------------- +assign wb0_clk_en = ifu_rtu_warm_up + || rbus_wb0_vld + || rbus_wb_wb0_vld; +// &Instance("gated_clk_cell", "x_wb0_clk"); @120 +gated_clk_cell x_wb0_clk ( + .clk_in (forever_cpuclk ), + .clk_out (wb0_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (wb0_clk_en ), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @121 +// .external_en (1'b0), @122 +// .global_en (cp0_yy_clk_en), @123 +// .module_en (cp0_rtu_icg_en), @124 +// .local_en (wb0_clk_en), @125 +// .clk_out (wb0_clk)); @126 + +always @ (posedge wb0_clk or negedge cpurst_b) +begin + if (!cpurst_b) + rbus_wb_wb0_vld <= 1'b0; + else if(rbus_wb0_vld) + rbus_wb_wb0_vld <= 1'b1; + else + rbus_wb_wb0_vld <= 1'b0; +end + +always @ (posedge wb0_clk) +begin + if(ifu_rtu_warm_up || rbus_wb0_vld) begin + rbus_wb_wb0_preg[5:0] <= rbus_wb0_preg[5:0]; + rbus_wb_wb0_data[31:0] <= rbus_wb0_data[31:0]; + rbus_wb_wb0_fpu_vld <= rbus_fpu_wb_vld; + end + else begin + rbus_wb_wb0_preg[5:0] <= rbus_wb_wb0_preg[5:0]; + rbus_wb_wb0_data[31:0] <= rbus_wb_wb0_data[31:0]; + rbus_wb_wb0_fpu_vld <= rbus_wb_wb0_fpu_vld; + end +end + +//---------------------------------------------------------- +// Write Back MUX +//---------------------------------------------------------- +assign rbus_wb_wb0_with_fpu_vld = + rbus_wb_wb0_vld || rbus_fpu_wb_vld; + +assign rbus_wb_wb0_with_fpu_preg[5:0] = + {6{rbus_wb_wb0_vld}} & rbus_wb_wb0_preg[5:0] + | {6{rbus_fpu_wb_vld}} & fpu_rtu_wb_preg[5:0]; + +assign rbus_wb_wb0_with_fpu_data[31:0] = + {32{rbus_wb_wb0_vld}} & rbus_wb_wb0_data[31:0] + | {32{rbus_fpu_wb_vld}} & fpu_rtu_wb_data[31:0]; + +assign rbus_wb_wb0_with_fpu_fpu_vld = + rbus_fpu_wb_vld; + +//for idu +assign rtu_idu_wb0_vld = rbus_wb_wb0_with_fpu_vld; +assign rtu_idu_wb0_preg[5:0] = rbus_wb_wb0_with_fpu_preg[5:0]; +assign rtu_idu_wb0_data[31:0] = rbus_wb_wb0_with_fpu_data[31:0]; +assign rtu_idu_wb0_fpu_vld = rbus_wb_wb0_with_fpu_fpu_vld; + +//for pad +assign rtu_pad_wb0_vld = rbus_wb_wb0_with_fpu_vld; +assign rtu_pad_wb0_preg[5:0] = rbus_wb_wb0_with_fpu_preg[5:0]; +assign rtu_pad_wb0_data[31:0] = rbus_wb_wb0_with_fpu_data[31:0]; + +//========================================================== +// Integer Write Back 1 +//========================================================== +// &Instance("gated_clk_cell", "x_wb1_clk"); @225 +// &Connect(.clk_in (forever_cpuclk), @226 +// .external_en (1'b0), @227 +// .global_en (cp0_yy_clk_en), @228 +// .module_en (cp0_rtu_icg_en), @229 +// .local_en (wb1_clk_en), @230 +// .clk_out (wb1_clk)); @231 +//---------------------------------------------------------- +// Result MUX +//---------------------------------------------------------- +assign rbus_wb_wb1_vld = rbus_lsu_wb_vld; +assign rbus_wb_wb1_preg[5:0] = lsu_rtu_wb_preg[5:0]; +assign rbus_wb_wb1_data[31:0] = lsu_rtu_wb_data[31:0]; + +//---------------------------------------------------------- +// Write Back MUX +//---------------------------------------------------------- +//for idu +assign rtu_idu_wb1_vld = rbus_wb_wb1_vld; +assign rtu_idu_wb1_preg[5:0] = rbus_wb_wb1_preg[5:0]; +assign rtu_idu_wb1_data[31:0] = rbus_wb_wb1_data[31:0]; +assign rtu_idu_wb1_lsu_vld = 1'b1; + +//for lsu +assign rtu_lsu_wb1_lsu_vld = rbus_wb_wb1_vld; +assign rtu_lsu_wb1_preg[5:0] = rbus_wb_wb1_preg[5:0]; +assign rtu_lsu_wb1_data[31:0] = rbus_wb_wb1_data[31:0]; + +//for pad +assign rtu_pad_wb1_vld = rbus_wb_wb1_vld; +assign rtu_pad_wb1_preg[5:0] = rbus_wb_wb1_preg[5:0]; +assign rtu_pad_wb1_data[31:0] = rbus_wb_wb1_data[31:0]; + +// &Instance("gated_clk_cell", "x_wb2_clk"); @327 +// &Connect(.clk_in (forever_cpuclk), @328 +// .external_en (1'b0), @329 +// .global_en (cp0_yy_clk_en), @330 +// .module_en (cp0_rtu_icg_en), @331 +// .local_en (wb2_clk_en), @332 +// .clk_out (wb2_clk)); @333 +//for idu +assign rtu_idu_wb2_vld = 1'b0; +assign rtu_idu_wb2_preg[5:0] = 6'b0; +assign rtu_idu_wb2_data[31:0] = 32'b0; + +//for pad +assign rtu_pad_wb2_vld = 1'b0; +assign rtu_pad_wb2_preg[5:0] = 6'b0; +assign rtu_pad_wb2_data[31:0] = 32'b0; + +//========================================================== +// FP Write Back +//========================================================== +//---------------------------------------------------------- +// Priority +//---------------------------------------------------------- +//fgpr wb priority: lsu > fpu +assign rtu_fpu_fgpr_wb_grant = !rbus_wb_fgpr_wb_stall; + +//---------------------------------------------------------- +// Result MUX +//---------------------------------------------------------- +assign rbus_fgpr_wb_vld = fpu_rtu_fgpr_wb_vld; +assign rbus_fgpr_wb_reg[4:0] = fpu_rtu_fgpr_wb_reg[4:0]; +assign rbus_fgpr_wb_data[`FLEN-1:0] = fpu_rtu_fgpr_wb_data[`FLEN-1:0]; + +//---------------------------------------------------------- +// Write Back Register +//---------------------------------------------------------- +assign fgpr_wb_clk_en = ifu_rtu_warm_up + || rbus_fgpr_wb_vld + || rbus_wb_fgpr_flop_vld; +// &Instance("gated_clk_cell", "x_fgpr_wb_clk"); @423 +gated_clk_cell x_fgpr_wb_clk ( + .clk_in (forever_cpuclk ), + .clk_out (fgpr_wb_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (fgpr_wb_clk_en ), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @424 +// .external_en (1'b0), @425 +// .global_en (cp0_yy_clk_en), @426 +// .module_en (cp0_rtu_icg_en), @427 +// .local_en (fgpr_wb_clk_en), @428 +// .clk_out (fgpr_wb_clk)); @429 + +always @ (posedge fgpr_wb_clk or negedge cpurst_b) +begin + if (!cpurst_b) + rbus_wb_fgpr_flop_vld <= 1'b0; + else if(!rbus_wb_fgpr_wb_stall) + rbus_wb_fgpr_flop_vld <= rbus_fgpr_wb_vld; + else + rbus_wb_fgpr_flop_vld <= rbus_wb_fgpr_flop_vld; +end + +always @ (posedge fgpr_wb_clk) +begin + if(ifu_rtu_warm_up || rbus_fgpr_wb_vld && !rbus_wb_fgpr_wb_stall) begin + rbus_wb_fgpr_flop_reg[4:0] <= rbus_fgpr_wb_reg[4:0]; + rbus_wb_fgpr_flop_data[`FLEN-1:0] <= rbus_fgpr_wb_data[`FLEN-1:0]; + end + else begin + rbus_wb_fgpr_flop_reg[4:0] <= rbus_wb_fgpr_flop_reg[4:0]; + rbus_wb_fgpr_flop_data[`FLEN-1:0] <= rbus_wb_fgpr_flop_data[`FLEN-1:0]; + end +end + +//---------------------------------------------------------- +// Result MUX +//---------------------------------------------------------- +assign rbus_wb_fgpr_wb_vld = rbus_wb_fgpr_flop_vld + || lsu_rtu_fgpr_wb_vld; + +assign rbus_wb_fgpr_wb_reg[4:0] = lsu_rtu_fgpr_wb_vld + ? lsu_rtu_fgpr_wb_reg[4:0] + : rbus_wb_fgpr_flop_reg[4:0]; + +assign rbus_wb_fgpr_wb_data[`FLEN-1:0] = lsu_rtu_fgpr_wb_vld + ? lsu_rtu_fgpr_wb_data[`FLEN-1:0] + : rbus_wb_fgpr_flop_data[`FLEN-1:0]; + +assign rbus_wb_fgpr_wb_stall = rbus_wb_fgpr_flop_vld + && lsu_rtu_fgpr_wb_vld; + +//---------------------------------------------------------- +// Output +//---------------------------------------------------------- +//for idu +assign rtu_idu_fgpr_wb_vld = rbus_wb_fgpr_wb_vld; +assign rtu_idu_fgpr_wb_reg[4:0] = rbus_wb_fgpr_wb_reg[4:0]; +assign rtu_idu_fgpr_wb_data[`FLEN-1:0] = rbus_wb_fgpr_wb_data[`FLEN-1:0]; +assign rtu_idu_fgpr_wb_flsu_vld = lsu_rtu_fgpr_wb_vld; +//for lsu +assign rtu_lsu_fgpr_wb_vld = rbus_wb_fgpr_wb_vld; +assign rtu_lsu_fgpr_wb_reg[4:0] = rbus_wb_fgpr_wb_reg[4:0]; +assign rtu_lsu_fgpr_wb_data[`FLEN-1:0] = rbus_wb_fgpr_wb_data[`FLEN-1:0]; +//for pad +assign rtu_pad_wb_freg_vld = rbus_wb_fgpr_wb_vld; +assign rtu_pad_wb_freg[4:0] = rbus_wb_fgpr_wb_reg[4:0]; +assign rtu_pad_wb_freg_data[`FLEN-1:0] = rbus_wb_fgpr_wb_data[`FLEN-1:0]; +//for cp0 +assign rtu_cp0_fp_dirty_vld = rbus_wb_fgpr_wb_vld; +// &Force("nonport","rtu_fpu_wb_grant") @510 +// &Force("nonport","rtu_idu_wb0_fpu_vld") @511 + +// &ModuleEnd; @514 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_retire.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_retire.v new file mode 100644 index 0000000000000000000000000000000000000000..144e087d8be481625289b20a541aadf4fcaa8c95 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_retire.v @@ -0,0 +1,1399 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_rtu_retire( + cbus_retire_ex2_chgflw_vld, + cbus_retire_ex2_cur_pc, + cbus_retire_ex2_expt_inst, + cbus_retire_ex2_flush, + cbus_retire_ex2_halt_info, + cbus_retire_ex2_inst_branch, + cbus_retire_ex2_inst_dret, + cbus_retire_ex2_inst_ebreak, + cbus_retire_ex2_inst_int, + cbus_retire_ex2_inst_mret, + cbus_retire_ex2_inst_nmi, + cbus_retire_ex2_inst_tail_int, + cbus_retire_ex2_inst_vld, + cbus_retire_ex2_int_hv, + cbus_retire_ex2_int_lv, + cbus_retire_ex2_ipop_int_mask, + cbus_retire_ex2_may_debug, + cbus_retire_ex2_next_pc, + cbus_retire_ex2_split_inst, + cbus_retire_ex2_tail_spec_inst, + cbus_retire_ex2_trap_vec, + cbus_retire_ex2_tval, + cp0_rtu_ex1_mret, + cp0_rtu_icg_en, + cp0_rtu_in_nmi, + cp0_xx_async_expt_en, + cp0_yy_clk_en, + cpurst_b, + dtu_rtu_async_halt_req, + dtu_rtu_dpc, + dtu_rtu_ebreak_action, + dtu_rtu_pending_tval, + dtu_rtu_resume_req, + dtu_rtu_step_en, + dtu_rtu_sync_flush, + dtu_rtu_sync_halt_req, + forever_cpuclk, + fpu_xx_no_op, + ifu_rtu_reset_halt_req, + int_retire_pending_int_hv, + iu_xx_no_op, + lockup_clk, + lockup_clk_en, + lockup_retire_dbg_vld, + lockup_retire_nmi_vld, + lsu_rtu_async_expt_vld, + lsu_rtu_async_ld_inst, + lsu_rtu_async_tval, + lsu_rtu_ex2_bus_err, + lsu_rtu_ex2_stall, + lsu_rtu_ex2_tval, + lsu_rtu_sync_ack, + lsu_xx_no_op, + pad_yy_icg_scan_en, + retire_cbus_debug_may_spec_fail, + retire_cbus_ex2_stall, + retire_cbus_flush_stall, + retire_int_nmi_ack, + retire_lockup_dbg_req, + retire_lockup_dbgon, + retire_lockup_expt_vld, + retire_lockup_nmi_exit, + retire_lockup_retire_pc, + retire_lockup_retire_vld, + retire_top_dbg_mode_on, + retire_top_dbg_stall, + retire_top_flush_cur_state, + retire_top_lsu_ex2_stall, + retire_xx_ex2_expt_raw, + rtu_cp0_bus_error, + rtu_cp0_epc, + rtu_cp0_exit_debug, + rtu_cp0_int_level, + rtu_cp0_nmi_vld, + rtu_cp0_tval, + rtu_dtu_dpc, + rtu_dtu_halt_ack, + rtu_dtu_pending_ack, + rtu_dtu_retire_chgflw, + rtu_dtu_retire_debug_expt_vld, + rtu_dtu_retire_halt_info, + rtu_dtu_retire_mret, + rtu_dtu_retire_next_pc, + rtu_dtu_retire_vld, + rtu_dtu_tval, + rtu_hpcp_retire_inst_vld, + rtu_idu_flush_fe, + rtu_idu_flush_stall, + rtu_idu_inst_retire, + rtu_idu_late_flush, + rtu_ifu_chgflw_pc, + rtu_ifu_chgflw_vld, + rtu_ifu_dbg_mask, + rtu_ifu_flush_fe, + rtu_lsu_async_expt_ack, + rtu_lsu_expt_ack, + rtu_lsu_expt_exit, + rtu_lsu_inst_retire, + rtu_lsu_sync_req, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_sysio_halted, + rtu_xx_no_op, + rtu_yy_xx_async_flush, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_flush, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld +); + +// &Ports; @24 +input cbus_retire_ex2_chgflw_vld; +input [31:0] cbus_retire_ex2_cur_pc; +input cbus_retire_ex2_expt_inst; +input cbus_retire_ex2_flush; +input [14:0] cbus_retire_ex2_halt_info; +input cbus_retire_ex2_inst_branch; +input cbus_retire_ex2_inst_dret; +input cbus_retire_ex2_inst_ebreak; +input cbus_retire_ex2_inst_int; +input cbus_retire_ex2_inst_mret; +input cbus_retire_ex2_inst_nmi; +input cbus_retire_ex2_inst_tail_int; +input cbus_retire_ex2_inst_vld; +input cbus_retire_ex2_int_hv; +input [7 :0] cbus_retire_ex2_int_lv; +input cbus_retire_ex2_ipop_int_mask; +input cbus_retire_ex2_may_debug; +input [31:0] cbus_retire_ex2_next_pc; +input cbus_retire_ex2_split_inst; +input cbus_retire_ex2_tail_spec_inst; +input [11:0] cbus_retire_ex2_trap_vec; +input [31:0] cbus_retire_ex2_tval; +input cp0_rtu_ex1_mret; +input cp0_rtu_icg_en; +input cp0_rtu_in_nmi; +input cp0_xx_async_expt_en; +input cp0_yy_clk_en; +input cpurst_b; +input dtu_rtu_async_halt_req; +input [31:0] dtu_rtu_dpc; +input dtu_rtu_ebreak_action; +input [31:0] dtu_rtu_pending_tval; +input dtu_rtu_resume_req; +input dtu_rtu_step_en; +input dtu_rtu_sync_flush; +input dtu_rtu_sync_halt_req; +input forever_cpuclk; +input fpu_xx_no_op; +input ifu_rtu_reset_halt_req; +input int_retire_pending_int_hv; +input iu_xx_no_op; +input lockup_clk_en; +input lockup_retire_dbg_vld; +input lockup_retire_nmi_vld; +input lsu_rtu_async_expt_vld; +input lsu_rtu_async_ld_inst; +input [31:0] lsu_rtu_async_tval; +input lsu_rtu_ex2_bus_err; +input lsu_rtu_ex2_stall; +input [31:0] lsu_rtu_ex2_tval; +input lsu_rtu_sync_ack; +input lsu_xx_no_op; +input pad_yy_icg_scan_en; +output lockup_clk; +output retire_cbus_debug_may_spec_fail; +output retire_cbus_ex2_stall; +output retire_cbus_flush_stall; +output retire_int_nmi_ack; +output retire_lockup_dbg_req; +output retire_lockup_dbgon; +output retire_lockup_expt_vld; +output retire_lockup_nmi_exit; +output [31:0] retire_lockup_retire_pc; +output retire_lockup_retire_vld; +output retire_top_dbg_mode_on; +output retire_top_dbg_stall; +output [2 :0] retire_top_flush_cur_state; +output retire_top_lsu_ex2_stall; +output retire_xx_ex2_expt_raw; +output rtu_cp0_bus_error; +output [31:0] rtu_cp0_epc; +output rtu_cp0_exit_debug; +output [7 :0] rtu_cp0_int_level; +output rtu_cp0_nmi_vld; +output [31:0] rtu_cp0_tval; +output [31:0] rtu_dtu_dpc; +output rtu_dtu_halt_ack; +output rtu_dtu_pending_ack; +output rtu_dtu_retire_chgflw; +output rtu_dtu_retire_debug_expt_vld; +output [14:0] rtu_dtu_retire_halt_info; +output rtu_dtu_retire_mret; +output [31:0] rtu_dtu_retire_next_pc; +output rtu_dtu_retire_vld; +output [31:0] rtu_dtu_tval; +output rtu_hpcp_retire_inst_vld; +output rtu_idu_flush_fe; +output rtu_idu_flush_stall; +output rtu_idu_inst_retire; +output rtu_idu_late_flush; +output [31:0] rtu_ifu_chgflw_pc; +output rtu_ifu_chgflw_vld; +output rtu_ifu_dbg_mask; +output rtu_ifu_flush_fe; +output rtu_lsu_async_expt_ack; +output rtu_lsu_expt_ack; +output rtu_lsu_expt_exit; +output rtu_lsu_inst_retire; +output rtu_lsu_sync_req; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31:0] rtu_pad_retire_pc; +output rtu_sysio_halted; +output rtu_xx_no_op; +output rtu_yy_xx_async_flush; +output rtu_yy_xx_dbgon; +output rtu_yy_xx_expt_int; +output [11:0] rtu_yy_xx_expt_vec; +output rtu_yy_xx_expt_vld; +output rtu_yy_xx_flush; +output rtu_yy_xx_int_hv; +output rtu_yy_xx_tail_int_vld; + +// &Regs; @25 +reg bkpt_req_split_lsu_trigger_buf; +reg bkpt_req_split_trigger_t1_buf; +reg dbg_mode_on; +reg dbg_mode_on_after_req; +reg [1 :0] dbg_stall_cur_state; +reg [1 :0] dbg_stall_next_state; +reg [2 :0] flush_cur_state; +reg [2 :0] flush_next_state; +reg [3 :0] halt_cause; +reg halt_req_split_trigger_t1_buf; +reg retire_async_flush; +reg retire_buf_async_trap_vld; +reg [14:0] retire_buf_split_trigger_t1_halt_info; +reg retire_buf_trap_vld; +reg retire_buf_xret_vld; +reg retire_int_flush; +reg retire_trap_ack_async; +reg retire_trap_ack_int; +reg retire_trap_ack_nmi; +reg [31:0] retire_trap_tval; +reg [11:0] retire_trap_vec; +reg [14:0] rtu_dtu_retire_halt_info; +reg [31:0] rtu_dtu_tval; + +// &Wires; @26 +wire bkpt_req_buf_split_trigger_t1; +wire bkpt_req_ebreak; +wire bkpt_req_pending; +wire bkpt_req_split_trigger_t1; +wire bkpt_req_t1_retire_vld; +wire bkpt_req_t1_retire_vld_raw; +wire bkpt_req_trigger_t0; +wire bkpt_req_trigger_t1; +wire bkpt_req_trigger_t1_raw; +wire cbus_retire_ex2_chgflw_vld; +wire [31:0] cbus_retire_ex2_cur_pc; +wire cbus_retire_ex2_expt_inst; +wire cbus_retire_ex2_flush; +wire [14:0] cbus_retire_ex2_halt_info; +wire cbus_retire_ex2_inst_branch; +wire cbus_retire_ex2_inst_dret; +wire cbus_retire_ex2_inst_ebreak; +wire cbus_retire_ex2_inst_int; +wire cbus_retire_ex2_inst_mret; +wire cbus_retire_ex2_inst_nmi; +wire cbus_retire_ex2_inst_tail_int; +wire cbus_retire_ex2_inst_vld; +wire cbus_retire_ex2_int_hv; +wire [7 :0] cbus_retire_ex2_int_lv; +wire cbus_retire_ex2_ipop_int_mask; +wire cbus_retire_ex2_may_debug; +wire [31:0] cbus_retire_ex2_next_pc; +wire cbus_retire_ex2_split_inst; +wire cbus_retire_ex2_tail_spec_inst; +wire [11:0] cbus_retire_ex2_trap_vec; +wire [31:0] cbus_retire_ex2_tval; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_nmi; +wire cp0_xx_async_expt_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire dtu_rtu_async_halt_req; +wire [31:0] dtu_rtu_dpc; +wire dtu_rtu_ebreak_action; +wire [31:0] dtu_rtu_pending_tval; +wire dtu_rtu_resume_req; +wire dtu_rtu_step_en; +wire dtu_rtu_sync_flush; +wire dtu_rtu_sync_halt_req; +wire forever_cpuclk; +wire fpu_xx_no_op; +wire halt_req; +wire halt_req_buf_split_trigger_t1; +wire halt_req_dm_async; +wire halt_req_dm_sync; +wire halt_req_ebreak; +wire halt_req_lockup_dm_sync; +wire halt_req_pending; +wire halt_req_reset; +wire halt_req_split_trigger_t1; +wire halt_req_step; +wire halt_req_t1; +wire halt_req_t1_raw; +wire halt_req_t1_retire_vld; +wire halt_req_t1_retire_vld_raw; +wire halt_req_trigger_t0; +wire halt_req_trigger_t1; +wire halt_req_trigger_t1_raw; +wire ifu_rtu_reset_halt_req; +wire int_retire_pending_int_hv; +wire iu_xx_no_op; +wire lockup_clk; +wire lockup_clk_en; +wire lockup_retire_dbg_vld; +wire lockup_retire_nmi_vld; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_async_ld_inst; +wire [31:0] lsu_rtu_async_tval; +wire lsu_rtu_ex2_bus_err; +wire lsu_rtu_ex2_stall; +wire [31:0] lsu_rtu_ex2_tval; +wire lsu_rtu_sync_ack; +wire lsu_xx_no_op; +wire pad_yy_icg_scan_en; +wire retire_async_expt; +wire retire_async_expt_en; +wire [11:0] retire_async_expt_vec; +wire retire_async_trap_vld; +wire [31:0] retire_async_tval; +wire retire_bkpt_expt; +wire retire_bkpt_expt_lsu_trigger_t1; +wire retire_bkpt_expt_split_lsu_trigger_t1; +wire retire_bkpt_expt_t1; +wire retire_cbus_debug_may_spec_fail; +wire retire_cbus_ex2_stall; +wire retire_cbus_flush_stall; +wire [31:0] retire_chgflw_pc; +wire retire_chgflw_vld; +wire retire_clk; +wire retire_clk_en; +wire retire_cpu_no_op; +wire retire_dbg_mode_async_trap_vld; +wire retire_dbg_stall; +wire retire_dbg_stall_set; +wire retire_debug_flush; +wire retire_ex2_retire_normal; +wire retire_ex2_retire_vld; +wire retire_exit_debug; +wire retire_expt_debug; +wire retire_expt_inst; +wire retire_flush_be; +wire retire_flush_fe; +wire retire_flush_fe_set; +wire retire_flush_stall; +wire [14:0] retire_halt_info; +wire retire_inst_expt; +wire [11:0] retire_inst_expt_vec; +wire retire_int_inst; +wire retire_int_nmi_ack; +wire retire_int_vld; +wire retire_lockup_dbg_req; +wire retire_lockup_dbgon; +wire retire_lockup_expt_vld; +wire retire_lockup_nmi_exit; +wire [31:0] retire_lockup_retire_pc; +wire retire_lockup_retire_vld; +wire retire_nmi_inst; +wire retire_nmi_vld; +wire retire_pending_bkpt_expt; +wire retire_sync_debug_may_spec_fail; +wire retire_sync_expt; +wire retire_tail_int_vld; +wire retire_top_dbg_mode_on; +wire retire_top_dbg_stall; +wire [2 :0] retire_top_flush_cur_state; +wire retire_top_lsu_ex2_stall; +wire [31:0] retire_trap_epc; +wire retire_trap_epc_sel_cur_pc; +wire retire_trap_tval_ex1; +wire retire_trap_vld; +wire retire_xx_ex2_expt_raw; +wire rtu_cp0_bus_error; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_nmi_vld; +wire [31:0] rtu_cp0_tval; +wire [31:0] rtu_dtu_dpc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_pending_ack; +wire rtu_dtu_retire_chgflw; +wire rtu_dtu_retire_debug_expt_vld; +wire rtu_dtu_retire_mret; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; +wire rtu_hpcp_retire_inst_vld; +wire rtu_idu_flush_fe; +wire rtu_idu_flush_stall; +wire rtu_idu_inst_retire; +wire rtu_idu_late_flush; +wire [31:0] rtu_ifu_chgflw_pc; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_dbg_mask; +wire rtu_ifu_flush_fe; +wire rtu_lsu_async_expt_ack; +wire rtu_lsu_expt_ack; +wire rtu_lsu_expt_exit; +wire rtu_lsu_inst_retire; +wire rtu_lsu_sync_req; +wire rtu_pad_inst_retire; +wire rtu_pad_inst_split; +wire [31:0] rtu_pad_retire_pc; +wire rtu_sysio_halted; +wire rtu_xx_no_op; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; + + +//========================================================== +// Retire valid signals +//========================================================== +assign retire_ex2_retire_vld = cbus_retire_ex2_inst_vld + && !cbus_retire_ex2_tail_spec_inst + && !lsu_rtu_ex2_stall + && !retire_dbg_stall; + +assign retire_ex2_retire_normal = retire_ex2_retire_vld + && !retire_sync_expt; + +//========================================================== +// Retire Exception Process +//========================================================== +//---------------------------------------------------------- +// Expt +//---------------------------------------------------------- +// Expt source includes: +// 1. EX1 Expt +// 2. bus error +// 3. breakpoint +assign retire_inst_expt = cbus_retire_ex2_expt_inst || retire_bkpt_expt; +assign retire_inst_expt_vec[11:0] = cbus_retire_ex2_trap_vec[11:0]; + +assign retire_async_expt_en = (cp0_xx_async_expt_en || !lsu_rtu_async_ld_inst) + && !cbus_retire_ex2_split_inst; +assign retire_async_expt = lsu_rtu_async_expt_vld; +assign retire_async_expt_vec[11:0] = lsu_rtu_async_ld_inst ? 12'd5 : 12'd7; +assign retire_async_tval[31:0] = lsu_rtu_async_tval[31:0]; + +assign retire_sync_expt = retire_inst_expt + || retire_pending_bkpt_expt; + +assign retire_expt_inst = retire_sync_expt + || retire_async_expt; +//expt in debug mode: expt except bkpt will set cmderr3 +assign retire_expt_debug = retire_pending_bkpt_expt + || retire_async_expt + || cbus_retire_ex2_expt_inst + && !retire_bkpt_expt; +assign retire_int_inst = cbus_retire_ex2_inst_int; +assign retire_nmi_inst = cbus_retire_ex2_inst_nmi; + +assign retire_xx_ex2_expt_raw = retire_expt_inst; + +//---------------------------------------------------------- +// Trap Vector +//---------------------------------------------------------- +// Trap level: +// 1. pending bkpt expt +// 2. NMI +// 3. Int +// 4. async expt +// 5. sync expt +// &CombBeg; @84 +always @( retire_int_inst + or retire_async_expt_vec[11:0] + or retire_async_expt + or retire_bkpt_expt + or retire_inst_expt_vec[11:0] + or retire_nmi_inst + or lockup_retire_nmi_vld + or retire_pending_bkpt_expt) +begin + if (retire_pending_bkpt_expt) begin + retire_trap_vec[11:0] = 12'd3; + + //retire_trap_ack_sync = 1'b1; + retire_trap_ack_async = 1'b0; + retire_trap_ack_int = 1'b0; + retire_trap_ack_nmi = 1'b0; + end + else if (retire_nmi_inst || lockup_retire_nmi_vld) begin // nmi + retire_trap_vec[11:0] = 12'd24; + + //retire_trap_ack_sync = 1'b0; + retire_trap_ack_async = 1'b0; + retire_trap_ack_int = 1'b0; + retire_trap_ack_nmi = 1'b1; + end + else if (retire_int_inst) begin + retire_trap_vec[11:0] = retire_inst_expt_vec[11:0]; + + //retire_trap_ack_sync = 1'b0; + retire_trap_ack_async = 1'b0; + retire_trap_ack_int = 1'b1; + retire_trap_ack_nmi = 1'b0; + end + else if (retire_async_expt) begin // async expt + retire_trap_vec[11:0] = retire_async_expt_vec[11:0]; + + //retire_trap_ack_sync = 1'b0; + retire_trap_ack_async = 1'b1; + retire_trap_ack_int = 1'b0; + retire_trap_ack_nmi = 1'b0; + end + else if (retire_bkpt_expt) begin + retire_trap_vec[11:0] = 12'd3; + + //retire_trap_ack_sync = 1'b1; + retire_trap_ack_async = 1'b0; + retire_trap_ack_int = 1'b0; + retire_trap_ack_nmi = 1'b0; + end + else begin + retire_trap_vec[11:0] = retire_inst_expt_vec[11:0]; + + //retire_trap_ack_sync = 1'b1; + retire_trap_ack_async = 1'b0; + retire_trap_ack_int = 1'b0; + retire_trap_ack_nmi = 1'b0; + end +// &CombEnd; @133 +end + +//---------------------------------------------------------- +// Trap TVAL +//---------------------------------------------------------- +//assign retire_trap_tval_pc = cbus_retire_ex2_expt_inst +// && (cbus_retire_ex2_trap_vec[3:0] == 4'h1 +// || cbus_retire_ex2_trap_vec[3:0] == 4'hc); +assign retire_trap_tval_ex1 = cbus_retire_ex2_expt_inst + && (cbus_retire_ex2_trap_vec[3:0] == 4'h1 + || cbus_retire_ex2_trap_vec[3:0] == 4'h2 + || cbus_retire_ex2_trap_vec[3:0] == 4'h4 + || cbus_retire_ex2_trap_vec[3:0] == 4'h5 + || cbus_retire_ex2_trap_vec[3:0] == 4'h6 + || cbus_retire_ex2_trap_vec[3:0] == 4'h7 + || cbus_retire_ex2_trap_vec[3:0] == 4'hc); + +// For tval proirity: +// 1. pending bkpt expt +// 2. NMI (do not update tval) +// 3. Int +// 4. async expt +// 5. sync expt +// &CombBeg; @156 +always @( dtu_rtu_pending_tval[31:0] + or retire_int_inst + or bkpt_req_trigger_t0 + or retire_async_expt + or retire_async_tval[31:0] + or retire_trap_tval_ex1 + or cbus_retire_ex2_tval[31:0] + or retire_pending_bkpt_expt) +begin + if (retire_pending_bkpt_expt) + retire_trap_tval[31:0] = dtu_rtu_pending_tval[31:0]; + else if (retire_int_inst) + retire_trap_tval[31:0] = 32'b0; + else if (retire_async_expt) + retire_trap_tval[31:0] = retire_async_tval[31:0]; +// else if (retire_trap_tval_pc) +// retire_trap_tval[31:0] = cbus_retire_ex2_cur_pc[31:0]; + else if (retire_trap_tval_ex1 || bkpt_req_trigger_t0) + retire_trap_tval[31:0] = cbus_retire_ex2_tval[31:0]; + else + retire_trap_tval[31:0] = 32'b0; +// &CombEnd @169 +end + +//---------------------------------------------------------- +// Trap EPC +//---------------------------------------------------------- +assign retire_trap_epc_sel_cur_pc = retire_sync_expt + || retire_async_expt + && (!retire_async_expt_en + || cbus_retire_ex2_inst_tail_int) + || (retire_int_inst || retire_nmi_inst) + && cbus_retire_ex2_ipop_int_mask; + +assign retire_trap_epc[31:0] = retire_trap_epc_sel_cur_pc + ? cbus_retire_ex2_cur_pc[31:0] + : cbus_retire_ex2_next_pc[31:0]; + +//---------------------------------------------------------- +// Sync Trap Ack +//---------------------------------------------------------- +assign retire_trap_vld = retire_ex2_retire_vld + && !halt_req && !dbg_mode_on + && (retire_expt_inst || retire_int_inst || retire_nmi_inst) + || lockup_retire_nmi_vld; + +//assign retire_sync_trap_vld = retire_ex2_retire_vld +// && !halt_req && !dbg_mode_on +// && retire_trap_ack_sync; + +assign retire_nmi_vld = retire_ex2_retire_vld + && !halt_req && !dbg_mode_on + && retire_trap_ack_nmi; + +assign retire_int_vld = retire_ex2_retire_vld + && !halt_req && !dbg_mode_on + && retire_trap_ack_int; + +assign retire_tail_int_vld = retire_ex2_retire_vld + && !halt_req && !dbg_mode_on + && !retire_expt_inst + && cbus_retire_ex2_inst_tail_int; + +assign retire_int_nmi_ack = retire_nmi_vld || lockup_retire_nmi_vld; + +//---------------------------------------------------------- +// Async Trap Ack +//---------------------------------------------------------- +//for lsu +assign retire_async_trap_vld = retire_async_expt + && (retire_trap_vld + && retire_trap_ack_async); +// || dbg_mode_on_after_req); +//debug mode async trap +assign retire_dbg_mode_async_trap_vld = retire_async_expt + && retire_ex2_retire_vld + && !retire_pending_bkpt_expt; + +//========================================================== +// Changeflow +//========================================================== +assign retire_chgflw_vld = retire_ex2_retire_vld && !retire_trap_vld + && (cbus_retire_ex2_chgflw_vld + || cbus_retire_ex2_flush) + || retire_exit_debug; + +assign retire_chgflw_pc[31:0] = retire_exit_debug + ? dtu_rtu_dpc[31:0] + : cbus_retire_ex2_next_pc[31:0]; + +//========================================================== +// Debug Process +//========================================================== +parameter STALL_IDLE = 2'b00; +parameter STALL_SET = 2'b01; +parameter STALL_RETIRE = 2'b10; + +//---------------------------------------------------------- +// Debug Stall +//---------------------------------------------------------- +assign retire_dbg_stall_set = cbus_retire_ex2_inst_vld + && !dbg_mode_on + && (cbus_retire_ex2_may_debug + || retire_sync_debug_may_spec_fail); +assign rtu_lsu_sync_req = retire_dbg_stall_set; + +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dbg_stall_cur_state[1:0] <= 2'b0; + else + dbg_stall_cur_state[1:0] <= dbg_stall_next_state[1:0]; +end + +// &CombBeg; @262 +always @( retire_ex2_retire_vld + or lsu_rtu_sync_ack + or dbg_stall_cur_state[1:0] + or retire_dbg_stall_set) +begin + case(dbg_stall_cur_state[1:0]) + STALL_IDLE: + if (retire_dbg_stall_set) + dbg_stall_next_state[1:0] = STALL_SET; + else + dbg_stall_next_state[1:0] = STALL_IDLE; + STALL_SET: + if (lsu_rtu_sync_ack) + dbg_stall_next_state[1:0] = STALL_RETIRE; + else + dbg_stall_next_state[1:0] = STALL_SET; + STALL_RETIRE: + if (retire_ex2_retire_vld) + dbg_stall_next_state[1:0] = STALL_IDLE; + else + dbg_stall_next_state[1:0] = STALL_RETIRE; + default: + dbg_stall_next_state[1:0] = STALL_IDLE; + endcase +// &CombEnd; @282 +end + +assign retire_dbg_stall = (dbg_stall_cur_state[1:0] == STALL_IDLE) + && retire_dbg_stall_set + || (dbg_stall_cur_state[1:0] == STALL_SET); +assign retire_top_dbg_stall = retire_dbg_stall; + +//---------------------------------------------------------- +// Halt Request : Timing 0 +//---------------------------------------------------------- +//t0 halt request will enter debug mode when not in debug mode +assign halt_req_reset = ifu_rtu_reset_halt_req; +//async halt req ignore dbg_mode_on +assign halt_req_dm_async = dtu_rtu_async_halt_req; +//ack dm sync halt req in lockup without inst retire +assign halt_req_lockup_dm_sync = lockup_retire_dbg_vld; +assign halt_req_ebreak = retire_ex2_retire_vld + && dtu_rtu_ebreak_action + && cbus_retire_ex2_inst_ebreak + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && !dbg_mode_on_after_req; +assign halt_req_trigger_t0 = retire_ex2_retire_vld + && cbus_retire_ex2_halt_info[`TDT_HINFO_MATCH] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_CHAIN] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_TIMING] + && cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && !dbg_mode_on_after_req; +assign halt_req_pending = retire_ex2_retire_vld + && cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION] + && !dbg_mode_on_after_req; +//t0 halt request +assign halt_req = halt_req_reset + || halt_req_ebreak + || halt_req_trigger_t0 + || halt_req_pending + || halt_req_dm_async + || halt_req_lockup_dm_sync; + +//---------------------------------------------------------- +// Halt Request : Timing 1 +//---------------------------------------------------------- +//cannot ack t1 halt request when: +//1.inst with pending halt or expt +//2.in debug mode +assign halt_req_t1_retire_vld_raw = retire_ex2_retire_vld + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && !dbg_mode_on_after_req; +//3.ack t0 halt request +//4.t1 bkpt expt request (see below) +assign halt_req_t1_retire_vld = halt_req_t1_retire_vld_raw + && !halt_req; +//Halt Request with Timing 1 +assign halt_req_dm_sync = halt_req_t1_retire_vld + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int + && dtu_rtu_sync_halt_req; +assign halt_req_step = halt_req_t1_retire_vld + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int + && dtu_rtu_step_en; +assign halt_req_trigger_t1_raw = halt_req_t1_retire_vld + && cbus_retire_ex2_halt_info[`TDT_HINFO_MATCH] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_CHAIN] + && cbus_retire_ex2_halt_info[`TDT_HINFO_TIMING] + && cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION]; +// &Force("nonport","veri_halt_req_t1"); @350 + +//split inst t1 trigger will be buffered and ack in last split inst +assign halt_req_trigger_t1 = halt_req_trigger_t1_raw + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int; +assign halt_req_split_trigger_t1 = halt_req_trigger_t1_raw + && (cbus_retire_ex2_split_inst + || cbus_retire_ex2_inst_tail_int); +//buffered split trigger will ack at non-split inst +assign halt_req_buf_split_trigger_t1 = halt_req_t1_retire_vld + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int + && halt_req_split_trigger_t1_buf; + +//t1 halt request will generate inst flush and signal dtu pending halt +assign halt_req_t1_raw = halt_req_dm_sync + || halt_req_trigger_t1 + || halt_req_buf_split_trigger_t1 + || halt_req_step; + +//cannot ack t1 halt request when: +//4.t1 bkpt expt request +assign halt_req_t1 = halt_req_t1_raw + && !retire_bkpt_expt_t1; + +//---------------------------------------------------------- +// Bkpt Expt Request : Timing 0 +//---------------------------------------------------------- +assign bkpt_req_ebreak = retire_ex2_retire_vld + && !dtu_rtu_ebreak_action + && cbus_retire_ex2_inst_ebreak + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT]; +assign bkpt_req_pending = retire_ex2_retire_vld + && cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION]; + +assign bkpt_req_trigger_t0 = retire_ex2_retire_vld + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT] + && cbus_retire_ex2_halt_info[`TDT_HINFO_MATCH] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_CHAIN] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_TIMING] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION]; +//normal bkpt expt includes ebreak and t0 trigger +assign retire_bkpt_expt = bkpt_req_ebreak + || bkpt_req_trigger_t0; +//pending bkpt expt has highest priority +assign retire_pending_bkpt_expt = bkpt_req_pending; + +//---------------------------------------------------------- +// Bkpt Expt Request : Timing 1 +//---------------------------------------------------------- +//cannot ack t1 halt request when: +//1.inst with pending halt or expt +assign bkpt_req_t1_retire_vld_raw = retire_ex2_retire_vld + && !cbus_retire_ex2_halt_info[`TDT_HINFO_PENDING_HALT]; +//2.ack t0 halt request +assign bkpt_req_t1_retire_vld = bkpt_req_t1_retire_vld_raw + && !halt_req; +//Halt Request with Timing 1 +assign bkpt_req_trigger_t1_raw = bkpt_req_t1_retire_vld + && cbus_retire_ex2_halt_info[`TDT_HINFO_MATCH] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_CHAIN] + && cbus_retire_ex2_halt_info[`TDT_HINFO_TIMING] + && !cbus_retire_ex2_halt_info[`TDT_HINFO_ACTION]; +// &Force("nonport","veri_retire_bkpt_expt_t1"); @434 +//split inst t1 trigger will be buffered and ack in last split inst +assign bkpt_req_trigger_t1 = bkpt_req_trigger_t1_raw + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int; +assign bkpt_req_split_trigger_t1 = bkpt_req_trigger_t1_raw + && (cbus_retire_ex2_split_inst + || cbus_retire_ex2_inst_tail_int); +//buffered split trigger will ack at non-split inst +assign bkpt_req_buf_split_trigger_t1 = bkpt_req_t1_retire_vld + && bkpt_req_split_trigger_t1_buf + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int; + +assign retire_bkpt_expt_t1 = bkpt_req_trigger_t1 + || bkpt_req_buf_split_trigger_t1; + +assign retire_bkpt_expt_lsu_trigger_t1 = bkpt_req_trigger_t1 + && cbus_retire_ex2_halt_info[`TDT_HINFO_LDST]; +assign retire_bkpt_expt_split_lsu_trigger_t1 = bkpt_req_buf_split_trigger_t1 + && bkpt_req_split_lsu_trigger_buf; + +//---------------------------------------------------------- +// May Debug Signal +//---------------------------------------------------------- +//dtu or dm may produce spec fail, signal cbus to stall ex1 inst commit +assign retire_cbus_debug_may_spec_fail = ifu_rtu_reset_halt_req + || dtu_rtu_async_halt_req + || lockup_retire_dbg_vld + || dtu_rtu_resume_req + || cbus_retire_ex2_inst_vld + && (dtu_rtu_sync_halt_req + || dtu_rtu_step_en + || halt_req_split_trigger_t1_buf + || bkpt_req_split_trigger_t1_buf + || dtu_rtu_sync_flush); +//sync (may) debug request should tirgger debug stall +assign retire_sync_debug_may_spec_fail = cbus_retire_ex2_inst_vld + && (dtu_rtu_sync_halt_req + || dtu_rtu_step_en + || halt_req_split_trigger_t1_buf + || bkpt_req_split_trigger_t1_buf + || dtu_rtu_sync_flush); + +//---------------------------------------------------------- +// Debug Sync Flush +//---------------------------------------------------------- +//when dtu signal sync flush, rtu should flush when any inst +//retire: include step and icount +assign retire_debug_flush = retire_ex2_retire_vld + && dtu_rtu_sync_flush + && !cbus_retire_ex2_split_inst + && !cbus_retire_ex2_inst_tail_int + && !dbg_mode_on_after_req; + +//---------------------------------------------------------- +// Exit Debug Mode +//---------------------------------------------------------- +//exit debug ignore exception: +//execute dret in debug mode should not generate exception +assign retire_exit_debug = dbg_mode_on_after_req + && (dtu_rtu_resume_req + || retire_ex2_retire_vld + && cbus_retire_ex2_inst_dret); + +//---------------------------------------------------------- +// Cause Select +//---------------------------------------------------------- +//select cause according to priority +//not includes itrigger and etrigger, which fire in +// &CombBeg; @512 +always @( halt_req_trigger_t0 + or halt_req_buf_split_trigger_t1 + or halt_req_pending + or halt_req_dm_sync + or lockup_retire_dbg_vld + or cbus_retire_ex2_halt_info[11:8] + or halt_req_reset + or halt_req_ebreak + or halt_req_trigger_t1 + or halt_req_dm_async) +begin + if(halt_req_dm_async) + halt_cause[3:0] = 4'd8; + else if(halt_req_pending) + halt_cause[3:0] = cbus_retire_ex2_halt_info[`TDT_HINFO_CAUSE:`TDT_HINFO_CAUSE-3]; + else if(halt_req_trigger_t0 + || halt_req_trigger_t1 + || halt_req_buf_split_trigger_t1) + halt_cause[3:0] = 4'd2; + else if(halt_req_ebreak) + halt_cause[3:0] = 4'd1; + else if(halt_req_reset) + halt_cause[3:0] = 4'd5; + else if(halt_req_dm_sync) + halt_cause[3:0] = 4'd3; + else if(lockup_retire_dbg_vld) + halt_cause[3:0] = 4'd3; + else //halt_req_step + halt_cause[3:0] = 4'd4; +// &CombEnd; @531 +end + +//---------------------------------------------------------- +// Debug Mode +//---------------------------------------------------------- +//debug mode on after request: +//used to mask ifu inst fetch and new halt request +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dbg_mode_on_after_req <= 1'b0; + else if (halt_req) + dbg_mode_on_after_req <= 1'b1; + else if (retire_exit_debug) + dbg_mode_on_after_req <= 1'b0; +end + +//debug mode on after flush be: +//indicate hart is in halt +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + dbg_mode_on <= 1'b0; + else if (retire_flush_be && dbg_mode_on_after_req) + dbg_mode_on <= 1'b1; + else if (retire_exit_debug) + dbg_mode_on <= 1'b0; +end + +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + retire_async_flush <= 1'b0; + else + retire_async_flush <= halt_req_dm_async; +end + +//---------------------------------------------------------- +// Split inst t1 halt info +//---------------------------------------------------------- +//if split inst hit t0 trigger, it will ack as normal inst +//if split inst hit t1 trigger, rtu will buffer and merge +//halt info, then ack at last split inst (!split) +//if split inst flush, t1 halt info will be flushed +//chain 1 match will clear/not merge into halt info +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + halt_req_split_trigger_t1_buf <= 1'b0; + else if (retire_flush_be || halt_req_trigger_t1) + halt_req_split_trigger_t1_buf <= 1'b0; + else if (halt_req_split_trigger_t1) + halt_req_split_trigger_t1_buf <= 1'b1; +end + +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + bkpt_req_split_trigger_t1_buf <= 1'b0; + bkpt_req_split_lsu_trigger_buf <= 1'b0; + end + else if (retire_flush_be || bkpt_req_trigger_t1) begin + bkpt_req_split_trigger_t1_buf <= 1'b0; + bkpt_req_split_lsu_trigger_buf <= 1'b0; + end + else if (bkpt_req_split_trigger_t1) begin + bkpt_req_split_trigger_t1_buf <= 1'b1; + bkpt_req_split_lsu_trigger_buf <= cbus_retire_ex2_halt_info[`TDT_HINFO_LDST]; + end +end + +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + retire_buf_split_trigger_t1_halt_info[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + else if (retire_flush_be || halt_req_trigger_t1 || bkpt_req_trigger_t1) + retire_buf_split_trigger_t1_halt_info[`TDT_HINFO_WIDTH-1:0] <= {`TDT_HINFO_WIDTH{1'b0}}; + else if (halt_req_split_trigger_t1 || bkpt_req_split_trigger_t1) + retire_buf_split_trigger_t1_halt_info[`TDT_HINFO_WIDTH-1:0] <= + retire_buf_split_trigger_t1_halt_info[`TDT_HINFO_WIDTH-1:0] + | cbus_retire_ex2_halt_info[`TDT_HINFO_WIDTH-1:0]; +end + +//---------------------------------------------------------- +// Retire Halt Info +//---------------------------------------------------------- +//if there is buffered split trigger t1 halt/bkpt req +//merge buffered halt info into retired halt info +assign retire_halt_info[`TDT_HINFO_WIDTH-1:0] = + cbus_retire_ex2_halt_info[`TDT_HINFO_WIDTH-1:0] + | {`TDT_HINFO_WIDTH{(halt_req_buf_split_trigger_t1 + || bkpt_req_buf_split_trigger_t1)}} + & retire_buf_split_trigger_t1_halt_info[`TDT_HINFO_WIDTH-1:0]; +// &Force("input", "cbus_retire_ex2_halt_info"); @628 +// &Force("bus", "cbus_retire_ex2_halt_info",`TDT_HINFO_WIDTH-1,0); @629 +// &Force("input", "cbus_retire_ex2_inst_branch"); @630 +// &Force("input", "cbus_retire_ex2_inst_dret"); @631 +// &Force("input", "cbus_retire_ex2_inst_ebreak"); @632 +// &Force("input", "cbus_retire_ex2_may_debug"); @633 +// &Force("input", "lockup_retire_dbg_vld"); @634 +// &Force("input", "dtu_rtu_async_halt_req"); @635 +// &Force("input", "dtu_rtu_ebreak_action"); @636 +// &Force("input", "dtu_rtu_resume_req"); @637 +// &Force("input", "dtu_rtu_step_en"); @638 +// &Force("input", "dtu_rtu_sync_flush"); @639 +// &Force("input", "lsu_rtu_sync_ack"); @640 + +//========================================================== +// Flush Control +//========================================================== +//---------------------------------------------------------- +// Flush Set +//---------------------------------------------------------- +// Flush fe will be set when: +// 1. expt +// 2. flush inst (cannot flush when ack int because of idu ipush sm) +// 3. t1 bkpt expt +// 4. t0 and t1 halt req: +// halt req will sync with inst retire by itself +assign retire_flush_fe_set = retire_ex2_retire_vld + && (retire_expt_inst + || retire_nmi_inst + || lockup_retire_nmi_vld + || cbus_retire_ex2_flush + && !retire_trap_ack_int + || retire_bkpt_expt_t1 + || retire_debug_flush) + || halt_req + || halt_req_t1; +//pipeline no operation +assign retire_cpu_no_op = lsu_xx_no_op + && iu_xx_no_op + && fpu_xx_no_op + && rtu_xx_no_op; + +//---------------------------------------------------------- +// Flush FSM +//---------------------------------------------------------- +parameter FLUSH_IDLE = 3'b000; +parameter FLUSH_FE = 3'b101; +parameter FLUSH_WAIT = 3'b100; +parameter FLUSH_BE = 3'b110; +parameter FLUSH_FE_BE = 3'b111; + +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + flush_cur_state[2:0] <= 3'b0; + else if (halt_req_dm_async) + flush_cur_state[2:0] <= FLUSH_FE_BE; + else + flush_cur_state[2:0] <= flush_next_state[2:0]; +end + +// &CombBeg; @716 +always @( flush_cur_state[2:0] + or retire_cpu_no_op + or retire_flush_fe_set) +begin + case(flush_cur_state[2:0]) + FLUSH_IDLE: + if (retire_flush_fe_set) + flush_next_state[2:0] = FLUSH_FE; + else + flush_next_state[2:0] = FLUSH_IDLE; + FLUSH_FE: + if (retire_cpu_no_op) + flush_next_state[2:0] = FLUSH_BE; + else + flush_next_state[2:0] = FLUSH_WAIT; + FLUSH_WAIT: + if (retire_cpu_no_op) + flush_next_state[2:0] = FLUSH_BE; + else + flush_next_state[2:0] = FLUSH_WAIT; + FLUSH_BE: + flush_next_state[2:0] = FLUSH_IDLE; + FLUSH_FE_BE: + flush_next_state[2:0] = FLUSH_IDLE; + default: + flush_next_state[2:0] = FLUSH_IDLE; + endcase +// &CombEnd; @740 +end + +assign retire_flush_stall = flush_cur_state[2]; +assign retire_flush_fe = flush_cur_state[0]; +assign retire_flush_be = flush_cur_state[1]; +//output +assign retire_top_flush_cur_state[2:0] = flush_cur_state[2:0]; + +//---------------------------------------------------------- +// Int Flush +//---------------------------------------------------------- +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) + retire_int_flush <= 1'b0; + else if (retire_flush_be) + retire_int_flush <= 1'b0; + else if (retire_trap_vld && retire_expt_inst && retire_trap_ack_int) + retire_int_flush <= 1'b1; +end + +//---------------------------------------------------------- +// Buffer retire info for flush be +//---------------------------------------------------------- +always @ (posedge retire_clk or negedge cpurst_b) +begin + if (!cpurst_b) begin + retire_buf_trap_vld <= 1'b0; + retire_buf_xret_vld <= 1'b0; + //retire_buf_sync_trap_vld <= 1'b0; + retire_buf_async_trap_vld <= 1'b0; + end + else if (retire_ex2_retire_vld) begin + retire_buf_trap_vld <= retire_trap_vld; + retire_buf_xret_vld <= retire_ex2_retire_normal + && cbus_retire_ex2_inst_mret; + //retire_buf_sync_trap_vld <= retire_sync_trap_vld; + retire_buf_async_trap_vld <= retire_async_trap_vld; + end + else if (retire_flush_be) begin + retire_buf_trap_vld <= 1'b0; + retire_buf_xret_vld <= 1'b0; + //retire_buf_sync_trap_vld <= 1'b0; + retire_buf_async_trap_vld <= 1'b0; + end +end + +//========================================================== +// Output +//========================================================== +//---------------------------------------------------------- +// For XX +//---------------------------------------------------------- +assign rtu_yy_xx_flush = retire_flush_be; +assign rtu_yy_xx_async_flush = retire_async_flush; +assign rtu_yy_xx_expt_vld = retire_trap_vld; +assign rtu_yy_xx_tail_int_vld = retire_tail_int_vld; +assign rtu_yy_xx_expt_int = retire_int_vld; +assign rtu_yy_xx_expt_vec[11:0] = retire_trap_vec[11:0]; +assign rtu_yy_xx_dbgon = dbg_mode_on; + +assign rtu_yy_xx_int_hv = cbus_retire_ex2_inst_tail_int + ? int_retire_pending_int_hv + : cbus_retire_ex2_int_hv; + +// &Force("output", "rtu_xx_no_op"); @807 +assign rtu_xx_no_op = !cbus_retire_ex2_inst_vld; + +assign retire_top_dbg_mode_on = dbg_mode_on_after_req; + +//---------------------------------------------------------- +// For Pad +//---------------------------------------------------------- +assign rtu_pad_inst_retire = retire_ex2_retire_vld; +assign rtu_pad_inst_split = cbus_retire_ex2_split_inst; +assign rtu_pad_retire_pc[31:0] = cbus_retire_ex2_cur_pc[31:0]; +assign rtu_sysio_halted = dbg_mode_on; + +//---------------------------------------------------------- +// For DTU +//---------------------------------------------------------- +//trigger signals +// &CombBeg; @825 +always @( halt_req_t1_raw + or halt_req + or retire_bkpt_expt_t1 + or halt_req_buf_split_trigger_t1 + or bkpt_req_buf_split_trigger_t1 + or halt_req_t1 + or retire_halt_info[14:0] + or halt_cause[3:0]) +begin + rtu_dtu_retire_halt_info[`TDT_HINFO_WIDTH-1:0] = retire_halt_info[`TDT_HINFO_WIDTH-1:0]; + if(1'b1) begin + rtu_dtu_retire_halt_info[`TDT_HINFO_ACTION] = halt_req || halt_req_t1; + rtu_dtu_retire_halt_info[`TDT_HINFO_PENDING_HALT] = halt_req_t1 || retire_bkpt_expt_t1; + rtu_dtu_retire_halt_info[`TDT_HINFO_ACTION01] = retire_halt_info[`TDT_HINFO_ACTION01] + || halt_req_buf_split_trigger_t1 + && bkpt_req_buf_split_trigger_t1 + || retire_bkpt_expt_t1 + && halt_req_t1_raw; + rtu_dtu_retire_halt_info[`TDT_HINFO_CAUSE:`TDT_HINFO_CAUSE-3] = halt_cause[3:0]; + end +// &CombEnd; @837 +end + +//halt signals +assign rtu_dtu_dpc[31:0] = cbus_retire_ex2_cur_pc[31:0]; + +// &CombBeg; @842 +always @( retire_bkpt_expt_split_lsu_trigger_t1 + or cbus_retire_ex2_cur_pc[31:0] + or lsu_rtu_ex2_tval[31:0] + or retire_bkpt_expt_lsu_trigger_t1) +begin + //if load/store mcontrol, update load/store address + if(retire_bkpt_expt_lsu_trigger_t1) + rtu_dtu_tval[31:0] = lsu_rtu_ex2_tval[31:0]; + //if split load/store mcontrol, update 0 + else if(retire_bkpt_expt_split_lsu_trigger_t1) + rtu_dtu_tval[31:0] = 32'b0; + //otherwise update cur pc + else + rtu_dtu_tval[31:0] = cbus_retire_ex2_cur_pc[31:0]; +// &CombEnd; @852 +end + +assign rtu_dtu_halt_ack = halt_req; +assign rtu_dtu_pending_ack = halt_req_pending || bkpt_req_pending; + +//inst retire and pcfifo +assign rtu_dtu_retire_vld = retire_ex2_retire_vld + && (retire_flush_fe_set + || !(cbus_retire_ex2_split_inst + || cbus_retire_ex2_inst_tail_int)); +assign rtu_dtu_retire_debug_expt_vld = retire_ex2_retire_vld + && dbg_mode_on + && retire_expt_debug; +assign rtu_dtu_retire_mret = cbus_retire_ex2_inst_mret; +assign rtu_dtu_retire_chgflw = cbus_retire_ex2_inst_branch; +assign rtu_dtu_retire_next_pc[31:0] = cbus_retire_ex2_next_pc[31:0]; + +//---------------------------------------------------------- +// For IFU +//---------------------------------------------------------- +assign rtu_ifu_chgflw_vld = retire_chgflw_vld; +assign rtu_ifu_flush_fe = retire_flush_fe; +assign rtu_ifu_chgflw_pc[31:0] = retire_chgflw_pc[31:0]; + +assign rtu_ifu_dbg_mask = dbg_mode_on_after_req; + +//---------------------------------------------------------- +// For CP0 +//---------------------------------------------------------- +assign rtu_cp0_epc[31:0] = retire_trap_epc[31:0]; +assign rtu_cp0_tval[31:0] = retire_trap_tval[31:0]; +assign rtu_cp0_exit_debug = retire_exit_debug; +assign rtu_cp0_nmi_vld = retire_nmi_vld || lockup_retire_nmi_vld; +assign rtu_cp0_bus_error = lsu_rtu_ex2_bus_err || lsu_rtu_async_expt_vld; +assign rtu_cp0_int_level[7:0] = cbus_retire_ex2_int_lv[7:0]; + +//---------------------------------------------------------- +// For IDU +//---------------------------------------------------------- +assign rtu_idu_inst_retire = retire_ex2_retire_vld; +assign rtu_idu_flush_stall = retire_flush_stall; +assign rtu_idu_flush_fe = retire_flush_fe; +assign rtu_idu_late_flush = retire_int_flush; + +//---------------------------------------------------------- +// For LSU +//---------------------------------------------------------- +assign rtu_lsu_expt_ack = retire_flush_be && retire_buf_trap_vld; +assign rtu_lsu_expt_exit = retire_flush_be && retire_buf_xret_vld; +//when in debug mode, rtu do not set trap_vld and flush +//so rtu should ack lsu when async inst retire +assign rtu_lsu_async_expt_ack = dbg_mode_on + ? retire_dbg_mode_async_trap_vld + : retire_flush_be && retire_buf_async_trap_vld; +assign rtu_lsu_inst_retire = retire_ex2_retire_vld; + +//---------------------------------------------------------- +// For HPCP +//---------------------------------------------------------- +assign rtu_hpcp_retire_inst_vld = retire_ex2_retire_vld && !cbus_retire_ex2_split_inst; +//assign rtu_hpcp_retire_pc[31:0] = cbus_retire_ex2_cur_pc[31:0]; +//assign rtu_hpcp_int_vld = retire_int_vld; + +//========================================================== +// Lockup +//========================================================== +assign retire_lockup_nmi_exit = cp0_rtu_ex1_mret && cp0_rtu_in_nmi; + +assign retire_lockup_dbg_req = dtu_rtu_sync_halt_req; +assign retire_lockup_expt_vld = retire_trap_vld + && !retire_int_inst + && !retire_nmi_inst + && retire_trap_vec[11:0] != 12'd3 + && retire_trap_vec[11:0] != 12'd11; +assign retire_lockup_retire_vld = retire_ex2_retire_vld; +assign retire_lockup_retire_pc[31:0] = cbus_retire_ex2_cur_pc[31:0]; +assign retire_lockup_dbgon = dbg_mode_on; + +//========================================================== +// Stall +//========================================================== +//stall ex2 pipeline and wait for lsu no op or lsu cmplt +assign retire_cbus_flush_stall = retire_flush_stall; +assign retire_cbus_ex2_stall = retire_dbg_stall + || lsu_rtu_ex2_stall; +assign retire_top_lsu_ex2_stall = lsu_rtu_ex2_stall; + +//========================================================== +// Gate Clk Cell +//========================================================== +assign retire_clk_en = cbus_retire_ex2_inst_vld + || halt_req + || retire_exit_debug + || retire_flush_fe_set + || retire_buf_trap_vld + || retire_buf_xret_vld + || retire_buf_async_trap_vld + || flush_cur_state[2:0] != FLUSH_IDLE + || dbg_stall_cur_state[1:0] != STALL_IDLE + || retire_async_flush + || halt_req_trigger_t1 + || halt_req_split_trigger_t1 + || bkpt_req_trigger_t1 + || bkpt_req_split_trigger_t1 + || lockup_clk_en; + +// &Instance("gated_clk_cell", "x_retire_clk"); @970 +gated_clk_cell x_retire_clk ( + .clk_in (forever_cpuclk ), + .clk_out (retire_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (retire_clk_en ), + .module_en (cp0_rtu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @971 +// .external_en (1'b0), @972 +// .global_en (cp0_yy_clk_en), @973 +// .module_en (cp0_rtu_icg_en), @974 +// .local_en (retire_clk_en), @975 +// .clk_out (retire_clk)); @976 + +assign lockup_clk = retire_clk; + +// &ModuleEnd; @980 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..f334db8e345e673fe22955bc1a443af8b1e62afc --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/rtu/rtl/pa_rtu_top.v @@ -0,0 +1,1142 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_rtu_top( + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + cp0_rtu_ex1_chgflw_pc, + cp0_rtu_ex1_chgflw_vld, + cp0_rtu_ex1_cmplt, + cp0_rtu_ex1_cmplt_dp, + cp0_rtu_ex1_dret, + cp0_rtu_ex1_ebreak, + cp0_rtu_ex1_expt_inst, + cp0_rtu_ex1_expt_tval, + cp0_rtu_ex1_expt_vec, + cp0_rtu_ex1_flush, + cp0_rtu_ex1_halt_info, + cp0_rtu_ex1_inst_len, + cp0_rtu_ex1_inst_vld, + cp0_rtu_ex1_ipush_spec_fail, + cp0_rtu_ex1_mret, + cp0_rtu_ex1_split_inst, + cp0_rtu_ex1_tail_fail, + cp0_rtu_icg_en, + cp0_rtu_in_expt, + cp0_rtu_in_nmi, + cp0_rtu_int_level, + cp0_rtu_int_mode, + cp0_rtu_mie, + cp0_rtu_mnxti_vld, + cp0_rtu_mpil, + cp0_rtu_pm_bypass, + cp0_rtu_tail_int_hv, + cp0_rtu_tail_int_id, + cp0_rtu_wb_data, + cp0_rtu_wb_preg, + cp0_rtu_wb_vld, + cp0_rtu_wfe_en, + cp0_xx_async_expt_en, + cp0_yy_clk_en, + cpu_clic_curid, + cpu_clic_int_exit, + cpurst_b, + dtu_rtu_async_halt_req, + dtu_rtu_dpc, + dtu_rtu_ebreak_action, + dtu_rtu_int_mask, + dtu_rtu_pending_tval, + dtu_rtu_resume_req, + dtu_rtu_step_en, + dtu_rtu_sync_flush, + dtu_rtu_sync_halt_req, + forever_cpuclk, + fpu_rtu_fgpr_wb_data, + fpu_rtu_fgpr_wb_reg, + fpu_rtu_fgpr_wb_vld, + fpu_rtu_wb_data, + fpu_rtu_wb_preg, + fpu_rtu_wb_vld, + fpu_xx_no_op, + idu_yy_xx_tail_ack, + ifu_rtu_lockup_ack, + ifu_rtu_reset_halt_req, + ifu_rtu_warm_up, + iu_rtu_ex1_bju_branch_inst, + iu_rtu_ex1_bju_cmplt, + iu_rtu_ex1_bju_cmplt_dp, + iu_rtu_ex1_bju_cur_pc, + iu_rtu_ex1_bju_inst_len, + iu_rtu_ex1_bju_inst_vld, + iu_rtu_ex1_bju_split_inst, + iu_rtu_ex1_cmplt, + iu_rtu_ex1_cmplt_dp, + iu_rtu_ex1_inst_len, + iu_rtu_ex1_inst_vld, + iu_rtu_ex1_ipop_int_mask, + iu_rtu_ex1_ipush_mie_en, + iu_rtu_ex1_ipush_spec_fail, + iu_rtu_ex1_next_pc, + iu_rtu_ex1_split_inst, + iu_rtu_ex1_tail_int_vld, + iu_rtu_ex2_bju_flush, + iu_rtu_ex2_bju_next_pc, + iu_rtu_ex2_bju_next_pc_vld, + iu_rtu_wb0_data, + iu_rtu_wb0_preg, + iu_rtu_wb0_vld, + iu_xx_no_op, + lsu_rtu_async_expt_vld, + lsu_rtu_async_ld_inst, + lsu_rtu_async_tval, + lsu_rtu_ex1_cmplt, + lsu_rtu_ex1_cmplt_dp, + lsu_rtu_ex1_halt_info, + lsu_rtu_ex1_inst_len, + lsu_rtu_ex1_inst_vld, + lsu_rtu_ex1_ipop_int_mask, + lsu_rtu_ex1_ipush_spec_inst, + lsu_rtu_ex1_split_inst, + lsu_rtu_ex2_bus_err, + lsu_rtu_ex2_expt_inst, + lsu_rtu_ex2_expt_vec, + lsu_rtu_ex2_stall, + lsu_rtu_ex2_tval, + lsu_rtu_fgpr_wb_data, + lsu_rtu_fgpr_wb_reg, + lsu_rtu_fgpr_wb_vld, + lsu_rtu_sync_ack, + lsu_rtu_wb_data, + lsu_rtu_wb_preg, + lsu_rtu_wb_vld, + lsu_xx_no_op, + pad_yy_icg_scan_en, + rtu_cp0_bus_error, + rtu_cp0_epc, + rtu_cp0_exit_debug, + rtu_cp0_fp_dirty_vld, + rtu_cp0_int_level, + rtu_cp0_lockup_clr, + rtu_cp0_lockup_vld, + rtu_cp0_mie_en, + rtu_cp0_mie_gateclk_en, + rtu_cp0_mnxti_pending_vld, + rtu_cp0_nmi_vld, + rtu_cp0_pending_int_hv, + rtu_cp0_pending_int_id, + rtu_cp0_pending_int_level, + rtu_cp0_tval, + rtu_cp0_wk_int, + rtu_dtu_debug_info, + rtu_dtu_dpc, + rtu_dtu_halt_ack, + rtu_dtu_nmi_pending, + rtu_dtu_pending_ack, + rtu_dtu_retire_chgflw, + rtu_dtu_retire_debug_expt_vld, + rtu_dtu_retire_halt_info, + rtu_dtu_retire_mret, + rtu_dtu_retire_next_pc, + rtu_dtu_retire_vld, + rtu_dtu_tval, + rtu_fpu_fgpr_wb_grant, + rtu_fpu_wb_grant, + rtu_hpcp_retire_inst_vld, + rtu_idu_ex1_int_dis_stall_gateclk_req, + rtu_idu_ex1_int_dis_stall_req, + rtu_idu_ex2_ipush_spec_inst_expt_vld, + rtu_idu_ex2_ipush_spec_inst_halt_info_vld, + rtu_idu_fgpr_wb_data, + rtu_idu_fgpr_wb_flsu_vld, + rtu_idu_fgpr_wb_reg, + rtu_idu_fgpr_wb_vld, + rtu_idu_flush_fe, + rtu_idu_flush_stall, + rtu_idu_id_tail_int_vld, + rtu_idu_inst_retire, + rtu_idu_late_flush, + rtu_idu_wb0_data, + rtu_idu_wb0_fpu_vld, + rtu_idu_wb0_preg, + rtu_idu_wb0_vld, + rtu_idu_wb1_data, + rtu_idu_wb1_lsu_vld, + rtu_idu_wb1_preg, + rtu_idu_wb1_vld, + rtu_idu_wb2_data, + rtu_idu_wb2_preg, + rtu_idu_wb2_vld, + rtu_ifu_chgflw_pc, + rtu_ifu_chgflw_vld, + rtu_ifu_dbg_mask, + rtu_ifu_flush_fe, + rtu_ifu_lockup_expt_vld, + rtu_ifu_lockup_mask, + rtu_ifu_lockup_req, + rtu_iu_bju_ex2_cur_pc, + rtu_iu_ex1_cmplt_dp_vld, + rtu_iu_ex1_cmplt_inst_len, + rtu_iu_ex1_cmplt_split_inst, + rtu_iu_ex1_cmplt_vld, + rtu_iu_pending_spec_expt_vld, + rtu_iu_pending_spec_halt_info_vld, + rtu_lsu_async_expt_ack, + rtu_lsu_expt_ack, + rtu_lsu_expt_exit, + rtu_lsu_fgpr_wb_data, + rtu_lsu_fgpr_wb_reg, + rtu_lsu_fgpr_wb_vld, + rtu_lsu_inst_retire, + rtu_lsu_sync_req, + rtu_lsu_wb1_data, + rtu_lsu_wb1_lsu_vld, + rtu_lsu_wb1_preg, + rtu_pad_inst_retire, + rtu_pad_inst_split, + rtu_pad_retire_pc, + rtu_pad_wb0_data, + rtu_pad_wb0_preg, + rtu_pad_wb0_vld, + rtu_pad_wb1_data, + rtu_pad_wb1_preg, + rtu_pad_wb1_vld, + rtu_pad_wb2_data, + rtu_pad_wb2_preg, + rtu_pad_wb2_vld, + rtu_pad_wb_freg, + rtu_pad_wb_freg_data, + rtu_pad_wb_freg_vld, + rtu_sysio_halted, + rtu_sysio_lockup_on, + rtu_xx_ex1_stall, + rtu_xx_no_op, + rtu_yy_xx_async_flush, + rtu_yy_xx_dbgon, + rtu_yy_xx_expt_int, + rtu_yy_xx_expt_vec, + rtu_yy_xx_expt_vld, + rtu_yy_xx_flush, + rtu_yy_xx_int_hv, + rtu_yy_xx_tail_int_vld, + sysio_rtu_nmi_int, + sysio_rtu_wk_event +); + +// &Ports; @24 +input clic_cpu_int_hv; +input [11:0] clic_cpu_int_id; +input [7 :0] clic_cpu_int_il; +input [1 :0] clic_cpu_int_priv; +input [30:0] cp0_rtu_ex1_chgflw_pc; +input cp0_rtu_ex1_chgflw_vld; +input cp0_rtu_ex1_cmplt; +input cp0_rtu_ex1_cmplt_dp; +input cp0_rtu_ex1_dret; +input cp0_rtu_ex1_ebreak; +input cp0_rtu_ex1_expt_inst; +input [31:0] cp0_rtu_ex1_expt_tval; +input [3 :0] cp0_rtu_ex1_expt_vec; +input cp0_rtu_ex1_flush; +input [14:0] cp0_rtu_ex1_halt_info; +input cp0_rtu_ex1_inst_len; +input cp0_rtu_ex1_inst_vld; +input cp0_rtu_ex1_ipush_spec_fail; +input cp0_rtu_ex1_mret; +input cp0_rtu_ex1_split_inst; +input cp0_rtu_ex1_tail_fail; +input cp0_rtu_icg_en; +input cp0_rtu_in_expt; +input cp0_rtu_in_nmi; +input [7 :0] cp0_rtu_int_level; +input [1 :0] cp0_rtu_int_mode; +input cp0_rtu_mie; +input cp0_rtu_mnxti_vld; +input [7 :0] cp0_rtu_mpil; +input [1 :0] cp0_rtu_pm_bypass; +input cp0_rtu_tail_int_hv; +input [11:0] cp0_rtu_tail_int_id; +input [31:0] cp0_rtu_wb_data; +input [5 :0] cp0_rtu_wb_preg; +input cp0_rtu_wb_vld; +input cp0_rtu_wfe_en; +input cp0_xx_async_expt_en; +input cp0_yy_clk_en; +input cpurst_b; +input dtu_rtu_async_halt_req; +input [31:0] dtu_rtu_dpc; +input dtu_rtu_ebreak_action; +input dtu_rtu_int_mask; +input [31:0] dtu_rtu_pending_tval; +input dtu_rtu_resume_req; +input dtu_rtu_step_en; +input dtu_rtu_sync_flush; +input dtu_rtu_sync_halt_req; +input forever_cpuclk; +input [31:0] fpu_rtu_fgpr_wb_data; +input [4 :0] fpu_rtu_fgpr_wb_reg; +input fpu_rtu_fgpr_wb_vld; +input [31:0] fpu_rtu_wb_data; +input [5 :0] fpu_rtu_wb_preg; +input fpu_rtu_wb_vld; +input fpu_xx_no_op; +input idu_yy_xx_tail_ack; +input ifu_rtu_lockup_ack; +input ifu_rtu_reset_halt_req; +input ifu_rtu_warm_up; +input iu_rtu_ex1_bju_branch_inst; +input iu_rtu_ex1_bju_cmplt; +input iu_rtu_ex1_bju_cmplt_dp; +input [30:0] iu_rtu_ex1_bju_cur_pc; +input iu_rtu_ex1_bju_inst_len; +input iu_rtu_ex1_bju_inst_vld; +input iu_rtu_ex1_bju_split_inst; +input iu_rtu_ex1_cmplt; +input iu_rtu_ex1_cmplt_dp; +input iu_rtu_ex1_inst_len; +input iu_rtu_ex1_inst_vld; +input iu_rtu_ex1_ipop_int_mask; +input iu_rtu_ex1_ipush_mie_en; +input iu_rtu_ex1_ipush_spec_fail; +input [30:0] iu_rtu_ex1_next_pc; +input iu_rtu_ex1_split_inst; +input iu_rtu_ex1_tail_int_vld; +input iu_rtu_ex2_bju_flush; +input [30:0] iu_rtu_ex2_bju_next_pc; +input iu_rtu_ex2_bju_next_pc_vld; +input [31:0] iu_rtu_wb0_data; +input [5 :0] iu_rtu_wb0_preg; +input iu_rtu_wb0_vld; +input iu_xx_no_op; +input lsu_rtu_async_expt_vld; +input lsu_rtu_async_ld_inst; +input [31:0] lsu_rtu_async_tval; +input lsu_rtu_ex1_cmplt; +input lsu_rtu_ex1_cmplt_dp; +input [14:0] lsu_rtu_ex1_halt_info; +input lsu_rtu_ex1_inst_len; +input lsu_rtu_ex1_inst_vld; +input lsu_rtu_ex1_ipop_int_mask; +input lsu_rtu_ex1_ipush_spec_inst; +input lsu_rtu_ex1_split_inst; +input lsu_rtu_ex2_bus_err; +input lsu_rtu_ex2_expt_inst; +input [3 :0] lsu_rtu_ex2_expt_vec; +input lsu_rtu_ex2_stall; +input [31:0] lsu_rtu_ex2_tval; +input [31:0] lsu_rtu_fgpr_wb_data; +input [4 :0] lsu_rtu_fgpr_wb_reg; +input lsu_rtu_fgpr_wb_vld; +input lsu_rtu_sync_ack; +input [31:0] lsu_rtu_wb_data; +input [5 :0] lsu_rtu_wb_preg; +input lsu_rtu_wb_vld; +input lsu_xx_no_op; +input pad_yy_icg_scan_en; +input sysio_rtu_nmi_int; +input sysio_rtu_wk_event; +output [11:0] cpu_clic_curid; +output cpu_clic_int_exit; +output rtu_cp0_bus_error; +output [31:0] rtu_cp0_epc; +output rtu_cp0_exit_debug; +output rtu_cp0_fp_dirty_vld; +output [7 :0] rtu_cp0_int_level; +output rtu_cp0_lockup_clr; +output rtu_cp0_lockup_vld; +output rtu_cp0_mie_en; +output rtu_cp0_mie_gateclk_en; +output rtu_cp0_mnxti_pending_vld; +output rtu_cp0_nmi_vld; +output rtu_cp0_pending_int_hv; +output [11:0] rtu_cp0_pending_int_id; +output [7 :0] rtu_cp0_pending_int_level; +output [31:0] rtu_cp0_tval; +output rtu_cp0_wk_int; +output [13:0] rtu_dtu_debug_info; +output [31:0] rtu_dtu_dpc; +output rtu_dtu_halt_ack; +output rtu_dtu_nmi_pending; +output rtu_dtu_pending_ack; +output rtu_dtu_retire_chgflw; +output rtu_dtu_retire_debug_expt_vld; +output [14:0] rtu_dtu_retire_halt_info; +output rtu_dtu_retire_mret; +output [31:0] rtu_dtu_retire_next_pc; +output rtu_dtu_retire_vld; +output [31:0] rtu_dtu_tval; +output rtu_fpu_fgpr_wb_grant; +output rtu_fpu_wb_grant; +output rtu_hpcp_retire_inst_vld; +output rtu_idu_ex1_int_dis_stall_gateclk_req; +output rtu_idu_ex1_int_dis_stall_req; +output rtu_idu_ex2_ipush_spec_inst_expt_vld; +output rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +output [31:0] rtu_idu_fgpr_wb_data; +output rtu_idu_fgpr_wb_flsu_vld; +output [4 :0] rtu_idu_fgpr_wb_reg; +output rtu_idu_fgpr_wb_vld; +output rtu_idu_flush_fe; +output rtu_idu_flush_stall; +output rtu_idu_id_tail_int_vld; +output rtu_idu_inst_retire; +output rtu_idu_late_flush; +output [31:0] rtu_idu_wb0_data; +output rtu_idu_wb0_fpu_vld; +output [5 :0] rtu_idu_wb0_preg; +output rtu_idu_wb0_vld; +output [31:0] rtu_idu_wb1_data; +output rtu_idu_wb1_lsu_vld; +output [5 :0] rtu_idu_wb1_preg; +output rtu_idu_wb1_vld; +output [31:0] rtu_idu_wb2_data; +output [5 :0] rtu_idu_wb2_preg; +output rtu_idu_wb2_vld; +output [31:0] rtu_ifu_chgflw_pc; +output rtu_ifu_chgflw_vld; +output rtu_ifu_dbg_mask; +output rtu_ifu_flush_fe; +output rtu_ifu_lockup_expt_vld; +output rtu_ifu_lockup_mask; +output rtu_ifu_lockup_req; +output [31:0] rtu_iu_bju_ex2_cur_pc; +output rtu_iu_ex1_cmplt_dp_vld; +output rtu_iu_ex1_cmplt_inst_len; +output rtu_iu_ex1_cmplt_split_inst; +output rtu_iu_ex1_cmplt_vld; +output rtu_iu_pending_spec_expt_vld; +output rtu_iu_pending_spec_halt_info_vld; +output rtu_lsu_async_expt_ack; +output rtu_lsu_expt_ack; +output rtu_lsu_expt_exit; +output [31:0] rtu_lsu_fgpr_wb_data; +output [4 :0] rtu_lsu_fgpr_wb_reg; +output rtu_lsu_fgpr_wb_vld; +output rtu_lsu_inst_retire; +output rtu_lsu_sync_req; +output [31:0] rtu_lsu_wb1_data; +output rtu_lsu_wb1_lsu_vld; +output [5 :0] rtu_lsu_wb1_preg; +output rtu_pad_inst_retire; +output rtu_pad_inst_split; +output [31:0] rtu_pad_retire_pc; +output [31:0] rtu_pad_wb0_data; +output [5 :0] rtu_pad_wb0_preg; +output rtu_pad_wb0_vld; +output [31:0] rtu_pad_wb1_data; +output [5 :0] rtu_pad_wb1_preg; +output rtu_pad_wb1_vld; +output [31:0] rtu_pad_wb2_data; +output [5 :0] rtu_pad_wb2_preg; +output rtu_pad_wb2_vld; +output [4 :0] rtu_pad_wb_freg; +output [31:0] rtu_pad_wb_freg_data; +output rtu_pad_wb_freg_vld; +output rtu_sysio_halted; +output rtu_sysio_lockup_on; +output rtu_xx_ex1_stall; +output rtu_xx_no_op; +output rtu_yy_xx_async_flush; +output rtu_yy_xx_dbgon; +output rtu_yy_xx_expt_int; +output [11:0] rtu_yy_xx_expt_vec; +output rtu_yy_xx_expt_vld; +output rtu_yy_xx_flush; +output rtu_yy_xx_int_hv; +output rtu_yy_xx_tail_int_vld; + +// &Regs; @25 + +// &Wires; @26 +wire cbus_int_ex1_split_inst; +wire cbus_int_ipop_int_mask; +wire cbus_int_ipush_mie_en; +wire cbus_retire_ex2_chgflw_vld; +wire [31:0] cbus_retire_ex2_cur_pc; +wire cbus_retire_ex2_expt_inst; +wire cbus_retire_ex2_flush; +wire [14:0] cbus_retire_ex2_halt_info; +wire cbus_retire_ex2_inst_branch; +wire cbus_retire_ex2_inst_dret; +wire cbus_retire_ex2_inst_ebreak; +wire cbus_retire_ex2_inst_int; +wire cbus_retire_ex2_inst_mret; +wire cbus_retire_ex2_inst_nmi; +wire cbus_retire_ex2_inst_tail_int; +wire cbus_retire_ex2_inst_vld; +wire cbus_retire_ex2_int_hv; +wire [7 :0] cbus_retire_ex2_int_lv; +wire cbus_retire_ex2_ipop_int_mask; +wire cbus_retire_ex2_may_debug; +wire [31:0] cbus_retire_ex2_next_pc; +wire cbus_retire_ex2_split_inst; +wire cbus_retire_ex2_tail_spec_inst; +wire [11:0] cbus_retire_ex2_trap_vec; +wire [31:0] cbus_retire_ex2_tval; +wire cbus_top_ex2_inst_vld; +wire cbus_top_ex2_uncommit_stall; +wire clic_cpu_int_hv; +wire [11:0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire [30:0] cp0_rtu_ex1_chgflw_pc; +wire cp0_rtu_ex1_chgflw_vld; +wire cp0_rtu_ex1_cmplt; +wire cp0_rtu_ex1_cmplt_dp; +wire cp0_rtu_ex1_dret; +wire cp0_rtu_ex1_ebreak; +wire cp0_rtu_ex1_expt_inst; +wire [31:0] cp0_rtu_ex1_expt_tval; +wire [3 :0] cp0_rtu_ex1_expt_vec; +wire cp0_rtu_ex1_flush; +wire [14:0] cp0_rtu_ex1_halt_info; +wire cp0_rtu_ex1_inst_len; +wire cp0_rtu_ex1_inst_vld; +wire cp0_rtu_ex1_ipush_spec_fail; +wire cp0_rtu_ex1_mret; +wire cp0_rtu_ex1_split_inst; +wire cp0_rtu_ex1_tail_fail; +wire cp0_rtu_icg_en; +wire cp0_rtu_in_expt; +wire cp0_rtu_in_nmi; +wire [7 :0] cp0_rtu_int_level; +wire [1 :0] cp0_rtu_int_mode; +wire cp0_rtu_mie; +wire cp0_rtu_mnxti_vld; +wire [7 :0] cp0_rtu_mpil; +wire [1 :0] cp0_rtu_pm_bypass; +wire cp0_rtu_tail_int_hv; +wire [11:0] cp0_rtu_tail_int_id; +wire [31:0] cp0_rtu_wb_data; +wire [5 :0] cp0_rtu_wb_preg; +wire cp0_rtu_wb_vld; +wire cp0_rtu_wfe_en; +wire cp0_xx_async_expt_en; +wire cp0_yy_clk_en; +wire [11:0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpurst_b; +wire dtu_rtu_async_halt_req; +wire [31:0] dtu_rtu_dpc; +wire dtu_rtu_ebreak_action; +wire dtu_rtu_int_mask; +wire [31:0] dtu_rtu_pending_tval; +wire dtu_rtu_resume_req; +wire dtu_rtu_step_en; +wire dtu_rtu_sync_flush; +wire dtu_rtu_sync_halt_req; +wire forever_cpuclk; +wire [31:0] fpu_rtu_fgpr_wb_data; +wire [4 :0] fpu_rtu_fgpr_wb_reg; +wire fpu_rtu_fgpr_wb_vld; +wire [31:0] fpu_rtu_wb_data; +wire [5 :0] fpu_rtu_wb_preg; +wire fpu_rtu_wb_vld; +wire fpu_xx_no_op; +wire idu_yy_xx_tail_ack; +wire ifu_rtu_lockup_ack; +wire ifu_rtu_reset_halt_req; +wire ifu_rtu_warm_up; +wire int_cbus_ex1_int_vld; +wire int_cbus_ex1_nmi_req; +wire int_cbus_int_hv; +wire int_lockup_nmi_req; +wire int_retire_pending_int_hv; +wire int_top_nmi_req; +wire [11:0] int_xx_int_id; +wire [7 :0] int_xx_int_lv; +wire iu_rtu_ex1_bju_branch_inst; +wire iu_rtu_ex1_bju_cmplt; +wire iu_rtu_ex1_bju_cmplt_dp; +wire [30:0] iu_rtu_ex1_bju_cur_pc; +wire iu_rtu_ex1_bju_inst_len; +wire iu_rtu_ex1_bju_inst_vld; +wire iu_rtu_ex1_bju_split_inst; +wire iu_rtu_ex1_cmplt; +wire iu_rtu_ex1_cmplt_dp; +wire iu_rtu_ex1_inst_len; +wire iu_rtu_ex1_inst_vld; +wire iu_rtu_ex1_ipop_int_mask; +wire iu_rtu_ex1_ipush_mie_en; +wire iu_rtu_ex1_ipush_spec_fail; +wire [30:0] iu_rtu_ex1_next_pc; +wire iu_rtu_ex1_split_inst; +wire iu_rtu_ex1_tail_int_vld; +wire iu_rtu_ex2_bju_flush; +wire [30:0] iu_rtu_ex2_bju_next_pc; +wire iu_rtu_ex2_bju_next_pc_vld; +wire [31:0] iu_rtu_wb0_data; +wire [5 :0] iu_rtu_wb0_preg; +wire iu_rtu_wb0_vld; +wire iu_xx_no_op; +wire lockup_clk; +wire lockup_clk_en; +wire lockup_retire_dbg_vld; +wire lockup_retire_nmi_vld; +wire [2 :0] lockup_top_cur_st; +wire lsu_rtu_async_expt_vld; +wire lsu_rtu_async_ld_inst; +wire [31:0] lsu_rtu_async_tval; +wire lsu_rtu_ex1_cmplt; +wire lsu_rtu_ex1_cmplt_dp; +wire [14:0] lsu_rtu_ex1_halt_info; +wire lsu_rtu_ex1_inst_len; +wire lsu_rtu_ex1_inst_vld; +wire lsu_rtu_ex1_ipop_int_mask; +wire lsu_rtu_ex1_ipush_spec_inst; +wire lsu_rtu_ex1_split_inst; +wire lsu_rtu_ex2_bus_err; +wire lsu_rtu_ex2_expt_inst; +wire [3 :0] lsu_rtu_ex2_expt_vec; +wire lsu_rtu_ex2_stall; +wire [31:0] lsu_rtu_ex2_tval; +wire [31:0] lsu_rtu_fgpr_wb_data; +wire [4 :0] lsu_rtu_fgpr_wb_reg; +wire lsu_rtu_fgpr_wb_vld; +wire lsu_rtu_sync_ack; +wire [31:0] lsu_rtu_wb_data; +wire [5 :0] lsu_rtu_wb_preg; +wire lsu_rtu_wb_vld; +wire lsu_xx_no_op; +wire pad_yy_icg_scan_en; +wire rbus_top_fpu_wb_stall; +wire rbus_top_iu_wb_stall; +wire retire_cbus_debug_may_spec_fail; +wire retire_cbus_ex2_stall; +wire retire_cbus_flush_stall; +wire retire_int_nmi_ack; +wire retire_lockup_dbg_req; +wire retire_lockup_dbgon; +wire retire_lockup_expt_vld; +wire retire_lockup_nmi_exit; +wire [31:0] retire_lockup_retire_pc; +wire retire_lockup_retire_vld; +wire retire_top_dbg_mode_on; +wire retire_top_dbg_stall; +wire [2 :0] retire_top_flush_cur_state; +wire retire_top_lsu_ex2_stall; +wire retire_xx_ex2_expt_raw; +wire rtu_cp0_bus_error; +wire [31:0] rtu_cp0_epc; +wire rtu_cp0_exit_debug; +wire rtu_cp0_fp_dirty_vld; +wire [7 :0] rtu_cp0_int_level; +wire rtu_cp0_lockup_clr; +wire rtu_cp0_lockup_vld; +wire rtu_cp0_mie_en; +wire rtu_cp0_mie_gateclk_en; +wire rtu_cp0_mnxti_pending_vld; +wire rtu_cp0_nmi_vld; +wire rtu_cp0_pending_int_hv; +wire [11:0] rtu_cp0_pending_int_id; +wire [7 :0] rtu_cp0_pending_int_level; +wire [31:0] rtu_cp0_tval; +wire rtu_cp0_wk_int; +wire [13:0] rtu_dtu_debug_info; +wire [31:0] rtu_dtu_dpc; +wire rtu_dtu_halt_ack; +wire rtu_dtu_nmi_pending; +wire rtu_dtu_pending_ack; +wire rtu_dtu_retire_chgflw; +wire rtu_dtu_retire_debug_expt_vld; +wire [14:0] rtu_dtu_retire_halt_info; +wire rtu_dtu_retire_mret; +wire [31:0] rtu_dtu_retire_next_pc; +wire rtu_dtu_retire_vld; +wire [31:0] rtu_dtu_tval; +wire rtu_fpu_fgpr_wb_grant; +wire rtu_fpu_wb_grant; +wire rtu_hpcp_retire_inst_vld; +wire rtu_idu_ex1_int_dis_stall_gateclk_req; +wire rtu_idu_ex1_int_dis_stall_req; +wire rtu_idu_ex2_ipush_spec_inst_expt_vld; +wire rtu_idu_ex2_ipush_spec_inst_halt_info_vld; +wire [31:0] rtu_idu_fgpr_wb_data; +wire rtu_idu_fgpr_wb_flsu_vld; +wire [4 :0] rtu_idu_fgpr_wb_reg; +wire rtu_idu_fgpr_wb_vld; +wire rtu_idu_flush_fe; +wire rtu_idu_flush_stall; +wire rtu_idu_id_tail_int_vld; +wire rtu_idu_inst_retire; +wire rtu_idu_late_flush; +wire [31:0] rtu_idu_wb0_data; +wire rtu_idu_wb0_fpu_vld; +wire [5 :0] rtu_idu_wb0_preg; +wire rtu_idu_wb0_vld; +wire [31:0] rtu_idu_wb1_data; +wire rtu_idu_wb1_lsu_vld; +wire [5 :0] rtu_idu_wb1_preg; +wire rtu_idu_wb1_vld; +wire [31:0] rtu_idu_wb2_data; +wire [5 :0] rtu_idu_wb2_preg; +wire rtu_idu_wb2_vld; +wire [31:0] rtu_ifu_chgflw_pc; +wire rtu_ifu_chgflw_vld; +wire rtu_ifu_dbg_mask; +wire rtu_ifu_flush_fe; +wire rtu_ifu_lockup_expt_vld; +wire rtu_ifu_lockup_mask; +wire rtu_ifu_lockup_req; +wire [31:0] rtu_iu_bju_ex2_cur_pc; +wire rtu_iu_ex1_cmplt_dp_vld; +wire rtu_iu_ex1_cmplt_inst_len; +wire rtu_iu_ex1_cmplt_split_inst; +wire rtu_iu_ex1_cmplt_vld; +wire rtu_iu_pending_spec_expt_vld; +wire rtu_iu_pending_spec_halt_info_vld; +wire rtu_lsu_async_expt_ack; +wire rtu_lsu_expt_ack; +wire rtu_lsu_expt_exit; +wire [31:0] rtu_lsu_fgpr_wb_data; +wire [4 :0] rtu_lsu_fgpr_wb_reg; +wire rtu_lsu_fgpr_wb_vld; +wire rtu_lsu_inst_retire; +wire rtu_lsu_sync_req; +wire [31:0] rtu_lsu_wb1_data; +wire rtu_lsu_wb1_lsu_vld; +wire [5 :0] rtu_lsu_wb1_preg; +wire rtu_pad_inst_retire; +wire rtu_pad_inst_split; +wire [31:0] rtu_pad_retire_pc; +wire [31:0] rtu_pad_wb0_data; +wire [5 :0] rtu_pad_wb0_preg; +wire rtu_pad_wb0_vld; +wire [31:0] rtu_pad_wb1_data; +wire [5 :0] rtu_pad_wb1_preg; +wire rtu_pad_wb1_vld; +wire [31:0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +wire [4 :0] rtu_pad_wb_freg; +wire [31:0] rtu_pad_wb_freg_data; +wire rtu_pad_wb_freg_vld; +wire rtu_sysio_halted; +wire rtu_sysio_lockup_on; +wire rtu_xx_ex1_stall; +wire rtu_xx_no_op; +wire rtu_yy_xx_async_flush; +wire rtu_yy_xx_dbgon; +wire rtu_yy_xx_expt_int; +wire [11:0] rtu_yy_xx_expt_vec; +wire rtu_yy_xx_expt_vld; +wire rtu_yy_xx_flush; +wire rtu_yy_xx_int_hv; +wire rtu_yy_xx_tail_int_vld; +wire sysio_rtu_nmi_int; +wire sysio_rtu_wk_event; + + +// &Instance("pa_rtu_retire"); @28 +pa_rtu_retire x_pa_rtu_retire ( + .cbus_retire_ex2_chgflw_vld (cbus_retire_ex2_chgflw_vld ), + .cbus_retire_ex2_cur_pc (cbus_retire_ex2_cur_pc ), + .cbus_retire_ex2_expt_inst (cbus_retire_ex2_expt_inst ), + .cbus_retire_ex2_flush (cbus_retire_ex2_flush ), + .cbus_retire_ex2_halt_info (cbus_retire_ex2_halt_info ), + .cbus_retire_ex2_inst_branch (cbus_retire_ex2_inst_branch ), + .cbus_retire_ex2_inst_dret (cbus_retire_ex2_inst_dret ), + .cbus_retire_ex2_inst_ebreak (cbus_retire_ex2_inst_ebreak ), + .cbus_retire_ex2_inst_int (cbus_retire_ex2_inst_int ), + .cbus_retire_ex2_inst_mret (cbus_retire_ex2_inst_mret ), + .cbus_retire_ex2_inst_nmi (cbus_retire_ex2_inst_nmi ), + .cbus_retire_ex2_inst_tail_int (cbus_retire_ex2_inst_tail_int ), + .cbus_retire_ex2_inst_vld (cbus_retire_ex2_inst_vld ), + .cbus_retire_ex2_int_hv (cbus_retire_ex2_int_hv ), + .cbus_retire_ex2_int_lv (cbus_retire_ex2_int_lv ), + .cbus_retire_ex2_ipop_int_mask (cbus_retire_ex2_ipop_int_mask ), + .cbus_retire_ex2_may_debug (cbus_retire_ex2_may_debug ), + .cbus_retire_ex2_next_pc (cbus_retire_ex2_next_pc ), + .cbus_retire_ex2_split_inst (cbus_retire_ex2_split_inst ), + .cbus_retire_ex2_tail_spec_inst (cbus_retire_ex2_tail_spec_inst ), + .cbus_retire_ex2_trap_vec (cbus_retire_ex2_trap_vec ), + .cbus_retire_ex2_tval (cbus_retire_ex2_tval ), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_xx_async_expt_en (cp0_xx_async_expt_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .dtu_rtu_async_halt_req (dtu_rtu_async_halt_req ), + .dtu_rtu_dpc (dtu_rtu_dpc ), + .dtu_rtu_ebreak_action (dtu_rtu_ebreak_action ), + .dtu_rtu_pending_tval (dtu_rtu_pending_tval ), + .dtu_rtu_resume_req (dtu_rtu_resume_req ), + .dtu_rtu_step_en (dtu_rtu_step_en ), + .dtu_rtu_sync_flush (dtu_rtu_sync_flush ), + .dtu_rtu_sync_halt_req (dtu_rtu_sync_halt_req ), + .forever_cpuclk (forever_cpuclk ), + .fpu_xx_no_op (fpu_xx_no_op ), + .ifu_rtu_reset_halt_req (ifu_rtu_reset_halt_req ), + .int_retire_pending_int_hv (int_retire_pending_int_hv ), + .iu_xx_no_op (iu_xx_no_op ), + .lockup_clk (lockup_clk ), + .lockup_clk_en (lockup_clk_en ), + .lockup_retire_dbg_vld (lockup_retire_dbg_vld ), + .lockup_retire_nmi_vld (lockup_retire_nmi_vld ), + .lsu_rtu_async_expt_vld (lsu_rtu_async_expt_vld ), + .lsu_rtu_async_ld_inst (lsu_rtu_async_ld_inst ), + .lsu_rtu_async_tval (lsu_rtu_async_tval ), + .lsu_rtu_ex2_bus_err (lsu_rtu_ex2_bus_err ), + .lsu_rtu_ex2_stall (lsu_rtu_ex2_stall ), + .lsu_rtu_ex2_tval (lsu_rtu_ex2_tval ), + .lsu_rtu_sync_ack (lsu_rtu_sync_ack ), + .lsu_xx_no_op (lsu_xx_no_op ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .retire_cbus_debug_may_spec_fail (retire_cbus_debug_may_spec_fail), + .retire_cbus_ex2_stall (retire_cbus_ex2_stall ), + .retire_cbus_flush_stall (retire_cbus_flush_stall ), + .retire_int_nmi_ack (retire_int_nmi_ack ), + .retire_lockup_dbg_req (retire_lockup_dbg_req ), + .retire_lockup_dbgon (retire_lockup_dbgon ), + .retire_lockup_expt_vld (retire_lockup_expt_vld ), + .retire_lockup_nmi_exit (retire_lockup_nmi_exit ), + .retire_lockup_retire_pc (retire_lockup_retire_pc ), + .retire_lockup_retire_vld (retire_lockup_retire_vld ), + .retire_top_dbg_mode_on (retire_top_dbg_mode_on ), + .retire_top_dbg_stall (retire_top_dbg_stall ), + .retire_top_flush_cur_state (retire_top_flush_cur_state ), + .retire_top_lsu_ex2_stall (retire_top_lsu_ex2_stall ), + .retire_xx_ex2_expt_raw (retire_xx_ex2_expt_raw ), + .rtu_cp0_bus_error (rtu_cp0_bus_error ), + .rtu_cp0_epc (rtu_cp0_epc ), + .rtu_cp0_exit_debug (rtu_cp0_exit_debug ), + .rtu_cp0_int_level (rtu_cp0_int_level ), + .rtu_cp0_nmi_vld (rtu_cp0_nmi_vld ), + .rtu_cp0_tval (rtu_cp0_tval ), + .rtu_dtu_dpc (rtu_dtu_dpc ), + .rtu_dtu_halt_ack (rtu_dtu_halt_ack ), + .rtu_dtu_pending_ack (rtu_dtu_pending_ack ), + .rtu_dtu_retire_chgflw (rtu_dtu_retire_chgflw ), + .rtu_dtu_retire_debug_expt_vld (rtu_dtu_retire_debug_expt_vld ), + .rtu_dtu_retire_halt_info (rtu_dtu_retire_halt_info ), + .rtu_dtu_retire_mret (rtu_dtu_retire_mret ), + .rtu_dtu_retire_next_pc (rtu_dtu_retire_next_pc ), + .rtu_dtu_retire_vld (rtu_dtu_retire_vld ), + .rtu_dtu_tval (rtu_dtu_tval ), + .rtu_hpcp_retire_inst_vld (rtu_hpcp_retire_inst_vld ), + .rtu_idu_flush_fe (rtu_idu_flush_fe ), + .rtu_idu_flush_stall (rtu_idu_flush_stall ), + .rtu_idu_inst_retire (rtu_idu_inst_retire ), + .rtu_idu_late_flush (rtu_idu_late_flush ), + .rtu_ifu_chgflw_pc (rtu_ifu_chgflw_pc ), + .rtu_ifu_chgflw_vld (rtu_ifu_chgflw_vld ), + .rtu_ifu_dbg_mask (rtu_ifu_dbg_mask ), + .rtu_ifu_flush_fe (rtu_ifu_flush_fe ), + .rtu_lsu_async_expt_ack (rtu_lsu_async_expt_ack ), + .rtu_lsu_expt_ack (rtu_lsu_expt_ack ), + .rtu_lsu_expt_exit (rtu_lsu_expt_exit ), + .rtu_lsu_inst_retire (rtu_lsu_inst_retire ), + .rtu_lsu_sync_req (rtu_lsu_sync_req ), + .rtu_pad_inst_retire (rtu_pad_inst_retire ), + .rtu_pad_inst_split (rtu_pad_inst_split ), + .rtu_pad_retire_pc (rtu_pad_retire_pc ), + .rtu_sysio_halted (rtu_sysio_halted ), + .rtu_xx_no_op (rtu_xx_no_op ), + .rtu_yy_xx_async_flush (rtu_yy_xx_async_flush ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .rtu_yy_xx_tail_int_vld (rtu_yy_xx_tail_int_vld ) +); + +// &Force("output", "rtu_yy_xx_dbgon"); @29 +// &Force("output", "rtu_yy_xx_flush"); @30 +// &Force("output", "rtu_yy_xx_expt_int"); @31 +// &Force("output", "rtu_yy_xx_expt_vld"); @32 +// &Force("output", "rtu_yy_xx_expt_vec"); @33 +// &Force("output", "rtu_yy_xx_int_hv"); @34 + +// &Instance("pa_rtu_cbus"); @36 +pa_rtu_cbus x_pa_rtu_cbus ( + .cbus_int_ex1_split_inst (cbus_int_ex1_split_inst ), + .cbus_int_ipop_int_mask (cbus_int_ipop_int_mask ), + .cbus_int_ipush_mie_en (cbus_int_ipush_mie_en ), + .cbus_retire_ex2_chgflw_vld (cbus_retire_ex2_chgflw_vld ), + .cbus_retire_ex2_cur_pc (cbus_retire_ex2_cur_pc ), + .cbus_retire_ex2_expt_inst (cbus_retire_ex2_expt_inst ), + .cbus_retire_ex2_flush (cbus_retire_ex2_flush ), + .cbus_retire_ex2_halt_info (cbus_retire_ex2_halt_info ), + .cbus_retire_ex2_inst_branch (cbus_retire_ex2_inst_branch ), + .cbus_retire_ex2_inst_dret (cbus_retire_ex2_inst_dret ), + .cbus_retire_ex2_inst_ebreak (cbus_retire_ex2_inst_ebreak ), + .cbus_retire_ex2_inst_int (cbus_retire_ex2_inst_int ), + .cbus_retire_ex2_inst_mret (cbus_retire_ex2_inst_mret ), + .cbus_retire_ex2_inst_nmi (cbus_retire_ex2_inst_nmi ), + .cbus_retire_ex2_inst_tail_int (cbus_retire_ex2_inst_tail_int ), + .cbus_retire_ex2_inst_vld (cbus_retire_ex2_inst_vld ), + .cbus_retire_ex2_int_hv (cbus_retire_ex2_int_hv ), + .cbus_retire_ex2_int_lv (cbus_retire_ex2_int_lv ), + .cbus_retire_ex2_ipop_int_mask (cbus_retire_ex2_ipop_int_mask ), + .cbus_retire_ex2_may_debug (cbus_retire_ex2_may_debug ), + .cbus_retire_ex2_next_pc (cbus_retire_ex2_next_pc ), + .cbus_retire_ex2_split_inst (cbus_retire_ex2_split_inst ), + .cbus_retire_ex2_tail_spec_inst (cbus_retire_ex2_tail_spec_inst ), + .cbus_retire_ex2_trap_vec (cbus_retire_ex2_trap_vec ), + .cbus_retire_ex2_tval (cbus_retire_ex2_tval ), + .cbus_top_ex2_inst_vld (cbus_top_ex2_inst_vld ), + .cbus_top_ex2_uncommit_stall (cbus_top_ex2_uncommit_stall ), + .cp0_rtu_ex1_chgflw_pc (cp0_rtu_ex1_chgflw_pc ), + .cp0_rtu_ex1_chgflw_vld (cp0_rtu_ex1_chgflw_vld ), + .cp0_rtu_ex1_cmplt (cp0_rtu_ex1_cmplt ), + .cp0_rtu_ex1_cmplt_dp (cp0_rtu_ex1_cmplt_dp ), + .cp0_rtu_ex1_dret (cp0_rtu_ex1_dret ), + .cp0_rtu_ex1_ebreak (cp0_rtu_ex1_ebreak ), + .cp0_rtu_ex1_expt_inst (cp0_rtu_ex1_expt_inst ), + .cp0_rtu_ex1_expt_tval (cp0_rtu_ex1_expt_tval ), + .cp0_rtu_ex1_expt_vec (cp0_rtu_ex1_expt_vec ), + .cp0_rtu_ex1_flush (cp0_rtu_ex1_flush ), + .cp0_rtu_ex1_halt_info (cp0_rtu_ex1_halt_info ), + .cp0_rtu_ex1_inst_len (cp0_rtu_ex1_inst_len ), + .cp0_rtu_ex1_inst_vld (cp0_rtu_ex1_inst_vld ), + .cp0_rtu_ex1_ipush_spec_fail (cp0_rtu_ex1_ipush_spec_fail ), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_ex1_split_inst (cp0_rtu_ex1_split_inst ), + .cp0_rtu_ex1_tail_fail (cp0_rtu_ex1_tail_fail ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_rtu_warm_up (ifu_rtu_warm_up ), + .int_cbus_ex1_int_vld (int_cbus_ex1_int_vld ), + .int_cbus_ex1_nmi_req (int_cbus_ex1_nmi_req ), + .int_cbus_int_hv (int_cbus_int_hv ), + .int_xx_int_id (int_xx_int_id ), + .int_xx_int_lv (int_xx_int_lv ), + .iu_rtu_ex1_bju_branch_inst (iu_rtu_ex1_bju_branch_inst ), + .iu_rtu_ex1_bju_cmplt (iu_rtu_ex1_bju_cmplt ), + .iu_rtu_ex1_bju_cmplt_dp (iu_rtu_ex1_bju_cmplt_dp ), + .iu_rtu_ex1_bju_cur_pc (iu_rtu_ex1_bju_cur_pc ), + .iu_rtu_ex1_bju_inst_len (iu_rtu_ex1_bju_inst_len ), + .iu_rtu_ex1_bju_inst_vld (iu_rtu_ex1_bju_inst_vld ), + .iu_rtu_ex1_bju_split_inst (iu_rtu_ex1_bju_split_inst ), + .iu_rtu_ex1_cmplt (iu_rtu_ex1_cmplt ), + .iu_rtu_ex1_cmplt_dp (iu_rtu_ex1_cmplt_dp ), + .iu_rtu_ex1_inst_len (iu_rtu_ex1_inst_len ), + .iu_rtu_ex1_inst_vld (iu_rtu_ex1_inst_vld ), + .iu_rtu_ex1_ipop_int_mask (iu_rtu_ex1_ipop_int_mask ), + .iu_rtu_ex1_ipush_mie_en (iu_rtu_ex1_ipush_mie_en ), + .iu_rtu_ex1_ipush_spec_fail (iu_rtu_ex1_ipush_spec_fail ), + .iu_rtu_ex1_next_pc (iu_rtu_ex1_next_pc ), + .iu_rtu_ex1_split_inst (iu_rtu_ex1_split_inst ), + .iu_rtu_ex1_tail_int_vld (iu_rtu_ex1_tail_int_vld ), + .iu_rtu_ex2_bju_flush (iu_rtu_ex2_bju_flush ), + .iu_rtu_ex2_bju_next_pc (iu_rtu_ex2_bju_next_pc ), + .iu_rtu_ex2_bju_next_pc_vld (iu_rtu_ex2_bju_next_pc_vld ), + .lsu_rtu_async_expt_vld (lsu_rtu_async_expt_vld ), + .lsu_rtu_ex1_cmplt (lsu_rtu_ex1_cmplt ), + .lsu_rtu_ex1_cmplt_dp (lsu_rtu_ex1_cmplt_dp ), + .lsu_rtu_ex1_halt_info (lsu_rtu_ex1_halt_info ), + .lsu_rtu_ex1_inst_len (lsu_rtu_ex1_inst_len ), + .lsu_rtu_ex1_inst_vld (lsu_rtu_ex1_inst_vld ), + .lsu_rtu_ex1_ipop_int_mask (lsu_rtu_ex1_ipop_int_mask ), + .lsu_rtu_ex1_ipush_spec_inst (lsu_rtu_ex1_ipush_spec_inst ), + .lsu_rtu_ex1_split_inst (lsu_rtu_ex1_split_inst ), + .lsu_rtu_ex2_expt_inst (lsu_rtu_ex2_expt_inst ), + .lsu_rtu_ex2_expt_vec (lsu_rtu_ex2_expt_vec ), + .lsu_rtu_ex2_tval (lsu_rtu_ex2_tval ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .retire_cbus_debug_may_spec_fail (retire_cbus_debug_may_spec_fail ), + .retire_cbus_ex2_stall (retire_cbus_ex2_stall ), + .retire_cbus_flush_stall (retire_cbus_flush_stall ), + .rtu_cp0_mie_en (rtu_cp0_mie_en ), + .rtu_cp0_mie_gateclk_en (rtu_cp0_mie_gateclk_en ), + .rtu_idu_ex1_int_dis_stall_gateclk_req (rtu_idu_ex1_int_dis_stall_gateclk_req ), + .rtu_idu_ex1_int_dis_stall_req (rtu_idu_ex1_int_dis_stall_req ), + .rtu_idu_ex2_ipush_spec_inst_expt_vld (rtu_idu_ex2_ipush_spec_inst_expt_vld ), + .rtu_idu_ex2_ipush_spec_inst_halt_info_vld (rtu_idu_ex2_ipush_spec_inst_halt_info_vld), + .rtu_iu_bju_ex2_cur_pc (rtu_iu_bju_ex2_cur_pc ), + .rtu_iu_ex1_cmplt_dp_vld (rtu_iu_ex1_cmplt_dp_vld ), + .rtu_iu_ex1_cmplt_inst_len (rtu_iu_ex1_cmplt_inst_len ), + .rtu_iu_ex1_cmplt_split_inst (rtu_iu_ex1_cmplt_split_inst ), + .rtu_iu_ex1_cmplt_vld (rtu_iu_ex1_cmplt_vld ), + .rtu_iu_pending_spec_expt_vld (rtu_iu_pending_spec_expt_vld ), + .rtu_iu_pending_spec_halt_info_vld (rtu_iu_pending_spec_halt_info_vld ), + .rtu_xx_ex1_stall (rtu_xx_ex1_stall ), + .rtu_yy_xx_flush (rtu_yy_xx_flush ) +); + + +// &Instance("pa_rtu_rbus"); @38 +pa_rtu_rbus x_pa_rtu_rbus ( + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_wb_data (cp0_rtu_wb_data ), + .cp0_rtu_wb_preg (cp0_rtu_wb_preg ), + .cp0_rtu_wb_vld (cp0_rtu_wb_vld ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .fpu_rtu_fgpr_wb_data (fpu_rtu_fgpr_wb_data ), + .fpu_rtu_fgpr_wb_reg (fpu_rtu_fgpr_wb_reg ), + .fpu_rtu_fgpr_wb_vld (fpu_rtu_fgpr_wb_vld ), + .fpu_rtu_wb_data (fpu_rtu_wb_data ), + .fpu_rtu_wb_preg (fpu_rtu_wb_preg ), + .fpu_rtu_wb_vld (fpu_rtu_wb_vld ), + .ifu_rtu_warm_up (ifu_rtu_warm_up ), + .iu_rtu_wb0_data (iu_rtu_wb0_data ), + .iu_rtu_wb0_preg (iu_rtu_wb0_preg ), + .iu_rtu_wb0_vld (iu_rtu_wb0_vld ), + .lsu_rtu_fgpr_wb_data (lsu_rtu_fgpr_wb_data ), + .lsu_rtu_fgpr_wb_reg (lsu_rtu_fgpr_wb_reg ), + .lsu_rtu_fgpr_wb_vld (lsu_rtu_fgpr_wb_vld ), + .lsu_rtu_wb_data (lsu_rtu_wb_data ), + .lsu_rtu_wb_preg (lsu_rtu_wb_preg ), + .lsu_rtu_wb_vld (lsu_rtu_wb_vld ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rbus_top_fpu_wb_stall (rbus_top_fpu_wb_stall ), + .rbus_top_iu_wb_stall (rbus_top_iu_wb_stall ), + .rtu_cp0_fp_dirty_vld (rtu_cp0_fp_dirty_vld ), + .rtu_fpu_fgpr_wb_grant (rtu_fpu_fgpr_wb_grant ), + .rtu_fpu_wb_grant (rtu_fpu_wb_grant ), + .rtu_idu_fgpr_wb_data (rtu_idu_fgpr_wb_data ), + .rtu_idu_fgpr_wb_flsu_vld (rtu_idu_fgpr_wb_flsu_vld), + .rtu_idu_fgpr_wb_reg (rtu_idu_fgpr_wb_reg ), + .rtu_idu_fgpr_wb_vld (rtu_idu_fgpr_wb_vld ), + .rtu_idu_wb0_data (rtu_idu_wb0_data ), + .rtu_idu_wb0_fpu_vld (rtu_idu_wb0_fpu_vld ), + .rtu_idu_wb0_preg (rtu_idu_wb0_preg ), + .rtu_idu_wb0_vld (rtu_idu_wb0_vld ), + .rtu_idu_wb1_data (rtu_idu_wb1_data ), + .rtu_idu_wb1_lsu_vld (rtu_idu_wb1_lsu_vld ), + .rtu_idu_wb1_preg (rtu_idu_wb1_preg ), + .rtu_idu_wb1_vld (rtu_idu_wb1_vld ), + .rtu_idu_wb2_data (rtu_idu_wb2_data ), + .rtu_idu_wb2_preg (rtu_idu_wb2_preg ), + .rtu_idu_wb2_vld (rtu_idu_wb2_vld ), + .rtu_lsu_fgpr_wb_data (rtu_lsu_fgpr_wb_data ), + .rtu_lsu_fgpr_wb_reg (rtu_lsu_fgpr_wb_reg ), + .rtu_lsu_fgpr_wb_vld (rtu_lsu_fgpr_wb_vld ), + .rtu_lsu_wb1_data (rtu_lsu_wb1_data ), + .rtu_lsu_wb1_lsu_vld (rtu_lsu_wb1_lsu_vld ), + .rtu_lsu_wb1_preg (rtu_lsu_wb1_preg ), + .rtu_pad_wb0_data (rtu_pad_wb0_data ), + .rtu_pad_wb0_preg (rtu_pad_wb0_preg ), + .rtu_pad_wb0_vld (rtu_pad_wb0_vld ), + .rtu_pad_wb1_data (rtu_pad_wb1_data ), + .rtu_pad_wb1_preg (rtu_pad_wb1_preg ), + .rtu_pad_wb1_vld (rtu_pad_wb1_vld ), + .rtu_pad_wb2_data (rtu_pad_wb2_data ), + .rtu_pad_wb2_preg (rtu_pad_wb2_preg ), + .rtu_pad_wb2_vld (rtu_pad_wb2_vld ), + .rtu_pad_wb_freg (rtu_pad_wb_freg ), + .rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), + .rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ) +); + + +// &Instance("pa_rtu_int"); @40 +pa_rtu_int x_pa_rtu_int ( + .cbus_int_ex1_split_inst (cbus_int_ex1_split_inst ), + .cbus_int_ipop_int_mask (cbus_int_ipop_int_mask ), + .cbus_int_ipush_mie_en (cbus_int_ipush_mie_en ), + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .cp0_rtu_ex1_mret (cp0_rtu_ex1_mret ), + .cp0_rtu_icg_en (cp0_rtu_icg_en ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cp0_rtu_int_level (cp0_rtu_int_level ), + .cp0_rtu_int_mode (cp0_rtu_int_mode ), + .cp0_rtu_mie (cp0_rtu_mie ), + .cp0_rtu_mnxti_vld (cp0_rtu_mnxti_vld ), + .cp0_rtu_mpil (cp0_rtu_mpil ), + .cp0_rtu_pm_bypass (cp0_rtu_pm_bypass ), + .cp0_rtu_tail_int_hv (cp0_rtu_tail_int_hv ), + .cp0_rtu_tail_int_id (cp0_rtu_tail_int_id ), + .cp0_rtu_wfe_en (cp0_rtu_wfe_en ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpurst_b (cpurst_b ), + .dtu_rtu_int_mask (dtu_rtu_int_mask ), + .forever_cpuclk (forever_cpuclk ), + .idu_yy_xx_tail_ack (idu_yy_xx_tail_ack ), + .int_cbus_ex1_int_vld (int_cbus_ex1_int_vld ), + .int_cbus_ex1_nmi_req (int_cbus_ex1_nmi_req ), + .int_cbus_int_hv (int_cbus_int_hv ), + .int_lockup_nmi_req (int_lockup_nmi_req ), + .int_retire_pending_int_hv (int_retire_pending_int_hv), + .int_top_nmi_req (int_top_nmi_req ), + .int_xx_int_id (int_xx_int_id ), + .int_xx_int_lv (int_xx_int_lv ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .retire_int_nmi_ack (retire_int_nmi_ack ), + .retire_xx_ex2_expt_raw (retire_xx_ex2_expt_raw ), + .rtu_cp0_mnxti_pending_vld (rtu_cp0_mnxti_pending_vld), + .rtu_cp0_pending_int_hv (rtu_cp0_pending_int_hv ), + .rtu_cp0_pending_int_id (rtu_cp0_pending_int_id ), + .rtu_cp0_pending_int_level (rtu_cp0_pending_int_level), + .rtu_cp0_wk_int (rtu_cp0_wk_int ), + .rtu_dtu_nmi_pending (rtu_dtu_nmi_pending ), + .rtu_idu_id_tail_int_vld (rtu_idu_id_tail_int_vld ), + .rtu_yy_xx_expt_int (rtu_yy_xx_expt_int ), + .rtu_yy_xx_expt_vec (rtu_yy_xx_expt_vec ), + .rtu_yy_xx_expt_vld (rtu_yy_xx_expt_vld ), + .rtu_yy_xx_int_hv (rtu_yy_xx_int_hv ), + .sysio_rtu_nmi_int (sysio_rtu_nmi_int ), + .sysio_rtu_wk_event (sysio_rtu_wk_event ) +); + + +// &Instance("pa_rtu_lockup"); @42 +pa_rtu_lockup x_pa_rtu_lockup ( + .cp0_rtu_in_expt (cp0_rtu_in_expt ), + .cp0_rtu_in_nmi (cp0_rtu_in_nmi ), + .cpurst_b (cpurst_b ), + .ifu_rtu_lockup_ack (ifu_rtu_lockup_ack ), + .int_lockup_nmi_req (int_lockup_nmi_req ), + .lockup_clk (lockup_clk ), + .lockup_clk_en (lockup_clk_en ), + .lockup_retire_dbg_vld (lockup_retire_dbg_vld ), + .lockup_retire_nmi_vld (lockup_retire_nmi_vld ), + .lockup_top_cur_st (lockup_top_cur_st ), + .retire_lockup_dbg_req (retire_lockup_dbg_req ), + .retire_lockup_dbgon (retire_lockup_dbgon ), + .retire_lockup_expt_vld (retire_lockup_expt_vld ), + .retire_lockup_nmi_exit (retire_lockup_nmi_exit ), + .retire_lockup_retire_pc (retire_lockup_retire_pc ), + .retire_lockup_retire_vld (retire_lockup_retire_vld), + .rtu_cp0_lockup_clr (rtu_cp0_lockup_clr ), + .rtu_cp0_lockup_vld (rtu_cp0_lockup_vld ), + .rtu_ifu_lockup_expt_vld (rtu_ifu_lockup_expt_vld ), + .rtu_ifu_lockup_mask (rtu_ifu_lockup_mask ), + .rtu_ifu_lockup_req (rtu_ifu_lockup_req ), + .rtu_sysio_lockup_on (rtu_sysio_lockup_on ) +); + + +assign rtu_dtu_debug_info[13:0] = { + int_top_nmi_req, + lockup_top_cur_st[2:0], + rbus_top_fpu_wb_stall, + rbus_top_iu_wb_stall, + cbus_top_ex2_uncommit_stall, + cbus_top_ex2_inst_vld, + retire_top_flush_cur_state[2:0], + retire_top_dbg_stall, + retire_top_dbg_mode_on, + retire_top_lsu_ex2_stall + }; + + +// &ModuleEnd; @58 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_access.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_access.v new file mode 100644 index 0000000000000000000000000000000000000000..f99d9f19c65e3004f46e697671fa51aabc71edc8 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_access.v @@ -0,0 +1,262 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module pa_sysmap_access( + sysmap_base_addr0_value, + sysmap_base_addr1_value, + sysmap_base_addr2_value, + sysmap_base_addr3_value, + sysmap_base_addr4_value, + sysmap_base_addr5_value, + sysmap_base_addr6_value, + sysmap_base_addr7_value, + sysmap_flg0_value, + sysmap_flg1_value, + sysmap_flg2_value, + sysmap_flg3_value, + sysmap_flg4_value, + sysmap_flg5_value, + sysmap_flg6_value, + sysmap_flg7_value, + sysmap_flg_y, + sysmap_pa_y +); + +// &Ports; @25 +input [19:0] sysmap_base_addr0_value; +input [19:0] sysmap_base_addr1_value; +input [19:0] sysmap_base_addr2_value; +input [19:0] sysmap_base_addr3_value; +input [19:0] sysmap_base_addr4_value; +input [19:0] sysmap_base_addr5_value; +input [19:0] sysmap_base_addr6_value; +input [19:0] sysmap_base_addr7_value; +input [4 :0] sysmap_flg0_value; +input [4 :0] sysmap_flg1_value; +input [4 :0] sysmap_flg2_value; +input [4 :0] sysmap_flg3_value; +input [4 :0] sysmap_flg4_value; +input [4 :0] sysmap_flg5_value; +input [4 :0] sysmap_flg6_value; +input [4 :0] sysmap_flg7_value; +input [19:0] sysmap_pa_y; +output [4 :0] sysmap_flg_y; + +// &Regs; @26 +reg [4 :0] sysmap_flg_y; + +// &Wires; @27 +wire addr_ge_bottom0; +wire addr_ge_bottom1; +wire addr_ge_bottom2; +wire addr_ge_bottom3; +wire addr_ge_bottom4; +wire addr_ge_bottom5; +wire addr_ge_bottom6; +wire addr_ge_bottom7; +wire addr_ge_upaddr0; +wire addr_ge_upaddr1; +wire addr_ge_upaddr2; +wire addr_ge_upaddr3; +wire addr_ge_upaddr4; +wire addr_ge_upaddr5; +wire addr_ge_upaddr6; +wire addr_ge_upaddr7; +wire [19:0] sysmap_base_addr0_value; +wire [19:0] sysmap_base_addr1_value; +wire [19:0] sysmap_base_addr2_value; +wire [19:0] sysmap_base_addr3_value; +wire [19:0] sysmap_base_addr4_value; +wire [19:0] sysmap_base_addr5_value; +wire [19:0] sysmap_base_addr6_value; +wire [19:0] sysmap_base_addr7_value; +wire sysmap_comp_hit0; +wire sysmap_comp_hit1; +wire sysmap_comp_hit2; +wire sysmap_comp_hit3; +wire sysmap_comp_hit4; +wire sysmap_comp_hit5; +wire sysmap_comp_hit6; +wire sysmap_comp_hit7; +wire [4 :0] sysmap_flg0_value; +wire [4 :0] sysmap_flg1_value; +wire [4 :0] sysmap_flg2_value; +wire [4 :0] sysmap_flg3_value; +wire [4 :0] sysmap_flg4_value; +wire [4 :0] sysmap_flg5_value; +wire [4 :0] sysmap_flg6_value; +wire [4 :0] sysmap_flg7_value; +wire [7 :0] sysmap_hit; +wire sysmap_hit0; +wire sysmap_hit1; +wire sysmap_hit2; +wire sysmap_hit3; +wire sysmap_hit4; +wire sysmap_hit5; +wire sysmap_hit6; +wire sysmap_hit7; +wire [19:0] sysmap_pa_y; + + +parameter ADDR_WIDTH = 32-12; +parameter FLG_WIDTH = 5; + +// compare hit +// &ConnRule(s/_x/0/); @33 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_0"); @34 +pa_sysmap_hit x_pa_sysmap_hit_0 ( + .addr_ge_bottom_x (addr_ge_bottom0 ), + .addr_ge_upaddr_x (addr_ge_upaddr0 ), + .sysmap_comp_hit_x (sysmap_comp_hit0 ), + .sysmap_hit_x (sysmap_hit0 ) +); + + +// &ConnRule(s/_x/1/); @36 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_1"); @37 +pa_sysmap_hit x_pa_sysmap_hit_1 ( + .addr_ge_bottom_x (addr_ge_bottom1 ), + .addr_ge_upaddr_x (addr_ge_upaddr1 ), + .sysmap_comp_hit_x (sysmap_comp_hit1 ), + .sysmap_hit_x (sysmap_hit1 ) +); + + +// &ConnRule(s/_x/2/); @39 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_2"); @40 +pa_sysmap_hit x_pa_sysmap_hit_2 ( + .addr_ge_bottom_x (addr_ge_bottom2 ), + .addr_ge_upaddr_x (addr_ge_upaddr2 ), + .sysmap_comp_hit_x (sysmap_comp_hit2 ), + .sysmap_hit_x (sysmap_hit2 ) +); + + +// &ConnRule(s/_x/3/); @42 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_3"); @43 +pa_sysmap_hit x_pa_sysmap_hit_3 ( + .addr_ge_bottom_x (addr_ge_bottom3 ), + .addr_ge_upaddr_x (addr_ge_upaddr3 ), + .sysmap_comp_hit_x (sysmap_comp_hit3 ), + .sysmap_hit_x (sysmap_hit3 ) +); + + +// &ConnRule(s/_x/4/); @45 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_4"); @46 +pa_sysmap_hit x_pa_sysmap_hit_4 ( + .addr_ge_bottom_x (addr_ge_bottom4 ), + .addr_ge_upaddr_x (addr_ge_upaddr4 ), + .sysmap_comp_hit_x (sysmap_comp_hit4 ), + .sysmap_hit_x (sysmap_hit4 ) +); + + +// &ConnRule(s/_x/5/); @48 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_5"); @49 +pa_sysmap_hit x_pa_sysmap_hit_5 ( + .addr_ge_bottom_x (addr_ge_bottom5 ), + .addr_ge_upaddr_x (addr_ge_upaddr5 ), + .sysmap_comp_hit_x (sysmap_comp_hit5 ), + .sysmap_hit_x (sysmap_hit5 ) +); + + +// &ConnRule(s/_x/6/); @51 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_6"); @52 +pa_sysmap_hit x_pa_sysmap_hit_6 ( + .addr_ge_bottom_x (addr_ge_bottom6 ), + .addr_ge_upaddr_x (addr_ge_upaddr6 ), + .sysmap_comp_hit_x (sysmap_comp_hit6 ), + .sysmap_hit_x (sysmap_hit6 ) +); + + +// &ConnRule(s/_x/7/); @54 +// &Instance("pa_sysmap_hit", "x_pa_sysmap_hit_7"); @55 +pa_sysmap_hit x_pa_sysmap_hit_7 ( + .addr_ge_bottom_x (addr_ge_bottom7 ), + .addr_ge_upaddr_x (addr_ge_upaddr7 ), + .sysmap_comp_hit_x (sysmap_comp_hit7 ), + .sysmap_hit_x (sysmap_hit7 ) +); + + +// &Force("nonport", "addr_ge_upaddr7"); @57 +assign {addr_ge_bottom7, addr_ge_bottom6, + addr_ge_bottom5, addr_ge_bottom4, + addr_ge_bottom3, addr_ge_bottom2, + addr_ge_bottom1, addr_ge_bottom0} = + {addr_ge_upaddr6, addr_ge_upaddr5, + addr_ge_upaddr4, addr_ge_upaddr3, + addr_ge_upaddr2, addr_ge_upaddr1, + addr_ge_upaddr0, 1'b1}; + + +assign sysmap_hit[7:0] = {sysmap_hit7, sysmap_hit6, + sysmap_hit5, sysmap_hit4, + sysmap_hit3, sysmap_hit2, + sysmap_hit1, sysmap_hit0}; + +// &CombBeg; @73 +always @( sysmap_flg2_value[4:0] + or sysmap_flg1_value[4:0] + or sysmap_flg6_value[4:0] + or sysmap_hit[7:0] + or sysmap_flg7_value[4:0] + or sysmap_flg5_value[4:0] + or sysmap_flg4_value[4:0] + or sysmap_flg3_value[4:0] + or sysmap_flg0_value[4:0]) +begin + case(sysmap_hit[7:0]) + 8'b00000001 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg0_value[FLG_WIDTH-1:0]; + 8'b00000010 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg1_value[FLG_WIDTH-1:0]; + 8'b00000100 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg2_value[FLG_WIDTH-1:0]; + 8'b00001000 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg3_value[FLG_WIDTH-1:0]; + 8'b00010000 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg4_value[FLG_WIDTH-1:0]; + 8'b00100000 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg5_value[FLG_WIDTH-1:0]; + 8'b01000000 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg6_value[FLG_WIDTH-1:0]; + 8'b10000000 : sysmap_flg_y[FLG_WIDTH-1:0] = sysmap_flg7_value[FLG_WIDTH-1:0]; + //default : sysmap_flg_y[FLG_WIDTH-1:0] = 5'b01111; + default : sysmap_flg_y[FLG_WIDTH-1:0] = 5'b10011; +endcase +// &CombEnd; @86 +end + +// sysmap addr adder +assign sysmap_comp_hit0 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr0_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit1 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr1_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit2 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr2_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit3 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr3_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit4 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr4_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit5 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr5_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit6 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr6_value[ADDR_WIDTH-1:0]; +assign sysmap_comp_hit7 = sysmap_pa_y[ADDR_WIDTH-1:0] + < sysmap_base_addr7_value[ADDR_WIDTH-1:0]; + + +// &ModuleEnd; @107 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_busif.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_busif.v new file mode 100644 index 0000000000000000000000000000000000000000..1a24efa909d6c0b95a4927a725e676546fd642df --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_busif.v @@ -0,0 +1,455 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_sysmap_busif( + cp0_pmp_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ifu_sysmap_rst_sample, + pad_cpu_sysmap_addr0, + pad_cpu_sysmap_addr0_attr, + pad_cpu_sysmap_addr1, + pad_cpu_sysmap_addr1_attr, + pad_cpu_sysmap_addr2, + pad_cpu_sysmap_addr2_attr, + pad_cpu_sysmap_addr3, + pad_cpu_sysmap_addr3_attr, + pad_cpu_sysmap_addr4, + pad_cpu_sysmap_addr4_attr, + pad_cpu_sysmap_addr5, + pad_cpu_sysmap_addr5_attr, + pad_cpu_sysmap_addr6, + pad_cpu_sysmap_addr6_attr, + pad_cpu_sysmap_addr7, + pad_cpu_sysmap_addr7_attr, + pad_yy_icg_scan_en, + sysmap_base_addr0_value, + sysmap_base_addr1_value, + sysmap_base_addr2_value, + sysmap_base_addr3_value, + sysmap_base_addr4_value, + sysmap_base_addr5_value, + sysmap_base_addr6_value, + sysmap_base_addr7_value, + sysmap_flg0_value, + sysmap_flg1_value, + sysmap_flg2_value, + sysmap_flg3_value, + sysmap_flg4_value, + sysmap_flg5_value, + sysmap_flg6_value, + sysmap_flg7_value, + sysmap_tcipif_cmplt, + sysmap_tcipif_rdata, + tcipif_sysmap_addr, + tcipif_sysmap_sel, + tcipif_sysmap_wdata, + tcipif_sysmap_write +); + + +// &Ports; @25 +input cp0_pmp_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input ifu_sysmap_rst_sample; +input [19:0] pad_cpu_sysmap_addr0; +input [2 :0] pad_cpu_sysmap_addr0_attr; +input [19:0] pad_cpu_sysmap_addr1; +input [2 :0] pad_cpu_sysmap_addr1_attr; +input [19:0] pad_cpu_sysmap_addr2; +input [2 :0] pad_cpu_sysmap_addr2_attr; +input [19:0] pad_cpu_sysmap_addr3; +input [2 :0] pad_cpu_sysmap_addr3_attr; +input [19:0] pad_cpu_sysmap_addr4; +input [2 :0] pad_cpu_sysmap_addr4_attr; +input [19:0] pad_cpu_sysmap_addr5; +input [2 :0] pad_cpu_sysmap_addr5_attr; +input [19:0] pad_cpu_sysmap_addr6; +input [2 :0] pad_cpu_sysmap_addr6_attr; +input [19:0] pad_cpu_sysmap_addr7; +input [2 :0] pad_cpu_sysmap_addr7_attr; +input pad_yy_icg_scan_en; +input [15:0] tcipif_sysmap_addr; +input tcipif_sysmap_sel; +input [31:0] tcipif_sysmap_wdata; +input tcipif_sysmap_write; +output [19:0] sysmap_base_addr0_value; +output [19:0] sysmap_base_addr1_value; +output [19:0] sysmap_base_addr2_value; +output [19:0] sysmap_base_addr3_value; +output [19:0] sysmap_base_addr4_value; +output [19:0] sysmap_base_addr5_value; +output [19:0] sysmap_base_addr6_value; +output [19:0] sysmap_base_addr7_value; +output [4 :0] sysmap_flg0_value; +output [4 :0] sysmap_flg1_value; +output [4 :0] sysmap_flg2_value; +output [4 :0] sysmap_flg3_value; +output [4 :0] sysmap_flg4_value; +output [4 :0] sysmap_flg5_value; +output [4 :0] sysmap_flg6_value; +output [4 :0] sysmap_flg7_value; +output sysmap_tcipif_cmplt; +output [31:0] sysmap_tcipif_rdata; + +// &Regs; @26 +reg [31:0] busif_rdata; + +// &Wires; @27 +wire [15:0] busif_addr; +wire busif_base_addr0_updt; +wire [31:0] busif_base_addr0_value; +wire busif_base_addr1_updt; +wire [31:0] busif_base_addr1_value; +wire busif_base_addr2_updt; +wire [31:0] busif_base_addr2_value; +wire busif_base_addr3_updt; +wire [31:0] busif_base_addr3_value; +wire busif_base_addr4_updt; +wire [31:0] busif_base_addr4_value; +wire busif_base_addr5_updt; +wire [31:0] busif_base_addr5_value; +wire busif_base_addr6_updt; +wire [31:0] busif_base_addr6_value; +wire busif_base_addr7_updt; +wire [31:0] busif_base_addr7_value; +wire busif_flg0_updt; +wire [31:0] busif_flg0_value; +wire busif_flg1_updt; +wire [31:0] busif_flg1_value; +wire busif_flg2_updt; +wire [31:0] busif_flg2_value; +wire busif_flg3_updt; +wire [31:0] busif_flg3_value; +wire busif_flg4_updt; +wire [31:0] busif_flg4_value; +wire busif_flg5_updt; +wire [31:0] busif_flg5_value; +wire busif_flg6_updt; +wire [31:0] busif_flg6_value; +wire busif_flg7_updt; +wire [31:0] busif_flg7_value; +wire busif_sel; +wire busif_updt; +wire [31:0] busif_wdata; +wire busif_write; +wire cp0_pmp_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire ifu_sysmap_rst_sample; +wire [19:0] pad_cpu_sysmap_addr0; +wire [2 :0] pad_cpu_sysmap_addr0_attr; +wire [19:0] pad_cpu_sysmap_addr1; +wire [2 :0] pad_cpu_sysmap_addr1_attr; +wire [19:0] pad_cpu_sysmap_addr2; +wire [2 :0] pad_cpu_sysmap_addr2_attr; +wire [19:0] pad_cpu_sysmap_addr3; +wire [2 :0] pad_cpu_sysmap_addr3_attr; +wire [19:0] pad_cpu_sysmap_addr4; +wire [2 :0] pad_cpu_sysmap_addr4_attr; +wire [19:0] pad_cpu_sysmap_addr5; +wire [2 :0] pad_cpu_sysmap_addr5_attr; +wire [19:0] pad_cpu_sysmap_addr6; +wire [2 :0] pad_cpu_sysmap_addr6_attr; +wire [19:0] pad_cpu_sysmap_addr7; +wire [2 :0] pad_cpu_sysmap_addr7_attr; +wire pad_yy_icg_scan_en; +wire [19:0] sysmap_base_addr0_value; +wire [19:0] sysmap_base_addr1_value; +wire [19:0] sysmap_base_addr2_value; +wire [19:0] sysmap_base_addr3_value; +wire [19:0] sysmap_base_addr4_value; +wire [19:0] sysmap_base_addr5_value; +wire [19:0] sysmap_base_addr6_value; +wire [19:0] sysmap_base_addr7_value; +wire sysmap_clk; +wire sysmap_clk_en; +wire [4 :0] sysmap_flg0_value; +wire [4 :0] sysmap_flg1_value; +wire [4 :0] sysmap_flg2_value; +wire [4 :0] sysmap_flg3_value; +wire [4 :0] sysmap_flg4_value; +wire [4 :0] sysmap_flg5_value; +wire [4 :0] sysmap_flg6_value; +wire [4 :0] sysmap_flg7_value; +wire sysmap_tcipif_cmplt; +wire [31:0] sysmap_tcipif_rdata; +wire [15:0] tcipif_sysmap_addr; +wire tcipif_sysmap_sel; +wire [31:0] tcipif_sysmap_wdata; +wire tcipif_sysmap_write; + + +parameter ADDR_WIDTH = 32-12; +parameter FLG_WIDTH = 5; + +parameter BASE_ADDR0_OFFSET = 12'h000; +parameter FLAG0_OFFSET = 12'h004; +parameter BASE_ADDR1_OFFSET = 12'h008; +parameter FLAG1_OFFSET = 12'h00c; +parameter BASE_ADDR2_OFFSET = 12'h010; +parameter FLAG2_OFFSET = 12'h014; +parameter BASE_ADDR3_OFFSET = 12'h018; +parameter FLAG3_OFFSET = 12'h01C; +parameter BASE_ADDR4_OFFSET = 12'h020; +parameter FLAG4_OFFSET = 12'h024; +parameter BASE_ADDR5_OFFSET = 12'h028; +parameter FLAG5_OFFSET = 12'h02C; +parameter BASE_ADDR6_OFFSET = 12'h030; +parameter FLAG6_OFFSET = 12'h034; +parameter BASE_ADDR7_OFFSET = 12'h038; +parameter FLAG7_OFFSET = 12'h03C; + +assign busif_sel = tcipif_sysmap_sel; +assign busif_addr[15:0] = tcipif_sysmap_addr[15:0]; +assign busif_write = tcipif_sysmap_write; +assign busif_wdata[31:0] = tcipif_sysmap_wdata[31:0]; + +assign busif_updt = busif_sel && busif_write; + +assign busif_base_addr0_updt = busif_updt && busif_addr[11:0] == BASE_ADDR0_OFFSET; +assign busif_base_addr1_updt = busif_updt && busif_addr[11:0] == BASE_ADDR1_OFFSET; +assign busif_base_addr2_updt = busif_updt && busif_addr[11:0] == BASE_ADDR2_OFFSET; +assign busif_base_addr3_updt = busif_updt && busif_addr[11:0] == BASE_ADDR3_OFFSET; +assign busif_base_addr4_updt = busif_updt && busif_addr[11:0] == BASE_ADDR4_OFFSET; +assign busif_base_addr5_updt = busif_updt && busif_addr[11:0] == BASE_ADDR5_OFFSET; +assign busif_base_addr6_updt = busif_updt && busif_addr[11:0] == BASE_ADDR6_OFFSET; +assign busif_base_addr7_updt = busif_updt && busif_addr[11:0] == BASE_ADDR7_OFFSET; + +assign busif_flg0_updt = busif_updt && busif_addr[11:0] == FLAG0_OFFSET; +assign busif_flg1_updt = busif_updt && busif_addr[11:0] == FLAG1_OFFSET; +assign busif_flg2_updt = busif_updt && busif_addr[11:0] == FLAG2_OFFSET; +assign busif_flg3_updt = busif_updt && busif_addr[11:0] == FLAG3_OFFSET; +assign busif_flg4_updt = busif_updt && busif_addr[11:0] == FLAG4_OFFSET; +assign busif_flg5_updt = busif_updt && busif_addr[11:0] == FLAG5_OFFSET; +assign busif_flg6_updt = busif_updt && busif_addr[11:0] == FLAG6_OFFSET; +assign busif_flg7_updt = busif_updt && busif_addr[11:0] == FLAG7_OFFSET; + +// &ConnRule(s/_x/0/); @74 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_0"); @75 +pa_sysmap_reg x_pa_sysmap_reg_0 ( + .busif_base_addr_x_updt (busif_base_addr0_updt ), + .busif_base_addr_x_value (busif_base_addr0_value ), + .busif_flg_x_updt (busif_flg0_updt ), + .busif_flg_x_value (busif_flg0_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr0 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr0_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr0_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg0_value ) +); + + +// &ConnRule(s/_x/1/); @77 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_1"); @78 +pa_sysmap_reg x_pa_sysmap_reg_1 ( + .busif_base_addr_x_updt (busif_base_addr1_updt ), + .busif_base_addr_x_value (busif_base_addr1_value ), + .busif_flg_x_updt (busif_flg1_updt ), + .busif_flg_x_value (busif_flg1_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr1 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr1_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr1_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg1_value ) +); + + +// &ConnRule(s/_x/2/); @80 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_2"); @81 +pa_sysmap_reg x_pa_sysmap_reg_2 ( + .busif_base_addr_x_updt (busif_base_addr2_updt ), + .busif_base_addr_x_value (busif_base_addr2_value ), + .busif_flg_x_updt (busif_flg2_updt ), + .busif_flg_x_value (busif_flg2_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr2 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr2_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr2_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg2_value ) +); + + +// &ConnRule(s/_x/3/); @83 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_3"); @84 +pa_sysmap_reg x_pa_sysmap_reg_3 ( + .busif_base_addr_x_updt (busif_base_addr3_updt ), + .busif_base_addr_x_value (busif_base_addr3_value ), + .busif_flg_x_updt (busif_flg3_updt ), + .busif_flg_x_value (busif_flg3_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr3 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr3_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr3_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg3_value ) +); + + +// &ConnRule(s/_x/4/); @86 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_4"); @87 +pa_sysmap_reg x_pa_sysmap_reg_4 ( + .busif_base_addr_x_updt (busif_base_addr4_updt ), + .busif_base_addr_x_value (busif_base_addr4_value ), + .busif_flg_x_updt (busif_flg4_updt ), + .busif_flg_x_value (busif_flg4_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr4 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr4_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr4_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg4_value ) +); + + +// &ConnRule(s/_x/5/); @89 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_5"); @90 +pa_sysmap_reg x_pa_sysmap_reg_5 ( + .busif_base_addr_x_updt (busif_base_addr5_updt ), + .busif_base_addr_x_value (busif_base_addr5_value ), + .busif_flg_x_updt (busif_flg5_updt ), + .busif_flg_x_value (busif_flg5_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr5 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr5_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr5_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg5_value ) +); + + +// &ConnRule(s/_x/6/); @92 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_6"); @93 +pa_sysmap_reg x_pa_sysmap_reg_6 ( + .busif_base_addr_x_updt (busif_base_addr6_updt ), + .busif_base_addr_x_value (busif_base_addr6_value ), + .busif_flg_x_updt (busif_flg6_updt ), + .busif_flg_x_value (busif_flg6_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr6 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr6_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr6_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg6_value ) +); + + +// &ConnRule(s/_x/7/); @95 +// &Instance("pa_sysmap_reg", "x_pa_sysmap_reg_7"); @96 +pa_sysmap_reg x_pa_sysmap_reg_7 ( + .busif_base_addr_x_updt (busif_base_addr7_updt ), + .busif_base_addr_x_value (busif_base_addr7_value ), + .busif_flg_x_updt (busif_flg7_updt ), + .busif_flg_x_value (busif_flg7_value ), + .busif_wdata (busif_wdata ), + .cpurst_b (cpurst_b ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr_x (pad_cpu_sysmap_addr7 ), + .pad_cpu_sysmap_addr_x_attr (pad_cpu_sysmap_addr7_attr ), + .sysmap_base_addr_x_value (sysmap_base_addr7_value ), + .sysmap_clk (sysmap_clk ), + .sysmap_flg_x_value (sysmap_flg7_value ) +); + + +// &CombBeg; @98 +always @( busif_flg7_value[31:0] + or busif_flg2_value[31:0] + or busif_base_addr7_value[31:0] + or busif_base_addr2_value[31:0] + or busif_flg1_value[31:0] + or busif_addr[11:0] + or busif_flg5_value[31:0] + or busif_base_addr6_value[31:0] + or busif_base_addr1_value[31:0] + or busif_base_addr0_value[31:0] + or busif_base_addr4_value[31:0] + or busif_base_addr5_value[31:0] + or busif_base_addr3_value[31:0] + or busif_flg0_value[31:0] + or busif_flg4_value[31:0] + or busif_flg6_value[31:0] + or busif_flg3_value[31:0]) +begin + case(busif_addr[11:0]) + BASE_ADDR0_OFFSET: busif_rdata[31:0] = busif_base_addr0_value[31:0]; + BASE_ADDR1_OFFSET: busif_rdata[31:0] = busif_base_addr1_value[31:0]; + BASE_ADDR2_OFFSET: busif_rdata[31:0] = busif_base_addr2_value[31:0]; + BASE_ADDR3_OFFSET: busif_rdata[31:0] = busif_base_addr3_value[31:0]; + BASE_ADDR4_OFFSET: busif_rdata[31:0] = busif_base_addr4_value[31:0]; + BASE_ADDR5_OFFSET: busif_rdata[31:0] = busif_base_addr5_value[31:0]; + BASE_ADDR6_OFFSET: busif_rdata[31:0] = busif_base_addr6_value[31:0]; + BASE_ADDR7_OFFSET: busif_rdata[31:0] = busif_base_addr7_value[31:0]; + FLAG0_OFFSET: busif_rdata[31:0] = busif_flg0_value[31:0]; + FLAG1_OFFSET: busif_rdata[31:0] = busif_flg1_value[31:0]; + FLAG2_OFFSET: busif_rdata[31:0] = busif_flg2_value[31:0]; + FLAG3_OFFSET: busif_rdata[31:0] = busif_flg3_value[31:0]; + FLAG4_OFFSET: busif_rdata[31:0] = busif_flg4_value[31:0]; + FLAG5_OFFSET: busif_rdata[31:0] = busif_flg5_value[31:0]; + FLAG6_OFFSET: busif_rdata[31:0] = busif_flg6_value[31:0]; + FLAG7_OFFSET: busif_rdata[31:0] = busif_flg7_value[31:0]; + default: busif_rdata[31:0] = 32'b0; + endcase +// &CombEnd; @118 +end + +assign sysmap_tcipif_cmplt = busif_sel; +assign sysmap_tcipif_rdata[31:0] = busif_rdata[31:0]; + +assign sysmap_clk_en = busif_updt | ifu_sysmap_rst_sample; +// &Instance("gated_clk_cell", "x_sysmap_clk"); @124 +gated_clk_cell x_sysmap_clk ( + .clk_in (forever_cpuclk ), + .clk_out (sysmap_clk ), + .external_en (1'b0 ), + .global_en (cp0_yy_clk_en ), + .local_en (sysmap_clk_en ), + .module_en (cp0_pmp_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk), @125 +// .external_en (1'b0), @126 +// .global_en (cp0_yy_clk_en), @127 +// .module_en (cp0_pmp_icg_en), @128 +// .local_en (sysmap_clk_en), @129 +// .clk_out (sysmap_clk)); @130 + +// &ModuleEnd; @132 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_hit.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_hit.v new file mode 100644 index 0000000000000000000000000000000000000000..0df81d614b8dce5b09060dfde87dea4e245e855b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_hit.v @@ -0,0 +1,47 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_sysmap_hit( + addr_ge_bottom_x, + addr_ge_upaddr_x, + sysmap_comp_hit_x, + sysmap_hit_x +); + +// &Ports; @23 +input addr_ge_bottom_x; +input sysmap_comp_hit_x; +output addr_ge_upaddr_x; +output sysmap_hit_x; + +// &Regs; @24 + +// &Wires; @25 +wire addr_ge_bottom_x; +wire addr_ge_upaddr_x; +wire addr_ls_top; +wire sysmap_comp_hit_x; +wire sysmap_hit_x; + + + +assign addr_ls_top = sysmap_comp_hit_x; + +assign addr_ge_upaddr_x = !addr_ls_top; +assign sysmap_hit_x = addr_ge_bottom_x && addr_ls_top; + +// &ModuleEnd; @33 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_reg.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_reg.v new file mode 100644 index 0000000000000000000000000000000000000000..de2090ba2ffd0398280beab8d6c031809d66b599 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_reg.v @@ -0,0 +1,102 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_sysmap_reg( + busif_base_addr_x_updt, + busif_base_addr_x_value, + busif_flg_x_updt, + busif_flg_x_value, + busif_wdata, + cpurst_b, + ifu_sysmap_rst_sample, + pad_cpu_sysmap_addr_x, + pad_cpu_sysmap_addr_x_attr, + sysmap_base_addr_x_value, + sysmap_clk, + sysmap_flg_x_value +); + + +// &Ports; @25 +input busif_base_addr_x_updt; +input busif_flg_x_updt; +input [31:0] busif_wdata; +input cpurst_b; +input ifu_sysmap_rst_sample; +input [19:0] pad_cpu_sysmap_addr_x; +input [2 :0] pad_cpu_sysmap_addr_x_attr; +input sysmap_clk; +output [31:0] busif_base_addr_x_value; +output [31:0] busif_flg_x_value; +output [19:0] sysmap_base_addr_x_value; +output [4 :0] sysmap_flg_x_value; + +// &Regs; @26 +reg [19:0] base_addr_value; +reg [2 :0] flg_value_3; + +// &Wires; @27 +wire busif_base_addr_x_updt; +wire [31:0] busif_base_addr_x_value; +wire busif_flg_x_updt; +wire [31:0] busif_flg_x_value; +wire [31:0] busif_wdata; +wire cpurst_b; +wire ifu_sysmap_rst_sample; +wire [19:0] pad_cpu_sysmap_addr_x; +wire [2 :0] pad_cpu_sysmap_addr_x_attr; +wire [19:0] sysmap_base_addr_x_value; +wire sysmap_clk; +wire [4 :0] sysmap_flg_x_value; + + +parameter ADDR_WIDTH = 32-12; +parameter FLG_WIDTH = 5; + +parameter FLG_RST_VALUE = {FLG_WIDTH{1'b0}}; +parameter ADDR_RST_VALUE = {ADDR_WIDTH{1'b0}}; + +// &Force("bus", "busif_wdata", 31, 0); @35 +// &Force("bus", "flg_x_reset_value", FLG_WIDTH-1, 0); @36 +always @ (posedge sysmap_clk or negedge cpurst_b) +begin + if (!cpurst_b) + flg_value_3[FLG_WIDTH-3:0] <= {(FLG_WIDTH-2){1'b0}}; + else if(ifu_sysmap_rst_sample) + flg_value_3[FLG_WIDTH-3:0] <= pad_cpu_sysmap_addr_x_attr[FLG_WIDTH-3:0]; + else if (busif_flg_x_updt) + flg_value_3[FLG_WIDTH-3:0] <= busif_wdata[FLG_WIDTH-1:2]; +end +assign busif_flg_x_value[31:0] = {{(32-FLG_WIDTH){1'b0}}, flg_value_3[FLG_WIDTH-3:0], 2'b0}; +assign sysmap_flg_x_value[FLG_WIDTH-1:0] = {flg_value_3[FLG_WIDTH-3:0], 2'b0}; + +always @ (posedge sysmap_clk or negedge cpurst_b) +begin + if (!cpurst_b) + base_addr_value[ADDR_WIDTH-1:0] <= {ADDR_WIDTH{1'b0}}; + else if(ifu_sysmap_rst_sample) + base_addr_value[ADDR_WIDTH-1:0] <= pad_cpu_sysmap_addr_x[ADDR_WIDTH-1:0]; + else if (busif_base_addr_x_updt) + base_addr_value[ADDR_WIDTH-1:0] <= busif_wdata[ADDR_WIDTH-1:0]; +end +assign busif_base_addr_x_value[31:0] = {{(32-ADDR_WIDTH){1'b0}}, base_addr_value[ADDR_WIDTH-1:0]}; +assign sysmap_base_addr_x_value[ADDR_WIDTH-1:0] = base_addr_value[ADDR_WIDTH-1:0]; + +// &ModuleEnd; @61 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_top.v new file mode 100644 index 0000000000000000000000000000000000000000..0634485dca36d66f4a4c72459515ce60c76d49f9 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/pa_sysmap_top.v @@ -0,0 +1,263 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module pa_sysmap_top( + cp0_pmp_icg_en, + cp0_yy_clk_en, + cpurst_b, + forever_cpuclk, + ifu_sysmap_pa, + ifu_sysmap_rst_sample, + lsu_sysmap_pa, + pad_cpu_sysmap_addr0, + pad_cpu_sysmap_addr0_attr, + pad_cpu_sysmap_addr1, + pad_cpu_sysmap_addr1_attr, + pad_cpu_sysmap_addr2, + pad_cpu_sysmap_addr2_attr, + pad_cpu_sysmap_addr3, + pad_cpu_sysmap_addr3_attr, + pad_cpu_sysmap_addr4, + pad_cpu_sysmap_addr4_attr, + pad_cpu_sysmap_addr5, + pad_cpu_sysmap_addr5_attr, + pad_cpu_sysmap_addr6, + pad_cpu_sysmap_addr6_attr, + pad_cpu_sysmap_addr7, + pad_cpu_sysmap_addr7_attr, + pad_yy_icg_scan_en, + sysmap_ifu_flg, + sysmap_lsu_flg, + sysmap_tcipif_cmplt, + sysmap_tcipif_rdata, + tcipif_sysmap_addr, + tcipif_sysmap_sel, + tcipif_sysmap_wdata, + tcipif_sysmap_write +); + +// &Ports; @24 +input cp0_pmp_icg_en; +input cp0_yy_clk_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] ifu_sysmap_pa; +input ifu_sysmap_rst_sample; +input [31:0] lsu_sysmap_pa; +input [19:0] pad_cpu_sysmap_addr0; +input [2 :0] pad_cpu_sysmap_addr0_attr; +input [19:0] pad_cpu_sysmap_addr1; +input [2 :0] pad_cpu_sysmap_addr1_attr; +input [19:0] pad_cpu_sysmap_addr2; +input [2 :0] pad_cpu_sysmap_addr2_attr; +input [19:0] pad_cpu_sysmap_addr3; +input [2 :0] pad_cpu_sysmap_addr3_attr; +input [19:0] pad_cpu_sysmap_addr4; +input [2 :0] pad_cpu_sysmap_addr4_attr; +input [19:0] pad_cpu_sysmap_addr5; +input [2 :0] pad_cpu_sysmap_addr5_attr; +input [19:0] pad_cpu_sysmap_addr6; +input [2 :0] pad_cpu_sysmap_addr6_attr; +input [19:0] pad_cpu_sysmap_addr7; +input [2 :0] pad_cpu_sysmap_addr7_attr; +input pad_yy_icg_scan_en; +input [15:0] tcipif_sysmap_addr; +input tcipif_sysmap_sel; +input [31:0] tcipif_sysmap_wdata; +input tcipif_sysmap_write; +output [4 :0] sysmap_ifu_flg; +output [4 :0] sysmap_lsu_flg; +output sysmap_tcipif_cmplt; +output [31:0] sysmap_tcipif_rdata; + +// &Regs; @25 + +// &Wires; @26 +wire cp0_pmp_icg_en; +wire cp0_yy_clk_en; +wire cpurst_b; +wire forever_cpuclk; +wire [31:0] ifu_sysmap_pa; +wire ifu_sysmap_rst_sample; +wire [31:0] lsu_sysmap_pa; +wire [19:0] pad_cpu_sysmap_addr0; +wire [2 :0] pad_cpu_sysmap_addr0_attr; +wire [19:0] pad_cpu_sysmap_addr1; +wire [2 :0] pad_cpu_sysmap_addr1_attr; +wire [19:0] pad_cpu_sysmap_addr2; +wire [2 :0] pad_cpu_sysmap_addr2_attr; +wire [19:0] pad_cpu_sysmap_addr3; +wire [2 :0] pad_cpu_sysmap_addr3_attr; +wire [19:0] pad_cpu_sysmap_addr4; +wire [2 :0] pad_cpu_sysmap_addr4_attr; +wire [19:0] pad_cpu_sysmap_addr5; +wire [2 :0] pad_cpu_sysmap_addr5_attr; +wire [19:0] pad_cpu_sysmap_addr6; +wire [2 :0] pad_cpu_sysmap_addr6_attr; +wire [19:0] pad_cpu_sysmap_addr7; +wire [2 :0] pad_cpu_sysmap_addr7_attr; +wire pad_yy_icg_scan_en; +wire [19:0] sysmap_base_addr0_value; +wire [19:0] sysmap_base_addr1_value; +wire [19:0] sysmap_base_addr2_value; +wire [19:0] sysmap_base_addr3_value; +wire [19:0] sysmap_base_addr4_value; +wire [19:0] sysmap_base_addr5_value; +wire [19:0] sysmap_base_addr6_value; +wire [19:0] sysmap_base_addr7_value; +wire [4 :0] sysmap_flg0; +wire [4 :0] sysmap_flg0_value; +wire [4 :0] sysmap_flg1; +wire [4 :0] sysmap_flg1_value; +wire [4 :0] sysmap_flg2_value; +wire [4 :0] sysmap_flg3_value; +wire [4 :0] sysmap_flg4_value; +wire [4 :0] sysmap_flg5_value; +wire [4 :0] sysmap_flg6_value; +wire [4 :0] sysmap_flg7_value; +wire [4 :0] sysmap_ifu_flg; +wire [4 :0] sysmap_lsu_flg; +wire [19:0] sysmap_pa0; +wire [19:0] sysmap_pa1; +wire sysmap_tcipif_cmplt; +wire [31:0] sysmap_tcipif_rdata; +wire [15:0] tcipif_sysmap_addr; +wire tcipif_sysmap_sel; +wire [31:0] tcipif_sysmap_wdata; +wire tcipif_sysmap_write; + + +parameter ADDR_WIDTH = 32-12; +parameter FLG_WIDTH = 5; + +//========================================================== +// System Map top Module +//========================================================== + +//------------------------------------------------ +// Instance two accesses for IFU and LSU +//------------------------------------------------ +// &ConnRule(s/_y/0/); @38 +// &Instance("pa_sysmap_access", "x_ifu_pa_sysmap_access"); @39 +pa_sysmap_access x_ifu_pa_sysmap_access ( + .sysmap_base_addr0_value (sysmap_base_addr0_value), + .sysmap_base_addr1_value (sysmap_base_addr1_value), + .sysmap_base_addr2_value (sysmap_base_addr2_value), + .sysmap_base_addr3_value (sysmap_base_addr3_value), + .sysmap_base_addr4_value (sysmap_base_addr4_value), + .sysmap_base_addr5_value (sysmap_base_addr5_value), + .sysmap_base_addr6_value (sysmap_base_addr6_value), + .sysmap_base_addr7_value (sysmap_base_addr7_value), + .sysmap_flg0_value (sysmap_flg0_value ), + .sysmap_flg1_value (sysmap_flg1_value ), + .sysmap_flg2_value (sysmap_flg2_value ), + .sysmap_flg3_value (sysmap_flg3_value ), + .sysmap_flg4_value (sysmap_flg4_value ), + .sysmap_flg5_value (sysmap_flg5_value ), + .sysmap_flg6_value (sysmap_flg6_value ), + .sysmap_flg7_value (sysmap_flg7_value ), + .sysmap_flg_y (sysmap_flg0 ), + .sysmap_pa_y (sysmap_pa0 ) +); + + +// &ConnRule(s/_y/1/); @41 +// &Instance("pa_sysmap_access", "x_lsu_pa_sysmap_access"); @42 +pa_sysmap_access x_lsu_pa_sysmap_access ( + .sysmap_base_addr0_value (sysmap_base_addr0_value), + .sysmap_base_addr1_value (sysmap_base_addr1_value), + .sysmap_base_addr2_value (sysmap_base_addr2_value), + .sysmap_base_addr3_value (sysmap_base_addr3_value), + .sysmap_base_addr4_value (sysmap_base_addr4_value), + .sysmap_base_addr5_value (sysmap_base_addr5_value), + .sysmap_base_addr6_value (sysmap_base_addr6_value), + .sysmap_base_addr7_value (sysmap_base_addr7_value), + .sysmap_flg0_value (sysmap_flg0_value ), + .sysmap_flg1_value (sysmap_flg1_value ), + .sysmap_flg2_value (sysmap_flg2_value ), + .sysmap_flg3_value (sysmap_flg3_value ), + .sysmap_flg4_value (sysmap_flg4_value ), + .sysmap_flg5_value (sysmap_flg5_value ), + .sysmap_flg6_value (sysmap_flg6_value ), + .sysmap_flg7_value (sysmap_flg7_value ), + .sysmap_flg_y (sysmap_flg1 ), + .sysmap_pa_y (sysmap_pa1 ) +); + + +// IFU Ports +// &Force("bus", "ifu_sysmap_pa", 31, 0); @45 +assign sysmap_pa0[19:0] = ifu_sysmap_pa[31:12]; +assign sysmap_ifu_flg[4:0] = sysmap_flg0[4:0]; + +// LSU Ports +// &Force("bus", "lsu_sysmap_pa", 31, 0); @50 +assign sysmap_pa1[19:0] = lsu_sysmap_pa[31:12]; +assign sysmap_lsu_flg[4:0] = sysmap_flg1[4:0]; + +// &Instance("pa_sysmap_busif"); @55 +pa_sysmap_busif x_pa_sysmap_busif ( + .cp0_pmp_icg_en (cp0_pmp_icg_en ), + .cp0_yy_clk_en (cp0_yy_clk_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_sysmap_rst_sample (ifu_sysmap_rst_sample ), + .pad_cpu_sysmap_addr0 (pad_cpu_sysmap_addr0 ), + .pad_cpu_sysmap_addr0_attr (pad_cpu_sysmap_addr0_attr), + .pad_cpu_sysmap_addr1 (pad_cpu_sysmap_addr1 ), + .pad_cpu_sysmap_addr1_attr (pad_cpu_sysmap_addr1_attr), + .pad_cpu_sysmap_addr2 (pad_cpu_sysmap_addr2 ), + .pad_cpu_sysmap_addr2_attr (pad_cpu_sysmap_addr2_attr), + .pad_cpu_sysmap_addr3 (pad_cpu_sysmap_addr3 ), + .pad_cpu_sysmap_addr3_attr (pad_cpu_sysmap_addr3_attr), + .pad_cpu_sysmap_addr4 (pad_cpu_sysmap_addr4 ), + .pad_cpu_sysmap_addr4_attr (pad_cpu_sysmap_addr4_attr), + .pad_cpu_sysmap_addr5 (pad_cpu_sysmap_addr5 ), + .pad_cpu_sysmap_addr5_attr (pad_cpu_sysmap_addr5_attr), + .pad_cpu_sysmap_addr6 (pad_cpu_sysmap_addr6 ), + .pad_cpu_sysmap_addr6_attr (pad_cpu_sysmap_addr6_attr), + .pad_cpu_sysmap_addr7 (pad_cpu_sysmap_addr7 ), + .pad_cpu_sysmap_addr7_attr (pad_cpu_sysmap_addr7_attr), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .sysmap_base_addr0_value (sysmap_base_addr0_value ), + .sysmap_base_addr1_value (sysmap_base_addr1_value ), + .sysmap_base_addr2_value (sysmap_base_addr2_value ), + .sysmap_base_addr3_value (sysmap_base_addr3_value ), + .sysmap_base_addr4_value (sysmap_base_addr4_value ), + .sysmap_base_addr5_value (sysmap_base_addr5_value ), + .sysmap_base_addr6_value (sysmap_base_addr6_value ), + .sysmap_base_addr7_value (sysmap_base_addr7_value ), + .sysmap_flg0_value (sysmap_flg0_value ), + .sysmap_flg1_value (sysmap_flg1_value ), + .sysmap_flg2_value (sysmap_flg2_value ), + .sysmap_flg3_value (sysmap_flg3_value ), + .sysmap_flg4_value (sysmap_flg4_value ), + .sysmap_flg5_value (sysmap_flg5_value ), + .sysmap_flg6_value (sysmap_flg6_value ), + .sysmap_flg7_value (sysmap_flg7_value ), + .sysmap_tcipif_cmplt (sysmap_tcipif_cmplt ), + .sysmap_tcipif_rdata (sysmap_tcipif_rdata ), + .tcipif_sysmap_addr (tcipif_sysmap_addr ), + .tcipif_sysmap_sel (tcipif_sysmap_sel ), + .tcipif_sysmap_wdata (tcipif_sysmap_wdata ), + .tcipif_sysmap_write (tcipif_sysmap_write ) +); + + +// &ModuleEnd; @75 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/sysmap.h b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/sysmap.h new file mode 100644 index 0000000000000000000000000000000000000000..cbc9150747c0a2a6f58d835321902fdf4c92685a --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/sysmap/rtl/sysmap.h @@ -0,0 +1,40 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// ADDR is 20-bit, 4K address +// Flag includes: Strong Order, Cacheable, Bufferable +`define SYSMAP_BASE_ADDR0 20'hffff +`define SYSMAP_FLG0 3'b011 + +`define SYSMAP_BASE_ADDR1 20'h1ffff +`define SYSMAP_FLG1 3'b000 + +`define SYSMAP_BASE_ADDR2 20'h3ffff +`define SYSMAP_FLG2 3'b011 + +`define SYSMAP_BASE_ADDR3 20'h6ffff +`define SYSMAP_FLG3 3'b000 + +`define SYSMAP_BASE_ADDR4 20'haffff +`define SYSMAP_FLG4 3'b011 + +`define SYSMAP_BASE_ADDR5 20'hf0000 +`define SYSMAP_FLG5 3'b100 + +`define SYSMAP_BASE_ADDR6 20'hfff5f +`define SYSMAP_FLG6 3'b011 + +`define SYSMAP_BASE_ADDR7 20'hfffff +`define SYSMAP_FLG7 3'b100 diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_behavior_bus.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_behavior_bus.v new file mode 100644 index 0000000000000000000000000000000000000000..388d75ba9e81d8592488ffc425fae34bbbbc8ef2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_behavior_bus.v @@ -0,0 +1,359 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_tcipif_behavior_bus( + bmu_tcipif_dbus_acc_deny, + bmu_tcipif_dbus_addr, + bmu_tcipif_dbus_req, + bmu_tcipif_dbus_req_dp, + bmu_tcipif_dbus_size, + bmu_tcipif_dbus_supv_mode, + bmu_tcipif_dbus_wdata, + bmu_tcipif_dbus_write, + clic_tcipif_cmplt, + clic_tcipif_rdata, + clint_tcipif_cmplt, + clint_tcipif_rdata, + cp0_biu_icg_en, + cpurst_b, + forever_cpuclk, + pad_cpu_tcip_base, + pad_yy_icg_scan_en, + rtu_yy_xx_dbgon, + sysmap_tcipif_cmplt, + sysmap_tcipif_rdata, + tcip_cp0_clic_base, + tcipif_bmu_dbus_acc_err, + tcipif_bmu_dbus_data, + tcipif_bmu_dbus_grnt, + tcipif_bmu_dbus_trans_cmplt, + tcipif_clic_sel, + tcipif_clic_size, + tcipif_clint_sel, + tcipif_sysmap_sel, + tcipif_xx_addr, + tcipif_xx_wdata, + tcipif_xx_write +); + +// &Ports; @24 +input bmu_tcipif_dbus_acc_deny; +input [31:0] bmu_tcipif_dbus_addr; +input bmu_tcipif_dbus_req; +input bmu_tcipif_dbus_req_dp; +input [1 :0] bmu_tcipif_dbus_size; +input bmu_tcipif_dbus_supv_mode; +input [31:0] bmu_tcipif_dbus_wdata; +input bmu_tcipif_dbus_write; +input clic_tcipif_cmplt; +input [31:0] clic_tcipif_rdata; +input clint_tcipif_cmplt; +input [31:0] clint_tcipif_rdata; +input cp0_biu_icg_en; +input cpurst_b; +input forever_cpuclk; +input [31:0] pad_cpu_tcip_base; +input pad_yy_icg_scan_en; +input rtu_yy_xx_dbgon; +input sysmap_tcipif_cmplt; +input [31:0] sysmap_tcipif_rdata; +output [31:0] tcip_cp0_clic_base; +output tcipif_bmu_dbus_acc_err; +output [31:0] tcipif_bmu_dbus_data; +output tcipif_bmu_dbus_grnt; +output tcipif_bmu_dbus_trans_cmplt; +output tcipif_clic_sel; +output [1 :0] tcipif_clic_size; +output tcipif_clint_sel; +output tcipif_sysmap_sel; +output [15:0] tcipif_xx_addr; +output [31:0] tcipif_xx_wdata; +output tcipif_xx_write; + +// &Regs; @25 +reg clic_sel_ff; +reg [1 :0] clic_size_ff; +reg clint_sel_ff; +reg dummy_addr_cmplt; +reg sysmap_sel_ff; +reg tcip_acc_deny_ff; +reg tcipif_acc_err; +reg [15:0] tcipif_xx_addr; +reg tcipif_xx_write; + +// &Wires; @26 +wire bmu_tcipif_dbus_acc_deny; +wire [31:0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31:0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire clic_req_mask; +wire clic_sel; +wire clic_tcipif_cmplt; +wire [31:0] clic_tcipif_rdata; +wire clint_req_mask; +wire clint_sel; +wire clint_tcipif_cmplt; +wire [31:0] clint_tcipif_rdata; +wire cp0_biu_icg_en; +wire cpurst_b; +wire dbus_err; +wire dbus_req_pre; +wire dbus_sel; +wire dummy_addr_sel; +wire forever_cpuclk; +wire [31:0] pad_cpu_tcip_base; +wire pad_yy_icg_scan_en; +wire rtu_yy_xx_dbgon; +wire sysmap_req_mask; +wire sysmap_sel; +wire sysmap_tcipif_cmplt; +wire [31:0] sysmap_tcipif_rdata; +wire tcip_acc_deny; +wire [31:0] tcip_cp0_clic_base; +wire tcip_ctrl_clk; +wire tcip_ctrl_clk_en; +wire tcip_dp_clk; +wire tcip_err; +wire [31:0] tcip_req_addr; +wire tcip_req_gate; +wire tcip_req_mask; +wire tcip_req_pre; +wire [1 :0] tcip_req_size; +wire tcip_req_write; +wire tcipif_bmu_dbus_acc_err; +wire [31:0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_clic_sel; +wire [1 :0] tcipif_clic_size; +wire tcipif_clint_sel; +wire [31:0] tcipif_rdata; +wire tcipif_sysmap_sel; +wire tcipif_trans_cmplt; +wire [31:0] tcipif_xx_wdata; +wire xx_tcipif_cmplt; + + +//========================================================== +// Req Arb +//========================================================== +//for grnt + +assign dbus_req_pre = bmu_tcipif_dbus_req && !tcip_req_mask; +assign tcip_req_pre = dbus_req_pre; + +assign tcip_req_gate = bmu_tcipif_dbus_req_dp; + +assign dbus_sel = bmu_tcipif_dbus_req_dp && !tcip_req_mask; + +//data path +assign dbus_err = !bmu_tcipif_dbus_supv_mode && !rtu_yy_xx_dbgon;// | bmu_tcipif_dbus_acc_deny; +assign tcip_err = dbus_sel && dbus_err; + +assign tcip_acc_deny = dbus_sel & bmu_tcipif_dbus_acc_deny; + +assign tcip_req_addr[31:0] = {32{dbus_sel}} & bmu_tcipif_dbus_addr[31:0]; + +assign tcip_req_write = dbus_sel & bmu_tcipif_dbus_write; + +assign tcip_req_size[1:0] = {2{dbus_sel}} & bmu_tcipif_dbus_size[1:0]; + +//========================================================== +// Addr Arb for IPs +//========================================================== + +// &Force("input","pad_cpu_tcip_base"); @59 +// &Force("bus","pad_cpu_tcip_base",31,0); @60 +assign clint_sel = (tcip_req_addr[31:16] == {pad_cpu_tcip_base[31:28],12'h000}); + +assign clic_sel = (tcip_req_addr[31:16] == {pad_cpu_tcip_base[31:28], 12'h080}); +assign tcip_cp0_clic_base[31:0] = {pad_cpu_tcip_base[31:28], 28'h0800000}; + +assign sysmap_sel = (tcip_req_addr[31:12] == {pad_cpu_tcip_base[31:28],16'hffff}); + +assign dummy_addr_sel = !(clint_sel | clic_sel | sysmap_sel); + +//========================================================== +// error +//========================================================== + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tcipif_acc_err <= 1'b0; + else if(tcip_req_pre) + tcipif_acc_err <= tcip_err; + else if(tcipif_acc_err) + tcipif_acc_err <= 1'b0; +end + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + clint_sel_ff <= 1'b0; + else if(tcip_req_pre) + clint_sel_ff <= clint_sel; + else if(clint_tcipif_cmplt) + clint_sel_ff <= 1'b0; +end +assign clint_req_mask = clint_sel_ff && !clint_tcipif_cmplt; +assign tcipif_clint_sel = clint_sel_ff && !tcipif_acc_err & !tcip_acc_deny_ff; + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + clic_sel_ff <= 1'b0; + else if(tcip_req_pre) + clic_sel_ff <= clic_sel; + else if(clic_tcipif_cmplt) + clic_sel_ff <= 1'b0; +end + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + clic_size_ff[1:0] <= 2'b0; + else if(tcip_req_pre) + clic_size_ff[1:0] <= tcip_req_size[1:0]; +end +assign clic_req_mask = clic_sel_ff && !clic_tcipif_cmplt; +assign tcipif_clic_sel = clic_sel_ff && !tcipif_acc_err && !tcip_acc_deny_ff; +assign tcipif_clic_size[1:0] = clic_size_ff[1:0]; +// &Force("nonport", "tcip_req_size"); @126 + + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + sysmap_sel_ff <= 1'b0; + else if(tcip_req_pre) + sysmap_sel_ff <= sysmap_sel; + else if(sysmap_tcipif_cmplt) + sysmap_sel_ff <= 1'b0; +end +assign sysmap_req_mask = sysmap_sel_ff && !sysmap_tcipif_cmplt; +assign tcipif_sysmap_sel = sysmap_sel_ff & !tcipif_acc_err && !tcip_acc_deny_ff; + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + dummy_addr_cmplt <= 1'b0; + else if(tcip_req_pre) + dummy_addr_cmplt <= dummy_addr_sel; + else if(dummy_addr_cmplt) + dummy_addr_cmplt <= 1'b0; +end + +assign tcip_req_mask = clint_req_mask + || clic_req_mask + || sysmap_req_mask; + + +always @(posedge tcip_ctrl_clk or negedge cpurst_b) +begin + if(!cpurst_b) + tcip_acc_deny_ff <= 1'b0; + else if (tcip_req_pre) + tcip_acc_deny_ff <= tcip_acc_deny; + else if (tcip_acc_deny_ff) + tcip_acc_deny_ff <= 1'b0; +end + +//========================================================== +// Addr, Wdata to IPs +//========================================================== +//addr and write en +always @(posedge tcip_dp_clk) +begin + if(tcip_req_pre) + begin + tcipif_xx_write <= tcip_req_write; + tcipif_xx_addr[15:0] <= tcip_req_addr[15:0]; + end +end + +assign tcipif_xx_wdata[31:0] = bmu_tcipif_dbus_wdata[31:0]; + +//========================================================== +// Grant and Cmplt from IPs to BMU +//========================================================== +//grant to BMU + +//cmplt to BMU +assign xx_tcipif_cmplt = clint_tcipif_cmplt + | clic_tcipif_cmplt + | sysmap_tcipif_cmplt; + +assign tcipif_trans_cmplt = xx_tcipif_cmplt + | dummy_addr_cmplt + | tcipif_acc_err + | tcip_acc_deny_ff; + +assign tcipif_rdata[31:0] = {32{clint_tcipif_cmplt}} & clint_tcipif_rdata[31:0] + | {32{clic_tcipif_cmplt}} & clic_tcipif_rdata[31:0] + | {32{sysmap_tcipif_cmplt}} & sysmap_tcipif_rdata[31:0]; + +assign tcipif_bmu_dbus_grnt = dbus_sel; +assign tcipif_bmu_dbus_trans_cmplt = tcipif_trans_cmplt; +assign tcipif_bmu_dbus_acc_err = tcipif_acc_err; +assign tcipif_bmu_dbus_data[31:0] = tcipif_rdata[31:0]; + +assign tcip_ctrl_clk_en = tcip_req_gate | tcipif_trans_cmplt; +// &Instance("gated_clk_cell", "x_tcipif_dbus_ctrl_clk"); @240 +gated_clk_cell x_tcipif_dbus_ctrl_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tcip_ctrl_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (tcip_ctrl_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @241 +// .external_en (1'b0 ), @242 +// .global_en (1'b1 ), @243 +// .module_en (cp0_biu_icg_en ), @244 +// .local_en (tcip_ctrl_clk_en ), @245 +// .clk_out (tcip_ctrl_clk ) @246 +// ); @247 + +// &Instance("gated_clk_cell", "x_tcipif_dbus_dp_clk"); @249 +gated_clk_cell x_tcipif_dbus_dp_clk ( + .clk_in (forever_cpuclk ), + .clk_out (tcip_dp_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (tcip_req_gate ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @250 +// .external_en (1'b0 ), @251 +// .global_en (1'b1 ), @252 +// .module_en (cp0_biu_icg_en ), @253 +// .local_en (tcip_req_gate ), @254 +// .clk_out (tcip_dp_clk ) @255 +// ); @256 + + +// &ModuleEnd; @266 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_dummy_bus.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_dummy_bus.v new file mode 100644 index 0000000000000000000000000000000000000000..addddf1c2a8d6128bdaaaf5f9307b39ad35c95ba --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_dummy_bus.v @@ -0,0 +1,153 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_tcipif_dummy_bus( + bmu_tcipif_ibus_acc_deny, + bmu_tcipif_ibus_addr, + bmu_tcipif_ibus_req, + bmu_tcipif_ibus_req_dp, + bmu_tcipif_ibus_size, + bmu_tcipif_ibus_supv_mode, + bmu_tcipif_ibus_wdata, + bmu_tcipif_ibus_write, + cp0_biu_icg_en, + cpurst_b, + forever_cpuclk, + pad_yy_icg_scan_en, + tcipif_bmu_ibus_acc_err, + tcipif_bmu_ibus_data, + tcipif_bmu_ibus_grnt, + tcipif_bmu_ibus_trans_cmplt +); + +// &Ports; @23 +input bmu_tcipif_ibus_acc_deny; +input [31:0] bmu_tcipif_ibus_addr; +input bmu_tcipif_ibus_req; +input bmu_tcipif_ibus_req_dp; +input [1 :0] bmu_tcipif_ibus_size; +input bmu_tcipif_ibus_supv_mode; +input [31:0] bmu_tcipif_ibus_wdata; +input bmu_tcipif_ibus_write; +input cp0_biu_icg_en; +input cpurst_b; +input forever_cpuclk; +input pad_yy_icg_scan_en; +output tcipif_bmu_ibus_acc_err; +output [31:0] tcipif_bmu_ibus_data; +output tcipif_bmu_ibus_grnt; +output tcipif_bmu_ibus_trans_cmplt; + +// &Regs; @24 +reg bus_next_state; +reg bus_state; + +// &Wires; @25 +wire bmu_tcipif_ibus_req; +wire bmu_tcipif_ibus_req_dp; +wire cp0_biu_icg_en; +wire cpurst_b; +wire forever_cpuclk; +wire ibus_acc_err; +wire ibus_busy; +wire ibus_req; +wire pad_yy_icg_scan_en; +wire sel_clk; +wire sel_clk_en; +wire tcipif_bmu_ibus_acc_err; +wire [31:0] tcipif_bmu_ibus_data; +wire tcipif_bmu_ibus_grnt; +wire tcipif_bmu_ibus_trans_cmplt; + + +//========================================================== +// ACK to IBUS +//========================================================== +// &Force("input","bmu_tcipif_ibus_addr"); @30 +// &Force("input","bmu_tcipif_ibus_write"); @31 +// &Force("input","bmu_tcipif_ibus_size"); @32 +// &Force("input","bmu_tcipif_ibus_acc_deny"); @33 +// &Force("input","bmu_tcipif_ibus_supv_mode"); @34 +// &Force("input","bmu_tcipif_ibus_wdata"); @35 +// &Force("input","bmu_tcipif_ibus_sec"); @37 +// &Force("bus","bmu_tcipif_ibus_addr",31,0); @39 +// &Force("bus","bmu_tcipif_ibus_size",1,0); @40 +// &Force("bus","bmu_tcipif_ibus_wdata",31,0); @41 + +parameter IDLE = 1'b0, + ERROR = 1'b1; + +assign sel_clk_en = bmu_tcipif_ibus_req_dp | ibus_busy; +// &Instance("gated_clk_cell", "x_tcipif_ibus_sel_clk"); @47 +gated_clk_cell x_tcipif_ibus_sel_clk ( + .clk_in (forever_cpuclk ), + .clk_out (sel_clk ), + .external_en (1'b0 ), + .global_en (1'b1 ), + .local_en (sel_clk_en ), + .module_en (cp0_biu_icg_en ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en) +); + +// &Connect(.clk_in (forever_cpuclk ), @48 +// .external_en (1'b0 ), @49 +// .global_en (1'b1 ), @50 +// .module_en (cp0_biu_icg_en ), @51 +// .local_en (sel_clk_en ), @52 +// .clk_out (sel_clk ) @53 +// ); @54 + +always@(posedge sel_clk or negedge cpurst_b) +begin + if(!cpurst_b) + bus_state <= IDLE; + else + bus_state <= bus_next_state; +end + +// &CombBeg; @64 +always @( bus_state + or ibus_req) +begin +case(bus_state) + IDLE: + if(ibus_req) + bus_next_state = ERROR; + else + bus_next_state = IDLE; + ERROR: + if(ibus_req) + bus_next_state = ERROR; + else + bus_next_state = IDLE; + default: + bus_next_state = IDLE; +endcase +// &CombEnd; @79 +end + +assign ibus_req = bmu_tcipif_ibus_req; +assign ibus_busy = (bus_state != IDLE); +assign ibus_acc_err = (bus_state == ERROR); + +assign tcipif_bmu_ibus_grnt = bmu_tcipif_ibus_req_dp; +assign tcipif_bmu_ibus_trans_cmplt = ibus_acc_err; +assign tcipif_bmu_ibus_acc_err = ibus_acc_err; +assign tcipif_bmu_ibus_data[31:0] = 32'b0; + +// &ModuleEnd; @90 +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_top.v new file mode 100644 index 0000000000000000000000000000000000000000..a61641c844aa6efa7e5960c601506e8b4c542b68 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tcipif/rtl/pa_tcipif_top.v @@ -0,0 +1,332 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module pa_tcipif_top( + bmu_tcipif_dbus_acc_deny, + bmu_tcipif_dbus_addr, + bmu_tcipif_dbus_req, + bmu_tcipif_dbus_req_dp, + bmu_tcipif_dbus_size, + bmu_tcipif_dbus_supv_mode, + bmu_tcipif_dbus_wdata, + bmu_tcipif_dbus_write, + bmu_tcipif_ibus_acc_deny, + bmu_tcipif_ibus_addr, + bmu_tcipif_ibus_req, + bmu_tcipif_ibus_req_dp, + bmu_tcipif_ibus_size, + bmu_tcipif_ibus_supv_mode, + bmu_tcipif_ibus_wdata, + bmu_tcipif_ibus_write, + clic_cpu_int_hv, + clic_cpu_int_id, + clic_cpu_int_il, + clic_cpu_int_priv, + cp0_biu_icg_en, + cp0_yy_priv_mode, + cpu_clic_curid, + cpu_clic_int_exit, + cpurst_b, + forever_cpuclk, + ifu_clic_warm_up, + pad_clic_int_vld, + pad_cpu_tcip_base, + pad_yy_dft_clk_rst_b, + pad_yy_icg_scan_en, + pad_yy_scan_mode, + rtu_yy_xx_dbgon, + sysio_clint_me_int, + sysio_clint_mtime, + sysmap_tcipif_cmplt, + sysmap_tcipif_rdata, + tcip_cp0_clic_base, + tcipif_bmu_dbus_acc_err, + tcipif_bmu_dbus_data, + tcipif_bmu_dbus_grnt, + tcipif_bmu_dbus_trans_cmplt, + tcipif_bmu_ibus_acc_err, + tcipif_bmu_ibus_data, + tcipif_bmu_ibus_grnt, + tcipif_bmu_ibus_trans_cmplt, + tcipif_sysmap_addr, + tcipif_sysmap_sel, + tcipif_sysmap_wdata, + tcipif_sysmap_write +); + +// &Ports; @23 +input bmu_tcipif_dbus_acc_deny; +input [31 :0] bmu_tcipif_dbus_addr; +input bmu_tcipif_dbus_req; +input bmu_tcipif_dbus_req_dp; +input [1 :0] bmu_tcipif_dbus_size; +input bmu_tcipif_dbus_supv_mode; +input [31 :0] bmu_tcipif_dbus_wdata; +input bmu_tcipif_dbus_write; +input bmu_tcipif_ibus_acc_deny; +input [31 :0] bmu_tcipif_ibus_addr; +input bmu_tcipif_ibus_req; +input bmu_tcipif_ibus_req_dp; +input [1 :0] bmu_tcipif_ibus_size; +input bmu_tcipif_ibus_supv_mode; +input [31 :0] bmu_tcipif_ibus_wdata; +input bmu_tcipif_ibus_write; +input cp0_biu_icg_en; +input [1 :0] cp0_yy_priv_mode; +input [11 :0] cpu_clic_curid; +input cpu_clic_int_exit; +input cpurst_b; +input forever_cpuclk; +input ifu_clic_warm_up; +input [127:0] pad_clic_int_vld; +input [31 :0] pad_cpu_tcip_base; +input pad_yy_dft_clk_rst_b; +input pad_yy_icg_scan_en; +input pad_yy_scan_mode; +input rtu_yy_xx_dbgon; +input sysio_clint_me_int; +input [63 :0] sysio_clint_mtime; +input sysmap_tcipif_cmplt; +input [31 :0] sysmap_tcipif_rdata; +output clic_cpu_int_hv; +output [11 :0] clic_cpu_int_id; +output [7 :0] clic_cpu_int_il; +output [1 :0] clic_cpu_int_priv; +output [31 :0] tcip_cp0_clic_base; +output tcipif_bmu_dbus_acc_err; +output [31 :0] tcipif_bmu_dbus_data; +output tcipif_bmu_dbus_grnt; +output tcipif_bmu_dbus_trans_cmplt; +output tcipif_bmu_ibus_acc_err; +output [31 :0] tcipif_bmu_ibus_data; +output tcipif_bmu_ibus_grnt; +output tcipif_bmu_ibus_trans_cmplt; +output [15 :0] tcipif_sysmap_addr; +output tcipif_sysmap_sel; +output [31 :0] tcipif_sysmap_wdata; +output tcipif_sysmap_write; + +// &Regs; @24 + +// &Wires; @25 +wire bmu_tcipif_dbus_acc_deny; +wire [31 :0] bmu_tcipif_dbus_addr; +wire bmu_tcipif_dbus_req; +wire bmu_tcipif_dbus_req_dp; +wire [1 :0] bmu_tcipif_dbus_size; +wire bmu_tcipif_dbus_supv_mode; +wire [31 :0] bmu_tcipif_dbus_wdata; +wire bmu_tcipif_dbus_write; +wire bmu_tcipif_ibus_acc_deny; +wire [31 :0] bmu_tcipif_ibus_addr; +wire bmu_tcipif_ibus_req; +wire bmu_tcipif_ibus_req_dp; +wire [1 :0] bmu_tcipif_ibus_size; +wire bmu_tcipif_ibus_supv_mode; +wire [31 :0] bmu_tcipif_ibus_wdata; +wire bmu_tcipif_ibus_write; +wire clic_cpu_int_hv; +wire [11 :0] clic_cpu_int_id; +wire [7 :0] clic_cpu_int_il; +wire [1 :0] clic_cpu_int_priv; +wire clic_tcipif_cmplt; +wire [31 :0] clic_tcipif_rdata; +wire clint_cpu_me_int; +wire clint_cpu_ms_int; +wire clint_cpu_mt_int; +wire clint_tcipif_cmplt; +wire [31 :0] clint_tcipif_rdata; +wire cp0_biu_icg_en; +wire [1 :0] cp0_yy_priv_mode; +wire [11 :0] cpu_clic_curid; +wire cpu_clic_int_exit; +wire cpurst_b; +wire forever_cpuclk; +wire ifu_clic_warm_up; +wire [127:0] pad_clic_int_vld; +wire [31 :0] pad_cpu_tcip_base; +wire pad_yy_dft_clk_rst_b; +wire pad_yy_icg_scan_en; +wire pad_yy_scan_mode; +wire rtu_yy_xx_dbgon; +wire sysio_clint_me_int; +wire [63 :0] sysio_clint_mtime; +wire sysmap_tcipif_cmplt; +wire [31 :0] sysmap_tcipif_rdata; +wire [31 :0] tcip_cp0_clic_base; +wire tcipif_bmu_dbus_acc_err; +wire [31 :0] tcipif_bmu_dbus_data; +wire tcipif_bmu_dbus_grnt; +wire tcipif_bmu_dbus_trans_cmplt; +wire tcipif_bmu_ibus_acc_err; +wire [31 :0] tcipif_bmu_ibus_data; +wire tcipif_bmu_ibus_grnt; +wire tcipif_bmu_ibus_trans_cmplt; +wire tcipif_clic_sel; +wire [1 :0] tcipif_clic_size; +wire tcipif_clint_sel; +wire [15 :0] tcipif_sysmap_addr; +wire tcipif_sysmap_sel; +wire [31 :0] tcipif_sysmap_wdata; +wire tcipif_sysmap_write; +wire [15 :0] tcipif_xx_addr; +wire [31 :0] tcipif_xx_wdata; +wire tcipif_xx_write; + + +// &Instance("pa_tcipif_func","x_pa_tcipif_func"); @31 +//--------------------------------------------------------- +// TCIPIF Connecting with BMU +//--------------------------------------------------------- +// &Instance("pa_tcipif_behavior_bus","x_pa_tcipif_dbus"); @36 +pa_tcipif_behavior_bus x_pa_tcipif_dbus ( + .bmu_tcipif_dbus_acc_deny (bmu_tcipif_dbus_acc_deny ), + .bmu_tcipif_dbus_addr (bmu_tcipif_dbus_addr ), + .bmu_tcipif_dbus_req (bmu_tcipif_dbus_req ), + .bmu_tcipif_dbus_req_dp (bmu_tcipif_dbus_req_dp ), + .bmu_tcipif_dbus_size (bmu_tcipif_dbus_size ), + .bmu_tcipif_dbus_supv_mode (bmu_tcipif_dbus_supv_mode ), + .bmu_tcipif_dbus_wdata (bmu_tcipif_dbus_wdata ), + .bmu_tcipif_dbus_write (bmu_tcipif_dbus_write ), + .clic_tcipif_cmplt (clic_tcipif_cmplt ), + .clic_tcipif_rdata (clic_tcipif_rdata ), + .clint_tcipif_cmplt (clint_tcipif_cmplt ), + .clint_tcipif_rdata (clint_tcipif_rdata ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_cpu_tcip_base (pad_cpu_tcip_base ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .rtu_yy_xx_dbgon (rtu_yy_xx_dbgon ), + .sysmap_tcipif_cmplt (sysmap_tcipif_cmplt ), + .sysmap_tcipif_rdata (sysmap_tcipif_rdata ), + .tcip_cp0_clic_base (tcip_cp0_clic_base ), + .tcipif_bmu_dbus_acc_err (tcipif_bmu_dbus_acc_err ), + .tcipif_bmu_dbus_data (tcipif_bmu_dbus_data ), + .tcipif_bmu_dbus_grnt (tcipif_bmu_dbus_grnt ), + .tcipif_bmu_dbus_trans_cmplt (tcipif_bmu_dbus_trans_cmplt), + .tcipif_clic_sel (tcipif_clic_sel ), + .tcipif_clic_size (tcipif_clic_size ), + .tcipif_clint_sel (tcipif_clint_sel ), + .tcipif_sysmap_sel (tcipif_sysmap_sel ), + .tcipif_xx_addr (tcipif_xx_addr ), + .tcipif_xx_wdata (tcipif_xx_wdata ), + .tcipif_xx_write (tcipif_xx_write ) +); + +// &Instance("pa_tcipif_dummy_bus","x_pa_tcipif_ibus"); @37 +pa_tcipif_dummy_bus x_pa_tcipif_ibus ( + .bmu_tcipif_ibus_acc_deny (bmu_tcipif_ibus_acc_deny ), + .bmu_tcipif_ibus_addr (bmu_tcipif_ibus_addr ), + .bmu_tcipif_ibus_req (bmu_tcipif_ibus_req ), + .bmu_tcipif_ibus_req_dp (bmu_tcipif_ibus_req_dp ), + .bmu_tcipif_ibus_size (bmu_tcipif_ibus_size ), + .bmu_tcipif_ibus_supv_mode (bmu_tcipif_ibus_supv_mode ), + .bmu_tcipif_ibus_wdata (bmu_tcipif_ibus_wdata ), + .bmu_tcipif_ibus_write (bmu_tcipif_ibus_write ), + .cp0_biu_icg_en (cp0_biu_icg_en ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .tcipif_bmu_ibus_acc_err (tcipif_bmu_ibus_acc_err ), + .tcipif_bmu_ibus_data (tcipif_bmu_ibus_data ), + .tcipif_bmu_ibus_grnt (tcipif_bmu_ibus_grnt ), + .tcipif_bmu_ibus_trans_cmplt (tcipif_bmu_ibus_trans_cmplt) +); + + +//--------------------------------------------------------- +// TCIPIF Connecting with Off-core IP +//--------------------------------------------------------- + +//-------------------------------------- +// Instance Core-Local Interrupt module +//-------------------------------------- +// &Instance("pa_clint_top"); @47 +pa_clint_top x_pa_clint_top ( + .clint_cpu_me_int (clint_cpu_me_int ), + .clint_cpu_ms_int (clint_cpu_ms_int ), + .clint_cpu_mt_int (clint_cpu_mt_int ), + .clint_tcipif_cmplt (clint_tcipif_cmplt), + .clint_tcipif_rdata (clint_tcipif_rdata), + .cpu_clint_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .sysio_clint_me_int (sysio_clint_me_int), + .sysio_clint_mtime (sysio_clint_mtime ), + .tcipif_clint_addr (tcipif_xx_addr ), + .tcipif_clint_sel (tcipif_clint_sel ), + .tcipif_clint_wdata (tcipif_xx_wdata ), + .tcipif_clint_write (tcipif_xx_write ) +); + +// &Connect( @48 +// .tcipif_clint_addr (tcipif_xx_addr ), @49 +// .tcipif_clint_wdata (tcipif_xx_wdata ), @50 +// .tcipif_clint_write (tcipif_xx_write ), @51 +// .cpu_clint_mode (cp0_yy_priv_mode ), @52 +// ); @53 + +//-------------------------------------- +// Instance interrupt controller module +//-------------------------------------- +// &Instance("pa_clic_top"); @59 +pa_clic_top x_pa_clic_top ( + .clic_cpu_int_hv (clic_cpu_int_hv ), + .clic_cpu_int_id (clic_cpu_int_id ), + .clic_cpu_int_il (clic_cpu_int_il ), + .clic_cpu_int_priv (clic_cpu_int_priv ), + .clic_tcipif_cmplt (clic_tcipif_cmplt ), + .clic_tcipif_rdata (clic_tcipif_rdata ), + .clint_cpu_me_int (clint_cpu_me_int ), + .clint_cpu_ms_int (clint_cpu_ms_int ), + .clint_cpu_mt_int (clint_cpu_mt_int ), + .cpu_clic_curid (cpu_clic_curid ), + .cpu_clic_int_exit (cpu_clic_int_exit ), + .cpu_clic_mode (cp0_yy_priv_mode ), + .cpurst_b (cpurst_b ), + .forever_cpuclk (forever_cpuclk ), + .ifu_clic_warm_up (ifu_clic_warm_up ), + .pad_clic_int_vld (pad_clic_int_vld ), + .pad_yy_dft_clk_rst_b (pad_yy_dft_clk_rst_b), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .tcipif_clic_addr (tcipif_xx_addr ), + .tcipif_clic_sel (tcipif_clic_sel ), + .tcipif_clic_size (tcipif_clic_size ), + .tcipif_clic_wdata (tcipif_xx_wdata ), + .tcipif_clic_write (tcipif_xx_write ) +); + +// &Connect( @60 +// .tcipif_clic_addr (tcipif_xx_addr ), @61 +// .tcipif_clic_wdata (tcipif_xx_wdata ), @62 +// .tcipif_clic_write (tcipif_xx_write ), @63 +// .cpu_clic_mode (cp0_yy_priv_mode), @64 +// ); @65 + +// &Connect( @68 +// .clic_pad_int_sec (clic_cpu_int_sec), @69 +// ); @70 + + +assign tcipif_sysmap_addr[15:0] = tcipif_xx_addr[15:0]; +assign tcipif_sysmap_write = tcipif_xx_write; +assign tcipif_sysmap_wdata[31:0] = tcipif_xx_wdata[31:0]; + +// &ModuleEnd; @81 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/common/tdt_gated_clk_cell.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/common/tdt_gated_clk_cell.v new file mode 100644 index 0000000000000000000000000000000000000000..e52f2454d1d2a25f528a6bd3e2a30fac8406aa9f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/common/tdt_gated_clk_cell.v @@ -0,0 +1,115 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module tdt_gated_clk_cell( + clk_in, + global_en, + module_en, + local_en, + external_en, + pad_yy_icg_scan_en, + clk_out +); + +input clk_in; +input global_en; +input module_en; +input local_en; +input external_en; +input pad_yy_icg_scan_en; +output clk_out; + +wire clk_en_bf_latch; +wire SE; + +assign clk_en_bf_latch = (global_en && (module_en || local_en)) || external_en ; + +// SE driven from primary input, held constant +assign SE = pad_yy_icg_scan_en; + +`ifdef TDT_GATED_CELL +tdt_gated_cell x_tdt_gated_cell( + .clk_in (clk_in), + .external_en (clk_en_bf_latch), + .SE (SE), + .clk_out (clk_out) + ); +//`ifdef TDT_SMIC +// `ifdef TDT_PROCESS55LL +//HVT_CLKLANQHDV8 x_gated_clk_cell( +//.CK(clk_in), +// `endif +//.TE(SE), +//.E(clk_en_bf_latch), +//.Q(clk_out)); +//`endif +//`ifdef TDT_TSMC +// `ifdef TDT_PROCESS40LP +//CKLNQD1BWP x_gated_clk_cell( +//.CP(clk_in), +//.TE(SE), +//.E(clk_en_bf_latch), +//.Q(clk_out)); +// `endif +// `ifdef TDT_PROCESS28HPC +// CKLNQD8BWP35P140 x_gated_clk_cell ( +// .CP (clk_in), +// .TE (SE), +// .E (clk_en_bf_latch), +// .Q (clk_out) +// ); +// `endif +//`endif +//`ifdef TDT_GSMC +// `ifdef TDT_PROCESS130 +//CLKGTPHD8X x_gated_clk_cell( +//.CK(clk_in), +// `endif +//.TE(SE), +//.E(clk_en_bf_latch), +//.Z(clk_out)); +//`endif +// +//`ifdef TDT_UMC +// `ifdef TDT_PROCESS28HDE +// PREICG_X4B_A9PP140ZTR_C30 x_gated_clk_cell ( +// .CK(clk_in), +// .SE(SE), +// .E(clk_en_bf_latch), +// .ECK(clk_out) +// ); +// `endif +// `ifdef TDT_PROCESS22HDE +// PREICG_X4B_A9PP140ZTS_C30 x_gated_clk_cell ( +// .CK(clk_in), +// .SE(SE), +// .E(clk_en_bf_latch), +// .ECK(clk_out) +// ); +// +// `endif +//`endif +`else +//STN_CKGTPLT_V5_1 x_gated_clk_cell ( +// .CK (clk_in), +// .SE (SE), +// .EN (clk_en_bf_latch), +// .Q (clk_out) +//); +assign clk_out = clk_in; +`endif + + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_apb_master.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_apb_master.v new file mode 100644 index 0000000000000000000000000000000000000000..7da890564ebcc3e9a5117ec704589235e86c42d7 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_apb_master.v @@ -0,0 +1,267 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_apb_master +#( + parameter PADDR_HIGH_WIDTH = 6, + parameter PADDR_LOW_WIDTH = 12, + parameter DTM_ADDR_WIDTH = PADDR_HIGH_WIDTH+PADDR_LOW_WIDTH, + parameter PADDR_WIDTH = PADDR_HIGH_WIDTH+PADDR_LOW_WIDTH+2, + parameter SLAVE_NUM = 1 +) +( + input tck, + input trst_b, + input cmd_vld, + input [DTM_ADDR_WIDTH-1:0] addr, + input [1:0] wr_flg, + input [31:0] wdata, + input dmihardreset, + output [31:0] rdata, + output apb_wr_ready, + + input pclk, + input preset_b, + output reg psel, + output reg penable, + output reg pwrite, + output reg [PADDR_WIDTH-1:0] paddr, + output reg [31:0] pwdata, + input pready, + input [31:0] prdata, + input pslverr, + + input dm_apb_clk_en, + input pad_icg_scan_en +); + //gated clock out + wire apb_pclk; + + //input sync + wire cmd_vld_sync; + wire dmihardreset_sync; + + tdt_dmi_pulse_sync x_tdt_dmi_pulse_cmd_vld ( + .src_clk (tck), + .dst_clk (pclk), + .src_rst_b (trst_b), + .dst_rst_b (preset_b), + .src_pulse (cmd_vld), + .dst_pulse (cmd_vld_sync) + ); + + tdt_dmi_pulse_sync x_tdt_dmi_pulse_dmihardreset ( + .src_clk (tck), + .dst_clk (pclk), + .src_rst_b (trst_b), + .dst_rst_b (preset_b), + .src_pulse (dmihardreset), + .dst_pulse (dmihardreset_sync) + ); + reg apb_wr_ready_pclk_d1; + reg [31:0] prdata_smp; + + //input sample + reg [1:0] wr_flg_smp; + reg [DTM_ADDR_WIDTH-1:0] addr_smp; + reg [31:0] wdata_smp; + + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + begin + wr_flg_smp[1:0] <= 2'b0; + addr_smp[DTM_ADDR_WIDTH-1:0] <= {DTM_ADDR_WIDTH{1'b0}}; + wdata_smp[31:0] <= 32'b0; + end + else if(dmihardreset_sync) + begin + wr_flg_smp[1:0] <= 2'b0; + addr_smp[DTM_ADDR_WIDTH-1:0] <= {DTM_ADDR_WIDTH{1'b0}}; + wdata_smp[31:0] <= 32'b0; + end + else if(cmd_vld_sync) + begin + wr_flg_smp[1:0] <= wr_flg[1:0]; + addr_smp[DTM_ADDR_WIDTH-1:0] <= addr[DTM_ADDR_WIDTH-1:0]; + wdata_smp[31:0] <= wdata[31:0]; + end + end + + //APB MASTER FSM + localparam IDLE = 2'b00; + localparam APB_SETUP = 2'b01; + localparam APB_ACCESS = 2'b10; + reg [1:0] p_state; + reg [1:0] n_state; + wire addr_is_legal; + wire trans_req; + reg cmd_vld_sync_dly; + + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + cmd_vld_sync_dly <= 1'b0; + else if(dmihardreset_sync) + cmd_vld_sync_dly <= 1'b0; + else + cmd_vld_sync_dly <= cmd_vld_sync; + end + + `ifdef TDT_DMI_SINGLE_SLAVE + assign addr_is_legal = 1'b1; + `else + assign addr_is_legal = addr[DTM_ADDR_WIDTH-1:DTM_ADDR_WIDTH-PADDR_HIGH_WIDTH] < ($unsigned(SLAVE_NUM) & {PADDR_HIGH_WIDTH+1{1'b1}}); + `endif + + assign trans_req = cmd_vld_sync_dly & (wr_flg_smp[0] ^ wr_flg_smp[1]) & addr_is_legal; + + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + p_state[1:0] <= 2'b00; + else if(dmihardreset_sync) + p_state[1:0] <= 2'b00; + else + p_state[1:0] <= n_state[1:0]; + end + + always @ (p_state[1:0] or + pready or + trans_req) + begin + case(p_state[1:0]) + IDLE : + if(trans_req) + n_state[1:0] = APB_SETUP; + else + n_state[1:0] = IDLE; + APB_SETUP : + n_state[1:0] = APB_ACCESS; + APB_ACCESS : + if(pready && trans_req) + n_state[1:0] = APB_SETUP; + else if(pready && !trans_req) + n_state[1:0] = IDLE; + else + n_state[1:0] = APB_ACCESS; + default : + n_state[1:0] = IDLE; + endcase + end + + //psel reg out + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + psel <= 1'b0; + else if(dmihardreset_sync) + psel <= 1'b0; + else if(p_state[1:0] == IDLE && trans_req) + psel <= 1'b1; + else if(p_state[1:0] == APB_ACCESS && pready && !trans_req)//miss pready at first + psel <= 1'b0; + end + + //penable reg out + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + penable <= 1'b0; + else if(dmihardreset_sync) + penable <= 1'b0; + else if(p_state[1:0] == APB_SETUP) + penable <= 1'b1; + else if(p_state[1:0] == APB_ACCESS && pready) + penable <= 1'b0; + end + + //pwrite, paddr, pwdata reg out + always @ (posedge apb_pclk or negedge preset_b) + begin + if(!preset_b) + begin + pwrite <= 1'b0; + paddr[PADDR_WIDTH-1:0] <= {PADDR_WIDTH{1'b0}}; + pwdata[31:0] <= 32'b0; + end + else if(dmihardreset_sync) + begin + pwrite <= 1'b0; + paddr[PADDR_WIDTH-1:0] <= {PADDR_WIDTH{1'b0}}; + pwdata[31:0] <= 32'b0; + end + else if(trans_req) + begin + pwrite <= wr_flg_smp[1]; + paddr[PADDR_WIDTH-1:0] <= {addr_smp[DTM_ADDR_WIDTH-1:0], 2'b0}; + pwdata[31:0] <= wdata_smp[31:0]; + end + end + + //response modify + wire apb_wr_ready_pclk; + + assign apb_wr_ready_pclk = pready & penable; + + always @ (posedge apb_pclk or negedge preset_b) begin + if(!preset_b) + apb_wr_ready_pclk_d1 <= 1'b0; + else if(dmihardreset_sync) + apb_wr_ready_pclk_d1 <= 1'b0; + else if (apb_wr_ready_pclk_d1) + apb_wr_ready_pclk_d1 <= 1'b0; + else if (apb_wr_ready_pclk) + apb_wr_ready_pclk_d1 <= 1'b1; + + end + + always @ (posedge apb_pclk or negedge preset_b) begin + if(!preset_b) + prdata_smp[31:0] <= 32'b0; + else if(dmihardreset_sync) + prdata_smp[31:0] <= 32'b0; + else if (apb_wr_ready_pclk) + prdata_smp[31:0] <= prdata[31:0]; + + end + + //output sync + tdt_dmi_pulse_sync x_tdt_dmi_pulse_sync_1( + .src_clk (pclk), + .dst_clk (tck), + .src_rst_b (preset_b), + .dst_rst_b (trst_b), + .src_pulse (apb_wr_ready_pclk_d1), + .dst_pulse (apb_wr_ready) + ); + + //output rdata + assign rdata[31:0] = prdata_smp[31:0]; + + //clock gating enable + wire apb_master_clk_en; + assign apb_master_clk_en = cmd_vld_sync | cmd_vld_sync_dly | psel | apb_wr_ready_pclk_d1 | dmihardreset_sync; + + tdt_gated_clk_cell x_tdt_gated_clk_cell( + .clk_in (pclk), + .global_en (1'b1), + .module_en (dm_apb_clk_en), + .local_en (apb_master_clk_en), + .external_en (1'b0), + .pad_yy_icg_scan_en (pad_icg_scan_en), + .clk_out (apb_pclk) + ); + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dm.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dm.v new file mode 100644 index 0000000000000000000000000000000000000000..a4b7590539a6cde4d6d5249034228d38c9fc4a82 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dm.v @@ -0,0 +1,3517 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dm #( + parameter APB_AW = 12, + parameter CORE_NUM = `TDT_DM_CORE_NUM, + parameter EXTHALTTRI_NUM = 4, + parameter EXTRESUMETRI_NUM = 4, + parameter PB_SIZE = 15, + parameter IMP_EBREAK = 1, + parameter CORE_MAX_XLEN = `TDT_DM_CORE_MAX_XLEN, + parameter [31:0] NEXTDM_BASEADDR = 32'h0, + parameter SBAW = 40, + parameter [CORE_NUM*4-1:0] ALLCORE_NSCRATCH = `TDT_DM_ALLCORE_NSCRATCH, + parameter [CORE_NUM*4-1:0] ALLCORE_ISA = `TDT_DM_ALLCORE_ISA +)( + input pclk, + input preset_b, + input forever_cpuclk, + input ciu_rst_b, + input sys_bus_clk_en, + input dm_pclk, + input [APB_AW-1:0] dm_paddr, + input dm_pwrite, + input dm_psel, + input dm_penable, + input [31:0] dm_pwdata, + output reg [31:0] dm_prdata, + output reg dm_pready, + output dm_pslverr, + + input pad_icg_scan_en, + + output dm_pclk_en, + output reg ndmresetn, +`ifdef TDT_DM_SINGLE_CORE + output reg dm_core_rstn, + output reg dm_core_halt_req_o, + output reg dm_core_async_halt_req_o, + output reg dm_core_resume_req_o, + output reg dm_core_halt_on_reset_o, + output reg [1:0] dm_core_halt_req_cause_o, + + input core_dm_halted_i, + input core_dm_havereset_i, + output reg dm_core_ack_havereset_o, + input core_dm_unavail_i, +`else + output reg [CORE_NUM-1:0] dm_core_rstn, + output reg [CORE_NUM-1:0] dm_core_halt_req_o, + output reg [CORE_NUM-1:0] dm_core_async_halt_req_o, + output reg [CORE_NUM-1:0] dm_core_resume_req_o, + output reg [CORE_NUM-1:0] dm_core_halt_on_reset_o, + output reg [CORE_NUM*2-1:0] dm_core_halt_req_cause_o, + + input [CORE_NUM-1:0] core_dm_halted_i, + input [CORE_NUM-1:0] core_dm_havereset_i, + output reg [CORE_NUM-1:0] dm_core_ack_havereset_o, + input [CORE_NUM-1:0] core_dm_unavail_i, +`endif + +`ifdef TDT_DM_EXT_TRIGGER_EN + input [EXTHALTTRI_NUM-1:0] pad_dm_halt_req_i, + output reg [EXTHALTTRI_NUM-1:0] dm_pad_halt_req_o, + + input [EXTRESUMETRI_NUM-1:0] pad_dm_resume_req_i, + output reg [EXTRESUMETRI_NUM-1:0] dm_pad_resume_req_o, +`endif + + output [31:0] dm_core_itr_o, +`ifdef TDT_DM_SINGLE_CORE + output dm_core_itr_vld_o, + input core_dm_itr_done_i, + input core_dm_exce_retire_i, +`else + output [CORE_NUM-1:0] dm_core_itr_vld_o, + input [CORE_NUM-1:0] core_dm_itr_done_i, + input [CORE_NUM-1:0] core_dm_exce_retire_i, +`endif + +`ifdef TDT_DM_SINGLE_CORE + output reg dm_core_wr_vld, +`else + output reg [CORE_NUM-1:0] dm_core_wr_vld, +`endif + output reg [1:0] dm_core_wr_flg, + output [CORE_MAX_XLEN-1:0] dm_core_wdata, +`ifdef TDT_DM_SINGLE_CORE + input core_dm_wr_ready, +`else + input [CORE_NUM-1:0] core_dm_wr_ready, +`endif + input [CORE_MAX_XLEN*CORE_NUM-1:0] core_dm_rx_data + +`ifdef TDT_DM_SBA +`ifdef TDT_DM_SBA_AXI + , + output [3:0] dm_pad_awid, + output [SBAW-1:0] dm_pad_awaddr, + output [3:0] dm_pad_awlen, + output [2:0] dm_pad_awsize, + output dm_pad_awvalid, + input pad_dm_awready, + output [`TDT_DM_SBA_DW-1:0] dm_pad_wdata, + output dm_pad_wvalid, + output dm_pad_wlast, + output [`TDT_DM_SBA_BW-1:0] dm_pad_wstrb, + input pad_dm_wready, + output dm_pad_bready, + input [3:0] pad_dm_bid, + input [1:0] pad_dm_bresp, + input pad_dm_bvalid, + output [3:0] dm_pad_arid, + output [SBAW-1:0] dm_pad_araddr, + output [3:0] dm_pad_arlen, + output [2:0] dm_pad_arsize, + output dm_pad_arvalid, + input pad_dm_arready, + input [3:0] pad_dm_rid, + input [`TDT_DM_SBA_DW-1:0] pad_dm_rdata, + input pad_dm_rvalid, + input pad_dm_rlast, + input [1:0] pad_dm_rresp, + output dm_pad_rready, + output [1:0] dm_pad_awburst, + output [3:0] dm_pad_awcache, + output dm_pad_awlock, + output [2:0] dm_pad_awprot, + output [1:0] dm_pad_arburst, + output [3:0] dm_pad_arcache, + output dm_pad_arlock, + output [2:0] dm_pad_arprot + //output [3:0] dm_pad_wid +`endif +`ifdef TDT_DM_SBA_AHB + , + output [3:0] dm_pad_hprot, + output dm_pad_hmastlock, + output [1:0] dm_pad_htrans, + output [SBAW-1:0] dm_pad_haddr, + output dm_pad_hwrite, + output [2:0] dm_pad_hburst, + output [2:0] dm_pad_hsize, + output [`TDT_DM_SBA_DW-1:0] dm_pad_hwdata, + input [`TDT_DM_SBA_DW-1:0] pad_dm_hrdata, + input pad_dm_hready, + input pad_dm_hresp +`endif +`endif +); + + //========================================================== + // local parameter define + //========================================================== +`ifdef TDT_DM_SINGLE_CORE + localparam CORE_NUM_W = 1; +`else + localparam CORE_NUM_W = $clog2(CORE_NUM); +`endif + localparam [APB_AW-1-2:0] OFFSET_DATA0 = 10'h04; + localparam [APB_AW-1-2:0] OFFSET_DATA1 = 10'h05; + localparam [APB_AW-1-2:0] OFFSET_DATA2 = 10'h06; + localparam [APB_AW-1-2:0] OFFSET_DATA3 = 10'h07; + localparam [APB_AW-1-2:0] OFFSET_DATA4 = 10'h08; + localparam [APB_AW-1-2:0] OFFSET_DATA5 = 10'h09; + localparam [APB_AW-1-2:0] OFFSET_DATA6 = 10'h0a; + localparam [APB_AW-1-2:0] OFFSET_DATA7 = 10'h0b; + localparam [APB_AW-1-2:0] OFFSET_DATA8 = 10'h0c; + localparam [APB_AW-1-2:0] OFFSET_DATA9 = 10'h0d; + localparam [APB_AW-1-2:0] OFFSET_DATA10 = 10'h0e; + localparam [APB_AW-1-2:0] OFFSET_DATA11 = 10'h0f; + localparam [APB_AW-1-2:0] OFFSET_DMCONTROL = 10'h10; + localparam [APB_AW-1-2:0] OFFSET_DMSTATUS = 10'h11; + localparam [APB_AW-1-2:0] OFFSET_HARTINFO = 10'h12; + localparam [APB_AW-1-2:0] OFFSET_HAWINDOW = 10'h15; + localparam [APB_AW-1-2:0] OFFSET_ABSTRACTCS = 10'h16; + localparam [APB_AW-1-2:0] OFFSET_COMMAND = 10'h17; + localparam [APB_AW-1-2:0] OFFSET_ABSTRACTAUTO = 10'h18; + localparam [APB_AW-1-2:0] OFFSET_NEXTDM = 10'h1d; + localparam [APB_AW-1-2:0] OFFSET_PB0 = 10'h20; + localparam [APB_AW-1-2:0] OFFSET_PB1 = 10'h21; + localparam [APB_AW-1-2:0] OFFSET_PB2 = 10'h22; + localparam [APB_AW-1-2:0] OFFSET_PB3 = 10'h23; + localparam [APB_AW-1-2:0] OFFSET_PB4 = 10'h24; + localparam [APB_AW-1-2:0] OFFSET_PB5 = 10'h25; + localparam [APB_AW-1-2:0] OFFSET_PB6 = 10'h26; + localparam [APB_AW-1-2:0] OFFSET_PB7 = 10'h27; + localparam [APB_AW-1-2:0] OFFSET_PB8 = 10'h28; + localparam [APB_AW-1-2:0] OFFSET_PB9 = 10'h29; + localparam [APB_AW-1-2:0] OFFSET_PB10 = 10'h2a; + localparam [APB_AW-1-2:0] OFFSET_PB11 = 10'h2b; + localparam [APB_AW-1-2:0] OFFSET_PB12 = 10'h2c; + localparam [APB_AW-1-2:0] OFFSET_PB13 = 10'h2d; + localparam [APB_AW-1-2:0] OFFSET_PB14 = 10'h2e; + localparam [APB_AW-1-2:0] OFFSET_PB15 = 10'h2f; + localparam [APB_AW-1-2:0] OFFSET_DMCS2 = 10'h32; + localparam [APB_AW-1-2:0] OFFSET_SBCS = 10'h38; + localparam [APB_AW-1-2:0] OFFSET_SBADDR0 = 10'h39; + localparam [APB_AW-1-2:0] OFFSET_SBADDR1 = 10'h3a; + localparam [APB_AW-1-2:0] OFFSET_SBDATA0 = 10'h3c; + localparam [APB_AW-1-2:0] OFFSET_SBDATA1 = 10'h3d; + localparam [APB_AW-1-2:0] OFFSET_SBDATA2 = 10'h3e; + localparam [APB_AW-1-2:0] OFFSET_SBDATA3 = 10'h3f; + localparam [APB_AW-1-2:0] OFFSET_HARTSUM0 = 10'h40; + localparam [APB_AW-1-2:0] OFFSET_ITR = 10'h1f; + localparam [APB_AW-1-2:0] OFFSET_CUSCS = 10'h70; + localparam [APB_AW-1-2:0] OFFSET_CUSCMD = 10'h71; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF0 = 10'h72; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF1 = 10'h73; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF2 = 10'h74; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF3 = 10'h75; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF4 = 10'h76; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF5 = 10'h77; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF6 = 10'h78; + localparam [APB_AW-1-2:0] OFFSET_CUSBUF7 = 10'h79; + localparam [APB_AW-1-2:0] OFFSET_COMPID = 10'h7f; + + localparam [11:0] TDT_DM_THEAD_JEP106_ID = 12'b1011_011_0111_1; + localparam [3:0] TDT_DM_VERSION = 4'h2; + localparam [11:0] TDT_DM_COMP_TYPE = 12'h0; + localparam [7:0] TDT_DM_COMP_VERSION = 8'h1; + localparam [11:0] TDT_DM_RV_DSCR0_ADDR = 12'h7b2; + localparam [11:0] TDT_DM_RV_DSCR1_ADDR = 12'h7b3; + + localparam [6:0] TDT_DM_RV_SYSTEM_OPCODE = 7'h73; + localparam [2:0] TDT_DM_RV_CSRRW_FUNC3 = 3'h1; + localparam [2:0] TDT_DM_RV_CSRRC_FUNC3 = 3'h3; + localparam [4:0] TDT_DM_RV_ZERO_GPR = 5'h0; + localparam [31:0] TDT_DM_RV_EBREAK = 32'b000000000001_00000_000_00000_1110011; + localparam [31:0] TDT_DM_RV_CEBREAK = 32'b000000000000_00001_001_00000_0000010; + + localparam [3:0] REGACC_IDLE = 4'h0; + localparam [3:0] REGACC_WDSC0 = 4'h1; + localparam [3:0] REGACC_RDSC0 = 4'h2; + localparam [3:0] REGACC_X6_2_DSC1 = 4'h3; + localparam [3:0] REGACC_DSC1_2_X6 = 4'h4; + localparam [3:0] REGACC_DSC0_2_G = 4'h5; + localparam [3:0] REGACC_G_2_DSC0 = 4'h6; + localparam [3:0] REGACC_C_2_X6 = 4'h7; + localparam [3:0] REGACC_X6_2_C = 4'h8; + localparam [3:0] REGACC_X6_2_DSC0 = 4'h9; + localparam [3:0] REGACC_DSC0_2_X6 = 4'ha; + //========================================================== + // wires and registers define + //========================================================== +`ifdef TDT_DM_SINGLE_CORE + wire core_dm_itr_done_pad; + wire core_dm_exce_retire_pad; + wire itr_vld_pad; + wire core_dm_wr_ready_pad; + reg core_dm_unavail_sync1; + reg core_dm_unavail_sync2; +`else + wire [CORE_NUM-1:0] core_dm_itr_done_pad; + wire [CORE_NUM-1:0] core_dm_exce_retire_pad; + wire [CORE_NUM-1:0] itr_vld_pad; + wire [CORE_NUM-1:0] core_dm_wr_ready_pad; + reg [CORE_NUM-1:0] core_dm_unavail_sync1; + reg [CORE_NUM-1:0] core_dm_unavail_sync2; +`endif + wire core_dm_itr_done_mux_pre; + wire core_dm_exce_retire_mux_pre; + reg core_dm_itr_done_mux; + reg core_dm_exce_retire_mux; + + wire itr_vld_mux; + wire core_dm_wr_ready_mux; + reg [3:0] sel_core_isa; + wire [CORE_NUM*4-1:0] all_core_isa; + wire [31:0] compid; + wire pb_sel; + wire intra_sel; + wire apb_access; + wire dm_intra_psel; + wire dm_intra_access; + wire dm_intra_apbw; + wire dm_intra_apbr; + wire cmd_busy_set; + wire haltreq_raise; + wire haltreq_fall; + wire aarsize_err; + +`ifdef TDT_DM_SINGLE_CORE + reg core_dm_halted_d; + wire core_dm_halted_req; + wire core_dm_resume_req; + wire core_dm_running; +`else + reg [CORE_NUM-1:0] core_dm_halted_d; + wire [CORE_NUM-1:0] core_dm_halted_req; + wire [CORE_NUM-1:0] core_dm_resume_req; + wire [CORE_NUM-1:0] core_dm_running; +`endif + wire [31:0] abstractauto; + wire [31:0] nextdm; + reg resumereq; + reg hartreset; + reg ackhavereset; + reg hasel; +`ifdef TDT_DM_SINGLE_CORE + reg hartsello; +`else + reg [CORE_NUM_W-1:0] hartsello; +`endif + wire [9:0] hartselhi; + reg setresethaltreq; + reg clrresethaltreq; + reg ndmreset; + wire [31:0] dmcontrol; + reg [31:0] hawindow; +`ifdef TDT_DM_SINGLE_CORE + wire hart_sel; +`else + wire [CORE_NUM-1:0] hart_sel; +`endif + wire impebreak; + wire allhavereset; + wire anyhavereset; +`ifdef TDT_DM_SINGLE_CORE + reg resumeack; +`else + reg [CORE_NUM-1:0] resumeack; +`endif + wire allresumeack; + wire anyresumeack; + wire allnonexistent; + wire anynonexistent; + wire allunavail; + wire anyunavail; + wire allrunning; + wire anyrunning; + wire allhalted; + wire anyhalted; + wire authenticated; + wire authbusy; + wire haresethaltreq; + wire confstrptrvalid; + wire [3:0] version; + wire [31:0] dmstatus; + reg grouptype; + reg [3:0] exttrigger; + reg [3:0] groups; + wire [3:0] read_group; + + reg hgwrite; + reg hgselect; + wire [31:0] dmcs2; + reg itr_send_pb_r; +`ifdef TDT_DM_SINGLE_CORE + wire nor_halt_req; + wire nor_halt_req_clr; + + wire hart_halt_req_en; + wire nor_resume_req; +`else + wire [CORE_NUM-1:0] nor_halt_req; + wire [CORE_NUM-1:0] nor_halt_req_clr; + + wire [CORE_NUM-1:0] hart_halt_req_en; + wire [CORE_NUM-1:0] nor_resume_req; +`endif +`ifdef TDT_DM_GROUP_TRI_EN + wire [3:0] core_read_group; + wire [3:0] ext_read_group; + `ifdef TDT_DM_SINGLE_CORE + reg [3:0] core_haltgp_info; + reg [3:0] core_resumegp_info; + wire harthalt_2_harthalt; + wire hartresume_2_hartresume; + wire gp_hart2hart_halt_req; + wire gp_hart2hart_resume_req; + `else + reg [3:0] core_haltgp_info [0:CORE_NUM-1]; + reg [3:0] core_resumegp_info [0:CORE_NUM-1]; + wire [CORE_NUM*CORE_NUM-1:0] harthalt_2_harthalt; + wire [CORE_NUM*CORE_NUM-1:0] hartresume_2_hartresume; + wire [CORE_NUM-1:0] gp_hart2hart_halt_req; + wire [CORE_NUM-1:0] gp_hart2hart_resume_req; + `endif + reg sel_hart_pend_resume; + reg sel_hart_pend_resume_d; + wire sel_hart_pend_resume_req; +`endif +`ifdef TDT_DM_SINGLE_CORE + wire hart_resume_req_en; +`else + wire [CORE_NUM-1:0] hart_resume_req_en; +`endif + reg [7:0] cmdtype; + reg aarpostincrement; + reg aarpostexec; + reg transfer; + reg write; + reg [15:0] regno; + reg [11:0] autoexecdata; + reg [15:0] autoexecprogbuf; + wire apb_access_pb0; + wire apb_access_pb1; + wire apb_access_pb2; + wire apb_access_pb3; + wire apb_access_pb4; + wire apb_access_pb5; + wire apb_access_pb6; + wire apb_access_pb7; + wire apb_access_pb8; + wire apb_access_pb9; + wire apb_access_pb10; + wire apb_access_pb11; + wire apb_access_pb12; + wire apb_access_pb13; + wire apb_access_pb14; + wire apb_access_pb15; + wire apb_access_data0; + wire apb_access_data1; + wire [15:0] apb_access_pb; + wire [15:0] apb_access_pb_real; + wire [11:0] apb_access_data_real; + wire autoaccen; + reg cmd_start; + reg cmd_work; + reg cmd_done; + reg pb_work; + wire busy; + wire [4:0] progbufsize; + reg [2:0] cmderr; + wire [3:0] datacount; + wire [31:0] abstractcs; + wire access_gpr; + wire access_csr; + wire access_dsc0; + reg [31:0] itr; +`ifdef TDT_DM_SINGLE_CORE + reg itr_vld; +`else + reg [CORE_NUM-1:0] itr_vld; +`endif + reg itr_work; +`ifdef TDT_DM_SINGLE_CORE + reg [CORE_MAX_XLEN-1:0] core_rdata_r; +`else + reg [CORE_MAX_XLEN-1:0] core_rdata_r [0:CORE_NUM-1]; +`endif + wire [CORE_MAX_XLEN-1:0] core_rdata_mux; + reg core_rdata_vld_r; + reg [31:0] data0; + reg [31:0] data1; + wire [31:0] hartsum0; + reg [2:0] cuscmderr; + reg cuscmdbusy; + wire [3:0] cusbufcnt; + wire [15:0] coredebuginfo; + wire [31:0] customcs; + reg [31:0] hartinfo; + wire [4*CORE_NUM-1:0] nscratch_all; + reg ebk_work; + wire [31:0] pb_mux; + reg [3:0] pb_idx; + wire [11:0] vendorid; + wire [11:0] comptype; + wire [7:0] compversion; + reg [31:0] prdata_pre; + reg [3:0] regacc_cur_state; + reg [3:0] regacc_nxt_state; + wire fsm_x6_2_dsc1; + wire fsm_x6_2_dsc0; + wire fsm_x6_2_c; + wire fsm_c_2_x6; + wire fsm_dsc0_2_x6; + wire fsm_dsc1_2_x6; + reg [31:0] progbuf[15:0]; +`ifdef TDT_DM_BUF_MOVE + reg [1:0] src_type; + reg [1:0] dst_type; + reg [3:0] src_reg; + reg [3:0] dst_reg; + reg internal_move_start; + reg [31:0] src_data_mux; + reg [31:0] cusbuf [0:`TDT_DM_CUSTOM_BUF_CNT-1]; + wire [31:0] cusbuf_all [0:7]; +`endif +`ifdef TDT_DM_SBA + reg [4:0] sbaddrplus; + wire [32:0] sbaddr0_plus_pre; + reg [31:0] sbaddr0; + reg [31:0] sbaddr1; + wire [2:0] sbversion; + reg sbbusy; + reg sbbusyerror; + reg sberror_will_be_4; + reg sberror_will_be_3; + reg [2:0] sberror; + wire [6:0] sbasize; + wire [4:0] sbaccess_info; + reg sbreadonaddr; + reg [2:0] sbaccess; + reg sbautoincrement; + reg sbreadondata; + wire [31:0] sbcs; + reg [31:0] sbdata0; + reg [31:0] sbdata1; + reg [31:0] sbdata2; + reg [31:0] sbdata3; + wire [`TDT_DM_SBA_DW-1:0] sba_w_data; + reg sba_wr_flg; + reg sba_wr_vld; + wire [SBAW-1:0] sba_wr_addr; + wire [63:0] sba_wr_addr_pre; + wire [2:0] sba_wr_size; + reg [`TDT_DM_SBA_DW-1:0] sba_rd_data; + reg sba_wr_ready; + wire sba_write; + wire sba_read; + wire sba_write_ignore_unalign; + wire sba_read_ignore_unalign; + reg sba_write_ignore_unalign_f; + reg sba_read_ignore_unalign_f; + reg sba_error; +`endif +`ifdef TDT_DM_EXT_TRIGGER_EN + reg [3:0] exttriin_haltgp_info [EXTHALTTRI_NUM-1:0]; + reg [3:0] exttriin_resumegp_info [EXTRESUMETRI_NUM-1:0]; + reg [3:0] exttriout_haltgp_info [EXTHALTTRI_NUM-1:0]; + reg [3:0] exttriout_resumegp_info [EXTRESUMETRI_NUM-1:0]; + wire [3:0] all_exttri_info [15:0]; + wire [CORE_NUM*EXTHALTTRI_NUM-1:0] harthalt_2_exttrio; + wire [CORE_NUM*EXTHALTTRI_NUM-1:0] exttriihalt_2_hart; + wire [EXTHALTTRI_NUM*EXTHALTTRI_NUM-1:0] exttriihalt_2_exttrio; + wire [CORE_NUM*EXTRESUMETRI_NUM-1:0] hartresume_2_exttrio; + wire [CORE_NUM*EXTRESUMETRI_NUM-1:0] exttriiresume_2_hart; + wire [EXTRESUMETRI_NUM*EXTRESUMETRI_NUM-1:0] exttriiresume_2_exttrio; + `ifdef TDT_DM_SINGLE_CORE + wire gp_exttrii2hart_resume_req; + wire gp_exttrii2hart_halt_req; + `else + wire [CORE_NUM-1:0] gp_exttrii2hart_resume_req; + wire [CORE_NUM-1:0] gp_exttrii2hart_halt_req; + `endif + wire [EXTHALTTRI_NUM-1:0] gp_hart2exttrio_halt_req; + wire [EXTHALTTRI_NUM-1:0] gp_exttrii2exttrio_halt_req; + wire [EXTHALTTRI_NUM-1:0] ext_halt_req_en; + wire [EXTRESUMETRI_NUM-1:0] gp_hart2exttrio_resume_req; + wire [EXTRESUMETRI_NUM-1:0] gp_exttrii2exttrio_resume_req; + wire [EXTRESUMETRI_NUM-1:0] ext_resume_req_en; +`endif + wire apbw_dmctrl; + wire apbw_dmcs2; + wire apbw_abscmd; + wire apbw_abscmdauto; + wire itr_send_pb; +`ifdef TDT_DM_SINGLE_CORE + wire itr_vld_en; +`else + wire [CORE_NUM-1:0] itr_vld_en; +`endif + wire apbw_cuscmd; + wire apbw_sbcs; +`ifdef TDT_DM_SINGLE_CORE + wire dm_core_wr_vld_en; +`else + wire [CORE_NUM-1:0] dm_core_wr_vld_en; +`endif + + wire access_illegal_reg; + wire pb_work_start; + + wire hg_sel_core; + wire hg_sel_exttri; + reg dmactive; + reg dmactive_d1; + wire sync_rst; + //========================================================== + // core info + //========================================================== + + assign all_core_isa[CORE_NUM*4-1:0] = ALLCORE_ISA; + assign nscratch_all[4*CORE_NUM-1:0] = ALLCORE_NSCRATCH; + + genvar i; + `ifdef TDT_DM_GROUP_TRI_EN + genvar j; + `else + `ifdef TDT_DM_EXT_TRIGGER_EN + genvar j; + `endif + `endif + //========================================================== + // apb mini decode + // if access programbuffer, send apb to pb + // if access other regs, send internal + //========================================================== + + assign pb_sel = dm_paddr[APB_AW-1:6] == {{APB_AW-8{1'b0}}, 2'b10}; + assign intra_sel = !pb_sel; + assign apb_access = dm_psel & dm_penable; + assign dm_intra_psel = dm_psel && intra_sel; + assign dm_intra_access = dm_intra_psel && dm_penable; + assign dm_intra_apbw = dm_intra_access && dm_pwrite; + assign dm_intra_apbr = dm_intra_access && !dm_pwrite; + + wire [31:0] pb_zero_value; + assign pb_zero_value[31:0] = 32'h0; + +`ifdef TDT_DM_PB_EN + generate + for (i=0; i= CORE_NUM) || (hasel && (|hawindow[31:CORE_NUM])); + assign allunavail = (hart_sel & core_dm_unavail_sync2) == hart_sel; + assign core_dm_running = ~core_dm_halted_i; + assign allrunning = (hart_sel & core_dm_running & ~core_dm_unavail_sync2) == hart_sel; + assign allhalted = (hart_sel & core_dm_halted_i & ~core_dm_unavail_sync2) == hart_sel; + assign anyresumeack = hart_sel & resumeack; + assign allnonexistent = (~hasel && (hartsello >= CORE_NUM)) || + (hasel && ((hartsello >= CORE_NUM) && (!hawindow[CORE_NUM-1:0]))); + assign anyunavail = hart_sel & core_dm_unavail_sync2; + assign anyrunning = hart_sel & core_dm_running & ~core_dm_unavail_sync2; + assign anyhalted = hart_sel & core_dm_halted_i & ~core_dm_unavail_sync2; +`else + assign allresumeack = (hart_sel[CORE_NUM-1:0] & resumeack[CORE_NUM-1:0]) == hart_sel[CORE_NUM-1:0]; + assign anynonexistent = (hartsello[CORE_NUM_W-1:0] >= CORE_NUM) || (hasel && (|hawindow[31:CORE_NUM])); + assign allunavail = (hart_sel[CORE_NUM-1:0] & core_dm_unavail_sync2[CORE_NUM-1:0]) == hart_sel[CORE_NUM-1:0]; + assign core_dm_running[CORE_NUM-1:0] = ~core_dm_halted_i[CORE_NUM-1:0]; + assign allrunning = (hart_sel[CORE_NUM-1:0] & core_dm_running[CORE_NUM-1:0] & ~core_dm_unavail_sync2[CORE_NUM-1:0]) == hart_sel[CORE_NUM-1:0]; + assign allhalted = (hart_sel[CORE_NUM-1:0] & core_dm_halted_i[CORE_NUM-1:0] & ~core_dm_unavail_sync2[CORE_NUM-1:0]) == hart_sel[CORE_NUM-1:0]; + assign anyresumeack = |(hart_sel[CORE_NUM-1:0] & resumeack[CORE_NUM-1:0]); + assign allnonexistent = (~hasel && (hartsello[CORE_NUM_W-1:0] >= CORE_NUM)) || + (hasel && ((hartsello[CORE_NUM_W-1:0] >= CORE_NUM) && (!(|hawindow[CORE_NUM-1:0])))); + assign anyunavail = |(hart_sel[CORE_NUM-1:0] & core_dm_unavail_sync2[CORE_NUM-1:0]); + assign anyrunning = |(hart_sel[CORE_NUM-1:0] & core_dm_running[CORE_NUM-1:0] & ~core_dm_unavail_sync2[CORE_NUM-1:0]); + assign anyhalted = |(hart_sel[CORE_NUM-1:0] & core_dm_halted_i[CORE_NUM-1:0] & ~core_dm_unavail_sync2[CORE_NUM-1:0]); +`endif + + assign authenticated = 1'b1; //not support authenticated + assign authbusy = 1'b0; //not support authenticated + assign haresethaltreq = 1'b1; //support hart on reset + assign confstrptrvalid = 1'b0; //not support + assign version[3:0] = TDT_DM_VERSION; + + assign dmstatus[31:0] = {9'h0, impebreak, 2'b0, allhavereset, anyhavereset, + allresumeack, anyresumeack, allnonexistent, anynonexistent, + allunavail, anyunavail, allrunning, anyrunning, allhalted, + anyhalted, authenticated, authbusy,haresethaltreq, + confstrptrvalid, version[3:0]}; + + //========================================================== + // dmcs2, groups halt and resume info + //========================================================== + assign apbw_dmcs2 = dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_DMCS2; + + wire [3:0] dmcs2_4zero; + wire dmcs2_zero; + + assign dmcs2_4zero[3:0] = 4'h0; + assign dmcs2_zero = 1'b0; + +`ifdef TDT_DM_GROUP_TRI_EN + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + grouptype <= 1'b0; + else if (sync_rst) + grouptype <= 1'b0; + else if (apbw_dmcs2) + grouptype <= dm_pwdata[11]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + exttrigger[3:0] <= 4'b0; + else if (sync_rst) + exttrigger[3:0] <= 4'b0; + else if (apbw_dmcs2) + exttrigger[3:0] <= dm_pwdata[10:7]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + groups[3:0] <= 4'b0; + else if (sync_rst) + groups[3:0] <= 4'b0; + else if (apbw_dmcs2) + groups[3:0] <= dm_pwdata[5:2]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + hgwrite <= 1'b0; + else if (sync_rst) + hgwrite <= 1'b0; + else if (apbw_dmcs2) + hgwrite <= dm_pwdata[1]; + else if (hgwrite) + hgwrite <= 1'b0; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + hgselect <= 1'b0; + else if (sync_rst) + hgselect <= 1'b0; + else if (apbw_dmcs2) + hgselect <= dm_pwdata[0]; + end +`else + always @ (*) begin + grouptype = dmcs2_zero; + end + + always @ (*) begin + exttrigger[3:0] = dmcs2_4zero[3:0]; + end + + always @ (*) begin + groups[3:0] = dmcs2_4zero[3:0]; + end + + always @ (*) begin + hgwrite = dmcs2_zero; + end + + always @ (*) begin + hgselect = dmcs2_zero; + end + +`endif + assign dmcs2[31:0] = {20'h0, grouptype, exttrigger[3:0], 1'b0, read_group[3:0], hgwrite, hgselect}; + + assign hg_sel_core = hgwrite & !hgselect; + assign hg_sel_exttri = hgwrite & hgselect; + + +`ifdef TDT_DM_EXT_TRIGGER_EN + generate + for (i=0; i= 16'h1020) || aarsize_err))) && ~busy) || + (autoaccen && (cmdtype[7:0] != 8'h0 || (transfer && (regno[15:0] >= 16'h1020))))) + cmderr[2:0] <= 3'h2; +`else + else if ((apbw_abscmd && ((dm_pwdata[31:24] != 8'h0) || (dm_pwdata[17] && ((dm_pwdata[15:5] != 11'h080) || aarsize_err))) && ~busy) || + (autoaccen && (cmdtype[7:0] != 8'h0 || (transfer && (regno[15:5] != 11'h080))))) + cmderr[2:0] <= 3'h2; +`endif + else if (core_dm_itr_done_mux && core_dm_exce_retire_mux && busy) + cmderr[2:0] <= 3'h3; +`ifdef TDT_DM_SINGLE_CORE + else if ((((dm_intra_apbw && dm_paddr_is_itr) || cmd_start || pb_work_start) && + (!hartsum0[hartsum0_idx[4:0]]) && ~busy) || (itr_vld_en && !hartsum0[hartsum0_idx[4:0]])) +`else + else if ((((dm_intra_apbw && dm_paddr_is_itr) || cmd_start || pb_work_start) && + (!hartsum0[hartsum0_idx[4:0]]) && ~busy) || (itr_vld_en[hartsello[CORE_NUM_W-1:0]] && !hartsum0[hartsum0_idx[4:0]])) +`endif + cmderr[2:0] <= 3'h4; + else if (busy && cmderr[2:0] == 3'h0 && cmd_busy_set) + cmderr[2:0] <= 3'h1; + end + + `ifdef TDT_DM_CORE_RV64 + assign datacount[3:0] = 4'h2; + `else + assign datacount[3:0] = 4'h1; + `endif + + assign abstractcs[31:0] = {3'b0, progbufsize[4:0], 11'b0, busy, 1'b0, cmderr[2:0], 4'b0, datacount[3:0]}; + + + //========================================================== + // ABS_CMD FSM + //========================================================== + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + regacc_cur_state[3:0] <= 4'h0; + else if (sync_rst) + regacc_cur_state[3:0] <= 4'h0; + else + regacc_cur_state[3:0] <= regacc_nxt_state[3:0]; + end + + wire not_acc_dsc0; + assign not_acc_dsc0 = regno[15:0] != 16'h7b2; + + always @ (regacc_cur_state[3:0] + or legal_cmd_sel + or access_csr + or core_dm_itr_done_mux + or access_illegal_reg + or access_dsc0 + or access_gpr + or cmd_start + or transfer + or core_dm_wr_ready_mux + or core_rdata_vld_r + or write + or not_acc_dsc0) + begin + case (regacc_cur_state[3:0]) + REGACC_IDLE : if (transfer && cmd_start && (~access_illegal_reg) && legal_cmd_sel) begin + if (write) + regacc_nxt_state[3:0] = REGACC_WDSC0; + else if (access_gpr) + regacc_nxt_state[3:0] = REGACC_G_2_DSC0; + else if (access_dsc0) + regacc_nxt_state[3:0] = REGACC_RDSC0; + else if (access_csr) + regacc_nxt_state[3:0] = REGACC_X6_2_DSC1; + else + regacc_nxt_state[3:0] = REGACC_IDLE; + end else begin + regacc_nxt_state[3:0] = REGACC_IDLE; + end + REGACC_WDSC0 : if (core_dm_wr_ready_mux) begin + if (access_gpr) + regacc_nxt_state[3:0] = REGACC_DSC0_2_G; + else if (access_dsc0) + regacc_nxt_state[3:0] = REGACC_IDLE; + else if (access_csr) + regacc_nxt_state[3:0] = REGACC_X6_2_DSC1; + else + regacc_nxt_state[3:0] = REGACC_WDSC0; + end else begin + regacc_nxt_state[3:0] = REGACC_WDSC0; + end + REGACC_G_2_DSC0 : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_RDSC0; + end else begin + regacc_nxt_state[3:0] = REGACC_G_2_DSC0; + end + REGACC_RDSC0 : if (core_rdata_vld_r) begin + regacc_nxt_state[3:0] = REGACC_IDLE; + end else begin + regacc_nxt_state[3:0] = REGACC_RDSC0; + end + REGACC_X6_2_DSC1 : if (core_dm_itr_done_mux) begin + if (access_csr && not_acc_dsc0) begin + if (write) + regacc_nxt_state[3:0] = REGACC_DSC0_2_X6; + else + regacc_nxt_state[3:0] = REGACC_C_2_X6; + end else begin + regacc_nxt_state[3:0] = REGACC_X6_2_DSC1; + end + end else begin + regacc_nxt_state[3:0] = REGACC_X6_2_DSC1; + end + REGACC_DSC0_2_G : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_IDLE; + end else begin + regacc_nxt_state[3:0] = REGACC_DSC0_2_G; + end + REGACC_DSC1_2_X6 : if (core_dm_itr_done_mux) begin + if (access_csr && not_acc_dsc0) begin + if (write) + regacc_nxt_state[3:0] = REGACC_IDLE; + else + regacc_nxt_state[3:0] = REGACC_RDSC0; + end else begin + regacc_nxt_state[3:0] = REGACC_DSC1_2_X6; + end + end else begin + regacc_nxt_state[3:0] = REGACC_DSC1_2_X6; + end + REGACC_DSC0_2_X6 : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_X6_2_C; + end else begin + regacc_nxt_state[3:0] = REGACC_DSC0_2_X6; + end + REGACC_X6_2_DSC0 : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_DSC1_2_X6; + end else begin + regacc_nxt_state[3:0] = REGACC_X6_2_DSC0; + end + REGACC_C_2_X6 : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_X6_2_DSC0; + end else begin + regacc_nxt_state[3:0] = REGACC_C_2_X6; + end + REGACC_X6_2_C : if (core_dm_itr_done_mux) begin + regacc_nxt_state[3:0] = REGACC_DSC1_2_X6; + end else begin + regacc_nxt_state[3:0] = REGACC_X6_2_C; + end + default : regacc_nxt_state[3:0] = REGACC_IDLE; + endcase + end + //========================================================== + // ITR and DCC + //========================================================== + assign access_gpr = (cmdtype[7:0] == 8'h0) && (regno[15:5] == 11'h080); +`ifdef TDT_ACC_CSR + assign access_csr = (cmdtype[7:0] == 8'h0) && (regno[15:12] == 4'h0); +`else + assign access_csr = 1'b0; +`endif + assign access_dsc0 = (cmdtype[7:0] == 8'h0) && (regno[15:0] == 16'h7b2); + +`ifdef TDT_ACC_CSR + assign access_illegal_reg = (cmdtype[7:0] == 8'h0) && (regno[15:0] >= 16'h1020); +`else + assign access_illegal_reg = (cmdtype[7:0] == 8'h0) && (regno[15:5] != 11'h080); +`endif + +`ifdef PROCESSOR_3 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 2'b00: sel_core_isa[3:0] = all_core_isa[3:0]; + 2'b01: sel_core_isa[3:0] = all_core_isa[7:4]; + 2'b10: sel_core_isa[3:0] = all_core_isa[11:8]; + 2'b11: sel_core_isa[3:0] = all_core_isa[15:12]; + default:sel_core_isa[3:0] = {4{1'bx}}; + endcase + end +`else + `ifdef PROCESSOR_2 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 2'b00: sel_core_isa[3:0] = all_core_isa[3:0]; + 2'b01: sel_core_isa[3:0] = all_core_isa[7:4]; + 2'b10: sel_core_isa[3:0] = all_core_isa[11:8]; + 2'b11: sel_core_isa[3:0] = 4'b0; + default:sel_core_isa[3:0] = {4{1'bx}}; + endcase + end + `else + `ifdef PROCESSOR_1 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 1'b0: sel_core_isa[3:0] = all_core_isa[3:0]; + 1'b1: sel_core_isa[3:0] = all_core_isa[7:4]; + default:sel_core_isa[3:0] = {4{1'bx}}; + endcase + end + `else + always @ (*) begin + sel_core_isa[3:0] = all_core_isa[3:0]; + end + `endif + `endif +`endif + + assign fsm_x6_2_dsc1 = regacc_nxt_state[3:0] == REGACC_X6_2_DSC1 && + ((regacc_cur_state[3:0] == REGACC_IDLE) || (regacc_cur_state[3:0] == REGACC_WDSC0)); + assign fsm_x6_2_dsc0 = regacc_nxt_state[3:0] == REGACC_X6_2_DSC0 && + regacc_cur_state[3:0] == REGACC_C_2_X6; + assign fsm_dsc1_2_x6 = regacc_nxt_state[3:0] == REGACC_DSC1_2_X6 && + ((regacc_cur_state[3:0] == REGACC_X6_2_DSC0) || (regacc_cur_state[3:0] == REGACC_X6_2_C)); + assign fsm_dsc0_2_x6 = regacc_nxt_state[3:0] == REGACC_DSC0_2_X6 && + regacc_cur_state[3:0] == REGACC_X6_2_DSC1; + assign fsm_c_2_x6 = regacc_nxt_state[3:0] == REGACC_C_2_X6 && + regacc_cur_state[3:0] == REGACC_X6_2_DSC1; + assign fsm_x6_2_c = regacc_nxt_state[3:0] == REGACC_X6_2_C && + regacc_cur_state[3:0] == REGACC_DSC0_2_X6; + +`ifdef TDT_DM_PB_EN + assign itr_send_pb = (pb_work_start && hartsum0[hartsum0_idx[4:0]]) || + (pb_work && !ebk_work && core_dm_itr_done_mux && !core_dm_exce_retire_mux); +`else + assign itr_send_pb = 1'b0; +`endif + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + itr_send_pb_r <= 1'b0; + else if (sync_rst) + itr_send_pb_r <= 1'b0; + else if (itr_send_pb_r) + itr_send_pb_r <= 1'b0; + else if (itr_send_pb) + itr_send_pb_r <= 1'b1; + + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + itr[31:0] <= 32'b0; + else if (sync_rst) + itr[31:0] <= 32'b0; + else if(dm_intra_apbw && dm_paddr_is_itr && legal_cmd_sel) + itr[31:0] <= dm_pwdata[31:0]; +`ifdef TDT_DM_PB_EN + else if (pb_work) + itr[31:0] <= pb_mux[31:0]; +`endif + else if (access_gpr) begin + if (transfer && !write && cmd_start && legal_cmd_sel) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR0_ADDR, regno[4:0], + TDT_DM_RV_CSRRW_FUNC3, TDT_DM_RV_ZERO_GPR, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (write && core_dm_wr_ready_mux) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR0_ADDR, TDT_DM_RV_ZERO_GPR, + TDT_DM_RV_CSRRC_FUNC3, regno[4:0], TDT_DM_RV_SYSTEM_OPCODE}; + endcase + end +`ifdef TDT_ACC_CSR + else if (access_csr && not_acc_dsc0) begin + if (fsm_x6_2_dsc1) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR1_ADDR, 5'h6, + TDT_DM_RV_CSRRW_FUNC3, TDT_DM_RV_ZERO_GPR, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (fsm_x6_2_dsc0) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR0_ADDR, 5'h6, + TDT_DM_RV_CSRRW_FUNC3, TDT_DM_RV_ZERO_GPR, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (fsm_dsc1_2_x6) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR1_ADDR, TDT_DM_RV_ZERO_GPR, + TDT_DM_RV_CSRRC_FUNC3, 5'h6, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (fsm_dsc0_2_x6) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {TDT_DM_RV_DSCR0_ADDR, TDT_DM_RV_ZERO_GPR, + TDT_DM_RV_CSRRC_FUNC3, 5'h6, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (fsm_c_2_x6) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {regno[11:0],TDT_DM_RV_ZERO_GPR, + TDT_DM_RV_CSRRC_FUNC3, 5'h6, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + else if (fsm_x6_2_c) + case (sel_core_isa[3:0]) + default : itr[31:0] <= {regno[11:0], 5'h6, + TDT_DM_RV_CSRRW_FUNC3, TDT_DM_RV_ZERO_GPR, TDT_DM_RV_SYSTEM_OPCODE}; + endcase + end +`endif + end + +`ifdef TDT_DM_SINGLE_CORE + assign itr_vld_en = (hartsello == 1'b0) && + ((dm_intra_apbw && dm_paddr_is_itr && ~busy && hartsum0[0]) || + (access_gpr && ((write && core_dm_wr_ready_pad) || + (!write && transfer && cmd_start && ~busy && hartsum0[0]))) + `ifdef TDT_ACC_CSR + || + (access_csr && (regno[15:0] != 16'h7b2) && + (fsm_x6_2_c || fsm_c_2_x6 || fsm_dsc0_2_x6 || fsm_dsc1_2_x6 || fsm_x6_2_dsc1 || fsm_x6_2_dsc0)) + `endif + `ifdef TDT_DM_PB_EN + || itr_send_pb_r + `endif + ); + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + itr_vld <= 1'b0; + else if (sync_rst) + itr_vld <= 1'b0; + else if (itr_vld) + itr_vld <= 1'b0; + else if (itr_vld_en) + itr_vld <= 1'b1; + end + + assign dm_core_itr_vld_o = itr_vld; + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + itr_work <= 1'b0; + else if (sync_rst) + itr_work <= 1'b0; + else if (core_dm_itr_done_mux) + itr_work <= 1'b0; + else if (dm_intra_apbw && dm_paddr_is_itr && ~busy && hartsum0[hartsum0_idx[4:0]]) + itr_work <= 1'b1; + end + + assign dm_core_wr_vld_en = hartsello == 1'b0 && ((transfer && + ((regacc_cur_state[3:0] == REGACC_IDLE && regacc_nxt_state[3:0] == REGACC_WDSC0) || + (((regacc_cur_state[3:0] == REGACC_IDLE) || (regacc_cur_state[3:0] == REGACC_G_2_DSC0) || + (regacc_cur_state[3:0] == REGACC_DSC1_2_X6)) && regacc_nxt_state[3:0] == REGACC_RDSC0))) || + (~cuscmdbusy && apbw_cuscmd && (dm_pwdata[31:24] == 8'h2 || dm_pwdata[31:24] == 8'h3))); + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + dm_core_wr_vld <= 1'b0; + else if (sync_rst) + dm_core_wr_vld <= 1'b0; + else if (dm_core_wr_vld_en) + dm_core_wr_vld <= 1'b1; + else if (dm_core_wr_vld) + dm_core_wr_vld <= 1'b0; + end +`else + generate + for (i=0; i 8'h3) +`else + if (dm_pwdata[31:24] > 8'h3 || dm_pwdata[31:24] == 8'h1 ) +`endif + cuscmderr[2:0] <= 3'h2; + else if (cuscmdbusy && apbw_cuscmd && (dm_pwdata[31:24] == 8'h2 || dm_pwdata[31:24] == 8'h3)) + cuscmderr[2:0] <= 3'h1; + else + cuscmderr[2:0] <= 3'h0; + end + end + +`ifdef TDT_DM_BUF_MOVE + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + src_type[1:0] <= 2'h0; + else if (sync_rst) + src_type[1:0] <= 2'h0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h1) + src_type[1:0] <= dm_pwdata[23:22]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + dst_type[1:0] <= 2'h0; + else if (sync_rst) + dst_type[1:0] <= 2'h0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h1) + dst_type[1:0] <= dm_pwdata[21:20]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + src_reg[3:0] <= 4'h0; + else if (sync_rst) + src_reg[3:0] <= 4'h0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h1) + src_reg[3:0] <= dm_pwdata[7:4]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + dst_reg[3:0] <= 4'h0; + else if (sync_rst) + dst_reg[3:0] <= 4'h0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h1) + dst_reg[3:0] <= dm_pwdata[3:0]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + internal_move_start <= 1'b0; + else if (sync_rst) + internal_move_start <= 1'b0; + else if (internal_move_start) + internal_move_start <= 1'b0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h1) + internal_move_start <= 1'b1; + end + + wire[31:0] datan_for_src_data; + wire[31:0] cusbufn_for_src_data; + + always @ (*) begin + case (src_reg[3:0]) + 4'h0 : datan_for_src_data[31:0] = data0[31:0]; + 4'h1 : datan_for_src_data[31:0] = data1[31:0]; + default : datan_for_src_data[31:0] = 32'd0; + endcase + end + +`ifdef TDT_DM_SBA + wire[31:0] sbdatan_for_src_data; + always @ (*) begin + case (src_reg[3:0]) + 4'h0 : sbdatan_for_src_data[31:0] = sbdata0[31:0]; + 4'h1 : sbdatan_for_src_data[31:0] = sbdata1[31:0]; + 4'h2 : sbdatan_for_src_data[31:0] = sbdata2[31:0]; + 4'h3 : sbdatan_for_src_data[31:0] = sbdata3[31:0]; + default : sbdatan_for_src_data[31:0] = 32'd0; + endcase + end +`endif + + always @ (*) begin + case (src_reg[3:0]) + 4'h0 : cusbufn_for_src_data[31:0] = cusbuf[0]; + 4'h1 : cusbufn_for_src_data[31:0] = cusbuf[1]; + 4'h2 : cusbufn_for_src_data[31:0] = cusbuf[2]; + 4'h3 : cusbufn_for_src_data[31:0] = cusbuf[3]; + 4'h4 : cusbufn_for_src_data[31:0] = cusbuf[4]; + 4'h5 : cusbufn_for_src_data[31:0] = cusbuf[5]; + 4'h6 : cusbufn_for_src_data[31:0] = cusbuf[6]; + 4'h7 : cusbufn_for_src_data[31:0] = cusbuf[7]; + default : cusbufn_for_src_data[31:0] = 32'd0; + endcase + end + + always @ (*) begin + case (src_type[1:0]) + 2'b00 : src_data_mux[31:0] = datan_for_src_data[31:0]; +`ifdef TDT_DM_SBA + 2'b01 : src_data_mux[31:0] = sbdatan_for_src_data[31:0]; +`endif + 2'b10 : src_data_mux[31:0] = cusbufn_for_src_data[31:0]; + default : src_data_mux[31:0] = 32'd0; + endcase + end + + generate + for (i=0; i<`TDT_DM_CUSTOM_BUF_CNT; i=i+1) begin : gen_cusbuf + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + cusbuf[i] <= 32'h0; + else if (sync_rst) + cusbuf[i] <= 32'h0; + + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == (OFFSET_CUSBUF0+i)) + cusbuf[i] <= dm_pwdata; + else if (internal_move_start && dst_type[1:0] == 2'b10 && dst_reg[3:0] == i[3:0]) + cusbuf[i] <= src_data_mux[31:0]; + end + end + endgenerate + + generate + for (i=0; i<8; i=i+1) begin : gen_cusbuf_all + if (i >= `TDT_DM_CUSTOM_BUF_CNT) begin : gen_pend_cusbuf + assign cusbuf_all[i] = 32'h0; + end else begin : gen_nor_cusbuf_all + assign cusbuf_all[i] = cusbuf[i]; + end + end + endgenerate +`endif + +`ifdef TDT_DM_SINGLE_CORE + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + dm_core_async_halt_req_o <= 1'b0; + else if (sync_rst) + dm_core_async_halt_req_o <= 1'b0; + else if (core_dm_halted_i) + dm_core_async_halt_req_o <= 1'b0; + else if (apbw_cuscmd && dm_pwdata[31:24] == 8'h0 && hart_sel) + dm_core_async_halt_req_o <= 1'b1; + end +`else + generate + for (i=0; i 32) begin : gen_sbaddr1 + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbaddr1[40-32-1:0] <= {40-32{1'b0}}; + else if (sync_rst) + sbaddr1[40-32-1:0] <= {40-32{1'b0}}; + + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR1 && sb_noerr) + sbaddr1[40-32-1:0] <= dm_pwdata[40-32-1:0]; + else if (sbautoincrement && sba_wr_ready && sbaddr0_plus_pre[32]) + sbaddr1[40-32-1:0] <= sbaddr1[40-32-1:0] + 1'b1; + end + + always @ (*) begin + sbaddr1[31:SBAW-32] = data_zero32[64-SBAW-1:0]; + end + end else begin : gen_dummy_sbaddr1 + always @ (*) begin + sbaddr1[31:0] = data_zero32[31:0]; + end + end + endgenerate + + assign sbversion[2:0] = 3'h1; + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbbusy <= 1'b0; + else if (sync_rst) + sbbusy <= 1'b0; + else if (sba_wr_ready) + sbbusy <= 1'b0; + else if (sba_wr_vld) + sbbusy <= 1'b1; + end + + wire sbbusyerr_set; + + generate + if (SBAW > 32) begin : gen_sbbusyerr_set_64 + assign sbbusyerr_set = (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR1) || + (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR0) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA1) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA2) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA3); + end else begin : gen_sbbusyerr_set_32 + assign sbbusyerr_set = (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR0) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA1) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA2) || + (dm_intra_access && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA3); + end + endgenerate + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbbusyerror <= 1'b0; + else if (sync_rst) + sbbusyerror <= 1'b0; + else if (sbbusyerr_set && sbbusy) + sbbusyerror <= 1'b1; + else if (apbw_sbcs && dm_pwdata[22]) + sbbusyerror <= 1'b0; + end + + wire sbaccess_unalian; +`ifdef TDT_DM_SBA_DW_128 + assign sbaccess_unalian = ((sbaccess[2:0] == 3'h2) && (|dm_pwdata[1:0])) || + ((sbaccess[2:0] == 3'h3) && (|dm_pwdata[2:0])) || + ((sbaccess[2:0] == 3'h4) && (|dm_pwdata[3:0])); +`else + `ifdef TDT_DM_SBA_DW_64 + assign sbaccess_unalian = ((sbaccess[2:0] == 3'h2) && (|dm_pwdata[1:0])) || + ((sbaccess[2:0] == 3'h3) && (|dm_pwdata[2:0])); + `else + assign sbaccess_unalian = ((sbaccess[2:0] == 3'h2) && (|dm_pwdata[1:0])); + `endif +`endif + //sba_error 4 must record, + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sberror_will_be_4 <= 1'b0; + else if (sync_rst) + sberror_will_be_4 <= 1'b0; + else if (apbw_sbcs && (&dm_pwdata[14:12])) + sberror_will_be_4 <= 1'b0; + `ifdef TDT_DM_SBA_DW_128 + else if (apbw_sbcs && ((dm_pwdata[19:17] < 3'h2) || (dm_pwdata[19:17] > 3'h4)) && ~sbbusy) +`else + `ifdef TDT_DM_SBA_DW_64 + else if (apbw_sbcs && ((dm_pwdata[19:17] < 3'h2) || (dm_pwdata[19:17] > 3'h3)) && ~sbbusy) + `else + else if (apbw_sbcs && (dm_pwdata[19:17] != 3'h2) && ~sbbusy) + + `endif +`endif + sberror_will_be_4 <= 1'b1; + `ifdef TDT_DM_SBA_DW_128 + else if (apbw_sbcs && !((dm_pwdata[19:17] < 3'h2) || (dm_pwdata[19:17] > 3'h4)) && ~sbbusy) +`else + `ifdef TDT_DM_SBA_DW_64 + else if (apbw_sbcs && !((dm_pwdata[19:17] < 3'h2) || (dm_pwdata[19:17] > 3'h3)) && ~sbbusy) + `else + else if (apbw_sbcs && (dm_pwdata[19:17] == 3'h2) && ~sbbusy) + + `endif +`endif + sberror_will_be_4 <= 1'b0; + end + +//sba_error 3 must record, when sba_wr_vld, set sba_error to 3 + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sberror_will_be_3 <= 1'b0; + else if (sync_rst) + sberror_will_be_3 <= 1'b0; + else if (apbw_sbcs && (&dm_pwdata[14:12])) + sberror_will_be_3 <= 1'b0; + else if (dm_intra_apbw && dm_paddr_is_sbaddr0 && sbaccess_unalian && ~sbbusy) + sberror_will_be_3 <= 1'b1; + else if (dm_intra_apbw && dm_paddr_is_sbaddr0 && !sbaccess_unalian && ~sbbusy) + sberror_will_be_3 <= 1'b0; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sberror[2:0] <= 3'h0; + else if (sync_rst) + sberror[2:0] <= 3'h0; + else if (apbw_sbcs && (&dm_pwdata[14:12])) + sberror[2:0] <= 3'h0; + else if (sberror_will_be_4 && (sba_write_ignore_unalign_f || sba_read_ignore_unalign_f) && sb_noerr) + sberror[2:0] <= 3'h4; + else if (sberror_will_be_3 && (sba_write_ignore_unalign_f || sba_read_ignore_unalign_f) && sb_noerr) + sberror[2:0] <= 3'h3; + else if (sba_error && sba_wr_ready) + sberror[2:0] <= 3'h7; + end + + assign sbasize[6:0] = `SBAW_WITH_WIDTH; + +`ifdef TDT_DM_SBA_DW_128 + assign sbaccess_info[4:0] = 5'b11100; +`else + `ifdef TDT_DM_SBA_DW_64 + assign sbaccess_info[4:0] = 5'b01100; + `else + assign sbaccess_info[4:0] = 5'b00100; + `endif +`endif + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbreadonaddr <= 1'b0; + else if (sync_rst) + sbreadonaddr <= 1'b0; + else if (apbw_sbcs) + sbreadonaddr <= dm_pwdata[20]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbaccess[2:0] <= 3'h2; + else if (sync_rst) + sbaccess[2:0] <= 3'h2; + else if (apbw_sbcs) + sbaccess[2:0] <= dm_pwdata[19:17]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbautoincrement <= 1'b0; + else if (sync_rst) + sbautoincrement <= 1'b0; + else if (apbw_sbcs) + sbautoincrement <= dm_pwdata[16]; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbreadondata <= 1'b0; + else if (sync_rst) + sbreadondata <= 1'b0; + else if (apbw_sbcs) + sbreadondata <= dm_pwdata[15]; + end + + assign sbcs[31:0] = {sbversion[2:0], 6'h0, sbbusyerror, sbbusy, sbreadonaddr, sbaccess[2:0], + sbautoincrement, sbreadondata, sberror[2:0], sbasize[6:0], sbaccess_info[4:0]}; + + assign sba_write = dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0 && + sbaddr0[1:0] == 2'b0 && !(sbreadonaddr || sbreadondata); + assign sba_read = (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR0 && dm_pwdata[1:0] == 2'b0 && sbreadonaddr) || + (dm_intra_apbr && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0 && sbaddr0[1:0] == 2'b0 && sbreadondata); + + assign sba_write_ignore_unalign = dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0 && !(sbreadonaddr || sbreadondata); + assign sba_read_ignore_unalign = (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBADDR0 && sbreadonaddr) || + (dm_intra_apbr && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0 && sbreadondata); + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sba_write_ignore_unalign_f <= 1'b0; + else if (sba_write_ignore_unalign_f) + sba_write_ignore_unalign_f <= 1'b0; + else if (sba_write_ignore_unalign) + sba_write_ignore_unalign_f <= 1'b1; + end + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sba_read_ignore_unalign_f <= 1'b0; + else if (sba_read_ignore_unalign_f) + sba_read_ignore_unalign_f <= 1'b0; + else if (sba_read_ignore_unalign) + sba_read_ignore_unalign_f <= 1'b1; + end + + wire [31:0] sbdata_zero_value; + assign sbdata_zero_value[31:0] = 32'h0; + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sba_wr_flg <= 1'b0; + else if (sync_rst) + sba_wr_flg <= 1'b0; + else if (sba_write) + sba_wr_flg <= 1'b1; + else if (sba_read) + sba_wr_flg <= 1'b0; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sba_wr_vld <= 1'b0; + else if (sync_rst) + sba_wr_vld <= 1'b0; + else if (sba_wr_vld) + sba_wr_vld <= 1'b0; + else if ((sba_write || sba_read) && sb_noerr && !sberror_will_be_3 && !sberror_will_be_4) + sba_wr_vld <= 1'b1; + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbdata0[31:0] <= 32'h0; + else if (sync_rst) + sbdata0[31:0] <= 32'h0; + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA0 && sb_noerr) + sbdata0[31:0] <= dm_pwdata[31:0]; + else if (sba_wr_ready && !sba_wr_flg) + sbdata0[31:0] <= sba_rd_data[31:0]; +`ifdef TDT_DM_BUF_MOVE + else if (internal_move_start && dst_type[1:0] == 2'b01 && dst_reg[3:0] == 4'h0) + sbdata0[31:0] <= src_data_mux[31:0]; +`endif + end + +`ifdef TDT_DM_SBA_DW_128 + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbdata1[31:0] <= 32'h0; + else if (sync_rst) + sbdata1[31:0] <= 32'h0; + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA1 && sb_noerr) + sbdata1[31:0] <= dm_pwdata[31:0]; + else if (sba_wr_ready && !sba_wr_flg && sbaccess[2:0] > 3'h2) + sbdata1[31:0] <= sba_rd_data[63:32]; + `ifdef TDT_DM_BUF_MOVE + else if (internal_move_start && dst_type[1:0] == 2'b01 && dst_reg[3:0] == 4'h1) + sbdata1[31:0] <= src_data_mux[31:0]; + `endif + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbdata2[31:0] <= 32'h0; + else if (sync_rst) + sbdata2[31:0] <= 32'h0; + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA2 && sb_noerr) + sbdata2[31:0] <= dm_pwdata[31:0]; + else if (sba_wr_ready && !sba_wr_flg && sbaccess[2:0] > 3'h3) + sbdata2[31:0] <= sba_rd_data[95:64]; + `ifdef TDT_DM_BUF_MOVE + else if (internal_move_start && dst_type[1:0] == 2'b01 && dst_reg[3:0] == 4'h2) + sbdata2[31:0] <= src_data_mux[31:0]; + `endif + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbdata3[31:0] <= 32'h0; + else if (sync_rst) + sbdata3[31:0] <= 32'h0; + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA3 && sb_noerr) + sbdata3[31:0] <= dm_pwdata[31:0]; + else if (sba_wr_ready && !sba_wr_flg && sbaccess[2:0] > 3'h3) + sbdata3[31:0] <= sba_rd_data[127:96]; + `ifdef TDT_DM_BUF_MOVE + else if (internal_move_start && dst_type[1:0] == 2'b01 && dst_reg[3:0] == 4'h3) + sbdata3[31:0] <= src_data_mux[31:0]; + `endif + end +`else + `ifdef TDT_DM_SBA_DW_64 + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + sbdata1[31:0] <= 32'h0; + else if (sync_rst) + sbdata1[31:0] <= 32'h0; + + else if (dm_intra_apbw && dm_paddr[APB_AW-1:2] == OFFSET_SBDATA1 && sb_noerr) + sbdata1[31:0] <= dm_pwdata[31:0]; + else if (sba_wr_ready && !sba_wr_flg && sbaccess[2:0] > 3'h2) + sbdata1[31:0] <= sba_rd_data[63:32]; + `ifdef TDT_DM_BUF_MOVE + else if (internal_move_start && dst_type[1:0] == 2'b01 && dst_reg[3:0] == 4'h1) + sbdata1[31:0] <= src_data_mux[31:0]; + `endif + end + + always @ (*) begin + sbdata2[31:0] = sbdata_zero_value[31:0]; + end + + always @ (*) begin + sbdata3[31:0] = sbdata_zero_value[31:0]; + end + `else + always @ (*) begin + sbdata1[31:0] = sbdata_zero_value[31:0]; + end + + always @ (*) begin + sbdata2[31:0] = sbdata_zero_value[31:0]; + end + + always @ (*) begin + sbdata3[31:0] = sbdata_zero_value[31:0]; + end + + `endif +`endif + +`ifdef TDT_DM_SBA_DW_128 + assign sba_w_data[`TDT_DM_SBA_DW-1:0] = {sbdata3[31:0], sbdata2[31:0], sbdata1[31:0], sbdata0[31:0]}; +`else + `ifdef TDT_DM_SBA_DW_64 + assign sba_w_data[`TDT_DM_SBA_DW-1:0] = {sbdata1[31:0], sbdata0[31:0]}; + `else + assign sba_w_data[`TDT_DM_SBA_DW-1:0] = sbdata0[31:0]; + `endif +`endif + + assign sba_wr_addr_pre[63:0] = {sbaddr1[31:0], sbaddr0[31:0]}; + assign sba_wr_addr[SBAW-1:0] = sba_wr_addr_pre[SBAW-1:0]; + assign sba_wr_size[2:0] = sbaccess[2:0]; + + wire sba_wr_vld_cpuclk_sync; + wire sba_wr_ready_async; + wire sba_wr_ready_pulse; + wire sba_error_async; + wire[`TDT_DM_SBA_DW-1:0] sba_rd_data_async; + reg sba_wr_vld_sync; + reg sba_wr_vld_cpuclk_post_sync; + reg sba_wr_ready_cpuclk_sync; + +//pclk to cpuclk cdc, async cdc +tdt_dm_pulse_sync u_tdt_dm_pulse_sync_cpuclk_vld( + .src_clk (pclk), + .dst_clk (forever_cpuclk), + .src_rst_b (preset_b), + .dst_rst_b (ciu_rst_b), + .src_pulse (sba_wr_vld), + .dst_pulse (sba_wr_vld_cpuclk_sync) +); +//cpuclk to axiclk cdc, sync cdc +always @(posedge forever_cpuclk or negedge ciu_rst_b) +begin + if(!ciu_rst_b) + sba_wr_vld_cpuclk_post_sync <= 1'b0; + else if(sys_bus_clk_en) + sba_wr_vld_cpuclk_post_sync <= 1'b0; + else if(sba_wr_vld_cpuclk_sync) + sba_wr_vld_cpuclk_post_sync <= 1'b1; +end + +always @(posedge forever_cpuclk or negedge ciu_rst_b) +begin + if(!ciu_rst_b) + sba_wr_vld_sync <= 1'b0; + else if(sys_bus_clk_en) + begin + if(sba_wr_vld_cpuclk_sync || sba_wr_vld_cpuclk_post_sync) + sba_wr_vld_sync <= 1'b1; + else if(sba_wr_vld_sync) + sba_wr_vld_sync <= 1'b0; + end +end +//axiclk to cpuclk cdc, sync cdc +always @ (posedge forever_cpuclk or negedge ciu_rst_b) begin + if (!ciu_rst_b) + sba_wr_ready_cpuclk_sync <= 1'b0; + else if (sys_bus_clk_en) + sba_wr_ready_cpuclk_sync <= sba_wr_ready_async; + else if(sba_wr_ready_cpuclk_sync) + sba_wr_ready_cpuclk_sync <= 1'b0; +end + +//cpuclk to pclk cdc, async cdc +tdt_dm_pulse_sync u_tdt_dm_pulse_sync_ready( + .src_clk (forever_cpuclk), + .dst_clk (pclk), + .src_rst_b (ciu_rst_b), + .dst_rst_b (preset_b), + .src_pulse (sba_wr_ready_cpuclk_sync), + .dst_pulse (sba_wr_ready_pulse) +); + +always @ (posedge pclk or negedge preset_b) begin + if (!preset_b) + sba_wr_ready <= 1'b0; + else + sba_wr_ready <= sba_wr_ready_pulse; +end + +always @ (posedge pclk or negedge preset_b) begin + if (!preset_b) + sba_error <= 1'b0; + else if(sba_wr_ready_pulse) + sba_error <= sba_error_async; +end + +always @ (posedge pclk or negedge preset_b) begin + if (!preset_b) + sba_rd_data[`TDT_DM_SBA_DW-1:0] <= {`TDT_DM_SBA_DW{1'b0}}; + else if(sba_wr_ready_pulse) + sba_rd_data[`TDT_DM_SBA_DW-1:0] <= sba_rd_data_async[`TDT_DM_SBA_DW-1:0]; +end + +`ifdef TDT_DM_SBA_AXI +tdt_sba_axi #( + .AXI_ADDR_WIDTH (SBAW) +) x_tdt_sba_axi ( + + .mclk (forever_cpuclk), + .mreset_b (ciu_rst_b), + .pad_icg_scan_en (pad_icg_scan_en), + .axim_clk_en (sys_bus_clk_en), + + .wr_data (sba_w_data), + .wr_flg (sba_wr_flg), + .wr_addr (sba_wr_addr), + .wr_vld (sba_wr_vld_sync), + .wr_size (sba_wr_size), + .rd_data (sba_rd_data_async), + .axi_wr_ready (sba_wr_ready_async), + .sba_error (sba_error_async), + + .awid (dm_pad_awid), + .awaddr (dm_pad_awaddr), + .awlen (dm_pad_awlen), + .awsize (dm_pad_awsize), + .awvalid (dm_pad_awvalid), + .awready (pad_dm_awready), + + .wdata (dm_pad_wdata), + .wstrb (dm_pad_wstrb), + .wlast (dm_pad_wlast), + .wvalid (dm_pad_wvalid), + .wready (pad_dm_wready), + + .bid (pad_dm_bid), + .bresp (pad_dm_bresp), + .bvalid (pad_dm_bvalid), + .bready (dm_pad_bready), + + .arid (dm_pad_arid), + .araddr (dm_pad_araddr), + .arlen (dm_pad_arlen), + .arsize (dm_pad_arsize), + .arvalid (dm_pad_arvalid), + .arready (pad_dm_arready), + + .rid (pad_dm_rid), + .rdata (pad_dm_rdata), + .rlast (pad_dm_rlast), + .rresp (pad_dm_rresp), + .rvalid (pad_dm_rvalid), + .rready (dm_pad_rready) + +); + assign dm_pad_awburst[1:0] = 2'b01; + assign dm_pad_awcache[3:0] = 4'h0; + assign dm_pad_awlock = 1'b0; + assign dm_pad_awprot[2:0] = 3'b010; + assign dm_pad_arburst[1:0] = 2'b01; + assign dm_pad_arcache[3:0] = 4'h0; + assign dm_pad_arlock = 1'b0; + assign dm_pad_arprot[2:0] = 3'b010; + //assign dm_pad_wid[3:0] = dm_pad_awid[3:0]; +`endif +`ifdef TDT_DM_SBA_AHB +tdt_sba_ahb #( + .AHB_ADDR_WIDTH (SBAW) +) x_tdt_sba_ahb ( + + .mclk (forever_cpuclk), + .mreset_b (ciu_rst_b), + .pad_icg_scan_en (pad_icg_scan_en), + .ahbm_clk_en (sys_bus_clk_en), + + .wr_data (sba_w_data), + .wr_flg (sba_wr_flg), + .wr_addr (sba_wr_addr), + .wr_vld (sba_wr_vld_sync), + .wr_size (sba_wr_size), + .rd_data (sba_rd_data_async), + .ahb_wr_ready (sba_wr_ready_async), + .sba_error (sba_error_async), + + .haddr (dm_pad_haddr), + .hburst (dm_pad_hburst), + .hsize (dm_pad_hsize), + .htrans (dm_pad_htrans), + .hwrite (dm_pad_hwrite), + .hwdata (dm_pad_hwdata), + .hrdata (pad_dm_hrdata), + .hready (pad_dm_hready), + .hresp (pad_dm_hresp) +); + assign dm_pad_hprot[3:0] = 4'h1; + assign dm_pad_hmastlock = 1'b0; +`endif + +`endif + + //========================================================== + // apb read + //========================================================== + + always @ (posedge pclk or negedge preset_b) begin + if (!preset_b) + dm_pready <= 1'b0; + else if (dm_pready) + dm_pready <= 1'b0; + else if (dm_psel && !dm_penable) + dm_pready <= 1'b1; + end + + assign nextdm[31:0] = NEXTDM_BASEADDR; + +`ifdef PROCESSOR_3 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 2'b00: hartinfo[31:0] = {8'h0, nscratch_all[3:0], 20'h0}; + 2'b01: hartinfo[31:0] = {8'h0, nscratch_all[7:4], 20'h0}; + 2'b10: hartinfo[31:0] = {8'h0, nscratch_all[11:8], 20'h0}; + 2'b11: hartinfo[31:0] = {8'h0, nscratch_all[15:12], 20'h0}; + default:hartinfo[31:0] = {32{1'bx}}; + endcase + end +`else + `ifdef PROCESSOR_2 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 2'b00: hartinfo[31:0] = {8'h0, nscratch_all[3:0], 20'h0}; + 2'b01: hartinfo[31:0] = {8'h0, nscratch_all[7:4], 20'h0}; + 2'b10: hartinfo[31:0] = {8'h0, nscratch_all[11:8], 20'h0}; + 2'b11: hartinfo[31:0] = 32'b0; + default:hartinfo[31:0] = {32{1'bx}}; + endcase + end + `else + `ifdef PROCESSOR_1 + always @ (*) begin + case(hartsello[CORE_NUM_W-1:0]) + 1'b0: hartinfo[31:0] = {8'h0, nscratch_all[3:0], 20'h0}; + 1'b1: hartinfo[31:0] = {8'h0, nscratch_all[7:4], 20'h0}; + default:hartinfo[31:0] = {32{1'bx}}; + endcase + end + `else + always @ (*) begin + hartinfo[31:0] = {8'h0, nscratch_all[3:0], 20'h0}; + end + `endif + `endif +`endif + + always @ (dm_paddr[APB_AW-1:2] or + data0 or + data1 or + dmcontrol or + dmstatus or + hartinfo or + hawindow or + abstractcs or + abstractauto or + nextdm or + hartsum0 or + itr or + customcs or + compid + `ifdef TDT_DM_PB_EN + or progbuf[0] + or progbuf[1] + or progbuf[2] + or progbuf[3] + or progbuf[4] + or progbuf[5] + or progbuf[6] + or progbuf[7] + or progbuf[8] + or progbuf[9] + or progbuf[10] + or progbuf[11] + or progbuf[12] + or progbuf[13] + or progbuf[14] + or progbuf[15] + `endif + `ifdef TDT_DM_GROUP_TRI_EN + or dmcs2 + `endif + `ifdef TDT_DM_SBA + or sbcs + or sbaddr0 + or sbaddr1 + or sbdata0 + or sbdata1 + or sbdata2 + or sbdata3 + `endif + `ifdef TDT_DM_BUF_MOVE + or cusbuf_all[7:0] + `endif + ) + begin + case (dm_paddr[APB_AW-1:2]) + OFFSET_DATA0 : prdata_pre[31:0] = data0[31:0]; + OFFSET_DATA1 : prdata_pre[31:0] = data1[31:0]; + OFFSET_DMCONTROL : prdata_pre[31:0] = dmcontrol[31:0]; + OFFSET_DMSTATUS : prdata_pre[31:0] = dmstatus[31:0]; + OFFSET_HARTINFO : prdata_pre[31:0] = hartinfo[31:0]; + OFFSET_HAWINDOW : prdata_pre[31:0] = hawindow[31:0]; + OFFSET_ABSTRACTCS : prdata_pre[31:0] = abstractcs[31:0]; + OFFSET_COMMAND : prdata_pre[31:0] = 32'h0; + OFFSET_ABSTRACTAUTO : prdata_pre[31:0] = abstractauto[31:0]; + OFFSET_NEXTDM : prdata_pre[31:0] = nextdm[31:0]; +`ifdef TDT_DM_PB_EN + OFFSET_PB0 : prdata_pre[31:0] = progbuf[0]; + OFFSET_PB1 : prdata_pre[31:0] = progbuf[1]; + OFFSET_PB2 : prdata_pre[31:0] = progbuf[2]; + OFFSET_PB3 : prdata_pre[31:0] = progbuf[3]; + OFFSET_PB4 : prdata_pre[31:0] = progbuf[4]; + OFFSET_PB5 : prdata_pre[31:0] = progbuf[5]; + OFFSET_PB6 : prdata_pre[31:0] = progbuf[6]; + OFFSET_PB7 : prdata_pre[31:0] = progbuf[7]; + OFFSET_PB8 : prdata_pre[31:0] = progbuf[8]; + OFFSET_PB9 : prdata_pre[31:0] = progbuf[9]; + OFFSET_PB10 : prdata_pre[31:0] = progbuf[10]; + OFFSET_PB11 : prdata_pre[31:0] = progbuf[11]; + OFFSET_PB12 : prdata_pre[31:0] = progbuf[12]; + OFFSET_PB13 : prdata_pre[31:0] = progbuf[13]; + OFFSET_PB14 : prdata_pre[31:0] = progbuf[14]; + OFFSET_PB15 : prdata_pre[31:0] = progbuf[15]; +`endif +`ifdef TDT_DM_GROUP_TRI_EN + OFFSET_DMCS2 : prdata_pre[31:0] = dmcs2[31:0]; +`endif +`ifdef TDT_DM_SBA + OFFSET_SBCS : prdata_pre[31:0] = sbcs[31:0]; + OFFSET_SBADDR0 : prdata_pre[31:0] = sbaddr0[31:0]; + OFFSET_SBADDR1 : prdata_pre[31:0] = sbaddr1[31:0]; + OFFSET_SBDATA0 : prdata_pre[31:0] = sbdata0[31:0]; + OFFSET_SBDATA1 : prdata_pre[31:0] = sbdata1[31:0]; + OFFSET_SBDATA2 : prdata_pre[31:0] = sbdata2[31:0]; + OFFSET_SBDATA3 : prdata_pre[31:0] = sbdata3[31:0]; +`endif + OFFSET_HARTSUM0 : prdata_pre[31:0] = hartsum0[31:0]; + OFFSET_ITR : prdata_pre[31:0] = itr[31:0]; + OFFSET_CUSCS : prdata_pre[31:0] = customcs[31:0]; + OFFSET_CUSCMD : prdata_pre[31:0] = 32'h0; +`ifdef TDT_DM_BUF_MOVE + OFFSET_CUSBUF0 : prdata_pre[31:0] = cusbuf_all[0]; + OFFSET_CUSBUF1 : prdata_pre[31:0] = cusbuf_all[1]; + OFFSET_CUSBUF2 : prdata_pre[31:0] = cusbuf_all[2]; + OFFSET_CUSBUF3 : prdata_pre[31:0] = cusbuf_all[3]; + OFFSET_CUSBUF4 : prdata_pre[31:0] = cusbuf_all[4]; + OFFSET_CUSBUF5 : prdata_pre[31:0] = cusbuf_all[5]; + OFFSET_CUSBUF6 : prdata_pre[31:0] = cusbuf_all[6]; + OFFSET_CUSBUF7 : prdata_pre[31:0] = cusbuf_all[7]; +`endif + OFFSET_COMPID : prdata_pre[31:0] = compid[31:0]; + default : prdata_pre[31:0] = 32'h0; + endcase + end + + always @ (posedge dm_pclk or negedge preset_b) begin + if (!preset_b) + dm_prdata[31:0] <= 32'b0; + else if (sync_rst) + dm_prdata[31:0] <= 32'b0; + else if (dm_psel && !dm_penable) + dm_prdata[31:0] <= prdata_pre[31:0]; + end + + assign dm_pslverr = 1'b0; + +`ifdef ASSERTION + `ifdef TDT_DM_SINGLE_CORE + property when_allunavail_is_high_allrunning_must_be_low; + @(posedge dm_pclk) allunavail |-> !allrunning; + endproperty + assert property(when_allunavail_is_high_allrunning_must_be_low); + + property when_allunavail_is_high_allhalted_must_be_low; + @(posedge dm_pclk) allunavail |-> !allhalted; + endproperty + assert property(when_allunavail_is_high_allhalted_must_be_low); + + property when_anyunavail_is_high_anyrunning_must_be_low; + @(posedge dm_pclk) anyunavail |-> !anyrunning; + endproperty + assert property(when_anyunavail_is_high_anyrunning_must_be_low); + + property when_anyunavail_is_high_anyhalted_must_be_low; + @(posedge dm_pclk) anyunavail |-> !anyhalted; + endproperty + assert property(when_anyunavail_is_high_anyhalted_must_be_low); + `else + property when_allunavail_is_high_allrunning_must_be_low; + @(posedge dm_pclk) allunavail |-> !allrunning; + endproperty + assert property(when_allunavail_is_high_allrunning_must_be_low); + + property when_allunavail_is_high_allhalted_must_be_low; + @(posedge dm_pclk) allunavail |-> !allhalted; + endproperty + assert property(when_allunavail_is_high_allhalted_must_be_low); + `endif +`endif +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_pulse_sync.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_pulse_sync.v new file mode 100644 index 0000000000000000000000000000000000000000..2d0c6cb7bea112075cf2f09ead8bdfa288acd1c0 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_pulse_sync.v @@ -0,0 +1,81 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dmi_pulse_sync #( + parameter SYNC_NUM = 2 +)( + input src_clk, + input dst_clk, + input src_rst_b, + input dst_rst_b, + input src_pulse, + output dst_pulse +); + reg src_pulse_2_lvl; + wire dst_lvl; + reg dst_lvl_d; + wire dst_lvl_src; + reg dst_lvl_src_d; + wire dst_pulse_2_src; + + always @ (posedge src_clk or negedge src_rst_b) begin + if(!src_rst_b) + dst_lvl_src_d <= 1'b0; + else + dst_lvl_src_d <= dst_lvl_src; + end + + assign dst_pulse_2_src = dst_lvl_src & ~dst_lvl_src_d; + + + always @ (posedge src_clk or negedge src_rst_b) begin + if(!src_rst_b) + src_pulse_2_lvl <= 1'b0; + else if (dst_pulse_2_src) + src_pulse_2_lvl <= 1'b0; + else if (src_pulse) + src_pulse_2_lvl <= 1'b1; + + //src_pulse_2_lvl <= ~src_pulse_2_lvl; + end + + tdt_dmi_sync_dff #( + .SYNC_NUM (SYNC_NUM) + ) x_tdt_dmi_sync_dff ( + .dst_clk (dst_clk), + .dst_rst_b (dst_rst_b), + .src_in (src_pulse_2_lvl), + .dst_out (dst_lvl) + ); + + tdt_dmi_sync_dff #( + .SYNC_NUM (SYNC_NUM) + ) x_tdt_dmi_sync_dff_back ( + .dst_clk (src_clk), + .dst_rst_b (src_rst_b), + .src_in (dst_lvl), + .dst_out (dst_lvl_src) + ); + + always @ (posedge dst_clk or negedge dst_rst_b) begin + if(!dst_rst_b) + dst_lvl_d <= 1'b0; + else + dst_lvl_d <= dst_lvl; + end + + assign dst_pulse = dst_lvl & ~dst_lvl_d; + +endmodule + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_sync_dff.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_sync_dff.v new file mode 100644 index 0000000000000000000000000000000000000000..cd58f828aec768bd44a03d0338e227853c7d4310 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dmi_sync_dff.v @@ -0,0 +1,35 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dmi_sync_dff #( + parameter SYNC_NUM = 2 +)( + input dst_clk, + input dst_rst_b, + input src_in, + output dst_out +); + +reg [SYNC_NUM-1:0] sync_ff; + +always @ (posedge dst_clk or negedge dst_rst_b) begin + if (!dst_rst_b) + sync_ff[SYNC_NUM-1:0] <= {SYNC_NUM{1'b0}}; + else + sync_ff[SYNC_NUM-1:0] <= {sync_ff[SYNC_NUM-2:0], src_in}; +end + +assign dst_out = sync_ff[SYNC_NUM-1]; + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_chain.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_chain.v new file mode 100644 index 0000000000000000000000000000000000000000..b57df29049660e85cd15c8eb57949775941de4c0 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_chain.v @@ -0,0 +1,135 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dtm_chain #( + parameter CHAIN_DW = 64, + parameter DTM_IRREG_WIDTH = 5, + parameter DTM_ABITS = 16, + parameter DTM_NDMIREG_WIDTH = 32 + +)( + input tclk, + input trst_b, + input dmihardreset, + input io_chain_tdi, + output chain_io_tdo, + + input [CHAIN_DW-1:0] idr_chain_dr, + input [DTM_IRREG_WIDTH-1:0] idr_chain_ir, + output [CHAIN_DW-1:0] chain_idr_data, + + input idr_dmi_mode, + input ctrl_chain_capture_dr, + input ctrl_chain_capture_ir, + input ctrl_chain_shift_dr, + input ctrl_chain_shift_ir, + input ctrl_chain_shift_par, + input ctrl_chain_shift_sync +); + + + localparam [DTM_IRREG_WIDTH-1:0] IDCODE = 5'h01; + localparam [DTM_IRREG_WIDTH-1:0] DMI_ACC = 5'h02; + localparam [DTM_IRREG_WIDTH-1:0] DTMCS = 5'h10; + localparam [DTM_IRREG_WIDTH-1:0] DMI = 5'h11; + + localparam DTM_DMIREG_WIDTH = DTM_ABITS + 2 + 32; + localparam DTM_DMIACCREG_WIDTH = 1; + + reg [CHAIN_DW-1:0] chain_shifter_pre; + reg [CHAIN_DW-1:0] chain_shifter; + reg parity; + reg tdo; + wire tdi; + + always @ (ctrl_chain_shift_ir or + tdi or + chain_shifter or + ctrl_chain_capture_dr or + idr_chain_dr[CHAIN_DW-1:0] or + ctrl_chain_capture_ir or + idr_chain_ir[DTM_IRREG_WIDTH-1:0] or + ctrl_chain_shift_dr or + idr_dmi_mode + ) begin + chain_shifter_pre[CHAIN_DW-1:0] = {CHAIN_DW{1'b0}}; + if (ctrl_chain_shift_ir) + chain_shifter_pre[DTM_IRREG_WIDTH-1:0] = {tdi, chain_shifter[DTM_IRREG_WIDTH-1:1]}; + else if (ctrl_chain_capture_dr) + chain_shifter_pre[CHAIN_DW-1:0] = idr_chain_dr[CHAIN_DW-1:0]; + else if (ctrl_chain_capture_ir) + chain_shifter_pre[CHAIN_DW-1:0] = {{CHAIN_DW-DTM_IRREG_WIDTH{1'b0}}, idr_chain_ir[DTM_IRREG_WIDTH-1:0]}; + else if (ctrl_chain_shift_dr) + case (idr_chain_ir[DTM_IRREG_WIDTH-1:0]) + DMI_ACC : chain_shifter_pre[DTM_DMIACCREG_WIDTH-1:0] = tdi;//1bit + DMI : if (idr_dmi_mode) + chain_shifter_pre[DTM_DMIREG_WIDTH-DTM_ABITS-1:0] = {tdi, chain_shifter[DTM_DMIREG_WIDTH-DTM_ABITS-1:1]};//44bit + else + chain_shifter_pre[DTM_DMIREG_WIDTH-1:0] = {tdi, chain_shifter[DTM_DMIREG_WIDTH-1:1]};//34bit + DTMCS : chain_shifter_pre[DTM_NDMIREG_WIDTH-1:0] = {tdi, chain_shifter[DTM_NDMIREG_WIDTH-1:1]};//32bit + IDCODE : chain_shifter_pre[DTM_NDMIREG_WIDTH-1:0] = {tdi, chain_shifter[DTM_NDMIREG_WIDTH-1:1]};//32bit + default : chain_shifter_pre[DTM_DMIACCREG_WIDTH-1:0] = tdi;//1bit,use DTM_DMIACCREG_WIDTH + endcase + else + chain_shifter_pre[CHAIN_DW-1:0] = chain_shifter[CHAIN_DW-1:0]; + end + + // data shift from the lowest bit + // sample tdi on the posedge of JTAG clock + always @ (posedge tclk) begin + chain_shifter[CHAIN_DW-1:0] <= chain_shifter_pre[CHAIN_DW-1:0]; + end + + assign chain_idr_data[CHAIN_DW-1:0] = chain_shifter[CHAIN_DW-1:0]; + //============================================== + // calculate the parity bit when read DR + //============================================== + always @ (posedge tclk) begin + if (ctrl_chain_capture_dr) + parity <= 1'b1; + else if (ctrl_chain_shift_dr) + parity <= parity ^ chain_shifter[0]; + end + + //============================================== + // set tdo on the negedge of tclk + // set tdo to logic 1 when IDLE + //============================================== + always @ (negedge tclk or negedge trst_b) begin + if (!trst_b) + tdo <= 1'b1; + else if (dmihardreset) + tdo <= 1'b1; + else if (ctrl_chain_shift_sync) + tdo <= 1'b0; + else if (ctrl_chain_shift_dr || ctrl_chain_shift_ir) + tdo <= chain_shifter[0]; + else if (ctrl_chain_shift_par) + tdo <= parity; + else + tdo <= 1'b1; + end + + //========================================================== + // jtag input and output + //========================================================== + + assign tdi = io_chain_tdi; + + assign chain_io_tdo = tdo; + +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_ctrl.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..8fec6f37d57db4528b21c00ec3f06068775b85fd --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_ctrl.v @@ -0,0 +1,495 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dtm_ctrl #( + parameter DTM_ABITS = 16, + parameter DTM_NDMIREG_WIDTH = 32, + parameter DTM_IRREG_WIDTH = 5, + parameter [6:0] DTM_FSM2_RSTCNT = 7'd80 +)( + input tclk, + input trst_b, + input dmihardreset, + input io_ctrl_tap_en, + input pad_dtm_jtag2_sel, + input pad_dtm_tms_i, + input idr_dmi_mode, + input [DTM_IRREG_WIDTH-1:0] idr_chain_ir, + output ctrl_io_tdo_en, + output ctrl_io_tms_oe, + output ctrl_chain_capture_dr, + output ctrl_chain_capture_ir, + output ctrl_idr_update_ir, + output ctrl_idr_update_dr, + output ctrl_idr_capture_dr, + output ctrl_chain_shift_dr, + output ctrl_chain_shift_ir, + output ctrl_chain_shift_par, + output ctrl_chain_shift_sync +); + + localparam DTM_DMIREG_WIDTH = DTM_ABITS + 2 + 32; + localparam DTM_DMIREG_ACC_WIDTH = DTM_DMIREG_WIDTH - DTM_ABITS; + localparam DTM_DMIACCREG_WIDTH = 1; + + localparam [DTM_IRREG_WIDTH-1:0] IDCODE = 5'h01; + localparam [DTM_IRREG_WIDTH-1:0] DMI_ACC = 5'h02; + localparam [DTM_IRREG_WIDTH-1:0] DTMCS = 5'h10; + localparam [DTM_IRREG_WIDTH-1:0] DMI = 5'h11; + + reg [7:0] fsm2_data_counter; + reg fsm2_parity; + reg fsm2_read_vld; + reg [1:0] fsm2_rs; + reg [1:0] fsm2_rs_counter; + reg [3:0] tap2_cur_st; + reg [3:0] tap2_nxt_st; + reg [6:0] tap2_rst_cnt; + reg [3:0] tap5_cur_st; + reg [3:0] tap5_nxt_st; + reg tdo_en; + reg tms_oe; + + + wire jtag2_sel; + wire fsm2_capture_dr; + wire fsm2_capture_ir; + wire fsm2_load_rs; + wire fsm2_load_rw; + wire fsm2_parity_vld; + wire fsm2_rs_had_dr_dmi_sel; + wire fsm2_rs_had_dr_sel; + wire fsm2_rs_had_dr_ndmi_sel; + wire fsm2_rs_had_ir_sel; + wire fsm2_shift_dr; + wire fsm2_shift_ir; + wire fsm2_shift_vld; + wire fsm2_start_vld; + wire fsm2_sync_vld; + wire fsm2_trn1; + wire fsm2_trn2; + wire fsm2_update_dr; + wire fsm2_update_ir; + wire fsm2_update_vld; + wire fsm5_capture_dr; + wire fsm5_capture_ir; + wire fsm5_shift_dr; + wire fsm5_shift_ir; + wire fsm5_update_dr; + wire fsm5_update_ir; + wire fsm2_rs_had_dr_dmiacc_sel; + wire tap2_rst_vld; + wire tms_i; + wire [7:0] counter_value_dmiacc; + wire [7:0] counter_value_dmi; + wire [7:0] counter_value_ndmi; + wire [7:0] counter_value_ir; + assign tms_i = pad_dtm_tms_i; + assign jtag2_sel = pad_dtm_jtag2_sel; + + //============================================================================== + // TAP5 controller state machine + //============================================================================== + localparam TAP5_RESET = 4'b0000; + localparam TAP5_IDLE = 4'b0001; + localparam TAP5_SELECT_DR_SCAN = 4'b0011; + localparam TAP5_SELECT_IR_SCAN = 4'b0010; + localparam TAP5_CAPTURE_IR = 4'b0110; + localparam TAP5_SHIFT_IR = 4'b0100; + localparam TAP5_EXIT1_IR = 4'b0101; + localparam TAP5_UPDATE_IR = 4'b0111; + localparam TAP5_CAPTURE_DR = 4'b1011; + localparam TAP5_SHIFT_DR = 4'b1010; + localparam TAP5_EXIT1_DR = 4'b1000; + localparam TAP5_UPDATE_DR = 4'b1001; + localparam TAP5_PAUSE_IR = 4'b1101; + localparam TAP5_EXIT2_IR = 4'b1111; + localparam TAP5_PAUSE_DR = 4'b1100; + localparam TAP5_EXIT2_DR = 4'b1110; + + always @ (posedge tclk or negedge trst_b) begin + if (~trst_b) + tap5_cur_st[3:0] <= TAP5_RESET; + else if (dmihardreset) + tap5_cur_st[3:0] <= TAP5_RESET; + else if (jtag2_sel) + tap5_cur_st[3:0] <= TAP5_RESET; + else + tap5_cur_st[3:0] <= tap5_nxt_st[3:0]; + end + + always @ (tap5_cur_st[3:0] or + io_ctrl_tap_en or + tms_i) begin + case(tap5_cur_st[3:0]) + TAP5_RESET: + if (io_ctrl_tap_en & ~tms_i) + tap5_nxt_st[3:0] = TAP5_IDLE; + else + tap5_nxt_st[3:0] = TAP5_RESET; + TAP5_IDLE: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_SELECT_DR_SCAN; + else + tap5_nxt_st[3:0] = TAP5_IDLE; + TAP5_SELECT_DR_SCAN: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_SELECT_IR_SCAN; + else + tap5_nxt_st[3:0] = TAP5_CAPTURE_DR; + TAP5_SELECT_IR_SCAN: + if (~tms_i) + tap5_nxt_st[3:0] = TAP5_CAPTURE_IR; + else + tap5_nxt_st[3:0] = TAP5_RESET; + TAP5_CAPTURE_IR: + if (~tms_i) + tap5_nxt_st[3:0] = TAP5_SHIFT_IR; + else + tap5_nxt_st[3:0] = TAP5_EXIT1_IR; + TAP5_SHIFT_IR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_EXIT1_IR; + else + tap5_nxt_st[3:0] = TAP5_SHIFT_IR; + TAP5_EXIT1_IR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_UPDATE_IR; + else + tap5_nxt_st[3:0] = TAP5_PAUSE_IR; + TAP5_PAUSE_IR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_EXIT2_IR; + else + tap5_nxt_st[3:0] = TAP5_PAUSE_IR; + TAP5_EXIT2_IR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_UPDATE_IR; + else + tap5_nxt_st[3:0] = TAP5_SHIFT_IR; + TAP5_UPDATE_IR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_SELECT_DR_SCAN; + else + tap5_nxt_st[3:0] = TAP5_IDLE; + TAP5_CAPTURE_DR: + if (~tms_i) + tap5_nxt_st[3:0] = TAP5_SHIFT_DR; + else + tap5_nxt_st[3:0] = TAP5_EXIT1_DR; + TAP5_SHIFT_DR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_EXIT1_DR; + else + tap5_nxt_st[3:0] = TAP5_SHIFT_DR; + TAP5_EXIT1_DR: + if (~tms_i) + tap5_nxt_st[3:0] = TAP5_PAUSE_DR; + else + tap5_nxt_st[3:0] = TAP5_UPDATE_DR; + TAP5_PAUSE_DR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_EXIT2_DR; + else + tap5_nxt_st[3:0] = TAP5_PAUSE_DR; + TAP5_EXIT2_DR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_UPDATE_DR; + else + tap5_nxt_st[3:0] = TAP5_SHIFT_DR; + TAP5_UPDATE_DR: + if (tms_i) + tap5_nxt_st[3:0] = TAP5_SELECT_DR_SCAN; + else + tap5_nxt_st[3:0] = TAP5_IDLE; + default: + tap5_nxt_st[3:0] = TAP5_RESET; + endcase + end + + //============================================= + // TAP5 status + //============================================= + assign fsm5_shift_ir = (tap5_cur_st[3:0] == TAP5_SHIFT_IR); + assign fsm5_update_ir = (tap5_cur_st[3:0] == TAP5_UPDATE_IR); + assign fsm5_shift_dr = (tap5_cur_st[3:0] == TAP5_SHIFT_DR); + assign fsm5_update_dr = (tap5_cur_st[3:0] == TAP5_UPDATE_DR); + assign fsm5_capture_dr = (tap5_cur_st[3:0] == TAP5_CAPTURE_DR); + assign fsm5_capture_ir = (tap5_cur_st[3:0] == TAP5_CAPTURE_IR); + + //============================================= + // TDO output enable in JTAG_5 interafce + //============================================= + always @ (negedge tclk or negedge trst_b) begin + if (~trst_b) + tdo_en <= 1'b0; + else if (dmihardreset) + tdo_en <= 1'b0; + else if (fsm5_shift_dr | fsm5_shift_ir) + tdo_en <= 1'b1; + else + tdo_en <= 1'b0; + end + + assign ctrl_io_tdo_en = tdo_en; + + //============================================================================== + // TAP2 controller state machine + //============================================================================== + parameter TAP2_RESET = 4'b0000; + parameter TAP2_START = 4'b0001; + parameter TAP2_RW = 4'b0010; + parameter TAP2_RS = 4'b0011; + parameter TAP2_TRN1 = 4'b0100; + parameter TAP2_DATA = 4'b0101; + parameter TAP2_SYNC = 4'b0110; + parameter TAP2_PARITY = 4'b0111; + parameter TAP2_TRN2 = 4'b1000; + + always @ (posedge tclk or negedge trst_b) begin + if (~trst_b) + tap2_cur_st[3:0] <= TAP2_RESET; + else if (dmihardreset) + tap2_cur_st[3:0] <= TAP2_RESET; + else if ((tap2_rst_vld & tms_i) | (~jtag2_sel)) + tap2_cur_st[3:0] <= TAP2_RESET; + else + tap2_cur_st[3:0] <= tap2_nxt_st[3:0]; + end + + //======================================== + // counter is counting dowwn when + // TMS id high and TCLK is valid + //======================================== + always @ (posedge tclk or negedge trst_b) begin + if (~trst_b) + tap2_rst_cnt[6:0] <= DTM_FSM2_RSTCNT; + else if (dmihardreset) + tap2_rst_cnt[6:0] <= DTM_FSM2_RSTCNT; + else if (~jtag2_sel) + tap2_rst_cnt[6:0] <= DTM_FSM2_RSTCNT; + else if (~tms_i) + tap2_rst_cnt[6:0] <= DTM_FSM2_RSTCNT; + else if (tap2_rst_cnt[6:0] > 7'd0) + tap2_rst_cnt[6:0] <= tap2_rst_cnt[6:0] - 7'd1; + else + tap2_rst_cnt[6:0] <= DTM_FSM2_RSTCNT; + end + + assign tap2_rst_vld = (tap2_rst_cnt[6:0] == 7'd00); + + always @ (tap2_cur_st[3:0] or + io_ctrl_tap_en or + tms_i or + fsm2_rs_counter[1:0] or + fsm2_read_vld or + fsm2_data_counter[7:0] + ) begin + case (tap2_cur_st[3:0]) + TAP2_RESET : begin + if (io_ctrl_tap_en & tms_i) + tap2_nxt_st[3:0] = TAP2_START; + else + tap2_nxt_st[3:0] = TAP2_RESET; + end + + TAP2_START : begin // wait for START bit (tms = 0) + if (~tms_i) // sample START bit, logic 0 + tap2_nxt_st[3:0] = TAP2_RW; + else + tap2_nxt_st[3:0] = TAP2_START; + end + + TAP2_RW : begin // RnW bit, 1=Read Op, 0=Write Op + tap2_nxt_st[3:0] = TAP2_RS; + end + + TAP2_RS : begin // RS[1:0] - Register Group Select + if (fsm2_rs_counter[1:0] == 2'd0) + tap2_nxt_st[3:0] = TAP2_TRN1; + else + tap2_nxt_st[3:0] = TAP2_RS; + end + + TAP2_TRN1 : begin // Turn Around 1 + if (fsm2_read_vld) // Read operation need a sync cycle + tap2_nxt_st[3:0] = TAP2_SYNC; + else // write operation + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_SYNC : begin + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_DATA : begin // IR or DR, Sample or Set + if (fsm2_data_counter[7:0] == 8'd0) + tap2_nxt_st[3:0] = TAP2_PARITY; + else + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_PARITY : begin + tap2_nxt_st[3:0] = TAP2_TRN2; + end + + TAP2_TRN2 : begin + tap2_nxt_st[3:0] = TAP2_START; + end + default : begin + tap2_nxt_st[3:0] = TAP2_RESET; + end + endcase + end + + assign fsm2_start_vld = (tap2_cur_st[3:0] == TAP2_RW); + assign fsm2_load_rw = (tap2_cur_st[3:0] == TAP2_RW); + assign fsm2_load_rs = (tap2_cur_st[3:0] == TAP2_RS); + assign fsm2_trn1 = (tap2_cur_st[3:0] == TAP2_TRN1); + assign fsm2_trn2 = (tap2_cur_st[3:0] == TAP2_TRN2); + assign fsm2_shift_vld = (tap2_cur_st[3:0] == TAP2_DATA); + assign fsm2_update_vld = (tap2_cur_st[3:0] == TAP2_TRN2); + assign fsm2_parity_vld = (tap2_cur_st[3:0] == TAP2_PARITY); + assign fsm2_sync_vld = (tap2_cur_st[3:0] == TAP2_SYNC); + + //========================================= + // load the RW + //========================================= + always @ (posedge tclk) begin + if (fsm2_load_rw) + fsm2_read_vld <= tms_i; + end + + //=========================================== + // load the RS[1:0] + //=========================================== + always @ (posedge tclk) begin + if (fsm2_start_vld) + fsm2_rs_counter[1:0] <= 2'd1; + else if (dmihardreset) + fsm2_rs_counter[1:0] <= 2'd1; + else if (fsm2_load_rs) + fsm2_rs_counter[1:0] <= fsm2_rs_counter[1:0] - 2'd1; + else + fsm2_rs_counter[1:0] <= fsm2_rs_counter[1:0]; + end + + always @ (posedge tclk) begin + if (fsm2_load_rs) + fsm2_rs[1:0] <= {tms_i, fsm2_rs[1]}; + else + fsm2_rs[1:0] <= fsm2_rs[1:0]; + end + + assign fsm2_rs_had_ir_sel = fsm2_rs[1:0] == 2'b10; //IR + assign fsm2_rs_had_dr_sel = fsm2_rs[1:0] == 2'b11; //DR + assign fsm2_rs_had_dr_dmiacc_sel = fsm2_rs_had_dr_sel & (idr_chain_ir[DTM_IRREG_WIDTH-1:0] == DMI_ACC); + assign fsm2_rs_had_dr_dmi_sel = fsm2_rs_had_dr_sel & (idr_chain_ir[DTM_IRREG_WIDTH-1:0] == DMI); + assign fsm2_rs_had_dr_ndmi_sel = fsm2_rs_had_dr_sel & (idr_chain_ir[DTM_IRREG_WIDTH-1:0] == IDCODE | idr_chain_ir[DTM_IRREG_WIDTH-1:0] == DTMCS); + + //=========================================== + // intialize DATA shift length + //=========================================== + always @ (posedge tclk) begin + if (fsm2_trn1) begin + if (fsm2_rs_had_dr_dmiacc_sel) + fsm2_data_counter[7:0] <= {8{1'b0}}; //DTM_DMIACCREG_WIDTH - 1'b1 + else if (fsm2_rs_had_dr_dmi_sel) begin + if (idr_dmi_mode) + fsm2_data_counter[7:0] <= counter_value_dmiacc[7:0]; //34 - 1, to fix lint + else + fsm2_data_counter[7:0] <= counter_value_dmi[7:0]; //50 - 1, to fix lint + end else if (fsm2_rs_had_dr_ndmi_sel) + fsm2_data_counter[7:0] <= counter_value_ndmi[7:0]; //32 - 1, to fix lint + else if (fsm2_rs_had_ir_sel) + fsm2_data_counter[7:0] <= counter_value_ir[7:0]; //5 - 1, to fix lint + else + fsm2_data_counter[7:0] <= {8{1'b0}}; + end + else if (fsm2_shift_vld) + fsm2_data_counter[7:0] <= fsm2_data_counter[7:0] - {{7{1'b0}},1'b1}; + end + + assign counter_value_dmiacc[7:0] = $unsigned(DTM_DMIREG_ACC_WIDTH-1) & {8{1'b1}}; //34 -1 + assign counter_value_dmi[7:0] = $unsigned(DTM_DMIREG_WIDTH-1) & {8{1'b1}}; //44 -1 + assign counter_value_ndmi[7:0] = $unsigned(DTM_NDMIREG_WIDTH-1) & {8{1'b1}}; //32-1 + assign counter_value_ir[7:0] = $unsigned(DTM_IRREG_WIDTH-1) & {8{1'b1}}; //5-1 + + //================================================ + // TMS output Enable + //================================================ + always @ (posedge tclk or negedge trst_b) begin + if (~trst_b) + tms_oe <= 1'b0; // default is input + else if (dmihardreset) + tms_oe <= 1'b0; // default is input + else if (fsm2_trn1 & fsm2_read_vld) + tms_oe <= 1'b1; + else if (fsm2_trn2) + tms_oe <= 1'b0; + else + tms_oe <= tms_oe; + end + + assign ctrl_io_tms_oe = tms_oe; + + //================================================ + // Parity Check + //================================================ + always @ (posedge tclk) begin + if (fsm2_start_vld) + fsm2_parity <= 1'b1; + else if ((fsm2_rs_had_dr_sel | fsm2_rs_had_ir_sel) & fsm2_shift_vld) + fsm2_parity <= fsm2_parity ^ tms_i; // calculate the parity bit + else if (fsm2_parity_vld) + fsm2_parity <= fsm2_parity ^ tms_i; // check received parity bit + else + fsm2_parity <= fsm2_parity; + end + + assign fsm2_shift_ir = fsm2_rs_had_ir_sel & fsm2_shift_vld; + assign fsm2_shift_dr = fsm2_rs_had_dr_sel & fsm2_shift_vld; + assign fsm2_capture_dr = fsm2_rs_had_dr_sel & fsm2_read_vld & fsm2_trn1; + assign fsm2_capture_ir = fsm2_rs_had_ir_sel & fsm2_read_vld & fsm2_trn1; + assign fsm2_update_ir = fsm2_update_vld & (~fsm2_read_vld) & fsm2_rs_had_ir_sel & (~fsm2_parity); + assign fsm2_update_dr = fsm2_update_vld & (~fsm2_read_vld) & fsm2_rs_had_dr_sel & (~fsm2_parity); + + assign ctrl_chain_shift_ir = fsm5_shift_ir | fsm2_shift_ir; + assign ctrl_chain_shift_dr = fsm5_shift_dr | fsm2_shift_dr; + assign ctrl_chain_capture_dr = fsm5_capture_dr | fsm2_capture_dr; + assign ctrl_chain_capture_ir = fsm5_capture_ir | fsm2_capture_ir; + assign ctrl_chain_shift_par = fsm2_parity_vld; + assign ctrl_chain_shift_sync = fsm2_sync_vld; + assign ctrl_idr_update_ir = fsm5_update_ir | fsm2_update_ir; + assign ctrl_idr_update_dr = fsm5_update_dr | fsm2_update_dr; + assign ctrl_idr_capture_dr = fsm5_capture_dr | fsm2_capture_dr; + + `ifdef ASSERTION + property jtag2_read_not_update_idr; + @(posedge tclk) (jtag2_sel & fsm2_read_vld) |-> ~(fsm2_update_ir | fsm2_update_dr); + endproperty + assert property(jtag2_read_not_update_idr); + + property jtag2_write_not_capture_idr; + @(posedge tclk) (jtag2_sel & ~fsm2_read_vld) |-> ~(fsm2_capture_ir | fsm2_capture_dr); + endproperty + assert property(jtag2_write_not_capture_idr); + `endif +endmodule + + + + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_idr.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_idr.v new file mode 100644 index 0000000000000000000000000000000000000000..019af953e6c791c896297f72a6cdcabb806b2b69 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_idr.v @@ -0,0 +1,245 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dtm_idr #( + parameter DTM_IRREG_WIDTH = 5, + parameter DTM_ABITS = 16, + parameter DTM_NDMIREG_WIDTH = 32, + parameter CHAIN_DW = DTM_ABITS + 32 + 2 + +)( + input tclk, + input trst_b, + output [CHAIN_DW-1:0] idr_chain_dr, + output [DTM_IRREG_WIDTH-1:0] idr_chain_ir, + input [CHAIN_DW-1:0] chain_idr_data, + output idr_dmi_mode, + input ctrl_idr_update_ir, + input ctrl_idr_update_dr, + input ctrl_idr_capture_dr, + output reg dmihardreset, + + output dtm_apbm_wr_vld, + output [DTM_ABITS-1:0] dtm_apbm_wr_addr, + output [1:0] dtm_apbm_wr_flg, + output [31:0] dtm_apbm_wdata, + input [31:0] apbm_dtm_rdata, + input apbm_dtm_wr_ready +); + + localparam [DTM_IRREG_WIDTH-1:0] IDCODE = 5'h01; + localparam [DTM_IRREG_WIDTH-1:0] DMI_ACC = 5'h02; + localparam [DTM_IRREG_WIDTH-1:0] DTMCS = 5'h10; + localparam [DTM_IRREG_WIDTH-1:0] DMI = 5'h11; + localparam [DTM_NDMIREG_WIDTH-1:0] IDCODE_REG_DEFINE = {4'h1, 16'h0, 12'b1011_011_0111_1}; + localparam [3:0] DTM_VERSION = 4'h1; + localparam [2:0] IDLE_CYCLE = `TDT_DMI_IDLE_CYCLE; + + reg [DTM_IRREG_WIDTH-1:0] dtm_ir; + wire [DTM_NDMIREG_WIDTH-1:0] dtm_idcode; + //reg dmihardreset; + reg dmireset; + wire [2:0] idle; + wire [1:0] dmistat; + wire [5:0] abits; + wire [3:0] version; + reg [DTM_ABITS-1:0] address; + reg [31:0] data; + reg [1:0] op; + reg mode; + reg [1:0] op_stat; + reg wr_vld; + reg dmi_req_running; + reg [CHAIN_DW-1:0] data_out; + + wire capture_dmi_in_running; + wire [CHAIN_DW-1:0] dmi_total; + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + dtm_ir[DTM_IRREG_WIDTH-1:0] <= IDCODE; + else if (dmihardreset) + dtm_ir[DTM_IRREG_WIDTH-1:0] <= IDCODE; + else if (ctrl_idr_update_ir) + dtm_ir[DTM_IRREG_WIDTH-1:0] <= chain_idr_data[DTM_IRREG_WIDTH-1:0]; + + end + + assign dtm_idcode[DTM_NDMIREG_WIDTH-1:0] = IDCODE_REG_DEFINE; + + assign idle[2:0] = IDLE_CYCLE; + assign dmistat[1:0] = op_stat[1:0]; + assign abits[5:0] = DTM_ABITS; + assign version[3:0] = DTM_VERSION; + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + dmihardreset <= 1'b0; + else if (dmihardreset) + dmihardreset <= 1'b0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DTMCS) + dmihardreset <= chain_idr_data[17]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + dmireset <= 1'b0; + else if (dmihardreset) + dmireset <= 1'b0; + else if (dmireset) + dmireset <= 1'b0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DTMCS) + dmireset <= chain_idr_data[16]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + mode <= 1'b0; + else if (dmihardreset) + mode <= 1'b0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI_ACC) + mode <= chain_idr_data[0]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + address[DTM_ABITS-1:0] <= {DTM_ABITS{1'b0}}; + else if (dmihardreset) + address[DTM_ABITS-1:0] <= {DTM_ABITS{1'b0}}; + else if (ctrl_idr_update_dr && !mode && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI && !dmi_req_running) + address[DTM_ABITS-1:0] <= chain_idr_data[34 +: DTM_ABITS]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + data[31:0] <= 32'h0; + else if (dmihardreset) + data[31:0] <= 32'h0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI && !dmi_req_running) + data[31:0] <= chain_idr_data[33:2]; + else if (apbm_dtm_wr_ready && op[1:0] == 2'b01) + //else if (apbm_dtm_wr_ready) + data[31:0] <= apbm_dtm_rdata[31:0]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + op[1:0] <= 2'b0; + else if (dmihardreset) + op[1:0] <= 2'b0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI && !dmi_req_running) + op[1:0] <= chain_idr_data[1:0]; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + wr_vld <= 1'b0; + else if (dmihardreset) + wr_vld <= 1'b0; + else if (wr_vld) + wr_vld <= 1'b0; + else if (ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI && (^chain_idr_data[1:0]) + && op_stat[1:0] == 2'b0 && !dmi_req_running) + wr_vld <= 1'b1; + end + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + dmi_req_running <= 1'b0; + else if (dmihardreset) + dmi_req_running <= 1'b0; + else if (apbm_dtm_wr_ready) + dmi_req_running <= 1'b0; + else if (wr_vld) + dmi_req_running <= 1'b1; + end + + assign capture_dmi_in_running = dmi_req_running && ctrl_idr_capture_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI; + + always @ (posedge tclk or negedge trst_b) begin + if (!trst_b) + op_stat[1:0] <= 2'b0; + else if (dmihardreset) + op_stat[1:0] <= 2'b0; + else if (dmireset) + op_stat[1:0] <= 2'b0; + else if (dmi_req_running && ctrl_idr_update_dr && dtm_ir[DTM_IRREG_WIDTH-1:0] == DMI && (^chain_idr_data[1:0]) || + capture_dmi_in_running) + op_stat[1:0] <= 2'b11; + end + + assign dmi_total[CHAIN_DW-1:0] = capture_dmi_in_running ? {address[DTM_ABITS-1:0], data[31:0], 2'b11} : {address[DTM_ABITS-1:0], data[31:0], op_stat[1:0]}; + + //generate + // if ((CHAIN_DW-DTM_ABITS-34) == 0) begin : gen_full_dmi + // assign dmi_total = {address, data, op_stat}; + // end else begin : gen_pad_dmi + // assign dmi_total = {{CHAIN_DW-DTM_ABITS-34{1'b0}}, address, data, op_stat}; + // end + //endgenerate + + always @ (dtm_ir[DTM_IRREG_WIDTH-1:0] or + dtm_idcode[DTM_NDMIREG_WIDTH-1:0] or + mode or + idle[2:0] or + dmistat[1:0] or + abits[5:0] or + version[3:0] or + dmi_total[CHAIN_DW-1:0] + ) begin + case (dtm_ir[DTM_IRREG_WIDTH-1:0]) + IDCODE : data_out[CHAIN_DW-1:0] = {{CHAIN_DW-DTM_NDMIREG_WIDTH{1'b0}}, dtm_idcode[DTM_NDMIREG_WIDTH-1:0]}; + DMI_ACC : data_out[CHAIN_DW-1:0] = {{CHAIN_DW-1{1'b0}}, mode}; + DTMCS : data_out[CHAIN_DW-1:0] = {{CHAIN_DW-15{1'b0}}, idle[2:0], dmistat[1:0], abits[5:0], version[3:0]}; + DMI : data_out[CHAIN_DW-1:0] = dmi_total[CHAIN_DW-1:0]; + default : data_out[CHAIN_DW-1:0] = {CHAIN_DW{1'b0}}; + endcase + end + + assign idr_dmi_mode = mode; + assign idr_chain_dr[CHAIN_DW-1:0] = data_out[CHAIN_DW-1:0]; + assign idr_chain_ir[DTM_IRREG_WIDTH-1:0] = dtm_ir[DTM_IRREG_WIDTH-1:0]; + assign dtm_apbm_wr_vld = wr_vld; + assign dtm_apbm_wr_flg[1:0] = op[1:0]; + assign dtm_apbm_wr_addr[DTM_ABITS-1:0] = address[DTM_ABITS-1:0]; + assign dtm_apbm_wdata[31:0] = data[31:0]; + + `ifdef ASSERTION + property update_dr_in_dmi_running_cannot_change_dmi_address; + @(posedge tclk) (dmi_req_running && !dmihardreset) |-> $stable(address[DTM_ABITS-1:0]); + endproperty + assert property(update_dr_in_dmi_running_cannot_change_dmi_address); + + property update_dr_in_dmi_running_cannot_change_dmi_op; + @(posedge tclk) (dmi_req_running && !dmihardreset) |-> $stable(op[1:0]); + endproperty + assert property(update_dr_in_dmi_running_cannot_change_dmi_op); + + property update_dr_in_dmi_running_cannot_change_dmi_data; + @(posedge tclk) (dmi_req_running && !dmihardreset && !apbm_dtm_wr_ready) |-> $stable(data[31:0]); + endproperty + assert property(update_dr_in_dmi_running_cannot_change_dmi_data); + + property update_dr_in_dmi_running_cannot_start_a_new_operation; + @(posedge tclk) (dmi_req_running && !dmihardreset) |=> $stable(wr_vld); + endproperty + assert property(update_dr_in_dmi_running_cannot_start_a_new_operation); + + property set_op_when_capture_dr_in_dmi_running; + @(posedge tclk) (dmi_req_running && ctrl_idr_capture_dr && dtm_ir == DMI) |-> (dmi_total[1:0] == 2'b11); + endproperty + assert property(set_op_when_capture_dr_in_dmi_running); + `endif + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_io.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_io.v new file mode 100644 index 0000000000000000000000000000000000000000..f1eebc8cd28101f0eef0db7534c559844fda7d2c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_io.v @@ -0,0 +1,41 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dtm_io( + input pad_dtm_jtag2_sel, + input pad_dtm_tap_en, + input pad_dtm_tdi, + input pad_dtm_tms_i, + output dtm_pad_tdo, + output dtm_pad_tdo_en, + output dtm_pad_tms_o, + output dtm_pad_tms_oe, + input chain_io_tdo, + input ctrl_io_tdo_en, + input ctrl_io_tms_oe, + output io_chain_tdi, + output io_ctrl_tap_en +); + + assign io_ctrl_tap_en = pad_dtm_tap_en; + assign io_chain_tdi = pad_dtm_jtag2_sel ? pad_dtm_tms_i : pad_dtm_tdi; + assign dtm_pad_tdo = chain_io_tdo; + assign dtm_pad_tms_o = chain_io_tdo; + assign dtm_pad_tdo_en = ctrl_io_tdo_en; + assign dtm_pad_tms_oe = ctrl_io_tms_oe; + +endmodule + + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_top.v new file mode 100644 index 0000000000000000000000000000000000000000..406edfae13644e08dcad0f97cfb0b6d8085fc42c --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/debug/tdt_dtm_top.v @@ -0,0 +1,152 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dtm_top #( + parameter DTM_ABITS = 16 +)( + input pad_dtm_tclk, + input pad_dtm_trst_b, + input pad_dtm_jtag2_sel, + input pad_dtm_tap_en, + input pad_dtm_tdi, + input pad_dtm_tms_i, + output dtm_pad_tdo, + output dtm_pad_tdo_en, + output dtm_pad_tms_o, + output dtm_pad_tms_oe, + + output dtm_apbm_wr_vld, + output [DTM_ABITS-1:0] dtm_apbm_wr_addr, + output [1:0] dtm_apbm_wr_flg, + output [31:0] dtm_apbm_wdata, + output dmihardreset, + input [31:0] apbm_dtm_rdata, + input apbm_dtm_wr_ready +); + + localparam DTM_NDMIREG_WIDTH = 32; + localparam DTM_IRREG_WIDTH = 5; + localparam DTM_FSM2_RSTCNT = 80; + localparam CHAIN_DW = DTM_ABITS + 32 + 2; + + wire chain_io_tdo; + wire ctrl_io_tdo_en; + wire ctrl_io_tms_oe; + wire io_chain_tdi; + wire io_ctrl_tap_en; + wire idr_dmi_mode; + wire ctrl_chain_capture_dr; + wire ctrl_chain_capture_ir; + wire ctrl_idr_update_ir; + wire ctrl_idr_update_dr; + wire ctrl_idr_capture_dr; + wire ctrl_chain_shift_dr; + wire ctrl_chain_shift_ir; + wire ctrl_chain_shift_par; + wire ctrl_chain_shift_sync; + wire [CHAIN_DW-1:0] idr_chain_dr; + wire [DTM_IRREG_WIDTH-1:0] idr_chain_ir; + wire [CHAIN_DW-1:0] chain_idr_data; + + tdt_dtm_io x_tdt_dtm_io ( + .pad_dtm_jtag2_sel (pad_dtm_jtag2_sel), + .pad_dtm_tap_en (pad_dtm_tap_en), + .pad_dtm_tdi (pad_dtm_tdi), + .pad_dtm_tms_i (pad_dtm_tms_i), + .dtm_pad_tdo (dtm_pad_tdo), + .dtm_pad_tdo_en (dtm_pad_tdo_en), + .dtm_pad_tms_o (dtm_pad_tms_o), + .dtm_pad_tms_oe (dtm_pad_tms_oe), + .chain_io_tdo (chain_io_tdo), + .ctrl_io_tdo_en (ctrl_io_tdo_en), + .ctrl_io_tms_oe (ctrl_io_tms_oe), + .io_chain_tdi (io_chain_tdi), + .io_ctrl_tap_en (io_ctrl_tap_en) + ); + + tdt_dtm_ctrl #( + .DTM_ABITS (DTM_ABITS), + .DTM_NDMIREG_WIDTH (DTM_NDMIREG_WIDTH), + .DTM_IRREG_WIDTH (DTM_IRREG_WIDTH), + .DTM_FSM2_RSTCNT (DTM_FSM2_RSTCNT[6:0]) + ) x_tdt_dtm_ctrl ( + .tclk (pad_dtm_tclk), + .trst_b (pad_dtm_trst_b), + .dmihardreset (dmihardreset), + .io_ctrl_tap_en (io_ctrl_tap_en), + .pad_dtm_jtag2_sel (pad_dtm_jtag2_sel), + .pad_dtm_tms_i (pad_dtm_tms_i), + .idr_dmi_mode (idr_dmi_mode), + .idr_chain_ir (idr_chain_ir[DTM_IRREG_WIDTH-1:0]), + .ctrl_io_tdo_en (ctrl_io_tdo_en), + .ctrl_io_tms_oe (ctrl_io_tms_oe), + .ctrl_chain_capture_dr (ctrl_chain_capture_dr), + .ctrl_chain_capture_ir (ctrl_chain_capture_ir), + .ctrl_idr_update_ir (ctrl_idr_update_ir), + .ctrl_idr_update_dr (ctrl_idr_update_dr), + .ctrl_idr_capture_dr (ctrl_idr_capture_dr), + .ctrl_chain_shift_dr (ctrl_chain_shift_dr), + .ctrl_chain_shift_ir (ctrl_chain_shift_ir), + .ctrl_chain_shift_par (ctrl_chain_shift_par), + .ctrl_chain_shift_sync (ctrl_chain_shift_sync) + ); + + tdt_dtm_chain #( + .CHAIN_DW (CHAIN_DW), + .DTM_IRREG_WIDTH (DTM_IRREG_WIDTH), + .DTM_ABITS (DTM_ABITS), + .DTM_NDMIREG_WIDTH (DTM_NDMIREG_WIDTH) + ) x_tdt_dtm_chain ( + .tclk (pad_dtm_tclk), + .trst_b (pad_dtm_trst_b), + .dmihardreset (dmihardreset), + .io_chain_tdi (io_chain_tdi), + .chain_io_tdo (chain_io_tdo), + .idr_chain_dr (idr_chain_dr), + .idr_chain_ir (idr_chain_ir), + .chain_idr_data (chain_idr_data), + .idr_dmi_mode (idr_dmi_mode), + .ctrl_chain_capture_dr (ctrl_chain_capture_dr), + .ctrl_chain_capture_ir (ctrl_chain_capture_ir), + .ctrl_chain_shift_dr (ctrl_chain_shift_dr), + .ctrl_chain_shift_ir (ctrl_chain_shift_ir), + .ctrl_chain_shift_par (ctrl_chain_shift_par), + .ctrl_chain_shift_sync (ctrl_chain_shift_sync) + ); + + tdt_dtm_idr #( + .CHAIN_DW (CHAIN_DW), + .DTM_IRREG_WIDTH (DTM_IRREG_WIDTH), + .DTM_ABITS (DTM_ABITS[5:0]), + .DTM_NDMIREG_WIDTH (DTM_NDMIREG_WIDTH) + ) x_tdt_dtm_idr ( + .tclk (pad_dtm_tclk), + .trst_b (pad_dtm_trst_b), + .dmihardreset (dmihardreset), + .idr_chain_dr (idr_chain_dr), + .idr_chain_ir (idr_chain_ir), + .idr_dmi_mode (idr_dmi_mode), + .chain_idr_data (chain_idr_data), + .ctrl_idr_update_ir (ctrl_idr_update_ir), + .ctrl_idr_update_dr (ctrl_idr_update_dr), + .ctrl_idr_capture_dr (ctrl_idr_capture_dr), + .dtm_apbm_wr_vld (dtm_apbm_wr_vld), + .dtm_apbm_wr_addr (dtm_apbm_wr_addr), + .dtm_apbm_wr_flg (dtm_apbm_wr_flg), + .dtm_apbm_wdata (dtm_apbm_wdata), + .apbm_dtm_rdata (apbm_dtm_rdata), + .apbm_dtm_wr_ready (apbm_dtm_wr_ready) + ); + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_define.h b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_define.h new file mode 100644 index 0000000000000000000000000000000000000000..bd3908be05e4cf97ad0848bbf425a004efd1620f --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_define.h @@ -0,0 +1,161 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +`ifdef TDT_DM_EXT_TRIGGER_EN + `define TDT_DM_GROUP_TRI_EN +`else + `ifdef PROCESSOR_3 + `define TDT_DM_GROUP_TRI_EN + `else + `ifdef PROCESSOR_2 + `define TDT_DM_GROUP_TRI_EN + `else + `ifdef PROCESSOR_1 + `define TDT_DM_GROUP_TRI_EN + `endif + `endif + `endif +`endif + +`ifdef TDT_DM_EXT_TRIGGER_EN + `ifdef TDT_DM_EXTHALTTRI_4 + `define TDT_DM_EXTHALTTRI_NUM 4 + `endif + `ifdef TDT_DM_EXTHALTTRI_3 + `define TDT_DM_EXTHALTTRI_NUM 3 + `endif + `ifdef TDT_DM_EXTHALTTRI_2 + `define TDT_DM_EXTHALTTRI_NUM 2 + `endif + `ifdef TDT_DM_EXTHALTTRI_1 + `define TDT_DM_EXTHALTTRI_NUM 1 + `endif + + `ifdef TDT_DM_EXTRESUMETRI_4 + `define TDT_DM_EXTRESUMETRI_NUM 4 + `endif + `ifdef TDT_DM_EXTRESUMETRI_3 + `define TDT_DM_EXTRESUMETRI_NUM 3 + `endif + `ifdef TDT_DM_EXTRESUMETRI_2 + `define TDT_DM_EXTRESUMETRI_NUM 2 + `endif + `ifdef TDT_DM_EXTRESUMETRI_1 + `define TDT_DM_EXTRESUMETRI_NUM 1 + `endif +`endif + + +`ifdef TDT_DM_CORE_RV64 + `define TDT_DM_CORE_ISA 4'h0 +`else + `ifdef TDT_DM_CORE_RV32 + `define TDT_DM_CORE_ISA 4'h1 + `else + `define TDT_DM_CORE_ISA 4'h2 + `endif +`endif + + +`ifdef TDT_DM_CORE_RV64 + `define TDT_DM_CORE_MAX_XLEN 64 +`else + `define TDT_DM_CORE_MAX_XLEN 32 +`endif + +`ifdef PROCESSOR_3 + `define TDT_DM_CORE_NUM 4 + `define TDT_DM_ALLCORE_NSCRATCH {`TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH} + `define TDT_DM_ALLCORE_ISA {`TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA} +`else + `ifdef PROCESSOR_2 + `define TDT_DM_CORE_NUM 3 + `define TDT_DM_ALLCORE_NSCRATCH {`TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH} + `define TDT_DM_ALLCORE_ISA {`TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA} + `else + `ifdef PROCESSOR_1 + `define TDT_DM_CORE_NUM 2 + `define TDT_DM_ALLCORE_NSCRATCH {`TDT_DM_CORE_NSCRATCH, `TDT_DM_CORE_NSCRATCH} + `define TDT_DM_ALLCORE_ISA {`TDT_DM_CORE_ISA, `TDT_DM_CORE_ISA} + `else + `define TDT_DM_CORE_NUM 1 + `define TDT_DM_SINGLE_CORE + `define TDT_DM_ALLCORE_NSCRATCH `TDT_DM_CORE_NSCRATCH + `define TDT_DM_ALLCORE_ISA `TDT_DM_CORE_ISA + `endif + `endif +`endif + +`ifdef TDT_DM_PB_EN + `ifdef TDT_DM_IEBREAK + `define TDT_DM_IMPEBREAK 1'b1 + `else + `define TDT_DM_IMPEBREAK 1'b0 + `endif + //to fix lint warning + `define PB_SIZE_WITH_WIDTH 5'd`TDT_DM_PB_SIZE +`else + `define TDT_DM_IMPEBREAK 1'b0 +`endif + +//`define TDT_DM_BUF_MOVE + +`ifdef TDT_DM_BUF_MOVE + `define TDT_DM_CUSTOM_BUF_CNT 8 +`endif + +//`define TDT_TRACE_ENC_EN + +`ifdef TDT_TRACE_ENC_EN + `ifdef PROCESSOR_3 + `define TDT_COMP_NUM 5 + `else + `ifdef PROCESSOR_2 + `define TDT_COMP_NUM 4 + `else + `ifdef PROCESSOR_1 + `define TDT_COMP_NUM 3 + `else + `define TDT_COMP_NUM 2 + `endif + `endif + `endif +`else + `define TDT_COMP_NUM 1 + `define TDT_SINGLE_COMP +`endif + +`define TDT_ACC_CSR + +`ifdef TDT_DM_SBA_DW_128 + `define TDT_DM_SBA_DW 128 + `define TDT_DM_SBA_BW 16 +`else + `ifdef TDT_DM_SBA_DW_64 + `define TDT_DM_SBA_DW 64 + `define TDT_DM_SBA_BW 8 + `else + `define TDT_DM_SBA_DW 32 + `define TDT_DM_SBA_BW 4 + `endif +`endif + +//to fix lint warning +`ifdef TDT_DM_SBA + `define SBAW_WITH_WIDTH 7'd`TDT_DM_SBAW +`endif +//========================================================== +// INTERNAL DEFINES END +//========================================================== diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dm_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dm_top.v new file mode 100644 index 0000000000000000000000000000000000000000..d2f8929ecd9c7cbe47b62c8e7205f807f6ca897b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dm_top.v @@ -0,0 +1,415 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dm_top ( + sys_apb_clk, + sys_apb_rst_b, + forever_cpuclk, + ciu_rst_b, + sys_bus_clk_en, + + pad_yy_icg_scan_en, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + + tdt_dmi_paddr, + tdt_dmi_pwrite, + tdt_dmi_psel, + tdt_dmi_penable, + tdt_dmi_pwdata, + tdt_dmi_prdata, + tdt_dmi_pready, + tdt_dmi_pslverr, + + + tdt_dm_pad_ndmreset_n, + tdt_dm_pad_hartreset_n, + + tdt_dm_dtu_halt_req, + tdt_dm_dtu_async_halt_req, + tdt_dm_dtu_resume_req, + tdt_dm_dtu_halt_on_reset, + tdt_dm_dtu_halt_req_cause, + dtu_tdt_dm_halted, + dtu_tdt_dm_havereset, + tdt_dm_dtu_ack_havereset, + pad_tdt_dm_core_unavail, + tdt_dm_dtu_itr, + tdt_dm_dtu_itr_vld, + dtu_tdt_dm_itr_done, + dtu_tdt_dm_retire_debug_expt_vld, + tdt_dm_dtu_wr_vld, + tdt_dm_dtu_wr_flg, + tdt_dm_dtu_wdata, + dtu_tdt_dm_wr_ready, + dtu_tdt_dm_rx_data + +`ifdef TDT_DM_EXT_TRIGGER_EN + , + pad_tdt_dm_halt_req, + tdt_dm_pad_halt_req, + pad_tdt_dm_resume_req, + tdt_dm_pad_resume_req +`endif + +`ifdef TDT_DM_SBA +`ifdef TDT_DM_SBA_AXI + , + tdt_dm_pad_awid, + tdt_dm_pad_awaddr, + tdt_dm_pad_awlen, + tdt_dm_pad_awsize, + tdt_dm_pad_awvalid, + pad_tdt_dm_awready, + tdt_dm_pad_wdata, + tdt_dm_pad_wvalid, + tdt_dm_pad_wlast, + tdt_dm_pad_wstrb, + pad_tdt_dm_wready, + tdt_dm_pad_bready, + pad_tdt_dm_bid, + pad_tdt_dm_bresp, + pad_tdt_dm_bvalid, + tdt_dm_pad_arid, + tdt_dm_pad_araddr, + tdt_dm_pad_arlen, + tdt_dm_pad_arsize, + tdt_dm_pad_arvalid, + pad_tdt_dm_arready, + pad_tdt_dm_rid, + pad_tdt_dm_rdata, + pad_tdt_dm_rvalid, + pad_tdt_dm_rlast, + pad_tdt_dm_rresp, + tdt_dm_pad_rready, + tdt_dm_pad_awburst, + tdt_dm_pad_awcache, + tdt_dm_pad_awlock, + tdt_dm_pad_awprot, + tdt_dm_pad_arburst, + tdt_dm_pad_arcache, + tdt_dm_pad_arlock, + tdt_dm_pad_arprot +`endif +`ifdef TDT_DM_SBA_AHB + , + tdt_dm_pad_hprot, + tdt_dm_pad_hmastlock, + tdt_dm_pad_htrans, + tdt_dm_pad_haddr, + tdt_dm_pad_hwrite, + tdt_dm_pad_hburst, + tdt_dm_pad_hsize, + tdt_dm_pad_hwdata, + pad_tdt_dm_hrdata, + pad_tdt_dm_hready, + pad_tdt_dm_hresp +`endif +`endif +); + + parameter [31:0] TDT_NEXT_DM_BA = `TDT_DM_NEXTDM_BA; + + + input sys_apb_clk; + input sys_apb_rst_b; + input forever_cpuclk; + input ciu_rst_b; + input sys_bus_clk_en; + input pad_yy_icg_scan_en; + input pad_yy_scan_mode; + input pad_yy_scan_rst_b; + + input [11:0] tdt_dmi_paddr; + input tdt_dmi_pwrite; +`ifdef TDT_SINGLE_COMP + input tdt_dmi_psel; +`else + input [`TDT_COMP_NUM-1:0] tdt_dmi_psel; +`endif + input tdt_dmi_penable; + input [31:0] tdt_dmi_pwdata; + output [`TDT_COMP_NUM*32-1:0] tdt_dmi_prdata; +`ifdef TDT_SINGLE_COMP + output tdt_dmi_pready; + output tdt_dmi_pslverr; +`else + output [`TDT_COMP_NUM-1:0] tdt_dmi_pready; + output [`TDT_COMP_NUM-1:0] tdt_dmi_pslverr; +`endif + +//========================================================== +// tdt to ciu reset +//========================================================== + output tdt_dm_pad_ndmreset_n; +`ifdef TDT_DM_SINGLE_CORE + output tdt_dm_pad_hartreset_n; +`else + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_pad_hartreset_n; +`endif + +//========================================================== +// interface between tdt and core +//========================================================== +`ifdef TDT_DM_SINGLE_CORE + output tdt_dm_dtu_halt_req; + output tdt_dm_dtu_async_halt_req; + output tdt_dm_dtu_resume_req; + output tdt_dm_dtu_halt_on_reset; + output [1:0] tdt_dm_dtu_halt_req_cause; + input dtu_tdt_dm_halted; + input dtu_tdt_dm_havereset; + output tdt_dm_dtu_ack_havereset; + input pad_tdt_dm_core_unavail; + output [31:0] tdt_dm_dtu_itr; + output tdt_dm_dtu_itr_vld; + input dtu_tdt_dm_itr_done; + input dtu_tdt_dm_retire_debug_expt_vld; + output tdt_dm_dtu_wr_vld; + output [1:0] tdt_dm_dtu_wr_flg; + output [`TDT_DM_CORE_MAX_XLEN-1:0] tdt_dm_dtu_wdata; + input dtu_tdt_dm_wr_ready; + input [`TDT_DM_CORE_MAX_XLEN*`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_rx_data; +`else + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_halt_req; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_async_halt_req; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_resume_req; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_halt_on_reset; + output [`TDT_DM_CORE_NUM*2-1:0] tdt_dm_dtu_halt_req_cause; + input [`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_halted; + input [`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_havereset; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_ack_havereset; + input [`TDT_DM_CORE_NUM-1:0] pad_tdt_dm_core_unavail; + output [31:0] tdt_dm_dtu_itr; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_itr_vld; + input [`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_itr_done; + input [`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_retire_debug_expt_vld; + output [`TDT_DM_CORE_NUM-1:0] tdt_dm_dtu_wr_vld; + output [1:0] tdt_dm_dtu_wr_flg; + output [`TDT_DM_CORE_MAX_XLEN-1:0] tdt_dm_dtu_wdata; + input [`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_wr_ready; + input [`TDT_DM_CORE_MAX_XLEN*`TDT_DM_CORE_NUM-1:0] dtu_tdt_dm_rx_data; +`endif + +//========================================================== +// halt/resume trigger interface between tdt and other +// cluster +//========================================================== +`ifdef TDT_DM_EXT_TRIGGER_EN + + input [`TDT_DM_EXTHALTTRI_NUM-1:0] pad_tdt_dm_halt_req; + output [`TDT_DM_EXTHALTTRI_NUM-1:0] tdt_dm_pad_halt_req; + input [`TDT_DM_EXTRESUMETRI_NUM-1:0] pad_tdt_dm_resume_req; + output [`TDT_DM_EXTRESUMETRI_NUM-1:0] tdt_dm_pad_resume_req; +`endif + +//========================================================== +// dm system bus access axi master +//========================================================== +`ifdef TDT_DM_SBA +`ifdef TDT_DM_SBA_AXI + + output [3:0] tdt_dm_pad_awid; + output [`TDT_DM_SBAW-1:0] tdt_dm_pad_awaddr; + output [3:0] tdt_dm_pad_awlen; + output [2:0] tdt_dm_pad_awsize; + output tdt_dm_pad_awvalid; + input pad_tdt_dm_awready; + output [`TDT_DM_SBA_DW-1:0] tdt_dm_pad_wdata; + output tdt_dm_pad_wvalid; + output tdt_dm_pad_wlast; + output [`TDT_DM_SBA_BW-1:0] tdt_dm_pad_wstrb; + input pad_tdt_dm_wready; + output tdt_dm_pad_bready; + input [3:0] pad_tdt_dm_bid; + input [1:0] pad_tdt_dm_bresp; + input pad_tdt_dm_bvalid; + output [3:0] tdt_dm_pad_arid; + output [`TDT_DM_SBAW-1:0] tdt_dm_pad_araddr; + output [3:0] tdt_dm_pad_arlen; + output [2:0] tdt_dm_pad_arsize; + output tdt_dm_pad_arvalid; + input pad_tdt_dm_arready; + input [3:0] pad_tdt_dm_rid; + input [`TDT_DM_SBA_DW-1:0] pad_tdt_dm_rdata; + input pad_tdt_dm_rvalid; + input pad_tdt_dm_rlast; + input [1:0] pad_tdt_dm_rresp; + output tdt_dm_pad_rready; + output [1:0] tdt_dm_pad_awburst; + output [3:0] tdt_dm_pad_awcache; + output tdt_dm_pad_awlock; + output [2:0] tdt_dm_pad_awprot; + output [1:0] tdt_dm_pad_arburst; + output [3:0] tdt_dm_pad_arcache; + output tdt_dm_pad_arlock; + output [2:0] tdt_dm_pad_arprot; + +`elsif TDT_DM_SBA_AHB + output [3:0] tdt_dm_pad_hprot; + output tdt_dm_pad_hmastlock; + output [1:0] tdt_dm_pad_htrans; + output [`TDT_DM_SBAW-1:0] tdt_dm_pad_haddr; + output tdt_dm_pad_hwrite; + output [2:0] tdt_dm_pad_hburst; + output [2:0] tdt_dm_pad_hsize; + output [`TDT_DM_SBA_DW-1:0] tdt_dm_pad_hwdata; + input [`TDT_DM_SBA_DW-1:0] pad_tdt_dm_hrdata; + input pad_tdt_dm_hready; + input pad_tdt_dm_hresp; +`endif +`endif + + + wire dm_pclk_en; + wire dm_pclk; + //wire[3:0] tdt_dm_pad_wid;//axi3 only port, axi4 nouse + + +gated_clk_cell x_gated_clk_cell( + .clk_in (sys_apb_clk), + .global_en (1'b1), + .module_en (1'b0), + .local_en (dm_pclk_en), + .external_en (1'b0), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en), + .clk_out (dm_pclk) +); + +tdt_dm #( + .APB_AW (12), + .CORE_NUM (`TDT_DM_CORE_NUM), +`ifdef TDT_DM_EXT_TRIGGER_EN + .EXTHALTTRI_NUM (`TDT_DM_EXTHALTTRI_NUM), + .EXTRESUMETRI_NUM (`TDT_DM_EXTRESUMETRI_NUM), +`endif +`ifdef TDT_DM_PB_EN + .PB_SIZE (`TDT_DM_PB_SIZE), +`endif + .IMP_EBREAK (`TDT_DM_IMPEBREAK), + .CORE_MAX_XLEN (`TDT_DM_CORE_MAX_XLEN), + .NEXTDM_BASEADDR (TDT_NEXT_DM_BA), +`ifdef TDT_DM_SBA + .SBAW (`TDT_DM_SBAW), +`endif + .ALLCORE_NSCRATCH (`TDT_DM_ALLCORE_NSCRATCH), + .ALLCORE_ISA (`TDT_DM_ALLCORE_ISA) +) x_tdt_dm ( + .pclk (sys_apb_clk), + .preset_b (sys_apb_rst_b), + .forever_cpuclk (forever_cpuclk), + .ciu_rst_b (ciu_rst_b), + .sys_bus_clk_en (sys_bus_clk_en), + .dm_pclk (dm_pclk), + .dm_paddr (tdt_dmi_paddr), + .dm_pwrite (tdt_dmi_pwrite), + .dm_psel (tdt_dmi_psel), + .dm_penable (tdt_dmi_penable), + .dm_pwdata (tdt_dmi_pwdata), + .dm_prdata (tdt_dmi_prdata[31:0]), + .dm_pready (tdt_dmi_pready), + .dm_pslverr (tdt_dmi_pslverr), + + .pad_icg_scan_en (pad_yy_icg_scan_en), + + .dm_pclk_en (dm_pclk_en), + .ndmresetn (tdt_dm_pad_ndmreset_n), + .dm_core_rstn (tdt_dm_pad_hartreset_n), + .dm_core_halt_req_o (tdt_dm_dtu_halt_req), + .dm_core_async_halt_req_o (tdt_dm_dtu_async_halt_req), + .dm_core_resume_req_o (tdt_dm_dtu_resume_req), + .dm_core_halt_on_reset_o (tdt_dm_dtu_halt_on_reset), + .dm_core_halt_req_cause_o (tdt_dm_dtu_halt_req_cause), + .core_dm_halted_i (dtu_tdt_dm_halted), + .core_dm_havereset_i (dtu_tdt_dm_havereset), + .dm_core_ack_havereset_o (tdt_dm_dtu_ack_havereset), + .core_dm_unavail_i (pad_tdt_dm_core_unavail), + +`ifdef TDT_DM_EXT_TRIGGER_EN + .pad_dm_halt_req_i (pad_tdt_dm_halt_req), + .dm_pad_halt_req_o (tdt_dm_pad_halt_req), + + .pad_dm_resume_req_i (pad_tdt_dm_resume_req), + .dm_pad_resume_req_o (tdt_dm_pad_resume_req), +`endif + + .dm_core_itr_o (tdt_dm_dtu_itr), + .dm_core_itr_vld_o (tdt_dm_dtu_itr_vld), + .core_dm_itr_done_i (dtu_tdt_dm_itr_done), + .core_dm_exce_retire_i (dtu_tdt_dm_retire_debug_expt_vld), + .dm_core_wr_vld (tdt_dm_dtu_wr_vld), + .dm_core_wr_flg (tdt_dm_dtu_wr_flg), + .dm_core_wdata (tdt_dm_dtu_wdata), + .core_dm_wr_ready (dtu_tdt_dm_wr_ready), + .core_dm_rx_data (dtu_tdt_dm_rx_data) + +`ifdef TDT_DM_SBA +`ifdef TDT_DM_SBA_AXI + , + .dm_pad_awid (tdt_dm_pad_awid), + .dm_pad_awaddr (tdt_dm_pad_awaddr), + .dm_pad_awlen (tdt_dm_pad_awlen), + .dm_pad_awsize (tdt_dm_pad_awsize), + .dm_pad_awvalid (tdt_dm_pad_awvalid), + .pad_dm_awready (pad_tdt_dm_awready), + .dm_pad_wdata (tdt_dm_pad_wdata), + .dm_pad_wvalid (tdt_dm_pad_wvalid), + .dm_pad_wlast (tdt_dm_pad_wlast), + .dm_pad_wstrb (tdt_dm_pad_wstrb), + .pad_dm_wready (pad_tdt_dm_wready), + .dm_pad_bready (tdt_dm_pad_bready), + .pad_dm_bid (pad_tdt_dm_bid), + .pad_dm_bresp (pad_tdt_dm_bresp), + .pad_dm_bvalid (pad_tdt_dm_bvalid), + .dm_pad_arid (tdt_dm_pad_arid), + .dm_pad_araddr (tdt_dm_pad_araddr), + .dm_pad_arlen (tdt_dm_pad_arlen), + .dm_pad_arsize (tdt_dm_pad_arsize), + .dm_pad_arvalid (tdt_dm_pad_arvalid), + .pad_dm_arready (pad_tdt_dm_arready), + .pad_dm_rid (pad_tdt_dm_rid), + .pad_dm_rdata (pad_tdt_dm_rdata), + .pad_dm_rvalid (pad_tdt_dm_rvalid), + .pad_dm_rlast (pad_tdt_dm_rlast), + .pad_dm_rresp (pad_tdt_dm_rresp), + .dm_pad_rready (tdt_dm_pad_rready), + .dm_pad_awburst (tdt_dm_pad_awburst), + .dm_pad_awcache (tdt_dm_pad_awcache), + .dm_pad_awlock (tdt_dm_pad_awlock), + .dm_pad_awprot (tdt_dm_pad_awprot), + .dm_pad_arburst (tdt_dm_pad_arburst), + .dm_pad_arcache (tdt_dm_pad_arcache), + .dm_pad_arlock (tdt_dm_pad_arlock), + .dm_pad_arprot (tdt_dm_pad_arprot) + //.dm_pad_wid (tdt_dm_pad_wid) +`endif +`ifdef TDT_DM_SBA_AHB + , + .dm_pad_hprot (tdt_dm_pad_hprot), + .dm_pad_hmastlock (tdt_dm_pad_hmastlock), + .dm_pad_htrans (tdt_dm_pad_htrans), + .dm_pad_haddr (tdt_dm_pad_haddr), + .dm_pad_hwrite (tdt_dm_pad_hwrite), + .dm_pad_hburst (tdt_dm_pad_hburst), + .dm_pad_hsize (tdt_dm_pad_hsize), + .dm_pad_hwdata (tdt_dm_pad_hwdata), + .pad_dm_hrdata (pad_tdt_dm_hrdata), + .pad_dm_hready (pad_tdt_dm_hready), + .pad_dm_hresp (pad_tdt_dm_hresp) +`endif +`endif + + +); +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi.v new file mode 100644 index 0000000000000000000000000000000000000000..4c4780d13102f82f8ef240bd460b78593c4188b2 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi.v @@ -0,0 +1,417 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module tdt_dmi ( + sys_apb_clk, + sys_apb_rst_b, + pad_tdt_dtm_tclk, + pad_tdt_dtm_trst_b, + pad_tdt_dtm_jtag2_sel, + pad_tdt_dtm_tap_en, + pad_tdt_dtm_tdi, + pad_tdt_dtm_tms_i, + tdt_dtm_pad_tdo, + tdt_dtm_pad_tdo_en, + tdt_dtm_pad_tms_o, + tdt_dtm_pad_tms_oe, + + pad_icg_scan_en, + +`ifdef TDT_DMI_SYSAPB_EN + pad_tdt_sysapb_en, + pad_tdt_dmi_paddr, + pad_tdt_dmi_pwrite, + pad_tdt_dmi_psel, + pad_tdt_dmi_penable, + pad_tdt_dmi_pwdata, + tdt_dmi_pad_prdata, + tdt_dmi_pad_pready, + tdt_dmi_pad_pslverr, + +`endif + + tdt_dmi_paddr, + tdt_dmi_pwrite, + tdt_dmi_penable, + tdt_dmi_pwdata, + tdt_dmi_psel, + tdt_dmi_prdata, + tdt_dmi_pslverr, + tdt_dmi_pready +); + + + input sys_apb_clk; + input sys_apb_rst_b; + input pad_tdt_dtm_tclk; + input pad_tdt_dtm_trst_b; + input pad_tdt_dtm_jtag2_sel; + input pad_tdt_dtm_tap_en; + input pad_tdt_dtm_tdi; + input pad_tdt_dtm_tms_i; + output tdt_dtm_pad_tdo; + output tdt_dtm_pad_tdo_en; + output tdt_dtm_pad_tms_o; + output tdt_dtm_pad_tms_oe; + + input pad_icg_scan_en; + +`ifdef TDT_DMI_SYSAPB_EN + input pad_tdt_sysapb_en; + input [12+`TDT_DMI_HIGH_ADDR_W-1:0] pad_tdt_dmi_paddr; + input pad_tdt_dmi_pwrite; + input pad_tdt_dmi_psel; + input pad_tdt_dmi_penable; + input [31:0] pad_tdt_dmi_pwdata; + output [31:0] tdt_dmi_pad_prdata; + output tdt_dmi_pad_pready; + output tdt_dmi_pad_pslverr; +`endif + + output [11:0] tdt_dmi_paddr; + output tdt_dmi_pwrite; + output tdt_dmi_penable; + output [31:0] tdt_dmi_pwdata; +`ifdef TDT_DMI_SINGLE_SLAVE + output tdt_dmi_psel; +`else + output [`TDT_DMI_SLAVE_NUM-1:0] tdt_dmi_psel; +`endif + input [32*`TDT_DMI_SLAVE_NUM-1:0] tdt_dmi_prdata; +`ifdef TDT_DMI_SINGLE_SLAVE + input tdt_dmi_pready; + input tdt_dmi_pslverr; +`else + input [`TDT_DMI_SLAVE_NUM-1:0] tdt_dmi_pready; + input [`TDT_DMI_SLAVE_NUM-1:0] tdt_dmi_pslverr; +`endif + + wire apbm_apbmux_psel; + wire apbm_apbmux_penable; + wire apbm_apbmux_pwrite; + wire [12+`TDT_DMI_HIGH_ADDR_W-1:0] apbm_apbmux_paddr; + wire [31:0] apbm_apbmux_pwdata; + wire apbmux_apbm_pready; + wire apbmux_apbm_pslverr; + wire [31:0] apbmux_apbm_prdata; +`ifdef TDT_DMI_SYSAPB_EN + wire pre_apbmux_apbdec_psel; + wire pre_apbmux_apbdec_penable; + wire pre_apbmux_apbdec_pwrite; + wire [12+`TDT_DMI_HIGH_ADDR_W-1:0] pre_apbmux_apbdec_paddr; + wire [31:0] pre_apbmux_apbdec_pwdata; + wire pre_apbdec_apbmux_pready; + wire pre_apbdec_apbmux_pslverr; + wire [31:0] pre_apbdec_apbmux_prdata; + +`endif + wire apbmux_apbdec_psel; + wire apbmux_apbdec_penable; + wire apbmux_apbdec_pwrite; + wire [12+`TDT_DMI_HIGH_ADDR_W-1:0] apbmux_apbdec_paddr; + wire [31:0] apbmux_apbdec_pwdata; + wire apbdec_apbmux_pready; + wire apbdec_apbmux_pslverr; + wire [31:0] apbdec_apbmux_prdata; + + wire dtm_apbm_wr_vld; + wire [`TDT_DMI_HIGH_ADDR_W+10-1:0] dtm_apbm_wr_addr; + wire [1:0] dtm_apbm_wr_flg; + wire [31:0] dtm_apbm_wdata; + wire dtm_apbm_dmihardreset; + wire [31:0] apbm_dtm_rdata; + wire apbm_dtm_wr_ready; + + wire apb_icg_en; + assign apb_icg_en = 1'b0; + +tdt_dtm_top #( + .DTM_ABITS (`TDT_DMI_HIGH_ADDR_W+10) +) x_tdt_dtm_top ( + .pad_dtm_tclk (pad_tdt_dtm_tclk), + .pad_dtm_trst_b (pad_tdt_dtm_trst_b), + .pad_dtm_jtag2_sel (pad_tdt_dtm_jtag2_sel), + .pad_dtm_tap_en (pad_tdt_dtm_tap_en), + .pad_dtm_tdi (pad_tdt_dtm_tdi), + .pad_dtm_tms_i (pad_tdt_dtm_tms_i), + .dtm_pad_tdo (tdt_dtm_pad_tdo), + .dtm_pad_tdo_en (tdt_dtm_pad_tdo_en), + .dtm_pad_tms_o (tdt_dtm_pad_tms_o), + .dtm_pad_tms_oe (tdt_dtm_pad_tms_oe), + + .dtm_apbm_wr_vld (dtm_apbm_wr_vld), + .dtm_apbm_wr_addr (dtm_apbm_wr_addr), + .dtm_apbm_wr_flg (dtm_apbm_wr_flg), + .dtm_apbm_wdata (dtm_apbm_wdata), + .dmihardreset (dtm_apbm_dmihardreset), + .apbm_dtm_rdata (apbm_dtm_rdata), + .apbm_dtm_wr_ready (apbm_dtm_wr_ready) +); + +//========================================================== +// apb master +//========================================================== + +tdt_apb_master #( + .PADDR_HIGH_WIDTH (`TDT_DMI_HIGH_ADDR_W), + .PADDR_LOW_WIDTH (10), + .SLAVE_NUM (`TDT_DMI_SLAVE_NUM) +) x_tdt_apb_master ( + .tck (pad_tdt_dtm_tclk), + .trst_b (pad_tdt_dtm_trst_b), + .cmd_vld (dtm_apbm_wr_vld), + .addr (dtm_apbm_wr_addr), + .wr_flg (dtm_apbm_wr_flg), + .wdata (dtm_apbm_wdata), + .dmihardreset (dtm_apbm_dmihardreset), + .rdata (apbm_dtm_rdata), + .apb_wr_ready (apbm_dtm_wr_ready), + + .pclk (sys_apb_clk), + .preset_b (sys_apb_rst_b), + .psel (apbm_apbmux_psel), + .penable (apbm_apbmux_penable), + .pwrite (apbm_apbmux_pwrite), + .paddr (apbm_apbmux_paddr), + .pwdata (apbm_apbmux_pwdata), + .pready (apbmux_apbm_pready), + .pslverr (apbmux_apbm_pslverr), + .prdata (apbmux_apbm_prdata), + + .dm_apb_clk_en (apb_icg_en), + .pad_icg_scan_en (pad_icg_scan_en) +); + +//========================================================== +// apb mux +//========================================================== +`ifdef TDT_DMI_SYSAPB_EN + +tdt_apb_mux #( + .PADDR_HIGH_WIDTH (`TDT_DMI_HIGH_ADDR_W), + .PADDR_LOW_WIDTH (10) +) x_tdt_apb_mux ( + .pclk (sys_apb_clk), + .preset_b (sys_apb_rst_b), + + .psel_dtm (apbm_apbmux_psel), + .penable_dtm (apbm_apbmux_penable), + .pwrite_dtm (apbm_apbmux_pwrite), + .paddr_dtm (apbm_apbmux_paddr), + .pwdata_dtm (apbm_apbmux_pwdata), + .pready_dtm (apbmux_apbm_pready), + .pslverr_dtm (apbmux_apbm_pslverr), + + .prdata_dtm (apbmux_apbm_prdata), + + .sysapb_en (pad_tdt_sysapb_en), + .psel_sys (pad_tdt_dmi_psel), + .penable_sys (pad_tdt_dmi_penable), + .pwrite_sys (pad_tdt_dmi_pwrite), + .paddr_sys (pad_tdt_dmi_paddr), + .pwdata_sys (pad_tdt_dmi_pwdata), + .pready_sys (tdt_dmi_pad_pready), + .prdata_sys (tdt_dmi_pad_prdata), + .pslverr_sys (tdt_dmi_pad_pslverr), + + .psel (pre_apbmux_apbdec_psel), + .penable (pre_apbmux_apbdec_penable), + .pwrite (pre_apbmux_apbdec_pwrite), + .paddr (pre_apbmux_apbdec_paddr), + .pwdata (pre_apbmux_apbdec_pwdata), + .pready (pre_apbdec_apbmux_pready), + .pslverr (pre_apbdec_apbmux_pslverr), + .prdata (pre_apbdec_apbmux_prdata), + + .dm_apb_clk_en (apb_icg_en), + .pad_icg_scan_en (pad_icg_scan_en) +); + +tdt_apb_regslice +#( + .PADDR_HIGH_WIDTH (`TDT_DMI_HIGH_ADDR_W), + .PADDR_LOW_WIDTH (10) +) x_tdt_apb_regslice ( + .pclk (sys_apb_clk), + .preset_b (sys_apb_rst_b), + + .psel (pre_apbmux_apbdec_psel), + .penable (pre_apbmux_apbdec_penable), + .pwrite (pre_apbmux_apbdec_pwrite), + .paddr (pre_apbmux_apbdec_paddr), + .pwdata (pre_apbmux_apbdec_pwdata), + .pready (apbdec_apbmux_pready), + .pslverr (apbdec_apbmux_pslverr), + .prdata (apbdec_apbmux_prdata), + + .psel_r (apbmux_apbdec_psel), + .penable_r (apbmux_apbdec_penable), + .pwrite_r (apbmux_apbdec_pwrite), + .paddr_r (apbmux_apbdec_paddr), + .pwdata_r (apbmux_apbdec_pwdata), + .pready_r (pre_apbdec_apbmux_pready), + .pslverr_r (pre_apbdec_apbmux_pslverr), + .prdata_r (pre_apbdec_apbmux_prdata), + + .dm_apb_clk_en (apb_icg_en), + .pad_icg_scan_en (pad_icg_scan_en) +); + +`else + assign apbmux_apbdec_psel = apbm_apbmux_psel; + assign apbmux_apbdec_penable = apbm_apbmux_penable; + assign apbmux_apbdec_pwrite = apbm_apbmux_pwrite; + assign apbmux_apbdec_paddr[12+`TDT_DMI_HIGH_ADDR_W-1:0] = apbm_apbmux_paddr[12+`TDT_DMI_HIGH_ADDR_W-1:0]; + assign apbmux_apbdec_pwdata[31:0] = apbm_apbmux_pwdata[31:0]; + assign apbmux_apbm_pready = apbdec_apbmux_pready; + assign apbmux_apbm_pslverr = apbdec_apbmux_pslverr; + assign apbmux_apbm_prdata[31:0] = apbdec_apbmux_prdata[31:0]; +`endif + +//========================================================== +// apb decoder +//========================================================== +`ifdef TDT_DMI_SINGLE_SLAVE + assign tdt_dmi_psel = apbmux_apbdec_psel; + assign tdt_dmi_penable = apbmux_apbdec_penable; + assign tdt_dmi_pwrite = apbmux_apbdec_pwrite; + assign tdt_dmi_paddr[11:0] = apbmux_apbdec_paddr[12+`TDT_DMI_HIGH_ADDR_W-1:0]; + assign tdt_dmi_pwdata[31:0] = apbmux_apbdec_pwdata[31:0]; + assign apbdec_apbmux_pready = tdt_dmi_pready; + assign apbdec_apbmux_pslverr = tdt_dmi_pslverr; + assign apbdec_apbmux_prdata[31:0] = tdt_dmi_prdata[32*`TDT_DMI_SLAVE_NUM-1:0]; +`else +tdt_apb_decoder #( +`ifdef TDT_DMI_SLAVE_31 + .PSEL_31_ADDR (`TDT_DMI_SLAVE_31_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_30 + .PSEL_30_ADDR (`TDT_DMI_SLAVE_30_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_29 + .PSEL_29_ADDR (`TDT_DMI_SLAVE_29_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_28 + .PSEL_28_ADDR (`TDT_DMI_SLAVE_28_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_27 + .PSEL_27_ADDR (`TDT_DMI_SLAVE_27_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_26 + .PSEL_26_ADDR (`TDT_DMI_SLAVE_26_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_25 + .PSEL_25_ADDR (`TDT_DMI_SLAVE_25_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_24 + .PSEL_24_ADDR (`TDT_DMI_SLAVE_24_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_23 + .PSEL_23_ADDR (`TDT_DMI_SLAVE_23_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_22 + .PSEL_22_ADDR (`TDT_DMI_SLAVE_22_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_21 + .PSEL_21_ADDR (`TDT_DMI_SLAVE_21_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_20 + .PSEL_20_ADDR (`TDT_DMI_SLAVE_20_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_19 + .PSEL_19_ADDR (`TDT_DMI_SLAVE_19_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_18 + .PSEL_18_ADDR (`TDT_DMI_SLAVE_18_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_17 + .PSEL_17_ADDR (`TDT_DMI_SLAVE_17_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_16 + .PSEL_16_ADDR (`TDT_DMI_SLAVE_16_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_15 + .PSEL_15_ADDR (`TDT_DMI_SLAVE_15_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_14 + .PSEL_14_ADDR (`TDT_DMI_SLAVE_14_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_13 + .PSEL_13_ADDR (`TDT_DMI_SLAVE_13_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_12 + .PSEL_12_ADDR (`TDT_DMI_SLAVE_12_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_11 + .PSEL_11_ADDR (`TDT_DMI_SLAVE_11_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_10 + .PSEL_10_ADDR (`TDT_DMI_SLAVE_10_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_9 + .PSEL_9_ADDR (`TDT_DMI_SLAVE_9_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_8 + .PSEL_8_ADDR (`TDT_DMI_SLAVE_8_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_7 + .PSEL_7_ADDR (`TDT_DMI_SLAVE_7_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_6 + .PSEL_6_ADDR (`TDT_DMI_SLAVE_6_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_5 + .PSEL_5_ADDR (`TDT_DMI_SLAVE_5_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_4 + .PSEL_4_ADDR (`TDT_DMI_SLAVE_4_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_3 + .PSEL_3_ADDR (`TDT_DMI_SLAVE_3_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_2 + .PSEL_2_ADDR (`TDT_DMI_SLAVE_2_BASEADDR), +`endif +`ifdef TDT_DMI_SLAVE_1 + .PSEL_1_ADDR (`TDT_DMI_SLAVE_1_BASEADDR), +`endif + .PSEL_0_ADDR ('d0), + .NUM_APB_SLAVES (`TDT_DMI_SLAVE_NUM), + .PADDR_HIGH_WIDTH (`TDT_DMI_HIGH_ADDR_W), + .PADDR_LOW_WIDTH (10) +) x_tdt_apb_decoder ( + .pclk (sys_apb_clk), + .preset_b (sys_apb_rst_b), + + .psel_m (apbmux_apbdec_psel), + .penable_m (apbmux_apbdec_penable), + .pwrite_m (apbmux_apbdec_pwrite), + .paddr_m (apbmux_apbdec_paddr), + .pwdata_m (apbmux_apbdec_pwdata), + .pready_m (apbdec_apbmux_pready), + .pslverr_m (apbdec_apbmux_pslverr), + .prdata_m (apbdec_apbmux_prdata), + + .penable (tdt_dmi_penable), + .pwrite (tdt_dmi_pwrite), + .paddr (tdt_dmi_paddr), + .pwdata (tdt_dmi_pwdata), + .psel (tdt_dmi_psel), + .pslverr (tdt_dmi_pslverr), + .pready (tdt_dmi_pready), + .prdata (tdt_dmi_prdata) +); +`endif + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_define.h b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_define.h new file mode 100644 index 0000000000000000000000000000000000000000..4da243667187b8e14317c8ab735d1253c925a3c5 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_define.h @@ -0,0 +1,313 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +//============================================================================= +// Category: Foundary and Process Configuration +//============================================================================= + +//========================================================== +// TDT_DMI_SYSAPB_EN : system bus apb access tdt_top enable +//========================================================== + +//`define TDT_DMI_SYSAPB_EN + +//========================================================== +// TDT_DMI_SLAVE_* : apb slave number, 0 must define, max to +// 63. Number must be sequence +//========================================================== + +`define TDT_DMI_SLAVE_0 +//`define TDT_DMI_SLAVE_1 +//`define TDT_DMI_SLAVE_2 +//`define TDT_DMI_SLAVE_3 +//`define TDT_DMI_SLAVE_4 +//`define TDT_DMI_SLAVE_5 +//`define TDT_DMI_SLAVE_6 +//`define TDT_DMI_SLAVE_7 +//`define TDT_DMI_SLAVE_8 +//`define TDT_DMI_SLAVE_9 +//`define TDT_DMI_SLAVE_10 +//`define TDT_DMI_SLAVE_11 +//`define TDT_DMI_SLAVE_12 +//`define TDT_DMI_SLAVE_13 +//`define TDT_DMI_SLAVE_14 +//`define TDT_DMI_SLAVE_15 +//`define TDT_DMI_SLAVE_16 +//`define TDT_DMI_SLAVE_17 +//`define TDT_DMI_SLAVE_18 +//`define TDT_DMI_SLAVE_19 +//`define TDT_DMI_SLAVE_20 +//`define TDT_DMI_SLAVE_21 +//`define TDT_DMI_SLAVE_22 +//`define TDT_DMI_SLAVE_23 +//`define TDT_DMI_SLAVE_24 +//`define TDT_DMI_SLAVE_25 +//`define TDT_DMI_SLAVE_26 +//`define TDT_DMI_SLAVE_27 +//`define TDT_DMI_SLAVE_28 +//`define TDT_DMI_SLAVE_29 +//`define TDT_DMI_SLAVE_30 +//`define TDT_DMI_SLAVE_31 + +`ifdef TDT_DMI_SLAVE_31 + `define TDT_DMI_SLAVE_NUM 32 +`else + `ifdef TDT_DMI_SLAVE_30 + `define TDT_DMI_SLAVE_NUM 31 + `else + `ifdef TDT_DMI_SLAVE_29 + `define TDT_DMI_SLAVE_NUM 30 + `else + `ifdef TDT_DMI_SLAVE_28 + `define TDT_DMI_SLAVE_NUM 29 + `else + `ifdef TDT_DMI_SLAVE_27 + `define TDT_DMI_SLAVE_NUM 28 + `else + `ifdef TDT_DMI_SLAVE_26 + `define TDT_DMI_SLAVE_NUM 27 + `else + `ifdef TDT_DMI_SLAVE_25 + `define TDT_DMI_SLAVE_NUM 26 + `else + `ifdef TDT_DMI_SLAVE_24 + `define TDT_DMI_SLAVE_NUM 25 + `else + `ifdef TDT_DMI_SLAVE_23 + `define TDT_DMI_SLAVE_NUM 24 + `else + `ifdef TDT_DMI_SLAVE_22 + `define TDT_DMI_SLAVE_NUM 23 + `else + `ifdef TDT_DMI_SLAVE_21 + `define TDT_DMI_SLAVE_NUM 22 + `else + `ifdef TDT_DMI_SLAVE_20 + `define TDT_DMI_SLAVE_NUM 21 + `else + `ifdef TDT_DMI_SLAVE_19 + `define TDT_DMI_SLAVE_NUM 20 + `else + `ifdef TDT_DMI_SLAVE_18 + `define TDT_DMI_SLAVE_NUM 19 + `else + `ifdef TDT_DMI_SLAVE_17 + `define TDT_DMI_SLAVE_NUM 18 + `else + `ifdef TDT_DMI_SLAVE_16 + `define TDT_DMI_SLAVE_NUM 17 + `else + `ifdef TDT_DMI_SLAVE_15 + `define TDT_DMI_SLAVE_NUM 16 + `else + `ifdef TDT_DMI_SLAVE_14 + `define TDT_DMI_SLAVE_NUM 15 + `else + `ifdef TDT_DMI_SLAVE_13 + `define TDT_DMI_SLAVE_NUM 14 + `else + `ifdef TDT_DMI_SLAVE_12 + `define TDT_DMI_SLAVE_NUM 13 + `else + `ifdef TDT_DMI_SLAVE_11 + `define TDT_DMI_SLAVE_NUM 12 + `else + `ifdef TDT_DMI_SLAVE_10 + `define TDT_DMI_SLAVE_NUM 11 + `else + `ifdef TDT_DMI_SLAVE_9 + `define TDT_DMI_SLAVE_NUM 10 + `else + `ifdef TDT_DMI_SLAVE_8 + `define TDT_DMI_SLAVE_NUM 9 + `else + `ifdef TDT_DMI_SLAVE_7 + `define TDT_DMI_SLAVE_NUM 8 + `else + `ifdef TDT_DMI_SLAVE_6 + `define TDT_DMI_SLAVE_NUM 7 + `else + `ifdef TDT_DMI_SLAVE_5 + `define TDT_DMI_SLAVE_NUM 6 + `else + `ifdef TDT_DMI_SLAVE_4 + `define TDT_DMI_SLAVE_NUM 5 + `else + `ifdef TDT_DMI_SLAVE_3 + `define TDT_DMI_SLAVE_NUM 4 + `else + `ifdef TDT_DMI_SLAVE_2 + `define TDT_DMI_SLAVE_NUM 3 + `else + `ifdef TDT_DMI_SLAVE_1 + `define TDT_DMI_SLAVE_NUM 2 + `else + `ifdef TDT_DMI_SLAVE_0 + `define TDT_DMI_SLAVE_NUM 1 + `define TDT_DMI_SINGLE_SLAVE + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif + `endif +`endif + +//========================================================== +// TDT_DMI_HIGH_ADDR_W : apb component decode address(each +// component have 4KB space), +// must >= clog2(SLAVE_NUM). +//========================================================== + +`ifdef TDT_DMI_SINGLE_SLAVE + `define TDT_DMI_HIGH_ADDR_W 0 +`else + `define TDT_DMI_HIGH_ADDR_W 6 +`endif + +//========================================================== +// TDT_DMI_SLAVE_*_BASEADDR : each component base address, +// width is TDT_DMI_HIGH_ADDR_W +//========================================================== + +`ifdef TDT_DMI_SLAVE_31 + `define TDT_DMI_SLAVE_31_BASEADDR 'd31 +`endif +`ifdef TDT_DMI_SLAVE_30 + `define TDT_DMI_SLAVE_30_BASEADDR 'd30 +`endif +`ifdef TDT_DMI_SLAVE_29 + `define TDT_DMI_SLAVE_29_BASEADDR 'd29 +`endif +`ifdef TDT_DMI_SLAVE_28 + `define TDT_DMI_SLAVE_28_BASEADDR 'd28 +`endif +`ifdef TDT_DMI_SLAVE_27 + `define TDT_DMI_SLAVE_27_BASEADDR 'd27 +`endif +`ifdef TDT_DMI_SLAVE_26 + `define TDT_DMI_SLAVE_26_BASEADDR 'd26 +`endif +`ifdef TDT_DMI_SLAVE_25 + `define TDT_DMI_SLAVE_25_BASEADDR 'd25 +`endif +`ifdef TDT_DMI_SLAVE_24 + `define TDT_DMI_SLAVE_24_BASEADDR 'd24 +`endif +`ifdef TDT_DMI_SLAVE_23 + `define TDT_DMI_SLAVE_23_BASEADDR 'd23 +`endif +`ifdef TDT_DMI_SLAVE_22 + `define TDT_DMI_SLAVE_22_BASEADDR 'd22 +`endif +`ifdef TDT_DMI_SLAVE_21 + `define TDT_DMI_SLAVE_21_BASEADDR 'd21 +`endif +`ifdef TDT_DMI_SLAVE_20 + `define TDT_DMI_SLAVE_20_BASEADDR 'd20 +`endif +`ifdef TDT_DMI_SLAVE_19 + `define TDT_DMI_SLAVE_19_BASEADDR 'd19 +`endif +`ifdef TDT_DMI_SLAVE_18 + `define TDT_DMI_SLAVE_18_BASEADDR 'd18 +`endif +`ifdef TDT_DMI_SLAVE_17 + `define TDT_DMI_SLAVE_17_BASEADDR 'd17 +`endif +`ifdef TDT_DMI_SLAVE_16 + `define TDT_DMI_SLAVE_16_BASEADDR 'd16 +`endif +`ifdef TDT_DMI_SLAVE_15 + `define TDT_DMI_SLAVE_15_BASEADDR 'd15 +`endif +`ifdef TDT_DMI_SLAVE_14 + `define TDT_DMI_SLAVE_14_BASEADDR 'd14 +`endif +`ifdef TDT_DMI_SLAVE_13 + `define TDT_DMI_SLAVE_13_BASEADDR 'd13 +`endif +`ifdef TDT_DMI_SLAVE_12 + `define TDT_DMI_SLAVE_12_BASEADDR 'd12 +`endif +`ifdef TDT_DMI_SLAVE_11 + `define TDT_DMI_SLAVE_11_BASEADDR 'd11 +`endif +`ifdef TDT_DMI_SLAVE_10 + `define TDT_DMI_SLAVE_10_BASEADDR 'd10 +`endif +`ifdef TDT_DMI_SLAVE_9 + `define TDT_DMI_SLAVE_9_BASEADDR 'd9 +`endif +`ifdef TDT_DMI_SLAVE_8 + `define TDT_DMI_SLAVE_8_BASEADDR 'd8 +`endif +`ifdef TDT_DMI_SLAVE_7 + `define TDT_DMI_SLAVE_7_BASEADDR 'd7 +`endif +`ifdef TDT_DMI_SLAVE_6 + `define TDT_DMI_SLAVE_6_BASEADDR 'd6 +`endif +`ifdef TDT_DMI_SLAVE_5 + `define TDT_DMI_SLAVE_5_BASEADDR 'd5 +`endif +`ifdef TDT_DMI_SLAVE_4 + `define TDT_DMI_SLAVE_4_BASEADDR 'd4 +`endif +`ifdef TDT_DMI_SLAVE_3 + `define TDT_DMI_SLAVE_3_BASEADDR 'd3 +`endif +`ifdef TDT_DMI_SLAVE_2 + `define TDT_DMI_SLAVE_2_BASEADDR 'd2 +`endif +`ifdef TDT_DMI_SLAVE_1 + `define TDT_DMI_SLAVE_1_BASEADDR 'd1 +`endif + +//========================================================== +// DTMCS IDLE CYCLE, [5, 7] +// IDLE_CYCLE and freq.tlk/freq.pclk must meet this relation when TDT_DMI_SYSAPB_EN is undefined +// Freq.pclk/Freq.tclk > 8/(IDLE_CYCLE-4) +// IDLE_CYCLE and freq.tlk/freq.pclk must meet this relation when TDT_DMI_SYSAPB_EN is defined +// Freq.pclk/Freq.tclk > 11/(IDLE_CYCLE-4) +//========================================================== + +`define TDT_DMI_IDLE_CYCLE 3'h7 + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_rst_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_rst_top.v new file mode 100644 index 0000000000000000000000000000000000000000..9cae965b2cdad30308de852c507e88c161eef721 --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_rst_top.v @@ -0,0 +1,46 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module tdt_dmi_rst_top( + sys_apb_clk, + sys_apb_rst_b, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + sync_sys_apb_rst_b + ); + + input sys_apb_clk; + input sys_apb_rst_b; + input pad_yy_scan_mode; + input pad_yy_scan_rst_b; + output sync_sys_apb_rst_b; + + wire sync_sys_apb_rst_b; + wire async_apb_rst_b; + reg sys_apb_rst_ff_1st; + +assign async_apb_rst_b = sys_apb_rst_b; + +always @(posedge sys_apb_clk or negedge async_apb_rst_b) +begin + if (!async_apb_rst_b) + sys_apb_rst_ff_1st <= 1'b0; + else + sys_apb_rst_ff_1st <= 1'b1; +end + +assign sync_sys_apb_rst_b = pad_yy_scan_mode ? pad_yy_scan_rst_b : sys_apb_rst_ff_1st; + +endmodule diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_top.v new file mode 100644 index 0000000000000000000000000000000000000000..65c571012063e25f94f13602a1baaf7f34728a1e --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_dmi_top.v @@ -0,0 +1,157 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @22 +module tdt_dmi_top( + pad_tdt_dtm_jtag2_sel, + pad_tdt_dtm_tap_en, + pad_tdt_dtm_tclk, + pad_tdt_dtm_tdi, + pad_tdt_dtm_tms_i, + pad_tdt_dtm_trst_b, + pad_tdt_icg_scan_en, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + sys_apb_clk, + sys_apb_rst_b, + tdt_dmi_paddr, + tdt_dmi_penable, + tdt_dmi_prdata, + tdt_dmi_pready, + tdt_dmi_psel, + tdt_dmi_pslverr, + tdt_dmi_pwdata, + tdt_dmi_pwrite, + tdt_dtm_pad_tdo, + tdt_dtm_pad_tdo_en, + tdt_dtm_pad_tms_o, + tdt_dtm_pad_tms_oe +); + +// &Ports; @23 +input pad_tdt_dtm_jtag2_sel; +input pad_tdt_dtm_tap_en; +input pad_tdt_dtm_tclk; +input pad_tdt_dtm_tdi; +input pad_tdt_dtm_tms_i; +input pad_tdt_dtm_trst_b; +input pad_tdt_icg_scan_en; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input sys_apb_clk; +input sys_apb_rst_b; +input [31:0] tdt_dmi_prdata; +input tdt_dmi_pready; +input tdt_dmi_pslverr; +output [11:0] tdt_dmi_paddr; +output tdt_dmi_penable; +output tdt_dmi_psel; +output [31:0] tdt_dmi_pwdata; +output tdt_dmi_pwrite; +output tdt_dtm_pad_tdo; +output tdt_dtm_pad_tdo_en; +output tdt_dtm_pad_tms_o; +output tdt_dtm_pad_tms_oe; + +// &Regs; @24 + +// &Wires; @25 + + +tdt_dmi_rst_top x_tdt_dmi_rst_top ( + .sys_apb_clk(sys_apb_clk), + .sys_apb_rst_b(sys_apb_rst_b), + .pad_yy_scan_mode(pad_yy_scan_mode), + .pad_yy_scan_rst_b(pad_yy_scan_rst_b), + .sync_sys_apb_rst_b(sync_sys_apb_rst_b) +); + +tdt_dmi x_tdt_dmi ( + .sys_apb_clk(sys_apb_clk), + .sys_apb_rst_b(sync_sys_apb_rst_b), + .pad_tdt_dtm_tclk(pad_tdt_dtm_tclk), + .pad_tdt_dtm_trst_b(pad_tdt_dtm_trst_b), + .pad_tdt_dtm_jtag2_sel(pad_tdt_dtm_jtag2_sel), + .pad_tdt_dtm_tap_en(pad_tdt_dtm_tap_en), + .pad_tdt_dtm_tdi(pad_tdt_dtm_tdi), + .pad_tdt_dtm_tms_i(pad_tdt_dtm_tms_i), + .tdt_dtm_pad_tdo(tdt_dtm_pad_tdo), + .tdt_dtm_pad_tdo_en(tdt_dtm_pad_tdo_en), + .tdt_dtm_pad_tms_o(tdt_dtm_pad_tms_o), + .tdt_dtm_pad_tms_oe(tdt_dtm_pad_tms_oe), + + .pad_icg_scan_en(pad_tdt_icg_scan_en), + + + .tdt_dmi_paddr(tdt_dmi_paddr), + .tdt_dmi_pwrite(tdt_dmi_pwrite), + .tdt_dmi_penable(tdt_dmi_penable), + .tdt_dmi_pwdata(tdt_dmi_pwdata), + .tdt_dmi_psel(tdt_dmi_psel), + .tdt_dmi_prdata(tdt_dmi_prdata), + .tdt_dmi_pslverr(tdt_dmi_pslverr), + .tdt_dmi_pready(tdt_dmi_pready) + +); + + +// &Force("input", "sys_apb_clk"); @75 +// &Force("input", "sys_apb_rst_b"); @76 +// &Force("input", "pad_tdt_dtm_tclk"); @77 +// &Force("input", "pad_tdt_dtm_trst_b"); @78 +// &Force("input", "pad_tdt_dtm_jtag2_sel"); @79 +// &Force("input", "pad_tdt_dtm_tap_en"); @80 +// &Force("input", "pad_tdt_dtm_tdi"); @81 +// &Force("input", "pad_tdt_dtm_tms_i"); @82 +// &Force("output", "tdt_dtm_pad_tdo"); @83 +// &Force("output", "tdt_dtm_pad_tdo_en"); @84 +// &Force("output", "tdt_dtm_pad_tms_o"); @85 +// &Force("output", "tdt_dtm_pad_tms_oe"); @86 +// &Force("input", "pad_tdt_icg_scan_en"); @87 +// &Force("input", "pad_yy_scan_mode"); @88 +// &Force("input", "pad_yy_scan_rst_b"); @89 + +// &Force("input", "pad_tdt_sysapb_en"); @92 +// &Force("input", "pad_tdt_dmi_paddr"); @93 +// &Force("bus","pad_tdt_dmi_paddr",12+`TDT_DMI_HIGH_ADDR_W-1,0); @94 +// &Force("input", "pad_tdt_dmi_pwrite"); @95 +// &Force("input", "pad_tdt_dmi_psel"); @96 +// &Force("input", "pad_tdt_dmi_penable"); @97 +// &Force("input", "pad_tdt_dmi_pwdata"); @98 +// &Force("bus","pad_tdt_dmi_pwdata",31,0); @99 +// &Force("output", "tdt_dmi_pad_prdata"); @100 +// &Force("bus","tdt_dmi_pad_prdata",31,0); @101 +// &Force("output", "tdt_dmi_pad_pready"); @102 +// &Force("output", "tdt_dmi_pad_pslverr"); @103 + +// &Force("output", "tdt_dmi_paddr"); @106 +// &Force("bus","tdt_dmi_paddr",11,0); @107 +// &Force("output", "tdt_dmi_pwrite"); @108 +// &Force("output", "tdt_dmi_penable"); @109 +// &Force("output", "tdt_dmi_pwdata"); @110 +// &Force("bus","tdt_dmi_pwdata",31,0); @111 +// &Force("output", "tdt_dmi_psel"); @113 +// &Force("output", "tdt_dmi_psel");&Force("bus","tdt_dmi_psel",`TDT_DMI_SLAVE_NUM-1,0); @115 +// &Force("input", "tdt_dmi_prdata"); @117 +// &Force("bus","tdt_dmi_prdata",32*`TDT_DMI_SLAVE_NUM-1,0); @118 +// &Force("input", "tdt_dmi_pready"); @120 +// &Force("input", "tdt_dmi_pslverr"); @121 +// &Force("input", "tdt_dmi_pready");&Force("bus","tdt_dmi_pready",`TDT_DMI_SLAVE_NUM-1,0); @123 +// &Force("input", "tdt_dmi_pslverr");&Force("bus","tdt_dmi_pslverr",`TDT_DMI_SLAVE_NUM-1,0); @124 + +// &ModuleEnd; @127 +endmodule + + diff --git a/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_top.v b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_top.v new file mode 100644 index 0000000000000000000000000000000000000000..cfc8f90716f312b1d12501fa2d70f9d1d09ab06b --- /dev/null +++ b/XUANTIE-RV_opene906/E906_RTL_FACTORY/gen_rtl/tdt/rtl/top/tdt_top.v @@ -0,0 +1,301 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @16 +module tdt_top( + ciu_rst_b, + dtu_tdt_dm_halted, + dtu_tdt_dm_havereset, + dtu_tdt_dm_itr_done, + dtu_tdt_dm_retire_debug_expt_vld, + dtu_tdt_dm_rx_data, + dtu_tdt_dm_wr_ready, + forever_cpuclk, + pad_tdt_dm_core_unavail, + pad_yy_icg_scan_en, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + sys_apb_clk, + sys_apb_rst_b, + sys_bus_clk_en, + tdt_dm_dtu_ack_havereset, + tdt_dm_dtu_async_halt_req, + tdt_dm_dtu_halt_on_reset, + tdt_dm_dtu_halt_req, + tdt_dm_dtu_halt_req_cause, + tdt_dm_dtu_itr, + tdt_dm_dtu_itr_vld, + tdt_dm_dtu_resume_req, + tdt_dm_dtu_wdata, + tdt_dm_dtu_wr_flg, + tdt_dm_dtu_wr_vld, + tdt_dm_pad_hartreset_n, + tdt_dm_pad_ndmreset_n, + tdt_dmi_paddr, + tdt_dmi_penable, + tdt_dmi_prdata, + tdt_dmi_pready, + tdt_dmi_psel, + tdt_dmi_pslverr, + tdt_dmi_pwdata, + tdt_dmi_pwrite +); + +// &Ports; @17 +input ciu_rst_b; +input dtu_tdt_dm_halted; +input dtu_tdt_dm_havereset; +input dtu_tdt_dm_itr_done; +input dtu_tdt_dm_retire_debug_expt_vld; +input [31:0] dtu_tdt_dm_rx_data; +input dtu_tdt_dm_wr_ready; +input forever_cpuclk; +input pad_tdt_dm_core_unavail; +input pad_yy_icg_scan_en; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input sys_apb_clk; +input sys_apb_rst_b; +input sys_bus_clk_en; +input [11:0] tdt_dmi_paddr; +input tdt_dmi_penable; +input tdt_dmi_psel; +input [31:0] tdt_dmi_pwdata; +input tdt_dmi_pwrite; +output tdt_dm_dtu_ack_havereset; +output tdt_dm_dtu_async_halt_req; +output tdt_dm_dtu_halt_on_reset; +output tdt_dm_dtu_halt_req; +output [1 :0] tdt_dm_dtu_halt_req_cause; +output [31:0] tdt_dm_dtu_itr; +output tdt_dm_dtu_itr_vld; +output tdt_dm_dtu_resume_req; +output [31:0] tdt_dm_dtu_wdata; +output [1 :0] tdt_dm_dtu_wr_flg; +output tdt_dm_dtu_wr_vld; +output tdt_dm_pad_hartreset_n; +output tdt_dm_pad_ndmreset_n; +output [31:0] tdt_dmi_prdata; +output tdt_dmi_pready; +output tdt_dmi_pslverr; + +// &Regs; @18 + +// &Wires; @19 + + +tdt_dm_top x_tdt_dm_top( + .sys_apb_clk(sys_apb_clk), + .sys_apb_rst_b(sys_apb_rst_b), + .forever_cpuclk(forever_cpuclk), + .ciu_rst_b(ciu_rst_b), + .sys_bus_clk_en(sys_bus_clk_en), + .pad_yy_icg_scan_en(pad_yy_icg_scan_en), + .pad_yy_scan_mode(pad_yy_scan_mode), + .pad_yy_scan_rst_b(pad_yy_scan_rst_b), + + .tdt_dmi_paddr(tdt_dmi_paddr), + .tdt_dmi_pwrite(tdt_dmi_pwrite), + .tdt_dmi_psel(tdt_dmi_psel), + .tdt_dmi_penable(tdt_dmi_penable), + .tdt_dmi_pwdata(tdt_dmi_pwdata), + .tdt_dmi_prdata(tdt_dmi_prdata), + .tdt_dmi_pready(tdt_dmi_pready), + .tdt_dmi_pslverr(tdt_dmi_pslverr), + + .tdt_dm_pad_ndmreset_n(tdt_dm_pad_ndmreset_n), + .tdt_dm_pad_hartreset_n(tdt_dm_pad_hartreset_n), + + .tdt_dm_dtu_halt_req(tdt_dm_dtu_halt_req), + .tdt_dm_dtu_async_halt_req(tdt_dm_dtu_async_halt_req), + .tdt_dm_dtu_resume_req(tdt_dm_dtu_resume_req), + .tdt_dm_dtu_halt_on_reset(tdt_dm_dtu_halt_on_reset), + .tdt_dm_dtu_halt_req_cause(tdt_dm_dtu_halt_req_cause), + .dtu_tdt_dm_halted(dtu_tdt_dm_halted), + .dtu_tdt_dm_havereset(dtu_tdt_dm_havereset), + .tdt_dm_dtu_ack_havereset(tdt_dm_dtu_ack_havereset), + .pad_tdt_dm_core_unavail(pad_tdt_dm_core_unavail), + .tdt_dm_dtu_itr(tdt_dm_dtu_itr), + .tdt_dm_dtu_itr_vld(tdt_dm_dtu_itr_vld), + .dtu_tdt_dm_itr_done(dtu_tdt_dm_itr_done), + .dtu_tdt_dm_retire_debug_expt_vld(dtu_tdt_dm_retire_debug_expt_vld), + .tdt_dm_dtu_wr_vld(tdt_dm_dtu_wr_vld), + .tdt_dm_dtu_wr_flg(tdt_dm_dtu_wr_flg), + .tdt_dm_dtu_wdata(tdt_dm_dtu_wdata), + .dtu_tdt_dm_wr_ready(dtu_tdt_dm_wr_ready), + .dtu_tdt_dm_rx_data(dtu_tdt_dm_rx_data) + + + + +); + + +// &Force("input","sys_apb_clk"); @127 +// &Force("input","sys_apb_rst_b"); @128 +// &Force("input","forever_cpuclk"); @129 +// &Force("input","ciu_rst_b"); @130 +// &Force("input","sys_bus_clk_en"); @131 +// &Force("input","pad_yy_icg_scan_en"); @132 +// &Force("input","pad_yy_scan_mode"); @133 +// &Force("input","pad_yy_scan_rst_b"); @134 +// &Force("input","tdt_dmi_paddr"); @135 +// &Force("bus","tdt_dmi_paddr",11,0); @136 +// &Force("input","tdt_dmi_pwrite"); @137 +// &Force("input","tdt_dmi_psel"); @139 +// &Force("input","tdt_dmi_psel");&Force("bus","tdt_dmi_psel",`TDT_COMP_NUM-1,0); @141 +// &Force("input","tdt_dmi_penable"); @143 +// &Force("input","tdt_dmi_pwdata"); @144 +// &Force("bus","tdt_dmi_pwdata",31,0); @145 +// &Force("output","tdt_dmi_prdata"); @146 +// &Force("bus","tdt_dmi_prdata",`TDT_COMP_NUM*32-1,0); @147 +// &Force("output","tdt_dmi_pready"); @149 +// &Force("output","tdt_dmi_pslverr"); @150 +// &Force("output","tdt_dmi_pready");&Force("bus","tdt_dmi_pready",`TDT_COMP_NUM-1,0); @152 +// &Force("output","tdt_dmi_pslverr");&Force("bus","tdt_dmi_pslverr",`TDT_COMP_NUM-1,0); @153 + +// &Force("output","tdt_dm_pad_ndmreset_n"); @156 +// &Force("output","tdt_dm_pad_hartreset_n"); @158 +// &Force("output","tdt_dm_dtu_halt_req"); @159 +// &Force("output","tdt_dm_dtu_async_halt_req"); @160 +// &Force("output","tdt_dm_dtu_resume_req"); @161 +// &Force("output","tdt_dm_dtu_halt_on_reset") @162 +// &Force("output","tdt_dm_dtu_halt_req_cause");&Force("bus","tdt_dm_dtu_halt_req_cause",`TDT_DM_CORE_NUM*2-1,0); @163 +// &Force("input","dtu_tdt_dm_halted"); @164 +// &Force("input","dtu_tdt_dm_havereset") @165 +// &Force("output","tdt_dm_dtu_ack_havereset"); @166 +// &Force("input","pad_tdt_dm_core_unavail"); @167 +// &Force("output","tdt_dm_dtu_itr");&Force("bus","tdt_dm_dtu_itr",31,0); @168 +// &Force("output","tdt_dm_dtu_itr_vld"); @169 +// &Force("input","dtu_tdt_dm_itr_done"); @170 +// &Force("input","dtu_tdt_dm_retire_debug_expt_vld"); @171 +// &Force("output","tdt_dm_dtu_wr_vld"); @172 +// &Force("output","tdt_dm_pad_hartreset_n");&Force("bus","tdt_dm_pad_hartreset_n",`TDT_DM_CORE_NUM-1,0); @174 +// &Force("output","tdt_dm_dtu_halt_req");&Force("bus","tdt_dm_dtu_halt_req",`TDT_DM_CORE_NUM-1,0); @175 +// &Force("output","tdt_dm_dtu_async_halt_req");&Force("bus","tdt_dm_dtu_async_halt_req",`TDT_DM_CORE_NUM-1,0); @176 +// &Force("output","tdt_dm_dtu_resume_req");&Force("bus","tdt_dm_dtu_resume_req",`TDT_DM_CORE_NUM-1,0); @177 +// &Force("output","tdt_dm_dtu_halt_on_reset");&Force("bus","tdt_dm_dtu_halt_on_reset",`TDT_DM_CORE_NUM-1,0); @178 +// &Force("output","tdt_dm_dtu_halt_req_cause");&Force("bus","tdt_dm_dtu_halt_req_cause",`TDT_DM_CORE_NUM*2-1,0); @179 +// &Force("input","dtu_tdt_dm_halted");&Force("bus","dtu_tdt_dm_halted",`TDT_DM_CORE_NUM-1,0); @180 +// &Force("input","dtu_tdt_dm_havereset");&Force("bus","dtu_tdt_dm_havereset",`TDT_DM_CORE_NUM-1,0); @181 +// &Force("output","tdt_dm_dtu_ack_havereset");&Force("bus","tdt_dm_dtu_ack_havereset",`TDT_DM_CORE_NUM-1,0); @182 +// &Force("input","pad_tdt_dm_core_unavail");&Force("bus","pad_tdt_dm_core_unavail",`TDT_DM_CORE_NUM-1,0); @183 +// &Force("output","tdt_dm_dtu_itr");&Force("bus","tdt_dm_dtu_itr",31,0); @184 +// &Force("output","tdt_dm_dtu_itr_vld");&Force("bus","tdt_dm_dtu_itr_vld",`TDT_DM_CORE_NUM-1,0); @185 +// &Force("input","dtu_tdt_dm_itr_done");&Force("bus","dtu_tdt_dm_itr_done",`TDT_DM_CORE_NUM-1,0); @186 +// &Force("input","dtu_tdt_dm_retire_debug_expt_vld");&Force("bus","dtu_tdt_dm_retire_debug_expt_vld",`TDT_DM_CORE_NUM-1,0); @187 +// &Force("output","tdt_dm_dtu_wr_vld");&Force("bus","tdt_dm_dtu_wr_vld",`TDT_DM_CORE_NUM-1,0); @188 +// &Force("output","tdt_dm_dtu_wr_flg"); @190 +// &Force("bus","tdt_dm_dtu_wr_flg",1,0); @191 +// &Force("output","tdt_dm_dtu_wdata"); @192 +// &Force("bus","tdt_dm_dtu_wdata",`TDT_DM_CORE_MAX_XLEN-1,0); @193 +// &Force("input","dtu_tdt_dm_wr_ready"); @195 +// &Force("input","dtu_tdt_dm_wr_ready");&Force("bus","dtu_tdt_dm_wr_ready",`TDT_DM_CORE_NUM-1,0); @197 + +// &Force("input","dtu_tdt_dm_rx_data"); @200 +// &Force("bus","dtu_tdt_dm_rx_data",`TDT_DM_CORE_MAX_XLEN * `TDT_DM_CORE_NUM - 1,0); @201 + +// &Force("input","pad_tdt_dm_halt_req"); @204 +// &Force("bus","pad_tdt_dm_halt_req",`TDT_DM_EXTHALTTRI_NUM-1,0); @205 +// &Force("input","pad_tdt_dm_resume_req"); @206 +// &Force("bus","pad_tdt_dm_resume_req",`TDT_DM_EXTRESUMETRI_NUM-1,0); @207 +// &Force("output","tdt_dm_pad_halt_req"); @208 +// &Force("bus","tdt_dm_pad_halt_req",`TDT_DM_EXTHALTTRI_NUM-1,0); @209 +// &Force("output","tdt_dm_pad_resume_req"); @210 +// &Force("bus","tdt_dm_pad_resume_req",`TDT_DM_EXTRESUMETRI_NUM-1,0); @211 + +// &Force("output","tdt_dm_pad_awid"); @215 +// &Force("bus","tdt_dm_pad_awid",3,0); @216 +// &Force("output","tdt_dm_pad_awaddr"); @217 +// &Force("bus","tdt_dm_pad_awaddr",`TDT_DM_SBAW-1,0); @218 +// &Force("output","tdt_dm_pad_awlen"); @219 +// &Force("bus","tdt_dm_pad_awlen",3,0); @220 +// &Force("output","tdt_dm_pad_awsize"); @221 +// &Force("bus","tdt_dm_pad_awsize",2,0); @222 +// &Force("output","tdt_dm_pad_awvalid"); @223 +// &Force("input","pad_tdt_dm_awready"); @224 +// &Force("output","tdt_dm_pad_wdata"); @225 +// &Force("bus","tdt_dm_pad_wdata",`TDT_DM_SBA_DW-1,0); @226 +// &Force("output","tdt_dm_pad_wvalid"); @227 +// &Force("output","tdt_dm_pad_wlast"); @228 +// &Force("output","tdt_dm_pad_wstrb"); @229 +// &Force("bus","tdt_dm_pad_wstrb",`TDT_DM_SBA_BW-1,0); @230 +// &Force("input","pad_tdt_dm_wready"); @231 +// &Force("output","tdt_dm_pad_bready"); @232 +// &Force("input","pad_tdt_dm_bid"); @233 +// &Force("bus","pad_tdt_dm_bid",3,0); @234 +// &Force("input","pad_tdt_dm_bresp"); @235 +// &Force("bus","pad_tdt_dm_bresp",1,0); @236 +// &Force("input","pad_tdt_dm_bvalid"); @237 +// &Force("output","tdt_dm_pad_arid"); @239 +// &Force("bus","tdt_dm_pad_arid",3,0); @240 +// &Force("output","tdt_dm_pad_araddr"); @241 +// &Force("bus","tdt_dm_pad_araddr",`TDT_DM_SBAW-1,0); @242 +// &Force("output","tdt_dm_pad_arlen"); @243 +// &Force("bus","tdt_dm_pad_arlen",3,0); @244 +// &Force("output","tdt_dm_pad_arsize"); @245 +// &Force("bus","tdt_dm_pad_arsize",2,0); @246 +// &Force("output","tdt_dm_pad_arvalid"); @247 +// &Force("input","pad_tdt_dm_arready"); @248 +// &Force("input","pad_tdt_dm_rid"); @250 +// &Force("bus","pad_tdt_dm_rid",3,0); @251 +// &Force("input","pad_tdt_dm_rdata"); @252 +// &Force("bus","pad_tdt_dm_rdata",`TDT_DM_SBA_DW-1,0); @253 +// &Force("input","pad_tdt_dm_rvalid"); @254 +// &Force("input","pad_tdt_dm_rlast"); @255 +// &Force("input","pad_tdt_dm_rresp"); @256 +// &Force("bus","pad_tdt_dm_rresp",1,0); @257 +// &Force("output","tdt_dm_pad_rready"); @259 +// &Force("output","tdt_dm_pad_awburst"); @261 +// &Force("bus","tdt_dm_pad_awburst",1,0); @262 +// &Force("output","tdt_dm_pad_awcache"); @263 +// &Force("bus","tdt_dm_pad_awcache",3,0); @264 +// &Force("output","tdt_dm_pad_awlock"); @265 +// //&Force("bus","tdt_dm_pad_awlock",1,0); @266 +// &Force("output","tdt_dm_pad_awprot"); @267 +// &Force("bus","tdt_dm_pad_awprot",2,0); @268 +// &Force("output","tdt_dm_pad_arburst"); @269 +// &Force("bus","tdt_dm_pad_arburst",1,0); @270 +// &Force("output","tdt_dm_pad_arcache"); @271 +// &Force("bus","tdt_dm_pad_arcache",3,0); @272 +// &Force("output","tdt_dm_pad_arlock"); @273 +// //&Force("bus","tdt_dm_pad_arlock",1,0); @274 +// &Force("output","tdt_dm_pad_arprot"); @275 +// &Force("bus","tdt_dm_pad_arprot",2,0); @276 +// &Force("output","tdt_dm_pad_htrans"); @279 +// &Force("bus","tdt_dm_pad_htrans",1,0); @280 +// &Force("output","tdt_dm_pad_hprot"); @281 +// &Force("bus","tdt_dm_pad_hprot",3,0); @282 +// &Force("output","tdt_dm_pad_hmastlock"); @283 +// &Force("output","tdt_dm_pad_haddr"); @285 +// &Force("bus","tdt_dm_pad_haddr",`TDT_DM_SBAW-1,0); @286 +// &Force("output","tdt_dm_pad_hwrite"); @287 +// &Force("output","tdt_dm_pad_hburst"); @288 +// &Force("bus","tdt_dm_pad_hburst",2,0); @289 +// &Force("output","tdt_dm_pad_hsize"); @290 +// &Force("bus","tdt_dm_pad_hsize",2,0); @291 +// &Force("output","tdt_dm_pad_hwdata"); @292 +// &Force("bus","tdt_dm_pad_hwdata",`TDT_DM_SBA_DW-1,0); @293 +// &Force("input","pad_tdt_dm_hrdata"); @294 +// &Force("bus","pad_tdt_dm_hrdata",`TDT_DM_SBA_DW-1,0); @295 +// &Force("input","pad_tdt_dm_hready"); @296 +// &Force("input","pad_tdt_dm_hresp"); @297 + + +// &ModuleEnd; @301 +endmodule + + + diff --git a/XUANTIE-RV_opene906/README.md b/XUANTIE-RV_opene906/README.md new file mode 100644 index 0000000000000000000000000000000000000000..54b5ad8af9a2b8826adcbc329cd80b1413ee88a5 --- /dev/null +++ b/XUANTIE-RV_opene906/README.md @@ -0,0 +1,75 @@ +# IP Readme + + Welcome to E906! Some key directories are shown below. +``` +|--E906_RTL_FACRORY/ + |--gen_rtl/ ##the source verilog code of E906 + |--setup/ ##set the environment variables +|--smart_run/ ##the RTL simulation environment + |--impl/ ##sdc file + |--logical/ ##the SoC demo and test bench to run the simulation + |--setup/ ##GNU tool chain setting + |--tests/ ##include the test suit, linker file, boot code and so on + |--work/ ##the working directory + |--Makefile ##the simulation script +|--doc/ ##the user and integration manual of E906 +``` + + +## Usage + + Step1: Get Started + +``` +$ cd E906_RTL_FACTORY +$ source setup/setup.csh +$ cd ../smart_run +$ make help +To gain more information about how to use smart testbench. +``` + + + Step2: Download and install C/C++ Compiler + +``` +You can download the GNU tool chain compiled by T-HEAD from the url below: +https://occ.t-head.cn/community/download?id=3948120165480468480 + +$ cd ./smart_run +GNU tool chain (specific riscv version) must be installed and specified before +compiling *.c/*.v tests of the smart environment. Please refer to the following +setup file about how to specify it: + ./smart_run/setup/example_setup.csh +``` + + +## Notes + +``` +The testbench supports iverilog, vcs and irun to run simulation and you can use Gtkwave or verdi +to open the waveform under ./smart_run/work/ directory. + +You can get the debugger, IDE and SDK from the url:https://occ.t-head.cn/community/download?id=575997419775328256 +``` + + +## Discussion + If you are interested in participating in discussions or improving the "openXuantie" cores, you can scan the DingDing QR code below to join the discussion group. + + + +#/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. +# +#Licensed under the Apache License, Version 2.0 (the "License"); +#you may not use this file except in compliance with the License. +#You may obtain a copy of the License at +# +### http://www.apache.org/licenses/LICENSE-2.0 +# +#Unless required by applicable law or agreed to in writing, software +#distributed under the License is distributed on an "AS IS" BASIS, +#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +#See the License for the specific language governing permissions and +#limitations under the License. +#*/ + diff --git a/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_bht_mem_test.v b/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_bht_mem_test.v new file mode 100644 index 0000000000000000000000000000000000000000..4cc922c2ff82b4730faceab426b0249d0286de26 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_bht_mem_test.v @@ -0,0 +1,205 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +`define CLK_PERIOD 10 +//`include "../../../cpu/cpu_cfig.h" + +module e906_bht_mem_test(bht_mem_test_pass); + +output bht_mem_test_pass; +`ifdef BHT_2K + parameter LOCAL_DATA_ADDR_WIDTH = 7; +`elsif BHT_4K + parameter LOCAL_DATA_ADDR_WIDTH = 8; +`elsif BHT_8K + parameter LOCAL_DATA_ADDR_WIDTH = 9; +`elsif BHT_16K + parameter LOCAL_DATA_ADDR_WIDTH = 10; +`endif + +parameter LOCAL_DATA_DATA_WIDTH = 16; +parameter LOCAL_DATA_WE_WIDTH = 16; + +reg forever_clk; + +reg [LOCAL_DATA_ADDR_WIDTH-1:0] bht_data_idx; +reg [LOCAL_DATA_DATA_WIDTH-1:0] bht_data_din; +wire [LOCAL_DATA_DATA_WIDTH-1:0] bht_data_dout; +reg [LOCAL_DATA_DATA_WIDTH-1:0] data_mask; +reg [LOCAL_DATA_DATA_WIDTH-1:0] data_mask_ff; +reg [LOCAL_DATA_DATA_WIDTH-1:0] golden_data; +reg bht_data_gwen; +reg [LOCAL_DATA_WE_WIDTH-1:0] bht_data_wen; +reg bht_data_cen; +reg bht_data_clk; + +reg bht_mem_test_pass; +//bht data array +`ifdef BHT_2K + pa_spsram_128x16 x_bht_array( +`elsif BHT_4K + pa_spsram_256x16 x_bht_array( +`elsif BHT_8K + pa_spsram_512x16 x_bht_array( +`elsif BHT_16K + pa_spsram_1024x16 x_bht_array( +`endif + .A (bht_data_idx[LOCAL_DATA_ADDR_WIDTH-1:0] ), + .CEN (bht_data_cen ), + .CLK (bht_data_clk ), + .D (bht_data_din[LOCAL_DATA_DATA_WIDTH-1:0] ), + .GWEN (bht_data_gwen ), + .Q (bht_data_dout[LOCAL_DATA_DATA_WIDTH-1:0] ), + .WEN (bht_data_wen[LOCAL_DATA_WE_WIDTH-1:0] ) + ); + + +always + #(`CLK_PERIOD/2) bht_data_clk = ~bht_data_clk; +always + #(`CLK_PERIOD/2) forever_clk = ~forever_clk; + +always@(posedge bht_data_clk) +begin + data_mask <= bht_data_wen[LOCAL_DATA_WE_WIDTH-1:0]; +end + +integer i; + +initial +begin +bht_data_clk = 0; +forever_clk = 0; +bht_mem_test_pass = 0; +repeat(50)@(posedge bht_data_clk) +//cen = 0 test +bht_data_cen = 1; +bht_data_wen = {LOCAL_DATA_WE_WIDTH{1'b1}}; +bht_data_gwen = 1'b1; +bht_data_idx = 0; +bht_data_din = 0; +for(i=0;i<10;i=i+1) +begin + @(posedge bht_data_clk) + bht_data_cen <= 0; + bht_data_gwen <= 1'b0; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b0}}; + bht_data_idx <= {LOCAL_DATA_ADDR_WIDTH{1'b0}} + i; + bht_data_din <= {LOCAL_DATA_DATA_WIDTH{1'b0}} + i; + @(posedge bht_data_clk) + bht_data_gwen <= 1'b1; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b1}}; + golden_data <= bht_data_din; + @(posedge bht_data_clk) + @(posedge bht_data_clk) + if(bht_data_dout != golden_data) + begin + $display("bht array cen == 0 test fail when i is %d!!!\n", i); + repeat(10)@(posedge bht_data_clk) + $finish; + end +end + +//cen = 1 test +bht_data_cen = 1; +bht_data_gwen = 1'b1; +bht_data_wen = {LOCAL_DATA_WE_WIDTH{1'b1}}; +bht_data_idx = 0; +bht_data_din = 0; +for(i=10;i<20;i=i+1) +begin + @(posedge bht_data_clk) + bht_data_cen <= 1; + bht_data_gwen <= 1'b0; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b0}}; + bht_data_idx <= {LOCAL_DATA_ADDR_WIDTH{1'b0}} + i; + bht_data_din <= {LOCAL_DATA_DATA_WIDTH{1'b0}} + i; + @(posedge bht_data_clk) + bht_data_gwen <= 1'b1; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b1}}; + golden_data <= bht_data_din; + @(posedge bht_data_clk) + @(posedge bht_data_clk) + if(bht_data_dout == golden_data) + begin + $display("bht array cen == 1 test fail when i is %d!!!\n", i); + repeat(10)@(posedge bht_data_clk) + $finish; + end +end + +//wen test +bht_data_cen = 1; +bht_data_gwen = 1'b1; +bht_data_wen = {LOCAL_DATA_WE_WIDTH{1'b1}}; +bht_data_idx = 0; +bht_data_din = 0; +for(i=0;i> i; + bht_data_din <= {LOCAL_DATA_DATA_WIDTH{1'b1}}; + @(posedge bht_data_clk) + bht_data_gwen <= 1'b1; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b1}}; + golden_data <= bht_data_din; + data_mask_ff <= data_mask; + @(posedge bht_data_clk) + @(posedge bht_data_clk) + if(golden_data != bht_data_dout & (~data_mask_ff)) + begin + $display("bht array wen test fail when i is %d, golden_data is 0x%h, data out is 0x%h\n", i, golden_data, bht_data_dout); + repeat(10)@(posedge bht_data_clk) + $finish; + end +end + + +//read and write test +bht_data_cen = 1; +bht_data_gwen = 1'b1; +bht_data_wen = {LOCAL_DATA_WE_WIDTH{1'b1}}; +bht_data_idx = 0; +bht_data_din = 0; +for(i=0;i<={LOCAL_DATA_ADDR_WIDTH{1'b1}};i=i+1) +begin + @(posedge bht_data_clk) + bht_data_cen <= 0; + bht_data_gwen <= 1'b0; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b0}}; + bht_data_idx <= {LOCAL_DATA_ADDR_WIDTH{1'b0}} + i; + bht_data_din <= {LOCAL_DATA_DATA_WIDTH{1'b1}}; + @(posedge bht_data_clk) + bht_data_gwen <=1'b1; + bht_data_wen <= {LOCAL_DATA_WE_WIDTH{1'b1}}; + @(posedge bht_data_clk) + @(posedge bht_data_clk) + bht_data_idx <= {LOCAL_DATA_ADDR_WIDTH{1'b0}} + i + 1; + if(bht_data_dout != {LOCAL_DATA_DATA_WIDTH{1'b1}}) + begin + $display("bht array read/write test fail when addr is %d\n", i); + repeat(10)@(posedge bht_data_clk) + $finish; + end +end + bht_mem_test_pass = 1; +end + + + + + +endmodule diff --git a/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_mem_test_tb.v b/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_mem_test_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..003a7655049935b41adb54f59b4dc8b5da55efdb --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/impl/mem_validate/e906_mem_test_tb.v @@ -0,0 +1,51 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +module e906_mem_test_tb(); + +wire bht_mem_test_pass; + + + +initial +begin + #100000; + if(bht_mem_test_pass) + begin + $display("*************************************************\n"); + $display("*************BHT MEMORY TEST PASS!!!*************\n"); + $display("*************************************************\n"); + end + else begin + $display("*************************************************\n"); + $display("*************BHT MEMORY TEST FAIL!!!*************\n"); + $display("*************************************************\n"); + $display("*************************************************\n"); + $display("**********SORRY!!! MEMORY TEST FAIL!!!***********\n"); + $display("*************************************************\n"); + $finish; + end + +end + +e906_bht_mem_test x_bht_mem_test (.bht_mem_test_pass(bht_mem_test_pass)); + +initial +begin + $dumpfile("test.vcd"); + $dumpvars; +end + +endmodule diff --git a/XUANTIE-RV_opene906/smart_run/impl/sdc/e906.sdc b/XUANTIE-RV_opene906/smart_run/impl/sdc/e906.sdc new file mode 100644 index 0000000000000000000000000000000000000000..a0ddd9570aeeb35b76da290ab4a367323db0aacc --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/impl/sdc/e906.sdc @@ -0,0 +1,160 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +set ClkMargin 1 + +################################################################################ +# GLOBAL UNITS +################################################################################ +set_units -time ns +set_units -capacitance pF + +set_case_analysis 0 [get_ports pad_yy_scan_mode] +set_case_analysis 0 [get_ports pad_yy_icg_scan_en] +set_case_analysis 0 [get_ports pad_yy_icg_scan_en] + +# CPU_CLOCK +#set CPUClkFrequency 150 +set CPUClkFrequency 1000 +set CPUClkName CPU_CLOCK +set CPUClkPoint pll_core_cpuclk +create_clock -period [expr 1000.0/($CPUClkFrequency*$ClkMargin)] -name $CPUClkName [get_ports pll_core_cpuclk] + +# JTG_CLOCK +set JTAGClkFrequency 25 +set JTAGClkName JTG_CLOCK +set JTAGClkPoint pad_had_jtg_tclk +create_clock -period [expr 1000.0/($JTAGClkFrequency*$ClkMargin)] -name $JTAGClkName [get_ports pad_had_jtg_tclk] + +set CPU_PERIOD [expr 1000.0/($CPUClkFrequency*$ClkMargin)] +set JTG_PERIOD [expr 1000.0/($JTAGClkFrequency*$ClkMargin)] + +set CLK_INPUTS [get_ports {*clk *clock *tck}] +set DATA_INPUTS [remove_from_collection [all_inputs] $CLK_INPUTS] +# CLIC_CLKx_pa_tcipif_top.x_pa_clic_top.x_clicreg_clk.clk_out +set CLIC_CLK "yes" +if {$CLIC_CLK == "yes"} { +create_generated_clock -name CLIC_CLK -source [get_ports pll_core_cpuclk] -edges {1 2 5} [filter [get_flat_pins x_pa_tcipif_top*x_pa_clic_top*x_clicreg_clk*x_gated_clk_cell/*] direction==out] +set_multicycle_path -from CPU_CLOCK -to CLIC_CLK -setup 2 -start +set_multicycle_path -from CPU_CLOCK -to CLIC_CLK -hold 1 -start +set_multicycle_path -from CLIC_CLK -to CPU_CLOCK -setup 2 -end +set_multicycle_path -from CLIC_CLK -to CPU_CLOCK -hold 1 -end +} + +set DC_setup_uncertainty 0.2 +set DC_hold_uncertainty 0.08 +set DC_max_fanout 32 +set DC_max_transition 0.5 + +if {$PROCESS == "UMC28"} { + set DC_setup_uncertainty 0.3 +} + +set_max_fanout $DC_max_fanout [current_design] +set_max_transition $DC_max_transition [current_design] +set_input_transition 0.1 $CLK_INPUTS + +set_clock_uncertainty -setup $DC_setup_uncertainty [all_clocks] +set_clock_uncertainty -hold $DC_hold_uncertainty [all_clocks] + + + +if {$CLIC_CLK == "yes"} { + set CLIC_INPUTS [get_ports {pad_clic_int_vld* pad_cpu_ext_int_b pad_cpu_sys_cnt*}] + set DATA_INPUTS [remove_from_collection $DATA_INPUTS $CLIC_INPUTS] +} + + +################################################################################ +# Ports Constrains +################################################################################ +#JTAG Ports +set JTAG_INPUTS [get_ports {pad_had_jtg_*}] +set JTAG_OUTPUTS [get_ports {had_pad_jtg_*}] +set DATA_INPUTS [remove_from_collection $DATA_INPUTS $JTAG_INPUTS] +set DATA_OUTPUTS [remove_from_collection [all_outputs] $JTAG_OUTPUTS] + +#JTAG Ports +set JTAG_INPUTS [get_ports {pad_had_jtg_*}] +set JTAG_OUTPUTS [get_ports {had_pad_jtg_*}] +set DATA_INPUTS [remove_from_collection $DATA_INPUTS $JTAG_INPUTS] +set DATA_OUTPUTS [remove_from_collection [all_outputs] $JTAG_OUTPUTS] + +set LOOSE_BUS_CONSTRAIN "no" +if {$LOOSE_BUS_CONSTRAIN == "yes"} { + set_false_path -from [all_inputs] + set_false_path -to [all_outputs] +} else { + #Jtag + set_input_delay -max [expr $JTG_PERIOD*0.4] -clock $JTAGClkName $JTAG_INPUTS + set_input_delay -min [expr $JTG_PERIOD*0.2] -clock $JTAGClkName $JTAG_INPUTS + + set_output_delay -max [expr $JTG_PERIOD*0.4] -clock $JTAGClkName $JTAG_OUTPUTS + set_output_delay -min [expr $JTG_PERIOD*0.2] -clock $JTAGClkName $JTAG_OUTPUTS + + #Default IO + set_input_delay -max [expr $CPU_PERIOD*0.4] -clock $CPUClkName $DATA_INPUTS + set_input_delay -min [expr $CPU_PERIOD*0.2] -clock $CPUClkName $DATA_INPUTS + + set_output_delay -max [expr $CPU_PERIOD*0.4] -clock $CPUClkName $DATA_OUTPUTS + set_output_delay -min [expr $CPU_PERIOD*0.2] -clock $CPUClkName $DATA_OUTPUTS + + #Timing Critical Ports + set_input_delay -max [expr $CPU_PERIOD*0.6] -clock $CPUClkName [get_ports {*hrdata*}] + set_input_delay -min [expr $CPU_PERIOD*0.3] -clock $CPUClkName [get_ports {*hrdata*}] + + set_output_delay -max [expr $CPU_PERIOD*0.6] -clock $CPUClkName [get_ports {*haddr* biu_pad_*}] + set_output_delay -min [expr $CPU_PERIOD*0.3] -clock $CPUClkName [get_ports {*haddr* biu_pad_*}] + +} + + +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_inst_retire*] +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_inst_split*] +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_retire_pc*] +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_wb_data*] +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_wb_preg*] +set_output_delay 0 -clock CPU_CLOCK [get_ports rtu_pad_wb_vld*] +set_output_delay 0 -clock CPU_CLOCK [get_ports lsu_pad_sc_pass*] +set_output_delay 0 -clock CPU_CLOCK [get_ports cp0_pad_mcause*] +set_output_delay 0 -clock CPU_CLOCK [get_ports cp0_pad_mintstatus*] +set_output_delay 0 -clock CPU_CLOCK [get_ports cp0_pad_mstatus*] + + +set_false_path -from CPU_CLOCK -to JTG_CLOCK +set_false_path -from JTG_CLOCK -to CPU_CLOCK +set_false_path -from [get_ports pad_cpu_rst_b] +set_false_path -from [get_ports pad_had_rst_b] +set_false_path -from [get_ports {pad_*_dahbl_base* pad_*_dahbl_mask* pad_*_iahbl_base* pad_*_iahbl_mask*}] + + +set CPUCLK_PER [expr 1000.0/($CPUClkFrequency*$ClkMargin)] +set Gateclk_cell [remove_from_collection [get_cells -hierarchical * -filter "ref_name =~ *CKLNQD1BWP*"] [get_cells -hierarchical * -filter "@full_name=~ *x_clic_clk*"]] + +if {$PROCESS == "UMC28"} { + set_clock_gating_check -setup [expr $CPUCLK_PER*0.2] [get_cells -hierarchical * -filter "ref_name =~ *PREICG*"] +} else { + set_clock_gating_check -setup [expr $CPUCLK_PER*0.2] [get_cells -hierarchical * -filter "ref_name =~ *CKLNQD*"] +} +#design for mul two cycle +set_clock_latency 0.2 [get_pins -of_objects [get_cells -hierarchical * -filter "full_name=~*x_pa_iu_mul/mul_ex2_wb_res_*&&is_sequential==true&&is_hierarchical==false&&ref_name!~*CKGT*"] -filter "direction==in&&full_name=~*clocked_on*"] + +############################################################ +# clock gating varailbes define +############################################################ +set ClockGatingSetup [expr 0.1*(1000.0/($CPUClkFrequency*$ClkMargin))] +set ClockGatingHold 0 + +set ClockGatingSyn true ; # true/false + diff --git a/XUANTIE-RV_opene906/smart_run/impl/sdc/tdt_dmi_top.sdc b/XUANTIE-RV_opene906/smart_run/impl/sdc/tdt_dmi_top.sdc new file mode 100644 index 0000000000000000000000000000000000000000..0038d4d52f9659ec6c2a37df59603d662283fa5a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/impl/sdc/tdt_dmi_top.sdc @@ -0,0 +1,155 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +############################################################################################# +# For Upper Level Flatten STA: set parent_path, e.g. "soc_top/aaa_top/bbb_top/" +# set cpu clock name of current chip, e.g. PLL_DIV_CLK_4 +# Keep Default Settings for Block-Level Implementation +############################################################################################# + +if {![info exist parent_path]} { set parent_path "" } ;# Default "" +if {![info exist APB_CLK_NAME]} { set APB_CLK_NAME SYS_APB_CLK } ;# Default SYS_APB_CLK +if {![info exist JTG_CLK_NAME]} { set JTG_CLK_NAME JTG_CLK } ;# Default JTG_CLK + +################################################################################ +# Initial variables for synthesis; modify this part based on design +################################################################################ + +set IF_READ_BUIDIN_VARIABLES 0 ;# For standalone usage, set to "1" ; For synthesis, set to "0" +set SYS_APB_SYNC 0 ; # For sync apb set to "1", for async apb set to "0" + +set CPU_PERIOD [expr (1000.00/1000)] ;# CPU is constrained at 1.0GHz +set JTG_PERIOD [expr (1000.00/50)] ;# JTG is constrained at 50MHz + +if {$IF_READ_BUIDIN_VARIABLES} { + set SETUP_UNCERTAINTY 0.2 + set HOLD_UNCERTAINTY 0.08 + set MAX_FANOUT 32 + set MAX_TRANSITION 0.5 + + set LOAD_PIN "AN2D2BWP12T30P140/A1" + set DRIVING_CELL "BUFFD2BWP12T30P140" +} + +################################################################################# +# Proc Used in this File +################################################################################# +proc list_add_prefix {input_list prefix} { + set output_list "" + foreach element $input_list { + lappend output_list ${prefix}${element} + } + return "$output_list" +} + +proc get_args_port_pin {input_list} { + if {[string match */* $input_list]} { + return "-through \[get_pins \{$input_list\}\]" + } elseif {[string match *in* [get_attribute [get_ports [lindex $input_list 0]] direction]]} { + return "-from \[get_ports \{$input_list\}\]" + } elseif {[string match *out* [get_attribute [get_ports [lindex $input_list 0]] direction]]} { + return "-to \[get_ports \{$input_list\}\]" + } else { + echo "! port_pin_list check failed for $input_list, mixing inputs, outputs, or pins is not allowed" + } +} + +if {$synopsys_program_name=="pt_shell"} { + proc get_flat_pins {arg} { + get_pins -hier -filter "is_hierarchical==false && full_name=~$arg" + } + proc get_flat_cells {arg} { + get_cells -hier -filter "is_hierarchical==false && full_name=~$arg" + } +} + +################################################################################# +# Basic Constraints +################################################################################# +if {$parent_path==""} { + set SYS_APB_PERIOD [expr $CPU_PERIOD * 2.0] + + set CLK_INPUTS [get_ports {*clk *clock *tck}] + set DATA_INPUTS [remove_from_collection [all_inputs] $CLK_INPUTS] + + set_max_fanout $MAX_FANOUT [current_design] + set_max_transition $MAX_TRANSITION [current_design] + set_input_transition 0.1 $CLK_INPUTS + set_load [expr [load_of [get_lib_pins */$LOAD_PIN]]*5.0] [all_outputs] + set_driving_cell -lib_cell $DRIVING_CELL $DATA_INPUTS + + create_clock [get_ports sys_apb_clk] -name $APB_CLK_NAME -period $SYS_APB_PERIOD + create_clock [get_ports pad_tdt_dtm_tclk] -name $JTG_CLK_NAME -period $JTG_PERIOD + + create_clock -name V_SYS_APB_CLK -period $SYS_APB_PERIOD + create_clock -name V_JTG_CLK -period $JTG_PERIOD + + set_max_delay [expr $SYS_APB_PERIOD] ignore_clock_latency \ + -from [get_clocks [list $APB_CLK_NAME V_SYS_APB_CLK]] \ + -to [get_clocks [list $JTG_CLK_NAME V_JTG_CLK]] + set_max_delay [expr $SYS_APB_PERIOD] ignore_clock_latency \ + -from [get_clocks [list $JTG_CLK_NAME V_JTG_CLK]] \ + -to [get_clocks [list $APB_CLK_NAME V_SYS_APB_CLK]] + + set_false_path -hold -from [get_clocks [list $APB_CLK_NAME V_SYS_APB_CLK]] \ + -to [get_clocks [list $JTG_CLK_NAME V_JTG_CLK]] + set_false_path -hold -from [get_clocks [list $JTG_CLK_NAME V_JTG_CLK]] \ + -to [get_clocks [list $APB_CLK_NAME V_SYS_APB_CLK]] +} + +################################################################################ +# Ports Constrains +################################################################################ +### JTG Ports +set JTG_INPUTS {pad_tdt_dtm_*} +set JTG_OUTPUTS {tdt_dtm_pad_t*} + +if {$parent_path==""} { + set_input_delay -max [expr $JTG_PERIOD*0.9] -clock V_JTG_CLK [get_ports $JTG_INPUTS] + set_input_delay -min 0 -clock V_JTG_CLK [get_ports $JTG_INPUTS] + + set_output_delay -max [expr $JTG_PERIOD*0.9] -clock V_JTG_CLK [get_ports $JTG_OUTPUTS] -clock_fall + set_output_delay -min 0 -clock V_JTG_CLK [get_ports $JTG_OUTPUTS] -clock_fall +} + +### SYS APB Ports +set APB_INPUTS [remove_from_collection $DATA_INPUTS [get_ports $JTG_INPUTS]] +set APB_OUTPUTS [remove_from_collection [all_outputs] [get_ports $JTG_OUTPUTS]] + +if {$parent_path==""} { + set_input_delay -max [expr $SYS_APB_PERIOD*0.6] -clock V_SYS_APB_CLK [get_ports $APB_INPUTS] + set_input_delay -min 0 -clock V_SYS_APB_CLK [get_ports $APB_INPUTS] + set_output_delay -max [expr $SYS_APB_PERIOD*0.6] -clock V_SYS_APB_CLK [get_ports $APB_OUTPUTS] + set_output_delay -min 0 -clock V_SYS_APB_CLK [get_ports $APB_OUTPUTS] +} + +################################################################################ +# Group Path +################################################################################ +if {$parent_path!=""} { return } +unset parent_path + +group_path -name INPUT -from [all_inputs] +group_path -name OUTPUT -to [all_outputs] +group_path -name COMBO -from [all_inputs] -to [all_outputs] + +set_clock_uncertainty -setup $SETUP_UNCERTAINTY [all_clocks] +set_clock_uncertainty -hold $HOLD_UNCERTAINTY [all_clocks] + +################################################################################ +# Set DFT Signals +################################################################################ +set_case_analysis 0 [get_ports pad_tdt_icg_scan_en] +set_case_analysis 0 [get_ports pad_yy_scan_mode + diff --git a/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb.v b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb.v new file mode 100644 index 0000000000000000000000000000000000000000..a046795e186c7385e5a821ea87ea837cc44db205 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb.v @@ -0,0 +1,352 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +//SYS MEM +`define S1_BASE_START 32'h60000000 +`define S1_BASE_END 32'h600fffff +//APB +`define S2_BASE_START 32'h40000000 +`define S2_BASE_END 32'h4fffffff +//IMEM +`define S4_BASE_START 32'h00000000 +`define S4_BASE_END 32'h0007ffff +//DMEM +`define S5_BASE_START 32'h20000000 +`define S5_BASE_END 32'h2007ffff + +// &Depend("environment.h"); @35 +// &ModuleBeg; @36 +module ahb( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwdata, + biu_pad_hwrite, + haddr_s1, + haddr_s2, + haddr_s3, + hburst_s1, + hburst_s3, + hmastlock, + hprot_s1, + hprot_s3, + hrdata_s1, + hrdata_s2, + hrdata_s3, + hready_s1, + hready_s2, + hready_s3, + hresp_s1, + hresp_s2, + hresp_s3, + hsel_s1, + hsel_s2, + hsel_s3, + hsize_s1, + hsize_s3, + htrans_s1, + htrans_s3, + hwdata_s1, + hwdata_s2, + hwdata_s3, + hwrite_s1, + hwrite_s2, + hwrite_s3, + pad_biu_hrdata, + pad_biu_hready, + pad_biu_hresp, + pad_cpu_rst_b, + pll_core_cpuclk, + smpu_deny +); + +// &Ports; @37 +input [31:0] biu_pad_haddr; +input [2 :0] biu_pad_hburst; +input [3 :0] biu_pad_hprot; +input [2 :0] biu_pad_hsize; +input [1 :0] biu_pad_htrans; +input [31:0] biu_pad_hwdata; +input biu_pad_hwrite; +input [31:0] hrdata_s1; +input [31:0] hrdata_s2; +input [31:0] hrdata_s3; +input hready_s1; +input hready_s2; +input hready_s3; +input [1 :0] hresp_s1; +input [1 :0] hresp_s2; +input [1 :0] hresp_s3; +input pad_cpu_rst_b; +input pll_core_cpuclk; +input smpu_deny; +output [31:0] haddr_s1; +output [31:0] haddr_s2; +output [31:0] haddr_s3; +output [2 :0] hburst_s1; +output [2 :0] hburst_s3; +output hmastlock; +output [3 :0] hprot_s1; +output [3 :0] hprot_s3; +output hsel_s1; +output hsel_s2; +output hsel_s3; +output [2 :0] hsize_s1; +output [2 :0] hsize_s3; +output [1 :0] htrans_s1; +output [1 :0] htrans_s3; +output [31:0] hwdata_s1; +output [31:0] hwdata_s2; +output [31:0] hwdata_s3; +output hwrite_s1; +output hwrite_s2; +output hwrite_s3; +output [31:0] pad_biu_hrdata; +output pad_biu_hready; +output [1 :0] pad_biu_hresp; + +// &Regs; @38 +reg busy_s1; +reg busy_s2; +reg busy_s3; +reg busy_s4; +reg busy_s5; +reg [31:0] pad_biu_hrdata; +reg pad_biu_hready; +reg [1 :0] pad_biu_hresp; + +// &Wires; @39 +wire arb_block; +wire [31:0] biu_pad_haddr; +wire [2 :0] biu_pad_hburst; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire [31:0] biu_pad_hwdata; +wire biu_pad_hwrite; +wire [31:0] haddr_s1; +wire [31:0] haddr_s2; +wire [31:0] haddr_s3; +wire [2 :0] hburst_s1; +wire [2 :0] hburst_s2; +wire [2 :0] hburst_s3; +wire hmastlock; +wire [3 :0] hprot_s1; +wire [3 :0] hprot_s2; +wire [3 :0] hprot_s3; +wire [31:0] hrdata_s1; +wire [31:0] hrdata_s2; +wire [31:0] hrdata_s3; +wire [31:0] hrdata_s4; +wire [31:0] hrdata_s5; +wire hready_s1; +wire hready_s2; +wire hready_s3; +wire hready_s4; +wire hready_s5; +wire [1 :0] hresp_s1; +wire [1 :0] hresp_s2; +wire [1 :0] hresp_s3; +wire [1 :0] hresp_s4; +wire [1 :0] hresp_s5; +wire hsel_s1; +wire hsel_s2; +wire hsel_s3; +wire hsel_s4; +wire hsel_s5; +wire [2 :0] hsize_s1; +wire [2 :0] hsize_s2; +wire [2 :0] hsize_s3; +wire [1 :0] htrans_s1; +wire [1 :0] htrans_s2; +wire [1 :0] htrans_s3; +wire [31:0] hwdata_s1; +wire [31:0] hwdata_s2; +wire [31:0] hwdata_s3; +wire hwrite_s1; +wire hwrite_s2; +wire hwrite_s3; +wire pad_cpu_rst_b; +wire pll_core_cpuclk; +wire pre_busy_s1; +wire pre_busy_s2; +wire pre_busy_s3; +wire pre_busy_s4; +wire pre_busy_s5; +wire smpu_deny; + + + + +// Support AHB LITE +assign hmastlock = 1'b0; +// &Force("input","biu_pad_hbusreq"); @48 + +assign haddr_s1[31:0] = biu_pad_haddr[31:0]; +assign hburst_s1[2:0] = biu_pad_hburst[2:0]; +assign hprot_s1[3:0] = biu_pad_hprot[3:0]; +assign hsize_s1[2:0] = biu_pad_hsize[2:0]; +assign htrans_s1[1:0] = biu_pad_htrans[1:0]; +assign hwrite_s1 = biu_pad_hwrite; +assign hwdata_s1[31:0] = biu_pad_hwdata[31:0]; + +assign haddr_s2[31:0] = biu_pad_haddr[31:0]; +assign hburst_s2[2:0] = biu_pad_hburst[2:0]; +assign hprot_s2[3:0] = biu_pad_hprot[3:0]; +assign hsize_s2[2:0] = biu_pad_hsize[2:0]; +assign htrans_s2[1:0] = biu_pad_htrans[1:0]; +assign hwrite_s2 = biu_pad_hwrite; +assign hwdata_s2[31:0] = biu_pad_hwdata[31:0]; +// &Force("nonport","hburst_s2"); @68 +// &Force("nonport","hsize_s2"); @69 +// &Force("nonport","htrans_s2"); @70 +// &Force("nonport","hprot_s2"); @71 +// &Force("bus","biu_pad_hprot",3,0); @72 + +assign haddr_s3[31:0] = biu_pad_haddr[31:0]; +assign hburst_s3[2:0] = biu_pad_hburst[2:0]; +assign hprot_s3[3:0] = biu_pad_hprot[3:0]; +assign hsize_s3[2:0] = biu_pad_hsize[2:0]; +assign htrans_s3[1:0] = biu_pad_htrans[1:0]; +assign hwrite_s3 = biu_pad_hwrite; +assign hwdata_s3[31:0] = biu_pad_hwdata[31:0]; + +assign hready_s4 = 1'b0; +assign hrdata_s4[31:0] = 32'b0; +assign hresp_s4[1:0] = 2'b0; + +// &Force("output","hsel_s4"); @95 + +assign hready_s5 = 1'b0; +assign hrdata_s5[31:0] = 32'b0; +assign hresp_s5[1:0] = 2'b0; + +// &Force("output","hsel_s5"); @113 + +// &Force("output","hsel_s1"); @117 +// &Force("output","hsel_s2"); @118 +// &Force("output","hsel_s3"); @119 + +assign hsel_s1 = (biu_pad_htrans[1]==1'b1) && (biu_pad_haddr >= `S1_BASE_START) && (biu_pad_haddr <= `S1_BASE_END) + && !arb_block && !smpu_deny; +assign hsel_s2 = (biu_pad_htrans[1]==1'b1) && (biu_pad_haddr >= `S2_BASE_START) && (biu_pad_haddr <= `S2_BASE_END) + && !arb_block && !smpu_deny; +assign hsel_s3 = (biu_pad_htrans[1]==1'b1) && (!hsel_s1 && !hsel_s2 && !hsel_s4 && !hsel_s5 + || smpu_deny) && !arb_block; + +assign hsel_s4 = 0; + +assign hsel_s5 = 0; + + +assign pre_busy_s1 = hsel_s1 || busy_s1 && !hready_s1; +assign pre_busy_s2 = hsel_s2 || busy_s2 && !hready_s2; +assign pre_busy_s3 = hsel_s3 || busy_s3 && !hready_s3; +assign pre_busy_s4 = 1'b0; + +assign pre_busy_s5 = 1'b0; +always @(posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b)begin + busy_s1 <= 1'b0; + busy_s2 <= 1'b0; + busy_s3 <= 1'b0; + busy_s4 <= 1'b0; + busy_s5 <= 1'b0; + end + else begin + busy_s1 <= pre_busy_s1; + busy_s2 <= pre_busy_s2; + busy_s3 <= pre_busy_s3; + busy_s4 <= pre_busy_s4; + busy_s5 <= pre_busy_s5; + end +end + +assign arb_block = busy_s1 && !hready_s1 || + busy_s2 && !hready_s2 || + busy_s3 && !hready_s3 || + busy_s4 && !hready_s4 || + busy_s5 && !hready_s5; + +//arbitration state machine +// &CombBeg; @182 +always @( hresp_s3[1:0] + or hready_s5 + or hresp_s1[1:0] + or busy_s3 + or busy_s4 + or hresp_s5[1:0] + or hrdata_s3[31:0] + or hready_s3 + or busy_s2 + or hrdata_s2[31:0] + or hrdata_s1[31:0] + or hresp_s4[1:0] + or busy_s5 + or hready_s2 + or busy_s1 + or hrdata_s4[31:0] + or hready_s4 + or hrdata_s5[31:0] + or hresp_s2[1:0] + or hready_s1) +begin + case({busy_s1,busy_s2,busy_s3,busy_s4,busy_s5}) + 5'b10000: + begin + pad_biu_hrdata[31:0] = hrdata_s1[31:0]; + pad_biu_hready = hready_s1; + pad_biu_hresp[1:0] = hresp_s1[1:0]; + end + 5'b01000: + begin + pad_biu_hrdata[31:0] = hrdata_s2[31:0]; + pad_biu_hready = hready_s2; + pad_biu_hresp[1:0] = hresp_s2[1:0]; + end + 5'b00100: + begin + pad_biu_hrdata[31:0] = hrdata_s3[31:0]; + pad_biu_hready = hready_s3; + pad_biu_hresp[1:0] = hresp_s3[1:0]; + end + 5'b00010: + begin + pad_biu_hrdata[31:0] = hrdata_s4[31:0]; + pad_biu_hready = hready_s4; + pad_biu_hresp[1:0] = hresp_s4[1:0]; + end + 5'b00001: + begin + pad_biu_hrdata[31:0] = hrdata_s5[31:0]; + pad_biu_hready = hready_s5; + pad_biu_hresp[1:0] = hresp_s5[1:0]; + end + default: + begin + pad_biu_hrdata[31:0] = 32'b0; + pad_biu_hready = 1'b1; + pad_biu_hresp[1:0] = 2'b0; + end + endcase +// &CombEnd; @221 +end +// &ModuleEnd; @222 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo.v b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo.v new file mode 100644 index 0000000000000000000000000000000000000000..51245b89fb27d15fc780f4b39d2587d7f0603cf2 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo.v @@ -0,0 +1,300 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module ahb_fifo( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwrite, + counter_num0, + cpu_clk, + cpu_rst_b, + fifo_biu_hready, + fifo_pad_haddr, + fifo_pad_hburst, + fifo_pad_hprot, + fifo_pad_hsize, + fifo_pad_htrans, + fifo_pad_hwrite, + pad_biu_hready +); + +// &Ports; @20 +input [31:0] biu_pad_haddr; +input [1 :0] biu_pad_hburst; +input [3 :0] biu_pad_hprot; +input [2 :0] biu_pad_hsize; +input [1 :0] biu_pad_htrans; +input biu_pad_hwrite; +input [31:0] counter_num0; +input cpu_clk; +input cpu_rst_b; +input pad_biu_hready; +output fifo_biu_hready; +output [31:0] fifo_pad_haddr; +output [1 :0] fifo_pad_hburst; +output [3 :0] fifo_pad_hprot; +output [2 :0] fifo_pad_hsize; +output [1 :0] fifo_pad_htrans; +output fifo_pad_hwrite; + +// &Regs; @21 +reg [1 :0] burst_counter; +reg burst_counter_dec; +reg burst_counter_start; +reg cur_state; +reg entry_vld; +reg hready_mask; +reg next_state; +reg [44:0] output_data; + +// &Wires; @22 +wire [31:0] biu_pad_haddr; +wire [1 :0] biu_pad_hburst; +wire biu_pad_hlock; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire biu_pad_hwrite; +wire burst_ctrl; +wire burst_trans; +wire count_done; +wire counter_done; +wire counter_en; +wire [31:0] counter_num0; +wire cpu_clk; +wire cpu_rst_b; +wire create_en; +wire create_en0; +wire fifo_biu_hready; +wire fifo_bypass; +wire [31:0] fifo_pad_haddr; +wire [1 :0] fifo_pad_hburst; +wire fifo_pad_hlock; +wire [3 :0] fifo_pad_hprot; +wire [2 :0] fifo_pad_hsize; +wire [1 :0] fifo_pad_htrans; +wire fifo_pad_hwrite; +wire [54:0] input_data; +wire [54:0] output_data0; +wire pad_biu_hready; +wire pop_en; +wire pop_req; +wire raddr_hit; + + +//set delay area + +parameter IMEM_START = 32'h00000000; +parameter IMEM_END = 32'h0001ffff; +parameter DMEM_START = 32'h20000000; +parameter DMEM_END = 32'h2001ffff; +parameter SMEM_START = 32'h60000000; +parameter SMEM_END = 32'h6001ffff; + +assign raddr_hit = ((biu_pad_haddr[31:0] >= SMEM_START) && (biu_pad_haddr[31:0] <= SMEM_END) + ) && biu_pad_hprot[3]; +// &Force("nonport", "raddr_hit"); @43 +//**************************************************** +// creat_ptr maintenance +//**************************************************** +// when entry is invalid delay entry can be bypassed if any of following conditions is met: +// 1. write trans 2. sequential burst trans 3. addr miss delay area +assign fifo_bypass = (biu_pad_hwrite || burst_trans || !raddr_hit) && !entry_vld || ( counter_num0[31:0] == 32'h0) ; +assign create_en = biu_pad_htrans[1] && !entry_vld && !fifo_bypass; + +//monitor burst trans +assign burst_ctrl = create_en && biu_pad_hburst[1]; +assign burst_trans = (cur_state == 1'b1) ; +//burst fsm +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if (!cpu_rst_b) + cur_state <= 1'b0; + else + cur_state <= next_state; +end + +// &CombBeg; @64 +always @( cur_state + or burst_ctrl + or fifo_biu_hready + or count_done + or biu_pad_htrans[1]) +begin +burst_counter_start = 1'b0 ; +burst_counter_dec = 1'b0 ; + +case(cur_state) +1'b0: + begin + if(burst_ctrl) + begin + next_state = 1'b1; + burst_counter_start = 1'b1; + end + else + next_state = 1'b0; + end +1'b1: + begin + if (count_done && fifo_biu_hready) + begin + next_state = 1'b0; + end + else if(biu_pad_htrans[1] && fifo_biu_hready ) + begin + burst_counter_dec = 1'b1; + next_state = 1'b1; + end + else + next_state = 1'b1; + end +endcase +// &CombEnd; @94 +end + +//burst counter +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if (!cpu_rst_b) + burst_counter[1:0] <= 2'b0; + else if (burst_counter_start) // wrap initial value + burst_counter[1:0] <= 2'b10; + else if (burst_counter_dec) + burst_counter[1:0] <= burst_counter[1:0] - 1'b1; + else + burst_counter[1:0] <= burst_counter[1:0]; +end + +assign count_done = (burst_counter[1:0] == 2'b0); +//**************************************************** +// entry_vld maintenance +//**************************************************** +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if (!cpu_rst_b) + entry_vld <= 1'b0; + else if (create_en) + entry_vld <= 1'b1; + else if (pop_en) + entry_vld <= 1'b0; +end + +//**************************************************** +// entry delay counter maintenance +//**************************************************** + + +assign counter_en = create_en; +// &Instance("ahb_fifo_counter", "x_counter_entry0"); @129 +ahb_fifo_counter x_counter_entry0 ( + .counter_done (counter_done), + .counter_en (counter_en ), + .counter_load (counter_num0), + .cpu_clk (cpu_clk ), + .cpu_rst_b (cpu_rst_b ) +); + +// &Connect (.counter_load (counter_num0 ), @130 +// .counter_en (counter_en ), @131 +// .counter_done (counter_done ) @132 +// ); @133 + +//**************************************************** +// pop logic maintenance +//**************************************************** + +assign pop_req = counter_done && entry_vld; +assign pop_en = pop_req && pad_biu_hready; + + +//**************************************************** +// entry content +//**************************************************** +assign biu_pad_hlock = 1'b0; +assign input_data[44:0] = { biu_pad_hwrite, biu_pad_haddr[31:0], biu_pad_hburst[1:0], biu_pad_hlock, + biu_pad_hprot[3:0], biu_pad_hsize[2:0], biu_pad_htrans[1:0]} ; + + +assign create_en0 = create_en ; + +// &Instance("ahb_fifo_entry", "x_ahb_fifo_entry0"); @156 +ahb_fifo_entry x_ahb_fifo_entry0 ( + .create_en (create_en0 ), + .data_in (input_data ), + .data_out (output_data0), + .entry_clk (cpu_clk ), + .entry_rst_b (cpu_rst_b ) +); + +// &Connect (.entry_clk (cpu_clk ), @157 +// .entry_rst_b (cpu_rst_b ), @158 +// .data_in (input_data ), @159 +// .create_en (create_en0 ), @160 +// .data_out (output_data0 ) @161 +// ); @162 + + +// &CombBeg; @165 +always @( pop_en + or output_data0[44:0]) +begin +case (pop_en) + 1'b0: output_data[44:0] = 45'b0; + 1'b1: output_data[44:0] = output_data0[44:0]; + default:output_data[44:0] = 45'b0; +endcase +// &CombEnd; @171 +end + + + +//**************************************************** +// i/o interface +//**************************************************** +//mask ready signal to acheive trans delay +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if (!cpu_rst_b) + hready_mask <= 1'b1; + else if (create_en) + hready_mask <= 1'b0; + else if (pop_en) + hready_mask <= 1'b1; + else + hready_mask <= hready_mask; +end + + +assign fifo_pad_htrans[1:0] = fifo_bypass ? biu_pad_htrans[1:0] : output_data[1:0]; +assign fifo_pad_hsize[2:0] = fifo_bypass ? biu_pad_hsize[2:0] : output_data[4:2]; +assign fifo_pad_hprot[3:0] = fifo_bypass ? biu_pad_hprot[3:0] : output_data[8:5]; +assign fifo_pad_hlock = fifo_bypass ? biu_pad_hlock : output_data[9]; +assign fifo_pad_hburst[1:0] = fifo_bypass ? biu_pad_hburst[1:0] : output_data[11:10]; +assign fifo_pad_haddr[31:0] = fifo_bypass ? biu_pad_haddr[31:0] : output_data[43:12]; +assign fifo_pad_hwrite = fifo_bypass ? biu_pad_hwrite : output_data[44]; + + +// &Force("nonport", "fifo_pad_hlock"); @204 + +assign fifo_biu_hready = pad_biu_hready && hready_mask; +// &Force("output", "fifo_biu_hready"); @208 + +// &ModuleEnd; @210 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_counter.v b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_counter.v new file mode 100644 index 0000000000000000000000000000000000000000..868f8cbb52f3985f2cc740a1129b7cc20d252063 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_counter.v @@ -0,0 +1,79 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module ahb_fifo_counter( + counter_done, + counter_en, + counter_load, + cpu_clk, + cpu_rst_b +); + +// &Ports; @20 +input counter_en; +input [31:0] counter_load; +input cpu_clk; +input cpu_rst_b; +output counter_done; + +// &Regs; @21 +reg [31:0] counter; +reg counter_en_ff; + +// &Wires; @22 +wire counter_done; +wire counter_en; +wire [31:0] counter_load; +wire cpu_clk; +wire cpu_rst_b; +wire load_cnt_en; + + +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if(!cpu_rst_b) + begin + counter_en_ff <= 1'b0; + end + else + begin + counter_en_ff <=counter_en ; + end +end + +assign load_cnt_en= (counter_en && !counter_en_ff); + /// || !(|counter[31:0]); + +always @(posedge cpu_clk or negedge cpu_rst_b) +begin + if(!cpu_rst_b) + begin + counter[31:0] <= 32'h0; + end + else if (load_cnt_en) + begin + counter[31:0] <= counter_load[31:0]; + end + else if (counter_done) + counter[31:0] <= 32'b0; + else + counter[31:0] <= counter[31:0] -1'b1; + end + +assign counter_done = (counter[31:0] == 32'b0) ; +// &Force("output","counter_done"); @56 +// &ModuleEnd; @57 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_entry.v b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_entry.v new file mode 100644 index 0000000000000000000000000000000000000000..11eff52dea9c5e19ffd41a16bc44cffbecacea01 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/ahb/ahb_fifo_entry.v @@ -0,0 +1,58 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module ahb_fifo_entry( + create_en, + data_in, + data_out, + entry_clk, + entry_rst_b +); + +// &Ports; @20 +input create_en; +input [54:0] data_in; +input entry_clk; +input entry_rst_b; +output [54:0] data_out; + +// &Regs; @21 +reg [54:0] data_out; + +// &Wires; @22 +wire create_en; +wire [54:0] data_in; +wire entry_clk; +wire entry_rst_b; + + +always @(posedge entry_clk or negedge entry_rst_b) +begin + if (!entry_rst_b) + data_out[54:0] <= 54'b0; + else if (create_en) + data_out[54:0] <= data_in[54:0]; + else + data_out[54:0] <= data_out[54:0]; +end + +// &Force("output","data_out"); @34 + + + + +// &ModuleEnd; @39 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/apb/apb.v b/XUANTIE-RV_opene906/smart_run/logical/apb/apb.v new file mode 100644 index 0000000000000000000000000000000000000000..18b59fe0c119412b70110f6366decb5488bded3a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/apb/apb.v @@ -0,0 +1,543 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module apb( + b_pad_gpio_porta, + biu_pad_lpmd_b, + clk_en, + corec_pmu_sleep_out, + cpu_clk, + fifo_pad_haddr, + fifo_pad_hprot, + haddr_s2, + hrdata_s2, + hready_s2, + hresp_s2, + hsel_s2, + hwdata_s2, + hwrite_s2, + i_pad_cpu_jtg_rst_b, + i_pad_jtg_tclk, + nmi_wake_int_lower, + pad_clk, + pad_cpu_rst_b, + pad_had_jtg_tap_en, + pad_had_jtg_tms_i, + pad_had_jtg_trst_b, + pad_had_jtg_trst_b_pre, + pad_vic_int_vld, + per_clk, + pg_reset_b, + pmu_corec_isolation, + pmu_corec_sleep_in, + smpu_deny, + sys_rst, + uart0_sin, + uart0_sout +); + +// &Ports; @21 +input [1 :0] biu_pad_lpmd_b; +input corec_pmu_sleep_out; +input [31:0] fifo_pad_haddr; +input [3 :0] fifo_pad_hprot; +input [31:0] haddr_s2; +input hsel_s2; +input [31:0] hwdata_s2; +input hwrite_s2; +input i_pad_cpu_jtg_rst_b; +input i_pad_jtg_tclk; +input pad_clk; +input pad_cpu_rst_b; +input pad_had_jtg_tap_en; +input pad_had_jtg_tms_i; +input pad_had_jtg_trst_b_pre; +input sys_rst; +input uart0_sin; +output clk_en; +output cpu_clk; +output [31:0] hrdata_s2; +output hready_s2; +output [1 :0] hresp_s2; +output [1 :0] nmi_wake_int_lower; +output pad_had_jtg_trst_b; +output [31:0] pad_vic_int_vld; +output per_clk; +output pg_reset_b; +output pmu_corec_isolation; +output pmu_corec_sleep_in; +output smpu_deny; +output uart0_sout; +inout [7 :0] b_pad_gpio_porta; + +// &Regs; @22 + +// &Wires; @23 +wire apb_clkgen_psel; +wire apb_gpio_psel; +wire apb_nmi_wake_psel; +wire apb_pmu_psel; +wire apb_smpu_psel; +wire apb_stim_psel; +wire apb_tim1_psel; +wire apb_tim_psel; +wire apb_uart_psel; +wire [31:0] apb_xx_paddr; +wire apb_xx_penable; +wire [31:0] apb_xx_pwdata; +wire apb_xx_pwrite; +wire [7 :0] b_pad_gpio_porta; +wire [1 :0] biu_pad_lpmd_b; +wire clk_en; +wire [31:0] clkgen_apb_prdata; +wire corec_pmu_sleep_out; +wire cpu_clk; +wire [31:0] fifo_pad_haddr; +wire [3 :0] fifo_pad_hprot; +wire gate_en0; +wire gate_en1; +wire [31:0] gpio_apb_prdata; +wire [7 :0] gpio_vic_int; +wire [31:0] haddr_s2; +wire [31:0] hrdata_s2; +wire hready_s2; +wire [1 :0] hresp_s2; +wire hsel_s2; +wire [31:0] hwdata_s2; +wire hwrite_s2; +wire i_pad_cpu_jtg_rst_b; +wire i_pad_jtg_tclk; +wire intraw_vld; +wire [31:0] nmi_wake_apb_prdata; +wire [3 :0] nmi_wake_int; +wire [1 :0] nmi_wake_int_higher; +wire [1 :0] nmi_wake_int_lower; +wire pad_clk; +wire pad_cpu_rst_b; +wire pad_had_jtg_tap_en; +wire pad_had_jtg_tms_i; +wire pad_had_jtg_trst_b; +wire pad_had_jtg_trst_b_pre; +wire [31:0] pad_vic_int_vld; +wire per_clk; +wire pg_reset_b; +wire [31:0] pmu_apb_prdata; +wire pmu_clk; +wire pmu_corec_isolation; +wire pmu_corec_sleep_in; +wire [31:0] smpu_apb_prdata; +wire smpu_deny; +wire [31:0] stim_apb_prdata; +wire [3 :0] stim_vic_int; +wire sys_rst; +wire [31:0] tim1_apb_prdata; +wire [3 :0] tim1_vic_int; +wire [31:0] tim_apb_prdata; +wire [3 :0] tim_vic_int; +wire uart0_sin; +wire uart0_sout; +wire uart0_vic_int; +wire [31:0] uart_apb_prdata; +wire wic_clk; + + + +// &Instance("apb_bridge", "x_apb_bridge"); @26 +apb_bridge x_apb_bridge ( + .apb_harb_hrdata (hrdata_s2 ), + .apb_harb_hready (hready_s2 ), + .apb_harb_hresp (hresp_s2 ), + .apb_xx_paddr (apb_xx_paddr ), + .apb_xx_penable (apb_xx_penable ), + .apb_xx_pwdata (apb_xx_pwdata ), + .apb_xx_pwrite (apb_xx_pwrite ), + .harb_apb_hsel (hsel_s2 ), + .harb_xx_haddr (haddr_s2 ), + .harb_xx_hwdata (hwdata_s2 ), + .harb_xx_hwrite (hwrite_s2 ), + .hclk (per_clk ), + .hrst_b (pg_reset_b ), + .prdata_s1 (uart_apb_prdata ), + .prdata_s2 (tim_apb_prdata ), + .prdata_s3 (pmu_apb_prdata ), + .prdata_s4 (gpio_apb_prdata ), + .prdata_s5 (stim_apb_prdata ), + .prdata_s6 (clkgen_apb_prdata ), + .prdata_s7 (smpu_apb_prdata ), + .prdata_s8 (nmi_wake_apb_prdata), + .prdata_s9 (tim1_apb_prdata ), + .psel_s1 (apb_uart_psel ), + .psel_s2 (apb_tim_psel ), + .psel_s3 (apb_pmu_psel ), + .psel_s4 (apb_gpio_psel ), + .psel_s5 (apb_stim_psel ), + .psel_s6 (apb_clkgen_psel ), + .psel_s7 (apb_smpu_psel ), + .psel_s8 (apb_nmi_wake_psel ), + .psel_s9 (apb_tim1_psel ) +); + +// &Connect( @27 +// .hclk (per_clk), @28 +// .hrst_b (pg_reset_b), @29 +// .harb_apb_hsel (hsel_s2), @30 +// .harb_xx_haddr (haddr_s2), @31 +// .harb_xx_hwdata (hwdata_s2), @32 +// .harb_xx_hwrite (hwrite_s2), @33 +// .apb_harb_hrdata (hrdata_s2), @34 +// .apb_harb_hready (hready_s2), @35 +// .apb_harb_hresp (hresp_s2), @36 +// .apb_xx_paddr (apb_xx_paddr), @37 +// .apb_xx_penable (apb_xx_penable), @38 +// .apb_xx_pwdata (apb_xx_pwdata), @39 +// .apb_xx_pwrite (apb_xx_pwrite), @40 +// .prdata_s1 (uart_apb_prdata), @41 +// .prdata_s2 (tim_apb_prdata), @42 +// .prdata_s3 (pmu_apb_prdata), @43 +// .prdata_s4 (gpio_apb_prdata), @44 +// .prdata_s5 (stim_apb_prdata), @45 +// .prdata_s6 (clkgen_apb_prdata), @46 +// .prdata_s7 (smpu_apb_prdata), @47 +// .prdata_s8 (nmi_wake_apb_prdata), @48 +// .prdata_s9 (tim1_apb_prdata), @49 +// .psel_s1 (apb_uart_psel), @50 +// .psel_s2 (apb_tim_psel), @51 +// .psel_s3 (apb_pmu_psel), @52 +// .psel_s4 (apb_gpio_psel), @53 +// .psel_s5 (apb_stim_psel), @54 +// .psel_s6 (apb_clkgen_psel), @55 +// .psel_s7 (apb_smpu_psel), @56 +// .psel_s8 (apb_nmi_wake_psel), @57 +// .psel_s9 (apb_tim1_psel) @58 +// ); @59 + +// &Instance("pmu", "x_pmu"); @61 +pmu x_pmu ( + .apb_pmu_paddr (apb_xx_paddr[11:0] ), + .apb_pmu_penable (apb_xx_penable ), + .apb_pmu_psel (apb_pmu_psel ), + .apb_pmu_pwdata (apb_xx_pwdata ), + .apb_pmu_pwrite (apb_xx_pwrite ), + .biu_pad_lpmd_b (biu_pad_lpmd_b ), + .corec_pmu_sleep_out (corec_pmu_sleep_out ), + .cpu_clk (cpu_clk ), + .gate_en0 (gate_en0 ), + .gate_en1 (gate_en1 ), + .had_pad_wakeup_req_b (1'b1 ), + .i_pad_cpu_jtg_rst_b (i_pad_cpu_jtg_rst_b ), + .i_pad_jtg_tclk (i_pad_jtg_tclk ), + .intraw_vld (intraw_vld ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_had_jtg_tap_en (pad_had_jtg_tap_en ), + .pad_had_jtg_tms_i (pad_had_jtg_tms_i ), + .pad_had_jtg_trst_b (pad_had_jtg_trst_b ), + .pad_had_jtg_trst_b_pre (pad_had_jtg_trst_b_pre), + .pg_reset_b (pg_reset_b ), + .pmu_apb_prdata (pmu_apb_prdata ), + .pmu_clk (pmu_clk ), + .pmu_corec_isolation (pmu_corec_isolation ), + .pmu_corec_sleep_in (pmu_corec_sleep_in ), + .sys_rst (sys_rst ) +); + +// &Connect( @62 +// .apb_pmu_psel (apb_pmu_psel), @63 +// .apb_pmu_paddr (apb_xx_paddr[11:0]), @64 +// .apb_pmu_penable (apb_xx_penable), @65 +// .apb_pmu_pwdata (apb_xx_pwdata), @66 +// .apb_pmu_pwrite (apb_xx_pwrite), @67 +// .pad_cpu_rst_b (pad_cpu_rst_b), @68 +// .pmu_apb_prdata (pmu_apb_prdata), @69 +// .intraw_b (wic_vic_intraw_b), @70 +// .had_pad_wakeup_req_b (1'b1 ) @71 +// // .ctl_xx_awake_enable (32'hffffffff), @72 +// // .pulse_int (1'b0) @73 +// // .pad_vic_event_vld (1'b0) @74 +// ); @75 + + +// &Instance("uart", "x_uart"); @78 +uart x_uart ( + .apb_uart_paddr (apb_xx_paddr ), + .apb_uart_penable (apb_xx_penable ), + .apb_uart_psel (apb_uart_psel ), + .apb_uart_pwdata (apb_xx_pwdata ), + .apb_uart_pwrite (apb_xx_pwrite ), + .rst_b (pad_cpu_rst_b ), + .s_in (uart0_sin ), + .s_out (uart0_sout ), + .sys_clk (pmu_clk ), + .uart_apb_prdata (uart_apb_prdata ), + .uart_vic_int (uart0_vic_int ) +); + +// &Connect( @79 +// .sys_clk (pmu_clk), @80 +// .apb_uart_psel (apb_uart_psel), @81 +// .apb_uart_paddr (apb_xx_paddr), @82 +// .apb_uart_penable (apb_xx_penable), @83 +// .apb_uart_pwdata (apb_xx_pwdata), @84 +// .apb_uart_pwrite (apb_xx_pwrite), @85 +// .rst_b (pad_cpu_rst_b), @86 +// .uart_apb_prdata (uart_apb_prdata), @87 +// .uart_vic_int (uart0_vic_int), @88 +// .s_in (uart0_sin), @89 +// .s_out (uart0_sout) @90 +// ); @91 + +// &Instance("timer", "x_timer"); @93 +timer x_timer ( + .paddr (apb_xx_paddr[15:0]), + .pclk (pmu_clk ), + .penable (apb_xx_penable ), + .prdata (tim_apb_prdata ), + .presetn (pad_cpu_rst_b ), + .psel (apb_tim_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ), + .timer_int (tim_vic_int ) +); + +// &Connect( @94 +// .presetn (pad_cpu_rst_b), @95 +// .prdata (tim_apb_prdata), @96 +// .timer_int (tim_vic_int), @97 +// .pclk (pmu_clk), @98 +// .penable (apb_xx_penable), @99 +// .paddr (apb_xx_paddr[15:0]), @100 +// .psel (apb_tim_psel), @101 +// .pwdata (apb_xx_pwdata), @102 +// .pwrite (apb_xx_pwrite) @103 +// ); @104 + +// &Instance("timer", "x_nmi_wake"); @106 +timer x_nmi_wake ( + .paddr (apb_xx_paddr[15:0] ), + .pclk (pmu_clk ), + .penable (apb_xx_penable ), + .prdata (nmi_wake_apb_prdata), + .presetn (pad_cpu_rst_b ), + .psel (apb_nmi_wake_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ), + .timer_int (nmi_wake_int ) +); + +// &Connect( @107 +// .presetn (pad_cpu_rst_b), @108 +// .prdata (nmi_wake_apb_prdata), @109 +// .timer_int (nmi_wake_int), @110 +// .pclk (pmu_clk), @111 +// .penable (apb_xx_penable), @112 +// .paddr (apb_xx_paddr[15:0]), @113 +// .psel (apb_nmi_wake_psel), @114 +// .pwdata (apb_xx_pwdata), @115 +// .pwrite (apb_xx_pwrite) @116 +// ); @117 +assign nmi_wake_int_lower[1:0]= nmi_wake_int[1:0]; +assign nmi_wake_int_higher[1:0] = nmi_wake_int[3:2]; + +// &Instance("timer", "x_stimer"); @121 +timer x_stimer ( + .paddr (apb_xx_paddr[15:0]), + .pclk (pmu_clk ), + .penable (apb_xx_penable ), + .prdata (stim_apb_prdata ), + .presetn (pad_cpu_rst_b ), + .psel (apb_stim_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ), + .timer_int (stim_vic_int ) +); + +// &Connect( @122 +// .presetn (pad_cpu_rst_b), @123 +// .prdata (stim_apb_prdata), @124 +// .timer_int (stim_vic_int), @125 +// .pclk (pmu_clk), @126 +// .penable (apb_xx_penable), @127 +// .paddr (apb_xx_paddr[15:0]), @128 +// .psel (apb_stim_psel), @129 +// .pwdata (apb_xx_pwdata), @130 +// .pwrite (apb_xx_pwrite) @131 +// ); @132 + +// &Instance("timer", "x_timer1"); @134 +timer x_timer1 ( + .paddr (apb_xx_paddr[15:0]), + .pclk (pmu_clk ), + .penable (apb_xx_penable ), + .prdata (tim1_apb_prdata ), + .presetn (pad_cpu_rst_b ), + .psel (apb_tim1_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ), + .timer_int (tim1_vic_int ) +); + +// &Connect( @135 +// .presetn (pad_cpu_rst_b), @136 +// .prdata (tim1_apb_prdata), @137 +// .timer_int (tim1_vic_int), @138 +// .pclk (pmu_clk), @139 +// .penable (apb_xx_penable), @140 +// .paddr (apb_xx_paddr[15:0]), @141 +// .psel (apb_tim1_psel), @142 +// .pwdata (apb_xx_pwdata), @143 +// .pwrite (apb_xx_pwrite) @144 +// ); @145 + + +// &Instance("fpga_clk_gen", "x_fpga_clk_gen"); @149 +fpga_clk_gen x_fpga_clk_gen ( + .clk_en (clk_en ), + .clkrst_b (pad_cpu_rst_b ), + .cpu_clk (cpu_clk ), + .gate_en0 (gate_en0 ), + .gate_en1 (gate_en1 ), + .pad_clk (pad_clk ), + .penable (apb_xx_penable ), + .per_clk (per_clk ), + .pmu_clk (pmu_clk ), + .prdata (clkgen_apb_prdata ), + .psel (apb_clkgen_psel ), + .pwdata (apb_xx_pwdata[2:0]), + .pwrite (apb_xx_pwrite ), + .wic_clk (wic_clk ) +); + +// &Connect( @150 +// .penable (apb_xx_penable ), @151 +// .psel (apb_clkgen_psel ), @152 +// .prdata (clkgen_apb_prdata ), @153 +// .pwdata (apb_xx_pwdata[2:0]), @154 +// .pwrite (apb_xx_pwrite ), @155 +// .clkrst_b (pad_cpu_rst_b ) @156 +// ); @157 +// &Instance("clk_aligner", "x_clk_aligner"); @159 +// &Connect( @160 +// .forever_cpuclk (pad_clk ), @161 +// .penable (apb_xx_penable ), @162 +// .paddr (apb_xx_paddr[11:0]), @163 +// .psel (apb_clkgen_psel ), @164 +// .prdata (clkgen_apb_prdata ), @165 +// .pwdata (apb_xx_pwdata[2:0]), @166 +// .pwrite (apb_xx_pwrite ), @167 +// .clkrst_b (pad_cpu_rst_b ) @168 +// ); @169 +// &Instance("clk_divider", "x_clk_divider"); @171 +// &Connect( @172 +// .osc_clk (pad_clk) @173 +// ); @174 + + + +// &Instance("gpio", "x_gpio"); @179 +gpio x_gpio ( + .b_pad_gpio_porta (b_pad_gpio_porta ), + .gpio_intr (gpio_vic_int ), + .paddr (apb_xx_paddr[6:2]), + .pclk (pmu_clk ), + .pclk_intr (pmu_clk ), + .penable (apb_xx_penable ), + .prdata (gpio_apb_prdata ), + .presetn (pad_cpu_rst_b ), + .psel (apb_gpio_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ) +); + +// &Connect( @180 +// .paddr (apb_xx_paddr[6:2]), @181 +// .pclk (pmu_clk), @182 +// .pclk_intr (pmu_clk), @183 +// .penable (apb_xx_penable), @184 +// .presetn (pad_cpu_rst_b), @185 +// .psel (apb_gpio_psel), @186 +// .pwdata (apb_xx_pwdata), @187 +// .pwrite (apb_xx_pwrite), @188 +// .gpio_intr (gpio_vic_int), @189 +// .prdata (gpio_apb_prdata) @190 +// ); @191 + +// &Instance("smpu_top", "x_smpu_top"); @193 +smpu_top x_smpu_top ( + .biu_pad_haddr (fifo_pad_haddr ), + .biu_pad_hprot (fifo_pad_hprot ), + .paddr (apb_xx_paddr[3:2]), + .pclk (per_clk ), + .penable (apb_xx_penable ), + .prdata (smpu_apb_prdata ), + .presetn (pg_reset_b ), + .psel (apb_smpu_psel ), + .pwdata (apb_xx_pwdata ), + .pwrite (apb_xx_pwrite ), + .smpu_deny (smpu_deny ) +); + +// &Connect( @194 +// .paddr (apb_xx_paddr[3:2]), @195 +// .pclk (per_clk), @196 +// .penable (apb_xx_penable), @197 +// .presetn (pg_reset_b), @198 +// .psel (apb_smpu_psel), @199 +// .pwdata (apb_xx_pwdata), @200 +// .pwrite (apb_xx_pwrite), @201 +// .prdata (smpu_apb_prdata), @202 +// .biu_pad_haddr (fifo_pad_haddr ), @203 +// .biu_pad_hprot (fifo_pad_hprot ) @204 +// ); @205 + +// &Instance("wic_top", "x_wic_top"); @207 +wic_top x_wic_top ( + .ctl_xx_awake_enable (32'hffffffff ), + .gpio_vic_int (gpio_vic_int ), + .intraw_vld (intraw_vld ), + .nmi_wake_int_higher (nmi_wake_int_higher), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_vic_int_vld (pad_vic_int_vld ), + .pulse_int (1'b0 ), + .stim_vic_int (stim_vic_int ), + .tim1_vic_int (tim1_vic_int ), + .tim_vic_int (tim_vic_int ), + .uart0_vic_int (uart0_vic_int ), + .wic_clk (wic_clk ) +); + +// &Connect( @208 +// .pulse_int (1'b0 ), @209 +// .ctl_xx_awake_enable (32'hffffffff ) @210 +// @211 +// ); @212 +// &Force("nonport","pulse_int"); @214 +// &Force("nonport","stim_vic_int"); @215 +// &Force("nonport","gpio_vic_int"); @216 + +// &Force("nonport", "pulse_int"); @220 +// &Force("nonport", "stim_vic_int"); @221 + +//assign pll_core_cpuclk = per_clk; +// &Force("output","per_clk"); @225 +// &Force("output","cpu_clk"); @226 +// &Force("output","pg_reset_b"); @227 + +// //&Force("output","cpu_clk"); @229 +// //&Force("output",""); @230 + +// &ModuleEnd; @232 +endmodule + + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/apb/apb_bridge.v b/XUANTIE-RV_opene906/smart_run/logical/apb/apb_bridge.v new file mode 100644 index 0000000000000000000000000000000000000000..6e4ed075b339c0f90a9dd538fa5293c5e8f323ed --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/apb/apb_bridge.v @@ -0,0 +1,475 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +`define PS1_BASE_START 32'h40015000 +`define PS1_BASE_END 32'h40015fff +// Timer +`define PS2_BASE_START 32'h40011000 +`define PS2_BASE_END 32'h40011fff +// PMU +`define PS3_BASE_START 32'h40016000 +`define PS3_BASE_END 32'h40016fff +//GPIO +`define PS4_BASE_START 32'h40019000 +`define PS4_BASE_END 32'h40019fff +//STimer +`define PS5_BASE_START 32'h40018000 +`define PS5_BASE_END 32'h40018fff +//CLKGEN +`define PS6_BASE_START 32'h40017000 +`define PS6_BASE_END 32'h40017fff +//SMPU +`define PS7_BASE_START 32'h4001A000 +`define PS7_BASE_END 32'h4001Afff +//NMI_WAKE +`define PS8_BASE_START 32'h40021000 +`define PS8_BASE_END 32'h40021fff +//NEW TIMER +`define PS9_BASE_START 32'h40031000 +`define PS9_BASE_END 32'h40031fff + +// &ModuleBeg; @48 +module apb_bridge( + apb_harb_hrdata, + apb_harb_hready, + apb_harb_hresp, + apb_xx_paddr, + apb_xx_penable, + apb_xx_pwdata, + apb_xx_pwrite, + harb_apb_hsel, + harb_xx_haddr, + harb_xx_hwdata, + harb_xx_hwrite, + hclk, + hrst_b, + prdata_s1, + prdata_s2, + prdata_s3, + prdata_s4, + prdata_s5, + prdata_s6, + prdata_s7, + prdata_s8, + prdata_s9, + psel_s1, + psel_s2, + psel_s3, + psel_s4, + psel_s5, + psel_s6, + psel_s7, + psel_s8, + psel_s9 +); + +// &Ports; @49 +input harb_apb_hsel; +input [31:0] harb_xx_haddr; +input [31:0] harb_xx_hwdata; +input harb_xx_hwrite; +input hclk; +input hrst_b; +input [31:0] prdata_s1; +input [31:0] prdata_s2; +input [31:0] prdata_s3; +input [31:0] prdata_s4; +input [31:0] prdata_s5; +input [31:0] prdata_s6; +input [31:0] prdata_s7; +input [31:0] prdata_s8; +input [31:0] prdata_s9; +output [31:0] apb_harb_hrdata; +output apb_harb_hready; +output [1 :0] apb_harb_hresp; +output [31:0] apb_xx_paddr; +output apb_xx_penable; +output [31:0] apb_xx_pwdata; +output apb_xx_pwrite; +output psel_s1; +output psel_s2; +output psel_s3; +output psel_s4; +output psel_s5; +output psel_s6; +output psel_s7; +output psel_s8; +output psel_s9; + +// &Regs; @50 +reg [31:0] apb_harb_hrdata; +reg apb_harb_hready; +reg [31:0] apb_xx_paddr; +reg apb_xx_penable; +reg apb_xx_psel; +reg [31:0] apb_xx_pwdata; +reg apb_xx_pwrite; +reg [2 :0] cur_state; +reg [31:0] haddr_latch; +reg hwrite_latch; +reg [2 :0] nxt_state; + +// &Wires; @51 +wire [1 :0] apb_harb_hresp; +wire busy_s1; +wire busy_s2; +wire busy_s3; +wire busy_s4; +wire busy_s5; +wire busy_s6; +wire busy_s7; +wire busy_s8; +wire busy_s9; +wire enable_latch; +wire enable_r_select; +wire harb_apb_hsel; +wire [31:0] harb_xx_haddr; +wire [31:0] harb_xx_hwdata; +wire harb_xx_hwrite; +wire hclk; +wire hrst_b; +wire idle_latch; +wire idle_r_select; +wire [31:0] prdata_s1; +wire [31:0] prdata_s2; +wire [31:0] prdata_s3; +wire [31:0] prdata_s4; +wire [31:0] prdata_s5; +wire [31:0] prdata_s6; +wire [31:0] prdata_s7; +wire [31:0] prdata_s8; +wire [31:0] prdata_s9; +wire psel_s1; +wire psel_s2; +wire psel_s3; +wire psel_s4; +wire psel_s5; +wire psel_s6; +wire psel_s7; +wire psel_s8; +wire psel_s9; + + +// &Force("output","apb_xx_paddr") @53 +// &Force("output","apb_xx_penable") @54 +// &Force("output","apb_xx_pwdata") @55 +// &Force("output","apb_xx_pwrite") @56 +// &Force("output","psel_s1") @57 +// &Force("output","psel_s2") @58 +// &Force("output","psel_s3") @59 +// &Force("output","psel_s4") @60 +// &Force("output","psel_s5") @61 +// &Force("output","psel_s6") @62 +// &Force("output","psel_s7") @63 +// &Force("output","psel_s8") @64 +// &Force("output","psel_s9") @65 + +assign apb_harb_hresp[1:0] = 2'b0; //always OK + +parameter IDLE = 3'b000; +parameter LATCH = 3'b001; +parameter W_SELECT = 3'b010; +parameter R_SELECT = 3'b011; +parameter ENABLE = 3'b100; + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + cur_state[2:0] <= IDLE; + end + else + begin + cur_state[2:0] <= nxt_state[2:0]; + end +end + +assign idle_latch = harb_apb_hsel && harb_xx_hwrite; +assign idle_r_select = harb_apb_hsel && !harb_xx_hwrite; +assign enable_latch = harb_apb_hsel && harb_xx_hwrite; +assign enable_r_select = harb_apb_hsel && !harb_xx_hwrite; + +//always @(cur_state[2:0] or harb_apb_hsel or harb_xx_hwrite) +//begin +// &CombBeg; @94 +always @( enable_r_select + or idle_latch + or idle_r_select + or enable_latch + or cur_state[2:0]) +begin +nxt_state[2:0] = IDLE; +case(cur_state[2:0]) + IDLE: + begin + if(idle_latch) + begin + nxt_state[2:0] = LATCH; + end + else if(idle_r_select) + begin + nxt_state[2:0] = R_SELECT; + end + else + begin + nxt_state[2:0] = IDLE; + end + end + LATCH: + begin + nxt_state[2:0] = W_SELECT; + end + W_SELECT: + begin + nxt_state[2:0] = ENABLE; + end + R_SELECT: + begin + nxt_state[2:0] = ENABLE; + end + ENABLE: + begin + if(enable_latch) + begin + nxt_state[2:0] = LATCH; + end + else if(enable_r_select) + begin + nxt_state[2:0] = R_SELECT; + end + else + begin + nxt_state[2:0] = IDLE; + end + end +endcase +// &CombEnd; @140 +end +//end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + haddr_latch[31:0] <= 32'b0; + hwrite_latch <= 1'b0; + end + else if(nxt_state[2:0]==LATCH) + begin + haddr_latch[31:0] <= harb_xx_haddr[31:0]; + hwrite_latch <= harb_xx_hwrite; + end + else + begin + haddr_latch[31:0] <= haddr_latch[31:0]; + hwrite_latch <= hwrite_latch; + end +end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + apb_xx_paddr[31:0] <= 32'b0; + apb_xx_pwrite <= 1'b0; + end + else if(nxt_state[2:0]==W_SELECT) + begin + apb_xx_paddr[31:0] <= haddr_latch[31:0]; + apb_xx_pwrite <= hwrite_latch; + end + else if(nxt_state[2:0]==R_SELECT) + begin + apb_xx_paddr[31:0] <= harb_xx_haddr[31:0]; + apb_xx_pwrite <= harb_xx_hwrite; + end + else + begin + apb_xx_paddr[31:0] <= apb_xx_paddr[31:0]; + apb_xx_pwrite <= apb_xx_pwrite; + end +end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + apb_xx_pwdata[31:0] <= 32'b0; + end + else if(nxt_state[2:0]==W_SELECT) + begin + apb_xx_pwdata[31:0] <= harb_xx_hwdata[31:0]; + end + else + begin + apb_xx_pwdata[31:0] <= apb_xx_pwdata[31:0]; + end +end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + apb_xx_psel <= 1'b0; + end + else if(nxt_state[2:0]==W_SELECT) + begin + apb_xx_psel <= 1'b1; + end + else if(nxt_state[2:0]==R_SELECT) + begin + apb_xx_psel <= 1'b1; + end + else if(nxt_state[2:0]==ENABLE) + begin + apb_xx_psel <= 1'b1; + end + else + begin + apb_xx_psel <= 1'b0; + end +end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + apb_xx_penable <= 1'b0; + end + else if(nxt_state[2:0]==ENABLE) + begin + apb_xx_penable <= 1'b1; + end + else + begin + apb_xx_penable <= 1'b0; + end +end + +always @(posedge hclk or negedge hrst_b) +begin + if(!hrst_b) + begin + apb_harb_hready <= 1'b1; + end + else if(nxt_state[2:0]==LATCH) + begin + apb_harb_hready <= 1'b0; + end + else if(nxt_state[2:0]==W_SELECT) + begin + apb_harb_hready <= 1'b0; + end + else if(nxt_state[2:0]==R_SELECT) + begin + apb_harb_hready <= 1'b0; + end + else + begin + apb_harb_hready <= 1'b1; + end +end + +assign psel_s1 = apb_xx_psel && (apb_xx_paddr>=`PS1_BASE_START) && (apb_xx_paddr<=`PS1_BASE_END); +assign psel_s2 = apb_xx_psel && (apb_xx_paddr>=`PS2_BASE_START) && (apb_xx_paddr<=`PS2_BASE_END); +assign psel_s3 = apb_xx_psel && (apb_xx_paddr>=`PS3_BASE_START) && (apb_xx_paddr<=`PS3_BASE_END); +assign psel_s4 = apb_xx_psel && (apb_xx_paddr>=`PS4_BASE_START) && (apb_xx_paddr<=`PS4_BASE_END); +assign psel_s5 = apb_xx_psel && (apb_xx_paddr>=`PS5_BASE_START) && (apb_xx_paddr<=`PS5_BASE_END); +assign psel_s6 = apb_xx_psel && (apb_xx_paddr>=`PS6_BASE_START) && (apb_xx_paddr<=`PS6_BASE_END); +assign psel_s7 = apb_xx_psel && (apb_xx_paddr>=`PS7_BASE_START) && (apb_xx_paddr<=`PS7_BASE_END); +assign psel_s8 = apb_xx_psel && (apb_xx_paddr>=`PS8_BASE_START) && (apb_xx_paddr<=`PS8_BASE_END); +assign psel_s9 = apb_xx_psel && (apb_xx_paddr>=`PS9_BASE_START) && (apb_xx_paddr<=`PS9_BASE_END); + + +assign busy_s1 = apb_xx_penable && psel_s1; +assign busy_s2 = apb_xx_penable && psel_s2; +assign busy_s3 = apb_xx_penable && psel_s3; +assign busy_s4 = apb_xx_penable && psel_s4; +assign busy_s5 = apb_xx_penable && psel_s5; +assign busy_s6 = apb_xx_penable && psel_s6; +assign busy_s7 = apb_xx_penable && psel_s7; +assign busy_s8 = apb_xx_penable && psel_s8; +assign busy_s9 = apb_xx_penable && psel_s9; + +// &CombBeg; @287 +always @( busy_s9 + or busy_s3 + or busy_s4 + or prdata_s3[31:0] + or prdata_s8[31:0] + or busy_s7 + or busy_s2 + or prdata_s5[31:0] + or busy_s6 + or prdata_s6[31:0] + or busy_s5 + or busy_s1 + or prdata_s1[31:0] + or busy_s8 + or prdata_s4[31:0] + or prdata_s9[31:0] + or prdata_s2[31:0] + or prdata_s7[31:0]) +begin +case({busy_s1,busy_s2,busy_s3,busy_s4,busy_s5,busy_s6,busy_s7,busy_s8,busy_s9}) + 9'b100000000: + begin + apb_harb_hrdata[31:0] = prdata_s1[31:0]; + end + 9'b010000000: + begin + apb_harb_hrdata[31:0] = prdata_s2[31:0]; + end + 9'b001000000: + begin + apb_harb_hrdata[31:0] = prdata_s3[31:0]; + end + 9'b000100000: + begin + apb_harb_hrdata[31:0] = prdata_s4[31:0]; + end + 9'b000010000: + begin + apb_harb_hrdata[31:0] = prdata_s5[31:0]; + end + 9'b000001000: + begin + apb_harb_hrdata[31:0] = prdata_s6[31:0]; + end + 9'b000000100: + begin + apb_harb_hrdata[31:0] = prdata_s7[31:0]; + end + 9'b000000010: + begin + apb_harb_hrdata[31:0] = prdata_s8[31:0]; + end + 9'b000000001: + begin + apb_harb_hrdata[31:0] = prdata_s9[31:0]; + end + + default: + begin + apb_harb_hrdata[31:0] = 32'b0; + end +endcase +// &CombEnd; @331 +end + +// &ModuleEnd; @333 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio.v b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio.v new file mode 100644 index 0000000000000000000000000000000000000000..b21f82994935cf575156bad193cc28b0f20f92f0 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio.v @@ -0,0 +1,174 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module gpio( + b_pad_gpio_porta, + gpio_intr, + paddr, + pclk, + pclk_intr, + penable, + prdata, + presetn, + psel, + pwdata, + pwrite +); + +// &Ports; @23 +input [6 :2] paddr; +input pclk; +input pclk_intr; +input penable; +input presetn; +input psel; +input [31:0] pwdata; +input pwrite; +output [7 :0] gpio_intr; +output [31:0] prdata; +inout [7 :0] b_pad_gpio_porta; + +// &Regs; @24 + +// &Wires; @25 +wire [7 :0] b_pad_gpio_porta; +wire [7 :0] gpio_ext_porta; +wire [7 :0] gpio_ext_porta_rb; +wire [7 :0] gpio_int_polarity; +wire [7 :0] gpio_inten; +wire [7 :0] gpio_intmask; +wire [7 :0] gpio_intr; +wire gpio_intr_flag_int; +wire gpio_intrclk_en; +wire [7 :0] gpio_intstatus; +wire [7 :0] gpio_inttype_level; +wire gpio_ls_sync; +wire [7 :0] gpio_porta_ddr; +wire [7 :0] gpio_porta_dr; +wire [7 :0] gpio_porta_eoi; +wire [7 :0] gpio_porta_oe; +wire [7 :0] gpio_raw_intstatus; +wire [7 :0] gpio_swporta_ctl; +wire [7 :0] gpio_swporta_ddr; +wire [7 :0] gpio_swporta_dr; +wire [6 :2] paddr; +wire pclk; +wire pclk_intr; +wire penable; +wire [31:0] prdata; +wire presetn; +wire psel; +wire [31:0] pwdata; +wire pwrite; + + +// &Force("nonport", "gpio_intstatus"); @27 +// &Force("nonport", "gpio_intr_flag"); @28 +// &Force("nonport", "gpio_intr_flag_n"); @29 +// &Force("nonport", "gpio_intr_int"); @30 +// &Force("nonport", "gpio_intr_n"); @31 +// &Force("nonport", "gpio_intr_flag_int"); @32 +// &Force("nonport", "gpio_intrclk_en"); @33 +// &Force("inout", "b_pad_gpio_porta"); @34 + +// &Instance("gpio_apbif"); @36 +gpio_apbif x_gpio_apbif ( + .gpio_ext_porta_rb (gpio_ext_porta_rb ), + .gpio_int_polarity (gpio_int_polarity ), + .gpio_inten (gpio_inten ), + .gpio_intmask (gpio_intmask ), + .gpio_intstatus (gpio_intstatus ), + .gpio_inttype_level (gpio_inttype_level), + .gpio_ls_sync (gpio_ls_sync ), + .gpio_porta_eoi (gpio_porta_eoi ), + .gpio_raw_intstatus (gpio_raw_intstatus), + .gpio_swporta_ctl (gpio_swporta_ctl ), + .gpio_swporta_ddr (gpio_swporta_ddr ), + .gpio_swporta_dr (gpio_swporta_dr ), + .paddr (paddr ), + .pclk (pclk ), + .penable (penable ), + .prdata (prdata ), + .presetn (presetn ), + .psel (psel ), + .pwdata (pwdata ), + .pwrite (pwrite ) +); + +// &Instance("gpio_ctrl"); @37 +gpio_ctrl x_gpio_ctrl ( + .gpio_ext_porta (gpio_ext_porta ), + .gpio_ext_porta_rb (gpio_ext_porta_rb ), + .gpio_int_polarity (gpio_int_polarity ), + .gpio_inten (gpio_inten ), + .gpio_intmask (gpio_intmask ), + .gpio_intr (gpio_intr ), + .gpio_intr_flag_int (gpio_intr_flag_int), + .gpio_intr_int (gpio_intstatus ), + .gpio_intrclk_en (gpio_intrclk_en ), + .gpio_inttype_level (gpio_inttype_level), + .gpio_ls_sync (gpio_ls_sync ), + .gpio_porta_ddr (gpio_porta_ddr ), + .gpio_porta_dr (gpio_porta_dr ), + .gpio_porta_eoi (gpio_porta_eoi ), + .gpio_raw_intstatus (gpio_raw_intstatus), + .gpio_swporta_ctl (gpio_swporta_ctl ), + .gpio_swporta_ddr (gpio_swporta_ddr ), + .gpio_swporta_dr (gpio_swporta_dr ), + .pclk (pclk ), + .pclk_intr (pclk_intr ), + .presetn (presetn ) +); + +// &Connect(.gpio_intr_int(gpio_intstatus)); @38 + +assign gpio_porta_oe[0] = gpio_porta_ddr[0]; +assign gpio_ext_porta[0] = b_pad_gpio_porta[0]; +assign b_pad_gpio_porta[0] = gpio_porta_oe[0] ? gpio_porta_dr[0] : 1'bz; + +assign gpio_porta_oe[1] = gpio_porta_ddr[1]; +assign gpio_ext_porta[1] = b_pad_gpio_porta[1]; +assign b_pad_gpio_porta[1] = gpio_porta_oe[1] ? gpio_porta_dr[1] : 1'bz; + +assign gpio_porta_oe[2] = gpio_porta_ddr[2]; +assign gpio_ext_porta[2] = b_pad_gpio_porta[2]; +assign b_pad_gpio_porta[2] = gpio_porta_oe[2] ? gpio_porta_dr[2] : 1'bz; + +assign gpio_porta_oe[3] = gpio_porta_ddr[3]; +assign gpio_ext_porta[3] = b_pad_gpio_porta[3]; +assign b_pad_gpio_porta[3] = gpio_porta_oe[3] ? gpio_porta_dr[3] : 1'bz; + +assign gpio_porta_oe[4] = gpio_porta_ddr[4]; +assign gpio_ext_porta[4] = b_pad_gpio_porta[4]; +assign b_pad_gpio_porta[4] = gpio_porta_oe[4] ? gpio_porta_dr[4] : 1'bz; + +assign gpio_porta_oe[5] = gpio_porta_ddr[5]; +assign gpio_ext_porta[5] = b_pad_gpio_porta[5]; +assign b_pad_gpio_porta[5] = gpio_porta_oe[5] ? gpio_porta_dr[5] : 1'bz; + +assign gpio_porta_oe[6] = gpio_porta_ddr[6]; +assign gpio_ext_porta[6] = b_pad_gpio_porta[6]; +assign b_pad_gpio_porta[6] = gpio_porta_oe[6] ? gpio_porta_dr[6] : 1'bz; + +assign gpio_porta_oe[7] = gpio_porta_ddr[7]; +assign gpio_ext_porta[7] = b_pad_gpio_porta[7]; +assign b_pad_gpio_porta[7] = gpio_porta_oe[7] ? gpio_porta_dr[7] : 1'bz; + +// &ModuleEnd; @72 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_apbif.v b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_apbif.v new file mode 100644 index 0000000000000000000000000000000000000000..ebdcbc572fd84e9e7df3b8f6fec18058487085e0 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_apbif.v @@ -0,0 +1,462 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +`define gpio_swporta_dr_OFFSET 5'b00000 +`define gpio_swporta_ddr_OFFSET 5'b00001 +`define gpio_swporta_ctl_OFFSET 5'b00010 + +`define gpio_inten_OFFSET 5'b01100 +`define gpio_intmask_OFFSET 5'b01101 +`define gpio_inttype_level_OFFSET 5'b01110 +`define gpio_int_polarity_OFFSET 5'b01111 +`define gpio_intstatus_OFFSET 5'b10000 +`define gpio_raw_intstatus_OFFSET 5'b10001 + +`define gpio_porta_eoi_OFFSET 5'b10011 +`define gpio_ext_porta_OFFSET 5'b10100 + +`define gpio_ls_sync_OFFSET 5'b11000 + + +// &ModuleBeg; @38 +module gpio_apbif( + gpio_ext_porta_rb, + gpio_int_polarity, + gpio_inten, + gpio_intmask, + gpio_intstatus, + gpio_inttype_level, + gpio_ls_sync, + gpio_porta_eoi, + gpio_raw_intstatus, + gpio_swporta_ctl, + gpio_swporta_ddr, + gpio_swporta_dr, + paddr, + pclk, + penable, + prdata, + presetn, + psel, + pwdata, + pwrite +); + +// &Ports; @39 +input [7 :0] gpio_ext_porta_rb; +input [7 :0] gpio_intstatus; +input [7 :0] gpio_raw_intstatus; +input [6 :2] paddr; +input pclk; +input penable; +input presetn; +input psel; +input [31:0] pwdata; +input pwrite; +output [7 :0] gpio_int_polarity; +output [7 :0] gpio_inten; +output [7 :0] gpio_intmask; +output [7 :0] gpio_inttype_level; +output gpio_ls_sync; +output [7 :0] gpio_porta_eoi; +output [7 :0] gpio_swporta_ctl; +output [7 :0] gpio_swporta_ddr; +output [7 :0] gpio_swporta_dr; +output [31:0] prdata; + +// &Regs; @40 +reg [3 :0] gpio_int_polarity_wen; +reg [3 :0] gpio_inten_wen; +reg [3 :0] gpio_intmask_wen; +reg [3 :0] gpio_inttype_level_wen; +reg [3 :0] gpio_ls_sync_wen; +reg [3 :0] gpio_porta_eoi_wen; +reg [3 :0] gpio_swporta_ctl_wen; +reg [3 :0] gpio_swporta_ddr_wen; +reg [3 :0] gpio_swporta_dr_wen; +reg [31:0] int_gpio_int_polarity; +reg [31:0] int_gpio_inten; +reg [31:0] int_gpio_intmask; +reg [31:0] int_gpio_inttype_level; +reg [31:0] int_gpio_ls_sync; +reg [31:0] int_gpio_porta_eoi; +reg [31:0] int_gpio_swporta_ctl; +reg [31:0] int_gpio_swporta_ddr; +reg [31:0] int_gpio_swporta_dr; +reg [31:0] iprdata; +reg [31:0] prdata; +reg [31:0] pwdata_int; +reg [31:0] ri_gpio_ext_porta_rb; +reg [31:0] ri_gpio_int_polarity; +reg [31:0] ri_gpio_inten; +reg [31:0] ri_gpio_intmask; +reg [31:0] ri_gpio_intstatus; +reg [31:0] ri_gpio_inttype_level; +reg [31:0] ri_gpio_ls_sync; +reg [31:0] ri_gpio_raw_intstatus; +reg [31:0] ri_gpio_swporta_ctl; +reg [31:0] ri_gpio_swporta_ddr; +reg [31:0] ri_gpio_swporta_dr; + +// &Wires; @41 +wire [7 :0] gpio_ext_porta_rb; +wire [7 :0] gpio_int_polarity; +wire [7 :0] gpio_inten; +wire [7 :0] gpio_intmask; +wire [7 :0] gpio_intstatus; +wire [7 :0] gpio_inttype_level; +wire gpio_ls_sync; +wire [7 :0] gpio_porta_eoi; +wire [7 :0] gpio_raw_intstatus; +wire [7 :0] gpio_swporta_ctl; +wire [7 :0] gpio_swporta_ddr; +wire [7 :0] gpio_swporta_dr; +wire [6 :2] paddr; +wire pclk; +wire penable; +wire presetn; +wire psel; +wire [31:0] pwdata; +wire pwrite; + + +// pwdata_int assigns to pwdata and padded with zero's +// &CombBeg; @44 +always @( pwdata[31:0]) +begin + pwdata_int = {31{1'b0}}; + pwdata_int[31:0] = pwdata[31:0]; +// &CombEnd; @47 +end + +// Generate Write Enable bus for gpio_swporta_dr register, +// gpio_swporta_dr register and gpio_swporta_ctl register. +// &CombBeg; @51 +always @( paddr[6:2] + or penable + or psel + or pwrite) +begin + gpio_swporta_dr_wen[3:0] = 4'b0000; + gpio_swporta_ddr_wen[3:0] = 4'b0000; + gpio_swporta_ctl_wen[3:0] = 4'b0000; + + if((psel == 1'b1) && (penable == 1'b1) && (pwrite == 1'b1)) + begin + if(paddr[6:2] == + `gpio_swporta_dr_OFFSET) + begin + gpio_swporta_dr_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_swporta_ddr_OFFSET) + begin + gpio_swporta_ddr_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_swporta_ctl_OFFSET) + begin + gpio_swporta_ctl_wen[3:0] = {4{1'b0}}; + end + end +// &CombEnd; @74 +end + +// Generate Write Enable bus for gpio_inten register, +// gpio_intmask register, gpio_inttype_level register, +// gpio_int_polarity register, gpio_ls_sync register +// and clear gpio_porta_eoi register. +// &CombBeg; @80 +always @( paddr[6:2] + or penable + or psel + or pwrite) +begin + gpio_inten_wen[3:0] = 4'b0000; + gpio_intmask_wen[3:0] = 4'b0000; + gpio_inttype_level_wen[3:0] = 4'b0000; + gpio_int_polarity_wen[3:0] = 4'b0000; + gpio_ls_sync_wen[3:0] = 4'b0000; + gpio_porta_eoi_wen[3:0] = 4'b0000; + + if((psel == 1'b1) && (penable == 1'b1) && (pwrite == 1'b1)) + begin + if(paddr[6:2] == + `gpio_inten_OFFSET) + begin + gpio_inten_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_intmask_OFFSET) + begin + gpio_intmask_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_inttype_level_OFFSET) + begin + gpio_inttype_level_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_int_polarity_OFFSET) + begin + gpio_int_polarity_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_ls_sync_OFFSET) + begin + gpio_ls_sync_wen[3:0] = {4{1'b1}}; + end + else if(paddr[6:2] == + `gpio_porta_eoi_OFFSET) + begin + gpio_porta_eoi_wen[3:0] = {4{1'b1}}; + end + end +// &CombEnd; @121 +end + +// Register used to store Software Port A Data register +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_swporta_dr[31:0] <= {32{1'b0}}; + else + if(&gpio_swporta_dr_wen) + int_gpio_swporta_dr[31:0] <= pwdata_int[31:0]; +end + +assign gpio_swporta_dr[7:0] = int_gpio_swporta_dr[7:0]; + +// &CombBeg; @135 +always @( int_gpio_swporta_dr[7:0]) +begin + ri_gpio_swporta_dr[31:0] = {32{1'b0}}; + ri_gpio_swporta_dr[7:0] = int_gpio_swporta_dr[7:0]; +// &CombEnd; @138 +end + +// Register used to store Software Port A Data Direction register +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_swporta_ddr[31:0] <= {32{1'b0}}; + else + if(&gpio_swporta_ddr_wen) + int_gpio_swporta_ddr[31:0] <= pwdata_int[31:0]; +end + +assign gpio_swporta_ddr[7:0] = int_gpio_swporta_ddr[7:0]; + +// &CombBeg; @152 +always @( int_gpio_swporta_ddr[7:0]) +begin + ri_gpio_swporta_ddr[31:0] = {32{1'b0}}; + ri_gpio_swporta_ddr[7:0] = int_gpio_swporta_ddr[7:0]; +// &CombEnd; @155 +end + +// Register used to store Software Port A mode control register +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_swporta_ctl[31:0] <= {32{1'b0}}; + else + if(&gpio_swporta_ctl_wen) + int_gpio_swporta_ctl[31:0] <= pwdata_int[31:0]; +end + +assign gpio_swporta_ctl[7:0] = int_gpio_swporta_ctl[7:0]; + +// &CombBeg; @169 +always @( int_gpio_swporta_ctl[7:0]) +begin + ri_gpio_swporta_ctl[31:0] = {32{1'b0}}; + ri_gpio_swporta_ctl[7:0] = int_gpio_swporta_ctl[7:0]; +// &CombEnd; @172 +end + +// Register used to store Interrupt Enable for each bit +// of Port A +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_inten[31:0] <= 32'b0; + else + if(&gpio_inten_wen) + int_gpio_inten[31:0] <= pwdata_int[31:0]; +end + +assign gpio_inten[7:0] = int_gpio_inten[7:0]; + +// &CombBeg; @187 +always @( int_gpio_inten[7:0]) +begin + ri_gpio_inten[31:0] = {32{1'b0}}; + ri_gpio_inten[7:0] = int_gpio_inten[7:0]; +// &CombEnd; @190 +end + +// Register used to store Interrupt mask for each bit of Port A +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_intmask[31:0] <= 32'b0; + else + if(&gpio_intmask_wen) + int_gpio_intmask[31:0] <= pwdata_int[31:0]; +end + +assign gpio_intmask[7:0] = int_gpio_intmask[7:0]; + +// &CombBeg; @204 +always @( int_gpio_intmask[7:0]) +begin + ri_gpio_intmask[31:0] = {32{1'b0}}; + ri_gpio_intmask[7:0] = int_gpio_intmask[7:0]; +// &CombEnd; @207 +end + +// Register used to store Interrupt type, level or edge, for each bit of Port A +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_inttype_level[31:0] <= 32'b0; + else + if(&gpio_inttype_level_wen) + int_gpio_inttype_level[31:0] <= pwdata_int[31:0]; +end + +assign gpio_inttype_level[7:0] = int_gpio_inttype_level[7:0]; + +// &CombBeg; @221 +always @( int_gpio_inttype_level[7:0]) +begin + ri_gpio_inttype_level[31:0] = {32{1'b0}}; + ri_gpio_inttype_level[7:0] = int_gpio_inttype_level[7:0]; +// &CombEnd; @224 +end + +// Register used to store Interrupt polarity for each bit of Port A +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_int_polarity[31:0] <= 32'b0; + else + if(&gpio_int_polarity_wen) + int_gpio_int_polarity[31:0] <= pwdata_int[31:0]; +end + +assign gpio_int_polarity[7:0] = int_gpio_int_polarity[7:0]; + +// &CombBeg; @238 +always @( int_gpio_int_polarity[7:0]) +begin + ri_gpio_int_polarity[31:0] = {32{1'b0}}; + ri_gpio_int_polarity[7:0] = int_gpio_int_polarity[7:0]; +// &CombEnd; @241 +end + +// Register used to store level sensitive interrupt synchronization +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + int_gpio_ls_sync[31:0] <= 32'b0; + else + if(&gpio_ls_sync_wen) + int_gpio_ls_sync[31:0] <= pwdata_int[31:0]; +end + +assign gpio_ls_sync = int_gpio_ls_sync[0]; + +// &CombBeg; @255 +always @( int_gpio_ls_sync[7:0]) +begin + ri_gpio_ls_sync[31:0] = {32{1'b0}}; + ri_gpio_ls_sync[7:0] = int_gpio_ls_sync[7:0]; +// &CombEnd; @258 +end + +// A write to Interrupt clear address generates pulse +// to control logic to clear interrupt. +// &CombBeg; @262 +always @( gpio_porta_eoi_wen + or pwdata_int[31:0]) +begin + int_gpio_porta_eoi[31:0] = {32{1'b0}}; + if(&gpio_porta_eoi_wen) + int_gpio_porta_eoi[31:0] = pwdata_int[31:0]; +// &CombEnd; @266 +end + +assign gpio_porta_eoi[7:0] = int_gpio_porta_eoi[7:0]; + +// Read only raw interrupt status register from ctrl block +// &CombBeg; @271 +always @( gpio_intstatus[7:0] + or gpio_raw_intstatus[7:0]) +begin + ri_gpio_raw_intstatus[31:0] = {32{1'b0}}; + ri_gpio_intstatus[31:0] = {32{1'b0}}; + + ri_gpio_raw_intstatus[7:0] = gpio_raw_intstatus[7:0]; + ri_gpio_intstatus[7:0] = gpio_intstatus[7:0]; +// &CombEnd; @277 +end + +// &CombBeg; @279 +always @( gpio_ext_porta_rb[7:0]) +begin + ri_gpio_ext_porta_rb[31:0] = {32{1'b0}}; + + ri_gpio_ext_porta_rb[7:0] = gpio_ext_porta_rb[7:0]; +// &CombEnd; @283 +end + +// Output of Read back data mux registered and driven onto +// prdata bus. +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + iprdata[31:0] <= {32{1'b0}}; + else + if((pwrite == 1'b0) && (psel == 1'b1) && (penable == 1'b0)) + case(paddr[6:2]) + `gpio_swporta_dr_OFFSET : iprdata <= ri_gpio_swporta_dr; + `gpio_swporta_ddr_OFFSET : iprdata <= ri_gpio_swporta_ddr; + `gpio_swporta_ctl_OFFSET : iprdata <= ri_gpio_swporta_ctl; + `gpio_inten_OFFSET : iprdata <= ri_gpio_inten; + `gpio_intmask_OFFSET : iprdata <= ri_gpio_intmask; + `gpio_inttype_level_OFFSET : iprdata <= ri_gpio_inttype_level; + `gpio_int_polarity_OFFSET : iprdata <= ri_gpio_int_polarity; + `gpio_intstatus_OFFSET : iprdata <= ri_gpio_intstatus; + `gpio_raw_intstatus_OFFSET : iprdata <= ri_gpio_raw_intstatus; + `gpio_ls_sync_OFFSET : iprdata <= ri_gpio_ls_sync; + `gpio_ext_porta_OFFSET : iprdata <= ri_gpio_ext_porta_rb; + default : iprdata[31:0] <= {32{1'b0}}; + endcase +end + +// &CombBeg; @309 +always @( iprdata[7:0]) +begin + prdata[31:0] = {32{1'b0}}; + prdata[7:0] = iprdata[7:0]; +// &CombEnd; @312 +end + +// &ModuleEnd; @314 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_ctrl.v b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..51c6e75f0f391070ca3406817d049d419037eea1 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/gpio/gpio_ctrl.v @@ -0,0 +1,345 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @21 +module gpio_ctrl( + gpio_ext_porta, + gpio_ext_porta_rb, + gpio_int_polarity, + gpio_inten, + gpio_intmask, + gpio_intr, + gpio_intr_flag_int, + gpio_intr_int, + gpio_intrclk_en, + gpio_inttype_level, + gpio_ls_sync, + gpio_porta_ddr, + gpio_porta_dr, + gpio_porta_eoi, + gpio_raw_intstatus, + gpio_swporta_ctl, + gpio_swporta_ddr, + gpio_swporta_dr, + pclk, + pclk_intr, + presetn +); + +// &Ports; @22 +input [7:0] gpio_ext_porta; +input [7:0] gpio_int_polarity; +input [7:0] gpio_inten; +input [7:0] gpio_intmask; +input [7:0] gpio_inttype_level; +input gpio_ls_sync; +input [7:0] gpio_porta_eoi; +input [7:0] gpio_swporta_ctl; +input [7:0] gpio_swporta_ddr; +input [7:0] gpio_swporta_dr; +input pclk; +input pclk_intr; +input presetn; +output [7:0] gpio_ext_porta_rb; +output [7:0] gpio_intr; +output gpio_intr_flag_int; +output [7:0] gpio_intr_int; +output gpio_intrclk_en; +output [7:0] gpio_porta_ddr; +output [7:0] gpio_porta_dr; +output [7:0] gpio_raw_intstatus; + +// &Regs; @23 +reg [7:0] ed_int_d1; +reg [7:0] ed_out; +reg [7:0] gpio_ext_porta_int; +reg [7:0] gpio_ext_porta_rb; +reg [7:0] gpio_intr_ed_pm; +reg gpio_intrclk_en; +reg [7:0] gpio_porta_ddr; +reg [7:0] gpio_porta_dr; +reg [7:0] int_gpio_raw_intstatus; +reg [7:0] int_pre_in; +reg [7:0] int_s1; +reg [7:0] int_sy_in; +reg [7:0] intrclk_en; +reg [7:0] ls_int_in; + +// &Wires; @24 +wire [7:0] ed_rf; +wire [7:0] gpio_ext_porta; +wire [7:0] gpio_int_polarity; +wire [7:0] gpio_inten; +wire [7:0] gpio_intmask; +wire [7:0] gpio_intr; +wire gpio_intr_flag_int; +wire [7:0] gpio_intr_int; +wire gpio_intrclk_en_int; +wire [7:0] gpio_inttype_level; +wire gpio_ls_sync; +wire [7:0] gpio_porta_eoi; +wire [7:0] gpio_raw_intstatus; +wire [7:0] gpio_swporta_ctl; +wire [7:0] gpio_swporta_ctl_internal; +wire [7:0] gpio_swporta_ddr; +wire [7:0] gpio_swporta_dr; +wire [7:0] int_in; +wire pclk; +wire pclk_intr; +wire presetn; + + +// &Force("output", "gpio_intr"); @26 +// &Force("output", "gpio_intr_int"); @27 +// &Force("output", "gpio_raw_intstatus"); @28 +// &Force("output", "gpio_porta_ddr"); @29 + +// gpio_intrclk_en output asserted if any bit of port +// a is enabled for edge sensitive interrupts or +// any bit of port a is enabled for level sensitive +// interrupts and level sensitive synchronisation +// is required. +integer type_i; +// &CombBeg; @37 +always @( gpio_inttype_level[1:0] + or gpio_ls_sync + or gpio_inten[7:0] + or gpio_inttype_level[7:1]) +begin + + for(type_i = 0 ; type_i < 8 ; type_i=type_i+1) + begin + if(gpio_inten[type_i] == 1'b1) + if(gpio_inttype_level[type_i] == 1'b1) + intrclk_en[type_i] = 1'b1; + else + intrclk_en[type_i] = gpio_ls_sync; + else + intrclk_en[type_i] = 1'b0; + end +// &CombEnd; @49 +end + +assign gpio_intrclk_en_int = | intrclk_en; + +always@(posedge pclk or negedge presetn) +begin + if(!presetn) + gpio_intrclk_en <= 1'b0; + else + gpio_intrclk_en <= gpio_intrclk_en_int; +end + +// Input is inverted for falling edge or active low +// sensitive interrupts. +integer polarity_i; +// &CombBeg; @64 +always @( gpio_ext_porta[1:0] + or gpio_int_polarity[7:0] + or gpio_ext_porta[7:0] + or gpio_int_polarity[1:0]) +begin + gpio_ext_porta_int[7:0] = {8{1'b0}}; + for(polarity_i = 0 ; polarity_i < 8 ; polarity_i=polarity_i+1) + begin + if(gpio_int_polarity[polarity_i] == 1'b0) + gpio_ext_porta_int[polarity_i] = ~gpio_ext_porta[polarity_i]; + else + gpio_ext_porta_int[polarity_i] = gpio_ext_porta[polarity_i]; + end +// &CombEnd; @73 +end + +// &CombBeg; @75 +always @( gpio_ext_porta_int[7:0]) +begin + int_sy_in[7:0] = {8{1'b0}}; + int_sy_in[7:0] = gpio_ext_porta_int[7:0]; +// &CombEnd; @78 +end + +// Meta-stabilty registers. Synchronize to pclk_intr. +always @(posedge pclk_intr or negedge presetn) +begin + if(!presetn) + int_s1[7:0] <= {8{1'b0}}; + else + int_s1[7:0] <= int_sy_in[7:0]; +end + +always @(posedge pclk_intr or negedge presetn) +begin + if(!presetn) + int_pre_in[7:0] <= {8{1'b0}}; + else + int_pre_in[7:0] <= int_s1; +end + +assign int_in[7:0] = int_pre_in[7:0]; + +// edge detect circuitry. +always @(posedge pclk_intr or negedge presetn) +begin + if(!presetn) + ed_int_d1[7:0] <= {8{1'b0}}; + else + ed_int_d1[7:0] <= int_in[7:0]; +end + +assign ed_rf[7:0] = int_in ^ ed_int_d1; + +// Rising edge detect +integer ed_j; +// &CombBeg; @112 +always @( ed_rf[7:0] + or int_in[7:0]) +begin + + ed_out[7:0] = {8{1'b0}}; + for(ed_j = 0 ; ed_j < 8 ; ed_j=ed_j+1) + begin + ed_out[ed_j] = ed_rf[ed_j] & int_in[ed_j]; + end +// &CombEnd; @119 +end + +// edge detect interrupt register pre-masking. If edge detection +// occurs at same time as write to interrupt clear register then +// write to interrupt clear register will not clear the interrupt. +// Interrupts can only be set when direction is input and in +// software mode. +assign gpio_swporta_ctl_internal[7:0] = gpio_swporta_ctl[7:0]; +integer int_k; +always @(posedge pclk_intr or negedge presetn) +begin + if(!presetn) + gpio_intr_ed_pm[7:0] <= {8{1'b0}}; + else + for(int_k = 0 ; int_k < 8 ; int_k=int_k+1) + begin + if(gpio_inten[int_k] == 1'b0) + gpio_intr_ed_pm[int_k] <= 1'b0; + else + if((ed_out[int_k] == 1'b1) && + (gpio_inten[int_k] == 1'b1) && + (gpio_swporta_ddr[int_k] == 1'b0) && + (gpio_swporta_ctl_internal[int_k] == 1'b0)) + gpio_intr_ed_pm[int_k] <= 1'b1; + else + if(gpio_porta_eoi[int_k] == 1'b1) + gpio_intr_ed_pm[int_k] <= 1'b0; + end +end + +// Level senistive interrupts may pass through synchronization +// and debounce logic. Under S/W control. +// Interrupts can only be set when direction is input and in +// software mode. +integer lsa_k; + +// &CombBeg; @155 +always @( int_in[7:0] + or gpio_swporta_ddr[7:0] + or gpio_swporta_ctl_internal[2:0] + or gpio_ls_sync + or int_sy_in[7:0] + or gpio_swporta_ctl_internal[7:2]) +begin + ls_int_in[7:0] = {8{1'b0}}; + for(lsa_k = 0 ; lsa_k < 8 ; lsa_k=lsa_k+1) + begin + if(((gpio_swporta_ddr[lsa_k]) == 1'b1) || + (gpio_swporta_ctl_internal[lsa_k] == 1'b1)) + ls_int_in[lsa_k] = 0; + else + if(gpio_ls_sync == 1'b1) + ls_int_in[lsa_k] = int_in[lsa_k]; + else + ls_int_in[lsa_k] = int_sy_in[lsa_k]; + end +// &CombEnd; @168 +end + +// Level or edge sensitive interrupts +integer raw_l; + +// &CombBeg; @173 +always @( gpio_inten[7:3] + or gpio_intr_ed_pm[2:0] + or gpio_intr_ed_pm[7:1] + or gpio_inten[4:0] + or gpio_inttype_level[7:0] + or ls_int_in[7:0]) +begin + int_gpio_raw_intstatus[7:0] = {8{1'b0}}; + for(raw_l = 0 ; raw_l < 8 ; raw_l=raw_l+1) + begin + if(gpio_inten[raw_l] == 1'b0) + int_gpio_raw_intstatus[raw_l] = 0; + else + if(gpio_inttype_level[raw_l] == 1'b1) + int_gpio_raw_intstatus[raw_l] = gpio_intr_ed_pm[raw_l]; + else + int_gpio_raw_intstatus[raw_l] = ls_int_in[raw_l]; + end +// &CombEnd; @185 +end + +assign gpio_raw_intstatus[7:0] = int_gpio_raw_intstatus[7:0]; +assign gpio_intr_int[7:0] = gpio_raw_intstatus[7:0] & ~gpio_intmask[7:0]; +assign gpio_intr[7:0] = gpio_intr_int[7:0]; + +assign gpio_intr_flag_int = |gpio_intr_int[7:0]; +// &CombBeg; @192 +always @( gpio_swporta_dr[7:0]) +begin + gpio_porta_dr[7:0] = {8{1'b0}}; + gpio_porta_dr[7:0] = gpio_swporta_dr[7:0]; +// &CombEnd; @195 +end + +// &CombBeg; @197 +always @( gpio_swporta_ddr[7:0]) +begin + gpio_porta_ddr[7:0] = {8{1'b0}}; + gpio_porta_ddr[7:0] = gpio_swporta_ddr[7:0]; +// &CombEnd; @200 +end + +integer rba_i; + +// &CombBeg; @204 +always @( gpio_swporta_dr[2:1] + or gpio_ext_porta[7:0] + or gpio_swporta_dr[7:0] + or gpio_porta_ddr[7:0]) +begin + gpio_ext_porta_rb[7:0] = {8{1'b0}}; + for(rba_i = 0 ; rba_i < 8 ; rba_i=rba_i+1) + begin + if(gpio_porta_ddr[rba_i] == 1'b1) + gpio_ext_porta_rb[rba_i] = gpio_swporta_dr[rba_i]; + else + gpio_ext_porta_rb[rba_i] = gpio_ext_porta[rba_i]; + end +// &CombEnd; @213 +end + +integer rbb_i; + +// &ModuleEnd; @217 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/mem/dahb_mem_ctrl.v b/XUANTIE-RV_opene906/smart_run/logical/mem/dahb_mem_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..ce5a5ccd38bbad68bbb0818ca8a1d092b22e95cd --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/mem/dahb_mem_ctrl.v @@ -0,0 +1,465 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module dahb_mem_ctrl( + lite_mmc_hsel, + lite_yy_haddr, + lite_yy_hsize, + lite_yy_htrans, + lite_yy_hwdata, + lite_yy_hwrite, + mmc_lite_hrdata, + mmc_lite_hready, + mmc_lite_hresp, + pad_biu_bigend_b, + pad_cpu_rst_b, + pll_core_cpuclk +); + +// &Ports; @22 +input lite_mmc_hsel; +input [31:0] lite_yy_haddr; +input [2 :0] lite_yy_hsize; +input [1 :0] lite_yy_htrans; +input [31:0] lite_yy_hwdata; +input lite_yy_hwrite; +input pad_biu_bigend_b; +input pad_cpu_rst_b; +input pll_core_cpuclk; +output [31:0] mmc_lite_hrdata; +output mmc_lite_hready; +output [1 :0] mmc_lite_hresp; + +// &Regs; @23 +reg [29:0] addr_holding; +reg [3 :0] lite_mem_wen; +reg lite_read_bypass; +reg lite_read_bypass_vld; +reg lite_read_stall; +reg lite_read_stall_vld; +reg [31:0] lite_wbuf_addr; +reg [31:0] lite_wbuf_data; +reg [2 :0] lite_wbuf_size; +reg lite_write_req; +reg lite_write_stall; + +// &Wires; @24 +wire lite_addr_hit; +wire lite_addr_no_hit; +wire [31:0] lite_bypass_data; +wire [31:0] lite_mem_addr; +wire lite_mem_cen; +wire [31:0] lite_mem_din; +wire [31:0] lite_mem_dout; +wire lite_mmc_hsel; +wire lite_read_addr_hit_with_bypass; +wire lite_read_addr_hit_with_stall; +wire lite_read_req; +wire lite_wbuf_update; +wire lite_write_cplt; +wire lite_write_en; +wire lite_write_req_en; +wire lite_write_stall_en; +wire [31:0] lite_yy_haddr; +wire [2 :0] lite_yy_hsize; +wire [31:0] lite_yy_hwdata; +wire lite_yy_hwrite; +wire [31:0] mmc_lite_hrdata; +wire mmc_lite_hready; +wire [1 :0] mmc_lite_hresp; +wire pad_biu_bigend_b; +wire pad_cpu_rst_b; +wire pll_core_cpuclk; +wire [7 :0] ram0_din; +wire [7 :0] ram0_dout; +wire [7 :0] ram1_din; +wire [7 :0] ram1_dout; +wire [7 :0] ram2_din; +wire [7 :0] ram2_dout; +wire [7 :0] ram3_din; +wire [7 :0] ram3_dout; +wire [7 :0] ram4_dout; +wire [7 :0] ram5_dout; +wire [7 :0] ram6_dout; +wire [7 :0] ram7_dout; +wire [29:0] ram_addr; +wire ram_clk; +wire [7 :0] ram_wen; + +parameter DMEM_WIDTH = 20; + +// &Force("nonport","lite_mem_addr"); @27 +// &Force("nonport","lite_mem_cen"); @28 +// &Force("nonport","lite_mem_din"); @29 +// &Force("nonport","lite_mem_dout"); @30 +// &Force("nonport","lite_mem_wen"); @31 +// &Force("input","lite_yy_htrans"); @32 +// &Force("bus", "lite_yy_htrans", 1, 0); @33 +// //&Force("nonport",""); @34 +// //&Force("nonport",""); @35 +// //&Force("nonport",""); @36 +// //&Force("nonport",""); @37 +// //&Force("nonport",""); @38 +// //&Force("nonport",""); @39 +// //&Force("nonport",""); @40 + + +//write buffer +assign lite_wbuf_update = lite_yy_hwrite && lite_mmc_hsel; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_wbuf_addr[31:0] <= 32'b0; + lite_wbuf_size[2:0] <= 3'b0; + end + else if (lite_wbuf_update) + begin + lite_wbuf_addr[31:0] <= lite_yy_haddr; + lite_wbuf_size[2:0] <= lite_yy_hsize; + end + //else if (lite_write_cplt) + //begin + // lite_wbuf_addr[31:0] <= 32'b0; + // lite_wbuf_size[2:0] <= 3'b0; + //end +end +//write data +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_wbuf_data[31:0] <= 32'b0; + end + else if (lite_write_req) + begin + lite_wbuf_data[31:0] <= lite_yy_hwdata[31:0]; + end +end +//read first and wirte will stall when address don't hit +assign lite_write_stall_en = lite_write_req && lite_addr_no_hit && lite_read_req; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_write_stall <= 1'b0; + end + else if (lite_write_stall_en) + begin + lite_write_stall <= 1'b1; + end + else if (lite_write_cplt) + begin + lite_write_stall <=1'b0; + end +end +//write request from bus interface +assign lite_write_req_en = lite_yy_hwrite && lite_mmc_hsel; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_write_req <= 1'b0; + end + else if (lite_write_req_en) + begin + lite_write_req <= 1'b1; + end + else + begin + lite_write_req <= 1'b0; + end +end +//read bypass and read stall +always @(posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_read_bypass <= 1'b0; + lite_read_stall <= 1'b0; + end + else + begin + lite_read_bypass <= lite_read_addr_hit_with_bypass; + lite_read_stall <= lite_read_addr_hit_with_stall; + end +end + +//no read first and write request or write stall +assign lite_write_en = ((lite_write_req | lite_write_stall) && (lite_addr_hit | (lite_yy_hwrite && lite_mmc_hsel) | ~lite_mmc_hsel)); +assign lite_bypass_data[31:0] = lite_wbuf_data[31:0]; +//write complete +assign lite_write_cplt = (lite_write_req | lite_write_stall) && (lite_addr_hit | ~lite_mmc_hsel | (lite_yy_hwrite && lite_mmc_hsel)); +//read request +assign lite_read_req = ~lite_yy_hwrite && lite_mmc_hsel; +//address hit +assign lite_addr_no_hit = (lite_yy_haddr[31:2] != lite_wbuf_addr[31:2]); +assign lite_addr_hit = ~lite_addr_no_hit; +//address hit and read will bypass +assign lite_read_addr_hit_with_bypass = lite_read_req && (lite_write_req | lite_write_stall) && lite_addr_hit && lite_read_bypass_vld; +//address hit but read will stall +assign lite_read_addr_hit_with_stall = lite_read_req && (lite_write_req | lite_write_stall) && lite_addr_hit && lite_read_stall_vld; + +//read bypass or stall +// &CombBeg; @140 +always @( lite_yy_haddr[1:0] + or lite_wbuf_addr[1:0] + or lite_wbuf_size[2:0] + or lite_yy_hsize[2:0]) +begin +casez({lite_wbuf_size[2:0],lite_yy_hsize[2:0],lite_wbuf_addr[1:0],lite_yy_haddr[1:0]}) +//st.b/ld.b +10'b000_000_00_00, +10'b000_000_01_01, +10'b000_000_10_10, +10'b000_000_11_11: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.b/ld.h +10'b000_001_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.b/ld.w +10'b000_010_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.h/ld.b +10'b001_000_0?_0?, +10'b001_000_1?_1?: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.h/ld.h +10'b001_001_0?_0?, +10'b001_001_1?_1?: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.h/ld.w +10'b001_010_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.w/all lds +10'b010_???_??_??: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +default: + begin + lite_read_bypass_vld = 1'b0; + lite_read_stall_vld = 1'b0; + end +endcase +// &CombEnd; @195 +end + + + +//memory select +assign lite_mem_cen = ~(lite_read_req | lite_write_req | lite_write_stall); +//memory write enable +// &CombBeg; @202 +always @( lite_wbuf_addr[1:0] + or lite_wbuf_size[2:0] + or pad_biu_bigend_b + or lite_write_en) +begin + case({pad_biu_bigend_b, lite_write_en, lite_wbuf_size[2:0], lite_wbuf_addr[1:0]}) + 7'b0100000: + begin + lite_mem_wen[3:0] = 4'b0111; + end + 7'b0100001: + begin + lite_mem_wen[3:0] = 4'b1011; + end + 7'b0100010: + begin + lite_mem_wen[3:0] = 4'b1101; + end + 7'b0100011: + begin + lite_mem_wen[3:0] = 4'b1110; + end + 7'b0100100: + begin + lite_mem_wen[3:0] = 4'b0011; + end + 7'b0100110: + begin + lite_mem_wen[3:0] = 4'b1100; + end + 7'b0101000: + begin + lite_mem_wen[3:0] = 4'b0000; + end + 7'b1100000: + begin + lite_mem_wen[3:0] = 4'b1110; + end + 7'b1100001: + begin + lite_mem_wen[3:0] = 4'b1101; + end + 7'b1100010: + begin + lite_mem_wen[3:0] = 4'b1011; + end + 7'b1100011: + begin + lite_mem_wen[3:0] = 4'b0111; + end + 7'b1100100: + begin + lite_mem_wen[3:0] = 4'b1100; + end + 7'b1100110: + begin + lite_mem_wen[3:0] = 4'b0011; + end + 7'b1101000: + begin + lite_mem_wen[3:0] = 4'b0000; + end + default: + begin + lite_mem_wen[3:0] = 4'b1111; + end + endcase +// &CombEnd; @265 +end + +assign lite_mem_addr[31:0] = (lite_write_en | lite_read_stall) ? lite_wbuf_addr[31:0] : lite_yy_haddr[31:0]; +assign lite_mem_din[31:0] = (lite_write_stall) ? lite_wbuf_data[31:0] : lite_yy_hwdata[31:0]; +assign mmc_lite_hrdata[31:0] = lite_read_bypass ? lite_bypass_data[31:0] : lite_mem_dout[31:0]; +assign mmc_lite_hready = !lite_read_stall; +assign mmc_lite_hresp[1:0] = 2'b0; + + + +//memory +always @(posedge pll_core_cpuclk) +begin + if(!lite_mem_cen) + addr_holding[29:0] <= lite_mem_addr[31:2]; +end + +assign ram_clk = pll_core_cpuclk; +assign ram_addr[29:0] = lite_mem_cen ? addr_holding[29:0] : lite_mem_addr[31:2]; +assign ram_wen[0] = (!lite_mem_cen && !lite_mem_wen[0]) && !ram_addr[17]; +assign ram_wen[1] = (!lite_mem_cen && !lite_mem_wen[1]) && !ram_addr[17]; +assign ram_wen[2] = (!lite_mem_cen && !lite_mem_wen[2]) && !ram_addr[17]; +assign ram_wen[3] = (!lite_mem_cen && !lite_mem_wen[3]) && !ram_addr[17]; + +assign ram_wen[4] = !lite_mem_cen && !lite_mem_wen[0] && ram_addr[17]; +assign ram_wen[5] = !lite_mem_cen && !lite_mem_wen[1] && ram_addr[17]; +assign ram_wen[6] = !lite_mem_cen && !lite_mem_wen[2] && ram_addr[17]; +assign ram_wen[7] = !lite_mem_cen && !lite_mem_wen[3] && ram_addr[17]; + +assign ram0_din[7:0] = lite_mem_din[7:0]; +assign ram1_din[7:0] = lite_mem_din[15:8]; +assign ram2_din[7:0] = lite_mem_din[23:16]; +assign ram3_din[7:0] = lite_mem_din[31:24]; +assign lite_mem_dout[31:0] = addr_holding[17] ? {ram7_dout[7:0], ram6_dout[7:0], ram5_dout[7:0], ram4_dout[7:0]} + : {ram3_dout[7:0], ram2_dout[7:0], ram1_dout[7:0], ram0_dout[7:0]}; + +// memory unit is in DPTHx8 size, 4 units are instanced +soc_fpga_ram #(8, 17) ram0( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[16:0]), + .PortADataIn (ram0_din), + .PortAWriteEnable(ram_wen[0]), + .PortADataOut(ram0_dout)); + +soc_fpga_ram #(8, 17) ram1( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[16:0]), + .PortADataIn (ram1_din), + .PortAWriteEnable(ram_wen[1]), + .PortADataOut(ram1_dout)); + +soc_fpga_ram #(8, 17) ram2( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[16:0]), + .PortADataIn (ram2_din), + .PortAWriteEnable(ram_wen[2]), + .PortADataOut(ram2_dout)); + +soc_fpga_ram #(8, 17) ram3( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[16:0]), + .PortADataIn (ram3_din), + .PortAWriteEnable(ram_wen[3]), + .PortADataOut(ram3_dout)); + +soc_fpga_ram #(8, 16) ram4( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[15:0]), + .PortADataIn (ram0_din), + .PortAWriteEnable(ram_wen[4]), + .PortADataOut(ram4_dout)); + +soc_fpga_ram #(8, 16) ram5( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[15:0]), + .PortADataIn (ram1_din), + .PortAWriteEnable(ram_wen[5]), + .PortADataOut(ram5_dout)); + +soc_fpga_ram #(8, 16) ram6( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[15:0]), + .PortADataIn (ram2_din), + .PortAWriteEnable(ram_wen[6]), + .PortADataOut(ram6_dout)); + +soc_fpga_ram #(8, 16) ram7( + .PortAClk (ram_clk), + .PortAAddr(ram_addr[15:0]), + .PortADataIn (ram3_din), + .PortAWriteEnable(ram_wen[7]), + .PortADataOut(ram7_dout)); + + +// &Force("nonport", "ram_addr"); @359 +// &Force("nonport", "ram0_din"); @360 +// &Force("nonport", "ram1_din"); @361 +// &Force("nonport", "ram2_din"); @362 +// &Force("nonport", "ram3_din"); @363 +// &Force("nonport", "ram0_dout"); @364 +// &Force("nonport", "ram1_dout"); @365 +// &Force("nonport", "ram2_dout"); @366 +// &Force("nonport", "ram3_dout"); @367 +// &Force("nonport", "ram4_dout"); @368 +// &Force("nonport", "ram5_dout"); @369 +// &Force("nonport", "ram6_dout"); @370 +// &Force("nonport", "ram7_dout"); @371 +// &Force("nonport", "ram_wen"); @372 +// &Force("nonport", "ram_clk"); @373 +// &ModuleEnd; @374 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/mem/iahb_mem_ctrl.v b/XUANTIE-RV_opene906/smart_run/logical/mem/iahb_mem_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..f09bf0ea32bff95364f35ff8f247e98b09cd8a64 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/mem/iahb_mem_ctrl.v @@ -0,0 +1,421 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module iahb_mem_ctrl( + lite_mmc_hsel, + lite_yy_haddr, + lite_yy_hsize, + lite_yy_htrans, + lite_yy_hwdata, + lite_yy_hwrite, + mmc_lite_hrdata, + mmc_lite_hready, + mmc_lite_hresp, + pad_biu_bigend_b, + pad_cpu_rst_b, + pll_core_cpuclk +); + +// &Ports; @22 +input lite_mmc_hsel; +input [31:0] lite_yy_haddr; +input [2 :0] lite_yy_hsize; +input [1 :0] lite_yy_htrans; +input [31:0] lite_yy_hwdata; +input lite_yy_hwrite; +input pad_biu_bigend_b; +input pad_cpu_rst_b; +input pll_core_cpuclk; +output [31:0] mmc_lite_hrdata; +output mmc_lite_hready; +output [1 :0] mmc_lite_hresp; + +// &Regs; @23 +reg [15:0] addr_holding; +reg [3 :0] lite_mem_wen; +reg lite_read_bypass; +reg lite_read_bypass_vld; +reg lite_read_stall; +reg lite_read_stall_vld; +reg [31:0] lite_wbuf_addr; +reg [31:0] lite_wbuf_data; +reg [2 :0] lite_wbuf_size; +reg lite_write_req; +reg lite_write_stall; + +// &Wires; @24 +wire lite_addr_hit; +wire lite_addr_no_hit; +wire [31:0] lite_bypass_data; +wire [31:0] lite_mem_addr; +wire lite_mem_cen; +wire [31:0] lite_mem_din; +wire [31:0] lite_mem_dout; +wire lite_mmc_hsel; +wire lite_read_addr_hit_with_bypass; +wire lite_read_addr_hit_with_stall; +wire lite_read_req; +wire lite_wbuf_update; +wire lite_write_cplt; +wire lite_write_en; +wire lite_write_req_en; +wire lite_write_stall_en; +wire [31:0] lite_yy_haddr; +wire [2 :0] lite_yy_hsize; +wire [31:0] lite_yy_hwdata; +wire lite_yy_hwrite; +wire [31:0] mmc_lite_hrdata; +wire mmc_lite_hready; +wire [1 :0] mmc_lite_hresp; +wire pad_biu_bigend_b; +wire pad_cpu_rst_b; +wire pll_core_cpuclk; +wire [7 :0] ram0_din; +wire [7 :0] ram0_dout; +wire [7 :0] ram1_din; +wire [7 :0] ram1_dout; +wire [7 :0] ram2_din; +wire [7 :0] ram2_dout; +wire [7 :0] ram3_din; +wire [7 :0] ram3_dout; +wire [15:0] ram_addr; +wire ram_clk; +wire [3 :0] ram_wen; + +parameter IMEM_WIDTH = 18; + +// &Force("nonport","lite_mem_addr"); @27 +// &Force("nonport","lite_mem_cen"); @28 +// &Force("nonport","lite_mem_din"); @29 +// &Force("nonport","lite_mem_dout"); @30 +// &Force("nonport","lite_mem_wen"); @31 +// &Force("input","lite_yy_htrans"); @32 +// &Force("bus", "lite_yy_htrans", 1, 0); @33 +// //&Force("nonport",""); @34 +// //&Force("nonport",""); @35 +// //&Force("nonport",""); @36 +// //&Force("nonport",""); @37 +// //&Force("nonport",""); @38 +// //&Force("nonport",""); @39 +// //&Force("nonport",""); @40 + + +//write buffer +assign lite_wbuf_update = lite_yy_hwrite && lite_mmc_hsel; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_wbuf_addr[31:0] <= 32'b0; + lite_wbuf_size[2:0] <= 3'b0; + end + else if (lite_wbuf_update) + begin + lite_wbuf_addr[31:0] <= lite_yy_haddr; + lite_wbuf_size[2:0] <= lite_yy_hsize; + end + //else if (lite_write_cplt) + //begin + // lite_wbuf_addr[31:0] <= 32'b0; + // lite_wbuf_size[2:0] <= 3'b0; + //end +end +//write data +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_wbuf_data[31:0] <= 32'b0; + end + else if (lite_write_req) + begin + lite_wbuf_data[31:0] <= lite_yy_hwdata[31:0]; + end +end +//read first and wirte will stall when address don't hit +assign lite_write_stall_en = lite_write_req && lite_addr_no_hit && lite_read_req; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_write_stall <= 1'b0; + end + else if (lite_write_stall_en) + begin + lite_write_stall <= 1'b1; + end + else if (lite_write_cplt) + begin + lite_write_stall <=1'b0; + end +end +//write request from bus interface +assign lite_write_req_en = lite_yy_hwrite && lite_mmc_hsel; +always @ (posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_write_req <= 1'b0; + end + else if (lite_write_req_en) + begin + lite_write_req <= 1'b1; + end + else + begin + lite_write_req <= 1'b0; + end +end +//read bypass and read stall +always @(posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + lite_read_bypass <= 1'b0; + lite_read_stall <= 1'b0; + end + else + begin + lite_read_bypass <= lite_read_addr_hit_with_bypass; + lite_read_stall <= lite_read_addr_hit_with_stall; + end +end + +//no read first and write request or write stall +assign lite_write_en = ((lite_write_req | lite_write_stall) && (lite_addr_hit | (lite_yy_hwrite && lite_mmc_hsel) | ~lite_mmc_hsel)); +assign lite_bypass_data[31:0] = lite_wbuf_data[31:0]; +//write complete +assign lite_write_cplt = (lite_write_req | lite_write_stall) && (lite_addr_hit | ~lite_mmc_hsel | (lite_yy_hwrite && lite_mmc_hsel)); +//read request +assign lite_read_req = ~lite_yy_hwrite && lite_mmc_hsel; +//address hit +assign lite_addr_no_hit = (lite_yy_haddr[31:2] != lite_wbuf_addr[31:2]); +assign lite_addr_hit = ~lite_addr_no_hit; +//address hit and read will bypass +assign lite_read_addr_hit_with_bypass = lite_read_req && (lite_write_req | lite_write_stall) && lite_addr_hit && lite_read_bypass_vld; +//address hit but read will stall +assign lite_read_addr_hit_with_stall = lite_read_req && (lite_write_req | lite_write_stall) && lite_addr_hit && lite_read_stall_vld; + +//read bypass or stall +// &CombBeg; @140 +always @( lite_yy_haddr[1:0] + or lite_wbuf_addr[1:0] + or lite_wbuf_size[2:0] + or lite_yy_hsize[2:0]) +begin +casez({lite_wbuf_size[2:0],lite_yy_hsize[2:0],lite_wbuf_addr[1:0],lite_yy_haddr[1:0]}) +//st.b/ld.b +10'b000_000_00_00, +10'b000_000_01_01, +10'b000_000_10_10, +10'b000_000_11_11: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.b/ld.h +10'b000_001_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.b/ld.w +10'b000_010_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.h/ld.b +10'b001_000_0?_0?, +10'b001_000_1?_1?: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.h/ld.h +10'b001_001_0?_0?, +10'b001_001_1?_1?: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +//st.h/ld.w +10'b001_010_??_??: + begin + lite_read_stall_vld = 1'b1; + lite_read_bypass_vld = 1'b0; + end +//st.w/all lds +10'b010_???_??_??: + begin + lite_read_bypass_vld = 1'b1; + lite_read_stall_vld = 1'b0; + end +default: + begin + lite_read_bypass_vld = 1'b0; + lite_read_stall_vld = 1'b0; + end +endcase +// &CombEnd; @195 +end + + + +//memory select +assign lite_mem_cen = ~(lite_read_req | lite_write_req | lite_write_stall); +//memory write enable +// &CombBeg; @202 +always @( lite_wbuf_addr[1:0] + or lite_wbuf_size[2:0] + or pad_biu_bigend_b + or lite_write_en) +begin + case({pad_biu_bigend_b, lite_write_en, lite_wbuf_size[2:0], lite_wbuf_addr[1:0]}) + 7'b0100000: + begin + lite_mem_wen[3:0] = 4'b0111; + end + 7'b0100001: + begin + lite_mem_wen[3:0] = 4'b1011; + end + 7'b0100010: + begin + lite_mem_wen[3:0] = 4'b1101; + end + 7'b0100011: + begin + lite_mem_wen[3:0] = 4'b1110; + end + 7'b0100100: + begin + lite_mem_wen[3:0] = 4'b0011; + end + 7'b0100110: + begin + lite_mem_wen[3:0] = 4'b1100; + end + 7'b0101000: + begin + lite_mem_wen[3:0] = 4'b0000; + end + 7'b1100000: + begin + lite_mem_wen[3:0] = 4'b1110; + end + 7'b1100001: + begin + lite_mem_wen[3:0] = 4'b1101; + end + 7'b1100010: + begin + lite_mem_wen[3:0] = 4'b1011; + end + 7'b1100011: + begin + lite_mem_wen[3:0] = 4'b0111; + end + 7'b1100100: + begin + lite_mem_wen[3:0] = 4'b1100; + end + 7'b1100110: + begin + lite_mem_wen[3:0] = 4'b0011; + end + 7'b1101000: + begin + lite_mem_wen[3:0] = 4'b0000; + end + default: + begin + lite_mem_wen[3:0] = 4'b1111; + end + endcase +// &CombEnd; @265 +end + +assign lite_mem_addr[31:0] = (lite_write_en | lite_read_stall) ? lite_wbuf_addr[31:0] : lite_yy_haddr[31:0]; +assign lite_mem_din[31:0] = (lite_write_stall) ? lite_wbuf_data[31:0] : lite_yy_hwdata[31:0]; +assign mmc_lite_hrdata[31:0] = lite_read_bypass ? lite_bypass_data[31:0] : lite_mem_dout[31:0]; +assign mmc_lite_hready = !lite_read_stall; +assign mmc_lite_hresp[1:0] = 2'b0; + + + +//memory +always @(posedge pll_core_cpuclk) +begin + if(!lite_mem_cen) + addr_holding[IMEM_WIDTH-3:0] <= lite_mem_addr[IMEM_WIDTH-1:2]; +end + +assign ram_clk = pll_core_cpuclk; +assign ram_addr[IMEM_WIDTH-3:0] = lite_mem_cen ? addr_holding[IMEM_WIDTH-3:0] : lite_mem_addr[IMEM_WIDTH-1:2]; +assign ram_wen[0] = !lite_mem_cen && !lite_mem_wen[0]; +assign ram_wen[1] = !lite_mem_cen && !lite_mem_wen[1]; +assign ram_wen[2] = !lite_mem_cen && !lite_mem_wen[2]; +assign ram_wen[3] = !lite_mem_cen && !lite_mem_wen[3]; + +assign ram0_din[7:0] = lite_mem_din[7:0]; +assign ram1_din[7:0] = lite_mem_din[15:8]; +assign ram2_din[7:0] = lite_mem_din[23:16]; +assign ram3_din[7:0] = lite_mem_din[31:24]; +assign lite_mem_dout[31:0] = {ram3_dout[7:0], ram2_dout[7:0], ram1_dout[7:0], ram0_dout[7:0]}; + +soc_fpga_ram #(8, IMEM_WIDTH-2) ram0( + .PortAClk (ram_clk), + .PortAAddr(ram_addr), + .PortADataIn (ram0_din), + .PortAWriteEnable(ram_wen[0]), + .PortADataOut(ram0_dout)); + +soc_fpga_ram #(8, IMEM_WIDTH-2) ram1( + .PortAClk (ram_clk), + .PortAAddr(ram_addr), + .PortADataIn (ram1_din), + .PortAWriteEnable(ram_wen[1]), + .PortADataOut(ram1_dout)); + +soc_fpga_ram #(8, IMEM_WIDTH-2) ram2( + .PortAClk (ram_clk), + .PortAAddr(ram_addr), + .PortADataIn (ram2_din), + .PortAWriteEnable(ram_wen[2]), + .PortADataOut(ram2_dout)); + +soc_fpga_ram #(8, IMEM_WIDTH-2) ram3( + .PortAClk (ram_clk), + .PortAAddr(ram_addr), + .PortADataIn (ram3_din), + .PortAWriteEnable(ram_wen[3]), + .PortADataOut(ram3_dout)); + +// &Force("nonport", "ram_addr"); @324 +// &Force("nonport", "ram0_din"); @325 +// &Force("nonport", "ram1_din"); @326 +// &Force("nonport", "ram2_din"); @327 +// &Force("nonport", "ram3_din"); @328 +// &Force("nonport", "ram0_dout"); @329 +// &Force("nonport", "ram1_dout"); @330 +// &Force("nonport", "ram2_dout"); @331 +// &Force("nonport", "ram3_dout"); @332 +// &Force("nonport", "ram_wen"); @333 +// &Force("nonport", "ram_clk"); @334 +// &ModuleEnd; @335 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/mem/mem_ctrl.v b/XUANTIE-RV_opene906/smart_run/logical/mem/mem_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..3e48c5334b30582eb2d63748fa2b2e2941764d04 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/mem/mem_ctrl.v @@ -0,0 +1,311 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module mem_ctrl( + haddr_s1, + hburst_s1, + hprot_s1, + hrdata_s1, + hready_s1, + hresp_s1, + hsel_s1, + hsize_s1, + htrans_s1, + hwdata_s1, + hwrite_s1, + pad_cpu_rst_b, + pll_core_cpuclk +); + +// &Ports; @25 +input [31:0] haddr_s1; +input [2 :0] hburst_s1; +input [3 :0] hprot_s1; +input hsel_s1; +input [2 :0] hsize_s1; +input [1 :0] htrans_s1; +input [31:0] hwdata_s1; +input hwrite_s1; +input pad_cpu_rst_b; +input pll_core_cpuclk; +output [31:0] hrdata_s1; +output hready_s1; +output [1 :0] hresp_s1; + +// &Wires; @26 +wire ahb_trans_clear; +wire ahb_trans_valid; +wire bypass_if_write_byte; +wire bypass_if_write_hword; +wire bypass_if_write_word; +wire [31:0] haddr; +wire [31:0] haddr_s1; +wire hclk; +wire [31:0] hrdata; +wire [31:0] hrdata_pre; +wire [31:0] hrdata_s1; +wire hready_s1; +wire [1 :0] hresp_s1; +wire hrst_b; +wire hsel; +wire hsel_s1; +wire [2 :0] hsize; +wire [2 :0] hsize_s1; +wire [1 :0] htrans; +wire [1 :0] htrans_s1; +wire [31:0] hwdata; +wire [31:0] hwdata_s1; +wire hwrite; +wire hwrite_s1; +wire pad_cpu_rst_b; +wire pll_core_cpuclk; +wire [14:0] ram0_addr; +wire [7 :0] ram0_din; +wire [7 :0] ram0_dout; +wire [14:0] ram1_addr; +wire [7 :0] ram1_din; +wire [7 :0] ram1_dout; +wire [14:0] ram2_addr; +wire [7 :0] ram2_din; +wire [7 :0] ram2_dout; +wire [14:0] ram3_addr; +wire [7 :0] ram3_din; +wire [7 :0] ram3_dout; +wire [31:0] ram_addr; +wire ram_clk; +wire [3 :0] ram_wen_byte; +wire [3 :0] ram_wen_hword; +wire [3 :0] ram_wen_word; +wire raw_bypass_en; +wire raw_en; +wire raw_no_bypass; +wire rdata_vld; +wire read_en; +wire write_en; + +// &Regs; @27 +reg [31:0] haddr_ff; +reg [31:0] hrdata_raw; +reg hread_ff; +reg hready; +reg [1 :0] hresp; +reg [2 :0] hsize_ff; +reg hwrite_ff; +reg [3 :0] ram_wen; +reg [3 :0] ram_wen_pre; +reg raw_data_vld; + + +// &Force("input", "hburst_s1"); @29 +// &Force("input", "hprot_s1"); @30 +// &Force("bus", "hburst_s1", 2, 0); @31 +// &Force("bus", "hprot_s1", 3, 0); @32 + +parameter MEM_ADDR_WIDTH = 17; + +assign hclk = pll_core_cpuclk; +assign hrst_b = pad_cpu_rst_b; +assign hsel = hsel_s1; +assign htrans[1:0] = htrans_s1[1:0]; +assign hsize[2:0] = hsize_s1[2:0]; +assign haddr[31:0] = haddr_s1[31:0]; +assign hwrite = hwrite_s1; +assign hresp_s1[1:0] = hresp[1:0]; +assign hready_s1 = hready; +assign hwdata[31:0] = hwdata_s1[31:0]; +assign hrdata_s1[31:0] = hrdata[31:0]; + +assign ahb_trans_valid = hsel && hready && + ((htrans[1:0] == 2'b10) || (htrans[1:0] == 2'b11)); + +assign ahb_trans_clear = hready && !hsel; + + +always @(posedge hclk or negedge hrst_b) +begin + if (!hrst_b) + begin + hwrite_ff <= 1'b0; + hread_ff <= 1'b0; + hsize_ff[2:0] <= 3'd0; + haddr_ff[31:0] <= 32'd0; + raw_data_vld <= 1'b0; + end + else if (ahb_trans_valid) + begin + hwrite_ff <= hwrite; + hread_ff <= !hwrite; + hsize_ff[2:0] <= hsize[2:0]; + haddr_ff[31:0] <= haddr[31:0]; + raw_data_vld <= raw_bypass_en; + end + else if (ahb_trans_clear) + begin + hwrite_ff <= 1'b0; + hread_ff <= 1'b0; + hsize_ff[2:0] <= 3'd0; + haddr_ff[31:0] <= 32'd0; + raw_data_vld <= 1'b0; + end +end + +assign write_en = hwrite_ff; +assign read_en = ahb_trans_valid && !hwrite; +assign rdata_vld = hread_ff; +assign raw_en = write_en && read_en; + +// ============================================= +// AHB bus response +// ============================================= +always @(posedge hclk or negedge hrst_b) +begin + if (!hrst_b) + hresp[1:0] <= 2'b00; + else + hresp[1:0] <= 2'b00; +end + +assign raw_no_bypass = raw_en && (!raw_bypass_en); + +always @(posedge hclk or negedge hrst_b) +begin + if (!hrst_b) + hready <= 1'b0; + else if (raw_no_bypass) + hready <= 1'b0; + else + hready <= 1'b1; +end + +assign ram_addr[31:0] = (write_en || !hready) ? haddr_ff[31:0] : haddr[31:0]; +// ============================================= +// data input and output distribution and reform +// ============================================= +assign ram_clk = hclk; +assign ram0_addr[MEM_ADDR_WIDTH-3:0] = ram_addr[MEM_ADDR_WIDTH-1:2]; +assign ram1_addr[MEM_ADDR_WIDTH-3:0] = ram_addr[MEM_ADDR_WIDTH-1:2]; +assign ram2_addr[MEM_ADDR_WIDTH-3:0] = ram_addr[MEM_ADDR_WIDTH-1:2]; +assign ram3_addr[MEM_ADDR_WIDTH-3:0] = ram_addr[MEM_ADDR_WIDTH-1:2]; +assign ram_wen_byte[0] = (haddr[1:0] == 2'h0); +assign ram_wen_byte[1] = (haddr[1:0] == 2'h1); +assign ram_wen_byte[2] = (haddr[1:0] == 2'h2); +assign ram_wen_byte[3] = (haddr[1:0] == 2'h3); +assign ram_wen_hword[0] = (haddr[1] == 1'd0); +assign ram_wen_hword[1] = (haddr[1] == 1'd0); +assign ram_wen_hword[2] = (haddr[1] == 1'd1); +assign ram_wen_hword[3] = (haddr[1] == 1'd1); +assign ram_wen_word[3:0] = 4'hf; + +always @( * ) +begin + case (hsize[2:0]) + 3'b000: // byte + ram_wen_pre[3:0] = ram_wen_byte[3:0]; + 3'b001: // half-word + ram_wen_pre[3:0] = ram_wen_hword[3:0]; + 3'b010: // word + ram_wen_pre[3:0] = ram_wen_word[3:0]; + default: + ram_wen_pre[3:0] = 4'b0; + endcase +end + +always @(posedge hclk or negedge hrst_b) +begin + if (!hrst_b) + ram_wen[3:0] <= 4'b0; + else if (ahb_trans_valid && hwrite) + ram_wen[3:0] <= ram_wen_pre[3:0]; + else + ram_wen[3:0] <= 4'b0; +end + +assign ram0_din[7:0] = hwdata[7:0]; +assign ram1_din[7:0] = hwdata[15:8]; +assign ram2_din[7:0] = hwdata[23:16]; +assign ram3_din[7:0] = hwdata[31:24]; + +assign bypass_if_write_word = (haddr_ff[MEM_ADDR_WIDTH-1:2] == haddr[MEM_ADDR_WIDTH-1:2]) && + (hsize_ff[1:0] == 2'b10); +assign bypass_if_write_hword = (haddr_ff[MEM_ADDR_WIDTH-1:1] == haddr[MEM_ADDR_WIDTH-1:1]) && + (hsize_ff[1:0] == 2'b01) && (!hsize[1]); +assign bypass_if_write_byte = (haddr_ff[MEM_ADDR_WIDTH-1:0] == haddr[MEM_ADDR_WIDTH-1:0]) && + (hsize[1:0] == 2'b00); + +assign raw_bypass_en = raw_en && (bypass_if_write_word || + bypass_if_write_hword || + bypass_if_write_byte); + +assign hrdata_pre[31:0] = rdata_vld ? {ram3_dout[7:0], ram2_dout[7:0], ram1_dout[7:0], ram0_dout[7:0]} : 32'b0; + +always @(posedge hclk or negedge hrst_b) +begin + if (!hrst_b) + hrdata_raw[31:0] <= 32'd0; + else if (raw_bypass_en) + hrdata_raw[31:0] <= hwdata[31:0]; + else + hrdata_raw[31:0] <= hrdata_raw[31:0]; +end + +assign hrdata[31:0] = raw_data_vld ? hrdata_raw[31:0] : hrdata_pre[31:0]; + +soc_fpga_ram #(8, MEM_ADDR_WIDTH-2) ram0( + .PortAClk (ram_clk), + .PortAAddr(ram0_addr), + .PortADataIn (ram0_din), + .PortAWriteEnable(ram_wen[0]), + .PortADataOut(ram0_dout)); + +soc_fpga_ram #(8, MEM_ADDR_WIDTH-2) ram1( + .PortAClk (ram_clk), + .PortAAddr(ram1_addr), + .PortADataIn (ram1_din), + .PortAWriteEnable(ram_wen[1]), + .PortADataOut(ram1_dout)); + +soc_fpga_ram #(8, MEM_ADDR_WIDTH-2) ram2( + .PortAClk (ram_clk), + .PortAAddr(ram2_addr), + .PortADataIn (ram2_din), + .PortAWriteEnable(ram_wen[2]), + .PortADataOut(ram2_dout)); + +soc_fpga_ram #(8, MEM_ADDR_WIDTH-2) ram3( + .PortAClk (ram_clk), + .PortAAddr(ram3_addr), + .PortADataIn (ram3_din), + .PortAWriteEnable(ram_wen[3]), + .PortADataOut(ram3_dout)); + +// &Force("nonport", "ram0_addr"); @212 +// &Force("nonport", "ram1_addr"); @213 +// &Force("nonport", "ram2_addr"); @214 +// &Force("nonport", "ram3_addr"); @215 +// &Force("nonport", "ram0_din"); @216 +// &Force("nonport", "ram1_din"); @217 +// &Force("nonport", "ram2_din"); @218 +// &Force("nonport", "ram3_din"); @219 +// &Force("nonport", "ram0_dout"); @220 +// &Force("nonport", "ram1_dout"); @221 +// &Force("nonport", "ram2_dout"); @222 +// &Force("nonport", "ram3_dout"); @223 +// &Force("nonport", "ram_wen"); @224 +// &Force("nonport", "ram_clk"); @225 + +// &ModuleEnd; @227 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/mem/soc_fpga_ram.v b/XUANTIE-RV_opene906/smart_run/logical/mem/soc_fpga_ram.v new file mode 100644 index 0000000000000000000000000000000000000000..f24ad4480ed8928a86d69d2cef02f3602338a7cc --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/mem/soc_fpga_ram.v @@ -0,0 +1,51 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module soc_fpga_ram( + PortAClk, + PortAAddr, + PortADataIn, + PortAWriteEnable, + + PortADataOut +); + +parameter DATAWIDTH = 2; +parameter ADDRWIDTH = 2; + +input PortAClk; +input [(ADDRWIDTH-1):0] PortAAddr; +input [(DATAWIDTH-1):0] PortADataIn; +input PortAWriteEnable; + +output [(DATAWIDTH-1):0] PortADataOut; + +parameter MEMDEPTH = 2**(ADDRWIDTH); + +reg [(DATAWIDTH-1):0] mem [(MEMDEPTH-1):0]; +reg [(DATAWIDTH-1):0] PortADataOut; + +always @(posedge PortAClk) +begin + if(PortAWriteEnable) + begin + mem[PortAAddr] <= PortADataIn; + end + else + begin + PortADataOut <= mem[PortAAddr]; + end +end + +endmodule diff --git a/XUANTIE-RV_opene906/smart_run/logical/pmu/pmu.v b/XUANTIE-RV_opene906/smart_run/logical/pmu/pmu.v new file mode 100644 index 0000000000000000000000000000000000000000..c727c2b651d912b076d81eab7a9fbe7508ac379a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/pmu/pmu.v @@ -0,0 +1,542 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("environment.h"); @21 +// &Depend("cpu_cfig.h"); @22 + +// &ModuleBeg; @24 +module pmu( + apb_pmu_paddr, + apb_pmu_penable, + apb_pmu_psel, + apb_pmu_pwdata, + apb_pmu_pwrite, + biu_pad_lpmd_b, + corec_pmu_sleep_out, + cpu_clk, + gate_en0, + gate_en1, + had_pad_wakeup_req_b, + i_pad_cpu_jtg_rst_b, + i_pad_jtg_tclk, + intraw_vld, + pad_cpu_rst_b, + pad_had_jtg_tap_en, + pad_had_jtg_tms_i, + pad_had_jtg_trst_b, + pad_had_jtg_trst_b_pre, + pg_reset_b, + pmu_apb_prdata, + pmu_clk, + pmu_corec_isolation, + pmu_corec_sleep_in, + sys_rst +); + +// &Ports; @25 +input [11:0] apb_pmu_paddr; +input apb_pmu_penable; +input apb_pmu_psel; +input [31:0] apb_pmu_pwdata; +input apb_pmu_pwrite; +input [1 :0] biu_pad_lpmd_b; +input corec_pmu_sleep_out; +input cpu_clk; +input had_pad_wakeup_req_b; +input i_pad_cpu_jtg_rst_b; +input i_pad_jtg_tclk; +input intraw_vld; +input pad_cpu_rst_b; +input pad_had_jtg_tap_en; +input pad_had_jtg_tms_i; +input pad_had_jtg_trst_b_pre; +input pmu_clk; +input sys_rst; +output gate_en0; +output gate_en1; +output pad_had_jtg_trst_b; +output pg_reset_b; +output [31:0] pmu_apb_prdata; +output pmu_corec_isolation; +output pmu_corec_sleep_in; + +// &Regs; @26 +reg [31:0] counter; +reg counter_en_ff; +reg [31:0] counter_load; +reg [31:0] ctrl_reg; +reg [2 :0] cur_state; +reg debug_pending; +reg event_ff; +reg event_pending; +reg [2 :0] next_state; +reg [2 :0] pg_next_state; +reg [2 :0] pg_state; +reg [31:0] pmu_apb_prdata; + +// &Wires; @27 +wire [11:0] apb_pmu_paddr; +wire apb_pmu_penable; +wire apb_pmu_psel; +wire [31:0] apb_pmu_pwdata; +wire apb_pmu_pwrite; +wire [1 :0] biu_pad_lpmd_b; +wire corec_pmu_sleep_out; +wire counter_en; +wire cpu_clk; +wire debug_ctl_en; +wire debug_vld; +wire debug_vld_pre; +wire debug_wake_vld; +wire doze_mode; +wire event_ctl_en; +wire event_vld; +wire gate_en0; +wire gate_en1; +wire had_pad_wakeup_req_b; +wire i_pad_cpu_jtg_rst_b; +wire i_pad_jtg_tclk; +wire intraw_vld; +wire load_cnt_en; +wire low_power_dis; +wire low_power_dis_pre; +wire lpmd_en; +wire lpmd_en_ff; +wire pad_cpu_rst_b; +wire pad_had_jtg_tap_en; +wire pad_had_jtg_tms_i; +wire pad_had_jtg_trst_b; +wire pad_had_jtg_trst_b_pre; +wire pad_vic_event_vld; +wire pg_reset_b; +wire pmu_clk; +wire pmu_corec_isolation; +wire pmu_corec_sleep_in; +wire pmu_debug_wakeup; +wire pmu_event_wakeup; +wire pmu_wakeup; +wire pmu_wic_wakeup; +wire stop_mode; +wire sys_rst; +wire wait_mode; +wire wic_ctl_en; + + +parameter IDLE = 3'b000; +parameter WAIT = 3'b001; +parameter DOZE = 3'b010; +parameter STOP = 3'b011; +parameter WAIT_AWAKE = 3'b100; + +parameter PG_IDLE = 3'b000; +parameter PG_RESET_ON = 3'b001; +parameter PG_ISO_ON = 3'b010; +parameter PG_POWER_OFF_REQ = 3'b011; +parameter PG_POWER_OFF = 3'b100; +parameter PG_POWER_ON = 3'b101; +parameter PG_ISO_OFF = 3'b110; +parameter PG_RESET_OFF = 3'b111; + +assign low_power_dis_pre = (biu_pad_lpmd_b[1:0] == 2'b11); + + +assign lpmd_en = (biu_pad_lpmd_b[1:0] != 2'b11) ; + +////////////sync ///////////////////// +// &Instance("sync", "x_cpu2pmu_sync1"); @58 +sync x_cpu2pmu_sync1 ( + .fast_clk (cpu_clk ), + .in (lpmd_en ), + .out (lpmd_en_ff ), + .pad_cpu_rst_b (pad_cpu_rst_b), + .slow_clk (pmu_clk ) +); + +// &Connect( .in ( lpmd_en ), @59 +// .out ( lpmd_en_ff ), @60 +// .fast_clk ( cpu_clk ), @61 +// .slow_clk ( pmu_clk ) @62 +// ); @63 + + + + + +// &Instance("sync", "x_cpu2pmu_sync2"); @69 +sync x_cpu2pmu_sync2 ( + .fast_clk (cpu_clk ), + .in (low_power_dis_pre), + .out (low_power_dis ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .slow_clk (pmu_clk ) +); + +// &Connect( .in ( low_power_dis_pre ), @70 +// .out ( low_power_dis ), @71 +// .fast_clk ( cpu_clk ), @72 +// .slow_clk ( pmu_clk ) @73 +// ); @74 + +//------------------------------------------------ +//WRITE CTRL REG +//------------------------------------------------ + +always @ (posedge pmu_clk or negedge pad_cpu_rst_b) +begin +if (!pad_cpu_rst_b) + begin + ctrl_reg[31:0] <= 32'b0; + end +else if (apb_pmu_psel && apb_pmu_pwrite && apb_pmu_penable) + begin + if (!apb_pmu_paddr[11:0] ) + ctrl_reg[31:0] <= apb_pmu_pwdata[31:0]; + else if (apb_pmu_paddr[11:0] == 12'h4 ) + counter_load[31:0] <= apb_pmu_pwdata[31:0]; + end +end + +//------------------------------------------------ +//READ CTRL REG +//------------------------------------------------ + +// &CombBeg; @99 +always @( apb_pmu_paddr[11:0] + or ctrl_reg[3:0] + or apb_pmu_psel + or apb_pmu_pwrite + or counter[31:0]) +begin +if (apb_pmu_psel && !apb_pmu_pwrite) +begin + if(!apb_pmu_paddr[11:0] ) + pmu_apb_prdata[31:0] = {28'b0,ctrl_reg[3:0]}; + else if (apb_pmu_paddr[11:0] == 12'h4 ) + pmu_apb_prdata[31:0] = counter[31:0]; + else + pmu_apb_prdata[31:0] = 32'b0; +end +// &CombEnd; @109 +end + +assign wic_ctl_en = ctrl_reg[0]; +assign event_ctl_en = ctrl_reg[1]; +assign debug_ctl_en = ctrl_reg[2]; +assign counter_en = ctrl_reg[3]; + +//event counter +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + counter_en_ff <=0; + end + else + begin + counter_en_ff <=counter_en ; + end +end + +assign load_cnt_en= (counter_en && !counter_en_ff) + || !(|counter[31:0]); + +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + counter[31:0] <= 32'h0; + end + else if (load_cnt_en) + begin + counter[31:0] <= counter_load[31:0]; + end + else if (counter_en) + counter[31:0] <= counter[31:0] -1'b1; + else + counter[31:0] <= counter[31:0]; +end + +assign pad_vic_event_vld = (counter[31:0] == 32'b0) && counter_en; + + + +assign pmu_wic_wakeup = intraw_vld && wic_ctl_en && lpmd_en_ff ; + +// event_wakeup + +assign event_vld = pad_vic_event_vld && !event_ff && lpmd_en_ff ; + +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + event_ff <= 1'b0; + else + event_ff <= pad_vic_event_vld; +end + +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + event_pending <= 1'b0; + else if (event_vld) + event_pending <= 1'b1; + else if (low_power_dis) + event_pending <= 1'b0; +end + +assign pmu_event_wakeup = event_pending && event_ctl_en ; + +//debug wake up + +// &Instance("tap2_sm", "x_tap2_sm"); @180 +tap2_sm x_tap2_sm ( + .debug_wake_vld (debug_wake_vld ), + .pad_had_jtg_tap_en (pad_had_jtg_tap_en ), + .tclk (i_pad_jtg_tclk ), + .tms_i (pad_had_jtg_tms_i ), + .trst_b (i_pad_cpu_jtg_rst_b) +); + +// &Connect(.tclk (i_pad_jtg_tclk ), @181 +// // .trst_b (i_pad_jtg_trst_b ), @182 +// .trst_b (i_pad_cpu_jtg_rst_b ), @183 +// .tms_i (pad_had_jtg_tms_i ) @184 +// ); @185 + +assign debug_vld_pre = (debug_wake_vld || !had_pad_wakeup_req_b) && lpmd_en_ff; + +// &Instance("px_had_sync", "x_jtag2pmu_sync"); @193 +px_had_sync x_jtag2pmu_sync ( + .clk1 (i_pad_jtg_tclk ), + .clk2 (pmu_clk ), + .rst1_b (pad_had_jtg_trst_b_pre), + .rst2_b (pad_cpu_rst_b ), + .sync_in (debug_vld_pre ), + .sync_out (debug_vld ) +); + +// &Connect(.clk1 (i_pad_jtg_tclk ), @194 +// .clk2 (pmu_clk ), @195 +// .rst1_b (pad_had_jtg_trst_b_pre ), @196 +// .rst2_b (pad_cpu_rst_b ), @197 +// .sync_in (debug_vld_pre ), @198 +// .sync_out (debug_vld ) @199 +// ); @200 + + + +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + debug_pending <= 1'b0; + else if (debug_vld) + debug_pending <= 1'b1; + else if (low_power_dis) + debug_pending <= 1'b0; +end + + +//assign pad_had_jdb_req_b = !debug_pending; +assign pmu_debug_wakeup = debug_pending && debug_ctl_en ; + +///// +assign pmu_wakeup = pmu_event_wakeup || pmu_wic_wakeup || pmu_debug_wakeup ; +//----------------------------------------- +// PMU FSM +//----------------------------------------- +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + cur_state[2:0] <= IDLE; + else + cur_state[2:0] <= next_state[2:0]; +end + + +//assign doze_mode = ( biu_pad_lpmd_b[1:0] == 2'b10); +//assign wait_mode = ( biu_pad_lpmd_b[1:0] == 2'b01); +//assign stop_mode = ( biu_pad_lpmd_b[1:0] == 2'b00); +assign doze_mode = 1'b0; +assign wait_mode = 1'b0; +assign stop_mode = 1'b0; + + + +// &CombBeg; @246 +always @( cur_state + or pmu_wakeup + or pg_state[2:0] + or biu_pad_lpmd_b[1:0] + or doze_mode + or stop_mode + or wait_mode) +begin +case(cur_state) +IDLE: +begin + if(doze_mode ) + begin + next_state = DOZE; + end + else if(wait_mode ) + begin + next_state = WAIT; + end + else if(stop_mode ) + begin + next_state = STOP; + end + else + begin + next_state = IDLE; + end +end + +DOZE: +begin + if(pmu_wakeup) + begin + next_state = WAIT_AWAKE; + end + else + begin + next_state = DOZE; + end +end + +WAIT: +begin + if(pmu_wakeup) + begin + next_state = WAIT_AWAKE; + end + else + begin + next_state = WAIT; + end +end + +STOP://////// more states more pg crtl signal +begin + if(pg_state[2:0]==3'b111) + begin + next_state = WAIT_AWAKE; + end + else + begin + next_state = STOP; + end +end + +WAIT_AWAKE: +begin + if(biu_pad_lpmd_b[1:0] == 2'b11) + begin + next_state = IDLE; + end + else + begin + next_state = WAIT_AWAKE; + end +end + +endcase +// &CombEnd; @317 +end + + + +assign gate_en0 = (cur_state[2:0] == IDLE) || (cur_state[2:0] == WAIT_AWAKE); +assign gate_en1 = (cur_state[2:0] == WAIT) || (cur_state[2:0] == IDLE) + || (cur_state[2:0] == WAIT_AWAKE); + +//---------------------------------------- +// Power Gating FSM +//----------------------------------------- + +always @(posedge pmu_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + pg_state[2:0] <= PG_IDLE; + else + pg_state[2:0] <= pg_next_state[2:0]; +end + +// &CombBeg; @337 +always @( pmu_wakeup + or pg_state[2:0] + or corec_pmu_sleep_out + or cur_state[2:0]) +begin +case(pg_state[2:0]) +PG_IDLE: +begin + if(cur_state[2:0] == STOP) + pg_next_state = PG_RESET_ON; + else + pg_next_state = PG_IDLE; +end +PG_RESET_ON: + pg_next_state = PG_ISO_ON; +PG_ISO_ON: + pg_next_state = PG_POWER_OFF_REQ; +PG_POWER_OFF_REQ: +begin + if(corec_pmu_sleep_out) + pg_next_state = PG_POWER_OFF; + else + pg_next_state = PG_POWER_OFF_REQ; +end +PG_POWER_OFF: +begin + if(pmu_wakeup) + pg_next_state = PG_POWER_ON; + else + pg_next_state = PG_POWER_OFF; +end +PG_POWER_ON: + pg_next_state = PG_ISO_OFF; +PG_ISO_OFF: + pg_next_state = PG_RESET_OFF; +PG_RESET_OFF: + pg_next_state = IDLE; +endcase +// &CombEnd @371 +end + + + +assign pmu_corec_sleep_in = pg_state[2:0] == PG_POWER_OFF_REQ + || pg_state[2:0] == PG_POWER_OFF; + +assign pmu_corec_isolation = pg_state[2:0] == PG_ISO_ON + || pg_state[2:0] == PG_POWER_OFF_REQ + || pg_state[2:0] == PG_POWER_OFF + || pg_state[2:0] == PG_POWER_ON + || pg_state[2:0] == PG_ISO_OFF; + +assign pg_reset_b = pg_state[2:0] == PG_IDLE + && pad_cpu_rst_b & sys_rst; + +assign pad_had_jtg_trst_b = pg_state[2:0] == PG_IDLE + && pad_had_jtg_trst_b_pre; + + + +// &ModuleEnd; @392 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_comp_hit.v b/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_comp_hit.v new file mode 100644 index 0000000000000000000000000000000000000000..cafaa4a59138e22508f6df963b91eb5cc034fc5b --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_comp_hit.v @@ -0,0 +1,77 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module smpu_comp_hit( + biu_pad_haddr, + biu_pad_hprot, + smpu_entry, + smpu_entry0, + smpu_hit, + smpu_hsec +); + +// &Ports; @20 +input [31:0] biu_pad_haddr; +input [3 :0] biu_pad_hprot; +input [31:0] smpu_entry; +input [31:0] smpu_entry0; +output smpu_hit; +output smpu_hsec; + +// &Regs; @21 +reg [22:0] addr_mask; + +// &Wires; @22 +wire addr_match; +wire [31:0] biu_pad_haddr; +wire [3 :0] biu_pad_hprot; +wire [31:0] smpu_entry; +wire [31:0] smpu_entry0; +wire smpu_hit; +wire smpu_hsec; + + + +// &Force("bus", "biu_pad_haddr", 31, 0); @25 +// &Force("bus", "biu_pad_hprot", 3, 0); @26 + +assign smpu_hit =1'b0; +// &Force("nonport", "addr_match"); @32 + +assign addr_match = {(smpu_entry[0] & !biu_pad_hprot[2]), + (addr_mask[22:0] & biu_pad_haddr[31:9])} + == { 1'b1, smpu_entry[31:9]}; + +assign smpu_hsec = {(smpu_entry0[0] & biu_pad_hprot[2]), + (addr_mask[22:0] & biu_pad_haddr[31:9])} + == { 1'b1, smpu_entry0[31:9]}; + +//Generate the address mask for the addr +// &CombBeg; @44 +always @( smpu_entry[4:1]) +begin + case(smpu_entry[4:1]) + 4'b0111 : addr_mask[22:0] = 23'h7f_ffff; + 4'b1000 : addr_mask[22:0] = 23'h7f_fffe; + 4'b1001 : addr_mask[22:0] = 23'h7f_fffc; + default : addr_mask[22:0] = 23'h00_0000; + endcase +// &CombEnd; @51 +end + + +// &ModuleEnd; @54 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_top.v b/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_top.v new file mode 100644 index 0000000000000000000000000000000000000000..37e3ca999f1ff0d312c2c721c65a75396e7f6789 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/smpu/smpu_top.v @@ -0,0 +1,208 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &Depend("cpu_cfig.h") @18 +// &ModuleBeg; @19 +module smpu_top( + biu_pad_haddr, + biu_pad_hprot, + paddr, + pclk, + penable, + prdata, + presetn, + psel, + pwdata, + pwrite, + smpu_deny +); + +// &Ports; @20 +input [31:0] biu_pad_haddr; +input [3 :0] biu_pad_hprot; +input [3 :2] paddr; +input pclk; +input penable; +input presetn; +input psel; +input [31:0] pwdata; +input pwrite; +output [31:0] prdata; +output smpu_deny; + +// &Regs; @21 +reg [31:0] prdata; +reg [31:0] smpu_entry0; +reg [31:0] smpu_entry1; +reg [31:0] smpu_entry2; + +// &Wires; @22 +wire [31:0] biu_pad_haddr; +wire [3 :0] biu_pad_hprot; +wire hsec_0; +wire hsec_1; +wire hsec_2; +wire pad_biu_hsec_pre; +wire [3 :2] paddr; +wire pclk; +wire penable; +wire presetn; +wire psel; +wire [31:0] pwdata; +wire pwrite; +wire smpu_deny; +wire smpu_hit0; +wire smpu_hit1; +wire smpu_hit2; + + + +// &Force("bus","biu_pad_haddr",31,0); @25 + +//========================================================== +// APB PWDATA +//========================================================== + +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + smpu_entry0 <= 32'b0; + smpu_entry1 <= 32'b0; + smpu_entry2 <= 32'b0; + end + else + begin + if(psel && pwrite && penable) + begin + case(paddr[3:2]) + 2'b00: + begin + smpu_entry0[31:0] <= pwdata[31:0]; + end + 2'b01: + begin + smpu_entry1[31:0] <= pwdata[31:0]; + end + 2'b10: + begin + smpu_entry2[31:0] <= pwdata[31:0]; + end + endcase + end + end +end + +//========================================================== +// APB PRDATA +//========================================================== +always @(posedge pclk) +begin + if(psel && !pwrite && !penable) + begin + case(paddr[3:2]) + 2'b00: + begin + prdata[31:0] <= smpu_entry0[31:0]; + end + 2'b01: + begin + prdata[31:0] <= smpu_entry1[31:0]; + end + 2'b10: + begin + prdata[31:0] <= smpu_entry2[31:0]; + end + default: + begin + prdata[31:0] <= 32'bx; + end + endcase + end +end + + + + +//&Instance("gated_clk_cell", "x_smpu_gated_clk"); +// //&Connect(.clk_in(forever_cpuclk), @93 +// // .global_en(cp0_yy_clk_en), @94 +// // .module_en(mpu_module_en), @95 +// // .local_en(1'b0), @96 +// // .external_en(1'b0), @97 +// // .clk_out(cpuclk)); @98 + +// &Force("output", "smpu_deny") @100 +assign smpu_deny = smpu_hit0 || smpu_hit1 || smpu_hit2; + +// &Instance("smpu_comp_hit", "x_smpu_comp_hit_0"); @103 +smpu_comp_hit x_smpu_comp_hit_0 ( + .biu_pad_haddr (biu_pad_haddr), + .biu_pad_hprot (biu_pad_hprot), + .smpu_entry (smpu_entry0 ), + .smpu_entry0 (smpu_entry0 ), + .smpu_hit (smpu_hit0 ), + .smpu_hsec (hsec_0 ) +); + +// &Connect(.smpu_hit (smpu_hit0 ), @104 +// .smpu_entry (smpu_entry0 ), @105 +// .smpu_hsec (hsec_0 ) @106 +// @107 +// ); @108 + +// &Instance("smpu_comp_hit", "x_smpu_comp_hit_1"); @110 +smpu_comp_hit x_smpu_comp_hit_1 ( + .biu_pad_haddr (biu_pad_haddr), + .biu_pad_hprot (biu_pad_hprot), + .smpu_entry (smpu_entry1 ), + .smpu_entry0 (smpu_entry0 ), + .smpu_hit (smpu_hit1 ), + .smpu_hsec (hsec_1 ) +); + +// &Connect(.smpu_hit (smpu_hit1 ), @111 +// .smpu_entry (smpu_entry1 ), @112 +// .smpu_hsec (hsec_1 ) @113 +// ); @114 + +// &Instance("smpu_comp_hit", "x_smpu_comp_hit_2"); @116 +smpu_comp_hit x_smpu_comp_hit_2 ( + .biu_pad_haddr (biu_pad_haddr), + .biu_pad_hprot (biu_pad_hprot), + .smpu_entry (smpu_entry2 ), + .smpu_entry0 (smpu_entry0 ), + .smpu_hit (smpu_hit2 ), + .smpu_hsec (hsec_2 ) +); + +// &Connect(.smpu_hit (smpu_hit2 ), @117 +// .smpu_entry (smpu_entry2 ), @118 +// .smpu_hsec (hsec_2 ) @119 +// ); @120 + + +//biu hsec +assign pad_biu_hsec_pre = hsec_0 || hsec_1 || hsec_2; + + +// &Force("nonport", "pad_biu_hsec_pre"); @140 + +// &Force("nonport","pad_biu_hsec"); @145 + +// &ModuleEnd; @148 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/cpu_sub_system_ahb.v b/XUANTIE-RV_opene906/smart_run/logical/system/cpu_sub_system_ahb.v new file mode 100644 index 0000000000000000000000000000000000000000..45836facc8979d337638e7b2c1383cde9386cce0 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/cpu_sub_system_ahb.v @@ -0,0 +1,741 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module cpu_sub_system_ahb( + biu_pad_haddr, + biu_pad_hburst, + biu_pad_hprot, + biu_pad_hsize, + biu_pad_htrans, + biu_pad_hwdata, + biu_pad_hwrite, + biu_pad_lpmd_b, + clk_en, + corec_pmu_sleep_out, + cpu_clk, + had_pad_jtg_tdo, + nmi_wake_int_lower, + pad_biu_bigend_b, + pad_biu_hrdata, + pad_biu_hready, + pad_biu_hresp, + pad_cpu_rst_b, + pad_had_jtg_tclk, + pad_had_jtg_tdi, + pad_had_jtg_tms, + pad_had_jtg_trst_b, + pad_vic_int_vld, + pad_yy_icg_scan_en, + pad_yy_scan_enable, + pad_yy_scan_mode, + pad_yy_scan_rst_b, + pg_reset_b, + pmu_corec_isolation, + pmu_corec_sleep_in, + sys_rst +); + +// &Ports; @23 +input clk_en; +input cpu_clk; +input [1 :0] nmi_wake_int_lower; +input pad_biu_bigend_b; +input [31 :0] pad_biu_hrdata; +input pad_biu_hready; +input [1 :0] pad_biu_hresp; +input pad_cpu_rst_b; +input pad_had_jtg_tclk; +input pad_had_jtg_tdi; +input pad_had_jtg_tms; +input pad_had_jtg_trst_b; +input [31 :0] pad_vic_int_vld; +input pad_yy_icg_scan_en; +input pad_yy_scan_enable; +input pad_yy_scan_mode; +input pad_yy_scan_rst_b; +input pg_reset_b; +input pmu_corec_isolation; +input pmu_corec_sleep_in; +output [31 :0] biu_pad_haddr; +output [2 :0] biu_pad_hburst; +output [3 :0] biu_pad_hprot; +output [2 :0] biu_pad_hsize; +output [1 :0] biu_pad_htrans; +output [31 :0] biu_pad_hwdata; +output biu_pad_hwrite; +output [1 :0] biu_pad_lpmd_b; +output corec_pmu_sleep_out; +output had_pad_jtg_tdo; +output sys_rst; + +// &Regs; @24 +reg [1 :0] biu_addr; +reg [1 :0] biu_size; +reg cpu_clk_div2; +reg [1 :0] dahbl_addr; +reg [1 :0] dahbl_size; +reg [1 :0] iahbl_addr; +reg [1 :0] iahbl_size; +reg [31 :0] pad_biu_hrdata_mux; +reg [63 :0] pad_cpu_sys_cnt; +reg [31 :0] pad_dahbl_hrdata_mux; +reg [31 :0] pad_iahbl_hrdata_mux; + +// &Wires; @25 +wire [31 :0] biu_pad_haddr; +wire [2 :0] biu_pad_hburst; +wire biu_pad_hlock; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire [31 :0] biu_pad_hwdata; +wire biu_pad_hwrite; +wire [1 :0] biu_pad_lpmd_b; +wire biu_pad_retire; +wire [31 :0] biu_pad_retire_pc; +wire [31 :0] biu_pad_wb1_gpr_data; +wire biu_pad_wb1_gpr_en; +wire [5 :0] biu_pad_wb1_gpr_index; +wire [31 :0] biu_pad_wb_gpr_data; +wire biu_pad_wb_gpr_en; +wire [5 :0] biu_pad_wb_gpr_index; +wire clk_en; +wire [31 :0] cp0_pad_mcause; +wire [31 :0] cp0_pad_mintstatus; +wire [31 :0] cp0_pad_mstatus; +wire cpu_clk; +wire cpu_pad_dfs_ack; +wire cpu_pad_halted; +wire cpu_pad_lockup; +wire [1 :0] cpu_pad_soft_rst; +wire cpu_rst; +wire [31 :0] dahbl_pad_haddr; +wire [2 :0] dahbl_pad_hburst; +wire dahbl_pad_hlock; +wire [3 :0] dahbl_pad_hprot; +wire [2 :0] dahbl_pad_hsize; +wire [1 :0] dahbl_pad_htrans; +wire [31 :0] dahbl_pad_hwdata; +wire dahbl_pad_hwrite; +wire had_pad_jtg_tdo; +wire [31 :0] iahbl_pad_haddr; +wire [2 :0] iahbl_pad_hburst; +wire iahbl_pad_hlock; +wire [3 :0] iahbl_pad_hprot; +wire [2 :0] iahbl_pad_hsize; +wire [1 :0] iahbl_pad_htrans; +wire [31 :0] iahbl_pad_hwdata; +wire iahbl_pad_hwrite; +wire nmi_req; +wire [1 :0] nmi_wake_int_lower; +wire pad_biu_bigend_b; +wire [31 :0] pad_biu_hrdata; +wire pad_biu_hready; +wire [1 :0] pad_biu_hresp; +wire pad_biu_hresp_0; +wire [ 128 - 1 :0] pad_clic_int_vld; +wire pad_cpu_dfs_req; +wire pad_cpu_ext_int_b; +wire pad_cpu_rst_b; +wire [31 :0] pad_dahbl_hrdata; +wire pad_dahbl_hready; +wire [1 :0] pad_dahbl_hresp; +wire pad_dahbl_hresp_0; +wire pad_had_jtg_tclk; +wire pad_had_jtg_tdi; +wire pad_had_jtg_tms; +wire pad_had_jtg_trst_b; +wire [31 :0] pad_iahbl_hrdata; +wire pad_iahbl_hready; +wire [1 :0] pad_iahbl_hresp; +wire pad_iahbl_hresp_0; +wire [31 :0] pad_vic_int_vld; +wire pad_yy_icg_scan_en; +wire pad_yy_scan_enable; +wire pad_yy_scan_mode; +wire pad_yy_scan_rst_b; +wire pg_reset_b; +wire rtu_pad_inst_split; +wire [31 :0] rtu_pad_wb2_data; +wire [5 :0] rtu_pad_wb2_preg; +wire rtu_pad_wb2_vld; +// wire [4 :0] rtu_pad_wb_freg; +// wire [63 :0] rtu_pad_wb_freg_data; +// wire rtu_pad_wb_freg_vld; + +wire [4 :0] rtu_pad_wb_freg; +wire rtu_pad_wb_freg_vld; + + +wire [31:0] rtu_pad_wb_freg_data; + + +wire sys_rst; +wire tdt_dm_pad_hartreset_n; +wire tdt_dm_pad_ndmreset_n; +wire [11 :0] tdt_dmi_paddr; +wire tdt_dmi_penable; +wire [31 :0] tdt_dmi_prdata; +wire tdt_dmi_pready; +wire tdt_dmi_psel; +wire tdt_dmi_pslverr; +wire [31 :0] tdt_dmi_pwdata; +wire tdt_dmi_pwrite; +wire tdt_dtm_pad_tdo_en; +wire tdt_dtm_pad_tms_o; +wire tdt_dtm_pad_tms_oe; +wire wakeup_req; + + + + + +// &Force("nonport","cp0_pad_mintstatus"); @35 +// &Force("nonport","cp0_pad_mstatus"); @36 +// &Instance("E902_181204", "x_e902"); @37 +// &Connect(.cp0_pad_psr (biu_pad_psr ), @39 +// .iu_pad_gpr_index (biu_pad_wb_gpr_index ), @40 +// .iu_pad_gpr_we (biu_pad_wb_gpr_en ), @41 +// .iu_pad_inst_retire (biu_pad_retire ), @42 +// .iu_pad_retire_pc (biu_pad_retire_pc ), @43 +// .pad_biu_hrdata_parity (1'b0 ), @44 +// .pad_dahbl_hrdata_parity (1'b0 ), @45 +// .pad_iahbl_hrdata_parity (1'b0 ), @46 +// .pad_sysio_bigend_b (pad_biu_bigend_b ), @47 +// .pad_sysio_clkratio (pad_biu_clkratio ), @48 +// .pad_sysio_gsb (pad_biu_gsb ), @49 +// .pad_clic_int_cfg (pad_clic_int_cfg ), @50 +// .pad_clic_int_vld (pad_clic_int_vld ), @51 +// .pad_ctim_refclk (1'b0 ), @52 +// .pad_ctim_calib (26'b0 ), @53 +// .pad_bmu_dahbl_base (12'h200 ), @54 +// .pad_bmu_dahbl_mask (12'hfff ), @55 +// .pad_bmu_iahbl_base (12'h000 ), @56 +// .pad_bmu_iahbl_mask (12'he00 ), @57 +// .pad_biu_hresp (pad_biu_hresp_0 ), @58 +// .pad_dahbl_hresp (pad_dahbl_hresp_0 ), @59 +// .pad_dahbl_hsec (1'b0 ), @60 +// .pad_iahbl_hresp (pad_iahbl_hresp[0] ), @61 +// .pad_iahbl_hsec (1'b0 ), @62 +// .ctim_pad_int_vld (ctim_int_vld ), @63 +// .sysio_pad_dbg_b (biu_pad_dbg_b ), @64 +// .sysio_pad_ipend_b (biu_pad_ipend_b ), @65 +// .sysio_pad_lpmd_b (biu_pad_lpmd_b ), @66 +// .sysio_pad_wakeup_b (biu_pad_wakeup_b ), @67 +// .iu_pad_gpr_data (biu_pad_wb_gpr_data ), @68 +// .pll_core_cpuclk (cpu_clk ), @69 +// .pad_cpu_rst_b (pg_reset_b ), @70 +// .pad_cpu_dfs_req (1'b0 ), @71 +// .pll_core_cpuclk_nogated (cpu_clk ), @72 +// .pad_sysio_endian_v2 (1'b0 ), @73 +// .pad_had_rst_b (pad_had_jtg_trst_b ), @74 +// .pad_had_jtg_trst_b (pad_had_jtg_trst_b ), @75 +// .pad_cpu_gpr_rst_b (pg_reset_b ), @76 +// .pad_sysio_clk_unlock (1'b0 ), @77 +// .pad_cpu_secu_dbg_en (1'b1 ) @78 +// @79 +// ); @80 +// &Force("inout","i_pad_jtg_tms"); @85 +// &Force("output","pad_had_jtg_tms_i"); @88 +// &Force("nonport", "pad_had_jtg_tdi"); @89 +// &Force("nonport", "had_pad_jtg_tdo"); @90 +// &Force("nonport","pad_cpu_secu_dbg_en"); @95 +// &Force("nonport","pad_cpu_secu_dbg_en"); @100 +// &Force("bus","pad_biu_hresp","1","0"); @110 +// &Force("nonport","sysio_pad_srst"); @111 +// &Force("nonport","iu_pad_inst_split"); @112 +// &Force("nonport","dahbl_pad_hburst"); @113 +// &Force("nonport","dahbl_pad_hprot"); @114 +// &Force("nonport","iahbl_pad_hburst"); @115 +// &Force("nonport","iahbl_pad_hprot"); @116 +// &Force("nonport","had_pad_jdb_pm"); @117 +// &Instance("iahb_mem_ctrl", "x_iahb_mem_ctrl"); @121 +// &Connect(.lite_yy_haddr (iahbl_pad_haddr ), @122 +// .lite_yy_hsize (iahbl_pad_hsize ), @123 +// .lite_yy_htrans (iahbl_pad_htrans ), @124 +// .lite_yy_hwdata (iahbl_pad_hwdata ), @125 +// .lite_yy_hwrite (iahbl_pad_hwrite ), @126 +// .mmc_lite_hrdata (pad_iahbl_hrdata ), @127 +// .mmc_lite_hready (pad_iahbl_hready ), @128 +// .mmc_lite_hresp (pad_iahbl_hresp ), @129 +// .lite_mmc_hsel (iahbl_pad_htrans[1] ), @130 +// .pll_core_cpuclk (cpu_clk ) @131 +// ); @132 + +//*********************** E906 ************************* +//&Instance("S902_1808102", "x_s902"); + +// assign pad_clic_int_vld = {{128 - 32{1'b0}},pad_vic_int_vld[31:0]}; + +assign pad_clic_int_vld[ 31 : 0] = pad_vic_int_vld[ 31 : 0]; + +assign pad_clic_int_vld[128 - 1 : 32] = 'h0; + +assign pad_cpu_ext_int_b =1'b1; + +// //&Force("input","pad_vic_int_cfg"); @145 +// &Force("nonport","cp0_pad_mintstatus"); @146 +// &Force("nonport","cp0_pad_mstatus"); @147 +// &Instance("E906_TOP", "x_e906"); @148 +openE906 x_e906_top ( + .biu_pad_haddr (biu_pad_haddr ), + .biu_pad_hburst (biu_pad_hburst ), + .biu_pad_hlock (biu_pad_hlock ), + .biu_pad_hprot (biu_pad_hprot ), + .biu_pad_hsize (biu_pad_hsize ), + .biu_pad_htrans (biu_pad_htrans ), + .biu_pad_hwdata (biu_pad_hwdata ), + .biu_pad_hwrite (biu_pad_hwrite ), + .clk_en (clk_en ), + .cp0_pad_mcause (cp0_pad_mcause ), + .cp0_pad_mintstatus (cp0_pad_mintstatus ), + .cp0_pad_mstatus (cp0_pad_mstatus ), + .cpu_pad_dfs_ack (cpu_pad_dfs_ack ), + .cpu_pad_halted (cpu_pad_halted ), + .cpu_pad_lockup (cpu_pad_lockup ), + .cpu_pad_soft_rst (cpu_pad_soft_rst ), + .dahbl_pad_haddr (dahbl_pad_haddr ), + .dahbl_pad_hburst (dahbl_pad_hburst ), + .dahbl_pad_hlock (dahbl_pad_hlock ), + .dahbl_pad_hprot (dahbl_pad_hprot ), + .dahbl_pad_hsize (dahbl_pad_hsize ), + .dahbl_pad_htrans (dahbl_pad_htrans ), + .dahbl_pad_hwdata (dahbl_pad_hwdata ), + .dahbl_pad_hwrite (dahbl_pad_hwrite ), + .iahbl_pad_haddr (iahbl_pad_haddr ), + .iahbl_pad_hburst (iahbl_pad_hburst ), + .iahbl_pad_hlock (iahbl_pad_hlock ), + .iahbl_pad_hprot (iahbl_pad_hprot ), + .iahbl_pad_hsize (iahbl_pad_hsize ), + .iahbl_pad_htrans (iahbl_pad_htrans ), + .iahbl_pad_hwdata (iahbl_pad_hwdata ), + .iahbl_pad_hwrite (iahbl_pad_hwrite ), + .pad_biu_hrdata (pad_biu_hrdata_mux ), + .pad_biu_hready (pad_biu_hready ), + .pad_biu_hresp (pad_biu_hresp_0 ), + .pad_bmu_dahbl_base (12'h200 ), + .pad_bmu_dahbl_mask (12'hfff ), + .pad_bmu_iahbl_base (12'h000 ), + .pad_bmu_iahbl_mask (12'he00 ), + .pad_clic_int_vld (pad_clic_int_vld ), + .pad_cpu_dfs_req (pad_cpu_dfs_req ), + .pad_cpu_ext_int_b (pad_cpu_ext_int_b ), + .pad_cpu_nmi (nmi_req ), + .pad_cpu_rst_addr (32'h0000_0000 ), + .pad_cpu_rst_b (cpu_rst ), + .pad_cpu_sys_cnt (pad_cpu_sys_cnt ), + .pad_cpu_sysmap_addr0 (20'h20000 ), + .pad_cpu_sysmap_addr0_attr (3'b011 ), + .pad_cpu_sysmap_addr1 (20'h30000 ), + .pad_cpu_sysmap_addr1_attr (3'b011 ), + .pad_cpu_sysmap_addr2 (20'h40000 ), + .pad_cpu_sysmap_addr2_attr (3'b000 ), + .pad_cpu_sysmap_addr3 (20'h50000 ), + .pad_cpu_sysmap_addr3_attr (3'b100 ), + .pad_cpu_sysmap_addr4 (20'h60000 ), + .pad_cpu_sysmap_addr4_attr (3'b000 ), + .pad_cpu_sysmap_addr5 (20'h70000 ), + .pad_cpu_sysmap_addr5_attr (3'b100 ), + .pad_cpu_sysmap_addr6 (20'he0000 ), + .pad_cpu_sysmap_addr6_attr (3'b000 ), + .pad_cpu_sysmap_addr7 (20'hfffff ), + .pad_cpu_sysmap_addr7_attr (3'b100 ), + .pad_cpu_tcip_base (32'he000_0000 ), + .pad_cpu_wakeup_event (wakeup_req ), + .pad_dahbl_hrdata (pad_dahbl_hrdata_mux ), + .pad_dahbl_hready (pad_dahbl_hready ), + .pad_dahbl_hresp (pad_dahbl_hresp_0 ), + .pad_iahbl_hrdata (pad_iahbl_hrdata_mux ), + .pad_iahbl_hready (pad_iahbl_hready ), + .pad_iahbl_hresp (pad_iahbl_hresp_0 ), + .pad_tdt_dm_core_unavail (1'b0 ), + .pad_yy_icg_scan_en (pad_yy_icg_scan_en ), + .pad_yy_scan_enable (pad_yy_scan_enable ), + .pad_yy_scan_mode (pad_yy_scan_mode ), + .pad_yy_scan_rst_b (pad_yy_scan_rst_b ), + .pll_core_cpuclk (cpu_clk ), + .rtu_pad_inst_retire (biu_pad_retire ), + .rtu_pad_inst_split (rtu_pad_inst_split ), + .rtu_pad_retire_pc (biu_pad_retire_pc ), + .rtu_pad_wb0_data (biu_pad_wb_gpr_data ), + .rtu_pad_wb0_preg (biu_pad_wb_gpr_index ), + .rtu_pad_wb0_vld (biu_pad_wb_gpr_en ), + .rtu_pad_wb1_data (biu_pad_wb1_gpr_data ), + .rtu_pad_wb1_preg (biu_pad_wb1_gpr_index ), + .rtu_pad_wb1_vld (biu_pad_wb1_gpr_en ), + .rtu_pad_wb2_data (rtu_pad_wb2_data ), + .rtu_pad_wb2_preg (rtu_pad_wb2_preg ), + .rtu_pad_wb2_vld (rtu_pad_wb2_vld ), + + .rtu_pad_wb_freg (rtu_pad_wb_freg ), +.rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), +.rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ), + + + // .rtu_pad_wb_freg (rtu_pad_wb_freg ), + // .rtu_pad_wb_freg_data (rtu_pad_wb_freg_data ), + // .rtu_pad_wb_freg_vld (rtu_pad_wb_freg_vld ), + .sys_apb_clk (cpu_clk_div2 ), + .sys_apb_rst_b (pad_cpu_rst_b ), + .sysio_pad_lpmd_b (biu_pad_lpmd_b ), + .tdt_dm_pad_hartreset_n (tdt_dm_pad_hartreset_n ), + .tdt_dm_pad_ndmreset_n (tdt_dm_pad_ndmreset_n ), + + + + + + .pad_yy_dft_clk_rst_b (1'b1 ), + + + .tdt_dmi_paddr (tdt_dmi_paddr ), + .tdt_dmi_penable (tdt_dmi_penable ), + .tdt_dmi_prdata (tdt_dmi_prdata ), + .tdt_dmi_pready (tdt_dmi_pready ), + .tdt_dmi_psel (tdt_dmi_psel ), + .tdt_dmi_pslverr (tdt_dmi_pslverr ), + .tdt_dmi_pwdata (tdt_dmi_pwdata ), + .tdt_dmi_pwrite (tdt_dmi_pwrite ) +); + +// &Connect(.rtu_pad_wb0_preg (biu_pad_wb_gpr_index ), @149 +// .rtu_pad_wb0_vld (biu_pad_wb_gpr_en ), @150 +// .rtu_pad_wb0_data (biu_pad_wb_gpr_data ), @151 +// .rtu_pad_wb1_preg (biu_pad_wb1_gpr_index ), @152 +// .rtu_pad_wb1_vld (biu_pad_wb1_gpr_en ), @153 +// .rtu_pad_wb1_data (biu_pad_wb1_gpr_data ), @154 +// .rtu_pad_inst_retire (biu_pad_retire ), @155 +// .rtu_pad_retire_pc (biu_pad_retire_pc ), @156 +// .pad_clic_int_vld (pad_clic_int_vld ), @157 +// .pad_cpu_sys_cnt (pad_cpu_sys_cnt ), @158 +// .pad_bmu_dahbl_base (12'h200 ), @159 +// .pad_bmu_dahbl_mask (12'hfff ), @160 +// .pad_bmu_iahbl_base (12'h000 ), @161 +// .pad_bmu_iahbl_mask (12'he00 ), @162 +// .pad_biu_hresp (pad_biu_hresp_0 ), @163 +// .pad_biu_hrdata (pad_biu_hrdata_mux ), @164 +// .pad_iahbl_hrdata (pad_iahbl_hrdata_mux ), @165 +// .pad_dahbl_hrdata (pad_dahbl_hrdata_mux ), @166 +// .pad_dahbl_hresp (pad_dahbl_hresp_0 ), @167 +// .pad_iahbl_hresp (pad_iahbl_hresp_0 ), @168 +// .sysio_pad_lpmd_b (biu_pad_lpmd_b ), @169 +// .pll_core_cpuclk (cpu_clk ), @170 +// .pad_cpu_rst_b (cpu_rst ), @171 +// .ilite_clk_en (clk_en ), @172 +// .dlite_clk_en (clk_en ), @173 +// .pad_cpu_dfs_req (pad_cpu_dfs_req ), @174 +// //.pad_had_rst_b (had_rst ), @175 +// .pad_had_jtg_trst_b (pad_had_jtg_trst_b ), @176 +// .cpu_pad_lockup (cpu_pad_lockup ), @177 +// .cpu_pad_soft_rst (cpu_pad_soft_rst ), @178 +// .pad_cpu_nmi (nmi_req ), @179 +// .pad_cpu_wakeup_event (wakeup_req ), @180 +// .pad_cpu_rst_addr (32'h0 ), @181 +// .pad_cpu_sysmap_addr0 (20'h20000), @182 +// .pad_cpu_sysmap_addr0_attr (3'b011), @183 +// .pad_cpu_sysmap_addr1 (20'h30000), @184 +// .pad_cpu_sysmap_addr1_attr (3'b011), @185 +// .pad_cpu_sysmap_addr2 (20'h40000), @186 +// .pad_cpu_sysmap_addr2_attr (3'b000), @187 +// .pad_cpu_sysmap_addr3 (20'h50000), @188 +// .pad_cpu_sysmap_addr3_attr (3'b100), @189 +// .pad_cpu_sysmap_addr4 (20'h60000), @190 +// .pad_cpu_sysmap_addr4_attr (3'b000), @191 +// .pad_cpu_sysmap_addr5 (20'h70000), @192 +// .pad_cpu_sysmap_addr5_attr (3'b100), @193 +// .pad_cpu_sysmap_addr6 (20'he0000), @194 +// .pad_cpu_sysmap_addr6_attr (3'b000), @195 +// .pad_cpu_sysmap_addr7 (20'hfffff), @196 +// .pad_cpu_sysmap_addr7_attr (3'b100), @197 +// .pad_cpu_tcip_base (32'he000_0000), @198 +// .pad_tdt_dm_core_unavail (1'b0), @199 +// .sys_apb_clk (cpu_clk_div2), @200 +// .sys_apb_rst_b (pad_cpu_rst_b), @201 +// ); @202 + +always@(posedge cpu_clk or negedge pad_cpu_rst_b) begin + if(!pad_cpu_rst_b) + cpu_clk_div2 <= 1'b0; + else + cpu_clk_div2 <= ~cpu_clk_div2; +end + +// &Force("nonport","cpu_pad_soft_rst"); @211 + +// &Instance("tdt_dmi_top_FPGA","x_tdt_dmi_top"); @213 +tdt_dmi_top x_tdt_dmi_top ( +`ifdef SELECT_2_WIRE_JTAG + .pad_tdt_dtm_jtag2_sel (1'b1 ), +`else + .pad_tdt_dtm_jtag2_sel (1'b0 ), +`endif + .pad_tdt_dtm_tap_en (1'b1 ), + .pad_tdt_dtm_tclk (pad_had_jtg_tclk ), + .pad_tdt_dtm_tdi (pad_had_jtg_tdi ), + .pad_tdt_dtm_tms_i (pad_had_jtg_tms ), + .pad_tdt_dtm_trst_b (pad_had_jtg_trst_b ), + .pad_tdt_icg_scan_en (1'b0 ), + .pad_yy_scan_mode (1'b0 ), + .pad_yy_scan_rst_b (1'b1 ), + .sys_apb_clk (cpu_clk_div2 ), + .sys_apb_rst_b (pad_cpu_rst_b ), + .tdt_dmi_paddr (tdt_dmi_paddr ), + .tdt_dmi_penable (tdt_dmi_penable ), + .tdt_dmi_prdata (tdt_dmi_prdata ), + .tdt_dmi_pready (tdt_dmi_pready ), + .tdt_dmi_psel (tdt_dmi_psel ), + .tdt_dmi_pslverr (tdt_dmi_pslverr ), + .tdt_dmi_pwdata (tdt_dmi_pwdata ), + .tdt_dmi_pwrite (tdt_dmi_pwrite ), + .tdt_dtm_pad_tdo (had_pad_jtg_tdo ), + .tdt_dtm_pad_tdo_en (tdt_dtm_pad_tdo_en ), + .tdt_dtm_pad_tms_o (tdt_dtm_pad_tms_o ), + .tdt_dtm_pad_tms_oe (tdt_dtm_pad_tms_oe ) +); + +// &Connect(.pad_tdt_icg_scan_en (1'b0), @214 +// .sys_apb_clk (cpu_clk_div2), @215 +// .sys_apb_rst_b (pad_cpu_rst_b), @216 +// .pad_tdt_dtm_jtag2_sel (1'b0), @217 +// .pad_tdt_dtm_tap_en (1'b1), @218 +// .tdt_dtm_pad_tdo (had_pad_jtg_tdo), @219 +// .pad_tdt_dtm_tclk (pad_had_jtg_tclk), @220 +// .pad_tdt_dtm_tdi (pad_had_jtg_tdi), @221 +// .pad_tdt_dtm_trst_b (pad_had_jtg_trst_b), @222 +// .pad_tdt_dtm_tms_i (pad_had_jtg_tms) @223 +// ); @224 + +// &Force("nonport","tdt_dtm_pad_tdo_en"); @226 +// &Force("nonport","tdt_dtm_pad_tms_o"); @227 +// &Force("nonport","tdt_dtm_pad_tms_oe"); @228 + +// &Force("nonport","rtu_pad_wb2_data"); @230 +// &Force("nonport","rtu_pad_wb2_preg"); @231 +// &Force("nonport","rtu_pad_wb2_vld"); @232 +// &Force("nonport","cpu_pad_lockup"); @233 +// &Force("nonport","cpu_pad_halted"); @234 +assign pad_cpu_dfs_req = 0; +assign nmi_req = nmi_wake_int_lower[0]; +assign wakeup_req = nmi_wake_int_lower[1]; +//assign clk_en = 1; +// sys cnt +always@(posedge cpu_clk or negedge pg_reset_b) +begin + if (!pg_reset_b) + pad_cpu_sys_cnt[63:0] <= 64'b0; + else + pad_cpu_sys_cnt[63:0] <= pad_cpu_sys_cnt[63:0] + 1'b1; +end + +assign cpu_rst = pg_reset_b & tdt_dm_pad_hartreset_n; +assign sys_rst = tdt_dm_pad_ndmreset_n; +// &Force("output","sys_rst"); @250 + + +// &Force("inout","i_pad_jtg_tms"); @255 +// &Force("output","pad_had_jtg_tms_i"); @258 +// &Force("nonport", "pad_had_jtg_tdi"); @259 +// &Force("nonport", "had_pad_jtg_tdo"); @260 + +// &Force("nonport","pad_cpu_secu_dbg_en"); @265 + +// &Force("nonport","pad_cpu_secu_dbg_en"); @270 + +assign pad_biu_hresp_0 = pad_biu_hresp[0]; +always@(posedge cpu_clk or negedge pg_reset_b) +begin + if(!pg_reset_b) begin + biu_size[1:0] <= 2'h2; + biu_addr[1:0] <= 2'b0; + end + else if((biu_pad_htrans == 2) && (!biu_pad_hwrite) && pad_biu_hready) begin + biu_size[1:0] <= biu_pad_hsize[1:0]; + biu_addr[1:0] <= biu_pad_haddr[1:0]; + end +end +always@(*) +begin + case({biu_size[1:0],biu_addr[1:0]}) + 4'b0000:pad_biu_hrdata_mux[31:0] = {24'h0,pad_biu_hrdata[7:0]}; + 4'b0001:pad_biu_hrdata_mux[31:0] = {16'h0,pad_biu_hrdata[15:8],8'h0}; + 4'b0010:pad_biu_hrdata_mux[31:0] = {8'h0,pad_biu_hrdata[23:16],16'h0}; + 4'b0011:pad_biu_hrdata_mux[31:0] = {pad_biu_hrdata[31:24],24'h0}; + 4'b0100: pad_biu_hrdata_mux[31:0] = {16'h0,pad_biu_hrdata[15:0]}; + 4'b0110: pad_biu_hrdata_mux[31:0] = {pad_biu_hrdata[31:16],16'h0}; + 4'b1000: pad_biu_hrdata_mux[31:0] = pad_biu_hrdata[31:0]; + default: pad_biu_hrdata_mux[31:0] = 32'h0; + endcase +end +// &Force("output","biu_pad_hsize"); @302 +// &Force("output","biu_pad_htrans"); @303 +// &Force("output","biu_pad_hwrite"); @304 +// &Force("output","biu_pad_haddr"); @305 +// &Instance("dahb_mem_ctrl", "x_dahb_mem_ctrl"); @307 +dahb_mem_ctrl x_dahb_mem_ctrl ( + .lite_mmc_hsel (dahbl_pad_htrans[1]), + .lite_yy_haddr (dahbl_pad_haddr ), + .lite_yy_hsize (dahbl_pad_hsize ), + .lite_yy_htrans (dahbl_pad_htrans ), + .lite_yy_hwdata (dahbl_pad_hwdata ), + .lite_yy_hwrite (dahbl_pad_hwrite ), + .mmc_lite_hrdata (pad_dahbl_hrdata ), + .mmc_lite_hready (pad_dahbl_hready ), + .mmc_lite_hresp (pad_dahbl_hresp ), + .pad_biu_bigend_b (pad_biu_bigend_b ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pll_core_cpuclk (cpu_clk ) +); + +// &Connect(.lite_yy_haddr (dahbl_pad_haddr ), @308 +// .lite_yy_hsize (dahbl_pad_hsize ), @309 +// .lite_yy_htrans (dahbl_pad_htrans ), @310 +// .lite_yy_hwdata (dahbl_pad_hwdata ), @311 +// .lite_yy_hwrite (dahbl_pad_hwrite ), @312 +// .mmc_lite_hrdata (pad_dahbl_hrdata ), @313 +// .mmc_lite_hready (pad_dahbl_hready ), @314 +// .mmc_lite_hresp (pad_dahbl_hresp ), @315 +// .lite_mmc_hsel (dahbl_pad_htrans[1] ), @316 +// .pll_core_cpuclk (cpu_clk ) @317 +// @318 +// ); @319 + +assign pad_dahbl_hresp_0 = pad_dahbl_hresp[0]; +// &Force("nonport","dahbl_pad_hburst"); @322 +// &Force("nonport","dahbl_pad_hprot"); @323 +always@(posedge cpu_clk or negedge pg_reset_b) +begin + if(!pg_reset_b) begin + dahbl_size[1:0] <= 2'h2; + dahbl_addr[1:0] <= 2'b0; + end + else if((dahbl_pad_htrans == 2) && (!dahbl_pad_hwrite) && pad_dahbl_hready) begin + dahbl_size[1:0] <= dahbl_pad_hsize[1:0]; + dahbl_addr[1:0] <= dahbl_pad_haddr[1:0]; + end +end +always@(*) +begin + case({dahbl_size[1:0],dahbl_addr[1:0]}) + 4'b0000:pad_dahbl_hrdata_mux[31:0] = {24'h0,pad_dahbl_hrdata[7:0]}; + 4'b0001:pad_dahbl_hrdata_mux[31:0] = {16'h0,pad_dahbl_hrdata[15:8],8'h0}; + 4'b0010:pad_dahbl_hrdata_mux[31:0] = {8'h0,pad_dahbl_hrdata[23:16],16'h0}; + 4'b0011:pad_dahbl_hrdata_mux[31:0] = {pad_dahbl_hrdata[31:24],24'h0}; + 4'b0100: pad_dahbl_hrdata_mux[31:0] = {16'h0,pad_dahbl_hrdata[15:0]}; + 4'b0110: pad_dahbl_hrdata_mux[31:0] = {pad_dahbl_hrdata[31:16],16'h0}; + 4'b1000: pad_dahbl_hrdata_mux[31:0] = pad_dahbl_hrdata[31:0]; + default: pad_dahbl_hrdata_mux[31:0] = 32'h0; + endcase +end + +// &Force("bus","pad_biu_hresp","1","0"); @350 +// &Force("nonport","sysio_pad_srst"); @351 +// &Force("nonport","iu_pad_inst_split"); @352 +// &Force("nonport","dahbl_pad_hburst"); @353 +// &Force("nonport","dahbl_pad_hprot"); @354 +// &Force("nonport","iahbl_pad_hburst"); @355 +// &Force("nonport","iahbl_pad_hprot"); @356 +// &Force("nonport","had_pad_jdb_pm"); @357 +// &Force("nonport","cpu_pad_dfs_ack"); @358 +// &Force("nonport","ifu_pad_sw_word"); @359 +// &Force("nonport","rtu_pad_inst_split"); @360 +//TODO +// &Force("nonport","biu_pad_hlock"); @363 +// &Force("nonport","dahbl_pad_hlock"); @364 +// &Force("nonport","iahbl_pad_hlock"); @365 + +// IAHB Lite Memory +// &Instance("iahb_mem_ctrl", "x_iahb_mem_ctrl"); @369 +iahb_mem_ctrl x_iahb_mem_ctrl ( + .lite_mmc_hsel (iahbl_pad_htrans[1]), + .lite_yy_haddr (iahbl_pad_haddr ), + .lite_yy_hsize (iahbl_pad_hsize ), + .lite_yy_htrans (iahbl_pad_htrans ), + .lite_yy_hwdata (iahbl_pad_hwdata ), + .lite_yy_hwrite (iahbl_pad_hwrite ), + .mmc_lite_hrdata (pad_iahbl_hrdata ), + .mmc_lite_hready (pad_iahbl_hready ), + .mmc_lite_hresp (pad_iahbl_hresp ), + .pad_biu_bigend_b (pad_biu_bigend_b ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pll_core_cpuclk (cpu_clk ) +); + +// &Connect(.lite_yy_haddr (iahbl_pad_haddr ), @370 +// .lite_yy_hsize (iahbl_pad_hsize ), @371 +// .lite_yy_htrans (iahbl_pad_htrans ), @372 +// .lite_yy_hwdata (iahbl_pad_hwdata ), @373 +// .lite_yy_hwrite (iahbl_pad_hwrite ), @374 +// .mmc_lite_hrdata (pad_iahbl_hrdata ), @375 +// .mmc_lite_hready (pad_iahbl_hready ), @376 +// .mmc_lite_hresp (pad_iahbl_hresp ), @377 +// .lite_mmc_hsel (iahbl_pad_htrans[1] ), @378 +// .pll_core_cpuclk (cpu_clk ) @379 +// ); @380 + +assign pad_iahbl_hresp_0 = pad_iahbl_hresp[0]; +always@(posedge cpu_clk or negedge pg_reset_b) +begin + if(!pg_reset_b) begin + iahbl_size[1:0] <= 2'h2; + iahbl_addr[1:0] <= 2'b0; + end + else if((iahbl_pad_htrans == 2) && (!iahbl_pad_hwrite) && pad_iahbl_hready) begin + iahbl_size[1:0] <= iahbl_pad_hsize[1:0]; + iahbl_addr[1:0] <= iahbl_pad_haddr[1:0]; + end +end +always@(*) +begin + case({iahbl_size[1:0],iahbl_addr[1:0]}) + 4'b0000:pad_iahbl_hrdata_mux[31:0] = {24'h0,pad_iahbl_hrdata[7:0]}; + 4'b0001:pad_iahbl_hrdata_mux[31:0] = {16'h0,pad_iahbl_hrdata[15:8],8'h0}; + 4'b0010:pad_iahbl_hrdata_mux[31:0] = {8'h0,pad_iahbl_hrdata[23:16],16'h0}; + 4'b0011:pad_iahbl_hrdata_mux[31:0] = {pad_iahbl_hrdata[31:24],24'h0}; + 4'b0100: pad_iahbl_hrdata_mux[31:0] = {16'h0,pad_iahbl_hrdata[15:0]}; + 4'b0110: pad_iahbl_hrdata_mux[31:0] = {pad_iahbl_hrdata[31:16],16'h0}; + 4'b1000: pad_iahbl_hrdata_mux[31:0] = pad_iahbl_hrdata[31:0]; + default: pad_iahbl_hrdata_mux[31:0] = 32'h0; + endcase +end + +//**************************************************** + + + + + +// &Force("input", "pmu_corec_isolation"); @416 +// &Force("input", "pmu_corec_sleep_in"); @417 +// &Force("output", "corec_pmu_sleep_out"); @418 + +// &Force("nonport","pad_had_jtag2_sel"); @420 +// &Force("nonport","sysio_pad_srst"); @421 +// &Force("nonport","biu_pad_retire"); @422 +// &Force("nonport","biu_pad_retire_pc"); @423 +// &Force("nonport","biu_pad_wb_gpr_data"); @424 +// &Force("nonport","biu_pad_wb_gpr_en"); @425 +// &Force("nonport","biu_pad_wb_gpr_index"); @426 +// &Force("nonport","biu_pad_wb1_gpr_data"); @427 +// &Force("nonport","biu_pad_wb1_gpr_en"); @428 +// &Force("nonport","biu_pad_wb1_gpr_index"); @429 +// &Force("nonport","cp0_pad_mcause"); @430 +// &Force("nonport","rtu_pad_wb_freg"); @431 +// &Force("nonport","rtu_pad_wb_freg_vld"); @432 +// &Force("nonport","rtu_pad_wb_freg_data"); @433 + + +// &ModuleEnd; @436 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/err_gen.v b/XUANTIE-RV_opene906/smart_run/logical/system/err_gen.v new file mode 100644 index 0000000000000000000000000000000000000000..8860d59de63a60d953c614a73e31b99061f72453 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/err_gen.v @@ -0,0 +1,101 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module err_gen( + haddr_s3, + hburst_s3, + hmastlock, + hprot_s3, + hrdata_s3, + hready_s3, + hresp_s3, + hsel_s3, + hsize_s3, + htrans_s3, + hwdata_s3, + hwrite_s3, + pad_cpu_rst_b, + pll_core_cpuclk +); + +// &Ports; @23 +input [31:0] haddr_s3; +input [2 :0] hburst_s3; +input hmastlock; +input [3 :0] hprot_s3; +input hsel_s3; +input [2 :0] hsize_s3; +input [1 :0] htrans_s3; +input [31:0] hwdata_s3; +input hwrite_s3; +input pad_cpu_rst_b; +input pll_core_cpuclk; +output [31:0] hrdata_s3; +output hready_s3; +output [1 :0] hresp_s3; + +// &Regs; @24 +reg hready_s3; + +// &Wires; @25 +wire [31:0] hrdata_s3; +wire [1 :0] hresp_s3; +wire hsel_s3; +wire pad_cpu_rst_b; +wire pll_core_cpuclk; + +// //&Force("input","pll_core_cpuclk"); @26 +// //&Force("input","pad_cpu_rst_b"); @27 +// &Force("input","hsel_s3"); @28 +// &Force("input","haddr_s3"); @29 +// &Force("bus", "haddr_s3", 31,0); @30 +// &Force("input","hburst_s3"); @31 +// &Force("bus", "hburst_s3", 2,0); @32 +// &Force("input","hmastlock"); @33 +// &Force("input","hprot_s3"); @34 +// &Force("bus", "hprot_s3", 3,0); @35 +// &Force("input","hsize_s3"); @36 +// &Force("bus", "hsize_s3", 2,0); @37 +// &Force("input","htrans_s3"); @38 +// &Force("bus", "htrans_s3", 1,0); @39 +// &Force("input","hwdata_s3"); @40 +// &Force("input","hwrite_s3"); @41 +// &Force("input","hsel_s3"); @42 +// &Force("output","hready_s3"); @43 +//assign hready_s3 = 1'b1; +assign hresp_s3[1:0] = 2'b01 ; + +always @(posedge pll_core_cpuclk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + begin + hready_s3 <= 1'b0; + end + else if(hsel_s3) + begin + hready_s3 <= 1'b0; + end + else + begin + hready_s3 <= 1'b1; + end +end + +// &Force("bus", "hwdata_s3", 31,0); @63 +assign hrdata_s3[31:0] = 32'b0; + +// &ModuleEnd; @66 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/fpga_clk_gen.v b/XUANTIE-RV_opene906/smart_run/logical/system/fpga_clk_gen.v new file mode 100644 index 0000000000000000000000000000000000000000..c192344290ff781d3da47f188912108d6b20e1cb --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/fpga_clk_gen.v @@ -0,0 +1,103 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @19 +module fpga_clk_gen( + clk_en, + clkrst_b, + cpu_clk, + gate_en0, + gate_en1, + pad_clk, + penable, + per_clk, + pmu_clk, + prdata, + psel, + pwdata, + pwrite, + wic_clk +); + +// &Ports; @20 +input clkrst_b; +input gate_en0; +input gate_en1; +input pad_clk; +input penable; +input psel; +input [2 :0] pwdata; +input pwrite; +output clk_en; +output cpu_clk; +output per_clk; +output pmu_clk; +output [31:0] prdata; +output wic_clk; + +// &Regs; @21 +reg [2 :0] input_clkratio; +reg [31:0] prdata; + +// &Wires; @22 +wire clk_en; +wire clkrst_b; +wire cpu_clk; +wire pad_clk; +wire penable; +wire per_clk; +wire pmu_clk; +wire psel; +wire [2 :0] pwdata; +wire pwrite; +wire wic_clk; + + +always@(posedge per_clk or negedge clkrst_b) +begin + if (!clkrst_b) + input_clkratio[2:0] <= 3'b0; + else if(psel && pwrite && penable) + input_clkratio[2:0] <= pwdata[2:0]; +end + +// &CombBeg; @32 +always @( psel + or pwrite) +begin +if(psel && !pwrite) +begin + prdata[31:0] <= 32'b0; +end +// &CombEnd; @37 +end + +assign cpu_clk = pad_clk; +assign wic_clk = pad_clk; +assign per_clk = pad_clk; +assign pmu_clk = pad_clk; + +assign clk_en = 1'b1; +// &Force("output","per_clk"); @45 + + +// &Force("input", "gate_en0"); @48 +// &Force("input", "gate_en1"); @49 +// &Force("nonport", "input_clkratio"); @50 + +// &ModuleEnd; @52 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/px_had_sync.v b/XUANTIE-RV_opene906/smart_run/logical/system/px_had_sync.v new file mode 100644 index 0000000000000000000000000000000000000000..5892eaf41f2b2a9d47af2e185967c8d6c4942dae --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/px_had_sync.v @@ -0,0 +1,91 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +module px_had_sync( + clk1, + clk2, + rst1_b, + rst2_b, + sync_in, + sync_out +); + +// &Ports; @22 +input clk1; +input clk2; +input rst1_b; +input rst2_b; +input sync_in; +output sync_out; + +// &Regs; @23 +reg sync_ff1_clk1; +reg sync_ff2_clk1; +reg sync_ff3_clk1; +reg sync_ff_clk2; + +// &Wires; @24 +wire clk1; +wire clk2; +wire rst1_b; +wire rst2_b; +wire sync_in; +wire sync_out; + + + +//============================================================================== +// sync logic from clk2 to clk1 +// step 1. flop once in clk2 domain +// step 2. flop twice in clk1 domain +// result: a pulse signal in clk1 domain +// constraint: slow clock --> fast clock +//============================================================================== + +always @(posedge clk2 or negedge rst2_b) +begin + if (!rst2_b) + sync_ff_clk2 <= 1'b0; + else + sync_ff_clk2 <= sync_in; +end + +always @(posedge clk1 or negedge rst1_b) +begin + if (!rst1_b) begin + sync_ff1_clk1 <= 1'b0; + sync_ff2_clk1 <= 1'b0; + end + else begin + sync_ff1_clk1 <= sync_ff_clk2; + sync_ff2_clk1 <= sync_ff1_clk1; + end +end + +// generates a pulse signal in clk1 domain +always @(posedge clk1 or negedge rst1_b) +begin + if (!rst1_b) + sync_ff3_clk1 <= 1'b0; + else + sync_ff3_clk1 <= sync_ff2_clk1; +end + +assign sync_out = !sync_ff3_clk1 && sync_ff2_clk1; + +// &ModuleEnd; @66 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/soc.v b/XUANTIE-RV_opene906/smart_run/logical/system/soc.v new file mode 100644 index 0000000000000000000000000000000000000000..bdf7bea29f8b502936a82266d006c9ad040fb3d7 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/soc.v @@ -0,0 +1,431 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @24 +module soc( + b_pad_gpio_porta, + i_pad_clk, + i_pad_jtg_nrst_b, + i_pad_jtg_tclk, + i_pad_jtg_tdi, + i_pad_jtg_tms, + i_pad_jtg_trst_b, + i_pad_rst_b, + i_pad_uart0_sin, + o_pad_jtg_tdo, + o_pad_uart0_sout +); + +// &Ports("compare", "../src_rtl/soc_top_golden_port.v"); @25 +input i_pad_clk; +input i_pad_jtg_nrst_b; +input i_pad_jtg_tclk; +input i_pad_jtg_tdi; +input i_pad_jtg_tms; +input i_pad_jtg_trst_b; +input i_pad_rst_b; +input i_pad_uart0_sin; +output o_pad_jtg_tdo; +output o_pad_uart0_sout; +inout [7 :0] b_pad_gpio_porta; + +// &Regs; @26 + +// &Wires; @27 +wire [7 :0] b_pad_gpio_porta; +wire [31:0] biu_pad_haddr; +wire [2 :0] biu_pad_hburst; +wire [3 :0] biu_pad_hprot; +wire [2 :0] biu_pad_hsize; +wire [1 :0] biu_pad_htrans; +wire [31:0] biu_pad_hwdata; +wire biu_pad_hwrite; +wire [1 :0] biu_pad_lpmd_b; +wire clk_en; +wire corec_pmu_sleep_out; +wire cpu_clk; +wire fifo_biu_hready; +wire [31:0] fifo_pad_haddr; +wire [2 :0] fifo_pad_hburst; +wire [3 :0] fifo_pad_hprot; +wire [2 :0] fifo_pad_hsize; +wire [1 :0] fifo_pad_htrans; +wire fifo_pad_hwrite; +wire had_pad_jtg_tdo; +wire [31:0] haddr_s1; +wire [31:0] haddr_s2; +wire [31:0] haddr_s3; +wire [2 :0] hburst_s1; +wire [2 :0] hburst_s3; +wire hmastlock; +wire [3 :0] hprot_s1; +wire [3 :0] hprot_s3; +wire [31:0] hrdata_s1; +wire [31:0] hrdata_s2; +wire [31:0] hrdata_s3; +wire hready_s1; +wire hready_s2; +wire hready_s3; +wire [1 :0] hresp_s1; +wire [1 :0] hresp_s2; +wire [1 :0] hresp_s3; +wire hsel_s1; +wire hsel_s2; +wire hsel_s3; +wire [2 :0] hsize_s1; +wire [2 :0] hsize_s3; +wire [1 :0] htrans_s1; +wire [1 :0] htrans_s3; +wire [31:0] hwdata_s1; +wire [31:0] hwdata_s2; +wire [31:0] hwdata_s3; +wire hwrite_s1; +wire hwrite_s2; +wire hwrite_s3; +wire i_pad_clk; +wire i_pad_cpu_jtg_rst_b; +wire i_pad_jtg_nrst_b; +wire i_pad_jtg_tclk; +wire i_pad_jtg_tdi; +wire i_pad_jtg_tms; +wire i_pad_jtg_trst_b; +wire i_pad_rst_b; +wire i_pad_uart0_sin; +wire [1 :0] nmi_wake_int_lower; +wire o_pad_jtg_tdo; +wire o_pad_uart0_sout; +wire [31:0] pad_biu_hrdata; +wire pad_biu_hready; +wire [1 :0] pad_biu_hresp; +wire pad_cpu_rst_b; +wire pad_had_jtg_tclk; +wire pad_had_jtg_tdi; +wire pad_had_jtg_tms; +wire pad_had_jtg_trst_b; +wire pad_had_jtg_trst_b_pre; +wire [31:0] pad_vic_int_vld; +wire per_clk; +wire pg_reset_b; +wire pmu_corec_isolation; +wire pmu_corec_sleep_in; +wire smpu_deny; +wire sys_rst; + + +//***********************Instance cpu_sub_system_ahb**************************** +// &Instance("cpu_sub_system_ahb", "x_cpu_sub_system_ahb"); @31 +// &Connect( @32 +// .clk_en (clk_en ) @33 +// ); @34 +// Support AHB_LITE +// &Instance("cpu_sub_system_ahb", "x_cpu_sub_system_ahb"); @38 +cpu_sub_system_ahb x_cpu_sub_system_ahb ( + .biu_pad_haddr (biu_pad_haddr ), + .biu_pad_hburst (biu_pad_hburst ), + .biu_pad_hprot (biu_pad_hprot ), + .biu_pad_hsize (biu_pad_hsize ), + .biu_pad_htrans (biu_pad_htrans ), + .biu_pad_hwdata (biu_pad_hwdata ), + .biu_pad_hwrite (biu_pad_hwrite ), + .biu_pad_lpmd_b (biu_pad_lpmd_b ), + .clk_en (clk_en ), + .corec_pmu_sleep_out (corec_pmu_sleep_out ), + .cpu_clk (cpu_clk ), + .had_pad_jtg_tdo (had_pad_jtg_tdo ), + .nmi_wake_int_lower (nmi_wake_int_lower ), + .pad_biu_bigend_b (1'b1 ), + .pad_biu_hrdata (pad_biu_hrdata ), + .pad_biu_hready (fifo_biu_hready ), + .pad_biu_hresp (pad_biu_hresp ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_had_jtg_tclk (pad_had_jtg_tclk ), + .pad_had_jtg_tdi (pad_had_jtg_tdi ), + .pad_had_jtg_tms (pad_had_jtg_tms ), + .pad_had_jtg_trst_b (pad_had_jtg_trst_b ), + .pad_vic_int_vld (pad_vic_int_vld ), + .pad_yy_icg_scan_en (1'b0 ), + .pad_yy_scan_enable (1'b0 ), + .pad_yy_scan_mode (1'b0 ), + .pad_yy_scan_rst_b (1'b1 ), + .pg_reset_b (pg_reset_b ), + .pmu_corec_isolation (pmu_corec_isolation ), + .pmu_corec_sleep_in (pmu_corec_sleep_in ), + .sys_rst (sys_rst ) +); + +// &Connect(.clk_en (clk_en ), @40 +// .pad_yy_gate_clk_en_b (1'b0 ), @41 +// .pad_yy_bist_tst_en (1'b0 ), @42 +// .pad_yy_scan_enable (1'b0 ), @43 +// .pad_yy_scan_mode (1'b0 ), @44 +// .pad_yy_icg_scan_en (1'b0 ), @45 +// .pad_yy_scan_rst_b (1'b1 ), @46 +// .pad_yy_dft_clk_rst_b (1'b1 ), @47 +// .pad_biu_bigend_b (1'b1 ), @48 +// .pad_biu_int_b (1'b1 ), @49 +// .pad_biu_fint_b (1'b1 ), @50 +// .pad_biu_fintraw_b (1'b1 ), @51 +// .pad_biu_avec_b (1'b0 ), @52 +// .pad_biu_vec_b (8'b0 ), @53 +// .pad_biu_gsb (32'b0 ), @54 +// //add for debug @55 +// .pad_biu_dbgrq_b (1'b1 ), @56 +// .pad_had_jtg_tap_en (1'b1 ), @57 +// .pad_biu_clkratio (3'b0 ), @58 +// .pad_biu_hready (fifo_biu_hready ) @59 +// ); @60 + +assign i_pad_cpu_jtg_rst_b = i_pad_rst_b & i_pad_jtg_trst_b; + +//assign pad_cpu_rst_b = i_pad_rst_b; +assign pad_cpu_rst_b = i_pad_jtg_nrst_b; +//assign pll_core_cpuclk = cpu_clk; +assign pad_had_jtg_tclk = i_pad_jtg_tclk; +//assign pad_had_jtg_trst_b_pre = i_pad_jtg_trst_b; +assign pad_had_jtg_trst_b_pre = i_pad_cpu_jtg_rst_b; +assign o_pad_jtg_tdo = had_pad_jtg_tdo; +assign pad_had_jtg_tdi = i_pad_jtg_tdi; +assign pad_had_jtg_tms = i_pad_jtg_tms; +// //&Force("inout","i_pad_jtg_tms"); @79 +// //&Force("nonport","pad_had_jtg_tms"); @82 +// &Force("nonport","had_pad_jdb_ack_b"); @84 +//***********************Instance ahb delay simulator *********************** +// &Instance("ahb_fifo", "x_ahb_fifo"); @86 +ahb_fifo x_ahb_fifo ( + .biu_pad_haddr (biu_pad_haddr ), + .biu_pad_hburst (biu_pad_hburst[1:0]), + .biu_pad_hprot (biu_pad_hprot ), + .biu_pad_hsize (biu_pad_hsize ), + .biu_pad_htrans (biu_pad_htrans ), + .biu_pad_hwrite (biu_pad_hwrite ), + .counter_num0 (32'h1 ), + .cpu_clk (per_clk ), + .cpu_rst_b (pg_reset_b ), + .fifo_biu_hready (fifo_biu_hready), + .fifo_pad_haddr (fifo_pad_haddr ), + .fifo_pad_hburst (fifo_pad_hburst[1:0]), + .fifo_pad_hprot (fifo_pad_hprot ), + .fifo_pad_hsize (fifo_pad_hsize ), + .fifo_pad_htrans (fifo_pad_htrans), + .fifo_pad_hwrite (fifo_pad_hwrite), + .pad_biu_hready (pad_biu_hready ) +); + +// &Connect( @87 +// .cpu_clk (per_clk ), @88 +// .cpu_rst_b (pg_reset_b ), @89 +// .counter_num0 (32'h1 ) @90 +// ); @91 + +//***********************Instance ahb bus arbiter**************************** +// &Instance("ahb", "x_ahb"); @94 +ahb x_ahb ( + .biu_pad_haddr (fifo_pad_haddr ), + .biu_pad_hburst (fifo_pad_hburst), + .biu_pad_hprot (fifo_pad_hprot ), + .biu_pad_hsize (fifo_pad_hsize ), + .biu_pad_htrans (fifo_pad_htrans), + .biu_pad_hwdata (biu_pad_hwdata ), + .biu_pad_hwrite (fifo_pad_hwrite), + .haddr_s1 (haddr_s1 ), + .haddr_s2 (haddr_s2 ), + .haddr_s3 (haddr_s3 ), + .hburst_s1 (hburst_s1 ), + .hburst_s3 (hburst_s3 ), + .hmastlock (hmastlock ), + .hprot_s1 (hprot_s1 ), + .hprot_s3 (hprot_s3 ), + .hrdata_s1 (hrdata_s1 ), + .hrdata_s2 (hrdata_s2 ), + .hrdata_s3 (hrdata_s3 ), + .hready_s1 (hready_s1 ), + .hready_s2 (hready_s2 ), + .hready_s3 (hready_s3 ), + .hresp_s1 (hresp_s1 ), + .hresp_s2 (hresp_s2 ), + .hresp_s3 (hresp_s3 ), + .hsel_s1 (hsel_s1 ), + .hsel_s2 (hsel_s2 ), + .hsel_s3 (hsel_s3 ), + .hsize_s1 (hsize_s1 ), + .hsize_s3 (hsize_s3 ), + .htrans_s1 (htrans_s1 ), + .htrans_s3 (htrans_s3 ), + .hwdata_s1 (hwdata_s1 ), + .hwdata_s2 (hwdata_s2 ), + .hwdata_s3 (hwdata_s3 ), + .hwrite_s1 (hwrite_s1 ), + .hwrite_s2 (hwrite_s2 ), + .hwrite_s3 (hwrite_s3 ), + .pad_biu_hrdata (pad_biu_hrdata ), + .pad_biu_hready (pad_biu_hready ), + .pad_biu_hresp (pad_biu_hresp ), + .pad_cpu_rst_b (pg_reset_b ), + .pll_core_cpuclk (per_clk ), + .smpu_deny (smpu_deny ) +); + +// &Connect( @95 +// .pll_core_cpuclk (per_clk ), @96 +// .pad_cpu_rst_b (pg_reset_b ), @97 +// .biu_pad_hbusreq (fifo_pad_hreq ), @98 +// .biu_pad_haddr (fifo_pad_haddr ), @99 +// .biu_pad_hburst (fifo_pad_hburst ), @100 +// .biu_pad_hlock (fifo_pad_hlock ), @101 +// .biu_pad_hprot (fifo_pad_hprot ), @102 +// .biu_pad_hsize (fifo_pad_hsize ), @103 +// .biu_pad_htrans (fifo_pad_htrans ), @104 +// .biu_pad_hwrite (fifo_pad_hwrite ) @105 +// ); @106 + +//***********************Instance ahb slave 1 **************************** + +// &Instance("mem_ctrl", "x_smem_ctrl"); @110 +mem_ctrl x_smem_ctrl ( + .haddr_s1 (haddr_s1 ), + .hburst_s1 (hburst_s1 ), + .hprot_s1 (hprot_s1 ), + .hrdata_s1 (hrdata_s1 ), + .hready_s1 (hready_s1 ), + .hresp_s1 (hresp_s1 ), + .hsel_s1 (hsel_s1 ), + .hsize_s1 (hsize_s1 ), + .htrans_s1 (htrans_s1 ), + .hwdata_s1 (hwdata_s1 ), + .hwrite_s1 (hwrite_s1 ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pll_core_cpuclk (per_clk ) +); + +// &Connect( @111 +// .pll_core_cpuclk (per_clk ) @112 +// ); @113 + +//***********************Instance ahb slave 2 **************************** + +// &Instance("apb", "x_apb"); @117 +apb x_apb ( + .b_pad_gpio_porta (b_pad_gpio_porta ), + .biu_pad_lpmd_b (biu_pad_lpmd_b ), + .clk_en (clk_en ), + .corec_pmu_sleep_out (corec_pmu_sleep_out ), + .cpu_clk (cpu_clk ), + .fifo_pad_haddr (fifo_pad_haddr ), + .fifo_pad_hprot (fifo_pad_hprot ), + .haddr_s2 (haddr_s2 ), + .hrdata_s2 (hrdata_s2 ), + .hready_s2 (hready_s2 ), + .hresp_s2 (hresp_s2 ), + .hsel_s2 (hsel_s2 ), + .hwdata_s2 (hwdata_s2 ), + .hwrite_s2 (hwrite_s2 ), + .i_pad_cpu_jtg_rst_b (i_pad_cpu_jtg_rst_b ), + .i_pad_jtg_tclk (i_pad_jtg_tclk ), + .nmi_wake_int_lower (nmi_wake_int_lower ), + .pad_clk (i_pad_clk ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pad_had_jtg_tap_en (1'b1 ), + .pad_had_jtg_tms_i (1'b1 ), + .pad_had_jtg_trst_b (pad_had_jtg_trst_b ), + .pad_had_jtg_trst_b_pre (pad_had_jtg_trst_b_pre), + .pad_vic_int_vld (pad_vic_int_vld ), + .per_clk (per_clk ), + .pg_reset_b (pg_reset_b ), + .pmu_corec_isolation (pmu_corec_isolation ), + .pmu_corec_sleep_in (pmu_corec_sleep_in ), + .smpu_deny (smpu_deny ), + .sys_rst (sys_rst ), + .uart0_sin (i_pad_uart0_sin ), + .uart0_sout (o_pad_uart0_sout ) +); + +// &Connect(.pad_clk (i_pad_clk ), @118 +// .uart0_sin (i_pad_uart0_sin ), @119 +// .uart0_sout (o_pad_uart0_sout ), @120 +// .gpio_ext_porta (i_pad_gpio_porta ), @121 +// .gpio_ext_portb (i_pad_gpio_portb ), @122 +// .gpio_porta_dr (o_pad_gpio_porta ), @123 +// .gpio_portb_dr (o_pad_gpio_portb ), @124 +// .gpio_portb_dr (o_pad_gpio_portb ), @125 +// .pad_had_jtg_tms_i (1'b1 ), @126 +// .pad_had_jtg_tap_en (1'b1 ) @127 +// @128 +// @129 +// ); @130 +//***********************Instance ahb slave 3 **************************** + +// &Instance("err_gen", "x_err_gen"); @133 +err_gen x_err_gen ( + .haddr_s3 (haddr_s3 ), + .hburst_s3 (hburst_s3 ), + .hmastlock (hmastlock ), + .hprot_s3 (hprot_s3 ), + .hrdata_s3 (hrdata_s3 ), + .hready_s3 (hready_s3 ), + .hresp_s3 (hresp_s3 ), + .hsel_s3 (hsel_s3 ), + .hsize_s3 (hsize_s3 ), + .htrans_s3 (htrans_s3 ), + .hwdata_s3 (hwdata_s3 ), + .hwrite_s3 (hwrite_s3 ), + .pad_cpu_rst_b (pg_reset_b ), + .pll_core_cpuclk (per_clk ) +); + +// &Connect ( @134 +// .pll_core_cpuclk (per_clk ), @135 +// .pad_cpu_rst_b (pg_reset_b ) @136 +// ); @137 + +//***********************Instance ahb slave 4 **************************** +// &Instance("mem_ctrl", "x_imem_ctrl"); @142 +// &Connect( @143 +// .haddr_s1 (haddr_s4 ), @144 +// .hburst_s1 (hburst_s4 ), @145 +// .hprot_s1 (hprot_s4 ), @146 +// .hrdata_s1 (hrdata_s4 ), @147 +// .hready_s1 (hready_s4 ), @148 +// .hresp_s1 (hresp_s4 ), @149 +// .hsel_s1 (hsel_s4 ), @150 +// .hsize_s1 (hsize_s4 ), @151 +// .htrans_s1 (htrans_s4 ), @152 +// .hwdata_s1 (hwdata_s4 ), @153 +// .hwrite_s1 (hwrite_s4 ), @154 +// .pll_core_cpuclk (per_clk ) @155 +// ); @156 + +//***********************Instance ahb slave 5 **************************** +// &Instance("mem_ctrl", "x_dmem_ctrl"); @162 +// &Connect( @163 +// .haddr_s1 (haddr_s5 ), @164 +// .hburst_s1 (hburst_s5 ), @165 +// .hprot_s1 (hprot_s5 ), @166 +// .hrdata_s1 (hrdata_s5 ), @167 +// .hready_s1 (hready_s5 ), @168 +// .hresp_s1 (hresp_s5 ), @169 +// .hsel_s1 (hsel_s5 ), @170 +// .hsize_s1 (hsize_s5 ), @171 +// .htrans_s1 (htrans_s5 ), @172 +// .hwdata_s1 (hwdata_s5 ), @173 +// .hwrite_s1 (hwrite_s5 ), @174 +// .pll_core_cpuclk (per_clk ) @175 +// ); @176 + +// &Force("nonport","pad_dahbl_hsec"); @179 +// &Force("nonport","pad_iahbl_hsec"); @180 +// &ModuleEnd; @181 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/sync.v b/XUANTIE-RV_opene906/smart_run/logical/system/sync.v new file mode 100644 index 0000000000000000000000000000000000000000..5c359c5aca33aed457599c2d5c634ad0ad4bb2b5 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/sync.v @@ -0,0 +1,94 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// * Non-Disclosure Agreement (NDA). * +// * * +// ***************************************************************************** +// FILE NAME : sync.vp +// AUTHOR : Tao Jiang +// ORIGINAL TIME : 2017.06.02 +// FUNCTION : sync signal +// : +// : +// : +// RESET : Async reset +// DFT : +// DFP : +// VERIFICATION : +// RELEASE HISTORY : +// ***************************************************************************** + + +// &ModuleBeg; @20 +module sync( + fast_clk, + in, + out, + pad_cpu_rst_b, + slow_clk +); + +// &Ports; @21 +input fast_clk; +input in; +input pad_cpu_rst_b; +input slow_clk; +output out; + +// &Regs; @22 +reg input_lv; +reg reg_clr; + +// &Wires; @23 +wire fast_clk; +wire in; +wire input_vld; +wire out; +wire pad_cpu_rst_b; +wire slow_clk; + + + + +assign input_vld = in ; + + +always@(posedge fast_clk or negedge pad_cpu_rst_b ) +begin + if (!pad_cpu_rst_b) + input_lv <= 1'b0; + else if (input_vld) + input_lv <= 1'b1; + else if (reg_clr) + input_lv <= 1'b0; +end + +always@(posedge slow_clk or negedge pad_cpu_rst_b ) +begin + if (!pad_cpu_rst_b) + reg_clr <= 1'b0; + else + reg_clr <= 1'b1; +end + + +assign out = input_lv; +// &ModuleEnd; @50 +endmodule + + + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/system/tap2_sm.v b/XUANTIE-RV_opene906/smart_run/logical/system/tap2_sm.v new file mode 100644 index 0000000000000000000000000000000000000000..18ae814ec1719b1553f804180bd2a0c8cac28b66 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/system/tap2_sm.v @@ -0,0 +1,271 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module tap2_sm( + debug_wake_vld, + pad_had_jtg_tap_en, + tclk, + tms_i, + trst_b +); + +// &Ports; @23 +input pad_had_jtg_tap_en; +input tclk; +input tms_i; +input trst_b; +output debug_wake_vld; + +// &Regs; @24 +reg [7:0] sm2_data_counter; +reg sm2_read_vld; +reg [1:0] sm2_rs; +reg [1:0] sm2_rs_counter; +reg sm2_write_vld; +reg [3:0] tap2_cur_st; +reg [3:0] tap2_nxt_st; +reg [6:0] tap2_rst_cnt; + +// &Wires; @25 +wire debug_wake_vld; +wire pad_had_jtg_tap_en; +wire sm2_load_rs; +wire sm2_load_rw; +wire sm2_rs_cdic_dr_sel; +wire sm2_rs_had_dr_sel; +wire sm2_shift_vld; +wire sm2_start_vld; +wire sm2_trn1; +wire tap2_rst_vld; +wire tap2_sm_tap_en; +wire tclk; +wire tms_i; +wire trst_b; + + +parameter TAP2_RESET = 4'b0000; +parameter TAP2_START = 4'b0001; +parameter TAP2_RW = 4'b0010; +parameter TAP2_RS = 4'b0011; +parameter TAP2_TRN1 = 4'b0100; +parameter TAP2_DATA = 4'b0101; +parameter TAP2_SYNC = 4'b0110; +parameter TAP2_PARITY = 4'b0111; +parameter TAP2_TRN2 = 4'b1000; + + +//========================================================== +// TAP enable +//========================================================== + +// tap enable contains two situations: +// 1. jtg_tap_en + + + +// theoretically, jtg_tap_en also needs synchonization, but +// 1. software gurantees +// 2. keep compatable with CK510, CK610 and CK810 software, avoid relucdant +// cycles to enter TAP state machine +// so, no synchonization is done to jtg_tap_en + +assign tap2_sm_tap_en = pad_had_jtg_tap_en; + +//============================================================================== +// TAP2 controller state machine +//============================================================================== + +always @(posedge tclk or negedge trst_b) +begin + if (!trst_b) + tap2_cur_st[3:0] <= TAP2_RESET; + else if (tap2_rst_vld && tms_i) + tap2_cur_st[3:0] <= TAP2_RESET; + else + tap2_cur_st[3:0] <= tap2_nxt_st[3:0]; +end + +//======================================== +// counter is counting dowwn when +// TMS id high and TCLK is valid +//======================================== +always @(posedge tclk or negedge trst_b) +begin + if (!trst_b) + tap2_rst_cnt[6:0] <= 7'd80; + else + begin + if (!tms_i) + tap2_rst_cnt[6:0] <= 7'd80; + else if (tap2_rst_cnt[6:0] > 7'd0) + tap2_rst_cnt[6:0] <= tap2_rst_cnt[6:0] - 7'd1; + else + tap2_rst_cnt[6:0] <= 7'd80; + end +end + +assign tap2_rst_vld = (tap2_rst_cnt[6:0] == 7'd00); + +// &CombBeg; @90 +always @( sm2_data_counter[7:0] + or tap2_cur_st[3:0] + or tap2_sm_tap_en + or sm2_read_vld + or tms_i + or sm2_rs_counter[1:0]) +begin + case (tap2_cur_st[3:0]) + TAP2_RESET : begin + if (tap2_sm_tap_en) begin + if (tms_i) + tap2_nxt_st[3:0] = TAP2_START; + else + tap2_nxt_st[3:0] = TAP2_RW; + end + else + tap2_nxt_st[3:0] = TAP2_RESET; + end + + TAP2_START : begin // wait for START bit (tms = 0) + if (!tms_i) // sample START bit, logic 0 + tap2_nxt_st[3:0] = TAP2_RW; + else + tap2_nxt_st[3:0] = TAP2_START; + end + + TAP2_RW : begin // RnW bit, 1=Read Op, 0=Write Op + tap2_nxt_st[3:0] = TAP2_RS; + end + + TAP2_RS : begin // RS[1:0] - Register Group Select + if (sm2_rs_counter[1:0] == 2'd0) + tap2_nxt_st[3:0] = TAP2_TRN1; + else + tap2_nxt_st[3:0] = TAP2_RS; + end + + TAP2_TRN1 : begin // Turn Around 1 + if (sm2_read_vld) // Read operation need a sync cycle + tap2_nxt_st[3:0] = TAP2_SYNC; + else // write operation + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_SYNC : begin + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_DATA : begin // IR or DR, Sample or Set + if (sm2_data_counter[7:0] == 8'd0) + tap2_nxt_st[3:0] = TAP2_PARITY; + else + tap2_nxt_st[3:0] = TAP2_DATA; + end + + TAP2_PARITY : begin + tap2_nxt_st[3:0] = TAP2_TRN2; + end + + TAP2_TRN2 : begin + tap2_nxt_st[3:0] = TAP2_START; + end + default : begin + tap2_nxt_st[3:0] = TAP2_RESET; + end + endcase +// &CombEnd; @150 +end + +assign sm2_start_vld = (tap2_cur_st[3:0] == TAP2_RW); +assign sm2_load_rw = (tap2_cur_st[3:0] == TAP2_RW); +assign sm2_load_rs = (tap2_cur_st[3:0] == TAP2_RS); +assign sm2_trn1 = (tap2_cur_st[3:0] == TAP2_TRN1); +assign sm2_shift_vld = (tap2_cur_st[3:0] == TAP2_DATA); + +//========================================= +// load the RW +//========================================= +always @(posedge tclk or negedge trst_b) +begin + if(!trst_b) + begin + sm2_read_vld <= 1'b0; + sm2_write_vld <= 1'b0; + end + else if (sm2_load_rw) + begin + sm2_read_vld <= tms_i; + sm2_write_vld <= !tms_i; + end + else + begin + sm2_read_vld <= sm2_read_vld; + sm2_write_vld <= !tms_i; + end +end + +assign debug_wake_vld = sm2_write_vld; + +//=========================================== +// load the RS[1:0] +//=========================================== +always @(posedge tclk) +begin + if (sm2_start_vld) + sm2_rs_counter[1:0] <= 2'd1; + else if (sm2_load_rs) + sm2_rs_counter[1:0] <= sm2_rs_counter[1:0] - 2'd1; + else + sm2_rs_counter[1:0] <= sm2_rs_counter[1:0]; +end + +always @(posedge tclk) +begin + if (sm2_load_rs) + sm2_rs[1:0] <= {tms_i, sm2_rs[1]}; + else + sm2_rs[1:0] <= sm2_rs[1:0]; +end + +// assign sm2_rs_cdic_ir_sel = sm2_rs[1:0] == 2'b00; +assign sm2_rs_cdic_dr_sel = sm2_rs[1:0] == 2'b01; +assign sm2_rs_had_dr_sel = sm2_rs[1:0] == 2'b11; + +//=========================================== +// intialize DATA shift length +// All DR is 32-bit length +// All IR is 8-bit length +//=========================================== +always @(posedge tclk) +begin + if (sm2_trn1) begin + if (sm2_rs_had_dr_sel || sm2_rs_cdic_dr_sel) + sm2_data_counter[7:0] <= 8'd31; + else + sm2_data_counter[7:0] <= 8'd7; + end + else if (sm2_shift_vld) + sm2_data_counter[7:0] <= sm2_data_counter[7:0] - 8'd1; + else + sm2_data_counter[7:0] <= sm2_data_counter[7:0]; +end + + +// &ModuleEnd; @227 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/tb/had_drv.h b/XUANTIE-RV_opene906/smart_run/logical/tb/had_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..7192084584b42e9fc62b84ee402f834e252cd780 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/tb/had_drv.h @@ -0,0 +1,602 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +//signal remaning +`ifdef JTAG_5 +`define jtag_tdo tb.jtg_tdo +`define jtag_tdi tb.jtg_tdi +`endif +`define jtag_tclk tb.jclk +`define jtag_tms tb.jtg_tms +`define jtag_trst_b tb.jrst_b +//----------------------------------------------- +//define the instructions opcodes +`define BKPT32 32'h80000000 +`define BKPT16 16'h0 +`define MOV_R0_R0 32'hc4004820 +`define MOV_R1_R1 32'hc4014821 +`define MOV_R2_R2 32'hc4024822 +`define MOV_R3_R3 32'hc4034823 +`define MOV_R4_R4 32'hc4044824 +`define MOV_R5_R5 32'hc4054825 +`define MOV_R6_R6 32'hc4064826 +`define MOV_R7_R7 32'hc4074827 +`define MOV_R8_R8 32'hc4084828 +`define MOV_R9_R9 32'hc4094829 +`define MOV_R10_R10 32'hc40a482a +`define MOV_R11_R11 32'hc40b482b +`define MOV_R12_R12 32'hc40c482c +`define MOV_R13_R13 32'hc40d482d +`define MOV_R14_R14 32'hc40e482e +`define MOV_R15_R15 32'hc40f482f +`define MOV_R16_R16 32'hc4104830 +`define MOV_R17_R17 32'hc4114831 +`define MOV_R18_R18 32'hc4124832 +`define MOV_R19_R19 32'hc4134833 +`define MOV_R20_R20 32'hc4144834 +`define MOV_R21_R21 32'hc4154835 +`define MOV_R22_R22 32'hc4164836 +`define MOV_R23_R23 32'hc4174837 +`define MOV_R24_R24 32'hc4184838 +`define MOV_R25_R25 32'hc4194839 +`define MOV_R26_R26 32'hc41a483a +`define MOV_R27_R27 32'hc41b483b +`define MOV_R28_R28 32'hc41c483c +`define MOV_R29_R29 32'hc41d483d +`define MOV_R30_R30 32'hc41e483e +`define MOV_R31_R31 32'hc41f483f + +`define MFCR_R1_CR0 32'hc0006021 +`define MFCR_R1_CR1 32'hc0016021 +`define MFCR_R1_CR2 32'hc0026021 +`define MFCR_R1_CR3 32'hc0036021 +`define MFCR_R1_CR4 32'hc0046021 +`define MFCR_R1_CR5 32'hc0056021 +`define MFCR_R1_CR6 32'hc0066021 +`define MFCR_R1_CR7 32'hc0076021 +`define MFCR_R1_CR8 32'hc0086021 +`define MFCR_R1_CR9 32'hc0096021 +`define MFCR_R1_CR10 32'hc00a6021 +`define MFCR_R1_CR11 32'hc00b6021 +`define MFCR_R1_CR12 32'hc00c6021 +`define MFCR_R1_CR13 32'hc00d6021 +`define MFCR_R1_CR14 32'hc00e6021 +`define MFCR_R1_CR15 32'hc00f6021 +`define MFCR_R1_CR16 32'hc0106021 +`define MFCR_R1_CR17 32'hc0116021 +`define MFCR_R1_CR18 32'hc0126021 +`define MFCR_R1_CR19 32'hc0136021 +`define MFCR_R1_CR20 32'hc0146021 +`define MFCR_R1_CR21 32'hc0156021 + +`define MTCR_R1_CR0 32'hc0016420 +`define MTCR_R1_CR1 32'hc0016421 +`define MTCR_R1_CR2 32'hc0016422 +`define MTCR_R1_CR3 32'hc0016423 +`define MTCR_R1_CR4 32'hc0016424 +`define MTCR_R1_CR5 32'hc0016425 +`define MTCR_R1_CR6 32'hc0016426 +`define MTCR_R1_CR7 32'hc0016427 +`define MTCR_R1_CR8 32'hc0016428 +`define MTCR_R1_CR9 32'hc0016429 +`define MTCR_R1_CR10 32'hc001642a +`define MTCR_R1_CR11 32'hc001642b +`define MTCR_R1_CR12 32'hc001642c +`define MTCR_R1_CR13 32'hc001642d + +`define LDW_R1_R2_0x0 32'hd8222000 +`define LDW_R1_R2_0x4 32'hd8222001 +`define LDW_R1_R2_0x8 32'hd8222002 +`define LDW_R1_R2_0xc 32'hd8222003 +`define LDW_R1_R2_0x10 32'hd8222004 +`define LDW_R1_R2_0x14 32'hd8222005 +`define LDW_R1_R2_0x18 32'hd8222006 +`define LDW_R1_R2_0x1c 32'hd8222007 +`define LDW_R1_R2_0x20 32'hd8222008 +`define LDW_R1_R2_0x24 32'hd8222009 +`define LDW_R1_R2_0x28 32'hd822200a +`define LDW_R1_R2_0x2c 32'hd822200b +`define LDW_R1_R2_0x30 32'hd822200c +`define LDW_R1_R2_0x34 32'hd822200d +`define LDW_R1_R2_0x38 32'hd822200e +`define LDW_R1_R2_0x3c 32'hd822200f +`define LDW_R1_R2_0x40 32'hd8222010 +`define LDW_R1_R2_0x44 32'hd8222011 +`define LDW_R1_R2_0x48 32'hd8222012 +`define LDW_R1_R2_0x4c 32'hd8222013 +`define LDW_R1_R2_0x50 32'hd8222014 +`define LDW_R1_R2_0x54 32'hd8222015 + +`define LDW_R1_R6_0x0 32'hd8262000 +`define LDW_R1_R6_0x4 32'hd8262001 + +`define STW_R1_R2_0x0 32'hdc222000 +`define STW_R1_R5_0x0 32'hdc252000 +`define STW_R1_R5_0x4 32'hdc252001 +`define STW_R1_R5_0x8 32'hdc252002 +`define STW_R1_R5_0xc 32'hdc252003 +`define STW_R1_R5_0x10 32'hdc252004 + +//----------------------------------------------- +//define the HAD registers +`define id 7'b0000010 +`define tracer 7'b0000011 +`define mbca 7'b0000100 +`define mbcb 7'b0000101 +`define pcfifo 7'b0000110 +`define baba 7'b0000111 +`define babb 7'b0001000 +`define bama 7'b0001001 +`define bamb 7'b0001010 +`define cpuscr 7'b0001011 +`define bypass 7'b0001100 +`define hcr 7'b0001101 +`define hsr 7'b0001110 + +`define daddr 7'b0011000 +`define ddata 7'b0011001 + +`define wbbr 7'b0010001 +`define psr 7'b0010010 +`define pc 7'b0010011 +`define ir 7'b0010100 +`define csr 7'b0010101 + +`define wbbr_go_ex 7'b1110001 +`define wbbr_go_nex 7'b1010001 +`define wbbr_ngo_ex 7'b0110001 +`define wbbr_ngo_nex 7'b0010001 +`define psr_go_ex 7'b1110010 +`define psr_go_nex 7'b1010010 +`define psr_ngo_ex 7'b0110010 +`define psr_ngo_nex 7'b0010010 +`define pc_go_ex 7'b1110011 +`define pc_go_nex 7'b1010011 +`define pc_ngo_ex 7'b0110011 +`define pc_ngo_nex 7'b0010011 +`define ir_go_ex 7'b1110100 +`define ir_go_nex 7'b1010100 +`define ir_ngo_ex 7'b0110100 +`define ir_ngo_nex 7'b0010100 +`define csr_go_ex 7'b1110101 +`define csr_go_nex 7'b1010101 +`define csr_ngo_ex 7'b0110101 +`define csr_ngo_nex 7'b0010101 +`define cpuscr_go_ex 7'b1101011 +`define cpuscr_go_nex 7'b1001011 + + +`define bypass_go_ex 7'b1101100 +`define bypass_go_nex 7'b1001100 +`define bypass_ngo_ex 7'b0101100 +`define bypass_ngo_nex 7'b0001100 +`ifdef JTAG_5 + // Task for JTAG 5 + //jtag reset, for example: jtag_rst(100) + task jtag_rst; + input[31:0] rst_cycle; + integer i; + begin + force `jtag_trst_b = 1'b1; + force `jtag_tms = 1'b0; + + //wait until posedge tclk + @(negedge `jtag_tclk); + force `jtag_trst_b = 1'b0; + + //wait for user specified cycles + for(i=0; i The hsr is: 0x%h |", + hsr_data_out[15:0]); + while(hsr_data_out[1:0]!=2'b10) + read_hadreg(`hsr,hsr_data_out); + $display(" The hsr is: 0x%h |", + hsr_data_out[15:0]); + $display("Now, CPU is in Debug Mode! |"); + $display("---------------------------------------"); + end +endtask + +/*********************************************************** +The following task was defined to check the cpu mode. +If the cpu has into debug mode, +************************************************************/ +task check_cpu_mode; + reg[15:0] hsr_data_out; + begin + read_hadreg(`hsr,hsr_data_out); + if(hsr_data_out[1:0]==2'b00) + begin + $display("----------------------------------------"); + $display("*** hsr value is:0x%h *** |", + hsr_data_out[15:0]); + $display("*** CPU is in Normal Mode! *** |"); + $display("----------------------------------------"); + end + else if(hsr_data_out[1:0]==2'b01) + begin + $display("----------------------------------------"); + $display("*** hsr value is:0x%h *** |", + hsr_data_out[15:0]); + $display("*** CPU is in LowPower Mode! *** |"); + $display("----------------------------------------"); + end + else if(hsr_data_out[1:0]==2'b10) + begin + $display("----------------------------------------"); + $display("*** hsr value is:0x%h *** |", + hsr_data_out[15:0]); + $display("*** CPU is in Debug Mode! *** |"); + $display("----------------------------------------"); + end + else + begin + $display("----------------------------------------"); + $display("*** hsr value is:0x%h *** |", + hsr_data_out[15:0]); + $display("*** CPU is in Reserve Mode! *** |"); + $display("----------------------------------------"); + end + end +endtask + diff --git a/XUANTIE-RV_opene906/smart_run/logical/tb/mnt.v b/XUANTIE-RV_opene906/smart_run/logical/tb/mnt.v new file mode 100644 index 0000000000000000000000000000000000000000..6f5464c204e77c6f8f455c2fad791dbd7eef6362 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/tb/mnt.v @@ -0,0 +1,168 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// `include "../cpu/environment.h" + +// * if gpr write back and pc retire happen at the same time,there is need to +// * use gpr buffer, if gpr write back is one cycle after pc retire, there is +// * no need to use gpr buffer. +// +// * for CK803 USE_GPR_BUFFER + + +// * interface with Smart SoC testbench. +// common interface +`define mcause tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.cp0_pad_mcause[31:0] + +// single issue cpu interface +`define retire tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire +`define retire_pc tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire_pc +`define wb_gpr_data tb.x_soc.x_cpu_sub_system_ahb.biu_pad_wb_gpr_data +`define wb_gpr_index tb.x_soc.x_cpu_sub_system_ahb.biu_pad_wb_gpr_index +`define wb_gpr_en tb.x_soc.x_cpu_sub_system_ahb.biu_pad_wb_gpr_en + +module mnt(); + +// * reg definition for PC buffer +// * these buffered signals are one cycle delay and used to print logfile +reg retire_latch; +reg [31:0] retire_pc_latch; + +// * reg definition for GPR buffer +// * these buffered signals are one cycle delay +reg wb_gpr_en_delay1; +reg [ 4:0] wb_gpr_index_delay1; +reg [31:0] wb_gpr_data_delay1; + +// * reg definition for GPR, these registers hold the old value of GPR +reg [31:0] GPR [31:0]; + +// * wire definition for GPR signal +// * these signals used to print logfile and is connected to wb_gpr directly +// * or wb_gpr_delay1 signal according to definition USE_GPR_BUFFER +wire wb_gpr_en_latch; +wire [ 4:0] wb_gpr_index_latch; +wire [31:0] wb_gpr_data_latch; + + + +// * PC Buffer +always @(posedge `clk or negedge `rst_b) +begin + if(!`rst_b) + retire_latch <= 1'b0; + else + retire_latch <= `retire; +end + +always @(posedge `clk) +begin + retire_pc_latch[31:0] <= `retire_pc[31:0]; +end + +// * GPR Buffer +always @(posedge `clk or negedge `rst_b) +begin + if(!`rst_b) + wb_gpr_en_delay1 <= 1'b0; + else + wb_gpr_en_delay1 <= `wb_gpr_en; +end + +always @(posedge `clk) +begin + wb_gpr_index_delay1[4:0] <= `wb_gpr_index[4:0]; + wb_gpr_data_delay1[31:0] <= `wb_gpr_data[31:0]; +end + +// * wires connecttion +// * if USE_GPR_BUFFER, use delayed signal, else use signal directly +assign wb_gpr_en_latch = `wb_gpr_en; +assign wb_gpr_index_latch[4:0] = `wb_gpr_index[4:0]; +assign wb_gpr_data_latch[31:0] = `wb_gpr_data[31:0]; + +// * GPR has three write ports. port 1 is for single issue cpu, port 2 and port 3 are +// * for dual issue cpu. port 1 and port 2 or 3 cannot be valid at the same time. +// * if port 2 and 3 are valid at the same time, they cannot write the same reigster. +// * this is assured by cpu inner logical +wire gpr_we; + +assign gpr_we = wb_gpr_en_latch; + +integer i; + +always @(posedge `clk or negedge `rst_b) +begin + if(!`rst_b) + begin + for(i = 0; i < 32; i = i+1) + begin + GPR[i] <= 32'b0; + end + end + else if(gpr_we) + begin + GPR[wb_gpr_index_latch] <= wb_gpr_data_latch; + end +end + +// * logfile is new in current directory. The name of the file is GPR.log +// * there are 3 write ports. the first is for single issue cpu. the second and +// * the third is for dual issue cpu. port for single issue and port for dual +// * issue cannot be valied at the same time. +integer GPR_FH; + +initial +begin + GPR_FH = $fopen("GPR.log"); + if(GPR_FH == 0) + begin + $display("can't open log file GPR.log in mnt.v!"); + $finish; + end +end + + +// * for single issue cpu, there is only one print function is valid at one time +// * when PC retire, print PC, PSR and GPR information +wire retire_pc_print; +assign retire_pc_print = retire_latch; + +always @(posedge `clk) +begin + if(retire_pc_print) + begin + $fwrite(GPR_FH, "PC : %8h |", retire_pc_latch[31:0]); + $fwrite(GPR_FH, "MCAUSE: %8h\n", `mcause); + for(i = 0; i < 32; i = i+1) + begin + if(wb_gpr_en_latch && (i == wb_gpr_index_latch[4:0])) + begin + $fwrite(GPR_FH, "gr%2d:%8h |",i,wb_gpr_data_latch[31:0]); + end + else + begin + $fwrite(GPR_FH, "gr%2d:%8h |",i,GPR[i]); + end + if(i % 4 == 3) + begin + $fwrite(GPR_FH, "\n"); + end + end + $fwrite(GPR_FH, "\n"); + end +end + +endmodule diff --git a/XUANTIE-RV_opene906/smart_run/logical/tb/tb.v b/XUANTIE-RV_opene906/smart_run/logical/tb/tb.v new file mode 100644 index 0000000000000000000000000000000000000000..59b64c0e01bff0e6d236de190ede4b3559bb876a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/tb/tb.v @@ -0,0 +1,446 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +`define E906 +`define SOC_TOP tb.x_soc +`define RTL_MEM tb.x_soc.x_smem_ctrl +`define ISA_MEM tb.x_pa_isa +`define JTAG_5 + +`define IAHB_LITE +`ifdef IAHB_LITE + `define RTL_IAHBL_MEM tb.x_soc.x_cpu_sub_system_ahb.x_iahb_mem_ctrl +`else + `define RTL_IAHBL_MEM tb.x_soc.x_imem_ctrl +`endif + +`define DAHB_LITE +`ifdef DAHB_LITE + `define RTL_DAHBL_MEM tb.x_soc.x_cpu_sub_system_ahb.x_dahb_mem_ctrl +`else + `define RTL_DAHBL_MEM tb.x_soc.x_dmem_ctrl +`endif + +//clock period +`define CLK_PERIOD 10 +`define TCLK_PERIOD 33 +`define MAX_RUN_TIME 700000000 +`define clk tb.clk +`define rst_b tb.rst_b +// `include "../cpu/environment.h" +`timescale 1ns/100ps + +module tb(); +reg clk; +reg jclk; +reg rst_b; +reg jrst_b; +reg nrst_b; +reg jtap_en; +//wire jtag2_sel; +wire jtg_tms; +wire jtg_tdi; +wire jtg_tdo; + +wire uart0_sin; +wire [7:0]b_pad_gpio_porta; +static integer FILE; +//Clock Generator +initial +begin + clk =0; + forever begin + #(`CLK_PERIOD/2) clk = ~clk; + end +end + +initial +begin + jclk = 0; + forever begin + #(`TCLK_PERIOD/2) jclk = ~jclk; + end +end + +//Reset Generater +initial +begin + rst_b = 1; + #100; + rst_b = 0; + #100; + rst_b = 1; +end + +initial +begin + jrst_b = 1; + #100; + jrst_b = 0; + #100; + jrst_b = 1; +end + +initial +begin + nrst_b = 1; + #100; + nrst_b = 0; + #100; + nrst_b = 1; +end + +/////////////////////////////////////// +// Memory Initialization +/////////////////////////////////////// +integer i; +reg [31:0] mem_data_size; +reg [31:0] mem_inst_size; + +reg [31:0] mem_inst_temp [65536]; +reg [31:0] mem_data_temp [65536]; + +initial +begin + $display("\t******START TO LOAD PROGRAM******\n"); + $readmemh("./case.pat", mem_inst_temp); + $readmemh("./data.pat", mem_data_temp); + + + for(i=0;i<65536;i=i+1) + begin + `RTL_IAHBL_MEM.ram0.mem[i][7:0] = ((^mem_inst_temp[i][31:24]) === 1'bx ) ? 8'b0:mem_inst_temp[i][31:24]; + `RTL_IAHBL_MEM.ram1.mem[i][7:0] = ((^mem_inst_temp[i][23:16]) === 1'bx ) ? 8'b0:mem_inst_temp[i][23:16]; + `RTL_IAHBL_MEM.ram2.mem[i][7:0] = ((^mem_inst_temp[i][15: 8]) === 1'bx ) ? 8'b0:mem_inst_temp[i][15: 8]; + `RTL_IAHBL_MEM.ram3.mem[i][7:0] = ((^mem_inst_temp[i][ 7: 0]) === 1'bx ) ? 8'b0:mem_inst_temp[i][ 7: 0]; + end + + for(i=0;i<=65536;i=i+1) + begin + `RTL_DAHBL_MEM.ram0.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram1.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram2.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram3.mem[i][7:0] = 8'b0; + end + for(i=0;i<=65536;i=i+1) + begin + `RTL_DAHBL_MEM.ram4.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram5.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram6.mem[i][7:0] = 8'b0; + `RTL_DAHBL_MEM.ram7.mem[i][7:0] = 8'b0; + end + + +end +/////////////////////////////////////// +// Finish Condition Control +/////////////////////////////////////// + +// Reaching the max simulation time. +reg [31:0] ins_counter; +initial +begin +#`MAX_RUN_TIME; + $display("**********************************************"); + $display("* meeting max simulation time, stop! *"); + $display("**********************************************"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); +$finish; +end +// No instrunction retired in the last `LAST_CYCLE cycles +reg [31:0] retire_inst_in_period; +reg [31:0] cycle_count; +`define LAST_CYCLE 5000 +always @(posedge clk or negedge rst_b) +begin + if(!rst_b) + cycle_count[31:0] <= 32'b1; + else + cycle_count[31:0] <= cycle_count[31:0] + 1'b1; +end + + +always @(posedge clk or negedge rst_b) +begin + if(!rst_b) //reset to zero + retire_inst_in_period[31:0] <= 32'b0; + else if( (cycle_count[31:0] % `LAST_CYCLE) == 0)//check and reset retire_inst_in_period every 50000 cycles + begin + if(retire_inst_in_period[31:0] == 0)begin + $display("*************************************************************"); + $display("* Error: There is no instructions retired in the last %d cycles! *", `LAST_CYCLE); + $display("* Simulation Fail and Finished! *"); + $display("*************************************************************"); + #10; + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + + $finish; + end + retire_inst_in_period[31:0] <= 32'b0; + end + else if(tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire) + retire_inst_in_period[31:0] <= retire_inst_in_period[31:0] + 1'b1; +end + + +//Finish control with address 32'h0 +reg [31:0] cpu_addr; +reg [1:0] cpu_trans; +reg cpu_write; +wire [31:0] cpu_wdata; +always @(posedge clk) +begin + cpu_trans[1:0] <= `SOC_TOP.biu_pad_htrans[1:0]; + cpu_addr[31:0] <= `SOC_TOP.biu_pad_haddr[31:0]; + cpu_write <= `SOC_TOP.biu_pad_hwrite; +end +assign cpu_wdata[31:0] = `SOC_TOP.biu_pad_hwdata[31:0]; +always @(posedge clk) +begin + if((cpu_trans[1:0] == 2'b10) && + (cpu_addr[31:0] == 32'h6000fff8) && + cpu_write && + (cpu_wdata[31:0] == 12'hfff || cpu_wdata[31:0] == 32'hffff0000)) + begin + $display("\n**********************************************"); + $display("* simulation finished successfully *"); + $display("**********************************************"); + #10; + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST PASS"); + + $finish; + end + else if((cpu_trans[1:0] == 2'b10) && + (cpu_addr[31:0] == 32'h6000fff8) && + cpu_write && + (cpu_wdata[31:0] == 12'heee || cpu_wdata[31:0] == 32'heeee0000)) + begin + $display("**********************************************"); + $display("* simulation finished with error *"); + $display("**********************************************"); + #10; + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + + $finish; + end + else if((cpu_trans[1:0] == 2'b10) && + (cpu_addr[31:0] == 32'h6000fff8) && + cpu_write) + begin +// $write("begin to display:"); + $write("%c", cpu_wdata[7:0]); + end +end + +//Dumping Control +`ifndef NO_DUMP +initial +begin + `ifdef NC_SIM + $dumpfile("test.vcd"); + $dumpvars; + `else + `ifdef IVERILOG_SIM + $dumpfile("test.vcd"); + $dumpvars; + `else + $fsdbDumpvars(); + `endif + `endif +end +`endif + +//Monitor +`ifndef NO_MONITOR +mnt x_mnt(); +`endif +uart_mnt x_uart_mnt(); +assign jtg_tdi = 1'b0; + +assign uart0_sin = 1'b1; + +//instantiate soc +soc x_soc( + .i_pad_clk ( clk ), + .i_pad_uart0_sin ( uart0_sin ), + .o_pad_uart0_sout ( uart0_sout ), + .i_pad_jtg_tclk ( jclk ), + .i_pad_jtg_trst_b ( jrst_b ), + .i_pad_jtg_nrst_b ( nrst_b ), + .b_pad_gpio_porta ( b_pad_gpio_porta ), +`ifdef JTAG_5 + .i_pad_jtg_tdi ( jtg_tdi ), + .o_pad_jtg_tdo ( jtg_tdo ), +`endif + .i_pad_jtg_tms ( jtg_tms ), +`ifdef RST_ACTIVE_HIGH + .i_pad_rst ( !rst_b ) +`else + .i_pad_rst_b ( rst_b ) +`endif +); + + +`ifdef PG_SIM + +`define MAX_ARCH_STRLEN 100 + +function supply_on; + //input string pad_name; + input [8*`MAX_ARCH_STRLEN : 1] pad_name; + input real value; +begin + supply_on = $mvsim_supply_on(pad_name, value); +end +endfunction + +function supply_off; + //input string pad_name; + input [8*`MAX_ARCH_STRLEN : 1] pad_name; +begin + supply_off = $mvsim_supply_off(pad_name); +end +endfunction + +real sp_on_vdd; +real sp_on_vss; + + +initial +begin + sp_on_vdd = supply_on("VDD", 1.2); + sp_on_vss = supply_on("VSS", 0); + +// #1000 +// force tb.x_soc.pad_cpu_rst_b = 1'b0; +// #20 +// force tb.x_soc.x_cpu_sub_system_ahb.x_ck803s.pmu_corec_isolation = 1'b1; +// #20 +// force tb.x_soc.x_cpu_sub_system_ahb.x_ck803s.pmu_corec_sleep_in = 1'b1; +// +// #500 +// +// release tb.x_soc.x_cpu_sub_system_ahb.x_ck803s.pmu_corec_sleep_in ; +// #20 +// release tb.x_soc.x_cpu_sub_system_ahb.x_ck803s.pmu_corec_isolation; +// #20 +// release tb.x_soc.pad_cpu_rst_b ; + +end + +initial +begin + $deposit(tb.x_soc.x_cpu_sub_system_ahb.pmu_corec_sleep_in, 1'b0); + $deposit(tb.x_soc.x_cpu_sub_system_ahb.pmu_corec_isolation, 1'b0); + $deposit(tb.x_soc.x_cpu_sub_system_ahb.corec_pmu_sleep_out, 1'b0); +end + +`endif + +`ifdef E902 + `define CPU_TOP tb.x_soc.x_cpu_sub_system_ahb.x_e902 +`elsif E906 + `define CPU_TOP tb.x_soc.x_cpu_sub_system_ahb.x_e906_top +`else + `define CPU_TOP tb.x_soc.x_cpu_sub_system_ahb.x_ck803s +`endif + +`define CPU_CLK `CPU_TOP.pll_core_cpuclk +`define CPU_RST `CPU_TOP.pad_cpu_rst_b + +`ifdef E902 + `define VIRTUAL_READ `CPU_TOP.x_cr_tcipif_top.x_cr_tcipif_dbus.dummy_addr_cmplt +`elsif E906 + `define VIRTUAL_READ `CPU_TOP.x_pa_tcipif_top.x_pa_tcipif_dbus.dummy_addr_cmplt +`else + `define VIRTUAL_READ `CPU_TOP.x_vg_tcip_top.x_nm_tcipif_dbus.dummy_addr_cmplt +`endif +`ifdef E902 + `define VIRTUAL_TIME `CPU_TOP.x_cr_tcipif_top.x_cr_tcipif_dbus.tcipif_rd_data[31:0] +`elsif E906 + `define VIRTUAL_TIME `CPU_TOP.x_pa_tcipif_top.x_pa_tcipif_dbus.tcipif_bmu_dbus_data[31:0] +`else + `define VIRTUAL_TIME `CPU_TOP.x_vg_tcip_top.x_nm_tcipif_dbus.tcipif_dbus_rd_data[31:0] +`endif + +reg [31:0] virtual_counter; + +always @(posedge `CPU_CLK or negedge `CPU_RST) +begin + if(!`CPU_RST) + virtual_counter[31:0] <= 32'b0; + else if(virtual_counter[31:0]==32'hffffffff) + virtual_counter[31:0] <= virtual_counter[31:0]; + else + virtual_counter[31:0] <= virtual_counter[31:0] +1'b1; +end + +initial +begin + #1; + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + #1; + + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + #1; + + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + #1; + + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + + #1; + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + + #1; + wait (`VIRTUAL_READ==1'b1); + force `VIRTUAL_TIME = virtual_counter[31:0]; + @(posedge `CPU_CLK); + release `VIRTUAL_TIME; + #1; +end + +// count instruction number +always @(posedge `CPU_CLK or negedge `CPU_RST) +begin + if(!`CPU_RST) + ins_counter[31:0] <= 32'b0; + else if(`SOC_TOP.x_cpu_sub_system_ahb.biu_pad_retire && + (`SOC_TOP.x_cpu_sub_system_ahb.biu_pad_retire_pc[31:0] > 32'had4)) + ins_counter[31:0] <= ins_counter[31:0] + 1'b1; + else + ins_counter[31:0] <= ins_counter[31:0]; +end + +endmodule + diff --git a/XUANTIE-RV_opene906/smart_run/logical/tb/uart_mnt.v b/XUANTIE-RV_opene906/smart_run/logical/tb/uart_mnt.v new file mode 100644 index 0000000000000000000000000000000000000000..137f791087ea12893243ea88536324153d6ba404 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/tb/uart_mnt.v @@ -0,0 +1,162 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +`define sout tb.uart0_sout +`define sin tb.uart0_sin + +module uart_mnt(); + +//############################################# +// Create baud_clk +//############################################# +parameter FCPU = 1000000000/`CLK_PERIOD; +parameter BAUD = 19200; +parameter CYCLE_CUNT=FCPU/(BAUD*16) - 1; + + +reg[31:0] div_counter; + +always @(posedge `clk or negedge `rst_b) +begin + if(!`rst_b) + begin + div_counter[31:0]<=CYCLE_CUNT; + end + else if(div_counter[31:0]==32'b0) + begin + div_counter[31:0]<=CYCLE_CUNT; + end + else + begin + div_counter[31:0]<=div_counter[31:0] - 1'b1; + end +end + +assign baud_clk=(div_counter[31:0]>=(CYCLE_CUNT/2))?0:1; + + +//############################################# +// Receive data +//############################################# + +reg sout_flop; +reg trig_count_en; +reg [4:0] trig_count; +reg shift_en; +reg [3:0] shift_count; +reg [3:0] capture_time; +reg[7:0] pack_data; + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + sout_flop<=1'b0; + else + sout_flop<=`sout; +end + +assign trig = sout_flop && !`sout && !shift_en; + + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + trig_count_en<=1'b0; + else if(trig) + trig_count_en<=1'b1; + else if(shift_en) + trig_count_en<=1'b0; +end + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + trig_count[4:0]<=5'b0; + else if(!trig_count_en) + trig_count[4:0]<=5'b0; + else if(trig_count_en) + trig_count[4:0]<= trig_count[4:0] + 1; +end + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + shift_en<=1'b0; + else if(trig_count[4:0]==22) + shift_en<=1'b1; + else if(capture_time[3:0]==8) + shift_en<=1'b0; +end + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + shift_count[3:0]<=4'b0; + else if(trig) + shift_count[3:0]<=4'b0; + else if(shift_en) + shift_count[3:0]<= shift_count[3:0] + 1; +end + +assign capture_en = shift_en && (shift_count[3:0]==0); + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + capture_time[3:0]<=4'b0; + else if(trig) + capture_time[3:0]<=4'b0; + else if(capture_en) + capture_time[3:0]<= capture_time[3:0] + 1; + end + +always @(posedge baud_clk or negedge `rst_b) +begin + if(!`rst_b) + begin + pack_data[7:0]<=8'b0; + end + else if (capture_en) + begin + pack_data[7:0]<={`sout,pack_data[7:1]}; + end + else + begin + pack_data[7:0]<=pack_data[7:0]; + end +end + +assign print_en = (capture_time[3:0]==8) && shift_en; + +//############################################# +// Print log +//############################################# +integer output_file; + +initial +begin + output_file=$fopen("uart_output.inf","w"); +end + +always @(posedge baud_clk ) +begin + if(print_en) + begin + $fwrite(output_file,"%C",pack_data[7:0]); + $write("\033[0;31m%C\033[0m",pack_data[7:0]); + end +end + +endmodule diff --git a/XUANTIE-RV_opene906/smart_run/logical/timer/timer.v b/XUANTIE-RV_opene906/smart_run/logical/timer/timer.v new file mode 100644 index 0000000000000000000000000000000000000000..e4387fa1330dfd0353585519edcc0da7123735bd --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/timer/timer.v @@ -0,0 +1,591 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module timer( + paddr, + pclk, + penable, + prdata, + presetn, + psel, + pwdata, + pwrite, + timer_int +); + +// &Ports; @24 +input [15:0] paddr; +input pclk; +input penable; +input presetn; +input psel; +input [31:0] pwdata; +input pwrite; +output [31:0] prdata; +output [3 :0] timer_int; + +// &Regs; @25 +reg [31:0] prdata; +reg [2 :0] timer_1_control_reg; +reg [31:0] timer_1_load_count; +reg timer_1_raw_int_status; +reg [2 :0] timer_2_control_reg; +reg [31:0] timer_2_load_count; +reg timer_2_raw_int_status; +reg [2 :0] timer_3_control_reg; +reg [31:0] timer_3_load_count; +reg timer_3_raw_int_status; +reg [2 :0] timer_4_control_reg; +reg [31:0] timer_4_load_count; +reg timer_4_raw_int_status; + +// &Wires; @26 +wire [15:0] paddr; +wire pclk; +wire presetn; +wire psel; +wire [31:0] pwdata; +wire pwrite; +wire [31:0] timer_1_current_value; +wire timer_1_int_clear; +wire timer_1_int_status; +wire timer_1_interrupt; +wire [31:0] timer_2_current_value; +wire timer_2_int_clear; +wire timer_2_int_status; +wire timer_2_interrupt; +wire [31:0] timer_3_current_value; +wire timer_3_int_clear; +wire timer_3_int_status; +wire timer_3_interrupt; +wire [31:0] timer_4_current_value; +wire timer_4_int_clear; +wire timer_4_int_status; +wire timer_4_interrupt; +wire [3 :0] timer_int; +wire timers_int_clear; + + +// &Force("bus","paddr",15,0); @28 +// &Force("bus","pwdata",31,0); @29 +// &Force("input","penable"); @30 +// &Force("output","prdata"); @31 +// &Force("bus","prdata",31,0); @32 +// &Force("output","timer_int"); @33 +// &Force("bus","timer_int",3,0); @34 + +// &Instance("counter", "timer_1"); @36 +counter timer_1 ( + .interrupt (timer_1_interrupt ), + .pclk (pclk ), + .presetn (presetn ), + .timer_current_value (timer_1_current_value ), + .timer_enable (timer_1_control_reg[0]), + .timer_load_count (timer_1_load_count ), + .timer_mode (timer_1_control_reg[1]) +); + +// &Connect(.pclk (pclk ), @37 +// .presetn (presetn ), @38 +// .timer_enable (timer_1_control_reg[0] ), @39 +// .timer_mode (timer_1_control_reg[1] ), @40 +// .timer_load_count (timer_1_load_count ), @41 +// .timer_current_value (timer_1_current_value ), @42 +// .interrupt (timer_1_interrupt ) @43 +// ); @44 + +// &Instance("counter", "timer_2"); @46 +counter timer_2 ( + .interrupt (timer_2_interrupt ), + .pclk (pclk ), + .presetn (presetn ), + .timer_current_value (timer_2_current_value ), + .timer_enable (timer_2_control_reg[0]), + .timer_load_count (timer_2_load_count ), + .timer_mode (timer_2_control_reg[1]) +); + +// &Connect(.pclk (pclk ), @47 +// .presetn (presetn ), @48 +// .timer_enable (timer_2_control_reg[0] ), @49 +// .timer_mode (timer_2_control_reg[1] ), @50 +// .timer_load_count (timer_2_load_count ), @51 +// .timer_current_value (timer_2_current_value ), @52 +// .interrupt (timer_2_interrupt ) @53 +// ); @54 + +// &Instance("counter", "timer_3"); @56 +counter timer_3 ( + .interrupt (timer_3_interrupt ), + .pclk (pclk ), + .presetn (presetn ), + .timer_current_value (timer_3_current_value ), + .timer_enable (timer_3_control_reg[0]), + .timer_load_count (timer_3_load_count ), + .timer_mode (timer_3_control_reg[1]) +); + +// &Connect(.pclk (pclk ), @57 +// .presetn (presetn ), @58 +// .timer_enable (timer_3_control_reg[0] ), @59 +// .timer_mode (timer_3_control_reg[1] ), @60 +// .timer_load_count (timer_3_load_count ), @61 +// .timer_current_value (timer_3_current_value ), @62 +// .interrupt (timer_3_interrupt ) @63 +// ); @64 + +// &Instance("counter", "timer_4"); @66 +counter timer_4 ( + .interrupt (timer_4_interrupt ), + .pclk (pclk ), + .presetn (presetn ), + .timer_current_value (timer_4_current_value ), + .timer_enable (timer_4_control_reg[0]), + .timer_load_count (timer_4_load_count ), + .timer_mode (timer_4_control_reg[1]) +); + +// &Connect(.pclk (pclk ), @67 +// .presetn (presetn ), @68 +// .timer_enable (timer_4_control_reg[0] ), @69 +// .timer_mode (timer_4_control_reg[1] ), @70 +// .timer_load_count (timer_4_load_count ), @71 +// .timer_current_value (timer_4_current_value ), @72 +// .interrupt (timer_4_interrupt ) @73 +// ); @74 + +//========================================================== +// APB PWDATA +//========================================================== +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_1_load_count <= 32'b0; + timer_1_control_reg <= 3'b0; + timer_2_load_count <= 32'b0; + timer_2_control_reg <= 3'b0; + timer_3_load_count <= 32'b0; + timer_3_control_reg <= 3'b0; + timer_4_load_count <= 32'b0; + timer_4_control_reg <= 3'b0; + end + else + begin + if(psel && pwrite && penable) + begin + case(paddr[7:2]) + 6'b000000: + begin + timer_1_load_count <= pwdata; + end + 6'b000010: + begin + timer_1_control_reg <= pwdata[2:0]; + end + 6'b000101: + begin + timer_2_load_count <= pwdata; + end + 6'b000111: + begin + timer_2_control_reg <= pwdata[2:0]; + end + 6'b001010: + begin + timer_3_load_count <= pwdata; + end + 6'b001100: + begin + timer_3_control_reg <= pwdata[2:0]; + end + 6'b001111: + begin + timer_4_load_count <= pwdata; + end + 6'b010001: + begin + timer_4_control_reg <= pwdata[2:0]; + end + endcase + end + end +end + +//========================================================== +// APB PRDATA +//========================================================== +always @(posedge pclk) +begin + if(psel && !pwrite) + begin + if (!penable) + begin + case(paddr[7:2]) + 6'b000000: + begin + prdata <= timer_1_load_count; + end + 6'b000001: + begin + prdata <= timer_1_current_value; + end + 6'b000010: + begin + prdata <= {29'b0, timer_1_control_reg}; + end + 6'b000011: + begin + prdata <= 32'b0; + end + 6'b000100: + begin + prdata <= {31'b0, timer_1_int_status}; + end + 6'b000101: + begin + prdata <= timer_2_load_count; + end + 6'b000110: + begin + prdata <= timer_2_current_value; + end + 6'b000111: + begin + prdata <= {29'b0, timer_2_control_reg}; + end + 6'b001000: + begin + prdata <= 32'b0; + end + 6'b001001: + begin + prdata <= {31'b0, timer_2_int_status}; + end + 6'b001010: + begin + prdata <= timer_3_load_count; + end + 6'b001011: + begin + prdata <= timer_3_current_value; + end + 6'b001100: + begin + prdata <= {29'b0, timer_3_control_reg}; + end + 6'b001101: + begin + prdata <= 32'b0; + end + 6'b001110: + begin + prdata <= {31'b0, timer_3_int_status}; + end + 6'b001111: + begin + prdata <= timer_4_load_count; + end + 6'b010000: + begin + prdata <= timer_4_current_value; + end + 6'b010001: + begin + prdata <= {29'b0, timer_4_control_reg}; + end + 6'b010010: + begin + prdata <= 32'b0; + end + 6'b010011: + begin + prdata <= {31'b0, timer_4_int_status}; + end + 6'b101000: + begin + prdata <= {28'b0, timer_int}; + end + 6'b101001: + begin + prdata <= 32'b0; + end + 6'b101010: + begin + prdata <= {28'b0, timer_4_raw_int_status, timer_3_raw_int_status, timer_2_raw_int_status, timer_1_raw_int_status}; + end + default: + begin + prdata <= 32'bx; + end + endcase + end + else + begin + prdata <= 32'bx; + end + end +end + +assign timer_int = {timer_4_int_status, timer_3_int_status, timer_2_int_status, timer_1_int_status}; + +//========================================================== +// Clear Interrupt when reads EOI +//========================================================== +assign timer_1_int_clear = (paddr[7:2] == 6'b000011) && psel && !pwrite; +assign timer_2_int_clear = (paddr[7:2] == 6'b001000) && psel && !pwrite; +assign timer_3_int_clear = (paddr[7:2] == 6'b001101) && psel && !pwrite; +assign timer_4_int_clear = (paddr[7:2] == 6'b010010) && psel && !pwrite; +assign timers_int_clear = (paddr[7:2] == 6'b101001) && psel && !pwrite; + +//========================================================== +// Timer 1 interrupt set and clear +//========================================================== +assign timer_1_int_status = timer_1_raw_int_status && !timer_1_control_reg[2]; +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_1_raw_int_status <= 1'b0; + end + else + begin + if(timer_1_control_reg[0]) + begin + if(timer_1_interrupt) + begin + timer_1_raw_int_status <= 1'b1; + end + else + begin + if(timer_1_int_clear || timers_int_clear) + begin + timer_1_raw_int_status <= 1'b0; + end + end + end + else + begin + timer_1_raw_int_status <= 1'b0; + end + end +end + +//========================================================== +// Timer 2 interrupt set and clear +//========================================================== +assign timer_2_int_status = timer_2_raw_int_status && !timer_2_control_reg[2]; +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_2_raw_int_status <= 1'b0; + end + else + begin + if(timer_2_control_reg[0]) + begin + if(timer_2_interrupt) + begin + timer_2_raw_int_status <= 1'b1; + end + else + begin + if(timer_2_int_clear || timers_int_clear) + begin + timer_2_raw_int_status <= 1'b0; + end + end + end + else + begin + timer_2_raw_int_status <= 1'b0; + end + end +end + +//========================================================== +// Timer 3 interrupt set and clear +//========================================================== +assign timer_3_int_status = timer_3_raw_int_status && !timer_3_control_reg[2]; +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_3_raw_int_status <= 1'b0; + end + else + begin + if(timer_3_control_reg[0]) + begin + if(timer_3_interrupt) + begin + timer_3_raw_int_status <= 1'b1; + end + else + begin + if(timer_3_int_clear || timers_int_clear) + begin + timer_3_raw_int_status <= 1'b0; + end + end + end + else + begin + timer_3_raw_int_status <= 1'b0; + end + end +end + +//========================================================== +// Timer 4 interrupt set and clear +//========================================================== +assign timer_4_int_status = timer_4_raw_int_status && !timer_4_control_reg[2]; +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_4_raw_int_status <= 1'b0; + end + else + begin + if(timer_4_control_reg[0]) + begin + if(timer_4_interrupt) + begin + timer_4_raw_int_status <= 1'b1; + end + else + begin + if(timer_4_int_clear || timers_int_clear) + begin + timer_4_raw_int_status <= 1'b0; + end + end + end + else + begin + timer_4_raw_int_status <= 1'b0; + end + end +end + +// &ModuleEnd; @385 +endmodule + +module counter( + interrupt, + pclk, + presetn, + timer_current_value, + timer_enable, + timer_load_count, + timer_mode +); + +// &Ports; @24 +input pclk; +input presetn; +input timer_enable; +input [31:0] timer_load_count; +input timer_mode; +output interrupt; +output [31:0] timer_current_value; + +// &Regs; @25 +reg [31:0] counter; +reg interrupt; +reg timer_enable_flop; + +// &Wires; @26 +wire load_cnt_en; +wire pclk; +wire presetn; +wire [31:0] timer_current_value; +wire timer_enable; +wire [31:0] timer_load_count; +wire timer_mode; + + +//========================================================== +// Counter +//========================================================== +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + timer_enable_flop <=0; + end + else + begin + timer_enable_flop <=timer_enable ; + end +end + +assign load_cnt_en= (timer_enable && !timer_enable_flop) + || !(|counter[31:0]); + +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + counter[31:0] <=32'hffffffff; + end + else if(load_cnt_en) + begin + if(timer_mode) + begin + counter[31:0]<=timer_load_count[31:0]; + end + else + begin + counter[31:0]<=32'hffffffff; + end + end + else if (timer_enable) + begin + counter[31:0]<=counter[31:0]-1'b1; + end + else + begin + counter[31:0]<=counter[31:0]; + end +end + +assign timer_current_value[31:0]=counter[31:0]; +//========================================================== +// Interrupt sigals +//========================================================== +//internel interrupt +always @(posedge pclk or negedge presetn) +begin + if(!presetn) + begin + interrupt <=1'b0; + end + else if(!{|counter[31:0]}) + begin + interrupt <=1'b1; + end + else + begin + interrupt<=1'b0 ; + end +end + +// &ModuleEnd; @94 +endmodule + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart.v new file mode 100644 index 0000000000000000000000000000000000000000..8bc65c1d81866a73a2d806bd62c11aa3874d6845 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart.v @@ -0,0 +1,239 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module uart( + apb_uart_paddr, + apb_uart_penable, + apb_uart_psel, + apb_uart_pwdata, + apb_uart_pwrite, + rst_b, + s_in, + s_out, + sys_clk, + uart_apb_prdata, + uart_vic_int +); + +// &Ports; @23 +input [31:0] apb_uart_paddr; +input apb_uart_penable; +input apb_uart_psel; +input [31:0] apb_uart_pwdata; +input apb_uart_pwrite; +input rst_b; +input s_in; +input sys_clk; +output s_out; +output [31:0] uart_apb_prdata; +output uart_vic_int; + +// &Regs; @24 + +// &Wires; @25 +wire [31:0] apb_uart_paddr; +wire apb_uart_penable; +wire apb_uart_psel; +wire [31:0] apb_uart_pwdata; +wire apb_uart_pwrite; +wire [15:0] ctrl_baud_gen_divisor; +wire ctrl_baud_gen_set_dllh_vld; +wire [1 :0] ctrl_receive_data_length; +wire ctrl_receive_parity_bit; +wire ctrl_receive_parity_en; +wire ctrl_receive_stop_length; +wire ctrl_reg_busy; +wire ctrl_reg_fe; +wire [3 :0] ctrl_reg_iid; +wire ctrl_reg_iid_vld; +wire ctrl_reg_oe; +wire ctrl_reg_pe; +wire [7 :0] ctrl_reg_rbr_wdata; +wire ctrl_reg_rbr_write_en; +wire ctrl_reg_thr_read; +wire ctrl_reg_thsr_empty; +wire [1 :0] ctrl_trans_data_length; +wire ctrl_trans_parity_bit; +wire ctrl_trans_parity_en; +wire [7 :0] ctrl_trans_shift_data; +wire ctrl_trans_stop_length; +wire ctrl_trans_thr_vld; +wire receive_clk_en; +wire receive_ctrl_busy; +wire receive_ctrl_fe; +wire receive_ctrl_pe; +wire [7 :0] receive_ctrl_rdata; +wire receive_ctrl_redata_over; +wire [15:0] reg_ctrl_dllh_data; +wire [2 :0] reg_ctrl_ier_enable; +wire [1 :0] reg_ctrl_lcr_dls; +wire reg_ctrl_lcr_eps; +wire reg_ctrl_lcr_pen; +wire reg_ctrl_lcr_stop; +wire reg_ctrl_lcr_wen; +wire reg_ctrl_rbr_vld; +wire reg_ctrl_set_dllh_vld; +wire [7 :0] reg_ctrl_thr_data; +wire reg_ctrl_thr_vld; +wire reg_ctrl_threint_en; +wire rst_b; +wire s_in; +wire s_out; +wire sys_clk; +wire trans_clk_en; +wire trans_ctrl_busy; +wire trans_ctrl_thr_read; +wire trans_ctrl_thsr_empty; +wire [31:0] uart_apb_prdata; +wire uart_vic_int; + + + +// &Instance("uart_apb_reg"); @28 +uart_apb_reg x_uart_apb_reg ( + .apb_uart_paddr (apb_uart_paddr ), + .apb_uart_penable (apb_uart_penable ), + .apb_uart_psel (apb_uart_psel ), + .apb_uart_pwdata (apb_uart_pwdata ), + .apb_uart_pwrite (apb_uart_pwrite ), + .ctrl_reg_busy (ctrl_reg_busy ), + .ctrl_reg_fe (ctrl_reg_fe ), + .ctrl_reg_iid (ctrl_reg_iid ), + .ctrl_reg_iid_vld (ctrl_reg_iid_vld ), + .ctrl_reg_oe (ctrl_reg_oe ), + .ctrl_reg_pe (ctrl_reg_pe ), + .ctrl_reg_rbr_wdata (ctrl_reg_rbr_wdata ), + .ctrl_reg_rbr_write_en (ctrl_reg_rbr_write_en), + .ctrl_reg_thr_read (ctrl_reg_thr_read ), + .ctrl_reg_thsr_empty (ctrl_reg_thsr_empty ), + .reg_ctrl_dllh_data (reg_ctrl_dllh_data ), + .reg_ctrl_ier_enable (reg_ctrl_ier_enable ), + .reg_ctrl_lcr_dls (reg_ctrl_lcr_dls ), + .reg_ctrl_lcr_eps (reg_ctrl_lcr_eps ), + .reg_ctrl_lcr_pen (reg_ctrl_lcr_pen ), + .reg_ctrl_lcr_stop (reg_ctrl_lcr_stop ), + .reg_ctrl_lcr_wen (reg_ctrl_lcr_wen ), + .reg_ctrl_rbr_vld (reg_ctrl_rbr_vld ), + .reg_ctrl_set_dllh_vld (reg_ctrl_set_dllh_vld), + .reg_ctrl_thr_data (reg_ctrl_thr_data ), + .reg_ctrl_thr_vld (reg_ctrl_thr_vld ), + .reg_ctrl_threint_en (reg_ctrl_threint_en ), + .rst_b (rst_b ), + .sys_clk (sys_clk ), + .uart_apb_prdata (uart_apb_prdata ), + .uart_vic_int (uart_vic_int ) +); + +// &Instance("uart_baud_gen"); @29 +uart_baud_gen x_uart_baud_gen ( + .ctrl_baud_gen_divisor (ctrl_baud_gen_divisor ), + .ctrl_baud_gen_set_dllh_vld (ctrl_baud_gen_set_dllh_vld), + .receive_clk_en (receive_clk_en ), + .rst_b (rst_b ), + .sys_clk (sys_clk ), + .trans_clk_en (trans_clk_en ) +); + +// &Instance("uart_ctrl"); @30 +uart_ctrl x_uart_ctrl ( + .ctrl_baud_gen_divisor (ctrl_baud_gen_divisor ), + .ctrl_baud_gen_set_dllh_vld (ctrl_baud_gen_set_dllh_vld), + .ctrl_receive_data_length (ctrl_receive_data_length ), + .ctrl_receive_parity_bit (ctrl_receive_parity_bit ), + .ctrl_receive_parity_en (ctrl_receive_parity_en ), + .ctrl_receive_stop_length (ctrl_receive_stop_length ), + .ctrl_reg_busy (ctrl_reg_busy ), + .ctrl_reg_fe (ctrl_reg_fe ), + .ctrl_reg_iid (ctrl_reg_iid ), + .ctrl_reg_iid_vld (ctrl_reg_iid_vld ), + .ctrl_reg_oe (ctrl_reg_oe ), + .ctrl_reg_pe (ctrl_reg_pe ), + .ctrl_reg_rbr_wdata (ctrl_reg_rbr_wdata ), + .ctrl_reg_rbr_write_en (ctrl_reg_rbr_write_en ), + .ctrl_reg_thr_read (ctrl_reg_thr_read ), + .ctrl_reg_thsr_empty (ctrl_reg_thsr_empty ), + .ctrl_trans_data_length (ctrl_trans_data_length ), + .ctrl_trans_parity_bit (ctrl_trans_parity_bit ), + .ctrl_trans_parity_en (ctrl_trans_parity_en ), + .ctrl_trans_shift_data (ctrl_trans_shift_data ), + .ctrl_trans_stop_length (ctrl_trans_stop_length ), + .ctrl_trans_thr_vld (ctrl_trans_thr_vld ), + .receive_ctrl_busy (receive_ctrl_busy ), + .receive_ctrl_fe (receive_ctrl_fe ), + .receive_ctrl_pe (receive_ctrl_pe ), + .receive_ctrl_rdata (receive_ctrl_rdata ), + .receive_ctrl_redata_over (receive_ctrl_redata_over ), + .reg_ctrl_dllh_data (reg_ctrl_dllh_data ), + .reg_ctrl_ier_enable (reg_ctrl_ier_enable ), + .reg_ctrl_lcr_dls (reg_ctrl_lcr_dls ), + .reg_ctrl_lcr_eps (reg_ctrl_lcr_eps ), + .reg_ctrl_lcr_pen (reg_ctrl_lcr_pen ), + .reg_ctrl_lcr_stop (reg_ctrl_lcr_stop ), + .reg_ctrl_lcr_wen (reg_ctrl_lcr_wen ), + .reg_ctrl_rbr_vld (reg_ctrl_rbr_vld ), + .reg_ctrl_set_dllh_vld (reg_ctrl_set_dllh_vld ), + .reg_ctrl_thr_data (reg_ctrl_thr_data ), + .reg_ctrl_thr_vld (reg_ctrl_thr_vld ), + .reg_ctrl_threint_en (reg_ctrl_threint_en ), + .rst_b (rst_b ), + .sys_clk (sys_clk ), + .trans_ctrl_busy (trans_ctrl_busy ), + .trans_ctrl_thr_read (trans_ctrl_thr_read ), + .trans_ctrl_thsr_empty (trans_ctrl_thsr_empty ) +); + +// &Instance("uart_trans"); @31 +uart_trans x_uart_trans ( + .ctrl_trans_data_length (ctrl_trans_data_length), + .ctrl_trans_parity_bit (ctrl_trans_parity_bit ), + .ctrl_trans_parity_en (ctrl_trans_parity_en ), + .ctrl_trans_shift_data (ctrl_trans_shift_data ), + .ctrl_trans_stop_length (ctrl_trans_stop_length), + .ctrl_trans_thr_vld (ctrl_trans_thr_vld ), + .rst_b (rst_b ), + .s_out (s_out ), + .sys_clk (sys_clk ), + .trans_clk_en (trans_clk_en ), + .trans_ctrl_busy (trans_ctrl_busy ), + .trans_ctrl_thr_read (trans_ctrl_thr_read ), + .trans_ctrl_thsr_empty (trans_ctrl_thsr_empty ) +); + +// &Instance("uart_receive"); @32 +uart_receive x_uart_receive ( + .ctrl_receive_data_length (ctrl_receive_data_length), + .ctrl_receive_parity_bit (ctrl_receive_parity_bit ), + .ctrl_receive_parity_en (ctrl_receive_parity_en ), + .ctrl_receive_stop_length (ctrl_receive_stop_length), + .ctrl_trans_parity_en (ctrl_trans_parity_en ), + .receive_clk_en (receive_clk_en ), + .receive_ctrl_busy (receive_ctrl_busy ), + .receive_ctrl_fe (receive_ctrl_fe ), + .receive_ctrl_pe (receive_ctrl_pe ), + .receive_ctrl_rdata (receive_ctrl_rdata ), + .receive_ctrl_redata_over (receive_ctrl_redata_over), + .rst_b (rst_b ), + .s_in (s_in ), + .sys_clk (sys_clk ) +); + + +// &ModuleEnd; @34 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart_apb_reg.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_apb_reg.v new file mode 100644 index 0000000000000000000000000000000000000000..bb8f7a7ebad90c8a6fdb8c398fdd4081cb0455ca --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_apb_reg.v @@ -0,0 +1,521 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module uart_apb_reg( + apb_uart_paddr, + apb_uart_penable, + apb_uart_psel, + apb_uart_pwdata, + apb_uart_pwrite, + ctrl_reg_busy, + ctrl_reg_fe, + ctrl_reg_iid, + ctrl_reg_iid_vld, + ctrl_reg_oe, + ctrl_reg_pe, + ctrl_reg_rbr_wdata, + ctrl_reg_rbr_write_en, + ctrl_reg_thr_read, + ctrl_reg_thsr_empty, + reg_ctrl_dllh_data, + reg_ctrl_ier_enable, + reg_ctrl_lcr_dls, + reg_ctrl_lcr_eps, + reg_ctrl_lcr_pen, + reg_ctrl_lcr_stop, + reg_ctrl_lcr_wen, + reg_ctrl_rbr_vld, + reg_ctrl_set_dllh_vld, + reg_ctrl_thr_data, + reg_ctrl_thr_vld, + reg_ctrl_threint_en, + rst_b, + sys_clk, + uart_apb_prdata, + uart_vic_int +); + +// &Ports; @23 +input [31:0] apb_uart_paddr; +input apb_uart_penable; +input apb_uart_psel; +input [31:0] apb_uart_pwdata; +input apb_uart_pwrite; +input ctrl_reg_busy; +input ctrl_reg_fe; +input [3 :0] ctrl_reg_iid; +input ctrl_reg_iid_vld; +input ctrl_reg_oe; +input ctrl_reg_pe; +input [7 :0] ctrl_reg_rbr_wdata; +input ctrl_reg_rbr_write_en; +input ctrl_reg_thr_read; +input ctrl_reg_thsr_empty; +input rst_b; +input sys_clk; +output [15:0] reg_ctrl_dllh_data; +output [2 :0] reg_ctrl_ier_enable; +output [1 :0] reg_ctrl_lcr_dls; +output reg_ctrl_lcr_eps; +output reg_ctrl_lcr_pen; +output reg_ctrl_lcr_stop; +output reg_ctrl_lcr_wen; +output reg_ctrl_rbr_vld; +output reg_ctrl_set_dllh_vld; +output [7 :0] reg_ctrl_thr_data; +output reg_ctrl_thr_vld; +output reg_ctrl_threint_en; +output [31:0] uart_apb_prdata; +output uart_vic_int; + +// &Regs; @24 +reg iid_priv_vld; +reg iir_iid_clr_vld; +reg [7 :0] uart_dlh; +reg [7 :0] uart_dll; +reg [3 :0] uart_ier; +reg [3 :0] uart_iir_iid; +reg [4 :0] uart_lcr; +reg uart_lcr_dlab; +reg uart_lsr_dr; +reg uart_lsr_fe; +reg uart_lsr_oe; +reg uart_lsr_pe; +reg uart_lsr_thre; +reg [7 :0] uart_rbr; +reg [7 :0] uart_reg_data_pre; +reg [7 :0] uart_thr; +reg uart_usr; +reg uart_vic_int; + +// &Wires; @25 +wire ahb_iir_read_vld; +wire ahb_lsr_read_vld; +wire ahb_rbr_read_vld; +wire ahb_usr_read_vld; +wire [31:0] apb_uart_paddr; +wire apb_uart_penable; +wire apb_uart_psel; +wire [31:0] apb_uart_pwdata; +wire apb_uart_pwrite; +wire ctrl_reg_busy; +wire ctrl_reg_fe; +wire [3 :0] ctrl_reg_iid; +wire ctrl_reg_iid_vld; +wire ctrl_reg_oe; +wire ctrl_reg_pe; +wire [7 :0] ctrl_reg_rbr_wdata; +wire ctrl_reg_rbr_write_en; +wire ctrl_reg_thr_read; +wire ctrl_reg_thsr_empty; +wire dllh_en; +wire [7 :0] endian_wdata; +wire iir_iid_write_vld; +wire rd_acc; +wire [15:0] reg_ctrl_dllh_data; +wire [2 :0] reg_ctrl_ier_enable; +wire [1 :0] reg_ctrl_lcr_dls; +wire reg_ctrl_lcr_eps; +wire reg_ctrl_lcr_pen; +wire reg_ctrl_lcr_stop; +wire reg_ctrl_lcr_wen; +wire reg_ctrl_rbr_vld; +wire reg_ctrl_set_dllh_vld; +wire [7 :0] reg_ctrl_thr_data; +wire reg_ctrl_thr_vld; +wire reg_ctrl_threint_en; +wire rst_b; +wire sys_clk; +wire [31:0] uart_apb_prdata; +wire uart_dlh_wen; +wire uart_dll_wen; +wire uart_ier_wen; +wire uart_lcr_wen; +wire uart_lsr_temt; +wire [7 :0] uart_reg_data; +wire [5 :0] uart_reg_haddr; +wire uart_thr_wen; +wire wr_acc; + + +parameter RBR = 6'h00; +parameter THR = 6'h00; +parameter DLL = 6'h00; +parameter DLH = 6'h01; +parameter IER = 6'h01; +parameter IIR = 6'h02; +parameter LCR = 6'h03; +parameter LSR = 6'h05; +parameter USR = 6'h1f; + +// &Force("bus","apb_uart_paddr",31,0); @37 +// &Force("bus","apb_uart_pwdata",31,0); @38 +// //&Force("output","uart_ahb_hready_resp"); @39 + +//================================================================================== +// write register control signal +//================================================================================== +// define transfer type; +//parameter TRANS_NONSEQ = 2'b10, +// TRANS_SEQ = 2'b11, +// RESP_OKAY = 2'b00, +// RESP_ERROR = 2'b01; +//assign acc_vld = ((ahb_uart_htrans[1:0] == TRANS_NONSEQ) +// || (ahb_uart_htrans[1:0] == TRANS_SEQ)) +// && ahb_uart_hsel && uart_ahb_hready_resp; +// +//assign rd_acc_pre = acc_vld && !ahb_uart_hwrite; +//assign wr_acc_pre = acc_vld && ahb_uart_hwrite; +// +//assign uart_ahb_hresp[1:0] = RESP_OKAY; +// +//parameter S_WRITE = 2'b10; +//parameter S_IDLE = 2'b00; +//parameter S_READ = 2'b01; +//parameter S_RAW = 2'b11; +// +//always @(posedge sys_clk or negedge rst_b) +//begin +// if(!rst_b) +// cur_state[1:0] <= S_IDLE; +// else +// cur_state[1:0] <= next_state[1:0]; +//end +// +//&CombBeg; +//next_state[1:0] = S_IDLE; +//rd_acc = 1'b0; +//casez(cur_state[1:0]) +// S_IDLE, +// S_READ, +// S_RAW: begin +// if(rd_acc_pre) +// begin +// rd_acc = 1'b1; +// next_state[1:0] = S_READ; +// end +// else if(wr_acc_pre) +// next_state[1:0] = S_WRITE; +// end +// S_WRITE: begin +// if(rd_acc_pre) +// next_state[1:0] = S_RAW; +// else if(wr_acc_pre) +// next_state[1:0] = S_WRITE; +// end +// default:next_state[1:0] = 2'bx; +//endcase +//&CombEnd; +// +//assign wr_acc = (cur_state[1:0] == S_WRITE); +// //&Force("output","uart_ahb_hready_resp"); @97 +//assign uart_ahb_hready_resp = ~(cur_state[1:0] == S_RAW); +//assign raw = (cur_state[2:0] == S_RAW); +//assign uart_reg_haddr[5:0] = (wr_acc || raw) +// ? uart_addr_lat[5:0] +// : ahb_uart_haddr[7:2]; +//// latch address +//// for byte or half word operation, data needs to be swapped. +//always @(posedge sys_clk or negedge rst_b) +//begin +// if(!rst_b) +// uart_addr_lat[5:0] <= 14'b0; +// else if(uart_ahb_hready_resp) +// begin +// uart_addr_lat[5:0] <= ahb_uart_haddr[7:2]; +// end +//end + + +//assign endian_wdata[7:0] = i_bigend_b ? ahb_uart_hwdata[7:0] : ahb_uart_hwdata[31:24]; +// &Force("bus","ahb_uart_hwdata",31,0); @117 +assign endian_wdata[7:0] = apb_uart_pwdata[7:0]; +assign wr_acc = apb_uart_psel && apb_uart_pwrite && apb_uart_penable; +assign rd_acc = apb_uart_psel && !apb_uart_pwrite && apb_uart_penable; +assign uart_reg_haddr[5:0] = apb_uart_paddr[7:2]; +//================================================================================== +// ahb write the uart register +//================================================================================== +assign dllh_en = !uart_usr && uart_lcr_dlab; +assign uart_dll_wen = dllh_en && wr_acc && (uart_reg_haddr[5:0] == DLL); +assign uart_dlh_wen = dllh_en && wr_acc && (uart_reg_haddr[5:0] == DLH); +assign uart_thr_wen = !uart_lcr_dlab && wr_acc && (uart_reg_haddr[5:0] == THR); +assign uart_ier_wen = !uart_lcr_dlab && wr_acc && (uart_reg_haddr[5:0] == IER); +assign uart_lcr_wen = wr_acc && (uart_reg_haddr[5:0] == LCR); + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_dll[7:0] <= 8'h0; + else if(uart_dll_wen) + uart_dll[7:0] <= endian_wdata[7:0]; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_dlh[7:0] <= 8'h0; + else if(uart_dlh_wen) + uart_dlh[7:0] <= endian_wdata[7:0]; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_thr[7:0] <= 8'h0; + else if(uart_thr_wen) + uart_thr[7:0] <= endian_wdata[7:0]; +end + + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_ier[3:0] <= 4'h0; + else if(uart_ier_wen) + uart_ier[3:0] <= endian_wdata[3:0] ; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + begin + uart_lcr_dlab <= 1'b0; + uart_lcr[4:0] <= 5'h0; + end + else if(uart_lcr_wen) + begin + uart_lcr_dlab <= endian_wdata[7]; + uart_lcr[4:0] <= endian_wdata[4:0] ; + end + else + begin + uart_lcr_dlab <= uart_lcr_dlab; + uart_lcr[4:0] <= uart_lcr[4:0]; + end +end +//================================================================================== +// ahb read the uart register +//================================================================================== +//always@(posedge sys_clk or negedge rst_b) +//begin +// if(!rst_b) +// uart_reg_data[7:0] <= 8'b0; +// else if(rd_acc) +// uart_reg_data[7:0] <= uart_reg_data_pre[7:0]; +//end +assign uart_reg_data[7:0] = rd_acc ? uart_reg_data_pre[7:0] : 8'bx; +// &CombBeg; @194 +always @( uart_dll[7:0] + or uart_lsr_fe + or uart_ier[2:0] + or uart_dlh[7:0] + or uart_lsr_oe + or uart_iir_iid[3:0] + or uart_rbr[7:0] + or uart_lcr_dlab + or uart_usr + or uart_lsr_pe + or uart_lsr_temt + or uart_reg_haddr[5:0] + or uart_lsr_thre + or uart_lcr[4:0] + or uart_lsr_dr) +begin +case(uart_reg_haddr[5:0]) + RBR: uart_reg_data_pre[7:0] = uart_lcr_dlab ? uart_dll[7:0] : uart_rbr[7:0]; + IER: uart_reg_data_pre[7:0] = uart_lcr_dlab ? uart_dlh[7:0] : {5'b0,uart_ier[2:0]}; + IIR: uart_reg_data_pre[7:0] = {4'b0,uart_iir_iid[3:0]}; + LCR: uart_reg_data_pre[7:0] = {uart_lcr_dlab,2'b0,uart_lcr[4:0]}; + LSR: uart_reg_data_pre[7:0] = {1'b0,uart_lsr_temt,uart_lsr_thre,1'b0, + uart_lsr_fe,uart_lsr_pe,uart_lsr_oe,uart_lsr_dr}; + USR: uart_reg_data_pre[7:0] = {6'b0,uart_usr}; + default:uart_reg_data_pre[7:0] = 8'b0; + endcase +// &CombEnd; @205 +end + +//assign uart_ahb_hrdata[31:24] = i_bigend_b ? 8'b0 : uart_reg_data[7:0]; +assign uart_apb_prdata[31:0] = {24'b0,uart_reg_data[7:0]}; +// &CombBeg; @209 +always @( uart_iir_iid[3:0]) +begin +casez(uart_iir_iid[3:0]) + 4'b0010:uart_vic_int =1'b1; + 4'b0100:uart_vic_int =1'b1; + 4'b0110:uart_vic_int =1'b1; + default: uart_vic_int = 1'b0; +endcase +// &CombEnd; @216 +end +//================================================================================== +// Interface with UART_CTRL +//================================================================================== +//================================================================================== +// UART_CTRL write the uart register +//================================================================================== + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_rbr[7:0] <= 8'b0; + else if(ctrl_reg_rbr_write_en) + uart_rbr[7:0] <= ctrl_reg_rbr_wdata[7:0]; +end + + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_iir_iid[3:0] <= 4'b0001; + else if(iir_iid_write_vld) + uart_iir_iid[3:0] <= ctrl_reg_iid[3:0]; + else if(iir_iid_clr_vld) + uart_iir_iid[3:0] <= 4'b0001; +end + +assign iir_iid_write_vld = ctrl_reg_iid_vld && iid_priv_vld; + +// &CombBeg; @245 +always @( uart_iir_iid[3:0] + or ctrl_reg_iid[2:0]) +begin + casez(uart_iir_iid[3:0]) + 4'b0001: iid_priv_vld = 1'b1; + 4'b0111: iid_priv_vld = 1'b1; + 4'b0010: iid_priv_vld = (ctrl_reg_iid[2] && !ctrl_reg_iid[0]) ? 1 : 0; + 4'b0100: iid_priv_vld = (ctrl_reg_iid[2:0] == 3'b110) ? 1 : 0; + 4'b0110: iid_priv_vld = 1'b0; + default: iid_priv_vld = 1'b0; + endcase +// &CombEnd; @254 +end + + +// &CombBeg; @257 +always @( ahb_rbr_read_vld + or uart_iir_iid[3:0] + or ahb_lsr_read_vld + or uart_lsr_thre + or ahb_iir_read_vld + or ahb_usr_read_vld) +begin + casez(uart_iir_iid[3:0]) + 4'b0010: iir_iid_clr_vld = !uart_lsr_thre || ahb_iir_read_vld; + 4'b0100: iir_iid_clr_vld = ahb_rbr_read_vld; + 4'b0110: iir_iid_clr_vld = ahb_lsr_read_vld; + 4'b0111: iir_iid_clr_vld = ahb_usr_read_vld; + default: iir_iid_clr_vld = 1'b0; + endcase +// &CombEnd; @265 +end + + +assign ahb_iir_read_vld = rd_acc && ( uart_reg_haddr[5:0] == IIR ); +assign ahb_lsr_read_vld = rd_acc && ( uart_reg_haddr[5:0] == LSR ); +assign ahb_usr_read_vld = rd_acc && ( uart_reg_haddr[5:0] == USR ); +assign ahb_rbr_read_vld = rd_acc && !uart_lcr_dlab &&( uart_reg_haddr[5:0] == RBR); + + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + begin + uart_lsr_thre <= 1'b1; + end + else if(uart_thr_wen) + begin + uart_lsr_thre <= 1'b0; + end + else if(ctrl_reg_thr_read) + begin + uart_lsr_thre <= 1'b1; + end +end + +assign uart_lsr_temt = ctrl_reg_thsr_empty && uart_lsr_thre; + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_lsr_dr <= 1'b0; + else if(ctrl_reg_rbr_write_en && !uart_lsr_pe && !uart_lsr_fe) + uart_lsr_dr <= 1'b1; + else if(ahb_rbr_read_vld ) + uart_lsr_dr <= 1'b0; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_lsr_fe <= 1'b0; + else if(ctrl_reg_fe) + uart_lsr_fe <= 1'b1; + else if( ahb_lsr_read_vld ) + uart_lsr_fe <= 1'b0; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_lsr_pe <= 1'b0; + else if(ctrl_reg_pe) + uart_lsr_pe <= 1'b1; + else if( ahb_lsr_read_vld ) + uart_lsr_pe <= 1'b0; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_lsr_oe <= 1'b0; + else if(ctrl_reg_oe) + uart_lsr_oe <= 1'b1; + else if( ahb_lsr_read_vld ) + uart_lsr_oe <= 1'b0; +end + +always @(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + uart_usr <= 1'b0; + else if(ctrl_reg_busy) + uart_usr <= 1'b1; + else if(!ctrl_reg_busy) + uart_usr <= 1'b0; +end + +//================================================================================== +// Interface with UART_CTRL +//================================================================================== +assign reg_ctrl_thr_vld = !uart_lsr_thre; +assign reg_ctrl_thr_data[7:0] = uart_thr[7:0]; +assign reg_ctrl_ier_enable[2:0] = uart_ier[2:0]; +assign reg_ctrl_dllh_data[15:0] = {uart_dlh[7:0],uart_dll[7:0]}; +assign reg_ctrl_lcr_eps = uart_lcr[4]; +assign reg_ctrl_lcr_pen = uart_lcr[3]; +assign reg_ctrl_lcr_stop = uart_lcr[2]; +assign reg_ctrl_lcr_dls[1:0] = uart_lcr[1:0]; +assign reg_ctrl_rbr_vld = uart_lsr_dr; +assign reg_ctrl_lcr_wen = uart_lcr_wen; +assign reg_ctrl_set_dllh_vld = uart_dlh_wen || uart_dll_wen; +assign reg_ctrl_threint_en = uart_ier_wen && endian_wdata[1]; + +// &ModuleEnd; @358 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart_baud_gen.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_baud_gen.v new file mode 100644 index 0000000000000000000000000000000000000000..594329f020cb6ca3d87c26d354c267b3bca8cfa7 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_baud_gen.v @@ -0,0 +1,160 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @23 +module uart_baud_gen( + ctrl_baud_gen_divisor, + ctrl_baud_gen_set_dllh_vld, + receive_clk_en, + rst_b, + sys_clk, + trans_clk_en +); + +// &Ports; @24 +input [15:0] ctrl_baud_gen_divisor; +input ctrl_baud_gen_set_dllh_vld; +input rst_b; +input sys_clk; +output receive_clk_en; +output trans_clk_en; + +// &Regs; @25 +reg [15:0] clk_counter; +reg receive_clk_en; +reg [3 :0] trans_clk_counter; + +// &Wires; @26 +wire clk_divisor_start_en; +wire clk_negedge_en; +wire [15:0] ctrl_baud_gen_divisor; +wire ctrl_baud_gen_set_dllh_vld; +wire divisor_more_then_3; +wire rst_b; +wire sys_clk; +wire trans_clk_en; +wire trans_clk_posedge_en; + + +// //&Force("output","receive_clk"); @28 +// //&Force("output","trans_clk"); @29 + +//--------------------------------------- +// divisor == 1 +//--------------------------------------- +//assign clk_divisor_1 = sys_clk; + +//--------------------------------------- +// divisor == 2 +//--------------------------------------- +//always@(posedge sys_clk or negedge rst_b) +//begin +// if(!rst_b) +// clk_divisor_2 <= 1'b0; +// else +// clk_divisor_2 <= ~clk_divisor_2; +//end +// +//--------------------------------------- +// divisor >= 3 +//--------------------------------------- +assign clk_divisor_start_en = |ctrl_baud_gen_divisor[15:0]; +//assign clk_posedge_en = (clk_counter[15:0] == 16'b10) ? 1 : 0; +assign clk_negedge_en = (clk_counter[15:0] == ctrl_baud_gen_divisor[15:0]) ? 1 : 0 ; + +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + clk_counter[15:0] <= 16'b1; + else if(ctrl_baud_gen_set_dllh_vld) + clk_counter[15:0] <= 16'b1; + else if(clk_negedge_en) + clk_counter[15:0] <= 1'b1; + else if(clk_divisor_start_en) + clk_counter[15:0] <= clk_counter[15:0]+1; + else + clk_counter[15:0] <= clk_counter[15:0]; +end +//always@(posedge sys_clk or negedge rst_b) +//begin +// if(!rst_b) +// clk_divisor_more <= 1'b0; +// else if(clk_posedge_en) +// clk_divisor_more <= 1'b1; +// else if(clk_negedge_en) +// clk_divisor_more <= 1'b0; +// else +// clk_divisor_more <= clk_divisor_more; +//end + +//---------------------------------------- +// receive clk +//---------------------------------------- + +assign divisor_more_then_3 = |ctrl_baud_gen_divisor[15:2]; + +// &CombBeg; @85 +always @( ctrl_baud_gen_divisor[1:0] + or clk_negedge_en + or divisor_more_then_3) +begin +casez({divisor_more_then_3,ctrl_baud_gen_divisor[1:0]}) + 3'b000: receive_clk_en = 1'b0; + 3'b001: receive_clk_en = 1'b1; + 3'b010: receive_clk_en = clk_negedge_en; + 3'b011, + 3'b1??: receive_clk_en = clk_negedge_en; + default: receive_clk_en = 1'b0; +endcase +// &CombEnd; @94 +end +// &Force("output","receive_clk_en"); @95 +//assign receive_clk = receive_clk_reg; +//---------------------------------------- +// trans_clk +//---------------------------------------- + +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + trans_clk_counter[3:0] <= 4'b0; + else if(receive_clk_en) + trans_clk_counter[3:0] <= trans_clk_counter[3:0] + 1'b1; + else + trans_clk_counter[3:0] <= trans_clk_counter[3:0]; +end + +assign trans_clk_posedge_en = (trans_clk_counter[3:0] == 4'b1111) ? 1 : 0; +//assign trans_clk_negedge_en = !(|trans_clk_counter[3:0]); +assign trans_clk_en = receive_clk_en && trans_clk_posedge_en; + +//always@(posedge receive_clk or negedge rst_b) +//begin +// if(!rst_b) +// trans_clk_reg <= 1'b0; +// else if(trans_clk_posedge_en) +// trans_clk_reg <= 1'b1; +// else if(trans_clk_negedge_en) +// trans_clk_reg <= 1'b0; +// else +// trans_clk_reg <= trans_clk_reg; +//end + +//assign trans_clk = trans_clk_reg; + +// &ModuleEnd; @129 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart_ctrl.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..aa3abf32e474a821dee09c756ead2e9207ed0bde --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_ctrl.v @@ -0,0 +1,308 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module uart_ctrl( + ctrl_baud_gen_divisor, + ctrl_baud_gen_set_dllh_vld, + ctrl_receive_data_length, + ctrl_receive_parity_bit, + ctrl_receive_parity_en, + ctrl_receive_stop_length, + ctrl_reg_busy, + ctrl_reg_fe, + ctrl_reg_iid, + ctrl_reg_iid_vld, + ctrl_reg_oe, + ctrl_reg_pe, + ctrl_reg_rbr_wdata, + ctrl_reg_rbr_write_en, + ctrl_reg_thr_read, + ctrl_reg_thsr_empty, + ctrl_trans_data_length, + ctrl_trans_parity_bit, + ctrl_trans_parity_en, + ctrl_trans_shift_data, + ctrl_trans_stop_length, + ctrl_trans_thr_vld, + receive_ctrl_busy, + receive_ctrl_fe, + receive_ctrl_pe, + receive_ctrl_rdata, + receive_ctrl_redata_over, + reg_ctrl_dllh_data, + reg_ctrl_ier_enable, + reg_ctrl_lcr_dls, + reg_ctrl_lcr_eps, + reg_ctrl_lcr_pen, + reg_ctrl_lcr_stop, + reg_ctrl_lcr_wen, + reg_ctrl_rbr_vld, + reg_ctrl_set_dllh_vld, + reg_ctrl_thr_data, + reg_ctrl_thr_vld, + reg_ctrl_threint_en, + rst_b, + sys_clk, + trans_ctrl_busy, + trans_ctrl_thr_read, + trans_ctrl_thsr_empty +); + +// &Ports; @23 +input receive_ctrl_busy; +input receive_ctrl_fe; +input receive_ctrl_pe; +input [7 :0] receive_ctrl_rdata; +input receive_ctrl_redata_over; +input [15:0] reg_ctrl_dllh_data; +input [2 :0] reg_ctrl_ier_enable; +input [1 :0] reg_ctrl_lcr_dls; +input reg_ctrl_lcr_eps; +input reg_ctrl_lcr_pen; +input reg_ctrl_lcr_stop; +input reg_ctrl_lcr_wen; +input reg_ctrl_rbr_vld; +input reg_ctrl_set_dllh_vld; +input [7 :0] reg_ctrl_thr_data; +input reg_ctrl_thr_vld; +input reg_ctrl_threint_en; +input rst_b; +input sys_clk; +input trans_ctrl_busy; +input trans_ctrl_thr_read; +input trans_ctrl_thsr_empty; +output [15:0] ctrl_baud_gen_divisor; +output ctrl_baud_gen_set_dllh_vld; +output [1 :0] ctrl_receive_data_length; +output ctrl_receive_parity_bit; +output ctrl_receive_parity_en; +output ctrl_receive_stop_length; +output ctrl_reg_busy; +output ctrl_reg_fe; +output [3 :0] ctrl_reg_iid; +output ctrl_reg_iid_vld; +output ctrl_reg_oe; +output ctrl_reg_pe; +output [7 :0] ctrl_reg_rbr_wdata; +output ctrl_reg_rbr_write_en; +output ctrl_reg_thr_read; +output ctrl_reg_thsr_empty; +output [1 :0] ctrl_trans_data_length; +output ctrl_trans_parity_bit; +output ctrl_trans_parity_en; +output [7 :0] ctrl_trans_shift_data; +output ctrl_trans_stop_length; +output ctrl_trans_thr_vld; + +// &Regs; @24 +reg ctrl_rbr_write_en_sample; +reg [3 :0] ctrl_reg_iid; +reg [7 :0] ctrl_reg_rbr_wdata; +reg receive_ctrl_fe_sample; +reg receive_ctrl_pe_sample; +reg thr_read_sample; + +// &Wires; @25 +wire [15:0] ctrl_baud_gen_divisor; +wire ctrl_baud_gen_set_dllh_vld; +wire [1 :0] ctrl_receive_data_length; +wire ctrl_receive_parity_bit; +wire ctrl_receive_parity_en; +wire ctrl_receive_stop_length; +wire ctrl_reg_busy; +wire ctrl_reg_fe; +wire ctrl_reg_iid_vld; +wire ctrl_reg_oe; +wire ctrl_reg_pe; +wire ctrl_reg_rbr_write_en; +wire ctrl_reg_thr_read; +wire ctrl_reg_thsr_empty; +wire [1 :0] ctrl_trans_data_length; +wire ctrl_trans_parity_bit; +wire ctrl_trans_parity_en; +wire [7 :0] ctrl_trans_shift_data; +wire ctrl_trans_stop_length; +wire ctrl_trans_thr_vld; +wire high_pri; +wire int_vld; +wire line_status_int; +wire receive_ctrl_busy; +wire receive_ctrl_fe; +wire receive_ctrl_pe; +wire [7 :0] receive_ctrl_rdata; +wire receive_ctrl_redata_over; +wire receive_data_int; +wire [15:0] reg_ctrl_dllh_data; +wire [2 :0] reg_ctrl_ier_enable; +wire [1 :0] reg_ctrl_lcr_dls; +wire reg_ctrl_lcr_eps; +wire reg_ctrl_lcr_pen; +wire reg_ctrl_lcr_stop; +wire reg_ctrl_lcr_wen; +wire reg_ctrl_rbr_vld; +wire reg_ctrl_set_dllh_vld; +wire [7 :0] reg_ctrl_thr_data; +wire reg_ctrl_thr_vld; +wire reg_ctrl_threint_en; +wire rst_b; +wire sys_clk; +wire thre_int_init; +wire trans_ctrl_busy; +wire trans_ctrl_thr_read; +wire trans_ctrl_thsr_empty; +wire trans_hold_empty_int; +wire uart_busy_int; + + +//============================================================== +// generate the transmit enable signal +//============================================================== +assign ctrl_trans_thr_vld = reg_ctrl_thr_vld; +assign ctrl_trans_shift_data[7:0] = reg_ctrl_thr_data[7:0]; +assign ctrl_trans_data_length[1:0] = reg_ctrl_lcr_dls[1:0]; +assign ctrl_trans_stop_length = reg_ctrl_lcr_stop; +assign ctrl_trans_parity_en = reg_ctrl_lcr_pen; +assign ctrl_trans_parity_bit = reg_ctrl_lcr_eps; +//============================================================== +// generate the receive control signal +//============================================================== +assign ctrl_receive_data_length[1:0] = reg_ctrl_lcr_dls[1:0]; +assign ctrl_receive_stop_length = reg_ctrl_lcr_stop; +assign ctrl_receive_parity_en = reg_ctrl_lcr_pen; +assign ctrl_receive_parity_bit = reg_ctrl_lcr_eps; + +//============================================================== +// generate the uart_reg control signal +//============================================================== + +//sample the thr_read signal +always @(posedge sys_clk or negedge rst_b ) +begin + if(!rst_b) + thr_read_sample <= 1'b0; + else + thr_read_sample <= !trans_ctrl_thr_read; +end + +assign ctrl_reg_thr_read = trans_ctrl_thr_read && thr_read_sample; +assign ctrl_reg_thsr_empty = trans_ctrl_thsr_empty; + +//sample the rbr write signal +always @(posedge sys_clk or negedge rst_b ) +begin + if(!rst_b) + ctrl_rbr_write_en_sample <= 1'b0; + else + ctrl_rbr_write_en_sample <= !receive_ctrl_redata_over; +end + +assign ctrl_reg_rbr_write_en = ctrl_rbr_write_en_sample && receive_ctrl_redata_over; + +// thr rbr write data +// &CombBeg; @72 +always @( reg_ctrl_lcr_dls[1:0] + or receive_ctrl_rdata[7:0]) +begin +case(reg_ctrl_lcr_dls[1:0]) + 2'b00: ctrl_reg_rbr_wdata[7:0] = {3'b0,receive_ctrl_rdata[7:3]}; + 2'b01: ctrl_reg_rbr_wdata[7:0] = {2'b0,receive_ctrl_rdata[7:2]}; + 2'b10: ctrl_reg_rbr_wdata[7:0] = {1'b0,receive_ctrl_rdata[7:1]}; + 2'b11: ctrl_reg_rbr_wdata[7:0] = receive_ctrl_rdata[7:0]; + default:ctrl_reg_rbr_wdata[7:0] = 8'b0; +endcase +// &CombEnd; @80 +end + +// generate the busy signale +assign ctrl_reg_busy = trans_ctrl_busy || receive_ctrl_busy; +assign uart_busy_int = ctrl_reg_busy && reg_ctrl_lcr_wen; + + +//sample the fram error signal +always @(posedge sys_clk or negedge rst_b ) +begin + if(!rst_b) + receive_ctrl_fe_sample <= 1'b0; + else + receive_ctrl_fe_sample <= !receive_ctrl_fe; +end + +assign ctrl_reg_fe = receive_ctrl_fe_sample && receive_ctrl_fe; + +//sample the parity error +always @(posedge sys_clk or negedge rst_b ) +begin + if(!rst_b) + receive_ctrl_pe_sample <= 1'b0; + else + receive_ctrl_pe_sample <= !receive_ctrl_pe; +end + +assign ctrl_reg_pe = receive_ctrl_pe_sample && receive_ctrl_pe; + +//generate the over run signal +assign ctrl_reg_oe = reg_ctrl_rbr_vld && ctrl_reg_rbr_write_en; + +// &Force("output","ctrl_reg_thr_read"); @112 +// &Force("output","ctrl_reg_busy"); @113 +// &Force("output","ctrl_reg_rbr_write_en"); @114 +// &Force("output","ctrl_reg_oe"); @115 +// &Force("output","ctrl_reg_pe"); @116 +// &Force("output","ctrl_reg_fe"); @117 + + +// generate the interrupt valid signal +assign int_vld = high_pri + || receive_data_int + || trans_hold_empty_int + || uart_busy_int ; + +assign ctrl_reg_iid_vld = int_vld; + +//generate the interrupt ID +assign high_pri = ctrl_reg_pe || ctrl_reg_fe || ctrl_reg_oe; + +assign line_status_int = high_pri && reg_ctrl_ier_enable[2]; +assign receive_data_int = ctrl_reg_rbr_write_en && reg_ctrl_ier_enable[0]; +assign trans_hold_empty_int = (ctrl_reg_thr_read && reg_ctrl_ier_enable[1]) + ||thre_int_init; +assign thre_int_init = reg_ctrl_threint_en && !reg_ctrl_thr_vld; +// &CombBeg; @136 +always @( uart_busy_int + or trans_hold_empty_int + or line_status_int + or receive_data_int) +begin +casez({line_status_int,receive_data_int,trans_hold_empty_int,uart_busy_int}) + 4'b1???: ctrl_reg_iid[3:0] = 4'b0110; + 4'b01??: ctrl_reg_iid[3:0] = 4'b0100; + 4'b001?: ctrl_reg_iid[3:0] = 4'b0010; + 4'b0001: ctrl_reg_iid[3:0] = 4'b0111; + default: ctrl_reg_iid[3:0] = 4'b0001; +endcase +// &CombEnd; @144 +end + +//============================================================== +// generate the baud clock control signal +//============================================================== +assign ctrl_baud_gen_divisor[15:0] = reg_ctrl_dllh_data[15:0]; +assign ctrl_baud_gen_set_dllh_vld = reg_ctrl_set_dllh_vld; +// &ModuleEnd; @151 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart_receive.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_receive.v new file mode 100644 index 0000000000000000000000000000000000000000..1260a82eb70186bbcf3df6c868cf2dcd2d00c599 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_receive.v @@ -0,0 +1,313 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module uart_receive( + ctrl_receive_data_length, + ctrl_receive_parity_bit, + ctrl_receive_parity_en, + ctrl_receive_stop_length, + ctrl_trans_parity_en, + receive_clk_en, + receive_ctrl_busy, + receive_ctrl_fe, + receive_ctrl_pe, + receive_ctrl_rdata, + receive_ctrl_redata_over, + rst_b, + s_in, + sys_clk +); + +// &Ports; @23 +input [1:0] ctrl_receive_data_length; +input ctrl_receive_parity_bit; +input ctrl_receive_parity_en; +input ctrl_receive_stop_length; +input ctrl_trans_parity_en; +input receive_clk_en; +input rst_b; +input s_in; +input sys_clk; +output receive_ctrl_busy; +output receive_ctrl_fe; +output receive_ctrl_pe; +output [7:0] receive_ctrl_rdata; +output receive_ctrl_redata_over; + +// &Regs; @24 +reg [3:0] counter; +reg [5:0] cur_state; +reg [2:0] da_conter; +reg di_reg1; +reg di_reg2; +reg fram_error; +reg [5:0] next_state; +reg parity_cout; +reg [7:0] receive_shift_reg; +reg sync1; +reg sync2; + +// &Wires; @25 +wire cont_16; +wire cont_8; +wire [1:0] ctrl_receive_data_length; +wire ctrl_receive_parity_bit; +wire ctrl_receive_parity_en; +wire ctrl_receive_stop_length; +wire ctrl_trans_parity_en; +wire data_over; +wire di_rx_in; +wire receive_clk_en; +wire receive_ctrl_busy; +wire receive_ctrl_fe; +wire receive_ctrl_pe; +wire [7:0] receive_ctrl_rdata; +wire receive_ctrl_redata_over; +wire rst_b; +wire rx_in; +wire s_in; +wire stop_over; +wire sys_clk; + + +parameter IDLE = 6'b000001, + START = 6'b000010, + DATA = 6'b000100, + PARITY = 6'b001000, + STOP = 6'b010000, + CLECT_SIG = 6'b100000; + +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + cur_state[5:0] <= IDLE; + else if(receive_clk_en) + cur_state[5:0] <= next_state[5:0]; +end + +////////////////////////////////////////////////////////// +////////////// midified by huawm, 2016-2-26 ////////////// +////////////////////////////////////////////////////////// +always @(posedge sys_clk or negedge rst_b) +begin + if(rst_b == 1'b0) + begin + sync1 <= 1'b1; + sync2 <= 1'b1; + end + else + begin + sync1 <= s_in; + sync2 <= sync1; + end +end +assign rx_in = sync2; + +//------------------------------------------------------- +// data integrity, the best two out of three samples will +// give the resulting serial input that will be passed to +// the RX FSM +// ------------------------------------------------------ +always @(posedge sys_clk or negedge rst_b) +begin + if(rst_b == 1'b0) + begin + di_reg1 <= 1'b1; + di_reg2 <= 1'b1; + end + else if(receive_clk_en) + begin + di_reg1 <= rx_in; + di_reg2 <= di_reg1; + end +end +assign di_rx_in = (rx_in & di_reg1) | (rx_in & di_reg2) | (di_reg1 & di_reg2); + +/////////////////////////////////////////////////////// + +// &CombBeg; @82 +always @( di_rx_in + or stop_over + or cur_state[5:0] + or cont_8 + or cont_16 + or data_over + or ctrl_trans_parity_en) +begin +next_state[5:0] = IDLE; +case(cur_state[5:0]) + IDLE: + begin + if(!di_rx_in) + next_state[5:0] = START; + end + START: + begin + if(cont_8) + begin + if(!di_rx_in) + next_state[5:0] = DATA; + end + else + next_state[5:0] = START; + end + DATA: + begin + if(cont_16 && data_over) + next_state[5:0] = ctrl_trans_parity_en ? PARITY : STOP; + else + next_state[5:0] = DATA; + end + PARITY: + begin + if(cont_16) + next_state[5:0] = STOP; + else + next_state[5:0] = PARITY; + end + STOP: + begin + if(cont_16 && stop_over) + begin + next_state[5:0] = CLECT_SIG; + end + else + next_state[5:0] = STOP; + end + CLECT_SIG: + next_state[5:0] = IDLE; + default: next_state[5:0] = IDLE; +endcase +// &CombEnd; @127 +end + + +// the clock counter +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + counter[3:0] <= 4'b0; + else if(receive_clk_en) + begin + if( (cur_state[0]) || ((cur_state[1]) && cont_8)) + counter[3:0] <= 4'b0; + else + counter[3:0] <= counter[3:0] + 1; + end +end + +assign cont_8 = (counter[3:0] == 4'b0111); +assign cont_16 = (counter[3:0] == 4'b1111); + + +//the data and the stop bit counter +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + da_conter[2:0] <= 2'b0; + else if(receive_clk_en) + begin + if((data_over || stop_over)&& cont_16) + da_conter[2:0] <= 2'b0; + else if(((cur_state[2]) ||(cur_state[4])) && cont_16) + da_conter[2:0] <= da_conter[2:0] + 1'b1; + end +end + +assign data_over = (da_conter[2:0] == {1'b1,ctrl_receive_data_length[1:0]}); +assign stop_over = (cur_state[4]) && (da_conter[2:0] == {2'b0,ctrl_receive_stop_length}); + +//============================================================== +// generate the output s_out signal +//============================================================== +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + receive_shift_reg[7:0] <= 8'b0; + else if(receive_clk_en) + begin + if((cur_state[2])&& cont_16) + receive_shift_reg[7:0] <= {di_rx_in,receive_shift_reg[7:1]}; + else if((cur_state[0])) + receive_shift_reg[7:0] <= 8'b0; + end +end + +assign receive_ctrl_rdata[7:0] = receive_shift_reg[7:0]; + + + +// generate the receive busy signal +assign receive_ctrl_busy = ~(cur_state[0]); + +//receive the parity and check the parity +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + parity_cout <= 1'b0; + else if(receive_clk_en) + begin + if((cur_state[2]) || (cur_state[3])) + begin + if(cont_16) + parity_cout <= parity_cout ^ di_rx_in; + else + parity_cout <= parity_cout; + end + else if(cur_state[4] || cur_state[5]) + parity_cout <= parity_cout; + else + parity_cout <= 1'b0; + end +end + + +//generate the fram error signal +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + fram_error <= 1'b0; + else if((cur_state[4])) + begin + if(fram_error == 1'b1) + fram_error <= fram_error; + else if(cont_16) + fram_error <= ~di_rx_in; + else + fram_error <= fram_error; + end + else if(cur_state[5]) + fram_error <= fram_error; + else + fram_error <= 1'b0; +end + + +// the parity error bit +assign receive_ctrl_pe = (~(parity_cout ^ ctrl_receive_parity_bit)) && ctrl_receive_parity_en && (cur_state[5]); +//the frame error bit +assign receive_ctrl_fe = fram_error && (cur_state[5]); +//generate the data receive control signal +// &Force("output","receive_ctrl_pe"); @236 + +assign receive_ctrl_redata_over = cur_state[5] && !fram_error && !receive_ctrl_pe; + + +// &ModuleEnd; @241 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/uart/uart_trans.v b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_trans.v new file mode 100644 index 0000000000000000000000000000000000000000..9df943ade7f8a3f1e2e4bfbc5a54e144b70347fd --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/uart/uart_trans.v @@ -0,0 +1,245 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @22 +module uart_trans( + ctrl_trans_data_length, + ctrl_trans_parity_bit, + ctrl_trans_parity_en, + ctrl_trans_shift_data, + ctrl_trans_stop_length, + ctrl_trans_thr_vld, + rst_b, + s_out, + sys_clk, + trans_clk_en, + trans_ctrl_busy, + trans_ctrl_thr_read, + trans_ctrl_thsr_empty +); + +// &Ports; @23 +input [1:0] ctrl_trans_data_length; +input ctrl_trans_parity_bit; +input ctrl_trans_parity_en; +input [7:0] ctrl_trans_shift_data; +input ctrl_trans_stop_length; +input ctrl_trans_thr_vld; +input rst_b; +input sys_clk; +input trans_clk_en; +output s_out; +output trans_ctrl_busy; +output trans_ctrl_thr_read; +output trans_ctrl_thsr_empty; + +// &Regs; @24 +reg [2:0] conter; +reg [4:0] cur_state; +reg [4:0] next_state; +reg parity_cout; +reg s_out; +reg thsr_empty; +reg trans_ctrl_thr_read; +reg [7:0] trans_shift_reg; + +// &Wires; @25 +wire [1:0] ctrl_trans_data_length; +wire ctrl_trans_parity_bit; +wire ctrl_trans_parity_en; +wire [7:0] ctrl_trans_shift_data; +wire ctrl_trans_stop_length; +wire ctrl_trans_thr_vld; +wire data_over; +wire parity_bit; +wire rst_b; +wire stop_over; +wire sys_clk; +wire thsr_shift_over; +wire thsr_wen; +wire trans_clk_en; +wire trans_ctrl_busy; +wire trans_ctrl_thsr_empty; +wire trans_enable; + + +parameter IDLE = 5'b00001, + START = 5'b00010, + DATA = 5'b00100, + PARITY = 5'b01000, + STOP = 5'b10000; + +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + cur_state[4:0] <= IDLE; + else if(trans_clk_en) + cur_state[4:0] <= next_state[4:0]; +end + + +assign trans_enable = !thsr_empty; + +// &CombBeg; @44 +always @( parity_bit + or stop_over + or cur_state[4:0] + or trans_enable + or ctrl_trans_parity_en + or trans_shift_reg[0] + or data_over + or thsr_wen) +begin +s_out = 1'b1; +next_state[4:0] = IDLE; +case(cur_state[4:0]) + IDLE: + begin + if(trans_enable) + next_state[4:0] = START; + end + START: + begin + s_out = 1'b0; + next_state[4:0] = DATA; + end + DATA: + begin + s_out = trans_shift_reg[0]; + if(data_over) + next_state[4:0] = ctrl_trans_parity_en ? PARITY : STOP; + else + next_state[4:0] = DATA; + end + PARITY: + begin + s_out = parity_bit; + next_state[4:0] = STOP; + end + STOP: + begin + s_out = 1'b1; + if(stop_over) + begin + if(thsr_wen) + next_state[4:0] = START; + else + next_state[4:0] = IDLE; + end + else + next_state[4:0] = STOP; + end + default: next_state[4:0] = IDLE; +endcase + +// &CombEnd; @87 +end + +always@(posedge sys_clk or negedge rst_b) +begin + if(!rst_b) + conter[2:0] <= 2'b0; + else if(trans_clk_en) + begin + if(data_over || stop_over) + conter[2:0] <= 2'b0; + else if((cur_state[2]) ||(cur_state[4])) + conter[2:0] <= conter[2:0] + 1'b1; + end +end + +assign data_over = (conter[2:0] == {1'b1,ctrl_trans_data_length[1:0]}); +assign stop_over = (cur_state[4]) && (conter[2:0] == {2'b0,ctrl_trans_stop_length}); + + +//============================================================== +// generate the signal to ctrl +//============================================================== +assign trans_ctrl_busy = !(cur_state[0]); +//always @(posedge trans_clk or negedge rst_b) +//begin +// if(!rst_b) +// stop_state_latch <= 1'b0; +// else +// stop_state_latch <= cur_state[4]; +//end +assign thsr_shift_over = cur_state[4]; +//assign trans_ctrl_shiftreg_over = thsr_shift_over; + +//============================================================== +// generate the output s_out signal +//============================================================== +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + trans_shift_reg[7:0] <= 8'b0; + else if(trans_clk_en) + begin + if((cur_state[2])) + trans_shift_reg[7:0] <= {1'b0,trans_shift_reg[7:1]}; + else if(thsr_wen) + trans_shift_reg[7:0] <= ctrl_trans_shift_data[7:0]; + end +end + +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + thsr_empty <= 1'b1; + else if(trans_clk_en) + begin + if( thsr_wen ) + thsr_empty <= 1'b0; + else if(thsr_shift_over) + thsr_empty <= 1'b1; + end +end + +assign thsr_wen = ctrl_trans_thr_vld && ( thsr_shift_over || thsr_empty); + +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + trans_ctrl_thr_read <= 1'b0; + else if(trans_clk_en) + begin + if( thsr_wen ) + trans_ctrl_thr_read <= 1'b1; + else + trans_ctrl_thr_read <= 1'b0; + end +end + +assign trans_ctrl_thsr_empty = thsr_empty; +always@(posedge sys_clk or negedge rst_b) +begin + if( !rst_b ) + parity_cout <= 1'b0; + else if(trans_clk_en) + begin + if(cur_state[1]) + parity_cout <= 1'b0; + else if( (cur_state[2])) + parity_cout <= parity_cout ^ trans_shift_reg[0]; + end +end + +assign parity_bit = ~(parity_cout ^ ctrl_trans_parity_bit); + +// &ModuleEnd; @180 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/wic/wic.v b/XUANTIE-RV_opene906/smart_run/logical/wic/wic.v new file mode 100644 index 0000000000000000000000000000000000000000..fee5f7bc03e45a4a05617eaec874300ee006d3d5 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/wic/wic.v @@ -0,0 +1,118 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// &ModuleBeg; @28 +module wic( + awake_data, + awake_disable, + awake_enable, + int_cfg, + int_exit, + int_pending, + int_vld, + pad_cpu_rst_b, + pending_clr, + wic_awake_en, + wic_clk +); + +// &Ports; @29 +input awake_data; +input awake_disable; +input awake_enable; +input int_cfg; +input int_exit; +input int_vld; +input pad_cpu_rst_b; +input pending_clr; +input wic_clk; +output int_pending; +output wic_awake_en; + +// &Regs; @30 +reg int_pending; +reg int_vld_ff; +reg wic_awake_en; + +// &Wires; @31 +wire awake_data; +wire awake_disable; +wire awake_enable; +wire int_cfg; +wire int_exit; +wire int_level; +wire int_pulse; +wire int_vld; +wire pad_cpu_rst_b; +wire pending_clr; +wire wic_clk; + + +//always@(posedge wic_clk or negedge pad_cpu_rst_b) +//begin +// if (!pad_cpu_rst_b) +// pending_ctrl_ff <= 1'b0; +// else +// pending_ctrl_ff <= pending_ctrl; +//end + + +always@(posedge wic_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + wic_awake_en <= 1'b0; + else if (awake_enable && awake_data) + wic_awake_en <= 1'b1; + else if (awake_disable && awake_data) + wic_awake_en <= 1'b0; +end +//------------------------------------------------ +// sample level-sensitive interrupt +//------------------------------------------------ + +assign int_level = int_vld && !int_cfg && int_exit; + +//------------------------------------------------ +// sample pulse-sensitive interrupt +//------------------------------------------------ +always@(posedge wic_clk or negedge pad_cpu_rst_b) +begin + if (!pad_cpu_rst_b) + int_vld_ff <= 1'b0; + else + int_vld_ff <= int_vld; +end + +assign int_pulse = int_vld && !int_vld_ff; + +//------------------------------------------------ +// int pending +//------------------------------------------------ +always@(posedge wic_clk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + int_pending <= 1'b0; + else if (!int_cfg) + int_pending <= int_level; + else if (pending_clr) + int_pending <= 1'b0; + else if(int_cfg) + int_pending <= int_pulse; +end +// &ModuleEnd; @98 +endmodule + + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/wic/wic_awake_en_32.v b/XUANTIE-RV_opene906/smart_run/logical/wic/wic_awake_en_32.v new file mode 100644 index 0000000000000000000000000000000000000000..cc7f8b720324499c87f1d9616239c3b8b832961d --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/wic/wic_awake_en_32.v @@ -0,0 +1,863 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &ModuleBeg; @23 +module wic_awake_en_32( + awake_data, + awake_disable, + awake_enable, + int_cfg, + int_exit, + int_pending, + int_vld, + pad_cpu_rst_b, + pending_clr, + wic_awake_en, + wic_clk +); + +// &Ports; @24 +input [31:0] awake_data; +input awake_disable; +input awake_enable; +input [31:0] int_cfg; +input [31:0] int_exit; +input [31:0] int_vld; +input pad_cpu_rst_b; +input [31:0] pending_clr; +input wic_clk; +output [31:0] int_pending; +output [31:0] wic_awake_en; + +// &Regs; @25 + +// &Wires; @26 +wire [31:0] awake_data; +wire awake_disable; +wire awake_enable; +wire [31:0] int_cfg; +wire [31:0] int_exit; +wire [31:0] int_pending; +wire [31:0] int_vld; +wire pad_cpu_rst_b; +wire [31:0] pending_clr; +wire [31:0] wic_awake_en; +wire wic_clk; + +// &Instance("wic", "x_wic_0"); @27 +wic x_wic_0 ( + .awake_data (awake_data[0] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[0] ), + .int_exit (int_exit[0] ), + .int_pending (int_pending[0] ), + .int_vld (int_vld[0] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[0] ), + .wic_awake_en (wic_awake_en[0]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[0] ), @28 +// .int_vld (int_vld[0] ), @29 +// .int_cfg (int_cfg[0] ), @30 +// .int_exit (int_exit[0] ), @31 +// .int_pending (int_pending[0] ), @32 +// .pending_clr (pending_clr[0] ), @33 +// .pending_set (pending_set[0] ), @34 +// .wic_awake_en (wic_awake_en[0] ) @35 +// ); @36 + +// &Instance("wic", "x_wic_1"); @38 +wic x_wic_1 ( + .awake_data (awake_data[1] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[1] ), + .int_exit (int_exit[1] ), + .int_pending (int_pending[1] ), + .int_vld (int_vld[1] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[1] ), + .wic_awake_en (wic_awake_en[1]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[1] ), @39 +// .int_vld (int_vld[1] ), @40 +// .int_cfg (int_cfg[1] ), @41 +// .int_exit (int_exit[1] ), @42 +// .int_pending (int_pending[1] ), @43 +// .pending_clr (pending_clr[1] ), @44 +// .pending_set (pending_set[1] ), @45 +// .wic_awake_en (wic_awake_en[1] ) @46 +// ); @47 + +// &Instance("wic", "x_wic_2"); @49 +wic x_wic_2 ( + .awake_data (awake_data[2] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[2] ), + .int_exit (int_exit[2] ), + .int_pending (int_pending[2] ), + .int_vld (int_vld[2] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[2] ), + .wic_awake_en (wic_awake_en[2]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[2] ), @50 +// .int_vld (int_vld[2] ), @51 +// .int_cfg (int_cfg[2] ), @52 +// .int_exit (int_exit[2] ), @53 +// .int_pending (int_pending[2] ), @54 +// .pending_clr (pending_clr[2] ), @55 +// .pending_set (pending_set[2] ), @56 +// .wic_awake_en (wic_awake_en[2] ) @57 +// ); @58 + +// &Instance("wic", "x_wic_3"); @60 +wic x_wic_3 ( + .awake_data (awake_data[3] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[3] ), + .int_exit (int_exit[3] ), + .int_pending (int_pending[3] ), + .int_vld (int_vld[3] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[3] ), + .wic_awake_en (wic_awake_en[3]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[3] ), @61 +// .int_vld (int_vld[3] ), @62 +// .int_cfg (int_cfg[3] ), @63 +// .int_exit (int_exit[3] ), @64 +// .int_pending (int_pending[3] ), @65 +// .pending_clr (pending_clr[3] ), @66 +// .pending_set (pending_set[3] ), @67 +// .wic_awake_en (wic_awake_en[3] ) @68 +// ); @69 + +// &Instance("wic", "x_wic_4"); @71 +wic x_wic_4 ( + .awake_data (awake_data[4] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[4] ), + .int_exit (int_exit[4] ), + .int_pending (int_pending[4] ), + .int_vld (int_vld[4] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[4] ), + .wic_awake_en (wic_awake_en[4]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[4] ), @72 +// .int_vld (int_vld[4] ), @73 +// .int_cfg (int_cfg[4] ), @74 +// .int_exit (int_exit[4] ), @75 +// .int_pending (int_pending[4] ), @76 +// .pending_clr (pending_clr[4] ), @77 +// .pending_set (pending_set[4] ), @78 +// .wic_awake_en (wic_awake_en[4] ) @79 +// ); @80 + +// &Instance("wic", "x_wic_5"); @82 +wic x_wic_5 ( + .awake_data (awake_data[5] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[5] ), + .int_exit (int_exit[5] ), + .int_pending (int_pending[5] ), + .int_vld (int_vld[5] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[5] ), + .wic_awake_en (wic_awake_en[5]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[5] ), @83 +// .int_vld (int_vld[5] ), @84 +// .int_cfg (int_cfg[5] ), @85 +// .int_exit (int_exit[5] ), @86 +// .int_pending (int_pending[5] ), @87 +// .pending_clr (pending_clr[5] ), @88 +// .pending_set (pending_set[5] ), @89 +// .wic_awake_en (wic_awake_en[5] ) @90 +// ); @91 + +// &Instance("wic", "x_wic_6"); @93 +wic x_wic_6 ( + .awake_data (awake_data[6] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[6] ), + .int_exit (int_exit[6] ), + .int_pending (int_pending[6] ), + .int_vld (int_vld[6] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[6] ), + .wic_awake_en (wic_awake_en[6]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[6] ), @94 +// .int_vld (int_vld[6] ), @95 +// .int_cfg (int_cfg[6] ), @96 +// .int_exit (int_exit[6] ), @97 +// .int_pending (int_pending[6] ), @98 +// .pending_clr (pending_clr[6] ), @99 +// .pending_set (pending_set[6] ), @100 +// .wic_awake_en (wic_awake_en[6] ) @101 +// ); @102 + +// &Instance("wic", "x_wic_7"); @104 +wic x_wic_7 ( + .awake_data (awake_data[7] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[7] ), + .int_exit (int_exit[7] ), + .int_pending (int_pending[7] ), + .int_vld (int_vld[7] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[7] ), + .wic_awake_en (wic_awake_en[7]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[7] ), @105 +// .int_vld (int_vld[7] ), @106 +// .int_cfg (int_cfg[7] ), @107 +// .int_exit (int_exit[7] ), @108 +// .int_pending (int_pending[7] ), @109 +// .pending_clr (pending_clr[7] ), @110 +// .pending_set (pending_set[7] ), @111 +// .wic_awake_en (wic_awake_en[7] ) @112 +// ); @113 + +// &Instance("wic", "x_wic_8"); @115 +wic x_wic_8 ( + .awake_data (awake_data[8] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[8] ), + .int_exit (int_exit[8] ), + .int_pending (int_pending[8] ), + .int_vld (int_vld[8] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[8] ), + .wic_awake_en (wic_awake_en[8]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[8] ), @116 +// .int_vld (int_vld[8] ), @117 +// .int_cfg (int_cfg[8] ), @118 +// .int_exit (int_exit[8] ), @119 +// .int_pending (int_pending[8] ), @120 +// .pending_clr (pending_clr[8] ), @121 +// .pending_set (pending_set[8] ), @122 +// .wic_awake_en (wic_awake_en[8] ) @123 +// ); @124 + +// &Instance("wic", "x_wic_9"); @126 +wic x_wic_9 ( + .awake_data (awake_data[9] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[9] ), + .int_exit (int_exit[9] ), + .int_pending (int_pending[9] ), + .int_vld (int_vld[9] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[9] ), + .wic_awake_en (wic_awake_en[9]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[9] ), @127 +// .int_vld (int_vld[9] ), @128 +// .int_cfg (int_cfg[9] ), @129 +// .int_exit (int_exit[9] ), @130 +// .int_pending (int_pending[9] ), @131 +// .pending_clr (pending_clr[9] ), @132 +// .pending_set (pending_set[9] ), @133 +// .wic_awake_en (wic_awake_en[9] ) @134 +// ); @135 + +// &Instance("wic", "x_wic_10"); @137 +wic x_wic_10 ( + .awake_data (awake_data[10] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[10] ), + .int_exit (int_exit[10] ), + .int_pending (int_pending[10] ), + .int_vld (int_vld[10] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[10] ), + .wic_awake_en (wic_awake_en[10]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[10] ), @138 +// .int_vld (int_vld[10] ), @139 +// .int_cfg (int_cfg[10] ), @140 +// .int_exit (int_exit[10] ), @141 +// .int_pending (int_pending[10] ), @142 +// .pending_clr (pending_clr[10] ), @143 +// .pending_set (pending_set[10] ), @144 +// .wic_awake_en (wic_awake_en[10] ) @145 +// ); @146 + +// &Instance("wic", "x_wic_11"); @148 +wic x_wic_11 ( + .awake_data (awake_data[11] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[11] ), + .int_exit (int_exit[11] ), + .int_pending (int_pending[11] ), + .int_vld (int_vld[11] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[11] ), + .wic_awake_en (wic_awake_en[11]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[11] ), @149 +// .int_vld (int_vld[11] ), @150 +// .int_cfg (int_cfg[11] ), @151 +// .int_exit (int_exit[11] ), @152 +// .int_pending (int_pending[11] ), @153 +// .pending_clr (pending_clr[11] ), @154 +// .pending_set (pending_set[11] ), @155 +// .wic_awake_en (wic_awake_en[11] ) @156 +// ); @157 + +// &Instance("wic", "x_wic_12"); @159 +wic x_wic_12 ( + .awake_data (awake_data[12] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[12] ), + .int_exit (int_exit[12] ), + .int_pending (int_pending[12] ), + .int_vld (int_vld[12] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[12] ), + .wic_awake_en (wic_awake_en[12]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[12] ), @160 +// .int_vld (int_vld[12] ), @161 +// .int_cfg (int_cfg[12] ), @162 +// .int_exit (int_exit[12] ), @163 +// .int_pending (int_pending[12] ), @164 +// .pending_clr (pending_clr[12] ), @165 +// .pending_set (pending_set[12] ), @166 +// .wic_awake_en (wic_awake_en[12] ) @167 +// ); @168 + +// &Instance("wic", "x_wic_13"); @170 +wic x_wic_13 ( + .awake_data (awake_data[13] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[13] ), + .int_exit (int_exit[13] ), + .int_pending (int_pending[13] ), + .int_vld (int_vld[13] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[13] ), + .wic_awake_en (wic_awake_en[13]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[13] ), @171 +// .int_vld (int_vld[13] ), @172 +// .int_cfg (int_cfg[13] ), @173 +// .int_exit (int_exit[13] ), @174 +// .int_pending (int_pending[13] ), @175 +// .pending_clr (pending_clr[13] ), @176 +// .pending_set (pending_set[13] ), @177 +// .wic_awake_en (wic_awake_en[13] ) @178 +// ); @179 + +// &Instance("wic", "x_wic_14"); @181 +wic x_wic_14 ( + .awake_data (awake_data[14] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[14] ), + .int_exit (int_exit[14] ), + .int_pending (int_pending[14] ), + .int_vld (int_vld[14] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[14] ), + .wic_awake_en (wic_awake_en[14]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[14] ), @182 +// .int_vld (int_vld[14] ), @183 +// .int_cfg (int_cfg[14] ), @184 +// .int_exit (int_exit[14] ), @185 +// .int_pending (int_pending[14] ), @186 +// .pending_clr (pending_clr[14] ), @187 +// .pending_set (pending_set[14] ), @188 +// .wic_awake_en (wic_awake_en[14] ) @189 +// ); @190 + +// &Instance("wic", "x_wic_15"); @192 +wic x_wic_15 ( + .awake_data (awake_data[15] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[15] ), + .int_exit (int_exit[15] ), + .int_pending (int_pending[15] ), + .int_vld (int_vld[15] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[15] ), + .wic_awake_en (wic_awake_en[15]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[15] ), @193 +// .int_vld (int_vld[15] ), @194 +// .int_cfg (int_cfg[15] ), @195 +// .int_exit (int_exit[15] ), @196 +// .int_pending (int_pending[15] ), @197 +// .pending_clr (pending_clr[15] ), @198 +// .pending_set (pending_set[15] ), @199 +// .wic_awake_en (wic_awake_en[15] ) @200 +// ); @201 + +// &Instance("wic", "x_wic_16"); @203 +wic x_wic_16 ( + .awake_data (awake_data[16] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[16] ), + .int_exit (int_exit[16] ), + .int_pending (int_pending[16] ), + .int_vld (int_vld[16] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[16] ), + .wic_awake_en (wic_awake_en[16]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[16] ), @204 +// .int_vld (int_vld[16] ), @205 +// .int_cfg (int_cfg[16] ), @206 +// .int_exit (int_exit[16] ), @207 +// .int_pending (int_pending[16] ), @208 +// .pending_clr (pending_clr[16] ), @209 +// .pending_set (pending_set[16] ), @210 +// .wic_awake_en (wic_awake_en[16] ) @211 +// ); @212 + +// &Instance("wic", "x_wic_17"); @214 +wic x_wic_17 ( + .awake_data (awake_data[17] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[17] ), + .int_exit (int_exit[17] ), + .int_pending (int_pending[17] ), + .int_vld (int_vld[17] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[17] ), + .wic_awake_en (wic_awake_en[17]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[17] ), @215 +// .int_vld (int_vld[17] ), @216 +// .int_cfg (int_cfg[17] ), @217 +// .int_exit (int_exit[17] ), @218 +// .int_pending (int_pending[17] ), @219 +// .pending_clr (pending_clr[17] ), @220 +// .pending_set (pending_set[17] ), @221 +// .wic_awake_en (wic_awake_en[17] ) @222 +// ); @223 + +// &Instance("wic", "x_wic_18"); @225 +wic x_wic_18 ( + .awake_data (awake_data[18] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[18] ), + .int_exit (int_exit[18] ), + .int_pending (int_pending[18] ), + .int_vld (int_vld[18] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[18] ), + .wic_awake_en (wic_awake_en[18]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[18] ), @226 +// .int_vld (int_vld[18] ), @227 +// .int_cfg (int_cfg[18] ), @228 +// .int_exit (int_exit[18] ), @229 +// .int_pending (int_pending[18] ), @230 +// .pending_clr (pending_clr[18] ), @231 +// .pending_set (pending_set[18] ), @232 +// .wic_awake_en (wic_awake_en[18] ) @233 +// ); @234 + +// &Instance("wic", "x_wic_19"); @236 +wic x_wic_19 ( + .awake_data (awake_data[19] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[19] ), + .int_exit (int_exit[19] ), + .int_pending (int_pending[19] ), + .int_vld (int_vld[19] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[19] ), + .wic_awake_en (wic_awake_en[19]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[19] ), @237 +// .int_vld (int_vld[19] ), @238 +// .int_cfg (int_cfg[19] ), @239 +// .int_exit (int_exit[19] ), @240 +// .int_pending (int_pending[19] ), @241 +// .pending_clr (pending_clr[19] ), @242 +// .pending_set (pending_set[19] ), @243 +// .wic_awake_en (wic_awake_en[19] ) @244 +// ); @245 + +// &Instance("wic", "x_wic_20"); @247 +wic x_wic_20 ( + .awake_data (awake_data[20] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[20] ), + .int_exit (int_exit[20] ), + .int_pending (int_pending[20] ), + .int_vld (int_vld[20] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[20] ), + .wic_awake_en (wic_awake_en[20]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[20] ), @248 +// .int_vld (int_vld[20] ), @249 +// .int_cfg (int_cfg[20] ), @250 +// .int_exit (int_exit[20] ), @251 +// .int_pending (int_pending[20] ), @252 +// .pending_clr (pending_clr[20] ), @253 +// .pending_set (pending_set[20] ), @254 +// .wic_awake_en (wic_awake_en[20] ) @255 +// ); @256 + +// &Instance("wic", "x_wic_21"); @258 +wic x_wic_21 ( + .awake_data (awake_data[21] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[21] ), + .int_exit (int_exit[21] ), + .int_pending (int_pending[21] ), + .int_vld (int_vld[21] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[21] ), + .wic_awake_en (wic_awake_en[21]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[21] ), @259 +// .int_vld (int_vld[21] ), @260 +// .int_cfg (int_cfg[21] ), @261 +// .int_exit (int_exit[21] ), @262 +// .int_pending (int_pending[21] ), @263 +// .pending_clr (pending_clr[21] ), @264 +// .pending_set (pending_set[21] ), @265 +// .wic_awake_en (wic_awake_en[21] ) @266 +// ); @267 + +// &Instance("wic", "x_wic_22"); @269 +wic x_wic_22 ( + .awake_data (awake_data[22] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[22] ), + .int_exit (int_exit[22] ), + .int_pending (int_pending[22] ), + .int_vld (int_vld[22] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[22] ), + .wic_awake_en (wic_awake_en[22]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[22] ), @270 +// .int_vld (int_vld[22] ), @271 +// .int_cfg (int_cfg[22] ), @272 +// .int_exit (int_exit[22] ), @273 +// .int_pending (int_pending[22] ), @274 +// .pending_clr (pending_clr[22] ), @275 +// .pending_set (pending_set[22] ), @276 +// .wic_awake_en (wic_awake_en[22] ) @277 +// ); @278 + +// &Instance("wic", "x_wic_23"); @280 +wic x_wic_23 ( + .awake_data (awake_data[23] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[23] ), + .int_exit (int_exit[23] ), + .int_pending (int_pending[23] ), + .int_vld (int_vld[23] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[23] ), + .wic_awake_en (wic_awake_en[23]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[23] ), @281 +// .int_vld (int_vld[23] ), @282 +// .int_cfg (int_cfg[23] ), @283 +// .int_exit (int_exit[23] ), @284 +// .int_pending (int_pending[23] ), @285 +// .pending_clr (pending_clr[23] ), @286 +// .pending_set (pending_set[23] ), @287 +// .wic_awake_en (wic_awake_en[23] ) @288 +// ); @289 + +// &Instance("wic", "x_wic_24"); @291 +wic x_wic_24 ( + .awake_data (awake_data[24] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[24] ), + .int_exit (int_exit[24] ), + .int_pending (int_pending[24] ), + .int_vld (int_vld[24] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[24] ), + .wic_awake_en (wic_awake_en[24]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[24] ), @292 +// .int_vld (int_vld[24] ), @293 +// .int_cfg (int_cfg[24] ), @294 +// .int_exit (int_exit[24] ), @295 +// .int_pending (int_pending[24] ), @296 +// .pending_clr (pending_clr[24] ), @297 +// .pending_set (pending_set[24] ), @298 +// .wic_awake_en (wic_awake_en[24] ) @299 +// ); @300 + +// &Instance("wic", "x_wic_25"); @302 +wic x_wic_25 ( + .awake_data (awake_data[25] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[25] ), + .int_exit (int_exit[25] ), + .int_pending (int_pending[25] ), + .int_vld (int_vld[25] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[25] ), + .wic_awake_en (wic_awake_en[25]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[25] ), @303 +// .int_vld (int_vld[25] ), @304 +// .int_cfg (int_cfg[25] ), @305 +// .int_exit (int_exit[25] ), @306 +// .int_pending (int_pending[25] ), @307 +// .pending_clr (pending_clr[25] ), @308 +// .pending_set (pending_set[25] ), @309 +// .wic_awake_en (wic_awake_en[25] ) @310 +// ); @311 + +// &Instance("wic", "x_wic_26"); @313 +wic x_wic_26 ( + .awake_data (awake_data[26] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[26] ), + .int_exit (int_exit[26] ), + .int_pending (int_pending[26] ), + .int_vld (int_vld[26] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[26] ), + .wic_awake_en (wic_awake_en[26]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[26] ), @314 +// .int_vld (int_vld[26] ), @315 +// .int_cfg (int_cfg[26] ), @316 +// .int_exit (int_exit[26] ), @317 +// .int_pending (int_pending[26] ), @318 +// .pending_clr (pending_clr[26] ), @319 +// .pending_set (pending_set[26] ), @320 +// .wic_awake_en (wic_awake_en[26] ) @321 +// ); @322 + +// &Instance("wic", "x_wic_27"); @324 +wic x_wic_27 ( + .awake_data (awake_data[27] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[27] ), + .int_exit (int_exit[27] ), + .int_pending (int_pending[27] ), + .int_vld (int_vld[27] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[27] ), + .wic_awake_en (wic_awake_en[27]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[27] ), @325 +// .int_vld (int_vld[27] ), @326 +// .int_cfg (int_cfg[27] ), @327 +// .int_exit (int_exit[27] ), @328 +// .int_pending (int_pending[27] ), @329 +// .pending_clr (pending_clr[27] ), @330 +// .pending_set (pending_set[27] ), @331 +// .wic_awake_en (wic_awake_en[27] ) @332 +// ); @333 + +// &Instance("wic", "x_wic_28"); @335 +wic x_wic_28 ( + .awake_data (awake_data[28] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[28] ), + .int_exit (int_exit[28] ), + .int_pending (int_pending[28] ), + .int_vld (int_vld[28] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[28] ), + .wic_awake_en (wic_awake_en[28]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[28] ), @336 +// .int_vld (int_vld[28] ), @337 +// .int_cfg (int_cfg[28] ), @338 +// .int_exit (int_exit[28] ), @339 +// .int_pending (int_pending[28] ), @340 +// .pending_clr (pending_clr[28] ), @341 +// .pending_set (pending_set[28] ), @342 +// .wic_awake_en (wic_awake_en[28] ) @343 +// ); @344 + +// &Instance("wic", "x_wic_29"); @346 +wic x_wic_29 ( + .awake_data (awake_data[29] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[29] ), + .int_exit (int_exit[29] ), + .int_pending (int_pending[29] ), + .int_vld (int_vld[29] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[29] ), + .wic_awake_en (wic_awake_en[29]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[29] ), @347 +// .int_vld (int_vld[29] ), @348 +// .int_cfg (int_cfg[29] ), @349 +// .int_exit (int_exit[29] ), @350 +// .int_pending (int_pending[29] ), @351 +// .pending_clr (pending_clr[29] ), @352 +// .pending_set (pending_set[29] ), @353 +// .wic_awake_en (wic_awake_en[29] ) @354 +// ); @355 + +// &Instance("wic", "x_wic_30"); @357 +wic x_wic_30 ( + .awake_data (awake_data[30] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[30] ), + .int_exit (int_exit[30] ), + .int_pending (int_pending[30] ), + .int_vld (int_vld[30] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[30] ), + .wic_awake_en (wic_awake_en[30]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[30] ), @358 +// .int_vld (int_vld[30] ), @359 +// .int_cfg (int_cfg[30] ), @360 +// .int_exit (int_exit[30] ), @361 +// .int_pending (int_pending[30] ), @362 +// .pending_clr (pending_clr[30] ), @363 +// .pending_set (pending_set[30] ), @364 +// .wic_awake_en (wic_awake_en[30] ) @365 +// ); @366 + +// &Instance("wic", "x_wic_31"); @368 +wic x_wic_31 ( + .awake_data (awake_data[31] ), + .awake_disable (awake_disable ), + .awake_enable (awake_enable ), + .int_cfg (int_cfg[31] ), + .int_exit (int_exit[31] ), + .int_pending (int_pending[31] ), + .int_vld (int_vld[31] ), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr[31] ), + .wic_awake_en (wic_awake_en[31]), + .wic_clk (wic_clk ) +); + +// &Connect (.awake_data (awake_data[31] ), @369 +// .int_vld (int_vld[31] ), @370 +// .int_cfg (int_cfg[31] ), @371 +// .int_exit (int_exit[31] ), @372 +// .int_pending (int_pending[31] ), @373 +// .pending_clr (pending_clr[31] ), @374 +// .pending_set (pending_set[31] ), @375 +// .wic_awake_en (wic_awake_en[31] ) @376 +// ); @377 + +// &ModuleEnd; @379 +endmodule + + diff --git a/XUANTIE-RV_opene906/smart_run/logical/wic/wic_top.v b/XUANTIE-RV_opene906/smart_run/logical/wic/wic_top.v new file mode 100644 index 0000000000000000000000000000000000000000..52ba71048b1b7e59a2d27a40c51691db4f2c0f04 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/logical/wic/wic_top.v @@ -0,0 +1,282 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +// &Depend("cpu_cfig.h"); @23 +// &ModuleBeg; @24 +module wic_top( + ctl_xx_awake_enable, + gpio_vic_int, + intraw_vld, + nmi_wake_int_higher, + pad_cpu_rst_b, + pad_vic_int_vld, + pulse_int, + stim_vic_int, + tim1_vic_int, + tim_vic_int, + uart0_vic_int, + wic_clk +); + +// &Ports; @25 +input [31:0] ctl_xx_awake_enable; +input [7 :0] gpio_vic_int; +input [1 :0] nmi_wake_int_higher; +input pad_cpu_rst_b; +input pulse_int; +input [3 :0] stim_vic_int; +input [3 :0] tim1_vic_int; +input [3 :0] tim_vic_int; +input uart0_vic_int; +input wic_clk; +output intraw_vld; +output [31:0] pad_vic_int_vld; + +// &Regs; @26 +reg [31:0] arb_int_ack; +reg [31:0] arb_int_ack_ff; + +// &Wires; @27 +wire [31:0] arb_int_ack_clr; +wire ctim_int_vld; +wire [31:0] ctl_xx_awake_enable; +wire [7 :0] gpio_vic_int; +wire [4 :0] int_ack_vec; +wire [31:0] int_pending; +wire intraw_vld; +wire [1 :0] nmi_wake_int_higher; +wire pad_cpu_rst_b; +wire [31:0] pad_vic_int_cfg; +wire [31:0] pad_vic_int_vld; +wire [31:0] pad_wic_int_cfg; +wire [31:0] pad_wic_int_vld; +wire [31:0] pending_clr; +wire pulse_int; +wire [3 :0] stim_vic_int; +wire [3 :0] tim1_vic_int; +wire [3 :0] tim_vic_int; +wire uart0_vic_int; +wire vec_int; +wire [31:0] wic_awake_en; +wire wic_clk; + + +// &Force("nonport","ctim_int_vld"); @30 +// &Force("nonport","pad_vic_int_cfg"); @31 +assign ctim_int_vld = 0; +// //&Force("bus", "biu_pad_psr", 31, 0); @34 +// &Force("nonport","pad_wic_int_cfg"); @35 +assign vec_int = 1'b0; +assign int_ack_vec[4:0] = 5'b0; + +always @( int_ack_vec[4:0]) +begin + case(int_ack_vec[4:0]) + 5'd0 : arb_int_ack[31:0] = 32'b00000000000000000000000000000001; + 5'd1 : arb_int_ack[31:0] = 32'b00000000000000000000000000000010; + 5'd2 : arb_int_ack[31:0] = 32'b00000000000000000000000000000100; + 5'd3 : arb_int_ack[31:0] = 32'b00000000000000000000000000001000; + 5'd4 : arb_int_ack[31:0] = 32'b00000000000000000000000000010000; + 5'd5 : arb_int_ack[31:0] = 32'b00000000000000000000000000100000; + 5'd6 : arb_int_ack[31:0] = 32'b00000000000000000000000001000000; + 5'd7 : arb_int_ack[31:0] = 32'b00000000000000000000000010000000; + 5'd8 : arb_int_ack[31:0] = 32'b00000000000000000000000100000000; + 5'd9 : arb_int_ack[31:0] = 32'b00000000000000000000001000000000; + 5'd10 : arb_int_ack[31:0] = 32'b00000000000000000000010000000000; + 5'd11 : arb_int_ack[31:0] = 32'b00000000000000000000100000000000; + 5'd12 : arb_int_ack[31:0] = 32'b00000000000000000001000000000000; + 5'd13 : arb_int_ack[31:0] = 32'b00000000000000000010000000000000; + 5'd14 : arb_int_ack[31:0] = 32'b00000000000000000100000000000000; + 5'd15 : arb_int_ack[31:0] = 32'b00000000000000001000000000000000; + 5'd16 : arb_int_ack[31:0] = 32'b00000000000000010000000000000000; + 5'd17 : arb_int_ack[31:0] = 32'b00000000000000100000000000000000; + 5'd18 : arb_int_ack[31:0] = 32'b00000000000001000000000000000000; + 5'd19 : arb_int_ack[31:0] = 32'b00000000000010000000000000000000; + 5'd20 : arb_int_ack[31:0] = 32'b00000000000100000000000000000000; + 5'd21 : arb_int_ack[31:0] = 32'b00000000001000000000000000000000; + 5'd22 : arb_int_ack[31:0] = 32'b00000000010000000000000000000000; + 5'd23 : arb_int_ack[31:0] = 32'b00000000100000000000000000000000; + 5'd24 : arb_int_ack[31:0] = 32'b00000001000000000000000000000000; + 5'd25 : arb_int_ack[31:0] = 32'b00000010000000000000000000000000; + 5'd26 : arb_int_ack[31:0] = 32'b00000100000000000000000000000000; + 5'd27 : arb_int_ack[31:0] = 32'b00001000000000000000000000000000; + 5'd28 : arb_int_ack[31:0] = 32'b00010000000000000000000000000000; + 5'd29 : arb_int_ack[31:0] = 32'b00100000000000000000000000000000; + 5'd30 : arb_int_ack[31:0] = 32'b01000000000000000000000000000000; + 5'd31 : arb_int_ack[31:0] = 32'b10000000000000000000000000000000; + default: arb_int_ack[31:0] = 32'bx; + endcase +end + +assign arb_int_ack_clr[31:0] = vec_int ? arb_int_ack[31:0] : 32'b0; + +always@(posedge wic_clk or negedge pad_cpu_rst_b) +begin + if(!pad_cpu_rst_b) + arb_int_ack_ff[31:0] <= 32'b0; + else + arb_int_ack_ff[31:0] <= arb_int_ack_clr[31:0]; +end + + + +// &Force("nonport", "arb_int_ack"); @92 +// &Force("nonport", "arb_int_ack_ff"); @93 + assign pending_clr[31:0] = arb_int_ack_clr[31:0] & ~arb_int_ack_ff[31:0]; + +//---------------------------------------------------------- +// instantiate wic +//------------------------------------------------------------------------- + +// &Force("nonport", "wic_awake_en"); @120 +// &Force("nonport", "wic_awake_en"); @125 +// &Instance("wic_awake_en_64", "x_wic_awake_en"); @130 +// &Connect(.awake_enable (vic_wic_awake_enable ), @132 +// .awake_disable (vic_wic_awake_disable ), @133 +// .awake_data (vic_wic_awake_data[63:0] ), @134 +// .int_exit (vic_wic_int_exit[63:0] ), @135 +// .pending_set (vic_wic_pending_set[63:0]), @136 +// .pending_clr (vic_wic_pending_clr[63:0]), @137 +// .int_vld (pad_wic_int_vld[63:0] ), @138 +// .int_cfg (pad_wic_int_cfg[63:0] ), @139 +// .wic_awake_en (wic_awake_en[63:0] ), @140 +// .int_pending (int_pending[63:0] ) @141 +// ); @142 +// &Connect(.awake_enable (1'b0 ), @144 +// .awake_disable (1'b0 ), @145 +// .awake_data (64'b0 ), @146 +// .int_exit (64'hffffffff_ffffffff ), @147 +// .pending_set (64'b0 ), @148 +// // .pending_clr (32'b0 ), @149 +// .int_vld (pad_wic_int_vld[63:0] ), @150 +// .int_cfg (pad_wic_int_cfg[63:0] ), @151 +// .wic_awake_en (wic_awake_en[63:0] ), @152 +// .int_pending (int_pending[63:0] ) @153 +// ); @154 + + +assign pad_wic_int_vld[31:0] = {6'b0,tim1_vic_int[3:0],nmi_wake_int_higher[1:0],pulse_int,stim_vic_int[3:0],gpio_vic_int[7:0],1'b0, + tim_vic_int[3:0],ctim_int_vld,uart0_vic_int}; +assign pad_wic_int_cfg[31:0] = {12'b0,1'b1,19'b0}; + +assign intraw_vld =|(int_pending[31:0] & ctl_xx_awake_enable[31:0]); +assign pad_vic_int_vld[31:0] = int_pending[31:0]; +assign pad_vic_int_cfg[31:0] = 32'b0; +// &Force("nonport", "wic_awake_en"); @172 + + +// &Instance("wic_awake_en_32", "x_wic_awake_en"); @176 +wic_awake_en_32 x_wic_awake_en ( + .awake_data (32'b0 ), + .awake_disable (1'b0 ), + .awake_enable (1'b0 ), + .int_cfg (pad_wic_int_cfg[31:0]), + .int_exit (32'hffffffff ), + .int_pending (int_pending[31:0] ), + .int_vld (pad_wic_int_vld[31:0]), + .pad_cpu_rst_b (pad_cpu_rst_b ), + .pending_clr (pending_clr ), + .wic_awake_en (wic_awake_en[31:0] ), + .wic_clk (wic_clk ) +); + +// &Connect(.awake_enable (vic_wic_awake_enable ), @178 +// .awake_disable (vic_wic_awake_disable ), @179 +// .awake_data (vic_wic_awake_data[31:0] ), @180 +// .int_exit (vic_wic_int_exit[31:0] ), @181 +// .pending_set (vic_wic_pending_set[31:0]), @182 +// .pending_clr (vic_wic_pending_clr[31:0]), @183 +// .int_vld (pad_wic_int_vld[31:0] ), @184 +// .int_cfg (pad_wic_int_cfg[31:0] ), @185 +// .wic_awake_en (wic_awake_en[31:0] ), @186 +// .int_pending (int_pending[31:0] ) @187 +// ); @188 +// &Connect(.awake_enable (1'b0 ), @190 +// .awake_disable (1'b0 ), @191 +// .awake_data (32'b0 ), @192 +// .int_exit (32'hffffffff ), @193 +// .pending_set (32'b0 ), @194 +// // .pending_clr (32'b0 ), @195 +// .int_vld (pad_wic_int_vld[31:0] ), @196 +// .int_cfg (pad_wic_int_cfg[31:0] ), @197 +// .wic_awake_en (wic_awake_en[31:0] ), @198 +// .int_pending (int_pending[31:0] ) @199 +// ); @200 + +// &Force("nonport", "wic_awake_en"); @217 +// &Instance("wic_awake_en_16", "x_wic_awake_en"); @221 +// &Connect(.awake_enable (vic_wic_awake_enable ), @223 +// .awake_disable (vic_wic_awake_disable ), @224 +// .awake_data (vic_wic_awake_data[15:0] ), @225 +// .int_exit (vic_wic_int_exit[15:0] ), @226 +// .pending_set (vic_wic_pending_set[15:0]), @227 +// .pending_clr (vic_wic_pending_clr[15:0]), @228 +// .int_vld (pad_wic_int_vld[15:0] ), @229 +// .int_cfg (pad_wic_int_cfg[15:0] ), @230 +// .wic_awake_en (wic_awake_en[15:0] ), @231 +// .int_pending (int_pending[15:0] ) @232 +// ); @233 +// &Connect(.awake_enable (1'b0 ), @235 +// .awake_disable (1'b0 ), @236 +// .awake_data (16'b0 ), @237 +// .int_exit (16'hffff ), @238 +// .pending_set (16'b0 ), @239 +// // .pending_clr (32'b0 ), @240 +// .int_vld (pad_wic_int_vld[15:0] ), @241 +// .int_cfg (pad_wic_int_cfg[15:0] ), @242 +// .wic_awake_en (wic_awake_en[15:0] ), @243 +// .int_pending (int_pending[15:0] ) @244 +// ); @245 + +// &Force("nonport", "wic_awake_en"); @263 +// &Instance("wic_awake_en_8", "x_wic_awake_en"); @267 +// &Connect(.awake_enable (vic_wic_awake_enable ), @269 +// .awake_disable (vic_wic_awake_disable ), @270 +// .awake_data (vic_wic_awake_data[7:0] ), @271 +// .int_exit (vic_wic_int_exit[7:0] ), @272 +// .pending_set (vic_wic_pending_set[7:0]), @273 +// .pending_clr (vic_wic_pending_clr[7:0]), @274 +// .int_vld (pad_wic_int_vld[7:0] ), @275 +// .int_cfg (pad_wic_int_cfg[7:0] ), @276 +// .wic_awake_en (wic_awake_en[7:0] ), @277 +// .int_pending (int_pending[7:0] ) @278 +// ); @279 +// &Connect(.awake_enable (1'b0 ), @281 +// .awake_disable (1'b0 ), @282 +// .awake_data (8'b0 ), @283 +// .int_exit (8'hff ), @284 +// .pending_set (8'b0 ), @285 +// // .pending_clr (32'b0 ), @286 +// .int_vld (pad_wic_int_vld[7:0] ), @287 +// .int_cfg (pad_wic_int_cfg[7:0] ), @288 +// .wic_awake_en (wic_awake_en[7:0] ), @289 +// .int_pending (int_pending[7:0] ) @290 +// ); @291 + +// &ModuleEnd; @295 +endmodule + + + + + + + + + + + + diff --git a/XUANTIE-RV_opene906/smart_run/setup/nc.tcl b/XUANTIE-RV_opene906/smart_run/setup/nc.tcl new file mode 100644 index 0000000000000000000000000000000000000000..795ce41cffd16f06b1d632decdad5a045f9c41ed --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/setup/nc.tcl @@ -0,0 +1,19 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +set probe_packed_limit 65536 +set probe_unpacked_limit 300000 + +run + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_list_join.c b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_list_join.c new file mode 100644 index 0000000000000000000000000000000000000000..bb193e71f8449d34b8db94960f8617771f108539 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_list_join.c @@ -0,0 +1,496 @@ +/* +Author : Shay Gal-On, EEMBC + +This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 +All rights reserved. + +EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the +CoreMark License that is distributed with the official EEMBC COREMARK Software release. +If you received this EEMBC CoreMark Software without the accompanying CoreMark License, +you must discontinue use and download the official release from www.coremark.org. + +Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, +make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. + +EEMBC +4354 Town Center Blvd. Suite 114-200 +El Dorado Hills, CA, 95762 +*/ + +#include "coremark.h" +/* +Topic: Description + Benchmark using a linked list. + + Linked list is a common data structure used in many applications. + + For our purposes, this will excercise the memory units of the processor. + In particular, usage of the list pointers to find and alter data. + + We are not using Malloc since some platforms do not support this library. + + Instead, the memory block being passed in is used to create a list, + and the benchmark takes care not to add more items then can be + accomodated by the memory block. The porting layer will make sure + that we have a valid memory block. + + All operations are done in place, without using any extra memory. + + The list itself contains list pointers and pointers to data items. + Data items contain the following: + + idx - An index that captures the initial order of the list. + data - Variable data initialized based on the input parameters. The 16b are divided as follows: + o Upper 8b are backup of original data. + o Bit 7 indicates if the lower 7 bits are to be used as is or calculated. + o Bits 0-2 indicate type of operation to perform to get a 7b value. + o Bits 3-6 provide input for the operation. + +*/ + +/* local functions */ + +list_head *core_list_find(list_head *list,list_data *info); +list_head *core_list_reverse(list_head *list); +list_head *core_list_remove(list_head *item); +list_head *core_list_undo_remove(list_head *item_removed, list_head *item_modified); +list_head *core_list_insert_new(list_head *insert_point + , list_data *info, list_head **memblock, list_data **datablock + , list_head *memblock_end, list_data *datablock_end); +typedef ee_s32(*list_cmp)(list_data *a, list_data *b, core_results *res); +list_head *core_list_mergesort(list_head *list, list_cmp cmp, core_results *res); + +ee_s16 calc_func(ee_s16 *pdata, core_results *res) { + ee_s16 data=*pdata; + ee_s16 retval; + ee_u8 optype=(data>>7) & 1; /* bit 7 indicates if the function result has been cached */ + if (optype) /* if cached, use cache */ + return (data & 0x007f); + else { /* otherwise calculate and cache the result */ + ee_s16 flag=data & 0x7; /* bits 0-2 is type of function to perform */ + ee_s16 dtype=((data>>3) & 0xf); /* bits 3-6 is specific data for the operation */ + dtype |= dtype << 4; /* replicate the lower 4 bits to get an 8b value */ + switch (flag) { + case 0: + if (dtype<0x22) /* set min period for bit corruption */ + dtype=0x22; + retval=core_bench_state(res->size,res->memblock[3],res->seed1,res->seed2,dtype,res->crc); + if (res->crcstate==0) + res->crcstate=retval; + break; + case 1: + retval=core_bench_matrix(&(res->mat),dtype,res->crc); + if (res->crcmatrix==0) + res->crcmatrix=retval; + break; + default: + retval=data; + break; + } + res->crc=crcu16(retval,res->crc); + retval &= 0x007f; + *pdata = (data & 0xff00) | 0x0080 | retval; /* cache the result */ + return retval; + } +} +/* Function: cmp_complex + Compare the data item in a list cell. + + Can be used by mergesort. +*/ +ee_s32 cmp_complex(list_data *a, list_data *b, core_results *res) { + ee_s16 val1=calc_func(&(a->data16),res); + ee_s16 val2=calc_func(&(b->data16),res); + return val1 - val2; +} + +/* Function: cmp_idx + Compare the idx item in a list cell, and regen the data. + + Can be used by mergesort. +*/ +ee_s32 cmp_idx(list_data *a, list_data *b, core_results *res) { + if (res==NULL) { + a->data16 = (a->data16 & 0xff00) | (0x00ff & (a->data16>>8)); + b->data16 = (b->data16 & 0xff00) | (0x00ff & (b->data16>>8)); + } + return a->idx - b->idx; +} + +void copy_info(list_data *to,list_data *from) { + to->data16=from->data16; + to->idx=from->idx; +} + +/* Benchmark for linked list: + - Try to find multiple data items. + - List sort + - Operate on data from list (crc) + - Single remove/reinsert + * At the end of this function, the list is back to original state +*/ +ee_u16 core_bench_list(core_results *res, ee_s16 finder_idx) { + ee_u16 retval=0; + ee_u16 found=0,missed=0; + list_head *list=res->list; + ee_s16 find_num=res->seed3; + list_head *this_find; + list_head *finder, *remover; + list_data info; + ee_s16 i; + + info.idx=finder_idx; + /* find values in the list, and change the list each time (reverse and cache if value found) */ + for (i=0; inext->info->data16 >> 8) & 1; + } + else { + found++; + if (this_find->info->data16 & 0x1) /* use found value */ + retval+=(this_find->info->data16 >> 9) & 1; + /* and cache next item at the head of the list (if any) */ + if (this_find->next != NULL) { + finder = this_find->next; + this_find->next = finder->next; + finder->next=list->next; + list->next=finder; + } + } + if (info.idx>=0) + info.idx++; +#if CORE_DEBUG + printf("List find %d: [%d,%d,%d]\n",i,retval,missed,found); +#endif + } + retval+=found*4-missed; + /* sort the list by data content and remove one item*/ + if (finder_idx>0) + list=core_list_mergesort(list,cmp_complex,res); + remover=core_list_remove(list->next); + /* CRC data content of list from location of index N forward, and then undo remove */ + finder=core_list_find(list,&info); + if (!finder) + finder=list->next; + while (finder) { + retval=crc16(list->info->data16,retval); + finder=finder->next; + } +#if CORE_DEBUG + printf("List sort 1: %04x\n",retval); +#endif + remover=core_list_undo_remove(remover,list->next); + /* sort the list by index, in effect returning the list to original state */ + list=core_list_mergesort(list,cmp_idx,NULL); + /* CRC data content of list */ + finder=list->next; + while (finder) { + retval=crc16(list->info->data16,retval); + finder=finder->next; + } +#if CORE_DEBUG + printf("List sort 2: %04x\n",retval); +#endif + return retval; +} +/* Function: core_list_init + Initialize list with data. + + Parameters: + blksize - Size of memory to be initialized. + memblock - Pointer to memory block. + seed - Actual values chosen depend on the seed parameter. + The seed parameter MUST be supplied from a source that cannot be determined at compile time + + Returns: + Pointer to the head of the list. + +*/ +list_head *core_list_init(ee_u32 blksize, list_head *memblock, ee_s16 seed) { + /* calculated pointers for the list */ + ee_u32 per_item=16+sizeof(struct list_data_s); + ee_u32 size=(blksize/per_item)-2; /* to accomodate systems with 64b pointers, and make sure same code is executed, set max list elements */ + list_head *memblock_end=memblock+size; + list_data *datablock=(list_data *)(memblock_end); + list_data *datablock_end=datablock+size; + /* some useful variables */ + ee_u32 i; + list_head *finder,*list=memblock; + list_data info; + + /* create a fake items for the list head and tail */ + list->next=NULL; + list->info=datablock; + list->info->idx=0x0000; + list->info->data16=(ee_s16)0x8080; + memblock++; + datablock++; + info.idx=0x7fff; + info.data16=(ee_s16)0xffff; + core_list_insert_new(list,&info,&memblock,&datablock,memblock_end,datablock_end); + + /* then insert size items */ + for (i=0; inext; + i=1; + while (finder->next!=NULL) { + if (iinfo->idx=i++; + else { + ee_u16 pat=(ee_u16)(i++ ^ seed); /* get a pseudo random number */ + finder->info->idx=0x3fff & (((i & 0x07) << 8) | pat); /* make sure the mixed items end up after the ones in sequence */ + } + finder=finder->next; + } + list = core_list_mergesort(list,cmp_idx,NULL); +#if CORE_DEBUG + printf("Initialized list:\n"); + finder=list; + while (finder) { + printf("[%04x,%04x]",finder->info->idx,(ee_u16)finder->info->data16); + finder=finder->next; + } + printf("\n"); +#endif + return list; +} + +/* Function: core_list_insert + Insert an item to the list + + Parameters: + insert_point - where to insert the item. + info - data for the cell. + memblock - pointer for the list header + datablock - pointer for the list data + memblock_end - end of region for list headers + datablock_end - end of region for list data + + Returns: + Pointer to new item. +*/ +list_head *core_list_insert_new(list_head *insert_point, list_data *info, list_head **memblock, list_data **datablock + , list_head *memblock_end, list_data *datablock_end) { + list_head *newitem; + + if ((*memblock+1) >= memblock_end) + return NULL; + if ((*datablock+1) >= datablock_end) + return NULL; + + newitem=*memblock; + (*memblock)++; + newitem->next=insert_point->next; + insert_point->next=newitem; + + newitem->info=*datablock; + (*datablock)++; + copy_info(newitem->info,info); + + return newitem; +} + +/* Function: core_list_remove + Remove an item from the list. + + Operation: + For a singly linked list, remove by copying the data from the next item + over to the current cell, and unlinking the next item. + + Note: + since there is always a fake item at the end of the list, no need to check for NULL. + + Returns: + Removed item. +*/ +list_head *core_list_remove(list_head *item) { + list_data *tmp; + list_head *ret=item->next; + /* swap data pointers */ + tmp=item->info; + item->info=ret->info; + ret->info=tmp; + /* and eliminate item */ + item->next=item->next->next; + ret->next=NULL; + return ret; +} + +/* Function: core_list_undo_remove + Undo a remove operation. + + Operation: + Since we want each iteration of the benchmark to be exactly the same, + we need to be able to undo a remove. + Link the removed item back into the list, and switch the info items. + + Parameters: + item_removed - Return value from the + item_modified - List item that was modified during + + Returns: + The item that was linked back to the list. + +*/ +list_head *core_list_undo_remove(list_head *item_removed, list_head *item_modified) { + list_data *tmp; + /* swap data pointers */ + tmp=item_removed->info; + item_removed->info=item_modified->info; + item_modified->info=tmp; + /* and insert item */ + item_removed->next=item_modified->next; + item_modified->next=item_removed; + return item_removed; +} + +/* Function: core_list_find + Find an item in the list + + Operation: + Find an item by idx (if not 0) or specific data value + + Parameters: + list - list head + info - idx or data to find + + Returns: + Found item, or NULL if not found. +*/ +list_head *core_list_find(list_head *list,list_data *info) { + if (info->idx>=0) { + while (list && (list->info->idx != info->idx)) + list=list->next; + return list; + } else { + while (list && ((list->info->data16 & 0xff) != info->data16)) + list=list->next; + return list; + } +} +/* Function: core_list_reverse + Reverse a list + + Operation: + Rearrange the pointers so the list is reversed. + + Parameters: + list - list head + info - idx or data to find + + Returns: + Found item, or NULL if not found. +*/ + +list_head *core_list_reverse(list_head *list) { + list_head *next=NULL, *tmp; + while (list) { + tmp=list->next; + list->next=next; + next=list; + list=tmp; + } + return next; +} +/* Function: core_list_mergesort + Sort the list in place without recursion. + + Description: + Use mergesort, as for linked list this is a realistic solution. + Also, since this is aimed at embedded, care was taken to use iterative rather then recursive algorithm. + The sort can either return the list to original order (by idx) , + or use the data item to invoke other other algorithms and change the order of the list. + + Parameters: + list - list to be sorted. + cmp - cmp function to use + + Returns: + New head of the list. + + Note: + We have a special header for the list that will always be first, + but the algorithm could theoretically modify where the list starts. + + */ +list_head *core_list_mergesort(list_head *list, list_cmp cmp, core_results *res) { + list_head *p, *q, *e, *tail; + ee_s32 insize, nmerges, psize, qsize, i; + + insize = 1; + + while (1) { + p = list; + list = NULL; + tail = NULL; + + nmerges = 0; /* count number of merges we do in this pass */ + + while (p) { + nmerges++; /* there exists a merge to be done */ + /* step `insize' places along from p */ + q = p; + psize = 0; + for (i = 0; i < insize; i++) { + psize++; + q = q->next; + if (!q) break; + } + + /* if q hasn't fallen off end, we have two lists to merge */ + qsize = insize; + + /* now we have two lists; merge them */ + while (psize > 0 || (qsize > 0 && q)) { + + /* decide whether next element of merge comes from p or q */ + if (psize == 0) { + /* p is empty; e must come from q. */ + e = q; q = q->next; qsize--; + } else if (qsize == 0 || !q) { + /* q is empty; e must come from p. */ + e = p; p = p->next; psize--; + } else if (cmp(p->info,q->info,res) <= 0) { + /* First element of p is lower (or same); e must come from p. */ + e = p; p = p->next; psize--; + } else { + /* First element of q is lower; e must come from q. */ + e = q; q = q->next; qsize--; + } + + /* add the next element to the merged list */ + if (tail) { + tail->next = e; + } else { + list = e; + } + tail = e; + } + + /* now p has stepped `insize' places along, and q has too */ + p = q; + } + + tail->next = NULL; + + /* If we have done only one merge, we're finished. */ + if (nmerges <= 1) /* allow for nmerges==0, the empty list case */ + return list; + + /* Otherwise repeat, merging lists twice the size */ + insize *= 2; + } +#if COMPILER_REQUIRES_SORT_RETURN + return list; +#endif +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_main.c b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9ce756e3631fccfd7f7b0f866bc1688c2c755d75 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_main.c @@ -0,0 +1,424 @@ +/* +Author : Shay Gal-On, EEMBC + +This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 +All rights reserved. + +EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the +CoreMark License that is distributed with the official EEMBC COREMARK Software release. +If you received this EEMBC CoreMark Software without the accompanying CoreMark License, +you must discontinue use and download the official release from www.coremark.org. + +Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, +make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. + +EEMBC +4354 Town Center Blvd. Suite 114-200 +El Dorado Hills, CA, 95762 +*/ +/* File: core_main.c + This file contains the framework to acquire a block of memory, seed initial parameters, tun t he benchmark and report the results. +*/ +#define VCUNT_SIM + +#include "coremark.h" +#include "timer.h" + +#ifdef VCUNT_SIM + //#include "vtimer.h" + extern unsigned int get_vtimer(); + int vtimer_start; + int vtimer_end; + int vcycles; +#endif + +int Loop_Num = 0; + +/* Function: iterate + Run the benchmark for a specified number of iterations. + + Operation: + For each type of benchmarked algorithm: + a - Initialize the data block for the algorithm. + b - Execute the algorithm N times. + + Returns: + NULL. +*/ +static ee_u16 list_known_crc[] = {(ee_u16)0xd4b0,(ee_u16)0x3340,(ee_u16)0x6a79,(ee_u16)0xe714,(ee_u16)0xe3c1}; +static ee_u16 matrix_known_crc[] = {(ee_u16)0xbe52,(ee_u16)0x1199,(ee_u16)0x5608,(ee_u16)0x1fd7,(ee_u16)0x0747}; +static ee_u16 state_known_crc[] = {(ee_u16)0x5e47,(ee_u16)0x39bf,(ee_u16)0xe5a4,(ee_u16)0x8e3a,(ee_u16)0x8d84}; +void *iterate(void *pres) { + ee_u32 i; + ee_u16 crc; + core_results *res=(core_results *)pres; + ee_u32 iterations=res->iterations; + res->crc=0; + res->crclist=0; + res->crcmatrix=0; + res->crcstate=0; + +#ifdef VCUNT_SIM + vtimer_start= get_vtimer(); +#endif + for (i=0; icrc=crcu16(crc,res->crc); + crc=core_bench_list(res,-1); + res->crc=crcu16(crc,res->crc); + if (i==0) res->crclist=res->crc; + } + +#ifdef VCUNT_SIM + + #define FREQ 100000000 + + vtimer_end= get_vtimer(); + vcycles = vtimer_end - vtimer_start; + vcycles = vcycles/iterations; + printf ("\nVCUNT_SIM: CoreMark has been run %d times, one times cost %d cycles !\n",iterations,vcycles); + float score; +// score = FREQ/(float)vcycles; +// printf ("\nVCUNT_SIM: CoreMark 1.0 : %f iterations/sec\n",score); //CoreMark = iterations of a sec + score = 1000000/(float)vcycles; //to relieve relations with FREQ + printf ("\nVCUNT_SIM: CoreMark 1.0 : %f (iterations/sec)/MHz\n",score); //CoreMark = iterations of a sec + sim_end(); +#endif + + return NULL; +} + +#if (SEED_METHOD==SEED_ARG) +ee_s32 get_seed_args(int i, int argc, char *argv[]); +#define get_seed(x) (ee_s16)get_seed_args(x,argc,argv) +#define get_seed_32(x) get_seed_args(x,argc,argv) +#else /* via function or volatile */ +ee_s32 get_seed_32(int i); +#define get_seed(x) (ee_s16)get_seed_32(x) +#endif + +#if (MEM_METHOD==MEM_STATIC) +ee_u8 static_memblk[TOTAL_DATA_SIZE]; +#endif +char *mem_name[3] = {"Static","Heap","Stack"}; +/* Function: main + Main entry routine for the benchmark. + This function is responsible for the following steps: + + 1 - Initialize input seeds from a source that cannot be determined at compile time. + 2 - Initialize memory block for use. + 3 - Run and time the benchmark. + 4 - Report results, testing the validity of the output if the seeds are known. + + Arguments: + 1 - first seed : Any value + 2 - second seed : Must be identical to first for iterations to be identical + 3 - third seed : Any value, should be at least an order of magnitude less then the input size, but bigger then 32. + 4 - Iterations : Special, if set to 0, iterations will be automatically determined such that the benchmark will run between 10 to 100 secs + +*/ + +//------------------------------------------------ +// setup uart +//------------------------------------------------ +#include "datatype.h" +#include "uart.h" +#include "stdio.h" + +t_ck_uart_device uart0 = {0xFFFF}; +//------------------------------------------------ + +#if MAIN_HAS_NOARGC +MAIN_RETURN_TYPE main(void) { + int argc=0; + char *argv[1]; +#else +MAIN_RETURN_TYPE main(int argc, char *argv[]) { +#endif + + int current_time; + ck_intc_init(); + Timer_Interrupt_Init(); + //-------------------------------------------------------- + // setup uart + //-------------------------------------------------------- + t_ck_uart_cfig uart_cfig; + + uart_cfig.baudrate = BAUD; // any integer value is allowed + uart_cfig.parity = PARITY_NONE; // PARITY_NONE / PARITY_ODD / PARITY_EVEN + uart_cfig.stopbit = STOPBIT_1; // STOPBIT_1 / STOPBIT_2 + uart_cfig.wordsize = WORDSIZE_8; // from WORDSIZE_5 to WORDSIZE_8 + uart_cfig.txmode = ENABLE; // ENABLE or DISABLE + + // open UART device with id = 0 (UART0) + ck_uart_open(&uart0, 0); + + // initialize uart using uart_cfig structure + ck_uart_init(&uart0, &uart_cfig); + //-------------------------------------------------------- + + ee_u16 i,j=0,num_algorithms=0; + ee_s16 known_id=-1,total_errors=0; + ee_u16 seedcrc=0; + long total_time; + core_results results[MULTITHREAD]; +#if (MEM_METHOD==MEM_STACK) + ee_u8 stack_memblock[TOTAL_DATA_SIZE*MULTITHREAD]; +#endif + /* first call any initializations needed */ + portable_init(&(results[0].port), &argc, argv); + /* First some checks to make sure benchmark will run ok */ + if (sizeof(struct list_head_s)>128) { + printf("list_head structure too big for comparable data!\n"); + return MAIN_RETURN_VAL; + } + results[0].seed1=get_seed(1); + results[0].seed2=get_seed(2); + results[0].seed3=get_seed(3); + results[0].iterations= 2; +#if CORE_DEBUG + results[0].iterations=1; +#endif + results[0].execs=get_seed_32(5); + if (results[0].execs==0) { /* if not supplied, execute all algorithms */ + results[0].execs=ALL_ALGORITHMS_MASK; + } + /* put in some default values based on one seed only for easy testing */ + if ((results[0].seed1==0) && (results[0].seed2==0) && (results[0].seed3==0)) { /* validation run */ + results[0].seed1=0; + results[0].seed2=0; + results[0].seed3=0x66; + } + if ((results[0].seed1==1) && (results[0].seed2==0) && (results[0].seed3==0)) { /* perfromance run */ + results[0].seed1=0x3415; + results[0].seed2=0x3415; + results[0].seed3=0x66; + } +#if (MEM_METHOD==MEM_STATIC) + results[0].memblock[0]=(void *)static_memblk; + results[0].size=TOTAL_DATA_SIZE; + results[0].err=0; + #if (MULTITHREAD>1) + #error "Cannot use a static data area with multiple contexts!" + #endif +#elif (MEM_METHOD==MEM_MALLOC) + for (i=0 ; i1) + if (default_num_contexts>MULTITHREAD) { + default_num_contexts=MULTITHREAD; + } + for (i=0 ; i=0) { + for (i=0 ; i 0) + printf("Iterations/Sec : %f\n",default_num_contexts*results[0].iterations/time_in_secs(total_time)); +#else + printf("Total time (secs): %d\n",time_in_secs(total_time)); + if (time_in_secs(total_time) > 0) + printf("Iterations/Sec : %d\n",default_num_contexts*results[0].iterations/time_in_secs(total_time)); +#endif + if (time_in_secs(total_time) < 10) { + printf("ERROR! Must execute for at least 10 secs for a valid result!\n"); + total_errors++; + } + + printf("Iterations : %d\n",(ee_u32)default_num_contexts*results[0].iterations); + printf("Compiler version : %s\n",COMPILER_VERSION); + printf("Compiler flags : %s\n",COMPILER_FLAGS); +#if (MULTITHREAD>1) + printf("Parallel %s : %d\n",PARALLEL_METHOD,default_num_contexts); +#endif + printf("Memory location : %s\n",MEM_LOCATION); + /* output for verification */ + printf("seedcrc : 0x%04x\n",seedcrc); + if (results[0].execs & ID_LIST) + for (i=0 ; i1) + printf(" / %d:%s",default_num_contexts,PARALLEL_METHOD); +#endif + printf("\n"); + } +#endif + } + if (total_errors>0) + printf("Errors detected\n"); + if (total_errors<0) + printf("Cannot validate operation for these seed values, please compare with results on a known platform.\n"); + +#if (MEM_METHOD==MEM_MALLOC) + for (i=0 ; i>(from)) & (~(0xffffffff << (to)))) + +#if CORE_DEBUG +void printmat(MATDAT *A, ee_u32 N, char *name) { + ee_u32 i,j; + printf("Matrix %s [%dx%d]:\n",name,N,N); + for (i=0; i N times, + changing the matrix values slightly by a constant amount each time. +*/ +ee_u16 core_bench_matrix(mat_params *p, ee_s16 seed, ee_u16 crc) { + ee_u32 N=p->N; + MATRES *C=p->C; + MATDAT *A=p->A; + MATDAT *B=p->B; + MATDAT val=(MATDAT)seed; + + crc=crc16(matrix_test(N,C,A,B,val),crc); + + return crc; +} + +/* Function: matrix_test + Perform matrix manipulation. + + Parameters: + N - Dimensions of the matrix. + C - memory for result matrix. + A - input matrix + B - operator matrix (not changed during operations) + + Returns: + A CRC value that captures all results calculated in the function. + In particular, crc of the value calculated on the result matrix + after each step by . + + Operation: + + 1 - Add a constant value to all elements of a matrix. + 2 - Multiply a matrix by a constant. + 3 - Multiply a matrix by a vector. + 4 - Multiply a matrix by a matrix. + 5 - Add a constant value to all elements of a matrix. + + After the last step, matrix A is back to original contents. +*/ +ee_s16 matrix_test(ee_u32 N, MATRES *C, MATDAT *A, MATDAT *B, MATDAT val) { + ee_u16 crc=0; + MATDAT clipval=matrix_big(val); + + matrix_add_const(N,A,val); /* make sure data changes */ +#if CORE_DEBUG + printmat(A,N,"matrix_add_const"); +#endif + matrix_mul_const(N,C,A,val); + crc=crc16(matrix_sum(N,C,clipval),crc); +#if CORE_DEBUG + printmatC(C,N,"matrix_mul_const"); +#endif + matrix_mul_vect(N,C,A,B); + crc=crc16(matrix_sum(N,C,clipval),crc); +#if CORE_DEBUG + printmatC(C,N,"matrix_mul_vect"); +#endif + matrix_mul_matrix(N,C,A,B); + crc=crc16(matrix_sum(N,C,clipval),crc); +#if CORE_DEBUG + printmatC(C,N,"matrix_mul_matrix"); +#endif + matrix_mul_matrix_bitextract(N,C,A,B); + crc=crc16(matrix_sum(N,C,clipval),crc); +#if CORE_DEBUG + printmatC(C,N,"matrix_mul_matrix_bitextract"); +#endif + + matrix_add_const(N,A,-val); /* return matrix to initial value */ + return crc; +} + +/* Function : matrix_init + Initialize the memory block for matrix benchmarking. + + Parameters: + blksize - Size of memory to be initialized. + memblk - Pointer to memory block. + seed - Actual values chosen depend on the seed parameter. + p - pointers to containing initialized matrixes. + + Returns: + Matrix dimensions. + + Note: + The seed parameter MUST be supplied from a source that cannot be determined at compile time +*/ +ee_u32 core_init_matrix(ee_u32 blksize, void *memblk, ee_s32 seed, mat_params *p) { + ee_u32 N=0; + MATDAT *A; + MATDAT *B; + ee_s32 order=1; + MATDAT val; + ee_u32 i=0,j=0; + if (seed==0) + seed=1; + while (jA=A; + p->B=B; + p->C=(MATRES *)align_mem(B+N*N); + p->N=N; +#if CORE_DEBUG + printmat(A,N,"A"); + printmat(B,N,"B"); +#endif + return N; +} + +/* Function: matrix_sum + Calculate a function that depends on the values of elements in the matrix. + + For each element, accumulate into a temporary variable. + + As long as this value is under the parameter clipval, + add 1 to the result if the element is bigger then the previous. + + Otherwise, reset the accumulator and add 10 to the result. +*/ +ee_s16 matrix_sum(ee_u32 N, MATRES *C, MATDAT clipval) { + MATRES tmp=0,prev=0,cur=0; + ee_s16 ret=0; + ee_u32 i,j; + for (i=0; iclipval) { + ret+=10; + tmp=0; + } else { + ret += (cur>prev) ? 1 : 0; + } + prev=cur; + } + } + return ret; +} + +/* Function: matrix_mul_const + Multiply a matrix by a constant. + This could be used as a scaler for instance. +*/ +void matrix_mul_const(ee_u32 N, MATRES *C, MATDAT *A, MATDAT val) { + ee_u32 i,j; + for (i=0; i. + This methodology is taken to accomodate any hardware or simulated platform. + The sample implementation returns millisecs by default, + and the resolution is controlled by +*/ +CORE_TICKS get_time(void) { + CORE_TICKS elapsed=(CORE_TICKS)(MYTIMEDIFF(stop_time_val, start_time_val)); + return elapsed; +} +/* Function : time_in_secs + Convert the value returned by get_time to seconds. + + The type is used to accomodate systems with no support for floating point. + Default implementation implemented by the EE_TICKS_PER_SEC macro above. +*/ +secs_ret time_in_secs(CORE_TICKS ticks) { + secs_ret retval=((secs_ret)ticks) / (secs_ret)EE_TICKS_PER_SEC; + return retval; +} + +ee_u32 default_num_contexts=1; + +/* Function : portable_init + Target specific initialization code + Test for some common mistakes. +*/ +void portable_init(core_portable *p, int *argc, char *argv[]) +{ +// #error "Call board initialization routines in portable init (if needed), in particular initialize UART!\n" + //-------------------------------------------- + // board_initial() -> start_timer() + //board_initial(); + start_time(); + //-------------------------------------------- + if (sizeof(ee_ptr_int) != sizeof(ee_u8 *)) { + printf("ERROR! Please define ee_ptr_int to a type that holds a pointer!\n"); + } + if (sizeof(ee_u32) != 4) { + printf("ERROR! Please define ee_u32 to a 32b unsigned type!\n"); + } + p->portable_id=1; +} +/* Function : portable_fini + Target specific final code +*/ +void portable_fini(core_portable *p) +{ + p->portable_id=0; +} + + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_portme.h b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_portme.h new file mode 100644 index 0000000000000000000000000000000000000000..95f5c4364e58e7f152397d3ae4e4317b8c60f6f6 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_portme.h @@ -0,0 +1,190 @@ +/* File : core_portme.h */ + +/* + Author : Shay Gal-On, EEMBC + Legal : TODO! +*/ +/* Topic : Description + This file contains configuration constants required to execute on different platforms +*/ +#ifndef CORE_PORTME_H +#define CORE_PORTME_H +/************************/ +/* Data types and settings */ +/************************/ +/* Configuration : HAS_FLOAT + Define to 1 if the platform supports floating point. +*/ + +#include "config.h" +#ifndef HAS_FLOAT +#define HAS_FLOAT 0 +#endif +/* Configuration : HAS_TIME_H + Define to 1 if platform has the time.h header file, + and implementation of functions thereof. +*/ +#ifndef HAS_TIME_H +#define HAS_TIME_H 1 +#endif +/* Configuration : USE_CLOCK + Define to 1 if platform has the time.h header file, + and implementation of functions thereof. +*/ +#ifndef USE_CLOCK +#define USE_CLOCK 1 +#endif +/* Configuration : HAS_STDIO + Define to 1 if the platform has stdio.h. +*/ +#ifndef HAS_STDIO +#define HAS_STDIO 0 +#endif +/* Configuration : HAS_PRINTF + Define to 1 if the platform has stdio.h and implements the printf function. +*/ +#ifndef HAS_PRINTF +#define HAS_PRINTF 0 +#endif + + +/* Definitions : COMPILER_VERSION, COMPILER_FLAGS, MEM_LOCATION + Initialize these strings per platform +*/ +#ifndef COMPILER_VERSION + #ifdef __GNUC__ + #define COMPILER_VERSION "GCC"__VERSION__ + #else + #define COMPILER_VERSION "Please put compiler version here (e.g. gcc 4.1)" + #endif +#endif +#ifndef COMPILER_FLAGS + #define COMPILER_FLAGS "-O" /* "Please put compiler flags here (e.g. -o3)" */ +#endif +#ifndef MEM_LOCATION + #define MEM_LOCATION "STACK" +#endif + + +/* Data Types : + To avoid compiler issues, define the data types that need ot be used for 8b, 16b and 32b in . + + *Imprtant* : + ee_ptr_int needs to be the data type used to hold pointers, otherwise coremark may fail!!! +*/ +typedef unsigned int size_t; +typedef signed short ee_s16; +typedef unsigned short ee_u16; +typedef signed int ee_s32; +typedef double ee_f32; +typedef unsigned char ee_u8; +typedef unsigned int ee_u32; +typedef ee_u32 ee_ptr_int; +typedef size_t ee_size_t; +#define NULL ((void *)0) +/* align_mem : + This macro is used to align an offset to point to a 32b value. It is used in the Matrix algorithm to initialize the input memory blocks. +*/ +#define align_mem(x) (void *)(4 + (((ee_ptr_int)(x) - 1) & ~3)) + +/* Configuration : CORE_TICKS + Define type of return from the timing functions. + */ +#define CORETIMETYPE ee_u32 +typedef ee_u32 CORE_TICKS; + +/* Configuration : SEED_METHOD + Defines method to get seed values that cannot be computed at compile time. + + Valid values : + SEED_ARG - from command line. + SEED_FUNC - from a system function. + SEED_VOLATILE - from volatile variables. +*/ +#ifndef SEED_METHOD +#define SEED_METHOD SEED_VOLATILE +#endif + +/* Configuration : MEM_METHOD + Defines method to get a block of memry. + + Valid values : + MEM_MALLOC - for platforms that implement malloc and have malloc.h. + MEM_STATIC - to use a static memory array. + MEM_STACK - to allocate the data block on the stack (NYI). +*/ +#ifndef MEM_METHOD +#define MEM_METHOD MEM_STACK +#endif + +/* Configuration : MULTITHREAD + Define for parallel execution + + Valid values : + 1 - only one context (default). + N>1 - will execute N copies in parallel. + + Note : + If this flag is defined to more then 1, an implementation for launching parallel contexts must be defined. + + Two sample implementations are provided. Use or to enable them. + + It is valid to have a different implementation of and in , + to fit a particular architecture. +*/ +#ifndef MULTITHREAD +#define MULTITHREAD 1 +#define USE_PTHREAD 0 +#define USE_FORK 0 +#define USE_SOCKET 0 +#endif + +/* Configuration : MAIN_HAS_NOARGC + Needed if platform does not support getting arguments to main. + + Valid values : + 0 - argc/argv to main is supported + 1 - argc/argv to main is not supported + + Note : + This flag only matters if MULTITHREAD has been defined to a value greater then 1. +*/ +#ifndef MAIN_HAS_NOARGC +#define MAIN_HAS_NOARGC 0 +#endif + +/* Configuration : MAIN_HAS_NORETURN + Needed if platform does not support returning a value from main. + + Valid values : + 0 - main returns an int, and return value will be 0. + 1 - platform does not support returning a value from main +*/ +#ifndef MAIN_HAS_NORETURN +#define MAIN_HAS_NORETURN 0 +#endif + +/* Variable : default_num_contexts + Not used for this simple port, must cintain the value 1. +*/ +extern ee_u32 default_num_contexts; + +typedef struct CORE_PORTABLE_S { + ee_u8 portable_id; +} core_portable; + +/* target specific init/fini */ +void portable_init(core_portable *p, int *argc, char *argv[]); +void portable_fini(core_portable *p); +extern void board_initial ( void ); +#if !defined(PROFILE_RUN) && !defined(PERFORMANCE_RUN) && !defined(VALIDATION_RUN) +#if (TOTAL_DATA_SIZE==1200) +#define PROFILE_RUN 1 +#elif (TOTAL_DATA_SIZE==2000) +#define PERFORMANCE_RUN 1 +#else +#define VALIDATION_RUN 1 +#endif +#endif + +#endif /* CORE_PORTME_H */ diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_state.c b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_state.c new file mode 100644 index 0000000000000000000000000000000000000000..4c8761dcc1feefbf7ddd9b061046d11c355a59f8 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_state.c @@ -0,0 +1,277 @@ +/* +Author : Shay Gal-On, EEMBC + +This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 +All rights reserved. + +EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the +CoreMark License that is distributed with the official EEMBC COREMARK Software release. +If you received this EEMBC CoreMark Software without the accompanying CoreMark License, +you must discontinue use and download the official release from www.coremark.org. + +Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, +make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. + +EEMBC +4354 Town Center Blvd. Suite 114-200 +El Dorado Hills, CA, 95762 +*/ +#include "coremark.h" +/* local functions */ +enum CORE_STATE core_state_transition( ee_u8 **instr , ee_u32 *transition_count); + +/* +Topic: Description + Simple state machines like this one are used in many embedded products. + + For more complex state machines, sometimes a state transition table implementation is used instead, + trading speed of direct coding for ease of maintenance. + + Since the main goal of using a state machine in CoreMark is to excercise the switch/if behaviour, + we are using a small moore machine. + + In particular, this machine tests type of string input, + trying to determine whether the input is a number or something else. + (see core_state.png). +*/ + +/* Function: core_bench_state + Benchmark function + + Go over the input twice, once direct, and once after introducing some corruption. +*/ +ee_u16 core_bench_state(ee_u32 blksize, ee_u8 *memblock, + ee_s16 seed1, ee_s16 seed2, ee_s16 step, ee_u16 crc) +{ + ee_u32 final_counts[NUM_CORE_STATES]; + ee_u32 track_counts[NUM_CORE_STATES]; + ee_u8 *p=memblock; + ee_u32 i; + + +#if CORE_DEBUG + printf("State Bench: %d,%d,%d,%04x\n",seed1,seed2,step,crc); +#endif + for (i=0; i0) { + for(i=0;i>3) & 0x3]; + next=4; + break; + case 3: /* float */ + case 4: /* float */ + buf=floatpat[(seed>>3) & 0x3]; + next=8; + break; + case 5: /* scientific */ + case 6: /* scientific */ + buf=scipat[(seed>>3) & 0x3]; + next=8; + break; + case 7: /* invalid */ + buf=errpat[(seed>>3) & 0x3]; + next=8; + break; + default: /* Never happen, just to make some compilers happy */ + break; + } + } + size++; + while (total='0') & (c<='9')) ? 1 : 0; + return retval; +} + +/* Function: core_state_transition + Actual state machine. + + The state machine will continue scanning until either: + 1 - an invalid input is detcted. + 2 - a valid number has been detected. + + The input pointer is updated to point to the end of the token, and the end state is returned (either specific format determined or invalid). +*/ + +enum CORE_STATE core_state_transition( ee_u8 **instr , ee_u32 *transition_count) { + ee_u8 *str=*instr; + ee_u8 NEXT_SYMBOL; + enum CORE_STATE state=CORE_START; + for( ; *str && state != CORE_INVALID; str++ ) { + NEXT_SYMBOL = *str; + if (NEXT_SYMBOL==',') /* end of this input */ { + str++; + break; + } + switch(state) { + case CORE_START: + if(ee_isdigit(NEXT_SYMBOL)) { + state = CORE_INT; + } + else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { + state = CORE_S1; + } + else if( NEXT_SYMBOL == '.' ) { + state = CORE_FLOAT; + } + else { + state = CORE_INVALID; + transition_count[CORE_INVALID]++; + } + transition_count[CORE_START]++; + break; + case CORE_S1: + if(ee_isdigit(NEXT_SYMBOL)) { + state = CORE_INT; + transition_count[CORE_S1]++; + } + else if( NEXT_SYMBOL == '.' ) { + state = CORE_FLOAT; + transition_count[CORE_S1]++; + } + else { + state = CORE_INVALID; + transition_count[CORE_S1]++; + } + break; + case CORE_INT: + if( NEXT_SYMBOL == '.' ) { + state = CORE_FLOAT; + transition_count[CORE_INT]++; + } + else if(!ee_isdigit(NEXT_SYMBOL)) { + state = CORE_INVALID; + transition_count[CORE_INT]++; + } + break; + case CORE_FLOAT: + if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) { + state = CORE_S2; + transition_count[CORE_FLOAT]++; + } + else if(!ee_isdigit(NEXT_SYMBOL)) { + state = CORE_INVALID; + transition_count[CORE_FLOAT]++; + } + break; + case CORE_S2: + if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { + state = CORE_EXPONENT; + transition_count[CORE_S2]++; + } + else { + state = CORE_INVALID; + transition_count[CORE_S2]++; + } + break; + case CORE_EXPONENT: + if(ee_isdigit(NEXT_SYMBOL)) { + state = CORE_SCIENTIFIC; + transition_count[CORE_EXPONENT]++; + } + else { + state = CORE_INVALID; + transition_count[CORE_EXPONENT]++; + } + break; + case CORE_SCIENTIFIC: + if(!ee_isdigit(NEXT_SYMBOL)) { + state = CORE_INVALID; + transition_count[CORE_INVALID]++; + } + break; + default: + break; + } + } + *instr=str; + return state; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_util.c b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_util.c new file mode 100644 index 0000000000000000000000000000000000000000..dd2ad5819ccf626d31232699aec498d51069e218 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/core_util.c @@ -0,0 +1,210 @@ +/* +Author : Shay Gal-On, EEMBC + +This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 +All rights reserved. + +EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the +CoreMark License that is distributed with the official EEMBC COREMARK Software release. +If you received this EEMBC CoreMark Software without the accompanying CoreMark License, +you must discontinue use and download the official release from www.coremark.org. + +Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, +make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. + +EEMBC +4354 Town Center Blvd. Suite 114-200 +El Dorado Hills, CA, 95762 +*/ +#include "coremark.h" +/* Function: get_seed + Get a values that cannot be determined at compile time. + + Since different embedded systems and compilers are used, 3 different methods are provided: + 1 - Using a volatile variable. This method is only valid if the compiler is forced to generate code that + reads the value of a volatile variable from memory at run time. + Please note, if using this method, you would need to modify core_portme.c to generate training profile. + 2 - Command line arguments. This is the preferred method if command line arguments are supported. + 3 - System function. If none of the first 2 methods is available on the platform, + a system function which is not a stub can be used. + + e.g. read the value on GPIO pins connected to switches, or invoke special simulator functions. +*/ +#if (SEED_METHOD==SEED_VOLATILE) + extern volatile ee_s32 seed1_volatile; + extern volatile ee_s32 seed2_volatile; + extern volatile ee_s32 seed3_volatile; + extern volatile ee_s32 seed4_volatile; + extern volatile ee_s32 seed5_volatile; + ee_s32 get_seed_32(int i) { + ee_s32 retval; + switch (i) { + case 1: + retval=seed1_volatile; + break; + case 2: + retval=seed2_volatile; + break; + case 3: + retval=seed3_volatile; + break; + case 4: + retval=seed4_volatile; + break; + case 5: + retval=seed5_volatile; + break; + default: + retval=0; + break; + } + return retval; + } +#elif (SEED_METHOD==SEED_ARG) +ee_s32 parseval(char *valstring) { + ee_s32 retval=0; + ee_s32 neg=1; + int hexmode=0; + if (*valstring == '-') { + neg=-1; + valstring++; + } + if ((valstring[0] == '0') && (valstring[1] == 'x')) { + hexmode=1; + valstring+=2; + } + /* first look for digits */ + if (hexmode) { + while (((*valstring >= '0') && (*valstring <= '9')) || ((*valstring >= 'a') && (*valstring <= 'f'))) { + ee_s32 digit=*valstring-'0'; + if (digit>9) + digit=10+*valstring-'a'; + retval*=16; + retval+=digit; + valstring++; + } + } else { + while ((*valstring >= '0') && (*valstring <= '9')) { + ee_s32 digit=*valstring-'0'; + retval*=10; + retval+=digit; + valstring++; + } + } + /* now add qualifiers */ + if (*valstring=='K') + retval*=1024; + if (*valstring=='M') + retval*=1024*1024; + + retval*=neg; + return retval; +} + +ee_s32 get_seed_args(int i, int argc, char *argv[]) { + if (argc>i) + return parseval(argv[i]); + return 0; +} + +#elif (SEED_METHOD==SEED_FUNC) +/* If using OS based function, you must define and implement the functions below in core_portme.h and core_portme.c ! */ +ee_s32 get_seed_32(int i) { + ee_s32 retval; + switch (i) { + case 1: + retval=portme_sys1(); + break; + case 2: + retval=portme_sys2(); + break; + case 3: + retval=portme_sys3(); + break; + case 4: + retval=portme_sys4(); + break; + case 5: + retval=portme_sys5(); + break; + default: + retval=0; + break; + } + return retval; +} +#endif + +/* Function: crc* + Service functions to calculate 16b CRC code. + +*/ +ee_u16 crcu8(ee_u8 data, ee_u16 crc ) +{ + ee_u8 i=0,x16=0,carry=0; + + for (i = 0; i < 8; i++) + { + x16 = (ee_u8)((data & 1) ^ ((ee_u8)crc & 1)); + data >>= 1; + + if (x16 == 1) + { + crc ^= 0x4002; + carry = 1; + } + else + carry = 0; + crc >>= 1; + if (carry) + crc |= 0x8000; + else + crc &= 0x7fff; + } + return crc; +} +ee_u16 crcu16(ee_u16 newval, ee_u16 crc) { + crc=crcu8( (ee_u8) (newval) ,crc); + crc=crcu8( (ee_u8) ((newval)>>8) ,crc); + return crc; +} +ee_u16 crcu32(ee_u32 newval, ee_u16 crc) { + crc=crc16((ee_s16) newval ,crc); + crc=crc16((ee_s16) (newval>>16) ,crc); + return crc; +} +ee_u16 crc16(ee_s16 newval, ee_u16 crc) { + return crcu16((ee_u16)newval, crc); +} + +ee_u8 check_data_types() { + ee_u8 retval=0; + if (sizeof(ee_u8) != 1) { + printf("ERROR: ee_u8 is not an 8b datatype!\n"); + retval++; + } + if (sizeof(ee_u16) != 2) { + printf("ERROR: ee_u16 is not a 16b datatype!\n"); + retval++; + } + if (sizeof(ee_s16) != 2) { + printf("ERROR: ee_s16 is not a 16b datatype!\n"); + retval++; + } + if (sizeof(ee_s32) != 4) { + printf("ERROR: ee_s32 is not a 32b datatype!\n"); + retval++; + } + if (sizeof(ee_u32) != 4) { + printf("ERROR: ee_u32 is not a 32b datatype!\n"); + retval++; + } + if (sizeof(ee_ptr_int) != sizeof(int *)) { + printf("ERROR: ee_ptr_int is not a datatype that holds an int pointer!\n"); + retval++; + } + if (retval>0) { + printf("ERROR: Please modify the datatypes in core_portme.h!\n"); + } + return retval; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/coremark.h b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/coremark.h new file mode 100644 index 0000000000000000000000000000000000000000..90c0f36f86e3e6e7cbf7a04fbcf8229eda8fcdf5 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/coremark.h @@ -0,0 +1,174 @@ +/* +Author : Shay Gal-On, EEMBC + +This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 +All rights reserved. + +EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the +CoreMark License that is distributed with the official EEMBC COREMARK Software release. +If you received this EEMBC CoreMark Software without the accompanying CoreMark License, +you must discontinue use and download the official release from www.coremark.org. + +Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, +make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. + +EEMBC +4354 Town Center Blvd. Suite 114-200 +El Dorado Hills, CA, 95762 +*/ +/* Topic: Description + This file contains declarations of the various benchmark functions. +*/ + +/* Configuration: TOTAL_DATA_SIZE + Define total size for data algorithms will operate on +*/ +#ifndef TOTAL_DATA_SIZE +#define TOTAL_DATA_SIZE 2*1000 +#endif + +#define SEED_ARG 0 +#define SEED_FUNC 1 +#define SEED_VOLATILE 2 + +#define MEM_STATIC 0 +#define MEM_MALLOC 1 +#define MEM_STACK 2 + +#include "core_portme.h" + +#if HAS_STDIO +#include +#endif +#if HAS_PRINTF +#define ee_printf printf +#endif + +/* Actual benchmark execution in iterate */ +void *iterate(void *pres); + +/* Typedef: secs_ret + For machines that have floating point support, get number of seconds as a double. + Otherwise an unsigned int. +*/ +#if HAS_FLOAT +typedef double secs_ret; +#else +typedef ee_u32 secs_ret; +#endif + +#if MAIN_HAS_NORETURN +#define MAIN_RETURN_VAL +#define MAIN_RETURN_TYPE void +#else +#define MAIN_RETURN_VAL 0 +#define MAIN_RETURN_TYPE int +#endif + +void start_time(void); +void stop_time(void); +CORE_TICKS get_time(void); +secs_ret time_in_secs(CORE_TICKS ticks); + +/* Misc useful functions */ +ee_u16 crcu8(ee_u8 data, ee_u16 crc); +ee_u16 crc16(ee_s16 newval, ee_u16 crc); +ee_u16 crcu16(ee_u16 newval, ee_u16 crc); +ee_u16 crcu32(ee_u32 newval, ee_u16 crc); +ee_u8 check_data_types(); +void *portable_malloc(ee_size_t size); +void portable_free(void *p); +ee_s32 parseval(char *valstring); + +/* Algorithm IDS */ +#define ID_LIST (1<<0) +#define ID_MATRIX (1<<1) +#define ID_STATE (1<<2) +#define ALL_ALGORITHMS_MASK (ID_LIST|ID_MATRIX|ID_STATE) +#define NUM_ALGORITHMS 3 + +/* list data structures */ +typedef struct list_data_s { + ee_s16 data16; + ee_s16 idx; +} list_data; + +typedef struct list_head_s { + struct list_head_s *next; + struct list_data_s *info; +} list_head; + + +/*matrix benchmark related stuff */ +#define MATDAT_INT 1 +#if MATDAT_INT +typedef ee_s16 MATDAT; +typedef ee_s32 MATRES; +#else +typedef ee_f16 MATDAT; +typedef ee_f32 MATRES; +#endif + +typedef struct MAT_PARAMS_S { + int N; + MATDAT *A; + MATDAT *B; + MATRES *C; +} mat_params; + +/* state machine related stuff */ +/* List of all the possible states for the FSM */ +typedef enum CORE_STATE { + CORE_START=0, + CORE_INVALID, + CORE_S1, + CORE_S2, + CORE_INT, + CORE_FLOAT, + CORE_EXPONENT, + CORE_SCIENTIFIC, + NUM_CORE_STATES +} core_state_e ; + + +/* Helper structure to hold results */ +typedef struct RESULTS_S { + /* inputs */ + ee_s16 seed1; /* Initializing seed */ + ee_s16 seed2; /* Initializing seed */ + ee_s16 seed3; /* Initializing seed */ + void *memblock[4]; /* Pointer to safe memory location */ + ee_u32 size; /* Size of the data */ + ee_u32 iterations; /* Number of iterations to execute */ + ee_u32 execs; /* Bitmask of operations to execute */ + struct list_head_s *list; + mat_params mat; + /* outputs */ + ee_u16 crc; + ee_u16 crclist; + ee_u16 crcmatrix; + ee_u16 crcstate; + ee_s16 err; + /* ultithread specific */ + core_portable port; +} core_results; + +/* Multicore execution handling */ +#if (MULTITHREAD>1) +ee_u8 core_start_parallel(core_results *res); +ee_u8 core_stop_parallel(core_results *res); +#endif + +/* list benchmark functions */ +list_head *core_list_init(ee_u32 blksize, list_head *memblock, ee_s16 seed); +ee_u16 core_bench_list(core_results *res, ee_s16 finder_idx); + +/* state benchmark functions */ +void core_init_state(ee_u32 size, ee_s16 seed, ee_u8 *p); +ee_u16 core_bench_state(ee_u32 blksize, ee_u8 *memblock, + ee_s16 seed1, ee_s16 seed2, ee_s16 step, ee_u16 crc); + +/* matrix benchmark functions */ +ee_u32 core_init_matrix(ee_u32 blksize, void *memblk, ee_s32 seed, mat_params *p); +ee_u16 core_bench_matrix(mat_params *p, ee_s16 seed, ee_u16 crc); + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/cvt.c b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/cvt.c new file mode 100644 index 0000000000000000000000000000000000000000..e7594e956ea6d77390a5600b6c9f23408593bc6a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/coremark/cvt.c @@ -0,0 +1,102 @@ +#include +#define CVTBUFSIZE 80 +static char CVTBUF[CVTBUFSIZE]; + +static char *cvt(double arg, int ndigits, int *decpt, int *sign, char *buf, int eflag) +{ + int r2; + double fi, fj; + char *p, *p1; + + if (ndigits < 0) ndigits = 0; + if (ndigits >= CVTBUFSIZE - 1) ndigits = CVTBUFSIZE - 2; + r2 = 0; + *sign = 0; + p = &buf[0]; + if (arg < 0) + { + *sign = 1; + arg = -arg; + } + arg = modf(arg, &fi); + p1 = &buf[CVTBUFSIZE]; + + if (fi != 0) + { + p1 = &buf[CVTBUFSIZE]; + while (fi != 0) + { + fj = modf(fi / 10, &fi); + *--p1 = (int)((fj + .03) * 10) + '0'; + r2++; + } + while (p1 < &buf[CVTBUFSIZE]) *p++ = *p1++; + } + else if (arg > 0) + { + while ((fj = arg * 10) < 1) + { + arg = fj; + r2--; + } + } + p1 = &buf[ndigits]; + if (eflag == 0) p1 += r2; + *decpt = r2; + if (p1 < &buf[0]) + { + buf[0] = '\0'; + return buf; + } + while (p <= p1 && p < &buf[CVTBUFSIZE]) + { + arg *= 10; + arg = modf(arg, &fj); + *p++ = (int) fj + '0'; + } + if (p1 >= &buf[CVTBUFSIZE]) + { + buf[CVTBUFSIZE - 1] = '\0'; + return buf; + } + p = p1; + *p1 += 5; + while (*p1 > '9') + { + *p1 = '0'; + if (p1 > buf) + ++*--p1; + else + { + *p1 = '1'; + (*decpt)++; + if (eflag == 0) + { + if (p > buf) *p = '0'; + p++; + } + } + } + *p = '\0'; + return buf; +} + +char *ecvt(double arg, int ndigits, int *decpt, int *sign) +{ + return cvt(arg, ndigits, decpt, sign, CVTBUF, 1); +} + +char *ecvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf) +{ + return cvt(arg, ndigits, decpt, sign, buf, 1); +} + +char *fcvt(double arg, int ndigits, int *decpt, int *sign) +{ + return cvt(arg, ndigits, decpt, sign, CVTBUF, 0); +} + +char *fcvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf) +{ + return cvt(arg, ndigits, decpt, sign, buf, 0); +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/debug/E906_DEBUG_PATTERN.v b/XUANTIE-RV_opene906/smart_run/tests/cases/debug/E906_DEBUG_PATTERN.v new file mode 100644 index 0000000000000000000000000000000000000000..a1c2520f456b6fdaad39daa477f5a56a5de54e38 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/debug/E906_DEBUG_PATTERN.v @@ -0,0 +1,425 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +`define TDT_DM_PB_SIZE 2 + +`define FPU + + + +module E906_DEBUG_PATTERN(); + reg[31:0] had_data_out; +ext_debug dh; +longint rd_value; +longint wr_value; +bit error; + +bit[1:0] dmi_op; +bit[`DTM_DTMCS_ABIT-1:0] dmi_address; +int dmi_value, dmi_expected_value; +int pb_size; + +process process1; +bit[31:0] data_high, data_low, data_temp; +bit[2:0] cmderr; +int halt_poll_num; + +int retire_num, retire_total_num; +bit[39:0] retire_pc; +int step_num; +bit[2:0] aarsize; +bit[31:0] itr_opcodes[$]; +bit[63:0] data_back; + +initial begin + //debug host class init + `ifdef SELECT_2_WIRE_JTAG + $display("RV Debug test, using 2-wire JTAG protocol"); + `else + $display("RV Debug test, using 5-wire JTAG protocol"); + `endif + + dh = new("dh"); + dh.initDTM(); + `ifdef TDT_DM_CORE_RV64 + aarsize=3; + `else + aarsize=2; + `endif + //start reading DTM registers + + wait_mstatus(); + $display("core enter handshake"); + +//********************************************************** +//dtm reg rd/wr +//********************************************************** + //1.check BYPASS value + dh.part_start("DTM.BYPASS"); + wr_value = 64'd0; + rd_value = 64'd0; + dh.rwDTMReg(`DTM_BYPASS, rd_value, wr_value, error); + //TODO: add check logic + $display("dtm.bypass = %0h", rd_value); + + //2.check IDCODE value + dh.part_start("DTM.IDCODE"); + wr_value = 64'd0; + rd_value = 64'd0; + dh.rwDTMReg(`DTM_IDCODE, rd_value, wr_value, error); + //TODO: add check logic + $display("dtm.idcode = %0h", rd_value); + +//********************************************************** +//dm reg rd/wr +//********************************************************** + //enable debug module + dmi_op = `DMI_WRITE; + dmi_address = `DM_DMCONTROL; + dmi_value = 32'd1; //enable dactive + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + + //1.check dmstatus value + dh.part_start("DM.dmstatus default value check:"); + dmi_op = `DMI_READ; + dmi_address = `DM_DMSTATUS; + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + // check DMSTATUS.version=2 + if (dmi_value[3:0] != 4'd2) begin + dh.tb_fatal($sformatf("Error:DM.dmstatus.version should be 2, but now %0h", dmi_value[3:0])); + end + $display("dmi_status default value: %h", dmi_value); + + dh.part_start("DM.dmcontrol default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_DMCONTROL, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value[19]!=1'b0 || + dmi_value[26]!=1'b0 || + dmi_value[25:16]!=10'd0 || + dmi_value[15:6]!=10'd0 || + dmi_value[1]!=1'b0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.hartinfo default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_HARTINFO, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + //if (dmi_value[23:20]!= `TDT_DM_CORE_NSCRATCH || + if (dmi_value[23:20]!= 4'h2 || + dmi_value[16]!=1'b0 || //dataaccess + dmi_value[15:12]!=10'd0 || //datasize + dmi_value[11:0]!=10'd0 //dataaddr + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.hawindowsel default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_HAWINDOWSEL, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.abstractcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end +`ifdef TDT_DM_PB_SIZE + pb_size = `TDT_DM_PB_SIZE; +`else + pb_size = 0; +`endif + if (dmi_value[28:24]!= pb_size + //if (dmi_value[28:24]!= 5'h1 //ZHAOKUAN TODO + || dmi_value[12]!=1'b0 //busy + || dmi_value[10:8]!=3'b0 //cmderr + || dmi_value[3:0]!=32/32 //datacount + //|| dmi_value[3:0]!=`TDT_DM_CORE_MAX_XLEN/32 //datacount + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + + dh.part_start("DM.COMMAND default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_COMMAND, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + + dh.part_start("DM.abstractauto default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTAUTO, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + +`ifdef TDT_DM_SBA + dh.part_start("DM.sbcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_SBCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + dmi_expected_value = 32'b0; + dmi_expected_value[31:29] = 3'd1;//sbversion + dmi_expected_value[19:17] = 3'd2; //sbaccess + dmi_expected_value[11:5] = 7'd32; //sbasize + `ifdef TDT_DM_SBA_DW_128 + dmi_expected_value[4] = 1'b1; //sbaccess128 + `endif + `ifdef TDT_DM_SBA_DW_64 + dmi_expected_value[3] = 1'b1; //sbaccess64 + `endif + dmi_expected_value[2] = 1'b1; //sbaccess32 + if (dmi_value[31:0]!= dmi_expected_value) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end +`else + dh.part_start("DM.sbcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_SBCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + dmi_expected_value = 32'b0; + if (dmi_value[31:0]!= dmi_expected_value) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end +`endif +//********************************************************** +//dm itr +//********************************************************** + + + //0.prepare + //enabel dm and select hart0 + dmi_op = `DMI_WRITE; + dmi_address = `DM_DMCONTROL; + dmi_value = 32'd1; //enable dactive + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + + //enter halt mode + dh.hart0_sync_halt_req(); + + //------------------ + //part1: test mepc write with program buffer: + // - write mepc with program buffer, then read back with abscmd, cmp the result + // - pb instructions: csrw mepc, s0; ebreak + dh.part_start("test mepc read/write with itr"); + //abscmd write s0=5a5a5a5a + dmi_value = 32'h5a5a5a5a; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 write error"); + end +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd execute error"); + end + //execute itr csrw mepc, so + dmi_value = `CSRW_MEPC_X8; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr execute error"); + end + //-read mepc(0x341) with abscmd +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b0, 16'h0341, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b0, 16'h0341, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read mepc execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'h5a5a5a5a) begin + dh.tb_error($sformatf("mepc pb write failed, with real mepc value[%0h]", dmi_value)); + end + + //write mepc with abscmd, and read mepc with pb + //-write mepc(0x341) with abscmd; csrr s0, mepc; ebreak + dmi_value = 32'ha5a5a5a5; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b1, 16'h0341, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b1, 16'h0341, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd write mepc execute error"); + end + //-read mepc(0x341) with pb + //-write epc with itr + dmi_value = `CSRR_X8_MEPC; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr csrr_x8_mepc execute error"); + end + //--read back s0 to data0 by abscmd + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1008, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read mepc execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'ha5a5a5a4) begin + dh.tb_error($sformatf("mepc pb read failed, with real mepc value[%0h]", dmi_value)); + end + + //------------------ + //part2: test f1 read: + // - write s0 with abscmd to 0xffff0000 + // - write f1 with program buffer, fmv.w.x f1, s0, fmv.x.w s1, f1 + // - then read back s1 with abscmd +`ifdef FPU + dh.part_start("test f1 read with program buffer"); + //write s0=ffff0000 + dmi_value = 32'hffff0000; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 write error"); + end + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd write s0 execute error"); + end + //-write pb + dmi_value = `FMV_X_W_F1_X8; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr fmv.x.w f1, x8 execute error"); + end + dmi_value = `FMV_W_X_X9_F1; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr fmv.w.x x9, f1 execute error"); + end + + //--read back s1 to data0 by abscmd + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1009, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read s1 execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'hffff0000) begin + dh.tb_error($sformatf("f1 read failed, with real f1 value[%0h] != 0xffff0000", dmi_value)); + end +`endif + + + //itr execution + //fff0011b addiw x2,x0,-1 + //03f11113 slli x2,x2,0x3f + //fff00293 li x5,-1 + //02514333 div x6,x2,x5 + //li x7 , 0xffffffff80000000 + //bne x6 , x7 , TEST_FAIL + +`ifdef TDT_DM_CORE_RV64 + dh.part_start("itr div execution"); + itr_opcodes.push_back(32'hfff0011b); // addiw x2,x0,-1 + itr_opcodes.push_back(32'h03f11113); // slli x2,x2,0x3f + itr_opcodes.push_back(32'hfff00293); // li x5,-1 + itr_opcodes.push_back(32'h02514333); // div x6,x2,x5 + foreach(itr_opcodes[i]) begin + dmi_value = itr_opcodes[i]; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr execute error"); + end + end + + //--read back x6 to data0/1 by abscmd + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1006, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read s1 execute error"); + end + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + data_back[31:0] = dmi_value; + dh.access_abscmd_data(1'b0, 32'd1, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + data_back[63:32] = dmi_value; + if (data_back != 64'h8000000000000000) begin + dh.tb_error($sformatf("x6[%0h] != 0xf8000000000000000", data_back)); + end +`endif + +//********************************************************** +// Memory Read / Write +//********************************************************** + $display(" Read Write Memory: begin"); + dmi_value = 32'h12345678; + dh.write_word_by_pb(64'h0000000020005000, dmi_value); + dmi_value = 32'h0; + dh.read_word_by_pb(64'h0000000020005000, dmi_value); + $display(" Memory value = %0h", dmi_value); + $display(" Read Write Memory: end"); + + dh.hart0_resume(); + //test pass finish + dh.trigger_tb_pass_finish(); +end + endmodule + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/debug/JTAG_DRV.vh b/XUANTIE-RV_opene906/smart_run/tests/cases/debug/JTAG_DRV.vh new file mode 100644 index 0000000000000000000000000000000000000000..3acb169daf39c8ef32c13a233450ae869f6ff184 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/debug/JTAG_DRV.vh @@ -0,0 +1,3077 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +`ifndef JTAG_DRV +`define JTAG_DRV + +// TBD: make the macro controlled by yaml file + +`define TDT_TM_MCONTROL_TRI_NUM 3 + + + +//signal renaming +//----------------------------------------------- + +// tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top + +//jtag interface +`define dtm_jtag2_sel tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.pad_tdt_dtm_jtag2_sel + +`ifdef SELECT_2_WIRE_JTAG + `define jtag2_sel 1'b1 +`else + `define jtag2_sel 1'b0 +`endif + +//-clk,rst +`define jtag_tclk tb.jclk +`define jtag_trst_b tb.jrst_b +//-control signals +`define jtag_tdi tb.jtg_tdi +`define jtag_tdo tb.jtg_tdo +`ifdef jtag2_sel + `define jtag_tms_i tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.pad_tdt_dtm_tms_i + `define jtag_tms_o tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.tdt_dtm_pad_tms_o + `define jtag_tms_oe tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.tdt_dtm_pad_tms_oe +`else + `define jtag_tms_i tb.jtg_tms + `define jtag_tms_o tb.jtg_tms +`endif + +`define cpuclk tb.clk +`define cpu_rst tb.rst_b +// `define SYSTEM_APB_EN 1'b1 + +//CORE0 +`define core0_cpu_retire_pc tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire_pc[31:0] +`define core0_cpu_retire0 tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire +`define mstatus tb.x_soc.x_cpu_sub_system_ahb.cp0_pad_mstatus + +//CORE0 insterrupt related +`define s_lpmd_mt_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_mt_int +`define s_lpmd_me_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_me_int +`define s_lpmd_ms_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_ms_int + + + +//----------------------------------------------- +//define the instructions opcodes +`define EBREAK 32'h00100073 +`define MV_X0_X0 32'h00000013 +`define MV_X1_X1 16'h8086 +`define MV_X2_X2 16'h810a +`define MV_X3_X3 16'h818e +`define MV_X4_X4 16'h8212 +`define MV_X5_X5 16'h8296 +`define MV_X6_X6 16'h831a +`define MV_X7_X7 16'h839e +`define MV_X8_X8 16'h8422 +`define MV_X9_X9 16'h84a6 +`define MV_X10_X10 16'h852a +`define MV_X11_X11 16'h85ae +`define MV_X12_X12 16'h8632 +`define MV_X13_X13 16'h86b6 +`define MV_X14_X14 16'h873a +`define MV_X15_X15 16'h87be +`define MV_X16_X16 16'h8842 +`define MV_X17_X17 16'h88c6 +`define MV_X18_X18 16'h894a +`define MV_X19_X19 16'h89ce +`define MV_X20_X20 16'h8a52 +`define MV_X21_X21 16'h8ad6 +`define MV_X22_X22 16'h8b5a +`define MV_X23_X23 16'h8bde +`define MV_X24_X24 16'h8c62 +`define MV_X25_X25 16'h8ce6 +`define MV_X26_X26 16'h8d6a +`define MV_X27_X27 16'h8dee +`define MV_X28_X28 16'h8e72 +`define MV_X29_X29 16'h8ef6 +`define MV_X30_X30 16'h8f7a +`define MV_X31_X31 16'h8ffe + +// FMV instructions +// Single +`define FMV_W_X_X9_F1 32'he00084d3 +`define FMV_X_W_F1_X8 32'hf00400d3 + + +`define FMV_X_W_X8_F16 32'he0080453 +`define FMV_X_W_X8_F17 32'he0088453 +`define FMV_X_W_X8_F18 32'he0090453 +`define FMV_X_W_X8_F19 32'he0098453 +`define FMV_X_W_X8_F20 32'he00a0453 +`define FMV_X_W_X8_F21 32'he00a8453 +`define FMV_X_W_X8_F22 32'he00b0453 +`define FMV_X_W_X8_F23 32'he00b8453 +`define FMV_X_W_X8_F24 32'he00c0453 +`define FMV_X_W_X8_F25 32'he00c8453 +`define FMV_X_W_X8_F26 32'he00d0453 +`define FMV_X_W_X8_F27 32'he00d8453 +`define FMV_X_W_X8_F28 32'he00e0453 +`define FMV_X_W_X8_F29 32'he00e8453 +`define FMV_X_W_X8_F30 32'he00f0453 +`define FMV_X_W_X8_F31 32'he00f8453 + +// Double +`define FMV_X_D_X8_F0 32'he2000453 +`define FMV_X_D_X8_F1 32'he2008453 +`define FMV_X_D_X8_F2 32'he2010453 +`define FMV_X_D_X8_F3 32'he2018453 +`define FMV_X_D_X8_F4 32'he2020453 +`define FMV_X_D_X8_F5 32'he2028453 +`define FMV_X_D_X8_F6 32'he2030453 +`define FMV_X_D_X8_F7 32'he2038453 +`define FMV_X_D_X8_F8 32'he2040453 +`define FMV_X_D_X8_F9 32'he2048453 +`define FMV_X_D_X8_F10 32'he2050453 +`define FMV_X_D_X8_F11 32'he2058453 +`define FMV_X_D_X8_F12 32'he2060453 +`define FMV_X_D_X8_F13 32'he2068453 +`define FMV_X_D_X8_F14 32'he2070453 +`define FMV_X_D_X8_F15 32'he2078453 +`define FMV_X_D_X8_F16 32'he2080453 +`define FMV_X_D_X8_F17 32'he2088453 +`define FMV_X_D_X8_F18 32'he2090453 +`define FMV_X_D_X8_F19 32'he2098453 +`define FMV_X_D_X8_F20 32'he20a0453 +`define FMV_X_D_X8_F21 32'he20a8453 +`define FMV_X_D_X8_F22 32'he20b0453 +`define FMV_X_D_X8_F23 32'he20b8453 +`define FMV_X_D_X8_F24 32'he20c0453 +`define FMV_X_D_X8_F25 32'he20c8453 +`define FMV_X_D_X8_F26 32'he20d0453 +`define FMV_X_D_X8_F27 32'he20d8453 +`define FMV_X_D_X8_F28 32'he20e0453 +`define FMV_X_D_X8_F29 32'he20e8453 +`define FMV_X_D_X8_F30 32'he20f0453 +`define FMV_X_D_X8_F31 32'he20f8453 +`define FMV_D_X_F0_X8 32'hf2040053 +`define FMV_D_X_F1_X8 32'hf20400d3 +`define FMV_D_X_F2_X8 32'hf2040153 +`define FMV_D_X_F3_X8 32'hf20401d3 +`define FMV_D_X_F4_X8 32'hf2040253 +`define FMV_D_X_F5_X8 32'hf20402d3 +`define FMV_D_X_F6_X8 32'hf2040353 +`define FMV_D_X_F7_X8 32'hf20403d3 +`define FMV_D_X_F8_X8 32'hf2040453 +`define FMV_D_X_F9_X8 32'hf20404d3 +`define FMV_D_X_F10_X8 32'hf2040553 +`define FMV_D_X_F11_X8 32'hf20405d3 +`define FMV_D_X_F12_X8 32'hf2040653 +`define FMV_D_X_F13_X8 32'hf20406d3 +`define FMV_D_X_F14_X8 32'hf2040753 +`define FMV_D_X_F15_X8 32'hf20407d3 +`define FMV_D_X_F16_X8 32'hf2040853 +`define FMV_D_X_F17_X8 32'hf20408d3 +`define FMV_D_X_F18_X8 32'hf2040953 +`define FMV_D_X_F19_X8 32'hf20409d3 +`define FMV_D_X_F20_X8 32'hf2040a53 +`define FMV_D_X_F21_X8 32'hf2040ad3 +`define FMV_D_X_F22_X8 32'hf2040b53 +`define FMV_D_X_F23_X8 32'hf2040bd3 +`define FMV_D_X_F24_X8 32'hf2040c53 +`define FMV_D_X_F25_X8 32'hf2040cd3 +`define FMV_D_X_F26_X8 32'hf2040d53 +`define FMV_D_X_F27_X8 32'hf2040dd3 +`define FMV_D_X_F28_X8 32'hf2040e53 +`define FMV_D_X_F29_X8 32'hf2040ed3 +`define FMV_D_X_F30_X8 32'hf2040f53 +`define FMV_D_X_F31_X8 32'hf2040fd3 + + +// Arithmetic Instructions +`define NOP 32'h00000013 +`define C_NOP 16'h0001 +`define ADDI_X5_X5_4 32'h00428293 +`define ADDI_X6_X6_4 32'h00430313 +`define SUBI_X5_X5_4 32'hffc28293 +`define ADD_X1_X0_X0 32'h000000b3 +`define ADD_X1_X1_1 32'h00108093 + +// Vector instructions +`define VMV_X_S_X0_X1 32'h32102057 +`define VSLIDE1DOWN_VX_V1_V1_X0 32'h3e1060d7 + + +// CSR R/W instructions +`define CSRW_HARTID_S0 32'hf1441073 +`define CSRR_X5_MCAUSE 32'h342022f3 +`define CSRR_X5_MSTATUS 32'h300022f3 +`define CSRR_X5_MXSTATUS 32'h7c0022f3 +`define CSRR_X0_MSTATUS 32'h30002073 +`define CSRW_MSTATUS_X0 32'h30001073 +`define CSRR_X0_SSTATUS 32'h10002073 +`define CSRW_SSTATUS_X0 32'h10001073 +`define CSRR_X0_SMCIR 32'h9c302073 +`define CSRW_SMCIR_X0 32'h9c301073 +`define CSRR_X0_MRVBR 32'h7c702073 +`define CSRW_MRVBR_X0 32'h7c701073 +`define CSRR_X0_MTVAL 32'h34302073 +`define CSRW_MTVAL_X0 32'h34301073 + +`define CSRW_PMPADDR0_X1 32'h3b009073 +`define CSRW_PMPADDR1_X1 32'h3b109073 +`define CSRW_PMPADDR2_X1 32'h3b209073 +`define CSRW_PMPADDR3_X1 32'h3b309073 +`define CSRW_PMPADDR4_X1 32'h3b409073 +`define CSRW_PMPADDR5_X1 32'h3b509073 +`define CSRW_PMPADDR6_X1 32'h3b609073 +`define CSRR_X1_PMPADDR0 32'h3b0020f3 +`define CSRR_X1_PMPADDR1 32'h3b1020f3 +`define CSRR_X1_PMPADDR2 32'h3b2020f3 +`define CSRR_X1_PMPADDR3 32'h3b3020f3 +`define CSRR_X1_PMPADDR4 32'h3b4020f3 +`define CSRR_X1_PMPADDR5 32'h3b5020f3 +`define CSRR_X1_PMPADDR6 32'h3b6020f3 + +`define CSRW_MEPC_X1 32'h34109073 +`define CSRR_X1_MEPC 32'h341020f3 +`define CSRW_MEPC_X8 32'h34141073 +`define CSRR_X8_MEPC 32'h34102473 + +`define CSRR_X3_MCPUID 32'hfc0021f3 + + +// CACHE instructions +`define DCACHE_IALL 32'h0020000b +`define DCACHE_CIALL 32'h0030000b +`define DCACHE_IPA_X5 32'h02a2800b +`define DCACHE_IVA_X5 32'h0262800b +`define DCACHE_CALL 32'h0010000b + +// LD/ST instructions +`define LD_X5_0_X6 32'h00033283 +`define LD_X5_0_X7 32'h0003b283 +`define LD_X5_0_X8 32'h00043283 +`define SD_X5_0_X6 32'h00533023 +`define SD_X5_0_X7 32'h0053b023 +`define SD_X5_0_X8 32'h00543023 + +`define LW_X7_0_X6 32'h00032383 +`define LW_X7_4_X6 32'h00432383 +`define LW_X7_8_X6 32'h00832383 +`define LW_X7_12_X6 32'h00C32383 +`define LW_X7_16_X6 32'h01032383 +`define LW_X7_24_X6 32'h01832383 +`define LW_X7_64_X6 32'h04032383 +`define LW_X7_0_X8 32'h00042383 +`define LW_X7_64_X8 32'h04042383 +`define SW_X7_0_X6 32'h00732023 +`define SW_X7_8_X6 32'h00732423 +`define SW_X7_16_X6 32'h00732823 +`define SW_X7_24_X6 32'h00732c23 + +`define LD_X7_0_X6 32'h00033383 +`define LD_X7_8_X6 32'h00833383 +`define LD_X7_16_X6 32'h01033383 +`define LD_X7_24_X6 32'h01833383 +`define SD_X7_0_X6 32'h00733023 +`define SD_X7_8_X6 32'h00733423 +`define SD_X7_16_X6 32'h00733823 +`define SD_X7_24_X6 32'h00733c23 + +`define LW_X6_0_X5 32'h0002a303 +// `define MFCR_R1_CR0 32'hc0006021 +// `define MFCR_R5_CR0 32'hc0006025 +// `define MFCR_R6_CR0_B3 32'hc0606026 +// `define MFCR_R1_CR1 32'hc0016021 +// `define MFCR_R1_CR1_B1 32'hc0216021 +// `define MFCR_R1_CR1_B3 32'hc0616021 +// `define MFCR_R1_CR2 32'hc0026021 +// `define MFCR_R1_CR2_B3 32'hc0626021 +// `define MFCR_R1_CR3 32'hc0036021 +// `define MFCR_R1_CR4 32'hc0046021 +// `define MFCR_R1_CR4_B3 32'hc0646021 +// `define MFCR_R1_CR5 32'hc0056021 +// `define MFCR_R1_CR6 32'hc0066021 +// `define MFCR_R1_CR6_B3 32'hc0666021 +// `define MFCR_R1_CR7 32'hc0076021 +// `define MFCR_R1_CR7_B3 32'hc0676021 +// `define MFCR_R1_CR8 32'hc0086021 +// `define MFCR_R1_CR8_B3 32'hc0686021 +// `define MFCR_R1_CR9 32'hc0096021 +// `define MFCR_R1_CR10 32'hc00a6021 +// `define MFCR_R1_CR10_B3 32'hc06a6021 +// `define MFCR_R1_CR11 32'hc00b6021 +// `define MFCR_R1_CR12 32'hc00c6021 +// `define MFCR_R1_CR13 32'hc00d6021 +// `define MFCR_R1_CR14 32'hc00e6021 +// `define MFCR_R1_CR14_B1 32'hc02e6021 +// `define MFCR_R1_CR15 32'hc00f6021 +// `define MFCR_R1_CR16 32'hc0106021 +// `define MFCR_R1_CR17 32'hc0116021 +// `define MFCR_R1_CR18 32'hc0126021 +// `define MFCR_R1_CR19 32'hc0136021 +// `define MFCR_R1_CR20 32'hc0146021 +// `define MFCR_R1_CR21 32'hc0156021 +// +// `define MTCR_R1_CR0 32'hc0016420 +// `define MTCR_R4_CR0 32'hc0046420 +// `define MTCR_R7_CR0 32'hc0076420 +// `define MTCR_R7_CR0_B3 32'hc0676420 +// `define MTCR_R1_CR1 32'hc0016421 +// `define MTCR_R11_CR1 32'hc00b6421 +// `define MTCR_R11_CR1_B1 32'hc02b6421 +// `define MTCR_R11_CR1_B3 32'hc06b6421 +// `define MTCR_R5_CR1_B3 32'hc0656421 +// `define MTCR_R6_CR1_B3 32'hc0666421 +// `define MTCR_R1_CR2 32'hc0016422 +// `define MTCR_R10_CR2 32'hc00a6422 +// `define MTCR_R9_CR2_B3 32'hc0696422 +// `define MTCR_R9_CR2 32'hc0096422 +// `define MTCR_R1_CR3 32'hc0016423 +// `define MTCR_R1_CR4 32'hc0016424 +// `define MTCR_R10_CR4 32'hc00a6424 +// `define MTCR_R9_CR4_B3 32'hc0696424 +// `define MTCR_R9_CR4 32'hc0096424 +// `define MTCR_R1_CR5 32'hc0016425 +// `define MTCR_R1_CR6 32'hc0016426 +// `define MTCR_R9_CR6_B3 32'hc0696426 +// `define MTCR_R1_CR7 32'hc0016427 +// `define MTCR_R12_CR7_B3 32'hc06c6427 +// `define MTCR_R1_CR8 32'hc0016428 +// `define MTCR_R1_CR9 32'hc0016429 +// `define MTCR_R1_CR10 32'hc001642a +// `define MTCR_R11_CR10_B3 32'hc06b642a +// `define MTCR_R1_CR11 32'hc001642b +// `define MTCR_R1_CR12 32'hc001642c +// `define MTCR_R1_CR13 32'hc001642d +// `define MTCR_R10_CR14_B1 32'hc02a642e +// `define MTCR_R12_CR14_B1 32'hc02c642e +// +// `define MTCR_R1_CR17 32'hc0016431 +// `define MTCR_R13_CR19 32'hc00d6433 +// `define MTCR_R1_CR31 32'hc001643f + +// `define MFCR_R1_CR0 32'hc0006021 +// `define MFCR_R5_CR0 32'hc0006025 +// `define MFCR_R6_CR0_B3 32'hc0606026 +// `define MFCR_R1_CR1 32'hc0016021 +// `define MFCR_R1_CR1_B1 32'hc0216021 +// `define MFCR_R1_CR1_B3 32'hc0616021 +// `define MFCR_R1_CR2 32'hc0026021 +// `define MFCR_R1_CR2_B3 32'hc0626021 +// `define MFCR_R1_CR3 32'hc0036021 +// `define MFCR_R1_CR4 32'hc0046021 +// `define MFCR_R1_CR4_B3 32'hc0646021 +// `define MFCR_R1_CR5 32'hc0056021 +// `define MFCR_R1_CR6 32'hc0066021 +// `define MFCR_R1_CR6_B3 32'hc0666021 +// `define MFCR_R1_CR7 32'hc0076021 +// `define MFCR_R1_CR7_B3 32'hc0676021 +// `define MFCR_R1_CR8 32'hc0086021 +// `define MFCR_R1_CR8_B3 32'hc0686021 +// `define MFCR_R1_CR9 32'hc0096021 +// `define MFCR_R1_CR10 32'hc00a6021 +// `define MFCR_R1_CR10_B3 32'hc06a6021 +// `define MFCR_R1_CR11 32'hc00b6021 +// `define MFCR_R1_CR12 32'hc00c6021 +// `define MFCR_R1_CR13 32'hc00d6021 +// `define MFCR_R1_CR14 32'hc00e6021 +// `define MFCR_R1_CR14_B1 32'hc02e6021 +// `define MFCR_R1_CR15 32'hc00f6021 +// `define MFCR_R1_CR16 32'hc0106021 +// `define MFCR_R1_CR17 32'hc0116021 +// `define MFCR_R1_CR18 32'hc0126021 +// `define MFCR_R1_CR19 32'hc0136021 +// `define MFCR_R1_CR20 32'hc0146021 +// `define MFCR_R1_CR21 32'hc0156021 +// +// `define MTCR_R1_CR0 32'hc0016420 +// `define MTCR_R4_CR0 32'hc0046420 +// `define MTCR_R7_CR0 32'hc0076420 +// `define MTCR_R7_CR0_B3 32'hc0676420 +// `define MTCR_R1_CR1 32'hc0016421 +// `define MTCR_R11_CR1 32'hc00b6421 +// `define MTCR_R11_CR1_B1 32'hc02b6421 +// `define MTCR_R11_CR1_B3 32'hc06b6421 +// `define MTCR_R5_CR1_B3 32'hc0656421 +// `define MTCR_R6_CR1_B3 32'hc0666421 +// `define MTCR_R1_CR2 32'hc0016422 +// `define MTCR_R10_CR2 32'hc00a6422 +// `define MTCR_R9_CR2_B3 32'hc0696422 +// `define MTCR_R9_CR2 32'hc0096422 +// `define MTCR_R1_CR3 32'hc0016423 +// `define MTCR_R1_CR4 32'hc0016424 +// `define MTCR_R10_CR4 32'hc00a6424 +// `define MTCR_R9_CR4_B3 32'hc0696424 +// `define MTCR_R9_CR4 32'hc0096424 +// `define MTCR_R1_CR5 32'hc0016425 +// `define MTCR_R1_CR6 32'hc0016426 +// `define MTCR_R9_CR6_B3 32'hc0696426 +// `define MTCR_R1_CR7 32'hc0016427 +// `define MTCR_R12_CR7_B3 32'hc06c6427 +// `define MTCR_R1_CR8 32'hc0016428 +// `define MTCR_R1_CR9 32'hc0016429 +// `define MTCR_R1_CR10 32'hc001642a +// `define MTCR_R11_CR10_B3 32'hc06b642a +// `define MTCR_R1_CR11 32'hc001642b +// `define MTCR_R1_CR12 32'hc001642c +// `define MTCR_R1_CR13 32'hc001642d +// `define MTCR_R10_CR14_B1 32'hc02a642e +// `define MTCR_R12_CR14_B1 32'hc02c642e +// +// `define MTCR_R1_CR17 32'hc0016431 +// `define MTCR_R13_CR19 32'hc00d6433 +// `define MTCR_R1_CR31 32'hc001643f + +`define MRET 32'h30200073 +`define SRET 32'h10200073 +`define INS_DRET 32'h7b200073 +`define INS_WFI 32'h10500073 +`define INS_ECALL 32'h00000073 + +`define LW_X7_0_X6 32'h00032383 +`define LW_X7_4_X6 32'h00432383 +`define LW_X7_8_X6 32'h00832383 +`define LW_X7_12_X6 32'h00C32383 +`define LW_X7_16_X6 32'h01032383 +`define LW_X7_24_X6 32'h01832383 +`define LW_X7_64_X6 32'h04032383 +`define LW_X7_0_X8 32'h00042383 +`define LW_X7_64_X8 32'h04042383 +`define SW_X7_0_X6 32'h00732023 +`define SW_X7_8_X6 32'h00732423 +`define SW_X7_16_X6 32'h00732823 +`define SW_X7_24_X6 32'h00732c23 + +`define LD_X7_0_X6 32'h00033383 +`define LD_X7_8_X6 32'h00833383 +`define LD_X7_16_X6 32'h01033383 +`define LD_X7_24_X6 32'h01833383 +`define SD_X7_0_X6 32'h00733023 +`define SD_X7_8_X6 32'h00733423 +`define SD_X7_16_X6 32'h00733823 +`define SD_X7_24_X6 32'h00733c23 + +`define LUI_T0_4 32'h000042b7 +`define LW_X0_0_T0 32'h0002a003 + + +//----------------------------------------------- +//define the DEBUG registers + +//------------------------------------------------- +`define DTM_BYPASS 5'h0 +`define DTM_IDCODE 5'h01 +`define DTM_DMIACC 5'h02 +`define DTM_DTMCS 5'h10 +`define DTM_DMI 5'h11 +`define DTM_BYPASS1 5'h1f +`define DTM_DTMCS_ABIT 5'd10 +`define DTM_DTMCS_VERSION 4'd1 + +`define DMI_NOP 2'b00 +`define DMI_READ 2'b01 +`define DMI_WRITE 2'b10 + +//Data0-11 0x04-0x0f Abstract data +//dmcontrol 0x10 Debug module control +//dmstatus 0x11 Debug module status +//hartinfo 0x12 Harts information +//hawindow 0x15 Hart array window +//abstractcs 0x16 Abstract command control and status +//command 0x17 Abstract command +//Abstractauto 0x18 Abstract command autoexec +//nextdm 0x1d Next debug module base address +//Progbuf0-15 0x20-0x2f Program buffer +//Dmcs2 0x32 Debug module control and status 2 +//Sbcs 0x38 System bus access control and status +//Sbaddress0 0x39 System bus access address 0 +//Sbaddress1 0x3a System bus access address 1 +//Sbdata0 0x3c System bus access data 0 +//Sbdata1 0x3d System bus access data 1 +//Sbdata2 0x3e System bus access data 2 +//Sbdata3 0x3f System bus access data 3 +//Haltsum0 0x40 Halts summary 0 +`define DM_DATA0 10'h4 +`define DM_DATA1 10'h5 +`define DM_DATA2 10'h6 +`define DM_DATA3 10'h7 +`define DM_DATA4 10'h8 +`define DM_DATA5 10'h9 +`define DM_DATA6 10'ha +`define DM_DATA7 10'hb +`define DM_DATA8 10'hc +`define DM_DATA9 10'hd +`define DM_DATA10 10'he +`define DM_DATA11 10'hf +`define DM_DMCONTROL 10'h10 +`define DM_DMSTATUS 10'h11 +`define DM_HARTINFO 10'h12 +`define DM_HAWINDOWSEL 10'h14 +`define DM_HAWINDOW 10'h15 +`define DM_ABSTRACTCS 10'h16 +`define DM_COMMAND 10'h17 +`define DM_ABSTRACTAUTO 10'h18 +`define DM_NEXTDM 10'h1d +`define DM_PROGBUF0 10'h20 +`define DM_PROGBUF1 10'h21 +`define DM_PROGBUF2 10'h22 +`define DM_PROGBUF3 10'h23 +`define DM_PROGBUF4 10'h24 +`define DM_PROGBUF5 10'h25 +`define DM_PROGBUF6 10'h26 +`define DM_PROGBUF7 10'h27 +`define DM_PROGBUF8 10'h28 +`define DM_PROGBUF9 10'h29 +`define DM_PROGBUF10 10'h2a +`define DM_PROGBUF11 10'h2b +`define DM_PROGBUF12 10'h2c +`define DM_PROGBUF13 10'h2d +`define DM_PROGBUF14 10'h2e +`define DM_PROGBUF15 10'h2f +`define DM_DMCS2 10'h32 +`define DM_SBCS 10'h38 +`define DM_SBADDRESS0 10'h39 +`define DM_SBADDRESS1 10'h3a +`define DM_SBADDRESS2 10'h3b +`define DM_SBADDRESS3 10'h37 +`define DM_SBDATA0 10'h3c +`define DM_SBDATA1 10'h3d +`define DM_SBDATA2 10'h3e +`define DM_SBDATA3 10'h3f +`define DM_HALTSUM0 10'h40 +`define DM_ITR 10'h1f +`define DM_CUSTOMCS 10'h70 +`define DM_CUSTOMCMD 10'h71 +`define DM_CUSTOMBUF0 10'h72 +`define DM_CUSTOMBUF1 10'h73 +`define DM_CUSTOMBUF2 10'h74 +`define DM_CUSTOMBUF3 10'h75 +`define DM_CUSTOMBUF4 10'h76 +`define DM_CUSTOMBUF5 10'h77 +`define DM_CUSTOMBUF6 10'h78 +`define DM_CUSTOMBUF7 10'h79 +`define DM_COMPID 10'h7f + +`define REG_CSR 2'd0 +`define REG_GPR 2'd1 +`define REG_FPR 2'd2 + +import "DPI-C" function void update_isa_trigger_csr(int tselect, int csr_num, longint csr_data); +//---------------------------------------------------- + +//jtag reset, for example: jtag_rst(100) +task jtag_rst; +input[31:0] rst_cycle; +integer i; +begin + //$display("%0t jtag reset starts", $time); + if (`jtag2_sel) begin + force `dtm_jtag2_sel = 1'b1; + force `jtag_tms_i = 1'b0; + @(negedge `jtag_tclk); + //wait for user specified cycles + for(i=0; i<82; i=i+1) begin + force `jtag_tms_i = 1'b1; + @(negedge `jtag_tclk); + end + end + + else begin + force `jtag_trst_b = 1'b1; + if (`jtag2_sel) + force `jtag_tms_i = 1'b1; + else + force `jtag_tms_i = 1'b0; + //wait until posedge tclk + @(negedge `jtag_tclk); + force `jtag_trst_b = 1'b0; + + //wait for user specified cycles + for(i=0; i>> DEBUG:Simulation Failed! @_@ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + +endtask: trigger_tb_error_finish + +//this task trigger testbench pass finish +task ext_debug::trigger_tb_pass_finish(); + integer FILE; + if (this.error_num > 0) begin + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + $display("$ Sorry, <<< CORE 0 >>> Simulation Failed! @_@ $"); + $display("$ You can have some tea and try again ^_^ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + end else begin + // exit + $display("#######################################################################"); + $display("# Congratulations, Simulation PASS! #"); + $display("#######################################################################"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST PASS"); + $finish; + end +endtask: trigger_tb_pass_finish + +//this task trigger testbench pass finish +task ext_debug::trigger_tb_bypass_finish(); + integer FILE; + if (this.error_num > 0) begin + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + $display("$ Sorry, <<< CORE 0 >>> Simulation Failed! @_@ $"); + $display("$ You can have some tea and try again ^_^ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + end else begin + // exit + $display("#######################################################################"); + $display("# This case was byPASSed because of feature not support! #"); + $display("#######################################################################"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST PASS"); + $finish; + end +endtask: trigger_tb_bypass_finish + +task ext_debug::hart0_async_halt_req(); + bit[1:0] dmi_op; + bit[`DTM_DTMCS_ABIT-1:0] dmi_address; + int dmi_value; + bit error; + this.tb_info("hart0: async halt request starts..."); + dmi_op = `DMI_WRITE; + dmi_address = `DM_CUSTOMCMD; + dmi_value = 32'h0; //dmcontrol.haltreq=1, dmcontrol.dmactive=1 + this.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("customcmd set error!"); + end + + //check haltsum0 + for (int i=0; i= pc_start && `core0_cpu_retire_pc <= pc_end) begin + + //part1.basic gpr/read write using abstract command + this.part_start("async halt start here:"); + + //enter halt mode + //this.hart0_async_halt_req(); + force `dtu_rtu_async_halt_req=1'b1; + @(posedge `cpuclk); + release `dtu_rtu_async_halt_req; + this.hart0_resume(); + + end + else begin + @(posedge `cpuclk); + end + + + + end + +`endif + +endtask:rand_async_halt + + +task ext_debug::clear_cmderr; +bit [31:0] dmi_value; +bit error; + this.part_start("DM.abstractcs cmderr clear:"); + dmi_value = 32'd0; + this.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("dmi read error"); + end + dmi_value[10:8]=3'b111; + this.rwMemorybyDMIwithCheck(`DMI_WRITE, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("dmi read error"); + end +endtask:clear_cmderr + +// task ext_debug::force_trigger_signal(bit exe, bit load, bit store, bit timing, bit select, bit action, bit [63:0] tdata2); +// `define CLK_dtu pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.forever_cpuclk +// `define ifu_addr_vld0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_addr_vld0 +// `define ifu_addr0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_exe_addr0[31:0] +// `define ifu_addr_vld1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_data_vld1 +// `define ifu_addr1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_exe_addr1[31:0] +// `define halt_info_ifu_vld pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info_vld +// `define halt_info_ifu0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info0[`TDT_HINFO_WIDTH-1:0] +// `define halt_info_ifu1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info1[`TDT_HINFO_WIDTH-1:0] + +// bit [31:0] ifu_addr0_vld0,ifu_addr1_vld1; +// bit [21:0] halt_info_ifu; + +// assign ifu_addr0_vld0 = {32{`ifu_addr_vld0}} & `ifu_addr0; +// assign ifu_addr1_vld1 = {32{`ifu_addr_vld1}} & `ifu_addr1; +// assign halt_info_ifu[21] = 1'b1; +// assign halt_info_ifu[0] = 1'b1;//cancel +// assign halt_info_ifu[1] = 1'b1;//match +// assign halt_info_ifu[11:8] = 4'b0010;//cause +// assign halt_info_ifu[4] = 1'b0; //action +// forever begin +// if (ifu_addr0_vld0 == tdata2[31:0]) begin +// force `halt_info_ifu_vld = 1'b0; +// @(posedge `CLK_dtu); +// force `halt_info_ifu_vld = 1'b1; +// force `halt_info_ifu0 = halt_info_ifu; +// @(posedge `CLK_dtu); +// release `halt_info_ifu_vld; +// release `halt_info_ifu0; +// end +// end + + +// forever begin +// if (ifu_addr1_vld1 == tdata2[31:0]) begin +// force `halt_info_ifu_vld = 1'b0; +// @(posedge `CLK_dtu); +// force `halt_info_ifu_vld = 1'b1; +// force `halt_info_ifu1 = halt_info_ifu; +// @(posedge `CLK_dtu); +// release `halt_info_ifu_vld; +// release `halt_info_ifu0; +// end +// end +// endtask:force_trigger_signal + +`endif //JTAG_DRV + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/E906_DEBUG_PATTERN.v b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/E906_DEBUG_PATTERN.v new file mode 100644 index 0000000000000000000000000000000000000000..a1c2520f456b6fdaad39daa477f5a56a5de54e38 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/E906_DEBUG_PATTERN.v @@ -0,0 +1,425 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +`define TDT_DM_PB_SIZE 2 + +`define FPU + + + +module E906_DEBUG_PATTERN(); + reg[31:0] had_data_out; +ext_debug dh; +longint rd_value; +longint wr_value; +bit error; + +bit[1:0] dmi_op; +bit[`DTM_DTMCS_ABIT-1:0] dmi_address; +int dmi_value, dmi_expected_value; +int pb_size; + +process process1; +bit[31:0] data_high, data_low, data_temp; +bit[2:0] cmderr; +int halt_poll_num; + +int retire_num, retire_total_num; +bit[39:0] retire_pc; +int step_num; +bit[2:0] aarsize; +bit[31:0] itr_opcodes[$]; +bit[63:0] data_back; + +initial begin + //debug host class init + `ifdef SELECT_2_WIRE_JTAG + $display("RV Debug test, using 2-wire JTAG protocol"); + `else + $display("RV Debug test, using 5-wire JTAG protocol"); + `endif + + dh = new("dh"); + dh.initDTM(); + `ifdef TDT_DM_CORE_RV64 + aarsize=3; + `else + aarsize=2; + `endif + //start reading DTM registers + + wait_mstatus(); + $display("core enter handshake"); + +//********************************************************** +//dtm reg rd/wr +//********************************************************** + //1.check BYPASS value + dh.part_start("DTM.BYPASS"); + wr_value = 64'd0; + rd_value = 64'd0; + dh.rwDTMReg(`DTM_BYPASS, rd_value, wr_value, error); + //TODO: add check logic + $display("dtm.bypass = %0h", rd_value); + + //2.check IDCODE value + dh.part_start("DTM.IDCODE"); + wr_value = 64'd0; + rd_value = 64'd0; + dh.rwDTMReg(`DTM_IDCODE, rd_value, wr_value, error); + //TODO: add check logic + $display("dtm.idcode = %0h", rd_value); + +//********************************************************** +//dm reg rd/wr +//********************************************************** + //enable debug module + dmi_op = `DMI_WRITE; + dmi_address = `DM_DMCONTROL; + dmi_value = 32'd1; //enable dactive + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + + //1.check dmstatus value + dh.part_start("DM.dmstatus default value check:"); + dmi_op = `DMI_READ; + dmi_address = `DM_DMSTATUS; + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + // check DMSTATUS.version=2 + if (dmi_value[3:0] != 4'd2) begin + dh.tb_fatal($sformatf("Error:DM.dmstatus.version should be 2, but now %0h", dmi_value[3:0])); + end + $display("dmi_status default value: %h", dmi_value); + + dh.part_start("DM.dmcontrol default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_DMCONTROL, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value[19]!=1'b0 || + dmi_value[26]!=1'b0 || + dmi_value[25:16]!=10'd0 || + dmi_value[15:6]!=10'd0 || + dmi_value[1]!=1'b0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.hartinfo default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_HARTINFO, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + //if (dmi_value[23:20]!= `TDT_DM_CORE_NSCRATCH || + if (dmi_value[23:20]!= 4'h2 || + dmi_value[16]!=1'b0 || //dataaccess + dmi_value[15:12]!=10'd0 || //datasize + dmi_value[11:0]!=10'd0 //dataaddr + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.hawindowsel default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_HAWINDOWSEL, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + dh.part_start("DM.abstractcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end +`ifdef TDT_DM_PB_SIZE + pb_size = `TDT_DM_PB_SIZE; +`else + pb_size = 0; +`endif + if (dmi_value[28:24]!= pb_size + //if (dmi_value[28:24]!= 5'h1 //ZHAOKUAN TODO + || dmi_value[12]!=1'b0 //busy + || dmi_value[10:8]!=3'b0 //cmderr + || dmi_value[3:0]!=32/32 //datacount + //|| dmi_value[3:0]!=`TDT_DM_CORE_MAX_XLEN/32 //datacount + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + + dh.part_start("DM.COMMAND default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_COMMAND, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + + + dh.part_start("DM.abstractauto default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTAUTO, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + if (dmi_value!= 32'd0 + ) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end + +`ifdef TDT_DM_SBA + dh.part_start("DM.sbcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_SBCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + dmi_expected_value = 32'b0; + dmi_expected_value[31:29] = 3'd1;//sbversion + dmi_expected_value[19:17] = 3'd2; //sbaccess + dmi_expected_value[11:5] = 7'd32; //sbasize + `ifdef TDT_DM_SBA_DW_128 + dmi_expected_value[4] = 1'b1; //sbaccess128 + `endif + `ifdef TDT_DM_SBA_DW_64 + dmi_expected_value[3] = 1'b1; //sbaccess64 + `endif + dmi_expected_value[2] = 1'b1; //sbaccess32 + if (dmi_value[31:0]!= dmi_expected_value) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end +`else + dh.part_start("DM.sbcs default value check:"); + dmi_value = 32'd0; + dh.rwMemorybyDMIwithCheck(`DMI_READ, `DM_SBCS, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("dmi read error"); + end + dmi_expected_value = 32'b0; + if (dmi_value[31:0]!= dmi_expected_value) begin + dh.tb_fatal($sformatf("reset value[%0h] error.", dmi_value)); + end +`endif +//********************************************************** +//dm itr +//********************************************************** + + + //0.prepare + //enabel dm and select hart0 + dmi_op = `DMI_WRITE; + dmi_address = `DM_DMCONTROL; + dmi_value = 32'd1; //enable dactive + dh.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + + //enter halt mode + dh.hart0_sync_halt_req(); + + //------------------ + //part1: test mepc write with program buffer: + // - write mepc with program buffer, then read back with abscmd, cmp the result + // - pb instructions: csrw mepc, s0; ebreak + dh.part_start("test mepc read/write with itr"); + //abscmd write s0=5a5a5a5a + dmi_value = 32'h5a5a5a5a; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 write error"); + end +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd execute error"); + end + //execute itr csrw mepc, so + dmi_value = `CSRW_MEPC_X8; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr execute error"); + end + //-read mepc(0x341) with abscmd +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b0, 16'h0341, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b0, 16'h0341, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read mepc execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'h5a5a5a5a) begin + dh.tb_error($sformatf("mepc pb write failed, with real mepc value[%0h]", dmi_value)); + end + + //write mepc with abscmd, and read mepc with pb + //-write mepc(0x341) with abscmd; csrr s0, mepc; ebreak + dmi_value = 32'ha5a5a5a5; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end +`ifdef TDT_DM_CORE_RV64 + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b1, 16'h0341, cmderr); +`else + dh.access_register_by_abscmd(3'd2, 1'b0, 1'b0, 1'b1, 1'b1, 16'h0341, cmderr); +`endif + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd write mepc execute error"); + end + //-read mepc(0x341) with pb + //-write epc with itr + dmi_value = `CSRR_X8_MEPC; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr csrr_x8_mepc execute error"); + end + //--read back s0 to data0 by abscmd + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1008, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read mepc execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'ha5a5a5a4) begin + dh.tb_error($sformatf("mepc pb read failed, with real mepc value[%0h]", dmi_value)); + end + + //------------------ + //part2: test f1 read: + // - write s0 with abscmd to 0xffff0000 + // - write f1 with program buffer, fmv.w.x f1, s0, fmv.x.w s1, f1 + // - then read back s1 with abscmd +`ifdef FPU + dh.part_start("test f1 read with program buffer"); + //write s0=ffff0000 + dmi_value = 32'hffff0000; + dh.access_abscmd_data(1'b1, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 write error"); + end + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b1, 16'h1008, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd write s0 execute error"); + end + //-write pb + dmi_value = `FMV_X_W_F1_X8; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr fmv.x.w f1, x8 execute error"); + end + dmi_value = `FMV_W_X_X9_F1; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr fmv.w.x x9, f1 execute error"); + end + + //--read back s1 to data0 by abscmd + dh.access_register_by_abscmd(aarsize, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1009, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read s1 execute error"); + end + dmi_value = 32'h0; + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + if (dmi_value != 32'hffff0000) begin + dh.tb_error($sformatf("f1 read failed, with real f1 value[%0h] != 0xffff0000", dmi_value)); + end +`endif + + + //itr execution + //fff0011b addiw x2,x0,-1 + //03f11113 slli x2,x2,0x3f + //fff00293 li x5,-1 + //02514333 div x6,x2,x5 + //li x7 , 0xffffffff80000000 + //bne x6 , x7 , TEST_FAIL + +`ifdef TDT_DM_CORE_RV64 + dh.part_start("itr div execution"); + itr_opcodes.push_back(32'hfff0011b); // addiw x2,x0,-1 + itr_opcodes.push_back(32'h03f11113); // slli x2,x2,0x3f + itr_opcodes.push_back(32'hfff00293); // li x5,-1 + itr_opcodes.push_back(32'h02514333); // div x6,x2,x5 + foreach(itr_opcodes[i]) begin + dmi_value = itr_opcodes[i]; + dh.execute_itr(dmi_value, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("itr execute error"); + end + end + + //--read back x6 to data0/1 by abscmd + dh.access_register_by_abscmd(3'd3, 1'b0, 1'b0, 1'b1, 1'b0, 16'h1006, cmderr); + if (cmderr != 3'b0) begin + dh.tb_fatal("abscmd read s1 execute error"); + end + dh.access_abscmd_data(1'b0, 32'd0, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + data_back[31:0] = dmi_value; + dh.access_abscmd_data(1'b0, 32'd1, dmi_value, error); + if (error == 1'b1) begin + dh.tb_fatal("data0 read error"); + end + data_back[63:32] = dmi_value; + if (data_back != 64'h8000000000000000) begin + dh.tb_error($sformatf("x6[%0h] != 0xf8000000000000000", data_back)); + end +`endif + +//********************************************************** +// Memory Read / Write +//********************************************************** + $display(" Read Write Memory: begin"); + dmi_value = 32'h12345678; + dh.write_word_by_pb(64'h0000000020005000, dmi_value); + dmi_value = 32'h0; + dh.read_word_by_pb(64'h0000000020005000, dmi_value); + $display(" Memory value = %0h", dmi_value); + $display(" Read Write Memory: end"); + + dh.hart0_resume(); + //test pass finish + dh.trigger_tb_pass_finish(); +end + endmodule + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/JTAG_DRV.vh b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/JTAG_DRV.vh new file mode 100644 index 0000000000000000000000000000000000000000..3acb169daf39c8ef32c13a233450ae869f6ff184 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/JTAG_DRV.vh @@ -0,0 +1,3077 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +`ifndef JTAG_DRV +`define JTAG_DRV + +// TBD: make the macro controlled by yaml file + +`define TDT_TM_MCONTROL_TRI_NUM 3 + + + +//signal renaming +//----------------------------------------------- + +// tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top + +//jtag interface +`define dtm_jtag2_sel tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.pad_tdt_dtm_jtag2_sel + +`ifdef SELECT_2_WIRE_JTAG + `define jtag2_sel 1'b1 +`else + `define jtag2_sel 1'b0 +`endif + +//-clk,rst +`define jtag_tclk tb.jclk +`define jtag_trst_b tb.jrst_b +//-control signals +`define jtag_tdi tb.jtg_tdi +`define jtag_tdo tb.jtg_tdo +`ifdef jtag2_sel + `define jtag_tms_i tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.pad_tdt_dtm_tms_i + `define jtag_tms_o tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.tdt_dtm_pad_tms_o + `define jtag_tms_oe tb.x_soc.x_cpu_sub_system_ahb.x_tdt_dmi_top.tdt_dtm_pad_tms_oe +`else + `define jtag_tms_i tb.jtg_tms + `define jtag_tms_o tb.jtg_tms +`endif + +`define cpuclk tb.clk +`define cpu_rst tb.rst_b +// `define SYSTEM_APB_EN 1'b1 + +//CORE0 +`define core0_cpu_retire_pc tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire_pc[31:0] +`define core0_cpu_retire0 tb.x_soc.x_cpu_sub_system_ahb.biu_pad_retire +`define mstatus tb.x_soc.x_cpu_sub_system_ahb.cp0_pad_mstatus + +//CORE0 insterrupt related +`define s_lpmd_mt_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_mt_int +`define s_lpmd_me_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_me_int +`define s_lpmd_ms_int tb.x_soc.x_cpu_sub_system_ahb.x_e906_top.x_pa_tcipif_top.clint_cpu_ms_int + + + +//----------------------------------------------- +//define the instructions opcodes +`define EBREAK 32'h00100073 +`define MV_X0_X0 32'h00000013 +`define MV_X1_X1 16'h8086 +`define MV_X2_X2 16'h810a +`define MV_X3_X3 16'h818e +`define MV_X4_X4 16'h8212 +`define MV_X5_X5 16'h8296 +`define MV_X6_X6 16'h831a +`define MV_X7_X7 16'h839e +`define MV_X8_X8 16'h8422 +`define MV_X9_X9 16'h84a6 +`define MV_X10_X10 16'h852a +`define MV_X11_X11 16'h85ae +`define MV_X12_X12 16'h8632 +`define MV_X13_X13 16'h86b6 +`define MV_X14_X14 16'h873a +`define MV_X15_X15 16'h87be +`define MV_X16_X16 16'h8842 +`define MV_X17_X17 16'h88c6 +`define MV_X18_X18 16'h894a +`define MV_X19_X19 16'h89ce +`define MV_X20_X20 16'h8a52 +`define MV_X21_X21 16'h8ad6 +`define MV_X22_X22 16'h8b5a +`define MV_X23_X23 16'h8bde +`define MV_X24_X24 16'h8c62 +`define MV_X25_X25 16'h8ce6 +`define MV_X26_X26 16'h8d6a +`define MV_X27_X27 16'h8dee +`define MV_X28_X28 16'h8e72 +`define MV_X29_X29 16'h8ef6 +`define MV_X30_X30 16'h8f7a +`define MV_X31_X31 16'h8ffe + +// FMV instructions +// Single +`define FMV_W_X_X9_F1 32'he00084d3 +`define FMV_X_W_F1_X8 32'hf00400d3 + + +`define FMV_X_W_X8_F16 32'he0080453 +`define FMV_X_W_X8_F17 32'he0088453 +`define FMV_X_W_X8_F18 32'he0090453 +`define FMV_X_W_X8_F19 32'he0098453 +`define FMV_X_W_X8_F20 32'he00a0453 +`define FMV_X_W_X8_F21 32'he00a8453 +`define FMV_X_W_X8_F22 32'he00b0453 +`define FMV_X_W_X8_F23 32'he00b8453 +`define FMV_X_W_X8_F24 32'he00c0453 +`define FMV_X_W_X8_F25 32'he00c8453 +`define FMV_X_W_X8_F26 32'he00d0453 +`define FMV_X_W_X8_F27 32'he00d8453 +`define FMV_X_W_X8_F28 32'he00e0453 +`define FMV_X_W_X8_F29 32'he00e8453 +`define FMV_X_W_X8_F30 32'he00f0453 +`define FMV_X_W_X8_F31 32'he00f8453 + +// Double +`define FMV_X_D_X8_F0 32'he2000453 +`define FMV_X_D_X8_F1 32'he2008453 +`define FMV_X_D_X8_F2 32'he2010453 +`define FMV_X_D_X8_F3 32'he2018453 +`define FMV_X_D_X8_F4 32'he2020453 +`define FMV_X_D_X8_F5 32'he2028453 +`define FMV_X_D_X8_F6 32'he2030453 +`define FMV_X_D_X8_F7 32'he2038453 +`define FMV_X_D_X8_F8 32'he2040453 +`define FMV_X_D_X8_F9 32'he2048453 +`define FMV_X_D_X8_F10 32'he2050453 +`define FMV_X_D_X8_F11 32'he2058453 +`define FMV_X_D_X8_F12 32'he2060453 +`define FMV_X_D_X8_F13 32'he2068453 +`define FMV_X_D_X8_F14 32'he2070453 +`define FMV_X_D_X8_F15 32'he2078453 +`define FMV_X_D_X8_F16 32'he2080453 +`define FMV_X_D_X8_F17 32'he2088453 +`define FMV_X_D_X8_F18 32'he2090453 +`define FMV_X_D_X8_F19 32'he2098453 +`define FMV_X_D_X8_F20 32'he20a0453 +`define FMV_X_D_X8_F21 32'he20a8453 +`define FMV_X_D_X8_F22 32'he20b0453 +`define FMV_X_D_X8_F23 32'he20b8453 +`define FMV_X_D_X8_F24 32'he20c0453 +`define FMV_X_D_X8_F25 32'he20c8453 +`define FMV_X_D_X8_F26 32'he20d0453 +`define FMV_X_D_X8_F27 32'he20d8453 +`define FMV_X_D_X8_F28 32'he20e0453 +`define FMV_X_D_X8_F29 32'he20e8453 +`define FMV_X_D_X8_F30 32'he20f0453 +`define FMV_X_D_X8_F31 32'he20f8453 +`define FMV_D_X_F0_X8 32'hf2040053 +`define FMV_D_X_F1_X8 32'hf20400d3 +`define FMV_D_X_F2_X8 32'hf2040153 +`define FMV_D_X_F3_X8 32'hf20401d3 +`define FMV_D_X_F4_X8 32'hf2040253 +`define FMV_D_X_F5_X8 32'hf20402d3 +`define FMV_D_X_F6_X8 32'hf2040353 +`define FMV_D_X_F7_X8 32'hf20403d3 +`define FMV_D_X_F8_X8 32'hf2040453 +`define FMV_D_X_F9_X8 32'hf20404d3 +`define FMV_D_X_F10_X8 32'hf2040553 +`define FMV_D_X_F11_X8 32'hf20405d3 +`define FMV_D_X_F12_X8 32'hf2040653 +`define FMV_D_X_F13_X8 32'hf20406d3 +`define FMV_D_X_F14_X8 32'hf2040753 +`define FMV_D_X_F15_X8 32'hf20407d3 +`define FMV_D_X_F16_X8 32'hf2040853 +`define FMV_D_X_F17_X8 32'hf20408d3 +`define FMV_D_X_F18_X8 32'hf2040953 +`define FMV_D_X_F19_X8 32'hf20409d3 +`define FMV_D_X_F20_X8 32'hf2040a53 +`define FMV_D_X_F21_X8 32'hf2040ad3 +`define FMV_D_X_F22_X8 32'hf2040b53 +`define FMV_D_X_F23_X8 32'hf2040bd3 +`define FMV_D_X_F24_X8 32'hf2040c53 +`define FMV_D_X_F25_X8 32'hf2040cd3 +`define FMV_D_X_F26_X8 32'hf2040d53 +`define FMV_D_X_F27_X8 32'hf2040dd3 +`define FMV_D_X_F28_X8 32'hf2040e53 +`define FMV_D_X_F29_X8 32'hf2040ed3 +`define FMV_D_X_F30_X8 32'hf2040f53 +`define FMV_D_X_F31_X8 32'hf2040fd3 + + +// Arithmetic Instructions +`define NOP 32'h00000013 +`define C_NOP 16'h0001 +`define ADDI_X5_X5_4 32'h00428293 +`define ADDI_X6_X6_4 32'h00430313 +`define SUBI_X5_X5_4 32'hffc28293 +`define ADD_X1_X0_X0 32'h000000b3 +`define ADD_X1_X1_1 32'h00108093 + +// Vector instructions +`define VMV_X_S_X0_X1 32'h32102057 +`define VSLIDE1DOWN_VX_V1_V1_X0 32'h3e1060d7 + + +// CSR R/W instructions +`define CSRW_HARTID_S0 32'hf1441073 +`define CSRR_X5_MCAUSE 32'h342022f3 +`define CSRR_X5_MSTATUS 32'h300022f3 +`define CSRR_X5_MXSTATUS 32'h7c0022f3 +`define CSRR_X0_MSTATUS 32'h30002073 +`define CSRW_MSTATUS_X0 32'h30001073 +`define CSRR_X0_SSTATUS 32'h10002073 +`define CSRW_SSTATUS_X0 32'h10001073 +`define CSRR_X0_SMCIR 32'h9c302073 +`define CSRW_SMCIR_X0 32'h9c301073 +`define CSRR_X0_MRVBR 32'h7c702073 +`define CSRW_MRVBR_X0 32'h7c701073 +`define CSRR_X0_MTVAL 32'h34302073 +`define CSRW_MTVAL_X0 32'h34301073 + +`define CSRW_PMPADDR0_X1 32'h3b009073 +`define CSRW_PMPADDR1_X1 32'h3b109073 +`define CSRW_PMPADDR2_X1 32'h3b209073 +`define CSRW_PMPADDR3_X1 32'h3b309073 +`define CSRW_PMPADDR4_X1 32'h3b409073 +`define CSRW_PMPADDR5_X1 32'h3b509073 +`define CSRW_PMPADDR6_X1 32'h3b609073 +`define CSRR_X1_PMPADDR0 32'h3b0020f3 +`define CSRR_X1_PMPADDR1 32'h3b1020f3 +`define CSRR_X1_PMPADDR2 32'h3b2020f3 +`define CSRR_X1_PMPADDR3 32'h3b3020f3 +`define CSRR_X1_PMPADDR4 32'h3b4020f3 +`define CSRR_X1_PMPADDR5 32'h3b5020f3 +`define CSRR_X1_PMPADDR6 32'h3b6020f3 + +`define CSRW_MEPC_X1 32'h34109073 +`define CSRR_X1_MEPC 32'h341020f3 +`define CSRW_MEPC_X8 32'h34141073 +`define CSRR_X8_MEPC 32'h34102473 + +`define CSRR_X3_MCPUID 32'hfc0021f3 + + +// CACHE instructions +`define DCACHE_IALL 32'h0020000b +`define DCACHE_CIALL 32'h0030000b +`define DCACHE_IPA_X5 32'h02a2800b +`define DCACHE_IVA_X5 32'h0262800b +`define DCACHE_CALL 32'h0010000b + +// LD/ST instructions +`define LD_X5_0_X6 32'h00033283 +`define LD_X5_0_X7 32'h0003b283 +`define LD_X5_0_X8 32'h00043283 +`define SD_X5_0_X6 32'h00533023 +`define SD_X5_0_X7 32'h0053b023 +`define SD_X5_0_X8 32'h00543023 + +`define LW_X7_0_X6 32'h00032383 +`define LW_X7_4_X6 32'h00432383 +`define LW_X7_8_X6 32'h00832383 +`define LW_X7_12_X6 32'h00C32383 +`define LW_X7_16_X6 32'h01032383 +`define LW_X7_24_X6 32'h01832383 +`define LW_X7_64_X6 32'h04032383 +`define LW_X7_0_X8 32'h00042383 +`define LW_X7_64_X8 32'h04042383 +`define SW_X7_0_X6 32'h00732023 +`define SW_X7_8_X6 32'h00732423 +`define SW_X7_16_X6 32'h00732823 +`define SW_X7_24_X6 32'h00732c23 + +`define LD_X7_0_X6 32'h00033383 +`define LD_X7_8_X6 32'h00833383 +`define LD_X7_16_X6 32'h01033383 +`define LD_X7_24_X6 32'h01833383 +`define SD_X7_0_X6 32'h00733023 +`define SD_X7_8_X6 32'h00733423 +`define SD_X7_16_X6 32'h00733823 +`define SD_X7_24_X6 32'h00733c23 + +`define LW_X6_0_X5 32'h0002a303 +// `define MFCR_R1_CR0 32'hc0006021 +// `define MFCR_R5_CR0 32'hc0006025 +// `define MFCR_R6_CR0_B3 32'hc0606026 +// `define MFCR_R1_CR1 32'hc0016021 +// `define MFCR_R1_CR1_B1 32'hc0216021 +// `define MFCR_R1_CR1_B3 32'hc0616021 +// `define MFCR_R1_CR2 32'hc0026021 +// `define MFCR_R1_CR2_B3 32'hc0626021 +// `define MFCR_R1_CR3 32'hc0036021 +// `define MFCR_R1_CR4 32'hc0046021 +// `define MFCR_R1_CR4_B3 32'hc0646021 +// `define MFCR_R1_CR5 32'hc0056021 +// `define MFCR_R1_CR6 32'hc0066021 +// `define MFCR_R1_CR6_B3 32'hc0666021 +// `define MFCR_R1_CR7 32'hc0076021 +// `define MFCR_R1_CR7_B3 32'hc0676021 +// `define MFCR_R1_CR8 32'hc0086021 +// `define MFCR_R1_CR8_B3 32'hc0686021 +// `define MFCR_R1_CR9 32'hc0096021 +// `define MFCR_R1_CR10 32'hc00a6021 +// `define MFCR_R1_CR10_B3 32'hc06a6021 +// `define MFCR_R1_CR11 32'hc00b6021 +// `define MFCR_R1_CR12 32'hc00c6021 +// `define MFCR_R1_CR13 32'hc00d6021 +// `define MFCR_R1_CR14 32'hc00e6021 +// `define MFCR_R1_CR14_B1 32'hc02e6021 +// `define MFCR_R1_CR15 32'hc00f6021 +// `define MFCR_R1_CR16 32'hc0106021 +// `define MFCR_R1_CR17 32'hc0116021 +// `define MFCR_R1_CR18 32'hc0126021 +// `define MFCR_R1_CR19 32'hc0136021 +// `define MFCR_R1_CR20 32'hc0146021 +// `define MFCR_R1_CR21 32'hc0156021 +// +// `define MTCR_R1_CR0 32'hc0016420 +// `define MTCR_R4_CR0 32'hc0046420 +// `define MTCR_R7_CR0 32'hc0076420 +// `define MTCR_R7_CR0_B3 32'hc0676420 +// `define MTCR_R1_CR1 32'hc0016421 +// `define MTCR_R11_CR1 32'hc00b6421 +// `define MTCR_R11_CR1_B1 32'hc02b6421 +// `define MTCR_R11_CR1_B3 32'hc06b6421 +// `define MTCR_R5_CR1_B3 32'hc0656421 +// `define MTCR_R6_CR1_B3 32'hc0666421 +// `define MTCR_R1_CR2 32'hc0016422 +// `define MTCR_R10_CR2 32'hc00a6422 +// `define MTCR_R9_CR2_B3 32'hc0696422 +// `define MTCR_R9_CR2 32'hc0096422 +// `define MTCR_R1_CR3 32'hc0016423 +// `define MTCR_R1_CR4 32'hc0016424 +// `define MTCR_R10_CR4 32'hc00a6424 +// `define MTCR_R9_CR4_B3 32'hc0696424 +// `define MTCR_R9_CR4 32'hc0096424 +// `define MTCR_R1_CR5 32'hc0016425 +// `define MTCR_R1_CR6 32'hc0016426 +// `define MTCR_R9_CR6_B3 32'hc0696426 +// `define MTCR_R1_CR7 32'hc0016427 +// `define MTCR_R12_CR7_B3 32'hc06c6427 +// `define MTCR_R1_CR8 32'hc0016428 +// `define MTCR_R1_CR9 32'hc0016429 +// `define MTCR_R1_CR10 32'hc001642a +// `define MTCR_R11_CR10_B3 32'hc06b642a +// `define MTCR_R1_CR11 32'hc001642b +// `define MTCR_R1_CR12 32'hc001642c +// `define MTCR_R1_CR13 32'hc001642d +// `define MTCR_R10_CR14_B1 32'hc02a642e +// `define MTCR_R12_CR14_B1 32'hc02c642e +// +// `define MTCR_R1_CR17 32'hc0016431 +// `define MTCR_R13_CR19 32'hc00d6433 +// `define MTCR_R1_CR31 32'hc001643f + +// `define MFCR_R1_CR0 32'hc0006021 +// `define MFCR_R5_CR0 32'hc0006025 +// `define MFCR_R6_CR0_B3 32'hc0606026 +// `define MFCR_R1_CR1 32'hc0016021 +// `define MFCR_R1_CR1_B1 32'hc0216021 +// `define MFCR_R1_CR1_B3 32'hc0616021 +// `define MFCR_R1_CR2 32'hc0026021 +// `define MFCR_R1_CR2_B3 32'hc0626021 +// `define MFCR_R1_CR3 32'hc0036021 +// `define MFCR_R1_CR4 32'hc0046021 +// `define MFCR_R1_CR4_B3 32'hc0646021 +// `define MFCR_R1_CR5 32'hc0056021 +// `define MFCR_R1_CR6 32'hc0066021 +// `define MFCR_R1_CR6_B3 32'hc0666021 +// `define MFCR_R1_CR7 32'hc0076021 +// `define MFCR_R1_CR7_B3 32'hc0676021 +// `define MFCR_R1_CR8 32'hc0086021 +// `define MFCR_R1_CR8_B3 32'hc0686021 +// `define MFCR_R1_CR9 32'hc0096021 +// `define MFCR_R1_CR10 32'hc00a6021 +// `define MFCR_R1_CR10_B3 32'hc06a6021 +// `define MFCR_R1_CR11 32'hc00b6021 +// `define MFCR_R1_CR12 32'hc00c6021 +// `define MFCR_R1_CR13 32'hc00d6021 +// `define MFCR_R1_CR14 32'hc00e6021 +// `define MFCR_R1_CR14_B1 32'hc02e6021 +// `define MFCR_R1_CR15 32'hc00f6021 +// `define MFCR_R1_CR16 32'hc0106021 +// `define MFCR_R1_CR17 32'hc0116021 +// `define MFCR_R1_CR18 32'hc0126021 +// `define MFCR_R1_CR19 32'hc0136021 +// `define MFCR_R1_CR20 32'hc0146021 +// `define MFCR_R1_CR21 32'hc0156021 +// +// `define MTCR_R1_CR0 32'hc0016420 +// `define MTCR_R4_CR0 32'hc0046420 +// `define MTCR_R7_CR0 32'hc0076420 +// `define MTCR_R7_CR0_B3 32'hc0676420 +// `define MTCR_R1_CR1 32'hc0016421 +// `define MTCR_R11_CR1 32'hc00b6421 +// `define MTCR_R11_CR1_B1 32'hc02b6421 +// `define MTCR_R11_CR1_B3 32'hc06b6421 +// `define MTCR_R5_CR1_B3 32'hc0656421 +// `define MTCR_R6_CR1_B3 32'hc0666421 +// `define MTCR_R1_CR2 32'hc0016422 +// `define MTCR_R10_CR2 32'hc00a6422 +// `define MTCR_R9_CR2_B3 32'hc0696422 +// `define MTCR_R9_CR2 32'hc0096422 +// `define MTCR_R1_CR3 32'hc0016423 +// `define MTCR_R1_CR4 32'hc0016424 +// `define MTCR_R10_CR4 32'hc00a6424 +// `define MTCR_R9_CR4_B3 32'hc0696424 +// `define MTCR_R9_CR4 32'hc0096424 +// `define MTCR_R1_CR5 32'hc0016425 +// `define MTCR_R1_CR6 32'hc0016426 +// `define MTCR_R9_CR6_B3 32'hc0696426 +// `define MTCR_R1_CR7 32'hc0016427 +// `define MTCR_R12_CR7_B3 32'hc06c6427 +// `define MTCR_R1_CR8 32'hc0016428 +// `define MTCR_R1_CR9 32'hc0016429 +// `define MTCR_R1_CR10 32'hc001642a +// `define MTCR_R11_CR10_B3 32'hc06b642a +// `define MTCR_R1_CR11 32'hc001642b +// `define MTCR_R1_CR12 32'hc001642c +// `define MTCR_R1_CR13 32'hc001642d +// `define MTCR_R10_CR14_B1 32'hc02a642e +// `define MTCR_R12_CR14_B1 32'hc02c642e +// +// `define MTCR_R1_CR17 32'hc0016431 +// `define MTCR_R13_CR19 32'hc00d6433 +// `define MTCR_R1_CR31 32'hc001643f + +`define MRET 32'h30200073 +`define SRET 32'h10200073 +`define INS_DRET 32'h7b200073 +`define INS_WFI 32'h10500073 +`define INS_ECALL 32'h00000073 + +`define LW_X7_0_X6 32'h00032383 +`define LW_X7_4_X6 32'h00432383 +`define LW_X7_8_X6 32'h00832383 +`define LW_X7_12_X6 32'h00C32383 +`define LW_X7_16_X6 32'h01032383 +`define LW_X7_24_X6 32'h01832383 +`define LW_X7_64_X6 32'h04032383 +`define LW_X7_0_X8 32'h00042383 +`define LW_X7_64_X8 32'h04042383 +`define SW_X7_0_X6 32'h00732023 +`define SW_X7_8_X6 32'h00732423 +`define SW_X7_16_X6 32'h00732823 +`define SW_X7_24_X6 32'h00732c23 + +`define LD_X7_0_X6 32'h00033383 +`define LD_X7_8_X6 32'h00833383 +`define LD_X7_16_X6 32'h01033383 +`define LD_X7_24_X6 32'h01833383 +`define SD_X7_0_X6 32'h00733023 +`define SD_X7_8_X6 32'h00733423 +`define SD_X7_16_X6 32'h00733823 +`define SD_X7_24_X6 32'h00733c23 + +`define LUI_T0_4 32'h000042b7 +`define LW_X0_0_T0 32'h0002a003 + + +//----------------------------------------------- +//define the DEBUG registers + +//------------------------------------------------- +`define DTM_BYPASS 5'h0 +`define DTM_IDCODE 5'h01 +`define DTM_DMIACC 5'h02 +`define DTM_DTMCS 5'h10 +`define DTM_DMI 5'h11 +`define DTM_BYPASS1 5'h1f +`define DTM_DTMCS_ABIT 5'd10 +`define DTM_DTMCS_VERSION 4'd1 + +`define DMI_NOP 2'b00 +`define DMI_READ 2'b01 +`define DMI_WRITE 2'b10 + +//Data0-11 0x04-0x0f Abstract data +//dmcontrol 0x10 Debug module control +//dmstatus 0x11 Debug module status +//hartinfo 0x12 Harts information +//hawindow 0x15 Hart array window +//abstractcs 0x16 Abstract command control and status +//command 0x17 Abstract command +//Abstractauto 0x18 Abstract command autoexec +//nextdm 0x1d Next debug module base address +//Progbuf0-15 0x20-0x2f Program buffer +//Dmcs2 0x32 Debug module control and status 2 +//Sbcs 0x38 System bus access control and status +//Sbaddress0 0x39 System bus access address 0 +//Sbaddress1 0x3a System bus access address 1 +//Sbdata0 0x3c System bus access data 0 +//Sbdata1 0x3d System bus access data 1 +//Sbdata2 0x3e System bus access data 2 +//Sbdata3 0x3f System bus access data 3 +//Haltsum0 0x40 Halts summary 0 +`define DM_DATA0 10'h4 +`define DM_DATA1 10'h5 +`define DM_DATA2 10'h6 +`define DM_DATA3 10'h7 +`define DM_DATA4 10'h8 +`define DM_DATA5 10'h9 +`define DM_DATA6 10'ha +`define DM_DATA7 10'hb +`define DM_DATA8 10'hc +`define DM_DATA9 10'hd +`define DM_DATA10 10'he +`define DM_DATA11 10'hf +`define DM_DMCONTROL 10'h10 +`define DM_DMSTATUS 10'h11 +`define DM_HARTINFO 10'h12 +`define DM_HAWINDOWSEL 10'h14 +`define DM_HAWINDOW 10'h15 +`define DM_ABSTRACTCS 10'h16 +`define DM_COMMAND 10'h17 +`define DM_ABSTRACTAUTO 10'h18 +`define DM_NEXTDM 10'h1d +`define DM_PROGBUF0 10'h20 +`define DM_PROGBUF1 10'h21 +`define DM_PROGBUF2 10'h22 +`define DM_PROGBUF3 10'h23 +`define DM_PROGBUF4 10'h24 +`define DM_PROGBUF5 10'h25 +`define DM_PROGBUF6 10'h26 +`define DM_PROGBUF7 10'h27 +`define DM_PROGBUF8 10'h28 +`define DM_PROGBUF9 10'h29 +`define DM_PROGBUF10 10'h2a +`define DM_PROGBUF11 10'h2b +`define DM_PROGBUF12 10'h2c +`define DM_PROGBUF13 10'h2d +`define DM_PROGBUF14 10'h2e +`define DM_PROGBUF15 10'h2f +`define DM_DMCS2 10'h32 +`define DM_SBCS 10'h38 +`define DM_SBADDRESS0 10'h39 +`define DM_SBADDRESS1 10'h3a +`define DM_SBADDRESS2 10'h3b +`define DM_SBADDRESS3 10'h37 +`define DM_SBDATA0 10'h3c +`define DM_SBDATA1 10'h3d +`define DM_SBDATA2 10'h3e +`define DM_SBDATA3 10'h3f +`define DM_HALTSUM0 10'h40 +`define DM_ITR 10'h1f +`define DM_CUSTOMCS 10'h70 +`define DM_CUSTOMCMD 10'h71 +`define DM_CUSTOMBUF0 10'h72 +`define DM_CUSTOMBUF1 10'h73 +`define DM_CUSTOMBUF2 10'h74 +`define DM_CUSTOMBUF3 10'h75 +`define DM_CUSTOMBUF4 10'h76 +`define DM_CUSTOMBUF5 10'h77 +`define DM_CUSTOMBUF6 10'h78 +`define DM_CUSTOMBUF7 10'h79 +`define DM_COMPID 10'h7f + +`define REG_CSR 2'd0 +`define REG_GPR 2'd1 +`define REG_FPR 2'd2 + +import "DPI-C" function void update_isa_trigger_csr(int tselect, int csr_num, longint csr_data); +//---------------------------------------------------- + +//jtag reset, for example: jtag_rst(100) +task jtag_rst; +input[31:0] rst_cycle; +integer i; +begin + //$display("%0t jtag reset starts", $time); + if (`jtag2_sel) begin + force `dtm_jtag2_sel = 1'b1; + force `jtag_tms_i = 1'b0; + @(negedge `jtag_tclk); + //wait for user specified cycles + for(i=0; i<82; i=i+1) begin + force `jtag_tms_i = 1'b1; + @(negedge `jtag_tclk); + end + end + + else begin + force `jtag_trst_b = 1'b1; + if (`jtag2_sel) + force `jtag_tms_i = 1'b1; + else + force `jtag_tms_i = 1'b0; + //wait until posedge tclk + @(negedge `jtag_tclk); + force `jtag_trst_b = 1'b0; + + //wait for user specified cycles + for(i=0; i>> DEBUG:Simulation Failed! @_@ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + +endtask: trigger_tb_error_finish + +//this task trigger testbench pass finish +task ext_debug::trigger_tb_pass_finish(); + integer FILE; + if (this.error_num > 0) begin + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + $display("$ Sorry, <<< CORE 0 >>> Simulation Failed! @_@ $"); + $display("$ You can have some tea and try again ^_^ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + end else begin + // exit + $display("#######################################################################"); + $display("# Congratulations, Simulation PASS! #"); + $display("#######################################################################"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST PASS"); + $finish; + end +endtask: trigger_tb_pass_finish + +//this task trigger testbench pass finish +task ext_debug::trigger_tb_bypass_finish(); + integer FILE; + if (this.error_num > 0) begin + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + $display("$ Sorry, <<< CORE 0 >>> Simulation Failed! @_@ $"); + $display("$ You can have some tea and try again ^_^ $"); + $display("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST FAIL"); + $finish; + end else begin + // exit + $display("#######################################################################"); + $display("# This case was byPASSed because of feature not support! #"); + $display("#######################################################################"); + FILE = $fopen("run_case.report","w"); + $fdisplay(FILE,"TEST PASS"); + $finish; + end +endtask: trigger_tb_bypass_finish + +task ext_debug::hart0_async_halt_req(); + bit[1:0] dmi_op; + bit[`DTM_DTMCS_ABIT-1:0] dmi_address; + int dmi_value; + bit error; + this.tb_info("hart0: async halt request starts..."); + dmi_op = `DMI_WRITE; + dmi_address = `DM_CUSTOMCMD; + dmi_value = 32'h0; //dmcontrol.haltreq=1, dmcontrol.dmactive=1 + this.rwMemorybyDMIwithCheck(dmi_op, dmi_address, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("customcmd set error!"); + end + + //check haltsum0 + for (int i=0; i= pc_start && `core0_cpu_retire_pc <= pc_end) begin + + //part1.basic gpr/read write using abstract command + this.part_start("async halt start here:"); + + //enter halt mode + //this.hart0_async_halt_req(); + force `dtu_rtu_async_halt_req=1'b1; + @(posedge `cpuclk); + release `dtu_rtu_async_halt_req; + this.hart0_resume(); + + end + else begin + @(posedge `cpuclk); + end + + + + end + +`endif + +endtask:rand_async_halt + + +task ext_debug::clear_cmderr; +bit [31:0] dmi_value; +bit error; + this.part_start("DM.abstractcs cmderr clear:"); + dmi_value = 32'd0; + this.rwMemorybyDMIwithCheck(`DMI_READ, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("dmi read error"); + end + dmi_value[10:8]=3'b111; + this.rwMemorybyDMIwithCheck(`DMI_WRITE, `DM_ABSTRACTCS, dmi_value, error); + if (error == 1'b1) begin + this.tb_fatal("dmi read error"); + end +endtask:clear_cmderr + +// task ext_debug::force_trigger_signal(bit exe, bit load, bit store, bit timing, bit select, bit action, bit [63:0] tdata2); +// `define CLK_dtu pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.forever_cpuclk +// `define ifu_addr_vld0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_addr_vld0 +// `define ifu_addr0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_exe_addr0[31:0] +// `define ifu_addr_vld1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_data_vld1 +// `define ifu_addr1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.ifu_dtu_exe_addr1[31:0] +// `define halt_info_ifu_vld pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info_vld +// `define halt_info_ifu0 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info0[`TDT_HINFO_WIDTH-1:0] +// `define halt_info_ifu1 pa_tb.x_ahb_soc.x_pa_cpu_dmi_top.x_pa_cpu_top.x_pa_core_top.x_pa_dtu_top.dtu_ifu_halt_info1[`TDT_HINFO_WIDTH-1:0] + +// bit [31:0] ifu_addr0_vld0,ifu_addr1_vld1; +// bit [21:0] halt_info_ifu; + +// assign ifu_addr0_vld0 = {32{`ifu_addr_vld0}} & `ifu_addr0; +// assign ifu_addr1_vld1 = {32{`ifu_addr_vld1}} & `ifu_addr1; +// assign halt_info_ifu[21] = 1'b1; +// assign halt_info_ifu[0] = 1'b1;//cancel +// assign halt_info_ifu[1] = 1'b1;//match +// assign halt_info_ifu[11:8] = 4'b0010;//cause +// assign halt_info_ifu[4] = 1'b0; //action +// forever begin +// if (ifu_addr0_vld0 == tdata2[31:0]) begin +// force `halt_info_ifu_vld = 1'b0; +// @(posedge `CLK_dtu); +// force `halt_info_ifu_vld = 1'b1; +// force `halt_info_ifu0 = halt_info_ifu; +// @(posedge `CLK_dtu); +// release `halt_info_ifu_vld; +// release `halt_info_ifu0; +// end +// end + + +// forever begin +// if (ifu_addr1_vld1 == tdata2[31:0]) begin +// force `halt_info_ifu_vld = 1'b0; +// @(posedge `CLK_dtu); +// force `halt_info_ifu_vld = 1'b1; +// force `halt_info_ifu1 = halt_info_ifu; +// @(posedge `CLK_dtu); +// release `halt_info_ifu_vld; +// release `halt_info_ifu0; +// end +// end +// endtask:force_trigger_signal + +`endif //JTAG_DRV + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/_TEST_MACRO_2_WIRE_JTAG.vh b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/_TEST_MACRO_2_WIRE_JTAG.vh new file mode 100644 index 0000000000000000000000000000000000000000..be8455b24301c06bad59591b86f24e0ef2eeb994 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/debug_2wire_jtag/_TEST_MACRO_2_WIRE_JTAG.vh @@ -0,0 +1,19 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +`define SELECT_2_WIRE_JTAG + + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/hello_world/hello_world_main.c b/XUANTIE-RV_opene906/smart_run/tests/cases/hello_world/hello_world_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a7cf7bd4cb19c87dcc7b2ffc0eb8b3ce8da3b5ee --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/hello_world/hello_world_main.c @@ -0,0 +1,53 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#include "stdio.h" + +int main (void) +{ + +//Section 1: Hello World! + printf("\nHello Friend!\n"); + printf("Welcome to T-HEAD World!\n"); + +//Section 2: Embeded ASM in C + int a; + int b; + int c; + a=1; + b=2; + c=0; + printf("\na is %d!\n",a); + printf("b is %d!\n",b); + printf("c is %d!\n",c); + +asm( + "mv x5,%[a]\n" + "mv x6,%[b]\n" + "label_add:" + "add %[c],x5,x6\n" + :[c]"=r"(c) + :[a]"r"(a),[b]"r"(b) + :"x5","x6" + ); + +if(c == 3) + printf("!!! PASS !!!"); +else + printf("!!! FAIL !!!"); + printf("after ASM c is changed to %d!\n",c); + + return 0; +} + diff --git a/XUANTIE-RV_opene906/smart_run/tests/cases/memcp/mem_copy_main.c b/XUANTIE-RV_opene906/smart_run/tests/cases/memcp/mem_copy_main.c new file mode 100644 index 0000000000000000000000000000000000000000..b98d466c93f54a1f25e0dd38a50c1d92a4f5d9d4 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/cases/memcp/mem_copy_main.c @@ -0,0 +1,115 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#define VCUNT_SIM + +#include "datatype.h" +#include "uart.h" +#include "stdio.h" +#include "timer.h" + +#ifdef VCUNT_SIM +//#include "vtimer.h" +extern unsigned int get_vtimer(); +#endif + +t_ck_uart_device uart0 = {0xFFFF}; + +int Loop_Num = 0; + +//void word_memcpy(int *dst, int *src, int len) +//{ +// int i = 0; +// for (;i < len; i++) +// dst[i] = src[i]; +//} +//void word_memset(int *dst, int data, int len) +//{ +// int i = 0; +// for (;i < len; i++) +// dst[i] = data; +// +//} +int main (void) +{ + unsigned int* src_addr = 0xc000; + unsigned int* des_addr = 0xe000; + int cp_size = 0x1000/4; + int i = 0; + + int current_time; + long total_time = 0; + + // initial memory + for(i=0;i +int fputc(int ch, FILE *stream) +{ + asm( + "li x13, 0x6000fff8 \n\t" + "sw %0, 0(x13) \n\t" + : :"r" (ch): "x13" ); +} + +void os_critical_enter(void) +{ +} + +void os_critical_exit(void) +{ +} + diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/intc.c b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/intc.c new file mode 100644 index 0000000000000000000000000000000000000000..8c5724d7a07309801ba088354c7adf35bc79a2e0 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/intc.c @@ -0,0 +1,32 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#include "datatype.h" +#include "uart.h" +#include "stdio.h" + +#define TCIP_BASE 0xE0000000 +#define CLIC_BASE 0xE0800000 +#define INTIE 0x400 + +//config the interrupt controller +void ck_intc_init() +{ + int *picr = TCIP_BASE; + *picr = 0x0; + + // Write ISER + int *piser = CLIC_BASE+INTIE+0x10; + *piser = 0x810000; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/minilibc_stdio.h b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/minilibc_stdio.h new file mode 100644 index 0000000000000000000000000000000000000000..d90f4d0af6765131866daa62bc83a0b33f271120 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/minilibc_stdio.h @@ -0,0 +1,74 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +/* + * minilibc stdio + * + */ + +#ifndef _MINILIBC_STDIO_H_ +#define _MINILIBC_STDIO_H__ + +#include + +#define BUFSIZE 2048 + +struct __stdio_file { + int fd; + int flags; + unsigned int bs; /* read: bytes in buffer */ + unsigned int bm; /* position in buffer */ +// unsigned int buflen; /* length of buf */ +// char *buf; + struct __stdio_file *next; /* for fflush */ + unsigned char ungetbuf; + char ungotten; + unsigned int lock; +}; + +#define ERRORINDICATOR 1 +#define EOFINDICATOR 2 +#define BUFINPUT 4 +#define BUFLINEWISE 8 +#define NOBUF 16 +#define STATICBUF 32 +#define FDPIPE 64 +#define CANREAD 128 +#define CANWRITE 256 + +#include + +/* ..scanf */ +struct arg_scanf { + void *data; + int (*getch)(void*); + int (*putch)(int,void*); +}; + +int __v_scanf(struct arg_scanf* fn, const char *format, va_list arg_ptr); + +struct arg_printf { + void *data; + int (*put)(void*,size_t,void*); +}; + +int __v_printf(struct arg_printf* fn, const char *format, va_list arg_ptr); +int __isinf(double d); +int __isnan(double d); +int __dtostr(double d,char *buf,unsigned int maxlen,unsigned int prec,unsigned int prec2); +int __lltostr(char *s, int size, unsigned long long i, int base, char UpCase); +int __ltostr(char *s, unsigned int size, unsigned long i, unsigned int base, int UpCase); + + +#endif /* _MINILIBC_STDIO_H_ */ diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/printf.h b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/printf.h new file mode 100644 index 0000000000000000000000000000000000000000..3d313b820741c2d2b9a10d84b5445c280060258b --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/printf.h @@ -0,0 +1,20 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#ifndef __PRINT_H +#define __PRINT_H +int printf(const char* fmt, ...); +static void vprintfmt(void (*putch)(int, void**), void **putdat, const char *fmt, va_list ap); +#endif + diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/timer.h b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/timer.h new file mode 100644 index 0000000000000000000000000000000000000000..42f8af5149125a4c657aa105784ac547e6abf162 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/timer.h @@ -0,0 +1,174 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +/* + * timer.h -- The interface functions and Mcros for SMART + * + */ +#include "config.h" + +#ifndef __CSKY_DEMO_TIMER_H +#define __CSKY_DEMO_TIMER_H + +#define TIMER_PERIOD 0xffffffff + +extern int Loop_Num; + +typedef struct CKS_TIMER +{ + volatile unsigned int LoadCount; /* The value to be loaded into Timer */ + volatile unsigned int CurrentValue; /* Timer Current Value */ + volatile unsigned int Control; /* Timer Control Register */ + volatile unsigned int EOI; /* Timer Clears the interrupt status */ + volatile unsigned int IntStatus; /* Timer Contains the interrupt status */ +}CKStruct_TIMER,* CKPStruct_TIMER; + +#define SMART_TIMER_BASE 0x40011000 + +///* Contains the interrupt status of all timers in the component. */ +//#define SMART_TIMER_INTSTATUS 0x10011028 +// +///* Returns all zeroes (0) and clears all active interrupts */ +//#define SMART_TIMER_EOI 0x1001102c +// +///* Contains the unmasked interrupt status of all timers in the component */ +//#define SMART_TIMER_RAW_INTSTATUS (volatile unsigned int *)0x10011030 + +/* + * Start timer. + */ +static int start_timer() +{ +#if CONFIG_SYS_SPARK + return 0; +#endif + CKPStruct_TIMER pTimer = (CKPStruct_TIMER)(SMART_TIMER_BASE); + pTimer->LoadCount = TIMER_PERIOD; + asm("":::"memory"); + pTimer->Control = 0x00000003; + return pTimer->CurrentValue; +} + + +static int start_set_timer(int a) +{ +#if CONFIG_SYS_SPARK + return 0; +#endif + CKPStruct_TIMER pTimer = (CKPStruct_TIMER)(SMART_TIMER_BASE); + pTimer->LoadCount = a; + asm("":::"memory"); + pTimer->Control = 0x00000003; + return pTimer->CurrentValue; +} + +/* + * Get timer value + */ +static int get_timer() +{ +#if CONFIG_SYS_SPARK + return 0; +#endif + CKPStruct_TIMER pTimer = (CKPStruct_TIMER)(SMART_TIMER_BASE); + return pTimer->CurrentValue; +} + + +/* + * Stop timer + */ +static int stop_timer() +{ +#if CONFIG_SYS_SPARK + return 0; +#endif + int temp; + CKPStruct_TIMER pTimer = (CKPStruct_TIMER)(SMART_TIMER_BASE); + temp = pTimer->CurrentValue; + pTimer->Control = 0x00000002; + return temp; +} + +#endif + +//Timer Interrupt Service +void CK_Timer_Interruptservice() +{ + volatile int eoi; + CKPStruct_TIMER pTimer = (CKPStruct_TIMER)(SMART_TIMER_BASE); + eoi = pTimer->EOI; + Loop_Num++; + //return Loop_Num; +} + +void Timer_Interrupt_Init() +{ +// asm("lrw r1, INTER_BEGIN\n" +// ".ifdef ck610\n" +// "mfcr r2, cr1\n" +// ".else\n" +// "mfcr r2, cr<1, 0>\n" +// ".endif\n" +// "movi r3, 10\n" +// "lsli r3, r3, 2\n" +// "addu r2, r2, r3\n" +// "st.w r1, (r2,0)\n" +// "br INTER_END\n" +// "INTER_BEGIN:\n" +// "subi sp, 16\n" +// "st.w r0, (sp)\n" +// "st.w r13, (sp, 4)\n" +// "st.w r14, (sp, 8)\n" +// "st.w r15, (sp, 12)\n" +// "subi sp, 16\n" +//// "st.w r8, (sp)\n" +//// "st.w r9, (sp, 4)\n" +//// "st.w r10, (sp, 8)\n" +//// "st.w r11, (sp, 12)\n" +//// "subi sp, 16\n" +// "st.w r4, (sp)\n" +// "st.w r5, (sp, 4)\n" +// "st.w r6, (sp, 8)\n" +// "st.w r7, (sp, 12)\n" +// "subi sp, 16\n" +// "st.w r0, (sp)\n" +// "st.w r1, (sp, 4)\n" +// "st.w r2, (sp, 8)\n" +// "st.w r3, (sp, 12)\n" +// "bsr CK_Timer_Interruptservice\n" +// "ld.w r0, (sp)\n" +// "ld.w r1, (sp, 4)\n" +// "ld.w r2, (sp, 8)\n" +// "ld.w r3, (sp, 12)\n" +// "addi sp, 16\n" +// "ld.w r4, (sp)\n" +// "ld.w r5, (sp, 4)\n" +// "ld.w r6, (sp, 8)\n" +// "ld.w r7, (sp, 12)\n" +//// "addi sp, 16\n" +//// "ld.w r8, (sp)\n" +//// "ld.w r9, (sp, 4)\n" +//// "ld.w r10, (sp, 8)\n" +//// "ld.w r11, (sp, 12)\n" +// "addi sp, 16\n" +// "ld.w r0, (sp)\n" +// "ld.w r13, (sp, 4)\n" +// "ld.w r14, (sp, 8)\n" +// "ld.w r15, (sp, 12)\n" +// "addi sp, 16\n" +// "rte\n" +// "INTER_END:"); +} + diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.c b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.c new file mode 100644 index 0000000000000000000000000000000000000000..d5787c881bc73b28793d0c1cf2722e15608fa11a --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.c @@ -0,0 +1,218 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#include "uart.h" +#include "config.h" + +/* UART register bit definitions */ +#define USR_UART_BUSY 0x01 +#define LSR_DATA_READY 0x01 +#define LSR_THR_EMPTY 0x20 +#define IER_RDA_INT_ENABLE 0x01 +#define IER_THRE_INT_ENABLE 0x02 +#define IIR_NO_ISQ_PEND 0x01 + +#define LCR_SET_DLAB 0x80 /* enable r/w DLR to set the baud rate */ +#define LCR_PARITY_ENABLE 0x08 /* parity enabled */ +#define LCR_PARITY_EVEN 0x10 /* Even parity enabled */ +#define LCR_PARITY_ODD 0xef /* Odd parity enabled */ +#define LCR_WORD_SIZE_5 0xfc /* the data length is 5 bits */ +#define LCR_WORD_SIZE_6 0x01 /* the data length is 6 bits */ +#define LCR_WORD_SIZE_7 0x02 /* the data length is 7 bits */ +#define LCR_WORD_SIZE_8 0x03 /* the data length is 8 bits */ +#define LCR_STOP_BIT1 0xfb /* 1 stop bit */ +#define LCR_STOP_BIT2 0x04 /* 1.5 stop bit */ + +#define CK_LSR_PFE 0x80 +#define CK_LSR_TEMT 0x40 +#define CK_LSR_THRE 0x40 +#define CK_LSR_BI 0x10 +#define CK_LSR_FE 0x08 +#define CK_LSR_PE 0x04 +#define CK_LSR_OE 0x02 +#define CK_LSR_DR 0x01 +#define CK_LSR_TRANS_EMPTY 0x20 + + +void ck_uart_set_baudrate(p_ck_uart_device uart_device, uint32_t baudrate) +{ /* {{{ ck_uart_set_baudrate */ + uint32_t baud_div; + uint32_t *addr = uart_device->register_map; + baud_div = (APB_FREQ/baudrate) >> 4; + uart_device->baudrate = baudrate; + *(reg8_t*)(addr+CK_UART_LCR) |= LCR_SET_DLAB; + *(reg8_t*)(addr+CK_UART_DLL) = (baud_div & 0xFF); + *(reg8_t*)(addr+CK_UART_DLH) = ((baud_div >> 8) & 0xFF); + *(reg8_t*)(addr+CK_UART_LCR) &= (~LCR_SET_DLAB); +} /* }}} */ + +void ck_uart_set_parity(p_ck_uart_device uart_device, t_ck_uart_parity parity) +{ /* {{{ ck_uart_set_parity */ + uart_device->parity = parity; + switch (parity) + { + case PARITY_NONE: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= (~LCR_PARITY_ENABLE); + break; + case PARITY_ODD: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_PARITY_ENABLE; + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= LCR_PARITY_ODD; + break; + case PARITY_EVEN: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_PARITY_ENABLE; + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_PARITY_EVEN; + break; + default: + break; + } +} /* }}} */ + +void ck_uart_set_wordsize(p_ck_uart_device uart_device, t_ck_uart_wordsize wordsize) +{ /* {{{ ck_uart_set_wordsize */ + uart_device->wordsize = wordsize; + switch (wordsize) + { + case WORDSIZE_5: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= LCR_WORD_SIZE_5; + break; + case WORDSIZE_6: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= 0xfd; + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_WORD_SIZE_6; + break; + case WORDSIZE_7: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= 0xfe; + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_WORD_SIZE_7; + break; + case WORDSIZE_8: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_WORD_SIZE_8; + break; + default: + break; + } +} /* }}} */ + +void ck_uart_set_stopbit(p_ck_uart_device uart_device, t_ck_uart_stopbit stopbit) +{ /* {{{ ck_uart_set_stopbit */ + uart_device->stopbit = stopbit; + switch(stopbit) + { + case STOPBIT_1: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) &= LCR_STOP_BIT1; + break; + case STOPBIT_2: + *(reg8_t*)(uart_device->register_map+CK_UART_LCR) |= LCR_STOP_BIT2; + break; + default: + break; + } +} /* }}} */ + + +void ck_uart_set_rxmode(p_ck_uart_device uart_device, t_ck_uart_mode rxmode) +{ /* {{{ ck_uart_set_rxmode */ + uart_device->rxmode = rxmode; + +} /* }}} */ + +void ck_uart_set_txmode(p_ck_uart_device uart_device, t_ck_uart_mode txmode) +{ /* {{{ ck_uart_set_txmode */ + uart_device->txmode = txmode; +} /* }}} */ + +/* + * @brief open a UART device, use id to select + * if more than one UART devices exist in SOC + * @param uart_device: uart device handler + * @param id: UART device ID + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_open(p_ck_uart_device uart_device, uint32_t id) +{ + if (id == 0) + { + uart_device->uart_id = 0; + uart_device->register_map = (uint32_t*)UART0_BASE_ADDR; + return 0; + } + else + { + return 1; + } +} + +/* + * @brief Initialize UART configurations from uart_cfig data structure + * @param uart_device: uart device handler + * @param uart_cfig: uart configurations collection, a structure datatype + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_init(p_ck_uart_device uart_device, p_ck_uart_cfig uart_cfig) +{ + if (uart_device->uart_id == 0xFFFF) + return 1; + ck_uart_set_baudrate(uart_device, uart_cfig->baudrate); + ck_uart_set_parity(uart_device, uart_cfig->parity); + ck_uart_set_wordsize(uart_device, uart_cfig->wordsize); + ck_uart_set_stopbit(uart_device, uart_cfig->stopbit); + ck_uart_set_rxmode(uart_device, uart_cfig->rxmode); + ck_uart_set_txmode(uart_device, uart_cfig->txmode); + return 0; +} + +/* + * @brief close UART device handler + * @param uart_device: uart device handler + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_close(p_ck_uart_device uart_device) +{ + ck_uart_set_rxmode(uart_device, DISABLE); + ck_uart_set_txmode(uart_device, DISABLE); + uart_device->uart_id = 0xFFFF; + return 0; +} + +/* + * @brief transmit a character through UART + * @param uart_device: uart device handler + * @param c: character needs to transmit + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_putc(p_ck_uart_device uart_device, uint8_t c) +{ + if (uart_device->txmode == DISABLE) + return 1; + // wait until uart transmit buffer is empty + while (!((*(reg8_t*)(uart_device->register_map+CK_UART_LSR)) & CK_LSR_TRANS_EMPTY)); + + *(reg8_t*)(uart_device->register_map+CK_UART_THR) = c; + return 0; +} + +/* + * @brief check uart device's status, busy or idle + * @param uart_device: uart device handler + * @retval 0 if uart is in idle, 1 if busy + */ +uint32_t ck_uart_status(p_ck_uart_device uart_device) +{ + uint8_t uart_lsr; + return 0; + //uart_lsr = *(reg8_t*)(uart_device->register_map+CK_UART_LSR); + if (uart_lsr & CK_LSR_TEMT) + return 0; + else + return 1; +} + diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.h b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.h new file mode 100644 index 0000000000000000000000000000000000000000..5355eee4b658047f29dadde7969e610708e61a37 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/uart.h @@ -0,0 +1,122 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#ifndef __UART_H__ +#define __UART_H__ + +#include "datatype.h" +#include "stdio.h" + +//#define FAPB 10000000L +#define BAUD 19200L +#define UART0_BASE_ADDR 0x40015000 +/* UART registers addr definition */ +#define CK_UART_RBR 0x00 /* Receive Buffer Register (32 bits, R) */ +#define CK_UART_THR 0x00 /* Transmit Holding Register (32 bits, W) */ +#define CK_UART_DLL 0x00 /* Divisor Latch(Low) (32 bits, R/W) */ +#define CK_UART_IER 0x01 /* Interrupt Enable Register (32 bits, R/W) */ +#define CK_UART_DLH 0x01 /* Divisor Latch(High) (32 bits, R/W) */ +#define CK_UART_IIR 0x02 /* Interrupt Identity Register (32 bits, R) */ +#define CK_UART_FCR 0x02 /* fifo Countrol Register (32 bits, W) */ +#define CK_UART_LCR 0x03 /* Line Control Register (32 bits, R/W) */ +#define CK_UART_MCR 0x04 /* Modem Control Register (32 bits, W) */ +#define CK_UART_LSR 0x05 /* Line Status Register (32 bits, R) */ +#define CK_UART_MSR 0x06 /* Modem Status Register (32 bits, R/W) */ +#define CK_UART_USR 0x1f /* UART Status Register (32 bits, R/W) */ + +typedef enum { + STOPBIT_1, + STOPBIT_2 +} t_ck_uart_stopbit; + +typedef enum { + PARITY_NONE, + PARITY_ODD, + PARITY_EVEN +} t_ck_uart_parity; + +typedef enum { + WORDSIZE_5, + WORDSIZE_6, + WORDSIZE_7, + WORDSIZE_8, + WORDSIZE_9 +} t_ck_uart_wordsize; + +typedef enum { + DISABLE, + ENABLE +} t_ck_uart_mode; + +typedef struct { + uint32_t baudrate; + t_ck_uart_stopbit stopbit; + t_ck_uart_parity parity; + t_ck_uart_wordsize wordsize; + t_ck_uart_mode rxmode; + t_ck_uart_mode txmode; +} t_ck_uart_cfig, *p_ck_uart_cfig; + +typedef struct { + uint32_t uart_id; + uint32_t* register_map; + uint32_t baudrate; + t_ck_uart_parity parity; + t_ck_uart_stopbit stopbit; + t_ck_uart_wordsize wordsize; + t_ck_uart_mode rxmode; + t_ck_uart_mode txmode; +} t_ck_uart_device, *p_ck_uart_device; + +/* + * @brief open a UART device, use id to select + * if more than one UART devices exist in SOC + * @param uart_device: uart device handler + * @param id: UART device ID + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_open(p_ck_uart_device uart_device, uint32_t id); + +/* + * @brief close UART device handler + * @param uart_device: uart device handler + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_close(p_ck_uart_device uart_device); + +/* + * @brief Initialize UART configurations from uart_cfig data structure + * @param uart_device: uart device handler + * @param uart_cfig: uart configurations collection, a structure datatype + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_init(p_ck_uart_device uart_device, p_ck_uart_cfig uart_cfig); + +/* + * @brief transmit a character through UART + * @param uart_device: uart device handler + * @param c: character needs to transmit + * @retval 0 if success, 1 if fail + */ +uint32_t ck_uart_putc(p_ck_uart_device uart_device, uint8_t c); + +/* + * @brief check uart device's status, busy or idle + * @param uart_device: uart device handler + * @retval 0 if uart is in idle, 1 if busy + */ +uint32_t ck_uart_status(p_ck_uart_device uart_device); + +#endif + diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.c b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.c new file mode 100644 index 0000000000000000000000000000000000000000..d136ce91ea88a845f78921970e9af2da8493f72b --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.c @@ -0,0 +1,39 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +int get_vtimer() +{ + volatile unsigned int LoadCount; + asm ("csrr %[LoadCount], time\n" + :[LoadCount]"=r"(LoadCount) + : + : + ); + //LoadCount = *TIMER_ADDR; + return LoadCount; + //int *TIMER_ADDR; + //TIMER_ADDR = 0xE0013000; + //volatile unsigned int LoadCount; + //LoadCount = *TIMER_ADDR; + //return LoadCount; +} + +void sim_end() +{ + int *END_ADDR; + END_ADDR = 0x6000FFF8; + unsigned int END_DATA; + END_DATA= 0xffff0000; + *END_ADDR = END_DATA; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.h b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.h new file mode 100644 index 0000000000000000000000000000000000000000..46bd48a59584922809d5eef3bd3a3ed622782cf9 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/clib/vtimer.h @@ -0,0 +1,22 @@ +/*Copyright 2020-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +/* + * timer.h -- The interface functions and Mcros for SMART + * + */ + +int get_vtimer(); + +void sim_end(); diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/__thead_printf.c b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/__thead_printf.c new file mode 100644 index 0000000000000000000000000000000000000000..fe4cb5d2ca7ff712f9628b18072c90aab4d97b95 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/__thead_printf.c @@ -0,0 +1,32 @@ +/*Copyright 2019-2021 T-Head Semiconductor Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#include +#include + +int __thead_vprintfsprintf(char *str, FILE *stream, const char *format, va_list arg_ptr) +{ + return 0; +} + +int __thead_vprintfprintf(FILE *stream, const char *format, va_list arg_ptr) +{ + return 0; +} + +#undef stdout +int stdout() +{ + return 0; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/printf.c b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/printf.c new file mode 100644 index 0000000000000000000000000000000000000000..b82803e4c8a0409ac2497eb73c75d54dadf1e012 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/printf.c @@ -0,0 +1,944 @@ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. These routines are thread +// safe and reentrant! +// Use this instead of the bloated standard/newlib printf cause these use +// malloc for printf (and may not be thread safe). +// +/////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include +#include +//#ifdef CONFIG_CSI_V2 +//#include +//#else +//#include +//#endif + + +// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the +// printf_config.h header file +// default: undefined +#ifdef PRINTF_INCLUDE_CONFIG_H +#include "printf_config.h" +#endif + + +// 'ntoa' conversion buffer size, this must be big enough to hold one converted +// numeric number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_NTOA_BUFFER_SIZE +#define PRINTF_NTOA_BUFFER_SIZE 32U +#endif + +// 'ftoa' conversion buffer size, this must be big enough to hold one converted +// float number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_FTOA_BUFFER_SIZE +#define PRINTF_FTOA_BUFFER_SIZE 32U +#endif + +// support for the floating point type (%f) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_SUPPORT_FLOAT +#endif + +// support for exponential floating point notation (%e/%g) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_SUPPORT_EXPONENTIAL +#endif + +// define the default floating point precision +// default: 6 digits +#ifndef PRINTF_DEFAULT_FLOAT_PRECISION +#define PRINTF_DEFAULT_FLOAT_PRECISION 6U +#endif + +// define the largest float suitable to print with %f +// default: 1e9 +#ifndef PRINTF_MAX_FLOAT +#define PRINTF_MAX_FLOAT 1e9 +#endif + +// support for the long long types (%llu or %p) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_SUPPORT_LONG_LONG +#endif + +// support for the ptrdiff_t type (%t) +// ptrdiff_t is normally defined in as long or long long type +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T +#define PRINTF_SUPPORT_PTRDIFF_T +#endif + +/////////////////////////////////////////////////////////////////////////////// + +// internal flag definitions +#define FLAGS_ZEROPAD (1U << 0U) +#define FLAGS_LEFT (1U << 1U) +#define FLAGS_PLUS (1U << 2U) +#define FLAGS_SPACE (1U << 3U) +#define FLAGS_HASH (1U << 4U) +#define FLAGS_UPPERCASE (1U << 5U) +#define FLAGS_CHAR (1U << 6U) +#define FLAGS_SHORT (1U << 7U) +#define FLAGS_LONG (1U << 8U) +#define FLAGS_LONG_LONG (1U << 9U) +#define FLAGS_PRECISION (1U << 10U) +#define FLAGS_ADAPT_EXP (1U << 11U) + + +// import float.h for DBL_MAX +#if defined(PRINTF_SUPPORT_FLOAT) +#include +#endif + +//extern int uart_putc(int ch); + +int puts(const char *s) +{ + while(*s !='\0') + { + fputc(*s, (void *)-1); + s++; + } + fputc('\n', (void *)-1); + return 0; +} + +void _putchar(char character) +{ + fputc(character, (void *)-1); +} + +int putchar(int c) +{ + _putchar(c); + return 0; +} + +// output function type +typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); + + +// wrapper (used as buffer) for output function type +typedef struct { + void (*fct)(char character, void* arg); + void* arg; +} out_fct_wrap_type; + + +// internal buffer output +static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) +{ + if (idx < maxlen) { + ((char*)buffer)[idx] = character; + } +} + + +// internal null output +static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)character; (void)buffer; (void)idx; (void)maxlen; +} + + +// internal _putchar wrapper +static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)buffer; (void)idx; (void)maxlen; + if (character) { + _putchar(character); + } +} + + +// internal output function wrapper +static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)idx; (void)maxlen; + if (character) { + // buffer is the output fct pointer + ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); + } +} + + +// internal secure strlen +// \return The length of the string (excluding the terminating 0) limited by 'maxsize' +static inline unsigned int _strnlen_s(const char* str, size_t maxsize) +{ + const char* s; + for (s = str; *s && maxsize--; ++s); + return (unsigned int)(s - str); +} + + +// internal test if char is a digit (0-9) +// \return true if char is a digit +static inline bool _is_digit(char ch) +{ + return (ch >= '0') && (ch <= '9'); +} + + +// internal ASCII string to unsigned int conversion +static unsigned int _atoi(const char** str) +{ + unsigned int i = 0U; + while (_is_digit(**str)) { + i = i * 10U + (unsigned int)(*((*str)++) - '0'); + } + return i; +} + + +// output the specified string in reverse, taking care of any zero-padding +static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) +{ + const size_t start_idx = idx; + + // pad spaces up to given width + if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { + for (size_t i = len; i < width; i++) { + out(' ', buffer, idx++, maxlen); + } + } + + // reverse string + while (len) { + out(buf[--len], buffer, idx++, maxlen); + } + + // append pad spaces up to given width + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) { + out(' ', buffer, idx++, maxlen); + } + } + + return idx; +} + + +// internal itoa format +static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) +{ + // pad leading zeros + if (!(flags & FLAGS_LEFT)) { + if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + // handle hash + if (flags & FLAGS_HASH) { + if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { + len--; + if (len && (base == 16U)) { + len--; + } + } + if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'x'; + } + else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'X'; + } + else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'b'; + } + if (len < PRINTF_NTOA_BUFFER_SIZE) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_NTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +// internal itoa for 'long' type +static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} + + +// internal itoa for 'long long' type +#if defined(PRINTF_SUPPORT_LONG_LONG) +static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} +#endif // PRINTF_SUPPORT_LONG_LONG + + +#if defined(PRINTF_SUPPORT_FLOAT) + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); +#endif + + +// internal ftoa for fixed decimal floating point +static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_FTOA_BUFFER_SIZE]; + size_t len = 0U; + double diff = 0.0; + + // powers of 10 + static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // test for special values + if (value != value) + return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); + if (value < -DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); + if (value > DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); + + // test for very large values + // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad + if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); +#else + return 0U; +#endif + } + + // test for negative + bool negative = false; + if (value < 0) { + negative = true; + value = 0 - value; + } + + // set default precision, if not set explicitly + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + // limit precision to 9, cause a prec >= 10 can lead to overflow errors + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { + buf[len++] = '0'; + prec--; + } + + int whole = (int)value; + double tmp = (value - whole) * pow10[prec]; + unsigned long frac = (unsigned long)tmp; + diff = tmp - frac; + + if (diff > 0.5) { + ++frac; + // handle rollover, e.g. case 0.99 with prec 1 is 1.0 + if (frac >= pow10[prec]) { + frac = 0; + ++whole; + } + } + else if (diff < 0.5) { + } + else if ((frac == 0U) || (frac & 1U)) { + // if halfway, round up if odd OR if last digit is 0 + ++frac; + } + + if (prec == 0U) { + diff = value - (double)whole; + if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { + // exactly 0.5 and ODD, then round up + // 1.5 -> 2, but 2.5 -> 2 + ++whole; + } + } + else { + unsigned int count = prec; + // now do fractional part, as an unsigned number + while (len < PRINTF_FTOA_BUFFER_SIZE) { + --count; + buf[len++] = (char)(48U + (frac % 10U)); + if (!(frac /= 10U)) { + break; + } + } + // add extra 0s + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { + buf[len++] = '0'; + } + if (len < PRINTF_FTOA_BUFFER_SIZE) { + // add decimal + buf[len++] = '.'; + } + } + + // do whole part, number is reversed + while (len < PRINTF_FTOA_BUFFER_SIZE) { + buf[len++] = (char)(48 + (whole % 10)); + if (!(whole /= 10)) { + break; + } + } + + // pad leading zeros + if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { + if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_FTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + // check for NaN and special values + if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { + return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); + } + + // determine the sign + const bool negative = value < 0; + if (negative) { + value = -value; + } + + // default precision + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + + // determine the decimal exponent + // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) + union { + uint64_t U; + double F; + } conv; + + conv.F = value; + int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 + conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) + // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 + int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); + // now we want to compute 10^expval but we want to be sure it won't overflow + exp2 = (int)(expval * 3.321928094887362 + 0.5); + const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; + const double z2 = z * z; + conv.U = (uint64_t)(exp2 + 1023) << 52U; + // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex + conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); + // correct for rounding errors + if (value < conv.F) { + expval--; + conv.F /= 10; + } + + // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters + unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; + + // in "%g" mode, "prec" is the number of *significant figures* not decimals + if (flags & FLAGS_ADAPT_EXP) { + // do we want to fall-back to "%f" mode? + if ((value >= 1e-4) && (value < 1e6)) { + if ((int)prec > expval) { + prec = (unsigned)((int)prec - expval - 1); + } + else { + prec = 0; + } + flags |= FLAGS_PRECISION; // make sure _ftoa respects precision + // no characters in exponent + minwidth = 0U; + expval = 0; + } + else { + // we use one sigfig for the whole part + if ((prec > 0) && (flags & FLAGS_PRECISION)) { + --prec; + } + } + } + + // will everything fit? + unsigned int fwidth = width; + if (width > minwidth) { + // we didn't fall-back so subtract the characters required for the exponent + fwidth -= minwidth; + } else { + // not enough characters, so go back to default sizing + fwidth = 0U; + } + if ((flags & FLAGS_LEFT) && minwidth) { + // if we're padding on the right, DON'T pad the floating part + fwidth = 0U; + } + + // rescale the float value + if (expval) { + value /= conv.F; + } + + // output the floating part + const size_t start_idx = idx; + idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); + + // output the exponent part + if (minwidth) { + // output the exponential symbol + out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); + // output the exponent value + idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); + // might need to right-pad spaces + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); + } + } + return idx; +} +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + + +// internal vsnprintf +static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) +{ + unsigned int flags, width, precision, n; + size_t idx = 0U; + + if (!buffer) { + // use null output function + out = _out_null; + } + + while (*format) + { + // format specifier? %[flags][width][.precision][length] + if (*format != '%') { + // no + out(*format, buffer, idx++, maxlen); + format++; + continue; + } + else { + // yes, evaluate it + format++; + } + + // evaluate flags + flags = 0U; + do { + switch (*format) { + case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; + case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; + case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; + case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; + case '#': flags |= FLAGS_HASH; format++; n = 1U; break; + default : n = 0U; break; + } + } while (n); + + // evaluate width field + width = 0U; + if (_is_digit(*format)) { + width = _atoi(&format); + } + else if (*format == '*') { + const int w = va_arg(va, int); + if (w < 0) { + flags |= FLAGS_LEFT; // reverse padding + width = (unsigned int)-w; + } + else { + width = (unsigned int)w; + } + format++; + } + + // evaluate precision field + precision = 0U; + if (*format == '.') { + flags |= FLAGS_PRECISION; + format++; + if (_is_digit(*format)) { + precision = _atoi(&format); + } + else if (*format == '*') { + const int prec = (int)va_arg(va, int); + precision = prec > 0 ? (unsigned int)prec : 0U; + format++; + } + } + + // evaluate length field + switch (*format) { + case 'l' : + flags |= FLAGS_LONG; + format++; + if (*format == 'l') { + flags |= FLAGS_LONG_LONG; + format++; + } + break; + case 'h' : + flags |= FLAGS_SHORT; + format++; + if (*format == 'h') { + flags |= FLAGS_CHAR; + format++; + } + break; +#if defined(PRINTF_SUPPORT_PTRDIFF_T) + case 't' : + flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; +#endif + case 'j' : + flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + case 'z' : + flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + default : + break; + } + + // evaluate specifier + switch (*format) { + case 'd' : + case 'i' : + case 'u' : + case 'x' : + case 'X' : + case 'o' : + case 'b' : { + // set the base + unsigned int base; + if (*format == 'x' || *format == 'X') { + base = 16U; + } + else if (*format == 'o') { + base = 8U; + } + else if (*format == 'b') { + base = 2U; + } + else { + base = 10U; + flags &= ~FLAGS_HASH; // no hash for dec format + } + // uppercase + if (*format == 'X') { + flags |= FLAGS_UPPERCASE; + } + + // no plus or space flag for u, x, X, o, b + if ((*format != 'i') && (*format != 'd')) { + flags &= ~(FLAGS_PLUS | FLAGS_SPACE); + } + + // ignore '0' flag when precision is given + if (flags & FLAGS_PRECISION) { + flags &= ~FLAGS_ZEROPAD; + } + + // convert the integer + if ((*format == 'i') || (*format == 'd')) { + // signed + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + const long long value = va_arg(va, long long); + idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + const long value = va_arg(va, long); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + else { + const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + } + else { + // unsigned + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); + } + else { + const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); + idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); + } + } + format++; + break; + } +#if defined(PRINTF_SUPPORT_FLOAT) + case 'f' : + case 'F' : + if (*format == 'F') flags |= FLAGS_UPPERCASE; + idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + case 'e': + case 'E': + case 'g': + case 'G': + if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; + if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; + idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + case 'c' : { + unsigned int l = 1U; + // pre padding + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // char output + out((char)va_arg(va, int), buffer, idx++, maxlen); + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 's' : { + const char* p = va_arg(va, char*); + unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); + // pre padding + if (flags & FLAGS_PRECISION) { + l = (l < precision ? l : precision); + } + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // string output + while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { + out(*(p++), buffer, idx++, maxlen); + } + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 'p' : { + width = sizeof(void*) * 2U; + flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; +#if defined(PRINTF_SUPPORT_LONG_LONG) + const bool is_ll = sizeof(uintptr_t) == sizeof(long long); + if (is_ll) { + idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); + } + else { +#endif + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); +#if defined(PRINTF_SUPPORT_LONG_LONG) + } +#endif + format++; + break; + } + + case '%' : + out('%', buffer, idx++, maxlen); + format++; + break; + + default : + out(*format, buffer, idx++, maxlen); + format++; + break; + } + } + + // termination + out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); + + // return written chars without terminating \0 + return (int)idx; +} + + +/////////////////////////////////////////////////////////////////////////////// + +int printf(const char* format, ...) +{ + va_list va; + va_start(va, format); + char buffer[1]; + const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int sprintf(char* buffer, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int snprintf(char* buffer, size_t count, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); + va_end(va); + return ret; +} + + +int vprintf(const char* format, va_list va) +{ + char buffer[1]; + return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); +} + + +int vsnprintf(char* buffer, size_t count, const char* format, va_list va) +{ + return _vsnprintf(_out_buffer, buffer, count, format, va); +} + + +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) +{ + va_list va; + va_start(va, format); + const out_fct_wrap_type out_fct_wrap = { out, arg }; + const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); + va_end(va); + return ret; +} diff --git a/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/vasprintf.c b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/vasprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..38ee78744ce8481c6663738796f8499484ebc375 --- /dev/null +++ b/XUANTIE-RV_opene906/smart_run/tests/lib/newlib_wrap/vasprintf.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include + + +#define CHUNKSIZE (256) + +int vasprintf(char **ret, const char *fmt, va_list ap) +{ + size_t chunks; + size_t buflen; + char * buf; + int len; + + chunks = ((strlen(fmt) + 1) / CHUNKSIZE) + 1; + buflen = chunks * CHUNKSIZE; + + *ret = NULL; + for (;;) { + buf = malloc(buflen); + if (buf == NULL) { + return -ENOMEM; + } + len = vsnprintf(buf, buflen, fmt, ap); + + if (len >= 0 && (size_t)len < buflen - 1) { + break; + } + free(buf); + buflen = (++chunks) * CHUNKSIZE; + + /* + * len >= 0 is required for vsnprintf implementations that + * return -1 for insufficient buffer + */ + + if (len >= 0 && buflen <= (size_t)len) { + buflen = len + 1; + } + } + + if (len > 0 && buf != NULL) { + // strip the string + *ret = strdup(buf); + if (*ret != NULL) + free(buf); + else + *ret = buf; + } + + return len; +} + +int asprintf(char **buf, const char *fmt, ...) +{ + va_list args; + int i; + + va_start(args, fmt); + i = vasprintf(buf, fmt, args); + va_end(args); + return i; +} diff --git a/dan-rodrigues_icestation-32/README.md b/dan-rodrigues_icestation-32/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fcbdb1e5a7ae8425834002d239959f5e072bfee7 --- /dev/null +++ b/dan-rodrigues_icestation-32/README.md @@ -0,0 +1,189 @@ +# icestation-32 + +This is a compact open-source FPGA game console targetting the Lattice iCE40 UltraPlus series. It's being developed using the open-source yosys and nextpnr tools and can be run on both the [iCEBreaker](https://github.com/icebreaker-fpga/icebreaker)** and [ULX3S](https://github.com/emard/ulx3s)* boards. + +As a retro-inspired console, it does not use framebuffers, rasterizers, shaders etc. It uses character maps, sprites and raster effects to implement various effects. This allows it to render 480p scenes from 64KByte. + +It is feature-complete and confirmed working on both the iCEBreaker and ULX3S targets. Remaining work is mainly cleanup, adding more supported gamepads, more demos and possibly other optional non-core features. + +*: Only the ECP5-45F and 85F have the 128kbyte of block RAM required. It's been confirmed working on boards with Winbond flash but thought to work on others too. Potentially boards with a 25F can be supported by moving the CPU RAM to external memory. + +**: iCEBreaker requires the additional 12bpp HDMI PMOD for video output. On the ULX3S, the onboard GPDI port is used for video output. + +## Video capture from ULX3S (DVI video) + +![HDMI capture from ULX3S](photos/ulx3s_hdmi_capture.jpg) +Platformer game hosted [here](https://github.com/dan-rodrigues/super-miyamoto-sprint). + +## Demo running on iCEBreaker + +![Demo photo](photos/main.jpg) +Demo with placeholder assets just for illustration. This along with other similarly copyrighted assets are not published here. + +## Features + +* RISC-V CPU (configurable with VexRiscV or PicoRV32) +* Custom VDP for smooth-scrolling layers and sprites +* Custom "copper" coprocessor integrated into VDP to perform raster effects +* [Custom multichannel ADPCM decoder / mixer](https://github.com/dan-rodrigues/ics-adpcm) (44.1KHz, 16bit stereo) +* Configurable video modes of 640x480@60hz or 848x480@60hz +* 4bpp graphics assembled from 8x8 tiles +* ARGB16 colors arranged into 16 palettes of 16 colors each +* Optional alpha blending using 4bit alpha intensity** +* 3x or 4x scrolling layers up to 1024x512 pixels each* +* 1x 1024x1024 pixel affine-transformable layer* +* 256x sprites of up to 16x16 pixels each +* 1060+ sprite pixels per line depending on clock and video mode +* 64kbyte of CPU RAM (2x iCE40 SPRAM) +* 64kbyte VDP RAM (2x iCE40 SPRAM) +* (S)NES-compatible pad interface*** + +The system doesn't require any RAM beyond what is available in the iCE40 UP5K. + +*: Only one of these layer types can be enabled at any given time but they can be toggled multiple times in a frame using raster-timed updates. The 4x layer implementation is still included in this repo but was disabled due to VRAM usage constraints. + +**: Visual artefacts can been seen if more than one alpha-enabled layer intersects with another i.e. using overlapping sprites. + +***: PCB push buttons are used by default. although an original SNES gamepad can be used. + +## Usage + +### Prerequisites + +* [yosys](https://github.com/YosysHQ/yosys) +* [nextpnr](https://github.com/YosysHQ/nextpnr) (-ice40 for iCEBreaker, -ecp5 for ULX3S) +* [icetools](https://github.com/YosysHQ/icestorm) (if building for iCEBreaker) +* [GNU RISC-V toolchain](https://github.com/riscv/riscv-gnu-toolchain) (newlib) +* [fujprog](https://github.com/kost/fujprog) (if flashing to ULX3S) + +The `CROSS` variable in `software/common/cross.mk` must be set according to the name of your RISC-V installation. + +While the RISC-V toolchain can be built from source, the PicoRV32 repo [includes a Makefile](https://github.com/cliffordwolf/picorv32#building-a-pure-rv32i-toolchain) with convenient build-and-install targets. This project only uses the `RV32I` ISA. Those with case-insensitive file systems will likely have issues building the toolchain from source. If so, binaries of the toolchain for various platforms are available [here](https://github.com/xpack-dev-tools/riscv-none-embed-gcc-xpack/releases/tag/v8.3.0-1.1). + +The open-tool-forge [fpga-toolchain](https://github.com/open-tool-forge/fpga-toolchain) project also provides nightly builds of most of these tools. + +### Build and program bitstream + +#### iCEBreaker + +``` +cd hardware +make icebreaker_prog +``` + +#### ULX3S + +``` +cd hardware +make ulx3s_prog +``` + +### Programming software + +Demo software is included under `/software` and can be programmed separately. For example, to build and program the `sprites` demo: + +### iCEBreaker + +``` +cd software/sprites/ +make icebreaker_prog +``` + +### ULX3S + +``` +cd software/sprites/ +make ulx3s_prog +``` + +Note that fujprog can be slow to flash larger files. Programming over WiFi [using the ESP32](https://github.com/emard/esp32ecp5) can be done as a faster alternative. + +### Programming documentation + +More detailed hardware documentation for the platform can be found in [doc/platform.md](doc/platform.md). + +### Running simulator (Verilator or CXXRTL, plus SDL2) + +A simulator using SDL2 and its documentation is included in the [/simulator](simulator/) directory. + +Demo software and simulator screenshots are included in the [/software](software/) directory. + +## Configuration + +### CPU + +One of two RISC-V implementations can be selected. The implementation is chosen using the boolean `USE_VEXRISCV` parameter in the `ics32` module. + +* PicoRV32: Enabled when `USE_VEXRISCV=0`. This was the original choice and the rest of the system was designed around its shared bus interface. While it is not as compact as the Vex, it is much faster to run in simulators as it is fully synchronous. +* VexRiscV (default): Enabled when `USE_VEXRISCV=1`. This was a later addition. A wrapper module is used to bridge between the Vex split IBus/DBus and the Pico-compatible shared bus. It is the more compact CPU which is especially important considering the size of the UP5K target. + +### Video modes + +One of two video modes can be selected and only when the project is built. The video modes can't be toggled in software. The `VIDEO_MODE` variable in [/hardware/Makefile](hardware/Makefile) selects which video mode to use. This Makefile variable in turn determines the value of the `ENABLE_WIDESCREEN` parameter in the `ics32` module. + +* 640x480@60hz: 25.175MHz VDP/CPU clock +* 848x480@60hz: 33.75MHz VDP clock, 16.88MHz CPU clock + +### CPU and VDP clock domains + +The 848x480 video mode has two clock domains because the UP5K cannot run the CPU at 33.75MHz while also meeting timing. For the `icebreaker` target, the dual clock domain setup is automatically enabled when `ENABLE_WIDESCREEN` is set. This can otherwise be manually configured using the `ENABLE_FAST_CPU` parameter. + +If the `ENABLE_FAST_CPU` parameter is set, there is only one clock domain with the CPU running at the VDP clock. Otherwise, the CPU runs at half the VDP clock as shown above. + +The ULX3S can run the CPU at the video clock (and beyond) but it defaults to the same configuration as the iCEBreaker for consistency. This also means software running on one platform will behave identically on the other. + +## Audio + +### iCEBreaker + +The `GAMEPAD_PMOD` parameter enables audio output using the 1BitSquared gamepad / audio PMOD. A stereo PDM DAC is used with this PMOD. This is the only option available for audio on the iCEBreaker. + +### ULX3S + +Audio is output through the headphone jack in both analog / digital form: + +* Analog output direct to headphones (noisy) +* Digital SPDIF using a 3.5mm -> RCA cable. The "composite video" cable can be plugged into the coax-in of an SPDIF receiver. + +## Controls + +The assumed controller layout matches an original SNES gamepad. + +By default, the controller is implemented using push buttons on the PCBs. Both the ULX3S and iCEBreaker buttons (on break out board) can be used but inputs are limited. + +### iCEBreaker + +The `GAMEPAD_PMOD` parameter in the [top level module](/hardware/icebreaker/ics32_top_icebreaker.v) can be set to use an original SNES gamepad rather than the 3 buttons on the breakout board. + +### ULX3S + +The `GAMEPAD_SOURCE` parameter in the [top level module](/hardware/ulx3s/ics32_top_ulx3s.v) sets the controller input. This string must be set to one of three values: + +* `PCB`: PCB buttons (default, limited inputs) +* `USB`: USB gamepad (if the gamepad to be used has a corresponding HID report decoder) +* `BLUETOOTH`: Bluetooth gamepad + +For the `USB` option, HID report descriptors aren't parsed so a fixed layout is assumed. More gamepads can be added over time since the only addition needed is a HID report decoder. The `USB_GAMEPAD` parameter selects which decoder to use and [this file](/hardware/usb/gamepads/usb_gamepad_reader.v) shows which gamepads are supported. + +For the `BLUETOOTH` option, an ESP32 program must be flashed first. A [separate repo](https://github.com/dan-rodrigues/ulx3s-bluetooth-gamepad) has the instructions on setting this up. The `BLUETOOTH` option will not do anything useful unless the ESP32 program in the linked repo is flashed first. If there's issues getting a Bluetooth gamepad to connect, pressing button 0 will reset the ESP32 (without resetting the rest of the system). This usually fixes any connection problems. + +The `GAMEPAD_LED` parameter can also be set to show some some of the current button inputs. There are only 8 LEDs so not all can be seen at once. The CPU controlled LED state is otherwise shown. + +## Resource usage + +The logic resources used can vary a lot based on which commit was used to build yosys. This can break UP5K builds if the LC usage is too high. + +yosys commit [c75d8c74](https://github.com/YosysHQ/yosys/commit/c75d8c74) produces this result which fits and routes reasonably quick: + +``` +Info: Device utilisation: +Info: ICESTORM_LC: 4790/ 5280 90% +``` + +## TODO + +* A better README file! +* Many bits of cleanup and optimization +* Support for more USB gamepads +* Confirm ULX3S boards with ISSI flash work as expected + diff --git a/dan-rodrigues_icestation-32/doc/platform.md b/dan-rodrigues_icestation-32/doc/platform.md new file mode 100644 index 0000000000000000000000000000000000000000..085d859385ef3b0291f990b59b1381a2ce1cf630 --- /dev/null +++ b/dan-rodrigues_icestation-32/doc/platform.md @@ -0,0 +1,838 @@ +Icestation-32 platform documentation +==================================== + +Icestation-32 is a compact open-source game console targeting small FPGAs. Because of this, facilities like RAM are quite minimalistic. It does however make good use of the flexibility of FPGAs to implement a custom VDP and audio processor. This allows for a surprising number of effects. + +The goal of this document is to describe the SoC in enough detail to develop software without necessarily having to consult the verilog implementation. However, in case of doubt, the verilog source is the actual specification. Although a few examples are given in C, it has been tried to stay as language-agnostic as possible to allow for implementing software in other languages as well. + +CPU +--- + +The main CPU is a single-core 32-bit RISC-V CPU implementing the `RV32I` ISA. This architecture has 31 general purpose registers. It has addition/subtraction, basic bit manipulation and control flow instructions, as well as memory stores and loads of 8/16/32 bits width. It most notably does *not* have multiplication or division instructions (but see [DSP](#dsp)). + +Details about the CPU instruction set and bit patterns can be found in the [RISC-V spec](https://riscv.org//wp-content/uploads/2017/05/riscv-spec-v2.2.pdf), chapter 2. The privileged spec is not implemented. + +Address space layout +-------------------- + +The Icestation-32 has a 32-bit flat address space. It is laid out with the RAM at the start, followed by memory-mapped peripherals and flash ROM. + +``` + ┌─────────────┐ 0xffff_ffff + │ │ + │ │ + │ reserved │ + │ │ + │ │ + ├─────────────┤ 0x0200_0000 + │ │ + │ │ + │ flash │ + │ │ + │ │ + ├─────────────┤ 0x0100_0000 + │ │ + │ │ + │ peripherals │ + │ │ + │ │ + ├─────────────┤ 0x0001_0000 + │ RAM │ + └─────────────┘ 0x0000_0000 +``` + +In detail: + +| from | to | description | +|:------------- |:------------- |:------------------------------------ | +| `0x0000_0000` | `0x0000_ffff` | [CPU RAM](#cpu-ram) | +| `0x0001_0000` | `0x0001_ffff` | [VDP](#vdp) | +| `0x0002_0000` | `0x0002_ffff` | [System status](#system-status) | +| `0x0003_0000` | `0x0003_ffff` | [DSP](#dsp) | +| `0x0004_0000` | `0x0004_ffff` | [Gamepad](#gamepad) | +| `0x0005_0000` | `0x0005_ffff` | [VDP "copper" RAM](#vdp-copper-ram) | +| `0x0006_0000` | `0x0006_ffff` | [Bootloader ROM](#bootloader-rom) | +| `0x0007_0000` | `0x0007_ffff` | [Flash control](#flash-control) | +| `0x0008_0000` | `0x0008_ffff` | [Audio](#audio) | +| `0x0100_0000` | `0x01ff_ffff` | [CPU flash access](#flash-access) | + +The different peripherals are described in the following sections. Note that these are the assigned memory ranges in the address decoder, and often only a small part of the address space is used. + +CPU RAM +======= + +This is the main RAM of the RISC-V CPU. There is 64 kB of general purpose RAM available, implemented as BRAMs on the FPGA fabric (icestation-32 doesn't use external SDRAM chips). This RAM stores both code and data. At boot, the boot ROM fills this memory with its initial state from flash and jumps to address `0x0000_0000`. + +VDP +=== + +Icestation-32 has a custom VDP with support for smooth-scrolling layers and sprites. + +The display resolution can be `848×480` or `640×480`. The VDP can be considered to have a virtual display size of `1024×512`, of which the top-left portion is visible on the display output: + +``` + 0 848 1024 + 0 ┌──────────────────┬──────┐ + │ ┊ │ + │ visible ┊ │ + │ screen ┊ │ + │ area ┊ │ + │ ┊ │ +480 ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┘ │ + │ │ + │ off-screen │ +512 └─────────────────────────┘ +``` + +The screen rendering consists of two main components: one or multiple layers of "scroll map", and sprites. A scroll map layer consists of fixed-size indexed tiles, and as the name implies, can be scrolled. Sprites are small graphics that can be overlaid over the map at any position. Instead of scroll map layers, an affine layer can be enabled, which is a 256-color tiled image that can be "distorted" with an affine transformation matrix. + +Registers +---------- + +The memory-mapped VDP registers are 16-bit, and laid out as follows: + +``` +reg r/w bits name description +------ --- ------- ------------------------ ---------------------------------------- +0x0000 w [15:0] SPRITE_BLOCK_ADDRESS Sprite metadata address register +0x0000 r [15:0] CURRENT_RASTER_X Current display-out X position +0x0002 w [15:0] SPRITE_DATA Sprite metadata write register +0x0004 w [15:0] PALETTE_ADDRESS Palette address register +0x0004 r [15:0] CURRENT_RASTER_Y Current display-out Y position +0x0006 w [15:0] PALETTE_WRITE_DATA Palette data write register +0x0008 w [15:0] VRAM_ADDRESS VRAM address register +0x000a w [15:0] VRAM_WRITE_DATA VRAM data write register +0x000c w [7:0] ADDRESS_INCREMENT Address increment after every VRAM write +0x000e w [15:0] SPRITE_TILE_BASE Tile offset for sprite layer +0x0010 w [0] ENABLE_COPPER Enable "copper" coprocessor +0x0012 w [15:0] SCROLL_TILE_ADDRESS_BASE Tile offset for scroll layers 0..3 +0x0014 w [15:0] SCROLL_MAP_ADDRESS_BASE Map offset for scroll layers 0..3 +0x0016 w [5:0] LAYER_ENABLE Enable layers display +0x0018 w [4:0] ALPHA_OVER_ENABLE Enable layer alpha blending +0x001a w [3:0] SCROLL_WIDE_MAP_ENABLE Wide-map mode for scroll layers 0..3 +0x0020 w [15:0] HSCROLL_0 Horizontal offset for scroll layer 0 +0x0020 w [15:0] AFFINE_TRANSLATE_X Affine layer x-translation +0x0022 w [15:0] HSCROLL_1 Horizontal offset for scroll layer 1 +0x0022 w [15:0] MATRIX_A Affine matrix A +0x0024 w [15:0] HSCROLL_2 Horizontal offset for scroll layer 2 +0x0024 w [15:0] MATRIX_B Affine matrix B +0x0026 w [15:0] HSCROLL_3 Horizontal offset for scroll layer 3 +0x0026 w [15:0] MATRIX_C Affine matrix C +0x0028 w [15:0] VSCROLL_0 Vertical offset for scroll layer 0 +0x0028 w [15:0] MATRIX_D Affine matrix D +0x002a w [15:0] VSCROLL_1 Vertical offset for scroll layer 1 +0x002a w [15:0] AFFINE_TRANSLATE_Y Affine layer y-translation +0x002c w [15:0] VSCROLL_2 Vertical offset for scroll layer 2 +0x002c w [15:0] AFFINE_PRETRANSLATE_X Affine layer x-pretranslation +0x002e w [15:0] VSCROLL_3 Vertical offset for scroll layer 3 +0x002e w [15:0] AFFINE_PRETRANSLATE_Y Affine layer y-pretranslation +``` + +The `HSCROLL_x` and `VSCROLL_x` registers are aliases for the affine transformation registers. How they are used depends on whether the affine layer is enabled. *Either* SCROLLx layers or the affine layer should be enabled, not both at the same time. + +The only values that can be read from the VDP are `CURRENT_RASTER_X` and `CURRENT_RASTER_Y`, which are the current raster x and y coordinate that are being output, respectively. The rest is write-only from the point of view of the CPU. + +VDP memory layout +----------------- + +The VDP has its own 64 kB RAM. This VDP RAM is not directly accessible from the CPU, but it can be written indirectly through a pair of registers (address, data). It is not possible to read from VDP memory. + +VDP memory is always addressed in 16-bit words, and all addresses are specified as such. So it's often convenient to regard it as 32768 (0x8000) words of memory. + +As all memory offsets are configurable (the only exception is the affine layer), the VDP memory can be laid out arbitrarily. The following contents are stored in VDP memory: + +- Tile graphics for scroll layers (configured through register `SCROLL_TILE_ADDRESS_BASE`). + +- Tile graphics for sprites (configured through register `SPRITE_TILE_BASE`). + +- Maps for the scroll layers. These select the indices for the tiles to show from the tile graphics (configured through register `SCROLL_MAP_ADDRESS_BASE`). + +- Graphics and tile map for the affine layer (if enabled, always at address `0`). + +To write to VDP memory, first write the index of the memory location to change to register `VRAM_ADDRESS`, then write the color to replace it with `VRAM_WRITE_DATA`. The auto-increment of the address after writes can be configured through `ADDRESS_INCREMENT`. Usually this register is set to 1, to quickly write adjacent VDP RAM memory locations. + +Palette +------- + +The VDP has a palette of 256 colors, where each color is 16-bit A4R4G4B4. The palette is, like the main VDP memory, written through a (address, data) pair of registers, but it is separate from the main memory. The palette represents all the colors that can be visible on the screen at the same time (aside from through copper effects). + +For all uses except the affine payer the palette is considered as a matrix of 16 palettes of 16 entries. The eventual color for each layer is determined in the following way: the 4 most significant bits of the palette index come from the scroll map or sprite metadata, the 4 least significant bits come from the tile or sprite graphics itself. This 8-bit value is then looked up in the global palette to get a final color. The value 0 (from the sprite or scroll tile graphics) is treated specially: it means to show the background through. As palette index 0 is special within the 16-entry palettes it is not possible to use palette indices `0x10`, `0x20` to `0xf0`, except through the affine layer which is a true 256-color image. + +To write to the palette, first write the index of the color to change to register `PALETTE_ADDRESS`, then write the color to replace it with `PALETTE_DATA`. The address auto-increments, so successive colors can be written simply by writing to `PALETTE_DATA` multiple times. + +Layers +------ + +The main concept of rendering in the VDP is so-called layers. Layers are, as their name implies, overlaid over each other. In the absence of alpha blending, the lowest layer number that has a certain pixel enabled (that has a non-zero value for it) will take precedence, or the background color (palette index 0) if there is no such layer. Each layer has its own horizontal and vertical scroll offset. There are 3 scroll layers. The 4th layer still has registers reserved for it but was disabled due to VRAM usage constraints. + +``` + ┌──────┐ + │ 0│ + │ │──┐ + │ │ 1│ + │ │ │──┐ + └──────┘ │ 2│ + │ │ │ + └──────┘ │ + │ │ + └──────┘ + + layers 0..2 +``` + +Sprites are sometimes considered a layer, but might be best considered to be *between* scroll layers, not a layer in themselves. They have a priority as part of their individual metadata to determine this position: priority 0 sprites are behind layer 2, the hindmost layer, whereas priority 3 sprites are on top of layer 0. See the `aquarium` demo for an example. + +Individual layers can be shown and hidden through the `LAYER_ENABLE` register: + +``` + LAYER_ENABLE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │AF │SPR│S3 │S2 │S1 │S0 │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +S0,S1,S2,S3: Enable scroll map layer 0,1,2,3 display, respectively. +SPR: Enable sprite display. +AF: Enable affine layer display. + +A value of 1 enables (shows) the respective layer, a value +of 0 disables (hides) it. +``` + +Alpha blending +-------------- + +The VDP supports 4-bit alpha blending. In the case of alpha blending the final color for a layer is alpha-blended over the final color of the layer below it, or the background. Alpha-blending more than two layers will result in visual artifacts. + +Post-multiplied alpha is used everywhere. This means that the color red green and blue component are multiplied with alpha color value before blending. + +Alpha blending can be configured per layer through the `ALPHA_OVER_ENABLE` register. + +``` + ALPHA_OVER_ENABLE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │SPR│S3 │S2 │S1 │S0 │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +S0,S1,S2,S3: Enable scroll map layer 0,1,2,3 alpha-over. +SPR: Enable alpha-over for sprites. + +A value of 1 enables alpha-over for the respective layer, a value +of 0 disables it. +``` + +Tiles +----- + +All tiles are sized 8×8. Tiles are stored in row-major order, with 4 bits per pixel. Each row of a tile is represented by two 16-bit integers, given colors A..H from left to right this becomes `{0xEFGH, 0xABCD}`: +``` + col + A B C D E F G H +row ┌───┬───┬───┬───┬───┬───┬───┬───┐ + 0 │ 1 │ 0 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 1 │ 3 │ 2 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 2 │ 5 │ 4 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 3 │ 7 │ 6 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 4 │ 9 │ 8 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 5 │ 11 │ 10 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 6 │ 13 │ 12 │ + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 7 │ 15 │ 14 │ + └───┴───┴───┴───┴───┴───┴───┴───┘ +``` +This means that a tile spans 16 words, or 32 bytes of memory. The tile graphics are laid out in memory consecutively with increasing tile ids, starting at 0. + +Let's say we want to make this little critter. Let's first draw him on a grid, then map the different shades to hexadecimal nibbles, and group these into 16-bit words: +``` + + col + A B C D E F G H +row ┌───┬───┬───┬───┬───┬───┬───┬───┐ _ 0 + 0 │ _ │ █ │ █ │ _ │ _ │ █ │ █ │ _ │ ░ 1 0x0440 0x0440 + ├───┼───┼───┼───┼───┼───┼───┼───┤ ▒ 2 + 1 │ _ │ _ │ █ │ _ │ _ │ █ │ _ │ _ │ ▓ 3 0x0040 0x0400 + ├───┼───┼───┼───┼───┼───┼───┼───┤ █ 4 + 2 │ _ │ _ │ ▓ │ ▓ │ ▓ │ ▓ │ _ │ _ │ 0x0033 0x3300 + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 3 │ _ │ ▓ │ ▒ │ ▒ │ ▒ │ ▒ │ ▓ │ _ │ 0x0322 0x2230 + ├───┼───┼───┼───┼───┼───┼───┼───┤ → + 4 │ _ │ ▓ │ _ │ ▒ │ ▒ │ _ │ ▓ │ _ │ 0x0302 0x2030 + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 5 │ ░ │ ░ │ ░ │ ░ │ ░ │ ░ │ ░ │ ░ │ 0x1111 0x1111 + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 6 │ ░ │ ░ │ ░ │ _ │ _ │ ░ │ ░ │ ░ │ 0x1110 0x0111 + ├───┼───┼───┼───┼───┼───┼───┼───┤ + 7 │ _ │ _ │ ▓ │ ▓ │ ▓ │ ▓ │ _ │ _ │ 0x0033 0x3300 + └───┴───┴───┴───┴───┴───┴───┴───┘ +``` + +Then swap the values horizontally, and concatenate them into an array: + +```c +const uint16_t tile[] = { + 0x0440, 0x0440, + 0x0400, 0x0040, + 0x3300, 0x0033, + 0x2230, 0x0322, + 0x2030, 0x0302, + 0x1111, 0x1111, + 0x0111, 0x1110, + 0x3300, 0x0033, +}; +``` + +Of course, this is only an example, doing this manually is not very convenient! See the function `upload_font_remapped_main` in `software/common/font.c`, or the `aquarium` demo for examples of building tile graphics on the fly from C. Alternatively the graphics can be converted from another format with some external tool like `utilities/gfx_convert`. SNES graphics editing tools may also be useful, as the idea is similar, though the exact storage format is not. + +The tiles for the scroll map and for sprites have the same format. This means that it's possible for these to share the same graphics, which can be convenient as well as save memory. + +Scroll map +---------- + +The scroll map is a grid of tiles of 8×8 pixels. There can be up to 512 distinct tiles, and each layer can have its own tile set. + +Tiles can be flipped (mirrored) horizontally as well as vertically using per-tile flags. They can also specify their own palette to use out of 16 available. + +The VDP scroll map memory layout consists of 64×64 tiles laid out in row-major order, with a 16-bit word per tile: + +``` + x + 0 .................... 63 + ┌────┬────┬─┈┈┈┈─┬────┬────┐ + 0 │ 0│ 1│ .... │62 │63 │ + . ├────┼────┼──┈┈──┼────┼────┤ + . │ 64│ 65│ .... │126 │127 │ + . ├────┼────┼──┈┈──┼────┼────┤ + . ┆ ┆ ┆ ┆ ┆ ┆ +y . ┆ ┆ ┆ .... ┆ ┆ ┆ + . ┆ ┆ ┆ ┆ ┆ ┆ + . ├────┼────┼──┈┈──┼────┼────┤ + . │ 64│ 65│ .... │126 │127 │ + . ├────┼────┼──┈┈──┼────┼────┤ + 63 │4032│4033│ .... │4094│4095│ + └────┴────┴─┈┈┈┈─┴────┴────┘ +``` + +This word for every tile specifies the tile id `TILEID`, x-flip bit `XF`, y-flip bit `YF`, and palette `PAL`: + +``` + scroll_map_tile + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ PAL │ - │YF │XF │ TILEID │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +TILEID: base tile id +XF: flip tile in x direction +YF: flip tile in y direction +PAL: the palette to use for this tile (upper 4 bits of palette index) +``` + +Layers can be of two kinds: "wide map" layers which are 128 by 64 tiles (1024×512 pixels) and which cover the entire screen area, and normal layers which are are 64 by 64 tiles (512×512 pixels). This mode can be set on a per layer basis in the `SCROLL_WIDE_MAP_ENABLE` register. + + +``` + SCROLL_WIDE_MAP_ENABLE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ │ │ │ │ │ │ │ │ │ │ │ │W3 │W2 │W1 │W0 │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +W3,W2,W1,W0: "wide map" mode for respective scroll layer + 0: 64×64 tiles (512×512 pixels) mode + 1: 128×64 tiles (1024×512 pixels) mode + +``` + +Wide layers can be considered as normal layers laid out side to side horizontally, consecutive in memory. So tile offsets will be like this: + +``` + wide layer + + x_tile + 0 63 64 127 + 0 ┌──────────┬──────────┐ + │0 │4096 │ + │ │ │ + │ │ │ + y │ .. │ .. │ +tile│ │ │ + │ │ │ + │ 4095│ 8191│ + 63 └──────────┴──────────┘ + +``` + +Layers can be scrolled with pixel granularity through the `HSCROLL_X` and `VSCROLL_X` registers. These registers configure the starting coordinate visible at the top-left of the display. The layers wrap around at the edges, both horizontally and vertically. This means that when scrolling, when the edge of the layer comes into view, the other side of the layer will be visible: + +``` +┌──────┐ ┌┈┈┈┬┈┈┈┐ +│A B│ ┆ │ ┆ +│ │ scroll ╎ D│C ┆ +│ │ → → ├───┼───┤ +│ │ offset ┆ B│A ┆ +│C D│ ┆ │ ┆ +└──────┘ └┈┈┈┴┈┈┈┘ + + layer visible screen area +``` + +Note that there will always be part of a layer off-screen vertically. Increasing the scroll coordinate in any direction will keep scrolling indefinitely, as the layer dimension (as well as the range of the scroll register) is a power of two, and scrolling wraps around. + +Layer maps and layer tiles graphics must be aligned in memory to an address that is a multiple of 4096 and 2048 respectively. These offsets are configured through the `SCROLL_TILE_ADDRESS_BASE` and `SCROLL_MAP_ADDRESS_BASE` registers respectively: + +``` + SCROLL_TILE_ADDRESS_BASE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ SCTB3 │ SCTB2 │ SCTB1 │ SCTB0 │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +SCTB0..SCTB3: offsets of the tile address base from the start + of VDP memory, in units of 2048 words. + +tile_base[x] = SCTBx << 11 +``` + +``` + SCROLL_MAP_ADDRESS_BASE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ SCMB3 │ - │ SCMB2 │ - │ SCMB1 │ - │ SCMB0 │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +SCROLL0..SCROLL3: offsets of the map address base from the start of + VDP memory, in units of 4096 words. + +map_base[x] = SCMBx << 12 +``` + +Sprites +------- + +255 sprites can be active at the same time. Each sprite can be 8×8, 8×16, 16×8 or 16×16 pixels, individually. + +All sprites are laid out in 8×8 tiles. Larger sprites will have consecutive tile ids for the columns, but rows are separated by an offset of 16. For example a 16×16 sprite has its four tile ids laid out like this: + +``` + 0 7 8 15 + ┌──────┬──────┐ + │ t+0 │ t+1 │ + 7 │ │ │ + ├──────┼──────┤ + 8 │ t+16 │ t+17 │ + │ │ │ + 15 └──────┴──────┘ +``` + +where `t` is the base id in the sprite metadata. 8×16, 16×8 sprites are similar: just leave out the bottom row or right column. + +Each sprite is defined by three 16-bit words of sprite metadata, `x`, `y`, `g`, written sequentially to the `SPRITE_BLOCK_ADDRESS` register. + +- `x` specifies the x position on the screen, as well as whether to flip the sprite in x direction: + +``` + sprite.x + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ - │XF │ XPOS │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +XPOS: x position of the sprite in screen coordinates +XF: x-flip bit +``` + +- `y` specifies the y position on the screen, as well as whether to flip the sprite in y direction. It also specifies the sprite dimensions. + +``` + sprite.y + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ W │ H │YF │ YPOS │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +YPOS: y position of the sprite in screen coordinates +YF: y-flip bit +W: sprite is 16 pixels instead of 8 pixels wide +H: sprite is 16 pixels instead of 8 pixels tall +``` + +- `g` defines the (base) tile id, which palette to use, and a rendering priority which specifies at which depth it will appear relative to layers. + +``` + sprite.g + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ PAL │ PRI │ TILEID │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +TILEID: base tile id +PRI: sprite priority; priority 0 sprites are behind layer 2, the hindmost layer, + whereas priority 3 sprites are on top of layer 0 +PAL: the palette to use for this sprite (upper 4 bits of palette index) +``` + +Sprite tile ids range from 0..1023, which means up to 1024 (8×8) or 256 (16×16) different sprite graphics can be available at the time to choose from. This is great for animations. It would however fill half of VDP RAM by itself! The base of the sprite tiles in VDP memory is configured through the `SPRITE_TILE_BASE` register: + +``` + SPRITE_TILE_BASE + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ SPTB │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +SPTB: offset of sprite tile base from the start of VDP memory, + in units of 2048 words. + +sprite_tile_base[x] = SPTB << 11 +``` + +The `XPOS` and `YPOS` specify where the top left corner of the sprite is rendered on the screen. Sprites can be partially visible at the borders of the screen. To have a sprite partially visible at the left and/or top of the screen, subtract from the maximum values; the coordinates wrap around. + +The flip bits flip (mirror) the contents of the sprite horizontally and/or vertically. All sprites, even 8×8 ones, are flipped as if they were the full 16×16, so when changing orientation so it is necessary to add an offset to the position to compensate for that. + +There is no separate visibility bit. To disable a sprite it is placed outside the view, generally at `y` equal to the screen height. + +Priority between sprites is determined by their position in metadata memory. Sprites with a higher index are always drawn above those with a lower index. This can cause (potentially useful) masking artefacts if a high index sprite with low layer priority overlaps a low index sprite with high layer priority. + +Affine layer +------------ + +The VDP supports one 1024×1024 pixel affine-transformable layer. + +The affine layer is a 256 color image, so it can utilize the entire palette. + +The data for the affine layer is always stored at offset `0` in memory. There, a 128×128 tile map and graphics for 256 different `8x8` 8-bit color tiles are interleaved. + +Rendering of the affine layer is configured through the following registers: + +- `AFFINE_PRETRANSLATE_X`, `AFFINE_PRETRANSLATE_Y`: Pre-transformation translation. +- `MATRIX_A`, `MATRIX_B`, `MATRIX_C`, `MATRIX_D`: Four-element 2D transformation matrix. +- `AFFINE_TRANSLATE_X`, `AFFINE_TRANSLATE_Y`: Final translation. + +Use of the affine layer is demonstrated in the `affine_platformer` demo. + +Copper +------ + +The VDP features a "copper" coprocessor to perform raster effects. This is a small CPU with four instructions that can modify the VDP registers on the fly, with high precision, *while* the image is being output to the display. + +This allows for tricks where one region of the screen is differently configured from another. A common "copper" effect is to change the palette for every line to get access to more colors (see the `copper_bars` demo). However, much more is possible. For example, only either the affine layer or the normal scroll layers can be enabled at the same time. Using the copper, it's possible to enable one in one region of the screen and the other in another (see the `affine_platformer` and `copper_polygon` demos). + +Copper instructions are 16 bits. It has four main instruction types: + +``` +op name description +-- ---------------- -------------------------------------------- +0 SET_TARGET Set target x or y position +1 WRITE_COMPRESSED Write register (compressed representation) +2 WRITE_REG Write registers +3 JUMP Set instruction pointer +``` + +The two most significant bits of the copper instruction word are the opcode `OP`. The meaning of the rest of the bits depends on the this opcode. + +``` + copper_instruction + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ OP │ ... ARGS ... │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +General instruction format. + +OP, ARGS: As specified per instruction below. + + + SET_TARGET + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ 0 │ 0 │ - │WT │ Y │ TGT │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +Sets either the x or y coordinate of the raster target, then +optionally waits until the current raster x and y match +the target. + +TGT: raster x/y value to target +Y: coordinate selection + 0: select x + 1: select y +WT: wait bit + 0: don't wait, set target x or y register and immediately advance to next + op + 1: set target x/y register then wait until raster x and y reach their + target before advancing to next op + + + WRITE_COMPRESSED + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ 0 │ 1 │ - │ - │ITY│ DAT │ REG │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +Write a short value to a VDP register, compactly. This is useful +because effects are often limited by the size of the copper +RAM. + +REG: target VDP register +DAT: data to write +ITY: autoincrement target Y (then automatically continue) + + + WRITE_REG + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ 1 │ 0 │ITY│ BAS │ NB │ - │ REG │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +Extended write to register instruction. + +REG: target base VDP register +NB: number of batches to write minus one +BAS: reg increment mode (batch size) + 0: REG+0, repeat + 1: REG+0, REG+1, repeat + 2: REG+0, REG+1, REG+2, REG+3, repeat +ITY: autoincrement target Y and wait between batches + + + JUMP + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ 1 │ 1 │ - │ - │ - │ ADR │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +Unconditional jump. + +ADR: jump target address (immediate) + +``` + +When the copper is started (through writing `1` to VDP register `ENABLE_COPPER`) it starts executing instructions at address `0` in copper memory. + +``` + ENABLE_COPPER + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │ - │EN │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +EN: 1=enable copper coprocessor, 0=disable copper coprocessor + Resets the instruction pointer to 0 when going from disabled to enabled. +``` + +Waiting for the target raster position will always wait for both the x and y raster position to match. So when an operation (say, auto-increment) sets only the y coordinate, the old target position for x is retained. + +The copper's VDP register writes may interfere with VDP register writes from the CPU. For example doing VRAM updates while the VDP writes a palette register can result in wrong values. It is recommended to disable the copper when accessing VDP registers or memory from the CPU, when the raster position is off-screen. + +System status +============= + +The system status peripheral exposes global status information and configuration for the system. Currently there is only one function: setting the LEDs on the board. This is often useful as a debug output. + +There is one 32-bit register. + +``` +reg r/w bits name description +------ --- ------- ---------- ---------------------------------------- +0x0000 w [7:0] LED LED status +``` + +DSP +=== + +The DSP (also `SYS_MUL`) has one function: a signed `s16 × s16 = s32` multiply. It exposes a hardware multiplier from the FPGA fabric to code running on the CPU. This allows for fast multiplication when necessary, even though the CPU architecture itself has no multiplication instruction. + +``` +reg r/w bits name description +------ --- ------- ---------- ---------------------------------------- +0x0000 w [15:0] MUL_A Multiplication operand A +0x0004 w [15:0] MUL_B Multiplication operand B +0x0000 r [31:0] MUL_RESULT Multiplication result +``` + +After writing to `MUL_A` and `MUL_B`, `MUL_RESULT` will read as the signed 32-bit result of `MUL_A * MUL_B`. The result in available instantly from the point of view of the CPU. + +Gamepad +======= + +The gamepad peripheral exposes a bit-banging serial interface to read out SNES (or emulated SNES) gamepads. + +There is one 32-bit register, of which the function differs for read or write. + +``` +reg r/w bits name description +------ --- ------- ---------- ---------------------------------------- +0x0000 w [0:0] LATCH Latch the current state of pad inputs +0x0000 w [1:1] CLK Serial clock out +0x0000 r [0:0] P1 Player 1 input +0x0000 r [1:1] P2 Player 2 input +``` + +Using the following pseudo-code + +``` +p1 := 0 +p2 := 0 +LATCH := 1 +LATCH := 0 +for bit in 0..15 + tmp := {P2,P1} + PAD_CLK := 1 + PAD_CLK := 0 + p1[bit] := tmp.P1 + p2[bit] := tmp.P2 +``` + +16 bits can be clocked out on `P1` and `P2` (LSB to MSB), of which the bottom 12 have a defined bit value: + +``` + gamepad_in + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 +┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ +│ - │ - │ - │ - │ R │ L │ X │ A │RT │LT │DN │UP │ST │SE │ Y │ B │ +└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ + +B: "B" button state +Y: "Y" button state +SE: "SELECT" button state +ST: "START" button state +UP: D-pad Up state +DN: D-pad Down state +LT: D-pad Left state +RT: D-pad Right state +A: "A" button state +X: "X" button state +L: Left shoulder button state +R: Right shoulder button state +``` + +A bit will be `1` while the associated button is pressed, and `0` when not. Edge sensitivity is implemented manually in the library. + +VDP "copper" RAM +================ + +The [VDP "copper" coprocessor](#copper) has its own memory-mapped RAM of 4 kB where the instructions for the coprocessor are stored. It is write-only from the CPU point of view and read-only from the copper. This memory is addressed in 16-bit words. + +Bootloader ROM +============== + +There is 1 kB (iCE40) or 2 kB (ECP5) of bootloader ROM integrated in the design. This is the first code that is invoked when the system starts. It is (mostly) assembly code, and is compiled from the `firmware` directory. It clears the registers to an initial state, sets up the flash chip, copies the first 64 kB of flash to RAM then jumps to RAM at offset `0x0000_0000`. + +Flash control +============= + +The flash control register can be used to communicate with the SPI flash, or configure hardware flash access, allowing the CPU to access flash as if it was directly wired into the address space (see [Flash access](#flash-access)). This setup is generally done by the bootloader, and not touched afterwards. However for special cases it could be used in application code, for example to write to flash to store savegames. + +``` +reg r/w bits name description +------ --- ------- ---------- -------------------------- +0x0000 r [3:0] OUT SPI output pins +0x0000 w [3:0] IN SPI input pins +0x0000 w [7:4] IN_EN Input/output mode select +0x0000 w [8:8] CLK SPI clock +0x0000 w [9:9] CSN SPI chip select (negated) +0x0000 w [15:15] ACTIVE Enable flash controller +``` + +Audio +===== + +The audio peripheral of the Icestation-32 streams digital audio directly from flash (there is no way sampled audio fits in the limited RAM), and can mix up to 8 channels. There is separate stereo volume and pitch control for each channel. + +A single audio data format is supported: mono IMA-ADPCM\* 44100Hz. The ADPCM block size is fixed at 1024 bytes. + +Use of the audio peripheral is demonstrated in the `audio_drumkit` demo. + +The ADPCM core is also hosted in a [separate repo](https://github.com/dan-rodrigues/ics-adpcm) which contains tests and further documentation. The documentation below is focused on how to use it in the context of this system. + +Conversion +---------- + +To convert audio to the required ADPCM format without a WAV header there's a special ADPCM converter tool (adpcm-xq), of which the source code is in `super-miyamoto-sprint/utility/adpcm-xq` as well as [its own repository](https://github.com/dbry/adpcm-xq). + + ADPCM-XQ Xtreme Quality IMA-ADPCM WAV Encoder / Decoder Version 0.3 + Copyright (c) 2018 David Bryant. All Rights Reserved. + +The command line to convert any audio file to the required format: + + sox -b16 -r44100 -c1 + adpcm-xq -r -y + +Alternatively, ffmpeg can be used: + + ffmpeg -y -guess_layout_max 0 -i $^ -f s16le -acodec adpcm_ima_wav -ac 1 + +\* ADPCM = "Adaptive Differential Pulse-Code Modulation". See [here](https://wiki.multimedia.cx/index.php/IMA_ADPCM) for a more in-detail description of the encoding. A scanned and OCRed version of the original specification [can be found here](http://www.cs.columbia.edu/~hgs/audio/dvi/IMA_ADPCM.pdf). + +Registers +--------- + +The memory-mapped audio registers are laid out as follows. The registers must be addressed as 32-bit except for the channel descriptors. + +``` +reg r/w bits name description +------ --- ------- ---------- ------------------------------------------------ +0x0000 w - CHANNELS Audio channel descriptors (16 bytes per channel) +0x0200 w [7:0] PLAY Start playing (bit per channel) +0x0200 r [7:0] PLAYING Playing status (bit per channel) +0x0204 w [7:0] STOP Stop playing (bit per channel) +0x0204 r [7:0] ENDED Sample ended (bit per channel) +0x0208 r [0:0] BUSY Audio busy status +``` + +- Write a `1` bit to the `PLAY` register at a given bit position to start playing the sample in that channel. Writing `0` will have no effect. If the sample was already playing it will restart. +- Write a `1` bit to the `STOP` register at a given bit position to stop playing the sample in that channel immediately. Writing `0`, or `1` if no sample was playing will have no effect. + +Channel descriptors are a byte-addressable 16-byte structure that specifies the sample to play on a channel: +``` +ofs type name description +---- ---- -------------- ------------------------------- +0x00 u16 START_ADDRESS Sample starting address +0x02 u8 (padding) +0x03 u8 FLAGS bit 0: LOOP +0x04 u16 END_ADDRESS Sample stop address +0x06 u16 LOOP_ADDRESS Sample loop address +0x08 u8 VOLUME_LEFT Left sound volume +0x09 u8 VOLUME_RIGHT Right sound volume +0x0a u16 PITCH Sound pitch +0x0c u16 (padding) +0x0e u16 (padding) +``` + +- The sample start, end and loop address specify from which address (relative to the start address of the program in flash) the sample is played, and where (if enabled) where to restart after loop. The addresses are specified in a multiple of the ADPCM block size, 1024 bytes. + +- The sound `VOLUME` can be specified separately for left and right for stereo positioning effects. Volumes are a signed 8bit value, with commonly used values being `0` (no sound) and `127` (loudest) and `-128` (loudest and inverted). At the loudest volumes there can be clipping, values around 16 are safest. + +- A `PITCH` value of `0x1000` plays the sound at the original pitch. A higher value of `PITCH` plays the sound at a higher playback rate, thus a higher pitch. So a value of `0x2000` would double the pitch, and a value of `0x800` half it. + +Flash access +============ + +When it is configured correctly by the boot ROM, the SPI flash is directly accessible from the CPU, starting at address `0x1000000`. + +Arbitrary data reads from this area are possible. The addressed area starts at the beginning of the program in flash, because the bootloader will have read the first 64 kB starting from `0x1000000` into RAM at boot. If a game has resources that won't fit in the limited RAM, they can be stored after the initial 64 kB where they can be read through this memory address region. diff --git a/dan-rodrigues_icestation-32/firmware/README.md b/dan-rodrigues_icestation-32/firmware/README.md new file mode 100644 index 0000000000000000000000000000000000000000..73b8aaf1591b858c710fdb289ee8d78c9c3c7eb5 --- /dev/null +++ b/dan-rodrigues_icestation-32/firmware/README.md @@ -0,0 +1,12 @@ +# Firmware + +This program is stored in 1kbyte of preinitialized block RAM and is the first code to be run on startup. + +## Tasks + +* If the `BOOT_PROMPT` variable in the Makefile is set, initialize the VDP with a text prompt. The text prompt is shown until a button on the board is set. The button is the left-shift-key in simulators and the user button on the iCEBreaker. +* Power up the flash and enable quad IO. +* Enter QPI mode if the `QPI_MODE` define is set in boot.S. Default is to remain in QSPI mode. +* Perform a dummy flash read with CRM enabled. This is assumed by the hardware `flash_reader` module which will always keep the flash in CRM mode. +* Perform IPL. 64kbyte at offset 0x200000 in flash is copied to CPU RAM. +* Jump to offset 0x0000 in CPU RAM. The user program now has control of the system. \ No newline at end of file diff --git a/dan-rodrigues_icestation-32/firmware/bootprint.c b/dan-rodrigues_icestation-32/firmware/bootprint.c new file mode 100644 index 0000000000000000000000000000000000000000..59fb190eeb71648887c94fea183fdb077f1a859c --- /dev/null +++ b/dan-rodrigues_icestation-32/firmware/bootprint.c @@ -0,0 +1,62 @@ +// bootprint.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "bootprint.h" + +#include "font.h" +#include "vdp.h" +#include "vdp_regs.h" + +void bp_print_init() { + vdp_enable_layers(SCROLL0); + vdp_set_wide_map_layers(SCROLL0); + vdp_set_alpha_over_layers(0); + vdp_set_vram_increment(1); + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, 0); + + // Monochrome minimal font + + const uint16_t tile_vram_base = 0x0000; + const uint16_t map_vram_base = 0x2000; + + // The C library functions for this is large and unnecessary for this minimal use case + VDP_SCROLL_TILE_ADDRESS_BASE = 0; + VDP_SCROLL_MAP_ADDRESS_BASE = (map_vram_base >> 12 &0xf); + + // Monochrome palette + + const uint16_t bg_color = 0xf033; + const uint16_t fg_color = 0xffff; + + vdp_set_single_palette_color(0, bg_color); + vdp_set_single_palette_color(1, fg_color); + + // + 0x10 to skip the space character + upload_font_minimal(tile_vram_base + 0x10); +} + +void bp_print(uint16_t vram_start, const char *string) { + vdp_seek_vram(vram_start); + + while (*string) { + // Map to the minimal character set + // This could alternatively be preencoded in the caller to avoid doing this here + uint8_t ascii_char = *string; + if (ascii_char == ' ') { + ascii_char = 0; + } else if (ascii_char > '9') { + ascii_char -= 0x40; + } + + uint16_t map = ascii_char; + + vdp_write_vram(map); + + string++; + } +} diff --git a/dan-rodrigues_icestation-32/firmware/bootprint.h b/dan-rodrigues_icestation-32/firmware/bootprint.h new file mode 100644 index 0000000000000000000000000000000000000000..74896e7d860c5c59886151006e48b49b6e2d9a57 --- /dev/null +++ b/dan-rodrigues_icestation-32/firmware/bootprint.h @@ -0,0 +1,15 @@ +// bootprint.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef bootprint_h +#define bootprint_h + +#include + +void bp_print_init(void); +void bp_print(uint16_t vram_start, const char *string); + +#endif /* bootprint_h */ diff --git a/dan-rodrigues_icestation-32/hardware/address_decoder.v b/dan-rodrigues_icestation-32/hardware/address_decoder.v new file mode 100644 index 0000000000000000000000000000000000000000..a00b73e8804550c154765b01efc94ee6eb014e2f --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/address_decoder.v @@ -0,0 +1,112 @@ +// address_decoder.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" + +module address_decoder #( + parameter REGISTERED_INPUTS = 0 +) ( + input clk, + input reset, + + input [24:0] cpu_address, + input cpu_mem_valid, + input [3:0] cpu_wstrb, + output reg [3:0] cpu_wstrb_decoder, + + output reg bootloader_en, + + output reg vdp_en, + output reg vdp_write_en, + + output reg audio_ctrl_en, + output reg audio_ctrl_write_en, + + output reg cpu_ram_en, + output reg cpu_ram_write_en, + + output reg status_en, + output reg status_write_en, + + output reg flash_read_en, + + output reg dsp_en, + output reg dsp_write_en, + + output reg pad_en, + output reg pad_write_en, + + output reg cop_ram_write_en, + + output reg flash_ctrl_en, + output reg flash_ctrl_write_en +); + reg [24:0] cpu_address_r; + reg cpu_mem_valid_r; + + generate + if (REGISTERED_INPUTS) begin + always @(posedge clk) begin + cpu_address_r <= cpu_address; + cpu_mem_valid_r <= cpu_mem_valid; + cpu_wstrb_decoder <= cpu_wstrb; + end + end else begin + always @* begin + cpu_address_r = cpu_address; + cpu_mem_valid_r = cpu_mem_valid; + cpu_wstrb_decoder = cpu_wstrb; + end + end + endgenerate + + // this doesn't need to be exposed but is here for consistency + reg cop_ram_en; + + always @* begin + bootloader_en = 0; + flash_read_en = 0; + audio_ctrl_en = 0; audio_ctrl_write_en = 0; + cpu_ram_en = 0; cpu_ram_write_en = 0; + status_en = 0; status_write_en = 0; + vdp_en = 0; vdp_write_en = 0; + dsp_en = 0; dsp_write_en = 0; + pad_en = 0; pad_write_en = 0; + cop_ram_en = 0; cop_ram_write_en = 0; + flash_ctrl_en = 0; flash_ctrl_write_en = 0; + + if (cpu_mem_valid_r && !reset) begin + if (cpu_address_r[24]) begin + flash_read_en = 1; + end else begin + case (cpu_address_r[19:16]) + 0: cpu_ram_en = 1; + 1: vdp_en = 1; + 2: status_en = 1; + 3: dsp_en = 1; + 4: pad_en = 1; + 5: cop_ram_en = 1; + 6: bootloader_en = 1; + 7: flash_ctrl_en = 1; + 8: audio_ctrl_en = 1; + endcase + end + + cpu_ram_write_en = cpu_ram_en && cpu_wstrb_decoder; + vdp_write_en = vdp_en && cpu_wstrb_decoder; + status_write_en = status_en && cpu_wstrb_decoder; + dsp_write_en = dsp_en && cpu_wstrb_decoder; + pad_write_en = pad_en && cpu_wstrb_decoder; + cop_ram_write_en = cop_ram_en && cpu_wstrb_decoder; + flash_ctrl_write_en = flash_ctrl_en && cpu_wstrb_decoder; + audio_ctrl_write_en = audio_ctrl_en && cpu_wstrb_decoder; + end + end + +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/bus_arbiter.v b/dan-rodrigues_icestation-32/hardware/bus_arbiter.v new file mode 100644 index 0000000000000000000000000000000000000000..5f29eb7bfb72657b9ba06b46d313b403f97b16af --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/bus_arbiter.v @@ -0,0 +1,140 @@ +// bus_arbiter.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "bus_arbiter.vh" + +module bus_arbiter #( + parameter SUPPORT_2X_CLK = 0, + parameter DEFAULT_CPU_RAM_READ = 0, + parameter READ_SOURCES = `BA_ALL +) ( + input clk, + + // CPU inputs + + input [3:0] cpu_wstrb, + input [15:0] cpu_address, + input [31:0] cpu_write_data, + + // Address decoder inputs + + input bootloader_en, + input vdp_en, + input flash_read_en, + input cpu_ram_en, + input dsp_en, + input status_en, + input pad_en, + input cop_en, + input flash_ctrl_en, + input audio_ctrl_en, + + // Ready-inputs from peripherals + + input flash_read_ready, + input vdp_ready, + input audio_ready, + + // Data inputs from peripherals + + input [31:0] bootloader_read_data, + input [31:0] cpu_ram_read_data, + input [31:0] flash_read_data, + input [15:0] vdp_read_data, + input [31:0] dsp_read_data, + input [2:0] pad_read_data, + input [3:0] flash_ctrl_read_data, + input [7:0] audio_cpu_read_data, + + // CPU outputs + + output reg cpu_mem_ready, + output [31:0] cpu_read_data +); + wire cpu_ram_ready, peripheral_ready; + + wire any_peripheral_ready = ((vdp_en && vdp_ready) + || flash_ctrl_en || status_en || dsp_en || pad_en + || cop_en || bootloader_en || audio_ready); + + generate + // using !cpu_mem_ready only works in CPU clk is full speed + if (!SUPPORT_2X_CLK) begin + assign cpu_ram_ready = cpu_ram_en && !cpu_mem_ready; + assign peripheral_ready = any_peripheral_ready && !cpu_mem_ready; + end else begin + assign cpu_ram_ready = cpu_ram_en; + assign peripheral_ready = any_peripheral_ready; + end + endgenerate + + always @(posedge clk) begin + cpu_mem_ready <= cpu_ram_ready || flash_read_ready || peripheral_ready; + end + + // needs registering due to timing + reg flash_read_en_r; + + always @(posedge clk) begin + flash_read_en_r <= flash_read_en; + end + + reg [31:0] cpu_read_data_ps, cpu_read_data_s; + assign cpu_read_data = cpu_read_data_s; + + always @* begin + if (READ_SOURCES & `BA_CPU_RAM) begin + cpu_read_data_ps = cpu_ram_read_data; + end else if (READ_SOURCES & `BA_FLASH) begin + cpu_read_data_ps = flash_read_data; + end else begin + cpu_read_data_ps = {32{1'bx}}; + end + + // the && with the parameters looks strange here but without it, it doesn't get optimized + // providing constants for the *_en inputs does not optimize as desired + // doing the && at the parameter level does work as expected though and reduces *flattened* cell count + + if (flash_read_en_r && (READ_SOURCES & `BA_FLASH)) begin + cpu_read_data_ps = flash_read_data; + end else if (vdp_en && (READ_SOURCES & `BA_VDP)) begin + cpu_read_data_ps[15:0] = vdp_read_data; + end else if (dsp_en && (READ_SOURCES & `BA_DSP)) begin + cpu_read_data_ps = dsp_read_data; + end else if (pad_en && (READ_SOURCES & `BA_PAD)) begin + cpu_read_data_ps[2:0] = pad_read_data; + end else if (bootloader_en && (READ_SOURCES & `BA_BOOT)) begin + cpu_read_data_ps = bootloader_read_data; + end else if (cpu_ram_en && (READ_SOURCES & `BA_CPU_RAM)) begin + cpu_read_data_ps = cpu_ram_read_data; + end else if (flash_ctrl_en && (READ_SOURCES & `BA_FLASH_CTRL)) begin + cpu_read_data_ps[3:0] = flash_ctrl_read_data; + end else if (audio_ctrl_en && (READ_SOURCES & `BA_AUDIO)) begin + cpu_read_data_ps[7:0] = audio_cpu_read_data; + end + end + + generate + if (SUPPORT_2X_CLK) begin + reg [31:0] cpu_read_data_r; + + always @* begin + cpu_read_data_s = cpu_read_data_r; + end + + always @(posedge clk) begin + cpu_read_data_r <= cpu_read_data_ps; + end + end else begin + always @* begin + cpu_read_data_s = cpu_read_data_ps; + end + end + endgenerate + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/bus_arbiter.vh b/dan-rodrigues_icestation-32/hardware/bus_arbiter.vh new file mode 100644 index 0000000000000000000000000000000000000000..534bb4368cd742f9254c8e5e0f729d56ef455808 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/bus_arbiter.vh @@ -0,0 +1,15 @@ +`ifndef bus_arbiter_vh +`define bus_arbiter_vh + +`define BA_CPU_RAM (1 << 0) +`define BA_VDP (1 << 1) +`define BA_DSP (1 << 2) +`define BA_PAD (1 << 3) +`define BA_BOOT (1 << 4) +`define BA_FLASH (1 << 5) +`define BA_FLASH_CTRL (1 << 6) +`define BA_AUDIO (1 << 7) + +`define BA_ALL (`BA_CPU_RAM | `BA_VDP | `BA_DSP | `BA_PAD | `BA_BOOT | `BA_FLASH | `BA_FLASH_CTRL | `BA_AUDIO) + +`endif diff --git a/dan-rodrigues_icestation-32/hardware/clocks.vh b/dan-rodrigues_icestation-32/hardware/clocks.vh new file mode 100644 index 0000000000000000000000000000000000000000..3ffafaff8238ef34f5b45efc305ecaa8b65a5e13 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/clocks.vh @@ -0,0 +1,11 @@ +`ifndef clocks_vh +`define clocks_vh + +`define CLK_1X_WIDESCREEN 16875000 +`define CLK_1X_STANDARD 12587500 +`define CLK_2X_WIDESCREEN 33750000 +`define CLK_2X_STANDARD 25175000 + + +`endif + diff --git a/dan-rodrigues_icestation-32/hardware/common/spram_256k.v b/dan-rodrigues_icestation-32/hardware/common/spram_256k.v new file mode 100644 index 0000000000000000000000000000000000000000..3fc6e1b0000afb89b7c65adbce811cc013d216ea --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/common/spram_256k.v @@ -0,0 +1,31 @@ +// This is based on the iCE40 SPRAM cell in the yosys techlibs + +module spram_256k ( + input clk, + input cs, + input [13:0] address, + input [15:0] write_data, + input [3:0] mask, + input write_en, + output reg [15:0] read_data +); + // This verilator comment is required for the C++ TB to do the IPL + // It slows the sim down, revise this at some point + + reg [15:0] mem [0:16383] /* verilator public */ ; + + always @(posedge clk) begin + if (cs) begin + if (!write_en) begin + read_data <= mem[address]; + end else begin + if (mask[0]) mem[address][ 3: 0] <= write_data[ 3: 0]; + if (mask[1]) mem[address][ 7: 4] <= write_data[ 7: 4]; + if (mask[2]) mem[address][11: 8] <= write_data[11: 8]; + if (mask[3]) mem[address][15:12] <= write_data[15:12]; + read_data <= 0; + end + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/constraints/VM_640x480.py b/dan-rodrigues_icestation-32/hardware/constraints/VM_640x480.py new file mode 100644 index 0000000000000000000000000000000000000000..91dd3ed652af827fdcebc5eac332247412ac499b --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/constraints/VM_640x480.py @@ -0,0 +1,3 @@ +ctx.addClock("clk_2x", 25.175) +ctx.addClock("clk_1x", 12.588) + diff --git a/dan-rodrigues_icestation-32/hardware/constraints/VM_848x480.py b/dan-rodrigues_icestation-32/hardware/constraints/VM_848x480.py new file mode 100644 index 0000000000000000000000000000000000000000..b59ffd1b93ae7a65d688884c4267de62a99396c7 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/constraints/VM_848x480.py @@ -0,0 +1,3 @@ +ctx.addClock("clk_2x", 33.75) +ctx.addClock("clk_1x", 16.88) + diff --git a/dan-rodrigues_icestation-32/hardware/cop_ram.v b/dan-rodrigues_icestation-32/hardware/cop_ram.v new file mode 100644 index 0000000000000000000000000000000000000000..39efb9fd741bb13c12a926f7e5b43c46f0f28617 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/cop_ram.v @@ -0,0 +1,42 @@ +// cop_ram.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" + +module cop_ram( + input clk, + + input [10:0] write_address, + input [15:0] write_data, + input write_en, + + input [10:0] read_address, + output reg [15:0] read_data, + input read_en +); + reg [15:0] ram [0:2047]; + + always @(posedge clk) begin + if (write_en) begin + ram[write_address] <= write_data[15:0]; + end + + if (read_en) begin + read_data <= ram[read_address]; + end + end + + wire has_contention = read_en && write_en && read_address == write_address; + + always @(posedge clk) begin + if (has_contention) begin + $display("COP RAM contention: %x", read_address); + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/cpu_peripheral_sync.v b/dan-rodrigues_icestation-32/hardware/cpu_peripheral_sync.v new file mode 100644 index 0000000000000000000000000000000000000000..1ba4423ed58e95de712bd2aa4a0a1bded5991e53 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/cpu_peripheral_sync.v @@ -0,0 +1,65 @@ +// cpu_peripheral_sync.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module cpu_peripheral_sync( + input clk_1x, + input clk_2x, + + // 1x inputs + input [3:0] cpu_wstrb, + input [31:0] cpu_address, + input [31:0] cpu_write_data, + input cpu_mem_valid, + + // 2x inputs + input cpu_mem_ready, + input [31:0] cpu_read_data, + + output reg [3:0] cpu_wstrb_2x, + output reg [31:0] cpu_write_data_2x, + output reg [31:0] cpu_address_2x, + output reg cpu_mem_valid_2x, + + output reg cpu_mem_ready_1x, + output reg [31:0] cpu_read_data_1x +); + + // --- 1x -> 2x --- + + always @(negedge clk_2x) begin + cpu_write_data_2x <= cpu_write_data; + cpu_address_2x <= cpu_address; + cpu_wstrb_2x <= cpu_wstrb; + cpu_mem_valid_2x <= cpu_mem_valid; + end + + // --- 2x -> 1x --- + + reg [31:0] cpu_read_data_r; + reg cpu_mem_ready_r, cpu_mem_ready_d; + + reg cpu_mem_ready_rose, cpu_mem_ready_rose_r; + + always @(negedge clk_2x) begin + cpu_read_data_r <= cpu_read_data; + + cpu_mem_ready_r <= cpu_mem_ready; + cpu_mem_ready_d <= cpu_mem_ready_r; + cpu_mem_ready_rose <= cpu_mem_ready_r && !cpu_mem_ready_d; + cpu_mem_ready_rose_r <= cpu_mem_ready_rose; + end + + // eliminating this stage causes problems + // negedge 2x clk -> posedge 1x clk gives these signals half a 2x clk cycle to propagate through CPU + + always @(posedge clk_1x) begin + cpu_read_data_1x <= cpu_read_data_r; + cpu_mem_ready_1x <= cpu_mem_ready_rose || cpu_mem_ready_rose_r; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/cpu_ram.v b/dan-rodrigues_icestation-32/hardware/cpu_ram.v new file mode 100644 index 0000000000000000000000000000000000000000..dff018e0550aec929125ea5d03145076272fb79a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/cpu_ram.v @@ -0,0 +1,47 @@ +// cpu_ram.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module cpu_ram( + input clk, + + input [13:0] address, + input cs, + input write_en, + input [3:0] wstrb, + input [31:0] write_data, + + output [31:0] read_data +); + wire [7:0] mask_write_en = { + wstrb[3], wstrb[3], + wstrb[2], wstrb[2], + wstrb[1], wstrb[1], + wstrb[0], wstrb[0] + }; + + spram_256k cpu_ram_0( + .clk(clk), + .address(address), + .write_data(write_data[15:0]), + .mask(mask_write_en[3:0]), + .write_en(write_en), + .cs(cs), + .read_data(read_data[15:0]) + ); + + spram_256k cpu_ram_1( + .clk(clk), + .address(address), + .write_data(write_data[31:16]), + .mask(mask_write_en[7:4]), + .write_en(write_en), + .cs(cs), + .read_data(read_data[31:16]) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/debouncer.v b/dan-rodrigues_icestation-32/hardware/debouncer.v new file mode 100644 index 0000000000000000000000000000000000000000..cd1ca5ebb52bc464259b03513ba03e2e5ff3f9bc --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/debouncer.v @@ -0,0 +1,83 @@ +// debouncer.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module debouncer #( + parameter integer BTN_COUNT = 8 +) ( + input clk, + input reset, + + input [BTN_COUNT - 1:0] btn, + + output reg [BTN_COUNT - 1:0] level, + output reg [BTN_COUNT - 1:0] trigger, + output reg [BTN_COUNT - 1:0] released +); + localparam BTN_WIDTH = BTN_COUNT - 1; + + reg [BTN_WIDTH:0] btn_r [0:1]; + + reg [15:0] debounce_counter_common; + wire debounce_counter_common_tick = debounce_counter_common[15]; + + reg [4:0] debounce_counter_button [0:BTN_WIDTH]; + + always @(posedge clk) begin + btn_r[1] <= btn_r[0]; + btn_r[0] <= btn; + end + + reg [BTN_WIDTH:0] level_r; + + always @(posedge clk) begin + if (reset) begin + level <= 0; + trigger <= 0; + released <= 0; + end else begin + for (i = 0; i < BTN_COUNT; i = i + 1) begin + if (debounce_counter_button[i][4]) begin + level[i] <= btn_r[1][i]; + end + + trigger[i] <= level[i] & ~level_r[i]; + released[i] <= ~level[i] & level_r[i]; + level_r[i] <= level[i]; + end + end + end + + always @(posedge clk) begin + if (reset) begin + debounce_counter_common <= 0; + end else begin + debounce_counter_common <= (debounce_counter_common_tick ? 0 : debounce_counter_common + 1); + end + end + + always @(posedge clk) begin + if (reset) begin + for (i = 0; i < BTN_COUNT; i = i + 1) begin + debounce_counter_button[i] <= 0; + end + end else begin + for (i = 0; i < BTN_COUNT; i = i + 1) begin + if ((btn_r[0][i] == btn_r[1][i])) begin + if (debounce_counter_common_tick && !debounce_counter_button[i][4]) begin + debounce_counter_button[i] <= debounce_counter_button[i] + 1; + end + end else begin + debounce_counter_button[i] <= 0; + end + end + end + end + + integer i; + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/debug.vh b/dan-rodrigues_icestation-32/hardware/debug.vh new file mode 100644 index 0000000000000000000000000000000000000000..f133571d2554fafaf631f2a86a81ae481950ee0a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/debug.vh @@ -0,0 +1,10 @@ +`undef debug +`undef stop + +`ifndef SYNTHESIS + `define debug(debug_command) debug_command + `define stop(debug_command) debug_command; $stop; +`else + `define debug(debug_command) + `define stop(debug_command) +`endif diff --git a/dan-rodrigues_icestation-32/hardware/delay_ff.v b/dan-rodrigues_icestation-32/hardware/delay_ff.v new file mode 100644 index 0000000000000000000000000000000000000000..8e56beec92c5a931a2d1ff4f63d6095518d87305 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/delay_ff.v @@ -0,0 +1,70 @@ +// delay_ff.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +// verilator lint_save +// verilator lint_off DECLFILENAME + +module delay_ff #( + parameter DELAY = 1, + parameter WIDTH = 1 +) ( + input clk, + + input [WIDTH-1:0] in, + output [WIDTH-1:0] out +); + delay_ffr #( + .DELAY(DELAY), + .WIDTH(WIDTH) + ) ffr ( + .clk(clk), + .reset(0), + + .in(in), + .out(out) + ); + +endmodule + + +module delay_ffr #( + parameter DELAY = 1, + parameter WIDTH = 1 +) ( + input clk, + input reset, + + input [WIDTH-1:0] in, + output [WIDTH-1:0] out +); + + reg [WIDTH-1:0] r [0:DELAY]; + + assign out = r[DELAY-1]; + + integer i; + + always @(posedge clk) begin + if (reset) begin + for (i = 0; i < DELAY; i = i + 1) begin + r[i] <= 0; + end + end else begin + r[0] <= in; + + if (DELAY > 1) begin + for (i = 1; i < DELAY; i = i + 1) begin + r[i] <= r[i - 1]; + end + end + end + end + +endmodule + +// verilator lint_restore diff --git a/dan-rodrigues_icestation-32/hardware/dpram.v b/dan-rodrigues_icestation-32/hardware/dpram.v new file mode 100644 index 0000000000000000000000000000000000000000..33754c40e79e0b3c9416cfd2a8ae818e6bcd84ba --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/dpram.v @@ -0,0 +1,37 @@ +// dpram.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module dpram #( + parameter integer DATA_WIDTH = 16, + parameter integer ADDRESS_WIDTH = 8, + + parameter integer DATA_BITS = DATA_WIDTH - 1, + parameter integer ADDRESS_BITS = ADDRESS_WIDTH - 1 +) ( + input clk, + + input write_en, + input [ADDRESS_BITS:0] write_address, + input [DATA_BITS:0] write_data, + + input [ADDRESS_BITS:0] read_address, + output reg [DATA_BITS:0] read_data +); + localparam WORDS = 1 << ADDRESS_WIDTH; + + reg [DATA_BITS:0] mem [0:WORDS - 1]; + + always @(posedge clk) begin + if (write_en) begin + mem[write_address] <= write_data; + end + + read_data <= mem[read_address]; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/flash_arbiter.v b/dan-rodrigues_icestation-32/hardware/flash_arbiter.v new file mode 100644 index 0000000000000000000000000000000000000000..42c9826c981b4b3a4e2784079e26551b543476ad --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/flash_arbiter.v @@ -0,0 +1,124 @@ +// flash_arbiter.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" + +module flash_arbiter( + input clk, + input reset, + + input [23:0] read_address_a, + input read_en_a, + input size_a, + output reg ready_a, + + input [23:0] read_address_b, + input read_en_b, + input size_b, + output reg ready_b, + + output [31:0] read_data, + + // QSPI flash + + output flash_clk_en, + output flash_csn, + output [3:0] flash_in, + output [3:0] flash_in_en, + input [3:0] flash_out +); + localparam [23:0] FLASH_USER_BASE = 24'h200000; + + // --- Arbitration between reader A/B --- + + localparam [0:0] + READER_A = 1, + READER_B = 0; + + reg reader_selected; + reg read_active; + + reg read_en_a_r, read_en_b_r; + reg read_en_a_edge, read_en_b_edge; + + always @(posedge clk) begin + read_en_a_r <= read_en_a; + read_en_b_r <= read_en_b; + read_en_a_edge <= (read_en_a && !read_en_a_r) || read_en_a_edge; + read_en_b_edge <= (read_en_b && !read_en_b_r) || read_en_b_edge; + + ready_a <= 0; + ready_b <= 0; + + // Is either reader waiting? + + if (!read_active) begin + // Prioritize B if there is a double read in same cycle + if (read_en_b_edge) begin + reader_selected <= READER_B; + read_active <= 1; + read_en_b_edge <= 0; + end else if (read_en_a_edge) begin + reader_selected <= READER_A; + read_active <= 1; + read_en_a_edge <= 0; + end + end + + // Is read done? + + if (flash_ready) begin + if (reader_selected == READER_A) begin + ready_a <= 1; + end else begin + ready_b <= 1; + end + + read_active <= 0; + end + + if (reset) begin + read_active <= 0; + end + end + + // --- Register flash reader inputs --- + + reg [23:0] flash_read_address; + reg flash_read_en; + reg flash_read_size; + + always @(posedge clk) begin + flash_read_address <= (reader_selected ? read_address_a : read_address_b) + FLASH_USER_BASE; + flash_read_en <= (reader_selected ? read_en_a : read_en_b) && read_active; + flash_read_size <= (reader_selected ? size_a : size_b); + end + + // --- Flash memory (16Mbyte - 1Mbyte) --- + + wire flash_ready; + + flash_reader flash_reader( + .clk(clk), + .reset(reset), + + .valid(flash_read_en), + .size(flash_read_size), + .address(flash_read_address), + + .data(read_data), + .ready(flash_ready), + + .flash_clk_en(flash_clk_en), + .flash_csn(flash_csn), + .flash_out(flash_out), + .flash_in(flash_in), + .flash_in_en(flash_in_en) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/flash_reader.v b/dan-rodrigues_icestation-32/hardware/flash_reader.v new file mode 100644 index 0000000000000000000000000000000000000000..7610eff3fe3f7c61b50306bcdfa28cd507c2a5f7 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/flash_reader.v @@ -0,0 +1,116 @@ +// flash_reader.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +// This flash controller assumes QPI (or QSPI) and CRM have been preenabled +// The assumed CRM command is 0xeb (Fast Read Quad I/O) +// It will keep CRM enabled after every read + +`default_nettype none + +// Note flash_in, flash_in_en and flash_csn are not registered in this module +// They are registered externally (SB_IO instances for up5k) + +module flash_reader #( + parameter [0:0] ASSUME_QPI = 0 +) ( + input clk, + input reset, + + input valid, + input [23:0] address, + input size, + output reg [31:0] data, + output reg ready, + + output reg flash_clk_en, + output reg flash_csn, + output reg [3:0] flash_in, + output reg [3:0] flash_in_en, + input [3:0] flash_out +); + localparam DUMMY_CYCLES = ASSUME_QPI ? 0 : 4; + + // Winbond: byte[5:4] == 2'b10 + // ISSI: byte[7:4] == 4'b1001 + localparam [7:0] CRM_BYTE = 8'h20 | 8'h80; + + reg [4:0] state; + + wire [3:0] byte_state = state[4:1]; + wire nybble_state = state[0]; + + reg [3:0] read_buffer; + wire [7:0] read_byte = {read_buffer, flash_out}; + + always @(posedge clk) begin + if (nybble_state) begin + read_buffer <= flash_out; + end + end + + reg [7:0] selected_byte; + + always @* begin + case (byte_state) + 0: selected_byte = address[23:16]; + 1: selected_byte = address[15:8]; + 2: selected_byte = address[7:0]; + default: selected_byte = CRM_BYTE; + endcase + end + + always @* begin + flash_in = nybble_state ? selected_byte[3:0] : selected_byte[7:4]; + end + + always @(posedge clk) begin + if (!nybble_state) begin + case (byte_state - (DUMMY_CYCLES / 2)) + 5: data[7:0] <= read_byte; + 6: data[15:8] <= read_byte; + 7: data[23:16] <= read_byte; + 8: data[31:24] <= read_byte; + endcase + end + end + + wire halted = (reset || !valid || ready); + + always @* begin + if (halted) begin + flash_in_en = 0; + flash_csn = 1; + end else begin + flash_csn = 0; + + case (byte_state) + 0, 1, 2, 3: flash_in_en = 4'hf; + default: flash_in_en = 0; + endcase + end + end + + wire [4:0] state_final = 5'h0b + (size ? 4 : 0) + DUMMY_CYCLES; + + always @(posedge clk) begin + if (halted) begin + flash_clk_en <= 0; + state <= 0; + ready <= 0; + end else begin + if (flash_clk_en) begin + state <= state + 1; + end + + flash_clk_en <= 1; + + if (state == state_final) begin + ready <= 1; + end + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/icebreaker/ics32_top_icebreaker.v b/dan-rodrigues_icestation-32/hardware/icebreaker/ics32_top_icebreaker.v new file mode 100644 index 0000000000000000000000000000000000000000..ff519530540ee7f385bfc229fc7b6681364764cb --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/icebreaker/ics32_top_icebreaker.v @@ -0,0 +1,345 @@ +// ics32_top_icebreaker.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module ics32_top_icebreaker #( + parameter [0:0] ENABLE_WIDESCREEN = 1, + parameter [0:0] GAMEPAD_PMOD = 0 +) ( + input clk_12m, + + output [3:0] vga_r, + output [3:0] vga_g, + output [3:0] vga_b, + + output vga_hsync, + output vga_vsync, + + output vga_clk, + output vga_de, + + output led_r, + output led_b, + + output flash_clk, + output flash_csn, + inout [3:0] flash_io, + + input btn_u, + + // PMOD 2 (3-button breakout board PMOD *OR* gamepad + audio PMOD) + + inout pmod2_1, + inout pmod2_2, + inout pmod2_3, + inout pmod2_4, + + inout pmod2_7, + inout pmod2_8, + inout pmod2_9, + inout pmod2_10 +); + // --- PDM Audio DAC (Gamepad + audio PMOD) --- + + localparam PCM_WIDTH = 16; + + generate + if (GAMEPAD_PMOD) begin + wire pdm_audio_l, pdm_audio_r; + + // PDM stereo output + + SB_IO #( + .PIN_TYPE(6'b010100), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) pdm_stereo_dac_sbio [1:0] ( + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN({pmod2_4, pmod2_10}), + .D_OUT_0({pdm_audio_l, pdm_audio_r}), + ); + + pdm_dac #( + .WIDTH(PCM_WIDTH) + ) pdm_stereo_dac [1:0] ( + .clk(clk_2x), + .reset(reset_2x), + + .pcm_in({audio_output_l, audio_output_r}), + .pcm_valid({audio_output_valid, audio_output_valid}), + + .pdm_out({pdm_audio_l, pdm_audio_r}) + ); + end + endgenerate + + // --- Clocks --- + + localparam integer CLK_2X_FREQ = ENABLE_WIDESCREEN ? `CLK_2X_WIDESCREEN : `CLK_2X_STANDARD; + localparam integer CLK_1X_FREQ = ENABLE_WIDESCREEN ? `CLK_1X_WIDESCREEN : `CLK_1X_STANDARD; + + // --- iCE40 PLL (640x480 or 848x480 clock selection) --- + + wire clk_1x, clk_2x; + wire pll_locked; + + pll_ice40 #( + .ENABLE_FAST_CLK(ENABLE_WIDESCREEN) + ) pll ( + .clk_12m(clk_12m), + + .locked(pll_locked), + .clk_1x(clk_1x), + .clk_2x(clk_2x) + ); + + // --- DVI video (dual PMOD with HDMI compatible port) --- + + // CLK + + SB_IO #( + .PIN_TYPE(6'b010000), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) vga_clk_sbio ( + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN(vga_clk), + .D_OUT_0(1'b0), + .D_OUT_1(1'b1) + ); + + // RGBS + DE + + SB_IO #( + .PIN_TYPE(6'b010100), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) vga_rgbsde_sbio [14:0] ( + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN({vga_de, vga_vsync, vga_hsync, vga_r, vga_g, vga_b}), + .D_OUT_0({vga_de_io, vga_vsync_io, vga_hsync_io, vga_r_io, vga_g_io, vga_b_io}), + ); + + // --- iCE40 Flash IO --- + + wire [3:0] flash_out; + wire [3:0] flash_in_en; + wire [3:0] flash_in; + + // IO + + SB_IO #( + .PIN_TYPE(6'b110100), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) flash_inout_sbio [3:0] ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .OUTPUT_ENABLE(flash_in_en), + .PACKAGE_PIN(flash_io), + .D_OUT_0(flash_in), + .D_IN_0(flash_out) + ); + + // CSN + + SB_IO #( + .PIN_TYPE(6'b010100), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) flash_csn_sbio ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN(flash_csn), + .D_OUT_0(flash_csn_io) + ); + + // CLK + + SB_IO #( + .PIN_TYPE(6'b010000), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) flash_clk_sbio ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN(flash_clk), + .D_OUT_0(flash_clk_ddr[0]), + .D_OUT_1(flash_clk_ddr[1]) + ); + + // --- User inputs --- + + // Gamepads: + + wire [1:0] pad_read_data; + + generate + if (GAMEPAD_PMOD) begin + wire [1:0] pad_read_data_n; + assign pad_read_data = ~pad_read_data_n; + + // Gamepad CLK + Latch + + SB_IO #( + .PIN_TYPE(6'b010100), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) gp_clk_latch_sbio [1:0] ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN({pmod2_1, pmod2_7}), + .D_OUT_0({pad_clk, pad_latch}) + ); + + // Gamepad data + + // There are actually 4 controller ports on the PMOD but the system is 2P only + + SB_IO #( + .PIN_TYPE(6'b000000), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) gp_data_sbio [1:0] ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN({pmod2_8, pmod2_2}), + .D_IN_0(pad_read_data_n) + ); + end else begin + // Breakout board buttons: + + wire [2:0] btn_r; + + SB_IO #( + .PIN_TYPE(6'b000000), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) btn_sbio [2:0] ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN({pmod2_10, pmod2_4, pmod2_9}), + .D_IN_0(btn_r) + ); + + // P1 has limited inputs using the breakout board + + wire [11:0] pad_btn = {btn_r[0], btn_r[2], 5'b0, btn_r[1]}; + + mock_gamepad mock_gamepad( + .clk(clk_2x), + + .pad_clk(pad_clk), + .pad_btn(pad_btn), + .pad_latch(pad_latch), + + .pad_out(pad_read_data[0]) + ); + + // P2 has no inputs when just using the breakout board + + assign pad_read_data[1] = 0; + end + endgenerate + + // User button: + + wire user_button; + wire user_button_n = !user_button; + + SB_IO #( + .PIN_TYPE(6'b000000), + .PULLUP(1'b0), + .NEG_TRIGGER(1'b0), + .IO_STANDARD("SB_LVCMOS") + ) btn_sbio ( + .INPUT_CLK(clk_2x), + .OUTPUT_CLK(clk_2x), + + .PACKAGE_PIN(btn_u), + .D_IN_0(user_button) + ); + + // --- icestation-32 --- + + wire reset_1x, reset_2x; + + wire [3:0] flash_in; + wire [3:0] flash_in_en; + wire flash_csn_io; + wire [1:0] flash_clk_ddr; + + wire pad_latch, pad_clk; + + wire vga_hsync_io, vga_vsync_io, vga_de_io; + wire [3:0] vga_r_io, vga_g_io, vga_b_io; + + wire audio_output_valid; + wire [15:0] audio_output_l, audio_output_r; + + ics32 #( + .CLK_1X_FREQ(CLK_1X_FREQ), + .CLK_2X_FREQ(CLK_2X_FREQ), + .ENABLE_WIDESCREEN(ENABLE_WIDESCREEN), + .ENABLE_FAST_CPU(0), + .RESET_DURATION_EXPONENT(24), + .ENABLE_BOOTLOADER(1), + .BOOTLOADER_SIZE(256), + ) ics32 ( + .clk_1x(clk_1x), + .clk_2x(clk_2x), + .pll_locked(pll_locked), + + .reset_1x(reset_1x), + .reset_2x(reset_2x), + + .vga_r(vga_r_io), + .vga_g(vga_g_io), + .vga_b(vga_b_io), + + .vga_hsync(vga_hsync_io), + .vga_vsync(vga_vsync_io), + .vga_de(vga_de_io), + + .pad_latch(pad_latch), + .pad_clk(pad_clk), + .pad_data(pad_read_data), + + .user_button(user_button_n), + + .led({led_r, led_b}), + + .flash_clk_ddr(flash_clk_ddr), + .flash_csn(flash_csn_io), + .flash_in_en(flash_in_en), + .flash_in(flash_in), + .flash_out(flash_out), + + .audio_output_l(audio_output_l), + .audio_output_r(audio_output_r), + .audio_output_valid(audio_output_valid) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/icebreaker/pdm_dac.v b/dan-rodrigues_icestation-32/hardware/icebreaker/pdm_dac.v new file mode 100644 index 0000000000000000000000000000000000000000..dfd7f714ccf1a4c6b686ff8e84ece5c1055517b1 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/icebreaker/pdm_dac.v @@ -0,0 +1,36 @@ +// pdm_dac.v +// +// Based on the icebreaker-examples repo: +// https://github.com/icebreaker-fpga/icebreaker-examples/tree/master/gamepad-audio + +`default_nettype none + +module pdm_dac #( + parameter integer WIDTH = 16 +) ( + input clk, + input reset, + + input [WIDTH - 1:0] pcm_in, + input pcm_valid, + + output pdm_out +); + reg [WIDTH - 1:0] pdm_level; + reg [WIDTH + 1:0] pdm_sigma; + assign pdm_out = ~pdm_sigma[WIDTH + 1]; + + always @(posedge clk) begin + if (reset) begin + pdm_level <= 0; + pdm_sigma <= 0; + end else begin + if (pcm_valid) begin + pdm_level <= pcm_in + ((1 << (WIDTH - 1))); + end + + pdm_sigma <= pdm_sigma + {pdm_out, pdm_out, pdm_level}; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/icebreaker/pll_ice40.v b/dan-rodrigues_icestation-32/hardware/icebreaker/pll_ice40.v new file mode 100644 index 0000000000000000000000000000000000000000..cc1b173c71eed2acaf51b195afb973f691dcedca --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/icebreaker/pll_ice40.v @@ -0,0 +1,49 @@ +// pll_ice40.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module pll_ice40 #( + parameter ENABLE_FAST_CLK = 1 +) ( + // verilator lint_off UNUSED + input clk_12m, + // verilator lint_on UNUSED + + output locked, + output clk_1x /* verilator clocker */, + output clk_2x /* verilator clocker */ +); + localparam PLL_DIVR_25M = 4'b0000; + localparam PLL_DIVF_25M = 7'b1000010; + localparam PLL_DIVQ_25M = 7'b101; + + localparam PLL_DIVR_33M = 4'b0000; + localparam PLL_DIVF_33M = 7'b0101100; + localparam PLL_DIVQ_33M = 7'b100; + + localparam PLL_DIVR = ENABLE_FAST_CLK ? PLL_DIVR_33M : PLL_DIVR_25M; + localparam PLL_DIVF = ENABLE_FAST_CLK ? PLL_DIVF_33M : PLL_DIVF_25M; + localparam PLL_DIVQ = ENABLE_FAST_CLK ? PLL_DIVQ_33M : PLL_DIVQ_25M; + + SB_PLL40_2F_PAD #( + .FEEDBACK_PATH("SIMPLE"), + .PLLOUT_SELECT_PORTA("GENCLK_HALF"), + .PLLOUT_SELECT_PORTB("GENCLK"), + .DIVR(PLL_DIVR), + .DIVF(PLL_DIVF), + .DIVQ(PLL_DIVQ), + .FILTER_RANGE(3'b001) + ) pll ( + .LOCK(locked), + .RESETB(1'b1), + .BYPASS(1'b0), + .PACKAGEPIN(clk_12m), + .PLLOUTGLOBALA(clk_1x), + .PLLOUTGLOBALB(clk_2x) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/icebreaker/spram_256k.v b/dan-rodrigues_icestation-32/hardware/icebreaker/spram_256k.v new file mode 100644 index 0000000000000000000000000000000000000000..65868d16715d7ba01062125f4a0a72b17bbc8b96 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/icebreaker/spram_256k.v @@ -0,0 +1,25 @@ +// This is based on the iCE40 SPRAM cell in the yosys techlibs + +module spram_256k ( + input clk, + input cs, + input [13:0] address, + input [15:0] write_data, + input [3:0] mask, + input write_en, + output reg [15:0] read_data +); + SB_SPRAM256KA ram ( + .ADDRESS(address), + .DATAIN(write_data), + .MASKWREN(mask), + .WREN(write_en), + .CHIPSELECT(cs), + .CLOCK(clk), + .STANDBY(0), + .SLEEP(0), + .POWEROFF(1), + .DATAOUT(read_data) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ics32.v b/dan-rodrigues_icestation-32/hardware/ics32.v new file mode 100644 index 0000000000000000000000000000000000000000..c322da84681ce335450311eecceb2de2da78d35c --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ics32.v @@ -0,0 +1,744 @@ +// ics32.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "bus_arbiter.vh" +`include "clocks.vh" + +module ics32 #( + parameter integer CLK_1X_FREQ = `CLK_1X_WIDESCREEN, + parameter integer CLK_2X_FREQ = `CLK_2X_WIDESCREEN, + parameter [0:0] USE_VEXRISCV = 1, + parameter [0:0] ENABLE_WIDESCREEN = 1, + parameter [0:0] ENABLE_FAST_CPU = 0, + parameter integer RESET_DURATION_EXPONENT = 2, + parameter [0:0] ENABLE_BOOTLOADER = 1, + parameter integer BOOTLOADER_SIZE = 256, + parameter ADPCM_STEP_LUT_PATH = "adpcm_step_lut.hex", +`ifdef BOOTLOADER + parameter BOOTLOADER_PATH = `BOOTLOADER +`else + parameter BOOTLOADER_PATH = "boot.hex" +`endif +) ( + input clk_1x, + input clk_2x, + input pll_locked, + + output reset_1x, + output reset_2x, + + output [3:0] vga_r, + output [3:0] vga_g, + output [3:0] vga_b, + + output vga_hsync, + output vga_vsync, + output vga_de, + + output [7:0] led, + + output pad_latch, + output pad_clk, + input [1:0] pad_data, + + input user_button, + + output [1:0] flash_clk_ddr, + output flash_csn, + output [3:0] flash_in, + output [3:0] flash_in_en, + input [3:0] flash_out, + + output [15:0] audio_output_l, + output [15:0] audio_output_r, + output audio_output_valid +); + // --- Bootloader --- + + localparam BOOTLOADER_ADDRESS_WIDTH = $clog2(BOOTLOADER_SIZE); + + reg [31:0] bootloader [0:BOOTLOADER_SIZE - 1]; + + reg [31:0] bootloader_read_data; + + initial begin + $readmemh(BOOTLOADER_PATH, bootloader); + end + + always @(posedge cpu_clk) begin + bootloader_read_data <= bootloader[cpu_address_1x[BOOTLOADER_ADDRESS_WIDTH + 1:2]]; + end + + // --- LEDs --- + + reg [7:0] status; + + assign led = status; + + always @(posedge vdp_clk) begin + if (vdp_reset) begin + status <= 8'h00; + end else if (status_write_en) begin + status <= cpu_write_data[7:0]; + end + end + + // --- DSP math support --- + + reg [15:0] dsp_mult_a, dsp_mult_b; + reg [31:0] dsp_result; + + // The dsp_mult_a/b assignments can't be in nested if statements to infer the MAC16 FFs + // Otherwise, SB_DFFs are spent on this + + always @(posedge vdp_clk) begin + if (dsp_write_en && !cpu_address[2]) begin + dsp_mult_a <= cpu_write_data[15:0]; + end + + if (dsp_write_en && cpu_address[2]) begin + dsp_mult_b <= cpu_write_data[15:0]; + end + + // signed only for now + dsp_result <= $signed(dsp_mult_a) * $signed(dsp_mult_b); + end + + // --- Reset generator --- + + reset_generator #( + .DURATION_EXPONENT(RESET_DURATION_EXPONENT) + ) reset_generator ( + .clk_1x(clk_1x), + .clk_2x(clk_2x), + .pll_locked(pll_locked), + + .reset_1x(reset_1x), + .reset_2x(reset_2x) + ); + + // --- Clock Assignment --- + + wire cpu_clk, vdp_clk; + wire cpu_reset, vdp_reset; + + generate + if (!ENABLE_FAST_CPU) begin + assign cpu_clk = clk_1x; + assign vdp_clk = clk_2x; + + assign cpu_reset = reset_1x; + assign vdp_reset = reset_2x; + end else begin + assign cpu_clk = clk_2x; + assign vdp_clk = clk_2x; + + assign cpu_reset = reset_2x; + assign vdp_reset = reset_2x; + end + endgenerate + + // --- Address deccoder --- + + wire vdp_en, vdp_write_en; + wire audio_ctrl_en, audio_ctrl_write_en; + wire status_en, status_write_en; + wire flash_read_en; + wire dsp_en, dsp_write_en; + wire pad_en, pad_write_en; + wire cop_ram_write_en; + wire flash_ctrl_en, flash_ctrl_write_en; + + wire [3:0] cpu_wstrb_decoder; + + address_decoder #( + .REGISTERED_INPUTS(!ENABLE_FAST_CPU) + ) decoder ( + .clk(vdp_clk), + .reset(vdp_reset), + + .cpu_address(cpu_address), + .cpu_mem_valid(cpu_mem_valid), + .cpu_wstrb(cpu_wstrb), + .cpu_wstrb_decoder(cpu_wstrb_decoder), + + .audio_ctrl_en(audio_ctrl_en), + .audio_ctrl_write_en(audio_ctrl_write_en), + + .vdp_en(vdp_en), + .vdp_write_en(vdp_write_en), + + .status_en(status_en), + .status_write_en(status_write_en), + + .dsp_en(dsp_en), + .dsp_write_en(dsp_write_en), + + .pad_en(pad_en), + .pad_write_en(pad_write_en), + + .cop_ram_write_en(cop_ram_write_en), + + .flash_read_en(flash_read_en), + + .flash_ctrl_en(flash_ctrl_en), + .flash_ctrl_write_en(flash_ctrl_write_en), + + // Unused (handled by 1x decoder) + .cpu_ram_en(), + .cpu_ram_write_en(), + .bootloader_en() + ); + + wire active_display; + assign vga_de = active_display; + + // --- Copper RAM --- + + wire [10:0] cop_ram_write_address = {cpu_address[11:2], cpu_wstrb_decoder[2]}; + wire [15:0] cop_ram_read_data; + + wire [10:0] cop_ram_read_address; + wire cop_ram_read_en; + + cop_ram cop_ram( + .clk(vdp_clk), + + .write_address(cop_ram_write_address), + .write_data(cpu_write_data[15:0]), + .write_en(cop_ram_write_en), + + .read_address(cop_ram_read_address), + .read_data(cop_ram_read_data), + .read_en(cop_ram_read_en) + ); + + // --- CPU 1x memory decoder / arbiter --- + + wire bootloader_en; + wire cpu_ram_en, cpu_ram_write_en; + + address_decoder decoder_1x( + .clk(cpu_clk), + .reset(cpu_reset), + + .cpu_address(cpu_address_1x), + .cpu_mem_valid(cpu_mem_valid_1x), + .cpu_wstrb(cpu_wstrb_1x), + + .cpu_ram_en(cpu_ram_en), + .cpu_ram_write_en(cpu_ram_write_en), + + .bootloader_en(bootloader_en), + + // Unused outputs (handled by 2x decoder) + .cpu_wstrb_decoder(), + .vdp_en(), + .audio_ctrl_en(), + .audio_ctrl_write_en(), + .status_en(), + .status_write_en(), + .flash_read_en(), + .dsp_write_en(), + .pad_en(), + .pad_write_en(), + .cop_ram_write_en(), + .flash_ctrl_en() + ); + + wire [31:0] cpu_read_data_1x_arbiter; + wire cpu_mem_ready_1x_arbiter; + + bus_arbiter #( + .SUPPORT_2X_CLK(0), + .READ_SOURCES(`BA_CPU_RAM | `BA_BOOT) + ) bus_arbiter_1x ( + .clk(cpu_clk), + + // Inputs + + .cpu_address(cpu_address_1x), + .cpu_write_data(cpu_write_data_1x), + .cpu_wstrb(cpu_wstrb_1x), + + .bootloader_en(bootloader_en), + .cpu_ram_en(cpu_ram_en), + .vdp_en(0), + .flash_read_en(0), + .dsp_en(0), + .status_en(0), + .pad_en(0), + .cop_en(0), + .flash_ctrl_en(0), + .audio_ctrl_en(0), + + .flash_read_ready(0), + .vdp_ready(0), + .audio_ready(0), + + .bootloader_read_data(bootloader_read_data), + .cpu_ram_read_data(cpu_ram_read_data), + .flash_read_data(0), + .dsp_read_data(0), + .vdp_read_data(0), + .pad_read_data(0), + .flash_ctrl_read_data(0), + .audio_cpu_read_data(0), + + // Outputs + + .cpu_mem_ready(cpu_mem_ready_1x_arbiter), + .cpu_read_data(cpu_read_data_1x_arbiter) + ); + + // --- 1x <-> 2x clock sync (if required) --- + + wire [31:0] cpu_read_data_2x_source; + wire cpu_mem_ready_2x_source; + wire cpu_access_1x = bootloader_en || cpu_ram_en; + + assign cpu_read_data_1x = cpu_access_1x ? cpu_read_data_1x_arbiter : cpu_read_data_2x_source; + assign cpu_mem_ready_1x = cpu_access_1x ? cpu_mem_ready_1x_arbiter : cpu_mem_ready_2x_source; + + generate + if (!ENABLE_FAST_CPU) begin + wire [31:0] cpu_read_data_2x_sync; + wire cpu_mem_ready_2x_sync; + + assign cpu_read_data_2x_source = cpu_read_data_2x_sync; + assign cpu_mem_ready_2x_source = cpu_mem_ready_2x_sync; + + cpu_peripheral_sync cpu_peripheral_sync( + .clk_1x(clk_1x), + .clk_2x(clk_2x), + + // 1x inputs + .cpu_address(cpu_address_1x), + .cpu_wstrb(cpu_wstrb_1x), + .cpu_write_data(cpu_write_data_1x), + .cpu_mem_valid(cpu_mem_valid_1x), + + // 2x inputs + .cpu_mem_ready(cpu_mem_ready), + .cpu_read_data(cpu_read_data), + + // 1x outputs (back to CPU) + .cpu_read_data_1x(cpu_read_data_2x_sync), + .cpu_mem_ready_1x(cpu_mem_ready_2x_sync), + + // 2x outputs + .cpu_wstrb_2x(cpu_wstrb), + .cpu_write_data_2x(cpu_write_data), + .cpu_address_2x(cpu_address), + .cpu_mem_valid_2x(cpu_mem_valid) + ); + end else begin + assign cpu_wstrb = cpu_wstrb_1x; + assign cpu_address = cpu_address_1x; + assign cpu_write_data = cpu_write_data_1x; + assign cpu_mem_valid = cpu_mem_valid_1x; + + assign cpu_read_data_2x_source = cpu_read_data; + assign cpu_mem_ready_2x_source = cpu_mem_ready; + end + endgenerate + + // --- VDP --- + + wire vdp_active_frame_ended; + + wire [6:0] vdp_write_address = {cpu_address[15:2], cpu_wstrb_decoder[2]}; + + wire vdp_read_en = vdp_en && !vdp_write_en; + + wire [15:0] vdp_read_data; + wire vdp_ready; + + wire [13:0] vram_address_odd; + wire [13:0] vram_address_even; + + wire vram_we_even; + wire vram_we_odd; + wire [15:0] vram_write_data_even; + wire [15:0] vram_write_data_odd; + + wire [15:0] vram_read_data_even; + wire [15:0] vram_read_data_odd; + + vdp # ( + .ENABLE_WIDESCREEN(ENABLE_WIDESCREEN) + ) vdp ( + .clk(vdp_clk), + .reset(vdp_reset), + + .host_address(vdp_write_address), + .host_read_en(vdp_read_en), + .host_write_en(vdp_write_en), + .host_read_data(vdp_read_data), + .host_ready(vdp_ready), + .host_write_data(cpu_write_data[15:0]), + + .vga_hsync(vga_hsync), + .vga_vsync(vga_vsync), + .r(vga_r), + .g(vga_g), + .b(vga_b), + + .active_display(active_display), + .active_frame_ended(vdp_active_frame_ended), + + .vram_address_even(vram_address_even), + .vram_we_even(vram_we_even), + .vram_write_data_even(vram_write_data_even), + .vram_read_data_even(vram_read_data_even), + + .vram_address_odd(vram_address_odd), + .vram_we_odd(vram_we_odd), + .vram_write_data_odd(vram_write_data_odd), + .vram_read_data_odd(vram_read_data_odd), + + .cop_ram_read_en(cop_ram_read_en), + .cop_ram_read_address(cop_ram_read_address), + .cop_ram_read_data(cop_ram_read_data), + + .frame_ended() + ); + + vram vram( + .clk(vdp_clk), + + .even_address(vram_address_even), + .odd_address(vram_address_odd), + .even_write_en(vram_we_even), + .odd_write_en(vram_we_odd), + .write_data({vram_write_data_odd, vram_write_data_even}), + + .read_data({vram_read_data_odd, vram_read_data_even}) + ); + + // --- ADPCM Audio --- + + wire audio_ctrl_ch_write_ready, audio_gb_write_ready; + wire audio_ctrl_ready = audio_ctrl_ch_write_ready || audio_gb_write_ready || audio_ctrl_read_ready; + + wire audio_ctrl_read_request = audio_ctrl_en && !audio_ctrl_write_en; + wire audio_ctrl_read_ready; + + wire audio_ctrl_ch_write_en = audio_ctrl_write_en && !cpu_address[9]; + wire audio_ctrl_gb_write_en = audio_ctrl_write_en && cpu_address[9]; + + wire [7:0] audio_ctrl_ch_write_address = {cpu_address[8:2], (cpu_wstrb_decoder[2] | cpu_wstrb_decoder[3])}; + + wire [1:0] audio_ctrl_write_byte_mask = { + cpu_wstrb_decoder[1] | cpu_wstrb_decoder[3], + cpu_wstrb_decoder[0] | cpu_wstrb_decoder[2] + }; + + wire [7:0] audio_ctrl_cpu_read_data; + + wire [22:0] pcm_read_address; + wire pcm_read_en; + wire pcm_data_ready; + + ics_adpcm #( + .OUTPUT_INTERVAL(CLK_2X_FREQ / 44100), + .CHANNELS(8), + .ADPCM_STEP_LUT_PATH(ADPCM_STEP_LUT_PATH) + ) ics_adpcm ( + .clk(vdp_clk), + .reset(vdp_reset), + + .ch_write_address(audio_ctrl_ch_write_address), + .ch_write_data(cpu_write_data[15:0]), + .ch_write_byte_mask(audio_ctrl_write_byte_mask), + .ch_write_en(audio_ctrl_ch_write_en), + .ch_write_ready(audio_ctrl_ch_write_ready), + + .gb_write_address(cpu_address[3:2]), + .gb_write_data(cpu_write_data[15:0]), + .gb_write_en(audio_ctrl_gb_write_en), + .gb_write_ready(audio_gb_write_ready), + + .status_read_address(cpu_address[3:2]), + .status_read_request(audio_ctrl_read_request), + .status_read_ready(audio_ctrl_read_ready), + .status_read_data(audio_ctrl_cpu_read_data), + + .pcm_address_valid(pcm_read_en), + .pcm_read_address(pcm_read_address), + .pcm_data_ready(pcm_data_ready), + .pcm_read_data(flash_read_data[15:0]), + + .output_l(audio_output_l), + .output_r(audio_output_r), + .output_valid(audio_output_valid), + + .gb_write_busy(), + .gb_playing(), + .gb_ended() + ); + + /* verilator public_module */ + + // --- CPU RAM --- + + wire [31:0] cpu_ram_read_data; + + cpu_ram cpu_ram( + .clk(cpu_clk), + + .address(cpu_address_1x[15:2]), + .write_en(cpu_ram_write_en), + .cs(cpu_ram_en), + .wstrb(cpu_wstrb_1x), + .write_data(cpu_write_data_1x), + + .read_data(cpu_ram_read_data) + ); + + // --- Gamepad IO --- + + reg [1:0] pad_ctrl; + + assign pad_latch = pad_ctrl[0]; + assign pad_clk = pad_ctrl[1]; + + always @(posedge vdp_clk) begin + if (pad_write_en) begin + pad_ctrl <= cpu_write_data[1:0]; + end + end + + // --- Bus arbiter --- + + wire [31:0] cpu_address; + wire cpu_mem_valid; + wire [3:0] cpu_wstrb; + wire [31:0] cpu_write_data; + wire [31:0] cpu_read_data; + wire cpu_mem_ready; + + bus_arbiter #( + .SUPPORT_2X_CLK(!ENABLE_FAST_CPU), + .READ_SOURCES(`BA_VDP | `BA_FLASH | `BA_DSP | `BA_PAD | `BA_FLASH_CTRL | `BA_AUDIO) + ) bus_arbiter ( + .clk(vdp_clk), + + // Inputs + + .cpu_address(cpu_address), + .cpu_write_data(cpu_write_data), + .cpu_wstrb(cpu_wstrb), + + .bootloader_en(0), + .cpu_ram_en(0), + .vdp_en(vdp_en), + .flash_read_en(flash_read_en), + .dsp_en(dsp_en), + .status_en(status_en), + .pad_en(pad_en), + .cop_en(cop_ram_write_en), + .flash_ctrl_en(flash_ctrl_en), + .audio_ctrl_en(audio_ctrl_en), + + .flash_read_ready(flash_read_ready), + .vdp_ready(vdp_ready), + .audio_ready(audio_ctrl_ready), + + .bootloader_read_data(0), + .cpu_ram_read_data(0), + .flash_read_data(flash_read_data), + .dsp_read_data(dsp_result), + .vdp_read_data(vdp_read_data), + .pad_read_data({user_button, pad_data}), + .flash_ctrl_read_data(flash_ctrl_read_data), + .audio_cpu_read_data(audio_ctrl_cpu_read_data), + + // Outputs + + .cpu_mem_ready(cpu_mem_ready), + .cpu_read_data(cpu_read_data) + ); + + // --- CPU --- + + wire [31:0] cpu_address_1x; + wire [3:0] cpu_wstrb_1x; + wire cpu_mem_valid_1x; + wire [31:0] cpu_write_data_1x; + + wire [31:0] cpu_read_data_1x; + wire cpu_mem_ready_1x; + + // verilator lint_save + // verilator lint_off PINMISSING + + localparam CPU_RESET_PC = ENABLE_BOOTLOADER ? 32'h60000 : 32'h00000; + + generate + if (USE_VEXRISCV) begin + vexriscv_shared_bus vex_shared_bus( + .clk(cpu_clk), + .reset(cpu_reset), + + .mem_ready(cpu_mem_ready_1x), + .mem_valid(cpu_mem_valid_1x), + .mem_addr(cpu_address_1x), + .mem_rdata(cpu_read_data_1x), + .mem_wdata(cpu_write_data_1x), + .mem_wstrb(cpu_wstrb_1x) + ); + end else begin + picorv32 #( + .ENABLE_TRACE(0), + + // Register file gets inferred as BRAMs so using rv32e has little practical gain + .ENABLE_REGS_16_31(1), + + // MMIO DSP is used instead of the included PCPI implementation + .ENABLE_FAST_MUL(0), + + .PROGADDR_RESET(CPU_RESET_PC), + // SP defined by software + // .STACKADDR(32'h0001_0000), + + // Greatly helps shift speed but still an optional extra that could be removed + .TWO_STAGE_SHIFT(0), + + // Huge savings with this enabled + .TWO_CYCLE_ALU(1), + + // Moderate savings and not really expecting trouble with aligned C code + .CATCH_MISALIGN(0), + .CATCH_ILLINSN(0), + + // Neutral at best even with retiming? + .TWO_CYCLE_COMPARE(0), + + // rdcycle(h) instructions are not needed + .ENABLE_COUNTERS(0), + .ENABLE_COUNTERS64(0), + + // IRQ now disabled (vdp_copper to be used instead) + .ENABLE_IRQ(0), + .ENABLE_IRQ_QREGS(0), + .ENABLE_IRQ_TIMER(0) + ) pico ( + .clk(cpu_clk), + .resetn(!cpu_reset), + + .mem_ready(cpu_mem_ready_1x), + .mem_valid(cpu_mem_valid_1x), + .mem_addr(cpu_address_1x), + .mem_rdata(cpu_read_data_1x), + .mem_wdata(cpu_write_data_1x), + .mem_wstrb(cpu_wstrb_1x), + + .irq(0) + ); + end + endgenerate + + // verilator lint_restore + + // --- Flash IO --- + + assign flash_clk_ddr = flash_ctrl_active ? {2{flash_ctrl_clk}} : {1'b0, flash_dma_clk_en}; + wire flash_dma_clk_en; + + assign flash_in = flash_ctrl_active ? flash_ctrl_in : flash_dma_in; + assign flash_in_en = flash_ctrl_active ? flash_ctrl_in_en : flash_dma_in_en; + + assign flash_csn = flash_ctrl_active ? flash_ctrl_csn : flash_dma_csn; + + // --- Flash arbiter --- + + wire flash_read_ready; + wire [31:0] flash_read_data; + + wire flash_dma_clk, flash_dma_csn; + wire [3:0] flash_dma_in_en; + wire [3:0] flash_dma_in; + + flash_arbiter flash_arbiter( + .clk(vdp_clk), + .reset(vdp_reset), + + // Reader A: CPU + + .read_address_a({cpu_address[23:2], 2'b00}), + .read_en_a(flash_read_en), + .ready_a(flash_read_ready), + + // 32bit reads (full size) + .size_a(1), + + // Reader B: ADPCM DSP + + .read_address_b({pcm_read_address, 1'b0}), + .read_en_b(pcm_read_en), + .ready_b(pcm_data_ready), + + // 16bit reads + .size_b(0), + + // Flash read data + + .read_data(flash_read_data), + + // Flash interface + + .flash_clk_en(flash_dma_clk_en), + .flash_csn(flash_dma_csn), + .flash_in_en(flash_dma_in_en), + .flash_in(flash_dma_in), + + .flash_out(flash_out) + ); + + // --- Flash CPU control --- + + reg flash_ctrl_active; + + reg [3:0] flash_ctrl_in; + reg [3:0] flash_ctrl_in_en; + reg flash_ctrl_clk; + reg flash_ctrl_csn; + + wire flash_ctrl_active_data = cpu_write_data[15]; + wire [3:0] flash_ctrl_in_data = cpu_write_data[3:0]; + wire [3:0] flash_ctrl_in_en_data = cpu_write_data[7:4]; + wire flash_ctrl_clk_data = cpu_write_data[8]; + wire flash_ctrl_csn_data = cpu_write_data[9]; + + // It's expected that flash_out is registered in the parent module (SB_IO reg for iCE40) + wire [3:0] flash_ctrl_read_data = flash_out; + + always @(posedge vdp_clk) begin + if (vdp_reset) begin + flash_ctrl_clk <= 0; + flash_ctrl_in_en <= 0; + end + + if (flash_ctrl_write_en) begin + flash_ctrl_in <= flash_ctrl_in_data; + flash_ctrl_in_en <= flash_ctrl_in_en_data; + flash_ctrl_clk <= flash_ctrl_clk_data; + flash_ctrl_csn <= flash_ctrl_csn_data; + end + end + + always @(posedge vdp_clk) begin + if (vdp_reset) begin + flash_ctrl_active <= 0; + end else if (flash_ctrl_write_en) begin + flash_ctrl_active <= flash_ctrl_active_data; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ics_adpcm.v b/dan-rodrigues_icestation-32/hardware/ics_adpcm.v new file mode 100644 index 0000000000000000000000000000000000000000..a14d7b5f49c0d71772c8062175731a4913cc4e9d --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ics_adpcm.v @@ -0,0 +1,1104 @@ +// ics_adpcm.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module ics_adpcm #( + parameter integer OUTPUT_INTERVAL = 33700000 / 44100, + parameter [15:0] ADPCM_BLOCK_SIZE = 1024 * 2, // in nibbles + parameter [3:0] CHANNELS = 8, + parameter ADPCM_STEP_LUT_PATH = "adpcm_step_lut.hex", + + // Derived parameters: + // Verilog-2005 doesn't allow localparams to be used in port list although OSS tools allow it + parameter CHANNEL_MSB = CHANNELS - 1 +) ( + input clk, + input reset, + + // Channel register writing + + input [7:0] ch_write_address, + input [15:0] ch_write_data, + input ch_write_en, + input [1:0] ch_write_byte_mask, + output reg ch_write_ready, + + // Global register writing + + input [0:0] gb_write_address, + input [CHANNEL_MSB:0] gb_write_data, + input gb_write_en, + output reg gb_write_busy, + output reg gb_write_ready, + + // Status register reading + + input [1:0] status_read_address, + input status_read_request, + output reg status_read_ready, + output reg [CHANNEL_MSB:0] status_read_data, + + // Audio flags + + output reg [CHANNEL_MSB:0] gb_ended, + output reg [CHANNEL_MSB:0] gb_playing, + + // PCM memory interface + + output [22:0] pcm_read_address, + output reg pcm_address_valid, + input pcm_data_ready, + input [15:0] pcm_read_data, + + // Audio output + + output signed [15:0] output_l, + output signed [15:0] output_r, + output reg output_valid, + + // Debug + + output [15:0] dbg_adpcm_predictor, + output [6:0] dbg_adpcm_step_index, + output reg dbg_adpcm_valid +); + localparam LOG2_DIVISOR = $clog2(OUTPUT_INTERVAL); + localparam DIVIDER_BITS = LOG2_DIVISOR; + + localparam P_REG_READ_LATENCY = 1; + localparam REG_READ_LATENCY = 2; + + localparam ADPCM_BLOCK_WIDTH = $clog2(ADPCM_BLOCK_SIZE) - 1; + + // --- Debug --- + + assign dbg_adpcm_predictor = adpcm_predictor; + assign dbg_adpcm_step_index = adpcm_step_index; + + // --- Output clock divider --- + + reg [DIVIDER_BITS: 0] output_counter; + wire output_ready = {{31 - DIVIDER_BITS{1'b0}}, output_counter} == OUTPUT_INTERVAL; + + always @(posedge clk) begin + if (reset || output_ready) begin + output_counter <= 0; + end else begin + output_counter <= output_counter + 1; + end + end + + // --- Output --- + + // Accumulators: + + // If 2x hard multipliers were free, these accumulators could just stay in the MAC instances + // This would mean these extra FFs aren't needed, but since only 1 multiplier is used, can't do that here + + reg [22:0] gb_level_l, gb_level_r; + + // Final truncation of the output happens here + // When mixing all the channels, the lower 7 fraction bits are preserved to help with accuracy + + wire acc_start = state_changed_to(STATE_CH_VOLUME); + + assign output_l = gb_level_l[22:7]; + assign output_r = gb_level_r[22:7]; + + reg acc_add_left; + reg acc_add_right; + + always @(posedge clk) begin + acc_add_left <= acc_start; + acc_add_right <= 0; + + if (output_valid) begin + gb_level_l <= 0; + gb_level_r <= 0; + end else if (acc_add_left) begin + gb_level_l <= mac_result_clipped; + acc_add_right <= 1; + end else if (acc_add_right) begin + gb_level_r <= mac_result_clipped; + end + end + + // Shared MAC: + + // It's expected that REG_VOLUME data is available by the time this is used + + always @(posedge clk) begin + if (acc_start) begin + mult_volume <= reg_read_data[7:0]; + mac_add <= gb_level_l; + end else begin + mult_volume <= reg_read_data[15:8]; + mac_add <= gb_level_r; + end + + mult_sample <= adpcm_predictor; + end + + reg signed [22:0] mac_add; + reg signed [7:0] mult_volume; + reg signed [15:0] mult_sample; + reg signed [23:0] mac_result; + + reg signed [22:0] mac_result_clipped; + + always @* begin + case (overflow(mac_result[23:22])) + OVERFLOW_NEGATIVE: mac_result_clipped = 23'h400000; + OVERFLOW_POSITIVE: mac_result_clipped = 23'h3fffff; + default: mac_result_clipped = mac_result[22:0]; + endcase + end + + always @* begin + mac_result = mult_volume * mult_sample + mac_add; + end + + // --- Registered inputs for writes --- + + reg [7:0] ch_write_address_r; + reg [15:0] ch_write_data_r; + reg ch_write_en_r, gb_write_en_r; + + reg [0:0] gb_write_address_r; + + wire regs_has_contention = reg_write_address == reg_read_address; + + always @(posedge clk) begin + ch_write_address_r <= ch_write_address; + ch_write_data_r <= ch_write_data; + ch_write_en_r <= ch_write_en; + + gb_write_address_r <= gb_write_address[0]; + gb_write_en_r <= gb_write_en; + end + + // --- Global registers --- + + // Writes: + + reg [CHANNEL_MSB:0] gb_start, gb_stop; + + always @(posedge clk) begin + if (reset || output_ready) begin + gb_start <= 0; + gb_stop <= 0; + + gb_write_busy <= 0; + end + + // These writes take precedence over the reset above + + if (gb_write_en_r) begin + case (gb_write_address_r[0]) + 0: gb_start <= gb_write_data[CHANNEL_MSB:0]; + 1: gb_stop <= gb_write_data[CHANNEL_MSB:0]; + endcase + + gb_write_busy <= 1; + end + end + + // Reads: + + reg [1:0] status_read_address_r; + + reg status_read_request_r; + wire status_read_request_rose = !status_read_request_r && status_read_request; + reg status_read_ready_d; + + always @(posedge clk) begin + status_read_address_r <= status_read_address; + status_read_request_r <= status_read_request; + end + + // Delay status_read_ready by 2 cycles + + always @(posedge clk) begin + status_read_ready_d <= status_read_request_rose; + status_read_ready <= status_read_ready_d; + end + + // Status read addresses: + // - 0: gb_playing + // - 1: gb_ended + // - 2/3: gb_write_busy on bit0, rest undefined + + always @(posedge clk) begin + status_read_data <= status_read_address_r[0] ? gb_ended : gb_playing; + + // Only add extra mux on bit0 + if (status_read_address_r[1]) begin + status_read_data[0] <= gb_write_busy; + end + end + + // Channel trigger shift register copy for FSM + + wire ch_complete = (state == STATE_CH_COMPLETE); + + reg [CHANNEL_MSB:0] gb_start_shift, gb_stop_shift; + wire gb_start_current = gb_start_shift[0]; + wire gb_stop_shift_current = gb_stop_shift[0]; + + always @(posedge clk) begin + if (reset) begin + gb_stop_shift <= {CHANNELS{1'b1}}; + gb_start_shift <= 0; + end if (output_ready) begin + gb_start_shift <= gb_start; + gb_stop_shift <= gb_stop; + end else if (ch_complete) begin + gb_stop_shift <= gb_stop_shift >> 1; + gb_start_shift <= gb_start_shift >> 1; + end + end + + // Channel start/end states + + wire ch_last = (ch == (CHANNELS - 1)); + + reg [CHANNEL_MSB:0] gb_ended_shift, gb_started_shift, gb_playing_shift; + reg gb_playing_current; + + always @(posedge clk) begin + if (reset) begin + gb_ended <= 0; + gb_playing <= 0; + end else if (output_ready) begin + gb_ended <= (gb_ended | gb_ended_shift) & ~gb_started_shift; + gb_ended_shift <= 0; + gb_started_shift <= 0; + + gb_playing <= gb_playing_shift; + gb_playing_shift <= 0; + end else if (ch_complete && !ch_last) begin + gb_ended_shift <= gb_ended_shift >> 1; + gb_started_shift <= gb_started_shift >> 1; + gb_playing_shift <= gb_playing_shift >> 1; + end else begin + gb_ended_shift[CHANNEL_MSB] <= gb_ended_shift[CHANNEL_MSB] | ch_ended; + gb_started_shift[CHANNEL_MSB] <= gb_started_shift[CHANNEL_MSB] | gb_start_current; + gb_playing_shift[CHANNEL_MSB] <= gb_playing_shift[CHANNEL_MSB] | gb_playing_current; + end + end + + // --- Public RAM --- + + // Register file: + + localparam [2:0] + REG_START = 0, + REG_FLAGS = 1, + REG_END = 2, + REG_LOOP = 3, + REG_VOLUMES = 4, + REG_PITCH = 5; + + reg [15:0] regs [0:255]; + + reg regs_read_en; + + always @* begin + case (state) + STATE_CTRL_CHECK, STATE_CTRL_DONE, STATE_CH_VOLUME, + STATE_ADPCM_WAIT_INIT_INDEX, STATE_ADPCM_WAIT_INIT_PREDICTOR, STATE_ADPCM_COMPUTE_DIFF, + STATE_ADPCM_COMPLETE_STEP: + regs_read_en = 1; + default: + regs_read_en = 0; + endcase + end + + // Read / Write: + + wire [7:0] reg_read_address = {1'b0, ch, regs_index}; + wire [7:0] reg_write_address = ch_write_address_r; + reg [15:0] reg_read_ram_output; + reg [15:0] reg_read_data; + + always @(posedge clk) begin + if (ch_write_en_r && !(regs_read_en && regs_has_contention)) begin + if (ch_write_byte_mask[0]) begin + regs[reg_write_address][7:0] <= ch_write_data_r[7:0]; + end + if (ch_write_byte_mask[1]) begin + regs[reg_write_address][15:8] <= ch_write_data_r[15:8]; + end + end + + // This extra stage is needed to help timing + // Otherwise the below FSM ends up in the critical path + reg_read_ram_output <= regs[reg_read_address]; + reg_read_data <= reg_read_ram_output; + end + + // Delay the write acknowledge incase the write was prevented to avoid contention + + reg regs_write_pending; + reg regs_write_en_d, gb_regs_write_en_d; + + wire regs_written = !(regs_read_en && regs_has_contention) && regs_write_pending; + wire regs_write_en_rose = (!regs_write_en_d && ch_write_en_r); + wire gb_regs_write_en_rose = (!gb_regs_write_en_d && gb_write_en_r); + + always @(posedge clk) begin + regs_write_pending <= (regs_write_en_rose || regs_write_pending) && !regs_written; + + regs_write_en_d <= ch_write_en_r; + gb_regs_write_en_d <= gb_write_en_r; + end + + always @(posedge clk) begin + if (reset) begin + ch_write_ready <= 0; + end else if (ch_write_en_r) begin + // Active for a single cycle only + ch_write_ready <= regs_written; + end else begin + ch_write_ready <= 0; + end + end + + always @(posedge clk) begin + gb_write_ready <= gb_regs_write_en_rose; + end + + // --- Private RAM --- + + // Register file: + + localparam [1:0] + P_REG_PCM_INDEX_LO = 0, + P_REG_PCM_INDEX_HI = 1, + P_REG_ADPCM_PREDICTOR = 2, + P_REG_PCM_INDEX_MID = 3; + + localparam + CH_CTRL_P_PLAYING = 0; + + reg [15:0] p_regs [0:255]; + + // Bottom 2 bits used for address + // MSB used in FSM below + reg [2:0] p_regs_index; + + reg p_reg_write_en; + reg [1:0] p_regs_write_index; + wire [7:0] p_regs_write_address = {2'b0, ch, p_regs_write_index[1:0]}; + + wire [7:0] p_regs_address = {2'b0, ch, p_regs_index[1:0]}; + reg [15:0] p_reg_read_data, p_reg_write_data; + + // Both the ADPCM step index LUT and the private register file are stored in this RAM + wire [7:0] p_reg_read_address = adpcm_needs_step_lut ? {1'b1, adpcm_step_index[6:0]} : p_regs_address; + + always @(posedge clk) begin + if (p_reg_write_en) begin + p_regs[p_regs_write_address] <= p_reg_write_data; + end + + p_reg_read_data <= p_regs[p_reg_read_address]; + end + + // Writes: + + reg p_regs_writing; + reg p_regs_write_complete; + wire p_regs_start_writing = state_changed_to(STATE_CH_VOLUME); + + wire [1:0] p_regs_index_writing_offset = p_regs_write_index + 1; + + always @(posedge clk) begin + p_regs_write_complete <= 0; + p_reg_write_en <= p_regs_writing; + + case (p_regs_index_writing_offset) + P_REG_PCM_INDEX_LO: p_reg_write_data <= pcm_target_index[15:0]; + P_REG_PCM_INDEX_HI: p_reg_write_data <= pcm_target_index[31:16]; + P_REG_ADPCM_PREDICTOR: p_reg_write_data <= adpcm_predictor; + + P_REG_PCM_INDEX_MID: begin + p_reg_write_data[4:0] <= pcm_target_index[36:32]; + p_reg_write_data[5] <= ch_ctrl_p[CH_CTRL_P_PLAYING]; + p_reg_write_data[14:8] <= adpcm_step_index; + + p_regs_writing <= 0; + p_regs_write_complete <= p_regs_writing; + end + endcase + + if (p_regs_start_writing) begin + p_regs_writing <= 1; + p_regs_write_index <= -1; + end else begin + p_regs_write_index <= p_regs_write_index + 1; + end + + if (reset) begin + p_regs_writing <= 0; + p_reg_write_en <= 0; + end + end + + // ADPCM step LUT: + + reg adpcm_needs_step_lut; + + always @* begin + case (state) + STATE_ADPCM_COMPUTE_DIFF, STATE_READ_WAIT, STATE_ADPCM_PREPARE_COMPUTE_DIFF, + STATE_ADPCM_COMPLETE_STEP, STATE_ADPCM_STORE_DIFF: + adpcm_needs_step_lut = 1; + default: + adpcm_needs_step_lut = 0; + endcase + end + + // The 89 defined entries are loaded in the latter half of the RAM used for the private register file + + initial begin + $readmemh(ADPCM_STEP_LUT_PATH, p_regs, 128, 128 + 88); + end + + // The MSB is used to flag index as out-of-bounds + // The lower 7 bits contains the replacement step index + + genvar i; + generate + for (i = 128 + 89; i < 255; i = i + 1) begin + initial begin + p_regs[i] = 16'h8000 + 88; + end + end + endgenerate + + initial begin + p_regs[255] = 16'h8000 + 0; + end + + // --- Channel FSM --- + + localparam [3:0] + STATE_LOAD_REGS = 0, + STATE_REG_SETUP = 1, + STATE_CTRL_CHECK = 2, + STATE_ADPCM_PREPARE_COMPUTE_DIFF = 3, + STATE_READ_WAIT = 4, + STATE_CH_VOLUME = 5, + STATE_CH_LOOP = 6, + STATE_CH_COMPLETE = 7, + STATE_ADPCM_STORE_DIFF = 8, + STATE_OUTPUT_WAIT = 9, + STATE_ADPCM_WAIT_INIT_PREDICTOR = 13, + STATE_ADPCM_WAIT_INIT_INDEX = 14, + STATE_CTRL_DONE = 15, + STATE_ADPCM_COMPUTE_DIFF = 11, + STATE_CH_ENDED = 12, + STATE_ADPCM_COMPLETE_STEP = 10; + + reg [3:0] ch; + reg [3:0] state; + + // One-hot friendly state change tracking + // This shouldn't prevent yosys from extracting the FSM + + reg [15:0] state_previous_mask; + + integer state_index; + always @(posedge clk) begin + for (state_index = 0; state_index < 16; state_index = state_index + 1) begin + state_previous_mask[state_index[3:0]] <= (state == state_index[3:0]); + end + end + + // --- + + reg [0:0] ch_ctrl_p; + + localparam + CH_CTRL_LOOP = 0, + CH_CTRL_ADPCM = 1; + + reg [2:0] regs_index; + + // --- Sample indexing --- + + // Index format: + // - 25 bits integer sample index + // - 12 bits fraction + + reg [36:0] pcm_target_index; + reg pcm_target_index_16_preadd; + + // Target address is reached when stepping index catches up to the target + reg pcm_target_address_reached; + + reg [24:0] pcm_stepping_index; + assign pcm_read_address = pcm_stepping_index[24:2]; + + wire block_starting = gb_start_current || adpcm_block_ended; + + reg [13:0] end_block, loop_block; + reg end_block_reached; + reg adpcm_block_ended; + + // Register anything involving big comparators to aid timing + + always @(posedge clk) begin + pcm_target_address_reached <= pcm_stepping_index == pcm_target_index[36:12]; + end_block_reached <= (end_block == pcm_stepping_index[24:ADPCM_BLOCK_WIDTH + 1]); + adpcm_block_ended <= pcm_stepping_index[ADPCM_BLOCK_WIDTH:0] == 0; + end + + // --- PCM data registering --- + + reg [15:0] pcm_read_data_r; + reg pcm_data_ready_r; + + // Max sample step is 16, which spans 4 words + // 2bits + 1bit carry = 3bits required for a comparator to see if registered word is still valid + + reg [2:0] pcm_stepping_index_previous_word; + wire pcm_registered_data_valid = pcm_stepping_index[4:2] == pcm_stepping_index_previous_word; + + always @(posedge clk) begin + pcm_data_ready_r <= pcm_data_ready && pcm_address_valid; + + if (pcm_address_valid) begin + pcm_read_data_r <= pcm_read_data; + end + end + + // --- ADPCM state --- + + reg [15:0] adpcm_predictor; + reg [6:0] adpcm_step_index; + + // Select which 4bit ADPCM nybble is to be used + + reg [3:0] adpcm_nybble; + wire adpcm_nybble_sign = adpcm_nybble[3]; + + always @* begin + case (pcm_stepping_index[1:0]) + 0: adpcm_nybble = pcm_read_data_r[3:0]; + 1: adpcm_nybble = pcm_read_data_r[7:4]; + 2: adpcm_nybble = pcm_read_data_r[11:8]; + 3: adpcm_nybble = pcm_read_data_r[15:12]; + endcase + end + + // --- ADPCM predictor --- + + reg [15:0] adpcm_diff; + + // Predictor diff shift-and-add: + + // Shift-and-add to implement this: + // adpcm_diff = (adpcm_nybble + 0.5) * step / 4 + + wire adpcm_diff_preload = state == STATE_ADPCM_PREPARE_COMPUTE_DIFF; + wire adpcm_diff_compute_complete = adpcm_nybble_shift == 0; + + always @(posedge clk) begin + if (adpcm_diff_preload) begin + adpcm_nybble_shift <= adpcm_nybble[2:0]; + adpcm_step_shift <= adpcm_step; + end else begin + adpcm_nybble_shift <= adpcm_nybble_shift << 1; + adpcm_step_shift <= adpcm_step_shift >> 1; + end + end + + always @(posedge clk) begin + if (adpcm_diff_preload) begin + adpcm_diff <= {1'b0, adpcm_step} >> 3; + end else if (adpcm_nybble_shift[2]) begin + adpcm_diff <= adpcm_diff + adpcm_step_shift; + end + end + + reg [15:0] adpcm_predictor_nx; + reg [16:0] adpcm_predictor_updated_no_clip; + + always @(posedge clk) begin + if (adpcm_nybble_sign) begin + adpcm_predictor_updated_no_clip <= $signed(adpcm_predictor) - $signed(adpcm_diff); + end else begin + adpcm_predictor_updated_no_clip <= $signed(adpcm_predictor) + $signed(adpcm_diff); + end + end + + // Predictor clipping: + + always @* begin + case (overflow(adpcm_predictor_updated_no_clip[16:15])) + OVERFLOW_NEGATIVE: adpcm_predictor_nx = 16'h8000; + OVERFLOW_POSITIVE: adpcm_predictor_nx = 16'h7fff; + default: adpcm_predictor_nx = adpcm_predictor_updated_no_clip[15:0]; + endcase + end + + // Shift-and-add state for computing the diff + + reg [2:0] adpcm_nybble_shift; + reg [14:0] adpcm_step_shift; + wire [14:0] adpcm_step = p_reg_read_data[14:0]; + + // --- ADPCM step index --- + + reg [6:0] adpcm_step_index_updated_no_clip; + reg adpcm_step_index_needs_clipping; + + always @* begin + adpcm_step_index_updated_no_clip = adpcm_step_delta + adpcm_step_index; + + if (p_reg_read_data[15]) begin + adpcm_step_index_needs_clipping = 1; + end else begin + adpcm_step_index_needs_clipping = 0; + end + end + + // Step delta + + reg [6:0] adpcm_step_delta; + + always @(posedge clk) begin + adpcm_step_delta <= adpcm_nybble[2] ? (({5'b0, adpcm_nybble[1:0]} + 1) << 1) : -1; + end + + // STATE_CTRL_CHECK: + + reg loop_check_needed; + reg ch_ended; + + // STATE_CH_ENDED: + + reg ctrl_complete; + + // STATE_LOAD_REGS: + + wire [2:0] regs_index_loading_offset = (p_regs_index - P_REG_READ_LATENCY); + wire regs_index_loading_complete = regs_index_loading_offset == {1'b0, P_REG_PCM_INDEX_MID}; + + always @(posedge clk) begin + output_valid <= 0; + + ctrl_complete <= 0; + ch_ended <= 0; + gb_playing_current <= 0; + + dbg_adpcm_valid <= 0; + + case (state) + STATE_LOAD_REGS: begin + p_regs_index <= p_regs_index + 1; + + case (regs_index_loading_offset[1:0]) + P_REG_PCM_INDEX_LO: pcm_target_index[15:0] <= p_reg_read_data; + P_REG_PCM_INDEX_HI: pcm_target_index[31:16] <= p_reg_read_data; + P_REG_ADPCM_PREDICTOR: adpcm_predictor <= p_reg_read_data; + + P_REG_PCM_INDEX_MID: begin + pcm_target_index[36:32] <= p_reg_read_data[4:0]; + ch_ctrl_p <= p_reg_read_data[5]; + adpcm_step_index <= p_reg_read_data[14:8]; + end + endcase + + if (regs_index_loading_complete) begin + regs_index <= 0; + state <= STATE_REG_SETUP; + end + end + STATE_REG_SETUP: begin + // Early exit if channel isn't playing + if (!ch_ctrl_p[CH_CTRL_P_PLAYING] && !gb_start_current) begin + state <= STATE_CH_COMPLETE; + end + + if (regs_index == (REG_READ_LATENCY - 1)) begin + state <= STATE_CTRL_CHECK; + end + + regs_index <= regs_index + 1; + + gb_playing_current <= ch_ctrl_p[CH_CTRL_P_PLAYING]; + end + STATE_CTRL_CHECK: begin + case (output_reg_offset(regs_index)) + REG_START: begin + if (gb_start_current) begin + pcm_target_index[11:0] <= 0; + pcm_target_index[ADPCM_BLOCK_WIDTH + 12:12] <= 0; + pcm_target_index[36:ADPCM_BLOCK_WIDTH + 12 + 1] <= reg_read_data[13:0]; + + ch_ctrl_p[CH_CTRL_P_PLAYING] <= 1; + + // Early exit if channel just started, regs below aren't used in first pass + ctrl_complete <= 1; + end + end + REG_FLAGS: begin + loop_check_needed <= reg_read_data[CH_CTRL_LOOP]; + + // Stepping index, used for addressing, must be copied before any pitch adjustment + pcm_stepping_index <= pcm_target_index[36:12]; + end + REG_END: begin + end_block <= reg_read_data[13:0]; + end + REG_LOOP: begin + loop_block <= reg_read_data[13:0]; + end + REG_PITCH: begin + // Carry out must be split due to at 37bit carry chain failing timing + pcm_target_index[16:0] <= pcm_target_index[16:0] + {1'b0, reg_read_data}; + pcm_target_index_16_preadd <= pcm_target_index[16]; + + // The below carry adjust will be handled regardless + ctrl_complete <= 1; + end + REG_PITCH + 1: begin + if (pcm_target_index_16_preadd && !pcm_target_index[16]) begin + pcm_target_index[36:17] <= pcm_target_index[36:17] + 1; + end + end + endcase + + if (gb_stop_shift_current) begin + ch_ctrl_p[CH_CTRL_P_PLAYING] <= 0; + ch_ended <= 1; + ctrl_complete <= 1; + end + + regs_index <= regs_index + 1; + + if (ctrl_complete) begin + regs_index <= REG_VOLUMES; + state <= STATE_CTRL_DONE; + end + end + STATE_CTRL_DONE: begin + if (ch_ctrl_p[CH_CTRL_P_PLAYING]) begin + pcm_address_valid <= 1; + + if (block_starting) begin + state <= STATE_ADPCM_WAIT_INIT_PREDICTOR; + end else if (pcm_target_address_reached) begin + pcm_address_valid <= 0; + // No step? Skip straight to volume output + // !state_changed is required because an extra cycle is needed for the register read + if (!state_changed_to(STATE_CTRL_DONE)) begin + state <= STATE_CH_VOLUME; + end + end else begin + state <= STATE_READ_WAIT; + end + end else begin + // Channel state is written back as part of this step + // This is needed to cover the case of ch_ctrl_p being updated to stop channel + state <= STATE_CH_VOLUME; + end + end + STATE_ADPCM_WAIT_INIT_PREDICTOR: begin + adpcm_predictor <= pcm_read_data_r; + + if (pcm_data_ready_r) begin + // Both stepping and target index are advanced when reading ADPCM headers + // Needed because header bytes are not factored into the pitch (playback rate) + pcm_stepping_index[2] <= 1; + pcm_target_index[36:14] <= pcm_target_index[36:14] + 1; + + // Signal to PCM memory controller that another word is needed + pcm_address_valid <= 0; + + state <= STATE_ADPCM_WAIT_INIT_INDEX; + end + end + STATE_ADPCM_WAIT_INIT_INDEX: begin + pcm_address_valid <= 1; + + adpcm_step_index <= pcm_read_data_r[6:0]; + + if (pcm_data_ready_r && !state_changed_to(STATE_ADPCM_WAIT_INIT_INDEX)) begin + pcm_stepping_index[3:2] <= 2'b10; + pcm_target_index[36:14] <= pcm_target_index[36:14] + 1; + + pcm_address_valid <= 0; + + state <= pcm_target_address_reached ? STATE_CH_VOLUME : STATE_READ_WAIT; + end + end + STATE_READ_WAIT: begin + pcm_address_valid <= 1; + + if (pcm_data_ready_r && !state_changed_to(STATE_READ_WAIT)) begin + pcm_address_valid <= 0; + state <= STATE_ADPCM_PREPARE_COMPUTE_DIFF; + end + end + STATE_ADPCM_PREPARE_COMPUTE_DIFF: begin + // Preparaton to update step index: + // It may be out of bounds here but will be corrected in a later state + adpcm_step_index <= adpcm_step_index_updated_no_clip; + + state <= STATE_ADPCM_COMPUTE_DIFF; + end + STATE_ADPCM_COMPUTE_DIFF: begin + if (adpcm_diff_compute_complete) begin + // Prepare stepping address for check next state (1 sample advanced) + pcm_stepping_index <= pcm_stepping_index + 1; + pcm_stepping_index_previous_word <= pcm_stepping_index[4:2]; + + state <= STATE_ADPCM_STORE_DIFF; + end + end + STATE_ADPCM_STORE_DIFF: begin + adpcm_predictor <= adpcm_predictor_nx; + + state <= STATE_ADPCM_COMPLETE_STEP; + end + STATE_ADPCM_COMPLETE_STEP: begin + // Clip step index if it is out of bounds + if (adpcm_step_index_needs_clipping) begin + adpcm_step_index <= p_reg_read_data[6:0]; + end + + dbg_adpcm_valid <= 1; + + // End-state checking and looping if needed: + + if (end_block_reached) begin + state <= loop_check_needed ? STATE_CH_LOOP : STATE_CH_ENDED; + end else if (!pcm_target_address_reached) begin + if (block_starting) begin + pcm_address_valid <= 1; + state <= STATE_ADPCM_WAIT_INIT_PREDICTOR; + end else if (pcm_registered_data_valid) begin + state <= STATE_ADPCM_PREPARE_COMPUTE_DIFF; + end else begin + pcm_address_valid <= 1; + state <= STATE_READ_WAIT; + end + end else begin + state <= STATE_CH_VOLUME; + end + end + STATE_CH_LOOP: begin + // PCM must catch up to stepping index, so reset in-block index to 0 + // Loop address must always point to start of ADPCM block + pcm_stepping_index[ADPCM_BLOCK_WIDTH:0] <= 0; + pcm_stepping_index[24:ADPCM_BLOCK_WIDTH + 1] <= loop_block; + + pcm_target_index[36:ADPCM_BLOCK_WIDTH + 12 + 1] <= loop_block; + + pcm_address_valid <= 1; + state <= STATE_ADPCM_WAIT_INIT_PREDICTOR; + end + STATE_CH_ENDED: begin + // Finished for case: sample end reached and loop not enabled + // This case may also be hit even if the channel isn't even playing + // ...but this has no unwanted side effects and avoids the logic cost of nesting this + ch_ctrl_p[CH_CTRL_P_PLAYING] <= 0; + + // Only mark it as ended if the channel actually *was* playing + ch_ended <= ch_ctrl_p[CH_CTRL_P_PLAYING]; + + state <= STATE_CH_VOLUME; + end + STATE_CH_VOLUME: begin + // Write back channel state in the meantime + if (p_regs_write_complete) begin + state <= STATE_CH_COMPLETE; + end + end + STATE_CH_COMPLETE: begin + p_regs_index <= 0; + ch <= ch + 1; + + state <= ch_last ? STATE_OUTPUT_WAIT : STATE_LOAD_REGS; + end + STATE_OUTPUT_WAIT: begin + ch <= 0; + + // Wait until a sample interval has passed before marking outputs as valid + if (output_ready) begin + state <= STATE_LOAD_REGS; + output_valid <= 1; + end + end + default: begin +`ifndef SYNTHESIS + $display("ADPCM DSP: Unhandled state"); + $stop; +`endif + end + endcase + + if (reset) begin + state <= STATE_LOAD_REGS; + p_regs_index <= 0; + regs_index <= 0; + ch <= 0; + output_valid <= 0; + pcm_address_valid <= 0; + + dbg_adpcm_valid <= 0; + end + end + + // --- Convenience functions --- + + localparam [1:0] + OVERFLOW_NONE = 2'b00, + OVERFLOW_POSITIVE = 2'b10, + OVERFLOW_NEGATIVE = 2'b11; + + function [1:0] overflow; + input [1:0] carry_sign; + + case (carry_sign) + 2'b01: overflow = OVERFLOW_POSITIVE; + 2'b10: overflow = OVERFLOW_NEGATIVE; + default: overflow = OVERFLOW_NONE; + endcase + endfunction + + function [2:0] output_reg_offset; + input [2:0] index; + + output_reg_offset = ((index - REG_READ_LATENCY) & 3'b111); + endfunction + + function [0:0] state_changed_to; + input [3:0] new_state; + + state_changed_to = !state_previous_mask[new_state] && (state == new_state); + endfunction + +`ifdef FORMAL + + integer valid_counter = 0; + wire past_valid = valid_counter != 0; + + initial begin + assume(reset); + end + + genvar i; + for (i = 0; i < 256; i = i + 1) begin + initial begin + regs[i] = 0; + end + end + + always @(posedge clk) begin + if (past_valid) begin + assume(!reset); + + // PCM data doesn't influence the assertions here so remove it from the search space + assume(pcm_data_ready); + assume(pcm_read_data == 0); + end + + valid_counter <= valid_counter + 1; + end + + always @(posedge clk) begin + if (past_valid) begin + assert(output_counter <= OUTPUT_INTERVAL); + end + end + + always @(posedge clk) begin + if (valid_counter > 2) begin + // If a global reg is written in same cycle as its normally cleared.. + if ($past(output_ready) && $past(gb_write_en_r)) begin + // ..the written data should persist + case ($past(ch_write_address[1:0])) + 0: assert(gb_start == $past(gb_write_data[CHANNEL_MSB:0])); + 1: assert(gb_stop == $past(gb_write_data[CHANNEL_MSB:0])); + endcase + + // ..busy flag should be set rather than being cleared in the same cycle + assert(gb_write_busy); + end + + // If a global reg is written.. + if ($past(gb_write_en_r)) begin + // ..busy flag should be set + assert(gb_write_busy); + end + + // If there was contention.. + if ($past(regs_has_contention) && $past(ch_write_en_r) && $past(regs_read_en)) begin + // ..then the write should be deferred + + assert($past(regs[ch_write_address_r]) == regs[$past(ch_write_address_r)]); + + // ..then the ready flag should not be set as the write is being deferred + assert(!ch_write_ready); + end + + // If there isn't contention during a write.. + if ($past(!regs_has_contention) && $past(ch_write_en_r) && $past(regs_write_pending)) begin + // ..then the write shouldn't be deferred + assert(ch_write_ready); + end + + // If there was a write, the byte mask should be respected + if ($past(ch_write_en_r) && $past(!regs_has_contention)) begin + case ($past(ch_write_byte_mask)) + 2'b00: begin + assert($past(regs[ch_write_address_r]) == regs[$past(ch_write_address_r)]); + end + 2'b01: begin + assert(($past(regs[ch_write_address_r]) & 16'hff00) == (regs[$past(ch_write_address_r)] & 16'hff00)); + assert(($past(ch_write_data_r) & 16'h00ff) == (regs[$past(ch_write_address_r)] & 16'h00ff)); + end + 2'b10: begin + assert(($past(regs[ch_write_address_r]) & 16'h00ff) == (regs[$past(ch_write_address_r)] & 16'h00ff)); + assert(($past(ch_write_data_r) & 16'hff00) == (regs[$past(ch_write_address_r)] & 16'hff00)); + end + 2'b11: begin + assert($past(ch_write_data_r) == regs[$past(ch_write_address_r)]); + end + endcase + end + + // If there was neither a channel write.. + if ($past(!ch_write_en_r)) begin + // ..the ready flag should be clear + assert(!ch_write_ready); + end + + // If a status read was just requested.. + if ($past(status_read_request) && $past(!status_read_request, 2) && $past(!status_read_request, 3)) begin + // ..the ready flag should be 0 as it needs to be delayed 2 cycles + assert(!status_read_ready); + end + + // If a status read was previously requested.. + if ($past(status_read_request, 2) && $past(!status_read_request, 3) && $past(!status_read_request, 4)) begin + // ..the ready flag should now be set + assert(status_read_ready); + end + + // If... + end + end + +`endif + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/layer_encoding.vh b/dan-rodrigues_icestation-32/hardware/layer_encoding.vh new file mode 100644 index 0000000000000000000000000000000000000000..6db5eefba59909f25cdd5b59e68a931e74ebeba6 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/layer_encoding.vh @@ -0,0 +1,16 @@ +`ifndef layer_encoding_vh +`define layer_encoding_vh + +`define LAYER_SPRITES 4 +`define LAYER_SCROLL3 3 +`define LAYER_SCROLL2 2 +`define LAYER_SCROLL1 1 +`define LAYER_SCROLL0 0 + +`define LAYER_SPRITES_OHE (1 << 4) +`define LAYER_SCROLL3_OHE (1 << 3) +`define LAYER_SCROLL2_OHE (1 << 2) +`define LAYER_SCROLL1_OHE (1 << 1) +`define LAYER_SCROLL0_OHE (1 << 0) + +`endif diff --git a/dan-rodrigues_icestation-32/hardware/mock_gamepad.v b/dan-rodrigues_icestation-32/hardware/mock_gamepad.v new file mode 100644 index 0000000000000000000000000000000000000000..e401faf9c283682dbc212d59f6c0446ebbbc7566 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/mock_gamepad.v @@ -0,0 +1,44 @@ +// mock_gamepad.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module mock_gamepad( + input clk, + + // Parallel button inputs + + input [11:0] pad_btn, + + // Serial control + + input pad_clk, + input pad_latch, + + // Serial out + + output [1:0] pad_out +); + reg pad_clk_r; + reg [11:0] pad_shift; + + // P1 reading only for now + assign pad_out[0] = pad_shift[0]; + assign pad_out[1] = 1'b0; + + always @(posedge clk) begin + if (pad_latch) begin + pad_shift <= pad_btn; + end + + if (pad_clk && !pad_clk_r) begin + pad_shift <= pad_shift >> 1; + end + + pad_clk_r <= pad_clk; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/picorv32.v b/dan-rodrigues_icestation-32/hardware/picorv32.v new file mode 100644 index 0000000000000000000000000000000000000000..62e777029477d5d53667f0d5d76517f4ea8da2c6 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/picorv32.v @@ -0,0 +1,3043 @@ +/* + * PicoRV32 -- A Small RISC-V (RV32I) Processor Core + * + * Copyright (C) 2015 Clifford Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +/* verilator lint_off WIDTH */ +/* verilator lint_off PINMISSING */ +/* verilator lint_off CASEOVERLAP */ +/* verilator lint_off CASEINCOMPLETE */ + +`timescale 1 ns / 1 ps +// `default_nettype none +// `define DEBUGNETS +// `define DEBUGREGS +// `define DEBUGASM +// `define DEBUG + +`ifdef DEBUG + `define debug(debug_command) debug_command +`else + `define debug(debug_command) +`endif + +`ifdef FORMAL + `define FORMAL_KEEP (* keep *) + `define assert(assert_expr) assert(assert_expr) +`else + `ifdef DEBUGNETS + `define FORMAL_KEEP (* keep *) + `else + `define FORMAL_KEEP + `endif + `define assert(assert_expr) empty_statement +`endif + +// uncomment this for register file in extra module +// `define PICORV32_REGS picorv32_regs + +// this macro can be used to check if the verilog files in your +// design are read in the correct order. +`define PICORV32_V + + +/*************************************************************** + * picorv32 + ***************************************************************/ + +module picorv32 #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] LATCHED_MEM_RDATA = 0, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output reg trap, + + output reg mem_valid, + output reg mem_instr, + input mem_ready, + + output reg [31:0] mem_addr, + output reg [31:0] mem_wdata, + output reg [ 3:0] mem_wstrb, + input [31:0] mem_rdata, + + // Look-Ahead Interface + output mem_la_read, + output mem_la_write, + output [31:0] mem_la_addr, + output reg [31:0] mem_la_wdata, + output reg [ 3:0] mem_la_wstrb, + + // Pico Co-Processor Interface (PCPI) + output reg pcpi_valid, + output reg [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ Interface + input [31:0] irq, + output reg [31:0] eoi, + +`ifdef RISCV_FORMAL + output reg rvfi_valid, + output reg [63:0] rvfi_order, + output reg [31:0] rvfi_insn, + output reg rvfi_trap, + output reg rvfi_halt, + output reg rvfi_intr, + output reg [ 1:0] rvfi_mode, + output reg [ 1:0] rvfi_ixl, + output reg [ 4:0] rvfi_rs1_addr, + output reg [ 4:0] rvfi_rs2_addr, + output reg [31:0] rvfi_rs1_rdata, + output reg [31:0] rvfi_rs2_rdata, + output reg [ 4:0] rvfi_rd_addr, + output reg [31:0] rvfi_rd_wdata, + output reg [31:0] rvfi_pc_rdata, + output reg [31:0] rvfi_pc_wdata, + output reg [31:0] rvfi_mem_addr, + output reg [ 3:0] rvfi_mem_rmask, + output reg [ 3:0] rvfi_mem_wmask, + output reg [31:0] rvfi_mem_rdata, + output reg [31:0] rvfi_mem_wdata, + + output reg [63:0] rvfi_csr_mcycle_rmask, + output reg [63:0] rvfi_csr_mcycle_wmask, + output reg [63:0] rvfi_csr_mcycle_rdata, + output reg [63:0] rvfi_csr_mcycle_wdata, + + output reg [63:0] rvfi_csr_minstret_rmask, + output reg [63:0] rvfi_csr_minstret_wmask, + output reg [63:0] rvfi_csr_minstret_rdata, + output reg [63:0] rvfi_csr_minstret_wdata, +`endif + + // Trace Interface + output reg trace_valid, + output reg [35:0] trace_data +); + localparam integer irq_timer = 0; + localparam integer irq_ebreak = 1; + localparam integer irq_buserror = 2; + + localparam integer irqregs_offset = ENABLE_REGS_16_31 ? 32 : 16; + localparam integer regfile_size = (ENABLE_REGS_16_31 ? 32 : 16) + 4*ENABLE_IRQ*ENABLE_IRQ_QREGS; + localparam integer regindex_bits = (ENABLE_REGS_16_31 ? 5 : 4) + ENABLE_IRQ*ENABLE_IRQ_QREGS; + + localparam WITH_PCPI = ENABLE_PCPI || ENABLE_MUL || ENABLE_FAST_MUL || ENABLE_DIV; + + localparam [35:0] TRACE_BRANCH = {4'b 0001, 32'b 0}; + localparam [35:0] TRACE_ADDR = {4'b 0010, 32'b 0}; + localparam [35:0] TRACE_IRQ = {4'b 1000, 32'b 0}; + + reg [63:0] count_cycle, count_instr; + reg [31:0] reg_pc, reg_next_pc, reg_op1, reg_op2, reg_out; + reg [4:0] reg_sh; + + reg [31:0] next_insn_opcode; + reg [31:0] dbg_insn_opcode; + reg [31:0] dbg_insn_addr; + + wire dbg_mem_valid = mem_valid; + wire dbg_mem_instr = mem_instr; + wire dbg_mem_ready = mem_ready; + wire [31:0] dbg_mem_addr = mem_addr; + wire [31:0] dbg_mem_wdata = mem_wdata; + wire [ 3:0] dbg_mem_wstrb = mem_wstrb; + wire [31:0] dbg_mem_rdata = mem_rdata; + + assign pcpi_rs1 = reg_op1; + assign pcpi_rs2 = reg_op2; + + wire [31:0] next_pc; + + reg irq_delay; + reg irq_active; + reg [31:0] irq_mask; + reg [31:0] irq_pending; + reg [31:0] timer; + +`ifndef PICORV32_REGS + reg [31:0] cpuregs [0:regfile_size-1]; + + integer i; + initial begin + if (REGS_INIT_ZERO) begin + for (i = 0; i < regfile_size; i = i+1) + cpuregs[i] = 0; + end + end +`endif + + task empty_statement; + // This task is used by the `assert directive in non-formal mode to + // avoid empty statement (which are unsupported by plain Verilog syntax). + begin end + endtask + +`ifdef DEBUGREGS + wire [31:0] dbg_reg_x0 = 0; + wire [31:0] dbg_reg_x1 = cpuregs[1]; + wire [31:0] dbg_reg_x2 = cpuregs[2]; + wire [31:0] dbg_reg_x3 = cpuregs[3]; + wire [31:0] dbg_reg_x4 = cpuregs[4]; + wire [31:0] dbg_reg_x5 = cpuregs[5]; + wire [31:0] dbg_reg_x6 = cpuregs[6]; + wire [31:0] dbg_reg_x7 = cpuregs[7]; + wire [31:0] dbg_reg_x8 = cpuregs[8]; + wire [31:0] dbg_reg_x9 = cpuregs[9]; + wire [31:0] dbg_reg_x10 = cpuregs[10]; + wire [31:0] dbg_reg_x11 = cpuregs[11]; + wire [31:0] dbg_reg_x12 = cpuregs[12]; + wire [31:0] dbg_reg_x13 = cpuregs[13]; + wire [31:0] dbg_reg_x14 = cpuregs[14]; + wire [31:0] dbg_reg_x15 = cpuregs[15]; + wire [31:0] dbg_reg_x16 = cpuregs[16]; + wire [31:0] dbg_reg_x17 = cpuregs[17]; + wire [31:0] dbg_reg_x18 = cpuregs[18]; + wire [31:0] dbg_reg_x19 = cpuregs[19]; + wire [31:0] dbg_reg_x20 = cpuregs[20]; + wire [31:0] dbg_reg_x21 = cpuregs[21]; + wire [31:0] dbg_reg_x22 = cpuregs[22]; + wire [31:0] dbg_reg_x23 = cpuregs[23]; + wire [31:0] dbg_reg_x24 = cpuregs[24]; + wire [31:0] dbg_reg_x25 = cpuregs[25]; + wire [31:0] dbg_reg_x26 = cpuregs[26]; + wire [31:0] dbg_reg_x27 = cpuregs[27]; + wire [31:0] dbg_reg_x28 = cpuregs[28]; + wire [31:0] dbg_reg_x29 = cpuregs[29]; + wire [31:0] dbg_reg_x30 = cpuregs[30]; + wire [31:0] dbg_reg_x31 = cpuregs[31]; +`endif + + // Internal PCPI Cores + + wire pcpi_mul_wr; + wire [31:0] pcpi_mul_rd; + wire pcpi_mul_wait; + wire pcpi_mul_ready; + + wire pcpi_div_wr; + wire [31:0] pcpi_div_rd; + wire pcpi_div_wait; + wire pcpi_div_ready; + + reg pcpi_int_wr; + reg [31:0] pcpi_int_rd; + reg pcpi_int_wait; + reg pcpi_int_ready; + + generate if (ENABLE_FAST_MUL) begin + picorv32_pcpi_fast_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else if (ENABLE_MUL) begin + picorv32_pcpi_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else begin + assign pcpi_mul_wr = 0; + assign pcpi_mul_rd = 32'bx; + assign pcpi_mul_wait = 0; + assign pcpi_mul_ready = 0; + end endgenerate + + generate if (ENABLE_DIV) begin + picorv32_pcpi_div pcpi_div ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_div_wr ), + .pcpi_rd (pcpi_div_rd ), + .pcpi_wait (pcpi_div_wait ), + .pcpi_ready(pcpi_div_ready ) + ); + end else begin + assign pcpi_div_wr = 0; + assign pcpi_div_rd = 32'bx; + assign pcpi_div_wait = 0; + assign pcpi_div_ready = 0; + end endgenerate + + always @* begin + pcpi_int_wr = 0; + pcpi_int_rd = 32'bx; + pcpi_int_wait = |{ENABLE_PCPI && pcpi_wait, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_wait, ENABLE_DIV && pcpi_div_wait}; + pcpi_int_ready = |{ENABLE_PCPI && pcpi_ready, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready, ENABLE_DIV && pcpi_div_ready}; + + (* parallel_case *) + case (1'b1) + ENABLE_PCPI && pcpi_ready: begin + pcpi_int_wr = ENABLE_PCPI ? pcpi_wr : 0; + pcpi_int_rd = ENABLE_PCPI ? pcpi_rd : 0; + end + (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready: begin + pcpi_int_wr = pcpi_mul_wr; + pcpi_int_rd = pcpi_mul_rd; + end + ENABLE_DIV && pcpi_div_ready: begin + pcpi_int_wr = pcpi_div_wr; + pcpi_int_rd = pcpi_div_rd; + end + endcase + end + + + // Memory Interface + + reg [1:0] mem_state; + reg [1:0] mem_wordsize; + reg [31:0] mem_rdata_word; + reg [31:0] mem_rdata_q; + reg mem_do_prefetch; + reg mem_do_rinst; + reg mem_do_rdata; + reg mem_do_wdata; + + wire mem_xfer; + reg mem_la_secondword, mem_la_firstword_reg, last_mem_valid; + wire mem_la_firstword = COMPRESSED_ISA && (mem_do_prefetch || mem_do_rinst) && next_pc[1] && !mem_la_secondword; + wire mem_la_firstword_xfer = COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg); + + reg prefetched_high_word; + reg clear_prefetched_high_word; + reg [15:0] mem_16bit_buffer; + + wire [31:0] mem_rdata_latched_noshuffle; + wire [31:0] mem_rdata_latched; + + wire mem_la_use_prefetched_high_word = COMPRESSED_ISA && mem_la_firstword && prefetched_high_word && !clear_prefetched_high_word; + assign mem_xfer = (mem_valid && mem_ready) || (mem_la_use_prefetched_high_word && mem_do_rinst); + + wire mem_busy = |{mem_do_prefetch, mem_do_rinst, mem_do_rdata, mem_do_wdata}; + wire mem_done = resetn && ((mem_xfer && |mem_state && (mem_do_rinst || mem_do_rdata || mem_do_wdata)) || (&mem_state && mem_do_rinst)) && + (!mem_la_firstword || (~&mem_rdata_latched[1:0] && mem_xfer)); + + assign mem_la_write = resetn && !mem_state && mem_do_wdata; + assign mem_la_read = resetn && ((!mem_la_use_prefetched_high_word && !mem_state && (mem_do_rinst || mem_do_prefetch || mem_do_rdata)) || + (COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg) && !mem_la_secondword && &mem_rdata_latched[1:0])); + assign mem_la_addr = (mem_do_prefetch || mem_do_rinst) ? {next_pc[31:2] + mem_la_firstword_xfer, 2'b00} : {reg_op1[31:2], 2'b00}; + + assign mem_rdata_latched_noshuffle = (mem_xfer || LATCHED_MEM_RDATA) ? mem_rdata : mem_rdata_q; + + assign mem_rdata_latched = COMPRESSED_ISA && mem_la_use_prefetched_high_word ? {16'bx, mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_secondword ? {mem_rdata_latched_noshuffle[15:0], mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_firstword ? {16'bx, mem_rdata_latched_noshuffle[31:16]} : mem_rdata_latched_noshuffle; + + always @(posedge clk) begin + if (!resetn) begin + mem_la_firstword_reg <= 0; + last_mem_valid <= 0; + end else begin + if (!last_mem_valid) + mem_la_firstword_reg <= mem_la_firstword; + last_mem_valid <= mem_valid && !mem_ready; + end + end + + always @* begin + (* full_case *) + case (mem_wordsize) + 0: begin + mem_la_wdata = reg_op2; + mem_la_wstrb = 4'b1111; + mem_rdata_word = mem_rdata; + end + 1: begin + mem_la_wdata = {2{reg_op2[15:0]}}; + mem_la_wstrb = reg_op1[1] ? 4'b1100 : 4'b0011; + case (reg_op1[1]) + 1'b0: mem_rdata_word = {16'b0, mem_rdata[15: 0]}; + 1'b1: mem_rdata_word = {16'b0, mem_rdata[31:16]}; + endcase + end + 2: begin + mem_la_wdata = {4{reg_op2[7:0]}}; + mem_la_wstrb = 4'b0001 << reg_op1[1:0]; + case (reg_op1[1:0]) + 2'b00: mem_rdata_word = {24'b0, mem_rdata[ 7: 0]}; + 2'b01: mem_rdata_word = {24'b0, mem_rdata[15: 8]}; + 2'b10: mem_rdata_word = {24'b0, mem_rdata[23:16]}; + 2'b11: mem_rdata_word = {24'b0, mem_rdata[31:24]}; + endcase + end + endcase + end + + always @(posedge clk) begin + if (mem_xfer) begin + mem_rdata_q <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + next_insn_opcode <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + end + + if (COMPRESSED_ISA && mem_done && (mem_do_prefetch || mem_do_rinst)) begin + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= {2'b0, mem_rdata_latched[10:7], mem_rdata_latched[12:11], mem_rdata_latched[5], mem_rdata_latched[6], 2'b00}; + end + 3'b010: begin // C.LW + mem_rdata_q[31:20] <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b 110: begin // C.SW + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b 000: begin // C.ADDI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 010: begin // C.LI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 011: begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[4:3], + mem_rdata_latched[5], mem_rdata_latched[2], mem_rdata_latched[6], 4'b 0000}); + end else begin // C.LUI + mem_rdata_q[31:12] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + end + 3'b100: begin + if (mem_rdata_latched[11:10] == 2'b00) begin // C.SRLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b01) begin // C.SRAI + mem_rdata_q[31:25] <= 7'b0100000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + if (mem_rdata_latched[6:5] == 2'b00) mem_rdata_q[14:12] <= 3'b000; + if (mem_rdata_latched[6:5] == 2'b01) mem_rdata_q[14:12] <= 3'b100; + if (mem_rdata_latched[6:5] == 2'b10) mem_rdata_q[14:12] <= 3'b110; + if (mem_rdata_latched[6:5] == 2'b11) mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:25] <= mem_rdata_latched[6:5] == 2'b00 ? 7'b0100000 : 7'b0000000; + end + end + 3'b 110: begin // C.BEQZ + mem_rdata_q[14:12] <= 3'b000; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + 3'b 111: begin // C.BNEZ + mem_rdata_q[14:12] <= 3'b001; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 001; + end + 3'b010: begin // C.LWSP + mem_rdata_q[31:20] <= {4'b0, mem_rdata_latched[3:2], mem_rdata_latched[12], mem_rdata_latched[6:4], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + end + 3'b110: begin // C.SWSP + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {4'b0, mem_rdata_latched[8:7], mem_rdata_latched[12:9], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + endcase + end + end + + always @(posedge clk) begin + if (resetn && !trap) begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) + `assert(!mem_do_wdata); + + if (mem_do_prefetch || mem_do_rinst) + `assert(!mem_do_rdata); + + if (mem_do_rdata) + `assert(!mem_do_prefetch && !mem_do_rinst); + + if (mem_do_wdata) + `assert(!(mem_do_prefetch || mem_do_rinst || mem_do_rdata)); + + if (mem_state == 2 || mem_state == 3) + `assert(mem_valid || mem_do_prefetch); + end + end + + always @(posedge clk) begin + if (!resetn || trap) begin + if (!resetn) + mem_state <= 0; + if (!resetn || mem_ready) + mem_valid <= 0; + mem_la_secondword <= 0; + prefetched_high_word <= 0; + end else begin + if (mem_la_read || mem_la_write) begin + mem_addr <= mem_la_addr; + mem_wstrb <= mem_la_wstrb & {4{mem_la_write}}; + end + if (mem_la_write) begin + mem_wdata <= mem_la_wdata; + end + case (mem_state) + 0: begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) begin + mem_valid <= !mem_la_use_prefetched_high_word; + mem_instr <= mem_do_prefetch || mem_do_rinst; + mem_wstrb <= 0; + mem_state <= 1; + end + if (mem_do_wdata) begin + mem_valid <= 1; + mem_instr <= 0; + mem_state <= 2; + end + end + 1: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch || mem_do_rinst || mem_do_rdata); + `assert(mem_valid == !mem_la_use_prefetched_high_word); + `assert(mem_instr == (mem_do_prefetch || mem_do_rinst)); + if (mem_xfer) begin + if (COMPRESSED_ISA && mem_la_read) begin + mem_valid <= 1; + mem_la_secondword <= 1; + if (!mem_la_use_prefetched_high_word) + mem_16bit_buffer <= mem_rdata[31:16]; + end else begin + mem_valid <= 0; + mem_la_secondword <= 0; + if (COMPRESSED_ISA && !mem_do_rdata) begin + if (~&mem_rdata[1:0] || mem_la_secondword) begin + mem_16bit_buffer <= mem_rdata[31:16]; + prefetched_high_word <= 1; + end else begin + prefetched_high_word <= 0; + end + end + mem_state <= mem_do_rinst || mem_do_rdata ? 0 : 3; + end + end + end + 2: begin + `assert(mem_wstrb != 0); + `assert(mem_do_wdata); + if (mem_xfer) begin + mem_valid <= 0; + mem_state <= 0; + end + end + 3: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch); + if (mem_do_rinst) begin + mem_state <= 0; + end + end + endcase + end + + if (clear_prefetched_high_word) + prefetched_high_word <= 0; + end + + + // Instruction Decoder + + reg instr_lui, instr_auipc, instr_jal, instr_jalr; + reg instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu; + reg instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw; + reg instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai; + reg instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and; + reg instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, instr_ecall_ebreak; + reg instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer; + wire instr_trap; + + reg [regindex_bits-1:0] decoded_rd, decoded_rs1, decoded_rs2; + reg [31:0] decoded_imm, decoded_imm_j; + reg decoder_trigger; + reg decoder_trigger_q; + reg decoder_pseudo_trigger; + reg decoder_pseudo_trigger_q; + reg compressed_instr; + + reg is_lui_auipc_jal; + reg is_lb_lh_lw_lbu_lhu; + reg is_slli_srli_srai; + reg is_jalr_addi_slti_sltiu_xori_ori_andi; + reg is_sb_sh_sw; + reg is_sll_srl_sra; + reg is_lui_auipc_jal_jalr_addi_add_sub; + reg is_slti_blt_slt; + reg is_sltiu_bltu_sltu; + reg is_beq_bne_blt_bge_bltu_bgeu; + reg is_lbu_lhu_lw; + reg is_alu_reg_imm; + reg is_alu_reg_reg; + reg is_compare; + + assign instr_trap = (CATCH_ILLINSN || WITH_PCPI) && !{instr_lui, instr_auipc, instr_jal, instr_jalr, + instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu, + instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw, + instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai, + instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and, + instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, + instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer}; + + wire is_rdcycle_rdcycleh_rdinstr_rdinstrh; + assign is_rdcycle_rdcycleh_rdinstr_rdinstrh = |{instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh}; + + reg [63:0] new_ascii_instr; + `FORMAL_KEEP reg [63:0] dbg_ascii_instr; + `FORMAL_KEEP reg [31:0] dbg_insn_imm; + `FORMAL_KEEP reg [4:0] dbg_insn_rs1; + `FORMAL_KEEP reg [4:0] dbg_insn_rs2; + `FORMAL_KEEP reg [4:0] dbg_insn_rd; + `FORMAL_KEEP reg [31:0] dbg_rs1val; + `FORMAL_KEEP reg [31:0] dbg_rs2val; + `FORMAL_KEEP reg dbg_rs1val_valid; + `FORMAL_KEEP reg dbg_rs2val_valid; + + always @* begin + new_ascii_instr = ""; + + if (instr_lui) new_ascii_instr = "lui"; + if (instr_auipc) new_ascii_instr = "auipc"; + if (instr_jal) new_ascii_instr = "jal"; + if (instr_jalr) new_ascii_instr = "jalr"; + + if (instr_beq) new_ascii_instr = "beq"; + if (instr_bne) new_ascii_instr = "bne"; + if (instr_blt) new_ascii_instr = "blt"; + if (instr_bge) new_ascii_instr = "bge"; + if (instr_bltu) new_ascii_instr = "bltu"; + if (instr_bgeu) new_ascii_instr = "bgeu"; + + if (instr_lb) new_ascii_instr = "lb"; + if (instr_lh) new_ascii_instr = "lh"; + if (instr_lw) new_ascii_instr = "lw"; + if (instr_lbu) new_ascii_instr = "lbu"; + if (instr_lhu) new_ascii_instr = "lhu"; + if (instr_sb) new_ascii_instr = "sb"; + if (instr_sh) new_ascii_instr = "sh"; + if (instr_sw) new_ascii_instr = "sw"; + + if (instr_addi) new_ascii_instr = "addi"; + if (instr_slti) new_ascii_instr = "slti"; + if (instr_sltiu) new_ascii_instr = "sltiu"; + if (instr_xori) new_ascii_instr = "xori"; + if (instr_ori) new_ascii_instr = "ori"; + if (instr_andi) new_ascii_instr = "andi"; + if (instr_slli) new_ascii_instr = "slli"; + if (instr_srli) new_ascii_instr = "srli"; + if (instr_srai) new_ascii_instr = "srai"; + + if (instr_add) new_ascii_instr = "add"; + if (instr_sub) new_ascii_instr = "sub"; + if (instr_sll) new_ascii_instr = "sll"; + if (instr_slt) new_ascii_instr = "slt"; + if (instr_sltu) new_ascii_instr = "sltu"; + if (instr_xor) new_ascii_instr = "xor"; + if (instr_srl) new_ascii_instr = "srl"; + if (instr_sra) new_ascii_instr = "sra"; + if (instr_or) new_ascii_instr = "or"; + if (instr_and) new_ascii_instr = "and"; + + if (instr_rdcycle) new_ascii_instr = "rdcycle"; + if (instr_rdcycleh) new_ascii_instr = "rdcycleh"; + if (instr_rdinstr) new_ascii_instr = "rdinstr"; + if (instr_rdinstrh) new_ascii_instr = "rdinstrh"; + + if (instr_getq) new_ascii_instr = "getq"; + if (instr_setq) new_ascii_instr = "setq"; + if (instr_retirq) new_ascii_instr = "retirq"; + if (instr_maskirq) new_ascii_instr = "maskirq"; + if (instr_waitirq) new_ascii_instr = "waitirq"; + if (instr_timer) new_ascii_instr = "timer"; + end + + reg [63:0] q_ascii_instr; + reg [31:0] q_insn_imm; + reg [31:0] q_insn_opcode; + reg [4:0] q_insn_rs1; + reg [4:0] q_insn_rs2; + reg [4:0] q_insn_rd; + reg dbg_next; + + wire launch_next_insn; + reg dbg_valid_insn; + + reg [63:0] cached_ascii_instr; + reg [31:0] cached_insn_imm; + reg [31:0] cached_insn_opcode; + reg [4:0] cached_insn_rs1; + reg [4:0] cached_insn_rs2; + reg [4:0] cached_insn_rd; + + always @(posedge clk) begin + q_ascii_instr <= dbg_ascii_instr; + q_insn_imm <= dbg_insn_imm; + q_insn_opcode <= dbg_insn_opcode; + q_insn_rs1 <= dbg_insn_rs1; + q_insn_rs2 <= dbg_insn_rs2; + q_insn_rd <= dbg_insn_rd; + dbg_next <= launch_next_insn; + + if (!resetn || trap) + dbg_valid_insn <= 0; + else if (launch_next_insn) + dbg_valid_insn <= 1; + + if (decoder_trigger_q) begin + cached_ascii_instr <= new_ascii_instr; + cached_insn_imm <= decoded_imm; + if (&next_insn_opcode[1:0]) + cached_insn_opcode <= next_insn_opcode; + else + cached_insn_opcode <= {16'b0, next_insn_opcode[15:0]}; + cached_insn_rs1 <= decoded_rs1; + cached_insn_rs2 <= decoded_rs2; + cached_insn_rd <= decoded_rd; + end + + if (launch_next_insn) begin + dbg_insn_addr <= next_pc; + end + end + + always @* begin + dbg_ascii_instr = q_ascii_instr; + dbg_insn_imm = q_insn_imm; + dbg_insn_opcode = q_insn_opcode; + dbg_insn_rs1 = q_insn_rs1; + dbg_insn_rs2 = q_insn_rs2; + dbg_insn_rd = q_insn_rd; + + if (dbg_next) begin + if (decoder_pseudo_trigger_q) begin + dbg_ascii_instr = cached_ascii_instr; + dbg_insn_imm = cached_insn_imm; + dbg_insn_opcode = cached_insn_opcode; + dbg_insn_rs1 = cached_insn_rs1; + dbg_insn_rs2 = cached_insn_rs2; + dbg_insn_rd = cached_insn_rd; + end else begin + dbg_ascii_instr = new_ascii_instr; + if (&next_insn_opcode[1:0]) + dbg_insn_opcode = next_insn_opcode; + else + dbg_insn_opcode = {16'b0, next_insn_opcode[15:0]}; + dbg_insn_imm = decoded_imm; + dbg_insn_rs1 = decoded_rs1; + dbg_insn_rs2 = decoded_rs2; + dbg_insn_rd = decoded_rd; + end + end + end + +`ifdef DEBUGASM + always @(posedge clk) begin + if (dbg_next) begin + $display("debugasm %x %x %s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "*"); + end + end +`endif + +`ifdef DEBUG + always @(posedge clk) begin + if (dbg_next) begin + if (&dbg_insn_opcode[1:0]) + $display("DECODE: 0x%08x 0x%08x %-0s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + else + $display("DECODE: 0x%08x 0x%04x %-0s", dbg_insn_addr, dbg_insn_opcode[15:0], dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + end + end +`endif + + always @(posedge clk) begin + is_lui_auipc_jal <= |{instr_lui, instr_auipc, instr_jal}; + is_lui_auipc_jal_jalr_addi_add_sub <= |{instr_lui, instr_auipc, instr_jal, instr_jalr, instr_addi, instr_add, instr_sub}; + is_slti_blt_slt <= |{instr_slti, instr_blt, instr_slt}; + is_sltiu_bltu_sltu <= |{instr_sltiu, instr_bltu, instr_sltu}; + is_lbu_lhu_lw <= |{instr_lbu, instr_lhu, instr_lw}; + is_compare <= |{is_beq_bne_blt_bge_bltu_bgeu, instr_slti, instr_slt, instr_sltiu, instr_sltu}; + + if (mem_do_rinst && mem_done) begin + instr_lui <= mem_rdata_latched[6:0] == 7'b0110111; + instr_auipc <= mem_rdata_latched[6:0] == 7'b0010111; + instr_jal <= mem_rdata_latched[6:0] == 7'b1101111; + instr_jalr <= mem_rdata_latched[6:0] == 7'b1100111 && mem_rdata_latched[14:12] == 3'b000; + instr_retirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ; + instr_waitirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000100 && ENABLE_IRQ; + + is_beq_bne_blt_bge_bltu_bgeu <= mem_rdata_latched[6:0] == 7'b1100011; + is_lb_lh_lw_lbu_lhu <= mem_rdata_latched[6:0] == 7'b0000011; + is_sb_sh_sw <= mem_rdata_latched[6:0] == 7'b0100011; + is_alu_reg_imm <= mem_rdata_latched[6:0] == 7'b0010011; + is_alu_reg_reg <= mem_rdata_latched[6:0] == 7'b0110011; + + { decoded_imm_j[31:20], decoded_imm_j[10:1], decoded_imm_j[11], decoded_imm_j[19:12], decoded_imm_j[0] } <= $signed({mem_rdata_latched[31:12], 1'b0}); + + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[19:15]; + decoded_rs2 <= mem_rdata_latched[24:20]; + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS) + decoded_rs1[regindex_bits-1] <= 1; // instr_getq + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ) + decoded_rs1 <= ENABLE_IRQ_QREGS ? irqregs_offset : 3; // instr_retirq + + compressed_instr <= 0; + if (COMPRESSED_ISA && mem_rdata_latched[1:0] != 2'b11) begin + compressed_instr <= 1; + decoded_rd <= 0; + decoded_rs1 <= 0; + decoded_rs2 <= 0; + + { decoded_imm_j[31:11], decoded_imm_j[4], decoded_imm_j[9:8], decoded_imm_j[10], decoded_imm_j[6], + decoded_imm_j[7], decoded_imm_j[3:1], decoded_imm_j[5], decoded_imm_j[0] } <= $signed({mem_rdata_latched[12:2], 1'b0}); + + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + is_alu_reg_imm <= |mem_rdata_latched[12:5]; + decoded_rs1 <= 2; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b010: begin // C.LW + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b110: begin // C.SW + is_sb_sh_sw <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.NOP / C.ADDI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + 3'b001: begin // C.JAL + instr_jal <= 1; + decoded_rd <= 1; + end + 3'b 010: begin // C.LI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + 3'b 011: begin + if (mem_rdata_latched[12] || mem_rdata_latched[6:2]) begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end else begin // C.LUI + instr_lui <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + end + end + 3'b100: begin + if (!mem_rdata_latched[11] && !mem_rdata_latched[12]) begin // C.SRLI, C.SRAI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + is_alu_reg_reg <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + end + 3'b101: begin // C.J + instr_jal <= 1; + end + 3'b110: begin // C.BEQZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + 3'b111: begin // C.BNEZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + if (!mem_rdata_latched[12]) begin + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + end + 3'b010: begin // C.LWSP + if (mem_rdata_latched[11:7]) begin + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 2; + end + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + instr_jalr <= 1; + decoded_rd <= 0; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + instr_jalr <= 1; + decoded_rd <= 1; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + end + 3'b110: begin // C.SWSP + is_sb_sh_sw <= 1; + decoded_rs1 <= 2; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + endcase + end + endcase + end + end + + if (decoder_trigger && !decoder_pseudo_trigger) begin + pcpi_insn <= WITH_PCPI ? mem_rdata_q : 'bx; + + instr_beq <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b000; + instr_bne <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b001; + instr_blt <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b100; + instr_bge <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b101; + instr_bltu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b110; + instr_bgeu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b111; + + instr_lb <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b000; + instr_lh <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b001; + instr_lw <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b010; + instr_lbu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b100; + instr_lhu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b101; + + instr_sb <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b000; + instr_sh <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b001; + instr_sw <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b010; + + instr_addi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b000; + instr_slti <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b010; + instr_sltiu <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b011; + instr_xori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b100; + instr_ori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b110; + instr_andi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b111; + + instr_slli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_srli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_srai <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + + instr_add <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0000000; + instr_sub <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0100000; + instr_sll <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_slt <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b010 && mem_rdata_q[31:25] == 7'b0000000; + instr_sltu <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b011 && mem_rdata_q[31:25] == 7'b0000000; + instr_xor <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b100 && mem_rdata_q[31:25] == 7'b0000000; + instr_srl <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_sra <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + instr_or <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b110 && mem_rdata_q[31:25] == 7'b0000000; + instr_and <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b111 && mem_rdata_q[31:25] == 7'b0000000; + + instr_rdcycle <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000100000010)) && ENABLE_COUNTERS; + instr_rdcycleh <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000100000010)) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + instr_rdinstr <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000001000000010) && ENABLE_COUNTERS; + instr_rdinstrh <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000001000000010) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + + instr_ecall_ebreak <= ((mem_rdata_q[6:0] == 7'b1110011 && !mem_rdata_q[31:21] && !mem_rdata_q[19:7]) || + (COMPRESSED_ISA && mem_rdata_q[15:0] == 16'h9002)); + + instr_getq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_setq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000001 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_maskirq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000011 && ENABLE_IRQ; + instr_timer <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000101 && ENABLE_IRQ && ENABLE_IRQ_TIMER; + + is_slli_srli_srai <= is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_jalr_addi_slti_sltiu_xori_ori_andi <= instr_jalr || is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b000, + mem_rdata_q[14:12] == 3'b010, + mem_rdata_q[14:12] == 3'b011, + mem_rdata_q[14:12] == 3'b100, + mem_rdata_q[14:12] == 3'b110, + mem_rdata_q[14:12] == 3'b111 + }; + + is_sll_srl_sra <= is_alu_reg_reg && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_lui_auipc_jal_jalr_addi_add_sub <= 0; + is_compare <= 0; + + (* parallel_case *) + case (1'b1) + instr_jal: + decoded_imm <= decoded_imm_j; + |{instr_lui, instr_auipc}: + decoded_imm <= mem_rdata_q[31:12] << 12; + |{instr_jalr, is_lb_lh_lw_lbu_lhu, is_alu_reg_imm}: + decoded_imm <= $signed(mem_rdata_q[31:20]); + is_beq_bne_blt_bge_bltu_bgeu: + decoded_imm <= $signed({mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8], 1'b0}); + is_sb_sh_sw: + decoded_imm <= $signed({mem_rdata_q[31:25], mem_rdata_q[11:7]}); + default: + decoded_imm <= 1'bx; + endcase + end + + if (!resetn) begin + is_beq_bne_blt_bge_bltu_bgeu <= 0; + is_compare <= 0; + + instr_beq <= 0; + instr_bne <= 0; + instr_blt <= 0; + instr_bge <= 0; + instr_bltu <= 0; + instr_bgeu <= 0; + + instr_addi <= 0; + instr_slti <= 0; + instr_sltiu <= 0; + instr_xori <= 0; + instr_ori <= 0; + instr_andi <= 0; + + instr_add <= 0; + instr_sub <= 0; + instr_sll <= 0; + instr_slt <= 0; + instr_sltu <= 0; + instr_xor <= 0; + instr_srl <= 0; + instr_sra <= 0; + instr_or <= 0; + instr_and <= 0; + end + end + + + // Main State Machine + + localparam cpu_state_trap = 8'b10000000; + localparam cpu_state_fetch = 8'b01000000; + localparam cpu_state_ld_rs1 = 8'b00100000; + localparam cpu_state_ld_rs2 = 8'b00010000; + localparam cpu_state_exec = 8'b00001000; + localparam cpu_state_shift = 8'b00000100; + localparam cpu_state_stmem = 8'b00000010; + localparam cpu_state_ldmem = 8'b00000001; + + reg [7:0] cpu_state; + reg [1:0] irq_state; + + `FORMAL_KEEP reg [127:0] dbg_ascii_state; + + always @* begin + dbg_ascii_state = ""; + if (cpu_state == cpu_state_trap) dbg_ascii_state = "trap"; + if (cpu_state == cpu_state_fetch) dbg_ascii_state = "fetch"; + if (cpu_state == cpu_state_ld_rs1) dbg_ascii_state = "ld_rs1"; + if (cpu_state == cpu_state_ld_rs2) dbg_ascii_state = "ld_rs2"; + if (cpu_state == cpu_state_exec) dbg_ascii_state = "exec"; + if (cpu_state == cpu_state_shift) dbg_ascii_state = "shift"; + if (cpu_state == cpu_state_stmem) dbg_ascii_state = "stmem"; + if (cpu_state == cpu_state_ldmem) dbg_ascii_state = "ldmem"; + end + + reg set_mem_do_rinst; + reg set_mem_do_rdata; + reg set_mem_do_wdata; + + reg latched_store; + reg latched_stalu; + reg latched_branch; + reg latched_compr; + reg latched_trace; + reg latched_is_lu; + reg latched_is_lh; + reg latched_is_lb; + reg [regindex_bits-1:0] latched_rd; + + reg [31:0] current_pc; + assign next_pc = latched_store && latched_branch ? reg_out & ~1 : reg_next_pc; + + reg [3:0] pcpi_timeout_counter; + reg pcpi_timeout; + + reg [31:0] next_irq_pending; + reg do_waitirq; + + reg [31:0] alu_out, alu_out_q; + reg alu_out_0, alu_out_0_q; + reg alu_wait, alu_wait_2; + + reg [31:0] alu_add_sub; + reg [31:0] alu_shl, alu_shr; + reg alu_eq, alu_ltu, alu_lts; + + generate if (TWO_CYCLE_ALU) begin + always @(posedge clk) begin + alu_add_sub <= instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq <= reg_op1 == reg_op2; + alu_lts <= $signed(reg_op1) < $signed(reg_op2); + alu_ltu <= reg_op1 < reg_op2; + alu_shl <= reg_op1 << reg_op2[4:0]; + alu_shr <= $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end else begin + always @* begin + alu_add_sub = instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq = reg_op1 == reg_op2; + alu_lts = $signed(reg_op1) < $signed(reg_op2); + alu_ltu = reg_op1 < reg_op2; + alu_shl = reg_op1 << reg_op2[4:0]; + alu_shr = $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end endgenerate + + always @* begin + alu_out_0 = 'bx; + (* parallel_case, full_case *) + case (1'b1) + instr_beq: + alu_out_0 = alu_eq; + instr_bne: + alu_out_0 = !alu_eq; + instr_bge: + alu_out_0 = !alu_lts; + instr_bgeu: + alu_out_0 = !alu_ltu; + is_slti_blt_slt && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_lts; + is_sltiu_bltu_sltu && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_ltu; + endcase + + alu_out = 'bx; + (* parallel_case, full_case *) + case (1'b1) + is_lui_auipc_jal_jalr_addi_add_sub: + alu_out = alu_add_sub; + is_compare: + alu_out = alu_out_0; + instr_xori || instr_xor: + alu_out = reg_op1 ^ reg_op2; + instr_ori || instr_or: + alu_out = reg_op1 | reg_op2; + instr_andi || instr_and: + alu_out = reg_op1 & reg_op2; + BARREL_SHIFTER && (instr_sll || instr_slli): + alu_out = alu_shl; + BARREL_SHIFTER && (instr_srl || instr_srli || instr_sra || instr_srai): + alu_out = alu_shr; + endcase + +`ifdef RISCV_FORMAL_BLACKBOX_ALU + alu_out_0 = $anyseq; + alu_out = $anyseq; +`endif + end + + reg clear_prefetched_high_word_q; + always @(posedge clk) clear_prefetched_high_word_q <= clear_prefetched_high_word; + + always @* begin + clear_prefetched_high_word = clear_prefetched_high_word_q; + if (!prefetched_high_word) + clear_prefetched_high_word = 0; + if (latched_branch || irq_state || !resetn) + clear_prefetched_high_word = COMPRESSED_ISA; + end + + reg cpuregs_write; + reg [31:0] cpuregs_wrdata; + reg [31:0] cpuregs_rs1; + reg [31:0] cpuregs_rs2; + reg [regindex_bits-1:0] decoded_rs; + + always @* begin + cpuregs_write = 0; + cpuregs_wrdata = 'bx; + + if (cpu_state == cpu_state_fetch) begin + (* parallel_case *) + case (1'b1) + latched_branch: begin + cpuregs_wrdata = reg_pc + (latched_compr ? 2 : 4); + cpuregs_write = 1; + end + latched_store && !latched_branch: begin + cpuregs_wrdata = latched_stalu ? alu_out_q : reg_out; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[0]: begin + cpuregs_wrdata = reg_next_pc | latched_compr; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[1]: begin + cpuregs_wrdata = irq_pending & ~irq_mask; + cpuregs_write = 1; + end + endcase + end + end + +`ifndef PICORV32_REGS + always @(posedge clk) begin + if (resetn && cpuregs_write && latched_rd) +`ifdef PICORV32_TESTBUG_001 + cpuregs[latched_rd ^ 1] <= cpuregs_wrdata; +`elsif PICORV32_TESTBUG_002 + cpuregs[latched_rd] <= cpuregs_wrdata ^ 1; +`else + cpuregs[latched_rd] <= cpuregs_wrdata; +`endif + end + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs1 ? cpuregs[decoded_rs1] : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs[decoded_rs2] : 0; +`else + cpuregs_rs1 = decoded_rs1 ? $anyseq : 0; + cpuregs_rs2 = decoded_rs2 ? $anyseq : 0; +`endif + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs ? cpuregs[decoded_rs] : 0; +`else + cpuregs_rs1 = decoded_rs ? $anyseq : 0; +`endif + cpuregs_rs2 = cpuregs_rs1; + end + end +`else + wire[31:0] cpuregs_rdata1; + wire[31:0] cpuregs_rdata2; + + wire [5:0] cpuregs_waddr = latched_rd; + wire [5:0] cpuregs_raddr1 = ENABLE_REGS_DUALPORT ? decoded_rs1 : decoded_rs; + wire [5:0] cpuregs_raddr2 = ENABLE_REGS_DUALPORT ? decoded_rs2 : 0; + + `PICORV32_REGS cpuregs ( + .clk(clk), + .wen(resetn && cpuregs_write && latched_rd), + .waddr(cpuregs_waddr), + .raddr1(cpuregs_raddr1), + .raddr2(cpuregs_raddr2), + .wdata(cpuregs_wrdata), + .rdata1(cpuregs_rdata1), + .rdata2(cpuregs_rdata2) + ); + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin + cpuregs_rs1 = decoded_rs1 ? cpuregs_rdata1 : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs_rdata2 : 0; + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; + cpuregs_rs1 = decoded_rs ? cpuregs_rdata1 : 0; + cpuregs_rs2 = cpuregs_rs1; + end + end +`endif + + assign launch_next_insn = cpu_state == cpu_state_fetch && decoder_trigger && (!ENABLE_IRQ || irq_delay || irq_active || !(irq_pending & ~irq_mask)); + + always @(posedge clk) begin + trap <= 0; + reg_sh <= 'bx; + reg_out <= 'bx; + set_mem_do_rinst = 0; + set_mem_do_rdata = 0; + set_mem_do_wdata = 0; + + alu_out_0_q <= alu_out_0; + alu_out_q <= alu_out; + + alu_wait <= 0; + alu_wait_2 <= 0; + + if (launch_next_insn) begin + dbg_rs1val <= 'bx; + dbg_rs2val <= 'bx; + dbg_rs1val_valid <= 0; + dbg_rs2val_valid <= 0; + end + + if (WITH_PCPI && CATCH_ILLINSN) begin + if (resetn && pcpi_valid && !pcpi_int_wait) begin + if (pcpi_timeout_counter) + pcpi_timeout_counter <= pcpi_timeout_counter - 1; + end else + pcpi_timeout_counter <= ~0; + pcpi_timeout <= !pcpi_timeout_counter; + end + + if (ENABLE_COUNTERS) begin + count_cycle <= resetn ? count_cycle + 1 : 0; + if (!ENABLE_COUNTERS64) count_cycle[63:32] <= 0; + end else begin + count_cycle <= 'bx; + count_instr <= 'bx; + end + + next_irq_pending = ENABLE_IRQ ? irq_pending & LATCHED_IRQ : 'bx; + + if (ENABLE_IRQ && ENABLE_IRQ_TIMER && timer) begin + if (timer - 1 == 0) + next_irq_pending[irq_timer] = 1; + timer <= timer - 1; + end + + if (ENABLE_IRQ) begin + next_irq_pending = next_irq_pending | irq; + end + + decoder_trigger <= mem_do_rinst && mem_done; + decoder_trigger_q <= decoder_trigger; + decoder_pseudo_trigger <= 0; + decoder_pseudo_trigger_q <= decoder_pseudo_trigger; + do_waitirq <= 0; + + trace_valid <= 0; + + if (!ENABLE_TRACE) + trace_data <= 'bx; + + if (!resetn) begin + reg_pc <= PROGADDR_RESET; + reg_next_pc <= PROGADDR_RESET; + if (ENABLE_COUNTERS) + count_instr <= 0; + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_trace <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + pcpi_valid <= 0; + pcpi_timeout <= 0; + irq_active <= 0; + irq_delay <= 0; + irq_mask <= ~0; + next_irq_pending = 0; + irq_state <= 0; + eoi <= 0; + timer <= 0; + if (~STACKADDR) begin + latched_store <= 1; + latched_rd <= 2; + reg_out <= STACKADDR; + end + cpu_state <= cpu_state_fetch; + end else + (* parallel_case, full_case *) + case (cpu_state) + cpu_state_trap: begin + trap <= 1; + end + + cpu_state_fetch: begin + mem_do_rinst <= !decoder_trigger && !do_waitirq; + mem_wordsize <= 0; + + current_pc = reg_next_pc; + + (* parallel_case *) + case (1'b1) + latched_branch: begin + current_pc = latched_store ? (latched_stalu ? alu_out_q : reg_out) & ~1 : reg_next_pc; + `debug($display("ST_RD: %2d 0x%08x, BRANCH 0x%08x", latched_rd, reg_pc + (latched_compr ? 2 : 4), current_pc);) + end + latched_store && !latched_branch: begin + `debug($display("ST_RD: %2d 0x%08x", latched_rd, latched_stalu ? alu_out_q : reg_out);) + end + ENABLE_IRQ && irq_state[0]: begin + current_pc = PROGADDR_IRQ; + irq_active <= 1; + mem_do_rinst <= 1; + end + ENABLE_IRQ && irq_state[1]: begin + eoi <= irq_pending & ~irq_mask; + next_irq_pending = next_irq_pending & irq_mask; + end + endcase + + if (ENABLE_TRACE && latched_trace) begin + latched_trace <= 0; + trace_valid <= 1; + if (latched_branch) + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_BRANCH | (current_pc & 32'hfffffffe); + else + trace_data <= (irq_active ? TRACE_IRQ : 0) | (latched_stalu ? alu_out_q : reg_out); + end + + reg_pc <= current_pc; + reg_next_pc <= current_pc; + + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + latched_rd <= decoded_rd; + latched_compr <= compressed_instr; + + if (ENABLE_IRQ && ((decoder_trigger && !irq_active && !irq_delay && |(irq_pending & ~irq_mask)) || irq_state)) begin + irq_state <= + irq_state == 2'b00 ? 2'b01 : + irq_state == 2'b01 ? 2'b10 : 2'b00; + latched_compr <= latched_compr; + if (ENABLE_IRQ_QREGS) + latched_rd <= irqregs_offset | irq_state[0]; + else + latched_rd <= irq_state[0] ? 4 : 3; + end else + if (ENABLE_IRQ && (decoder_trigger || do_waitirq) && instr_waitirq) begin + if (irq_pending) begin + latched_store <= 1; + reg_out <= irq_pending; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + mem_do_rinst <= 1; + end else + do_waitirq <= 1; + end else + if (decoder_trigger) begin + `debug($display("-- %-0t", $time);) + irq_delay <= irq_active; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + if (ENABLE_TRACE) + latched_trace <= 1; + if (ENABLE_COUNTERS) begin + count_instr <= count_instr + 1; + if (!ENABLE_COUNTERS64) count_instr[63:32] <= 0; + end + if (instr_jal) begin + mem_do_rinst <= 1; + reg_next_pc <= current_pc + decoded_imm_j; + latched_branch <= 1; + end else begin + mem_do_rinst <= 0; + mem_do_prefetch <= !instr_jalr && !instr_retirq; + cpu_state <= cpu_state_ld_rs1; + end + end + end + + cpu_state_ld_rs1: begin + reg_op1 <= 'bx; + reg_op2 <= 'bx; + + (* parallel_case *) + case (1'b1) + (CATCH_ILLINSN || WITH_PCPI) && instr_trap: begin + if (WITH_PCPI) begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + pcpi_valid <= 1; + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end else begin + cpu_state <= cpu_state_ld_rs2; + end + end else begin + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + ENABLE_COUNTERS && is_rdcycle_rdcycleh_rdinstr_rdinstrh: begin + (* parallel_case, full_case *) + case (1'b1) + instr_rdcycle: + reg_out <= count_cycle[31:0]; + instr_rdcycleh && ENABLE_COUNTERS64: + reg_out <= count_cycle[63:32]; + instr_rdinstr: + reg_out <= count_instr[31:0]; + instr_rdinstrh && ENABLE_COUNTERS64: + reg_out <= count_instr[63:32]; + endcase + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + is_lui_auipc_jal: begin + reg_op1 <= instr_lui ? 0 : reg_pc; + reg_op2 <= decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_getq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_setq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_rd <= latched_rd | irqregs_offset; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_retirq: begin + eoi <= 0; + irq_active <= 0; + latched_branch <= 1; + latched_store <= 1; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= CATCH_MISALIGN ? (cpuregs_rs1 & 32'h fffffffe) : cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_maskirq: begin + latched_store <= 1; + reg_out <= irq_mask; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + irq_mask <= cpuregs_rs1 | MASKED_IRQ; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_TIMER && instr_timer: begin + latched_store <= 1; + reg_out <= timer; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + timer <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + is_lb_lh_lw_lbu_lhu && !instr_trap: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_ldmem; + mem_do_rinst <= 1; + end + is_slli_srli_srai && !BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_sh <= decoded_rs2; + cpu_state <= cpu_state_shift; + end + is_jalr_addi_slti_sltiu_xori_ori_andi, is_slli_srli_srai && BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_op2 <= is_slli_srli_srai && BARREL_SHIFTER ? decoded_rs2 : decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + default: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + (* parallel_case *) + case (1'b1) + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end else + cpu_state <= cpu_state_ld_rs2; + end + endcase + end + + cpu_state_ld_rs2: begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + + (* parallel_case *) + case (1'b1) + WITH_PCPI && instr_trap: begin + pcpi_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end + + cpu_state_exec: begin + reg_out <= reg_pc + decoded_imm; + if ((TWO_CYCLE_ALU || TWO_CYCLE_COMPARE) && (alu_wait || alu_wait_2)) begin + mem_do_rinst <= mem_do_prefetch && !alu_wait_2; + alu_wait <= alu_wait_2; + end else + if (is_beq_bne_blt_bge_bltu_bgeu) begin + latched_rd <= 0; + latched_store <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + latched_branch <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + if (mem_done) + cpu_state <= cpu_state_fetch; + if (TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0) begin + decoder_trigger <= 0; + set_mem_do_rinst = 1; + end + end else begin + latched_branch <= instr_jalr; + latched_store <= 1; + latched_stalu <= 1; + cpu_state <= cpu_state_fetch; + end + end + + cpu_state_shift: begin + latched_store <= 1; + if (reg_sh == 0) begin + reg_out <= reg_op1; + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_fetch; + end else if (TWO_STAGE_SHIFT && reg_sh >= 4) begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 4; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 4; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 4; + endcase + reg_sh <= reg_sh - 4; + end else begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 1; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 1; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 1; + endcase + reg_sh <= reg_sh - 1; + end + end + + cpu_state_stmem: begin + if (ENABLE_TRACE) + reg_out <= reg_op2; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_wdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_sb: mem_wordsize <= 2; + instr_sh: mem_wordsize <= 1; + instr_sw: mem_wordsize <= 0; + endcase + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_wdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + cpu_state <= cpu_state_fetch; + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + end + end + end + + cpu_state_ldmem: begin + latched_store <= 1; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_rdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_lb || instr_lbu: mem_wordsize <= 2; + instr_lh || instr_lhu: mem_wordsize <= 1; + instr_lw: mem_wordsize <= 0; + endcase + latched_is_lu <= is_lbu_lhu_lw; + latched_is_lh <= instr_lh; + latched_is_lb <= instr_lb; + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_rdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + (* parallel_case, full_case *) + case (1'b1) + latched_is_lu: reg_out <= mem_rdata_word; + latched_is_lh: reg_out <= $signed(mem_rdata_word[15:0]); + latched_is_lb: reg_out <= $signed(mem_rdata_word[7:0]); + endcase + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + cpu_state <= cpu_state_fetch; + end + end + end + endcase + + if (CATCH_MISALIGN && resetn && (mem_do_rdata || mem_do_wdata)) begin + if (mem_wordsize == 0 && reg_op1[1:0] != 0) begin + `debug($display("MISALIGNED WORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (mem_wordsize == 1 && reg_op1[0] != 0) begin + `debug($display("MISALIGNED HALFWORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + end + if (CATCH_MISALIGN && resetn && mem_do_rinst && (COMPRESSED_ISA ? reg_pc[0] : |reg_pc[1:0])) begin + `debug($display("MISALIGNED INSTRUCTION: 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (!CATCH_ILLINSN && decoder_trigger_q && !decoder_pseudo_trigger_q && instr_ecall_ebreak) begin + cpu_state <= cpu_state_trap; + end + + if (!resetn || mem_done) begin + mem_do_prefetch <= 0; + mem_do_rinst <= 0; + mem_do_rdata <= 0; + mem_do_wdata <= 0; + end + + if (set_mem_do_rinst) + mem_do_rinst <= 1; + if (set_mem_do_rdata) + mem_do_rdata <= 1; + if (set_mem_do_wdata) + mem_do_wdata <= 1; + + irq_pending <= next_irq_pending & ~MASKED_IRQ; + + if (!CATCH_MISALIGN) begin + if (COMPRESSED_ISA) begin + reg_pc[0] <= 0; + reg_next_pc[0] <= 0; + end else begin + reg_pc[1:0] <= 0; + reg_next_pc[1:0] <= 0; + end + end + current_pc = 'bx; + end + +`ifdef RISCV_FORMAL + reg dbg_irq_call; + reg dbg_irq_enter; + reg [31:0] dbg_irq_ret; + always @(posedge clk) begin + rvfi_valid <= resetn && (launch_next_insn || trap) && dbg_valid_insn; + rvfi_order <= resetn ? rvfi_order + rvfi_valid : 0; + + rvfi_insn <= dbg_insn_opcode; + rvfi_rs1_addr <= dbg_rs1val_valid ? dbg_insn_rs1 : 0; + rvfi_rs2_addr <= dbg_rs2val_valid ? dbg_insn_rs2 : 0; + rvfi_pc_rdata <= dbg_insn_addr; + rvfi_rs1_rdata <= dbg_rs1val_valid ? dbg_rs1val : 0; + rvfi_rs2_rdata <= dbg_rs2val_valid ? dbg_rs2val : 0; + rvfi_trap <= trap; + rvfi_halt <= trap; + rvfi_intr <= dbg_irq_enter; + rvfi_mode <= 3; + rvfi_ixl <= 1; + + if (!resetn) begin + dbg_irq_call <= 0; + dbg_irq_enter <= 0; + end else + if (rvfi_valid) begin + dbg_irq_call <= 0; + dbg_irq_enter <= dbg_irq_call; + end else + if (irq_state == 1) begin + dbg_irq_call <= 1; + dbg_irq_ret <= next_pc; + end + + if (!resetn) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end else + if (cpuregs_write && !irq_state) begin +`ifdef PICORV32_TESTBUG_003 + rvfi_rd_addr <= latched_rd ^ 1; +`else + rvfi_rd_addr <= latched_rd; +`endif +`ifdef PICORV32_TESTBUG_004 + rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata ^ 1 : 0; +`else + rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata : 0; +`endif + end else + if (rvfi_valid) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + + casez (dbg_insn_opcode) + 32'b 0000000_?????_000??_???_?????_0001011: begin // getq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + 32'b 0000001_?????_?????_???_000??_0001011: begin // setq + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + 32'b 0000010_?????_00000_???_00000_0001011: begin // retirq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + endcase + + if (!dbg_irq_call) begin + if (dbg_mem_instr) begin + rvfi_mem_addr <= 0; + rvfi_mem_rmask <= 0; + rvfi_mem_wmask <= 0; + rvfi_mem_rdata <= 0; + rvfi_mem_wdata <= 0; + end else + if (dbg_mem_valid && dbg_mem_ready) begin + rvfi_mem_addr <= dbg_mem_addr; + rvfi_mem_rmask <= dbg_mem_wstrb ? 0 : ~0; + rvfi_mem_wmask <= dbg_mem_wstrb; + rvfi_mem_rdata <= dbg_mem_rdata; + rvfi_mem_wdata <= dbg_mem_wdata; + end + end + end + + always @* begin +`ifdef PICORV32_TESTBUG_005 + rvfi_pc_wdata = (dbg_irq_call ? dbg_irq_ret : dbg_insn_addr) ^ 4; +`else + rvfi_pc_wdata = dbg_irq_call ? dbg_irq_ret : dbg_insn_addr; +`endif + + rvfi_csr_mcycle_rmask = 0; + rvfi_csr_mcycle_wmask = 0; + rvfi_csr_mcycle_rdata = 0; + rvfi_csr_mcycle_wdata = 0; + + rvfi_csr_minstret_rmask = 0; + rvfi_csr_minstret_wmask = 0; + rvfi_csr_minstret_rdata = 0; + rvfi_csr_minstret_wdata = 0; + + if (rvfi_valid && rvfi_insn[6:0] == 7'b 1110011 && rvfi_insn[13:12] == 3'b010) begin + if (rvfi_insn[31:20] == 12'h C00) begin + rvfi_csr_mcycle_rmask = 64'h 0000_0000_FFFF_FFFF; + rvfi_csr_mcycle_rdata = {32'h 0000_0000, rvfi_rd_wdata}; + end + if (rvfi_insn[31:20] == 12'h C80) begin + rvfi_csr_mcycle_rmask = 64'h FFFF_FFFF_0000_0000; + rvfi_csr_mcycle_rdata = {rvfi_rd_wdata, 32'h 0000_0000}; + end + if (rvfi_insn[31:20] == 12'h C02) begin + rvfi_csr_minstret_rmask = 64'h 0000_0000_FFFF_FFFF; + rvfi_csr_minstret_rdata = {32'h 0000_0000, rvfi_rd_wdata}; + end + if (rvfi_insn[31:20] == 12'h C82) begin + rvfi_csr_minstret_rmask = 64'h FFFF_FFFF_0000_0000; + rvfi_csr_minstret_rdata = {rvfi_rd_wdata, 32'h 0000_0000}; + end + end + end +`endif + + // Formal Verification +`ifdef FORMAL + reg [3:0] last_mem_nowait; + always @(posedge clk) + last_mem_nowait <= {last_mem_nowait, mem_ready || !mem_valid}; + + // stall the memory interface for max 4 cycles + restrict property (|last_mem_nowait || mem_ready || !mem_valid); + + // resetn low in first cycle, after that resetn high + restrict property (resetn != $initstate); + + // this just makes it much easier to read traces. uncomment as needed. + // assume property (mem_valid || !mem_ready); + + reg ok; + always @* begin + if (resetn) begin + // instruction fetches are read-only + if (mem_valid && mem_instr) + assert (mem_wstrb == 0); + + // cpu_state must be valid + ok = 0; + if (cpu_state == cpu_state_trap) ok = 1; + if (cpu_state == cpu_state_fetch) ok = 1; + if (cpu_state == cpu_state_ld_rs1) ok = 1; + if (cpu_state == cpu_state_ld_rs2) ok = !ENABLE_REGS_DUALPORT; + if (cpu_state == cpu_state_exec) ok = 1; + if (cpu_state == cpu_state_shift) ok = 1; + if (cpu_state == cpu_state_stmem) ok = 1; + if (cpu_state == cpu_state_ldmem) ok = 1; + assert (ok); + end + end + + reg last_mem_la_read = 0; + reg last_mem_la_write = 0; + reg [31:0] last_mem_la_addr; + reg [31:0] last_mem_la_wdata; + reg [3:0] last_mem_la_wstrb = 0; + + always @(posedge clk) begin + last_mem_la_read <= mem_la_read; + last_mem_la_write <= mem_la_write; + last_mem_la_addr <= mem_la_addr; + last_mem_la_wdata <= mem_la_wdata; + last_mem_la_wstrb <= mem_la_wstrb; + + if (last_mem_la_read) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wstrb == 0); + end + if (last_mem_la_write) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wdata == last_mem_la_wdata); + assert(mem_wstrb == last_mem_la_wstrb); + end + if (mem_la_read || mem_la_write) begin + assert(!mem_valid || mem_ready); + end + end +`endif +endmodule + +// This is a simple example implementation of PICORV32_REGS. +// Use the PICORV32_REGS mechanism if you want to use custom +// memory resources to implement the processor register file. +// Note that your implementation must match the requirements of +// the PicoRV32 configuration. (e.g. QREGS, etc) +module picorv32_regs ( + input clk, wen, + input [5:0] waddr, + input [5:0] raddr1, + input [5:0] raddr2, + input [31:0] wdata, + output [31:0] rdata1, + output [31:0] rdata2 +); + reg [31:0] regs [0:30]; + + always @(posedge clk) + if (wen) regs[~waddr[4:0]] <= wdata; + + assign rdata1 = regs[~raddr1[4:0]]; + assign rdata2 = regs[~raddr2[4:0]]; +endmodule + + +/*************************************************************** + * picorv32_pcpi_mul + ***************************************************************/ + +module picorv32_pcpi_mul #( + parameter STEPS_AT_ONCE = 1, + parameter CARRY_CHAIN = 4 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg pcpi_wait_q; + wire mul_start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_mul <= 0; + instr_mulh <= 0; + instr_mulhsu <= 0; + instr_mulhu <= 0; + + if (resetn && pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul <= 1; + 3'b001: instr_mulh <= 1; + 3'b010: instr_mulhsu <= 1; + 3'b011: instr_mulhu <= 1; + endcase + end + + pcpi_wait <= instr_any_mul; + pcpi_wait_q <= pcpi_wait; + end + + reg [63:0] rs1, rs2, rd, rdx; + reg [63:0] next_rs1, next_rs2, this_rs2; + reg [63:0] next_rd, next_rdx, next_rdt; + reg [6:0] mul_counter; + reg mul_waiting; + reg mul_finish; + integer i, j; + + // carry save accumulator + always @* begin + next_rd = rd; + next_rdx = rdx; + next_rs1 = rs1; + next_rs2 = rs2; + + for (i = 0; i < STEPS_AT_ONCE; i=i+1) begin + this_rs2 = next_rs1[0] ? next_rs2 : 0; + if (CARRY_CHAIN == 0) begin + next_rdt = next_rd ^ next_rdx ^ this_rs2; + next_rdx = ((next_rd & next_rdx) | (next_rd & this_rs2) | (next_rdx & this_rs2)) << 1; + next_rd = next_rdt; + end else begin + next_rdt = 0; + for (j = 0; j < 64; j = j + CARRY_CHAIN) + {next_rdt[j+CARRY_CHAIN-1], next_rd[j +: CARRY_CHAIN]} = + next_rd[j +: CARRY_CHAIN] + next_rdx[j +: CARRY_CHAIN] + this_rs2[j +: CARRY_CHAIN]; + next_rdx = next_rdt << 1; + end + next_rs1 = next_rs1 >> 1; + next_rs2 = next_rs2 << 1; + end + end + + always @(posedge clk) begin + mul_finish <= 0; + if (!resetn) begin + mul_waiting <= 1; + end else + if (mul_waiting) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + + rd <= 0; + rdx <= 0; + mul_counter <= (instr_any_mulh ? 63 - STEPS_AT_ONCE : 31 - STEPS_AT_ONCE); + mul_waiting <= !mul_start; + end else begin + rd <= next_rd; + rdx <= next_rdx; + rs1 <= next_rs1; + rs2 <= next_rs2; + + mul_counter <= mul_counter - STEPS_AT_ONCE; + if (mul_counter[6]) begin + mul_finish <= 1; + mul_waiting <= 1; + end + end + end + + always @(posedge clk) begin + pcpi_wr <= 0; + pcpi_ready <= 0; + if (mul_finish && resetn) begin + pcpi_wr <= 1; + pcpi_ready <= 1; + pcpi_rd <= instr_any_mulh ? rd >> 32 : rd; + end + end +endmodule + +module picorv32_pcpi_fast_mul #( + parameter EXTRA_MUL_FFS = 0, + parameter EXTRA_INSN_FFS = 0, + parameter MUL_CLKGATE = 0 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output pcpi_wr, + output [31:0] pcpi_rd, + output pcpi_wait, + output pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg shift_out; + reg [3:0] active; + reg [32:0] rs1, rs2, rs1_q, rs2_q; + reg [63:0] rd, rd_q; + + wire pcpi_insn_valid = pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001; + reg pcpi_insn_valid_q; + + always @* begin + instr_mul = 0; + instr_mulh = 0; + instr_mulhsu = 0; + instr_mulhu = 0; + + if (resetn && (EXTRA_INSN_FFS ? pcpi_insn_valid_q : pcpi_insn_valid)) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul = 1; + 3'b001: instr_mulh = 1; + 3'b010: instr_mulhsu = 1; + 3'b011: instr_mulhu = 1; + endcase + end + end + + always @(posedge clk) begin + pcpi_insn_valid_q <= pcpi_insn_valid; + if (!MUL_CLKGATE || active[0]) begin + rs1_q <= rs1; + rs2_q <= rs2; + end + if (!MUL_CLKGATE || active[1]) begin + rd <= $signed(EXTRA_MUL_FFS ? rs1_q : rs1) * $signed(EXTRA_MUL_FFS ? rs2_q : rs2); + end + if (!MUL_CLKGATE || active[2]) begin + rd_q <= rd; + end + end + + always @(posedge clk) begin + if (instr_any_mul && !(EXTRA_MUL_FFS ? active[3:0] : active[1:0])) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + active[0] <= 1; + end else begin + active[0] <= 0; + end + + active[3:1] <= active; + shift_out <= instr_any_mulh; + + if (!resetn) + active <= 0; + end + + assign pcpi_wr = active[EXTRA_MUL_FFS ? 3 : 1]; + assign pcpi_wait = 0; + assign pcpi_ready = active[EXTRA_MUL_FFS ? 3 : 1]; +`ifdef RISCV_FORMAL_ALTOPS + assign pcpi_rd = + instr_mul ? (pcpi_rs1 + pcpi_rs2) ^ 32'h5876063e : + instr_mulh ? (pcpi_rs1 + pcpi_rs2) ^ 32'hf6583fb7 : + instr_mulhsu ? (pcpi_rs1 - pcpi_rs2) ^ 32'hecfbe137 : + instr_mulhu ? (pcpi_rs1 + pcpi_rs2) ^ 32'h949ce5e8 : 1'bx; +`else + assign pcpi_rd = shift_out ? (EXTRA_MUL_FFS ? rd_q : rd) >> 32 : (EXTRA_MUL_FFS ? rd_q : rd); +`endif +endmodule + + +/*************************************************************** + * picorv32_pcpi_div + ***************************************************************/ + +module picorv32_pcpi_div ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_div, instr_divu, instr_rem, instr_remu; + wire instr_any_div_rem = |{instr_div, instr_divu, instr_rem, instr_remu}; + + reg pcpi_wait_q; + wire start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_div <= 0; + instr_divu <= 0; + instr_rem <= 0; + instr_remu <= 0; + + if (resetn && pcpi_valid && !pcpi_ready && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b100: instr_div <= 1; + 3'b101: instr_divu <= 1; + 3'b110: instr_rem <= 1; + 3'b111: instr_remu <= 1; + endcase + end + + pcpi_wait <= instr_any_div_rem && resetn; + pcpi_wait_q <= pcpi_wait && resetn; + end + + reg [31:0] dividend; + reg [62:0] divisor; + reg [31:0] quotient; + reg [31:0] quotient_msk; + reg running; + reg outsign; + + always @(posedge clk) begin + pcpi_ready <= 0; + pcpi_wr <= 0; + pcpi_rd <= 'bx; + + if (!resetn) begin + running <= 0; + end else + if (start) begin + running <= 1; + dividend <= (instr_div || instr_rem) && pcpi_rs1[31] ? -pcpi_rs1 : pcpi_rs1; + divisor <= ((instr_div || instr_rem) && pcpi_rs2[31] ? -pcpi_rs2 : pcpi_rs2) << 31; + outsign <= (instr_div && (pcpi_rs1[31] != pcpi_rs2[31]) && |pcpi_rs2) || (instr_rem && pcpi_rs1[31]); + quotient <= 0; + quotient_msk <= 1 << 31; + end else + if (!quotient_msk && running) begin + running <= 0; + pcpi_ready <= 1; + pcpi_wr <= 1; +`ifdef RISCV_FORMAL_ALTOPS + case (1) + instr_div: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h7f8529ec; + instr_divu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h10e8fd70; + instr_rem: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h8da68fa5; + instr_remu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h3138d0e1; + endcase +`else + if (instr_div || instr_divu) + pcpi_rd <= outsign ? -quotient : quotient; + else + pcpi_rd <= outsign ? -dividend : dividend; +`endif + end else begin + if (divisor <= dividend) begin + dividend <= dividend - divisor; + quotient <= quotient | quotient_msk; + end + divisor <= divisor >> 1; +`ifdef RISCV_FORMAL_ALTOPS + quotient_msk <= quotient_msk >> 5; +`else + quotient_msk <= quotient_msk >> 1; +`endif + end + end +endmodule + + +/*************************************************************** + * picorv32_axi + ***************************************************************/ + +module picorv32_axi #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output trap, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + wire mem_instr; + wire mem_ready; + wire [31:0] mem_rdata; + + picorv32_axi_adapter axi_adapter ( + .clk (clk ), + .resetn (resetn ), + .mem_axi_awvalid(mem_axi_awvalid), + .mem_axi_awready(mem_axi_awready), + .mem_axi_awaddr (mem_axi_awaddr ), + .mem_axi_awprot (mem_axi_awprot ), + .mem_axi_wvalid (mem_axi_wvalid ), + .mem_axi_wready (mem_axi_wready ), + .mem_axi_wdata (mem_axi_wdata ), + .mem_axi_wstrb (mem_axi_wstrb ), + .mem_axi_bvalid (mem_axi_bvalid ), + .mem_axi_bready (mem_axi_bready ), + .mem_axi_arvalid(mem_axi_arvalid), + .mem_axi_arready(mem_axi_arready), + .mem_axi_araddr (mem_axi_araddr ), + .mem_axi_arprot (mem_axi_arprot ), + .mem_axi_rvalid (mem_axi_rvalid ), + .mem_axi_rready (mem_axi_rready ), + .mem_axi_rdata (mem_axi_rdata ), + .mem_valid (mem_valid ), + .mem_instr (mem_instr ), + .mem_ready (mem_ready ), + .mem_addr (mem_addr ), + .mem_wdata (mem_wdata ), + .mem_wstrb (mem_wstrb ), + .mem_rdata (mem_rdata ) + ); + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); +endmodule + + +/*************************************************************** + * picorv32_axi_adapter + ***************************************************************/ + +module picorv32_axi_adapter ( + input clk, resetn, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Native PicoRV32 memory interface + + input mem_valid, + input mem_instr, + output mem_ready, + input [31:0] mem_addr, + input [31:0] mem_wdata, + input [ 3:0] mem_wstrb, + output [31:0] mem_rdata +); + reg ack_awvalid; + reg ack_arvalid; + reg ack_wvalid; + reg xfer_done; + + assign mem_axi_awvalid = mem_valid && |mem_wstrb && !ack_awvalid; + assign mem_axi_awaddr = mem_addr; + assign mem_axi_awprot = 0; + + assign mem_axi_arvalid = mem_valid && !mem_wstrb && !ack_arvalid; + assign mem_axi_araddr = mem_addr; + assign mem_axi_arprot = mem_instr ? 3'b100 : 3'b000; + + assign mem_axi_wvalid = mem_valid && |mem_wstrb && !ack_wvalid; + assign mem_axi_wdata = mem_wdata; + assign mem_axi_wstrb = mem_wstrb; + + assign mem_ready = mem_axi_bvalid || mem_axi_rvalid; + assign mem_axi_bready = mem_valid && |mem_wstrb; + assign mem_axi_rready = mem_valid && !mem_wstrb; + assign mem_rdata = mem_axi_rdata; + + always @(posedge clk) begin + if (!resetn) begin + ack_awvalid <= 0; + end else begin + xfer_done <= mem_valid && mem_ready; + if (mem_axi_awready && mem_axi_awvalid) + ack_awvalid <= 1; + if (mem_axi_arready && mem_axi_arvalid) + ack_arvalid <= 1; + if (mem_axi_wready && mem_axi_wvalid) + ack_wvalid <= 1; + if (xfer_done || !mem_valid) begin + ack_awvalid <= 0; + ack_arvalid <= 0; + ack_wvalid <= 0; + end + end + end +endmodule + + +/*************************************************************** + * picorv32_wb + ***************************************************************/ + +module picorv32_wb #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + output trap, + + // Wishbone interfaces + input wb_rst_i, + input wb_clk_i, + + output reg [31:0] wbm_adr_o, + output reg [31:0] wbm_dat_o, + input [31:0] wbm_dat_i, + output reg wbm_we_o, + output reg [3:0] wbm_sel_o, + output reg wbm_stb_o, + input wbm_ack_i, + output reg wbm_cyc_o, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data, + + output mem_instr +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + reg mem_ready; + reg [31:0] mem_rdata; + + wire clk; + wire resetn; + + assign clk = wb_clk_i; + assign resetn = ~wb_rst_i; + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); + + localparam IDLE = 2'b00; + localparam WBSTART = 2'b01; + localparam WBEND = 2'b10; + + reg [1:0] state; + + wire we; + assign we = (mem_wstrb[0] | mem_wstrb[1] | mem_wstrb[2] | mem_wstrb[3]); + + always @(posedge wb_clk_i) begin + if (wb_rst_i) begin + wbm_adr_o <= 0; + wbm_dat_o <= 0; + wbm_we_o <= 0; + wbm_sel_o <= 0; + wbm_stb_o <= 0; + wbm_cyc_o <= 0; + state <= IDLE; + end else begin + case (state) + IDLE: begin + if (mem_valid) begin + wbm_adr_o <= mem_addr; + wbm_dat_o <= mem_wdata; + wbm_we_o <= we; + wbm_sel_o <= mem_wstrb; + + wbm_stb_o <= 1'b1; + wbm_cyc_o <= 1'b1; + state <= WBSTART; + end else begin + mem_ready <= 1'b0; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBSTART:begin + if (wbm_ack_i) begin + mem_rdata <= wbm_dat_i; + mem_ready <= 1'b1; + + state <= WBEND; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBEND: begin + mem_ready <= 1'b0; + + state <= IDLE; + end + default: + state <= IDLE; + endcase + end + end +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/reset_generator.v b/dan-rodrigues_icestation-32/hardware/reset_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..e4b81a755d1821728ea0aa2b2bf9f5ef56a061be --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/reset_generator.v @@ -0,0 +1,53 @@ +// reset_generator.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module reset_generator #( + parameter integer DURATION_EXPONENT = 8 +) ( + input clk_1x, + input clk_2x, + input pll_locked, + + // (TODO: an actual user reset input, presumably from a button or otherwise) + + output reg reset_1x = 1, + output reg reset_2x = 1 +); + reg pll_locked_r; + + always @(negedge clk_2x) begin + pll_locked_r <= pll_locked; + end + + reg [DURATION_EXPONENT:0] counter = 0; + + reg reset = 1; + + always @(negedge clk_2x) begin + if (!pll_locked_r) begin + counter <= 0; + reset <= 1; + end else begin + if (!counter[DURATION_EXPONENT]) begin + counter <= counter + 1; + end else if (!clk_1x) begin + // ensure that both reset_1x and reset_2x occur on the same rising edge + reset <= 0; + end + end + end + + always @(posedge clk_1x) begin + reset_1x <= reset; + end + + always @(posedge clk_2x) begin + reset_2x <= reset; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/dacpwm.v b/dan-rodrigues_icestation-32/hardware/ulx3s/dacpwm.v new file mode 100644 index 0000000000000000000000000000000000000000..d7e0702d98fe3c6b110a1691d749e1a5973ddd17 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/dacpwm.v @@ -0,0 +1,44 @@ +// This module is originally from this repo: +// https://github.com/emard/ulx3s-misc/tree/master/examples/audio/hdl + +// combines resistor DAC and PWM +// upper bits using DAC, lower bit using PWM + +module dacpwm +#( + parameter C_pcm_bits = 12, // input: how many bits PCM (including sign bit) + parameter C_dac_bits = 4 // output: how many bits DAC output, unsigned +) +( + input clk, // required to run PWM + input signed [C_pcm_bits-1:0] pcm, // 12-bit signed PCM input + output [C_dac_bits-1:0] dac // 4-bit unsigned DAC output +); + parameter C_pwm_bits = C_pcm_bits-C_dac_bits; // how many bits for PWM that increases DAC resolution + + // generate 2 DAC output optional values: PCM+0 and PCM+1 + reg [C_dac_bits-1:0] R_dac0, R_dac1; + reg [C_pwm_bits-1:0] R_pcm_low; + always @(posedge clk) + begin + R_dac0 <= { ~pcm[C_pcm_bits-1], pcm[C_pcm_bits-2:C_pcm_bits-C_dac_bits]}; + R_dac1 <= { ~pcm[C_pcm_bits-1], pcm[C_pcm_bits-2:C_pcm_bits-C_dac_bits]} + 1; + R_pcm_low <= pcm[C_pwm_bits-1:0]; + end + + // constantly running PWM counter + reg [C_pwm_bits-1:0] R_pwm_counter; + always @(posedge clk) + R_pwm_counter <= R_pwm_counter + 1; // constantly running + + // the comparator + // using PWM to switch between dac0 and dac1 + reg [C_dac_bits-1:0] R_dac_output; + always @(posedge clk) + begin + R_dac_output <= R_pwm_counter >= R_pcm_low ? R_dac0 : R_dac1; + end + + assign dac = R_dac_output; +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/esp32_spi_gamepad.v b/dan-rodrigues_icestation-32/hardware/ulx3s/esp32_spi_gamepad.v new file mode 100644 index 0000000000000000000000000000000000000000..b88a5e0424e8491539d69a40407ef17842ad5761 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/esp32_spi_gamepad.v @@ -0,0 +1,74 @@ +// esp32_spi_gamepad.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module esp32_spi_gamepad #( + parameter integer PAD_BUTTONS = 12 +) ( + input clk, + input reset, + + // ESP32 reset support + + input user_reset, + output esp32_en, + output esp32_gpio0, + output esp32_gpio12, + + // SPI gamepad input + + input spi_csn, + input spi_clk, + input spi_mosi, + + output reg [PAD_BUTTONS - 1:0] pad_btn +); + localparam PAD_WIDTH = PAD_BUTTONS - 1; + + // --- ESP32 resetting --- + + assign esp32_en = !user_reset; + + // ESP32 "strapping pins" for boot: + // MTDI (GPIO12) apparently has pull down in ESP32 but still need this for whatever reason + // Serial console shows ESP32 stuck in reset loop otherwise + + // GPIO0 = 1 (SPI flash boot, instead of serial bootloader) + assign esp32_gpio0 = 1; + + // MTDI = 0 (VDD_SDIO = 3.3v, instead of 1.8v) + assign esp32_gpio12 = 0; + + // --- SPI gamepad --- + + reg spi_clk_r; + reg spi_csn_r; + + reg [PAD_WIDTH:0] receive_buffer; + + wire spi_csn_rose = spi_csn && !spi_csn_r; + wire spi_csn_fell = !spi_csn && spi_csn_r; + wire spi_clk_rose = spi_clk && !spi_clk_r; + + always @(posedge clk) begin + if (reset) begin + pad_btn <= 0; + spi_clk_r <= 0; + spi_csn_r <= 1; + end else begin + spi_clk_r <= spi_clk; + spi_csn_r <= spi_csn; + + if (!spi_csn && spi_clk_rose) begin + receive_buffer <= {spi_mosi, receive_buffer[PAD_WIDTH:1]}; + end else if (spi_csn_rose) begin + pad_btn <= receive_buffer; + end + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_25.v b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_25.v new file mode 100644 index 0000000000000000000000000000000000000000..55392d1eda0447f5191823de8010e526b84024b8 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_25.v @@ -0,0 +1,60 @@ +// diamond 3.7 accepts this PLL +// diamond 3.8-3.9 is untested +// diamond 3.10 or higher is likely to abort with error about unable to use feedback signal +// cause of this could be from wrong CPHASE/FPHASE parameters +module generated_pll_25 +( + input clkin, // 25 MHz, 0 deg + output clkout0, // 125 MHz, 0 deg + output clkout2, // 25 MHz, 0 deg + output clkout3, // 12.5 MHz, 0 deg + output locked +); +(* FREQUENCY_PIN_CLKI="25" *) +(* FREQUENCY_PIN_CLKOP="125" *) +(* FREQUENCY_PIN_CLKOS2="25" *) +(* FREQUENCY_PIN_CLKOS3="12.5" *) +(* ICP_CURRENT="12" *) (* LPF_RESISTOR="8" *) (* MFG_ENABLE_FILTEROPAMP="1" *) (* MFG_GMCREF_SEL="2" *) +EHXPLLL #( + .PLLRST_ENA("DISABLED"), + .INTFB_WAKE("DISABLED"), + .STDBY_ENABLE("DISABLED"), + .DPHASE_SOURCE("DISABLED"), + .OUTDIVIDER_MUXA("DIVA"), + .OUTDIVIDER_MUXB("DIVB"), + .OUTDIVIDER_MUXC("DIVC"), + .OUTDIVIDER_MUXD("DIVD"), + .CLKI_DIV(1), + .CLKOP_ENABLE("ENABLED"), + .CLKOP_DIV(5), + .CLKOP_CPHASE(2), + .CLKOP_FPHASE(0), + .CLKOS2_ENABLE("ENABLED"), + .CLKOS2_DIV(25), + .CLKOS2_CPHASE(2), + .CLKOS2_FPHASE(0), + .CLKOS3_ENABLE("ENABLED"), + .CLKOS3_DIV(50), + .CLKOS3_CPHASE(2), + .CLKOS3_FPHASE(0), + .FEEDBK_PATH("CLKOP"), + .CLKFB_DIV(5) + ) pll_i ( + .RST(1'b0), + .STDBY(1'b0), + .CLKI(clkin), + .CLKOP(clkout0), + .CLKOS2(clkout2), + .CLKOS3(clkout3), + .CLKFB(clkout0), + .CLKINTFB(), + .PHASESEL0(1'b0), + .PHASESEL1(1'b0), + .PHASEDIR(1'b1), + .PHASESTEP(1'b1), + .PHASELOADREG(1'b1), + .PLLWAKESYNC(1'b0), + .ENCLKOP(1'b0), + .LOCK(locked) + ); +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_33_75.v b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_33_75.v new file mode 100644 index 0000000000000000000000000000000000000000..7e1a088e3b539b2150af8aa900d84ecdab2629a3 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_33_75.v @@ -0,0 +1,60 @@ +// diamond 3.7 accepts this PLL +// diamond 3.8-3.9 is untested +// diamond 3.10 or higher is likely to abort with error about unable to use feedback signal +// cause of this could be from wrong CPHASE/FPHASE parameters +module generated_pll_33_75 +( + input clkin, // 25 MHz, 0 deg + output clkout0, // 168.75 MHz, 0 deg + output clkout2, // 33.75 MHz, 0 deg + output clkout3, // 16.875 MHz, 0 deg + output locked +); +(* FREQUENCY_PIN_CLKI="25" *) +(* FREQUENCY_PIN_CLKOP="168.75" *) +(* FREQUENCY_PIN_CLKOS2="33.75" *) +(* FREQUENCY_PIN_CLKOS3="16.875" *) +(* ICP_CURRENT="12" *) (* LPF_RESISTOR="8" *) (* MFG_ENABLE_FILTEROPAMP="1" *) (* MFG_GMCREF_SEL="2" *) +EHXPLLL #( + .PLLRST_ENA("DISABLED"), + .INTFB_WAKE("DISABLED"), + .STDBY_ENABLE("DISABLED"), + .DPHASE_SOURCE("DISABLED"), + .OUTDIVIDER_MUXA("DIVA"), + .OUTDIVIDER_MUXB("DIVB"), + .OUTDIVIDER_MUXC("DIVC"), + .OUTDIVIDER_MUXD("DIVD"), + .CLKI_DIV(4), + .CLKOP_ENABLE("ENABLED"), + .CLKOP_DIV(4), + .CLKOP_CPHASE(2), + .CLKOP_FPHASE(0), + .CLKOS2_ENABLE("ENABLED"), + .CLKOS2_DIV(20), + .CLKOS2_CPHASE(2), + .CLKOS2_FPHASE(0), + .CLKOS3_ENABLE("ENABLED"), + .CLKOS3_DIV(40), + .CLKOS3_CPHASE(2), + .CLKOS3_FPHASE(0), + .FEEDBK_PATH("CLKOP"), + .CLKFB_DIV(27) + ) pll_i ( + .RST(1'b0), + .STDBY(1'b0), + .CLKI(clkin), + .CLKOP(clkout0), + .CLKOS2(clkout2), + .CLKOS3(clkout3), + .CLKFB(clkout0), + .CLKINTFB(), + .PHASESEL0(1'b0), + .PHASESEL1(1'b0), + .PHASEDIR(1'b1), + .PHASESTEP(1'b1), + .PHASELOADREG(1'b1), + .PLLWAKESYNC(1'b0), + .ENCLKOP(1'b0), + .LOCK(locked) + ); +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_usb.v b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_usb.v new file mode 100644 index 0000000000000000000000000000000000000000..0bea5ec7d51c6f27c8df34b343bb1aabfd2c8959 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/generated_pll_usb.v @@ -0,0 +1,53 @@ +// diamond 3.7 accepts this PLL +// diamond 3.8-3.9 is untested +// diamond 3.10 or higher is likely to abort with error about unable to use feedback signal +// cause of this could be from wrong CPHASE/FPHASE parameters +module generated_pll_usb +( + input clkin, // 25 MHz, 0 deg + output clkout0, // 60 MHz, 0 deg + output clkout1, // 6 MHz, 0 deg + output locked +); +(* FREQUENCY_PIN_CLKI="25" *) +(* FREQUENCY_PIN_CLKOP="60" *) +(* FREQUENCY_PIN_CLKOS="6" *) +(* ICP_CURRENT="12" *) (* LPF_RESISTOR="8" *) (* MFG_ENABLE_FILTEROPAMP="1" *) (* MFG_GMCREF_SEL="2" *) +EHXPLLL #( + .PLLRST_ENA("DISABLED"), + .INTFB_WAKE("DISABLED"), + .STDBY_ENABLE("DISABLED"), + .DPHASE_SOURCE("DISABLED"), + .OUTDIVIDER_MUXA("DIVA"), + .OUTDIVIDER_MUXB("DIVB"), + .OUTDIVIDER_MUXC("DIVC"), + .OUTDIVIDER_MUXD("DIVD"), + .CLKI_DIV(5), + .CLKOP_ENABLE("ENABLED"), + .CLKOP_DIV(10), + .CLKOP_CPHASE(4), + .CLKOP_FPHASE(0), + .CLKOS_ENABLE("ENABLED"), + .CLKOS_DIV(100), + .CLKOS_CPHASE(4), + .CLKOS_FPHASE(0), + .FEEDBK_PATH("CLKOP"), + .CLKFB_DIV(12) + ) pll_i ( + .RST(1'b0), + .STDBY(1'b0), + .CLKI(clkin), + .CLKOP(clkout0), + .CLKOS(clkout1), + .CLKFB(clkout0), + .CLKINTFB(), + .PHASESEL0(1'b0), + .PHASESEL1(1'b0), + .PHASEDIR(1'b1), + .PHASESTEP(1'b1), + .PHASELOADREG(1'b1), + .PLLWAKESYNC(1'b0), + .ENCLKOP(1'b0), + .LOCK(locked) + ); +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/hdmi_encoder.v b/dan-rodrigues_icestation-32/hardware/ulx3s/hdmi_encoder.v new file mode 100644 index 0000000000000000000000000000000000000000..593af5c55cd9ab7bf0d05b28cdd74efddff5ec6a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/hdmi_encoder.v @@ -0,0 +1,110 @@ +// This module provides HDMI suitable output from VGA-like input +// Original repo: https://github.com/emard/ulx3s_zx_spectrum/blob/master/src/hdmi.v + +module hdmi_encoder( + input wire pixel_clk, + input wire pixel_clk_x5, + input wire [7:0] red, green, blue, + input wire vde, hsync, vsync, + output wire [3:0] gpdi_dp, gpdi_dn +); + + // 10b8b TMDS encoding of RGB and Sync + // + wire [9:0] TMDS_red, TMDS_green, TMDS_blue; + TMDS_encoder encode_R(.clk(pixel_clk), .VD(red ), .CD(2'b00) , .VDE(vde), .TMDS(TMDS_red)); + TMDS_encoder encode_G(.clk(pixel_clk), .VD(green), .CD(2'b00) , .VDE(vde), .TMDS(TMDS_green)); + TMDS_encoder encode_B(.clk(pixel_clk), .VD(blue ), .CD({vsync,hsync}), .VDE(vde), .TMDS(TMDS_blue)); + + // shift out 10 bits each pix clock (2 DDR bits at a 5x rate) + // + reg [2:0] ctr_mod5 = 0; + reg shift_ld = 0; + + always @(posedge pixel_clk_x5) + begin + shift_ld <= (ctr_mod5==4'd4); + ctr_mod5 <= (ctr_mod5==4'd4) ? 4'd0 : ctr_mod5 + 4'd1; + end + + reg [9:0] shift_R = 0, shift_G = 0, shift_B = 0, shift_C = 0; + + always @(posedge pixel_clk_x5) + begin + shift_R <= shift_ld ? TMDS_red : shift_R[9:2]; + shift_G <= shift_ld ? TMDS_green : shift_G[9:2]; + shift_B <= shift_ld ? TMDS_blue : shift_B[9:2]; + shift_C <= shift_ld ? 10'h3e0 : shift_C[9:2]; + end + +`ifdef __ICARUS__ + // (pseudo-) differential DDR driver (pure verilog version) + // + assign gpdi_dp[3] = pixel_clk_x5 ? shift_C[0] : shift_C[1]; + assign gpdi_dp[2] = pixel_clk_x5 ? shift_R[0] : shift_R[1]; + assign gpdi_dp[1] = pixel_clk_x5 ? shift_G[0] : shift_G[1]; + assign gpdi_dp[0] = pixel_clk_x5 ? shift_B[0] : shift_B[1]; + + assign gpdi_dn = ~ gpdi_dp; +`else + // (pseudo-) differential DDR driver (ECP5 synthesis version) + //* + ODDRX1F ddr3p( .Q(gpdi_dp[3]), .SCLK(pixel_clk_x5), .D0(shift_C[0]), .D1(shift_C[1]), .RST(0) ); + ODDRX1F ddr2p( .Q(gpdi_dp[2]), .SCLK(pixel_clk_x5), .D0(shift_R[0]), .D1(shift_R[1]), .RST(0) ); + ODDRX1F ddr1p( .Q(gpdi_dp[1]), .SCLK(pixel_clk_x5), .D0(shift_G[0]), .D1(shift_G[1]), .RST(0) ); + ODDRX1F ddr0p( .Q(gpdi_dp[0]), .SCLK(pixel_clk_x5), .D0(shift_B[0]), .D1(shift_B[1]), .RST(0) ); + + ODDRX1F ddr3n( .Q(gpdi_dn[3]), .SCLK(pixel_clk_x5), .D0(~shift_C[0]), .D1(~shift_C[1]), .RST(0) ); + ODDRX1F ddr2n( .Q(gpdi_dn[2]), .SCLK(pixel_clk_x5), .D0(~shift_R[0]), .D1(~shift_R[1]), .RST(0) ); + ODDRX1F ddr1n( .Q(gpdi_dn[1]), .SCLK(pixel_clk_x5), .D0(~shift_G[0]), .D1(~shift_G[1]), .RST(0) ); + ODDRX1F ddr0n( .Q(gpdi_dn[0]), .SCLK(pixel_clk_x5), .D0(~shift_B[0]), .D1(~shift_B[1]), .RST(0) ); +`endif + +endmodule + + +// DVI-D 10b8b TMDS encoder module +// +module TMDS_encoder( + input clk, // pix clock + input [7:0] VD, // video data (red, green or blue) + input [1:0] CD, // control data + input VDE, // video data enable, to choose between CD (when VDE=0) and VD (when VDE=1) + output reg [9:0] TMDS = 0 +); + + reg [3:0] dc_bias = 0; + + // compute data word + wire [3:0] ones = VD[0] + VD[1] + VD[2] + VD[3] + VD[4] + VD[5] + VD[6] + VD[7]; + wire XNOR = (ones>4'd4) || (ones==4'd4 && VD[0]==1'b0); + wire [8:0] dw; + assign dw[8] = ~XNOR; + assign dw[7] = dw[6] ^ VD[7] ^ XNOR; + assign dw[6] = dw[5] ^ VD[6] ^ XNOR; + assign dw[5] = dw[4] ^ VD[5] ^ XNOR; + assign dw[4] = dw[3] ^ VD[4] ^ XNOR; + assign dw[3] = dw[2] ^ VD[3] ^ XNOR; + assign dw[2] = dw[1] ^ VD[2] ^ XNOR; + assign dw[1] = dw[0] ^ VD[1] ^ XNOR; + assign dw[0] = VD[0]; + + // calculate 1/0 disparity & invert as needed to minimize dc bias + wire [3:0] dw_disp = dw[0] + dw[1] + dw[2] + dw[3] + dw[4] + dw[5] + dw[6] + dw[7] + 4'b1100; + wire sign_eq = (dw_disp[3] == dc_bias[3]); + + wire [3:0] delta = dw_disp - ({dw[8] ^ ~sign_eq} & ~(dw_disp==0 || dc_bias==0)); + wire inv_dw = (dw_disp==0 || dc_bias==0) ? ~dw[8] : sign_eq; + + wire [3:0] dc_bias_d = inv_dw ? dc_bias - delta : dc_bias + delta; + + // set output signals + wire [9:0] TMDS_data = { inv_dw, dw[8], dw[7:0] ^ {8{inv_dw}} }; + wire [9:0] TMDS_code = CD[1] ? (CD[0] ? 10'b1010101011 : 10'b0101010100) + : (CD[0] ? 10'b0010101011 : 10'b1101010100); + + always @(posedge clk) TMDS <= VDE ? TMDS_data : TMDS_code; + always @(posedge clk) dc_bias <= VDE ? dc_bias_d : 0; + +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/ics32_top_ulx3s.v b/dan-rodrigues_icestation-32/hardware/ulx3s/ics32_top_ulx3s.v new file mode 100644 index 0000000000000000000000000000000000000000..e9353d028ba8f46ebea7197871e634b5fd7326df --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/ics32_top_ulx3s.v @@ -0,0 +1,385 @@ +// ics32_top_ulx3s.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "clocks.vh" + +module ics32_top_ulx3s #( + // Set to one of "PCB", "USB" or "BLUETOOTH" + parameter GAMEPAD_SOURCE = "PCB", + + // Selects USB gamepad HID report decoder + // Ignored if (GAMEPAD_SOURCE != "USB") + parameter USB_GAMEPAD = "BUFFALO", + + parameter [0:0] GAMEPAD_LED = 0, + parameter [0:0] ENABLE_WIDESCREEN = 1, + parameter [0:0] ENABLE_FAST_CPU = 0 +) ( + input clk_25mhz, + + output [3:0] gpdi_dp, + output [3:0] gpdi_dn, + + output [3:0] audio_l, + output [3:0] audio_r, + output [3:0] audio_v, + + output [7:0] led, + + input [6:0] btn, + + output flash_csn, + inout [3:0] flash_io, + + input usb_fpga_dp, + inout usb_fpga_bd_dp, + inout usb_fpga_bd_dn, + output usb_fpga_pu_dp, + output usb_fpga_pu_dn, + + output wifi_en, + output wifi_gpio0, + output wifi_gpio12, + + input wifi_gpio4, + input wifi_gpio16, + input wifi_gpio2 +); + // --- Clocks --- + + localparam integer CLK_2X_FREQ = ENABLE_WIDESCREEN ? `CLK_2X_WIDESCREEN : `CLK_2X_STANDARD; + localparam integer CLK_1X_FREQ = ENABLE_WIDESCREEN ? `CLK_1X_WIDESCREEN : `CLK_1X_STANDARD; + + // --- ECP5 PLL (640x480 or 848x480 clock selection) --- + + // Main PLL: + + wire clk_1x, clk_2x, clk_10x; + wire pll_locked; + + pll_ecp5 #( + .ENABLE_FAST_CLK(ENABLE_WIDESCREEN) + ) pll_main ( + .clk_25m(clk_25mhz), + + .locked(pll_locked), + .clk_1x(clk_1x), + .clk_2x(clk_2x), + .clk_10x(clk_10x) + ); + + // USB PLL (6MHz): + + wire clk_usb; + wire pll_locked_usb; + + generated_pll_usb pll_usb ( + .clkin(clk_25mhz), + + .clkout1(clk_usb), + .locked(pll_locked_usb) + ); + + // --- HDMI --- + + hdmi_encoder hdmi( + .pixel_clk(clk_2x), + .pixel_clk_x5(clk_10x), + + .red({2{vga_r}}), + .green({2{vga_g}}), + .blue({2{vga_b}}), + + .vde(vga_de), + .hsync(vga_hsync), + .vsync(vga_vsync), + + .gpdi_dp(gpdi_dp), + .gpdi_dn(gpdi_dn) + ); + + // --- DAC --- + + // SPDIF: + + wire [15:0] spdif_selected_sample = spdif_channel_select ? audio_output_r_valid : audio_output_l_valid; + wire [23:0] spdif_pcm_in = {spdif_selected_sample, 8'b0}; + + wire spdif; + wire spdif_channel_select; + assign audio_v = {2'b00, spdif, 1'b0}; + + spdif_tx #( + .C_clk_freq(CLK_2X_FREQ), + .C_sample_freq(44100) + ) spdif_tx ( + .clk(clk_2x), + .data_in(spdif_pcm_in), + .address_out(spdif_channel_select), + .spdif_out(spdif) + ); + + // Analog: + + reg [15:0] audio_output_l_valid, audio_output_r_valid; + + always @(posedge clk_2x) begin + if (audio_output_valid) begin + audio_output_l_valid <= audio_output_l; + audio_output_r_valid <= audio_output_r; + end + end + + dacpwm #( + .C_pcm_bits(16), + .C_dac_bits(4) + ) dacpwm [1:0] ( + .clk(clk_2x), + + .pcm({audio_output_l_valid, audio_output_r_valid}), + .dac({audio_l, audio_r}) + ); + + // --- ECP5 Flash IO --- + + wire [3:0] flash_out; + wire [3:0] flash_in_en; + wire [3:0] flash_in; + + // Flash bidirectional IO + + wire [3:0] flash_out_r; + wire [3:0] flash_in_en_r; + wire [3:0] flash_in_r; + + (* BEL="X11/Y93/SLICEA" *) TRELLIS_SLICE flash_in_r_0 ( + .CLK(clk_2x), + .M0(flash_in[0]), .M1(flash_in[1]), + .Q0(flash_in_r[0]), .Q1(flash_in_r[1]) + ); + + (* BEL="X11/Y93/SLICEB" *) TRELLIS_SLICE flash_in_r_1 ( + .CLK(clk_2x), + .M0(flash_in[2]), .M1(flash_in[3]), + .Q0(flash_in_r[2]), .Q1(flash_in_r[3]) + ); + + (* BEL="X11/Y93/SLICEC" *) TRELLIS_SLICE flash_in_en_r_0 ( + .CLK(clk_2x), + .M0(~flash_in_en[0]), .M1(~flash_in_en[1]), + .Q0(flash_in_en_r[0]), .Q1(flash_in_en_r[1]) + ); + + (* BEL="X11/Y93/SLICED" *) TRELLIS_SLICE flash_in_en_r_1 ( + .CLK(clk_2x), + .M0(~flash_in_en[2]), .M1(~flash_in_en[3]), + .Q0(flash_in_en_r[2]), .Q1(flash_in_en_r[3]) + ); + + (* BEL="X9/Y93/SLICEA" *) TRELLIS_SLICE flash_out_r_0 ( + .CLK(clk_2x), + .M0(flash_out[0]), .M1(flash_out[1]), + .Q0(flash_out_r[0]), .Q1(flash_out_r[1]), + ); + + (* BEL="X9/Y93/SLICEB" *) TRELLIS_SLICE flash_out_r_1 ( + .CLK(clk_2x), + .M0(flash_out[2]), .M1(flash_out[3]), + .Q0(flash_out_r[2]), .Q1(flash_out_r[3]), + ); + + BB flash_io_bb[3:0] ( + .I(flash_in_r), + .T(flash_in_en_r), + .O(flash_out), + .B(flash_io) + ); + + // Flash CSN + + wire flash_csn_r; + + (* BEL="X15/Y93/SLICEA" *) TRELLIS_SLICE flash_csn_r_0 ( + .CLK(clk_2x), + .M0(flash_csn_io), + .Q0(flash_csn_r) + ); + + OB flash_csn_ob( + .I(flash_csn_r), + .O(flash_csn) + ); + + // SPI CLK + + // * The ECP5 SPI clock must be controlled with USRMCLK + // * DDR primitive can't be used with USRMCLK + // * There is no built in supported to route a global clock USRMCLK + + wire [1:0] flash_clk_ddr_r; + wire flash_clk_out = clk_2x ? flash_clk_ddr_r[0] : flash_clk_ddr_r[1]; + + (* BEL="X2/Y93/SLICEA" *) TRELLIS_SLICE ddr_ff_0 ( + .CLK(clk_2x), + .M0(flash_clk_ddr[0]), + .Q0(flash_clk_ddr_r[0]) + ); + + (* BEL="X2/Y92/SLICEA" *) TRELLIS_SLICE #(.CLKMUX("INV")) ddr_ff_1 ( + .CLK(clk_2x), + .M0(flash_clk_ddr[1]), + .Q0(flash_clk_ddr_r[1]) + ); + + USRMCLK spi_clk ( + .USRMCLKI(flash_clk_out), + .USRMCLKTS(1'b0) + ); + + // --- Gamepad reading --- + + wire [11:0] pad_btn; + wire [1:0] pad_read_data; + + // P1 is supported using the gamepad_state instance below + + mock_gamepad mock_gamepad( + .clk(clk_2x), + + .pad_clk(pad_clk), + .pad_btn(pad_btn), + .pad_latch(pad_latch), + + .pad_out(pad_read_data[0]) + ); + + // P2 currently not supported on ULX3S + + assign pad_read_data[1] = 0; + + // The mock_gamepad above is driven by gamepad data from one of the sources below. + // GAMEPAD_SOURCE is used to detmine which one: + + wire user_button; + + ulx3s_gamepad_state #( + .GAMEPAD_SOURCE(GAMEPAD_SOURCE), + .USB_GAMEPAD(USB_GAMEPAD) + ) gamepad_state ( + .clk(clk_2x), + .reset(reset_2x), + + // ESP32: + + .esp32_en(wifi_en), + .esp32_gpio0(wifi_gpio0), + .esp32_gpio12(wifi_gpio12), + + .esp32_gpio2(wifi_gpio2), + .esp32_gpio16(wifi_gpio16), + .esp32_gpio4(wifi_gpio4), + + // USB: + + .clk_usb(clk_usb), + .usb_reset(!pll_locked_usb), + + .usb_dif(usb_fpga_dp), + .usb_dp(usb_fpga_bd_dp), + .usb_dn(usb_fpga_bd_dn), + + .usb_pu_dp(usb_fpga_pu_dp), + .usb_pu_dn(usb_fpga_pu_dn), + + // PCB: + + .btn(btn), + + // Selected gamepad state: + + .pad_btn(pad_btn) + ); + + // Unlike the gamepads, user button input is always provided by PCB + // btn[0] is shared with the ESP32 reset if (GAMEPAD_SOURCE == "BLUETOOTH") + + wire user_button; + + debouncer #( + .BTN_COUNT(1) + ) user_button_debouncer ( + .clk(clk_2x), + .reset(reset_2x), + + .btn(!btn[0]), + .level(user_button) + ); + + // --- icestation-32 --- + + assign led = GAMEPAD_LED ? pad_btn : status_led; + + wire reset_1x, reset_2x; + + wire flash_csn_io; + wire [1:0] flash_clk_ddr; + + wire [3:0] vga_r, vga_g, vga_b; + wire vga_de, vga_vsync, vga_hsync; + + wire audio_output_valid; + wire [15:0] audio_output_l, audio_output_r; + + wire pad_latch, pad_clk; + + wire [7:0] status_led; + + ics32 #( + .CLK_1X_FREQ(CLK_1X_FREQ), + .CLK_2X_FREQ(CLK_2X_FREQ), + .ENABLE_WIDESCREEN(ENABLE_WIDESCREEN), + .ENABLE_FAST_CPU(ENABLE_FAST_CPU), + .RESET_DURATION_EXPONENT(24), + .ENABLE_BOOTLOADER(1), + .BOOTLOADER_SIZE(512) + ) ics32 ( + .clk_1x(clk_1x), + .clk_2x(clk_2x), + .pll_locked(pll_locked), + + .reset_1x(reset_1x), + .reset_2x(reset_2x), + + .vga_r(vga_r), + .vga_g(vga_g), + .vga_b(vga_b), + + .vga_de(vga_de), + .vga_hsync(vga_hsync), + .vga_vsync(vga_vsync), + + .pad_latch(pad_latch), + .pad_clk(pad_clk), + .pad_data(pad_read_data), + + .user_button(user_button), + + .led(status_led), + + .flash_clk_ddr(flash_clk_ddr), + .flash_csn(flash_csn_io), + .flash_in_en(flash_in_en), + .flash_in(flash_in), + .flash_out(flash_out_r), + + .audio_output_l(audio_output_l), + .audio_output_r(audio_output_r), + .audio_output_valid(audio_output_valid) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/pll_ecp5.v b/dan-rodrigues_icestation-32/hardware/ulx3s/pll_ecp5.v new file mode 100644 index 0000000000000000000000000000000000000000..818829e3f21688046b1e5bfba7ec4b5010703931 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/pll_ecp5.v @@ -0,0 +1,39 @@ +// pll_ecp5.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module pll_ecp5 #( + parameter ENABLE_FAST_CLK = 1 +) ( + input clk_25m, + + output locked, + output clk_1x, + output clk_2x, + output clk_10x +); + generate + if (ENABLE_FAST_CLK) begin + generated_pll_33_75 generated_pll( + .clkin(clk_25m), + .clkout0(clk_10x), + .clkout3(clk_1x), + .clkout2(clk_2x), + .locked(locked) + ); + end else begin + generated_pll_25 generated_pll( + .clkin(clk_25m), + .clkout0(clk_10x), + .clkout3(clk_1x), + .clkout2(clk_2x), + .locked(locked) + ); + end + endgenerate + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/spdif_tx.v b/dan-rodrigues_icestation-32/hardware/ulx3s/spdif_tx.v new file mode 100644 index 0000000000000000000000000000000000000000..045cba65786521a00e70e14612ca58ded6cb1c38 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/spdif_tx.v @@ -0,0 +1,155 @@ +// File hdl/spdif_tx.vhd translated with vhd2vl v3.0 VHDL to Verilog RTL translator +// vhd2vl settings: +// * Verilog Module Declaration Style: 2001 + +// vhd2vl is Free (libre) Software: +// Copyright (C) 2001 Vincenzo Liguori - Ocean Logic Pty Ltd +// http://www.ocean-logic.com +// Modifications Copyright (C) 2006 Mark Gonzales - PMC Sierra Inc +// Modifications (C) 2010 Shankar Giri +// Modifications Copyright (C) 2002-2017 Larry Doolittle +// http://doolittle.icarus.com/~larry/vhd2vl/ +// Modifications (C) 2017 Rodrigo A. Melo +// +// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting +// Verilog for correctness, ideally with a formal verification tool. +// +// You are welcome to redistribute vhd2vl under certain conditions. +// See the license (GPLv2) file included with the source for details. + +// The result of translation follows. Its copyright status should be +// considered unchanged from the original VHDL. + +// https://ackspace.nl/wiki/SP/DIF_transmitter_project +// EMARD's modification: phase accu clk divider +// no timescale needed + +module spdif_tx( +input wire clk, +input wire [23:0] data_in, +output reg address_out, +output wire spdif_out +); + +parameter [31:0] C_clk_freq=25000000; +parameter [31:0] C_sample_freq=48000; +// Hz sample rate +// system clock +// 24-bit signed value +// 1 address bit means stereo only + + + +// math to digitaly divide input clock into 128x Fsample (6.144MHz for 48K samplerate) +parameter C_phase_accu_bits = 24; //clock divider phase accumulator +// constant C_phase_increment: integer := C_sample_freq * 2**(C_phase_accu_bits+7) / C_clk_freq; -- exact expression but it overflows with trellis +parameter C_phase_increment = (C_sample_freq / 100) * 2 ** (C_phase_accu_bits - 3) / (C_clk_freq / 100) * 2 ** 10; // works with trellis up to C_clk_freq = 100 MHz +reg [C_phase_accu_bits - 1:0] R_phase_accu; +reg [1:0] R_clkdiv_shift; +reg [23:0] data_in_buffer; +reg [5:0] bit_counter = 1'b0; +reg [8:0] frame_counter = 1'b0; +reg data_biphase = 1'b0; +reg [7:0] data_out_buffer; +reg parity; +reg [23:0] channel_status_shift; +wire [23:0] channel_status = 24'b001000000000000001000000; + + always @(posedge clk) begin + R_phase_accu <= R_phase_accu + C_phase_increment; + R_clkdiv_shift <= {R_clkdiv_shift[0],R_phase_accu[C_phase_accu_bits - 1]}; + end + + always @(posedge clk) begin + if(R_clkdiv_shift == 2'b01) begin + bit_counter <= bit_counter + 1; + end + end + + always @(posedge clk) begin + if(R_clkdiv_shift == 2'b01) begin + parity <= data_in_buffer[23] ^ data_in_buffer[22] ^ data_in_buffer[21] ^ data_in_buffer[20] ^ data_in_buffer[19] ^ data_in_buffer[18] ^ data_in_buffer[17] ^ data_in_buffer[16] ^ data_in_buffer[15] ^ data_in_buffer[14] ^ data_in_buffer[13] ^ data_in_buffer[12] ^ data_in_buffer[11] ^ data_in_buffer[10] ^ data_in_buffer[9] ^ data_in_buffer[8] ^ data_in_buffer[7] ^ data_in_buffer[6] ^ data_in_buffer[5] ^ data_in_buffer[4] ^ data_in_buffer[3] ^ data_in_buffer[2] ^ data_in_buffer[1] ^ data_in_buffer[0] ^ channel_status_shift[23]; + if(bit_counter == 6'b000011) begin + data_in_buffer <= data_in; + end + if(bit_counter == 6'b111111) begin + if(frame_counter == 9'b101111111) begin + frame_counter <= {9{1'b0}}; + end + else begin + frame_counter <= frame_counter + 1; + end + end + end + end + + always @(posedge clk) begin + if(R_clkdiv_shift == 2'b01) begin + if(bit_counter == 6'b111111) begin + if(frame_counter == 9'b101111111) begin + // next frame is 0, load preamble Z + address_out <= 1'b0; + channel_status_shift <= channel_status; + data_out_buffer <= 8'b10011100; + end + else begin + if(frame_counter[0] == 1'b1) begin + // next frame is even, load preamble X + channel_status_shift <= {channel_status_shift[22:0],1'b0}; + data_out_buffer <= 8'b10010011; + address_out <= 1'b0; + end + else begin + // next frame is odd, load preable Y + data_out_buffer <= 8'b10010110; + address_out <= 1'b1; + end + end + end + else begin + if(bit_counter[2:0] == 3'b111) begin + // load new part of data into buffer + case(bit_counter[5:3]) + 3'b000 : begin + data_out_buffer <= {1'b1,data_in_buffer[0],1'b1,data_in_buffer[1],1'b1,data_in_buffer[2],1'b1,data_in_buffer[3]}; + end + 3'b001 : begin + data_out_buffer <= {1'b1,data_in_buffer[4],1'b1,data_in_buffer[5],1'b1,data_in_buffer[6],1'b1,data_in_buffer[7]}; + end + 3'b010 : begin + data_out_buffer <= {1'b1,data_in_buffer[8],1'b1,data_in_buffer[9],1'b1,data_in_buffer[10],1'b1,data_in_buffer[11]}; + end + 3'b011 : begin + data_out_buffer <= {1'b1,data_in_buffer[12],1'b1,data_in_buffer[13],1'b1,data_in_buffer[14],1'b1,data_in_buffer[15]}; + end + 3'b100 : begin + data_out_buffer <= {1'b1,data_in_buffer[16],1'b1,data_in_buffer[17],1'b1,data_in_buffer[18],1'b1,data_in_buffer[19]}; + end + 3'b101 : begin + data_out_buffer <= {1'b1,data_in_buffer[20],1'b1,data_in_buffer[21],1'b1,data_in_buffer[22],1'b1,data_in_buffer[23]}; + end + 3'b110 : begin + data_out_buffer <= {5'b10101,channel_status_shift[23],1'b1,parity}; + end + default : begin + end + endcase + end + else begin + data_out_buffer <= {data_out_buffer[6:0],1'b0}; + end + end + end + end + + always @(posedge clk) begin + if(R_clkdiv_shift == 2'b01) begin + if(data_out_buffer[(7)] == 1'b1) begin + data_biphase <= ~data_biphase; + end + end + end + + assign spdif_out = data_biphase; + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/ulx3s/ulx3s_gamepad_state.v b/dan-rodrigues_icestation-32/hardware/ulx3s/ulx3s_gamepad_state.v new file mode 100644 index 0000000000000000000000000000000000000000..071e29df9ea26726fbb601c40cae958a5bd63428 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/ulx3s/ulx3s_gamepad_state.v @@ -0,0 +1,141 @@ +// ulx3s_gamepad_state.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module ulx3s_gamepad_state #( + // Set to one of "PCB", "USB" or "BLUETOOTH" + parameter GAMEPAD_SOURCE = "PCB", + parameter USB_GAMEPAD = "BUFFALO" +) ( + input clk, + input reset, + + // ESP32: + + output esp32_en, + output esp32_gpio0, + output esp32_gpio12, + + input esp32_gpio2, + input esp32_gpio16, + input esp32_gpio4, + + // USB: + + input clk_usb, + input usb_reset, + + input usb_dif, + inout usb_dp, + inout usb_dn, + + output usb_pu_dp, + output usb_pu_dn, + + // PCB: + + input [6:0] btn, + + // Selected gamepad state: + + output [11:0] pad_btn +); + generate + if (GAMEPAD_SOURCE == "BLUETOOTH") begin + // ESP32 + Bluetooth gamepads + + // Inputs: + + reg [2:0] esp_sync_ff [0:1]; + + wire esp_spi_mosi = esp_sync_ff[1][2]; + wire esp_spi_clk = esp_sync_ff[1][1]; + wire esp_spi_csn = esp_sync_ff[1][0]; + + always @(posedge clk) begin + esp_sync_ff[1] <= esp_sync_ff[0]; + esp_sync_ff[0] <= {esp32_gpio4, esp32_gpio16, esp32_gpio2}; + end + + // Debouncer (only needed for ESP32 reset): + + wire esp32_reset; + + debouncer #( + .BTN_COUNT(1) + ) esp32_reset_debouncer ( + .clk(clk), + .reset(reset), + + .btn(!btn[0]), + .level(esp32_reset) + ); + + // SPI gamepad reader: + + esp32_spi_gamepad esp32_spi_gamepad( + .clk(clk), + .reset(reset), + + .user_reset(esp32_reset), + .esp32_en(esp32_en), + .esp32_gpio0(esp32_gpio0), + .esp32_gpio12(esp32_gpio12), + + .spi_csn(esp_spi_csn), + .spi_clk(esp_spi_clk), + .spi_mosi(esp_spi_mosi), + + .pad_btn(pad_btn) + ); + end else begin + // Keep ESP32 enabled for programming through WiFi: + + assign esp32_en = 1; + assign esp32_gpio0 = 1; + + if (GAMEPAD_SOURCE == "USB") begin + // USB gamepad (US2): + + assign usb_pu_dp = 1'b0; + assign usb_pu_dn = 1'b0; + + wire [11:0] usb_btn; + + usb_gamepad_reader #( + .GAMEPAD(USB_GAMEPAD) + ) usb_gamepad_reader ( + .clk(clk_usb), + .reset(usb_reset), + + .usb_dif(usb_dif), + .usb_dp(usb_dp), + .usb_dn(usb_dn), + + .usb_btn(usb_btn) + ); + + reg [11:0] buttons_sync_ff [0:1]; + assign pad_btn = buttons_sync_ff[1]; + + always @(posedge clk) begin + buttons_sync_ff[1] <= buttons_sync_ff[0]; + buttons_sync_ff[0] <= usb_btn; + end + end else if (GAMEPAD_SOURCE == "PCB") begin + // PCB buttons: + + assign pad_btn = {btn[6], btn[5], btn[4], btn[3], 1'b0, !btn[0], btn[1], btn[2]}; + end else begin + // GAMEPAD_SOURCE not set correctly so error out. + // Doesn't seem to be a nicer way to do this in Verilog-2005 + non_existant_module GAMEPAD_SOURCE_INVALID_PARAMETER(); + end + end + endgenerate + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/gamepads/usb_gamepad_reader.v b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usb_gamepad_reader.v new file mode 100644 index 0000000000000000000000000000000000000000..11837ffc1ee09498edf363ea6f16ad5d023c9289 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usb_gamepad_reader.v @@ -0,0 +1,67 @@ +`default_nettype none + +module usb_gamepad_reader #( + parameter GAMEPAD = "BUFFALO" +) ( + input clk, + input reset, + + input usb_dif, + inout usb_dp, + inout usb_dn, + + output [11:0] usb_btn +); + localparam C_report_bytes = 8; + + wire [C_report_bytes*8-1:0] S_report; + wire S_report_valid; + wire [7:0] usb_buttons; + + usbh_host_hid #( + .C_usb_speed(0), + .C_report_length(C_report_bytes), + .C_report_length_strict(0) + ) us2_hid_host ( + .clk(clk), + .bus_reset(reset), + .usb_dif(usb_dif), + .usb_dp(usb_dp), + .usb_dn(usb_dn), + .hid_report(S_report), + .hid_valid(S_report_valid) + ); + + generate + if (GAMEPAD == "BUFFALO") begin + usbh_report_decoder_buffalo usbh_report_decoder( + .i_clk(clk), + .i_report(S_report), + .i_report_valid(S_report_valid), + .o_btn(usb_btn) + ); + end + + if (GAMEPAD == "KEYPAD") begin + usbh_report_decoder_keypad usbh_report_decoder( + .i_clk(clk), + .i_report(S_report), + .i_report_valid(S_report_valid), + .o_btn(usb_btn) + ); + end + + if (GAMEPAD == "WINGMAN") begin + usbh_report_decoder_wingman usbh_report_decoder( + .i_clk(clk), + .i_report(S_report), + .i_report_valid(S_report_valid), + .o_btn(usb_btn) + ); + end + + // (...more gamepads) + + endgenerate + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_buffalo.v b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_buffalo.v new file mode 100644 index 0000000000000000000000000000000000000000..b1ca97b8291d223471c64d57b51f55493a52a859 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_buffalo.v @@ -0,0 +1,37 @@ +// "BUFFALO Classic USB Gamepad" + +`default_nettype none + +module usbh_report_decoder_buffalo( + input wire i_clk, + input wire [63:0] i_report, + input wire i_report_valid, + output reg [11:0] o_btn +); + wire left = i_report[7:0] == 0; + wire right = i_report[7:0] == 8'hff; + wire up = i_report[15:8] == 0; + wire down = i_report[15:8] == 8'hff; + + wire a = i_report[16]; + wire b = i_report[17]; + wire x = i_report[18]; + wire y = i_report[19]; + + wire l = i_report[20]; + wire r = i_report[21]; + + wire select = i_report[22]; + wire start = i_report[23]; + + always @(posedge i_clk) begin + if (i_report_valid) begin + o_btn <= { + r, l, x, a, + right, left, down, up, + start, select, y, b + }; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_keypad.v b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_keypad.v new file mode 100644 index 0000000000000000000000000000000000000000..49cbd29f069f06b7e45386b5bcd84220b5f18802 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_keypad.v @@ -0,0 +1,80 @@ +// usbh_report_decoder_keypad.v: Generic USB keyboard keypad +// +// Copyright (C) 2020 Mara "vmedea" +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +// HID report layout: +// +// [7:0] Modifier keys +// [15:8] Padding +// [23:16] Keycode 0 +// [31:24] Keycode 1 +// [39:32] Keycode 2 +// [47:40] Keycode 3 +// [55:48] Keycode 4 +// [63:56] Keycode 5 +// +module keycode_match #( + parameter [7:0] KEYCODE = 8'h00 +) ( + input wire [63:0] i_report, + output wire o_btn +); + wire [7:0] key0 = i_report[23:16]; + wire [7:0] key1 = i_report[31:24]; + wire [7:0] key2 = i_report[39:32]; + wire [7:0] key3 = i_report[47:40]; + wire [7:0] key4 = i_report[55:48]; + wire [7:0] key5 = i_report[63:56]; + + wire o_btn = key0 == KEYCODE | key1 == KEYCODE | key2 == KEYCODE | key3 == KEYCODE | key4 == KEYCODE | key5 == KEYCODE; +endmodule + +module usbh_report_decoder_keypad( + input wire i_clk, + input wire [63:0] i_report, + input wire i_report_valid, + output reg [11:0] o_btn +); + wire left, right, up, down, a, b, x, y, l, r, select, start; + + // Mimic Wii dance mat layout + // + // ┌───┬───┬───┐ + // │ B │ ↑ │ A │ + // ├───┼───┼───┤ + // │ ← │ │ → │ + // ├───┼───┼───┤ + // │ Y │ ↓ │ X │ + // └───┴───┴───┘ + + keycode_match #(.KEYCODE(8'h5c /* keypad 4 */)) m_left(.i_report(i_report), .o_btn(left)); + keycode_match #(.KEYCODE(8'h5e /* keypad 5 */)) m_right(.i_report(i_report), .o_btn(right)); + keycode_match #(.KEYCODE(8'h60 /* keypad 8 */)) m_up(.i_report(i_report), .o_btn(up)); + keycode_match #(.KEYCODE(8'h5a /* keypad 2 */)) m_down(.i_report(i_report), .o_btn(down)); + keycode_match #(.KEYCODE(8'h61 /* keypad 9 */)) m_a(.i_report(i_report), .o_btn(a)); + keycode_match #(.KEYCODE(8'h5f /* keypad 7 */)) m_b(.i_report(i_report), .o_btn(b)); + keycode_match #(.KEYCODE(8'h5b /* keypad 3 */)) m_x(.i_report(i_report), .o_btn(x)); + keycode_match #(.KEYCODE(8'h59 /* keypad 1 */)) m_y(.i_report(i_report), .o_btn(y)); + + keycode_match #(.KEYCODE(8'h62 /* keypad 0 */)) m_l(.i_report(i_report), .o_btn(l)); + keycode_match #(.KEYCODE(8'h63 /* keypad . */)) m_r(.i_report(i_report), .o_btn(r)); + + keycode_match #(.KEYCODE(8'h57 /* keypad + */)) m_select(.i_report(i_report), .o_btn(select)); + keycode_match #(.KEYCODE(8'h58 /* keypad ⏎ */)) m_start(.i_report(i_report), .o_btn(start)); + + always @(posedge i_clk) begin + if (i_report_valid) begin + o_btn <= { + r, l, x, a, + right, left, down, up, + start, select, y, b + }; + end + end + +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_wingman.v b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_wingman.v new file mode 100644 index 0000000000000000000000000000000000000000..4c49f7582f98db954178a7afa7c0f3475b95e7bc --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/gamepads/usbh_report_decoder_wingman.v @@ -0,0 +1,107 @@ +// 046d:c20a Logitech, Inc. WingMan RumblePad + +`default_nettype none + +module usbh_report_decoder_wingman( + input wire i_clk, + input wire [63:0] i_report, + input wire i_report_valid, + output reg [11:0] o_btn +); +// HID report layout: +// +// [7:0] Left stick X +// [15:8] Left stick Y +// [23:16] Throttle slider +// [31:24] Right stick X +// [39:32] Right stick Y +// [43:40] Hat (clockwise) +// [44] Button A +// [45] Button B +// [46] Button C +// [47] Button X +// [48] Button Y +// [49] Button Z +// [50] Button L +// [51] Button R +// [52] Button S +// [53] Application 1 +// [54] Application 2 +// [55] Application 3: Rumble +// [56] Application 4: Mode +// [57] Application 5 +// [58] Application 6 +// [59] Application 7 +// [60] Application 8 +// [61] Application 9 +// [62] Application 10 +// [63] Application 11 +// +// Hat switch values: +// +// LRUD +// 0 = up 0010 +// 1 = right-up 0110 +// 2 = right 0100 +// 3 = right-down 0101 +// 4 = down 0001 +// 5 = left-down 1001 +// 6 = left 1000 +// 7 = left-up 1010 +// 8 = unpressed 0000 +// +// Layout (Logitech): +// +// Z +// Y +// C +// X B +// +// A +// +// Layout (SNES): +// +// X A +// +// Select Start Y B +// +// Mapping: +// +// LEFT/RIGHT/UP/DOWN = Hat, ignore analog sticks for now +// A = B +// B = A +// X = Y +// Y = X +// L = L +// R = R +// Select = C +// Start = S +// + wire [3:0] hat = i_report[43:40]; + wire left = hat == 5 | hat == 6 | hat == 7; + wire right = hat == 1 | hat == 2 | hat == 3; + wire up = hat == 0 | hat == 1 | hat == 7; + wire down = hat == 3 | hat == 4 | hat == 5; + + wire a = i_report[45]; + wire b = i_report[44]; + wire x = i_report[48]; + wire y = i_report[47]; + + wire l = i_report[50]; + wire r = i_report[51]; + + wire select = i_report[46]; + wire start = i_report[52]; + + always @(posedge i_clk) begin + if (i_report_valid) begin + o_btn <= { + r, l, x, a, + right, left, down, up, + start, select, y, b + }; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/usb_phy.v b/dan-rodrigues_icestation-32/hardware/usb/usb_phy.v new file mode 100644 index 0000000000000000000000000000000000000000..43a982e70abfc70e8d04e84efad280025caac20a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usb_phy.v @@ -0,0 +1,217 @@ +// File ../../../../usb11_phy_vhdl/usb_phy.vhd translated with vhd2vl v3.0 VHDL to Verilog RTL translator +// vhd2vl settings: +// * Verilog Module Declaration Style: 2001 + +// vhd2vl is Free (libre) Software: +// Copyright (C) 2001 Vincenzo Liguori - Ocean Logic Pty Ltd +// http://www.ocean-logic.com +// Modifications Copyright (C) 2006 Mark Gonzales - PMC Sierra Inc +// Modifications (C) 2010 Shankar Giri +// Modifications Copyright (C) 2002-2017 Larry Doolittle +// http://doolittle.icarus.com/~larry/vhd2vl/ +// Modifications (C) 2017 Rodrigo A. Melo +// +// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting +// Verilog for correctness, ideally with a formal verification tool. +// +// You are welcome to redistribute vhd2vl under certain conditions. +// See the license (GPLv2) file included with the source for details. + +// The result of translation follows. Its copyright status should be +// considered unchanged from the original VHDL. + +//======================================================================================-- +// Verilog to VHDL conversion by Martin Neumann martin@neumnns-mail.de -- +// -- +// /////////////////////////////////////////////////////////////////// -- +// // // -- +// // USB 1.1 PHY // -- +// // // -- +// // // -- +// // Author: Rudolf Usselmann // -- +// // rudi@asics.ws // -- +// // // -- +// // // -- +// // Downloaded from: http://www.opencores.org/cores/usb_phy/ // -- +// // // -- +// /////////////////////////////////////////////////////////////////// -- +// // // -- +// // Copyright (C) 2000-2002 Rudolf Usselmann // -- +// // www.asics.ws // -- +// // rudi@asics.ws // -- +// // // -- +// // This source file may be used and distributed without // -- +// // restriction provided that this copyright statement is not // -- +// // removed from the file and that any derivative work contains // -- +// // the original copyright notice and the associated disclaimer. // -- +// // // -- +// // THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY // -- +// // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // -- +// // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // -- +// // FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR // -- +// // OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // -- +// // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // -- +// // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // -- +// // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // -- +// // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // -- +// // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // -- +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // -- +// // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // -- +// // POSSIBILITY OF SUCH DAMAGE. // -- +// // // -- +// /////////////////////////////////////////////////////////////////// -- +//======================================================================================-- +// no timescale needed + +module usb_phy( +input wire clk, +input wire rst, +input wire phy_tx_mode, +output wire usb_rst, +input wire rxd, +input wire rxdp, +input wire rxdn, +output wire txdp, +output wire txdn, +output wire txoe, +output wire ce_o, +output wire sync_err_o, +output wire bit_stuff_err_o, +output wire byte_err_o, +input wire LineCtrl_i, +input wire [7:0] DataOut_i, +input wire TxValid_i, +output wire TxReady_o, +output wire [7:0] DataIn_o, +output wire RxValid_o, +output wire RxActive_o, +output wire RxError_o, +output wire [1:0] LineState_o +); + +parameter usb_rst_det=1'b1; +// 48 MHz +// active low +// HIGH level for differential io mode (else single-ended) +// Transciever Interface +// clk recovery debug +// RX debug interface +// UTMI Interface +// 0: normal data TX, 1: line control (for low speed usb) +// byte_to_send or LineCtrl mode (see usb_tx_phy) + + + +//component usb_tx_phy +//port ( +// clk : in std_logic; +// rst : in std_logic; +// fs_ce : in std_logic; +// phy_mode : in std_logic; +// -- Transciever Interface +// txdp, txdn, txoe : out std_logic; +// -- UTMI Interface +// DataOut_i : in std_logic_vector(7 downto 0); +// TxValid_i : in std_logic; +// TxReady_o : out std_logic +//); +//end component; +// +//component usb_rx_phy +//port ( +// clk : in std_logic; +// rst : in std_logic; +// -- Transciever Interface +// fs_ce : out std_logic; +// rxd, rxdp, rxdn : in std_logic; +// -- UTMI Interface +// DataIn_o : out std_logic_vector(7 downto 0); +// RxValid_o : out std_logic; +// RxActive_o : out std_logic; +// RxError_o : out std_logic; +// RxEn_i : in std_logic; +// LineState : out std_logic_vector(1 downto 0) +//); +//end component; +wire [1:0] LineState; +wire fs_ce; +reg [4:0] rst_cnt; +wire txoe_out; +reg usb_rst_out = 1'b0; +wire reset; + + //======================================================================================-- + // Misc Logic -- + //======================================================================================-- + assign usb_rst = usb_rst_out; + assign LineState_o = LineState; + assign txoe = txoe_out; + //======================================================================================-- + // TX Phy -- + //======================================================================================-- + usb_tx_phy i_tx_phy( + .clk(clk), + .rst(rst), + .fs_ce(fs_ce), + .phy_mode(phy_tx_mode), + // Transciever Interface + .txdp(txdp), + .txdn(txdn), + .txoe(txoe_out), + // UTMI Interface + .LineCtrl_i(LineCtrl_i), + .DataOut_i(DataOut_i), + .TxValid_i(TxValid_i), + .TxReady_o(TxReady_o)); + + //======================================================================================-- + // RX Phy and DPLL -- + //======================================================================================-- + assign reset = ~rst; + usb_rx_phy E_rx_phy_emard( + .clk(clk), + .reset(reset), + .clk_recovered_edge(fs_ce), + // Transciever Interface + .usb_dif(rxd), + .usb_dp(rxdp), + .usb_dn(rxdn), + // UTMI Interface + .data(DataIn_o), + .valid(RxValid_o), + .rx_active(RxActive_o), + .rx_en(txoe_out), + .linestate(LineState)); + + assign RxError_o = 1'b0; + assign ce_o = fs_ce; + //======================================================================================-- + // Generate an USB Reset if we see SE0 for at least 2.5uS -- + //======================================================================================-- + generate if (usb_rst_det == 1'b1) begin: usb_rst_g + always @(posedge clk) begin + if(rst == 1'b0) begin + rst_cnt <= {5{1'b0}}; + end else begin + if(LineState != 2'b00) begin + rst_cnt <= {5{1'b0}}; + end + else if(usb_rst_out == 1'b0 && fs_ce == 1'b1) begin + rst_cnt <= rst_cnt + 1; + end + end + end + + always @(posedge clk) begin + if(rst_cnt == 5'b11111) begin + usb_rst_out <= 1'b1; + end + else begin + usb_rst_out <= 1'b0; + end + end + + end + endgenerate + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/usb_rx_phy.v b/dan-rodrigues_icestation-32/hardware/usb/usb_rx_phy.v new file mode 100644 index 0000000000000000000000000000000000000000..74d0151474b5fb07907de8c14445c68c1fe382ae --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usb_rx_phy.v @@ -0,0 +1,247 @@ +// File ../../../../usb11_phy_vhdl/usb_rx_phy.vhd translated with vhd2vl v3.0 VHDL to Verilog RTL translator +// vhd2vl settings: +// * Verilog Module Declaration Style: 2001 + +// vhd2vl is Free (libre) Software: +// Copyright (C) 2001 Vincenzo Liguori - Ocean Logic Pty Ltd +// http://www.ocean-logic.com +// Modifications Copyright (C) 2006 Mark Gonzales - PMC Sierra Inc +// Modifications (C) 2010 Shankar Giri +// Modifications Copyright (C) 2002-2017 Larry Doolittle +// http://doolittle.icarus.com/~larry/vhd2vl/ +// Modifications (C) 2017 Rodrigo A. Melo +// +// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting +// Verilog for correctness, ideally with a formal verification tool. +// +// You are welcome to redistribute vhd2vl under certain conditions. +// See the license (GPLv2) file included with the source for details. + +// The result of translation follows. Its copyright status should be +// considered unchanged from the original VHDL. + +// (c)EMARD +// License=GPL +// USB RX soft-core +// differential data correctly recovered +// it works as drop in phy replacement +// but receives data more reliable than old core +// signal timings are not exactly identical as old core +// note that reset has direct logic here and some signals +// are named differently +// no timescale needed + +module usb_rx_phy( +input wire clk, +input wire reset, +input wire usb_dif, +input wire usb_dp, +input wire usb_dn, +output wire [1:0] linestate, +output wire clk_recovered, +output wire clk_recovered_edge, +output wire rawdata, +input wire rx_en, +output wire rx_active, +output wire rx_error, +output wire valid, +output wire [7:0] data +); + +parameter [31:0] C_clk_input_hz=6000000; +parameter [31:0] C_clk_bit_hz=1500000; +parameter [31:0] C_PA_bits=8; +// phase accumulator bits, 8 is ok +// input clock and reset +// differential D+/D- input + + + +// entity +parameter C_PA_inc = 2 ** (C_PA_bits - 1) * C_clk_bit_hz / C_clk_input_hz; // default PA increment +// constant C_PA_phase: unsigned(C_PA_bits-2 downto 0) := +// ( +// C_PA_bits-2 => '0', -- 1/4 +// C_PA_bits-3 => '0', -- 1/8 +// C_PA_bits-4 => '0', -- 1/16 +// C_PA_bits-5 => '0', -- 1/32 +// others => '1' +// ); +parameter C_PA_compensate = C_PA_inc[C_PA_bits - 2:0] + C_PA_inc[C_PA_bits - 2:0] + C_PA_inc[C_PA_bits - 2:0]; +parameter C_PA_init = C_PA_compensate; +parameter C_valid_init = 8'h80; // (data'high => '1', others => '0'); -- adjusted (1 bit early) to split stream at byte boundary +parameter C_idlecnt_init = 7'b1000000; // (6 => '1', others => '0'); -- 6 data bits + 1 stuff bit +reg [C_PA_bits - 1:0] R_PA; +reg [1:0] R_dif_shift; +reg [1:0] R_clk_recovered_shift; +wire S_clk_recovered; +wire S_linebit; reg R_linebit_prev; wire S_bit; wire R_bit; +reg R_frame; +reg [7:0] R_data; reg [7:0] R_data_latch; +reg [7:0] R_valid = C_valid_init; +reg [1:0] R_linestate; reg [1:0] R_linestate_sync; +reg [1:0] R_linestate_prev; +reg [6:0] R_idlecnt = C_idlecnt_init; +reg R_preamble; +reg R_rxactive; +reg R_rx_en; +reg R_valid_prev; + + always @(posedge clk) begin + if((usb_dn == 1'b1 || usb_dp == 1'b1) && rx_en == 1'b1) begin + // during SE0, this avoids noise at differential input + R_dif_shift <= {usb_dif,R_dif_shift[(1):1]}; + end + R_clk_recovered_shift <= {S_clk_recovered,R_clk_recovered_shift[(1):1]}; + R_linestate <= {usb_dn,usb_dp}; + R_linestate_prev <= R_linestate; + R_rx_en <= rx_en; + end + + always @(posedge clk) begin + if(R_dif_shift[(1)] != R_dif_shift[((1)) - 1]) begin + R_PA[((C_PA_bits - 1)) - 1:0] <= C_PA_init[((C_PA_bits - 1)) - 1:0]; + end + else begin + R_PA <= R_PA + C_PA_inc; + end + end + + assign S_clk_recovered = R_PA[(C_PA_bits - 1)]; + assign clk_recovered = S_clk_recovered; + assign clk_recovered_edge = R_clk_recovered_shift[1] != S_clk_recovered ? 1'b1 : 1'b0; + // clk_recovered_edge <= '1' when R_clk_recovered_shift(1) /= S_clk_recovered or R_linestate = "00" else '0'; -- NOTE: allows clocking during SE0 + assign S_linebit = R_dif_shift[((1)) - 1]; + assign S_bit = ~(S_linebit ^ R_linebit_prev); + // process that just shifts data and skips stuffed bit + always @(posedge clk) begin + if(R_rx_en == 1'b1 && reset == 1'b0) begin + if(R_clk_recovered_shift[1] != S_clk_recovered) begin + // synchronous with recovered clock + if(R_linebit_prev == S_linebit) begin + R_idlecnt <= {R_idlecnt[0],R_idlecnt[(6):1]}; + // shift (used for stuffed bit removal) + end + else begin + R_idlecnt <= C_idlecnt_init; + // reset + end + R_linebit_prev <= S_linebit; + if((R_idlecnt[0] == 1'b0 && R_frame == 1'b1) || R_frame == 1'b0) begin + // skips stuffed bit if in the frame + if(R_linestate_sync == 2'b00) begin + R_data <= {8{1'b0}}; + // SE0 resets data to prevent restarting the frame from old shifted data + end + else begin + R_data <= {S_bit,R_data[(7):1]}; + // only payload bits, skips stuffed bit + end + end + if(R_frame == 1'b1 && R_valid[1] == 1'b1) begin + // timing early, gated to latch byte + // if R_frame = '1' then -- timing early + // if R_rxactive = '1' and R_valid(1) = '1' then -- timing exact but gated to latch byte + // if R_rxactive = '1' then -- timing exact, data exact + R_data_latch <= R_data; + // FIXME is there a better way (bit delay) than to register whole R_data byte + end + end + end + end + + always @(posedge clk) begin + if(R_rx_en == 1'b1 && reset == 1'b0) begin + if(R_clk_recovered_shift[1] != S_clk_recovered) begin + // synchronous with recovered clock + if(R_linestate_sync == 2'b00) begin + // SE0 -- single-ended detection of the end of frame + R_frame <= 1'b0; + R_valid <= {8{1'b0}}; + R_preamble <= 1'b0; + R_rxactive <= 1'b0; + end + else begin + if(R_frame == 1'b1) begin + // differential reading of the frame + if(R_preamble == 1'b1) begin + // wait for first preamble byte + if(R_data[((7)) - 1:((7)) - 6] == 6'b100000) begin + // 100000 detects end of preamble + R_preamble <= 1'b0; + R_valid <= C_valid_init; + R_rxactive <= 1'b1; + // timing 2 bits later + end + // exact timing: this makes the rxactive rise at the same time as orig phy + // if S_bit = '1' and R_data(R_data'high downto R_data'high-3) = "0000" then -- 10000 detects end of preamble early + // R_rxactive <= '1'; + // end if; + end + else begin + // after preamble is found, circular-shift "R_valid" register + if(R_idlecnt[0] == 1'b0) begin + // if stuffed bit is not expected + R_valid <= {R_valid[0],R_valid[(7):1]}; + end + else begin + // stuffed bit S_bit=0 is expected + if(S_bit == 1'b1) begin + // if stuffed bit is wrong (line probably idle) + R_valid <= {8{1'b0}}; + // drop frame + R_frame <= 1'b0; + R_rxactive <= 1'b0; + end + end + // skip stuffed bit + end + end + else begin + // R_frame = '0' + // if S_bit = '0' and R_data(R_data'high downto R_data'high-1) = "11" then -- exact timing differential detection of the start of frame + if(R_data[(7):((7)) - 5] == 6'b000111) begin + // later timing differential detection of the start of frame + R_frame <= 1'b1; + R_preamble <= 1'b1; + R_valid <= {8{1'b0}}; + R_rxactive <= 1'b0; + end + end + end + R_linestate_sync <= R_linestate; + end + // synchronous with recovered clock + end + else begin + // R_rx_en = '0' + R_valid <= {8{1'b0}}; + R_frame <= 1'b0; + R_rxactive <= 1'b0; + end + end + + assign data = R_data_latch; + // delayed 1 cycle in order to detect SE0 reliably + assign rawdata = R_linebit_prev; + assign linestate = R_linestate; + // timing 1 bit early + // linestate <= R_linestate_prev; -- exact timing to match timing with original + // rx_active <= R_rxactive; -- exact timing + assign rx_active = R_frame; + // timing early + assign rx_error = 1'b0; + //B_valid_1clk: block + //begin + always @(posedge clk) begin + R_valid_prev <= R_valid[0]; + end + + // valid <= '1' when R_valid_prev = '0' and R_valid(0) = '1' else '0'; -- single clk cycle + assign valid = R_valid[0] & ~R_valid_prev; + // single clk cycle + // valid <= R_valid(0); -- spans several clk cycles + //end block; +// architecture + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/usb_tx_phy.v b/dan-rodrigues_icestation-32/hardware/usb/usb_tx_phy.v new file mode 100644 index 0000000000000000000000000000000000000000..7ed23932c18ee790a774cde8668cc0c3cbe061f5 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usb_tx_phy.v @@ -0,0 +1,430 @@ +// File ../../../../usb11_phy_vhdl/usb_tx_phy.vhd translated with vhd2vl v3.0 VHDL to Verilog RTL translator +// vhd2vl settings: +// * Verilog Module Declaration Style: 2001 + +// vhd2vl is Free (libre) Software: +// Copyright (C) 2001 Vincenzo Liguori - Ocean Logic Pty Ltd +// http://www.ocean-logic.com +// Modifications Copyright (C) 2006 Mark Gonzales - PMC Sierra Inc +// Modifications (C) 2010 Shankar Giri +// Modifications Copyright (C) 2002-2017 Larry Doolittle +// http://doolittle.icarus.com/~larry/vhd2vl/ +// Modifications (C) 2017 Rodrigo A. Melo +// +// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting +// Verilog for correctness, ideally with a formal verification tool. +// +// You are welcome to redistribute vhd2vl under certain conditions. +// See the license (GPLv2) file included with the source for details. + +// The result of translation follows. Its copyright status should be +// considered unchanged from the original VHDL. + +//======================================================================================-- +// Verilog to VHDL conversion by Martin Neumann martin@neumnns-mail.de -- +// -- +// /////////////////////////////////////////////////////////////////// -- +// // // -- +// // USB 1.1 PHY // -- +// // TX // -- +// // // -- +// // // -- +// // Author: Rudolf Usselmann // -- +// // rudi@asics.ws // -- +// // // -- +// // // -- +// // Downloaded from: http://www.opencores.org/cores/usb_phy/ // -- +// // // -- +// /////////////////////////////////////////////////////////////////// -- +// // // -- +// // Copyright (C) 2000-2002 Rudolf Usselmann // -- +// // www.asics.ws // -- +// // rudi@asics.ws // -- +// // // -- +// // This source file may be used and distributed without // -- +// // restriction provided that this copyright statement is not // -- +// // removed from the file and that any derivative work contains // -- +// // the original copyright notice and the associated disclaimer. // -- +// // // -- +// // THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY // -- +// // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // -- +// // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // -- +// // FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR // -- +// // OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // -- +// // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // -- +// // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // -- +// // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // -- +// // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // -- +// // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // -- +// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // -- +// // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // -- +// // POSSIBILITY OF SUCH DAMAGE. // -- +// // // -- +// /////////////////////////////////////////////////////////////////// -- +//======================================================================================-- +// -- +// Change history -- +// +-------+-----------+-------+------------------------------------------------------+ -- +// | Vers. | Date | Autor | Comment | -- +// +-------+-----------+-------+------------------------------------------------------+ -- +// | 2.1 |20 Jul 2019| EMARD | LineCtrl_i: 0: Data TX, 1: KEEPALIVE/RESUME/RESET | -- +// | | | | DataOut_i(1 downto 0)="00": KEEPALIVE (2 clk of SE0) | -- +// | | | | DataOut_i(1 downto 0)="01": RESUME (20ms of K) | -- +// | | | | DataOut_i(1 downto 0)="11": RESET (20ms of SE0) | -- +// | 2.0 | 3 Jul 2016| MN | Changed eop logic due to USB spec violation | -- +// | 1.1 |23 Apr 2011| MN | Added missing 'rst' in process sensitivity lists | -- +// | | | | Added ELSE constructs in next_state process to | -- +// | | | | prevent an undesired latch implementation. | -- +// | 1.0 |04 Feb 2011| MN | Initial version | -- +//======================================================================================-- +// no timescale needed + +module usb_tx_phy( +input wire clk, +input wire rst, +input wire fs_ce, +input wire phy_mode, +output reg txdp, +output reg txdn, +output reg txoe, +input wire LineCtrl_i, +input wire [7:0] DataOut_i, +input wire TxValid_i, +output reg TxReady_o +); + +// HIGH level for differential IO mode (else single-ended) +// Transciever Interface +// UTMI Interface +// 0: Data TX, 1: LineCtrl +// TX byte or LineCtrl mode + + + +reg [7:0] hold_reg; +reg ld_data; +wire ld_data_d; +wire ld_sop_d; +reg R_LineCtrl_i; +reg R_long_i; +reg R_busreset_i; +reg [15:0] bit_cnt; // 20ms long @ 6MHz: (15 downto 0) +wire sft_done_e; +wire any_eop_state; +wire append_eop; +wire se_state; +reg data_xmit; +reg [7:0] hold_reg_d; +reg [2:0] one_cnt; +reg sd_bs_o; +reg sd_nrzi_o; +reg sd_raw_o; +reg sft_done; +reg sft_done_r; +reg [3:0] state; +wire stuff; +reg tx_ip; +reg tx_ip_sync; +reg txoe_r1; reg txoe_r2; +wire S_long; +parameter IDLE_STATE = 4'b0000; +parameter SOP_STATE = 4'b0001; +parameter DATA_STATE = 4'b0010; +parameter WAIT_STATE = 4'b0011; +parameter EOP0_STATE = 4'b1000; +parameter EOP1_STATE = 4'b1001; +parameter EOP2_STATE = 4'b1010; +parameter EOP3_STATE = 4'b1011; +parameter EOP4_STATE = 4'b1100; +parameter EOP5_STATE = 4'b1101; + + //======================================================================================-- + // Misc Logic -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + TxReady_o <= 1'b0; + end else begin + TxReady_o <= (ld_data_d | (R_LineCtrl_i & any_eop_state)) & TxValid_i; + end + end + + always @(posedge clk) begin + ld_data <= ld_data_d; + end + + //======================================================================================-- + // Transmit in progress indicator -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + tx_ip <= 1'b0; + end else begin + if(ld_sop_d == 1'b1) begin + tx_ip <= 1'b1; + end + else if(append_eop == 1'b1) begin + tx_ip <= 1'b0; + end + end + end + + always @(posedge clk) begin + if(rst == 1'b0) begin + tx_ip_sync <= 1'b0; + end else begin + if(fs_ce == 1'b1) begin + tx_ip_sync <= tx_ip; + end + end + end + + // data_xmit helps us to catch cases where TxValid drops due to + // packet END and then gets re-asserted as a new packet starts. + // We might not see this because we are still transmitting. + // data_xmit should solve those cases ... + always @(posedge clk) begin + if(rst == 1'b0) begin + data_xmit <= 1'b0; + end else begin + if(TxValid_i == 1'b1 && tx_ip == 1'b0) begin + data_xmit <= 1'b1; + end + else if(TxValid_i == 1'b0) begin + data_xmit <= 1'b0; + end + end + end + + //======================================================================================-- + // Shift Register -- + //======================================================================================-- + always @(posedge clk) begin + //IF rising_edge(clk) THEN + if(rst == 1'b0) begin + bit_cnt <= {16{1'b0}}; + end else begin + if(tx_ip_sync == 1'b0) begin + bit_cnt <= {16{1'b0}}; + end + else if(fs_ce == 1'b1 && stuff == 1'b0) begin + bit_cnt <= bit_cnt + 1; + end + end + end + + always @(posedge clk) begin + if(tx_ip_sync == 1'b0) begin + sd_raw_o <= 1'b0; + end + else begin + sd_raw_o <= hold_reg_d[bit_cnt[2:0]]; + end + end + + always @(posedge clk) begin + if(rst == 1'b0) begin + sft_done <= 1'b0; + sft_done_r <= 1'b0; + end else begin + if(bit_cnt[(15)] == (R_LineCtrl_i & R_long_i) && bit_cnt[2:0] == 3'b111) begin + sft_done <= ~stuff; + end + else begin + sft_done <= 1'b0; + end + sft_done_r <= sft_done; + end + end + + assign sft_done_e = sft_done & ~sft_done_r; + // Out Data Hold Register + always @(posedge clk) begin + if(rst == 1'b0) begin + hold_reg <= 8'h00; + hold_reg_d <= 8'h00; + end else begin + if(ld_sop_d == 1'b1) begin + hold_reg <= 8'h80; + end + else if(ld_data == 1'b1) begin + hold_reg <= DataOut_i; + end + hold_reg_d <= hold_reg; + end + end + + //======================================================================================-- + // Bit Stuffer -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + one_cnt <= 3'b000; + end else begin + if(tx_ip_sync == 1'b0) begin + one_cnt <= 3'b000; + end + else if(fs_ce == 1'b1) begin + if(sd_raw_o == 1'b0 || stuff == 1'b1) begin + one_cnt <= 3'b000; + end + else begin + one_cnt <= one_cnt + 1; + end + end + end + end + + assign stuff = one_cnt == 3'b110 ? 1'b1 : 1'b0; + always @(posedge clk) begin + if(rst == 1'b0) begin + sd_bs_o <= 1'b0; + end else begin + if(fs_ce == 1'b1) begin + if(tx_ip_sync == 1'b0) begin + sd_bs_o <= 1'b0; + end + else begin + if(stuff == 1'b1) begin + sd_bs_o <= 1'b0; + end + else begin + sd_bs_o <= sd_raw_o; + end + end + end + end + end + + //======================================================================================-- + // NRZI Encoder -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + sd_nrzi_o <= 1'b1; + end else begin + if(tx_ip_sync == 1'b0 || txoe_r1 == 1'b0 || R_LineCtrl_i == 1'b1) begin + if(R_LineCtrl_i == 1'b1) begin + sd_nrzi_o <= S_long; + end + else begin + sd_nrzi_o <= 1'b1; + end + end + else if(fs_ce == 1'b1) begin + if(sd_bs_o == 1'b1) begin + sd_nrzi_o <= sd_nrzi_o; + end + else begin + sd_nrzi_o <= ~sd_nrzi_o; + end + end + end + end + + //======================================================================================-- + // Output Enable Logic -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + txoe_r1 <= 1'b0; + txoe_r2 <= 1'b0; + txoe <= 1'b1; + end else begin + if(fs_ce == 1'b1) begin + txoe_r1 <= tx_ip_sync; + txoe_r2 <= txoe_r1; + txoe <= ~(txoe_r1 | txoe_r2); + end + end + end + + //======================================================================================-- + // Output Registers -- + //======================================================================================-- + always @(posedge clk) begin + if(rst == 1'b0) begin + txdp <= 1'b1; + txdn <= 1'b0; + end else begin + if(fs_ce == 1'b1) begin + if(phy_mode == 1'b1) begin + txdp <= ~se_state & sd_nrzi_o; + txdn <= ~se_state & ~sd_nrzi_o; + end + else begin + txdp <= sd_nrzi_o; + txdn <= se_state; + end + end + end + end + + //======================================================================================-- + // Tx Statemashine -- + //======================================================================================-- + assign any_eop_state = state[3]; + always @(posedge clk) begin + if(rst == 1'b0) begin + state <= IDLE_STATE; + end else begin + if(any_eop_state == 1'b0) begin + case(state) + IDLE_STATE : begin + if(TxValid_i == 1'b1) begin + R_LineCtrl_i <= LineCtrl_i; + R_long_i <= DataOut_i[0]; + R_busreset_i <= DataOut_i[1]; + // IF DataOut_i(0) = '0' THEN + // state <= EOP1_STATE; -- fast but txready_o wrong + // ELSE + state <= SOP_STATE; + // END IF; + end + end + SOP_STATE : begin + if(sft_done_e == 1'b1) begin + state <= DATA_STATE; + end + end + DATA_STATE : begin + if(data_xmit == 1'b0 && sft_done_e == 1'b1) begin + if(one_cnt == 3'b101 && hold_reg_d[7] == 1'b1) begin + state <= EOP0_STATE; + end + else begin + state <= EOP1_STATE; + end + end + end + WAIT_STATE : begin + if(fs_ce == 1'b1) begin + state <= IDLE_STATE; + end + end + default : begin + state <= IDLE_STATE; + end + endcase + end + else begin + if(fs_ce == 1'b1) begin + if(state == EOP5_STATE) begin + state <= WAIT_STATE; + end + else begin + state <= (state) + 1; + end + end + end + end + end + + assign append_eop = (state[3:2] == 2'b11) ? 1'b1 : 1'b0; + // EOP4_STATE OR EOP5_STATE + assign se_state = append_eop == 1'b1 || (state != WAIT_STATE && R_LineCtrl_i == 1'b1 && R_long_i == 1'b1 && R_busreset_i == 1'b1) ? 1'b1 : 1'b0; + assign ld_sop_d = state == IDLE_STATE ? TxValid_i : 1'b0; + assign ld_data_d = state == SOP_STATE || (state == DATA_STATE && data_xmit == 1'b1) ? sft_done_e : 1'b0; + assign S_long = state != WAIT_STATE && R_long_i == 1'b1 ? 1'b0 : 1'b1; + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/usbh_crc16.v b/dan-rodrigues_icestation-32/hardware/usb/usbh_crc16.v new file mode 100644 index 0000000000000000000000000000000000000000..0f3af063c588ef6e6229d9486ae3cfb1c9575fdc --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usbh_crc16.v @@ -0,0 +1,73 @@ +//----------------------------------------------------------------- +// USB Full Speed Host +// V0.5 +// Ultra-Embedded.com +// Copyright 2015-2019 +// +// Email: admin@ultra-embedded.com +// +// License: GPL +// If you would like a version with a more permissive license for +// use in closed source commercial applications please contact me +// for details. +//----------------------------------------------------------------- +// +// This file is open source HDL; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of +// the License, or (at your option) any later version. +// +// This file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this file; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +// USA +//----------------------------------------------------------------- + +//----------------------------------------------------------------- +// Generated File +//----------------------------------------------------------------- +//----------------------------------------------------------------- +// Module: 16-bit CRC used by USB data packets +//----------------------------------------------------------------- +module usbh_crc16 +( + input [15:0] crc_i, + input [7:0] data_i, + output [15:0] crc_o +); + +//----------------------------------------------------------------- +// Implementation +//----------------------------------------------------------------- +assign crc_o[15] = data_i[0] ^ data_i[1] ^ data_i[2] ^ data_i[3] ^ data_i[4] ^ + data_i[5] ^ data_i[6] ^ data_i[7] ^ crc_i[7] ^ crc_i[6] ^ + crc_i[5] ^ crc_i[4] ^ crc_i[3] ^ crc_i[2] ^ + crc_i[1] ^ crc_i[0]; +assign crc_o[14] = data_i[0] ^ data_i[1] ^ data_i[2] ^ data_i[3] ^ data_i[4] ^ data_i[5] ^ + data_i[6] ^ crc_i[6] ^ crc_i[5] ^ crc_i[4] ^ + crc_i[3] ^ crc_i[2] ^ crc_i[1] ^ crc_i[0]; +assign crc_o[13] = data_i[6] ^ data_i[7] ^ crc_i[7] ^ crc_i[6]; +assign crc_o[12] = data_i[5] ^ data_i[6] ^ crc_i[6] ^ crc_i[5]; +assign crc_o[11] = data_i[4] ^ data_i[5] ^ crc_i[5] ^ crc_i[4]; +assign crc_o[10] = data_i[3] ^ data_i[4] ^ crc_i[4] ^ crc_i[3]; +assign crc_o[9] = data_i[2] ^ data_i[3] ^ crc_i[3] ^ crc_i[2]; +assign crc_o[8] = data_i[1] ^ data_i[2] ^ crc_i[2] ^ crc_i[1]; +assign crc_o[7] = data_i[0] ^ data_i[1] ^ crc_i[15] ^ crc_i[1] ^ crc_i[0]; +assign crc_o[6] = data_i[0] ^ crc_i[14] ^ crc_i[0]; +assign crc_o[5] = crc_i[13]; +assign crc_o[4] = crc_i[12]; +assign crc_o[3] = crc_i[11]; +assign crc_o[2] = crc_i[10]; +assign crc_o[1] = crc_i[9]; +assign crc_o[0] = data_i[0] ^ data_i[1] ^ data_i[2] ^ data_i[3] ^ data_i[4] ^ data_i[5] ^ + data_i[6] ^ data_i[7] ^ crc_i[8] ^ crc_i[7] ^ crc_i[6] ^ + crc_i[5] ^ crc_i[4] ^ crc_i[3] ^ crc_i[2] ^ + crc_i[1] ^ crc_i[0]; + +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/usb/usbh_crc5.v b/dan-rodrigues_icestation-32/hardware/usb/usbh_crc5.v new file mode 100644 index 0000000000000000000000000000000000000000..133afee376322ed31e26bc5d73a259796c3b8ed7 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usbh_crc5.v @@ -0,0 +1,63 @@ +//----------------------------------------------------------------- +// USB Full Speed Host +// V0.5 +// Ultra-Embedded.com +// Copyright 2015-2019 +// +// Email: admin@ultra-embedded.com +// +// License: GPL +// If you would like a version with a more permissive license for +// use in closed source commercial applications please contact me +// for details. +//----------------------------------------------------------------- +// +// This file is open source HDL; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of +// the License, or (at your option) any later version. +// +// This file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this file; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +// USA +//----------------------------------------------------------------- + +//----------------------------------------------------------------- +// Generated File +//----------------------------------------------------------------- +//----------------------------------------------------------------- +// Module: 5-bit CRC used by USB tokens +//----------------------------------------------------------------- +module usbh_crc5 +( + input [4:0] crc_i, + input [10:0] data_i, + output [4:0] crc_o +); + +//----------------------------------------------------------------- +// Implementation +//----------------------------------------------------------------- +assign crc_o[0] = data_i[10] ^ data_i[9] ^ data_i[6] ^ data_i[5] ^ data_i[3] ^ data_i[0] ^ + crc_i[0] ^ crc_i[3] ^ crc_i[4]; + +assign crc_o[1] = data_i[10] ^ data_i[7] ^ data_i[6] ^ data_i[4] ^ data_i[1] ^ + crc_i[0] ^ crc_i[1] ^ crc_i[4]; + +assign crc_o[2] = data_i[10] ^ data_i[9] ^ data_i[8] ^ data_i[7] ^ data_i[6] ^ data_i[3] ^ data_i[2] ^ data_i[0] ^ + crc_i[0] ^ crc_i[1] ^ crc_i[2] ^ crc_i[3] ^ crc_i[4]; + +assign crc_o[3] = data_i[10] ^ data_i[9] ^ data_i[8] ^ data_i[7] ^ data_i[4] ^ data_i[3] ^ data_i[1] ^ + crc_i[1] ^ crc_i[2] ^ crc_i[3] ^ crc_i[4]; + +assign crc_o[4] = data_i[10] ^ data_i[9] ^ data_i[8] ^ data_i[5] ^ data_i[4] ^ data_i[2] ^ + crc_i[2] ^ crc_i[3] ^ crc_i[4]; + +endmodule + diff --git a/dan-rodrigues_icestation-32/hardware/usb/usbh_host_hid.v b/dan-rodrigues_icestation-32/hardware/usb/usbh_host_hid.v new file mode 100644 index 0000000000000000000000000000000000000000..86505e6ef56f98935cb813f09521a279ce1d7106 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usbh_host_hid.v @@ -0,0 +1,801 @@ +// File ../../../../usbhost/usbh_host_hid_convertible.vhd translated with vhd2vl v3.0 VHDL to Verilog RTL translator +// vhd2vl settings: +// * Verilog Module Declaration Style: 2001 + +// vhd2vl is Free (libre) Software: +// Copyright (C) 2001 Vincenzo Liguori - Ocean Logic Pty Ltd +// http://www.ocean-logic.com +// Modifications Copyright (C) 2006 Mark Gonzales - PMC Sierra Inc +// Modifications (C) 2010 Shankar Giri +// Modifications Copyright (C) 2002-2017 Larry Doolittle +// http://doolittle.icarus.com/~larry/vhd2vl/ +// Modifications (C) 2017 Rodrigo A. Melo +// +// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting +// Verilog for correctness, ideally with a formal verification tool. +// +// You are welcome to redistribute vhd2vl under certain conditions. +// See the license (GPLv2) file included with the source for details. + +// The result of translation follows. Its copyright status should be +// considered unchanged from the original VHDL. + +// (c)EMARD +// License=GPL +// USB HOST for HID devices +// drives SIE directly +// suggested reading +// http://www.usbmadesimple.co.uk/ +// online USB descriptor parser +// https://eleccelerator.com/usbdescreqparser/ +// no timescale needed + +module usbh_host_hid +#( +parameter C_setup_retry=4, +parameter C_setup_interval=17, +parameter C_report_interval=16, +parameter C_report_endpoint=1, +parameter C_report_length=20, // bytes +parameter C_report_length_strict=0, // 0:accept length>0, 1:require exact length +parameter C_keepalive_setup=1'b1, +parameter C_keepalive_status=1'b1, +parameter C_keepalive_report=1'b1, +parameter C_keepalive_phase_bits=12, // keepalive/sof frequency 12:low speed, 15:full speed +// NOTE: C_keepalive_phase_bits=12 at C_usb_speed=0 ( 6 MHz) +// or C_keepalive_phase_bits=15 at C_usb_speed=1 (48 MHz) +// will send keepalive/SOF every 0.68 ms +// USB standard requires keepalive < 1 ms but SOF every 1 ms +-1% +// so far all full-speed devices tested accept SOF at 0.68 ms rate +parameter C_keepalive_phase=2048, // 4044:KEEPALIVE low speed, 2048:low/full speed good for both +parameter C_keepalive_type=1'b1, // 1:KEEPALIVE low speed (may work for full speed, LUT saver), 0:SOF full speed +parameter C_setup_rom_file="usbh_setup_rom.mem", +parameter C_setup_rom_len=16, +// FIXME: For C_usb_speed=1 reset timing is 4x shorter than required by USB standard +parameter C_usb_speed=0 // '0':6 MHz low speed '1':48 MHz full speed +) +( +input wire clk, // main clock input +input wire usb_dif, // differential or single-ended input +inout wire usb_dp, // single ended bidirectional +inout wire usb_dn, +input wire bus_reset, // force bus reset and setup (similar to re-plugging USB device) +output wire [7:0] led, // HID debugging +output wire [15:0] rx_count, // rx response length +output wire rx_done, // rx done +output wire [C_report_length * 8 - 1:0] hid_report, // HID report (filtered with expected length) +output wire hid_valid +); + +wire clk_usb; // 48 or 60 MHz +wire S_rxd; +wire S_rxdp; wire S_rxdn; +wire S_txdp; wire S_txdn; wire S_txoe; +wire [63:0] S_oled; +wire [1:0] S_LINESTATE; +wire S_LINECTRL; +wire S_TXVALID; +wire S_TXREADY; +wire S_RXVALID; +wire S_RXACTIVE; +wire S_RXERROR; +wire [7:0] S_DATAIN; +wire [7:0] S_DATAOUT; +wire S_BREAK; // UTMI debug +wire S_sync_err; wire S_bit_stuff_err; wire S_byte_err; +reg [7:0] R_setup_rom_addr = 1'b0; reg [7:0] R_setup_rom_addr_acked = 1'b0; + +reg [7:0] C_setup_rom[0:C_setup_rom_len-1]; // ( x"00", x"05", x"01", x"00", x"00", x"00", x"00", x"00", x"00", x"09", x"01", x"00", x"00", x"00", x"00", x"00" ); +initial $readmemh(C_setup_rom_file, C_setup_rom); + +reg [2:0] R_setup_byte_counter = 1'b0; +reg ctrlin; +reg datastatus = 1'b0; +parameter C_datastatus_enable = 1'b0; +reg [15:0] R_packet_counter; +reg [1:0] R_state = 2'b00; +parameter C_STATE_DETACHED = 2'b00; +parameter C_STATE_SETUP = 2'b01; +parameter C_STATE_REPORT = 2'b10; +parameter C_STATE_DATA = 2'b11; +reg [C_setup_retry:0] R_retry; +reg [17:0] R_slow = 0; // 2**17 clocks = 22 ms interval at 6 MHz +reg R_reset_pending; +reg R_reset_accepted; +// sie wires +reg start_i = 1'b0; +reg in_transfer_i = 1'b0; +reg sof_transfer_i = 1'b0; +reg resp_expected_i = 1'b0; +reg [7:0] token_pid_i = 0; +reg [6:0] token_dev_i = 0; +reg [3:0] token_ep_i = 0; +reg [15:0] data_len_i = 0; +reg data_idx_i = 1'b0; +wire [7:0] tx_data_i; +wire ack_o; +wire tx_pop_o; +wire [7:0] rx_data_o; +wire rx_push_o; +wire tx_done_o; +wire rx_done_o; +wire crc_err_o; +wire timeout_o; +wire [7:0] response_o; +wire [15:0] rx_count_o; +wire idle_o; +reg R_set_address_found; +reg [6:0] R_dev_address_requested; +reg [6:0] R_dev_address_confirmed; +reg [7:0] R_stored_response; +reg [15:0] R_wLength; +reg [15:0] R_bytes_remaining; +wire [7:0] S_expected_response; +reg R_advance_data = 1'b0; +wire S_transmission_over; +reg R_timeout; // rising edge tracking +reg R_first_byte_0_found; + +reg [7:0] R_report_buf[0:C_report_length - 1]; +reg [15:0] R_rx_count; +reg R_hid_valid; +reg R_crc_err; +reg R_rx_done; + + generate if (C_usb_speed == 1) begin: G_full_speed + assign clk_usb = clk; + // 48 MHz with "usb_rx_phy_48MHz.vhd" or 60 MHz with "usb_rx_phy_60MHz.vhd" + // transciever soft-core + //usb_fpga_pu_dp <= '0'; -- D+ pulldown for USB host mode + //usb_fpga_pu_dn <= '0'; -- D- pulldown for USB host mode + assign S_rxd = usb_dif; + // differential input reads D+ + //S_rxd <= usb_dp; -- single-ended input reads D+ may work as well + assign S_rxdp = usb_dp; + // single-ended input reads D+ + assign S_rxdn = usb_dn; + // single-ended input reads D- + assign usb_dp = S_txoe == 1'b0 ? S_txdp : 1'bZ; + assign usb_dn = S_txoe == 1'b0 ? S_txdn : 1'bZ; + end + endgenerate + generate if (C_usb_speed == 0) begin: G_low_speed + assign clk_usb = clk; + // 6 MHz + // transciever soft-core + // for low speed USB, here are swaped D+ and D- + //usb_fpga_pu_dp <= '0'; -- D+ pulldown for USB host mode + //usb_fpga_pu_dn <= '0'; -- D- pulldown for USB host mode + assign S_rxd = ~usb_dif; + // differential input reads inverted D+ for low speed + //S_rxd <= not usb_dp; -- single-ended input reads D+ may work as well + assign S_rxdp = usb_dn; + // single-ended input reads D- for low speed + assign S_rxdn = usb_dp; + // single-ended input reads D+ for low speed + assign usb_dp = S_txoe == 1'b0 ? S_txdn : 1'bZ; + assign usb_dn = S_txoe == 1'b0 ? S_txdp : 1'bZ; + end + endgenerate + reg R_txover_debug = 1'b1; + assign led = {R_reset_pending, R_txover_debug, R_setup_rom_addr_acked[3], S_LINESTATE, R_state}; + // USB1.1 PHY soft-core + usb_phy + E_usb11_phy( + .clk(clk_usb), + // full speed: 48 MHz or 60 MHz, low speed: 6 MHz or 7.5 MHz + .rst(~bus_reset), + // 1-don't reset, 0-hold reset + .phy_tx_mode(1'b1), + // 1-differential, 0-single-ended + // UTMI interface to usb-serial core + .LineCtrl_i(S_LINECTRL), + .TxValid_i(S_TXVALID), + .DataOut_i(S_DATAOUT), + // 8-bit TX + .TxReady_o(S_TXREADY), + .RxValid_o(S_RXVALID), + .DataIn_o(S_DATAIN), + // 8-bit RX + .RxActive_o(S_RXACTIVE), + .RxError_o(S_RXERROR), + .LineState_o(S_LINESTATE), + // 2-bit + // debug interface + .sync_err_o(S_sync_err), + .bit_stuff_err_o(S_bit_stuff_err), + .byte_err_o(S_byte_err), + // transciever interface to hardware + .rxd(S_rxd), + // differential input from D+ + .rxdp(S_rxdp), + // single-ended input from D+ + .rxdn(S_rxdn), + // single-ended input from D- + .txdp(S_txdp), + // single-ended output to D+ + .txdn(S_txdn), + // single-ended output to D- + // 3-state control: 0-output, 1-input + .txoe(S_txoe)); + + + // address advance, retry logic, set_address accpetance + assign S_transmission_over = rx_done_o == 1'b1 || (timeout_o == 1'b1 && R_timeout == 1'b0) ? 1'b1 : 1'b0; + always @(posedge clk_usb) begin + R_timeout <= timeout_o; + if(R_reset_accepted == 1'b1) begin + R_setup_rom_addr <= 8'd0; + R_setup_rom_addr_acked <= 8'd0; + R_setup_byte_counter <= 3'd0; + R_retry <= 0; + R_reset_pending <= 1'b0; + R_txover_debug <= 1'b0; + end + else begin + if(bus_reset == 1'b1) begin + R_reset_pending <= 1'b1; + end + case(R_state) + C_STATE_DETACHED : begin + // start from unitialized device + R_dev_address_confirmed <= 7'd0; + R_retry <= 0; + end + C_STATE_SETUP : begin + if(S_transmission_over == 1'b1) begin + R_txover_debug <= 1'b1; + // decide to continue with next setup or to retry + case(token_pid_i) + 8'h2D : begin + if(rx_done_o == 1'b1 && response_o == 8'hD2) begin + // ACK to SETUP + // continue with next setup + R_setup_rom_addr_acked <= R_setup_rom_addr; + R_retry <= 0; + end + else begin + // failed, rewind to unacknowledged setup and retry + R_setup_rom_addr <= R_setup_rom_addr_acked; + if(R_retry[C_setup_retry] == 1'b0) begin + R_retry <= R_retry + 1; + end + end + end + endcase + end + else begin + // transmission is going on -- advance address + if(tx_pop_o == 1'b1) begin + R_setup_rom_addr <= R_setup_rom_addr + 1; + R_setup_byte_counter <= R_setup_byte_counter + 1; + end + end + R_stored_response <= 8'h00; + end + C_STATE_REPORT : begin + if(S_transmission_over == 1'b1) begin + // multiple timeouts at waiting for response will detach + if(timeout_o == 1'b1 && R_timeout == 1'b0) begin + if(R_retry[C_setup_retry] == 1'b0) begin + R_retry <= R_retry + 1; + end + end + else begin + if(rx_done_o == 1'b1) begin + R_retry <= 0; + end + end + end + end + default : begin + // C_STATE_DATA => + if(S_transmission_over == 1'b1) begin + case(token_pid_i) + 8'hE1 : begin + if(rx_done_o == 1'b1 && response_o == 8'hD2) begin + // ACK to DATA OUT + R_stored_response <= response_o; + // continue with next setup + R_setup_rom_addr_acked <= R_setup_rom_addr; + R_retry <= 0; + end + else begin + // failed, rewind to unacknowledged setup and retry + R_setup_rom_addr <= R_setup_rom_addr_acked; + if(R_retry[C_setup_retry] == 1'b0) begin + R_retry <= R_retry + 1; + end + end + end + default : begin + // x"69" + if(timeout_o == 1'b1 && R_timeout == 1'b0) begin + if(R_retry[C_setup_retry] == 1'b0) begin + R_retry <= R_retry + 1; + end + end + else begin + if(rx_done_o == 1'b1) begin + R_stored_response <= response_o; + // SIE quirk: set address returns 4B = PID_DATA1 instead of D2 + if(response_o == 8'h4B) begin + R_retry <= 0; + R_dev_address_confirmed <= R_dev_address_requested; + end + else // set address failed + R_retry <= R_retry + 1; + end + end + end + endcase + end + else begin + // transmission is going on -- advance address but only data, not setup counter + if(tx_pop_o == 1'b1) begin + R_setup_rom_addr <= R_setup_rom_addr + 1; + end + end + end + endcase + end + // reset accepted + end + + assign tx_data_i = C_setup_rom[R_setup_rom_addr]; + // B_requested_set_address: block + // NOTE: it works only if each setup packet in ROM is 8 bytes + // if data is added to ROM, then R_setup_rom_addr should be + // replaced with another register that tracks actual offset from + // setup packet + always @(posedge clk_usb) begin + case(R_state) + C_STATE_DETACHED : begin + R_dev_address_requested <= 7'd0; + R_set_address_found <= 1'b0; + R_wLength <= 16'h0000; + end + C_STATE_SETUP : begin + case(R_setup_byte_counter[2:0]) + 3'b000 : begin + // every 8 bytes, 1st byte + if(tx_data_i == 8'h00) begin + R_first_byte_0_found <= 1'b1; + end + else begin + R_first_byte_0_found <= 1'b0; + end + end + 3'b001 : begin + // every 8 bytes, 2nd byte + if(tx_data_i == 8'h05) begin + R_set_address_found <= R_first_byte_0_found; + end + R_wLength <= 16'h0000; + end + 3'b010 : begin + // every 8 bytes, 3rd byte + if(R_set_address_found == 1'b1) begin + // every 8 bytes, 3rd byte + R_dev_address_requested <= tx_data_i[6:0]; + end + end + 3'b110 : begin + // every 8 bytes, 7th byte + R_wLength[7:0] <= tx_data_i; + end + 3'b111 : begin + // every 8 bytes, 8th byte wLength high byte currently forced to 0 + R_wLength[15:8] <= 8'h00; + // tx_data_i; + end + endcase + end + default : begin + R_wLength <= 16'h0000; + R_set_address_found <= 1'b0; + end + endcase + end + + reg [10:0] R_sof_counter; + // FIXME not sure how to map counter to dev and ep + wire [6:0] S_sof_dev = R_sof_counter[10:4]; + wire [3:0] S_sof_ep = R_sof_counter[3:0]; + + assign S_expected_response = data_idx_i == 1'b1 ? 8'h4B : 8'hC3; + always @(posedge clk_usb) begin + R_advance_data <= 1'b0; + // default + case(R_state) + C_STATE_DETACHED : begin + // start from unitialized device + R_reset_accepted <= 1'b0; + if(S_LINESTATE == 2'b01) begin + if(R_slow[17] == 1'b0) begin + // 22 ms + R_slow <= R_slow + 1; + end + else begin + R_slow <= 18'd0; + sof_transfer_i <= 1'b1; + // transfer SOF or linectrl + in_transfer_i <= 1'b1; + // 0:SOF, 1:linectrl + token_pid_i[1:0] <= 2'b11; + // linectrl: bus reset + token_dev_i <= 7'd0; + // after reset device address will be 0 + resp_expected_i <= 1'b0; + ctrlin <= 1'b0; + start_i <= 1'b1; + R_packet_counter <= 16'h0000; + R_sof_counter <= 11'd0; + R_state <= C_STATE_SETUP; + end + end + else begin + start_i <= 1'b0; + R_slow <= 18'd0; + end + end + C_STATE_SETUP : begin + // send setup sequence (enumeration) + if(idle_o == 1'b1) begin + if(R_slow[C_setup_interval] == 1'b0) begin + R_slow <= R_slow + 1; + if(R_retry[C_setup_retry] == 1'b1) begin + R_reset_accepted <= 1'b1; + R_state <= C_STATE_DETACHED; + end + if(R_slow[C_keepalive_phase_bits-1:0] == C_keepalive_phase && C_keepalive_setup == 1'b1) begin + // keepalive: first at 0.35 ms, then every 0.68 ms + // keepalive signal + sof_transfer_i <= 1'b1; + // transfer SOF or linectrl + in_transfer_i <= C_keepalive_type; + // 0:SOF, 1:linectrl + if(C_keepalive_type) + token_pid_i[1:0] <= 2'b00; + else + begin + token_pid_i <= 8'hA5; + token_dev_i <= S_sof_dev; + token_ep_i <= S_sof_ep; + data_len_i <= 16'h0000; + R_sof_counter <= R_sof_counter + 1; + end + // linectrl: keepalive + resp_expected_i <= 1'b0; + start_i <= 1'b1; + end + else begin + start_i <= 1'b0; + end + end + else begin + // time passed, send next setup packet or read status or read response + R_slow <= 18'd0; + sof_transfer_i <= 1'b0; + token_dev_i <= R_dev_address_confirmed; + token_ep_i <= 4'h0; + resp_expected_i <= 1'b1; + if(R_setup_rom_addr == C_setup_rom_len) begin + data_len_i <= 16'h0000; + start_i <= 1'b0; + R_state <= C_STATE_REPORT; + end + else begin + in_transfer_i <= 1'b0; + token_pid_i <= 8'h2D; + data_len_i <= 16'h0008; + if(R_set_address_found == 1'b1 || ctrlin == 1'b1 || R_wLength != 16'h0000) begin + R_bytes_remaining <= R_wLength; + // R_bytes_remaining <= x"0000"; + if(R_set_address_found == 1'b1) begin + ctrlin <= 1'b1; + datastatus <= 1'b0; + end + else begin + datastatus <= C_datastatus_enable; + // after IN send status OUT + end + data_idx_i <= 1'b1; + // next sending as DATA1 + R_state <= C_STATE_DATA; + end + else begin + data_idx_i <= 1'b0; + // send as DATA0 + ctrlin <= tx_data_i[7]; + R_packet_counter <= R_packet_counter + 1; + start_i <= 1'b1; + end + end + end + end + else begin + // not idle + start_i <= 1'b0; + end + end + C_STATE_REPORT : begin + // request report (send IN request) + if(idle_o == 1'b1) begin + if(R_slow[C_report_interval] == 1'b0) begin + R_slow <= R_slow + 1; + if(R_slow[C_keepalive_phase_bits-1:0] == C_keepalive_phase && C_keepalive_report == 1'b1) begin + // keepalive: first at 0.35 ms, then every 0.68 ms + // keepalive signal + sof_transfer_i <= 1'b1; + // transfer SOF or linectrl + in_transfer_i <= C_keepalive_type; + // 0:SOF, 1:linectrl + if(C_keepalive_type) + token_pid_i[1:0] <= 2'b00; + else + begin + token_pid_i <= 8'hA5; + token_dev_i <= S_sof_dev; + token_ep_i <= S_sof_ep; + data_len_i <= 16'h0000; + R_sof_counter <= R_sof_counter + 1; + end + // linectrl: keepalive + resp_expected_i <= 1'b0; + start_i <= 1'b1; + end + else begin + start_i <= 1'b0; + end + end + else begin + R_slow <= 18'd0; + // HOST: < SYNC >< IN >EP1 CRC5 + // D+ ___-_-_-_---_--___-_-_-_-__-_-_--________ + // D- ---_-_-_-___-__---_-_-_-_--_-_-__--__---- + // 00000001100101100000000100000101 + // < 0 8 >< 9 6 >< 0 ><1 > + sof_transfer_i <= 1'b0; + in_transfer_i <= 1'b1; + token_pid_i <= 8'h69; + if(C_keepalive_type == 1'b0) + token_dev_i <= R_dev_address_confirmed; + token_ep_i <= C_report_endpoint; + data_idx_i <= 1'b0; + // R_packet_counter <= R_packet_counter + 1; + resp_expected_i <= 1'b1; + start_i <= 1'b1; + if(R_reset_pending == 1'b1 || S_LINESTATE == 2'b00 || R_retry[C_setup_retry] == 1'b1) begin + R_reset_accepted <= 1'b1; + R_state <= C_STATE_DETACHED; + end + end + end + else begin + // not idle + start_i <= 1'b0; + end + end + default : begin + // C_STATE_DATA receive or send data phase + if(idle_o == 1'b1) begin + if(R_slow[C_setup_interval] == 1'b0) begin + R_slow <= R_slow + 1; + if(R_retry[C_setup_retry] == 1'b1) begin + R_reset_accepted <= 1'b1; + R_state <= C_STATE_DETACHED; + end + if(R_slow[C_keepalive_phase_bits-1:0] == C_keepalive_phase && C_keepalive_status == 1'b1) begin + // keepalive: first at 0.35 ms, then every 0.68 ms + // keepalive signal + sof_transfer_i <= 1'b1; + // transfer SOF or linectrl + in_transfer_i <= C_keepalive_type; + // 0:SOF, 1:linectrl + if(C_keepalive_type) + token_pid_i[1:0] <= 2'b00; + else + begin + token_pid_i <= 8'hA5; + token_dev_i <= S_sof_dev; + token_ep_i <= S_sof_ep; + data_len_i <= 16'h0000; + R_sof_counter <= R_sof_counter + 1; + end + // linectrl: keepalive + resp_expected_i <= 1'b0; + start_i <= 1'b1; + end + else begin + start_i <= 1'b0; + end + end + else begin + // time to send request + R_slow <= 18'd0; + sof_transfer_i <= 1'b0; + in_transfer_i <= ctrlin; + if(ctrlin == 1'b1) begin + token_pid_i <= 8'h69; + // 69=IN + end + else begin + token_pid_i <= 8'hE1; + // E1=OUT + end + if(C_keepalive_type == 1'b0) + token_dev_i <= R_dev_address_confirmed; + token_ep_i <= 4'h0; + resp_expected_i <= 1'b1; + if(R_bytes_remaining != 16'h0000) begin + if(R_bytes_remaining[15:3] != 13'd0) begin + // 8 or more remaining bytes + data_len_i <= 16'h0008; + // transmit 8 bytes in a packet + end + else begin + // less than 8 remaining + data_len_i <= {13'd0,R_bytes_remaining[2:0]}; + // transmit remaining bytes (less than 8) + end + end + else begin + data_len_i <= 16'h0000; + end + if(ctrlin == 1'b1) begin + if(R_stored_response == 8'h4B || R_stored_response == 8'hC3) begin + // SIE quirk: 4B is returned for 0-len packet instead of D2 ACK + R_advance_data <= 1'b1; + if(R_bytes_remaining[15:3] == 13'd0) begin + ctrlin <= 1'b0; + if(datastatus == 1'b0) begin + R_state <= C_STATE_SETUP; + end + // after all IN packets, send 0-length OUT packet as confirmation. + // TODO: see standard what is correct data_idx_i = 0 or 1 + end + else begin + R_advance_data <= 1'b1; + R_packet_counter <= R_packet_counter + 1; + start_i <= 1'b1; + end + end + else begin + R_packet_counter <= R_packet_counter + 1; + start_i <= 1'b1; + end + end + else begin + // ctrlin = 0 + if(R_stored_response == 8'hD2) begin + R_advance_data <= 1'b1; + if(datastatus == 1'b1) begin + R_state <= C_STATE_SETUP; + end + else begin + if(R_bytes_remaining == 16'h0000) begin + ctrlin <= 1'b1; + // OUT phase will finish with IN 0-length packet + end + end + end + else begin + R_packet_counter <= R_packet_counter + 1; + start_i <= 1'b1; + end + end + end + end + else begin + start_i <= 1'b0; + end + // always during C_STATE_DATA + // counts bytes required for DATA state, then exit + if(R_advance_data == 1'b1) begin + if(R_bytes_remaining != 16'h0000) begin + if(R_bytes_remaining[15:3] != 13'd0) begin + // 8 or more remaining bytes + R_bytes_remaining[15:3] <= R_bytes_remaining[15:3] - 1; + end + else begin + // less than 8 remaining + R_bytes_remaining[2:0] <= 3'b000; + end + data_idx_i <= ~data_idx_i; + // alternates DATA 0/1 + end + else begin + if(ctrlin == 1'b1) begin + data_idx_i <= 1'b1; + // always DATA1 at last IN + end + end + end + end + endcase + end + + wire [6:0] reverse_token_dev_i = { + token_dev_i[0], token_dev_i[1], token_dev_i[2], token_dev_i[3], + token_dev_i[4], token_dev_i[5], token_dev_i[6] + }; + wire [3:0] reverse_token_ep_i = { + token_ep_i[0], token_ep_i[1], token_ep_i[2], token_ep_i[3] + }; + // USB SIE-core + usbh_sie usb_sie_core( + .clk_i(clk_usb), // low speed: 6 MHz, full speed: 48 MHz + .rst_i(bus_reset), + .start_i(start_i), + .in_transfer_i(in_transfer_i), + .sof_transfer_i(sof_transfer_i), + .resp_expected_i(resp_expected_i), + .token_pid_i(token_pid_i), + .token_dev_i(reverse_token_dev_i), + .token_ep_i(reverse_token_ep_i), + .data_len_i(data_len_i), + .data_idx_i(data_idx_i), + .tx_data_i(tx_data_i), + .ack_o(ack_o), + .tx_pop_o(tx_pop_o), + .rx_data_o(rx_data_o), + .rx_push_o(rx_push_o), + .tx_done_o(tx_done_o), + .rx_done_o(rx_done_o), + .crc_err_o(crc_err_o), + .timeout_o(timeout_o), + .response_o(response_o), + .rx_count_o(rx_count_o), + .idle_o(idle_o), + .utmi_txready_i(S_TXREADY), + .utmi_data_i(S_DATAIN), + .utmi_rxvalid_i(S_RXVALID), + .utmi_rxactive_i(S_RXACTIVE), + .utmi_linectrl_o(S_LINECTRL), + .utmi_data_o(S_DATAOUT), + .utmi_txvalid_o(S_TXVALID)); + + // B_report_reader: block + wire S_report_length_ok = C_report_length_strict ? R_rx_count == C_report_length : R_rx_count != 0; + always @(posedge clk_usb) begin + R_rx_count <= rx_count_o; + // to offload routing (apart from this, "rx_count_o" could be used directly) + if(rx_push_o == 1'b1) begin + R_report_buf[R_rx_count] <= rx_data_o; + end + // rx_done_o is '1' for several clocks... + // action on falling edge + R_rx_done <= rx_done_o; + if(R_rx_done == 1'b1 && rx_done_o == 1'b0) begin + R_crc_err <= 1'b0; + end + else begin + if(crc_err_o == 1'b1) begin + R_crc_err <= 1'b1; + end + end + // at falling edge of rx_done it should not accumulate any crc error + if(R_rx_done == 1'b1 && rx_done_o == 1'b0 && R_crc_err == 1'b0 && timeout_o == 1'b0 && R_state == C_STATE_REPORT && S_report_length_ok) begin + R_hid_valid <= 1'b1; + end + else begin + R_hid_valid <= 1'b0; + end + end + + genvar i; + generate for (i=0; i <= C_report_length - 1; i = i + 1) begin: G_report + assign hid_report[i*8+7:i*8] = R_report_buf[i]; + end + endgenerate + assign hid_valid = R_hid_valid; + assign rx_count = rx_count_o; + // report byte count directly from SIE + //rx_count <= R_packet_counter; -- debugging setup problems + //rx_count(7 downto 0) <= R_stored_response; + //rx_count(7 downto 0) <= R_E1_response; + //rx_count(R_retry'range) <= R_retry; -- debugging report problems + assign rx_done = rx_done_o; + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/usb/usbh_sie.v b/dan-rodrigues_icestation-32/hardware/usb/usbh_sie.v new file mode 100644 index 0000000000000000000000000000000000000000..14181f8e675b1435d24e5b7498241bea34d93fb4 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/usb/usbh_sie.v @@ -0,0 +1,813 @@ +//----------------------------------------------------------------- +// USB Full Speed Host +// V0.5 +// Ultra-Embedded.com +// Copyright 2015-2019 +// +// Email: admin@ultra-embedded.com +// +// License: GPL +// If you would like a version with a more permissive license for +// use in closed source commercial applications please contact me +// for details. +//----------------------------------------------------------------- +// +// This file is open source HDL; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of +// the License, or (at your option) any later version. +// +// This file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this file; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +// USA +//----------------------------------------------------------------- + +//----------------------------------------------------------------- +// Generated File +//----------------------------------------------------------------- + +module usbh_sie +#( + parameter c_crc_complex = 0 // 0:simple CRC compare always LUT saver, 1:CRC compare with and-mask at end of packet +) +( + // Inputs + input clk_i + ,input rst_i + ,input start_i + ,input in_transfer_i + ,input sof_transfer_i + ,input resp_expected_i + ,input [ 7:0] token_pid_i + ,input [ 6:0] token_dev_i + ,input [ 3:0] token_ep_i + ,input [ 15:0] data_len_i + ,input data_idx_i + ,input [ 7:0] tx_data_i + ,input utmi_txready_i + ,input [ 7:0] utmi_data_i + ,input utmi_rxvalid_i + ,input utmi_rxactive_i + + // Outputs + ,output ack_o + ,output tx_pop_o + ,output [ 7:0] rx_data_o + ,output rx_push_o + ,output tx_done_o + ,output rx_done_o + ,output crc_err_o + ,output timeout_o + ,output [ 7:0] response_o + ,output [ 15:0] rx_count_o + ,output idle_o + ,output utmi_linectrl_o + ,output [ 7:0] utmi_data_o + ,output utmi_txvalid_o +); + + + +//----------------------------------------------------------------- +// Registers / Wires +//----------------------------------------------------------------- +reg start_ack_q; + +// Status +reg status_tx_done_q; +reg status_rx_done_q; +reg status_crc_err_q; +reg status_timeout_q; +reg [7:0] status_response_q; + +reg [15:0] byte_count_q; +reg in_transfer_q; + +reg [2:0] rx_time_q; +reg rx_time_en_q; +reg [8:0] last_tx_time_q; + +reg send_data1_q; +reg send_sof_q; +reg send_ack_q; + +// CRC16 +reg [15:0] crc_sum_q; +wire [15:0] crc_out_w; +wire [7:0] crc_data_in_w; + +// CRC5 +wire [4:0] crc5_out_w; +wire [4:0] crc5_next_w = crc5_out_w ^ 5'h1F; + +reg [15:0] token_q; + +reg wait_resp_q; + +reg [3:0] state_q; + +//----------------------------------------------------------------- +// Definitions +//----------------------------------------------------------------- +localparam RX_TIMEOUT = 9'd511; // 10.6uS @ 48MHz, 85us @ 6MHz +localparam TX_IFS = 9'd7; // 2 FS bit times (x5 CLKs @ 60MHz, x4 CLKs @ 48MHz) + +localparam PID_OUT = 8'hE1; +localparam PID_IN = 8'h69; +localparam PID_SOF = 8'hA5; +localparam PID_SETUP = 8'h2D; + +localparam PID_DATA0 = 8'hC3; +localparam PID_DATA1 = 8'h4B; + +localparam PID_ACK = 8'hD2; +localparam PID_NAK = 8'h5A; +localparam PID_STALL = 8'h1E; + +// States +localparam STATE_IDLE = 4'd0; +localparam STATE_RX_DATA = 4'd1; +localparam STATE_TX_PID = 4'd2; +localparam STATE_TX_DATA = 4'd3; +localparam STATE_TX_CRC1 = 4'd4; +localparam STATE_TX_CRC2 = 4'd5; +localparam STATE_TX_TOKEN1 = 4'd6; +localparam STATE_TX_TOKEN2 = 4'd7; +localparam STATE_TX_TOKEN3 = 4'd8; +localparam STATE_TX_ACKNAK = 4'd9; +localparam STATE_TX_WAIT = 4'd10; +localparam STATE_RX_WAIT = 4'd11; +localparam STATE_TX_IFS = 4'd12; + +localparam RX_TIME_ZERO = 3'd0; +localparam RX_TIME_INC = 3'd1; +localparam RX_TIME_READY = 3'd7; // 2-bit times (x5 CLKs @ 60MHz, x4 CLKs @ 48MHz) + +//----------------------------------------------------------------- +// Wires +//----------------------------------------------------------------- +// Rx data +wire [7:0] rx_data_w; +wire data_ready_w; +wire crc_byte_w; +wire rx_active_w; + +// 2-bit times after last RX (inter-packet delay)? +wire autoresp_thresh_w = send_ack_q & rx_time_en_q & (rx_time_q == RX_TIME_READY); + +// Response timeout (no response after 500uS from transmit) +wire rx_resp_timeout_w = (last_tx_time_q >= RX_TIMEOUT) & wait_resp_q; + +// Tx - Tx IFS timeout +wire tx_ifs_ready_w = (last_tx_time_q >= TX_IFS); + +wire status_response_data_w = (status_response_q == PID_DATA0 || status_response_q == PID_DATA1); + +// CRC16 error on received data +wire crc_error_w; +generate + if(c_crc_complex) + assign crc_error_w = (state_q == STATE_RX_DATA) && !rx_active_w && in_transfer_q && + status_response_data_w && + (crc_sum_q != 16'hB001); // USB1.0 and USB1.1 complex for host, incomplete packet won't have CRC error + else + assign crc_error_w = crc_sum_q != 16'hB001; // USB1.0 simple for host, incomplete packet will have CRC error +endgenerate +//----------------------------------------------------------------- +// State Machine +//----------------------------------------------------------------- +reg [3:0] next_state_r; + +always @ * +begin + next_state_r = state_q; + + //----------------------------------------- + // Tx State Machine + //----------------------------------------- + case (state_q) + + //----------------------------------------- + // TX_TOKEN1 (byte 1 of token) + //----------------------------------------- + STATE_TX_TOKEN1 : + begin + // Data sent? + if (utmi_txready_i) + begin + if (utmi_linectrl_r) + next_state_r = STATE_TX_IFS; + else + next_state_r = STATE_TX_TOKEN2; + end + end + //----------------------------------------- + // TX_TOKEN2 (byte 2 of token) + //----------------------------------------- + STATE_TX_TOKEN2 : + begin + // Data sent? + if (utmi_txready_i) + next_state_r = STATE_TX_TOKEN3; + end + //----------------------------------------- + // TX_TOKEN3 (byte 3 of token) + //----------------------------------------- + STATE_TX_TOKEN3 : + begin + // Data sent? + if (utmi_txready_i) + begin + // SOF - no data packet + if (send_sof_q) + next_state_r = STATE_TX_IFS; + // IN - wait for data + else if (in_transfer_q) + next_state_r = STATE_RX_WAIT; + // OUT/SETUP - Send data or ZLP + else + next_state_r = STATE_TX_IFS; + end + end + //----------------------------------------- + // TX_IFS + //----------------------------------------- + STATE_TX_IFS : + begin + // IFS expired + if (tx_ifs_ready_w) + begin + // SOF - no data packet + if (send_sof_q) + next_state_r = STATE_IDLE; + // OUT/SETUP - Send data or ZLP + else + next_state_r = STATE_TX_PID; + end + end + //----------------------------------------- + // TX_PID + //----------------------------------------- + STATE_TX_PID : + begin + // Last data byte sent? + if (utmi_txready_i && (byte_count_q == 16'b0)) + next_state_r = STATE_TX_CRC1; + else if (utmi_txready_i) + next_state_r = STATE_TX_DATA; + end + //----------------------------------------- + // TX_DATA + //----------------------------------------- + STATE_TX_DATA : + begin + // Last data byte sent? + if (utmi_txready_i && (byte_count_q == 16'b0)) + next_state_r = STATE_TX_CRC1; + end + //----------------------------------------- + // TX_CRC1 (first byte) + //----------------------------------------- + STATE_TX_CRC1 : + begin + // Data sent? + if (utmi_txready_i) + next_state_r = STATE_TX_CRC2; + end + //----------------------------------------- + // TX_CRC (second byte) + //----------------------------------------- + STATE_TX_CRC2 : + begin + // Data sent? + if (utmi_txready_i) + begin + // If a response is expected + if (wait_resp_q) + next_state_r = STATE_RX_WAIT; + // No response expected (e.g ISO transfer) + else + next_state_r = STATE_IDLE; + end + end + //----------------------------------------- + // STATE_TX_WAIT + //----------------------------------------- + STATE_TX_WAIT : + begin + // Waited long enough? + if (autoresp_thresh_w) + next_state_r = STATE_TX_ACKNAK; + end + //----------------------------------------- + // STATE_TX_ACKNAK + //----------------------------------------- + STATE_TX_ACKNAK : + begin + // Data sent? + if (utmi_txready_i) + next_state_r = STATE_IDLE; + end + //----------------------------------------- + // STATE_RX_WAIT + //----------------------------------------- + STATE_RX_WAIT : + begin + // Data received? + if (data_ready_w) + next_state_r = STATE_RX_DATA; + // Waited long enough? + else if (rx_resp_timeout_w) + next_state_r = STATE_IDLE; + end + //----------------------------------------- + // RX_DATA + //----------------------------------------- + STATE_RX_DATA : + begin + // Receive complete + if (~rx_active_w) + begin + // Send ACK but incoming data had CRC error, do not ACK + if (crc_error_w && send_ack_q && status_response_data_w) + next_state_r = STATE_IDLE; + // Send an ACK response without CPU interaction? + else if (send_ack_q && status_response_data_w) + next_state_r = STATE_TX_WAIT; + else + next_state_r = STATE_IDLE; + end + end + //----------------------------------------- + // IDLE / RECEIVE BEGIN + //----------------------------------------- + STATE_IDLE : + begin + // Token transfer request + if (start_i) + next_state_r = STATE_TX_TOKEN1; + end + default : + ; + endcase +end + +// Update state +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + state_q <= STATE_IDLE; +else + state_q <= next_state_r; + +//----------------------------------------------------------------- +// Tx Token +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + token_q <= 16'h0000; +else if (state_q == STATE_IDLE) + token_q <= {token_dev_i, token_ep_i, 5'b0}; +// PID of token sent, capture calculated CRC for token packet +else if (state_q == STATE_TX_TOKEN1 && utmi_txready_i) + token_q[4:0] <= crc5_next_w; + +//----------------------------------------------------------------- +// Tx Timer +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + last_tx_time_q <= 9'd0; +// Start counting from last Tx +else if (state_q == STATE_IDLE || (utmi_txvalid_o && utmi_txready_i)) + last_tx_time_q <= 9'd0; +// Increment the Tx timeout +else if (last_tx_time_q != RX_TIMEOUT) + last_tx_time_q <= last_tx_time_q + 9'd1; + + +//----------------------------------------------------------------- +// Transmit / Receive counter +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + byte_count_q <= 16'h0000; +// New transfer request (not automatic SOF request) +else if (state_q == STATE_IDLE && start_i && !sof_transfer_i) + byte_count_q <= data_len_i; +else if (state_q == STATE_RX_WAIT) + byte_count_q <= 16'h0000; +// Transmit byte +else if ((state_q == STATE_TX_PID || state_q == STATE_TX_DATA) && utmi_txready_i) +begin + // Count down data left to send + if (byte_count_q != 16'd0) + byte_count_q <= byte_count_q - 16'd1; +end +// Received byte +else if (state_q == STATE_RX_DATA && data_ready_w && !crc_byte_w) + byte_count_q <= byte_count_q + 16'd1; + +//----------------------------------------------------------------- +// Transfer start ack +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + start_ack_q <= 1'b0; +// First byte of PID sent, ack transfer request +else if (state_q == STATE_TX_TOKEN1 && utmi_txready_i) + start_ack_q <= 1'b1; +else + start_ack_q <= 1'b0; + +//----------------------------------------------------------------- +// Record request details +//----------------------------------------------------------------- +reg utmi_linectrl_r = 1'b0; +always @ (posedge clk_i or posedge rst_i) +if (rst_i) +begin + in_transfer_q <= 1'b0; + send_ack_q <= 1'b0; + send_data1_q <= 1'b0; + send_sof_q <= 1'b0; +end +// Start of new request +else if (state_q == STATE_IDLE && start_i) +begin + // Transfer request + // e.g. (H)SOF [sof_transfer_i] + // (H)OUT + (H)DATA + (F)ACK/NACK/STALL [data_len_i >= 0 && !in_transfer_i] + // (H)IN + (F)DATA + (H)ACK [in_transfer_i] + // (H)IN + (F)NAK/STALL [in_transfer_i] + in_transfer_q <= in_transfer_i; + + // Send ACK in response to IN DATA + send_ack_q <= in_transfer_i && resp_expected_i; + + // DATA0/1 + send_data1_q <= data_idx_i; + utmi_linectrl_r <= sof_transfer_i & in_transfer_i; + send_sof_q <= sof_transfer_i; +end + +//----------------------------------------------------------------- +// Response delay timer +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +if (rst_i) +begin + rx_time_q <= RX_TIME_ZERO; + rx_time_en_q <= 1'b0; +end +else if (state_q == STATE_IDLE) +begin + rx_time_q <= RX_TIME_ZERO; + rx_time_en_q <= 1'b0; +end +// Receive complete +else if (state_q == STATE_RX_DATA && !utmi_rxactive_i) +begin + // Reset time since end of last data byte + rx_time_q <= RX_TIME_ZERO; + rx_time_en_q <= 1'b1; +end +// Increment timer if enabled (and less than the threshold) +else if (rx_time_en_q && rx_time_q != RX_TIME_READY) + rx_time_q <= rx_time_q + RX_TIME_INC; + +// Response expected +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + wait_resp_q <= 1'b0; +// Incoming data +else if (state_q == STATE_RX_WAIT && data_ready_w) + wait_resp_q <= 1'b0; +else if (state_q == STATE_IDLE && start_i) + wait_resp_q <= resp_expected_i; + +//----------------------------------------------------------------- +// Status +//----------------------------------------------------------------- +always @ (posedge clk_i or posedge rst_i) +begin + if (rst_i) + begin + status_response_q <= 8'h00; + status_timeout_q <= 1'b0; + status_rx_done_q <= 1'b0; + status_tx_done_q <= 1'b0; + end + else + begin + case (state_q) + + //----------------------------------------- + // RX_WAIT + //----------------------------------------- + STATE_RX_WAIT : + begin + // Store response PID + if (data_ready_w) + status_response_q <= rx_data_w; + + // Waited long enough? + if (rx_resp_timeout_w) + status_timeout_q <= 1'b1; + + status_tx_done_q <= 1'b0; + end + //----------------------------------------- + // RX_DATA + //----------------------------------------- + STATE_RX_DATA : + begin + // Receive complete + if (!utmi_rxactive_i) + status_rx_done_q <= 1'b1; + else + status_rx_done_q <= 1'b0; + end + //----------------------------------------- + // TX_CRC (second byte) + //----------------------------------------- + STATE_TX_CRC2 : + begin + // Data sent? + if (utmi_txready_i && !wait_resp_q) + begin + // Transfer now complete + status_tx_done_q <= 1'b1; + end + end + //----------------------------------------- + // IDLE / RECEIVE BEGIN + //----------------------------------------- + STATE_IDLE : + begin + // Transfer request + // e.g. (H)SOF [sof_transfer_i] + // (H)OUT + (H)DATA + (F)ACK/NACK/STALL [data_len_i >= 0 && !in_transfer_i] + // (H)IN + (F)DATA + (H)ACK [in_transfer_i] + // (H)IN + (F)NAK/STALL [in_transfer_i] + if (start_i && !sof_transfer_i) // (not automatic SOF request) + begin + // Clear status + status_response_q <= 8'h00; + status_timeout_q <= 1'b0; + end + + status_rx_done_q <= 1'b0; + status_tx_done_q <= 1'b0; + end + //----------------------------------------- + // DEFAULT + //----------------------------------------- + default : + begin + status_rx_done_q <= 1'b0; + status_tx_done_q <= 1'b0; + end + endcase + end +end + + +//----------------------------------------------------------------- +// Data delay (to strip the CRC16 trailing bytes) +//----------------------------------------------------------------- +reg [31:0] data_buffer_q; +reg [3:0] data_valid_q; +reg [3:0] rx_active_q; + +wire shift_en_w = (utmi_rxvalid_i & utmi_rxactive_i) || !utmi_rxactive_i; + +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + data_buffer_q <= 32'b0; +else if (shift_en_w) + data_buffer_q <= {utmi_data_i, data_buffer_q[31:8]}; + +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + data_valid_q <= 4'b0; +else if (shift_en_w) + data_valid_q <= {(utmi_rxvalid_i & utmi_rxactive_i), data_valid_q[3:1]}; +else + data_valid_q <= {data_valid_q[3:1], 1'b0}; + +reg [1:0] data_crc_q; +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + data_crc_q <= 2'b0; +else if (shift_en_w) + data_crc_q <= {!utmi_rxactive_i, data_crc_q[1]}; + +always @ (posedge clk_i or posedge rst_i) +if (rst_i) + rx_active_q <= 4'b0; +else + rx_active_q <= {utmi_rxactive_i, rx_active_q[3:1]}; + +assign rx_data_w = data_buffer_q[7:0]; +assign data_ready_w = data_valid_q[0]; +assign crc_byte_w = data_crc_q[0]; +assign rx_active_w = rx_active_q[0]; + +//----------------------------------------------------------------- +// CRC +//----------------------------------------------------------------- + +// CRC16 (Data) +usbh_crc16 +u_crc16 +( + .crc_i(crc_sum_q), + .data_i(crc_data_in_w), + .crc_o(crc_out_w) +); + +// CRC5 (Token) +usbh_crc5 +u_crc5 +( + .crc_i(5'h1F), + .data_i(token_q[15:5]), + .crc_o(crc5_out_w) +); + +// CRC control / check +always @ (posedge clk_i or posedge rst_i) +begin + if (rst_i) + begin + crc_sum_q <= 16'hFFFF; + status_crc_err_q <= 1'b0; + end + else + begin + case (state_q) + //----------------------------------------- + // TX_PID + //----------------------------------------- + STATE_TX_PID : + begin + // First byte is PID (not CRC'd), reset CRC16 + crc_sum_q <= 16'hFFFF; + end + //----------------------------------------- + // TX_DATA + //----------------------------------------- + STATE_TX_DATA : + begin + // Data sent? + if (utmi_txready_i) + begin + // Next CRC start value + crc_sum_q <= crc_out_w; + end + end + //----------------------------------------- + // RX_WAIT + //----------------------------------------- + STATE_RX_WAIT : + begin + // Reset CRC16 + crc_sum_q <= 16'hFFFF; + end + //----------------------------------------- + // RX_DATA + //----------------------------------------- + STATE_RX_DATA : + begin + // Data received? + if (data_ready_w) + begin + // Next CRC start value + crc_sum_q <= crc_out_w; + end + // Receive complete + else if (!rx_active_w) + begin + // If some data received, check CRC + if (crc_error_w && status_response_data_w) + status_crc_err_q <= 1'b1; + else + status_crc_err_q <= 1'b0; + end + end + + //----------------------------------------- + // IDLE / RECEIVE BEGIN + //----------------------------------------- + STATE_IDLE : + begin + // Start transfer request + if (start_i && !sof_transfer_i) + begin + // Clear error flag! + status_crc_err_q <= 1'b0; + end + end + default : + ; + endcase + end +end + +//----------------------------------------------------------------- +// Assignments +//----------------------------------------------------------------- +wire [15:0] token_rev_w; + +genvar i; +generate +for (i=0; i < 16; i=i+1) +begin : LOOP + assign token_rev_w[i] = token_q[15-i]; +end +endgenerate + +reg utmi_txvalid_r; +reg [7:0] utmi_data_r; + +always @ * +begin + if (state_q == STATE_TX_CRC1) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = crc_sum_q[7:0] ^ 8'hFF; + end + else if (state_q == STATE_TX_CRC2) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = crc_sum_q[15:8] ^ 8'hFF; + end + else if (state_q == STATE_TX_TOKEN1) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = token_pid_i; + end + else if (state_q == STATE_TX_TOKEN2) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = token_rev_w[7:0]; + end + else if (state_q == STATE_TX_TOKEN3) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = token_rev_w[15:8]; + end + else if (state_q == STATE_TX_PID) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = send_data1_q ? PID_DATA1 : PID_DATA0; + end + else if (state_q == STATE_TX_ACKNAK) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = PID_ACK; + end + else if (state_q == STATE_TX_DATA) + begin + utmi_txvalid_r = 1'b1; + utmi_data_r = tx_data_i; + end + else + begin + utmi_txvalid_r = 1'b0; + utmi_data_r = 8'b0; + end +end + +assign utmi_txvalid_o = utmi_txvalid_r; +assign utmi_data_o = utmi_data_r; +assign utmi_linectrl_o = utmi_linectrl_r; + +// Push incoming data into FIFO (not PID or CRC) +assign rx_data_o = rx_data_w; +assign rx_push_o = (state_q != STATE_IDLE && state_q != STATE_RX_WAIT) & data_ready_w & !crc_byte_w; + +assign crc_data_in_w = (state_q == STATE_RX_DATA) ? rx_data_w : tx_data_i; + +assign rx_count_o = byte_count_q; +assign idle_o = (state_q == STATE_IDLE); + +assign ack_o = start_ack_q; + +assign tx_pop_o = state_q == STATE_TX_DATA && utmi_txready_i; + +assign tx_done_o = status_tx_done_q; +assign rx_done_o = status_rx_done_q; +assign crc_err_o = status_crc_err_q; +assign timeout_o = status_timeout_q; +assign response_o = status_response_q; + + + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp.v new file mode 100644 index 0000000000000000000000000000000000000000..0594a3f96078c464b266172465dc40c01b3b1e7a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp.v @@ -0,0 +1,729 @@ +// vdp.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" +`include "layer_encoding.vh" + +module vdp #( + parameter [0:0] ENABLE_WIDESCREEN = 0, + parameter [1:0] LAYERS_TOTAL = 3 +) ( + input clk, + input reset, + + // Host interface + + input [15:0] host_address, + + input [15:0] host_write_data, + input host_write_en, + + input host_read_en, + output reg [15:0] host_read_data, + output host_ready, + + // VGA output + + output reg [3:0] r, + output reg [3:0] g, + output reg [3:0] b, + + output vga_hsync, + output vga_vsync, + + output active_display, + + // Single-cycle strobes, NOT suitable for VGA + + output line_ended, + output frame_ended, + output active_frame_ended, + + // VRAM interface + + output [13:0] vram_address_even, + output vram_we_even, + input [15:0] vram_read_data_even, + output [15:0] vram_write_data_even, + + output [13:0] vram_address_odd, + output vram_we_odd, + input [15:0] vram_read_data_odd, + output [15:0] vram_write_data_odd, + + // Copper RAM interface + + output cop_ram_read_en, + output [10:0] cop_ram_read_address, + input [15:0] cop_ram_read_data +); + // --- Video timing --- + + // 848x480@60hz + + localparam H_ACTIVE_WIDTH_848 = 848; + localparam H_SYNC_848 = 112; + localparam H_BACKPORCH_848 = 112; + + localparam V_FRONTPORCH_848 = 6; + localparam V_SYNC_848 = 8; + localparam V_BACKPORCH_848 = 23; + + // 640x480@60hz + + localparam H_ACTIVE_WIDTH_640 = 640; + localparam H_SYNC_640 = 96; + localparam H_BACKPORCH_640 = 48; + + localparam V_FRONTPORCH_640 = 11; + localparam V_SYNC_640 = 2; + localparam V_BACKPORCH_640 = 31; + + // common between both modes + + localparam V_ACTIVE_HEIGHT = 480; + localparam H_FRONTPORCH = 16; + + // select one of the above video modes according to parameter + + localparam H_ACTIVE_WIDTH = ENABLE_WIDESCREEN ? H_ACTIVE_WIDTH_848 : H_ACTIVE_WIDTH_640; + localparam H_SYNC = ENABLE_WIDESCREEN ? H_SYNC_848 : H_SYNC_640; + localparam H_BACKPORCH = ENABLE_WIDESCREEN ? H_BACKPORCH_848 : H_BACKPORCH_640; + + localparam V_FRONTPORCH = ENABLE_WIDESCREEN ? V_FRONTPORCH_848 : V_FRONTPORCH_640; + localparam V_SYNC = ENABLE_WIDESCREEN ? V_SYNC_848 : V_SYNC_640; + localparam V_BACKPORCH = ENABLE_WIDESCREEN ? V_BACKPORCH_848 : V_BACKPORCH_640; + + // for use by other blocks below + + localparam OFFSCREEN_X_TOTAL = H_SYNC + H_FRONTPORCH + H_BACKPORCH; + localparam HEIGHT_TOTAL = V_ACTIVE_HEIGHT + V_FRONTPORCH + V_SYNC + V_BACKPORCH; + + wire [11:0] raster_x; + wire [10:0] raster_y; + + // verilator lint_off PINMISSING + + vdp_vga_timing #( + .H_ACTIVE_WIDTH(H_ACTIVE_WIDTH), + .V_ACTIVE_HEIGHT(V_ACTIVE_HEIGHT), + .H_FRONTPORCH(H_FRONTPORCH), + .H_SYNC(H_SYNC), + .H_BACKPORCH(H_BACKPORCH), + .V_FRONTPORCH(V_FRONTPORCH), + .V_SYNC(V_SYNC), + .V_BACKPORCH(V_BACKPORCH) + ) vga_timing ( + .clk(clk), + + .raster_x(raster_x), + .raster_y(raster_y), + + .hsync(vga_hsync), + .vsync(vga_vsync), + .active_display(active_display), + .active_frame_ended(active_frame_ended), + + .line_ended(line_ended), + .frame_ended(frame_ended) + ); + + // verilator lint_on PINMISSING + + // --- Host interface --- + + wire [4:0] register_write_address, register_read_address; + wire [15:0] register_write_data; + wire register_write_en; + + vdp_host_interface host_interface( + .clk(clk), + .reset(reset), + + .host_read_en(host_read_en), + .ready(host_ready), + .vram_write_pending(vram_write_pending), + + .host_write_en(host_write_en), + .register_write_en(register_write_en), + + .cop_write_address(cop_write_address), + .cop_write_data(cop_write_data), + .cop_write_en(copper_write_en), + + .host_address(host_address), + .host_write_data(host_write_data), + .register_write_data(register_write_data), + .register_write_address(register_write_address), + .read_address(register_read_address) + ); + + // --- Copper --- + + wire [4:0] cop_write_address; + wire [15:0] cop_write_data; + wire copper_write_en; + wire cop_write_ready; + + vdp_copper copper( + .clk(clk), + .reset(reset), + + .enable(cop_enable), + + .raster_x(raster_x), + .raster_y(raster_y), + + .ram_read_en(cop_ram_read_en), + .ram_read_address(cop_ram_read_address), + .ram_read_data(cop_ram_read_data), + + .reg_write_address(cop_write_address), + .reg_write_data(cop_write_data), + .reg_write_en(copper_write_en) + ); + + // --- Register writes --- + + reg [5:0] layer_enable = 0; + reg [4:0] layer_enable_alpha_over = 0; + + wire affine_enabled = layer_enable[5]; + + reg [15:0] scroll_tile_base; + reg [15:0] scroll_map_base; + + reg [15:0] scroll_x [0:3]; + reg [15:0] scroll_y [0:3]; + + reg [3:0] scroll_use_wide_map; + + reg [3:0] sprite_tile_base; + wire [13:0] full_sprite_tile_base = {sprite_tile_base, 10'b0}; + + reg [15:0] vram_write_data_16b; + reg [1:0] vram_port_write_en_mask; + reg [14:0] vram_write_address_full; + wire [13:0] vram_write_address_16b = vram_write_address_full[14:1]; + reg [7:0] vram_port_address_increment; + reg vram_write_pending; + + reg cop_enable; + + // --- Writes: comb. --- + + always @* begin + palette_write_en = 0; + + // This block has the same structure as the below one, for consistency + // Looks odd while only one case is handled for the time being + + if (register_write_en) begin + if (!register_write_address[4]) begin + case (register_write_address[3:0]) + 3: begin + palette_write_en = 1; + end + endcase + end + end + end + + // --- Writes: clocked --- + + always @(posedge clk) begin + if (reset) begin + cop_enable <= 0; + end + + sprite_metadata_write_en <= 0; + sprite_metadata_block_select <= sprite_metadata_block_select_nx; + + if (sprite_metadata_write_en && sprite_meta_address_needs_increment) begin + sprite_metadata_address <= sprite_metadata_address + 1; + end + + if (palette_write_en) begin + palette_write_address <= palette_write_address + 1; + end + + if (vram_write_pending && vram_written) begin + vram_write_pending <= 0; + vram_write_address_full <= vram_write_address_full + vram_port_address_increment; + vram_port_write_en_mask <= 2'b00; + end + + if (register_write_en) begin + if (!register_write_address[4]) begin + case (register_write_address[3:0]) + 0: begin + sprite_metadata_address <= register_write_data[7:0]; + sprite_metadata_block_select <= 3'b001; + end + 1: begin + // (sprite_metadata_write_data driven directly by register_write_data below) + sprite_metadata_write_en <= 1; + end + 2: begin + palette_write_address <= register_write_data[7:0]; + end + 3: begin + // (palette write, which is handed separately above) + end + 4: begin + vram_write_address_full <= register_write_data; + vram_port_write_en_mask <= 2'b00; + end + 5: begin + vram_write_data_16b <= register_write_data; + vram_port_write_en_mask <= vram_write_address_full[0] ? 2'b10 : 2'b01; + + vram_write_pending <= 1; + end + 6: begin + vram_port_address_increment <= register_write_data[7:0]; + end + 7: begin + sprite_tile_base <= register_write_data[13:10]; + end + 8: begin + cop_enable <= register_write_data[0]; + end + 9: begin + scroll_tile_base <= register_write_data; + end + 10: begin + scroll_map_base <= register_write_data; + end + 11: begin + layer_enable <= register_write_data[5:0]; + end + 12: begin + layer_enable_alpha_over <= register_write_data[7:0]; + end + 13: begin + scroll_use_wide_map <= register_write_data[3:0]; + end + default: begin + `stop($display("unimplemented register: %x", register_write_address);) + end + endcase + end else if (register_write_address[4]) begin + case (register_write_address[3:2]) + 0: scroll_x[register_write_address[1:0]] <= register_write_data; + 1: scroll_y[register_write_address[1:0]] <= register_write_data; + endcase + end + end + end + + // --- Register reads --- + + always @(posedge clk) begin + case (register_read_address[1]) + 0: host_read_data <= raster_x; + 1: host_read_data <= raster_y; + endcase + end + + // --- Sprite metadata writing --- + + reg [7:0] sprite_metadata_address; + reg [2:0] sprite_metadata_block_select; + wire [15:0] sprite_metadata_write_data = register_write_data; + reg sprite_metadata_write_en; + + reg [2:0] sprite_metadata_block_select_nx; + wire sprite_meta_address_needs_increment = sprite_metadata_block_select[2]; + + always @* begin + sprite_metadata_block_select_nx = sprite_metadata_block_select; + + if (sprite_metadata_write_en) begin + sprite_metadata_block_select_nx = {sprite_metadata_block_select[1:0], sprite_metadata_block_select[2]}; + end + end + + // --- Affine layer register mapping --- + + // affine layer reuses the regular scroll registers + // the two kinds of layers can't be active at the same time so reuse these to save LCs + + wire [15:0] affine_pretranslate_x = scroll_x[0]; + wire [15:0] affine_pretranslate_y = scroll_y[1]; + + wire [15:0] affine_a = scroll_x[1]; + wire [15:0] affine_b = scroll_x[2]; + wire [15:0] affine_c = scroll_x[3]; + wire [15:0] affine_d = scroll_y[0]; + + wire [15:0] affine_translate_x = scroll_y[2]; + wire [15:0] affine_translate_y = scroll_y[3]; + + // --- Palette RAM --- + + reg [7:0] palette_write_address; + wire [15:0] pal_write_data = register_write_data; + reg palette_write_en; + + reg [15:0] palette_ram [0:255]; + reg [15:0] palette_output; + + wire [7:0] palette_masked_read_address = prioritized_masked_pixel; + reg [15:0] palette_masked_output; + + wire [7:0] palette_read_address = prioritized_pixel; + + always @(posedge clk) begin + if (palette_write_en) begin + palette_ram[palette_write_address] <= pal_write_data; + end + + palette_output <= palette_ram[palette_read_address]; + palette_masked_output <= palette_ram[palette_masked_read_address]; + end + + // --- Blender --- + + assign layer_mask = ~layer_enable_alpha_over; + + wire source_layer_enabled = |(prioritized_masked_layer & layer_enable_alpha_over); + wire [11:0] blender_output_color; + + vdp_blender blender( + .clk(clk), + + .source_layer_enabled(source_layer_enabled), + .source_color(palette_masked_output), + + .dest_color(palette_output), + + .output_color(blender_output_color) + ); + + wire [11:0] output_color = (active_display ? blender_output_color : 12'b0); + + always @(posedge clk) begin + r <= output_color[11:8]; + g <= output_color[7:4]; + b <= output_color[3:0]; + end + + // --- Raster offset for scrolling layers --- + + localparam SCROLL_START_LEAD_TIME = 32; + localparam SCROLL_OFFSCREEN_ADVANCE = -7; + + reg [9:0] raster_x_offset; + + localparam HEIGHT_DIFF = HEIGHT_TOTAL - 512; + + wire scroll_base_x_start = raster_x == (OFFSCREEN_X_TOTAL - SCROLL_START_LEAD_TIME); + + // the +1 is to preserve alignment between raster_x[2:0] (used to sequence VRAM access) + localparam SCROLL_BASE_X_INITIAL = SCROLL_OFFSCREEN_ADVANCE + 1; + + always @(posedge clk) begin + raster_x_offset <= scroll_base_x_start ? SCROLL_BASE_X_INITIAL : raster_x_offset + 1; + end + + // --- Raster offset for sprites --- + + reg [9:0] sprites_x; + reg [8:0] sprites_y; + + localparam SPRITE_X_INITIAL = -1; + localparam SPRITE_START_LEAD_TIME = 10; + localparam SPRITE_HOLD_TIME = HEIGHT_TOTAL - 512; + + // alternatively instead of comparing all bits in raster_x, just check for all 1-bits + // since it counts up and resets to 0 predictably + wire sprites_x_start = (raster_x == (OFFSCREEN_X_TOTAL - SPRITE_START_LEAD_TIME - 1)); + wire sprites_x_reset = line_ended; + reg sprites_x_counting; + + always @(posedge clk) begin + // used for line buffer read address for display + if (sprites_x_reset) begin + sprites_x_counting <= 0; + end else if (sprites_x_start) begin + sprites_x_counting <= 1; + end + + sprites_x <= (sprites_x_counting ? sprites_x + 1 : SPRITE_X_INITIAL); + end + + localparam SPRITE_MAX_HEIGHT = 16; + localparam SPRITE_Y_DELAY = 2; + + always @(posedge clk) begin + if (line_ended) begin + if (raster_y == (HEIGHT_TOTAL - SPRITE_MAX_HEIGHT - SPRITE_Y_DELAY)) begin + sprites_y <= 512 - SPRITE_MAX_HEIGHT; + end else begin + sprites_y <= sprites_y + 1; + end + end + end + + // --- Shared pixel row reverser --- + + // Sprites and scroll layers can optionally have their graphics data flipped horizontally. + // Since only 1 of these can be read at a time, this reversing logic can be shared between all. + + wire map_pixel_row_needs_x_flip = |(scroll_x_flip & scroll_char_load); + wire sprite_pixel_row_needs_x_flip = vram_sprite_read_data_needs_x_flip && vram_sprite_read_data_valid; + wire should_reverse_pixel_row = map_pixel_row_needs_x_flip || sprite_pixel_row_needs_x_flip; + + reg [31:0] pixel_row_ordered; + + always @* begin + if (should_reverse_pixel_row) begin + pixel_row_ordered[31:28] = vram_read_data_r[3:0]; + pixel_row_ordered[27:24] = vram_read_data_r[7:4]; + pixel_row_ordered[23:20] = vram_read_data_r[11:8]; + pixel_row_ordered[19:16] = vram_read_data_r[15:12]; + + pixel_row_ordered[15:12] = vram_read_data_r[19:16]; + pixel_row_ordered[11:8] = vram_read_data_r[23:20]; + pixel_row_ordered[7:4] = vram_read_data_r[27:24]; + pixel_row_ordered[3:0] = vram_read_data_r[31:28]; + end else begin + pixel_row_ordered = vram_read_data_r; + end + end + + // --- Scroll pixel generators --- + + localparam [1:0] LAYER_LAST = LAYERS_TOTAL - 1; + + wire [7:0] scroll_output_pixel [0:3]; + + generate + genvar i; + for (i = 0; i < LAYERS_TOTAL; i = i + 1) begin : scroll_pixel_gen + vdp_scroll_pixel_generator #( + .STAGE_PIXEL_ROW(i != LAYER_LAST) + ) scroll_pixel_generator ( + .clk(clk), + + .scroll_x_granular(scroll_x[i][2:0]), + .raster_x_granular(raster_x_offset[2:0]), + .pixel_row(pixel_row_ordered), + .palette_number(scroll_palette[i]), + .meta_load_enable(scroll_meta_load[i]), + .tile_row_load_enable(scroll_char_load[i]), + .shifter_preload_load_enable(load_all_scroll_row_data), + + .pixel(scroll_output_pixel[i]) + ); + end + endgenerate + + // --- Priority control --- + + localparam [4:0] LAYER_ENABLE_MASK = (1 << (LAYERS_TOTAL)) - 1 | `LAYER_SPRITES_OHE; + + wire [7:0] prioritized_pixel; + wire [4:0] prioritized_masked_layer; + wire [7:0] prioritized_masked_pixel; + + // verilator lint_off UNUSED + wire [4:0] prioritized_layer; + // verilator lint_on UNUSED + + wire [4:0] layer_mask; + + wire [7:0] selected_layer_pixel = affine_enabled ? affine_output_pixel : scroll_output_pixel[0]; + + vdp_priority_compute priority_compute( + .clk(clk), + + .scroll0_pixel(selected_layer_pixel), + .scroll0_is_8bpp(affine_enabled), + + .scroll1_pixel(scroll_output_pixel[1]), + .scroll2_pixel(scroll_output_pixel[2]), + .scroll3_pixel(scroll_output_pixel[3]), + + .sprite_pixel(sprite_pixel), + .sprite_priority(sprite_pixel_priority), + + .layer_enable(layer_enable[4:0] & (affine_enabled ? `LAYER_SPRITES_OHE | `LAYER_SCROLL0_OHE : LAYER_ENABLE_MASK)), + .layer_mask(layer_mask), + + .prioritized_pixel(prioritized_pixel), + .prioritized_layer(prioritized_layer), + .prioritized_masked_layer(prioritized_masked_layer), + .prioritized_masked_pixel(prioritized_masked_pixel) + ); + + // --- VRAM bus arbiter --- + + reg [15:0] vram_read_data_even_r, vram_read_data_odd_r; + wire [31:0] vram_read_data_r = {vram_read_data_odd_r, vram_read_data_even_r}; + + always @(posedge clk) begin + vram_read_data_even_r <= vram_read_data_even; + vram_read_data_odd_r <= vram_read_data_odd; + end + + wire [3:0] scroll_meta_load; + wire [3:0] scroll_char_load; + + wire load_all_scroll_row_data; + wire vram_written; + + wire [3:0] scroll_palette [0:3]; + wire [3:0] scroll_x_flip; + + vdp_vram_bus_arbiter_standard bus_arbiter( + .clk(clk), + + .raster_x_offset(raster_x_offset), + .raster_x(raster_x), + .raster_y(raster_y), + + // Scroll attributes + + .scroll_x_0(scroll_x[0]), .scroll_x_1(scroll_x[1]), .scroll_x_2(scroll_x[2]), .scroll_x_3(scroll_x[3]), + .scroll_y_0(scroll_y[0]), .scroll_y_1(scroll_y[1]), .scroll_y_2(scroll_y[2]), .scroll_y_3(scroll_y[3]), + + .scroll_tile_base(scroll_tile_base), + .scroll_map_base(scroll_map_base), + .scroll_use_wide_map(scroll_use_wide_map), + + // Affine attributes + + .affine_enabled(affine_enabled), + .affine_offscreen(affine_offscreen), + + .affine_vram_address_even(affine_vram_address_even), .affine_vram_address_odd(affine_vram_address_odd), + + // Sprite attributes + + .vram_sprite_address(vram_sprite_address), + + // Output control for various functional blocks + + .vram_written(vram_written), + .load_all_scroll_row_data(load_all_scroll_row_data), + .vram_sprite_read_data_valid(vram_sprite_read_data_valid), + + .scroll_char_load(scroll_char_load), + .scroll_meta_load(scroll_meta_load), + + // VRAM write control + + .vram_port_write_en_mask(vram_port_write_en_mask), + .vram_write_address_16b(vram_write_address_16b), + .vram_write_data_16b(vram_write_data_16b), + + // Output scroll attributes + + .scroll_palette_0(scroll_palette[0]), .scroll_palette_1(scroll_palette[1]), + .scroll_palette_2(scroll_palette[2]), .scroll_palette_3(scroll_palette[3]), + + .scroll_x_flip_0(scroll_x_flip[0]), .scroll_x_flip_1(scroll_x_flip[1]), + .scroll_x_flip_2(scroll_x_flip[2]), .scroll_x_flip_3(scroll_x_flip[3]), + + // VRAM interface + + .vram_read_data_even(vram_read_data_even_r), + .vram_read_data_odd(vram_read_data_odd_r), + + .vram_address_even(vram_address_even), .vram_address_odd(vram_address_odd), + .vram_write_data_even(vram_write_data_even), .vram_write_data_odd(vram_write_data_odd), + .vram_we_even(vram_we_even), .vram_we_odd(vram_we_odd) + ); + + // --- Sprites --- + + wire [7:0] sprite_pixel; + wire [1:0] sprite_pixel_priority; + + wire [13:0] vram_sprite_address; + wire vram_sprite_read_data_needs_x_flip; + wire vram_sprite_read_data_valid; + + wire sprite_core_reset = line_ended; + + vdp_sprite_core sprites( + .clk(clk), + .start_new_line(sprite_core_reset), + + .render_x(sprites_x), + .render_y(sprites_y), + + .meta_address(sprite_metadata_address), + .meta_write_data(sprite_metadata_write_data), + .meta_block_select(sprite_metadata_block_select), + .meta_we(sprite_metadata_write_en), + + .vram_base_address(full_sprite_tile_base), + .vram_read_address(vram_sprite_address), + .vram_read_data(pixel_row_ordered), + .vram_read_data_needs_x_flip(vram_sprite_read_data_needs_x_flip), + .vram_data_valid(vram_sprite_read_data_valid), + + .pixel(sprite_pixel), + .pixel_priority(sprite_pixel_priority) + ); + + // --- Affine layer --- + + wire [13:0] affine_vram_address_even, affine_vram_address_odd; + + wire [7:0] affine_output_pixel; + + reg [9:0] affine_x; + wire [8:0] affine_y = raster_y; + + wire affine_x_start = raster_x == (OFFSCREEN_X_TOTAL - 17); + wire affine_x_end = line_ended; + + reg affine_offscreen; + + always @(posedge clk) begin + affine_x <= affine_x + 1; + + if (affine_x_start) begin + affine_x <= 0; + affine_offscreen <= 0; + end else if (affine_x_end) begin + affine_offscreen <= 1; + end + end + + vdp_affine_layer affine( + .clk(clk), + + .x(affine_x), + .y(affine_y), + + .pretranslate_x(affine_pretranslate_x), + .pretranslate_y(affine_pretranslate_y), + + .translate_x(affine_translate_x), + .translate_y(affine_translate_y), + + .a(affine_a), + .b(affine_b), + .c(affine_c), + .d(affine_d), + + .vram_even_address(affine_vram_address_even), + .vram_even_data(vram_read_data_even_r), + + .vram_odd_address(affine_vram_address_odd), + .vram_odd_data(vram_read_data_odd_r), + + .output_pixel(affine_output_pixel) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_affine_layer.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_affine_layer.v new file mode 100644 index 0000000000000000000000000000000000000000..73e6c0d64a416984080fbb1d8c55163781bd0d85 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_affine_layer.v @@ -0,0 +1,152 @@ +// vdp_affine_layer.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_affine_layer #( + parameter VRAM_READ_LATENCY = 3 +) ( + input clk, + + // Source x/y, derived from current raster position + + input [9:0] x, + input [8:0] y, + + // Translation vectors + + input signed [15:0] pretranslate_x, + input signed [15:0] pretranslate_y, + + input signed [15:0] translate_x, + input signed [15:0] translate_y, + + // 2x2 matrix + + input signed [15:0] a, + input signed [15:0] b, + input signed [15:0] c, + input signed [15:0] d, + + // VRAM interface + + output [13:0] vram_even_address, + input [15:0] vram_even_data, + + output [13:0] vram_odd_address, + input [15:0] vram_odd_data, + + // Output X cycles later + + output reg [7:0] output_pixel +); + // 1. transform input xy + + reg [25:0] xt_full, yt_full; + + wire signed [15:0] pretranslated_x = {{6{1'b0}}, x} + pretranslate_x; + wire signed [15:0] pretranslated_y = {{7{1'b0}}, y} + pretranslate_y; + + // counting LC usage with yosys shows that actual LC FFs aren't spent + // these are "absorbed" into the SB_MAC16 adder as part of inferred mulitply-add + reg signed [25:0] translate_x_r, translate_y_r; + + always @(posedge clk) begin + translate_x_r <= (translate_x << 10) + (1 << 9); + translate_y_r <= (translate_y << 10) + (1 << 9); + end + + // infer 2x SB_MAC16 multiply-add and another 2x for just multiply + always @(posedge clk) begin + xt_full <= pretranslated_x * a + (pretranslated_y * b + translate_x_r); + yt_full <= pretranslated_x * c + (pretranslated_y * d + translate_y_r); + end + + wire [15:0] xt = xt_full >> 10; + wire [15:0] yt = yt_full >> 10; + + // 2. derive vram lookup address from transformed x/y + + // are we in the defined 1024x1024 region? + // apparently super nes games can choose to render a placeholder map char for out of bounds region + wire out_of_bounds = xt[15:10] || yt[15:10]; + wire out_of_bounds_d; + + delay_ff #( + .DELAY(VRAM_READ_LATENCY * 2) + ) out_of_bounds_delay ( + .clk(clk), + .in(out_of_bounds), + .out(out_of_bounds_d) + ); + + wire [6:0] map_x = xt >> 3; + wire [6:0] map_y = yt >> 3; + + wire [2:0] char_x = xt; + wire [2:0] char_y = yt; + + wire [13:0] vram_map_address = {map_y, map_x}; + + // resolved map address + assign vram_even_address = vram_map_address[13:1]; + + // delay to perform byte select within the map word + + wire map_x_d; + + delay_ff #( + .DELAY(VRAM_READ_LATENCY) + ) map_x_delay ( + .clk(clk), + .in(map_x[0]), + .out(map_x_d) + ); + + // delay to perform char fetch using the fetched map word + + delay_ff #( + .WIDTH(6), + .DELAY(VRAM_READ_LATENCY) + ) char_xy_delay ( + .clk(clk), + .in({char_y, char_x}), + .out({char_y_d, char_x_d}) + ); + + // 3. fetch char data using previously fetched map + + wire char_pixel_select_d; + + delay_ff #( + // *2 because +1 fetch for the map, +1 fetch for the pixel + .DELAY(VRAM_READ_LATENCY * 2) + ) char_pixel_select_delay ( + .clk(clk), + .in(char_x[0]), + .out(char_pixel_select_d) + ); + + wire [2:0] char_x_d, char_y_d; + + // char address based on pixel coordinate within char + + wire [7:0] vram_map_fetch_selected = map_x_d ? vram_even_data[15:8] : vram_even_data[7:0]; + wire [7:0] char_id = vram_map_fetch_selected; + wire [13:0] char_address = {char_id, char_y_d, char_x_d}; + + // resolved pixel address + assign vram_odd_address = char_address[13:1]; + + // 4. output the fetched pixel + + wire [7:0] selected_pixel = char_pixel_select_d ? vram_odd_data[15:8] : vram_odd_data[7:0]; + + always @(posedge clk) begin + output_pixel <= out_of_bounds_d ? 0 : selected_pixel; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_blender.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_blender.v new file mode 100644 index 0000000000000000000000000000000000000000..b5f01c60321826e2015f7b3f2c62560de27ca937 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_blender.v @@ -0,0 +1,181 @@ +// vdp_blender.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_blender( + input clk, + + input source_layer_enabled, + input [15:0] source_color, + + input [15:0] dest_color, + + output reg [15:0] output_color +); + reg [31:0] output_source; + reg [31:0] output_dest; + + reg [31:0] mult_source, mult_source_alpha; + reg [31:0] mult_dest, mult_dest_alpha; + + wire [3:0] alpha_source = source_color[15:12]; + wire [3:0] alpha_dest = dest_color[15:12]; + + // sum the output including 1 bit of fraction + // it's more accurate to sum using all fraction bits but doing this saves a bunch of slices + // there is also diminishing returns in perceived accuracy since the fraction MSB is most important + + wire [3:0] blended_r = (output_source[23:19] + output_dest[23:19] + 1) >> 1; + wire [3:0] blended_g = (output_source[15:11] + output_dest[15:11] + 1) >> 1; + wire [3:0] blended_b = (output_source[7:3] + output_dest[7:3] + 1) >> 1; + + // BRAM table for scaled alpha values + + // address: + // ddddsssss + // d: dest alpha + // s: source alpha + + // output: + // ------DD DDDSSSSS + // S: source alpha multiplier + // D: dest alpha multiplier + + reg [15:0] alpha_lut [0:255]; + + reg [7:0] alpha_lut_address; + reg [15:0] alpha_lut_output; + + wire [4:0] alpha_lut_source_output = alpha_lut_output[4:0]; + wire [4:0] alpha_lut_dest_output = alpha_lut_output[9:5]; + +`ifndef ALPHA_LUT + genvar var_source_alpha, var_dest_alpha; + + generate + for (var_dest_alpha = 0; var_dest_alpha < 16; var_dest_alpha = var_dest_alpha + 1) begin: gen_vda + for (var_source_alpha = 0; var_source_alpha < 16; var_source_alpha = var_source_alpha + 1) begin: gen_vsa + + integer mapped_source_alpha, mapped_dest_alpha; + integer lut_index = (var_dest_alpha << 4) + var_source_alpha; + + initial begin + mapped_source_alpha = (var_source_alpha > 0 ? var_source_alpha + 1 : 0); + mapped_dest_alpha = (var_dest_alpha > 0 ? var_dest_alpha + 1 : 0); + mapped_dest_alpha = ((16 - mapped_source_alpha) * mapped_dest_alpha) / 16; + + // this causes an assertion in yosys when using this with cxxrtl + // issue with context on the root cause: + // https://github.com/YosysHQ/yosys/issues/2129 + alpha_lut[lut_index] = mapped_source_alpha | (mapped_dest_alpha << 5); + end + end + end + endgenerate +`else + initial begin + $readmemh(`ALPHA_LUT, alpha_lut); + end +`endif + + always @(posedge clk) begin + alpha_lut_output <= alpha_lut[alpha_lut_address]; + end + + // need to add 2 cycles of pipeline delay to allow LUT lookup + + wire source_visible = (alpha_source != 0) && source_layer_enabled; + wire source_visible_d; + + delay_ff #( + .DELAY(1), + .WIDTH(1) + ) source_visible_dm ( + .clk(clk), + .in(source_visible), + .out(source_visible_d) + ); + + wire [11:0] output_source_color_d; + + delay_ff #( + .DELAY(2), + .WIDTH(12) + ) output_source_color_dm ( + .clk(clk), + .in(source_color[11:0]), + .out(output_source_color_d) + ); + + wire [11:0] output_dest_color_d; + + delay_ff #( + .DELAY(2), + .WIDTH(12) + ) output_dest_color_dm ( + .clk(clk), + .in(dest_color[11:0]), + .out(output_dest_color_d) + ); + + always @(posedge clk) begin + // force address to 0 if dest not opaque + alpha_lut_address <= {alpha_dest, source_visible_d ? alpha_source : 4'b0000}; + + mult_source <= { + 4'b0000, color_r(output_source_color_d), + 4'b0000, color_g(output_source_color_d), + 4'b0000, color_b(output_source_color_d) + }; + + mult_source_alpha <= alpha_lut_source_output; + + mult_dest <= { + 4'b0000, color_r(output_dest_color_d), + 4'b0000, color_g(output_dest_color_d), + 4'b0000, color_b(output_dest_color_d) + }; + + mult_dest_alpha <= alpha_lut_dest_output; + + output_source <= mult_source * mult_source_alpha; + output_dest <= mult_dest * mult_dest_alpha; + + output_color <= {blended_r, blended_g, blended_b}; + end + + // convenience functions to extract a certain color component + + function [3:0] color_b; + input [15:0] argb16; + begin + color_b = argb16[3:0]; + end + endfunction + + function [3:0] color_g; + input [15:0] argb16; + begin + color_g = argb16[7:4]; + end + endfunction + + function [3:0] color_r; + input [15:0] argb16; + begin + color_r = argb16[11:8]; + end + endfunction + + function [3:0] color_a; + input [15:0] argb16; + begin + color_a = argb16[15:12]; + end + endfunction + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_copper.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_copper.v new file mode 100644 index 0000000000000000000000000000000000000000..7d1dffb6ccc64e8a876a91d81b92e937bcc8785b --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_copper.v @@ -0,0 +1,257 @@ +// vdp_copper.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`include "debug.vh" + +`default_nettype none + +module vdp_copper( + input clk, + input reset, + + input enable, + + // Raster tracking + + input [10:0] raster_x, + input [9:0] raster_y, + + // RAM interface + + output [10:0] ram_read_address, + output ram_read_en, + input [15:0] ram_read_data, + + // Register interface + + output reg [4:0] reg_write_address, + output reg [15:0] reg_write_data, + output reg reg_write_en +); + localparam PC_RESET = 10'h000; + + wire operating = !reset && enable; + + reg [10:0] pc; + assign ram_read_address = pc; + + reg ram_read_deferring; + assign ram_read_en = operating && !ram_read_deferring; + + // --- Raster tracking --- + + reg [10:0] target_x; + reg [9:0] target_y; + + wire target_hit = (target_x == raster_x && target_y == raster_y); + + // --- Ops --- + + // oo------ -------- + // o: 2bit op + // remaining fields are op-defined + + wire [1:0] op = ram_read_data[15:14]; + reg [1:0] op_current; + + localparam OP_SET_TARGET = 2'h0; + localparam OP_WRITE_COMPRESSED = 2'h1; + localparam OP_WRITE_REG = 2'h2; + localparam OP_JUMP = 2'h3; + + // SET_TARGET / WAIT_TARGET + + // oo-wsvvv vvvvvvvv + // + // v: raster x/y value + // s: + // 0: select x + // 1: select y + // w: + // 0: don't wait, immediately advance to next op + // 1: wait until raster x/y reaches the target before advancing to next op + + wire op_target_wait = ram_read_data[12]; + wire op_target_select = ram_read_data[11]; + wire [10:0] op_target_value = ram_read_data[10:0]; + + // REG_WRITE + + // ooiiynnn nn-rrrrr + // + // r: target register + // n: number of batches write + // i: reg increment mode (batch size) + // 0: reg[0], repeat + // 1: reg[0], reg[1], repeat + // 2: reg[0], reg[1], reg[2], reg[3], repeat + // y: autoincrement target Y and wait between batches + + wire [4:0] op_write_target_reg = ram_read_data[4:0]; + wire [4:0] op_write_batch_count = ram_read_data[10:6]; + wire op_write_auto_wait = ram_read_data[11]; + wire [1:0] op_write_increment_mode = ram_read_data[13:12]; + + reg [4:0] op_write_target_reg_r; + reg [4:0] op_write_batch_count_r; + reg op_write_auto_wait_r; + reg [1:0] op_write_increment_mode_r; + + // working state + + reg [1:0] op_write_counter; + reg [1:0] op_write_reg_offset; + + always @* begin + case (op_write_increment_mode_r) + 0: op_write_reg_offset = 0; + 1: op_write_reg_offset = op_write_counter & 2'b01; + 2: op_write_reg_offset = op_write_counter & 2'b11; + 3: begin + op_write_reg_offset = 0; + `stop($display("unexpected state");) + end + endcase + end + + reg op_write_batch_complete; + + always @* begin + case (op_write_increment_mode_r) + 0: op_write_batch_complete = 1; + 1: op_write_batch_complete = op_write_counter & 1; + 2: op_write_batch_complete = op_write_counter == 2'b11; + 3: begin + op_write_batch_complete = 1; + `stop($display("unexpected state");) + end + endcase + end + + // REG_WRITE_COMPRESSED + + // oo--yddd ddrrrrrr + // + // r: target register + // d: data to write + // y: autoincrement target Y (then automatically continue) + + wire [5:0] op_write_compressed_reg = ram_read_data[5:0]; + wire [15:0] op_write_compressed_data = ram_read_data[10:6]; + wire op_write_compressed_auto_increment_y = ram_read_data[11]; + + // JUMP + + wire [10:0] op_jump_target = ram_read_data[10:0]; + + // --- FSM --- + + localparam STATE_OP_DECODE = 0; + localparam STATE_DATA_FETCH = 1; + localparam STATE_RASTER_WAITING = 2; + localparam STATE_OP_PREFETCH = 3; + + reg [1:0] state; + + always @(posedge clk) begin + if (!operating) begin + pc <= PC_RESET; + + reg_write_en <= 0; + + target_x <= 0; + target_y <= 0; + state <= STATE_OP_PREFETCH; + + ram_read_deferring <= 0; + end else begin + reg_write_en <= 0; + + if (state == STATE_OP_DECODE) begin + case (op) + OP_SET_TARGET: begin + if (op_target_select) begin + target_y <= op_target_value; + end else begin + target_x <= op_target_value; + end + + state <= (op_target_wait ? STATE_RASTER_WAITING : STATE_OP_DECODE); + + if (op_target_wait) begin + ram_read_deferring <= 1; + end + + pc <= pc + 1; + end + OP_WRITE_REG: begin + op_write_target_reg_r <= op_write_target_reg; + op_write_batch_count_r <= op_write_batch_count; + op_write_auto_wait_r <= op_write_auto_wait; + op_write_increment_mode_r <= op_write_increment_mode; + + op_write_counter <= 0; + + state <= STATE_DATA_FETCH; + pc <= pc + 1; + end + OP_JUMP: begin + pc <= op_jump_target; + state <= STATE_OP_PREFETCH; + end + OP_WRITE_COMPRESSED: begin + reg_write_address <= op_write_compressed_reg; + reg_write_data <= op_write_compressed_data; + reg_write_en <= 1; + + if (op_write_compressed_auto_increment_y) begin + target_y <= raster_y + 1; + end + + pc <= pc + 1; + end + endcase + + op_current <= op; + end else if (state == STATE_DATA_FETCH) begin + reg_write_data <= ram_read_data; + reg_write_address <= op_write_target_reg_r + op_write_reg_offset; + reg_write_en <= 1; + + op_write_counter <= op_write_counter + 1; + + if (op_write_batch_complete) begin + if (op_write_batch_count_r == 0) begin + state <= STATE_OP_DECODE; + end else begin + op_write_batch_count_r <= op_write_batch_count_r - 1; + + if (op_write_auto_wait_r) begin + target_y <= raster_y + 1; + ram_read_deferring <= 1; + state <= STATE_RASTER_WAITING; + end + end + end + + pc <= pc + 1; + end else if (state == STATE_RASTER_WAITING) begin + if (target_hit) begin + if (op_current == OP_WRITE_REG && op_write_auto_wait_r) begin + state <= STATE_DATA_FETCH; + end else begin + state <= STATE_OP_DECODE; + end + + ram_read_deferring <= 0; + end + end else if (state == STATE_OP_PREFETCH) begin + state <= STATE_OP_DECODE; + end + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_host_interface.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_host_interface.v new file mode 100644 index 0000000000000000000000000000000000000000..59a5ca269e5fa62b1a23ed4bd197b767a3a7a4f0 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_host_interface.v @@ -0,0 +1,96 @@ +// vdp_host_interface.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" + +module vdp_host_interface( + input clk, + input reset, + + input [5:0] host_address, + output reg [4:0] register_write_address, + input vram_write_pending, + + // Writes.. + + output reg register_write_en, + output reg [15:0] register_write_data, + output reg ready, + + // ..from CPU + + input host_write_en, + input [15:0] host_write_data, + + // ..from copper + + input cop_write_en, + input [4:0] cop_write_address, + input [15:0] cop_write_data, + + // Reads (only from CPU) + + input host_read_en, + output reg [4:0] read_address +); + reg host_write_en_r; + reg host_write_pending; + reg host_read_en_r; + + wire host_write_en_gated = host_write_en && !host_write_pending && !vram_write_pending; + + always @(posedge clk) begin + host_write_en_r <= host_write_en; + host_read_en_r <= host_read_en; + end + + always @(posedge clk) begin + // Reads use the registered input as a 1 cycle delay is required before output valid + // Writes only need to be delayed if a subsequent write risks clobbering VRAM + ready <= (host_write_en_gated || host_read_en_r); + end + + always @(posedge clk) begin + if (reset) begin + register_write_en <= 0; + end else begin + register_write_en <= cop_write_en || host_write_en_gated; + end + end + + always @(posedge clk) begin + if (reset) begin + host_write_pending <= 0; + end else if (host_write_en_gated) begin + host_write_pending <= 1; + end else if (!host_write_en) begin + host_write_pending <= 0; + end + end + + always @(posedge clk) begin + if (host_write_en) begin + register_write_address <= host_address; + register_write_data <= host_write_data; + end else begin + register_write_address <= cop_write_address; + register_write_data <= cop_write_data; + end + + // CPU is always free to read + read_address <= host_address; + end + + always @(posedge clk) begin + if (!reset && cop_write_en && host_write_en) begin + // Must be a software or hardware bug so flag it accordingly + `stop($display("CPU / VDP copper write conflict. CPU: %x, COP: %x", host_address, cop_write_address);) + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_layer_priority_select.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_layer_priority_select.v new file mode 100644 index 0000000000000000000000000000000000000000..596cdba38065eda90dbc8a937fce57ec1473561b --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_layer_priority_select.v @@ -0,0 +1,102 @@ +// vdp_layer_priority_select.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "layer_encoding.vh" + +module vdp_layer_priority_select( + input clk, + + input [4:0] layer_mask, + + input [7:0] scroll0_pixel, + input [7:0] scroll1_pixel, + input [7:0] scroll2_pixel, + input [7:0] scroll3_pixel, + + input [1:0] sprite_priority, + input [7:0] sprite_pixel, + + output reg [4:0] prioritized_layer, + output reg [7:0] prioritized_pixel, + output reg [2:0] resolved_priority +); + wire sprite_opaque_r = layer_mask_r[`LAYER_SPRITES]; + + // 1a: Register inputs for output (2.) + + reg [7:0] scroll_pixel_r [0:3]; + reg [7:0] sprite_pixel_r; + reg [1:0] sprite_priority_r; + reg [4:0] layer_mask_r; + + always @(posedge clk) begin + scroll_pixel_r[0] <= scroll0_pixel; + scroll_pixel_r[1] <= scroll1_pixel; + scroll_pixel_r[2] <= scroll2_pixel; + scroll_pixel_r[3] <= scroll3_pixel; + + sprite_pixel_r <= sprite_pixel; + sprite_priority_r <= sprite_priority; + + layer_mask_r <= layer_mask; + end + + // 1b: Determine priority of layers / sprites + + wire [2:0] sprite_priority_score = {sprite_priority_r, 1'b1}; + wire [2:0] layer_priority_score = {layer_encoded_priority, 1'b0}; + reg [1:0] layer_encoded_priority; + reg [3:0] layer_prioritized_ohe; + + always @(posedge clk) begin + // if (layer_mask[3]) begin... + layer_encoded_priority <= 0; + layer_prioritized_ohe <= `LAYER_SCROLL3_OHE; + + if (layer_mask[2]) begin + layer_encoded_priority <= 1; + layer_prioritized_ohe <= `LAYER_SCROLL2_OHE; + end + if (layer_mask[1]) begin + layer_encoded_priority <= 2; + layer_prioritized_ohe <= `LAYER_SCROLL1_OHE; + end + if (layer_mask[0]) begin + layer_encoded_priority <= 3; + layer_prioritized_ohe <= `LAYER_SCROLL0_OHE; + end + end + + // 2a: Use above priorities to select the topmost pixel + + always @* begin + if (sprite_opaque_r && (sprite_priority_score > layer_priority_score)) begin + prioritized_layer = `LAYER_SPRITES_OHE; + resolved_priority = sprite_priority_score; + end else if (|layer_mask_r[3:0]) begin + prioritized_layer = layer_prioritized_ohe; + resolved_priority = layer_priority_score; + end else begin + prioritized_layer = 0; + resolved_priority = 0; + end + end + + // 2b: Output pixel according to topmost pixel using the outputs from above + + always @* begin + // 0 at the end of this ternary is required to default to color 0 when no others are on screen + prioritized_pixel = + prioritized_layer[0] ? scroll_pixel_r[0] : + prioritized_layer[1] ? scroll_pixel_r[1] : + prioritized_layer[2] ? scroll_pixel_r[2] : + prioritized_layer[3] ? scroll_pixel_r[3] : + sprite_opaque_r ? sprite_pixel_r : 0; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_map_address_generator.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_map_address_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..d1e3d574fdf46421a66efe55848cf165eb4dca56 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_map_address_generator.v @@ -0,0 +1,85 @@ +// vdp_map_address_generator.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_map_address_generator #( + parameter [0:0] REGISTERED_INPUTS = 0 +) ( + input clk, + + input [9:0] scroll_y, + input [6:0] scroll_x_coarse, + + input [9:0] raster_y, + input [6:0] raster_x_coarse, + + input [14:0] map_base_address, + input [7:0] stride, + + output [14:0] map_address_16b +); + reg [9:0] scroll_y_r; + reg [6:0] scroll_x_coarse_r; + reg [9:0] raster_y_r; + reg [6:0] raster_x_coarse_r; + reg [14:0] map_base_address_r; + reg [7:0] stride_r; + + generate + if (REGISTERED_INPUTS) begin + always @(posedge clk) begin + scroll_y_r <= scroll_y; + scroll_x_coarse_r <= scroll_x_coarse; + raster_y_r <= raster_y; + raster_x_coarse_r <= raster_x_coarse; + map_base_address_r <= map_base_address; + stride_r <= stride; + end + end else begin + always @* begin + scroll_y_r = scroll_y; + scroll_x_coarse_r = scroll_x_coarse; + raster_y_r = raster_y; + raster_x_coarse_r = raster_x_coarse; + map_base_address_r = map_base_address; + stride_r = stride; + end + end + endgenerate + + wire [6:0] column = scroll_x_coarse_r + raster_x_coarse_r; + wire [5:0] row = (scroll_y_r + raster_y_r) >> 3; + + // cheap, only requires +1 LUT + wire map_page_select = (stride_r & 8'h80) && column[6]; + + assign map_address_16b = {map_page_select, row, column[5:0]} + map_base_address_r; + +endmodule + + // Most of these are probably the "+ map_base_address" which gets optimised when 64 or 128 is used + // Number of cells: 54 + // SB_CARRY 27 + // SB_LUT4 27 + + // this is the nicer alternative but expensive + // not as nice of an API though + + // always @* begin + // if (stride & 8'h80) begin + // //breaks, as expected + // map_address = {row, column} + map_base_address; + // end else begin + // // works, as before + // map_address = {row, column[5:0]} + map_base_address; + // end + // end + + // Number of cells: 90 + // SB_CARRY 40 + // SB_LUT4 50 + diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_priority_compute.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_priority_compute.v new file mode 100644 index 0000000000000000000000000000000000000000..67e7751851054692c6a69a314bd9e7ece57806c1 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_priority_compute.v @@ -0,0 +1,98 @@ +// vdp_priority_compute.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_priority_compute( + input clk, + + input [7:0] scroll0_pixel, + input scroll0_is_8bpp, + + input [7:0] scroll1_pixel, + input [7:0] scroll2_pixel, + input [7:0] scroll3_pixel, + + input [7:0] sprite_pixel, + input [1:0] sprite_priority, + + input [4:0] layer_enable, + input [4:0] layer_mask, + + output reg [7:0] prioritized_pixel, + output reg [4:0] prioritized_layer, + + output reg [7:0] prioritized_masked_pixel, + output reg [4:0] prioritized_masked_layer +); + + wire [4:0] layer_opacity = { + |sprite_pixel[3:0], + |scroll3_pixel[3:0], + |scroll2_pixel[3:0], + |scroll1_pixel[3:0], + |(scroll0_is_8bpp ? scroll0_pixel[7:0] : scroll0_pixel[3:0]) + }; + + wire [4:0] primary_layers = layer_enable & layer_opacity & layer_mask; + wire [4:0] masked_layers = layer_enable & layer_opacity & ~layer_mask; + + wire [4:0] prioritized_layer_nx; + wire [7:0] prioritized_pixel_nx; + + wire [4:0] masked_layer_nx; + wire [7:0] masked_pixel_nx; + + wire [2:0] primary_resolved_priority; + wire [2:0] masked_resolved_priority; + + vdp_layer_priority_select primary_priority_select( + .clk(clk), + + .layer_mask(primary_layers), + .sprite_priority(sprite_priority), + + .scroll0_pixel(scroll0_pixel), + .scroll1_pixel(scroll1_pixel), + .scroll2_pixel(scroll2_pixel), + .scroll3_pixel(scroll3_pixel), + .sprite_pixel(sprite_pixel), + + .prioritized_layer(prioritized_layer_nx), + .prioritized_pixel(prioritized_pixel_nx), + .resolved_priority(primary_resolved_priority) + ); + + vdp_layer_priority_select masked_priority_select( + .clk(clk), + + .layer_mask(masked_layers), + .sprite_priority(sprite_priority), + + .scroll0_pixel(scroll0_pixel), + .scroll1_pixel(scroll1_pixel), + .scroll2_pixel(scroll2_pixel), + .scroll3_pixel(scroll3_pixel), + .sprite_pixel(sprite_pixel), + + .prioritized_layer(masked_layer_nx), + .prioritized_pixel(masked_pixel_nx), + .resolved_priority(masked_resolved_priority) + ); + + // if primary layer beats masked layer, force masked layer to 0 + // this lets a higher priority alpha-over layer win over an otherwise prioritised layer + wire force_masked_layer_off = primary_resolved_priority > masked_resolved_priority; + + always @(posedge clk) begin + prioritized_layer <= prioritized_layer_nx; + prioritized_pixel <= prioritized_pixel_nx; + + prioritized_masked_layer <= force_masked_layer_off ? 0 : masked_layer_nx; + prioritized_masked_pixel <= masked_pixel_nx; + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_scroll_pixel_generator.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_scroll_pixel_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..7f34466b19ba5cb4dc5fe831984453880c3cd600 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_scroll_pixel_generator.v @@ -0,0 +1,65 @@ +// vdp_scroll_pixel_generator.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_scroll_pixel_generator #( + parameter STAGE_PIXEL_ROW = 1 +) ( + input clk, + input [2:0] scroll_x_granular, + input [2:0] raster_x_granular, + input [31:0] pixel_row, + input [3:0] palette_number, + + input tile_row_load_enable, + input meta_load_enable, + input shifter_preload_load_enable, + + output reg [7:0] pixel +); + + reg [31:0] pixel_row_preloaded; + reg [31:0] output_pixel_row_t; + reg [31:0] output_pixel_row; + + reg [3:0] output_palette_number; + reg [3:0] palette_number_preloaded; + reg [3:0] output_palette_number_t; + + wire [7:0] pixel_nx = {output_palette_number, output_pixel_row[31:28]}; + + always @(posedge clk) begin + pixel <= pixel_nx; + end + + always @(posedge clk) begin + if (STAGE_PIXEL_ROW && tile_row_load_enable) begin + pixel_row_preloaded <= pixel_row; + end + + if (meta_load_enable) begin + palette_number_preloaded <= palette_number; + end + end + + always @(posedge clk) begin + if (shifter_preload_load_enable) begin + output_pixel_row_t <= STAGE_PIXEL_ROW ? pixel_row_preloaded : pixel_row; + output_palette_number_t <= palette_number_preloaded; + end + end + + always @(posedge clk) begin + if (~(scroll_x_granular) == raster_x_granular) begin + output_pixel_row <= output_pixel_row_t; + output_palette_number <= output_palette_number_t; + end else begin + output_pixel_row <= {output_pixel_row[27:0], 4'b0000}; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_core.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_core.v new file mode 100644 index 0000000000000000000000000000000000000000..b6a12f94f2e63af498146011ab5ae0d42834ef41 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_core.v @@ -0,0 +1,322 @@ +// vdp_sprite_core.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_sprite_core #( + parameter [0:0] REGSTER_RENDER_X = 0 +) ( + input clk, + input start_new_line, + + input [9:0] render_x, + input [8:0] render_y, + + input [7:0] meta_address, + input [15:0] meta_write_data, + input [2:0] meta_block_select, + input meta_we, + + input [13:0] vram_base_address, + output vram_read_data_needs_x_flip, + output [13:0] vram_read_address, + input [31:0] vram_read_data, + input vram_data_valid, + + output [7:0] pixel, + output [1:0] pixel_priority +); + reg start_new_line_r; + + always @(posedge clk) begin + start_new_line_r <= start_new_line; + end + + // yosys hangs on the "make count" target with x_r removed: + // > 28.39. Executing DFF2DFFE pass (transform $dff to $dffe where applicable). + // ... + // need to investigate this, leaving this commented out until then + // It would save on LCs though + // SPRITE_X_INITIAL needs to have an additional -1 if this change is made + + reg [9:0] render_x_r; + + generate + if (REGSTER_RENDER_X) begin + always @(posedge clk) begin + render_x_r <= render_x; + end + end else begin + always @* begin + render_x_r = render_x; + end + end + endgenerate + + // --- Metadata block writing --- + + assign x_block_we = meta_block_select[0] && meta_we; + assign y_block_we = meta_block_select[1] && meta_we; + assign g_block_we = meta_block_select[2] && meta_we; + + // --- y_block --- + + // ----whYy yyyyyyyy + // y: sprite y (9 bits, could be extended to 10bits on another platform) + // h: height select (8 or 16) + // w: width select (8 or 16) + // Y: Y flip - the advantage of doing it here is that it frees up bits in other attribute blocks + // -: unused + + reg [15:0] y_block [0:255]; + + reg [15:0] y_block_data_out; + wire [7:0] y_block_read_address; + + wire y_block_we; + + always @(posedge clk) begin + if (y_block_we) begin + y_block[meta_address] <= meta_write_data; + end + + y_block_data_out <= y_block[y_block_read_address]; + end + + // --- g_block --- + + // ppppPPgg gggggggg + // g: character # + // p: palette + // P: priority + + reg [15:0] g_block [0:255]; + + reg [15:0] g_block_data_out; + wire [7:0] g_block_read_address; + + wire g_block_we; + + always @(posedge clk) begin + if (g_block_we) begin + g_block[meta_address] <= meta_write_data; + end + + g_block_data_out <= g_block[g_block_read_address]; + end + + // --- x_block --- + + // -----Xxx xxxxxxxx + // x: x position + // X: flip + // -: unused + + reg [15:0] x_block [0:255]; + + reg [15:0] x_block_data_out; + wire [7:0] x_block_read_address; + + wire x_block_we; + + always @(posedge clk) begin + if (x_block_we) begin + x_block[meta_address] <= meta_write_data; + end + + x_block_data_out <= x_block[x_block_read_address]; + end + + // --- Hit list (private) --- + + // layout: + // T--wcccc iiiiiiii + // i: sprite ID + // c: collision Y within sprite (0-15, 16px sprite tall is the max) + // w: width select (8 or 16) + // T: terminator bit + // -: unused + + wire hit_list_select = render_y[0]; + + wire hit_list_ended = hit_list_render_read_data[15]; + + wire [15:0] hit_list_render_read_data = hit_list_select ? + hit_list_read_data_1 : hit_list_read_data_0; + + wire [7:0] hit_list_read_address; + + wire [7:0] hit_list_write_address; + wire hit_list_write_en; + wire [15:0] hit_list_data_in; + + wire [15:0] hit_list_read_data_0; + wire [15:0] hit_list_read_data_1; + + dpram #( + .ADDRESS_WIDTH(8), + .DATA_WIDTH(16) + ) hit_list [1:0] ( + .clk(clk), + + .write_en({2{hit_list_write_en}} & {~hit_list_select, hit_list_select}), + .write_address(hit_list_write_address), + .write_data(hit_list_data_in), + + .read_address(hit_list_read_address), + .read_data({hit_list_read_data_1, hit_list_read_data_0}) + ); + + // --- Line buffers --- + + // Selected buffer toggles every line + wire line_buffer_select = !render_y[0]; + + wire [9:0] line_buffer_write_address; + wire [9:0] line_buffer_write_data; + wire line_buffer_write_en; + + wire [9:0] line_buffer_clear_write_address; + wire line_buffer_clear_en; + + wire [19:0] line_buffer_data_out; + wire [9:0] line_buffer_data_out_0 = line_buffer_data_out[9:0]; + wire [9:0] line_buffer_data_out_1 = line_buffer_data_out[19:10]; + + genvar i; + generate + for (i = 0; i < 2; i = i + 1) begin : line_buffer_gen + wire select = line_buffer_select ^ i; + + wire [9:0] write_address = select ? line_buffer_write_address : line_buffer_clear_write_address; + wire [9:0] write_data = select ? line_buffer_write_data : line_buffer_clear_data_in; + wire write_en = select ? line_buffer_write_en : line_buffer_clear_en; + + wire [9:0] read_data; + assign line_buffer_data_out[i * 10+:10] = read_data; + + dpram #( + .ADDRESS_WIDTH(10), + .DATA_WIDTH(10) + ) line_buffer ( + .clk(clk), + + .write_en(write_en), + .write_address(write_address), + .write_data(write_data), + + .read_address(line_buffer_display_read_address), + .read_data(read_data) + ); + end + endgenerate + + // Clearing: + + reg [9:0] line_buffer_previous_read_address; + assign line_buffer_clear_write_address = line_buffer_previous_read_address; + wire [9:0] line_buffer_clear_data_in = 10'b0; + + assign line_buffer_clear_en = 1; + + always @(posedge clk) begin + line_buffer_previous_read_address <= line_buffer_display_read_address; + end + + // Reading: + + wire [9:0] line_buffer_display_read_address; + wire [9:0] line_buffer_display_data; + + // data to read from active buffer + assign line_buffer_display_data = line_buffer_select ? + line_buffer_data_out_1 : line_buffer_data_out_0; + + assign line_buffer_display_read_address = render_x_r; + + // These are registered in the sprite_line_buffer module + + // 8bit palette index + assign pixel = line_buffer_display_data[7:0]; + // 2bit priority + assign pixel_priority = line_buffer_display_data[9:8]; + + // there is no competing access from blitter / prefetch + assign hit_list_read_address = hit_list_blitter_read_address; + + // --- Sprite raster-collision testing --- + + // attribute extraction from y_block data + + wire [8:0] sprite_y_read = y_block_data_out[8:0]; + wire [4:0] sprite_selected_height = y_block_data_out[10] ? 16 : 8; + wire sprite_flip_y = y_block_data_out[9]; + wire sprite_width_select = y_block_data_out[11]; + + assign hit_list_data_in[14:13] = 0; + + vdp_sprite_raster_collision collision( + .clk(clk), + .restart(start_new_line_r), + + .render_y(render_y), + + // reading + .sprite_y(sprite_y_read), + .sprite_test_id(y_block_read_address), + .sprite_height(sprite_selected_height), + .flip_y(sprite_flip_y), + .width_select_in(sprite_width_select), + + // writing + .sprite_y_intersect(hit_list_data_in[11:8]), + .sprite_id(hit_list_data_in[7:0]), + .hit_list_index(hit_list_write_address), + .finished(hit_list_data_in[15]), + .width_select_out(hit_list_data_in[12]), + .hit_list_write_en(hit_list_write_en) + ); + + // --- Sprite render --- + + wire [7:0] hit_list_blitter_read_address; + wire [7:0] blitter_sprite_meta_read_address; + + // these happen to be the same read address, at the same time + assign g_block_read_address = blitter_sprite_meta_read_address; + assign x_block_read_address = blitter_sprite_meta_read_address; + + vdp_sprite_render render( + .clk(clk), + .restart(start_new_line_r), + + .vram_base_address(vram_base_address), + .vram_read_address(vram_read_address), + .vram_read_data_needs_x_flip(vram_read_data_needs_x_flip), + .vram_read_data(vram_read_data), + .vram_data_valid(vram_data_valid), + + .sprite_meta_address(blitter_sprite_meta_read_address), + + .character(g_block_data_out[9:0]), + .palette(g_block_data_out[15:12]), + .pixel_priority(g_block_data_out[11:10]), + + .target_x(x_block_data_out[9:0]), + .flip_x(x_block_data_out[10]), + + .line_buffer_write_address(line_buffer_write_address), + .line_buffer_write_data(line_buffer_write_data), + .line_buffer_write_en(line_buffer_write_en), + + .hit_list_read_address(hit_list_blitter_read_address), + .sprite_id(hit_list_render_read_data[7:0]), + .line_offset(hit_list_render_read_data[11:8]), + .width_select(hit_list_render_read_data[12]), + .hit_list_ended(hit_list_ended) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_raster_collision.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_raster_collision.v new file mode 100644 index 0000000000000000000000000000000000000000..c10d1797839ac731d591f28416b16ee6a6883ebc --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_raster_collision.v @@ -0,0 +1,285 @@ +// vdp_sprite_raster_collision.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_sprite_raster_collision #( +`ifdef FORMAL + // This FORMAL condition can applied in a wrapper testbench instead of doing it here + // the assertions below can then be lifted out of this source since they just assert on outputs anyway + parameter SPRITES_TOTAL = 16 +`else + parameter SPRITES_TOTAL = 255 +`endif +) ( + input clk, + input restart, + + input [8:0] render_y, + + // sprite attribute data + input [8:0] sprite_y, + input [4:0] sprite_height, + input width_select_in, + input flip_y, + + // sprite to read attributes for + output reg [7:0] sprite_test_id, + + // hit list outputs + output reg [8:0] hit_list_index, + output reg [7:0] sprite_id, + output reg [3:0] sprite_y_intersect, + output reg width_select_out, + + output reg hit_list_write_en, + + output reg finished +); + localparam READ_LATENCY = 3; + + // changes per line + reg [8:0] render_y_r; + + // changes per sprite + reg [8:0] sprite_y_r; + reg [4:0] sprite_height_r; + + wire ready; + + delay_ffr #(.DELAY(3)) ready_dm ( + .clk(clk), + .reset(restart), + .in(1), + .out(ready) + ); + + wire output_valid; + + delay_ffr #(.DELAY(1)) output_valid_dm ( + .clk(clk), + .reset(restart), + .in(ready), + .out(output_valid) + ); + + wire flip_y_d, width_select_d; + + delay_ffr #(.DELAY(2), .WIDTH(2)) attributes_dm ( + .clk(clk), + .reset(restart), + .in({flip_y, width_select_in}), + .out({flip_y_d, width_select_d}) + ); + + wire [4:0] sprite_height_d; + + delay_ffr #(.DELAY(2), .WIDTH(5)) sprite_height_dm ( + .clk(clk), + .reset(restart), + .in(sprite_height), + .out(sprite_height_d) + ); + + reg finished_t; + + reg [8:0] sprite_y_intersect_t; + reg has_collision, has_collision_t; + + wire [8:0] sprite_y_intersect_nx = render_y_r - sprite_y_r; + wire has_collision_nx = sprite_y_intersect_nx < sprite_height_r; + wire hit_list_needs_increment = ready && (has_collision_t || will_finish); + + wire finished_nx = finished_t || all_sprites_processed; + wire will_finish = !finished_t && finished_nx; + + wire all_sprites_processed = (sprite_id == (SPRITES_TOTAL - READ_LATENCY + 1)) && output_valid; + wire hit_list_full = hit_list_index == 9'h100; + + wire collision_needs_writing = (ready && has_collision_t && !finished_t); + wire hit_list_terminator_needs_writing = (!hit_list_full && finished_t); + wire hit_list_write_en_nx = collision_needs_writing || hit_list_terminator_needs_writing; + + always @(posedge clk) begin + if (restart) begin + finished <= 0; + finished_t <= 0; + hit_list_write_en <= 0; + + // probably not needed, account for any latency and remove + // this is already registered in parent vdp module + render_y_r <= render_y; + + // -1 for preincrement index + hit_list_index <= -1; + + sprite_test_id <= 0; + sprite_id <= -(READ_LATENCY) - 1; + end else if (!finished) begin + hit_list_index <= hit_list_needs_increment ? hit_list_index + 1 : hit_list_index; + sprite_test_id <= sprite_test_id + 1; + sprite_id <= sprite_id + 1; + + hit_list_write_en <= hit_list_write_en_nx; + + finished_t <= finished_nx; + finished <= finished_t; + end else begin + hit_list_write_en <= 0; + end + end + + always @(posedge clk) begin + // register inputs from y_block + sprite_y_r <= sprite_y; + sprite_height_r <= sprite_height; + + // register comparator result from previously read y_block + sprite_y_intersect_t <= sprite_y_intersect_nx; + has_collision_t <= has_collision_nx; + + // move the above registered result to the output for this module + sprite_y_intersect <= flip_y_d ? sprite_height_d - sprite_y_intersect_t - 1 : sprite_y_intersect_t; + has_collision <= has_collision_t; + width_select_out <= width_select_d; + end + +`ifdef FORMAL + + reg past_valid = 0; + integer valid_count = 0; + + initial begin + restrict(restart); + end + + always @(posedge clk) begin + if (past_valid) begin + assume(!restart); + end + end + + always @(posedge clk) begin + if (past_valid) begin + if ($past(restart)) begin + assert(!output_valid); + end + end + + past_valid <= 1; + + if (!restart) begin + valid_count <= valid_count + 1; + end else begin + valid_count <= 0; + end + end + + // expectations when evaluation just started + + always @(posedge clk) begin + if (past_valid) begin + if ($fell(restart)) begin + assert(sprite_test_id == 8'h00); + assert(!finished); + assert(!output_valid); + assert(!hit_list_write_en); + end + end + end + + // expectations when evaluation just finished + + always @(posedge clk) begin + if (past_valid) begin + if ($rose(finished)) begin + assert(output_valid); + assert(hit_list_write_en); + end + end + end + + always @(posedge clk) begin + if (past_valid) begin + if ($rose(output_valid) && has_collision) begin + if (has_collision) begin + // it's PRE increment pointer so it's only 00 on the first collision + assert(hit_list_index == 8'h00); + assert(hit_list_write_en); + end else begin + // and it should be ff (or -1) if there was no collision initially + assert(hit_list_index == 8'hff); + assert(!hit_list_write_en); + end + end + end + end + + // temporary variables for use with the below assertions + + integer sprite_pos, raster_pos; + integer sprite_top; + integer flipped_y_intersect; + + localparam PIPE_DELAY = 3; + + // the pipeline adds latency of PIPE_DELAY cycles so these are added for convenience + + reg [8:0] input_sprite_y; + reg [8:0] input_render_y; + reg [7:0] input_sprite_height; + reg input_flip_y; + reg input_width_select_in; + + always @(posedge clk) begin + input_sprite_y = $past(sprite_y, PIPE_DELAY - 1); + input_render_y = $past(render_y, PIPE_DELAY - 1); + input_sprite_height = $past(sprite_height, PIPE_DELAY - 1); + input_flip_y = $past(flip_y, PIPE_DELAY - 1); + input_width_select_in = $past(width_select_in, PIPE_DELAY - 1); + end + + always @(posedge clk) begin + if (valid_count > (PIPE_DELAY + 1)) begin + sprite_top = input_sprite_y; + sprite_pos = input_sprite_y + input_sprite_height; + raster_pos = input_render_y; + flipped_y_intersect = (sprite_y_intersect ^ {4{input_flip_y}}) % input_sprite_height; + + // a) cases where there IS collision + if (!finished && output_valid && has_collision) begin + // intersect should in be in range (0..= sprite.top + // assert($past(render_y, PIPE_DELAY) >= $past(sprite_y, PIPE_DELAY)); + + // sprite.bottom > raster + assert(sprite_pos > raster_pos); + + assert(width_select_out == input_width_select_in); + + assert(hit_list_write_en); + end + + // b) cases where there is NO collision: + if (!finished && output_valid && !has_collision) begin + assert(raster_pos < sprite_top + || raster_pos >= sprite_pos); + + assert(!hit_list_write_en); + end + end + + // render_y is not supposed to change in the middle of a sprite list evaluation + if (!restart) begin + assume($stable(render_y)); + end + end + +`endif + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_render.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_render.v new file mode 100644 index 0000000000000000000000000000000000000000..ddaf7872fe6e5a6c64867f791f7aa980a8026b59 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_sprite_render.v @@ -0,0 +1,307 @@ +// vdp_sprite_render.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" + +module vdp_sprite_render( + input clk, + input restart, + + // line buffer writing + output reg [9:0] line_buffer_write_address, + output reg [9:0] line_buffer_write_data, + output reg line_buffer_write_en, + + // prefetch reading + input [13:0] vram_base_address, + output vram_read_data_needs_x_flip, + output reg [13:0] vram_read_address, + input [31:0] vram_read_data, + input vram_data_valid, + + // shared between g_block / x_block attributes + output reg [7:0] sprite_meta_address, + + // g_block reading + input [9:0] character, + input [3:0] palette, + input [1:0] pixel_priority, + + // x_block reading + input [9:0] target_x, + input flip_x, + + // hit list reading + output reg [8:0] hit_list_read_address, + input [7:0] sprite_id, + input [3:0] line_offset, + input width_select, + input hit_list_ended +); + // --- Hit list reading --- + + reg [7:0] sprite_id_r; + reg [3:0] line_offset_r; + reg width_select_r; + reg hit_list_ended_r; + + reg hit_list_data_valid; + reg hit_list_input_valid; + + wire hit_list_ready = hit_list_input_valid && hit_list_dependency_ready; + wire hit_list_dependency_ready = x_block_ready; + wire hit_list_end_reached = x_block_finished; + + always @(posedge clk) begin + if (hit_list_ready) begin + sprite_id_r <= sprite_id; + line_offset_r <= line_offset; + width_select_r <= width_select; + hit_list_ended_r <= hit_list_ended | hit_list_read_address[8]; + end + end + + always @(posedge clk) begin + if (restart) begin + hit_list_read_address <= 0; + hit_list_data_valid <= 0; + hit_list_input_valid <= 0; + end else begin + hit_list_data_valid <= 0; + hit_list_input_valid <= 1; + + if (hit_list_ready) begin + hit_list_read_address <= hit_list_read_address + 1; + + hit_list_data_valid <= 1; + hit_list_input_valid <= 0; + end + end + end + + // --- Sprite x_block / g_block reading --- + + reg [1:0] x_block_loaded; + reg x_block_data_valid; + + reg x_block_ready; + reg x_block_finished; + + wire x_block_dependency_ready = vram_fetcher_ready; + + // Inputs from hitlist: + + reg [3:0] xb_line_offset; + reg xb_width_select_r; + + // Outputs to VRAM fetcher: + + // x_block + reg [9:0] target_x_r; + reg flip_x_r; + assign vram_read_data_needs_x_flip = flip_x_r; + + // y_block + reg width_r; + + // g_block + reg [9:0] character_r; + reg [3:0] palette_r; + reg [1:0] priority_r; + + always @(posedge clk) begin + if (restart) begin + x_block_ready <= 1; + x_block_loaded <= 0; + x_block_data_valid <= 0; + x_block_finished <= 0; + end else if (hit_list_data_valid && hit_list_ended_r) begin + // finished for this line + x_block_data_valid <= 0; + x_block_ready <= 0; + + x_block_finished <= 1; + end else if (!x_block_finished && !x_block_ready) begin + if (x_block_loaded && x_block_dependency_ready) begin + // x_block + target_x_r <= target_x; + flip_x_r <= flip_x; + + // y_block + width_r <= xb_width_select_r; + + // g_block + character_r <= character; + palette_r <= palette; + priority_r <= pixel_priority; + + x_block_data_valid <= 1; + x_block_ready <= 1; + end + + x_block_loaded <= 1; + end else if (!x_block_finished && x_block_ready && hit_list_data_valid) begin + sprite_meta_address <= sprite_id_r; + + // pipelined for the vram fetcher + xb_line_offset <= line_offset_r; + xb_width_select_r <= width_select_r; + + x_block_loaded <= 0; + x_block_ready <= 0; + x_block_data_valid <= 0; + end + end + + // --- VRAM sprite row fetching --- + + localparam VRAM_READ_LATENCY = 3; + localparam ROW_OFFSET = 128; + + reg fetching_second_row; + reg sprite_row_is_valid; + reg char_x; + + reg [1:0] vram_load_counter; + reg vram_loading; + + // line needs to be offset *to the next row* + wire [13:0] char_offset = xb_line_offset[2:0] + xb_line_offset[3] * ROW_OFFSET; + wire [13:0] sprite_row_vram_address = vram_base_address + character_r * 8 + char_offset; + + // verilator lint_off UNUSED + reg sprite_finished; + // verilator lint_on UNUSED + + reg vram_fetcher_ready; + + // pipelined attribtues from earlier fetch + reg [3:0] vf_palette; + reg [1:0] vf_priority; + reg [9:0] vf_target_x; + reg vf_flip; + + reg [31:0] vf_row_prefetched; + + always @(posedge clk) begin + if (restart) begin + vram_loading <= 0; + sprite_finished <= 0; + + sprite_row_is_valid <= 0; + + vram_fetcher_ready <= 1; + + `debug(vram_load_counter <= 0;) + `debug(vram_read_address <= 0;) + `debug(fetching_second_row <= 0;) + end else begin + sprite_finished <= 0; + sprite_row_is_valid <= 0; + + if (vram_loading) begin + if (vram_load_counter != VRAM_READ_LATENCY) begin + vram_load_counter <= vram_load_counter + 1; + end else if (vram_data_valid) begin + // this can be set before the ready signal since blitter makes its own copy + // on the very first step + vf_row_prefetched <= vram_read_data; + + vf_palette <= palette_r; + vf_priority <= priority_r; + vf_flip <= flip_x_r; + + vf_target_x <= target_x_r; + + sprite_row_is_valid <= 1; + + // 8pixel / 16pixel width handling + + if (width_r && !fetching_second_row) begin + // setup to read next 8px row... + vram_read_address <= vram_read_address + 8; + vram_load_counter <= 0; + + // ...and render first 8px in mean time + char_x <= 0; + fetching_second_row <= 1; + end else begin + // render second half of 16 pixel sprite if needed + char_x <= fetching_second_row; + + sprite_finished <= 1; + vram_loading <= 0; + + vram_fetcher_ready <= 1; + end + end + end else if (x_block_data_valid) begin + vram_read_address <= sprite_row_vram_address; + + vram_load_counter <= 0; + fetching_second_row <= 0; + vram_loading <= 1; + vram_fetcher_ready <= 0; + + sprite_row_is_valid <= 0; + end + end + end + + // --- Blitter --- + + wire blitter_input_valid = sprite_row_is_valid; + wire [9:0] blitter_x_start = vf_target_x + (char_x ^ vf_flip) * 8; + wire pixel_is_opaque = (blitter_output_pixel != 0); + + reg [31:0] blitter_row_shifter; + reg [3:0] blitter_palette; + reg [1:0] blitter_priority; + + wire blitter_drawing_first_pixel = blitter_input_valid; + wire [31:0] blitter_output_source = blitter_drawing_first_pixel ? vf_row_prefetched : blitter_row_shifter; + + reg [3:0] blitter_pixel_counter; + wire blitter_all_pixels_counted = blitter_pixel_counter[3]; + + wire [3:0] blitter_output_pixel = blitter_output_source[31:28]; + wire [1:0] blitter_output_priority = (blitter_drawing_first_pixel ? vf_priority : blitter_priority); + wire [3:0] blitter_output_palette = (blitter_drawing_first_pixel ? vf_palette : blitter_palette); + + wire [31:0] blitter_next_shift = {blitter_output_source[27:0], 4'b0000}; + + wire blitter_drawing = blitter_input_valid || !blitter_all_pixels_counted; + wire line_buffer_write_en_nx = pixel_is_opaque && blitter_drawing; + wire [9:0] line_buffer_write_address_nx = blitter_input_valid ? blitter_x_start : line_buffer_write_address + 1; + + reg [2:0] blitter_pixel_counter_nx; + + always @* begin + blitter_pixel_counter_nx = blitter_pixel_counter; + + if (blitter_input_valid) begin + blitter_pixel_counter_nx = 0; + end else if (!blitter_all_pixels_counted) begin + blitter_pixel_counter_nx = blitter_pixel_counter + 1; + end + end + + always @(posedge clk) begin + line_buffer_write_en <= line_buffer_write_en_nx; + line_buffer_write_data <= {blitter_output_priority, blitter_output_palette, blitter_output_pixel}; + blitter_row_shifter <= blitter_next_shift; + line_buffer_write_address <= line_buffer_write_address_nx; + blitter_pixel_counter <= blitter_pixel_counter_nx; + + if (blitter_input_valid) begin + blitter_palette <= vf_palette; + blitter_priority <= vf_priority; + end + end + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_tile_address_generator.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_tile_address_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..b63ca956aa8f5cabe7f824e18cdea3947ee0f441 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_tile_address_generator.v @@ -0,0 +1,38 @@ +// vdp_tile_address_generator.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_tile_address_generator( + input clk, + + input [2:0] scroll_y_granular, + input [2:0] raster_y_granular, + input [15:0] vram_data, + input [13:0] tile_base_address, + + output [13:0] tile_address +); + reg [2:0] scroll_y_granular_h; + reg [2:0] raster_y_granular_h; + reg [15:0] map_data_h; + reg [13:0] tile_base_address_h; + + always @(posedge clk) begin + scroll_y_granular_h <= scroll_y_granular; + raster_y_granular_h <= raster_y_granular; + map_data_h <= vram_data; + tile_base_address_h <= tile_base_address; + end + + wire is_yflipped = map_data_h[10]; + wire [2:0] tile_row = scroll_y_granular_h + raster_y_granular_h; + wire [2:0] resolved_tile_row = is_yflipped ? ~tile_row : tile_row; + wire [8:0] tile_number = map_data_h[8:0]; + + assign tile_address = tile_base_address_h + {tile_number, resolved_tile_row}; + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_vga_timing.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vga_timing.v new file mode 100644 index 0000000000000000000000000000000000000000..3ff5055a9884b8dc37db9d6bc3ab13bbe6fe955c --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vga_timing.v @@ -0,0 +1,176 @@ +// vdp_vga_timing.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module vdp_vga_timing #( + parameter H_ACTIVE_WIDTH = 848, + parameter V_ACTIVE_HEIGHT = 480, + + parameter H_FRONTPORCH = 16, + parameter H_SYNC = 112, + parameter H_BACKPORCH = 112, + + parameter V_FRONTPORCH = 6, + parameter V_SYNC = 8, + parameter V_BACKPORCH = 23 +) ( + input clk, + + output reg [10:0] raster_x = 0, + output reg [9:0] raster_y = 0, + + output reg line_ended, + output reg frame_ended, + + output reg active_line_started, + output reg active_frame_ended, + + output reg hsync, + output reg vsync, + output reg active_display +); + localparam STATE_FP = 0; + localparam STATE_SYNC = 1; + localparam STATE_BP = 2; + localparam STATE_ACTIVE = 3; + + localparam H_SIZE = H_ACTIVE_WIDTH + H_FRONTPORCH + H_SYNC + H_BACKPORCH; + localparam V_SIZE = V_ACTIVE_HEIGHT + V_FRONTPORCH + V_SYNC + V_BACKPORCH; + + localparam H_OFFSCREEN_WIDTH = H_SIZE - H_ACTIVE_WIDTH; + localparam V_OFFSCREEN_HEIGHT = V_SIZE - V_ACTIVE_HEIGHT; + + wire line_ended_nx = x_fsm_nx == STATE_FP && x_fsm == STATE_ACTIVE; + wire frame_ended_nx = y_fsm_nx == STATE_ACTIVE && y_fsm == STATE_BP && line_ended_nx; + wire active_frame_ended_nx = line_ended_nx && y_fsm == STATE_ACTIVE && y_fsm_nx == STATE_FP; + + wire hsync_b_nx = x_fsm == STATE_SYNC; + wire vsync_b_nx = y_fsm == STATE_SYNC; + + wire active_display_nx = y_fsm == STATE_ACTIVE && x_fsm_nx == STATE_ACTIVE; + + wire active_line_started_nx = x_fsm == STATE_FP && x_fsm_nx == STATE_ACTIVE; + + reg [1:0] x_fsm_nx; + + always @* begin + x_fsm_nx = (raster_x == x_next_count ? x_fsm + 1 : x_fsm); + end + + reg [1:0] y_fsm_nx; + + always @* begin + y_fsm_nx = y_fsm; + + if (line_ended_nx) begin + y_fsm_nx = (raster_y == y_next_count ? y_fsm + 1 : y_fsm); + end + end + + reg [1:0] x_fsm = 0; + reg [1:0] y_fsm = STATE_ACTIVE; + + always @(posedge clk) begin + x_fsm <= x_fsm_nx; + y_fsm <= y_fsm_nx; + end + + reg [10:0] x_next_count, y_next_count; + + // target counts to advance state + + always @* begin + (* full_case, parallel_case *) + case (x_fsm) + STATE_FP: x_next_count = H_FRONTPORCH - 1; + STATE_SYNC: x_next_count = H_FRONTPORCH + H_SYNC - 1; + STATE_BP: x_next_count = H_SYNC + H_FRONTPORCH + H_BACKPORCH - 1; + STATE_ACTIVE: x_next_count = H_SIZE - 1; + endcase + end + + always @* begin + (* full_case, parallel_case *) + case (y_fsm) + STATE_FP: y_next_count = V_ACTIVE_HEIGHT + V_FRONTPORCH - 1; + STATE_SYNC: y_next_count = V_ACTIVE_HEIGHT + V_FRONTPORCH + V_SYNC - 1; + STATE_BP: y_next_count = V_SIZE - 1; + STATE_ACTIVE: y_next_count = V_ACTIVE_HEIGHT - 1; + endcase + end + + reg [10:0] raster_x_nx; + reg [9:0] raster_y_nx; + + always @* begin + raster_x_nx = raster_x + 1; + raster_y_nx = raster_y; + + if (line_ended_nx) begin + raster_x_nx = 0; + raster_y_nx = raster_y + 1; + + if (frame_ended_nx) begin + raster_y_nx = 0; + end + end + end + + always @(posedge clk) begin + raster_x <= raster_x_nx; + raster_y <= raster_y_nx; + end + + always @(posedge clk) begin + hsync <= !hsync_b_nx; + vsync <= !vsync_b_nx; + active_display <= active_display_nx; + line_ended <= line_ended_nx; + frame_ended <= frame_ended_nx; + active_line_started <= active_line_started_nx; + active_frame_ended <= active_frame_ended_nx; + end + +`ifdef FORMAL + + reg past_valid = 0; + reg [1:0] past_counter = 0; + + initial begin + restrict(reset); + end + + always @(posedge clk) begin + if (past_counter < 3) begin + past_counter <= past_counter + 1; + end else begin + past_valid <= 1; + end + + if (past_counter != 0) begin + assume(!reset); + end + end + + always @(posedge clk) begin + if (!$past(reset) && past_counter > 2) begin + assert(active_display == (raster_x > H_OFFSCREEN_WIDTH && raster_y < (V_SIZE - V_OFFSCREEN_HEIGHT))); + + assert(!hsync == ((raster_x >= H_FRONTPORCH) && (raster_x < H_FRONTPORCH + H_SYNC))); + assert(!vsync == ((raster_y >= V_ACTIVE_HEIGHT + V_FRONTPORCH) && (raster_y < V_ACTIVE_HEIGHT + V_FRONTPORCH + V_SYNC))); + + assert(line_ended_nx == (raster_x == (H_SIZE - 1))); + assert(line_ended == (raster_x == 0)); + + assert(frame_ended_nx == (raster_y == (V_SIZE - 1))); + assert(active_frame_ended_nx == (raster_y == V_ACTIVE_HEIGHT - 1 && line_ended_nx)); + end + end + +`endif + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_interleaved.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_interleaved.v new file mode 100644 index 0000000000000000000000000000000000000000..5324d0f3639f58009b7d9dc88b5da5623670cde7 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_interleaved.v @@ -0,0 +1,371 @@ +// vdp_vram_bus_arbiter_interleaved.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" +`include "layer_encoding.vh" + +// This is the original VRAM bus arbiter that uses interleaved tilemaps +// It allows for 4 scrolling layers using separate odd / even addresses for the separate RAMs +// The downside is that the interleaving means VRAM space may be wasted + +// This is one of the older parts of the project before and could use some cleanup + +module vdp_vram_bus_arbiter_interleaved( + input clk, + + // Reference raster positions + + input [10:0] raster_x_offset, + input [10:0] raster_x, + input [9:0] raster_y, + + // Scroll attributes + + input [10:0] scroll_x_0, scroll_x_1, scroll_x_2, scroll_x_3, + input [9:0] scroll_y_0, scroll_y_1, scroll_y_2, scroll_y_3, + + // 4 layers combined + input [15:0] scroll_tile_base, + input [15:0] scroll_map_base, + + // Affine attributes + + input affine_enabled, + input affine_offscreen, + input [13:0] affine_vram_address_even, affine_vram_address_odd, + + // Sprite attributes + + input [13:0] vram_sprite_address, + + // 4 layers combined + input [3:0] scroll_use_wide_map, + + // Output scroll attributes + + output [3:0] scroll_palette_0, scroll_palette_1, scroll_palette_2, scroll_palette_3, + output scroll_x_flip_0, scroll_x_flip_1, scroll_x_flip_2, scroll_x_flip_3, + + // Output control for various functional blocks + + output reg load_all_scroll_row_data, + output reg vram_written, + output reg vram_sprite_read_data_valid, + + output reg [3:0] scroll_char_load, + output reg [3:0] scroll_meta_load, + + // VRAM write control + + input [1:0] vram_port_write_en_mask, + input [13:0] vram_write_address_16b, + input [15:0] vram_write_data_16b, + + // VRAM interface + + input [15:0] vram_read_data_even, vram_read_data_odd, + + output reg [13:0] vram_address_even, vram_address_odd, + output reg [15:0] vram_write_data_even, vram_write_data_odd, + output reg vram_we_even, vram_we_odd +); + // --- Layer attribute selection --- + + reg [9:0] gen_even_hscroll; + reg [9:0] gen_even_scroll_y; + reg [13:0] gen_even_map_base; + reg gen_even_use_wide_map; + + reg [9:0] gen_odd_hscroll; + reg [9:0] gen_odd_scroll_y; + reg [13:0] gen_odd_map_base; + reg gen_odd_use_wide_map; + + wire [3:0] gen_even_palette = vram_read_data_even[15:12]; + wire gen_even_hflip = vram_read_data_even[9]; + + wire [3:0] gen_odd_palette = vram_read_data_odd[15:12]; + wire gen_odd_hflip = vram_read_data_odd[9]; + + wire [13:0] gen_even_next_map_address; + wire [13:0] gen_odd_next_map_address; + + reg gen_toggle_nx; + reg gen_toggle; + + always @(posedge clk) begin + gen_toggle <= gen_toggle_nx; + end + + always @* begin + if (!gen_toggle) begin + // 0 + gen_even_hscroll = scroll_x_0; + gen_even_scroll_y = scroll_y_0; + gen_even_map_base = full_scroll_map_base(0); + gen_even_use_wide_map = scroll_use_wide_map[0]; + // 1 + gen_odd_hscroll = scroll_x_1; + gen_odd_scroll_y = scroll_y_1; + gen_odd_map_base = full_scroll_map_base(1); + gen_odd_use_wide_map = scroll_use_wide_map[1]; + end else begin + // 2 + gen_even_hscroll = scroll_x_2; + gen_even_scroll_y = scroll_y_2; + gen_even_map_base = full_scroll_map_base(2); + gen_even_use_wide_map = scroll_use_wide_map[2]; + // 3 + gen_odd_hscroll = scroll_x_3; + gen_odd_scroll_y = scroll_y_3; + gen_odd_map_base = full_scroll_map_base(3); + gen_odd_use_wide_map = scroll_use_wide_map[3]; + end + end + + // --- Tile address generator --- + + reg [2:0] tile_address_gen_scroll_y_granular; + wire [2:0] tile_address_gen_raster_y_granular = raster_y[2:0]; + reg [15:0] tile_address_gen_map_data_in; + reg [13:0] tile_address_gen_base_address; + + wire [13:0] tile_address_gen_tile_address_out; + + vdp_tile_address_generator tile_address_generator( + .clk(clk), + + .scroll_y_granular(tile_address_gen_scroll_y_granular), + .raster_y_granular(tile_address_gen_raster_y_granular), + .vram_data(tile_address_gen_map_data_in), + .tile_base_address(tile_address_gen_base_address), + + .tile_address(tile_address_gen_tile_address_out) + ); + + // --- Map address generators --- + + wire [10:0] raster_x_next_tile = raster_x_offset[9:3] + 1; + + vdp_map_address_generator even_generator( + .raster_y(raster_y), + .raster_x_coarse(raster_x_next_tile), + + .scroll_x_coarse(gen_even_hscroll[9:3]), + .scroll_y(gen_even_scroll_y), + + .map_base_address(gen_even_map_base), + .stride(gen_even_use_wide_map ? 128 : 64), + + .map_address_16b(gen_even_next_map_address) + ); + + vdp_map_address_generator odd_generator( + .raster_y(raster_y), + .raster_x_coarse(raster_x_next_tile), + + .scroll_x_coarse(gen_odd_hscroll[9:3]), + .scroll_y(gen_odd_scroll_y), + + .map_base_address(gen_odd_map_base), + .stride(gen_odd_use_wide_map ? 128 : 64), + + .map_address_16b(gen_odd_next_map_address) + ); + + // --- Scroll meta prefetch --- + + reg [15:0] scroll_map_data_hold [0:3]; + + wire [3:0] even_palette = vram_read_data_even[15:12]; + wire [3:0] odd_palette = vram_read_data_odd[15:12]; + + wire even_x_flip = vram_read_data_even[9]; + wire odd_x_flip = vram_read_data_odd[9]; + + assign scroll_palette_0 = even_palette; + assign scroll_palette_1 = odd_palette; + assign scroll_palette_2 = even_palette; + assign scroll_palette_3 = odd_palette; + + assign scroll_x_flip_0 = even_x_flip; + assign scroll_x_flip_1 = odd_x_flip; + assign scroll_x_flip_2 = even_x_flip; + assign scroll_x_flip_3 = odd_x_flip; + + always @(posedge clk) begin + // (scroll0 meta doesn't need to be held) + + if (scroll_meta_load[`LAYER_SCROLL1]) + scroll_map_data_hold[`LAYER_SCROLL1] <= vram_read_data_odd; + if (scroll_meta_load[`LAYER_SCROLL2]) + scroll_map_data_hold[`LAYER_SCROLL2] <= vram_read_data_even; + if (scroll_meta_load[`LAYER_SCROLL3]) + scroll_map_data_hold[`LAYER_SCROLL3] <= vram_read_data_odd; + end + + // --- VRAM bus control --- + + reg [13:0] vram_address_even_nx, vram_address_odd_nx; + reg [1:0] vram_render_write_en_mask_nx; + + always @* begin + scroll_meta_load = 0; + scroll_char_load = 0; + + load_all_scroll_row_data = 0; + vram_render_write_en_mask_nx = 0; + + gen_toggle_nx = 0; + vram_address_even_nx = 0; + vram_address_odd_nx = 0; + vram_written = 0; + + tile_address_gen_scroll_y_granular = 0; + tile_address_gen_map_data_in = 0; + tile_address_gen_base_address = 0; + + vram_sprite_read_data_valid = 0; + + // TODO: define and document the -1 offset in one place + case ((raster_x[2:0] - 1) &3'b111) + 0: begin + // now: s2/s3 map data + scroll_meta_load = `LAYER_SCROLL2_OHE | `LAYER_SCROLL3_OHE; + + // next: s1 tile + vram_address_even_nx = tile_address_gen_tile_address_out; + vram_address_odd_nx = tile_address_gen_tile_address_out; + + // next next: s1 prepare tile address gen + tile_address_gen_scroll_y_granular = scroll_y_1[2:0]; + tile_address_gen_map_data_in = scroll_map_data_hold[1]; + tile_address_gen_base_address = full_scroll_tile_base(1); + end + 1: begin + // now: sprite row data available + vram_sprite_read_data_valid = 1; + + // next: s2 tile + vram_address_even_nx = tile_address_gen_tile_address_out; + vram_address_odd_nx = tile_address_gen_tile_address_out; + + // next next: s3 tile + tile_address_gen_scroll_y_granular = scroll_y_2[2:0]; + tile_address_gen_map_data_in = scroll_map_data_hold[2]; + tile_address_gen_base_address = full_scroll_tile_base(2); + end + 2: begin + // now: nothing, because this was a CPU write + + // next: s2 tile + vram_address_even_nx = tile_address_gen_tile_address_out; + vram_address_odd_nx = tile_address_gen_tile_address_out; + + // next next: s3 tile + tile_address_gen_scroll_y_granular = scroll_y_3[2:0]; + tile_address_gen_map_data_in = scroll_map_data_hold[3]; + tile_address_gen_base_address = full_scroll_tile_base(3); + end + 3: begin + gen_toggle_nx = 0; + + // now: s0 tile + scroll_char_load = `LAYER_SCROLL0_OHE; + + // next: s3 tile + vram_address_even_nx = tile_address_gen_tile_address_out; + vram_address_odd_nx = tile_address_gen_tile_address_out; + + // next next: none + end + 4: begin + gen_toggle_nx = 1; + + // now: s1 tile + scroll_char_load = `LAYER_SCROLL1_OHE; + + // next: s0/s1 map address + vram_address_even_nx = gen_even_next_map_address; + vram_address_odd_nx = gen_odd_next_map_address; + end + 5: begin + // now: s2 tile + scroll_char_load = `LAYER_SCROLL2_OHE; + + // next: s1/s2 map address + vram_address_even_nx = gen_even_next_map_address; + vram_address_odd_nx = gen_odd_next_map_address; + end + 6: begin + // next: sprite row fetch (if any, this could be ignored in sprite_core) + vram_address_even_nx = vram_sprite_address; + vram_address_odd_nx = vram_sprite_address; + + // now: s3 tile, which is loaded simultaneously with the previously prefetched layers + // the offset added to count[2:0] compensates for this being a cycle earlier + load_all_scroll_row_data = 1; + end + 7: begin + // host write - every 8 cycles + vram_address_even_nx = vram_write_address_16b; + vram_address_odd_nx = vram_write_address_16b; + vram_written = 1; + vram_render_write_en_mask_nx = vram_port_write_en_mask; + + // now: s0/s1 map data + scroll_meta_load = `LAYER_SCROLL0_OHE | `LAYER_SCROLL1_OHE; + + // s0: prepare tile address gen + tile_address_gen_scroll_y_granular = scroll_y_0[2:0]; + tile_address_gen_map_data_in = vram_read_data_even; + tile_address_gen_base_address = full_scroll_tile_base(0); + end + endcase + end + + // --- VRAM write data passthrough --- + + always @* begin + vram_write_data_even = vram_write_data_16b; + vram_write_data_odd = vram_write_data_16b; + end + + // --- VRAM bus registers --- + + wire affine_needs_vram = affine_enabled && !affine_offscreen; + + always @(posedge clk) begin + vram_address_even <= affine_needs_vram ? affine_vram_address_even : vram_address_even_nx; + vram_we_even <= affine_needs_vram ? 0 : vram_render_write_en_mask_nx[0]; + + vram_address_odd <= affine_needs_vram ? affine_vram_address_odd : vram_address_odd_nx; + vram_we_odd <= affine_needs_vram ? 0 : vram_render_write_en_mask_nx[1]; + end + + // --- VRAM base address mapping functions --- + + function [13:0] full_scroll_tile_base; + input [1:0] layer; + + begin + full_scroll_tile_base = {scroll_tile_base >> (layer * 4), 10'b0}; + end + + endfunction + + function [13:0] full_scroll_map_base; + input [1:0] layer; + + begin + full_scroll_map_base = {scroll_map_base >> (layer * 4), 10'b0}; + end + + endfunction + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_standard.v b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_standard.v new file mode 100644 index 0000000000000000000000000000000000000000..7d45faccc08028c395da6b654c23b5f24ff8761a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vdp/vdp_vram_bus_arbiter_standard.v @@ -0,0 +1,340 @@ +// vdp_vram_bus_arbiter_standard.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +`include "debug.vh" +`include "layer_encoding.vh" + +// 3 layer, non-interleaved bus arbiter +// Unlike vdp_vram_bus_arbiter_interleaved, tilemaps are stored in VRAM contiguously +// This sacrifices 1 layer in exchange for more flexible, less wasteful VRAM management + +module vdp_vram_bus_arbiter_standard( + input clk, + + // Reference raster positions + + input [10:0] raster_x_offset, + input [10:0] raster_x, + input [9:0] raster_y, + + // Scroll attributes + + input [10:0] scroll_x_0, scroll_x_1, scroll_x_2, scroll_x_3, + input [9:0] scroll_y_0, scroll_y_1, scroll_y_2, scroll_y_3, + + // 4 layers combined + input [15:0] scroll_tile_base, + input [15:0] scroll_map_base, + + // Affine attributes + + input affine_enabled, + input affine_offscreen, + input [13:0] affine_vram_address_even, affine_vram_address_odd, + + // Sprite attributes + + input [13:0] vram_sprite_address, + + // 4 layers combined + input [3:0] scroll_use_wide_map, + + // Output scroll attributes + + output [3:0] scroll_palette_0, scroll_palette_1, scroll_palette_2, scroll_palette_3, + output scroll_x_flip_0, scroll_x_flip_1, scroll_x_flip_2, scroll_x_flip_3, + + // Output control for various functional blocks + + output reg load_all_scroll_row_data, + output reg vram_written, + output reg vram_sprite_read_data_valid, + + output reg [3:0] scroll_char_load, + output reg [3:0] scroll_meta_load, + + // VRAM write control + + input [1:0] vram_port_write_en_mask, + input [13:0] vram_write_address_16b, + input [15:0] vram_write_data_16b, + + // VRAM interface + + input [15:0] vram_read_data_even, vram_read_data_odd, + + output reg [13:0] vram_address_even, vram_address_odd, + output reg [15:0] vram_write_data_even, vram_write_data_odd, + output reg vram_we_even, vram_we_odd +); + // --- Layer attribute selection --- + + reg [10:0] scroll_x_selected; + reg [9:0] scroll_y_selected; + reg [14:0] scroll_map_base_selected; + reg scroll_use_wide_map_selected; + + always @* begin + case (map_address_layer_select) + `LAYER_SCROLL0: scroll_x_selected = scroll_x_0; + `LAYER_SCROLL1: scroll_x_selected = scroll_x_1; + default: scroll_x_selected = scroll_x_2; + endcase + + case (map_address_layer_select) + `LAYER_SCROLL0: scroll_y_selected = scroll_y_0; + `LAYER_SCROLL1: scroll_y_selected = scroll_y_1; + default: scroll_y_selected = scroll_y_2; + endcase + + scroll_map_base_selected = full_scroll_map_base(map_address_layer_select); + scroll_use_wide_map_selected = scroll_use_wide_map[map_address_layer_select]; + end + + // --- Tile address generator --- + + wire [2:0] tile_raster_y_granular = raster_y[2:0]; + wire [13:0] tile_address; + + vdp_tile_address_generator tile_address_generator( + .clk(clk), + + .scroll_y_granular(tile_scroll_y_granular_selected), + .raster_y_granular(tile_raster_y_granular), + .vram_data(tile_map_data_selected), + .tile_base_address(tile_base_selected), + + .tile_address(tile_address) + ); + + reg [2:0] tile_scroll_y_granular_selected; + reg [15:0] tile_map_data_selected; + reg [13:0] tile_base_selected; + + always @* begin + case (tile_address_layer_select) + `LAYER_SCROLL0: tile_scroll_y_granular_selected = scroll_y_0[2:0]; + `LAYER_SCROLL1: tile_scroll_y_granular_selected = scroll_y_1[2:0]; + default: tile_scroll_y_granular_selected = scroll_y_2[2:0]; + endcase + + tile_map_data_selected = scroll_map_data_hold[tile_address_layer_select]; + tile_base_selected = full_scroll_tile_base(tile_address_layer_select); + end + + // --- Map address generators --- + + wire [10:0] raster_x_next_tile = raster_x_offset[9:3] + 1; + + wire [13:0] map_address = map_address_16b[14:1]; + wire map_word_select = map_address_16b[0]; + + wire [14:0] map_address_16b; + + vdp_map_address_generator #( + .REGISTERED_INPUTS(1) + ) map_address_generator ( + .clk(clk), + + .raster_y(raster_y), + .raster_x_coarse(raster_x_next_tile), + + .scroll_x_coarse(scroll_x_selected[9:3]), + .scroll_y(scroll_y_selected), + + .map_base_address(scroll_map_base_selected), + .stride(scroll_use_wide_map_selected ? 128 : 64), + + .map_address_16b(map_address_16b) + ); + + // --- Scroll meta prefetch --- + + reg [15:0] scroll_map_data_hold [0:3]; + + wire [3:0] palette_selected = map_selected_word[15:12]; + + // A delay is needed on the VRAM word select since the fetches are pipelined + + wire map_word_select_d; + + delay_ff #( + .DELAY(3) + ) map_word_select_dm ( + .clk(clk), + .in(map_word_select), + .out(map_word_select_d) + ); + + wire [15:0] map_selected_word = map_word_select_d ? vram_read_data_odd : vram_read_data_even; + + assign scroll_palette_0 = palette_selected; + assign scroll_palette_1 = palette_selected; + assign scroll_palette_2 = palette_selected; + assign scroll_palette_3 = 0; + + assign scroll_x_flip_0 = scroll_map_data_hold[`LAYER_SCROLL0][9]; + assign scroll_x_flip_1 = scroll_map_data_hold[`LAYER_SCROLL1][9]; + assign scroll_x_flip_2 = scroll_map_data_hold[`LAYER_SCROLL2][9]; + assign scroll_x_flip_3 = 0; + + always @(posedge clk) begin + if (scroll_meta_load[`LAYER_SCROLL0]) + scroll_map_data_hold[`LAYER_SCROLL0] <= map_selected_word; + if (scroll_meta_load[`LAYER_SCROLL1]) + scroll_map_data_hold[`LAYER_SCROLL1] <= map_selected_word; + if (scroll_meta_load[`LAYER_SCROLL2]) + scroll_map_data_hold[`LAYER_SCROLL2] <= map_selected_word; + if (scroll_meta_load[`LAYER_SCROLL3]) + scroll_map_data_hold[`LAYER_SCROLL3] <= map_selected_word; + end + + // --- VRAM bus control --- + + reg [13:0] vram_address_nx; + reg [1:0] vram_render_write_en_mask_nx; + + reg [1:0] map_address_layer_select; + reg [1:0] tile_address_layer_select; + + always @* begin + scroll_meta_load = 0; + scroll_char_load = 0; + + map_address_layer_select = 0; + tile_address_layer_select = 0; + + load_all_scroll_row_data = 0; + vram_render_write_en_mask_nx = 0; + + vram_address_nx = 0; + vram_written = 0; + + vram_sprite_read_data_valid = 0; + + case (raster_x_offset[2:0]) + 0: begin + // now: s0 map data + scroll_meta_load = `LAYER_SCROLL0_OHE; + + // host write - every 8 cycles + vram_address_nx = vram_write_address_16b; + vram_written = 1; + vram_render_write_en_mask_nx = vram_port_write_en_mask; + end + 1: begin + // now: s1 map + scroll_meta_load = `LAYER_SCROLL1_OHE; + + // next: sprite access + vram_address_nx = vram_sprite_address; + + // next next: s0 tile address + tile_address_layer_select = `LAYER_SCROLL0; + end + 2: begin + // now: s2 map + scroll_meta_load = `LAYER_SCROLL2_OHE; + + // next: s0 tile + vram_address_nx = tile_address; + + // next next: s1 tile address + tile_address_layer_select = `LAYER_SCROLL1; + end + 3: begin + // next: s1 tile + vram_address_nx = tile_address; + + // next next: s2 tile address + tile_address_layer_select = `LAYER_SCROLL2; + end + 4: begin + // now: sprites acccess + vram_sprite_read_data_valid = 1; + + // next: s2 tile + vram_address_nx = tile_address; + + // next next: s0 map + map_address_layer_select = `LAYER_SCROLL0; + end + 5: begin + // now: s0 tile + scroll_char_load = `LAYER_SCROLL0_OHE; + + // next: s0 map + vram_address_nx = map_address; + + // next next: s1 map + map_address_layer_select = `LAYER_SCROLL1; + end + 6: begin + // now: s1 tile + scroll_char_load = `LAYER_SCROLL1_OHE; + + // next: s1 map + vram_address_nx = map_address; + + // next next: s2 map + map_address_layer_select = `LAYER_SCROLL2; + end + 7: begin + // now: s1 tile + // (this should be implicit according to load_all...) + scroll_char_load = `LAYER_SCROLL2_OHE; + + // next: s2 map + vram_address_nx = map_address; + + // now: s3 tile, which is loaded simultaneously with the previously prefetched layers + load_all_scroll_row_data = 1; + end + endcase + end + + // --- VRAM write data passthrough --- + + always @* begin + vram_write_data_even = vram_write_data_16b; + vram_write_data_odd = vram_write_data_16b; + end + + // --- VRAM bus registers --- + + wire affine_needs_vram = affine_enabled && !affine_offscreen; + + always @(posedge clk) begin + vram_address_even <= affine_needs_vram ? affine_vram_address_even : vram_address_nx; + vram_we_even <= affine_needs_vram ? 0 : vram_render_write_en_mask_nx[0]; + + vram_address_odd <= affine_needs_vram ? affine_vram_address_odd : vram_address_nx; + vram_we_odd <= affine_needs_vram ? 0 : vram_render_write_en_mask_nx[1]; + end + + // --- VRAM base address mapping functions --- + + function [13:0] full_scroll_tile_base; + input [1:0] layer; + + begin + full_scroll_tile_base = {scroll_tile_base >> (layer * 4), 11'b0}; + end + + endfunction + + function [14:0] full_scroll_map_base; + input [1:0] layer; + + begin + full_scroll_map_base = {scroll_map_base >> (layer * 4), 12'b0}; + end + + endfunction + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_00000.v b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_00000.v new file mode 100644 index 0000000000000000000000000000000000000000..27412fb74a44637dbf3843293cd94039c4689823 --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_00000.v @@ -0,0 +1,2361 @@ +// Generator : SpinalHDL v1.4.0 git head : ecb5a80b713566f417ea3ea061f9969e73770a7f +// Date : 06/07/2020, 18:35:14 +// Component : VexRiscv + + +`define BranchCtrlEnum_defaultEncoding_type [1:0] +`define BranchCtrlEnum_defaultEncoding_INC 2'b00 +`define BranchCtrlEnum_defaultEncoding_B 2'b01 +`define BranchCtrlEnum_defaultEncoding_JAL 2'b10 +`define BranchCtrlEnum_defaultEncoding_JALR 2'b11 + +`define AluBitwiseCtrlEnum_defaultEncoding_type [1:0] +`define AluBitwiseCtrlEnum_defaultEncoding_XOR_1 2'b00 +`define AluBitwiseCtrlEnum_defaultEncoding_OR_1 2'b01 +`define AluBitwiseCtrlEnum_defaultEncoding_AND_1 2'b10 + +`define ShiftCtrlEnum_defaultEncoding_type [1:0] +`define ShiftCtrlEnum_defaultEncoding_DISABLE_1 2'b00 +`define ShiftCtrlEnum_defaultEncoding_SLL_1 2'b01 +`define ShiftCtrlEnum_defaultEncoding_SRL_1 2'b10 +`define ShiftCtrlEnum_defaultEncoding_SRA_1 2'b11 + +`define AluCtrlEnum_defaultEncoding_type [1:0] +`define AluCtrlEnum_defaultEncoding_ADD_SUB 2'b00 +`define AluCtrlEnum_defaultEncoding_SLT_SLTU 2'b01 +`define AluCtrlEnum_defaultEncoding_BITWISE 2'b10 + +`define Src2CtrlEnum_defaultEncoding_type [1:0] +`define Src2CtrlEnum_defaultEncoding_RS 2'b00 +`define Src2CtrlEnum_defaultEncoding_IMI 2'b01 +`define Src2CtrlEnum_defaultEncoding_IMS 2'b10 +`define Src2CtrlEnum_defaultEncoding_PC 2'b11 + +`define Src1CtrlEnum_defaultEncoding_type [1:0] +`define Src1CtrlEnum_defaultEncoding_RS 2'b00 +`define Src1CtrlEnum_defaultEncoding_IMU 2'b01 +`define Src1CtrlEnum_defaultEncoding_PC_INCREMENT 2'b10 +`define Src1CtrlEnum_defaultEncoding_URS1 2'b11 + + +module StreamFifoLowLatency ( + input io_push_valid, + output io_push_ready, + input io_push_payload_error, + input [31:0] io_push_payload_inst, + output reg io_pop_valid, + input io_pop_ready, + output reg io_pop_payload_error, + output reg [31:0] io_pop_payload_inst, + input io_flush, + output [0:0] io_occupancy, + input clk, + input reset +); + wire _zz_4_; + wire [0:0] _zz_5_; + reg _zz_1_; + reg pushPtr_willIncrement; + reg pushPtr_willClear; + wire pushPtr_willOverflowIfInc; + wire pushPtr_willOverflow; + reg popPtr_willIncrement; + reg popPtr_willClear; + wire popPtr_willOverflowIfInc; + wire popPtr_willOverflow; + wire ptrMatch; + reg risingOccupancy; + wire empty; + wire full; + wire pushing; + wire popping; + wire [32:0] _zz_2_; + reg [32:0] _zz_3_; + + assign _zz_4_ = (! empty); + assign _zz_5_ = _zz_2_[0 : 0]; + always @ (*) begin + _zz_1_ = 1'b0; + if(pushing)begin + _zz_1_ = 1'b1; + end + end + + always @ (*) begin + pushPtr_willIncrement = 1'b0; + if(pushing)begin + pushPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + pushPtr_willClear = 1'b0; + if(io_flush)begin + pushPtr_willClear = 1'b1; + end + end + + assign pushPtr_willOverflowIfInc = 1'b1; + assign pushPtr_willOverflow = (pushPtr_willOverflowIfInc && pushPtr_willIncrement); + always @ (*) begin + popPtr_willIncrement = 1'b0; + if(popping)begin + popPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + popPtr_willClear = 1'b0; + if(io_flush)begin + popPtr_willClear = 1'b1; + end + end + + assign popPtr_willOverflowIfInc = 1'b1; + assign popPtr_willOverflow = (popPtr_willOverflowIfInc && popPtr_willIncrement); + assign ptrMatch = 1'b1; + assign empty = (ptrMatch && (! risingOccupancy)); + assign full = (ptrMatch && risingOccupancy); + assign pushing = (io_push_valid && io_push_ready); + assign popping = (io_pop_valid && io_pop_ready); + assign io_push_ready = (! full); + always @ (*) begin + if(_zz_4_)begin + io_pop_valid = 1'b1; + end else begin + io_pop_valid = io_push_valid; + end + end + + assign _zz_2_ = _zz_3_; + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_error = _zz_5_[0]; + end else begin + io_pop_payload_error = io_push_payload_error; + end + end + + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_inst = _zz_2_[32 : 1]; + end else begin + io_pop_payload_inst = io_push_payload_inst; + end + end + + assign io_occupancy = (risingOccupancy && ptrMatch); + always @ (posedge clk or posedge reset) begin + if (reset) begin + risingOccupancy <= 1'b0; + end else begin + if((pushing != popping))begin + risingOccupancy <= pushing; + end + if(io_flush)begin + risingOccupancy <= 1'b0; + end + end + end + + always @ (posedge clk) begin + if(_zz_1_)begin + _zz_3_ <= {io_push_payload_inst,io_push_payload_error}; + end + end + + +endmodule + +module VexRiscv ( + output iBus_cmd_valid, + input iBus_cmd_ready, + output [31:0] iBus_cmd_payload_pc, + input iBus_rsp_valid, + input iBus_rsp_payload_error, + input [31:0] iBus_rsp_payload_inst, + output dBus_cmd_valid, + input dBus_cmd_ready, + output dBus_cmd_payload_wr, + output [31:0] dBus_cmd_payload_address, + output [31:0] dBus_cmd_payload_data, + output [1:0] dBus_cmd_payload_size, + input dBus_rsp_ready, + input dBus_rsp_error, + input [31:0] dBus_rsp_data, + input clk, + input reset +); + wire _zz_84_; + wire _zz_85_; + reg [31:0] _zz_86_; + reg [31:0] _zz_87_; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + wire [0:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy; + wire _zz_88_; + wire _zz_89_; + wire _zz_90_; + wire _zz_91_; + wire _zz_92_; + wire _zz_93_; + wire _zz_94_; + wire _zz_95_; + wire [1:0] _zz_96_; + wire [0:0] _zz_97_; + wire [0:0] _zz_98_; + wire [0:0] _zz_99_; + wire [0:0] _zz_100_; + wire [0:0] _zz_101_; + wire [0:0] _zz_102_; + wire [0:0] _zz_103_; + wire [0:0] _zz_104_; + wire [0:0] _zz_105_; + wire [0:0] _zz_106_; + wire [2:0] _zz_107_; + wire [31:0] _zz_108_; + wire [2:0] _zz_109_; + wire [0:0] _zz_110_; + wire [2:0] _zz_111_; + wire [0:0] _zz_112_; + wire [2:0] _zz_113_; + wire [0:0] _zz_114_; + wire [2:0] _zz_115_; + wire [0:0] _zz_116_; + wire [2:0] _zz_117_; + wire [0:0] _zz_118_; + wire [2:0] _zz_119_; + wire [4:0] _zz_120_; + wire [11:0] _zz_121_; + wire [11:0] _zz_122_; + wire [31:0] _zz_123_; + wire [31:0] _zz_124_; + wire [31:0] _zz_125_; + wire [31:0] _zz_126_; + wire [31:0] _zz_127_; + wire [31:0] _zz_128_; + wire [31:0] _zz_129_; + wire [31:0] _zz_130_; + wire [32:0] _zz_131_; + wire [19:0] _zz_132_; + wire [11:0] _zz_133_; + wire [11:0] _zz_134_; + wire _zz_135_; + wire _zz_136_; + wire [31:0] _zz_137_; + wire _zz_138_; + wire _zz_139_; + wire _zz_140_; + wire [0:0] _zz_141_; + wire [0:0] _zz_142_; + wire _zz_143_; + wire [0:0] _zz_144_; + wire [16:0] _zz_145_; + wire [31:0] _zz_146_; + wire _zz_147_; + wire _zz_148_; + wire [0:0] _zz_149_; + wire [1:0] _zz_150_; + wire [0:0] _zz_151_; + wire [0:0] _zz_152_; + wire _zz_153_; + wire [0:0] _zz_154_; + wire [13:0] _zz_155_; + wire [31:0] _zz_156_; + wire [31:0] _zz_157_; + wire [31:0] _zz_158_; + wire [31:0] _zz_159_; + wire [31:0] _zz_160_; + wire [31:0] _zz_161_; + wire _zz_162_; + wire [0:0] _zz_163_; + wire [0:0] _zz_164_; + wire [0:0] _zz_165_; + wire [0:0] _zz_166_; + wire _zz_167_; + wire [0:0] _zz_168_; + wire [10:0] _zz_169_; + wire [31:0] _zz_170_; + wire [31:0] _zz_171_; + wire [31:0] _zz_172_; + wire [31:0] _zz_173_; + wire [0:0] _zz_174_; + wire [2:0] _zz_175_; + wire [1:0] _zz_176_; + wire [1:0] _zz_177_; + wire _zz_178_; + wire [0:0] _zz_179_; + wire [7:0] _zz_180_; + wire _zz_181_; + wire _zz_182_; + wire [31:0] _zz_183_; + wire [31:0] _zz_184_; + wire [31:0] _zz_185_; + wire [31:0] _zz_186_; + wire [0:0] _zz_187_; + wire [0:0] _zz_188_; + wire [0:0] _zz_189_; + wire [0:0] _zz_190_; + wire _zz_191_; + wire [0:0] _zz_192_; + wire [4:0] _zz_193_; + wire [31:0] _zz_194_; + wire [31:0] _zz_195_; + wire [0:0] _zz_196_; + wire [0:0] _zz_197_; + wire [0:0] _zz_198_; + wire [0:0] _zz_199_; + wire _zz_200_; + wire [0:0] _zz_201_; + wire [1:0] _zz_202_; + wire [31:0] _zz_203_; + wire [31:0] _zz_204_; + wire [31:0] _zz_205_; + wire [31:0] _zz_206_; + wire [31:0] _zz_207_; + wire [31:0] _zz_208_; + wire _zz_209_; + wire _zz_210_; + wire decode_SRC2_FORCE_ZERO; + wire `BranchCtrlEnum_defaultEncoding_type decode_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_1_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_2_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_3_; + wire [31:0] memory_MEMORY_READ_DATA; + wire `AluBitwiseCtrlEnum_defaultEncoding_type decode_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_4_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_5_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_6_; + wire decode_BYPASSABLE_EXECUTE_STAGE; + wire [31:0] execute_BRANCH_CALC; + wire [31:0] writeBack_REGFILE_WRITE_DATA; + wire [31:0] execute_REGFILE_WRITE_DATA; + wire `ShiftCtrlEnum_defaultEncoding_type decode_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_7_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_8_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_9_; + wire decode_MEMORY_ENABLE; + wire decode_SRC_LESS_UNSIGNED; + wire [31:0] memory_FORMAL_PC_NEXT; + wire [31:0] execute_FORMAL_PC_NEXT; + wire [31:0] decode_FORMAL_PC_NEXT; + wire decode_MEMORY_STORE; + wire `AluCtrlEnum_defaultEncoding_type decode_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_10_; + wire `AluCtrlEnum_defaultEncoding_type _zz_11_; + wire `AluCtrlEnum_defaultEncoding_type _zz_12_; + wire [31:0] memory_PC; + wire [31:0] decode_RS1; + wire execute_BRANCH_DO; + wire [31:0] decode_SRC1; + wire [1:0] memory_MEMORY_ADDRESS_LOW; + wire [1:0] execute_MEMORY_ADDRESS_LOW; + wire [31:0] decode_SRC2; + wire execute_BYPASSABLE_MEMORY_STAGE; + wire decode_BYPASSABLE_MEMORY_STAGE; + wire [31:0] decode_RS2; + wire [31:0] memory_BRANCH_CALC; + wire memory_BRANCH_DO; + wire [31:0] execute_PC; + wire [31:0] execute_RS1; + wire `BranchCtrlEnum_defaultEncoding_type execute_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_13_; + wire decode_RS2_USE; + wire decode_RS1_USE; + wire execute_REGFILE_WRITE_VALID; + wire execute_BYPASSABLE_EXECUTE_STAGE; + wire memory_REGFILE_WRITE_VALID; + wire [31:0] memory_INSTRUCTION; + wire memory_BYPASSABLE_MEMORY_STAGE; + wire writeBack_REGFILE_WRITE_VALID; + reg [31:0] _zz_14_; + wire [31:0] memory_REGFILE_WRITE_DATA; + wire `ShiftCtrlEnum_defaultEncoding_type execute_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_15_; + wire execute_SRC_LESS_UNSIGNED; + wire execute_SRC2_FORCE_ZERO; + wire execute_SRC_USE_SUB_LESS; + wire [31:0] _zz_16_; + wire [31:0] _zz_17_; + wire `Src2CtrlEnum_defaultEncoding_type decode_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_18_; + wire [31:0] _zz_19_; + wire `Src1CtrlEnum_defaultEncoding_type decode_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_20_; + wire decode_SRC_USE_SUB_LESS; + wire decode_SRC_ADD_ZERO; + wire [31:0] execute_SRC_ADD_SUB; + wire execute_SRC_LESS; + wire `AluCtrlEnum_defaultEncoding_type execute_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_21_; + wire [31:0] execute_SRC2; + wire [31:0] execute_SRC1; + wire `AluBitwiseCtrlEnum_defaultEncoding_type execute_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_22_; + wire [31:0] _zz_23_; + wire _zz_24_; + reg _zz_25_; + wire [31:0] decode_INSTRUCTION_ANTICIPATED; + reg decode_REGFILE_WRITE_VALID; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_26_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_27_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_28_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_29_; + wire `AluCtrlEnum_defaultEncoding_type _zz_30_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_31_; + wire writeBack_MEMORY_STORE; + reg [31:0] _zz_32_; + wire writeBack_MEMORY_ENABLE; + wire [1:0] writeBack_MEMORY_ADDRESS_LOW; + wire [31:0] writeBack_MEMORY_READ_DATA; + wire memory_MEMORY_STORE; + wire memory_MEMORY_ENABLE; + wire [31:0] execute_SRC_ADD; + wire [31:0] execute_RS2; + wire [31:0] execute_INSTRUCTION; + wire execute_MEMORY_STORE; + wire execute_MEMORY_ENABLE; + wire execute_ALIGNEMENT_FAULT; + wire [31:0] decode_PC; + wire [31:0] decode_INSTRUCTION; + wire [31:0] writeBack_PC; + wire [31:0] writeBack_INSTRUCTION; + wire decode_arbitration_haltItself; + reg decode_arbitration_haltByOther; + reg decode_arbitration_removeIt; + wire decode_arbitration_flushIt; + wire decode_arbitration_flushNext; + wire decode_arbitration_isValid; + wire decode_arbitration_isStuck; + wire decode_arbitration_isStuckByOthers; + wire decode_arbitration_isFlushed; + wire decode_arbitration_isMoving; + wire decode_arbitration_isFiring; + reg execute_arbitration_haltItself; + wire execute_arbitration_haltByOther; + reg execute_arbitration_removeIt; + wire execute_arbitration_flushIt; + wire execute_arbitration_flushNext; + reg execute_arbitration_isValid; + wire execute_arbitration_isStuck; + wire execute_arbitration_isStuckByOthers; + wire execute_arbitration_isFlushed; + wire execute_arbitration_isMoving; + wire execute_arbitration_isFiring; + reg memory_arbitration_haltItself; + wire memory_arbitration_haltByOther; + reg memory_arbitration_removeIt; + wire memory_arbitration_flushIt; + reg memory_arbitration_flushNext; + reg memory_arbitration_isValid; + wire memory_arbitration_isStuck; + wire memory_arbitration_isStuckByOthers; + wire memory_arbitration_isFlushed; + wire memory_arbitration_isMoving; + wire memory_arbitration_isFiring; + wire writeBack_arbitration_haltItself; + wire writeBack_arbitration_haltByOther; + reg writeBack_arbitration_removeIt; + wire writeBack_arbitration_flushIt; + wire writeBack_arbitration_flushNext; + reg writeBack_arbitration_isValid; + wire writeBack_arbitration_isStuck; + wire writeBack_arbitration_isStuckByOthers; + wire writeBack_arbitration_isFlushed; + wire writeBack_arbitration_isMoving; + wire writeBack_arbitration_isFiring; + wire [31:0] lastStageInstruction /* verilator public */ ; + wire [31:0] lastStagePc /* verilator public */ ; + wire lastStageIsValid /* verilator public */ ; + wire lastStageIsFiring /* verilator public */ ; + wire IBusSimplePlugin_fetcherHalt; + reg IBusSimplePlugin_incomingInstruction; + wire IBusSimplePlugin_pcValids_0; + wire IBusSimplePlugin_pcValids_1; + wire IBusSimplePlugin_pcValids_2; + wire IBusSimplePlugin_pcValids_3; + wire BranchPlugin_jumpInterface_valid; + wire [31:0] BranchPlugin_jumpInterface_payload; + wire IBusSimplePlugin_externalFlush; + wire IBusSimplePlugin_jump_pcLoad_valid; + wire [31:0] IBusSimplePlugin_jump_pcLoad_payload; + wire IBusSimplePlugin_fetchPc_output_valid; + wire IBusSimplePlugin_fetchPc_output_ready; + wire [31:0] IBusSimplePlugin_fetchPc_output_payload; + reg [31:0] IBusSimplePlugin_fetchPc_pcReg /* verilator public */ ; + reg IBusSimplePlugin_fetchPc_correction; + reg IBusSimplePlugin_fetchPc_correctionReg; + wire IBusSimplePlugin_fetchPc_corrected; + reg IBusSimplePlugin_fetchPc_pcRegPropagate; + reg IBusSimplePlugin_fetchPc_booted; + reg IBusSimplePlugin_fetchPc_inc; + reg [31:0] IBusSimplePlugin_fetchPc_pc; + reg IBusSimplePlugin_fetchPc_flushed; + wire IBusSimplePlugin_iBusRsp_redoFetch; + wire IBusSimplePlugin_iBusRsp_stages_0_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_0_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_output_payload; + reg IBusSimplePlugin_iBusRsp_stages_0_halt; + wire IBusSimplePlugin_iBusRsp_stages_1_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_1_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_output_payload; + wire IBusSimplePlugin_iBusRsp_stages_1_halt; + wire _zz_33_; + wire _zz_34_; + wire IBusSimplePlugin_iBusRsp_flush; + wire _zz_35_; + wire _zz_36_; + reg _zz_37_; + reg IBusSimplePlugin_iBusRsp_readyForError; + wire IBusSimplePlugin_iBusRsp_output_valid; + wire IBusSimplePlugin_iBusRsp_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_pc; + wire IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + wire IBusSimplePlugin_iBusRsp_output_payload_isRvc; + wire IBusSimplePlugin_injector_decodeInput_valid; + wire IBusSimplePlugin_injector_decodeInput_ready; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_pc; + wire IBusSimplePlugin_injector_decodeInput_payload_rsp_error; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + wire IBusSimplePlugin_injector_decodeInput_payload_isRvc; + reg _zz_38_; + reg [31:0] _zz_39_; + reg _zz_40_; + reg [31:0] _zz_41_; + reg _zz_42_; + reg IBusSimplePlugin_injector_nextPcCalc_valids_0; + reg IBusSimplePlugin_injector_nextPcCalc_valids_1; + reg IBusSimplePlugin_injector_nextPcCalc_valids_2; + reg IBusSimplePlugin_injector_nextPcCalc_valids_3; + reg IBusSimplePlugin_injector_nextPcCalc_valids_4; + reg [31:0] IBusSimplePlugin_injector_formal_rawInDecode; + wire IBusSimplePlugin_cmd_valid; + wire IBusSimplePlugin_cmd_ready; + wire [31:0] IBusSimplePlugin_cmd_payload_pc; + wire IBusSimplePlugin_pending_inc; + wire IBusSimplePlugin_pending_dec; + reg [2:0] IBusSimplePlugin_pending_value; + wire [2:0] IBusSimplePlugin_pending_next; + wire IBusSimplePlugin_cmdFork_canEmit; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + reg [2:0] IBusSimplePlugin_rspJoin_rspBuffer_discardCounter; + wire IBusSimplePlugin_rspJoin_rspBuffer_flush; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_pc; + reg IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + wire IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + wire IBusSimplePlugin_rspJoin_join_valid; + wire IBusSimplePlugin_rspJoin_join_ready; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_pc; + wire IBusSimplePlugin_rspJoin_join_payload_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + wire IBusSimplePlugin_rspJoin_join_payload_isRvc; + wire IBusSimplePlugin_rspJoin_exceptionDetected; + wire _zz_43_; + wire _zz_44_; + reg execute_DBusSimplePlugin_skipCmd; + reg [31:0] _zz_45_; + reg [3:0] _zz_46_; + wire [3:0] execute_DBusSimplePlugin_formalMask; + reg [31:0] writeBack_DBusSimplePlugin_rspShifted; + wire _zz_47_; + reg [31:0] _zz_48_; + wire _zz_49_; + reg [31:0] _zz_50_; + reg [31:0] writeBack_DBusSimplePlugin_rspFormated; + wire [22:0] _zz_51_; + wire _zz_52_; + wire _zz_53_; + wire _zz_54_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_55_; + wire `AluCtrlEnum_defaultEncoding_type _zz_56_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_57_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_58_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_59_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_60_; + wire [4:0] decode_RegFilePlugin_regFileReadAddress1; + wire [4:0] decode_RegFilePlugin_regFileReadAddress2; + wire [31:0] decode_RegFilePlugin_rs1Data; + wire [31:0] decode_RegFilePlugin_rs2Data; + reg lastStageRegFileWrite_valid /* verilator public */ ; + wire [4:0] lastStageRegFileWrite_payload_address /* verilator public */ ; + wire [31:0] lastStageRegFileWrite_payload_data /* verilator public */ ; + reg _zz_61_; + reg [31:0] execute_IntAluPlugin_bitwise; + reg [31:0] _zz_62_; + reg [31:0] _zz_63_; + wire _zz_64_; + reg [19:0] _zz_65_; + wire _zz_66_; + reg [19:0] _zz_67_; + reg [31:0] _zz_68_; + reg [31:0] execute_SrcPlugin_addSub; + wire execute_SrcPlugin_less; + reg execute_LightShifterPlugin_isActive; + wire execute_LightShifterPlugin_isShift; + reg [4:0] execute_LightShifterPlugin_amplitudeReg; + wire [4:0] execute_LightShifterPlugin_amplitude; + wire [31:0] execute_LightShifterPlugin_shiftInput; + wire execute_LightShifterPlugin_done; + reg [31:0] _zz_69_; + reg _zz_70_; + reg _zz_71_; + reg _zz_72_; + reg [4:0] _zz_73_; + wire execute_BranchPlugin_eq; + wire [2:0] _zz_74_; + reg _zz_75_; + reg _zz_76_; + wire [31:0] execute_BranchPlugin_branch_src1; + wire _zz_77_; + reg [10:0] _zz_78_; + wire _zz_79_; + reg [19:0] _zz_80_; + wire _zz_81_; + reg [18:0] _zz_82_; + reg [31:0] _zz_83_; + wire [31:0] execute_BranchPlugin_branch_src2; + wire [31:0] execute_BranchPlugin_branchAdder; + reg [31:0] decode_to_execute_RS2; + reg decode_to_execute_REGFILE_WRITE_VALID; + reg execute_to_memory_REGFILE_WRITE_VALID; + reg memory_to_writeBack_REGFILE_WRITE_VALID; + reg decode_to_execute_BYPASSABLE_MEMORY_STAGE; + reg execute_to_memory_BYPASSABLE_MEMORY_STAGE; + reg [31:0] decode_to_execute_SRC2; + reg [1:0] execute_to_memory_MEMORY_ADDRESS_LOW; + reg [1:0] memory_to_writeBack_MEMORY_ADDRESS_LOW; + reg [31:0] decode_to_execute_SRC1; + reg decode_to_execute_SRC_USE_SUB_LESS; + reg execute_to_memory_BRANCH_DO; + reg [31:0] decode_to_execute_RS1; + reg [31:0] decode_to_execute_INSTRUCTION; + reg [31:0] execute_to_memory_INSTRUCTION; + reg [31:0] memory_to_writeBack_INSTRUCTION; + reg [31:0] decode_to_execute_PC; + reg [31:0] execute_to_memory_PC; + reg [31:0] memory_to_writeBack_PC; + reg `AluCtrlEnum_defaultEncoding_type decode_to_execute_ALU_CTRL; + reg decode_to_execute_MEMORY_STORE; + reg execute_to_memory_MEMORY_STORE; + reg memory_to_writeBack_MEMORY_STORE; + reg [31:0] decode_to_execute_FORMAL_PC_NEXT; + reg [31:0] execute_to_memory_FORMAL_PC_NEXT; + reg decode_to_execute_SRC_LESS_UNSIGNED; + reg decode_to_execute_MEMORY_ENABLE; + reg execute_to_memory_MEMORY_ENABLE; + reg memory_to_writeBack_MEMORY_ENABLE; + reg `ShiftCtrlEnum_defaultEncoding_type decode_to_execute_SHIFT_CTRL; + reg [31:0] execute_to_memory_REGFILE_WRITE_DATA; + reg [31:0] memory_to_writeBack_REGFILE_WRITE_DATA; + reg [31:0] execute_to_memory_BRANCH_CALC; + reg decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + reg `AluBitwiseCtrlEnum_defaultEncoding_type decode_to_execute_ALU_BITWISE_CTRL; + reg [31:0] memory_to_writeBack_MEMORY_READ_DATA; + reg `BranchCtrlEnum_defaultEncoding_type decode_to_execute_BRANCH_CTRL; + reg decode_to_execute_SRC2_FORCE_ZERO; + `ifndef SYNTHESIS + reg [31:0] decode_BRANCH_CTRL_string; + reg [31:0] _zz_1__string; + reg [31:0] _zz_2__string; + reg [31:0] _zz_3__string; + reg [39:0] decode_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_4__string; + reg [39:0] _zz_5__string; + reg [39:0] _zz_6__string; + reg [71:0] decode_SHIFT_CTRL_string; + reg [71:0] _zz_7__string; + reg [71:0] _zz_8__string; + reg [71:0] _zz_9__string; + reg [63:0] decode_ALU_CTRL_string; + reg [63:0] _zz_10__string; + reg [63:0] _zz_11__string; + reg [63:0] _zz_12__string; + reg [31:0] execute_BRANCH_CTRL_string; + reg [31:0] _zz_13__string; + reg [71:0] execute_SHIFT_CTRL_string; + reg [71:0] _zz_15__string; + reg [23:0] decode_SRC2_CTRL_string; + reg [23:0] _zz_18__string; + reg [95:0] decode_SRC1_CTRL_string; + reg [95:0] _zz_20__string; + reg [63:0] execute_ALU_CTRL_string; + reg [63:0] _zz_21__string; + reg [39:0] execute_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_22__string; + reg [71:0] _zz_26__string; + reg [23:0] _zz_27__string; + reg [39:0] _zz_28__string; + reg [31:0] _zz_29__string; + reg [63:0] _zz_30__string; + reg [95:0] _zz_31__string; + reg [95:0] _zz_55__string; + reg [63:0] _zz_56__string; + reg [31:0] _zz_57__string; + reg [39:0] _zz_58__string; + reg [23:0] _zz_59__string; + reg [71:0] _zz_60__string; + reg [63:0] decode_to_execute_ALU_CTRL_string; + reg [71:0] decode_to_execute_SHIFT_CTRL_string; + reg [39:0] decode_to_execute_ALU_BITWISE_CTRL_string; + reg [31:0] decode_to_execute_BRANCH_CTRL_string; + `endif + + reg [31:0] RegFilePlugin_regFile [0:31] /* verilator public */ ; + + assign _zz_88_ = ((execute_arbitration_isValid && execute_LightShifterPlugin_isShift) && (execute_SRC2[4 : 0] != 5'h0)); + assign _zz_89_ = (! execute_arbitration_isStuckByOthers); + assign _zz_90_ = (writeBack_arbitration_isValid && writeBack_REGFILE_WRITE_VALID); + assign _zz_91_ = (1'b1 || (! 1'b1)); + assign _zz_92_ = (memory_arbitration_isValid && memory_REGFILE_WRITE_VALID); + assign _zz_93_ = (1'b1 || (! memory_BYPASSABLE_MEMORY_STAGE)); + assign _zz_94_ = (execute_arbitration_isValid && execute_REGFILE_WRITE_VALID); + assign _zz_95_ = (1'b1 || (! execute_BYPASSABLE_EXECUTE_STAGE)); + assign _zz_96_ = writeBack_INSTRUCTION[13 : 12]; + assign _zz_97_ = _zz_51_[6 : 6]; + assign _zz_98_ = _zz_51_[20 : 20]; + assign _zz_99_ = _zz_51_[18 : 18]; + assign _zz_100_ = _zz_51_[19 : 19]; + assign _zz_101_ = _zz_51_[9 : 9]; + assign _zz_102_ = _zz_51_[4 : 4]; + assign _zz_103_ = _zz_51_[10 : 10]; + assign _zz_104_ = _zz_51_[17 : 17]; + assign _zz_105_ = _zz_51_[5 : 5]; + assign _zz_106_ = _zz_51_[11 : 11]; + assign _zz_107_ = {IBusSimplePlugin_fetchPc_inc,(2'b00)}; + assign _zz_108_ = {29'd0, _zz_107_}; + assign _zz_109_ = (IBusSimplePlugin_pending_value + _zz_111_); + assign _zz_110_ = IBusSimplePlugin_pending_inc; + assign _zz_111_ = {2'd0, _zz_110_}; + assign _zz_112_ = IBusSimplePlugin_pending_dec; + assign _zz_113_ = {2'd0, _zz_112_}; + assign _zz_114_ = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000))); + assign _zz_115_ = {2'd0, _zz_114_}; + assign _zz_116_ = IBusSimplePlugin_pending_dec; + assign _zz_117_ = {2'd0, _zz_116_}; + assign _zz_118_ = execute_SRC_LESS; + assign _zz_119_ = (3'b100); + assign _zz_120_ = decode_INSTRUCTION[19 : 15]; + assign _zz_121_ = decode_INSTRUCTION[31 : 20]; + assign _zz_122_ = {decode_INSTRUCTION[31 : 25],decode_INSTRUCTION[11 : 7]}; + assign _zz_123_ = ($signed(_zz_124_) + $signed(_zz_127_)); + assign _zz_124_ = ($signed(_zz_125_) + $signed(_zz_126_)); + assign _zz_125_ = execute_SRC1; + assign _zz_126_ = (execute_SRC_USE_SUB_LESS ? (~ execute_SRC2) : execute_SRC2); + assign _zz_127_ = (execute_SRC_USE_SUB_LESS ? _zz_128_ : _zz_129_); + assign _zz_128_ = 32'h00000001; + assign _zz_129_ = 32'h0; + assign _zz_130_ = (_zz_131_ >>> 1); + assign _zz_131_ = {((execute_SHIFT_CTRL == `ShiftCtrlEnum_defaultEncoding_SRA_1) && execute_LightShifterPlugin_shiftInput[31]),execute_LightShifterPlugin_shiftInput}; + assign _zz_132_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}; + assign _zz_133_ = execute_INSTRUCTION[31 : 20]; + assign _zz_134_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}; + assign _zz_135_ = 1'b1; + assign _zz_136_ = 1'b1; + assign _zz_137_ = 32'h00007014; + assign _zz_138_ = ((decode_INSTRUCTION & 32'h40003014) == 32'h40001010); + assign _zz_139_ = ((decode_INSTRUCTION & 32'h00007014) == 32'h00001010); + assign _zz_140_ = ((decode_INSTRUCTION & 32'h00000058) == 32'h0); + assign _zz_141_ = ((decode_INSTRUCTION & _zz_146_) == 32'h00000020); + assign _zz_142_ = (1'b0); + assign _zz_143_ = ({_zz_147_,_zz_148_} != (2'b00)); + assign _zz_144_ = ({_zz_149_,_zz_150_} != (3'b000)); + assign _zz_145_ = {(_zz_151_ != _zz_152_),{_zz_153_,{_zz_154_,_zz_155_}}}; + assign _zz_146_ = 32'h00000020; + assign _zz_147_ = ((decode_INSTRUCTION & 32'h00002010) == 32'h00002000); + assign _zz_148_ = ((decode_INSTRUCTION & 32'h00005000) == 32'h00001000); + assign _zz_149_ = ((decode_INSTRUCTION & _zz_156_) == 32'h00000040); + assign _zz_150_ = {(_zz_157_ == _zz_158_),(_zz_159_ == _zz_160_)}; + assign _zz_151_ = ((decode_INSTRUCTION & _zz_161_) == 32'h00000040); + assign _zz_152_ = (1'b0); + assign _zz_153_ = ({_zz_54_,_zz_162_} != (2'b00)); + assign _zz_154_ = ({_zz_163_,_zz_164_} != (2'b00)); + assign _zz_155_ = {(_zz_165_ != _zz_166_),{_zz_167_,{_zz_168_,_zz_169_}}}; + assign _zz_156_ = 32'h00000044; + assign _zz_157_ = (decode_INSTRUCTION & 32'h00002014); + assign _zz_158_ = 32'h00002010; + assign _zz_159_ = (decode_INSTRUCTION & 32'h40004034); + assign _zz_160_ = 32'h40000030; + assign _zz_161_ = 32'h00000040; + assign _zz_162_ = ((decode_INSTRUCTION & 32'h00000070) == 32'h00000020); + assign _zz_163_ = _zz_54_; + assign _zz_164_ = ((decode_INSTRUCTION & _zz_170_) == 32'h0); + assign _zz_165_ = ((decode_INSTRUCTION & _zz_171_) == 32'h00001000); + assign _zz_166_ = (1'b0); + assign _zz_167_ = ((_zz_172_ == _zz_173_) != (1'b0)); + assign _zz_168_ = ({_zz_174_,_zz_175_} != (4'b0000)); + assign _zz_169_ = {(_zz_176_ != _zz_177_),{_zz_178_,{_zz_179_,_zz_180_}}}; + assign _zz_170_ = 32'h00000020; + assign _zz_171_ = 32'h00001000; + assign _zz_172_ = (decode_INSTRUCTION & 32'h00003000); + assign _zz_173_ = 32'h00002000; + assign _zz_174_ = _zz_52_; + assign _zz_175_ = {_zz_53_,{_zz_181_,_zz_182_}}; + assign _zz_176_ = {(_zz_183_ == _zz_184_),(_zz_185_ == _zz_186_)}; + assign _zz_177_ = (2'b00); + assign _zz_178_ = (_zz_52_ != (1'b0)); + assign _zz_179_ = ({_zz_187_,_zz_188_} != (2'b00)); + assign _zz_180_ = {(_zz_189_ != _zz_190_),{_zz_191_,{_zz_192_,_zz_193_}}}; + assign _zz_181_ = ((decode_INSTRUCTION & 32'h0000000c) == 32'h00000004); + assign _zz_182_ = ((decode_INSTRUCTION & 32'h00000028) == 32'h0); + assign _zz_183_ = (decode_INSTRUCTION & 32'h00000004); + assign _zz_184_ = 32'h0; + assign _zz_185_ = (decode_INSTRUCTION & 32'h00000018); + assign _zz_186_ = 32'h0; + assign _zz_187_ = _zz_53_; + assign _zz_188_ = ((decode_INSTRUCTION & _zz_194_) == 32'h00000004); + assign _zz_189_ = ((decode_INSTRUCTION & _zz_195_) == 32'h00000040); + assign _zz_190_ = (1'b0); + assign _zz_191_ = (_zz_52_ != (1'b0)); + assign _zz_192_ = ({_zz_196_,_zz_197_} != (2'b00)); + assign _zz_193_ = {(_zz_198_ != _zz_199_),{_zz_200_,{_zz_201_,_zz_202_}}}; + assign _zz_194_ = 32'h0000001c; + assign _zz_195_ = 32'h00000048; + assign _zz_196_ = ((decode_INSTRUCTION & 32'h00000064) == 32'h00000024); + assign _zz_197_ = ((decode_INSTRUCTION & 32'h00003014) == 32'h00001010); + assign _zz_198_ = ((decode_INSTRUCTION & 32'h00000024) == 32'h00000020); + assign _zz_199_ = (1'b0); + assign _zz_200_ = ({(_zz_203_ == _zz_204_),(_zz_205_ == _zz_206_)} != (2'b00)); + assign _zz_201_ = ((_zz_207_ == _zz_208_) != (1'b0)); + assign _zz_202_ = {(_zz_209_ != (1'b0)),(_zz_210_ != (1'b0))}; + assign _zz_203_ = (decode_INSTRUCTION & 32'h00006004); + assign _zz_204_ = 32'h00006000; + assign _zz_205_ = (decode_INSTRUCTION & 32'h00005004); + assign _zz_206_ = 32'h00004000; + assign _zz_207_ = (decode_INSTRUCTION & 32'h00006004); + assign _zz_208_ = 32'h00002000; + assign _zz_209_ = ((decode_INSTRUCTION & 32'h00000014) == 32'h00000004); + assign _zz_210_ = ((decode_INSTRUCTION & 32'h00000044) == 32'h00000004); + always @ (posedge clk) begin + if(_zz_135_) begin + _zz_86_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress1]; + end + end + + always @ (posedge clk) begin + if(_zz_136_) begin + _zz_87_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress2]; + end + end + + always @ (posedge clk) begin + if(_zz_25_) begin + RegFilePlugin_regFile[lastStageRegFileWrite_payload_address] <= lastStageRegFileWrite_payload_data; + end + end + + StreamFifoLowLatency IBusSimplePlugin_rspJoin_rspBuffer_c ( + .io_push_valid (iBus_rsp_valid ), //i + .io_push_ready (IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready ), //o + .io_push_payload_error (iBus_rsp_payload_error ), //i + .io_push_payload_inst (iBus_rsp_payload_inst[31:0] ), //i + .io_pop_valid (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid ), //o + .io_pop_ready (_zz_84_ ), //i + .io_pop_payload_error (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error ), //o + .io_pop_payload_inst (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst[31:0] ), //o + .io_flush (_zz_85_ ), //i + .io_occupancy (IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy ), //o + .clk (clk ), //i + .reset (reset ) //i + ); + `ifndef SYNTHESIS + always @(*) begin + case(decode_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_BRANCH_CTRL_string = "JALR"; + default : decode_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_1_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_1__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_1__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_1__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_1__string = "JALR"; + default : _zz_1__string = "????"; + endcase + end + always @(*) begin + case(_zz_2_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_2__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_2__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_2__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_2__string = "JALR"; + default : _zz_2__string = "????"; + endcase + end + always @(*) begin + case(_zz_3_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_3__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_3__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_3__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_3__string = "JALR"; + default : _zz_3__string = "????"; + endcase + end + always @(*) begin + case(decode_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_4_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_4__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_4__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_4__string = "AND_1"; + default : _zz_4__string = "?????"; + endcase + end + always @(*) begin + case(_zz_5_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_5__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_5__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_5__string = "AND_1"; + default : _zz_5__string = "?????"; + endcase + end + always @(*) begin + case(_zz_6_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_6__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_6__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_6__string = "AND_1"; + default : _zz_6__string = "?????"; + endcase + end + always @(*) begin + case(decode_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_SHIFT_CTRL_string = "SRA_1 "; + default : decode_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_7_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_7__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_7__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_7__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_7__string = "SRA_1 "; + default : _zz_7__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_8_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_8__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_8__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_8__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_8__string = "SRA_1 "; + default : _zz_8__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_9_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_9__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_9__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_9__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_9__string = "SRA_1 "; + default : _zz_9__string = "?????????"; + endcase + end + always @(*) begin + case(decode_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_ALU_CTRL_string = "BITWISE "; + default : decode_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_10_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_10__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_10__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_10__string = "BITWISE "; + default : _zz_10__string = "????????"; + endcase + end + always @(*) begin + case(_zz_11_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_11__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_11__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_11__string = "BITWISE "; + default : _zz_11__string = "????????"; + endcase + end + always @(*) begin + case(_zz_12_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_12__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_12__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_12__string = "BITWISE "; + default : _zz_12__string = "????????"; + endcase + end + always @(*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : execute_BRANCH_CTRL_string = "JALR"; + default : execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_13_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_13__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_13__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_13__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_13__string = "JALR"; + default : _zz_13__string = "????"; + endcase + end + always @(*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : execute_SHIFT_CTRL_string = "SRA_1 "; + default : execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_15_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_15__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_15__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_15__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_15__string = "SRA_1 "; + default : _zz_15__string = "?????????"; + endcase + end + always @(*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_SRC2_CTRL_string = "PC "; + default : decode_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_18_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_18__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_18__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_18__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_18__string = "PC "; + default : _zz_18__string = "???"; + endcase + end + always @(*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_SRC1_CTRL_string = "URS1 "; + default : decode_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_20_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_20__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_20__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_20__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_20__string = "URS1 "; + default : _zz_20__string = "????????????"; + endcase + end + always @(*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : execute_ALU_CTRL_string = "BITWISE "; + default : execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_21_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_21__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_21__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_21__string = "BITWISE "; + default : _zz_21__string = "????????"; + endcase + end + always @(*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_22_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_22__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_22__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_22__string = "AND_1"; + default : _zz_22__string = "?????"; + endcase + end + always @(*) begin + case(_zz_26_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_26__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_26__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_26__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_26__string = "SRA_1 "; + default : _zz_26__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_27_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_27__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_27__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_27__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_27__string = "PC "; + default : _zz_27__string = "???"; + endcase + end + always @(*) begin + case(_zz_28_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_28__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_28__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_28__string = "AND_1"; + default : _zz_28__string = "?????"; + endcase + end + always @(*) begin + case(_zz_29_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_29__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_29__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_29__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_29__string = "JALR"; + default : _zz_29__string = "????"; + endcase + end + always @(*) begin + case(_zz_30_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_30__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_30__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_30__string = "BITWISE "; + default : _zz_30__string = "????????"; + endcase + end + always @(*) begin + case(_zz_31_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_31__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_31__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_31__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_31__string = "URS1 "; + default : _zz_31__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_55_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_55__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_55__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_55__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_55__string = "URS1 "; + default : _zz_55__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_56_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_56__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_56__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_56__string = "BITWISE "; + default : _zz_56__string = "????????"; + endcase + end + always @(*) begin + case(_zz_57_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_57__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_57__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_57__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_57__string = "JALR"; + default : _zz_57__string = "????"; + endcase + end + always @(*) begin + case(_zz_58_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_58__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_58__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_58__string = "AND_1"; + default : _zz_58__string = "?????"; + endcase + end + always @(*) begin + case(_zz_59_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_59__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_59__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_59__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_59__string = "PC "; + default : _zz_59__string = "???"; + endcase + end + always @(*) begin + case(_zz_60_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_60__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_60__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_60__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_60__string = "SRA_1 "; + default : _zz_60__string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_to_execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_to_execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_to_execute_ALU_CTRL_string = "BITWISE "; + default : decode_to_execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_to_execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_to_execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_to_execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_to_execute_SHIFT_CTRL_string = "SRA_1 "; + default : decode_to_execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_to_execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(decode_to_execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_to_execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_to_execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_to_execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_to_execute_BRANCH_CTRL_string = "JALR"; + default : decode_to_execute_BRANCH_CTRL_string = "????"; + endcase + end + `endif + + assign decode_SRC2_FORCE_ZERO = (decode_SRC_ADD_ZERO && (! decode_SRC_USE_SUB_LESS)); + assign decode_BRANCH_CTRL = _zz_1_; + assign _zz_2_ = _zz_3_; + assign memory_MEMORY_READ_DATA = dBus_rsp_data; + assign decode_ALU_BITWISE_CTRL = _zz_4_; + assign _zz_5_ = _zz_6_; + assign decode_BYPASSABLE_EXECUTE_STAGE = _zz_97_[0]; + assign execute_BRANCH_CALC = {execute_BranchPlugin_branchAdder[31 : 1],(1'b0)}; + assign writeBack_REGFILE_WRITE_DATA = memory_to_writeBack_REGFILE_WRITE_DATA; + assign execute_REGFILE_WRITE_DATA = _zz_62_; + assign decode_SHIFT_CTRL = _zz_7_; + assign _zz_8_ = _zz_9_; + assign decode_MEMORY_ENABLE = _zz_98_[0]; + assign decode_SRC_LESS_UNSIGNED = _zz_99_[0]; + assign memory_FORMAL_PC_NEXT = execute_to_memory_FORMAL_PC_NEXT; + assign execute_FORMAL_PC_NEXT = decode_to_execute_FORMAL_PC_NEXT; + assign decode_FORMAL_PC_NEXT = (decode_PC + 32'h00000004); + assign decode_MEMORY_STORE = _zz_100_[0]; + assign decode_ALU_CTRL = _zz_10_; + assign _zz_11_ = _zz_12_; + assign memory_PC = execute_to_memory_PC; + assign decode_RS1 = decode_RegFilePlugin_rs1Data; + assign execute_BRANCH_DO = _zz_76_; + assign decode_SRC1 = _zz_63_; + assign memory_MEMORY_ADDRESS_LOW = execute_to_memory_MEMORY_ADDRESS_LOW; + assign execute_MEMORY_ADDRESS_LOW = dBus_cmd_payload_address[1 : 0]; + assign decode_SRC2 = _zz_68_; + assign execute_BYPASSABLE_MEMORY_STAGE = decode_to_execute_BYPASSABLE_MEMORY_STAGE; + assign decode_BYPASSABLE_MEMORY_STAGE = _zz_101_[0]; + assign decode_RS2 = decode_RegFilePlugin_rs2Data; + assign memory_BRANCH_CALC = execute_to_memory_BRANCH_CALC; + assign memory_BRANCH_DO = execute_to_memory_BRANCH_DO; + assign execute_PC = decode_to_execute_PC; + assign execute_RS1 = decode_to_execute_RS1; + assign execute_BRANCH_CTRL = _zz_13_; + assign decode_RS2_USE = _zz_102_[0]; + assign decode_RS1_USE = _zz_103_[0]; + assign execute_REGFILE_WRITE_VALID = decode_to_execute_REGFILE_WRITE_VALID; + assign execute_BYPASSABLE_EXECUTE_STAGE = decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + assign memory_REGFILE_WRITE_VALID = execute_to_memory_REGFILE_WRITE_VALID; + assign memory_INSTRUCTION = execute_to_memory_INSTRUCTION; + assign memory_BYPASSABLE_MEMORY_STAGE = execute_to_memory_BYPASSABLE_MEMORY_STAGE; + assign writeBack_REGFILE_WRITE_VALID = memory_to_writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + _zz_14_ = execute_REGFILE_WRITE_DATA; + if(_zz_88_)begin + _zz_14_ = _zz_69_; + end + end + + assign memory_REGFILE_WRITE_DATA = execute_to_memory_REGFILE_WRITE_DATA; + assign execute_SHIFT_CTRL = _zz_15_; + assign execute_SRC_LESS_UNSIGNED = decode_to_execute_SRC_LESS_UNSIGNED; + assign execute_SRC2_FORCE_ZERO = decode_to_execute_SRC2_FORCE_ZERO; + assign execute_SRC_USE_SUB_LESS = decode_to_execute_SRC_USE_SUB_LESS; + assign _zz_16_ = decode_PC; + assign _zz_17_ = decode_RS2; + assign decode_SRC2_CTRL = _zz_18_; + assign _zz_19_ = decode_RS1; + assign decode_SRC1_CTRL = _zz_20_; + assign decode_SRC_USE_SUB_LESS = _zz_104_[0]; + assign decode_SRC_ADD_ZERO = _zz_105_[0]; + assign execute_SRC_ADD_SUB = execute_SrcPlugin_addSub; + assign execute_SRC_LESS = execute_SrcPlugin_less; + assign execute_ALU_CTRL = _zz_21_; + assign execute_SRC2 = decode_to_execute_SRC2; + assign execute_SRC1 = decode_to_execute_SRC1; + assign execute_ALU_BITWISE_CTRL = _zz_22_; + assign _zz_23_ = writeBack_INSTRUCTION; + assign _zz_24_ = writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + _zz_25_ = 1'b0; + if(lastStageRegFileWrite_valid)begin + _zz_25_ = 1'b1; + end + end + + assign decode_INSTRUCTION_ANTICIPATED = (decode_arbitration_isStuck ? decode_INSTRUCTION : IBusSimplePlugin_iBusRsp_output_payload_rsp_inst); + always @ (*) begin + decode_REGFILE_WRITE_VALID = _zz_106_[0]; + if((decode_INSTRUCTION[11 : 7] == 5'h0))begin + decode_REGFILE_WRITE_VALID = 1'b0; + end + end + + assign writeBack_MEMORY_STORE = memory_to_writeBack_MEMORY_STORE; + always @ (*) begin + _zz_32_ = writeBack_REGFILE_WRITE_DATA; + if((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE))begin + _zz_32_ = writeBack_DBusSimplePlugin_rspFormated; + end + end + + assign writeBack_MEMORY_ENABLE = memory_to_writeBack_MEMORY_ENABLE; + assign writeBack_MEMORY_ADDRESS_LOW = memory_to_writeBack_MEMORY_ADDRESS_LOW; + assign writeBack_MEMORY_READ_DATA = memory_to_writeBack_MEMORY_READ_DATA; + assign memory_MEMORY_STORE = execute_to_memory_MEMORY_STORE; + assign memory_MEMORY_ENABLE = execute_to_memory_MEMORY_ENABLE; + assign execute_SRC_ADD = execute_SrcPlugin_addSub; + assign execute_RS2 = decode_to_execute_RS2; + assign execute_INSTRUCTION = decode_to_execute_INSTRUCTION; + assign execute_MEMORY_STORE = decode_to_execute_MEMORY_STORE; + assign execute_MEMORY_ENABLE = decode_to_execute_MEMORY_ENABLE; + assign execute_ALIGNEMENT_FAULT = 1'b0; + assign decode_PC = IBusSimplePlugin_injector_decodeInput_payload_pc; + assign decode_INSTRUCTION = IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + assign writeBack_PC = memory_to_writeBack_PC; + assign writeBack_INSTRUCTION = memory_to_writeBack_INSTRUCTION; + assign decode_arbitration_haltItself = 1'b0; + always @ (*) begin + decode_arbitration_haltByOther = 1'b0; + if((decode_arbitration_isValid && (_zz_70_ || _zz_71_)))begin + decode_arbitration_haltByOther = 1'b1; + end + end + + always @ (*) begin + decode_arbitration_removeIt = 1'b0; + if(decode_arbitration_isFlushed)begin + decode_arbitration_removeIt = 1'b1; + end + end + + assign decode_arbitration_flushIt = 1'b0; + assign decode_arbitration_flushNext = 1'b0; + always @ (*) begin + execute_arbitration_haltItself = 1'b0; + if(((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! dBus_cmd_ready)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_44_)))begin + execute_arbitration_haltItself = 1'b1; + end + if(_zz_88_)begin + if(_zz_89_)begin + if(! execute_LightShifterPlugin_done) begin + execute_arbitration_haltItself = 1'b1; + end + end + end + end + + assign execute_arbitration_haltByOther = 1'b0; + always @ (*) begin + execute_arbitration_removeIt = 1'b0; + if(execute_arbitration_isFlushed)begin + execute_arbitration_removeIt = 1'b1; + end + end + + assign execute_arbitration_flushIt = 1'b0; + assign execute_arbitration_flushNext = 1'b0; + always @ (*) begin + memory_arbitration_haltItself = 1'b0; + if((((memory_arbitration_isValid && memory_MEMORY_ENABLE) && (! memory_MEMORY_STORE)) && ((! dBus_rsp_ready) || 1'b0)))begin + memory_arbitration_haltItself = 1'b1; + end + end + + assign memory_arbitration_haltByOther = 1'b0; + always @ (*) begin + memory_arbitration_removeIt = 1'b0; + if(memory_arbitration_isFlushed)begin + memory_arbitration_removeIt = 1'b1; + end + end + + assign memory_arbitration_flushIt = 1'b0; + always @ (*) begin + memory_arbitration_flushNext = 1'b0; + if(BranchPlugin_jumpInterface_valid)begin + memory_arbitration_flushNext = 1'b1; + end + end + + assign writeBack_arbitration_haltItself = 1'b0; + assign writeBack_arbitration_haltByOther = 1'b0; + always @ (*) begin + writeBack_arbitration_removeIt = 1'b0; + if(writeBack_arbitration_isFlushed)begin + writeBack_arbitration_removeIt = 1'b1; + end + end + + assign writeBack_arbitration_flushIt = 1'b0; + assign writeBack_arbitration_flushNext = 1'b0; + assign lastStageInstruction = writeBack_INSTRUCTION; + assign lastStagePc = writeBack_PC; + assign lastStageIsValid = writeBack_arbitration_isValid; + assign lastStageIsFiring = writeBack_arbitration_isFiring; + assign IBusSimplePlugin_fetcherHalt = 1'b0; + always @ (*) begin + IBusSimplePlugin_incomingInstruction = 1'b0; + if(IBusSimplePlugin_iBusRsp_stages_1_input_valid)begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + end + + assign IBusSimplePlugin_externalFlush = ({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,{execute_arbitration_flushNext,decode_arbitration_flushNext}}} != (4'b0000)); + assign IBusSimplePlugin_jump_pcLoad_valid = (BranchPlugin_jumpInterface_valid != (1'b0)); + assign IBusSimplePlugin_jump_pcLoad_payload = BranchPlugin_jumpInterface_payload; + always @ (*) begin + IBusSimplePlugin_fetchPc_correction = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_correction = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_corrected = (IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_correctionReg); + always @ (*) begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b0; + if(IBusSimplePlugin_iBusRsp_stages_1_input_ready)begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b1; + end + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_pc = (IBusSimplePlugin_fetchPc_pcReg + _zz_108_); + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_pc = IBusSimplePlugin_jump_pcLoad_payload; + end + IBusSimplePlugin_fetchPc_pc[0] = 1'b0; + IBusSimplePlugin_fetchPc_pc[1] = 1'b0; + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_flushed = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_flushed = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_output_valid = ((! IBusSimplePlugin_fetcherHalt) && IBusSimplePlugin_fetchPc_booted); + assign IBusSimplePlugin_fetchPc_output_payload = IBusSimplePlugin_fetchPc_pc; + assign IBusSimplePlugin_iBusRsp_redoFetch = 1'b0; + assign IBusSimplePlugin_iBusRsp_stages_0_input_valid = IBusSimplePlugin_fetchPc_output_valid; + assign IBusSimplePlugin_fetchPc_output_ready = IBusSimplePlugin_iBusRsp_stages_0_input_ready; + assign IBusSimplePlugin_iBusRsp_stages_0_input_payload = IBusSimplePlugin_fetchPc_output_payload; + always @ (*) begin + IBusSimplePlugin_iBusRsp_stages_0_halt = 1'b0; + if((IBusSimplePlugin_iBusRsp_stages_0_input_valid && ((! IBusSimplePlugin_cmdFork_canEmit) || (! IBusSimplePlugin_cmd_ready))))begin + IBusSimplePlugin_iBusRsp_stages_0_halt = 1'b1; + end + end + + assign _zz_33_ = (! IBusSimplePlugin_iBusRsp_stages_0_halt); + assign IBusSimplePlugin_iBusRsp_stages_0_input_ready = (IBusSimplePlugin_iBusRsp_stages_0_output_ready && _zz_33_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_valid = (IBusSimplePlugin_iBusRsp_stages_0_input_valid && _zz_33_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_payload = IBusSimplePlugin_iBusRsp_stages_0_input_payload; + assign IBusSimplePlugin_iBusRsp_stages_1_halt = 1'b0; + assign _zz_34_ = (! IBusSimplePlugin_iBusRsp_stages_1_halt); + assign IBusSimplePlugin_iBusRsp_stages_1_input_ready = (IBusSimplePlugin_iBusRsp_stages_1_output_ready && _zz_34_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_valid = (IBusSimplePlugin_iBusRsp_stages_1_input_valid && _zz_34_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_payload = IBusSimplePlugin_iBusRsp_stages_1_input_payload; + assign IBusSimplePlugin_iBusRsp_flush = (IBusSimplePlugin_externalFlush || IBusSimplePlugin_iBusRsp_redoFetch); + assign IBusSimplePlugin_iBusRsp_stages_0_output_ready = _zz_35_; + assign _zz_35_ = ((1'b0 && (! _zz_36_)) || IBusSimplePlugin_iBusRsp_stages_1_input_ready); + assign _zz_36_ = _zz_37_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_valid = _zz_36_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_payload = IBusSimplePlugin_fetchPc_pcReg; + always @ (*) begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b1; + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b0; + end + if((! IBusSimplePlugin_pcValids_0))begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b0; + end + end + + assign IBusSimplePlugin_iBusRsp_output_ready = ((1'b0 && (! IBusSimplePlugin_injector_decodeInput_valid)) || IBusSimplePlugin_injector_decodeInput_ready); + assign IBusSimplePlugin_injector_decodeInput_valid = _zz_38_; + assign IBusSimplePlugin_injector_decodeInput_payload_pc = _zz_39_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_error = _zz_40_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_inst = _zz_41_; + assign IBusSimplePlugin_injector_decodeInput_payload_isRvc = _zz_42_; + assign IBusSimplePlugin_pcValids_0 = IBusSimplePlugin_injector_nextPcCalc_valids_1; + assign IBusSimplePlugin_pcValids_1 = IBusSimplePlugin_injector_nextPcCalc_valids_2; + assign IBusSimplePlugin_pcValids_2 = IBusSimplePlugin_injector_nextPcCalc_valids_3; + assign IBusSimplePlugin_pcValids_3 = IBusSimplePlugin_injector_nextPcCalc_valids_4; + assign IBusSimplePlugin_injector_decodeInput_ready = (! decode_arbitration_isStuck); + assign decode_arbitration_isValid = IBusSimplePlugin_injector_decodeInput_valid; + assign iBus_cmd_valid = IBusSimplePlugin_cmd_valid; + assign IBusSimplePlugin_cmd_ready = iBus_cmd_ready; + assign iBus_cmd_payload_pc = IBusSimplePlugin_cmd_payload_pc; + assign IBusSimplePlugin_pending_next = (_zz_109_ - _zz_113_); + assign IBusSimplePlugin_cmdFork_canEmit = (IBusSimplePlugin_iBusRsp_stages_0_output_ready && (IBusSimplePlugin_pending_value != (3'b111))); + assign IBusSimplePlugin_cmd_valid = (IBusSimplePlugin_iBusRsp_stages_0_input_valid && IBusSimplePlugin_cmdFork_canEmit); + assign IBusSimplePlugin_pending_inc = (IBusSimplePlugin_cmd_valid && IBusSimplePlugin_cmd_ready); + assign IBusSimplePlugin_cmd_payload_pc = {IBusSimplePlugin_iBusRsp_stages_0_input_payload[31 : 2],(2'b00)}; + assign IBusSimplePlugin_rspJoin_rspBuffer_flush = ((IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000)) || IBusSimplePlugin_iBusRsp_flush); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_valid = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter == (3'b000))); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + assign _zz_84_ = (IBusSimplePlugin_rspJoin_rspBuffer_output_ready || IBusSimplePlugin_rspJoin_rspBuffer_flush); + assign IBusSimplePlugin_pending_dec = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && _zz_84_); + assign IBusSimplePlugin_rspJoin_fetchRsp_pc = IBusSimplePlugin_iBusRsp_stages_1_output_payload; + always @ (*) begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + if((! IBusSimplePlugin_rspJoin_rspBuffer_output_valid))begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = 1'b0; + end + end + + assign IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + assign IBusSimplePlugin_rspJoin_exceptionDetected = 1'b0; + assign IBusSimplePlugin_rspJoin_join_valid = (IBusSimplePlugin_iBusRsp_stages_1_output_valid && IBusSimplePlugin_rspJoin_rspBuffer_output_valid); + assign IBusSimplePlugin_rspJoin_join_payload_pc = IBusSimplePlugin_rspJoin_fetchRsp_pc; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_error = IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_inst = IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + assign IBusSimplePlugin_rspJoin_join_payload_isRvc = IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + assign IBusSimplePlugin_iBusRsp_stages_1_output_ready = (IBusSimplePlugin_iBusRsp_stages_1_output_valid ? (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready) : IBusSimplePlugin_rspJoin_join_ready); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_ready = (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready); + assign _zz_43_ = (! IBusSimplePlugin_rspJoin_exceptionDetected); + assign IBusSimplePlugin_rspJoin_join_ready = (IBusSimplePlugin_iBusRsp_output_ready && _zz_43_); + assign IBusSimplePlugin_iBusRsp_output_valid = (IBusSimplePlugin_rspJoin_join_valid && _zz_43_); + assign IBusSimplePlugin_iBusRsp_output_payload_pc = IBusSimplePlugin_rspJoin_join_payload_pc; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_error = IBusSimplePlugin_rspJoin_join_payload_rsp_error; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_inst = IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + assign IBusSimplePlugin_iBusRsp_output_payload_isRvc = IBusSimplePlugin_rspJoin_join_payload_isRvc; + assign _zz_44_ = 1'b0; + always @ (*) begin + execute_DBusSimplePlugin_skipCmd = 1'b0; + if(execute_ALIGNEMENT_FAULT)begin + execute_DBusSimplePlugin_skipCmd = 1'b1; + end + end + + assign dBus_cmd_valid = (((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! execute_arbitration_isStuckByOthers)) && (! execute_arbitration_isFlushed)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_44_)); + assign dBus_cmd_payload_wr = execute_MEMORY_STORE; + assign dBus_cmd_payload_size = execute_INSTRUCTION[13 : 12]; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_45_ = {{{execute_RS2[7 : 0],execute_RS2[7 : 0]},execute_RS2[7 : 0]},execute_RS2[7 : 0]}; + end + 2'b01 : begin + _zz_45_ = {execute_RS2[15 : 0],execute_RS2[15 : 0]}; + end + default : begin + _zz_45_ = execute_RS2[31 : 0]; + end + endcase + end + + assign dBus_cmd_payload_data = _zz_45_; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_46_ = (4'b0001); + end + 2'b01 : begin + _zz_46_ = (4'b0011); + end + default : begin + _zz_46_ = (4'b1111); + end + endcase + end + + assign execute_DBusSimplePlugin_formalMask = (_zz_46_ <<< dBus_cmd_payload_address[1 : 0]); + assign dBus_cmd_payload_address = execute_SRC_ADD; + always @ (*) begin + writeBack_DBusSimplePlugin_rspShifted = writeBack_MEMORY_READ_DATA; + case(writeBack_MEMORY_ADDRESS_LOW) + 2'b01 : begin + writeBack_DBusSimplePlugin_rspShifted[7 : 0] = writeBack_MEMORY_READ_DATA[15 : 8]; + end + 2'b10 : begin + writeBack_DBusSimplePlugin_rspShifted[15 : 0] = writeBack_MEMORY_READ_DATA[31 : 16]; + end + 2'b11 : begin + writeBack_DBusSimplePlugin_rspShifted[7 : 0] = writeBack_MEMORY_READ_DATA[31 : 24]; + end + default : begin + end + endcase + end + + assign _zz_47_ = (writeBack_DBusSimplePlugin_rspShifted[7] && (! writeBack_INSTRUCTION[14])); + always @ (*) begin + _zz_48_[31] = _zz_47_; + _zz_48_[30] = _zz_47_; + _zz_48_[29] = _zz_47_; + _zz_48_[28] = _zz_47_; + _zz_48_[27] = _zz_47_; + _zz_48_[26] = _zz_47_; + _zz_48_[25] = _zz_47_; + _zz_48_[24] = _zz_47_; + _zz_48_[23] = _zz_47_; + _zz_48_[22] = _zz_47_; + _zz_48_[21] = _zz_47_; + _zz_48_[20] = _zz_47_; + _zz_48_[19] = _zz_47_; + _zz_48_[18] = _zz_47_; + _zz_48_[17] = _zz_47_; + _zz_48_[16] = _zz_47_; + _zz_48_[15] = _zz_47_; + _zz_48_[14] = _zz_47_; + _zz_48_[13] = _zz_47_; + _zz_48_[12] = _zz_47_; + _zz_48_[11] = _zz_47_; + _zz_48_[10] = _zz_47_; + _zz_48_[9] = _zz_47_; + _zz_48_[8] = _zz_47_; + _zz_48_[7 : 0] = writeBack_DBusSimplePlugin_rspShifted[7 : 0]; + end + + assign _zz_49_ = (writeBack_DBusSimplePlugin_rspShifted[15] && (! writeBack_INSTRUCTION[14])); + always @ (*) begin + _zz_50_[31] = _zz_49_; + _zz_50_[30] = _zz_49_; + _zz_50_[29] = _zz_49_; + _zz_50_[28] = _zz_49_; + _zz_50_[27] = _zz_49_; + _zz_50_[26] = _zz_49_; + _zz_50_[25] = _zz_49_; + _zz_50_[24] = _zz_49_; + _zz_50_[23] = _zz_49_; + _zz_50_[22] = _zz_49_; + _zz_50_[21] = _zz_49_; + _zz_50_[20] = _zz_49_; + _zz_50_[19] = _zz_49_; + _zz_50_[18] = _zz_49_; + _zz_50_[17] = _zz_49_; + _zz_50_[16] = _zz_49_; + _zz_50_[15 : 0] = writeBack_DBusSimplePlugin_rspShifted[15 : 0]; + end + + always @ (*) begin + case(_zz_96_) + 2'b00 : begin + writeBack_DBusSimplePlugin_rspFormated = _zz_48_; + end + 2'b01 : begin + writeBack_DBusSimplePlugin_rspFormated = _zz_50_; + end + default : begin + writeBack_DBusSimplePlugin_rspFormated = writeBack_DBusSimplePlugin_rspShifted; + end + endcase + end + + assign _zz_52_ = ((decode_INSTRUCTION & 32'h00000010) == 32'h00000010); + assign _zz_53_ = ((decode_INSTRUCTION & 32'h00000048) == 32'h00000048); + assign _zz_54_ = ((decode_INSTRUCTION & 32'h00000004) == 32'h00000004); + assign _zz_51_ = {(((decode_INSTRUCTION & _zz_137_) == 32'h00005010) != (1'b0)),{({_zz_138_,_zz_139_} != (2'b00)),{(_zz_140_ != (1'b0)),{(_zz_141_ != _zz_142_),{_zz_143_,{_zz_144_,_zz_145_}}}}}}; + assign _zz_55_ = _zz_51_[1 : 0]; + assign _zz_31_ = _zz_55_; + assign _zz_56_ = _zz_51_[3 : 2]; + assign _zz_30_ = _zz_56_; + assign _zz_57_ = _zz_51_[8 : 7]; + assign _zz_29_ = _zz_57_; + assign _zz_58_ = _zz_51_[13 : 12]; + assign _zz_28_ = _zz_58_; + assign _zz_59_ = _zz_51_[15 : 14]; + assign _zz_27_ = _zz_59_; + assign _zz_60_ = _zz_51_[22 : 21]; + assign _zz_26_ = _zz_60_; + assign decode_RegFilePlugin_regFileReadAddress1 = decode_INSTRUCTION_ANTICIPATED[19 : 15]; + assign decode_RegFilePlugin_regFileReadAddress2 = decode_INSTRUCTION_ANTICIPATED[24 : 20]; + assign decode_RegFilePlugin_rs1Data = _zz_86_; + assign decode_RegFilePlugin_rs2Data = _zz_87_; + always @ (*) begin + lastStageRegFileWrite_valid = (_zz_24_ && writeBack_arbitration_isFiring); + if(_zz_61_)begin + lastStageRegFileWrite_valid = 1'b1; + end + end + + assign lastStageRegFileWrite_payload_address = _zz_23_[11 : 7]; + assign lastStageRegFileWrite_payload_data = _zz_32_; + always @ (*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 & execute_SRC2); + end + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 | execute_SRC2); + end + default : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 ^ execute_SRC2); + end + endcase + end + + always @ (*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_BITWISE : begin + _zz_62_ = execute_IntAluPlugin_bitwise; + end + `AluCtrlEnum_defaultEncoding_SLT_SLTU : begin + _zz_62_ = {31'd0, _zz_118_}; + end + default : begin + _zz_62_ = execute_SRC_ADD_SUB; + end + endcase + end + + always @ (*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : begin + _zz_63_ = _zz_19_; + end + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : begin + _zz_63_ = {29'd0, _zz_119_}; + end + `Src1CtrlEnum_defaultEncoding_IMU : begin + _zz_63_ = {decode_INSTRUCTION[31 : 12],12'h0}; + end + default : begin + _zz_63_ = {27'd0, _zz_120_}; + end + endcase + end + + assign _zz_64_ = _zz_121_[11]; + always @ (*) begin + _zz_65_[19] = _zz_64_; + _zz_65_[18] = _zz_64_; + _zz_65_[17] = _zz_64_; + _zz_65_[16] = _zz_64_; + _zz_65_[15] = _zz_64_; + _zz_65_[14] = _zz_64_; + _zz_65_[13] = _zz_64_; + _zz_65_[12] = _zz_64_; + _zz_65_[11] = _zz_64_; + _zz_65_[10] = _zz_64_; + _zz_65_[9] = _zz_64_; + _zz_65_[8] = _zz_64_; + _zz_65_[7] = _zz_64_; + _zz_65_[6] = _zz_64_; + _zz_65_[5] = _zz_64_; + _zz_65_[4] = _zz_64_; + _zz_65_[3] = _zz_64_; + _zz_65_[2] = _zz_64_; + _zz_65_[1] = _zz_64_; + _zz_65_[0] = _zz_64_; + end + + assign _zz_66_ = _zz_122_[11]; + always @ (*) begin + _zz_67_[19] = _zz_66_; + _zz_67_[18] = _zz_66_; + _zz_67_[17] = _zz_66_; + _zz_67_[16] = _zz_66_; + _zz_67_[15] = _zz_66_; + _zz_67_[14] = _zz_66_; + _zz_67_[13] = _zz_66_; + _zz_67_[12] = _zz_66_; + _zz_67_[11] = _zz_66_; + _zz_67_[10] = _zz_66_; + _zz_67_[9] = _zz_66_; + _zz_67_[8] = _zz_66_; + _zz_67_[7] = _zz_66_; + _zz_67_[6] = _zz_66_; + _zz_67_[5] = _zz_66_; + _zz_67_[4] = _zz_66_; + _zz_67_[3] = _zz_66_; + _zz_67_[2] = _zz_66_; + _zz_67_[1] = _zz_66_; + _zz_67_[0] = _zz_66_; + end + + always @ (*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : begin + _zz_68_ = _zz_17_; + end + `Src2CtrlEnum_defaultEncoding_IMI : begin + _zz_68_ = {_zz_65_,decode_INSTRUCTION[31 : 20]}; + end + `Src2CtrlEnum_defaultEncoding_IMS : begin + _zz_68_ = {_zz_67_,{decode_INSTRUCTION[31 : 25],decode_INSTRUCTION[11 : 7]}}; + end + default : begin + _zz_68_ = _zz_16_; + end + endcase + end + + always @ (*) begin + execute_SrcPlugin_addSub = _zz_123_; + if(execute_SRC2_FORCE_ZERO)begin + execute_SrcPlugin_addSub = execute_SRC1; + end + end + + assign execute_SrcPlugin_less = ((execute_SRC1[31] == execute_SRC2[31]) ? execute_SrcPlugin_addSub[31] : (execute_SRC_LESS_UNSIGNED ? execute_SRC2[31] : execute_SRC1[31])); + assign execute_LightShifterPlugin_isShift = (execute_SHIFT_CTRL != `ShiftCtrlEnum_defaultEncoding_DISABLE_1); + assign execute_LightShifterPlugin_amplitude = (execute_LightShifterPlugin_isActive ? execute_LightShifterPlugin_amplitudeReg : execute_SRC2[4 : 0]); + assign execute_LightShifterPlugin_shiftInput = (execute_LightShifterPlugin_isActive ? memory_REGFILE_WRITE_DATA : execute_SRC1); + assign execute_LightShifterPlugin_done = (execute_LightShifterPlugin_amplitude[4 : 1] == (4'b0000)); + always @ (*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_SLL_1 : begin + _zz_69_ = (execute_LightShifterPlugin_shiftInput <<< 1); + end + default : begin + _zz_69_ = _zz_130_; + end + endcase + end + + always @ (*) begin + _zz_70_ = 1'b0; + if(_zz_72_)begin + if((_zz_73_ == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + if(_zz_90_)begin + if(_zz_91_)begin + if((writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if(_zz_92_)begin + if(_zz_93_)begin + if((memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if(_zz_94_)begin + if(_zz_95_)begin + if((execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if((! decode_RS1_USE))begin + _zz_70_ = 1'b0; + end + end + + always @ (*) begin + _zz_71_ = 1'b0; + if(_zz_72_)begin + if((_zz_73_ == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + if(_zz_90_)begin + if(_zz_91_)begin + if((writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if(_zz_92_)begin + if(_zz_93_)begin + if((memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if(_zz_94_)begin + if(_zz_95_)begin + if((execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if((! decode_RS2_USE))begin + _zz_71_ = 1'b0; + end + end + + assign execute_BranchPlugin_eq = (execute_SRC1 == execute_SRC2); + assign _zz_74_ = execute_INSTRUCTION[14 : 12]; + always @ (*) begin + if((_zz_74_ == (3'b000))) begin + _zz_75_ = execute_BranchPlugin_eq; + end else if((_zz_74_ == (3'b001))) begin + _zz_75_ = (! execute_BranchPlugin_eq); + end else if((((_zz_74_ & (3'b101)) == (3'b101)))) begin + _zz_75_ = (! execute_SRC_LESS); + end else begin + _zz_75_ = execute_SRC_LESS; + end + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : begin + _zz_76_ = 1'b0; + end + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_76_ = 1'b1; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_76_ = 1'b1; + end + default : begin + _zz_76_ = _zz_75_; + end + endcase + end + + assign execute_BranchPlugin_branch_src1 = ((execute_BRANCH_CTRL == `BranchCtrlEnum_defaultEncoding_JALR) ? execute_RS1 : execute_PC); + assign _zz_77_ = _zz_132_[19]; + always @ (*) begin + _zz_78_[10] = _zz_77_; + _zz_78_[9] = _zz_77_; + _zz_78_[8] = _zz_77_; + _zz_78_[7] = _zz_77_; + _zz_78_[6] = _zz_77_; + _zz_78_[5] = _zz_77_; + _zz_78_[4] = _zz_77_; + _zz_78_[3] = _zz_77_; + _zz_78_[2] = _zz_77_; + _zz_78_[1] = _zz_77_; + _zz_78_[0] = _zz_77_; + end + + assign _zz_79_ = _zz_133_[11]; + always @ (*) begin + _zz_80_[19] = _zz_79_; + _zz_80_[18] = _zz_79_; + _zz_80_[17] = _zz_79_; + _zz_80_[16] = _zz_79_; + _zz_80_[15] = _zz_79_; + _zz_80_[14] = _zz_79_; + _zz_80_[13] = _zz_79_; + _zz_80_[12] = _zz_79_; + _zz_80_[11] = _zz_79_; + _zz_80_[10] = _zz_79_; + _zz_80_[9] = _zz_79_; + _zz_80_[8] = _zz_79_; + _zz_80_[7] = _zz_79_; + _zz_80_[6] = _zz_79_; + _zz_80_[5] = _zz_79_; + _zz_80_[4] = _zz_79_; + _zz_80_[3] = _zz_79_; + _zz_80_[2] = _zz_79_; + _zz_80_[1] = _zz_79_; + _zz_80_[0] = _zz_79_; + end + + assign _zz_81_ = _zz_134_[11]; + always @ (*) begin + _zz_82_[18] = _zz_81_; + _zz_82_[17] = _zz_81_; + _zz_82_[16] = _zz_81_; + _zz_82_[15] = _zz_81_; + _zz_82_[14] = _zz_81_; + _zz_82_[13] = _zz_81_; + _zz_82_[12] = _zz_81_; + _zz_82_[11] = _zz_81_; + _zz_82_[10] = _zz_81_; + _zz_82_[9] = _zz_81_; + _zz_82_[8] = _zz_81_; + _zz_82_[7] = _zz_81_; + _zz_82_[6] = _zz_81_; + _zz_82_[5] = _zz_81_; + _zz_82_[4] = _zz_81_; + _zz_82_[3] = _zz_81_; + _zz_82_[2] = _zz_81_; + _zz_82_[1] = _zz_81_; + _zz_82_[0] = _zz_81_; + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_83_ = {{_zz_78_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}},1'b0}; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_83_ = {_zz_80_,execute_INSTRUCTION[31 : 20]}; + end + default : begin + _zz_83_ = {{_zz_82_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}},1'b0}; + end + endcase + end + + assign execute_BranchPlugin_branch_src2 = _zz_83_; + assign execute_BranchPlugin_branchAdder = (execute_BranchPlugin_branch_src1 + execute_BranchPlugin_branch_src2); + assign BranchPlugin_jumpInterface_valid = ((memory_arbitration_isValid && memory_BRANCH_DO) && (! 1'b0)); + assign BranchPlugin_jumpInterface_payload = memory_BRANCH_CALC; + assign _zz_18_ = _zz_27_; + assign _zz_12_ = decode_ALU_CTRL; + assign _zz_10_ = _zz_30_; + assign _zz_21_ = decode_to_execute_ALU_CTRL; + assign _zz_20_ = _zz_31_; + assign _zz_9_ = decode_SHIFT_CTRL; + assign _zz_7_ = _zz_26_; + assign _zz_15_ = decode_to_execute_SHIFT_CTRL; + assign _zz_6_ = decode_ALU_BITWISE_CTRL; + assign _zz_4_ = _zz_28_; + assign _zz_22_ = decode_to_execute_ALU_BITWISE_CTRL; + assign _zz_3_ = decode_BRANCH_CTRL; + assign _zz_1_ = _zz_29_; + assign _zz_13_ = decode_to_execute_BRANCH_CTRL; + assign decode_arbitration_isFlushed = (({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,execute_arbitration_flushNext}} != (3'b000)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,{execute_arbitration_flushIt,decode_arbitration_flushIt}}} != (4'b0000))); + assign execute_arbitration_isFlushed = (({writeBack_arbitration_flushNext,memory_arbitration_flushNext} != (2'b00)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,execute_arbitration_flushIt}} != (3'b000))); + assign memory_arbitration_isFlushed = ((writeBack_arbitration_flushNext != (1'b0)) || ({writeBack_arbitration_flushIt,memory_arbitration_flushIt} != (2'b00))); + assign writeBack_arbitration_isFlushed = (1'b0 || (writeBack_arbitration_flushIt != (1'b0))); + assign decode_arbitration_isStuckByOthers = (decode_arbitration_haltByOther || (((1'b0 || execute_arbitration_isStuck) || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign decode_arbitration_isStuck = (decode_arbitration_haltItself || decode_arbitration_isStuckByOthers); + assign decode_arbitration_isMoving = ((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)); + assign decode_arbitration_isFiring = ((decode_arbitration_isValid && (! decode_arbitration_isStuck)) && (! decode_arbitration_removeIt)); + assign execute_arbitration_isStuckByOthers = (execute_arbitration_haltByOther || ((1'b0 || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign execute_arbitration_isStuck = (execute_arbitration_haltItself || execute_arbitration_isStuckByOthers); + assign execute_arbitration_isMoving = ((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)); + assign execute_arbitration_isFiring = ((execute_arbitration_isValid && (! execute_arbitration_isStuck)) && (! execute_arbitration_removeIt)); + assign memory_arbitration_isStuckByOthers = (memory_arbitration_haltByOther || (1'b0 || writeBack_arbitration_isStuck)); + assign memory_arbitration_isStuck = (memory_arbitration_haltItself || memory_arbitration_isStuckByOthers); + assign memory_arbitration_isMoving = ((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)); + assign memory_arbitration_isFiring = ((memory_arbitration_isValid && (! memory_arbitration_isStuck)) && (! memory_arbitration_removeIt)); + assign writeBack_arbitration_isStuckByOthers = (writeBack_arbitration_haltByOther || 1'b0); + assign writeBack_arbitration_isStuck = (writeBack_arbitration_haltItself || writeBack_arbitration_isStuckByOthers); + assign writeBack_arbitration_isMoving = ((! writeBack_arbitration_isStuck) && (! writeBack_arbitration_removeIt)); + assign writeBack_arbitration_isFiring = ((writeBack_arbitration_isValid && (! writeBack_arbitration_isStuck)) && (! writeBack_arbitration_removeIt)); + assign _zz_85_ = 1'b0; + always @ (posedge clk or posedge reset) begin + if (reset) begin + IBusSimplePlugin_fetchPc_pcReg <= 32'h0; + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + IBusSimplePlugin_fetchPc_booted <= 1'b0; + IBusSimplePlugin_fetchPc_inc <= 1'b0; + _zz_37_ <= 1'b0; + _zz_38_ <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + IBusSimplePlugin_pending_value <= (3'b000); + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (3'b000); + _zz_61_ <= 1'b1; + execute_LightShifterPlugin_isActive <= 1'b0; + _zz_72_ <= 1'b0; + execute_arbitration_isValid <= 1'b0; + memory_arbitration_isValid <= 1'b0; + writeBack_arbitration_isValid <= 1'b0; + memory_to_writeBack_REGFILE_WRITE_DATA <= 32'h0; + memory_to_writeBack_INSTRUCTION <= 32'h0; + end else begin + if(IBusSimplePlugin_fetchPc_correction)begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b1; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + end + IBusSimplePlugin_fetchPc_booted <= 1'b1; + if((IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_pcRegPropagate))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b1; + end + if(((! IBusSimplePlugin_fetchPc_output_valid) && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_booted && ((IBusSimplePlugin_fetchPc_output_ready || IBusSimplePlugin_fetchPc_correction) || IBusSimplePlugin_fetchPc_pcRegPropagate)))begin + IBusSimplePlugin_fetchPc_pcReg <= IBusSimplePlugin_fetchPc_pc; + end + if(IBusSimplePlugin_iBusRsp_flush)begin + _zz_37_ <= 1'b0; + end + if(_zz_35_)begin + _zz_37_ <= (IBusSimplePlugin_iBusRsp_stages_0_output_valid && (! 1'b0)); + end + if(decode_arbitration_removeIt)begin + _zz_38_ <= 1'b0; + end + if(IBusSimplePlugin_iBusRsp_output_ready)begin + _zz_38_ <= (IBusSimplePlugin_iBusRsp_output_valid && (! IBusSimplePlugin_externalFlush)); + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + end + if((! (! IBusSimplePlugin_iBusRsp_stages_1_input_ready)))begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b1; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if((! (! IBusSimplePlugin_injector_decodeInput_ready)))begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= IBusSimplePlugin_injector_nextPcCalc_valids_0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + end + if((! execute_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= IBusSimplePlugin_injector_nextPcCalc_valids_1; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + end + if((! memory_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= IBusSimplePlugin_injector_nextPcCalc_valids_2; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + end + if((! writeBack_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= IBusSimplePlugin_injector_nextPcCalc_valids_3; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + end + IBusSimplePlugin_pending_value <= IBusSimplePlugin_pending_next; + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter - _zz_115_); + if(IBusSimplePlugin_iBusRsp_flush)begin + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (IBusSimplePlugin_pending_value - _zz_117_); + end + _zz_61_ <= 1'b0; + if(_zz_88_)begin + if(_zz_89_)begin + execute_LightShifterPlugin_isActive <= 1'b1; + if(execute_LightShifterPlugin_done)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + end + end + if(execute_arbitration_removeIt)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + _zz_72_ <= (_zz_24_ && writeBack_arbitration_isFiring); + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_INSTRUCTION <= memory_INSTRUCTION; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_DATA <= memory_REGFILE_WRITE_DATA; + end + if(((! execute_arbitration_isStuck) || execute_arbitration_removeIt))begin + execute_arbitration_isValid <= 1'b0; + end + if(((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)))begin + execute_arbitration_isValid <= decode_arbitration_isValid; + end + if(((! memory_arbitration_isStuck) || memory_arbitration_removeIt))begin + memory_arbitration_isValid <= 1'b0; + end + if(((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)))begin + memory_arbitration_isValid <= execute_arbitration_isValid; + end + if(((! writeBack_arbitration_isStuck) || writeBack_arbitration_removeIt))begin + writeBack_arbitration_isValid <= 1'b0; + end + if(((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)))begin + writeBack_arbitration_isValid <= memory_arbitration_isValid; + end + end + end + + always @ (posedge clk) begin + if(IBusSimplePlugin_iBusRsp_output_ready)begin + _zz_39_ <= IBusSimplePlugin_iBusRsp_output_payload_pc; + _zz_40_ <= IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + _zz_41_ <= IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + _zz_42_ <= IBusSimplePlugin_iBusRsp_output_payload_isRvc; + end + if(IBusSimplePlugin_injector_decodeInput_ready)begin + IBusSimplePlugin_injector_formal_rawInDecode <= IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + end + `ifndef SYNTHESIS + `ifdef FORMAL + assert((! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) + `else + if(!(! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) begin + $display("FAILURE DBusSimplePlugin doesn't allow memory stage stall when read happend"); + $finish; + end + `endif + `endif + `ifndef SYNTHESIS + `ifdef FORMAL + assert((! (((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE) && (! writeBack_MEMORY_STORE)) && writeBack_arbitration_isStuck))) + `else + if(!(! (((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE) && (! writeBack_MEMORY_STORE)) && writeBack_arbitration_isStuck))) begin + $display("FAILURE DBusSimplePlugin doesn't allow writeback stage stall when read happend"); + $finish; + end + `endif + `endif + if(_zz_88_)begin + if(_zz_89_)begin + execute_LightShifterPlugin_amplitudeReg <= (execute_LightShifterPlugin_amplitude - 5'h01); + end + end + _zz_73_ <= _zz_23_[11 : 7]; + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS2 <= _zz_17_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_REGFILE_WRITE_VALID <= decode_REGFILE_WRITE_VALID; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_REGFILE_WRITE_VALID <= execute_REGFILE_WRITE_VALID; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_VALID <= memory_REGFILE_WRITE_VALID; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_MEMORY_STAGE <= decode_BYPASSABLE_MEMORY_STAGE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BYPASSABLE_MEMORY_STAGE <= execute_BYPASSABLE_MEMORY_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2 <= decode_SRC2; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ADDRESS_LOW <= execute_MEMORY_ADDRESS_LOW; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_ADDRESS_LOW <= memory_MEMORY_ADDRESS_LOW; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC1 <= decode_SRC1; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_USE_SUB_LESS <= decode_SRC_USE_SUB_LESS; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BRANCH_DO <= execute_BRANCH_DO; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS1 <= _zz_19_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_INSTRUCTION <= decode_INSTRUCTION; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_INSTRUCTION <= execute_INSTRUCTION; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_PC <= _zz_16_; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_PC <= execute_PC; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_PC <= memory_PC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_CTRL <= _zz_11_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_STORE <= decode_MEMORY_STORE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_STORE <= execute_MEMORY_STORE; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_STORE <= memory_MEMORY_STORE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_FORMAL_PC_NEXT <= decode_FORMAL_PC_NEXT; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_FORMAL_PC_NEXT <= execute_FORMAL_PC_NEXT; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_LESS_UNSIGNED <= decode_SRC_LESS_UNSIGNED; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_ENABLE <= decode_MEMORY_ENABLE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ENABLE <= execute_MEMORY_ENABLE; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_ENABLE <= memory_MEMORY_ENABLE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SHIFT_CTRL <= _zz_8_; + end + if(((! memory_arbitration_isStuck) && (! execute_arbitration_isStuckByOthers)))begin + execute_to_memory_REGFILE_WRITE_DATA <= _zz_14_; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BRANCH_CALC <= execute_BRANCH_CALC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_EXECUTE_STAGE <= decode_BYPASSABLE_EXECUTE_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_BITWISE_CTRL <= _zz_5_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_READ_DATA <= memory_MEMORY_READ_DATA; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BRANCH_CTRL <= _zz_2_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_FORCE_ZERO <= decode_SRC2_FORCE_ZERO; + end + end + + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_60000.v b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_60000.v new file mode 100644 index 0000000000000000000000000000000000000000..9c614eba3d288339b95055c753a394f2276752df --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_reset_60000.v @@ -0,0 +1,2361 @@ +// Generator : SpinalHDL v1.4.0 git head : ecb5a80b713566f417ea3ea061f9969e73770a7f +// Date : 06/07/2020, 18:21:32 +// Component : VexRiscv + + +`define BranchCtrlEnum_defaultEncoding_type [1:0] +`define BranchCtrlEnum_defaultEncoding_INC 2'b00 +`define BranchCtrlEnum_defaultEncoding_B 2'b01 +`define BranchCtrlEnum_defaultEncoding_JAL 2'b10 +`define BranchCtrlEnum_defaultEncoding_JALR 2'b11 + +`define AluBitwiseCtrlEnum_defaultEncoding_type [1:0] +`define AluBitwiseCtrlEnum_defaultEncoding_XOR_1 2'b00 +`define AluBitwiseCtrlEnum_defaultEncoding_OR_1 2'b01 +`define AluBitwiseCtrlEnum_defaultEncoding_AND_1 2'b10 + +`define ShiftCtrlEnum_defaultEncoding_type [1:0] +`define ShiftCtrlEnum_defaultEncoding_DISABLE_1 2'b00 +`define ShiftCtrlEnum_defaultEncoding_SLL_1 2'b01 +`define ShiftCtrlEnum_defaultEncoding_SRL_1 2'b10 +`define ShiftCtrlEnum_defaultEncoding_SRA_1 2'b11 + +`define AluCtrlEnum_defaultEncoding_type [1:0] +`define AluCtrlEnum_defaultEncoding_ADD_SUB 2'b00 +`define AluCtrlEnum_defaultEncoding_SLT_SLTU 2'b01 +`define AluCtrlEnum_defaultEncoding_BITWISE 2'b10 + +`define Src2CtrlEnum_defaultEncoding_type [1:0] +`define Src2CtrlEnum_defaultEncoding_RS 2'b00 +`define Src2CtrlEnum_defaultEncoding_IMI 2'b01 +`define Src2CtrlEnum_defaultEncoding_IMS 2'b10 +`define Src2CtrlEnum_defaultEncoding_PC 2'b11 + +`define Src1CtrlEnum_defaultEncoding_type [1:0] +`define Src1CtrlEnum_defaultEncoding_RS 2'b00 +`define Src1CtrlEnum_defaultEncoding_IMU 2'b01 +`define Src1CtrlEnum_defaultEncoding_PC_INCREMENT 2'b10 +`define Src1CtrlEnum_defaultEncoding_URS1 2'b11 + + +module StreamFifoLowLatency ( + input io_push_valid, + output io_push_ready, + input io_push_payload_error, + input [31:0] io_push_payload_inst, + output reg io_pop_valid, + input io_pop_ready, + output reg io_pop_payload_error, + output reg [31:0] io_pop_payload_inst, + input io_flush, + output [0:0] io_occupancy, + input clk, + input reset +); + wire _zz_4_; + wire [0:0] _zz_5_; + reg _zz_1_; + reg pushPtr_willIncrement; + reg pushPtr_willClear; + wire pushPtr_willOverflowIfInc; + wire pushPtr_willOverflow; + reg popPtr_willIncrement; + reg popPtr_willClear; + wire popPtr_willOverflowIfInc; + wire popPtr_willOverflow; + wire ptrMatch; + reg risingOccupancy; + wire empty; + wire full; + wire pushing; + wire popping; + wire [32:0] _zz_2_; + reg [32:0] _zz_3_; + + assign _zz_4_ = (! empty); + assign _zz_5_ = _zz_2_[0 : 0]; + always @ (*) begin + _zz_1_ = 1'b0; + if(pushing)begin + _zz_1_ = 1'b1; + end + end + + always @ (*) begin + pushPtr_willIncrement = 1'b0; + if(pushing)begin + pushPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + pushPtr_willClear = 1'b0; + if(io_flush)begin + pushPtr_willClear = 1'b1; + end + end + + assign pushPtr_willOverflowIfInc = 1'b1; + assign pushPtr_willOverflow = (pushPtr_willOverflowIfInc && pushPtr_willIncrement); + always @ (*) begin + popPtr_willIncrement = 1'b0; + if(popping)begin + popPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + popPtr_willClear = 1'b0; + if(io_flush)begin + popPtr_willClear = 1'b1; + end + end + + assign popPtr_willOverflowIfInc = 1'b1; + assign popPtr_willOverflow = (popPtr_willOverflowIfInc && popPtr_willIncrement); + assign ptrMatch = 1'b1; + assign empty = (ptrMatch && (! risingOccupancy)); + assign full = (ptrMatch && risingOccupancy); + assign pushing = (io_push_valid && io_push_ready); + assign popping = (io_pop_valid && io_pop_ready); + assign io_push_ready = (! full); + always @ (*) begin + if(_zz_4_)begin + io_pop_valid = 1'b1; + end else begin + io_pop_valid = io_push_valid; + end + end + + assign _zz_2_ = _zz_3_; + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_error = _zz_5_[0]; + end else begin + io_pop_payload_error = io_push_payload_error; + end + end + + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_inst = _zz_2_[32 : 1]; + end else begin + io_pop_payload_inst = io_push_payload_inst; + end + end + + assign io_occupancy = (risingOccupancy && ptrMatch); + always @ (posedge clk or posedge reset) begin + if (reset) begin + risingOccupancy <= 1'b0; + end else begin + if((pushing != popping))begin + risingOccupancy <= pushing; + end + if(io_flush)begin + risingOccupancy <= 1'b0; + end + end + end + + always @ (posedge clk) begin + if(_zz_1_)begin + _zz_3_ <= {io_push_payload_inst,io_push_payload_error}; + end + end + + +endmodule + +module VexRiscv ( + output iBus_cmd_valid, + input iBus_cmd_ready, + output [31:0] iBus_cmd_payload_pc, + input iBus_rsp_valid, + input iBus_rsp_payload_error, + input [31:0] iBus_rsp_payload_inst, + output dBus_cmd_valid, + input dBus_cmd_ready, + output dBus_cmd_payload_wr, + output [31:0] dBus_cmd_payload_address, + output [31:0] dBus_cmd_payload_data, + output [1:0] dBus_cmd_payload_size, + input dBus_rsp_ready, + input dBus_rsp_error, + input [31:0] dBus_rsp_data, + input clk, + input reset +); + wire _zz_84_; + wire _zz_85_; + reg [31:0] _zz_86_; + reg [31:0] _zz_87_; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + wire [0:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy; + wire _zz_88_; + wire _zz_89_; + wire _zz_90_; + wire _zz_91_; + wire _zz_92_; + wire _zz_93_; + wire _zz_94_; + wire _zz_95_; + wire [1:0] _zz_96_; + wire [0:0] _zz_97_; + wire [0:0] _zz_98_; + wire [0:0] _zz_99_; + wire [0:0] _zz_100_; + wire [0:0] _zz_101_; + wire [0:0] _zz_102_; + wire [0:0] _zz_103_; + wire [0:0] _zz_104_; + wire [0:0] _zz_105_; + wire [0:0] _zz_106_; + wire [2:0] _zz_107_; + wire [31:0] _zz_108_; + wire [2:0] _zz_109_; + wire [0:0] _zz_110_; + wire [2:0] _zz_111_; + wire [0:0] _zz_112_; + wire [2:0] _zz_113_; + wire [0:0] _zz_114_; + wire [2:0] _zz_115_; + wire [0:0] _zz_116_; + wire [2:0] _zz_117_; + wire [0:0] _zz_118_; + wire [2:0] _zz_119_; + wire [4:0] _zz_120_; + wire [11:0] _zz_121_; + wire [11:0] _zz_122_; + wire [31:0] _zz_123_; + wire [31:0] _zz_124_; + wire [31:0] _zz_125_; + wire [31:0] _zz_126_; + wire [31:0] _zz_127_; + wire [31:0] _zz_128_; + wire [31:0] _zz_129_; + wire [31:0] _zz_130_; + wire [32:0] _zz_131_; + wire [19:0] _zz_132_; + wire [11:0] _zz_133_; + wire [11:0] _zz_134_; + wire _zz_135_; + wire _zz_136_; + wire [31:0] _zz_137_; + wire _zz_138_; + wire _zz_139_; + wire _zz_140_; + wire [0:0] _zz_141_; + wire [0:0] _zz_142_; + wire _zz_143_; + wire [0:0] _zz_144_; + wire [16:0] _zz_145_; + wire [31:0] _zz_146_; + wire _zz_147_; + wire _zz_148_; + wire [0:0] _zz_149_; + wire [1:0] _zz_150_; + wire [0:0] _zz_151_; + wire [0:0] _zz_152_; + wire _zz_153_; + wire [0:0] _zz_154_; + wire [13:0] _zz_155_; + wire [31:0] _zz_156_; + wire [31:0] _zz_157_; + wire [31:0] _zz_158_; + wire [31:0] _zz_159_; + wire [31:0] _zz_160_; + wire [31:0] _zz_161_; + wire _zz_162_; + wire [0:0] _zz_163_; + wire [0:0] _zz_164_; + wire [0:0] _zz_165_; + wire [0:0] _zz_166_; + wire _zz_167_; + wire [0:0] _zz_168_; + wire [10:0] _zz_169_; + wire [31:0] _zz_170_; + wire [31:0] _zz_171_; + wire [31:0] _zz_172_; + wire [31:0] _zz_173_; + wire [0:0] _zz_174_; + wire [2:0] _zz_175_; + wire [1:0] _zz_176_; + wire [1:0] _zz_177_; + wire _zz_178_; + wire [0:0] _zz_179_; + wire [7:0] _zz_180_; + wire _zz_181_; + wire _zz_182_; + wire [31:0] _zz_183_; + wire [31:0] _zz_184_; + wire [31:0] _zz_185_; + wire [31:0] _zz_186_; + wire [0:0] _zz_187_; + wire [0:0] _zz_188_; + wire [0:0] _zz_189_; + wire [0:0] _zz_190_; + wire _zz_191_; + wire [0:0] _zz_192_; + wire [4:0] _zz_193_; + wire [31:0] _zz_194_; + wire [31:0] _zz_195_; + wire [0:0] _zz_196_; + wire [0:0] _zz_197_; + wire [0:0] _zz_198_; + wire [0:0] _zz_199_; + wire _zz_200_; + wire [0:0] _zz_201_; + wire [1:0] _zz_202_; + wire [31:0] _zz_203_; + wire [31:0] _zz_204_; + wire [31:0] _zz_205_; + wire [31:0] _zz_206_; + wire [31:0] _zz_207_; + wire [31:0] _zz_208_; + wire _zz_209_; + wire _zz_210_; + wire decode_SRC2_FORCE_ZERO; + wire `BranchCtrlEnum_defaultEncoding_type decode_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_1_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_2_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_3_; + wire [31:0] memory_MEMORY_READ_DATA; + wire `AluBitwiseCtrlEnum_defaultEncoding_type decode_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_4_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_5_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_6_; + wire decode_BYPASSABLE_EXECUTE_STAGE; + wire [31:0] execute_BRANCH_CALC; + wire [31:0] writeBack_REGFILE_WRITE_DATA; + wire [31:0] execute_REGFILE_WRITE_DATA; + wire `ShiftCtrlEnum_defaultEncoding_type decode_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_7_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_8_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_9_; + wire decode_MEMORY_ENABLE; + wire decode_SRC_LESS_UNSIGNED; + wire [31:0] memory_FORMAL_PC_NEXT; + wire [31:0] execute_FORMAL_PC_NEXT; + wire [31:0] decode_FORMAL_PC_NEXT; + wire decode_MEMORY_STORE; + wire `AluCtrlEnum_defaultEncoding_type decode_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_10_; + wire `AluCtrlEnum_defaultEncoding_type _zz_11_; + wire `AluCtrlEnum_defaultEncoding_type _zz_12_; + wire [31:0] memory_PC; + wire [31:0] decode_RS1; + wire execute_BRANCH_DO; + wire [31:0] decode_SRC1; + wire [1:0] memory_MEMORY_ADDRESS_LOW; + wire [1:0] execute_MEMORY_ADDRESS_LOW; + wire [31:0] decode_SRC2; + wire execute_BYPASSABLE_MEMORY_STAGE; + wire decode_BYPASSABLE_MEMORY_STAGE; + wire [31:0] decode_RS2; + wire [31:0] memory_BRANCH_CALC; + wire memory_BRANCH_DO; + wire [31:0] execute_PC; + wire [31:0] execute_RS1; + wire `BranchCtrlEnum_defaultEncoding_type execute_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_13_; + wire decode_RS2_USE; + wire decode_RS1_USE; + wire execute_REGFILE_WRITE_VALID; + wire execute_BYPASSABLE_EXECUTE_STAGE; + wire memory_REGFILE_WRITE_VALID; + wire [31:0] memory_INSTRUCTION; + wire memory_BYPASSABLE_MEMORY_STAGE; + wire writeBack_REGFILE_WRITE_VALID; + reg [31:0] _zz_14_; + wire [31:0] memory_REGFILE_WRITE_DATA; + wire `ShiftCtrlEnum_defaultEncoding_type execute_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_15_; + wire execute_SRC_LESS_UNSIGNED; + wire execute_SRC2_FORCE_ZERO; + wire execute_SRC_USE_SUB_LESS; + wire [31:0] _zz_16_; + wire [31:0] _zz_17_; + wire `Src2CtrlEnum_defaultEncoding_type decode_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_18_; + wire [31:0] _zz_19_; + wire `Src1CtrlEnum_defaultEncoding_type decode_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_20_; + wire decode_SRC_USE_SUB_LESS; + wire decode_SRC_ADD_ZERO; + wire [31:0] execute_SRC_ADD_SUB; + wire execute_SRC_LESS; + wire `AluCtrlEnum_defaultEncoding_type execute_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_21_; + wire [31:0] execute_SRC2; + wire [31:0] execute_SRC1; + wire `AluBitwiseCtrlEnum_defaultEncoding_type execute_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_22_; + wire [31:0] _zz_23_; + wire _zz_24_; + reg _zz_25_; + wire [31:0] decode_INSTRUCTION_ANTICIPATED; + reg decode_REGFILE_WRITE_VALID; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_26_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_27_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_28_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_29_; + wire `AluCtrlEnum_defaultEncoding_type _zz_30_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_31_; + wire writeBack_MEMORY_STORE; + reg [31:0] _zz_32_; + wire writeBack_MEMORY_ENABLE; + wire [1:0] writeBack_MEMORY_ADDRESS_LOW; + wire [31:0] writeBack_MEMORY_READ_DATA; + wire memory_MEMORY_STORE; + wire memory_MEMORY_ENABLE; + wire [31:0] execute_SRC_ADD; + wire [31:0] execute_RS2; + wire [31:0] execute_INSTRUCTION; + wire execute_MEMORY_STORE; + wire execute_MEMORY_ENABLE; + wire execute_ALIGNEMENT_FAULT; + wire [31:0] decode_PC; + wire [31:0] decode_INSTRUCTION; + wire [31:0] writeBack_PC; + wire [31:0] writeBack_INSTRUCTION; + wire decode_arbitration_haltItself; + reg decode_arbitration_haltByOther; + reg decode_arbitration_removeIt; + wire decode_arbitration_flushIt; + wire decode_arbitration_flushNext; + wire decode_arbitration_isValid; + wire decode_arbitration_isStuck; + wire decode_arbitration_isStuckByOthers; + wire decode_arbitration_isFlushed; + wire decode_arbitration_isMoving; + wire decode_arbitration_isFiring; + reg execute_arbitration_haltItself; + wire execute_arbitration_haltByOther; + reg execute_arbitration_removeIt; + wire execute_arbitration_flushIt; + wire execute_arbitration_flushNext; + reg execute_arbitration_isValid; + wire execute_arbitration_isStuck; + wire execute_arbitration_isStuckByOthers; + wire execute_arbitration_isFlushed; + wire execute_arbitration_isMoving; + wire execute_arbitration_isFiring; + reg memory_arbitration_haltItself; + wire memory_arbitration_haltByOther; + reg memory_arbitration_removeIt; + wire memory_arbitration_flushIt; + reg memory_arbitration_flushNext; + reg memory_arbitration_isValid; + wire memory_arbitration_isStuck; + wire memory_arbitration_isStuckByOthers; + wire memory_arbitration_isFlushed; + wire memory_arbitration_isMoving; + wire memory_arbitration_isFiring; + wire writeBack_arbitration_haltItself; + wire writeBack_arbitration_haltByOther; + reg writeBack_arbitration_removeIt; + wire writeBack_arbitration_flushIt; + wire writeBack_arbitration_flushNext; + reg writeBack_arbitration_isValid; + wire writeBack_arbitration_isStuck; + wire writeBack_arbitration_isStuckByOthers; + wire writeBack_arbitration_isFlushed; + wire writeBack_arbitration_isMoving; + wire writeBack_arbitration_isFiring; + wire [31:0] lastStageInstruction /* verilator public */ ; + wire [31:0] lastStagePc /* verilator public */ ; + wire lastStageIsValid /* verilator public */ ; + wire lastStageIsFiring /* verilator public */ ; + wire IBusSimplePlugin_fetcherHalt; + reg IBusSimplePlugin_incomingInstruction; + wire IBusSimplePlugin_pcValids_0; + wire IBusSimplePlugin_pcValids_1; + wire IBusSimplePlugin_pcValids_2; + wire IBusSimplePlugin_pcValids_3; + wire BranchPlugin_jumpInterface_valid; + wire [31:0] BranchPlugin_jumpInterface_payload; + wire IBusSimplePlugin_externalFlush; + wire IBusSimplePlugin_jump_pcLoad_valid; + wire [31:0] IBusSimplePlugin_jump_pcLoad_payload; + wire IBusSimplePlugin_fetchPc_output_valid; + wire IBusSimplePlugin_fetchPc_output_ready; + wire [31:0] IBusSimplePlugin_fetchPc_output_payload; + reg [31:0] IBusSimplePlugin_fetchPc_pcReg /* verilator public */ ; + reg IBusSimplePlugin_fetchPc_correction; + reg IBusSimplePlugin_fetchPc_correctionReg; + wire IBusSimplePlugin_fetchPc_corrected; + reg IBusSimplePlugin_fetchPc_pcRegPropagate; + reg IBusSimplePlugin_fetchPc_booted; + reg IBusSimplePlugin_fetchPc_inc; + reg [31:0] IBusSimplePlugin_fetchPc_pc; + reg IBusSimplePlugin_fetchPc_flushed; + wire IBusSimplePlugin_iBusRsp_redoFetch; + wire IBusSimplePlugin_iBusRsp_stages_0_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_0_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_output_payload; + reg IBusSimplePlugin_iBusRsp_stages_0_halt; + wire IBusSimplePlugin_iBusRsp_stages_1_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_1_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_output_payload; + wire IBusSimplePlugin_iBusRsp_stages_1_halt; + wire _zz_33_; + wire _zz_34_; + wire IBusSimplePlugin_iBusRsp_flush; + wire _zz_35_; + wire _zz_36_; + reg _zz_37_; + reg IBusSimplePlugin_iBusRsp_readyForError; + wire IBusSimplePlugin_iBusRsp_output_valid; + wire IBusSimplePlugin_iBusRsp_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_pc; + wire IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + wire IBusSimplePlugin_iBusRsp_output_payload_isRvc; + wire IBusSimplePlugin_injector_decodeInput_valid; + wire IBusSimplePlugin_injector_decodeInput_ready; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_pc; + wire IBusSimplePlugin_injector_decodeInput_payload_rsp_error; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + wire IBusSimplePlugin_injector_decodeInput_payload_isRvc; + reg _zz_38_; + reg [31:0] _zz_39_; + reg _zz_40_; + reg [31:0] _zz_41_; + reg _zz_42_; + reg IBusSimplePlugin_injector_nextPcCalc_valids_0; + reg IBusSimplePlugin_injector_nextPcCalc_valids_1; + reg IBusSimplePlugin_injector_nextPcCalc_valids_2; + reg IBusSimplePlugin_injector_nextPcCalc_valids_3; + reg IBusSimplePlugin_injector_nextPcCalc_valids_4; + reg [31:0] IBusSimplePlugin_injector_formal_rawInDecode; + wire IBusSimplePlugin_cmd_valid; + wire IBusSimplePlugin_cmd_ready; + wire [31:0] IBusSimplePlugin_cmd_payload_pc; + wire IBusSimplePlugin_pending_inc; + wire IBusSimplePlugin_pending_dec; + reg [2:0] IBusSimplePlugin_pending_value; + wire [2:0] IBusSimplePlugin_pending_next; + wire IBusSimplePlugin_cmdFork_canEmit; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + reg [2:0] IBusSimplePlugin_rspJoin_rspBuffer_discardCounter; + wire IBusSimplePlugin_rspJoin_rspBuffer_flush; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_pc; + reg IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + wire IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + wire IBusSimplePlugin_rspJoin_join_valid; + wire IBusSimplePlugin_rspJoin_join_ready; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_pc; + wire IBusSimplePlugin_rspJoin_join_payload_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + wire IBusSimplePlugin_rspJoin_join_payload_isRvc; + wire IBusSimplePlugin_rspJoin_exceptionDetected; + wire _zz_43_; + wire _zz_44_; + reg execute_DBusSimplePlugin_skipCmd; + reg [31:0] _zz_45_; + reg [3:0] _zz_46_; + wire [3:0] execute_DBusSimplePlugin_formalMask; + reg [31:0] writeBack_DBusSimplePlugin_rspShifted; + wire _zz_47_; + reg [31:0] _zz_48_; + wire _zz_49_; + reg [31:0] _zz_50_; + reg [31:0] writeBack_DBusSimplePlugin_rspFormated; + wire [22:0] _zz_51_; + wire _zz_52_; + wire _zz_53_; + wire _zz_54_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_55_; + wire `AluCtrlEnum_defaultEncoding_type _zz_56_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_57_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_58_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_59_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_60_; + wire [4:0] decode_RegFilePlugin_regFileReadAddress1; + wire [4:0] decode_RegFilePlugin_regFileReadAddress2; + wire [31:0] decode_RegFilePlugin_rs1Data; + wire [31:0] decode_RegFilePlugin_rs2Data; + reg lastStageRegFileWrite_valid /* verilator public */ ; + wire [4:0] lastStageRegFileWrite_payload_address /* verilator public */ ; + wire [31:0] lastStageRegFileWrite_payload_data /* verilator public */ ; + reg _zz_61_; + reg [31:0] execute_IntAluPlugin_bitwise; + reg [31:0] _zz_62_; + reg [31:0] _zz_63_; + wire _zz_64_; + reg [19:0] _zz_65_; + wire _zz_66_; + reg [19:0] _zz_67_; + reg [31:0] _zz_68_; + reg [31:0] execute_SrcPlugin_addSub; + wire execute_SrcPlugin_less; + reg execute_LightShifterPlugin_isActive; + wire execute_LightShifterPlugin_isShift; + reg [4:0] execute_LightShifterPlugin_amplitudeReg; + wire [4:0] execute_LightShifterPlugin_amplitude; + wire [31:0] execute_LightShifterPlugin_shiftInput; + wire execute_LightShifterPlugin_done; + reg [31:0] _zz_69_; + reg _zz_70_; + reg _zz_71_; + reg _zz_72_; + reg [4:0] _zz_73_; + wire execute_BranchPlugin_eq; + wire [2:0] _zz_74_; + reg _zz_75_; + reg _zz_76_; + wire [31:0] execute_BranchPlugin_branch_src1; + wire _zz_77_; + reg [10:0] _zz_78_; + wire _zz_79_; + reg [19:0] _zz_80_; + wire _zz_81_; + reg [18:0] _zz_82_; + reg [31:0] _zz_83_; + wire [31:0] execute_BranchPlugin_branch_src2; + wire [31:0] execute_BranchPlugin_branchAdder; + reg [31:0] decode_to_execute_RS2; + reg decode_to_execute_REGFILE_WRITE_VALID; + reg execute_to_memory_REGFILE_WRITE_VALID; + reg memory_to_writeBack_REGFILE_WRITE_VALID; + reg decode_to_execute_BYPASSABLE_MEMORY_STAGE; + reg execute_to_memory_BYPASSABLE_MEMORY_STAGE; + reg [31:0] decode_to_execute_SRC2; + reg [1:0] execute_to_memory_MEMORY_ADDRESS_LOW; + reg [1:0] memory_to_writeBack_MEMORY_ADDRESS_LOW; + reg [31:0] decode_to_execute_SRC1; + reg decode_to_execute_SRC_USE_SUB_LESS; + reg execute_to_memory_BRANCH_DO; + reg [31:0] decode_to_execute_RS1; + reg [31:0] decode_to_execute_INSTRUCTION; + reg [31:0] execute_to_memory_INSTRUCTION; + reg [31:0] memory_to_writeBack_INSTRUCTION; + reg [31:0] decode_to_execute_PC; + reg [31:0] execute_to_memory_PC; + reg [31:0] memory_to_writeBack_PC; + reg `AluCtrlEnum_defaultEncoding_type decode_to_execute_ALU_CTRL; + reg decode_to_execute_MEMORY_STORE; + reg execute_to_memory_MEMORY_STORE; + reg memory_to_writeBack_MEMORY_STORE; + reg [31:0] decode_to_execute_FORMAL_PC_NEXT; + reg [31:0] execute_to_memory_FORMAL_PC_NEXT; + reg decode_to_execute_SRC_LESS_UNSIGNED; + reg decode_to_execute_MEMORY_ENABLE; + reg execute_to_memory_MEMORY_ENABLE; + reg memory_to_writeBack_MEMORY_ENABLE; + reg `ShiftCtrlEnum_defaultEncoding_type decode_to_execute_SHIFT_CTRL; + reg [31:0] execute_to_memory_REGFILE_WRITE_DATA; + reg [31:0] memory_to_writeBack_REGFILE_WRITE_DATA; + reg [31:0] execute_to_memory_BRANCH_CALC; + reg decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + reg `AluBitwiseCtrlEnum_defaultEncoding_type decode_to_execute_ALU_BITWISE_CTRL; + reg [31:0] memory_to_writeBack_MEMORY_READ_DATA; + reg `BranchCtrlEnum_defaultEncoding_type decode_to_execute_BRANCH_CTRL; + reg decode_to_execute_SRC2_FORCE_ZERO; + `ifndef SYNTHESIS + reg [31:0] decode_BRANCH_CTRL_string; + reg [31:0] _zz_1__string; + reg [31:0] _zz_2__string; + reg [31:0] _zz_3__string; + reg [39:0] decode_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_4__string; + reg [39:0] _zz_5__string; + reg [39:0] _zz_6__string; + reg [71:0] decode_SHIFT_CTRL_string; + reg [71:0] _zz_7__string; + reg [71:0] _zz_8__string; + reg [71:0] _zz_9__string; + reg [63:0] decode_ALU_CTRL_string; + reg [63:0] _zz_10__string; + reg [63:0] _zz_11__string; + reg [63:0] _zz_12__string; + reg [31:0] execute_BRANCH_CTRL_string; + reg [31:0] _zz_13__string; + reg [71:0] execute_SHIFT_CTRL_string; + reg [71:0] _zz_15__string; + reg [23:0] decode_SRC2_CTRL_string; + reg [23:0] _zz_18__string; + reg [95:0] decode_SRC1_CTRL_string; + reg [95:0] _zz_20__string; + reg [63:0] execute_ALU_CTRL_string; + reg [63:0] _zz_21__string; + reg [39:0] execute_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_22__string; + reg [71:0] _zz_26__string; + reg [23:0] _zz_27__string; + reg [39:0] _zz_28__string; + reg [31:0] _zz_29__string; + reg [63:0] _zz_30__string; + reg [95:0] _zz_31__string; + reg [95:0] _zz_55__string; + reg [63:0] _zz_56__string; + reg [31:0] _zz_57__string; + reg [39:0] _zz_58__string; + reg [23:0] _zz_59__string; + reg [71:0] _zz_60__string; + reg [63:0] decode_to_execute_ALU_CTRL_string; + reg [71:0] decode_to_execute_SHIFT_CTRL_string; + reg [39:0] decode_to_execute_ALU_BITWISE_CTRL_string; + reg [31:0] decode_to_execute_BRANCH_CTRL_string; + `endif + + reg [31:0] RegFilePlugin_regFile [0:31] /* verilator public */ ; + + assign _zz_88_ = ((execute_arbitration_isValid && execute_LightShifterPlugin_isShift) && (execute_SRC2[4 : 0] != 5'h0)); + assign _zz_89_ = (! execute_arbitration_isStuckByOthers); + assign _zz_90_ = (writeBack_arbitration_isValid && writeBack_REGFILE_WRITE_VALID); + assign _zz_91_ = (1'b1 || (! 1'b1)); + assign _zz_92_ = (memory_arbitration_isValid && memory_REGFILE_WRITE_VALID); + assign _zz_93_ = (1'b1 || (! memory_BYPASSABLE_MEMORY_STAGE)); + assign _zz_94_ = (execute_arbitration_isValid && execute_REGFILE_WRITE_VALID); + assign _zz_95_ = (1'b1 || (! execute_BYPASSABLE_EXECUTE_STAGE)); + assign _zz_96_ = writeBack_INSTRUCTION[13 : 12]; + assign _zz_97_ = _zz_51_[6 : 6]; + assign _zz_98_ = _zz_51_[20 : 20]; + assign _zz_99_ = _zz_51_[18 : 18]; + assign _zz_100_ = _zz_51_[19 : 19]; + assign _zz_101_ = _zz_51_[9 : 9]; + assign _zz_102_ = _zz_51_[4 : 4]; + assign _zz_103_ = _zz_51_[10 : 10]; + assign _zz_104_ = _zz_51_[17 : 17]; + assign _zz_105_ = _zz_51_[5 : 5]; + assign _zz_106_ = _zz_51_[11 : 11]; + assign _zz_107_ = {IBusSimplePlugin_fetchPc_inc,(2'b00)}; + assign _zz_108_ = {29'd0, _zz_107_}; + assign _zz_109_ = (IBusSimplePlugin_pending_value + _zz_111_); + assign _zz_110_ = IBusSimplePlugin_pending_inc; + assign _zz_111_ = {2'd0, _zz_110_}; + assign _zz_112_ = IBusSimplePlugin_pending_dec; + assign _zz_113_ = {2'd0, _zz_112_}; + assign _zz_114_ = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000))); + assign _zz_115_ = {2'd0, _zz_114_}; + assign _zz_116_ = IBusSimplePlugin_pending_dec; + assign _zz_117_ = {2'd0, _zz_116_}; + assign _zz_118_ = execute_SRC_LESS; + assign _zz_119_ = (3'b100); + assign _zz_120_ = decode_INSTRUCTION[19 : 15]; + assign _zz_121_ = decode_INSTRUCTION[31 : 20]; + assign _zz_122_ = {decode_INSTRUCTION[31 : 25],decode_INSTRUCTION[11 : 7]}; + assign _zz_123_ = ($signed(_zz_124_) + $signed(_zz_127_)); + assign _zz_124_ = ($signed(_zz_125_) + $signed(_zz_126_)); + assign _zz_125_ = execute_SRC1; + assign _zz_126_ = (execute_SRC_USE_SUB_LESS ? (~ execute_SRC2) : execute_SRC2); + assign _zz_127_ = (execute_SRC_USE_SUB_LESS ? _zz_128_ : _zz_129_); + assign _zz_128_ = 32'h00000001; + assign _zz_129_ = 32'h0; + assign _zz_130_ = (_zz_131_ >>> 1); + assign _zz_131_ = {((execute_SHIFT_CTRL == `ShiftCtrlEnum_defaultEncoding_SRA_1) && execute_LightShifterPlugin_shiftInput[31]),execute_LightShifterPlugin_shiftInput}; + assign _zz_132_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}; + assign _zz_133_ = execute_INSTRUCTION[31 : 20]; + assign _zz_134_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}; + assign _zz_135_ = 1'b1; + assign _zz_136_ = 1'b1; + assign _zz_137_ = 32'h00007014; + assign _zz_138_ = ((decode_INSTRUCTION & 32'h40003014) == 32'h40001010); + assign _zz_139_ = ((decode_INSTRUCTION & 32'h00007014) == 32'h00001010); + assign _zz_140_ = ((decode_INSTRUCTION & 32'h00000058) == 32'h0); + assign _zz_141_ = ((decode_INSTRUCTION & _zz_146_) == 32'h00000020); + assign _zz_142_ = (1'b0); + assign _zz_143_ = ({_zz_147_,_zz_148_} != (2'b00)); + assign _zz_144_ = ({_zz_149_,_zz_150_} != (3'b000)); + assign _zz_145_ = {(_zz_151_ != _zz_152_),{_zz_153_,{_zz_154_,_zz_155_}}}; + assign _zz_146_ = 32'h00000020; + assign _zz_147_ = ((decode_INSTRUCTION & 32'h00002010) == 32'h00002000); + assign _zz_148_ = ((decode_INSTRUCTION & 32'h00005000) == 32'h00001000); + assign _zz_149_ = ((decode_INSTRUCTION & _zz_156_) == 32'h00000040); + assign _zz_150_ = {(_zz_157_ == _zz_158_),(_zz_159_ == _zz_160_)}; + assign _zz_151_ = ((decode_INSTRUCTION & _zz_161_) == 32'h00000040); + assign _zz_152_ = (1'b0); + assign _zz_153_ = ({_zz_54_,_zz_162_} != (2'b00)); + assign _zz_154_ = ({_zz_163_,_zz_164_} != (2'b00)); + assign _zz_155_ = {(_zz_165_ != _zz_166_),{_zz_167_,{_zz_168_,_zz_169_}}}; + assign _zz_156_ = 32'h00000044; + assign _zz_157_ = (decode_INSTRUCTION & 32'h00002014); + assign _zz_158_ = 32'h00002010; + assign _zz_159_ = (decode_INSTRUCTION & 32'h40004034); + assign _zz_160_ = 32'h40000030; + assign _zz_161_ = 32'h00000040; + assign _zz_162_ = ((decode_INSTRUCTION & 32'h00000070) == 32'h00000020); + assign _zz_163_ = _zz_54_; + assign _zz_164_ = ((decode_INSTRUCTION & _zz_170_) == 32'h0); + assign _zz_165_ = ((decode_INSTRUCTION & _zz_171_) == 32'h00001000); + assign _zz_166_ = (1'b0); + assign _zz_167_ = ((_zz_172_ == _zz_173_) != (1'b0)); + assign _zz_168_ = ({_zz_174_,_zz_175_} != (4'b0000)); + assign _zz_169_ = {(_zz_176_ != _zz_177_),{_zz_178_,{_zz_179_,_zz_180_}}}; + assign _zz_170_ = 32'h00000020; + assign _zz_171_ = 32'h00001000; + assign _zz_172_ = (decode_INSTRUCTION & 32'h00003000); + assign _zz_173_ = 32'h00002000; + assign _zz_174_ = _zz_52_; + assign _zz_175_ = {_zz_53_,{_zz_181_,_zz_182_}}; + assign _zz_176_ = {(_zz_183_ == _zz_184_),(_zz_185_ == _zz_186_)}; + assign _zz_177_ = (2'b00); + assign _zz_178_ = (_zz_52_ != (1'b0)); + assign _zz_179_ = ({_zz_187_,_zz_188_} != (2'b00)); + assign _zz_180_ = {(_zz_189_ != _zz_190_),{_zz_191_,{_zz_192_,_zz_193_}}}; + assign _zz_181_ = ((decode_INSTRUCTION & 32'h0000000c) == 32'h00000004); + assign _zz_182_ = ((decode_INSTRUCTION & 32'h00000028) == 32'h0); + assign _zz_183_ = (decode_INSTRUCTION & 32'h00000004); + assign _zz_184_ = 32'h0; + assign _zz_185_ = (decode_INSTRUCTION & 32'h00000018); + assign _zz_186_ = 32'h0; + assign _zz_187_ = _zz_53_; + assign _zz_188_ = ((decode_INSTRUCTION & _zz_194_) == 32'h00000004); + assign _zz_189_ = ((decode_INSTRUCTION & _zz_195_) == 32'h00000040); + assign _zz_190_ = (1'b0); + assign _zz_191_ = (_zz_52_ != (1'b0)); + assign _zz_192_ = ({_zz_196_,_zz_197_} != (2'b00)); + assign _zz_193_ = {(_zz_198_ != _zz_199_),{_zz_200_,{_zz_201_,_zz_202_}}}; + assign _zz_194_ = 32'h0000001c; + assign _zz_195_ = 32'h00000048; + assign _zz_196_ = ((decode_INSTRUCTION & 32'h00000064) == 32'h00000024); + assign _zz_197_ = ((decode_INSTRUCTION & 32'h00003014) == 32'h00001010); + assign _zz_198_ = ((decode_INSTRUCTION & 32'h00000024) == 32'h00000020); + assign _zz_199_ = (1'b0); + assign _zz_200_ = ({(_zz_203_ == _zz_204_),(_zz_205_ == _zz_206_)} != (2'b00)); + assign _zz_201_ = ((_zz_207_ == _zz_208_) != (1'b0)); + assign _zz_202_ = {(_zz_209_ != (1'b0)),(_zz_210_ != (1'b0))}; + assign _zz_203_ = (decode_INSTRUCTION & 32'h00006004); + assign _zz_204_ = 32'h00006000; + assign _zz_205_ = (decode_INSTRUCTION & 32'h00005004); + assign _zz_206_ = 32'h00004000; + assign _zz_207_ = (decode_INSTRUCTION & 32'h00006004); + assign _zz_208_ = 32'h00002000; + assign _zz_209_ = ((decode_INSTRUCTION & 32'h00000014) == 32'h00000004); + assign _zz_210_ = ((decode_INSTRUCTION & 32'h00000044) == 32'h00000004); + always @ (posedge clk) begin + if(_zz_135_) begin + _zz_86_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress1]; + end + end + + always @ (posedge clk) begin + if(_zz_136_) begin + _zz_87_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress2]; + end + end + + always @ (posedge clk) begin + if(_zz_25_) begin + RegFilePlugin_regFile[lastStageRegFileWrite_payload_address] <= lastStageRegFileWrite_payload_data; + end + end + + StreamFifoLowLatency IBusSimplePlugin_rspJoin_rspBuffer_c ( + .io_push_valid (iBus_rsp_valid ), //i + .io_push_ready (IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready ), //o + .io_push_payload_error (iBus_rsp_payload_error ), //i + .io_push_payload_inst (iBus_rsp_payload_inst[31:0] ), //i + .io_pop_valid (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid ), //o + .io_pop_ready (_zz_84_ ), //i + .io_pop_payload_error (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error ), //o + .io_pop_payload_inst (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst[31:0] ), //o + .io_flush (_zz_85_ ), //i + .io_occupancy (IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy ), //o + .clk (clk ), //i + .reset (reset ) //i + ); + `ifndef SYNTHESIS + always @(*) begin + case(decode_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_BRANCH_CTRL_string = "JALR"; + default : decode_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_1_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_1__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_1__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_1__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_1__string = "JALR"; + default : _zz_1__string = "????"; + endcase + end + always @(*) begin + case(_zz_2_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_2__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_2__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_2__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_2__string = "JALR"; + default : _zz_2__string = "????"; + endcase + end + always @(*) begin + case(_zz_3_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_3__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_3__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_3__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_3__string = "JALR"; + default : _zz_3__string = "????"; + endcase + end + always @(*) begin + case(decode_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_4_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_4__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_4__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_4__string = "AND_1"; + default : _zz_4__string = "?????"; + endcase + end + always @(*) begin + case(_zz_5_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_5__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_5__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_5__string = "AND_1"; + default : _zz_5__string = "?????"; + endcase + end + always @(*) begin + case(_zz_6_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_6__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_6__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_6__string = "AND_1"; + default : _zz_6__string = "?????"; + endcase + end + always @(*) begin + case(decode_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_SHIFT_CTRL_string = "SRA_1 "; + default : decode_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_7_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_7__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_7__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_7__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_7__string = "SRA_1 "; + default : _zz_7__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_8_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_8__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_8__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_8__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_8__string = "SRA_1 "; + default : _zz_8__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_9_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_9__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_9__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_9__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_9__string = "SRA_1 "; + default : _zz_9__string = "?????????"; + endcase + end + always @(*) begin + case(decode_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_ALU_CTRL_string = "BITWISE "; + default : decode_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_10_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_10__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_10__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_10__string = "BITWISE "; + default : _zz_10__string = "????????"; + endcase + end + always @(*) begin + case(_zz_11_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_11__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_11__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_11__string = "BITWISE "; + default : _zz_11__string = "????????"; + endcase + end + always @(*) begin + case(_zz_12_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_12__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_12__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_12__string = "BITWISE "; + default : _zz_12__string = "????????"; + endcase + end + always @(*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : execute_BRANCH_CTRL_string = "JALR"; + default : execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_13_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_13__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_13__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_13__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_13__string = "JALR"; + default : _zz_13__string = "????"; + endcase + end + always @(*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : execute_SHIFT_CTRL_string = "SRA_1 "; + default : execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_15_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_15__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_15__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_15__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_15__string = "SRA_1 "; + default : _zz_15__string = "?????????"; + endcase + end + always @(*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_SRC2_CTRL_string = "PC "; + default : decode_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_18_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_18__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_18__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_18__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_18__string = "PC "; + default : _zz_18__string = "???"; + endcase + end + always @(*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_SRC1_CTRL_string = "URS1 "; + default : decode_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_20_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_20__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_20__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_20__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_20__string = "URS1 "; + default : _zz_20__string = "????????????"; + endcase + end + always @(*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : execute_ALU_CTRL_string = "BITWISE "; + default : execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_21_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_21__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_21__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_21__string = "BITWISE "; + default : _zz_21__string = "????????"; + endcase + end + always @(*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_22_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_22__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_22__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_22__string = "AND_1"; + default : _zz_22__string = "?????"; + endcase + end + always @(*) begin + case(_zz_26_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_26__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_26__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_26__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_26__string = "SRA_1 "; + default : _zz_26__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_27_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_27__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_27__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_27__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_27__string = "PC "; + default : _zz_27__string = "???"; + endcase + end + always @(*) begin + case(_zz_28_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_28__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_28__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_28__string = "AND_1"; + default : _zz_28__string = "?????"; + endcase + end + always @(*) begin + case(_zz_29_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_29__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_29__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_29__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_29__string = "JALR"; + default : _zz_29__string = "????"; + endcase + end + always @(*) begin + case(_zz_30_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_30__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_30__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_30__string = "BITWISE "; + default : _zz_30__string = "????????"; + endcase + end + always @(*) begin + case(_zz_31_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_31__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_31__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_31__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_31__string = "URS1 "; + default : _zz_31__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_55_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_55__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_55__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_55__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_55__string = "URS1 "; + default : _zz_55__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_56_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_56__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_56__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_56__string = "BITWISE "; + default : _zz_56__string = "????????"; + endcase + end + always @(*) begin + case(_zz_57_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_57__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_57__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_57__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_57__string = "JALR"; + default : _zz_57__string = "????"; + endcase + end + always @(*) begin + case(_zz_58_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_58__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_58__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_58__string = "AND_1"; + default : _zz_58__string = "?????"; + endcase + end + always @(*) begin + case(_zz_59_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_59__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_59__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_59__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_59__string = "PC "; + default : _zz_59__string = "???"; + endcase + end + always @(*) begin + case(_zz_60_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_60__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_60__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_60__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_60__string = "SRA_1 "; + default : _zz_60__string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_to_execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_to_execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_to_execute_ALU_CTRL_string = "BITWISE "; + default : decode_to_execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_to_execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_to_execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_to_execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_to_execute_SHIFT_CTRL_string = "SRA_1 "; + default : decode_to_execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_to_execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(decode_to_execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_to_execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_to_execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_to_execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_to_execute_BRANCH_CTRL_string = "JALR"; + default : decode_to_execute_BRANCH_CTRL_string = "????"; + endcase + end + `endif + + assign decode_SRC2_FORCE_ZERO = (decode_SRC_ADD_ZERO && (! decode_SRC_USE_SUB_LESS)); + assign decode_BRANCH_CTRL = _zz_1_; + assign _zz_2_ = _zz_3_; + assign memory_MEMORY_READ_DATA = dBus_rsp_data; + assign decode_ALU_BITWISE_CTRL = _zz_4_; + assign _zz_5_ = _zz_6_; + assign decode_BYPASSABLE_EXECUTE_STAGE = _zz_97_[0]; + assign execute_BRANCH_CALC = {execute_BranchPlugin_branchAdder[31 : 1],(1'b0)}; + assign writeBack_REGFILE_WRITE_DATA = memory_to_writeBack_REGFILE_WRITE_DATA; + assign execute_REGFILE_WRITE_DATA = _zz_62_; + assign decode_SHIFT_CTRL = _zz_7_; + assign _zz_8_ = _zz_9_; + assign decode_MEMORY_ENABLE = _zz_98_[0]; + assign decode_SRC_LESS_UNSIGNED = _zz_99_[0]; + assign memory_FORMAL_PC_NEXT = execute_to_memory_FORMAL_PC_NEXT; + assign execute_FORMAL_PC_NEXT = decode_to_execute_FORMAL_PC_NEXT; + assign decode_FORMAL_PC_NEXT = (decode_PC + 32'h00000004); + assign decode_MEMORY_STORE = _zz_100_[0]; + assign decode_ALU_CTRL = _zz_10_; + assign _zz_11_ = _zz_12_; + assign memory_PC = execute_to_memory_PC; + assign decode_RS1 = decode_RegFilePlugin_rs1Data; + assign execute_BRANCH_DO = _zz_76_; + assign decode_SRC1 = _zz_63_; + assign memory_MEMORY_ADDRESS_LOW = execute_to_memory_MEMORY_ADDRESS_LOW; + assign execute_MEMORY_ADDRESS_LOW = dBus_cmd_payload_address[1 : 0]; + assign decode_SRC2 = _zz_68_; + assign execute_BYPASSABLE_MEMORY_STAGE = decode_to_execute_BYPASSABLE_MEMORY_STAGE; + assign decode_BYPASSABLE_MEMORY_STAGE = _zz_101_[0]; + assign decode_RS2 = decode_RegFilePlugin_rs2Data; + assign memory_BRANCH_CALC = execute_to_memory_BRANCH_CALC; + assign memory_BRANCH_DO = execute_to_memory_BRANCH_DO; + assign execute_PC = decode_to_execute_PC; + assign execute_RS1 = decode_to_execute_RS1; + assign execute_BRANCH_CTRL = _zz_13_; + assign decode_RS2_USE = _zz_102_[0]; + assign decode_RS1_USE = _zz_103_[0]; + assign execute_REGFILE_WRITE_VALID = decode_to_execute_REGFILE_WRITE_VALID; + assign execute_BYPASSABLE_EXECUTE_STAGE = decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + assign memory_REGFILE_WRITE_VALID = execute_to_memory_REGFILE_WRITE_VALID; + assign memory_INSTRUCTION = execute_to_memory_INSTRUCTION; + assign memory_BYPASSABLE_MEMORY_STAGE = execute_to_memory_BYPASSABLE_MEMORY_STAGE; + assign writeBack_REGFILE_WRITE_VALID = memory_to_writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + _zz_14_ = execute_REGFILE_WRITE_DATA; + if(_zz_88_)begin + _zz_14_ = _zz_69_; + end + end + + assign memory_REGFILE_WRITE_DATA = execute_to_memory_REGFILE_WRITE_DATA; + assign execute_SHIFT_CTRL = _zz_15_; + assign execute_SRC_LESS_UNSIGNED = decode_to_execute_SRC_LESS_UNSIGNED; + assign execute_SRC2_FORCE_ZERO = decode_to_execute_SRC2_FORCE_ZERO; + assign execute_SRC_USE_SUB_LESS = decode_to_execute_SRC_USE_SUB_LESS; + assign _zz_16_ = decode_PC; + assign _zz_17_ = decode_RS2; + assign decode_SRC2_CTRL = _zz_18_; + assign _zz_19_ = decode_RS1; + assign decode_SRC1_CTRL = _zz_20_; + assign decode_SRC_USE_SUB_LESS = _zz_104_[0]; + assign decode_SRC_ADD_ZERO = _zz_105_[0]; + assign execute_SRC_ADD_SUB = execute_SrcPlugin_addSub; + assign execute_SRC_LESS = execute_SrcPlugin_less; + assign execute_ALU_CTRL = _zz_21_; + assign execute_SRC2 = decode_to_execute_SRC2; + assign execute_SRC1 = decode_to_execute_SRC1; + assign execute_ALU_BITWISE_CTRL = _zz_22_; + assign _zz_23_ = writeBack_INSTRUCTION; + assign _zz_24_ = writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + _zz_25_ = 1'b0; + if(lastStageRegFileWrite_valid)begin + _zz_25_ = 1'b1; + end + end + + assign decode_INSTRUCTION_ANTICIPATED = (decode_arbitration_isStuck ? decode_INSTRUCTION : IBusSimplePlugin_iBusRsp_output_payload_rsp_inst); + always @ (*) begin + decode_REGFILE_WRITE_VALID = _zz_106_[0]; + if((decode_INSTRUCTION[11 : 7] == 5'h0))begin + decode_REGFILE_WRITE_VALID = 1'b0; + end + end + + assign writeBack_MEMORY_STORE = memory_to_writeBack_MEMORY_STORE; + always @ (*) begin + _zz_32_ = writeBack_REGFILE_WRITE_DATA; + if((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE))begin + _zz_32_ = writeBack_DBusSimplePlugin_rspFormated; + end + end + + assign writeBack_MEMORY_ENABLE = memory_to_writeBack_MEMORY_ENABLE; + assign writeBack_MEMORY_ADDRESS_LOW = memory_to_writeBack_MEMORY_ADDRESS_LOW; + assign writeBack_MEMORY_READ_DATA = memory_to_writeBack_MEMORY_READ_DATA; + assign memory_MEMORY_STORE = execute_to_memory_MEMORY_STORE; + assign memory_MEMORY_ENABLE = execute_to_memory_MEMORY_ENABLE; + assign execute_SRC_ADD = execute_SrcPlugin_addSub; + assign execute_RS2 = decode_to_execute_RS2; + assign execute_INSTRUCTION = decode_to_execute_INSTRUCTION; + assign execute_MEMORY_STORE = decode_to_execute_MEMORY_STORE; + assign execute_MEMORY_ENABLE = decode_to_execute_MEMORY_ENABLE; + assign execute_ALIGNEMENT_FAULT = 1'b0; + assign decode_PC = IBusSimplePlugin_injector_decodeInput_payload_pc; + assign decode_INSTRUCTION = IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + assign writeBack_PC = memory_to_writeBack_PC; + assign writeBack_INSTRUCTION = memory_to_writeBack_INSTRUCTION; + assign decode_arbitration_haltItself = 1'b0; + always @ (*) begin + decode_arbitration_haltByOther = 1'b0; + if((decode_arbitration_isValid && (_zz_70_ || _zz_71_)))begin + decode_arbitration_haltByOther = 1'b1; + end + end + + always @ (*) begin + decode_arbitration_removeIt = 1'b0; + if(decode_arbitration_isFlushed)begin + decode_arbitration_removeIt = 1'b1; + end + end + + assign decode_arbitration_flushIt = 1'b0; + assign decode_arbitration_flushNext = 1'b0; + always @ (*) begin + execute_arbitration_haltItself = 1'b0; + if(((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! dBus_cmd_ready)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_44_)))begin + execute_arbitration_haltItself = 1'b1; + end + if(_zz_88_)begin + if(_zz_89_)begin + if(! execute_LightShifterPlugin_done) begin + execute_arbitration_haltItself = 1'b1; + end + end + end + end + + assign execute_arbitration_haltByOther = 1'b0; + always @ (*) begin + execute_arbitration_removeIt = 1'b0; + if(execute_arbitration_isFlushed)begin + execute_arbitration_removeIt = 1'b1; + end + end + + assign execute_arbitration_flushIt = 1'b0; + assign execute_arbitration_flushNext = 1'b0; + always @ (*) begin + memory_arbitration_haltItself = 1'b0; + if((((memory_arbitration_isValid && memory_MEMORY_ENABLE) && (! memory_MEMORY_STORE)) && ((! dBus_rsp_ready) || 1'b0)))begin + memory_arbitration_haltItself = 1'b1; + end + end + + assign memory_arbitration_haltByOther = 1'b0; + always @ (*) begin + memory_arbitration_removeIt = 1'b0; + if(memory_arbitration_isFlushed)begin + memory_arbitration_removeIt = 1'b1; + end + end + + assign memory_arbitration_flushIt = 1'b0; + always @ (*) begin + memory_arbitration_flushNext = 1'b0; + if(BranchPlugin_jumpInterface_valid)begin + memory_arbitration_flushNext = 1'b1; + end + end + + assign writeBack_arbitration_haltItself = 1'b0; + assign writeBack_arbitration_haltByOther = 1'b0; + always @ (*) begin + writeBack_arbitration_removeIt = 1'b0; + if(writeBack_arbitration_isFlushed)begin + writeBack_arbitration_removeIt = 1'b1; + end + end + + assign writeBack_arbitration_flushIt = 1'b0; + assign writeBack_arbitration_flushNext = 1'b0; + assign lastStageInstruction = writeBack_INSTRUCTION; + assign lastStagePc = writeBack_PC; + assign lastStageIsValid = writeBack_arbitration_isValid; + assign lastStageIsFiring = writeBack_arbitration_isFiring; + assign IBusSimplePlugin_fetcherHalt = 1'b0; + always @ (*) begin + IBusSimplePlugin_incomingInstruction = 1'b0; + if(IBusSimplePlugin_iBusRsp_stages_1_input_valid)begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + end + + assign IBusSimplePlugin_externalFlush = ({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,{execute_arbitration_flushNext,decode_arbitration_flushNext}}} != (4'b0000)); + assign IBusSimplePlugin_jump_pcLoad_valid = (BranchPlugin_jumpInterface_valid != (1'b0)); + assign IBusSimplePlugin_jump_pcLoad_payload = BranchPlugin_jumpInterface_payload; + always @ (*) begin + IBusSimplePlugin_fetchPc_correction = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_correction = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_corrected = (IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_correctionReg); + always @ (*) begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b0; + if(IBusSimplePlugin_iBusRsp_stages_1_input_ready)begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b1; + end + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_pc = (IBusSimplePlugin_fetchPc_pcReg + _zz_108_); + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_pc = IBusSimplePlugin_jump_pcLoad_payload; + end + IBusSimplePlugin_fetchPc_pc[0] = 1'b0; + IBusSimplePlugin_fetchPc_pc[1] = 1'b0; + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_flushed = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_flushed = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_output_valid = ((! IBusSimplePlugin_fetcherHalt) && IBusSimplePlugin_fetchPc_booted); + assign IBusSimplePlugin_fetchPc_output_payload = IBusSimplePlugin_fetchPc_pc; + assign IBusSimplePlugin_iBusRsp_redoFetch = 1'b0; + assign IBusSimplePlugin_iBusRsp_stages_0_input_valid = IBusSimplePlugin_fetchPc_output_valid; + assign IBusSimplePlugin_fetchPc_output_ready = IBusSimplePlugin_iBusRsp_stages_0_input_ready; + assign IBusSimplePlugin_iBusRsp_stages_0_input_payload = IBusSimplePlugin_fetchPc_output_payload; + always @ (*) begin + IBusSimplePlugin_iBusRsp_stages_0_halt = 1'b0; + if((IBusSimplePlugin_iBusRsp_stages_0_input_valid && ((! IBusSimplePlugin_cmdFork_canEmit) || (! IBusSimplePlugin_cmd_ready))))begin + IBusSimplePlugin_iBusRsp_stages_0_halt = 1'b1; + end + end + + assign _zz_33_ = (! IBusSimplePlugin_iBusRsp_stages_0_halt); + assign IBusSimplePlugin_iBusRsp_stages_0_input_ready = (IBusSimplePlugin_iBusRsp_stages_0_output_ready && _zz_33_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_valid = (IBusSimplePlugin_iBusRsp_stages_0_input_valid && _zz_33_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_payload = IBusSimplePlugin_iBusRsp_stages_0_input_payload; + assign IBusSimplePlugin_iBusRsp_stages_1_halt = 1'b0; + assign _zz_34_ = (! IBusSimplePlugin_iBusRsp_stages_1_halt); + assign IBusSimplePlugin_iBusRsp_stages_1_input_ready = (IBusSimplePlugin_iBusRsp_stages_1_output_ready && _zz_34_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_valid = (IBusSimplePlugin_iBusRsp_stages_1_input_valid && _zz_34_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_payload = IBusSimplePlugin_iBusRsp_stages_1_input_payload; + assign IBusSimplePlugin_iBusRsp_flush = (IBusSimplePlugin_externalFlush || IBusSimplePlugin_iBusRsp_redoFetch); + assign IBusSimplePlugin_iBusRsp_stages_0_output_ready = _zz_35_; + assign _zz_35_ = ((1'b0 && (! _zz_36_)) || IBusSimplePlugin_iBusRsp_stages_1_input_ready); + assign _zz_36_ = _zz_37_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_valid = _zz_36_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_payload = IBusSimplePlugin_fetchPc_pcReg; + always @ (*) begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b1; + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b0; + end + if((! IBusSimplePlugin_pcValids_0))begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b0; + end + end + + assign IBusSimplePlugin_iBusRsp_output_ready = ((1'b0 && (! IBusSimplePlugin_injector_decodeInput_valid)) || IBusSimplePlugin_injector_decodeInput_ready); + assign IBusSimplePlugin_injector_decodeInput_valid = _zz_38_; + assign IBusSimplePlugin_injector_decodeInput_payload_pc = _zz_39_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_error = _zz_40_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_inst = _zz_41_; + assign IBusSimplePlugin_injector_decodeInput_payload_isRvc = _zz_42_; + assign IBusSimplePlugin_pcValids_0 = IBusSimplePlugin_injector_nextPcCalc_valids_1; + assign IBusSimplePlugin_pcValids_1 = IBusSimplePlugin_injector_nextPcCalc_valids_2; + assign IBusSimplePlugin_pcValids_2 = IBusSimplePlugin_injector_nextPcCalc_valids_3; + assign IBusSimplePlugin_pcValids_3 = IBusSimplePlugin_injector_nextPcCalc_valids_4; + assign IBusSimplePlugin_injector_decodeInput_ready = (! decode_arbitration_isStuck); + assign decode_arbitration_isValid = IBusSimplePlugin_injector_decodeInput_valid; + assign iBus_cmd_valid = IBusSimplePlugin_cmd_valid; + assign IBusSimplePlugin_cmd_ready = iBus_cmd_ready; + assign iBus_cmd_payload_pc = IBusSimplePlugin_cmd_payload_pc; + assign IBusSimplePlugin_pending_next = (_zz_109_ - _zz_113_); + assign IBusSimplePlugin_cmdFork_canEmit = (IBusSimplePlugin_iBusRsp_stages_0_output_ready && (IBusSimplePlugin_pending_value != (3'b111))); + assign IBusSimplePlugin_cmd_valid = (IBusSimplePlugin_iBusRsp_stages_0_input_valid && IBusSimplePlugin_cmdFork_canEmit); + assign IBusSimplePlugin_pending_inc = (IBusSimplePlugin_cmd_valid && IBusSimplePlugin_cmd_ready); + assign IBusSimplePlugin_cmd_payload_pc = {IBusSimplePlugin_iBusRsp_stages_0_input_payload[31 : 2],(2'b00)}; + assign IBusSimplePlugin_rspJoin_rspBuffer_flush = ((IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000)) || IBusSimplePlugin_iBusRsp_flush); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_valid = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter == (3'b000))); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + assign _zz_84_ = (IBusSimplePlugin_rspJoin_rspBuffer_output_ready || IBusSimplePlugin_rspJoin_rspBuffer_flush); + assign IBusSimplePlugin_pending_dec = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && _zz_84_); + assign IBusSimplePlugin_rspJoin_fetchRsp_pc = IBusSimplePlugin_iBusRsp_stages_1_output_payload; + always @ (*) begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + if((! IBusSimplePlugin_rspJoin_rspBuffer_output_valid))begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = 1'b0; + end + end + + assign IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + assign IBusSimplePlugin_rspJoin_exceptionDetected = 1'b0; + assign IBusSimplePlugin_rspJoin_join_valid = (IBusSimplePlugin_iBusRsp_stages_1_output_valid && IBusSimplePlugin_rspJoin_rspBuffer_output_valid); + assign IBusSimplePlugin_rspJoin_join_payload_pc = IBusSimplePlugin_rspJoin_fetchRsp_pc; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_error = IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_inst = IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + assign IBusSimplePlugin_rspJoin_join_payload_isRvc = IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + assign IBusSimplePlugin_iBusRsp_stages_1_output_ready = (IBusSimplePlugin_iBusRsp_stages_1_output_valid ? (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready) : IBusSimplePlugin_rspJoin_join_ready); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_ready = (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready); + assign _zz_43_ = (! IBusSimplePlugin_rspJoin_exceptionDetected); + assign IBusSimplePlugin_rspJoin_join_ready = (IBusSimplePlugin_iBusRsp_output_ready && _zz_43_); + assign IBusSimplePlugin_iBusRsp_output_valid = (IBusSimplePlugin_rspJoin_join_valid && _zz_43_); + assign IBusSimplePlugin_iBusRsp_output_payload_pc = IBusSimplePlugin_rspJoin_join_payload_pc; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_error = IBusSimplePlugin_rspJoin_join_payload_rsp_error; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_inst = IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + assign IBusSimplePlugin_iBusRsp_output_payload_isRvc = IBusSimplePlugin_rspJoin_join_payload_isRvc; + assign _zz_44_ = 1'b0; + always @ (*) begin + execute_DBusSimplePlugin_skipCmd = 1'b0; + if(execute_ALIGNEMENT_FAULT)begin + execute_DBusSimplePlugin_skipCmd = 1'b1; + end + end + + assign dBus_cmd_valid = (((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! execute_arbitration_isStuckByOthers)) && (! execute_arbitration_isFlushed)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_44_)); + assign dBus_cmd_payload_wr = execute_MEMORY_STORE; + assign dBus_cmd_payload_size = execute_INSTRUCTION[13 : 12]; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_45_ = {{{execute_RS2[7 : 0],execute_RS2[7 : 0]},execute_RS2[7 : 0]},execute_RS2[7 : 0]}; + end + 2'b01 : begin + _zz_45_ = {execute_RS2[15 : 0],execute_RS2[15 : 0]}; + end + default : begin + _zz_45_ = execute_RS2[31 : 0]; + end + endcase + end + + assign dBus_cmd_payload_data = _zz_45_; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_46_ = (4'b0001); + end + 2'b01 : begin + _zz_46_ = (4'b0011); + end + default : begin + _zz_46_ = (4'b1111); + end + endcase + end + + assign execute_DBusSimplePlugin_formalMask = (_zz_46_ <<< dBus_cmd_payload_address[1 : 0]); + assign dBus_cmd_payload_address = execute_SRC_ADD; + always @ (*) begin + writeBack_DBusSimplePlugin_rspShifted = writeBack_MEMORY_READ_DATA; + case(writeBack_MEMORY_ADDRESS_LOW) + 2'b01 : begin + writeBack_DBusSimplePlugin_rspShifted[7 : 0] = writeBack_MEMORY_READ_DATA[15 : 8]; + end + 2'b10 : begin + writeBack_DBusSimplePlugin_rspShifted[15 : 0] = writeBack_MEMORY_READ_DATA[31 : 16]; + end + 2'b11 : begin + writeBack_DBusSimplePlugin_rspShifted[7 : 0] = writeBack_MEMORY_READ_DATA[31 : 24]; + end + default : begin + end + endcase + end + + assign _zz_47_ = (writeBack_DBusSimplePlugin_rspShifted[7] && (! writeBack_INSTRUCTION[14])); + always @ (*) begin + _zz_48_[31] = _zz_47_; + _zz_48_[30] = _zz_47_; + _zz_48_[29] = _zz_47_; + _zz_48_[28] = _zz_47_; + _zz_48_[27] = _zz_47_; + _zz_48_[26] = _zz_47_; + _zz_48_[25] = _zz_47_; + _zz_48_[24] = _zz_47_; + _zz_48_[23] = _zz_47_; + _zz_48_[22] = _zz_47_; + _zz_48_[21] = _zz_47_; + _zz_48_[20] = _zz_47_; + _zz_48_[19] = _zz_47_; + _zz_48_[18] = _zz_47_; + _zz_48_[17] = _zz_47_; + _zz_48_[16] = _zz_47_; + _zz_48_[15] = _zz_47_; + _zz_48_[14] = _zz_47_; + _zz_48_[13] = _zz_47_; + _zz_48_[12] = _zz_47_; + _zz_48_[11] = _zz_47_; + _zz_48_[10] = _zz_47_; + _zz_48_[9] = _zz_47_; + _zz_48_[8] = _zz_47_; + _zz_48_[7 : 0] = writeBack_DBusSimplePlugin_rspShifted[7 : 0]; + end + + assign _zz_49_ = (writeBack_DBusSimplePlugin_rspShifted[15] && (! writeBack_INSTRUCTION[14])); + always @ (*) begin + _zz_50_[31] = _zz_49_; + _zz_50_[30] = _zz_49_; + _zz_50_[29] = _zz_49_; + _zz_50_[28] = _zz_49_; + _zz_50_[27] = _zz_49_; + _zz_50_[26] = _zz_49_; + _zz_50_[25] = _zz_49_; + _zz_50_[24] = _zz_49_; + _zz_50_[23] = _zz_49_; + _zz_50_[22] = _zz_49_; + _zz_50_[21] = _zz_49_; + _zz_50_[20] = _zz_49_; + _zz_50_[19] = _zz_49_; + _zz_50_[18] = _zz_49_; + _zz_50_[17] = _zz_49_; + _zz_50_[16] = _zz_49_; + _zz_50_[15 : 0] = writeBack_DBusSimplePlugin_rspShifted[15 : 0]; + end + + always @ (*) begin + case(_zz_96_) + 2'b00 : begin + writeBack_DBusSimplePlugin_rspFormated = _zz_48_; + end + 2'b01 : begin + writeBack_DBusSimplePlugin_rspFormated = _zz_50_; + end + default : begin + writeBack_DBusSimplePlugin_rspFormated = writeBack_DBusSimplePlugin_rspShifted; + end + endcase + end + + assign _zz_52_ = ((decode_INSTRUCTION & 32'h00000010) == 32'h00000010); + assign _zz_53_ = ((decode_INSTRUCTION & 32'h00000048) == 32'h00000048); + assign _zz_54_ = ((decode_INSTRUCTION & 32'h00000004) == 32'h00000004); + assign _zz_51_ = {(((decode_INSTRUCTION & _zz_137_) == 32'h00005010) != (1'b0)),{({_zz_138_,_zz_139_} != (2'b00)),{(_zz_140_ != (1'b0)),{(_zz_141_ != _zz_142_),{_zz_143_,{_zz_144_,_zz_145_}}}}}}; + assign _zz_55_ = _zz_51_[1 : 0]; + assign _zz_31_ = _zz_55_; + assign _zz_56_ = _zz_51_[3 : 2]; + assign _zz_30_ = _zz_56_; + assign _zz_57_ = _zz_51_[8 : 7]; + assign _zz_29_ = _zz_57_; + assign _zz_58_ = _zz_51_[13 : 12]; + assign _zz_28_ = _zz_58_; + assign _zz_59_ = _zz_51_[15 : 14]; + assign _zz_27_ = _zz_59_; + assign _zz_60_ = _zz_51_[22 : 21]; + assign _zz_26_ = _zz_60_; + assign decode_RegFilePlugin_regFileReadAddress1 = decode_INSTRUCTION_ANTICIPATED[19 : 15]; + assign decode_RegFilePlugin_regFileReadAddress2 = decode_INSTRUCTION_ANTICIPATED[24 : 20]; + assign decode_RegFilePlugin_rs1Data = _zz_86_; + assign decode_RegFilePlugin_rs2Data = _zz_87_; + always @ (*) begin + lastStageRegFileWrite_valid = (_zz_24_ && writeBack_arbitration_isFiring); + if(_zz_61_)begin + lastStageRegFileWrite_valid = 1'b1; + end + end + + assign lastStageRegFileWrite_payload_address = _zz_23_[11 : 7]; + assign lastStageRegFileWrite_payload_data = _zz_32_; + always @ (*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 & execute_SRC2); + end + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 | execute_SRC2); + end + default : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 ^ execute_SRC2); + end + endcase + end + + always @ (*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_BITWISE : begin + _zz_62_ = execute_IntAluPlugin_bitwise; + end + `AluCtrlEnum_defaultEncoding_SLT_SLTU : begin + _zz_62_ = {31'd0, _zz_118_}; + end + default : begin + _zz_62_ = execute_SRC_ADD_SUB; + end + endcase + end + + always @ (*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : begin + _zz_63_ = _zz_19_; + end + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : begin + _zz_63_ = {29'd0, _zz_119_}; + end + `Src1CtrlEnum_defaultEncoding_IMU : begin + _zz_63_ = {decode_INSTRUCTION[31 : 12],12'h0}; + end + default : begin + _zz_63_ = {27'd0, _zz_120_}; + end + endcase + end + + assign _zz_64_ = _zz_121_[11]; + always @ (*) begin + _zz_65_[19] = _zz_64_; + _zz_65_[18] = _zz_64_; + _zz_65_[17] = _zz_64_; + _zz_65_[16] = _zz_64_; + _zz_65_[15] = _zz_64_; + _zz_65_[14] = _zz_64_; + _zz_65_[13] = _zz_64_; + _zz_65_[12] = _zz_64_; + _zz_65_[11] = _zz_64_; + _zz_65_[10] = _zz_64_; + _zz_65_[9] = _zz_64_; + _zz_65_[8] = _zz_64_; + _zz_65_[7] = _zz_64_; + _zz_65_[6] = _zz_64_; + _zz_65_[5] = _zz_64_; + _zz_65_[4] = _zz_64_; + _zz_65_[3] = _zz_64_; + _zz_65_[2] = _zz_64_; + _zz_65_[1] = _zz_64_; + _zz_65_[0] = _zz_64_; + end + + assign _zz_66_ = _zz_122_[11]; + always @ (*) begin + _zz_67_[19] = _zz_66_; + _zz_67_[18] = _zz_66_; + _zz_67_[17] = _zz_66_; + _zz_67_[16] = _zz_66_; + _zz_67_[15] = _zz_66_; + _zz_67_[14] = _zz_66_; + _zz_67_[13] = _zz_66_; + _zz_67_[12] = _zz_66_; + _zz_67_[11] = _zz_66_; + _zz_67_[10] = _zz_66_; + _zz_67_[9] = _zz_66_; + _zz_67_[8] = _zz_66_; + _zz_67_[7] = _zz_66_; + _zz_67_[6] = _zz_66_; + _zz_67_[5] = _zz_66_; + _zz_67_[4] = _zz_66_; + _zz_67_[3] = _zz_66_; + _zz_67_[2] = _zz_66_; + _zz_67_[1] = _zz_66_; + _zz_67_[0] = _zz_66_; + end + + always @ (*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : begin + _zz_68_ = _zz_17_; + end + `Src2CtrlEnum_defaultEncoding_IMI : begin + _zz_68_ = {_zz_65_,decode_INSTRUCTION[31 : 20]}; + end + `Src2CtrlEnum_defaultEncoding_IMS : begin + _zz_68_ = {_zz_67_,{decode_INSTRUCTION[31 : 25],decode_INSTRUCTION[11 : 7]}}; + end + default : begin + _zz_68_ = _zz_16_; + end + endcase + end + + always @ (*) begin + execute_SrcPlugin_addSub = _zz_123_; + if(execute_SRC2_FORCE_ZERO)begin + execute_SrcPlugin_addSub = execute_SRC1; + end + end + + assign execute_SrcPlugin_less = ((execute_SRC1[31] == execute_SRC2[31]) ? execute_SrcPlugin_addSub[31] : (execute_SRC_LESS_UNSIGNED ? execute_SRC2[31] : execute_SRC1[31])); + assign execute_LightShifterPlugin_isShift = (execute_SHIFT_CTRL != `ShiftCtrlEnum_defaultEncoding_DISABLE_1); + assign execute_LightShifterPlugin_amplitude = (execute_LightShifterPlugin_isActive ? execute_LightShifterPlugin_amplitudeReg : execute_SRC2[4 : 0]); + assign execute_LightShifterPlugin_shiftInput = (execute_LightShifterPlugin_isActive ? memory_REGFILE_WRITE_DATA : execute_SRC1); + assign execute_LightShifterPlugin_done = (execute_LightShifterPlugin_amplitude[4 : 1] == (4'b0000)); + always @ (*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_SLL_1 : begin + _zz_69_ = (execute_LightShifterPlugin_shiftInput <<< 1); + end + default : begin + _zz_69_ = _zz_130_; + end + endcase + end + + always @ (*) begin + _zz_70_ = 1'b0; + if(_zz_72_)begin + if((_zz_73_ == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + if(_zz_90_)begin + if(_zz_91_)begin + if((writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if(_zz_92_)begin + if(_zz_93_)begin + if((memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if(_zz_94_)begin + if(_zz_95_)begin + if((execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]))begin + _zz_70_ = 1'b1; + end + end + end + if((! decode_RS1_USE))begin + _zz_70_ = 1'b0; + end + end + + always @ (*) begin + _zz_71_ = 1'b0; + if(_zz_72_)begin + if((_zz_73_ == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + if(_zz_90_)begin + if(_zz_91_)begin + if((writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if(_zz_92_)begin + if(_zz_93_)begin + if((memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if(_zz_94_)begin + if(_zz_95_)begin + if((execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]))begin + _zz_71_ = 1'b1; + end + end + end + if((! decode_RS2_USE))begin + _zz_71_ = 1'b0; + end + end + + assign execute_BranchPlugin_eq = (execute_SRC1 == execute_SRC2); + assign _zz_74_ = execute_INSTRUCTION[14 : 12]; + always @ (*) begin + if((_zz_74_ == (3'b000))) begin + _zz_75_ = execute_BranchPlugin_eq; + end else if((_zz_74_ == (3'b001))) begin + _zz_75_ = (! execute_BranchPlugin_eq); + end else if((((_zz_74_ & (3'b101)) == (3'b101)))) begin + _zz_75_ = (! execute_SRC_LESS); + end else begin + _zz_75_ = execute_SRC_LESS; + end + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : begin + _zz_76_ = 1'b0; + end + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_76_ = 1'b1; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_76_ = 1'b1; + end + default : begin + _zz_76_ = _zz_75_; + end + endcase + end + + assign execute_BranchPlugin_branch_src1 = ((execute_BRANCH_CTRL == `BranchCtrlEnum_defaultEncoding_JALR) ? execute_RS1 : execute_PC); + assign _zz_77_ = _zz_132_[19]; + always @ (*) begin + _zz_78_[10] = _zz_77_; + _zz_78_[9] = _zz_77_; + _zz_78_[8] = _zz_77_; + _zz_78_[7] = _zz_77_; + _zz_78_[6] = _zz_77_; + _zz_78_[5] = _zz_77_; + _zz_78_[4] = _zz_77_; + _zz_78_[3] = _zz_77_; + _zz_78_[2] = _zz_77_; + _zz_78_[1] = _zz_77_; + _zz_78_[0] = _zz_77_; + end + + assign _zz_79_ = _zz_133_[11]; + always @ (*) begin + _zz_80_[19] = _zz_79_; + _zz_80_[18] = _zz_79_; + _zz_80_[17] = _zz_79_; + _zz_80_[16] = _zz_79_; + _zz_80_[15] = _zz_79_; + _zz_80_[14] = _zz_79_; + _zz_80_[13] = _zz_79_; + _zz_80_[12] = _zz_79_; + _zz_80_[11] = _zz_79_; + _zz_80_[10] = _zz_79_; + _zz_80_[9] = _zz_79_; + _zz_80_[8] = _zz_79_; + _zz_80_[7] = _zz_79_; + _zz_80_[6] = _zz_79_; + _zz_80_[5] = _zz_79_; + _zz_80_[4] = _zz_79_; + _zz_80_[3] = _zz_79_; + _zz_80_[2] = _zz_79_; + _zz_80_[1] = _zz_79_; + _zz_80_[0] = _zz_79_; + end + + assign _zz_81_ = _zz_134_[11]; + always @ (*) begin + _zz_82_[18] = _zz_81_; + _zz_82_[17] = _zz_81_; + _zz_82_[16] = _zz_81_; + _zz_82_[15] = _zz_81_; + _zz_82_[14] = _zz_81_; + _zz_82_[13] = _zz_81_; + _zz_82_[12] = _zz_81_; + _zz_82_[11] = _zz_81_; + _zz_82_[10] = _zz_81_; + _zz_82_[9] = _zz_81_; + _zz_82_[8] = _zz_81_; + _zz_82_[7] = _zz_81_; + _zz_82_[6] = _zz_81_; + _zz_82_[5] = _zz_81_; + _zz_82_[4] = _zz_81_; + _zz_82_[3] = _zz_81_; + _zz_82_[2] = _zz_81_; + _zz_82_[1] = _zz_81_; + _zz_82_[0] = _zz_81_; + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_83_ = {{_zz_78_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}},1'b0}; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_83_ = {_zz_80_,execute_INSTRUCTION[31 : 20]}; + end + default : begin + _zz_83_ = {{_zz_82_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}},1'b0}; + end + endcase + end + + assign execute_BranchPlugin_branch_src2 = _zz_83_; + assign execute_BranchPlugin_branchAdder = (execute_BranchPlugin_branch_src1 + execute_BranchPlugin_branch_src2); + assign BranchPlugin_jumpInterface_valid = ((memory_arbitration_isValid && memory_BRANCH_DO) && (! 1'b0)); + assign BranchPlugin_jumpInterface_payload = memory_BRANCH_CALC; + assign _zz_18_ = _zz_27_; + assign _zz_12_ = decode_ALU_CTRL; + assign _zz_10_ = _zz_30_; + assign _zz_21_ = decode_to_execute_ALU_CTRL; + assign _zz_20_ = _zz_31_; + assign _zz_9_ = decode_SHIFT_CTRL; + assign _zz_7_ = _zz_26_; + assign _zz_15_ = decode_to_execute_SHIFT_CTRL; + assign _zz_6_ = decode_ALU_BITWISE_CTRL; + assign _zz_4_ = _zz_28_; + assign _zz_22_ = decode_to_execute_ALU_BITWISE_CTRL; + assign _zz_3_ = decode_BRANCH_CTRL; + assign _zz_1_ = _zz_29_; + assign _zz_13_ = decode_to_execute_BRANCH_CTRL; + assign decode_arbitration_isFlushed = (({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,execute_arbitration_flushNext}} != (3'b000)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,{execute_arbitration_flushIt,decode_arbitration_flushIt}}} != (4'b0000))); + assign execute_arbitration_isFlushed = (({writeBack_arbitration_flushNext,memory_arbitration_flushNext} != (2'b00)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,execute_arbitration_flushIt}} != (3'b000))); + assign memory_arbitration_isFlushed = ((writeBack_arbitration_flushNext != (1'b0)) || ({writeBack_arbitration_flushIt,memory_arbitration_flushIt} != (2'b00))); + assign writeBack_arbitration_isFlushed = (1'b0 || (writeBack_arbitration_flushIt != (1'b0))); + assign decode_arbitration_isStuckByOthers = (decode_arbitration_haltByOther || (((1'b0 || execute_arbitration_isStuck) || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign decode_arbitration_isStuck = (decode_arbitration_haltItself || decode_arbitration_isStuckByOthers); + assign decode_arbitration_isMoving = ((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)); + assign decode_arbitration_isFiring = ((decode_arbitration_isValid && (! decode_arbitration_isStuck)) && (! decode_arbitration_removeIt)); + assign execute_arbitration_isStuckByOthers = (execute_arbitration_haltByOther || ((1'b0 || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign execute_arbitration_isStuck = (execute_arbitration_haltItself || execute_arbitration_isStuckByOthers); + assign execute_arbitration_isMoving = ((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)); + assign execute_arbitration_isFiring = ((execute_arbitration_isValid && (! execute_arbitration_isStuck)) && (! execute_arbitration_removeIt)); + assign memory_arbitration_isStuckByOthers = (memory_arbitration_haltByOther || (1'b0 || writeBack_arbitration_isStuck)); + assign memory_arbitration_isStuck = (memory_arbitration_haltItself || memory_arbitration_isStuckByOthers); + assign memory_arbitration_isMoving = ((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)); + assign memory_arbitration_isFiring = ((memory_arbitration_isValid && (! memory_arbitration_isStuck)) && (! memory_arbitration_removeIt)); + assign writeBack_arbitration_isStuckByOthers = (writeBack_arbitration_haltByOther || 1'b0); + assign writeBack_arbitration_isStuck = (writeBack_arbitration_haltItself || writeBack_arbitration_isStuckByOthers); + assign writeBack_arbitration_isMoving = ((! writeBack_arbitration_isStuck) && (! writeBack_arbitration_removeIt)); + assign writeBack_arbitration_isFiring = ((writeBack_arbitration_isValid && (! writeBack_arbitration_isStuck)) && (! writeBack_arbitration_removeIt)); + assign _zz_85_ = 1'b0; + always @ (posedge clk or posedge reset) begin + if (reset) begin + IBusSimplePlugin_fetchPc_pcReg <= 32'h00060000; + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + IBusSimplePlugin_fetchPc_booted <= 1'b0; + IBusSimplePlugin_fetchPc_inc <= 1'b0; + _zz_37_ <= 1'b0; + _zz_38_ <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + IBusSimplePlugin_pending_value <= (3'b000); + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (3'b000); + _zz_61_ <= 1'b1; + execute_LightShifterPlugin_isActive <= 1'b0; + _zz_72_ <= 1'b0; + execute_arbitration_isValid <= 1'b0; + memory_arbitration_isValid <= 1'b0; + writeBack_arbitration_isValid <= 1'b0; + memory_to_writeBack_REGFILE_WRITE_DATA <= 32'h0; + memory_to_writeBack_INSTRUCTION <= 32'h0; + end else begin + if(IBusSimplePlugin_fetchPc_correction)begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b1; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + end + IBusSimplePlugin_fetchPc_booted <= 1'b1; + if((IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_pcRegPropagate))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b1; + end + if(((! IBusSimplePlugin_fetchPc_output_valid) && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_booted && ((IBusSimplePlugin_fetchPc_output_ready || IBusSimplePlugin_fetchPc_correction) || IBusSimplePlugin_fetchPc_pcRegPropagate)))begin + IBusSimplePlugin_fetchPc_pcReg <= IBusSimplePlugin_fetchPc_pc; + end + if(IBusSimplePlugin_iBusRsp_flush)begin + _zz_37_ <= 1'b0; + end + if(_zz_35_)begin + _zz_37_ <= (IBusSimplePlugin_iBusRsp_stages_0_output_valid && (! 1'b0)); + end + if(decode_arbitration_removeIt)begin + _zz_38_ <= 1'b0; + end + if(IBusSimplePlugin_iBusRsp_output_ready)begin + _zz_38_ <= (IBusSimplePlugin_iBusRsp_output_valid && (! IBusSimplePlugin_externalFlush)); + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + end + if((! (! IBusSimplePlugin_iBusRsp_stages_1_input_ready)))begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b1; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if((! (! IBusSimplePlugin_injector_decodeInput_ready)))begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= IBusSimplePlugin_injector_nextPcCalc_valids_0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + end + if((! execute_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= IBusSimplePlugin_injector_nextPcCalc_valids_1; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + end + if((! memory_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= IBusSimplePlugin_injector_nextPcCalc_valids_2; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + end + if((! writeBack_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= IBusSimplePlugin_injector_nextPcCalc_valids_3; + end + if(IBusSimplePlugin_fetchPc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_4 <= 1'b0; + end + IBusSimplePlugin_pending_value <= IBusSimplePlugin_pending_next; + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter - _zz_115_); + if(IBusSimplePlugin_iBusRsp_flush)begin + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (IBusSimplePlugin_pending_value - _zz_117_); + end + _zz_61_ <= 1'b0; + if(_zz_88_)begin + if(_zz_89_)begin + execute_LightShifterPlugin_isActive <= 1'b1; + if(execute_LightShifterPlugin_done)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + end + end + if(execute_arbitration_removeIt)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + _zz_72_ <= (_zz_24_ && writeBack_arbitration_isFiring); + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_INSTRUCTION <= memory_INSTRUCTION; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_DATA <= memory_REGFILE_WRITE_DATA; + end + if(((! execute_arbitration_isStuck) || execute_arbitration_removeIt))begin + execute_arbitration_isValid <= 1'b0; + end + if(((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)))begin + execute_arbitration_isValid <= decode_arbitration_isValid; + end + if(((! memory_arbitration_isStuck) || memory_arbitration_removeIt))begin + memory_arbitration_isValid <= 1'b0; + end + if(((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)))begin + memory_arbitration_isValid <= execute_arbitration_isValid; + end + if(((! writeBack_arbitration_isStuck) || writeBack_arbitration_removeIt))begin + writeBack_arbitration_isValid <= 1'b0; + end + if(((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)))begin + writeBack_arbitration_isValid <= memory_arbitration_isValid; + end + end + end + + always @ (posedge clk) begin + if(IBusSimplePlugin_iBusRsp_output_ready)begin + _zz_39_ <= IBusSimplePlugin_iBusRsp_output_payload_pc; + _zz_40_ <= IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + _zz_41_ <= IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + _zz_42_ <= IBusSimplePlugin_iBusRsp_output_payload_isRvc; + end + if(IBusSimplePlugin_injector_decodeInput_ready)begin + IBusSimplePlugin_injector_formal_rawInDecode <= IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + end + `ifndef SYNTHESIS + `ifdef FORMAL + assert((! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) + `else + if(!(! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) begin + $display("FAILURE DBusSimplePlugin doesn't allow memory stage stall when read happend"); + $finish; + end + `endif + `endif + `ifndef SYNTHESIS + `ifdef FORMAL + assert((! (((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE) && (! writeBack_MEMORY_STORE)) && writeBack_arbitration_isStuck))) + `else + if(!(! (((writeBack_arbitration_isValid && writeBack_MEMORY_ENABLE) && (! writeBack_MEMORY_STORE)) && writeBack_arbitration_isStuck))) begin + $display("FAILURE DBusSimplePlugin doesn't allow writeback stage stall when read happend"); + $finish; + end + `endif + `endif + if(_zz_88_)begin + if(_zz_89_)begin + execute_LightShifterPlugin_amplitudeReg <= (execute_LightShifterPlugin_amplitude - 5'h01); + end + end + _zz_73_ <= _zz_23_[11 : 7]; + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS2 <= _zz_17_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_REGFILE_WRITE_VALID <= decode_REGFILE_WRITE_VALID; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_REGFILE_WRITE_VALID <= execute_REGFILE_WRITE_VALID; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_VALID <= memory_REGFILE_WRITE_VALID; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_MEMORY_STAGE <= decode_BYPASSABLE_MEMORY_STAGE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BYPASSABLE_MEMORY_STAGE <= execute_BYPASSABLE_MEMORY_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2 <= decode_SRC2; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ADDRESS_LOW <= execute_MEMORY_ADDRESS_LOW; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_ADDRESS_LOW <= memory_MEMORY_ADDRESS_LOW; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC1 <= decode_SRC1; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_USE_SUB_LESS <= decode_SRC_USE_SUB_LESS; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BRANCH_DO <= execute_BRANCH_DO; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS1 <= _zz_19_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_INSTRUCTION <= decode_INSTRUCTION; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_INSTRUCTION <= execute_INSTRUCTION; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_PC <= _zz_16_; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_PC <= execute_PC; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_PC <= memory_PC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_CTRL <= _zz_11_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_STORE <= decode_MEMORY_STORE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_STORE <= execute_MEMORY_STORE; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_STORE <= memory_MEMORY_STORE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_FORMAL_PC_NEXT <= decode_FORMAL_PC_NEXT; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_FORMAL_PC_NEXT <= execute_FORMAL_PC_NEXT; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_LESS_UNSIGNED <= decode_SRC_LESS_UNSIGNED; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_ENABLE <= decode_MEMORY_ENABLE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ENABLE <= execute_MEMORY_ENABLE; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_ENABLE <= memory_MEMORY_ENABLE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SHIFT_CTRL <= _zz_8_; + end + if(((! memory_arbitration_isStuck) && (! execute_arbitration_isStuckByOthers)))begin + execute_to_memory_REGFILE_WRITE_DATA <= _zz_14_; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BRANCH_CALC <= execute_BRANCH_CALC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_EXECUTE_STAGE <= decode_BYPASSABLE_EXECUTE_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_BITWISE_CTRL <= _zz_5_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_MEMORY_READ_DATA <= memory_MEMORY_READ_DATA; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BRANCH_CTRL <= _zz_2_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_FORCE_ZERO <= decode_SRC2_FORCE_ZERO; + end + end + + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_shared_bus.v b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_shared_bus.v new file mode 100644 index 0000000000000000000000000000000000000000..53a81570c427da6be5a11b259b417ef658bcbe3a --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vexriscv/vexriscv_shared_bus.v @@ -0,0 +1,122 @@ +// vexriscv_shared_bus.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +// This is a basic wrapper module that adapts the Vex split ibus / dbus to a shared bus. +// The interface follows the naming of the PicoRV32 assumed by the rest of the system. + +// Not ideal for performance since ibus / dbus can run concurrently depending on addresses. +// It does work without modifying the rest of system and can be used to easily switch between Pico/Vex. + +// VexRiscV project, which was used to generate the two sources included in the vexriscv/ directory: +// https://github.com/SpinalHDL/VexRiscv + +`default_nettype none + +module vexriscv_shared_bus( + input clk, + input reset, + + input mem_ready, + output mem_valid, + + output [31:0] mem_addr, + input [31:0] mem_rdata, + output [31:0] mem_wdata, + output [3:0] mem_wstrb +); + // PicoRV32-style bus interface + + assign mem_addr = vex_address_r; + assign mem_wdata = vex_data_r; + assign mem_wstrb = vex_wstrb; + + assign mem_valid = vex_bus_active; + + // VexRiscV simple ibus / dbus <-> PicoRV32 bus adapter + + reg vex_bus_active; + + reg vex_i_bus_active; + wire vex_d_bus_active = !vex_i_bus_active; + + reg [31:0] vex_address_r; + reg [31:0] vex_data_r; + reg [3:0] vex_wstrb; + + wire vex_mem_ready = vex_bus_active && mem_ready; + wire vex_i_rsp_valid = vex_i_bus_active && vex_mem_ready; + wire vex_d_rsp_valid = vex_d_bus_active && vex_mem_ready; + + wire [1:0] vex_write_size; + wire vex_d_write_en; + wire [31:0] vex_d_write_data; + + wire vex_i_valid, vex_d_valid; + wire [31:0] vex_i_address; + wire [31:0] vex_d_address; + + // iBus_cmd_ready can be driven using comb. logic with iBus_cmd_valid.. + wire vex_i_ready = vex_i_valid && !vex_bus_active; + // ..but dBus_cmd_ready can't usse iBus_cmd_valid without logic loops, so register it + reg vex_d_started; + wire vex_d_ready = vex_d_started && vex_d_valid && vex_bus_active; + + always @(posedge clk) begin + if (reset) begin + vex_bus_active <= 0; + vex_d_started <= 0; + end else begin + vex_d_started <= 0; + + if (!vex_bus_active) begin + if (vex_i_valid) begin + vex_i_bus_active <= 1; + vex_bus_active <= 1; + + vex_address_r <= vex_i_address; + end else if (vex_d_valid) begin + vex_i_bus_active <= 0; + vex_bus_active <= 1; + vex_d_started <= 1; + + vex_address_r <= vex_d_address; + vex_data_r <= vex_d_write_data; + vex_wstrb <= vex_d_write_en ? (((1 << (1 << vex_write_size)) - 1) << vex_d_address[1:0]) : 0; + end + end else if (vex_mem_ready) begin + vex_bus_active <= 0; + vex_wstrb <= 0; + vex_d_started <= 0; + end + end + end + + VexRiscv vex( + .clk(clk), + .reset(reset), + + .iBus_cmd_payload_pc(vex_i_address), + .iBus_cmd_valid(vex_i_valid), + .iBus_cmd_ready(vex_i_ready), + + .iBus_rsp_payload_inst(mem_rdata), + .iBus_rsp_valid(vex_i_rsp_valid), + + .dBus_cmd_payload_address(vex_d_address), + .dBus_cmd_payload_data(vex_d_write_data), + .dBus_cmd_payload_size(vex_write_size), + .dBus_cmd_payload_wr(vex_d_write_en), + .dBus_cmd_valid(vex_d_valid), + .dBus_cmd_ready(vex_d_ready), + + .dBus_rsp_ready(vex_d_rsp_valid), + .dBus_rsp_data(mem_rdata), + + .dBus_rsp_error(0), + .iBus_rsp_payload_error(0) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/hardware/vram.v b/dan-rodrigues_icestation-32/hardware/vram.v new file mode 100644 index 0000000000000000000000000000000000000000..130735f6f33ea89f343298e20d74b4ff34a82a8b --- /dev/null +++ b/dan-rodrigues_icestation-32/hardware/vram.v @@ -0,0 +1,36 @@ +`default_nettype none + +// 64kbyte split into independently addressable 2x 32kbyte 16bit blocks + +module vram( + input clk, + + input [13:0] even_address, + input [13:0] odd_address, + input even_write_en, + input odd_write_en, + input [31:0] write_data, + + output [31:0] read_data +); + spram_256k vram_0 ( + .clk(clk), + .address(even_address), + .write_data(write_data[15:0]), + .mask(4'b1111), + .write_en(even_write_en), + .cs(1), + .read_data(read_data[15:0]) + ); + + spram_256k vram_1 ( + .clk(clk), + .address(odd_address), + .write_data(write_data[31:16]), + .mask(4'b1111), + .write_en(odd_write_en), + .cs(1), + .read_data(read_data[31:16]) + ); + +endmodule diff --git a/dan-rodrigues_icestation-32/scripts/ecp5_brams.py b/dan-rodrigues_icestation-32/scripts/ecp5_brams.py new file mode 100644 index 0000000000000000000000000000000000000000..228c3b3a9b21e46bbc97458d58ecc2db568d4ea3 --- /dev/null +++ b/dan-rodrigues_icestation-32/scripts/ecp5_brams.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +''' +Find and replace the Icestation-32's initial RAM in the FPGA configuration file +with an arbitary program. + +This can then be directly converted to a bitstream and uploaded to the FPGA. +This allows uploading a game together with otherwise unchanged hardware without having to +re-run yosys and nextpnr every time. + +It only works for games that do not rely on flash resources, or that have +flash resources already still in place from a previous run. + +Usage: + ecp5_brams.py ulx3s_pnr.json ulx3s.config boot_multi_noipl.bin prog.bin out.config + ecppack --input out.config --bit out.bit + fujprog -j sram out.bit # or through FTP +''' +# (C) Mara "vmedea" 2020 +# SPDX-License-Identifier: MIT +import sys +import json +import re +import struct + +BOOTLOADER_SIZE = 512 +RAM_SIZE = 16384 + +# regexp for BRAM init statements +# these are followed by 256 lines of 8 12-bit hexadecimal values +BRAM_RE = re.compile("\.bram_init (\d+)$") + +class ConfigFile: + def __init__(self, inconfig): + ''' + Load a FPGA configuration file. + ''' + with open(inconfig, 'r') as f: + self.config = list(f) + + # Remember starting line number in configuration for every BRAM + self.brams = {} + for line_nr, line in enumerate(self.config): + match = BRAM_RE.match(line) + if match: + # it must be followed by 256 lines of data, then an empty line + assert(self.config[line_nr + 257] == '\n') + self.brams[int(match.group(1))] = {'line_nr': line_nr} + + def write(self, outconfig): + ''' + Write updated FPGA configuration to disk. + ''' + with open(outconfig, 'w') as f: + f.write(''.join(self.config)) + + def parse_bram_data(self, num): + ''' + Parse BRAM data from config file. + ''' + base = self.brams[num]['line_nr'] + 1 + result = [] + for line in range(256): + items = self.config[base + line].rstrip().split(' ') + items = [int(x, 16) for x in items] + assert(len(items) == 8) + result += items + return result + + def set_bram_data(self, num, data): + ''' + Fill a BRAM in config file with new data. + ''' + base = self.brams[num]['line_nr'] + 1 + assert(len(data) == 2048) + for line in range(256): + items = [] + for val in data[line * 8:line * 8 + 8]: + assert(val >= 0 and val < 4096) + items.append('%03x' % val) + self.config[base + line] = (' '.join(items)) + '\n' + +class DesignFile: + def __init__(self, injson): + '''Load nextpnr-augmented JSON design file.''' + # load nextpnr-augmented JSON design file + with open(injson, 'r') as f: + self.design = json.load(f) + + # Create a table of BRAM WID by name + self.wid_by_name = {} + for name, cell in self.design['modules']['top']['cells'].items(): + if cell['type'] == 'DP16KD': + wid = int(cell['attributes']['WID'], 2) + self.wid_by_name[name] = wid + +COLUMN_MASK = 0x8080808080808080 +MAGIC = 0x0002040810204081 +ALL_MASK = 0xffffffffffffffff + +def transpose8x8(byte): + '''8×8 bit matrix transpose.''' + block8x8 = next(byte) | (next(byte) << 8) | (next(byte) << 16) | (next(byte) << 24) | (next(byte) << 32) | (next(byte) << 40) | (next(byte) << 48) | (next(byte) << 56) + return (((((block8x8 << (7 - col)) & COLUMN_MASK) * MAGIC) & ALL_MASK) >> 56 for col in range(8)) + +def interleave_rams32(ram): + ''' + Interleave 32 * 8 1-bit RAMs into a single 32-bit RAM. + ''' + result = [0] * 16384 + assert(len(ram) == 32) + + for addrh in range(16384 // 8): + p = [transpose8x8(ram[ofs + bit][addrh] for bit in range(0, 8)) for ofs in [0, 8, 16, 24]] + result[addrh * 8: addrh * 8 + 8] = [(a | (b << 8) | (c << 16) | (d << 24)) for (a, b, c, d) in zip(*p)] + + return result + +def deinterleave_ram32(ram): + ''' + Deinterleave a 32-bit RAM into 32 * 8 1-bit RAMs. + ''' + assert(len(ram) == 16384) + result = [[0] * 2048 for bit in range(32)] + + for addrh in range(16384 // 8): + s = ram[addrh * 8:addrh * 8 + 8] + for ofs in [0, 8, 16, 24]: + for bit, v in enumerate(transpose8x8((x >> ofs) & 0xff for x in s)): + result[bit + ofs][addrh] = v + + return result + +def bootrom_to_bram(rom): + ''' + Encode bootrom contents to a single BRAM as used in the ICS32 design. + ''' + bram = [0] * 2048 + for idx, val in enumerate(rom): + bram[idx * 4 + 0] = (val >> 0) & 0x1ff + bram[idx * 4 + 1] = (val >> 9) & 0x1ff + bram[idx * 4 + 2] = (val >> 18) & 0x1ff + bram[idx * 4 + 3] = (val >> 27) & 0x1ff + + return bram + +def load_binary(inprog, size): + '''Load binary data as an array of little endian 32-bit words.''' + with open(inprog, 'rb') as f: + progdata = bytearray(size * 4) + f.readinto(progdata) + return list(struct.unpack(f'<{size}I', progdata)) + +# --------------------------------------------------- Tests -------------------------------------------- +def ram_interleave_test(): + testdata = [(((65535 - x) << 16) | x) for x in range(16384)] + + rams = deinterleave_ram32(testdata) + assert(rams[0] == [170] * 2048) + assert(rams[1] == [204] * 2048) + assert(rams[2] == [240] * 2048) + assert(rams[3] == [0, 255] * 1024) + assert(rams[4] == [0, 0, 255, 255] * 512) + # ... + assert(rams[16] == [85] * 2048) + assert(interleave_rams32(rams) == testdata) + +def bootrom_test(config, design, firmware='../../firmware/boot_multi.bin'): + # check that contents of the specified bram match the bootrom as expected + wid = design.wid_by_name['ics32.bootloader.0.0.0'] + bootrom = config.parse_bram_data(wid) + data_check = open(firmware, 'rb').read() + import struct + + for idx in range(len(data_check) // 4): + a = bootrom[idx * 4 + 0] & 0x1ff + b = bootrom[idx * 4 + 1] & 0x1ff + c = bootrom[idx * 4 + 2] & 0x1ff + d = bootrom[idx * 4 + 3] & 0x1f + val = a | (b << 9) | (c << 18) | (d << 27) + + assert(struct.pack('(), p_clk.get(), p_in.get()); + flash.check_conflicts(p_in__en.get()); + p_out.set(io); + + return bb_p_flash__bb::eval(); + } + +private: + QSPIFlashSim flash; +}; + +// Audio blackbox: + +class AudioDACSampleSink { + +public: + static AudioDACSampleSink default_sink; + + void set_samples(int16_t left, int16_t right) { + samples_pending_fetch = true; + this->left = left; + this->right = right; + } + + bool get_samples(int16_t *left, int16_t *right) { + if (!samples_pending_fetch) { + return false; + } + + assert(left); + assert(right); + + *left = this->left; + *right = this->right; + samples_pending_fetch = false; + + return true; + } + +private: + bool samples_pending_fetch = false; + int16_t left = 0, right = 0; +}; + +AudioDACSampleSink AudioDACSampleSink::default_sink = AudioDACSampleSink(); + +class AudioDACBlackBox : public cxxrtl_design::bb_p_audio__dac__bb { + +public: + AudioDACBlackBox(AudioDACSampleSink sample_sink) : sample_sink(sample_sink) {}; + + bool eval() override { + if (posedge_p_clk()) { + sample_sink.set_samples(static_cast(p_in__l.get()), static_cast(p_in__r.get())); + } + + return bb_p_audio__dac__bb::eval(); + } + +private: + AudioDACSampleSink sample_sink; +}; + +namespace cxxrtl_design { + +std::unique_ptr bb_p_flash__bb::create(std::string name, metadata_map parameters, metadata_map attributes) { + return std::make_unique(Simulation::default_flash); +} + +std::unique_ptr bb_p_audio__dac__bb::create(std::string name, metadata_map parameters, metadata_map attributes) { + return std::make_unique(AudioDACSampleSink::default_sink); +} + +} + +void CXXRTLSimulation::preload_cpu_program(const std::vector &program) { + auto & cpu_ram_0 = top.memory_p_ics32_2e_cpu__ram_2e_cpu__ram__0_2e_mem; + auto & cpu_ram_1 = top.memory_p_ics32_2e_cpu__ram_2e_cpu__ram__1_2e_mem; + + size_t ipl_load_length = std::min((size_t)0x10000, program.size()); + + for (size_t i = 0; i < ipl_load_length / 4; i++) { + uint16_t low_word = program[i * 4] | program[i * 4 + 1] << 8; + uint16_t high_word = program[i * 4 + 2] | program[i * 4 + 3] << 8; + + cpu_ram_0[i] = value<16>{low_word}; + cpu_ram_1[i] = value<16>{high_word}; + } +} + +uint8_t CXXRTLSimulation::r() const { + return top.p_vga__r.get(); +} + +uint8_t CXXRTLSimulation::g() const { + return top.p_vga__g.get(); +} + +uint8_t CXXRTLSimulation::b() const { + return top.p_vga__b.get(); +} + +bool CXXRTLSimulation::hsync() const { + return top.p_vga__hsync.get(); +} + +bool CXXRTLSimulation::vsync() const { + return top.p_vga__vsync.get(); +} + +void CXXRTLSimulation::final() { +#if VCD_WRITE + vcd_stream.close(); +#endif +} + +bool CXXRTLSimulation::finished() const { + return false; +} + +void CXXRTLSimulation::step(uint64_t time) { + // using .set() has a severe performance impact (to profile and confirm) + top.p_clk__1x = value<1>{clk_1x}; + top.p_clk__2x = value<1>{clk_2x}; + + top.p_btn__u.set(button_user); + top.p_btn__1.set(button_1); + top.p_btn__2.set(button_2); + top.p_btn__3.set(button_3); + + top.step(); + +#if VCD_WRITE + update_trace(time); +#endif +} + +bool CXXRTLSimulation::get_samples(int16_t *left, int16_t *right) { + return AudioDACSampleSink::default_sink.get_samples(left, right); +} + +#if VCD_WRITE + +void CXXRTLSimulation::trace(const std::string &filename) { + vcd_stream.exceptions(std::ofstream::failbit | std::ofstream::badbit); + vcd_stream.open(filename, std::ios::out); + + cxxrtl::debug_items debug; + top.debug_info(debug); + + vcd.timescale(1, "ns"); + + // for now, just filter to a few signals of interest + const std::vector filter_names = {"pico", "clk", "reset", "valid", "ready"}; + + vcd.add(debug, [&](const std::string &name, const debug_item &item) { + for (auto filter_name : filter_names) { + if (name.find(filter_name) != std::string::npos) { + return true; + } + } + + return false; + }); +} + +void CXXRTLSimulation::update_trace(uint64_t time) { + vcd.sample(time); + + vcd_stream << vcd.buffer; + vcd.buffer.clear(); +} + +#endif diff --git a/dan-rodrigues_icestation-32/simulator/CXXRTLSimulation.hpp b/dan-rodrigues_icestation-32/simulator/CXXRTLSimulation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3e6f8f7bcb3c89dd2c2d3afb6076101e23e91f96 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/CXXRTLSimulation.hpp @@ -0,0 +1,52 @@ +#ifndef CXXRTLSimulation_hpp +#define CXXRTLSimulation_hpp + +#include +#include + +#include "Simulation.hpp" + +#include "cxxrtl_sim.h" + +#if VCD_WRITE +#include +#endif + +class CXXRTLSimulation: public Simulation { + +public: + void forward_cmd_args(int argc, const char * argv[]) override {}; + + void preload_cpu_program(const std::vector &program) override; + void step(uint64_t time) override; + +#if VCD_WRITE + void trace(const std::string &filename) override; +#endif + + uint8_t r() const override; + uint8_t g() const override; + uint8_t b() const override; + + bool hsync() const override; + bool vsync() const override; + + bool get_samples(int16_t *left, int16_t *right) override; + + void final() override; + + bool finished() const override; + +private: + cxxrtl_design::p_ics32__tb top; + std::unique_ptr flash; + +#if VCD_WRITE + cxxrtl::vcd_writer vcd; + std::ofstream vcd_stream; + + void update_trace(uint64_t time); +#endif +}; + +#endif /* CXXRTLSimulation_hpp */ diff --git a/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.cpp b/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c45edb58bc8910cd44098ab3b9359532e95800aa --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.cpp @@ -0,0 +1,505 @@ +// QSPIFlashSim.cpp +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "QSPIFlashSim.hpp" + +#include +#include +#include +#include +#include + +void QSPIFlashSim::load(const std::vector &source, size_t offset) { + size_t source_end_index = source.size() + offset; + assert(source_end_index < max_size); + data.resize(std::max(source_end_index, data.size())); + + defined_ranges.insert(Range(offset, source.size())); + + std::copy(source.begin(), source.end(), data.begin() + offset); +} + +uint8_t QSPIFlashSim::update(bool csn, bool clk, uint8_t new_io, uint8_t *new_output_en) { + bool csn_prev = this->csn; + this->csn = csn; + + bool still_deactivated = csn_prev && csn; + if (still_deactivated) { + return 0; + } + + bool clk_prev = this->clk; + this->clk = clk; + + bool should_deactivate = csn && !csn_prev; + bool should_activate = !csn && csn_prev; + if (should_deactivate) { + output_en = 0; + clk_on_deactivate = clk; + + if (bit_count != 0) { + log_if(enable_incomplete_byte_logging, + "/CS deasserted before transferring a complete byte"); + } + } else if (should_activate) { + state = (crm_enabled ? IOState::ADDRESS : IOState::CMD); + + if (!crm_enabled) { + cmd = CMD::UNDEFINED; + io_mode = (cmd_mode == CMDMode::QPI ? IOMode::QUAD : IOMode::SINGLE); + } + + read_index = 0; + read_buffer = 0; + byte_count = 0; + bit_count = 0; + output_en = 0; + + if (activated_previously && clk_on_deactivate != clk) { + log_if(enable_idle_clock_state_mismatch_logging, + "Activated clock state doesn't match previous deactivation state"); + } + + activated_previously = true; + } + + bool clk_rose = clk && !clk_prev; + bool clk_fell = !clk && clk_prev; + if (!csn && clk_rose) { + posedge_tick(new_io); + } else if (!csn && clk_fell) { + negedge_tick(new_io); + } + + if (new_output_en) { + *new_output_en = this->output_en; + } + + return io; +} + + +bool QSPIFlashSim::check_conflicts(uint8_t input_en) const { + uint8_t conflict_mask = output_en & input_en; + if (conflict_mask) { + log_error("IO conflict (" + format_hex(conflict_mask, 1) + ")"); + } + + return conflict_mask; +} + +// (this will be extended if DDR reads are added, where DATA state must work on posedge too) +void QSPIFlashSim::negedge_tick(uint8_t io) { + switch (state) { + case IOState::DATA: + if (bit_count == 0) { + if (!index_is_defined(read_index)) { + send_buffer = 0x00; + log_error("Read index undefined (index: " + format_hex(read_index, 6) + ")"); + } else { + uint8_t byte_to_send = data[read_index++]; + send_buffer = byte_to_send; + log_info("...sending byte: " + format_hex(byte_to_send)); + } + } + send_bits(); + break; + case IOState::REG_READ: + if (bit_count == 0) { + send_buffer = status_for_cmd(); + log_info("...sending register byte: " + format_hex(send_buffer)); + } + send_bits(); + break; + default: + break; + } +} + +QSPIFlashSim::CMD QSPIFlashSim::cmd_from_op(uint8_t cmd_op) { + static const std::set supported_cmds = { + CMD::READ_DATA, CMD::FAST_READ_DUAL_IO, CMD::FAST_READ_QUAD_IO, + CMD::WRITE_ENABLE_VOLATILE, + CMD::READ_STATUS_REG_2, CMD::WRITE_STATUS_REG_2, + CMD::RELEASE_POWER_DOWN, CMD::POWER_DOWN, + CMD::ENTER_QPI, CMD::EXIT_QPI, + CMD::READ_JEDEC_ID + }; + + static const std::map cmd_op_map = []() { + std::map map; + for (auto cmd : supported_cmds) { + uint8_t cmd_op = static_cast(cmd); + map.emplace(cmd_op, cmd); + } + + return map; + }(); + + + auto cmd = cmd_op_map.find(cmd_op); + if (cmd != cmd_op_map.end()) { + return cmd->second; + } else { + return CMD::UNDEFINED; + } +} + +void QSPIFlashSim::handle_new_cmd() { + uint8_t new_cmd_op = read_buffer; + + cmd = cmd_from_op(new_cmd_op); + log_info("CMD received: " + format_hex(new_cmd_op) + ": " + cmd_name(cmd)); + + if (powered_down && cmd != CMD::RELEASE_POWER_DOWN) { + log_error("Ignoring CMD as flash is in powered-down state"); + return; + } + + switch (cmd) { + case CMD::READ_DATA: + io_mode = IOMode::SINGLE; + transition_io_state(IOState::ADDRESS); + break; + case CMD::FAST_READ_DUAL_IO: + io_mode = IOMode::DUAL; + transition_io_state(IOState::ADDRESS); + break; + case CMD::FAST_READ_QUAD_IO: + if (quad_enabled()) { + io_mode = IOMode::QUAD; + transition_io_state(IOState::ADDRESS); + } else { + log_error("Ignoring Quad CMD: QE bit must be set first"); + transition_io_state(IOState::IDLE); + } + break; + case CMD::WRITE_ENABLE_VOLATILE: + log_info("...volatile write-enable bit set..."); + status_volatile_write_enable = true; + transition_io_state(IOState::IDLE); + break; + case CMD::READ_STATUS_REG_2: + io_mode = IOMode::SINGLE; + transition_io_state(IOState::REG_READ); + break; + case CMD::WRITE_STATUS_REG_2: + if (status_volatile_write_enable) { + io_mode = IOMode::SINGLE; + transition_io_state(IOState::REG_WRITE); + } else { + log_error("Ignoring attempt to write SR2 without write-enabling first"); + } + break; + case CMD::ENTER_QPI: + if (cmd_mode != CMDMode::QPI) { + log_info("Transitioning to QPI mode"); + } else { + log_info("Attempted to re-enter QPI mode"); + } + cmd_mode = CMDMode::QPI; + transition_io_state(IOState::IDLE); + break; + case CMD::EXIT_QPI: + if (cmd_mode != CMDMode::SPI) { + log_info("Transitioning to SPI mode"); + } else { + log_info("Attempted to re-enter SPI mode"); + } + cmd_mode = CMDMode::SPI; + transition_io_state(IOState::IDLE); + break; + case CMD::RELEASE_POWER_DOWN: + if (powered_down) { + log_info("Transitioning to powered-up state"); + } + powered_down = false; + transition_io_state(IOState::IDLE); + break; + case CMD::POWER_DOWN: + if (!powered_down) { + log_info("Transitioning to powered-down state"); + } + powered_down = true; + transition_io_state(IOState::IDLE); + break; + case CMD::READ_JEDEC_ID: + io_mode = IOMode::SINGLE; + transition_io_state(IOState::REG_READ); + break; + default: + log_error("Unrecognized command (" + format_hex(new_cmd_op) + ")"); + io_mode = IOMode::SINGLE; + transition_io_state(IOState::IDLE); + break; + } +} + +const std::string QSPIFlashSim::cmd_name(CMD cmd) { + static const std::map map = { + {CMD::UNDEFINED, "Undefined (this shouldn't be seen in normal use)"}, + {CMD::READ_DATA, "Read Data"}, + {CMD::FAST_READ_DUAL_IO, "Fast Read Dual I/O"}, + {CMD::FAST_READ_QUAD_IO, "Fast Read Quad I/O"}, + {CMD::WRITE_ENABLE_VOLATILE, "Write Enable (volatile)"}, + {CMD::READ_STATUS_REG_2, "Read Status Register 2"}, + {CMD::WRITE_STATUS_REG_2, "Write Status Register 2"}, + {CMD::RELEASE_POWER_DOWN, "Release Power-Down"}, + {CMD::POWER_DOWN, "Power-Down"}, + {CMD::ENTER_QPI, "Enter QPI"}, + {CMD::EXIT_QPI, "Exit QPI"}, + {CMD::READ_JEDEC_ID, "Read JEDEC Manufacturer ID"} + }; + + auto name = map.find(cmd); + if (name != map.end()) { + return name->second; + } else { + assert(false); + return "Unrecognized CMD"; + } +} + +bool QSPIFlashSim::quad_enabled() { + return status_2 & 0x02; +} + +// (QPI mode has configurable latency..) +uint8_t QSPIFlashSim::dummy_cycles_for_cmd() { + switch (cmd) { + case CMD::READ_DATA: + return 0; + case CMD::FAST_READ_DUAL_IO: + return 0; + case CMD::FAST_READ_QUAD_IO: + return (cmd_mode == CMDMode::QPI ? qpi_extra_dummy_cycles : 4); + default: + assert(false); + return 0; + } +} + +void QSPIFlashSim::posedge_tick(uint8_t io) { + switch (state) { + case IOState::CMD: + read_bits(io, cmd_mode == CMDMode::QPI ? 4 : 1); + if (byte_count == 1) { + handle_new_cmd(); + } + break; + case IOState::ADDRESS: + read_bits(io); + + if (bit_count == 0) { + read_index <<= 8; + read_index |= read_buffer; + } + + if (byte_count == 3) { + log_info("Address set to: " + format_hex(read_index)); + + transition_io_state(state_after_address()); + } + break; + case IOState::CRM_CMD: + read_bits(io); + if (byte_count == 1) { + const uint8_t crm_mask = 0x30; + const uint8_t crm_byte = 0x20; + bool new_crm_state = (read_buffer & crm_mask) == crm_byte; + + if (crm_enabled && !new_crm_state) { + log_info("CRM disabled"); + } else if (!crm_enabled && new_crm_state) { + log_info("CRM enabled for command: " + format_hex(static_cast(cmd))); + } else if (new_crm_state) { + log_info("...CRM still enabled..."); + } + + crm_enabled = new_crm_state; + + uint8_t cmd_dummy_cycles = dummy_cycles_for_cmd(); + transition_io_state(cmd_dummy_cycles ? IOState::DUMMY : IOState::DATA); + dummy_cycles = cmd_dummy_cycles; + } + break; + case IOState::DUMMY: + dummy_cycles--; + if (!dummy_cycles) { + transition_io_state(IOState::DATA); + } + break; + case IOState::REG_WRITE: + read_bits(io); + if (byte_count == 1) { + write_status_reg(); + transition_io_state(IOState::IDLE); + } + break; + case IOState::IDLE: + if (cmd == CMD::POWER_DOWN && powered_down) { + log_error("Ignoring previous power-down CMD as /CS wasn't deasserted after"); + powered_down = false; + } + break; + default: + break; + } +} + +uint8_t QSPIFlashSim::status_for_cmd() { + switch (cmd) { + case CMD::READ_STATUS_REG_2: + return status_2; + case CMD::READ_JEDEC_ID: + return static_cast(mfid); + default: + assert(false); + return 0; + } +} + +void QSPIFlashSim::write_status_reg() { + status_volatile_write_enable = false; + + switch (cmd) { + case CMD::WRITE_STATUS_REG_2: + log_info("SR2 updated to: " + format_hex(read_buffer)); + status_2 = read_buffer; + break; + default: + assert(false); + break; + } +} + +void QSPIFlashSim::transition_io_state(QSPIFlashSim::IOState new_state) { + byte_count = 0; + state = new_state; +} + +QSPIFlashSim::IOState QSPIFlashSim::state_after_address() { + switch (cmd) { + case CMD::READ_DATA: + return IOState::DATA; + case CMD::FAST_READ_DUAL_IO: case CMD::FAST_READ_QUAD_IO: + return IOState::CRM_CMD; + default: + assert(false); + return IOState::DATA; + } +} + +bool QSPIFlashSim::index_is_defined(size_t index) { + for (auto range : defined_ranges) { + if (range.contains(index)) { + return true; + } + } + + return false; +} + +uint8_t QSPIFlashSim::bit_count_for_mode() { + switch (io_mode) { + case IOMode::SINGLE: + return 1; + case IOMode::DUAL: + return 2; + case IOMode::QUAD: + return 4; + default: + assert(false); + return 0; + } +} + +uint8_t QSPIFlashSim::send_bits() { + return send_bits(bit_count_for_mode()); +} + +uint8_t QSPIFlashSim::send_bits(uint8_t count) { + assert(count <= 4); + + uint8_t mask = (1 << count) - 1; + uint8_t shift = 8 - count; + + // SPI transfer goes out on IO[1], not IO[0] + uint8_t out_shift = (count == 1 ? 6 : shift); + uint8_t out_mask = (count == 1 ? 1 << 1 : mask); + + uint8_t out = (send_buffer & (mask << shift)) >> out_shift; + send_buffer <<= count; + bit_count += count; + + if (bit_count >= 8) { + assert(bit_count == 8); + bit_count = 0; + } + + output_en = out_mask; + io = out; + + return out; +} + +void QSPIFlashSim::read_bits(uint8_t io) { + read_bits(io, bit_count_for_mode()); +} + +void QSPIFlashSim::read_bits(uint8_t io, uint8_t count) { + assert(count <= 4); + + read_buffer <<= count; + read_buffer |= io & ((1 << count) - 1); + bit_count += count; + + if (bit_count >= 8) { + assert(bit_count == 8); + bit_count = 0; + byte_count++; + } +} + +bool QSPIFlashSim::Range::contains(size_t index) const { + return index >= offset && index < (offset + length); +} + +bool QSPIFlashSim::Range::operator < (const Range &other) const { + return offset < other.offset || length < other.length; +} + +void QSPIFlashSim::log_if(bool condition, const std::string &message) const { + if (condition) { + log_info(message); + }; +} + +void QSPIFlashSim::log_info(const std::string &message) const { + if (enable_info_logging) { + std::cout << "QSPIFlashSim: " << message << std::endl; + } +} + +void QSPIFlashSim::log_error(const std::string &message) const { + if (enable_error_logging) { + std::cerr << "QSPIFlashSim error: " << message << std::endl; + } +} + +std::string QSPIFlashSim::format_hex(uint8_t integer) const { + return format_hex(integer, sizeof(uint8_t) * 2); +} + +template std::string QSPIFlashSim::format_hex(T integer) const { + return format_hex(integer, sizeof(T) * 2); +} + +std::string QSPIFlashSim::format_hex(uint32_t integer, uint32_t chars) const { + std::stringstream stream; + stream << std::hex << std::setfill('0') << std::setw(chars) << integer; + return stream.str(); +} diff --git a/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.hpp b/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3eaa30f16d70152cdca424130f5c4617464fb809 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/QSPIFlashSim.hpp @@ -0,0 +1,151 @@ +// QSPIFlashSim.hpp +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +// This is a minimal SPI/DSPI and eventually QSPI flash model +// The list of supported commands is defined below in CMD + +// Modelled after the W25Q128JV-DTR +// https://www.winbond.com/resource-files/w25q128jv_dtr%20revc%2003272018%20plus.pdf + +#ifndef QSPIFlashSim_hpp +#define QSPIFlashSim_hpp + +#include +#include +#include +#include + +class QSPIFlashSim { + +public: + enum class MFID: uint8_t { + WINBOND = 0xef, + ISSI = 0x9d + }; + + /// Initializes the flash model with a given maximum size. + QSPIFlashSim(size_t max_size = 0x1000000, MFID mfid = MFID::WINBOND) : mfid(mfid), max_size(max_size) {}; + + /// Loads the entire contents of source into the given offset in flash memory. + /// By default, errors are logged on attempts to access flash memory outside of the loaded regions. + void load(const std::vector &source, size_t offset); + + /// Updates the state of the model with the given inputs. + /// Returns the updated state of the IO pins after these updates. + /// Optionally sets the state of the output enable for the corresponding output bits using new_output_en. + uint8_t update(bool csn, bool clk, uint8_t io, uint8_t *new_output_en = NULL); + + /// Logs an error if the there is a conflict between the current output and input enables. + /// Returns true if there was a conflict. + bool check_conflicts(uint8_t input_en) const; + + /// If true, RELEASE_POWER_DOWN must be sent before using the flash + bool powered_down = true; + + bool enable_info_logging = false; + bool enable_error_logging = true; + + /// Opt-in cases for info logging + bool enable_incomplete_byte_logging = true; + bool enable_idle_clock_state_mismatch_logging = true; + +private: + struct Range { + Range(size_t offset, size_t length) : offset(offset), length(length) {} + size_t offset, length; + + bool operator < (const Range &other) const; + bool contains(size_t index) const; + }; + + enum class CMD: uint8_t { + READ_DATA = 0x03, FAST_READ_DUAL_IO = 0xbb, FAST_READ_QUAD_IO = 0xeb, + WRITE_ENABLE_VOLATILE = 0x50, + READ_STATUS_REG_2 = 0x35, WRITE_STATUS_REG_2 = 0x31, + ENTER_QPI = 0x38, EXIT_QPI = 0xff, + RELEASE_POWER_DOWN = 0xab, POWER_DOWN = 0xb9, + READ_JEDEC_ID = 0x9f, + UNDEFINED = 0x00 + }; + + enum class CMDMode { + SPI, QPI + }; + + enum class IOState { + CMD, ADDRESS, CRM_CMD, DUMMY, DATA, + REG_READ, REG_WRITE, + IDLE + }; + + enum class IOMode { + SINGLE, DUAL, QUAD + }; + + MFID mfid = MFID::WINBOND; + + bool csn = true, clk = false; + + size_t max_size; + std::vector data; + std::set defined_ranges; + + IOState state = IOState::CMD; + IOMode io_mode = IOMode::SINGLE; + CMDMode cmd_mode = CMDMode::SPI; + uint8_t io; + uint8_t bit_count_for_mode(); + + CMD cmd = CMD::UNDEFINED; + bool crm_enabled = false; + + CMD cmd_from_op(uint8_t cmd_op); + uint8_t dummy_cycles_for_cmd(); + void handle_new_cmd(); + const std::string cmd_name(CMD cmd); + + uint8_t read_buffer = 0; + uint8_t bit_count = 0; + uint8_t byte_count = 0; + uint32_t read_index = 0; + uint8_t dummy_cycles = 0; + bool clk_on_deactivate = false; + bool activated_previously = false; + + void posedge_tick(uint8_t io); + void negedge_tick(uint8_t io); + void read_bits(uint8_t io); + void read_bits(uint8_t io, uint8_t count); + + uint8_t qpi_extra_dummy_cycles = 0; + + bool status_volatile_write_enable = false; + uint8_t /*status_1 = 0x00,*/ status_2 = 0x00/*, status_3 = 0x00*/; + + void write_status_reg(); + uint8_t status_for_cmd(); + bool quad_enabled(); + + uint8_t output_en = 0; + uint8_t send_buffer = 0; + + uint8_t send_bits(); + uint8_t send_bits(uint8_t count); + + bool index_is_defined(size_t index); + + IOState state_after_address(); + void transition_io_state(IOState new_state); + + void log_error(const std::string &message) const; + void log_info(const std::string &message) const; + void log_if(bool condition, const std::string &message) const; + + std::string format_hex(uint8_t integer) const ; + std::string format_hex(uint32_t integer, uint32_t chars) const ; + template std::string format_hex(T integer) const ; +}; +#endif /* QSPIFlashSim_hpp */ diff --git a/dan-rodrigues_icestation-32/simulator/README.md b/dan-rodrigues_icestation-32/simulator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a96bd7a9c74edeceece15c142cccf0292083b5c --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/README.md @@ -0,0 +1,42 @@ +# VGA simulator + +This is the WIP simulator used to simulate the system with VGA output. + +## Prerequisites + +* Yosys (required for the included iCE40 cell sim libraries) +* SDL2 +* Verilator, if the Verilator implementation of the simulation is used + +## Usage + +### Verilator + +``` +make verilator_sim +./verilator_sim +``` + +### CXXRTL + +``` +make cxxrtl_sim +./cxxrtl_sim +``` + +## Quickstart + +An example script is included to build and run the sprites demo + Verilator sim in one step. Note that this example script assumes a GNU RISC-V toolchain is already installed and configured in its Makefile. + +``` +./build-and-run-sprites-demo.sh +``` +## Tool versions used for testing + +* Verilator: 4.034 +* CXXRTL (yosys commit): `74e93e08` + +## TODO + +* Refine and extend the `_trace` targets +* Any possible correctness / performance improvements for the yosys script used prior to `write_cxxrtl` \ No newline at end of file diff --git a/dan-rodrigues_icestation-32/simulator/Simulation.cpp b/dan-rodrigues_icestation-32/simulator/Simulation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f557066b53baa3c71a6b41232b87abf639ab54c5 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/Simulation.cpp @@ -0,0 +1,3 @@ +#include "Simulation.hpp" + +QSPIFlashSim Simulation::default_flash = QSPIFlashSim(); diff --git a/dan-rodrigues_icestation-32/simulator/Simulation.hpp b/dan-rodrigues_icestation-32/simulator/Simulation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3418097b8d097796787ceff57d5f865f8b48fcee --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/Simulation.hpp @@ -0,0 +1,50 @@ +#ifndef Simulation_hpp +#define Simulation_hpp + +#include +#include +#include + +#include "QSPIFlashSim.hpp" + +class Simulation { + +public: + static QSPIFlashSim default_flash; + + virtual ~Simulation() {} + + void operator = (Simulation const &s) = delete; + + bool clk_1x = false, clk_2x = false; + bool button_user = false; + bool button_1 = false, button_2 = false, button_3 = false; + bool button_y = false, button_up = false, button_down = false; + bool button_l = false, button_r = false; + bool button_x = false, button_a = false; + bool button_select = false, button_start = false; + + virtual void forward_cmd_args(int argc, const char * argv[]) = 0; + + virtual void preload_cpu_program(const std::vector &program) = 0; + virtual void step(uint64_t time) = 0; + +#if VCD_WRITE + virtual void trace(const std::string &filename) = 0; +#endif + + virtual uint8_t r() const = 0; + virtual uint8_t g() const = 0; + virtual uint8_t b() const = 0; + + virtual bool hsync() const = 0; + virtual bool vsync() const = 0; + + virtual bool get_samples(int16_t *left, int16_t *right) = 0; + + virtual void final() = 0; + + virtual bool finished() const = 0; +}; + +#endif /* Simulation_hpp */ diff --git a/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.cpp b/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cded75bc66f21342b68b0d4a9dd37251d5eaeb8 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.cpp @@ -0,0 +1,135 @@ +#include "VerilatorSimulation.hpp" + +#include + +#include "Vics32_tb__Syms.h" + +// verilator specific: called by $time in Verilog +static vluint64_t main_time = 0; +double sc_time_stamp() { + return main_time; +} + +void VerilatorSimulation::forward_cmd_args(int argc, const char *argv[]) { + Verilated::commandArgs(argc, argv); +} + +bool VerilatorSimulation::finished() const { + return Verilated::gotFinish(); +} + +void VerilatorSimulation::preload_cpu_program(const std::vector &program) { + auto ram_0 = tb->ics32_tb->ics32->cpu_ram->cpu_ram_0->mem; + auto ram_1 = tb->ics32_tb->ics32->cpu_ram->cpu_ram_1->mem; + + size_t ipl_load_length = std::min((size_t)0x10000, program.size()); + for (size_t i = 0; i < ipl_load_length / 4; i++) { + ram_0[i] = program[i * 4] | program[i * 4 + 1] << 8; + ram_1[i] = program[i * 4 + 2] | program[i * 4 + 3] << 8; + } +} + +void VerilatorSimulation::step(uint64_t time) { + main_time = time; + + tb->clk_1x = clk_1x; + tb->clk_2x = clk_2x; + + tb->btn_u = button_user; + tb->btn_1 = button_1; + tb->btn_2 = button_2; + tb->btn_3 = button_3; + + tb->btn_y = button_y; + tb->btn_up = button_up; + tb->btn_down = button_down; + + tb->btn_l = button_l; + tb->btn_r = button_r; + + tb->btn_x = button_x; + tb->btn_a = button_a; + + tb->btn_start = button_start; + tb->btn_select = button_select; + + tb->eval(); + + auto flash_bb = tb->ics32_tb->flash; + uint8_t out_en; + uint8_t io = flash.update(flash_bb->csn, flash_bb->clk, flash_bb->in, &out_en); + flash.check_conflicts(flash_bb->in_en); + + tb->eval(); + + flash_bb->out = io; + flash_bb->out_en = out_en; + +#if VCD_WRITE + trace_update(time); +#endif +} + +bool VerilatorSimulation::get_samples(int16_t *left, int16_t *right) { + auto dac = tb->ics32_tb->audio; + bool has_sample = dac->valid && dac->clk; + + if (has_sample) { + assert(left); + assert(right); + + *left = dac->in_l; + *right = dac->in_r; + } + + return has_sample; +} + +#if VCD_WRITE + +void VerilatorSimulation::trace_update(uint64_t time) { + assert(tfp); + tfp->dump((vluint64_t)time); +} + +void VerilatorSimulation::trace(const std::string &filename) { + Verilated::traceEverOn(true); + + tfp = std::unique_ptr(new VerilatedVcdC); + + tb->trace(tfp.get(), 99); + tfp->open(filename.c_str()); + assert(tfp->isOpen()); +} + +#endif + +uint8_t VerilatorSimulation::r() const { + return tb->vga_r; +} + +uint8_t VerilatorSimulation::g() const { + return tb->vga_g; +} + +uint8_t VerilatorSimulation::b() const { + return tb->vga_b; +} + +bool VerilatorSimulation::hsync() const { + return tb->vga_hsync; +} + +bool VerilatorSimulation::vsync() const { + return tb->vga_vsync; +} + +void VerilatorSimulation::final() { + tb->final(); + +#if VCD_WRITE + if (tfp) { + tfp->close(); + } +#endif +} diff --git a/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.hpp b/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0fb24ed5d8771676f5f9c8379430e413e1dbb0c6 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/VerilatorSimulation.hpp @@ -0,0 +1,50 @@ +#ifndef VerilatorSimulation_hpp +#define VerilatorSimulation_hpp + +#include + +#include "Simulation.hpp" +#include "obj_dir/Vics32_tb.h" + +#if VCD_WRITE +#include +#endif + +class VerilatorSimulation: public Simulation { + +public: + VerilatorSimulation() : flash(Simulation::default_flash) {} + + void forward_cmd_args(int argc, const char * argv[]) override; + + void preload_cpu_program(const std::vector &program) override; + void step(uint64_t time) override; + +#if VCD_WRITE + void trace(const std::string &filename) override; +#endif + + uint8_t r() const override; + uint8_t g() const override; + uint8_t b() const override; + + bool hsync() const override; + bool vsync() const override; + + bool get_samples(int16_t *left, int16_t *right) override; + + void final() override; + + bool finished() const override; + +private: + std::unique_ptr tb = std::unique_ptr(new Vics32_tb); + QSPIFlashSim flash; + +#if VCD_WRITE + std::unique_ptr tfp; + void trace_update(uint64_t time); +#endif +}; + +#endif /* VerilatorSimulation_hpp */ diff --git a/dan-rodrigues_icestation-32/simulator/ics32_tb.v b/dan-rodrigues_icestation-32/simulator/ics32_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..773d69bf2415564d4f89eafd87419adc0083bbdb --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/ics32_tb.v @@ -0,0 +1,217 @@ +// ics32_tb.v +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +`default_nettype none + +module ics32_tb( + input clk_1x, + input clk_2x, + + output [3:0] vga_r, + output [3:0] vga_g, + output [3:0] vga_b, + + output vga_hsync, + output vga_vsync, + output vga_de, + + output [7:0] led, + + input btn_u, + input btn_1, + input btn_2, + input btn_3, + + input btn_down, + input btn_up, + + input btn_l, + input btn_r, + + input btn_y, + input btn_x, + input btn_a, + + input btn_select, + input btn_start +); + ics32 #( + .CLK_1X_FREQ(`CLK_1X_WIDESCREEN), + .CLK_2X_FREQ(`CLK_2X_WIDESCREEN), + .ENABLE_WIDESCREEN(1), + .ENABLE_FAST_CPU(0), + .RESET_DURATION_EXPONENT(2), + .ADPCM_STEP_LUT_PATH("../hardware/adpcm_step_lut.hex"), + .BOOTLOADER_SIZE(512), + + // Vex is smaller but for simulation the Pico is faster (fully synchronous) + .USE_VEXRISCV(1), + + // The boot code configures the QSPI flash which is needed to access any flash resources such as audio + // If this isn't needed, this can be disabled to speed up the sim start time + .ENABLE_BOOTLOADER(1) + ) ics32 ( + .clk_1x(clk_1x), + .clk_2x(clk_2x), + .reset_1x(), + .reset_2x(), + .pll_locked(1), + + .vga_r(vga_r), + .vga_g(vga_g), + .vga_b(vga_b), + + .vga_hsync(vga_hsync), + .vga_vsync(vga_vsync), + .vga_de(vga_de), + + .pad_latch(pad_latch), + .pad_clk(pad_clk), + .pad_data(pad_read_data), + + .user_button(btn_u), + + .led(led), + + .flash_clk_ddr(flash_clk_ddr), + .flash_csn(flash_csn), + .flash_in_en(flash_in_en), + .flash_in(flash_in), + .flash_out(flash_out), + + .audio_output_valid(audio_valid), + .audio_output_l(audio_l), + .audio_output_r(audio_r) + ); + + // --- Gamepad reading --- + + // Only the 3 buttons on the breakboard are used as a partial gamepad + // This can be extended later with an actual gamepad PMOD + + wire [11:0] pad_btn = { + btn_r, btn_l, btn_x, btn_a, + btn_1, btn_3, btn_down, btn_up, + btn_start, btn_select, btn_y, btn_2 + }; + + wire [1:0] pad_read_data; + + wire pad_latch, pad_clk; + + // P1 is currently controllable in the sim + + mock_gamepad mock_gamepad( + .clk(clk_2x), + + .pad_clk(pad_clk), + .pad_btn(pad_btn), + .pad_latch(pad_latch), + + .pad_out(pad_read_data[0]) + ); + + // P2 isn't + + assign pad_read_data[1] = 0; + + + // --- Flash sim blackbox --- + + wire [1:0] flash_clk_ddr; + wire flash_csn; + wire [3:0] flash_in_en; + wire [3:0] flash_in; + wire [3:0] flash_out; + + reg [3:0] flash_in_r; + reg [3:0] flash_out_r; + reg flash_csn_r; + + assign flash_csn_bb = flash_csn_r; + assign flash_in_bb = flash_in_r; + assign flash_in_en_bb = flash_in_en; + wire [3:0] flash_out = flash_out_r; + + always @(posedge clk_2x) begin + flash_in_r <= flash_in; + flash_csn_r <= flash_csn; + + flash_out_r <= flash_out_bb; + end + + // This isn't quite what SB_IO does in DDR mode + // Since we're not actually pushing out DDR data streams, this could be replaced with a reimplementation of flash_clk_out + // There might be also a simpler way to do this in a way that works in both sims + + reg flash_clk_l, flash_clk_h; + assign flash_clk_bb = clk_2x ? flash_clk_h : flash_clk_l; + + always @(posedge clk_2x) begin + flash_clk_h <= flash_clk_ddr[0]; + end + + always @(negedge clk_2x) begin + flash_clk_l <= flash_clk_ddr[1]; + end + + // Parameters could be forwarded to the sim factory functions + // This could later be used to assume a certain power-up state (depending on icepack "-s" switch) + + wire flash_clk_bb; + wire flash_csn_bb; + wire [3:0] flash_in_bb; + wire [3:0] flash_in_en_bb; + wire [3:0] flash_out_bb; + + flash_bb flash( + .clk(flash_clk_bb), + .csn(flash_csn_bb), + .in_en(flash_in_en_bb), + .in(flash_in_bb), + .out(flash_out_bb), + .out_en() + ); + + // --- Audio DAC blackbox --- + + wire audio_valid; + wire [15:0] audio_l, audio_r; + + audio_dac_bb audio( + .clk(clk_2x), + .valid(audio_valid), + .in_l(audio_l), + .in_r(audio_r) + ); + +endmodule + +(* cxxrtl_blackbox *) +module flash_bb( + input clk /* verilator public */, + input csn /* verilator public */, + input [3:0] in_en /* verilator public */, + input [3:0] in /* verilator public */, + (* cxxrtl_sync *) output [3:0] out /* verilator public */, + (* cxxrtl_sync *) output [3:0] out_en /* verilator public */ +); + +/* verilator public_module */ + +endmodule + +(* cxxrtl_blackbox *) +module audio_dac_bb( + (* cxxrtl_edge = "p" *) input clk /* verilator public */, + input valid /* verilator public */, + input [15:0] in_l /* verilator public */, + input [15:0] in_r /* verilator public */ +); + +/* verilator public_module */ + +endmodule diff --git a/dan-rodrigues_icestation-32/simulator/main.cpp b/dan-rodrigues_icestation-32/simulator/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8621776dda9916f6f21fc0296994d5f53e757fe2 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/main.cpp @@ -0,0 +1,422 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "QSPIFlashSim.hpp" + +#include "tinywav.h" + +#ifdef SIM_VERILATOR + +#include "VerilatorSimulation.hpp" +typedef VerilatorSimulation SimulationImpl; +const std::string title = "verilator"; + +#elif defined(SIM_CXXRTL) + +#include "CXXRTLSimulation.hpp" +typedef CXXRTLSimulation SimulationImpl; +const std::string title = "cxxrtl"; + +#else + +#error Expected one of SIM_VERILATOR or SIM_CXXRTL to be defined + +#endif + +// Audio: + +#define AUDIO_SUPPORT + +void audio_callback(void *userdata, Uint8 *stream, int len); +std::deque audio_callback_samples; + +SDL_AudioDeviceID init_sdl_audio(void); +bool write_captured_audio(const std::string &path, const std::vector &samples); + +int main(int argc, const char **argv) { + if (argc < 2) { + std::cout << "Usage: " << std::endl; + return EXIT_SUCCESS; + } + + std::string wav_output_path = ""; + int64_t sim_cycles = std::numeric_limits::max(); + bool enable_audio_output = false; + + int opt = 0; + while ((opt = getopt_long(argc, (char **)argv, "w:t:na", NULL, NULL)) != -1) { + switch (opt) { + case 'w': +#ifdef AUDIO_SUPPORT + { + wav_output_path = optarg; + if (wav_output_path.empty()) { + std::cerr << "WAV output path must not be empty" << std::endl; + return EXIT_FAILURE; + } + } break; +#else + std::cerr << "Can't enable WAV dumping (wasn't built with AUDIO_SUPPORT)" << std::endl; + return EXIT_FAILURE; +#endif + case 'a': +#ifdef AUDIO_SUPPORT + enable_audio_output = true; + break; +#else + std::cerr << "Can't enable audio output (wasn't built with AUDIO_SUPPORT)" << std::endl; + return EXIT_FAILURE; +#endif + case 't': + sim_cycles = strtol(optarg, NULL, 10); + if (sim_cycles <= 0) { + std::cerr << "-t argument must be a non-zero positive integer" << std::endl; + return EXIT_FAILURE; + } + case '?': + return EXIT_FAILURE; + } + } + +#ifdef AUDIO_SUPPORT + bool wav_output_required = !wav_output_path.empty(); + bool audio_capture_required = enable_audio_output || wav_output_required; +#else + bool wav_output_required = false; + bool audio_capture_required = false; +#endif + + // 1. Load test program... + + if (optind >= argc) { + std::cerr << "Expected test program path after any options" << std::endl; + return EXIT_FAILURE; + } + + auto cpu_program_path = argv[optind]; + + std::ifstream cpu_program_stream(cpu_program_path, std::ios::binary); + if (cpu_program_stream.fail()) { + std::cerr << "Failed to open file: " << cpu_program_path << std::endl; + return EXIT_FAILURE; + } + + std::vector cpu_program(std::istreambuf_iterator(cpu_program_stream), {}); + cpu_program_stream.close(); + + if (cpu_program.size() % 4) { + std::cerr << "Program has irregular size: " << cpu_program.size() << std::endl; + return EXIT_FAILURE; + } + + const size_t flash_user_base = 0x200000; + const size_t flash_ipl_size = 0x10000; + + // Prepare flash before initializing the core sim instance + + QSPIFlashSim flash_sim; + flash_sim.powered_down = true; + flash_sim.enable_info_logging = false; + + if (cpu_program.size() < flash_ipl_size) { + cpu_program.resize(flash_ipl_size); + } + + flash_sim.load(cpu_program, flash_user_base); + Simulation::default_flash = flash_sim; + + SimulationImpl sim; + sim.forward_cmd_args(argc, argv); + sim.preload_cpu_program(cpu_program); + + // 2. Present an SDL window to simulate video output + + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) { + std::cerr << "SDL_Init() failed: " << SDL_GetError() << std::endl; + return EXIT_FAILURE; + } + + // SDL defaults to Metal API on MacOS and is incredibly slow to run SDL_RenderPresent() + // Hint to use OpenGL if possible +#if TARGET_OS_MAC + SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl"); +#endif + + // 848x480 is assumed (smaller video modes will still appear correctly) + + const auto active_width = 848; + const auto offscreen_width = 240; + const auto total_width = active_width + offscreen_width; + + const auto active_height = 480; + const auto offscreen_height = 37; + const auto total_height = active_height + offscreen_height; + + auto window = SDL_CreateWindow( + ("ics32-sim (" + title + ")").c_str(), + SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, + total_width, + total_height, + SDL_WINDOW_SHOWN + ); + + auto renderer = SDL_CreateRenderer(window, -1, 0); + SDL_RenderSetScale(renderer, 1, 1); + SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); + SDL_RenderClear(renderer); + + SDL_Texture *texture = SDL_CreateTexture(renderer, + SDL_PIXELFORMAT_RGB24, + SDL_TEXTUREACCESS_STATIC, + total_width, + total_height + ); + + const size_t rgb24_size = 3; + uint8_t *pixels = (uint8_t *)std::calloc(total_width * total_height * rgb24_size, sizeof(uint8_t)); + assert(pixels); + + int current_x = 0; + int current_y = 0; + size_t pixel_index = 0; + +#if VCD_WRITE + sim.trace("ics.vcd"); +#endif + + bool vga_hsync_previous = true; + bool vga_vsync_previous = true; + + // Audio init + + SDL_AudioDeviceID audio_device_id = 0; + if (enable_audio_output) { + audio_device_id = init_sdl_audio(); + } + + sim.clk_1x = 0; + sim.clk_2x = 0; + + uint64_t time = 0; + uint64_t previous_ticks = 0; + + const auto sdl_poll_interval = 10000; + auto sdl_poll_counter = sdl_poll_interval; + + std::vector audio_samples; + + while (!sim.finished() && (time / 2) < sim_cycles) { + sim.clk_2x = 0; + sim.step(time); + time++; + + sim.clk_2x = 1; + sim.clk_1x = time & 2; + sim.step(time); + time++; + + const auto extend_color = [] (uint8_t component) { + return component | component << 4; + }; + + // Plot current output pixel + bool active_display = sim.vsync() && sim.hsync(); + bool in_bounds = current_x < total_width && current_y < total_height; + if (active_display && in_bounds) { + pixels[pixel_index++] = extend_color(sim.r()); + pixels[pixel_index++] = extend_color(sim.g()); + pixels[pixel_index++] = extend_color(sim.b()); + } else if (active_display) { + std::cout << "Attempted to draw out of bounds pixel: (" << current_x << ", " << current_y << ")" << std::endl; + } + + current_x++; + + const auto update_pixel_index = [&] () { + pixel_index = current_y * total_width * rgb24_size; + }; + + if (!sim.hsync()) { + current_x = 0; + update_pixel_index(); + } + + if (sim.hsync() && !vga_hsync_previous) { + current_y++; + update_pixel_index(); + } + + vga_hsync_previous = sim.hsync(); + + if (!sim.vsync()) { + current_y = 0; + update_pixel_index(); + } + + if (sim.vsync() && !vga_vsync_previous) { + const auto stride = total_width * rgb24_size; + SDL_UpdateTexture(texture, NULL, pixels, stride); + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); + + // Simulate gamepad input with keyboard + + SDL_PumpEvents(); + const Uint8 *state = SDL_GetKeyboardState(NULL); + + sim.button_user = state[SDL_SCANCODE_LSHIFT]; + sim.button_1 = state[SDL_SCANCODE_RIGHT]; + sim.button_2 = state[SDL_SCANCODE_RSHIFT]; + sim.button_3 = state[SDL_SCANCODE_LEFT]; + + sim.button_up = state[SDL_SCANCODE_UP]; + sim.button_down = state[SDL_SCANCODE_DOWN]; + + sim.button_l = state[SDL_SCANCODE_Q]; + sim.button_r = state[SDL_SCANCODE_W]; + + sim.button_x = state[SDL_SCANCODE_A]; + sim.button_a = state[SDL_SCANCODE_S]; + sim.button_y = state[SDL_SCANCODE_Z]; + + sim.button_start = state[SDL_SCANCODE_E]; + sim.button_select = state[SDL_SCANCODE_R]; + + // Measure time spent to render frame + + uint64_t current_ticks = SDL_GetTicks(); + double delta = current_ticks - previous_ticks; + auto fps_estimate = 1 / (delta / 1000.f); + std::cout << "Frame drawn in: " << delta << "ms, " << fps_estimate << "fps" << std::endl; + previous_ticks = current_ticks; + } + + vga_vsync_previous = sim.vsync(); + + // Audio capture (optional) + + if (audio_capture_required) { + int16_t audio_left, audio_right; + if (sim.get_samples(&audio_left, &audio_right)) { + if (enable_audio_output) { + audio_callback_samples.push_back(audio_left); + audio_callback_samples.push_back(audio_right); + } + + if (wav_output_required) { + audio_samples.push_back(audio_left); + audio_samples.push_back(audio_right); + } + } + } + + // Exit check + + if (!(--sdl_poll_counter)) { + SDL_Event e; + if (SDL_PollEvent(&e) && (e.type == SDL_QUIT)) { + std::cout << "Quitting.." << "\n"; + break; + } + + sdl_poll_counter = sdl_poll_interval; + } + }; + + sim.final(); + + if (audio_device_id >= 2) { + SDL_CloseAudioDevice(audio_device_id); + } + + SDL_DestroyTexture(texture); + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); + + std::free(pixels); + + if (wav_output_required) { + if (!write_captured_audio(wav_output_path, audio_samples)) { + return EXIT_FAILURE; + } + } + + return EXIT_SUCCESS; +} + +// Audio related functions: + +bool write_captured_audio(const std::string &path, const std::vector &samples) { + TinyWav tw; + auto open_status = tinywav_open_write( + &tw, + 2, + 44100, + TW_INT16, + TW_INTERLEAVED, + path.c_str() + ); + + if (open_status) { + std::cerr << "Failed to open WAV file for writing: " << path << std::endl; + return false; + } + + // tinywav expects floats regardless of the encoded format + std::vector float_samples; + for (auto sample : samples) { + float_samples.push_back(((float)sample) / 32767); + } + + tinywav_write_f(&tw, &float_samples[0], (int)(float_samples.size() / 2)); + tinywav_close_write(&tw); + + return true; +} + +SDL_AudioDeviceID init_sdl_audio() { + SDL_AudioSpec want, have; + SDL_AudioDeviceID dev; + + SDL_memset(&want, 0, sizeof(want)); + want.freq = 44100; + want.format = AUDIO_S16; + want.channels = 2; + want.samples = 4096; + want.callback = audio_callback; + + dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0); + if (dev == 0) { + std::cerr << "SDL_OpenAudioDevice() failed: " << SDL_GetError() << std::endl; + } else { + if (have.format != want.format) { + std::cerr << "Could not open device with SDL AUDIO_S16 format" << std::endl; + } + + SDL_PauseAudioDevice(dev, 0); + } + + return dev; +} + +// SDL audio callback: + +void audio_callback(void *userdata, Uint8 *stream, int len) { + std::memset(stream, 0, len); + + size_t length = std::min((size_t)len / 4, audio_callback_samples.size() / 2); + int16_t *samples = (int16_t *)stream; + std::copy(audio_callback_samples.cbegin(), audio_callback_samples.cbegin() + length, samples); + audio_callback_samples.erase(audio_callback_samples.cbegin(), audio_callback_samples.cbegin() + length); + + std::cout << "Audio: copied " << length << " stereo samples" << "\n"; +} diff --git a/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.cpp b/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.cpp new file mode 100644 index 0000000000000000000000000000000000000000..460337db158237faf409478e1b7247f70e8ffea1 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.cpp @@ -0,0 +1,258 @@ +/** + * Copyright (c) 2015-2017, Martin Roth (mhroth@gmail.com) + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + + + +#include +#include +#if _WIN32 +#include +#include +#else +#include +#include +#endif +#include "tinywav.h" + +int tinywav_open_write(TinyWav *tw, + int16_t numChannels, int32_t samplerate, + TinyWavSampleFormat sampFmt, TinyWavChannelFormat chanFmt, + const char *path) { +#if _WIN32 + errno_t err = fopen_s(&tw->f, path, "w"); + assert(err == 0); +#else + tw->f = fopen(path, "w"); +#endif + assert(tw->f != NULL); + tw->numChannels = numChannels; + tw->totalFramesWritten = 0; + tw->sampFmt = sampFmt; + tw->chanFmt = chanFmt; + + // prepare WAV header + TinyWavHeader h; + h.ChunkID = htonl(0x52494646); // "RIFF" + h.ChunkSize = 0; // fill this in on file-close + h.Format = htonl(0x57415645); // "WAVE" + h.Subchunk1ID = htonl(0x666d7420); // "fmt " + h.Subchunk1Size = 16; // PCM + h.AudioFormat = (tw->sampFmt-1); // 1 PCM, 3 IEEE float + h.NumChannels = numChannels; + h.SampleRate = samplerate; + h.ByteRate = samplerate * numChannels * tw->sampFmt; + h.BlockAlign = numChannels * tw->sampFmt; + h.BitsPerSample = 8*tw->sampFmt; + h.Subchunk2ID = htonl(0x64617461); // "data" + h.Subchunk2Size = 0; // fill this in on file-close + + // write WAV header + fwrite(&h, sizeof(TinyWavHeader), 1, tw->f); + + return 0; +} + +int tinywav_open_read(TinyWav *tw, const char *path, TinyWavChannelFormat chanFmt, TinyWavSampleFormat sampFmt) { + tw->f = fopen(path, "rb"); + assert(tw->f != NULL); + + size_t ret = fread(&tw->h, sizeof(TinyWavHeader), 1, tw->f); + assert(ret > 0); + assert(tw->h.ChunkID == htonl(0x52494646)); // "RIFF" + assert(tw->h.Format == htonl(0x57415645)); // "WAVE" + assert(tw->h.Subchunk1ID == htonl(0x666d7420)); // "fmt " + + // skip over any other chunks before the "data" chunk + while (tw->h.Subchunk2ID != htonl(0x64617461)) { // "data" + fseek(tw->f, 4, SEEK_CUR); + fread(&tw->h.Subchunk2ID, 4, 1, tw->f); + } + assert(tw->h.Subchunk2ID == htonl(0x64617461)); // "data" + fread(&tw->h.Subchunk2Size, 4, 1, tw->f); + + tw->numChannels = tw->h.NumChannels; + tw->chanFmt = chanFmt; + tw->sampFmt = sampFmt; + + tw->totalFramesWritten = tw->h.Subchunk2Size / (tw->numChannels * tw->sampFmt); + return 0; +} + +int tinywav_read_f(TinyWav *tw, void *data, int len) { // returns number of frames read + switch (tw->sampFmt) { + case TW_INT16: { //TODO(gio): implement TW_INT16 conversion + int16_t *z = (int16_t *) alloca(tw->numChannels*len*sizeof(int16_t)); + switch (tw->chanFmt) { + case TW_INTERLEAVED: { + const float *const x = (const float *const) data; + for (int i = 0; i < tw->numChannels*len; ++i) { + z[i] = (int16_t) (x[i] * 32767.0f); + } + break; + } + case TW_INLINE: { + const float *const x = (const float *const) data; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = (int16_t) (x[j*len+i] * 32767.0f); + } + } + break; + } + case TW_SPLIT: { + const float **const x = (const float **const) data; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = (int16_t) (x[j][i] * 32767.0f); + } + } + break; + } + default: return 0; + } + + tw->totalFramesWritten += len; + return (int) fwrite(z, sizeof(int16_t), tw->numChannels*len, tw->f); + } + case TW_FLOAT32: { + size_t samples_read = 0; + float *interleaved_data = (float *) alloca(tw->numChannels*len*sizeof(float)); + samples_read = fread(interleaved_data, sizeof(float), tw->numChannels*len, tw->f); + switch (tw->chanFmt) { + case TW_INTERLEAVED: { // channel buffer is interleaved e.g. [LRLRLRLR] + memcpy(data, interleaved_data, tw->numChannels*len*sizeof(float)); + return (int) (samples_read/tw->numChannels); + } + case TW_INLINE: { // channel buffer is inlined e.g. [LLLLRRRR] + for (int i = 0, pos = 0; i < tw->numChannels; i++) { + for (int j = i; j < len * tw->numChannels; j += tw->numChannels, ++pos) { + ((float *) data)[pos] = interleaved_data[j]; + } + } + return (int) (samples_read/tw->numChannels); + } + case TW_SPLIT: { // channel buffer is split e.g. [[LLLL],[RRRR]] + for (int i = 0, pos = 0; i < tw->numChannels; i++) { + for (int j = 0; j < len; j++, ++pos) { + ((float **) data)[i][j] = interleaved_data[j*tw->numChannels + i]; + } + } + return (int) (samples_read/tw->numChannels); + } + default: return 0; + } + } + default: return 0; + } + + return len; +} + +void tinywav_close_read(TinyWav *tw) { + fclose(tw->f); + tw->f = NULL; +} + +size_t tinywav_write_f(TinyWav *tw, void *f, int len) { + switch (tw->sampFmt) { + case TW_INT16: { + int16_t *z = (int16_t *) alloca(tw->numChannels*len*sizeof(int16_t)); + switch (tw->chanFmt) { + case TW_INTERLEAVED: { + const float *const x = (const float *const) f; + for (int i = 0; i < tw->numChannels*len; ++i) { + z[i] = (int16_t) (x[i] * 32767.0f); + } + break; + } + case TW_INLINE: { + const float *const x = (const float *const) f; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = (int16_t) (x[j*len+i] * 32767.0f); + } + } + break; + } + case TW_SPLIT: { + const float **const x = (const float **const) f; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = (int16_t) (x[j][i] * 32767.0f); + } + } + break; + } + default: return 0; + } + + tw->totalFramesWritten += len; + return fwrite(z, sizeof(int16_t), tw->numChannels*len, tw->f); + break; + } + case TW_FLOAT32: { + float *z = (float *) alloca(tw->numChannels*len*sizeof(float)); + switch (tw->chanFmt) { + case TW_INTERLEAVED: { + tw->totalFramesWritten += len; + return fwrite(f, sizeof(float), tw->numChannels*len, tw->f); + } + case TW_INLINE: { + const float *const x = (const float *const) f; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = x[j*len+i]; + } + } + break; + } + case TW_SPLIT: { + const float **const x = (const float **const) f; + for (int i = 0, k = 0; i < len; ++i) { + for (int j = 0; j < tw->numChannels; ++j) { + z[k++] = x[j][i]; + } + } + break; + } + default: return 0; + } + + tw->totalFramesWritten += len; + return fwrite(z, sizeof(float), tw->numChannels*len, tw->f); + } + default: return 0; + } +} + +void tinywav_close_write(TinyWav *tw) { + uint32_t data_len = tw->totalFramesWritten * tw->numChannels * tw->sampFmt; + + // set length of data + fseek(tw->f, 4, SEEK_SET); + uint32_t chunkSize_len = 36 + data_len; + fwrite(&chunkSize_len, sizeof(uint32_t), 1, tw->f); + + fseek(tw->f, 40, SEEK_SET); + fwrite(&data_len, sizeof(uint32_t), 1, tw->f); + + fclose(tw->f); + tw->f = NULL; +} + +bool tinywav_isOpen(TinyWav *tw) { + return (tw->f != NULL); +} diff --git a/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.h b/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.h new file mode 100644 index 0000000000000000000000000000000000000000..0964f8a5b953811bfabc973a954c6b6c5da36230 --- /dev/null +++ b/dan-rodrigues_icestation-32/simulator/tinywav/tinywav.h @@ -0,0 +1,129 @@ +/** + * Copyright (c) 2015-2017, Martin Roth (mhroth@gmail.com) + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + + + +#ifndef _TINY_WAV_ +#define _TINY_WAV_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// http://soundfile.sapp.org/doc/WaveFormat/ +typedef struct TinyWavHeader { + uint32_t ChunkID; + uint32_t ChunkSize; + uint32_t Format; + uint32_t Subchunk1ID; + uint32_t Subchunk1Size; + uint16_t AudioFormat; + uint16_t NumChannels; + uint32_t SampleRate; + uint32_t ByteRate; + uint16_t BlockAlign; + uint16_t BitsPerSample; + uint32_t Subchunk2ID; + uint32_t Subchunk2Size; +} TinyWavHeader; + +typedef enum TinyWavChannelFormat { + TW_INTERLEAVED, // channel buffer is interleaved e.g. [LRLRLRLR] + TW_INLINE, // channel buffer is inlined e.g. [LLLLRRRR] + TW_SPLIT // channel buffer is split e.g. [[LLLL],[RRRR]] +} TinyWavChannelFormat; + +typedef enum TinyWavSampleFormat { + TW_INT16 = 2, // two byte signed integer + TW_FLOAT32 = 4 // four byte IEEE float +} TinyWavSampleFormat; + +typedef struct TinyWav { + FILE *f; + TinyWavHeader h; + int16_t numChannels; + uint32_t totalFramesWritten; + TinyWavChannelFormat chanFmt; + TinyWavSampleFormat sampFmt; +} TinyWav; + +/** + * Open a file for writing. + * + * @param numChannels The number of channels to write. + * @param samplerate The sample rate of the audio. + * @param sampFmt The sample format (e.g. 16-bit integer or 32-bit float). + * @param chanFmt The channel format (how the channel data is layed out in memory) + * @param path The path of the file to write to. The file will be overwritten. + * + * @return The error code. Zero if no error. + */ +int tinywav_open_write(TinyWav *tw, + int16_t numChannels, int32_t samplerate, + TinyWavSampleFormat sampFmt, TinyWavChannelFormat chanFmt, + const char *path); + +/** + * Open a file for reading. + * + * @param sampFmt The sample format (e.g. 16-bit integer or 32-bit float) + * that the file should be converted to. + * @param chanFmt The channel format (how the channel data is layed out in memory) when read. + * @param path The path of the file to read. + * + * @return The error code. Zero if no error. + */ +int tinywav_open_read(TinyWav *tw, const char *path, + TinyWavChannelFormat chanFmt, TinyWavSampleFormat sampFmt); + +/** + * Read sample data from the file. + * + * @param data A pointer to the data structure to read to. This data is expected to have the + * correct memory layout to match the specifications given in tinywav_open_read(). + * @param len The number of frames to read. + */ +int tinywav_read_f(TinyWav *tw, void *data, int len); + +/** Stop reading the file. The Tinywav struct is now invalid. */ +void tinywav_close_read(TinyWav *tw); + +/** + * Write sample data to file. + * + * @param tw The TinyWav structure which has already been prepared. + * @param f A pointer to the sample data to write. + * @param len The number of frames to write. + * + * @return The total number of samples written to file. + */ +size_t tinywav_write_f(TinyWav *tw, void *f, int len); + +/** Stop writing to the file. The Tinywav struct is now invalid. */ +void tinywav_close_write(TinyWav *tw); + +/** Returns true if the Tinywav struct is available to write or write. False otherwise. */ +bool tinywav_isOpen(TinyWav *tw); + +#ifdef __cplusplus +} +#endif + +#endif // _TINY_WAV_ diff --git a/dan-rodrigues_icestation-32/software/README.md b/dan-rodrigues_icestation-32/software/README.md new file mode 100644 index 0000000000000000000000000000000000000000..298066ec3e88b3273b6ac1b4089c8610886daaca --- /dev/null +++ b/dan-rodrigues_icestation-32/software/README.md @@ -0,0 +1,108 @@ +# Demo software + +## Prerequisites + +* GNU RISC-V toolchain +* GNU Make (any version >= 3.81 should work) + +The `CROSS` variable in `common/cross.mk` must be set according to the name of your RISC-V installation. + +## Simulation + +`cd` into any demo directory and run `make sim`. This will: + +1. Build the demo software +2. Build the simulator +3. Launch the demo in the simulator + +## Running on FPGA + +In any demo directory, running one of the following commands will build and flash the software onto a given board: + +``` +make icebreaker_prog +``` + +``` +make ulx3s_prog +``` + +## Games + +### [Super Miyamoto Sprint](https://github.com/dan-rodrigues/super-miyamoto-sprint) + +Platformer game inspired by other games of the period. Because of its size it is [hosted separately here](https://github.com/dan-rodrigues/super-miyamoto-sprint). It clones this repo as a submodule. + +![Super Miyamoto Sprint game](screenshots/sms.png) + +### [IceTetris](/software/tetris/) + +Tetris inspired game combining sprites for the falling blocks and tilemaps for the rest of the playfield. Based on tetris4terminals. + +![IceTetris game](screenshots/tetris.png) + +## Demos + +### [affine_platformer](/software/affine_platformer/) + +Demo with various system features combined into a single scene including: + +* Affine layer, which renders the rotating and scaling 8 ball. +* Copper coprocessor, used to do a raster-timed toggle between the affine 8 ball background and the horizontally scrolling ground. +* Sprites, displaying the hero character and the horizontally scrolling clouds. +* Gamepad input, used to make the hero jump and to manually zoom the affine layer that displays the 8 ball. + +![Affine platformer demo](screenshots/affine_platformer.png) + +### [audio_drumkit](/software/audio_drumkit/) + +Interactive audio demo with 3 preloaded samples triggered by 3 buttons. + +* Audio can be dumped to WAV by passing the `-w` switch to the sim (i.e. `-w sim.wav`). +* Audio can also be played back in realtime by passing the `-a` switch but it will sound choppy at less than 60FPS. + +![Audio drumkit demo](screenshots/audio_drumkit.png) + +### [aquarium](/software/aquarium/) + +A demo that demonstrates the animation of large numbers of sprites and shows how sprite priority interacts with scroll layers. + +### [copper_polygon](/software/copper_polygon/) + +Copper coprocessor demo using horizontal raster effects to draw a rotated, scaled polygon. The copper has a simple instruction set dedicated to performing raster-synced writes to the VDP. The CPU transforms a polygon each frame, traces its edges, then emits copper machine code used to toggle the display of a static opaque layer. The effective result is a layer mask in the shape of the transformed polygon. + +The copper is implemented in vdp_copper.v and has 4kbyte of instruction memory. + +![Platformer demo](screenshots/copper_polygon.png) + +### [copper_bars](/software/copper_bars/) + +Copper coprocessor demo using vertical raster effects only. This is a simpler demo than the above polygon demo and displays squished and strecthed "raster bars" by altering a single color each line. The bar layer itself is as a single-colored opaque layer. The apparent movement and alpha blending is done with raster effects. + +![Platformer demo](screenshots/copper_bars_squish.png) + +### [platformer](/software/platformer/) + +Controllable character sprite that can walk and jump with simple physics on a static playfield. This uses the gamepad interface which is currently mocked using the 3 buttons on the iCEBreaker. + +![Platformer demo](screenshots/platformer.png) + +### [sprites](/software/sprites/) + +Animated sprites demo. A palette-based PNG file is converted to the ics-32 format and compiled into the demo. This demo also shows alpha blending of sprites onto a variable backgroud color. + +![sprites demo](screenshots/sprites.png) + +### [hello_world](/software/hello_world/) + +Minimal example using a single scrolling layer to display monochrome text. + +![hello_world demo](screenshots/hello_world.png) + +## Acknowledgements + +* IceTetris by [vmedea](https://github.com/dan-rodrigues/icestation-32/pull/12), sound effects by [pan14](https://freesound.org/people/pan14/sounds/263133/) and [solernix](https://freesound.org/people/solernix/sounds/540902/). +* [Rotating crystal graphics](https://opengameart.org/content/rotating-crystal-animation-8-step) by qubodup +* [8x8 font](https://github.com/dhepper/font8x8) by dhepper +* [Super Miyamoto spritesheet](https://opengameart.org/content/super-miyamoto) by Lars Doucet & Sean Choate. Minor modifications were made for the `platformer` demo. +* [Super Mario World Redrawn](https://www.romhacking.net/hacks/2919/) game mod by IceGoom diff --git a/dan-rodrigues_icestation-32/software/affine_platformer/fg_map.h b/dan-rodrigues_icestation-32/software/affine_platformer/fg_map.h new file mode 100644 index 0000000000000000000000000000000000000000..7c4f38ab8d9dbe8b40f0f7533df872b5c7774c4b --- /dev/null +++ b/dan-rodrigues_icestation-32/software/affine_platformer/fg_map.h @@ -0,0 +1,3591 @@ +#include +#include + +const uint16_t fg_map[] = { + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01ea, + 0x07ea, + 0x0122, + 0x0122, + 0x03d7, + 0x03d6, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01d6, + 0x01d7, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x07ec, + 0x01dc, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x7586, + 0x7786, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x03dc, + 0x05ec, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01ea, + 0x07ea, + 0x0122, + 0x0122, + 0x03e7, + 0x03e6, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01e6, + 0x01e7, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x07dc, + 0x01ec, + 0x0122, + 0x0122, + 0x0122, + 0x01d8, + 0x01d9, + 0x7186, + 0x7386, + 0x03d9, + 0x03d8, + 0x0122, + 0x0122, + 0x0122, + 0x03ec, + 0x05dc, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122 +}; + +const size_t fg_map_length = 3584; diff --git a/dan-rodrigues_icestation-32/software/affine_platformer/main.c b/dan-rodrigues_icestation-32/software/affine_platformer/main.c new file mode 100644 index 0000000000000000000000000000000000000000..ad89bcaa258eb814972dc3acef627fb4f0453d4f --- /dev/null +++ b/dan-rodrigues_icestation-32/software/affine_platformer/main.c @@ -0,0 +1,642 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "vdp.h" +#include "math_util.h" +#include "assert.h" +#include "gamepad.h" +#include "math_util.h" + +#include "copper.h" +#include "vdp_regs.h" + +#include +#include + +#include "fg_tiles.h" +#include "fg_map.h" +#include "fg_palette.h" + +#include "ball_tiles.h" +#include "ball_palette.h" + +#include "sprite_tiles.h" +#include "sprite_palette.h" + +#include "cloud_small_tiles.h" +#include "cloud_small_palette.h" + +// VRAM layout + +static const uint16_t SCROLL_TILE_BASE = 0x5000; +static const uint16_t SCROLL_MAP_BASE = 0x4000; +static const uint16_t SPRITE_TILE_BASE = 0x7000; + +// Hero sprites + +typedef enum { + RUN0, + RUN1, + RUN2, + + JUMP_RISING, + JUMP_FALLING, + + LOOKING_UP, + + LOOKING_SCREEN_DIRECT, + LOOKING_SCREEN_LEFT, + LOOKING_SCREEN_RIGHT, + + PEACE_SIGN +} HeroFrame; + +static const HeroFrame HERO_IDLE_FRAME = RUN2; + +static const uint8_t HERO_FRAME_MAX_TILES = 2; +static const int16_t HERO_FRAME_TILES_END = -1; + +typedef struct { + HeroFrame frame; + + int16_t x_offset; + int16_t y_offset; + + uint8_t x_flip; + + // const int16_t tiles[HERO_FRAME_MAX_TILES] + const int16_t tiles[2]; +} HeroFrameLayout; + +// Sprite positioning / updating + +static const int32_t Q_1 = 0x10000; + +typedef enum { + LEFT, RIGHT +} SpriteDirection; + +typedef struct { + int16_t x, y; + int16_t x_fraction, y_fraction; +} SpritePosition; + +typedef struct { + int32_t x, y; +} SpriteVelocity; + +typedef struct { + HeroFrame frame; + uint32_t frame_counter; + + SpritePosition position; + SpriteVelocity velocity; + SpriteDirection direction; +} Hero; + +void hero_update_state(Hero *hero, uint16_t pad, uint16_t pad_edge); +void draw_hero_sprites(Hero *hero, int16_t sprite_tile); +void sa_apply_velocity(SpriteVelocity *velocity, SpritePosition *position); + +// Cloud sprites + +static const uint16_t CLOUD_SPRITE_TILE_BASE = 0x020; +static const uint16_t CLOUD_SPRITE_TILE_SMALL = CLOUD_SPRITE_TILE_BASE; +static const uint16_t CLOUD_SPRITE_TILE_BIG = CLOUD_SPRITE_TILE_BASE + 0x20; +static const uint8_t CLOUD_PALETTE_ID = 6; + +void draw_cloud_sprites(void); +void draw_small_cloud_sprite(int16_t x, int16_t y); +void draw_big_cloud_sprite(int16_t x, int16_t y); + +void write_cached_sprite_meta(uint16_t x_block, uint16_t y_block, uint16_t g_block); +void upload_cached_sprite_meta(void); +static uint16_t *sprite_meta_cache_pointer; +static uint16_t sprite_meta[256 * 3]; + +// Affine ball + +static const int16_t AFFINE_Q_1 = 0x400; +static const int16_t BALL_ANGLE_DELTA = 4; + +void update_ball(uint16_t pad); +void scale_ball(uint16_t pad); +void configure_ball_affine(void); + +int32_t current_ball_speed(void); + +int16_t ball_angle = 0; +int16_t ball_inverse_scale = 0x1000; +bool ball_auto_scale = true; +bool ball_auto_scaling_up = true; +int32_t ball_auto_scale_idle_counter; + +int16_t affine_pretranslate_x, affine_pretranslate_y; +int16_t affine_a, affine_b, affine_c, affine_d; +int16_t affine_scroll_x, affine_scroll_y; + +// Scroll context + +int32_t scroll_x_acc = 0; + +void write_copper_program(void); +void queue_16x16_sprite_upload(uint16_t source_tile_base, uint16_t sprite_tile); + +static const int16_t GROUND_OFFSET = 432; + +int main() { + vdp_enable_copper(false); + + // Affine layer must be disabled to write VRAM + vdp_enable_layers(0); + + // Foregound is a 512x512 map tiled repeatedly + vdp_set_wide_map_layers(0); + vdp_set_alpha_over_layers(0); + + const int16_t map_y_offset = -48; + vdp_set_layer_scroll(0, 0, map_y_offset); + + vdp_set_vram_increment(1); + vdp_seek_vram(0); + vdp_fill_vram(0x8000, 0x0000); + + // Odd words contain 8x8 tiles + + const uint8_t ball_palette_id = 3; + + vdp_seek_vram(0x0001); + vdp_set_vram_increment(2); + + for (size_t i = 0; i < ball_tiles_length / 2; i++) { + // Graphics are 4bit indexes and must be padded to the 8bit format + uint32_t row = ((uint32_t *)ball_tiles)[i]; + + for (uint32_t x = 0; x < 4; x++) { + uint8_t pixel_lo = (row >> 28) & 0xf; + pixel_lo |= (pixel_lo ? ball_palette_id << 4 : 0); + + uint8_t pixel_hi = (row >> 24) & 0xf; + pixel_hi |= (pixel_lo ? ball_palette_id << 4 : 0); + + vdp_write_vram(pixel_lo | pixel_hi << 8); + row <<= 8; + } + } + + // Even words contain a 128x128 map that references the above tiles + + const uint16_t affine_map_dimension = 128; + const uint16_t affine_ball_dimension = 16; + + for (uint16_t y = 0; y < affine_ball_dimension; y++) { + // Address needs to be reset every line as the 128x128 bitmap occupies a portion at top left + // The full affine map size is 1024x1024 pixels + vdp_seek_vram(y * affine_map_dimension); + + for (uint16_t x = 0; x < affine_ball_dimension / 2; x++) { + uint16_t map = y * affine_ball_dimension + (x * 2); + uint16_t map_word = map | (map + 1) << 8; + vdp_write_vram(map_word); + } + } + + vdp_set_vram_increment(1); + + // Affine palette + + vdp_write_palette_range(ball_palette_id * 0x10, ball_palette_length, ball_palette); + + // Foreground tiles + + vdp_set_layer_tile_base(0, SCROLL_TILE_BASE); + + // Load tileset to the 3rd "page" of 128 tiles, where it is expected + vdp_seek_vram(SCROLL_TILE_BASE + 0x1800); + vdp_write_vram_block(fg_tiles, fg_tiles_length); + + // Foreground map + + vdp_set_layer_map_base(0, SCROLL_MAP_BASE); + + vdp_seek_vram(SCROLL_MAP_BASE); + vdp_write_vram_block(fg_map, fg_map_length); + + // Foreground palette + + const uint8_t palette_size = 0x10; + const uint8_t map_palette_id = 2; + + vdp_write_palette_range(map_palette_id * palette_size, palette_size, fg_palette); + + // Sprites + + vdp_set_sprite_tile_base(SPRITE_TILE_BASE); + + vdp_seek_palette(0); + vdp_write_palette_range(0, palette_size, sprite_palette); + + // Cloud sprites + + vdp_seek_vram(SPRITE_TILE_BASE + CLOUD_SPRITE_TILE_BASE * 0x10); + vdp_write_vram_block(cloud_small_tiles, cloud_small_tiles_length); + + // Cloud palette + + vdp_write_palette_range(CLOUD_PALETTE_ID * 0x10, cloud_small_palette_length, &cloud_small_palette[0]); + + // Background color + + const uint16_t background_color = 0xf488; + vdp_set_single_palette_color(0, background_color); + + SpritePosition hero_position = {.x = 560, .y = GROUND_OFFSET, .x_fraction = 0, .y_fraction = 0}; + SpriteVelocity hero_velocity = {0, 0}; + + Hero hero = { + .frame = HERO_IDLE_FRAME, + .frame_counter = 0, + .direction = RIGHT, + .position = hero_position, + .velocity = hero_velocity + }; + + // Gamepad state + + uint16_t p1_pad = 0; + uint16_t p1_pad_edge = 0; + + vdp_clear_all_sprites(); + + while (true) { + sprite_meta_cache_pointer = &sprite_meta[0]; + + update_ball(p1_pad); + hero_update_state(&hero, p1_pad, p1_pad_edge); + scroll_x_acc += current_ball_speed(); + + draw_hero_sprites(&hero, 0); + draw_cloud_sprites(); + + vdp_wait_frame_ended(); + vdp_enable_copper(false); + + upload_cached_sprite_meta(); + + write_copper_program(); + vdp_enable_copper(true); + + pad_read(&p1_pad, NULL, &p1_pad_edge, NULL); + } + + return 0; +} + +void hero_update_state(Hero *hero, uint16_t pad, uint16_t pad_edge) { + SpriteVelocity *velocity = &hero->velocity; + SpritePosition *position = &hero->position; + + // Jumping + + const int32_t jump_initial_speed = 5 * Q_1; + + bool grounded = hero->position.y >= GROUND_OFFSET; + + if (grounded && (pad_edge & GP_B)) { + velocity->y = -jump_initial_speed; + } + + // Gravity + + const int32_t gravity_delta_high = Q_1 / 2; + const int32_t gravity_delta_low = Q_1 / 6; + const int32_t fall_velocity_max = 5 * Q_1; + + // Holding button B sustains the jump for longer + + int32_t gravity_delta = (pad & GP_B ? gravity_delta_low : gravity_delta_high); + + velocity->y += gravity_delta; + velocity->y = MIN(velocity->y, fall_velocity_max); + + // Update hero position according to newly set velocity + + velocity->x = current_ball_speed(); + sa_apply_velocity(velocity, position); + + // Correct position if hero has "fallen through the ground" + + if (position->y > GROUND_OFFSET) { + velocity->y = 0; + position->y = GROUND_OFFSET; + position->y_fraction = 0; + } + + // Animation + + grounded = hero->position.y >= GROUND_OFFSET; + + if (grounded) { + // Idle state or walking + + switch (hero->frame) { + case RUN0: case RUN1: case RUN2: + break; + default: + hero->frame = HERO_IDLE_FRAME; + break; + } + + int32_t frame_counter = hero->frame_counter; + + if (frame_counter < 0) { + const int32_t hero_default_frame_duration = 5 * Q_1; + frame_counter = hero_default_frame_duration; + hero->frame = (hero->frame == RUN2 ? RUN0 : hero->frame + 1); + } else if (hero->velocity.x != 0) { + int32_t frame_counter_delta = ABS(hero->velocity.x); + frame_counter -= frame_counter_delta; + } else { + hero->frame = HERO_IDLE_FRAME; + } + + hero->frame_counter = frame_counter; + } else { + // Frame for jumping or falling + + hero->frame = (SIGN(velocity->y) ? JUMP_RISING : JUMP_FALLING); + } +} + +void sa_apply_velocity(SpriteVelocity *velocity, SpritePosition *position) { + // X position is fixed, so only update Y position here + int32_t y_full = position->y * Q_1 | (position->y_fraction & 0xffff); + y_full += velocity->y; + position->y_fraction = y_full & 0xffff; + position->y = y_full / Q_1; +} + +void draw_hero_sprites(Hero *hero, int16_t sprite_tile) { + static const HeroFrameLayout hero_frames[] = { + {RUN0, 0, -1, 0, {0x000, 0x0e0}}, + {RUN1, 0, 0, 0, {0x002, 0x0e0}}, + {RUN2, 0, 0, 0, {0x004, 0x0e0}}, + + {JUMP_RISING, 0, 0, 0, {0x006, 0x0e8}}, + {JUMP_FALLING, 0, 0, 0, {0x1a4, 0x18e}}, + + {LOOKING_UP, 0, 0, 0, {0x004, 0x140}}, + + {LOOKING_SCREEN_DIRECT, 0, 0, 0, {0x00e, 0x108}}, + {LOOKING_SCREEN_LEFT, 0, 0, 0, {0x00e, 0x0e0}}, + {LOOKING_SCREEN_RIGHT, 0, 0, 1, {0x00e, 0x0e0}}, + + {PEACE_SIGN, 0, 0, 0, {0x16e, 0x166}}, + }; + + static const size_t hero_frame_count = sizeof(hero_frames) / sizeof(HeroFrameLayout); + + const uint8_t hero_palette = 0; + const uint8_t hero_priority = 3; + const int16_t hero_y_offset = -18; + + const HeroFrameLayout *sprite_frame = NULL; + for (uint16_t i = 0; i < hero_frame_count; i++) { + if (hero_frames[i].frame == hero->frame) { + sprite_frame = &hero_frames[i]; + break; + } + } + + assert(sprite_frame); + + int16_t sprite_y = hero->position.y; + + for (uint8_t i = 0; i < HERO_FRAME_MAX_TILES; i++) { + int16_t frame_tile = sprite_frame->tiles[i]; + if (frame_tile == HERO_FRAME_TILES_END) { + break; + } + + // sprite metadata + + uint16_t x_block = hero->position.x + sprite_frame->x_offset; + x_block &= 0x3ff; + bool hero_needs_flip = (hero->direction == RIGHT); + bool frame_needs_flip = sprite_frame->x_flip; + x_block |= (hero_needs_flip ^ frame_needs_flip ? SPRITE_X_FLIP : 0); + + uint16_t y_block = sprite_y + sprite_frame->y_offset; + y_block += hero_y_offset; + y_block &= 0x1ff; + y_block |= SPRITE_16_TALL | SPRITE_16_WIDE; + + uint16_t g_block = sprite_tile; + g_block |= hero_priority << SPRITE_PRIORITY_SHIFT | hero_palette << SPRITE_PAL_SHIFT; + + // upload sprite graphics (only one hero frame is in VRAM at any given time) + queue_16x16_sprite_upload(frame_tile, sprite_tile); + + // set sprite metadata (pointing to the graphics uploaded in previous step) + write_cached_sprite_meta(x_block, y_block, g_block); + + sprite_y -= 16; + sprite_tile += 2; + } +} + +void queue_16x16_sprite_upload(uint16_t source_tile_base, uint16_t sprite_tile) { + vdp_seek_vram(SPRITE_TILE_BASE + sprite_tile * 0x10); + + const uint16_t *source_tiles = sprite_tiles + source_tile_base * 0x10; + const uint16_t frame_row_word_size = 0x10 * 2; + + // first row (upper 16x8 half) + vdp_write_vram_block(source_tiles, frame_row_word_size); + + // second row (lower 16x8 half) + const uint16_t sprite_row_word_stride = 0x20 * 0x10 / 2; + vdp_seek_vram(SPRITE_TILE_BASE + (0x10 + sprite_tile) * 0x10); + vdp_write_vram_block(source_tiles + sprite_row_word_stride, frame_row_word_size); +} + +void update_ball(uint16_t pad) { + scale_ball(pad); + configure_ball_affine(); + + ball_angle += BALL_ANGLE_DELTA; +} + +void configure_ball_affine() { + const int16_t ball_dimension = 128; + const int16_t ball_x_offset = 256; + + affine_pretranslate_x = ball_dimension / 2; + affine_pretranslate_y = ball_dimension / 2; + + int16_t scroll = (AFFINE_Q_1 * ball_dimension) / ball_inverse_scale; + + affine_scroll_x = -ball_x_offset; + affine_scroll_y = scroll / 2 - GROUND_OFFSET; + + int16_t sint = sys_multiply(sin(ball_angle), ball_inverse_scale) / SIN_MAX; + int16_t cost = sys_multiply(cos(ball_angle), ball_inverse_scale) / SIN_MAX; + + affine_a = cost; + affine_b = sint; + affine_c = -sint; + affine_d = cost; +} + +void write_copper_program() { + cop_ram_seek(0); + + // Top part of screen: enable affine layer + cop_set_target_x(0); + cop_wait_target_y(0); + cop_write(&VDP_AFFINE_TRANSLATE_X, affine_scroll_x); + cop_write(&VDP_AFFINE_TRANSLATE_Y, affine_scroll_y); + cop_write(&VDP_AFFINE_PRETRANSLATE_X, affine_pretranslate_x); + cop_write(&VDP_AFFINE_PRETRANSLATE_Y, affine_pretranslate_y); + cop_write(&VDP_MATRIX_A, affine_a); + cop_write(&VDP_MATRIX_B, affine_b); + cop_write(&VDP_MATRIX_C, affine_c); + cop_write(&VDP_MATRIX_D, affine_d); + cop_write(&VDP_LAYER_ENABLE, AFFINE | SCROLL0 | SPRITES); + + // Bottom half of screen: disable affine layer and enable SCROLL0 instead + // The scroll must be set here because the same regs are used for the affine scroll + cop_wait_target_y(GROUND_OFFSET); + cop_write(&VDP_HSCROLL_BASE[0], scroll_x_acc / Q_1); + cop_write(&VDP_VSCROLL_BASE[0], -48); + cop_write(&VDP_LAYER_ENABLE, SCROLL0 | SPRITES); + + cop_jump(0); +} + +int32_t current_ball_speed() { + // 128 * pi = 402.1 + const int16_t ball_circumference = 402; + + int32_t scaled_circumference = (ball_circumference * AFFINE_Q_1) / ball_inverse_scale; + int32_t ground_delta = ((scaled_circumference * BALL_ANGLE_DELTA) * Q_1) / SIN_PERIOD; + + return ground_delta; +} + +void scale_ball(uint16_t pad) { + const int16_t scale_delta = 8; + const int16_t scale_min = 0x0100; + const int16_t scale_max = 0x1000; + + const int32_t idle_counter = 60 * 3; + + if (pad & GP_LEFT && (~pad & GP_RIGHT)) { + ball_inverse_scale = MIN(ball_inverse_scale + scale_delta, scale_max); + ball_auto_scale = false; + } + + if (pad & GP_RIGHT && (~pad & GP_LEFT)) { + ball_inverse_scale = MAX(ball_inverse_scale - scale_delta, scale_min); + ball_auto_scale = false; + } + + if (ball_auto_scale_idle_counter) { + ball_auto_scale_idle_counter--; + } else if (ball_auto_scale) { + if (ball_auto_scaling_up) { + ball_inverse_scale -= scale_delta; + ball_auto_scaling_up = (ball_inverse_scale > scale_min); + + if (!ball_auto_scaling_up) { + ball_auto_scale_idle_counter = idle_counter; + } + } else { + ball_inverse_scale += scale_delta; + ball_auto_scaling_up = !(ball_inverse_scale < scale_max); + + if (ball_auto_scaling_up) { + ball_auto_scale_idle_counter = idle_counter; + } + } + } +} + +void draw_cloud_sprites() { + int16_t cloud_small_x_offset = -(scroll_x_acc / Q_1 / 2); + int16_t cloud_big_x_offset = -(scroll_x_acc / Q_1 / 3); + + static const SpritePosition cloud_base_positions_small[] = { + {.x = 8, .y = 32}, {.x = 280, .y = 128}, {.x = 385, .y = 48}, {.x = 530, .y = 160} + }; + + static const SpritePosition cloud_base_positions_big[] = { + {.x = 32, .y = 80}, {.x = 430, .y = 130}, {.x = 760, .y = 192}, {.x = 870, .y = 8} + }; + + for (uint32_t i = 0; i < sizeof(cloud_base_positions_big) / sizeof(SpritePosition); i++) { + draw_big_cloud_sprite( + cloud_base_positions_big[i].x + cloud_big_x_offset, + cloud_base_positions_big[i].y + ); + } + + for (uint32_t i = 0; i < sizeof(cloud_base_positions_small) / sizeof(SpritePosition); i++) { + draw_small_cloud_sprite( + cloud_base_positions_small[i].x + cloud_small_x_offset, + cloud_base_positions_small[i].y + ); + } +} + +void draw_small_cloud_sprite(int16_t x_base, int16_t y_base) { + uint16_t x_block = x_base; + x_block &= 0x3ff; + + uint16_t y_block = y_base; + y_block &= 0x1ff; + y_block |= SPRITE_16_TALL | SPRITE_16_WIDE; + + uint16_t g_block = CLOUD_SPRITE_TILE_SMALL; + g_block |= 0 << SPRITE_PRIORITY_SHIFT | CLOUD_PALETTE_ID << SPRITE_PAL_SHIFT; + + write_cached_sprite_meta(x_block, y_block, g_block); + write_cached_sprite_meta((x_block + 16) & 0x3ff, y_block, g_block + 2); + write_cached_sprite_meta((x_block + 32) & 0x3ff, y_block, g_block + 4); + write_cached_sprite_meta((x_block + 48) & 0x3ff, y_block, g_block + 6); +} + +void draw_big_cloud_sprite(int16_t x_base, int16_t y_base) { + for (uint8_t y = 0; y < 3; y++) { + for (uint8_t x = 0; x < 7; x++) { + uint16_t x_block = x_base + x * 16; + x_block &= 0x3ff; + + uint16_t y_block = y_base + y * 16; + y_block &= 0x1ff; + y_block |= SPRITE_16_TALL | SPRITE_16_WIDE; + + uint16_t g_block = (CLOUD_SPRITE_TILE_BIG + y * 0x20 + x * 2); + g_block |= 0 << SPRITE_PRIORITY_SHIFT | CLOUD_PALETTE_ID << SPRITE_PAL_SHIFT; + + write_cached_sprite_meta(x_block, y_block, g_block); + } + } +} + +void write_cached_sprite_meta(uint16_t x_block, uint16_t y_block, uint16_t g_block) { + *sprite_meta_cache_pointer++ = x_block; + *sprite_meta_cache_pointer++ = y_block; + *sprite_meta_cache_pointer++ = g_block; +} + +void upload_cached_sprite_meta() { + vdp_seek_sprite(0); + + for (uint16_t *pointer = &sprite_meta[0]; pointer < sprite_meta_cache_pointer; pointer += 3) { + vdp_write_sprite_meta(pointer[0], pointer[1], pointer[2]); + } +} diff --git a/dan-rodrigues_icestation-32/software/aquarium/main.c b/dan-rodrigues_icestation-32/software/aquarium/main.c new file mode 100644 index 0000000000000000000000000000000000000000..07bf639f209a52013b7bdfedd124a6aea933b989 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/aquarium/main.c @@ -0,0 +1,229 @@ +// main.c: demonstrate use of sprite priorities +// +// Copyright (C) 2020 Mara "vmedea" +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "vdp.h" +#include "font.h" +#include "rand.h" + +// dev-friendly way to define gfx inline +#define L(a,b,c,d,e,f,g,h) (e << 12) | (f << 8) | (g << 4) | (h << 0), (a << 12) | (b << 8) | (c << 4) | (d << 0) +#define _ 0 // transparent +#define a 10 +#define b 11 +#define c 12 +#define d 13 +#define e 14 +#define f 15 + +static const uint16_t gfx[][16] = { + { + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(1,1,1,1,1,1,1,2), + L(2,2,2,2,2,2,2,2), + }, + { + L(_,_,_,_,_,_,_,_), + L(_,_,2,2,_,2,_,_), + L(_,2,3,1,2,2,_,_), + L(_,2,1,1,1,2,_,_), + L(_,2,1,1,2,2,_,_), + L(_,_,2,2,_,2,_,_), + L(_,_,_,_,_,_,_,_), + L(_,_,_,_,_,_,_,_), + }, + { + L(_,_,_,_,_,_,_,_), + L(_,_,2,2,2,_,2,_), + L(_,2,1,1,1,2,2,_), + L(_,2,3,1,1,1,2,_), + L(_,2,1,1,1,1,2,_), + L(_,2,1,1,1,2,2,_), + L(_,_,2,2,2,_,2,_), + L(_,_,_,_,_,_,_,_), + }, + { + L(_,_,_,_,_,_,_,_), + L(_,2,2,2,2,_,2,_), + L(2,1,1,1,1,2,2,_), + L(2,3,1,1,1,1,2,_), + L(2,1,1,1,1,1,2,_), + L(2,1,1,1,1,2,2,_), + L(_,2,2,2,2,_,2,_), + L(_,_,_,_,_,_,_,_), + }, + { + L(_,_,2,2,_,_,_,2), + L(_,2,1,1,2,_,2,2), + L(2,1,3,1,1,2,1,2), + L(2,1,1,1,1,1,1,2), + L(2,1,1,1,1,1,1,2), + L(2,1,1,1,1,2,1,2), + L(_,2,1,1,2,_,2,2), + L(_,_,2,2,_,_,_,2), + }, +}; +#undef _ +#undef a +#undef b +#undef c +#undef d +#undef e +#undef f +#undef L + +const uint16_t bg_color = 0xf001; +// bright colors +static const uint16_t fg_colors1[] = { + 0xff22, 0xff82, 0xfff2, 0x0000, // layers + 0xf33f, 0xf73f, 0xfb2f, 0xff4f, // sprites + 0xffff, 0xf88f, // info +}; +// dimmed colors +static const uint16_t fg_colors2[] = { + 0xff00, 0xfe60, 0xfcc0, 0x0000, // layers + 0xf00f, 0xf60e, 0xeb0e, 0xff0f, // sprites + 0xffff, 0xf8ff, // info +}; + +const uint8_t LAYER_COUNT = 3; +const uint16_t TILE_VRAM_BASE = 0x0000; +const uint16_t LAYER_MAP_BASE[3] = {0x1000, 0x3000, 0x5000}; +const uint16_t BASE_X = 712; +const uint16_t BASE_Y = 300; + +const uint16_t NSPRITES = 40; +const uint16_t POSEXP = 3; // fixed-point precision of sprite positions to allow for fractional speeds +const uint16_t INFO_X = 22; +const uint16_t INFO_Y = 2; +// aquarium walls +const uint16_t X_MIN = 250; +const uint16_t X_MAX = 450; +const uint16_t Y_MIN = 185; +const uint16_t Y_MAX = 325; + +static void print(uint8_t palette_id, const char *string) { + uint16_t attr = palette_id << SCROLL_MAP_PAL_SHIFT; + while (*string) { + vdp_write_vram((*string & 0xff) | attr); + string++; + } +} + +int main() { + uint8_t enabled_layers = SCROLL0 | SCROLL1 | SCROLL2 | (LAYER_COUNT == 4 ? SCROLL3 : 0) | SPRITES; + + vdp_enable_layers(enabled_layers); + vdp_set_wide_map_layers(SCROLL0 | SCROLL1 | SCROLL2); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + vdp_clear_all_sprites(); + vdp_set_sprite_tile_base(TILE_VRAM_BASE); + + for (uint8_t i = 0; i < LAYER_COUNT; i++) { + vdp_set_layer_map_base(i, LAYER_MAP_BASE[i]); + vdp_set_layer_tile_base(i, TILE_VRAM_BASE); + } + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + upload_font(TILE_VRAM_BASE); + vdp_seek_vram(TILE_VRAM_BASE + 128 * 16); + vdp_write_vram_block((const uint16_t*)gfx, sizeof(gfx)); + + // palette setup + vdp_set_single_palette_color(0, bg_color); + for (uint8_t i = 0; i < sizeof(fg_colors1) / sizeof(fg_colors1[0]); i++) { + vdp_set_single_palette_color(i * 0x10 + 1, fg_colors1[i]); + vdp_set_single_palette_color(i * 0x10 + 2, fg_colors2[i]); + vdp_set_single_palette_color(i * 0x10 + 3, 0xf000); // non-tranparent black + } + + // aquarium decoration + for (uint8_t i = 0; i < LAYER_COUNT; i++) { + uint8_t palette_id = i; + + for (uint8_t y = 0; y < 9; ++y) { + vdp_seek_vram(LAYER_MAP_BASE[i] + y * 64); + for (uint8_t x = 0; x < 9; ++x) { + if ((x < 2 || x > 6) || (y < 2 || y > 6)) + vdp_write_vram(128 | (palette_id << SCROLL_MAP_PAL_SHIFT)); + else + vdp_write_vram(0); + } + } + } + + // legend + vdp_seek_vram(LAYER_MAP_BASE[0] + INFO_Y * 64 + INFO_X); + print(9, "Sprite Priority"); + for (uint8_t i = 0; i < 4; ++i) { + vdp_seek_vram(LAYER_MAP_BASE[0] + (INFO_Y + 2 + i * 2) * 64 + INFO_X + 3); + vdp_write_vram((129 + i) | ((i + 4) << SCROLL_MAP_PAL_SHIFT)); + vdp_write_vram(' '); + vdp_write_vram(' '); + vdp_write_vram(' '); + vdp_write_vram(' '); + vdp_write_vram(' '); + vdp_write_vram(' '); + vdp_write_vram(('0' + i) | (8 << SCROLL_MAP_PAL_SHIFT)); + } + + // fixed layer scroll offsets + for (uint8_t i = 0; i < LAYER_COUNT; i++) { + vdp_set_layer_scroll(i, BASE_X - i * 7, BASE_Y - i * 7); + } + + // initial fish positioning + int16_t sprite_x[NSPRITES], sprite_y[NSPRITES]; + int16_t sprite_dx[NSPRITES], sprite_dy[NSPRITES]; + uint16_t sprite_g[NSPRITES]; + for (uint8_t idx = 0; idx < NSPRITES; ++idx) { + sprite_x[idx] = (X_MIN + randbits(8)) << POSEXP; + sprite_y[idx] = (Y_MIN + randbits(7)) << POSEXP; + int16_t speed = (idx & 3) + 2; + sprite_dx[idx] = (idx & 1) ? -speed : speed; + sprite_dy[idx] = (idx & 2) ? -1 : 1; + sprite_g[idx] = (129 + (idx & 3)) | (((idx & 3) + 4) << SPRITE_PAL_SHIFT) | ((idx & 3) << SPRITE_PRIORITY_SHIFT); + } + + while (true) { + vdp_seek_sprite(0); + for (uint8_t idx = 0; idx < NSPRITES; ++idx) { + // subtract an offset when flipped to prevent a jarring jump; even 8x8 sprites are flipped as if they are 16x16, this compensates for that + bool xflip = sprite_dx[idx] > 0; + uint16_t xofs = xflip ? -8 : 0; + vdp_write_sprite_meta( + (((sprite_x[idx] >> POSEXP) + xofs) & 0x3ff) | (xflip ? SPRITE_X_FLIP : 0), + ((sprite_y[idx] >> POSEXP) & 0x1ff), sprite_g[idx]); + } + + for (uint8_t idx = 0; idx < NSPRITES; ++idx) { + sprite_x[idx] += sprite_dx[idx]; + sprite_y[idx] += sprite_dy[idx]; + if (sprite_x[idx] < (X_MIN << POSEXP) && sprite_dx[idx] < 0) + sprite_dx[idx] = -sprite_dx[idx]; + if (sprite_x[idx] > (X_MAX << POSEXP) && sprite_dx[idx] > 0) + sprite_dx[idx] = -sprite_dx[idx]; + if (sprite_y[idx] < (Y_MIN << POSEXP) && sprite_dy[idx] < 0) + sprite_dy[idx] = -sprite_dy[idx]; + if (sprite_y[idx] > (Y_MAX << POSEXP) && sprite_dy[idx] > 0) + sprite_dy[idx] = -sprite_dy[idx]; + } + + vdp_wait_frame_ended(); + } +} diff --git a/dan-rodrigues_icestation-32/software/audio_drumkit/main.c b/dan-rodrigues_icestation-32/software/audio_drumkit/main.c new file mode 100644 index 0000000000000000000000000000000000000000..fd002523a15ec7ef67ff0c66353e4b36770f1813 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/audio_drumkit/main.c @@ -0,0 +1,109 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "audio.h" + +#include "vdp.h" +#include "font.h" +#include "vdp_print.h" +#include "gamepad.h" + +#include "snare.h" +#include "kick.h" +#include "cymbal.h" + +const uint16_t MAP_VRAM_BASE = 0x4000; +const uint16_t TILE_VRAM_BASE = 0x0000; + +void print_channel_states(void); + +int main() { + // Configure video (to display channel status) + + vdp_enable_layers(SCROLL0); + vdp_set_wide_map_layers(SCROLL0); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + vdp_set_layer_scroll(0, 0, 0); + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + vdp_set_layer_tile_base(0, TILE_VRAM_BASE); + upload_font(TILE_VRAM_BASE); + + const uint16_t bg_color = 0xf033; + const uint16_t fg_color = 0xffff; + + vdp_set_single_palette_color(0, bg_color); + vdp_set_single_palette_color(1, fg_color); + + vdp_set_layer_map_base(0, MAP_VRAM_BASE); + vdp_seek_vram(MAP_VRAM_BASE); + + vp_print_init(); + + // Configure channel context + + static const int16_t *sample_pointers[] = {snare, kick, cymbal}; + const size_t sample_lengths[] = {snare_length, kick_length, cymbal_length}; + + const int8_t volume = 0x0c; + + for (uint32_t i = 0; i < sizeof(sample_pointers) / sizeof(int16_t*); i++) { + volatile AudioChannel *ch = &AUDIO->channels[i]; + audio_set_aligned_addresses(ch, sample_pointers[i], sample_lengths[i]); + ch->pitch = 0x1000; + ch->flags = 0; + ch->volumes.left = volume; + ch->volumes.right = volume; + } + + uint16_t p1_pad_edge = 0, p1_pad = 0; + + // Play channels according to user input + + while (true) { + pad_read(&p1_pad, NULL, &p1_pad_edge, NULL); + + if (!AUDIO_STATUS_BUSY) { + uint16_t start_mask = 0; + start_mask |= (p1_pad_edge & GP_B) ? 0x01 : 0; + start_mask |= (p1_pad_edge & GP_LEFT) ? 0x02 : 0; + start_mask |= (p1_pad_edge & GP_RIGHT) ? 0x04 : 0; + AUDIO_GB_PLAY = start_mask; + } + + vdp_wait_frame_ended(); + print_channel_states(); + } +} + +void print_channel_states() { + const uint8_t base_x = 2; + const uint8_t base_y = 2; + + static const char *sample_labels[] = {"Snare ", "Kick ", "Cymbal"}; + + vp_printf(base_x, base_y, 0, SCROLL0, MAP_VRAM_BASE, "Channel Sample Status"); + vp_printf(base_x, base_y + 1, 0, SCROLL0, MAP_VRAM_BASE, "--------- --------- ---------"); + + for (uint32_t i = 0; i < 3; i++) { + uint8_t y = base_y + i * 2 + 2; + char *status = (AUDIO_STATUS_PLAYING & (1 << i)) ? "Playing" : "Stopped"; + + vp_printf(base_x, y, 0, SCROLL0, MAP_VRAM_BASE, + "%d %s %s", + i, sample_labels[i], status); + } + + vp_printf(base_x, base_y + 10, 0, SCROLL0, MAP_VRAM_BASE, "Press buttons to play"); +} diff --git a/dan-rodrigues_icestation-32/software/blinky/main.c b/dan-rodrigues_icestation-32/software/blinky/main.c new file mode 100644 index 0000000000000000000000000000000000000000..5f8bf76927adaffe54aa937b25a0fb4113216e31 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/blinky/main.c @@ -0,0 +1,21 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "vdp.h" +#include "status.h" + +int main() { + // Blink leds 0..7 along to the vsync clock + uint32_t frame = 0; + while (true) { + status_set_leds(frame / 16); + vdp_wait_frame_ended(); + frame += 1; + } +} diff --git a/dan-rodrigues_icestation-32/software/common/font.c b/dan-rodrigues_icestation-32/software/common/font.c new file mode 100644 index 0000000000000000000000000000000000000000..25f7a67775cb8f84a6738d47cdb57fba80c2e2e7 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/font.c @@ -0,0 +1,49 @@ +// font.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include + +#include "vdp.h" +#include "font.h" + +#include "font8x8_basic.h" +#include "font8x8_minimal.h" + +// this converts the 1bpp font tiles to the required 4bpp color format + +void upload_font(uint16_t vram_base) { + upload_font_remapped(vram_base, 0, 1); +} + +void upload_font_minimal(uint16_t vram_base) { + upload_font_remapped_main(vram_base, 0, 1, font8x8_minimal, sizeof(font8x8_minimal)/8); +} + +void upload_font_remapped(uint16_t vram_base, uint8_t transparent, uint8_t opaque) { + upload_font_remapped_main(vram_base, transparent, opaque, font8x8_basic, sizeof(font8x8_basic)/8); +} + +void upload_font_remapped_main(uint16_t vram_base, uint8_t transparent, uint8_t opaque, const char font[][8], uint16_t char_total) { + vdp_seek_vram(vram_base); + vdp_set_vram_increment(1); + + for (uint32_t char_id = 0; char_id < char_total; char_id++) { + for(uint32_t line = 0; line < 8; line++) { + uint32_t monochrome_line = font[char_id][line]; + uint32_t rendered_line = 0; + + for (uint32_t pixel = 0; pixel < 8; pixel++) { + rendered_line <<= 4; + rendered_line |= (monochrome_line & 0x01) ? opaque : transparent; + + monochrome_line >>= 1; + } + + vdp_write_vram(rendered_line & 0xffff); + vdp_write_vram(rendered_line >> 16); + } + } +} diff --git a/dan-rodrigues_icestation-32/software/common/font.h b/dan-rodrigues_icestation-32/software/common/font.h new file mode 100644 index 0000000000000000000000000000000000000000..d9d05856c3be2c84af07408c7e156d43760500bc --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/font.h @@ -0,0 +1,24 @@ +// font.h: Convert 8x8 1bpp font tiles to the required 4bpp color format. +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef font_h +#define font_h + +// Upload a 128-character ASCII font at vram_base. +void upload_font(uint16_t vram_base); + +// Upload a minimal uppercase latin only font at vram_base. +void upload_font_minimal(uint16_t vram_base); + +// Upload a default 128-character ASCII font at vram_base, providing a color +// 0..15 to use for foreground and background. +void upload_font_remapped(uint16_t vram_base, uint8_t transparent, uint8_t opaque); + +// Upload a specified font with specified number of characters at vram_base, +// providing a color 0..15 to use for foreground and background. +void upload_font_remapped_main(uint16_t vram_base, uint8_t transparent, uint8_t opaque, const char font[][8], uint16_t char_total); + +#endif /* font_h */ diff --git a/dan-rodrigues_icestation-32/software/common/font8x8_basic.h b/dan-rodrigues_icestation-32/software/common/font8x8_basic.h new file mode 100644 index 0000000000000000000000000000000000000000..85c33b23416cc37f7f545912d70c496a87bb84dd --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/font8x8_basic.h @@ -0,0 +1,153 @@ +/** + * 8x8 monochrome bitmap fonts for rendering + * Author: Daniel Hepper + * + * License: Public Domain + * + * Based on: + * // Summary: font8x8.h + * // 8x8 monochrome bitmap fonts for rendering + * // + * // Author: + * // Marcel Sondaar + * // International Business Machines (public domain VGA fonts) + * // + * // License: + * // Public Domain + * + * Fetched from: http://dimensionalrift.homelinux.net/combuster/mos3/?p=viewsource&file=/modules/gfx/font8_8.asm + **/ + +// Constant: font8x8_basic +// Contains an 8x8 font map for unicode points U+0000 - U+007F (basic latin) +const char font8x8_basic[128][8] = { + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0000 (nul) + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0001 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0002 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0003 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0004 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0005 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0006 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0007 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0008 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0009 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000A + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000B + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000C + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000D + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000E + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000F + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0010 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0011 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0012 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0013 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0014 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0015 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0016 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0017 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0018 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0019 + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001A + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001B + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001C + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001D + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001E + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001F + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 (space) + { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!) + { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (") + { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#) + { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($) + { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%) + { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&) + { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (') + { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (() + { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ()) + { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*) + { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+) + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,) + { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-) + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.) + { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/) + { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0) + { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1) + { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2) + { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3) + { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4) + { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5) + { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6) + { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7) + { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8) + { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9) + { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:) + { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (;) + { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<) + { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=) + { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>) + { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?) + { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@) + { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A) + { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B) + { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C) + { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D) + { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E) + { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F) + { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G) + { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H) + { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I) + { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J) + { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K) + { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L) + { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M) + { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N) + { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O) + { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P) + { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q) + { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R) + { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S) + { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T) + { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U) + { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V) + { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W) + { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X) + { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y) + { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z) + { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([) + { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\) + { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (]) + { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^) + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_) + { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`) + { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a) + { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b) + { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c) + { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d) + { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e) + { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f) + { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g) + { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h) + { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i) + { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j) + { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k) + { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l) + { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m) + { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n) + { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o) + { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p) + { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q) + { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r) + { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s) + { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t) + { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u) + { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v) + { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w) + { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x) + { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y) + { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z) + { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({) + { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|) + { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (}) + { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~) + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F +}; + diff --git a/dan-rodrigues_icestation-32/software/common/font8x8_minimal.h b/dan-rodrigues_icestation-32/software/common/font8x8_minimal.h new file mode 100644 index 0000000000000000000000000000000000000000..8757a80038e8eff2b2212a4ee845f19edb30f90b --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/font8x8_minimal.h @@ -0,0 +1,31 @@ +// Minimized 8x8 font based on the font8x8_basic.h + +const char font8x8_minimal[26][8] = { + // Alpha chars only for now: + { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A) + { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B) + { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C) + { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D) + { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E) + { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F) + { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G) + { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H) + { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I) + { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J) + { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K) + { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L) + { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M) + { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N) + { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O) + { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P) + { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q) + { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R) + { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S) + { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T) + { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U) + { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V) + { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W) + { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X) + { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y) + { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00} // U+005A (Z) +}; diff --git a/dan-rodrigues_icestation-32/software/common/rand.c b/dan-rodrigues_icestation-32/software/common/rand.c new file mode 100644 index 0000000000000000000000000000000000000000..e7abfb30440deb13e53051711b99a8d57bf129fd --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/rand.c @@ -0,0 +1,25 @@ +// rand.c: generate random bits +// +// Copyright (C) 2020 Mara "vmedea" +// +// SPDX-License-Identifier: MIT +#include "rand.h" + +static uint32_t random_state = 0x12345678; + +void srand(uint32_t s) { + random_state = s; +} + +uint32_t randbits(uint8_t nbits) { + uint32_t val = 0; + for (uint8_t i = 0; i < nbits; ++i) { + uint32_t lsb = random_state & 1; + random_state >>= 1; + if (lsb) + random_state ^= 0xf00f00f0; + + val = (val << 1) | lsb; + } + return val; +} diff --git a/dan-rodrigues_icestation-32/software/common/rand.h b/dan-rodrigues_icestation-32/software/common/rand.h new file mode 100644 index 0000000000000000000000000000000000000000..9bf95ec3c78930fdcaa57d72cf72331725440c8f --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/rand.h @@ -0,0 +1,23 @@ +// rand.h: generate random bits +// +// Copyright (C) 2020 Mara "vmedea" +// +// SPDX-License-Identifier: MIT + +#ifndef rand_h +#define rand_h + +#include + +/** + * Seed random number generator. + */ +void srand(uint32_t s); + +/** + * LFSR "random" bits implementation. This does not generate strong randomness, + * only unpredictability fine for visual effects and such. + */ +uint32_t randbits(uint8_t nbits); + +#endif diff --git a/dan-rodrigues_icestation-32/software/common/tinyprintf.c b/dan-rodrigues_icestation-32/software/common/tinyprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..c4d01999d02b1e7f0046381082e9587fc8df43a6 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/tinyprintf.c @@ -0,0 +1,522 @@ +/* +File: tinyprintf.c + +Copyright (C) 2004 Kustaa Nyholm + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#include "tinyprintf.h" + + +/* + * Configuration + */ + +/* Enable long int support */ +#define PRINTF_LONG_SUPPORT + +/* Enable long long int support (implies long int support) */ +#define PRINTF_LONG_LONG_SUPPORT + +/* Enable %z (size_t) support */ +#define PRINTF_SIZE_T_SUPPORT + +/* + * Configuration adjustments + */ +#ifdef PRINTF_SIZE_T_SUPPORT +#include +#endif + +#ifdef PRINTF_LONG_LONG_SUPPORT +# define PRINTF_LONG_SUPPORT +#endif + +/* __SIZEOF___ defined at least by gcc */ +#ifdef __SIZEOF_POINTER__ +# define SIZEOF_POINTER __SIZEOF_POINTER__ +#endif +#ifdef __SIZEOF_LONG_LONG__ +# define SIZEOF_LONG_LONG __SIZEOF_LONG_LONG__ +#endif +#ifdef __SIZEOF_LONG__ +# define SIZEOF_LONG __SIZEOF_LONG__ +#endif +#ifdef __SIZEOF_INT__ +# define SIZEOF_INT __SIZEOF_INT__ +#endif + +#ifdef __GNUC__ +# define _TFP_GCC_NO_INLINE_ __attribute__ ((noinline)) +#else +# define _TFP_GCC_NO_INLINE_ +#endif + +/* + * Implementation + */ +struct param { + char lz:1; /**< Leading zeros */ + char alt:1; /**< alternate form */ + char uc:1; /**< Upper case (for base16 only) */ + char align_left:1; /**< 0 == align right (default), 1 == align left */ + unsigned int width; /**< field width */ + char sign; /**< The sign to display (if any) */ + unsigned int base; /**< number base (e.g.: 8, 10, 16) */ + char *bf; /**< Buffer to output */ +}; + + +#ifdef PRINTF_LONG_LONG_SUPPORT +static void _TFP_GCC_NO_INLINE_ ulli2a( + unsigned long long int num, struct param *p) +{ + int n = 0; + unsigned long long int d = 1; + char *bf = p->bf; + while (num / d >= p->base) + d *= p->base; + while (d != 0) { + int dgt = num / d; + num %= d; + d /= p->base; + if (n || dgt > 0 || d == 0) { + *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); + ++n; + } + } + *bf = 0; +} + +static void lli2a(long long int num, struct param *p) +{ + if (num < 0) { + num = -num; + p->sign = '-'; + } + ulli2a(num, p); +} +#endif + +#ifdef PRINTF_LONG_SUPPORT +static void uli2a(unsigned long int num, struct param *p) +{ + int n = 0; + unsigned long int d = 1; + char *bf = p->bf; + while (num / d >= p->base) + d *= p->base; + while (d != 0) { + int dgt = num / d; + num %= d; + d /= p->base; + if (n || dgt > 0 || d == 0) { + *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); + ++n; + } + } + *bf = 0; +} + +static void li2a(long num, struct param *p) +{ + if (num < 0) { + num = -num; + p->sign = '-'; + } + uli2a(num, p); +} +#endif + +static void ui2a(unsigned int num, struct param *p) +{ + int n = 0; + unsigned int d = 1; + char *bf = p->bf; + while (num / d >= p->base) + d *= p->base; + while (d != 0) { + int dgt = num / d; + num %= d; + d /= p->base; + if (n || dgt > 0 || d == 0) { + *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); + ++n; + } + } + *bf = 0; +} + +static void i2a(int num, struct param *p) +{ + if (num < 0) { + num = -num; + p->sign = '-'; + } + ui2a(num, p); +} + +static int a2d(char ch) +{ + if (ch >= '0' && ch <= '9') + return ch - '0'; + else if (ch >= 'a' && ch <= 'f') + return ch - 'a' + 10; + else if (ch >= 'A' && ch <= 'F') + return ch - 'A' + 10; + else + return -1; +} + +static char a2u(char ch, const char **src, int base, unsigned int *nump) +{ + const char *p = *src; + unsigned int num = 0; + int digit; + while ((digit = a2d(ch)) >= 0) { + if (digit > base) + break; + num = num * base + digit; + ch = *p++; + } + *src = p; + *nump = num; + return ch; +} + +static void putchw(void *putp, putcf putf, struct param *p) +{ + char ch; + int n = p->width; + char *bf = p->bf; + + /* Number of filling characters */ + while (*bf++ && n > 0) + n--; + if (p->sign) + n--; + if (p->alt && p->base == 16) + n -= 2; + else if (p->alt && p->base == 8) + n--; + + /* Fill with space to align to the right, before alternate or sign */ + if (!p->lz && !p->align_left) { + while (n-- > 0) + putf(putp, ' '); + } + + /* print sign */ + if (p->sign) + putf(putp, p->sign); + + /* Alternate */ + if (p->alt && p->base == 16) { + putf(putp, '0'); + putf(putp, (p->uc ? 'X' : 'x')); + } else if (p->alt && p->base == 8) { + putf(putp, '0'); + } + + /* Fill with zeros, after alternate or sign */ + if (p->lz) { + while (n-- > 0) + putf(putp, '0'); + } + + /* Put actual buffer */ + bf = p->bf; + while ((ch = *bf++)) + putf(putp, ch); + + /* Fill with space to align to the left, after string */ + if (!p->lz && p->align_left) { + while (n-- > 0) + putf(putp, ' '); + } +} + +void tfp_format(void *putp, putcf putf, const char *fmt, va_list va) +{ + struct param p; +#ifdef PRINTF_LONG_SUPPORT + char bf[23]; /* long = 64b on some architectures */ +#else + char bf[12]; /* int = 32b on some architectures */ +#endif + char ch; + p.bf = bf; + + while ((ch = *(fmt++))) { + if (ch != '%') { + putf(putp, ch); + } else { +#ifdef PRINTF_LONG_SUPPORT + char lng = 0; /* 1 for long, 2 for long long */ +#endif + /* Init parameter struct */ + p.lz = 0; + p.alt = 0; + p.width = 0; + p.align_left = 0; + p.sign = 0; + + /* Flags */ + while ((ch = *(fmt++))) { + switch (ch) { + case '-': + p.align_left = 1; + continue; + case '0': + p.lz = 1; + continue; + case '#': + p.alt = 1; + continue; + default: + break; + } + break; + } + + /* Width */ + if (ch >= '0' && ch <= '9') { + ch = a2u(ch, &fmt, 10, &(p.width)); + } + + /* We accept 'x.y' format but don't support it completely: + * we ignore the 'y' digit => this ignores 0-fill + * size and makes it == width (ie. 'x') */ + if (ch == '.') { + p.lz = 1; /* zero-padding */ + /* ignore actual 0-fill size: */ + do { + ch = *(fmt++); + } while ((ch >= '0') && (ch <= '9')); + } + +#ifdef PRINTF_SIZE_T_SUPPORT +# ifdef PRINTF_LONG_SUPPORT + if (ch == 'z') { + ch = *(fmt++); + if (sizeof(size_t) == sizeof(unsigned long int)) + lng = 1; +# ifdef PRINTF_LONG_LONG_SUPPORT + else if (sizeof(size_t) == sizeof(unsigned long long int)) + lng = 2; +# endif + } else +# endif +#endif + +#ifdef PRINTF_LONG_SUPPORT + if (ch == 'l') { + ch = *(fmt++); + lng = 1; +#ifdef PRINTF_LONG_LONG_SUPPORT + if (ch == 'l') { + ch = *(fmt++); + lng = 2; + } +#endif + } +#endif + switch (ch) { + case 0: + goto abort; + case 'u': + p.base = 10; +#ifdef PRINTF_LONG_SUPPORT +#ifdef PRINTF_LONG_LONG_SUPPORT + if (2 == lng) + ulli2a(va_arg(va, unsigned long long int), &p); + else +#endif + if (1 == lng) + uli2a(va_arg(va, unsigned long int), &p); + else +#endif + ui2a(va_arg(va, unsigned int), &p); + putchw(putp, putf, &p); + break; + case 'd': + case 'i': + p.base = 10; +#ifdef PRINTF_LONG_SUPPORT +#ifdef PRINTF_LONG_LONG_SUPPORT + if (2 == lng) + lli2a(va_arg(va, long long int), &p); + else +#endif + if (1 == lng) + li2a(va_arg(va, long int), &p); + else +#endif + i2a(va_arg(va, int), &p); + putchw(putp, putf, &p); + break; +#ifdef SIZEOF_POINTER + case 'p': + p.alt = 1; +# if defined(SIZEOF_INT) && SIZEOF_POINTER <= SIZEOF_INT + lng = 0; +# elif defined(SIZEOF_LONG) && SIZEOF_POINTER <= SIZEOF_LONG + lng = 1; +# elif defined(SIZEOF_LONG_LONG) && SIZEOF_POINTER <= SIZEOF_LONG_LONG + lng = 2; +# endif +#endif + // fall through + case 'x': + case 'X': + p.base = 16; + p.uc = (ch == 'X')?1:0; +#ifdef PRINTF_LONG_SUPPORT +#ifdef PRINTF_LONG_LONG_SUPPORT + if (2 == lng) + ulli2a(va_arg(va, unsigned long long int), &p); + else +#endif + if (1 == lng) + uli2a(va_arg(va, unsigned long int), &p); + else +#endif + ui2a(va_arg(va, unsigned int), &p); + putchw(putp, putf, &p); + break; + case 'o': + p.base = 8; + ui2a(va_arg(va, unsigned int), &p); + putchw(putp, putf, &p); + break; + case 'c': + putf(putp, (char)(va_arg(va, int))); + break; + case 's': + p.bf = va_arg(va, char *); + putchw(putp, putf, &p); + p.bf = bf; + break; + case '%': + putf(putp, ch); + default: + break; + } + } + } + abort:; +} + +#if TINYPRINTF_DEFINE_TFP_PRINTF +static putcf stdout_putf; +static void *stdout_putp; + +void init_printf(void *putp, putcf putf) +{ + stdout_putf = putf; + stdout_putp = putp; +} + +void tfp_printf(char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + tfp_format(stdout_putp, stdout_putf, fmt, va); + va_end(va); +} +#endif + +#if TINYPRINTF_DEFINE_TFP_SPRINTF +struct _vsnprintf_putcf_data +{ + size_t dest_capacity; + char *dest; + size_t num_chars; +}; + +static void _vsnprintf_putcf(void *p, char c) +{ + struct _vsnprintf_putcf_data *data = (struct _vsnprintf_putcf_data*)p; + if (data->num_chars < data->dest_capacity) + data->dest[data->num_chars] = c; + data->num_chars ++; +} + +int tfp_vsnprintf(char *str, size_t size, const char *format, va_list ap) +{ + struct _vsnprintf_putcf_data data; + + if (size < 1) + return 0; + + data.dest = str; + data.dest_capacity = size-1; + data.num_chars = 0; + tfp_format(&data, _vsnprintf_putcf, format, ap); + + if (data.num_chars < data.dest_capacity) + data.dest[data.num_chars] = '\0'; + else + data.dest[data.dest_capacity] = '\0'; + + return data.num_chars; +} + +int tfp_snprintf(char *str, size_t size, const char *format, ...) +{ + va_list ap; + int retval; + + va_start(ap, format); + retval = tfp_vsnprintf(str, size, format, ap); + va_end(ap); + return retval; +} + +struct _vsprintf_putcf_data +{ + char *dest; + size_t num_chars; +}; + +static void _vsprintf_putcf(void *p, char c) +{ + struct _vsprintf_putcf_data *data = (struct _vsprintf_putcf_data*)p; + data->dest[data->num_chars++] = c; +} + +int tfp_vsprintf(char *str, const char *format, va_list ap) +{ + struct _vsprintf_putcf_data data; + data.dest = str; + data.num_chars = 0; + tfp_format(&data, _vsprintf_putcf, format, ap); + data.dest[data.num_chars] = '\0'; + return data.num_chars; +} + +int tfp_sprintf(char *str, const char *format, ...) +{ + va_list ap; + int retval; + + va_start(ap, format); + retval = tfp_vsprintf(str, format, ap); + va_end(ap); + return retval; +} +#endif diff --git a/dan-rodrigues_icestation-32/software/common/tinyprintf.h b/dan-rodrigues_icestation-32/software/common/tinyprintf.h new file mode 100644 index 0000000000000000000000000000000000000000..a769f4a8d3c8d8dfc25e26e91c77a12db9687c69 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/common/tinyprintf.h @@ -0,0 +1,186 @@ +/* +File: tinyprintf.h + +Copyright (C) 2004 Kustaa Nyholm + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +This library is really just two files: 'tinyprintf.h' and 'tinyprintf.c'. + +They provide a simple and small (+400 loc) printf functionality to +be used in embedded systems. + +I've found them so useful in debugging that I do not bother with a +debugger at all. + +They are distributed in source form, so to use them, just compile them +into your project. + +Two printf variants are provided: printf and the 'sprintf' family of +functions ('snprintf', 'sprintf', 'vsnprintf', 'vsprintf'). + +The formats supported by this implementation are: +'c' 'd' 'i' 'o' 'p' 'u' 's' 'x' 'X'. + +Zero padding and field width are also supported. + +If the library is compiled with 'PRINTF_SUPPORT_LONG' defined, then +the long specifier is also supported. Note that this will pull in some +long math routines (pun intended!) and thus make your executable +noticeably longer. Likewise with 'PRINTF_LONG_LONG_SUPPORT' for the +long long specifier, and with 'PRINTF_SIZE_T_SUPPORT' for the size_t +specifier. + +The memory footprint of course depends on the target CPU, compiler and +compiler options, but a rough guesstimate (based on a H8S target) is about +1.4 kB for code and some twenty 'int's and 'char's, say 60 bytes of stack space. +Not too bad. Your mileage may vary. By hacking the source code you can +get rid of some hundred bytes, I'm sure, but personally I feel the balance of +functionality and flexibility versus code size is close to optimal for +many embedded systems. + +To use the printf, you need to supply your own character output function, +something like : + +void putc ( void* p, char c) +{ + while (!SERIAL_PORT_EMPTY) ; + SERIAL_PORT_TX_REGISTER = c; +} + +Before you can call printf, you need to initialize it to use your +character output function with something like: + +init_printf(NULL,putc); + +Notice the 'NULL' in 'init_printf' and the parameter 'void* p' in 'putc', +the NULL (or any pointer) you pass into the 'init_printf' will eventually be +passed to your 'putc' routine. This allows you to pass some storage space (or +anything really) to the character output function, if necessary. +This is not often needed but it was implemented like that because it made +implementing the sprintf function so neat (look at the source code). + +The code is re-entrant, except for the 'init_printf' function, so it is safe +to call it from interrupts too, although this may result in mixed output. +If you rely on re-entrancy, take care that your 'putc' function is re-entrant! + +The printf and sprintf functions are actually macros that translate to +'tfp_printf' and 'tfp_sprintf' when 'TINYPRINTF_OVERRIDE_LIBC' is set +(default). Setting it to 0 makes it possible to use them along with +'stdio.h' printf's in a single source file. When +'TINYPRINTF_OVERRIDE_LIBC' is set, please note that printf/sprintf are +not function-like macros, so if you have variables or struct members +with these names, things will explode in your face. Without variadic +macros this is the best we can do to wrap these function. If it is a +problem, just give up the macros and use the functions directly, or +rename them. + +It is also possible to avoid defining tfp_printf and/or tfp_sprintf by +clearing 'TINYPRINTF_DEFINE_TFP_PRINTF' and/or +'TINYPRINTF_DEFINE_TFP_SPRINTF' to 0. This allows for example to +export only tfp_format, which is at the core of all the other +functions. + +For further details see source code. + +regs Kusti, 23.10.2004 +*/ + +#ifndef __TFP_PRINTF__ +#define __TFP_PRINTF__ + +#include + +/* Global configuration */ + +/* Set this to 0 if you do not want to provide tfp_printf */ +#ifndef TINYPRINTF_DEFINE_TFP_PRINTF +# define TINYPRINTF_DEFINE_TFP_PRINTF 1 +#endif + +/* Set this to 0 if you do not want to provide + tfp_sprintf/snprintf/vsprintf/vsnprintf */ +#ifndef TINYPRINTF_DEFINE_TFP_SPRINTF +# define TINYPRINTF_DEFINE_TFP_SPRINTF 1 +#endif + +/* Set this to 0 if you do not want tfp_printf and + tfp_{vsn,sn,vs,s}printf to be also available as + printf/{vsn,sn,vs,s}printf */ +#ifndef TINYPRINTF_OVERRIDE_LIBC +# define TINYPRINTF_OVERRIDE_LIBC 1 +#endif + +/* Optional external types dependencies */ + +#if TINYPRINTF_DEFINE_TFP_SPRINTF +# include /* size_t */ +#endif + +/* Declarations */ + +#ifdef __GNUC__ +# define _TFP_SPECIFY_PRINTF_FMT(fmt_idx,arg1_idx) \ + __attribute__((format (printf, fmt_idx, arg1_idx))) +#else +# define _TFP_SPECIFY_PRINTF_FMT(fmt_idx,arg1_idx) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*putcf) (void *, char); + +/* + 'tfp_format' really is the central function for all tinyprintf. For + each output character after formatting, the 'putf' callback is + called with 2 args: + - an arbitrary void* 'putp' param defined by the user and + passed unmodified from 'tfp_format', + - the character. + The 'tfp_printf' and 'tfp_sprintf' functions simply define their own + callback and pass to it the right 'putp' it is expecting. +*/ +void tfp_format(void *putp, putcf putf, const char *fmt, va_list va); + +#if TINYPRINTF_DEFINE_TFP_SPRINTF +int tfp_vsnprintf(char *str, size_t size, const char *fmt, va_list ap); +int tfp_snprintf(char *str, size_t size, const char *fmt, ...) \ + _TFP_SPECIFY_PRINTF_FMT(3, 4); +int tfp_vsprintf(char *str, const char *fmt, va_list ap); +int tfp_sprintf(char *str, const char *fmt, ...) \ + _TFP_SPECIFY_PRINTF_FMT(2, 3); +# if TINYPRINTF_OVERRIDE_LIBC +# define vsnprintf tfp_vsnprintf +# define snprintf tfp_snprintf +# define vsprintf tfp_vsprintf +# define sprintf tfp_sprintf +# endif +#endif + +#if TINYPRINTF_DEFINE_TFP_PRINTF +void init_printf(void *putp, putcf putf); +void tfp_printf(char *fmt, ...) _TFP_SPECIFY_PRINTF_FMT(1, 2); +# if TINYPRINTF_OVERRIDE_LIBC +# define printf tfp_printf +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dan-rodrigues_icestation-32/software/copper_bars/main.c b/dan-rodrigues_icestation-32/software/copper_bars/main.c new file mode 100644 index 0000000000000000000000000000000000000000..afa7e6da89f66ec7250746b4e22d1f565759b0fd --- /dev/null +++ b/dan-rodrigues_icestation-32/software/copper_bars/main.c @@ -0,0 +1,164 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include +#include + +#include "vdp.h" +#include "vdp_regs.h" +#include "copper.h" +#include "math_util.h" + +static const uint16_t TILE_BASE = 0x0000; +static const uint16_t MAP_BASE = 0x1000; + +static const uint8_t BAR_PALETTE_ID = 0; +static const uint8_t BAR_COLOR_ID = 1; + +static void draw_raster_bars(uint32_t line_offset, uint32_t angle); + +static uint16_t preshifted_argb[32]; + +int main() { + vdp_enable_copper(false); + vdp_enable_layers(SCROLL0 | SCROLL1); + vdp_set_alpha_over_layers(SCROLL0); + vdp_set_wide_map_layers(0); + + vdp_set_vram_increment(1); + + // one opaque tile to use for all graphics in demo + + const uint16_t opaque_tile = 0; + + vdp_set_layer_tile_base(0, TILE_BASE); + vdp_set_layer_tile_base(1, TILE_BASE); + vdp_seek_vram(TILE_BASE); + vdp_fill_vram(0x10, 0x1111); + + // checkerboard background (512x512, tiled repeatedly) + + const uint16_t map_size = 0x1000; + + vdp_set_layer_map_base(1, MAP_BASE + map_size); + vdp_seek_vram(MAP_BASE + map_size); + + const uint8_t checkerboard_dimension = 4; + + for (uint8_t y = 0; y < 64; y++) { + uint8_t y_even = (y / checkerboard_dimension) & 1; + + for (uint8_t x = 0; x < 64; x++) { + const uint8_t light_palette = 1; + const uint8_t dark_palette = 2; + + uint8_t x_even = (x / checkerboard_dimension) & 1; + bool is_dark = y_even ^ x_even; + + uint8_t palette = is_dark ? dark_palette : light_palette; + uint16_t map_word = opaque_tile | palette << SCROLL_MAP_PAL_SHIFT; + vdp_write_vram(map_word); + } + } + + vdp_set_layer_scroll(1, 0, 0); + + // initialize all map tiles to the empty opaque tile (space character) + + vdp_set_layer_map_base(0, MAP_BASE); + vdp_seek_vram(MAP_BASE); + vdp_fill_vram(0x1000, opaque_tile | BAR_PALETTE_ID << SCROLL_MAP_PAL_SHIFT); + + // checkerboard background palette + + const uint8_t checkerboard_bright_palette_id = 0x11; + const uint16_t checkerboard_bright_color = 0xfaaa; + vdp_set_single_palette_color(checkerboard_bright_palette_id, checkerboard_bright_color); + + const uint8_t checkerboard_dark_palette_id = 0x21; + const uint16_t checkerboard_dark_color = 0xf000; + vdp_set_single_palette_color(checkerboard_dark_palette_id, checkerboard_dark_color); + + uint16_t line_offset = 0; + uint16_t angle = 0; + + vdp_wait_frame_ended(); + + for (uint8_t i = 0; i < 32; i++) { + if (i < 16) { + preshifted_argb[i] = i << 12 | i << 8 | i << 4 | i; + } else { + preshifted_argb[i] = preshifted_argb[~i & 0xf]; + } + } + + while (true) { + draw_raster_bars(line_offset, angle); + + vdp_wait_frame_ended(); + vdp_enable_copper(false); + + line_offset++; + angle++; + } + + return 0; +} + +static void draw_raster_bars(uint32_t line_offset, uint32_t angle) { + static const uint16_t color_masks[] = { + 0xff00, 0xf0f0, 0xf00f, 0xffff, 0xfff0, 0xf0ff, 0xff0f, 0xffff + }; + const size_t color_mask_count = sizeof(color_masks) / sizeof(uint16_t); + const uint32_t bar_height = 32; + + COPBatchWriteConfig config = { + .mode = CWM_DOUBLE, + .reg = &VDP_PALETTE_ADDRESS, + .batch_wait_between_lines = true + }; + + cop_ram_seek(0); + + cop_set_target_x(0); + cop_wait_target_y(0); + cop_wait_target_x(2); + + vdp_enable_copper(true); + + uint32_t line = 0; + + while (line < SCREEN_ACTIVE_HEIGHT) { + const uint32_t angle_delta = 6; + const int16_t offset_scale = 0x18; + + int16_t sint = sin(angle); + angle += angle_delta; + int32_t offset = sys_multiply(sint, offset_scale) / SIN_MAX; + + uint32_t selected_line = line + line_offset + offset; + uint32_t bar_offset = selected_line % bar_height; + + config.batch_count = 1; + cop_start_batch_write(&config); + + uint32_t mask_selected = (selected_line / bar_height) % color_mask_count; + uint32_t color_mask = color_masks[mask_selected]; + + uint32_t color = 0; + uint32_t y = bar_offset % bar_height; + color = preshifted_argb[y]; + color &= color_mask; + + cop_add_batch_double(&config, BAR_COLOR_ID, color); + + line++; + cop_wait_target_y(line); + } + + cop_jump(0); +} diff --git a/dan-rodrigues_icestation-32/software/copper_polygon/main.c b/dan-rodrigues_icestation-32/software/copper_polygon/main.c new file mode 100644 index 0000000000000000000000000000000000000000..44756db1f3536064151ac84c4a35ba046e918cb3 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/copper_polygon/main.c @@ -0,0 +1,456 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include +#include + +#include "vdp.h" +#include "vdp_regs.h" +#include "copper.h" +#include "math_util.h" +#include "font.h" +#include "vdp_print.h" + +static const int32_t EDGE_Q_1 = 0x10000; +static const int16_t SCALE_Q_1 = 0x0100; + +typedef struct { + int16_t x; + int16_t y; +} Vertex; + +typedef enum { + ST_IDLE, + ST_ZOOM_IN, + ST_HOLD, + ST_ZOOM_OUT +} State; + +static void draw_transformed_triangle(Vertex *vertices); +static void draw_triangle(uint16_t angle, int16_t scale); + +static VDPLayer POLYGON_VISIBLE_LAYERS = SCROLL0 | SCROLL1; +static VDPLayer POLYGON_HIDDEN_LAYERS = SCROLL1; + +static const uint16_t TILE_BASE = 0x0000; +static const uint16_t MAP_BASE_BG = 0x1000; +static const uint16_t MAP_BASE_FG = 0x2000; + +// current state context + +static State state; + +static int16_t angle; +static int16_t scale; +static uint8_t alpha; +static uint16_t state_counter; + +static void enter_state(State new_state); +static void update_current_state(void); + +int main() { + vdp_enable_copper(false); + vdp_enable_layers(POLYGON_HIDDEN_LAYERS); + + vdp_set_vram_increment(1); + + vp_print_init(); + + // tiles (8x8 font, common to both layers) + vdp_set_layer_tile_base(0, TILE_BASE); + vdp_set_layer_tile_base(1, TILE_BASE); + + const uint8_t background_index = 1; + const uint8_t foreground_index = 2; + upload_font_remapped( + TILE_BASE, + background_index, + foreground_index); + + // the polygon layer (also showing the text) is a full wdith 1024x512 layer + vdp_set_wide_map_layers(SCROLL0); + // this layer is also alpha blended onto the checkboard background + vdp_set_alpha_over_layers(SCROLL0); + + // checkerboard background (512x512, tiled repeatedly) + vdp_set_layer_map_base(1, MAP_BASE_BG); + vdp_seek_vram(MAP_BASE_BG); + + const uint8_t checkerboard_dimension = 4; + const uint16_t opaque_tile = ' '; + + for (uint8_t y = 0; y < 64; y++) { + uint8_t y_even = (y / checkerboard_dimension) & 1; + + for (uint8_t x = 0; x < 64; x++) { + const uint8_t light_palette = 1; + const uint8_t dark_palette = 2; + + uint8_t x_even = (x / checkerboard_dimension) & 1; + bool is_dark = y_even ^ x_even; + + uint8_t palette = is_dark ? dark_palette : light_palette; + uint16_t map_word = opaque_tile | palette << SCROLL_MAP_PAL_SHIFT; + vdp_write_vram(map_word); + } + } + + // initialize all map tiles to the empty opaque tile (space character) + + vdp_set_layer_map_base(0, MAP_BASE_FG); + vdp_seek_vram(MAP_BASE_FG); + vdp_fill_vram(0x2000, opaque_tile); + + // print info + + const uint8_t context_y = 24; + + const char *const title = "You're watching an icestation-32 horizontal raster effects demonstration"; + const char *const subtitle = "Brought to you by vdp_copper.v"; + + const char *const context_1 = "This text and orange background are on a static, opaque layer."; + const char *const context_2 = "The copper coprocessor shows / hides this layer with raster effects."; + const char *const context_3 = "The copper program does raster-synced writes with sequences of WAIT and WRITE instructions."; + + vp_printf(vp_center_string_x(title), context_y, 0, SCROLL0, MAP_BASE_FG, title); + vp_printf(vp_center_string_x(subtitle), context_y + 1, 0, SCROLL0, MAP_BASE_FG, subtitle); + + vp_printf(vp_center_string_x(context_1), context_y + 4, 0, SCROLL0, MAP_BASE_FG, context_1); + vp_printf(vp_center_string_x(context_2), context_y + 6, 0, SCROLL0, MAP_BASE_FG, context_2); + vp_printf(vp_center_string_x(context_3), context_y + 8, 0, SCROLL0, MAP_BASE_FG, context_3); + + // checkerboard scrolling background palette + + const uint8_t checkerboard_bright_palette_id = 0x11; + const uint16_t checkerboard_bright_color = 0xfaaa; + vdp_set_single_palette_color(checkerboard_bright_palette_id, checkerboard_bright_color); + + const uint8_t checkerboard_dark_palette_id = 0x21; + const uint16_t checkerboard_dark_color = 0xf000; + vdp_set_single_palette_color(checkerboard_dark_palette_id, checkerboard_dark_color); + + uint32_t frame_counter = 0; + uint16_t line_offset = 0; + uint16_t scroll = 0; + + enter_state(ST_IDLE); + + vdp_wait_frame_ended(); + + while (true) { + // write copper program for this frame + draw_triangle(angle, scale); + + // this wait must happen before changing copper enable state + // there is risk of contention with VDP register writes otherwise + vdp_wait_frame_ended(); + vdp_enable_copper(false); + + update_current_state(); + + // metrics + + const uint8_t metrics_x = 39; + const uint8_t metrics_y = 39; + + uint16_t bytes_used = cop_ram_get_write_index() * 2; + vp_printf(metrics_x, metrics_y, 0, SCROLL0, MAP_BASE_FG, "Copper RAM usage: %d bytes", bytes_used); + + // polygon/text color updates + + const uint8_t polygon_bg_palette_id = 0x01; + const uint16_t polygon_bg_color = 0xfa70; + uint16_t color = (polygon_bg_color & 0x0fff) | alpha << 12; + vdp_set_single_palette_color(polygon_bg_palette_id, color); + + const uint8_t polygon_fg_palette_id = 0x02; + const uint16_t polygon_fg_color = 0xffff; + color = (polygon_fg_color & 0x0fff) | alpha << 12; + vdp_set_single_palette_color(polygon_fg_palette_id, color); + + vdp_set_layer_scroll(1, scroll, scroll); + + frame_counter++; + line_offset++; + + if (frame_counter % 2) { + scroll++; + } + } + + return 0; +} + +static void enter_state(State new_state) { + switch (new_state) { + case ST_IDLE: + angle = SIN_PERIOD / 2; + scale = 2; + alpha = 0; + break; + case ST_ZOOM_IN: + break; + case ST_HOLD: + break; + case ST_ZOOM_OUT: + break; + } + + state_counter = 0; + state = new_state; +} + +static void update_current_state() { + switch (state) { + case ST_IDLE: { + const uint16_t idle_frames = 180; + + if (state_counter > idle_frames) { + enter_state(ST_ZOOM_IN); + } + + } break; + case ST_ZOOM_IN: { + const int16_t target_scale = 0x3f0; + + if (scale > 0x10 && alpha != 0xf && state_counter % 4 == 0) { + alpha++; + } + + if (scale >= target_scale) { + enter_state(ST_HOLD); + } + + scale += 2; + } break; + case ST_HOLD: { + if (state_counter > 60) { + enter_state(ST_ZOOM_OUT); + } + } break; + case ST_ZOOM_OUT: { + if (scale < 0xc0 && alpha != 0 && state_counter % 4 == 0) { + alpha--; + } + + if (scale > 0) { + scale -= 2; + } else { + enter_state(ST_IDLE); + } + } break; + } + + state_counter++; + angle++; +} + +static void draw_triangle(uint16_t angle, int16_t scale) { + const int16_t screen_center_x = 848 / 2 + 240; + const int16_t screen_center_y = 480 / 2; + const int16_t radius = 240 - 1; + + Vertex vertices[3]; + + for (uint8_t i = 0; i < 3; i++) { + uint16_t angle_offset = i * SIN_PERIOD / 3; + int16_t sin_t = sin(angle + angle_offset); + int16_t cos_t = cos(angle + angle_offset); + + int16_t vertex_x = sys_multiply(cos_t, -radius) / SIN_MAX; + int16_t vertex_y = sys_multiply(sin_t, -radius) / SIN_MAX; + + vertex_x = sys_multiply(vertex_x, scale) / SCALE_Q_1; + vertex_y = sys_multiply(vertex_y, scale) / SCALE_Q_1; + + vertex_x += screen_center_x; + vertex_y += screen_center_y; + + vertices[i].x = vertex_x; + vertices[i].y = vertex_y; + } + + draw_transformed_triangle(vertices); +} + +static void draw_triangle_segment(int32_t *x1, int32_t *x2, int16_t y_base, int16_t y_end, int32_t x1_delta, int32_t x2_delta) { + bool needs_swap; + + if (*x1 == *x2) { + needs_swap = x1_delta > x2_delta; + } else { + needs_swap = *x1 > *x2; + } + + int32_t left, right; + int32_t delta_left, delta_right; + + if (!needs_swap) { + left = *x1; + right = *x2; + delta_left = x1_delta; + delta_right = x2_delta; + } else { + left = *x2; + right = *x1; + delta_left = x2_delta; + delta_right = x1_delta; + } + + // clip segment to fit the screen height if needed + + bool segment_needs_drawing = true; + + if (y_base < 0 && y_end > 0) { + // onscreen edge, but partially offscreen + left += -y_base * delta_left; + right += -y_base * delta_right; + + y_base = 0; + } else if (y_base < 0 && y_end < 0) { + // entirely offscreen edge, nothing to draw + // advance deltas and bail out + int16_t segment_height = y_end - y_base; + + left += segment_height * delta_left; + right += segment_height * delta_right; + + segment_needs_drawing = false; + } + + if (segment_needs_drawing) { + y_end = MIN(y_end, SCREEN_ACTIVE_HEIGHT); + + for (int16_t y = y_base; y < y_end; y++) { + left += delta_left; + right += delta_right; + + int16_t edge_left = left / EDGE_Q_1; + int16_t edge_right = right / EDGE_Q_1; + + const uint8_t line_start_slack = 16; + const uint16_t left_bound = SCREEN_OFFSCREEN_X - line_start_slack; + + if (edge_left < left_bound) { + // edge left side... + cop_wait_target_x(left_bound); + } else { + cop_wait_target_x(edge_left); + } + + cop_write_compressed(&VDP_LAYER_ENABLE, POLYGON_VISIBLE_LAYERS, false); + + if ((edge_right - edge_left) > 2) { + const uint8_t line_end_slack = 3; + const int16_t right_bound = RASTER_X_MAX - line_end_slack; + + if (edge_right > right_bound) { + cop_wait_target_x(right_bound); + } else { + // ...wait to reach the ride side of the edge... + cop_wait_target_x(edge_right); + } + } + + // ...edge right side + cop_write_compressed(&VDP_LAYER_ENABLE, POLYGON_HIDDEN_LAYERS, true); + } + } + + *x1 = needs_swap ? right : left; + *x2 = needs_swap ? left : right; +} + +static void sort_vertex_pair(Vertex *v1, Vertex *v2) { + if (v2->y < v1->y) { + Vertex t = *v1; + *v1 = *v2; + *v2 = t; + } +} + +static void sort_vertices(Vertex *vertices) { + sort_vertex_pair(&vertices[0], &vertices[1]); + sort_vertex_pair(&vertices[1], &vertices[2]); + sort_vertex_pair(&vertices[0], &vertices[1]); +} + +static void draw_transformed_triangle(Vertex *vertices) { + cop_ram_seek(0); + + // wait for raster (0, 0) to give the CPU a head start in writing this program + cop_set_target_x(0); + cop_wait_target_y(0); + // copper prefetches the next word while it waits, so make it wait for one more op to avoid contention + cop_wait_target_x(2); + + // the copper at this point can be enabled as it will wait for raster using the above ops + // the rest of the RAM is now available to be written without contention + // this is fine so long as the copper PC (read pointer) doesn't "catch up" to the CPU write pointer + vdp_enable_copper(true); + + sort_vertices(vertices); + + Vertex top = vertices[0]; + Vertex mid = vertices[1]; + Vertex bottom = vertices[2]; + + // top segment + + int16_t dx1 = mid.x - top.x; + int16_t dy1 = mid.y - top.y; + + int16_t dx2 = bottom.x - top.x; + int16_t dy2 = bottom.y - top.y; + + if (dy2 == 0) { + // this is a zero height triangle so nothing to do + return; + } + + if (top.y > 0) { + // offset the triangle vertically if there is empty space above it + cop_set_target_y(top.y); + } + + // note it's dx/dy rather than dy/dx + // the triangle edges are drawn by stepping through each vertical line, then doing x += (dx/dy) + + int32_t x1_delta; + int32_t x2_delta = (dx2 * EDGE_Q_1) / dy2; + + int32_t x1_long = top.x * EDGE_Q_1; + int32_t x2_long = x1_long; + + bool top_segment_visible = (dy1 != 0); + if (top_segment_visible) { + x1_delta = (dx1 * EDGE_Q_1) / dy1; + + draw_triangle_segment(&x1_long, &x2_long, top.y, mid.y, x1_delta, x2_delta); + } + + // bottom segment + + dx1 = bottom.x - mid.x; + dy1 = bottom.y - mid.y; + + if (!top_segment_visible) { + x1_long = mid.x * EDGE_Q_1; + x2_long = top.x * EDGE_Q_1; + } + + bool bottom_segment_visible = (dy1 != 0); + if (bottom_segment_visible) { + x1_delta = (dx1 * EDGE_Q_1) / dy1; + + draw_triangle_segment(&x1_long, &x2_long, mid.y, bottom.y, x1_delta, x2_delta); + } + + cop_write(&VDP_LAYER_ENABLE, POLYGON_HIDDEN_LAYERS); + + cop_jump(0); +} diff --git a/dan-rodrigues_icestation-32/software/gamepad_test/main.c b/dan-rodrigues_icestation-32/software/gamepad_test/main.c new file mode 100644 index 0000000000000000000000000000000000000000..ec11558fa69fe8ab16baf119fc676bf75d1a680b --- /dev/null +++ b/dan-rodrigues_icestation-32/software/gamepad_test/main.c @@ -0,0 +1,101 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include +#include + +#include "assert.h" +#include "vdp.h" +#include "font.h" +#include "gamepad.h" +#include "vdp_print.h" + +static const uint8_t TEXT_PALETTE_ID = 0; +static const uint16_t MAP_VRAM_BASE = 0x4000; +static const uint16_t TILE_VRAM_BASE = 0x0000; + +static void print_gamepad(uint16_t pad_encoded, uint16_t base_x, uint16_t base_y); + +int main() { + vdp_enable_layers(SCROLL0); + vdp_set_wide_map_layers(SCROLL0); + vdp_set_alpha_over_layers(0); + + vp_print_init(); + + vdp_set_vram_increment(1); + + vdp_set_layer_scroll(0, 0, 0); + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + const uint16_t tile_vram_base = 0x0000; + const uint16_t map_vram_base = 0x4000; + + vdp_set_layer_tile_base(0, TILE_VRAM_BASE); + upload_font(tile_vram_base); + + const uint16_t bg_color = 0xf033; + const uint16_t fg_color = 0xffff; + + vdp_set_single_palette_color(TEXT_PALETTE_ID * 0x10 + 0, bg_color); + vdp_set_single_palette_color(TEXT_PALETTE_ID * 0x10 + 1, fg_color); + + vdp_set_layer_map_base(0, MAP_VRAM_BASE); + vdp_seek_vram(map_vram_base); + + uint16_t p1_current = 0, p2_current = 0; + + const uint8_t p1_base_x = 40; + const uint8_t p1_base_y = 10; + + const uint8_t p2_base_x = 60; + const uint8_t p2_base_y = 10; + + const uint8_t user_base_x = 47; + const uint8_t user_base_y = 25; + + while (true) { + vdp_wait_frame_ended(); + + pad_read(&p1_current, &p2_current, NULL, NULL); + + vp_printf(p1_base_x, p1_base_y, TEXT_PALETTE_ID, SCROLL0, MAP_VRAM_BASE, "Player 1"); + print_gamepad(p1_current, p1_base_x, p1_base_y + 2); + + vp_printf(p2_base_x, p2_base_y, TEXT_PALETTE_ID, SCROLL0, MAP_VRAM_BASE, "Player 2"); + print_gamepad(p2_current, p2_base_x, p2_base_y + 2); + + vp_printf(user_base_x, user_base_y, + TEXT_PALETTE_ID, SCROLL0, MAP_VRAM_BASE, + "User button: %d", + pad_read_user_button()); + } +} + +static void print_gamepad(uint16_t pad_encoded, uint16_t base_x, uint16_t base_y) { + static const char * const input_labels[] = { + "B", "Y", "Select", "Start", + "Up", "Down", "Left", "Right", + "A", "X", "L", "R" + }; + + for (uint8_t i = 0; i < 12; i++) { + const uint8_t spacing = 8; + + vp_printf(base_x, base_y + i, + TEXT_PALETTE_ID, SCROLL0, MAP_VRAM_BASE, + "%s:", + input_labels[i]); + + vp_printf(base_x + spacing, base_y + i, + TEXT_PALETTE_ID, SCROLL0, MAP_VRAM_BASE, + "%d", + (pad_encoded >> i) & 1); + } +} diff --git a/dan-rodrigues_icestation-32/software/hello_world/main.c b/dan-rodrigues_icestation-32/software/hello_world/main.c new file mode 100644 index 0000000000000000000000000000000000000000..e54b26e8b43691ebf1ea2a2fa5f437e4bfb77d25 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/hello_world/main.c @@ -0,0 +1,59 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "vdp.h" +#include "font.h" + +int main() { + vdp_enable_layers(SCROLL0); + vdp_set_wide_map_layers(SCROLL0); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + vdp_set_layer_scroll(0, 0, 0); + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + const uint16_t tile_vram_base = 0x0000; + const uint16_t map_vram_base = 0x4000; + + vdp_set_layer_tile_base(0, tile_vram_base); + upload_font(tile_vram_base); + + const uint16_t bg_color = 0xf033; + const uint16_t fg_color = 0xffff; + + vdp_set_single_palette_color(0, bg_color); + vdp_set_single_palette_color(1, fg_color); + + vdp_set_layer_map_base(0, map_vram_base); + vdp_seek_vram(map_vram_base); + + const char *const hello_string = "Hello world!"; + const uint8_t palette_id = 0x0; + const uint8_t flip_x = false; + const uint8_t flip_y = false; + + const char *string = hello_string; + + while (*string) { + uint16_t map = *string & 0xff; + map |= palette_id << SCROLL_MAP_PAL_SHIFT; + map |= flip_x << SCROLL_MAP_X_FLIP_SHIFT; + map |= flip_y << SCROLL_MAP_Y_FLIP_SHIFT; + + vdp_write_vram(map); + + string++; + } + + while (true) {} +} diff --git a/dan-rodrigues_icestation-32/software/lib/assert.c b/dan-rodrigues_icestation-32/software/lib/assert.c new file mode 100644 index 0000000000000000000000000000000000000000..37863a7fe3b14aafbef5a9c0cb85dc6879087a59 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/assert.c @@ -0,0 +1,32 @@ +// assert.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "assert.h" + +static AssertHandler custom_handler; + +void assert_impl(bool assertion, const char *file, int line, const char *message) { +#ifdef ASSERT_ENABLED + if (assertion) { + return; + } + + if (custom_handler) { + custom_handler(file, line, message); + } else { + __asm("ebreak"); + } +#endif +} + +noreturn void fatal_error_impl(const char *file, int line, const char *message) { + assert_impl(false, file, line, message); + while(true) {} +} + +void assert_set_handler(AssertHandler handler) { + custom_handler = handler; +} diff --git a/dan-rodrigues_icestation-32/software/lib/assert.h b/dan-rodrigues_icestation-32/software/lib/assert.h new file mode 100644 index 0000000000000000000000000000000000000000..6e24414e1d563666d206c656675e80e69f79265e --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/assert.h @@ -0,0 +1,23 @@ +// assert.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef assert_h +#define assert_h + +#include +#include + +#define assert(condition) assert_impl(condition, __FILE__, __LINE__, #condition) +#define fatal_error(message) fatal_error_impl(__FILE__, __LINE__, message) + +typedef void (*AssertHandler)(const char *file, int line, const char *message); + +void assert_impl(bool assertion, const char *file, int line, const char *message); +noreturn void fatal_error_impl(const char *file, int line, const char *message); + +void assert_set_handler(AssertHandler handler); + +#endif /* assert_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/audio.c b/dan-rodrigues_icestation-32/software/lib/audio.c new file mode 100644 index 0000000000000000000000000000000000000000..4d0ad464ba738d52760a2f6b371a39281dadd4a5 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/audio.c @@ -0,0 +1,28 @@ +// audio.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "audio.h" + +void audio_set_aligned_addresses(volatile AudioChannel *channel, const int16_t *start, size_t length) { + AudioAlignedAddresses addresses; + audio_aligned_addresses(start, length, &addresses); + + channel->sample_start_address = addresses.start; + channel->sample_end_address = addresses.end; + channel->sample_loop_address = addresses.loop; +} + +void audio_aligned_addresses(const int16_t *start, size_t length, AudioAlignedAddresses *addresses) { + const uintptr_t cpu_flash_base = 0x1000000; + const size_t adpcm_block_size = 0x400; // in bytes + + uintptr_t block_start = (((size_t)start - cpu_flash_base)) / adpcm_block_size; + uintptr_t block_end = block_start + (length + (adpcm_block_size / 2 - 1)) / (adpcm_block_size / 2); + + addresses->start = block_start; + addresses->end = block_end; + addresses->loop = block_start; +} diff --git a/dan-rodrigues_icestation-32/software/lib/audio.h b/dan-rodrigues_icestation-32/software/lib/audio.h new file mode 100644 index 0000000000000000000000000000000000000000..5d4dedc4a2e84a639266f1aa3dad46e1252bd874 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/audio.h @@ -0,0 +1,80 @@ +// audio.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef audio_h +#define audio_h + +#include +#include + +static const void *const AUDIO_BASE = (uint32_t *)0x80000; + +typedef volatile uint32_t *const AUDIO_REG; + +typedef enum { + AUDIO_FLAG_LOOP = (1 << 0) +} __attribute__((packed)) AudioFlags; + +typedef struct { + volatile int8_t left, right; +} __attribute__((packed)) AudioVolumes; + +typedef struct { + volatile uint16_t sample_start_address; + + volatile uint8_t flags; + uint8_t flags_padding; + + volatile uint16_t sample_end_address; + volatile uint16_t sample_loop_address; + volatile AudioVolumes volumes; + volatile uint16_t pitch; + + // (unused padding) + uint16_t padding[2]; + +} __attribute__((packed)) AudioChannel; + +typedef struct { + volatile AudioChannel channels[8]; +} __attribute__((packed)) Audio; + +// Writes: + +static Audio *const AUDIO = (Audio*)(AUDIO_BASE + 0x000); +static AUDIO_REG AUDIO_GB_BASE = (AUDIO_REG)(AUDIO_BASE + 0x200); + +#define AUDIO_GB_PLAY (*((AUDIO_REG) AUDIO_GB_BASE + 0)) +#define AUDIO_GB_STOP (*((AUDIO_REG) AUDIO_GB_BASE + 1)) + +// Reads: + +#define AUDIO_STATUS_PLAYING (*((AUDIO_REG) AUDIO_BASE + 0)) +#define AUDIO_STATUS_ENDED (*((AUDIO_REG) AUDIO_BASE + 1)) +#define AUDIO_STATUS_BUSY ((*((AUDIO_REG) AUDIO_BASE + 2)) & 0x01) + +// Utility functions: + +typedef struct { + uint16_t start; + uint16_t end; + uint16_t loop; +} AudioAlignedAddresses; + +/** + * Set sample start address and length for a channel. The specified length is in + * 16-bit units. The loop address will be the same as the end address, so if + * looping is enabled the entire sample will loop. + */ +void audio_set_aligned_addresses(volatile AudioChannel *channel, const int16_t *start, size_t length); + +/** + * Compute sample start address and length for a channel. The specified length + * is in 16-bit units. + */ +void audio_aligned_addresses(const int16_t *start, size_t length, AudioAlignedAddresses *addresses); + +#endif /* audio_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/copper.c b/dan-rodrigues_icestation-32/software/lib/copper.c new file mode 100644 index 0000000000000000000000000000000000000000..c3f83f96dd47572e32d29ea13e6f6ca37d752ca9 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/copper.c @@ -0,0 +1,138 @@ +// copper.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "copper.h" + +#include + +#include "assert.h" + +// volatile is strictly correct here considering a separate coprocessor is reading this +// in practice it might not matter by the time the function returns +static volatile uint16_t * const COP_RAM = (uint16_t *)0x50000; +static const size_t COP_RAM_SIZE = 0x1000 / sizeof(uint16_t); + +static uint32_t cop_pc = 0; + +static const uint8_t OP_SHIFT = 14; + +typedef enum { + SET_TARGET = 0, + WRITE_COMPRESSED = 1, + WRITE_REG = 2, + JUMP = 3 +} Op; + +static void cop_target(uint16_t target, bool is_y, bool wait); +static uint8_t cop_reg(VDP_REG reg); + +void cop_ram_seek(uint16_t address) { + assert(address < COP_RAM_SIZE); + + cop_pc = address; +} + +uint16_t cop_ram_get_write_index(void) { + return cop_pc; +} + +void cop_set_target_x(uint16_t target_x) { + cop_target(target_x, false, false); +} + +void cop_set_target_y(uint16_t target_y) { + cop_target(target_y, true, false); +} + +void cop_wait_target_x(uint16_t target_x) { + cop_target(target_x, false, true); +} + +void cop_wait_target_y(uint16_t target_y) { + cop_target(target_y, true, true); +} + +static void cop_target(uint16_t target, bool is_y, bool wait) { + uint16_t op_word = SET_TARGET << OP_SHIFT; + op_word |= is_y ? 1 << 11 : 0; + op_word |= wait ? 1 << 12 : 0; + op_word |= target & 0x7ff; + COP_RAM[cop_pc++] = op_word; +} + +void cop_write(VDP_REG reg, uint16_t data) { + COPBatchWriteConfig config = { + .mode = CWM_SINGLE, + .reg = reg, + .batch_count = 1, + .batch_wait_between_lines = false + }; + + cop_start_batch_write(&config); + cop_add_batch_single(&config, data); +} + +void cop_write_compressed(VDP_REG reg, uint8_t data, bool increment_target_y) { + uint16_t op_word = WRITE_COMPRESSED << OP_SHIFT; + op_word |= cop_reg(reg); + op_word |= (data & 0x1f) << 6; + op_word |= increment_target_y ? 1 << 11 : 0; + COP_RAM[cop_pc++] = op_word; +} + +void cop_jump(uint16_t address) { + assert(address < COP_RAM_SIZE); + + uint16_t op_word = JUMP << OP_SHIFT; + op_word |= address & 0x7ff; + COP_RAM[cop_pc++] = op_word; +} + +// batch writes + +void cop_start_batch_write(COPBatchWriteConfig *config) { + assert(config->batch_count > 0); + assert(config->batch_count <= 32); + + uint16_t op_word = WRITE_REG << OP_SHIFT; + op_word |= cop_reg(config->reg); + op_word |= (config->batch_count - 1) << 6; + op_word |= config->batch_wait_between_lines ? 1 << 11 : 0; + op_word |= config->mode << 12; + COP_RAM[cop_pc++] = op_word; + + config->batches_written = 0; +} + +void cop_add_batch_single(COPBatchWriteConfig *config, uint16_t data) { + COP_RAM[cop_pc++] = data; + + config->batches_written++; +} + +void cop_add_batch_double(COPBatchWriteConfig *config, uint16_t data0, uint16_t data1) { + COP_RAM[cop_pc++] = data0; + COP_RAM[cop_pc++] = data1; + + config->batches_written++; +} + +void cop_add_batch_quad(COPBatchWriteConfig *config, uint16_t data0, uint16_t data1, uint16_t data2, uint16_t data3) { + COP_RAM[cop_pc++] = data0; + COP_RAM[cop_pc++] = data1; + COP_RAM[cop_pc++] = data2; + COP_RAM[cop_pc++] = data3; + + config->batches_written++; +} + +static uint8_t cop_reg(VDP_REG reg) { + return ((uint32_t)reg / 2) & 0x3f; +} + +void cop_assert_config_consistent(const COPBatchWriteConfig *config) { + assert(config->batches_written < config->batch_count); +} diff --git a/dan-rodrigues_icestation-32/software/lib/copper.h b/dan-rodrigues_icestation-32/software/lib/copper.h new file mode 100644 index 0000000000000000000000000000000000000000..83c23d48ba2d5591180840f1c6ec77535f4aa9e5 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/copper.h @@ -0,0 +1,51 @@ +// copper.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef copper_h +#define copper_h + +#include +#include + +#include "vdp.h" + +typedef enum { + CWM_SINGLE = 0, + CWM_DOUBLE = 1, + CWM_QUAD = 2 +} COPWriteMode; + +typedef struct { + COPWriteMode mode; + VDP_REG reg; + uint8_t batch_count; + bool batch_wait_between_lines; + + int8_t batches_written; +} COPBatchWriteConfig; + +void cop_ram_seek(uint16_t address); +uint16_t cop_ram_get_write_index(void); + +void cop_set_target_x(uint16_t target_x); +void cop_set_target_y(uint16_t target_y); + +void cop_wait_target_x(uint16_t target_x); +void cop_wait_target_y(uint16_t target_y); + +void cop_write(VDP_REG reg, uint16_t data); +void cop_write_compressed(VDP_REG reg, uint8_t data, bool increment_target_y); + +void cop_start_batch_write(COPBatchWriteConfig *config); +void cop_add_batch_single(COPBatchWriteConfig *config, uint16_t data); +void cop_add_batch_double(COPBatchWriteConfig *config, uint16_t data0, uint16_t data1); +void cop_add_batch_quad(COPBatchWriteConfig *config, uint16_t data0, uint16_t data1, uint16_t data2, uint16_t data3); + +void cop_jump(uint16_t address); + +void cop_assert_config_consistent(const COPBatchWriteConfig *config); + +#endif /* copper_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/gamepad.c b/dan-rodrigues_icestation-32/software/lib/gamepad.c new file mode 100644 index 0000000000000000000000000000000000000000..1b764f7c3165820e3f863f68b44758e7c4cc1cda --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/gamepad.c @@ -0,0 +1,87 @@ +// gamepad.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include + +#include "gamepad.h" + +#include "assert.h" + +static volatile uint32_t * const PAD_BASE = (uint32_t *)0x40000; + +static const uint32_t PAD_LATCH = 1 << 0; +static const uint32_t PAD_CLK = 1 << 1; +static const uint32_t USER_BUTTON = 1 << 2; + +#define PAD_IO (*((volatile uint32_t *) PAD_BASE + 0)) + +// The parts of this function that access PAD_IO will eventually be rewritten in assembly +// The (S)NES pads may work properly if the latch/clk/input is accessed too quickly by the CPU +// Complicating things are the 2 possible clocks for the CPU and third party clones of the gamepads +// +// The assembly function can order and time accesses appropriately + +void pad_read(uint16_t *p1_current, uint16_t *p2_current, uint16_t *p1_edge, uint16_t *p2_edge) { + assert(p1_current); + + const uint8_t button_count = 16; + + // Latch the current state of pad inputs + PAD_IO = PAD_LATCH; + PAD_IO = 0; + + uint16_t p1_new = 0; + uint16_t p2_new = 0; + for (uint8_t i = 0; i < button_count; i++) { + p1_new >>= 1; + p2_new >>= 1; + + // Read current bit.. + uint8_t input_bits = PAD_IO; + // ..and clock in the next bit + PAD_IO = PAD_CLK; + PAD_IO = 0; + + p1_new |= (input_bits & 1) << 15; + p2_new |= ((input_bits >> 1) & 1) << 15; + } + + // Edge inputs + if (p1_edge) { + *p1_edge = (p1_new ^ *p1_current) & p1_new; + } + if (p2_current && p2_edge) { + *p2_edge = (p2_new ^ *p2_current) & p2_new; + } + + // Level inputs + *p1_current = p1_new; + + if (p2_current) { + *p2_current = p2_new; + } +} + +void pad_decode_input(uint16_t encoded_input, PadInputDecoded *decoded_input) { + assert(decoded_input); + + for (uint32_t i = 0; i < 12; i++) { + decoded_input->indexed[i] = encoded_input & 1; + encoded_input >>= 1; + } +} + +bool pad_read_user_button() { + return (PAD_IO & USER_BUTTON); +} + +const PadInputDecoded PAD_INPUT_DECODED_NO_INPUT = { + .b = 0, .y = 0, .select = 0, .start = 0, + .up = 0, .down = 0, .left = 0, .right = 0, + .a = 0, .x = 0, .l = 0, .r = 0, + + .raw = 0 +}; diff --git a/dan-rodrigues_icestation-32/software/lib/gamepad.h b/dan-rodrigues_icestation-32/software/lib/gamepad.h new file mode 100644 index 0000000000000000000000000000000000000000..9939631bfcb0cc952015774096ce85852215a3bf --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/gamepad.h @@ -0,0 +1,50 @@ +// gamepad.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef gamepad_h +#define gamepad_h + +#include +#include + +typedef enum { + GP_B = 1 << 0, + GP_Y = 1 << 1, + GP_SELECT = 1 << 2, + GP_START = 1 << 3, + GP_UP = 1 << 4, + GP_DOWN = 1 << 5, + GP_LEFT = 1 << 6, + GP_RIGHT = 1 << 7, + GP_A = 1 << 8, + GP_X = 1 << 9, + GP_L = 1 << 10, + GP_R = 1 << 11 +} PadInput; + +typedef struct { + union { + struct { + bool b, y, select, start; + bool up, down, left, right; + bool a, x; + bool l, r; + }; + + bool indexed[12]; + }; + + uint16_t raw; +} PadInputDecoded; + +extern const PadInputDecoded PAD_INPUT_DECODED_NO_INPUT; + +void pad_read(uint16_t *p1_current, uint16_t *p2_current, uint16_t *p1_edge, uint16_t *p2_edge); +void pad_decode_input(uint16_t encoded_input, PadInputDecoded *decoded_input); + +bool pad_read_user_button(void); + +#endif /* gamepad_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/math_util.c b/dan-rodrigues_icestation-32/software/lib/math_util.c new file mode 100644 index 0000000000000000000000000000000000000000..85621abf3f6c85107c64a45a8fc93db7cf8d154c --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/math_util.c @@ -0,0 +1,53 @@ +// math_util.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "math_util.h" + +#include "sin_table.h" + +// Multiplier (memory-mapped multiplier on the FPGA) + +static volatile uint32_t *const SYS_MUL_BASE = (uint32_t *)0x030000; + +#define SYS_MUL_A (*((volatile int32_t *)SYS_MUL_BASE + 0)) +#define SYS_MUL_B (*((volatile int32_t *)SYS_MUL_BASE + 1)) + +#define SYS_MUL_RESULT (*((volatile int32_t *)SYS_MUL_BASE + 0)) + +int32_t sys_multiply(int32_t a, int32_t b) { + SYS_MUL_A = a; + SYS_MUL_B = b; + + return SYS_MUL_RESULT; +} + +// sin() / cos() + +static const uint16_t SIN_HALF_PERIOD = SIN_PERIOD / 2; +static const uint16_t SIN_QUARTER_PERIOD = SIN_PERIOD / 4; + +int16_t cos(uint16_t angle) { + return sin(angle + SIN_QUARTER_PERIOD); +} + +int16_t sin(uint16_t angle) { + angle &= (SIN_PERIOD - 1); + + // special cases to avoid "flat spots" in the sin wave + if (angle == SIN_QUARTER_PERIOD) { + return SIN_MAX; + } else if (angle == (3 * SIN_QUARTER_PERIOD)) { + return -SIN_MAX; + } + + uint16_t index = angle; + index = (angle & SIN_QUARTER_PERIOD ? -index : index); + index &= (SIN_QUARTER_PERIOD - 1); + + int16_t sin = sin_table[index]; + + return (angle & SIN_HALF_PERIOD ? -sin : sin); +} diff --git a/dan-rodrigues_icestation-32/software/lib/math_util.h b/dan-rodrigues_icestation-32/software/lib/math_util.h new file mode 100644 index 0000000000000000000000000000000000000000..67d39d3432fb04f577762d167d784e28d43a5bbd --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/math_util.h @@ -0,0 +1,30 @@ +// math_util.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef math_util_h +#define math_util_h + +#include + +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define ABS(a) (((a) < 0) ? (-(a)) : (a)) +#define SIGN(a) ((a) < 0) + +// Signed s16xs16=s32 multiply +// +// The int32_t parameter types are only so compiler generated code doesn't +// unnecessarily truncate the upper bits when it has no ill effect. + +int32_t sys_multiply(int32_t a, int32_t b); + +static const uint16_t SIN_PERIOD = 0x400; +static const int16_t SIN_MAX = 0x4000; + +int16_t cos(uint16_t angle); +int16_t sin(uint16_t angle); + +#endif diff --git a/dan-rodrigues_icestation-32/software/lib/sin_table.h b/dan-rodrigues_icestation-32/software/lib/sin_table.h new file mode 100644 index 0000000000000000000000000000000000000000..b29b2b3c90bb46a56d57292c20b6de0fc51ac2ea --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/sin_table.h @@ -0,0 +1,260 @@ +#include + +const int16_t sin_table[] = { + 0x0000, + 0x0064, + 0x00c9, + 0x012d, + 0x0192, + 0x01f6, + 0x025b, + 0x02bf, + 0x0323, + 0x0388, + 0x03ec, + 0x0451, + 0x04b5, + 0x0519, + 0x057d, + 0x05e1, + 0x0645, + 0x06a9, + 0x070d, + 0x0771, + 0x07d5, + 0x0839, + 0x089c, + 0x0900, + 0x0964, + 0x09c7, + 0x0a2a, + 0x0a8d, + 0x0af1, + 0x0b54, + 0x0bb6, + 0x0c19, + 0x0c7c, + 0x0cde, + 0x0d41, + 0x0da3, + 0x0e05, + 0x0e67, + 0x0ec9, + 0x0f2b, + 0x0f8c, + 0x0fee, + 0x104f, + 0x10b0, + 0x1111, + 0x1172, + 0x11d3, + 0x1233, + 0x1294, + 0x12f4, + 0x1354, + 0x13b3, + 0x1413, + 0x1472, + 0x14d1, + 0x1530, + 0x158f, + 0x15ee, + 0x164c, + 0x16aa, + 0x1708, + 0x1766, + 0x17c3, + 0x1820, + 0x187d, + 0x18da, + 0x1937, + 0x1993, + 0x19ef, + 0x1a4b, + 0x1aa6, + 0x1b02, + 0x1b5d, + 0x1bb7, + 0x1c12, + 0x1c6c, + 0x1cc6, + 0x1d20, + 0x1d79, + 0x1dd2, + 0x1e2b, + 0x1e83, + 0x1edc, + 0x1f34, + 0x1f8b, + 0x1fe2, + 0x2039, + 0x2090, + 0x20e7, + 0x213d, + 0x2192, + 0x21e8, + 0x223d, + 0x2292, + 0x22e6, + 0x233a, + 0x238e, + 0x23e1, + 0x2434, + 0x2487, + 0x24da, + 0x252c, + 0x257d, + 0x25cf, + 0x261f, + 0x2670, + 0x26c0, + 0x2710, + 0x275f, + 0x27af, + 0x27fd, + 0x284b, + 0x2899, + 0x28e7, + 0x2934, + 0x2981, + 0x29cd, + 0x2a19, + 0x2a65, + 0x2ab0, + 0x2afa, + 0x2b45, + 0x2b8e, + 0x2bd8, + 0x2c21, + 0x2c6a, + 0x2cb2, + 0x2cf9, + 0x2d41, + 0x2d88, + 0x2dce, + 0x2e14, + 0x2e5a, + 0x2e9f, + 0x2ee3, + 0x2f28, + 0x2f6b, + 0x2faf, + 0x2ff1, + 0x3034, + 0x3076, + 0x30b7, + 0x30f8, + 0x3138, + 0x3179, + 0x31b8, + 0x31f7, + 0x3236, + 0x3274, + 0x32b1, + 0x32ee, + 0x332b, + 0x3367, + 0x33a3, + 0x33de, + 0x3419, + 0x3453, + 0x348c, + 0x34c6, + 0x34fe, + 0x3536, + 0x356e, + 0x35a5, + 0x35dc, + 0x3612, + 0x3647, + 0x367c, + 0x36b1, + 0x36e5, + 0x3718, + 0x374b, + 0x377d, + 0x37af, + 0x37e0, + 0x3811, + 0x3841, + 0x3871, + 0x38a0, + 0x38cf, + 0x38fd, + 0x392a, + 0x3957, + 0x3983, + 0x39af, + 0x39da, + 0x3a05, + 0x3a2f, + 0x3a59, + 0x3a82, + 0x3aaa, + 0x3ad2, + 0x3afa, + 0x3b20, + 0x3b47, + 0x3b6c, + 0x3b91, + 0x3bb6, + 0x3bda, + 0x3bfd, + 0x3c20, + 0x3c42, + 0x3c63, + 0x3c84, + 0x3ca5, + 0x3cc5, + 0x3ce4, + 0x3d02, + 0x3d21, + 0x3d3e, + 0x3d5b, + 0x3d77, + 0x3d93, + 0x3dae, + 0x3dc9, + 0x3de2, + 0x3dfc, + 0x3e14, + 0x3e2d, + 0x3e44, + 0x3e5b, + 0x3e71, + 0x3e87, + 0x3e9c, + 0x3eb1, + 0x3ec5, + 0x3ed8, + 0x3eeb, + 0x3efd, + 0x3f0e, + 0x3f1f, + 0x3f2f, + 0x3f3f, + 0x3f4e, + 0x3f5d, + 0x3f6a, + 0x3f78, + 0x3f84, + 0x3f90, + 0x3f9c, + 0x3fa6, + 0x3fb1, + 0x3fba, + 0x3fc3, + 0x3fcb, + 0x3fd3, + 0x3fda, + 0x3fe1, + 0x3fe7, + 0x3fec, + 0x3ff0, + 0x3ff4, + 0x3ff8, + 0x3ffb, + 0x3ffd, + 0x3ffe, + 0x3fff +}; diff --git a/dan-rodrigues_icestation-32/software/lib/status.c b/dan-rodrigues_icestation-32/software/lib/status.c new file mode 100644 index 0000000000000000000000000000000000000000..ebbefe132946b5e2ad53e87f163895c0368f2138 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/status.c @@ -0,0 +1,11 @@ +// status.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "status.h" + +void status_set_leds(uint8_t val) { + SYS_STATUS_LEDS = val; +} diff --git a/dan-rodrigues_icestation-32/software/lib/status.h b/dan-rodrigues_icestation-32/software/lib/status.h new file mode 100644 index 0000000000000000000000000000000000000000..ef9b44a0f21b9e2662c96ca834f1b45d7fa8cfe8 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/status.h @@ -0,0 +1,21 @@ +// status.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef status_h +#define status_h + +#include +#include + +static volatile void *const SYS_STATUS_BASE = (uint32_t *)0x20000; +typedef volatile uint32_t *const SYS_STATUS_REG; + +#define SYS_STATUS_LEDS (*((SYS_STATUS_REG)SYS_STATUS_BASE + 0)) + +// Sets the status leds on the board. Takes a bitmask. +void status_set_leds(uint8_t val); + +#endif diff --git a/dan-rodrigues_icestation-32/software/lib/vdp.c b/dan-rodrigues_icestation-32/software/lib/vdp.c new file mode 100644 index 0000000000000000000000000000000000000000..2dedfaa27d59e0030a5e9fc47463a64f4d455c38 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/vdp.c @@ -0,0 +1,217 @@ +// vdp.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "vdp.h" + +#include "vdp_regs.h" +#include "assert.h" + +// exported constants + +const VDPLayer VDP_ALL_LAYERS = 0x1f; + +// scrolling layer map attributes + +const uint16_t SCROLL_MAP_X_FLIP_SHIFT = 9; +const uint16_t SCROLL_MAP_Y_FLIP_SHIFT = 10; + +const uint16_t SCROLL_MAP_X_FLIP = 1 << SCROLL_MAP_X_FLIP_SHIFT; +const uint16_t SCROLL_MAP_Y_FLIP = 1 << SCROLL_MAP_Y_FLIP_SHIFT; +const uint16_t SCROLL_MAP_PAL_SHIFT = 12; + +// sprite meta attributes + +// x_block +const uint16_t SPRITE_X_FLIP = 1 << 10; + +// y_block +const uint16_t SPRITE_Y_FLIP = 1 << 9; +const uint16_t SPRITE_16_TALL = 1 << 10; +const uint16_t SPRITE_16_WIDE = 1 << 11; + +// g_block +const uint16_t SPRITE_PRIORITY_SHIFT = 10; +const uint16_t SPRITE_PAL_SHIFT = 12; + +// MARK: Metrics + +const uint16_t SCREEN_ACTIVE_WIDTH = 848; +const uint16_t SCREEN_ACTIVE_HEIGHT = 480; +const uint16_t SCREEN_OFFSCREEN_X = 240; + +const uint16_t RASTER_X_MAX = SCREEN_ACTIVE_WIDTH + SCREEN_OFFSCREEN_X - 1; + +// MARK: Functions + +void vdp_enable_copper(uint8_t enable) { + VDP_ENABLE_COPPER = enable; +} + +static void update_layer_address(uint8_t layer, uint16_t address, uint16_t *combined) { +#ifdef VDP_INTERLEAVED_MAP + const uint8_t address_shift = 11; +#else + const uint8_t address_shift = 12; +#endif + + uint8_t shift = layer * 4; + uint16_t mask = 0xf << shift; + *combined &= ~mask; + *combined |= (address >> address_shift &0xf) << shift; +} + +void vdp_set_layer_map_base(uint8_t layer, uint16_t address) { + static uint16_t combined_base = 0; + + update_layer_address(layer, address, &combined_base); + VDP_SCROLL_MAP_ADDRESS_BASE = combined_base; +} + +void vdp_set_layer_tile_base(uint8_t layer, uint16_t address) { + static uint16_t combined_base = 0; + + update_layer_address(layer, address, &combined_base); + VDP_SCROLL_TILE_ADDRESS_BASE = combined_base; +} + +void vdp_set_alpha_over_layers(VDPLayer layers) { + VDP_ALPHA_OVER_ENABLE = layers; +} + +void vdp_enable_layers(VDPLayer layers) { + VDP_LAYER_ENABLE = layers; +} + +void vdp_write_vram(uint16_t word) { + VDP_VRAM_WRITE_DATA = word; +} + +void vdp_fill_vram(uint16_t count, uint16_t word) { + for (uint32_t i = 0; i < count; i++) { + VDP_VRAM_WRITE_DATA = word; + } +} + +void vdp_seek_vram(uint16_t address) { + VDP_VRAM_ADDRESS = address; +} + +void vdp_write_palette_range(uint8_t color_id_start, uint32_t count, const uint16_t *palette_start) { + VDP_PALETTE_ADDRESS = color_id_start; + + for (uint32_t i = 0; i < count; i++) { + VDP_PALETTE_WRITE_DATA = palette_start[i]; + } +} + +void vdp_set_single_palette_color(uint8_t color_id, uint16_t color) { + VDP_PALETTE_ADDRESS = color_id; + VDP_PALETTE_WRITE_DATA = color; +} + +void vdp_seek_palette(uint8_t color_id) { + VDP_PALETTE_ADDRESS = color_id; +} + +void vdp_write_palette_color(uint16_t color) { + VDP_PALETTE_WRITE_DATA = color; +} + +void vdp_set_layer_scroll(uint8_t layer, uint16_t scroll_x, uint16_t scroll_y) { + uint8_t index = layer & 0xff; + VDP_HSCROLL_BASE[index] = scroll_x; + VDP_VSCROLL_BASE[index] = scroll_y; +} + +void vdp_set_vram_increment(uint8_t increment) { + VDP_ADDRESS_INCREMENT = increment; +} + +void vdp_write_vram_block(const uint16_t *data, uint16_t size) { + if (!size) { + return; + } + + // gcc generates suboptimal loop with a while() + const uint16_t *end = data + size; + do { + VDP_VRAM_WRITE_DATA = *data++; + } while (data != end); +} + +void vdp_write_single_sprite_meta(uint8_t sprite_id, uint16_t x_block, uint16_t y_block, uint16_t g_block) { + VDP_SPRITE_BLOCK_ADDRESS = sprite_id; + + VDP_SPRITE_DATA = x_block; + VDP_SPRITE_DATA = y_block; + VDP_SPRITE_DATA = g_block; +} + +void vdp_seek_sprite(uint8_t sprite_id) { + VDP_SPRITE_BLOCK_ADDRESS = sprite_id; +} + +void vdp_write_sprite_meta(uint16_t x_block, uint16_t y_block, uint16_t g_block) { + VDP_SPRITE_DATA = x_block; + VDP_SPRITE_DATA = y_block; + VDP_SPRITE_DATA = g_block; +} + +void vdp_set_sprite_tile_base(uint16_t base) { + VDP_SPRITE_TILE_BASE = base / 2; +} + +void vdp_clear_all_sprites() { + const uint16_t y_block = 480; + + VDP_SPRITE_BLOCK_ADDRESS = 0; + + for (uint32_t i = 0; i < 256; i++) { + VDP_SPRITE_DATA = 0; + VDP_SPRITE_DATA = y_block; + VDP_SPRITE_DATA = 0; + } +} + +void vdp_set_wide_map_layers(VDPLayer layers) { + VDP_SCROLL_WIDE_MAP_ENABLE = layers; +} + +void vdp_set_affine_matrix(int16_t a, int16_t b, int16_t c, int16_t d) { + VDP_MATRIX_A = a; + VDP_MATRIX_B = b; + VDP_MATRIX_C = c; + VDP_MATRIX_D = d; +} + +void vdp_set_affine_pretranslate(int16_t x, int16_t y) { + VDP_AFFINE_PRETRANSLATE_X = x; + VDP_AFFINE_PRETRANSLATE_Y = y; +} + +void vdp_set_affine_translate(int16_t x, int16_t y) { + VDP_AFFINE_TRANSLATE_X = x; + VDP_AFFINE_TRANSLATE_Y = y; +} + +void vdp_wait_frame_ended() { + const uint16_t final_line = 480; + + while (VDP_CURRENT_RASTER_Y != (final_line - 1)) {} + while (VDP_CURRENT_RASTER_Y != final_line) {} +} + +bool vdp_layer_is_odd(VDPLayer layer) { + switch (layer) { + case SCROLL0: case SCROLL2: + return false; + case SCROLL1: case SCROLL3: + return true; + default: + fatal_error("Unexpected VDPLayer param"); + return false; + } +} diff --git a/dan-rodrigues_icestation-32/software/lib/vdp.h b/dan-rodrigues_icestation-32/software/lib/vdp.h new file mode 100644 index 0000000000000000000000000000000000000000..a0675d92b56727b9bde1f61209ce74dc4e3c9b10 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/vdp.h @@ -0,0 +1,116 @@ +// vdp.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef vdp_h +#define vdp_h + +#include +#include + +typedef volatile uint16_t *const VDP_REG; + +static VDP_REG VDP_BASE = (VDP_REG)0x010000; + +typedef enum { + SCROLL0 = 1 << 0, + SCROLL1 = 1 << 1, + SCROLL2 = 1 << 2, + SCROLL3 = 1 << 3, + SPRITES = 1 << 4, + + AFFINE = 1 << 5 +} VDPLayer; + +extern const VDPLayer VDP_ALL_LAYERS; + +// MARK: Screen metrics + +extern const uint16_t SCREEN_ACTIVE_WIDTH; +extern const uint16_t SCREEN_ACTIVE_HEIGHT; +extern const uint16_t SCREEN_OFFSCREEN_X; + +extern const uint16_t RASTER_X_MAX; + +// MARK: Attributes + +// scrolling layer map attribute bits + +extern const uint16_t SCROLL_MAP_X_FLIP_SHIFT; +extern const uint16_t SCROLL_MAP_Y_FLIP_SHIFT; + +extern const uint16_t SCROLL_MAP_X_FLIP; +extern const uint16_t SCROLL_MAP_Y_FLIP; +extern const uint16_t SCROLL_MAP_PAL_SHIFT; + +// sprite meta block attribute bits + +// y_block +extern const uint16_t SPRITE_Y_FLIP; +extern const uint16_t SPRITE_16_TALL; +extern const uint16_t SPRITE_16_WIDE; + +// g_block +extern const uint16_t SPRITE_PRIORITY_SHIFT; +extern const uint16_t SPRITE_PAL_SHIFT; + +// x_block +extern const uint16_t SPRITE_X_FLIP; + +// MARK: Read functions + +static const VDP_REG VDP_CURRENT_RASTER_BASE = VDP_BASE + 0x00; + +#define VDP_CURRENT_RASTER_X (*((VDP_REG) VDP_CURRENT_RASTER_BASE + 0)) +#define VDP_CURRENT_RASTER_Y (*((VDP_REG) VDP_CURRENT_RASTER_BASE + 2)) + +void vdp_wait_frame_ended(void); + +// MARK: Write functions + +void vdp_enable_copper(uint8_t enable); + +void vdp_enable_layers(VDPLayer layers); +void vdp_set_alpha_over_layers(VDPLayer layers); +void vdp_set_wide_map_layers(VDPLayer layers); + +void vdp_set_layer_tile_base(uint8_t layer, uint16_t address); +void vdp_set_layer_map_base(uint8_t layer, uint16_t address); + +void vdp_seek_vram(uint16_t address); +void vdp_fill_vram(uint16_t count, uint16_t word); +void vdp_write_vram(uint16_t word); +void vdp_write_vram_block(const uint16_t *data, uint16_t size); +void vdp_set_vram_increment(uint8_t increment); + +void vdp_write_palette_range(uint8_t color_id_start, uint32_t count, const uint16_t *palette_start); + +void vdp_set_single_palette_color(uint8_t color_id, uint16_t color); +void vdp_seek_palette(uint8_t palette_id); +void vdp_write_palette_color(uint16_t color); + +void vdp_set_layer_scroll(uint8_t layer, uint16_t scroll_x, uint16_t scroll_y); + +void vdp_set_sprite_tile_base(uint16_t base); +void vdp_write_single_sprite_meta(uint8_t sprite_id, uint16_t x_block, uint16_t y_block, uint16_t g_block); +void vdp_seek_sprite(uint8_t sprite_id); +void vdp_write_sprite_meta(uint16_t x_block, uint16_t y_block, uint16_t g_block); +void vdp_clear_all_sprites(void); + +void vdp_set_affine_matrix(int16_t a, int16_t b, int16_t c, int16_t d); +void vdp_set_affine_pretranslate(int16_t x, int16_t y); + +void vdp_set_target_raster_x(uint16_t x); +void vdp_set_target_raster_y(uint16_t y); + +void vdp_set_affine_matrix(int16_t a, int16_t b, int16_t c, int16_t d); +void vdp_set_affine_pretranslate(int16_t x, int16_t y); +void vdp_set_affine_translate(int16_t x, int16_t y); + +// MARK: Convenience + +bool vdp_layer_is_odd(VDPLayer layer); + +#endif /* vdp_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/vdp_print.c b/dan-rodrigues_icestation-32/software/lib/vdp_print.c new file mode 100644 index 0000000000000000000000000000000000000000..e5ee673e28b9ae6a1ee7d8aa74622d805da6cc1a --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/vdp_print.c @@ -0,0 +1,90 @@ +// vdp_print.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "vdp_print.h" + +#include "tinyprintf.h" + +static uint8_t current_x, current_y; +static uint16_t current_palette_mask; +static VDPLayer current_layer; +static uint16_t current_vram_base; + +static void seek_update() { + bool second_page = (current_x % 128) >= 64; + current_x %= 64; + + uint16_t address = current_y * 64 + current_x; + address += (second_page ? 0x1000 : 0); + + vdp_seek_vram(current_vram_base + address); +} + +static void vdp_putc(__attribute__((unused)) void *p, char c) { + uint16_t map = c & 0xff; + map |= current_palette_mask; + + vdp_write_vram(map); + current_x++; + + if (current_x == 64) { + seek_update(); + } +} + +void vp_print_init() { + init_printf(NULL, vdp_putc); +} + +void vp_printf_list(uint8_t x, uint8_t y, uint8_t palette, VDPLayer layer, uint16_t vram_base, const char *fmt, va_list args) { + vdp_set_vram_increment(1); + + current_palette_mask = palette << SCROLL_MAP_PAL_SHIFT; + current_x = x; + current_y = y; + current_layer = layer; + current_vram_base = vram_base; + + seek_update(); + + tfp_format(NULL, vdp_putc, fmt, args); +} + +void vp_printf(uint8_t x, uint8_t y, uint8_t palette, VDPLayer layer, uint16_t vram_base, const char *fmt, ...) { + va_list args; + va_start(args, fmt); + vp_printf_list(x, y, palette, layer, vram_base, fmt, args); + va_end(args); +} + +void vp_clear_row(uint8_t y, VDPLayer layer, uint16_t vram_base, bool half_width) { + vdp_set_vram_increment(1); + + current_x = 0; + current_y = y; + current_palette_mask = 0; + current_layer = layer; + current_vram_base = vram_base; + + seek_update(); + + + uint32_t width = SCREEN_ACTIVE_WIDTH / 8; + width /= (half_width ? 2 : 1); + + for (uint32_t i = 0; i < width; i++) { + vdp_putc(NULL, ' '); + } +} + +uint8_t vp_center_string_x(const char *string) { + uint8_t length = 0; + while (*string++) { + length++; + } + + return SCREEN_ACTIVE_WIDTH / 8 / 2 - length / 2; +} diff --git a/dan-rodrigues_icestation-32/software/lib/vdp_print.h b/dan-rodrigues_icestation-32/software/lib/vdp_print.h new file mode 100644 index 0000000000000000000000000000000000000000..1d8871bddf05006e4ad713e37751d38de7c9bea4 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/vdp_print.h @@ -0,0 +1,25 @@ +// vdp_print.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef vdp_print_h +#define vdp_print_h + +#include +#include +#include + +#include "vdp.h" + +void vp_print_init(void); + +void vp_printf(uint8_t x, uint8_t y, uint8_t palette, VDPLayer layer, uint16_t vram_base, const char *fmt, ...); +void vp_printf_list(uint8_t x, uint8_t y, uint8_t palette, VDPLayer layer, uint16_t vram_base, const char *fmt, va_list args); + +void vp_clear_row(uint8_t y, VDPLayer layer, uint16_t vram_base, bool half_width); + +uint8_t vp_center_string_x(const char *string); + +#endif /* vdp_print_h */ diff --git a/dan-rodrigues_icestation-32/software/lib/vdp_regs.h b/dan-rodrigues_icestation-32/software/lib/vdp_regs.h new file mode 100644 index 0000000000000000000000000000000000000000..67841e05d6aa807cbe7db55f2e3697e57d6d6cb1 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/lib/vdp_regs.h @@ -0,0 +1,49 @@ +// vdp_regs.h +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#ifndef vdp_regs_h +#define vdp_regs_h + +#include "vdp.h" + +// these register locations are kept in a separate header to avoid importing them using vdp.h +// only code that actually needs to know reg locations should include this (i.e. copper program) + +static VDP_REG VDP_HSCROLL_BASE = VDP_BASE + 0x10; +static VDP_REG VDP_VSCROLL_BASE = VDP_BASE + 0x14; + +#define VDP_LAYER_ENABLE (*((VDP_REG) VDP_BASE + 11)) +#define VDP_ALPHA_OVER_ENABLE (*((VDP_REG) VDP_BASE + 12)) +#define VDP_SCROLL_WIDE_MAP_ENABLE (*((VDP_REG) VDP_BASE + 13)) + +#define VDP_MATRIX_A (*((VDP_REG) VDP_HSCROLL_BASE + 1)) +#define VDP_MATRIX_B (*((VDP_REG) VDP_HSCROLL_BASE + 2)) +#define VDP_MATRIX_C (*((VDP_REG) VDP_HSCROLL_BASE + 3)) +#define VDP_MATRIX_D (*((VDP_REG) VDP_VSCROLL_BASE + 0)) + +#define VDP_AFFINE_TRANSLATE_X (*((VDP_REG) VDP_HSCROLL_BASE + 0)) +#define VDP_AFFINE_TRANSLATE_Y (*((VDP_REG) VDP_VSCROLL_BASE + 1)) + +#define VDP_AFFINE_PRETRANSLATE_X (*((VDP_REG) VDP_VSCROLL_BASE + 2)) +#define VDP_AFFINE_PRETRANSLATE_Y (*((VDP_REG) VDP_VSCROLL_BASE + 3)) + +#define VDP_SPRITE_TILE_BASE (*((VDP_REG) VDP_BASE + 7)) +#define VDP_SPRITE_BLOCK_ADDRESS (*((VDP_REG) VDP_BASE + 0)) +#define VDP_SPRITE_DATA (*((VDP_REG) VDP_BASE + 1)) + +#define VDP_PALETTE_ADDRESS (*((VDP_REG) VDP_BASE + 2)) +#define VDP_PALETTE_WRITE_DATA (*((VDP_REG) VDP_BASE + 3)) + +#define VDP_VRAM_ADDRESS (*((VDP_REG) VDP_BASE + 4)) +#define VDP_VRAM_WRITE_DATA (*((VDP_REG) VDP_BASE + 5)) +#define VDP_ADDRESS_INCREMENT (*((VDP_REG) VDP_BASE + 6)) + +#define VDP_ENABLE_COPPER (*((VDP_REG) VDP_BASE + 8)) + +#define VDP_SCROLL_TILE_ADDRESS_BASE (*((VDP_REG) VDP_BASE + 9)) +#define VDP_SCROLL_MAP_ADDRESS_BASE (*((VDP_REG) VDP_BASE + 10)) + +#endif /* vdp_regs_h */ diff --git a/dan-rodrigues_icestation-32/software/platformer/fg_map.h b/dan-rodrigues_icestation-32/software/platformer/fg_map.h new file mode 100644 index 0000000000000000000000000000000000000000..7c4f38ab8d9dbe8b40f0f7533df872b5c7774c4b --- /dev/null +++ b/dan-rodrigues_icestation-32/software/platformer/fg_map.h @@ -0,0 +1,3591 @@ +#include +#include + +const uint16_t fg_map[] = { + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x40f8, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2182, + 0x2183, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2194, + 0x2195, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x2192, + 0x2193, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01ea, + 0x07ea, + 0x0122, + 0x0122, + 0x03d7, + 0x03d6, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01d6, + 0x01d7, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x07ec, + 0x01dc, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x7586, + 0x7786, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x03dc, + 0x05ec, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01ea, + 0x07ea, + 0x0122, + 0x0122, + 0x03e7, + 0x03e6, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x01e6, + 0x01e7, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x07dc, + 0x01ec, + 0x0122, + 0x0122, + 0x0122, + 0x01d8, + 0x01d9, + 0x7186, + 0x7386, + 0x03d9, + 0x03d8, + 0x0122, + 0x0122, + 0x0122, + 0x03ec, + 0x05dc, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122, + 0x0122 +}; + +const size_t fg_map_length = 3584; diff --git a/dan-rodrigues_icestation-32/software/platformer/main.c b/dan-rodrigues_icestation-32/software/platformer/main.c new file mode 100644 index 0000000000000000000000000000000000000000..f9486b9b2331f9eb31d92c14970439960cab81cc --- /dev/null +++ b/dan-rodrigues_icestation-32/software/platformer/main.c @@ -0,0 +1,380 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "vdp.h" +#include "math_util.h" +#include "assert.h" +#include "gamepad.h" + +#include +#include + +#include "fg_tiles.h" +#include "fg_map.h" +#include "fg_palette.h" + +#include "miyamoto_tiles.h" +#include "miyamoto_palette.h" + +// vram layout constants + +static const uint16_t SCROLL_TILE_BASE = 0x0000; +static const uint16_t SCROLL_MAP_BASE = 0x4000; +static const uint16_t SPRITE_TILE_BASE = 0x6000; + +// sprite graphics + +typedef enum { + RUN0, + RUN1, + RUN2, + + JUMP_RISING, + JUMP_FALLING, + + LOOKING_UP, + + LOOKING_SCREEN_DIRECT, + LOOKING_SCREEN_LEFT, + LOOKING_SCREEN_RIGHT, + + PEACE_SIGN +} HeroFrame; + +static const HeroFrame IDLE_HERO_FRAME = RUN2; + +static const uint8_t HERO_FRAME_MAX_TILES = 2; +static const int16_t HERO_FRAME_TILES_END = -1; + +typedef struct { + HeroFrame frame; + + int16_t x_offset; + int16_t y_offset; + + uint8_t x_flip; + + // const int16_t tiles[HERO_FRAME_MAX_TILES] + const int16_t tiles[2]; +} SpriteFrame; + +// sprite positioning / updating + +static const int32_t Q_1 = 0x10000; + +typedef enum { + LEFT, RIGHT +} SpriteDirection; + +typedef struct { + int16_t x, y; + int16_t x_fraction, y_fraction; +} SpritePosition; + +typedef struct { + int32_t x, y; +} SpriteVelocity; + +typedef struct { + HeroFrame frame; + uint32_t frame_counter; + + SpritePosition position; + SpriteVelocity velocity; + SpriteDirection direction; +} Hero; + +void update_hero_state(Hero *hero, uint16_t pad, uint16_t pad_edge); +void apply_velocity(SpriteVelocity *velocity, SpritePosition *position); + +void draw_hero_sprites(uint8_t *base_sprite_id, Hero *hero, int16_t sprite_tile); +void upload_16x16_sprite(uint16_t source_tile_base, uint16_t sprite_tile); + +static const int16_t GROUND_OFFSET = 415; + +int main() { + vdp_enable_layers(SCROLL0 | SPRITES); + + // the foregound is a 512x512 map tiled repeatedly + vdp_set_wide_map_layers(0); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + const int16_t map_y_offset = -48; + vdp_set_layer_scroll(0, 0, map_y_offset); + + vdp_seek_vram(0); + vdp_fill_vram(0x8000, 0x0000); + + // foreground tiles + + vdp_set_layer_tile_base(0, SCROLL_TILE_BASE); + + // this loads tileset to the 3rd "page" of 128 tiles, where it is expected + vdp_seek_vram(0 + 0x1800); + vdp_write_vram_block(fg_tiles, fg_tiles_length); + + // foreground map + + vdp_set_layer_map_base(0, SCROLL_MAP_BASE); + + vdp_seek_vram(SCROLL_MAP_BASE); + vdp_write_vram_block(fg_map, fg_map_length); + + // foreground palette + + const uint8_t palette_size = 0x10; + + const uint8_t map_palette_id = 2; + vdp_write_palette_range(map_palette_id * palette_size, palette_size, fg_palette); + + // sprites + + vdp_set_sprite_tile_base(SPRITE_TILE_BASE); + + vdp_seek_palette(0); + vdp_write_palette_range(0, miyamoto_palette_length, miyamoto_palette); + + // background color + + const uint16_t background_color = 0xf488; + vdp_set_single_palette_color(0, background_color); + + SpritePosition hero_position = {.x = 400, .y = GROUND_OFFSET, .x_fraction = 0, .y_fraction = 0}; + SpriteVelocity hero_velocity = {0, 0}; + + Hero hero = { + .frame = IDLE_HERO_FRAME, + .frame_counter = 0, + .direction = RIGHT, + .position = hero_position, + .velocity = hero_velocity + }; + + // init gamepad state + + uint16_t p1_pad = 0; + uint16_t p1_pad_edge = 0; + + // init sprites context before entering game loop + + uint8_t base_sprite_id = 0; + vdp_clear_all_sprites(); + + while (true) { + update_hero_state(&hero, p1_pad, p1_pad_edge); + draw_hero_sprites(&base_sprite_id, &hero, 0); + + vdp_wait_frame_ended(); + + pad_read(&p1_pad, NULL, &p1_pad_edge, NULL); + + base_sprite_id = 0; + } + + return 0; +} + +void update_hero_state(Hero *hero, uint16_t pad, uint16_t pad_edge) { + // walking left/right + + const int32_t walk_max_speed = 2 * Q_1; + const int32_t walk_correction_delta = Q_1 / 2; + const int32_t walk_idle_delta = Q_1 / 8; + + SpriteVelocity *velocity = &hero->velocity; + SpritePosition *position = &hero->position; + + if (pad & GP_LEFT && (~pad & GP_RIGHT)) { + velocity->x += !SIGN(velocity->x) ? -walk_correction_delta : -walk_idle_delta; + velocity->x = MAX(-walk_max_speed, velocity->x); + + if (SIGN(velocity->x)) { + hero->direction = LEFT; + } + } else if (pad & GP_RIGHT && (~pad & GP_LEFT)) { + velocity->x += (SIGN(velocity->x) && velocity->x) ? walk_correction_delta : walk_idle_delta; + velocity->x = MIN(walk_max_speed, velocity->x); + + if (!SIGN(velocity->x)) { + hero->direction = RIGHT; + } + } else { + int32_t abs_velocity = ABS(velocity->x); + abs_velocity -= walk_idle_delta; + abs_velocity = (SIGN(abs_velocity) ? 0 : abs_velocity); + velocity->x = (SIGN(velocity->x) ? -abs_velocity : abs_velocity); + } + + // jumping + + const int32_t jump_initial_speed = 5 * Q_1; + + bool grounded = hero->position.y >= GROUND_OFFSET; + + if (grounded && (pad_edge & GP_B)) { + velocity->y = -jump_initial_speed; + } + + // gravity + + const int32_t gravity_delta_high = Q_1 / 2; + const int32_t gravity_delta_low = Q_1 / 6; + const int32_t fall_velocity_max = 5 * Q_1; + + // holding button B sustains the jump for longer + + int32_t gravity_delta = (pad & GP_B ? gravity_delta_low : gravity_delta_high); + + velocity->y += gravity_delta; + velocity->y = MIN(velocity->y, fall_velocity_max); + + // update hero position according to newly set velocity + + apply_velocity(velocity, position); + + // correct position if hero has "fallen through the ground" + + if (position->y > GROUND_OFFSET) { + velocity->y = 0; + position->y = GROUND_OFFSET; + position->y_fraction = 0; + } + + // animation + + grounded = hero->position.y >= GROUND_OFFSET; + + if (grounded) { + // frame for idle state or walking + + switch (hero->frame) { + case RUN0: case RUN1: case RUN2: + break; + default: + hero->frame = IDLE_HERO_FRAME; + break; + } + + int32_t frame_counter = hero->frame_counter; + + if (frame_counter < 0) { + const int32_t hero_default_frame_duration = 5 * Q_1; + frame_counter = hero_default_frame_duration; + hero->frame = (hero->frame == RUN2 ? RUN0 : hero->frame + 1); + } else if (hero->velocity.x != 0) { + int32_t frame_counter_delta = ABS(hero->velocity.x); + frame_counter -= frame_counter_delta; + } else { + hero->frame = IDLE_HERO_FRAME; + } + + hero->frame_counter = frame_counter; + } else { + // frame for jumping or falling + + hero->frame = (SIGN(velocity->y) ? JUMP_RISING : JUMP_FALLING); + } +} + +void apply_velocity(SpriteVelocity *velocity, SpritePosition *position) { + int32_t x_full = position->x * Q_1 | (position->x_fraction & 0xffff); + x_full += velocity->x; + position->x_fraction = x_full & 0xffff; + position->x = x_full / Q_1; + + int32_t y_full = position->y * Q_1 | (position->y_fraction & 0xffff); + y_full += velocity->y; + position->y_fraction = y_full & 0xffff; + position->y = y_full / Q_1; +} + +void draw_hero_sprites(uint8_t *base_sprite_id, Hero *hero, int16_t sprite_tile) { + static const SpriteFrame hero_frames[] = { + {RUN0, 0, -1, 0, {0x000, 0x0e0}}, + {RUN1, 0, 0, 0, {0x002, 0x0e0}}, + {RUN2, 0, 0, 0, {0x004, 0x0e0}}, + + {JUMP_RISING, 0, 0, 0, {0x006, 0x0e8}}, + {JUMP_FALLING, 0, 0, 0, {0x1a4, 0x18e}}, + + {LOOKING_UP, 0, 0, 0, {0x004, 0x140}}, + + {LOOKING_SCREEN_DIRECT, 0, 0, 0, {0x00e, 0x108}}, + {LOOKING_SCREEN_LEFT, 0, 0, 0, {0x00e, 0x0e0}}, + {LOOKING_SCREEN_RIGHT, 0, 0, 1, {0x00e, 0x0e0}}, + + {PEACE_SIGN, 0, 0, 0, {0x16e, 0x166}}, + }; + + static const size_t hero_frame_count = sizeof(hero_frames) / sizeof(SpriteFrame); + + const uint8_t hero_palette = 0; + const uint8_t hero_priority = 3; + + const SpriteFrame *sprite_frame = NULL; + for (uint16_t i = 0; i < hero_frame_count; i++) { + if (hero_frames[i].frame == hero->frame) { + sprite_frame = &hero_frames[i]; + break; + } + } + + assert(sprite_frame); + + uint8_t sprite_id = *base_sprite_id; + int16_t sprite_y = hero->position.y; + + for (uint8_t i = 0; i < HERO_FRAME_MAX_TILES; i++) { + int16_t frame_tile = sprite_frame->tiles[i]; + if (frame_tile == HERO_FRAME_TILES_END) { + break; + } + + // sprite metadata + + uint16_t x_block = hero->position.x + sprite_frame->x_offset; + x_block &= 0x3ff; + bool hero_needs_flip = (hero->direction == RIGHT); + bool frame_needs_flip = sprite_frame->x_flip; + x_block |= (hero_needs_flip ^ frame_needs_flip ? SPRITE_X_FLIP : 0); + + uint16_t y_block = sprite_y + sprite_frame->y_offset; + y_block &= 0x1ff; + y_block |= SPRITE_16_TALL | SPRITE_16_WIDE; + + uint16_t g_block = sprite_tile; + g_block |= hero_priority << SPRITE_PRIORITY_SHIFT | hero_palette << SPRITE_PAL_SHIFT; + + // upload sprite graphis + upload_16x16_sprite(frame_tile, sprite_tile); + + // set sprite metadata (pointing to the graphics uploaded in previous step) + vdp_write_single_sprite_meta(sprite_id, x_block, y_block, g_block); + + sprite_y -= 16; + sprite_id++; + sprite_tile += 2; + } + + *base_sprite_id = sprite_id; +} + +void upload_16x16_sprite(uint16_t source_tile_base, uint16_t sprite_tile) { + vdp_seek_vram(SPRITE_TILE_BASE + sprite_tile * 0x10); + + const uint16_t *source_tiles = miyamoto_tiles + source_tile_base * 0x10; + const uint16_t frame_row_word_size = 0x10 * 2; + + // first row (upper 16x8 half) + vdp_write_vram_block(source_tiles, frame_row_word_size); + + // second row (lower 16x8 half) + const uint16_t sprite_row_word_stride = 0x20 * 0x10 / 2; + vdp_seek_vram(SPRITE_TILE_BASE + (0x10 + sprite_tile) * 0x10); + vdp_write_vram_block(source_tiles + sprite_row_word_stride, frame_row_word_size); +} diff --git a/dan-rodrigues_icestation-32/software/scroll_layers/main.c b/dan-rodrigues_icestation-32/software/scroll_layers/main.c new file mode 100644 index 0000000000000000000000000000000000000000..a2a354d53f60cea62a968e0ed8c1374f901e9004 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/scroll_layers/main.c @@ -0,0 +1,98 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "vdp.h" +#include "font.h" + +// This only exists to test refactoring / rewrites of vdp_bus_arbiter_*.v + +static void print_greeting(uint8_t palette_id, bool flip_x, bool flip_y); + +int main() { + const uint8_t layer_count = 4; + const uint16_t x_base = 500; + const uint16_t y_base = 240; + + uint8_t enabled_layers = SCROLL0 | SCROLL1 | SCROLL2 | (layer_count == 4 ? SCROLL3 : 0); + + vdp_enable_layers(enabled_layers); + vdp_set_wide_map_layers(0); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + const uint16_t tile_vram_base = 0x0000; + + const uint16_t map_vram_base = 0x1000; + const uint16_t map_size = 0x1000; + + for (uint8_t i = 0; i < layer_count; i++) { + uint16_t layer_map_base = i * map_size + map_vram_base; + vdp_set_layer_map_base(i, layer_map_base); + vdp_set_layer_tile_base(i, tile_vram_base); + } + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + upload_font(tile_vram_base); + + const uint16_t bg_color = 0xf033; + static const uint16_t fg_colors[] = {0xffff, 0xfff0, 0xf0ff, 0xf0f0}; + + vdp_set_single_palette_color(0, bg_color); + + for (uint8_t i = 0; i < layer_count; i++) { + vdp_set_single_palette_color(i * 0x10 + 1, fg_colors[i]); + } + + for (uint8_t i = 0; i < layer_count; i++) { + uint16_t layer_map_base = i * map_size + map_vram_base; + vdp_seek_vram(layer_map_base); + + uint8_t palette_id = i; + + // Regular, unflipped text + print_greeting(palette_id, false, false); + + vdp_write_vram(' '); + + // Flipped text + print_greeting(palette_id, true, false); + } + + uint32_t frame_counter = 0; + + while (true) { + for (uint8_t i = 0; i < layer_count; i++) { + uint16_t scroll = frame_counter / (i + 1); + uint16_t layer_ofset = i * 32; + vdp_set_layer_scroll(i, -x_base + layer_ofset + scroll, -y_base + layer_ofset + scroll); + } + + vdp_wait_frame_ended(); + + frame_counter++; + } +} + +static void print_greeting(uint8_t palette_id, bool flip_x, bool flip_y) { + const char *string = "Hello world!"; + + while (*string) { + uint16_t map = *string & 0xff; + map |= palette_id << SCROLL_MAP_PAL_SHIFT; + map |= flip_x << SCROLL_MAP_X_FLIP_SHIFT; + map |= flip_y << SCROLL_MAP_Y_FLIP_SHIFT; + + vdp_write_vram(map); + + string++; + } +} diff --git a/dan-rodrigues_icestation-32/software/sprites/main.c b/dan-rodrigues_icestation-32/software/sprites/main.c new file mode 100644 index 0000000000000000000000000000000000000000..9a7a1d423a615d9d11b9d71b2df64489815b4216 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/sprites/main.c @@ -0,0 +1,178 @@ +// main.c +// +// Copyright (C) 2020 Dan Rodrigues +// +// SPDX-License-Identifier: MIT + +#include "vdp.h" +#include "math_util.h" + +#include +#include + +#include "crystal_tiles.h" +#include "crystal_palette.h" + +static void draw_crystal_sprite(uint8_t *base_sprite_id, uint16_t base_tile, uint8_t palette, uint16_t x, uint16_t y); + +// sprite pattern arrangement + +static const uint8_t YELLOW_PALETTE = 0; +static const uint8_t RED_PALETTE = 1; +static const uint8_t GREEN_PALETTE = 2; +static const uint8_t MAGENTA_PALETTE = 3; + +// background colors to cycle through +// note the format is ARGB16 so all example colors for the background are alpha = 100% +static const uint16_t CYCLED_BACKGROUND_COLORS[] = {0xf088, 0xf600, 0xf888, 0xf000}; + +// sprite circle arrangements + +typedef struct { + uint8_t sprite_count; + uint16_t angle_delta; + int16_t radius; + uint8_t palette; +} CircleArrangement; + +static const CircleArrangement CIRCLE_ARRANGEMENTS[] = { + {.sprite_count = 32, .angle_delta = SIN_PERIOD / 32, .radius = 192, .palette = YELLOW_PALETTE}, + {.sprite_count = 16, .angle_delta = SIN_PERIOD / 16, .radius = 128, .palette = GREEN_PALETTE}, + {.sprite_count = 8, .angle_delta = SIN_PERIOD / 8, .radius = 64, .palette = RED_PALETTE}, + {.sprite_count = 1, .angle_delta = SIN_PERIOD / 1, .radius = 0, .palette = MAGENTA_PALETTE}, +}; + +static const size_t CIRCLE_ARRANGEMENT_COUNT = sizeof(CIRCLE_ARRANGEMENTS) / sizeof(CircleArrangement); + +// sprite animation metadata + +static const uint8_t CRYSTAL_ANIMATION_FRAMES = 8; +static const uint8_t CRYSTAL_FRAME_WIDTH = 32; + +// options to toggle + +// layers must be opted into alpha compositing (normally just 1 layer due to blender limits) +// without it enabled, the "alpha" channel is treated as an intensity from black to the original color +// with it enabled, the alpha channel is used to blend with the topmost opaque layer beneath it +static const bool ENABLE_SPRITE_ALPHA = true; + +// this enables immediate animation for use in the simulator since the frame rate is much lower +static const bool ENABLE_FAST_ANIMATION = false; + +int main() { + // layer configuration (only sprites are used here) + vdp_enable_layers(SPRITES); + vdp_set_alpha_over_layers(ENABLE_SPRITE_ALPHA ? SPRITES : 0); + + const uint16_t tile_base = 0x0000; + vdp_set_sprite_tile_base(tile_base); + + // tile upload + + vdp_set_vram_increment(1); + vdp_seek_vram(tile_base); + vdp_write_vram_block(crystal_tiles, crystal_tiles_length); + + // palette upload + + vdp_seek_palette(0); + + // yellow + for (uint16_t i = 0; i < crystal_palette_length; i++) { + vdp_write_palette_color(crystal_palette[i]); + } + // red + for (uint16_t i = 0; i < crystal_palette_length; i++) { + vdp_write_palette_color(crystal_palette[i] & 0xff00); + } + // green + for (uint16_t i = 0; i < crystal_palette_length; i++) { + vdp_write_palette_color(crystal_palette[i] & 0xf0f0); + } + // magenta + for (uint16_t i = 0; i < crystal_palette_length; i++) { + uint16_t color = crystal_palette[i]; + vdp_write_palette_color((color & 0xff00) | (color & 0x00f0) >> 4); + } + + uint16_t frame_counter = 0; + uint8_t base_sprite_id = 0; + + vdp_clear_all_sprites(); + + while(true) { + // first row of 32x32 animation frames + const uint8_t crystal_frames_bank_0 = 0x000; + // second row of 32x32 animation frames + const uint8_t crystal_frames_bank_1 = 0x040; + + uint8_t crystal_frame = frame_counter / 4; + crystal_frame &= (CRYSTAL_ANIMATION_FRAMES - 1); + uint16_t crystal_tile_base = (crystal_frame & 3) * CRYSTAL_FRAME_WIDTH / 8; + crystal_tile_base += (crystal_frame & 4) ? crystal_frames_bank_1 : crystal_frames_bank_0; + + uint8_t back_color_index = frame_counter / (ENABLE_FAST_ANIMATION ? 1: 0x80) & 3; + + vdp_set_single_palette_color(0, CYCLED_BACKGROUND_COLORS[back_color_index]); + + vdp_seek_sprite(0); + + for (uint8_t circle = 0; circle < CIRCLE_ARRANGEMENT_COUNT; circle++) { + CircleArrangement arrangement = CIRCLE_ARRANGEMENTS[circle]; + + int16_t radius = arrangement.radius; + uint8_t palette = arrangement.palette; + uint8_t sprite_count = arrangement.sprite_count; + uint16_t angle_delta = arrangement.angle_delta; + + uint16_t angle = frame_counter; + + for (uint8_t i = 0; i < sprite_count; i++) { + const int16_t screen_center_x = 848 / 2; + const int16_t screen_center_y = 480 / 2; + + int16_t sin_t = sin(angle); + int16_t cos_t = cos(angle); + + int16_t sprite_x = sys_multiply(cos_t, -radius) / SIN_MAX; + int16_t sprite_y = sys_multiply(sin_t, -radius) / SIN_MAX; + + sprite_x += screen_center_x; + sprite_y += screen_center_y; + + draw_crystal_sprite(&base_sprite_id, crystal_tile_base, palette, sprite_x, sprite_y); + + angle += angle_delta; + } + } + + vdp_wait_frame_ended(); + + base_sprite_id = 0; + frame_counter++; + } +} + +static void draw_crystal_sprite(uint8_t *base_sprite_id, uint16_t base_tile, uint8_t palette, uint16_t x, uint16_t y) { + const int16_t sprite_x_offset = -16; + const int16_t sprite_y_offset = -16; + + for (uint8_t i = 0; i < 4; i++) { + bool right_column = (i & 1); + bool bottom_row = (i & 2); + + uint16_t x_block = x + sprite_x_offset + (right_column ? 0x10 : 0); + + uint16_t y_block = y + sprite_y_offset + (bottom_row ? 0x10 : 0); + y_block &= 0x1ff; + y_block |= SPRITE_16_TALL | SPRITE_16_WIDE; + + uint16_t g_block = base_tile; + g_block += (right_column ? 0x02 : 0); + g_block += (bottom_row ? 0x20 : 0); + g_block |= palette << SPRITE_PAL_SHIFT; + + vdp_write_sprite_meta(x_block, y_block, g_block); + *base_sprite_id += 1; + } +} diff --git a/dan-rodrigues_icestation-32/software/tetris/main.c b/dan-rodrigues_icestation-32/software/tetris/main.c new file mode 100644 index 0000000000000000000000000000000000000000..1696181be9b8e15521d17a7ca123ec7e0c260291 --- /dev/null +++ b/dan-rodrigues_icestation-32/software/tetris/main.c @@ -0,0 +1,1023 @@ +// main.c: Tetris +// +// Copyright (C) 2020 mara +// based on tetris4terminals by fnh , adapted by emard +// SPDX-License-Identifier: MIT + +// Basic tetris game, demonstrates: +// - use of sprites over tile map combining text and custom tiles +// - use of different palettes, simple palette animation +// - use of gamepad edge triggered actions +// - unpredictability by seeding a random generator with keypress time + +#include +#include + +#include "audio.h" +#include "vdp.h" +#include "font.h" +#include "gamepad.h" +#include "rand.h" + +#include "shortbeep.h" +#include "longbeep.h" + +// screen and timing +// cannot use the constant here due to gcc error "error: initializer element is not constant" +static const uint16_t TILES_W = /* SCREEN_ACTIVE_WIDTH */ 848 / 8; +static const uint16_t TILES_H = /* SCREEN_ACTIVE_HEIGHT */ 480 / 8; +static const uint32_t FRAME_MS = 17; +static const uint16_t TILE_VRAM_BASE = 0x0000; +static const uint16_t MAP_VRAM_BASE = 0x4000; + +// max level +// 9: (default), 0.1s delay between steps +// 10: impossible, no delay between steps +static const uint8_t MAX_level = 9; + +// number of different block shapes (changing this will require quite a few +// other changes throughout the game) +static const uint8_t NUM_SHAPES = 7; + +// starts game with step 1 s at level 1, it's a longest step time +static const uint32_t MS_STEP_START = 1000; +#define STEP_FASTER(x) x*3/4 + +// board definitions +#define ROWS 24 // height of board +#define COLS 10 // width of board + +static const uint8_t ROWSD = 23; // last N rows of active gamefield displayed +#define ROW0 (ROWS - ROWSD) // first row displayed +static const uint8_t ROWNEW = 0; // ROW in memory where new piece appears +static const uint8_t COLNEW = 3; // COL in memory where new piece appears + +// screen position of board +static const uint16_t BOARD_X = TILES_W / 2 - (COLS + 20) / 2; +static const uint16_t BOARD_Y = TILES_H / 2 - ROWS / 2; + +// screen position of score and level indicators +static const uint16_t INFO_X = BOARD_X + COLS + 5; +static const uint16_t INFO_Y = BOARD_Y + ROWS / 2 + 1; + +// current game state (bitfield) +enum game_state { + PLAYING, + TIMEOUT, + GAME_OVER, + BEGINNING, + PAUSED, +}; + +// game actions +enum game_cmd { + CMD_NONE, + CMD_LEFT, + CMD_RIGHT, + CMD_ROTATE_CCW, + CMD_ROTATE_CW, + CMD_DROP, + CMD_START, +}; + +// game sounds +enum game_sound { + SND_SHORTBEEP = 0, // https://freesound.org/people/solernix/sounds/540902/ + SND_LONGBEEP = 1, // https://freesound.org/people/pan14/sounds/263133/ +}; + +static const int16_t *const SAMPLE_POINTERS[] = {shortbeep, longbeep}; +static const size_t *const SAMPLE_LENGTHS[] = {&shortbeep_length, &longbeep_length}; +const int8_t VOLUME = 0x0c; +const int16_t PITCH = 0x1000; // neutral pitch + +// graphics tiles +enum game_chars { + CHAR_SPACE = ' ', + // walls and floor of board (must be consecutive) + CHAR_WALL = 140, + CHAR_FLOOR = 141, + CHAR_FLOOR_LEFT = 142, + CHAR_FLOOR_RIGHT = 143, + // tetris block types are consecutive from here + CHAR_BLOCK = 128, +}; + +// graphics palettes +enum game_palettes { + PAL_MAIN = 0, + PAL_BLOCK = 1, // block palettes are consecutive from here + PAL_BLINK = 14, + PAL_ALT = 15, +}; + +// high-scores: 1 point per new block, 20 points per completed row +static const uint32_t SCORE_PER_BLOCK = 1; +static const uint32_t SCORE_PER_ROW = 20; + + +// color per block type, this consists of: +// foreground color, background color, background fade +static const uint16_t BLOCK_COLORS[][3] = { + {0xf660, 0xfff0, 0x0002}, // yellow box 2x2 + {0xf606, 0xff0f, 0x0020}, // lilac T-shape + {0xf066, 0xf0ff, 0x0300}, // cyan straight 1x4 + {0xf060, 0xf0f0, 0x0202}, // green S-shape + {0xf600, 0xff00, 0x0011}, // red Z-shape + {0xf630, 0xff80, 0x0012}, // orange L-shape + {0xf006, 0xf00f, 0x0110}, // blue J-shape +}; + +// 8x8 binary glyphs for block types +static const char BLOCK_GLYPHS[][8] = { + { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O) + { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T) + { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I) + { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S) + { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z) + { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L) + { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J) +}; + +// 8x8 binary glyphs for walls and floors and decorations +static const char WALL_GLYPHS[][8] = { + { 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18}, // Wall + { 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00}, // Floor + { 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00}, // Left corner + { 0x0c, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00}, // Right corner +}; + +/* Each shape of Tetris block in 4 rotations. + * There are four pixels per shape, represented as positions, each pixel position is in a (row << 4 | column) format. +*/ +static const uint8_t ROTATED_BLOCK_PATTERN[][4] = { + // O: yellow square 2x2, all rotations the same + // xx + // xx + {0x11, 0x12, 0x21, 0x22}, + {0x11, 0x12, 0x21, 0x22}, + {0x11, 0x12, 0x21, 0x22}, + {0x11, 0x12, 0x21, 0x22}, + + // T: lilac T-shape block + // xxx + // x + {0x11, 0x12, 0x13, 0x22}, + {0x02, 0x12, 0x13, 0x22}, + {0x02, 0x11, 0x12, 0x13}, + {0x02, 0x11, 0x12, 0x22}, + + // I: cyan 1x4 block + // xxxx + {0x02, 0x12, 0x22, 0x32}, + {0x10, 0x11, 0x12, 0x13}, + {0x02, 0x12, 0x22, 0x32}, + {0x10, 0x11, 0x12, 0x13}, + + // S: red 2+2 shifted block + // xx + // xx + {0x12, 0x13, 0x21, 0x22}, + {0x11, 0x21, 0x22, 0x32}, + {0x12, 0x13, 0x21, 0x22}, + {0x11, 0x21, 0x22, 0x32}, + + // Z: green 2+2 shifted block (inverse to red) + // xx + // xx + {0x11, 0x12, 0x22, 0x23}, + {0x12, 0x21, 0x22, 0x31}, + {0x11, 0x12, 0x22, 0x23}, + {0x12, 0x21, 0x22, 0x31}, + + // L: blue 3+1 L-shaped block + // xxx + // .x + {0x11, 0x12, 0x13, 0x21}, + {0x11, 0x21, 0x31, 0x32}, + {0x23, 0x31, 0x32, 0x33}, + {0x12, 0x13, 0x23, 0x33}, + + // J: orange 1+3 L-shaped block + // xxx + // x. + {0x11, 0x12, 0x13, 0x23}, + {0x11, 0x12, 0x21, 0x31}, + {0x21, 0x31, 0x32, 0x33}, + {0x13, 0x23, 0x32, 0x33}, +}; + +// global state +static enum game_state state; +static uint8_t command; + +static uint8_t free_rows; +static uint8_t board[ROWS][COLS]; // the main game-board + +static bool show_block; +static uint8_t current_index; // index of the current block (for colorization) +static const uint8_t *current_block; // bit-pattern of the current block +static uint8_t current_rotation; +static int8_t current_row; // row of the current block +static int8_t current_col; // col of the current block + +// block animation +static int8_t current_xanim; // delta of displayed x position to real x position (in screen pixels) +static int8_t current_yanim; // delta of displayed y position to real y position (in screen pixels) + +static uint8_t lines; // number of fully removed lines +static uint8_t level; // current level +static uint32_t score; // current game score + +static int time_now_ms, time_next_ms; +static int step_ms; // time step of the piece to fall one tile + +// icestation controller state +static uint16_t p1_current = 0; +static uint16_t p2_current = 0; +static uint16_t p1_edge = 0; +static uint16_t p2_edge = 0; + +// 2 fair randomizer pools +static uint8_t shuffled_pool[2][7] = { {0,1,2,3,4,5,6}, {0,1,2,3,4,5,6} }; +static uint8_t active_pool = 0; // alternates 0/1 +static uint8_t pool_index = 0; // 0-7 + +// palette fade/blink state +uint8_t fade_intensity = 0; +bool fade_direction = true; + +/** + * Exchange 2 random indices in the pool. + */ +static void shuffle_inactive_pool(void) { + uint8_t x = 7, y = 7; + uint8_t i, t; + while (x == 7) + x = randbits(3); + while (y == 7 || y == x) + y = randbits(3); + // x=0..6 y=0..6 + i = active_pool ^ 1; // inactive pool + // exchange using temprary var + t = shuffled_pool[i][x]; + shuffled_pool[i][x] = shuffled_pool[i][y]; + shuffled_pool[i][y] = t; +} + +/** + * Create fair-random new block + * from the active shuffled pool + */ +static void create_random_block(void) { + uint8_t x; + shuffle_inactive_pool(); + x = shuffled_pool[active_pool][pool_index]; + if (++pool_index == 7) { + pool_index = 0; + active_pool ^= 1; + } + current_index = x; + current_rotation = 0; + current_block = ROTATED_BLOCK_PATTERN[current_index * 4 + (current_rotation & 3)]; +} + +/** + * Rotate current block by a multiple of 90 degrees. + */ +static void rotate_block(char r) { + current_rotation = (current_rotation + r) & 3; + current_block = ROTATED_BLOCK_PATTERN[current_index * 4 + (current_rotation & 3)]; +} + +/** + * Accessor function for the gaming board position at (row,col). + * Use val=1 for occupied and val=0 for empty places. + */ +static void set_pixel(uint8_t row, uint8_t col, uint8_t val) { + board[row][col] = val; +} + +/** + * Get raw pixel value at a position on the board. + */ +static uint8_t get_pixel(uint8_t row, uint8_t col) { + return board[row][col]; +} + +/** + * Check whether the gaming board position at (row,col) is occupied. + */ +static bool occupied(uint8_t row, uint8_t col) { + return board[row][col] != 0; +} + +/** + * Clear the whole gaming board. + */ +static void clear_board(void) { + for (uint8_t r = 0; r < ROWS; r++) { + for (uint8_t c = 0; c < COLS; c++) { + set_pixel(r, c, 0); + } + } +} + +/** + * Check whether the current block fits at the position given by + * (current_row, current_col). + * Returns 1 if the block fits, and 0 if not. + */ +static bool test_if_block_fits(void) { + for (uint8_t idx = 0; idx < 4; ++idx) { + int cri = current_row + (current_block[idx] >> 4); + int ccj = current_col + (current_block[idx] & 0xf); + + if (ccj < 0) return 0; // too far left + if (ccj >= COLS) return 0; // too far right + if (cri >= ROWS) return 0; // too low + + if (occupied(cri, ccj)) return 0; + } + + return 1; // block fits +} + +/** + * Copy the bits from the current block at its current position + * to the gaming board. This means to fix the current 'foreground' + * block into the static 'background' gaming-board pattern. + */ +static void copy_block_to_gameboard(void) { + for (uint8_t idx = 0; idx < 4; ++idx) { + uint8_t cri = current_row + (current_block[idx] >> 4); + uint8_t ccj = current_col + (current_block[idx] & 0xf); + + set_pixel(cri, ccj, current_index + 1); + } +} + +/** + * Check whether the specified game-board row (0=top,23=bottom) + * is complete (all bits set) or not. + */ +static bool is_complete_row(uint8_t r) { + for (uint8_t c = 0; c < COLS; c++) { + if (!occupied(r, c)) + return 0; + } + + return 1; +} + +/** + * Remove one (presumed complete) row from the game-board, + * so that all rows above the specified row drop one level. + */ +static void remove_row(uint8_t row) { + for (uint8_t c = 0; c < COLS; c++) { + for (uint8_t r = row; r > 0; r--) { + set_pixel(r, c, get_pixel(r-1, c)); + } + + // finally, clear topmost pixel + set_pixel(0, c, 0); + } +} + +/** + * Put a single character or other tile on the screen. + */ +static void scr_putc(uint8_t y, uint8_t x, uint16_t palette_mask, char c) { + uint16_t map = c & 0xff; + map |= palette_mask; + + uint16_t address = y * 64 + x % 64 + ((x % 128) >= 64 ? 0x1000 : 0); + vdp_seek_vram(MAP_VRAM_BASE + address); + vdp_write_vram(map); +} + +/** Clear screen. + */ +static void scr_clear(void) { + vdp_seek_vram(MAP_VRAM_BASE); + vdp_fill_vram(0x2000, ' '); +} + +/** + * Make a sound. + */ +static void sound_play(enum game_sound ch) { + AUDIO_GB_PLAY = 1 << ch; +} + +/** + * Print the given integer value, zero-padded to provided width. + * values that don't fit will be truncated. + */ +static void scr_zpadnum(uint8_t y, uint8_t x, uint16_t palette_mask, uint32_t val, uint8_t width) { + x += width - 1; + for (uint8_t i = 0; i < width; ++i) { + scr_putc(y, x, palette_mask, '0' + (val % 10)); + val /= 10; + --x; + } +} + +/** + * Print a string. + */ +static void scr_puts(uint8_t y, uint8_t x, uint16_t palette_mask, char *s) { + while (*s) { + scr_putc(y, x, palette_mask, *s); + ++x; + ++s; + } +} + +/** + * Display (or erase) the current block at its current position, + * depending on the show_block global. + */ +static void update_block_sprites(void) { + vdp_seek_sprite(0); + if (!show_block) { + // tetris pieces have four blocks, so only four sprites will be in use + for (uint8_t idx = 0; idx < 4; ++idx) { + vdp_write_sprite_meta(0, SCREEN_ACTIVE_HEIGHT, 0); + } + } else { + uint16_t sprite_g = (CHAR_BLOCK + current_index) | ((PAL_BLOCK + current_index) << SPRITE_PAL_SHIFT) | (3 << SPRITE_PRIORITY_SHIFT); + for (uint8_t idx = 0; idx < 4; ++idx) { + uint8_t cri = current_row + (current_block[idx] >> 4); + uint8_t crj = current_col + (current_block[idx] & 0xf); + vdp_write_sprite_meta(((BOARD_X + crj) * 8 + current_xanim) & 0x3ff, + ((BOARD_Y + cri - ROW0) * 8 + current_yanim) & 0x1ff, + sprite_g); + } + } +} + +/** + * Display the current game board. + * This method redraws the whole gaming board including borders. + */ +static void display_board(void) { + uint8_t r, c; + + for (r = 0; r < ROWSD; r++) { + scr_putc(BOARD_Y + r, BOARD_X - 1, 0, CHAR_WALL); // one row of the board: border, data, border + + for (c = 0; c < COLS; c++) { + uint8_t val = get_pixel(r + ROW0, c); + uint16_t tile; + if (val != 0) { // Part of block + tile = ((PAL_BLOCK + val - 1) << SCROLL_MAP_PAL_SHIFT); + tile |= CHAR_BLOCK + val - 1; + } else { // Background + tile = (c & 1) ? (PAL_ALT << SCROLL_MAP_PAL_SHIFT) : (PAL_MAIN << SCROLL_MAP_PAL_SHIFT); + tile |= CHAR_SPACE; + } + scr_putc(BOARD_Y + r, BOARD_X + c, tile, 0); + } + + scr_putc(BOARD_Y + r, BOARD_X + COLS, 0, CHAR_WALL); + } + + // print floor + scr_putc(BOARD_Y + r, BOARD_X - 1, 0, CHAR_FLOOR_LEFT); + for(c = 0; c < COLS; c++) + scr_putc(BOARD_Y + r, BOARD_X + c, 0, CHAR_FLOOR); + scr_putc(BOARD_Y + r, BOARD_X + COLS, 0, CHAR_FLOOR_RIGHT); +} + +/** + * Display the current level and score values, and paused state. + */ +static void display_score(void) { + const uint16_t blink = PAL_BLINK << SCROLL_MAP_PAL_SHIFT; + + scr_puts(INFO_Y, INFO_X + 0, 0, "Level: "); + scr_zpadnum(INFO_Y, INFO_X + 7, 0, level, 2); + + scr_puts(INFO_Y + 1, INFO_X + 0, 0, "Score: "); + scr_zpadnum(INFO_Y + 1, INFO_X + 7, 0, score, 4); + + if (state == PAUSED) { + scr_puts(INFO_Y + 3, INFO_X + 0, blink, "[Paused]"); + } else { + scr_puts(INFO_Y + 3, INFO_X + 0, blink, " "); + } +} + +// Efficiently center fixed-length message. +#define CENTER(y, color, message) scr_puts(y, TILES_W / 2 - (sizeof(message) - 1) / 2, color, message) + +/** + * Called when the game starts initially. + */ +static void do_beginning(void) { + const uint16_t blink = PAL_BLINK << SCROLL_MAP_PAL_SHIFT; + scr_clear(); + show_block = false; + + CENTER(TILES_H / 2 - 2, 0, "Welcome to IceTetris!"); + CENTER(TILES_H / 2 + 2, blink, "Press [Start] to start."); +} + +/** + * Called when the game is over. + */ +static void do_gameover(void) { + const uint16_t blink = PAL_BLINK << SCROLL_MAP_PAL_SHIFT; + scr_clear(); + show_block = false; + + CENTER(TILES_H / 2 - 1, 0, "Game over!"); + + scr_puts(TILES_H / 2 + 1, 40, 0, "Level: "); + scr_zpadnum(TILES_H / 2 + 1, 47, 0, level, 2); + + scr_puts(TILES_H / 2 + 1, 50, 0, "Score: "); + scr_zpadnum(TILES_H / 2 + 1, 57, 0, score, 4); + + CENTER(TILES_H / 2 + 3, blink, "Press [Start] to start a new game."); +} + +/** + * Enter the specified game state. + */ +static void set_state(enum game_state s) { + enum game_state oldstate = state; + state = s; + + /* Leaving state. */ + switch (oldstate) { + case PAUSED: + display_score(); + break; + default: + break; + } + + /* Entering state. */ + switch (state) { + case GAME_OVER: + do_gameover(); + break; + case BEGINNING: + do_beginning(); + break; + case PAUSED: + display_score(); + break; + default: + break; + } +} + +/** + * Check for completed rows and remove them from the gaming board. + */ +static void check_remove_completed_rows(void) { + uint8_t r, removed; + + removed = 0; + for (r = 0; r < ROWS; r++) { + if (is_complete_row(r)) { + removed++; + break; + } + } + + removed = 0; + for (r = 0; r < ROWS; r++) { + if (is_complete_row(r)) { + removed++; + remove_row(r); + score += SCORE_PER_ROW; + if (++lines == 4) { + lines = 0; + if (level < MAX_level) { + level++; + step_ms = STEP_FASTER(step_ms); // 3/4 times game speedup + } + } + } + } + + if (current_row < free_rows) + free_rows = current_row; + free_rows += removed; + + if (removed) { + sound_play(SND_LONGBEEP); + } + display_board(); + display_score(); +} + +/** + * Try to move the current block left. + * This function updates the current_col variable. + */ +static void cmd_move_left(void) { + current_col--; + if (test_if_block_fits()) { + current_xanim = 8; + return; + } + + // If we arrive here, the block doesn't fit, + // and we simply undo the column change. + current_col++; +} + +/** + * Try to move the current block right. + * This function updates the current_col variable. + */ +static void cmd_move_right(void) { + current_col++; + if (test_if_block_fits()) { + current_xanim = -8; + return; + } + + // If we arrive here, the block doesn't fit, + // and we simply undo the column change. + current_col--; +} + +/** + * Try to rotate the current block. + * This function updates the current_block variable. + */ +static void cmd_rotate(char r) { + rotate_block(r); + if (test_if_block_fits()) return; + + // If we arrive here, the block doesn't fit, + // and we undo the rotation by three more rotations... + rotate_block(-r); +} + +/** + * Attempt to move the current block one position down. + * If it doesn't fit, copy the current block to the gaming board + * and check for completed rows. If any completed rows are found, + * check_remove_completed_rows() also automatically repaints the + * whole gaming board. + * Finally, we create a new random block. + */ +static void cmd_move_down(void) { + current_row++; + if (test_if_block_fits()) { + current_yanim = -8; + return; // fits + } + + if (current_row <= ROWNEW + 2) { // already stuck right on top + set_state(GAME_OVER); + return; + } + + // If we arrive here, the block doesn't fit, + // and we have to copy it to the game board. + // we also need a new random block... + current_row--; + + sound_play(SND_SHORTBEEP); + copy_block_to_gameboard(); + check_remove_completed_rows(); // repaints all when necessary + + current_row = ROWNEW; + current_col = COLNEW; + current_yanim = -8; + + create_random_block(); + score += SCORE_PER_BLOCK; +} + +/** + * Set the time target value for the next automatic downward move. + */ +static void set_next_step_timeout(void) { + time_next_ms = time_next_ms + step_ms; +} + +/** + * Check for timed downward movement. + */ +static void check_for_timeout(void) { + if (time_now_ms >= time_next_ms) { + set_next_step_timeout(); + // Don't time out while paused, but keep bumping the next step timeout nevertheless, + // to avoid a sudden avalanche of blocks after unpausing. + if (state == PLAYING) { + set_state(TIMEOUT); + } + } +} + +/** + * Initialize game state for a new game. + */ +static void init_game(void) { + scr_clear(); + clear_board(); + display_board(); + + srand(time_now_ms); // seed RNG with current time + free_rows = ROWS; + for(uint8_t i = 0; i < 7; i++) { + active_pool = 1; + shuffle_inactive_pool(); + active_pool = 0; + shuffle_inactive_pool(); + } + current_row = ROWNEW; + current_col = COLNEW; + create_random_block(); + + score = SCORE_PER_BLOCK; // one block created right now + lines = 0; + level = 1; + time_next_ms = time_now_ms; + step_ms = MS_STEP_START; // level 1 step 1 s -> level 9 step 0.1 s + set_next_step_timeout(); + + state = PLAYING; + command = CMD_NONE; + show_block = true; +} + +static void check_handle_command(void) { + uint8_t tmp; + int8_t previous_row; + + switch (state) { + case BEGINNING: // if in begin screen, only CMD_START will start the game + if (command == CMD_START) { + init_game(); + } + return; + case GAME_OVER: // if the game is over, we only react to the restart command. + if (command == CMD_START) { + init_game(); + } + return; + case PAUSED: // if paused, don't respond to any commands except to unpause + if (command == CMD_START) { + set_state(PLAYING); + } + command = CMD_NONE; + return; + case TIMEOUT: // check for possible timeout. + cmd_move_down(); + if (state == TIMEOUT) { // not gameover by now? + set_state(PLAYING); + } + return; + case PLAYING: // check whether we have a command. If so, handle it. + tmp = command; + command = CMD_NONE; + + switch (tmp) { + case CMD_LEFT: // try to move the current block left + cmd_move_left(); + break; + + case CMD_ROTATE_CCW: // try to rotate the current block + cmd_rotate(1); + break; + + case CMD_ROTATE_CW: // try to rotate the current block + cmd_rotate(-1); + break; + + case CMD_RIGHT: // try to move the current block right + cmd_move_right(); + break; + + case CMD_DROP: // drop the current block + previous_row = current_row; + for( ; test_if_block_fits(); ) current_row++; + + // now one step back, then paint the block in its + // final position and allow to move left-right + // before sticking it finally + current_row--; + + if (previous_row != current_row) { + // after drop, reset step time to proprely delay final "stick" + current_yanim = -8; // soft landing + time_next_ms = time_now_ms; + set_next_step_timeout(); + } + break; + + case CMD_START: // quit and (re-) start the game + set_state(PAUSED); + break; + + default: + // do nothing + break; + } + return; + } +} + +/** + * Blink a palette color. + */ +static void animate_palette(void) { + if (fade_direction) { + fade_intensity += 1; + if (fade_intensity == 63) { + fade_direction = false; + } + } else { + fade_intensity -= 1; + if (fade_intensity == 0) { + fade_direction = true; + } + } + vdp_set_single_palette_color(PAL_BLINK * 16 + 0x2, + 0xf000 | // Fading Alpha as well would create a kind of quadratic effect. + (fade_intensity >> 2) << 8 | + (fade_intensity >> 2) << 4 | + (fade_intensity >> 2) << 0); + +} + +/** + * Animate block sprite movement. This movement is purely visual and does not + * affect the game logic. + */ +static void animate_movement(void) { + if (state == PAUSED) + return; + + // This is a really simple animation. It moves the block into place, + // linearly correcting the current delta towards zero. + if (current_xanim < 0) + current_xanim += 1; + if (current_xanim > 0) + current_xanim -= 1; + if (current_yanim < 0) + current_yanim += 1; + if (current_yanim > 0) + current_yanim -= 1; +} + +/** + * Input processing. + */ +static void process_gamepad_input(void) { + pad_read(&p1_current, &p2_current, &p1_edge, &p2_edge); + + if (p1_edge & GP_DOWN) { + command = CMD_DROP; + } + if (p1_edge & GP_LEFT) { + command = CMD_LEFT; + } + if (p1_edge & GP_RIGHT) { + command = CMD_RIGHT; + } + // Allow using either the shoulder buttons or B/Y to rotate blocks, + // depending on the gamepad either can be more convenient. + if (p1_edge & (GP_L | GP_B)) { + command = CMD_ROTATE_CCW; + } + if (p1_edge & (GP_R | GP_Y)) { + command = CMD_ROTATE_CW; + } + // Both START and SELECT trigger the START command because the ULX3S board doesn't have a + // START button. + if (p1_edge & (GP_START | GP_SELECT)) { + command = CMD_START; + } +} + +/** + * Font upload with a background image instead of a single transparent color. + */ +static void upload_font_with_background(uint16_t vram_base, uint8_t bg[8][8], uint8_t opaque, const char font[][8], uint16_t char_total) { + vdp_seek_vram(vram_base); + vdp_set_vram_increment(1); + + for (uint32_t char_id = 0; char_id < char_total; char_id++) { + for(uint32_t line = 0; line < 8; line++) { + uint32_t monochrome_line = font[char_id][line]; + uint32_t rendered_line = 0; + + for (uint32_t pixel = 0; pixel < 8; pixel++) { + rendered_line <<= 4; + rendered_line |= (monochrome_line & 0x01) ? opaque : bg[line][pixel]; + + monochrome_line >>= 1; + } + + vdp_write_vram(rendered_line & 0xffff); + vdp_write_vram(rendered_line >> 16); + } + } +} + +int main(void) { + vdp_enable_layers(SCROLL0 | SPRITES); + vdp_set_wide_map_layers(SCROLL0); + vdp_set_alpha_over_layers(0); + + vdp_set_vram_increment(1); + + vdp_set_layer_scroll(0, 0, 0); + vdp_clear_all_sprites(); + + vdp_seek_vram(0x0000); + vdp_fill_vram(0x8000, ' '); + + vdp_set_layer_tile_base(0, TILE_VRAM_BASE); + vdp_set_layer_map_base(0, MAP_VRAM_BASE); + vdp_set_sprite_tile_base(TILE_VRAM_BASE); + upload_font_remapped(TILE_VRAM_BASE, 1, 2); + upload_font_remapped_main(TILE_VRAM_BASE + 16 * CHAR_WALL, 1, 2, WALL_GLYPHS, sizeof(WALL_GLYPHS) / 8); + + // Set up block glyph tiles + // Make "frosted look" for block tile background. + uint8_t background[8][8]; + for(uint32_t line = 0; line < 4; line++) { + for (uint32_t pixel = 0; pixel < 4; pixel++) { + uint8_t v = 5 - (line < pixel ? line : pixel); + background[line][pixel] = v; + background[line][7 - pixel] = v; + background[7 - line][pixel] = v; + background[7 - line][7 - pixel] = v; + } + } + + // Upload the tiles with glyphs on top. + upload_font_with_background(TILE_VRAM_BASE + 16 * CHAR_BLOCK, background, 1, BLOCK_GLYPHS, sizeof(BLOCK_GLYPHS) / 8); + + // Set up palette + const uint16_t screen_bg = 0x0000; + const uint16_t font_fg = 0xfccc; + + // Text colors + vdp_set_single_palette_color(PAL_MAIN * 16 + 0x0, screen_bg); + vdp_set_single_palette_color(PAL_MAIN * 16 + 0x1, screen_bg); + vdp_set_single_palette_color(PAL_MAIN * 16 + 0x2, font_fg); + + vdp_set_single_palette_color(PAL_BLINK * 16 + 0x1, screen_bg); // blinking text + vdp_set_single_palette_color(PAL_BLINK * 16 + 0x2, 0xffff); + + vdp_set_single_palette_color(PAL_ALT * 16 + 0x1, 0x4444); // background striping + vdp_set_single_palette_color(PAL_ALT * 16 + 0x2, font_fg); + + // Block colors + for (uint8_t idx = 0; idx < NUM_SHAPES; ++idx) { + vdp_seek_palette((PAL_BLOCK + idx) * 16 + 0x1); + vdp_write_palette_color(BLOCK_COLORS[idx][0]); + + uint16_t color = BLOCK_COLORS[idx][1]; + for (uint8_t f = 0; f < 4; ++f) { + vdp_write_palette_color(color); + color += BLOCK_COLORS[idx][2]; + } + } + + // Audio setup + for (uint32_t i = 0; i < sizeof(SAMPLE_POINTERS) / sizeof(int16_t*); i++) { + volatile AudioChannel *ch = &AUDIO->channels[i]; + audio_set_aligned_addresses(ch, SAMPLE_POINTERS[i], *SAMPLE_LENGTHS[i]); + ch->pitch = PITCH; + ch->flags = 0; + ch->volumes.left = VOLUME; + ch->volumes.right = VOLUME; + } + + // Start frame loop + set_state(BEGINNING); + + fade_intensity = 0; + fade_direction = true; + + while (true) { + process_gamepad_input(); + + check_for_timeout(); + + check_handle_command(); + + update_block_sprites(); + + animate_movement(); + animate_palette(); + + vdp_wait_frame_ended(); + time_now_ms += FRAME_MS; + } +} diff --git a/dan-rodrigues_icestation-32/utilities/common/DataHeader.hpp b/dan-rodrigues_icestation-32/utilities/common/DataHeader.hpp new file mode 100644 index 0000000000000000000000000000000000000000..015e9793f7e0ee9a4e4c6682a4440ceeb2cb3335 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/common/DataHeader.hpp @@ -0,0 +1,129 @@ +#ifndef DataHeader_hpp +#define DataHeader_hpp + +#include +#include +#include +#include + +#include +#include + +class DataHeader { + +public: + template + static void write_combined_h( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream + ); + + template + static void write_h( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream + ); + + template + static void write_c( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream + ); + +private: + template + static void write_body( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + bool split, + std::ostream &stream + ); +}; + +template +void DataHeader::write_h( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream) +{ + stream << "#include " << "\n"; + stream << "#include " << "\n\n"; + + stream << "extern const " << header_type << " " << identifier << "[];" << "\n"; + stream << "extern const size_t " << identifier << "_length;" << "\n"; +} + +template +void DataHeader::write_c( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream) +{ + write_body(data, header_type, identifier, true, stream); +} + +template +void DataHeader::write_combined_h( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + std::ostream &stream) +{ + write_body(data, header_type, identifier, false, stream); +} + +template +void DataHeader::write_body( + const std::vector &data, + const std::string &header_type, + const std::string &identifier, + bool split, + std::ostream &stream) +{ + std::ios_base::fmtflags f(std::cout.flags()); + + const auto indentation = " "; + const auto characters = sizeof(T) * 2; + + // headers for size_t and stdint + + if (split) { + stream << "#include \"" << identifier << ".h\"" << "\n\n"; + } else { + stream << "#include " << "\n"; + stream << "#include " << "\n\n"; + } + + // data + + stream << "const " << header_type << " " << identifier << "[] = {" << "\n"; + + for (auto it = begin(data); it != end(data); ++it) { + auto separator = (it + 1 == end(data)) ? "" : ","; + if (std::is_signed::value) { + stream << indentation << *it << separator << "\n"; + } else { + uint32_t data = *it; + stream << indentation << "0x" << std::setfill('0') << std::setw(characters) << std::hex << data << separator << "\n"; + } + } + + stream << "};" << "\n\n"; + + // length + + stream << "const size_t " << identifier << "_length = " << std::setfill('0') << std::dec << data.size() << ";\n"; + + std::cout.flags(f); +} + +#endif /* DataHeader_hpp */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1629202137dbd542b79b5ec8b3cb3b1ad4ef5c31 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.cpp @@ -0,0 +1,84 @@ +#include +#include + +#include "Image.hpp" +#include "ImageMetrics.h" + +#include "lodepng.h" +#include "lodepng_util.h" + +Image::Image() : bpp(0) {} + +Image::Image(std::vector tile_data, std::vector palette_data, InputFormat format) { + switch (format) { + case PNG: + this->init_from_png(tile_data); + break; + case SNES: + this->init_from_snes(tile_data, palette_data); + break; + default: + throw std::invalid_argument("Input format not handled: " + std::to_string(format)); + } + + // 16 colors only for now + this->bpp = 4; +} + +void Image::init_from_png(std::vector data) { + uint32_t width, height; + std::vector png_decoded; + + lodepng::State lode_state; + lode_state.decoder.color_convert = 0; + + auto error = lodepng::decode(png_decoded, width, height, lode_state, data); + if (error) { + throw std::invalid_argument("Failed to decode png: " + std::string(lodepng_error_text(error))); + } + + if (lode_state.info_png.color.colortype == LCT_PALETTE) { + std::cout << "Found paletted image" << std::endl; + std::cout << "Palette size: " << lode_state.info_raw.palettesize << std::endl; + } else { + throw std::invalid_argument("only color-indexed PNG files not supported for now"); + } + + std::vector indexed_image; + for (auto y = 0; y < height; y++) { + for (auto x = 0; x < width; x++) { + auto pixel_index = y * width + (x ^ 0x01); + auto palette_index = lodepng::getPaletteValue(&png_decoded[0], pixel_index, lode_state.info_raw.bitdepth); + indexed_image.push_back(palette_index); + } + } + + this->tiles = Tiles(indexed_image, width, height); + + uint32_t *png_palette = reinterpret_cast(lode_state.info_png.color.palette); + size_t palette_size = lode_state.info_png.color.palettesize; + std::vector rgba32_palette(png_palette, png_palette + palette_size); + + this->palette = Palette(rgba32_palette); +} + +void Image::init_from_snes(std::vector tile_data, std::vector palette_data) { + this->tiles = Tiles(tile_data); + + // Was a palette provided?.. + if (!palette_data.empty()) { + this->palette = Palette(palette_data); + } else { + // ...if not, generate a simple monochrome one + std::vector mono_palette; + for (auto i = 0; i < 16 * 16; i++) { + uint8_t component = i << 4; + mono_palette.push_back(component); + mono_palette.push_back(component); + mono_palette.push_back(component); + } + + this->palette = Palette(mono_palette); + } +} + diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.hpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.hpp new file mode 100644 index 0000000000000000000000000000000000000000..19fed0e8b361b5788d4ae0e7a79637d52f696d5a --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Image.hpp @@ -0,0 +1,28 @@ +#ifndef Image_hpp +#define Image_hpp + +#include +#include + +#include "Tiles.hpp" +#include "Palette.hpp" + +enum InputFormat { PNG, SNES }; + +class Image { + +public: + Image(); + Image(std::vector tile_data, std::vector palette_data, InputFormat format); + + uint8_t bpp; + + Tiles tiles; + Palette palette; + +private: + void init_from_png(std::vector data); + void init_from_snes(std::vector tile_data, std::vector palette_data); +}; + +#endif /* Image_hpp */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/ImageMetrics.h b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/ImageMetrics.h new file mode 100644 index 0000000000000000000000000000000000000000..5cc807582a39abdd5240967ef7e423c1f5bf0319 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/ImageMetrics.h @@ -0,0 +1,23 @@ +#ifndef ImageMetrics_h +#define ImageMetrics_h + +// xcode does not indent namespace apparently + +namespace ImageMetrics { + +namespace ICS { +const auto TILE_SIZE = 32; +const auto TILE_STRIDE = 16; +const auto TILE_BYTE_STRIDE = TILE_STRIDE * TILE_SIZE; +const auto TILE_ROW_STRIDE = TILE_STRIDE * 8; +} + +namespace SNES { +const auto TILE_SIZE = 32; +const auto TILE_STRIDE = 16; +const auto TILE_ROW_STRIDE = TILE_STRIDE * 8; +} + +} + +#endif /* ImageMetrics_h */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab08fd2f11be39e785ceaaf4f4a9de2a0f4872e5 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.cpp @@ -0,0 +1,42 @@ +#include "Map.hpp" + +std::vector Map::ics_map() { + const auto dimension = 64; + size_t total_tiles = dimension * dimension; + total_tiles = std::min(vram.size() / sizeof(uint16_t), total_tiles); + + std::vector converted_map; + + for(uint16_t i = 0; i < total_tiles; i++) { + // Map the 64x64 space to a snes address + uint16_t offset = 0; + uint16_t snesx = i & 0x1f; + uint16_t snesy = (i / 64) & 0x1f; + uint16_t snes_map_base = (snesx + snesy * 0x20) * 2; + + if (i & 0x20) { + offset += 0x800; + } + if (i >= 64 * 32) { + offset += 0x1000; + } + + uint16_t snes_map = vram[offset + snes_map_base]; + snes_map |= vram[offset + snes_map_base + 1] << 8; + + uint16_t new_map = (snes_map & 0x01ff); + uint16_t y_flip = snes_map & 0x8000; + new_map |= y_flip ? 1 << 10 : 0; + + uint16_t x_flip = snes_map & 0x4000; + new_map |= x_flip ? 1 << 9 : 0; + + uint16_t palette = (snes_map & 0x1c00) >> 10; + new_map |= palette << 12; + + converted_map.push_back(new_map); + } + + return converted_map; +} + diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.hpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8279a3b513d5fdf1b7eaf65d0eb083d569440de2 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Map.hpp @@ -0,0 +1,18 @@ +#ifndef Map_hpp +#define Map_hpp + +#include +#include + +class Map { + +public: + Map(std::vector snes_vram) : vram(snes_vram) {}; + + std::vector ics_map(); + +private: + std::vector vram; +}; + +#endif /* Map_hpp */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b562d6524cedf5b762f493203134c42004f4c12a --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.cpp @@ -0,0 +1,51 @@ +#include "Palette.hpp" + +#include + +Palette::Palette() {} + +Palette::Palette(std::vector rgba32_palette) { + this->rgba32_palette = rgba32_palette; +} + +Palette::Palette(const std::vector &rgba24_palette) { + auto palette_size = rgba24_palette.size(); + if (palette_size % 3) { + std::cerr << "Warning: expected palette to byte 3 bytes per color" << std::endl; + palette_size -= palette_size % 3; + } + + // (eventually 256 color support needed) + const auto palette_size_4bpp = 16; + const auto rgb24_size = 3; + + for (auto i = 0; i < palette_size_4bpp; i++) { + size_t index = i * rgb24_size; + uint8_t r = rgba24_palette[index]; + uint8_t g = rgba24_palette[index + 1]; + uint8_t b = rgba24_palette[index + 2]; + uint32_t color = 0xff << 24 | r | g << 8 | b << 16; + + rgba32_palette.push_back(color); + } +} + +std::vector Palette::ics_palette() const { + std::vector ics_palette; + + auto round = [] (uint8_t component) { + return (component - 8) / 0x10; + }; + + for (auto color : this->rgba32_palette) { + uint8_t a = round(color >> 24 & 0xff); + uint8_t b = round(color >> 16 & 0xff); + uint8_t g = round(color >> 8 & 0xff); + uint8_t r = round(color & 0xff); + + uint16_t ics_color = a << 12 | r << 8 | g << 4 | b; + ics_palette.push_back(ics_color); + } + + return ics_palette; +} diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.hpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2e9bb7c77f29fcc2e9936eca3862b6863bbda57d --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Palette.hpp @@ -0,0 +1,19 @@ +#ifndef Palette_hpp +#define Palette_hpp + +#include +#include + +class Palette { + +public: + Palette(); + Palette(std::vector rgba32_palette); + Palette(const std::vector &rgba24_palette); + + std::vector rgba32_palette; + + std::vector ics_palette() const; +}; + +#endif /* Palette_hpp */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d2876d6453d6dfa7a8aa40a06be9ce0f726fbaa --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.cpp @@ -0,0 +1,129 @@ +#include "Tiles.hpp" +#include "ImageMetrics.h" + +#include + +Tiles::Tiles() : width(0), height(0) {} + +Tiles::Tiles(std::vector bitmap, uint16_t width, uint16_t height) { + this->bitmap = bitmap; + this->width = width; + this->height = height; +} + +// 4bpp conversion +std::vector Tiles::ics_tiles() const { + std::vector tiles; + + const uint8_t tiles_x_total = this->width / 8; + const uint8_t tiles_y_total = this->height / 8; + + // convert from the bitmap format to the 8x8 4bpp format + for (uint8_t tile_y = 0; tile_y < tiles_y_total; tile_y++) { + for (uint8_t tile_x = 0; tile_x < tiles_x_total; tile_x++) { + // 8x8 conversion + for (uint8_t pixel_y = 0; pixel_y < 8; pixel_y++) { + // write adjacent pixels at a time + uint8_t high_pixel = 0; + uint32_t pixel_row = 0; + + for (uint8_t pixel_x = 0; pixel_x < 8; pixel_x++) { + uint16_t x = tile_x * 8 + pixel_x; + uint16_t y = tile_y * 8 + pixel_y; + uint16_t base_index = y * width + x; + + uint8_t pixel = bitmap[base_index]; + if (pixel > 0x0f) { + std::cerr << "Pixel out of range for 4bpp conversion: " << std::hex << pixel << std::endl; + pixel = 0; + } + + if (pixel_x % 2) { + pixel_row <<= 8; + pixel_row |= (pixel | high_pixel << 4); + } else { + high_pixel = pixel; + } + } + + tiles.push_back(pixel_row); + } + } + } + + return tiles; +} + +// packed 4bpp conversion + +std::vector Tiles::packed_4bpp_tiles() const { + std::vector tiles; + uint8_t high_pixel = 0; + + for (auto i = 0; i < this->bitmap.size(); i++) { + uint8_t pixel = this->bitmap[i]; + + if (i % 2) { + tiles.push_back(pixel | high_pixel << 4); + } else { + high_pixel = pixel; + } + } + + return tiles; +} + +// SNES format + +Tiles::Tiles(std::vector snes_tiles) { + std::vector bitmap; + bitmap.resize(snes_tiles.size() * 2); + + const auto tile_size = ImageMetrics::SNES::TILE_SIZE; + + auto size = snes_tiles.size(); + if (size % tile_size) { + std::cerr << "Warning: expected size of SNES tiles to be a multiple of 32" << std::endl; + size &= ~(tile_size - 1); + } + + const auto tile_count = size / tile_size; + + for (auto tile = 0; tile < tile_count; tile++) { + for (auto row = 0; row < 8; row++) { + auto read_index = tile * tile_size + row * 2; + + auto bp0 = snes_tiles[read_index]; + auto bp1 = snes_tiles[read_index + 1]; + auto bp2 = snes_tiles[read_index + 16]; + auto bp3 = snes_tiles[read_index + 17]; + + for (auto pixel = 0; pixel < 8; pixel++) { + uint8_t converted_pixel = 0; + + converted_pixel |= (bp3 & 0x80) >> 4; + converted_pixel |= (bp2 & 0x80) >> 5; + converted_pixel |= (bp1 & 0x80) >> 6; + converted_pixel |= (bp0 & 0x80) >> 7; + + auto x = tile % 16 * 8 + pixel; + auto y = tile / 16 * 8 + row; + auto write_index = y * 128 + x; + + bitmap[write_index] = converted_pixel; + + bp3 <<= 1; + bp2 <<= 1; + bp1 <<= 1; + bp0 <<= 1; + } + } + } + + this->bitmap = bitmap; + this->width = ImageMetrics::SNES::TILE_ROW_STRIDE; + this->height = bitmap.size() / this->width; +} + + +// TODO: 256 color (for affine layer) diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.hpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fbf2f0f6ce1794eebd869077821d88b5623b1ddd --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/intermediate/Tiles.hpp @@ -0,0 +1,24 @@ +#ifndef Tiles_hpp +#define Tiles_hpp + +#include +#include + +#include "lodepng.h" + +class Tiles { + +public: + Tiles(); + Tiles(std::vector bitmap_image, uint16_t width, uint16_t height); + Tiles(std::vector snes_tiles); + + uint16_t width; + uint16_t height; + std::vector bitmap; + + std::vector ics_tiles() const; + std::vector packed_4bpp_tiles() const; +}; + +#endif /* Tiles_hpp */ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1130afe5e2018c77e44b1b39c1df1acf2e49239c --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.cpp @@ -0,0 +1,6406 @@ +/* +LodePNG version 20200306 + +Copyright (c) 2005-2020 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +/* +The manual and changelog are in the header file "lodepng.h" +Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C. +*/ + +#include "lodepng.h" + +#ifdef LODEPNG_COMPILE_DISK +#include /* LONG_MAX */ +#include /* file handling */ +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +#include /* allocations */ +#endif /* LODEPNG_COMPILE_ALLOCATORS */ + +#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ +#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ +#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ +#endif /*_MSC_VER */ + +const char* LODEPNG_VERSION_STRING = "20200306"; + +/* +This source file is built up in the following large parts. The code sections +with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. +-Tools for C and common code for PNG and Zlib +-C Code for Zlib (huffman, deflate, ...) +-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) +-The C++ wrapper around all of the above +*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // Tools for C, and common code for PNG and Zlib. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*The malloc, realloc and free functions defined here with "lodepng_" in front +of the name, so that you can easily change them to others related to your +platform if needed. Everything else in the code calls these. Pass +-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out +#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and +define them in your own project's source files without needing to change +lodepng source code. Don't forget to remove "static" if you copypaste them +from here.*/ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +static void* lodepng_malloc(size_t size) { +#ifdef LODEPNG_MAX_ALLOC + if(size > LODEPNG_MAX_ALLOC) return 0; +#endif + return malloc(size); +} + +/* NOTE: when realloc returns NULL, it leaves the original memory untouched */ +static void* lodepng_realloc(void* ptr, size_t new_size) { +#ifdef LODEPNG_MAX_ALLOC + if(new_size > LODEPNG_MAX_ALLOC) return 0; +#endif + return realloc(ptr, new_size); +} + +static void lodepng_free(void* ptr) { + free(ptr); +} +#else /*LODEPNG_COMPILE_ALLOCATORS*/ +/* TODO: support giving additional void* payload to the custom allocators */ +void* lodepng_malloc(size_t size); +void* lodepng_realloc(void* ptr, size_t new_size); +void lodepng_free(void* ptr); +#endif /*LODEPNG_COMPILE_ALLOCATORS*/ + +/* convince the compiler to inline a function, for use when this measurably improves performance */ +/* inline is not available in C90, but use it when supported by the compiler */ +#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L)) +#define LODEPNG_INLINE inline +#else +#define LODEPNG_INLINE /* not available */ +#endif + +/* restrict is not available in C90, but use it when supported by the compiler */ +#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\ + (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \ + (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus)) +#define LODEPNG_RESTRICT __restrict +#else +#define LODEPNG_RESTRICT /* not available */ +#endif + +/* Replacements for C library functions such as memcpy and strlen, to support platforms +where a full C library is not available. The compiler can recognize them and compile +to something as fast. */ + +static void lodepng_memcpy(void* LODEPNG_RESTRICT dst, + const void* LODEPNG_RESTRICT src, size_t size) { + size_t i; + for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i]; +} + +static void lodepng_memset(void* LODEPNG_RESTRICT dst, + int value, size_t num) { + size_t i; + for(i = 0; i < num; i++) ((char*)dst)[i] = (char)value; +} + +/* does not check memory out of bounds, do not use on untrusted data */ +static size_t lodepng_strlen(const char* a) { + const char* orig = a; + /* avoid warning about unused function in case of disabled COMPILE... macros */ + (void)(&lodepng_strlen); + while(*a) a++; + return (size_t)(a - orig); +} + +#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define LODEPNG_ABS(x) ((x) < 0 ? -(x) : (x)) + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER) +/* Safely check if adding two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_addofl(size_t a, size_t b, size_t* result) { + *result = a + b; /* Unsigned addition is well defined and safe in C90 */ + return *result < a; +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/ + +#ifdef LODEPNG_COMPILE_DECODER +/* Safely check if multiplying two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_mulofl(size_t a, size_t b, size_t* result) { + *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ + return (a != 0 && *result / a != b); +} + +#ifdef LODEPNG_COMPILE_ZLIB +/* Safely check if a + b > c, even if overflow could happen. */ +static int lodepng_gtofl(size_t a, size_t b, size_t c) { + size_t d; + if(lodepng_addofl(a, b, &d)) return 1; + return d > c; +} +#endif /*LODEPNG_COMPILE_ZLIB*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +/* +Often in case of an error a value is assigned to a variable and then it breaks +out of a loop (to go to the cleanup phase of a function). This macro does that. +It makes the error handling code shorter and more readable. + +Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83); +*/ +#define CERROR_BREAK(errorvar, code){\ + errorvar = code;\ + break;\ +} + +/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ +#define ERROR_BREAK(code) CERROR_BREAK(error, code) + +/*Set error var to the error code, and return it.*/ +#define CERROR_RETURN_ERROR(errorvar, code){\ + errorvar = code;\ + return code;\ +} + +/*Try the code, if it returns error, also return the error.*/ +#define CERROR_TRY_RETURN(call){\ + unsigned error = call;\ + if(error) return error;\ +} + +/*Set error var to the error code, and return from the void function.*/ +#define CERROR_RETURN(errorvar, code){\ + errorvar = code;\ + return;\ +} + +/* +About uivector, ucvector and string: +-All of them wrap dynamic arrays or text strings in a similar way. +-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. +-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. +-They're not used in the interface, only internally in this file as static functions. +-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. +*/ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER +/*dynamic vector of unsigned ints*/ +typedef struct uivector { + unsigned* data; + size_t size; /*size in number of unsigned longs*/ + size_t allocsize; /*allocated size in bytes*/ +} uivector; + +static void uivector_cleanup(void* p) { + ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; + lodepng_free(((uivector*)p)->data); + ((uivector*)p)->data = NULL; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_resize(uivector* p, size_t size) { + size_t allocsize = size * sizeof(unsigned); + if(allocsize > p->allocsize) { + size_t newsize = allocsize + (p->allocsize >> 1u); + void* data = lodepng_realloc(p->data, newsize); + if(data) { + p->allocsize = newsize; + p->data = (unsigned*)data; + } + else return 0; /*error: not enough memory*/ + } + p->size = size; + return 1; /*success*/ +} + +static void uivector_init(uivector* p) { + p->data = NULL; + p->size = p->allocsize = 0; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_push_back(uivector* p, unsigned c) { + if(!uivector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* /////////////////////////////////////////////////////////////////////////// */ + +/*dynamic vector of unsigned chars*/ +typedef struct ucvector { + unsigned char* data; + size_t size; /*used size*/ + size_t allocsize; /*allocated size*/ +} ucvector; + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_resize(ucvector* p, size_t size) { + if(size > p->allocsize) { + size_t newsize = size + (p->allocsize >> 1u); + void* data = lodepng_realloc(p->data, newsize); + if(data) { + p->allocsize = newsize; + p->data = (unsigned char*)data; + } + else return 0; /*error: not enough memory*/ + } + p->size = size; + return 1; /*success*/ +} + +static ucvector ucvector_init(unsigned char* buffer, size_t size) { + ucvector v; + v.data = buffer; + v.allocsize = v.size = size; + return v; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +/*free string pointer and set it to NULL*/ +static void string_cleanup(char** out) { + lodepng_free(*out); + *out = NULL; +} + +static char* alloc_string_sized(const char* in, size_t insize) { + char* out = (char*)lodepng_malloc(insize + 1); + if(out) { + lodepng_memcpy(out, in, insize); + out[insize] = 0; + } + return out; +} + +/* dynamically allocates a new string with a copy of the null terminated input text */ +static char* alloc_string(const char* in) { + return alloc_string_sized(in, lodepng_strlen(in)); +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG) +static unsigned lodepng_read32bitInt(const unsigned char* buffer) { + return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) | + ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]); +} +#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/ + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) +/*buffer must have at least 4 allocated bytes available*/ +static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) { + buffer[0] = (unsigned char)((value >> 24) & 0xff); + buffer[1] = (unsigned char)((value >> 16) & 0xff); + buffer[2] = (unsigned char)((value >> 8) & 0xff); + buffer[3] = (unsigned char)((value ) & 0xff); +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / File IO / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DISK + +/* returns negative value on error. This should be pure C compatible, so no fstat. */ +static long lodepng_filesize(const char* filename) { + FILE* file; + long size; + file = fopen(filename, "rb"); + if(!file) return -1; + + if(fseek(file, 0, SEEK_END) != 0) { + fclose(file); + return -1; + } + + size = ftell(file); + /* It may give LONG_MAX as directory size, this is invalid for us. */ + if(size == LONG_MAX) size = -1; + + fclose(file); + return size; +} + +/* load file into buffer that already has the correct allocated size. Returns error code.*/ +static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) { + FILE* file; + size_t readsize; + file = fopen(filename, "rb"); + if(!file) return 78; + + readsize = fread(out, 1, size, file); + fclose(file); + + if(readsize != size) return 78; + return 0; +} + +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { + long size = lodepng_filesize(filename); + if(size < 0) return 78; + *outsize = (size_t)size; + + *out = (unsigned char*)lodepng_malloc((size_t)size); + if(!(*out) && size > 0) return 83; /*the above malloc failed*/ + + return lodepng_buffer_file(*out, (size_t)size, filename); +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { + FILE* file; + file = fopen(filename, "wb" ); + if(!file) return 79; + fwrite(buffer, 1, buffersize, file); + fclose(file); + return 0; +} + +#endif /*LODEPNG_COMPILE_DISK*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of common code and tools. Begin of Zlib related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER + +typedef struct { + ucvector* data; + unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/ +} LodePNGBitWriter; + +static void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) { + writer->data = data; + writer->bp = 0; +} + +/*TODO: this ignores potential out of memory errors*/ +#define WRITEBIT(writer, bit){\ + /* append new byte */\ + if(((writer->bp) & 7u) == 0) {\ + if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\ + writer->data->data[writer->data->size - 1] = 0;\ + }\ + (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\ + ++writer->bp;\ +} + +/* LSB of value is written first, and LSB of bytes is used first */ +static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) { + if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */ + WRITEBIT(writer, value); + } else { + /* TODO: increase output size only once here rather than in each WRITEBIT */ + size_t i; + for(i = 0; i != nbits; ++i) { + WRITEBIT(writer, (unsigned char)((value >> i) & 1)); + } + } +} + +/* This one is to use for adding huffman symbol, the value bits are written MSB first */ +static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) { + size_t i; + for(i = 0; i != nbits; ++i) { + /* TODO: increase output size only once here rather than in each WRITEBIT */ + WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u)); + } +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +typedef struct { + const unsigned char* data; + size_t size; /*size of data in bytes*/ + size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/ + size_t bp; + unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/ +} LodePNGBitReader; + +/* data size argument is in bytes. Returns error if size too large causing overflow */ +static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) { + size_t temp; + reader->data = data; + reader->size = size; + /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */ + if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105; + /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and + trying to ensure 32 more bits*/ + if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105; + reader->bp = 0; + reader->buffer = 0; + return 0; /*ok*/ +} + +/* +ensureBits functions: +Ensures the reader can at least read nbits bits in one or more readBits calls, +safely even if not enough bits are available. +Returns 1 if there are enough bits available, 0 if not. +*/ + +/*See ensureBits documentation above. This one ensures exactly 1 bit */ +/*static unsigned ensureBits1(LodePNGBitReader* reader) { + if(reader->bp >= reader->bitsize) return 0; + reader->buffer = (unsigned)reader->data[reader->bp >> 3u] >> (reader->bp & 7u); + return 1; +}*/ + +/*See ensureBits documentation above. This one ensures up to 9 bits */ +static unsigned ensureBits9(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 1u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u); + reader->buffer >>= (reader->bp & 7u); + return 1; + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + reader->buffer >>= (reader->bp & 7u); + return reader->bp + nbits <= reader->bitsize; + } +} + +/*See ensureBits documentation above. This one ensures up to 17 bits */ +static unsigned ensureBits17(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 2u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u); + reader->buffer >>= (reader->bp & 7u); + return 1; + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + reader->buffer >>= (reader->bp & 7u); + return reader->bp + nbits <= reader->bitsize; + } +} + +/*See ensureBits documentation above. This one ensures up to 25 bits */ +static LODEPNG_INLINE unsigned ensureBits25(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 3u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + return 1; + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); + reader->buffer >>= (reader->bp & 7u); + return reader->bp + nbits <= reader->bitsize; + } +} + +/*See ensureBits documentation above. This one ensures up to 32 bits */ +static LODEPNG_INLINE unsigned ensureBits32(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 4u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u))); + return 1; + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); + if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + return reader->bp + nbits <= reader->bitsize; + } +} + +/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */ +static unsigned peekBits(LodePNGBitReader* reader, size_t nbits) { + /* The shift allows nbits to be only up to 31. */ + return reader->buffer & ((1u << nbits) - 1u); +} + +/* Must have enough bits available with ensureBits */ +static void advanceBits(LodePNGBitReader* reader, size_t nbits) { + reader->buffer >>= nbits; + reader->bp += nbits; +} + +/* Must have enough bits available with ensureBits */ +static unsigned readBits(LodePNGBitReader* reader, size_t nbits) { + unsigned result = peekBits(reader, nbits); + advanceBits(reader, nbits); + return result; +} + +/* Public for testing only. steps and result must have numsteps values. */ +unsigned lode_png_test_bitreader(const unsigned char* data, size_t size, + size_t numsteps, const size_t* steps, unsigned* result) { + size_t i; + LodePNGBitReader reader; + unsigned error = LodePNGBitReader_init(&reader, data, size); + if(error) return 0; + for(i = 0; i < numsteps; i++) { + size_t step = steps[i]; + unsigned ok; + if(step > 25) ok = ensureBits32(&reader, step); + else if(step > 17) ok = ensureBits25(&reader, step); + else if(step > 9) ok = ensureBits17(&reader, step); + else ok = ensureBits9(&reader, step); + if(!ok) return 0; + result[i] = readBits(&reader, step); + } + return 1; +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +static unsigned reverseBits(unsigned bits, unsigned num) { + /*TODO: implement faster lookup table based version when needed*/ + unsigned i, result = 0; + for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i; + return result; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflate - Huffman / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#define FIRST_LENGTH_CODE_INDEX 257 +#define LAST_LENGTH_CODE_INDEX 285 +/*256 literals, the end code, some length codes, and 2 unused codes*/ +#define NUM_DEFLATE_CODE_SYMBOLS 288 +/*the distance codes have their own symbols, 30 used, 2 unused*/ +#define NUM_DISTANCE_SYMBOLS 32 +/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ +#define NUM_CODE_LENGTH_CODES 19 + +/*the base lengths represented by codes 257-285*/ +static const unsigned LENGTHBASE[29] + = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, + 67, 83, 99, 115, 131, 163, 195, 227, 258}; + +/*the extra bits used by codes 257-285 (added to base length)*/ +static const unsigned LENGTHEXTRA[29] + = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 0}; + +/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ +static const unsigned DISTANCEBASE[30] + = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, + 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + +/*the extra bits of backwards distances (added to base)*/ +static const unsigned DISTANCEEXTRA[30] + = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + +/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman +tree of the dynamic huffman tree lengths is generated*/ +static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] + = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Huffman tree struct, containing multiple representations of the tree +*/ +typedef struct HuffmanTree { + unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/ + unsigned* lengths; /*the lengths of the huffman codes*/ + unsigned maxbitlen; /*maximum number of bits a single code can get*/ + unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ + /* for reading only */ + unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/ + unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/ +} HuffmanTree; + +static void HuffmanTree_init(HuffmanTree* tree) { + tree->codes = 0; + tree->lengths = 0; + tree->table_len = 0; + tree->table_value = 0; +} + +static void HuffmanTree_cleanup(HuffmanTree* tree) { + lodepng_free(tree->codes); + lodepng_free(tree->lengths); + lodepng_free(tree->table_len); + lodepng_free(tree->table_value); +} + +/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/ +/* values 8u and 9u work the fastest */ +#define FIRSTBITS 9u + +/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination, +which is possible in case of only 0 or 1 present symbols. */ +#define INVALIDSYMBOL 65535u + +/* make table for huffman decoding */ +static unsigned HuffmanTree_makeTable(HuffmanTree* tree) { + static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/ + static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u; + size_t i, numpresent, pointer, size; /*total table size*/ + unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned)); + if(!maxlens) return 83; /*alloc fail*/ + + /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/ + lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens)); + for(i = 0; i < tree->numcodes; i++) { + unsigned symbol = tree->codes[i]; + unsigned l = tree->lengths[i]; + unsigned index; + if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/ + /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/ + index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS); + maxlens[index] = LODEPNG_MAX(maxlens[index], l); + } + /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */ + size = headsize; + for(i = 0; i < headsize; ++i) { + unsigned l = maxlens[i]; + if(l > FIRSTBITS) size += (1u << (l - FIRSTBITS)); + } + tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len)); + tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value)); + if(!tree->table_len || !tree->table_value) { + lodepng_free(maxlens); + /* freeing tree->table values is done at a higher scope */ + return 83; /*alloc fail*/ + } + /*initialize with an invalid length to indicate unused entries*/ + for(i = 0; i < size; ++i) tree->table_len[i] = 16; + + /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/ + pointer = headsize; + for(i = 0; i < headsize; ++i) { + unsigned l = maxlens[i]; + if(l <= FIRSTBITS) continue; + tree->table_len[i] = l; + tree->table_value[i] = pointer; + pointer += (1u << (l - FIRSTBITS)); + } + lodepng_free(maxlens); + + /*fill in the first table for short symbols, or secondary table for long symbols*/ + numpresent = 0; + for(i = 0; i < tree->numcodes; ++i) { + unsigned l = tree->lengths[i]; + unsigned symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/ + /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/ + unsigned reverse = reverseBits(symbol, l); + if(l == 0) continue; + numpresent++; + + if(l <= FIRSTBITS) { + /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/ + unsigned num = 1u << (FIRSTBITS - l); + unsigned j; + for(j = 0; j < num; ++j) { + /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/ + unsigned index = reverse | (j << l); + if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ + tree->table_len[index] = l; + tree->table_value[index] = i; + } + } else { + /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/ + /*the FIRSTBITS MSBs of the symbol are the first table index*/ + unsigned index = reverse & mask; + unsigned maxlen = tree->table_len[index]; + /*log2 of secondary table length, should be >= l - FIRSTBITS*/ + unsigned tablelen = maxlen - FIRSTBITS; + unsigned start = tree->table_value[index]; /*starting index in secondary table*/ + unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/ + unsigned j; + if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ + for(j = 0; j < num; ++j) { + unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */ + unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS))); + tree->table_len[index2] = l; + tree->table_value[index2] = i; + } + } + } + + if(numpresent < 2) { + /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits, + but deflate uses 1 bit instead. In case of 0 symbols, no symbols can + appear at all, but such huffman tree could still exist (e.g. if distance + codes are never used). In both cases, not all symbols of the table will be + filled in. Fill them in with an invalid symbol value so returning them from + huffmanDecodeSymbol will cause error. */ + for(i = 0; i < size; ++i) { + if(tree->table_len[i] == 16) { + /* As length, use a value smaller than FIRSTBITS for the head table, + and a value larger than FIRSTBITS for the secondary table, to ensure + valid behavior for advanceBits when reading this symbol. */ + tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1); + tree->table_value[i] = INVALIDSYMBOL; + } + } + } else { + /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. + If that is not the case (due to too long length codes), the table will not + have been fully used, and this is an error (not all bit combinations can be + decoded): an oversubscribed huffman tree, indicated by error 55. */ + for(i = 0; i < size; ++i) { + if(tree->table_len[i] == 16) return 55; + } + } + + return 0; +} + +/* +Second step for the ...makeFromLengths and ...makeFromFrequencies functions. +numcodes, lengths and maxbitlen must already be filled in correctly. return +value is error. +*/ +static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { + unsigned* blcount; + unsigned* nextcode; + unsigned error = 0; + unsigned bits, n; + + tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); + blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); + nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); + if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/ + + if(!error) { + for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0; + /*step 1: count number of instances of each code length*/ + for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]]; + /*step 2: generate the nextcode values*/ + for(bits = 1; bits <= tree->maxbitlen; ++bits) { + nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u; + } + /*step 3: generate all the codes*/ + for(n = 0; n != tree->numcodes; ++n) { + if(tree->lengths[n] != 0) { + tree->codes[n] = nextcode[tree->lengths[n]]++; + /*remove superfluous bits from the code*/ + tree->codes[n] &= ((1u << tree->lengths[n]) - 1u); + } + } + } + + lodepng_free(blcount); + lodepng_free(nextcode); + + if(!error) error = HuffmanTree_makeTable(tree); + return error; +} + +/* +given the code lengths (as stored in the PNG file), generate the tree as defined +by Deflate. maxbitlen is the maximum bits that a code in the tree can have. +return value is error. +*/ +static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, + size_t numcodes, unsigned maxbitlen) { + unsigned i; + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->maxbitlen = maxbitlen; + return HuffmanTree_makeFromLengths2(tree); +} + +#ifdef LODEPNG_COMPILE_ENCODER + +/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding", +Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ + +/*chain node for boundary package merge*/ +typedef struct BPMNode { + int weight; /*the sum of all weights in this chain*/ + unsigned index; /*index of this leaf node (called "count" in the paper)*/ + struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ + int in_use; +} BPMNode; + +/*lists of chains*/ +typedef struct BPMLists { + /*memory pool*/ + unsigned memsize; + BPMNode* memory; + unsigned numfree; + unsigned nextfree; + BPMNode** freelist; + /*two heads of lookahead chains per list*/ + unsigned listsize; + BPMNode** chains0; + BPMNode** chains1; +} BPMLists; + +/*creates a new chain node with the given parameters, from the memory in the lists */ +static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) { + unsigned i; + BPMNode* result; + + /*memory full, so garbage collect*/ + if(lists->nextfree >= lists->numfree) { + /*mark only those that are in use*/ + for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; + for(i = 0; i != lists->listsize; ++i) { + BPMNode* node; + for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; + for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; + } + /*collect those that are free*/ + lists->numfree = 0; + for(i = 0; i != lists->memsize; ++i) { + if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; + } + lists->nextfree = 0; + } + + result = lists->freelist[lists->nextfree++]; + result->weight = weight; + result->index = index; + result->tail = tail; + return result; +} + +/*sort the leaves with stable mergesort*/ +static void bpmnode_sort(BPMNode* leaves, size_t num) { + BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); + size_t width, counter = 0; + for(width = 1; width < num; width *= 2) { + BPMNode* a = (counter & 1) ? mem : leaves; + BPMNode* b = (counter & 1) ? leaves : mem; + size_t p; + for(p = 0; p < num; p += 2 * width) { + size_t q = (p + width > num) ? num : (p + width); + size_t r = (p + 2 * width > num) ? num : (p + 2 * width); + size_t i = p, j = q, k; + for(k = p; k < r; k++) { + if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; + else b[k] = a[j++]; + } + } + counter++; + } + if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num); + lodepng_free(mem); +} + +/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ +static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) { + unsigned lastindex = lists->chains1[c]->index; + + if(c == 0) { + if(lastindex >= numpresent) return; + lists->chains0[c] = lists->chains1[c]; + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); + } else { + /*sum of the weights of the head nodes of the previous lookahead chains.*/ + int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; + lists->chains0[c] = lists->chains1[c]; + if(lastindex < numpresent && sum > leaves[lastindex].weight) { + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); + return; + } + lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); + /*in the end we are only interested in the chain of the last list, so no + need to recurse if we're at the last one (this gives measurable speedup)*/ + if(num + 1 < (int)(2 * numpresent - 2)) { + boundaryPM(lists, leaves, numpresent, c - 1, num); + boundaryPM(lists, leaves, numpresent, c - 1, num); + } + } +} + +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen) { + unsigned error = 0; + unsigned i; + size_t numpresent = 0; /*number of symbols with non-zero frequency*/ + BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ + + if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ + if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/ + + leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); + if(!leaves) return 83; /*alloc fail*/ + + for(i = 0; i != numcodes; ++i) { + if(frequencies[i] > 0) { + leaves[numpresent].weight = (int)frequencies[i]; + leaves[numpresent].index = i; + ++numpresent; + } + } + + lodepng_memset(lengths, 0, numcodes * sizeof(*lengths)); + + /*ensure at least two present symbols. There should be at least one symbol + according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To + make these work as well ensure there are at least two symbols. The + Package-Merge code below also doesn't work correctly if there's only one + symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/ + if(numpresent == 0) { + lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ + } else if(numpresent == 1) { + lengths[leaves[0].index] = 1; + lengths[leaves[0].index == 0 ? 1 : 0] = 1; + } else { + BPMLists lists; + BPMNode* node; + + bpmnode_sort(leaves, numpresent); + + lists.listsize = maxbitlen; + lists.memsize = 2 * maxbitlen * (maxbitlen + 1); + lists.nextfree = 0; + lists.numfree = lists.memsize; + lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); + lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); + lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ + + if(!error) { + for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; + + bpmnode_create(&lists, leaves[0].weight, 1, 0); + bpmnode_create(&lists, leaves[1].weight, 2, 0); + + for(i = 0; i != lists.listsize; ++i) { + lists.chains0[i] = &lists.memory[0]; + lists.chains1[i] = &lists.memory[1]; + } + + /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ + for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); + + for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) { + for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; + } + } + + lodepng_free(lists.memory); + lodepng_free(lists.freelist); + lodepng_free(lists.chains0); + lodepng_free(lists.chains1); + } + + lodepng_free(leaves); + return error; +} + +/*Create the Huffman tree given the symbol frequencies*/ +static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, + size_t mincodes, size_t numcodes, unsigned maxbitlen) { + unsigned error = 0; + while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + tree->maxbitlen = maxbitlen; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + + error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); + if(!error) error = HuffmanTree_makeFromLengths2(tree); + return error; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ +static unsigned generateFixedLitLenTree(HuffmanTree* tree) { + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ + for(i = 0; i <= 143; ++i) bitlen[i] = 8; + for(i = 144; i <= 255; ++i) bitlen[i] = 9; + for(i = 256; i <= 279; ++i) bitlen[i] = 7; + for(i = 280; i <= 287; ++i) bitlen[i] = 8; + + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static unsigned generateFixedDistanceTree(HuffmanTree* tree) { + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*there are 32 distance codes, but 30-31 are unused*/ + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* +returns the code. The bit reader must already have been ensured at least 15 bits +*/ +static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) { + unsigned short code = peekBits(reader, FIRSTBITS); + unsigned short l = codetree->table_len[code]; + unsigned short value = codetree->table_value[code]; + if(l <= FIRSTBITS) { + advanceBits(reader, l); + return value; + } else { + unsigned index2; + advanceBits(reader, FIRSTBITS); + index2 = value + peekBits(reader, l - FIRSTBITS); + advanceBits(reader, codetree->table_len[index2] - FIRSTBITS); + return codetree->table_value[index2]; + } +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Inflator (Decompressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*get the tree of a deflated block with fixed tree, as specified in the deflate specification +Returns error code.*/ +static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { + unsigned error = generateFixedLitLenTree(tree_ll); + if(error) return error; + return generateFixedDistanceTree(tree_d); +} + +/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ +static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, + LodePNGBitReader* reader) { + /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ + unsigned error = 0; + unsigned n, HLIT, HDIST, HCLEN, i; + + /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ + unsigned* bitlen_ll = 0; /*lit,len code lengths*/ + unsigned* bitlen_d = 0; /*dist code lengths*/ + /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ + unsigned* bitlen_cl = 0; + HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ + + if(!ensureBits17(reader, 14)) return 49; /*error: the bit pointer is or will go past the memory*/ + + /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ + HLIT = readBits(reader, 5) + 257; + /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ + HDIST = readBits(reader, 5) + 1; + /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ + HCLEN = readBits(reader, 4) + 4; + + bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); + if(!bitlen_cl) return 83 /*alloc fail*/; + + HuffmanTree_init(&tree_cl); + + while(!error) { + /*read the code length codes out of 3 * (amount of code length codes) bits*/ + if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) { + ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/ + } + for(i = 0; i != HCLEN; ++i) { + ensureBits9(reader, 3); /*out of bounds already checked above */ + bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3); + } + for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) { + bitlen_cl[CLCL_ORDER[i]] = 0; + } + + error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*now we can use this tree to read the lengths for the tree that this function will return*/ + bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); + lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll)); + lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d)); + + /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ + i = 0; + while(i < HLIT + HDIST) { + unsigned code; + ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/ + code = huffmanDecodeSymbol(reader, &tree_cl); + if(code <= 15) /*a length code*/ { + if(i < HLIT) bitlen_ll[i] = code; + else bitlen_d[i - HLIT] = code; + ++i; + } else if(code == 16) /*repeat previous*/ { + unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ + unsigned value; /*set value to the previous code*/ + + if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ + + replength += readBits(reader, 2); + + if(i < HLIT + 1) value = bitlen_ll[i - 1]; + else value = bitlen_d[i - HLIT - 1]; + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ + if(i < HLIT) bitlen_ll[i] = value; + else bitlen_d[i - HLIT] = value; + ++i; + } + } else if(code == 17) /*repeat "0" 3-10 times*/ { + unsigned replength = 3; /*read in the bits that indicate repeat length*/ + replength += readBits(reader, 3); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } else if(code == 18) /*repeat "0" 11-138 times*/ { + unsigned replength = 11; /*read in the bits that indicate repeat length*/ + replength += readBits(reader, 7); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } else /*if(code == INVALIDSYMBOL)*/ { + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + /*check if any of the ensureBits above went out of bounds*/ + if(reader->bp > reader->bitsize) { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ + ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + } + } + if(error) break; + + if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ + + /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ + error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); + if(error) break; + error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); + + break; /*end of error-while*/ + } + + lodepng_free(bitlen_cl); + lodepng_free(bitlen_ll); + lodepng_free(bitlen_d); + HuffmanTree_cleanup(&tree_cl); + + return error; +} + +/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/ +static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader, + unsigned btype) { + unsigned error = 0; + HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ + HuffmanTree tree_d; /*the huffman tree for distance codes*/ + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d); + else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader); + + while(!error) /*decode all symbols until end reached, breaks at end code*/ { + /*code_ll is literal, length or end code*/ + unsigned code_ll; + ensureBits25(reader, 20); /* up to 15 for the huffman symbol, up to 5 for the length extra bits */ + code_ll = huffmanDecodeSymbol(reader, &tree_ll); + if(code_ll <= 255) /*literal symbol*/ { + if(!ucvector_resize(out, out->size + 1)) ERROR_BREAK(83 /*alloc fail*/); + out->data[out->size - 1] = (unsigned char)code_ll; + } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ { + unsigned code_d, distance; + unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ + size_t start, backward, length; + + /*part 1: get length base*/ + length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; + + /*part 2: get extra bits and add the value of that to length*/ + numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; + if(numextrabits_l != 0) { + /* bits already ensured above */ + length += readBits(reader, numextrabits_l); + } + + /*part 3: get distance code*/ + ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */ + code_d = huffmanDecodeSymbol(reader, &tree_d); + if(code_d > 29) { + if(code_d <= 31) { + ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/ + } else /* if(code_d == INVALIDSYMBOL) */{ + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + } + distance = DISTANCEBASE[code_d]; + + /*part 4: get extra bits from distance*/ + numextrabits_d = DISTANCEEXTRA[code_d]; + if(numextrabits_d != 0) { + /* bits already ensured above */ + distance += readBits(reader, numextrabits_d); + } + + /*part 5: fill in all the out[n] values based on the length and dist*/ + start = out->size; + if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ + backward = start - distance; + + if(!ucvector_resize(out, out->size + length)) ERROR_BREAK(83 /*alloc fail*/); + if(distance < length) { + size_t forward; + lodepng_memcpy(out->data + start, out->data + backward, distance); + start += distance; + for(forward = distance; forward < length; ++forward) { + out->data[start++] = out->data[backward++]; + } + } else { + lodepng_memcpy(out->data + start, out->data + backward, length); + } + } else if(code_ll == 256) { + break; /*end code, break the loop*/ + } else /*if(code_ll == INVALIDSYMBOL)*/ { + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + /*check if any of the ensureBits above went out of bounds*/ + if(reader->bp > reader->bitsize) { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ + ERROR_BREAK(51); /*error, bit pointer jumps past memory*/ + } + } + + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader, + const LodePNGDecompressSettings* settings) { + size_t bytepos; + size_t size = reader->size; + unsigned LEN, NLEN, error = 0; + + /*go to first boundary of byte*/ + bytepos = (reader->bp + 7u) >> 3u; + + /*read LEN (2 bytes) and NLEN (2 bytes)*/ + if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/ + LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; + NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; + + /*check if 16-bit NLEN is really the one's complement of LEN*/ + if(!settings->ignore_nlen && LEN + NLEN != 65535) { + return 21; /*error: NLEN is not one's complement of LEN*/ + } + + if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/ + + /*read the literal data: LEN bytes are now stored in the out buffer*/ + if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/ + + lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN); + bytepos += LEN; + + reader->bp = bytepos << 3u; + + return error; +} + +static unsigned lodepng_inflatev(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + unsigned BFINAL = 0; + LodePNGBitReader reader; + unsigned error = LodePNGBitReader_init(&reader, in, insize); + + if(error) return error; + + while(!BFINAL) { + unsigned BTYPE; + if(!ensureBits9(&reader, 3)) return 52; /*error, bit pointer will jump past memory*/ + BFINAL = readBits(&reader, 1); + BTYPE = readBits(&reader, 2); + + if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ + else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/ + else error = inflateHuffmanBlock(out, &reader, BTYPE); /*compression, BTYPE 01 or 10*/ + + if(error) return error; + } + + return error; +} + +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_inflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + if(settings->custom_inflate) { + unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings); + out->allocsize = out->size; + return error; + } else { + return lodepng_inflatev(out, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflator (Compressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; + +/*search the index in the array, that has the largest value smaller than or equal to the given value, +given array must be sorted (if no value is smaller, it returns the size of the given array)*/ +static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { + /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ + size_t left = 1; + size_t right = array_size - 1; + + while(left <= right) { + size_t mid = (left + right) >> 1; + if(array[mid] >= value) right = mid - 1; + else left = mid + 1; + } + if(left >= array_size || array[left] > value) left--; + return left; +} + +static void addLengthDistance(uivector* values, size_t length, size_t distance) { + /*values in encoded vector are those used by deflate: + 0-255: literal bytes + 256: end + 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) + 286-287: invalid*/ + + unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); + unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); + unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); + unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); + + size_t pos = values->size; + /*TODO: return error when this fails (out of memory)*/ + unsigned ok = uivector_resize(values, values->size + 4); + if(ok) { + values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX; + values->data[pos + 1] = extra_length; + values->data[pos + 2] = dist_code; + values->data[pos + 3] = extra_distance; + } +} + +/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 +bytes as input because 3 is the minimum match length for deflate*/ +static const unsigned HASH_NUM_VALUES = 65536; +static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ + +typedef struct Hash { + int* head; /*hash value to head circular pos - can be outdated if went around window*/ + /*circular pos to prev circular pos*/ + unsigned short* chain; + int* val; /*circular pos to hash value*/ + + /*TODO: do this not only for zeros but for any repeated byte. However for PNG + it's always going to be the zeros that dominate, so not important for PNG*/ + int* headz; /*similar to head, but for chainz*/ + unsigned short* chainz; /*those with same amount of zeros*/ + unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ +} Hash; + +static unsigned hash_init(Hash* hash, unsigned windowsize) { + unsigned i; + hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); + hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); + hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); + hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) { + return 83; /*alloc fail*/ + } + + /*initialize hash table*/ + for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; + for(i = 0; i != windowsize; ++i) hash->val[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ + + for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ + + return 0; +} + +static void hash_cleanup(Hash* hash) { + lodepng_free(hash->head); + lodepng_free(hash->val); + lodepng_free(hash->chain); + + lodepng_free(hash->zeros); + lodepng_free(hash->headz); + lodepng_free(hash->chainz); +} + + + +static unsigned getHash(const unsigned char* data, size_t size, size_t pos) { + unsigned result = 0; + if(pos + 2 < size) { + /*A simple shift and xor hash is used. Since the data of PNGs is dominated + by zeroes due to the filters, a better hash does not have a significant + effect on speed in traversing the chain, and causes more time spend on + calculating the hash.*/ + result ^= ((unsigned)data[pos + 0] << 0u); + result ^= ((unsigned)data[pos + 1] << 4u); + result ^= ((unsigned)data[pos + 2] << 8u); + } else { + size_t amount, i; + if(pos >= size) return 0; + amount = size - pos; + for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u)); + } + return result & HASH_BIT_MASK; +} + +static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) { + const unsigned char* start = data + pos; + const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; + if(end > data + size) end = data + size; + data = start; + while(data != end && *data == 0) ++data; + /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ + return (unsigned)(data - start); +} + +/*wpos = pos & (windowsize - 1)*/ +static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) { + hash->val[wpos] = (int)hashval; + if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; + hash->head[hashval] = (int)wpos; + + hash->zeros[wpos] = numzeros; + if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; + hash->headz[numzeros] = (int)wpos; +} + +/* +LZ77-encode the data. Return value is error code. The input are raw bytes, the output +is in the form of unsigned integers with codes representing for example literal bytes, or +length/distance pairs. +It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a +sliding window (of windowsize) is used, and all past bytes in that window can be used as +the "dictionary". A brute force search through all possible distances would be slow, and +this hash technique is one out of several ways to speed this up. +*/ +static unsigned encodeLZ77(uivector* out, Hash* hash, + const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, + unsigned minmatch, unsigned nicematch, unsigned lazymatching) { + size_t pos; + unsigned i, error = 0; + /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ + unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u; + unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; + + unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ + unsigned numzeros = 0; + + unsigned offset; /*the offset represents the distance in LZ77 terminology*/ + unsigned length; + unsigned lazy = 0; + unsigned lazylength = 0, lazyoffset = 0; + unsigned hashval; + unsigned current_offset, current_length; + unsigned prev_offset; + const unsigned char *lastptr, *foreptr, *backptr; + unsigned hashpos; + + if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ + if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ + + if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; + + for(pos = inpos; pos < insize; ++pos) { + size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ + unsigned chainlength = 0; + + hashval = getHash(in, insize, pos); + + if(usezeros && hashval == 0) { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } else { + numzeros = 0; + } + + updateHashChain(hash, wpos, hashval, numzeros); + + /*the length and offset found for the current position*/ + length = 0; + offset = 0; + + hashpos = hash->chain[wpos]; + + lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; + + /*search for the longest string*/ + prev_offset = 0; + for(;;) { + if(chainlength++ >= maxchainlength) break; + current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize); + + if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ + prev_offset = current_offset; + if(current_offset > 0) { + /*test the next characters*/ + foreptr = &in[pos]; + backptr = &in[pos - current_offset]; + + /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ + if(numzeros >= 3) { + unsigned skip = hash->zeros[hashpos]; + if(skip > numzeros) skip = numzeros; + backptr += skip; + foreptr += skip; + } + + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ { + ++backptr; + ++foreptr; + } + current_length = (unsigned)(foreptr - &in[pos]); + + if(current_length > length) { + length = current_length; /*the longest length*/ + offset = current_offset; /*the offset that is related to this longest length*/ + /*jump out once a length of max length is found (speed gain). This also jumps + out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ + if(current_length >= nicematch) break; + } + } + + if(hashpos == hash->chain[hashpos]) break; + + if(numzeros >= 3 && length > numzeros) { + hashpos = hash->chainz[hashpos]; + if(hash->zeros[hashpos] != numzeros) break; + } else { + hashpos = hash->chain[hashpos]; + /*outdated hash value, happens if particular value was not encountered in whole last window*/ + if(hash->val[hashpos] != (int)hashval) break; + } + } + + if(lazymatching) { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) { + lazy = 1; + lazylength = length; + lazyoffset = offset; + continue; /*try the next byte*/ + } + if(lazy) { + lazy = 0; + if(pos == 0) ERROR_BREAK(81); + if(length > lazylength + 1) { + /*push the previous character as literal*/ + if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); + } else { + length = lazylength; + offset = lazyoffset; + hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ + hash->headz[numzeros] = -1; /*idem*/ + --pos; + } + } + } + if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); + + /*encode it as length/distance pair or literal value*/ + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ { + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } else if(length < minmatch || (length == 3 && offset > 4096)) { + /*compensate for the fact that longer offsets have more extra bits, a + length of only 3 may be not worth it then*/ + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } else { + addLengthDistance(out, length, offset); + for(i = 1; i < length; ++i) { + ++pos; + wpos = pos & (windowsize - 1); + hashval = getHash(in, insize, pos); + if(usezeros && hashval == 0) { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } else { + numzeros = 0; + } + updateHashChain(hash, wpos, hashval, numzeros); + } + } + } /*end of the loop through each character of input*/ + + return error; +} + +/* /////////////////////////////////////////////////////////////////////////// */ + +static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) { + /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, + 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ + + size_t i, numdeflateblocks = (datasize + 65534u) / 65535u; + unsigned datapos = 0; + for(i = 0; i != numdeflateblocks; ++i) { + unsigned BFINAL, BTYPE, LEN, NLEN; + unsigned char firstbyte; + size_t pos = out->size; + + BFINAL = (i == numdeflateblocks - 1); + BTYPE = 0; + + LEN = 65535; + if(datasize - datapos < 65535u) LEN = (unsigned)datasize - datapos; + NLEN = 65535 - LEN; + + if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/ + + firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u)); + out->data[pos + 0] = firstbyte; + out->data[pos + 1] = (unsigned char)(LEN & 255); + out->data[pos + 2] = (unsigned char)(LEN >> 8u); + out->data[pos + 3] = (unsigned char)(NLEN & 255); + out->data[pos + 4] = (unsigned char)(NLEN >> 8u); + lodepng_memcpy(out->data + pos + 5, data + datapos, LEN); + datapos += LEN; + } + + return 0; +} + +/* +write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. +tree_ll: the tree for lit and len codes. +tree_d: the tree for distance codes. +*/ +static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded, + const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { + size_t i = 0; + for(i = 0; i != lz77_encoded->size; ++i) { + unsigned val = lz77_encoded->data[i]; + writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[val]); + if(val > 256) /*for a length code, 3 more things have to be added*/ { + unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; + unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; + unsigned length_extra_bits = lz77_encoded->data[++i]; + + unsigned distance_code = lz77_encoded->data[++i]; + + unsigned distance_index = distance_code; + unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; + unsigned distance_extra_bits = lz77_encoded->data[++i]; + + writeBits(writer, length_extra_bits, n_length_extra_bits); + writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]); + writeBits(writer, distance_extra_bits, n_distance_extra_bits); + } + } +} + +/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ +static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash, + const unsigned char* data, size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) { + unsigned error = 0; + + /* + A block is compressed as follows: The PNG data is lz77 encoded, resulting in + literal bytes and length/distance pairs. This is then huffman compressed with + two huffman trees. One huffman tree is used for the lit and len values ("ll"), + another huffman tree is used for the dist values ("d"). These two trees are + stored using their code lengths, and to compress even more these code lengths + are also run-length encoded and huffman compressed. This gives a huffman tree + of code lengths "cl". The code lengths used to describe this third tree are + the code length code lengths ("clcl"). + */ + + /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ + uivector lz77_encoded; + HuffmanTree tree_ll; /*tree for lit,len values*/ + HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ + unsigned* frequencies_ll = 0; /*frequency of lit,len codes*/ + unsigned* frequencies_d = 0; /*frequency of dist codes*/ + unsigned* frequencies_cl = 0; /*frequency of code length codes*/ + unsigned* bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/ + unsigned* bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/ + size_t datasize = dataend - datapos; + + /* + If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent + tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are + some analogies: + bitlen_lld is to tree_cl what data is to tree_ll and tree_d. + bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. + bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. + */ + + unsigned BFINAL = final; + size_t i; + size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl; + unsigned HLIT, HDIST, HCLEN; + + uivector_init(&lz77_encoded); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_cl); + /* could fit on stack, but >1KB is on the larger side so allocate instead */ + frequencies_ll = (unsigned*)lodepng_malloc(286 * sizeof(*frequencies_ll)); + frequencies_d = (unsigned*)lodepng_malloc(30 * sizeof(*frequencies_d)); + frequencies_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); + + if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/ + + /*This while loop never loops due to a break at the end, it is here to + allow breaking out of it to the cleanup phase on error conditions.*/ + while(!error) { + lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll)); + lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d)); + lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); + + if(settings->use_lz77) { + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(error) break; + } else { + if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); + for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ + } + + /*Count the frequencies of lit, len and dist codes*/ + for(i = 0; i != lz77_encoded.size; ++i) { + unsigned symbol = lz77_encoded.data[i]; + ++frequencies_ll[symbol]; + if(symbol > 256) { + unsigned dist = lz77_encoded.data[i + 2]; + ++frequencies_d[dist]; + i += 3; + } + } + frequencies_ll[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ + + /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ + error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll, 257, 286, 15); + if(error) break; + /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ + error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d, 2, 30, 15); + if(error) break; + + numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286); + numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30); + /*store the code lengths of both generated trees in bitlen_lld*/ + numcodes_lld = numcodes_ll + numcodes_d; + bitlen_lld = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld)); + /*numcodes_lld_e never needs more size than bitlen_lld*/ + bitlen_lld_e = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e)); + if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/ + numcodes_lld_e = 0; + + for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i]; + for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[i]; + + /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), + 17 (3-10 zeroes), 18 (11-138 zeroes)*/ + for(i = 0; i != numcodes_lld; ++i) { + unsigned j = 0; /*amount of repetitions*/ + while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j; + + if(bitlen_lld[i] == 0 && j >= 2) /*repeat code for zeroes*/ { + ++j; /*include the first zero*/ + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ { + bitlen_lld_e[numcodes_lld_e++] = 17; + bitlen_lld_e[numcodes_lld_e++] = j - 3; + } else /*repeat code 18 supports max 138 zeroes*/ { + if(j > 138) j = 138; + bitlen_lld_e[numcodes_lld_e++] = 18; + bitlen_lld_e[numcodes_lld_e++] = j - 11; + } + i += (j - 1); + } else if(j >= 3) /*repeat code for value other than zero*/ { + size_t k; + unsigned num = j / 6u, rest = j % 6u; + bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; + for(k = 0; k < num; ++k) { + bitlen_lld_e[numcodes_lld_e++] = 16; + bitlen_lld_e[numcodes_lld_e++] = 6 - 3; + } + if(rest >= 3) { + bitlen_lld_e[numcodes_lld_e++] = 16; + bitlen_lld_e[numcodes_lld_e++] = rest - 3; + } + else j -= rest; + i += j; + } else /*too short to benefit from repeat code*/ { + bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; + } + } + + /*generate tree_cl, the huffmantree of huffmantrees*/ + for(i = 0; i != numcodes_lld_e; ++i) { + ++frequencies_cl[bitlen_lld_e[i]]; + /*after a repeat code come the bits that specify the number of repetitions, + those don't need to be in the frequencies_cl calculation*/ + if(bitlen_lld_e[i] >= 16) ++i; + } + + error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl, + NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*compute amount of code-length-code-lengths to output*/ + numcodes_cl = NUM_CODE_LENGTH_CODES; + /*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/ + while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) { + numcodes_cl--; + } + + /* + Write everything into the output + + After the BFINAL and BTYPE, the dynamic block consists out of the following: + - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN + - (HCLEN+4)*3 bits code lengths of code length alphabet + - HLIT + 257 code lengths of lit/length alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - HDIST + 1 code lengths of distance alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - compressed data + - 256 (end code) + */ + + /*Write block type*/ + writeBits(writer, BFINAL, 1); + writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/ + writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/ + + /*write the HLIT, HDIST and HCLEN values*/ + /*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies + or in the loop for numcodes_cl above, which saves space. */ + HLIT = (unsigned)(numcodes_ll - 257); + HDIST = (unsigned)(numcodes_d - 1); + HCLEN = (unsigned)(numcodes_cl - 4); + writeBits(writer, HLIT, 5); + writeBits(writer, HDIST, 5); + writeBits(writer, HCLEN, 4); + + /*write the code lengths of the code length alphabet ("bitlen_cl")*/ + for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3); + + /*write the lengths of the lit/len AND the dist alphabet*/ + for(i = 0; i != numcodes_lld_e; ++i) { + writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]); + /*extra bits of repeat codes*/ + if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2); + else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3); + else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7); + } + + /*write the compressed data symbols*/ + writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d); + /*error: the length of the end code 256 must be larger than 0*/ + if(tree_ll.lengths[256] == 0) ERROR_BREAK(64); + + /*write the end code*/ + writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]); + + break; /*end of error-while*/ + } + + /*cleanup*/ + uivector_cleanup(&lz77_encoded); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_cl); + lodepng_free(frequencies_ll); + lodepng_free(frequencies_d); + lodepng_free(frequencies_cl); + lodepng_free(bitlen_lld); + lodepng_free(bitlen_lld_e); + + return error; +} + +static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash, + const unsigned char* data, + size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) { + HuffmanTree tree_ll; /*tree for literal values and length codes*/ + HuffmanTree tree_d; /*tree for distance codes*/ + + unsigned BFINAL = final; + unsigned error = 0; + size_t i; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + error = generateFixedLitLenTree(&tree_ll); + if(!error) error = generateFixedDistanceTree(&tree_d); + + if(!error) { + writeBits(writer, BFINAL, 1); + writeBits(writer, 1, 1); /*first bit of BTYPE*/ + writeBits(writer, 0, 1); /*second bit of BTYPE*/ + + if(settings->use_lz77) /*LZ77 encoded*/ { + uivector lz77_encoded; + uivector_init(&lz77_encoded); + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d); + uivector_cleanup(&lz77_encoded); + } else /*no LZ77, but still will be Huffman compressed*/ { + for(i = datapos; i < dataend; ++i) { + writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]); + } + } + /*add END code*/ + if(!error) writeBitsReversed(writer,tree_ll.codes[256], tree_ll.lengths[256]); + } + + /*cleanup*/ + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + unsigned error = 0; + size_t i, blocksize, numdeflateblocks; + Hash hash; + LodePNGBitWriter writer; + + LodePNGBitWriter_init(&writer, out); + + if(settings->btype > 2) return 61; + else if(settings->btype == 0) return deflateNoCompression(out, in, insize); + else if(settings->btype == 1) blocksize = insize; + else /*if(settings->btype == 2)*/ { + /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ + blocksize = insize / 8u + 8; + if(blocksize < 65536) blocksize = 65536; + if(blocksize > 262144) blocksize = 262144; + } + + numdeflateblocks = (insize + blocksize - 1) / blocksize; + if(numdeflateblocks == 0) numdeflateblocks = 1; + + error = hash_init(&hash, settings->windowsize); + + if(!error) { + for(i = 0; i != numdeflateblocks && !error; ++i) { + unsigned final = (i == numdeflateblocks - 1); + size_t start = i * blocksize; + size_t end = start + blocksize; + if(end > insize) end = insize; + + if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final); + else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final); + } + } + + hash_cleanup(&hash); + + return error; +} + +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_deflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + if(settings->custom_deflate) { + return settings->custom_deflate(out, outsize, in, insize, settings); + } else { + return lodepng_deflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Adler32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { + unsigned s1 = adler & 0xffffu; + unsigned s2 = (adler >> 16u) & 0xffffu; + + while(len != 0u) { + unsigned i; + /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5552u ? 5552u : len; + len -= amount; + for(i = 0; i != amount; ++i) { + s1 += (*data++); + s2 += s1; + } + s1 %= 65521u; + s2 %= 65521u; + } + + return (s2 << 16u) | s1; +} + +/*Return the adler32 of the bytes data[0..len-1]*/ +static unsigned adler32(const unsigned char* data, unsigned len) { + return update_adler32(1u, data, len); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Zlib / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DECODER + +static unsigned lodepng_zlib_decompressv(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + unsigned error = 0; + unsigned CM, CINFO, FDICT; + + if(insize < 2) return 53; /*error, size of zlib data too small*/ + /*read information from zlib header*/ + if((in[0] * 256 + in[1]) % 31 != 0) { + /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ + return 24; + } + + CM = in[0] & 15; + CINFO = (in[0] >> 4) & 15; + /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ + FDICT = (in[1] >> 5) & 1; + /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ + + if(CM != 8 || CINFO > 7) { + /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ + return 25; + } + if(FDICT != 0) { + /*error: the specification of PNG says about the zlib stream: + "The additional flags shall not specify a preset dictionary."*/ + return 26; + } + + error = inflatev(out, in + 2, insize - 2, settings); + if(error) return error; + + if(!settings->ignore_adler32) { + unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); + unsigned checksum = adler32(out->data, (unsigned)(out->size)); + if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ + } + + return 0; /*no error*/ +} + + +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */ +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, + const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { + if(settings->custom_zlib) { + return settings->custom_zlib(out, outsize, in, insize, settings); + } else { + unsigned error; + ucvector v = ucvector_init(*out, *outsize); + if(expected_size) { + /*reserve the memory to avoid intermediate reallocations*/ + ucvector_resize(&v, *outsize + expected_size); + v.size = *outsize; + } + error = lodepng_zlib_decompressv(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + size_t i; + unsigned error; + unsigned char* deflatedata = 0; + size_t deflatesize = 0; + + error = deflate(&deflatedata, &deflatesize, in, insize, settings); + + *out = NULL; + *outsize = 0; + if(!error) { + *outsize = deflatesize + 6; + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!*out) error = 83; /*alloc fail*/ + } + + if(!error) { + unsigned ADLER32 = adler32(in, (unsigned)insize); + /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ + unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ + unsigned FLEVEL = 0; + unsigned FDICT = 0; + unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; + unsigned FCHECK = 31 - CMFFLG % 31; + CMFFLG += FCHECK; + + (*out)[0] = (unsigned char)(CMFFLG >> 8); + (*out)[1] = (unsigned char)(CMFFLG & 255); + for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i]; + lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32); + } + + lodepng_free(deflatedata); + return error; +} + +/* compress using the default or custom zlib function */ +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + if(settings->custom_zlib) { + return settings->custom_zlib(out, outsize, in, insize, settings); + } else { + return lodepng_zlib_compress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#else /*no LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DECODER +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, + const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + (void)expected_size; + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/*this is a good tradeoff between speed and compression ratio*/ +#define DEFAULT_WINDOWSIZE 2048 + +void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { + /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ + settings->btype = 2; + settings->use_lz77 = 1; + settings->windowsize = DEFAULT_WINDOWSIZE; + settings->minmatch = 3; + settings->nicematch = 128; + settings->lazymatching = 1; + + settings->custom_zlib = 0; + settings->custom_deflate = 0; + settings->custom_context = 0; +} + +const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; + + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { + settings->ignore_adler32 = 0; + settings->ignore_nlen = 0; + + settings->custom_zlib = 0; + settings->custom_inflate = 0; + settings->custom_context = 0; +} + +const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0}; + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of Zlib related code. Begin of PNG related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / CRC32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + + +#ifndef LODEPNG_NO_COMPILE_CRC +/* CRC polynomial: 0xedb88320 */ +static unsigned lodepng_crc32_table[256] = { + 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, + 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, + 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, + 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, + 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, + 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, + 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, + 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, + 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, + 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, + 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, + 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, + 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, + 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, + 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, + 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, + 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, + 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, + 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, + 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, + 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, + 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, + 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, + 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, + 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, + 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, + 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, + 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, + 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, + 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, + 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, + 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u +}; + +/*Return the CRC of the bytes buf[0..len-1].*/ +unsigned lodepng_crc32(const unsigned char* data, size_t length) { + unsigned r = 0xffffffffu; + size_t i; + for(i = 0; i < length; ++i) { + r = lodepng_crc32_table[(r ^ data[i]) & 0xffu] ^ (r >> 8u); + } + return r ^ 0xffffffffu; +} +#else /* !LODEPNG_NO_COMPILE_CRC */ +unsigned lodepng_crc32(const unsigned char* data, size_t length); +#endif /* !LODEPNG_NO_COMPILE_CRC */ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Reading and writing PNG color channel bits / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first, +so LodePNGBitWriter and LodePNGBitReader can't be used for those. */ + +static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) { + unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); + ++(*bitpointer); + return result; +} + +/* TODO: make this faster */ +static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { + unsigned result = 0; + size_t i; + for(i = 0 ; i < nbits; ++i) { + result <<= 1u; + result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); + } + return result; +} + +static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { + /*the current bit in bitstream may be 0 or 1 for this to work*/ + if(bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u)))); + else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u))); + ++(*bitpointer); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG chunks / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_chunk_length(const unsigned char* chunk) { + return lodepng_read32bitInt(&chunk[0]); +} + +void lodepng_chunk_type(char type[5], const unsigned char* chunk) { + unsigned i; + for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; + type[4] = 0; /*null termination char*/ +} + +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) { + if(lodepng_strlen(type) != 4) return 0; + return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); +} + +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) { + return((chunk[4] & 32) != 0); +} + +unsigned char lodepng_chunk_private(const unsigned char* chunk) { + return((chunk[6] & 32) != 0); +} + +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) { + return((chunk[7] & 32) != 0); +} + +unsigned char* lodepng_chunk_data(unsigned char* chunk) { + return &chunk[8]; +} + +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) { + return &chunk[8]; +} + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk) { + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); + /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ + unsigned checksum = lodepng_crc32(&chunk[4], length + 4); + if(CRC != checksum) return 1; + else return 0; +} + +void lodepng_chunk_generate_crc(unsigned char* chunk) { + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_crc32(&chunk[4], length + 4); + lodepng_set32bitInt(chunk + 8 + length, CRC); +} + +unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end) { + if(chunk >= end || end - chunk < 12) return end; /*too small to contain a chunk*/ + if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 + && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { + /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ + return chunk + 8; + } else { + size_t total_chunk_length; + unsigned char* result; + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; + result = chunk + total_chunk_length; + if(result < chunk) return end; /*pointer overflow*/ + return result; + } +} + +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end) { + if(chunk >= end || end - chunk < 12) return end; /*too small to contain a chunk*/ + if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 + && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { + /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ + return chunk + 8; + } else { + size_t total_chunk_length; + const unsigned char* result; + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; + result = chunk + total_chunk_length; + if(result < chunk) return end; /*pointer overflow*/ + return result; + } +} + +unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]) { + for(;;) { + if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ + if(lodepng_chunk_type_equals(chunk, type)) return chunk; + chunk = lodepng_chunk_next(chunk, end); + } +} + +const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) { + for(;;) { + if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ + if(lodepng_chunk_type_equals(chunk, type)) return chunk; + chunk = lodepng_chunk_next_const(chunk, end); + } +} + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk) { + unsigned i; + size_t total_chunk_length, new_length; + unsigned char *chunk_start, *new_buffer; + + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77; + if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77; + + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outsize) = new_length; + chunk_start = &(*out)[new_length - total_chunk_length]; + + for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; + + return 0; +} + +/*Sets length and name and allocates the space for data and crc but does not +set data or crc yet. Returns the start of the chunk in chunk. The start of +the data is at chunk + 8. To finalize chunk, add the data, then use +lodepng_chunk_generate_crc */ +static unsigned lodepng_chunk_init(unsigned char** chunk, + ucvector* out, + unsigned length, const char* type) { + size_t new_length = out->size; + if(lodepng_addofl(new_length, length, &new_length)) return 77; + if(lodepng_addofl(new_length, 12, &new_length)) return 77; + if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/ + *chunk = out->data + new_length - length - 12u; + + /*1: length*/ + lodepng_set32bitInt(*chunk, length); + + /*2: chunk name (4 letters)*/ + lodepng_memcpy(*chunk + 4, type, 4); + + return 0; +} + +/* like lodepng_chunk_create but with custom allocsize */ +static unsigned lodepng_chunk_createv(ucvector* out, + unsigned length, const char* type, const unsigned char* data) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type)); + + /*3: the data*/ + lodepng_memcpy(chunk + 8, data, length); + + /*4: CRC (of the chunkname characters and the data)*/ + lodepng_chunk_generate_crc(chunk); + + return 0; +} + +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, + unsigned length, const char* type, const unsigned char* data) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_chunk_createv(&v, length, type, data); + *out = v.data; + *outsize = v.size; + return error; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Color types, channels, bits / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype. +Return value is a LodePNG error code.*/ +static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) { + switch(colortype) { + case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; + case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; + case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */ + default: return 31; /* invalid color type */ + } + return 0; /*allowed color type / bits combination*/ +} + +static unsigned getNumColorChannels(LodePNGColorType colortype) { + switch(colortype) { + case LCT_GREY: return 1; + case LCT_RGB: return 3; + case LCT_PALETTE: return 1; + case LCT_GREY_ALPHA: return 2; + case LCT_RGBA: return 4; + case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */ + default: return 0; /*invalid color type*/ + } +} + +static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { + /*bits per pixel is amount of channels * bits per channel*/ + return getNumColorChannels(colortype) * bitdepth; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +void lodepng_color_mode_init(LodePNGColorMode* info) { + info->key_defined = 0; + info->key_r = info->key_g = info->key_b = 0; + info->colortype = LCT_RGBA; + info->bitdepth = 8; + info->palette = 0; + info->palettesize = 0; +} + +/*allocates palette memory if needed, and initializes all colors to black*/ +static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) { + size_t i; + /*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/ + /*the palette must have room for up to 256 colors with 4 bytes each.*/ + if(!info->palette) info->palette = (unsigned char*)lodepng_malloc(1024); + if(!info->palette) return; /*alloc fail*/ + for(i = 0; i != 256; ++i) { + /*Initialize all unused colors with black, the value used for invalid palette indices. + This is an error according to the PNG spec, but common PNG decoders make it black instead. + That makes color conversion slightly faster due to no error handling needed.*/ + info->palette[i * 4 + 0] = 0; + info->palette[i * 4 + 1] = 0; + info->palette[i * 4 + 2] = 0; + info->palette[i * 4 + 3] = 255; + } +} + +void lodepng_color_mode_cleanup(LodePNGColorMode* info) { + lodepng_palette_clear(info); +} + +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { + lodepng_color_mode_cleanup(dest); + lodepng_memcpy(dest, source, sizeof(LodePNGColorMode)); + if(source->palette) { + dest->palette = (unsigned char*)lodepng_malloc(1024); + if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ + lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4); + } + return 0; +} + +LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) { + LodePNGColorMode result; + lodepng_color_mode_init(&result); + result.colortype = colortype; + result.bitdepth = bitdepth; + return result; +} + +static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { + size_t i; + if(a->colortype != b->colortype) return 0; + if(a->bitdepth != b->bitdepth) return 0; + if(a->key_defined != b->key_defined) return 0; + if(a->key_defined) { + if(a->key_r != b->key_r) return 0; + if(a->key_g != b->key_g) return 0; + if(a->key_b != b->key_b) return 0; + } + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) { + if(a->palette[i] != b->palette[i]) return 0; + } + return 1; +} + +void lodepng_palette_clear(LodePNGColorMode* info) { + if(info->palette) lodepng_free(info->palette); + info->palette = 0; + info->palettesize = 0; +} + +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + if(!info->palette) /*allocate palette if empty*/ { + lodepng_color_mode_alloc_palette(info); + if(!info->palette) return 83; /*alloc fail*/ + } + if(info->palettesize >= 256) { + return 108; /*too many palette values*/ + } + info->palette[4 * info->palettesize + 0] = r; + info->palette[4 * info->palettesize + 1] = g; + info->palette[4 * info->palettesize + 2] = b; + info->palette[4 * info->palettesize + 3] = a; + ++info->palettesize; + return 0; +} + +/*calculate bits per pixel out of colortype and bitdepth*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info) { + return lodepng_get_bpp_lct(info->colortype, info->bitdepth); +} + +unsigned lodepng_get_channels(const LodePNGColorMode* info) { + return getNumColorChannels(info->colortype); +} + +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { + return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; +} + +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { + return (info->colortype & 4) != 0; /*4 or 6*/ +} + +unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { + return info->colortype == LCT_PALETTE; +} + +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { + size_t i; + for(i = 0; i != info->palettesize; ++i) { + if(info->palette[i * 4 + 3] < 255) return 1; + } + return 0; +} + +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { + return info->key_defined + || lodepng_is_alpha_type(info) + || lodepng_has_palette_alpha(info); +} + +static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { + size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); + size_t n = (size_t)w * (size_t)h; + return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u; +} + +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { + return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); +} + + +#ifdef LODEPNG_COMPILE_PNG + +/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, +and in addition has one extra byte per line: the filter byte. So this gives a larger +result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */ +static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp) { + /* + 1 for the filter byte, and possibly plus padding bits per line. */ + /* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */ + size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u; + return (size_t)h * line; +} + +#ifdef LODEPNG_COMPILE_DECODER +/*Safely checks whether size_t overflow can be caused due to amount of pixels. +This check is overcautious rather than precise. If this check indicates no overflow, +you can safely compute in a size_t (but not an unsigned): +-(size_t)w * (size_t)h * 8 +-amount of bytes in IDAT (including filter, padding and Adam7 bytes) +-amount of bytes in raw color model +Returns 1 if overflow possible, 0 if not. +*/ +static int lodepng_pixel_overflow(unsigned w, unsigned h, + const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) { + size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); + size_t numpixels, total; + size_t line; /* bytes per line in worst case */ + + if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1; + if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */ + + /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */ + if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1; + if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1; + + if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */ + if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */ + + return 0; /* no overflow */ +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static void LodePNGUnknownChunks_init(LodePNGInfo* info) { + unsigned i; + for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; + for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; +} + +static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { + unsigned i; + for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); +} + +static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { + unsigned i; + + LodePNGUnknownChunks_cleanup(dest); + + for(i = 0; i != 3; ++i) { + size_t j; + dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; + dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); + if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ + for(j = 0; j < src->unknown_chunks_size[i]; ++j) { + dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; + } + } + + return 0; +} + +/******************************************************************************/ + +static void LodePNGText_init(LodePNGInfo* info) { + info->text_num = 0; + info->text_keys = NULL; + info->text_strings = NULL; +} + +static void LodePNGText_cleanup(LodePNGInfo* info) { + size_t i; + for(i = 0; i != info->text_num; ++i) { + string_cleanup(&info->text_keys[i]); + string_cleanup(&info->text_strings[i]); + } + lodepng_free(info->text_keys); + lodepng_free(info->text_strings); +} + +static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + size_t i = 0; + dest->text_keys = 0; + dest->text_strings = 0; + dest->text_num = 0; + for(i = 0; i != source->text_num; ++i) { + CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); + } + return 0; +} + +static unsigned lodepng_add_text_sized(LodePNGInfo* info, const char* key, const char* str, size_t size) { + char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); + + if(new_keys) info->text_keys = new_keys; + if(new_strings) info->text_strings = new_strings; + + if(!new_keys || !new_strings) return 83; /*alloc fail*/ + + ++info->text_num; + info->text_keys[info->text_num - 1] = alloc_string(key); + info->text_strings[info->text_num - 1] = alloc_string_sized(str, size); + if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/ + + return 0; +} + +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { + return lodepng_add_text_sized(info, key, str, lodepng_strlen(str)); +} + +void lodepng_clear_text(LodePNGInfo* info) { + LodePNGText_cleanup(info); +} + +/******************************************************************************/ + +static void LodePNGIText_init(LodePNGInfo* info) { + info->itext_num = 0; + info->itext_keys = NULL; + info->itext_langtags = NULL; + info->itext_transkeys = NULL; + info->itext_strings = NULL; +} + +static void LodePNGIText_cleanup(LodePNGInfo* info) { + size_t i; + for(i = 0; i != info->itext_num; ++i) { + string_cleanup(&info->itext_keys[i]); + string_cleanup(&info->itext_langtags[i]); + string_cleanup(&info->itext_transkeys[i]); + string_cleanup(&info->itext_strings[i]); + } + lodepng_free(info->itext_keys); + lodepng_free(info->itext_langtags); + lodepng_free(info->itext_transkeys); + lodepng_free(info->itext_strings); +} + +static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + size_t i = 0; + dest->itext_keys = 0; + dest->itext_langtags = 0; + dest->itext_transkeys = 0; + dest->itext_strings = 0; + dest->itext_num = 0; + for(i = 0; i != source->itext_num; ++i) { + CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], + source->itext_transkeys[i], source->itext_strings[i])); + } + return 0; +} + +void lodepng_clear_itext(LodePNGInfo* info) { + LodePNGIText_cleanup(info); +} + +static unsigned lodepng_add_itext_sized(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str, size_t size) { + char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); + char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); + char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); + + if(new_keys) info->itext_keys = new_keys; + if(new_langtags) info->itext_langtags = new_langtags; + if(new_transkeys) info->itext_transkeys = new_transkeys; + if(new_strings) info->itext_strings = new_strings; + + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/ + + ++info->itext_num; + + info->itext_keys[info->itext_num - 1] = alloc_string(key); + info->itext_langtags[info->itext_num - 1] = alloc_string(langtag); + info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey); + info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size); + + return 0; +} + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str) { + return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str)); +} + +/* same as set but does not delete */ +static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { + if(profile_size == 0) return 100; /*invalid ICC profile size*/ + + info->iccp_name = alloc_string(name); + info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size); + + if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/ + + lodepng_memcpy(info->iccp_profile, profile, profile_size); + info->iccp_profile_size = profile_size; + + return 0; /*ok*/ +} + +unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { + if(info->iccp_name) lodepng_clear_icc(info); + info->iccp_defined = 1; + + return lodepng_assign_icc(info, name, profile, profile_size); +} + +void lodepng_clear_icc(LodePNGInfo* info) { + string_cleanup(&info->iccp_name); + lodepng_free(info->iccp_profile); + info->iccp_profile = NULL; + info->iccp_profile_size = 0; + info->iccp_defined = 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +void lodepng_info_init(LodePNGInfo* info) { + lodepng_color_mode_init(&info->color); + info->interlace_method = 0; + info->compression_method = 0; + info->filter_method = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + info->background_defined = 0; + info->background_r = info->background_g = info->background_b = 0; + + LodePNGText_init(info); + LodePNGIText_init(info); + + info->time_defined = 0; + info->phys_defined = 0; + + info->gama_defined = 0; + info->chrm_defined = 0; + info->srgb_defined = 0; + info->iccp_defined = 0; + info->iccp_name = NULL; + info->iccp_profile = NULL; + + LodePNGUnknownChunks_init(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +void lodepng_info_cleanup(LodePNGInfo* info) { + lodepng_color_mode_cleanup(&info->color); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + LodePNGText_cleanup(info); + LodePNGIText_cleanup(info); + + lodepng_clear_icc(info); + + LodePNGUnknownChunks_cleanup(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + lodepng_info_cleanup(dest); + lodepng_memcpy(dest, source, sizeof(LodePNGInfo)); + lodepng_color_mode_init(&dest->color); + CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); + if(source->iccp_defined) { + CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size)); + } + + LodePNGUnknownChunks_init(dest); + CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + return 0; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ +static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) { + unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ + /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ + unsigned p = index & m; + in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ + in = in << (bits * (m - p)); + if(p == 0) out[index * bits / 8u] = in; + else out[index * bits / 8u] |= in; +} + +typedef struct ColorTree ColorTree; + +/* +One node of a color tree +This is the data structure used to count the number of unique colors and to get a palette +index for a color. It's like an octree, but because the alpha channel is used too, each +node has 16 instead of 8 children. +*/ +struct ColorTree { + ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ + int index; /*the payload. Only has a meaningful value if this is in the last level*/ +}; + +static void color_tree_init(ColorTree* tree) { + lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children)); + tree->index = -1; +} + +static void color_tree_cleanup(ColorTree* tree) { + int i; + for(i = 0; i != 16; ++i) { + if(tree->children[i]) { + color_tree_cleanup(tree->children[i]); + lodepng_free(tree->children[i]); + } + } +} + +/*returns -1 if color not present, its index otherwise*/ +static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + int bit = 0; + for(bit = 0; bit < 8; ++bit) { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) return -1; + else tree = tree->children[i]; + } + return tree ? tree->index : -1; +} + +#ifdef LODEPNG_COMPILE_ENCODER +static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + return color_tree_get(tree, r, g, b, a) >= 0; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*color is not allowed to already exist. +Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist") +Returns error code, or 0 if ok*/ +static unsigned color_tree_add(ColorTree* tree, + unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) { + int bit; + for(bit = 0; bit < 8; ++bit) { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) { + tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); + if(!tree->children[i]) return 83; /*alloc fail*/ + color_tree_init(tree->children[i]); + } + tree = tree->children[i]; + } + tree->index = (int)index; + return 0; +} + +/*put a pixel, given its RGBA color, into image of any color type*/ +static unsigned rgba8ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + if(mode->colortype == LCT_GREY) { + unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/ + if(mode->bitdepth == 8) out[i] = gray; + else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray; + else { + /*take the most significant bits of gray*/ + gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u); + addColorBits(out, i, mode->bitdepth, gray); + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + out[i * 3 + 0] = r; + out[i * 3 + 1] = g; + out[i * 3 + 2] = b; + } else { + out[i * 6 + 0] = out[i * 6 + 1] = r; + out[i * 6 + 2] = out[i * 6 + 3] = g; + out[i * 6 + 4] = out[i * 6 + 5] = b; + } + } else if(mode->colortype == LCT_PALETTE) { + int index = color_tree_get(tree, r, g, b, a); + if(index < 0) return 82; /*color not in palette*/ + if(mode->bitdepth == 8) out[i] = index; + else addColorBits(out, i, mode->bitdepth, (unsigned)index); + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/ + if(mode->bitdepth == 8) { + out[i * 2 + 0] = gray; + out[i * 2 + 1] = a; + } else if(mode->bitdepth == 16) { + out[i * 4 + 0] = out[i * 4 + 1] = gray; + out[i * 4 + 2] = out[i * 4 + 3] = a; + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + out[i * 4 + 0] = r; + out[i * 4 + 1] = g; + out[i * 4 + 2] = b; + out[i * 4 + 3] = a; + } else { + out[i * 8 + 0] = out[i * 8 + 1] = r; + out[i * 8 + 2] = out[i * 8 + 3] = g; + out[i * 8 + 4] = out[i * 8 + 5] = b; + out[i * 8 + 6] = out[i * 8 + 7] = a; + } + } + + return 0; /*no error*/ +} + +/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ +static void rgba16ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, + unsigned short r, unsigned short g, unsigned short b, unsigned short a) { + if(mode->colortype == LCT_GREY) { + unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/ + out[i * 2 + 0] = (gray >> 8) & 255; + out[i * 2 + 1] = gray & 255; + } else if(mode->colortype == LCT_RGB) { + out[i * 6 + 0] = (r >> 8) & 255; + out[i * 6 + 1] = r & 255; + out[i * 6 + 2] = (g >> 8) & 255; + out[i * 6 + 3] = g & 255; + out[i * 6 + 4] = (b >> 8) & 255; + out[i * 6 + 5] = b & 255; + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/ + out[i * 4 + 0] = (gray >> 8) & 255; + out[i * 4 + 1] = gray & 255; + out[i * 4 + 2] = (a >> 8) & 255; + out[i * 4 + 3] = a & 255; + } else if(mode->colortype == LCT_RGBA) { + out[i * 8 + 0] = (r >> 8) & 255; + out[i * 8 + 1] = r & 255; + out[i * 8 + 2] = (g >> 8) & 255; + out[i * 8 + 3] = g & 255; + out[i * 8 + 4] = (b >> 8) & 255; + out[i * 8 + 5] = b & 255; + out[i * 8 + 6] = (a >> 8) & 255; + out[i * 8 + 7] = a & 255; + } +} + +/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ +static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, + unsigned char* b, unsigned char* a, + const unsigned char* in, size_t i, + const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + *r = *g = *b = in[i]; + if(mode->key_defined && *r == mode->key_r) *a = 0; + else *a = 255; + } else if(mode->bitdepth == 16) { + *r = *g = *b = in[i * 2 + 0]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 255; + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = i * mode->bitdepth; + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + *r = *g = *b = (value * 255) / highest; + if(mode->key_defined && value == mode->key_r) *a = 0; + else *a = 255; + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; + if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; + else *a = 255; + } else { + *r = in[i * 6 + 0]; + *g = in[i * 6 + 2]; + *b = in[i * 6 + 4]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 255; + } + } else if(mode->colortype == LCT_PALETTE) { + unsigned index; + if(mode->bitdepth == 8) index = in[i]; + else { + size_t j = i * mode->bitdepth; + index = readBitsFromReversedStream(&j, in, mode->bitdepth); + } + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + *r = mode->palette[index * 4 + 0]; + *g = mode->palette[index * 4 + 1]; + *b = mode->palette[index * 4 + 2]; + *a = mode->palette[index * 4 + 3]; + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + *r = *g = *b = in[i * 2 + 0]; + *a = in[i * 2 + 1]; + } else { + *r = *g = *b = in[i * 4 + 0]; + *a = in[i * 4 + 2]; + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + *r = in[i * 4 + 0]; + *g = in[i * 4 + 1]; + *b = in[i * 4 + 2]; + *a = in[i * 4 + 3]; + } else { + *r = in[i * 8 + 0]; + *g = in[i * 8 + 2]; + *b = in[i * 8 + 4]; + *a = in[i * 8 + 6]; + } + } +} + +/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color +mode test cases, optimized to convert the colors much faster, when converting +to the common case of RGBA with 8 bit per channel. buffer must be RGBA with +enough memory.*/ +static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, + const unsigned char* LODEPNG_RESTRICT in, + const LodePNGColorMode* mode) { + unsigned num_channels = 4; + size_t i; + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i]; + buffer[3] = 255; + } + if(mode->key_defined) { + buffer -= numpixels * num_channels; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + if(buffer[0] == mode->key_r) buffer[3] = 0; + } + } + } else if(mode->bitdepth == 16) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; + } + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; + } + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + lodepng_memcpy(buffer, &in[i * 3], 3); + buffer[3] = 255; + } + if(mode->key_defined) { + buffer -= numpixels * num_channels; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0; + } + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + buffer[3] = mode->key_defined + && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; + } + } + } else if(mode->colortype == LCT_PALETTE) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = in[i]; + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 4); + } + } else { + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 4); + } + } + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + buffer[3] = in[i * 2 + 1]; + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + buffer[3] = in[i * 4 + 2]; + } + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + lodepng_memcpy(buffer, in, numpixels * 4); + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + buffer[3] = in[i * 8 + 6]; + } + } + } +} + +/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/ +static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, + const unsigned char* LODEPNG_RESTRICT in, + const LodePNGColorMode* mode) { + const unsigned num_channels = 3; + size_t i; + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i]; + } + } else if(mode->bitdepth == 16) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + } + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + } + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + lodepng_memcpy(buffer, in, numpixels * 3); + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + } + } + } else if(mode->colortype == LCT_PALETTE) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = in[i]; + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 3); + } + } else { + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 3); + } + } + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + } + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + lodepng_memcpy(buffer, &in[i * 4], 3); + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + } + } + } +} + +/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with +given color type, but the given color type must be 16-bit itself.*/ +static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, + const unsigned char* in, size_t i, const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { + *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 65535; + } else if(mode->colortype == LCT_RGB) { + *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; + *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; + *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; + if(mode->key_defined + && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 65535; + } else if(mode->colortype == LCT_GREY_ALPHA) { + *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; + *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; + } else if(mode->colortype == LCT_RGBA) { + *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; + *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; + *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; + *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; + } +} + +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h) { + size_t i; + ColorTree tree; + size_t numpixels = (size_t)w * (size_t)h; + unsigned error = 0; + + if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) { + return 107; /* error: must provide palette if input mode is palette */ + } + + if(lodepng_color_mode_equal(mode_out, mode_in)) { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + lodepng_memcpy(out, in, numbytes); + return 0; + } + + if(mode_out->colortype == LCT_PALETTE) { + size_t palettesize = mode_out->palettesize; + const unsigned char* palette = mode_out->palette; + size_t palsize = (size_t)1u << mode_out->bitdepth; + /*if the user specified output palette but did not give the values, assume + they want the values of the input color type (assuming that one is palette). + Note that we never create a new palette ourselves.*/ + if(palettesize == 0) { + palettesize = mode_in->palettesize; + palette = mode_in->palette; + /*if the input was also palette with same bitdepth, then the color types are also + equal, so copy literally. This to preserve the exact indices that were in the PNG + even in case there are duplicate colors in the palette.*/ + if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + lodepng_memcpy(out, in, numbytes); + return 0; + } + } + if(palettesize < palsize) palsize = palettesize; + color_tree_init(&tree); + for(i = 0; i != palsize; ++i) { + const unsigned char* p = &palette[i * 4]; + error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); + if(error) break; + } + } + + if(!error) { + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) { + for(i = 0; i != numpixels; ++i) { + unsigned short r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + rgba16ToPixel(out, i, mode_out, r, g, b, a); + } + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) { + getPixelColorsRGBA8(out, numpixels, in, mode_in); + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { + getPixelColorsRGB8(out, numpixels, in, mode_in); + } else { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); + if(error) break; + } + } + } + + if(mode_out->colortype == LCT_PALETTE) { + color_tree_cleanup(&tree); + } + + return error; +} + + +/* Converts a single rgb color without alpha from one type to another, color bits truncated to +their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow +function, do not use to process all pixels of an image. Alpha channel not supported on purpose: +this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the +specification it looks like bKGD should ignore the alpha values of the palette since it can use +any palette index but doesn't have an alpha channel. Idem with ignoring color key. */ +unsigned lodepng_convert_rgb( + unsigned* r_out, unsigned* g_out, unsigned* b_out, + unsigned r_in, unsigned g_in, unsigned b_in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) { + unsigned r = 0, g = 0, b = 0; + unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/ + unsigned shift = 16 - mode_out->bitdepth; + + if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) { + r = g = b = r_in * mul; + } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) { + r = r_in * mul; + g = g_in * mul; + b = b_in * mul; + } else if(mode_in->colortype == LCT_PALETTE) { + if(r_in >= mode_in->palettesize) return 82; + r = mode_in->palette[r_in * 4 + 0] * 257u; + g = mode_in->palette[r_in * 4 + 1] * 257u; + b = mode_in->palette[r_in * 4 + 2] * 257u; + } else { + return 31; + } + + /* now convert to output format */ + if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) { + *r_out = r >> shift ; + } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) { + *r_out = r >> shift ; + *g_out = g >> shift ; + *b_out = b >> shift ; + } else if(mode_out->colortype == LCT_PALETTE) { + unsigned i; + /* a 16-bit color cannot be in the palette */ + if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82; + for(i = 0; i < mode_out->palettesize; i++) { + unsigned j = i * 4; + if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] && + (b >> 8) == mode_out->palette[j + 2]) { + *r_out = i; + return 0; + } + } + return 82; + } else { + return 31; + } + + return 0; +} + +#ifdef LODEPNG_COMPILE_ENCODER + +void lodepng_color_stats_init(LodePNGColorStats* stats) { + /*stats*/ + stats->colored = 0; + stats->key = 0; + stats->key_r = stats->key_g = stats->key_b = 0; + stats->alpha = 0; + stats->numcolors = 0; + stats->bits = 1; + stats->numpixels = 0; + /*settings*/ + stats->allow_palette = 1; + stats->allow_greyscale = 1; +} + +/*function used for debug purposes with C++*/ +/*void printColorStats(LodePNGColorStats* p) { + std::cout << "colored: " << (int)p->colored << ", "; + std::cout << "key: " << (int)p->key << ", "; + std::cout << "key_r: " << (int)p->key_r << ", "; + std::cout << "key_g: " << (int)p->key_g << ", "; + std::cout << "key_b: " << (int)p->key_b << ", "; + std::cout << "alpha: " << (int)p->alpha << ", "; + std::cout << "numcolors: " << (int)p->numcolors << ", "; + std::cout << "bits: " << (int)p->bits << std::endl; +}*/ + +/*Returns how many bits needed to represent given value (max 8 bit)*/ +static unsigned getValueRequiredBits(unsigned char value) { + if(value == 0 || value == 255) return 1; + /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ + if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; + return 8; +} + +/*stats must already have been inited. */ +unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, + const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* mode_in) { + size_t i; + ColorTree tree; + size_t numpixels = (size_t)w * (size_t)h; + unsigned error = 0; + + /* mark things as done already if it would be impossible to have a more expensive case */ + unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0; + unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1; + unsigned numcolors_done = 0; + unsigned bpp = lodepng_get_bpp(mode_in); + unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0; + unsigned sixteen = 0; /* whether the input image is 16 bit */ + unsigned maxnumcolors = 257; + if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp)); + + stats->numpixels += numpixels; + + /*if palette not allowed, no need to compute numcolors*/ + if(!stats->allow_palette) numcolors_done = 1; + + color_tree_init(&tree); + + /*If the stats was already filled in from previous data, fill its palette in tree + and mark things as done already if we know they are the most expensive case already*/ + if(stats->alpha) alpha_done = 1; + if(stats->colored) colored_done = 1; + if(stats->bits == 16) numcolors_done = 1; + if(stats->bits >= bpp) bits_done = 1; + if(stats->numcolors >= maxnumcolors) numcolors_done = 1; + + if(!numcolors_done) { + for(i = 0; i < stats->numcolors; i++) { + const unsigned char* color = &stats->palette[i * 4]; + error = color_tree_add(&tree, color[0], color[1], color[2], color[3], i); + if(error) goto cleanup; + } + } + + /*Check if the 16-bit input is truly 16-bit*/ + if(mode_in->bitdepth == 16 && !sixteen) { + unsigned short r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ { + stats->bits = 16; + sixteen = 1; + bits_done = 1; + numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ + break; + } + } + } + + if(sixteen) { + unsigned short r = 0, g = 0, b = 0, a = 0; + + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + + if(!colored_done && (r != g || r != b)) { + stats->colored = 1; + colored_done = 1; + } + + if(!alpha_done) { + unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); + if(a != 65535 && (a != 0 || (stats->key && !matchkey))) { + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } else if(a == 0 && !stats->alpha && !stats->key) { + stats->key = 1; + stats->key_r = r; + stats->key_g = g; + stats->key_b = b; + } else if(a == 65535 && stats->key && matchkey) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } + } + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(stats->key && !stats->alpha) { + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } + } + } + } else /* < 16-bit */ { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + + if(!bits_done && stats->bits < 8) { + /*only r is checked, < 8 bits is only relevant for grayscale*/ + unsigned bits = getValueRequiredBits(r); + if(bits > stats->bits) stats->bits = bits; + } + bits_done = (stats->bits >= bpp); + + if(!colored_done && (r != g || r != b)) { + stats->colored = 1; + colored_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ + } + + if(!alpha_done) { + unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); + if(a != 255 && (a != 0 || (stats->key && !matchkey))) { + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } else if(a == 0 && !stats->alpha && !stats->key) { + stats->key = 1; + stats->key_r = r; + stats->key_g = g; + stats->key_b = b; + } else if(a == 255 && stats->key && matchkey) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + + if(!numcolors_done) { + if(!color_tree_has(&tree, r, g, b, a)) { + error = color_tree_add(&tree, r, g, b, a, stats->numcolors); + if(error) goto cleanup; + if(stats->numcolors < 256) { + unsigned char* p = stats->palette; + unsigned n = stats->numcolors; + p[n * 4 + 0] = r; + p[n * 4 + 1] = g; + p[n * 4 + 2] = b; + p[n * 4 + 3] = a; + } + ++stats->numcolors; + numcolors_done = stats->numcolors >= maxnumcolors; + } + } + + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(stats->key && !stats->alpha) { + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + } + + /*make the stats's key always 16-bit for consistency - repeat each byte twice*/ + stats->key_r += (stats->key_r << 8); + stats->key_g += (stats->key_g << 8); + stats->key_b += (stats->key_b << 8); + } + +cleanup: + color_tree_cleanup(&tree); + return error; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit +(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for +all pixels of an image but only for a few additional values. */ +static unsigned lodepng_color_stats_add(LodePNGColorStats* stats, + unsigned r, unsigned g, unsigned b, unsigned a) { + unsigned error = 0; + unsigned char image[8]; + LodePNGColorMode mode; + lodepng_color_mode_init(&mode); + image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g; + image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a; + mode.bitdepth = 16; + mode.colortype = LCT_RGBA; + error = lodepng_compute_color_stats(stats, image, 1, 1, &mode); + lodepng_color_mode_cleanup(&mode); + return error; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Computes a minimal PNG color model that can contain all colors as indicated by the stats. +The stats should be computed with lodepng_compute_color_stats. +mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant. +Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image, +e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ... +This is used if auto_convert is enabled (it is by default). +*/ +static unsigned auto_choose_color(LodePNGColorMode* mode_out, + const LodePNGColorMode* mode_in, + const LodePNGColorStats* stats) { + unsigned error = 0; + unsigned palettebits; + size_t i, n; + size_t numpixels = stats->numpixels; + unsigned palette_ok, gray_ok; + + unsigned alpha = stats->alpha; + unsigned key = stats->key; + unsigned bits = stats->bits; + + mode_out->key_defined = 0; + + if(key && numpixels <= 16) { + alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + key = 0; + if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + + gray_ok = !stats->colored; + if(!stats->allow_greyscale) gray_ok = 0; + if(!gray_ok && bits < 8) bits = 8; + + n = stats->numcolors; + palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); + palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/ + if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/ + if(!stats->allow_palette) palette_ok = 0; + + if(palette_ok) { + const unsigned char* p = stats->palette; + lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ + for(i = 0; i != stats->numcolors; ++i) { + error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); + if(error) break; + } + + mode_out->colortype = LCT_PALETTE; + mode_out->bitdepth = palettebits; + + if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize + && mode_in->bitdepth == mode_out->bitdepth) { + /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ + lodepng_color_mode_cleanup(mode_out); + lodepng_color_mode_copy(mode_out, mode_in); + } + } else /*8-bit or 16-bit per channel*/ { + mode_out->bitdepth = bits; + mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA) + : (gray_ok ? LCT_GREY : LCT_RGB); + if(key) { + unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/ + mode_out->key_r = stats->key_r & mask; + mode_out->key_g = stats->key_g & mask; + mode_out->key_b = stats->key_b & mask; + mode_out->key_defined = 1; + } + } + + return error; +} + +#endif /* #ifdef LODEPNG_COMPILE_ENCODER */ + +/* +Paeth predictor, used by PNG filter type 4 +The parameters are of type short, but should come from unsigned chars, the shorts +are only needed to make the paeth calculation correct. +*/ +static unsigned char paethPredictor(short a, short b, short c) { + short pa = LODEPNG_ABS(b - c); + short pb = LODEPNG_ABS(a - c); + short pc = LODEPNG_ABS(a + b - c - c); + /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */ + if(pb < pa) { a = b; pa = pb; } + return (pc < pa) ? c : a; +} + +/*shared values used by multiple Adam7 related functions*/ + +static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ +static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ +static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ +static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ + +/* +Outputs various dimensions and positions in the image related to the Adam7 reduced images. +passw: output containing the width of the 7 passes +passh: output containing the height of the 7 passes +filter_passstart: output containing the index of the start and end of each + reduced image with filter bytes +padded_passstart output containing the index of the start and end of each + reduced image when without filter bytes but with padded scanlines +passstart: output containing the index of the start and end of each reduced + image without padding between scanlines, but still padding between the images +w, h: width and height of non-interlaced image +bpp: bits per pixel +"padded" is only relevant if bpp is less than 8 and a scanline or image does not + end at a full byte +*/ +static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], + size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { + /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ + unsigned i; + + /*calculate width and height in pixels of each pass*/ + for(i = 0; i != 7; ++i) { + passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; + passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; + if(passw[i] == 0) passh[i] = 0; + if(passh[i] == 0) passw[i] = 0; + } + + filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; + for(i = 0; i != 7; ++i) { + /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ + filter_passstart[i + 1] = filter_passstart[i] + + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0); + /*bits padded if needed to fill full byte at end of each scanline*/ + padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u); + /*only padded at end of reduced image*/ + passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u; + } +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Decoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*read the information from the header and store it in the LodePNGInfo. return value is error*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, + const unsigned char* in, size_t insize) { + unsigned width, height; + LodePNGInfo* info = &state->info_png; + if(insize == 0 || in == 0) { + CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ + } + if(insize < 33) { + CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ + } + + /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ + /* TODO: remove this. One should use a new LodePNGState for new sessions */ + lodepng_info_cleanup(info); + lodepng_info_init(info); + + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { + CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ + } + if(lodepng_chunk_length(in + 8) != 13) { + CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ + } + if(!lodepng_chunk_type_equals(in + 8, "IHDR")) { + CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ + } + + /*read the values given in the header*/ + width = lodepng_read32bitInt(&in[16]); + height = lodepng_read32bitInt(&in[20]); + /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/ + if(w) *w = width; + if(h) *h = height; + info->color.bitdepth = in[24]; + info->color.colortype = (LodePNGColorType)in[25]; + info->compression_method = in[26]; + info->filter_method = in[27]; + info->interlace_method = in[28]; + + /*errors returned only after the parsing so other values are still output*/ + + /*error: invalid image size*/ + if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93); + /*error: invalid colortype or bitdepth combination*/ + state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); + if(state->error) return state->error; + /*error: only compression method 0 is allowed in the specification*/ + if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); + /*error: only filter method 0 is allowed in the specification*/ + if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); + /*error: only interlace methods 0 and 1 exist in the specification*/ + if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); + + if(!state->decoder.ignore_crc) { + unsigned CRC = lodepng_read32bitInt(&in[29]); + unsigned checksum = lodepng_crc32(&in[12], 17); + if(CRC != checksum) { + CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ + } + } + + return state->error; +} + +static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, + size_t bytewidth, unsigned char filterType, size_t length) { + /* + For PNG filter method 0 + unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, + the filter works byte per byte (bytewidth = 1) + precon is the previous unfiltered scanline, recon the result, scanline the current one + the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead + recon and scanline MAY be the same memory address! precon must be disjoint. + */ + + size_t i; + switch(filterType) { + case 0: + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + break; + case 1: + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; + break; + case 2: + if(precon) { + for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; + } else { + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + } + break; + case 3: + if(precon) { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u); + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1u); + } else { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1u); + } + break; + case 4: + if(precon) { + for(i = 0; i != bytewidth; ++i) { + recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ + } + + /* Unroll independent paths of the paeth predictor. A 6x and 8x version would also be possible but that + adds too much code. Whether this actually speeds anything up at all depends on compiler and settings. */ + if(bytewidth >= 4) { + for(; i + 3 < length; i += 4) { + size_t j = i - bytewidth; + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3]; + unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2], q3 = precon[j + 3]; + recon[i + 0] = s0 + paethPredictor(r0, p0, q0); + recon[i + 1] = s1 + paethPredictor(r1, p1, q1); + recon[i + 2] = s2 + paethPredictor(r2, p2, q2); + recon[i + 3] = s3 + paethPredictor(r3, p3, q3); + } + } else if(bytewidth >= 3) { + for(; i + 2 < length; i += 3) { + size_t j = i - bytewidth; + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2]; + unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2]; + recon[i + 0] = s0 + paethPredictor(r0, p0, q0); + recon[i + 1] = s1 + paethPredictor(r1, p1, q1); + recon[i + 2] = s2 + paethPredictor(r2, p2, q2); + } + } else if(bytewidth >= 2) { + for(; i + 1 < length; i += 2) { + size_t j = i - bytewidth; + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1]; + unsigned char q0 = precon[j + 0], q1 = precon[j + 1]; + recon[i + 0] = s0 + paethPredictor(r0, p0, q0); + recon[i + 1] = s1 + paethPredictor(r1, p1, q1); + } + } + + for(; i != length; ++i) { + recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); + } + } else { + for(i = 0; i != bytewidth; ++i) { + recon[i] = scanline[i]; + } + for(i = bytewidth; i < length; ++i) { + /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ + recon[i] = (scanline[i] + recon[i - bytewidth]); + } + } + break; + default: return 36; /*error: invalid filter type given*/ + } + return 0; +} + +static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + /* + For PNG filter method 0 + this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) + out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline + w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel + in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) + */ + + unsigned y; + unsigned char* prevline = 0; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7u) / 8u; + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; + + for(y = 0; y < h; ++y) { + size_t outindex = linebytes * y; + size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + unsigned char filterType = in[inindex]; + + CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); + + prevline = &out[outindex]; + } + + return 0; +} + +/* +in: Adam7 interlaced image, with no padding bits between scanlines, but between + reduced images so that each reduced image starts at a byte. +out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h +bpp: bits per pixel +out has the following size in bits: w * h * bpp. +in is possibly bigger due to padding bits between reduced images. +out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation +(because that's likely a little bit faster) +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + size_t bytewidth = bpp / 8u; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; + size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w + + ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth; + for(b = 0; b < bytewidth; ++b) { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp; + for(b = 0; b < bpp; ++b) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +static void removePaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) { + /* + After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need + to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers + for the Adam7 code, the color convert code and the output to the user. + in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must + have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits + also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 + only useful if (ilinebits - olinebits) is a value in the range 1..7 + */ + unsigned y; + size_t diff = ilinebits - olinebits; + size_t ibp = 0, obp = 0; /*input and output bit pointers*/ + for(y = 0; y < h; ++y) { + size_t x; + for(x = 0; x < olinebits; ++x) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + ibp += diff; + } +} + +/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from +the IDAT chunks (with filter index bytes and possible padding bits) +return value is error*/ +static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, + unsigned w, unsigned h, const LodePNGInfo* info_png) { + /* + This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. + Steps: + *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8) + *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace + NOTE: the in buffer will be overwritten with intermediate data! + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + if(bpp == 0) return 31; /*error: invalid colortype*/ + + if(info_png->interlace_method == 0) { + if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) { + CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); + removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h); + } + /*we can immediately filter into the out buffer, no other steps needed*/ + else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); + } else /*interlace_method is 1 (Adam7)*/ { + unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + for(i = 0; i != 7; ++i) { + CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); + /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, + move bytes instead of bits or move not at all*/ + if(bpp < 8) { + /*remove padding bits in scanlines; after this there still may be padding + bits between the different reduced images: each reduced image still starts nicely at a byte*/ + removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, + ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]); + } + } + + Adam7_deinterlace(out, in, w, h, bpp); + } + + return 0; +} + +static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { + unsigned pos = 0, i; + color->palettesize = chunkLength / 3u; + if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/ + lodepng_color_mode_alloc_palette(color); + if(!color->palette && color->palettesize) { + color->palettesize = 0; + return 83; /*alloc fail*/ + } + + for(i = 0; i != color->palettesize; ++i) { + color->palette[4 * i + 0] = data[pos++]; /*R*/ + color->palette[4 * i + 1] = data[pos++]; /*G*/ + color->palette[4 * i + 2] = data[pos++]; /*B*/ + color->palette[4 * i + 3] = 255; /*alpha*/ + } + + return 0; /* OK */ +} + +static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { + unsigned i; + if(color->colortype == LCT_PALETTE) { + /*error: more alpha values given than there are palette entries*/ + if(chunkLength > color->palettesize) return 39; + + for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; + } else if(color->colortype == LCT_GREY) { + /*error: this chunk must be 2 bytes for grayscale image*/ + if(chunkLength != 2) return 30; + + color->key_defined = 1; + color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; + } else if(color->colortype == LCT_RGB) { + /*error: this chunk must be 6 bytes for RGB image*/ + if(chunkLength != 6) return 41; + + color->key_defined = 1; + color->key_r = 256u * data[0] + data[1]; + color->key_g = 256u * data[2] + data[3]; + color->key_b = 256u * data[4] + data[5]; + } + else return 42; /*error: tRNS chunk not allowed for other color models*/ + + return 0; /* OK */ +} + + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*background color chunk (bKGD)*/ +static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(info->color.colortype == LCT_PALETTE) { + /*error: this chunk must be 1 byte for indexed color image*/ + if(chunkLength != 1) return 43; + + /*error: invalid palette index, or maybe this chunk appeared before PLTE*/ + if(data[0] >= info->color.palettesize) return 103; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = data[0]; + } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { + /*error: this chunk must be 2 bytes for grayscale image*/ + if(chunkLength != 2) return 44; + + /*the values are truncated to bitdepth in the PNG file*/ + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { + /*error: this chunk must be 6 bytes for grayscale image*/ + if(chunkLength != 6) return 45; + + /*the values are truncated to bitdepth in the PNG file*/ + info->background_defined = 1; + info->background_r = 256u * data[0] + data[1]; + info->background_g = 256u * data[2] + data[3]; + info->background_b = 256u * data[4] + data[5]; + } + + return 0; /* OK */ +} + +/*text chunk (tEXt)*/ +static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + char *key = 0, *str = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + unsigned length, string2_begin; + + length = 0; + while(length < chunkLength && data[length] != 0) ++length; + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + string2_begin = length + 1; /*skip keyword null terminator*/ + + length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin); + str = (char*)lodepng_malloc(length + 1); + if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(str, data + string2_begin, length); + str[length] = 0; + + error = lodepng_add_text(info, key, str); + + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*compressed text chunk (zTXt)*/ +static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + + unsigned length, string2_begin; + char *key = 0; + unsigned char* str = 0; + size_t size = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + + length = (unsigned)chunkLength - string2_begin; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&str, &size, 0, &data[string2_begin], + length, zlibsettings); + if(error) break; + error = lodepng_add_text_sized(info, key, (char*)str, size); + + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*international text chunk (iTXt)*/ +static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + unsigned i; + + unsigned length, begin, compressed; + char *key = 0, *langtag = 0, *transkey = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + /*Quick check if the chunk length isn't too small. Even without check + it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ + if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ + + /*read the key*/ + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + /*read the compression method*/ + compressed = data[length + 1]; + if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty for the next 3 texts*/ + + /*read the langtag*/ + begin = length + 3; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + langtag = (char*)lodepng_malloc(length + 1); + if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(langtag, data + begin, length); + langtag[length] = 0; + + /*read the transkey*/ + begin += length + 1; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + transkey = (char*)lodepng_malloc(length + 1); + if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(transkey, data + begin, length); + transkey[length] = 0; + + /*read the actual text*/ + begin += length + 1; + + length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; + + if(compressed) { + unsigned char* str = 0; + size_t size = 0; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&str, &size, 0, &data[begin], + length, zlibsettings); + if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)str, size); + lodepng_free(str); + } else { + error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)(data + begin), length); + } + + break; + } + + lodepng_free(key); + lodepng_free(langtag); + lodepng_free(transkey); + + return error; +} + +static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ + + info->time_defined = 1; + info->time.year = 256u * data[0] + data[1]; + info->time.month = data[2]; + info->time.day = data[3]; + info->time.hour = data[4]; + info->time.minute = data[5]; + info->time.second = data[6]; + + return 0; /* OK */ +} + +static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ + + info->phys_defined = 1; + info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + info->phys_unit = data[8]; + + return 0; /* OK */ +} + +static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/ + + info->gama_defined = 1; + info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + + return 0; /* OK */ +} + +static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/ + + info->chrm_defined = 1; + info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3]; + info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7]; + info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11]; + info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15]; + info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19]; + info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23]; + info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27]; + info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31]; + + return 0; /* OK */ +} + +static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/ + + info->srgb_defined = 1; + info->srgb_intent = data[0]; + + return 0; /* OK */ +} + +static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + unsigned i; + size_t size = 0; + + unsigned length, string2_begin; + + info->iccp_defined = 1; + if(info->iccp_name) lodepng_clear_icc(info); + + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/ + if(length < 1 || length > 79) return 89; /*keyword too short or long*/ + + info->iccp_name = (char*)lodepng_malloc(length + 1); + if(!info->iccp_name) return 83; /*alloc fail*/ + + info->iccp_name[length] = 0; + for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i]; + + if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/ + + length = (unsigned)chunkLength - string2_begin; + error = zlib_decompress(&info->iccp_profile, &size, 0, + &data[string2_begin], + length, zlibsettings); + info->iccp_profile_size = size; + if(!error && !info->iccp_profile_size) error = 100; /*invalid ICC profile size*/ + return error; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, + const unsigned char* in, size_t insize) { + const unsigned char* chunk = in + pos; + unsigned chunkLength; + const unsigned char* data; + unsigned unhandled = 0; + unsigned error = 0; + + if(pos + 4 > insize) return 30; + chunkLength = lodepng_chunk_length(chunk); + if(chunkLength > 2147483647) return 63; + data = lodepng_chunk_data_const(chunk); + if(data + chunkLength + 4 > in + insize) return 30; + + if(lodepng_chunk_type_equals(chunk, "PLTE")) { + error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { + error = readChunk_tRNS(&state->info_png.color, data, chunkLength); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { + error = readChunk_bKGD(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { + error = readChunk_tEXt(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { + error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { + error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { + error = readChunk_tIME(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { + error = readChunk_pHYs(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { + error = readChunk_gAMA(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { + error = readChunk_cHRM(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { + error = readChunk_sRGB(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { + error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else { + /* unhandled chunk is ok (is not an error) */ + unhandled = 1; + } + + if(!error && !unhandled && !state->decoder.ignore_crc) { + if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/ + } + + return error; +} + +/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ +static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) { + unsigned char IEND = 0; + const unsigned char* chunk; + unsigned char* idat; /*the data from idat chunks, zlib compressed*/ + size_t idatsize = 0; + unsigned char* scanlines = 0; + size_t scanlines_size = 0, expected_size = 0; + size_t outsize = 0; + + /*for unknown chunk order*/ + unsigned unknown = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + + + /* safe output values in case error happens */ + *out = 0; + *w = *h = 0; + + state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ + if(state->error) return; + + if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) { + CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ + } + + /*the input filesize is a safe upper bound for the sum of idat chunks size*/ + idat = (unsigned char*)lodepng_malloc(insize); + if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/ + + chunk = &in[33]; /*first byte of the first chunk after the header*/ + + /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + IDAT data is put at the start of the in buffer*/ + while(!IEND && !state->error) { + unsigned chunkLength; + const unsigned char* data; /*the data in the chunk*/ + + /*error: size of the in buffer too small to contain next chunk*/ + if((size_t)((chunk - in) + 12) > insize || chunk < in) { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 30); + } + + /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ + chunkLength = lodepng_chunk_length(chunk); + /*error: chunk length larger than the max PNG chunk size*/ + if(chunkLength > 2147483647) { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 63); + } + + if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) { + CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ + } + + data = lodepng_chunk_data_const(chunk); + + unknown = 0; + + /*IDAT chunk, containing compressed image data*/ + if(lodepng_chunk_type_equals(chunk, "IDAT")) { + size_t newsize; + if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); + if(newsize > insize) CERROR_BREAK(state->error, 95); + lodepng_memcpy(idat + idatsize, data, chunkLength); + idatsize += chunkLength; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 3; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else if(lodepng_chunk_type_equals(chunk, "IEND")) { + /*IEND chunk*/ + IEND = 1; + } else if(lodepng_chunk_type_equals(chunk, "PLTE")) { + /*palette chunk (PLTE)*/ + state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 2; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { + /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled + in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that + affects the alpha channel of pixels. */ + state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*background color chunk (bKGD)*/ + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { + state->error = readChunk_bKGD(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { + /*text chunk (tEXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_tEXt(&state->info_png, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { + /*compressed text chunk (zTXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { + /*international text chunk (iTXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { + state->error = readChunk_tIME(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { + state->error = readChunk_pHYs(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { + state->error = readChunk_gAMA(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { + state->error = readChunk_cHRM(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { + state->error = readChunk_sRGB(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { + state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { + /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ + if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) { + CERROR_BREAK(state->error, 69); + } + + unknown = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(state->decoder.remember_unknown_chunks) { + state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], + &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ { + if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ + } + + if(!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize); + } + + if(state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) { + state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */ + } + + if(!state->error) { + /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. + If the decompressed size does not match the prediction, the image must be corrupt.*/ + if(state->info_png.interlace_method == 0) { + size_t bpp = lodepng_get_bpp(&state->info_png.color); + expected_size = lodepng_get_raw_size_idat(*w, *h, bpp); + } else { + size_t bpp = lodepng_get_bpp(&state->info_png.color); + /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/ + expected_size = 0; + expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp); + if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp); + if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp); + if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp); + } + + state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings); + } + if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/ + lodepng_free(idat); + + if(!state->error) { + outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!*out) state->error = 83; /*alloc fail*/ + } + if(!state->error) { + lodepng_memset(*out, 0, outsize); + state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png); + } + lodepng_free(scanlines); +} + +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) { + *out = 0; + decodeGeneric(out, w, h, state, in, insize); + if(state->error) return state->error; + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) { + /*same color type, no copying or converting of data needed*/ + /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype + the raw image has to the end user*/ + if(!state->decoder.color_convert) { + state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); + if(state->error) return state->error; + } + } else { /*color conversion needed*/ + unsigned char* data = *out; + size_t outsize; + + /*TODO: check if this works according to the statement in the documentation: "The converter can convert + from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/ + if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) + && !(state->info_raw.bitdepth == 8)) { + return 56; /*unsupported color mode conversion*/ + } + + outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!(*out)) { + state->error = 83; /*alloc fail*/ + } + else state->error = lodepng_convert(*out, data, &state->info_raw, + &state->info_png.color, *w, *h); + lodepng_free(data); + } + return state->error; +} + +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + error = lodepng_decode(out, w, h, &state, in, insize); + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); +} + +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer = 0; + size_t buffersize; + unsigned error; + /* safe output values in case error happens */ + *out = 0; + *w = *h = 0; + error = lodepng_load_file(&buffer, &buffersize, filename); + if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { + return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); +} + +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { + return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { + settings->color_convert = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->read_text_chunks = 1; + settings->remember_unknown_chunks = 0; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + settings->ignore_crc = 0; + settings->ignore_critical = 0; + settings->ignore_end = 0; + lodepng_decompress_settings_init(&settings->zlibsettings); +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) + +void lodepng_state_init(LodePNGState* state) { +#ifdef LODEPNG_COMPILE_DECODER + lodepng_decoder_settings_init(&state->decoder); +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + lodepng_encoder_settings_init(&state->encoder); +#endif /*LODEPNG_COMPILE_ENCODER*/ + lodepng_color_mode_init(&state->info_raw); + lodepng_info_init(&state->info_png); + state->error = 1; +} + +void lodepng_state_cleanup(LodePNGState* state) { + lodepng_color_mode_cleanup(&state->info_raw); + lodepng_info_cleanup(&state->info_png); +} + +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { + lodepng_state_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->info_raw); + lodepng_info_init(&dest->info_png); + dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; + dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; +} + +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Encoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + + +static unsigned writeSignature(ucvector* out) { + size_t pos = out->size; + const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10}; + /*8 bytes PNG signature, aka the magic bytes*/ + if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/ + lodepng_memcpy(out->data + pos, signature, 8); + return 0; +} + +static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { + unsigned char *chunk, *data; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR")); + data = chunk + 8; + + lodepng_set32bitInt(data + 0, w); /*width*/ + lodepng_set32bitInt(data + 4, h); /*height*/ + data[8] = (unsigned char)bitdepth; /*bit depth*/ + data[9] = (unsigned char)colortype; /*color type*/ + data[10] = 0; /*compression method*/ + data[11] = 0; /*filter method*/ + data[12] = interlace_method; /*interlace method*/ + + lodepng_chunk_generate_crc(chunk); + return 0; +} + +/* only adds the chunk if needed (there is a key or palette with alpha) */ +static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { + unsigned char* chunk; + size_t i, j = 8; + + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE")); + + for(i = 0; i != info->palettesize; ++i) { + /*add all channels except alpha channel*/ + chunk[j++] = info->palette[i * 4 + 0]; + chunk[j++] = info->palette[i * 4 + 1]; + chunk[j++] = info->palette[i * 4 + 2]; + } + + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { + unsigned char* chunk = 0; + + if(info->colortype == LCT_PALETTE) { + size_t i, amount = info->palettesize; + /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ + for(i = info->palettesize; i != 0; --i) { + if(info->palette[4 * (i - 1) + 3] != 255) break; + --amount; + } + if(amount) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS")); + /*add the alpha channel values from the palette*/ + for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3]; + } + } else if(info->colortype == LCT_GREY) { + if(info->key_defined) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS")); + chunk[8] = (unsigned char)(info->key_r >> 8); + chunk[9] = (unsigned char)(info->key_r & 255); + } + } else if(info->colortype == LCT_RGB) { + if(info->key_defined) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS")); + chunk[8] = (unsigned char)(info->key_r >> 8); + chunk[9] = (unsigned char)(info->key_r & 255); + chunk[10] = (unsigned char)(info->key_g >> 8); + chunk[11] = (unsigned char)(info->key_g & 255); + chunk[12] = (unsigned char)(info->key_b >> 8); + chunk[13] = (unsigned char)(info->key_b & 255); + } + } + + if(chunk) lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, + LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* zlib = 0; + size_t zlibsize = 0; + + error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings); + if(!error) { + error = lodepng_chunk_createv(out, zlibsize, "IDAT", zlib); + } + lodepng_free(zlib); + return error; +} + +static unsigned addChunk_IEND(ucvector* out) { + return lodepng_chunk_createv(out, 0, "IEND", 0); +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { + unsigned char* chunk = 0; + size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring); + size_t size = keysize + 1 + textsize; + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt")); + lodepng_memcpy(chunk + 8, keyword, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + lodepng_memcpy(chunk + 9 + keysize, textstring, textsize); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, + LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t textsize = lodepng_strlen(textstring); + size_t keysize = lodepng_strlen(keyword); + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + + error = zlib_compress(&compressed, &compressedsize, + (const unsigned char*)textstring, textsize, zlibsettings); + if(!error) { + size_t size = keysize + 2 + compressedsize; + error = lodepng_chunk_init(&chunk, out, size, "zTXt"); + } + if(!error) { + lodepng_memcpy(chunk + 8, keyword, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + chunk[9 + keysize] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +static unsigned addChunk_iTXt(ucvector* out, unsigned compress, const char* keyword, const char* langtag, + const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t textsize = lodepng_strlen(textstring); + size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey); + + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + + if(compress) { + error = zlib_compress(&compressed, &compressedsize, + (const unsigned char*)textstring, textsize, zlibsettings); + } + if(!error) { + size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize); + error = lodepng_chunk_init(&chunk, out, size, "iTXt"); + } + if(!error) { + size_t pos = 8; + lodepng_memcpy(chunk + pos, keyword, keysize); + pos += keysize; + chunk[pos++] = 0; /*null termination char*/ + chunk[pos++] = (compress ? 1 : 0); /*compression flag*/ + chunk[pos++] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + pos, langtag, langsize); + pos += langsize; + chunk[pos++] = 0; /*null termination char*/ + lodepng_memcpy(chunk + pos, transkey, transsize); + pos += transsize; + chunk[pos++] = 0; /*null termination char*/ + if(compress) { + lodepng_memcpy(chunk + pos, compressed, compressedsize); + } else { + lodepng_memcpy(chunk + pos, textstring, textsize); + } + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk = 0; + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD")); + chunk[8] = (unsigned char)(info->background_r >> 8); + chunk[9] = (unsigned char)(info->background_r & 255); + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD")); + chunk[8] = (unsigned char)(info->background_r >> 8); + chunk[9] = (unsigned char)(info->background_r & 255); + chunk[10] = (unsigned char)(info->background_g >> 8); + chunk[11] = (unsigned char)(info->background_g & 255); + chunk[12] = (unsigned char)(info->background_b >> 8); + chunk[13] = (unsigned char)(info->background_b & 255); + } else if(info->color.colortype == LCT_PALETTE) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD")); + chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/ + } + if(chunk) lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME")); + chunk[8] = (unsigned char)(time->year >> 8); + chunk[9] = (unsigned char)(time->year & 255); + chunk[10] = (unsigned char)time->month; + chunk[11] = (unsigned char)time->day; + chunk[12] = (unsigned char)time->hour; + chunk[13] = (unsigned char)time->minute; + chunk[14] = (unsigned char)time->second; + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs")); + lodepng_set32bitInt(chunk + 8, info->phys_x); + lodepng_set32bitInt(chunk + 12, info->phys_y); + chunk[16] = info->phys_unit; + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA")); + lodepng_set32bitInt(chunk + 8, info->gama_gamma); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM")); + lodepng_set32bitInt(chunk + 8, info->chrm_white_x); + lodepng_set32bitInt(chunk + 12, info->chrm_white_y); + lodepng_set32bitInt(chunk + 16, info->chrm_red_x); + lodepng_set32bitInt(chunk + 20, info->chrm_red_y); + lodepng_set32bitInt(chunk + 24, info->chrm_green_x); + lodepng_set32bitInt(chunk + 28, info->chrm_green_y); + lodepng_set32bitInt(chunk + 32, info->chrm_blue_x); + lodepng_set32bitInt(chunk + 36, info->chrm_blue_y); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) { + unsigned char data = info->srgb_intent; + return lodepng_chunk_createv(out, 1, "sRGB", &data); +} + +static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t keysize = lodepng_strlen(info->iccp_name); + + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + error = zlib_compress(&compressed, &compressedsize, + info->iccp_profile, info->iccp_profile_size, zlibsettings); + if(!error) { + size_t size = keysize + 2 + compressedsize; + error = lodepng_chunk_init(&chunk, out, size, "iCCP"); + } + if(!error) { + lodepng_memcpy(chunk + 8, info->iccp_name, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + chunk[9 + keysize] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, + size_t length, size_t bytewidth, unsigned char filterType) { + size_t i; + switch(filterType) { + case 0: /*None*/ + for(i = 0; i != length; ++i) out[i] = scanline[i]; + break; + case 1: /*Sub*/ + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; + break; + case 2: /*Up*/ + if(prevline) { + for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; + } else { + for(i = 0; i != length; ++i) out[i] = scanline[i]; + } + break; + case 3: /*Average*/ + if(prevline) { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); + } else { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); + } + break; + case 4: /*Paeth*/ + if(prevline) { + /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ + for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); + for(i = bytewidth; i < length; ++i) { + out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); + } + } else { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ + for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); + } + break; + default: return; /*invalid filter type given*/ + } +} + +/* integer binary logarithm, max return value is 31 */ +static size_t ilog2(size_t i) { + size_t result = 0; + if(i >= 65536) { result += 16; i >>= 16; } + if(i >= 256) { result += 8; i >>= 8; } + if(i >= 16) { result += 4; i >>= 4; } + if(i >= 4) { result += 2; i >>= 2; } + if(i >= 2) { result += 1; /*i >>= 1;*/ } + return result; +} + +/* integer approximation for i * log2(i), helper function for LFS_ENTROPY */ +static size_t ilog2i(size_t i) { + size_t l; + if(i == 0) return 0; + l = ilog2(i); + /* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u) + linearly approximates the missing fractional part multiplied by i */ + return i * l + ((i - (1u << l)) << 1u); +} + +static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* color, const LodePNGEncoderSettings* settings) { + /* + For PNG filter method 0 + out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are + the scanlines with 1 extra byte per scanline + */ + + unsigned bpp = lodepng_get_bpp(color); + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7u) / 8u; + const unsigned char* prevline = 0; + unsigned x, y; + unsigned error = 0; + LodePNGFilterStrategy strategy = settings->filter_strategy; + + /* + There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: + * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. + use fixed filtering, with the filter None). + * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is + not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply + all five filters and select the filter that produces the smallest sum of absolute values per row. + This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. + + If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, + but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum + heuristic is used. + */ + if(settings->filter_palette_zero && + (color->colortype == LCT_PALETTE || color->bitdepth < 8)) strategy = LFS_ZERO; + + if(bpp == 0) return 31; /*error: invalid color type*/ + + if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) { + unsigned char type = (unsigned char)strategy; + for(y = 0; y != h; ++y) { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } else if(strategy == LFS_MINSUM) { + /*adaptive filtering*/ + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned char type, bestType = 0; + + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + + if(!error) { + for(y = 0; y != h; ++y) { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) { + size_t sum = 0; + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + + /*calculate the sum of the result*/ + if(type == 0) { + for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]); + } else { + for(x = 0; x != linebytes; ++x) { + /*For differences, each byte should be treated as signed, values above 127 are negative + (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. + This means filtertype 0 is almost never chosen, but that is justified.*/ + unsigned char s = attempt[type][x]; + sum += s < 128 ? s : (255U - s); + } + } + + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum < smallest) { + bestType = type; + smallest = sum; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } else if(strategy == LFS_ENTROPY) { + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t bestSum = 0; + unsigned type, bestType = 0; + unsigned count[256]; + + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + + if(!error) { + for(y = 0; y != h; ++y) { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) { + size_t sum = 0; + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + lodepng_memset(count, 0, 256 * sizeof(*count)); + for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; + ++count[type]; /*the filter type itself is part of the scanline*/ + for(x = 0; x != 256; ++x) { + sum += ilog2i(count[x]); + } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum > bestSum) { + bestType = type; + bestSum = sum; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } else if(strategy == LFS_PREDEFINED) { + for(y = 0; y != h; ++y) { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + unsigned char type = settings->predefined_filters[y]; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } else if(strategy == LFS_BRUTE_FORCE) { + /*brute force filter chooser. + deflate the scanline after every filter attempt to see which one deflates best. + This is very slow and gives only slightly smaller, sometimes even larger, result*/ + size_t size[5]; + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned type = 0, bestType = 0; + unsigned char* dummy; + LodePNGCompressSettings zlibsettings; + lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings)); + /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, + to simulate the true case where the tree is the same for the whole image. Sometimes it gives + better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare + cases better compression. It does make this a bit less slow, so it's worth doing this.*/ + zlibsettings.btype = 1; + /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG + images only, so disable it*/ + zlibsettings.custom_zlib = 0; + zlibsettings.custom_deflate = 0; + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + if(!error) { + for(y = 0; y != h; ++y) /*try the 5 filter types*/ { + for(type = 0; type != 5; ++type) { + unsigned testsize = (unsigned)linebytes; + /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ + + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + size[type] = 0; + dummy = 0; + zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); + lodepng_free(dummy); + /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || size[type] < smallest) { + bestType = type; + smallest = size[type]; + } + } + prevline = &in[y * linebytes]; + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else return 88; /* unknown filter strategy */ + + return error; +} + +static void addPaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) { + /*The opposite of the removePaddingBits function + olinebits must be >= ilinebits*/ + unsigned y; + size_t diff = olinebits - ilinebits; + size_t obp = 0, ibp = 0; /*bit pointers*/ + for(y = 0; y != h; ++y) { + size_t x; + for(x = 0; x < ilinebits; ++x) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + /*obp += diff; --> no, fill in some value in the padding bits too, to avoid + "Use of uninitialised value of size ###" warning from valgrind*/ + for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); + } +} + +/* +in: non-interlaced image with size w*h +out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with + no padding bits between scanlines, but between reduced images so that each + reduced image starts at a byte. +bpp: bits per pixel +there are no padding bits, not between scanlines, not between reduced images +in has the following size in bits: w * h * bpp. +out is possibly bigger due to padding bits between reduced images +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + size_t bytewidth = bpp / 8u; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; + for(b = 0; b < bytewidth; ++b) { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + for(b = 0; b < bpp; ++b) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. +return value is error**/ +static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { + /* + This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: + *) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter + *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + unsigned error = 0; + + if(info_png->interlace_method == 0) { + *outsize = h + (h * ((w * bpp + 7u) / 8u)); /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ + + if(!error) { + /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ + if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) { + unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u)); + if(!padded) error = 83; /*alloc fail*/ + if(!error) { + addPaddingBits(padded, in, ((w * bpp + 7u) / 8u) * 8u, w * bpp, h); + error = filter(*out, padded, w, h, &info_png->color, settings); + } + lodepng_free(padded); + } else { + /*we can immediately filter into the out buffer, no other steps needed*/ + error = filter(*out, in, w, h, &info_png->color, settings); + } + } + } else /*interlace_method is 1 (Adam7)*/ { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned char* adam7; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out)) error = 83; /*alloc fail*/ + + adam7 = (unsigned char*)lodepng_malloc(passstart[7]); + if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ + + if(!error) { + unsigned i; + + Adam7_interlace(adam7, in, w, h, bpp); + for(i = 0; i != 7; ++i) { + if(bpp < 8) { + unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); + if(!padded) ERROR_BREAK(83); /*alloc fail*/ + addPaddingBits(padded, &adam7[passstart[i]], + ((passw[i] * bpp + 7u) / 8u) * 8u, passw[i] * bpp, passh[i]); + error = filter(&(*out)[filter_passstart[i]], padded, + passw[i], passh[i], &info_png->color, settings); + lodepng_free(padded); + } else { + error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], + passw[i], passh[i], &info_png->color, settings); + } + + if(error) break; + } + } + + lodepng_free(adam7); + } + + return error; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) { + unsigned char* inchunk = data; + while((size_t)(inchunk - data) < datasize) { + CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); + out->allocsize = out->size; /*fix the allocsize again*/ + inchunk = lodepng_chunk_next(inchunk, data + datasize); + } + return 0; +} + +static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) { + /* + It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19 + are "RGB ". We do not perform any full parsing of the ICC profile here, other + than check those 4 bytes to grayscale profile. Other than that, validity of + the profile is not checked. This is needed only because the PNG specification + requires using a non-gray color model if there is an ICC profile with "RGB " + (sadly limiting compression opportunities if the input data is grayscale RGB + data), and requires using a gray color model if it is "GRAY". + */ + if(size < 20) return 0; + return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y'; +} + +static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) { + /* See comment in isGrayICCProfile*/ + if(size < 20) return 0; + return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' '; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state) { + unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ + size_t datasize = 0; + ucvector outv = ucvector_init(NULL, 0); + LodePNGInfo info; + const LodePNGInfo* info_png = &state->info_png; + + lodepng_info_init(&info); + + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + state->error = 0; + + /*check input values validity*/ + if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) { + state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ + goto cleanup; + } + if(state->encoder.zlibsettings.btype > 2) { + state->error = 61; /*error: invalid btype*/ + goto cleanup; + } + if(info_png->interlace_method > 1) { + state->error = 71; /*error: invalid interlace mode*/ + goto cleanup; + } + state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth); + if(state->error) goto cleanup; /*error: invalid color type given*/ + state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); + if(state->error) goto cleanup; /*error: invalid color type given*/ + + /* color convert and compute scanline filter types */ + lodepng_info_copy(&info, &state->info_png); + if(state->encoder.auto_convert) { + LodePNGColorStats stats; + lodepng_color_stats_init(&stats); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->iccp_defined && + isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { + /*the PNG specification does not allow to use palette with a GRAY ICC profile, even + if the palette has only gray colors, so disallow it.*/ + stats.allow_palette = 0; + } + if(info_png->iccp_defined && + isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { + /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/ + stats.allow_greyscale = 0; + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->background_defined) { + /*the background chunk's color must be taken into account as well*/ + unsigned r = 0, g = 0, b = 0; + LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16); + lodepng_convert_rgb(&r, &g, &b, info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color); + state->error = lodepng_color_stats_add(&stats, r, g, b, 65535); + if(state->error) goto cleanup; + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + state->error = auto_choose_color(&info.color, &state->info_raw, &stats); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*also convert the background chunk*/ + if(info_png->background_defined) { + if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b, + info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) { + state->error = 104; + goto cleanup; + } + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->iccp_defined) { + unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); + unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); + unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA; + if(!gray_icc && !rgb_icc) { + state->error = 100; /* Disallowed profile color type for PNG */ + goto cleanup; + } + if(gray_icc != gray_png) { + /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa, + or in case of auto_convert, it wasn't possible to find appropriate model*/ + state->error = state->encoder.auto_convert ? 102 : 101; + goto cleanup; + } + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { + unsigned char* converted; + size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u; + + converted = (unsigned char*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + lodepng_free(converted); + if(state->error) goto cleanup; + } + else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + + /* output all PNG chunks */ { +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + size_t i; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*write signature and chunks*/ + state->error = writeSignature(&outv); + if(state->error) goto cleanup; + /*IHDR*/ + state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*unknown chunks between IHDR and PLTE*/ + if(info.unknown_chunks_data[0]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); + if(state->error) goto cleanup; + } + /*color profile chunks must come before PLTE */ + if(info.iccp_defined) { + state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } + if(info.srgb_defined) { + state->error = addChunk_sRGB(&outv, &info); + if(state->error) goto cleanup; + } + if(info.gama_defined) { + state->error = addChunk_gAMA(&outv, &info); + if(state->error) goto cleanup; + } + if(info.chrm_defined) { + state->error = addChunk_cHRM(&outv, &info); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*PLTE*/ + if(info.color.colortype == LCT_PALETTE) { + state->error = addChunk_PLTE(&outv, &info.color); + if(state->error) goto cleanup; + } + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { + /*force_palette means: write suggested palette for truecolor in PLTE chunk*/ + state->error = addChunk_PLTE(&outv, &info.color); + if(state->error) goto cleanup; + } + /*tRNS (this will only add if when necessary) */ + state->error = addChunk_tRNS(&outv, &info.color); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*bKGD (must come between PLTE and the IDAt chunks*/ + if(info.background_defined) { + state->error = addChunk_bKGD(&outv, &info); + if(state->error) goto cleanup; + } + /*pHYs (must come before the IDAT chunks)*/ + if(info.phys_defined) { + state->error = addChunk_pHYs(&outv, &info); + if(state->error) goto cleanup; + } + + /*unknown chunks between PLTE and IDAT*/ + if(info.unknown_chunks_data[1]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*IDAT (multiple IDAT chunks must be consecutive)*/ + state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*tIME*/ + if(info.time_defined) { + state->error = addChunk_tIME(&outv, &info.time); + if(state->error) goto cleanup; + } + /*tEXt and/or zTXt*/ + for(i = 0; i != info.text_num; ++i) { + if(lodepng_strlen(info.text_keys[i]) > 79) { + state->error = 66; /*text chunk too large*/ + goto cleanup; + } + if(lodepng_strlen(info.text_keys[i]) < 1) { + state->error = 67; /*text chunk too small*/ + goto cleanup; + } + if(state->encoder.text_compression) { + state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } else { + state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); + if(state->error) goto cleanup; + } + } + /*LodePNG version id in text chunk*/ + if(state->encoder.add_id) { + unsigned already_added_id_text = 0; + for(i = 0; i != info.text_num; ++i) { + const char* k = info.text_keys[i]; + /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */ + if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' && + k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') { + already_added_id_text = 1; + break; + } + } + if(already_added_id_text == 0) { + state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ + if(state->error) goto cleanup; + } + } + /*iTXt*/ + for(i = 0; i != info.itext_num; ++i) { + if(lodepng_strlen(info.itext_keys[i]) > 79) { + state->error = 66; /*text chunk too large*/ + goto cleanup; + } + if(lodepng_strlen(info.itext_keys[i]) < 1) { + state->error = 67; /*text chunk too small*/ + goto cleanup; + } + state->error = addChunk_iTXt( + &outv, state->encoder.text_compression, + info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], + &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } + + /*unknown chunks between IDAT and IEND*/ + if(info.unknown_chunks_data[2]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + state->error = addChunk_IEND(&outv); + if(state->error) goto cleanup; + } + +cleanup: + lodepng_info_cleanup(&info); + lodepng_free(data); + + /*instead of cleaning the vector up, give it to the output*/ + *out = outv.data; + *outsize = outv.size; + + return state->error; +} + +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, + unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + state.info_png.color.colortype = colortype; + state.info_png.color.bitdepth = bitdepth; + lodepng_encode(out, outsize, image, w, h, &state); + error = state.error; + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); + if(!error) error = lodepng_save_file(buffer, buffersize, filename); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { + lodepng_compress_settings_init(&settings->zlibsettings); + settings->filter_palette_zero = 1; + settings->filter_strategy = LFS_MINSUM; + settings->auto_convert = 1; + settings->force_palette = 0; + settings->predefined_filters = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->add_id = 0; + settings->text_compression = 1; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/* +This returns the description of a numerical error code in English. This is also +the documentation of all the error codes. +*/ +const char* lodepng_error_text(unsigned code) { + switch(code) { + case 0: return "no error, everything went ok"; + case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ + case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ + case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ + case 13: return "problem while processing dynamic deflate block"; + case 14: return "problem while processing dynamic deflate block"; + case 15: return "problem while processing dynamic deflate block"; + /*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/ + case 16: return "invalid code while processing dynamic deflate block"; + case 17: return "end of out buffer memory reached while inflating"; + case 18: return "invalid distance code while inflating"; + case 19: return "end of out buffer memory reached while inflating"; + case 20: return "invalid deflate block BTYPE encountered while decoding"; + case 21: return "NLEN is not ones complement of LEN in a deflate block"; + + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ + case 22: return "end of out buffer memory reached while inflating"; + case 23: return "end of in buffer memory reached while inflating"; + case 24: return "invalid FCHECK in zlib header"; + case 25: return "invalid compression method in zlib header"; + case 26: return "FDICT encountered in zlib header while it's not used for PNG"; + case 27: return "PNG file is smaller than a PNG header"; + /*Checks the magic file header, the first 8 bytes of the PNG file*/ + case 28: return "incorrect PNG signature, it's no PNG or corrupted"; + case 29: return "first chunk is not the header chunk"; + case 30: return "chunk length too large, chunk broken off at end of file"; + case 31: return "illegal PNG color type or bpp"; + case 32: return "illegal PNG compression method"; + case 33: return "illegal PNG filter method"; + case 34: return "illegal PNG interlace method"; + case 35: return "chunk length of a chunk is too large or the chunk too small"; + case 36: return "illegal PNG filter type encountered"; + case 37: return "illegal bit depth for this color type given"; + case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/ + case 39: return "tRNS chunk before PLTE or has more entries than palette size"; + case 40: return "tRNS chunk has wrong size for grayscale image"; + case 41: return "tRNS chunk has wrong size for RGB image"; + case 42: return "tRNS chunk appeared while it was not allowed for this color type"; + case 43: return "bKGD chunk has wrong size for palette image"; + case 44: return "bKGD chunk has wrong size for grayscale image"; + case 45: return "bKGD chunk has wrong size for RGB image"; + case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; + case 49: return "jumped past memory while generating dynamic huffman tree"; + case 50: return "jumped past memory while generating dynamic huffman tree"; + case 51: return "jumped past memory while inflating huffman block"; + case 52: return "jumped past memory while inflating"; + case 53: return "size of zlib data too small"; + case 54: return "repeat symbol in tree while there was no value symbol yet"; + /*jumped past tree while generating huffman tree, this could be when the + tree will have more leaves than symbols after generating it out of the + given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ + case 55: return "jumped past tree while generating huffman tree"; + case 56: return "given output image colortype or bitdepth not supported for color conversion"; + case 57: return "invalid CRC encountered (checking CRC can be disabled)"; + case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; + case 59: return "requested color conversion not supported"; + case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; + case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; + /*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/ + case 62: return "conversion from color to grayscale not supported"; + /*(2^31-1)*/ + case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; + /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ + case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; + case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; + case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; + case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; + case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; + case 71: return "invalid interlace mode given to encoder (must be 0 or 1)"; + case 72: return "while decoding, invalid compression method encountering in zTXt or iTXt chunk (it must be 0)"; + case 73: return "invalid tIME chunk size"; + case 74: return "invalid pHYs chunk size"; + /*length could be wrong, or data chopped off*/ + case 75: return "no null termination char found while decoding text chunk"; + case 76: return "iTXt chunk too short to contain required bytes"; + case 77: return "integer overflow in buffer size"; + case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ + case 79: return "failed to open file for writing"; + case 80: return "tried creating a tree of 0 symbols"; + case 81: return "lazy matching at pos 0 is impossible"; + case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds"; + case 83: return "memory allocation failed"; + case 84: return "given image too small to contain all pixels to be encoded"; + case 86: return "impossible offset in lz77 encoding (internal bug)"; + case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; + case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; + case 89: return "text chunk keyword too short or long: must have size 1-79"; + /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ + case 90: return "windowsize must be a power of two"; + case 91: return "invalid decompressed idat size"; + case 92: return "integer overflow due to too many pixels"; + case 93: return "zero width or height is invalid"; + case 94: return "header chunk must have a size of 13 bytes"; + case 95: return "integer overflow with combined idat chunk size"; + case 96: return "invalid gAMA chunk size"; + case 97: return "invalid cHRM chunk size"; + case 98: return "invalid sRGB chunk size"; + case 99: return "invalid sRGB rendering intent"; + case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY"; + case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa"; + case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification"; + case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?"; + case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)"; + case 105: return "integer overflow of bitsize"; + case 106: return "PNG file must have PLTE chunk if color type is palette"; + case 107: return "color convert from palette mode requested without setting the palette data in it"; + case 108: return "tried to add more than 256 values to a palette"; + } + return "unknown error code"; +} +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // C++ Wrapper // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng { + +#ifdef LODEPNG_COMPILE_DISK +unsigned load_file(std::vector& buffer, const std::string& filename) { + long size = lodepng_filesize(filename.c_str()); + if(size < 0) return 78; + buffer.resize((size_t)size); + return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned save_file(const std::vector& buffer, const std::string& filename) { + return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); +} +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings) { + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_decompress(&buffer, &buffersize, 0, in, insize, &settings); + if(buffer) { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings) { + return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings) { + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); + if(buffer) { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings) { + return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ + + +#ifdef LODEPNG_COMPILE_PNG + +State::State() { + lodepng_state_init(this); +} + +State::State(const State& other) { + lodepng_state_init(this); + lodepng_state_copy(this, &other); +} + +State::~State() { + lodepng_state_cleanup(this); +} + +State& State::operator=(const State& other) { + lodepng_state_copy(this, &other); + return *this; +} + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer = 0; + unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); + if(buffer && !error) { + State state; + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) { + return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize) { + unsigned char* buffer = NULL; + unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); + if(buffer && !error) { + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in) { + return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, + LodePNGColorType colortype, unsigned bitdepth) { + std::vector buffer; + /* safe output values in case error happens */ + w = h = 0; + unsigned error = load_file(buffer, filename); + if(error) return error; + return decode(out, w, h, buffer, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DECODER */ +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); + if(buffer) { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} + +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); + if(buffer) { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state) { + if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, state); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + std::vector buffer; + unsigned error = encode(buffer, in, w, h, colortype, bitdepth); + if(!error) error = save_file(buffer, filename); + return error; +} + +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_PNG */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.h b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.h new file mode 100644 index 0000000000000000000000000000000000000000..a386459f9237075f270421d03bde60df8a43ee1d --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng.h @@ -0,0 +1,1945 @@ +/* +LodePNG version 20200306 + +Copyright (c) 2005-2020 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef LODEPNG_H +#define LODEPNG_H + +#include /*for size_t*/ + +extern const char* LODEPNG_VERSION_STRING; + +/* +The following #defines are used to create code sections. They can be disabled +to disable code sections, which can give faster compile time and smaller binary. +The "NO_COMPILE" defines are designed to be used to pass as defines to the +compiler command to disable them without modifying this header, e.g. +-DLODEPNG_NO_COMPILE_ZLIB for gcc. +In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to +allow implementing a custom lodepng_crc32. +*/ +/*deflate & zlib. If disabled, you must specify alternative zlib functions in +the custom_zlib field of the compress and decompress settings*/ +#ifndef LODEPNG_NO_COMPILE_ZLIB +#define LODEPNG_COMPILE_ZLIB +#endif + +/*png encoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_PNG +#define LODEPNG_COMPILE_PNG +#endif + +/*deflate&zlib decoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_DECODER +#define LODEPNG_COMPILE_DECODER +#endif + +/*deflate&zlib encoder and png encoder*/ +#ifndef LODEPNG_NO_COMPILE_ENCODER +#define LODEPNG_COMPILE_ENCODER +#endif + +/*the optional built in harddisk file loading and saving functions*/ +#ifndef LODEPNG_NO_COMPILE_DISK +#define LODEPNG_COMPILE_DISK +#endif + +/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ +#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS +#define LODEPNG_COMPILE_ANCILLARY_CHUNKS +#endif + +/*ability to convert error numerical codes to English text string*/ +#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT +#define LODEPNG_COMPILE_ERROR_TEXT +#endif + +/*Compile the default allocators (C's free, malloc and realloc). If you disable this, +you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your +source files with custom allocators.*/ +#ifndef LODEPNG_NO_COMPILE_ALLOCATORS +#define LODEPNG_COMPILE_ALLOCATORS +#endif + +/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ +#ifdef __cplusplus +#ifndef LODEPNG_NO_COMPILE_CPP +#define LODEPNG_COMPILE_CPP +#endif +#endif + +#ifdef LODEPNG_COMPILE_CPP +#include +#include +#endif /*LODEPNG_COMPILE_CPP*/ + +#ifdef LODEPNG_COMPILE_PNG +/*The PNG color types (also used for raw image).*/ +typedef enum LodePNGColorType { + LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/ + LCT_RGB = 2, /*RGB: 8,16 bit*/ + LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ + LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/ + LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/ + /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid + byte value from 0 to 255 that could be present in an invalid PNG file header. Do + not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use + the valid color type names above, or numeric values like 1 or 7 when checking for + particular disallowed color type byte values, or cast to integer to print it.*/ + LCT_MAX_OCTET_VALUE = 255 +} LodePNGColorType; + +#ifdef LODEPNG_COMPILE_DECODER +/* +Converts PNG data in memory to raw pixel data. +out: Output parameter. Pointer to buffer that will contain the raw pixel data. + After decoding, its size is w * h * (bytes per pixel) bytes larger than + initially. Bytes per pixel depends on colortype and bitdepth. + Must be freed after usage with free(*out). + Note: for 16-bit per channel colors, uses big endian format like PNG does. +w: Output parameter. Pointer to width of pixel data. +h: Output parameter. Pointer to height of pixel data. +in: Memory buffer with the PNG file. +insize: size of the in buffer. +colortype: the desired color type for the raw output image. See explanation on PNG color types. +bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_DISK +/* +Load PNG from disk, from file with given name. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); + +/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Converts raw pixel data into a PNG image in memory. The colortype and bitdepth + of the output PNG image cannot be chosen, they are automatically determined + by the colortype, bitdepth and content of the input pixel data. + Note: for 16-bit per channel colors, needs big endian format like PNG does. +out: Output parameter. Pointer to buffer that will contain the PNG image data. + Must be freed after usage with free(*out). +outsize: Output parameter. Pointer to the size in bytes of the out buffer. +image: The raw pixel data to encode. The size of this buffer should be + w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. +w: width of the raw pixel data in pixels. +h: height of the raw pixel data in pixels. +colortype: the color type of the raw input image. See explanation on PNG color types. +bitdepth: the bit depth of the raw input image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DISK +/* +Converts raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned lodepng_encode_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng { +#ifdef LODEPNG_COMPILE_DECODER +/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype +is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts PNG file from disk to raw pixel data in memory. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::string& filename, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype +is that of the raw input data. The output PNG color type will be auto chosen.*/ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts 32-bit RGBA raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/*Returns an English description of the numerical error code.*/ +const char* lodepng_error_text(unsigned code); +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Settings for zlib decompression*/ +typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; +struct LodePNGDecompressSettings { + /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ + unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ + unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/ + + /*use custom zlib decoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + /*use custom deflate decoder instead of built in one (default: null) + if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate)*/ + unsigned (*custom_inflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGDecompressSettings lodepng_default_decompress_settings; +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Settings for zlib compression. Tweaking these settings tweaks the balance +between speed and compression ratio. +*/ +typedef struct LodePNGCompressSettings LodePNGCompressSettings; +struct LodePNGCompressSettings /*deflate = compress*/ { + /*LZ77 related settings*/ + unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ + unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ + unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ + unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ + unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ + unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ + + /*use custom zlib encoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + /*use custom deflate encoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_deflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGCompressSettings lodepng_default_compress_settings; +void lodepng_compress_settings_init(LodePNGCompressSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_PNG +/* +Color mode of an image. Contains all information required to decode the pixel +bits to RGBA colors. This information is the same as used in the PNG file +format, and is used both for PNG and raw image data in LodePNG. +*/ +typedef struct LodePNGColorMode { + /*header (IHDR)*/ + LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ + unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ + + /* + palette (PLTE and tRNS) + + Dynamically allocated with the colors of the palette, including alpha. + This field may not be allocated directly, use lodepng_color_mode_init first, + then lodepng_palette_add per color to correctly initialize it (to ensure size + of exactly 1024 bytes). + + The alpha channels must be set as well, set them to 255 for opaque images. + + When decoding, by default you can ignore this palette, since LodePNG already + fills the palette colors in the pixels of the raw RGBA output. + + The palette is only supported for color type 3. + */ + unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/ + size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/ + + /* + transparent color key (tRNS) + + This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. + For grayscale PNGs, r, g and b will all 3 be set to the same. + + When decoding, by default you can ignore this information, since LodePNG sets + pixels with this key to transparent already in the raw RGBA output. + + The color key is only supported for color types 0 and 2. + */ + unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ + unsigned key_r; /*red/grayscale component of color key*/ + unsigned key_g; /*green component of color key*/ + unsigned key_b; /*blue component of color key*/ +} LodePNGColorMode; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_color_mode_init(LodePNGColorMode* info); +void lodepng_color_mode_cleanup(LodePNGColorMode* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); +/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */ +LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth); + +void lodepng_palette_clear(LodePNGColorMode* info); +/*add 1 color to the palette*/ +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a); + +/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info); +/*get the amount of color channels used, based on colortype in the struct. +If a palette is used, it counts as 1 channel.*/ +unsigned lodepng_get_channels(const LodePNGColorMode* info); +/*is it a grayscale type? (only colortype 0 or 4)*/ +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); +/*has it got an alpha channel? (only colortype 2 or 6)*/ +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); +/*has it got a palette? (only colortype 3)*/ +unsigned lodepng_is_palette_type(const LodePNGColorMode* info); +/*only returns true if there is a palette and there is a value in the palette with alpha < 255. +Loops through the palette to check this.*/ +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); +/* +Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. +Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). +Returns false if the image can only have opaque pixels. +In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, +or if "key_defined" is true. +*/ +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); +/*Returns the byte size of a raw image buffer with given width, height and color mode*/ +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*The information of a Time chunk in PNG.*/ +typedef struct LodePNGTime { + unsigned year; /*2 bytes used (0-65535)*/ + unsigned month; /*1-12*/ + unsigned day; /*1-31*/ + unsigned hour; /*0-23*/ + unsigned minute; /*0-59*/ + unsigned second; /*0-60 (to allow for leap seconds)*/ +} LodePNGTime; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Information about the PNG image, except pixels, width and height.*/ +typedef struct LodePNGInfo { + /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ + unsigned compression_method;/*compression method of the original file. Always 0.*/ + unsigned filter_method; /*filter method of the original file*/ + unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/ + LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /* + Suggested background color chunk (bKGD) + + This uses the same color mode and bit depth as the PNG (except no alpha channel), + with values truncated to the bit depth in the unsigned integer. + + For grayscale and palette PNGs, the value is stored in background_r. The values + in background_g and background_b are then unused. + + So when decoding, you may get these in a different color mode than the one you requested + for the raw pixels. + + When encoding with auto_convert, you must use the color model defined in info_png.color for + these values. The encoder normally ignores info_png.color when auto_convert is on, but will + use it to interpret these values (and convert copies of them to its chosen color model). + + When encoding, avoid setting this to an expensive color, such as a non-gray value + when the image is gray, or the compression will be worse since it will be forced to + write the PNG with a more expensive color mode (when auto_convert is on). + + The decoder does not use this background color to edit the color of pixels. This is a + completely optional metadata feature. + */ + unsigned background_defined; /*is a suggested background color given?*/ + unsigned background_r; /*red/gray/palette component of suggested background color*/ + unsigned background_g; /*green component of suggested background color*/ + unsigned background_b; /*blue component of suggested background color*/ + + /* + non-international text chunks (tEXt and zTXt) + + The char** arrays each contain num strings. The actual messages are in + text_strings, while text_keys are keywords that give a short description what + the actual text represents, e.g. Title, Author, Description, or anything else. + + All the string fields below including keys, names and language tags are null terminated. + The PNG specification uses null characters for the keys, names and tags, and forbids null + characters to appear in the main text which is why we can use null termination everywhere here. + + A keyword is minimum 1 character and maximum 79 characters long. It's + discouraged to use a single line length longer than 79 characters for texts. + + Don't allocate these text buffers yourself. Use the init/cleanup functions + correctly and use lodepng_add_text and lodepng_clear_text. + */ + size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ + char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ + char** text_strings; /*the actual text*/ + + /* + international text chunks (iTXt) + Similar to the non-international text chunks, but with additional strings + "langtags" and "transkeys". + */ + size_t itext_num; /*the amount of international texts in this PNG*/ + char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ + char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ + char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ + char** itext_strings; /*the actual international text - UTF-8 string*/ + + /*time chunk (tIME)*/ + unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ + LodePNGTime time; + + /*phys chunk (pHYs)*/ + unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ + unsigned phys_x; /*pixels per unit in x direction*/ + unsigned phys_y; /*pixels per unit in y direction*/ + unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ + + /* + Color profile related chunks: gAMA, cHRM, sRGB, iCPP + + LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color + profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please + use these values with a color management library. + + See the PNG, ICC and sRGB specifications for more information about the meaning of these values. + */ + + /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */ + unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */ + unsigned gama_gamma; /* Gamma exponent times 100000 */ + + /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */ + unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */ + unsigned chrm_white_x; /* White Point x times 100000 */ + unsigned chrm_white_y; /* White Point y times 100000 */ + unsigned chrm_red_x; /* Red x times 100000 */ + unsigned chrm_red_y; /* Red y times 100000 */ + unsigned chrm_green_x; /* Green x times 100000 */ + unsigned chrm_green_y; /* Green y times 100000 */ + unsigned chrm_blue_x; /* Blue x times 100000 */ + unsigned chrm_blue_y; /* Blue y times 100000 */ + + /* + sRGB chunk: optional. May not appear at the same time as iCCP. + If gAMA is also present gAMA must contain value 45455. + If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000. + */ + unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */ + unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */ + + /* + iCCP chunk: optional. May not appear at the same time as sRGB. + + LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a + separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color + management and conversions. + + For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC + profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and + enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile. + + For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray + PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure + the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is + enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder + error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel + data if the pixels could be encoded as grayscale but the ICC profile is RGB. + + To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so + make sure you compute it carefully to avoid the above problems. + */ + unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */ + char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */ + /* + The ICC profile in iccp_profile_size bytes. + Don't allocate this buffer yourself. Use the init/cleanup functions + correctly and use lodepng_set_icc and lodepng_clear_icc. + */ + unsigned char* iccp_profile; + unsigned iccp_profile_size; /* The size of iccp_profile in bytes */ + + /* End of color profile related chunks */ + + + /* + unknown chunks: chunks not known by LodePNG, passed on byte for byte. + + There are 3 buffers, one for each position in the PNG where unknown chunks can appear. + Each buffer contains all unknown chunks for that position consecutively. + The 3 positions are: + 0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. + + For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag + above in here, since the encoder will blindly follow this and could then encode an invalid PNG file + (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use + this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST), + or any non-standard PNG chunk. + + Do not allocate or traverse this data yourself. Use the chunk traversing functions declared + later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. + */ + unsigned char* unknown_chunks_data[3]; + size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGInfo; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_info_init(LodePNGInfo* info); +void lodepng_info_cleanup(LodePNGInfo* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ +void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ +void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ + +/*replaces if exists*/ +unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size); +void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/* +Converts raw buffer from one color type to another color type, based on +LodePNGColorMode structs to describe the input and output color type. +See the reference manual at the end of this header file to see which color conversions are supported. +return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) +The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel +of the output color type (lodepng_get_bpp). +For < 8 bpp images, there should not be padding bits at the end of scanlines. +For 16-bit per channel colors, uses big endian format like PNG does. +Return value is LodePNG error code +*/ +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DECODER +/* +Settings for the decoder. This contains settings for the PNG and the Zlib +decoder, but not the Info settings from the Info structs. +*/ +typedef struct LodePNGDecoderSettings { + LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + + /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ + unsigned ignore_crc; /*ignore CRC checksums*/ + unsigned ignore_critical; /*ignore unknown critical chunks*/ + unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ + /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable + errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some + strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters + in string keys, etc... */ + + unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ + /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ + unsigned remember_unknown_chunks; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGDecoderSettings; + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ +typedef enum LodePNGFilterStrategy { + /*every filter at zero*/ + LFS_ZERO = 0, + /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/ + LFS_ONE = 1, + LFS_TWO = 2, + LFS_THREE = 3, + LFS_FOUR = 4, + /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ + LFS_MINSUM, + /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending + on the image, this is better or worse than minsum.*/ + LFS_ENTROPY, + /* + Brute-force-search PNG filters by compressing each filter for each scanline. + Experimental, very slow, and only rarely gives better compression than MINSUM. + */ + LFS_BRUTE_FORCE, + /*use predefined_filters buffer: you specify the filter type for each scanline*/ + LFS_PREDEFINED +} LodePNGFilterStrategy; + +/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...), +which helps decide which color model to use for encoding. +Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ +typedef struct LodePNGColorStats { + unsigned colored; /*not grayscale*/ + unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ + unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ + unsigned short key_g; + unsigned short key_b; + unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ + unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/ + unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/ + unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/ + size_t numpixels; + + /*user settings for computing/using the stats*/ + unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/ + unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/ +} LodePNGColorStats; + +void lodepng_color_stats_init(LodePNGColorStats* stats); + +/*Get a LodePNGColorStats of the image. The stats must already have been inited. +Returns error code (e.g. alloc fail) or 0 if ok.*/ +unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); + +/*Settings for the encoder.*/ +typedef struct LodePNGEncoderSettings { + LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ + + unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ + + /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than + 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to + completely follow the official PNG heuristic, filter_palette_zero must be true and + filter_strategy must be LFS_MINSUM*/ + unsigned filter_palette_zero; + /*Which filter strategy to use when not using zeroes due to filter_palette_zero. + Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ + LodePNGFilterStrategy filter_strategy; + /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with + the same length as the amount of scanlines in the image, and each value must <= 5. You + have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero + must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ + const unsigned char* predefined_filters; + + /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). + If colortype is 3, PLTE is _always_ created.*/ + unsigned force_palette; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*add LodePNG identifier and version as a text chunk, for debugging*/ + unsigned add_id; + /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ + unsigned text_compression; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGEncoderSettings; + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) +/*The settings, state and information for extended encoding and decoding.*/ +typedef struct LodePNGState { +#ifdef LODEPNG_COMPILE_DECODER + LodePNGDecoderSettings decoder; /*the decoding settings*/ +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + LodePNGEncoderSettings encoder; /*the encoding settings*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ + LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ + unsigned error; +} LodePNGState; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_state_init(LodePNGState* state); +void lodepng_state_cleanup(LodePNGState* state); +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_DECODER +/* +Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and +getting much more information about the PNG image and color mode. +*/ +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); + +/* +Read the PNG header, but not the actual data. This returns only the information +that is in the IHDR chunk of the PNG, such as width, height and color type. The +information is placed in the info_png field of the LodePNGState. +*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* +Reads one metadata chunk (other than IHDR) of the PNG file and outputs what it +read in the state. Returns error code on failure. +Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const +to find the desired chunk type, and if non null use lodepng_inspect_chunk (with +chunk_pointer - start_of_file as pos). +Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...). +Ignores unsupported, unknown, non-metadata or IHDR chunks (without error). +Requirements: &in[pos] must point to start of a chunk, must use regular +lodepng_inspect first since format of most other chunks depends on IHDR, and if +there is a PLTE chunk, that one must be inspected before tRNS or bKGD. +*/ +unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_ENCODER +/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* +The lodepng_chunk functions are normally not needed, except to traverse the +unknown chunks stored in the LodePNGInfo struct, or add new ones to it. +It also allows traversing the chunks of an encoded PNG file yourself. + +The chunk pointer always points to the beginning of the chunk itself, that is +the first byte of the 4 length bytes. + +In the PNG file format, chunks have the following format: +-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer) +-4 bytes chunk type (ASCII a-z,A-Z only, see below) +-length bytes of data (may be 0 bytes if length was 0) +-4 bytes of CRC, computed on chunk name + data + +The first chunk starts at the 8th byte of the PNG file, the entire rest of the file +exists out of concatenated chunks with the above format. + +PNG standard chunk ASCII naming conventions: +-First byte: uppercase = critical, lowercase = ancillary +-Second byte: uppercase = public, lowercase = private +-Third byte: must be uppercase +-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy +*/ + +/* +Gets the length of the data of the chunk. Total chunk length has 12 bytes more. +There must be at least 4 bytes to read from. If the result value is too large, +it may be corrupt data. +*/ +unsigned lodepng_chunk_length(const unsigned char* chunk); + +/*puts the 4-byte type in null terminated string*/ +void lodepng_chunk_type(char type[5], const unsigned char* chunk); + +/*check if the type is the given type*/ +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); + +/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); + +/*0: public, 1: private (see PNG standard)*/ +unsigned char lodepng_chunk_private(const unsigned char* chunk); + +/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); + +/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ +unsigned char* lodepng_chunk_data(unsigned char* chunk); +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); + +/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ +unsigned lodepng_chunk_check_crc(const unsigned char* chunk); + +/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ +void lodepng_chunk_generate_crc(unsigned char* chunk); + +/* +Iterate to next chunks, allows iterating through all chunks of the PNG file. +Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call, +or the 8th byte of a PNG file which always has the first chunk), or alternatively may +point to the first byte of the PNG file (which is not a chunk but the magic header, the +function will then skip over it and return the first real chunk). +Will output pointer to the start of the next chunk, or at or beyond end of the file if there +is no more chunk after this or possibly if the chunk is corrupt. +Start this process at the 8th byte of the PNG file. +In a non-corrupt PNG file, the last chunk should have name "IEND". +*/ +unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end); +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end); + +/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/ +unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]); +const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]); + +/* +Appends chunk to the data in out. The given chunk should already have its chunk header. +The out variable and outsize are updated to reflect the new reallocated buffer. +Returns error code (0 if it went ok) +*/ +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk); + +/* +Appends new chunk to out. The chunk to append is given by giving its length, type +and data separately. The type is a 4-letter string. +The out variable and outsize are updated to reflect the new reallocated buffer. +Returne error code (0 if it went ok) +*/ +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length, + const char* type, const unsigned char* data); + + +/*Calculate CRC32 of buffer*/ +unsigned lodepng_crc32(const unsigned char* buf, size_t len); +#endif /*LODEPNG_COMPILE_PNG*/ + + +#ifdef LODEPNG_COMPILE_ZLIB +/* +This zlib part can be used independently to zlib compress and decompress a +buffer. It cannot be used to create gzip files however, and it only supports the +part of zlib that is required for PNG, it does not support dictionaries. +*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); + +/* +Decompresses Zlib data. Reallocates the out buffer and appends the data. The +data must be according to the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Compresses data with Zlib. Reallocates the out buffer and appends the data. +Zlib adds a small header and trailer around the deflate data. +The data is output in the format of the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +/* +Find length-limited Huffman code for given frequencies. This function is in the +public interface only for tests, it's used internally by lodepng_deflate. +*/ +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen); + +/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into buffer. The function allocates the out buffer, and +after usage you should free it. +out: output parameter, contains pointer to loaded buffer. +outsize: output parameter, size of the allocated out buffer +filename: the path to the file to load +return value: error code (0 means ok) +*/ +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); + +/* +Save a file from buffer to disk. Warning, if it exists, this function overwrites +the file without warning! +buffer: the buffer to write +buffersize: size of the buffer to write +filename: the path to the file to save to +return value: error code (0 means ok) +*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ + +#ifdef LODEPNG_COMPILE_CPP +/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ +namespace lodepng { +#ifdef LODEPNG_COMPILE_PNG +class State : public LodePNGState { + public: + State(); + State(const State& other); + ~State(); + State& operator=(const State& other); +}; + +#ifdef LODEPNG_COMPILE_DECODER +/* Same as other lodepng::decode, but using a State for more settings and information. */ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Same as other lodepng::encode, but using a State for more settings and information. */ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into an std::vector. +return value: error code (0 means ok) +*/ +unsigned load_file(std::vector& buffer, const std::string& filename); + +/* +Save the binary data in an std::vector to a file on disk. The file is overwritten +without warning. +*/ +unsigned save_file(const std::vector& buffer, const std::string& filename); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_PNG */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +/* Zlib-decompress an unsigned char buffer */ +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); + +/* Zlib-decompress an std::vector */ +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Zlib-compress an unsigned char buffer */ +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); + +/* Zlib-compress an std::vector */ +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ + +/* +TODO: +[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often +[.] check compatibility with various compilers - done but needs to be redone for every newer version +[X] converting color to 16-bit per channel types +[X] support color profile chunk types (but never let them touch RGB values by default) +[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST) +[ ] make sure encoder generates no chunks with size > (2^31)-1 +[ ] partial decoding (stream processing) +[X] let the "isFullyOpaque" function check color keys and transparent palettes too +[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" +[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58) +[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... +[ ] error messages with line numbers (and version) +[ ] errors in state instead of as return code? +[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk +[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes +[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... +[ ] allow user to give data (void*) to custom allocator +[X] provide alternatives for C library functions not present on some platforms (memcpy, ...) +*/ + +#endif /*LODEPNG_H inclusion guard*/ + +/* +LodePNG Documentation +--------------------- + +0. table of contents +-------------------- + + 1. about + 1.1. supported features + 1.2. features not supported + 2. C and C++ version + 3. security + 4. decoding + 5. encoding + 6. color conversions + 6.1. PNG color types + 6.2. color conversions + 6.3. padding bits + 6.4. A note about 16-bits per channel and endianness + 7. error values + 8. chunks and PNG editing + 9. compiler support + 10. examples + 10.1. decoder C++ example + 10.2. decoder C example + 11. state settings reference + 12. changes + 13. contact information + + +1. about +-------- + +PNG is a file format to store raster images losslessly with good compression, +supporting different color types and alpha channel. + +LodePNG is a PNG codec according to the Portable Network Graphics (PNG) +Specification (Second Edition) - W3C Recommendation 10 November 2003. + +The specifications used are: + +*) Portable Network Graphics (PNG) Specification (Second Edition): + http://www.w3.org/TR/2003/REC-PNG-20031110 +*) RFC 1950 ZLIB Compressed Data Format version 3.3: + http://www.gzip.org/zlib/rfc-zlib.html +*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: + http://www.gzip.org/zlib/rfc-deflate.html + +The most recent version of LodePNG can currently be found at +http://lodev.org/lodepng/ + +LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds +extra functionality. + +LodePNG exists out of two files: +-lodepng.h: the header file for both C and C++ +-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage + +If you want to start using LodePNG right away without reading this doc, get the +examples from the LodePNG website to see how to use it in code, or check the +smaller examples in chapter 13 here. + +LodePNG is simple but only supports the basic requirements. To achieve +simplicity, the following design choices were made: There are no dependencies +on any external library. There are functions to decode and encode a PNG with +a single function call, and extended versions of these functions taking a +LodePNGState struct allowing to specify or get more information. By default +the colors of the raw image are always RGB or RGBA, no matter what color type +the PNG file uses. To read and write files, there are simple functions to +convert the files to/from buffers in memory. + +This all makes LodePNG suitable for loading textures in games, demos and small +programs, ... It's less suitable for full fledged image editors, loading PNGs +over network (it requires all the image data to be available before decoding can +begin), life-critical systems, ... + +1.1. supported features +----------------------- + +The following features are supported by the decoder: + +*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, + or the same color type as the PNG +*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image +*) Adam7 interlace and deinterlace for any color type +*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk +*) support for alpha channels, including RGBA color model, translucent palettes and color keying +*) zlib decompression (inflate) +*) zlib compression (deflate) +*) CRC32 and ADLER32 checksums +*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only, + plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system. +*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. +*) the following chunks are supported by both encoder and decoder: + IHDR: header information + PLTE: color palette + IDAT: pixel data + IEND: the final chunk + tRNS: transparency for palettized images + tEXt: textual information + zTXt: compressed textual information + iTXt: international textual information + bKGD: suggested background color + pHYs: physical dimensions + tIME: modification time + cHRM: RGB chromaticities + gAMA: RGB gamma correction + iCCP: ICC color profile + sRGB: rendering intent + +1.2. features not supported +--------------------------- + +The following features are _not_ supported: + +*) some features needed to make a conformant PNG-Editor might be still missing. +*) partial loading/stream processing. All data must be available and is processed in one call. +*) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG: + sBIT + hIST + sPLT + + +2. C and C++ version +-------------------- + +The C version uses buffers allocated with alloc that you need to free() +yourself. You need to use init and cleanup functions for each struct whenever +using a struct from the C version to avoid exploits and memory leaks. + +The C++ version has extra functions with std::vectors in the interface and the +lodepng::State class which is a LodePNGState with constructor and destructor. + +These files work without modification for both C and C++ compilers because all +the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers +ignore it, and the C code is made to compile both with strict ISO C90 and C++. + +To use the C++ version, you need to rename the source file to lodepng.cpp +(instead of lodepng.c), and compile it with a C++ compiler. + +To use the C version, you need to rename the source file to lodepng.c (instead +of lodepng.cpp), and compile it with a C compiler. + + +3. Security +----------- + +Even if carefully designed, it's always possible that LodePNG contains possible +exploits. If you discover one, please let me know, and it will be fixed. + +When using LodePNG, care has to be taken with the C version of LodePNG, as well +as the C-style structs when working with C++. The following conventions are used +for all C-style structs: + +-if a struct has a corresponding init function, always call the init function when making a new one +-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks +-if a struct has a corresponding copy function, use the copy function instead of "=". + The destination must also be inited already. + + +4. Decoding +----------- + +Decoding converts a PNG compressed image to a raw pixel buffer. + +Most documentation on using the decoder is at its declarations in the header +above. For C, simple decoding can be done with functions such as +lodepng_decode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_decode. For C++, all decoding can be done with the +various lodepng::decode functions, and lodepng::State can be used for advanced +features. + +When using the LodePNGState, it uses the following fields for decoding: +*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here +*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get +*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use + +LodePNGInfo info_png +-------------------- + +After decoding, this contains extra information of the PNG image, except the actual +pixels, width and height because these are already gotten directly from the decoder +functions. + +It contains for example the original color type of the PNG image, text comments, +suggested background color, etc... More details about the LodePNGInfo struct are +at its declaration documentation. + +LodePNGColorMode info_raw +------------------------- + +When decoding, here you can specify which color type you want +the resulting raw image to be. If this is different from the colortype of the +PNG, then the decoder will automatically convert the result. This conversion +always works, except if you want it to convert a color PNG to grayscale or to +a palette with missing colors. + +By default, 32-bit color is used for the result. + +LodePNGDecoderSettings decoder +------------------------------ + +The settings can be used to ignore the errors created by invalid CRC and Adler32 +chunks, and to disable the decoding of tEXt chunks. + +There's also a setting color_convert, true by default. If false, no conversion +is done, the resulting data will be as it was in the PNG (after decompression) +and you'll have to puzzle the colors of the pixels together yourself using the +color type information in the LodePNGInfo. + + +5. Encoding +----------- + +Encoding converts a raw pixel buffer to a PNG compressed image. + +Most documentation on using the encoder is at its declarations in the header +above. For C, simple encoding can be done with functions such as +lodepng_encode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_encode. For C++, all encoding can be done with the +various lodepng::encode functions, and lodepng::State can be used for advanced +features. + +Like the decoder, the encoder can also give errors. However it gives less errors +since the encoder input is trusted, the decoder input (a PNG image that could +be forged by anyone) is not trusted. + +When using the LodePNGState, it uses the following fields for encoding: +*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. +*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has +*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use + +LodePNGInfo info_png +-------------------- + +When encoding, you use this the opposite way as when decoding: for encoding, +you fill in the values you want the PNG to have before encoding. By default it's +not needed to specify a color type for the PNG since it's automatically chosen, +but it's possible to choose it yourself given the right settings. + +The encoder will not always exactly match the LodePNGInfo struct you give, +it tries as close as possible. Some things are ignored by the encoder. The +encoder uses, for example, the following settings from it when applicable: +colortype and bitdepth, text chunks, time chunk, the color key, the palette, the +background color, the interlace method, unknown chunks, ... + +When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. +If the palette contains any colors for which the alpha channel is not 255 (so +there are translucent colors in the palette), it'll add a tRNS chunk. + +LodePNGColorMode info_raw +------------------------- + +You specify the color type of the raw image that you give to the input here, +including a possible transparent color key and palette you happen to be using in +your raw image data. + +By default, 32-bit color is assumed, meaning your input has to be in RGBA +format with 4 bytes (unsigned chars) per pixel. + +LodePNGEncoderSettings encoder +------------------------------ + +The following settings are supported (some are in sub-structs): +*) auto_convert: when this option is enabled, the encoder will +automatically choose the smallest possible color mode (including color key) that +can encode the colors of all pixels without information loss. +*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, + 2 = dynamic huffman tree (best compression). Should be 2 for proper + compression. +*) use_lz77: whether or not to use LZ77 for compressed block types. Should be + true for proper compression. +*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value + 2048 by default, but can be set to 32768 for better, but slow, compression. +*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE + chunk if force_palette is true. This can used as suggested palette to convert + to by viewers that don't support more than 256 colors (if those still exist) +*) add_id: add text chunk "Encoder: LodePNG " to the image. +*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. + zTXt chunks use zlib compression on the text. This gives a smaller result on + large texts but a larger result on small texts (such as a single program name). + It's all tEXt or all zTXt though, there's no separate setting per text yet. + + +6. color conversions +-------------------- + +An important thing to note about LodePNG, is that the color type of the PNG, and +the color type of the raw image, are completely independent. By default, when +you decode a PNG, you get the result as a raw image in the color type you want, +no matter whether the PNG was encoded with a palette, grayscale or RGBA color. +And if you encode an image, by default LodePNG will automatically choose the PNG +color type that gives good compression based on the values of colors and amount +of colors in the image. It can be configured to let you control it instead as +well, though. + +To be able to do this, LodePNG does conversions from one color mode to another. +It can convert from almost any color type to any other color type, except the +following conversions: RGB to grayscale is not supported, and converting to a +palette when the palette doesn't have a required color is not supported. This is +not supported on purpose: this is information loss which requires a color +reduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray +is easy, but there are multiple ways if you want to give some channels more +weight). + +By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB +color, no matter what color type the PNG has. And by default when encoding, +LodePNG automatically picks the best color model for the output PNG, and expects +the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control +the color format of the images yourself, you can skip this chapter. + +6.1. PNG color types +-------------------- + +A PNG image can have many color types, ranging from 1-bit color to 64-bit color, +as well as palettized color modes. After the zlib decompression and unfiltering +in the PNG image is done, the raw pixel data will have that color type and thus +a certain amount of bits per pixel. If you want the output raw image after +decoding to have another color type, a conversion is done by LodePNG. + +The PNG specification gives the following color types: + +0: grayscale, bit depths 1, 2, 4, 8, 16 +2: RGB, bit depths 8 and 16 +3: palette, bit depths 1, 2, 4 and 8 +4: grayscale with alpha, bit depths 8 and 16 +6: RGBA, bit depths 8 and 16 + +Bit depth is the amount of bits per pixel per color channel. So the total amount +of bits per pixel is: amount of channels * bitdepth. + +6.2. color conversions +---------------------- + +As explained in the sections about the encoder and decoder, you can specify +color types and bit depths in info_png and info_raw to change the default +behaviour. + +If, when decoding, you want the raw image to be something else than the default, +you need to set the color type and bit depth you want in the LodePNGColorMode, +or the parameters colortype and bitdepth of the simple decoding function. + +If, when encoding, you use another color type than the default in the raw input +image, you need to specify its color type and bit depth in the LodePNGColorMode +of the raw image, or use the parameters colortype and bitdepth of the simple +encoding function. + +If, when encoding, you don't want LodePNG to choose the output PNG color type +but control it yourself, you need to set auto_convert in the encoder settings +to false, and specify the color type you want in the LodePNGInfo of the +encoder (including palette: it can generate a palette if auto_convert is true, +otherwise not). + +If the input and output color type differ (whether user chosen or auto chosen), +LodePNG will do a color conversion, which follows the rules below, and may +sometimes result in an error. + +To avoid some confusion: +-the decoder converts from PNG to raw image +-the encoder converts from raw image to PNG +-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image +-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG +-when encoding, the color type in LodePNGInfo is ignored if auto_convert + is enabled, it is automatically generated instead +-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original + PNG image, but it can be ignored since the raw image has the color type you requested instead +-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion + between the color types is done if the color types are supported. If it is not + supported, an error is returned. If the types are the same, no conversion is done. +-even though some conversions aren't supported, LodePNG supports loading PNGs from any + colortype and saving PNGs to any colortype, sometimes it just requires preparing + the raw image correctly before encoding. +-both encoder and decoder use the same color converter. + +The function lodepng_convert does the color conversion. It is available in the +interface but normally isn't needed since the encoder and decoder already call +it. + +Non supported color conversions: +-color to grayscale when non-gray pixels are present: no error is thrown, but +the result will look ugly because only the red channel is taken (it assumes all +three channels are the same in this case so ignores green and blue). The reason +no error is given is to allow converting from three-channel grayscale images to +one-channel even if there are numerical imprecisions. +-anything to palette when the palette does not have an exact match for a from-color +in it: in this case an error is thrown + +Supported color conversions: +-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA +-any gray or gray+alpha, to gray or gray+alpha +-anything to a palette, as long as the palette has the requested colors in it +-removing alpha channel +-higher to smaller bitdepth, and vice versa + +If you want no color conversion to be done (e.g. for speed or control): +-In the encoder, you can make it save a PNG with any color type by giving the +raw color mode and LodePNGInfo the same color mode, and setting auto_convert to +false. +-In the decoder, you can make it store the pixel data in the same color type +as the PNG has, by setting the color_convert setting to false. Settings in +info_raw are then ignored. + +6.3. padding bits +----------------- + +In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines +have a bit amount that isn't a multiple of 8, then padding bits are used so that each +scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. +The raw input image you give to the encoder, and the raw output image you get from the decoder +will NOT have these padding bits, e.g. in the case of a 1-bit image with a width +of 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte, +not the first bit of a new byte. + +6.4. A note about 16-bits per channel and endianness +---------------------------------------------------- + +LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like +for any other color format. The 16-bit values are stored in big endian (most +significant byte first) in these arrays. This is the opposite order of the +little endian used by x86 CPU's. + +LodePNG always uses big endian because the PNG file format does so internally. +Conversions to other formats than PNG uses internally are not supported by +LodePNG on purpose, there are myriads of formats, including endianness of 16-bit +colors, the order in which you store R, G, B and A, and so on. Supporting and +converting to/from all that is outside the scope of LodePNG. + +This may mean that, depending on your use case, you may want to convert the big +endian output of LodePNG to little endian with a for loop. This is certainly not +always needed, many applications and libraries support big endian 16-bit colors +anyway, but it means you cannot simply cast the unsigned char* buffer to an +unsigned short* buffer on x86 CPUs. + + +7. error values +--------------- + +All functions in LodePNG that return an error code, return 0 if everything went +OK, or a non-zero code if there was an error. + +The meaning of the LodePNG error values can be retrieved with the function +lodepng_error_text: given the numerical error code, it returns a description +of the error in English as a string. + +Check the implementation of lodepng_error_text to see the meaning of each code. + + +8. chunks and PNG editing +------------------------- + +If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG +editor that should follow the rules about handling of unknown chunks, or if your +program is able to read other types of chunks than the ones handled by LodePNG, +then that's possible with the chunk functions of LodePNG. + +A PNG chunk has the following layout: + +4 bytes length +4 bytes type name +length bytes data +4 bytes CRC + +8.1. iterating through chunks +----------------------------- + +If you have a buffer containing the PNG image data, then the first chunk (the +IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the +signature of the PNG and are not part of a chunk. But if you start at byte 8 +then you have a chunk, and can check the following things of it. + +NOTE: none of these functions check for memory buffer boundaries. To avoid +exploits, always make sure the buffer contains all the data of the chunks. +When using lodepng_chunk_next, make sure the returned value is within the +allocated memory. + +unsigned lodepng_chunk_length(const unsigned char* chunk): + +Get the length of the chunk's data. The total chunk length is this length + 12. + +void lodepng_chunk_type(char type[5], const unsigned char* chunk): +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): + +Get the type of the chunk or compare if it's a certain type + +unsigned char lodepng_chunk_critical(const unsigned char* chunk): +unsigned char lodepng_chunk_private(const unsigned char* chunk): +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): + +Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). +Check if the chunk is private (public chunks are part of the standard, private ones not). +Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical +chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your +program doesn't handle that type of unknown chunk. + +unsigned char* lodepng_chunk_data(unsigned char* chunk): +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): + +Get a pointer to the start of the data of the chunk. + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk): +void lodepng_chunk_generate_crc(unsigned char* chunk): + +Check if the crc is correct or generate a correct one. + +unsigned char* lodepng_chunk_next(unsigned char* chunk): +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): + +Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these +functions do no boundary checking of the allocated data whatsoever, so make sure there is enough +data available in the buffer to be able to go to the next chunk. + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk): +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length, + const char* type, const unsigned char* data): + +These functions are used to create new chunks that are appended to the data in *out that has +length *outsize. The append function appends an existing chunk to the new data. The create +function creates a new chunk with the given parameters and appends it. Type is the 4-letter +name of the chunk. + +8.2. chunks in info_png +----------------------- + +The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 +buffers (each with size) to contain 3 types of unknown chunks: +the ones that come before the PLTE chunk, the ones that come between the PLTE +and the IDAT chunks, and the ones that come after the IDAT chunks. +It's necessary to make the distinction between these 3 cases because the PNG +standard forces to keep the ordering of unknown chunks compared to the critical +chunks, but does not force any other ordering rules. + +info_png.unknown_chunks_data[0] is the chunks before PLTE +info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT +info_png.unknown_chunks_data[2] is the chunks after IDAT + +The chunks in these 3 buffers can be iterated through and read by using the same +way described in the previous subchapter. + +When using the decoder to decode a PNG, you can make it store all unknown chunks +if you set the option settings.remember_unknown_chunks to 1. By default, this +option is off (0). + +The encoder will always encode unknown chunks that are stored in the info_png. +If you need it to add a particular chunk that isn't known by LodePNG, you can +use lodepng_chunk_append or lodepng_chunk_create to the chunk data in +info_png.unknown_chunks_data[x]. + +Chunks that are known by LodePNG should not be added in that way. E.g. to make +LodePNG add a bKGD chunk, set background_defined to true and add the correct +parameters there instead. + + +9. compiler support +------------------- + +No libraries other than the current standard C library are needed to compile +LodePNG. For the C++ version, only the standard C++ library is needed on top. +Add the files lodepng.c(pp) and lodepng.h to your project, include +lodepng.h where needed, and your program can read/write PNG files. + +It is compatible with C90 and up, and C++03 and up. + +If performance is important, use optimization when compiling! For both the +encoder and decoder, this makes a large difference. + +Make sure that LodePNG is compiled with the same compiler of the same version +and with the same settings as the rest of the program, or the interfaces with +std::vectors and std::strings in C++ can be incompatible. + +CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. + +*) gcc and g++ + +LodePNG is developed in gcc so this compiler is natively supported. It gives no +warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ +version 4.7.1 on Linux, 32-bit and 64-bit. + +*) Clang + +Fully supported and warning-free. + +*) Mingw + +The Mingw compiler (a port of gcc for Windows) should be fully supported by +LodePNG. + +*) Visual Studio and Visual C++ Express Edition + +LodePNG should be warning-free with warning level W4. Two warnings were disabled +with pragmas though: warning 4244 about implicit conversions, and warning 4996 +where it wants to use a non-standard function fopen_s instead of the standard C +fopen. + +Visual Studio may want "stdafx.h" files to be included in each source file and +give an error "unexpected end of file while looking for precompiled header". +This is not standard C++ and will not be added to the stock LodePNG. You can +disable it for lodepng.cpp only by right clicking it, Properties, C/C++, +Precompiled Headers, and set it to Not Using Precompiled Headers there. + +NOTE: Modern versions of VS should be fully supported, but old versions, e.g. +VS6, are not guaranteed to work. + +*) Compilers on Macintosh + +LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for +C and C++. + +*) Other Compilers + +If you encounter problems on any compilers, feel free to let me know and I may +try to fix it if the compiler is modern and standards compliant. + + +10. examples +------------ + +This decoder example shows the most basic usage of LodePNG. More complex +examples can be found on the LodePNG website. + +10.1. decoder C++ example +------------------------- + +#include "lodepng.h" +#include + +int main(int argc, char *argv[]) { + const char* filename = argc > 1 ? argv[1] : "test.png"; + + //load and decode + std::vector image; + unsigned width, height; + unsigned error = lodepng::decode(image, width, height, filename); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +10.2. decoder C example +----------------------- + +#include "lodepng.h" + +int main(int argc, char *argv[]) { + unsigned error; + unsigned char* image; + size_t width, height; + const char* filename = argc > 1 ? argv[1] : "test.png"; + + error = lodepng_decode32_file(&image, &width, &height, filename); + + if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); + + / * use image here * / + + free(image); + return 0; +} + +11. state settings reference +---------------------------- + +A quick reference of some settings to set on the LodePNGState + +For decoding: + +state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums +state.decoder.zlibsettings.custom_...: use custom inflate function +state.decoder.ignore_crc: ignore CRC checksums +state.decoder.ignore_critical: ignore unknown critical chunks +state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors +state.decoder.color_convert: convert internal PNG color to chosen one +state.decoder.read_text_chunks: whether to read in text metadata chunks +state.decoder.remember_unknown_chunks: whether to read in unknown chunks +state.info_raw.colortype: desired color type for decoded image +state.info_raw.bitdepth: desired bit depth for decoded image +state.info_raw....: more color settings, see struct LodePNGColorMode +state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo + +For encoding: + +state.encoder.zlibsettings.btype: disable compression by setting it to 0 +state.encoder.zlibsettings.use_lz77: use LZ77 in compression +state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize +state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match +state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching +state.encoder.zlibsettings.lazymatching: try one more LZ77 matching +state.encoder.zlibsettings.custom_...: use custom deflate function +state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png +state.encoder.filter_palette_zero: PNG filter strategy for palette +state.encoder.filter_strategy: PNG filter strategy to encode with +state.encoder.force_palette: add palette even if not encoding to one +state.encoder.add_id: add LodePNG identifier and version as a text chunk +state.encoder.text_compression: use compressed text chunks for metadata +state.info_raw.colortype: color type of raw input image you provide +state.info_raw.bitdepth: bit depth of raw input image you provide +state.info_raw: more color settings, see struct LodePNGColorMode +state.info_png.color.colortype: desired color type if auto_convert is false +state.info_png.color.bitdepth: desired bit depth if auto_convert is false +state.info_png.color....: more color settings, see struct LodePNGColorMode +state.info_png....: more PNG related settings, see struct LodePNGInfo + + +12. changes +----------- + +The version number of LodePNG is the date of the change given in the format +yyyymmdd. + +Some changes aren't backwards compatible. Those are indicated with a (!) +symbol. + +Not all changes are listed here, the commit history in github lists more: +https://github.com/lvandeve/lodepng + +*) 06 mar 2020: simplified some of the dynamic memory allocations. +*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct + overflow checks. +*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables. +*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette + if gray ICC profile) and non-ICC LodePNGColorProfile renamed to + LodePNGColorStats. +*) 30 dec 2018: code style changes only: removed newlines before opening braces. +*) 10 sep 2018: added way to inspect metadata chunks without full decoding. +*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use + palette index in case of palette. +*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This + change is backwards compatible unless you relied on unknown_chunks for those. +*) 11 jun 2018: less restrictive check for pixel size integer overflow +*) 14 jan 2018: allow optionally ignoring a few more recoverable errors +*) 17 sep 2017: fix memory leak for some encoder input error cases +*) 27 nov 2016: grey+alpha auto color model detection bugfix +*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). +*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within + the limits of pure C90). +*) 08 dec 2015: Made load_file function return error if file can't be opened. +*) 24 okt 2015: Bugfix with decoding to palette output. +*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. +*) 24 aug 2014: Moved to github +*) 23 aug 2014: Reduced needless memory usage of decoder. +*) 28 jun 2014: Removed fix_png setting, always support palette OOB for + simplicity. Made ColorProfile public. +*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. +*) 22 dec 2013: Power of two windowsize required for optimization. +*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. +*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). +*) 11 mar 2013: (!) Bugfix with custom free. Changed from "my" to "lodepng_" + prefix for the custom allocators and made it possible with a new #define to + use custom ones in your project without needing to change lodepng's code. +*) 28 jan 2013: Bugfix with color key. +*) 27 okt 2012: Tweaks in text chunk keyword length error handling. +*) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode. + (no palette). Better deflate tree encoding. New compression tweak settings. + Faster color conversions while decoding. Some internal cleanups. +*) 23 sep 2012: Reduced warnings in Visual Studio a little bit. +*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions + and made it work with function pointers instead. +*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc + and free functions and toggle #defines from compiler flags. Small fixes. +*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible. +*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed + redundant C++ codec classes. Reduced amount of structs. Everything changed, + but it is cleaner now imho and functionality remains the same. Also fixed + several bugs and shrunk the implementation code. Made new samples. +*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best + PNG color model and bit depth, based on the amount and type of colors of the + raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. +*) 9 okt 2011: simpler hash chain implementation for the encoder. +*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. +*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. + A bug with the PNG filtertype heuristic was fixed, so that it chooses much + better ones (it's quite significant). A setting to do an experimental, slow, + brute force search for PNG filter types is added. +*) 17 aug 2011: (!) changed some C zlib related function names. +*) 16 aug 2011: made the code less wide (max 120 characters per line). +*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. +*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. +*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman + to optimize long sequences of zeros. +*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and + LodePNG_InfoColor_canHaveAlpha functions for convenience. +*) 7 nov 2010: added LodePNG_error_text function to get error code description. +*) 30 okt 2010: made decoding slightly faster +*) 26 okt 2010: (!) changed some C function and struct names (more consistent). + Reorganized the documentation and the declaration order in the header. +*) 08 aug 2010: only changed some comments and external samples. +*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. +*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. +*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could + read by ignoring the problem but windows apps couldn't. +*) 06 jun 2008: added more error checks for out of memory cases. +*) 26 apr 2008: added a few more checks here and there to ensure more safety. +*) 06 mar 2008: crash with encoding of strings fixed +*) 02 feb 2008: support for international text chunks added (iTXt) +*) 23 jan 2008: small cleanups, and #defines to divide code in sections +*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. +*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. +*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added + Also various fixes, such as in the deflate and the padding bits code. +*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved + filtering code of encoder. +*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A + C++ wrapper around this provides an interface almost identical to before. + Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code + are together in these files but it works both for C and C++ compilers. +*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks +*) 30 aug 2007: bug fixed which makes this Borland C++ compatible +*) 09 aug 2007: some VS2005 warnings removed again +*) 21 jul 2007: deflate code placed in new namespace separate from zlib code +*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images +*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing + invalid std::vector element [0] fixed, and level 3 and 4 warnings removed +*) 02 jun 2007: made the encoder add a tag with version by default +*) 27 may 2007: zlib and png code separated (but still in the same file), + simple encoder/decoder functions added for more simple usage cases +*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), + moved some examples from here to lodepng_examples.cpp +*) 12 may 2007: palette decoding bug fixed +*) 24 apr 2007: changed the license from BSD to the zlib license +*) 11 mar 2007: very simple addition: ability to encode bKGD chunks. +*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding + palettized PNG images. Plus little interface change with palette and texts. +*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. + Fixed a bug where the end code of a block had length 0 in the Huffman tree. +*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented + and supported by the encoder, resulting in smaller PNGs at the output. +*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. +*) 24 jan 2007: gave encoder an error interface. Added color conversion from any + greyscale type to 8-bit greyscale with or without alpha. +*) 21 jan 2007: (!) Totally changed the interface. It allows more color types + to convert to and is more uniform. See the manual for how it works now. +*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: + encode/decode custom tEXt chunks, separate classes for zlib & deflate, and + at last made the decoder give errors for incorrect Adler32 or Crc. +*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. +*) 29 dec 2006: Added support for encoding images without alpha channel, and + cleaned out code as well as making certain parts faster. +*) 28 dec 2006: Added "Settings" to the encoder. +*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. + Removed some code duplication in the decoder. Fixed little bug in an example. +*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. + Fixed a bug of the decoder with 16-bit per color. +*) 15 okt 2006: Changed documentation structure +*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the + given image buffer, however for now it's not compressed. +*) 08 sep 2006: (!) Changed to interface with a Decoder class +*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different + way. Renamed decodePNG to decodePNGGeneric. +*) 29 jul 2006: (!) Changed the interface: image info is now returned as a + struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. +*) 28 jul 2006: Cleaned the code and added new error checks. + Corrected terminology "deflate" into "inflate". +*) 23 jun 2006: Added SDL example in the documentation in the header, this + example allows easy debugging by displaying the PNG and its transparency. +*) 22 jun 2006: (!) Changed way to obtain error value. Added + loadFile function for convenience. Made decodePNG32 faster. +*) 21 jun 2006: (!) Changed type of info vector to unsigned. + Changed position of palette in info vector. Fixed an important bug that + happened on PNGs with an uncompressed block. +*) 16 jun 2006: Internally changed unsigned into unsigned where + needed, and performed some optimizations. +*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them + in LodePNG namespace. Changed the order of the parameters. Rewrote the + documentation in the header. Renamed files to lodepng.cpp and lodepng.h +*) 22 apr 2006: Optimized and improved some code +*) 07 sep 2005: (!) Changed to std::vector interface +*) 12 aug 2005: Initial release (C++, decoder only) + + +13. contact information +----------------------- + +Feel free to contact me with suggestions, problems, comments, ... concerning +LodePNG. If you encounter a PNG image that doesn't work properly with this +decoder, feel free to send it and I'll use it to find and fix the problem. + +My email address is (puzzle the account and domain together with an @ symbol): +Domain: gmail dot com. +Account: lode dot vandevenne. + + +Copyright (c) 2005-2020 Lode Vandevenne +*/ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..899a49d8482143f8bdc6be50c350e01064ea5a93 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.cpp @@ -0,0 +1,1765 @@ +/* +LodePNG Utils + +Copyright (c) 2005-2020 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "lodepng_util.h" +#include // TODO: remove, don't print stuff from here, return errors instead +#include /* allocations */ + +namespace lodepng { + +LodePNGInfo getPNGHeaderInfo(const std::vector& png) { + unsigned w, h; + lodepng::State state; + lodepng_inspect(&w, &h, &state, &png[0], png.size()); + return state.info_png; +} + +unsigned getChunkInfo(std::vector& names, std::vector& sizes, + const std::vector& png) { + // Listing chunks is based on the original file, not the decoded png info. + const unsigned char *chunk, *end; + end = &png.back() + 1; + chunk = &png.front() + 8; + + while(chunk < end && end - chunk >= 8) { + char type[5]; + lodepng_chunk_type(type, chunk); + if(std::string(type).size() != 4) return 1; + + unsigned length = lodepng_chunk_length(chunk); + names.push_back(type); + sizes.push_back(length); + chunk = lodepng_chunk_next_const(chunk, end); + } + return 0; +} + +unsigned getChunks(std::vector names[3], + std::vector > chunks[3], + const std::vector& png) { + const unsigned char *chunk, *next, *end; + end = &png.back() + 1; + chunk = &png.front() + 8; + + int location = 0; + + while(chunk < end && end - chunk >= 8) { + char type[5]; + lodepng_chunk_type(type, chunk); + std::string name(type); + if(name.size() != 4) return 1; + + next = lodepng_chunk_next_const(chunk, end); + + if(name == "IHDR") { + location = 0; + } else if(name == "PLTE") { + location = 1; + } else if(name == "IDAT") { + location = 2; + } else if(name == "IEND") { + break; // anything after IEND is not part of the PNG or the 3 groups here. + } else { + if(next >= end) return 1; // invalid chunk, content too far + names[location].push_back(name); + chunks[location].push_back(std::vector(chunk, next)); + } + + chunk = next; + } + return 0; +} + + +unsigned insertChunks(std::vector& png, + const std::vector > chunks[3]) { + const unsigned char *chunk, *begin, *end; + end = &png.back() + 1; + begin = chunk = &png.front() + 8; + + long l0 = 0; //location 0: IHDR-l0-PLTE (or IHDR-l0-l1-IDAT) + long l1 = 0; //location 1: PLTE-l1-IDAT (or IHDR-l0-l1-IDAT) + long l2 = 0; //location 2: IDAT-l2-IEND + + while(chunk < end && end - chunk >= 8) { + char type[5]; + lodepng_chunk_type(type, chunk); + std::string name(type); + if(name.size() != 4) return 1; + + if(name == "PLTE") { + if(l0 == 0) l0 = chunk - begin + 8; + } else if(name == "IDAT") { + if(l0 == 0) l0 = chunk - begin + 8; + if(l1 == 0) l1 = chunk - begin + 8; + } else if(name == "IEND") { + if(l2 == 0) l2 = chunk - begin + 8; + } + + chunk = lodepng_chunk_next_const(chunk, end); + } + + std::vector result; + result.insert(result.end(), png.begin(), png.begin() + l0); + for(size_t i = 0; i < chunks[0].size(); i++) result.insert(result.end(), chunks[0][i].begin(), chunks[0][i].end()); + result.insert(result.end(), png.begin() + l0, png.begin() + l1); + for(size_t i = 0; i < chunks[1].size(); i++) result.insert(result.end(), chunks[1][i].begin(), chunks[1][i].end()); + result.insert(result.end(), png.begin() + l1, png.begin() + l2); + for(size_t i = 0; i < chunks[2].size(); i++) result.insert(result.end(), chunks[2][i].begin(), chunks[2][i].end()); + result.insert(result.end(), png.begin() + l2, png.end()); + + png = result; + return 0; +} + +unsigned getFilterTypesInterlaced(std::vector >& filterTypes, + const std::vector& png) { + //Get color type and interlace type + lodepng::State state; + unsigned w, h; + unsigned error; + error = lodepng_inspect(&w, &h, &state, &png[0], png.size()); + + if(error) return 1; + + //Read literal data from all IDAT chunks + const unsigned char *chunk, *begin, *end; + end = &png.back() + 1; + begin = chunk = &png.front() + 8; + + std::vector zdata; + + while(chunk < end && end - chunk >= 8) { + char type[5]; + lodepng_chunk_type(type, chunk); + if(std::string(type).size() != 4) break; //Probably not a PNG file + + if(std::string(type) == "IDAT") { + const unsigned char* cdata = lodepng_chunk_data_const(chunk); + unsigned clength = lodepng_chunk_length(chunk); + if(chunk + clength + 12 > end || clength > png.size() || chunk + clength + 12 < begin) { + // corrupt chunk length + return 1; + } + + for(unsigned i = 0; i < clength; i++) { + zdata.push_back(cdata[i]); + } + } + + chunk = lodepng_chunk_next_const(chunk, end); + } + + //Decompress all IDAT data (if the while loop ended early, this might fail) + std::vector data; + error = lodepng::decompress(data, &zdata[0], zdata.size()); + + if(error) return 1; + + if(state.info_png.interlace_method == 0) { + filterTypes.resize(1); + + //A line is 1 filter byte + all pixels + size_t linebytes = 1 + lodepng_get_raw_size(w, 1, &state.info_png.color); + + for(size_t i = 0; i < data.size(); i += linebytes) { + filterTypes[0].push_back(data[i]); + } + } else { + //Interlaced + filterTypes.resize(7); + static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ + static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ + static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ + static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ + size_t pos = 0; + for(size_t j = 0; j < 7; j++) { + unsigned w2 = (w - ADAM7_IX[j] + ADAM7_DX[j] - 1) / ADAM7_DX[j]; + unsigned h2 = (h - ADAM7_IY[j] + ADAM7_DY[j] - 1) / ADAM7_DY[j]; + if(ADAM7_IX[j] >= w || ADAM7_IY[j] >= h) continue; + size_t linebytes = 1 + lodepng_get_raw_size(w2, 1, &state.info_png.color); + for(size_t i = 0; i < h2; i++) { + filterTypes[j].push_back(data[pos]); + pos += linebytes; + } + } + } + return 0; /* OK */ +} + + +unsigned getFilterTypes(std::vector& filterTypes, const std::vector& png) { + std::vector > passes; + unsigned error = getFilterTypesInterlaced(passes, png); + if(error) return error; + + if(passes.size() == 1) { + filterTypes.swap(passes[0]); + } else { + // Simplify interlaced filter types to get a single filter value per scanline: + // put pass 6 and 7 alternating in the one vector, these filters + // correspond to the closest to what it would be for non-interlaced + // image. If the image is only 1 pixel wide, pass 6 doesn't exist so the + // alternative values column0 are used. The shift values are to match + // the y position in the interlaced sub-images. + // NOTE: the values 0-6 match Adam7's passes 1-7. + const unsigned column0[8] = {0, 6, 4, 6, 2, 6, 4, 6}; + const unsigned column1[8] = {5, 6, 5, 6, 5, 6, 5, 6}; + const unsigned shift0[8] = {3, 1, 2, 1, 3, 1, 2, 1}; + const unsigned shift1[8] = {1, 1, 1, 1, 1, 1, 1, 1}; + lodepng::State state; + unsigned w, h; + lodepng_inspect(&w, &h, &state, &png[0], png.size()); + const unsigned* column = w > 1 ? column1 : column0; + const unsigned* shift = w > 1 ? shift1 : shift0; + for(size_t i = 0; i < h; i++) { + filterTypes.push_back(passes[column[i & 7u]][i >> shift[i & 7u]]); + } + } + return 0; /* OK */ +} + +int getPaletteValue(const unsigned char* data, size_t i, int bits) { + if(bits == 8) return data[i]; + else if(bits == 4) return (data[i / 2] >> ((i % 2) * 4)) & 15; + else if(bits == 2) return (data[i / 4] >> ((i % 4) * 2)) & 3; + else if(bits == 1) return (data[i / 8] >> (i % 8)) & 1; + else return 0; +} + + +//////////////////////////////////////////////////////////////////////////////// + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + + + +// Only temporarily here until this is integrated into lodepng.c(pp) +#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) + +// Only temporarily here until this is integrated into lodepng.c(pp) +#ifdef LODEPNG_COMPILE_ALLOCATORS +static void* lodepng_malloc(size_t size) { + return malloc(size); +} +static void lodepng_free(void* ptr) { + free(ptr); +} +#else /*LODEPNG_COMPILE_ALLOCATORS*/ +void* lodepng_malloc(size_t size); +void lodepng_free(void* ptr); +#endif /*LODEPNG_COMPILE_ALLOCATORS*/ + +/* avoid needing for FLT_MAX. This assumes IEEE 32-bit float. */ +static const float lodepng_flt_max = 3.40282346638528859811704183484516925e38f; + +/* define infinity and NaN in a way compatible with ANSI C90 (no INFINITY or NAN macros) yet also with visual studio */ +/* visual studio doesn't allow division through a zero literal, but allows it through non-const variable set to zero */ +float lodepng_flt_zero_ = 0.0f; +static const float lodepng_flt_inf = 1.0f / lodepng_flt_zero_; /* infinity */ +static const float lodepng_flt_nan = 0.0f / lodepng_flt_zero_; /* not a number */ + +/* powf polyfill, 5-6 digits accurate, 33% slower than powf, assumes IEEE +32-bit float, but other than that multiplatform and no math lib needed +(note: powf also isn't in ISO C90, and pow is slower). */ +static float lodepng_powf(float x, float y) { + float j, t0, t1; + int i = 0; + /* handle all the special floating point rules */ + if(x == 1 || y == 0) return 1; + if(!(x > 0 && x <= lodepng_flt_max && y == y && y <= lodepng_flt_max && y >= -lodepng_flt_max)) { + if(y == 1) return x; /* preserves negative-0 */ + if(x != x || y != y) return x + y; /* nan */ + if(x > 0) { + if(x > lodepng_flt_max) return y <= 0 ? (y == 0 ? 1 : 0) : x; /* x = +infinity */ + } else { + if(!(y < -1073741824.0f || y > 1073741824.0f)) { /* large y always even integer, but cast would overflow */ + i = (int)y; + if(i != y) { + return (x < -lodepng_flt_max) ? (y < 0 ? 0 : lodepng_flt_inf) : + (x == 0 ? (y < 0 ? lodepng_flt_inf : 0) : lodepng_flt_nan); + } + if(i & 1) return x == 0 ? (y < 0 ? (1 / x) : x) : -lodepng_powf(-x, y); + } + if(x == 0) return y <= 0 ? lodepng_flt_inf : 0; + if(x < -lodepng_flt_max) { /* x == -infinity */ + return y <= 0 ? (y == 0 ? 1 : 0) : ((i & 1) ? + -lodepng_flt_inf : lodepng_flt_inf); + } + x = -x; + if(x == 1) return 1; + } + if(y < -lodepng_flt_max || y > lodepng_flt_max) return ((x < 1) != (y > 0)) ? (y < 0 ? -y : y) : 0; + } + + j = 0; + while(x < (1.0f / 65536)) { j -= 16; x *= 65536.0f; } + while(x > 65536) { j += 16; x *= (1.0f / 65536); } + while(x < 1) { j--; x *= 2.0f; } + while(x > 2) { j++; x *= 0.5f; } + /* polynomial to approximate log2(x) with x in range 1..2 */ + t0 = -0.393118410458557f + x * (-0.0883639468229365f + x * (0.466142650227994f + x * 0.0153397331014276f)); + t1 = 0.0907447971403586f + x * (0.388892024755479f + x * 0.137228280305862f); + x = t0 / t1 + j; + + x *= y; /* using the formula exp2(y * log2(x)) */ + + if(!(x > -128.0f && x < 128.0f)) return x > 0 ? lodepng_flt_inf : 0; /* prevent int overflow */ + i = (int)x; + x -= i; + /* polynomial to approximate exp2(x) with x in range -1..1 */ + t0 = 1.0f + x * (0.41777833582744256f + x * (0.0728482595347711f + x * 0.005635023478609625f)); + t1 = 1.0f + x * (-0.27537016151408167f + x * 0.023501446055084033f); + while(i <= -31) { t0 *= (1.0f / 2147483648.0f); i += 31; } + while(i >= 31) { t0 *= 2147483648.0f; i -= 31; } + return (i < 0) ? (t0 / (t1 * (1 << -i))) : ((t0 * (1 << i)) / t1); +} + +/* Parameters of a tone reproduction curve, either with a power law formula or with a lookup table. */ +typedef struct { + unsigned type; /* 0=linear, 1=lut, 2 = simple gamma, 3-6 = parametric (matches ICC parametric types 1-4) */ + float* lut; /* for type 1 */ + size_t lut_size; + float gamma; /* for type 2 and more */ + float a, b, c, d, e, f; /* parameters for type 3-7 */ +} LodePNGICCCurve; + +void lodepng_icc_curve_init(LodePNGICCCurve* curve) { + curve->lut = 0; + curve->lut_size = 0; +} + +void lodepng_icc_curve_cleanup(LodePNGICCCurve* curve) { + lodepng_free(curve->lut); +} + +/* Values parsed from ICC profile, see parseICC for more information about this subset.*/ +typedef struct { + /* 0 = color model not supported by PNG (CMYK, Lab, ...), 1 = gray, 2 = RGB */ + int inputspace; + int version_major; + int version_minor; + int version_bugfix; + + /* The whitepoint of the profile connection space (PCS). Should always be D50, but parsed and used anyway. + (to be clear, whitepoint and illuminant are synonyms in practice, but here field "illuminant" is ICC's + "global" whitepoint that is always D50, and the field "white" below allows deriving the whitepoint of + the particular RGB space represented here) */ + float illuminant[3]; + + /* if true, has chromatic adaptation matrix that must be used. If false, you must compute a chromatic adaptation + matrix yourself from "illuminant" and "white". */ + unsigned has_chad; + float chad[9]; /* chromatic adaptation matrix, if given */ + + /* The whitepoint of the RGB color space as stored in the ICC file. If has_chad, must be adapted with the + chad matrix to become the one we need to go to absolute XYZ (in fact ICC implies it should then be + exactly D50 in the file, redundantly, before this transformation with chad), else use as-is (then its + values can actually be something else than D50, and are the ones we need). */ + unsigned has_whitepoint; + float white[3]; + /* Chromaticities of the RGB space in XYZ color space, but given such that you must still + whitepoint adapt them from D50 to the RGB space whitepoint to go to absolute XYZ (if has_chad, + with chad, else with bradford adaptation matrix from illuminant to white). */ + unsigned has_chromaticity; + float red[3]; + float green[3]; + float blue[3]; + + unsigned has_trc; /* TRC = tone reproduction curve (aka "gamma correction") */ + + /* TRC's for the three channels (only first one used if grayscale) */ + LodePNGICCCurve trc[3]; +} LodePNGICC; + +void lodepng_icc_init(LodePNGICC* icc) { + lodepng_icc_curve_init(&icc->trc[0]); + lodepng_icc_curve_init(&icc->trc[1]); + lodepng_icc_curve_init(&icc->trc[2]); +} + +void lodepng_icc_cleanup(LodePNGICC* icc) { + lodepng_icc_curve_cleanup(&icc->trc[0]); + lodepng_icc_curve_cleanup(&icc->trc[1]); + lodepng_icc_curve_cleanup(&icc->trc[2]); +} + +/* ICC tone response curve, nonlinear (encoded) to linear. +Input and output in range 0-1. If color was integer 0-255, multiply with (1.0f/255) +to get the correct floating point behavior. +Outside of range 0-1, will not clip but either return x itself, or in cases +where it makes sense, a value defined by the same function. +NOTE: ICC requires clipping, but we do that only later when converting float to integer.*/ +static float iccForwardTRC(const LodePNGICCCurve* curve, float x) { + if(curve->type == 0) { + return x; + } + if(curve->type == 1) { /* Lookup table */ + float v0, v1, fraction; + size_t index; + if(!curve->lut) return 0; /* error */ + if(x < 0) return x; + index = (size_t)(x * (curve->lut_size - 1)); + if(index >= curve->lut_size) return x; + + /* LERP */ + v0 = curve->lut[index]; + v1 = (index + 1 < curve->lut_size) ? curve->lut[index + 1] : 1.0f; + fraction = (x * (curve->lut_size - 1)) - index; + return v0 * (1 - fraction) + v1 * fraction; + } + if(curve->type == 2) { + /* Gamma expansion */ + return (x > 0) ? lodepng_powf(x, curve->gamma) : x; + } + /* TODO: all the ones below are untested */ + if(curve->type == 3) { + if(x < 0) return x; + return x >= (-curve->b / curve->a) ? (lodepng_powf(curve->a * x + curve->b, curve->gamma) + curve->c) : 0; + } + if(curve->type == 4) { + if(x < 0) return x; + return x >= (-curve->b / curve->a) ? (lodepng_powf(curve->a * x + curve->b, curve->gamma) + curve->c) : curve->c; + } + if(curve->type == 5) { + return x >= curve->d ? (lodepng_powf(curve->a * x + curve->b, curve->gamma)) : (curve->c * x); + } + if(curve->type == 6) { + return x >= curve->d ? (lodepng_powf(curve->a * x + curve->b, curve->gamma) + curve->c) : (curve->c * x + curve->f); + } + return 0; +} + +/* ICC tone response curve, linear to nonlinear (encoded). +Input and output in range 0-1. Outside of that range, will not clip but either +return x itself, or in cases where it makes sense, a value defined by the same function. +NOTE: ICC requires clipping, but we do that only later when converting float to integer.*/ +static float iccBackwardTRC(const LodePNGICCCurve* curve, float x) { + if(curve->type == 0) { + return x; + } + if(curve->type == 1) { + size_t a, b, m; + float v; + if(x <= 0) return x; + if(x >= 1) return x; + /* binary search in the table */ + /* TODO: use faster way of inverting the lookup table */ + a = 0; + b = curve->lut_size; + for(;;) { + if(a == b) return curve->lut[a]; + if(a + 1 == b) { + /* LERP */ + float v0 = curve->lut[a]; + float v1 = curve->lut[b]; + float fraction; + if(v0 == v1) return v0; + fraction = (x - v0) / (v1 - v0); + return v0 * (1 - fraction) + v1 * fraction; + } + m = (a + b) / 2u; + v = curve->lut[m]; + if(v > x) { + b = m; + } else { + a = m; + } + } + return 0; + } + if(curve->type == 2) { + /* Gamma compression */ + return (x > 0) ? lodepng_powf(x, 1.0f / curve->gamma) : x; + } + /* TODO: all the ones below are untested */ + if(curve->type == 3) { + if(x < 0) return x; + return x > 0 ? ((lodepng_powf(x, 1.0f / curve->gamma) - curve->b) / curve->a) : (-curve->b / curve->a); + } + if(curve->type == 4) { + if(x < 0) return x; + return x > curve->c ? + ((lodepng_powf(x - curve->c, 1.0f / curve->gamma) - curve->b) / curve->a) : + (-curve->b / curve->a); + } + if(curve->type == 5) { + return x > (curve->c * curve->d) ? + ((lodepng_powf(x, 1.0f / curve->gamma) - curve->b) / curve->a) : + (x / curve->c); + } + if(curve->type == 6) { + return x > (curve->c * curve->d + curve->f) ? + ((lodepng_powf(x - curve->c, 1.0f / curve->gamma) - curve->b) / curve->a) : + ((x - curve->f) / curve->c); + } + return 0; +} + +static unsigned decodeICCUint16(const unsigned char* data, size_t size, size_t* pos) { + *pos += 2; + if (*pos > size) return 0; + return (unsigned)((data[*pos - 2] << 8) | (data[*pos - 1])); +} + +static unsigned decodeICCUint32(const unsigned char* data, size_t size, size_t* pos) { + *pos += 4; + if (*pos > size) return 0; + return (unsigned)((data[*pos - 4] << 24) | (data[*pos - 3] << 16) | (data[*pos - 2] << 8) | (data[*pos - 1] << 0)); +} + +static int decodeICCInt32(const unsigned char* data, size_t size, size_t* pos) { + *pos += 4; + if (*pos > size) return 0; + /*TODO: this is incorrect if sizeof(int) != 4*/ + return (data[*pos - 4] << 24) | (data[*pos - 3] << 16) | (data[*pos - 2] << 8) | (data[*pos - 1] << 0); +} + +static float decodeICC15Fixed16(const unsigned char* data, size_t size, size_t* pos) { + return decodeICCInt32(data, size, pos) / 65536.0; +} + +static unsigned isICCword(const unsigned char* data, size_t size, size_t pos, const char* word) { + if(pos + 4 > size) return 0; + return data[pos + 0] == (unsigned char)word[0] && + data[pos + 1] == (unsigned char)word[1] && + data[pos + 2] == (unsigned char)word[2] && + data[pos + 3] == (unsigned char)word[3]; +} + +/* Parses a subset of the ICC profile, supporting the necessary mix of ICC v2 +and ICC v4 required to correctly convert the RGB color space to XYZ. +Does not parse values not related to this specific PNG-related purpose, and +does not support non-RGB profiles or lookup-table based chroma (but it +supports lookup tables for TRC aka "gamma"). */ +static unsigned parseICC(LodePNGICC* icc, const unsigned char* data, size_t size) { + size_t i, j; + size_t pos = 0; + unsigned version; + unsigned inputspace; + size_t numtags; + + if(size < 132) return 1; /* Too small to be a valid icc profile. */ + + icc->has_chromaticity = 0; + icc->has_whitepoint = 0; + icc->has_trc = 0; + icc->has_chad = 0; + + icc->trc[0].type = icc->trc[1].type = icc->trc[2].type = 0; + icc->white[0] = icc->white[1] = icc->white[2] = 0; + icc->red[0] = icc->red[1] = icc->red[2] = 0; + icc->green[0] = icc->green[1] = icc->green[2] = 0; + icc->blue[0] = icc->blue[1] = icc->blue[2] = 0; + + pos = 8; + version = decodeICCUint32(data, size, &pos); + if(pos >= size) return 1; + icc->version_major = (int)((version >> 24) & 255); + icc->version_minor = (int)((version >> 20) & 15); + icc->version_bugfix = (int)((version >> 16) & 15); + + pos = 16; + inputspace = decodeICCUint32(data, size, &pos); + if(pos >= size) return 1; + if(inputspace == 0x47524159) { + /* The string "GRAY" as unsigned 32-bit int. */ + icc->inputspace = 1; + } else if(inputspace == 0x52474220) { + /* The string "RGB " as unsigned 32-bit int. */ + icc->inputspace = 2; + } else { + /* unsupported by PNG (CMYK, YCbCr, Lab, HSV, ...) */ + icc->inputspace = 0; + } + + /* Should always be 0.9642, 1.0, 0.8249 */ + pos = 68; + icc->illuminant[0] = decodeICC15Fixed16(data, size, &pos); + icc->illuminant[1] = decodeICC15Fixed16(data, size, &pos); + icc->illuminant[2] = decodeICC15Fixed16(data, size, &pos); + + pos = 128; + numtags = decodeICCUint32(data, size, &pos); + if(pos >= size) return 1; + /* scan for tags we want to handle */ + for(i = 0; i < numtags; i++) { + size_t offset; + unsigned tagsize; + size_t namepos = pos; + pos += 4; + offset = decodeICCUint32(data, size, &pos); + tagsize = decodeICCUint32(data, size, &pos); + if(pos >= size || offset >= size) return 1; + if(offset + tagsize > size) return 1; + if(tagsize < 8) return 1; + + if(isICCword(data, size, namepos, "wtpt")) { + offset += 8; /* skip tag and reserved */ + icc->white[0] = decodeICC15Fixed16(data, size, &offset); + icc->white[1] = decodeICC15Fixed16(data, size, &offset); + icc->white[2] = decodeICC15Fixed16(data, size, &offset); + icc->has_whitepoint = 1; + } else if(isICCword(data, size, namepos, "rXYZ")) { + offset += 8; /* skip tag and reserved */ + icc->red[0] = decodeICC15Fixed16(data, size, &offset); + icc->red[1] = decodeICC15Fixed16(data, size, &offset); + icc->red[2] = decodeICC15Fixed16(data, size, &offset); + icc->has_chromaticity = 1; + } else if(isICCword(data, size, namepos, "gXYZ")) { + offset += 8; /* skip tag and reserved */ + icc->green[0] = decodeICC15Fixed16(data, size, &offset); + icc->green[1] = decodeICC15Fixed16(data, size, &offset); + icc->green[2] = decodeICC15Fixed16(data, size, &offset); + icc->has_chromaticity = 1; + } else if(isICCword(data, size, namepos, "bXYZ")) { + offset += 8; /* skip tag and reserved */ + icc->blue[0] = decodeICC15Fixed16(data, size, &offset); + icc->blue[1] = decodeICC15Fixed16(data, size, &offset); + icc->blue[2] = decodeICC15Fixed16(data, size, &offset); + icc->has_chromaticity = 1; + } else if(isICCword(data, size, namepos, "chad")) { + offset += 8; /* skip datatype keyword "sf32" and reserved */ + for(j = 0; j < 9; j++) { + icc->chad[j] = decodeICC15Fixed16(data, size, &offset); + } + icc->has_chad = 1; + } else if(isICCword(data, size, namepos, "rTRC") || + isICCword(data, size, namepos, "gTRC") || + isICCword(data, size, namepos, "bTRC") || + isICCword(data, size, namepos, "kTRC")) { + char c = (char)data[namepos]; + /* both 'k' and 'r' are stored in channel 0 */ + int channel = (c == 'b') ? 2 : (c == 'g' ? 1 : 0); + /* "curv": linear, gamma power or LUT */ + if(isICCword(data, size, offset, "curv")) { + size_t count; + LodePNGICCCurve* trc = &icc->trc[channel]; + icc->has_trc = 1; + offset += 8; /* skip tag "curv" and reserved */ + count = decodeICCUint32(data, size, &offset); + if(count == 0) { + trc->type = 0; /* linear */ + } else if(count == 1) { + trc->type = 2; /* gamma */ + trc->gamma = decodeICCUint16(data, size, &offset) / 256.0f; + } else { + trc->type = 1; /* LUT */ + if(offset + count * 2 > size || count > 16777216) return 1; /* also avoid crazy count */ + trc->lut_size = count; + trc->lut = (float*)lodepng_malloc(count * sizeof(float)); + for(j = 0; j < count; j++) { + trc->lut[j] = decodeICCUint16(data, size, &offset) * (1.0f / 65535.0f); + } + } + } + /* "para": parametric formula with gamma power, multipliers, biases and comparison point */ + /* TODO: test this on a realistic sample */ + if(isICCword(data, size, offset, "para")) { + unsigned type; + LodePNGICCCurve* trc = &icc->trc[channel]; + icc->has_trc = 1; + offset += 8; /* skip tag "para" and reserved */ + type = decodeICCUint16(data, size, &offset); + offset += 2; + if(type > 4) return 1; /* unknown parametric curve type */ + trc->type = type + 2; + trc->gamma = decodeICC15Fixed16(data, size, &offset); + if(type >= 1) { + trc->a = decodeICC15Fixed16(data, size, &offset); + trc->b = decodeICC15Fixed16(data, size, &offset); + } + if(type >= 2) { + trc->c = decodeICC15Fixed16(data, size, &offset); + } + if(type >= 3) { + trc->d = decodeICC15Fixed16(data, size, &offset); + } + if(type == 4) { + trc->e = decodeICC15Fixed16(data, size, &offset); + trc->f = decodeICC15Fixed16(data, size, &offset); + } + } + /* TODO: verify: does the "chrm" tag participate in computation so should be parsed? */ + } + /* Return error if any parse went beyond the filesize. Note that the + parsing itself was always safe since it bound-checks inside. */ + if(offset > size) return 1; + } + + return 0; +} + +/* Multiplies 3 vector values with 3x3 matrix */ +static void mulMatrix(float* x2, float* y2, float* z2, const float* m, double x, double y, double z) { + /* double used as inputs even though in general the images are float, so the sums happen in + double precision, because float can give numerical problems for nearby values */ + *x2 = x * m[0] + y * m[1] + z * m[2]; + *y2 = x * m[3] + y * m[4] + z * m[5]; + *z2 = x * m[6] + y * m[7] + z * m[8]; +} + +static void mulMatrixMatrix(float* result, const float* a, const float* b) { + int i; + float temp[9]; /* temp is to allow result and a or b to be the same */ + mulMatrix(&temp[0], &temp[3], &temp[6], a, b[0], b[3], b[6]); + mulMatrix(&temp[1], &temp[4], &temp[7], a, b[1], b[4], b[7]); + mulMatrix(&temp[2], &temp[5], &temp[8], a, b[2], b[5], b[8]); + for(i = 0; i < 9; i++) result[i] = temp[i]; +} + +/* Inverts 3x3 matrix in place */ +static unsigned invMatrix(float* m) { + int i; + /* double used instead of float for intermediate computations to avoid + intermediate numerical precision issues */ + double e0 = (double)m[4] * m[8] - (double)m[5] * m[7]; + double e3 = (double)m[5] * m[6] - (double)m[3] * m[8]; + double e6 = (double)m[3] * m[7] - (double)m[4] * m[6]; + /* inverse determinant */ + double d = 1.0 / (m[0] * e0 + m[1] * e3 + m[2] * e6); + float result[9]; + if((d > 0 ? d : -d) > 1e15) return 1; /* error, likely not invertible */ + result[0] = e0 * d; + result[1] = ((double)m[2] * m[7] - (double)m[1] * m[8]) * d; + result[2] = ((double)m[1] * m[5] - (double)m[2] * m[4]) * d; + result[3] = e3 * d; + result[4] = ((double)m[0] * m[8] - (double)m[2] * m[6]) * d; + result[5] = ((double)m[3] * m[2] - (double)m[0] * m[5]) * d; + result[6] = e6 * d; + result[7] = ((double)m[6] * m[1] - (double)m[0] * m[7]) * d; + result[8] = ((double)m[0] * m[4] - (double)m[3] * m[1]) * d; + for(i = 0; i < 9; i++) m[i] = result[i]; + return 0; /* ok */ +} + +/* Get the matrix to go from linear RGB to XYZ given the RGB whitepoint and chromaticities in XYZ colorspace */ +static unsigned getChrmMatrixXYZ(float* m, + float wX, float wY, float wZ, + float rX, float rY, float rZ, + float gX, float gY, float gZ, + float bX, float bY, float bZ) { + float t[9]; + float rs, gs, bs; + t[0] = rX; t[1] = gX; t[2] = bX; + t[3] = rY; t[4] = gY; t[5] = bY; + t[6] = rZ; t[7] = gZ; t[8] = bZ; + if(invMatrix(t)) return 1; /* error, not invertible */ + mulMatrix(&rs, &gs, &bs, t, wX, wY, wZ); + m[0] = rs * rX; m[1] = gs * gX; m[2] = bs * bX; + m[3] = rs * rY; m[4] = gs * gY; m[5] = bs * bY; + m[6] = rs * rZ; m[7] = gs * gZ; m[8] = bs * bZ; + return 0; +} + +/* Get the matrix to go from linear RGB to XYZ given the RGB whitepoint and chromaticities in xy colorspace */ +static unsigned getChrmMatrixXY(float* m, + float wx, float wy, + float rx, float ry, + float gx, float gy, + float bx, float by) { + if(wy == 0 || ry == 0 || gy == 0 || by == 0) { + return 1; /* error, division through zero */ + } else { + float wX = wx / wy, wY = 1, wZ = (1 - wx - wy) / wy; + float rX = rx / ry, rY = 1, rZ = (1 - rx - ry) / ry; + float gX = gx / gy, gY = 1, gZ = (1 - gx - gy) / gy; + float bX = bx / by, bY = 1, bZ = (1 - bx - by) / by; + return getChrmMatrixXYZ(m, wX, wY, wZ, rX, rY, rZ, gX, gY, gZ, bX, bY, bZ); + } +} + +/* Returns matrix that adapts from source whitepoint 0 to destination whitepoint 1. +Types: 0=XYZ scaling, 1=Bradford, 2=Vonkries */ +static unsigned getAdaptationMatrix(float* m, int type, + float wx0, float wy0, float wz0, + float wx1, float wy1, float wz1) { + int i; + static const float bradford[9] = { + 0.8951, 0.2664, -0.1614, + -0.7502, 1.7135, 0.0367, + 0.0389, -0.0685, 1.0296 + }; + static const float bradfordinv[9] = { + 0.9869929, -0.1470543, 0.1599627, + 0.4323053, 0.5183603, 0.0492912, + -0.0085287, 0.0400428, 0.9684867 + }; + static const float vonkries[9] = { + 0.40024, 0.70760, -0.08081, + -0.22630, 1.16532, 0.04570, + 0.00000, 0.00000, 0.91822, + }; + static const float vonkriesinv[9] = { + 1.8599364, -1.1293816, 0.2198974, + 0.3611914, 0.6388125, -0.0000064, + 0.0000000, 0.0000000, 1.0890636 + }; + if(type == 0) { + for(i = 0; i < 9; i++) m[i] = 0; + m[0] = wx1 / wx0; + m[4] = wy1 / wy0; + m[8] = wz1 / wz0; + } else { + const float* cat = (type == 1) ? bradford : vonkries; + const float* inv = (type == 1) ? bradfordinv : vonkriesinv; + float rho0, gam0, bet0, rho1, gam1, bet1, rho2, gam2, bet2; + mulMatrix(&rho0, &gam0, &bet0, cat, wx0, wy0, wz0); + mulMatrix(&rho1, &gam1, &bet1, cat, wx1, wy1, wz1); + rho2 = rho1 / rho0; + gam2 = gam1 / gam0; + bet2 = bet1 / bet0; + /* Multiply diagonal matrix with cat */ + for(i = 0; i < 3; i++) { + m[i + 0] = rho2 * cat[i + 0]; + m[i + 3] = gam2 * cat[i + 3]; + m[i + 6] = bet2 * cat[i + 6]; + } + mulMatrixMatrix(m, inv, m); + } + return 0; /* ok */ +} + +/* validate whether the ICC profile is supported here for PNG */ +static unsigned validateICC(const LodePNGICC* icc) { + /* disable for unsupported things in the icc profile */ + if(icc->inputspace == 0) return 0; + /* if we didn't recognize both chrm and trc, then maybe the ICC uses data + types not supported here yet, so fall back to not using it. */ + if(icc->inputspace == 2) { + /* RGB profile should have chromaticities */ + if(!icc->has_chromaticity) return 0; + } + /* An ICC profile without whitepoint is invalid for the kind of profiles used here. */ + if(!icc->has_whitepoint) return 0; + if(!icc->has_trc) return 0; + return 1; /* ok */ +} + +/* Returns chromaticity matrix for given ICC profile, adapted from ICC's +global illuminant as necessary. +Also returns the profile's whitepoint. +In case of a gray profile (icc->inputspace == 1), the identity matrix will be returned +so in that case you could skip the transform. */ +static unsigned getICCChrm(float m[9], float whitepoint[3], const LodePNGICC* icc) { + size_t i; + if(icc->inputspace == 2) { /* RGB profile */ + float red[3], green[3], blue[3]; + float white[3]; /* the whitepoint of the RGB color space (absolute) */ + /* Adaptation matrix a. + This is an adaptation needed for ICC's file format (due to it using + an internal global illuminant unrelated to the actual images) */ + float a[9] = {1,0,0, 0,1,0, 0,0,1}; + /* If the profile has chromatic adaptation matrix "chad", use that one, + else compute it from the illuminant and whitepoint. */ + if(icc->has_chad) { + for(i = 0; i < 9; i++) a[i] = icc->chad[i]; + invMatrix(a); + } else { + if(getAdaptationMatrix(a, 1, icc->illuminant[0], icc->illuminant[1], icc->illuminant[2], + icc->white[0], icc->white[1], icc->white[2])) { + return 1; /* error computing matrix */ + } + } + /* If the profile has a chad, then also the RGB's whitepoint must also be adapted from it (and the one + given is normally D50). If it did not have a chad, then the whitepoint given is already the adapted one. */ + if(icc->has_chad) { + mulMatrix(&white[0], &white[1], &white[2], a, icc->white[0], icc->white[1], icc->white[2]); + } else { + for(i = 0; i < 3; i++) white[i] = icc->white[i]; + } + + mulMatrix(&red[0], &red[1], &red[2], a, icc->red[0], icc->red[1], icc->red[2]); + mulMatrix(&green[0], &green[1], &green[2], a, icc->green[0], icc->green[1], icc->green[2]); + mulMatrix(&blue[0], &blue[1], &blue[2], a, icc->blue[0], icc->blue[1], icc->blue[2]); + + if(getChrmMatrixXYZ(m, white[0], white[1], white[2], red[0], red[1], red[2], + green[0], green[1], green[2], blue[0], blue[1], blue[2])) { + return 1; /* error computing matrix */ + } + /* output absolute whitepoint of the original RGB model */ + whitepoint[0] = white[0]; + whitepoint[1] = white[1]; + whitepoint[2] = white[2]; + } else { + /* output the unity matrix, for doing no transform */ + m[0] = m[4] = m[8] = 1; + m[1] = m[2] = m[3] = m[5] = m[6] = m[7] = 0; + /* grayscale, don't do anything. That means we are implicitely using equal energy whitepoint "E", indicate + this to the output. */ + whitepoint[0] = whitepoint[1] = whitepoint[2] = 1; + } + return 0; /* success */ +} + +/* Outputs whitepoint and matrix to go from the icc or info profile (depending on what was in the PNG) to XYZ, +without applying any (rendering intent related) whitepoint adaptation */ +static unsigned getChrm(float m[9], float whitepoint[3], unsigned use_icc, + const LodePNGICC* icc, const LodePNGInfo* info) { + size_t i; + if(use_icc) { + if(getICCChrm(m, whitepoint, icc)) return 1; /* error in the matrix computations */ + } else if(info->chrm_defined && !info->srgb_defined) { + float wx = info->chrm_white_x / 100000.0f, wy = info->chrm_white_y / 100000.0f; + float rx = info->chrm_red_x / 100000.0f, ry = info->chrm_red_y / 100000.0f; + float gx = info->chrm_green_x / 100000.0f, gy = info->chrm_green_y / 100000.0f; + float bx = info->chrm_blue_x / 100000.0f, by = info->chrm_blue_y / 100000.0f; + if(getChrmMatrixXY(m, wx, wy, rx, ry, gx, gy, bx, by)) return 1; /* returns if error */ + /* Output whitepoint, xyY to XYZ: */ + whitepoint[0] = wx / wy; + whitepoint[1] = 1; + whitepoint[2] = (1 - wx - wy) / wy; + } else { + /* the standard linear sRGB to XYZ matrix */ + static const float srgb[9] = { + 0.4124564f, 0.3575761f, 0.1804375f, + 0.2126729f, 0.7151522f, 0.0721750f, + 0.0193339f, 0.1191920f, 0.9503041f + }; + for(i = 0; i < 9; i++) m[i] = srgb[i]; + /* sRGB's whitepoint xyY "0.3127,0.3290,1" in XYZ: */ + whitepoint[0] = 0.9504559270516716f; + whitepoint[1] = 1; + whitepoint[2] = 1.0890577507598784f; + } + return 0; +} + +/* Returns whether the color chunks in info represent the default PNG sRGB, +which is when either no colorometry fields are present at all, or an srgb +field or chrm/gama field with default values are present. +ICC chunks representing sRGB are currently considered not the same. */ +static unsigned isSRGB(const LodePNGInfo* info) { + if(!info) return 1; /* the default is considered sRGB. */ + + /* TODO: support some ICC profiles that represent sRGB too. Tricky due to + possible slight deviations and many ways of representing its gamma function. */ + if(info->iccp_defined) return 0; + + if(info->srgb_defined) return 1; + + /* The gamma chunk is unable to represent sRGB's two-part gamma, so cannot + be sRGB, even if it's the default 45455. */ + if(info->gama_defined) return 0; + + if(info->chrm_defined) { + if(info->chrm_white_x != 31270 || info->chrm_white_y != 32900) return 0; + if(info->chrm_red_x != 64000 || info->chrm_red_y != 33000) return 0; + if(info->chrm_green_x != 30000 || info->chrm_green_y != 60000) return 0; + if(info->chrm_blue_x != 15000 || info->chrm_blue_y != 6000) return 0; + } + + return 1; +} + +/* Checks whether the RGB models are equal (chromaticities, ...). The raw byte +format is allowed to be different. Input pointers are allowed to be null, +they then represent the default PNG sRGB (same as having no color model +chunks at all or an srgb chunk in the PNG) */ +static unsigned modelsEqual(const LodePNGState* state_a, + const LodePNGState* state_b) { + size_t i; + const LodePNGInfo* a = state_a ? &state_a->info_png : 0; + const LodePNGInfo* b = state_b ? &state_b->info_png : 0; + if(isSRGB(a) != isSRGB(b)) return 0; + /* now a and b are guaranteed to be non-NULL */ + if(a->iccp_defined != b->iccp_defined) return 0; + if(a->iccp_defined) { + if(a->iccp_profile_size != b->iccp_profile_size) return 0; + /* TODO: return equal in more cases, such as when two ICC profiles that are + not byte-for-byte equal, but represent the same color model. */ + for(i = 0; i < a->iccp_profile_size; i++) { + if(a->iccp_profile[i] != b->iccp_profile[i]) return 0; + } + /* since the ICC model overrides gamma and chrm, those can be ignored. */ + /* TODO: this doesn't cover the case where the ICC profile is invalid */ + return 1; + } + + if(a->srgb_defined != b->srgb_defined) return 0; + if(a->srgb_defined) { + /* since the sRGB model overrides gamma and chrm, those can be ignored. + srgb_intent not checked since the conversion ignores it */ + return 1; + } + + if(a->gama_defined != b->gama_defined) return 0; + if(a->gama_defined) { + if(a->gama_gamma != b->gama_gamma) return 0; + } + + if(a->chrm_defined != b->chrm_defined) return 0; + if(a->chrm_defined) { + if(a->chrm_white_x != b->chrm_white_x) return 0; + if(a->chrm_white_y != b->chrm_white_y) return 0; + if(a->chrm_red_x != b->chrm_red_x) return 0; + if(a->chrm_red_y != b->chrm_red_y) return 0; + if(a->chrm_green_x != b->chrm_green_x) return 0; + if(a->chrm_green_y != b->chrm_green_y) return 0; + if(a->chrm_blue_x != b->chrm_blue_x) return 0; + if(a->chrm_blue_y != b->chrm_blue_y) return 0; + } + + return 1; +} + +/* Converts in-place. Does not clamp. Do not use for integer input, make table instead there. */ +static void convertToXYZ_gamma(float* out, const float* in, unsigned w, unsigned h, + const LodePNGInfo* info, unsigned use_icc, const LodePNGICC* icc) { + size_t i, c; + size_t n = w * h; + for(i = 0; i < n * 4; i++) { + out[i] = in[i]; + } + if(use_icc) { + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + /* TODO: this is likely very slow */ + out[i * 4 + c] = iccForwardTRC(&icc->trc[c], in[i * 4 + c]); + } + } + } else if(info->gama_defined && !info->srgb_defined) { + /* nothing to do if gamma is 1 */ + if(info->gama_gamma != 100000) { + float gamma = 100000.0f / info->gama_gamma; + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + float v = in[i * 4 + c]; + out[i * 4 + c] = (v <= 0) ? v : lodepng_powf(v, gamma); + } + } + } + } else { + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + /* sRGB gamma expand */ + float v = in[i * 4 + c]; + out[i * 4 + c] = (v < 0.04045f) ? (v / 12.92f) : lodepng_powf((v + 0.055f) / 1.055f, 2.4f); + } + } + } +} + +/* Same as convertToXYZ_gamma, but creates a lookup table rather than operating on an image */ +static void convertToXYZ_gamma_table(float* out, size_t n, size_t c, + const LodePNGInfo* info, unsigned use_icc, const LodePNGICC* icc) { + size_t i; + float mul = 1.0f / (n - 1); + if(use_icc) { + for(i = 0; i < n; i++) { + float v = i * mul; + out[i] = iccForwardTRC(&icc->trc[c], v); + } + } else if(info->gama_defined && !info->srgb_defined) { + /* no power needed if gamma is 1 */ + if(info->gama_gamma == 100000) { + for(i = 0; i < n; i++) { + out[i] = i * mul; + } + } else { + float gamma = 100000.0f / info->gama_gamma; + for(i = 0; i < n; i++) { + float v = i * mul; + out[i] = lodepng_powf(v, gamma); + } + } + } else { + for(i = 0; i < n; i++) { + /* sRGB gamma expand */ + float v = i * mul; + out[i] = (v < 0.04045f) ? (v / 12.92f) : lodepng_powf((v + 0.055f) / 1.055f, 2.4f); + } + } +} + +/* In-place */ +static unsigned convertToXYZ_chrm(float* im, unsigned w, unsigned h, + const LodePNGInfo* info, unsigned use_icc, const LodePNGICC* icc, + float whitepoint[3]) { + unsigned error = 0; + size_t i; + size_t n = w * h; + float m[9]; /* XYZ to linear RGB matrix */ + + /* Must be called even for grayscale, to get the correct whitepoint to output */ + error = getChrm(m, whitepoint, use_icc, icc, info); + if(error) return error; + + /* Note: no whitepoint adaptation done to m here, because we only do the + adaptation in convertFromXYZ (we only whitepoint adapt when going to the + target RGB space, but here we're going from the source RGB space to XYZ) */ + + /* Apply the above computed linear-RGB-to-XYZ matrix to the pixels. + Skip the transform if it's the unit matrix (which is the case if grayscale profile) */ + if(!use_icc || icc->inputspace == 2) { + for(i = 0; i < n; i++) { + size_t j = i * 4; + mulMatrix(&im[j + 0], &im[j + 1], &im[j + 2], m, im[j + 0], im[j + 1], im[j + 2]); + } + } + + return 0; +} + +unsigned convertToXYZ(float* out, float whitepoint[3], const unsigned char* in, + unsigned w, unsigned h, const LodePNGState* state) { + unsigned error = 0; + size_t i; + size_t n = w * h; + const LodePNGColorMode* mode_in = &state->info_raw; + const LodePNGInfo* info = &state->info_png; + unsigned char* data = 0; + float* gammatable = 0; + int bit16 = mode_in->bitdepth > 8; + size_t num = bit16 ? 65536 : 256; + LodePNGColorMode tempmode = lodepng_color_mode_make(LCT_RGBA, bit16 ? 16 : 8); + + + unsigned use_icc = 0; + LodePNGICC icc; + lodepng_icc_init(&icc); + if(info->iccp_defined) { + error = parseICC(&icc, info->iccp_profile, info->iccp_profile_size); + if(error) goto cleanup; /* corrupted ICC profile */ + use_icc = validateICC(&icc); + } + + data = (unsigned char*)lodepng_malloc(w * h * (bit16 ? 8 : 4)); + error = lodepng_convert(data, in, &tempmode, mode_in, w, h); + if(error) goto cleanup; + + /* Handle transfer function */ + { + float* gammatable_r; + float* gammatable_g; + float* gammatable_b; + + /* RGB ICC, can have three different transfer functions */ + if(use_icc && icc.inputspace == 2) { + gammatable = (float*)lodepng_malloc(num * 3 * sizeof(float)); + gammatable_r = &gammatable[num * 0]; + gammatable_g = &gammatable[num * 1]; + gammatable_b = &gammatable[num * 2]; + convertToXYZ_gamma_table(gammatable_r, num, 0, info, use_icc, &icc); + convertToXYZ_gamma_table(gammatable_g, num, 1, info, use_icc, &icc); + convertToXYZ_gamma_table(gammatable_b, num, 2, info, use_icc, &icc); + } else { + gammatable = (float*)lodepng_malloc(num * sizeof(float)); + gammatable_r = gammatable_g = gammatable_b = gammatable; + convertToXYZ_gamma_table(gammatable, num, 0, info, use_icc, &icc); + } + + if(bit16) { + for(i = 0; i < n; i++) { + out[i * 4 + 0] = gammatable_r[data[i * 8 + 0] * 256u + data[i * 8 + 1]]; + out[i * 4 + 1] = gammatable_g[data[i * 8 + 2] * 256u + data[i * 8 + 3]]; + out[i * 4 + 2] = gammatable_b[data[i * 8 + 4] * 256u + data[i * 8 + 5]]; + out[i * 4 + 3] = (data[i * 8 + 6] * 256 + data[i * 8 + 7]) * (1 / 65535.0f); + } + } else { + for(i = 0; i < n; i++) { + out[i * 4 + 0] = gammatable_r[data[i * 4 + 0]]; + out[i * 4 + 1] = gammatable_g[data[i * 4 + 1]]; + out[i * 4 + 2] = gammatable_b[data[i * 4 + 2]]; + out[i * 4 + 3] = data[i * 4 + 3] * (1 / 255.0f); + } + } + } + + convertToXYZ_chrm(out, w, h, info, use_icc, &icc, whitepoint); + +cleanup: + lodepng_icc_cleanup(&icc); + lodepng_free(data); + lodepng_free(gammatable); + return error; +} + +unsigned convertToXYZFloat(float* out, float whitepoint[3], const float* in, + unsigned w, unsigned h, const LodePNGState* state) { + unsigned error = 0; + const LodePNGInfo* info = &state->info_png; + + unsigned use_icc = 0; + LodePNGICC icc; + lodepng_icc_init(&icc); + if(info->iccp_defined) { + error = parseICC(&icc, info->iccp_profile, info->iccp_profile_size); + if(error) goto cleanup; /* corrupted ICC profile */ + use_icc = validateICC(&icc); + } + /* Input is floating point, so lookup table cannot be used, but it's ensured to + use float pow, not the slower double pow. */ + convertToXYZ_gamma(out, in, w, h, info, use_icc, &icc); + convertToXYZ_chrm(out, w, h, info, use_icc, &icc, whitepoint); + +cleanup: + lodepng_icc_cleanup(&icc); + return error; +} + +static unsigned convertFromXYZ_chrm(float* out, const float* in, unsigned w, unsigned h, + const LodePNGInfo* info, unsigned use_icc, const LodePNGICC* icc, + const float whitepoint[3], unsigned rendering_intent) { + size_t i; + size_t n = w * h; + + float m[9]; /* XYZ to linear RGB matrix */ + float white[3]; /* The whitepoint (absolute) of the target RGB space */ + + if(getChrm(m, white, use_icc, icc, info)) return 1; + if(invMatrix(m)) return 1; /* error, not invertible */ + + /* for relative rendering intent (any except absolute "3"), must whitepoint adapt to the original whitepoint. + this also ensures grayscale stays grayscale (with absolute, grayscale could become e.g. blue or sepia) */ + if(rendering_intent != 3) { + float a[9] = {1,0,0, 0,1,0, 0,0,1}; + /* "white" = absolute whitepoint of the new target RGB space, read from the target color profile. + "whitepoint" is original absolute whitepoint (input as parameter of this function) of an + RGB space the XYZ data once had before it was converted to XYZ, in other words the whitepoint that + we want to adapt our current data to to make sure values that had equal R==G==B in the old space have + the same property now (white stays white and gray stays gray). + Note: "absolute" whitepoint above means, can be used as-is, not needing further adaptation itself like icc.white does.*/ + if(getAdaptationMatrix(a, 1, whitepoint[0], whitepoint[1], whitepoint[2], white[0], white[1], white[2])) { + return 1; + } + /* multiply the from xyz matrix with the adaptation matrix: in total, + the resulting matrix first adapts in XYZ space, then converts to RGB*/ + mulMatrixMatrix(m, m, a); + } + + /* Apply the above computed XYZ-to-linear-RGB matrix to the pixels. + This transformation also includes the whitepoint adaptation. The transform + can be skipped only if it's the unit matrix (only if grayscale profile and no + whitepoint adaptation, such as with rendering intent 3)*/ + if(!use_icc || icc->inputspace == 2 || rendering_intent != 3) { + for(i = 0; i < n; i++) { + size_t j = i * 4; + mulMatrix(&out[j + 0], &out[j + 1], &out[j + 2], m, in[j + 0], in[j + 1], in[j + 2]); + out[j + 3] = in[j + 3]; + } + } else { + for(i = 0; i < n * 4; i++) { + out[i] = in[i]; + } + } + + return 0; +} + +/* Converts in-place. Does not clamp. */ +static void convertFromXYZ_gamma(float* im, unsigned w, unsigned h, + const LodePNGInfo* info, unsigned use_icc, const LodePNGICC* icc) { + size_t i, c; + size_t n = w * h; + if(use_icc) { + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + /* TODO: this is likely very slow */ + im[i * 4 + c] = iccBackwardTRC(&icc->trc[c], im[i * 4 + c]); + } + } + } else if(info->gama_defined && !info->srgb_defined) { + /* nothing to do if gamma is 1 */ + if(info->gama_gamma != 100000) { + float gamma = info->gama_gamma / 100000.0f; + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + if(im[i * 4 + c] > 0) im[i * 4 + c] = lodepng_powf(im[i * 4 + c], gamma); + } + } + } + } else { + for(i = 0; i < n; i++) { + for(c = 0; c < 3; c++) { + /* sRGB gamma compress */ + float* v = &im[i * 4 + c]; + *v = (*v < 0.0031308f) ? (*v * 12.92f) : (1.055f * lodepng_powf(*v, 1 / 2.4f) - 0.055f); + } + } + } +} + +unsigned convertFromXYZ(unsigned char* out, const float* in, unsigned w, unsigned h, + const LodePNGState* state, + const float whitepoint[3], unsigned rendering_intent) { + unsigned error = 0; + size_t i, c; + size_t n = w * h; + const LodePNGColorMode* mode_out = &state->info_raw; + const LodePNGInfo* info = &state->info_png; + int bit16 = mode_out->bitdepth > 8; + float* im = 0; + unsigned char* data = 0; + + /* parse ICC if present */ + unsigned use_icc = 0; + LodePNGICC icc; + lodepng_icc_init(&icc); + if(info->iccp_defined) { + error = parseICC(&icc, info->iccp_profile, info->iccp_profile_size); + if(error) goto cleanup; /* corrupted ICC profile */ + use_icc = validateICC(&icc); + } + + /* Handle gamut */ + im = (float*)lodepng_malloc(w * h * 4 * sizeof(float)); + error = convertFromXYZ_chrm(im, in, w, h, info, use_icc, &icc, whitepoint, rendering_intent); + if(error) goto cleanup; + + /* Handle transfer function */ + /* Input is floating point, so lookup table cannot be used, but it's ensured to use float pow, not the slower double pow. */ + convertFromXYZ_gamma(im, w, h, info, use_icc, &icc); + + /* Convert to integer output */ + data = (unsigned char*)lodepng_malloc(w * h * 8); + /* TODO: check if also 1/2/4 bit case needed: rounding is at different fine-grainedness for 8 and 16 bits below. */ + if(bit16) { + LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGBA, 16); + for(i = 0; i < n; i++) { + for(c = 0; c < 4; c++) { + size_t j = i * 8 + c * 2; + int i16 = (int)(0.5f + 65535.0f * LODEPNG_MIN(LODEPNG_MAX(0.0f, im[i * 4 + c]), 1.0f)); + data[j + 0] = i16 >> 8; + data[j + 1] = i16 & 255; + } + } + error = lodepng_convert(out, data, mode_out, &mode16, w, h); + if(error) goto cleanup; + } else { + LodePNGColorMode mode8 = lodepng_color_mode_make(LCT_RGBA, 8); + for(i = 0; i < n; i++) { + for(c = 0; c < 4; c++) { + int i8 = (int)(0.5f + 255.0f * LODEPNG_MIN(LODEPNG_MAX(0.0f, im[i * 4 + c]), 1.0f)); + data[i * 4 + c] = i8; + } + } + error = lodepng_convert(out, data, mode_out, &mode8, w, h); + if(error) goto cleanup; + } + +cleanup: + lodepng_icc_cleanup(&icc); + lodepng_free(im); + lodepng_free(data); + return error; +} + +unsigned convertFromXYZFloat(float* out, const float* in, unsigned w, unsigned h, + const LodePNGState* state, + const float whitepoint[3], unsigned rendering_intent) { + unsigned error = 0; + const LodePNGInfo* info = &state->info_png; + + /* parse ICC if present */ + unsigned use_icc = 0; + LodePNGICC icc; + lodepng_icc_init(&icc); + if(info->iccp_defined) { + error = parseICC(&icc, info->iccp_profile, info->iccp_profile_size); + if(error) goto cleanup; /* corrupted ICC profile */ + use_icc = validateICC(&icc); + } + + /* Handle gamut */ + error = convertFromXYZ_chrm(out, in, w, h, info, use_icc, &icc, whitepoint, rendering_intent); + if(error) goto cleanup; + + /* Handle transfer function */ + convertFromXYZ_gamma(out, w, h, info, use_icc, &icc); + +cleanup: + lodepng_icc_cleanup(&icc); + return error; +} + +unsigned convertRGBModel(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_out, + const LodePNGState* state_in, + unsigned rendering_intent) { + if(modelsEqual(state_in, state_out)) { + return lodepng_convert(out, in, &state_out->info_raw, &state_in->info_raw, w, h); + } else { + unsigned error = 0; + float* xyz = (float*)lodepng_malloc(w * h * 4 * sizeof(float)); + float whitepoint[3]; + error = convertToXYZ(&xyz[0], whitepoint, in, w, h, state_in); + if (!error) error = convertFromXYZ(out, &xyz[0], w, h, state_out, whitepoint, rendering_intent); + lodepng_free(xyz); + return error; + } +} + +unsigned convertToSrgb(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_in) { + LodePNGState srgb; + lodepng_state_init(&srgb); + lodepng_color_mode_copy(&srgb.info_raw, &state_in->info_raw); + return convertRGBModel(out, in, w, h, &srgb, state_in, 1); +} + +unsigned convertFromSrgb(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_out) { + LodePNGState srgb; + lodepng_state_init(&srgb); + lodepng_color_mode_copy(&srgb.info_raw, &state_out->info_raw); + return convertRGBModel(out, in, w, h, state_out, &srgb, 1); +} + +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +//////////////////////////////////////////////////////////////////////////////// + + + +//This uses a stripped down version of picoPNG to extract detailed zlib information while decompressing. +static const unsigned long LENBASE[29] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; +static const unsigned long LENEXTRA[29] = {0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; +static const unsigned long DISTBASE[30] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577}; +static const unsigned long DISTEXTRA[30] = {0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; +static const unsigned long CLCL[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; //code length code lengths + +struct ExtractZlib { // Zlib decompression and information extraction + std::vector* zlibinfo; + ExtractZlib(std::vector* info) : zlibinfo(info) {}; + int error; + + unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) { + unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1; + bitp++; + return result; + } + + unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits) { + unsigned long result = 0; + for(size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i; + return result; + } + + struct HuffmanTree { + int makeFromLengths(const std::vector& bitlen, unsigned long maxbitlen) { //make tree given the lengths + unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0; + std::vector tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0); + //count number of instances of each code length + for(unsigned long bits = 0; bits < numcodes; bits++) blcount[bitlen[bits]]++; + for(unsigned long bits = 1; bits <= maxbitlen; bits++) { + nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1; + } + //generate all the codes + for(unsigned long n = 0; n < numcodes; n++) if(bitlen[n] != 0) tree1d[n] = nextcode[bitlen[n]]++; + tree2d.clear(); tree2d.resize(numcodes * 2, 32767); //32767 here means the tree2d isn't filled there yet + for(unsigned long n = 0; n < numcodes; n++) //the codes + for(unsigned long i = 0; i < bitlen[n]; i++) { //the bits for this code + unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1; + if(treepos > numcodes - 2) return 55; + if(tree2d[2 * treepos + bit] == 32767) { //not yet filled in + if(i + 1 == bitlen[n]) { + //last bit + tree2d[2 * treepos + bit] = n; + treepos = 0; + } else { + //addresses are encoded as values > numcodes + tree2d[2 * treepos + bit] = ++nodefilled + numcodes; + treepos = nodefilled; + } + } + else treepos = tree2d[2 * treepos + bit] - numcodes; //subtract numcodes from address to get address value + } + return 0; + } + int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const { //Decodes a symbol from the tree + unsigned long numcodes = (unsigned long)tree2d.size() / 2; + if(treepos >= numcodes) return 11; //error: you appeared outside the codetree + result = tree2d[2 * treepos + bit]; + decoded = (result < numcodes); + treepos = decoded ? 0 : result - numcodes; + return 0; + } + //2D representation of a huffman tree: one dimension is "0" or "1", the other contains all nodes and leaves. + std::vector tree2d; + }; + + void inflate(std::vector& out, const std::vector& in, size_t inpos = 0) { + size_t bp = 0, pos = 0; //bit pointer and byte pointer + error = 0; + unsigned long BFINAL = 0; + while(!BFINAL && !error) { + size_t uncomprblockstart = pos; + size_t bpstart = bp; + if(bp >> 3 >= in.size()) { error = 52; return; } //error, bit pointer will jump past memory + BFINAL = readBitFromStream(bp, &in[inpos]); + unsigned long BTYPE = readBitFromStream(bp, &in[inpos]); BTYPE += 2 * readBitFromStream(bp, &in[inpos]); + zlibinfo->resize(zlibinfo->size() + 1); + zlibinfo->back().btype = BTYPE; + if(BTYPE == 3) { error = 20; return; } //error: invalid BTYPE + else if(BTYPE == 0) inflateNoCompression(out, &in[inpos], bp, pos, in.size()); + else inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE); + size_t uncomprblocksize = pos - uncomprblockstart; + zlibinfo->back().compressedbits = bp - bpstart; + zlibinfo->back().uncompressedbytes = uncomprblocksize; + } + } + + void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) { //get the tree of a deflated block with fixed tree + std::vector bitlen(288, 8), bitlenD(32, 5);; + for(size_t i = 144; i <= 255; i++) bitlen[i] = 9; + for(size_t i = 256; i <= 279; i++) bitlen[i] = 7; + tree.makeFromLengths(bitlen, 15); + treeD.makeFromLengths(bitlenD, 15); + } + + //the code tree for Huffman codes, dist codes, and code length codes + HuffmanTree codetree, codetreeD, codelengthcodetree; + unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& tree, size_t inlength) { + //decode a single symbol from given list of bits with given code tree. return value is the symbol + bool decoded; unsigned long ct; + for(size_t treepos = 0;;) { + if((bp & 0x07) == 0 && (bp >> 3) > inlength) { error = 10; return 0; } //error: end reached without endcode + error = tree.decode(decoded, ct, treepos, readBitFromStream(bp, in)); + if(error) return 0; //stop, an error happened + if(decoded) return ct; + } + } + + void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD, + const unsigned char* in, size_t& bp, size_t inlength) { + size_t bpstart = bp; + //get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree + std::vector bitlen(288, 0), bitlenD(32, 0); + if(bp >> 3 >= inlength - 2) { error = 49; return; } //the bit pointer is or will go past the memory + size_t HLIT = readBitsFromStream(bp, in, 5) + 257; //number of literal/length codes + 257 + size_t HDIST = readBitsFromStream(bp, in, 5) + 1; //number of dist codes + 1 + size_t HCLEN = readBitsFromStream(bp, in, 4) + 4; //number of code length codes + 4 + zlibinfo->back().hlit = HLIT - 257; + zlibinfo->back().hdist = HDIST - 1; + zlibinfo->back().hclen = HCLEN - 4; + std::vector codelengthcode(19); //lengths of tree to decode the lengths of the dynamic tree + for(size_t i = 0; i < 19; i++) codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0; + //code length code lengths + for(size_t i = 0; i < codelengthcode.size(); i++) zlibinfo->back().clcl.push_back(codelengthcode[i]); + error = codelengthcodetree.makeFromLengths(codelengthcode, 7); if(error) return; + size_t i = 0, replength; + while(i < HLIT + HDIST) { + unsigned long code = huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength); if(error) return; + zlibinfo->back().treecodes.push_back(code); //tree symbol code + if(code <= 15) { if(i < HLIT) bitlen[i++] = code; else bitlenD[i++ - HLIT] = code; } //a length code + else if(code == 16) { //repeat previous + if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 3 + readBitsFromStream(bp, in, 2); + unsigned long value; //set value to the previous code + if((i - 1) < HLIT) value = bitlen[i - 1]; + else value = bitlenD[i - HLIT - 1]; + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths + if(i >= HLIT + HDIST) { error = 13; return; } //error: i is larger than the amount of codes + if(i < HLIT) bitlen[i++] = value; else bitlenD[i++ - HLIT] = value; + } + } else if(code == 17) { //repeat "0" 3-10 times + if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 3 + readBitsFromStream(bp, in, 3); + zlibinfo->back().treecodes.push_back(replength); //tree symbol code repetitions + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths + if(i >= HLIT + HDIST) { error = 14; return; } //error: i is larger than the amount of codes + if(i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; + } + } else if(code == 18) { //repeat "0" 11-138 times + if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 11 + readBitsFromStream(bp, in, 7); + zlibinfo->back().treecodes.push_back(replength); //tree symbol code repetitions + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths + if(i >= HLIT + HDIST) { error = 15; return; } //error: i is larger than the amount of codes + if(i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; + } + } + else { error = 16; return; } //error: somehow an unexisting code appeared. This can never happen. + } + if(bitlen[256] == 0) { error = 64; return; } //the length of the end code 256 must be larger than 0 + error = tree.makeFromLengths(bitlen, 15); + if(error) return; //now we've finally got HLIT and HDIST, so generate the code trees, and the function is done + error = treeD.makeFromLengths(bitlenD, 15); + if(error) return; + zlibinfo->back().treebits = bp - bpstart; + //lit/len/end symbol lengths + for(size_t j = 0; j < bitlen.size(); j++) zlibinfo->back().litlenlengths.push_back(bitlen[j]); + //dist lengths + for(size_t j = 0; j < bitlenD.size(); j++) zlibinfo->back().distlengths.push_back(bitlenD[j]); + } + + void inflateHuffmanBlock(std::vector& out, + const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype) { + size_t numcodes = 0, numlit = 0, numlen = 0; //for logging + if(btype == 1) { generateFixedTrees(codetree, codetreeD); } + else if(btype == 2) { getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength); if(error) return; } + for(;;) { + unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); if(error) return; + numcodes++; + zlibinfo->back().lz77_lcode.push_back(code); //output code + zlibinfo->back().lz77_dcode.push_back(0); + zlibinfo->back().lz77_lbits.push_back(0); + zlibinfo->back().lz77_dbits.push_back(0); + zlibinfo->back().lz77_lvalue.push_back(0); + zlibinfo->back().lz77_dvalue.push_back(0); + + if(code == 256) { + break; //end code + } else if(code <= 255) { //literal symbol + out.push_back((unsigned char)(code)); + pos++; + numlit++; + } else if(code >= 257 && code <= 285) { //length code + size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257]; + if((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory + length += readBitsFromStream(bp, in, numextrabits); + unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength); if(error) return; + if(codeD > 29) { error = 18; return; } //error: invalid dist code (30-31 are never used) + unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD]; + if((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory + dist += readBitsFromStream(bp, in, numextrabitsD); + size_t start = pos, back = start - dist; //backwards + for(size_t i = 0; i < length; i++) { + out.push_back(out[back++]); + pos++; + if(back >= start) back = start - dist; + } + numlen++; + zlibinfo->back().lz77_dcode.back() = codeD; //output distance code + zlibinfo->back().lz77_lbits.back() = numextrabits; //output length extra bits + zlibinfo->back().lz77_dbits.back() = numextrabitsD; //output dist extra bits + zlibinfo->back().lz77_lvalue.back() = length; //output length + zlibinfo->back().lz77_dvalue.back() = dist; //output dist + } + } + zlibinfo->back().numlit = numlit; //output number of literal symbols + zlibinfo->back().numlen = numlen; //output number of length symbols + } + + void inflateNoCompression(std::vector& out, + const unsigned char* in, size_t& bp, size_t& pos, size_t inlength) { + while((bp & 0x7) != 0) bp++; //go to first boundary of byte + size_t p = bp / 8; + if(p >= inlength - 4) { error = 52; return; } //error, bit pointer will jump past memory + unsigned long LEN = in[p] + 256u * in[p + 1], NLEN = in[p + 2] + 256u * in[p + 3]; p += 4; + if(LEN + NLEN != 65535) { error = 21; return; } //error: NLEN is not one's complement of LEN + if(p + LEN > inlength) { error = 23; return; } //error: reading outside of in buffer + for(unsigned long n = 0; n < LEN; n++) { + out.push_back(in[p++]); //read LEN bytes of literal data + pos++; + } + bp = p * 8; + } + + int decompress(std::vector& out, const std::vector& in) { //returns error value + if(in.size() < 2) { return 53; } //error, size of zlib data too small + //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way + if((in[0] * 256 + in[1]) % 31 != 0) { return 24; } + unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1; + //error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec + if(CM != 8 || CINFO > 7) { return 25; } + //error: the PNG spec says about the zlib stream: "The additional flags shall not specify a preset dictionary." + if(FDICT != 0) { return 26; } + inflate(out, in, 2); + return error; //note: adler32 checksum was skipped and ignored + } +}; + +struct ExtractPNG { //PNG decoding and information extraction + std::vector* zlibinfo; + ExtractPNG(std::vector* info) : zlibinfo(info) {}; + int error; + void decode(const unsigned char* in, size_t size) { + error = 0; + if(size == 0 || in == 0) { error = 48; return; } //the given data is empty + readPngHeader(&in[0], size); if(error) return; + size_t pos = 33; //first byte of the first chunk after the header + std::vector idat; //the data from idat chunks + bool IEND = false; + //loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + //IDAT data is put at the start of the in buffer + while(!IEND) { + //error: size of the in buffer too small to contain next chunk + if(pos + 8 >= size) { error = 30; return; } + size_t chunkLength = read32bitInt(&in[pos]); pos += 4; + if(chunkLength > 2147483647) { error = 63; return; } + //error: size of the in buffer too small to contain next chunk + if(pos + chunkLength >= size) { error = 35; return; } + //IDAT chunk, containing compressed image data + if(in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') { + idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]); + pos += (4 + chunkLength); + } else if(in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') { + pos += 4; + IEND = true; + } else { //it's not an implemented chunk type, so ignore it: skip over the data + pos += (chunkLength + 4); //skip 4 letters and uninterpreted data of unimplemented chunk + } + pos += 4; //step over CRC (which is ignored) + } + std::vector out; //now the out buffer will be filled + ExtractZlib zlib(zlibinfo); //decompress with the Zlib decompressor + error = zlib.decompress(out, idat); + if(error) return; //stop if the zlib decompressor returned an error + } + + //read the information from the header and store it in the Info + void readPngHeader(const unsigned char* in, size_t inlength) { + if(inlength < 29) { error = 27; return; } //error: the data length is smaller than the length of the header + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { error = 28; return; } //no PNG signature + //error: it doesn't start with a IHDR chunk! + if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { error = 29; return; } + } + + unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) { + unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1; + bitp++; + return result; + } + + unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits) { + unsigned long result = 0; + for(size_t i = nbits - 1; i < nbits; i--) result += ((readBitFromReversedStream(bitp, bits)) << i); + return result; + } + + void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) { + bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++; + } + + unsigned long read32bitInt(const unsigned char* buffer) { + return (unsigned int)((buffer[0] << 24u) | (buffer[1] << 16u) | (buffer[2] << 8u) | buffer[3]); + } +}; + +void extractZlibInfo(std::vector& zlibinfo, const std::vector& in) { + ExtractPNG decoder(&zlibinfo); + decoder.decode(&in[0], in.size()); + + if(decoder.error) std::cout << "extract error: " << decoder.error << std::endl; +} + +} // namespace lodepng diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.h b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.h new file mode 100644 index 0000000000000000000000000000000000000000..97fd804c36527074e2276a875c416b8e9631bd4d --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/lodepng/lodepng_util.h @@ -0,0 +1,290 @@ +/* +LodePNG Utils + +Copyright (c) 2005-2020 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +/* +Extra C++ utilities for LodePNG, for convenience. +Not part of the stable API of lodepng, more loose separate utils. +*/ + +#ifndef LODEPNG_UTIL_H +#define LODEPNG_UTIL_H + +#include +#include +#include "lodepng.h" + +namespace lodepng { + +/* +Returns info from the header of the PNG by value, purely for convenience. +Does NOT check for errors. Returns bogus info if the PNG has an error. +Does not require cleanup of allocated memory because no palette or text chunk +info is in the LodePNGInfo object after checking only the header of the PNG. +*/ +LodePNGInfo getPNGHeaderInfo(const std::vector& png); + +/* +Get the names and sizes of all chunks in the PNG file. +Returns 0 if ok, non-0 if error happened. +*/ +unsigned getChunkInfo(std::vector& names, std::vector& sizes, + const std::vector& png); + +/* +Returns the names and full chunks (including the name and everything else that +makes up the chunk) for all chunks except IHDR, PLTE, IDAT and IEND. +It separates the chunks into 3 separate lists, representing the chunks between +certain critical chunks: 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND +Returns 0 if ok, non-0 if error happened. +*/ +unsigned getChunks(std::vector names[3], + std::vector > chunks[3], + const std::vector& png); + +/* +Inserts chunks into the given png file. The chunks must be fully encoded, +including length, type, content and CRC. +The array index determines where it goes: +0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. +They're appended at the end of those locations within the PNG. +Returns 0 if ok, non-0 if error happened. +*/ +unsigned insertChunks(std::vector& png, + const std::vector > chunks[3]); + +/* +Get the filtertypes of each scanline in this PNG file. +Returns 0 if ok, 1 if PNG decoding error happened. + +For a non-interlaced PNG, it returns one filtertype per scanline, in order. + +For interlaced PNGs, it returns a result as if it's not interlaced. It returns +one filtertype per scanline, in order. The values match pass 6 and 7 of the +Adam7 interlacing, alternating between the two, so that the values correspond +the most to their scanlines. +*/ +unsigned getFilterTypes(std::vector& filterTypes, const std::vector& png); + +/* +Get the filtertypes of each scanline in every interlace pass this PNG file. +Returns 0 if ok, 1 if PNG decoding error happened. + +For a non-interlaced PNG, it returns one filtertype per scanline, in order, in +a single std::vector in filterTypes. + +For an interlaced PNG, it returns 7 std::vectors in filterTypes, one for each +Adam7 pass. The amount of values per pass can be calculated as follows, where +w and h are the size of the image and all divisions are integer divisions: +pass 1: (h + 7) / 8 +pass 2: w <= 4 ? 0 : (h + 7) / 8 +pass 3: h <= 4 ? 0 : (h + 7) / 8 +pass 4: w <= 2 ? 0 : (h + 3) / 4 +pass 5: h <= 2 ? 0 : (h + 3) / 4 +pass 6: w <= 1 ? 0 : (h + 1) / 2 +pass 7: h <= 1 ? 0 : (h + 1) / 2 +*/ +unsigned getFilterTypesInterlaced(std::vector >& filterTypes, + const std::vector& png); + +/* +Returns the value of the i-th pixel in an image with 1, 2, 4 or 8-bit color. +E.g. if bits is 4 and i is 5, it returns the 5th nibble (4-bit group), which +is the second half of the 3th byte, in big endian (PNG's endian order). +*/ +int getPaletteValue(const unsigned char* data, size_t i, int bits); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +/* Similar to convertRGBModel, but the 'to' model is sRGB. The pixel format +of in and out must be the same and is given by state_in->info_raw. An +error may occur if the pixel format cannot contain the new colors (e.g. palette) */ +unsigned convertToSrgb(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_in); + +/* Similar to convertRGBModel, but the 'from' model is sRGB. The pixel format +of in and out must be the same and is given by state_out->info_raw. An +error may occur if the pixel format cannot contain the new colors (e.g. palette) */ +unsigned convertFromSrgb(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_out); + +/* +Converts from one RGB model to another RGB model. +Similar to calling convertToXYZ followed by convertFromXYZ, but may be +more efficient and more precise (e.g. no computation needed when both models +are the same). See their documentation for more info. + +Parameters: + +*) out: output pixel data +*) in: input pixel data +*) w, h: image size +*) state_out: output RGB color model in state_out->info_png and byte format in state_out->info_raw. +*) state_in: output RGB color model in state_in->info_png and byte format in state_in->info_raw +*) return value: 0 if ok, positive value if error +*) rendering_intent: 1 for relative, 3 for absolute, should be relative for standard behavior. + See description at convertFromXYZ. +*/ +unsigned convertRGBModel(unsigned char* out, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGState* state_out, + const LodePNGState* state_in, + unsigned rendering_intent); + +/* +Converts the RGB color to the absolute XYZ color space given the RGB color profile +chunks in the PNG info. + +Color space here refers to the different possible RGB spaces with different +possible chromaticities or whitepoint and XYZ color from colorimetry, not the +LodePNGColorType that describes the byte based encoding. + +You need this function only if the PNG could contain data in an arbitrary RGB +color space and you wish to output to a display or format that does not provide +color management for you (so you need to convert rather than pass on the profile +to it) but expects a certain RGB format (e.g. sRGB). See the background info below. + +Supports the gAMA, cHRM, sRGB and iCCP colorimetry chunks. If no colometry chunks are present +(that is, in state->info_png, the fields gama_defined, chrm_defined, srgb_defined and +iccp_defined are all 0), it assumes the format is sRGB. +For more information, see the chunk specifications in the PNG specification. + +Some background: + +A PNG image contains RGB data inside, but this data may use a specific RGB model (by default sRGB but +different if colorimetry chunks are given). +The computer display and/or operating system can have another RGB model (typically sRGB, or wider gamut +or HDR formats). + +The PNG chunks describe what format the data inside has, not the format of the display. To correctly +display a PNG image on a display, a conversion is needed from the PNG model to the display model if their +models differ. Some options to achieve that are: +*) If your use case already supports color management on its own, you can give it the RGB values straight from + the PNG image and give it the information from the cHRM, gAMA, sRGB and iCCP chunks (which you can find + in the LodePNGInfo), and the color management should then handle it correctly for you. You don't need + this function here in that case. +*) If your use case does not support color management, you may instead want to give it the RGB values in a + consistent color model, such as sRGB, but the PNG does not necessarily have it in this desired model. + In that case, use the function below (or a similar one from a CMS library if you prefer) to convert it to + the absolute color space XYZ, and then you can convert it to the target RGB with the counterpart convertFromXYZ + further below. + +Parameters: + +*) out: 4 floats per pixel, X,Y,Z,alpha color format, in range 0-1 (normally, not clipped if beyond), must + be allocated to have 4 * w * h floats available. +*) whitepoint: output argument, the whitepoint the original RGB data used, given in absolute XYZ. Needed for + relative rendering intents: give these values to counterpart function convertFromXYZ. +*) in: input RGB color, in byte format given by state->info_raw and RGB color profile given by info->info_png +*) w, h: image size +*) state (when using a LodePNG decode function that takes a LodePNGState parameter, can directly use that one): + state->info_png: PNG info with possibly an RGB color model in cHRM,gAMA and/or sRGB chunks + state->info_raw: byte format of in (amount of channels, bit depth) +*) return value: 0 if ok, positive value if error +*/ +unsigned convertToXYZ(float* out, float whitepoint[3], + const unsigned char* in, unsigned w, unsigned h, + const LodePNGState* state); + +/* +Same as convertToXYZ but takes floating point input. Slower. +The main black..white range in 0..1. Does not clip values that are outside that range. +*/ +unsigned convertToXYZFloat(float* out, float whitepoint[3], const float* in, + unsigned w, unsigned h, const LodePNGState* state); + +/* +Converts XYZ to RGB in the RGB color model given by info and byte format by mode_out. +If info has no coloremtry chunks, converts to sRGB. +Parameters: +*) out: output color in byte format given by state->info_raw and RGB color profile given + by info->info_png. Must have enough bytes allocated to contain pixels in the given byte format. +*) in: 4 floats per pixel, X,Y,Z,alpha color format, in range 0-1 (normally). +*) whitepoint: input argument, the original whitepoint in absolute XYZ that the pixel data + in "in" had back when it was in a previous RGB space. Needed to preserve the whitepoint + in the new target RGB space for relative rendering intent. +*) rendering_intent: the desired rendering intent, with numeric meaning matching the + values used by ICC: 0=perceptual, 1=relative, 2=saturation, 3=absolute. + Should be 1 for normal use cases, it adapts white to match that of different RGB + models which is the best practice. Using 3 may change the color of white and may + turn grayscale into colors of a certain tone. Using 0 and 2 will have the same + effect as 1 because using those requires more data than the matrix-based RGB profiles + supporetd here have. +*) w, h: image size +*) state: + state->info_png: PNG info with possibly an RGB color profile in cHRM,gAMA and/or sRGB chunks + state->info_raw: byte format of out (amount of channels, bit depth) +*) return value: 0 if ok, positive value if error +*/ +unsigned convertFromXYZ(unsigned char* out, const float* in, unsigned w, unsigned h, + const LodePNGState* state, + const float whitepoint[3], unsigned rendering_intent); + +/* +Same as convertFromXYZ but outputs the RGB colors in floating point. +The main black..white range in 0..1. Does not clip values that are outside that range. +*/ +unsigned convertFromXYZFloat(float* out, const float* in, unsigned w, unsigned h, + const LodePNGState* state, + const float whitepoint[3], unsigned rendering_intent); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/* +The information for extractZlibInfo. +*/ +struct ZlibBlockInfo { + int btype; //block type (0-2) + size_t compressedbits; //size of compressed block in bits + size_t uncompressedbytes; //size of uncompressed block in bytes + + // only filled in for block type 2 + size_t treebits; //encoded tree size in bits + int hlit; //the HLIT value that was filled in for this tree + int hdist; //the HDIST value that was filled in for this tree + int hclen; //the HCLEN value that was filled in for this tree + std::vector clcl; //19 code length code lengths (compressed tree's tree) + std::vector treecodes; //N tree codes, with values 0-18. Values 17 or 18 are followed by the repetition value. + std::vector litlenlengths; //288 code lengths for lit/len symbols + std::vector distlengths; //32 code lengths for dist symbols + + // only filled in for block types 1 or 2 + std::vector lz77_lcode; //LZ77 codes. 0-255: literals. 256: end symbol. 257-285: length code of length/dist pairs + // the next vectors have the same size as lz77_lcode, but an element only has meaningful value if lz77_lcode contains a length code. + std::vector lz77_dcode; + std::vector lz77_lbits; + std::vector lz77_dbits; + std::vector lz77_lvalue; + std::vector lz77_dvalue; + size_t numlit; //number of lit codes in this block + size_t numlen; //number of len codes in this block +}; + +//Extracts all info needed from a PNG file to reconstruct the zlib compression exactly. +void extractZlibInfo(std::vector& zlibinfo, const std::vector& in); + +} // namespace lodepng + +#endif /*LODEPNG_UTIL_H inclusion guard*/ diff --git a/dan-rodrigues_icestation-32/utilities/gfx_convert/main.cpp b/dan-rodrigues_icestation-32/utilities/gfx_convert/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..079afa950505ef1d05d0ad5fc6b1ebbc11c7d870 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/gfx_convert/main.cpp @@ -0,0 +1,292 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "lodepng.h" +#include "lodepng_util.h" + +#include "Palette.hpp" +#include "Tiles.hpp" +#include "Image.hpp" +#include "Map.hpp" + +#include "DataHeader.hpp" + +static void save_transcoded_png(Image image, const std::string &name); +static bool save_palette(const Palette &palette, const std::string &path); + +static bool load_palette(const std::string &path, + std::optional palette_id, + std::vector &palette_data); + +static bool convert_image(const std::vector &input_data, + const std::vector &palette_data, + InputFormat input_format, + const std::string &name, + const std::string &output_prefix); + +static bool convert_map(const std::vector &input_data, + const std::string &output_path); + +int main(int argc, char **argv) { + InputFormat input_format = PNG; + + std::string palette_path; + std::optional palette_id = std::nullopt; + std::string output_prefix = ""; + std::string palette_output_path; + + // Map conversion args: + + std::string map_output_path = ""; + uint16_t snes_vram_offset = 0; + + if (argc < 2) { + std::cout << "Usage: [options] " << std::endl; + return EXIT_SUCCESS; + } + + int opt; + char *endptr; + + const option options[] = { + {.name = "snes-vram", .has_arg = required_argument, .flag = NULL, .val = 'v'}, + {.name = "snes-vram-offset", .has_arg = required_argument, .flag = NULL, .val = 'y'}, + {.name = "map-output", .has_arg = required_argument, .flag = NULL, .val = 'm'}, + {.name = "palette-output", .has_arg = required_argument, .flag = NULL, .val = 'x'} + }; + + while ((opt = getopt_long(argc, argv, "m:f:p:i:o:", &options[0], NULL)) != -1) { + switch (opt) { + case 'f': { + std::string input_format_arg = optarg; + std::transform(input_format_arg.begin(), input_format_arg.end(), input_format_arg.begin(), ::tolower); + + if (input_format_arg == "png") { + input_format = PNG; + } else if (input_format_arg == "snes") { + input_format = SNES; + } else { + std::cerr << "Error: unrecognized input format: " << input_format_arg << std::endl; + return EXIT_FAILURE; + } + + } break; + case 'p': + palette_path = optarg; + break; + case 'i': + palette_id = strtol(optarg, &endptr, 10); + break; + case 'o': + output_prefix = optarg; + break; + case 'm': + map_output_path = optarg; + break; + case 'y': + snes_vram_offset = strtol(optarg, &endptr, 16); + break; + case 'x': + palette_output_path = optarg; + break; + case '?': + return EXIT_FAILURE; + } + } + + std::string image_path; + if (argc == (optind + 1)) { + image_path = argv[optind]; + } else if (argc == optind) { + std::cout << "No image file path given, checking for palette file path.." << "\n"; + } else { + std::cout << "Expected at least one input file" << "\n"; + return EXIT_FAILURE; + } + + // Load graphics (or map) data + + std::vector input_data; + if (!image_path.empty()) { + std::ifstream input_stream(image_path, std::ios::binary); + input_stream.seekg(snes_vram_offset); + if (input_stream.fail()) { + std::cerr << "Failed to open input file: " << image_path << std::endl; + return EXIT_FAILURE; + } + input_data = std::vector(std::istreambuf_iterator(input_stream), {}); + input_stream.close(); + } + + // Map conversion: + + if (!map_output_path.empty()) { + bool success = convert_map(input_data, map_output_path); + return success ? EXIT_SUCCESS : EXIT_FAILURE; + } + + // Was a custom palette provided? + + std::vector palette_data; + if (!palette_path.empty()) { + if (!load_palette(palette_path, palette_id, palette_data)) { + return EXIT_FAILURE; + } + } else if (palette_id.has_value()) { + std::cout << "Custom palette ID specified but no palette was provided" << std::endl; + return EXIT_FAILURE; + } + + bool has_image = !image_path.empty() && !input_data.empty(); + if (has_image) { + if (!convert_image(input_data, palette_data, input_format, image_path, output_prefix)) { + return EXIT_FAILURE; + } + } + + // Palette conversion (standalone): + + bool convert_standalone_palette = map_output_path.empty() && !palette_path.empty() && !palette_output_path.empty(); + if (convert_standalone_palette) { + std::cout << "..converting standalone palette: " << palette_output_path << "\n"; + + Palette palette = Palette(palette_data); + save_palette(palette, palette_output_path); + } + + return EXIT_SUCCESS; +} + +static bool convert_image(const std::vector &input_data, + const std::vector &palette_data, + InputFormat input_format, + const std::string &name, + const std::string &output_prefix) +{ + Image image; + try { + image = Image(input_data, palette_data, input_format); + } catch (std::invalid_argument e) { + std::cerr << "Failed to convert tiles and palette to image: " << e.what() << std::endl; + return false; + } + + // Tiles output + + auto tiles = image.tiles.ics_tiles(); + auto tiles_name = output_prefix + "tiles"; + std::ofstream output_tiles_binary_stream(tiles_name + ".bin", std::ios::out); + for (size_t i = 0; i < tiles.size(); i++) { + output_tiles_binary_stream.write((char *)(&tiles[i]), sizeof(uint32_t)); + } + output_tiles_binary_stream.close(); + + // Palette output + + auto palette_name = output_prefix + "palette"; + if (!save_palette(image.palette, palette_name + ".bin")) { + return false; + } + + // Test PNG to quickly verify results + + save_transcoded_png(image, output_prefix); + + return true; +} + +void save_transcoded_png(Image image, const std::string &name) { + auto packed_4bpp_tiles = image.tiles.packed_4bpp_tiles(); + + lodepng::State save_state; + + save_state.info_png.color.colortype = LCT_PALETTE; + save_state.info_png.color.bitdepth = image.bpp; + save_state.info_raw.colortype = LCT_PALETTE; + save_state.info_raw.bitdepth = image.bpp; + + save_state.encoder.auto_convert = 0; + + for (auto i = 0; i < 16; i++) { + uint32_t color = image.palette.rgba32_palette[i]; + uint8_t r = color & 0xff; + uint8_t g = color >> 8 & 0xff; + uint8_t b = color >> 16 & 0xff; + uint8_t a = color >> 24 & 0xff; + + lodepng_palette_add(&save_state.info_png.color, r, g, b, a); + lodepng_palette_add(&save_state.info_raw, r, g, b, a); + } + + std::vector buffer; + auto error = lodepng::encode(buffer, &packed_4bpp_tiles[0], image.tiles.width, image.tiles.height, save_state); + if (error) { + std::cerr << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; + return; + } + + lodepng::save_file(buffer, "test.png"); +} + +static bool save_palette(const Palette &palette, const std::string &path) { + auto palette_data = palette.ics_palette(); + std::ofstream stream(path, std::ios::out); + if (stream.fail()) { + std::cerr << "Failed to open palette file for writing: " << path << std::endl; + return false; + } + + stream.write((char *)(&palette_data[0]), sizeof(uint16_t) * palette_data.size()); + stream.close(); + + return true; +} + +static bool convert_map(const std::vector &input_data, const std::string &output_path) { + Map map(input_data); + + std::ofstream stream(output_path, std::ios::out); + if (stream.fail()) { + std::cerr << "Failed to open map file for writing: " << output_path << std::endl; + return false; + } + + auto ics_map = map.ics_map(); + stream.write((char *)&ics_map[0], ics_map.size() * sizeof(uint16_t)); + stream.close(); + + std::cout << "Successfully converted map file with output: " << output_path << "\n"; + return true; +} + +static bool load_palette(const std::string &path, std::optional palette_id, std::vector &palette_data) { + std::fstream stream(path); + if (stream.fail()) { + std::cerr << "Error: failed to open palette file" << std::endl; + return false; + } + + // Was only a single palette within the entire set requested? + if (palette_id.has_value()) { + // Read only the 16 colors of that one palette + const auto rgb24_palette_size = 16 * 3; + palette_data.resize(rgb24_palette_size); + auto palette_file_base = palette_id.value() * rgb24_palette_size; + stream.seekg(palette_file_base); + stream.read((char *)&palette_data[0], rgb24_palette_size); + } else { + // Read entire palette + palette_data = std::vector(std::istreambuf_iterator(stream), {}); + } + + stream.close(); + + return true; +} diff --git a/dan-rodrigues_icestation-32/utilities/header_gen/main.cpp b/dan-rodrigues_icestation-32/utilities/header_gen/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26c247c3060797797dc8e38571b676ef165d57df --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/header_gen/main.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include + +#include "DataHeader.hpp" + +int main(int argc, char **argv) { + std::string type_name = "uint16_t"; + std::string identifier = "data"; + std::string output_file_prefix = "data"; + size_t max_length = SIZE_MAX; + bool split_sources = false; + + int opt = 0; + while ((opt = getopt_long(argc, argv, "t:i:o:m:s", NULL, NULL)) != -1) { + switch (opt) { + case 't': + type_name = optarg; + break; + case 'i': + identifier = optarg; + break; + case 'o': + output_file_prefix = optarg; + break; + case 'm': + max_length = strtol(optarg, NULL, 10); + break; + case 's': + split_sources = true; + break; + case '?': + return EXIT_FAILURE; + } + } + + if (argc != optind + 1) { + std::cerr << "Usage: [options] " << std::endl; + return EXIT_SUCCESS; + } + + bool is8bit = (type_name == "uint8_t"); + + std::string input_path = argv[optind]; + std::fstream stream(input_path); + std::istreambuf_iterator it(stream); + std::istreambuf_iterator end; + + if (stream.fail()) { + std::cerr << "Failed to open file: " << input_path << std::endl; + return EXIT_FAILURE; + } + + std::vector data(std::istreambuf_iterator(stream), {}); + stream.close(); + + if (data.empty()) { + std::cerr << "File is empty" << std::endl; + return EXIT_FAILURE; + } + + auto h_file_path = output_file_prefix + ".h"; + std::ofstream h_stream(h_file_path, std::ios::out); + if (h_stream.fail()) { + std::cerr << "Failed to open .h for writing: " << h_file_path << std::endl; + return EXIT_FAILURE; + } + + if (split_sources) { + std::vector words; + + auto c_file_path = output_file_prefix + ".c"; + std::ofstream c_stream(c_file_path, std::ios::out); + if (c_stream.fail()) { + std::cerr << "Failed to open .c for writing: " << c_file_path << std::endl; + return EXIT_FAILURE; + } + + if (is8bit) { + DataHeader::write_h(data, type_name, identifier, h_stream); + DataHeader::write_c(data, type_name, identifier, c_stream); + } else { + for (size_t i = 0; i < data.size() / 2; i++) { + words.push_back(data[i * 2] | data[i * 2 + 1] << 8); + } + + DataHeader::write_h(words, type_name, identifier, h_stream); + DataHeader::write_c(words, type_name, identifier, c_stream); + } + + c_stream.close(); + } else { + DataHeader::write_combined_h(data, type_name, identifier, h_stream); + } + + h_stream.close(); + + return EXIT_SUCCESS; +} diff --git a/dan-rodrigues_icestation-32/utilities/sin_gen/main.cpp b/dan-rodrigues_icestation-32/utilities/sin_gen/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dc1028f4476f927e941d995b3e4438412f633b8 --- /dev/null +++ b/dan-rodrigues_icestation-32/utilities/sin_gen/main.cpp @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "DataHeader.hpp" + +int main(int argc, char **argv) { + bool split_sources = false; + bool full_period = true; + bool output_binary = false; + std::string output_file_prefix = "sin"; + uint16_t count = 256; + int16_t sin_max = 0x4000; + uint32_t repeat_count = 1; + + int opt = 0; + while ((opt = getopt_long(argc, argv, "r:m:c:sqb", NULL, NULL)) != -1) { + switch (opt) { + case 'm': { + int64_t sin_max_64 = strtol(optarg, NULL, 16); + if (sin_max_64 > std::numeric_limits::max()) { + std::cerr << "-m arg must be a signed 16bit integer" << std::endl; + return EXIT_FAILURE; + } + if (sin_max_64 <= 0) { + std::cerr << "-m arg must be a non-zero positive integer" << std::endl; + return EXIT_FAILURE; + } + sin_max = (int16_t)sin_max_64; + } break; + case 'c': { + int64_t count_64 = strtol(optarg, NULL, 10); + if (count_64 > std::numeric_limits::max()) { + std::cerr << "-c arg must be an unsigned 16bit integer" << std::endl; + return EXIT_FAILURE; + } + if (count_64 <= 0) { + std::cerr << "-c arg must be a non-zero positive integer" << std::endl; + return EXIT_FAILURE; + } + count = (uint16_t)count_64; + } break; + case 'q': + full_period = false; + break; + case 's': + split_sources = true; + break; + case 'b': + output_binary = true; + break; + case 'r': { + int64_t repeat_count_64 = strtol(optarg, NULL, 10); + if (repeat_count_64 < 0 || repeat_count_64 > std::numeric_limits::max()) { + std::cerr << "-r arg must be an unsigned 32bit integer" << std::endl; + return EXIT_FAILURE; + } + + repeat_count = (uint32_t)repeat_count_64; + } break; + case '?': + return EXIT_FAILURE; + } + } + + std::vector table; + table.resize(count); + + for (int i = 0; i < count; i++) { + auto theta = M_PI * 2 / count * repeat_count * i; + table[i] = sin(theta / (full_period ? 1 : 4)) * sin_max; + } + + const std::string identifier = output_file_prefix; + const std::string type_name = "int16_t"; + + if (output_binary) { + std::ofstream bin_stream(output_file_prefix + ".bin", std::ios::out | std::ios::binary); + bin_stream.write((char *)&table[0], table.size() * sizeof(int16_t)); + bin_stream.close(); + } + + auto h_file_path = output_file_prefix + ".h"; + std::ofstream h_stream(h_file_path); + + if (split_sources) { + DataHeader::write_h(table, type_name, identifier, h_stream); + + auto c_file_path = output_file_prefix + ".c"; + std::ofstream c_stream(c_file_path, std::ios::out); + if (c_stream.fail()) { + std::cerr << "Failed to open .c for writing: " << c_file_path << std::endl; + return EXIT_FAILURE; + } + DataHeader::write_c(table, type_name, identifier, c_stream); + c_stream.close(); + } else { + DataHeader::write_combined_h(table, type_name, identifier, h_stream); + } + h_stream.close(); + + return EXIT_SUCCESS; +} diff --git a/im-tomu_fomu-workshop/.github/dependabot.yml b/im-tomu_fomu-workshop/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..2511b638a4e3a070e4154efc821fe2ffb6548af5 --- /dev/null +++ b/im-tomu_fomu-workshop/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: +- package-ecosystem: gitsubmodule + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/im-tomu_fomu-workshop/.github/workflows/doc.yml b/im-tomu_fomu-workshop/.github/workflows/doc.yml new file mode 100644 index 0000000000000000000000000000000000000000..9be903d75e64460c520156b5b77a4ed8adc6db29 --- /dev/null +++ b/im-tomu_fomu-workshop/.github/workflows/doc.yml @@ -0,0 +1,44 @@ +name: 'doc' + +on: + push: + pull_request: + schedule: + - cron: '0 0 * * 5' + workflow_dispatch: + +jobs: + + sphinx: + runs-on: ubuntu-latest + steps: + + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Build docs + run: | + cd docs + make env + pip3 install -U wheel setuptools + pip3 install -r requirements.txt + make html + + - uses: actions/upload-artifact@v2 + with: + name: docs + path: docs/_build/html + + - name: Publish site to gh-pages + if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + run: | + cd docs/_build/html + touch .nojekyll + git init + cp ../../../.git/config ./.git/config + git add . + git config --local user.email "push@gha" + git config --local user.name "GHA" + git commit -a -m "update ${{ github.sha }}" + git push -u origin +HEAD:gh-pages diff --git a/im-tomu_fomu-workshop/.github/workflows/test.yml b/im-tomu_fomu-workshop/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..578e72d69a53c4c3ff223f3b06ffa53496c604ac --- /dev/null +++ b/im-tomu_fomu-workshop/.github/workflows/test.yml @@ -0,0 +1,142 @@ +name: 'test' + +on: + push: + pull_request: + schedule: + - cron: '0 0 * * 5' + workflow_dispatch: + +jobs: + + + fomu-toolchain: + strategy: + fail-fast: false + matrix: + include: + - { icon: 🐧, os: Ubuntu } + - { icon: 🧊, os: Windows } + - { icon: 🍎, os: macOS } + runs-on: ${{ matrix.os }}-latest + name: '${{ matrix.icon}} ${{ matrix.os }} | fomu-toolchain' + defaults: + run: + shell: bash + steps: + + - run: git config --global core.autocrlf input + shell: bash + + - uses: actions/checkout@v2 + with: + submodules: true + fetch-depth: 0 + + - uses: actions/setup-python@v2 + with: + python-version: 3.8 + + - name: Install Scala + uses: olafurpg/setup-scala@v10 + with: + java-version: openjdk@1.11 + + - name: Install (Ubuntu) + if: matrix.os == 'ubuntu' + run: | + curl -L https://ziglang.org/download/0.9.0/zig-linux-x86_64-0.9.0.tar.xz | tar -xJf - + echo "$(pwd)/zig-linux-x86_64-0.9.0" >> $GITHUB_PATH + + - name: Install (Mac OS) + if: matrix.os == 'macos' + run: brew install zig + + - name: Install (Windows) + if: matrix.os == 'windows' + run: | + choco install zig --version 0.9.0 + ln -s $(which python) /usr/bin/python3 + + - run: python ./get-toolchain.py + env: + GH_TOKEN: ${{ github.token }} + + - run: ./.github/tests.sh + + + all-in-one: + name: '🛳️ Container | All-in-one' + runs-on: ubuntu-latest + env: + GHDL_PLUGIN_MODULE: ghdl + steps: + + - uses: actions/checkout@v2 + with: + submodules: true + fetch-depth: 0 + + - uses: docker://gcr.io/hdl-containers/impl + with: + args: ./.github/hdl-tests.sh + + + fine-grained: + name: '🛳️ Container | Fine-grained' + runs-on: ubuntu-latest + env: + GHDL_PLUGIN_MODULE: ghdl + CONTAINER_ENGINE: docker + steps: + + - uses: actions/checkout@v2 + with: + submodules: true + fetch-depth: 0 + + - name: Pull container images + run: | + docker pull gcr.io/hdl-containers/ghdl/yosys + docker pull gcr.io/hdl-containers/nextpnr/ice40 + docker pull gcr.io/hdl-containers/icestorm + + - run: ./.github/hdl-tests.sh + + + msys2: + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: [ + {icon: '⬛', sys: 'mingw32'}, + {icon: '🟦', sys: 'mingw64'}, + {icon: '🟨', sys: 'ucrt64' }, + ] + name: '${{ matrix.icon }} MSYS2 | ${{ matrix.sys }}' + defaults: + run: + shell: msys2 {0} + steps: + + - name: '${{ matrix.icon }} Setup MSYS2' + uses: msys2/setup-msys2@v2 + with: + msystem: ${{ matrix.sys }} + update: true + install: make + pacboy: > + icestorm:p + yosys:p + nextpnr:p + + - run: git config --global core.autocrlf input + shell: bash + + - uses: actions/checkout@v2 + with: + submodules: true + fetch-depth: 0 + + - run: ./.github/hdl-tests.sh diff --git a/im-tomu_fomu-workshop/.readthedocs.yml b/im-tomu_fomu-workshop/.readthedocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..366c34250925a9fced1f42d2dc959b4874696612 --- /dev/null +++ b/im-tomu_fomu-workshop/.readthedocs.yml @@ -0,0 +1,22 @@ +# .readthedocs.yml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +build: + os: ubuntu-lts-latest + tools: + # Need to use mambaforge as miniconda runs out of memory on rtd. + python: mambaforge-latest + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: docs/conf.py + +#formats: +#- htmlzip + +conda: + environment: docs/environment.yml diff --git a/im-tomu_fomu-workshop/DEVELOPMENT.md b/im-tomu_fomu-workshop/DEVELOPMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..1bb53e80c378bf6968fd8439041becfa8eceedd3 --- /dev/null +++ b/im-tomu_fomu-workshop/DEVELOPMENT.md @@ -0,0 +1,180 @@ +# Developing the Workshop + +The workshop is written in +[reStructuredText (rst)](https://en.wikipedia.org/wiki/ReStructuredText) and +[generated using Sphinx](https://www.sphinx-doc.org/en/master/). + +It is hosted on [Read The Docs](http://readthedocs.org/) and currently uses the +[Material Design style](https://material.io/) developed by Google through +[a slightly custom version of the `sphinx_materialdesign_theme` package](http://github.com/SymbiFlow/sphinx_materialdesign_theme). + +It uses the [`sphinxcontrib-session` extension](https://github.com/mithro/sphinxcontrib-session) +to properly highlight the example sessions and to allow copying only the +session lines. + +Other sphinx extensions which are used include; + +- [`sphinxcontrib-hdl-diagrams`](http://sphinxcontrib-hdl-diagrams.rtfd.io/) to + generate nice diagrams from Verilog examples. +- [`sphinx-wavedrom`](https://github.com/bavovanachte/sphinx-wavedrom) to + generate [nice waveform diagrams](http://wavedrom.com/). `sphinxcontrib-wavedrom`? +- [`sphinx_tabs`](https://github.com/djungelorm/sphinx-tabs) to support tabs + for different Linux / Windows / Mac OS X instructions. + +## Useful Resources for writing docs + +- [Sphinx RestructuredText Primer](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html) +- [ReStructuredText directives](https://docutils.sourceforge.io/docs/ref/rst/directives.html) +- [Material Design Icons](https://material.io/resources/icons/) + +# Building Workshop Locally + +## On Mac & Linux + +```shell-session +$ cd docs +``` +Download conda environment with Python utilities: + +```shell-session +$ make env +rm -rf env +make _download/Miniconda3-latest-Linux-x86_64.sh +make[1]: Entering directory '~/fomu-workshop/docs' +mkdir env +wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O _download/Miniconda3-latest-Linux-x86_64.sh +--2020-01-03 10:15:07-- https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh +Resolving repo.anaconda.com (repo.anaconda.com)... 104.16.131.3, 104.16.130.3, 2606:4700::6810:8203, ... +Connecting to repo.anaconda.com (repo.anaconda.com)|104.16.131.3|:443... connected. +HTTP request sent, awaiting response... 200 OK +Length: 71785000 (68M) [application/x-sh] +Saving to: ‘_download/Miniconda3-latest-Linux-x86_64.sh’ + +_download/Miniconda3-latest-Linux-x86_64.sh 100%[==================>] 68.46M 1.29MB/s in 17s + +2020-01-03 10:15:29 (3.98 MB/s) - ‘_download/Miniconda3-latest-Linux-x86_64.sh’ saved [71785000/71785000] + +chmod a+x _download/Miniconda3-latest-Linux-x86_64.sh +make[1]: Leaving directory '~/fomu-workshop/docs' +_download/Miniconda3-latest-Linux-x86_64.sh -p ~/fomu-workshop/docs/env -b -f +PREFIX=~/fomu-workshop/docs/env +Unpacking payload ... +Collecting package metadata (current_repodata.json): done +Solving environment: done + +## Package Plan ## + + environment location: ~/fomu-workshop/docs/env + + added / updated specs: + - _libgcc_mutex==0.1=main + - asn1crypto==1.2.0=py37_0 + - ca-certificates==2019.10.16=0 + + + +tk-8.6.10 | 3.2 MB | ########################### | 100% +_libgcc_mutex-0.1 | 2 KB | ########################### | 100% +xorg-libsm-1.2.3 | 25 KB | ########################### | 100% +requests-2.22.0 | 84 KB | ########################### | 100% +harfbuzz-2.4.0 | 1.5 MB | ########################### | 100% +conda-package-handli | 942 KB | ########################### | 100% +Preparing transaction: done +Verifying transaction: done +Executing transaction: done +``` + +Install dependencies: + +```shell-session +$ pip install -r requirements.txt +``` + +Build the html output: + +```shell-session +$ make html +Running Sphinx v2.3.1 +loading pickled environment... done +building [mo]: targets for 0 po files that are out of date +building [html]: targets for 21 source files that are out of date +updating environment: [config changed ('version')] 15 added, 0 changed, 6 removed +reading sources... [100%] verilog +writing output... [100%] verilog +copying images... [100%] _static/wishbone-usb-debug-bridge.png +copying static files... ... done +copying extra files... done +dumping search index in English (code: en)... done +dumping object inventory... done +build succeeded, 15 warnings. + +The HTML pages are in _build/html. +Copying tabs assets +``` + +Start your web browser: + +```shell-session +$ xdg-open ./_build/html/index.html +``` + +## On Windows + +You may use either cmd.exe or Powershell. To begin with, set up venv. This may prompt you to install Python from the Microsoft Store: +```shell-session +$ cd docs +$ python -mvenv . +``` + +Activate the venv by running `Activate.bat` (if using cmd.exe) or `Activate.ps1` (if using Powershell). You must do this any time you want to work on the documentation: + +```shell-session +$ .\Scripts\Activate.ps1 +(docs) $ +``` + +You'll notice that the word `(docs)` is added to your command prompt. This indicates you're in a venv directory. + +Next, install dependencies: + +```shell-session +(docs) $ pip install -r requirements.txtCollecting sphinx_symbiflow_theme + Cloning http://github.com/SymbiFlow/sphinx_materialdesign_theme.git (to revision master) to c:\users\sean\appdata\local\temp\pip-install-do82_l8w\sphinx-symbiflow-theme_75938b6aa0c04180962403b9b4b53fae + Running command git clone -q http://github.com/SymbiFlow/sphinx_materialdesign_theme.git 'C:\Users\sean\AppData\Local\Temp\pip-install-do82_l8w\sphinx-symbiflow-theme_75938b6aa0c04180962403b9b4b53fae' + Resolved http://github.com/SymbiFlow/sphinx_materialdesign_theme.git to commit 5a7c118c6485461de299366f638a0f3cc41ed4e8 +Collecting sphinxcontrib-session + Cloning https://github.com/mithro/sphinxcontrib-session.git to c:\users\sean\appdata\local\temp\pip-install-do82_l8w\sphinxcontrib-session_468cf0a370a04b079fd59a990969f629 + Running command git clone -q https://github.com/mithro/sphinxcontrib-session.git 'C:\Users\sean\AppData\Local\Temp\pip-install-do82_l8w\sphinxcontrib-session_468cf0a370a04b079fd59a990969f629' + Resolved https://github.com/mithro/sphinxcontrib-session.git to commit f9e959a696ba02d874ffc291a3b83a4458c1bad6 + + + + Running setup.py install for sphinxcontrib-session ... done + Running setup.py install for sphinxcontrib-hdl-diagrams ... done + Running setup.py install for sphinx-symbiflow-theme ... done +Successfully installed Jinja2-3.0.3 MarkupSafe-2.0.1 Pygments-2.11.2 alabaster-0.7.12 appdirs-1.4.4 attrdict-2.0.1 babel-2.9.1 cairocffi-1.3.0 cairosvg-2.5.2 certifi-2021.10.8 cffi-1.15.0 charset-normalizer-2.0.10 colorama-0.4.4 cssselect2-0.4.1 defusedxml-0.7.1 docutils-0.16 idna-3.3 imagesize-1.3.0 livereload-2.6.3 nmigen-0.2 packaging-21.3 pillow-9.0.0 pycparser-2.21 pyparsing-3.0.7 pytz-2021.3 pyvcd-0.1.7 requests-2.27.1 six-1.16.0 snowballstemmer-2.2.0 sphinx-3.5.4 sphinx-autobuild-2021.3.14 sphinx-symbiflow-theme-0.1.11 sphinx-tabs-3.2.0 sphinxcontrib-applehelp-1.0.2 sphinxcontrib-devhelp-1.0.2 sphinxcontrib-hdl-diagrams-0.0.dev0 sphinxcontrib-htmlhelp-2.0.0 sphinxcontrib-jsmath-1.0.1 sphinxcontrib-qthelp-1.0.3 sphinxcontrib-serializinghtml-1.1.5 sphinxcontrib-session-0.0.1 sphinxcontrib-wavedrom-3.0.2 svgwrite-1.4.1 tinycss2-1.1.1 tornado-6.1 urllib3-1.26.8 wasmtime-0.30.0 wavedrom-2.0.3.post2 webencodings-0.5.1 xcffib-0.11.1 yowasp-yosys-0.13.dev285 +WARNING: You are using pip version 21.2.4; however, version 22.0 is available. +You should consider upgrading via the 'E:\Code\Fomu\workshop\docs\Scripts\python.exe -m pip install --upgrade pip' command. +(docs) $ +``` + +Build HTML: +``` +(docs) $ sphinx-build -M html . _build +Running Sphinx v3.5.4 + + + +dumping search index in English (code: en)... done +dumping object inventory... done +build succeeded, 20 warnings. + +The HTML pages are in _build\html. +(docs) $ +``` + +Start your web browser: + +```shell-session +$ explorer ./_build/html/index.html +``` \ No newline at end of file diff --git a/im-tomu_fomu-workshop/README.md b/im-tomu_fomu-workshop/README.md new file mode 100644 index 0000000000000000000000000000000000000000..325d5fe36c2163aa69b93fe365dff24c002002e1 --- /dev/null +++ b/im-tomu_fomu-workshop/README.md @@ -0,0 +1,56 @@ +

+ +

+ +

+ + + 'test' workflow status + 'doc' workflow status +

+ +Hi, I'm Fomu! [This workshop](https://workshop.fomu.im/) covers the basics of Fomu in a top-down approach. +We'll start out by learning **what** Fomu is, **how to load software** into Fomu, **how to write software** for Fomu and +finally **how to write hardware** for Fomu. + +

+ + +

+ +FPGAs are complex, weird things, so we'll take a gentle approach and start out by treating it like a Python interpreter +first, and gradually peel away layers until we're writing our own hardware registers. +You can take a break at any time and explore! +Stop when you feel the concepts are too unfamiliar, or plough on and dig deep into the world of hardware. + +The contents of this workshop is published at [workshop.fomu.im](https://workshop.fomu.im). + +## Repository Contents + +- [docs](./docs) - The actual workshop directions and content. +- [hdl](./hdl) + - [verilog](./hdl/verilog) - The files required for the [Verilog on Fomu](https://workshop.fomu.im/en/latest/verilog.html) + section of the workshop. + - [vhdl](./hdl/vhdl) - The files required for the [VHDL on Fomu](https://workshop.fomu.im/en/latest/vhdl.html) section + of the workshop. + - [mixed](./hdl/mixed) - The files required for the [Mixed HDL on Fomu](https://workshop.fomu.im/en/latest/mixedhdl.html) + section of the workshop. +- [icestudio](./icestudio) - The files required for the [Fomu on IceStudio *Nightly*](https://workshop.fomu.im/en/latest/icestudio.html) + section of the workshop. +- [litex](./litex), [migen](./migen) - The files required for the [Migen and LiteX](https://workshop.fomu.im/en/latest/migen.html) + section of the workshop. +- [reference](./reference) - Extra reference documentation such as schematics and part datasheets. +- riscv + - [riscv-blink](./riscv-blink) - The files required for the [Fomu as a CPU](https://workshop.fomu.im/en/latest/riscv.html) + section of the workshop. + - [riscv-rust-blink](./riscv-rust-blink) - The files required for the [Fomu as a CPU, Using Rust](https://workshop.fomu.im/en/latest/riscv.html#using-rust) + section of the workshop. + +# Development + +For guidelines about how to develop the workshop or how to build the workshop +locally, see [DEVELOPMENT](DEVELOPMENT.md). diff --git a/im-tomu_fomu-workshop/docs/conf.py b/im-tomu_fomu-workshop/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..a244b2610368d5b7229b7f9dbab4a9eb12877ddf --- /dev/null +++ b/im-tomu_fomu-workshop/docs/conf.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config +import os +import re +import sys + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = 'FPGA Tomu (Fomu) Workshop' +copyright = '2019, Tomu Project Authors' +author = 'Tomu Project Authors' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ +# 'sphinx.ext.intersphinx', + 'sphinxcontrib.jquery', + 'sphinx.ext.todo', + 'sphinx.ext.githubpages', + 'sphinx.ext.extlinks', + 'sphinxcontrib_hdl_diagrams', + 'sphinx_tabs.tabs', + 'sphinxcontrib_session', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = ['.rst'] + +# The master toctree document. +master_doc = 'index' + +# Enable github links when not on readthedocs +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +if not on_rtd: + html_context = { + "display_github": True, # Integrate GitHub + "github_user": "im-tomu", # Username + "github_repo": "fomu-workshop", # Repo name + "github_version": "master", # Version + "conf_py_path": "/docs/", + } +else: + docs_dir = os.path.abspath(os.path.dirname(__file__)) + print("Docs dir is:", docs_dir) + import subprocess + subprocess.call('git fetch origin --unshallow', cwd=docs_dir, shell=True) + subprocess.check_call('git fetch origin --tags', cwd=docs_dir, shell=True) + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = re.sub('^v', '', os.popen('git describe ').read().strip()) +# The short X.Y version. +version = release + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [ + '_build', '_download', 'env', 'Thumbs.db', '.DS_Store', '*.sw*', +] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'default' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_symbiflow_theme' + +# Html logo in drawer. +# Fit in the drawer at the width of image is 240 px. +html_logo = '_static/logo.png' +html_favicon = '_static/icon.png' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +html_theme_options = { + # Specify a list of menu in Header. + # Tuples forms: + # ('Name', 'external url or path of pages in the document', + # boolean, 'icon name') + # + # Third argument: + # True indicates an external link. + # False indicates path of pages in the document. + # + # Fourth argument: + # Specify the icon name. + # For details see link. + # https://material.io/icons/ + 'header_links': [ + ('Workshop Home', 'index', False, 'home'), + ("Website", "https://fomu.im", True, 'web'), + ("GitHub", "https://github.com/im-tomu/fomu-workshop", True, 'code'), + ("Report Issue", "https://github.com/im-tomu/fomu-workshop/issues/new", True, 'bug_report'), + ("Buy", "https://j.mp/fomu-cs", True, 'shopping_cart'), + ("Contact", "help", False, 'live_help'), + ], + + # Customize css colors. + # For details see link. + # https://getmdl.io/customize/index.html + # + # Values: amber, blue, brown, cyan deep_orange, deep_purple, green, grey, + # indigo, light_blue, light_green, lime, orange, pink, purple, red, + # teal, yellow + # (Default: indigo) + 'primary_color': 'blue', + # Values: Same as primary_color. (Default: pink) + 'accent_color': 'orange', + + # Customize layout. + # For details see link. + # https://getmdl.io/components/index.html#layout-section + 'fixed_drawer': True, + 'fixed_header': True, + 'header_waterfall': True, + 'header_scroll': False, + + # Render title in header. + # Values: True, False (Default: False) + 'show_header_title': False, + # Render title in drawer. + # Values: True, False (Default: True) + 'show_drawer_title': True, + # Render footer. + # Values: True, False (Default: True) + 'show_footer': True, + + # Hide the symbiflow links + 'hide_symbiflow_links': True, +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +#html_sidebars = { +# '**': [ +# 'relations.html', # needs 'show_related': True theme option to display +# 'searchbox.html', +# ] +#} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'FPGATomuFomuWorkshopdoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'FPGATomuFomuWorkshop.tex', 'FPGA Tomu (Fomu) Workshop Documentation', + 'Tomu Project Authors', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'fpgatomufomuworkshop', 'FPGA Tomu (Fomu) Workshop Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'FPGATomuFomuWorkshop', 'FPGA Tomu (Fomu) Workshop Documentation', + author, 'FPGATomuFomuWorkshop', 'One line description of project.', + 'Miscellaneous'), +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} + +# -- Options for todo extension ---------------------------------------------- + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + +locale_dirs = ['translations/'] # path is example but recommended. +gettext_compact = False # optional. + +extlinks = { + 'repo': ('https://github.com/im-tomu/fomu-workshop/blob/master/%s', None) +} diff --git a/im-tomu_fomu-workshop/docs/environment.yml b/im-tomu_fomu-workshop/docs/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..ba6682d2aab157ea5848fe0a02cf4fe68f731c05 --- /dev/null +++ b/im-tomu_fomu-workshop/docs/environment.yml @@ -0,0 +1,15 @@ +name: fomu-workshop +channels: +- litex-hub +- conda-forge +- defaults +dependencies: +- python +- pip +- pycairo +- pango +- pygobject +- yosys +- netlistsvg +- pip: + - -r requirements.txt diff --git a/im-tomu_fomu-workshop/docs/requirements.txt b/im-tomu_fomu-workshop/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b66a91638f1a74b76ded9d846415c0447c70ff6 --- /dev/null +++ b/im-tomu_fomu-workshop/docs/requirements.txt @@ -0,0 +1,21 @@ +sphinx>=4.5.0 +sphinx-autobuild +sphinxcontrib-jquery + +# Better looking Sphinx theme +# sphinx_materialdesign_theme +git+http://github.com/SymbiFlow/sphinx_materialdesign_theme.git@master#egg=sphinx_symbiflow_theme + +# Support tabs for Linux / Mac / Windows +sphinx_tabs + +# Support copying without prompts. +git+https://github.com/mithro/sphinxcontrib-session.git#egg=sphinxcontrib-session + +#- HDL specific functionality + +# Wavedrom diagrams! +sphinxcontrib-wavedrom + +# Verilog diagrams using Yosys + netlistsvg +git+https://github.com/SymbiFlow/sphinxcontrib-hdl-diagrams.git#egg=sphinxcontrib-hdl-diagrams diff --git a/im-tomu_fomu-workshop/get-toolchain.py b/im-tomu_fomu-workshop/get-toolchain.py new file mode 100644 index 0000000000000000000000000000000000000000..415251812e04a00ca808c5b49bb6b0f9fab81b01 --- /dev/null +++ b/im-tomu_fomu-workshop/get-toolchain.py @@ -0,0 +1,150 @@ +#!/usr/bin/python + +from __future__ import print_function + +import hashlib +import json +import os +import sys + +if sys.version_info.major == 2: + from urllib import urlretrieve +elif sys.version_info.major == 3: + from urllib.request import urlretrieve +else: + sys.stderr.write("Unknown Python version") + sys.exit(1) + + +def platform(): + if 'linux' in sys.platform: + return 'Linux' + elif 'darwin' in sys.platform: + return 'macOS' + elif 'win' in sys.platform or 'msys' in sys.platform: + return 'Windows' + else: + return sys.platform + + +def reporthook(chunk, chunk_size, total_size): + # Be quiet on travis. + if os.environ.get('CI', False): + return + download_size = min(total_size, chunk * chunk_size) + print("Downloaded", download_size, "of", total_size, "%.2f%%" % (download_size*1.0/total_size*100.0)) + +def download_files(to_download): + for filename, url in to_download: + if "sha" in filename and "sha1" not in filename: + continue + if os.path.exists(filename): + continue + print("Downloading", url, "into", filename) + urlretrieve(url, filename, reporthook=reporthook) + + +def check_files(to_download): + sumfile = [f for f, u in to_download if f.endswith('sha1')][0] + print("Checksum file", sumfile) + sumfile_lines = [l.split() for l in open(sumfile, 'r').read().strip().splitlines()] + print(sumfile_lines) + + error = False + for wanted_checksum, path in sumfile_lines: + filename = os.path.basename(path) + + hasher = hashlib.sha1() + with open(filename, 'rb') as f: + while True: + data = f.read(4096) + if not data: + break + hasher.update(data) + + actual_checksum = hasher.hexdigest() + + if wanted_checksum != actual_checksum: + print( + filename, "removed broken file,", + "wanted checksum:", wanted_checksum, + "actual checksum:", actual_checksum, + ) + os.unlink(filename) + error = True + else: + print( + filename, "good file,", + "matching checksum:", actual_checksum, + ) + return not error + + +TOOLCHAIN = "https://api.github.com/repos/im-tomu/fomu-toolchain/releases/%s" % ("tags/nightly" if os.environ.get('CI', False) else "latest") + + +def get_toolchain_data(): + if sys.version_info.major == 2: + from urllib2 import urlopen, Request + elif sys.version_info.major == 3: + from urllib.request import urlopen, Request + + request = Request(TOOLCHAIN) + + token = os.environ.get('GH_TOKEN', None) + if token: + request.add_header('Authorization', 'token %s' % token) + + response = urlopen(request) + return json.loads(response.read()) + + +def main(argv): + toolchain_data = get_toolchain_data() + if 'assets' not in toolchain_data: + import pprint + pprint.pprint(toolchain_data) + + plat = platform() + print("Platform:", plat) + + to_download = [] + + for asset in toolchain_data['assets']: + if plat not in asset['name']: + continue + to_download.append((asset['name'], asset['browser_download_url'])) + + while True: + download_files(to_download) + if check_files(to_download): + break + + for tarball in [f for f, u in to_download if f.endswith(('.tar.gz', '.tar.xz'))]: + import tarfile + + with tarfile.open(tarball) as tarf: + tarf.extractall() + + for zipball in [f for f, u in to_download if f.endswith('.zip')]: + import zipfile + class ZipFileWithPerm(zipfile.ZipFile): + def _extract_member(self, member, targetpath, pwd): + if not isinstance(member, zipfile.ZipInfo): + member = self.getinfo(member) + + targetpath = zipfile.ZipFile._extract_member(self, member, targetpath, pwd) + + attr = member.external_attr >> 16 + if attr != 0: + os.chmod(targetpath, attr) + return targetpath + + with ZipFileWithPerm(zipball) as zipf: + zipf.extractall() + + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/im-tomu_fomu-workshop/hdl/mixed/blink/README.md b/im-tomu_fomu-workshop/hdl/mixed/blink/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e74fa6b1a2e50bea05e9d1e0e0157f4726c0dee --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/mixed/blink/README.md @@ -0,0 +1,22 @@ +# Minimal Mixed HDL Example (VHDL and Verilog) + +A minimal mixed HDL example which simply blinks the RGB LEDs at different +frequencies. + +This example contains equivalent sources in VHDL and Verilog, which can be +combined freely: + +- `blink.vhd` + `clkgen.v` +- `blink.v` + `clkgen.vhdl` +- `blink.vhd` + `clkgen.vhdl` +- `blink.v` + `clkgen.v` + +All four cases produce exactly the same result, because the same design is +described regardless of the HDL language used. In the makefile, the first +case is built by default. + +## Using + +Type `make` to build the DFU image. +Type `make load` to load the DFU image onto the Fomu board. +Type `make clean` to remove all the generated files. diff --git a/im-tomu_fomu-workshop/hdl/mixed/blink/blink.v b/im-tomu_fomu-workshop/hdl/mixed/blink/blink.v new file mode 100644 index 0000000000000000000000000000000000000000..61b6dd705c85c470eea5417b4f12350ce9b98e12 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/mixed/blink/blink.v @@ -0,0 +1,77 @@ +// Simple tri-colour LED blink example. + +// Correctly map pins for the iCE40UP5K SB_RGBA_DRV hard macro. +// The variables EVT, PVT and HACKER are set from the Makefile. +`ifdef EVT +`define BLUEPWM RGB0PWM +`define REDPWM RGB1PWM +`define GREENPWM RGB2PWM +`elsif HACKER +`define BLUEPWM RGB0PWM +`define GREENPWM RGB1PWM +`define REDPWM RGB2PWM +`elsif PVT +`define GREENPWM RGB0PWM +`define REDPWM RGB1PWM +`define BLUEPWM RGB2PWM +`else +`error_board_not_supported +`endif + +module Fomu_Blink ( + // 48MHz Clock input + // -------- + input clki, + // LED outputs + // -------- + output rgb0, + output rgb1, + output rgb2, + // USB Pins (which should be statically driven if not being used). + // -------- + output usb_dp, + output usb_dn, + output usb_dp_pu +); + + // Assign USB pins to "0" so as to disconnect Fomu from + // the host system. Otherwise it would try to talk to + // us over USB, which wouldn't work since we have no stack. + assign usb_dp = 1'b0; + assign usb_dn = 1'b0; + assign usb_dp_pu = 1'b0; + + wire [2:0] color; + + // Instantiate clkgen for reducing the system clock + clkgen clk_generator ( + .clk(clki), + .cnt(color) + ); + + // Instantiate iCE40 LED driver hard logic, connecting up + // counter state and LEDs. + // + // Note that it's possible to drive the LEDs directly, + // however that is not current-limited and results in + // overvolting the red LED. + // + // See also: + // https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 + SB_RGBA_DRV #( + .CURRENT_MODE("0b1"), // half current + .RGB0_CURRENT("0b000011"), // 4 mA + .RGB1_CURRENT("0b000011"), // 4 mA + .RGB2_CURRENT("0b000011") // 4 mA + ) RGBA_DRIVER ( + .CURREN(1'b1), + .RGBLEDEN(1'b1), + .`BLUEPWM(color[2]), // Blue + .`REDPWM(color[1]), // Red + .`GREENPWM(color[0]), // Green + .RGB0(rgb0), + .RGB1(rgb1), + .RGB2(rgb2) + ); + +endmodule diff --git a/im-tomu_fomu-workshop/hdl/mixed/blink/blink.vhd b/im-tomu_fomu-workshop/hdl/mixed/blink/blink.vhd new file mode 100644 index 0000000000000000000000000000000000000000..300bc6b369c86793cff5fd4c13eff60db85bf75f --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/mixed/blink/blink.vhd @@ -0,0 +1,78 @@ +library ieee; +context ieee.ieee_std_context; + +use work.components.all; + +entity Fomu_Blink is + port ( + -- 48MHz Clock input + clki: in std_logic; + + -- LED outputs + rgb0: out std_logic; + rgb1: out std_logic; + rgb2: out std_logic; + + -- USB Pins (which should be statically driven if not being used) + usb_dp: out std_logic; + usb_dn: out std_logic; + usb_dp_pu: out std_logic + ); +end; + +architecture arch of Fomu_Blink is + + signal clk: std_logic; + signal color: std_logic_vector(2 downto 0) := (others=>'0'); + + component clkgen + port ( + clk: in std_logic; + cnt: out std_logic_vector(2 downto 0) + ); + end component; + +begin + + -- Assign USB pins to "0" so as to disconnect Fomu from + -- the host system. Otherwise it would try to talk to + -- us over USB, which wouldn't work since we have no stack. + usb_dp <= '0'; + usb_dn <= '0'; + usb_dp_pu <= '0'; + + -- Instantiate clkgen for reducing the system clock + clk_generator: clkgen + port map ( + clk => clki, + cnt => color + ); + + -- Instantiate iCE40 LED driver hard logic, connecting up + -- counter state and LEDs. + -- + -- Note that it's possible to drive the LEDs directly, + -- however that is not current-limited and results in + -- overvolting the red LED. + -- + -- See also: + -- https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 + rgba_driver: SB_RGBA_DRV + generic map ( + CURRENT_MODE => "0b1", -- half current + RGB0_CURRENT => "0b000011", -- 4 mA + RGB1_CURRENT => "0b000011", -- 4 mA + RGB2_CURRENT => "0b000011" -- 4 mA + ) + port map ( + CURREN => '1', + RGBLEDEN => '1', + RGB0PWM => color(2), + RGB1PWM => color(1), + RGB2PWM => color(0), + RGB0 => rgb0, + RGB1 => rgb1, + RGB2 => rgb2 + ); + +end; diff --git a/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.v b/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.v new file mode 100644 index 0000000000000000000000000000000000000000..4025dbfe47355c75f7243e4f0fd9245890bd64e8 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.v @@ -0,0 +1,21 @@ +module clkgen ( + input wire clk, + output wire [2:0] cnt +); + + // Connect to system clock (with buffering) + wire clko; + SB_GB clk_gb ( + .USER_SIGNAL_TO_GLOBAL_BUFFER(clk), + .GLOBAL_BUFFER_OUTPUT(clko) + ); + + // Use counter logic to divide system clock. The clock is 48 MHz, + // so we divide it down by 2^28. + reg [28:0] counter = 0; + always @(posedge clko) begin + counter <= counter + 1; + end + assign cnt = counter[25:23]; + +endmodule diff --git a/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.vhd b/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.vhd new file mode 100644 index 0000000000000000000000000000000000000000..3a6435deadfeba0f4edea4ba7ade38ab08c9b981 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/mixed/blink/clkgen.vhd @@ -0,0 +1,38 @@ +library ieee; +context ieee.ieee_std_context; + +use work.components.all; + +entity clkgen is + port ( + clk : in std_logic; + cnt : out std_logic_vector(2 downto 0) + ); +end; + +architecture arch of clkgen is + + signal clko: std_logic; + signal counter: unsigned(27 downto 0) := (others=>'0'); + +begin + + -- Connect to system clock (with buffering) + clk_gb: SB_GB + port map ( + USER_SIGNAL_TO_GLOBAL_BUFFER => clk, + GLOBAL_BUFFER_OUTPUT => clko + ); + + -- Use counter logic to divide system clock. The clock is 48 MHz, + -- so we divide it down by 2^28. + process(clko) + begin + if rising_edge(clko) then + counter <= counter + 1; + end if; + end process; + + cnt <= std_logic_vector(counter(counter'left downto counter'left-cnt'length+1)); + +end; diff --git a/im-tomu_fomu-workshop/hdl/sb_ice40_components.vhd b/im-tomu_fomu-workshop/hdl/sb_ice40_components.vhd new file mode 100644 index 0000000000000000000000000000000000000000..af0244c7dc662e486afde3de7340a66156c41466 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/sb_ice40_components.vhd @@ -0,0 +1,32 @@ +library ieee ; +use ieee.std_logic_1164.all; + +package components is + +component SB_GB + port( + GLOBAL_BUFFER_OUTPUT : out std_logic; + USER_SIGNAL_TO_GLOBAL_BUFFER : in std_logic + ); +end component; + +component SB_RGBA_DRV + generic ( + CURRENT_MODE : string := "0b0"; + RGB0_CURRENT : string := "0b000000"; + RGB1_CURRENT : string := "0b000000"; + RGB2_CURRENT : string := "0b000000" + ); + port ( + RGB0PWM : in std_logic; + RGB1PWM : in std_logic; + RGB2PWM : in std_logic; + CURREN : in std_logic; + RGBLEDEN : in std_logic; + RGB0 : out std_logic; + RGB1 : out std_logic; + RGB2 : out std_logic + ); +end component; + +end components; diff --git a/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/README.md b/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cc5b96c1838428d6c4c4611834b0e2ba899317e5 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/README.md @@ -0,0 +1,10 @@ +# Minimal Verilog Example - Expanded Version + +A minimal Verilog example which permanantly blinks the green LED and +supports enabling the red and blue LED by button press or connecting pins. + +## Using + +Type `make` to build the DFU image. +Type `dfu-util -D blink.dfu` to load the DFU image onto the Fomu board. +Type `make clean` to remove all the generated files. diff --git a/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/blink.v b/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/blink.v new file mode 100644 index 0000000000000000000000000000000000000000..b48cf61796622ed3ca71bacfc7822295bd5598db --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/verilog/blink-expanded/blink.v @@ -0,0 +1,166 @@ +// Simple tri-colour LED blink example, with button control +// +// Green LED blinks forever, blue and red LED can be turned on by connecting +// pins or pressing buttons. +// +// On EVT Fomu boards: +// +// 1st LED colour - Blue - controlled by pressing Button 5, or connect 1 to 2 +// 2nd LED colour - Red - controlled by pressing Button 6, or connect 3 to 4 +// 3rd LED colour - Green - controlled by clock (blinking) +// +// On DVT / Hacker / Production Fomu boards: +// +// 1st LED colour - Blue - turn on by connecting pin 1 to pin 2 +// 2nd LED colour - Green - controlled by clock (blinking) +// 3rd LED colour - Red - turn on by connecting pin 3 to pin 4 +// +// We use `defines to handle these two cases, because the SB_RGBA_DRV +// iCE40UP5K hard macro is unable to do RGBn to output pin mapping internally +// (the RGB0 / RGB1 / RGB2 parameters to SB_RGBA_DRV *must* be mapped +// to the same named RGB0 / RGB1 / RGB2 physical pins; arachne-pnr +// errors if they are not, and currently nextpnr just ignores mismapped +// pins and enforces this mapping) +// +// This is all kludged into a single file to make a standalone simple test; +// a better design would wrap SB_RGBA_DRV into a Fomu specific module and +// hide the LED colour mapping; and also set the appropriate pins for +// the buttons at instantiation time. +// +`ifdef EVT +`define BLUEPWM RGB0PWM +`define REDPWM RGB1PWM +`define GREENPWM RGB2PWM +`elsif HACKER +`define BLUEPWM RGB0PWM +`define GREENPWM RGB1PWM +`define REDPWM RGB2PWM +`elsif PVT +`define GREENPWM RGB0PWM +`define REDPWM RGB1PWM +`define BLUEPWM RGB2PWM +`else +`error_board_not_supported +`endif + +module blink ( + // 48MHz Clock input + // -------- + input clki, + // LED outputs + // -------- + output rgb0, + output rgb1, + output rgb2, + // User touchable pins + // -------- + // Connect 1-2 to enable blue LED + input user_1, + output user_2, + // Connect 3-4 to enable red LED + output user_3, + input user_4, + // USB Pins (which should be statically driven if not being used). + // -------- + output usb_dp, + output usb_dn, + output usb_dp_pu +); + + // Assign USB pins to "0" so as to disconnect Fomu from + // the host system. Otherwise it would try to talk to + // us over USB, which wouldn't work since we have no stack. + assign usb_dp = 1'b0; + assign usb_dn = 1'b0; + assign usb_dp_pu = 1'b0; + + // Connect to system clock (with buffering) + wire clk; + SB_GB clk_gb ( + .USER_SIGNAL_TO_GLOBAL_BUFFER(clki), + .GLOBAL_BUFFER_OUTPUT(clk) + ); + + // Configure user pins so that we can detect the user connecting + // 1-2 or 3-4 with conductive material. + // + // We do this by grounding user_2 and user_3, and configuring inputs + // with pullups on user_1 and user_4. + assign user_2 = 1'b0; + assign user_3 = 1'b0; + + localparam SB_IO_TYPE_SIMPLE_INPUT = 6'b000001; + + wire user_1_pulled; + SB_IO #( + .PIN_TYPE(SB_IO_TYPE_SIMPLE_INPUT), + .PULLUP(1'b1) + ) user_1_io ( + .PACKAGE_PIN(user_1), + .OUTPUT_ENABLE(1'b0), + .INPUT_CLK(clk), + .D_IN_0(user_1_pulled), + ); + + wire user_4_pulled; + SB_IO #( + .PIN_TYPE(SB_IO_TYPE_SIMPLE_INPUT), + .PULLUP(1'b 1) + ) user_4_io ( + .PACKAGE_PIN(user_4), + .OUTPUT_ENABLE(1'b0), + .INPUT_CLK(clk), + .D_IN_0(user_4_pulled), + ); + + wire enable_blue = ~user_1_pulled; + wire enable_red = ~user_4_pulled; + + // Use counter logic to divide system clock. The clock is 48 MHz, + // so we divide it down by 2^28. + reg [28:0] counter = 0; + always @(posedge clk) begin + counter <= counter + 1; + end + + // Instantiate iCE40 LED driver hard logic, connecting up + // latched button state, counter state, and LEDs. + // + // Note that it's possible to drive the LEDs directly, + // however that is not current-limited and results in + // overvolting the red LED. + // + // See also: + // https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 + SB_RGBA_DRV RGBA_DRIVER ( + .CURREN(1'b1), + .RGBLEDEN(1'b1), + .`BLUEPWM(enable_blue), // Blue + .`REDPWM(enable_red), // Red + .`GREENPWM(counter[23]), // Green (blinking) + .RGB0(rgb0), + .RGB1(rgb1), + .RGB2(rgb2) + ); + + // Parameters from iCE40 UltraPlus LED Driver Usage Guide, pages 19-20 + localparam RGBA_CURRENT_MODE_FULL = "0b0"; + localparam RGBA_CURRENT_MODE_HALF = "0b1"; + + // Current levels in Full / Half mode + localparam RGBA_CURRENT_04MA_02MA = "0b000001"; + localparam RGBA_CURRENT_08MA_04MA = "0b000011"; + localparam RGBA_CURRENT_12MA_06MA = "0b000111"; + localparam RGBA_CURRENT_16MA_08MA = "0b001111"; + localparam RGBA_CURRENT_20MA_10MA = "0b011111"; + localparam RGBA_CURRENT_24MA_12MA = "0b111111"; + + // Set parameters of RGBA_DRIVER (output current) + // + // Mapping of RGBn to LED colours determined experimentally + defparam RGBA_DRIVER.CURRENT_MODE = RGBA_CURRENT_MODE_HALF; + defparam RGBA_DRIVER.RGB0_CURRENT = RGBA_CURRENT_16MA_08MA; // Blue - Needs more current. + defparam RGBA_DRIVER.RGB1_CURRENT = RGBA_CURRENT_08MA_04MA; // Red + defparam RGBA_DRIVER.RGB2_CURRENT = RGBA_CURRENT_08MA_04MA; // Green + +endmodule diff --git a/im-tomu_fomu-workshop/hdl/verilog/blink/README.md b/im-tomu_fomu-workshop/hdl/verilog/blink/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dadb1cbc75c80eb4b377489322fdb8d4fda341d6 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/verilog/blink/README.md @@ -0,0 +1,10 @@ +# Minimal Verilog Example + +A minimal Verilog example which simply blinks the RGB LEDs at different +frequencies. + +## Using + +Type `make` to build the DFU image. +Type `make load` to load the DFU image onto the Fomu board. +Type `make clean` to remove all the generated files. diff --git a/im-tomu_fomu-workshop/hdl/verilog/blink/blink.v b/im-tomu_fomu-workshop/hdl/verilog/blink/blink.v new file mode 100644 index 0000000000000000000000000000000000000000..1e09f5bdb3b4ed1adbddd0fb567b4e899fa85ec6 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/verilog/blink/blink.v @@ -0,0 +1,83 @@ +// Simple tri-colour LED blink example. + +// Correctly map pins for the iCE40UP5K SB_RGBA_DRV hard macro. +// The variables EVT, PVT and HACKER are set from the Makefile. +`ifdef EVT +`define BLUEPWM RGB0PWM +`define REDPWM RGB1PWM +`define GREENPWM RGB2PWM +`elsif HACKER +`define BLUEPWM RGB0PWM +`define GREENPWM RGB1PWM +`define REDPWM RGB2PWM +`elsif PVT +`define GREENPWM RGB0PWM +`define REDPWM RGB1PWM +`define BLUEPWM RGB2PWM +`else +`error_board_not_supported +`endif + +module top ( + // 48MHz Clock input + // -------- + input clki, + // LED outputs + // -------- + output rgb0, + output rgb1, + output rgb2, + // USB Pins (which should be statically driven if not being used). + // -------- + output usb_dp, + output usb_dn, + output usb_dp_pu +); + + // Assign USB pins to "0" so as to disconnect Fomu from + // the host system. Otherwise it would try to talk to + // us over USB, which wouldn't work since we have no stack. + assign usb_dp = 1'b0; + assign usb_dn = 1'b0; + assign usb_dp_pu = 1'b0; + + // Connect to system clock (with buffering) + wire clk; + SB_GB clk_gb ( + .USER_SIGNAL_TO_GLOBAL_BUFFER(clki), + .GLOBAL_BUFFER_OUTPUT(clk) + ); + + // Use counter logic to divide system clock. The clock is 48 MHz, + // so we divide it down by 2^28. + reg [28:0] counter = 0; + always @(posedge clk) begin + counter <= counter + 1; + end + + // Instantiate iCE40 LED driver hard logic, connecting up + // counter state and LEDs. + // + // Note that it's possible to drive the LEDs directly, + // however that is not current-limited and results in + // overvolting the red LED. + // + // See also: + // https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 + SB_RGBA_DRV #( + .CURRENT_MODE("0b1"), // half current + .RGB0_CURRENT("0b000011"), // 4 mA + .RGB1_CURRENT("0b000011"), // 4 mA + .RGB2_CURRENT("0b000011") // 4 mA + ) RGBA_DRIVER ( + .CURREN(1'b1), + .RGBLEDEN(1'b1), + .`BLUEPWM(counter[25]), // Blue + .`REDPWM(counter[24]), // Red + .`GREENPWM(counter[23]), // Green + .RGB0(rgb0), + .RGB1(rgb1), + .RGB2(rgb2) + ); + +endmodule diff --git a/im-tomu_fomu-workshop/hdl/vhdl/blink/README.md b/im-tomu_fomu-workshop/hdl/vhdl/blink/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d9edf52cd00e74b20bc17e998e838ff71f4cda7 --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/vhdl/blink/README.md @@ -0,0 +1,10 @@ +# Minimal VHDL Example + +A minimal VHDL example which simply blinks the RGB LEDs at different +frequencies. + +## Using + +Type `make` to build the DFU image. +Type `make load` to load the DFU image onto the Fomu board. +Type `make clean` to remove all the generated files. diff --git a/im-tomu_fomu-workshop/hdl/vhdl/blink/blink.vhd b/im-tomu_fomu-workshop/hdl/vhdl/blink/blink.vhd new file mode 100644 index 0000000000000000000000000000000000000000..25a94004f2089f15fbd7ad68cf0c90fdf31f652e --- /dev/null +++ b/im-tomu_fomu-workshop/hdl/vhdl/blink/blink.vhd @@ -0,0 +1,80 @@ +library ieee; +context ieee.ieee_std_context; + +use work.components.all; + +entity Fomu_Blink is + port ( + -- 48MHz Clock input + clki: in std_logic; + + -- LED outputs + rgb0: out std_logic; + rgb1: out std_logic; + rgb2: out std_logic; + + -- USB Pins (which should be statically driven if not being used) + usb_dp: out std_logic; + usb_dn: out std_logic; + usb_dp_pu: out std_logic + ); +end; + +architecture arch of Fomu_Blink is + + signal clk: std_logic; + signal counter: unsigned(27 downto 0) := (others=>'0'); + +begin + + -- Assign USB pins to "0" so as to disconnect Fomu from + -- the host system. Otherwise it would try to talk to + -- us over USB, which wouldn't work since we have no stack. + usb_dp <= '0'; + usb_dn <= '0'; + usb_dp_pu <= '0'; + + -- Connect to system clock (with buffering) + clk_gb: SB_GB + port map ( + USER_SIGNAL_TO_GLOBAL_BUFFER => clki, + GLOBAL_BUFFER_OUTPUT => clk + ); + + -- Use counter logic to divide system clock. The clock is 48 MHz, + -- so we divide it down by 2^28. + process(clk) + begin + if rising_edge(clk) then + counter <= counter + 1; + end if; + end process; + + -- Instantiate iCE40 LED driver hard logic, connecting up + -- counter state and LEDs. + -- + -- Note that it's possible to drive the LEDs directly, + -- however that is not current-limited and results in + -- overvolting the red LED. + -- + -- See also: + -- https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 + rgba_driver: SB_RGBA_DRV + generic map ( + CURRENT_MODE => "0b1", -- half current + RGB0_CURRENT => "0b000011", -- 4 mA + RGB1_CURRENT => "0b000011", -- 4 mA + RGB2_CURRENT => "0b000011" -- 4 mA + ) + port map ( + CURREN => '1', + RGBLEDEN => '1', + RGB0PWM => counter(counter'left), + RGB1PWM => counter(counter'left-1), + RGB2PWM => counter(counter'left-2), + RGB0 => rgb0, + RGB1 => rgb1, + RGB2 => rgb2 + ); + +end; diff --git a/im-tomu_fomu-workshop/litex/lxbuildenv.py b/im-tomu_fomu-workshop/litex/lxbuildenv.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcb2e61d5df61bad5b66d611f662521b0365f37 --- /dev/null +++ b/im-tomu_fomu-workshop/litex/lxbuildenv.py @@ -0,0 +1,606 @@ +#!/usr/bin/env python3 + +# This script enables easy, cross-platform building without the need +# to install third-party Python modules. + +LXBUILDENV_VERSION = '2019.8.19.1' +import sys +import os +import subprocess +import argparse + + +DEPS_DIR = "deps" + +DEFAULT_DEPS = { + 'migen': 'https://github.com/m-labs/migen.git', + 'litex': 'https://github.com/enjoy-digital/litex.git', + 'litedram': 'https://github.com/enjoy-digital/litedram.git', + 'litex_boards': 'https://github.com/litex-hub/litex-boards.git', + 'litescope': 'https://github.com/enjoy-digital/litescope.git', + 'pyserial': 'https://github.com/pyserial/pyserial.git', +} + +OPTIONAL_DEPS = { + 'liteeth': 'https://github.com/enjoy-digital/liteeth.git', + 'liteusb': 'https://github.com/enjoy-digital/liteusb.git', + 'litepcie': 'https://github.com/enjoy-digital/litepcie.git', + 'litesdcard': 'https://github.com/enjoy-digital/litesdcard.git', + 'liteiclink': 'https://github.com/enjoy-digital/liteiclink.git', + 'litevideo': 'https://github.com/enjoy-digital/litevideo.git', + 'usb': 'https://github.com/pyusb/pyusb.git', +} + +# Obtain the path to this script, plus a trailing separator. This will +# be used later on to construct various environment variables for paths +# to a variety of support directories. +script_path = os.path.dirname(os.path.realpath(__file__)) + os.path.sep + +# Look through the specified file for known variables to get the dependency list +def read_configuration(filename, args): + import ast + + # Always check the Python version + dependencies = { + 'python': 1 + } + configuration = { + 'skip-git': False + } + main_src = "" + + try: + with open(sys.argv[0], 'r') as f: + main_src = f.read() + main_ast = ast.parse(main_src, filename=filename) + except: + configuration['dependencies'] = list(dependencies.keys()) + return configuration + + # Iterate through the top-level nodes looking for variables named + # LX_DEPENDENCIES or LX_DEPENDENCY and get the values that are + # assigned to them. + for node in ast.iter_child_nodes(main_ast): + if isinstance(node, ast.Assign): + value = node.value + for target in node.targets: + if isinstance(target, ast.Name): + if target.id == "LX_DEPENDENCIES" or target.id == "LX_DEPENDENCY": + if isinstance(value, (ast.List, ast.Tuple)): + for elt in value.elts: + if isinstance(elt, ast.Str): + dependencies[elt.s] = 1 + elif isinstance(value, ast.Str): + dependencies[value.s] = 1 + elif target.id == "LX_CONFIGURATION" or target.id == "LX_CONFIG": + if isinstance(value, (ast.List, ast.Tuple)): + for elt in value.elts: + if isinstance(elt, ast.Str): + configuration[elt.s] = True + elif isinstance(value, ast.Str): + configuration[value.s] = True + + # Set up sub-dependencies + if 'riscv' in dependencies: + dependencies['make'] = 1 + if args.lx_check_git or (not configuration['skip-git'] and not args.lx_ignore_git): + dependencies['git'] = 1 + configuration['dependencies'] = list(dependencies.keys()) + return configuration + +def get_python_path(script_path, args): + # Python has no concept of a local dependency path, such as the C `-I`` + # switch, or the nodejs `node_modules` path, or the rust cargo registry. + # Instead, it relies on an environment variable to append to the search + # path. + # Construct this variable by adding each subdirectory under the `deps/` + # directory to the PYTHONPATH environment variable. + python_path = [] + if os.path.isdir(script_path + DEPS_DIR): + for dep in os.listdir(script_path + DEPS_DIR): + dep = script_path + DEPS_DIR + os.path.sep + dep + if os.path.isdir(dep): + python_path.append(dep) + return python_path + +def fixup_env(script_path, args): + os.environ["PYTHONPATH"] = os.pathsep.join(get_python_path(script_path, 0)) + + # Set the "LXBUILDENV_REEXEC" variable to prevent the script from continuously + # reinvoking itself. + os.environ["LXBUILDENV_REEXEC"] = "1" + + # Python randomizes the order in which it traverses hashes, and Migen uses + # hashes an awful lot when bringing together modules. As such, the order + # in which Migen generates its output Verilog will change with every run, + # and the addresses for various modules will change. + # Make builds deterministic so that the generated Verilog code won't change + # across runs. + os.environ["PYTHONHASHSEED"] = "1" + + # Some Makefiles are invoked as part of the build process, and those Makefiles + # occasionally have calls to Python. Ensure those Makefiles use the same + # interpreter that this script is using. + os.environ["PYTHON"] = sys.executable + + # Set the environment variable "V" to 1. This causes Makefiles to print + # the commands they run, which makes them easier to debug. + if "lx_verbose" in args and args.lx_verbose: + os.environ["V"] = "1" + + # If the user just wanted to print the environment variables, do that and quit. + if args.lx_print_env: + print("PYTHONPATH={}".format(os.environ["PYTHONPATH"])) + print("PYTHONHASHSEED={}".format(os.environ["PYTHONHASHSEED"])) + print("PYTHON={}".format(sys.executable)) + print("LXBUILDENV_REEXEC={}".format(os.environ["LXBUILDENV_REEXEC"])) + + sys.exit(0) + +# Equivalent to the powershell Get-Command, and kinda like `which` +def get_command(cmd): + if os.name == 'nt': + path_ext = os.environ["PATHEXT"].split(os.pathsep) + else: + path_ext = [""] + for ext in path_ext: + for path in os.environ["PATH"].split(os.pathsep): + if os.path.exists(path + os.path.sep + cmd + ext): + return path + os.path.sep + cmd + ext + return None + +def check_python_version(args): + import platform + # Litex / Migen require Python 3.5 or newer. Ensure we're running + # under a compatible version of Python. + if sys.version_info[:3] < (3, 5): + return (False, + "python: You need Python 3.5+ (version {} found)".format(sys.version_info[:3])) + return (True, "python 3.5+: ok (Python {} found)".format(platform.python_version())) + +def check_vivado(args): + vivado_path = get_command("vivado") + if vivado_path == None: + # Look for the default Vivado install directory + if os.name == 'nt': + base_dir = r"C:\Xilinx\Vivado" + else: + base_dir = "/opt/Xilinx/Vivado" + if os.path.exists(base_dir): + for file in os.listdir(base_dir): + bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin" + if os.path.exists(bin_dir + os.path.sep + "vivado"): + os.environ["PATH"] += os.pathsep + bin_dir + vivado_path = bin_dir + break + if vivado_path == None: + return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html") + return (True, "found at {}".format(vivado_path)) + +def check_cmd(args, cmd, name=None, fix=None): + if name is None: + name = cmd + path = get_command(cmd) + if path == None: + return (False, name + " not found in your PATH", fix) + return (True, "found at {}".format(path)) + +def check_make(args): + return check_cmd(args, "make", "GNU Make") + +def check_riscv(args): + riscv64 = check_cmd(args, "riscv64-unknown-elf-gcc", "riscv toolchain", "download it from https://www.sifive.com/boards/") + if riscv64[0] == True: + return riscv64 + + riscv32 = check_cmd(args, "riscv32-unknown-elf-gcc", "riscv toolchain", "download it from https://www.sifive.com/boards/") + if riscv32[0] == True: + return riscv32 + + return riscv64 + +def check_yosys(args): + return check_cmd(args, "yosys") + +def check_arachne(args): + return check_cmd(args, "arachne-pnr") + +def check_git(args): + return check_cmd(args, "git") + +def check_icestorm(args): + return check_cmd(args, "icepack") + +def check_nextpnr_ice40(args): + return check_cmd(args, "nextpnr-ice40") + +dependency_checkers = { + 'python': check_python_version, + 'vivado': check_vivado, + 'make': check_make, + 'git': check_git, + 'riscv': check_riscv, + 'yosys': check_yosys, + 'arachne-pnr': check_arachne, + 'icestorm': check_icestorm, + 'nextpnr-ice40': check_nextpnr_ice40, +} + +# Validate that the required dependencies (Vivado, compilers, etc.) +# have been installed. +def check_dependencies(args, dependency_list): + dependency_errors = 0 + for dependency_name in dependency_list: + if not dependency_name in dependency_checkers: + print('lxbuildenv: WARNING: Unrecognized dependency "{}"'.format(dependency_name)) + continue + result = dependency_checkers[dependency_name](args) + if result[0] == False: + if len(result) > 2: + print('lxbuildenv: {}: {} -- {}'.format(dependency_name, result[1], result[2])) + else: + print('lxbuildenv: {}: {}'.format(dependency_name, result[1])) + dependency_errors = dependency_errors + 1 + + elif args.lx_check_deps or args.lx_verbose: + print('lxbuildenv: dependency: {}: {}'.format(dependency_name, result[1])) + if dependency_errors > 0: + if args.lx_ignore_deps: + if not args.lx_quiet: + print('lxbuildenv: {} missing dependencies were found but continuing anyway'.format(dependency_errors)) + else: + if not args.lx_quiet: + print('lxbuildenv: To ignore dependencies, re-run with "--lx-ignore-deps"') + raise SystemExit(str(dependency_errors) + + " missing dependencies were found") + + if args.lx_check_deps: + sys.exit(0) + +# Return True if the given tree needs to be initialized +def check_module_recursive(root_path, depth, verbose=False, breadcrumbs=[]): + if verbose: + print('git-dep: checking if "{}" requires updating (depth: {})...'.format(root_path, depth)) + + # If the directory isn't a valid git repo, initialization is required + git_dir_cmd = subprocess.Popen(["git", "rev-parse", "--show-toplevel"], + cwd=root_path, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + (git_stdout, _) = git_dir_cmd.communicate() + if git_dir_cmd.wait() != 0: + if verbose: + print('git-dep: missing git directory, starting update...') + return True + git_dir = git_stdout.decode().strip() + + if git_dir in breadcrumbs: + if verbose: + print('git-dep: root path {} is not in git path'.format(root_path)) + return True + breadcrumbs.append(git_dir) + + if not os.path.exists(git_dir + os.path.sep + '.git'): + if verbose: + print('git-dep: .git not found in "{}"'.format(git_dir)) + return True + + # If there are no submodules, no initialization needs to be done + if not os.path.isfile(git_dir + os.path.sep + '.gitmodules'): + if verbose: + print('git-dep: .gitmodules not found in "{}", so not updating'.format(git_dir)) + return False + + # Loop through the gitmodules to check all submodules + gitmodules = open(git_dir + os.path.sep + '.gitmodules', 'r') + for line in gitmodules: + parts = line.split("=", 2) + if parts[0].strip() == "path": + path = parts[1].strip() + if check_module_recursive(git_dir + os.path.sep + path, depth + 1, verbose=verbose, breadcrumbs=breadcrumbs): + return True + return False + +# Determine whether we need to invoke "git submodules init --recurse" +def check_submodules(script_path, args): + if check_module_recursive(script_path, 0, verbose=args.lx_verbose): + if not args.lx_quiet: + print("lxbuildenv: Missing git submodules -- updating") + print("lxbuildenv: To ignore git issues, re-run with --lx-ignore-git") + subprocess.Popen(["git", "submodule", "update", + "--init", "--recursive"], cwd=script_path).wait() + elif args.lx_verbose: + if not args.lx_quiet: + print("lxbuildenv: Submodule check: Submodules found") + + +def lx_git(cmd, *args): + import subprocess + git_cmd = ["git", cmd] + if args is not None: + for arg in args: + git_cmd = git_cmd + [arg] + subprocess.call(git_cmd) + +def lx_print_deps(): + print('lxbuildenv: Supported dependencies:') + for dep in dependency_checkers.keys(): + print('lxbuildenv: {}'.format(dep)) + print('lxbuildenv: To define a dependency, add a variable inside {} at the top level called LX_DEPENDENCIES and assign it a list or tuple.'.format(sys.argv[0])) + print('lxbuildenv: For example:') + print('lxbuildenv: LX_DEPENDENCIES = ("riscv", "vivado")') + + +def lx_main(args): + if args.lx_print_env: + fixup_env(script_path, args) + + elif args.lx_print_deps: + lx_print_deps() + + elif args.lx_run is not None: + script_name=args.lx_run[0] + config = read_configuration(script_name, args) + + fixup_env(script_path, args) + if not config['skip-git']: + check_submodules(script_path, args) + + try: + sys.exit(subprocess.Popen( + [sys.executable] + [script_name] + args.lx_run[1:]).wait()) + except: + sys.exit(1) + elif args.init: + if args.main is None: + main_name = os.getcwd().split(os.path.sep)[-1] + '.py' + new_main_name = input('lxbuildenv: What would you like your main program to be called? [' + main_name + '] ') + if new_main_name is not None and new_main_name != "": + main_name = new_main_name + else: + main_name = args.main + if not main_name.endswith('.py'): + main_name = main_name + '.py' + + if args.no_git: + print("lxbuildenv: skipping git initialization") + else: + if not os.path.exists(DEPS_DIR): + os.mkdir(DEPS_DIR) + + if not os.path.exists(".git"): + print("lxbuildenv: initializing git repository") + lx_git('init') + else: + print("lxbuildenv: using existing git repository") + lx_git('add', str(__file__)) + + for dep_name, dep_url in DEFAULT_DEPS.items(): + dest_path = '{}{}{}'.format(DEPS_DIR, '/', dep_name) + if not os.path.exists(dest_path): + lx_git('submodule', 'add', dep_url, dest_path) + lx_git('add', dest_path) + + lx_git('submodule', 'update', '--init', '--recursive') + + if args.no_bin: + print("lxbuildenv: skipping bin/ initialization") + elif os.path.exists("bin"): + print("lxbuildenv: bin/ directory exists -- remove bin/ directory to re-initialize") + else: + bin_tools = { + 'mkmscimg': 'litex.soc.software.mkmscimg', + 'litex_term': 'litex.tools.litex_term', + 'litex_server': 'litex.tools.litex_server', + 'litex_sim': 'litex.tools.litex_sim', + 'litex_read_verilog': 'litex.tools.litex_read_verilog', + 'litex_simple': 'litex.boards.targets.simple', + } + bin_template = """#!/usr/bin/env python3 + +import sys +import os + +# This script lives in the "bin" directory, but uses a helper script in the parent +# directory. Obtain the current path so we can get the absolute parent path. +script_path = os.path.dirname(os.path.realpath( + __file__)) + os.path.sep + os.path.pardir + os.path.sep +sys.path.insert(0, script_path) +import lxbuildenv + +""" + print("lxbuildenv: Creating binaries") + os.mkdir("bin") + for bin_name, python_module in bin_tools.items(): + with open('bin' + os.path.sep + bin_name, 'w', newline='\n') as new_bin: + new_bin.write(bin_template) + new_bin.write('from ' + python_module + ' import main\n') + new_bin.write('main()\n') + import stat + os.chmod('bin' + os.path.sep + bin_name, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + if not args.no_git: + lx_git('add', '--chmod=+x', 'bin' + os.path.sep + bin_name) + + if os.path.exists(main_name): + print("lxbuildenv: skipping creation of {}: file exists".format(main_name)) + else: + print("lxbuildenv: creating main program {}".format(main_name)) + with open(main_name, 'w') as m: + program_template = """#!/usr/bin/env python3 +# This variable defines all the external programs that this module +# relies on. lxbuildenv reads this variable in order to ensure +# the build will finish without exiting due to missing third-party +# programs. +LX_DEPENDENCIES = ["riscv", "vivado"] + +# Import lxbuildenv to integrate the deps/ directory +import lxbuildenv + +# Disable pylint's E1101, which breaks completely on migen +#pylint:disable=E1101 + +from migen import * +from litex.build.xilinx import VivadoProgrammer, XilinxPlatform +from litex.build.generic_platform import Pins, IOStandard +from litex.soc.integration import SoCSDRAM +from litex.soc.integration.builder import Builder +from litex.soc.integration.soc_core import csr_map_update + +_io = [ + ("clk50", 0, Pins("J19"), IOStandard("LVCMOS33")), +] + +class Platform(XilinxPlatform): + def __init__(self, toolchain="vivado", programmer="vivado", part="35"): + part = "xc7a" + part + "t-fgg484-2" + def create_programmer(self): + if self.programmer == "vivado": + return VivadoProgrammer(flash_part="n25q128-3.3v-spi-x1_x2_x4") + else: + raise ValueError("{} programmer is not supported" + .format(self.programmer)) + + def do_finalize(self, fragment): + XilinxPlatform.do_finalize(self, fragment) + +class BaseSoC(SoCSDRAM): + csr_peripherals = [ + "ddrphy", +# "dna", + "xadc", + "cpu_or_bridge", + ] + csr_map_update(SoCSDRAM.csr_map, csr_peripherals) + + def __init__(self, platform, **kwargs): + clk_freq = int(100e6) + +def main(): + platform = Platform() + soc = BaseSoC(platform) + builder = Builder(soc, output_dir="build", csr_csv="test/csr.csv") + vns = builder.build() + soc.do_exit(vns) + +if __name__ == "__main__": + main() +""" + m.write(program_template) + if not args.no_git: + lx_git("add", main_name) + else: + return False + return True + +# For the main command, parse args and hand it off to main() +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Wrap Python code to enable quickstart", + add_help=False) + parser.add_argument( + "-h", "--help", '--lx-help', help="show this help message and exit", action="help" + ) + parser.add_argument( + '-i', '--init', '--lx-init', help='initialize a new project', action="store_true" + ) + parser.add_argument( + '-m', '--main', '--lx-main', help='name of main project' + ) + parser.add_argument( + '--no-bin', '--lx-no-bin', help="don't create a bin/ directory" + ) + parser.add_argument( + '--no-git', '--lx-no-git', help="Don't create a git repository" + ) + parser.add_argument( + '-e', '--print-env', '--lx-print-env', dest="lx_print_env", help="print environment variable listing for pycharm, vscode, or bash", action="store_true" + ) + parser.add_argument( + '-d', '--print-deps', '--lx-print-deps', dest="lx_print_deps", help="print all possible dependencies and then exit", action="store_true" + ) + parser.add_argument( + "--lx-verbose", help="increase verboseness of some processes", action="store_true" + ) + parser.add_argument( + '-r', '--run', '--lx-run', dest='lx_run', help="run the given script under lxbuildenv", nargs=argparse.REMAINDER + ) + args = parser.parse_args() + + if not lx_main(args): + parser.print_help() + +elif not os.path.isfile(sys.argv[0]): + print("lxbuildenv doesn't operate while in interactive mode") + +elif "LXBUILDENV_REEXEC" not in os.environ: + parser = argparse.ArgumentParser( + description="Wrap Python code to enable quickstart", + add_help=False) + parser.add_argument( + "--lx-verbose", help="increase verboseness of some processes", action="store_true" + ) + parser.add_argument( + "--lx-quiet", help="decrease verboseness of some processes", action="store_true" + ) + parser.add_argument( + "--lx-print-env", help="print environment variable listing for pycharm, vscode, or bash", action="store_true" + ) + parser.add_argument( + "--lx-check-deps", help="check build environment for dependencies such as compiler and fpga tools and then exit", action="store_true" + ) + parser.add_argument( + "--lx-print-deps", help="print all possible dependencies and then exit", action="store_true" + ) + parser.add_argument( + "--lx-help", action="help" + ) + parser.add_argument( + "--lx-ignore-deps", help="try building even if dependencies are missing", action="store_true" + ) + parser.add_argument( + "--lx-ignore-git", help="don't do a check of the git repo", action="store_true" + ) + parser.add_argument( + "--lx-check-git", help="force a git check even if it's otherwise disabled", action="store_true" + ) + (args, rest) = parser.parse_known_args() + + if not args.lx_quiet: + print("lxbuildenv: v{} (run {} --lx-help for help)".format(LXBUILDENV_VERSION, sys.argv[0])) + + if args.lx_print_deps: + lx_print_deps() + sys.exit(0) + + config = read_configuration(sys.argv[0], args) + deps = config['dependencies'] + + fixup_env(script_path, args) + check_dependencies(args, deps) + if args.lx_check_git: + check_submodules(script_path, args) + elif config['skip-git']: + if not args.lx_quiet: + print('lxbuildenv: Skipping git configuration because "skip-git" was found in LX_CONFIGURATION') + print('lxbuildenv: To fetch from git, run {} --lx-check-git'.format(" ".join(sys.argv))) + elif args.lx_ignore_git: + if not args.lx_quiet: + print('lxbuildenv: Skipping git configuration because "--lx-ignore-git" Was specified') + else: + check_submodules(script_path, args) + + try: + sys.exit(subprocess.Popen( + [sys.executable] + [sys.argv[0]] + rest).wait()) + except Exception as e: + print(e) + sys.exit(1) +else: + # Overwrite the deps directory. + # Because we're running with a predefined PYTHONPATH, you'd think that + # the DEPS_DIR would be first. + # Unfortunately, setuptools causes the sitewide packages to take precedence + # over the PYTHONPATH variable. + # Work around this bug by inserting paths into the first index. + for path in get_python_path(script_path, None): + sys.path.insert(0, path) diff --git a/im-tomu_fomu-workshop/litex/rtl/2-stage-1024-cache.v b/im-tomu_fomu-workshop/litex/rtl/2-stage-1024-cache.v new file mode 100644 index 0000000000000000000000000000000000000000..669e3a67cad2671f09eae0fff52a02c5f9655e07 --- /dev/null +++ b/im-tomu_fomu-workshop/litex/rtl/2-stage-1024-cache.v @@ -0,0 +1,3289 @@ +// Generator : SpinalHDL v1.3.3 git head : 8b8cd335eecbea3b5f1f970f218a982dbdb12d99 +// Date : 25/04/2019, 15:31:44 +// Component : VexRiscv + + +`define EnvCtrlEnum_defaultEncoding_type [1:0] +`define EnvCtrlEnum_defaultEncoding_NONE 2'b00 +`define EnvCtrlEnum_defaultEncoding_XRET 2'b01 +`define EnvCtrlEnum_defaultEncoding_ECALL 2'b10 +`define EnvCtrlEnum_defaultEncoding_EBREAK 2'b11 + +`define Src2CtrlEnum_defaultEncoding_type [1:0] +`define Src2CtrlEnum_defaultEncoding_RS 2'b00 +`define Src2CtrlEnum_defaultEncoding_IMI 2'b01 +`define Src2CtrlEnum_defaultEncoding_IMS 2'b10 +`define Src2CtrlEnum_defaultEncoding_PC 2'b11 + +`define Src1CtrlEnum_defaultEncoding_type [1:0] +`define Src1CtrlEnum_defaultEncoding_RS 2'b00 +`define Src1CtrlEnum_defaultEncoding_IMU 2'b01 +`define Src1CtrlEnum_defaultEncoding_PC_INCREMENT 2'b10 +`define Src1CtrlEnum_defaultEncoding_URS1 2'b11 + +`define AluCtrlEnum_defaultEncoding_type [1:0] +`define AluCtrlEnum_defaultEncoding_ADD_SUB 2'b00 +`define AluCtrlEnum_defaultEncoding_SLT_SLTU 2'b01 +`define AluCtrlEnum_defaultEncoding_BITWISE 2'b10 + +`define BranchCtrlEnum_defaultEncoding_type [1:0] +`define BranchCtrlEnum_defaultEncoding_INC 2'b00 +`define BranchCtrlEnum_defaultEncoding_B 2'b01 +`define BranchCtrlEnum_defaultEncoding_JAL 2'b10 +`define BranchCtrlEnum_defaultEncoding_JALR 2'b11 + +`define ShiftCtrlEnum_defaultEncoding_type [1:0] +`define ShiftCtrlEnum_defaultEncoding_DISABLE_1 2'b00 +`define ShiftCtrlEnum_defaultEncoding_SLL_1 2'b01 +`define ShiftCtrlEnum_defaultEncoding_SRL_1 2'b10 +`define ShiftCtrlEnum_defaultEncoding_SRA_1 2'b11 + +`define AluBitwiseCtrlEnum_defaultEncoding_type [1:0] +`define AluBitwiseCtrlEnum_defaultEncoding_XOR_1 2'b00 +`define AluBitwiseCtrlEnum_defaultEncoding_OR_1 2'b01 +`define AluBitwiseCtrlEnum_defaultEncoding_AND_1 2'b10 + +module InstructionCache ( + input io_flush, + input io_cpu_prefetch_isValid, + output reg io_cpu_prefetch_haltIt, + input [31:0] io_cpu_prefetch_pc, + input io_cpu_fetch_isValid, + input io_cpu_fetch_isStuck, + input io_cpu_fetch_isRemoved, + input [31:0] io_cpu_fetch_pc, + output [31:0] io_cpu_fetch_data, + input io_cpu_fetch_dataBypassValid, + input [31:0] io_cpu_fetch_dataBypass, + output io_cpu_fetch_mmuBus_cmd_isValid, + output [31:0] io_cpu_fetch_mmuBus_cmd_virtualAddress, + output io_cpu_fetch_mmuBus_cmd_bypassTranslation, + input [31:0] io_cpu_fetch_mmuBus_rsp_physicalAddress, + input io_cpu_fetch_mmuBus_rsp_isIoAccess, + input io_cpu_fetch_mmuBus_rsp_allowRead, + input io_cpu_fetch_mmuBus_rsp_allowWrite, + input io_cpu_fetch_mmuBus_rsp_allowExecute, + input io_cpu_fetch_mmuBus_rsp_exception, + input io_cpu_fetch_mmuBus_rsp_refilling, + output io_cpu_fetch_mmuBus_end, + input io_cpu_fetch_mmuBus_busy, + output [31:0] io_cpu_fetch_physicalAddress, + output io_cpu_fetch_cacheMiss, + output io_cpu_fetch_error, + output io_cpu_fetch_mmuRefilling, + output io_cpu_fetch_mmuException, + input io_cpu_fetch_isUser, + output io_cpu_fetch_haltIt, + input io_cpu_decode_isValid, + input io_cpu_decode_isStuck, + input [31:0] io_cpu_decode_pc, + output [31:0] io_cpu_decode_physicalAddress, + output [31:0] io_cpu_decode_data, + input io_cpu_fill_valid, + input [31:0] io_cpu_fill_payload, + output io_mem_cmd_valid, + input io_mem_cmd_ready, + output [31:0] io_mem_cmd_payload_address, + output [2:0] io_mem_cmd_payload_size, + input io_mem_rsp_valid, + input [31:0] io_mem_rsp_payload_data, + input io_mem_rsp_payload_error, + input clk, + input reset); + reg [23:0] _zz_10_; + reg [31:0] _zz_11_; + wire _zz_12_; + wire _zz_13_; + wire [0:0] _zz_14_; + wire [0:0] _zz_15_; + wire [23:0] _zz_16_; + reg _zz_1_; + reg _zz_2_; + reg lineLoader_fire; + reg lineLoader_valid; + reg [31:0] lineLoader_address; + reg lineLoader_hadError; + reg lineLoader_flushPending; + reg [5:0] lineLoader_flushCounter; + reg _zz_3_; + reg lineLoader_cmdSent; + reg lineLoader_wayToAllocate_willIncrement; + wire lineLoader_wayToAllocate_willClear; + wire lineLoader_wayToAllocate_willOverflowIfInc; + wire lineLoader_wayToAllocate_willOverflow; + reg [2:0] lineLoader_wordIndex; + wire lineLoader_write_tag_0_valid; + wire [4:0] lineLoader_write_tag_0_payload_address; + wire lineLoader_write_tag_0_payload_data_valid; + wire lineLoader_write_tag_0_payload_data_error; + wire [21:0] lineLoader_write_tag_0_payload_data_address; + wire lineLoader_write_data_0_valid; + wire [7:0] lineLoader_write_data_0_payload_address; + wire [31:0] lineLoader_write_data_0_payload_data; + wire _zz_4_; + wire [4:0] _zz_5_; + wire _zz_6_; + wire fetchStage_read_waysValues_0_tag_valid; + wire fetchStage_read_waysValues_0_tag_error; + wire [21:0] fetchStage_read_waysValues_0_tag_address; + wire [23:0] _zz_7_; + wire [7:0] _zz_8_; + wire _zz_9_; + wire [31:0] fetchStage_read_waysValues_0_data; + wire fetchStage_hit_hits_0; + wire fetchStage_hit_valid; + wire fetchStage_hit_error; + wire [31:0] fetchStage_hit_data; + wire [31:0] fetchStage_hit_word; + reg [23:0] ways_0_tags [0:31]; + reg [31:0] ways_0_datas [0:255]; + assign _zz_12_ = (! lineLoader_flushCounter[5]); + assign _zz_13_ = (lineLoader_flushPending && (! (lineLoader_valid || io_cpu_fetch_isValid))); + assign _zz_14_ = _zz_7_[0 : 0]; + assign _zz_15_ = _zz_7_[1 : 1]; + assign _zz_16_ = {lineLoader_write_tag_0_payload_data_address,{lineLoader_write_tag_0_payload_data_error,lineLoader_write_tag_0_payload_data_valid}}; + always @ (posedge clk) begin + if(_zz_2_) begin + ways_0_tags[lineLoader_write_tag_0_payload_address] <= _zz_16_; + end + end + + always @ (posedge clk) begin + if(_zz_6_) begin + _zz_10_ <= ways_0_tags[_zz_5_]; + end + end + + always @ (posedge clk) begin + if(_zz_1_) begin + ways_0_datas[lineLoader_write_data_0_payload_address] <= lineLoader_write_data_0_payload_data; + end + end + + always @ (posedge clk) begin + if(_zz_9_) begin + _zz_11_ <= ways_0_datas[_zz_8_]; + end + end + + always @ (*) begin + _zz_1_ = 1'b0; + if(lineLoader_write_data_0_valid)begin + _zz_1_ = 1'b1; + end + end + + always @ (*) begin + _zz_2_ = 1'b0; + if(lineLoader_write_tag_0_valid)begin + _zz_2_ = 1'b1; + end + end + + assign io_cpu_fetch_haltIt = io_cpu_fetch_mmuBus_busy; + always @ (*) begin + lineLoader_fire = 1'b0; + if(io_mem_rsp_valid)begin + if((lineLoader_wordIndex == (3'b111)))begin + lineLoader_fire = 1'b1; + end + end + end + + always @ (*) begin + io_cpu_prefetch_haltIt = (lineLoader_valid || lineLoader_flushPending); + if(_zz_12_)begin + io_cpu_prefetch_haltIt = 1'b1; + end + if((! _zz_3_))begin + io_cpu_prefetch_haltIt = 1'b1; + end + if(io_flush)begin + io_cpu_prefetch_haltIt = 1'b1; + end + end + + assign io_mem_cmd_valid = (lineLoader_valid && (! lineLoader_cmdSent)); + assign io_mem_cmd_payload_address = {lineLoader_address[31 : 5],(5'b00000)}; + assign io_mem_cmd_payload_size = (3'b101); + always @ (*) begin + lineLoader_wayToAllocate_willIncrement = 1'b0; + if(lineLoader_fire)begin + lineLoader_wayToAllocate_willIncrement = 1'b1; + end + end + + assign lineLoader_wayToAllocate_willClear = 1'b0; + assign lineLoader_wayToAllocate_willOverflowIfInc = 1'b1; + assign lineLoader_wayToAllocate_willOverflow = (lineLoader_wayToAllocate_willOverflowIfInc && lineLoader_wayToAllocate_willIncrement); + assign _zz_4_ = 1'b1; + assign lineLoader_write_tag_0_valid = ((_zz_4_ && lineLoader_fire) || (! lineLoader_flushCounter[5])); + assign lineLoader_write_tag_0_payload_address = (lineLoader_flushCounter[5] ? lineLoader_address[9 : 5] : lineLoader_flushCounter[4 : 0]); + assign lineLoader_write_tag_0_payload_data_valid = lineLoader_flushCounter[5]; + assign lineLoader_write_tag_0_payload_data_error = (lineLoader_hadError || io_mem_rsp_payload_error); + assign lineLoader_write_tag_0_payload_data_address = lineLoader_address[31 : 10]; + assign lineLoader_write_data_0_valid = (io_mem_rsp_valid && _zz_4_); + assign lineLoader_write_data_0_payload_address = {lineLoader_address[9 : 5],lineLoader_wordIndex}; + assign lineLoader_write_data_0_payload_data = io_mem_rsp_payload_data; + assign _zz_5_ = io_cpu_prefetch_pc[9 : 5]; + assign _zz_6_ = (! io_cpu_fetch_isStuck); + assign _zz_7_ = _zz_10_; + assign fetchStage_read_waysValues_0_tag_valid = _zz_14_[0]; + assign fetchStage_read_waysValues_0_tag_error = _zz_15_[0]; + assign fetchStage_read_waysValues_0_tag_address = _zz_7_[23 : 2]; + assign _zz_8_ = io_cpu_prefetch_pc[9 : 2]; + assign _zz_9_ = (! io_cpu_fetch_isStuck); + assign fetchStage_read_waysValues_0_data = _zz_11_; + assign fetchStage_hit_hits_0 = (fetchStage_read_waysValues_0_tag_valid && (fetchStage_read_waysValues_0_tag_address == io_cpu_fetch_mmuBus_rsp_physicalAddress[31 : 10])); + assign fetchStage_hit_valid = (fetchStage_hit_hits_0 != (1'b0)); + assign fetchStage_hit_error = fetchStage_read_waysValues_0_tag_error; + assign fetchStage_hit_data = fetchStage_read_waysValues_0_data; + assign fetchStage_hit_word = fetchStage_hit_data[31 : 0]; + assign io_cpu_fetch_data = (io_cpu_fetch_dataBypassValid ? io_cpu_fetch_dataBypass : fetchStage_hit_word); + assign io_cpu_fetch_mmuBus_cmd_isValid = io_cpu_fetch_isValid; + assign io_cpu_fetch_mmuBus_cmd_virtualAddress = io_cpu_fetch_pc; + assign io_cpu_fetch_mmuBus_cmd_bypassTranslation = 1'b0; + assign io_cpu_fetch_mmuBus_end = ((! io_cpu_fetch_isStuck) || io_cpu_fetch_isRemoved); + assign io_cpu_fetch_physicalAddress = io_cpu_fetch_mmuBus_rsp_physicalAddress; + assign io_cpu_fetch_cacheMiss = (! fetchStage_hit_valid); + assign io_cpu_fetch_error = fetchStage_hit_error; + assign io_cpu_fetch_mmuRefilling = io_cpu_fetch_mmuBus_rsp_refilling; + assign io_cpu_fetch_mmuException = ((! io_cpu_fetch_mmuBus_rsp_refilling) && (io_cpu_fetch_mmuBus_rsp_exception || (! io_cpu_fetch_mmuBus_rsp_allowExecute))); + always @ (posedge clk) begin + if(reset) begin + lineLoader_valid <= 1'b0; + lineLoader_hadError <= 1'b0; + lineLoader_flushPending <= 1'b1; + lineLoader_cmdSent <= 1'b0; + lineLoader_wordIndex <= (3'b000); + end else begin + if(lineLoader_fire)begin + lineLoader_valid <= 1'b0; + end + if(lineLoader_fire)begin + lineLoader_hadError <= 1'b0; + end + if(io_cpu_fill_valid)begin + lineLoader_valid <= 1'b1; + end + if(io_flush)begin + lineLoader_flushPending <= 1'b1; + end + if(_zz_13_)begin + lineLoader_flushPending <= 1'b0; + end + if((io_mem_cmd_valid && io_mem_cmd_ready))begin + lineLoader_cmdSent <= 1'b1; + end + if(lineLoader_fire)begin + lineLoader_cmdSent <= 1'b0; + end + if(io_mem_rsp_valid)begin + lineLoader_wordIndex <= (lineLoader_wordIndex + (3'b001)); + if(io_mem_rsp_payload_error)begin + lineLoader_hadError <= 1'b1; + end + end + end + end + + always @ (posedge clk) begin + if(io_cpu_fill_valid)begin + lineLoader_address <= io_cpu_fill_payload; + end + if(_zz_12_)begin + lineLoader_flushCounter <= (lineLoader_flushCounter + (6'b000001)); + end + _zz_3_ <= lineLoader_flushCounter[5]; + if(_zz_13_)begin + lineLoader_flushCounter <= (6'b000000); + end + end + +endmodule + +module VexRiscv ( + input [31:0] externalResetVector, + input timerInterrupt, + input softwareInterrupt, + input [31:0] externalInterruptArray, + output reg iBusWishbone_CYC, + output reg iBusWishbone_STB, + input iBusWishbone_ACK, + output iBusWishbone_WE, + output [29:0] iBusWishbone_ADR, + input [31:0] iBusWishbone_DAT_MISO, + output [31:0] iBusWishbone_DAT_MOSI, + output [3:0] iBusWishbone_SEL, + input iBusWishbone_ERR, + output [1:0] iBusWishbone_BTE, + output [2:0] iBusWishbone_CTI, + output dBusWishbone_CYC, + output dBusWishbone_STB, + input dBusWishbone_ACK, + output dBusWishbone_WE, + output [29:0] dBusWishbone_ADR, + input [31:0] dBusWishbone_DAT_MISO, + output [31:0] dBusWishbone_DAT_MOSI, + output reg [3:0] dBusWishbone_SEL, + input dBusWishbone_ERR, + output [1:0] dBusWishbone_BTE, + output [2:0] dBusWishbone_CTI, + input clk, + input reset); + wire _zz_130_; + wire _zz_131_; + wire _zz_132_; + wire _zz_133_; + wire _zz_134_; + wire [31:0] _zz_135_; + wire _zz_136_; + wire _zz_137_; + wire _zz_138_; + wire _zz_139_; + wire _zz_140_; + wire _zz_141_; + wire _zz_142_; + wire _zz_143_; + wire _zz_144_; + wire _zz_145_; + wire [31:0] _zz_146_; + reg _zz_147_; + reg [31:0] _zz_148_; + reg [31:0] _zz_149_; + reg [31:0] _zz_150_; + reg [3:0] _zz_151_; + reg [31:0] _zz_152_; + wire IBusCachedPlugin_cache_io_cpu_prefetch_haltIt; + wire IBusCachedPlugin_cache_io_cpu_fetch_error; + wire IBusCachedPlugin_cache_io_cpu_fetch_mmuRefilling; + wire IBusCachedPlugin_cache_io_cpu_fetch_mmuException; + wire [31:0] IBusCachedPlugin_cache_io_cpu_fetch_data; + wire IBusCachedPlugin_cache_io_cpu_fetch_cacheMiss; + wire [31:0] IBusCachedPlugin_cache_io_cpu_fetch_physicalAddress; + wire IBusCachedPlugin_cache_io_cpu_fetch_haltIt; + wire IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_isValid; + wire [31:0] IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_virtualAddress; + wire IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_bypassTranslation; + wire IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_end; + wire [31:0] IBusCachedPlugin_cache_io_cpu_decode_data; + wire [31:0] IBusCachedPlugin_cache_io_cpu_decode_physicalAddress; + wire IBusCachedPlugin_cache_io_mem_cmd_valid; + wire [31:0] IBusCachedPlugin_cache_io_mem_cmd_payload_address; + wire [2:0] IBusCachedPlugin_cache_io_mem_cmd_payload_size; + wire _zz_153_; + wire _zz_154_; + wire _zz_155_; + wire _zz_156_; + wire _zz_157_; + wire _zz_158_; + wire [1:0] _zz_159_; + wire _zz_160_; + wire _zz_161_; + wire _zz_162_; + wire [1:0] _zz_163_; + wire _zz_164_; + wire [2:0] _zz_165_; + wire [2:0] _zz_166_; + wire [31:0] _zz_167_; + wire [2:0] _zz_168_; + wire [0:0] _zz_169_; + wire [0:0] _zz_170_; + wire [0:0] _zz_171_; + wire [0:0] _zz_172_; + wire [0:0] _zz_173_; + wire [0:0] _zz_174_; + wire [0:0] _zz_175_; + wire [0:0] _zz_176_; + wire [0:0] _zz_177_; + wire [2:0] _zz_178_; + wire [4:0] _zz_179_; + wire [11:0] _zz_180_; + wire [11:0] _zz_181_; + wire [31:0] _zz_182_; + wire [31:0] _zz_183_; + wire [31:0] _zz_184_; + wire [31:0] _zz_185_; + wire [31:0] _zz_186_; + wire [31:0] _zz_187_; + wire [31:0] _zz_188_; + wire [31:0] _zz_189_; + wire [32:0] _zz_190_; + wire [19:0] _zz_191_; + wire [11:0] _zz_192_; + wire [11:0] _zz_193_; + wire [1:0] _zz_194_; + wire [1:0] _zz_195_; + wire [2:0] _zz_196_; + wire [0:0] _zz_197_; + wire [0:0] _zz_198_; + wire [0:0] _zz_199_; + wire [0:0] _zz_200_; + wire [0:0] _zz_201_; + wire [0:0] _zz_202_; + wire [26:0] _zz_203_; + wire [6:0] _zz_204_; + wire [1:0] _zz_205_; + wire _zz_206_; + wire _zz_207_; + wire [0:0] _zz_208_; + wire [4:0] _zz_209_; + wire [0:0] _zz_210_; + wire [0:0] _zz_211_; + wire _zz_212_; + wire [0:0] _zz_213_; + wire [20:0] _zz_214_; + wire [31:0] _zz_215_; + wire [31:0] _zz_216_; + wire _zz_217_; + wire [0:0] _zz_218_; + wire [1:0] _zz_219_; + wire [31:0] _zz_220_; + wire [31:0] _zz_221_; + wire [31:0] _zz_222_; + wire [0:0] _zz_223_; + wire [1:0] _zz_224_; + wire [1:0] _zz_225_; + wire [1:0] _zz_226_; + wire _zz_227_; + wire [0:0] _zz_228_; + wire [17:0] _zz_229_; + wire [31:0] _zz_230_; + wire _zz_231_; + wire _zz_232_; + wire [31:0] _zz_233_; + wire [31:0] _zz_234_; + wire _zz_235_; + wire _zz_236_; + wire _zz_237_; + wire _zz_238_; + wire _zz_239_; + wire [0:0] _zz_240_; + wire [0:0] _zz_241_; + wire _zz_242_; + wire [0:0] _zz_243_; + wire [15:0] _zz_244_; + wire [31:0] _zz_245_; + wire [31:0] _zz_246_; + wire [31:0] _zz_247_; + wire [31:0] _zz_248_; + wire [31:0] _zz_249_; + wire [31:0] _zz_250_; + wire [31:0] _zz_251_; + wire [31:0] _zz_252_; + wire [31:0] _zz_253_; + wire [0:0] _zz_254_; + wire [0:0] _zz_255_; + wire [1:0] _zz_256_; + wire [1:0] _zz_257_; + wire _zz_258_; + wire [0:0] _zz_259_; + wire [13:0] _zz_260_; + wire [31:0] _zz_261_; + wire [31:0] _zz_262_; + wire [31:0] _zz_263_; + wire _zz_264_; + wire [0:0] _zz_265_; + wire [1:0] _zz_266_; + wire [0:0] _zz_267_; + wire [0:0] _zz_268_; + wire [1:0] _zz_269_; + wire [1:0] _zz_270_; + wire _zz_271_; + wire [0:0] _zz_272_; + wire [10:0] _zz_273_; + wire [31:0] _zz_274_; + wire [31:0] _zz_275_; + wire [31:0] _zz_276_; + wire _zz_277_; + wire _zz_278_; + wire [31:0] _zz_279_; + wire [31:0] _zz_280_; + wire [31:0] _zz_281_; + wire [31:0] _zz_282_; + wire _zz_283_; + wire _zz_284_; + wire [0:0] _zz_285_; + wire [0:0] _zz_286_; + wire _zz_287_; + wire [0:0] _zz_288_; + wire [8:0] _zz_289_; + wire [31:0] _zz_290_; + wire _zz_291_; + wire _zz_292_; + wire [0:0] _zz_293_; + wire [0:0] _zz_294_; + wire [0:0] _zz_295_; + wire [0:0] _zz_296_; + wire _zz_297_; + wire [0:0] _zz_298_; + wire [5:0] _zz_299_; + wire [31:0] _zz_300_; + wire [31:0] _zz_301_; + wire [31:0] _zz_302_; + wire [31:0] _zz_303_; + wire [31:0] _zz_304_; + wire [0:0] _zz_305_; + wire [0:0] _zz_306_; + wire [1:0] _zz_307_; + wire [1:0] _zz_308_; + wire _zz_309_; + wire [0:0] _zz_310_; + wire [2:0] _zz_311_; + wire [31:0] _zz_312_; + wire [31:0] _zz_313_; + wire _zz_314_; + wire _zz_315_; + wire _zz_316_; + wire [0:0] _zz_317_; + wire [0:0] _zz_318_; + wire [1:0] _zz_319_; + wire [1:0] _zz_320_; + wire [31:0] _zz_321_; + wire [31:0] _zz_322_; + wire [31:0] _zz_323_; + wire _zz_324_; + wire [0:0] _zz_325_; + wire [12:0] _zz_326_; + wire [31:0] _zz_327_; + wire [31:0] _zz_328_; + wire [31:0] _zz_329_; + wire _zz_330_; + wire [0:0] _zz_331_; + wire [6:0] _zz_332_; + wire [31:0] _zz_333_; + wire [31:0] _zz_334_; + wire [31:0] _zz_335_; + wire _zz_336_; + wire [0:0] _zz_337_; + wire [0:0] _zz_338_; + wire decode_CSR_WRITE_OPCODE; + wire decode_SRC_LESS_UNSIGNED; + wire `EnvCtrlEnum_defaultEncoding_type decode_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_1_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_2_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_3_; + wire [31:0] execute_FORMAL_PC_NEXT; + wire [31:0] decode_FORMAL_PC_NEXT; + wire `Src2CtrlEnum_defaultEncoding_type decode_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_4_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_5_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_6_; + wire decode_IS_CSR; + wire decode_MEMORY_ENABLE; + wire `Src1CtrlEnum_defaultEncoding_type decode_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_7_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_8_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_9_; + wire decode_CSR_READ_OPCODE; + wire execute_REGFILE_WRITE_VALID; + wire `AluCtrlEnum_defaultEncoding_type decode_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_10_; + wire `AluCtrlEnum_defaultEncoding_type _zz_11_; + wire `AluCtrlEnum_defaultEncoding_type _zz_12_; + wire decode_SRC2_FORCE_ZERO; + wire decode_MEMORY_STORE; + wire `BranchCtrlEnum_defaultEncoding_type decode_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_13_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_14_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_15_; + wire `ShiftCtrlEnum_defaultEncoding_type decode_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_16_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_17_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_18_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type decode_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_19_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_20_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_21_; + wire execute_CSR_READ_OPCODE; + wire execute_CSR_WRITE_OPCODE; + wire execute_IS_CSR; + wire _zz_22_; + wire _zz_23_; + wire `EnvCtrlEnum_defaultEncoding_type execute_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_24_; + wire [31:0] execute_BRANCH_CALC; + wire execute_BRANCH_DO; + wire [31:0] _zz_25_; + wire [31:0] execute_PC; + wire [31:0] execute_RS1; + wire `BranchCtrlEnum_defaultEncoding_type execute_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_26_; + wire _zz_27_; + wire `ShiftCtrlEnum_defaultEncoding_type execute_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_28_; + wire _zz_29_; + wire [31:0] _zz_30_; + wire [31:0] _zz_31_; + wire execute_SRC_LESS_UNSIGNED; + wire execute_SRC2_FORCE_ZERO; + wire execute_SRC_USE_SUB_LESS; + wire `Src2CtrlEnum_defaultEncoding_type execute_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_32_; + wire [31:0] _zz_33_; + wire `Src1CtrlEnum_defaultEncoding_type execute_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_34_; + wire [31:0] _zz_35_; + wire decode_SRC_USE_SUB_LESS; + wire decode_SRC_ADD_ZERO; + wire _zz_36_; + wire [31:0] execute_SRC_ADD_SUB; + wire execute_SRC_LESS; + wire `AluCtrlEnum_defaultEncoding_type execute_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_37_; + wire [31:0] _zz_38_; + wire [31:0] execute_SRC2; + wire [31:0] execute_SRC1; + wire `AluBitwiseCtrlEnum_defaultEncoding_type execute_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_39_; + reg _zz_40_; + wire [31:0] _zz_41_; + wire [31:0] _zz_42_; + reg decode_REGFILE_WRITE_VALID; + wire decode_LEGAL_INSTRUCTION; + wire decode_INSTRUCTION_READY; + wire _zz_43_; + wire _zz_44_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_45_; + wire _zz_46_; + wire _zz_47_; + wire _zz_48_; + wire _zz_49_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_50_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_51_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_52_; + wire `AluCtrlEnum_defaultEncoding_type _zz_53_; + wire _zz_54_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_55_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_56_; + wire _zz_57_; + wire _zz_58_; + reg [31:0] _zz_59_; + wire [1:0] execute_MEMORY_ADDRESS_LOW; + wire [31:0] execute_MEMORY_READ_DATA; + wire [31:0] execute_REGFILE_WRITE_DATA; + wire [31:0] _zz_60_; + wire [31:0] execute_SRC_ADD; + wire [1:0] _zz_61_; + wire [31:0] execute_RS2; + wire [31:0] execute_INSTRUCTION; + wire execute_MEMORY_STORE; + wire execute_MEMORY_ENABLE; + wire execute_ALIGNEMENT_FAULT; + wire _zz_62_; + wire decode_FLUSH_ALL; + reg IBusCachedPlugin_rsp_issueDetected; + reg _zz_63_; + reg _zz_64_; + reg _zz_65_; + reg [31:0] _zz_66_; + wire [31:0] _zz_67_; + wire [31:0] _zz_68_; + wire [31:0] _zz_69_; + wire [31:0] decode_PC /* verilator public */ ; + wire [31:0] decode_INSTRUCTION /* verilator public */ ; + wire decode_arbitration_haltItself /* verilator public */ ; + reg decode_arbitration_haltByOther; + reg decode_arbitration_removeIt; + reg decode_arbitration_flushAll /* verilator public */ ; + wire decode_arbitration_isValid /* verilator public */ ; + wire decode_arbitration_isStuck; + wire decode_arbitration_isStuckByOthers; + wire decode_arbitration_isFlushed; + wire decode_arbitration_isMoving; + wire decode_arbitration_isFiring; + reg execute_arbitration_haltItself; + wire execute_arbitration_haltByOther; + reg execute_arbitration_removeIt; + wire execute_arbitration_flushAll; + reg execute_arbitration_isValid; + wire execute_arbitration_isStuck; + wire execute_arbitration_isStuckByOthers; + wire execute_arbitration_isFlushed; + wire execute_arbitration_isMoving; + wire execute_arbitration_isFiring; + reg IBusCachedPlugin_fetcherHalt; + wire IBusCachedPlugin_fetcherflushIt; + reg IBusCachedPlugin_incomingInstruction; + wire IBusCachedPlugin_pcValids_0; + wire IBusCachedPlugin_pcValids_1; + wire IBusCachedPlugin_redoBranch_valid; + wire [31:0] IBusCachedPlugin_redoBranch_payload; + reg IBusCachedPlugin_decodeExceptionPort_valid; + reg [3:0] IBusCachedPlugin_decodeExceptionPort_payload_code; + wire [31:0] IBusCachedPlugin_decodeExceptionPort_payload_badAddr; + reg DBusSimplePlugin_memoryExceptionPort_valid; + reg [3:0] DBusSimplePlugin_memoryExceptionPort_payload_code; + wire [31:0] DBusSimplePlugin_memoryExceptionPort_payload_badAddr; + wire decodeExceptionPort_valid; + wire [3:0] decodeExceptionPort_payload_code; + wire [31:0] decodeExceptionPort_payload_badAddr; + wire BranchPlugin_jumpInterface_valid; + wire [31:0] BranchPlugin_jumpInterface_payload; + reg BranchPlugin_branchExceptionPort_valid; + wire [3:0] BranchPlugin_branchExceptionPort_payload_code; + wire [31:0] BranchPlugin_branchExceptionPort_payload_badAddr; + reg CsrPlugin_jumpInterface_valid; + reg [31:0] CsrPlugin_jumpInterface_payload; + wire CsrPlugin_exceptionPendings_0; + wire CsrPlugin_exceptionPendings_1; + wire externalInterrupt; + wire contextSwitching; + reg [1:0] CsrPlugin_privilege; + wire CsrPlugin_forceMachineWire; + reg CsrPlugin_selfException_valid; + reg [3:0] CsrPlugin_selfException_payload_code; + wire [31:0] CsrPlugin_selfException_payload_badAddr; + wire CsrPlugin_allowInterrupts; + wire CsrPlugin_allowException; + wire IBusCachedPlugin_jump_pcLoad_valid; + wire [31:0] IBusCachedPlugin_jump_pcLoad_payload; + wire [2:0] _zz_70_; + wire [2:0] _zz_71_; + wire _zz_72_; + wire _zz_73_; + wire IBusCachedPlugin_fetchPc_preOutput_valid; + wire IBusCachedPlugin_fetchPc_preOutput_ready; + wire [31:0] IBusCachedPlugin_fetchPc_preOutput_payload; + wire _zz_74_; + wire IBusCachedPlugin_fetchPc_output_valid; + wire IBusCachedPlugin_fetchPc_output_ready; + wire [31:0] IBusCachedPlugin_fetchPc_output_payload; + reg [31:0] IBusCachedPlugin_fetchPc_pcReg /* verilator public */ ; + reg IBusCachedPlugin_fetchPc_inc; + reg IBusCachedPlugin_fetchPc_propagatePc; + reg [31:0] IBusCachedPlugin_fetchPc_pc; + reg IBusCachedPlugin_fetchPc_samplePcNext; + reg _zz_75_; + wire IBusCachedPlugin_iBusRsp_stages_0_input_valid; + wire IBusCachedPlugin_iBusRsp_stages_0_input_ready; + wire [31:0] IBusCachedPlugin_iBusRsp_stages_0_input_payload; + wire IBusCachedPlugin_iBusRsp_stages_0_output_valid; + wire IBusCachedPlugin_iBusRsp_stages_0_output_ready; + wire [31:0] IBusCachedPlugin_iBusRsp_stages_0_output_payload; + reg IBusCachedPlugin_iBusRsp_stages_0_halt; + wire IBusCachedPlugin_iBusRsp_stages_0_inputSample; + wire IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid; + wire IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready; + wire [31:0] IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload; + wire IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_valid; + wire IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_ready; + wire [31:0] IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_payload; + reg IBusCachedPlugin_iBusRsp_cacheRspArbitration_halt; + wire IBusCachedPlugin_iBusRsp_cacheRspArbitration_inputSample; + wire _zz_76_; + wire _zz_77_; + wire _zz_78_; + wire _zz_79_; + reg _zz_80_; + reg IBusCachedPlugin_iBusRsp_readyForError; + wire IBusCachedPlugin_iBusRsp_decodeInput_valid; + wire IBusCachedPlugin_iBusRsp_decodeInput_ready; + wire [31:0] IBusCachedPlugin_iBusRsp_decodeInput_payload_pc; + wire IBusCachedPlugin_iBusRsp_decodeInput_payload_rsp_error; + wire [31:0] IBusCachedPlugin_iBusRsp_decodeInput_payload_rsp_inst; + wire IBusCachedPlugin_iBusRsp_decodeInput_payload_isRvc; + reg IBusCachedPlugin_injector_nextPcCalc_valids_0; + reg IBusCachedPlugin_injector_nextPcCalc_valids_1; + reg IBusCachedPlugin_injector_decodeRemoved; + wire iBus_cmd_valid; + wire iBus_cmd_ready; + reg [31:0] iBus_cmd_payload_address; + wire [2:0] iBus_cmd_payload_size; + wire iBus_rsp_valid; + wire [31:0] iBus_rsp_payload_data; + wire iBus_rsp_payload_error; + wire IBusCachedPlugin_s0_tightlyCoupledHit; + reg IBusCachedPlugin_s1_tightlyCoupledHit; + wire IBusCachedPlugin_rsp_iBusRspOutputHalt; + reg IBusCachedPlugin_rsp_redoFetch; + wire dBus_cmd_valid; + wire dBus_cmd_ready; + wire dBus_cmd_payload_wr; + wire [31:0] dBus_cmd_payload_address; + wire [31:0] dBus_cmd_payload_data; + wire [1:0] dBus_cmd_payload_size; + wire dBus_rsp_ready; + wire dBus_rsp_error; + wire [31:0] dBus_rsp_data; + reg execute_DBusSimplePlugin_cmdSent; + reg execute_DBusSimplePlugin_skipCmd; + reg [31:0] _zz_81_; + reg [3:0] _zz_82_; + wire [3:0] execute_DBusSimplePlugin_formalMask; + reg [31:0] execute_DBusSimplePlugin_rspShifted; + wire _zz_83_; + reg [31:0] _zz_84_; + wire _zz_85_; + reg [31:0] _zz_86_; + reg [31:0] execute_DBusSimplePlugin_rspFormated; + wire [26:0] _zz_87_; + wire _zz_88_; + wire _zz_89_; + wire _zz_90_; + wire _zz_91_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_92_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_93_; + wire `AluCtrlEnum_defaultEncoding_type _zz_94_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_95_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_96_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_97_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_98_; + wire [4:0] execute_RegFilePlugin_regFileReadAddress1; + wire [4:0] execute_RegFilePlugin_regFileReadAddress2; + wire _zz_99_; + wire [31:0] execute_RegFilePlugin_rs1Data; + wire [31:0] execute_RegFilePlugin_rs2Data; + wire execute_RegFilePlugin_regFileWrite_valid /* verilator public */ ; + wire [4:0] execute_RegFilePlugin_regFileWrite_payload_address /* verilator public */ ; + wire [31:0] execute_RegFilePlugin_regFileWrite_payload_data /* verilator public */ ; + reg [31:0] execute_IntAluPlugin_bitwise; + reg [31:0] _zz_100_; + reg [31:0] _zz_101_; + wire _zz_102_; + reg [19:0] _zz_103_; + wire _zz_104_; + reg [19:0] _zz_105_; + reg [31:0] _zz_106_; + reg [31:0] execute_SrcPlugin_addSub; + wire execute_SrcPlugin_less; + reg execute_LightShifterPlugin_isActive; + wire execute_LightShifterPlugin_isShift; + reg [4:0] execute_LightShifterPlugin_amplitudeReg; + wire [4:0] execute_LightShifterPlugin_amplitude; + reg [31:0] execute_LightShifterPlugin_shiftReg; + wire [31:0] execute_LightShifterPlugin_shiftInput; + wire execute_LightShifterPlugin_done; + reg [31:0] _zz_107_; + wire execute_BranchPlugin_eq; + wire [2:0] _zz_108_; + reg _zz_109_; + reg _zz_110_; + wire [31:0] execute_BranchPlugin_branch_src1; + wire _zz_111_; + reg [10:0] _zz_112_; + wire _zz_113_; + reg [19:0] _zz_114_; + wire _zz_115_; + reg [18:0] _zz_116_; + reg [31:0] _zz_117_; + wire [31:0] execute_BranchPlugin_branch_src2; + wire [31:0] execute_BranchPlugin_branchAdder; + wire [1:0] CsrPlugin_misa_base; + wire [25:0] CsrPlugin_misa_extensions; + reg [1:0] CsrPlugin_mtvec_mode; + reg [29:0] CsrPlugin_mtvec_base; + reg [31:0] CsrPlugin_mepc; + reg CsrPlugin_mstatus_MIE; + reg CsrPlugin_mstatus_MPIE; + reg [1:0] CsrPlugin_mstatus_MPP; + reg CsrPlugin_mip_MEIP; + reg CsrPlugin_mip_MTIP; + reg CsrPlugin_mip_MSIP; + reg CsrPlugin_mie_MEIE; + reg CsrPlugin_mie_MTIE; + reg CsrPlugin_mie_MSIE; + reg [31:0] CsrPlugin_mscratch; + reg CsrPlugin_mcause_interrupt; + reg [3:0] CsrPlugin_mcause_exceptionCode; + reg [31:0] CsrPlugin_mtval; + reg [63:0] CsrPlugin_mcycle = 64'b0000000000000000000000000000000000000000000000000000000000000000; + reg [63:0] CsrPlugin_minstret = 64'b0000000000000000000000000000000000000000000000000000000000000000; + reg CsrPlugin_exceptionPortCtrl_exceptionValids_decode; + reg CsrPlugin_exceptionPortCtrl_exceptionValids_execute; + reg CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode; + reg CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute; + reg [3:0] CsrPlugin_exceptionPortCtrl_exceptionContext_code; + reg [31:0] CsrPlugin_exceptionPortCtrl_exceptionContext_badAddr; + wire [1:0] CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilegeUncapped; + wire [1:0] CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilege; + wire [1:0] _zz_118_; + wire _zz_119_; + wire [2:0] _zz_120_; + wire [2:0] _zz_121_; + wire _zz_122_; + wire _zz_123_; + wire [1:0] _zz_124_; + reg CsrPlugin_interrupt; + reg [3:0] CsrPlugin_interruptCode /* verilator public */ ; + reg [1:0] CsrPlugin_interruptTargetPrivilege; + wire CsrPlugin_exception; + wire CsrPlugin_lastStageWasWfi; + reg CsrPlugin_pipelineLiberator_done; + wire CsrPlugin_interruptJump /* verilator public */ ; + reg CsrPlugin_hadException; + reg [1:0] CsrPlugin_targetPrivilege; + reg [3:0] CsrPlugin_trapCause; + reg [1:0] CsrPlugin_xtvec_mode; + reg [29:0] CsrPlugin_xtvec_base; + wire execute_CsrPlugin_inWfi /* verilator public */ ; + wire execute_CsrPlugin_blockedBySideEffects; + reg execute_CsrPlugin_illegalAccess; + reg execute_CsrPlugin_illegalInstruction; + reg [31:0] execute_CsrPlugin_readData; + wire execute_CsrPlugin_writeInstruction; + wire execute_CsrPlugin_readInstruction; + wire execute_CsrPlugin_writeEnable; + wire execute_CsrPlugin_readEnable; + wire [31:0] execute_CsrPlugin_readToWriteData; + reg [31:0] execute_CsrPlugin_writeData; + wire [11:0] execute_CsrPlugin_csrAddress; + reg [31:0] _zz_125_; + reg [31:0] externalInterruptArray_regNext; + wire [31:0] _zz_126_; + reg `AluBitwiseCtrlEnum_defaultEncoding_type decode_to_execute_ALU_BITWISE_CTRL; + reg `ShiftCtrlEnum_defaultEncoding_type decode_to_execute_SHIFT_CTRL; + reg `BranchCtrlEnum_defaultEncoding_type decode_to_execute_BRANCH_CTRL; + reg decode_to_execute_MEMORY_STORE; + reg decode_to_execute_SRC2_FORCE_ZERO; + reg `AluCtrlEnum_defaultEncoding_type decode_to_execute_ALU_CTRL; + reg decode_to_execute_SRC_USE_SUB_LESS; + reg decode_to_execute_REGFILE_WRITE_VALID; + reg decode_to_execute_CSR_READ_OPCODE; + reg `Src1CtrlEnum_defaultEncoding_type decode_to_execute_SRC1_CTRL; + reg decode_to_execute_MEMORY_ENABLE; + reg decode_to_execute_IS_CSR; + reg `Src2CtrlEnum_defaultEncoding_type decode_to_execute_SRC2_CTRL; + reg [31:0] decode_to_execute_PC; + reg [31:0] decode_to_execute_INSTRUCTION; + reg [31:0] decode_to_execute_FORMAL_PC_NEXT; + reg `EnvCtrlEnum_defaultEncoding_type decode_to_execute_ENV_CTRL; + reg decode_to_execute_SRC_LESS_UNSIGNED; + reg decode_to_execute_CSR_WRITE_OPCODE; + reg [2:0] _zz_127_; + reg _zz_128_; + reg [31:0] iBusWishbone_DAT_MISO_regNext; + wire dBus_cmd_halfPipe_valid; + wire dBus_cmd_halfPipe_ready; + wire dBus_cmd_halfPipe_payload_wr; + wire [31:0] dBus_cmd_halfPipe_payload_address; + wire [31:0] dBus_cmd_halfPipe_payload_data; + wire [1:0] dBus_cmd_halfPipe_payload_size; + reg dBus_cmd_halfPipe_regs_valid; + reg dBus_cmd_halfPipe_regs_ready; + reg dBus_cmd_halfPipe_regs_payload_wr; + reg [31:0] dBus_cmd_halfPipe_regs_payload_address; + reg [31:0] dBus_cmd_halfPipe_regs_payload_data; + reg [1:0] dBus_cmd_halfPipe_regs_payload_size; + reg [3:0] _zz_129_; + `ifndef SYNTHESIS + reg [47:0] decode_ENV_CTRL_string; + reg [47:0] _zz_1__string; + reg [47:0] _zz_2__string; + reg [47:0] _zz_3__string; + reg [23:0] decode_SRC2_CTRL_string; + reg [23:0] _zz_4__string; + reg [23:0] _zz_5__string; + reg [23:0] _zz_6__string; + reg [95:0] decode_SRC1_CTRL_string; + reg [95:0] _zz_7__string; + reg [95:0] _zz_8__string; + reg [95:0] _zz_9__string; + reg [63:0] decode_ALU_CTRL_string; + reg [63:0] _zz_10__string; + reg [63:0] _zz_11__string; + reg [63:0] _zz_12__string; + reg [31:0] decode_BRANCH_CTRL_string; + reg [31:0] _zz_13__string; + reg [31:0] _zz_14__string; + reg [31:0] _zz_15__string; + reg [71:0] decode_SHIFT_CTRL_string; + reg [71:0] _zz_16__string; + reg [71:0] _zz_17__string; + reg [71:0] _zz_18__string; + reg [39:0] decode_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_19__string; + reg [39:0] _zz_20__string; + reg [39:0] _zz_21__string; + reg [47:0] execute_ENV_CTRL_string; + reg [47:0] _zz_24__string; + reg [31:0] execute_BRANCH_CTRL_string; + reg [31:0] _zz_26__string; + reg [71:0] execute_SHIFT_CTRL_string; + reg [71:0] _zz_28__string; + reg [23:0] execute_SRC2_CTRL_string; + reg [23:0] _zz_32__string; + reg [95:0] execute_SRC1_CTRL_string; + reg [95:0] _zz_34__string; + reg [63:0] execute_ALU_CTRL_string; + reg [63:0] _zz_37__string; + reg [39:0] execute_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_39__string; + reg [39:0] _zz_45__string; + reg [95:0] _zz_50__string; + reg [31:0] _zz_51__string; + reg [47:0] _zz_52__string; + reg [63:0] _zz_53__string; + reg [23:0] _zz_55__string; + reg [71:0] _zz_56__string; + reg [71:0] _zz_92__string; + reg [23:0] _zz_93__string; + reg [63:0] _zz_94__string; + reg [47:0] _zz_95__string; + reg [31:0] _zz_96__string; + reg [95:0] _zz_97__string; + reg [39:0] _zz_98__string; + reg [39:0] decode_to_execute_ALU_BITWISE_CTRL_string; + reg [71:0] decode_to_execute_SHIFT_CTRL_string; + reg [31:0] decode_to_execute_BRANCH_CTRL_string; + reg [63:0] decode_to_execute_ALU_CTRL_string; + reg [95:0] decode_to_execute_SRC1_CTRL_string; + reg [23:0] decode_to_execute_SRC2_CTRL_string; + reg [47:0] decode_to_execute_ENV_CTRL_string; + `endif + + reg [31:0] RegFilePlugin_regFile [0:31] /* verilator public */ ; + assign _zz_153_ = ((execute_arbitration_isValid && execute_LightShifterPlugin_isShift) && (execute_SRC2[4 : 0] != (5'b00000))); + assign _zz_154_ = (! execute_arbitration_isStuckByOthers); + assign _zz_155_ = ({decodeExceptionPort_valid,IBusCachedPlugin_decodeExceptionPort_valid} != (2'b00)); + assign _zz_156_ = ({CsrPlugin_selfException_valid,{BranchPlugin_branchExceptionPort_valid,DBusSimplePlugin_memoryExceptionPort_valid}} != (3'b000)); + assign _zz_157_ = (CsrPlugin_hadException || CsrPlugin_interruptJump); + assign _zz_158_ = (execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)); + assign _zz_159_ = execute_INSTRUCTION[29 : 28]; + assign _zz_160_ = (IBusCachedPlugin_fetchPc_preOutput_valid && IBusCachedPlugin_fetchPc_preOutput_ready); + assign _zz_161_ = (iBus_cmd_valid || (_zz_127_ != (3'b000))); + assign _zz_162_ = (! dBus_cmd_halfPipe_regs_valid); + assign _zz_163_ = execute_INSTRUCTION[13 : 12]; + assign _zz_164_ = execute_INSTRUCTION[13]; + assign _zz_165_ = (_zz_70_ - (3'b001)); + assign _zz_166_ = {IBusCachedPlugin_fetchPc_inc,(2'b00)}; + assign _zz_167_ = {29'd0, _zz_166_}; + assign _zz_168_ = (execute_MEMORY_STORE ? (3'b110) : (3'b100)); + assign _zz_169_ = _zz_87_[0 : 0]; + assign _zz_170_ = _zz_87_[7 : 7]; + assign _zz_171_ = _zz_87_[18 : 18]; + assign _zz_172_ = _zz_87_[19 : 19]; + assign _zz_173_ = _zz_87_[20 : 20]; + assign _zz_174_ = _zz_87_[21 : 21]; + assign _zz_175_ = _zz_87_[24 : 24]; + assign _zz_176_ = _zz_87_[25 : 25]; + assign _zz_177_ = execute_SRC_LESS; + assign _zz_178_ = (3'b100); + assign _zz_179_ = execute_INSTRUCTION[19 : 15]; + assign _zz_180_ = execute_INSTRUCTION[31 : 20]; + assign _zz_181_ = {execute_INSTRUCTION[31 : 25],execute_INSTRUCTION[11 : 7]}; + assign _zz_182_ = ($signed(_zz_183_) + $signed(_zz_186_)); + assign _zz_183_ = ($signed(_zz_184_) + $signed(_zz_185_)); + assign _zz_184_ = execute_SRC1; + assign _zz_185_ = (execute_SRC_USE_SUB_LESS ? (~ execute_SRC2) : execute_SRC2); + assign _zz_186_ = (execute_SRC_USE_SUB_LESS ? _zz_187_ : _zz_188_); + assign _zz_187_ = (32'b00000000000000000000000000000001); + assign _zz_188_ = (32'b00000000000000000000000000000000); + assign _zz_189_ = (_zz_190_ >>> 1); + assign _zz_190_ = {((execute_SHIFT_CTRL == `ShiftCtrlEnum_defaultEncoding_SRA_1) && execute_LightShifterPlugin_shiftInput[31]),execute_LightShifterPlugin_shiftInput}; + assign _zz_191_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}; + assign _zz_192_ = execute_INSTRUCTION[31 : 20]; + assign _zz_193_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}; + assign _zz_194_ = (_zz_118_ & (~ _zz_195_)); + assign _zz_195_ = (_zz_118_ - (2'b01)); + assign _zz_196_ = (_zz_120_ - (3'b001)); + assign _zz_197_ = execute_CsrPlugin_writeData[7 : 7]; + assign _zz_198_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_199_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_200_ = execute_CsrPlugin_writeData[11 : 11]; + assign _zz_201_ = execute_CsrPlugin_writeData[7 : 7]; + assign _zz_202_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_203_ = (iBus_cmd_payload_address >>> 5); + assign _zz_204_ = ({3'd0,_zz_129_} <<< dBus_cmd_halfPipe_payload_address[1 : 0]); + assign _zz_205_ = {_zz_73_,_zz_72_}; + assign _zz_206_ = ((decode_INSTRUCTION & (32'b00000000000000000000000001100100)) == (32'b00000000000000000000000000100100)); + assign _zz_207_ = ((decode_INSTRUCTION & (32'b00000000000000000011000001010100)) == (32'b00000000000000000001000000010000)); + assign _zz_208_ = _zz_89_; + assign _zz_209_ = {(_zz_215_ == _zz_216_),{_zz_217_,{_zz_218_,_zz_219_}}}; + assign _zz_210_ = ((decode_INSTRUCTION & _zz_220_) == (32'b00000000000000000001000000000000)); + assign _zz_211_ = (1'b0); + assign _zz_212_ = ((_zz_221_ == _zz_222_) != (1'b0)); + assign _zz_213_ = ({_zz_223_,_zz_224_} != (3'b000)); + assign _zz_214_ = {(_zz_225_ != _zz_226_),{_zz_227_,{_zz_228_,_zz_229_}}}; + assign _zz_215_ = (decode_INSTRUCTION & (32'b00000000000000000001000000010000)); + assign _zz_216_ = (32'b00000000000000000001000000010000); + assign _zz_217_ = ((decode_INSTRUCTION & _zz_230_) == (32'b00000000000000000010000000010000)); + assign _zz_218_ = _zz_91_; + assign _zz_219_ = {_zz_231_,_zz_232_}; + assign _zz_220_ = (32'b00000000000000000001000000000000); + assign _zz_221_ = (decode_INSTRUCTION & (32'b00000000000000000011000000000000)); + assign _zz_222_ = (32'b00000000000000000010000000000000); + assign _zz_223_ = (_zz_233_ == _zz_234_); + assign _zz_224_ = {_zz_235_,_zz_236_}; + assign _zz_225_ = {_zz_237_,_zz_238_}; + assign _zz_226_ = (2'b00); + assign _zz_227_ = (_zz_239_ != (1'b0)); + assign _zz_228_ = (_zz_240_ != _zz_241_); + assign _zz_229_ = {_zz_242_,{_zz_243_,_zz_244_}}; + assign _zz_230_ = (32'b00000000000000000010000000010000); + assign _zz_231_ = ((decode_INSTRUCTION & _zz_245_) == (32'b00000000000000000000000000000100)); + assign _zz_232_ = ((decode_INSTRUCTION & _zz_246_) == (32'b00000000000000000000000000000000)); + assign _zz_233_ = (decode_INSTRUCTION & (32'b00000000000000000000000001000100)); + assign _zz_234_ = (32'b00000000000000000000000001000000); + assign _zz_235_ = ((decode_INSTRUCTION & _zz_247_) == (32'b00000000000000000010000000010000)); + assign _zz_236_ = ((decode_INSTRUCTION & _zz_248_) == (32'b01000000000000000000000000110000)); + assign _zz_237_ = ((decode_INSTRUCTION & _zz_249_) == (32'b00000000000000000010000000000000)); + assign _zz_238_ = ((decode_INSTRUCTION & _zz_250_) == (32'b00000000000000000001000000000000)); + assign _zz_239_ = ((decode_INSTRUCTION & _zz_251_) == (32'b00000000000000000000000000100000)); + assign _zz_240_ = (_zz_252_ == _zz_253_); + assign _zz_241_ = (1'b0); + assign _zz_242_ = ({_zz_254_,_zz_255_} != (2'b00)); + assign _zz_243_ = (_zz_256_ != _zz_257_); + assign _zz_244_ = {_zz_258_,{_zz_259_,_zz_260_}}; + assign _zz_245_ = (32'b00000000000000000000000000001100); + assign _zz_246_ = (32'b00000000000000000000000000101000); + assign _zz_247_ = (32'b00000000000000000010000000010100); + assign _zz_248_ = (32'b01000000000000000100000000110100); + assign _zz_249_ = (32'b00000000000000000010000000010000); + assign _zz_250_ = (32'b00000000000000000101000000000000); + assign _zz_251_ = (32'b00000000000000000000000000100000); + assign _zz_252_ = (decode_INSTRUCTION & (32'b00000000000000000000000001011000)); + assign _zz_253_ = (32'b00000000000000000000000000000000); + assign _zz_254_ = ((decode_INSTRUCTION & _zz_261_) == (32'b00000000000000000000000000000100)); + assign _zz_255_ = _zz_90_; + assign _zz_256_ = {(_zz_262_ == _zz_263_),_zz_90_}; + assign _zz_257_ = (2'b00); + assign _zz_258_ = ({_zz_264_,{_zz_265_,_zz_266_}} != (4'b0000)); + assign _zz_259_ = ({_zz_267_,_zz_268_} != (2'b00)); + assign _zz_260_ = {(_zz_269_ != _zz_270_),{_zz_271_,{_zz_272_,_zz_273_}}}; + assign _zz_261_ = (32'b00000000000000000000000000010100); + assign _zz_262_ = (decode_INSTRUCTION & (32'b00000000000000000000000001000100)); + assign _zz_263_ = (32'b00000000000000000000000000000100); + assign _zz_264_ = ((decode_INSTRUCTION & _zz_274_) == (32'b00000000000000000000000000000000)); + assign _zz_265_ = (_zz_275_ == _zz_276_); + assign _zz_266_ = {_zz_277_,_zz_278_}; + assign _zz_267_ = (_zz_279_ == _zz_280_); + assign _zz_268_ = (_zz_281_ == _zz_282_); + assign _zz_269_ = {_zz_89_,_zz_283_}; + assign _zz_270_ = (2'b00); + assign _zz_271_ = (_zz_284_ != (1'b0)); + assign _zz_272_ = (_zz_285_ != _zz_286_); + assign _zz_273_ = {_zz_287_,{_zz_288_,_zz_289_}}; + assign _zz_274_ = (32'b00000000000000000000000001000100); + assign _zz_275_ = (decode_INSTRUCTION & (32'b00000000000000000000000000011000)); + assign _zz_276_ = (32'b00000000000000000000000000000000); + assign _zz_277_ = ((decode_INSTRUCTION & (32'b00000000000000000110000000000100)) == (32'b00000000000000000010000000000000)); + assign _zz_278_ = ((decode_INSTRUCTION & (32'b00000000000000000101000000000100)) == (32'b00000000000000000001000000000000)); + assign _zz_279_ = (decode_INSTRUCTION & (32'b00000000000000000000000000110100)); + assign _zz_280_ = (32'b00000000000000000000000000100000); + assign _zz_281_ = (decode_INSTRUCTION & (32'b00000000000000000000000001100100)); + assign _zz_282_ = (32'b00000000000000000000000000100000); + assign _zz_283_ = ((decode_INSTRUCTION & (32'b00000000000000000000000000011100)) == (32'b00000000000000000000000000000100)); + assign _zz_284_ = ((decode_INSTRUCTION & (32'b00000000000000000000000001011000)) == (32'b00000000000000000000000001000000)); + assign _zz_285_ = ((decode_INSTRUCTION & _zz_290_) == (32'b00000000000000000000000001010000)); + assign _zz_286_ = (1'b0); + assign _zz_287_ = ({_zz_291_,_zz_292_} != (2'b00)); + assign _zz_288_ = ({_zz_293_,_zz_294_} != (2'b00)); + assign _zz_289_ = {(_zz_295_ != _zz_296_),{_zz_297_,{_zz_298_,_zz_299_}}}; + assign _zz_290_ = (32'b00010000000000000011000001010000); + assign _zz_291_ = ((decode_INSTRUCTION & (32'b00010000000100000011000001010000)) == (32'b00000000000100000000000001010000)); + assign _zz_292_ = ((decode_INSTRUCTION & (32'b00010000010000000011000001010000)) == (32'b00010000000000000000000001010000)); + assign _zz_293_ = ((decode_INSTRUCTION & _zz_300_) == (32'b00000000000000000110000000010000)); + assign _zz_294_ = ((decode_INSTRUCTION & _zz_301_) == (32'b00000000000000000100000000010000)); + assign _zz_295_ = ((decode_INSTRUCTION & _zz_302_) == (32'b00000000000000000010000000010000)); + assign _zz_296_ = (1'b0); + assign _zz_297_ = ((_zz_303_ == _zz_304_) != (1'b0)); + assign _zz_298_ = ({_zz_305_,_zz_306_} != (2'b00)); + assign _zz_299_ = {(_zz_307_ != _zz_308_),{_zz_309_,{_zz_310_,_zz_311_}}}; + assign _zz_300_ = (32'b00000000000000000110000000010100); + assign _zz_301_ = (32'b00000000000000000101000000010100); + assign _zz_302_ = (32'b00000000000000000110000000010100); + assign _zz_303_ = (decode_INSTRUCTION & (32'b00000000000000000001000001001000)); + assign _zz_304_ = (32'b00000000000000000001000000001000); + assign _zz_305_ = _zz_88_; + assign _zz_306_ = ((decode_INSTRUCTION & (32'b00000000000000000000000001110000)) == (32'b00000000000000000000000000100000)); + assign _zz_307_ = {_zz_88_,((decode_INSTRUCTION & _zz_312_) == (32'b00000000000000000000000000000000))}; + assign _zz_308_ = (2'b00); + assign _zz_309_ = (((decode_INSTRUCTION & _zz_313_) == (32'b00000000000000000101000000010000)) != (1'b0)); + assign _zz_310_ = ({_zz_314_,_zz_315_} != (2'b00)); + assign _zz_311_ = {(_zz_316_ != (1'b0)),{(_zz_317_ != _zz_318_),(_zz_319_ != _zz_320_)}}; + assign _zz_312_ = (32'b00000000000000000000000000100000); + assign _zz_313_ = (32'b00000000000000000111000001010100); + assign _zz_314_ = ((decode_INSTRUCTION & (32'b01000000000000000011000001010100)) == (32'b01000000000000000001000000010000)); + assign _zz_315_ = ((decode_INSTRUCTION & (32'b00000000000000000111000001010100)) == (32'b00000000000000000001000000010000)); + assign _zz_316_ = ((decode_INSTRUCTION & (32'b00000000000000000000000000010000)) == (32'b00000000000000000000000000010000)); + assign _zz_317_ = ((decode_INSTRUCTION & (32'b00000000000000000000000000000000)) == (32'b00000000000000000000000000000000)); + assign _zz_318_ = (1'b0); + assign _zz_319_ = {((decode_INSTRUCTION & (32'b00000000000000000001000001010000)) == (32'b00000000000000000001000001010000)),((decode_INSTRUCTION & (32'b00000000000000000010000001010000)) == (32'b00000000000000000010000001010000))}; + assign _zz_320_ = (2'b00); + assign _zz_321_ = (32'b00000000000000000001000001111111); + assign _zz_322_ = (decode_INSTRUCTION & (32'b00000000000000000010000001111111)); + assign _zz_323_ = (32'b00000000000000000010000001110011); + assign _zz_324_ = ((decode_INSTRUCTION & (32'b00000000000000000100000001111111)) == (32'b00000000000000000100000001100011)); + assign _zz_325_ = ((decode_INSTRUCTION & (32'b00000000000000000010000001111111)) == (32'b00000000000000000010000000010011)); + assign _zz_326_ = {((decode_INSTRUCTION & (32'b00000000000000000110000000111111)) == (32'b00000000000000000000000000100011)),{((decode_INSTRUCTION & (32'b00000000000000000010000001111111)) == (32'b00000000000000000000000000000011)),{((decode_INSTRUCTION & _zz_327_) == (32'b00000000000000000000000000000011)),{(_zz_328_ == _zz_329_),{_zz_330_,{_zz_331_,_zz_332_}}}}}}; + assign _zz_327_ = (32'b00000000000000000101000001011111); + assign _zz_328_ = (decode_INSTRUCTION & (32'b00000000000000000111000001111011)); + assign _zz_329_ = (32'b00000000000000000000000001100011); + assign _zz_330_ = ((decode_INSTRUCTION & (32'b00000000000000000110000001111111)) == (32'b00000000000000000000000000001111)); + assign _zz_331_ = ((decode_INSTRUCTION & (32'b11111110000000000000000001111111)) == (32'b00000000000000000000000000110011)); + assign _zz_332_ = {((decode_INSTRUCTION & (32'b10111100000000000111000001111111)) == (32'b00000000000000000101000000010011)),{((decode_INSTRUCTION & (32'b11111100000000000011000001111111)) == (32'b00000000000000000001000000010011)),{((decode_INSTRUCTION & _zz_333_) == (32'b00000000000000000101000000110011)),{(_zz_334_ == _zz_335_),{_zz_336_,{_zz_337_,_zz_338_}}}}}}; + assign _zz_333_ = (32'b10111110000000000111000001111111); + assign _zz_334_ = (decode_INSTRUCTION & (32'b10111110000000000111000001111111)); + assign _zz_335_ = (32'b00000000000000000000000000110011); + assign _zz_336_ = ((decode_INSTRUCTION & (32'b11011111111111111111111111111111)) == (32'b00010000001000000000000001110011)); + assign _zz_337_ = ((decode_INSTRUCTION & (32'b11111111111011111111111111111111)) == (32'b00000000000000000000000001110011)); + assign _zz_338_ = ((decode_INSTRUCTION & (32'b11111111111111111111111111111111)) == (32'b00010000010100000000000001110011)); + initial begin + $readmemb("2-stage-1024-cache.v_toplevel_RegFilePlugin_regFile.bin",RegFilePlugin_regFile); + end + always @ (posedge clk) begin + if(_zz_40_) begin + RegFilePlugin_regFile[execute_RegFilePlugin_regFileWrite_payload_address] <= execute_RegFilePlugin_regFileWrite_payload_data; + end + end + + always @ (posedge clk) begin + if(_zz_99_) begin + _zz_148_ <= RegFilePlugin_regFile[execute_RegFilePlugin_regFileReadAddress1]; + end + end + + always @ (posedge clk) begin + if(_zz_99_) begin + _zz_149_ <= RegFilePlugin_regFile[execute_RegFilePlugin_regFileReadAddress2]; + end + end + + InstructionCache IBusCachedPlugin_cache ( + .io_flush(_zz_130_), + .io_cpu_prefetch_isValid(_zz_131_), + .io_cpu_prefetch_haltIt(IBusCachedPlugin_cache_io_cpu_prefetch_haltIt), + .io_cpu_prefetch_pc(IBusCachedPlugin_iBusRsp_stages_0_input_payload), + .io_cpu_fetch_isValid(_zz_132_), + .io_cpu_fetch_isStuck(_zz_133_), + .io_cpu_fetch_isRemoved(_zz_134_), + .io_cpu_fetch_pc(IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload), + .io_cpu_fetch_data(IBusCachedPlugin_cache_io_cpu_fetch_data), + .io_cpu_fetch_dataBypassValid(IBusCachedPlugin_s1_tightlyCoupledHit), + .io_cpu_fetch_dataBypass(_zz_135_), + .io_cpu_fetch_mmuBus_cmd_isValid(IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_isValid), + .io_cpu_fetch_mmuBus_cmd_virtualAddress(IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_virtualAddress), + .io_cpu_fetch_mmuBus_cmd_bypassTranslation(IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_bypassTranslation), + .io_cpu_fetch_mmuBus_rsp_physicalAddress(IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_cmd_virtualAddress), + .io_cpu_fetch_mmuBus_rsp_isIoAccess(_zz_136_), + .io_cpu_fetch_mmuBus_rsp_allowRead(_zz_137_), + .io_cpu_fetch_mmuBus_rsp_allowWrite(_zz_138_), + .io_cpu_fetch_mmuBus_rsp_allowExecute(_zz_139_), + .io_cpu_fetch_mmuBus_rsp_exception(_zz_140_), + .io_cpu_fetch_mmuBus_rsp_refilling(_zz_141_), + .io_cpu_fetch_mmuBus_end(IBusCachedPlugin_cache_io_cpu_fetch_mmuBus_end), + .io_cpu_fetch_mmuBus_busy(_zz_142_), + .io_cpu_fetch_physicalAddress(IBusCachedPlugin_cache_io_cpu_fetch_physicalAddress), + .io_cpu_fetch_cacheMiss(IBusCachedPlugin_cache_io_cpu_fetch_cacheMiss), + .io_cpu_fetch_error(IBusCachedPlugin_cache_io_cpu_fetch_error), + .io_cpu_fetch_mmuRefilling(IBusCachedPlugin_cache_io_cpu_fetch_mmuRefilling), + .io_cpu_fetch_mmuException(IBusCachedPlugin_cache_io_cpu_fetch_mmuException), + .io_cpu_fetch_isUser(_zz_143_), + .io_cpu_fetch_haltIt(IBusCachedPlugin_cache_io_cpu_fetch_haltIt), + .io_cpu_decode_isValid(_zz_144_), + .io_cpu_decode_isStuck(_zz_145_), + .io_cpu_decode_pc(_zz_146_), + .io_cpu_decode_physicalAddress(IBusCachedPlugin_cache_io_cpu_decode_physicalAddress), + .io_cpu_decode_data(IBusCachedPlugin_cache_io_cpu_decode_data), + .io_cpu_fill_valid(_zz_147_), + .io_cpu_fill_payload(IBusCachedPlugin_cache_io_cpu_fetch_physicalAddress), + .io_mem_cmd_valid(IBusCachedPlugin_cache_io_mem_cmd_valid), + .io_mem_cmd_ready(iBus_cmd_ready), + .io_mem_cmd_payload_address(IBusCachedPlugin_cache_io_mem_cmd_payload_address), + .io_mem_cmd_payload_size(IBusCachedPlugin_cache_io_mem_cmd_payload_size), + .io_mem_rsp_valid(iBus_rsp_valid), + .io_mem_rsp_payload_data(iBus_rsp_payload_data), + .io_mem_rsp_payload_error(iBus_rsp_payload_error), + .clk(clk), + .reset(reset) + ); + always @(*) begin + case(_zz_205_) + 2'b00 : begin + _zz_150_ = BranchPlugin_jumpInterface_payload; + end + 2'b01 : begin + _zz_150_ = CsrPlugin_jumpInterface_payload; + end + default : begin + _zz_150_ = IBusCachedPlugin_redoBranch_payload; + end + endcase + end + + always @(*) begin + case(_zz_124_) + 2'b00 : begin + _zz_151_ = DBusSimplePlugin_memoryExceptionPort_payload_code; + _zz_152_ = DBusSimplePlugin_memoryExceptionPort_payload_badAddr; + end + 2'b01 : begin + _zz_151_ = BranchPlugin_branchExceptionPort_payload_code; + _zz_152_ = BranchPlugin_branchExceptionPort_payload_badAddr; + end + default : begin + _zz_151_ = CsrPlugin_selfException_payload_code; + _zz_152_ = CsrPlugin_selfException_payload_badAddr; + end + endcase + end + + `ifndef SYNTHESIS + always @(*) begin + case(decode_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : decode_ENV_CTRL_string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : decode_ENV_CTRL_string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : decode_ENV_CTRL_string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : decode_ENV_CTRL_string = "EBREAK"; + default : decode_ENV_CTRL_string = "??????"; + endcase + end + always @(*) begin + case(_zz_1_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_1__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_1__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_1__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_1__string = "EBREAK"; + default : _zz_1__string = "??????"; + endcase + end + always @(*) begin + case(_zz_2_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_2__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_2__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_2__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_2__string = "EBREAK"; + default : _zz_2__string = "??????"; + endcase + end + always @(*) begin + case(_zz_3_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_3__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_3__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_3__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_3__string = "EBREAK"; + default : _zz_3__string = "??????"; + endcase + end + always @(*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_SRC2_CTRL_string = "PC "; + default : decode_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_4_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_4__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_4__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_4__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_4__string = "PC "; + default : _zz_4__string = "???"; + endcase + end + always @(*) begin + case(_zz_5_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_5__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_5__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_5__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_5__string = "PC "; + default : _zz_5__string = "???"; + endcase + end + always @(*) begin + case(_zz_6_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_6__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_6__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_6__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_6__string = "PC "; + default : _zz_6__string = "???"; + endcase + end + always @(*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_SRC1_CTRL_string = "URS1 "; + default : decode_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_7_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_7__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_7__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_7__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_7__string = "URS1 "; + default : _zz_7__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_8_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_8__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_8__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_8__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_8__string = "URS1 "; + default : _zz_8__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_9_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_9__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_9__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_9__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_9__string = "URS1 "; + default : _zz_9__string = "????????????"; + endcase + end + always @(*) begin + case(decode_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_ALU_CTRL_string = "BITWISE "; + default : decode_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_10_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_10__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_10__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_10__string = "BITWISE "; + default : _zz_10__string = "????????"; + endcase + end + always @(*) begin + case(_zz_11_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_11__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_11__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_11__string = "BITWISE "; + default : _zz_11__string = "????????"; + endcase + end + always @(*) begin + case(_zz_12_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_12__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_12__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_12__string = "BITWISE "; + default : _zz_12__string = "????????"; + endcase + end + always @(*) begin + case(decode_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_BRANCH_CTRL_string = "JALR"; + default : decode_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_13_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_13__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_13__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_13__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_13__string = "JALR"; + default : _zz_13__string = "????"; + endcase + end + always @(*) begin + case(_zz_14_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_14__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_14__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_14__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_14__string = "JALR"; + default : _zz_14__string = "????"; + endcase + end + always @(*) begin + case(_zz_15_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_15__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_15__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_15__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_15__string = "JALR"; + default : _zz_15__string = "????"; + endcase + end + always @(*) begin + case(decode_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_SHIFT_CTRL_string = "SRA_1 "; + default : decode_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_16_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_16__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_16__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_16__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_16__string = "SRA_1 "; + default : _zz_16__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_17_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_17__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_17__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_17__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_17__string = "SRA_1 "; + default : _zz_17__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_18_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_18__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_18__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_18__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_18__string = "SRA_1 "; + default : _zz_18__string = "?????????"; + endcase + end + always @(*) begin + case(decode_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_19_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_19__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_19__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_19__string = "AND_1"; + default : _zz_19__string = "?????"; + endcase + end + always @(*) begin + case(_zz_20_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_20__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_20__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_20__string = "AND_1"; + default : _zz_20__string = "?????"; + endcase + end + always @(*) begin + case(_zz_21_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_21__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_21__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_21__string = "AND_1"; + default : _zz_21__string = "?????"; + endcase + end + always @(*) begin + case(execute_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : execute_ENV_CTRL_string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : execute_ENV_CTRL_string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : execute_ENV_CTRL_string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : execute_ENV_CTRL_string = "EBREAK"; + default : execute_ENV_CTRL_string = "??????"; + endcase + end + always @(*) begin + case(_zz_24_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_24__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_24__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_24__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_24__string = "EBREAK"; + default : _zz_24__string = "??????"; + endcase + end + always @(*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : execute_BRANCH_CTRL_string = "JALR"; + default : execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_26_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_26__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_26__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_26__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_26__string = "JALR"; + default : _zz_26__string = "????"; + endcase + end + always @(*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : execute_SHIFT_CTRL_string = "SRA_1 "; + default : execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_28_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_28__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_28__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_28__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_28__string = "SRA_1 "; + default : _zz_28__string = "?????????"; + endcase + end + always @(*) begin + case(execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : execute_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : execute_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : execute_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : execute_SRC2_CTRL_string = "PC "; + default : execute_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_32_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_32__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_32__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_32__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_32__string = "PC "; + default : _zz_32__string = "???"; + endcase + end + always @(*) begin + case(execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : execute_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : execute_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : execute_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : execute_SRC1_CTRL_string = "URS1 "; + default : execute_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_34_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_34__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_34__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_34__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_34__string = "URS1 "; + default : _zz_34__string = "????????????"; + endcase + end + always @(*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : execute_ALU_CTRL_string = "BITWISE "; + default : execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_37_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_37__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_37__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_37__string = "BITWISE "; + default : _zz_37__string = "????????"; + endcase + end + always @(*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_39_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_39__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_39__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_39__string = "AND_1"; + default : _zz_39__string = "?????"; + endcase + end + always @(*) begin + case(_zz_45_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_45__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_45__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_45__string = "AND_1"; + default : _zz_45__string = "?????"; + endcase + end + always @(*) begin + case(_zz_50_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_50__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_50__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_50__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_50__string = "URS1 "; + default : _zz_50__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_51_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_51__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_51__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_51__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_51__string = "JALR"; + default : _zz_51__string = "????"; + endcase + end + always @(*) begin + case(_zz_52_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_52__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_52__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_52__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_52__string = "EBREAK"; + default : _zz_52__string = "??????"; + endcase + end + always @(*) begin + case(_zz_53_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_53__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_53__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_53__string = "BITWISE "; + default : _zz_53__string = "????????"; + endcase + end + always @(*) begin + case(_zz_55_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_55__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_55__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_55__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_55__string = "PC "; + default : _zz_55__string = "???"; + endcase + end + always @(*) begin + case(_zz_56_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_56__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_56__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_56__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_56__string = "SRA_1 "; + default : _zz_56__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_92_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_92__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_92__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_92__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_92__string = "SRA_1 "; + default : _zz_92__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_93_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_93__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_93__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_93__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_93__string = "PC "; + default : _zz_93__string = "???"; + endcase + end + always @(*) begin + case(_zz_94_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_94__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_94__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_94__string = "BITWISE "; + default : _zz_94__string = "????????"; + endcase + end + always @(*) begin + case(_zz_95_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_95__string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_95__string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : _zz_95__string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : _zz_95__string = "EBREAK"; + default : _zz_95__string = "??????"; + endcase + end + always @(*) begin + case(_zz_96_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_96__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_96__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_96__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_96__string = "JALR"; + default : _zz_96__string = "????"; + endcase + end + always @(*) begin + case(_zz_97_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_97__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_97__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_97__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_97__string = "URS1 "; + default : _zz_97__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_98_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_98__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_98__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_98__string = "AND_1"; + default : _zz_98__string = "?????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_to_execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(decode_to_execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_to_execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_to_execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_to_execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_to_execute_SHIFT_CTRL_string = "SRA_1 "; + default : decode_to_execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_to_execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_to_execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_to_execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_to_execute_BRANCH_CTRL_string = "JALR"; + default : decode_to_execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_to_execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_to_execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_to_execute_ALU_CTRL_string = "BITWISE "; + default : decode_to_execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_to_execute_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_to_execute_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_to_execute_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_to_execute_SRC1_CTRL_string = "URS1 "; + default : decode_to_execute_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_to_execute_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_to_execute_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_to_execute_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_to_execute_SRC2_CTRL_string = "PC "; + default : decode_to_execute_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(decode_to_execute_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : decode_to_execute_ENV_CTRL_string = "NONE "; + `EnvCtrlEnum_defaultEncoding_XRET : decode_to_execute_ENV_CTRL_string = "XRET "; + `EnvCtrlEnum_defaultEncoding_ECALL : decode_to_execute_ENV_CTRL_string = "ECALL "; + `EnvCtrlEnum_defaultEncoding_EBREAK : decode_to_execute_ENV_CTRL_string = "EBREAK"; + default : decode_to_execute_ENV_CTRL_string = "??????"; + endcase + end + `endif + + assign decode_CSR_WRITE_OPCODE = _zz_23_; + assign decode_SRC_LESS_UNSIGNED = _zz_47_; + assign decode_ENV_CTRL = _zz_1_; + assign _zz_2_ = _zz_3_; + assign execute_FORMAL_PC_NEXT = decode_to_execute_FORMAL_PC_NEXT; + assign decode_FORMAL_PC_NEXT = _zz_67_; + assign decode_SRC2_CTRL = _zz_4_; + assign _zz_5_ = _zz_6_; + assign decode_IS_CSR = _zz_57_; + assign decode_MEMORY_ENABLE = _zz_49_; + assign decode_SRC1_CTRL = _zz_7_; + assign _zz_8_ = _zz_9_; + assign decode_CSR_READ_OPCODE = _zz_22_; + assign execute_REGFILE_WRITE_VALID = decode_to_execute_REGFILE_WRITE_VALID; + assign decode_ALU_CTRL = _zz_10_; + assign _zz_11_ = _zz_12_; + assign decode_SRC2_FORCE_ZERO = _zz_36_; + assign decode_MEMORY_STORE = _zz_48_; + assign decode_BRANCH_CTRL = _zz_13_; + assign _zz_14_ = _zz_15_; + assign decode_SHIFT_CTRL = _zz_16_; + assign _zz_17_ = _zz_18_; + assign decode_ALU_BITWISE_CTRL = _zz_19_; + assign _zz_20_ = _zz_21_; + assign execute_CSR_READ_OPCODE = decode_to_execute_CSR_READ_OPCODE; + assign execute_CSR_WRITE_OPCODE = decode_to_execute_CSR_WRITE_OPCODE; + assign execute_IS_CSR = decode_to_execute_IS_CSR; + assign execute_ENV_CTRL = _zz_24_; + assign execute_BRANCH_CALC = _zz_25_; + assign execute_BRANCH_DO = _zz_27_; + assign execute_PC = decode_to_execute_PC; + assign execute_RS1 = _zz_42_; + assign execute_BRANCH_CTRL = _zz_26_; + assign execute_SHIFT_CTRL = _zz_28_; + assign execute_SRC_LESS_UNSIGNED = decode_to_execute_SRC_LESS_UNSIGNED; + assign execute_SRC2_FORCE_ZERO = decode_to_execute_SRC2_FORCE_ZERO; + assign execute_SRC_USE_SUB_LESS = decode_to_execute_SRC_USE_SUB_LESS; + assign execute_SRC2_CTRL = _zz_32_; + assign execute_SRC1_CTRL = _zz_34_; + assign decode_SRC_USE_SUB_LESS = _zz_46_; + assign decode_SRC_ADD_ZERO = _zz_43_; + assign execute_SRC_ADD_SUB = _zz_31_; + assign execute_SRC_LESS = _zz_29_; + assign execute_ALU_CTRL = _zz_37_; + assign execute_SRC2 = _zz_33_; + assign execute_SRC1 = _zz_35_; + assign execute_ALU_BITWISE_CTRL = _zz_39_; + always @ (*) begin + _zz_40_ = 1'b0; + if(execute_RegFilePlugin_regFileWrite_valid)begin + _zz_40_ = 1'b1; + end + end + + always @ (*) begin + decode_REGFILE_WRITE_VALID = _zz_44_; + if((decode_INSTRUCTION[11 : 7] == (5'b00000)))begin + decode_REGFILE_WRITE_VALID = 1'b0; + end + end + + assign decode_LEGAL_INSTRUCTION = _zz_58_; + assign decode_INSTRUCTION_READY = 1'b1; + always @ (*) begin + _zz_59_ = execute_REGFILE_WRITE_DATA; + execute_arbitration_haltItself = 1'b0; + if(((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! dBus_cmd_ready)) && (! execute_DBusSimplePlugin_skipCmd)) && (! execute_DBusSimplePlugin_cmdSent)))begin + execute_arbitration_haltItself = 1'b1; + end + if((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! execute_MEMORY_STORE)) && (! dBus_rsp_ready)))begin + execute_arbitration_haltItself = 1'b1; + end + if((execute_arbitration_isValid && execute_MEMORY_ENABLE))begin + _zz_59_ = execute_DBusSimplePlugin_rspFormated; + end + if(_zz_153_)begin + _zz_59_ = _zz_107_; + if(_zz_154_)begin + if(! execute_LightShifterPlugin_done) begin + execute_arbitration_haltItself = 1'b1; + end + end + end + if((execute_arbitration_isValid && execute_IS_CSR))begin + _zz_59_ = execute_CsrPlugin_readData; + if(execute_CsrPlugin_blockedBySideEffects)begin + execute_arbitration_haltItself = 1'b1; + end + end + end + + assign execute_MEMORY_ADDRESS_LOW = _zz_61_; + assign execute_MEMORY_READ_DATA = _zz_60_; + assign execute_REGFILE_WRITE_DATA = _zz_38_; + assign execute_SRC_ADD = _zz_30_; + assign execute_RS2 = _zz_41_; + assign execute_INSTRUCTION = decode_to_execute_INSTRUCTION; + assign execute_MEMORY_STORE = decode_to_execute_MEMORY_STORE; + assign execute_MEMORY_ENABLE = decode_to_execute_MEMORY_ENABLE; + assign execute_ALIGNEMENT_FAULT = _zz_62_; + assign decode_FLUSH_ALL = _zz_54_; + always @ (*) begin + IBusCachedPlugin_rsp_issueDetected = _zz_63_; + _zz_64_ = _zz_65_; + IBusCachedPlugin_decodeExceptionPort_valid = 1'b0; + IBusCachedPlugin_decodeExceptionPort_payload_code = (4'bxxxx); + if(((_zz_132_ && IBusCachedPlugin_cache_io_cpu_fetch_mmuException) && (! _zz_65_)))begin + _zz_64_ = 1'b1; + IBusCachedPlugin_decodeExceptionPort_valid = IBusCachedPlugin_iBusRsp_readyForError; + IBusCachedPlugin_decodeExceptionPort_payload_code = (4'b1100); + end + if(((_zz_132_ && IBusCachedPlugin_cache_io_cpu_fetch_error) && (! _zz_63_)))begin + IBusCachedPlugin_rsp_issueDetected = 1'b1; + IBusCachedPlugin_decodeExceptionPort_valid = IBusCachedPlugin_iBusRsp_readyForError; + IBusCachedPlugin_decodeExceptionPort_payload_code = (4'b0001); + end + if(IBusCachedPlugin_fetcherHalt)begin + IBusCachedPlugin_decodeExceptionPort_valid = 1'b0; + end + end + + always @ (*) begin + _zz_63_ = _zz_64_; + _zz_65_ = 1'b0; + IBusCachedPlugin_rsp_redoFetch = 1'b0; + _zz_147_ = (IBusCachedPlugin_rsp_redoFetch && (! IBusCachedPlugin_cache_io_cpu_fetch_mmuRefilling)); + if(((_zz_132_ && IBusCachedPlugin_cache_io_cpu_fetch_mmuRefilling) && (! 1'b0)))begin + _zz_65_ = 1'b1; + IBusCachedPlugin_rsp_redoFetch = 1'b1; + end + if(((_zz_132_ && IBusCachedPlugin_cache_io_cpu_fetch_cacheMiss) && (! _zz_64_)))begin + _zz_63_ = 1'b1; + _zz_147_ = 1'b1; + IBusCachedPlugin_rsp_redoFetch = 1'b1; + end + if((! IBusCachedPlugin_iBusRsp_readyForError))begin + IBusCachedPlugin_rsp_redoFetch = 1'b0; + end + if((! IBusCachedPlugin_iBusRsp_readyForError))begin + _zz_147_ = 1'b0; + end + end + + always @ (*) begin + _zz_66_ = decode_FORMAL_PC_NEXT; + if(IBusCachedPlugin_redoBranch_valid)begin + _zz_66_ = IBusCachedPlugin_redoBranch_payload; + end + end + + assign decode_PC = _zz_69_; + assign decode_INSTRUCTION = _zz_68_; + assign decode_arbitration_haltItself = 1'b0; + always @ (*) begin + decode_arbitration_haltByOther = 1'b0; + if(CsrPlugin_interrupt)begin + decode_arbitration_haltByOther = decode_arbitration_isValid; + end + if(((execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)) != (1'b0)))begin + decode_arbitration_haltByOther = 1'b1; + end + end + + always @ (*) begin + decode_arbitration_removeIt = 1'b0; + if(_zz_155_)begin + decode_arbitration_removeIt = 1'b1; + end + if(decode_arbitration_isFlushed)begin + decode_arbitration_removeIt = 1'b1; + end + end + + always @ (*) begin + decode_arbitration_flushAll = 1'b0; + execute_arbitration_removeIt = 1'b0; + IBusCachedPlugin_fetcherHalt = 1'b0; + CsrPlugin_jumpInterface_valid = 1'b0; + CsrPlugin_jumpInterface_payload = (32'bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); + if(BranchPlugin_jumpInterface_valid)begin + decode_arbitration_flushAll = 1'b1; + end + CsrPlugin_exceptionPortCtrl_exceptionValids_execute = CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute; + if(_zz_156_)begin + decode_arbitration_flushAll = 1'b1; + execute_arbitration_removeIt = 1'b1; + CsrPlugin_exceptionPortCtrl_exceptionValids_execute = 1'b1; + end + if(execute_arbitration_isFlushed)begin + CsrPlugin_exceptionPortCtrl_exceptionValids_execute = 1'b0; + end + if(({CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute,CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode} != (2'b00)))begin + IBusCachedPlugin_fetcherHalt = 1'b1; + end + if(_zz_157_)begin + IBusCachedPlugin_fetcherHalt = 1'b1; + CsrPlugin_jumpInterface_valid = 1'b1; + CsrPlugin_jumpInterface_payload = {CsrPlugin_xtvec_base,(2'b00)}; + decode_arbitration_flushAll = 1'b1; + end + if(_zz_158_)begin + IBusCachedPlugin_fetcherHalt = 1'b1; + CsrPlugin_jumpInterface_valid = 1'b1; + decode_arbitration_flushAll = 1'b1; + case(_zz_159_) + 2'b11 : begin + CsrPlugin_jumpInterface_payload = CsrPlugin_mepc; + end + default : begin + end + endcase + end + if(execute_arbitration_isFlushed)begin + execute_arbitration_removeIt = 1'b1; + end + end + + assign execute_arbitration_haltByOther = 1'b0; + assign execute_arbitration_flushAll = 1'b0; + assign IBusCachedPlugin_fetcherflushIt = 1'b0; + always @ (*) begin + IBusCachedPlugin_incomingInstruction = 1'b0; + if(IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid)begin + IBusCachedPlugin_incomingInstruction = 1'b1; + end + end + + assign CsrPlugin_forceMachineWire = 1'b0; + assign CsrPlugin_allowInterrupts = 1'b1; + assign CsrPlugin_allowException = 1'b1; + assign IBusCachedPlugin_jump_pcLoad_valid = ({CsrPlugin_jumpInterface_valid,{BranchPlugin_jumpInterface_valid,IBusCachedPlugin_redoBranch_valid}} != (3'b000)); + assign _zz_70_ = {IBusCachedPlugin_redoBranch_valid,{CsrPlugin_jumpInterface_valid,BranchPlugin_jumpInterface_valid}}; + assign _zz_71_ = (_zz_70_ & (~ _zz_165_)); + assign _zz_72_ = _zz_71_[1]; + assign _zz_73_ = _zz_71_[2]; + assign IBusCachedPlugin_jump_pcLoad_payload = _zz_150_; + assign _zz_74_ = (! IBusCachedPlugin_fetcherHalt); + assign IBusCachedPlugin_fetchPc_output_valid = (IBusCachedPlugin_fetchPc_preOutput_valid && _zz_74_); + assign IBusCachedPlugin_fetchPc_preOutput_ready = (IBusCachedPlugin_fetchPc_output_ready && _zz_74_); + assign IBusCachedPlugin_fetchPc_output_payload = IBusCachedPlugin_fetchPc_preOutput_payload; + always @ (*) begin + IBusCachedPlugin_fetchPc_propagatePc = 1'b0; + if((IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid && IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready))begin + IBusCachedPlugin_fetchPc_propagatePc = 1'b1; + end + end + + always @ (*) begin + IBusCachedPlugin_fetchPc_pc = (IBusCachedPlugin_fetchPc_pcReg + _zz_167_); + IBusCachedPlugin_fetchPc_samplePcNext = 1'b0; + if(IBusCachedPlugin_fetchPc_propagatePc)begin + IBusCachedPlugin_fetchPc_samplePcNext = 1'b1; + end + if(IBusCachedPlugin_jump_pcLoad_valid)begin + IBusCachedPlugin_fetchPc_samplePcNext = 1'b1; + IBusCachedPlugin_fetchPc_pc = IBusCachedPlugin_jump_pcLoad_payload; + end + if(_zz_160_)begin + IBusCachedPlugin_fetchPc_samplePcNext = 1'b1; + end + IBusCachedPlugin_fetchPc_pc[0] = 1'b0; + IBusCachedPlugin_fetchPc_pc[1] = 1'b0; + end + + assign IBusCachedPlugin_fetchPc_preOutput_valid = _zz_75_; + assign IBusCachedPlugin_fetchPc_preOutput_payload = IBusCachedPlugin_fetchPc_pc; + assign IBusCachedPlugin_iBusRsp_stages_0_input_valid = IBusCachedPlugin_fetchPc_output_valid; + assign IBusCachedPlugin_fetchPc_output_ready = IBusCachedPlugin_iBusRsp_stages_0_input_ready; + assign IBusCachedPlugin_iBusRsp_stages_0_input_payload = IBusCachedPlugin_fetchPc_output_payload; + assign IBusCachedPlugin_iBusRsp_stages_0_inputSample = 1'b1; + always @ (*) begin + IBusCachedPlugin_iBusRsp_stages_0_halt = 1'b0; + if(IBusCachedPlugin_cache_io_cpu_prefetch_haltIt)begin + IBusCachedPlugin_iBusRsp_stages_0_halt = 1'b1; + end + end + + assign _zz_76_ = (! IBusCachedPlugin_iBusRsp_stages_0_halt); + assign IBusCachedPlugin_iBusRsp_stages_0_input_ready = (IBusCachedPlugin_iBusRsp_stages_0_output_ready && _zz_76_); + assign IBusCachedPlugin_iBusRsp_stages_0_output_valid = (IBusCachedPlugin_iBusRsp_stages_0_input_valid && _zz_76_); + assign IBusCachedPlugin_iBusRsp_stages_0_output_payload = IBusCachedPlugin_iBusRsp_stages_0_input_payload; + always @ (*) begin + IBusCachedPlugin_iBusRsp_cacheRspArbitration_halt = 1'b0; + if(IBusCachedPlugin_cache_io_cpu_fetch_haltIt)begin + IBusCachedPlugin_iBusRsp_cacheRspArbitration_halt = 1'b1; + end + if((IBusCachedPlugin_rsp_issueDetected || IBusCachedPlugin_rsp_iBusRspOutputHalt))begin + IBusCachedPlugin_iBusRsp_cacheRspArbitration_halt = 1'b1; + end + end + + assign _zz_77_ = (! IBusCachedPlugin_iBusRsp_cacheRspArbitration_halt); + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready = (IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_ready && _zz_77_); + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_valid = (IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid && _zz_77_); + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_payload = IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload; + assign IBusCachedPlugin_iBusRsp_stages_0_output_ready = _zz_78_; + assign _zz_78_ = ((1'b0 && (! _zz_79_)) || IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready); + assign _zz_79_ = _zz_80_; + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid = _zz_79_; + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload = IBusCachedPlugin_fetchPc_pcReg; + always @ (*) begin + IBusCachedPlugin_iBusRsp_readyForError = 1'b1; + if((! IBusCachedPlugin_pcValids_0))begin + IBusCachedPlugin_iBusRsp_readyForError = 1'b0; + end + end + + assign IBusCachedPlugin_pcValids_0 = IBusCachedPlugin_injector_nextPcCalc_valids_0; + assign IBusCachedPlugin_pcValids_1 = IBusCachedPlugin_injector_nextPcCalc_valids_1; + assign IBusCachedPlugin_iBusRsp_decodeInput_ready = (! decode_arbitration_isStuck); + assign decode_arbitration_isValid = (IBusCachedPlugin_iBusRsp_decodeInput_valid && (! IBusCachedPlugin_injector_decodeRemoved)); + assign _zz_69_ = IBusCachedPlugin_iBusRsp_decodeInput_payload_pc; + assign _zz_68_ = IBusCachedPlugin_iBusRsp_decodeInput_payload_rsp_inst; + assign _zz_67_ = (decode_PC + (32'b00000000000000000000000000000100)); + assign iBus_cmd_valid = IBusCachedPlugin_cache_io_mem_cmd_valid; + always @ (*) begin + iBus_cmd_payload_address = IBusCachedPlugin_cache_io_mem_cmd_payload_address; + iBus_cmd_payload_address = IBusCachedPlugin_cache_io_mem_cmd_payload_address; + end + + assign iBus_cmd_payload_size = IBusCachedPlugin_cache_io_mem_cmd_payload_size; + assign IBusCachedPlugin_s0_tightlyCoupledHit = 1'b0; + assign _zz_131_ = (IBusCachedPlugin_iBusRsp_stages_0_input_valid && (! IBusCachedPlugin_s0_tightlyCoupledHit)); + assign _zz_134_ = (IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt); + assign _zz_135_ = (32'b00000000000000000000000000000000); + assign _zz_132_ = (IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_valid && (! IBusCachedPlugin_s1_tightlyCoupledHit)); + assign _zz_133_ = (! IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready); + assign _zz_143_ = (CsrPlugin_privilege == (2'b00)); + assign IBusCachedPlugin_rsp_iBusRspOutputHalt = 1'b0; + assign IBusCachedPlugin_decodeExceptionPort_payload_badAddr = {IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload[31 : 2],(2'b00)}; + assign IBusCachedPlugin_redoBranch_valid = IBusCachedPlugin_rsp_redoFetch; + assign IBusCachedPlugin_redoBranch_payload = IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_payload; + assign IBusCachedPlugin_iBusRsp_decodeInput_valid = IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_valid; + assign IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_ready = IBusCachedPlugin_iBusRsp_decodeInput_ready; + assign IBusCachedPlugin_iBusRsp_decodeInput_payload_rsp_inst = IBusCachedPlugin_cache_io_cpu_fetch_data; + assign IBusCachedPlugin_iBusRsp_decodeInput_payload_pc = IBusCachedPlugin_iBusRsp_cacheRspArbitration_output_payload; + assign _zz_139_ = 1'b1; + assign _zz_137_ = 1'b1; + assign _zz_138_ = 1'b1; + assign _zz_136_ = 1'b0; + assign _zz_140_ = 1'b0; + assign _zz_141_ = 1'b0; + assign _zz_142_ = 1'b0; + assign _zz_130_ = (decode_arbitration_isValid && decode_FLUSH_ALL); + assign _zz_62_ = (((dBus_cmd_payload_size == (2'b10)) && (dBus_cmd_payload_address[1 : 0] != (2'b00))) || ((dBus_cmd_payload_size == (2'b01)) && (dBus_cmd_payload_address[0 : 0] != (1'b0)))); + always @ (*) begin + execute_DBusSimplePlugin_skipCmd = 1'b0; + if(execute_ALIGNEMENT_FAULT)begin + execute_DBusSimplePlugin_skipCmd = 1'b1; + end + end + + assign dBus_cmd_valid = (((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! execute_arbitration_isStuckByOthers)) && (! execute_arbitration_isFlushed)) && (! execute_DBusSimplePlugin_skipCmd)) && (! execute_DBusSimplePlugin_cmdSent)); + assign dBus_cmd_payload_wr = execute_MEMORY_STORE; + assign dBus_cmd_payload_size = execute_INSTRUCTION[13 : 12]; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_81_ = {{{execute_RS2[7 : 0],execute_RS2[7 : 0]},execute_RS2[7 : 0]},execute_RS2[7 : 0]}; + end + 2'b01 : begin + _zz_81_ = {execute_RS2[15 : 0],execute_RS2[15 : 0]}; + end + default : begin + _zz_81_ = execute_RS2[31 : 0]; + end + endcase + end + + assign dBus_cmd_payload_data = _zz_81_; + assign _zz_61_ = dBus_cmd_payload_address[1 : 0]; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_82_ = (4'b0001); + end + 2'b01 : begin + _zz_82_ = (4'b0011); + end + default : begin + _zz_82_ = (4'b1111); + end + endcase + end + + assign execute_DBusSimplePlugin_formalMask = (_zz_82_ <<< dBus_cmd_payload_address[1 : 0]); + assign dBus_cmd_payload_address = execute_SRC_ADD; + assign _zz_60_ = dBus_rsp_data; + always @ (*) begin + DBusSimplePlugin_memoryExceptionPort_valid = 1'b0; + DBusSimplePlugin_memoryExceptionPort_payload_code = (4'bxxxx); + if(execute_ALIGNEMENT_FAULT)begin + DBusSimplePlugin_memoryExceptionPort_payload_code = {1'd0, _zz_168_}; + DBusSimplePlugin_memoryExceptionPort_valid = 1'b1; + end + if((! ((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (1'b0 || (! execute_arbitration_isStuckByOthers)))))begin + DBusSimplePlugin_memoryExceptionPort_valid = 1'b0; + end + end + + assign DBusSimplePlugin_memoryExceptionPort_payload_badAddr = execute_REGFILE_WRITE_DATA; + always @ (*) begin + execute_DBusSimplePlugin_rspShifted = execute_MEMORY_READ_DATA; + case(execute_MEMORY_ADDRESS_LOW) + 2'b01 : begin + execute_DBusSimplePlugin_rspShifted[7 : 0] = execute_MEMORY_READ_DATA[15 : 8]; + end + 2'b10 : begin + execute_DBusSimplePlugin_rspShifted[15 : 0] = execute_MEMORY_READ_DATA[31 : 16]; + end + 2'b11 : begin + execute_DBusSimplePlugin_rspShifted[7 : 0] = execute_MEMORY_READ_DATA[31 : 24]; + end + default : begin + end + endcase + end + + assign _zz_83_ = (execute_DBusSimplePlugin_rspShifted[7] && (! execute_INSTRUCTION[14])); + always @ (*) begin + _zz_84_[31] = _zz_83_; + _zz_84_[30] = _zz_83_; + _zz_84_[29] = _zz_83_; + _zz_84_[28] = _zz_83_; + _zz_84_[27] = _zz_83_; + _zz_84_[26] = _zz_83_; + _zz_84_[25] = _zz_83_; + _zz_84_[24] = _zz_83_; + _zz_84_[23] = _zz_83_; + _zz_84_[22] = _zz_83_; + _zz_84_[21] = _zz_83_; + _zz_84_[20] = _zz_83_; + _zz_84_[19] = _zz_83_; + _zz_84_[18] = _zz_83_; + _zz_84_[17] = _zz_83_; + _zz_84_[16] = _zz_83_; + _zz_84_[15] = _zz_83_; + _zz_84_[14] = _zz_83_; + _zz_84_[13] = _zz_83_; + _zz_84_[12] = _zz_83_; + _zz_84_[11] = _zz_83_; + _zz_84_[10] = _zz_83_; + _zz_84_[9] = _zz_83_; + _zz_84_[8] = _zz_83_; + _zz_84_[7 : 0] = execute_DBusSimplePlugin_rspShifted[7 : 0]; + end + + assign _zz_85_ = (execute_DBusSimplePlugin_rspShifted[15] && (! execute_INSTRUCTION[14])); + always @ (*) begin + _zz_86_[31] = _zz_85_; + _zz_86_[30] = _zz_85_; + _zz_86_[29] = _zz_85_; + _zz_86_[28] = _zz_85_; + _zz_86_[27] = _zz_85_; + _zz_86_[26] = _zz_85_; + _zz_86_[25] = _zz_85_; + _zz_86_[24] = _zz_85_; + _zz_86_[23] = _zz_85_; + _zz_86_[22] = _zz_85_; + _zz_86_[21] = _zz_85_; + _zz_86_[20] = _zz_85_; + _zz_86_[19] = _zz_85_; + _zz_86_[18] = _zz_85_; + _zz_86_[17] = _zz_85_; + _zz_86_[16] = _zz_85_; + _zz_86_[15 : 0] = execute_DBusSimplePlugin_rspShifted[15 : 0]; + end + + always @ (*) begin + case(_zz_163_) + 2'b00 : begin + execute_DBusSimplePlugin_rspFormated = _zz_84_; + end + 2'b01 : begin + execute_DBusSimplePlugin_rspFormated = _zz_86_; + end + default : begin + execute_DBusSimplePlugin_rspFormated = execute_DBusSimplePlugin_rspShifted; + end + endcase + end + + assign _zz_88_ = ((decode_INSTRUCTION & (32'b00000000000000000000000000000100)) == (32'b00000000000000000000000000000100)); + assign _zz_89_ = ((decode_INSTRUCTION & (32'b00000000000000000000000001001000)) == (32'b00000000000000000000000001001000)); + assign _zz_90_ = ((decode_INSTRUCTION & (32'b00000000000000000100000001010000)) == (32'b00000000000000000100000001010000)); + assign _zz_91_ = ((decode_INSTRUCTION & (32'b00000000000000000000000001010000)) == (32'b00000000000000000000000000010000)); + assign _zz_87_ = {(_zz_91_ != (1'b0)),{({_zz_206_,_zz_207_} != (2'b00)),{({_zz_208_,_zz_209_} != (6'b000000)),{(_zz_210_ != _zz_211_),{_zz_212_,{_zz_213_,_zz_214_}}}}}}; + assign _zz_58_ = ({((decode_INSTRUCTION & (32'b00000000000000000000000001011111)) == (32'b00000000000000000000000000010111)),{((decode_INSTRUCTION & (32'b00000000000000000000000001111111)) == (32'b00000000000000000000000001101111)),{((decode_INSTRUCTION & (32'b00000000000000000001000001101111)) == (32'b00000000000000000000000000000011)),{((decode_INSTRUCTION & _zz_321_) == (32'b00000000000000000001000001110011)),{(_zz_322_ == _zz_323_),{_zz_324_,{_zz_325_,_zz_326_}}}}}}} != (20'b00000000000000000000)); + assign _zz_57_ = _zz_169_[0]; + assign _zz_92_ = _zz_87_[4 : 3]; + assign _zz_56_ = _zz_92_; + assign _zz_93_ = _zz_87_[6 : 5]; + assign _zz_55_ = _zz_93_; + assign _zz_54_ = _zz_170_[0]; + assign _zz_94_ = _zz_87_[9 : 8]; + assign _zz_53_ = _zz_94_; + assign _zz_95_ = _zz_87_[11 : 10]; + assign _zz_52_ = _zz_95_; + assign _zz_96_ = _zz_87_[13 : 12]; + assign _zz_51_ = _zz_96_; + assign _zz_97_ = _zz_87_[17 : 16]; + assign _zz_50_ = _zz_97_; + assign _zz_49_ = _zz_171_[0]; + assign _zz_48_ = _zz_172_[0]; + assign _zz_47_ = _zz_173_[0]; + assign _zz_46_ = _zz_174_[0]; + assign _zz_98_ = _zz_87_[23 : 22]; + assign _zz_45_ = _zz_98_; + assign _zz_44_ = _zz_175_[0]; + assign _zz_43_ = _zz_176_[0]; + assign decodeExceptionPort_valid = ((decode_arbitration_isValid && decode_INSTRUCTION_READY) && (! decode_LEGAL_INSTRUCTION)); + assign decodeExceptionPort_payload_code = (4'b0010); + assign decodeExceptionPort_payload_badAddr = decode_INSTRUCTION; + assign execute_RegFilePlugin_regFileReadAddress1 = decode_INSTRUCTION[19 : 15]; + assign execute_RegFilePlugin_regFileReadAddress2 = decode_INSTRUCTION[24 : 20]; + assign _zz_99_ = (! execute_arbitration_isStuck); + assign execute_RegFilePlugin_rs1Data = _zz_148_; + assign execute_RegFilePlugin_rs2Data = _zz_149_; + assign _zz_42_ = execute_RegFilePlugin_rs1Data; + assign _zz_41_ = execute_RegFilePlugin_rs2Data; + assign execute_RegFilePlugin_regFileWrite_valid = (execute_REGFILE_WRITE_VALID && execute_arbitration_isFiring); + assign execute_RegFilePlugin_regFileWrite_payload_address = execute_INSTRUCTION[11 : 7]; + assign execute_RegFilePlugin_regFileWrite_payload_data = _zz_59_; + always @ (*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 & execute_SRC2); + end + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 | execute_SRC2); + end + default : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 ^ execute_SRC2); + end + endcase + end + + always @ (*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_BITWISE : begin + _zz_100_ = execute_IntAluPlugin_bitwise; + end + `AluCtrlEnum_defaultEncoding_SLT_SLTU : begin + _zz_100_ = {31'd0, _zz_177_}; + end + default : begin + _zz_100_ = execute_SRC_ADD_SUB; + end + endcase + end + + assign _zz_38_ = _zz_100_; + assign _zz_36_ = (decode_SRC_ADD_ZERO && (! decode_SRC_USE_SUB_LESS)); + always @ (*) begin + case(execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : begin + _zz_101_ = execute_RS1; + end + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : begin + _zz_101_ = {29'd0, _zz_178_}; + end + `Src1CtrlEnum_defaultEncoding_IMU : begin + _zz_101_ = {execute_INSTRUCTION[31 : 12],(12'b000000000000)}; + end + default : begin + _zz_101_ = {27'd0, _zz_179_}; + end + endcase + end + + assign _zz_35_ = _zz_101_; + assign _zz_102_ = _zz_180_[11]; + always @ (*) begin + _zz_103_[19] = _zz_102_; + _zz_103_[18] = _zz_102_; + _zz_103_[17] = _zz_102_; + _zz_103_[16] = _zz_102_; + _zz_103_[15] = _zz_102_; + _zz_103_[14] = _zz_102_; + _zz_103_[13] = _zz_102_; + _zz_103_[12] = _zz_102_; + _zz_103_[11] = _zz_102_; + _zz_103_[10] = _zz_102_; + _zz_103_[9] = _zz_102_; + _zz_103_[8] = _zz_102_; + _zz_103_[7] = _zz_102_; + _zz_103_[6] = _zz_102_; + _zz_103_[5] = _zz_102_; + _zz_103_[4] = _zz_102_; + _zz_103_[3] = _zz_102_; + _zz_103_[2] = _zz_102_; + _zz_103_[1] = _zz_102_; + _zz_103_[0] = _zz_102_; + end + + assign _zz_104_ = _zz_181_[11]; + always @ (*) begin + _zz_105_[19] = _zz_104_; + _zz_105_[18] = _zz_104_; + _zz_105_[17] = _zz_104_; + _zz_105_[16] = _zz_104_; + _zz_105_[15] = _zz_104_; + _zz_105_[14] = _zz_104_; + _zz_105_[13] = _zz_104_; + _zz_105_[12] = _zz_104_; + _zz_105_[11] = _zz_104_; + _zz_105_[10] = _zz_104_; + _zz_105_[9] = _zz_104_; + _zz_105_[8] = _zz_104_; + _zz_105_[7] = _zz_104_; + _zz_105_[6] = _zz_104_; + _zz_105_[5] = _zz_104_; + _zz_105_[4] = _zz_104_; + _zz_105_[3] = _zz_104_; + _zz_105_[2] = _zz_104_; + _zz_105_[1] = _zz_104_; + _zz_105_[0] = _zz_104_; + end + + always @ (*) begin + case(execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : begin + _zz_106_ = execute_RS2; + end + `Src2CtrlEnum_defaultEncoding_IMI : begin + _zz_106_ = {_zz_103_,execute_INSTRUCTION[31 : 20]}; + end + `Src2CtrlEnum_defaultEncoding_IMS : begin + _zz_106_ = {_zz_105_,{execute_INSTRUCTION[31 : 25],execute_INSTRUCTION[11 : 7]}}; + end + default : begin + _zz_106_ = execute_PC; + end + endcase + end + + assign _zz_33_ = _zz_106_; + always @ (*) begin + execute_SrcPlugin_addSub = _zz_182_; + if(execute_SRC2_FORCE_ZERO)begin + execute_SrcPlugin_addSub = execute_SRC1; + end + end + + assign execute_SrcPlugin_less = ((execute_SRC1[31] == execute_SRC2[31]) ? execute_SrcPlugin_addSub[31] : (execute_SRC_LESS_UNSIGNED ? execute_SRC2[31] : execute_SRC1[31])); + assign _zz_31_ = execute_SrcPlugin_addSub; + assign _zz_30_ = execute_SrcPlugin_addSub; + assign _zz_29_ = execute_SrcPlugin_less; + assign execute_LightShifterPlugin_isShift = (execute_SHIFT_CTRL != `ShiftCtrlEnum_defaultEncoding_DISABLE_1); + assign execute_LightShifterPlugin_amplitude = (execute_LightShifterPlugin_isActive ? execute_LightShifterPlugin_amplitudeReg : execute_SRC2[4 : 0]); + assign execute_LightShifterPlugin_shiftInput = (execute_LightShifterPlugin_isActive ? execute_LightShifterPlugin_shiftReg : execute_SRC1); + assign execute_LightShifterPlugin_done = (execute_LightShifterPlugin_amplitude[4 : 1] == (4'b0000)); + always @ (*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_SLL_1 : begin + _zz_107_ = (execute_LightShifterPlugin_shiftInput <<< 1); + end + default : begin + _zz_107_ = _zz_189_; + end + endcase + end + + assign execute_BranchPlugin_eq = (execute_SRC1 == execute_SRC2); + assign _zz_108_ = execute_INSTRUCTION[14 : 12]; + always @ (*) begin + if((_zz_108_ == (3'b000))) begin + _zz_109_ = execute_BranchPlugin_eq; + end else if((_zz_108_ == (3'b001))) begin + _zz_109_ = (! execute_BranchPlugin_eq); + end else if((((_zz_108_ & (3'b101)) == (3'b101)))) begin + _zz_109_ = (! execute_SRC_LESS); + end else begin + _zz_109_ = execute_SRC_LESS; + end + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : begin + _zz_110_ = 1'b0; + end + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_110_ = 1'b1; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_110_ = 1'b1; + end + default : begin + _zz_110_ = _zz_109_; + end + endcase + end + + assign _zz_27_ = _zz_110_; + assign execute_BranchPlugin_branch_src1 = ((execute_BRANCH_CTRL == `BranchCtrlEnum_defaultEncoding_JALR) ? execute_RS1 : execute_PC); + assign _zz_111_ = _zz_191_[19]; + always @ (*) begin + _zz_112_[10] = _zz_111_; + _zz_112_[9] = _zz_111_; + _zz_112_[8] = _zz_111_; + _zz_112_[7] = _zz_111_; + _zz_112_[6] = _zz_111_; + _zz_112_[5] = _zz_111_; + _zz_112_[4] = _zz_111_; + _zz_112_[3] = _zz_111_; + _zz_112_[2] = _zz_111_; + _zz_112_[1] = _zz_111_; + _zz_112_[0] = _zz_111_; + end + + assign _zz_113_ = _zz_192_[11]; + always @ (*) begin + _zz_114_[19] = _zz_113_; + _zz_114_[18] = _zz_113_; + _zz_114_[17] = _zz_113_; + _zz_114_[16] = _zz_113_; + _zz_114_[15] = _zz_113_; + _zz_114_[14] = _zz_113_; + _zz_114_[13] = _zz_113_; + _zz_114_[12] = _zz_113_; + _zz_114_[11] = _zz_113_; + _zz_114_[10] = _zz_113_; + _zz_114_[9] = _zz_113_; + _zz_114_[8] = _zz_113_; + _zz_114_[7] = _zz_113_; + _zz_114_[6] = _zz_113_; + _zz_114_[5] = _zz_113_; + _zz_114_[4] = _zz_113_; + _zz_114_[3] = _zz_113_; + _zz_114_[2] = _zz_113_; + _zz_114_[1] = _zz_113_; + _zz_114_[0] = _zz_113_; + end + + assign _zz_115_ = _zz_193_[11]; + always @ (*) begin + _zz_116_[18] = _zz_115_; + _zz_116_[17] = _zz_115_; + _zz_116_[16] = _zz_115_; + _zz_116_[15] = _zz_115_; + _zz_116_[14] = _zz_115_; + _zz_116_[13] = _zz_115_; + _zz_116_[12] = _zz_115_; + _zz_116_[11] = _zz_115_; + _zz_116_[10] = _zz_115_; + _zz_116_[9] = _zz_115_; + _zz_116_[8] = _zz_115_; + _zz_116_[7] = _zz_115_; + _zz_116_[6] = _zz_115_; + _zz_116_[5] = _zz_115_; + _zz_116_[4] = _zz_115_; + _zz_116_[3] = _zz_115_; + _zz_116_[2] = _zz_115_; + _zz_116_[1] = _zz_115_; + _zz_116_[0] = _zz_115_; + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_117_ = {{_zz_112_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}},1'b0}; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_117_ = {_zz_114_,execute_INSTRUCTION[31 : 20]}; + end + default : begin + _zz_117_ = {{_zz_116_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}},1'b0}; + end + endcase + end + + assign execute_BranchPlugin_branch_src2 = _zz_117_; + assign execute_BranchPlugin_branchAdder = (execute_BranchPlugin_branch_src1 + execute_BranchPlugin_branch_src2); + assign _zz_25_ = {execute_BranchPlugin_branchAdder[31 : 1],(1'b0)}; + assign BranchPlugin_jumpInterface_valid = ((execute_arbitration_isValid && (! execute_arbitration_isStuckByOthers)) && execute_BRANCH_DO); + assign BranchPlugin_jumpInterface_payload = execute_BRANCH_CALC; + always @ (*) begin + BranchPlugin_branchExceptionPort_valid = ((execute_arbitration_isValid && execute_BRANCH_DO) && BranchPlugin_jumpInterface_payload[1]); + if(1'b0)begin + BranchPlugin_branchExceptionPort_valid = 1'b0; + end + end + + assign BranchPlugin_branchExceptionPort_payload_code = (4'b0000); + assign BranchPlugin_branchExceptionPort_payload_badAddr = BranchPlugin_jumpInterface_payload; + always @ (*) begin + CsrPlugin_privilege = (2'b11); + if(CsrPlugin_forceMachineWire)begin + CsrPlugin_privilege = (2'b11); + end + end + + assign CsrPlugin_misa_base = (2'b01); + assign CsrPlugin_misa_extensions = (26'b00000000000000000000000000); + assign CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilegeUncapped = (2'b11); + assign CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilege = ((CsrPlugin_privilege < CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilegeUncapped) ? CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilegeUncapped : CsrPlugin_privilege); + assign _zz_118_ = {decodeExceptionPort_valid,IBusCachedPlugin_decodeExceptionPort_valid}; + assign _zz_119_ = _zz_194_[0]; + assign _zz_120_ = {CsrPlugin_selfException_valid,{BranchPlugin_branchExceptionPort_valid,DBusSimplePlugin_memoryExceptionPort_valid}}; + assign _zz_121_ = (_zz_120_ & (~ _zz_196_)); + assign _zz_122_ = _zz_121_[1]; + assign _zz_123_ = _zz_121_[2]; + assign _zz_124_ = {_zz_123_,_zz_122_}; + always @ (*) begin + CsrPlugin_exceptionPortCtrl_exceptionValids_decode = CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode; + if(_zz_155_)begin + CsrPlugin_exceptionPortCtrl_exceptionValids_decode = 1'b1; + end + if(decode_arbitration_isFlushed)begin + CsrPlugin_exceptionPortCtrl_exceptionValids_decode = 1'b0; + end + end + + assign CsrPlugin_exceptionPendings_0 = CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode; + assign CsrPlugin_exceptionPendings_1 = CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute; + always @ (*) begin + CsrPlugin_interrupt = 1'b0; + CsrPlugin_interruptCode = (4'bxxxx); + CsrPlugin_interruptTargetPrivilege = (2'bxx); + if((CsrPlugin_mstatus_MIE || (CsrPlugin_privilege < (2'b11))))begin + if((((CsrPlugin_mip_MTIP && CsrPlugin_mie_MTIE) && 1'b1) && (! 1'b0)))begin + CsrPlugin_interrupt = 1'b1; + CsrPlugin_interruptCode = (4'b0111); + CsrPlugin_interruptTargetPrivilege = (2'b11); + end + if((((CsrPlugin_mip_MSIP && CsrPlugin_mie_MSIE) && 1'b1) && (! 1'b0)))begin + CsrPlugin_interrupt = 1'b1; + CsrPlugin_interruptCode = (4'b0011); + CsrPlugin_interruptTargetPrivilege = (2'b11); + end + if((((CsrPlugin_mip_MEIP && CsrPlugin_mie_MEIE) && 1'b1) && (! 1'b0)))begin + CsrPlugin_interrupt = 1'b1; + CsrPlugin_interruptCode = (4'b1011); + CsrPlugin_interruptTargetPrivilege = (2'b11); + end + end + if((! CsrPlugin_allowInterrupts))begin + CsrPlugin_interrupt = 1'b0; + end + end + + assign CsrPlugin_exception = (CsrPlugin_exceptionPortCtrl_exceptionValids_execute && CsrPlugin_allowException); + assign CsrPlugin_lastStageWasWfi = 1'b0; + always @ (*) begin + CsrPlugin_pipelineLiberator_done = ((! (execute_arbitration_isValid != (1'b0))) && IBusCachedPlugin_pcValids_1); + if((CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute != (1'b0)))begin + CsrPlugin_pipelineLiberator_done = 1'b0; + end + if(CsrPlugin_hadException)begin + CsrPlugin_pipelineLiberator_done = 1'b0; + end + end + + assign CsrPlugin_interruptJump = (CsrPlugin_interrupt && CsrPlugin_pipelineLiberator_done); + always @ (*) begin + CsrPlugin_targetPrivilege = CsrPlugin_interruptTargetPrivilege; + if(CsrPlugin_hadException)begin + CsrPlugin_targetPrivilege = CsrPlugin_exceptionPortCtrl_exceptionTargetPrivilege; + end + end + + always @ (*) begin + CsrPlugin_trapCause = CsrPlugin_interruptCode; + if(CsrPlugin_hadException)begin + CsrPlugin_trapCause = CsrPlugin_exceptionPortCtrl_exceptionContext_code; + end + end + + always @ (*) begin + CsrPlugin_xtvec_mode = (2'bxx); + CsrPlugin_xtvec_base = (30'bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_xtvec_mode = CsrPlugin_mtvec_mode; + CsrPlugin_xtvec_base = CsrPlugin_mtvec_base; + end + default : begin + end + endcase + end + + assign contextSwitching = CsrPlugin_jumpInterface_valid; + assign _zz_23_ = (! (((decode_INSTRUCTION[14 : 13] == (2'b01)) && (decode_INSTRUCTION[19 : 15] == (5'b00000))) || ((decode_INSTRUCTION[14 : 13] == (2'b11)) && (decode_INSTRUCTION[19 : 15] == (5'b00000))))); + assign _zz_22_ = (decode_INSTRUCTION[13 : 7] != (7'b0100000)); + assign execute_CsrPlugin_inWfi = 1'b0; + assign execute_CsrPlugin_blockedBySideEffects = 1'b0; + always @ (*) begin + execute_CsrPlugin_illegalAccess = 1'b1; + execute_CsrPlugin_readData = (32'b00000000000000000000000000000000); + case(execute_CsrPlugin_csrAddress) + 12'b101111000000 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[31 : 0] = _zz_125_; + end + 12'b001100000000 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[12 : 11] = CsrPlugin_mstatus_MPP; + execute_CsrPlugin_readData[7 : 7] = CsrPlugin_mstatus_MPIE; + execute_CsrPlugin_readData[3 : 3] = CsrPlugin_mstatus_MIE; + end + 12'b001101000001 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[31 : 0] = CsrPlugin_mepc; + end + 12'b001100000101 : begin + if(execute_CSR_WRITE_OPCODE)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + end + 12'b001101000100 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[11 : 11] = CsrPlugin_mip_MEIP; + execute_CsrPlugin_readData[7 : 7] = CsrPlugin_mip_MTIP; + execute_CsrPlugin_readData[3 : 3] = CsrPlugin_mip_MSIP; + end + 12'b001101000011 : begin + if(execute_CSR_READ_OPCODE)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + execute_CsrPlugin_readData[31 : 0] = CsrPlugin_mtval; + end + 12'b111111000000 : begin + if(execute_CSR_READ_OPCODE)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + execute_CsrPlugin_readData[31 : 0] = _zz_126_; + end + 12'b001101000000 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[31 : 0] = CsrPlugin_mscratch; + end + 12'b001100000100 : begin + execute_CsrPlugin_illegalAccess = 1'b0; + execute_CsrPlugin_readData[11 : 11] = CsrPlugin_mie_MEIE; + execute_CsrPlugin_readData[7 : 7] = CsrPlugin_mie_MTIE; + execute_CsrPlugin_readData[3 : 3] = CsrPlugin_mie_MSIE; + end + 12'b001101000010 : begin + if(execute_CSR_READ_OPCODE)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + execute_CsrPlugin_readData[31 : 31] = CsrPlugin_mcause_interrupt; + execute_CsrPlugin_readData[3 : 0] = CsrPlugin_mcause_exceptionCode; + end + default : begin + end + endcase + if((CsrPlugin_privilege < execute_CsrPlugin_csrAddress[9 : 8]))begin + execute_CsrPlugin_illegalAccess = 1'b1; + end + if(((! execute_arbitration_isValid) || (! execute_IS_CSR)))begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + end + + always @ (*) begin + execute_CsrPlugin_illegalInstruction = 1'b0; + if((execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)))begin + if((CsrPlugin_privilege < execute_INSTRUCTION[29 : 28]))begin + execute_CsrPlugin_illegalInstruction = 1'b1; + end + end + end + + always @ (*) begin + CsrPlugin_selfException_valid = 1'b0; + CsrPlugin_selfException_payload_code = (4'bxxxx); + if((execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_ECALL)))begin + CsrPlugin_selfException_valid = 1'b1; + case(CsrPlugin_privilege) + 2'b00 : begin + CsrPlugin_selfException_payload_code = (4'b1000); + end + default : begin + CsrPlugin_selfException_payload_code = (4'b1011); + end + endcase + end + if((execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_EBREAK)))begin + CsrPlugin_selfException_valid = 1'b1; + CsrPlugin_selfException_payload_code = (4'b0011); + end + end + + assign CsrPlugin_selfException_payload_badAddr = execute_INSTRUCTION; + assign execute_CsrPlugin_writeInstruction = ((execute_arbitration_isValid && execute_IS_CSR) && execute_CSR_WRITE_OPCODE); + assign execute_CsrPlugin_readInstruction = ((execute_arbitration_isValid && execute_IS_CSR) && execute_CSR_READ_OPCODE); + assign execute_CsrPlugin_writeEnable = ((execute_CsrPlugin_writeInstruction && (! execute_CsrPlugin_blockedBySideEffects)) && (! execute_arbitration_isStuckByOthers)); + assign execute_CsrPlugin_readEnable = ((execute_CsrPlugin_readInstruction && (! execute_CsrPlugin_blockedBySideEffects)) && (! execute_arbitration_isStuckByOthers)); + assign execute_CsrPlugin_readToWriteData = execute_CsrPlugin_readData; + always @ (*) begin + case(_zz_164_) + 1'b0 : begin + execute_CsrPlugin_writeData = execute_SRC1; + end + default : begin + execute_CsrPlugin_writeData = (execute_INSTRUCTION[12] ? (execute_CsrPlugin_readToWriteData & (~ execute_SRC1)) : (execute_CsrPlugin_readToWriteData | execute_SRC1)); + end + endcase + end + + assign execute_CsrPlugin_csrAddress = execute_INSTRUCTION[31 : 20]; + assign _zz_126_ = (_zz_125_ & externalInterruptArray_regNext); + assign externalInterrupt = (_zz_126_ != (32'b00000000000000000000000000000000)); + assign _zz_21_ = decode_ALU_BITWISE_CTRL; + assign _zz_19_ = _zz_45_; + assign _zz_39_ = decode_to_execute_ALU_BITWISE_CTRL; + assign _zz_18_ = decode_SHIFT_CTRL; + assign _zz_16_ = _zz_56_; + assign _zz_28_ = decode_to_execute_SHIFT_CTRL; + assign _zz_15_ = decode_BRANCH_CTRL; + assign _zz_13_ = _zz_51_; + assign _zz_26_ = decode_to_execute_BRANCH_CTRL; + assign _zz_12_ = decode_ALU_CTRL; + assign _zz_10_ = _zz_53_; + assign _zz_37_ = decode_to_execute_ALU_CTRL; + assign _zz_9_ = decode_SRC1_CTRL; + assign _zz_7_ = _zz_50_; + assign _zz_34_ = decode_to_execute_SRC1_CTRL; + assign _zz_6_ = decode_SRC2_CTRL; + assign _zz_4_ = _zz_55_; + assign _zz_32_ = decode_to_execute_SRC2_CTRL; + assign _zz_3_ = decode_ENV_CTRL; + assign _zz_1_ = _zz_52_; + assign _zz_24_ = decode_to_execute_ENV_CTRL; + assign decode_arbitration_isFlushed = ({execute_arbitration_flushAll,decode_arbitration_flushAll} != (2'b00)); + assign execute_arbitration_isFlushed = (execute_arbitration_flushAll != (1'b0)); + assign decode_arbitration_isStuckByOthers = (decode_arbitration_haltByOther || (1'b0 || execute_arbitration_isStuck)); + assign decode_arbitration_isStuck = (decode_arbitration_haltItself || decode_arbitration_isStuckByOthers); + assign decode_arbitration_isMoving = ((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)); + assign decode_arbitration_isFiring = ((decode_arbitration_isValid && (! decode_arbitration_isStuck)) && (! decode_arbitration_removeIt)); + assign execute_arbitration_isStuckByOthers = (execute_arbitration_haltByOther || 1'b0); + assign execute_arbitration_isStuck = (execute_arbitration_haltItself || execute_arbitration_isStuckByOthers); + assign execute_arbitration_isMoving = ((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)); + assign execute_arbitration_isFiring = ((execute_arbitration_isValid && (! execute_arbitration_isStuck)) && (! execute_arbitration_removeIt)); + assign iBusWishbone_ADR = {_zz_203_,_zz_127_}; + assign iBusWishbone_CTI = ((_zz_127_ == (3'b111)) ? (3'b111) : (3'b010)); + assign iBusWishbone_BTE = (2'b00); + assign iBusWishbone_SEL = (4'b1111); + assign iBusWishbone_WE = 1'b0; + assign iBusWishbone_DAT_MOSI = (32'bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); + always @ (*) begin + iBusWishbone_CYC = 1'b0; + iBusWishbone_STB = 1'b0; + if(_zz_161_)begin + iBusWishbone_CYC = 1'b1; + iBusWishbone_STB = 1'b1; + end + end + + assign iBus_cmd_ready = (iBus_cmd_valid && iBusWishbone_ACK); + assign iBus_rsp_valid = _zz_128_; + assign iBus_rsp_payload_data = iBusWishbone_DAT_MISO_regNext; + assign iBus_rsp_payload_error = 1'b0; + assign dBus_cmd_halfPipe_valid = dBus_cmd_halfPipe_regs_valid; + assign dBus_cmd_halfPipe_payload_wr = dBus_cmd_halfPipe_regs_payload_wr; + assign dBus_cmd_halfPipe_payload_address = dBus_cmd_halfPipe_regs_payload_address; + assign dBus_cmd_halfPipe_payload_data = dBus_cmd_halfPipe_regs_payload_data; + assign dBus_cmd_halfPipe_payload_size = dBus_cmd_halfPipe_regs_payload_size; + assign dBus_cmd_ready = dBus_cmd_halfPipe_regs_ready; + assign dBusWishbone_ADR = (dBus_cmd_halfPipe_payload_address >>> 2); + assign dBusWishbone_CTI = (3'b000); + assign dBusWishbone_BTE = (2'b00); + always @ (*) begin + case(dBus_cmd_halfPipe_payload_size) + 2'b00 : begin + _zz_129_ = (4'b0001); + end + 2'b01 : begin + _zz_129_ = (4'b0011); + end + default : begin + _zz_129_ = (4'b1111); + end + endcase + end + + always @ (*) begin + dBusWishbone_SEL = _zz_204_[3:0]; + if((! dBus_cmd_halfPipe_payload_wr))begin + dBusWishbone_SEL = (4'b1111); + end + end + + assign dBusWishbone_WE = dBus_cmd_halfPipe_payload_wr; + assign dBusWishbone_DAT_MOSI = dBus_cmd_halfPipe_payload_data; + assign dBus_cmd_halfPipe_ready = (dBus_cmd_halfPipe_valid && dBusWishbone_ACK); + assign dBusWishbone_CYC = dBus_cmd_halfPipe_valid; + assign dBusWishbone_STB = dBus_cmd_halfPipe_valid; + assign dBus_rsp_ready = ((dBus_cmd_halfPipe_valid && (! dBusWishbone_WE)) && dBusWishbone_ACK); + assign dBus_rsp_data = dBusWishbone_DAT_MISO; + assign dBus_rsp_error = 1'b0; + always @ (posedge clk) begin + if(reset) begin + IBusCachedPlugin_fetchPc_pcReg <= externalResetVector; + IBusCachedPlugin_fetchPc_inc <= 1'b0; + _zz_75_ <= 1'b0; + _zz_80_ <= 1'b0; + IBusCachedPlugin_injector_nextPcCalc_valids_0 <= 1'b0; + IBusCachedPlugin_injector_nextPcCalc_valids_1 <= 1'b0; + IBusCachedPlugin_injector_decodeRemoved <= 1'b0; + execute_DBusSimplePlugin_cmdSent <= 1'b0; + execute_LightShifterPlugin_isActive <= 1'b0; + CsrPlugin_mstatus_MIE <= 1'b0; + CsrPlugin_mstatus_MPIE <= 1'b0; + CsrPlugin_mstatus_MPP <= (2'b11); + CsrPlugin_mie_MEIE <= 1'b0; + CsrPlugin_mie_MTIE <= 1'b0; + CsrPlugin_mie_MSIE <= 1'b0; + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode <= 1'b0; + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute <= 1'b0; + CsrPlugin_hadException <= 1'b0; + _zz_125_ <= (32'b00000000000000000000000000000000); + execute_arbitration_isValid <= 1'b0; + _zz_127_ <= (3'b000); + _zz_128_ <= 1'b0; + dBus_cmd_halfPipe_regs_valid <= 1'b0; + dBus_cmd_halfPipe_regs_ready <= 1'b1; + end else begin + if(IBusCachedPlugin_fetchPc_propagatePc)begin + IBusCachedPlugin_fetchPc_inc <= 1'b0; + end + if(IBusCachedPlugin_jump_pcLoad_valid)begin + IBusCachedPlugin_fetchPc_inc <= 1'b0; + end + if(_zz_160_)begin + IBusCachedPlugin_fetchPc_inc <= 1'b1; + end + if(IBusCachedPlugin_fetchPc_samplePcNext)begin + IBusCachedPlugin_fetchPc_pcReg <= IBusCachedPlugin_fetchPc_pc; + end + _zz_75_ <= 1'b1; + if((IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt))begin + _zz_80_ <= 1'b0; + end + if(_zz_78_)begin + _zz_80_ <= IBusCachedPlugin_iBusRsp_stages_0_output_valid; + end + if((IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt))begin + IBusCachedPlugin_injector_nextPcCalc_valids_0 <= 1'b0; + end + if((! (! IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready)))begin + IBusCachedPlugin_injector_nextPcCalc_valids_0 <= 1'b1; + end + if((IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt))begin + IBusCachedPlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if((! execute_arbitration_isStuck))begin + IBusCachedPlugin_injector_nextPcCalc_valids_1 <= IBusCachedPlugin_injector_nextPcCalc_valids_0; + end + if((IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt))begin + IBusCachedPlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if(decode_arbitration_removeIt)begin + IBusCachedPlugin_injector_decodeRemoved <= 1'b1; + end + if((IBusCachedPlugin_jump_pcLoad_valid || IBusCachedPlugin_fetcherflushIt))begin + IBusCachedPlugin_injector_decodeRemoved <= 1'b0; + end + if((dBus_cmd_valid && dBus_cmd_ready))begin + execute_DBusSimplePlugin_cmdSent <= 1'b1; + end + if((! execute_arbitration_isStuck))begin + execute_DBusSimplePlugin_cmdSent <= 1'b0; + end + if(_zz_153_)begin + if(_zz_154_)begin + execute_LightShifterPlugin_isActive <= 1'b1; + if(execute_LightShifterPlugin_done)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + end + end + if(execute_arbitration_removeIt)begin + execute_LightShifterPlugin_isActive <= 1'b0; + end + if((! decode_arbitration_isStuck))begin + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode <= 1'b0; + end else begin + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_decode <= CsrPlugin_exceptionPortCtrl_exceptionValids_decode; + end + if((! execute_arbitration_isStuck))begin + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute <= (CsrPlugin_exceptionPortCtrl_exceptionValids_decode && (! decode_arbitration_isStuck)); + end else begin + CsrPlugin_exceptionPortCtrl_exceptionValidsRegs_execute <= 1'b0; + end + CsrPlugin_hadException <= CsrPlugin_exception; + if(_zz_157_)begin + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_mstatus_MIE <= 1'b0; + CsrPlugin_mstatus_MPIE <= CsrPlugin_mstatus_MIE; + CsrPlugin_mstatus_MPP <= CsrPlugin_privilege; + end + default : begin + end + endcase + end + if(_zz_158_)begin + case(_zz_159_) + 2'b11 : begin + CsrPlugin_mstatus_MPP <= (2'b00); + CsrPlugin_mstatus_MIE <= CsrPlugin_mstatus_MPIE; + CsrPlugin_mstatus_MPIE <= 1'b1; + end + default : begin + end + endcase + end + if(((! execute_arbitration_isStuck) || execute_arbitration_removeIt))begin + execute_arbitration_isValid <= 1'b0; + end + if(((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)))begin + execute_arbitration_isValid <= decode_arbitration_isValid; + end + case(execute_CsrPlugin_csrAddress) + 12'b101111000000 : begin + if(execute_CsrPlugin_writeEnable)begin + _zz_125_ <= execute_CsrPlugin_writeData[31 : 0]; + end + end + 12'b001100000000 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mstatus_MPP <= execute_CsrPlugin_writeData[12 : 11]; + CsrPlugin_mstatus_MPIE <= _zz_197_[0]; + CsrPlugin_mstatus_MIE <= _zz_198_[0]; + end + end + 12'b001101000001 : begin + end + 12'b001100000101 : begin + end + 12'b001101000100 : begin + end + 12'b001101000011 : begin + end + 12'b111111000000 : begin + end + 12'b001101000000 : begin + end + 12'b001100000100 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mie_MEIE <= _zz_200_[0]; + CsrPlugin_mie_MTIE <= _zz_201_[0]; + CsrPlugin_mie_MSIE <= _zz_202_[0]; + end + end + 12'b001101000010 : begin + end + default : begin + end + endcase + if(_zz_161_)begin + if(iBusWishbone_ACK)begin + _zz_127_ <= (_zz_127_ + (3'b001)); + end + end + _zz_128_ <= (iBusWishbone_CYC && iBusWishbone_ACK); + if(_zz_162_)begin + dBus_cmd_halfPipe_regs_valid <= dBus_cmd_valid; + dBus_cmd_halfPipe_regs_ready <= (! dBus_cmd_valid); + end else begin + dBus_cmd_halfPipe_regs_valid <= (! dBus_cmd_halfPipe_ready); + dBus_cmd_halfPipe_regs_ready <= dBus_cmd_halfPipe_ready; + end + end + end + + always @ (posedge clk) begin + if(IBusCachedPlugin_iBusRsp_cacheRspArbitration_input_ready)begin + IBusCachedPlugin_s1_tightlyCoupledHit <= IBusCachedPlugin_s0_tightlyCoupledHit; + end + if((! execute_arbitration_isStuckByOthers))begin + execute_LightShifterPlugin_shiftReg <= _zz_59_; + end + if(_zz_153_)begin + if(_zz_154_)begin + execute_LightShifterPlugin_amplitudeReg <= (execute_LightShifterPlugin_amplitude - (5'b00001)); + end + end + CsrPlugin_mip_MEIP <= externalInterrupt; + CsrPlugin_mip_MTIP <= timerInterrupt; + CsrPlugin_mip_MSIP <= softwareInterrupt; + CsrPlugin_mcycle <= (CsrPlugin_mcycle + (64'b0000000000000000000000000000000000000000000000000000000000000001)); + if(execute_arbitration_isFiring)begin + CsrPlugin_minstret <= (CsrPlugin_minstret + (64'b0000000000000000000000000000000000000000000000000000000000000001)); + end + if(_zz_155_)begin + CsrPlugin_exceptionPortCtrl_exceptionContext_code <= (_zz_119_ ? IBusCachedPlugin_decodeExceptionPort_payload_code : decodeExceptionPort_payload_code); + CsrPlugin_exceptionPortCtrl_exceptionContext_badAddr <= (_zz_119_ ? IBusCachedPlugin_decodeExceptionPort_payload_badAddr : decodeExceptionPort_payload_badAddr); + end + if(_zz_156_)begin + CsrPlugin_exceptionPortCtrl_exceptionContext_code <= _zz_151_; + CsrPlugin_exceptionPortCtrl_exceptionContext_badAddr <= _zz_152_; + end + if(_zz_157_)begin + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_mcause_interrupt <= (! CsrPlugin_hadException); + CsrPlugin_mcause_exceptionCode <= CsrPlugin_trapCause; + CsrPlugin_mepc <= execute_PC; + if(CsrPlugin_hadException)begin + CsrPlugin_mtval <= CsrPlugin_exceptionPortCtrl_exceptionContext_badAddr; + end + end + default : begin + end + endcase + end + externalInterruptArray_regNext <= externalInterruptArray; + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_BITWISE_CTRL <= _zz_20_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SHIFT_CTRL <= _zz_17_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BRANCH_CTRL <= _zz_14_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_STORE <= decode_MEMORY_STORE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_FORCE_ZERO <= decode_SRC2_FORCE_ZERO; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_CTRL <= _zz_11_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_USE_SUB_LESS <= decode_SRC_USE_SUB_LESS; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_REGFILE_WRITE_VALID <= decode_REGFILE_WRITE_VALID; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_CSR_READ_OPCODE <= decode_CSR_READ_OPCODE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC1_CTRL <= _zz_8_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_ENABLE <= decode_MEMORY_ENABLE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_CSR <= decode_IS_CSR; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_CTRL <= _zz_5_; + end + if(((! execute_arbitration_isStuck) && (! CsrPlugin_exceptionPortCtrl_exceptionValids_execute)))begin + decode_to_execute_PC <= decode_PC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_INSTRUCTION <= decode_INSTRUCTION; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_FORMAL_PC_NEXT <= _zz_66_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ENV_CTRL <= _zz_2_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_LESS_UNSIGNED <= decode_SRC_LESS_UNSIGNED; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_CSR_WRITE_OPCODE <= decode_CSR_WRITE_OPCODE; + end + case(execute_CsrPlugin_csrAddress) + 12'b101111000000 : begin + end + 12'b001100000000 : begin + end + 12'b001101000001 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mepc <= execute_CsrPlugin_writeData[31 : 0]; + end + end + 12'b001100000101 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mtvec_base <= execute_CsrPlugin_writeData[31 : 2]; + CsrPlugin_mtvec_mode <= execute_CsrPlugin_writeData[1 : 0]; + end + end + 12'b001101000100 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mip_MSIP <= _zz_199_[0]; + end + end + 12'b001101000011 : begin + end + 12'b111111000000 : begin + end + 12'b001101000000 : begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mscratch <= execute_CsrPlugin_writeData[31 : 0]; + end + end + 12'b001100000100 : begin + end + 12'b001101000010 : begin + end + default : begin + end + endcase + iBusWishbone_DAT_MISO_regNext <= iBusWishbone_DAT_MISO; + if(_zz_162_)begin + dBus_cmd_halfPipe_regs_payload_wr <= dBus_cmd_payload_wr; + dBus_cmd_halfPipe_regs_payload_address <= dBus_cmd_payload_address; + dBus_cmd_halfPipe_regs_payload_data <= dBus_cmd_payload_data; + dBus_cmd_halfPipe_regs_payload_size <= dBus_cmd_payload_size; + end + end + +endmodule + diff --git a/im-tomu_fomu-workshop/litex/rtl/spimemio.v b/im-tomu_fomu-workshop/litex/rtl/spimemio.v new file mode 100644 index 0000000000000000000000000000000000000000..0bbf532600c009536bb3ed7c1be961862ac7f931 --- /dev/null +++ b/im-tomu_fomu-workshop/litex/rtl/spimemio.v @@ -0,0 +1,579 @@ +/* + * PicoSoC - A simple example SoC using PicoRV32 + * + * Copyright (C) 2017 Clifford Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +module spimemio ( + input clk, resetn, + + input valid, + output ready, + input [23:0] addr, + output reg [31:0] rdata, + + output flash_csb, + output flash_clk, + + output flash_io0_oe, + output flash_io1_oe, + output flash_io2_oe, + output flash_io3_oe, + + output flash_io0_do, + output flash_io1_do, + output flash_io2_do, + output flash_io3_do, + + input flash_io0_di, + input flash_io1_di, + input flash_io2_di, + input flash_io3_di, + + input [3:0] cfgreg_we, + input [31:0] cfgreg_di, + output [31:0] cfgreg_do +); + reg xfer_resetn; + reg din_valid; + wire din_ready; + reg [7:0] din_data; + reg [3:0] din_tag; + reg din_cont; + reg din_qspi; + reg din_ddr; + reg din_rd; + + wire dout_valid; + wire [7:0] dout_data; + wire [3:0] dout_tag; + + reg [23:0] buffer; + + reg [23:0] rd_addr; + reg rd_valid; + reg rd_wait; + reg rd_inc; + + assign ready = valid && (addr == rd_addr) && rd_valid; + wire jump = valid && !ready && (addr != rd_addr+4) && rd_valid; + + reg softreset; + + reg config_en; // cfgreg[31] + reg config_ddr; // cfgreg[22] + reg config_qspi; // cfgreg[21] + reg config_cont; // cfgreg[20] + reg [3:0] config_dummy; // cfgreg[19:16] + reg [3:0] config_oe; // cfgreg[11:8] + reg config_csb; // cfgreg[5] + reg config_clk; // cfgref[4] + reg [3:0] config_do; // cfgreg[3:0] + + assign cfgreg_do[31] = config_en; + assign cfgreg_do[30:23] = 0; + assign cfgreg_do[22] = config_ddr; + assign cfgreg_do[21] = config_qspi; + assign cfgreg_do[20] = config_cont; + assign cfgreg_do[19:16] = config_dummy; + assign cfgreg_do[15:12] = 0; + assign cfgreg_do[11:8] = {flash_io3_oe, flash_io2_oe, flash_io1_oe, flash_io0_oe}; + assign cfgreg_do[7:6] = 0; + assign cfgreg_do[5] = flash_csb; + assign cfgreg_do[4] = flash_clk; + assign cfgreg_do[3:0] = {flash_io3_di, flash_io2_di, flash_io1_di, flash_io0_di}; + + always @(posedge clk) begin + softreset <= !config_en || cfgreg_we; + if (!resetn) begin + softreset <= 1; + config_en <= 1; + config_csb <= 0; + config_clk <= 0; + config_oe <= 0; + config_do <= 0; + config_ddr <= 0; + config_qspi <= 0; + config_cont <= 0; + config_dummy <= 8; + end else begin + if (cfgreg_we[0]) begin + config_csb <= cfgreg_di[5]; + config_clk <= cfgreg_di[4]; + config_do <= cfgreg_di[3:0]; + end + if (cfgreg_we[1]) begin + config_oe <= cfgreg_di[11:8]; + end + if (cfgreg_we[2]) begin + config_ddr <= cfgreg_di[22]; + config_qspi <= cfgreg_di[21]; + config_cont <= cfgreg_di[20]; + config_dummy <= cfgreg_di[19:16]; + end + if (cfgreg_we[3]) begin + config_en <= cfgreg_di[31]; + end + end + end + + wire xfer_csb; + wire xfer_clk; + + wire xfer_io0_oe; + wire xfer_io1_oe; + wire xfer_io2_oe; + wire xfer_io3_oe; + + wire xfer_io0_do; + wire xfer_io1_do; + wire xfer_io2_do; + wire xfer_io3_do; + + reg xfer_io0_90; + reg xfer_io1_90; + reg xfer_io2_90; + reg xfer_io3_90; + + always @(negedge clk) begin + xfer_io0_90 <= xfer_io0_do; + xfer_io1_90 <= xfer_io1_do; + xfer_io2_90 <= xfer_io2_do; + xfer_io3_90 <= xfer_io3_do; + end + + assign flash_csb = config_en ? xfer_csb : config_csb; + assign flash_clk = config_en ? xfer_clk : config_clk; + + assign flash_io0_oe = config_en ? xfer_io0_oe : config_oe[0]; + assign flash_io1_oe = config_en ? xfer_io1_oe : config_oe[1]; + assign flash_io2_oe = config_en ? xfer_io2_oe : config_oe[2]; + assign flash_io3_oe = config_en ? xfer_io3_oe : config_oe[3]; + + assign flash_io0_do = config_en ? (config_ddr ? xfer_io0_90 : xfer_io0_do) : config_do[0]; + assign flash_io1_do = config_en ? (config_ddr ? xfer_io1_90 : xfer_io1_do) : config_do[1]; + assign flash_io2_do = config_en ? (config_ddr ? xfer_io2_90 : xfer_io2_do) : config_do[2]; + assign flash_io3_do = config_en ? (config_ddr ? xfer_io3_90 : xfer_io3_do) : config_do[3]; + + wire xfer_dspi = din_ddr && !din_qspi; + wire xfer_ddr = din_ddr && din_qspi; + + spimemio_xfer xfer ( + .clk (clk ), + .resetn (xfer_resetn ), + .din_valid (din_valid ), + .din_ready (din_ready ), + .din_data (din_data ), + .din_tag (din_tag ), + .din_cont (din_cont ), + .din_dspi (xfer_dspi ), + .din_qspi (din_qspi ), + .din_ddr (xfer_ddr ), + .din_rd (din_rd ), + .dout_valid (dout_valid ), + .dout_data (dout_data ), + .dout_tag (dout_tag ), + .flash_csb (xfer_csb ), + .flash_clk (xfer_clk ), + .flash_io0_oe (xfer_io0_oe ), + .flash_io1_oe (xfer_io1_oe ), + .flash_io2_oe (xfer_io2_oe ), + .flash_io3_oe (xfer_io3_oe ), + .flash_io0_do (xfer_io0_do ), + .flash_io1_do (xfer_io1_do ), + .flash_io2_do (xfer_io2_do ), + .flash_io3_do (xfer_io3_do ), + .flash_io0_di (flash_io0_di), + .flash_io1_di (flash_io1_di), + .flash_io2_di (flash_io2_di), + .flash_io3_di (flash_io3_di) + ); + + reg [3:0] state; + + always @(posedge clk) begin + xfer_resetn <= 1; + din_valid <= 0; + + if (!resetn || softreset) begin + state <= 0; + xfer_resetn <= 0; + rd_valid <= 0; + din_tag <= 0; + din_cont <= 0; + din_qspi <= 0; + din_ddr <= 0; + din_rd <= 0; + end else begin + if (dout_valid && dout_tag == 1) buffer[ 7: 0] <= dout_data; + if (dout_valid && dout_tag == 2) buffer[15: 8] <= dout_data; + if (dout_valid && dout_tag == 3) buffer[23:16] <= dout_data; + if (dout_valid && dout_tag == 4) begin + rdata <= {dout_data, buffer}; + rd_addr <= rd_inc ? rd_addr + 4 : addr; + rd_valid <= 1; + rd_wait <= rd_inc; + rd_inc <= 1; + end + + if (valid) + rd_wait <= 0; + + case (state) + 0: begin + din_valid <= 1; + din_data <= 8'h ff; + din_tag <= 0; + if (din_ready) begin + din_valid <= 0; + state <= 1; + end + end + 1: begin + if (dout_valid) begin + xfer_resetn <= 0; + state <= 2; + end + end + 2: begin + din_valid <= 1; + din_data <= 8'h ab; + din_tag <= 0; + if (din_ready) begin + din_valid <= 0; + state <= 3; + end + end + 3: begin + if (dout_valid) begin + xfer_resetn <= 0; + state <= 4; + end + end + 4: begin + rd_inc <= 0; + din_valid <= 1; + din_tag <= 0; + case ({config_ddr, config_qspi}) + 2'b11: din_data <= 8'h ED; + 2'b01: din_data <= 8'h EB; + 2'b10: din_data <= 8'h BB; + 2'b00: din_data <= 8'h 03; + endcase + if (din_ready) begin + din_valid <= 0; + state <= 5; + end + end + 5: begin + if (valid && !ready) begin + din_valid <= 1; + din_tag <= 0; + din_data <= addr[23:16]; + din_qspi <= config_qspi; + din_ddr <= config_ddr; + if (din_ready) begin + din_valid <= 0; + state <= 6; + end + end + end + 6: begin + din_valid <= 1; + din_tag <= 0; + din_data <= addr[15:8]; + if (din_ready) begin + din_valid <= 0; + state <= 7; + end + end + 7: begin + din_valid <= 1; + din_tag <= 0; + din_data <= addr[7:0]; + if (din_ready) begin + din_valid <= 0; + din_data <= 0; + state <= config_qspi || config_ddr ? 8 : 9; + end + end + 8: begin + din_valid <= 1; + din_tag <= 0; + din_data <= config_cont ? 8'h A5 : 8'h FF; + if (din_ready) begin + din_rd <= 1; + din_data <= config_dummy; + din_valid <= 0; + state <= 9; + end + end + 9: begin + din_valid <= 1; + din_tag <= 1; + if (din_ready) begin + din_valid <= 0; + state <= 10; + end + end + 10: begin + din_valid <= 1; + din_data <= 8'h 00; + din_tag <= 2; + if (din_ready) begin + din_valid <= 0; + state <= 11; + end + end + 11: begin + din_valid <= 1; + din_tag <= 3; + if (din_ready) begin + din_valid <= 0; + state <= 12; + end + end + 12: begin + if (!rd_wait || valid) begin + din_valid <= 1; + din_tag <= 4; + if (din_ready) begin + din_valid <= 0; + state <= 9; + end + end + end + endcase + + if (jump) begin + rd_inc <= 0; + rd_valid <= 0; + xfer_resetn <= 0; + if (config_cont) begin + state <= 5; + end else begin + state <= 4; + din_qspi <= 0; + din_ddr <= 0; + end + din_rd <= 0; + end + end + end +endmodule + +module spimemio_xfer ( + input clk, resetn, + + input din_valid, + output din_ready, + input [7:0] din_data, + input [3:0] din_tag, + input din_cont, + input din_dspi, + input din_qspi, + input din_ddr, + input din_rd, + + output dout_valid, + output [7:0] dout_data, + output [3:0] dout_tag, + + output reg flash_csb, + output reg flash_clk, + + output reg flash_io0_oe, + output reg flash_io1_oe, + output reg flash_io2_oe, + output reg flash_io3_oe, + + output reg flash_io0_do, + output reg flash_io1_do, + output reg flash_io2_do, + output reg flash_io3_do, + + input flash_io0_di, + input flash_io1_di, + input flash_io2_di, + input flash_io3_di +); + reg [7:0] obuffer; + reg [7:0] ibuffer; + + reg [3:0] count; + reg [3:0] dummy_count; + + reg xfer_cont; + reg xfer_dspi; + reg xfer_qspi; + reg xfer_ddr; + reg xfer_ddr_q; + reg xfer_rd; + reg [3:0] xfer_tag; + reg [3:0] xfer_tag_q; + + reg [7:0] next_obuffer; + reg [7:0] next_ibuffer; + reg [3:0] next_count; + + reg fetch; + reg next_fetch; + reg last_fetch; + + always @(posedge clk) begin + xfer_ddr_q <= xfer_ddr; + xfer_tag_q <= xfer_tag; + end + + assign din_ready = din_valid && resetn && next_fetch; + + assign dout_valid = (xfer_ddr_q ? fetch && !last_fetch : next_fetch && !fetch) && resetn; + assign dout_data = ibuffer; + assign dout_tag = xfer_tag_q; + + always @* begin + flash_io0_oe = 0; + flash_io1_oe = 0; + flash_io2_oe = 0; + flash_io3_oe = 0; + + flash_io0_do = 0; + flash_io1_do = 0; + flash_io2_do = 0; + flash_io3_do = 0; + + next_obuffer = obuffer; + next_ibuffer = ibuffer; + next_count = count; + next_fetch = 0; + + if (dummy_count == 0) begin + casez ({xfer_ddr, xfer_qspi, xfer_dspi}) + 3'b 000: begin + flash_io0_oe = 1; + flash_io0_do = obuffer[7]; + + if (flash_clk) begin + next_obuffer = {obuffer[6:0], 1'b 0}; + next_count = count - |count; + end else begin + next_ibuffer = {ibuffer[6:0], flash_io1_di}; + end + + next_fetch = (next_count == 0); + end + 3'b 01?: begin + flash_io0_oe = !xfer_rd; + flash_io1_oe = !xfer_rd; + flash_io2_oe = !xfer_rd; + flash_io3_oe = !xfer_rd; + + flash_io0_do = obuffer[4]; + flash_io1_do = obuffer[5]; + flash_io2_do = obuffer[6]; + flash_io3_do = obuffer[7]; + + if (flash_clk) begin + next_obuffer = {obuffer[3:0], 4'b 0000}; + next_count = count - {|count, 2'b00}; + end else begin + next_ibuffer = {ibuffer[3:0], flash_io3_di, flash_io2_di, flash_io1_di, flash_io0_di}; + end + + next_fetch = (next_count == 0); + end + 3'b 11?: begin + flash_io0_oe = !xfer_rd; + flash_io1_oe = !xfer_rd; + flash_io2_oe = !xfer_rd; + flash_io3_oe = !xfer_rd; + + flash_io0_do = obuffer[4]; + flash_io1_do = obuffer[5]; + flash_io2_do = obuffer[6]; + flash_io3_do = obuffer[7]; + + next_obuffer = {obuffer[3:0], 4'b 0000}; + next_ibuffer = {ibuffer[3:0], flash_io3_di, flash_io2_di, flash_io1_di, flash_io0_di}; + next_count = count - {|count, 2'b00}; + + next_fetch = (next_count == 0); + end + 3'b ??1: begin + flash_io0_oe = !xfer_rd; + flash_io1_oe = !xfer_rd; + + flash_io0_do = obuffer[6]; + flash_io1_do = obuffer[7]; + + if (flash_clk) begin + next_obuffer = {obuffer[5:0], 2'b 00}; + next_count = count - {|count, 1'b0}; + end else begin + next_ibuffer = {ibuffer[5:0], flash_io1_di, flash_io0_di}; + end + + next_fetch = (next_count == 0); + end + endcase + end + end + + always @(posedge clk) begin + if (!resetn) begin + fetch <= 1; + last_fetch <= 1; + flash_csb <= 1; + flash_clk <= 0; + count <= 0; + dummy_count <= 0; + xfer_tag <= 0; + xfer_cont <= 0; + xfer_dspi <= 0; + xfer_qspi <= 0; + xfer_ddr <= 0; + xfer_rd <= 0; + end else begin + fetch <= next_fetch; + last_fetch <= xfer_ddr ? fetch : 1; + if (dummy_count) begin + flash_clk <= !flash_clk && !flash_csb; + dummy_count <= dummy_count - flash_clk; + end else + if (count) begin + flash_clk <= !flash_clk && !flash_csb; + obuffer <= next_obuffer; + ibuffer <= next_ibuffer; + count <= next_count; + end + if (din_valid && din_ready) begin + flash_csb <= 0; + flash_clk <= 0; + + count <= 8; + dummy_count <= din_rd ? din_data : 0; + obuffer <= din_data; + + xfer_tag <= din_tag; + xfer_cont <= din_cont; + xfer_dspi <= din_dspi; + xfer_qspi <= din_qspi; + xfer_ddr <= din_ddr; + xfer_rd <= din_rd; + end + end + end +endmodule diff --git a/im-tomu_fomu-workshop/litex/workshop.py b/im-tomu_fomu-workshop/litex/workshop.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf99e6bce3e1c4e8b30795de1ca54ec3fb21f01 --- /dev/null +++ b/im-tomu_fomu-workshop/litex/workshop.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# This variable defines all the external programs that this module +# relies on. lxbuildenv reads this variable in order to ensure +# the build will finish without exiting due to missing third-party +# programs. +LX_DEPENDENCIES = ["icestorm", "yosys", "nextpnr-ice40"] +#LX_CONFIG = "skip-git" # This can be useful for workshops + +# Import lxbuildenv to integrate the deps/ directory +import os,os.path,shutil,sys,subprocess +sys.path.insert(0, os.path.dirname(__file__)) +import lxbuildenv + +# Disable pylint's E1101, which breaks completely on migen +#pylint:disable=E1101 + +from migen import * +from migen.genlib.resetsync import AsyncResetSynchronizer + +from litex.soc.integration.soc_core import SoCCore +from litex.soc.integration.builder import Builder +from litex.soc.interconnect.csr import AutoCSR, CSRStatus, CSRStorage + +from litex_boards.targets.fomu import BaseSoC, add_dfu_suffix + +from valentyusb.usbcore import io as usbio +from valentyusb.usbcore.cpu import dummyusb + +import argparse + +def main(): + parser = argparse.ArgumentParser( + description="Build Fomu Main Gateware") + parser.add_argument( + "--seed", default=0, help="seed to use in nextpnr" + ) + parser.add_argument( + "--placer", default="heap", choices=["sa", "heap"], help="which placer to use in nextpnr" + ) + parser.add_argument( + "--board", choices=["evt", "pvt", "hacker"], required=True, + help="build for a particular hardware board" + ) + args = parser.parse_args() + + soc = BaseSoC(args.board, pnr_seed=args.seed, pnr_placer=args.placer, usb_bridge=True) + + builder = Builder(soc, + output_dir="build", csr_csv="build/csr.csv", + compile_software=False) + vns = builder.build() + soc.do_exit(vns) + add_dfu_suffix(os.path.join('build', 'gateware', 'fomu_{}.bin'.format(args.board))) + + +if __name__ == "__main__": + main() diff --git a/im-tomu_fomu-workshop/litex/workshop_rgb.py b/im-tomu_fomu-workshop/litex/workshop_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..8319262bf7d87b3e6b6bbf2f7f3ede31408dab15 --- /dev/null +++ b/im-tomu_fomu-workshop/litex/workshop_rgb.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# This variable defines all the external programs that this module +# relies on. lxbuildenv reads this variable in order to ensure +# the build will finish without exiting due to missing third-party +# programs. +LX_DEPENDENCIES = ["icestorm", "yosys", "nextpnr-ice40"] +#LX_CONFIG = "skip-git" # This can be useful for workshops + +# Import lxbuildenv to integrate the deps/ directory +import os,os.path,shutil,sys,subprocess +sys.path.insert(0, os.path.dirname(__file__)) +import lxbuildenv + +# Disable pylint's E1101, which breaks completely on migen +#pylint:disable=E1101 + +from migen import * +from migen.genlib.resetsync import AsyncResetSynchronizer + +from litex.soc.integration.soc_core import SoCCore +from litex.soc.integration.builder import Builder +from litex.soc.interconnect.csr import AutoCSR, CSRStatus, CSRStorage + +from litex_boards.targets.fomu import BaseSoC, add_dfu_suffix + +from valentyusb.usbcore import io as usbio +from valentyusb.usbcore.cpu import dummyusb + +import argparse + +class FomuRGB(Module, AutoCSR): + def __init__(self, pads): + self.output = CSRStorage(3) + self.specials += Instance("SB_RGBA_DRV", + i_CURREN = 0b1, + i_RGBLEDEN = 0b1, + i_RGB0PWM = self.output.storage[0], + i_RGB1PWM = self.output.storage[1], + i_RGB2PWM = self.output.storage[2], + o_RGB0 = pads.r, + o_RGB1 = pads.g, + o_RGB2 = pads.b, + p_CURRENT_MODE = "0b1", + p_RGB0_CURRENT = "0b000011", + p_RGB1_CURRENT = "0b000011", + p_RGB2_CURRENT = "0b000011", + ) + +def main(): + parser = argparse.ArgumentParser( + description="Build Fomu Main Gateware") + parser.add_argument( + "--seed", default=0, help="seed to use in nextpnr" + ) + parser.add_argument( + "--placer", default="heap", choices=["sa", "heap"], help="which placer to use in nextpnr" + ) + parser.add_argument( + "--board", choices=["evt", "pvt", "hacker"], required=True, + help="build for a particular hardware board" + ) + args = parser.parse_args() + + soc = BaseSoC(args.board, pnr_seed=args.seed, pnr_placer=args.placer, usb_bridge=True) + + # Add the LED driver block. Get the `rgb_led` pins from the definition + # file, then instantiate the module we defined above. + led_pads = soc.platform.request("rgb_led") + soc.submodules.fomu_rgb = FomuRGB(led_pads) + + # Indicate that `fomu_rgb` is a CSR, and should be added to the bus. + # Otherwise we wouldn't be able to access `fomu_rgb` at all. + # Note that the value here must match the value above, so if you did + # `soc.submodules.frgb = FomuRGB(led_pads)` then you would need to + # change this to `soc.add_csr("frgb")`. + soc.add_csr("fomu_rgb") + + builder = Builder(soc, + output_dir="build", csr_csv="build/csr.csv", + compile_software=False) + vns = builder.build() + soc.do_exit(vns) + add_dfu_suffix(os.path.join('build', 'gateware', 'fomu_{}.bin'.format(args.board))) + + +if __name__ == "__main__": + main() diff --git a/im-tomu_fomu-workshop/migen/blink-expanded.py b/im-tomu_fomu-workshop/migen/blink-expanded.py new file mode 100644 index 0000000000000000000000000000000000000000..bf4de38a15b66cd55743b73f66aba8ac4f9b3b62 --- /dev/null +++ b/im-tomu_fomu-workshop/migen/blink-expanded.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Simple tri-colour LED blink example.""" + +# Import lxbuildenv to integrate the deps/ directory +import os, sys +sys.path.insert(0, os.path.dirname(__file__)) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "litex")) +import lxbuildenv + +from migen import * +from migen.build.generic_platform import * +import fomu + +if 'FOMU_REV' not in os.environ: + print('Board type must be specified in FOMU_REV environment variable!') + exit(1) + +# +# Parameters from iCE40 UltraPlus LED Driver Usage Guide, pages 19-20 +# + +# Current modes +RGBA_CURRENT_MODE_FULL = '0b0' +RGBA_CURRENT_MODE_HALF = '0b1' + +# Current levels in Full / Half mode +RGBA_CURRENT_04MA_02MA = '0b000001' +RGBA_CURRENT_08MA_04MA = '0b000011' +RGBA_CURRENT_12MA_06MA = '0b000111' +RGBA_CURRENT_16MA_08MA = '0b001111' +RGBA_CURRENT_20MA_10MA = '0b011111' +RGBA_CURRENT_24MA_12MA = '0b111111' + +# Type for input pins, from ICE Technology Library Manual, pages 87-90 +SB_IO_TYPE_SIMPLE_INPUT = 0b000001 + +# +# Signals +# +counter = Signal(28) + +rgb0_pwm = Signal(1) +rgb1_pwm = Signal(1) +rgb2_pwm = Signal(1) + +input1 = Signal(1) +input2 = Signal(1) + +# Setup platform and correctly map pins for the +# iCE40UP5K SB_RGBA_DRV hard macro. +if os.environ['FOMU_REV'] in ['evt1', 'evt2']: + platform = fomu.FomuEvt2Platform() + blue_pwm = rgb0_pwm + red_pwm = rgb1_pwm + green_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'evt3': + platform = fomu.FomuEvt3Platform() + blue_pwm = rgb0_pwm + red_pwm = rgb1_pwm + green_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'hacker': + platform = fomu.FomuHackerPlatform() + blue_pwm = rgb0_pwm + green_pwm = rgb1_pwm + red_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'pvt': + platform = fomu.FomuPvtPlatform() + green_pwm = rgb0_pwm + red_pwm = rgb1_pwm + blue_pwm = rgb2_pwm +else: + print('Board not supported!') + exit(2) + +usb_pins = platform.request('usb') +rgb_pins = platform.request('rgb_led') + +touch_pins = [platform.request('user_touch_n', i) for i in range(0, 4)] + +m = Module() + +### + +# Drive the USB outputs to constant values as they are not in use. +# Assign USB pins to "0" so as to disconnect Fomu from +# the host system. Otherwise it would try to talk to +# us over USB, which wouldn't work since we have no stack. +m.comb += [ + usb_pins.d_p.eq(0), + usb_pins.d_n.eq(0), + usb_pins.pullup.eq(0), +] + +# Use touch pins 1+2 to ground pulled-up inputs +m.comb += [ + touch_pins[1].eq(0), + touch_pins[2].eq(0) +] + +# Wire inputs and clock divider to LEDs +m.comb += [ + red_pwm.eq(~input2), + green_pwm.eq(counter[23]), + blue_pwm.eq(~input1) +] + +# Increment counter on clock signal +m.sync += counter.eq(counter + 1) + +# Instantiate iCE40 LED driver hard logic, connecting up +# latched button state, counter state, and LEDs. +# +# Note that it's possible to drive the LEDs directly, +# however that is not current-limited and results in +# overvolting the red LED. +# +# See also: +# https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 +m.specials += Instance( + 'SB_RGBA_DRV', + i_CURREN=0b1, + i_RGBLEDEN=0b1, + i_RGB0PWM=rgb0_pwm, + i_RGB1PWM=rgb1_pwm, + i_RGB2PWM=rgb2_pwm, + o_RGB0=rgb_pins.r, + o_RGB1=rgb_pins.g, + o_RGB2=rgb_pins.b, + p_CURRENT_MODE=RGBA_CURRENT_MODE_HALF, + p_RGB0_CURRENT=RGBA_CURRENT_08MA_04MA, + p_RGB1_CURRENT=RGBA_CURRENT_08MA_04MA, + p_RGB2_CURRENT=RGBA_CURRENT_08MA_04MA +) + +m.specials += Instance( + 'SB_IO', + i_PACKAGE_PIN=touch_pins[0], + i_OUTPUT_ENABLE=0b0, + o_D_IN_0=input1, + p_PIN_TYPE=SB_IO_TYPE_SIMPLE_INPUT, + p_PULLUP=0b1 +) + +m.specials += Instance( + 'SB_IO', + i_PACKAGE_PIN=touch_pins[3], + i_OUTPUT_ENABLE=0b0, + o_D_IN_0=input2, + p_PIN_TYPE=SB_IO_TYPE_SIMPLE_INPUT, + p_PULLUP=0b1 +) + +platform.build(m) diff --git a/im-tomu_fomu-workshop/migen/blink.py b/im-tomu_fomu-workshop/migen/blink.py new file mode 100644 index 0000000000000000000000000000000000000000..2d823ebe90fb5e70aa616bf0224c005840ba5a23 --- /dev/null +++ b/im-tomu_fomu-workshop/migen/blink.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Simple tri-colour LED blink example.""" + +# Import lxbuildenv to integrate the deps/ directory +import os, sys +sys.path.insert(0, os.path.dirname(__file__)) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "litex")) +import lxbuildenv + +from migen import * +import fomu + +if 'FOMU_REV' not in os.environ: + print('Board type must be specified in FOMU_REV environment variable!') + exit(1) + +# +# Parameters from iCE40 UltraPlus LED Driver Usage Guide, pages 19-20 +# + +# Current modes +RGBA_CURRENT_MODE_FULL = '0b0' +RGBA_CURRENT_MODE_HALF = '0b1' + +# Current levels in Full / Half mode +RGBA_CURRENT_04MA_02MA = '0b000001' +RGBA_CURRENT_08MA_04MA = '0b000011' +RGBA_CURRENT_12MA_06MA = '0b000111' +RGBA_CURRENT_16MA_08MA = '0b001111' +RGBA_CURRENT_20MA_10MA = '0b011111' +RGBA_CURRENT_24MA_12MA = '0b111111' + +# +# Signals +# +counter = Signal(28) + +rgb0_pwm = Signal(1) +rgb1_pwm = Signal(1) +rgb2_pwm = Signal(1) + +# Setup platform and correctly map pins for the +# iCE40UP5K SB_RGBA_DRV hard macro. +if os.environ['FOMU_REV'] in ['evt1', 'evt2']: + platform = fomu.FomuEvt2Platform() + blue_pwm = rgb0_pwm + red_pwm = rgb1_pwm + green_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'evt3': + platform = fomu.FomuEvt3Platform() + blue_pwm = rgb0_pwm + red_pwm = rgb1_pwm + green_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'hacker': + platform = fomu.FomuHackerPlatform() + blue_pwm = rgb0_pwm + green_pwm = rgb1_pwm + red_pwm = rgb2_pwm +elif os.environ['FOMU_REV'] == 'pvt': + platform = fomu.FomuPvtPlatform() + green_pwm = rgb0_pwm + red_pwm = rgb1_pwm + blue_pwm = rgb2_pwm +else: + print('Board not supported!') + exit(2) + +usb_pins = platform.request('usb') +rgb_pins = platform.request('rgb_led') + +m = Module() + +### + +# Drive the USB outputs to constant values as they are not in use. +# Assign USB pins to "0" so as to disconnect Fomu from +# the host system. Otherwise it would try to talk to +# us over USB, which wouldn't work since we have no stack. +m.comb += [ + usb_pins.d_p.eq(0), + usb_pins.d_n.eq(0), + usb_pins.pullup.eq(0) +] + +m.comb += [ + red_pwm.eq(counter[24]), + green_pwm.eq(counter[23]), + blue_pwm.eq(counter[25]) +] + +# Increment counter on clock signal +m.sync += counter.eq(counter + 1) + +# Instantiate iCE40 LED driver hard logic, connecting up +# latched button state, counter state, and LEDs. +# +# Note that it's possible to drive the LEDs directly, +# however that is not current-limited and results in +# overvolting the red LED. +# +# See also: +# https://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 +m.specials += Instance( + 'SB_RGBA_DRV', + i_CURREN=0b1, + i_RGBLEDEN=0b1, + i_RGB0PWM=rgb0_pwm, + i_RGB1PWM=rgb1_pwm, + i_RGB2PWM=rgb2_pwm, + o_RGB0=rgb_pins.r, + o_RGB1=rgb_pins.g, + o_RGB2=rgb_pins.b, + p_CURRENT_MODE=RGBA_CURRENT_MODE_HALF, + p_RGB0_CURRENT=RGBA_CURRENT_08MA_04MA, + p_RGB1_CURRENT=RGBA_CURRENT_08MA_04MA, + p_RGB2_CURRENT=RGBA_CURRENT_08MA_04MA +) + +platform.build(m) diff --git a/im-tomu_fomu-workshop/migen/fomu.py b/im-tomu_fomu-workshop/migen/fomu.py new file mode 100644 index 0000000000000000000000000000000000000000..64bf3523958eea12276363a950c64e3247954cc5 --- /dev/null +++ b/im-tomu_fomu-workshop/migen/fomu.py @@ -0,0 +1,141 @@ +""" Fomu board definitions (mapping of I/O pins, clock, etc.) """ + +from migen import * +from migen.build.generic_platform import * +from migen.build.lattice import LatticePlatform + + +class FomuPvtPlatform(LatticePlatform): + """ Based on + https://github.com/litex-hub/litex-boards/blob/master/litex_boards/partner/platforms/fomu_pvt.py """ + + _io = [ + ('clk48', 0, Pins('F4'), IOStandard('LVCMOS33')), + + ('user_led_n', 0, Pins('A5'), IOStandard('LVCMOS33')), + ('rgb_led', 0, + Subsignal('r', Pins('C5')), + Subsignal('g', Pins('B5')), + Subsignal('b', Pins('A5')), + IOStandard('LVCMOS33')), + + ('user_touch_n', 0, Pins('E4'), IOStandard('LVCMOS33')), + ('user_touch_n', 1, Pins('D5'), IOStandard('LVCMOS33')), + ('user_touch_n', 2, Pins('E5'), IOStandard('LVCMOS33')), + ('user_touch_n', 3, Pins('F5'), IOStandard('LVCMOS33')), + + ('usb', 0, + Subsignal('d_p', Pins('A1')), + Subsignal('d_n', Pins('A2')), + Subsignal('pullup', Pins('A4')), + IOStandard('LVCMOS33')) + ] + + _connectors = [ + ('touch_pins', 'E4 D5 E5 F5') + ] + + default_clk_name = 'clk48' + default_clk_period = 1e9 / 48e6 + + def __init__(self): + LatticePlatform.__init__(self, + 'ice40-up5k-uwg30', + self._io, + self._connectors, + toolchain='icestorm') + + def create_programmer(self): + return IceStormProgrammer() + + +class FomuHackerPlatform(LatticePlatform): + """ Based on + https://github.com/litex-hub/litex-boards/blob/master/litex_boards/partner/platforms/fomu_hacker.py """ + + _io = [ + ('clk48', 0, Pins('F5'), IOStandard('LVCMOS33')), + + ('user_led_n', 0, Pins('A5'), IOStandard('LVCMOS33')), + ('rgb_led', 0, + Subsignal('r', Pins('C5')), + Subsignal('g', Pins('B5')), + Subsignal('b', Pins('A5')), + IOStandard('LVCMOS33')), + + ('user_touch_n', 0, Pins('F4'), IOStandard('LVCMOS33')), + ('user_touch_n', 1, Pins('E5'), IOStandard('LVCMOS33')), + ('user_touch_n', 2, Pins('E4'), IOStandard('LVCMOS33')), + ('user_touch_n', 3, Pins('F2'), IOStandard('LVCMOS33')), + + ('usb', 0, + Subsignal('d_p', Pins('A4')), + Subsignal('d_n', Pins('A2')), + Subsignal('pullup', Pins('D5')), + IOStandard('LVCMOS33')) + ] + + _connectors = [ + ('touch_pins', 'F4 E5 E4 F2') + ] + + default_clk_name = 'clk48' + default_clk_period = 1e9 / 48e6 + + def __init__(self): + LatticePlatform.__init__(self, + 'ice40-up5k-uwg30', + self._io, + self._connectors, + toolchain='icestorm') + + def create_programmer(self): + return IceStormProgrammer() + + +class FomuEvt2Platform(LatticePlatform): + """ Based on + https://github.com/litex-hub/litex-boards/blob/master/litex_boards/partner/platforms/fomu_evt.py """ + + _io = [ + ('clk48', 0, Pins('44'), IOStandard('LVCMOS33')), + + ('user_led_n', 0, Pins('41'), IOStandard('LVCMOS33')), + ('rgb_led', 0, + Subsignal('r', Pins('40')), + Subsignal('g', Pins('39')), + Subsignal('b', Pins('41')), + IOStandard('LVCMOS33')), + + ('user_touch_n', 0, Pins('48'), IOStandard('LVCMOS33')), + ('user_touch_n', 1, Pins('47'), IOStandard('LVCMOS33')), + ('user_touch_n', 2, Pins('46'), IOStandard('LVCMOS33')), + ('user_touch_n', 3, Pins('45'), IOStandard('LVCMOS33')), + + ('usb', 0, + Subsignal('d_p', Pins('34')), + Subsignal('d_n', Pins('37')), + Subsignal('pullup', Pins('35')), + Subsignal('pulldown', Pins('36')), + IOStandard('LVCMOS33')) + ] + + _connectors = [ + ('touch_pins', '48 47 46 45') + ] + + default_clk_name = 'clk48' + default_clk_period = 1e9 / 48e6 + + def __init__(self): + LatticePlatform.__init__(self, + 'ice40-up5k-sg48', + self._io, + self._connectors, + toolchain='icestorm') + + def create_programmer(self): + return IceStormProgrammer() + + +FomuEvt3Platform = FomuEvt2Platform diff --git a/im-tomu_fomu-workshop/riscv-blink/include/csr-defs.h b/im-tomu_fomu-workshop/riscv-blink/include/csr-defs.h new file mode 100644 index 0000000000000000000000000000000000000000..d98e8dfb7b09cbbd8ba10f7a0e89bf72e60a4ab7 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/csr-defs.h @@ -0,0 +1,11 @@ +#ifndef CSR_DEFS__H +#define CSR_DEFS__H + +#define CSR_MSTATUS_MIE 0x8 + +#define CSR_IRQ_MASK 0xBC0 +#define CSR_IRQ_PENDING 0xFC0 + +#define CSR_DCACHE_INFO 0xCC0 + +#endif /* CSR_DEFS__H */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/generated/csr.h b/im-tomu_fomu-workshop/riscv-blink/include/generated/csr.h new file mode 100644 index 0000000000000000000000000000000000000000..c18b1022f1846b31db04fbdfab53ac92583688bc --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/generated/csr.h @@ -0,0 +1,773 @@ +//-------------------------------------------------------------------------------- +// Auto-generated by Migen (ae42105) & LiteX (3a72688b) on 2019-08-23 13:21:26 +//-------------------------------------------------------------------------------- +#ifndef __GENERATED_CSR_H +#define __GENERATED_CSR_H +#include +#ifdef CSR_ACCESSORS_DEFINED +extern void csr_writeb(uint8_t value, unsigned long addr); +extern uint8_t csr_readb(unsigned long addr); +extern void csr_writew(uint16_t value, unsigned long addr); +extern uint16_t csr_readw(unsigned long addr); +extern void csr_writel(uint32_t value, unsigned long addr); +extern uint32_t csr_readl(unsigned long addr); +#else /* ! CSR_ACCESSORS_DEFINED */ +#include +#endif /* ! CSR_ACCESSORS_DEFINED */ + +/* ctrl */ +#define CSR_CTRL_BASE 0xe0000000L +#define CSR_CTRL_RESET_ADDR 0xe0000000L +#define CSR_CTRL_RESET_SIZE 1 +static inline unsigned char ctrl_reset_read(void) { + unsigned char r = csr_readl(0xe0000000L); + return r; +} +static inline void ctrl_reset_write(unsigned char value) { + csr_writel(value, 0xe0000000L); +} +#define CSR_CTRL_SCRATCH_ADDR 0xe0000004L +#define CSR_CTRL_SCRATCH_SIZE 4 +static inline unsigned int ctrl_scratch_read(void) { + unsigned int r = csr_readl(0xe0000004L); + r <<= 8; + r |= csr_readl(0xe0000008L); + r <<= 8; + r |= csr_readl(0xe000000cL); + r <<= 8; + r |= csr_readl(0xe0000010L); + return r; +} +static inline void ctrl_scratch_write(unsigned int value) { + csr_writel(value >> 24, 0xe0000004L); + csr_writel(value >> 16, 0xe0000008L); + csr_writel(value >> 8, 0xe000000cL); + csr_writel(value, 0xe0000010L); +} +#define CSR_CTRL_BUS_ERRORS_ADDR 0xe0000014L +#define CSR_CTRL_BUS_ERRORS_SIZE 4 +static inline unsigned int ctrl_bus_errors_read(void) { + unsigned int r = csr_readl(0xe0000014L); + r <<= 8; + r |= csr_readl(0xe0000018L); + r <<= 8; + r |= csr_readl(0xe000001cL); + r <<= 8; + r |= csr_readl(0xe0000020L); + return r; +} + +/* picorvspi */ +#define CSR_PICORVSPI_BASE 0xe0005000L +#define CSR_PICORVSPI_CFG1_ADDR 0xe0005000L +#define CSR_PICORVSPI_CFG1_SIZE 1 +static inline unsigned char picorvspi_cfg1_read(void) { + unsigned char r = csr_readl(0xe0005000L); + return r; +} +static inline void picorvspi_cfg1_write(unsigned char value) { + csr_writel(value, 0xe0005000L); +} +#define CSR_PICORVSPI_CFG2_ADDR 0xe0005004L +#define CSR_PICORVSPI_CFG2_SIZE 1 +static inline unsigned char picorvspi_cfg2_read(void) { + unsigned char r = csr_readl(0xe0005004L); + return r; +} +static inline void picorvspi_cfg2_write(unsigned char value) { + csr_writel(value, 0xe0005004L); +} +#define CSR_PICORVSPI_CFG3_ADDR 0xe0005008L +#define CSR_PICORVSPI_CFG3_SIZE 1 +static inline unsigned char picorvspi_cfg3_read(void) { + unsigned char r = csr_readl(0xe0005008L); + return r; +} +static inline void picorvspi_cfg3_write(unsigned char value) { + csr_writel(value, 0xe0005008L); +} +#define CSR_PICORVSPI_CFG4_ADDR 0xe000500cL +#define CSR_PICORVSPI_CFG4_SIZE 1 +static inline unsigned char picorvspi_cfg4_read(void) { + unsigned char r = csr_readl(0xe000500cL); + return r; +} +static inline void picorvspi_cfg4_write(unsigned char value) { + csr_writel(value, 0xe000500cL); +} +#define CSR_PICORVSPI_STAT1_ADDR 0xe0005010L +#define CSR_PICORVSPI_STAT1_SIZE 1 +static inline unsigned char picorvspi_stat1_read(void) { + unsigned char r = csr_readl(0xe0005010L); + return r; +} +#define CSR_PICORVSPI_STAT2_ADDR 0xe0005014L +#define CSR_PICORVSPI_STAT2_SIZE 1 +static inline unsigned char picorvspi_stat2_read(void) { + unsigned char r = csr_readl(0xe0005014L); + return r; +} +#define CSR_PICORVSPI_STAT3_ADDR 0xe0005018L +#define CSR_PICORVSPI_STAT3_SIZE 1 +static inline unsigned char picorvspi_stat3_read(void) { + unsigned char r = csr_readl(0xe0005018L); + return r; +} +#define CSR_PICORVSPI_STAT4_ADDR 0xe000501cL +#define CSR_PICORVSPI_STAT4_SIZE 1 +static inline unsigned char picorvspi_stat4_read(void) { + unsigned char r = csr_readl(0xe000501cL); + return r; +} + +/* reboot */ +#define CSR_REBOOT_BASE 0xe0006000L +#define CSR_REBOOT_CTRL_ADDR 0xe0006000L +#define CSR_REBOOT_CTRL_SIZE 1 +static inline unsigned char reboot_ctrl_read(void) { + unsigned char r = csr_readl(0xe0006000L); + return r; +} +static inline void reboot_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0006000L); +} +#define CSR_REBOOT_ADDR_ADDR 0xe0006004L +#define CSR_REBOOT_ADDR_SIZE 4 +static inline unsigned int reboot_addr_read(void) { + unsigned int r = csr_readl(0xe0006004L); + r <<= 8; + r |= csr_readl(0xe0006008L); + r <<= 8; + r |= csr_readl(0xe000600cL); + r <<= 8; + r |= csr_readl(0xe0006010L); + return r; +} +static inline void reboot_addr_write(unsigned int value) { + csr_writel(value >> 24, 0xe0006004L); + csr_writel(value >> 16, 0xe0006008L); + csr_writel(value >> 8, 0xe000600cL); + csr_writel(value, 0xe0006010L); +} + +/* rgb */ +#define CSR_RGB_BASE 0xe0006800L +#define CSR_RGB_DAT_ADDR 0xe0006800L +#define CSR_RGB_DAT_SIZE 1 +static inline unsigned char rgb_dat_read(void) { + unsigned char r = csr_readl(0xe0006800L); + return r; +} +static inline void rgb_dat_write(unsigned char value) { + csr_writel(value, 0xe0006800L); +} +#define CSR_RGB_ADDR_ADDR 0xe0006804L +#define CSR_RGB_ADDR_SIZE 1 +static inline unsigned char rgb_addr_read(void) { + unsigned char r = csr_readl(0xe0006804L); + return r; +} +static inline void rgb_addr_write(unsigned char value) { + csr_writel(value, 0xe0006804L); +} +#define CSR_RGB_CTRL_ADDR 0xe0006808L +#define CSR_RGB_CTRL_SIZE 1 +static inline unsigned char rgb_ctrl_read(void) { + unsigned char r = csr_readl(0xe0006808L); + return r; +} +static inline void rgb_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0006808L); +} +#define CSR_RGB_RAW_ADDR 0xe000680cL +#define CSR_RGB_RAW_SIZE 1 +static inline unsigned char rgb_raw_read(void) { + unsigned char r = csr_readl(0xe000680cL); + return r; +} +static inline void rgb_raw_write(unsigned char value) { + csr_writel(value, 0xe000680cL); +} + +/* timer0 */ +#define CSR_TIMER0_BASE 0xe0002800L +#define CSR_TIMER0_LOAD_ADDR 0xe0002800L +#define CSR_TIMER0_LOAD_SIZE 4 +static inline unsigned int timer0_load_read(void) { + unsigned int r = csr_readl(0xe0002800L); + r <<= 8; + r |= csr_readl(0xe0002804L); + r <<= 8; + r |= csr_readl(0xe0002808L); + r <<= 8; + r |= csr_readl(0xe000280cL); + return r; +} +static inline void timer0_load_write(unsigned int value) { + csr_writel(value >> 24, 0xe0002800L); + csr_writel(value >> 16, 0xe0002804L); + csr_writel(value >> 8, 0xe0002808L); + csr_writel(value, 0xe000280cL); +} +#define CSR_TIMER0_RELOAD_ADDR 0xe0002810L +#define CSR_TIMER0_RELOAD_SIZE 4 +static inline unsigned int timer0_reload_read(void) { + unsigned int r = csr_readl(0xe0002810L); + r <<= 8; + r |= csr_readl(0xe0002814L); + r <<= 8; + r |= csr_readl(0xe0002818L); + r <<= 8; + r |= csr_readl(0xe000281cL); + return r; +} +static inline void timer0_reload_write(unsigned int value) { + csr_writel(value >> 24, 0xe0002810L); + csr_writel(value >> 16, 0xe0002814L); + csr_writel(value >> 8, 0xe0002818L); + csr_writel(value, 0xe000281cL); +} +#define CSR_TIMER0_EN_ADDR 0xe0002820L +#define CSR_TIMER0_EN_SIZE 1 +static inline unsigned char timer0_en_read(void) { + unsigned char r = csr_readl(0xe0002820L); + return r; +} +static inline void timer0_en_write(unsigned char value) { + csr_writel(value, 0xe0002820L); +} +#define CSR_TIMER0_UPDATE_VALUE_ADDR 0xe0002824L +#define CSR_TIMER0_UPDATE_VALUE_SIZE 1 +static inline unsigned char timer0_update_value_read(void) { + unsigned char r = csr_readl(0xe0002824L); + return r; +} +static inline void timer0_update_value_write(unsigned char value) { + csr_writel(value, 0xe0002824L); +} +#define CSR_TIMER0_VALUE_ADDR 0xe0002828L +#define CSR_TIMER0_VALUE_SIZE 4 +static inline unsigned int timer0_value_read(void) { + unsigned int r = csr_readl(0xe0002828L); + r <<= 8; + r |= csr_readl(0xe000282cL); + r <<= 8; + r |= csr_readl(0xe0002830L); + r <<= 8; + r |= csr_readl(0xe0002834L); + return r; +} +#define CSR_TIMER0_EV_STATUS_ADDR 0xe0002838L +#define CSR_TIMER0_EV_STATUS_SIZE 1 +static inline unsigned char timer0_ev_status_read(void) { + unsigned char r = csr_readl(0xe0002838L); + return r; +} +static inline void timer0_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0002838L); +} +#define CSR_TIMER0_EV_PENDING_ADDR 0xe000283cL +#define CSR_TIMER0_EV_PENDING_SIZE 1 +static inline unsigned char timer0_ev_pending_read(void) { + unsigned char r = csr_readl(0xe000283cL); + return r; +} +static inline void timer0_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe000283cL); +} +#define CSR_TIMER0_EV_ENABLE_ADDR 0xe0002840L +#define CSR_TIMER0_EV_ENABLE_SIZE 1 +static inline unsigned char timer0_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0002840L); + return r; +} +static inline void timer0_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0002840L); +} + +/* touch */ +#define CSR_TOUCH_BASE 0xe0005800L +#define CSR_TOUCH_O_ADDR 0xe0005800L +#define CSR_TOUCH_O_SIZE 1 +static inline unsigned char touch_o_read(void) { + unsigned char r = csr_readl(0xe0005800L); + return r; +} +static inline void touch_o_write(unsigned char value) { + csr_writel(value, 0xe0005800L); +} +#define CSR_TOUCH_OE_ADDR 0xe0005804L +#define CSR_TOUCH_OE_SIZE 1 +static inline unsigned char touch_oe_read(void) { + unsigned char r = csr_readl(0xe0005804L); + return r; +} +static inline void touch_oe_write(unsigned char value) { + csr_writel(value, 0xe0005804L); +} +#define CSR_TOUCH_I_ADDR 0xe0005808L +#define CSR_TOUCH_I_SIZE 1 +static inline unsigned char touch_i_read(void) { + unsigned char r = csr_readl(0xe0005808L); + return r; +} + +/* usb */ +#define CSR_USB_BASE 0xe0004800L +#define CSR_USB_PULLUP_OUT_ADDR 0xe0004800L +#define CSR_USB_PULLUP_OUT_SIZE 1 +static inline unsigned char usb_pullup_out_read(void) { + unsigned char r = csr_readl(0xe0004800L); + return r; +} +static inline void usb_pullup_out_write(unsigned char value) { + csr_writel(value, 0xe0004800L); +} +#define CSR_USB_EP_0_OUT_EV_STATUS_ADDR 0xe0004804L +#define CSR_USB_EP_0_OUT_EV_STATUS_SIZE 1 +static inline unsigned char usb_ep_0_out_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004804L); + return r; +} +static inline void usb_ep_0_out_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004804L); +} +#define CSR_USB_EP_0_OUT_EV_PENDING_ADDR 0xe0004808L +#define CSR_USB_EP_0_OUT_EV_PENDING_SIZE 1 +static inline unsigned char usb_ep_0_out_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004808L); + return r; +} +static inline void usb_ep_0_out_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004808L); +} +#define CSR_USB_EP_0_OUT_EV_ENABLE_ADDR 0xe000480cL +#define CSR_USB_EP_0_OUT_EV_ENABLE_SIZE 1 +static inline unsigned char usb_ep_0_out_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000480cL); + return r; +} +static inline void usb_ep_0_out_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000480cL); +} +#define CSR_USB_EP_0_OUT_LAST_TOK_ADDR 0xe0004810L +#define CSR_USB_EP_0_OUT_LAST_TOK_SIZE 1 +static inline unsigned char usb_ep_0_out_last_tok_read(void) { + unsigned char r = csr_readl(0xe0004810L); + return r; +} +#define CSR_USB_EP_0_OUT_RESPOND_ADDR 0xe0004814L +#define CSR_USB_EP_0_OUT_RESPOND_SIZE 1 +static inline unsigned char usb_ep_0_out_respond_read(void) { + unsigned char r = csr_readl(0xe0004814L); + return r; +} +static inline void usb_ep_0_out_respond_write(unsigned char value) { + csr_writel(value, 0xe0004814L); +} +#define CSR_USB_EP_0_OUT_DTB_ADDR 0xe0004818L +#define CSR_USB_EP_0_OUT_DTB_SIZE 1 +static inline unsigned char usb_ep_0_out_dtb_read(void) { + unsigned char r = csr_readl(0xe0004818L); + return r; +} +static inline void usb_ep_0_out_dtb_write(unsigned char value) { + csr_writel(value, 0xe0004818L); +} +#define CSR_USB_EP_0_OUT_OBUF_HEAD_ADDR 0xe000481cL +#define CSR_USB_EP_0_OUT_OBUF_HEAD_SIZE 1 +static inline unsigned char usb_ep_0_out_obuf_head_read(void) { + unsigned char r = csr_readl(0xe000481cL); + return r; +} +static inline void usb_ep_0_out_obuf_head_write(unsigned char value) { + csr_writel(value, 0xe000481cL); +} +#define CSR_USB_EP_0_OUT_OBUF_EMPTY_ADDR 0xe0004820L +#define CSR_USB_EP_0_OUT_OBUF_EMPTY_SIZE 1 +static inline unsigned char usb_ep_0_out_obuf_empty_read(void) { + unsigned char r = csr_readl(0xe0004820L); + return r; +} +#define CSR_USB_EP_0_IN_EV_STATUS_ADDR 0xe0004824L +#define CSR_USB_EP_0_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_ep_0_in_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004824L); + return r; +} +static inline void usb_ep_0_in_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004824L); +} +#define CSR_USB_EP_0_IN_EV_PENDING_ADDR 0xe0004828L +#define CSR_USB_EP_0_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_ep_0_in_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004828L); + return r; +} +static inline void usb_ep_0_in_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004828L); +} +#define CSR_USB_EP_0_IN_EV_ENABLE_ADDR 0xe000482cL +#define CSR_USB_EP_0_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_ep_0_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000482cL); + return r; +} +static inline void usb_ep_0_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000482cL); +} +#define CSR_USB_EP_0_IN_LAST_TOK_ADDR 0xe0004830L +#define CSR_USB_EP_0_IN_LAST_TOK_SIZE 1 +static inline unsigned char usb_ep_0_in_last_tok_read(void) { + unsigned char r = csr_readl(0xe0004830L); + return r; +} +#define CSR_USB_EP_0_IN_RESPOND_ADDR 0xe0004834L +#define CSR_USB_EP_0_IN_RESPOND_SIZE 1 +static inline unsigned char usb_ep_0_in_respond_read(void) { + unsigned char r = csr_readl(0xe0004834L); + return r; +} +static inline void usb_ep_0_in_respond_write(unsigned char value) { + csr_writel(value, 0xe0004834L); +} +#define CSR_USB_EP_0_IN_DTB_ADDR 0xe0004838L +#define CSR_USB_EP_0_IN_DTB_SIZE 1 +static inline unsigned char usb_ep_0_in_dtb_read(void) { + unsigned char r = csr_readl(0xe0004838L); + return r; +} +static inline void usb_ep_0_in_dtb_write(unsigned char value) { + csr_writel(value, 0xe0004838L); +} +#define CSR_USB_EP_0_IN_IBUF_HEAD_ADDR 0xe000483cL +#define CSR_USB_EP_0_IN_IBUF_HEAD_SIZE 1 +static inline unsigned char usb_ep_0_in_ibuf_head_read(void) { + unsigned char r = csr_readl(0xe000483cL); + return r; +} +static inline void usb_ep_0_in_ibuf_head_write(unsigned char value) { + csr_writel(value, 0xe000483cL); +} +#define CSR_USB_EP_0_IN_IBUF_EMPTY_ADDR 0xe0004840L +#define CSR_USB_EP_0_IN_IBUF_EMPTY_SIZE 1 +static inline unsigned char usb_ep_0_in_ibuf_empty_read(void) { + unsigned char r = csr_readl(0xe0004840L); + return r; +} +#define CSR_USB_EP_1_IN_EV_STATUS_ADDR 0xe0004844L +#define CSR_USB_EP_1_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_ep_1_in_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004844L); + return r; +} +static inline void usb_ep_1_in_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004844L); +} +#define CSR_USB_EP_1_IN_EV_PENDING_ADDR 0xe0004848L +#define CSR_USB_EP_1_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_ep_1_in_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004848L); + return r; +} +static inline void usb_ep_1_in_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004848L); +} +#define CSR_USB_EP_1_IN_EV_ENABLE_ADDR 0xe000484cL +#define CSR_USB_EP_1_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_ep_1_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000484cL); + return r; +} +static inline void usb_ep_1_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000484cL); +} +#define CSR_USB_EP_1_IN_LAST_TOK_ADDR 0xe0004850L +#define CSR_USB_EP_1_IN_LAST_TOK_SIZE 1 +static inline unsigned char usb_ep_1_in_last_tok_read(void) { + unsigned char r = csr_readl(0xe0004850L); + return r; +} +#define CSR_USB_EP_1_IN_RESPOND_ADDR 0xe0004854L +#define CSR_USB_EP_1_IN_RESPOND_SIZE 1 +static inline unsigned char usb_ep_1_in_respond_read(void) { + unsigned char r = csr_readl(0xe0004854L); + return r; +} +static inline void usb_ep_1_in_respond_write(unsigned char value) { + csr_writel(value, 0xe0004854L); +} +#define CSR_USB_EP_1_IN_DTB_ADDR 0xe0004858L +#define CSR_USB_EP_1_IN_DTB_SIZE 1 +static inline unsigned char usb_ep_1_in_dtb_read(void) { + unsigned char r = csr_readl(0xe0004858L); + return r; +} +static inline void usb_ep_1_in_dtb_write(unsigned char value) { + csr_writel(value, 0xe0004858L); +} +#define CSR_USB_EP_1_IN_IBUF_HEAD_ADDR 0xe000485cL +#define CSR_USB_EP_1_IN_IBUF_HEAD_SIZE 1 +static inline unsigned char usb_ep_1_in_ibuf_head_read(void) { + unsigned char r = csr_readl(0xe000485cL); + return r; +} +static inline void usb_ep_1_in_ibuf_head_write(unsigned char value) { + csr_writel(value, 0xe000485cL); +} +#define CSR_USB_EP_1_IN_IBUF_EMPTY_ADDR 0xe0004860L +#define CSR_USB_EP_1_IN_IBUF_EMPTY_SIZE 1 +static inline unsigned char usb_ep_1_in_ibuf_empty_read(void) { + unsigned char r = csr_readl(0xe0004860L); + return r; +} +#define CSR_USB_EP_2_OUT_EV_STATUS_ADDR 0xe0004864L +#define CSR_USB_EP_2_OUT_EV_STATUS_SIZE 1 +static inline unsigned char usb_ep_2_out_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004864L); + return r; +} +static inline void usb_ep_2_out_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004864L); +} +#define CSR_USB_EP_2_OUT_EV_PENDING_ADDR 0xe0004868L +#define CSR_USB_EP_2_OUT_EV_PENDING_SIZE 1 +static inline unsigned char usb_ep_2_out_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004868L); + return r; +} +static inline void usb_ep_2_out_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004868L); +} +#define CSR_USB_EP_2_OUT_EV_ENABLE_ADDR 0xe000486cL +#define CSR_USB_EP_2_OUT_EV_ENABLE_SIZE 1 +static inline unsigned char usb_ep_2_out_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000486cL); + return r; +} +static inline void usb_ep_2_out_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000486cL); +} +#define CSR_USB_EP_2_OUT_LAST_TOK_ADDR 0xe0004870L +#define CSR_USB_EP_2_OUT_LAST_TOK_SIZE 1 +static inline unsigned char usb_ep_2_out_last_tok_read(void) { + unsigned char r = csr_readl(0xe0004870L); + return r; +} +#define CSR_USB_EP_2_OUT_RESPOND_ADDR 0xe0004874L +#define CSR_USB_EP_2_OUT_RESPOND_SIZE 1 +static inline unsigned char usb_ep_2_out_respond_read(void) { + unsigned char r = csr_readl(0xe0004874L); + return r; +} +static inline void usb_ep_2_out_respond_write(unsigned char value) { + csr_writel(value, 0xe0004874L); +} +#define CSR_USB_EP_2_OUT_DTB_ADDR 0xe0004878L +#define CSR_USB_EP_2_OUT_DTB_SIZE 1 +static inline unsigned char usb_ep_2_out_dtb_read(void) { + unsigned char r = csr_readl(0xe0004878L); + return r; +} +static inline void usb_ep_2_out_dtb_write(unsigned char value) { + csr_writel(value, 0xe0004878L); +} +#define CSR_USB_EP_2_OUT_OBUF_HEAD_ADDR 0xe000487cL +#define CSR_USB_EP_2_OUT_OBUF_HEAD_SIZE 1 +static inline unsigned char usb_ep_2_out_obuf_head_read(void) { + unsigned char r = csr_readl(0xe000487cL); + return r; +} +static inline void usb_ep_2_out_obuf_head_write(unsigned char value) { + csr_writel(value, 0xe000487cL); +} +#define CSR_USB_EP_2_OUT_OBUF_EMPTY_ADDR 0xe0004880L +#define CSR_USB_EP_2_OUT_OBUF_EMPTY_SIZE 1 +static inline unsigned char usb_ep_2_out_obuf_empty_read(void) { + unsigned char r = csr_readl(0xe0004880L); + return r; +} +#define CSR_USB_EP_2_IN_EV_STATUS_ADDR 0xe0004884L +#define CSR_USB_EP_2_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_ep_2_in_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004884L); + return r; +} +static inline void usb_ep_2_in_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004884L); +} +#define CSR_USB_EP_2_IN_EV_PENDING_ADDR 0xe0004888L +#define CSR_USB_EP_2_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_ep_2_in_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004888L); + return r; +} +static inline void usb_ep_2_in_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004888L); +} +#define CSR_USB_EP_2_IN_EV_ENABLE_ADDR 0xe000488cL +#define CSR_USB_EP_2_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_ep_2_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000488cL); + return r; +} +static inline void usb_ep_2_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000488cL); +} +#define CSR_USB_EP_2_IN_LAST_TOK_ADDR 0xe0004890L +#define CSR_USB_EP_2_IN_LAST_TOK_SIZE 1 +static inline unsigned char usb_ep_2_in_last_tok_read(void) { + unsigned char r = csr_readl(0xe0004890L); + return r; +} +#define CSR_USB_EP_2_IN_RESPOND_ADDR 0xe0004894L +#define CSR_USB_EP_2_IN_RESPOND_SIZE 1 +static inline unsigned char usb_ep_2_in_respond_read(void) { + unsigned char r = csr_readl(0xe0004894L); + return r; +} +static inline void usb_ep_2_in_respond_write(unsigned char value) { + csr_writel(value, 0xe0004894L); +} +#define CSR_USB_EP_2_IN_DTB_ADDR 0xe0004898L +#define CSR_USB_EP_2_IN_DTB_SIZE 1 +static inline unsigned char usb_ep_2_in_dtb_read(void) { + unsigned char r = csr_readl(0xe0004898L); + return r; +} +static inline void usb_ep_2_in_dtb_write(unsigned char value) { + csr_writel(value, 0xe0004898L); +} +#define CSR_USB_EP_2_IN_IBUF_HEAD_ADDR 0xe000489cL +#define CSR_USB_EP_2_IN_IBUF_HEAD_SIZE 1 +static inline unsigned char usb_ep_2_in_ibuf_head_read(void) { + unsigned char r = csr_readl(0xe000489cL); + return r; +} +static inline void usb_ep_2_in_ibuf_head_write(unsigned char value) { + csr_writel(value, 0xe000489cL); +} +#define CSR_USB_EP_2_IN_IBUF_EMPTY_ADDR 0xe00048a0L +#define CSR_USB_EP_2_IN_IBUF_EMPTY_SIZE 1 +static inline unsigned char usb_ep_2_in_ibuf_empty_read(void) { + unsigned char r = csr_readl(0xe00048a0L); + return r; +} +#define CSR_USB_ADDRESS_ADDR 0xe00048a4L +#define CSR_USB_ADDRESS_SIZE 1 +static inline unsigned char usb_address_read(void) { + unsigned char r = csr_readl(0xe00048a4L); + return r; +} +static inline void usb_address_write(unsigned char value) { + csr_writel(value, 0xe00048a4L); +} + +/* version */ +#define CSR_VERSION_BASE 0xe0007000L +#define CSR_VERSION_MAJOR_ADDR 0xe0007000L +#define CSR_VERSION_MAJOR_SIZE 1 +static inline unsigned char version_major_read(void) { + unsigned char r = csr_readl(0xe0007000L); + return r; +} +#define CSR_VERSION_MINOR_ADDR 0xe0007004L +#define CSR_VERSION_MINOR_SIZE 1 +static inline unsigned char version_minor_read(void) { + unsigned char r = csr_readl(0xe0007004L); + return r; +} +#define CSR_VERSION_REVISION_ADDR 0xe0007008L +#define CSR_VERSION_REVISION_SIZE 1 +static inline unsigned char version_revision_read(void) { + unsigned char r = csr_readl(0xe0007008L); + return r; +} +#define CSR_VERSION_GITREV_ADDR 0xe000700cL +#define CSR_VERSION_GITREV_SIZE 4 +static inline unsigned int version_gitrev_read(void) { + unsigned int r = csr_readl(0xe000700cL); + r <<= 8; + r |= csr_readl(0xe0007010L); + r <<= 8; + r |= csr_readl(0xe0007014L); + r <<= 8; + r |= csr_readl(0xe0007018L); + return r; +} +#define CSR_VERSION_GITEXTRA_ADDR 0xe000701cL +#define CSR_VERSION_GITEXTRA_SIZE 2 +static inline unsigned short int version_gitextra_read(void) { + unsigned short int r = csr_readl(0xe000701cL); + r <<= 8; + r |= csr_readl(0xe0007020L); + return r; +} +#define CSR_VERSION_DIRTY_ADDR 0xe0007024L +#define CSR_VERSION_DIRTY_SIZE 1 +static inline unsigned char version_dirty_read(void) { + unsigned char r = csr_readl(0xe0007024L); + return r; +} +#define CSR_VERSION_MODEL_ADDR 0xe0007028L +#define CSR_VERSION_MODEL_SIZE 1 +static inline unsigned char version_model_read(void) { + unsigned char r = csr_readl(0xe0007028L); + return r; +} + +/* constants */ +#define TIMER0_INTERRUPT 0 +static inline int timer0_interrupt_read(void) { + return 0; +} +#define USB_INTERRUPT 3 +static inline int usb_interrupt_read(void) { + return 3; +} +#define CSR_DATA_WIDTH 8 +static inline int csr_data_width_read(void) { + return 8; +} +#define SYSTEM_CLOCK_FREQUENCY 12000000 +static inline int system_clock_frequency_read(void) { + return 12000000; +} +#define CONFIG_BITSTREAM_SYNC_HEADER1 2123999870 +static inline int config_bitstream_sync_header1_read(void) { + return 2123999870; +} +#define CONFIG_BITSTREAM_SYNC_HEADER2 2125109630 +static inline int config_bitstream_sync_header2_read(void) { + return 2125109630; +} +#define CONFIG_CLOCK_FREQUENCY 12000000 +static inline int config_clock_frequency_read(void) { + return 12000000; +} +#define CONFIG_CPU_RESET_ADDR 0 +static inline int config_cpu_reset_addr_read(void) { + return 0; +} +#define CONFIG_CPU_TYPE "VEXRISCV" +static inline const char * config_cpu_type_read(void) { + return "VEXRISCV"; +} +#define CONFIG_CPU_VARIANT "VEXRISCV" +static inline const char * config_cpu_variant_read(void) { + return "VEXRISCV"; +} +#define CONFIG_CSR_DATA_WIDTH 8 +static inline int config_csr_data_width_read(void) { + return 8; +} +#define CONFIG_FOMU_REV "HACKER" +static inline const char * config_fomu_rev_read(void) { + return "HACKER"; +} +#define CONFIG_FOMU_REV_HACKER 1 +static inline int config_fomu_rev_hacker_read(void) { + return 1; +} + +#endif diff --git a/im-tomu_fomu-workshop/riscv-blink/include/generated/mem.h b/im-tomu_fomu-workshop/riscv-blink/include/generated/mem.h new file mode 100644 index 0000000000000000000000000000000000000000..6fe108e317ae6608173dfd821661f9c526352d56 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/generated/mem.h @@ -0,0 +1,16 @@ +#ifndef __GENERATED_MEM_H +#define __GENERATED_MEM_H + +#define VEXRISCV_DEBUG_BASE 0xf00f0000 +#define VEXRISCV_DEBUG_SIZE 0x00000010 + +#define SRAM_BASE 0x10000000 +#define SRAM_SIZE 0x00020000 + +#define ROM_BASE 0x00000000 +#define ROM_SIZE 0x00002000 + +#define SPIFLASH_BASE 0x20000000 +#define SPIFLASH_SIZE 0x00200000 + +#endif diff --git a/im-tomu_fomu-workshop/riscv-blink/include/hw/common.h b/im-tomu_fomu-workshop/riscv-blink/include/hw/common.h new file mode 100644 index 0000000000000000000000000000000000000000..af668f74e5bd33411f3253e982e6820e67405ff7 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/hw/common.h @@ -0,0 +1,52 @@ +#ifndef __HW_COMMON_H +#define __HW_COMMON_H + +#include + +/* To overwrite CSR accessors, define extern, non-inlined versions + * of csr_read[bwl]() and csr_write[bwl](), and define + * CSR_ACCESSORS_DEFINED. + */ + +#ifndef CSR_ACCESSORS_DEFINED +#define CSR_ACCESSORS_DEFINED + +#ifdef __ASSEMBLER__ +#define MMPTR(x) x +#else /* ! __ASSEMBLER__ */ +#define MMPTR(x) (*((volatile unsigned int *)(x))) + +static inline void csr_writeb(uint8_t value, uint32_t addr) +{ + *((volatile uint8_t *)addr) = value; +} + +static inline uint8_t csr_readb(uint32_t addr) +{ + return *(volatile uint8_t *)addr; +} + +static inline void csr_writew(uint16_t value, uint32_t addr) +{ + *((volatile uint16_t *)addr) = value; +} + +static inline uint16_t csr_readw(uint32_t addr) +{ + return *(volatile uint16_t *)addr; +} + +static inline void csr_writel(uint32_t value, uint32_t addr) +{ + *((volatile uint32_t *)addr) = value; +} + +static inline uint32_t csr_readl(uint32_t addr) +{ + return *(volatile uint32_t *)addr; +} +#endif /* ! __ASSEMBLER__ */ + +#endif /* ! CSR_ACCESSORS_DEFINED */ + +#endif /* __HW_COMMON_H */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/irq.h b/im-tomu_fomu-workshop/riscv-blink/include/irq.h new file mode 100644 index 0000000000000000000000000000000000000000..19f00b1c55b34afb1e053ff8f6b7d0a334265094 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/irq.h @@ -0,0 +1,144 @@ +#ifndef __IRQ_H +#define __IRQ_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __picorv32__ +// PicoRV32 has a very limited interrupt support, implemented via custom +// instructions. It also doesn't have a global interrupt enable/disable, so +// we have to emulate it via saving and restoring a mask and using 0/~1 as a +// hardware mask. +// Due to all this somewhat low-level mess, all of the glue is implemented in +// the RiscV crt0, and this header is kept as a thin wrapper. Since interrupts +// managed by this layer, do not call interrupt instructions directly, as the +// state will go out of sync with the hardware. + +// Read only. +extern unsigned int _irq_pending; +// Read only. +extern unsigned int _irq_mask; +// Read only. +extern unsigned int _irq_enabled; +extern void _irq_enable(void); +extern void _irq_disable(void); +extern void _irq_setmask(unsigned int); +#endif + +static inline unsigned int irq_getie(void) +{ +#if defined (__lm32__) + unsigned int ie; + __asm__ __volatile__("rcsr %0, IE" : "=r" (ie)); + return ie; +#elif defined (__or1k__) + return !!(mfspr(SPR_SR) & SPR_SR_IEE); +#elif defined (__picorv32__) + return _irq_enabled != 0; +#elif defined (__vexriscv__) + return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; +#elif defined (__minerva__) + return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; +#else +#error Unsupported architecture +#endif +} + +static inline void irq_setie(unsigned int ie) +{ +#if defined (__lm32__) + __asm__ __volatile__("wcsr IE, %0" : : "r" (ie)); +#elif defined (__or1k__) + if (ie & 0x1) + mtspr(SPR_SR, mfspr(SPR_SR) | SPR_SR_IEE); + else + mtspr(SPR_SR, mfspr(SPR_SR) & ~SPR_SR_IEE); +#elif defined (__picorv32__) + if (ie & 0x1) + _irq_enable(); + else + _irq_disable(); +#elif defined (__vexriscv__) + if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE); +#elif defined (__minerva__) + if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE); +#else +#error Unsupported architecture +#endif +} + +static inline unsigned int irq_getmask(void) +{ +#if defined (__lm32__) + unsigned int mask; + __asm__ __volatile__("rcsr %0, IM" : "=r" (mask)); + return mask; +#elif defined (__or1k__) + return mfspr(SPR_PICMR); +#elif defined (__picorv32__) + // PicoRV32 interrupt mask bits are high-disabled. This is the inverse of how + // LiteX sees things. + return ~_irq_mask; +#elif defined (__vexriscv__) + unsigned int mask; + asm volatile ("csrr %0, %1" : "=r"(mask) : "i"(CSR_IRQ_MASK)); + return mask; +#elif defined (__minerva__) + unsigned int mask; + asm volatile ("csrr %0, %1" : "=r"(mask) : "i"(CSR_IRQ_MASK)); + return mask; +#else +#error Unsupported architecture +#endif +} + +static inline void irq_setmask(unsigned int mask) +{ +#if defined (__lm32__) + __asm__ __volatile__("wcsr IM, %0" : : "r" (mask)); +#elif defined (__or1k__) + mtspr(SPR_PICMR, mask); +#elif defined (__picorv32__) + // PicoRV32 interrupt mask bits are high-disabled. This is the inverse of how + // LiteX sees things. + _irq_setmask(~mask); +#elif defined (__vexriscv__) + asm volatile ("csrw %0, %1" :: "i"(CSR_IRQ_MASK), "r"(mask)); +#elif defined (__minerva__) + asm volatile ("csrw %0, %1" :: "i"(CSR_IRQ_MASK), "r"(mask)); +#else +#error Unsupported architecture +#endif +} + +static inline unsigned int irq_pending(void) +{ +#if defined (__lm32__) + unsigned int pending; + __asm__ __volatile__("rcsr %0, IP" : "=r" (pending)); + return pending; +#elif defined (__or1k__) + return mfspr(SPR_PICSR); +#elif defined (__picorv32__) + return _irq_pending; +#elif defined (__vexriscv__) + unsigned int pending; + asm volatile ("csrr %0, %1" : "=r"(pending) : "i"(CSR_IRQ_PENDING)); + return pending; +#elif defined (__minerva__) + unsigned int pending; + asm volatile ("csrr %0, %1" : "=r"(pending) : "i"(CSR_IRQ_PENDING)); + return pending; +#else +#error Unsupported architecture +#endif +} + +#ifdef __cplusplus +} +#endif + +#endif /* __IRQ_H */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/reboot.h b/im-tomu_fomu-workshop/riscv-blink/include/reboot.h new file mode 100644 index 0000000000000000000000000000000000000000..5dc6c4ad21355bb6484efa1a49d1c5a5d0d57000 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/reboot.h @@ -0,0 +1,16 @@ +#ifndef __REBOOT_H_ +#define __REBOOT_H_ + +#include + +__attribute__((noreturn)) static inline void reboot(void) { + reboot_ctrl_write(0xac); + while (1); +} + +__attribute__((noreturn)) static inline void reboot_to_image(uint8_t image_index) { + reboot_ctrl_write(0xac | (image_index & 3) << 0); + while (1); +} + +#endif /* __REBOOT_H_ */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/rgb.h b/im-tomu_fomu-workshop/riscv-blink/include/rgb.h new file mode 100644 index 0000000000000000000000000000000000000000..54554292381b93b39438530242e1046ddc828e85 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/rgb.h @@ -0,0 +1,29 @@ +#ifndef _RGB_H_ +#define _RGB_H_ + +void rgb_init(void); +void rgb_set(uint8_t r, uint8_t g, uint8_t b); + +// The amount of time to stay off or on +void rgb_on_time(uint8_t ms); +void rgb_off_time(uint8_t ms); + +// The amount of time to breathe in/out +void rgb_in_time(uint8_t ms); +void rgb_out_time(uint8_t ms); + +enum led_registers { + LEDDCR0 = 8, + LEDDBR = 9, + LEDDONR = 10, + LEDDOFR = 11, + LEDDBCRR = 5, + LEDDBCFR = 6, + LEDDPWRR = 1, + LEDDPWRG = 2, + LEDDPWRB = 3, +}; + +void rgb_write(uint8_t value, uint8_t addr); + +#endif /* _RGB_H_ */ \ No newline at end of file diff --git a/im-tomu_fomu-workshop/riscv-blink/include/system.h b/im-tomu_fomu-workshop/riscv-blink/include/system.h new file mode 100644 index 0000000000000000000000000000000000000000..2d108d2c1a5ddcba882fdf2a746f4ff6343741d8 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/system.h @@ -0,0 +1,59 @@ +#ifndef __SYSTEM_H +#define __SYSTEM_H + +#ifdef __cplusplus +extern "C" { +#endif + +void flush_cpu_icache(void); +void flush_cpu_dcache(void); +void flush_l2_cache(void); + +#ifdef __or1k__ +#include +static inline unsigned long mfspr(unsigned long add) +{ + unsigned long ret; + + __asm__ __volatile__ ("l.mfspr %0,%1,0" : "=r" (ret) : "r" (add)); + + return ret; +} + +static inline void mtspr(unsigned long add, unsigned long val) +{ + __asm__ __volatile__ ("l.mtspr %0,%1,0" : : "r" (add), "r" (val)); +} +#endif + + +#if defined(__vexriscv__) || defined(__minerva__) +#include +#define csrr(reg) ({ unsigned long __tmp; \ + asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ + __tmp; }) + +#define csrw(reg, val) ({ \ + if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ + asm volatile ("csrw " #reg ", %0" :: "i"(val)); \ + else \ + asm volatile ("csrw " #reg ", %0" :: "r"(val)); }) + +#define csrs(reg, bit) ({ \ + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrs x0, " #reg ", %0" :: "i"(bit)); \ + else \ + asm volatile ("csrrs x0, " #reg ", %0" :: "r"(bit)); }) + +#define csrc(reg, bit) ({ \ + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrc x0, " #reg ", %0" :: "i"(bit)); \ + else \ + asm volatile ("csrrc x0, " #reg ", %0" :: "r"(bit)); }) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __SYSTEM_H */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/time.h b/im-tomu_fomu-workshop/riscv-blink/include/time.h new file mode 100644 index 0000000000000000000000000000000000000000..cbbc688f008e99fb925b91179096dad1e2bec942 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/time.h @@ -0,0 +1,16 @@ +#ifndef __TIME_H +#define __TIME_H + +#ifdef __cplusplus +extern "C" { +#endif + +void time_init(void); +int elapsed(int *last_event, int period); +void msleep(int ms); + +#ifdef __cplusplus +} +#endif + +#endif /* __TIME_H */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/usb-eptri.h b/im-tomu_fomu-workshop/riscv-blink/include/usb-eptri.h new file mode 100644 index 0000000000000000000000000000000000000000..dde83cd709145dd3f0697ff6d4e35908ee9e9812 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/usb-eptri.h @@ -0,0 +1,244 @@ +#ifndef __USB_EPTRI_H_ +#define __USB_EPTRI_H_ + +#ifdef CSR_ACCESSORS_DEFINED +extern void csr_writeb(uint8_t value, unsigned long addr); +extern uint8_t csr_readb(unsigned long addr); +extern void csr_writew(uint16_t value, unsigned long addr); +extern uint16_t csr_readw(unsigned long addr); +extern void csr_writel(uint32_t value, unsigned long addr); +extern uint32_t csr_readl(unsigned long addr); +#else /* ! CSR_ACCESSORS_DEFINED */ +#include +#endif /* ! CSR_ACCESSORS_DEFINED */ + +#define CSR_USB_BASE 0xe0004800L +#define CSR_USB_PULLUP_OUT_ADDR 0xe0004800L +#define CSR_USB_PULLUP_OUT_SIZE 1 +static inline unsigned char usb_pullup_out_read(void) { + unsigned char r = csr_readl(0xe0004800L); + return r; +} +static inline void usb_pullup_out_write(unsigned char value) { + csr_writel(value, 0xe0004800L); +} +#define CSR_USB_ADDRESS_ADDR 0xe0004804L +#define CSR_USB_ADDRESS_SIZE 1 +static inline unsigned char usb_address_read(void) { + unsigned char r = csr_readl(0xe0004804L); + return r; +} +static inline void usb_address_write(unsigned char value) { + csr_writel(value, 0xe0004804L); +} +#define CSR_USB_ADDRESS_ADDR_OFFSET 0 +#define CSR_USB_ADDRESS_ADDR_SIZE 7 +#define CSR_USB_NEXT_EV_ADDR 0xe0004808L +#define CSR_USB_NEXT_EV_SIZE 1 +static inline unsigned char usb_next_ev_read(void) { + unsigned char r = csr_readl(0xe0004808L); + return r; +} +#define CSR_USB_NEXT_EV_IN_OFFSET 0 +#define CSR_USB_NEXT_EV_IN_SIZE 1 +#define CSR_USB_NEXT_EV_OUT_OFFSET 1 +#define CSR_USB_NEXT_EV_OUT_SIZE 1 +#define CSR_USB_NEXT_EV_SETUP_OFFSET 2 +#define CSR_USB_NEXT_EV_SETUP_SIZE 1 +#define CSR_USB_NEXT_EV_RESET_OFFSET 3 +#define CSR_USB_NEXT_EV_RESET_SIZE 1 +#define CSR_USB_SETUP_DATA_ADDR 0xe000480cL +#define CSR_USB_SETUP_DATA_SIZE 1 +static inline unsigned char usb_setup_data_read(void) { + unsigned char r = csr_readl(0xe000480cL); + return r; +} +#define CSR_USB_SETUP_DATA_DATA_OFFSET 0 +#define CSR_USB_SETUP_DATA_DATA_SIZE 8 +#define CSR_USB_SETUP_CTRL_ADDR 0xe0004810L +#define CSR_USB_SETUP_CTRL_SIZE 1 +static inline unsigned char usb_setup_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004810L); + return r; +} +static inline void usb_setup_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004810L); +} +#define CSR_USB_SETUP_CTRL_RESET_OFFSET 5 +#define CSR_USB_SETUP_CTRL_RESET_SIZE 1 +#define CSR_USB_SETUP_STATUS_ADDR 0xe0004814L +#define CSR_USB_SETUP_STATUS_SIZE 1 +static inline unsigned char usb_setup_status_read(void) { + unsigned char r = csr_readl(0xe0004814L); + return r; +} +#define CSR_USB_SETUP_STATUS_EPNO_OFFSET 0 +#define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 +#define CSR_USB_SETUP_STATUS_HAVE_OFFSET 4 +#define CSR_USB_SETUP_STATUS_HAVE_SIZE 1 +#define CSR_USB_SETUP_STATUS_PEND_OFFSET 5 +#define CSR_USB_SETUP_STATUS_PEND_SIZE 1 +#define CSR_USB_SETUP_STATUS_IS_IN_OFFSET 6 +#define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 +#define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 +#define CSR_USB_SETUP_STATUS_DATA_SIZE 1 +#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004818L +#define CSR_USB_SETUP_EV_STATUS_SIZE 1 +static inline unsigned char usb_setup_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004818L); + return r; +} +static inline void usb_setup_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004818L); +} +#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe000481cL +#define CSR_USB_SETUP_EV_PENDING_SIZE 1 +static inline unsigned char usb_setup_ev_pending_read(void) { + unsigned char r = csr_readl(0xe000481cL); + return r; +} +static inline void usb_setup_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe000481cL); +} +#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe0004820L +#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 +static inline unsigned char usb_setup_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004820L); + return r; +} +static inline void usb_setup_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004820L); +} +#define CSR_USB_IN_DATA_ADDR 0xe0004824L +#define CSR_USB_IN_DATA_SIZE 1 +static inline unsigned char usb_in_data_read(void) { + unsigned char r = csr_readl(0xe0004824L); + return r; +} +static inline void usb_in_data_write(unsigned char value) { + csr_writel(value, 0xe0004824L); +} +#define CSR_USB_IN_DATA_DATA_OFFSET 0 +#define CSR_USB_IN_DATA_DATA_SIZE 8 +#define CSR_USB_IN_CTRL_ADDR 0xe0004828L +#define CSR_USB_IN_CTRL_SIZE 1 +static inline unsigned char usb_in_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004828L); + return r; +} +static inline void usb_in_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004828L); +} +#define CSR_USB_IN_CTRL_EPNO_OFFSET 0 +#define CSR_USB_IN_CTRL_EPNO_SIZE 4 +#define CSR_USB_IN_CTRL_RESET_OFFSET 5 +#define CSR_USB_IN_CTRL_RESET_SIZE 1 +#define CSR_USB_IN_CTRL_STALL_OFFSET 6 +#define CSR_USB_IN_CTRL_STALL_SIZE 1 +#define CSR_USB_IN_STATUS_ADDR 0xe000482cL +#define CSR_USB_IN_STATUS_SIZE 1 +static inline unsigned char usb_in_status_read(void) { + unsigned char r = csr_readl(0xe000482cL); + return r; +} +#define CSR_USB_IN_STATUS_IDLE_OFFSET 0 +#define CSR_USB_IN_STATUS_IDLE_SIZE 1 +#define CSR_USB_IN_STATUS_HAVE_OFFSET 4 +#define CSR_USB_IN_STATUS_HAVE_SIZE 1 +#define CSR_USB_IN_STATUS_PEND_OFFSET 5 +#define CSR_USB_IN_STATUS_PEND_SIZE 1 +#define CSR_USB_IN_EV_STATUS_ADDR 0xe0004830L +#define CSR_USB_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_in_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004830L); + return r; +} +static inline void usb_in_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004830L); +} +#define CSR_USB_IN_EV_PENDING_ADDR 0xe0004834L +#define CSR_USB_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_in_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004834L); + return r; +} +static inline void usb_in_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004834L); +} +#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004838L +#define CSR_USB_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004838L); + return r; +} +static inline void usb_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004838L); +} +#define CSR_USB_OUT_DATA_ADDR 0xe000483cL +#define CSR_USB_OUT_DATA_SIZE 1 +static inline unsigned char usb_out_data_read(void) { + unsigned char r = csr_readl(0xe000483cL); + return r; +} +#define CSR_USB_OUT_DATA_DATA_OFFSET 0 +#define CSR_USB_OUT_DATA_DATA_SIZE 8 +#define CSR_USB_OUT_CTRL_ADDR 0xe0004840L +#define CSR_USB_OUT_CTRL_SIZE 1 +static inline unsigned char usb_out_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004840L); + return r; +} +static inline void usb_out_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004840L); +} +#define CSR_USB_OUT_CTRL_EPNO_OFFSET 0 +#define CSR_USB_OUT_CTRL_EPNO_SIZE 4 +#define CSR_USB_OUT_CTRL_ENABLE_OFFSET 4 +#define CSR_USB_OUT_CTRL_ENABLE_SIZE 1 +#define CSR_USB_OUT_CTRL_RESET_OFFSET 5 +#define CSR_USB_OUT_CTRL_RESET_SIZE 1 +#define CSR_USB_OUT_CTRL_STALL_OFFSET 6 +#define CSR_USB_OUT_CTRL_STALL_SIZE 1 +#define CSR_USB_OUT_STATUS_ADDR 0xe0004844L +#define CSR_USB_OUT_STATUS_SIZE 1 +static inline unsigned char usb_out_status_read(void) { + unsigned char r = csr_readl(0xe0004844L); + return r; +} +#define CSR_USB_OUT_STATUS_EPNO_OFFSET 0 +#define CSR_USB_OUT_STATUS_EPNO_SIZE 4 +#define CSR_USB_OUT_STATUS_HAVE_OFFSET 4 +#define CSR_USB_OUT_STATUS_HAVE_SIZE 1 +#define CSR_USB_OUT_STATUS_PEND_OFFSET 5 +#define CSR_USB_OUT_STATUS_PEND_SIZE 1 +#define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004848L +#define CSR_USB_OUT_EV_STATUS_SIZE 1 +static inline unsigned char usb_out_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004848L); + return r; +} +static inline void usb_out_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004848L); +} +#define CSR_USB_OUT_EV_PENDING_ADDR 0xe000484cL +#define CSR_USB_OUT_EV_PENDING_SIZE 1 +static inline unsigned char usb_out_ev_pending_read(void) { + unsigned char r = csr_readl(0xe000484cL); + return r; +} +static inline void usb_out_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe000484cL); +} +#define CSR_USB_OUT_EV_ENABLE_ADDR 0xe0004850L +#define CSR_USB_OUT_EV_ENABLE_SIZE 1 +static inline unsigned char usb_out_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004850L); + return r; +} +static inline void usb_out_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004850L); +} + +#define USB_INTERRUPT 3 + +#endif /* __USB_EPTRI_H_ */ diff --git a/im-tomu_fomu-workshop/riscv-blink/include/usb.h b/im-tomu_fomu-workshop/riscv-blink/include/usb.h new file mode 100644 index 0000000000000000000000000000000000000000..816707b2202e12d408eaebd8702c0870e73339f9 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/include/usb.h @@ -0,0 +1,31 @@ +#ifndef __USB_H +#define __USB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +struct usb_setup_request; + +void usb_isr(void); +void usb_init(void); +void usb_connect(void); +void usb_idle(void); +void usb_disconnect(void); +void usb_setup(const struct usb_setup_request *setup, uint32_t size); +void usb_set_address(uint8_t address); + +void usb_ack_in(uint8_t epno); +void usb_ack_out(uint8_t epno); +void usb_err_in(uint8_t epno); +void usb_err_out(uint8_t epno); + +void usb_send(const void *data, int total_count); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/im-tomu_fomu-workshop/riscv-blink/src/main.c b/im-tomu_fomu-workshop/riscv-blink/src/main.c new file mode 100644 index 0000000000000000000000000000000000000000..869759fd0c8e3ada613ac8dffebb97da6a9106d5 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/main.c @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include + +// Input a value 0 to 255 to get a color value. +// The colours are a transition r - g - b - back to r. +static void color_wheel(uint8_t WheelPos) { + WheelPos = 255 - WheelPos; + uint8_t r, g, b; + if(WheelPos < 85) { + r = 255 - WheelPos * 3; + g = 0; + b = WheelPos * 3; + } + else if(WheelPos < 170) { + WheelPos -= 85; + r = 0; + g = WheelPos * 3; + b = 255 - WheelPos * 3; + } + else { + WheelPos -= 170; + r = WheelPos * 3; + g = 255 - WheelPos * 3; + b = 0; + } + + rgb_set(r, g, b); +} + +void isr(void) { + unsigned int irqs; + + irqs = irq_pending() & irq_getmask(); + + if (irqs & (1 << USB_INTERRUPT)) + usb_isr(); +} + + +int main(void) { + irq_setmask(0); + irq_setie(1); + usb_init(); + rgb_init(); + usb_connect(); + int i = 0; + while (1) { + color_wheel(i++); + msleep(80); + } +} diff --git a/im-tomu_fomu-workshop/riscv-blink/src/rgb.c b/im-tomu_fomu-workshop/riscv-blink/src/rgb.c new file mode 100644 index 0000000000000000000000000000000000000000..7cc3d212007b28c9ce1fef007f16e10afe018eee --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/rgb.c @@ -0,0 +1,73 @@ +#include +#include +#include + +#define BREATHE_ENABLE (1 << 7) +#define BREATHE_EDGE_ON (0 << 6) +#define BREATHE_EDGE_BOTH (1 << 6) +#define BREATHE_MODE_MODULATE (1 << 5) +#define BREATHE_MODE_FIXED (0 << 5) + +// Breathe rate is in 128 ms increments +#define BREATHE_RATE_MS(x) ((((x)+1) / 128 & 7) << 0) + +// Blink on/off time is in 32 ms increments +#define BLINK_TIME_MS(x) (((x)) / 32) + +#define LEDDEN (1 << 7) +#define FR250 (1 << 6) +#define OUTPUL (1 << 5) +#define OUTSKEW (1 << 4) +#define QUICK_STOP (1 << 3) +#define PWM_MODE_LFSR (1 << 2) +#define PWM_MODE_LINEAR (0 << 2) + +void rgb_write(uint8_t value, uint8_t addr) { + rgb_addr_write(addr); + rgb_dat_write(value); +} + +void rgb_init(void) { + // Turn on the RGB block and current enable, as well as enabling led control + rgb_ctrl_write((1 << 0) | (1 << 1) | (1 << 2)); + + // Enable the LED driver, and set 250 Hz mode. + // Also set quick stop, which we'll use to switch patterns quickly. + rgb_write(LEDDEN | FR250 | QUICK_STOP, LEDDCR0); + + // Set clock register to 12 MHz / 64 kHz - 1 + rgb_write((12000000/64000)-1, LEDDBR); + + rgb_write(BLINK_TIME_MS(32), LEDDONR); // Amount of time to stay "on" + rgb_write(BLINK_TIME_MS(0), LEDDOFR); // Amount of time to stay "off" + + rgb_write(BREATHE_ENABLE | BREATHE_MODE_FIXED | BREATHE_RATE_MS(128), LEDDBCRR); + rgb_write(BREATHE_ENABLE | BREATHE_MODE_FIXED | BREATHE_RATE_MS(128), LEDDBCFR); +} + +void rgb_set(uint8_t r, uint8_t g, uint8_t b) { + // Note: the LEDD control registers have arbitrary names that + // do not match up with the LEDD pin outputs. Hence this strange + // mapping. + rgb_write(r, LEDDPWRR); // Blue + rgb_write(g, LEDDPWRG); // Red + rgb_write(b, LEDDPWRB); // Green +} + +// The amount of time to stay off or on +void rgb_on_time(uint8_t ms) { + rgb_write(BLINK_TIME_MS(ms), LEDDONR); // Amount of time to stay "on" +} + +void rgb_off_time(uint8_t ms) { + rgb_write(BLINK_TIME_MS(ms), LEDDOFR); // Amount of time to stay "off" +} + +// The amount of time to breathe in/out +void rgb_in_time(uint8_t ms) { + rgb_write(BREATHE_ENABLE| BREATHE_MODE_FIXED | BREATHE_RATE_MS(ms), LEDDBCRR); +} + +void rgb_out_time(uint8_t ms) { + rgb_write(BREATHE_ENABLE | BREATHE_MODE_FIXED | BREATHE_RATE_MS(ms), LEDDBCFR); +} diff --git a/im-tomu_fomu-workshop/riscv-blink/src/time.c b/im-tomu_fomu-workshop/riscv-blink/src/time.c new file mode 100644 index 0000000000000000000000000000000000000000..aca09c04e2d1de7d8c7a7cda74941c84dbf63774 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/time.c @@ -0,0 +1,43 @@ +#include +#include + +void time_init(void) +{ + int t; + + timer0_en_write(0); + t = 2*SYSTEM_CLOCK_FREQUENCY; + timer0_reload_write(t); + timer0_load_write(t); + timer0_en_write(1); +} + +int elapsed(int *last_event, int period) +{ + int t, dt; + + timer0_update_value_write(1); + t = timer0_reload_read() - timer0_value_read(); + if(period < 0) { + *last_event = t; + return 1; + } + dt = t - *last_event; + if(dt < 0) + dt += timer0_reload_read(); + if((dt > period) || (dt < 0)) { + *last_event = t; + return 1; + } else + return 0; +} + +void msleep(int ms) +{ + timer0_en_write(0); + timer0_reload_write(0); + timer0_load_write(SYSTEM_CLOCK_FREQUENCY/1000*ms); + timer0_en_write(1); + timer0_update_value_write(1); + while(timer0_value_read()) timer0_update_value_write(1); +} \ No newline at end of file diff --git a/im-tomu_fomu-workshop/riscv-blink/src/usb-dev.c b/im-tomu_fomu-workshop/riscv-blink/src/usb-dev.c new file mode 100644 index 0000000000000000000000000000000000000000..1758222f01fae84ce41c78257d3126aa6dc78aee --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/usb-dev.c @@ -0,0 +1,200 @@ +#include +#include +#include +#include + +struct usb_setup_request { + union { + struct { + uint8_t bmRequestType; + uint8_t bRequest; + }; + uint16_t wRequestAndType; + }; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; +}; + +static const uint8_t usb_device_descriptor[] = { + 0x12, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40, + 0x09, 0x12, 0xf0, 0x5b, 0x01, 0x01, 0x01, 0x02, + 0x00, 0x01 +}; + +static const uint8_t usb_config_descriptor[] = { + 0x09, 0x02, 0x12, 0x00, 0x01, 0x01, 0x01, 0x80, + 0x32, 0x09, 0x04, 0x00, 0x00, 0x00, 0xfe, 0x00, + 0x00, 0x02 +}; + +static const uint8_t usb_string0_descriptor[] = { + 0x04, 0x03, 0x09, 0x04 +}; + +static const uint8_t usb_string1_descriptor[] = { + 0x0c, 0x03, 0x46, 0x00, 0x6f, 0x00, 0x6f, 0x00, + 0x73, 0x00, 0x6e, 0x00 +}; + +static const uint8_t usb_string2_descriptor[] = { + 0x16, 0x03, 0x46, 0x00, 0x6f, 0x00, 0x6d, 0x00, + 0x75, 0x00, 0x20, 0x00, 0x42, 0x00, 0x6c, 0x00, + 0x69, 0x00, 0x6e, 0x00, 0x6b, 0x00 +}; + +static const uint8_t usb_bos_descriptor[] = { + 0x05, 0x0f, 0x1d, 0x00, 0x01, 0x18, 0x10, 0x05, + 0x00, 0x38, 0xb6, 0x08, 0x34, 0xa9, 0x09, 0xa0, + 0x47, 0x8b, 0xfd, 0xa0, 0x76, 0x88, 0x15, 0xb6, + 0x65, 0x00, 0x01, 0x02, 0x01, +}; + +static const uint8_t usb_ms_compat_id_descriptor[] = { + 0x28, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x57, 0x49, 0x4e, 0x55, 0x53, 0x42, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +#define MSFT_VENDOR_CODE '~' // Arbitrary, but should be printable ASCII +static const uint8_t usb_string_microsoft[18] = { + 18, 3, 'M','S','F','T','1','0','0', MSFT_VENDOR_CODE, + 0, 0, 0, 0, 0, 0, 0, 0, +}; + + +static uint8_t reply_buffer[8]; +static uint8_t usb_configuration = 0; +static uint8_t data_buffer[64]; + +__attribute__((section(".ramtext"))) +void usb_setup(const struct usb_setup_request *setup, uint32_t size) +{ + const uint8_t *data = NULL; + uint32_t datalen = 0; + uint8_t ep_dir_is_in = setup->bmRequestType >> 7; + + (void)size; + + switch (setup->wRequestAndType) + { + case 0x0500: // SET_ADDRESS + usb_set_address(setup->wValue); + break; + + case 0x0b01: // SET_INTERFACE + break; + + case 0x0900: // SET_CONFIGURATION + usb_configuration = setup->wValue; + break; + + case 0x0880: // GET_CONFIGURATION + reply_buffer[0] = usb_configuration; + datalen = 1; + data = reply_buffer; + break; + + case 0x0080: // GET_STATUS (device) + reply_buffer[0] = 0; + reply_buffer[1] = 0; + datalen = 2; + data = reply_buffer; + break; + + case 0x0082: // GET_STATUS (endpoint) + if (setup->wIndex > 0) + { + usb_err_in(0); + return; + } + reply_buffer[0] = 0; + reply_buffer[1] = 0; + data = reply_buffer; + datalen = 2; + break; + + case 0x0102: // CLEAR_FEATURE (endpoint) + if (setup->wIndex > 0 || setup->wValue != 0) + { + usb_err_out(0); + return; + } + break; + + case 0x0302: // SET_FEATURE (endpoint) + if (setup->wIndex > 0 || setup->wValue != 0) + { + usb_err_out(0); + return; + } + break; + + case 0x0680: // GET_DESCRIPTOR + case 0x0681: + #define CASE_VALUE(match, result) case match: data = result; datalen = sizeof(result); break + switch (setup->wValue) { + CASE_VALUE(0x0100, usb_device_descriptor); + CASE_VALUE(0x0200, usb_config_descriptor); + CASE_VALUE(0x0300, usb_string0_descriptor); + CASE_VALUE(0x0301, usb_string1_descriptor); + CASE_VALUE(0x0302, usb_string2_descriptor); + CASE_VALUE(0x03ee, usb_string_microsoft); + CASE_VALUE(0x0f00, usb_bos_descriptor); + default: usb_err_in(0); return; + } + #undef CASE_VALUE + goto send; + + case (MSFT_VENDOR_CODE << 8) | 0xC0: // Get Microsoft descriptor + case (MSFT_VENDOR_CODE << 8) | 0xC1: + if (setup->wIndex == 0x0004) + { + // Return WCID descriptor + data = usb_ms_compat_id_descriptor; + datalen = sizeof(usb_ms_compat_id_descriptor); + break; + } + usb_err_in(0); + return; + +#ifdef LANDING_PAGE_URL + case (WEBUSB_VENDOR_CODE << 8) | 0xC0: // Get WebUSB descriptor + if (setup->wIndex == 0x0002) + { + if (setup->wValue == 0x0001) + { + data = get_landing_url_descriptor(&datalen); + break; + } + } + usb_err_in(0); + return; +#endif + + default: + usb_err_in(0); + return; + } + +send: + if (data && datalen) { + if (datalen > setup->wLength) + datalen = setup->wLength; + if (datalen > sizeof(data_buffer)) + datalen = sizeof(data_buffer); + memcpy(data_buffer, data, datalen); + usb_send(data_buffer, datalen); + usb_ack_out(0); + } + else { + // Ack the opposite endpoint type + if (ep_dir_is_in) + usb_ack_out(0); + else + usb_ack_in(0); + } + return; +} diff --git a/im-tomu_fomu-workshop/riscv-blink/src/usb-epfifo.c b/im-tomu_fomu-workshop/riscv-blink/src/usb-epfifo.c new file mode 100644 index 0000000000000000000000000000000000000000..09527b264359b8c276f3faebda2f6a13decbf66a --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/usb-epfifo.c @@ -0,0 +1,263 @@ +#include +#include +#include +#include + +// #ifdef CSR_USB_EP_0_OUT_EV_PENDING_ADDR +#if 1 + +#define EP0OUT_BUFFERS 1 +__attribute__((aligned(4))) +static uint8_t usb_ep0out_buffer_len[EP0OUT_BUFFERS]; +static uint8_t usb_ep0out_buffer[EP0OUT_BUFFERS][128]; +static uint8_t usb_ep0out_last_tok[EP0OUT_BUFFERS]; +static uint8_t usb_ep0out_wr_ptr; +static uint8_t usb_ep0out_rd_ptr; +static const int MAX_BYTE_LENGTH = 64; + +static const uint8_t * current_data; +static int current_length; +static int data_offset; +static int data_to_send; +static int next_packet_is_empty; + +static uint8_t new_address; +static int have_new_address; + +// Note that our PIDs are only bits 2 and 3 of the token, +// since all other bits are effectively redundant at this point. +enum USB_PID { + USB_PID_OUT = 0, + USB_PID_SOF = 1, + USB_PID_IN = 2, + USB_PID_SETUP = 3, +}; + +enum epfifo_response { + EPF_ACK = 0, + EPF_NAK = 1, + EPF_NONE = 2, + EPF_STALL = 3, +}; + +#define USB_EV_ERROR 1 +#define USB_EV_PACKET 2 + +// Firmware versions < 1.9 didn't have usb_address_write() +static void usb_set_address_wrapper(uint8_t address) { + if (version_major_read() < 1) + return; + if (version_minor_read() < 9) + return; + usb_address_write(address); +} + +void epfifo_usb_idle(void) { + usb_ep_0_out_ev_enable_write(0); + usb_ep_0_in_ev_enable_write(0); + + // Reject all incoming data, since there is no handler anymore + usb_ep_0_out_respond_write(EPF_NAK); + + // Reject outgoing data, since we don't have any to give. + usb_ep_0_in_respond_write(EPF_NAK); + + irq_setmask(irq_getmask() & ~(1 << USB_INTERRUPT)); +} + +void epfifo_usb_disconnect(void) { + usb_ep_0_out_ev_enable_write(0); + usb_ep_0_in_ev_enable_write(0); + irq_setmask(irq_getmask() & ~(1 << USB_INTERRUPT)); + usb_pullup_out_write(0); + usb_set_address_wrapper(0); +} + +void epfifo_usb_connect(void) { + + usb_ep_0_out_ev_pending_write(usb_ep_0_out_ev_enable_read()); + usb_ep_0_in_ev_pending_write(usb_ep_0_in_ev_pending_read()); + usb_ep_0_out_ev_enable_write(USB_EV_PACKET | USB_EV_ERROR); + usb_ep_0_in_ev_enable_write(USB_EV_PACKET | USB_EV_ERROR); + + // Accept incoming data by default. + //usb_ep_0_out_respond_write(EPF_ACK); + + // Reject outgoing data, since we have none to give yet. + usb_ep_0_in_respond_write(EPF_NAK); + + usb_pullup_out_write(1); + + irq_setmask(irq_getmask() | (1 << USB_INTERRUPT)); +} + +void epfifo_usb_init(void) { + usb_disconnect(); + usb_ep0out_wr_ptr = 0; + usb_ep0out_rd_ptr = 0; +} + +static void process_tx(void) { + + // Don't allow requeueing -- only queue more data if we're + // currently set up to respond NAK. + if (usb_ep_0_in_respond_read() != EPF_NAK) { + return; + } + + // Prevent us from double-filling the buffer. + if (!usb_ep_0_in_ibuf_empty_read()) { + return; + } + + if (!current_data || !current_length) { + return; + } + + data_offset += data_to_send; + + data_to_send = current_length - data_offset; + + // Clamp the data to the maximum packet length + if (data_to_send > MAX_BYTE_LENGTH) { + data_to_send = MAX_BYTE_LENGTH; + next_packet_is_empty = 0; + } + else if (data_to_send == MAX_BYTE_LENGTH) { + next_packet_is_empty = 1; + } + else if (next_packet_is_empty) { + next_packet_is_empty = 0; + data_to_send = 0; + } + else if (current_data == NULL || data_to_send <= 0) { + next_packet_is_empty = 0; + current_data = NULL; + current_length = 0; + data_offset = 0; + data_to_send = 0; + return; + } + + int this_offset; + for (this_offset = data_offset; this_offset < (data_offset + data_to_send); this_offset++) { + usb_ep_0_in_ibuf_head_write(current_data[this_offset]); + } + usb_ep_0_in_respond_write(EPF_ACK); + return; +} + +void epfifo_usb_send(const void *data, int total_count) { + + while ((current_length || current_data) && usb_ep_0_in_respond_read() != EPF_NAK) + process_tx(); + current_data = (uint8_t *)data; + current_length = total_count; + data_offset = 0; + data_to_send = 0; + process_tx(); +} + +void epfifo_usb_wait_for_send_done(void) { + while (current_data && current_length) + process_tx(); + while ((usb_ep_0_in_dtb_read() & 1) == 1) + ; +} + +void epfifo_usb_isr(void) { + uint8_t ep0o_pending = usb_ep_0_out_ev_pending_read(); + uint8_t ep0i_pending = usb_ep_0_in_ev_pending_read(); + + // We just got an "IN" token. Send data if we have it. + if (ep0i_pending) { + usb_ep_0_in_respond_write(EPF_NAK); + if (have_new_address) { + have_new_address = 0; + usb_set_address_wrapper(new_address); + } + usb_ep_0_in_ev_pending_write(ep0i_pending); + } + + // We got an OUT or a SETUP packet. Copy it to usb_ep0out_buffer + // and clear the "pending" bit. + if (ep0o_pending) { + uint8_t last_tok = usb_ep_0_out_last_tok_read(); + uint32_t obuf_len = 0; + uint8_t obuf[67]; + if (!usb_ep_0_out_obuf_empty_read()) { + while (!usb_ep_0_out_obuf_empty_read()) { + obuf[obuf_len++] = usb_ep_0_out_obuf_head_read(); + usb_ep_0_out_obuf_head_write(0); + } + } + + if (obuf_len >= 2) + obuf_len -= 2 /* Strip off CRC16 */; + + if (last_tok == USB_PID_SETUP) { + usb_ep_0_in_dtb_write(1); + data_offset = 0; + current_length = 0; + current_data = NULL; + usb_setup((const void *)obuf, obuf_len); + } + + //usb_ep_0_out_respond_write(EPF_ACK); + usb_ep_0_out_ev_pending_write(ep0o_pending); + } + + process_tx(); + return; +} + +void epfifo_usb_ack_in(uint8_t epno) { + (void)epno; + usb_ep_0_in_respond_write(EPF_ACK); +} + +void epfifo_usb_ack_out(uint8_t epno) { + (void)epno; + usb_ep_0_out_respond_write(EPF_ACK); +} + +void epfifo_usb_err_in(uint8_t epno) { + (void)epno; + usb_ep_0_in_respond_write(EPF_STALL); +} + +void epfifo_usb_err_out(uint8_t epno) { + (void)epno; + usb_ep_0_out_respond_write(EPF_STALL); +} + +int epfifo_usb_recv(void *buffer, unsigned int buffer_len) { + + // Set the OUT response to ACK, since we are in a position to receive data now. + usb_ep_0_out_respond_write(EPF_ACK); + while (1) { + if (usb_ep0out_rd_ptr != usb_ep0out_wr_ptr) { + if (usb_ep0out_last_tok[usb_ep0out_rd_ptr] == USB_PID_OUT) { + unsigned int ep0_buffer_len = usb_ep0out_buffer_len[usb_ep0out_rd_ptr]; + if (ep0_buffer_len < buffer_len) + buffer_len = ep0_buffer_len; + // usb_ep0out_buffer_len[usb_ep0out_rd_ptr] = 0; + memcpy(buffer, (void *)&usb_ep0out_buffer[usb_ep0out_rd_ptr], buffer_len); + usb_ep0out_rd_ptr = (usb_ep0out_rd_ptr + 1) & (EP0OUT_BUFFERS-1); + return buffer_len; + } + else if (usb_ep0out_last_tok[usb_ep0out_rd_ptr] == USB_PID_SETUP) { + return -1; + } + usb_ep0out_rd_ptr = (usb_ep0out_rd_ptr + 1) & (EP0OUT_BUFFERS-1); + } + } + return 0; +} + +void epfifo_usb_set_address(uint8_t _new_address) { + new_address = _new_address; + have_new_address = 1; +} + +#endif /* CSR_USB_EP_0_OUT_EV_PENDING_ADDR */ diff --git a/im-tomu_fomu-workshop/riscv-blink/src/usb-eptri.c b/im-tomu_fomu-workshop/riscv-blink/src/usb-eptri.c new file mode 100644 index 0000000000000000000000000000000000000000..25841393d6894bd0d5789699c32c3d05762f77c9 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/usb-eptri.c @@ -0,0 +1,314 @@ +#include +#include +#include +#include +#include + +__attribute__((aligned(4))) + +//__attribute__((used, aligned(4))) +//static uint8_t volatile previous_setup_packet[10]; +//__attribute__((used)) +//volatile uint32_t previous_setup_length; + +static uint8_t volatile out_buffer_length; +static uint8_t volatile out_buffer[128]; +static uint8_t volatile out_ep; +static uint8_t volatile out_have; +static const int max_byte_length = 64; + +static const uint8_t * volatile current_data; +static volatile int current_length; +static volatile uint8_t current_epno; +static volatile int data_offset; +static volatile int data_to_send; +static int next_packet_is_empty; + +__attribute__((used)) +const uint8_t * last_data; +__attribute__((used)) +int last_length; +__attribute__((used)) +int last_epno; +__attribute__((used)) +int last_data_offset; +__attribute__((used)) +int last_data_to_send; +__attribute__((used)) +int last_packet_was_empty; + +static uint8_t next_address = 0; + +#define USB_EV_ERROR 1 +#define USB_EV_PACKET 2 + +void eptri_usb_idle(void) { + irq_setmask(irq_getmask() & ~(1 << USB_INTERRUPT)); +} + +void eptri_usb_disconnect(void) { + irq_setmask(irq_getmask() & ~(1 << USB_INTERRUPT)); + usb_pullup_out_write(0); +} + +void eptri_usb_connect(void) { + usb_setup_ev_pending_write(usb_setup_ev_pending_read()); + usb_in_ev_pending_write(usb_in_ev_pending_read()); + usb_out_ev_pending_write(usb_out_ev_pending_read()); + usb_setup_ev_enable_write(3); + usb_in_ev_enable_write(1); + usb_out_ev_enable_write(1); + + // Reset the IN handler + usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); + + // Reset the SETUP handler + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_RESET_OFFSET); + + // Reset the OUT handler + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); + + // Accept incoming data by default. + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); + + usb_address_write(0); + + // Turn on the external pullup + usb_pullup_out_write(1); + + // Unmask the interrupt so we can respond to interrupts + irq_setmask(irq_getmask() | (1 << USB_INTERRUPT)); +} + +void eptri_usb_init(void) { + out_buffer_length = 0; + usb_pullup_out_write(0); + usb_address_write(0); + usb_out_ctrl_write(0); + + usb_setup_ev_enable_write(0); + usb_in_ev_enable_write(0); + usb_out_ev_enable_write(0); + + // Reset the IN handler + usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); + + // Reset the SETUP handler + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_RESET_OFFSET); + + // Reset the OUT handler + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); + + return; +} + +static void process_tx(void) { + + // Don't allow requeueing -- only queue more data if the system is idle. + if (!(usb_in_status_read() & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) { + return; + } + + // Don't send empty data + if (!current_data || !current_length) { + return; + } + + last_data_offset = data_offset; + data_offset += data_to_send; + + last_data_to_send = data_to_send; + data_to_send = current_length - data_offset; + + // Clamp the data to the maximum packet length + if (data_to_send > max_byte_length) { + last_data_to_send = data_to_send; + data_to_send = max_byte_length; + last_packet_was_empty = next_packet_is_empty; + next_packet_is_empty = 0; + } + else if (data_to_send == max_byte_length) { + last_packet_was_empty = next_packet_is_empty; + next_packet_is_empty = 1; + } + else if (next_packet_is_empty) { + last_packet_was_empty = next_packet_is_empty; + next_packet_is_empty = 0; + + last_data_to_send = data_to_send; + data_to_send = 0; + } + else if (current_data == NULL || data_to_send <= 0) { + last_packet_was_empty = next_packet_is_empty; + next_packet_is_empty = 0; + + last_data = current_data; + last_length = current_length; + last_data_offset = data_offset; + last_data_to_send = data_to_send; + + current_data = NULL; + current_length = 0; + data_offset = 0; + data_to_send = 0; + return; + } + + // We have more data to send, so fill the buffer + int this_offset; + for (this_offset = data_offset; this_offset < (data_offset + data_to_send); this_offset++) { + usb_in_data_write(current_data[this_offset]); + } + + // Updating the epno queues the data + usb_in_ctrl_write(current_epno & 0xf); + return; +} + +static void process_rx(void) { + // If we already have data in our buffer, don't do anything. + if (out_have) + return; + + // If there isn't any data in the FIFO, don't do anything. + if (!(usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET))) + return; + + out_have = 1; + out_ep = (usb_out_status_read() >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; + out_buffer_length = 0; + while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { + out_buffer[out_buffer_length++] = usb_out_data_read(); + } + + // Strip off the CRC16 that's at the end of the buffer + if (out_buffer_length >= 2) + out_buffer_length -= 2; +} + +void eptri_usb_send(const void *data, int total_count) { + uint8_t epno = 0; + while ((current_length || current_data) && !(usb_in_status_read() & 2)) + process_tx(); + last_epno = current_epno; + + current_data = (uint8_t *)data; + current_length = total_count; + current_epno = epno; + data_offset = 0; + data_to_send = 0; + process_tx(); +} + +void eptri_usb_wait_for_send_done(void) { + while (current_data && current_length) + ; + while (usb_in_status_read() & (1 << CSR_USB_IN_STATUS_HAVE_OFFSET)) + ; +} + +void eptri_usb_isr(void) { + uint8_t setup_packet[10]; + uint32_t setup_length; + uint8_t setup_pending = usb_setup_ev_pending_read(); + uint8_t in_pending = usb_in_ev_pending_read(); + uint8_t out_pending = usb_out_ev_pending_read(); + + // Clear all interrupts before we handle them + usb_setup_ev_pending_write(setup_pending); + usb_in_ev_pending_write(in_pending); + usb_out_ev_pending_write(out_pending); + + // USB reset event + if (setup_pending & 2) { + out_buffer_length = 0; + out_have = 0; + current_data = NULL; + current_length = 0; + usb_connect(); + return; + } + + // We got a SETUP packet. Copy it to the setup buffer and clear + // the "pending" bit. + if (setup_pending & 1) { +// previous_setup_length = setup_length; +// memcpy((void *)previous_setup_packet, (void *)setup_packet, sizeof(setup_packet)); + + setup_length = 0; + memset((void *)setup_packet, 0, sizeof(setup_packet)); + while (usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET)) { + setup_packet[setup_length++] = usb_setup_data_read(); + } + + // If we have 8 bytes, that's a full SETUP packet. + // Otherwise, it was an RX error. + if (setup_length == 10) { + usb_setup((const struct usb_setup_request *)setup_packet, 8); + } + } + + // An "IN" transaction just completed. + if (in_pending) { + // Process more data to send, if we have any. + process_tx(); + + // If next_address is nonzero, then this is the completion of + // the IN packet that follows as the final ACK. This means + // we're free to set our address now. + if (next_address) { + usb_address_write(next_address); + next_address = 0; + } + } + + // An "OUT" transaction just completed so we have new data. + // (But only if we can accept the data) + if (out_pending) { + process_rx(); + } + + return; +} + +void eptri_usb_ack_in(uint8_t ep) { + (void)ep; + // Writing to this register queues a transfer + usb_in_ctrl_write(0); +} + +void eptri_usb_ack_out(uint8_t ep) { + (void)ep; + out_have = 0; + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); +} + +void eptri_usb_err_in(uint8_t ep) { + (void)ep; + usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_STALL_OFFSET); +} + +void eptri_usb_err_out(uint8_t ep) { + (void)ep; + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_STALL_OFFSET); +} + +int eptri_usb_recv(void *buffer, int buffer_len) { + // Set the OUT response to ACK, since we are in a position to receive data now. + if (out_have) { + usb_ack_out(0); + } + while (1) { + if (out_have) { + if (buffer_len > out_buffer_length) + buffer_len = out_buffer_length; + memcpy(buffer, (void *)out_buffer, buffer_len); + usb_ack_out(0); + return buffer_len; + } + } +} + +void eptri_usb_set_address(uint8_t new_address) { + next_address = new_address; +} diff --git a/im-tomu_fomu-workshop/riscv-blink/src/usb.c b/im-tomu_fomu-workshop/riscv-blink/src/usb.c new file mode 100644 index 0000000000000000000000000000000000000000..a9245a7d53a8f47c024348c64500d5b76802863e --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-blink/src/usb.c @@ -0,0 +1,106 @@ +#include +#include +#include + +struct usb_setup_request; + +void epfifo_usb_isr(void); +void epfifo_usb_init(void); +void epfifo_usb_connect(void); +void epfifo_usb_idle(void); +void epfifo_usb_disconnect(void); +void epfifo_usb_set_address(uint8_t address); +void epfifo_usb_ack_in(uint8_t epno); +void epfifo_usb_ack_out(uint8_t epno); +void epfifo_usb_err_in(uint8_t epno); +void epfifo_usb_err_out(uint8_t epno); +void epfifo_usb_send(const void *data, int total_count); + +void eptri_usb_isr(void); +void eptri_usb_init(void); +void eptri_usb_connect(void); +void eptri_usb_idle(void); +void eptri_usb_disconnect(void); +void eptri_usb_set_address(uint8_t address); +void eptri_usb_ack_in(uint8_t epno); +void eptri_usb_ack_out(uint8_t epno); +void eptri_usb_err_in(uint8_t epno); +void eptri_usb_err_out(uint8_t epno); +void eptri_usb_send(const void *data, int total_count); + +void usb_isr(void) { + if (version_major_read() == 2) + eptri_usb_isr(); + else + epfifo_usb_isr(); +} + +void usb_init(void) { + if (version_major_read() == 2) + eptri_usb_init(); + else + epfifo_usb_init(); +} + +void usb_connect(void) { + if (version_major_read() == 2) + eptri_usb_connect(); + else + epfifo_usb_connect(); +} + +void usb_idle(void) { + if (version_major_read() == 2) + eptri_usb_idle(); + else + epfifo_usb_idle(); +} + +void usb_disconnect(void) { + if (version_major_read() == 2) + eptri_usb_disconnect(); + else + epfifo_usb_disconnect(); +} + +void usb_set_address(uint8_t address) { + if (version_major_read() == 2) + eptri_usb_set_address(address); + else + epfifo_usb_set_address(address); +} + +void usb_ack_in(uint8_t epno) { + if (version_major_read() == 2) + eptri_usb_ack_in(epno); + else + epfifo_usb_ack_in(epno); +} + +void usb_ack_out(uint8_t epno) { + if (version_major_read() == 2) + eptri_usb_ack_out(epno); + else + epfifo_usb_ack_out(epno); +} + +void usb_err_in(uint8_t epno) { + if (version_major_read() == 2) + eptri_usb_err_in(epno); + else + epfifo_usb_err_in(epno); +} + +void usb_err_out(uint8_t epno) { + if (version_major_read() == 2) + eptri_usb_err_out(epno); + else + epfifo_usb_err_out(epno); +} + +void usb_send(const void *data, int total_count) { + if (version_major_read() == 2) + eptri_usb_send(data, total_count); + else + epfifo_usb_send(data, total_count); +} diff --git a/im-tomu_fomu-workshop/riscv-rust-blink/src/c/irq.c b/im-tomu_fomu-workshop/riscv-rust-blink/src/c/irq.c new file mode 100644 index 0000000000000000000000000000000000000000..433e5912d0a297c4ce35d47b853232e7ef1e453e --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-rust-blink/src/c/irq.c @@ -0,0 +1,22 @@ +#include +#include +#include +#include + + +void isr(void) { + unsigned int irqs; + + irqs = irq_pending() & irq_getmask(); + + if (irqs & (1 << USB_INTERRUPT)) { + usb_isr(); + } + +} + +void irq_init() { + irq_setmask(0); + irq_setie(1); + csrw(mie, 0x880); +} \ No newline at end of file diff --git a/im-tomu_fomu-workshop/riscv-zig-blink/README.md b/im-tomu_fomu-workshop/riscv-zig-blink/README.md new file mode 100644 index 0000000000000000000000000000000000000000..39c330c5fb4f5e756c3335912571231c46879a07 --- /dev/null +++ b/im-tomu_fomu-workshop/riscv-zig-blink/README.md @@ -0,0 +1,14 @@ +# riscv-zig-blink + +Written against zig 0.9.0 + +You can obtain the zig compiler via https://ziglang.org/download/ +e.g. a linux user might run: +``` +curl -L https://ziglang.org/download/0.9.0/zig-linux-x86_64-0.9.0.tar.xz | tar -xJf - +alias zig=./zig-linux-x86_64-0.9.0/zig +``` + +Run `zig build --help` from this directory for usage and options. + +`zig build run -Drelease` will compile the demo and and run it on your connected FOMU. diff --git a/kunalg123_vsdflow/procs/call_timer.tcl b/kunalg123_vsdflow/procs/call_timer.tcl new file mode 100644 index 0000000000000000000000000000000000000000..2446ffa0c77bfd329956b9af085a3541ff9117b8 --- /dev/null +++ b/kunalg123_vsdflow/procs/call_timer.tcl @@ -0,0 +1,227 @@ +if {$enable_prelayout_timing == 1} { + set prefix "prelayout" + } else { + set prefix "postlayout" +} + +set inputConfFile $OutputDirectory/$DesignName.${prefix}.conf +set outputReportFileName $OutputDirectory/$DesignName.${prefix}.timing.rpt +puts "\nInfo: Timing Analysis Started...." +puts "\nInfo: Initializing number of threads, libraries, sdc, verilog netlist path..." +source $proc_dir/reopenStdout.proc +source $proc_dir/set_num_threads.proc +reopenStdout $OutputDirectory/$DesignName.${prefix}.conf +#set_multi_cpu_usage -localCpu 1 + +source $proc_dir/read_lib.proc +read_lib -min $EarlyLibraryPath + +read_lib -max $LateLibraryPath + +source $proc_dir/read_verilog.proc +read_verilog $OutputDirectory/$DesignName.final.synth.v + +#source $proc_dir/read_sdc.proc +#read_sdc $OutputDirectory/$DesignName.sdc + +reopenStdout /dev/tty + + +if {$enable_prelayout_timing == 1} { + puts "\nInfo: enable_prelayout_timing is $enable_prelayout_timing. Enabling zero-wire load parasitics" + set spef_file [open $OutputDirectory/synthesis/$DesignName.${prefix}.spef w] +puts $spef_file "*SPEF \"IEEE 1481-1998\" " +puts $spef_file "*DESIGN \"$DesignName\" " +puts $spef_file "*DATE \"Tue Sep 25 11:51:50 2012\" " +puts $spef_file "*VENDOR \"TAU 2015 Contest\" " +puts $spef_file "*PROGRAM \"Benchmark Parasitic Generator\" " +puts $spef_file "*VERSION \"0.0\" " +puts $spef_file "*DESIGN_FLOW \"NETLIST_TYPE_VERILOG\" " +puts $spef_file "*DIVIDER / " +puts $spef_file "*DELIMITER : " +puts $spef_file "*BUS_DELIMITER \[ \] " +puts $spef_file "*T_UNIT 1 PS " +puts $spef_file "*C_UNIT 1 FF " +puts $spef_file "*R_UNIT 1 KOHM " +puts $spef_file "*L_UNIT 1 UH " +close $spef_file +} + +set conf_file [open $OutputDirectory/$DesignName.${prefix}.conf a] +puts $conf_file "link_design $DesignName" +puts $conf_file "read_sdc $OutputDirectory/$DesignName.sdc" +#puts $conf_file "cppr -enable" +if {$enable_prelayout_timing == 1} { + puts $conf_file "read_spef $OutputDirectory/synthesis/$DesignName.${prefix}.spef" + } else { + puts $conf_file "read_spef $OutputDirectory/synthesis/$DesignName.spef" + } +puts $conf_file "report_checks -group_count 10000 -unique_paths_to_endpoint -format full_clock_expanded" +puts $conf_file "exit" +#puts $conf_file "report_wns " +#puts $conf_file "report_path -num_paths 10000 " +#puts $conf_file "dump_timer " +#puts $conf_file "dump_slack " +close $conf_file + + + + +puts "\nInfo: Timing Analysis Started...." +puts "\nInfo: Initializing number of threads, libraries, sdc, verilog netlist path..." +puts "input conf file is $inputConfFile" +puts "output report file is $outputReportFileName" +#set time_elapsed_in_us [time {exec -ignorestderr >& $outputReportFileName OpenTimer -i $inputConfFile}] +set time_elapsed_in_us [time {exec sta $inputConfFile >& $outputReportFileName}] +set time_elapsed_in_sec "[expr {[lindex $time_elapsed_in_us 0]/100000}]sec" +puts "\nInfo: STA finished in $time_elapsed_in_sec seconds" +puts "\nInfo: Refer to $outputReportFileName for warnings and errors" +set tcl_precision 3 + +#-----find worst output violation------# +if {$generate_report == 1} { +set worst_RAT_slack "-" +set report_file [open $outputReportFileName r] +set pattern {RAT} +while {[gets $report_file line] != -1} { + if {[regexp $pattern $line]} { + set worst_RAT_slack "[lindex [join $line " "] 3] ps" + break + } else { + continue + } +} +close $report_file + +#-----find number of output violation------# +set report_file [open $outputReportFileName r] +set count 0 +while {[gets $report_file line] != -1} { + incr count [regexp -all -- $pattern $line] +} +set Number_output_violations $count +close $report_file + +#-----find worst setup violation------# +set worst_negative_setup_slack "-" +set report_file [open $outputReportFileName r] +set pattern {Setup} +while {[gets $report_file line] != -1} { + if {[regexp $pattern $line]} { + set worst_negative_setup_slack "[lindex [join $line " "] 3]" + break + } else { + continue + } +} +close $report_file + + +#-----find number of setup violation------# +set report_file [open $outputReportFileName r] +set count 0 +while {[gets $report_file line] != -1} { + incr count [regexp -all -- $pattern $line] +} +set Number_of_setup_violations $count +close $report_file + +#-----find worst hold violation------# +set worst_negative_hold_slack "-" +set report_file [open $outputReportFileName r] +set pattern {Hold} +while {[gets $report_file line] != -1} { + if {[regexp $pattern $line]} { + set worst_negative_hold_slack "[lindex [join $line " "] 3] ps" + break + } else { + continue + } +} +close $report_file + +#-----find number of hold violation------# +set report_file [open $outputReportFileName r] +set count 0 +while {[gets $report_file line] != -1} { + incr count [regexp -all -- $pattern $line] +} +set Number_of_hold_violations $count +close $report_file + +#-----find number of instance------# +set pattern {Num of gates} +set report_file [open $outputReportFileName r] +while {[gets $report_file line] != -1} { + if {[regexp -all -- $pattern $line]} { + set Instance_count [lindex [join $line " "] 4 ] + break + } else { + continue + } +} +close $report_file + +puts "\n" +puts "****Please refer to qor file in below path ****" +puts $qorReportName + +if {$lib_mismatch_err == 1} { +set pattern {Slack} +set vesta_file [open $OutputDirectory/$DesignName.vesta.log] + while {[gets $vesta_file line] != -1} { + if {[regexp -all -- $pattern $line]} { + set worst_negative_setup_slack [string map {"ps" ""} [lindex [split $line "="] 1]] + break + } else { + continue + } + } +close $vesta_file +} + +set operating_period [expr {$clock_period - $worst_negative_setup_slack}] +set operating_frequency [expr {1000000/$operating_period}] +set formatStr {%15s%15s%15s%15s%15s%15s%15s%15s%15s} + +puts [format $formatStr "-----------" "-------" "--------------" "---------" "---------" "--------" "--------" "-------" "-------"] +puts [format $formatStr "Design Name" "Runtime" "Instance Count" "WNS setup" "FEP Setup" "WNS Hold" "FEP Hold" "WNS RAT" "FEP RAT"] +puts [format $formatStr "-----------" "-------" "--------------" "---------" "---------" "--------" "--------" "-------" "-------"] + +foreach design_name $DesignName runtime $time_elapsed_in_sec instance_count $Instance_count wns_setup $worst_negative_setup_slack fep_setup $Number_of_setup_violations wns_hold $worst_negative_hold_slack fep_hold $Number_of_hold_violations wns_rat $worst_RAT_slack fep_rat $Number_output_violations { + puts [format $formatStr $design_name $runtime $instance_count $wns_setup $fep_setup $wns_hold $fep_hold $wns_rat $fep_rat] +} + +puts [format $formatStr "-----------" "-------" "--------------" "---------" "---------" "--------" "--------" "-------" "-------"] +puts "\n" + +set prelayout_timing_rpt [open $qorReportName w] +puts "Design Name = $DesignName" +puts "Runtime = $time_elapsed_in_sec" +puts "Instance Count = $Instance_count" +puts "WNS setup = $worst_negative_setup_slack ps" +puts "FEP Setup = $Number_of_setup_violations" +puts "Clock period = $clock_period ps" +puts "Operating Frequency = $operating_frequency MHz" +puts "WNS Hold = $worst_negative_hold_slack" +puts "FEP Hold = $Number_of_hold_violations" +puts "WNS RAT = $worst_RAT_slack" +puts "FEP RAT = $Number_output_violations" +puts "\n" + +puts $prelayout_timing_rpt "Design Name = $DesignName" +puts $prelayout_timing_rpt "Runtime = $time_elapsed_in_sec" +puts $prelayout_timing_rpt "Instance Count = $Instance_count" +puts $prelayout_timing_rpt "WNS setup = $worst_negative_setup_slack ps" +puts $prelayout_timing_rpt "FEP Setup = $Number_of_setup_violations" +puts $prelayout_timing_rpt "Clock period = $clock_period ps" +puts $prelayout_timing_rpt "Operating Frequency = $operating_frequency MHz" +puts $prelayout_timing_rpt "WNS Hold = $worst_negative_hold_slack" +puts $prelayout_timing_rpt "FEP Hold = $Number_of_hold_violations" +puts $prelayout_timing_rpt "WNS RAT = $worst_RAT_slack" +puts $prelayout_timing_rpt "FEP RAT = $Number_output_violations" +puts "\n" +close $prelayout_timing_rpt + +} + diff --git a/kunalg123_vsdflow/verilog/picorv32.v b/kunalg123_vsdflow/verilog/picorv32.v new file mode 100644 index 0000000000000000000000000000000000000000..8611fd4ed52a745dd92ff4c97a6021910b3b8c29 --- /dev/null +++ b/kunalg123_vsdflow/verilog/picorv32.v @@ -0,0 +1,2980 @@ +/* + * PicoRV32 -- A Small RISC-V (RV32I) Processor Core + * + * Copyright (C) 2015 Clifford Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +`timescale 1 ns / 1 ps +// `default_nettype none +// `define DEBUGNETS +// `define DEBUGREGS +// `define DEBUGASM +// `define DEBUG + +`ifdef DEBUG + `define debug(debug_command) debug_command +`else + `define debug(debug_command) +`endif + +`ifdef FORMAL + `define FORMAL_KEEP (* keep *) + `define assert(assert_expr) assert(assert_expr) +`else + `ifdef DEBUGNETS + `define FORMAL_KEEP (* keep *) + `else + `define FORMAL_KEEP + `endif + `define assert(assert_expr) empty_statement +`endif + +// uncomment this for register file in extra module +// `define PICORV32_REGS picorv32_regs + +// this macro can be used to check if the verilog files in your +// design are read in the correct order. +`define PICORV32_V + + +/*************************************************************** + * picorv32 + ***************************************************************/ + +module picorv32 #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] LATCHED_MEM_RDATA = 0, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output reg trap, + + output reg mem_valid, + output reg mem_instr, + input mem_ready, + + output reg [31:0] mem_addr, + output reg [31:0] mem_wdata, + output reg [ 3:0] mem_wstrb, + input [31:0] mem_rdata, + + // Look-Ahead Interface + output mem_la_read, + output mem_la_write, + output [31:0] mem_la_addr, + output reg [31:0] mem_la_wdata, + output reg [ 3:0] mem_la_wstrb, + + // Pico Co-Processor Interface (PCPI) + output reg pcpi_valid, + output reg [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ Interface + input [31:0] irq, + output reg [31:0] eoi, + +`ifdef RISCV_FORMAL + output reg rvfi_valid, + output reg [63:0] rvfi_order, + output reg [31:0] rvfi_insn, + output reg rvfi_trap, + output reg rvfi_halt, + output reg rvfi_intr, + output reg [ 1:0] rvfi_mode, + output reg [ 4:0] rvfi_rs1_addr, + output reg [ 4:0] rvfi_rs2_addr, + output reg [31:0] rvfi_rs1_rdata, + output reg [31:0] rvfi_rs2_rdata, + output reg [ 4:0] rvfi_rd_addr, + output reg [31:0] rvfi_rd_wdata, + output reg [31:0] rvfi_pc_rdata, + output reg [31:0] rvfi_pc_wdata, + output reg [31:0] rvfi_mem_addr, + output reg [ 3:0] rvfi_mem_rmask, + output reg [ 3:0] rvfi_mem_wmask, + output reg [31:0] rvfi_mem_rdata, + output reg [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output reg trace_valid, + output reg [35:0] trace_data +); + localparam integer irq_timer = 0; + localparam integer irq_ebreak = 1; + localparam integer irq_buserror = 2; + + localparam integer irqregs_offset = ENABLE_REGS_16_31 ? 32 : 16; + localparam integer regfile_size = (ENABLE_REGS_16_31 ? 32 : 16) + 4*ENABLE_IRQ*ENABLE_IRQ_QREGS; + localparam integer regindex_bits = (ENABLE_REGS_16_31 ? 5 : 4) + ENABLE_IRQ*ENABLE_IRQ_QREGS; + + localparam WITH_PCPI = ENABLE_PCPI || ENABLE_MUL || ENABLE_FAST_MUL || ENABLE_DIV; + + localparam [35:0] TRACE_BRANCH = {4'b 0001, 32'b 0}; + localparam [35:0] TRACE_ADDR = {4'b 0010, 32'b 0}; + localparam [35:0] TRACE_IRQ = {4'b 1000, 32'b 0}; + + reg [63:0] count_cycle, count_instr; + reg [31:0] reg_pc, reg_next_pc, reg_op1, reg_op2, reg_out; + reg [4:0] reg_sh; + + reg [31:0] next_insn_opcode; + reg [31:0] dbg_insn_opcode; + reg [31:0] dbg_insn_addr; + + wire dbg_mem_valid = mem_valid; + wire dbg_mem_instr = mem_instr; + wire dbg_mem_ready = mem_ready; + wire [31:0] dbg_mem_addr = mem_addr; + wire [31:0] dbg_mem_wdata = mem_wdata; + wire [ 3:0] dbg_mem_wstrb = mem_wstrb; + wire [31:0] dbg_mem_rdata = mem_rdata; + + assign pcpi_rs1 = reg_op1; + assign pcpi_rs2 = reg_op2; + + wire [31:0] next_pc; + + reg irq_delay; + reg irq_active; + reg [31:0] irq_mask; + reg [31:0] irq_pending; + reg [31:0] timer; + +`ifndef PICORV32_REGS + reg [31:0] cpuregs [0:regfile_size-1]; + + integer i; + initial begin + if (REGS_INIT_ZERO) begin + for (i = 0; i < regfile_size; i = i+1) + cpuregs[i] = 0; + end + end +`endif + + task empty_statement; + // This task is used by the `assert directive in non-formal mode to + // avoid empty statement (which are unsupported by plain Verilog syntax). + begin end + endtask + +`ifdef DEBUGREGS + wire [31:0] dbg_reg_x0 = 0; + wire [31:0] dbg_reg_x1 = cpuregs[1]; + wire [31:0] dbg_reg_x2 = cpuregs[2]; + wire [31:0] dbg_reg_x3 = cpuregs[3]; + wire [31:0] dbg_reg_x4 = cpuregs[4]; + wire [31:0] dbg_reg_x5 = cpuregs[5]; + wire [31:0] dbg_reg_x6 = cpuregs[6]; + wire [31:0] dbg_reg_x7 = cpuregs[7]; + wire [31:0] dbg_reg_x8 = cpuregs[8]; + wire [31:0] dbg_reg_x9 = cpuregs[9]; + wire [31:0] dbg_reg_x10 = cpuregs[10]; + wire [31:0] dbg_reg_x11 = cpuregs[11]; + wire [31:0] dbg_reg_x12 = cpuregs[12]; + wire [31:0] dbg_reg_x13 = cpuregs[13]; + wire [31:0] dbg_reg_x14 = cpuregs[14]; + wire [31:0] dbg_reg_x15 = cpuregs[15]; + wire [31:0] dbg_reg_x16 = cpuregs[16]; + wire [31:0] dbg_reg_x17 = cpuregs[17]; + wire [31:0] dbg_reg_x18 = cpuregs[18]; + wire [31:0] dbg_reg_x19 = cpuregs[19]; + wire [31:0] dbg_reg_x20 = cpuregs[20]; + wire [31:0] dbg_reg_x21 = cpuregs[21]; + wire [31:0] dbg_reg_x22 = cpuregs[22]; + wire [31:0] dbg_reg_x23 = cpuregs[23]; + wire [31:0] dbg_reg_x24 = cpuregs[24]; + wire [31:0] dbg_reg_x25 = cpuregs[25]; + wire [31:0] dbg_reg_x26 = cpuregs[26]; + wire [31:0] dbg_reg_x27 = cpuregs[27]; + wire [31:0] dbg_reg_x28 = cpuregs[28]; + wire [31:0] dbg_reg_x29 = cpuregs[29]; + wire [31:0] dbg_reg_x30 = cpuregs[30]; + wire [31:0] dbg_reg_x31 = cpuregs[31]; +`endif + + // Internal PCPI Cores + + wire pcpi_mul_wr; + wire [31:0] pcpi_mul_rd; + wire pcpi_mul_wait; + wire pcpi_mul_ready; + + wire pcpi_div_wr; + wire [31:0] pcpi_div_rd; + wire pcpi_div_wait; + wire pcpi_div_ready; + + reg pcpi_int_wr; + reg [31:0] pcpi_int_rd; + reg pcpi_int_wait; + reg pcpi_int_ready; + + generate if (ENABLE_FAST_MUL) begin + picorv32_pcpi_fast_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else if (ENABLE_MUL) begin + picorv32_pcpi_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else begin + assign pcpi_mul_wr = 0; + assign pcpi_mul_rd = 32'bx; + assign pcpi_mul_wait = 0; + assign pcpi_mul_ready = 0; + end endgenerate + + generate if (ENABLE_DIV) begin + picorv32_pcpi_div pcpi_div ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_div_wr ), + .pcpi_rd (pcpi_div_rd ), + .pcpi_wait (pcpi_div_wait ), + .pcpi_ready(pcpi_div_ready ) + ); + end else begin + assign pcpi_div_wr = 0; + assign pcpi_div_rd = 32'bx; + assign pcpi_div_wait = 0; + assign pcpi_div_ready = 0; + end endgenerate + + always @* begin + pcpi_int_wr = 0; + pcpi_int_rd = 32'bx; + pcpi_int_wait = |{ENABLE_PCPI && pcpi_wait, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_wait, ENABLE_DIV && pcpi_div_wait}; + pcpi_int_ready = |{ENABLE_PCPI && pcpi_ready, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready, ENABLE_DIV && pcpi_div_ready}; + + (* parallel_case *) + case (1'b1) + ENABLE_PCPI && pcpi_ready: begin + pcpi_int_wr = ENABLE_PCPI ? pcpi_wr : 0; + pcpi_int_rd = ENABLE_PCPI ? pcpi_rd : 0; + end + (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready: begin + pcpi_int_wr = pcpi_mul_wr; + pcpi_int_rd = pcpi_mul_rd; + end + ENABLE_DIV && pcpi_div_ready: begin + pcpi_int_wr = pcpi_div_wr; + pcpi_int_rd = pcpi_div_rd; + end + endcase + end + + + // Memory Interface + + reg [1:0] mem_state; + reg [1:0] mem_wordsize; + reg [31:0] mem_rdata_word; + reg [31:0] mem_rdata_q; + reg mem_do_prefetch; + reg mem_do_rinst; + reg mem_do_rdata; + reg mem_do_wdata; + + wire mem_xfer; + reg mem_la_secondword, mem_la_firstword_reg, last_mem_valid; + wire mem_la_firstword = COMPRESSED_ISA && (mem_do_prefetch || mem_do_rinst) && next_pc[1] && !mem_la_secondword; + wire mem_la_firstword_xfer = COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg); + + reg prefetched_high_word; + reg clear_prefetched_high_word; + reg [15:0] mem_16bit_buffer; + + wire [31:0] mem_rdata_latched_noshuffle; + wire [31:0] mem_rdata_latched; + + wire mem_la_use_prefetched_high_word = COMPRESSED_ISA && mem_la_firstword && prefetched_high_word && !clear_prefetched_high_word; + assign mem_xfer = (mem_valid && mem_ready) || (mem_la_use_prefetched_high_word && mem_do_rinst); + + wire mem_busy = |{mem_do_prefetch, mem_do_rinst, mem_do_rdata, mem_do_wdata}; + wire mem_done = resetn && ((mem_xfer && |mem_state && (mem_do_rinst || mem_do_rdata || mem_do_wdata)) || (&mem_state && mem_do_rinst)) && + (!mem_la_firstword || (~&mem_rdata_latched[1:0] && mem_xfer)); + + assign mem_la_write = resetn && !mem_state && mem_do_wdata; + assign mem_la_read = resetn && ((!mem_la_use_prefetched_high_word && !mem_state && (mem_do_rinst || mem_do_prefetch || mem_do_rdata)) || + (COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg) && !mem_la_secondword && &mem_rdata_latched[1:0])); + assign mem_la_addr = (mem_do_prefetch || mem_do_rinst) ? {next_pc[31:2] + mem_la_firstword_xfer, 2'b00} : {reg_op1[31:2], 2'b00}; + + assign mem_rdata_latched_noshuffle = (mem_xfer || LATCHED_MEM_RDATA) ? mem_rdata : mem_rdata_q; + + assign mem_rdata_latched = COMPRESSED_ISA && mem_la_use_prefetched_high_word ? {16'bx, mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_secondword ? {mem_rdata_latched_noshuffle[15:0], mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_firstword ? {16'bx, mem_rdata_latched_noshuffle[31:16]} : mem_rdata_latched_noshuffle; + + always @(posedge clk) begin + if (!resetn) begin + mem_la_firstword_reg <= 0; + last_mem_valid <= 0; + end else begin + if (!last_mem_valid) + mem_la_firstword_reg <= mem_la_firstword; + last_mem_valid <= mem_valid && !mem_ready; + end + end + + always @* begin + (* full_case *) + case (mem_wordsize) + 0: begin + mem_la_wdata = reg_op2; + mem_la_wstrb = 4'b1111; + mem_rdata_word = mem_rdata; + end + 1: begin + mem_la_wdata = {2{reg_op2[15:0]}}; + mem_la_wstrb = reg_op1[1] ? 4'b1100 : 4'b0011; + case (reg_op1[1]) + 1'b0: mem_rdata_word = {16'b0, mem_rdata[15: 0]}; + 1'b1: mem_rdata_word = {16'b0, mem_rdata[31:16]}; + endcase + end + 2: begin + mem_la_wdata = {4{reg_op2[7:0]}}; + mem_la_wstrb = 4'b0001 << reg_op1[1:0]; + case (reg_op1[1:0]) + 2'b00: mem_rdata_word = {24'b0, mem_rdata[ 7: 0]}; + 2'b01: mem_rdata_word = {24'b0, mem_rdata[15: 8]}; + 2'b10: mem_rdata_word = {24'b0, mem_rdata[23:16]}; + 2'b11: mem_rdata_word = {24'b0, mem_rdata[31:24]}; + endcase + end + endcase + end + + always @(posedge clk) begin + if (mem_xfer) begin + mem_rdata_q <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + next_insn_opcode <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + end + + if (COMPRESSED_ISA && mem_done && (mem_do_prefetch || mem_do_rinst)) begin + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= {2'b0, mem_rdata_latched[10:7], mem_rdata_latched[12:11], mem_rdata_latched[5], mem_rdata_latched[6], 2'b00}; + end + 3'b010: begin // C.LW + mem_rdata_q[31:20] <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b 110: begin // C.SW + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b 000: begin // C.ADDI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 010: begin // C.LI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 011: begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[4:3], + mem_rdata_latched[5], mem_rdata_latched[2], mem_rdata_latched[6], 4'b 0000}); + end else begin // C.LUI + mem_rdata_q[31:12] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + end + 3'b100: begin + if (mem_rdata_latched[11:10] == 2'b00) begin // C.SRLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b01) begin // C.SRAI + mem_rdata_q[31:25] <= 7'b0100000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + if (mem_rdata_latched[6:5] == 2'b00) mem_rdata_q[14:12] <= 3'b000; + if (mem_rdata_latched[6:5] == 2'b01) mem_rdata_q[14:12] <= 3'b100; + if (mem_rdata_latched[6:5] == 2'b10) mem_rdata_q[14:12] <= 3'b110; + if (mem_rdata_latched[6:5] == 2'b11) mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:25] <= mem_rdata_latched[6:5] == 2'b00 ? 7'b0100000 : 7'b0000000; + end + end + 3'b 110: begin // C.BEQZ + mem_rdata_q[14:12] <= 3'b000; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + 3'b 111: begin // C.BNEZ + mem_rdata_q[14:12] <= 3'b001; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 001; + end + 3'b010: begin // C.LWSP + mem_rdata_q[31:20] <= {4'b0, mem_rdata_latched[3:2], mem_rdata_latched[12], mem_rdata_latched[6:4], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + end + 3'b110: begin // C.SWSP + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {4'b0, mem_rdata_latched[8:7], mem_rdata_latched[12:9], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + endcase + end + end + + always @(posedge clk) begin + if (resetn && !trap) begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) + `assert(!mem_do_wdata); + + if (mem_do_prefetch || mem_do_rinst) + `assert(!mem_do_rdata); + + if (mem_do_rdata) + `assert(!mem_do_prefetch && !mem_do_rinst); + + if (mem_do_wdata) + `assert(!(mem_do_prefetch || mem_do_rinst || mem_do_rdata)); + + if (mem_state == 2 || mem_state == 3) + `assert(mem_valid || mem_do_prefetch); + end + end + + always @(posedge clk) begin + if (!resetn || trap) begin + if (!resetn) + mem_state <= 0; + if (!resetn || mem_ready) + mem_valid <= 0; + mem_la_secondword <= 0; + prefetched_high_word <= 0; + end else begin + if (mem_la_read || mem_la_write) begin + mem_addr <= mem_la_addr; + mem_wstrb <= mem_la_wstrb & {4{mem_la_write}}; + end + if (mem_la_write) begin + mem_wdata <= mem_la_wdata; + end + case (mem_state) + 0: begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) begin + mem_valid <= !mem_la_use_prefetched_high_word; + mem_instr <= mem_do_prefetch || mem_do_rinst; + mem_wstrb <= 0; + mem_state <= 1; + end + if (mem_do_wdata) begin + mem_valid <= 1; + mem_instr <= 0; + mem_state <= 2; + end + end + 1: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch || mem_do_rinst || mem_do_rdata); + `assert(mem_valid == !mem_la_use_prefetched_high_word); + `assert(mem_instr == (mem_do_prefetch || mem_do_rinst)); + if (mem_xfer) begin + if (COMPRESSED_ISA && mem_la_read) begin + mem_valid <= 1; + mem_la_secondword <= 1; + if (!mem_la_use_prefetched_high_word) + mem_16bit_buffer <= mem_rdata[31:16]; + end else begin + mem_valid <= 0; + mem_la_secondword <= 0; + if (COMPRESSED_ISA && !mem_do_rdata) begin + if (~&mem_rdata[1:0] || mem_la_secondword) begin + mem_16bit_buffer <= mem_rdata[31:16]; + prefetched_high_word <= 1; + end else begin + prefetched_high_word <= 0; + end + end + mem_state <= mem_do_rinst || mem_do_rdata ? 0 : 3; + end + end + end + 2: begin + `assert(mem_wstrb != 0); + `assert(mem_do_wdata); + if (mem_xfer) begin + mem_valid <= 0; + mem_state <= 0; + end + end + 3: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch); + if (mem_do_rinst) begin + mem_state <= 0; + end + end + endcase + end + + if (clear_prefetched_high_word) + prefetched_high_word <= 0; + end + + + // Instruction Decoder + + reg instr_lui, instr_auipc, instr_jal, instr_jalr; + reg instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu; + reg instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw; + reg instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai; + reg instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and; + reg instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, instr_ecall_ebreak; + reg instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer; + wire instr_trap; + + reg [regindex_bits-1:0] decoded_rd, decoded_rs1, decoded_rs2; + reg [31:0] decoded_imm, decoded_imm_uj; + reg decoder_trigger; + reg decoder_trigger_q; + reg decoder_pseudo_trigger; + reg decoder_pseudo_trigger_q; + reg compressed_instr; + + reg is_lui_auipc_jal; + reg is_lb_lh_lw_lbu_lhu; + reg is_slli_srli_srai; + reg is_jalr_addi_slti_sltiu_xori_ori_andi; + reg is_sb_sh_sw; + reg is_sll_srl_sra; + reg is_lui_auipc_jal_jalr_addi_add_sub; + reg is_slti_blt_slt; + reg is_sltiu_bltu_sltu; + reg is_beq_bne_blt_bge_bltu_bgeu; + reg is_lbu_lhu_lw; + reg is_alu_reg_imm; + reg is_alu_reg_reg; + reg is_compare; + + assign instr_trap = (CATCH_ILLINSN || WITH_PCPI) && !{instr_lui, instr_auipc, instr_jal, instr_jalr, + instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu, + instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw, + instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai, + instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and, + instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, + instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer}; + + wire is_rdcycle_rdcycleh_rdinstr_rdinstrh; + assign is_rdcycle_rdcycleh_rdinstr_rdinstrh = |{instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh}; + + reg [63:0] new_ascii_instr; + `FORMAL_KEEP reg [63:0] dbg_ascii_instr; + `FORMAL_KEEP reg [31:0] dbg_insn_imm; + `FORMAL_KEEP reg [4:0] dbg_insn_rs1; + `FORMAL_KEEP reg [4:0] dbg_insn_rs2; + `FORMAL_KEEP reg [4:0] dbg_insn_rd; + `FORMAL_KEEP reg [31:0] dbg_rs1val; + `FORMAL_KEEP reg [31:0] dbg_rs2val; + `FORMAL_KEEP reg dbg_rs1val_valid; + `FORMAL_KEEP reg dbg_rs2val_valid; + + always @* begin + new_ascii_instr = ""; + + if (instr_lui) new_ascii_instr = "lui"; + if (instr_auipc) new_ascii_instr = "auipc"; + if (instr_jal) new_ascii_instr = "jal"; + if (instr_jalr) new_ascii_instr = "jalr"; + + if (instr_beq) new_ascii_instr = "beq"; + if (instr_bne) new_ascii_instr = "bne"; + if (instr_blt) new_ascii_instr = "blt"; + if (instr_bge) new_ascii_instr = "bge"; + if (instr_bltu) new_ascii_instr = "bltu"; + if (instr_bgeu) new_ascii_instr = "bgeu"; + + if (instr_lb) new_ascii_instr = "lb"; + if (instr_lh) new_ascii_instr = "lh"; + if (instr_lw) new_ascii_instr = "lw"; + if (instr_lbu) new_ascii_instr = "lbu"; + if (instr_lhu) new_ascii_instr = "lhu"; + if (instr_sb) new_ascii_instr = "sb"; + if (instr_sh) new_ascii_instr = "sh"; + if (instr_sw) new_ascii_instr = "sw"; + + if (instr_addi) new_ascii_instr = "addi"; + if (instr_slti) new_ascii_instr = "slti"; + if (instr_sltiu) new_ascii_instr = "sltiu"; + if (instr_xori) new_ascii_instr = "xori"; + if (instr_ori) new_ascii_instr = "ori"; + if (instr_andi) new_ascii_instr = "andi"; + if (instr_slli) new_ascii_instr = "slli"; + if (instr_srli) new_ascii_instr = "srli"; + if (instr_srai) new_ascii_instr = "srai"; + + if (instr_add) new_ascii_instr = "add"; + if (instr_sub) new_ascii_instr = "sub"; + if (instr_sll) new_ascii_instr = "sll"; + if (instr_slt) new_ascii_instr = "slt"; + if (instr_sltu) new_ascii_instr = "sltu"; + if (instr_xor) new_ascii_instr = "xor"; + if (instr_srl) new_ascii_instr = "srl"; + if (instr_sra) new_ascii_instr = "sra"; + if (instr_or) new_ascii_instr = "or"; + if (instr_and) new_ascii_instr = "and"; + + if (instr_rdcycle) new_ascii_instr = "rdcycle"; + if (instr_rdcycleh) new_ascii_instr = "rdcycleh"; + if (instr_rdinstr) new_ascii_instr = "rdinstr"; + if (instr_rdinstrh) new_ascii_instr = "rdinstrh"; + + if (instr_getq) new_ascii_instr = "getq"; + if (instr_setq) new_ascii_instr = "setq"; + if (instr_retirq) new_ascii_instr = "retirq"; + if (instr_maskirq) new_ascii_instr = "maskirq"; + if (instr_waitirq) new_ascii_instr = "waitirq"; + if (instr_timer) new_ascii_instr = "timer"; + end + + reg [63:0] q_ascii_instr; + reg [31:0] q_insn_imm; + reg [31:0] q_insn_opcode; + reg [4:0] q_insn_rs1; + reg [4:0] q_insn_rs2; + reg [4:0] q_insn_rd; + reg dbg_next; + + wire launch_next_insn; + reg dbg_valid_insn; + + reg [63:0] cached_ascii_instr; + reg [31:0] cached_insn_imm; + reg [31:0] cached_insn_opcode; + reg [4:0] cached_insn_rs1; + reg [4:0] cached_insn_rs2; + reg [4:0] cached_insn_rd; + + always @(posedge clk) begin + q_ascii_instr <= dbg_ascii_instr; + q_insn_imm <= dbg_insn_imm; + q_insn_opcode <= dbg_insn_opcode; + q_insn_rs1 <= dbg_insn_rs1; + q_insn_rs2 <= dbg_insn_rs2; + q_insn_rd <= dbg_insn_rd; + dbg_next <= launch_next_insn; + + if (!resetn || trap) + dbg_valid_insn <= 0; + else if (launch_next_insn) + dbg_valid_insn <= 1; + + if (decoder_trigger_q) begin + cached_ascii_instr <= new_ascii_instr; + cached_insn_imm <= decoded_imm; + if (&next_insn_opcode[1:0]) + cached_insn_opcode <= next_insn_opcode; + else + cached_insn_opcode <= {16'b0, next_insn_opcode[15:0]}; + cached_insn_rs1 <= decoded_rs1; + cached_insn_rs2 <= decoded_rs2; + cached_insn_rd <= decoded_rd; + end + + if (launch_next_insn) begin + dbg_insn_addr <= next_pc; + end + end + + always @* begin + dbg_ascii_instr = q_ascii_instr; + dbg_insn_imm = q_insn_imm; + dbg_insn_opcode = q_insn_opcode; + dbg_insn_rs1 = q_insn_rs1; + dbg_insn_rs2 = q_insn_rs2; + dbg_insn_rd = q_insn_rd; + + if (dbg_next) begin + if (decoder_pseudo_trigger_q) begin + dbg_ascii_instr = cached_ascii_instr; + dbg_insn_imm = cached_insn_imm; + dbg_insn_opcode = cached_insn_opcode; + dbg_insn_rs1 = cached_insn_rs1; + dbg_insn_rs2 = cached_insn_rs2; + dbg_insn_rd = cached_insn_rd; + end else begin + dbg_ascii_instr = new_ascii_instr; + if (&next_insn_opcode[1:0]) + dbg_insn_opcode = next_insn_opcode; + else + dbg_insn_opcode = {16'b0, next_insn_opcode[15:0]}; + dbg_insn_imm = decoded_imm; + dbg_insn_rs1 = decoded_rs1; + dbg_insn_rs2 = decoded_rs2; + dbg_insn_rd = decoded_rd; + end + end + end + +`ifdef DEBUGASM + always @(posedge clk) begin + if (dbg_next) begin + $display("debugasm %x %x %s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "*"); + end + end +`endif + +`ifdef DEBUG + always @(posedge clk) begin + if (dbg_next) begin + if (&dbg_insn_opcode[1:0]) + $display("DECODE: 0x%08x 0x%08x %-0s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + else + $display("DECODE: 0x%08x 0x%04x %-0s", dbg_insn_addr, dbg_insn_opcode[15:0], dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + end + end +`endif + + always @(posedge clk) begin + is_lui_auipc_jal <= |{instr_lui, instr_auipc, instr_jal}; + is_lui_auipc_jal_jalr_addi_add_sub <= |{instr_lui, instr_auipc, instr_jal, instr_jalr, instr_addi, instr_add, instr_sub}; + is_slti_blt_slt <= |{instr_slti, instr_blt, instr_slt}; + is_sltiu_bltu_sltu <= |{instr_sltiu, instr_bltu, instr_sltu}; + is_lbu_lhu_lw <= |{instr_lbu, instr_lhu, instr_lw}; + is_compare <= |{is_beq_bne_blt_bge_bltu_bgeu, instr_slti, instr_slt, instr_sltiu, instr_sltu}; + + if (mem_do_rinst && mem_done) begin + instr_lui <= mem_rdata_latched[6:0] == 7'b0110111; + instr_auipc <= mem_rdata_latched[6:0] == 7'b0010111; + instr_jal <= mem_rdata_latched[6:0] == 7'b1101111; + instr_jalr <= mem_rdata_latched[6:0] == 7'b1100111 && mem_rdata_latched[14:12] == 3'b000; + instr_retirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ; + instr_waitirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000100 && ENABLE_IRQ; + + is_beq_bne_blt_bge_bltu_bgeu <= mem_rdata_latched[6:0] == 7'b1100011; + is_lb_lh_lw_lbu_lhu <= mem_rdata_latched[6:0] == 7'b0000011; + is_sb_sh_sw <= mem_rdata_latched[6:0] == 7'b0100011; + is_alu_reg_imm <= mem_rdata_latched[6:0] == 7'b0010011; + is_alu_reg_reg <= mem_rdata_latched[6:0] == 7'b0110011; + + { decoded_imm_uj[31:20], decoded_imm_uj[10:1], decoded_imm_uj[11], decoded_imm_uj[19:12], decoded_imm_uj[0] } <= $signed({mem_rdata_latched[31:12], 1'b0}); + + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[19:15]; + decoded_rs2 <= mem_rdata_latched[24:20]; + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS) + decoded_rs1[regindex_bits-1] <= 1; // instr_getq + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ) + decoded_rs1 <= ENABLE_IRQ_QREGS ? irqregs_offset : 3; // instr_retirq + + compressed_instr <= 0; + if (COMPRESSED_ISA && mem_rdata_latched[1:0] != 2'b11) begin + compressed_instr <= 1; + decoded_rd <= 0; + decoded_rs1 <= 0; + decoded_rs2 <= 0; + + { decoded_imm_uj[31:11], decoded_imm_uj[4], decoded_imm_uj[9:8], decoded_imm_uj[10], decoded_imm_uj[6], + decoded_imm_uj[7], decoded_imm_uj[3:1], decoded_imm_uj[5], decoded_imm_uj[0] } <= $signed({mem_rdata_latched[12:2], 1'b0}); + + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + is_alu_reg_imm <= |mem_rdata_latched[12:5]; + decoded_rs1 <= 2; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b010: begin // C.LW + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b110: begin // C.SW + is_sb_sh_sw <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.NOP / C.ADDI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + 3'b001: begin // C.JAL + instr_jal <= 1; + decoded_rd <= 1; + end + 3'b 010: begin // C.LI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + 3'b 011: begin + if (mem_rdata_latched[12] || mem_rdata_latched[6:2]) begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end else begin // C.LUI + instr_lui <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + end + end + 3'b100: begin + if (!mem_rdata_latched[11] && !mem_rdata_latched[12]) begin // C.SRLI, C.SRAI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + is_alu_reg_reg <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + end + 3'b101: begin // C.J + instr_jal <= 1; + end + 3'b110: begin // C.BEQZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + 3'b111: begin // C.BNEZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + if (!mem_rdata_latched[12]) begin + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + end + 3'b010: begin // C.LWSP + if (mem_rdata_latched[11:7]) begin + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 2; + end + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + instr_jalr <= 1; + decoded_rd <= 0; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + instr_jalr <= 1; + decoded_rd <= 1; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + end + 3'b110: begin // C.SWSP + is_sb_sh_sw <= 1; + decoded_rs1 <= 2; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + endcase + end + endcase + end + end + + if (decoder_trigger && !decoder_pseudo_trigger) begin + pcpi_insn <= WITH_PCPI ? mem_rdata_q : 'bx; + + instr_beq <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b000; + instr_bne <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b001; + instr_blt <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b100; + instr_bge <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b101; + instr_bltu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b110; + instr_bgeu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b111; + + instr_lb <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b000; + instr_lh <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b001; + instr_lw <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b010; + instr_lbu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b100; + instr_lhu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b101; + + instr_sb <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b000; + instr_sh <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b001; + instr_sw <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b010; + + instr_addi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b000; + instr_slti <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b010; + instr_sltiu <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b011; + instr_xori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b100; + instr_ori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b110; + instr_andi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b111; + + instr_slli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_srli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_srai <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + + instr_add <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0000000; + instr_sub <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0100000; + instr_sll <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_slt <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b010 && mem_rdata_q[31:25] == 7'b0000000; + instr_sltu <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b011 && mem_rdata_q[31:25] == 7'b0000000; + instr_xor <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b100 && mem_rdata_q[31:25] == 7'b0000000; + instr_srl <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_sra <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + instr_or <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b110 && mem_rdata_q[31:25] == 7'b0000000; + instr_and <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b111 && mem_rdata_q[31:25] == 7'b0000000; + + instr_rdcycle <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000100000010)) && ENABLE_COUNTERS; + instr_rdcycleh <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000100000010)) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + instr_rdinstr <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000001000000010) && ENABLE_COUNTERS; + instr_rdinstrh <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000001000000010) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + + instr_ecall_ebreak <= ((mem_rdata_q[6:0] == 7'b1110011 && !mem_rdata_q[31:21] && !mem_rdata_q[19:7]) || + (COMPRESSED_ISA && mem_rdata_q[15:0] == 16'h9002)); + + instr_getq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_setq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000001 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_maskirq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000011 && ENABLE_IRQ; + instr_timer <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000101 && ENABLE_IRQ && ENABLE_IRQ_TIMER; + + is_slli_srli_srai <= is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_jalr_addi_slti_sltiu_xori_ori_andi <= instr_jalr || is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b000, + mem_rdata_q[14:12] == 3'b010, + mem_rdata_q[14:12] == 3'b011, + mem_rdata_q[14:12] == 3'b100, + mem_rdata_q[14:12] == 3'b110, + mem_rdata_q[14:12] == 3'b111 + }; + + is_sll_srl_sra <= is_alu_reg_reg && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_lui_auipc_jal_jalr_addi_add_sub <= 0; + is_compare <= 0; + + (* parallel_case *) + case (1'b1) + instr_jal: + decoded_imm <= decoded_imm_uj; + |{instr_lui, instr_auipc}: + decoded_imm <= mem_rdata_q[31:12] << 12; + |{instr_jalr, is_lb_lh_lw_lbu_lhu, is_alu_reg_imm}: + decoded_imm <= $signed(mem_rdata_q[31:20]); + is_beq_bne_blt_bge_bltu_bgeu: + decoded_imm <= $signed({mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8], 1'b0}); + is_sb_sh_sw: + decoded_imm <= $signed({mem_rdata_q[31:25], mem_rdata_q[11:7]}); + default: + decoded_imm <= 1'bx; + endcase + end + + if (!resetn) begin + is_beq_bne_blt_bge_bltu_bgeu <= 0; + is_compare <= 0; + + instr_beq <= 0; + instr_bne <= 0; + instr_blt <= 0; + instr_bge <= 0; + instr_bltu <= 0; + instr_bgeu <= 0; + + instr_addi <= 0; + instr_slti <= 0; + instr_sltiu <= 0; + instr_xori <= 0; + instr_ori <= 0; + instr_andi <= 0; + + instr_add <= 0; + instr_sub <= 0; + instr_sll <= 0; + instr_slt <= 0; + instr_sltu <= 0; + instr_xor <= 0; + instr_srl <= 0; + instr_sra <= 0; + instr_or <= 0; + instr_and <= 0; + end + end + + + // Main State Machine + + localparam cpu_state_trap = 8'b10000000; + localparam cpu_state_fetch = 8'b01000000; + localparam cpu_state_ld_rs1 = 8'b00100000; + localparam cpu_state_ld_rs2 = 8'b00010000; + localparam cpu_state_exec = 8'b00001000; + localparam cpu_state_shift = 8'b00000100; + localparam cpu_state_stmem = 8'b00000010; + localparam cpu_state_ldmem = 8'b00000001; + + reg [7:0] cpu_state; + reg [1:0] irq_state; + + `FORMAL_KEEP reg [127:0] dbg_ascii_state; + + always @* begin + dbg_ascii_state = ""; + if (cpu_state == cpu_state_trap) dbg_ascii_state = "trap"; + if (cpu_state == cpu_state_fetch) dbg_ascii_state = "fetch"; + if (cpu_state == cpu_state_ld_rs1) dbg_ascii_state = "ld_rs1"; + if (cpu_state == cpu_state_ld_rs2) dbg_ascii_state = "ld_rs2"; + if (cpu_state == cpu_state_exec) dbg_ascii_state = "exec"; + if (cpu_state == cpu_state_shift) dbg_ascii_state = "shift"; + if (cpu_state == cpu_state_stmem) dbg_ascii_state = "stmem"; + if (cpu_state == cpu_state_ldmem) dbg_ascii_state = "ldmem"; + end + + reg set_mem_do_rinst; + reg set_mem_do_rdata; + reg set_mem_do_wdata; + + reg latched_store; + reg latched_stalu; + reg latched_branch; + reg latched_compr; + reg latched_trace; + reg latched_is_lu; + reg latched_is_lh; + reg latched_is_lb; + reg [regindex_bits-1:0] latched_rd; + + reg [31:0] current_pc; + assign next_pc = latched_store && latched_branch ? reg_out & ~1 : reg_next_pc; + + reg [3:0] pcpi_timeout_counter; + reg pcpi_timeout; + + reg [31:0] next_irq_pending; + reg do_waitirq; + + reg [31:0] alu_out, alu_out_q; + reg alu_out_0, alu_out_0_q; + reg alu_wait, alu_wait_2; + + reg [31:0] alu_add_sub; + reg [31:0] alu_shl, alu_shr; + reg alu_eq, alu_ltu, alu_lts; + + generate if (TWO_CYCLE_ALU) begin + always @(posedge clk) begin + alu_add_sub <= instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq <= reg_op1 == reg_op2; + alu_lts <= $signed(reg_op1) < $signed(reg_op2); + alu_ltu <= reg_op1 < reg_op2; + alu_shl <= reg_op1 << reg_op2[4:0]; + alu_shr <= $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end else begin + always @* begin + alu_add_sub = instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq = reg_op1 == reg_op2; + alu_lts = $signed(reg_op1) < $signed(reg_op2); + alu_ltu = reg_op1 < reg_op2; + alu_shl = reg_op1 << reg_op2[4:0]; + alu_shr = $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end endgenerate + + always @* begin + alu_out_0 = 'bx; + (* parallel_case, full_case *) + case (1'b1) + instr_beq: + alu_out_0 = alu_eq; + instr_bne: + alu_out_0 = !alu_eq; + instr_bge: + alu_out_0 = !alu_lts; + instr_bgeu: + alu_out_0 = !alu_ltu; + is_slti_blt_slt && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_lts; + is_sltiu_bltu_sltu && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_ltu; + endcase + + alu_out = 'bx; + (* parallel_case, full_case *) + case (1'b1) + is_lui_auipc_jal_jalr_addi_add_sub: + alu_out = alu_add_sub; + is_compare: + alu_out = alu_out_0; + instr_xori || instr_xor: + alu_out = reg_op1 ^ reg_op2; + instr_ori || instr_or: + alu_out = reg_op1 | reg_op2; + instr_andi || instr_and: + alu_out = reg_op1 & reg_op2; + BARREL_SHIFTER && (instr_sll || instr_slli): + alu_out = alu_shl; + BARREL_SHIFTER && (instr_srl || instr_srli || instr_sra || instr_srai): + alu_out = alu_shr; + endcase + +`ifdef RISCV_FORMAL_BLACKBOX_ALU + alu_out_0 = $anyseq; + alu_out = $anyseq; +`endif + end + + reg clear_prefetched_high_word_q; + always @(posedge clk) clear_prefetched_high_word_q <= clear_prefetched_high_word; + + always @* begin + clear_prefetched_high_word = clear_prefetched_high_word_q; + if (!prefetched_high_word) + clear_prefetched_high_word = 0; + if (latched_branch || irq_state || !resetn) + clear_prefetched_high_word = COMPRESSED_ISA; + end + + reg cpuregs_write; + reg [31:0] cpuregs_wrdata; + reg [31:0] cpuregs_rs1; + reg [31:0] cpuregs_rs2; + reg [regindex_bits-1:0] decoded_rs; + + always @* begin + cpuregs_write = 0; + cpuregs_wrdata = 'bx; + + if (cpu_state == cpu_state_fetch) begin + (* parallel_case *) + case (1'b1) + latched_branch: begin + cpuregs_wrdata = reg_pc + (latched_compr ? 2 : 4); + cpuregs_write = 1; + end + latched_store && !latched_branch: begin + cpuregs_wrdata = latched_stalu ? alu_out_q : reg_out; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[0]: begin + cpuregs_wrdata = reg_next_pc | latched_compr; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[1]: begin + cpuregs_wrdata = irq_pending & ~irq_mask; + cpuregs_write = 1; + end + endcase + end + end + +`ifndef PICORV32_REGS + always @(posedge clk) begin + if (resetn && cpuregs_write && latched_rd) + cpuregs[latched_rd] <= cpuregs_wrdata; + end + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs1 ? cpuregs[decoded_rs1] : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs[decoded_rs2] : 0; +`else + cpuregs_rs1 = decoded_rs1 ? $anyseq : 0; + cpuregs_rs2 = decoded_rs2 ? $anyseq : 0; +`endif + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs ? cpuregs[decoded_rs] : 0; +`else + cpuregs_rs1 = decoded_rs ? $anyseq : 0; +`endif + cpuregs_rs2 = cpuregs_rs1; + end + end +`else + wire[31:0] cpuregs_rdata1; + wire[31:0] cpuregs_rdata2; + + wire [5:0] cpuregs_waddr = latched_rd; + wire [5:0] cpuregs_raddr1 = ENABLE_REGS_DUALPORT ? decoded_rs1 : decoded_rs; + wire [5:0] cpuregs_raddr2 = ENABLE_REGS_DUALPORT ? decoded_rs2 : 0; + + `PICORV32_REGS cpuregs ( + .clk(clk), + .wen(resetn && cpuregs_write && latched_rd), + .waddr(cpuregs_waddr), + .raddr1(cpuregs_raddr1), + .raddr2(cpuregs_raddr2), + .wdata(cpuregs_wrdata), + .rdata1(cpuregs_rdata1), + .rdata2(cpuregs_rdata2) + ); + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin + cpuregs_rs1 = decoded_rs1 ? cpuregs_rdata1 : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs_rdata2 : 0; + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; + cpuregs_rs1 = decoded_rs ? cpuregs_rdata1 : 0; + cpuregs_rs2 = cpuregs_rs1; + end + end +`endif + + assign launch_next_insn = cpu_state == cpu_state_fetch && decoder_trigger && (!ENABLE_IRQ || irq_delay || irq_active || !(irq_pending & ~irq_mask)); + + always @(posedge clk) begin + trap <= 0; + reg_sh <= 'bx; + reg_out <= 'bx; + set_mem_do_rinst = 0; + set_mem_do_rdata = 0; + set_mem_do_wdata = 0; + + alu_out_0_q <= alu_out_0; + alu_out_q <= alu_out; + + alu_wait <= 0; + alu_wait_2 <= 0; + + if (launch_next_insn) begin + dbg_rs1val <= 'bx; + dbg_rs2val <= 'bx; + dbg_rs1val_valid <= 0; + dbg_rs2val_valid <= 0; + end + + if (WITH_PCPI && CATCH_ILLINSN) begin + if (resetn && pcpi_valid && !pcpi_int_wait) begin + if (pcpi_timeout_counter) + pcpi_timeout_counter <= pcpi_timeout_counter - 1; + end else + pcpi_timeout_counter <= ~0; + pcpi_timeout <= !pcpi_timeout_counter; + end + + if (ENABLE_COUNTERS) begin + count_cycle <= resetn ? count_cycle + 1 : 0; + if (!ENABLE_COUNTERS64) count_cycle[63:32] <= 0; + end else begin + count_cycle <= 'bx; + count_instr <= 'bx; + end + + next_irq_pending = ENABLE_IRQ ? irq_pending & LATCHED_IRQ : 'bx; + + if (ENABLE_IRQ && ENABLE_IRQ_TIMER && timer) begin + if (timer - 1 == 0) + next_irq_pending[irq_timer] = 1; + timer <= timer - 1; + end + + if (ENABLE_IRQ) begin + next_irq_pending = next_irq_pending | irq; + end + + decoder_trigger <= mem_do_rinst && mem_done; + decoder_trigger_q <= decoder_trigger; + decoder_pseudo_trigger <= 0; + decoder_pseudo_trigger_q <= decoder_pseudo_trigger; + do_waitirq <= 0; + + trace_valid <= 0; + + if (!ENABLE_TRACE) + trace_data <= 'bx; + + if (!resetn) begin + reg_pc <= PROGADDR_RESET; + reg_next_pc <= PROGADDR_RESET; + if (ENABLE_COUNTERS) + count_instr <= 0; + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_trace <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + pcpi_valid <= 0; + pcpi_timeout <= 0; + irq_active <= 0; + irq_delay <= 0; + irq_mask <= ~0; + next_irq_pending = 0; + irq_state <= 0; + eoi <= 0; + timer <= 0; + if (~STACKADDR) begin + latched_store <= 1; + latched_rd <= 2; + reg_out <= STACKADDR; + end + cpu_state <= cpu_state_fetch; + end else + (* parallel_case, full_case *) + case (cpu_state) + cpu_state_trap: begin + trap <= 1; + end + + cpu_state_fetch: begin + mem_do_rinst <= !decoder_trigger && !do_waitirq; + mem_wordsize <= 0; + + current_pc = reg_next_pc; + + (* parallel_case *) + case (1'b1) + latched_branch: begin + current_pc = latched_store ? (latched_stalu ? alu_out_q : reg_out) & ~1 : reg_next_pc; + `debug($display("ST_RD: %2d 0x%08x, BRANCH 0x%08x", latched_rd, reg_pc + (latched_compr ? 2 : 4), current_pc);) + end + latched_store && !latched_branch: begin + `debug($display("ST_RD: %2d 0x%08x", latched_rd, latched_stalu ? alu_out_q : reg_out);) + end + ENABLE_IRQ && irq_state[0]: begin + current_pc = PROGADDR_IRQ; + irq_active <= 1; + mem_do_rinst <= 1; + end + ENABLE_IRQ && irq_state[1]: begin + eoi <= irq_pending & ~irq_mask; + next_irq_pending = next_irq_pending & irq_mask; + end + endcase + + if (ENABLE_TRACE && latched_trace) begin + latched_trace <= 0; + trace_valid <= 1; + if (latched_branch) + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_BRANCH | (current_pc & 32'hfffffffe); + else + trace_data <= (irq_active ? TRACE_IRQ : 0) | (latched_stalu ? alu_out_q : reg_out); + end + + reg_pc <= current_pc; + reg_next_pc <= current_pc; + + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + latched_rd <= decoded_rd; + latched_compr <= compressed_instr; + + if (ENABLE_IRQ && ((decoder_trigger && !irq_active && !irq_delay && |(irq_pending & ~irq_mask)) || irq_state)) begin + irq_state <= + irq_state == 2'b00 ? 2'b01 : + irq_state == 2'b01 ? 2'b10 : 2'b00; + latched_compr <= latched_compr; + if (ENABLE_IRQ_QREGS) + latched_rd <= irqregs_offset | irq_state[0]; + else + latched_rd <= irq_state[0] ? 4 : 3; + end else + if (ENABLE_IRQ && (decoder_trigger || do_waitirq) && instr_waitirq) begin + if (irq_pending) begin + latched_store <= 1; + reg_out <= irq_pending; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + mem_do_rinst <= 1; + end else + do_waitirq <= 1; + end else + if (decoder_trigger) begin + `debug($display("-- %-0t", $time);) + irq_delay <= irq_active; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + if (ENABLE_TRACE) + latched_trace <= 1; + if (ENABLE_COUNTERS) begin + count_instr <= count_instr + 1; + if (!ENABLE_COUNTERS64) count_instr[63:32] <= 0; + end + if (instr_jal) begin + mem_do_rinst <= 1; + reg_next_pc <= current_pc + decoded_imm_uj; + latched_branch <= 1; + end else begin + mem_do_rinst <= 0; + mem_do_prefetch <= !instr_jalr && !instr_retirq; + cpu_state <= cpu_state_ld_rs1; + end + end + end + + cpu_state_ld_rs1: begin + reg_op1 <= 'bx; + reg_op2 <= 'bx; + + (* parallel_case *) + case (1'b1) + (CATCH_ILLINSN || WITH_PCPI) && instr_trap: begin + if (WITH_PCPI) begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + pcpi_valid <= 1; + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end else begin + cpu_state <= cpu_state_ld_rs2; + end + end else begin + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + ENABLE_COUNTERS && is_rdcycle_rdcycleh_rdinstr_rdinstrh: begin + (* parallel_case, full_case *) + case (1'b1) + instr_rdcycle: + reg_out <= count_cycle[31:0]; + instr_rdcycleh && ENABLE_COUNTERS64: + reg_out <= count_cycle[63:32]; + instr_rdinstr: + reg_out <= count_instr[31:0]; + instr_rdinstrh && ENABLE_COUNTERS64: + reg_out <= count_instr[63:32]; + endcase + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + is_lui_auipc_jal: begin + reg_op1 <= instr_lui ? 0 : reg_pc; + reg_op2 <= decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_getq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_setq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_rd <= latched_rd | irqregs_offset; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_retirq: begin + eoi <= 0; + irq_active <= 0; + latched_branch <= 1; + latched_store <= 1; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= CATCH_MISALIGN ? (cpuregs_rs1 & 32'h fffffffe) : cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_maskirq: begin + latched_store <= 1; + reg_out <= irq_mask; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + irq_mask <= cpuregs_rs1 | MASKED_IRQ; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_TIMER && instr_timer: begin + latched_store <= 1; + reg_out <= timer; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + timer <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + is_lb_lh_lw_lbu_lhu && !instr_trap: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_ldmem; + mem_do_rinst <= 1; + end + is_slli_srli_srai && !BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_sh <= decoded_rs2; + cpu_state <= cpu_state_shift; + end + is_jalr_addi_slti_sltiu_xori_ori_andi, is_slli_srli_srai && BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_op2 <= is_slli_srli_srai && BARREL_SHIFTER ? decoded_rs2 : decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + default: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + (* parallel_case *) + case (1'b1) + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end else + cpu_state <= cpu_state_ld_rs2; + end + endcase + end + + cpu_state_ld_rs2: begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + + (* parallel_case *) + case (1'b1) + WITH_PCPI && instr_trap: begin + pcpi_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end + + cpu_state_exec: begin + reg_out <= reg_pc + decoded_imm; + if ((TWO_CYCLE_ALU || TWO_CYCLE_COMPARE) && (alu_wait || alu_wait_2)) begin + mem_do_rinst <= mem_do_prefetch && !alu_wait_2; + alu_wait <= alu_wait_2; + end else + if (is_beq_bne_blt_bge_bltu_bgeu) begin + latched_rd <= 0; + latched_store <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + latched_branch <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + if (mem_done) + cpu_state <= cpu_state_fetch; + if (TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0) begin + decoder_trigger <= 0; + set_mem_do_rinst = 1; + end + end else begin + latched_branch <= instr_jalr; + latched_store <= 1; + latched_stalu <= 1; + cpu_state <= cpu_state_fetch; + end + end + + cpu_state_shift: begin + latched_store <= 1; + if (reg_sh == 0) begin + reg_out <= reg_op1; + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_fetch; + end else if (TWO_STAGE_SHIFT && reg_sh >= 4) begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 4; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 4; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 4; + endcase + reg_sh <= reg_sh - 4; + end else begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 1; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 1; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 1; + endcase + reg_sh <= reg_sh - 1; + end + end + + cpu_state_stmem: begin + if (ENABLE_TRACE) + reg_out <= reg_op2; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_wdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_sb: mem_wordsize <= 2; + instr_sh: mem_wordsize <= 1; + instr_sw: mem_wordsize <= 0; + endcase + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_wdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + cpu_state <= cpu_state_fetch; + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + end + end + end + + cpu_state_ldmem: begin + latched_store <= 1; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_rdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_lb || instr_lbu: mem_wordsize <= 2; + instr_lh || instr_lhu: mem_wordsize <= 1; + instr_lw: mem_wordsize <= 0; + endcase + latched_is_lu <= is_lbu_lhu_lw; + latched_is_lh <= instr_lh; + latched_is_lb <= instr_lb; + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_rdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + (* parallel_case, full_case *) + case (1'b1) + latched_is_lu: reg_out <= mem_rdata_word; + latched_is_lh: reg_out <= $signed(mem_rdata_word[15:0]); + latched_is_lb: reg_out <= $signed(mem_rdata_word[7:0]); + endcase + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + cpu_state <= cpu_state_fetch; + end + end + end + endcase + + if (CATCH_MISALIGN && resetn && (mem_do_rdata || mem_do_wdata)) begin + if (mem_wordsize == 0 && reg_op1[1:0] != 0) begin + `debug($display("MISALIGNED WORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (mem_wordsize == 1 && reg_op1[0] != 0) begin + `debug($display("MISALIGNED HALFWORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + end + if (CATCH_MISALIGN && resetn && mem_do_rinst && (COMPRESSED_ISA ? reg_pc[0] : |reg_pc[1:0])) begin + `debug($display("MISALIGNED INSTRUCTION: 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (!CATCH_ILLINSN && decoder_trigger_q && !decoder_pseudo_trigger_q && instr_ecall_ebreak) begin + cpu_state <= cpu_state_trap; + end + + if (!resetn || mem_done) begin + mem_do_prefetch <= 0; + mem_do_rinst <= 0; + mem_do_rdata <= 0; + mem_do_wdata <= 0; + end + + if (set_mem_do_rinst) + mem_do_rinst <= 1; + if (set_mem_do_rdata) + mem_do_rdata <= 1; + if (set_mem_do_wdata) + mem_do_wdata <= 1; + + irq_pending <= next_irq_pending & ~MASKED_IRQ; + + if (!CATCH_MISALIGN) begin + if (COMPRESSED_ISA) begin + reg_pc[0] <= 0; + reg_next_pc[0] <= 0; + end else begin + reg_pc[1:0] <= 0; + reg_next_pc[1:0] <= 0; + end + end + current_pc = 'bx; + end + +`ifdef RISCV_FORMAL + reg dbg_irq_call; + reg dbg_irq_enter; + reg [31:0] dbg_irq_ret; + always @(posedge clk) begin + rvfi_valid <= resetn && (launch_next_insn || trap) && dbg_valid_insn; + rvfi_order <= resetn ? rvfi_order + rvfi_valid : 0; + + rvfi_insn <= dbg_insn_opcode; + rvfi_rs1_addr <= dbg_rs1val_valid ? dbg_insn_rs1 : 0; + rvfi_rs2_addr <= dbg_rs2val_valid ? dbg_insn_rs2 : 0; + rvfi_pc_rdata <= dbg_insn_addr; + rvfi_rs1_rdata <= dbg_rs1val_valid ? dbg_rs1val : 0; + rvfi_rs2_rdata <= dbg_rs2val_valid ? dbg_rs2val : 0; + rvfi_trap <= trap; + rvfi_halt <= trap; + rvfi_intr <= dbg_irq_enter; + rvfi_mode <= 3; + + if (!resetn) begin + dbg_irq_call <= 0; + dbg_irq_enter <= 0; + end else + if (rvfi_valid) begin + dbg_irq_call <= 0; + dbg_irq_enter <= dbg_irq_call; + end else + if (irq_state == 1) begin + dbg_irq_call <= 1; + dbg_irq_ret <= next_pc; + end + + if (!resetn) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end else + if (cpuregs_write && !irq_state) begin + rvfi_rd_addr <= latched_rd; + rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata : 0; + end else + if (rvfi_valid) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + + casez (dbg_insn_opcode) + 32'b 0000000_?????_000??_???_?????_0001011: begin // getq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + 32'b 0000001_?????_?????_???_000??_0001011: begin // setq + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + 32'b 0000010_?????_00000_???_00000_0001011: begin // retirq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + endcase + + if (!dbg_irq_call) begin + if (dbg_mem_instr) begin + rvfi_mem_addr <= 0; + rvfi_mem_rmask <= 0; + rvfi_mem_wmask <= 0; + rvfi_mem_rdata <= 0; + rvfi_mem_wdata <= 0; + end else + if (dbg_mem_valid && dbg_mem_ready) begin + rvfi_mem_addr <= dbg_mem_addr; + rvfi_mem_rmask <= dbg_mem_wstrb ? 0 : ~0; + rvfi_mem_wmask <= dbg_mem_wstrb; + rvfi_mem_rdata <= dbg_mem_rdata; + rvfi_mem_wdata <= dbg_mem_wdata; + end + end + end + + always @* begin + rvfi_pc_wdata = dbg_irq_call ? dbg_irq_ret : dbg_insn_addr; + end +`endif + + // Formal Verification +`ifdef FORMAL + reg [3:0] last_mem_nowait; + always @(posedge clk) + last_mem_nowait <= {last_mem_nowait, mem_ready || !mem_valid}; + + // stall the memory interface for max 4 cycles + restrict property (|last_mem_nowait || mem_ready || !mem_valid); + + // resetn low in first cycle, after that resetn high + restrict property (resetn != $initstate); + + // this just makes it much easier to read traces. uncomment as needed. + // assume property (mem_valid || !mem_ready); + + reg ok; + always @* begin + if (resetn) begin + // instruction fetches are read-only + if (mem_valid && mem_instr) + assert (mem_wstrb == 0); + + // cpu_state must be valid + ok = 0; + if (cpu_state == cpu_state_trap) ok = 1; + if (cpu_state == cpu_state_fetch) ok = 1; + if (cpu_state == cpu_state_ld_rs1) ok = 1; + if (cpu_state == cpu_state_ld_rs2) ok = !ENABLE_REGS_DUALPORT; + if (cpu_state == cpu_state_exec) ok = 1; + if (cpu_state == cpu_state_shift) ok = 1; + if (cpu_state == cpu_state_stmem) ok = 1; + if (cpu_state == cpu_state_ldmem) ok = 1; + assert (ok); + end + end + + reg last_mem_la_read = 0; + reg last_mem_la_write = 0; + reg [31:0] last_mem_la_addr; + reg [31:0] last_mem_la_wdata; + reg [3:0] last_mem_la_wstrb = 0; + + always @(posedge clk) begin + last_mem_la_read <= mem_la_read; + last_mem_la_write <= mem_la_write; + last_mem_la_addr <= mem_la_addr; + last_mem_la_wdata <= mem_la_wdata; + last_mem_la_wstrb <= mem_la_wstrb; + + if (last_mem_la_read) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wstrb == 0); + end + if (last_mem_la_write) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wdata == last_mem_la_wdata); + assert(mem_wstrb == last_mem_la_wstrb); + end + if (mem_la_read || mem_la_write) begin + assert(!mem_valid || mem_ready); + end + end +`endif +endmodule + +// This is a simple example implementation of PICORV32_REGS. +// Use the PICORV32_REGS mechanism if you want to use custom +// memory resources to implement the processor register file. +// Note that your implementation must match the requirements of +// the PicoRV32 configuration. (e.g. QREGS, etc) +module picorv32_regs ( + input clk, wen, + input [5:0] waddr, + input [5:0] raddr1, + input [5:0] raddr2, + input [31:0] wdata, + output [31:0] rdata1, + output [31:0] rdata2 +); + reg [31:0] regs [0:30]; + + always @(posedge clk) + if (wen) regs[~waddr[4:0]] <= wdata; + + assign rdata1 = regs[~raddr1[4:0]]; + assign rdata2 = regs[~raddr2[4:0]]; +endmodule + + +/*************************************************************** + * picorv32_pcpi_mul + ***************************************************************/ + +module picorv32_pcpi_mul #( + parameter STEPS_AT_ONCE = 1, + parameter CARRY_CHAIN = 4 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg pcpi_wait_q; + wire mul_start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_mul <= 0; + instr_mulh <= 0; + instr_mulhsu <= 0; + instr_mulhu <= 0; + + if (resetn && pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul <= 1; + 3'b001: instr_mulh <= 1; + 3'b010: instr_mulhsu <= 1; + 3'b011: instr_mulhu <= 1; + endcase + end + + pcpi_wait <= instr_any_mul; + pcpi_wait_q <= pcpi_wait; + end + + reg [63:0] rs1, rs2, rd, rdx; + reg [63:0] next_rs1, next_rs2, this_rs2; + reg [63:0] next_rd, next_rdx, next_rdt; + reg [6:0] mul_counter; + reg mul_waiting; + reg mul_finish; + integer i, j; + + // carry save accumulator + always @* begin + next_rd = rd; + next_rdx = rdx; + next_rs1 = rs1; + next_rs2 = rs2; + + for (i = 0; i < STEPS_AT_ONCE; i=i+1) begin + this_rs2 = next_rs1[0] ? next_rs2 : 0; + if (CARRY_CHAIN == 0) begin + next_rdt = next_rd ^ next_rdx ^ this_rs2; + next_rdx = ((next_rd & next_rdx) | (next_rd & this_rs2) | (next_rdx & this_rs2)) << 1; + next_rd = next_rdt; + end else begin + next_rdt = 0; + for (j = 0; j < 64; j = j + CARRY_CHAIN) + {next_rdt[j+CARRY_CHAIN-1], next_rd[j +: CARRY_CHAIN]} = + next_rd[j +: CARRY_CHAIN] + next_rdx[j +: CARRY_CHAIN] + this_rs2[j +: CARRY_CHAIN]; + next_rdx = next_rdt << 1; + end + next_rs1 = next_rs1 >> 1; + next_rs2 = next_rs2 << 1; + end + end + + always @(posedge clk) begin + mul_finish <= 0; + if (!resetn) begin + mul_waiting <= 1; + end else + if (mul_waiting) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + + rd <= 0; + rdx <= 0; + mul_counter <= (instr_any_mulh ? 63 - STEPS_AT_ONCE : 31 - STEPS_AT_ONCE); + mul_waiting <= !mul_start; + end else begin + rd <= next_rd; + rdx <= next_rdx; + rs1 <= next_rs1; + rs2 <= next_rs2; + + mul_counter <= mul_counter - STEPS_AT_ONCE; + if (mul_counter[6]) begin + mul_finish <= 1; + mul_waiting <= 1; + end + end + end + + always @(posedge clk) begin + pcpi_wr <= 0; + pcpi_ready <= 0; + if (mul_finish && resetn) begin + pcpi_wr <= 1; + pcpi_ready <= 1; + pcpi_rd <= instr_any_mulh ? rd >> 32 : rd; + end + end +endmodule + +module picorv32_pcpi_fast_mul #( + parameter EXTRA_MUL_FFS = 0, + parameter EXTRA_INSN_FFS = 0, + parameter MUL_CLKGATE = 0 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output pcpi_wr, + output [31:0] pcpi_rd, + output pcpi_wait, + output pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg shift_out; + reg [3:0] active; + reg [32:0] rs1, rs2, rs1_q, rs2_q; + reg [63:0] rd, rd_q; + + wire pcpi_insn_valid = pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001; + reg pcpi_insn_valid_q; + + always @* begin + instr_mul = 0; + instr_mulh = 0; + instr_mulhsu = 0; + instr_mulhu = 0; + + if (resetn && (EXTRA_INSN_FFS ? pcpi_insn_valid_q : pcpi_insn_valid)) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul = 1; + 3'b001: instr_mulh = 1; + 3'b010: instr_mulhsu = 1; + 3'b011: instr_mulhu = 1; + endcase + end + end + + always @(posedge clk) begin + pcpi_insn_valid_q <= pcpi_insn_valid; + if (!MUL_CLKGATE || active[0]) begin + rs1_q <= rs1; + rs2_q <= rs2; + end + if (!MUL_CLKGATE || active[1]) begin + rd <= $signed(EXTRA_MUL_FFS ? rs1_q : rs1) * $signed(EXTRA_MUL_FFS ? rs2_q : rs2); + end + if (!MUL_CLKGATE || active[2]) begin + rd_q <= rd; + end + end + + always @(posedge clk) begin + if (instr_any_mul && !(EXTRA_MUL_FFS ? active[3:0] : active[1:0])) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + active[0] <= 1; + end else begin + active[0] <= 0; + end + + active[3:1] <= active; + shift_out <= instr_any_mulh; + + if (!resetn) + active <= 0; + end + + assign pcpi_wr = active[EXTRA_MUL_FFS ? 3 : 1]; + assign pcpi_wait = 0; + assign pcpi_ready = active[EXTRA_MUL_FFS ? 3 : 1]; +`ifdef RISCV_FORMAL_ALTOPS + assign pcpi_rd = + instr_mul ? (pcpi_rs1 + pcpi_rs2) ^ 32'h5876063e : + instr_mulh ? (pcpi_rs1 + pcpi_rs2) ^ 32'hf6583fb7 : + instr_mulhsu ? (pcpi_rs1 - pcpi_rs2) ^ 32'hecfbe137 : + instr_mulhu ? (pcpi_rs1 + pcpi_rs2) ^ 32'h949ce5e8 : 1'bx; +`else + assign pcpi_rd = shift_out ? (EXTRA_MUL_FFS ? rd_q : rd) >> 32 : (EXTRA_MUL_FFS ? rd_q : rd); +`endif +endmodule + + +/*************************************************************** + * picorv32_pcpi_div + ***************************************************************/ + +module picorv32_pcpi_div ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_div, instr_divu, instr_rem, instr_remu; + wire instr_any_div_rem = |{instr_div, instr_divu, instr_rem, instr_remu}; + + reg pcpi_wait_q; + wire start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_div <= 0; + instr_divu <= 0; + instr_rem <= 0; + instr_remu <= 0; + + if (resetn && pcpi_valid && !pcpi_ready && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b100: instr_div <= 1; + 3'b101: instr_divu <= 1; + 3'b110: instr_rem <= 1; + 3'b111: instr_remu <= 1; + endcase + end + + pcpi_wait <= instr_any_div_rem && resetn; + pcpi_wait_q <= pcpi_wait && resetn; + end + + reg [31:0] dividend; + reg [62:0] divisor; + reg [31:0] quotient; + reg [31:0] quotient_msk; + reg running; + reg outsign; + + always @(posedge clk) begin + pcpi_ready <= 0; + pcpi_wr <= 0; + pcpi_rd <= 'bx; + + if (!resetn) begin + running <= 0; + end else + if (start) begin + running <= 1; + dividend <= (instr_div || instr_rem) && pcpi_rs1[31] ? -pcpi_rs1 : pcpi_rs1; + divisor <= ((instr_div || instr_rem) && pcpi_rs2[31] ? -pcpi_rs2 : pcpi_rs2) << 31; + outsign <= (instr_div && (pcpi_rs1[31] != pcpi_rs2[31]) && |pcpi_rs2) || (instr_rem && pcpi_rs1[31]); + quotient <= 0; + quotient_msk <= 1 << 31; + end else + if (!quotient_msk && running) begin + running <= 0; + pcpi_ready <= 1; + pcpi_wr <= 1; +`ifdef RISCV_FORMAL_ALTOPS + case (1) + instr_div: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h7f8529ec; + instr_divu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h10e8fd70; + instr_rem: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h8da68fa5; + instr_remu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h3138d0e1; + endcase +`else + if (instr_div || instr_divu) + pcpi_rd <= outsign ? -quotient : quotient; + else + pcpi_rd <= outsign ? -dividend : dividend; +`endif + end else begin + if (divisor <= dividend) begin + dividend <= dividend - divisor; + quotient <= quotient | quotient_msk; + end + divisor <= divisor >> 1; +`ifdef RISCV_FORMAL_ALTOPS + quotient_msk <= quotient_msk >> 5; +`else + quotient_msk <= quotient_msk >> 1; +`endif + end + end +endmodule + + +/*************************************************************** + * picorv32_axi + ***************************************************************/ + +module picorv32_axi #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output trap, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + wire mem_instr; + wire mem_ready; + wire [31:0] mem_rdata; + + picorv32_axi_adapter axi_adapter ( + .clk (clk ), + .resetn (resetn ), + .mem_axi_awvalid(mem_axi_awvalid), + .mem_axi_awready(mem_axi_awready), + .mem_axi_awaddr (mem_axi_awaddr ), + .mem_axi_awprot (mem_axi_awprot ), + .mem_axi_wvalid (mem_axi_wvalid ), + .mem_axi_wready (mem_axi_wready ), + .mem_axi_wdata (mem_axi_wdata ), + .mem_axi_wstrb (mem_axi_wstrb ), + .mem_axi_bvalid (mem_axi_bvalid ), + .mem_axi_bready (mem_axi_bready ), + .mem_axi_arvalid(mem_axi_arvalid), + .mem_axi_arready(mem_axi_arready), + .mem_axi_araddr (mem_axi_araddr ), + .mem_axi_arprot (mem_axi_arprot ), + .mem_axi_rvalid (mem_axi_rvalid ), + .mem_axi_rready (mem_axi_rready ), + .mem_axi_rdata (mem_axi_rdata ), + .mem_valid (mem_valid ), + .mem_instr (mem_instr ), + .mem_ready (mem_ready ), + .mem_addr (mem_addr ), + .mem_wdata (mem_wdata ), + .mem_wstrb (mem_wstrb ), + .mem_rdata (mem_rdata ) + ); + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); +endmodule + + +/*************************************************************** + * picorv32_axi_adapter + ***************************************************************/ + +module picorv32_axi_adapter ( + input clk, resetn, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Native PicoRV32 memory interface + + input mem_valid, + input mem_instr, + output mem_ready, + input [31:0] mem_addr, + input [31:0] mem_wdata, + input [ 3:0] mem_wstrb, + output [31:0] mem_rdata +); + reg ack_awvalid; + reg ack_arvalid; + reg ack_wvalid; + reg xfer_done; + + assign mem_axi_awvalid = mem_valid && |mem_wstrb && !ack_awvalid; + assign mem_axi_awaddr = mem_addr; + assign mem_axi_awprot = 0; + + assign mem_axi_arvalid = mem_valid && !mem_wstrb && !ack_arvalid; + assign mem_axi_araddr = mem_addr; + assign mem_axi_arprot = mem_instr ? 3'b100 : 3'b000; + + assign mem_axi_wvalid = mem_valid && |mem_wstrb && !ack_wvalid; + assign mem_axi_wdata = mem_wdata; + assign mem_axi_wstrb = mem_wstrb; + + assign mem_ready = mem_axi_bvalid || mem_axi_rvalid; + assign mem_axi_bready = mem_valid && |mem_wstrb; + assign mem_axi_rready = mem_valid && !mem_wstrb; + assign mem_rdata = mem_axi_rdata; + + always @(posedge clk) begin + if (!resetn) begin + ack_awvalid <= 0; + end else begin + xfer_done <= mem_valid && mem_ready; + if (mem_axi_awready && mem_axi_awvalid) + ack_awvalid <= 1; + if (mem_axi_arready && mem_axi_arvalid) + ack_arvalid <= 1; + if (mem_axi_wready && mem_axi_wvalid) + ack_wvalid <= 1; + if (xfer_done || !mem_valid) begin + ack_awvalid <= 0; + ack_arvalid <= 0; + ack_wvalid <= 0; + end + end + end +endmodule + + +/*************************************************************** + * picorv32_wb + ***************************************************************/ + +module picorv32_wb #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + output trap, + + // Wishbone interfaces + input wb_rst_i, + input wb_clk_i, + + output reg [31:0] wbm_adr_o, + output reg [31:0] wbm_dat_o, + input [31:0] wbm_dat_i, + output reg wbm_we_o, + output reg [3:0] wbm_sel_o, + output reg wbm_stb_o, + input wbm_ack_i, + output reg wbm_cyc_o, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data, + + output mem_instr +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + reg mem_ready; + reg [31:0] mem_rdata; + + wire clk; + wire resetn; + + assign clk = wb_clk_i; + assign resetn = ~wb_rst_i; + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); + + localparam IDLE = 2'b00; + localparam WBSTART = 2'b01; + localparam WBEND = 2'b10; + + reg [1:0] state; + + wire we; + assign we = (mem_wstrb[0] | mem_wstrb[1] | mem_wstrb[2] | mem_wstrb[3]); + + always @(posedge wb_clk_i) begin + if (wb_rst_i) begin + wbm_adr_o <= 0; + wbm_dat_o <= 0; + wbm_we_o <= 0; + wbm_sel_o <= 0; + wbm_stb_o <= 0; + wbm_cyc_o <= 0; + state <= IDLE; + end else begin + case (state) + IDLE: begin + if (mem_valid) begin + wbm_adr_o <= mem_addr; + wbm_dat_o <= mem_wdata; + wbm_we_o <= we; + wbm_sel_o <= mem_wstrb; + + wbm_stb_o <= 1'b1; + wbm_cyc_o <= 1'b1; + state <= WBSTART; + end else begin + mem_ready <= 1'b0; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBSTART:begin + if (wbm_ack_i) begin + mem_rdata <= wbm_dat_i; + mem_ready <= 1'b1; + + state <= WBEND; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBEND: begin + mem_ready <= 1'b0; + + state <= IDLE; + end + default: + state <= IDLE; + endcase + end + end +endmodule + diff --git a/kunalg123_vsdflow/verilog/spi_slave.v b/kunalg123_vsdflow/verilog/spi_slave.v new file mode 100644 index 0000000000000000000000000000000000000000..cac0352283873b69e941968267a84b4eee6c2552 --- /dev/null +++ b/kunalg123_vsdflow/verilog/spi_slave.v @@ -0,0 +1,133 @@ +`define COMMAND 2'b00 +`define ADDRESS 2'b01 +`define DATA 2'b10 +`define IDLE 2'b11 // Not used + +module spi_slave(SCK, SDI, CSB, SDO, sdoenb, idata, odata, oaddr, rdstb, wrstb); + input SCK; + input SDI; + input CSB; + output SDO; + output sdoenb; + input [7:0] idata; + output [7:0] odata; + output [7:0] oaddr; + output rdstb; + output wrstb; + + reg [7:0] addr; + reg wrstb; + reg rdstb; + reg sdoenb; + reg [1:0] state; + reg [2:0] count; + reg writemode; + reg readmode; + reg [2:0] fixed; + wire [7:0] odata; + reg [6:0] predata; + wire [7:0] oaddr; + reg [7:0] ldata; + + assign odata = {predata, SDI}; + assign oaddr = (state == `ADDRESS) ? {addr[6:0], SDI} : addr; + assign SDO = ldata[7]; + + // Readback data is captured on the falling edge of SCK so that + // it is guaranteed valid at the next rising edge. + always @(negedge SCK or posedge CSB) begin + if (CSB == 1'b1) begin + wrstb <= 1'b0; + ldata <= 8'b00000000; + sdoenb <= 1'b1; + end else begin + + // After CSB low, 1st SCK starts command + + if (state == `DATA) begin + if (readmode == 1'b1) begin + sdoenb <= 1'b0; + if (count == 3'b000) begin + ldata <= idata; + end else begin + ldata <= {ldata[6:0], 1'b0}; // Shift out + end + end else begin + sdoenb <= 1'b1; + end + + // Apply write strobe on SCK negative edge on the next-to-last + // data bit so that it updates data on the rising edge of SCK + // on the last data bit. + + if (count == 3'b111) begin + if (writemode == 1'b1) begin + wrstb <= 1'b1; + end + end else begin + wrstb <= 1'b0; + end + end else begin + wrstb <= 1'b0; + sdoenb <= 1'b1; + end // ! state `DATA + end // ! CSB + end // always @ ~SCK + + always @(posedge SCK or posedge CSB) begin + if (CSB == 1'b1) begin + // Default state on reset + addr <= 8'h00; + rdstb <= 1'b0; + predata <= 7'b0000000; + state <= `COMMAND; + count <= 3'b000; + readmode <= 1'b0; + writemode <= 1'b0; + fixed <= 3'b000; + end else begin + // After CSB low, 1st SCK starts command + if (state == `COMMAND) begin + rdstb <= 1'b0; + count <= count + 1; + if (count == 3'b000) begin + writemode <= SDI; + end else if (count == 3'b001) begin + readmode <= SDI; + end else if (count < 3'b101) begin + fixed <= {fixed[1:0], SDI}; + end else if (count == 3'b111) begin + state <= `ADDRESS; + end + end else if (state == `ADDRESS) begin + count <= count + 1; + addr <= {addr[6:0], SDI}; + if (count == 3'b111) begin + if (readmode == 1'b1) begin + rdstb <= 1'b1; + end + state <= `DATA; + end else begin + rdstb <= 1'b0; + end + end else if (state == `DATA) begin + predata <= {predata[6:0], SDI}; + count <= count + 1; + if (count == 3'b111) begin + if (fixed == 3'b001) begin + state <= `COMMAND; + end else if (fixed != 3'b000) begin + fixed <= fixed - 1; + addr <= addr + 1; // Auto increment address (fixed) + end else begin + addr <= addr + 1; // Auto increment address (streaming) + end + end else begin + rdstb <= 1'b0; + end + end // ! state `DATA + end // ! CSB + end // always @ SCK + +endmodule // spi_slave + diff --git a/kunalg123_vsdflow/vsdflow.tcl b/kunalg123_vsdflow/vsdflow.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b7077e404ba1826c4b63fd8ba1c50a43a8cca606 --- /dev/null +++ b/kunalg123_vsdflow/vsdflow.tcl @@ -0,0 +1,468 @@ +#! /bin/env tclsh +#----------------------------------------------------------------------------------------------# +puts "-------------- Below settings will ensure the correct behavior of vsdsynth -------------------" +puts "-----Please review below settings with VSD team or drop an email to kunalpghosh@gmail.com-----\n" +#----------------------------------------------------------------------------------------------# + +puts "Set your technology using variable \"tech_name\"" +set tech_name osu018 +puts "Setting technology to $tech_name" + +puts "This is the place where all procs are located" +set proc_dir procs +puts "Setting variable 'proc_dir' to $proc_dir\n" + +puts "tcl_precision specifies the number of digits to generate when converting floating point values to strings" +set tcl_precision 3 +puts "Setting variable 'tcl_precision' to $tcl_precision\n" + +puts "Set run_synthesis variable to '1' if you want to run synthesis. If you want to use the.prelayout.timing.rpt of previous runs. which is stored in outdir_, set this variable to '0' to skip synthesis and jump to STA" +set run_synthesis 1 +puts "Setting variable 'run_synthesis' to $run_synthesis\n" + + +puts "Set generate_sdc to '1' if you want to generate SDC from data given in excel sheet. If you already have sdc, save it in outdir_ as .sdc and set this variable to '0'" +set generate_sdc 1 +puts "Setting variable 'generate_sdc' to $generate_sdc\n" + +puts "Set enable_prelayout_timing to '1' for running STA with zero-wire load parasitics. If you have generated spef, set this variable to '0'" +set enable_prelayout_timing 1 +puts "Setting variable 'enable_prelayout_timing' to $enable_prelayout_timing\n" + +puts "Set do_STA to '1' if you want to run STA after synthesis. Else, set this variable to '0'" +set do_STA 1 +puts "Setting variable 'do_STA' to $do_STA\n" + +puts "Set generate_report to '1' if you want to generate QOR of your design. Else, set this variable to '0'" +set generate_report 0 +puts "Setting variable 'generate_report' to $generate_report\n" + +puts "If generate_report is '1', there are currently 2 kinds of reporting format we provide. If you need horizontal reporting, set generate_horizontal_report to '1'" +set generate_horizontal_report 1 +puts "Setting variable 'generate_horizontal_report' to $generate_horizontal_report\n" + +puts "If generate_report is '1', there are currently 2 kinds of reporting format we provide. If you need vertical reporting, set generate_horizontal_report to '1'" +set generate_vertical_report 1 +puts "Setting variable 'generate_vertical_report' to $generate_vertical_report\n" + +puts "If run_place_and_route is '1', it will run placement and routing" +set run_place_and_route 1 +puts "Setting variable 'run_place_and_route' to $run_place_and_route\n" +#-----------------------------------------------------------# +#----- Checks whether vsdsynth usage is correct or not -----# +#-----------------------------------------------------------# + +set working_dir [exec pwd] +set vsd_array_length [llength [split [lindex $argv 0] .]] +set input [lindex [split [lindex $argv 0] .] $vsd_array_length-1] + +if {![regexp {^csv} $input] || $argc!=1 } { + puts "Error in usage" + puts "Usage: ./vsdsynth <.csv>" + puts "where <.csv> file has below inputs" + exit +} else { +#-----------------------------------------------------------------------------------------------------------------------------------------------------# +#------ converts .csv to matrix and creates initial variables "DesignName OutputDirectory NetlistDirectory EarlyLibraryPath LateLibraryPath"----------# +#----------- If you are modifying this script, please use above variables as starting point. Use "puts" command to report above variables-------------# +#-----------------------------------------------------------------------------------------------------------------------------------------------------# + set filename [lindex $argv 0] + package require csv + package require struct::matrix + struct::matrix m + set f [open $filename] + csv::read2matrix $f m , auto + close $f + set columns [m columns] + m add columns $columns + m link my_arr + set num_of_rows [m rows] + set i 0 + while {$i < $num_of_rows} { + puts "\nInfo: Setting $my_arr(0,$i) as '$my_arr(1,$i)'" + if {$i == 0} { + set [string map {" " ""} $my_arr(0,$i)] $my_arr(1,$i) + } else { + set [string map {" " ""} $my_arr(0,$i)] [file normalize $my_arr(1,$i)] + } + set i [expr {$i+1}] + } +} + +puts "\nInfo: Below are the list of initial variables and their values. User can use these variables for further debug. Use 'puts ' command to query value of below variables" +puts "DesignName = $DesignName" +puts "OutputDirectory = $OutputDirectory" +puts "NetlistDirectory = $NetlistDirectory" +puts "EarlyLibraryPath = $EarlyLibraryPath" +puts "LateLibraryPath = $LateLibraryPath" +puts "ConstraintsFile = $ConstraintsFile" + +#-------------------------------------------------------------------------------------------# +#-----Below script checks if directories and files mentioned in csv file, exists or not-----# +#-------------------------------------------------------------------------------------------# +if {![file isdirectory temp]} { + file mkdir temp +} + +if {! [file exists $EarlyLibraryPath] } { + puts "\nError: Cannot find early cell library in path $EarlyLibraryPath. Exiting... " + exit +} else { + puts "\nInfo: Early cell library found in path $EarlyLibraryPath" +} + + +if {! [file exists $LateLibraryPath]} { + puts "\nError: Cannot find late cell library in path $LateLibraryPath. Exiting... " + exit +} else { + puts "\nInfo: Late cell library found in path $LateLibraryPath" +} + +if {![file isdirectory $OutputDirectory]} { + puts "\nInfo: Cannot find output directory $OutputDirectory. Creating $OutputDirectory" + file mkdir $OutputDirectory +} else { + puts "\nInfo: Output directory found in path $OutputDirectory" +} + +if {! [file isdirectory $NetlistDirectory]} { + puts "\nError: Cannot find RTL netlist directory in path $NetlistDirectory. Exiting..." + exit +} else { + puts "\nInfo: RTL netlist directory found in path $NetlistDirectory" +} + +if {! [file exists $ConstraintsFile] } { + puts "\nError: Cannot find constraints file in path $ConstraintsFile. Exiting... " + exit +} else { + puts "\nInfo: Constraints file found in path $ConstraintsFile" +} + + +#----------------------------------------------------------------------------# +#---------------------- Constraints FILE creations--------------------------# +#----------------------------- SDC Format -----------------------------------# +#----------------------------------------------------------------------------# +if {$generate_sdc == 1} { + +puts "\nInfo: Dumping SDC constraints for $DesignName" +::struct::matrix constraints +set chan [open $ConstraintsFile] +csv::read2matrix $chan constraints , auto +close $chan +set number_of_rows [constraints rows] +set number_of_columns [constraints columns] + +#-----check row number for "clocks" and column number for "IO delays and slew section" in constraints.csv---## +set clock_start [lindex [lindex [constraints search all CLOCKS] 0 ] 1] +set clock_start_column [lindex [lindex [constraints search all CLOCKS] 0 ] 0] +set clock_period [constraints get cell [expr {$clock_start+1}] [expr {$clock_start_column+1}]] + +#-----check row number for "inputs" section in constraints.csv---## +set input_ports_start [lindex [lindex [constraints search all INPUTS] 0 ] 1] + +#-----check row number for "outputs" section in constraints.csv---## +set output_ports_start [lindex [lindex [constraints search all OUTPUTS] 0 ] 1] + +#-------------------clock constraints--------------------## +#-------------------clock latency constraints------------# + +set clock_early_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] early_rise_delay] 0 ] 0] + +set clock_early_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] early_fall_delay] 0 ] 0] + +set clock_late_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] late_rise_delay] 0 ] 0] + +set clock_late_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] late_fall_delay] 0 ] 0] + +#-------------------clock transition constraints------------# + +set clock_early_rise_slew_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] early_rise_slew] 0 ] 0] + +set clock_early_fall_slew_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] early_fall_slew] 0 ] 0] + +set clock_late_rise_slew_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] late_rise_slew] 0 ] 0] + +set clock_late_fall_slew_start [lindex [lindex [constraints search rect $clock_start_column $clock_start [expr {$number_of_columns-1}] [expr {$input_ports_start-1}] late_fall_slew] 0 ] 0] + +set sdc_file [open $OutputDirectory/$DesignName.sdc "w"] +set i [expr {$clock_start+1}] +set end_of_ports [expr {$input_ports_start-1}] +puts "\nInfo-SDC: Working on clock constraints....." +while { $i < $end_of_ports } { + puts -nonewline $sdc_file "\ncreate_clock -name [constraints get cell 0 $i] -period [constraints get cell 1 $i] -waveform \{0 [expr {[constraints get cell 1 $i]*[constraints get cell 2 $i]/100}]\} \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_transition -rise -min [constraints get cell $clock_early_rise_slew_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_transition -fall -min [constraints get cell $clock_early_fall_slew_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_transition -rise -max [constraints get cell $clock_late_rise_slew_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_transition -fall -max [constraints get cell $clock_late_fall_slew_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_delay -min -rise [constraints get cell $clock_early_rise_delay_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_delay -min -fall [constraints get cell $clock_early_fall_delay_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_delay -max -rise [constraints get cell $clock_late_rise_delay_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + puts -nonewline $sdc_file "\nset_input_delay -max -fall [constraints get cell $clock_late_fall_delay_start $i] -clock [constraints get cell 0 $i] \[get_ports [constraints get cell 0 $i]\]" + set i [expr {$i+1}] +} + +#------------------------------------------------------------------------------## +#-------------------create input delay and slew constraints--------------------## +#------------------------------------------------------------------------------## + +set input_early_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] early_rise_delay] 0 ] 0] +set input_early_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] early_fall_delay] 0 ] 0] +set input_late_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] late_rise_delay] 0 ] 0] +set input_late_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] late_fall_delay] 0 ] 0] + +set input_early_rise_slew_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] early_rise_slew] 0 ] 0] +set input_early_fall_slew_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] early_fall_slew] 0 ] 0] +set input_late_rise_slew_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] late_rise_slew] 0 ] 0] +set input_late_fall_slew_start [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] late_fall_slew] 0 ] 0] + + +set related_clock [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] clocks] 0 ] 0] +set bussed_status [lindex [lindex [constraints search rect $clock_start_column $input_ports_start [expr {$number_of_columns-1}] [expr {$output_ports_start-1}] bussed] 0 ] 0] + +set i [expr {$input_ports_start+1}] +set end_of_ports [expr {$output_ports_start-1}] +puts "\nInfo-SDC: Working on IO constraints....." +puts "\nInfo-SDC: Categorizing input ports as bits and bussed" + +while { $i < $end_of_ports } { +#--------------------------optional script----differentiating input ports as bussed and bits------# +set netlist [glob -dir $NetlistDirectory *.v] +set tmp_file [open ./temp/1 w] +foreach f $netlist { + set fd [open $f] + while {[gets $fd line] != -1} { + set pattern1 " [constraints get cell 0 $i];" + if {[regexp -all -- $pattern1 $line]} { + set pattern2 [lindex [split $line ";"] 0] + if {[regexp -all {input} [lindex [split $pattern2 "\S+"] 0]]} { + set s1 "[lindex [split $pattern2 "\S+"] 0] [lindex [split $pattern2 "\S+"] 1] [lindex [split $pattern2 "\S+"] 2]" + puts -nonewline $tmp_file "\n[regsub -all {\s+} $s1 " "]" + } + } + } +close $fd +} +close $tmp_file +set tmp_file [open ./temp/1 r] +set tmp2_file [open ./temp/2 w] +puts -nonewline $tmp2_file "[join [lsort -unique [split [read $tmp_file] \n]] \n]" +close $tmp_file +close $tmp2_file +set tmp2_file [open ./temp/2 r] +set count [split [llength [read $tmp2_file]] " "] +set check_bussed [constraints get cell $bussed_status $i] +if {$count > 2 || $check_bussed == "yes"} { + set inp_ports [concat [constraints get cell 0 $i]*] + } else { + set inp_ports [constraints get cell 0 $i] + } + puts -nonewline $sdc_file "\nset_input_delay -clock [constraints get cell $related_clock $i] -min -rise [constraints get cell $input_early_rise_delay_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_delay -clock [constraints get cell $related_clock $i] -min -fall [constraints get cell $input_early_fall_delay_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_delay -clock [constraints get cell $related_clock $i] -max -rise [constraints get cell $input_late_rise_delay_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_delay -clock [constraints get cell $related_clock $i] -max -fall [constraints get cell $input_late_fall_delay_start $i] \[get_ports $inp_ports\]" + + puts -nonewline $sdc_file "\nset_input_transition -clock [constraints get cell $related_clock $i] -min -rise [constraints get cell $input_early_rise_slew_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_transition -clock [constraints get cell $related_clock $i] -min -fall [constraints get cell $input_early_fall_slew_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_transition -clock [constraints get cell $related_clock $i] -max -rise [constraints get cell $input_late_rise_slew_start $i] \[get_ports $inp_ports\]" + puts -nonewline $sdc_file "\nset_input_transition -clock [constraints get cell $related_clock $i] -max -fall [constraints get cell $input_late_fall_slew_start $i] \[get_ports $inp_ports\]" + + + set i [expr {$i+1}] +} +close $tmp2_file +#------------------------------------------------------------------------------## +#-------------------create output delay and load constraints--------------------## +#------------------------------------------------------------------------------## + +set output_early_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] early_rise_delay] 0 ] 0] +set output_early_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] early_fall_delay] 0 ] 0] +set output_late_rise_delay_start [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] late_rise_delay] 0 ] 0] +set output_late_fall_delay_start [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] late_fall_delay] 0 ] 0] +set output_load_start [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] load] 0 ] 0] +set related_clock [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] clocks] 0 ] 0] +set bussed_status [lindex [lindex [constraints search rect $clock_start_column $output_ports_start [expr {$number_of_columns-1}] [expr {$number_of_rows-1}] bussed] 0 ] 0] + +set i [expr {$output_ports_start+1}] +set end_of_ports [expr {$number_of_rows}] +puts "\nInfo-SDC: Working on IO constraints....." +puts "\nInfo-SDC: Categorizing output ports as bits and bussed" + +while { $i < $end_of_ports } { +#--------------------------optional script----differentiating input ports as bussed and bits------# +set netlist [glob -dir $NetlistDirectory *.v] +set tmp_file [open ./temp/1 w] +foreach f $netlist { + set fd [open $f] + while {[gets $fd line] != -1} { + set pattern1 " [constraints get cell 0 $i];" + if {[regexp -all -- $pattern1 $line]} { + set pattern2 [lindex [split $line ";"] 0] + if {[regexp -all {output} [lindex [split $pattern2 "\S+"] 0]]} { + set s1 "[lindex [split $pattern2 "\S+"] 0] [lindex [split $pattern2 "\S+"] 1] [lindex [split $pattern2 "\S+"] 2]" + puts -nonewline $tmp_file "\n[regsub -all {\s+} $s1 " "]" + } + } + } +close $fd +} +close $tmp_file +set tmp_file [open ./temp/1 r] +set tmp2_file [open ./temp/2 w] +puts -nonewline $tmp2_file "[join [lsort -unique [split [read $tmp_file] \n]] \n]" +close $tmp_file +close $tmp2_file +set tmp2_file [open ./temp/2 r] +set count [split [llength [read $tmp2_file]]] +set check_bussed [constraints get cell $bussed_status $i] + +if {$count > 2 || $check_bussed == "yes"} { + set op_ports [concat [constraints get cell 0 $i]*] +} else { + set op_ports [constraints get cell 0 $i] +} + puts -nonewline $sdc_file "\nset_output_delay -clock [constraints get cell $related_clock $i] -min -rise [constraints get cell $output_early_rise_delay_start $i] \[get_ports $op_ports\]" + puts -nonewline $sdc_file "\nset_output_delay -clock [constraints get cell $related_clock $i] -min -fall [constraints get cell $output_early_fall_delay_start $i] \[get_ports $op_ports\]" + puts -nonewline $sdc_file "\nset_output_delay -clock [constraints get cell $related_clock $i] -max -rise [constraints get cell $output_late_rise_delay_start $i] \[get_ports $op_ports\]" + puts -nonewline $sdc_file "\nset_output_delay -clock [constraints get cell $related_clock $i] -max -fall [constraints get cell $output_late_fall_delay_start $i] \[get_ports $op_ports\]" + puts -nonewline $sdc_file "\nset_load [constraints get cell $output_load_start $i] \[get_ports $op_ports\]" + set i [expr {$i+1}] +} +close $tmp2_file +close $sdc_file + +puts "\nInfo: SDC created. Please use constraints in path $OutputDirectory/$DesignName.sdc" +} +#----------------------------------------------------------------------------# +#-------------Hierarchy check and synthesis using yosys from qflow-----------# +#----------------------------------------------------------------------------# +puts "\nStarting synthesis using qflow" +if {$run_synthesis == 1} { + +if {![file isdirectory $OutputDirectory/source]} { +file mkdir $OutputDirectory/source +} + +if {![file isdirectory $OutputDirectory/synthesis]} { +file mkdir $OutputDirectory/synthesis +} + +if {![file isdirectory $OutputDirectory/layout]} { +file mkdir $OutputDirectory/layout +} + +set netlist [glob -dir $NetlistDirectory *.v] +foreach f $netlist { + set qverilog [file tail $f] + if {![file exists $OutputDirectory/source/$qverilog]} { + file link -symbolic $OutputDirectory/source/$qverilog $f + } +} +cd $OutputDirectory +set err [catch {exec qflow -T $tech_name synthesize $DesignName}] +cd $working_dir + +#if {[file exists $OutputDirectory/$DesignName.synth.v]} { +# file delete -force $OutputDirectory/$DesignName.synth.v +# } + +#file link -symbolic $OutputDirectory/$DesignName.synth.v $OutputDirectory/synthesis/$DesignName.rtlnopwr.v +} + +if {$run_synthesis == 1} { + if {$err == 1} { + puts "\nSynthesis finished with errors" + } else { + puts "\nSynthesis finished without errors" + } + + puts "\nPlease review log file \"$OutputDirectory/log/synth.log\" for errors/warnings " + + +#set pnr_settings [open $OutputDirectory/project_vars.sh a] +#puts $pnr_settings "set initial_density = 0.6" +#puts $pnr_settings "set addspacers_options = \"-stripe 5 200 PG\"" +#puts $pnr_settings "set route_layers = 5" +#puts $pnr_settings " set vesta_options = \"--period $clock_period\"" +#close $pnr_settings +} + +#---------------------------------------------------------------------------------------------# +#------------------------- Edit synth.v to be usable by Opentimer-----------------------------# +#---------------------------------------------------------------------------------------------# + + +#set output [open $OutputDirectory/$DesignName.final.synth.v "w"] + +#set filename "$OutputDirectory/${DesignName}_synth.rtlbb.v" +#set fid [open $filename r] +# while {[gets $fid line] != -1} { +# puts -nonewline $output [string map {"wire vdd = 1'b1;" "" "wire gnd = 1'b0;" "" "vdd" "1'h1" "gnd" "1'h0"} $line] +# puts -nonewline $output "\n" +#} +#close $fid +#close $output + +puts "\nInfo: Please find the synthesized netlist for $DesignName at below path. You can use this netlist for STA or PNR" +puts "\n$OutputDirectory/synthesis/${DesignName}_synth.rtlbb.v" +file copy -force $OutputDirectory/synthesis/${DesignName}.rtlnopwr.v $OutputDirectory/$DesignName.final.synth.v +source $proc_dir/read_sdc.proc +read_sdc $OutputDirectory/$DesignName.sdc + +#--------------------------------------------------------------------------------------------------# +#-------------------------Static timing analysis using Opentimer-----------------------------------# +#--------------------------------------------------------------------------------------------------# +if {$enable_prelayout_timing == 1} { + puts "\nInfo: Pre-layout STA started" + cd $working_dir + source $proc_dir/call_timer.tcl + set qorReportName $OutputDirectory/$DesignName.prelayout.timing.qor + + cd $OutputDirectory + catch {exec qflow sta $DesignName >& $OutputDirectory/$DesignName.vesta.log} + file copy -force $OutputDirectory/log/sta.log $OutputDirectory/$DesignName.${prefix}.vesta.log + puts "\nInfo: Pre-layout STA finished" +} + +#----------------------------------------------------------------------------# +#--------------------------------PNR from qflow------------------------------# +#----------------------------------------------------------------------------# + +puts "\nCreating a backup of synthesis netlist" + +#file copy -force -force $OutputDirectory/synthesis/$DesignName.rtlnopwr.v $OutputDirectory/synthesis/$DesignName.rtlnopwr.mysynth.v +#file copy -force -force $OutputDirectory/synthesis/$DesignName.rtl.v $OutputDirectory/synthesis/$DesignName.rtl.mysynth.v +#file copy -force -force $OutputDirectory/synthesis/$DesignName.spc $OutputDirectory/synthesis/$DesignName.mysynth.spc + +if {$run_place_and_route == 1} { + puts "\nPlace and Route step from qflow started" + cd $OutputDirectory + set err [catch {exec qflow place route $DesignName}] + cd $working_dir + puts "\nPlace and Route step from qflow finished" + + + + #file copy -force $OutputDirectory/$DesignName.conf $OutputDirectory/$DesignName.postlayout.conf + + #set inputConfFile $OutputDirectory/$DesignName.postlayout.conf + #set outputReportFileName $OutputDirectory/$DesignName.postlayout.timing.rpt + set qorReportName $OutputDirectory/$DesignName.postlayout.timing.qor + + puts "\nInfo: Post-layout STA started" + cd $OutputDirectory + catch {exec qflow backanno $DesignName >& $OutputDirectory/$DesignName.vesta.log} + #file copy -force $OutputDirectory/log/post_sta.log $OutputDirectory/$DesignName.postlayout.vesta.log + file copy -force $OutputDirectory/synthesis/${DesignName}.rtlnopwr.v $OutputDirectory/$DesignName.final.synth.v + + cd $working_dir + set enable_prelayout_timing 0 + source $proc_dir/call_timer.tcl +puts "\nInfo: Please find the synthesized netlist for $DesignName at below path. You can use this netlist for STA or PNR" +puts "\n$OutputDirectory/synthesis/${DesignName}.rtlbb.v" + + puts "\nInfo: Post-layout STA finished" +} + diff --git a/nanamake_r22sdf/README.md b/nanamake_r22sdf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..070c491b51c05fedf899b74e3546eacd39f07b40 --- /dev/null +++ b/nanamake_r22sdf/README.md @@ -0,0 +1,81 @@ +r22sdf +====== + +Implementation of pipeline FFT described in Verilog HDL. + +* Radix-22 single-path delay feedback (R22SDF) architecture +* Scaled fixed-point arithmetic +* Synthesizable with FPGA implementation software + + +Interface +--------- + + module FFT #( + parameter WIDTH = 16 + )( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) + ); + +Data must be input consecutively in natural order. +The result is scaled to 1/N and output in bit-reversed order. +The output latency differs depending on the transform size. +For 64-point FFT, it is 71 clock cycles. + +*64-point FFT timing diagram* +![64-point FFT timing diagram](img/fft64_wave.png) + + +Source Files +------------ + +There are two kinds of configurations. + +* Basic configuration for small size FFT +* Resource saving configuration for large size FFT + +In my environment, when the number of FFT points is greater than or equal to 256 + it is better to use the resource saving configuration. + +For the basic configuration, use the following files. + + FFT.v + SdfUnit.v + SdfUnit2.v + Butterfly.v + DelayBuffer.v + Multiply.v + Twiddle.v + +*FFT.v* and *Twiddle.v* must be created according to the number of FFT points + and the data bit length. +*SdfUnit2.v* is required if the number of FFT points is not a power of 4. +To make a resource saving configuration, replace *SdfUnit.v* with *SdfUnit_TC.v* + and add *TwiddleConvert4.v* or *TwiddleConvert8.v*. + +*TwiddleConvert4* reduces the table size of *Twiddle* to 1/4. +Likewise, *TwiddleConvert8* reduces it to 1/8, but requires more additional logic + than *TwiddleConvert4*. +*TwiddleConvert8* is used by default, but *TwiddleConvert4* may be better in some cases. + + +Architecture +------------ + +Radix-22 single-path delay feedback (R22SDF) + is known as an efficient implementation of pipeline FFT. +There is radix-2 single-path delay feedback (R2SDF) in a similar architecture, + but R22SDF uses fewer multipliers. + +![64-point FFT block diagram](img/fft64_block.png) + +![SDF unit block diagram](img/sdfunit.png) + +![Deriving radix-22 butterfly](img/butterfly.png) diff --git a/nanamake_r22sdf/img/fft64_wave.json b/nanamake_r22sdf/img/fft64_wave.json new file mode 100644 index 0000000000000000000000000000000000000000..5aefbb69161de2eb523c658e57658aabffba9b79 --- /dev/null +++ b/nanamake_r22sdf/img/fft64_wave.json @@ -0,0 +1,9 @@ +{ signal: [ + { name: 'di_en' , wave: '0.1...|.0.........', node: '..a...............' }, + { name: 'di_re/im', wave: 'x.===x|=x.........', data: 'D0 D1 D2 D63' }, + { node: '..b.......c.......' }, + { name: 'do_en' , wave: '0........|1...|.0.', node: '..........d.......' }, + { name: 'do_re/im', wave: 'x........|===x|=x.', data: 'D0 D1 D2 D63' }, + ], + edge: ['a|b', 'b<->c 71 clock cycles', 'c|d'], +} diff --git a/nanamake_r22sdf/sim/fft_128_tc/TB128.v b/nanamake_r22sdf/sim/fft_128_tc/TB128.v new file mode 100644 index 0000000000000000000000000000000000000000..cca807d3edfee95c3e08e7473c6f4ec7e1f3f6f5 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/TB128.v @@ -0,0 +1,132 @@ +//---------------------------------------------------------------------- +// TB: FftTop Testbench +//---------------------------------------------------------------------- +`timescale 1ns/1ns +module TB #( + parameter N = 128 +); + +localparam NN = log2(N); // Count Bit Width of FFT Point + +// log2 constant function +function integer log2; + input integer x; + integer value; + begin + value = x-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end +endfunction + +// Internal Regs and Nets +reg clock; +reg reset; +reg di_en; +reg [15:0] di_re; +reg [15:0] di_im; +wire do_en; +wire[15:0] do_re; +wire[15:0] do_im; + +reg [15:0] imem[0:2*N-1]; +reg [15:0] omem[0:2*N-1]; + +//---------------------------------------------------------------------- +// Clock and Reset +//---------------------------------------------------------------------- +always begin + clock = 0; #10; + clock = 1; #10; +end + +initial begin + reset = 0; #20; + reset = 1; #100; + reset = 0; +end + +//---------------------------------------------------------------------- +// Functional Blocks +//---------------------------------------------------------------------- + +// Input Control Initialize +initial begin + wait (reset == 1); + di_en = 0; +end + +// Output Data Capture +initial begin : OCAP + integer n; + forever begin + n = 0; + while (do_en !== 1) @(negedge clock); + while ((do_en == 1) && (n < N)) begin + omem[2*n ] = do_re; + omem[2*n+1] = do_im; + n = n + 1; + @(negedge clock); + end + end +end + +//---------------------------------------------------------------------- +// Tasks +//---------------------------------------------------------------------- +task LoadInputData; + input[80*8:1] filename; +begin + $readmemh(filename, imem); +end +endtask + +task GenerateInputWave; + integer n; +begin + di_en <= 1; + for (n = 0; n < N; n = n + 1) begin + di_re <= imem[2*n]; + di_im <= imem[2*n+1]; + @(posedge clock); + end + di_en <= 0; + di_re <= 'bx; + di_im <= 'bx; +end +endtask + +task SaveOutputData; + input[80*8:1] filename; + integer fp, n, m, i; +begin + fp = $fopen(filename); + m = 0; + for (n = 0; n < N; n = n + 1) begin + for (i = 0; i < NN; i = i + 1) m[NN-1-i] = n[i]; + $fdisplay(fp, "%h %h // %d", omem[2*m], omem[2*m+1], n[NN-1:0]); + end + $fclose(fp); +end +endtask + +//---------------------------------------------------------------------- +// Module Instances +//---------------------------------------------------------------------- +FFT FFT ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (di_en ), // i + .di_re (di_re ), // i + .di_im (di_im ), // i + .do_en (do_en ), // o + .do_re (do_re ), // o + .do_im (do_im ) // o +); + +//---------------------------------------------------------------------- +// Include Stimuli +//---------------------------------------------------------------------- +`include "stim.v" + +endmodule diff --git a/nanamake_r22sdf/sim/fft_128_tc/input4.txt b/nanamake_r22sdf/sim/fft_128_tc/input4.txt new file mode 100644 index 0000000000000000000000000000000000000000..7959ed387748076b6ce3bcf34db14ecef5db5e44 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/input4.txt @@ -0,0 +1,128 @@ +7FFD 0000 // 0 1.000 0.000 +7FD5 0000 // 1 0.999 0.000 +7F5F 0000 // 2 0.995 0.000 +7E9A 0000 // 3 0.989 0.000 +7D87 0000 // 4 0.981 0.000 +7C27 0000 // 5 0.970 0.000 +7A7A 0000 // 6 0.957 0.000 +7881 0000 // 7 0.941 0.000 +763F 0000 // 8 0.924 0.000 +73B3 0000 // 9 0.904 0.000 +70E0 0000 // 10 0.882 0.000 +6DC7 0000 // 11 0.858 0.000 +6A6B 0000 // 12 0.831 0.000 +66CD 0000 // 13 0.803 0.000 +62EF 0000 // 14 0.773 0.000 +5ED5 0000 // 15 0.741 0.000 +5A80 0000 // 16 0.707 0.000 +55F3 0000 // 17 0.671 0.000 +5132 0000 // 18 0.634 0.000 +4C3E 0000 // 19 0.596 0.000 +471B 0000 // 20 0.556 0.000 +41CC 0000 // 21 0.514 0.000 +3C55 0000 // 22 0.471 0.000 +36B9 0000 // 23 0.428 0.000 +30FB 0000 // 24 0.383 0.000 +2B1E 0000 // 25 0.337 0.000 +2527 0000 // 26 0.290 0.000 +1F19 0000 // 27 0.243 0.000 +18F8 0000 // 28 0.195 0.000 +12C8 0000 // 29 0.147 0.000 +0C8C 0000 // 30 0.098 0.000 +0648 0000 // 31 0.049 0.000 +0000 0000 // 32 0.000 0.000 +F9B8 0000 // 33 -0.049 0.000 +F374 0000 // 34 -0.098 0.000 +ED38 0000 // 35 -0.147 0.000 +E708 0000 // 36 -0.195 0.000 +E0E7 0000 // 37 -0.243 0.000 +DAD9 0000 // 38 -0.290 0.000 +D4E2 0000 // 39 -0.337 0.000 +CF05 0000 // 40 -0.383 0.000 +C947 0000 // 41 -0.428 0.000 +C3AB 0000 // 42 -0.471 0.000 +BE34 0000 // 43 -0.514 0.000 +B8E5 0000 // 44 -0.556 0.000 +B3C2 0000 // 45 -0.596 0.000 +AECE 0000 // 46 -0.634 0.000 +AA0D 0000 // 47 -0.671 0.000 +A580 0000 // 48 -0.707 0.000 +A12B 0000 // 49 -0.741 0.000 +9D11 0000 // 50 -0.773 0.000 +9933 0000 // 51 -0.803 0.000 +9595 0000 // 52 -0.831 0.000 +9239 0000 // 53 -0.858 0.000 +8F20 0000 // 54 -0.882 0.000 +8C4D 0000 // 55 -0.904 0.000 +89C1 0000 // 56 -0.924 0.000 +877F 0000 // 57 -0.941 0.000 +8586 0000 // 58 -0.957 0.000 +83D9 0000 // 59 -0.970 0.000 +8279 0000 // 60 -0.981 0.000 +8166 0000 // 61 -0.989 0.000 +80A1 0000 // 62 -0.995 0.000 +802B 0000 // 63 -0.999 0.000 +8003 0000 // 64 -1.000 0.000 +802B 0000 // 65 -0.999 0.000 +80A1 0000 // 66 -0.995 0.000 +8166 0000 // 67 -0.989 0.000 +8279 0000 // 68 -0.981 0.000 +83D9 0000 // 69 -0.970 0.000 +8586 0000 // 70 -0.957 0.000 +877F 0000 // 71 -0.941 0.000 +89C1 0000 // 72 -0.924 0.000 +8C4D 0000 // 73 -0.904 0.000 +8F20 0000 // 74 -0.882 0.000 +9239 0000 // 75 -0.858 0.000 +9595 0000 // 76 -0.831 0.000 +9933 0000 // 77 -0.803 0.000 +9D11 0000 // 78 -0.773 0.000 +A12B 0000 // 79 -0.741 0.000 +A580 0000 // 80 -0.707 0.000 +AA0D 0000 // 81 -0.671 0.000 +AECE 0000 // 82 -0.634 0.000 +B3C2 0000 // 83 -0.596 0.000 +B8E5 0000 // 84 -0.556 0.000 +BE34 0000 // 85 -0.514 0.000 +C3AB 0000 // 86 -0.471 0.000 +C947 0000 // 87 -0.428 0.000 +CF05 0000 // 88 -0.383 0.000 +D4E2 0000 // 89 -0.337 0.000 +DAD9 0000 // 90 -0.290 0.000 +E0E7 0000 // 91 -0.243 0.000 +E708 0000 // 92 -0.195 0.000 +ED38 0000 // 93 -0.147 0.000 +F374 0000 // 94 -0.098 0.000 +F9B8 0000 // 95 -0.049 0.000 +0000 0000 // 96 -0.000 0.000 +0648 0000 // 97 0.049 0.000 +0C8C 0000 // 98 0.098 0.000 +12C8 0000 // 99 0.147 0.000 +18F8 0000 // 100 0.195 0.000 +1F19 0000 // 101 0.243 0.000 +2527 0000 // 102 0.290 0.000 +2B1E 0000 // 103 0.337 0.000 +30FB 0000 // 104 0.383 0.000 +36B9 0000 // 105 0.428 0.000 +3C55 0000 // 106 0.471 0.000 +41CC 0000 // 107 0.514 0.000 +471B 0000 // 108 0.556 0.000 +4C3E 0000 // 109 0.596 0.000 +5132 0000 // 110 0.634 0.000 +55F3 0000 // 111 0.671 0.000 +5A80 0000 // 112 0.707 0.000 +5ED5 0000 // 113 0.741 0.000 +62EF 0000 // 114 0.773 0.000 +66CD 0000 // 115 0.803 0.000 +6A6B 0000 // 116 0.831 0.000 +6DC7 0000 // 117 0.858 0.000 +70E0 0000 // 118 0.882 0.000 +73B3 0000 // 119 0.904 0.000 +763F 0000 // 120 0.924 0.000 +7881 0000 // 121 0.941 0.000 +7A7A 0000 // 122 0.957 0.000 +7C27 0000 // 123 0.970 0.000 +7D87 0000 // 124 0.981 0.000 +7E9A 0000 // 125 0.989 0.000 +7F5F 0000 // 126 0.995 0.000 +7FD5 0000 // 127 0.999 0.000 diff --git a/nanamake_r22sdf/sim/fft_128_tc/input5.txt b/nanamake_r22sdf/sim/fft_128_tc/input5.txt new file mode 100644 index 0000000000000000000000000000000000000000..ddc1b3a7f378a426066e82b5a30da8a16c2b8ffa --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/input5.txt @@ -0,0 +1,128 @@ +7FFD 0000 // 0 1.000 0.000 +5ED5 55F3 // 1 0.741 0.671 +0C8C 7F5F // 2 0.098 0.995 +B3C2 66CD // 3 -0.596 0.803 +8279 18F8 // 4 -0.981 0.195 +9239 BE34 // 5 -0.858 -0.514 +DAD9 8586 // 6 -0.290 -0.957 +36B9 8C4D // 7 0.428 -0.904 +763F CF05 // 8 0.924 -0.383 +7881 2B1E // 9 0.941 0.337 +3C55 70E0 // 10 0.471 0.882 +E0E7 7C27 // 11 -0.243 0.970 +9595 471B // 12 -0.831 0.556 +8166 ED38 // 13 -0.989 -0.147 +AECE 9D11 // 14 -0.634 -0.773 +0648 802B // 15 0.049 -0.999 +5A80 A580 // 16 0.707 -0.707 +7FD5 F9B8 // 17 0.999 -0.049 +62EF 5132 // 18 0.773 0.634 +12C8 7E9A // 19 0.147 0.989 +B8E5 6A6B // 20 -0.556 0.831 +83D9 1F19 // 21 -0.970 0.243 +8F20 C3AB // 22 -0.882 -0.471 +D4E2 877F // 23 -0.337 -0.941 +30FB 89C1 // 24 0.383 -0.924 +73B3 C947 // 25 0.904 -0.428 +7A7A 2527 // 26 0.957 0.290 +41CC 6DC7 // 27 0.514 0.858 +E708 7D87 // 28 -0.195 0.981 +9933 4C3E // 29 -0.803 0.596 +80A1 F374 // 30 -0.995 -0.098 +AA0D A12B // 31 -0.671 -0.741 +0000 8003 // 32 -0.000 -1.000 +55F3 A12B // 33 0.671 -0.741 +7F5F F374 // 34 0.995 -0.098 +66CD 4C3E // 35 0.803 0.596 +18F8 7D87 // 36 0.195 0.981 +BE34 6DC7 // 37 -0.514 0.858 +8586 2527 // 38 -0.957 0.290 +8C4D C947 // 39 -0.904 -0.428 +CF05 89C1 // 40 -0.383 -0.924 +2B1E 877F // 41 0.337 -0.941 +70E0 C3AB // 42 0.882 -0.471 +7C27 1F19 // 43 0.970 0.243 +471B 6A6B // 44 0.556 0.831 +ED38 7E9A // 45 -0.147 0.989 +9D11 5132 // 46 -0.773 0.634 +802B F9B8 // 47 -0.999 -0.049 +A580 A580 // 48 -0.707 -0.707 +F9B8 802B // 49 -0.049 -0.999 +5132 9D11 // 50 0.634 -0.773 +7E9A ED38 // 51 0.989 -0.147 +6A6B 471B // 52 0.831 0.556 +1F19 7C27 // 53 0.243 0.970 +C3AB 70E0 // 54 -0.471 0.882 +877F 2B1E // 55 -0.941 0.337 +89C1 CF05 // 56 -0.924 -0.383 +C947 8C4D // 57 -0.428 -0.904 +2527 8586 // 58 0.290 -0.957 +6DC7 BE34 // 59 0.858 -0.514 +7D87 18F8 // 60 0.981 0.195 +4C3E 66CD // 61 0.596 0.803 +F374 7F5F // 62 -0.098 0.995 +A12B 55F3 // 63 -0.741 0.671 +8003 0000 // 64 -1.000 0.000 +A12B AA0D // 65 -0.741 -0.671 +F374 80A1 // 66 -0.098 -0.995 +4C3E 9933 // 67 0.596 -0.803 +7D87 E708 // 68 0.981 -0.195 +6DC7 41CC // 69 0.858 0.514 +2527 7A7A // 70 0.290 0.957 +C947 73B3 // 71 -0.428 0.904 +89C1 30FB // 72 -0.924 0.383 +877F D4E2 // 73 -0.941 -0.337 +C3AB 8F20 // 74 -0.471 -0.882 +1F19 83D9 // 75 0.243 -0.970 +6A6B B8E5 // 76 0.831 -0.556 +7E9A 12C8 // 77 0.989 0.147 +5132 62EF // 78 0.634 0.773 +F9B8 7FD5 // 79 -0.049 0.999 +A580 5A80 // 80 -0.707 0.707 +802B 0648 // 81 -0.999 0.049 +9D11 AECE // 82 -0.773 -0.634 +ED38 8166 // 83 -0.147 -0.989 +471B 9595 // 84 0.556 -0.831 +7C27 E0E7 // 85 0.970 -0.243 +70E0 3C55 // 86 0.882 0.471 +2B1E 7881 // 87 0.337 0.941 +CF05 763F // 88 -0.383 0.924 +8C4D 36B9 // 89 -0.904 0.428 +8586 DAD9 // 90 -0.957 -0.290 +BE34 9239 // 91 -0.514 -0.858 +18F8 8279 // 92 0.195 -0.981 +66CD B3C2 // 93 0.803 -0.596 +7F5F 0C8C // 94 0.995 0.098 +55F3 5ED5 // 95 0.671 0.741 +0000 7FFD // 96 0.000 1.000 +AA0D 5ED5 // 97 -0.671 0.741 +80A1 0C8C // 98 -0.995 0.098 +9933 B3C2 // 99 -0.803 -0.596 +E708 8279 // 100 -0.195 -0.981 +41CC 9239 // 101 0.514 -0.858 +7A7A DAD9 // 102 0.957 -0.290 +73B3 36B9 // 103 0.904 0.428 +30FB 763F // 104 0.383 0.924 +D4E2 7881 // 105 -0.337 0.941 +8F20 3C55 // 106 -0.882 0.471 +83D9 E0E7 // 107 -0.970 -0.243 +B8E5 9595 // 108 -0.556 -0.831 +12C8 8166 // 109 0.147 -0.989 +62EF AECE // 110 0.773 -0.634 +7FD5 0648 // 111 0.999 0.049 +5A80 5A80 // 112 0.707 0.707 +0648 7FD5 // 113 0.049 0.999 +AECE 62EF // 114 -0.634 0.773 +8166 12C8 // 115 -0.989 0.147 +9595 B8E5 // 116 -0.831 -0.556 +E0E7 83D9 // 117 -0.243 -0.970 +3C55 8F20 // 118 0.471 -0.882 +7881 D4E2 // 119 0.941 -0.337 +763F 30FB // 120 0.924 0.383 +36B9 73B3 // 121 0.428 0.904 +DAD9 7A7A // 122 -0.290 0.957 +9239 41CC // 123 -0.858 0.514 +8279 E708 // 124 -0.981 -0.195 +B3C2 9933 // 125 -0.596 -0.803 +0C8C 80A1 // 126 0.098 -0.995 +5ED5 AA0D // 127 0.741 -0.671 diff --git a/nanamake_r22sdf/sim/fft_128_tc/output4.txt b/nanamake_r22sdf/sim/fft_128_tc/output4.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d29be8072f40df8c6a49e76dcba19224b7bd6aa --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/output4.txt @@ -0,0 +1,128 @@ +0000 0000 // 0 +3ffe ffff // 1 +0000 0000 // 2 +0000 ffff // 3 +0000 0000 // 4 +0000 0000 // 5 +0000 0000 // 6 +0000 0000 // 7 +0000 0000 // 8 +0000 0000 // 9 +0000 0000 // 10 +0000 0000 // 11 +0000 0000 // 12 +0000 0000 // 13 +0000 0000 // 14 +0000 ffff // 15 +0000 0000 // 16 +0000 0000 // 17 +0000 0000 // 18 +0000 0000 // 19 +0000 0000 // 20 +0000 0000 // 21 +0000 0000 // 22 +0000 0000 // 23 +0000 0000 // 24 +0000 0000 // 25 +0000 0000 // 26 +0000 0000 // 27 +0000 0000 // 28 +0000 0000 // 29 +0000 0000 // 30 +0000 0000 // 31 +0000 0000 // 32 +0000 0000 // 33 +0000 0000 // 34 +0000 ffff // 35 +0000 0000 // 36 +0000 0000 // 37 +0000 0000 // 38 +0000 0000 // 39 +0000 0000 // 40 +0000 0000 // 41 +0000 0000 // 42 +0001 0000 // 43 +0000 0000 // 44 +0000 0000 // 45 +0000 0000 // 46 +0000 0000 // 47 +0000 0000 // 48 +0000 0000 // 49 +0000 0000 // 50 +0000 0000 // 51 +0000 0000 // 52 +0000 0000 // 53 +0000 0000 // 54 +0000 0000 // 55 +0000 0000 // 56 +0000 0000 // 57 +0000 0000 // 58 +0000 0000 // 59 +0000 0000 // 60 +0000 0000 // 61 +0000 0000 // 62 +0000 ffff // 63 +0000 0000 // 64 +0000 0000 // 65 +0000 0000 // 66 +0000 0000 // 67 +0000 0000 // 68 +0000 0000 // 69 +0000 0000 // 70 +0000 0000 // 71 +0000 0000 // 72 +ffff 0000 // 73 +0000 0000 // 74 +ffff 0000 // 75 +0000 0000 // 76 +0000 0000 // 77 +0000 0000 // 78 +0000 0000 // 79 +0000 0000 // 80 +ffff 0000 // 81 +0000 0000 // 82 +0000 0000 // 83 +0000 0000 // 84 +0000 0000 // 85 +0000 0000 // 86 +0000 0000 // 87 +0000 0000 // 88 +0000 0000 // 89 +0000 0000 // 90 +0000 0000 // 91 +0000 0000 // 92 +0000 0000 // 93 +0000 0000 // 94 +0000 0000 // 95 +0000 0000 // 96 +0000 0000 // 97 +0000 0000 // 98 +0000 0000 // 99 +0000 0000 // 100 +0000 0000 // 101 +0000 0000 // 102 +0000 0000 // 103 +0000 0000 // 104 +ffff 0000 // 105 +0000 0000 // 106 +0000 0000 // 107 +0000 0000 // 108 +0000 0000 // 109 +0000 0000 // 110 +0000 0000 // 111 +0000 0000 // 112 +0000 0000 // 113 +0000 0000 // 114 +0000 0000 // 115 +0000 0000 // 116 +0000 0000 // 117 +0000 0000 // 118 +0000 0000 // 119 +0000 0000 // 120 +0000 0000 // 121 +0000 0000 // 122 +0000 0000 // 123 +0000 0000 // 124 +0000 0000 // 125 +0000 0000 // 126 +3ffe 0001 // 127 diff --git a/nanamake_r22sdf/sim/fft_128_tc/output5.txt b/nanamake_r22sdf/sim/fft_128_tc/output5.txt new file mode 100644 index 0000000000000000000000000000000000000000..a72a02b34d01af5c3ade8d4dc8a9397340b79f76 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/output5.txt @@ -0,0 +1,128 @@ +0000 0000 // 0 +0000 0000 // 1 +0000 0000 // 2 +0000 ffff // 3 +0000 0000 // 4 +0000 0000 // 5 +0000 0000 // 6 +0000 0000 // 7 +0000 0000 // 8 +0000 0000 // 9 +0000 0000 // 10 +ffff ffff // 11 +0000 0000 // 12 +0000 0000 // 13 +0000 0000 // 14 +7ffd ffff // 15 +0000 0000 // 16 +0000 0000 // 17 +0000 0000 // 18 +0000 0000 // 19 +0000 0000 // 20 +0000 0000 // 21 +0000 0000 // 22 +0000 0000 // 23 +0000 0000 // 24 +0000 0000 // 25 +0000 0000 // 26 +0000 0000 // 27 +0000 0000 // 28 +0000 0000 // 29 +0000 0000 // 30 +0000 0000 // 31 +0000 0000 // 32 +0000 0000 // 33 +0000 0000 // 34 +0000 0000 // 35 +0000 0000 // 36 +0000 0000 // 37 +0000 0000 // 38 +0000 0000 // 39 +0000 0000 // 40 +0000 0000 // 41 +0000 0000 // 42 +0000 0000 // 43 +0000 0000 // 44 +0000 0000 // 45 +0000 0000 // 46 +0000 0000 // 47 +0000 0000 // 48 +0000 0000 // 49 +0000 0000 // 50 +0000 0000 // 51 +0000 0000 // 52 +0000 0000 // 53 +0000 0000 // 54 +0000 0000 // 55 +0000 0000 // 56 +0000 0000 // 57 +0000 0000 // 58 +0000 0000 // 59 +0000 0000 // 60 +0000 0000 // 61 +0000 0000 // 62 +ffff ffff // 63 +0000 0000 // 64 +0000 0000 // 65 +0000 0000 // 66 +0000 0000 // 67 +0000 0000 // 68 +0000 0000 // 69 +0000 0000 // 70 +0000 0000 // 71 +0000 0000 // 72 +0000 0000 // 73 +0000 0000 // 74 +0000 0000 // 75 +0000 0000 // 76 +0000 0000 // 77 +0000 0000 // 78 +0000 0000 // 79 +0000 0000 // 80 +0000 0000 // 81 +0000 0000 // 82 +0000 0000 // 83 +0000 0000 // 84 +0000 0000 // 85 +0000 0000 // 86 +0000 0000 // 87 +0000 0000 // 88 +0000 0000 // 89 +0000 0000 // 90 +0000 0000 // 91 +0000 0000 // 92 +0000 0000 // 93 +0000 0000 // 94 +0000 0000 // 95 +0000 0000 // 96 +0000 0000 // 97 +0000 0000 // 98 +0000 0000 // 99 +0000 0000 // 100 +0000 0000 // 101 +0000 0000 // 102 +0000 0000 // 103 +0000 0000 // 104 +0000 0000 // 105 +0000 0000 // 106 +0000 0000 // 107 +0000 0000 // 108 +0000 0000 // 109 +0000 0000 // 110 +0000 0000 // 111 +0000 0000 // 112 +0000 0000 // 113 +0000 0000 // 114 +0000 0000 // 115 +0000 0000 // 116 +0000 0000 // 117 +0000 0000 // 118 +0000 0000 // 119 +0000 0000 // 120 +0000 0000 // 121 +0000 0000 // 122 +0000 0000 // 123 +0000 0000 // 124 +0000 0000 // 125 +0000 0000 // 126 +0000 0000 // 127 diff --git a/nanamake_r22sdf/sim/fft_128_tc/stim.v b/nanamake_r22sdf/sim/fft_128_tc/stim.v new file mode 100644 index 0000000000000000000000000000000000000000..25a3b02c27a929caca4b72a1ea648602b636cf74 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/stim.v @@ -0,0 +1,35 @@ +//---------------------------------------------------------------------- +// Test Stimuli +//---------------------------------------------------------------------- +initial begin : STIM + wait (reset == 1); + wait (reset == 0); + repeat(10) @(posedge clock); + + fork + begin + LoadInputData("input4.txt"); + GenerateInputWave; + // @(posedge clock); + LoadInputData("input5.txt"); + GenerateInputWave; + end + begin + wait (do_en == 1); + repeat(N) @(posedge clock); + SaveOutputData("output4.txt"); + @(negedge clock); + wait (do_en == 1); + repeat(N) @(posedge clock); + SaveOutputData("output5.txt"); + end + join + + repeat(10) @(posedge clock); + $finish; +end +initial begin : TIMEOUT + repeat(1000) #20; // 1000 Clock Cycle Time + $display("[FAILED] Simulation timed out."); + $finish; +end diff --git a/nanamake_r22sdf/sim/fft_128_tc/stim1.v b/nanamake_r22sdf/sim/fft_128_tc/stim1.v new file mode 100644 index 0000000000000000000000000000000000000000..8f81268b8da0d225ec1150aa98aee56f2d438a65 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_128_tc/stim1.v @@ -0,0 +1,35 @@ +//---------------------------------------------------------------------- +// Test Stimuli +//---------------------------------------------------------------------- +initial begin : STIM + wait (reset == 1); + wait (reset == 0); + repeat(10) @(posedge clock); + + fork + begin + LoadInputData("input4.txt"); + GenerateInputWave; + @(posedge clock); + LoadInputData("input5.txt"); + GenerateInputWave; + end + begin + wait (do_en == 1); + repeat(N) @(posedge clock); + SaveOutputData("output4.txt"); + @(negedge clock); + wait (do_en == 1); + repeat(N) @(posedge clock); + SaveOutputData("output5.txt"); + end + join + + repeat(10) @(posedge clock); + $finish; +end +initial begin : TIMEOUT + repeat(1000) #20; // 1000 Clock Cycle Time + $display("[FAILED] Simulation timed out."); + $finish; +end diff --git a/nanamake_r22sdf/sim/fft_64/TB64.v b/nanamake_r22sdf/sim/fft_64/TB64.v new file mode 100644 index 0000000000000000000000000000000000000000..c653863f359811d930a882ffd6e298fdfa7c5917 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/TB64.v @@ -0,0 +1,121 @@ +//---------------------------------------------------------------------- +// TB: FftTop Testbench +//---------------------------------------------------------------------- +`timescale 1ns/1ns +module TB; + +reg clock; +reg reset; +reg di_en; +reg [15:0] di_re; +reg [15:0] di_im; +wire do_en; +wire[15:0] do_re; +wire[15:0] do_im; + +reg [15:0] imem[0:127]; +reg [15:0] omem[0:127]; + +//---------------------------------------------------------------------- +// Clock and Reset +//---------------------------------------------------------------------- +always begin + clock = 0; #10; + clock = 1; #10; +end + +initial begin + reset = 0; #20; + reset = 1; #100; + reset = 0; +end + +//---------------------------------------------------------------------- +// Functional Blocks +//---------------------------------------------------------------------- + +// Input Control Initialize +initial begin + wait (reset == 1); + di_en = 0; +end + +// Output Data Capture +initial begin : OCAP + integer n; + forever begin + n = 0; + while (do_en !== 1) @(negedge clock); + while ((do_en == 1) && (n < 64)) begin + omem[2*n ] = do_re; + omem[2*n+1] = do_im; + n = n + 1; + @(negedge clock); + end + end +end + +//---------------------------------------------------------------------- +// Tasks +//---------------------------------------------------------------------- +task LoadInputData; + input[80*8:1] filename; +begin + $readmemh(filename, imem); +end +endtask + +task GenerateInputWave; + integer n; +begin + di_en <= 1; + for (n = 0; n < 64; n = n + 1) begin + di_re <= imem[2*n]; + di_im <= imem[2*n+1]; + @(posedge clock); + end + di_en <= 0; + di_re <= 'bx; + di_im <= 'bx; +end +endtask + +task SaveOutputData; + input[80*8:1] filename; + integer fp, n, m; +begin + fp = $fopen(filename); + m = 0; + for (n = 0; n < 64; n = n + 1) begin + m[5] = n[0]; + m[4] = n[1]; + m[3] = n[2]; + m[2] = n[3]; + m[1] = n[4]; + m[0] = n[5]; + $fdisplay(fp, "%h %h // %d", omem[2*m], omem[2*m+1], n[5:0]); + end + $fclose(fp); +end +endtask + +//---------------------------------------------------------------------- +// Module Instances +//---------------------------------------------------------------------- +FFT FFT ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (di_en ), // i + .di_re (di_re ), // i + .di_im (di_im ), // i + .do_en (do_en ), // o + .do_re (do_re ), // o + .do_im (do_im ) // o +); + +//---------------------------------------------------------------------- +// Include Stimuli +//---------------------------------------------------------------------- +`include "stim.v" + +endmodule diff --git a/nanamake_r22sdf/sim/fft_64/input4.txt b/nanamake_r22sdf/sim/fft_64/input4.txt new file mode 100644 index 0000000000000000000000000000000000000000..d7124737194c49b0e9ae2c080c760aaa78ec5e9c --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/input4.txt @@ -0,0 +1,64 @@ +7FFD 0000 // 0 1.000 0.000 +7F5F 0000 // 1 0.995 0.000 +7D87 0000 // 2 0.981 0.000 +7A7A 0000 // 3 0.957 0.000 +763F 0000 // 4 0.924 0.000 +70E0 0000 // 5 0.882 0.000 +6A6B 0000 // 6 0.831 0.000 +62EF 0000 // 7 0.773 0.000 +5A80 0000 // 8 0.707 0.000 +5132 0000 // 9 0.634 0.000 +471B 0000 // 10 0.556 0.000 +3C55 0000 // 11 0.471 0.000 +30FB 0000 // 12 0.383 0.000 +2527 0000 // 13 0.290 0.000 +18F8 0000 // 14 0.195 0.000 +0C8C 0000 // 15 0.098 0.000 +0000 0000 // 16 0.000 0.000 +F374 0000 // 17 -0.098 0.000 +E708 0000 // 18 -0.195 0.000 +DAD9 0000 // 19 -0.290 0.000 +CF05 0000 // 20 -0.383 0.000 +C3AB 0000 // 21 -0.471 0.000 +B8E5 0000 // 22 -0.556 0.000 +AECE 0000 // 23 -0.634 0.000 +A580 0000 // 24 -0.707 0.000 +9D11 0000 // 25 -0.773 0.000 +9595 0000 // 26 -0.831 0.000 +8F20 0000 // 27 -0.882 0.000 +89C1 0000 // 28 -0.924 0.000 +8586 0000 // 29 -0.957 0.000 +8279 0000 // 30 -0.981 0.000 +80A1 0000 // 31 -0.995 0.000 +8003 0000 // 32 -1.000 0.000 +80A1 0000 // 33 -0.995 0.000 +8279 0000 // 34 -0.981 0.000 +8586 0000 // 35 -0.957 0.000 +89C1 0000 // 36 -0.924 0.000 +8F20 0000 // 37 -0.882 0.000 +9595 0000 // 38 -0.831 0.000 +9D11 0000 // 39 -0.773 0.000 +A580 0000 // 40 -0.707 0.000 +AECE 0000 // 41 -0.634 0.000 +B8E5 0000 // 42 -0.556 0.000 +C3AB 0000 // 43 -0.471 0.000 +CF05 0000 // 44 -0.383 0.000 +DAD9 0000 // 45 -0.290 0.000 +E708 0000 // 46 -0.195 0.000 +F374 0000 // 47 -0.098 0.000 +0000 0000 // 48 -0.000 0.000 +0C8C 0000 // 49 0.098 0.000 +18F8 0000 // 50 0.195 0.000 +2527 0000 // 51 0.290 0.000 +30FB 0000 // 52 0.383 0.000 +3C55 0000 // 53 0.471 0.000 +471B 0000 // 54 0.556 0.000 +5132 0000 // 55 0.634 0.000 +5A80 0000 // 56 0.707 0.000 +62EF 0000 // 57 0.773 0.000 +6A6B 0000 // 58 0.831 0.000 +70E0 0000 // 59 0.882 0.000 +763F 0000 // 60 0.924 0.000 +7A7A 0000 // 61 0.957 0.000 +7D87 0000 // 62 0.981 0.000 +7F5F 0000 // 63 0.995 0.000 diff --git a/nanamake_r22sdf/sim/fft_64/input5.txt b/nanamake_r22sdf/sim/fft_64/input5.txt new file mode 100644 index 0000000000000000000000000000000000000000..68af1a9a783332b0a18414ea017e277d94d34e42 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/input5.txt @@ -0,0 +1,64 @@ +7FFD 0000 // 0 1.000 0.000 +0C8C 7F5F // 1 0.098 0.995 +8279 18F8 // 2 -0.981 0.195 +DAD9 8586 // 3 -0.290 -0.957 +763F CF05 // 4 0.924 -0.383 +3C55 70E0 // 5 0.471 0.882 +9595 471B // 6 -0.831 0.556 +AECE 9D11 // 7 -0.634 -0.773 +5A80 A580 // 8 0.707 -0.707 +62EF 5132 // 9 0.773 0.634 +B8E5 6A6B // 10 -0.556 0.831 +8F20 C3AB // 11 -0.882 -0.471 +30FB 89C1 // 12 0.383 -0.924 +7A7A 2527 // 13 0.957 0.290 +E708 7D87 // 14 -0.195 0.981 +80A1 F374 // 15 -0.995 -0.098 +0000 8003 // 16 -0.000 -1.000 +7F5F F374 // 17 0.995 -0.098 +18F8 7D87 // 18 0.195 0.981 +8586 2527 // 19 -0.957 0.290 +CF05 89C1 // 20 -0.383 -0.924 +70E0 C3AB // 21 0.882 -0.471 +471B 6A6B // 22 0.556 0.831 +9D11 5132 // 23 -0.773 0.634 +A580 A580 // 24 -0.707 -0.707 +5132 9D11 // 25 0.634 -0.773 +6A6B 471B // 26 0.831 0.556 +C3AB 70E0 // 27 -0.471 0.882 +89C1 CF05 // 28 -0.924 -0.383 +2527 8586 // 29 0.290 -0.957 +7D87 18F8 // 30 0.981 0.195 +F374 7F5F // 31 -0.098 0.995 +8003 0000 // 32 -1.000 0.000 +F374 80A1 // 33 -0.098 -0.995 +7D87 E708 // 34 0.981 -0.195 +2527 7A7A // 35 0.290 0.957 +89C1 30FB // 36 -0.924 0.383 +C3AB 8F20 // 37 -0.471 -0.882 +6A6B B8E5 // 38 0.831 -0.556 +5132 62EF // 39 0.634 0.773 +A580 5A80 // 40 -0.707 0.707 +9D11 AECE // 41 -0.773 -0.634 +471B 9595 // 42 0.556 -0.831 +70E0 3C55 // 43 0.882 0.471 +CF05 763F // 44 -0.383 0.924 +8586 DAD9 // 45 -0.957 -0.290 +18F8 8279 // 46 0.195 -0.981 +7F5F 0C8C // 47 0.995 0.098 +0000 7FFD // 48 0.000 1.000 +80A1 0C8C // 49 -0.995 0.098 +E708 8279 // 50 -0.195 -0.981 +7A7A DAD9 // 51 0.957 -0.290 +30FB 763F // 52 0.383 0.924 +8F20 3C55 // 53 -0.882 0.471 +B8E5 9595 // 54 -0.556 -0.831 +62EF AECE // 55 0.773 -0.634 +5A80 5A80 // 56 0.707 0.707 +AECE 62EF // 57 -0.634 0.773 +9595 B8E5 // 58 -0.831 -0.556 +3C55 8F20 // 59 0.471 -0.882 +763F 30FB // 60 0.924 0.383 +DAD9 7A7A // 61 -0.290 0.957 +8279 E708 // 62 -0.981 -0.195 +0C8C 80A1 // 63 0.098 -0.995 diff --git a/nanamake_r22sdf/sim/fft_64/output4.txt b/nanamake_r22sdf/sim/fft_64/output4.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3805d0ea2d9104cb7b9d8e5fd738e6435bd5bbc --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/output4.txt @@ -0,0 +1,64 @@ +0000 0000 // 0 +3fff ffff // 1 +0000 0000 // 2 +0000 ffff // 3 +0000 0000 // 4 +0000 0000 // 5 +0000 0000 // 6 +0000 0000 // 7 +0000 0000 // 8 +0000 0000 // 9 +0000 0000 // 10 +0000 0000 // 11 +0000 0000 // 12 +0000 0000 // 13 +0000 0000 // 14 +0001 ffff // 15 +0000 0000 // 16 +0000 0000 // 17 +0000 0000 // 18 +0000 0000 // 19 +0000 0000 // 20 +0000 0000 // 21 +0000 0000 // 22 +0000 0000 // 23 +0000 0000 // 24 +0000 0001 // 25 +0000 0000 // 26 +0000 0000 // 27 +0000 0000 // 28 +0000 0000 // 29 +0000 0000 // 30 +0000 0001 // 31 +0000 0000 // 32 +0000 0000 // 33 +0000 0000 // 34 +0000 0000 // 35 +0000 0000 // 36 +0000 0001 // 37 +0000 0000 // 38 +0000 0000 // 39 +0000 0000 // 40 +0000 0001 // 41 +0000 0000 // 42 +0001 0001 // 43 +0000 0000 // 44 +0000 0001 // 45 +0000 0000 // 46 +0000 0000 // 47 +0000 0000 // 48 +0000 0000 // 49 +0000 0000 // 50 +0000 0000 // 51 +0000 0000 // 52 +0001 0000 // 53 +0000 0000 // 54 +0000 0000 // 55 +0000 0000 // 56 +0000 0000 // 57 +0000 0000 // 58 +0000 0000 // 59 +0000 0000 // 60 +0000 0000 // 61 +0000 0000 // 62 +3fff 0001 // 63 diff --git a/nanamake_r22sdf/sim/fft_64/output5.txt b/nanamake_r22sdf/sim/fft_64/output5.txt new file mode 100644 index 0000000000000000000000000000000000000000..9006920aa33259863555dc0cd0e32f5c9cbe392e --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/output5.txt @@ -0,0 +1,64 @@ +0000 0000 // 0 +0000 0000 // 1 +0000 0000 // 2 +0000 ffff // 3 +0000 0000 // 4 +0000 0000 // 5 +0000 0000 // 6 +0000 0000 // 7 +0000 0000 // 8 +0000 0000 // 9 +0000 0000 // 10 +0000 0000 // 11 +0000 0000 // 12 +0000 0000 // 13 +0000 0000 // 14 +7ffd ffff // 15 +0000 0000 // 16 +0000 0000 // 17 +0000 0000 // 18 +0000 0000 // 19 +0000 0000 // 20 +0000 0000 // 21 +0000 0000 // 22 +0000 0001 // 23 +0000 0000 // 24 +0000 0000 // 25 +0000 0000 // 26 +0000 0000 // 27 +0000 0000 // 28 +0000 0000 // 29 +0000 0000 // 30 +0001 0000 // 31 +0000 0000 // 32 +0000 0000 // 33 +0000 0000 // 34 +0000 0000 // 35 +0000 0000 // 36 +0000 0000 // 37 +0000 0000 // 38 +0000 0000 // 39 +0000 0000 // 40 +0000 0000 // 41 +0000 0000 // 42 +0000 0000 // 43 +0000 0000 // 44 +0000 0000 // 45 +0000 0000 // 46 +0000 0000 // 47 +0000 0000 // 48 +0000 0000 // 49 +0000 0000 // 50 +0000 0000 // 51 +0000 0000 // 52 +0000 0000 // 53 +0000 0000 // 54 +0000 0000 // 55 +0000 0000 // 56 +0000 0000 // 57 +0000 0000 // 58 +0000 0000 // 59 +0000 0000 // 60 +0000 0000 // 61 +0000 0000 // 62 +0000 0000 // 63 diff --git a/nanamake_r22sdf/sim/fft_64/stim.v b/nanamake_r22sdf/sim/fft_64/stim.v new file mode 100644 index 0000000000000000000000000000000000000000..2bd70fcf84e50c6b5aba297bb02747b9f2fb29b1 --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/stim.v @@ -0,0 +1,35 @@ +//---------------------------------------------------------------------- +// Test Stimuli +//---------------------------------------------------------------------- +initial begin : STIM + wait (reset == 1); + wait (reset == 0); + repeat(10) @(posedge clock); + + fork + begin + LoadInputData("input4.txt"); + GenerateInputWave; + // @(posedge clock); + LoadInputData("input5.txt"); + GenerateInputWave; + end + begin + wait (do_en == 1); + repeat(64) @(posedge clock); + SaveOutputData("output4.txt"); + @(negedge clock); + wait (do_en == 1); + repeat(64) @(posedge clock); + SaveOutputData("output5.txt"); + end + join + + repeat(10) @(posedge clock); + $finish; +end +initial begin : TIMEOUT + repeat(1000) #20; // 1000 Clock Cycle Time + $display("[FAILED] Simulation timed out."); + $finish; +end diff --git a/nanamake_r22sdf/sim/fft_64/stim1.v b/nanamake_r22sdf/sim/fft_64/stim1.v new file mode 100644 index 0000000000000000000000000000000000000000..7e0aa7dd9218ca860a8bc2e018e3d2b98a155fcb --- /dev/null +++ b/nanamake_r22sdf/sim/fft_64/stim1.v @@ -0,0 +1,35 @@ +//---------------------------------------------------------------------- +// Test Stimuli +//---------------------------------------------------------------------- +initial begin : STIM + wait (reset == 1); + wait (reset == 0); + repeat(10) @(posedge clock); + + fork + begin + LoadInputData("input4.txt"); + GenerateInputWave; + @(posedge clock); + LoadInputData("input5.txt"); + GenerateInputWave; + end + begin + wait (do_en == 1); + repeat(64) @(posedge clock); + SaveOutputData("output4.txt"); + @(negedge clock); + wait (do_en == 1); + repeat(64) @(posedge clock); + SaveOutputData("output5.txt"); + end + join + + repeat(10) @(posedge clock); + $finish; +end +initial begin : TIMEOUT + repeat(1000) #20; // 1000 Clock Cycle Time + $display("[FAILED] Simulation timed out."); + $finish; +end diff --git a/nanamake_r22sdf/tool/twiddle.txt b/nanamake_r22sdf/tool/twiddle.txt new file mode 100644 index 0000000000000000000000000000000000000000..a41b848340f623aae2fedbe1f463b4cd1087d635 --- /dev/null +++ b/nanamake_r22sdf/tool/twiddle.txt @@ -0,0 +1,1025 @@ +// wn_re = cos(-2pi*n/1024) wn_im = sin(-2pi*n/1024) +assign wn_re[ 0] = 32'h00000000; assign wn_im[ 0] = 32'h00000000; // 0 1.000 -0.000 +assign wn_re[ 1] = 32'h7FFF6216; assign wn_im[ 1] = 32'hFF36F078; // 1 1.000 -0.006 +assign wn_re[ 2] = 32'h7FFD885A; assign wn_im[ 2] = 32'hFE6DE2E0; // 2 1.000 -0.012 +assign wn_re[ 3] = 32'h7FFA72D1; assign wn_im[ 3] = 32'hFDA4D929; // 3 1.000 -0.018 +assign wn_re[ 4] = 32'h7FF62182; assign wn_im[ 4] = 32'hFCDBD541; // 4 1.000 -0.025 +assign wn_re[ 5] = 32'h7FF09478; assign wn_im[ 5] = 32'hFC12D91A; // 5 1.000 -0.031 +assign wn_re[ 6] = 32'h7FE9CBC0; assign wn_im[ 6] = 32'hFB49E6A3; // 6 0.999 -0.037 +assign wn_re[ 7] = 32'h7FE1C76B; assign wn_im[ 7] = 32'hFA80FFCB; // 7 0.999 -0.043 +assign wn_re[ 8] = 32'h7FD8878E; assign wn_im[ 8] = 32'hF9B82684; // 8 0.999 -0.049 +assign wn_re[ 9] = 32'h7FCE0C3E; assign wn_im[ 9] = 32'hF8EF5CBB; // 9 0.998 -0.055 +assign wn_re[10] = 32'h7FC25596; assign wn_im[10] = 32'hF826A462; // 10 0.998 -0.061 +assign wn_re[11] = 32'h7FB563B3; assign wn_im[11] = 32'hF75DFF66; // 11 0.998 -0.067 +assign wn_re[12] = 32'h7FA736B4; assign wn_im[12] = 32'hF6956FB7; // 12 0.997 -0.074 +assign wn_re[13] = 32'h7F97CEBD; assign wn_im[13] = 32'hF5CCF743; // 13 0.997 -0.080 +assign wn_re[14] = 32'h7F872BF3; assign wn_im[14] = 32'hF50497FB; // 14 0.996 -0.086 +assign wn_re[15] = 32'h7F754E80; assign wn_im[15] = 32'hF43C53CB; // 15 0.996 -0.092 +assign wn_re[16] = 32'h7F62368F; assign wn_im[16] = 32'hF3742CA2; // 16 0.995 -0.098 +assign wn_re[17] = 32'h7F4DE451; assign wn_im[17] = 32'hF2AC246E; // 17 0.995 -0.104 +assign wn_re[18] = 32'h7F3857F6; assign wn_im[18] = 32'hF1E43D1C; // 18 0.994 -0.110 +assign wn_re[19] = 32'h7F2191B4; assign wn_im[19] = 32'hF11C789A; // 19 0.993 -0.116 +assign wn_re[20] = 32'h7F0991C4; assign wn_im[20] = 32'hF054D8D5; // 20 0.992 -0.122 +assign wn_re[21] = 32'h7EF05860; assign wn_im[21] = 32'hEF8D5FB8; // 21 0.992 -0.128 +assign wn_re[22] = 32'h7ED5E5C6; assign wn_im[22] = 32'hEEC60F31; // 22 0.991 -0.135 +assign wn_re[23] = 32'h7EBA3A39; assign wn_im[23] = 32'hEDFEE92B; // 23 0.990 -0.141 +assign wn_re[24] = 32'h7E9D55FC; assign wn_im[24] = 32'hED37EF91; // 24 0.989 -0.147 +assign wn_re[25] = 32'h7E7F3957; assign wn_im[25] = 32'hEC71244F; // 25 0.988 -0.153 +assign wn_re[26] = 32'h7E5FE493; assign wn_im[26] = 32'hEBAA894F; // 26 0.987 -0.159 +assign wn_re[27] = 32'h7E3F57FF; assign wn_im[27] = 32'hEAE4207A; // 27 0.986 -0.165 +assign wn_re[28] = 32'h7E1D93EA; assign wn_im[28] = 32'hEA1DEBBB; // 28 0.985 -0.171 +assign wn_re[29] = 32'h7DFA98A8; assign wn_im[29] = 32'hE957ECFB; // 29 0.984 -0.177 +assign wn_re[30] = 32'h7DD6668F; assign wn_im[30] = 32'hE8922622; // 30 0.983 -0.183 +assign wn_re[31] = 32'h7DB0FDF8; assign wn_im[31] = 32'hE7CC9917; // 31 0.982 -0.189 +assign wn_re[32] = 32'h7D8A5F40; assign wn_im[32] = 32'hE70747C4; // 32 0.981 -0.195 +assign wn_re[33] = 32'h7D628AC6; assign wn_im[33] = 32'hE642340D; // 33 0.980 -0.201 +assign wn_re[34] = 32'h7D3980EC; assign wn_im[34] = 32'hE57D5FDA; // 34 0.978 -0.207 +assign wn_re[35] = 32'h7D0F4218; assign wn_im[35] = 32'hE4B8CD11; // 35 0.977 -0.213 +assign wn_re[36] = 32'h7CE3CEB2; assign wn_im[36] = 32'hE3F47D96; // 36 0.976 -0.219 +assign wn_re[37] = 32'h7CB72724; assign wn_im[37] = 32'hE330734D; // 37 0.974 -0.225 +assign wn_re[38] = 32'h7C894BDE; assign wn_im[38] = 32'hE26CB01B; // 38 0.973 -0.231 +assign wn_re[39] = 32'h7C5A3D50; assign wn_im[39] = 32'hE1A935E2; // 39 0.972 -0.237 +assign wn_re[40] = 32'h7C29FBEE; assign wn_im[40] = 32'hE0E60685; // 40 0.970 -0.243 +assign wn_re[41] = 32'h7BF88830; assign wn_im[41] = 32'hE02323E5; // 41 0.969 -0.249 +assign wn_re[42] = 32'h7BC5E290; assign wn_im[42] = 32'hDF608FE4; // 42 0.967 -0.255 +assign wn_re[43] = 32'h7B920B89; assign wn_im[43] = 32'hDE9E4C60; // 43 0.965 -0.261 +assign wn_re[44] = 32'h7B5D039E; assign wn_im[44] = 32'hDDDC5B3B; // 44 0.964 -0.267 +assign wn_re[45] = 32'h7B26CB4F; assign wn_im[45] = 32'hDD1ABE51; // 45 0.962 -0.273 +assign wn_re[46] = 32'h7AEF6323; assign wn_im[46] = 32'hDC597781; // 46 0.960 -0.279 +assign wn_re[47] = 32'h7AB6CBA4; assign wn_im[47] = 32'hDB9888A8; // 47 0.959 -0.284 +assign wn_re[48] = 32'h7A7D055B; assign wn_im[48] = 32'hDAD7F3A2; // 48 0.957 -0.290 +assign wn_re[49] = 32'h7A4210D8; assign wn_im[49] = 32'hDA17BA4A; // 49 0.955 -0.296 +assign wn_re[50] = 32'h7A05EEAD; assign wn_im[50] = 32'hD957DE7A; // 50 0.953 -0.302 +assign wn_re[51] = 32'h79C89F6E; assign wn_im[51] = 32'hD898620C; // 51 0.951 -0.308 +assign wn_re[52] = 32'h798A23B1; assign wn_im[52] = 32'hD7D946D8; // 52 0.950 -0.314 +assign wn_re[53] = 32'h794A7C12; assign wn_im[53] = 32'hD71A8EB5; // 53 0.948 -0.320 +assign wn_re[54] = 32'h7909A92D; assign wn_im[54] = 32'hD65C3B7B; // 54 0.946 -0.325 +assign wn_re[55] = 32'h78C7ABA2; assign wn_im[55] = 32'hD59E4EFF; // 55 0.944 -0.331 +assign wn_re[56] = 32'h78848414; assign wn_im[56] = 32'hD4E0CB15; // 56 0.942 -0.337 +assign wn_re[57] = 32'h78403329; assign wn_im[57] = 32'hD423B191; // 57 0.939 -0.343 +assign wn_re[58] = 32'h77FAB989; assign wn_im[58] = 32'hD3670446; // 58 0.937 -0.348 +assign wn_re[59] = 32'h77B417DF; assign wn_im[59] = 32'hD2AAC504; // 59 0.935 -0.354 +assign wn_re[60] = 32'h776C4EDB; assign wn_im[60] = 32'hD1EEF59E; // 60 0.933 -0.360 +assign wn_re[61] = 32'h77235F2D; assign wn_im[61] = 32'hD13397E2; // 61 0.931 -0.366 +assign wn_re[62] = 32'h76D94989; assign wn_im[62] = 32'hD078AD9E; // 62 0.929 -0.371 +assign wn_re[63] = 32'h768E0EA6; assign wn_im[63] = 32'hCFBE389F; // 63 0.926 -0.377 +assign wn_re[64] = 32'h7641AF3D; assign wn_im[64] = 32'hCF043AB3; // 64 0.924 -0.383 +assign wn_re[65] = 32'h75F42C0B; assign wn_im[65] = 32'hCE4AB5A2; // 65 0.922 -0.388 +assign wn_re[66] = 32'h75A585CF; assign wn_im[66] = 32'hCD91AB39; // 66 0.919 -0.394 +assign wn_re[67] = 32'h7555BD4C; assign wn_im[67] = 32'hCCD91D3D; // 67 0.917 -0.400 +assign wn_re[68] = 32'h7504D345; assign wn_im[68] = 32'hCC210D79; // 68 0.914 -0.405 +assign wn_re[69] = 32'h74B2C884; assign wn_im[69] = 32'hCB697DB0; // 69 0.912 -0.411 +assign wn_re[70] = 32'h745F9DD1; assign wn_im[70] = 32'hCAB26FA9; // 70 0.909 -0.416 +assign wn_re[71] = 32'h740B53FB; assign wn_im[71] = 32'hC9FBE527; // 71 0.907 -0.422 +assign wn_re[72] = 32'h73B5EBD1; assign wn_im[72] = 32'hC945DFEC; // 72 0.904 -0.428 +assign wn_re[73] = 32'h735F6626; assign wn_im[73] = 32'hC89061BA; // 73 0.901 -0.433 +assign wn_re[74] = 32'h7307C3D0; assign wn_im[74] = 32'hC7DB6C50; // 74 0.899 -0.439 +assign wn_re[75] = 32'h72AF05A7; assign wn_im[75] = 32'hC727016D; // 75 0.896 -0.444 +assign wn_re[76] = 32'h72552C85; assign wn_im[76] = 32'hC67322CE; // 76 0.893 -0.450 +assign wn_re[77] = 32'h71FA3949; assign wn_im[77] = 32'hC5BFD22E; // 77 0.890 -0.455 +assign wn_re[78] = 32'h719E2CD2; assign wn_im[78] = 32'hC50D1149; // 78 0.888 -0.461 +assign wn_re[79] = 32'h71410805; assign wn_im[79] = 32'hC45AE1D7; // 79 0.885 -0.466 +assign wn_re[80] = 32'h70E2CBC6; assign wn_im[80] = 32'hC3A94590; // 80 0.882 -0.471 +assign wn_re[81] = 32'h708378FF; assign wn_im[81] = 32'hC2F83E2A; // 81 0.879 -0.477 +assign wn_re[82] = 32'h7023109A; assign wn_im[82] = 32'hC247CD5A; // 82 0.876 -0.482 +assign wn_re[83] = 32'h6FC19385; assign wn_im[83] = 32'hC197F4D4; // 83 0.873 -0.488 +assign wn_re[84] = 32'h6F5F02B2; assign wn_im[84] = 32'hC0E8B648; // 84 0.870 -0.493 +assign wn_re[85] = 32'h6EFB5F12; assign wn_im[85] = 32'hC03A1368; // 85 0.867 -0.498 +assign wn_re[86] = 32'h6E96A99D; assign wn_im[86] = 32'hBF8C0DE3; // 86 0.864 -0.504 +assign wn_re[87] = 32'h6E30E34A; assign wn_im[87] = 32'hBEDEA765; // 87 0.861 -0.509 +assign wn_re[88] = 32'h6DCA0D14; assign wn_im[88] = 32'hBE31E19B; // 88 0.858 -0.514 +assign wn_re[89] = 32'h6D6227FA; assign wn_im[89] = 32'hBD85BE30; // 89 0.855 -0.519 +assign wn_re[90] = 32'h6CF934FC; assign wn_im[90] = 32'hBCDA3ECB; // 90 0.851 -0.525 +assign wn_re[91] = 32'h6C8F351C; assign wn_im[91] = 32'hBC2F6513; // 91 0.848 -0.530 +assign wn_re[92] = 32'h6C242960; assign wn_im[92] = 32'hBB8532B0; // 92 0.845 -0.535 +assign wn_re[93] = 32'h6BB812D1; assign wn_im[93] = 32'hBADBA943; // 93 0.842 -0.540 +assign wn_re[94] = 32'h6B4AF279; assign wn_im[94] = 32'hBA32CA71; // 94 0.838 -0.545 +assign wn_re[95] = 32'h6ADCC964; assign wn_im[95] = 32'hB98A97D8; // 95 0.835 -0.550 +assign wn_re[96] = 32'h6A6D98A4; assign wn_im[96] = 32'hB8E31319; // 96 0.831 -0.556 +assign wn_re[97] = 32'h69FD614A; assign wn_im[97] = 32'hB83C3DD1; // 97 0.828 -0.561 +assign wn_re[98] = 32'h698C246C; assign wn_im[98] = 32'hB796199B; // 98 0.825 -0.566 +assign wn_re[99] = 32'h6919E320; assign wn_im[99] = 32'hB6F0A812; // 99 0.821 -0.571 +assign wn_re[100] = 32'h68A69E81; assign wn_im[100] = 32'hB64BEACD; // 100 0.818 -0.576 +assign wn_re[101] = 32'h683257AB; assign wn_im[101] = 32'hB5A7E362; // 101 0.814 -0.581 +assign wn_re[102] = 32'h67BD0FBD; assign wn_im[102] = 32'hB5049368; // 102 0.810 -0.586 +assign wn_re[103] = 32'h6746C7D8; assign wn_im[103] = 32'hB461FC70; // 103 0.807 -0.591 +assign wn_re[104] = 32'h66CF8120; assign wn_im[104] = 32'hB3C0200C; // 104 0.803 -0.596 +assign wn_re[105] = 32'h66573CBB; assign wn_im[105] = 32'hB31EFFCC; // 105 0.800 -0.601 +assign wn_re[106] = 32'h65DDFBD3; assign wn_im[106] = 32'hB27E9D3C; // 106 0.796 -0.606 +assign wn_re[107] = 32'h6563BF92; assign wn_im[107] = 32'hB1DEF9E9; // 107 0.792 -0.610 +assign wn_re[108] = 32'h64E88926; assign wn_im[108] = 32'hB140175B; // 108 0.788 -0.615 +assign wn_re[109] = 32'h646C59BF; assign wn_im[109] = 32'hB0A1F71D; // 109 0.785 -0.620 +assign wn_re[110] = 32'h63EF3290; assign wn_im[110] = 32'hB0049AB3; // 110 0.781 -0.625 +assign wn_re[111] = 32'h637114CC; assign wn_im[111] = 32'hAF6803A2; // 111 0.777 -0.630 +assign wn_re[112] = 32'h62F201AC; assign wn_im[112] = 32'hAECC336C; // 112 0.773 -0.634 +assign wn_re[113] = 32'h6271FA69; assign wn_im[113] = 32'hAE312B92; // 113 0.769 -0.639 +assign wn_re[114] = 32'h61F1003F; assign wn_im[114] = 32'hAD96ED92; // 114 0.765 -0.644 +assign wn_re[115] = 32'h616F146C; assign wn_im[115] = 32'hACFD7AE8; // 115 0.761 -0.649 +assign wn_re[116] = 32'h60EC3830; assign wn_im[116] = 32'hAC64D510; // 116 0.757 -0.653 +assign wn_re[117] = 32'h60686CCF; assign wn_im[117] = 32'hABCCFD83; // 117 0.753 -0.658 +assign wn_re[118] = 32'h5FE3B38D; assign wn_im[118] = 32'hAB35F5B5; // 118 0.749 -0.662 +assign wn_re[119] = 32'h5F5E0DB3; assign wn_im[119] = 32'hAA9FBF1E; // 119 0.745 -0.667 +assign wn_re[120] = 32'h5ED77C8A; assign wn_im[120] = 32'hAA0A5B2E; // 120 0.741 -0.672 +assign wn_re[121] = 32'h5E50015D; assign wn_im[121] = 32'hA975CB57; // 121 0.737 -0.676 +assign wn_re[122] = 32'h5DC79D7C; assign wn_im[122] = 32'hA8E21106; // 122 0.733 -0.681 +assign wn_re[123] = 32'h5D3E5237; assign wn_im[123] = 32'hA84F2DAA; // 123 0.728 -0.685 +assign wn_re[124] = 32'h5CB420E0; assign wn_im[124] = 32'hA7BD22AC; // 124 0.724 -0.690 +assign wn_re[125] = 32'h5C290ACC; assign wn_im[125] = 32'hA72BF174; // 125 0.720 -0.694 +assign wn_re[126] = 32'h5B9D1154; assign wn_im[126] = 32'hA69B9B68; // 126 0.716 -0.698 +assign wn_re[127] = 32'h5B1035CF; assign wn_im[127] = 32'hA60C21EE; // 127 0.711 -0.703 +assign wn_re[128] = 32'h5A82799A; assign wn_im[128] = 32'hA57D8666; // 128 0.707 -0.707 +assign wn_re[129] = 32'h59F3DE12; assign wn_im[129] = 32'hA4EFCA31; // 129 0.703 -0.711 +assign wn_re[130] = 32'h59646498; assign wn_im[130] = 32'hA462EEAC; // 130 0.698 -0.716 +assign wn_re[131] = 32'h58D40E8C; assign wn_im[131] = 32'hA3D6F534; // 131 0.694 -0.720 +assign wn_re[132] = 32'h5842DD54; assign wn_im[132] = 32'hA34BDF20; // 132 0.690 -0.724 +assign wn_re[133] = 32'h57B0D256; assign wn_im[133] = 32'hA2C1ADC9; // 133 0.685 -0.728 +assign wn_re[134] = 32'h571DEEFA; assign wn_im[134] = 32'hA2386284; // 134 0.681 -0.733 +assign wn_re[135] = 32'h568A34A9; assign wn_im[135] = 32'hA1AFFEA3; // 135 0.676 -0.737 +assign wn_re[136] = 32'h55F5A4D2; assign wn_im[136] = 32'hA1288376; // 136 0.672 -0.741 +assign wn_re[137] = 32'h556040E2; assign wn_im[137] = 32'hA0A1F24D; // 137 0.667 -0.745 +assign wn_re[138] = 32'h54CA0A4B; assign wn_im[138] = 32'hA01C4C73; // 138 0.662 -0.749 +assign wn_re[139] = 32'h5433027D; assign wn_im[139] = 32'h9F979331; // 139 0.658 -0.753 +assign wn_re[140] = 32'h539B2AF0; assign wn_im[140] = 32'h9F13C7D0; // 140 0.653 -0.757 +assign wn_re[141] = 32'h53028518; assign wn_im[141] = 32'h9E90EB94; // 141 0.649 -0.761 +assign wn_re[142] = 32'h5269126E; assign wn_im[142] = 32'h9E0EFFC1; // 142 0.644 -0.765 +assign wn_re[143] = 32'h51CED46E; assign wn_im[143] = 32'h9D8E0597; // 143 0.639 -0.769 +assign wn_re[144] = 32'h5133CC94; assign wn_im[144] = 32'h9D0DFE54; // 144 0.634 -0.773 +assign wn_re[145] = 32'h5097FC5E; assign wn_im[145] = 32'h9C8EEB34; // 145 0.630 -0.777 +assign wn_re[146] = 32'h4FFB654D; assign wn_im[146] = 32'h9C10CD70; // 146 0.625 -0.781 +assign wn_re[147] = 32'h4F5E08E3; assign wn_im[147] = 32'h9B93A641; // 147 0.620 -0.785 +assign wn_re[148] = 32'h4EBFE8A5; assign wn_im[148] = 32'h9B1776DA; // 148 0.615 -0.788 +assign wn_re[149] = 32'h4E210617; assign wn_im[149] = 32'h9A9C406E; // 149 0.610 -0.792 +assign wn_re[150] = 32'h4D8162C4; assign wn_im[150] = 32'h9A22042D; // 150 0.606 -0.796 +assign wn_re[151] = 32'h4CE10034; assign wn_im[151] = 32'h99A8C345; // 151 0.601 -0.800 +assign wn_re[152] = 32'h4C3FDFF4; assign wn_im[152] = 32'h99307EE0; // 152 0.596 -0.803 +assign wn_re[153] = 32'h4B9E0390; assign wn_im[153] = 32'h98B93828; // 153 0.591 -0.807 +assign wn_re[154] = 32'h4AFB6C98; assign wn_im[154] = 32'h9842F043; // 154 0.586 -0.810 +assign wn_re[155] = 32'h4A581C9E; assign wn_im[155] = 32'h97CDA855; // 155 0.581 -0.814 +assign wn_re[156] = 32'h49B41533; assign wn_im[156] = 32'h9759617F; // 156 0.576 -0.818 +assign wn_re[157] = 32'h490F57EE; assign wn_im[157] = 32'h96E61CE0; // 157 0.571 -0.821 +assign wn_re[158] = 32'h4869E665; assign wn_im[158] = 32'h9673DB94; // 158 0.566 -0.825 +assign wn_re[159] = 32'h47C3C22F; assign wn_im[159] = 32'h96029EB6; // 159 0.561 -0.828 +assign wn_re[160] = 32'h471CECE7; assign wn_im[160] = 32'h9592675C; // 160 0.556 -0.831 +assign wn_re[161] = 32'h46756828; assign wn_im[161] = 32'h9523369C; // 161 0.550 -0.835 +assign wn_re[162] = 32'h45CD358F; assign wn_im[162] = 32'h94B50D87; // 162 0.545 -0.838 +assign wn_re[163] = 32'h452456BD; assign wn_im[163] = 32'h9447ED2F; // 163 0.540 -0.842 +assign wn_re[164] = 32'h447ACD50; assign wn_im[164] = 32'h93DBD6A0; // 164 0.535 -0.845 +assign wn_re[165] = 32'h43D09AED; assign wn_im[165] = 32'h9370CAE4; // 165 0.530 -0.848 +assign wn_re[166] = 32'h4325C135; assign wn_im[166] = 32'h9306CB04; // 166 0.525 -0.851 +assign wn_re[167] = 32'h427A41D0; assign wn_im[167] = 32'h929DD806; // 167 0.519 -0.855 +assign wn_re[168] = 32'h41CE1E65; assign wn_im[168] = 32'h9235F2EC; // 168 0.514 -0.858 +assign wn_re[169] = 32'h4121589B; assign wn_im[169] = 32'h91CF1CB6; // 169 0.509 -0.861 +assign wn_re[170] = 32'h4073F21D; assign wn_im[170] = 32'h91695663; // 170 0.504 -0.864 +assign wn_re[171] = 32'h3FC5EC98; assign wn_im[171] = 32'h9104A0EE; // 171 0.498 -0.867 +assign wn_re[172] = 32'h3F1749B8; assign wn_im[172] = 32'h90A0FD4E; // 172 0.493 -0.870 +assign wn_re[173] = 32'h3E680B2C; assign wn_im[173] = 32'h903E6C7B; // 173 0.488 -0.873 +assign wn_re[174] = 32'h3DB832A6; assign wn_im[174] = 32'h8FDCEF66; // 174 0.482 -0.876 +assign wn_re[175] = 32'h3D07C1D6; assign wn_im[175] = 32'h8F7C8701; // 175 0.477 -0.879 +assign wn_re[176] = 32'h3C56BA70; assign wn_im[176] = 32'h8F1D343A; // 176 0.471 -0.882 +assign wn_re[177] = 32'h3BA51E29; assign wn_im[177] = 32'h8EBEF7FB; // 177 0.466 -0.885 +assign wn_re[178] = 32'h3AF2EEB7; assign wn_im[178] = 32'h8E61D32E; // 178 0.461 -0.888 +assign wn_re[179] = 32'h3A402DD2; assign wn_im[179] = 32'h8E05C6B7; // 179 0.455 -0.890 +assign wn_re[180] = 32'h398CDD32; assign wn_im[180] = 32'h8DAAD37B; // 180 0.450 -0.893 +assign wn_re[181] = 32'h38D8FE93; assign wn_im[181] = 32'h8D50FA59; // 181 0.444 -0.896 +assign wn_re[182] = 32'h382493B0; assign wn_im[182] = 32'h8CF83C30; // 182 0.439 -0.899 +assign wn_re[183] = 32'h376F9E46; assign wn_im[183] = 32'h8CA099DA; // 183 0.433 -0.901 +assign wn_re[184] = 32'h36BA2014; assign wn_im[184] = 32'h8C4A142F; // 184 0.428 -0.904 +assign wn_re[185] = 32'h36041AD9; assign wn_im[185] = 32'h8BF4AC05; // 185 0.422 -0.907 +assign wn_re[186] = 32'h354D9057; assign wn_im[186] = 32'h8BA0622F; // 186 0.416 -0.909 +assign wn_re[187] = 32'h34968250; assign wn_im[187] = 32'h8B4D377C; // 187 0.411 -0.912 +assign wn_re[188] = 32'h33DEF287; assign wn_im[188] = 32'h8AFB2CBB; // 188 0.405 -0.914 +assign wn_re[189] = 32'h3326E2C3; assign wn_im[189] = 32'h8AAA42B4; // 189 0.400 -0.917 +assign wn_re[190] = 32'h326E54C7; assign wn_im[190] = 32'h8A5A7A31; // 190 0.394 -0.919 +assign wn_re[191] = 32'h31B54A5E; assign wn_im[191] = 32'h8A0BD3F5; // 191 0.388 -0.922 +assign wn_re[192] = 32'h30FBC54D; assign wn_im[192] = 32'h89BE50C3; // 192 0.383 -0.924 +assign wn_re[193] = 32'h3041C761; assign wn_im[193] = 32'h8971F15A; // 193 0.377 -0.926 +assign wn_re[194] = 32'h2F875262; assign wn_im[194] = 32'h8926B677; // 194 0.371 -0.929 +assign wn_re[195] = 32'h2ECC681E; assign wn_im[195] = 32'h88DCA0D3; // 195 0.366 -0.931 +assign wn_re[196] = 32'h2E110A62; assign wn_im[196] = 32'h8893B125; // 196 0.360 -0.933 +assign wn_re[197] = 32'h2D553AFC; assign wn_im[197] = 32'h884BE821; // 197 0.354 -0.935 +assign wn_re[198] = 32'h2C98FBBA; assign wn_im[198] = 32'h88054677; // 198 0.348 -0.937 +assign wn_re[199] = 32'h2BDC4E6F; assign wn_im[199] = 32'h87BFCCD7; // 199 0.343 -0.939 +assign wn_re[200] = 32'h2B1F34EB; assign wn_im[200] = 32'h877B7BEC; // 200 0.337 -0.942 +assign wn_re[201] = 32'h2A61B101; assign wn_im[201] = 32'h8738545E; // 201 0.331 -0.944 +assign wn_re[202] = 32'h29A3C485; assign wn_im[202] = 32'h86F656D3; // 202 0.325 -0.946 +assign wn_re[203] = 32'h28E5714B; assign wn_im[203] = 32'h86B583EE; // 203 0.320 -0.948 +assign wn_re[204] = 32'h2826B928; assign wn_im[204] = 32'h8675DC4F; // 204 0.314 -0.950 +assign wn_re[205] = 32'h27679DF4; assign wn_im[205] = 32'h86376092; // 205 0.308 -0.951 +assign wn_re[206] = 32'h26A82186; assign wn_im[206] = 32'h85FA1153; // 206 0.302 -0.953 +assign wn_re[207] = 32'h25E845B6; assign wn_im[207] = 32'h85BDEF28; // 207 0.296 -0.955 +assign wn_re[208] = 32'h25280C5E; assign wn_im[208] = 32'h8582FAA5; // 208 0.290 -0.957 +assign wn_re[209] = 32'h24677758; assign wn_im[209] = 32'h8549345C; // 209 0.284 -0.959 +assign wn_re[210] = 32'h23A6887F; assign wn_im[210] = 32'h85109CDD; // 210 0.279 -0.960 +assign wn_re[211] = 32'h22E541AF; assign wn_im[211] = 32'h84D934B1; // 211 0.273 -0.962 +assign wn_re[212] = 32'h2223A4C5; assign wn_im[212] = 32'h84A2FC62; // 212 0.267 -0.964 +assign wn_re[213] = 32'h2161B3A0; assign wn_im[213] = 32'h846DF477; // 213 0.261 -0.965 +assign wn_re[214] = 32'h209F701C; assign wn_im[214] = 32'h843A1D70; // 214 0.255 -0.967 +assign wn_re[215] = 32'h1FDCDC1B; assign wn_im[215] = 32'h840777D0; // 215 0.249 -0.969 +assign wn_re[216] = 32'h1F19F97B; assign wn_im[216] = 32'h83D60412; // 216 0.243 -0.970 +assign wn_re[217] = 32'h1E56CA1E; assign wn_im[217] = 32'h83A5C2B0; // 217 0.237 -0.972 +assign wn_re[218] = 32'h1D934FE5; assign wn_im[218] = 32'h8376B422; // 218 0.231 -0.973 +assign wn_re[219] = 32'h1CCF8CB3; assign wn_im[219] = 32'h8348D8DC; // 219 0.225 -0.974 +assign wn_re[220] = 32'h1C0B826A; assign wn_im[220] = 32'h831C314E; // 220 0.219 -0.976 +assign wn_re[221] = 32'h1B4732EF; assign wn_im[221] = 32'h82F0BDE8; // 221 0.213 -0.977 +assign wn_re[222] = 32'h1A82A026; assign wn_im[222] = 32'h82C67F14; // 222 0.207 -0.978 +assign wn_re[223] = 32'h19BDCBF3; assign wn_im[223] = 32'h829D753A; // 223 0.201 -0.980 +assign wn_re[224] = 32'h18F8B83C; assign wn_im[224] = 32'h8275A0C0; // 224 0.195 -0.981 +assign wn_re[225] = 32'h183366E9; assign wn_im[225] = 32'h824F0208; // 225 0.189 -0.982 +assign wn_re[226] = 32'h176DD9DE; assign wn_im[226] = 32'h82299971; // 226 0.183 -0.983 +assign wn_re[227] = 32'h16A81305; assign wn_im[227] = 32'h82056758; // 227 0.177 -0.984 +assign wn_re[228] = 32'h15E21445; assign wn_im[228] = 32'h81E26C16; // 228 0.171 -0.985 +assign wn_re[229] = 32'h151BDF86; assign wn_im[229] = 32'h81C0A801; // 229 0.165 -0.986 +assign wn_re[230] = 32'h145576B1; assign wn_im[230] = 32'h81A01B6D; // 230 0.159 -0.987 +assign wn_re[231] = 32'h138EDBB1; assign wn_im[231] = 32'h8180C6A9; // 231 0.153 -0.988 +assign wn_re[232] = 32'h12C8106F; assign wn_im[232] = 32'h8162AA04; // 232 0.147 -0.989 +assign wn_re[233] = 32'h120116D5; assign wn_im[233] = 32'h8145C5C7; // 233 0.141 -0.990 +assign wn_re[234] = 32'h1139F0CF; assign wn_im[234] = 32'h812A1A3A; // 234 0.135 -0.991 +assign wn_re[235] = 32'h1072A048; assign wn_im[235] = 32'h810FA7A0; // 235 0.128 -0.992 +assign wn_re[236] = 32'h0FAB272B; assign wn_im[236] = 32'h80F66E3C; // 236 0.122 -0.992 +assign wn_re[237] = 32'h0EE38766; assign wn_im[237] = 32'h80DE6E4C; // 237 0.116 -0.993 +assign wn_re[238] = 32'h0E1BC2E4; assign wn_im[238] = 32'h80C7A80A; // 238 0.110 -0.994 +assign wn_re[239] = 32'h0D53DB92; assign wn_im[239] = 32'h80B21BAF; // 239 0.104 -0.995 +assign wn_re[240] = 32'h0C8BD35E; assign wn_im[240] = 32'h809DC971; // 240 0.098 -0.995 +assign wn_re[241] = 32'h0BC3AC35; assign wn_im[241] = 32'h808AB180; // 241 0.092 -0.996 +assign wn_re[242] = 32'h0AFB6805; assign wn_im[242] = 32'h8078D40D; // 242 0.086 -0.996 +assign wn_re[243] = 32'h0A3308BD; assign wn_im[243] = 32'h80683143; // 243 0.080 -0.997 +assign wn_re[244] = 32'h096A9049; assign wn_im[244] = 32'h8058C94C; // 244 0.074 -0.997 +assign wn_re[245] = 32'h08A2009A; assign wn_im[245] = 32'h804A9C4D; // 245 0.067 -0.998 +assign wn_re[246] = 32'h07D95B9E; assign wn_im[246] = 32'h803DAA6A; // 246 0.061 -0.998 +assign wn_re[247] = 32'h0710A345; assign wn_im[247] = 32'h8031F3C2; // 247 0.055 -0.998 +assign wn_re[248] = 32'h0647D97C; assign wn_im[248] = 32'h80277872; // 248 0.049 -0.999 +assign wn_re[249] = 32'h057F0035; assign wn_im[249] = 32'h801E3895; // 249 0.043 -0.999 +assign wn_re[250] = 32'h04B6195D; assign wn_im[250] = 32'h80163440; // 250 0.037 -0.999 +assign wn_re[251] = 32'h03ED26E6; assign wn_im[251] = 32'h800F6B88; // 251 0.031 -1.000 +assign wn_re[252] = 32'h03242ABF; assign wn_im[252] = 32'h8009DE7E; // 252 0.025 -1.000 +assign wn_re[253] = 32'h025B26D7; assign wn_im[253] = 32'h80058D2F; // 253 0.018 -1.000 +assign wn_re[254] = 32'h01921D20; assign wn_im[254] = 32'h800277A6; // 254 0.012 -1.000 +assign wn_re[255] = 32'h00C90F88; assign wn_im[255] = 32'h80009DEA; // 255 0.006 -1.000 +assign wn_re[256] = 32'h00000000; assign wn_im[256] = 32'h80000000; // 256 0.000 -1.000 +assign wn_re[257] = 32'hxxxxxxxx; assign wn_im[257] = 32'hxxxxxxxx; // 257 -0.006 -1.000 +assign wn_re[258] = 32'hFE6DE2E0; assign wn_im[258] = 32'h800277A6; // 258 -0.012 -1.000 +assign wn_re[259] = 32'hxxxxxxxx; assign wn_im[259] = 32'hxxxxxxxx; // 259 -0.018 -1.000 +assign wn_re[260] = 32'hFCDBD541; assign wn_im[260] = 32'h8009DE7E; // 260 -0.025 -1.000 +assign wn_re[261] = 32'hFC12D91A; assign wn_im[261] = 32'h800F6B88; // 261 -0.031 -1.000 +assign wn_re[262] = 32'hFB49E6A3; assign wn_im[262] = 32'h80163440; // 262 -0.037 -0.999 +assign wn_re[263] = 32'hxxxxxxxx; assign wn_im[263] = 32'hxxxxxxxx; // 263 -0.043 -0.999 +assign wn_re[264] = 32'hF9B82684; assign wn_im[264] = 32'h80277872; // 264 -0.049 -0.999 +assign wn_re[265] = 32'hxxxxxxxx; assign wn_im[265] = 32'hxxxxxxxx; // 265 -0.055 -0.998 +assign wn_re[266] = 32'hF826A462; assign wn_im[266] = 32'h803DAA6A; // 266 -0.061 -0.998 +assign wn_re[267] = 32'hF75DFF66; assign wn_im[267] = 32'h804A9C4D; // 267 -0.067 -0.998 +assign wn_re[268] = 32'hF6956FB7; assign wn_im[268] = 32'h8058C94C; // 268 -0.074 -0.997 +assign wn_re[269] = 32'hxxxxxxxx; assign wn_im[269] = 32'hxxxxxxxx; // 269 -0.080 -0.997 +assign wn_re[270] = 32'hF50497FB; assign wn_im[270] = 32'h8078D40D; // 270 -0.086 -0.996 +assign wn_re[271] = 32'hxxxxxxxx; assign wn_im[271] = 32'hxxxxxxxx; // 271 -0.092 -0.996 +assign wn_re[272] = 32'hF3742CA2; assign wn_im[272] = 32'h809DC971; // 272 -0.098 -0.995 +assign wn_re[273] = 32'hF2AC246E; assign wn_im[273] = 32'h80B21BAF; // 273 -0.104 -0.995 +assign wn_re[274] = 32'hF1E43D1C; assign wn_im[274] = 32'h80C7A80A; // 274 -0.110 -0.994 +assign wn_re[275] = 32'hxxxxxxxx; assign wn_im[275] = 32'hxxxxxxxx; // 275 -0.116 -0.993 +assign wn_re[276] = 32'hF054D8D5; assign wn_im[276] = 32'h80F66E3C; // 276 -0.122 -0.992 +assign wn_re[277] = 32'hxxxxxxxx; assign wn_im[277] = 32'hxxxxxxxx; // 277 -0.128 -0.992 +assign wn_re[278] = 32'hEEC60F31; assign wn_im[278] = 32'h812A1A3A; // 278 -0.135 -0.991 +assign wn_re[279] = 32'hEDFEE92B; assign wn_im[279] = 32'h8145C5C7; // 279 -0.141 -0.990 +assign wn_re[280] = 32'hED37EF91; assign wn_im[280] = 32'h8162AA04; // 280 -0.147 -0.989 +assign wn_re[281] = 32'hxxxxxxxx; assign wn_im[281] = 32'hxxxxxxxx; // 281 -0.153 -0.988 +assign wn_re[282] = 32'hEBAA894F; assign wn_im[282] = 32'h81A01B6D; // 282 -0.159 -0.987 +assign wn_re[283] = 32'hxxxxxxxx; assign wn_im[283] = 32'hxxxxxxxx; // 283 -0.165 -0.986 +assign wn_re[284] = 32'hEA1DEBBB; assign wn_im[284] = 32'h81E26C16; // 284 -0.171 -0.985 +assign wn_re[285] = 32'hE957ECFB; assign wn_im[285] = 32'h82056758; // 285 -0.177 -0.984 +assign wn_re[286] = 32'hE8922622; assign wn_im[286] = 32'h82299971; // 286 -0.183 -0.983 +assign wn_re[287] = 32'hxxxxxxxx; assign wn_im[287] = 32'hxxxxxxxx; // 287 -0.189 -0.982 +assign wn_re[288] = 32'hE70747C4; assign wn_im[288] = 32'h8275A0C0; // 288 -0.195 -0.981 +assign wn_re[289] = 32'hxxxxxxxx; assign wn_im[289] = 32'hxxxxxxxx; // 289 -0.201 -0.980 +assign wn_re[290] = 32'hE57D5FDA; assign wn_im[290] = 32'h82C67F14; // 290 -0.207 -0.978 +assign wn_re[291] = 32'hE4B8CD11; assign wn_im[291] = 32'h82F0BDE8; // 291 -0.213 -0.977 +assign wn_re[292] = 32'hE3F47D96; assign wn_im[292] = 32'h831C314E; // 292 -0.219 -0.976 +assign wn_re[293] = 32'hxxxxxxxx; assign wn_im[293] = 32'hxxxxxxxx; // 293 -0.225 -0.974 +assign wn_re[294] = 32'hE26CB01B; assign wn_im[294] = 32'h8376B422; // 294 -0.231 -0.973 +assign wn_re[295] = 32'hxxxxxxxx; assign wn_im[295] = 32'hxxxxxxxx; // 295 -0.237 -0.972 +assign wn_re[296] = 32'hE0E60685; assign wn_im[296] = 32'h83D60412; // 296 -0.243 -0.970 +assign wn_re[297] = 32'hE02323E5; assign wn_im[297] = 32'h840777D0; // 297 -0.249 -0.969 +assign wn_re[298] = 32'hDF608FE4; assign wn_im[298] = 32'h843A1D70; // 298 -0.255 -0.967 +assign wn_re[299] = 32'hxxxxxxxx; assign wn_im[299] = 32'hxxxxxxxx; // 299 -0.261 -0.965 +assign wn_re[300] = 32'hDDDC5B3B; assign wn_im[300] = 32'h84A2FC62; // 300 -0.267 -0.964 +assign wn_re[301] = 32'hxxxxxxxx; assign wn_im[301] = 32'hxxxxxxxx; // 301 -0.273 -0.962 +assign wn_re[302] = 32'hDC597781; assign wn_im[302] = 32'h85109CDD; // 302 -0.279 -0.960 +assign wn_re[303] = 32'hDB9888A8; assign wn_im[303] = 32'h8549345C; // 303 -0.284 -0.959 +assign wn_re[304] = 32'hDAD7F3A2; assign wn_im[304] = 32'h8582FAA5; // 304 -0.290 -0.957 +assign wn_re[305] = 32'hxxxxxxxx; assign wn_im[305] = 32'hxxxxxxxx; // 305 -0.296 -0.955 +assign wn_re[306] = 32'hD957DE7A; assign wn_im[306] = 32'h85FA1153; // 306 -0.302 -0.953 +assign wn_re[307] = 32'hxxxxxxxx; assign wn_im[307] = 32'hxxxxxxxx; // 307 -0.308 -0.951 +assign wn_re[308] = 32'hD7D946D8; assign wn_im[308] = 32'h8675DC4F; // 308 -0.314 -0.950 +assign wn_re[309] = 32'hD71A8EB5; assign wn_im[309] = 32'h86B583EE; // 309 -0.320 -0.948 +assign wn_re[310] = 32'hD65C3B7B; assign wn_im[310] = 32'h86F656D3; // 310 -0.325 -0.946 +assign wn_re[311] = 32'hxxxxxxxx; assign wn_im[311] = 32'hxxxxxxxx; // 311 -0.331 -0.944 +assign wn_re[312] = 32'hD4E0CB15; assign wn_im[312] = 32'h877B7BEC; // 312 -0.337 -0.942 +assign wn_re[313] = 32'hxxxxxxxx; assign wn_im[313] = 32'hxxxxxxxx; // 313 -0.343 -0.939 +assign wn_re[314] = 32'hD3670446; assign wn_im[314] = 32'h88054677; // 314 -0.348 -0.937 +assign wn_re[315] = 32'hD2AAC504; assign wn_im[315] = 32'h884BE821; // 315 -0.354 -0.935 +assign wn_re[316] = 32'hD1EEF59E; assign wn_im[316] = 32'h8893B125; // 316 -0.360 -0.933 +assign wn_re[317] = 32'hxxxxxxxx; assign wn_im[317] = 32'hxxxxxxxx; // 317 -0.366 -0.931 +assign wn_re[318] = 32'hD078AD9E; assign wn_im[318] = 32'h8926B677; // 318 -0.371 -0.929 +assign wn_re[319] = 32'hxxxxxxxx; assign wn_im[319] = 32'hxxxxxxxx; // 319 -0.377 -0.926 +assign wn_re[320] = 32'hCF043AB3; assign wn_im[320] = 32'h89BE50C3; // 320 -0.383 -0.924 +assign wn_re[321] = 32'hCE4AB5A2; assign wn_im[321] = 32'h8A0BD3F5; // 321 -0.388 -0.922 +assign wn_re[322] = 32'hCD91AB39; assign wn_im[322] = 32'h8A5A7A31; // 322 -0.394 -0.919 +assign wn_re[323] = 32'hxxxxxxxx; assign wn_im[323] = 32'hxxxxxxxx; // 323 -0.400 -0.917 +assign wn_re[324] = 32'hCC210D79; assign wn_im[324] = 32'h8AFB2CBB; // 324 -0.405 -0.914 +assign wn_re[325] = 32'hxxxxxxxx; assign wn_im[325] = 32'hxxxxxxxx; // 325 -0.411 -0.912 +assign wn_re[326] = 32'hCAB26FA9; assign wn_im[326] = 32'h8BA0622F; // 326 -0.416 -0.909 +assign wn_re[327] = 32'hC9FBE527; assign wn_im[327] = 32'h8BF4AC05; // 327 -0.422 -0.907 +assign wn_re[328] = 32'hC945DFEC; assign wn_im[328] = 32'h8C4A142F; // 328 -0.428 -0.904 +assign wn_re[329] = 32'hxxxxxxxx; assign wn_im[329] = 32'hxxxxxxxx; // 329 -0.433 -0.901 +assign wn_re[330] = 32'hC7DB6C50; assign wn_im[330] = 32'h8CF83C30; // 330 -0.439 -0.899 +assign wn_re[331] = 32'hxxxxxxxx; assign wn_im[331] = 32'hxxxxxxxx; // 331 -0.444 -0.896 +assign wn_re[332] = 32'hC67322CE; assign wn_im[332] = 32'h8DAAD37B; // 332 -0.450 -0.893 +assign wn_re[333] = 32'hC5BFD22E; assign wn_im[333] = 32'h8E05C6B7; // 333 -0.455 -0.890 +assign wn_re[334] = 32'hC50D1149; assign wn_im[334] = 32'h8E61D32E; // 334 -0.461 -0.888 +assign wn_re[335] = 32'hxxxxxxxx; assign wn_im[335] = 32'hxxxxxxxx; // 335 -0.466 -0.885 +assign wn_re[336] = 32'hC3A94590; assign wn_im[336] = 32'h8F1D343A; // 336 -0.471 -0.882 +assign wn_re[337] = 32'hxxxxxxxx; assign wn_im[337] = 32'hxxxxxxxx; // 337 -0.477 -0.879 +assign wn_re[338] = 32'hC247CD5A; assign wn_im[338] = 32'h8FDCEF66; // 338 -0.482 -0.876 +assign wn_re[339] = 32'hC197F4D4; assign wn_im[339] = 32'h903E6C7B; // 339 -0.488 -0.873 +assign wn_re[340] = 32'hC0E8B648; assign wn_im[340] = 32'h90A0FD4E; // 340 -0.493 -0.870 +assign wn_re[341] = 32'hxxxxxxxx; assign wn_im[341] = 32'hxxxxxxxx; // 341 -0.498 -0.867 +assign wn_re[342] = 32'hBF8C0DE3; assign wn_im[342] = 32'h91695663; // 342 -0.504 -0.864 +assign wn_re[343] = 32'hxxxxxxxx; assign wn_im[343] = 32'hxxxxxxxx; // 343 -0.509 -0.861 +assign wn_re[344] = 32'hBE31E19B; assign wn_im[344] = 32'h9235F2EC; // 344 -0.514 -0.858 +assign wn_re[345] = 32'hBD85BE30; assign wn_im[345] = 32'h929DD806; // 345 -0.519 -0.855 +assign wn_re[346] = 32'hBCDA3ECB; assign wn_im[346] = 32'h9306CB04; // 346 -0.525 -0.851 +assign wn_re[347] = 32'hxxxxxxxx; assign wn_im[347] = 32'hxxxxxxxx; // 347 -0.530 -0.848 +assign wn_re[348] = 32'hBB8532B0; assign wn_im[348] = 32'h93DBD6A0; // 348 -0.535 -0.845 +assign wn_re[349] = 32'hxxxxxxxx; assign wn_im[349] = 32'hxxxxxxxx; // 349 -0.540 -0.842 +assign wn_re[350] = 32'hBA32CA71; assign wn_im[350] = 32'h94B50D87; // 350 -0.545 -0.838 +assign wn_re[351] = 32'hB98A97D8; assign wn_im[351] = 32'h9523369C; // 351 -0.550 -0.835 +assign wn_re[352] = 32'hB8E31319; assign wn_im[352] = 32'h9592675C; // 352 -0.556 -0.831 +assign wn_re[353] = 32'hxxxxxxxx; assign wn_im[353] = 32'hxxxxxxxx; // 353 -0.561 -0.828 +assign wn_re[354] = 32'hB796199B; assign wn_im[354] = 32'h9673DB94; // 354 -0.566 -0.825 +assign wn_re[355] = 32'hxxxxxxxx; assign wn_im[355] = 32'hxxxxxxxx; // 355 -0.571 -0.821 +assign wn_re[356] = 32'hB64BEACD; assign wn_im[356] = 32'h9759617F; // 356 -0.576 -0.818 +assign wn_re[357] = 32'hB5A7E362; assign wn_im[357] = 32'h97CDA855; // 357 -0.581 -0.814 +assign wn_re[358] = 32'hB5049368; assign wn_im[358] = 32'h9842F043; // 358 -0.586 -0.810 +assign wn_re[359] = 32'hxxxxxxxx; assign wn_im[359] = 32'hxxxxxxxx; // 359 -0.591 -0.807 +assign wn_re[360] = 32'hB3C0200C; assign wn_im[360] = 32'h99307EE0; // 360 -0.596 -0.803 +assign wn_re[361] = 32'hxxxxxxxx; assign wn_im[361] = 32'hxxxxxxxx; // 361 -0.601 -0.800 +assign wn_re[362] = 32'hB27E9D3C; assign wn_im[362] = 32'h9A22042D; // 362 -0.606 -0.796 +assign wn_re[363] = 32'hB1DEF9E9; assign wn_im[363] = 32'h9A9C406E; // 363 -0.610 -0.792 +assign wn_re[364] = 32'hB140175B; assign wn_im[364] = 32'h9B1776DA; // 364 -0.615 -0.788 +assign wn_re[365] = 32'hxxxxxxxx; assign wn_im[365] = 32'hxxxxxxxx; // 365 -0.620 -0.785 +assign wn_re[366] = 32'hB0049AB3; assign wn_im[366] = 32'h9C10CD70; // 366 -0.625 -0.781 +assign wn_re[367] = 32'hxxxxxxxx; assign wn_im[367] = 32'hxxxxxxxx; // 367 -0.630 -0.777 +assign wn_re[368] = 32'hAECC336C; assign wn_im[368] = 32'h9D0DFE54; // 368 -0.634 -0.773 +assign wn_re[369] = 32'hAE312B92; assign wn_im[369] = 32'h9D8E0597; // 369 -0.639 -0.769 +assign wn_re[370] = 32'hAD96ED92; assign wn_im[370] = 32'h9E0EFFC1; // 370 -0.644 -0.765 +assign wn_re[371] = 32'hxxxxxxxx; assign wn_im[371] = 32'hxxxxxxxx; // 371 -0.649 -0.761 +assign wn_re[372] = 32'hAC64D510; assign wn_im[372] = 32'h9F13C7D0; // 372 -0.653 -0.757 +assign wn_re[373] = 32'hxxxxxxxx; assign wn_im[373] = 32'hxxxxxxxx; // 373 -0.658 -0.753 +assign wn_re[374] = 32'hAB35F5B5; assign wn_im[374] = 32'hA01C4C73; // 374 -0.662 -0.749 +assign wn_re[375] = 32'hAA9FBF1E; assign wn_im[375] = 32'hA0A1F24D; // 375 -0.667 -0.745 +assign wn_re[376] = 32'hAA0A5B2E; assign wn_im[376] = 32'hA1288376; // 376 -0.672 -0.741 +assign wn_re[377] = 32'hxxxxxxxx; assign wn_im[377] = 32'hxxxxxxxx; // 377 -0.676 -0.737 +assign wn_re[378] = 32'hA8E21106; assign wn_im[378] = 32'hA2386284; // 378 -0.681 -0.733 +assign wn_re[379] = 32'hxxxxxxxx; assign wn_im[379] = 32'hxxxxxxxx; // 379 -0.685 -0.728 +assign wn_re[380] = 32'hA7BD22AC; assign wn_im[380] = 32'hA34BDF20; // 380 -0.690 -0.724 +assign wn_re[381] = 32'hA72BF174; assign wn_im[381] = 32'hA3D6F534; // 381 -0.694 -0.720 +assign wn_re[382] = 32'hA69B9B68; assign wn_im[382] = 32'hA462EEAC; // 382 -0.698 -0.716 +assign wn_re[383] = 32'hxxxxxxxx; assign wn_im[383] = 32'hxxxxxxxx; // 383 -0.703 -0.711 +assign wn_re[384] = 32'hA57D8666; assign wn_im[384] = 32'hA57D8666; // 384 -0.707 -0.707 +assign wn_re[385] = 32'hxxxxxxxx; assign wn_im[385] = 32'hxxxxxxxx; // 385 -0.711 -0.703 +assign wn_re[386] = 32'hA462EEAC; assign wn_im[386] = 32'hA69B9B68; // 386 -0.716 -0.698 +assign wn_re[387] = 32'hA3D6F534; assign wn_im[387] = 32'hA72BF174; // 387 -0.720 -0.694 +assign wn_re[388] = 32'hA34BDF20; assign wn_im[388] = 32'hA7BD22AC; // 388 -0.724 -0.690 +assign wn_re[389] = 32'hxxxxxxxx; assign wn_im[389] = 32'hxxxxxxxx; // 389 -0.728 -0.685 +assign wn_re[390] = 32'hA2386284; assign wn_im[390] = 32'hA8E21106; // 390 -0.733 -0.681 +assign wn_re[391] = 32'hxxxxxxxx; assign wn_im[391] = 32'hxxxxxxxx; // 391 -0.737 -0.676 +assign wn_re[392] = 32'hA1288376; assign wn_im[392] = 32'hAA0A5B2E; // 392 -0.741 -0.672 +assign wn_re[393] = 32'hA0A1F24D; assign wn_im[393] = 32'hAA9FBF1E; // 393 -0.745 -0.667 +assign wn_re[394] = 32'hA01C4C73; assign wn_im[394] = 32'hAB35F5B5; // 394 -0.749 -0.662 +assign wn_re[395] = 32'hxxxxxxxx; assign wn_im[395] = 32'hxxxxxxxx; // 395 -0.753 -0.658 +assign wn_re[396] = 32'h9F13C7D0; assign wn_im[396] = 32'hAC64D510; // 396 -0.757 -0.653 +assign wn_re[397] = 32'hxxxxxxxx; assign wn_im[397] = 32'hxxxxxxxx; // 397 -0.761 -0.649 +assign wn_re[398] = 32'h9E0EFFC1; assign wn_im[398] = 32'hAD96ED92; // 398 -0.765 -0.644 +assign wn_re[399] = 32'h9D8E0597; assign wn_im[399] = 32'hAE312B92; // 399 -0.769 -0.639 +assign wn_re[400] = 32'h9D0DFE54; assign wn_im[400] = 32'hAECC336C; // 400 -0.773 -0.634 +assign wn_re[401] = 32'hxxxxxxxx; assign wn_im[401] = 32'hxxxxxxxx; // 401 -0.777 -0.630 +assign wn_re[402] = 32'h9C10CD70; assign wn_im[402] = 32'hB0049AB3; // 402 -0.781 -0.625 +assign wn_re[403] = 32'hxxxxxxxx; assign wn_im[403] = 32'hxxxxxxxx; // 403 -0.785 -0.620 +assign wn_re[404] = 32'h9B1776DA; assign wn_im[404] = 32'hB140175B; // 404 -0.788 -0.615 +assign wn_re[405] = 32'h9A9C406E; assign wn_im[405] = 32'hB1DEF9E9; // 405 -0.792 -0.610 +assign wn_re[406] = 32'h9A22042D; assign wn_im[406] = 32'hB27E9D3C; // 406 -0.796 -0.606 +assign wn_re[407] = 32'hxxxxxxxx; assign wn_im[407] = 32'hxxxxxxxx; // 407 -0.800 -0.601 +assign wn_re[408] = 32'h99307EE0; assign wn_im[408] = 32'hB3C0200C; // 408 -0.803 -0.596 +assign wn_re[409] = 32'hxxxxxxxx; assign wn_im[409] = 32'hxxxxxxxx; // 409 -0.807 -0.591 +assign wn_re[410] = 32'h9842F043; assign wn_im[410] = 32'hB5049368; // 410 -0.810 -0.586 +assign wn_re[411] = 32'h97CDA855; assign wn_im[411] = 32'hB5A7E362; // 411 -0.814 -0.581 +assign wn_re[412] = 32'h9759617F; assign wn_im[412] = 32'hB64BEACD; // 412 -0.818 -0.576 +assign wn_re[413] = 32'hxxxxxxxx; assign wn_im[413] = 32'hxxxxxxxx; // 413 -0.821 -0.571 +assign wn_re[414] = 32'h9673DB94; assign wn_im[414] = 32'hB796199B; // 414 -0.825 -0.566 +assign wn_re[415] = 32'hxxxxxxxx; assign wn_im[415] = 32'hxxxxxxxx; // 415 -0.828 -0.561 +assign wn_re[416] = 32'h9592675C; assign wn_im[416] = 32'hB8E31319; // 416 -0.831 -0.556 +assign wn_re[417] = 32'h9523369C; assign wn_im[417] = 32'hB98A97D8; // 417 -0.835 -0.550 +assign wn_re[418] = 32'h94B50D87; assign wn_im[418] = 32'hBA32CA71; // 418 -0.838 -0.545 +assign wn_re[419] = 32'hxxxxxxxx; assign wn_im[419] = 32'hxxxxxxxx; // 419 -0.842 -0.540 +assign wn_re[420] = 32'h93DBD6A0; assign wn_im[420] = 32'hBB8532B0; // 420 -0.845 -0.535 +assign wn_re[421] = 32'hxxxxxxxx; assign wn_im[421] = 32'hxxxxxxxx; // 421 -0.848 -0.530 +assign wn_re[422] = 32'h9306CB04; assign wn_im[422] = 32'hBCDA3ECB; // 422 -0.851 -0.525 +assign wn_re[423] = 32'h929DD806; assign wn_im[423] = 32'hBD85BE30; // 423 -0.855 -0.519 +assign wn_re[424] = 32'h9235F2EC; assign wn_im[424] = 32'hBE31E19B; // 424 -0.858 -0.514 +assign wn_re[425] = 32'hxxxxxxxx; assign wn_im[425] = 32'hxxxxxxxx; // 425 -0.861 -0.509 +assign wn_re[426] = 32'h91695663; assign wn_im[426] = 32'hBF8C0DE3; // 426 -0.864 -0.504 +assign wn_re[427] = 32'hxxxxxxxx; assign wn_im[427] = 32'hxxxxxxxx; // 427 -0.867 -0.498 +assign wn_re[428] = 32'h90A0FD4E; assign wn_im[428] = 32'hC0E8B648; // 428 -0.870 -0.493 +assign wn_re[429] = 32'h903E6C7B; assign wn_im[429] = 32'hC197F4D4; // 429 -0.873 -0.488 +assign wn_re[430] = 32'h8FDCEF66; assign wn_im[430] = 32'hC247CD5A; // 430 -0.876 -0.482 +assign wn_re[431] = 32'hxxxxxxxx; assign wn_im[431] = 32'hxxxxxxxx; // 431 -0.879 -0.477 +assign wn_re[432] = 32'h8F1D343A; assign wn_im[432] = 32'hC3A94590; // 432 -0.882 -0.471 +assign wn_re[433] = 32'hxxxxxxxx; assign wn_im[433] = 32'hxxxxxxxx; // 433 -0.885 -0.466 +assign wn_re[434] = 32'h8E61D32E; assign wn_im[434] = 32'hC50D1149; // 434 -0.888 -0.461 +assign wn_re[435] = 32'h8E05C6B7; assign wn_im[435] = 32'hC5BFD22E; // 435 -0.890 -0.455 +assign wn_re[436] = 32'h8DAAD37B; assign wn_im[436] = 32'hC67322CE; // 436 -0.893 -0.450 +assign wn_re[437] = 32'hxxxxxxxx; assign wn_im[437] = 32'hxxxxxxxx; // 437 -0.896 -0.444 +assign wn_re[438] = 32'h8CF83C30; assign wn_im[438] = 32'hC7DB6C50; // 438 -0.899 -0.439 +assign wn_re[439] = 32'hxxxxxxxx; assign wn_im[439] = 32'hxxxxxxxx; // 439 -0.901 -0.433 +assign wn_re[440] = 32'h8C4A142F; assign wn_im[440] = 32'hC945DFEC; // 440 -0.904 -0.428 +assign wn_re[441] = 32'h8BF4AC05; assign wn_im[441] = 32'hC9FBE527; // 441 -0.907 -0.422 +assign wn_re[442] = 32'h8BA0622F; assign wn_im[442] = 32'hCAB26FA9; // 442 -0.909 -0.416 +assign wn_re[443] = 32'hxxxxxxxx; assign wn_im[443] = 32'hxxxxxxxx; // 443 -0.912 -0.411 +assign wn_re[444] = 32'h8AFB2CBB; assign wn_im[444] = 32'hCC210D79; // 444 -0.914 -0.405 +assign wn_re[445] = 32'hxxxxxxxx; assign wn_im[445] = 32'hxxxxxxxx; // 445 -0.917 -0.400 +assign wn_re[446] = 32'h8A5A7A31; assign wn_im[446] = 32'hCD91AB39; // 446 -0.919 -0.394 +assign wn_re[447] = 32'h8A0BD3F5; assign wn_im[447] = 32'hCE4AB5A2; // 447 -0.922 -0.388 +assign wn_re[448] = 32'h89BE50C3; assign wn_im[448] = 32'hCF043AB3; // 448 -0.924 -0.383 +assign wn_re[449] = 32'hxxxxxxxx; assign wn_im[449] = 32'hxxxxxxxx; // 449 -0.926 -0.377 +assign wn_re[450] = 32'h8926B677; assign wn_im[450] = 32'hD078AD9E; // 450 -0.929 -0.371 +assign wn_re[451] = 32'hxxxxxxxx; assign wn_im[451] = 32'hxxxxxxxx; // 451 -0.931 -0.366 +assign wn_re[452] = 32'h8893B125; assign wn_im[452] = 32'hD1EEF59E; // 452 -0.933 -0.360 +assign wn_re[453] = 32'h884BE821; assign wn_im[453] = 32'hD2AAC504; // 453 -0.935 -0.354 +assign wn_re[454] = 32'h88054677; assign wn_im[454] = 32'hD3670446; // 454 -0.937 -0.348 +assign wn_re[455] = 32'hxxxxxxxx; assign wn_im[455] = 32'hxxxxxxxx; // 455 -0.939 -0.343 +assign wn_re[456] = 32'h877B7BEC; assign wn_im[456] = 32'hD4E0CB15; // 456 -0.942 -0.337 +assign wn_re[457] = 32'hxxxxxxxx; assign wn_im[457] = 32'hxxxxxxxx; // 457 -0.944 -0.331 +assign wn_re[458] = 32'h86F656D3; assign wn_im[458] = 32'hD65C3B7B; // 458 -0.946 -0.325 +assign wn_re[459] = 32'h86B583EE; assign wn_im[459] = 32'hD71A8EB5; // 459 -0.948 -0.320 +assign wn_re[460] = 32'h8675DC4F; assign wn_im[460] = 32'hD7D946D8; // 460 -0.950 -0.314 +assign wn_re[461] = 32'hxxxxxxxx; assign wn_im[461] = 32'hxxxxxxxx; // 461 -0.951 -0.308 +assign wn_re[462] = 32'h85FA1153; assign wn_im[462] = 32'hD957DE7A; // 462 -0.953 -0.302 +assign wn_re[463] = 32'hxxxxxxxx; assign wn_im[463] = 32'hxxxxxxxx; // 463 -0.955 -0.296 +assign wn_re[464] = 32'h8582FAA5; assign wn_im[464] = 32'hDAD7F3A2; // 464 -0.957 -0.290 +assign wn_re[465] = 32'h8549345C; assign wn_im[465] = 32'hDB9888A8; // 465 -0.959 -0.284 +assign wn_re[466] = 32'h85109CDD; assign wn_im[466] = 32'hDC597781; // 466 -0.960 -0.279 +assign wn_re[467] = 32'hxxxxxxxx; assign wn_im[467] = 32'hxxxxxxxx; // 467 -0.962 -0.273 +assign wn_re[468] = 32'h84A2FC62; assign wn_im[468] = 32'hDDDC5B3B; // 468 -0.964 -0.267 +assign wn_re[469] = 32'hxxxxxxxx; assign wn_im[469] = 32'hxxxxxxxx; // 469 -0.965 -0.261 +assign wn_re[470] = 32'h843A1D70; assign wn_im[470] = 32'hDF608FE4; // 470 -0.967 -0.255 +assign wn_re[471] = 32'h840777D0; assign wn_im[471] = 32'hE02323E5; // 471 -0.969 -0.249 +assign wn_re[472] = 32'h83D60412; assign wn_im[472] = 32'hE0E60685; // 472 -0.970 -0.243 +assign wn_re[473] = 32'hxxxxxxxx; assign wn_im[473] = 32'hxxxxxxxx; // 473 -0.972 -0.237 +assign wn_re[474] = 32'h8376B422; assign wn_im[474] = 32'hE26CB01B; // 474 -0.973 -0.231 +assign wn_re[475] = 32'hxxxxxxxx; assign wn_im[475] = 32'hxxxxxxxx; // 475 -0.974 -0.225 +assign wn_re[476] = 32'h831C314E; assign wn_im[476] = 32'hE3F47D96; // 476 -0.976 -0.219 +assign wn_re[477] = 32'h82F0BDE8; assign wn_im[477] = 32'hE4B8CD11; // 477 -0.977 -0.213 +assign wn_re[478] = 32'h82C67F14; assign wn_im[478] = 32'hE57D5FDA; // 478 -0.978 -0.207 +assign wn_re[479] = 32'hxxxxxxxx; assign wn_im[479] = 32'hxxxxxxxx; // 479 -0.980 -0.201 +assign wn_re[480] = 32'h8275A0C0; assign wn_im[480] = 32'hE70747C4; // 480 -0.981 -0.195 +assign wn_re[481] = 32'hxxxxxxxx; assign wn_im[481] = 32'hxxxxxxxx; // 481 -0.982 -0.189 +assign wn_re[482] = 32'h82299971; assign wn_im[482] = 32'hE8922622; // 482 -0.983 -0.183 +assign wn_re[483] = 32'h82056758; assign wn_im[483] = 32'hE957ECFB; // 483 -0.984 -0.177 +assign wn_re[484] = 32'h81E26C16; assign wn_im[484] = 32'hEA1DEBBB; // 484 -0.985 -0.171 +assign wn_re[485] = 32'hxxxxxxxx; assign wn_im[485] = 32'hxxxxxxxx; // 485 -0.986 -0.165 +assign wn_re[486] = 32'h81A01B6D; assign wn_im[486] = 32'hEBAA894F; // 486 -0.987 -0.159 +assign wn_re[487] = 32'hxxxxxxxx; assign wn_im[487] = 32'hxxxxxxxx; // 487 -0.988 -0.153 +assign wn_re[488] = 32'h8162AA04; assign wn_im[488] = 32'hED37EF91; // 488 -0.989 -0.147 +assign wn_re[489] = 32'h8145C5C7; assign wn_im[489] = 32'hEDFEE92B; // 489 -0.990 -0.141 +assign wn_re[490] = 32'h812A1A3A; assign wn_im[490] = 32'hEEC60F31; // 490 -0.991 -0.135 +assign wn_re[491] = 32'hxxxxxxxx; assign wn_im[491] = 32'hxxxxxxxx; // 491 -0.992 -0.128 +assign wn_re[492] = 32'h80F66E3C; assign wn_im[492] = 32'hF054D8D5; // 492 -0.992 -0.122 +assign wn_re[493] = 32'hxxxxxxxx; assign wn_im[493] = 32'hxxxxxxxx; // 493 -0.993 -0.116 +assign wn_re[494] = 32'h80C7A80A; assign wn_im[494] = 32'hF1E43D1C; // 494 -0.994 -0.110 +assign wn_re[495] = 32'h80B21BAF; assign wn_im[495] = 32'hF2AC246E; // 495 -0.995 -0.104 +assign wn_re[496] = 32'h809DC971; assign wn_im[496] = 32'hF3742CA2; // 496 -0.995 -0.098 +assign wn_re[497] = 32'hxxxxxxxx; assign wn_im[497] = 32'hxxxxxxxx; // 497 -0.996 -0.092 +assign wn_re[498] = 32'h8078D40D; assign wn_im[498] = 32'hF50497FB; // 498 -0.996 -0.086 +assign wn_re[499] = 32'hxxxxxxxx; assign wn_im[499] = 32'hxxxxxxxx; // 499 -0.997 -0.080 +assign wn_re[500] = 32'h8058C94C; assign wn_im[500] = 32'hF6956FB7; // 500 -0.997 -0.074 +assign wn_re[501] = 32'h804A9C4D; assign wn_im[501] = 32'hF75DFF66; // 501 -0.998 -0.067 +assign wn_re[502] = 32'h803DAA6A; assign wn_im[502] = 32'hF826A462; // 502 -0.998 -0.061 +assign wn_re[503] = 32'hxxxxxxxx; assign wn_im[503] = 32'hxxxxxxxx; // 503 -0.998 -0.055 +assign wn_re[504] = 32'h80277872; assign wn_im[504] = 32'hF9B82684; // 504 -0.999 -0.049 +assign wn_re[505] = 32'hxxxxxxxx; assign wn_im[505] = 32'hxxxxxxxx; // 505 -0.999 -0.043 +assign wn_re[506] = 32'h80163440; assign wn_im[506] = 32'hFB49E6A3; // 506 -0.999 -0.037 +assign wn_re[507] = 32'h800F6B88; assign wn_im[507] = 32'hFC12D91A; // 507 -1.000 -0.031 +assign wn_re[508] = 32'h8009DE7E; assign wn_im[508] = 32'hFCDBD541; // 508 -1.000 -0.025 +assign wn_re[509] = 32'hxxxxxxxx; assign wn_im[509] = 32'hxxxxxxxx; // 509 -1.000 -0.018 +assign wn_re[510] = 32'h800277A6; assign wn_im[510] = 32'hFE6DE2E0; // 510 -1.000 -0.012 +assign wn_re[511] = 32'hxxxxxxxx; assign wn_im[511] = 32'hxxxxxxxx; // 511 -1.000 -0.006 +assign wn_re[512] = 32'hxxxxxxxx; assign wn_im[512] = 32'hxxxxxxxx; // 512 -1.000 -0.000 +assign wn_re[513] = 32'h80009DEA; assign wn_im[513] = 32'h00C90F88; // 513 -1.000 0.006 +assign wn_re[514] = 32'hxxxxxxxx; assign wn_im[514] = 32'hxxxxxxxx; // 514 -1.000 0.012 +assign wn_re[515] = 32'hxxxxxxxx; assign wn_im[515] = 32'hxxxxxxxx; // 515 -1.000 0.018 +assign wn_re[516] = 32'h8009DE7E; assign wn_im[516] = 32'h03242ABF; // 516 -1.000 0.025 +assign wn_re[517] = 32'hxxxxxxxx; assign wn_im[517] = 32'hxxxxxxxx; // 517 -1.000 0.031 +assign wn_re[518] = 32'hxxxxxxxx; assign wn_im[518] = 32'hxxxxxxxx; // 518 -0.999 0.037 +assign wn_re[519] = 32'h801E3895; assign wn_im[519] = 32'h057F0035; // 519 -0.999 0.043 +assign wn_re[520] = 32'hxxxxxxxx; assign wn_im[520] = 32'hxxxxxxxx; // 520 -0.999 0.049 +assign wn_re[521] = 32'hxxxxxxxx; assign wn_im[521] = 32'hxxxxxxxx; // 521 -0.998 0.055 +assign wn_re[522] = 32'h803DAA6A; assign wn_im[522] = 32'h07D95B9E; // 522 -0.998 0.061 +assign wn_re[523] = 32'hxxxxxxxx; assign wn_im[523] = 32'hxxxxxxxx; // 523 -0.998 0.067 +assign wn_re[524] = 32'hxxxxxxxx; assign wn_im[524] = 32'hxxxxxxxx; // 524 -0.997 0.074 +assign wn_re[525] = 32'h80683143; assign wn_im[525] = 32'h0A3308BD; // 525 -0.997 0.080 +assign wn_re[526] = 32'hxxxxxxxx; assign wn_im[526] = 32'hxxxxxxxx; // 526 -0.996 0.086 +assign wn_re[527] = 32'hxxxxxxxx; assign wn_im[527] = 32'hxxxxxxxx; // 527 -0.996 0.092 +assign wn_re[528] = 32'h809DC971; assign wn_im[528] = 32'h0C8BD35E; // 528 -0.995 0.098 +assign wn_re[529] = 32'hxxxxxxxx; assign wn_im[529] = 32'hxxxxxxxx; // 529 -0.995 0.104 +assign wn_re[530] = 32'hxxxxxxxx; assign wn_im[530] = 32'hxxxxxxxx; // 530 -0.994 0.110 +assign wn_re[531] = 32'h80DE6E4C; assign wn_im[531] = 32'h0EE38766; // 531 -0.993 0.116 +assign wn_re[532] = 32'hxxxxxxxx; assign wn_im[532] = 32'hxxxxxxxx; // 532 -0.992 0.122 +assign wn_re[533] = 32'hxxxxxxxx; assign wn_im[533] = 32'hxxxxxxxx; // 533 -0.992 0.128 +assign wn_re[534] = 32'h812A1A3A; assign wn_im[534] = 32'h1139F0CF; // 534 -0.991 0.135 +assign wn_re[535] = 32'hxxxxxxxx; assign wn_im[535] = 32'hxxxxxxxx; // 535 -0.990 0.141 +assign wn_re[536] = 32'hxxxxxxxx; assign wn_im[536] = 32'hxxxxxxxx; // 536 -0.989 0.147 +assign wn_re[537] = 32'h8180C6A9; assign wn_im[537] = 32'h138EDBB1; // 537 -0.988 0.153 +assign wn_re[538] = 32'hxxxxxxxx; assign wn_im[538] = 32'hxxxxxxxx; // 538 -0.987 0.159 +assign wn_re[539] = 32'hxxxxxxxx; assign wn_im[539] = 32'hxxxxxxxx; // 539 -0.986 0.165 +assign wn_re[540] = 32'h81E26C16; assign wn_im[540] = 32'h15E21445; // 540 -0.985 0.171 +assign wn_re[541] = 32'hxxxxxxxx; assign wn_im[541] = 32'hxxxxxxxx; // 541 -0.984 0.177 +assign wn_re[542] = 32'hxxxxxxxx; assign wn_im[542] = 32'hxxxxxxxx; // 542 -0.983 0.183 +assign wn_re[543] = 32'h824F0208; assign wn_im[543] = 32'h183366E9; // 543 -0.982 0.189 +assign wn_re[544] = 32'hxxxxxxxx; assign wn_im[544] = 32'hxxxxxxxx; // 544 -0.981 0.195 +assign wn_re[545] = 32'hxxxxxxxx; assign wn_im[545] = 32'hxxxxxxxx; // 545 -0.980 0.201 +assign wn_re[546] = 32'h82C67F14; assign wn_im[546] = 32'h1A82A026; // 546 -0.978 0.207 +assign wn_re[547] = 32'hxxxxxxxx; assign wn_im[547] = 32'hxxxxxxxx; // 547 -0.977 0.213 +assign wn_re[548] = 32'hxxxxxxxx; assign wn_im[548] = 32'hxxxxxxxx; // 548 -0.976 0.219 +assign wn_re[549] = 32'h8348D8DC; assign wn_im[549] = 32'h1CCF8CB3; // 549 -0.974 0.225 +assign wn_re[550] = 32'hxxxxxxxx; assign wn_im[550] = 32'hxxxxxxxx; // 550 -0.973 0.231 +assign wn_re[551] = 32'hxxxxxxxx; assign wn_im[551] = 32'hxxxxxxxx; // 551 -0.972 0.237 +assign wn_re[552] = 32'h83D60412; assign wn_im[552] = 32'h1F19F97B; // 552 -0.970 0.243 +assign wn_re[553] = 32'hxxxxxxxx; assign wn_im[553] = 32'hxxxxxxxx; // 553 -0.969 0.249 +assign wn_re[554] = 32'hxxxxxxxx; assign wn_im[554] = 32'hxxxxxxxx; // 554 -0.967 0.255 +assign wn_re[555] = 32'h846DF477; assign wn_im[555] = 32'h2161B3A0; // 555 -0.965 0.261 +assign wn_re[556] = 32'hxxxxxxxx; assign wn_im[556] = 32'hxxxxxxxx; // 556 -0.964 0.267 +assign wn_re[557] = 32'hxxxxxxxx; assign wn_im[557] = 32'hxxxxxxxx; // 557 -0.962 0.273 +assign wn_re[558] = 32'h85109CDD; assign wn_im[558] = 32'h23A6887F; // 558 -0.960 0.279 +assign wn_re[559] = 32'hxxxxxxxx; assign wn_im[559] = 32'hxxxxxxxx; // 559 -0.959 0.284 +assign wn_re[560] = 32'hxxxxxxxx; assign wn_im[560] = 32'hxxxxxxxx; // 560 -0.957 0.290 +assign wn_re[561] = 32'h85BDEF28; assign wn_im[561] = 32'h25E845B6; // 561 -0.955 0.296 +assign wn_re[562] = 32'hxxxxxxxx; assign wn_im[562] = 32'hxxxxxxxx; // 562 -0.953 0.302 +assign wn_re[563] = 32'hxxxxxxxx; assign wn_im[563] = 32'hxxxxxxxx; // 563 -0.951 0.308 +assign wn_re[564] = 32'h8675DC4F; assign wn_im[564] = 32'h2826B928; // 564 -0.950 0.314 +assign wn_re[565] = 32'hxxxxxxxx; assign wn_im[565] = 32'hxxxxxxxx; // 565 -0.948 0.320 +assign wn_re[566] = 32'hxxxxxxxx; assign wn_im[566] = 32'hxxxxxxxx; // 566 -0.946 0.325 +assign wn_re[567] = 32'h8738545E; assign wn_im[567] = 32'h2A61B101; // 567 -0.944 0.331 +assign wn_re[568] = 32'hxxxxxxxx; assign wn_im[568] = 32'hxxxxxxxx; // 568 -0.942 0.337 +assign wn_re[569] = 32'hxxxxxxxx; assign wn_im[569] = 32'hxxxxxxxx; // 569 -0.939 0.343 +assign wn_re[570] = 32'h88054677; assign wn_im[570] = 32'h2C98FBBA; // 570 -0.937 0.348 +assign wn_re[571] = 32'hxxxxxxxx; assign wn_im[571] = 32'hxxxxxxxx; // 571 -0.935 0.354 +assign wn_re[572] = 32'hxxxxxxxx; assign wn_im[572] = 32'hxxxxxxxx; // 572 -0.933 0.360 +assign wn_re[573] = 32'h88DCA0D3; assign wn_im[573] = 32'h2ECC681E; // 573 -0.931 0.366 +assign wn_re[574] = 32'hxxxxxxxx; assign wn_im[574] = 32'hxxxxxxxx; // 574 -0.929 0.371 +assign wn_re[575] = 32'hxxxxxxxx; assign wn_im[575] = 32'hxxxxxxxx; // 575 -0.926 0.377 +assign wn_re[576] = 32'h89BE50C3; assign wn_im[576] = 32'h30FBC54D; // 576 -0.924 0.383 +assign wn_re[577] = 32'hxxxxxxxx; assign wn_im[577] = 32'hxxxxxxxx; // 577 -0.922 0.388 +assign wn_re[578] = 32'hxxxxxxxx; assign wn_im[578] = 32'hxxxxxxxx; // 578 -0.919 0.394 +assign wn_re[579] = 32'h8AAA42B4; assign wn_im[579] = 32'h3326E2C3; // 579 -0.917 0.400 +assign wn_re[580] = 32'hxxxxxxxx; assign wn_im[580] = 32'hxxxxxxxx; // 580 -0.914 0.405 +assign wn_re[581] = 32'hxxxxxxxx; assign wn_im[581] = 32'hxxxxxxxx; // 581 -0.912 0.411 +assign wn_re[582] = 32'h8BA0622F; assign wn_im[582] = 32'h354D9057; // 582 -0.909 0.416 +assign wn_re[583] = 32'hxxxxxxxx; assign wn_im[583] = 32'hxxxxxxxx; // 583 -0.907 0.422 +assign wn_re[584] = 32'hxxxxxxxx; assign wn_im[584] = 32'hxxxxxxxx; // 584 -0.904 0.428 +assign wn_re[585] = 32'h8CA099DA; assign wn_im[585] = 32'h376F9E46; // 585 -0.901 0.433 +assign wn_re[586] = 32'hxxxxxxxx; assign wn_im[586] = 32'hxxxxxxxx; // 586 -0.899 0.439 +assign wn_re[587] = 32'hxxxxxxxx; assign wn_im[587] = 32'hxxxxxxxx; // 587 -0.896 0.444 +assign wn_re[588] = 32'h8DAAD37B; assign wn_im[588] = 32'h398CDD32; // 588 -0.893 0.450 +assign wn_re[589] = 32'hxxxxxxxx; assign wn_im[589] = 32'hxxxxxxxx; // 589 -0.890 0.455 +assign wn_re[590] = 32'hxxxxxxxx; assign wn_im[590] = 32'hxxxxxxxx; // 590 -0.888 0.461 +assign wn_re[591] = 32'h8EBEF7FB; assign wn_im[591] = 32'h3BA51E29; // 591 -0.885 0.466 +assign wn_re[592] = 32'hxxxxxxxx; assign wn_im[592] = 32'hxxxxxxxx; // 592 -0.882 0.471 +assign wn_re[593] = 32'hxxxxxxxx; assign wn_im[593] = 32'hxxxxxxxx; // 593 -0.879 0.477 +assign wn_re[594] = 32'h8FDCEF66; assign wn_im[594] = 32'h3DB832A6; // 594 -0.876 0.482 +assign wn_re[595] = 32'hxxxxxxxx; assign wn_im[595] = 32'hxxxxxxxx; // 595 -0.873 0.488 +assign wn_re[596] = 32'hxxxxxxxx; assign wn_im[596] = 32'hxxxxxxxx; // 596 -0.870 0.493 +assign wn_re[597] = 32'h9104A0EE; assign wn_im[597] = 32'h3FC5EC98; // 597 -0.867 0.498 +assign wn_re[598] = 32'hxxxxxxxx; assign wn_im[598] = 32'hxxxxxxxx; // 598 -0.864 0.504 +assign wn_re[599] = 32'hxxxxxxxx; assign wn_im[599] = 32'hxxxxxxxx; // 599 -0.861 0.509 +assign wn_re[600] = 32'h9235F2EC; assign wn_im[600] = 32'h41CE1E65; // 600 -0.858 0.514 +assign wn_re[601] = 32'hxxxxxxxx; assign wn_im[601] = 32'hxxxxxxxx; // 601 -0.855 0.519 +assign wn_re[602] = 32'hxxxxxxxx; assign wn_im[602] = 32'hxxxxxxxx; // 602 -0.851 0.525 +assign wn_re[603] = 32'h9370CAE4; assign wn_im[603] = 32'h43D09AED; // 603 -0.848 0.530 +assign wn_re[604] = 32'hxxxxxxxx; assign wn_im[604] = 32'hxxxxxxxx; // 604 -0.845 0.535 +assign wn_re[605] = 32'hxxxxxxxx; assign wn_im[605] = 32'hxxxxxxxx; // 605 -0.842 0.540 +assign wn_re[606] = 32'h94B50D87; assign wn_im[606] = 32'h45CD358F; // 606 -0.838 0.545 +assign wn_re[607] = 32'hxxxxxxxx; assign wn_im[607] = 32'hxxxxxxxx; // 607 -0.835 0.550 +assign wn_re[608] = 32'hxxxxxxxx; assign wn_im[608] = 32'hxxxxxxxx; // 608 -0.831 0.556 +assign wn_re[609] = 32'h96029EB6; assign wn_im[609] = 32'h47C3C22F; // 609 -0.828 0.561 +assign wn_re[610] = 32'hxxxxxxxx; assign wn_im[610] = 32'hxxxxxxxx; // 610 -0.825 0.566 +assign wn_re[611] = 32'hxxxxxxxx; assign wn_im[611] = 32'hxxxxxxxx; // 611 -0.821 0.571 +assign wn_re[612] = 32'h9759617F; assign wn_im[612] = 32'h49B41533; // 612 -0.818 0.576 +assign wn_re[613] = 32'hxxxxxxxx; assign wn_im[613] = 32'hxxxxxxxx; // 613 -0.814 0.581 +assign wn_re[614] = 32'hxxxxxxxx; assign wn_im[614] = 32'hxxxxxxxx; // 614 -0.810 0.586 +assign wn_re[615] = 32'h98B93828; assign wn_im[615] = 32'h4B9E0390; // 615 -0.807 0.591 +assign wn_re[616] = 32'hxxxxxxxx; assign wn_im[616] = 32'hxxxxxxxx; // 616 -0.803 0.596 +assign wn_re[617] = 32'hxxxxxxxx; assign wn_im[617] = 32'hxxxxxxxx; // 617 -0.800 0.601 +assign wn_re[618] = 32'h9A22042D; assign wn_im[618] = 32'h4D8162C4; // 618 -0.796 0.606 +assign wn_re[619] = 32'hxxxxxxxx; assign wn_im[619] = 32'hxxxxxxxx; // 619 -0.792 0.610 +assign wn_re[620] = 32'hxxxxxxxx; assign wn_im[620] = 32'hxxxxxxxx; // 620 -0.788 0.615 +assign wn_re[621] = 32'h9B93A641; assign wn_im[621] = 32'h4F5E08E3; // 621 -0.785 0.620 +assign wn_re[622] = 32'hxxxxxxxx; assign wn_im[622] = 32'hxxxxxxxx; // 622 -0.781 0.625 +assign wn_re[623] = 32'hxxxxxxxx; assign wn_im[623] = 32'hxxxxxxxx; // 623 -0.777 0.630 +assign wn_re[624] = 32'h9D0DFE54; assign wn_im[624] = 32'h5133CC94; // 624 -0.773 0.634 +assign wn_re[625] = 32'hxxxxxxxx; assign wn_im[625] = 32'hxxxxxxxx; // 625 -0.769 0.639 +assign wn_re[626] = 32'hxxxxxxxx; assign wn_im[626] = 32'hxxxxxxxx; // 626 -0.765 0.644 +assign wn_re[627] = 32'h9E90EB94; assign wn_im[627] = 32'h53028518; // 627 -0.761 0.649 +assign wn_re[628] = 32'hxxxxxxxx; assign wn_im[628] = 32'hxxxxxxxx; // 628 -0.757 0.653 +assign wn_re[629] = 32'hxxxxxxxx; assign wn_im[629] = 32'hxxxxxxxx; // 629 -0.753 0.658 +assign wn_re[630] = 32'hA01C4C73; assign wn_im[630] = 32'h54CA0A4B; // 630 -0.749 0.662 +assign wn_re[631] = 32'hxxxxxxxx; assign wn_im[631] = 32'hxxxxxxxx; // 631 -0.745 0.667 +assign wn_re[632] = 32'hxxxxxxxx; assign wn_im[632] = 32'hxxxxxxxx; // 632 -0.741 0.672 +assign wn_re[633] = 32'hA1AFFEA3; assign wn_im[633] = 32'h568A34A9; // 633 -0.737 0.676 +assign wn_re[634] = 32'hxxxxxxxx; assign wn_im[634] = 32'hxxxxxxxx; // 634 -0.733 0.681 +assign wn_re[635] = 32'hxxxxxxxx; assign wn_im[635] = 32'hxxxxxxxx; // 635 -0.728 0.685 +assign wn_re[636] = 32'hA34BDF20; assign wn_im[636] = 32'h5842DD54; // 636 -0.724 0.690 +assign wn_re[637] = 32'hxxxxxxxx; assign wn_im[637] = 32'hxxxxxxxx; // 637 -0.720 0.694 +assign wn_re[638] = 32'hxxxxxxxx; assign wn_im[638] = 32'hxxxxxxxx; // 638 -0.716 0.698 +assign wn_re[639] = 32'hA4EFCA31; assign wn_im[639] = 32'h59F3DE12; // 639 -0.711 0.703 +assign wn_re[640] = 32'hxxxxxxxx; assign wn_im[640] = 32'hxxxxxxxx; // 640 -0.707 0.707 +assign wn_re[641] = 32'hxxxxxxxx; assign wn_im[641] = 32'hxxxxxxxx; // 641 -0.703 0.711 +assign wn_re[642] = 32'hA69B9B68; assign wn_im[642] = 32'h5B9D1154; // 642 -0.698 0.716 +assign wn_re[643] = 32'hxxxxxxxx; assign wn_im[643] = 32'hxxxxxxxx; // 643 -0.694 0.720 +assign wn_re[644] = 32'hxxxxxxxx; assign wn_im[644] = 32'hxxxxxxxx; // 644 -0.690 0.724 +assign wn_re[645] = 32'hA84F2DAA; assign wn_im[645] = 32'h5D3E5237; // 645 -0.685 0.728 +assign wn_re[646] = 32'hxxxxxxxx; assign wn_im[646] = 32'hxxxxxxxx; // 646 -0.681 0.733 +assign wn_re[647] = 32'hxxxxxxxx; assign wn_im[647] = 32'hxxxxxxxx; // 647 -0.676 0.737 +assign wn_re[648] = 32'hAA0A5B2E; assign wn_im[648] = 32'h5ED77C8A; // 648 -0.672 0.741 +assign wn_re[649] = 32'hxxxxxxxx; assign wn_im[649] = 32'hxxxxxxxx; // 649 -0.667 0.745 +assign wn_re[650] = 32'hxxxxxxxx; assign wn_im[650] = 32'hxxxxxxxx; // 650 -0.662 0.749 +assign wn_re[651] = 32'hABCCFD83; assign wn_im[651] = 32'h60686CCF; // 651 -0.658 0.753 +assign wn_re[652] = 32'hxxxxxxxx; assign wn_im[652] = 32'hxxxxxxxx; // 652 -0.653 0.757 +assign wn_re[653] = 32'hxxxxxxxx; assign wn_im[653] = 32'hxxxxxxxx; // 653 -0.649 0.761 +assign wn_re[654] = 32'hAD96ED92; assign wn_im[654] = 32'h61F1003F; // 654 -0.644 0.765 +assign wn_re[655] = 32'hxxxxxxxx; assign wn_im[655] = 32'hxxxxxxxx; // 655 -0.639 0.769 +assign wn_re[656] = 32'hxxxxxxxx; assign wn_im[656] = 32'hxxxxxxxx; // 656 -0.634 0.773 +assign wn_re[657] = 32'hAF6803A2; assign wn_im[657] = 32'h637114CC; // 657 -0.630 0.777 +assign wn_re[658] = 32'hxxxxxxxx; assign wn_im[658] = 32'hxxxxxxxx; // 658 -0.625 0.781 +assign wn_re[659] = 32'hxxxxxxxx; assign wn_im[659] = 32'hxxxxxxxx; // 659 -0.620 0.785 +assign wn_re[660] = 32'hB140175B; assign wn_im[660] = 32'h64E88926; // 660 -0.615 0.788 +assign wn_re[661] = 32'hxxxxxxxx; assign wn_im[661] = 32'hxxxxxxxx; // 661 -0.610 0.792 +assign wn_re[662] = 32'hxxxxxxxx; assign wn_im[662] = 32'hxxxxxxxx; // 662 -0.606 0.796 +assign wn_re[663] = 32'hB31EFFCC; assign wn_im[663] = 32'h66573CBB; // 663 -0.601 0.800 +assign wn_re[664] = 32'hxxxxxxxx; assign wn_im[664] = 32'hxxxxxxxx; // 664 -0.596 0.803 +assign wn_re[665] = 32'hxxxxxxxx; assign wn_im[665] = 32'hxxxxxxxx; // 665 -0.591 0.807 +assign wn_re[666] = 32'hB5049368; assign wn_im[666] = 32'h67BD0FBD; // 666 -0.586 0.810 +assign wn_re[667] = 32'hxxxxxxxx; assign wn_im[667] = 32'hxxxxxxxx; // 667 -0.581 0.814 +assign wn_re[668] = 32'hxxxxxxxx; assign wn_im[668] = 32'hxxxxxxxx; // 668 -0.576 0.818 +assign wn_re[669] = 32'hB6F0A812; assign wn_im[669] = 32'h6919E320; // 669 -0.571 0.821 +assign wn_re[670] = 32'hxxxxxxxx; assign wn_im[670] = 32'hxxxxxxxx; // 670 -0.566 0.825 +assign wn_re[671] = 32'hxxxxxxxx; assign wn_im[671] = 32'hxxxxxxxx; // 671 -0.561 0.828 +assign wn_re[672] = 32'hB8E31319; assign wn_im[672] = 32'h6A6D98A4; // 672 -0.556 0.831 +assign wn_re[673] = 32'hxxxxxxxx; assign wn_im[673] = 32'hxxxxxxxx; // 673 -0.550 0.835 +assign wn_re[674] = 32'hxxxxxxxx; assign wn_im[674] = 32'hxxxxxxxx; // 674 -0.545 0.838 +assign wn_re[675] = 32'hBADBA943; assign wn_im[675] = 32'h6BB812D1; // 675 -0.540 0.842 +assign wn_re[676] = 32'hxxxxxxxx; assign wn_im[676] = 32'hxxxxxxxx; // 676 -0.535 0.845 +assign wn_re[677] = 32'hxxxxxxxx; assign wn_im[677] = 32'hxxxxxxxx; // 677 -0.530 0.848 +assign wn_re[678] = 32'hBCDA3ECB; assign wn_im[678] = 32'h6CF934FC; // 678 -0.525 0.851 +assign wn_re[679] = 32'hxxxxxxxx; assign wn_im[679] = 32'hxxxxxxxx; // 679 -0.519 0.855 +assign wn_re[680] = 32'hxxxxxxxx; assign wn_im[680] = 32'hxxxxxxxx; // 680 -0.514 0.858 +assign wn_re[681] = 32'hBEDEA765; assign wn_im[681] = 32'h6E30E34A; // 681 -0.509 0.861 +assign wn_re[682] = 32'hxxxxxxxx; assign wn_im[682] = 32'hxxxxxxxx; // 682 -0.504 0.864 +assign wn_re[683] = 32'hxxxxxxxx; assign wn_im[683] = 32'hxxxxxxxx; // 683 -0.498 0.867 +assign wn_re[684] = 32'hC0E8B648; assign wn_im[684] = 32'h6F5F02B2; // 684 -0.493 0.870 +assign wn_re[685] = 32'hxxxxxxxx; assign wn_im[685] = 32'hxxxxxxxx; // 685 -0.488 0.873 +assign wn_re[686] = 32'hxxxxxxxx; assign wn_im[686] = 32'hxxxxxxxx; // 686 -0.482 0.876 +assign wn_re[687] = 32'hC2F83E2A; assign wn_im[687] = 32'h708378FF; // 687 -0.477 0.879 +assign wn_re[688] = 32'hxxxxxxxx; assign wn_im[688] = 32'hxxxxxxxx; // 688 -0.471 0.882 +assign wn_re[689] = 32'hxxxxxxxx; assign wn_im[689] = 32'hxxxxxxxx; // 689 -0.466 0.885 +assign wn_re[690] = 32'hC50D1149; assign wn_im[690] = 32'h719E2CD2; // 690 -0.461 0.888 +assign wn_re[691] = 32'hxxxxxxxx; assign wn_im[691] = 32'hxxxxxxxx; // 691 -0.455 0.890 +assign wn_re[692] = 32'hxxxxxxxx; assign wn_im[692] = 32'hxxxxxxxx; // 692 -0.450 0.893 +assign wn_re[693] = 32'hC727016D; assign wn_im[693] = 32'h72AF05A7; // 693 -0.444 0.896 +assign wn_re[694] = 32'hxxxxxxxx; assign wn_im[694] = 32'hxxxxxxxx; // 694 -0.439 0.899 +assign wn_re[695] = 32'hxxxxxxxx; assign wn_im[695] = 32'hxxxxxxxx; // 695 -0.433 0.901 +assign wn_re[696] = 32'hC945DFEC; assign wn_im[696] = 32'h73B5EBD1; // 696 -0.428 0.904 +assign wn_re[697] = 32'hxxxxxxxx; assign wn_im[697] = 32'hxxxxxxxx; // 697 -0.422 0.907 +assign wn_re[698] = 32'hxxxxxxxx; assign wn_im[698] = 32'hxxxxxxxx; // 698 -0.416 0.909 +assign wn_re[699] = 32'hCB697DB0; assign wn_im[699] = 32'h74B2C884; // 699 -0.411 0.912 +assign wn_re[700] = 32'hxxxxxxxx; assign wn_im[700] = 32'hxxxxxxxx; // 700 -0.405 0.914 +assign wn_re[701] = 32'hxxxxxxxx; assign wn_im[701] = 32'hxxxxxxxx; // 701 -0.400 0.917 +assign wn_re[702] = 32'hCD91AB39; assign wn_im[702] = 32'h75A585CF; // 702 -0.394 0.919 +assign wn_re[703] = 32'hxxxxxxxx; assign wn_im[703] = 32'hxxxxxxxx; // 703 -0.388 0.922 +assign wn_re[704] = 32'hxxxxxxxx; assign wn_im[704] = 32'hxxxxxxxx; // 704 -0.383 0.924 +assign wn_re[705] = 32'hCFBE389F; assign wn_im[705] = 32'h768E0EA6; // 705 -0.377 0.926 +assign wn_re[706] = 32'hxxxxxxxx; assign wn_im[706] = 32'hxxxxxxxx; // 706 -0.371 0.929 +assign wn_re[707] = 32'hxxxxxxxx; assign wn_im[707] = 32'hxxxxxxxx; // 707 -0.366 0.931 +assign wn_re[708] = 32'hD1EEF59E; assign wn_im[708] = 32'h776C4EDB; // 708 -0.360 0.933 +assign wn_re[709] = 32'hxxxxxxxx; assign wn_im[709] = 32'hxxxxxxxx; // 709 -0.354 0.935 +assign wn_re[710] = 32'hxxxxxxxx; assign wn_im[710] = 32'hxxxxxxxx; // 710 -0.348 0.937 +assign wn_re[711] = 32'hD423B191; assign wn_im[711] = 32'h78403329; // 711 -0.343 0.939 +assign wn_re[712] = 32'hxxxxxxxx; assign wn_im[712] = 32'hxxxxxxxx; // 712 -0.337 0.942 +assign wn_re[713] = 32'hxxxxxxxx; assign wn_im[713] = 32'hxxxxxxxx; // 713 -0.331 0.944 +assign wn_re[714] = 32'hD65C3B7B; assign wn_im[714] = 32'h7909A92D; // 714 -0.325 0.946 +assign wn_re[715] = 32'hxxxxxxxx; assign wn_im[715] = 32'hxxxxxxxx; // 715 -0.320 0.948 +assign wn_re[716] = 32'hxxxxxxxx; assign wn_im[716] = 32'hxxxxxxxx; // 716 -0.314 0.950 +assign wn_re[717] = 32'hD898620C; assign wn_im[717] = 32'h79C89F6E; // 717 -0.308 0.951 +assign wn_re[718] = 32'hxxxxxxxx; assign wn_im[718] = 32'hxxxxxxxx; // 718 -0.302 0.953 +assign wn_re[719] = 32'hxxxxxxxx; assign wn_im[719] = 32'hxxxxxxxx; // 719 -0.296 0.955 +assign wn_re[720] = 32'hDAD7F3A2; assign wn_im[720] = 32'h7A7D055B; // 720 -0.290 0.957 +assign wn_re[721] = 32'hxxxxxxxx; assign wn_im[721] = 32'hxxxxxxxx; // 721 -0.284 0.959 +assign wn_re[722] = 32'hxxxxxxxx; assign wn_im[722] = 32'hxxxxxxxx; // 722 -0.279 0.960 +assign wn_re[723] = 32'hDD1ABE51; assign wn_im[723] = 32'h7B26CB4F; // 723 -0.273 0.962 +assign wn_re[724] = 32'hxxxxxxxx; assign wn_im[724] = 32'hxxxxxxxx; // 724 -0.267 0.964 +assign wn_re[725] = 32'hxxxxxxxx; assign wn_im[725] = 32'hxxxxxxxx; // 725 -0.261 0.965 +assign wn_re[726] = 32'hDF608FE4; assign wn_im[726] = 32'h7BC5E290; // 726 -0.255 0.967 +assign wn_re[727] = 32'hxxxxxxxx; assign wn_im[727] = 32'hxxxxxxxx; // 727 -0.249 0.969 +assign wn_re[728] = 32'hxxxxxxxx; assign wn_im[728] = 32'hxxxxxxxx; // 728 -0.243 0.970 +assign wn_re[729] = 32'hE1A935E2; assign wn_im[729] = 32'h7C5A3D50; // 729 -0.237 0.972 +assign wn_re[730] = 32'hxxxxxxxx; assign wn_im[730] = 32'hxxxxxxxx; // 730 -0.231 0.973 +assign wn_re[731] = 32'hxxxxxxxx; assign wn_im[731] = 32'hxxxxxxxx; // 731 -0.225 0.974 +assign wn_re[732] = 32'hE3F47D96; assign wn_im[732] = 32'h7CE3CEB2; // 732 -0.219 0.976 +assign wn_re[733] = 32'hxxxxxxxx; assign wn_im[733] = 32'hxxxxxxxx; // 733 -0.213 0.977 +assign wn_re[734] = 32'hxxxxxxxx; assign wn_im[734] = 32'hxxxxxxxx; // 734 -0.207 0.978 +assign wn_re[735] = 32'hE642340D; assign wn_im[735] = 32'h7D628AC6; // 735 -0.201 0.980 +assign wn_re[736] = 32'hxxxxxxxx; assign wn_im[736] = 32'hxxxxxxxx; // 736 -0.195 0.981 +assign wn_re[737] = 32'hxxxxxxxx; assign wn_im[737] = 32'hxxxxxxxx; // 737 -0.189 0.982 +assign wn_re[738] = 32'hE8922622; assign wn_im[738] = 32'h7DD6668F; // 738 -0.183 0.983 +assign wn_re[739] = 32'hxxxxxxxx; assign wn_im[739] = 32'hxxxxxxxx; // 739 -0.177 0.984 +assign wn_re[740] = 32'hxxxxxxxx; assign wn_im[740] = 32'hxxxxxxxx; // 740 -0.171 0.985 +assign wn_re[741] = 32'hEAE4207A; assign wn_im[741] = 32'h7E3F57FF; // 741 -0.165 0.986 +assign wn_re[742] = 32'hxxxxxxxx; assign wn_im[742] = 32'hxxxxxxxx; // 742 -0.159 0.987 +assign wn_re[743] = 32'hxxxxxxxx; assign wn_im[743] = 32'hxxxxxxxx; // 743 -0.153 0.988 +assign wn_re[744] = 32'hED37EF91; assign wn_im[744] = 32'h7E9D55FC; // 744 -0.147 0.989 +assign wn_re[745] = 32'hxxxxxxxx; assign wn_im[745] = 32'hxxxxxxxx; // 745 -0.141 0.990 +assign wn_re[746] = 32'hxxxxxxxx; assign wn_im[746] = 32'hxxxxxxxx; // 746 -0.135 0.991 +assign wn_re[747] = 32'hEF8D5FB8; assign wn_im[747] = 32'h7EF05860; // 747 -0.128 0.992 +assign wn_re[748] = 32'hxxxxxxxx; assign wn_im[748] = 32'hxxxxxxxx; // 748 -0.122 0.992 +assign wn_re[749] = 32'hxxxxxxxx; assign wn_im[749] = 32'hxxxxxxxx; // 749 -0.116 0.993 +assign wn_re[750] = 32'hF1E43D1C; assign wn_im[750] = 32'h7F3857F6; // 750 -0.110 0.994 +assign wn_re[751] = 32'hxxxxxxxx; assign wn_im[751] = 32'hxxxxxxxx; // 751 -0.104 0.995 +assign wn_re[752] = 32'hxxxxxxxx; assign wn_im[752] = 32'hxxxxxxxx; // 752 -0.098 0.995 +assign wn_re[753] = 32'hF43C53CB; assign wn_im[753] = 32'h7F754E80; // 753 -0.092 0.996 +assign wn_re[754] = 32'hxxxxxxxx; assign wn_im[754] = 32'hxxxxxxxx; // 754 -0.086 0.996 +assign wn_re[755] = 32'hxxxxxxxx; assign wn_im[755] = 32'hxxxxxxxx; // 755 -0.080 0.997 +assign wn_re[756] = 32'hF6956FB7; assign wn_im[756] = 32'h7FA736B4; // 756 -0.074 0.997 +assign wn_re[757] = 32'hxxxxxxxx; assign wn_im[757] = 32'hxxxxxxxx; // 757 -0.067 0.998 +assign wn_re[758] = 32'hxxxxxxxx; assign wn_im[758] = 32'hxxxxxxxx; // 758 -0.061 0.998 +assign wn_re[759] = 32'hF8EF5CBB; assign wn_im[759] = 32'h7FCE0C3E; // 759 -0.055 0.998 +assign wn_re[760] = 32'hxxxxxxxx; assign wn_im[760] = 32'hxxxxxxxx; // 760 -0.049 0.999 +assign wn_re[761] = 32'hxxxxxxxx; assign wn_im[761] = 32'hxxxxxxxx; // 761 -0.043 0.999 +assign wn_re[762] = 32'hFB49E6A3; assign wn_im[762] = 32'h7FE9CBC0; // 762 -0.037 0.999 +assign wn_re[763] = 32'hxxxxxxxx; assign wn_im[763] = 32'hxxxxxxxx; // 763 -0.031 1.000 +assign wn_re[764] = 32'hxxxxxxxx; assign wn_im[764] = 32'hxxxxxxxx; // 764 -0.025 1.000 +assign wn_re[765] = 32'hFDA4D929; assign wn_im[765] = 32'h7FFA72D1; // 765 -0.018 1.000 +assign wn_re[766] = 32'hxxxxxxxx; assign wn_im[766] = 32'hxxxxxxxx; // 766 -0.012 1.000 +assign wn_re[767] = 32'hxxxxxxxx; assign wn_im[767] = 32'hxxxxxxxx; // 767 -0.006 1.000 +assign wn_re[768] = 32'hxxxxxxxx; assign wn_im[768] = 32'hxxxxxxxx; // 768 -0.000 1.000 +assign wn_re[769] = 32'hxxxxxxxx; assign wn_im[769] = 32'hxxxxxxxx; // 769 0.006 1.000 +assign wn_re[770] = 32'hxxxxxxxx; assign wn_im[770] = 32'hxxxxxxxx; // 770 0.012 1.000 +assign wn_re[771] = 32'hxxxxxxxx; assign wn_im[771] = 32'hxxxxxxxx; // 771 0.018 1.000 +assign wn_re[772] = 32'hxxxxxxxx; assign wn_im[772] = 32'hxxxxxxxx; // 772 0.025 1.000 +assign wn_re[773] = 32'hxxxxxxxx; assign wn_im[773] = 32'hxxxxxxxx; // 773 0.031 1.000 +assign wn_re[774] = 32'hxxxxxxxx; assign wn_im[774] = 32'hxxxxxxxx; // 774 0.037 0.999 +assign wn_re[775] = 32'hxxxxxxxx; assign wn_im[775] = 32'hxxxxxxxx; // 775 0.043 0.999 +assign wn_re[776] = 32'hxxxxxxxx; assign wn_im[776] = 32'hxxxxxxxx; // 776 0.049 0.999 +assign wn_re[777] = 32'hxxxxxxxx; assign wn_im[777] = 32'hxxxxxxxx; // 777 0.055 0.998 +assign wn_re[778] = 32'hxxxxxxxx; assign wn_im[778] = 32'hxxxxxxxx; // 778 0.061 0.998 +assign wn_re[779] = 32'hxxxxxxxx; assign wn_im[779] = 32'hxxxxxxxx; // 779 0.067 0.998 +assign wn_re[780] = 32'hxxxxxxxx; assign wn_im[780] = 32'hxxxxxxxx; // 780 0.074 0.997 +assign wn_re[781] = 32'hxxxxxxxx; assign wn_im[781] = 32'hxxxxxxxx; // 781 0.080 0.997 +assign wn_re[782] = 32'hxxxxxxxx; assign wn_im[782] = 32'hxxxxxxxx; // 782 0.086 0.996 +assign wn_re[783] = 32'hxxxxxxxx; assign wn_im[783] = 32'hxxxxxxxx; // 783 0.092 0.996 +assign wn_re[784] = 32'hxxxxxxxx; assign wn_im[784] = 32'hxxxxxxxx; // 784 0.098 0.995 +assign wn_re[785] = 32'hxxxxxxxx; assign wn_im[785] = 32'hxxxxxxxx; // 785 0.104 0.995 +assign wn_re[786] = 32'hxxxxxxxx; assign wn_im[786] = 32'hxxxxxxxx; // 786 0.110 0.994 +assign wn_re[787] = 32'hxxxxxxxx; assign wn_im[787] = 32'hxxxxxxxx; // 787 0.116 0.993 +assign wn_re[788] = 32'hxxxxxxxx; assign wn_im[788] = 32'hxxxxxxxx; // 788 0.122 0.992 +assign wn_re[789] = 32'hxxxxxxxx; assign wn_im[789] = 32'hxxxxxxxx; // 789 0.128 0.992 +assign wn_re[790] = 32'hxxxxxxxx; assign wn_im[790] = 32'hxxxxxxxx; // 790 0.135 0.991 +assign wn_re[791] = 32'hxxxxxxxx; assign wn_im[791] = 32'hxxxxxxxx; // 791 0.141 0.990 +assign wn_re[792] = 32'hxxxxxxxx; assign wn_im[792] = 32'hxxxxxxxx; // 792 0.147 0.989 +assign wn_re[793] = 32'hxxxxxxxx; assign wn_im[793] = 32'hxxxxxxxx; // 793 0.153 0.988 +assign wn_re[794] = 32'hxxxxxxxx; assign wn_im[794] = 32'hxxxxxxxx; // 794 0.159 0.987 +assign wn_re[795] = 32'hxxxxxxxx; assign wn_im[795] = 32'hxxxxxxxx; // 795 0.165 0.986 +assign wn_re[796] = 32'hxxxxxxxx; assign wn_im[796] = 32'hxxxxxxxx; // 796 0.171 0.985 +assign wn_re[797] = 32'hxxxxxxxx; assign wn_im[797] = 32'hxxxxxxxx; // 797 0.177 0.984 +assign wn_re[798] = 32'hxxxxxxxx; assign wn_im[798] = 32'hxxxxxxxx; // 798 0.183 0.983 +assign wn_re[799] = 32'hxxxxxxxx; assign wn_im[799] = 32'hxxxxxxxx; // 799 0.189 0.982 +assign wn_re[800] = 32'hxxxxxxxx; assign wn_im[800] = 32'hxxxxxxxx; // 800 0.195 0.981 +assign wn_re[801] = 32'hxxxxxxxx; assign wn_im[801] = 32'hxxxxxxxx; // 801 0.201 0.980 +assign wn_re[802] = 32'hxxxxxxxx; assign wn_im[802] = 32'hxxxxxxxx; // 802 0.207 0.978 +assign wn_re[803] = 32'hxxxxxxxx; assign wn_im[803] = 32'hxxxxxxxx; // 803 0.213 0.977 +assign wn_re[804] = 32'hxxxxxxxx; assign wn_im[804] = 32'hxxxxxxxx; // 804 0.219 0.976 +assign wn_re[805] = 32'hxxxxxxxx; assign wn_im[805] = 32'hxxxxxxxx; // 805 0.225 0.974 +assign wn_re[806] = 32'hxxxxxxxx; assign wn_im[806] = 32'hxxxxxxxx; // 806 0.231 0.973 +assign wn_re[807] = 32'hxxxxxxxx; assign wn_im[807] = 32'hxxxxxxxx; // 807 0.237 0.972 +assign wn_re[808] = 32'hxxxxxxxx; assign wn_im[808] = 32'hxxxxxxxx; // 808 0.243 0.970 +assign wn_re[809] = 32'hxxxxxxxx; assign wn_im[809] = 32'hxxxxxxxx; // 809 0.249 0.969 +assign wn_re[810] = 32'hxxxxxxxx; assign wn_im[810] = 32'hxxxxxxxx; // 810 0.255 0.967 +assign wn_re[811] = 32'hxxxxxxxx; assign wn_im[811] = 32'hxxxxxxxx; // 811 0.261 0.965 +assign wn_re[812] = 32'hxxxxxxxx; assign wn_im[812] = 32'hxxxxxxxx; // 812 0.267 0.964 +assign wn_re[813] = 32'hxxxxxxxx; assign wn_im[813] = 32'hxxxxxxxx; // 813 0.273 0.962 +assign wn_re[814] = 32'hxxxxxxxx; assign wn_im[814] = 32'hxxxxxxxx; // 814 0.279 0.960 +assign wn_re[815] = 32'hxxxxxxxx; assign wn_im[815] = 32'hxxxxxxxx; // 815 0.284 0.959 +assign wn_re[816] = 32'hxxxxxxxx; assign wn_im[816] = 32'hxxxxxxxx; // 816 0.290 0.957 +assign wn_re[817] = 32'hxxxxxxxx; assign wn_im[817] = 32'hxxxxxxxx; // 817 0.296 0.955 +assign wn_re[818] = 32'hxxxxxxxx; assign wn_im[818] = 32'hxxxxxxxx; // 818 0.302 0.953 +assign wn_re[819] = 32'hxxxxxxxx; assign wn_im[819] = 32'hxxxxxxxx; // 819 0.308 0.951 +assign wn_re[820] = 32'hxxxxxxxx; assign wn_im[820] = 32'hxxxxxxxx; // 820 0.314 0.950 +assign wn_re[821] = 32'hxxxxxxxx; assign wn_im[821] = 32'hxxxxxxxx; // 821 0.320 0.948 +assign wn_re[822] = 32'hxxxxxxxx; assign wn_im[822] = 32'hxxxxxxxx; // 822 0.325 0.946 +assign wn_re[823] = 32'hxxxxxxxx; assign wn_im[823] = 32'hxxxxxxxx; // 823 0.331 0.944 +assign wn_re[824] = 32'hxxxxxxxx; assign wn_im[824] = 32'hxxxxxxxx; // 824 0.337 0.942 +assign wn_re[825] = 32'hxxxxxxxx; assign wn_im[825] = 32'hxxxxxxxx; // 825 0.343 0.939 +assign wn_re[826] = 32'hxxxxxxxx; assign wn_im[826] = 32'hxxxxxxxx; // 826 0.348 0.937 +assign wn_re[827] = 32'hxxxxxxxx; assign wn_im[827] = 32'hxxxxxxxx; // 827 0.354 0.935 +assign wn_re[828] = 32'hxxxxxxxx; assign wn_im[828] = 32'hxxxxxxxx; // 828 0.360 0.933 +assign wn_re[829] = 32'hxxxxxxxx; assign wn_im[829] = 32'hxxxxxxxx; // 829 0.366 0.931 +assign wn_re[830] = 32'hxxxxxxxx; assign wn_im[830] = 32'hxxxxxxxx; // 830 0.371 0.929 +assign wn_re[831] = 32'hxxxxxxxx; assign wn_im[831] = 32'hxxxxxxxx; // 831 0.377 0.926 +assign wn_re[832] = 32'hxxxxxxxx; assign wn_im[832] = 32'hxxxxxxxx; // 832 0.383 0.924 +assign wn_re[833] = 32'hxxxxxxxx; assign wn_im[833] = 32'hxxxxxxxx; // 833 0.388 0.922 +assign wn_re[834] = 32'hxxxxxxxx; assign wn_im[834] = 32'hxxxxxxxx; // 834 0.394 0.919 +assign wn_re[835] = 32'hxxxxxxxx; assign wn_im[835] = 32'hxxxxxxxx; // 835 0.400 0.917 +assign wn_re[836] = 32'hxxxxxxxx; assign wn_im[836] = 32'hxxxxxxxx; // 836 0.405 0.914 +assign wn_re[837] = 32'hxxxxxxxx; assign wn_im[837] = 32'hxxxxxxxx; // 837 0.411 0.912 +assign wn_re[838] = 32'hxxxxxxxx; assign wn_im[838] = 32'hxxxxxxxx; // 838 0.416 0.909 +assign wn_re[839] = 32'hxxxxxxxx; assign wn_im[839] = 32'hxxxxxxxx; // 839 0.422 0.907 +assign wn_re[840] = 32'hxxxxxxxx; assign wn_im[840] = 32'hxxxxxxxx; // 840 0.428 0.904 +assign wn_re[841] = 32'hxxxxxxxx; assign wn_im[841] = 32'hxxxxxxxx; // 841 0.433 0.901 +assign wn_re[842] = 32'hxxxxxxxx; assign wn_im[842] = 32'hxxxxxxxx; // 842 0.439 0.899 +assign wn_re[843] = 32'hxxxxxxxx; assign wn_im[843] = 32'hxxxxxxxx; // 843 0.444 0.896 +assign wn_re[844] = 32'hxxxxxxxx; assign wn_im[844] = 32'hxxxxxxxx; // 844 0.450 0.893 +assign wn_re[845] = 32'hxxxxxxxx; assign wn_im[845] = 32'hxxxxxxxx; // 845 0.455 0.890 +assign wn_re[846] = 32'hxxxxxxxx; assign wn_im[846] = 32'hxxxxxxxx; // 846 0.461 0.888 +assign wn_re[847] = 32'hxxxxxxxx; assign wn_im[847] = 32'hxxxxxxxx; // 847 0.466 0.885 +assign wn_re[848] = 32'hxxxxxxxx; assign wn_im[848] = 32'hxxxxxxxx; // 848 0.471 0.882 +assign wn_re[849] = 32'hxxxxxxxx; assign wn_im[849] = 32'hxxxxxxxx; // 849 0.477 0.879 +assign wn_re[850] = 32'hxxxxxxxx; assign wn_im[850] = 32'hxxxxxxxx; // 850 0.482 0.876 +assign wn_re[851] = 32'hxxxxxxxx; assign wn_im[851] = 32'hxxxxxxxx; // 851 0.488 0.873 +assign wn_re[852] = 32'hxxxxxxxx; assign wn_im[852] = 32'hxxxxxxxx; // 852 0.493 0.870 +assign wn_re[853] = 32'hxxxxxxxx; assign wn_im[853] = 32'hxxxxxxxx; // 853 0.498 0.867 +assign wn_re[854] = 32'hxxxxxxxx; assign wn_im[854] = 32'hxxxxxxxx; // 854 0.504 0.864 +assign wn_re[855] = 32'hxxxxxxxx; assign wn_im[855] = 32'hxxxxxxxx; // 855 0.509 0.861 +assign wn_re[856] = 32'hxxxxxxxx; assign wn_im[856] = 32'hxxxxxxxx; // 856 0.514 0.858 +assign wn_re[857] = 32'hxxxxxxxx; assign wn_im[857] = 32'hxxxxxxxx; // 857 0.519 0.855 +assign wn_re[858] = 32'hxxxxxxxx; assign wn_im[858] = 32'hxxxxxxxx; // 858 0.525 0.851 +assign wn_re[859] = 32'hxxxxxxxx; assign wn_im[859] = 32'hxxxxxxxx; // 859 0.530 0.848 +assign wn_re[860] = 32'hxxxxxxxx; assign wn_im[860] = 32'hxxxxxxxx; // 860 0.535 0.845 +assign wn_re[861] = 32'hxxxxxxxx; assign wn_im[861] = 32'hxxxxxxxx; // 861 0.540 0.842 +assign wn_re[862] = 32'hxxxxxxxx; assign wn_im[862] = 32'hxxxxxxxx; // 862 0.545 0.838 +assign wn_re[863] = 32'hxxxxxxxx; assign wn_im[863] = 32'hxxxxxxxx; // 863 0.550 0.835 +assign wn_re[864] = 32'hxxxxxxxx; assign wn_im[864] = 32'hxxxxxxxx; // 864 0.556 0.831 +assign wn_re[865] = 32'hxxxxxxxx; assign wn_im[865] = 32'hxxxxxxxx; // 865 0.561 0.828 +assign wn_re[866] = 32'hxxxxxxxx; assign wn_im[866] = 32'hxxxxxxxx; // 866 0.566 0.825 +assign wn_re[867] = 32'hxxxxxxxx; assign wn_im[867] = 32'hxxxxxxxx; // 867 0.571 0.821 +assign wn_re[868] = 32'hxxxxxxxx; assign wn_im[868] = 32'hxxxxxxxx; // 868 0.576 0.818 +assign wn_re[869] = 32'hxxxxxxxx; assign wn_im[869] = 32'hxxxxxxxx; // 869 0.581 0.814 +assign wn_re[870] = 32'hxxxxxxxx; assign wn_im[870] = 32'hxxxxxxxx; // 870 0.586 0.810 +assign wn_re[871] = 32'hxxxxxxxx; assign wn_im[871] = 32'hxxxxxxxx; // 871 0.591 0.807 +assign wn_re[872] = 32'hxxxxxxxx; assign wn_im[872] = 32'hxxxxxxxx; // 872 0.596 0.803 +assign wn_re[873] = 32'hxxxxxxxx; assign wn_im[873] = 32'hxxxxxxxx; // 873 0.601 0.800 +assign wn_re[874] = 32'hxxxxxxxx; assign wn_im[874] = 32'hxxxxxxxx; // 874 0.606 0.796 +assign wn_re[875] = 32'hxxxxxxxx; assign wn_im[875] = 32'hxxxxxxxx; // 875 0.610 0.792 +assign wn_re[876] = 32'hxxxxxxxx; assign wn_im[876] = 32'hxxxxxxxx; // 876 0.615 0.788 +assign wn_re[877] = 32'hxxxxxxxx; assign wn_im[877] = 32'hxxxxxxxx; // 877 0.620 0.785 +assign wn_re[878] = 32'hxxxxxxxx; assign wn_im[878] = 32'hxxxxxxxx; // 878 0.625 0.781 +assign wn_re[879] = 32'hxxxxxxxx; assign wn_im[879] = 32'hxxxxxxxx; // 879 0.630 0.777 +assign wn_re[880] = 32'hxxxxxxxx; assign wn_im[880] = 32'hxxxxxxxx; // 880 0.634 0.773 +assign wn_re[881] = 32'hxxxxxxxx; assign wn_im[881] = 32'hxxxxxxxx; // 881 0.639 0.769 +assign wn_re[882] = 32'hxxxxxxxx; assign wn_im[882] = 32'hxxxxxxxx; // 882 0.644 0.765 +assign wn_re[883] = 32'hxxxxxxxx; assign wn_im[883] = 32'hxxxxxxxx; // 883 0.649 0.761 +assign wn_re[884] = 32'hxxxxxxxx; assign wn_im[884] = 32'hxxxxxxxx; // 884 0.653 0.757 +assign wn_re[885] = 32'hxxxxxxxx; assign wn_im[885] = 32'hxxxxxxxx; // 885 0.658 0.753 +assign wn_re[886] = 32'hxxxxxxxx; assign wn_im[886] = 32'hxxxxxxxx; // 886 0.662 0.749 +assign wn_re[887] = 32'hxxxxxxxx; assign wn_im[887] = 32'hxxxxxxxx; // 887 0.667 0.745 +assign wn_re[888] = 32'hxxxxxxxx; assign wn_im[888] = 32'hxxxxxxxx; // 888 0.672 0.741 +assign wn_re[889] = 32'hxxxxxxxx; assign wn_im[889] = 32'hxxxxxxxx; // 889 0.676 0.737 +assign wn_re[890] = 32'hxxxxxxxx; assign wn_im[890] = 32'hxxxxxxxx; // 890 0.681 0.733 +assign wn_re[891] = 32'hxxxxxxxx; assign wn_im[891] = 32'hxxxxxxxx; // 891 0.685 0.728 +assign wn_re[892] = 32'hxxxxxxxx; assign wn_im[892] = 32'hxxxxxxxx; // 892 0.690 0.724 +assign wn_re[893] = 32'hxxxxxxxx; assign wn_im[893] = 32'hxxxxxxxx; // 893 0.694 0.720 +assign wn_re[894] = 32'hxxxxxxxx; assign wn_im[894] = 32'hxxxxxxxx; // 894 0.698 0.716 +assign wn_re[895] = 32'hxxxxxxxx; assign wn_im[895] = 32'hxxxxxxxx; // 895 0.703 0.711 +assign wn_re[896] = 32'hxxxxxxxx; assign wn_im[896] = 32'hxxxxxxxx; // 896 0.707 0.707 +assign wn_re[897] = 32'hxxxxxxxx; assign wn_im[897] = 32'hxxxxxxxx; // 897 0.711 0.703 +assign wn_re[898] = 32'hxxxxxxxx; assign wn_im[898] = 32'hxxxxxxxx; // 898 0.716 0.698 +assign wn_re[899] = 32'hxxxxxxxx; assign wn_im[899] = 32'hxxxxxxxx; // 899 0.720 0.694 +assign wn_re[900] = 32'hxxxxxxxx; assign wn_im[900] = 32'hxxxxxxxx; // 900 0.724 0.690 +assign wn_re[901] = 32'hxxxxxxxx; assign wn_im[901] = 32'hxxxxxxxx; // 901 0.728 0.685 +assign wn_re[902] = 32'hxxxxxxxx; assign wn_im[902] = 32'hxxxxxxxx; // 902 0.733 0.681 +assign wn_re[903] = 32'hxxxxxxxx; assign wn_im[903] = 32'hxxxxxxxx; // 903 0.737 0.676 +assign wn_re[904] = 32'hxxxxxxxx; assign wn_im[904] = 32'hxxxxxxxx; // 904 0.741 0.672 +assign wn_re[905] = 32'hxxxxxxxx; assign wn_im[905] = 32'hxxxxxxxx; // 905 0.745 0.667 +assign wn_re[906] = 32'hxxxxxxxx; assign wn_im[906] = 32'hxxxxxxxx; // 906 0.749 0.662 +assign wn_re[907] = 32'hxxxxxxxx; assign wn_im[907] = 32'hxxxxxxxx; // 907 0.753 0.658 +assign wn_re[908] = 32'hxxxxxxxx; assign wn_im[908] = 32'hxxxxxxxx; // 908 0.757 0.653 +assign wn_re[909] = 32'hxxxxxxxx; assign wn_im[909] = 32'hxxxxxxxx; // 909 0.761 0.649 +assign wn_re[910] = 32'hxxxxxxxx; assign wn_im[910] = 32'hxxxxxxxx; // 910 0.765 0.644 +assign wn_re[911] = 32'hxxxxxxxx; assign wn_im[911] = 32'hxxxxxxxx; // 911 0.769 0.639 +assign wn_re[912] = 32'hxxxxxxxx; assign wn_im[912] = 32'hxxxxxxxx; // 912 0.773 0.634 +assign wn_re[913] = 32'hxxxxxxxx; assign wn_im[913] = 32'hxxxxxxxx; // 913 0.777 0.630 +assign wn_re[914] = 32'hxxxxxxxx; assign wn_im[914] = 32'hxxxxxxxx; // 914 0.781 0.625 +assign wn_re[915] = 32'hxxxxxxxx; assign wn_im[915] = 32'hxxxxxxxx; // 915 0.785 0.620 +assign wn_re[916] = 32'hxxxxxxxx; assign wn_im[916] = 32'hxxxxxxxx; // 916 0.788 0.615 +assign wn_re[917] = 32'hxxxxxxxx; assign wn_im[917] = 32'hxxxxxxxx; // 917 0.792 0.610 +assign wn_re[918] = 32'hxxxxxxxx; assign wn_im[918] = 32'hxxxxxxxx; // 918 0.796 0.606 +assign wn_re[919] = 32'hxxxxxxxx; assign wn_im[919] = 32'hxxxxxxxx; // 919 0.800 0.601 +assign wn_re[920] = 32'hxxxxxxxx; assign wn_im[920] = 32'hxxxxxxxx; // 920 0.803 0.596 +assign wn_re[921] = 32'hxxxxxxxx; assign wn_im[921] = 32'hxxxxxxxx; // 921 0.807 0.591 +assign wn_re[922] = 32'hxxxxxxxx; assign wn_im[922] = 32'hxxxxxxxx; // 922 0.810 0.586 +assign wn_re[923] = 32'hxxxxxxxx; assign wn_im[923] = 32'hxxxxxxxx; // 923 0.814 0.581 +assign wn_re[924] = 32'hxxxxxxxx; assign wn_im[924] = 32'hxxxxxxxx; // 924 0.818 0.576 +assign wn_re[925] = 32'hxxxxxxxx; assign wn_im[925] = 32'hxxxxxxxx; // 925 0.821 0.571 +assign wn_re[926] = 32'hxxxxxxxx; assign wn_im[926] = 32'hxxxxxxxx; // 926 0.825 0.566 +assign wn_re[927] = 32'hxxxxxxxx; assign wn_im[927] = 32'hxxxxxxxx; // 927 0.828 0.561 +assign wn_re[928] = 32'hxxxxxxxx; assign wn_im[928] = 32'hxxxxxxxx; // 928 0.831 0.556 +assign wn_re[929] = 32'hxxxxxxxx; assign wn_im[929] = 32'hxxxxxxxx; // 929 0.835 0.550 +assign wn_re[930] = 32'hxxxxxxxx; assign wn_im[930] = 32'hxxxxxxxx; // 930 0.838 0.545 +assign wn_re[931] = 32'hxxxxxxxx; assign wn_im[931] = 32'hxxxxxxxx; // 931 0.842 0.540 +assign wn_re[932] = 32'hxxxxxxxx; assign wn_im[932] = 32'hxxxxxxxx; // 932 0.845 0.535 +assign wn_re[933] = 32'hxxxxxxxx; assign wn_im[933] = 32'hxxxxxxxx; // 933 0.848 0.530 +assign wn_re[934] = 32'hxxxxxxxx; assign wn_im[934] = 32'hxxxxxxxx; // 934 0.851 0.525 +assign wn_re[935] = 32'hxxxxxxxx; assign wn_im[935] = 32'hxxxxxxxx; // 935 0.855 0.519 +assign wn_re[936] = 32'hxxxxxxxx; assign wn_im[936] = 32'hxxxxxxxx; // 936 0.858 0.514 +assign wn_re[937] = 32'hxxxxxxxx; assign wn_im[937] = 32'hxxxxxxxx; // 937 0.861 0.509 +assign wn_re[938] = 32'hxxxxxxxx; assign wn_im[938] = 32'hxxxxxxxx; // 938 0.864 0.504 +assign wn_re[939] = 32'hxxxxxxxx; assign wn_im[939] = 32'hxxxxxxxx; // 939 0.867 0.498 +assign wn_re[940] = 32'hxxxxxxxx; assign wn_im[940] = 32'hxxxxxxxx; // 940 0.870 0.493 +assign wn_re[941] = 32'hxxxxxxxx; assign wn_im[941] = 32'hxxxxxxxx; // 941 0.873 0.488 +assign wn_re[942] = 32'hxxxxxxxx; assign wn_im[942] = 32'hxxxxxxxx; // 942 0.876 0.482 +assign wn_re[943] = 32'hxxxxxxxx; assign wn_im[943] = 32'hxxxxxxxx; // 943 0.879 0.477 +assign wn_re[944] = 32'hxxxxxxxx; assign wn_im[944] = 32'hxxxxxxxx; // 944 0.882 0.471 +assign wn_re[945] = 32'hxxxxxxxx; assign wn_im[945] = 32'hxxxxxxxx; // 945 0.885 0.466 +assign wn_re[946] = 32'hxxxxxxxx; assign wn_im[946] = 32'hxxxxxxxx; // 946 0.888 0.461 +assign wn_re[947] = 32'hxxxxxxxx; assign wn_im[947] = 32'hxxxxxxxx; // 947 0.890 0.455 +assign wn_re[948] = 32'hxxxxxxxx; assign wn_im[948] = 32'hxxxxxxxx; // 948 0.893 0.450 +assign wn_re[949] = 32'hxxxxxxxx; assign wn_im[949] = 32'hxxxxxxxx; // 949 0.896 0.444 +assign wn_re[950] = 32'hxxxxxxxx; assign wn_im[950] = 32'hxxxxxxxx; // 950 0.899 0.439 +assign wn_re[951] = 32'hxxxxxxxx; assign wn_im[951] = 32'hxxxxxxxx; // 951 0.901 0.433 +assign wn_re[952] = 32'hxxxxxxxx; assign wn_im[952] = 32'hxxxxxxxx; // 952 0.904 0.428 +assign wn_re[953] = 32'hxxxxxxxx; assign wn_im[953] = 32'hxxxxxxxx; // 953 0.907 0.422 +assign wn_re[954] = 32'hxxxxxxxx; assign wn_im[954] = 32'hxxxxxxxx; // 954 0.909 0.416 +assign wn_re[955] = 32'hxxxxxxxx; assign wn_im[955] = 32'hxxxxxxxx; // 955 0.912 0.411 +assign wn_re[956] = 32'hxxxxxxxx; assign wn_im[956] = 32'hxxxxxxxx; // 956 0.914 0.405 +assign wn_re[957] = 32'hxxxxxxxx; assign wn_im[957] = 32'hxxxxxxxx; // 957 0.917 0.400 +assign wn_re[958] = 32'hxxxxxxxx; assign wn_im[958] = 32'hxxxxxxxx; // 958 0.919 0.394 +assign wn_re[959] = 32'hxxxxxxxx; assign wn_im[959] = 32'hxxxxxxxx; // 959 0.922 0.388 +assign wn_re[960] = 32'hxxxxxxxx; assign wn_im[960] = 32'hxxxxxxxx; // 960 0.924 0.383 +assign wn_re[961] = 32'hxxxxxxxx; assign wn_im[961] = 32'hxxxxxxxx; // 961 0.926 0.377 +assign wn_re[962] = 32'hxxxxxxxx; assign wn_im[962] = 32'hxxxxxxxx; // 962 0.929 0.371 +assign wn_re[963] = 32'hxxxxxxxx; assign wn_im[963] = 32'hxxxxxxxx; // 963 0.931 0.366 +assign wn_re[964] = 32'hxxxxxxxx; assign wn_im[964] = 32'hxxxxxxxx; // 964 0.933 0.360 +assign wn_re[965] = 32'hxxxxxxxx; assign wn_im[965] = 32'hxxxxxxxx; // 965 0.935 0.354 +assign wn_re[966] = 32'hxxxxxxxx; assign wn_im[966] = 32'hxxxxxxxx; // 966 0.937 0.348 +assign wn_re[967] = 32'hxxxxxxxx; assign wn_im[967] = 32'hxxxxxxxx; // 967 0.939 0.343 +assign wn_re[968] = 32'hxxxxxxxx; assign wn_im[968] = 32'hxxxxxxxx; // 968 0.942 0.337 +assign wn_re[969] = 32'hxxxxxxxx; assign wn_im[969] = 32'hxxxxxxxx; // 969 0.944 0.331 +assign wn_re[970] = 32'hxxxxxxxx; assign wn_im[970] = 32'hxxxxxxxx; // 970 0.946 0.325 +assign wn_re[971] = 32'hxxxxxxxx; assign wn_im[971] = 32'hxxxxxxxx; // 971 0.948 0.320 +assign wn_re[972] = 32'hxxxxxxxx; assign wn_im[972] = 32'hxxxxxxxx; // 972 0.950 0.314 +assign wn_re[973] = 32'hxxxxxxxx; assign wn_im[973] = 32'hxxxxxxxx; // 973 0.951 0.308 +assign wn_re[974] = 32'hxxxxxxxx; assign wn_im[974] = 32'hxxxxxxxx; // 974 0.953 0.302 +assign wn_re[975] = 32'hxxxxxxxx; assign wn_im[975] = 32'hxxxxxxxx; // 975 0.955 0.296 +assign wn_re[976] = 32'hxxxxxxxx; assign wn_im[976] = 32'hxxxxxxxx; // 976 0.957 0.290 +assign wn_re[977] = 32'hxxxxxxxx; assign wn_im[977] = 32'hxxxxxxxx; // 977 0.959 0.284 +assign wn_re[978] = 32'hxxxxxxxx; assign wn_im[978] = 32'hxxxxxxxx; // 978 0.960 0.279 +assign wn_re[979] = 32'hxxxxxxxx; assign wn_im[979] = 32'hxxxxxxxx; // 979 0.962 0.273 +assign wn_re[980] = 32'hxxxxxxxx; assign wn_im[980] = 32'hxxxxxxxx; // 980 0.964 0.267 +assign wn_re[981] = 32'hxxxxxxxx; assign wn_im[981] = 32'hxxxxxxxx; // 981 0.965 0.261 +assign wn_re[982] = 32'hxxxxxxxx; assign wn_im[982] = 32'hxxxxxxxx; // 982 0.967 0.255 +assign wn_re[983] = 32'hxxxxxxxx; assign wn_im[983] = 32'hxxxxxxxx; // 983 0.969 0.249 +assign wn_re[984] = 32'hxxxxxxxx; assign wn_im[984] = 32'hxxxxxxxx; // 984 0.970 0.243 +assign wn_re[985] = 32'hxxxxxxxx; assign wn_im[985] = 32'hxxxxxxxx; // 985 0.972 0.237 +assign wn_re[986] = 32'hxxxxxxxx; assign wn_im[986] = 32'hxxxxxxxx; // 986 0.973 0.231 +assign wn_re[987] = 32'hxxxxxxxx; assign wn_im[987] = 32'hxxxxxxxx; // 987 0.974 0.225 +assign wn_re[988] = 32'hxxxxxxxx; assign wn_im[988] = 32'hxxxxxxxx; // 988 0.976 0.219 +assign wn_re[989] = 32'hxxxxxxxx; assign wn_im[989] = 32'hxxxxxxxx; // 989 0.977 0.213 +assign wn_re[990] = 32'hxxxxxxxx; assign wn_im[990] = 32'hxxxxxxxx; // 990 0.978 0.207 +assign wn_re[991] = 32'hxxxxxxxx; assign wn_im[991] = 32'hxxxxxxxx; // 991 0.980 0.201 +assign wn_re[992] = 32'hxxxxxxxx; assign wn_im[992] = 32'hxxxxxxxx; // 992 0.981 0.195 +assign wn_re[993] = 32'hxxxxxxxx; assign wn_im[993] = 32'hxxxxxxxx; // 993 0.982 0.189 +assign wn_re[994] = 32'hxxxxxxxx; assign wn_im[994] = 32'hxxxxxxxx; // 994 0.983 0.183 +assign wn_re[995] = 32'hxxxxxxxx; assign wn_im[995] = 32'hxxxxxxxx; // 995 0.984 0.177 +assign wn_re[996] = 32'hxxxxxxxx; assign wn_im[996] = 32'hxxxxxxxx; // 996 0.985 0.171 +assign wn_re[997] = 32'hxxxxxxxx; assign wn_im[997] = 32'hxxxxxxxx; // 997 0.986 0.165 +assign wn_re[998] = 32'hxxxxxxxx; assign wn_im[998] = 32'hxxxxxxxx; // 998 0.987 0.159 +assign wn_re[999] = 32'hxxxxxxxx; assign wn_im[999] = 32'hxxxxxxxx; // 999 0.988 0.153 +assign wn_re[1000] = 32'hxxxxxxxx; assign wn_im[1000] = 32'hxxxxxxxx; // 1000 0.989 0.147 +assign wn_re[1001] = 32'hxxxxxxxx; assign wn_im[1001] = 32'hxxxxxxxx; // 1001 0.990 0.141 +assign wn_re[1002] = 32'hxxxxxxxx; assign wn_im[1002] = 32'hxxxxxxxx; // 1002 0.991 0.135 +assign wn_re[1003] = 32'hxxxxxxxx; assign wn_im[1003] = 32'hxxxxxxxx; // 1003 0.992 0.128 +assign wn_re[1004] = 32'hxxxxxxxx; assign wn_im[1004] = 32'hxxxxxxxx; // 1004 0.992 0.122 +assign wn_re[1005] = 32'hxxxxxxxx; assign wn_im[1005] = 32'hxxxxxxxx; // 1005 0.993 0.116 +assign wn_re[1006] = 32'hxxxxxxxx; assign wn_im[1006] = 32'hxxxxxxxx; // 1006 0.994 0.110 +assign wn_re[1007] = 32'hxxxxxxxx; assign wn_im[1007] = 32'hxxxxxxxx; // 1007 0.995 0.104 +assign wn_re[1008] = 32'hxxxxxxxx; assign wn_im[1008] = 32'hxxxxxxxx; // 1008 0.995 0.098 +assign wn_re[1009] = 32'hxxxxxxxx; assign wn_im[1009] = 32'hxxxxxxxx; // 1009 0.996 0.092 +assign wn_re[1010] = 32'hxxxxxxxx; assign wn_im[1010] = 32'hxxxxxxxx; // 1010 0.996 0.086 +assign wn_re[1011] = 32'hxxxxxxxx; assign wn_im[1011] = 32'hxxxxxxxx; // 1011 0.997 0.080 +assign wn_re[1012] = 32'hxxxxxxxx; assign wn_im[1012] = 32'hxxxxxxxx; // 1012 0.997 0.074 +assign wn_re[1013] = 32'hxxxxxxxx; assign wn_im[1013] = 32'hxxxxxxxx; // 1013 0.998 0.067 +assign wn_re[1014] = 32'hxxxxxxxx; assign wn_im[1014] = 32'hxxxxxxxx; // 1014 0.998 0.061 +assign wn_re[1015] = 32'hxxxxxxxx; assign wn_im[1015] = 32'hxxxxxxxx; // 1015 0.998 0.055 +assign wn_re[1016] = 32'hxxxxxxxx; assign wn_im[1016] = 32'hxxxxxxxx; // 1016 0.999 0.049 +assign wn_re[1017] = 32'hxxxxxxxx; assign wn_im[1017] = 32'hxxxxxxxx; // 1017 0.999 0.043 +assign wn_re[1018] = 32'hxxxxxxxx; assign wn_im[1018] = 32'hxxxxxxxx; // 1018 0.999 0.037 +assign wn_re[1019] = 32'hxxxxxxxx; assign wn_im[1019] = 32'hxxxxxxxx; // 1019 1.000 0.031 +assign wn_re[1020] = 32'hxxxxxxxx; assign wn_im[1020] = 32'hxxxxxxxx; // 1020 1.000 0.025 +assign wn_re[1021] = 32'hxxxxxxxx; assign wn_im[1021] = 32'hxxxxxxxx; // 1021 1.000 0.018 +assign wn_re[1022] = 32'hxxxxxxxx; assign wn_im[1022] = 32'hxxxxxxxx; // 1022 1.000 0.012 +assign wn_re[1023] = 32'hxxxxxxxx; assign wn_im[1023] = 32'hxxxxxxxx; // 1023 1.000 0.006 diff --git a/nanamake_r22sdf/verilog/Butterfly.v b/nanamake_r22sdf/verilog/Butterfly.v new file mode 100644 index 0000000000000000000000000000000000000000..61df7986180c8ec1ec3b931b80129d3e26cd8829 --- /dev/null +++ b/nanamake_r22sdf/verilog/Butterfly.v @@ -0,0 +1,32 @@ +//---------------------------------------------------------------------- +// Butterfly: Add/Sub and Scaling +//---------------------------------------------------------------------- +module Butterfly #( + parameter WIDTH = 16, + parameter RH = 0 // Round Half Up +)( + input signed [WIDTH-1:0] x0_re, // Input Data #0 (Real) + input signed [WIDTH-1:0] x0_im, // Input Data #0 (Imag) + input signed [WIDTH-1:0] x1_re, // Input Data #1 (Real) + input signed [WIDTH-1:0] x1_im, // Input Data #1 (Imag) + output signed [WIDTH-1:0] y0_re, // Output Data #0 (Real) + output signed [WIDTH-1:0] y0_im, // Output Data #0 (Imag) + output signed [WIDTH-1:0] y1_re, // Output Data #1 (Real) + output signed [WIDTH-1:0] y1_im // Output Data #1 (Imag) +); + +wire signed [WIDTH:0] add_re, add_im, sub_re, sub_im; + +// Add/Sub +assign add_re = x0_re + x1_re; +assign add_im = x0_im + x1_im; +assign sub_re = x0_re - x1_re; +assign sub_im = x0_im - x1_im; + +// Scaling +assign y0_re = (add_re + RH) >>> 1; +assign y0_im = (add_im + RH) >>> 1; +assign y1_re = (sub_re + RH) >>> 1; +assign y1_im = (sub_im + RH) >>> 1; + +endmodule diff --git a/nanamake_r22sdf/verilog/DelayBuffer.v b/nanamake_r22sdf/verilog/DelayBuffer.v new file mode 100644 index 0000000000000000000000000000000000000000..19bff722e18864f3630c36b972539adad07c6810 --- /dev/null +++ b/nanamake_r22sdf/verilog/DelayBuffer.v @@ -0,0 +1,32 @@ +//---------------------------------------------------------------------- +// DelayBuffer: Generate Constant Delay +//---------------------------------------------------------------------- +module DelayBuffer #( + parameter DEPTH = 32, + parameter WIDTH = 16 +)( + input clock, // Master Clock + input [WIDTH-1:0] di_re, // Data Input (Real) + input [WIDTH-1:0] di_im, // Data Input (Imag) + output [WIDTH-1:0] do_re, // Data Output (Real) + output [WIDTH-1:0] do_im // Data Output (Imag) +); + +reg [WIDTH-1:0] buf_re[0:DEPTH-1]; +reg [WIDTH-1:0] buf_im[0:DEPTH-1]; +integer n; + +// Shift Buffer +always @(posedge clock) begin + for (n = DEPTH-1; n > 0; n = n - 1) begin + buf_re[n] <= buf_re[n-1]; + buf_im[n] <= buf_im[n-1]; + end + buf_re[0] <= di_re; + buf_im[0] <= di_im; +end + +assign do_re = buf_re[DEPTH-1]; +assign do_im = buf_im[DEPTH-1]; + +endmodule diff --git a/nanamake_r22sdf/verilog/FFT1024_32B.v b/nanamake_r22sdf/verilog/FFT1024_32B.v new file mode 100644 index 0000000000000000000000000000000000000000..2875ebc770f6b2bfde1e15b9f2fd6e74873cffac --- /dev/null +++ b/nanamake_r22sdf/verilog/FFT1024_32B.v @@ -0,0 +1,89 @@ +//---------------------------------------------------------------------- +// FFT: 1024-Point FFT Using Radix-2^2 Single-Path Delay Feedback +//---------------------------------------------------------------------- +module FFT #( + parameter WIDTH = 32 +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) +); +//---------------------------------------------------------------------- +// Data must be input consecutively in natural order. +// The result is scaled to 1/N and output in bit-reversed order. +//---------------------------------------------------------------------- + +wire su1_do_en; +wire[WIDTH-1:0] su1_do_re; +wire[WIDTH-1:0] su1_do_im; +wire su2_do_en; +wire[WIDTH-1:0] su2_do_re; +wire[WIDTH-1:0] su2_do_im; +wire su3_do_en; +wire[WIDTH-1:0] su3_do_re; +wire[WIDTH-1:0] su3_do_im; +wire su4_do_en; +wire[WIDTH-1:0] su4_do_re; +wire[WIDTH-1:0] su4_do_im; + +SdfUnit #(.N(1024),.M(1024),.WIDTH(WIDTH)) SU1 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (di_en ), // i + .di_re (di_re ), // i + .di_im (di_im ), // i + .do_en (su1_do_en ), // o + .do_re (su1_do_re ), // o + .do_im (su1_do_im ) // o +); + +SdfUnit #(.N(1024),.M(256),.WIDTH(WIDTH)) SU2 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su1_do_en ), // i + .di_re (su1_do_re ), // i + .di_im (su1_do_im ), // i + .do_en (su2_do_en ), // o + .do_re (su2_do_re ), // o + .do_im (su2_do_im ) // o +); + +SdfUnit #(.N(1024),.M(64),.WIDTH(WIDTH)) SU3 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su2_do_en ), // i + .di_re (su2_do_re ), // i + .di_im (su2_do_im ), // i + .do_en (su3_do_en ), // o + .do_re (su3_do_re ), // o + .do_im (su3_do_im ) // o +); + +SdfUnit #(.N(1024),.M(16),.WIDTH(WIDTH)) SU4 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su3_do_en ), // i + .di_re (su3_do_re ), // i + .di_im (su3_do_im ), // i + .do_en (su4_do_en ), // o + .do_re (su4_do_re ), // o + .do_im (su4_do_im ) // o +); + +SdfUnit #(.N(1024),.M(4),.WIDTH(WIDTH)) SU5 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su4_do_en ), // i + .di_re (su4_do_re ), // i + .di_im (su4_do_im ), // i + .do_en (do_en ), // o + .do_re (do_re ), // o + .do_im (do_im ) // o +); + +endmodule diff --git a/nanamake_r22sdf/verilog/FFT128.v b/nanamake_r22sdf/verilog/FFT128.v new file mode 100644 index 0000000000000000000000000000000000000000..6d50ff6af13ca58a4283f84af7f8b52f8c47b474 --- /dev/null +++ b/nanamake_r22sdf/verilog/FFT128.v @@ -0,0 +1,76 @@ +//---------------------------------------------------------------------- +// FFT: 128-Point FFT Using Radix-2^2 Single-Path Delay Feedback +//---------------------------------------------------------------------- +module FFT #( + parameter WIDTH = 16 +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) +); +//---------------------------------------------------------------------- +// Data must be input consecutively in natural order. +// The result is scaled to 1/N and output in bit-reversed order. +// The output latency is 137 clock cycles. +//---------------------------------------------------------------------- + +wire su1_do_en; +wire[WIDTH-1:0] su1_do_re; +wire[WIDTH-1:0] su1_do_im; +wire su2_do_en; +wire[WIDTH-1:0] su2_do_re; +wire[WIDTH-1:0] su2_do_im; +wire su3_do_en; +wire[WIDTH-1:0] su3_do_re; +wire[WIDTH-1:0] su3_do_im; + +SdfUnit #(.N(128),.M(128),.WIDTH(WIDTH)) SU1 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (di_en ), // i + .di_re (di_re ), // i + .di_im (di_im ), // i + .do_en (su1_do_en ), // o + .do_re (su1_do_re ), // o + .do_im (su1_do_im ) // o +); + +SdfUnit #(.N(128),.M(32),.WIDTH(WIDTH)) SU2 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su1_do_en ), // i + .di_re (su1_do_re ), // i + .di_im (su1_do_im ), // i + .do_en (su2_do_en ), // o + .do_re (su2_do_re ), // o + .do_im (su2_do_im ) // o +); + +SdfUnit #(.N(128),.M(8),.WIDTH(WIDTH)) SU3 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su2_do_en ), // i + .di_re (su2_do_re ), // i + .di_im (su2_do_im ), // i + .do_en (su3_do_en ), // o + .do_re (su3_do_re ), // o + .do_im (su3_do_im ) // o +); + +SdfUnit2 #(.WIDTH(WIDTH)) SU4 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su3_do_en ), // i + .di_re (su3_do_re ), // i + .di_im (su3_do_im ), // i + .do_en (do_en ), // o + .do_re (do_re ), // o + .do_im (do_im ) // o +); + +endmodule diff --git a/nanamake_r22sdf/verilog/FFT64.v b/nanamake_r22sdf/verilog/FFT64.v new file mode 100644 index 0000000000000000000000000000000000000000..9ad22ad75aea837a512002de0df380d1654c905a --- /dev/null +++ b/nanamake_r22sdf/verilog/FFT64.v @@ -0,0 +1,62 @@ +//---------------------------------------------------------------------- +// FFT: 64-Point FFT Using Radix-2^2 Single-Path Delay Feedback +//---------------------------------------------------------------------- +module FFT #( + parameter WIDTH = 16 +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) +); +//---------------------------------------------------------------------- +// Data must be input consecutively in natural order. +// The result is scaled to 1/N and output in bit-reversed order. +// The output latency is 71 clock cycles. +//---------------------------------------------------------------------- + +wire su1_do_en; +wire[WIDTH-1:0] su1_do_re; +wire[WIDTH-1:0] su1_do_im; +wire su2_do_en; +wire[WIDTH-1:0] su2_do_re; +wire[WIDTH-1:0] su2_do_im; + +SdfUnit #(.N(64),.M(64),.WIDTH(WIDTH)) SU1 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (di_en ), // i + .di_re (di_re ), // i + .di_im (di_im ), // i + .do_en (su1_do_en ), // o + .do_re (su1_do_re ), // o + .do_im (su1_do_im ) // o +); + +SdfUnit #(.N(64),.M(16),.WIDTH(WIDTH)) SU2 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su1_do_en ), // i + .di_re (su1_do_re ), // i + .di_im (su1_do_im ), // i + .do_en (su2_do_en ), // o + .do_re (su2_do_re ), // o + .do_im (su2_do_im ) // o +); + +SdfUnit #(.N(64),.M(4),.WIDTH(WIDTH)) SU3 ( + .clock (clock ), // i + .reset (reset ), // i + .di_en (su2_do_en ), // i + .di_re (su2_do_re ), // i + .di_im (su2_do_im ), // i + .do_en (do_en ), // o + .do_re (do_re ), // o + .do_im (do_im ) // o +); + +endmodule diff --git a/nanamake_r22sdf/verilog/Multiply.v b/nanamake_r22sdf/verilog/Multiply.v new file mode 100644 index 0000000000000000000000000000000000000000..6172571df6168bad447500b67ec673d84cff2ee3 --- /dev/null +++ b/nanamake_r22sdf/verilog/Multiply.v @@ -0,0 +1,35 @@ +//---------------------------------------------------------------------- +// Multiply: Complex Multiplier +//---------------------------------------------------------------------- +module Multiply #( + parameter WIDTH = 16 +)( + input signed [WIDTH-1:0] a_re, + input signed [WIDTH-1:0] a_im, + input signed [WIDTH-1:0] b_re, + input signed [WIDTH-1:0] b_im, + output signed [WIDTH-1:0] m_re, + output signed [WIDTH-1:0] m_im +); + +wire signed [WIDTH*2-1:0] arbr, arbi, aibr, aibi; +wire signed [WIDTH-1:0] sc_arbr, sc_arbi, sc_aibr, sc_aibi; + +// Signed Multiplication +assign arbr = a_re * b_re; +assign arbi = a_re * b_im; +assign aibr = a_im * b_re; +assign aibi = a_im * b_im; + +// Scaling +assign sc_arbr = arbr >>> (WIDTH-1); +assign sc_arbi = arbi >>> (WIDTH-1); +assign sc_aibr = aibr >>> (WIDTH-1); +assign sc_aibi = aibi >>> (WIDTH-1); + +// Sub/Add +// These sub/add may overflow if unnormalized data is input. +assign m_re = sc_arbr - sc_aibi; +assign m_im = sc_arbi + sc_aibr; + +endmodule diff --git a/nanamake_r22sdf/verilog/SdfUnit.v b/nanamake_r22sdf/verilog/SdfUnit.v new file mode 100644 index 0000000000000000000000000000000000000000..67edc4941c1292ecd2058c4bddcb0e35da5eb430 --- /dev/null +++ b/nanamake_r22sdf/verilog/SdfUnit.v @@ -0,0 +1,277 @@ +//---------------------------------------------------------------------- +// SdfUnit: Radix-2^2 Single-Path Delay Feedback Unit for N-Point FFT +//---------------------------------------------------------------------- +module SdfUnit #( + parameter N = 64, // Number of FFT Point + parameter M = 64, // Twiddle Resolution + parameter WIDTH = 16 // Data Bit Length +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) +); + +// log2 constant function +function integer log2; + input integer x; + integer value; + begin + value = x-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end +endfunction + +localparam LOG_N = log2(N); // Bit Length of N +localparam LOG_M = log2(M); // Bit Length of M + +//---------------------------------------------------------------------- +// Internal Regs and Nets +//---------------------------------------------------------------------- +// 1st Butterfly +reg [LOG_N-1:0] di_count; // Input Data Count +wire bf1_bf; // Butterfly Add/Sub Enable +wire[WIDTH-1:0] bf1_x0_re; // Data #0 to Butterfly (Real) +wire[WIDTH-1:0] bf1_x0_im; // Data #0 to Butterfly (Imag) +wire[WIDTH-1:0] bf1_x1_re; // Data #1 to Butterfly (Real) +wire[WIDTH-1:0] bf1_x1_im; // Data #1 to Butterfly (Imag) +wire[WIDTH-1:0] bf1_y0_re; // Data #0 from Butterfly (Real) +wire[WIDTH-1:0] bf1_y0_im; // Data #0 from Butterfly (Imag) +wire[WIDTH-1:0] bf1_y1_re; // Data #1 from Butterfly (Real) +wire[WIDTH-1:0] bf1_y1_im; // Data #1 from Butterfly (Imag) +wire[WIDTH-1:0] db1_di_re; // Data to DelayBuffer (Real) +wire[WIDTH-1:0] db1_di_im; // Data to DelayBuffer (Imag) +wire[WIDTH-1:0] db1_do_re; // Data from DelayBuffer (Real) +wire[WIDTH-1:0] db1_do_im; // Data from DelayBuffer (Imag) +wire[WIDTH-1:0] bf1_sp_re; // Single-Path Data Output (Real) +wire[WIDTH-1:0] bf1_sp_im; // Single-Path Data Output (Imag) +reg bf1_sp_en; // Single-Path Data Enable +reg [LOG_N-1:0] bf1_count; // Single-Path Data Count +wire bf1_start; // Single-Path Output Trigger +wire bf1_end; // End of Single-Path Data +wire bf1_mj; // Twiddle (-j) Enable +reg [WIDTH-1:0] bf1_do_re; // 1st Butterfly Output Data (Real) +reg [WIDTH-1:0] bf1_do_im; // 1st Butterfly Output Data (Imag) + +// 2nd Butterfly +reg bf2_bf; // Butterfly Add/Sub Enable +wire[WIDTH-1:0] bf2_x0_re; // Data #0 to Butterfly (Real) +wire[WIDTH-1:0] bf2_x0_im; // Data #0 to Butterfly (Imag) +wire[WIDTH-1:0] bf2_x1_re; // Data #1 to Butterfly (Real) +wire[WIDTH-1:0] bf2_x1_im; // Data #1 to Butterfly (Imag) +wire[WIDTH-1:0] bf2_y0_re; // Data #0 from Butterfly (Real) +wire[WIDTH-1:0] bf2_y0_im; // Data #0 from Butterfly (Imag) +wire[WIDTH-1:0] bf2_y1_re; // Data #1 from Butterfly (Real) +wire[WIDTH-1:0] bf2_y1_im; // Data #1 from Butterfly (Imag) +wire[WIDTH-1:0] db2_di_re; // Data to DelayBuffer (Real) +wire[WIDTH-1:0] db2_di_im; // Data to DelayBuffer (Imag) +wire[WIDTH-1:0] db2_do_re; // Data from DelayBuffer (Real) +wire[WIDTH-1:0] db2_do_im; // Data from DelayBuffer (Imag) +wire[WIDTH-1:0] bf2_sp_re; // Single-Path Data Output (Real) +wire[WIDTH-1:0] bf2_sp_im; // Single-Path Data Output (Imag) +reg bf2_sp_en; // Single-Path Data Enable +reg [LOG_N-1:0] bf2_count; // Single-Path Data Count +reg bf2_start; // Single-Path Output Trigger +wire bf2_end; // End of Single-Path Data +reg [WIDTH-1:0] bf2_do_re; // 2nd Butterfly Output Data (Real) +reg [WIDTH-1:0] bf2_do_im; // 2nd Butterfly Output Data (Imag) +reg bf2_do_en; // 2nd Butterfly Output Data Enable + +// Multiplication +wire[1:0] tw_sel; // Twiddle Select (2n/n/3n) +wire[LOG_N-3:0] tw_num; // Twiddle Number (n) +wire[LOG_N-1:0] tw_addr; // Twiddle Table Address +wire[WIDTH-1:0] tw_re; // Twiddle Factor (Real) +wire[WIDTH-1:0] tw_im; // Twiddle Factor (Imag) +reg mu_en; // Multiplication Enable +wire[WIDTH-1:0] mu_a_re; // Multiplier Input (Real) +wire[WIDTH-1:0] mu_a_im; // Multiplier Input (Imag) +wire[WIDTH-1:0] mu_m_re; // Multiplier Output (Real) +wire[WIDTH-1:0] mu_m_im; // Multiplier Output (Imag) +reg [WIDTH-1:0] mu_do_re; // Multiplication Output Data (Real) +reg [WIDTH-1:0] mu_do_im; // Multiplication Output Data (Imag) +reg mu_do_en; // Multiplication Output Data Enable + +//---------------------------------------------------------------------- +// 1st Butterfly +//---------------------------------------------------------------------- +always @(posedge clock or posedge reset) begin + if (reset) begin + di_count <= {LOG_N{1'b0}}; + end else begin + di_count <= di_en ? (di_count + 1'b1) : {LOG_N{1'b0}}; + end +end +assign bf1_bf = di_count[LOG_M-1]; + +// Set unknown value x for verification +assign bf1_x0_re = bf1_bf ? db1_do_re : {WIDTH{1'bx}}; +assign bf1_x0_im = bf1_bf ? db1_do_im : {WIDTH{1'bx}}; +assign bf1_x1_re = bf1_bf ? di_re : {WIDTH{1'bx}}; +assign bf1_x1_im = bf1_bf ? di_im : {WIDTH{1'bx}}; + +Butterfly #(.WIDTH(WIDTH),.RH(0)) BF1 ( + .x0_re (bf1_x0_re ), // i + .x0_im (bf1_x0_im ), // i + .x1_re (bf1_x1_re ), // i + .x1_im (bf1_x1_im ), // i + .y0_re (bf1_y0_re ), // o + .y0_im (bf1_y0_im ), // o + .y1_re (bf1_y1_re ), // o + .y1_im (bf1_y1_im ) // o +); + +DelayBuffer #(.DEPTH(2**(LOG_M-1)),.WIDTH(WIDTH)) DB1 ( + .clock (clock ), // i + .di_re (db1_di_re ), // i + .di_im (db1_di_im ), // i + .do_re (db1_do_re ), // o + .do_im (db1_do_im ) // o +); + +assign db1_di_re = bf1_bf ? bf1_y1_re : di_re; +assign db1_di_im = bf1_bf ? bf1_y1_im : di_im; +assign bf1_sp_re = bf1_bf ? bf1_y0_re : bf1_mj ? db1_do_im : db1_do_re; +assign bf1_sp_im = bf1_bf ? bf1_y0_im : bf1_mj ? -db1_do_re : db1_do_im; + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf1_sp_en <= 1'b0; + bf1_count <= {LOG_N{1'b0}}; + end else begin + bf1_sp_en <= bf1_start ? 1'b1 : bf1_end ? 1'b0 : bf1_sp_en; + bf1_count <= bf1_sp_en ? (bf1_count + 1'b1) : {LOG_N{1'b0}}; + end +end +assign bf1_start = (di_count == (2**(LOG_M-1)-1)); +assign bf1_end = (bf1_count == (2**LOG_N-1)); +assign bf1_mj = (bf1_count[LOG_M-1:LOG_M-2] == 2'd3); + +always @(posedge clock) begin + bf1_do_re <= bf1_sp_re; + bf1_do_im <= bf1_sp_im; +end + +//---------------------------------------------------------------------- +// 2nd Butterfly +//---------------------------------------------------------------------- +always @(posedge clock) begin + bf2_bf <= bf1_count[LOG_M-2]; +end + +// Set unknown value x for verification +assign bf2_x0_re = bf2_bf ? db2_do_re : {WIDTH{1'bx}}; +assign bf2_x0_im = bf2_bf ? db2_do_im : {WIDTH{1'bx}}; +assign bf2_x1_re = bf2_bf ? bf1_do_re : {WIDTH{1'bx}}; +assign bf2_x1_im = bf2_bf ? bf1_do_im : {WIDTH{1'bx}}; + +// Negative bias occurs when RH=0 and positive bias occurs when RH=1. +// Using both alternately reduces the overall rounding error. +Butterfly #(.WIDTH(WIDTH),.RH(1)) BF2 ( + .x0_re (bf2_x0_re ), // i + .x0_im (bf2_x0_im ), // i + .x1_re (bf2_x1_re ), // i + .x1_im (bf2_x1_im ), // i + .y0_re (bf2_y0_re ), // o + .y0_im (bf2_y0_im ), // o + .y1_re (bf2_y1_re ), // o + .y1_im (bf2_y1_im ) // o +); + +DelayBuffer #(.DEPTH(2**(LOG_M-2)),.WIDTH(WIDTH)) DB2 ( + .clock (clock ), // i + .di_re (db2_di_re ), // i + .di_im (db2_di_im ), // i + .do_re (db2_do_re ), // o + .do_im (db2_do_im ) // o +); + +assign db2_di_re = bf2_bf ? bf2_y1_re : bf1_do_re; +assign db2_di_im = bf2_bf ? bf2_y1_im : bf1_do_im; +assign bf2_sp_re = bf2_bf ? bf2_y0_re : db2_do_re; +assign bf2_sp_im = bf2_bf ? bf2_y0_im : db2_do_im; + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf2_sp_en <= 1'b0; + bf2_count <= {LOG_N{1'b0}}; + end else begin + bf2_sp_en <= bf2_start ? 1'b1 : bf2_end ? 1'b0 : bf2_sp_en; + bf2_count <= bf2_sp_en ? (bf2_count + 1'b1) : {LOG_N{1'b0}}; + end +end + +always @(posedge clock) begin + bf2_start <= (bf1_count == (2**(LOG_M-2)-1)) & bf1_sp_en; +end +assign bf2_end = (bf2_count == (2**LOG_N-1)); + +always @(posedge clock) begin + bf2_do_re <= bf2_sp_re; + bf2_do_im <= bf2_sp_im; +end + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf2_do_en <= 1'b0; + end else begin + bf2_do_en <= bf2_sp_en; + end +end + +//---------------------------------------------------------------------- +// Multiplication +//---------------------------------------------------------------------- +assign tw_sel[1] = bf2_count[LOG_M-2]; +assign tw_sel[0] = bf2_count[LOG_M-1]; +assign tw_num = bf2_count << (LOG_N-LOG_M); +assign tw_addr = tw_num * tw_sel; + +Twiddle TW ( + .clock (clock ), // i + .addr (tw_addr), // i + .tw_re (tw_re ), // o + .tw_im (tw_im ) // o +); + +// Multiplication is bypassed when twiddle address is 0. +always @(posedge clock) begin + mu_en <= (tw_addr != {LOG_N{1'b0}}); +end +// Set unknown value x for verification +assign mu_a_re = mu_en ? bf2_do_re : {WIDTH{1'bx}}; +assign mu_a_im = mu_en ? bf2_do_im : {WIDTH{1'bx}}; + +Multiply #(.WIDTH(WIDTH)) MU ( + .a_re (mu_a_re), // i + .a_im (mu_a_im), // i + .b_re (tw_re ), // i + .b_im (tw_im ), // i + .m_re (mu_m_re), // o + .m_im (mu_m_im) // o +); + +always @(posedge clock) begin + mu_do_re <= mu_en ? mu_m_re : bf2_do_re; + mu_do_im <= mu_en ? mu_m_im : bf2_do_im; +end + +always @(posedge clock or posedge reset) begin + if (reset) begin + mu_do_en <= 1'b0; + end else begin + mu_do_en <= bf2_do_en; + end +end + +// No multiplication required at final stage +assign do_en = (LOG_M == 2) ? bf2_do_en : mu_do_en; +assign do_re = (LOG_M == 2) ? bf2_do_re : mu_do_re; +assign do_im = (LOG_M == 2) ? bf2_do_im : mu_do_im; + +endmodule diff --git a/nanamake_r22sdf/verilog/SdfUnit2.v b/nanamake_r22sdf/verilog/SdfUnit2.v new file mode 100644 index 0000000000000000000000000000000000000000..13bcf5a14590b6744dcdb9cc1a07c8e82e960e43 --- /dev/null +++ b/nanamake_r22sdf/verilog/SdfUnit2.v @@ -0,0 +1,94 @@ +//---------------------------------------------------------------------- +// SdfUnit2: Radix-2 SDF Dedicated for Twiddle Resolution M = 2 +//---------------------------------------------------------------------- +module SdfUnit2 #( + parameter WIDTH = 16, // Data Bit Length + parameter BF_RH = 0 // Butterfly Round Half Up +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output reg do_en, // Output Data Enable + output reg [WIDTH-1:0] do_re, // Output Data (Real) + output reg [WIDTH-1:0] do_im // Output Data (Imag) +); + +//---------------------------------------------------------------------- +// Internal Regs and Nets +//---------------------------------------------------------------------- +reg bf_en; // Butterfly Add/Sub Enable +wire[WIDTH-1:0] x0_re; // Data #0 to Butterfly (Real) +wire[WIDTH-1:0] x0_im; // Data #0 to Butterfly (Imag) +wire[WIDTH-1:0] x1_re; // Data #1 to Butterfly (Real) +wire[WIDTH-1:0] x1_im; // Data #1 to Butterfly (Imag) +wire[WIDTH-1:0] y0_re; // Data #0 from Butterfly (Real) +wire[WIDTH-1:0] y0_im; // Data #0 from Butterfly (Imag) +wire[WIDTH-1:0] y1_re; // Data #1 from Butterfly (Real) +wire[WIDTH-1:0] y1_im; // Data #1 from Butterfly (Imag) +wire[WIDTH-1:0] db_di_re; // Data to DelayBuffer (Real) +wire[WIDTH-1:0] db_di_im; // Data to DelayBuffer (Imag) +wire[WIDTH-1:0] db_do_re; // Data from DelayBuffer (Real) +wire[WIDTH-1:0] db_do_im; // Data from DelayBuffer (Imag) +wire[WIDTH-1:0] bf_sp_re; // Single-Path Data Output (Real) +wire[WIDTH-1:0] bf_sp_im; // Single-Path Data Output (Imag) +reg bf_sp_en; // Single-Path Data Enable + +//---------------------------------------------------------------------- +// Butterfly Add/Sub +//---------------------------------------------------------------------- +always @(posedge clock or posedge reset) begin + if (reset) begin + bf_en <= 1'b0; + end else begin + bf_en <= di_en ? ~bf_en : 1'b0; + end +end + +// Set unknown value x for verification +assign x0_re = bf_en ? db_do_re : {WIDTH{1'bx}}; +assign x0_im = bf_en ? db_do_im : {WIDTH{1'bx}}; +assign x1_re = bf_en ? di_re : {WIDTH{1'bx}}; +assign x1_im = bf_en ? di_im : {WIDTH{1'bx}}; + +Butterfly #(.WIDTH(WIDTH),.RH(BF_RH)) BF ( + .x0_re (x0_re ), // i + .x0_im (x0_im ), // i + .x1_re (x1_re ), // i + .x1_im (x1_im ), // i + .y0_re (y0_re ), // o + .y0_im (y0_im ), // o + .y1_re (y1_re ), // o + .y1_im (y1_im ) // o +); + +DelayBuffer #(.DEPTH(1),.WIDTH(WIDTH)) DB ( + .clock (clock ), // i + .di_re (db_di_re ), // i + .di_im (db_di_im ), // i + .do_re (db_do_re ), // o + .do_im (db_do_im ) // o +); + +assign db_di_re = bf_en ? y1_re : di_re; +assign db_di_im = bf_en ? y1_im : di_im; +assign bf_sp_re = bf_en ? y0_re : db_do_re; +assign bf_sp_im = bf_en ? y0_im : db_do_im; + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf_sp_en <= 1'b0; + do_en <= 1'b0; + end else begin + bf_sp_en <= di_en; + do_en <= bf_sp_en; + end +end + +always @(posedge clock) begin + do_re <= bf_sp_re; + do_im <= bf_sp_im; +end + +endmodule diff --git a/nanamake_r22sdf/verilog/SdfUnit_TC.v b/nanamake_r22sdf/verilog/SdfUnit_TC.v new file mode 100644 index 0000000000000000000000000000000000000000..6fdf6f8cb6841b8969aabce9523bfa63c932e995 --- /dev/null +++ b/nanamake_r22sdf/verilog/SdfUnit_TC.v @@ -0,0 +1,344 @@ +//---------------------------------------------------------------------- +// SdfUnit: Radix-2^2 SDF Unit with Twiddle Conversion +//---------------------------------------------------------------------- +module SdfUnit #( + parameter N = 64, // Number of FFT Point + parameter M = 64, // Twiddle Resolution + parameter WIDTH = 16, // Data Bit Length + parameter T4_EN = 0, // Use TwiddleConvert4 + parameter T8_EN = 1, // Use TwiddleConvert8 + parameter TW_FF = 1, // Use Twiddle Output Register + parameter TC_FF = 1, // Use TwiddleConvert Output Register + parameter B1_RH = 0, // 1st Butterfly Round Half Up + parameter B2_RH = 1, // 2nd Butterfly Round Half Up + parameter LP = 0 // Power Saving +)( + input clock, // Master Clock + input reset, // Active High Asynchronous Reset + input di_en, // Input Data Enable + input [WIDTH-1:0] di_re, // Input Data (Real) + input [WIDTH-1:0] di_im, // Input Data (Imag) + output do_en, // Output Data Enable + output [WIDTH-1:0] do_re, // Output Data (Real) + output [WIDTH-1:0] do_im // Output Data (Imag) +); + +// log2 constant function +function integer log2; + input integer x; + integer value; + begin + value = x-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end +endfunction + +localparam LOG_N = log2(N); // Bit Length of N +localparam LOG_M = log2(M); // Bit Length of M + +// When using Twiddle Conversion, start counting 1T earlier +localparam TC_EN = T4_EN | T8_EN; +localparam EARLY = TC_EN & TW_FF & TC_FF; + +//---------------------------------------------------------------------- +// Internal Regs and Nets +//---------------------------------------------------------------------- +// 1st Butterfly +reg [LOG_N-1:0] di_count; // Input Data Count +wire bf1_bf; // Butterfly Add/Sub Enable +wire[WIDTH-1:0] bf1_x0_re; // Data #0 to Butterfly (Real) +wire[WIDTH-1:0] bf1_x0_im; // Data #0 to Butterfly (Imag) +wire[WIDTH-1:0] bf1_x1_re; // Data #1 to Butterfly (Real) +wire[WIDTH-1:0] bf1_x1_im; // Data #1 to Butterfly (Imag) +wire[WIDTH-1:0] bf1_y0_re; // Data #0 from Butterfly (Real) +wire[WIDTH-1:0] bf1_y0_im; // Data #0 from Butterfly (Imag) +wire[WIDTH-1:0] bf1_y1_re; // Data #1 from Butterfly (Real) +wire[WIDTH-1:0] bf1_y1_im; // Data #1 from Butterfly (Imag) +wire[WIDTH-1:0] db1_di_re; // Data to DelayBuffer (Real) +wire[WIDTH-1:0] db1_di_im; // Data to DelayBuffer (Imag) +wire[WIDTH-1:0] db1_do_re; // Data from DelayBuffer (Real) +wire[WIDTH-1:0] db1_do_im; // Data from DelayBuffer (Imag) +wire[WIDTH-1:0] bf1_sp_re; // Single-Path Data Output (Real) +wire[WIDTH-1:0] bf1_sp_im; // Single-Path Data Output (Imag) +reg bf1_sp_en; // Single-Path Data Enable +reg [LOG_N-1:0] bf1_count; // Single-Path Data Count +wire bf1_start; // Single-Path Output Trigger +wire bf1_end; // End of Single-Path Data +wire bf1_mj; // Twiddle (-j) Enable +reg [WIDTH-1:0] bf1_do_re; // 1st Butterfly Output Data (Real) +reg [WIDTH-1:0] bf1_do_im; // 1st Butterfly Output Data (Imag) + +// 2nd Butterfly +reg bf2_bf; // Butterfly Add/Sub Enable +wire[WIDTH-1:0] bf2_x0_re; // Data #0 to Butterfly (Real) +wire[WIDTH-1:0] bf2_x0_im; // Data #0 to Butterfly (Imag) +wire[WIDTH-1:0] bf2_x1_re; // Data #1 to Butterfly (Real) +wire[WIDTH-1:0] bf2_x1_im; // Data #1 to Butterfly (Imag) +wire[WIDTH-1:0] bf2_y0_re; // Data #0 from Butterfly (Real) +wire[WIDTH-1:0] bf2_y0_im; // Data #0 from Butterfly (Imag) +wire[WIDTH-1:0] bf2_y1_re; // Data #1 from Butterfly (Real) +wire[WIDTH-1:0] bf2_y1_im; // Data #1 from Butterfly (Imag) +wire[WIDTH-1:0] db2_di_re; // Data to DelayBuffer (Real) +wire[WIDTH-1:0] db2_di_im; // Data to DelayBuffer (Imag) +wire[WIDTH-1:0] db2_do_re; // Data from DelayBuffer (Real) +wire[WIDTH-1:0] db2_do_im; // Data from DelayBuffer (Imag) +wire[WIDTH-1:0] bf2_sp_re; // Single-Path Data Output (Real) +wire[WIDTH-1:0] bf2_sp_im; // Single-Path Data Output (Imag) +reg bf2_ct_en; // Single-Path Data Count Enable +reg [LOG_N-1:0] bf2_count; // Single-Path Data Count +wire bf2_start_0t;// Single-Path Output Trigger +reg bf2_start_1t;// Single-Path Output Trigger +wire bf2_start; // Single-Path Output Trigger +wire bf2_end; // End of Single-Path Data +reg bf2_ct_en_1d;// Single-Path Data Enable When Using TC +wire bf2_sp_en; // Single-Path Data Enable +reg [WIDTH-1:0] bf2_do_re; // 2nd Butterfly Output Data (Real) +reg [WIDTH-1:0] bf2_do_im; // 2nd Butterfly Output Data (Imag) +reg bf2_do_en; // 2nd Butterfly Output Data Enable + +// Multiplication +wire[1:0] tw_sel; // Twiddle Select (2n/n/3n) +wire[LOG_N-3:0] tw_num; // Twiddle Number (n) +wire[LOG_N-1:0] tw_addr; // Twiddle Table Address +wire[LOG_N-1:0] tc_addr; // Twiddle Address from TwiddleConvert +wire[LOG_N-1:0] tw_addr_tc; // Twiddle Address after TC_EN Switch +wire[WIDTH-1:0] tw_re; // Twiddle Data from Table (Real) +wire[WIDTH-1:0] tw_im; // Twiddle Data from Table (Imag) +wire[WIDTH-1:0] tc_re; // Twiddle Data from TwiddleConvert (Real) +wire[WIDTH-1:0] tc_im; // Twiddle Data from TwiddleConvert (Imag) +reg tw_nz; // Multiplication Enable +reg tw_nz_1d; // Multiplication Enable +wire mu_en; // Multiplication Enable +wire[WIDTH-1:0] mu_a_re; // Multiplier Input (Real) +wire[WIDTH-1:0] mu_a_im; // Multiplier Input (Imag) +wire[WIDTH-1:0] mu_b_re; // Twiddle Data to Multiplier (Real) +wire[WIDTH-1:0] mu_b_im; // Twiddle Data to Multiplier (Imag) +wire[WIDTH-1:0] mu_m_re; // Multiplier Output (Real) +wire[WIDTH-1:0] mu_m_im; // Multiplier Output (Imag) +reg [WIDTH-1:0] mu_do_re; // Multiplication Output Data (Real) +reg [WIDTH-1:0] mu_do_im; // Multiplication Output Data (Imag) +reg mu_do_en; // Multiplication Output Data Enable + +//---------------------------------------------------------------------- +// 1st Butterfly +//---------------------------------------------------------------------- +always @(posedge clock or posedge reset) begin + if (reset) begin + di_count <= {LOG_N{1'b0}}; + end else begin + di_count <= di_en ? (di_count + 1'b1) : {LOG_N{1'b0}}; + end +end +assign bf1_bf = di_count[LOG_M-1]; + +// Reducing signal changes may reduce power consumption +// Set unknown value x for verification +assign bf1_x0_re = bf1_bf ? db1_do_re : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf1_x0_im = bf1_bf ? db1_do_im : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf1_x1_re = bf1_bf ? di_re : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf1_x1_im = bf1_bf ? di_im : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; + +Butterfly #(.WIDTH(WIDTH),.RH(B1_RH)) BF1 ( + .x0_re (bf1_x0_re ), // i + .x0_im (bf1_x0_im ), // i + .x1_re (bf1_x1_re ), // i + .x1_im (bf1_x1_im ), // i + .y0_re (bf1_y0_re ), // o + .y0_im (bf1_y0_im ), // o + .y1_re (bf1_y1_re ), // o + .y1_im (bf1_y1_im ) // o +); + +DelayBuffer #(.DEPTH(2**(LOG_M-1)),.WIDTH(WIDTH)) DB1 ( + .clock (clock ), // i + .di_re (db1_di_re ), // i + .di_im (db1_di_im ), // i + .do_re (db1_do_re ), // o + .do_im (db1_do_im ) // o +); + +assign db1_di_re = bf1_bf ? bf1_y1_re : di_re; +assign db1_di_im = bf1_bf ? bf1_y1_im : di_im; +assign bf1_sp_re = bf1_bf ? bf1_y0_re : bf1_mj ? db1_do_im : db1_do_re; +assign bf1_sp_im = bf1_bf ? bf1_y0_im : bf1_mj ? -db1_do_re : db1_do_im; + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf1_sp_en <= 1'b0; + bf1_count <= {LOG_N{1'b0}}; + end else begin + bf1_sp_en <= bf1_start ? 1'b1 : bf1_end ? 1'b0 : bf1_sp_en; + bf1_count <= bf1_sp_en ? (bf1_count + 1'b1) : {LOG_N{1'b0}}; + end +end +assign bf1_start = (di_count == (2**(LOG_M-1)-1)); +assign bf1_end = (bf1_count == (2**LOG_N-1)); +assign bf1_mj = (bf1_count[LOG_M-1:LOG_M-2] == 2'd3); + +always @(posedge clock) begin + bf1_do_re <= bf1_sp_re; + bf1_do_im <= bf1_sp_im; +end + +//---------------------------------------------------------------------- +// 2nd Butterfly +//---------------------------------------------------------------------- +always @(posedge clock) begin + bf2_bf <= bf1_count[LOG_M-2]; +end + +// Reducing signal changes may reduce power consumption +// Set unknown value x for verification +assign bf2_x0_re = bf2_bf ? db2_do_re : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf2_x0_im = bf2_bf ? db2_do_im : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf2_x1_re = bf2_bf ? bf1_do_re : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; +assign bf2_x1_im = bf2_bf ? bf1_do_im : LP ? {WIDTH{1'b0}} : {WIDTH{1'bx}}; + +// Negative bias occurs when RH=0 and positive bias occurs when RH=1. +// Using both alternately reduces the overall rounding error. +Butterfly #(.WIDTH(WIDTH),.RH(B2_RH)) BF2 ( + .x0_re (bf2_x0_re ), // i + .x0_im (bf2_x0_im ), // i + .x1_re (bf2_x1_re ), // i + .x1_im (bf2_x1_im ), // i + .y0_re (bf2_y0_re ), // o + .y0_im (bf2_y0_im ), // o + .y1_re (bf2_y1_re ), // o + .y1_im (bf2_y1_im ) // o +); + +DelayBuffer #(.DEPTH(2**(LOG_M-2)),.WIDTH(WIDTH)) DB2 ( + .clock (clock ), // i + .di_re (db2_di_re ), // i + .di_im (db2_di_im ), // i + .do_re (db2_do_re ), // o + .do_im (db2_do_im ) // o +); + +assign db2_di_re = bf2_bf ? bf2_y1_re : bf1_do_re; +assign db2_di_im = bf2_bf ? bf2_y1_im : bf1_do_im; +assign bf2_sp_re = bf2_bf ? bf2_y0_re : db2_do_re; +assign bf2_sp_im = bf2_bf ? bf2_y0_im : db2_do_im; + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf2_ct_en <= 1'b0; + bf2_count <= {LOG_N{1'b0}}; + end else begin + bf2_ct_en <= bf2_start ? 1'b1 : bf2_end ? 1'b0 : bf2_ct_en; + bf2_count <= bf2_ct_en ? (bf2_count + 1'b1) : {LOG_N{1'b0}}; + end +end + +// When using Twiddle Conversion, start counting 1T earlier +assign bf2_start_0t = (bf1_count == (2**(LOG_M-2)-1)) & bf1_sp_en; +always @(posedge clock) begin + bf2_start_1t <= bf2_start_0t; +end +assign bf2_start = EARLY ? bf2_start_0t : bf2_start_1t; +assign bf2_end = (bf2_count == (2**LOG_N-1)); + +always @(posedge clock) begin + bf2_ct_en_1d <= bf2_ct_en; +end +assign bf2_sp_en = EARLY ? bf2_ct_en_1d : bf2_ct_en; + +always @(posedge clock) begin + bf2_do_re <= bf2_sp_re; + bf2_do_im <= bf2_sp_im; +end + +always @(posedge clock or posedge reset) begin + if (reset) begin + bf2_do_en <= 1'b0; + end else begin + bf2_do_en <= bf2_sp_en; + end +end + +//---------------------------------------------------------------------- +// Multiplication +//---------------------------------------------------------------------- +assign tw_sel[1] = bf2_count[LOG_M-2]; +assign tw_sel[0] = bf2_count[LOG_M-1]; +assign tw_num = bf2_count << (LOG_N-LOG_M); +assign tw_addr = tw_num * tw_sel; + +Twiddle #(.TW_FF(TW_FF)) TW ( + .clock (clock ), // i + .addr (tw_addr_tc ), // i + .tw_re (tw_re ), // o + .tw_im (tw_im ) // o +); + +generate if (T4_EN) begin + TwiddleConvert4 #(.LOG_N(LOG_N),.WIDTH(WIDTH),.TW_FF(TW_FF),.TC_FF(TC_FF)) TC ( + .clock (clock ), // i + .tw_addr (tw_addr), // i + .tw_re (tw_re ), // i + .tw_im (tw_im ), // i + .tc_addr (tc_addr), // o + .tc_re (tc_re ), // o + .tc_im (tc_im ) // o + ); +end else if (T8_EN) begin + TwiddleConvert8 #(.LOG_N(LOG_N),.WIDTH(WIDTH),.TW_FF(TW_FF),.TC_FF(TC_FF)) TC ( + .clock (clock ), // i + .tw_addr (tw_addr), // i + .tw_re (tw_re ), // i + .tw_im (tw_im ), // i + .tc_addr (tc_addr), // o + .tc_re (tc_re ), // o + .tc_im (tc_im ) // o + ); +end else begin + assign tc_addr = {LOG_N{1'bx}}; + assign tc_re = {WIDTH{1'bx}}; + assign tc_im = {WIDTH{1'bx}}; +end endgenerate + +assign tw_addr_tc = TC_EN ? tc_addr : tw_addr; +assign mu_b_re = TC_EN ? tc_re : tw_re; +assign mu_b_im = TC_EN ? tc_im : tw_im; + +// Multiplication is bypassed when twiddle address is 0. +always @(posedge clock) begin + tw_nz <= (tw_addr != {LOG_N{1'b0}}); + tw_nz_1d <= tw_nz; +end +// When using Twiddle Conversion, address generated 1T Earlier +assign mu_en = EARLY ? tw_nz_1d : tw_nz; + +// Set unknown value x for verification +assign mu_a_re = mu_en ? bf2_do_re : {WIDTH{1'bx}}; +assign mu_a_im = mu_en ? bf2_do_im : {WIDTH{1'bx}}; + +Multiply #(.WIDTH(WIDTH)) MU ( + .a_re (mu_a_re), // i + .a_im (mu_a_im), // i + .b_re (mu_b_re), // i + .b_im (mu_b_im), // i + .m_re (mu_m_re), // o + .m_im (mu_m_im) // o +); + +always @(posedge clock) begin + mu_do_re <= mu_en ? mu_m_re : bf2_do_re; + mu_do_im <= mu_en ? mu_m_im : bf2_do_im; +end + +always @(posedge clock or posedge reset) begin + if (reset) begin + mu_do_en <= 1'b0; + end else begin + mu_do_en <= bf2_do_en; + end +end + +// No multiplication required at final stage +assign do_en = (LOG_M == 2) ? bf2_do_en : mu_do_en; +assign do_re = (LOG_M == 2) ? bf2_do_re : mu_do_re; +assign do_im = (LOG_M == 2) ? bf2_do_im : mu_do_im; + +endmodule diff --git a/nanamake_r22sdf/verilog/Twiddle1024_32B.v b/nanamake_r22sdf/verilog/Twiddle1024_32B.v new file mode 100644 index 0000000000000000000000000000000000000000..c6b438d6abc87d766da931975f23c501a30c4c95 --- /dev/null +++ b/nanamake_r22sdf/verilog/Twiddle1024_32B.v @@ -0,0 +1,1064 @@ +//---------------------------------------------------------------------- +// Twiddle: 1024-Point Twiddle Table for Radix-2^2 Butterfly +//---------------------------------------------------------------------- +module Twiddle #( + parameter TW_FF = 1 // Use Output Register +)( + input clock, // Master Clock + input [9:0] addr, // Twiddle Factor Number + output [31:0] tw_re, // Twiddle Factor (Real) + output [31:0] tw_im // Twiddle Factor (Imag) +); + +wire[31:0] wn_re[0:1023]; // Twiddle Table (Real) +wire[31:0] wn_im[0:1023]; // Twiddle Table (Imag) +wire[31:0] mx_re; // Multiplexer output (Real) +wire[31:0] mx_im; // Multiplexer output (Imag) +reg [31:0] ff_re; // Register output (Real) +reg [31:0] ff_im; // Register output (Imag) + +assign mx_re = wn_re[addr]; +assign mx_im = wn_im[addr]; + +always @(posedge clock) begin + ff_re <= mx_re; + ff_im <= mx_im; +end + +assign tw_re = TW_FF ? ff_re : mx_re; +assign tw_im = TW_FF ? ff_im : mx_im; + +//---------------------------------------------------------------------- +// Twiddle Factor Value +//---------------------------------------------------------------------- +// Multiplication is bypassed when twiddle address is 0. +// Setting wn_re[0] = 0 and wn_im[0] = 0 makes it easier to check the waveform. +// It may also reduce power consumption slightly. +// +// wn_re = cos(-2pi*n/1024) wn_im = sin(-2pi*n/1024) +assign wn_re[ 0] = 32'h00000000; assign wn_im[ 0] = 32'h00000000; // 0 1.000 -0.000 +assign wn_re[ 1] = 32'h7FFF6216; assign wn_im[ 1] = 32'hFF36F078; // 1 1.000 -0.006 +assign wn_re[ 2] = 32'h7FFD885A; assign wn_im[ 2] = 32'hFE6DE2E0; // 2 1.000 -0.012 +assign wn_re[ 3] = 32'h7FFA72D1; assign wn_im[ 3] = 32'hFDA4D929; // 3 1.000 -0.018 +assign wn_re[ 4] = 32'h7FF62182; assign wn_im[ 4] = 32'hFCDBD541; // 4 1.000 -0.025 +assign wn_re[ 5] = 32'h7FF09478; assign wn_im[ 5] = 32'hFC12D91A; // 5 1.000 -0.031 +assign wn_re[ 6] = 32'h7FE9CBC0; assign wn_im[ 6] = 32'hFB49E6A3; // 6 0.999 -0.037 +assign wn_re[ 7] = 32'h7FE1C76B; assign wn_im[ 7] = 32'hFA80FFCB; // 7 0.999 -0.043 +assign wn_re[ 8] = 32'h7FD8878E; assign wn_im[ 8] = 32'hF9B82684; // 8 0.999 -0.049 +assign wn_re[ 9] = 32'h7FCE0C3E; assign wn_im[ 9] = 32'hF8EF5CBB; // 9 0.998 -0.055 +assign wn_re[10] = 32'h7FC25596; assign wn_im[10] = 32'hF826A462; // 10 0.998 -0.061 +assign wn_re[11] = 32'h7FB563B3; assign wn_im[11] = 32'hF75DFF66; // 11 0.998 -0.067 +assign wn_re[12] = 32'h7FA736B4; assign wn_im[12] = 32'hF6956FB7; // 12 0.997 -0.074 +assign wn_re[13] = 32'h7F97CEBD; assign wn_im[13] = 32'hF5CCF743; // 13 0.997 -0.080 +assign wn_re[14] = 32'h7F872BF3; assign wn_im[14] = 32'hF50497FB; // 14 0.996 -0.086 +assign wn_re[15] = 32'h7F754E80; assign wn_im[15] = 32'hF43C53CB; // 15 0.996 -0.092 +assign wn_re[16] = 32'h7F62368F; assign wn_im[16] = 32'hF3742CA2; // 16 0.995 -0.098 +assign wn_re[17] = 32'h7F4DE451; assign wn_im[17] = 32'hF2AC246E; // 17 0.995 -0.104 +assign wn_re[18] = 32'h7F3857F6; assign wn_im[18] = 32'hF1E43D1C; // 18 0.994 -0.110 +assign wn_re[19] = 32'h7F2191B4; assign wn_im[19] = 32'hF11C789A; // 19 0.993 -0.116 +assign wn_re[20] = 32'h7F0991C4; assign wn_im[20] = 32'hF054D8D5; // 20 0.992 -0.122 +assign wn_re[21] = 32'h7EF05860; assign wn_im[21] = 32'hEF8D5FB8; // 21 0.992 -0.128 +assign wn_re[22] = 32'h7ED5E5C6; assign wn_im[22] = 32'hEEC60F31; // 22 0.991 -0.135 +assign wn_re[23] = 32'h7EBA3A39; assign wn_im[23] = 32'hEDFEE92B; // 23 0.990 -0.141 +assign wn_re[24] = 32'h7E9D55FC; assign wn_im[24] = 32'hED37EF91; // 24 0.989 -0.147 +assign wn_re[25] = 32'h7E7F3957; assign wn_im[25] = 32'hEC71244F; // 25 0.988 -0.153 +assign wn_re[26] = 32'h7E5FE493; assign wn_im[26] = 32'hEBAA894F; // 26 0.987 -0.159 +assign wn_re[27] = 32'h7E3F57FF; assign wn_im[27] = 32'hEAE4207A; // 27 0.986 -0.165 +assign wn_re[28] = 32'h7E1D93EA; assign wn_im[28] = 32'hEA1DEBBB; // 28 0.985 -0.171 +assign wn_re[29] = 32'h7DFA98A8; assign wn_im[29] = 32'hE957ECFB; // 29 0.984 -0.177 +assign wn_re[30] = 32'h7DD6668F; assign wn_im[30] = 32'hE8922622; // 30 0.983 -0.183 +assign wn_re[31] = 32'h7DB0FDF8; assign wn_im[31] = 32'hE7CC9917; // 31 0.982 -0.189 +assign wn_re[32] = 32'h7D8A5F40; assign wn_im[32] = 32'hE70747C4; // 32 0.981 -0.195 +assign wn_re[33] = 32'h7D628AC6; assign wn_im[33] = 32'hE642340D; // 33 0.980 -0.201 +assign wn_re[34] = 32'h7D3980EC; assign wn_im[34] = 32'hE57D5FDA; // 34 0.978 -0.207 +assign wn_re[35] = 32'h7D0F4218; assign wn_im[35] = 32'hE4B8CD11; // 35 0.977 -0.213 +assign wn_re[36] = 32'h7CE3CEB2; assign wn_im[36] = 32'hE3F47D96; // 36 0.976 -0.219 +assign wn_re[37] = 32'h7CB72724; assign wn_im[37] = 32'hE330734D; // 37 0.974 -0.225 +assign wn_re[38] = 32'h7C894BDE; assign wn_im[38] = 32'hE26CB01B; // 38 0.973 -0.231 +assign wn_re[39] = 32'h7C5A3D50; assign wn_im[39] = 32'hE1A935E2; // 39 0.972 -0.237 +assign wn_re[40] = 32'h7C29FBEE; assign wn_im[40] = 32'hE0E60685; // 40 0.970 -0.243 +assign wn_re[41] = 32'h7BF88830; assign wn_im[41] = 32'hE02323E5; // 41 0.969 -0.249 +assign wn_re[42] = 32'h7BC5E290; assign wn_im[42] = 32'hDF608FE4; // 42 0.967 -0.255 +assign wn_re[43] = 32'h7B920B89; assign wn_im[43] = 32'hDE9E4C60; // 43 0.965 -0.261 +assign wn_re[44] = 32'h7B5D039E; assign wn_im[44] = 32'hDDDC5B3B; // 44 0.964 -0.267 +assign wn_re[45] = 32'h7B26CB4F; assign wn_im[45] = 32'hDD1ABE51; // 45 0.962 -0.273 +assign wn_re[46] = 32'h7AEF6323; assign wn_im[46] = 32'hDC597781; // 46 0.960 -0.279 +assign wn_re[47] = 32'h7AB6CBA4; assign wn_im[47] = 32'hDB9888A8; // 47 0.959 -0.284 +assign wn_re[48] = 32'h7A7D055B; assign wn_im[48] = 32'hDAD7F3A2; // 48 0.957 -0.290 +assign wn_re[49] = 32'h7A4210D8; assign wn_im[49] = 32'hDA17BA4A; // 49 0.955 -0.296 +assign wn_re[50] = 32'h7A05EEAD; assign wn_im[50] = 32'hD957DE7A; // 50 0.953 -0.302 +assign wn_re[51] = 32'h79C89F6E; assign wn_im[51] = 32'hD898620C; // 51 0.951 -0.308 +assign wn_re[52] = 32'h798A23B1; assign wn_im[52] = 32'hD7D946D8; // 52 0.950 -0.314 +assign wn_re[53] = 32'h794A7C12; assign wn_im[53] = 32'hD71A8EB5; // 53 0.948 -0.320 +assign wn_re[54] = 32'h7909A92D; assign wn_im[54] = 32'hD65C3B7B; // 54 0.946 -0.325 +assign wn_re[55] = 32'h78C7ABA2; assign wn_im[55] = 32'hD59E4EFF; // 55 0.944 -0.331 +assign wn_re[56] = 32'h78848414; assign wn_im[56] = 32'hD4E0CB15; // 56 0.942 -0.337 +assign wn_re[57] = 32'h78403329; assign wn_im[57] = 32'hD423B191; // 57 0.939 -0.343 +assign wn_re[58] = 32'h77FAB989; assign wn_im[58] = 32'hD3670446; // 58 0.937 -0.348 +assign wn_re[59] = 32'h77B417DF; assign wn_im[59] = 32'hD2AAC504; // 59 0.935 -0.354 +assign wn_re[60] = 32'h776C4EDB; assign wn_im[60] = 32'hD1EEF59E; // 60 0.933 -0.360 +assign wn_re[61] = 32'h77235F2D; assign wn_im[61] = 32'hD13397E2; // 61 0.931 -0.366 +assign wn_re[62] = 32'h76D94989; assign wn_im[62] = 32'hD078AD9E; // 62 0.929 -0.371 +assign wn_re[63] = 32'h768E0EA6; assign wn_im[63] = 32'hCFBE389F; // 63 0.926 -0.377 +assign wn_re[64] = 32'h7641AF3D; assign wn_im[64] = 32'hCF043AB3; // 64 0.924 -0.383 +assign wn_re[65] = 32'h75F42C0B; assign wn_im[65] = 32'hCE4AB5A2; // 65 0.922 -0.388 +assign wn_re[66] = 32'h75A585CF; assign wn_im[66] = 32'hCD91AB39; // 66 0.919 -0.394 +assign wn_re[67] = 32'h7555BD4C; assign wn_im[67] = 32'hCCD91D3D; // 67 0.917 -0.400 +assign wn_re[68] = 32'h7504D345; assign wn_im[68] = 32'hCC210D79; // 68 0.914 -0.405 +assign wn_re[69] = 32'h74B2C884; assign wn_im[69] = 32'hCB697DB0; // 69 0.912 -0.411 +assign wn_re[70] = 32'h745F9DD1; assign wn_im[70] = 32'hCAB26FA9; // 70 0.909 -0.416 +assign wn_re[71] = 32'h740B53FB; assign wn_im[71] = 32'hC9FBE527; // 71 0.907 -0.422 +assign wn_re[72] = 32'h73B5EBD1; assign wn_im[72] = 32'hC945DFEC; // 72 0.904 -0.428 +assign wn_re[73] = 32'h735F6626; assign wn_im[73] = 32'hC89061BA; // 73 0.901 -0.433 +assign wn_re[74] = 32'h7307C3D0; assign wn_im[74] = 32'hC7DB6C50; // 74 0.899 -0.439 +assign wn_re[75] = 32'h72AF05A7; assign wn_im[75] = 32'hC727016D; // 75 0.896 -0.444 +assign wn_re[76] = 32'h72552C85; assign wn_im[76] = 32'hC67322CE; // 76 0.893 -0.450 +assign wn_re[77] = 32'h71FA3949; assign wn_im[77] = 32'hC5BFD22E; // 77 0.890 -0.455 +assign wn_re[78] = 32'h719E2CD2; assign wn_im[78] = 32'hC50D1149; // 78 0.888 -0.461 +assign wn_re[79] = 32'h71410805; assign wn_im[79] = 32'hC45AE1D7; // 79 0.885 -0.466 +assign wn_re[80] = 32'h70E2CBC6; assign wn_im[80] = 32'hC3A94590; // 80 0.882 -0.471 +assign wn_re[81] = 32'h708378FF; assign wn_im[81] = 32'hC2F83E2A; // 81 0.879 -0.477 +assign wn_re[82] = 32'h7023109A; assign wn_im[82] = 32'hC247CD5A; // 82 0.876 -0.482 +assign wn_re[83] = 32'h6FC19385; assign wn_im[83] = 32'hC197F4D4; // 83 0.873 -0.488 +assign wn_re[84] = 32'h6F5F02B2; assign wn_im[84] = 32'hC0E8B648; // 84 0.870 -0.493 +assign wn_re[85] = 32'h6EFB5F12; assign wn_im[85] = 32'hC03A1368; // 85 0.867 -0.498 +assign wn_re[86] = 32'h6E96A99D; assign wn_im[86] = 32'hBF8C0DE3; // 86 0.864 -0.504 +assign wn_re[87] = 32'h6E30E34A; assign wn_im[87] = 32'hBEDEA765; // 87 0.861 -0.509 +assign wn_re[88] = 32'h6DCA0D14; assign wn_im[88] = 32'hBE31E19B; // 88 0.858 -0.514 +assign wn_re[89] = 32'h6D6227FA; assign wn_im[89] = 32'hBD85BE30; // 89 0.855 -0.519 +assign wn_re[90] = 32'h6CF934FC; assign wn_im[90] = 32'hBCDA3ECB; // 90 0.851 -0.525 +assign wn_re[91] = 32'h6C8F351C; assign wn_im[91] = 32'hBC2F6513; // 91 0.848 -0.530 +assign wn_re[92] = 32'h6C242960; assign wn_im[92] = 32'hBB8532B0; // 92 0.845 -0.535 +assign wn_re[93] = 32'h6BB812D1; assign wn_im[93] = 32'hBADBA943; // 93 0.842 -0.540 +assign wn_re[94] = 32'h6B4AF279; assign wn_im[94] = 32'hBA32CA71; // 94 0.838 -0.545 +assign wn_re[95] = 32'h6ADCC964; assign wn_im[95] = 32'hB98A97D8; // 95 0.835 -0.550 +assign wn_re[96] = 32'h6A6D98A4; assign wn_im[96] = 32'hB8E31319; // 96 0.831 -0.556 +assign wn_re[97] = 32'h69FD614A; assign wn_im[97] = 32'hB83C3DD1; // 97 0.828 -0.561 +assign wn_re[98] = 32'h698C246C; assign wn_im[98] = 32'hB796199B; // 98 0.825 -0.566 +assign wn_re[99] = 32'h6919E320; assign wn_im[99] = 32'hB6F0A812; // 99 0.821 -0.571 +assign wn_re[100] = 32'h68A69E81; assign wn_im[100] = 32'hB64BEACD; // 100 0.818 -0.576 +assign wn_re[101] = 32'h683257AB; assign wn_im[101] = 32'hB5A7E362; // 101 0.814 -0.581 +assign wn_re[102] = 32'h67BD0FBD; assign wn_im[102] = 32'hB5049368; // 102 0.810 -0.586 +assign wn_re[103] = 32'h6746C7D8; assign wn_im[103] = 32'hB461FC70; // 103 0.807 -0.591 +assign wn_re[104] = 32'h66CF8120; assign wn_im[104] = 32'hB3C0200C; // 104 0.803 -0.596 +assign wn_re[105] = 32'h66573CBB; assign wn_im[105] = 32'hB31EFFCC; // 105 0.800 -0.601 +assign wn_re[106] = 32'h65DDFBD3; assign wn_im[106] = 32'hB27E9D3C; // 106 0.796 -0.606 +assign wn_re[107] = 32'h6563BF92; assign wn_im[107] = 32'hB1DEF9E9; // 107 0.792 -0.610 +assign wn_re[108] = 32'h64E88926; assign wn_im[108] = 32'hB140175B; // 108 0.788 -0.615 +assign wn_re[109] = 32'h646C59BF; assign wn_im[109] = 32'hB0A1F71D; // 109 0.785 -0.620 +assign wn_re[110] = 32'h63EF3290; assign wn_im[110] = 32'hB0049AB3; // 110 0.781 -0.625 +assign wn_re[111] = 32'h637114CC; assign wn_im[111] = 32'hAF6803A2; // 111 0.777 -0.630 +assign wn_re[112] = 32'h62F201AC; assign wn_im[112] = 32'hAECC336C; // 112 0.773 -0.634 +assign wn_re[113] = 32'h6271FA69; assign wn_im[113] = 32'hAE312B92; // 113 0.769 -0.639 +assign wn_re[114] = 32'h61F1003F; assign wn_im[114] = 32'hAD96ED92; // 114 0.765 -0.644 +assign wn_re[115] = 32'h616F146C; assign wn_im[115] = 32'hACFD7AE8; // 115 0.761 -0.649 +assign wn_re[116] = 32'h60EC3830; assign wn_im[116] = 32'hAC64D510; // 116 0.757 -0.653 +assign wn_re[117] = 32'h60686CCF; assign wn_im[117] = 32'hABCCFD83; // 117 0.753 -0.658 +assign wn_re[118] = 32'h5FE3B38D; assign wn_im[118] = 32'hAB35F5B5; // 118 0.749 -0.662 +assign wn_re[119] = 32'h5F5E0DB3; assign wn_im[119] = 32'hAA9FBF1E; // 119 0.745 -0.667 +assign wn_re[120] = 32'h5ED77C8A; assign wn_im[120] = 32'hAA0A5B2E; // 120 0.741 -0.672 +assign wn_re[121] = 32'h5E50015D; assign wn_im[121] = 32'hA975CB57; // 121 0.737 -0.676 +assign wn_re[122] = 32'h5DC79D7C; assign wn_im[122] = 32'hA8E21106; // 122 0.733 -0.681 +assign wn_re[123] = 32'h5D3E5237; assign wn_im[123] = 32'hA84F2DAA; // 123 0.728 -0.685 +assign wn_re[124] = 32'h5CB420E0; assign wn_im[124] = 32'hA7BD22AC; // 124 0.724 -0.690 +assign wn_re[125] = 32'h5C290ACC; assign wn_im[125] = 32'hA72BF174; // 125 0.720 -0.694 +assign wn_re[126] = 32'h5B9D1154; assign wn_im[126] = 32'hA69B9B68; // 126 0.716 -0.698 +assign wn_re[127] = 32'h5B1035CF; assign wn_im[127] = 32'hA60C21EE; // 127 0.711 -0.703 +assign wn_re[128] = 32'h5A82799A; assign wn_im[128] = 32'hA57D8666; // 128 0.707 -0.707 +assign wn_re[129] = 32'h59F3DE12; assign wn_im[129] = 32'hA4EFCA31; // 129 0.703 -0.711 +assign wn_re[130] = 32'h59646498; assign wn_im[130] = 32'hA462EEAC; // 130 0.698 -0.716 +assign wn_re[131] = 32'h58D40E8C; assign wn_im[131] = 32'hA3D6F534; // 131 0.694 -0.720 +assign wn_re[132] = 32'h5842DD54; assign wn_im[132] = 32'hA34BDF20; // 132 0.690 -0.724 +assign wn_re[133] = 32'h57B0D256; assign wn_im[133] = 32'hA2C1ADC9; // 133 0.685 -0.728 +assign wn_re[134] = 32'h571DEEFA; assign wn_im[134] = 32'hA2386284; // 134 0.681 -0.733 +assign wn_re[135] = 32'h568A34A9; assign wn_im[135] = 32'hA1AFFEA3; // 135 0.676 -0.737 +assign wn_re[136] = 32'h55F5A4D2; assign wn_im[136] = 32'hA1288376; // 136 0.672 -0.741 +assign wn_re[137] = 32'h556040E2; assign wn_im[137] = 32'hA0A1F24D; // 137 0.667 -0.745 +assign wn_re[138] = 32'h54CA0A4B; assign wn_im[138] = 32'hA01C4C73; // 138 0.662 -0.749 +assign wn_re[139] = 32'h5433027D; assign wn_im[139] = 32'h9F979331; // 139 0.658 -0.753 +assign wn_re[140] = 32'h539B2AF0; assign wn_im[140] = 32'h9F13C7D0; // 140 0.653 -0.757 +assign wn_re[141] = 32'h53028518; assign wn_im[141] = 32'h9E90EB94; // 141 0.649 -0.761 +assign wn_re[142] = 32'h5269126E; assign wn_im[142] = 32'h9E0EFFC1; // 142 0.644 -0.765 +assign wn_re[143] = 32'h51CED46E; assign wn_im[143] = 32'h9D8E0597; // 143 0.639 -0.769 +assign wn_re[144] = 32'h5133CC94; assign wn_im[144] = 32'h9D0DFE54; // 144 0.634 -0.773 +assign wn_re[145] = 32'h5097FC5E; assign wn_im[145] = 32'h9C8EEB34; // 145 0.630 -0.777 +assign wn_re[146] = 32'h4FFB654D; assign wn_im[146] = 32'h9C10CD70; // 146 0.625 -0.781 +assign wn_re[147] = 32'h4F5E08E3; assign wn_im[147] = 32'h9B93A641; // 147 0.620 -0.785 +assign wn_re[148] = 32'h4EBFE8A5; assign wn_im[148] = 32'h9B1776DA; // 148 0.615 -0.788 +assign wn_re[149] = 32'h4E210617; assign wn_im[149] = 32'h9A9C406E; // 149 0.610 -0.792 +assign wn_re[150] = 32'h4D8162C4; assign wn_im[150] = 32'h9A22042D; // 150 0.606 -0.796 +assign wn_re[151] = 32'h4CE10034; assign wn_im[151] = 32'h99A8C345; // 151 0.601 -0.800 +assign wn_re[152] = 32'h4C3FDFF4; assign wn_im[152] = 32'h99307EE0; // 152 0.596 -0.803 +assign wn_re[153] = 32'h4B9E0390; assign wn_im[153] = 32'h98B93828; // 153 0.591 -0.807 +assign wn_re[154] = 32'h4AFB6C98; assign wn_im[154] = 32'h9842F043; // 154 0.586 -0.810 +assign wn_re[155] = 32'h4A581C9E; assign wn_im[155] = 32'h97CDA855; // 155 0.581 -0.814 +assign wn_re[156] = 32'h49B41533; assign wn_im[156] = 32'h9759617F; // 156 0.576 -0.818 +assign wn_re[157] = 32'h490F57EE; assign wn_im[157] = 32'h96E61CE0; // 157 0.571 -0.821 +assign wn_re[158] = 32'h4869E665; assign wn_im[158] = 32'h9673DB94; // 158 0.566 -0.825 +assign wn_re[159] = 32'h47C3C22F; assign wn_im[159] = 32'h96029EB6; // 159 0.561 -0.828 +assign wn_re[160] = 32'h471CECE7; assign wn_im[160] = 32'h9592675C; // 160 0.556 -0.831 +assign wn_re[161] = 32'h46756828; assign wn_im[161] = 32'h9523369C; // 161 0.550 -0.835 +assign wn_re[162] = 32'h45CD358F; assign wn_im[162] = 32'h94B50D87; // 162 0.545 -0.838 +assign wn_re[163] = 32'h452456BD; assign wn_im[163] = 32'h9447ED2F; // 163 0.540 -0.842 +assign wn_re[164] = 32'h447ACD50; assign wn_im[164] = 32'h93DBD6A0; // 164 0.535 -0.845 +assign wn_re[165] = 32'h43D09AED; assign wn_im[165] = 32'h9370CAE4; // 165 0.530 -0.848 +assign wn_re[166] = 32'h4325C135; assign wn_im[166] = 32'h9306CB04; // 166 0.525 -0.851 +assign wn_re[167] = 32'h427A41D0; assign wn_im[167] = 32'h929DD806; // 167 0.519 -0.855 +assign wn_re[168] = 32'h41CE1E65; assign wn_im[168] = 32'h9235F2EC; // 168 0.514 -0.858 +assign wn_re[169] = 32'h4121589B; assign wn_im[169] = 32'h91CF1CB6; // 169 0.509 -0.861 +assign wn_re[170] = 32'h4073F21D; assign wn_im[170] = 32'h91695663; // 170 0.504 -0.864 +assign wn_re[171] = 32'h3FC5EC98; assign wn_im[171] = 32'h9104A0EE; // 171 0.498 -0.867 +assign wn_re[172] = 32'h3F1749B8; assign wn_im[172] = 32'h90A0FD4E; // 172 0.493 -0.870 +assign wn_re[173] = 32'h3E680B2C; assign wn_im[173] = 32'h903E6C7B; // 173 0.488 -0.873 +assign wn_re[174] = 32'h3DB832A6; assign wn_im[174] = 32'h8FDCEF66; // 174 0.482 -0.876 +assign wn_re[175] = 32'h3D07C1D6; assign wn_im[175] = 32'h8F7C8701; // 175 0.477 -0.879 +assign wn_re[176] = 32'h3C56BA70; assign wn_im[176] = 32'h8F1D343A; // 176 0.471 -0.882 +assign wn_re[177] = 32'h3BA51E29; assign wn_im[177] = 32'h8EBEF7FB; // 177 0.466 -0.885 +assign wn_re[178] = 32'h3AF2EEB7; assign wn_im[178] = 32'h8E61D32E; // 178 0.461 -0.888 +assign wn_re[179] = 32'h3A402DD2; assign wn_im[179] = 32'h8E05C6B7; // 179 0.455 -0.890 +assign wn_re[180] = 32'h398CDD32; assign wn_im[180] = 32'h8DAAD37B; // 180 0.450 -0.893 +assign wn_re[181] = 32'h38D8FE93; assign wn_im[181] = 32'h8D50FA59; // 181 0.444 -0.896 +assign wn_re[182] = 32'h382493B0; assign wn_im[182] = 32'h8CF83C30; // 182 0.439 -0.899 +assign wn_re[183] = 32'h376F9E46; assign wn_im[183] = 32'h8CA099DA; // 183 0.433 -0.901 +assign wn_re[184] = 32'h36BA2014; assign wn_im[184] = 32'h8C4A142F; // 184 0.428 -0.904 +assign wn_re[185] = 32'h36041AD9; assign wn_im[185] = 32'h8BF4AC05; // 185 0.422 -0.907 +assign wn_re[186] = 32'h354D9057; assign wn_im[186] = 32'h8BA0622F; // 186 0.416 -0.909 +assign wn_re[187] = 32'h34968250; assign wn_im[187] = 32'h8B4D377C; // 187 0.411 -0.912 +assign wn_re[188] = 32'h33DEF287; assign wn_im[188] = 32'h8AFB2CBB; // 188 0.405 -0.914 +assign wn_re[189] = 32'h3326E2C3; assign wn_im[189] = 32'h8AAA42B4; // 189 0.400 -0.917 +assign wn_re[190] = 32'h326E54C7; assign wn_im[190] = 32'h8A5A7A31; // 190 0.394 -0.919 +assign wn_re[191] = 32'h31B54A5E; assign wn_im[191] = 32'h8A0BD3F5; // 191 0.388 -0.922 +assign wn_re[192] = 32'h30FBC54D; assign wn_im[192] = 32'h89BE50C3; // 192 0.383 -0.924 +assign wn_re[193] = 32'h3041C761; assign wn_im[193] = 32'h8971F15A; // 193 0.377 -0.926 +assign wn_re[194] = 32'h2F875262; assign wn_im[194] = 32'h8926B677; // 194 0.371 -0.929 +assign wn_re[195] = 32'h2ECC681E; assign wn_im[195] = 32'h88DCA0D3; // 195 0.366 -0.931 +assign wn_re[196] = 32'h2E110A62; assign wn_im[196] = 32'h8893B125; // 196 0.360 -0.933 +assign wn_re[197] = 32'h2D553AFC; assign wn_im[197] = 32'h884BE821; // 197 0.354 -0.935 +assign wn_re[198] = 32'h2C98FBBA; assign wn_im[198] = 32'h88054677; // 198 0.348 -0.937 +assign wn_re[199] = 32'h2BDC4E6F; assign wn_im[199] = 32'h87BFCCD7; // 199 0.343 -0.939 +assign wn_re[200] = 32'h2B1F34EB; assign wn_im[200] = 32'h877B7BEC; // 200 0.337 -0.942 +assign wn_re[201] = 32'h2A61B101; assign wn_im[201] = 32'h8738545E; // 201 0.331 -0.944 +assign wn_re[202] = 32'h29A3C485; assign wn_im[202] = 32'h86F656D3; // 202 0.325 -0.946 +assign wn_re[203] = 32'h28E5714B; assign wn_im[203] = 32'h86B583EE; // 203 0.320 -0.948 +assign wn_re[204] = 32'h2826B928; assign wn_im[204] = 32'h8675DC4F; // 204 0.314 -0.950 +assign wn_re[205] = 32'h27679DF4; assign wn_im[205] = 32'h86376092; // 205 0.308 -0.951 +assign wn_re[206] = 32'h26A82186; assign wn_im[206] = 32'h85FA1153; // 206 0.302 -0.953 +assign wn_re[207] = 32'h25E845B6; assign wn_im[207] = 32'h85BDEF28; // 207 0.296 -0.955 +assign wn_re[208] = 32'h25280C5E; assign wn_im[208] = 32'h8582FAA5; // 208 0.290 -0.957 +assign wn_re[209] = 32'h24677758; assign wn_im[209] = 32'h8549345C; // 209 0.284 -0.959 +assign wn_re[210] = 32'h23A6887F; assign wn_im[210] = 32'h85109CDD; // 210 0.279 -0.960 +assign wn_re[211] = 32'h22E541AF; assign wn_im[211] = 32'h84D934B1; // 211 0.273 -0.962 +assign wn_re[212] = 32'h2223A4C5; assign wn_im[212] = 32'h84A2FC62; // 212 0.267 -0.964 +assign wn_re[213] = 32'h2161B3A0; assign wn_im[213] = 32'h846DF477; // 213 0.261 -0.965 +assign wn_re[214] = 32'h209F701C; assign wn_im[214] = 32'h843A1D70; // 214 0.255 -0.967 +assign wn_re[215] = 32'h1FDCDC1B; assign wn_im[215] = 32'h840777D0; // 215 0.249 -0.969 +assign wn_re[216] = 32'h1F19F97B; assign wn_im[216] = 32'h83D60412; // 216 0.243 -0.970 +assign wn_re[217] = 32'h1E56CA1E; assign wn_im[217] = 32'h83A5C2B0; // 217 0.237 -0.972 +assign wn_re[218] = 32'h1D934FE5; assign wn_im[218] = 32'h8376B422; // 218 0.231 -0.973 +assign wn_re[219] = 32'h1CCF8CB3; assign wn_im[219] = 32'h8348D8DC; // 219 0.225 -0.974 +assign wn_re[220] = 32'h1C0B826A; assign wn_im[220] = 32'h831C314E; // 220 0.219 -0.976 +assign wn_re[221] = 32'h1B4732EF; assign wn_im[221] = 32'h82F0BDE8; // 221 0.213 -0.977 +assign wn_re[222] = 32'h1A82A026; assign wn_im[222] = 32'h82C67F14; // 222 0.207 -0.978 +assign wn_re[223] = 32'h19BDCBF3; assign wn_im[223] = 32'h829D753A; // 223 0.201 -0.980 +assign wn_re[224] = 32'h18F8B83C; assign wn_im[224] = 32'h8275A0C0; // 224 0.195 -0.981 +assign wn_re[225] = 32'h183366E9; assign wn_im[225] = 32'h824F0208; // 225 0.189 -0.982 +assign wn_re[226] = 32'h176DD9DE; assign wn_im[226] = 32'h82299971; // 226 0.183 -0.983 +assign wn_re[227] = 32'h16A81305; assign wn_im[227] = 32'h82056758; // 227 0.177 -0.984 +assign wn_re[228] = 32'h15E21445; assign wn_im[228] = 32'h81E26C16; // 228 0.171 -0.985 +assign wn_re[229] = 32'h151BDF86; assign wn_im[229] = 32'h81C0A801; // 229 0.165 -0.986 +assign wn_re[230] = 32'h145576B1; assign wn_im[230] = 32'h81A01B6D; // 230 0.159 -0.987 +assign wn_re[231] = 32'h138EDBB1; assign wn_im[231] = 32'h8180C6A9; // 231 0.153 -0.988 +assign wn_re[232] = 32'h12C8106F; assign wn_im[232] = 32'h8162AA04; // 232 0.147 -0.989 +assign wn_re[233] = 32'h120116D5; assign wn_im[233] = 32'h8145C5C7; // 233 0.141 -0.990 +assign wn_re[234] = 32'h1139F0CF; assign wn_im[234] = 32'h812A1A3A; // 234 0.135 -0.991 +assign wn_re[235] = 32'h1072A048; assign wn_im[235] = 32'h810FA7A0; // 235 0.128 -0.992 +assign wn_re[236] = 32'h0FAB272B; assign wn_im[236] = 32'h80F66E3C; // 236 0.122 -0.992 +assign wn_re[237] = 32'h0EE38766; assign wn_im[237] = 32'h80DE6E4C; // 237 0.116 -0.993 +assign wn_re[238] = 32'h0E1BC2E4; assign wn_im[238] = 32'h80C7A80A; // 238 0.110 -0.994 +assign wn_re[239] = 32'h0D53DB92; assign wn_im[239] = 32'h80B21BAF; // 239 0.104 -0.995 +assign wn_re[240] = 32'h0C8BD35E; assign wn_im[240] = 32'h809DC971; // 240 0.098 -0.995 +assign wn_re[241] = 32'h0BC3AC35; assign wn_im[241] = 32'h808AB180; // 241 0.092 -0.996 +assign wn_re[242] = 32'h0AFB6805; assign wn_im[242] = 32'h8078D40D; // 242 0.086 -0.996 +assign wn_re[243] = 32'h0A3308BD; assign wn_im[243] = 32'h80683143; // 243 0.080 -0.997 +assign wn_re[244] = 32'h096A9049; assign wn_im[244] = 32'h8058C94C; // 244 0.074 -0.997 +assign wn_re[245] = 32'h08A2009A; assign wn_im[245] = 32'h804A9C4D; // 245 0.067 -0.998 +assign wn_re[246] = 32'h07D95B9E; assign wn_im[246] = 32'h803DAA6A; // 246 0.061 -0.998 +assign wn_re[247] = 32'h0710A345; assign wn_im[247] = 32'h8031F3C2; // 247 0.055 -0.998 +assign wn_re[248] = 32'h0647D97C; assign wn_im[248] = 32'h80277872; // 248 0.049 -0.999 +assign wn_re[249] = 32'h057F0035; assign wn_im[249] = 32'h801E3895; // 249 0.043 -0.999 +assign wn_re[250] = 32'h04B6195D; assign wn_im[250] = 32'h80163440; // 250 0.037 -0.999 +assign wn_re[251] = 32'h03ED26E6; assign wn_im[251] = 32'h800F6B88; // 251 0.031 -1.000 +assign wn_re[252] = 32'h03242ABF; assign wn_im[252] = 32'h8009DE7E; // 252 0.025 -1.000 +assign wn_re[253] = 32'h025B26D7; assign wn_im[253] = 32'h80058D2F; // 253 0.018 -1.000 +assign wn_re[254] = 32'h01921D20; assign wn_im[254] = 32'h800277A6; // 254 0.012 -1.000 +assign wn_re[255] = 32'h00C90F88; assign wn_im[255] = 32'h80009DEA; // 255 0.006 -1.000 +assign wn_re[256] = 32'h00000000; assign wn_im[256] = 32'h80000000; // 256 0.000 -1.000 +assign wn_re[257] = 32'hxxxxxxxx; assign wn_im[257] = 32'hxxxxxxxx; // 257 -0.006 -1.000 +assign wn_re[258] = 32'hFE6DE2E0; assign wn_im[258] = 32'h800277A6; // 258 -0.012 -1.000 +assign wn_re[259] = 32'hxxxxxxxx; assign wn_im[259] = 32'hxxxxxxxx; // 259 -0.018 -1.000 +assign wn_re[260] = 32'hFCDBD541; assign wn_im[260] = 32'h8009DE7E; // 260 -0.025 -1.000 +assign wn_re[261] = 32'hFC12D91A; assign wn_im[261] = 32'h800F6B88; // 261 -0.031 -1.000 +assign wn_re[262] = 32'hFB49E6A3; assign wn_im[262] = 32'h80163440; // 262 -0.037 -0.999 +assign wn_re[263] = 32'hxxxxxxxx; assign wn_im[263] = 32'hxxxxxxxx; // 263 -0.043 -0.999 +assign wn_re[264] = 32'hF9B82684; assign wn_im[264] = 32'h80277872; // 264 -0.049 -0.999 +assign wn_re[265] = 32'hxxxxxxxx; assign wn_im[265] = 32'hxxxxxxxx; // 265 -0.055 -0.998 +assign wn_re[266] = 32'hF826A462; assign wn_im[266] = 32'h803DAA6A; // 266 -0.061 -0.998 +assign wn_re[267] = 32'hF75DFF66; assign wn_im[267] = 32'h804A9C4D; // 267 -0.067 -0.998 +assign wn_re[268] = 32'hF6956FB7; assign wn_im[268] = 32'h8058C94C; // 268 -0.074 -0.997 +assign wn_re[269] = 32'hxxxxxxxx; assign wn_im[269] = 32'hxxxxxxxx; // 269 -0.080 -0.997 +assign wn_re[270] = 32'hF50497FB; assign wn_im[270] = 32'h8078D40D; // 270 -0.086 -0.996 +assign wn_re[271] = 32'hxxxxxxxx; assign wn_im[271] = 32'hxxxxxxxx; // 271 -0.092 -0.996 +assign wn_re[272] = 32'hF3742CA2; assign wn_im[272] = 32'h809DC971; // 272 -0.098 -0.995 +assign wn_re[273] = 32'hF2AC246E; assign wn_im[273] = 32'h80B21BAF; // 273 -0.104 -0.995 +assign wn_re[274] = 32'hF1E43D1C; assign wn_im[274] = 32'h80C7A80A; // 274 -0.110 -0.994 +assign wn_re[275] = 32'hxxxxxxxx; assign wn_im[275] = 32'hxxxxxxxx; // 275 -0.116 -0.993 +assign wn_re[276] = 32'hF054D8D5; assign wn_im[276] = 32'h80F66E3C; // 276 -0.122 -0.992 +assign wn_re[277] = 32'hxxxxxxxx; assign wn_im[277] = 32'hxxxxxxxx; // 277 -0.128 -0.992 +assign wn_re[278] = 32'hEEC60F31; assign wn_im[278] = 32'h812A1A3A; // 278 -0.135 -0.991 +assign wn_re[279] = 32'hEDFEE92B; assign wn_im[279] = 32'h8145C5C7; // 279 -0.141 -0.990 +assign wn_re[280] = 32'hED37EF91; assign wn_im[280] = 32'h8162AA04; // 280 -0.147 -0.989 +assign wn_re[281] = 32'hxxxxxxxx; assign wn_im[281] = 32'hxxxxxxxx; // 281 -0.153 -0.988 +assign wn_re[282] = 32'hEBAA894F; assign wn_im[282] = 32'h81A01B6D; // 282 -0.159 -0.987 +assign wn_re[283] = 32'hxxxxxxxx; assign wn_im[283] = 32'hxxxxxxxx; // 283 -0.165 -0.986 +assign wn_re[284] = 32'hEA1DEBBB; assign wn_im[284] = 32'h81E26C16; // 284 -0.171 -0.985 +assign wn_re[285] = 32'hE957ECFB; assign wn_im[285] = 32'h82056758; // 285 -0.177 -0.984 +assign wn_re[286] = 32'hE8922622; assign wn_im[286] = 32'h82299971; // 286 -0.183 -0.983 +assign wn_re[287] = 32'hxxxxxxxx; assign wn_im[287] = 32'hxxxxxxxx; // 287 -0.189 -0.982 +assign wn_re[288] = 32'hE70747C4; assign wn_im[288] = 32'h8275A0C0; // 288 -0.195 -0.981 +assign wn_re[289] = 32'hxxxxxxxx; assign wn_im[289] = 32'hxxxxxxxx; // 289 -0.201 -0.980 +assign wn_re[290] = 32'hE57D5FDA; assign wn_im[290] = 32'h82C67F14; // 290 -0.207 -0.978 +assign wn_re[291] = 32'hE4B8CD11; assign wn_im[291] = 32'h82F0BDE8; // 291 -0.213 -0.977 +assign wn_re[292] = 32'hE3F47D96; assign wn_im[292] = 32'h831C314E; // 292 -0.219 -0.976 +assign wn_re[293] = 32'hxxxxxxxx; assign wn_im[293] = 32'hxxxxxxxx; // 293 -0.225 -0.974 +assign wn_re[294] = 32'hE26CB01B; assign wn_im[294] = 32'h8376B422; // 294 -0.231 -0.973 +assign wn_re[295] = 32'hxxxxxxxx; assign wn_im[295] = 32'hxxxxxxxx; // 295 -0.237 -0.972 +assign wn_re[296] = 32'hE0E60685; assign wn_im[296] = 32'h83D60412; // 296 -0.243 -0.970 +assign wn_re[297] = 32'hE02323E5; assign wn_im[297] = 32'h840777D0; // 297 -0.249 -0.969 +assign wn_re[298] = 32'hDF608FE4; assign wn_im[298] = 32'h843A1D70; // 298 -0.255 -0.967 +assign wn_re[299] = 32'hxxxxxxxx; assign wn_im[299] = 32'hxxxxxxxx; // 299 -0.261 -0.965 +assign wn_re[300] = 32'hDDDC5B3B; assign wn_im[300] = 32'h84A2FC62; // 300 -0.267 -0.964 +assign wn_re[301] = 32'hxxxxxxxx; assign wn_im[301] = 32'hxxxxxxxx; // 301 -0.273 -0.962 +assign wn_re[302] = 32'hDC597781; assign wn_im[302] = 32'h85109CDD; // 302 -0.279 -0.960 +assign wn_re[303] = 32'hDB9888A8; assign wn_im[303] = 32'h8549345C; // 303 -0.284 -0.959 +assign wn_re[304] = 32'hDAD7F3A2; assign wn_im[304] = 32'h8582FAA5; // 304 -0.290 -0.957 +assign wn_re[305] = 32'hxxxxxxxx; assign wn_im[305] = 32'hxxxxxxxx; // 305 -0.296 -0.955 +assign wn_re[306] = 32'hD957DE7A; assign wn_im[306] = 32'h85FA1153; // 306 -0.302 -0.953 +assign wn_re[307] = 32'hxxxxxxxx; assign wn_im[307] = 32'hxxxxxxxx; // 307 -0.308 -0.951 +assign wn_re[308] = 32'hD7D946D8; assign wn_im[308] = 32'h8675DC4F; // 308 -0.314 -0.950 +assign wn_re[309] = 32'hD71A8EB5; assign wn_im[309] = 32'h86B583EE; // 309 -0.320 -0.948 +assign wn_re[310] = 32'hD65C3B7B; assign wn_im[310] = 32'h86F656D3; // 310 -0.325 -0.946 +assign wn_re[311] = 32'hxxxxxxxx; assign wn_im[311] = 32'hxxxxxxxx; // 311 -0.331 -0.944 +assign wn_re[312] = 32'hD4E0CB15; assign wn_im[312] = 32'h877B7BEC; // 312 -0.337 -0.942 +assign wn_re[313] = 32'hxxxxxxxx; assign wn_im[313] = 32'hxxxxxxxx; // 313 -0.343 -0.939 +assign wn_re[314] = 32'hD3670446; assign wn_im[314] = 32'h88054677; // 314 -0.348 -0.937 +assign wn_re[315] = 32'hD2AAC504; assign wn_im[315] = 32'h884BE821; // 315 -0.354 -0.935 +assign wn_re[316] = 32'hD1EEF59E; assign wn_im[316] = 32'h8893B125; // 316 -0.360 -0.933 +assign wn_re[317] = 32'hxxxxxxxx; assign wn_im[317] = 32'hxxxxxxxx; // 317 -0.366 -0.931 +assign wn_re[318] = 32'hD078AD9E; assign wn_im[318] = 32'h8926B677; // 318 -0.371 -0.929 +assign wn_re[319] = 32'hxxxxxxxx; assign wn_im[319] = 32'hxxxxxxxx; // 319 -0.377 -0.926 +assign wn_re[320] = 32'hCF043AB3; assign wn_im[320] = 32'h89BE50C3; // 320 -0.383 -0.924 +assign wn_re[321] = 32'hCE4AB5A2; assign wn_im[321] = 32'h8A0BD3F5; // 321 -0.388 -0.922 +assign wn_re[322] = 32'hCD91AB39; assign wn_im[322] = 32'h8A5A7A31; // 322 -0.394 -0.919 +assign wn_re[323] = 32'hxxxxxxxx; assign wn_im[323] = 32'hxxxxxxxx; // 323 -0.400 -0.917 +assign wn_re[324] = 32'hCC210D79; assign wn_im[324] = 32'h8AFB2CBB; // 324 -0.405 -0.914 +assign wn_re[325] = 32'hxxxxxxxx; assign wn_im[325] = 32'hxxxxxxxx; // 325 -0.411 -0.912 +assign wn_re[326] = 32'hCAB26FA9; assign wn_im[326] = 32'h8BA0622F; // 326 -0.416 -0.909 +assign wn_re[327] = 32'hC9FBE527; assign wn_im[327] = 32'h8BF4AC05; // 327 -0.422 -0.907 +assign wn_re[328] = 32'hC945DFEC; assign wn_im[328] = 32'h8C4A142F; // 328 -0.428 -0.904 +assign wn_re[329] = 32'hxxxxxxxx; assign wn_im[329] = 32'hxxxxxxxx; // 329 -0.433 -0.901 +assign wn_re[330] = 32'hC7DB6C50; assign wn_im[330] = 32'h8CF83C30; // 330 -0.439 -0.899 +assign wn_re[331] = 32'hxxxxxxxx; assign wn_im[331] = 32'hxxxxxxxx; // 331 -0.444 -0.896 +assign wn_re[332] = 32'hC67322CE; assign wn_im[332] = 32'h8DAAD37B; // 332 -0.450 -0.893 +assign wn_re[333] = 32'hC5BFD22E; assign wn_im[333] = 32'h8E05C6B7; // 333 -0.455 -0.890 +assign wn_re[334] = 32'hC50D1149; assign wn_im[334] = 32'h8E61D32E; // 334 -0.461 -0.888 +assign wn_re[335] = 32'hxxxxxxxx; assign wn_im[335] = 32'hxxxxxxxx; // 335 -0.466 -0.885 +assign wn_re[336] = 32'hC3A94590; assign wn_im[336] = 32'h8F1D343A; // 336 -0.471 -0.882 +assign wn_re[337] = 32'hxxxxxxxx; assign wn_im[337] = 32'hxxxxxxxx; // 337 -0.477 -0.879 +assign wn_re[338] = 32'hC247CD5A; assign wn_im[338] = 32'h8FDCEF66; // 338 -0.482 -0.876 +assign wn_re[339] = 32'hC197F4D4; assign wn_im[339] = 32'h903E6C7B; // 339 -0.488 -0.873 +assign wn_re[340] = 32'hC0E8B648; assign wn_im[340] = 32'h90A0FD4E; // 340 -0.493 -0.870 +assign wn_re[341] = 32'hxxxxxxxx; assign wn_im[341] = 32'hxxxxxxxx; // 341 -0.498 -0.867 +assign wn_re[342] = 32'hBF8C0DE3; assign wn_im[342] = 32'h91695663; // 342 -0.504 -0.864 +assign wn_re[343] = 32'hxxxxxxxx; assign wn_im[343] = 32'hxxxxxxxx; // 343 -0.509 -0.861 +assign wn_re[344] = 32'hBE31E19B; assign wn_im[344] = 32'h9235F2EC; // 344 -0.514 -0.858 +assign wn_re[345] = 32'hBD85BE30; assign wn_im[345] = 32'h929DD806; // 345 -0.519 -0.855 +assign wn_re[346] = 32'hBCDA3ECB; assign wn_im[346] = 32'h9306CB04; // 346 -0.525 -0.851 +assign wn_re[347] = 32'hxxxxxxxx; assign wn_im[347] = 32'hxxxxxxxx; // 347 -0.530 -0.848 +assign wn_re[348] = 32'hBB8532B0; assign wn_im[348] = 32'h93DBD6A0; // 348 -0.535 -0.845 +assign wn_re[349] = 32'hxxxxxxxx; assign wn_im[349] = 32'hxxxxxxxx; // 349 -0.540 -0.842 +assign wn_re[350] = 32'hBA32CA71; assign wn_im[350] = 32'h94B50D87; // 350 -0.545 -0.838 +assign wn_re[351] = 32'hB98A97D8; assign wn_im[351] = 32'h9523369C; // 351 -0.550 -0.835 +assign wn_re[352] = 32'hB8E31319; assign wn_im[352] = 32'h9592675C; // 352 -0.556 -0.831 +assign wn_re[353] = 32'hxxxxxxxx; assign wn_im[353] = 32'hxxxxxxxx; // 353 -0.561 -0.828 +assign wn_re[354] = 32'hB796199B; assign wn_im[354] = 32'h9673DB94; // 354 -0.566 -0.825 +assign wn_re[355] = 32'hxxxxxxxx; assign wn_im[355] = 32'hxxxxxxxx; // 355 -0.571 -0.821 +assign wn_re[356] = 32'hB64BEACD; assign wn_im[356] = 32'h9759617F; // 356 -0.576 -0.818 +assign wn_re[357] = 32'hB5A7E362; assign wn_im[357] = 32'h97CDA855; // 357 -0.581 -0.814 +assign wn_re[358] = 32'hB5049368; assign wn_im[358] = 32'h9842F043; // 358 -0.586 -0.810 +assign wn_re[359] = 32'hxxxxxxxx; assign wn_im[359] = 32'hxxxxxxxx; // 359 -0.591 -0.807 +assign wn_re[360] = 32'hB3C0200C; assign wn_im[360] = 32'h99307EE0; // 360 -0.596 -0.803 +assign wn_re[361] = 32'hxxxxxxxx; assign wn_im[361] = 32'hxxxxxxxx; // 361 -0.601 -0.800 +assign wn_re[362] = 32'hB27E9D3C; assign wn_im[362] = 32'h9A22042D; // 362 -0.606 -0.796 +assign wn_re[363] = 32'hB1DEF9E9; assign wn_im[363] = 32'h9A9C406E; // 363 -0.610 -0.792 +assign wn_re[364] = 32'hB140175B; assign wn_im[364] = 32'h9B1776DA; // 364 -0.615 -0.788 +assign wn_re[365] = 32'hxxxxxxxx; assign wn_im[365] = 32'hxxxxxxxx; // 365 -0.620 -0.785 +assign wn_re[366] = 32'hB0049AB3; assign wn_im[366] = 32'h9C10CD70; // 366 -0.625 -0.781 +assign wn_re[367] = 32'hxxxxxxxx; assign wn_im[367] = 32'hxxxxxxxx; // 367 -0.630 -0.777 +assign wn_re[368] = 32'hAECC336C; assign wn_im[368] = 32'h9D0DFE54; // 368 -0.634 -0.773 +assign wn_re[369] = 32'hAE312B92; assign wn_im[369] = 32'h9D8E0597; // 369 -0.639 -0.769 +assign wn_re[370] = 32'hAD96ED92; assign wn_im[370] = 32'h9E0EFFC1; // 370 -0.644 -0.765 +assign wn_re[371] = 32'hxxxxxxxx; assign wn_im[371] = 32'hxxxxxxxx; // 371 -0.649 -0.761 +assign wn_re[372] = 32'hAC64D510; assign wn_im[372] = 32'h9F13C7D0; // 372 -0.653 -0.757 +assign wn_re[373] = 32'hxxxxxxxx; assign wn_im[373] = 32'hxxxxxxxx; // 373 -0.658 -0.753 +assign wn_re[374] = 32'hAB35F5B5; assign wn_im[374] = 32'hA01C4C73; // 374 -0.662 -0.749 +assign wn_re[375] = 32'hAA9FBF1E; assign wn_im[375] = 32'hA0A1F24D; // 375 -0.667 -0.745 +assign wn_re[376] = 32'hAA0A5B2E; assign wn_im[376] = 32'hA1288376; // 376 -0.672 -0.741 +assign wn_re[377] = 32'hxxxxxxxx; assign wn_im[377] = 32'hxxxxxxxx; // 377 -0.676 -0.737 +assign wn_re[378] = 32'hA8E21106; assign wn_im[378] = 32'hA2386284; // 378 -0.681 -0.733 +assign wn_re[379] = 32'hxxxxxxxx; assign wn_im[379] = 32'hxxxxxxxx; // 379 -0.685 -0.728 +assign wn_re[380] = 32'hA7BD22AC; assign wn_im[380] = 32'hA34BDF20; // 380 -0.690 -0.724 +assign wn_re[381] = 32'hA72BF174; assign wn_im[381] = 32'hA3D6F534; // 381 -0.694 -0.720 +assign wn_re[382] = 32'hA69B9B68; assign wn_im[382] = 32'hA462EEAC; // 382 -0.698 -0.716 +assign wn_re[383] = 32'hxxxxxxxx; assign wn_im[383] = 32'hxxxxxxxx; // 383 -0.703 -0.711 +assign wn_re[384] = 32'hA57D8666; assign wn_im[384] = 32'hA57D8666; // 384 -0.707 -0.707 +assign wn_re[385] = 32'hxxxxxxxx; assign wn_im[385] = 32'hxxxxxxxx; // 385 -0.711 -0.703 +assign wn_re[386] = 32'hA462EEAC; assign wn_im[386] = 32'hA69B9B68; // 386 -0.716 -0.698 +assign wn_re[387] = 32'hA3D6F534; assign wn_im[387] = 32'hA72BF174; // 387 -0.720 -0.694 +assign wn_re[388] = 32'hA34BDF20; assign wn_im[388] = 32'hA7BD22AC; // 388 -0.724 -0.690 +assign wn_re[389] = 32'hxxxxxxxx; assign wn_im[389] = 32'hxxxxxxxx; // 389 -0.728 -0.685 +assign wn_re[390] = 32'hA2386284; assign wn_im[390] = 32'hA8E21106; // 390 -0.733 -0.681 +assign wn_re[391] = 32'hxxxxxxxx; assign wn_im[391] = 32'hxxxxxxxx; // 391 -0.737 -0.676 +assign wn_re[392] = 32'hA1288376; assign wn_im[392] = 32'hAA0A5B2E; // 392 -0.741 -0.672 +assign wn_re[393] = 32'hA0A1F24D; assign wn_im[393] = 32'hAA9FBF1E; // 393 -0.745 -0.667 +assign wn_re[394] = 32'hA01C4C73; assign wn_im[394] = 32'hAB35F5B5; // 394 -0.749 -0.662 +assign wn_re[395] = 32'hxxxxxxxx; assign wn_im[395] = 32'hxxxxxxxx; // 395 -0.753 -0.658 +assign wn_re[396] = 32'h9F13C7D0; assign wn_im[396] = 32'hAC64D510; // 396 -0.757 -0.653 +assign wn_re[397] = 32'hxxxxxxxx; assign wn_im[397] = 32'hxxxxxxxx; // 397 -0.761 -0.649 +assign wn_re[398] = 32'h9E0EFFC1; assign wn_im[398] = 32'hAD96ED92; // 398 -0.765 -0.644 +assign wn_re[399] = 32'h9D8E0597; assign wn_im[399] = 32'hAE312B92; // 399 -0.769 -0.639 +assign wn_re[400] = 32'h9D0DFE54; assign wn_im[400] = 32'hAECC336C; // 400 -0.773 -0.634 +assign wn_re[401] = 32'hxxxxxxxx; assign wn_im[401] = 32'hxxxxxxxx; // 401 -0.777 -0.630 +assign wn_re[402] = 32'h9C10CD70; assign wn_im[402] = 32'hB0049AB3; // 402 -0.781 -0.625 +assign wn_re[403] = 32'hxxxxxxxx; assign wn_im[403] = 32'hxxxxxxxx; // 403 -0.785 -0.620 +assign wn_re[404] = 32'h9B1776DA; assign wn_im[404] = 32'hB140175B; // 404 -0.788 -0.615 +assign wn_re[405] = 32'h9A9C406E; assign wn_im[405] = 32'hB1DEF9E9; // 405 -0.792 -0.610 +assign wn_re[406] = 32'h9A22042D; assign wn_im[406] = 32'hB27E9D3C; // 406 -0.796 -0.606 +assign wn_re[407] = 32'hxxxxxxxx; assign wn_im[407] = 32'hxxxxxxxx; // 407 -0.800 -0.601 +assign wn_re[408] = 32'h99307EE0; assign wn_im[408] = 32'hB3C0200C; // 408 -0.803 -0.596 +assign wn_re[409] = 32'hxxxxxxxx; assign wn_im[409] = 32'hxxxxxxxx; // 409 -0.807 -0.591 +assign wn_re[410] = 32'h9842F043; assign wn_im[410] = 32'hB5049368; // 410 -0.810 -0.586 +assign wn_re[411] = 32'h97CDA855; assign wn_im[411] = 32'hB5A7E362; // 411 -0.814 -0.581 +assign wn_re[412] = 32'h9759617F; assign wn_im[412] = 32'hB64BEACD; // 412 -0.818 -0.576 +assign wn_re[413] = 32'hxxxxxxxx; assign wn_im[413] = 32'hxxxxxxxx; // 413 -0.821 -0.571 +assign wn_re[414] = 32'h9673DB94; assign wn_im[414] = 32'hB796199B; // 414 -0.825 -0.566 +assign wn_re[415] = 32'hxxxxxxxx; assign wn_im[415] = 32'hxxxxxxxx; // 415 -0.828 -0.561 +assign wn_re[416] = 32'h9592675C; assign wn_im[416] = 32'hB8E31319; // 416 -0.831 -0.556 +assign wn_re[417] = 32'h9523369C; assign wn_im[417] = 32'hB98A97D8; // 417 -0.835 -0.550 +assign wn_re[418] = 32'h94B50D87; assign wn_im[418] = 32'hBA32CA71; // 418 -0.838 -0.545 +assign wn_re[419] = 32'hxxxxxxxx; assign wn_im[419] = 32'hxxxxxxxx; // 419 -0.842 -0.540 +assign wn_re[420] = 32'h93DBD6A0; assign wn_im[420] = 32'hBB8532B0; // 420 -0.845 -0.535 +assign wn_re[421] = 32'hxxxxxxxx; assign wn_im[421] = 32'hxxxxxxxx; // 421 -0.848 -0.530 +assign wn_re[422] = 32'h9306CB04; assign wn_im[422] = 32'hBCDA3ECB; // 422 -0.851 -0.525 +assign wn_re[423] = 32'h929DD806; assign wn_im[423] = 32'hBD85BE30; // 423 -0.855 -0.519 +assign wn_re[424] = 32'h9235F2EC; assign wn_im[424] = 32'hBE31E19B; // 424 -0.858 -0.514 +assign wn_re[425] = 32'hxxxxxxxx; assign wn_im[425] = 32'hxxxxxxxx; // 425 -0.861 -0.509 +assign wn_re[426] = 32'h91695663; assign wn_im[426] = 32'hBF8C0DE3; // 426 -0.864 -0.504 +assign wn_re[427] = 32'hxxxxxxxx; assign wn_im[427] = 32'hxxxxxxxx; // 427 -0.867 -0.498 +assign wn_re[428] = 32'h90A0FD4E; assign wn_im[428] = 32'hC0E8B648; // 428 -0.870 -0.493 +assign wn_re[429] = 32'h903E6C7B; assign wn_im[429] = 32'hC197F4D4; // 429 -0.873 -0.488 +assign wn_re[430] = 32'h8FDCEF66; assign wn_im[430] = 32'hC247CD5A; // 430 -0.876 -0.482 +assign wn_re[431] = 32'hxxxxxxxx; assign wn_im[431] = 32'hxxxxxxxx; // 431 -0.879 -0.477 +assign wn_re[432] = 32'h8F1D343A; assign wn_im[432] = 32'hC3A94590; // 432 -0.882 -0.471 +assign wn_re[433] = 32'hxxxxxxxx; assign wn_im[433] = 32'hxxxxxxxx; // 433 -0.885 -0.466 +assign wn_re[434] = 32'h8E61D32E; assign wn_im[434] = 32'hC50D1149; // 434 -0.888 -0.461 +assign wn_re[435] = 32'h8E05C6B7; assign wn_im[435] = 32'hC5BFD22E; // 435 -0.890 -0.455 +assign wn_re[436] = 32'h8DAAD37B; assign wn_im[436] = 32'hC67322CE; // 436 -0.893 -0.450 +assign wn_re[437] = 32'hxxxxxxxx; assign wn_im[437] = 32'hxxxxxxxx; // 437 -0.896 -0.444 +assign wn_re[438] = 32'h8CF83C30; assign wn_im[438] = 32'hC7DB6C50; // 438 -0.899 -0.439 +assign wn_re[439] = 32'hxxxxxxxx; assign wn_im[439] = 32'hxxxxxxxx; // 439 -0.901 -0.433 +assign wn_re[440] = 32'h8C4A142F; assign wn_im[440] = 32'hC945DFEC; // 440 -0.904 -0.428 +assign wn_re[441] = 32'h8BF4AC05; assign wn_im[441] = 32'hC9FBE527; // 441 -0.907 -0.422 +assign wn_re[442] = 32'h8BA0622F; assign wn_im[442] = 32'hCAB26FA9; // 442 -0.909 -0.416 +assign wn_re[443] = 32'hxxxxxxxx; assign wn_im[443] = 32'hxxxxxxxx; // 443 -0.912 -0.411 +assign wn_re[444] = 32'h8AFB2CBB; assign wn_im[444] = 32'hCC210D79; // 444 -0.914 -0.405 +assign wn_re[445] = 32'hxxxxxxxx; assign wn_im[445] = 32'hxxxxxxxx; // 445 -0.917 -0.400 +assign wn_re[446] = 32'h8A5A7A31; assign wn_im[446] = 32'hCD91AB39; // 446 -0.919 -0.394 +assign wn_re[447] = 32'h8A0BD3F5; assign wn_im[447] = 32'hCE4AB5A2; // 447 -0.922 -0.388 +assign wn_re[448] = 32'h89BE50C3; assign wn_im[448] = 32'hCF043AB3; // 448 -0.924 -0.383 +assign wn_re[449] = 32'hxxxxxxxx; assign wn_im[449] = 32'hxxxxxxxx; // 449 -0.926 -0.377 +assign wn_re[450] = 32'h8926B677; assign wn_im[450] = 32'hD078AD9E; // 450 -0.929 -0.371 +assign wn_re[451] = 32'hxxxxxxxx; assign wn_im[451] = 32'hxxxxxxxx; // 451 -0.931 -0.366 +assign wn_re[452] = 32'h8893B125; assign wn_im[452] = 32'hD1EEF59E; // 452 -0.933 -0.360 +assign wn_re[453] = 32'h884BE821; assign wn_im[453] = 32'hD2AAC504; // 453 -0.935 -0.354 +assign wn_re[454] = 32'h88054677; assign wn_im[454] = 32'hD3670446; // 454 -0.937 -0.348 +assign wn_re[455] = 32'hxxxxxxxx; assign wn_im[455] = 32'hxxxxxxxx; // 455 -0.939 -0.343 +assign wn_re[456] = 32'h877B7BEC; assign wn_im[456] = 32'hD4E0CB15; // 456 -0.942 -0.337 +assign wn_re[457] = 32'hxxxxxxxx; assign wn_im[457] = 32'hxxxxxxxx; // 457 -0.944 -0.331 +assign wn_re[458] = 32'h86F656D3; assign wn_im[458] = 32'hD65C3B7B; // 458 -0.946 -0.325 +assign wn_re[459] = 32'h86B583EE; assign wn_im[459] = 32'hD71A8EB5; // 459 -0.948 -0.320 +assign wn_re[460] = 32'h8675DC4F; assign wn_im[460] = 32'hD7D946D8; // 460 -0.950 -0.314 +assign wn_re[461] = 32'hxxxxxxxx; assign wn_im[461] = 32'hxxxxxxxx; // 461 -0.951 -0.308 +assign wn_re[462] = 32'h85FA1153; assign wn_im[462] = 32'hD957DE7A; // 462 -0.953 -0.302 +assign wn_re[463] = 32'hxxxxxxxx; assign wn_im[463] = 32'hxxxxxxxx; // 463 -0.955 -0.296 +assign wn_re[464] = 32'h8582FAA5; assign wn_im[464] = 32'hDAD7F3A2; // 464 -0.957 -0.290 +assign wn_re[465] = 32'h8549345C; assign wn_im[465] = 32'hDB9888A8; // 465 -0.959 -0.284 +assign wn_re[466] = 32'h85109CDD; assign wn_im[466] = 32'hDC597781; // 466 -0.960 -0.279 +assign wn_re[467] = 32'hxxxxxxxx; assign wn_im[467] = 32'hxxxxxxxx; // 467 -0.962 -0.273 +assign wn_re[468] = 32'h84A2FC62; assign wn_im[468] = 32'hDDDC5B3B; // 468 -0.964 -0.267 +assign wn_re[469] = 32'hxxxxxxxx; assign wn_im[469] = 32'hxxxxxxxx; // 469 -0.965 -0.261 +assign wn_re[470] = 32'h843A1D70; assign wn_im[470] = 32'hDF608FE4; // 470 -0.967 -0.255 +assign wn_re[471] = 32'h840777D0; assign wn_im[471] = 32'hE02323E5; // 471 -0.969 -0.249 +assign wn_re[472] = 32'h83D60412; assign wn_im[472] = 32'hE0E60685; // 472 -0.970 -0.243 +assign wn_re[473] = 32'hxxxxxxxx; assign wn_im[473] = 32'hxxxxxxxx; // 473 -0.972 -0.237 +assign wn_re[474] = 32'h8376B422; assign wn_im[474] = 32'hE26CB01B; // 474 -0.973 -0.231 +assign wn_re[475] = 32'hxxxxxxxx; assign wn_im[475] = 32'hxxxxxxxx; // 475 -0.974 -0.225 +assign wn_re[476] = 32'h831C314E; assign wn_im[476] = 32'hE3F47D96; // 476 -0.976 -0.219 +assign wn_re[477] = 32'h82F0BDE8; assign wn_im[477] = 32'hE4B8CD11; // 477 -0.977 -0.213 +assign wn_re[478] = 32'h82C67F14; assign wn_im[478] = 32'hE57D5FDA; // 478 -0.978 -0.207 +assign wn_re[479] = 32'hxxxxxxxx; assign wn_im[479] = 32'hxxxxxxxx; // 479 -0.980 -0.201 +assign wn_re[480] = 32'h8275A0C0; assign wn_im[480] = 32'hE70747C4; // 480 -0.981 -0.195 +assign wn_re[481] = 32'hxxxxxxxx; assign wn_im[481] = 32'hxxxxxxxx; // 481 -0.982 -0.189 +assign wn_re[482] = 32'h82299971; assign wn_im[482] = 32'hE8922622; // 482 -0.983 -0.183 +assign wn_re[483] = 32'h82056758; assign wn_im[483] = 32'hE957ECFB; // 483 -0.984 -0.177 +assign wn_re[484] = 32'h81E26C16; assign wn_im[484] = 32'hEA1DEBBB; // 484 -0.985 -0.171 +assign wn_re[485] = 32'hxxxxxxxx; assign wn_im[485] = 32'hxxxxxxxx; // 485 -0.986 -0.165 +assign wn_re[486] = 32'h81A01B6D; assign wn_im[486] = 32'hEBAA894F; // 486 -0.987 -0.159 +assign wn_re[487] = 32'hxxxxxxxx; assign wn_im[487] = 32'hxxxxxxxx; // 487 -0.988 -0.153 +assign wn_re[488] = 32'h8162AA04; assign wn_im[488] = 32'hED37EF91; // 488 -0.989 -0.147 +assign wn_re[489] = 32'h8145C5C7; assign wn_im[489] = 32'hEDFEE92B; // 489 -0.990 -0.141 +assign wn_re[490] = 32'h812A1A3A; assign wn_im[490] = 32'hEEC60F31; // 490 -0.991 -0.135 +assign wn_re[491] = 32'hxxxxxxxx; assign wn_im[491] = 32'hxxxxxxxx; // 491 -0.992 -0.128 +assign wn_re[492] = 32'h80F66E3C; assign wn_im[492] = 32'hF054D8D5; // 492 -0.992 -0.122 +assign wn_re[493] = 32'hxxxxxxxx; assign wn_im[493] = 32'hxxxxxxxx; // 493 -0.993 -0.116 +assign wn_re[494] = 32'h80C7A80A; assign wn_im[494] = 32'hF1E43D1C; // 494 -0.994 -0.110 +assign wn_re[495] = 32'h80B21BAF; assign wn_im[495] = 32'hF2AC246E; // 495 -0.995 -0.104 +assign wn_re[496] = 32'h809DC971; assign wn_im[496] = 32'hF3742CA2; // 496 -0.995 -0.098 +assign wn_re[497] = 32'hxxxxxxxx; assign wn_im[497] = 32'hxxxxxxxx; // 497 -0.996 -0.092 +assign wn_re[498] = 32'h8078D40D; assign wn_im[498] = 32'hF50497FB; // 498 -0.996 -0.086 +assign wn_re[499] = 32'hxxxxxxxx; assign wn_im[499] = 32'hxxxxxxxx; // 499 -0.997 -0.080 +assign wn_re[500] = 32'h8058C94C; assign wn_im[500] = 32'hF6956FB7; // 500 -0.997 -0.074 +assign wn_re[501] = 32'h804A9C4D; assign wn_im[501] = 32'hF75DFF66; // 501 -0.998 -0.067 +assign wn_re[502] = 32'h803DAA6A; assign wn_im[502] = 32'hF826A462; // 502 -0.998 -0.061 +assign wn_re[503] = 32'hxxxxxxxx; assign wn_im[503] = 32'hxxxxxxxx; // 503 -0.998 -0.055 +assign wn_re[504] = 32'h80277872; assign wn_im[504] = 32'hF9B82684; // 504 -0.999 -0.049 +assign wn_re[505] = 32'hxxxxxxxx; assign wn_im[505] = 32'hxxxxxxxx; // 505 -0.999 -0.043 +assign wn_re[506] = 32'h80163440; assign wn_im[506] = 32'hFB49E6A3; // 506 -0.999 -0.037 +assign wn_re[507] = 32'h800F6B88; assign wn_im[507] = 32'hFC12D91A; // 507 -1.000 -0.031 +assign wn_re[508] = 32'h8009DE7E; assign wn_im[508] = 32'hFCDBD541; // 508 -1.000 -0.025 +assign wn_re[509] = 32'hxxxxxxxx; assign wn_im[509] = 32'hxxxxxxxx; // 509 -1.000 -0.018 +assign wn_re[510] = 32'h800277A6; assign wn_im[510] = 32'hFE6DE2E0; // 510 -1.000 -0.012 +assign wn_re[511] = 32'hxxxxxxxx; assign wn_im[511] = 32'hxxxxxxxx; // 511 -1.000 -0.006 +assign wn_re[512] = 32'hxxxxxxxx; assign wn_im[512] = 32'hxxxxxxxx; // 512 -1.000 -0.000 +assign wn_re[513] = 32'h80009DEA; assign wn_im[513] = 32'h00C90F88; // 513 -1.000 0.006 +assign wn_re[514] = 32'hxxxxxxxx; assign wn_im[514] = 32'hxxxxxxxx; // 514 -1.000 0.012 +assign wn_re[515] = 32'hxxxxxxxx; assign wn_im[515] = 32'hxxxxxxxx; // 515 -1.000 0.018 +assign wn_re[516] = 32'h8009DE7E; assign wn_im[516] = 32'h03242ABF; // 516 -1.000 0.025 +assign wn_re[517] = 32'hxxxxxxxx; assign wn_im[517] = 32'hxxxxxxxx; // 517 -1.000 0.031 +assign wn_re[518] = 32'hxxxxxxxx; assign wn_im[518] = 32'hxxxxxxxx; // 518 -0.999 0.037 +assign wn_re[519] = 32'h801E3895; assign wn_im[519] = 32'h057F0035; // 519 -0.999 0.043 +assign wn_re[520] = 32'hxxxxxxxx; assign wn_im[520] = 32'hxxxxxxxx; // 520 -0.999 0.049 +assign wn_re[521] = 32'hxxxxxxxx; assign wn_im[521] = 32'hxxxxxxxx; // 521 -0.998 0.055 +assign wn_re[522] = 32'h803DAA6A; assign wn_im[522] = 32'h07D95B9E; // 522 -0.998 0.061 +assign wn_re[523] = 32'hxxxxxxxx; assign wn_im[523] = 32'hxxxxxxxx; // 523 -0.998 0.067 +assign wn_re[524] = 32'hxxxxxxxx; assign wn_im[524] = 32'hxxxxxxxx; // 524 -0.997 0.074 +assign wn_re[525] = 32'h80683143; assign wn_im[525] = 32'h0A3308BD; // 525 -0.997 0.080 +assign wn_re[526] = 32'hxxxxxxxx; assign wn_im[526] = 32'hxxxxxxxx; // 526 -0.996 0.086 +assign wn_re[527] = 32'hxxxxxxxx; assign wn_im[527] = 32'hxxxxxxxx; // 527 -0.996 0.092 +assign wn_re[528] = 32'h809DC971; assign wn_im[528] = 32'h0C8BD35E; // 528 -0.995 0.098 +assign wn_re[529] = 32'hxxxxxxxx; assign wn_im[529] = 32'hxxxxxxxx; // 529 -0.995 0.104 +assign wn_re[530] = 32'hxxxxxxxx; assign wn_im[530] = 32'hxxxxxxxx; // 530 -0.994 0.110 +assign wn_re[531] = 32'h80DE6E4C; assign wn_im[531] = 32'h0EE38766; // 531 -0.993 0.116 +assign wn_re[532] = 32'hxxxxxxxx; assign wn_im[532] = 32'hxxxxxxxx; // 532 -0.992 0.122 +assign wn_re[533] = 32'hxxxxxxxx; assign wn_im[533] = 32'hxxxxxxxx; // 533 -0.992 0.128 +assign wn_re[534] = 32'h812A1A3A; assign wn_im[534] = 32'h1139F0CF; // 534 -0.991 0.135 +assign wn_re[535] = 32'hxxxxxxxx; assign wn_im[535] = 32'hxxxxxxxx; // 535 -0.990 0.141 +assign wn_re[536] = 32'hxxxxxxxx; assign wn_im[536] = 32'hxxxxxxxx; // 536 -0.989 0.147 +assign wn_re[537] = 32'h8180C6A9; assign wn_im[537] = 32'h138EDBB1; // 537 -0.988 0.153 +assign wn_re[538] = 32'hxxxxxxxx; assign wn_im[538] = 32'hxxxxxxxx; // 538 -0.987 0.159 +assign wn_re[539] = 32'hxxxxxxxx; assign wn_im[539] = 32'hxxxxxxxx; // 539 -0.986 0.165 +assign wn_re[540] = 32'h81E26C16; assign wn_im[540] = 32'h15E21445; // 540 -0.985 0.171 +assign wn_re[541] = 32'hxxxxxxxx; assign wn_im[541] = 32'hxxxxxxxx; // 541 -0.984 0.177 +assign wn_re[542] = 32'hxxxxxxxx; assign wn_im[542] = 32'hxxxxxxxx; // 542 -0.983 0.183 +assign wn_re[543] = 32'h824F0208; assign wn_im[543] = 32'h183366E9; // 543 -0.982 0.189 +assign wn_re[544] = 32'hxxxxxxxx; assign wn_im[544] = 32'hxxxxxxxx; // 544 -0.981 0.195 +assign wn_re[545] = 32'hxxxxxxxx; assign wn_im[545] = 32'hxxxxxxxx; // 545 -0.980 0.201 +assign wn_re[546] = 32'h82C67F14; assign wn_im[546] = 32'h1A82A026; // 546 -0.978 0.207 +assign wn_re[547] = 32'hxxxxxxxx; assign wn_im[547] = 32'hxxxxxxxx; // 547 -0.977 0.213 +assign wn_re[548] = 32'hxxxxxxxx; assign wn_im[548] = 32'hxxxxxxxx; // 548 -0.976 0.219 +assign wn_re[549] = 32'h8348D8DC; assign wn_im[549] = 32'h1CCF8CB3; // 549 -0.974 0.225 +assign wn_re[550] = 32'hxxxxxxxx; assign wn_im[550] = 32'hxxxxxxxx; // 550 -0.973 0.231 +assign wn_re[551] = 32'hxxxxxxxx; assign wn_im[551] = 32'hxxxxxxxx; // 551 -0.972 0.237 +assign wn_re[552] = 32'h83D60412; assign wn_im[552] = 32'h1F19F97B; // 552 -0.970 0.243 +assign wn_re[553] = 32'hxxxxxxxx; assign wn_im[553] = 32'hxxxxxxxx; // 553 -0.969 0.249 +assign wn_re[554] = 32'hxxxxxxxx; assign wn_im[554] = 32'hxxxxxxxx; // 554 -0.967 0.255 +assign wn_re[555] = 32'h846DF477; assign wn_im[555] = 32'h2161B3A0; // 555 -0.965 0.261 +assign wn_re[556] = 32'hxxxxxxxx; assign wn_im[556] = 32'hxxxxxxxx; // 556 -0.964 0.267 +assign wn_re[557] = 32'hxxxxxxxx; assign wn_im[557] = 32'hxxxxxxxx; // 557 -0.962 0.273 +assign wn_re[558] = 32'h85109CDD; assign wn_im[558] = 32'h23A6887F; // 558 -0.960 0.279 +assign wn_re[559] = 32'hxxxxxxxx; assign wn_im[559] = 32'hxxxxxxxx; // 559 -0.959 0.284 +assign wn_re[560] = 32'hxxxxxxxx; assign wn_im[560] = 32'hxxxxxxxx; // 560 -0.957 0.290 +assign wn_re[561] = 32'h85BDEF28; assign wn_im[561] = 32'h25E845B6; // 561 -0.955 0.296 +assign wn_re[562] = 32'hxxxxxxxx; assign wn_im[562] = 32'hxxxxxxxx; // 562 -0.953 0.302 +assign wn_re[563] = 32'hxxxxxxxx; assign wn_im[563] = 32'hxxxxxxxx; // 563 -0.951 0.308 +assign wn_re[564] = 32'h8675DC4F; assign wn_im[564] = 32'h2826B928; // 564 -0.950 0.314 +assign wn_re[565] = 32'hxxxxxxxx; assign wn_im[565] = 32'hxxxxxxxx; // 565 -0.948 0.320 +assign wn_re[566] = 32'hxxxxxxxx; assign wn_im[566] = 32'hxxxxxxxx; // 566 -0.946 0.325 +assign wn_re[567] = 32'h8738545E; assign wn_im[567] = 32'h2A61B101; // 567 -0.944 0.331 +assign wn_re[568] = 32'hxxxxxxxx; assign wn_im[568] = 32'hxxxxxxxx; // 568 -0.942 0.337 +assign wn_re[569] = 32'hxxxxxxxx; assign wn_im[569] = 32'hxxxxxxxx; // 569 -0.939 0.343 +assign wn_re[570] = 32'h88054677; assign wn_im[570] = 32'h2C98FBBA; // 570 -0.937 0.348 +assign wn_re[571] = 32'hxxxxxxxx; assign wn_im[571] = 32'hxxxxxxxx; // 571 -0.935 0.354 +assign wn_re[572] = 32'hxxxxxxxx; assign wn_im[572] = 32'hxxxxxxxx; // 572 -0.933 0.360 +assign wn_re[573] = 32'h88DCA0D3; assign wn_im[573] = 32'h2ECC681E; // 573 -0.931 0.366 +assign wn_re[574] = 32'hxxxxxxxx; assign wn_im[574] = 32'hxxxxxxxx; // 574 -0.929 0.371 +assign wn_re[575] = 32'hxxxxxxxx; assign wn_im[575] = 32'hxxxxxxxx; // 575 -0.926 0.377 +assign wn_re[576] = 32'h89BE50C3; assign wn_im[576] = 32'h30FBC54D; // 576 -0.924 0.383 +assign wn_re[577] = 32'hxxxxxxxx; assign wn_im[577] = 32'hxxxxxxxx; // 577 -0.922 0.388 +assign wn_re[578] = 32'hxxxxxxxx; assign wn_im[578] = 32'hxxxxxxxx; // 578 -0.919 0.394 +assign wn_re[579] = 32'h8AAA42B4; assign wn_im[579] = 32'h3326E2C3; // 579 -0.917 0.400 +assign wn_re[580] = 32'hxxxxxxxx; assign wn_im[580] = 32'hxxxxxxxx; // 580 -0.914 0.405 +assign wn_re[581] = 32'hxxxxxxxx; assign wn_im[581] = 32'hxxxxxxxx; // 581 -0.912 0.411 +assign wn_re[582] = 32'h8BA0622F; assign wn_im[582] = 32'h354D9057; // 582 -0.909 0.416 +assign wn_re[583] = 32'hxxxxxxxx; assign wn_im[583] = 32'hxxxxxxxx; // 583 -0.907 0.422 +assign wn_re[584] = 32'hxxxxxxxx; assign wn_im[584] = 32'hxxxxxxxx; // 584 -0.904 0.428 +assign wn_re[585] = 32'h8CA099DA; assign wn_im[585] = 32'h376F9E46; // 585 -0.901 0.433 +assign wn_re[586] = 32'hxxxxxxxx; assign wn_im[586] = 32'hxxxxxxxx; // 586 -0.899 0.439 +assign wn_re[587] = 32'hxxxxxxxx; assign wn_im[587] = 32'hxxxxxxxx; // 587 -0.896 0.444 +assign wn_re[588] = 32'h8DAAD37B; assign wn_im[588] = 32'h398CDD32; // 588 -0.893 0.450 +assign wn_re[589] = 32'hxxxxxxxx; assign wn_im[589] = 32'hxxxxxxxx; // 589 -0.890 0.455 +assign wn_re[590] = 32'hxxxxxxxx; assign wn_im[590] = 32'hxxxxxxxx; // 590 -0.888 0.461 +assign wn_re[591] = 32'h8EBEF7FB; assign wn_im[591] = 32'h3BA51E29; // 591 -0.885 0.466 +assign wn_re[592] = 32'hxxxxxxxx; assign wn_im[592] = 32'hxxxxxxxx; // 592 -0.882 0.471 +assign wn_re[593] = 32'hxxxxxxxx; assign wn_im[593] = 32'hxxxxxxxx; // 593 -0.879 0.477 +assign wn_re[594] = 32'h8FDCEF66; assign wn_im[594] = 32'h3DB832A6; // 594 -0.876 0.482 +assign wn_re[595] = 32'hxxxxxxxx; assign wn_im[595] = 32'hxxxxxxxx; // 595 -0.873 0.488 +assign wn_re[596] = 32'hxxxxxxxx; assign wn_im[596] = 32'hxxxxxxxx; // 596 -0.870 0.493 +assign wn_re[597] = 32'h9104A0EE; assign wn_im[597] = 32'h3FC5EC98; // 597 -0.867 0.498 +assign wn_re[598] = 32'hxxxxxxxx; assign wn_im[598] = 32'hxxxxxxxx; // 598 -0.864 0.504 +assign wn_re[599] = 32'hxxxxxxxx; assign wn_im[599] = 32'hxxxxxxxx; // 599 -0.861 0.509 +assign wn_re[600] = 32'h9235F2EC; assign wn_im[600] = 32'h41CE1E65; // 600 -0.858 0.514 +assign wn_re[601] = 32'hxxxxxxxx; assign wn_im[601] = 32'hxxxxxxxx; // 601 -0.855 0.519 +assign wn_re[602] = 32'hxxxxxxxx; assign wn_im[602] = 32'hxxxxxxxx; // 602 -0.851 0.525 +assign wn_re[603] = 32'h9370CAE4; assign wn_im[603] = 32'h43D09AED; // 603 -0.848 0.530 +assign wn_re[604] = 32'hxxxxxxxx; assign wn_im[604] = 32'hxxxxxxxx; // 604 -0.845 0.535 +assign wn_re[605] = 32'hxxxxxxxx; assign wn_im[605] = 32'hxxxxxxxx; // 605 -0.842 0.540 +assign wn_re[606] = 32'h94B50D87; assign wn_im[606] = 32'h45CD358F; // 606 -0.838 0.545 +assign wn_re[607] = 32'hxxxxxxxx; assign wn_im[607] = 32'hxxxxxxxx; // 607 -0.835 0.550 +assign wn_re[608] = 32'hxxxxxxxx; assign wn_im[608] = 32'hxxxxxxxx; // 608 -0.831 0.556 +assign wn_re[609] = 32'h96029EB6; assign wn_im[609] = 32'h47C3C22F; // 609 -0.828 0.561 +assign wn_re[610] = 32'hxxxxxxxx; assign wn_im[610] = 32'hxxxxxxxx; // 610 -0.825 0.566 +assign wn_re[611] = 32'hxxxxxxxx; assign wn_im[611] = 32'hxxxxxxxx; // 611 -0.821 0.571 +assign wn_re[612] = 32'h9759617F; assign wn_im[612] = 32'h49B41533; // 612 -0.818 0.576 +assign wn_re[613] = 32'hxxxxxxxx; assign wn_im[613] = 32'hxxxxxxxx; // 613 -0.814 0.581 +assign wn_re[614] = 32'hxxxxxxxx; assign wn_im[614] = 32'hxxxxxxxx; // 614 -0.810 0.586 +assign wn_re[615] = 32'h98B93828; assign wn_im[615] = 32'h4B9E0390; // 615 -0.807 0.591 +assign wn_re[616] = 32'hxxxxxxxx; assign wn_im[616] = 32'hxxxxxxxx; // 616 -0.803 0.596 +assign wn_re[617] = 32'hxxxxxxxx; assign wn_im[617] = 32'hxxxxxxxx; // 617 -0.800 0.601 +assign wn_re[618] = 32'h9A22042D; assign wn_im[618] = 32'h4D8162C4; // 618 -0.796 0.606 +assign wn_re[619] = 32'hxxxxxxxx; assign wn_im[619] = 32'hxxxxxxxx; // 619 -0.792 0.610 +assign wn_re[620] = 32'hxxxxxxxx; assign wn_im[620] = 32'hxxxxxxxx; // 620 -0.788 0.615 +assign wn_re[621] = 32'h9B93A641; assign wn_im[621] = 32'h4F5E08E3; // 621 -0.785 0.620 +assign wn_re[622] = 32'hxxxxxxxx; assign wn_im[622] = 32'hxxxxxxxx; // 622 -0.781 0.625 +assign wn_re[623] = 32'hxxxxxxxx; assign wn_im[623] = 32'hxxxxxxxx; // 623 -0.777 0.630 +assign wn_re[624] = 32'h9D0DFE54; assign wn_im[624] = 32'h5133CC94; // 624 -0.773 0.634 +assign wn_re[625] = 32'hxxxxxxxx; assign wn_im[625] = 32'hxxxxxxxx; // 625 -0.769 0.639 +assign wn_re[626] = 32'hxxxxxxxx; assign wn_im[626] = 32'hxxxxxxxx; // 626 -0.765 0.644 +assign wn_re[627] = 32'h9E90EB94; assign wn_im[627] = 32'h53028518; // 627 -0.761 0.649 +assign wn_re[628] = 32'hxxxxxxxx; assign wn_im[628] = 32'hxxxxxxxx; // 628 -0.757 0.653 +assign wn_re[629] = 32'hxxxxxxxx; assign wn_im[629] = 32'hxxxxxxxx; // 629 -0.753 0.658 +assign wn_re[630] = 32'hA01C4C73; assign wn_im[630] = 32'h54CA0A4B; // 630 -0.749 0.662 +assign wn_re[631] = 32'hxxxxxxxx; assign wn_im[631] = 32'hxxxxxxxx; // 631 -0.745 0.667 +assign wn_re[632] = 32'hxxxxxxxx; assign wn_im[632] = 32'hxxxxxxxx; // 632 -0.741 0.672 +assign wn_re[633] = 32'hA1AFFEA3; assign wn_im[633] = 32'h568A34A9; // 633 -0.737 0.676 +assign wn_re[634] = 32'hxxxxxxxx; assign wn_im[634] = 32'hxxxxxxxx; // 634 -0.733 0.681 +assign wn_re[635] = 32'hxxxxxxxx; assign wn_im[635] = 32'hxxxxxxxx; // 635 -0.728 0.685 +assign wn_re[636] = 32'hA34BDF20; assign wn_im[636] = 32'h5842DD54; // 636 -0.724 0.690 +assign wn_re[637] = 32'hxxxxxxxx; assign wn_im[637] = 32'hxxxxxxxx; // 637 -0.720 0.694 +assign wn_re[638] = 32'hxxxxxxxx; assign wn_im[638] = 32'hxxxxxxxx; // 638 -0.716 0.698 +assign wn_re[639] = 32'hA4EFCA31; assign wn_im[639] = 32'h59F3DE12; // 639 -0.711 0.703 +assign wn_re[640] = 32'hxxxxxxxx; assign wn_im[640] = 32'hxxxxxxxx; // 640 -0.707 0.707 +assign wn_re[641] = 32'hxxxxxxxx; assign wn_im[641] = 32'hxxxxxxxx; // 641 -0.703 0.711 +assign wn_re[642] = 32'hA69B9B68; assign wn_im[642] = 32'h5B9D1154; // 642 -0.698 0.716 +assign wn_re[643] = 32'hxxxxxxxx; assign wn_im[643] = 32'hxxxxxxxx; // 643 -0.694 0.720 +assign wn_re[644] = 32'hxxxxxxxx; assign wn_im[644] = 32'hxxxxxxxx; // 644 -0.690 0.724 +assign wn_re[645] = 32'hA84F2DAA; assign wn_im[645] = 32'h5D3E5237; // 645 -0.685 0.728 +assign wn_re[646] = 32'hxxxxxxxx; assign wn_im[646] = 32'hxxxxxxxx; // 646 -0.681 0.733 +assign wn_re[647] = 32'hxxxxxxxx; assign wn_im[647] = 32'hxxxxxxxx; // 647 -0.676 0.737 +assign wn_re[648] = 32'hAA0A5B2E; assign wn_im[648] = 32'h5ED77C8A; // 648 -0.672 0.741 +assign wn_re[649] = 32'hxxxxxxxx; assign wn_im[649] = 32'hxxxxxxxx; // 649 -0.667 0.745 +assign wn_re[650] = 32'hxxxxxxxx; assign wn_im[650] = 32'hxxxxxxxx; // 650 -0.662 0.749 +assign wn_re[651] = 32'hABCCFD83; assign wn_im[651] = 32'h60686CCF; // 651 -0.658 0.753 +assign wn_re[652] = 32'hxxxxxxxx; assign wn_im[652] = 32'hxxxxxxxx; // 652 -0.653 0.757 +assign wn_re[653] = 32'hxxxxxxxx; assign wn_im[653] = 32'hxxxxxxxx; // 653 -0.649 0.761 +assign wn_re[654] = 32'hAD96ED92; assign wn_im[654] = 32'h61F1003F; // 654 -0.644 0.765 +assign wn_re[655] = 32'hxxxxxxxx; assign wn_im[655] = 32'hxxxxxxxx; // 655 -0.639 0.769 +assign wn_re[656] = 32'hxxxxxxxx; assign wn_im[656] = 32'hxxxxxxxx; // 656 -0.634 0.773 +assign wn_re[657] = 32'hAF6803A2; assign wn_im[657] = 32'h637114CC; // 657 -0.630 0.777 +assign wn_re[658] = 32'hxxxxxxxx; assign wn_im[658] = 32'hxxxxxxxx; // 658 -0.625 0.781 +assign wn_re[659] = 32'hxxxxxxxx; assign wn_im[659] = 32'hxxxxxxxx; // 659 -0.620 0.785 +assign wn_re[660] = 32'hB140175B; assign wn_im[660] = 32'h64E88926; // 660 -0.615 0.788 +assign wn_re[661] = 32'hxxxxxxxx; assign wn_im[661] = 32'hxxxxxxxx; // 661 -0.610 0.792 +assign wn_re[662] = 32'hxxxxxxxx; assign wn_im[662] = 32'hxxxxxxxx; // 662 -0.606 0.796 +assign wn_re[663] = 32'hB31EFFCC; assign wn_im[663] = 32'h66573CBB; // 663 -0.601 0.800 +assign wn_re[664] = 32'hxxxxxxxx; assign wn_im[664] = 32'hxxxxxxxx; // 664 -0.596 0.803 +assign wn_re[665] = 32'hxxxxxxxx; assign wn_im[665] = 32'hxxxxxxxx; // 665 -0.591 0.807 +assign wn_re[666] = 32'hB5049368; assign wn_im[666] = 32'h67BD0FBD; // 666 -0.586 0.810 +assign wn_re[667] = 32'hxxxxxxxx; assign wn_im[667] = 32'hxxxxxxxx; // 667 -0.581 0.814 +assign wn_re[668] = 32'hxxxxxxxx; assign wn_im[668] = 32'hxxxxxxxx; // 668 -0.576 0.818 +assign wn_re[669] = 32'hB6F0A812; assign wn_im[669] = 32'h6919E320; // 669 -0.571 0.821 +assign wn_re[670] = 32'hxxxxxxxx; assign wn_im[670] = 32'hxxxxxxxx; // 670 -0.566 0.825 +assign wn_re[671] = 32'hxxxxxxxx; assign wn_im[671] = 32'hxxxxxxxx; // 671 -0.561 0.828 +assign wn_re[672] = 32'hB8E31319; assign wn_im[672] = 32'h6A6D98A4; // 672 -0.556 0.831 +assign wn_re[673] = 32'hxxxxxxxx; assign wn_im[673] = 32'hxxxxxxxx; // 673 -0.550 0.835 +assign wn_re[674] = 32'hxxxxxxxx; assign wn_im[674] = 32'hxxxxxxxx; // 674 -0.545 0.838 +assign wn_re[675] = 32'hBADBA943; assign wn_im[675] = 32'h6BB812D1; // 675 -0.540 0.842 +assign wn_re[676] = 32'hxxxxxxxx; assign wn_im[676] = 32'hxxxxxxxx; // 676 -0.535 0.845 +assign wn_re[677] = 32'hxxxxxxxx; assign wn_im[677] = 32'hxxxxxxxx; // 677 -0.530 0.848 +assign wn_re[678] = 32'hBCDA3ECB; assign wn_im[678] = 32'h6CF934FC; // 678 -0.525 0.851 +assign wn_re[679] = 32'hxxxxxxxx; assign wn_im[679] = 32'hxxxxxxxx; // 679 -0.519 0.855 +assign wn_re[680] = 32'hxxxxxxxx; assign wn_im[680] = 32'hxxxxxxxx; // 680 -0.514 0.858 +assign wn_re[681] = 32'hBEDEA765; assign wn_im[681] = 32'h6E30E34A; // 681 -0.509 0.861 +assign wn_re[682] = 32'hxxxxxxxx; assign wn_im[682] = 32'hxxxxxxxx; // 682 -0.504 0.864 +assign wn_re[683] = 32'hxxxxxxxx; assign wn_im[683] = 32'hxxxxxxxx; // 683 -0.498 0.867 +assign wn_re[684] = 32'hC0E8B648; assign wn_im[684] = 32'h6F5F02B2; // 684 -0.493 0.870 +assign wn_re[685] = 32'hxxxxxxxx; assign wn_im[685] = 32'hxxxxxxxx; // 685 -0.488 0.873 +assign wn_re[686] = 32'hxxxxxxxx; assign wn_im[686] = 32'hxxxxxxxx; // 686 -0.482 0.876 +assign wn_re[687] = 32'hC2F83E2A; assign wn_im[687] = 32'h708378FF; // 687 -0.477 0.879 +assign wn_re[688] = 32'hxxxxxxxx; assign wn_im[688] = 32'hxxxxxxxx; // 688 -0.471 0.882 +assign wn_re[689] = 32'hxxxxxxxx; assign wn_im[689] = 32'hxxxxxxxx; // 689 -0.466 0.885 +assign wn_re[690] = 32'hC50D1149; assign wn_im[690] = 32'h719E2CD2; // 690 -0.461 0.888 +assign wn_re[691] = 32'hxxxxxxxx; assign wn_im[691] = 32'hxxxxxxxx; // 691 -0.455 0.890 +assign wn_re[692] = 32'hxxxxxxxx; assign wn_im[692] = 32'hxxxxxxxx; // 692 -0.450 0.893 +assign wn_re[693] = 32'hC727016D; assign wn_im[693] = 32'h72AF05A7; // 693 -0.444 0.896 +assign wn_re[694] = 32'hxxxxxxxx; assign wn_im[694] = 32'hxxxxxxxx; // 694 -0.439 0.899 +assign wn_re[695] = 32'hxxxxxxxx; assign wn_im[695] = 32'hxxxxxxxx; // 695 -0.433 0.901 +assign wn_re[696] = 32'hC945DFEC; assign wn_im[696] = 32'h73B5EBD1; // 696 -0.428 0.904 +assign wn_re[697] = 32'hxxxxxxxx; assign wn_im[697] = 32'hxxxxxxxx; // 697 -0.422 0.907 +assign wn_re[698] = 32'hxxxxxxxx; assign wn_im[698] = 32'hxxxxxxxx; // 698 -0.416 0.909 +assign wn_re[699] = 32'hCB697DB0; assign wn_im[699] = 32'h74B2C884; // 699 -0.411 0.912 +assign wn_re[700] = 32'hxxxxxxxx; assign wn_im[700] = 32'hxxxxxxxx; // 700 -0.405 0.914 +assign wn_re[701] = 32'hxxxxxxxx; assign wn_im[701] = 32'hxxxxxxxx; // 701 -0.400 0.917 +assign wn_re[702] = 32'hCD91AB39; assign wn_im[702] = 32'h75A585CF; // 702 -0.394 0.919 +assign wn_re[703] = 32'hxxxxxxxx; assign wn_im[703] = 32'hxxxxxxxx; // 703 -0.388 0.922 +assign wn_re[704] = 32'hxxxxxxxx; assign wn_im[704] = 32'hxxxxxxxx; // 704 -0.383 0.924 +assign wn_re[705] = 32'hCFBE389F; assign wn_im[705] = 32'h768E0EA6; // 705 -0.377 0.926 +assign wn_re[706] = 32'hxxxxxxxx; assign wn_im[706] = 32'hxxxxxxxx; // 706 -0.371 0.929 +assign wn_re[707] = 32'hxxxxxxxx; assign wn_im[707] = 32'hxxxxxxxx; // 707 -0.366 0.931 +assign wn_re[708] = 32'hD1EEF59E; assign wn_im[708] = 32'h776C4EDB; // 708 -0.360 0.933 +assign wn_re[709] = 32'hxxxxxxxx; assign wn_im[709] = 32'hxxxxxxxx; // 709 -0.354 0.935 +assign wn_re[710] = 32'hxxxxxxxx; assign wn_im[710] = 32'hxxxxxxxx; // 710 -0.348 0.937 +assign wn_re[711] = 32'hD423B191; assign wn_im[711] = 32'h78403329; // 711 -0.343 0.939 +assign wn_re[712] = 32'hxxxxxxxx; assign wn_im[712] = 32'hxxxxxxxx; // 712 -0.337 0.942 +assign wn_re[713] = 32'hxxxxxxxx; assign wn_im[713] = 32'hxxxxxxxx; // 713 -0.331 0.944 +assign wn_re[714] = 32'hD65C3B7B; assign wn_im[714] = 32'h7909A92D; // 714 -0.325 0.946 +assign wn_re[715] = 32'hxxxxxxxx; assign wn_im[715] = 32'hxxxxxxxx; // 715 -0.320 0.948 +assign wn_re[716] = 32'hxxxxxxxx; assign wn_im[716] = 32'hxxxxxxxx; // 716 -0.314 0.950 +assign wn_re[717] = 32'hD898620C; assign wn_im[717] = 32'h79C89F6E; // 717 -0.308 0.951 +assign wn_re[718] = 32'hxxxxxxxx; assign wn_im[718] = 32'hxxxxxxxx; // 718 -0.302 0.953 +assign wn_re[719] = 32'hxxxxxxxx; assign wn_im[719] = 32'hxxxxxxxx; // 719 -0.296 0.955 +assign wn_re[720] = 32'hDAD7F3A2; assign wn_im[720] = 32'h7A7D055B; // 720 -0.290 0.957 +assign wn_re[721] = 32'hxxxxxxxx; assign wn_im[721] = 32'hxxxxxxxx; // 721 -0.284 0.959 +assign wn_re[722] = 32'hxxxxxxxx; assign wn_im[722] = 32'hxxxxxxxx; // 722 -0.279 0.960 +assign wn_re[723] = 32'hDD1ABE51; assign wn_im[723] = 32'h7B26CB4F; // 723 -0.273 0.962 +assign wn_re[724] = 32'hxxxxxxxx; assign wn_im[724] = 32'hxxxxxxxx; // 724 -0.267 0.964 +assign wn_re[725] = 32'hxxxxxxxx; assign wn_im[725] = 32'hxxxxxxxx; // 725 -0.261 0.965 +assign wn_re[726] = 32'hDF608FE4; assign wn_im[726] = 32'h7BC5E290; // 726 -0.255 0.967 +assign wn_re[727] = 32'hxxxxxxxx; assign wn_im[727] = 32'hxxxxxxxx; // 727 -0.249 0.969 +assign wn_re[728] = 32'hxxxxxxxx; assign wn_im[728] = 32'hxxxxxxxx; // 728 -0.243 0.970 +assign wn_re[729] = 32'hE1A935E2; assign wn_im[729] = 32'h7C5A3D50; // 729 -0.237 0.972 +assign wn_re[730] = 32'hxxxxxxxx; assign wn_im[730] = 32'hxxxxxxxx; // 730 -0.231 0.973 +assign wn_re[731] = 32'hxxxxxxxx; assign wn_im[731] = 32'hxxxxxxxx; // 731 -0.225 0.974 +assign wn_re[732] = 32'hE3F47D96; assign wn_im[732] = 32'h7CE3CEB2; // 732 -0.219 0.976 +assign wn_re[733] = 32'hxxxxxxxx; assign wn_im[733] = 32'hxxxxxxxx; // 733 -0.213 0.977 +assign wn_re[734] = 32'hxxxxxxxx; assign wn_im[734] = 32'hxxxxxxxx; // 734 -0.207 0.978 +assign wn_re[735] = 32'hE642340D; assign wn_im[735] = 32'h7D628AC6; // 735 -0.201 0.980 +assign wn_re[736] = 32'hxxxxxxxx; assign wn_im[736] = 32'hxxxxxxxx; // 736 -0.195 0.981 +assign wn_re[737] = 32'hxxxxxxxx; assign wn_im[737] = 32'hxxxxxxxx; // 737 -0.189 0.982 +assign wn_re[738] = 32'hE8922622; assign wn_im[738] = 32'h7DD6668F; // 738 -0.183 0.983 +assign wn_re[739] = 32'hxxxxxxxx; assign wn_im[739] = 32'hxxxxxxxx; // 739 -0.177 0.984 +assign wn_re[740] = 32'hxxxxxxxx; assign wn_im[740] = 32'hxxxxxxxx; // 740 -0.171 0.985 +assign wn_re[741] = 32'hEAE4207A; assign wn_im[741] = 32'h7E3F57FF; // 741 -0.165 0.986 +assign wn_re[742] = 32'hxxxxxxxx; assign wn_im[742] = 32'hxxxxxxxx; // 742 -0.159 0.987 +assign wn_re[743] = 32'hxxxxxxxx; assign wn_im[743] = 32'hxxxxxxxx; // 743 -0.153 0.988 +assign wn_re[744] = 32'hED37EF91; assign wn_im[744] = 32'h7E9D55FC; // 744 -0.147 0.989 +assign wn_re[745] = 32'hxxxxxxxx; assign wn_im[745] = 32'hxxxxxxxx; // 745 -0.141 0.990 +assign wn_re[746] = 32'hxxxxxxxx; assign wn_im[746] = 32'hxxxxxxxx; // 746 -0.135 0.991 +assign wn_re[747] = 32'hEF8D5FB8; assign wn_im[747] = 32'h7EF05860; // 747 -0.128 0.992 +assign wn_re[748] = 32'hxxxxxxxx; assign wn_im[748] = 32'hxxxxxxxx; // 748 -0.122 0.992 +assign wn_re[749] = 32'hxxxxxxxx; assign wn_im[749] = 32'hxxxxxxxx; // 749 -0.116 0.993 +assign wn_re[750] = 32'hF1E43D1C; assign wn_im[750] = 32'h7F3857F6; // 750 -0.110 0.994 +assign wn_re[751] = 32'hxxxxxxxx; assign wn_im[751] = 32'hxxxxxxxx; // 751 -0.104 0.995 +assign wn_re[752] = 32'hxxxxxxxx; assign wn_im[752] = 32'hxxxxxxxx; // 752 -0.098 0.995 +assign wn_re[753] = 32'hF43C53CB; assign wn_im[753] = 32'h7F754E80; // 753 -0.092 0.996 +assign wn_re[754] = 32'hxxxxxxxx; assign wn_im[754] = 32'hxxxxxxxx; // 754 -0.086 0.996 +assign wn_re[755] = 32'hxxxxxxxx; assign wn_im[755] = 32'hxxxxxxxx; // 755 -0.080 0.997 +assign wn_re[756] = 32'hF6956FB7; assign wn_im[756] = 32'h7FA736B4; // 756 -0.074 0.997 +assign wn_re[757] = 32'hxxxxxxxx; assign wn_im[757] = 32'hxxxxxxxx; // 757 -0.067 0.998 +assign wn_re[758] = 32'hxxxxxxxx; assign wn_im[758] = 32'hxxxxxxxx; // 758 -0.061 0.998 +assign wn_re[759] = 32'hF8EF5CBB; assign wn_im[759] = 32'h7FCE0C3E; // 759 -0.055 0.998 +assign wn_re[760] = 32'hxxxxxxxx; assign wn_im[760] = 32'hxxxxxxxx; // 760 -0.049 0.999 +assign wn_re[761] = 32'hxxxxxxxx; assign wn_im[761] = 32'hxxxxxxxx; // 761 -0.043 0.999 +assign wn_re[762] = 32'hFB49E6A3; assign wn_im[762] = 32'h7FE9CBC0; // 762 -0.037 0.999 +assign wn_re[763] = 32'hxxxxxxxx; assign wn_im[763] = 32'hxxxxxxxx; // 763 -0.031 1.000 +assign wn_re[764] = 32'hxxxxxxxx; assign wn_im[764] = 32'hxxxxxxxx; // 764 -0.025 1.000 +assign wn_re[765] = 32'hFDA4D929; assign wn_im[765] = 32'h7FFA72D1; // 765 -0.018 1.000 +assign wn_re[766] = 32'hxxxxxxxx; assign wn_im[766] = 32'hxxxxxxxx; // 766 -0.012 1.000 +assign wn_re[767] = 32'hxxxxxxxx; assign wn_im[767] = 32'hxxxxxxxx; // 767 -0.006 1.000 +assign wn_re[768] = 32'hxxxxxxxx; assign wn_im[768] = 32'hxxxxxxxx; // 768 -0.000 1.000 +assign wn_re[769] = 32'hxxxxxxxx; assign wn_im[769] = 32'hxxxxxxxx; // 769 0.006 1.000 +assign wn_re[770] = 32'hxxxxxxxx; assign wn_im[770] = 32'hxxxxxxxx; // 770 0.012 1.000 +assign wn_re[771] = 32'hxxxxxxxx; assign wn_im[771] = 32'hxxxxxxxx; // 771 0.018 1.000 +assign wn_re[772] = 32'hxxxxxxxx; assign wn_im[772] = 32'hxxxxxxxx; // 772 0.025 1.000 +assign wn_re[773] = 32'hxxxxxxxx; assign wn_im[773] = 32'hxxxxxxxx; // 773 0.031 1.000 +assign wn_re[774] = 32'hxxxxxxxx; assign wn_im[774] = 32'hxxxxxxxx; // 774 0.037 0.999 +assign wn_re[775] = 32'hxxxxxxxx; assign wn_im[775] = 32'hxxxxxxxx; // 775 0.043 0.999 +assign wn_re[776] = 32'hxxxxxxxx; assign wn_im[776] = 32'hxxxxxxxx; // 776 0.049 0.999 +assign wn_re[777] = 32'hxxxxxxxx; assign wn_im[777] = 32'hxxxxxxxx; // 777 0.055 0.998 +assign wn_re[778] = 32'hxxxxxxxx; assign wn_im[778] = 32'hxxxxxxxx; // 778 0.061 0.998 +assign wn_re[779] = 32'hxxxxxxxx; assign wn_im[779] = 32'hxxxxxxxx; // 779 0.067 0.998 +assign wn_re[780] = 32'hxxxxxxxx; assign wn_im[780] = 32'hxxxxxxxx; // 780 0.074 0.997 +assign wn_re[781] = 32'hxxxxxxxx; assign wn_im[781] = 32'hxxxxxxxx; // 781 0.080 0.997 +assign wn_re[782] = 32'hxxxxxxxx; assign wn_im[782] = 32'hxxxxxxxx; // 782 0.086 0.996 +assign wn_re[783] = 32'hxxxxxxxx; assign wn_im[783] = 32'hxxxxxxxx; // 783 0.092 0.996 +assign wn_re[784] = 32'hxxxxxxxx; assign wn_im[784] = 32'hxxxxxxxx; // 784 0.098 0.995 +assign wn_re[785] = 32'hxxxxxxxx; assign wn_im[785] = 32'hxxxxxxxx; // 785 0.104 0.995 +assign wn_re[786] = 32'hxxxxxxxx; assign wn_im[786] = 32'hxxxxxxxx; // 786 0.110 0.994 +assign wn_re[787] = 32'hxxxxxxxx; assign wn_im[787] = 32'hxxxxxxxx; // 787 0.116 0.993 +assign wn_re[788] = 32'hxxxxxxxx; assign wn_im[788] = 32'hxxxxxxxx; // 788 0.122 0.992 +assign wn_re[789] = 32'hxxxxxxxx; assign wn_im[789] = 32'hxxxxxxxx; // 789 0.128 0.992 +assign wn_re[790] = 32'hxxxxxxxx; assign wn_im[790] = 32'hxxxxxxxx; // 790 0.135 0.991 +assign wn_re[791] = 32'hxxxxxxxx; assign wn_im[791] = 32'hxxxxxxxx; // 791 0.141 0.990 +assign wn_re[792] = 32'hxxxxxxxx; assign wn_im[792] = 32'hxxxxxxxx; // 792 0.147 0.989 +assign wn_re[793] = 32'hxxxxxxxx; assign wn_im[793] = 32'hxxxxxxxx; // 793 0.153 0.988 +assign wn_re[794] = 32'hxxxxxxxx; assign wn_im[794] = 32'hxxxxxxxx; // 794 0.159 0.987 +assign wn_re[795] = 32'hxxxxxxxx; assign wn_im[795] = 32'hxxxxxxxx; // 795 0.165 0.986 +assign wn_re[796] = 32'hxxxxxxxx; assign wn_im[796] = 32'hxxxxxxxx; // 796 0.171 0.985 +assign wn_re[797] = 32'hxxxxxxxx; assign wn_im[797] = 32'hxxxxxxxx; // 797 0.177 0.984 +assign wn_re[798] = 32'hxxxxxxxx; assign wn_im[798] = 32'hxxxxxxxx; // 798 0.183 0.983 +assign wn_re[799] = 32'hxxxxxxxx; assign wn_im[799] = 32'hxxxxxxxx; // 799 0.189 0.982 +assign wn_re[800] = 32'hxxxxxxxx; assign wn_im[800] = 32'hxxxxxxxx; // 800 0.195 0.981 +assign wn_re[801] = 32'hxxxxxxxx; assign wn_im[801] = 32'hxxxxxxxx; // 801 0.201 0.980 +assign wn_re[802] = 32'hxxxxxxxx; assign wn_im[802] = 32'hxxxxxxxx; // 802 0.207 0.978 +assign wn_re[803] = 32'hxxxxxxxx; assign wn_im[803] = 32'hxxxxxxxx; // 803 0.213 0.977 +assign wn_re[804] = 32'hxxxxxxxx; assign wn_im[804] = 32'hxxxxxxxx; // 804 0.219 0.976 +assign wn_re[805] = 32'hxxxxxxxx; assign wn_im[805] = 32'hxxxxxxxx; // 805 0.225 0.974 +assign wn_re[806] = 32'hxxxxxxxx; assign wn_im[806] = 32'hxxxxxxxx; // 806 0.231 0.973 +assign wn_re[807] = 32'hxxxxxxxx; assign wn_im[807] = 32'hxxxxxxxx; // 807 0.237 0.972 +assign wn_re[808] = 32'hxxxxxxxx; assign wn_im[808] = 32'hxxxxxxxx; // 808 0.243 0.970 +assign wn_re[809] = 32'hxxxxxxxx; assign wn_im[809] = 32'hxxxxxxxx; // 809 0.249 0.969 +assign wn_re[810] = 32'hxxxxxxxx; assign wn_im[810] = 32'hxxxxxxxx; // 810 0.255 0.967 +assign wn_re[811] = 32'hxxxxxxxx; assign wn_im[811] = 32'hxxxxxxxx; // 811 0.261 0.965 +assign wn_re[812] = 32'hxxxxxxxx; assign wn_im[812] = 32'hxxxxxxxx; // 812 0.267 0.964 +assign wn_re[813] = 32'hxxxxxxxx; assign wn_im[813] = 32'hxxxxxxxx; // 813 0.273 0.962 +assign wn_re[814] = 32'hxxxxxxxx; assign wn_im[814] = 32'hxxxxxxxx; // 814 0.279 0.960 +assign wn_re[815] = 32'hxxxxxxxx; assign wn_im[815] = 32'hxxxxxxxx; // 815 0.284 0.959 +assign wn_re[816] = 32'hxxxxxxxx; assign wn_im[816] = 32'hxxxxxxxx; // 816 0.290 0.957 +assign wn_re[817] = 32'hxxxxxxxx; assign wn_im[817] = 32'hxxxxxxxx; // 817 0.296 0.955 +assign wn_re[818] = 32'hxxxxxxxx; assign wn_im[818] = 32'hxxxxxxxx; // 818 0.302 0.953 +assign wn_re[819] = 32'hxxxxxxxx; assign wn_im[819] = 32'hxxxxxxxx; // 819 0.308 0.951 +assign wn_re[820] = 32'hxxxxxxxx; assign wn_im[820] = 32'hxxxxxxxx; // 820 0.314 0.950 +assign wn_re[821] = 32'hxxxxxxxx; assign wn_im[821] = 32'hxxxxxxxx; // 821 0.320 0.948 +assign wn_re[822] = 32'hxxxxxxxx; assign wn_im[822] = 32'hxxxxxxxx; // 822 0.325 0.946 +assign wn_re[823] = 32'hxxxxxxxx; assign wn_im[823] = 32'hxxxxxxxx; // 823 0.331 0.944 +assign wn_re[824] = 32'hxxxxxxxx; assign wn_im[824] = 32'hxxxxxxxx; // 824 0.337 0.942 +assign wn_re[825] = 32'hxxxxxxxx; assign wn_im[825] = 32'hxxxxxxxx; // 825 0.343 0.939 +assign wn_re[826] = 32'hxxxxxxxx; assign wn_im[826] = 32'hxxxxxxxx; // 826 0.348 0.937 +assign wn_re[827] = 32'hxxxxxxxx; assign wn_im[827] = 32'hxxxxxxxx; // 827 0.354 0.935 +assign wn_re[828] = 32'hxxxxxxxx; assign wn_im[828] = 32'hxxxxxxxx; // 828 0.360 0.933 +assign wn_re[829] = 32'hxxxxxxxx; assign wn_im[829] = 32'hxxxxxxxx; // 829 0.366 0.931 +assign wn_re[830] = 32'hxxxxxxxx; assign wn_im[830] = 32'hxxxxxxxx; // 830 0.371 0.929 +assign wn_re[831] = 32'hxxxxxxxx; assign wn_im[831] = 32'hxxxxxxxx; // 831 0.377 0.926 +assign wn_re[832] = 32'hxxxxxxxx; assign wn_im[832] = 32'hxxxxxxxx; // 832 0.383 0.924 +assign wn_re[833] = 32'hxxxxxxxx; assign wn_im[833] = 32'hxxxxxxxx; // 833 0.388 0.922 +assign wn_re[834] = 32'hxxxxxxxx; assign wn_im[834] = 32'hxxxxxxxx; // 834 0.394 0.919 +assign wn_re[835] = 32'hxxxxxxxx; assign wn_im[835] = 32'hxxxxxxxx; // 835 0.400 0.917 +assign wn_re[836] = 32'hxxxxxxxx; assign wn_im[836] = 32'hxxxxxxxx; // 836 0.405 0.914 +assign wn_re[837] = 32'hxxxxxxxx; assign wn_im[837] = 32'hxxxxxxxx; // 837 0.411 0.912 +assign wn_re[838] = 32'hxxxxxxxx; assign wn_im[838] = 32'hxxxxxxxx; // 838 0.416 0.909 +assign wn_re[839] = 32'hxxxxxxxx; assign wn_im[839] = 32'hxxxxxxxx; // 839 0.422 0.907 +assign wn_re[840] = 32'hxxxxxxxx; assign wn_im[840] = 32'hxxxxxxxx; // 840 0.428 0.904 +assign wn_re[841] = 32'hxxxxxxxx; assign wn_im[841] = 32'hxxxxxxxx; // 841 0.433 0.901 +assign wn_re[842] = 32'hxxxxxxxx; assign wn_im[842] = 32'hxxxxxxxx; // 842 0.439 0.899 +assign wn_re[843] = 32'hxxxxxxxx; assign wn_im[843] = 32'hxxxxxxxx; // 843 0.444 0.896 +assign wn_re[844] = 32'hxxxxxxxx; assign wn_im[844] = 32'hxxxxxxxx; // 844 0.450 0.893 +assign wn_re[845] = 32'hxxxxxxxx; assign wn_im[845] = 32'hxxxxxxxx; // 845 0.455 0.890 +assign wn_re[846] = 32'hxxxxxxxx; assign wn_im[846] = 32'hxxxxxxxx; // 846 0.461 0.888 +assign wn_re[847] = 32'hxxxxxxxx; assign wn_im[847] = 32'hxxxxxxxx; // 847 0.466 0.885 +assign wn_re[848] = 32'hxxxxxxxx; assign wn_im[848] = 32'hxxxxxxxx; // 848 0.471 0.882 +assign wn_re[849] = 32'hxxxxxxxx; assign wn_im[849] = 32'hxxxxxxxx; // 849 0.477 0.879 +assign wn_re[850] = 32'hxxxxxxxx; assign wn_im[850] = 32'hxxxxxxxx; // 850 0.482 0.876 +assign wn_re[851] = 32'hxxxxxxxx; assign wn_im[851] = 32'hxxxxxxxx; // 851 0.488 0.873 +assign wn_re[852] = 32'hxxxxxxxx; assign wn_im[852] = 32'hxxxxxxxx; // 852 0.493 0.870 +assign wn_re[853] = 32'hxxxxxxxx; assign wn_im[853] = 32'hxxxxxxxx; // 853 0.498 0.867 +assign wn_re[854] = 32'hxxxxxxxx; assign wn_im[854] = 32'hxxxxxxxx; // 854 0.504 0.864 +assign wn_re[855] = 32'hxxxxxxxx; assign wn_im[855] = 32'hxxxxxxxx; // 855 0.509 0.861 +assign wn_re[856] = 32'hxxxxxxxx; assign wn_im[856] = 32'hxxxxxxxx; // 856 0.514 0.858 +assign wn_re[857] = 32'hxxxxxxxx; assign wn_im[857] = 32'hxxxxxxxx; // 857 0.519 0.855 +assign wn_re[858] = 32'hxxxxxxxx; assign wn_im[858] = 32'hxxxxxxxx; // 858 0.525 0.851 +assign wn_re[859] = 32'hxxxxxxxx; assign wn_im[859] = 32'hxxxxxxxx; // 859 0.530 0.848 +assign wn_re[860] = 32'hxxxxxxxx; assign wn_im[860] = 32'hxxxxxxxx; // 860 0.535 0.845 +assign wn_re[861] = 32'hxxxxxxxx; assign wn_im[861] = 32'hxxxxxxxx; // 861 0.540 0.842 +assign wn_re[862] = 32'hxxxxxxxx; assign wn_im[862] = 32'hxxxxxxxx; // 862 0.545 0.838 +assign wn_re[863] = 32'hxxxxxxxx; assign wn_im[863] = 32'hxxxxxxxx; // 863 0.550 0.835 +assign wn_re[864] = 32'hxxxxxxxx; assign wn_im[864] = 32'hxxxxxxxx; // 864 0.556 0.831 +assign wn_re[865] = 32'hxxxxxxxx; assign wn_im[865] = 32'hxxxxxxxx; // 865 0.561 0.828 +assign wn_re[866] = 32'hxxxxxxxx; assign wn_im[866] = 32'hxxxxxxxx; // 866 0.566 0.825 +assign wn_re[867] = 32'hxxxxxxxx; assign wn_im[867] = 32'hxxxxxxxx; // 867 0.571 0.821 +assign wn_re[868] = 32'hxxxxxxxx; assign wn_im[868] = 32'hxxxxxxxx; // 868 0.576 0.818 +assign wn_re[869] = 32'hxxxxxxxx; assign wn_im[869] = 32'hxxxxxxxx; // 869 0.581 0.814 +assign wn_re[870] = 32'hxxxxxxxx; assign wn_im[870] = 32'hxxxxxxxx; // 870 0.586 0.810 +assign wn_re[871] = 32'hxxxxxxxx; assign wn_im[871] = 32'hxxxxxxxx; // 871 0.591 0.807 +assign wn_re[872] = 32'hxxxxxxxx; assign wn_im[872] = 32'hxxxxxxxx; // 872 0.596 0.803 +assign wn_re[873] = 32'hxxxxxxxx; assign wn_im[873] = 32'hxxxxxxxx; // 873 0.601 0.800 +assign wn_re[874] = 32'hxxxxxxxx; assign wn_im[874] = 32'hxxxxxxxx; // 874 0.606 0.796 +assign wn_re[875] = 32'hxxxxxxxx; assign wn_im[875] = 32'hxxxxxxxx; // 875 0.610 0.792 +assign wn_re[876] = 32'hxxxxxxxx; assign wn_im[876] = 32'hxxxxxxxx; // 876 0.615 0.788 +assign wn_re[877] = 32'hxxxxxxxx; assign wn_im[877] = 32'hxxxxxxxx; // 877 0.620 0.785 +assign wn_re[878] = 32'hxxxxxxxx; assign wn_im[878] = 32'hxxxxxxxx; // 878 0.625 0.781 +assign wn_re[879] = 32'hxxxxxxxx; assign wn_im[879] = 32'hxxxxxxxx; // 879 0.630 0.777 +assign wn_re[880] = 32'hxxxxxxxx; assign wn_im[880] = 32'hxxxxxxxx; // 880 0.634 0.773 +assign wn_re[881] = 32'hxxxxxxxx; assign wn_im[881] = 32'hxxxxxxxx; // 881 0.639 0.769 +assign wn_re[882] = 32'hxxxxxxxx; assign wn_im[882] = 32'hxxxxxxxx; // 882 0.644 0.765 +assign wn_re[883] = 32'hxxxxxxxx; assign wn_im[883] = 32'hxxxxxxxx; // 883 0.649 0.761 +assign wn_re[884] = 32'hxxxxxxxx; assign wn_im[884] = 32'hxxxxxxxx; // 884 0.653 0.757 +assign wn_re[885] = 32'hxxxxxxxx; assign wn_im[885] = 32'hxxxxxxxx; // 885 0.658 0.753 +assign wn_re[886] = 32'hxxxxxxxx; assign wn_im[886] = 32'hxxxxxxxx; // 886 0.662 0.749 +assign wn_re[887] = 32'hxxxxxxxx; assign wn_im[887] = 32'hxxxxxxxx; // 887 0.667 0.745 +assign wn_re[888] = 32'hxxxxxxxx; assign wn_im[888] = 32'hxxxxxxxx; // 888 0.672 0.741 +assign wn_re[889] = 32'hxxxxxxxx; assign wn_im[889] = 32'hxxxxxxxx; // 889 0.676 0.737 +assign wn_re[890] = 32'hxxxxxxxx; assign wn_im[890] = 32'hxxxxxxxx; // 890 0.681 0.733 +assign wn_re[891] = 32'hxxxxxxxx; assign wn_im[891] = 32'hxxxxxxxx; // 891 0.685 0.728 +assign wn_re[892] = 32'hxxxxxxxx; assign wn_im[892] = 32'hxxxxxxxx; // 892 0.690 0.724 +assign wn_re[893] = 32'hxxxxxxxx; assign wn_im[893] = 32'hxxxxxxxx; // 893 0.694 0.720 +assign wn_re[894] = 32'hxxxxxxxx; assign wn_im[894] = 32'hxxxxxxxx; // 894 0.698 0.716 +assign wn_re[895] = 32'hxxxxxxxx; assign wn_im[895] = 32'hxxxxxxxx; // 895 0.703 0.711 +assign wn_re[896] = 32'hxxxxxxxx; assign wn_im[896] = 32'hxxxxxxxx; // 896 0.707 0.707 +assign wn_re[897] = 32'hxxxxxxxx; assign wn_im[897] = 32'hxxxxxxxx; // 897 0.711 0.703 +assign wn_re[898] = 32'hxxxxxxxx; assign wn_im[898] = 32'hxxxxxxxx; // 898 0.716 0.698 +assign wn_re[899] = 32'hxxxxxxxx; assign wn_im[899] = 32'hxxxxxxxx; // 899 0.720 0.694 +assign wn_re[900] = 32'hxxxxxxxx; assign wn_im[900] = 32'hxxxxxxxx; // 900 0.724 0.690 +assign wn_re[901] = 32'hxxxxxxxx; assign wn_im[901] = 32'hxxxxxxxx; // 901 0.728 0.685 +assign wn_re[902] = 32'hxxxxxxxx; assign wn_im[902] = 32'hxxxxxxxx; // 902 0.733 0.681 +assign wn_re[903] = 32'hxxxxxxxx; assign wn_im[903] = 32'hxxxxxxxx; // 903 0.737 0.676 +assign wn_re[904] = 32'hxxxxxxxx; assign wn_im[904] = 32'hxxxxxxxx; // 904 0.741 0.672 +assign wn_re[905] = 32'hxxxxxxxx; assign wn_im[905] = 32'hxxxxxxxx; // 905 0.745 0.667 +assign wn_re[906] = 32'hxxxxxxxx; assign wn_im[906] = 32'hxxxxxxxx; // 906 0.749 0.662 +assign wn_re[907] = 32'hxxxxxxxx; assign wn_im[907] = 32'hxxxxxxxx; // 907 0.753 0.658 +assign wn_re[908] = 32'hxxxxxxxx; assign wn_im[908] = 32'hxxxxxxxx; // 908 0.757 0.653 +assign wn_re[909] = 32'hxxxxxxxx; assign wn_im[909] = 32'hxxxxxxxx; // 909 0.761 0.649 +assign wn_re[910] = 32'hxxxxxxxx; assign wn_im[910] = 32'hxxxxxxxx; // 910 0.765 0.644 +assign wn_re[911] = 32'hxxxxxxxx; assign wn_im[911] = 32'hxxxxxxxx; // 911 0.769 0.639 +assign wn_re[912] = 32'hxxxxxxxx; assign wn_im[912] = 32'hxxxxxxxx; // 912 0.773 0.634 +assign wn_re[913] = 32'hxxxxxxxx; assign wn_im[913] = 32'hxxxxxxxx; // 913 0.777 0.630 +assign wn_re[914] = 32'hxxxxxxxx; assign wn_im[914] = 32'hxxxxxxxx; // 914 0.781 0.625 +assign wn_re[915] = 32'hxxxxxxxx; assign wn_im[915] = 32'hxxxxxxxx; // 915 0.785 0.620 +assign wn_re[916] = 32'hxxxxxxxx; assign wn_im[916] = 32'hxxxxxxxx; // 916 0.788 0.615 +assign wn_re[917] = 32'hxxxxxxxx; assign wn_im[917] = 32'hxxxxxxxx; // 917 0.792 0.610 +assign wn_re[918] = 32'hxxxxxxxx; assign wn_im[918] = 32'hxxxxxxxx; // 918 0.796 0.606 +assign wn_re[919] = 32'hxxxxxxxx; assign wn_im[919] = 32'hxxxxxxxx; // 919 0.800 0.601 +assign wn_re[920] = 32'hxxxxxxxx; assign wn_im[920] = 32'hxxxxxxxx; // 920 0.803 0.596 +assign wn_re[921] = 32'hxxxxxxxx; assign wn_im[921] = 32'hxxxxxxxx; // 921 0.807 0.591 +assign wn_re[922] = 32'hxxxxxxxx; assign wn_im[922] = 32'hxxxxxxxx; // 922 0.810 0.586 +assign wn_re[923] = 32'hxxxxxxxx; assign wn_im[923] = 32'hxxxxxxxx; // 923 0.814 0.581 +assign wn_re[924] = 32'hxxxxxxxx; assign wn_im[924] = 32'hxxxxxxxx; // 924 0.818 0.576 +assign wn_re[925] = 32'hxxxxxxxx; assign wn_im[925] = 32'hxxxxxxxx; // 925 0.821 0.571 +assign wn_re[926] = 32'hxxxxxxxx; assign wn_im[926] = 32'hxxxxxxxx; // 926 0.825 0.566 +assign wn_re[927] = 32'hxxxxxxxx; assign wn_im[927] = 32'hxxxxxxxx; // 927 0.828 0.561 +assign wn_re[928] = 32'hxxxxxxxx; assign wn_im[928] = 32'hxxxxxxxx; // 928 0.831 0.556 +assign wn_re[929] = 32'hxxxxxxxx; assign wn_im[929] = 32'hxxxxxxxx; // 929 0.835 0.550 +assign wn_re[930] = 32'hxxxxxxxx; assign wn_im[930] = 32'hxxxxxxxx; // 930 0.838 0.545 +assign wn_re[931] = 32'hxxxxxxxx; assign wn_im[931] = 32'hxxxxxxxx; // 931 0.842 0.540 +assign wn_re[932] = 32'hxxxxxxxx; assign wn_im[932] = 32'hxxxxxxxx; // 932 0.845 0.535 +assign wn_re[933] = 32'hxxxxxxxx; assign wn_im[933] = 32'hxxxxxxxx; // 933 0.848 0.530 +assign wn_re[934] = 32'hxxxxxxxx; assign wn_im[934] = 32'hxxxxxxxx; // 934 0.851 0.525 +assign wn_re[935] = 32'hxxxxxxxx; assign wn_im[935] = 32'hxxxxxxxx; // 935 0.855 0.519 +assign wn_re[936] = 32'hxxxxxxxx; assign wn_im[936] = 32'hxxxxxxxx; // 936 0.858 0.514 +assign wn_re[937] = 32'hxxxxxxxx; assign wn_im[937] = 32'hxxxxxxxx; // 937 0.861 0.509 +assign wn_re[938] = 32'hxxxxxxxx; assign wn_im[938] = 32'hxxxxxxxx; // 938 0.864 0.504 +assign wn_re[939] = 32'hxxxxxxxx; assign wn_im[939] = 32'hxxxxxxxx; // 939 0.867 0.498 +assign wn_re[940] = 32'hxxxxxxxx; assign wn_im[940] = 32'hxxxxxxxx; // 940 0.870 0.493 +assign wn_re[941] = 32'hxxxxxxxx; assign wn_im[941] = 32'hxxxxxxxx; // 941 0.873 0.488 +assign wn_re[942] = 32'hxxxxxxxx; assign wn_im[942] = 32'hxxxxxxxx; // 942 0.876 0.482 +assign wn_re[943] = 32'hxxxxxxxx; assign wn_im[943] = 32'hxxxxxxxx; // 943 0.879 0.477 +assign wn_re[944] = 32'hxxxxxxxx; assign wn_im[944] = 32'hxxxxxxxx; // 944 0.882 0.471 +assign wn_re[945] = 32'hxxxxxxxx; assign wn_im[945] = 32'hxxxxxxxx; // 945 0.885 0.466 +assign wn_re[946] = 32'hxxxxxxxx; assign wn_im[946] = 32'hxxxxxxxx; // 946 0.888 0.461 +assign wn_re[947] = 32'hxxxxxxxx; assign wn_im[947] = 32'hxxxxxxxx; // 947 0.890 0.455 +assign wn_re[948] = 32'hxxxxxxxx; assign wn_im[948] = 32'hxxxxxxxx; // 948 0.893 0.450 +assign wn_re[949] = 32'hxxxxxxxx; assign wn_im[949] = 32'hxxxxxxxx; // 949 0.896 0.444 +assign wn_re[950] = 32'hxxxxxxxx; assign wn_im[950] = 32'hxxxxxxxx; // 950 0.899 0.439 +assign wn_re[951] = 32'hxxxxxxxx; assign wn_im[951] = 32'hxxxxxxxx; // 951 0.901 0.433 +assign wn_re[952] = 32'hxxxxxxxx; assign wn_im[952] = 32'hxxxxxxxx; // 952 0.904 0.428 +assign wn_re[953] = 32'hxxxxxxxx; assign wn_im[953] = 32'hxxxxxxxx; // 953 0.907 0.422 +assign wn_re[954] = 32'hxxxxxxxx; assign wn_im[954] = 32'hxxxxxxxx; // 954 0.909 0.416 +assign wn_re[955] = 32'hxxxxxxxx; assign wn_im[955] = 32'hxxxxxxxx; // 955 0.912 0.411 +assign wn_re[956] = 32'hxxxxxxxx; assign wn_im[956] = 32'hxxxxxxxx; // 956 0.914 0.405 +assign wn_re[957] = 32'hxxxxxxxx; assign wn_im[957] = 32'hxxxxxxxx; // 957 0.917 0.400 +assign wn_re[958] = 32'hxxxxxxxx; assign wn_im[958] = 32'hxxxxxxxx; // 958 0.919 0.394 +assign wn_re[959] = 32'hxxxxxxxx; assign wn_im[959] = 32'hxxxxxxxx; // 959 0.922 0.388 +assign wn_re[960] = 32'hxxxxxxxx; assign wn_im[960] = 32'hxxxxxxxx; // 960 0.924 0.383 +assign wn_re[961] = 32'hxxxxxxxx; assign wn_im[961] = 32'hxxxxxxxx; // 961 0.926 0.377 +assign wn_re[962] = 32'hxxxxxxxx; assign wn_im[962] = 32'hxxxxxxxx; // 962 0.929 0.371 +assign wn_re[963] = 32'hxxxxxxxx; assign wn_im[963] = 32'hxxxxxxxx; // 963 0.931 0.366 +assign wn_re[964] = 32'hxxxxxxxx; assign wn_im[964] = 32'hxxxxxxxx; // 964 0.933 0.360 +assign wn_re[965] = 32'hxxxxxxxx; assign wn_im[965] = 32'hxxxxxxxx; // 965 0.935 0.354 +assign wn_re[966] = 32'hxxxxxxxx; assign wn_im[966] = 32'hxxxxxxxx; // 966 0.937 0.348 +assign wn_re[967] = 32'hxxxxxxxx; assign wn_im[967] = 32'hxxxxxxxx; // 967 0.939 0.343 +assign wn_re[968] = 32'hxxxxxxxx; assign wn_im[968] = 32'hxxxxxxxx; // 968 0.942 0.337 +assign wn_re[969] = 32'hxxxxxxxx; assign wn_im[969] = 32'hxxxxxxxx; // 969 0.944 0.331 +assign wn_re[970] = 32'hxxxxxxxx; assign wn_im[970] = 32'hxxxxxxxx; // 970 0.946 0.325 +assign wn_re[971] = 32'hxxxxxxxx; assign wn_im[971] = 32'hxxxxxxxx; // 971 0.948 0.320 +assign wn_re[972] = 32'hxxxxxxxx; assign wn_im[972] = 32'hxxxxxxxx; // 972 0.950 0.314 +assign wn_re[973] = 32'hxxxxxxxx; assign wn_im[973] = 32'hxxxxxxxx; // 973 0.951 0.308 +assign wn_re[974] = 32'hxxxxxxxx; assign wn_im[974] = 32'hxxxxxxxx; // 974 0.953 0.302 +assign wn_re[975] = 32'hxxxxxxxx; assign wn_im[975] = 32'hxxxxxxxx; // 975 0.955 0.296 +assign wn_re[976] = 32'hxxxxxxxx; assign wn_im[976] = 32'hxxxxxxxx; // 976 0.957 0.290 +assign wn_re[977] = 32'hxxxxxxxx; assign wn_im[977] = 32'hxxxxxxxx; // 977 0.959 0.284 +assign wn_re[978] = 32'hxxxxxxxx; assign wn_im[978] = 32'hxxxxxxxx; // 978 0.960 0.279 +assign wn_re[979] = 32'hxxxxxxxx; assign wn_im[979] = 32'hxxxxxxxx; // 979 0.962 0.273 +assign wn_re[980] = 32'hxxxxxxxx; assign wn_im[980] = 32'hxxxxxxxx; // 980 0.964 0.267 +assign wn_re[981] = 32'hxxxxxxxx; assign wn_im[981] = 32'hxxxxxxxx; // 981 0.965 0.261 +assign wn_re[982] = 32'hxxxxxxxx; assign wn_im[982] = 32'hxxxxxxxx; // 982 0.967 0.255 +assign wn_re[983] = 32'hxxxxxxxx; assign wn_im[983] = 32'hxxxxxxxx; // 983 0.969 0.249 +assign wn_re[984] = 32'hxxxxxxxx; assign wn_im[984] = 32'hxxxxxxxx; // 984 0.970 0.243 +assign wn_re[985] = 32'hxxxxxxxx; assign wn_im[985] = 32'hxxxxxxxx; // 985 0.972 0.237 +assign wn_re[986] = 32'hxxxxxxxx; assign wn_im[986] = 32'hxxxxxxxx; // 986 0.973 0.231 +assign wn_re[987] = 32'hxxxxxxxx; assign wn_im[987] = 32'hxxxxxxxx; // 987 0.974 0.225 +assign wn_re[988] = 32'hxxxxxxxx; assign wn_im[988] = 32'hxxxxxxxx; // 988 0.976 0.219 +assign wn_re[989] = 32'hxxxxxxxx; assign wn_im[989] = 32'hxxxxxxxx; // 989 0.977 0.213 +assign wn_re[990] = 32'hxxxxxxxx; assign wn_im[990] = 32'hxxxxxxxx; // 990 0.978 0.207 +assign wn_re[991] = 32'hxxxxxxxx; assign wn_im[991] = 32'hxxxxxxxx; // 991 0.980 0.201 +assign wn_re[992] = 32'hxxxxxxxx; assign wn_im[992] = 32'hxxxxxxxx; // 992 0.981 0.195 +assign wn_re[993] = 32'hxxxxxxxx; assign wn_im[993] = 32'hxxxxxxxx; // 993 0.982 0.189 +assign wn_re[994] = 32'hxxxxxxxx; assign wn_im[994] = 32'hxxxxxxxx; // 994 0.983 0.183 +assign wn_re[995] = 32'hxxxxxxxx; assign wn_im[995] = 32'hxxxxxxxx; // 995 0.984 0.177 +assign wn_re[996] = 32'hxxxxxxxx; assign wn_im[996] = 32'hxxxxxxxx; // 996 0.985 0.171 +assign wn_re[997] = 32'hxxxxxxxx; assign wn_im[997] = 32'hxxxxxxxx; // 997 0.986 0.165 +assign wn_re[998] = 32'hxxxxxxxx; assign wn_im[998] = 32'hxxxxxxxx; // 998 0.987 0.159 +assign wn_re[999] = 32'hxxxxxxxx; assign wn_im[999] = 32'hxxxxxxxx; // 999 0.988 0.153 +assign wn_re[1000] = 32'hxxxxxxxx; assign wn_im[1000] = 32'hxxxxxxxx; // 1000 0.989 0.147 +assign wn_re[1001] = 32'hxxxxxxxx; assign wn_im[1001] = 32'hxxxxxxxx; // 1001 0.990 0.141 +assign wn_re[1002] = 32'hxxxxxxxx; assign wn_im[1002] = 32'hxxxxxxxx; // 1002 0.991 0.135 +assign wn_re[1003] = 32'hxxxxxxxx; assign wn_im[1003] = 32'hxxxxxxxx; // 1003 0.992 0.128 +assign wn_re[1004] = 32'hxxxxxxxx; assign wn_im[1004] = 32'hxxxxxxxx; // 1004 0.992 0.122 +assign wn_re[1005] = 32'hxxxxxxxx; assign wn_im[1005] = 32'hxxxxxxxx; // 1005 0.993 0.116 +assign wn_re[1006] = 32'hxxxxxxxx; assign wn_im[1006] = 32'hxxxxxxxx; // 1006 0.994 0.110 +assign wn_re[1007] = 32'hxxxxxxxx; assign wn_im[1007] = 32'hxxxxxxxx; // 1007 0.995 0.104 +assign wn_re[1008] = 32'hxxxxxxxx; assign wn_im[1008] = 32'hxxxxxxxx; // 1008 0.995 0.098 +assign wn_re[1009] = 32'hxxxxxxxx; assign wn_im[1009] = 32'hxxxxxxxx; // 1009 0.996 0.092 +assign wn_re[1010] = 32'hxxxxxxxx; assign wn_im[1010] = 32'hxxxxxxxx; // 1010 0.996 0.086 +assign wn_re[1011] = 32'hxxxxxxxx; assign wn_im[1011] = 32'hxxxxxxxx; // 1011 0.997 0.080 +assign wn_re[1012] = 32'hxxxxxxxx; assign wn_im[1012] = 32'hxxxxxxxx; // 1012 0.997 0.074 +assign wn_re[1013] = 32'hxxxxxxxx; assign wn_im[1013] = 32'hxxxxxxxx; // 1013 0.998 0.067 +assign wn_re[1014] = 32'hxxxxxxxx; assign wn_im[1014] = 32'hxxxxxxxx; // 1014 0.998 0.061 +assign wn_re[1015] = 32'hxxxxxxxx; assign wn_im[1015] = 32'hxxxxxxxx; // 1015 0.998 0.055 +assign wn_re[1016] = 32'hxxxxxxxx; assign wn_im[1016] = 32'hxxxxxxxx; // 1016 0.999 0.049 +assign wn_re[1017] = 32'hxxxxxxxx; assign wn_im[1017] = 32'hxxxxxxxx; // 1017 0.999 0.043 +assign wn_re[1018] = 32'hxxxxxxxx; assign wn_im[1018] = 32'hxxxxxxxx; // 1018 0.999 0.037 +assign wn_re[1019] = 32'hxxxxxxxx; assign wn_im[1019] = 32'hxxxxxxxx; // 1019 1.000 0.031 +assign wn_re[1020] = 32'hxxxxxxxx; assign wn_im[1020] = 32'hxxxxxxxx; // 1020 1.000 0.025 +assign wn_re[1021] = 32'hxxxxxxxx; assign wn_im[1021] = 32'hxxxxxxxx; // 1021 1.000 0.018 +assign wn_re[1022] = 32'hxxxxxxxx; assign wn_im[1022] = 32'hxxxxxxxx; // 1022 1.000 0.012 +assign wn_re[1023] = 32'hxxxxxxxx; assign wn_im[1023] = 32'hxxxxxxxx; // 1023 1.000 0.006 + +endmodule diff --git a/nanamake_r22sdf/verilog/Twiddle128.v b/nanamake_r22sdf/verilog/Twiddle128.v new file mode 100644 index 0000000000000000000000000000000000000000..42d4f3634d4fcb72384fdd73887f2afebbc28146 --- /dev/null +++ b/nanamake_r22sdf/verilog/Twiddle128.v @@ -0,0 +1,168 @@ +//---------------------------------------------------------------------- +// Twiddle: 128-Point Twiddle Table for Radix-2^2 Butterfly +//---------------------------------------------------------------------- +module Twiddle #( + parameter TW_FF = 1 // Use Output Register +)( + input clock, // Master Clock + input [6:0] addr, // Twiddle Factor Number + output [15:0] tw_re, // Twiddle Factor (Real) + output [15:0] tw_im // Twiddle Factor (Imag) +); + +wire[15:0] wn_re[0:127]; // Twiddle Table (Real) +wire[15:0] wn_im[0:127]; // Twiddle Table (Imag) +wire[15:0] mx_re; // Multiplexer output (Real) +wire[15:0] mx_im; // Multiplexer output (Imag) +reg [15:0] ff_re; // Register output (Real) +reg [15:0] ff_im; // Register output (Imag) + +assign mx_re = wn_re[addr]; +assign mx_im = wn_im[addr]; + +always @(posedge clock) begin + ff_re <= mx_re; + ff_im <= mx_im; +end + +assign tw_re = TW_FF ? ff_re : mx_re; +assign tw_im = TW_FF ? ff_im : mx_im; + +//---------------------------------------------------------------------- +// Twiddle Factor Value +//---------------------------------------------------------------------- +// Multiplication is bypassed when twiddle address is 0. +// Setting wn_re[0] = 0 and wn_im[0] = 0 makes it easier to check the waveform. +// It may also reduce power consumption slightly. +// +// wn_re = cos(-2pi*n/128) wn_im = sin(-2pi*n/128) +assign wn_re[ 0] = 16'h0000; assign wn_im[ 0] = 16'h0000; // 0 1.000 -0.000 +assign wn_re[ 1] = 16'h7FD9; assign wn_im[ 1] = 16'hF9B8; // 1 0.999 -0.049 +assign wn_re[ 2] = 16'h7F62; assign wn_im[ 2] = 16'hF374; // 2 0.995 -0.098 +assign wn_re[ 3] = 16'h7E9D; assign wn_im[ 3] = 16'hED38; // 3 0.989 -0.147 +assign wn_re[ 4] = 16'h7D8A; assign wn_im[ 4] = 16'hE707; // 4 0.981 -0.195 +assign wn_re[ 5] = 16'h7C2A; assign wn_im[ 5] = 16'hE0E6; // 5 0.970 -0.243 +assign wn_re[ 6] = 16'h7A7D; assign wn_im[ 6] = 16'hDAD8; // 6 0.957 -0.290 +assign wn_re[ 7] = 16'h7885; assign wn_im[ 7] = 16'hD4E1; // 7 0.942 -0.337 +assign wn_re[ 8] = 16'h7642; assign wn_im[ 8] = 16'hCF04; // 8 0.924 -0.383 +assign wn_re[ 9] = 16'h73B6; assign wn_im[ 9] = 16'hC946; // 9 0.904 -0.428 +assign wn_re[10] = 16'h70E3; assign wn_im[10] = 16'hC3A9; // 10 0.882 -0.471 +assign wn_re[11] = 16'h6DCA; assign wn_im[11] = 16'hBE32; // 11 0.858 -0.514 +assign wn_re[12] = 16'h6A6E; assign wn_im[12] = 16'hB8E3; // 12 0.831 -0.556 +assign wn_re[13] = 16'h66D0; assign wn_im[13] = 16'hB3C0; // 13 0.803 -0.596 +assign wn_re[14] = 16'h62F2; assign wn_im[14] = 16'hAECC; // 14 0.773 -0.634 +assign wn_re[15] = 16'h5ED7; assign wn_im[15] = 16'hAA0A; // 15 0.741 -0.672 +assign wn_re[16] = 16'h5A82; assign wn_im[16] = 16'hA57E; // 16 0.707 -0.707 +assign wn_re[17] = 16'h55F6; assign wn_im[17] = 16'hA129; // 17 0.672 -0.741 +assign wn_re[18] = 16'h5134; assign wn_im[18] = 16'h9D0E; // 18 0.634 -0.773 +assign wn_re[19] = 16'h4C40; assign wn_im[19] = 16'h9930; // 19 0.596 -0.803 +assign wn_re[20] = 16'h471D; assign wn_im[20] = 16'h9592; // 20 0.556 -0.831 +assign wn_re[21] = 16'h41CE; assign wn_im[21] = 16'h9236; // 21 0.514 -0.858 +assign wn_re[22] = 16'h3C57; assign wn_im[22] = 16'h8F1D; // 22 0.471 -0.882 +assign wn_re[23] = 16'h36BA; assign wn_im[23] = 16'h8C4A; // 23 0.428 -0.904 +assign wn_re[24] = 16'h30FC; assign wn_im[24] = 16'h89BE; // 24 0.383 -0.924 +assign wn_re[25] = 16'h2B1F; assign wn_im[25] = 16'h877B; // 25 0.337 -0.942 +assign wn_re[26] = 16'h2528; assign wn_im[26] = 16'h8583; // 26 0.290 -0.957 +assign wn_re[27] = 16'h1F1A; assign wn_im[27] = 16'h83D6; // 27 0.243 -0.970 +assign wn_re[28] = 16'h18F9; assign wn_im[28] = 16'h8276; // 28 0.195 -0.981 +assign wn_re[29] = 16'h12C8; assign wn_im[29] = 16'h8163; // 29 0.147 -0.989 +assign wn_re[30] = 16'h0C8C; assign wn_im[30] = 16'h809E; // 30 0.098 -0.995 +assign wn_re[31] = 16'h0648; assign wn_im[31] = 16'h8027; // 31 0.049 -0.999 +assign wn_re[32] = 16'h0000; assign wn_im[32] = 16'h8000; // 32 0.000 -1.000 +assign wn_re[33] = 16'hF9B8; assign wn_im[33] = 16'h8027; // 33 -0.049 -0.999 +assign wn_re[34] = 16'hF374; assign wn_im[34] = 16'h809E; // 34 -0.098 -0.995 +assign wn_re[35] = 16'hxxxx; assign wn_im[35] = 16'hxxxx; // 35 -0.147 -0.989 +assign wn_re[36] = 16'hE707; assign wn_im[36] = 16'h8276; // 36 -0.195 -0.981 +assign wn_re[37] = 16'hxxxx; assign wn_im[37] = 16'hxxxx; // 37 -0.243 -0.970 +assign wn_re[38] = 16'hDAD8; assign wn_im[38] = 16'h8583; // 38 -0.290 -0.957 +assign wn_re[39] = 16'hD4E1; assign wn_im[39] = 16'h877B; // 39 -0.337 -0.942 +assign wn_re[40] = 16'hCF04; assign wn_im[40] = 16'h89BE; // 40 -0.383 -0.924 +assign wn_re[41] = 16'hxxxx; assign wn_im[41] = 16'hxxxx; // 41 -0.428 -0.904 +assign wn_re[42] = 16'hC3A9; assign wn_im[42] = 16'h8F1D; // 42 -0.471 -0.882 +assign wn_re[43] = 16'hxxxx; assign wn_im[43] = 16'hxxxx; // 43 -0.514 -0.858 +assign wn_re[44] = 16'hB8E3; assign wn_im[44] = 16'h9592; // 44 -0.556 -0.831 +assign wn_re[45] = 16'hB3C0; assign wn_im[45] = 16'h9930; // 45 -0.596 -0.803 +assign wn_re[46] = 16'hAECC; assign wn_im[46] = 16'h9D0E; // 46 -0.634 -0.773 +assign wn_re[47] = 16'hxxxx; assign wn_im[47] = 16'hxxxx; // 47 -0.672 -0.741 +assign wn_re[48] = 16'hA57E; assign wn_im[48] = 16'hA57E; // 48 -0.707 -0.707 +assign wn_re[49] = 16'hxxxx; assign wn_im[49] = 16'hxxxx; // 49 -0.741 -0.672 +assign wn_re[50] = 16'h9D0E; assign wn_im[50] = 16'hAECC; // 50 -0.773 -0.634 +assign wn_re[51] = 16'h9930; assign wn_im[51] = 16'hB3C0; // 51 -0.803 -0.596 +assign wn_re[52] = 16'h9592; assign wn_im[52] = 16'hB8E3; // 52 -0.831 -0.556 +assign wn_re[53] = 16'hxxxx; assign wn_im[53] = 16'hxxxx; // 53 -0.858 -0.514 +assign wn_re[54] = 16'h8F1D; assign wn_im[54] = 16'hC3A9; // 54 -0.882 -0.471 +assign wn_re[55] = 16'hxxxx; assign wn_im[55] = 16'hxxxx; // 55 -0.904 -0.428 +assign wn_re[56] = 16'h89BE; assign wn_im[56] = 16'hCF04; // 56 -0.924 -0.383 +assign wn_re[57] = 16'h877B; assign wn_im[57] = 16'hD4E1; // 57 -0.942 -0.337 +assign wn_re[58] = 16'h8583; assign wn_im[58] = 16'hDAD8; // 58 -0.957 -0.290 +assign wn_re[59] = 16'hxxxx; assign wn_im[59] = 16'hxxxx; // 59 -0.970 -0.243 +assign wn_re[60] = 16'h8276; assign wn_im[60] = 16'hE707; // 60 -0.981 -0.195 +assign wn_re[61] = 16'hxxxx; assign wn_im[61] = 16'hxxxx; // 61 -0.989 -0.147 +assign wn_re[62] = 16'h809E; assign wn_im[62] = 16'hF374; // 62 -0.995 -0.098 +assign wn_re[63] = 16'h8027; assign wn_im[63] = 16'hF9B8; // 63 -0.999 -0.049 +assign wn_re[64] = 16'hxxxx; assign wn_im[64] = 16'hxxxx; // 64 -1.000 -0.000 +assign wn_re[65] = 16'hxxxx; assign wn_im[65] = 16'hxxxx; // 65 -0.999 0.049 +assign wn_re[66] = 16'h809E; assign wn_im[66] = 16'h0C8C; // 66 -0.995 0.098 +assign wn_re[67] = 16'hxxxx; assign wn_im[67] = 16'hxxxx; // 67 -0.989 0.147 +assign wn_re[68] = 16'hxxxx; assign wn_im[68] = 16'hxxxx; // 68 -0.981 0.195 +assign wn_re[69] = 16'h83D6; assign wn_im[69] = 16'h1F1A; // 69 -0.970 0.243 +assign wn_re[70] = 16'hxxxx; assign wn_im[70] = 16'hxxxx; // 70 -0.957 0.290 +assign wn_re[71] = 16'hxxxx; assign wn_im[71] = 16'hxxxx; // 71 -0.942 0.337 +assign wn_re[72] = 16'h89BE; assign wn_im[72] = 16'h30FC; // 72 -0.924 0.383 +assign wn_re[73] = 16'hxxxx; assign wn_im[73] = 16'hxxxx; // 73 -0.904 0.428 +assign wn_re[74] = 16'hxxxx; assign wn_im[74] = 16'hxxxx; // 74 -0.882 0.471 +assign wn_re[75] = 16'h9236; assign wn_im[75] = 16'h41CE; // 75 -0.858 0.514 +assign wn_re[76] = 16'hxxxx; assign wn_im[76] = 16'hxxxx; // 76 -0.831 0.556 +assign wn_re[77] = 16'hxxxx; assign wn_im[77] = 16'hxxxx; // 77 -0.803 0.596 +assign wn_re[78] = 16'h9D0E; assign wn_im[78] = 16'h5134; // 78 -0.773 0.634 +assign wn_re[79] = 16'hxxxx; assign wn_im[79] = 16'hxxxx; // 79 -0.741 0.672 +assign wn_re[80] = 16'hxxxx; assign wn_im[80] = 16'hxxxx; // 80 -0.707 0.707 +assign wn_re[81] = 16'hAA0A; assign wn_im[81] = 16'h5ED7; // 81 -0.672 0.741 +assign wn_re[82] = 16'hxxxx; assign wn_im[82] = 16'hxxxx; // 82 -0.634 0.773 +assign wn_re[83] = 16'hxxxx; assign wn_im[83] = 16'hxxxx; // 83 -0.596 0.803 +assign wn_re[84] = 16'hB8E3; assign wn_im[84] = 16'h6A6E; // 84 -0.556 0.831 +assign wn_re[85] = 16'hxxxx; assign wn_im[85] = 16'hxxxx; // 85 -0.514 0.858 +assign wn_re[86] = 16'hxxxx; assign wn_im[86] = 16'hxxxx; // 86 -0.471 0.882 +assign wn_re[87] = 16'hC946; assign wn_im[87] = 16'h73B6; // 87 -0.428 0.904 +assign wn_re[88] = 16'hxxxx; assign wn_im[88] = 16'hxxxx; // 88 -0.383 0.924 +assign wn_re[89] = 16'hxxxx; assign wn_im[89] = 16'hxxxx; // 89 -0.337 0.942 +assign wn_re[90] = 16'hDAD8; assign wn_im[90] = 16'h7A7D; // 90 -0.290 0.957 +assign wn_re[91] = 16'hxxxx; assign wn_im[91] = 16'hxxxx; // 91 -0.243 0.970 +assign wn_re[92] = 16'hxxxx; assign wn_im[92] = 16'hxxxx; // 92 -0.195 0.981 +assign wn_re[93] = 16'hED38; assign wn_im[93] = 16'h7E9D; // 93 -0.147 0.989 +assign wn_re[94] = 16'hxxxx; assign wn_im[94] = 16'hxxxx; // 94 -0.098 0.995 +assign wn_re[95] = 16'hxxxx; assign wn_im[95] = 16'hxxxx; // 95 -0.049 0.999 +assign wn_re[96] = 16'hxxxx; assign wn_im[96] = 16'hxxxx; // 96 -0.000 1.000 +assign wn_re[97] = 16'hxxxx; assign wn_im[97] = 16'hxxxx; // 97 0.049 0.999 +assign wn_re[98] = 16'hxxxx; assign wn_im[98] = 16'hxxxx; // 98 0.098 0.995 +assign wn_re[99] = 16'hxxxx; assign wn_im[99] = 16'hxxxx; // 99 0.147 0.989 +assign wn_re[100] = 16'hxxxx; assign wn_im[100] = 16'hxxxx; // 100 0.195 0.981 +assign wn_re[101] = 16'hxxxx; assign wn_im[101] = 16'hxxxx; // 101 0.243 0.970 +assign wn_re[102] = 16'hxxxx; assign wn_im[102] = 16'hxxxx; // 102 0.290 0.957 +assign wn_re[103] = 16'hxxxx; assign wn_im[103] = 16'hxxxx; // 103 0.337 0.942 +assign wn_re[104] = 16'hxxxx; assign wn_im[104] = 16'hxxxx; // 104 0.383 0.924 +assign wn_re[105] = 16'hxxxx; assign wn_im[105] = 16'hxxxx; // 105 0.428 0.904 +assign wn_re[106] = 16'hxxxx; assign wn_im[106] = 16'hxxxx; // 106 0.471 0.882 +assign wn_re[107] = 16'hxxxx; assign wn_im[107] = 16'hxxxx; // 107 0.514 0.858 +assign wn_re[108] = 16'hxxxx; assign wn_im[108] = 16'hxxxx; // 108 0.556 0.831 +assign wn_re[109] = 16'hxxxx; assign wn_im[109] = 16'hxxxx; // 109 0.596 0.803 +assign wn_re[110] = 16'hxxxx; assign wn_im[110] = 16'hxxxx; // 110 0.634 0.773 +assign wn_re[111] = 16'hxxxx; assign wn_im[111] = 16'hxxxx; // 111 0.672 0.741 +assign wn_re[112] = 16'hxxxx; assign wn_im[112] = 16'hxxxx; // 112 0.707 0.707 +assign wn_re[113] = 16'hxxxx; assign wn_im[113] = 16'hxxxx; // 113 0.741 0.672 +assign wn_re[114] = 16'hxxxx; assign wn_im[114] = 16'hxxxx; // 114 0.773 0.634 +assign wn_re[115] = 16'hxxxx; assign wn_im[115] = 16'hxxxx; // 115 0.803 0.596 +assign wn_re[116] = 16'hxxxx; assign wn_im[116] = 16'hxxxx; // 116 0.831 0.556 +assign wn_re[117] = 16'hxxxx; assign wn_im[117] = 16'hxxxx; // 117 0.858 0.514 +assign wn_re[118] = 16'hxxxx; assign wn_im[118] = 16'hxxxx; // 118 0.882 0.471 +assign wn_re[119] = 16'hxxxx; assign wn_im[119] = 16'hxxxx; // 119 0.904 0.428 +assign wn_re[120] = 16'hxxxx; assign wn_im[120] = 16'hxxxx; // 120 0.924 0.383 +assign wn_re[121] = 16'hxxxx; assign wn_im[121] = 16'hxxxx; // 121 0.942 0.337 +assign wn_re[122] = 16'hxxxx; assign wn_im[122] = 16'hxxxx; // 122 0.957 0.290 +assign wn_re[123] = 16'hxxxx; assign wn_im[123] = 16'hxxxx; // 123 0.970 0.243 +assign wn_re[124] = 16'hxxxx; assign wn_im[124] = 16'hxxxx; // 124 0.981 0.195 +assign wn_re[125] = 16'hxxxx; assign wn_im[125] = 16'hxxxx; // 125 0.989 0.147 +assign wn_re[126] = 16'hxxxx; assign wn_im[126] = 16'hxxxx; // 126 0.995 0.098 +assign wn_re[127] = 16'hxxxx; assign wn_im[127] = 16'hxxxx; // 127 0.999 0.049 + +endmodule diff --git a/nanamake_r22sdf/verilog/Twiddle64.v b/nanamake_r22sdf/verilog/Twiddle64.v new file mode 100644 index 0000000000000000000000000000000000000000..22b1ac0fdda32db9ad710f5c623566a9388555e5 --- /dev/null +++ b/nanamake_r22sdf/verilog/Twiddle64.v @@ -0,0 +1,104 @@ +//---------------------------------------------------------------------- +// Twiddle: 64-Point Twiddle Table for Radix-2^2 Butterfly +//---------------------------------------------------------------------- +module Twiddle #( + parameter TW_FF = 1 // Use Output Register +)( + input clock, // Master Clock + input [5:0] addr, // Twiddle Factor Number + output [15:0] tw_re, // Twiddle Factor (Real) + output [15:0] tw_im // Twiddle Factor (Imag) +); + +wire[15:0] wn_re[0:63]; // Twiddle Table (Real) +wire[15:0] wn_im[0:63]; // Twiddle Table (Imag) +wire[15:0] mx_re; // Multiplexer output (Real) +wire[15:0] mx_im; // Multiplexer output (Imag) +reg [15:0] ff_re; // Register output (Real) +reg [15:0] ff_im; // Register output (Imag) + +assign mx_re = wn_re[addr]; +assign mx_im = wn_im[addr]; + +always @(posedge clock) begin + ff_re <= mx_re; + ff_im <= mx_im; +end + +assign tw_re = TW_FF ? ff_re : mx_re; +assign tw_im = TW_FF ? ff_im : mx_im; + +//---------------------------------------------------------------------- +// Twiddle Factor Value +//---------------------------------------------------------------------- +// Multiplication is bypassed when twiddle address is 0. +// Setting wn_re[0] = 0 and wn_im[0] = 0 makes it easier to check the waveform. +// It may also reduce power consumption slightly. +// +// wn_re = cos(-2pi*n/64) wn_im = sin(-2pi*n/64) +assign wn_re[ 0] = 16'h0000; assign wn_im[ 0] = 16'h0000; // 0 1.000 -0.000 +assign wn_re[ 1] = 16'h7F62; assign wn_im[ 1] = 16'hF374; // 1 0.995 -0.098 +assign wn_re[ 2] = 16'h7D8A; assign wn_im[ 2] = 16'hE707; // 2 0.981 -0.195 +assign wn_re[ 3] = 16'h7A7D; assign wn_im[ 3] = 16'hDAD8; // 3 0.957 -0.290 +assign wn_re[ 4] = 16'h7642; assign wn_im[ 4] = 16'hCF04; // 4 0.924 -0.383 +assign wn_re[ 5] = 16'h70E3; assign wn_im[ 5] = 16'hC3A9; // 5 0.882 -0.471 +assign wn_re[ 6] = 16'h6A6E; assign wn_im[ 6] = 16'hB8E3; // 6 0.831 -0.556 +assign wn_re[ 7] = 16'h62F2; assign wn_im[ 7] = 16'hAECC; // 7 0.773 -0.634 +assign wn_re[ 8] = 16'h5A82; assign wn_im[ 8] = 16'hA57E; // 8 0.707 -0.707 +assign wn_re[ 9] = 16'h5134; assign wn_im[ 9] = 16'h9D0E; // 9 0.634 -0.773 +assign wn_re[10] = 16'h471D; assign wn_im[10] = 16'h9592; // 10 0.556 -0.831 +assign wn_re[11] = 16'h3C57; assign wn_im[11] = 16'h8F1D; // 11 0.471 -0.882 +assign wn_re[12] = 16'h30FC; assign wn_im[12] = 16'h89BE; // 12 0.383 -0.924 +assign wn_re[13] = 16'h2528; assign wn_im[13] = 16'h8583; // 13 0.290 -0.957 +assign wn_re[14] = 16'h18F9; assign wn_im[14] = 16'h8276; // 14 0.195 -0.981 +assign wn_re[15] = 16'h0C8C; assign wn_im[15] = 16'h809E; // 15 0.098 -0.995 +assign wn_re[16] = 16'h0000; assign wn_im[16] = 16'h8000; // 16 0.000 -1.000 +assign wn_re[17] = 16'hxxxx; assign wn_im[17] = 16'hxxxx; // 17 -0.098 -0.995 +assign wn_re[18] = 16'hE707; assign wn_im[18] = 16'h8276; // 18 -0.195 -0.981 +assign wn_re[19] = 16'hxxxx; assign wn_im[19] = 16'hxxxx; // 19 -0.290 -0.957 +assign wn_re[20] = 16'hCF04; assign wn_im[20] = 16'h89BE; // 20 -0.383 -0.924 +assign wn_re[21] = 16'hC3A9; assign wn_im[21] = 16'h8F1D; // 21 -0.471 -0.882 +assign wn_re[22] = 16'hB8E3; assign wn_im[22] = 16'h9592; // 22 -0.556 -0.831 +assign wn_re[23] = 16'hxxxx; assign wn_im[23] = 16'hxxxx; // 23 -0.634 -0.773 +assign wn_re[24] = 16'hA57E; assign wn_im[24] = 16'hA57E; // 24 -0.707 -0.707 +assign wn_re[25] = 16'hxxxx; assign wn_im[25] = 16'hxxxx; // 25 -0.773 -0.634 +assign wn_re[26] = 16'h9592; assign wn_im[26] = 16'hB8E3; // 26 -0.831 -0.556 +assign wn_re[27] = 16'h8F1D; assign wn_im[27] = 16'hC3A9; // 27 -0.882 -0.471 +assign wn_re[28] = 16'h89BE; assign wn_im[28] = 16'hCF04; // 28 -0.924 -0.383 +assign wn_re[29] = 16'hxxxx; assign wn_im[29] = 16'hxxxx; // 29 -0.957 -0.290 +assign wn_re[30] = 16'h8276; assign wn_im[30] = 16'hE707; // 30 -0.981 -0.195 +assign wn_re[31] = 16'hxxxx; assign wn_im[31] = 16'hxxxx; // 31 -0.995 -0.098 +assign wn_re[32] = 16'hxxxx; assign wn_im[32] = 16'hxxxx; // 32 -1.000 -0.000 +assign wn_re[33] = 16'h809E; assign wn_im[33] = 16'h0C8C; // 33 -0.995 0.098 +assign wn_re[34] = 16'hxxxx; assign wn_im[34] = 16'hxxxx; // 34 -0.981 0.195 +assign wn_re[35] = 16'hxxxx; assign wn_im[35] = 16'hxxxx; // 35 -0.957 0.290 +assign wn_re[36] = 16'h89BE; assign wn_im[36] = 16'h30FC; // 36 -0.924 0.383 +assign wn_re[37] = 16'hxxxx; assign wn_im[37] = 16'hxxxx; // 37 -0.882 0.471 +assign wn_re[38] = 16'hxxxx; assign wn_im[38] = 16'hxxxx; // 38 -0.831 0.556 +assign wn_re[39] = 16'h9D0E; assign wn_im[39] = 16'h5134; // 39 -0.773 0.634 +assign wn_re[40] = 16'hxxxx; assign wn_im[40] = 16'hxxxx; // 40 -0.707 0.707 +assign wn_re[41] = 16'hxxxx; assign wn_im[41] = 16'hxxxx; // 41 -0.634 0.773 +assign wn_re[42] = 16'hB8E3; assign wn_im[42] = 16'h6A6E; // 42 -0.556 0.831 +assign wn_re[43] = 16'hxxxx; assign wn_im[43] = 16'hxxxx; // 43 -0.471 0.882 +assign wn_re[44] = 16'hxxxx; assign wn_im[44] = 16'hxxxx; // 44 -0.383 0.924 +assign wn_re[45] = 16'hDAD8; assign wn_im[45] = 16'h7A7D; // 45 -0.290 0.957 +assign wn_re[46] = 16'hxxxx; assign wn_im[46] = 16'hxxxx; // 46 -0.195 0.981 +assign wn_re[47] = 16'hxxxx; assign wn_im[47] = 16'hxxxx; // 47 -0.098 0.995 +assign wn_re[48] = 16'hxxxx; assign wn_im[48] = 16'hxxxx; // 48 -0.000 1.000 +assign wn_re[49] = 16'hxxxx; assign wn_im[49] = 16'hxxxx; // 49 0.098 0.995 +assign wn_re[50] = 16'hxxxx; assign wn_im[50] = 16'hxxxx; // 50 0.195 0.981 +assign wn_re[51] = 16'hxxxx; assign wn_im[51] = 16'hxxxx; // 51 0.290 0.957 +assign wn_re[52] = 16'hxxxx; assign wn_im[52] = 16'hxxxx; // 52 0.383 0.924 +assign wn_re[53] = 16'hxxxx; assign wn_im[53] = 16'hxxxx; // 53 0.471 0.882 +assign wn_re[54] = 16'hxxxx; assign wn_im[54] = 16'hxxxx; // 54 0.556 0.831 +assign wn_re[55] = 16'hxxxx; assign wn_im[55] = 16'hxxxx; // 55 0.634 0.773 +assign wn_re[56] = 16'hxxxx; assign wn_im[56] = 16'hxxxx; // 56 0.707 0.707 +assign wn_re[57] = 16'hxxxx; assign wn_im[57] = 16'hxxxx; // 57 0.773 0.634 +assign wn_re[58] = 16'hxxxx; assign wn_im[58] = 16'hxxxx; // 58 0.831 0.556 +assign wn_re[59] = 16'hxxxx; assign wn_im[59] = 16'hxxxx; // 59 0.882 0.471 +assign wn_re[60] = 16'hxxxx; assign wn_im[60] = 16'hxxxx; // 60 0.924 0.383 +assign wn_re[61] = 16'hxxxx; assign wn_im[61] = 16'hxxxx; // 61 0.957 0.290 +assign wn_re[62] = 16'hxxxx; assign wn_im[62] = 16'hxxxx; // 62 0.981 0.195 +assign wn_re[63] = 16'hxxxx; assign wn_im[63] = 16'hxxxx; // 63 0.995 0.098 + +endmodule diff --git a/nanamake_r22sdf/verilog/TwiddleConvert4.v b/nanamake_r22sdf/verilog/TwiddleConvert4.v new file mode 100644 index 0000000000000000000000000000000000000000..d93502f8a6c70cb49c6080982e3996669eb97000 --- /dev/null +++ b/nanamake_r22sdf/verilog/TwiddleConvert4.v @@ -0,0 +1,61 @@ +//---------------------------------------------------------------------- +// TwiddleConvert4: Convert Twiddle Value to Reduce Table Size to 1/4 +//---------------------------------------------------------------------- +module TwiddleConvert4 #( + parameter LOG_N = 6, // Address Bit Length + parameter WIDTH = 16, // Data Bit Length + parameter TW_FF = 1, // Use Twiddle Output Register + parameter TC_FF = 1 // Use Output Register +)( + input clock, // Master Clock + input [LOG_N-1:0] tw_addr, // Twiddle Number + input [WIDTH-1:0] tw_re, // Twiddle Value (Real) + input [WIDTH-1:0] tw_im, // Twiddle Value (Imag) + output [LOG_N-1:0] tc_addr, // Converted Twiddle Number + output [WIDTH-1:0] tc_re, // Converted Twiddle Value (Real) + output [WIDTH-1:0] tc_im // Converted Twiddle Value (Imag) +); + +// Internal Nets +reg [LOG_N-1:0] ff_addr; +wire[LOG_N-1:0] sel_addr; +reg [WIDTH-1:0] mx_re; +reg [WIDTH-1:0] mx_im; +reg [WIDTH-1:0] ff_re; +reg [WIDTH-1:0] ff_im; + +// Convert Twiddle Number +assign tc_addr[LOG_N-1:LOG_N-2] = 2'd0; +assign tc_addr[LOG_N-3:0] = tw_addr[LOG_N-3:0]; + +// Convert Twiddle Value +always @(posedge clock) begin + ff_addr <= tw_addr; +end +assign sel_addr = TW_FF ? ff_addr : tw_addr; + +always @* begin + if (sel_addr[LOG_N-3:0] == {LOG_N-2{1'b0}}) begin + case (sel_addr[LOG_N-1:LOG_N-2]) + 2'd0 : {mx_re, mx_im} <= {{WIDTH{1'b0}}, {WIDTH{1'b0}}}; + 2'd1 : {mx_re, mx_im} <= {{WIDTH{1'b0}}, {1'b1,{WIDTH-1{1'b0}}}}; + default : {mx_re, mx_im} <= {{WIDTH{1'bx}}, {WIDTH{1'bx}}}; + endcase + end else begin + case (sel_addr[LOG_N-1:LOG_N-2]) + 2'd0 : {mx_re, mx_im} <= { tw_re, tw_im}; + 2'd1 : {mx_re, mx_im} <= { tw_im, -tw_re}; + 2'd2 : {mx_re, mx_im} <= {-tw_re, -tw_im}; + default : {mx_re, mx_im} <= {{WIDTH{1'bx}}, {WIDTH{1'bx}}}; + endcase + end +end +always @(posedge clock) begin + ff_re <= mx_re; + ff_im <= mx_im; +end + +assign tc_re = TC_FF ? ff_re : mx_re; +assign tc_im = TC_FF ? ff_im : mx_im; + +endmodule diff --git a/nanamake_r22sdf/verilog/TwiddleConvert8.v b/nanamake_r22sdf/verilog/TwiddleConvert8.v new file mode 100644 index 0000000000000000000000000000000000000000..801be86e0feaa2ed9c7ad975be53b3b727224c10 --- /dev/null +++ b/nanamake_r22sdf/verilog/TwiddleConvert8.v @@ -0,0 +1,70 @@ +//---------------------------------------------------------------------- +// TwiddleConvert8: Convert Twiddle Value to Reduce Table Size to 1/8 +//---------------------------------------------------------------------- +module TwiddleConvert8 #( + parameter LOG_N = 6, // Address Bit Length + parameter WIDTH = 16, // Data Bit Length + parameter TW_FF = 1, // Use Twiddle Output Register + parameter TC_FF = 1 // Use Output Register +)( + input clock, // Master Clock + input [LOG_N-1:0] tw_addr, // Twiddle Number + input [WIDTH-1:0] tw_re, // Twiddle Value (Real) + input [WIDTH-1:0] tw_im, // Twiddle Value (Imag) + output [LOG_N-1:0] tc_addr, // Converted Twiddle Number + output [WIDTH-1:0] tc_re, // Converted Twiddle Value (Real) + output [WIDTH-1:0] tc_im // Converted Twiddle Value (Imag) +); + +// Define Constants +localparam[WIDTH-1:0] COSMQ = (((32'h5A82799A<<1) >> (32-WIDTH)) + 1)>>1; // cos(-pi/4) +localparam[WIDTH-1:0] SINMH = 32'h80000000 >> (32-WIDTH); // sin(-pi/2) + +// Internal Nets +reg [LOG_N-1:0] ff_addr; +wire[LOG_N-1:0] sel_addr; +reg [WIDTH-1:0] mx_re; +reg [WIDTH-1:0] mx_im; +reg [WIDTH-1:0] ff_re; +reg [WIDTH-1:0] ff_im; + +// Convert Twiddle Number +assign tc_addr[LOG_N-1:LOG_N-3] = 3'd0; +assign tc_addr[LOG_N-4:0] = tw_addr[LOG_N-3] ? -tw_addr[LOG_N-4:0] : tw_addr[LOG_N-4:0]; + +// Convert Twiddle Value +always @(posedge clock) begin + ff_addr <= tw_addr; +end +assign sel_addr = TW_FF ? ff_addr : tw_addr; + +always @* begin + if (sel_addr[LOG_N-4:0] == {LOG_N-3{1'b0}}) begin + case (sel_addr[LOG_N-1:LOG_N-3]) + 3'd0 : {mx_re, mx_im} <= {{WIDTH{1'b0}}, {WIDTH{1'b0}}}; + 3'd1 : {mx_re, mx_im} <= { COSMQ , -COSMQ }; + 3'd2 : {mx_re, mx_im} <= {{WIDTH{1'b0}}, SINMH }; + 3'd3 : {mx_re, mx_im} <= {-COSMQ , -COSMQ }; + default : {mx_re, mx_im} <= {{WIDTH{1'bx}}, {WIDTH{1'bx}}}; + endcase + end else begin + case (sel_addr[LOG_N-1:LOG_N-3]) + 3'd0 : {mx_re, mx_im} <= { tw_re, tw_im}; + 3'd1 : {mx_re, mx_im} <= {-tw_im, -tw_re}; + 3'd2 : {mx_re, mx_im} <= { tw_im, -tw_re}; + 3'd3 : {mx_re, mx_im} <= {-tw_re, tw_im}; + 3'd4 : {mx_re, mx_im} <= {-tw_re, -tw_im}; + 3'd5 : {mx_re, mx_im} <= { tw_im, tw_re}; + default : {mx_re, mx_im} <= {{WIDTH{1'bx}}, {WIDTH{1'bx}}}; + endcase + end +end +always @(posedge clock) begin + ff_re <= mx_re; + ff_im <= mx_im; +end + +assign tc_re = TC_FF ? ff_re : mx_re; +assign tc_im = TC_FF ? ff_im : mx_im; + +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/2Image_3Filter_0Bias_Conv_Input_Output.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/2Image_3Filter_0Bias_Conv_Input_Output.txt new file mode 100644 index 0000000000000000000000000000000000000000..8fb80b72bfa188ae4dc983e58ad1c0761a9b891e --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/2Image_3Filter_0Bias_Conv_Input_Output.txt @@ -0,0 +1,72 @@ +A(:,:,1)=[2 1 2 0 1; 2 2 0 0 1; 1 1 1 0 1; 2 0 0 1 0; 0 0 0 1 1] + +A(:,:,2)=[0 0 0 1 1; 0 1 0 1 0; 2 0 0 1 0; 0 0 2 2 0; 0 0 1 1 1] + +A(:,:,3)=[2 0 0 1 0; 0 0 0 1 1; 0 0 2 2 0; 2 2 0 0 1; 0 1 0 1 0] + + +A1(:,:,1)=[2 1 0 0 1; 2 2 0 3 1; 1 1 1 0 4; 2 0 0 1 3; 1 2 0 0 1] + +A1(:,:,2)=[0 2 0 1 1; 0 1 0 1 1; 2 0 0 1 4; 0 4 2 2 0; 0 0 1 0 0] + +A1(:,:,3)=[2 0 0 1 4; 1 0 2 1 1; 1 0 2 2 0; 2 4 0 0 0; 0 1 0 1 1] + + + +B(:,:,1)=[1 0 0; 0 1 0; 0 0 1] + +B(:,:,2)=[2 0 0; 0 2 0; 0 0 2] + +B(:,:,3)=[1 0 -3; -3 0 0; 0 -3 -1] + + +B1(:,:,1)=[1 0 -2; 0 1 0; 2 0 1] + +B1(:,:,2)=[-2 0 1; 0 2 0; -1 0 2] + +B1(:,:,3)=[-1 0 -3; -1 0 0; 0 2 -1] + + +B2(:,:,1)=[0 0 1; 0 1 -2; -2 0 0] + +B2(:,:,2)=[2 0 2; 0 1 0; -2 0 -1] + +B2(:,:,3)=[0 0 3; -3 0 1; 1 0 -1] + + + +D5 = conv(A1,B2) + + -5 -1 8 + 0 7 -11 + 6 -8 6 + +D4 = conv(A1,B1) + + 2 1 8 + 11 -6 -5 + 0 -1 1 + +D3 = conv(A1,B) + + 2 -4 -7 + -14 7 -4 + 0 -14 3 + +D2 = conv(A,B2) + + -3 1 3 + -3 10 -8 + 4 1 2 + +D1 = conv(A,B1) + + -1 5 10 + 15 4 -8 + -9 0 6 + +D = conv(A,B) + + 5 -8 -1 + 1 7 -8 + -8 -5 6 \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName.txt new file mode 100644 index 0000000000000000000000000000000000000000..835959f15fa023683534c304c7028551590fa168 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName.txt @@ -0,0 +1,8 @@ +253 254 247 235 220 246 249 252 +253 247 231 232 187 178 247 252 +252 212 235 227 201 192 211 249 +249 226 201 213 215 203 226 249 +253 251 211 223 238 223 250 251 +252 254 238 240 103 240 254 254 +252 252 250 196 65 254 251 253 +251 251 251 212 215 252 253 252 diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName1.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName1.txt new file mode 100644 index 0000000000000000000000000000000000000000..835959f15fa023683534c304c7028551590fa168 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Matlab functions/FileName1.txt @@ -0,0 +1,8 @@ +253 254 247 235 220 246 249 252 +253 247 231 232 187 178 247 252 +252 212 235 227 201 192 211 249 +249 226 201 213 215 203 226 249 +253 251 211 223 238 223 250 251 +252 254 238 240 103 240 254 254 +252 252 250 196 65 254 251 253 +251 251 251 212 215 252 253 252 diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/README.md b/padhi499_Image-Classification-using-CNN-on-FPGA/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bbd52b437333bc7356cfdf0e545ac37cf83a819f --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/README.md @@ -0,0 +1,21 @@ +# Image Classification using CNN on FPGA +Project is about designing a Trained Neural n/w (CIFAR-10 dataset) on FPGA to classify an Image I/P using deep-learning concept(CNN- Convolutional Neural Network). + +There are 6 Layers(Sliding Window Convolution, ReLU Activation, Max Pooling, Flattening, Fully Connected and Softmax Activation) which decides the class of our I/P Image. Kernels/Filters are used for feature detection from an Image I/P. Image I/P can be a Greyscale/Colored one. + +# Tools Used +1. Xilinx Vivado v17.4 +2. Matlab vR2018.a + +# Languages Used +1. Verilog HDL + +# Tasks Achieved +1. Got some basic knowledge about FPGA and its Resources, Vivado 17.4, Matlab R2018a. +2. Verilog modules were created(Matrix Multiplication, Generic MUX, Matrix Convolution, ReLU Activation, Max Pooling) using Vivado 17.4. +3. Matrix functions were created using Matlab R2018a for reference purpose and matching results. +4. A Grey-scale Image was considered first (Took a Colored Image(3D Matrix) and Converted to Greyscale Image(2D Matrix) using Matlab) and compared results for both (Verilog modules & Matlab functions) for Matrix Multiplication and ReLU Activation. Results were matching. + +# Contributor +1. Abhinas Padhi(FPGA Design Engineer) +2. Shivkumar V(B. M. S. College of Engineering, Bangalore) diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/Matlab/conv_output.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/Matlab/conv_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..eb9db3476d0ce1f7a1c052ed11add5d318f7839b --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/Matlab/conv_output.txt @@ -0,0 +1,6 @@ +-448 -188 -1048 -778 992 1372 +-868 -128 -638 -988 812 1772 +-1068 -258 72 -448 332 1312 +-1038 -548 -938 -98 1742 882 +-578 -978 -2928 582 3492 412 +-158 -1088 -3558 982 3752 132 diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/bias.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/bias.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8263ee9860594d2806b0dfd1bfd17528b0ba2a4 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/bias.txt @@ -0,0 +1 @@ +2 \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input1.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input1.txt new file mode 100644 index 0000000000000000000000000000000000000000..ccc712b07e8e50265b8ef9140fd2bf8bca2ece0d --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input1.txt @@ -0,0 +1,3 @@ +10 0 -10 +10 0 -10 +10 0 -10 \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input2.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input2.txt new file mode 100644 index 0000000000000000000000000000000000000000..201853c792512fbab9ecada85a02e3a1b867bdc1 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/filter_input2.txt @@ -0,0 +1,3 @@ +-10 0 10 +-10 0 10 +-10 0 10 \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/mat_input.txt b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/mat_input.txt new file mode 100644 index 0000000000000000000000000000000000000000..835959f15fa023683534c304c7028551590fa168 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Testing/Convolution/mat_input.txt @@ -0,0 +1,8 @@ +253 254 247 235 220 246 249 252 +253 247 231 232 187 178 247 252 +252 212 235 227 201 192 211 249 +249 226 201 213 215 203 226 249 +253 251 211 223 238 223 250 251 +252 254 238 240 103 240 254 254 +252 252 250 196 65 254 251 253 +251 251 251 212 215 252 253 252 diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU.v new file mode 100644 index 0000000000000000000000000000000000000000..bf350631d74678ca030949c6a34a1e4773d3878b --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU.v @@ -0,0 +1,49 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 12/23/2019 12:38:00 PM +// Design Name: +// Module Name: ReLU +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + + +module ReLU #(parameter In_d_W=18)( + input clk, clr, en_act, en_act_out, + input signed [In_d_W-1:0] A, + output reg signed [In_d_W-1:0] Y + ); + reg signed [In_d_W-1:0] X; + always@(posedge clk) + begin + if(clr==1) + begin Y<=0; X<=0; end + else if(clr==0) begin + case({en_act,en_act_out}) + 2'b00: Y<=Y; + 2'b01: Y<=X; + 2'b10: begin + if(A<0) X<='d0; + else if(A>=0) X<=A; + end + 2'b11: begin + if(A<0) X<='d0; + else if(A>=0) X<=A; + Y<=X; + end + endcase + end + end +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU_Activation.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU_Activation.v new file mode 100644 index 0000000000000000000000000000000000000000..21d6627c8365f8c019a867d2d4a185d804d5a78a --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/ReLU_Activation.v @@ -0,0 +1,55 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 12/23/2019 01:35:53 PM +// Design Name: +// Module Name: ReLU_Activation +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + +module ReLU_Activation #(parameter In_d_W=18,R=3,C=3) ( // + input clk,clr,en_act,en_act_out, + input [(In_d_W * R * C)-1:0] X, + output [(In_d_W * R * C)-1:0] Z + ); + + wire [In_d_W-1:0] B [0:R*C-1]; + wire [In_d_W-1:0] D [0:R*C-1]; + + generate + genvar i; + for(i=0; i=R*C*In_d_W) + begin + assign Wrow[j+In_d_W-1:j]='d0; + assign Wcol[j+In_d_W-1:j]='d0; + end + end + endgenerate + + c_counter_binary_0 common( + .CLK(clk), // input wire CLK + .CE(clk_en), // input wire CE + .SCLR(clr), // input wire SCLR + .Q(addr_com) // output wire [3 : 0] Q + ); + + mux_g #((In_d_W*(2**In_Add_W)),In_Add_W) MUXrow(.A(Wrow),.S(addr_com),.Y(din_r)); + + mux_g #((In_d_W*(2**In_Add_W)),In_Add_W) MUXcol(.A(Wcol),.S(addr_com),.Y(din_c)); + + matrix_multiplier #(In_d_W,In_Add_W,R*C,Timeperiod) DUT(.clk(clk),.rst(rst),.clr(clr),.ena_r(en_wr),.ena_c(en_wr),.enb_r(en_rd), + .enb_c(en_rd),.wea_r(wr),.wea_c(wr),.din_r(din_r),.din_c(din_c),.addra_r(addr_com),.addrb_r(addr_com),.addra_c(addr_com), + .addrb_c(addr_com),.en_MAC(en_MAC),.en_MAC_out(en_MAC_out),.y(Y)); + +endmodule \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/counter_g.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/counter_g.v new file mode 100644 index 0000000000000000000000000000000000000000..80e5d349204ace40452962b4d8036827441f7254 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/counter_g.v @@ -0,0 +1,41 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 01/17/2020 01:18:19 PM +// Design Name: +// Module Name: counter_g +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + + +module counter_g #(Add_W=4)( + input CLK,RST, + input CE, + input SCLR, + output reg [Add_W-1:0] Q + ); + + always@(posedge CLK) + begin + if(RST==0) + Q<=0; + else if(SCLR==1) + Q<=0; + else if(CE==0) + Q<=Q; + else if(CE==1) + Q<=Q+1; + end +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mac_generic.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mac_generic.v new file mode 100644 index 0000000000000000000000000000000000000000..cc999b5b8afb8742c619c1960a350757ed69ab30 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mac_generic.v @@ -0,0 +1,48 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 11/12/2019 12:02:06 PM +// Design Name: +// Module Name: mac_generic +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + +module mac_generic #(parameter I_W=8)( + input clk, + input rst, + input clr, + input en_MAC, + input signed [I_W-1:0] A, + input signed [I_W-1:0] B, + input en_MAC_out, + output reg signed [(2*I_W)+1:0] Y + ); + reg [(2*I_W)+1:0] temp1,temp2; + always@(posedge clk) + begin + if(rst==0) begin temp1<=0; temp2<=0; Y<=0; end + + else if(clr==1) begin temp1<=0; temp2<=0; Y<=0; end + + else if(rst==1 & clr==0) begin + case({en_MAC,en_MAC_out}) + 2'b00: begin temp1<=0; temp2<=temp2+temp1; Y<=0; end + 2'b01: begin temp1<=0; temp2<=temp2+temp1; Y<=temp2; end + 2'b10: begin temp1<=A*B; temp2<=temp2+temp1; Y<=0; end + 2'b11: begin temp1<=A*B; temp2<=temp2+temp1; Y<=temp2; end + endcase + end + end +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/matrix_multiplier.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/matrix_multiplier.v new file mode 100644 index 0000000000000000000000000000000000000000..ba4bcc03344e64b3e738d815419972f546a3cd03 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/matrix_multiplier.v @@ -0,0 +1,65 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 11/12/2019 12:32:33 PM +// Design Name: +// Module Name: matrix_multiplier +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + +module matrix_multiplier #(parameter In_W=8,In_D_Add_W=4,In_Items=6,Timeperiod=10)( +input clk, +input rst, +input clr, +input ena_r,ena_c, +input enb_r,enb_c, +input wea_r,wea_c, +//input web_r,web_c, +input signed [In_W-1:0] din_r,din_c, +input [In_D_Add_W-1:0] addra_r,addrb_r,addra_c,addrb_c, +input en_MAC, +input en_MAC_out, +output signed [((2*In_W)+2)-1:0] y ); + +wire [In_D_Add_W-1:0] addr_r,addr_c; +wire [In_W-1:0] row_in,col_in; + +blk_mem_gen_0 ROW ( + .clka(clk), // input wire clka + .ena(ena_r), // input wire ena + .wea(wea_r), // input wire [0 : 0] wea + .addra(addra_r), // input wire [3 : 0] addra + .dina(din_r), // input wire [7 : 0] dina + .clkb(clk), // input wire clkb + .enb(enb_r), // input wire enb + .addrb(addrb_r), // input wire [3 : 0] addrb + .doutb(row_in) // output wire [7 : 0] doutb +); + +blk_mem_gen_0 COLUMN ( + .clka(clk), // input wire clka + .ena(ena_c), // input wire ena + .wea(wea_c), // input wire [0 : 0] wea + .addra(addra_c), // input wire [3 : 0] addra + .dina(din_c), // input wire [7 : 0] dina + .clkb(clk), // input wire clkb + .enb(enb_c), // input wire enb + .addrb(addrb_c), // input wire [3 : 0] addrb + .doutb(col_in) // output wire [7 : 0] doutb +); + +mac_generic #(In_W) MAC(.clk(clk),.rst(rst),.clr(clr),.en_MAC(en_MAC),.A(row_in),.B(col_in),.en_MAC_out(en_MAC_out),.Y(y)); + +endmodule \ No newline at end of file diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_data.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_data.v new file mode 100644 index 0000000000000000000000000000000000000000..960f35d09f936d3dfaaf877e84e7f52fd9841b97 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_data.v @@ -0,0 +1,47 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 01/02/2020 01:05:13 PM +// Design Name: +// Module Name: max_data +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + +module max_data #(parameter In_d_W=8, R=3, C=3)( + input [(In_d_W*R*C)-1:0] A, + output [In_d_W-1:0] Y + ); + + wire [In_d_W-1:0] X [0:(R*C)-1]; + wire [In_d_W-1:0] Z [0:(R*C)-1]; + + generate + genvar i; + for(i=0;i<(In_d_W*R*C);i=i+In_d_W) + begin + assign X[i/In_d_W]=A[i+In_d_W-1:i]; + end + endgenerate + + generate + genvar j; + assign Z[0]=X[0]; + for(j=0;j<(R*C)-1;j=j+1) + begin + max_value #(In_d_W) DUT(.A(Z[j]),.B(X[j+1]),.Y(Z[j+1])); + end + assign Y=Z[(R*C)-1]; + endgenerate +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_pooling.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_pooling.v new file mode 100644 index 0000000000000000000000000000000000000000..63792a176028ad77693f5b4d40cce512ea9e9203 --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/max_pooling.v @@ -0,0 +1,95 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 01/06/2020 11:56:13 AM +// Design Name: +// Module Name: max_pooling +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + + +module max_pooling #(parameter In_W=18, R=3, C=3, R_P=2, C_P=2, P=0, S=1, Timeperiod=10) ( + input clk, + input rst, + input clr, + input en_pool, + input en_pool_out, + input [(In_W*R*C)-1:0] N, //[161:0] N + output reg [((In_W)*(((R+(2*P)-R_P)/S)+1)*(((C+(2*P)-C_P)/S)+1))-1:0] Y //[71:0] Y + ); + + wire [(In_W*(((R+(2*P)-R_P)/S)+1))-1:0] Z [0:(((((R+(2*P)-R_P)/S)+1)*C)-1)]; // [35:0] Z [0:5] + wire [(In_W*R_P*C_P)-1:0] X [0:((((((R+(2*P)-R_P)/S)+1)*(((C+(2*P)-C_P)/S)+1)))-1)]; // [71:0] X [0:3] + //wire [In_W-1:0] W1 [0:((((((R+(2*P)-R_P)/S)+1)*(((C+(2*P)-C_P)/S)+1)))-1)]; // [17:0] W1 [0:3] + wire [((((R+(2*P)-R_P)/S)+1)*(((C+(2*P)-C_P)/S)+1)*In_W)-1:0] W; // [71:0] W + reg [((((R+(2*P)-R_P)/S)+1)*(((C+(2*P)-C_P)/S)+1)*In_W)-1:0] temp; + + generate + genvar i,j; + for(i=0;iB) + Y<=A; + else if(A<=B) + Y<=B; + end +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_2x1.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_2x1.v new file mode 100644 index 0000000000000000000000000000000000000000..61d704b00e24a0f6dbb106aaf6bce4d29067ee9b --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_2x1.v @@ -0,0 +1,31 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 01/14/2020 04:51:34 PM +// Design Name: +// Module Name: mux_2x1 +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + + +module mux_2X1 #(parameter In_d_W=8)( + input [In_d_W-1:0] I0, + input [In_d_W-1:0] I1, + input Sel, + output [In_d_W-1:0] Y + ); + + assign Y=(Sel==0)?I0:I1; +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_g.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_g.v new file mode 100644 index 0000000000000000000000000000000000000000..50ad0e6c9bf27da4f870f2e80708f513896462ca --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/mux_g.v @@ -0,0 +1,41 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 01/16/2020 01:03:24 PM +// Design Name: +// Module Name: mux_g +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + + +module mux_g #(parameter In_d_W=16*8, S_W=4)( //Over here, this mux works like, I have 128 bit as I/P and I need 8 bit O/P. So, 128/8=16 +//Therefore, S=4 as 2^4=16 +input [In_d_W-1:0] A, +input [S_W-1:0] S, +output [(In_d_W/(2**S_W))-1:0] Y +); +parameter Out_d_W=In_d_W/(2**S_W); +wire [Out_d_W-1:0] W [0:(2**S_W)-1]; +generate +genvar i; +for(i=0; i<(2**S_W); i=i+1) +begin + assign W[i]=A[ (i*Out_d_W)+Out_d_W-1 : i*Out_d_W ]; +end +endgenerate + +assign Y=W[S]; + +endmodule diff --git a/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/slide_window_conv.v b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/slide_window_conv.v new file mode 100644 index 0000000000000000000000000000000000000000..bef10956972ae5928efbc2e22a6b86c455ec25ec --- /dev/null +++ b/padhi499_Image-Classification-using-CNN-on-FPGA/Verilog Codes/slide_window_conv.v @@ -0,0 +1,80 @@ +`timescale 1ns / 1ps +////////////////////////////////////////////////////////////////////////////////// +// Company: +// Engineer: +// +// Create Date: 12/16/2019 01:03:43 PM +// Design Name: +// Module Name: slide_window_conv +// Project Name: +// Target Devices: +// Tool Versions: +// Description: +// +// Dependencies: +// +// Revision: +// Revision 0.01 - File Created +// Additional Comments: +// +////////////////////////////////////////////////////////////////////////////////// + +module slide_window_conv #(parameter In_d_W=8, In_Add_W=4, R_N=5, C_N=5, R_F=3, C_F=3, P=0, S=1, Timeperiod=10) ( + input clk,clk_en,rst,clr,en_wr,en_rd,wr,en_MAC,en_MAC_out, //wr=1 (Write), wr=0 (Read) + input [(C_N*R_N*In_d_W)-1:0] N, // [199:0] N + input [(C_F*R_F*In_d_W)-1:0] F, // [71:0] F + output [(((2*In_d_W)+2)*(((R_N+(2*P)-R_F)/S)+1)*(((C_N+(2*P)-C_F)/S)+1))-1:0] Y // [161:0] Y + ); + parameter R_O=(((R_N+(2*P)-R_F)/S)+1); //3 + parameter C_O=(((C_N+(2*P)-C_F)/S)+1); //3 + parameter Out_d_W=((2*In_d_W)+2); //18 + //wire [(In_d_W*R_N)-1:0] X [0:(C_N-1)]; // [39:0] X [0:4] + wire [(In_d_W*R_O)-1:0] Z [0:((R_O*C_N)-1)]; // [23:0] Z [0:14] + wire [(In_d_W*R_F*C_F)-1:0] A [0:(R_O*C_O)-1]; // [71:0] A [0:8] + wire [Out_d_W-1:0] W [0:(R_O*C_O)-1]; // [17:0] W [0:8] + + generate + genvar i,j; + for(i=0;i + + +////////////////////////////////////// Type Defs +// +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +u08 hex2bin(u08 hex_digit); +u08 gethex_byte(void); + +int main(void) +{ + + s16 read_buf; + u08 byte; + u32 byte_count = 0; + u32 tmp_count; + + read_buf = getchar(); + while (read_buf != EOF) + { + byte = (u08)read_buf; + + if (byte == ':') + { + tmp_count = gethex_byte(); // Byte count + gethex_byte(); // Address + gethex_byte(); // Address + if (gethex_byte() == 0x00) // Data Record + { + byte_count += tmp_count; + } + } + read_buf = getchar(); + } + + + printf("\nIntel HEX file contains %lu bytes.\n\n", byte_count); + + return(0); + +} + +u08 gethex_byte(void) +{ + u08 nibble_hi; + u08 nibble_lo; + + nibble_hi = hex2bin(getchar()); + nibble_lo = hex2bin(getchar()); + + return (((nibble_hi<<4)&0xF0)|(nibble_lo)); +} + +u08 hex2bin(u08 hex_digit) +{ + u08 nibble; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) // 0 to 9 + { + nibble = hex_digit - 0x30; + } + else if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) // A to F + { + nibble = hex_digit - 0x37; + } + else if ((hex_digit >= 0x61) && (hex_digit <= 0x66)) // a to f + { + nibble = hex_digit - 0x57; + } + else + { + nibble = 0xFF; + } + + return nibble; +} + diff --git a/turbo9team_turbo9/asm/s192hex8.c b/turbo9team_turbo9/asm/s192hex8.c new file mode 100644 index 0000000000000000000000000000000000000000..0ecdee4789180d78645275ced0eccd583b629201 --- /dev/null +++ b/turbo9team_turbo9/asm/s192hex8.c @@ -0,0 +1,242 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: s19 to hex file converter +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +/* + +; --==========================> Gator uProccessor <===========================-- +; -- File: s192hex8.c +; -- Engineer: Kevin Phillipson +; -- Date: 03.28.07 +; -- Revision: 10.03.20 +; -- Description: +; +; THIS IS OLD CODE AND SHOULD PROBABLY BE REWRITTEN, BUT IT WORKS. +; +; --==========================================================================-- + +*/ + +#include +#include + +#define WIDTH 8 + +#define BUF_SIZE 16 + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +u08 hex2bin(u08 hex_digit); +u08 bin2hex(u08 nibble); +s16 load_buffer(void); +void crlf(void); + + +u08 buffer[BUF_SIZE]; +s16 eof_buf[BUF_SIZE]; + + +main(void) +{ + + + u32 idx = 0; + + u08 num_bytes; + + u16 hex_file_addr; + u32 hex_file_depth = 0; + + u32 raw_idx = 0; + u16 raw_addr[0x10000]; + u08 raw_data[0x10000]; + + s08 flush; + u08 state = 0; + + for (idx = 0; idx < BUF_SIZE; idx++) + buffer[idx] = 0x00; + + for (idx = 0; idx < BUF_SIZE; idx++) + eof_buf[idx] = 0x00; + + while (load_buffer() != EOF) + { + flush = 0; + + switch(state) + { + case 0: + if (strncmp(buffer,"S1",2) == 0) + { + num_bytes = (hex2bin(buffer[2]) << 4) + + (hex2bin(buffer[3])) - 3; + + hex_file_addr = (hex2bin(buffer[4]) << 12) + + (hex2bin(buffer[5]) << 8) + + (hex2bin(buffer[6]) << 4) + + (hex2bin(buffer[7])); + + flush = 8; + state = 1; + } + break; + + case 1: + if (num_bytes != 0) + { + if (hex_file_addr > hex_file_depth) + { + hex_file_depth = hex_file_addr; + } + + raw_addr[raw_idx] = hex_file_addr; + raw_data[raw_idx] = (hex2bin(buffer[0]) << 4) + + (hex2bin(buffer[1])); + + raw_idx++; + hex_file_addr++; + num_bytes--; + flush = 2; + + if (num_bytes == 0) + { + state = 0; + } + } + else + { + state = 0; + } + + break; + + default: + state = 0; + break; + } + + for (idx = 1; idx < flush; idx++) + load_buffer(); + } + + for (idx = 0; idx < raw_idx; idx++) + { + putchar(bin2hex((raw_data[idx] >> 4) & 0x0F)); + putchar(bin2hex((raw_data[idx] >> 0) & 0x0F)); + + crlf(); + } + + //return(0); + +} + + +s16 load_buffer(void) +{ + s16 tmp; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + buffer[tmp] = buffer[tmp+1]; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + eof_buf[tmp] = eof_buf[tmp+1]; + + if (eof_buf[BUF_SIZE-1] != EOF) // + { + tmp = getchar(); + + //make ucase + if((tmp >= 0x61) && (tmp <= 0x7A)) + tmp = tmp - 0x20; + + } + else + { + tmp = EOF; + } + + buffer[BUF_SIZE-1] = tmp; + eof_buf[BUF_SIZE-1] = tmp; + + return eof_buf[0]; +} + +void crlf(void) +{ + putchar(0x0D); + putchar(0x0A); +} + +u08 hex2bin(u08 hex_digit) +{ + u08 nibble; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) + nibble = hex_digit - 0x30; + else + if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) + nibble = hex_digit - 0x37; + else + nibble = 0xFF; + + return nibble; +} + +u08 bin2hex(u08 nibble) +{ + u08 hex_digit; + + if (nibble < 0x0A) + hex_digit = nibble + 0x30; + else + hex_digit = nibble + 0x37; + + return hex_digit; +} diff --git a/turbo9team_turbo9/asm/s192hex8_offset0x8000.c b/turbo9team_turbo9/asm/s192hex8_offset0x8000.c new file mode 100644 index 0000000000000000000000000000000000000000..0d7e2b95a86e13fd8a3e68c02718c2cbaa95a73f --- /dev/null +++ b/turbo9team_turbo9/asm/s192hex8_offset0x8000.c @@ -0,0 +1,279 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: s19 to hex file converter +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +/* + +; --==========================> Gator uProccessor <===========================-- +; -- File: s192hex8.c +; -- Engineer: Kevin Phillipson +; -- Date: 03.28.07 +; -- Revision: 10.03.20 +; -- Description: +; +; THIS IS OLD CODE AND SHOULD PROBABLY BE REWRITTEN, BUT IT WORKS. +; +; --==========================================================================-- + +*/ + +#include +#include + +#define WIDTH 8 + +#define BUF_SIZE 16 +#define MEM_OFFSET 0x8000 +#define MEM_END 0xFFFF +#define MEM_SIZE 0x10000 + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +u08 hex2bin(u08 hex_digit); +u08 bin2hex(u08 nibble); +s16 load_buffer(void); +void crlf(void); +void lf(void); + + +u08 buffer[BUF_SIZE]; +s16 eof_buf[BUF_SIZE]; + + +int main(void) +{ + + + u32 addr_idx = 0; + u32 idx = 0; + + u08 num_bytes; + + u08 tmp; + + u16 hex_file_addr; + u32 hex_file_depth = 0; + + u32 raw_idx = 0; + u32 raw_addr[MEM_SIZE]; + u08 raw_data[MEM_SIZE]; + + s08 flush; + u08 state = 0; + + for (idx = 0; idx < MEM_SIZE; idx++) + raw_addr[idx] = 0xFFFFFFFF; // Mark as unused + + for (idx = 0; idx < BUF_SIZE; idx++) + buffer[idx] = 0x00; + + for (idx = 0; idx < BUF_SIZE; idx++) + eof_buf[idx] = 0x00; + + while (load_buffer() != EOF) + { + flush = 0; + + switch(state) + { + case 0: + if (strncmp(buffer,"S1",2) == 0) + { + num_bytes = (hex2bin(buffer[2]) << 4) + + (hex2bin(buffer[3])) - 3; + + hex_file_addr = (hex2bin(buffer[4]) << 12) + + (hex2bin(buffer[5]) << 8) + + (hex2bin(buffer[6]) << 4) + + (hex2bin(buffer[7])); + + flush = 8; + state = 1; + } + break; + + case 1: + if (num_bytes != 0) + { + if (hex_file_addr > hex_file_depth) + { + hex_file_depth = hex_file_addr; + } + + raw_addr[raw_idx] = hex_file_addr; + raw_data[raw_idx] = (hex2bin(buffer[0]) << 4) + + (hex2bin(buffer[1])); + + raw_idx++; + hex_file_addr++; + num_bytes--; + flush = 2; + + if (num_bytes == 0) + { + state = 0; + } + } + else + { + state = 0; + } + + break; + + default: + state = 0; + break; + } + + for (idx = 1; idx < flush; idx++) + load_buffer(); + } + + for (addr_idx = MEM_OFFSET; addr_idx <= MEM_END; addr_idx++) + { + // DEADBEEF + switch(addr_idx % 4) + { + case 0: + tmp = 0xDE; + break; + case 1: + tmp = 0xAD; + break; + case 2: + tmp = 0xBE; + break; + default: + tmp = 0xEF; + break; + } + + for (idx = 0; idx < raw_idx; idx++) + { + if (raw_addr[idx] == addr_idx) + tmp = raw_data[idx]; + } + putchar(bin2hex((tmp >> 4) & 0x0F)); + putchar(bin2hex((tmp >> 0) & 0x0F)); + + lf(); + } + + return(0); + +} + + +s16 load_buffer(void) +{ + s16 tmp; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + buffer[tmp] = buffer[tmp+1]; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + eof_buf[tmp] = eof_buf[tmp+1]; + + if (eof_buf[BUF_SIZE-1] != EOF) // + { + tmp = getchar(); + + //make ucase + if((tmp >= 0x61) && (tmp <= 0x7A)) + tmp = tmp - 0x20; + + } + else + { + tmp = EOF; + } + + buffer[BUF_SIZE-1] = tmp; + eof_buf[BUF_SIZE-1] = tmp; + + return eof_buf[0]; +} + +void lf(void) +{ + putchar(0x0A); +} + +void crlf(void) +{ + putchar(0x0D); + putchar(0x0A); +} + +u08 hex2bin(u08 hex_digit) +{ + u08 nibble; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) + nibble = hex_digit - 0x30; + else + if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) + nibble = hex_digit - 0x37; + else + nibble = 0xFF; + + return nibble; +} + +u08 bin2hex(u08 nibble) +{ + u08 hex_digit; + + if (nibble < 0x0A) + hex_digit = nibble + 0x30; + else + hex_digit = nibble + 0x37; + + return hex_digit; +} diff --git a/turbo9team_turbo9/asm/s192hex8_offset0x8000_even.c b/turbo9team_turbo9/asm/s192hex8_offset0x8000_even.c new file mode 100644 index 0000000000000000000000000000000000000000..8db56e0f9b17696e8326f51456b1cb977ba90784 --- /dev/null +++ b/turbo9team_turbo9/asm/s192hex8_offset0x8000_even.c @@ -0,0 +1,282 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: s19 to hex file converter +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +/* + +; --==========================> Gator uProccessor <===========================-- +; -- File: s192hex8.c +; -- Engineer: Kevin Phillipson +; -- Date: 03.28.07 +; -- Revision: 10.03.20 +; -- Description: +; +; THIS IS OLD CODE AND SHOULD PROBABLY BE REWRITTEN, BUT IT WORKS. +; +; --==========================================================================-- + +*/ + +#include +#include + +#define WIDTH 8 + +#define BUF_SIZE 16 +#define MEM_OFFSET 0x8000 +#define MEM_END 0xFFFF +#define MEM_SIZE 0x10000 + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +u08 hex2bin(u08 hex_digit); +u08 bin2hex(u08 nibble); +s16 load_buffer(void); +void crlf(void); +void lf(void); + + +u08 buffer[BUF_SIZE]; +s16 eof_buf[BUF_SIZE]; + + +int main(void) +{ + + + u32 addr_idx = 0; + u32 idx = 0; + + u08 num_bytes; + + u08 tmp; + + u16 hex_file_addr; + u32 hex_file_depth = 0; + + u32 raw_idx = 0; + u32 raw_addr[MEM_SIZE]; + u08 raw_data[MEM_SIZE]; + + s08 flush; + u08 state = 0; + + for (idx = 0; idx < MEM_SIZE; idx++) + raw_addr[idx] = 0xFFFFFFFF; // Mark as unused + + for (idx = 0; idx < BUF_SIZE; idx++) + buffer[idx] = 0x00; + + for (idx = 0; idx < BUF_SIZE; idx++) + eof_buf[idx] = 0x00; + + while (load_buffer() != EOF) + { + flush = 0; + + switch(state) + { + case 0: + if (strncmp(buffer,"S1",2) == 0) + { + num_bytes = (hex2bin(buffer[2]) << 4) + + (hex2bin(buffer[3])) - 3; + + hex_file_addr = (hex2bin(buffer[4]) << 12) + + (hex2bin(buffer[5]) << 8) + + (hex2bin(buffer[6]) << 4) + + (hex2bin(buffer[7])); + + flush = 8; + state = 1; + } + break; + + case 1: + if (num_bytes != 0) + { + if (hex_file_addr > hex_file_depth) + { + hex_file_depth = hex_file_addr; + } + + raw_addr[raw_idx] = hex_file_addr; + raw_data[raw_idx] = (hex2bin(buffer[0]) << 4) + + (hex2bin(buffer[1])); + + raw_idx++; + hex_file_addr++; + num_bytes--; + flush = 2; + + if (num_bytes == 0) + { + state = 0; + } + } + else + { + state = 0; + } + + break; + + default: + state = 0; + break; + } + + for (idx = 1; idx < flush; idx++) + load_buffer(); + } + + for (addr_idx = MEM_OFFSET; addr_idx <= MEM_END; addr_idx++) + { + // DEADBEEF + switch(addr_idx % 4) + { + case 0: + tmp = 0xDE; + break; + case 1: + tmp = 0xAD; + break; + case 2: + tmp = 0xBE; + break; + default: + tmp = 0xEF; + break; + } + + for (idx = 0; idx < raw_idx; idx++) + { + if (raw_addr[idx] == addr_idx) + tmp = raw_data[idx]; + } + if ((addr_idx&0x00000001) == 0) //even + { + putchar(bin2hex((tmp >> 4) & 0x0F)); + putchar(bin2hex((tmp >> 0) & 0x0F)); + lf(); + } + + } + + return(0); + +} + + +s16 load_buffer(void) +{ + s16 tmp; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + buffer[tmp] = buffer[tmp+1]; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + eof_buf[tmp] = eof_buf[tmp+1]; + + if (eof_buf[BUF_SIZE-1] != EOF) // + { + tmp = getchar(); + + //make ucase + if((tmp >= 0x61) && (tmp <= 0x7A)) + tmp = tmp - 0x20; + + } + else + { + tmp = EOF; + } + + buffer[BUF_SIZE-1] = tmp; + eof_buf[BUF_SIZE-1] = tmp; + + return eof_buf[0]; +} + +void lf(void) +{ + putchar(0x0A); +} + +void crlf(void) +{ + putchar(0x0D); + putchar(0x0A); +} + +u08 hex2bin(u08 hex_digit) +{ + u08 nibble; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) + nibble = hex_digit - 0x30; + else + if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) + nibble = hex_digit - 0x37; + else + nibble = 0xFF; + + return nibble; +} + +u08 bin2hex(u08 nibble) +{ + u08 hex_digit; + + if (nibble < 0x0A) + hex_digit = nibble + 0x30; + else + hex_digit = nibble + 0x37; + + return hex_digit; +} diff --git a/turbo9team_turbo9/asm/s192hex8_offset0x8000_odd.c b/turbo9team_turbo9/asm/s192hex8_offset0x8000_odd.c new file mode 100644 index 0000000000000000000000000000000000000000..26870bad298f9a42970152703243e022971fd731 --- /dev/null +++ b/turbo9team_turbo9/asm/s192hex8_offset0x8000_odd.c @@ -0,0 +1,282 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: s19 to hex file converter +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +/* + +; --==========================> Gator uProccessor <===========================-- +; -- File: s192hex8.c +; -- Engineer: Kevin Phillipson +; -- Date: 03.28.07 +; -- Revision: 10.03.20 +; -- Description: +; +; THIS IS OLD CODE AND SHOULD PROBABLY BE REWRITTEN, BUT IT WORKS. +; +; --==========================================================================-- + +*/ + +#include +#include + +#define WIDTH 8 + +#define BUF_SIZE 16 +#define MEM_OFFSET 0x8000 +#define MEM_END 0xFFFF +#define MEM_SIZE 0x10000 + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +u08 hex2bin(u08 hex_digit); +u08 bin2hex(u08 nibble); +s16 load_buffer(void); +void crlf(void); +void lf(void); + + +u08 buffer[BUF_SIZE]; +s16 eof_buf[BUF_SIZE]; + + +int main(void) +{ + + + u32 addr_idx = 0; + u32 idx = 0; + + u08 num_bytes; + + u08 tmp; + + u16 hex_file_addr; + u32 hex_file_depth = 0; + + u32 raw_idx = 0; + u32 raw_addr[MEM_SIZE]; + u08 raw_data[MEM_SIZE]; + + s08 flush; + u08 state = 0; + + for (idx = 0; idx < MEM_SIZE; idx++) + raw_addr[idx] = 0xFFFFFFFF; // Mark as unused + + for (idx = 0; idx < BUF_SIZE; idx++) + buffer[idx] = 0x00; + + for (idx = 0; idx < BUF_SIZE; idx++) + eof_buf[idx] = 0x00; + + while (load_buffer() != EOF) + { + flush = 0; + + switch(state) + { + case 0: + if (strncmp(buffer,"S1",2) == 0) + { + num_bytes = (hex2bin(buffer[2]) << 4) + + (hex2bin(buffer[3])) - 3; + + hex_file_addr = (hex2bin(buffer[4]) << 12) + + (hex2bin(buffer[5]) << 8) + + (hex2bin(buffer[6]) << 4) + + (hex2bin(buffer[7])); + + flush = 8; + state = 1; + } + break; + + case 1: + if (num_bytes != 0) + { + if (hex_file_addr > hex_file_depth) + { + hex_file_depth = hex_file_addr; + } + + raw_addr[raw_idx] = hex_file_addr; + raw_data[raw_idx] = (hex2bin(buffer[0]) << 4) + + (hex2bin(buffer[1])); + + raw_idx++; + hex_file_addr++; + num_bytes--; + flush = 2; + + if (num_bytes == 0) + { + state = 0; + } + } + else + { + state = 0; + } + + break; + + default: + state = 0; + break; + } + + for (idx = 1; idx < flush; idx++) + load_buffer(); + } + + for (addr_idx = MEM_OFFSET; addr_idx <= MEM_END; addr_idx++) + { + // DEADBEEF + switch(addr_idx % 4) + { + case 0: + tmp = 0xDE; + break; + case 1: + tmp = 0xAD; + break; + case 2: + tmp = 0xBE; + break; + default: + tmp = 0xEF; + break; + } + + for (idx = 0; idx < raw_idx; idx++) + { + if (raw_addr[idx] == addr_idx) + tmp = raw_data[idx]; + } + if ((addr_idx&0x00000001) == 1) //odd + { + putchar(bin2hex((tmp >> 4) & 0x0F)); + putchar(bin2hex((tmp >> 0) & 0x0F)); + lf(); + } + + } + + return(0); + +} + + +s16 load_buffer(void) +{ + s16 tmp; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + buffer[tmp] = buffer[tmp+1]; + + for (tmp = 0; tmp < BUF_SIZE-1; tmp++) + eof_buf[tmp] = eof_buf[tmp+1]; + + if (eof_buf[BUF_SIZE-1] != EOF) // + { + tmp = getchar(); + + //make ucase + if((tmp >= 0x61) && (tmp <= 0x7A)) + tmp = tmp - 0x20; + + } + else + { + tmp = EOF; + } + + buffer[BUF_SIZE-1] = tmp; + eof_buf[BUF_SIZE-1] = tmp; + + return eof_buf[0]; +} + +void lf(void) +{ + putchar(0x0A); +} + +void crlf(void) +{ + putchar(0x0D); + putchar(0x0A); +} + +u08 hex2bin(u08 hex_digit) +{ + u08 nibble; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) + nibble = hex_digit - 0x30; + else + if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) + nibble = hex_digit - 0x37; + else + nibble = 0xFF; + + return nibble; +} + +u08 bin2hex(u08 nibble) +{ + u08 hex_digit; + + if (nibble < 0x0A) + hex_digit = nibble + 0x30; + else + hex_digit = nibble + 0x37; + + return hex_digit; +} diff --git a/turbo9team_turbo9/asm/sim_boot.vh b/turbo9team_turbo9/asm/sim_boot.vh new file mode 100644 index 0000000000000000000000000000000000000000..914feb924caac989d56ed652350b6273b15aefea --- /dev/null +++ b/turbo9team_turbo9/asm/sim_boot.vh @@ -0,0 +1,66 @@ +//////////////////////////////////////////////////////////////////////////////// +// // +// Definition file // +// // +//////////////////////////////////////////////////////////////////////////////// + +`define asm_acia_data 16'h0002 +`define asm_acia_putchar_a 16'hFEBE +`define asm_acia_status 16'h0003 +`define asm_apa_wait 16'hFEC0 +`define asm_apx_end 16'hFF93 +`define asm_apx_loop 16'hFF8A +`define asm_boot_firq_vector 16'hFFF6 +`define asm_boot_irq_vector 16'hFFF8 +`define asm_boot_nmi_vector 16'hFFFC +`define asm_boot_reserved_vector 16'hFFF0 +`define asm_boot_reset_vector 16'hFFFE +`define asm_boot_return 16'hFE9C +`define asm_boot_sim_stop 16'hFEAA +`define asm_boot_stack 16'hFE00 +`define asm_boot_start 16'hFE00 +`define asm_boot_swi2_vector 16'hFFF4 +`define asm_boot_swi3_vector 16'hFFF2 +`define asm_boot_swi_vector 16'hFFFA +`define asm_boot_vector_table 16'hFFF0 +`define asm_call_prog_start 16'hFE96 +`define asm_getchar_a 16'hFED7 +`define asm_gethex_byte 16'hFFB8 +`define asm_gethex_digit 16'hFFA8 +`define asm_ghd_0to9 16'hFFB1 +`define asm_ghd_AtoF 16'hFFB5 +`define asm_ghd_done 16'hFFB7 +`define asm_input_prompt 16'hFF68 +`define asm_LF 16'h000A +`define asm_load_bad 16'hFF2E +`define asm_load_good0 16'hFF3E +`define asm_load_good1 16'hFF50 +`define asm_main_loop 16'hFE16 +`define asm_output_port 16'h0000 +`define asm_pca_not_lf 16'hFEBE +`define asm_pca_sim_out 16'hFECD +`define asm_print_x 16'hFF88 +`define asm_prog_start 16'h8000 +`define asm_prompt 16'hFF0E +`define asm_putchar_a 16'hFEAF +`define asm_puthex_16bit 16'hFFD2 +`define asm_puthex_byte 16'hFFC5 +`define asm_puthex_digit 16'hFF95 +`define asm_puthex_digit1 16'hFFA1 +`define asm_puthex_digit2 16'hFFA3 +`define asm_return_msg 16'hFF6C +`define asm_s1_record 16'hFE2A +`define asm_s1r_checkit 16'hFE5C +`define asm_s1r_loop 16'hFE4E +`define asm_s9_record 16'hFE6D +`define asm_s9r_good_load 16'hFE7A +`define asm_sim_detect 16'hFFED +`define asm_sim_putchar_buf 16'hFFEF +`define asm_sim_putchar_en 16'hFFEE +`define asm_swi_handler 16'hFEE2 +`define asm_swi_handler_1 16'hFF02 +`define asm_swi_handler_2 16'hFEF6 +`define asm_swi_handler_3 16'hFEEC +`define asm_swi_handler_exit 16'hFF0B +`define asm_uca_done 16'hFFE5 +`define asm_ucase_a 16'hFFDB diff --git a/turbo9team_turbo9/asm/tb_dv_asm.vh b/turbo9team_turbo9/asm/tb_dv_asm.vh new file mode 100644 index 0000000000000000000000000000000000000000..ee20a8fea0b2815160ab750bc357c624c9cc5746 --- /dev/null +++ b/turbo9team_turbo9/asm/tb_dv_asm.vh @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////// +// // +// Definition file // +// // +//////////////////////////////////////////////////////////////////////////////// + +`define asm_code_under_test 16'hFC41 +`define asm_code_under_test_br_bwd 16'hFD8A +`define asm_code_under_test_br_fwd 16'hFE89 +`define asm_code_under_test_idx_pc8_bwd 16'hFD8B +`define asm_code_under_test_idx_pc8_fwd 16'hFE8A +`define asm_code_under_test_mid 16'hFE08 +`define asm_data_addr 16'hFE8A +`define asm_data_block_end 16'hFFD0 +`define asm_data_block_last_byte 16'hFFCF +`define asm_done_s_ptr 16'hFC27 +`define asm_done_s_ptr_loop 16'hFC31 +`define asm_done_u_ptr 16'hFC34 +`define asm_done_u_ptr_loop 16'hFC3E +`define asm_firq_vector 16'hFFF6 +`define asm_init_a 16'hFFE5 +`define asm_init_b 16'hFFE6 +`define asm_init_cc 16'hFFE4 +`define asm_init_dp 16'hFFE7 +`define asm_init_pc 16'hFFEE +`define asm_init_stack_data 16'hFFE4 +`define asm_init_u_s 16'hFFEC +`define asm_init_x 16'hFFE8 +`define asm_init_y 16'hFFEA +`define asm_irq_vector 16'hFFF8 +`define asm_nmi_vector 16'hFFFC +`define asm_output_port 16'h0000 +`define asm_reserved_vector 16'hFFF0 +`define asm_reset_vector 16'hFFFE +`define asm_stack_end 16'hFFD0 +`define asm_stack_start 16'hFFF0 +`define asm_start_s_ptr 16'hFC00 +`define asm_start_u_ptr 16'hFC14 +`define asm_swi2_vector 16'hFFF4 +`define asm_swi3_vector 16'hFFF2 +`define asm_swi_vector 16'hFFFA +`define asm_vector_table 16'hFFF0 diff --git a/turbo9team_turbo9/asm/test.txt b/turbo9team_turbo9/asm/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/turbo9team_turbo9/asm/verihead.c b/turbo9team_turbo9/asm/verihead.c new file mode 100644 index 0000000000000000000000000000000000000000..de630556b7b5ec566a679a2b31b476fc61e3cb33 --- /dev/null +++ b/turbo9team_turbo9/asm/verihead.c @@ -0,0 +1,338 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Inputs a sym file containing EQUs and outputs a verilog +// header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include +#include +#include +#include + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +union LONG +{ + s32 sl; + u32 ul; + s16 si[2]; + u16 ui[2]; + s08 sb[4]; + u08 ub[4]; +}; + +union WORD +{ + s16 si; + u16 ui; + s08 sb[2]; + u08 ub[2]; +}; + +#define MAX_CTRL_VEC 256 +#define MAX_PTR_VEC 256 +#define MAX_EQU 256 +#define MAX_MACROS 256 +#define MAX_SREC_LEN 64 +#define MAX_SREC_DEPTH 512 +#define MAXLINE 256 + +#define IN +#define OUT + +#define LF 0x0A + +enum error_codes { + ERR_ALREADY_ALLOCATED = -8, + ERR_INVALID_STATE = -7, + ERR_INVALID_FIELD = -6, + ERR_FILE_IO = -5, + ERR_DUPLICATE_ENTRY = -4, + ERR_NOT_FOUND = -3, + ERR_MISC = -2, + ERR_NULL_PTR = -1, + ERR_OK = 0 +}; + +// --==============================================-- +// strip_string +// +// This function will take a string and strip out all characters that are +// not in the large if statement condition below. Repeated invalid +// characters will be consolidated into a single space character. +// +// line - the string to be operated ron. +// clip_leading_whitespace - remove leading whitespace +// retval - returns 0 if successful. Negative value is return if error +// +s16 strip_string(char *line, u08 clip_leading_whitespace) +{ + s16 retval = ERR_OK; + + u16 i = 0; + u16 j = 0; + u08 flag = clip_leading_whitespace; + + if (!line) + { + retval = ERR_NULL_PTR; + printf( "Error: null pointer passed to strip_string function\n"); + goto done; + } + + while ((line[j] != '\0') && (line[j] != LF)) // While not end of string + { + if + ( + ((line[j] >= 'A') && (line[j] <= 'Z')) || + ((line[j] >= 'a') && (line[j] <= 'z')) || + ((line[j] >= '0') && (line[j] <= '9')) || + (line[j] == '.') || + (line[j] == ']') || + (line[j] == '[') || + (line[j] == '/') || + (line[j] == '_') + ) + { + line[i] = line[j]; // Valid character. Copy back into string + i++; + flag = 0; + } + else if(line[j] == ';') + { + line[i] = '\0'; + retval = j+2; // Point to beginning of comment as return val. + goto done; + } + else + { + if (flag == 0) + { + line[i] = ' '; // First invalid character. Insert a space + i++; + flag = 1; + } + } + j++; + } + + line[i] = '\0'; + +done: + return retval; +} + +// --==============================================-- +// Get Field Function +// +// This function will take a string that is made up of fields seperated +// by space characters and return the desired field. +// +// line - input string with space delimiters +// field - output string +// field_num - specifies field number to return +// field_spaces - specifies how many spaces to include in field +// ret_val - the starting position of the desired field. +// returns an ERR_* type if error +// +// TODO: Needs reevaluation to use strtok() and not take in a stack variable to store fields. +// *field output should not be a char array, but just point to the tokenized field from +// strtok(). +s16 get_field(char *line, char *field, u08 field_num, u08 field_spaces) +{ + s16 ret_val = ERR_NOT_FOUND; + u16 i = 0; + u16 j = 0; + + if (!line) + { + ret_val = ERR_NULL_PTR; + printf( "Error: null pointer passed to get_field function\n"); + goto done; + } + + while ((line[i] != '\0') && (j != field_num)) // While not end of string + { + if (line[i] == ' ') j++; + i++; + } + if (j != field_num) // Field not found + { + ret_val = ERR_NOT_FOUND; + field[0] = '\0'; + goto done; + } + else + { + ret_val = i; // return position + } + + j = 0; + while ((line[i] != '\0') && !((line[i] == ' ') && (field_spaces == 0))) // While not end of string + { + field[j] = line[i]; + if (line[i] == ' ') + field_spaces--; + j++; + i++; + } + field[j] = '\0'; + + if (j == 0) // Field has zero length + { + ret_val = ERR_NOT_FOUND; + goto done; + } + +done: + return ret_val; +} + +void make_str_pad(u08 str_len, u08 width, char pad_char, char * pad) +{ + u08 i; + + if ( width <= str_len ) + { + pad[0] = pad_char; + pad[1] = '\0'; + } + else + { + for (i=0; i<(width-str_len); i++) + { + pad[i] = pad_char; + } + pad[(width-str_len)] = '\0'; + } +} + +int main(int argc, char ** argv) +{ + int retval = 0; + FILE *f_in, *f_out; + char *in_name; + char *out_name; + char str[MAXLINE] = {0}; + char field0[MAXLINE] = {0}; + char field1[MAXLINE] = {0}; + char pad[32] = {0}; + int index = 0; + int opt; + + // put ':' in the starting of the + // string so that program can + //distinguish between '?' and ':' + while((opt = getopt(argc, argv, "io?")) != -1) + { + switch(opt) + { + case 'i': + in_name = argv[optind]; + printf("input filename %s\n", in_name); + break; + case 'o': + out_name = argv[optind]; + printf("output filename %s\n", out_name); + break; + case '?': + default: + printf("%s -i -o \n", argv[0]); + break; + } + optind++; + } + + if((f_in = fopen(in_name, "r")) == NULL) + { + perror("Input filename failed\n"); + goto done; + } + + if((f_out = fopen(out_name, "w")) == NULL) + { + perror("Output filename failed\n"); + goto done; + } + + // Write header data + fprintf(f_out, "////////////////////////////////////////////////////////////////////////////////\n"); + fprintf(f_out, "// //\n"); + fprintf(f_out, "// Definition file //\n"); + fprintf(f_out, "// //\n"); + fprintf(f_out, "////////////////////////////////////////////////////////////////////////////////\n\n"); + + while(fgets(str, MAXLINE, f_in) != NULL) + { + //printf("Processing string: %s", str); + if(strip_string(str, 0)) + { + fprintf(stderr, "Could not properly reformat line %d\n", index); + goto done; + } + if(get_field(str, field1, 2, 0) < 0) + { + fprintf(stderr, "Failed getting field 2\n"); + goto done; + } + if(get_field(str, field0, 0, 0) < 0) + { + fprintf(stderr, "Failed getting field 0\n"); + goto done; + } + + make_str_pad(strlen(field0), 32, ' ', pad); + fprintf(f_out, "`define asm_%s%s16'h%s\n", field0, pad, field1); + index++; + } + +done: + if(f_in) fclose(f_in); + if(f_out) fclose(f_out); + return retval; +} diff --git a/turbo9team_turbo9/c_code/README.md b/turbo9team_turbo9/c_code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a3d25b238c40d27ae795c9d0f74ddeb3f7cf90e6 --- /dev/null +++ b/turbo9team_turbo9/c_code/README.md @@ -0,0 +1,11 @@ +## c_code +| | | +|---------------------------------------------|---------------------------------------| +| [build_gcc/](c_code/build_gcc/) | build directory for GCC | +| [build_vbcc/](c_code/build_vbcc/) | build directory for VBCC | +| [byte_sieve_src/](c_code/byte_sieve_src/) | BYTE Sieve source | +| [dhrystone_src/](c_code/dhrystone_src/) | Dhrystone source | +| [hello_world_src/](c_code/hello_world_src/) | Hello World source | +| [lib_gcc/](c_code/lib_gcc/) | Library for GCC | +| [lib_vbcc/](c_code/lib_vbcc/) | Library for VBCC | + diff --git a/turbo9team_turbo9/c_code/byte_sieve_src/byte_sieve.c b/turbo9team_turbo9/c_code/byte_sieve_src/byte_sieve.c new file mode 100644 index 0000000000000000000000000000000000000000..3eb5f4914b0d101112a34fddd6da64d951c86134 --- /dev/null +++ b/turbo9team_turbo9/c_code/byte_sieve_src/byte_sieve.c @@ -0,0 +1,120 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: +// BYTE Sieve Benchmark (Language: C) +// Originally published in BYTE magazine September 1981 +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include "lib.h" +#define ITER_TOTAL 10 + + +#define true 1 +#define false 0 +#define size 8190 +#define sizepl 8191 +unsigned char flags[sizepl]; + +SECTION_START +int main( void ) { + + COUNTER_VAR + unsigned int i, prime, k, count, iter; + + setup(); + + acia_print_str ("\n"); + acia_print_str ("BYTE Sieve Benchmark (Language: C, "); + acia_print_str ("Compiler: "); +#ifdef _VBCC + acia_print_str ("vbcc"); +#else + acia_print_str (COMPILER); +#endif + acia_print_str (")\n"); + acia_print_str ("Originally published in BYTE magazine September 1981\n"); + acia_print_str ("\n"); + acia_print_unsigned_long (ITER_TOTAL); + acia_print_str (" iterations\n"); + + COUNTER_START + + for (iter = 1; iter <= ITER_TOTAL; iter ++) { + count=0 ; + for (i = 0; i <= size; i++) + flags[i] = true; + for (i = 0; i <= size; i++) { + if (flags[i]) { + prime = i + i + 3; + k = i + prime; + while (k <= size) { + flags[k] = false; + k += prime; + } + count = count + 1; + } + } + } + + COUNTER_STOP + + acia_print_str ("\n"); + acia_print_unsigned_long (count); + acia_print_str (" primes\n\n"); + + acia_print_str ("Number of iterations: "); + acia_print_unsigned_long (ITER_TOTAL); + acia_print_str ("\n\n"); + + COUNTER_PRINT + + acia_print_str ("\n"); + + teardown(); + + return ( 0 ); + +} + + + diff --git a/turbo9team_turbo9/c_code/byte_sieve_src/orig_src/byte_sieve.c b/turbo9team_turbo9/c_code/byte_sieve_src/orig_src/byte_sieve.c new file mode 100644 index 0000000000000000000000000000000000000000..f557605d273259ca015a530c3e4ce04838896b7c --- /dev/null +++ b/turbo9team_turbo9/c_code/byte_sieve_src/orig_src/byte_sieve.c @@ -0,0 +1,27 @@ + +#define true 1 +#define false 0 +#define size 8190 +#define sizepl 8191 +char flags[sizepl]; +main() { + int i, prime, k, count, iter; + printf("10 iterations\n"); + for (iter = 1; iter <= 10; iter ++) { + count=0 ; + for (i = 0; i <= size; i++) + flags[i] = true; + for (i = 0; i <= size; i++) { + if (flags[i]) { + prime = i + i + 3; + k = i + prime; + while (k <= size) { + flags[k] = false; + k += prime; + } + count = count + 1; + } + } + } + printf("\n%d primes", count); +} diff --git a/turbo9team_turbo9/c_code/dhrystone_src/dhry.h b/turbo9team_turbo9/c_code/dhrystone_src/dhry.h new file mode 100644 index 0000000000000000000000000000000000000000..f23e6aa6df08de10ea1b4ba384206bfacb4b8aeb --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/dhry.h @@ -0,0 +1,433 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry.h (part 1 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * Siemens AG, E STE 35 + * Postfach 3240 + * 8520 Erlangen + * Germany (West) + * Phone: [xxx-49]-9131-7-20330 + * (8-17 Central European Time) + * Usenet: ..!mcvax!unido!estevax!weicker + * + * Original Version (in Ada) published in + * "Communications of the ACM" vol. 27., no. 10 (Oct. 1984), + * pp. 1013 - 1030, together with the statistics + * on which the distribution of statements etc. is based. + * + * In this C version, the following C library functions are used: + * - strcpy, strcmp (inside the measurement loop) + * - printf, scanf (outside the measurement loop) + * In addition, Berkeley UNIX system calls "times ()" or "time ()" + * are used for execution time measurement. For measurements + * on other systems, these calls have to be changed. + * + * Collection of Results: + * Reinhold Weicker (address see above) and + * + * Rick Richardson + * PC Research. Inc. + * 94 Apple Orchard Drive + * Tinton Falls, NJ 07724 + * Phone: (201) 389-8963 (9-17 EST) + * Usenet: ...!uunet!pcrat!rick + * + * Please send results to Rick Richardson and/or Reinhold Weicker. + * Complete information should be given on hardware and software used. + * Hardware information includes: Machine type, CPU, type and size + * of caches; for microprocessors: clock frequency, memory speed + * (number of wait states). + * Software information includes: Compiler (and runtime library) + * manufacturer and version, compilation switches, OS version. + * The Operating System version may give an indication about the + * compiler; Dhrystone itself performs no OS calls in the measurement loop. + * + * The complete output generated by the program should be mailed + * such that at least some checks for correctness can be made. + * + *************************************************************************** + * + * History: This version C/2.1 has been made for two reasons: + * + * 1) There is an obvious need for a common C version of + * Dhrystone, since C is at present the most popular system + * programming language for the class of processors + * (microcomputers, minicomputers) where Dhrystone is used most. + * There should be, as far as possible, only one C version of + * Dhrystone such that results can be compared without + * restrictions. In the past, the C versions distributed + * by Rick Richardson (Version 1.1) and by Reinhold Weicker + * had small (though not significant) differences. + * + * 2) As far as it is possible without changes to the Dhrystone + * statistics, optimizing compilers should be prevented from + * removing significant statements. + * + * This C version has been developed in cooperation with + * Rick Richardson (Tinton Falls, NJ), it incorporates many + * ideas from the "Version 1.1" distributed previously by + * him over the UNIX network Usenet. + * I also thank Chaim Benedelac (National Semiconductor), + * David Ditzel (SUN), Earl Killian and John Mashey (MIPS), + * Alan Smith and Rafael Saavedra-Barrera (UC at Berkeley) + * for their help with comments on earlier versions of the + * benchmark. + * + * Changes: In the initialization part, this version follows mostly + * Rick Richardson's version distributed via Usenet, not the + * version distributed earlier via floppy disk by Reinhold Weicker. + * As a concession to older compilers, names have been made + * unique within the first 8 characters. + * Inside the measurement loop, this version follows the + * version previously distributed by Reinhold Weicker. + * + * At several places in the benchmark, code has been added, + * but within the measurement loop only in branches that + * are not executed. The intention is that optimizing compilers + * should be prevented from moving code out of the measurement + * loop, or from removing code altogether. Since the statements + * that are executed within the measurement loop have NOT been + * changed, the numbers defining the "Dhrystone distribution" + * (distribution of statements, operand types and locality) + * still hold. Except for sophisticated optimizing compilers, + * execution times for this version should be the same as + * for previous versions. + * + * Since it has proven difficult to subtract the time for the + * measurement loop overhead in a correct way, the loop check + * has been made a part of the benchmark. This does have + * an impact - though a very minor one - on the distribution + * statistics which have been updated for this version. + * + * All changes within the measurement loop are described + * and discussed in the companion paper "Rationale for + * Dhrystone version 2". + * + * Because of the self-imposed limitation that the order and + * distribution of the executed statements should not be + * changed, there are still cases where optimizing compilers + * may not generate code for some statements. To a certain + * degree, this is unavoidable for small synthetic benchmarks. + * Users of the benchmark are advised to check code listings + * whether code is generated for all statements of Dhrystone. + * + * Version 2.1 is identical to version 2.0 distributed via + * the UNIX network Usenet in March 1988 except that it corrects + * some minor deficiencies that were found by users of version 2.0. + * The only change within the measurement loop is that a + * non-executed "else" part was added to the "if" statement in + * Func_3, and a non-executed "else" part removed from Proc_3. + * + *************************************************************************** + * + * Defines: The following "Defines" are possible: + * -DREG=register (default: Not defined) + * As an approximation to what an average C programmer + * might do, the "register" storage class is applied + * (if enabled by -DREG=register) + * - for local variables, if they are used (dynamically) + * five or more times + * - for parameters if they are used (dynamically) + * six or more times + * Note that an optimal "register" strategy is + * compiler-dependent, and that "register" declarations + * do not necessarily lead to faster execution. + * -DNOSTRUCTASSIGN (default: Not defined) + * Define if the C compiler does not support + * assignment of structures. + * -DNOENUMS (default: Not defined) + * Define if the C compiler does not support + * enumeration types. + * -DTIMES (default) + * -DTIME + * The "times" function of UNIX (returning process times) + * or the "time" function (returning wallclock time) + * is used for measurement. + * For single user machines, "time ()" is adequate. For + * multi-user machines where you cannot get single-user + * access, use the "times ()" function. If you have + * neither, use a stopwatch in the dead of night. + * "printf"s are provided marking the points "Start Timer" + * and "Stop Timer". DO NOT use the UNIX "time(1)" + * command, as this will measure the total time to + * run this program, which will (erroneously) include + * the time to allocate storage (malloc) and to perform + * the initialization. + * -DHZ=nnn + * In Berkeley UNIX, the function "times" returns process + * time in 1/HZ seconds, with HZ = 60 for most systems. + * CHECK YOUR SYSTEM DESCRIPTION BEFORE YOU JUST APPLY + * A VALUE. + * + *************************************************************************** + * + * Compilation model and measurement (IMPORTANT): + * + * This C version of Dhrystone consists of three files: + * - dhry.h (this file, containing global definitions and comments) + * - dhry_1.c (containing the code corresponding to Ada package Pack_1) + * - dhry_2.c (containing the code corresponding to Ada package Pack_2) + * + * The following "ground rules" apply for measurements: + * - Separate compilation + * - No procedure merging + * - Otherwise, compiler optimizations are allowed but should be indicated + * - Default results are those without register declarations + * See the companion paper "Rationale for Dhrystone Version 2" for a more + * detailed discussion of these ground rules. + * + * For 16-Bit processors (e.g. 80186, 80286), times for all compilation + * models ("small", "medium", "large" etc.) should be given if possible, + * together with a definition of these models for the compiler system used. + * + ************************************************************************** + * + * Dhrystone (C version) statistics: + * + * [Comment from the first distribution, updated for version 2. + * Note that because of language differences, the numbers are slightly + * different from the Ada version.] + * + * The following program contains statements of a high level programming + * language (here: C) in a distribution considered representative: + * + * assignments 52 (51.0 %) + * control statements 33 (32.4 %) + * procedure, function calls 17 (16.7 %) + * + * 103 statements are dynamically executed. The program is balanced with + * respect to the three aspects: + * + * - statement type + * - operand type + * - operand locality + * operand global, local, parameter, or constant. + * + * The combination of these three aspects is balanced only approximately. + * + * 1. Statement Type: + * ----------------- number + * + * V1 = V2 9 + * (incl. V1 = F(..) + * V = Constant 12 + * Assignment, 7 + * with array element + * Assignment, 6 + * with record component + * -- + * 34 34 + * + * X = Y +|-|"&&"|"|" Z 5 + * X = Y +|-|"==" Constant 6 + * X = X +|- 1 3 + * X = Y *|/ Z 2 + * X = Expression, 1 + * two operators + * X = Expression, 1 + * three operators + * -- + * 18 18 + * + * if .... 14 + * with "else" 7 + * without "else" 7 + * executed 3 + * not executed 4 + * for ... 7 | counted every time + * while ... 4 | the loop condition + * do ... while 1 | is evaluated + * switch ... 1 + * break 1 + * declaration with 1 + * initialization + * -- + * 34 34 + * + * P (...) procedure call 11 + * user procedure 10 + * library procedure 1 + * X = F (...) + * function call 6 + * user function 5 + * library function 1 + * -- + * 17 17 + * --- + * 103 + * + * The average number of parameters in procedure or function calls + * is 1.82 (not counting the function values aX * + * + * 2. Operators + * ------------ + * number approximate + * percentage + * + * Arithmetic 32 50.8 + * + * + 21 33.3 + * - 7 11.1 + * * 3 4.8 + * / (int div) 1 1.6 + * + * Comparison 27 42.8 + * + * == 9 14.3 + * /= 4 6.3 + * > 1 1.6 + * < 3 4.8 + * >= 1 1.6 + * <= 9 14.3 + * + * Logic 4 6.3 + * + * && (AND-THEN) 1 1.6 + * | (OR) 1 1.6 + * ! (NOT) 2 3.2 + * + * -- ----- + * 63 100.1 + * + * + * 3. Operand Type (counted once per operand reference): + * --------------- + * number approximate + * percentage + * + * Integer 175 72.3 % + * Character 45 18.6 % + * Pointer 12 5.0 % + * String30 6 2.5 % + * Array 2 0.8 % + * Record 2 0.8 % + * --- ------- + * 242 100.0 % + * + * When there is an access path leading to the final operand (e.g. a record + * component), only the final data type on the access path is counted. + * + * + * 4. Operand Locality: + * ------------------- + * number approximate + * percentage + * + * local variable 114 47.1 % + * global variable 22 9.1 % + * parameter 45 18.6 % + * value 23 9.5 % + * reference 22 9.1 % + * function result 6 2.5 % + * constant 55 22.7 % + * --- ------- + * 242 100.0 % + * + * + * The program does not compute anything meaningful, but it is syntactically + * and semantically correct. All variables have a value assigned to them + * before they are used as a source operand. + * + * There has been no explicit effort to account for the effects of a + * cache, or to balance the use of long or short displacements for code or + * data. + * + *************************************************************************** + */ + +/*************************************************************************** + * Adapted for embedded microcontrollers by Graham Davies, ECROS Technology. + * + * Further adapted for Turbo9 (pipelined 6809 microprocessor) + * Reverted as much as possible back to original dhrystone 2.1 (diff to review) + * All timing related code and replaced with simple clock counter HW + * turbo9_lib.* contains necessary std_lib functions + * By Kevin Phillipson & Michael Rywalt + * + **************************************************************************/ + + +/* Compiler and system dependent definitions: */ + +/*#define REG register*/ + +#define Mic_secs_Per_Second 1000000.0 + /* Berkeley UNIX C returns process times in seconds/HZ */ + +#ifdef NOSTRUCTASSIGN +#define structassign(d, s) memcpy(&(d), &(s), sizeof(d)) +#else +#define structassign(d, s) d = s +#endif + +#ifdef NOENUM +#define Ident_1 0 +#define Ident_2 1 +#define Ident_3 2 +#define Ident_4 3 +#define Ident_5 4 + typedef int Enumeration; +#else + typedef enum {Ident_1, Ident_2, Ident_3, Ident_4, Ident_5} + Enumeration; +#endif + /* for boolean and enumeration types in Ada, Pascal */ + +/* General definitions: */ + +/*#include //Turbo9: remove*/ + /* for strcpy, strcmp */ + +#define Null 0 + /* Value of a Null pointer */ +#define true 1 +#define false 0 + +typedef int One_Thirty; +typedef int One_Fifty; +typedef char Capital_Letter; +typedef int Boolean; +typedef char Str_30 [31]; +typedef int Arr_1_Dim [50]; +typedef int Arr_2_Dim [50] [50]; + +typedef struct record + { + struct record *Ptr_Comp; + Enumeration Discr; + union { + struct { + Enumeration Enum_Comp; + int Int_Comp; + char Str_Comp [31]; + } var_1; + struct { + Enumeration E_Comp_2; + char Str_2_Comp [31]; + } var_2; + struct { + char Ch_1_Comp; + char Ch_2_Comp; + } var_3; + } variant; + } Rec_Type, *Rec_Pointer; + +/* Prototypes of function defined in dhry21b.c and called from dhry21a.c. + */ +void Proc_6( Enumeration Enum_Val_Par, Enumeration * Enum_Ref_Par ); +void Proc_7( One_Fifty Int_1_Par_Val, One_Fifty Int_2_Par_Val, + One_Fifty * Int_Par_Ref ); +void Proc_8( Arr_1_Dim Arr_1_Par_Ref, Arr_2_Dim Arr_2_Par_Ref, + int Int_1_Par_Val, int Int_2_Par_Val ); +Enumeration Func_1( Capital_Letter Ch_1_Par_Val, Capital_Letter Ch_2_Par_Val ); +Boolean Func_2( Str_30 Str_1_Par_Ref, Str_30 Str_2_Par_Ref ); + diff --git a/turbo9team_turbo9/c_code/dhrystone_src/dhry1.c b/turbo9team_turbo9/c_code/dhrystone_src/dhry1.c new file mode 100644 index 0000000000000000000000000000000000000000..554ebbd53394d169db7f89a210680e5a9ebe0870 --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/dhry1.c @@ -0,0 +1,414 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry_1.c (part 2 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * + **************************************************************************** + */ + +/*************************************************************************** + * Adapted for embedded microcontrollers by Graham Davies, ECROS Technology. + * + * Further adapted for Turbo9 (pipelined 6809 microprocessor) + * Reverted as much as possible back to original dhrystone 2.1 (diff to review) + * All timing related code and replaced with simple clock counter HW + * turbo9_lib.* contains necessary std_lib functions + * By Kevin Phillipson & Michael Rywalt + * + **************************************************************************/ + +#include "dhry.h" +/*#include */ /* Turbo9: remove */ +/*#include */ /* Turbo9: remove */ +/*#include */ /* Turbo9: remove */ +#include "lib.h" + +/* Global Variables: */ + +static char space1[50]; +static char space2[50]; + +Rec_Pointer Ptr_Glob, + Next_Ptr_Glob; +int Int_Glob; +Boolean Bool_Glob; +char Ch_1_Glob, + Ch_2_Glob; +int Arr_1_Glob [50]; +int Arr_2_Glob [50] [50]; + +#ifndef REG + Boolean Reg = false; +#define REG + /* REG becomes defined as empty */ + /* i.e. no register variables */ +#else + Boolean Reg = true; +#endif + + +/* variables for time measurement: */ + +/* Turbo9: removed all timing variables */ + +/* end of variables for time measurement */ + +void Proc_1( REG Rec_Pointer Ptr_Val_Par ); +void Proc_2( One_Fifty * Int_Par_Ref ); +void Proc_3( Rec_Pointer * Ptr_Ref_Par ); +void Proc_4( void ); +void Proc_5( void ); + +SECTION_START + int main( void ) /* Turbo9: added "prog_start */ +/*****/ + + /* main program, corresponds to procedures */ + /* Main and Proc_0 in the Ada version */ +{ + + COUNTER_VAR + + One_Fifty Int_1_Loc; + REG One_Fifty Int_2_Loc; + One_Fifty Int_3_Loc; + REG char Ch_Index; + Enumeration Enum_Loc; + Str_30 Str_1_Loc; + Str_30 Str_2_Loc; + REG int Run_Index; + REG int Number_Of_Runs; + + /* Initializations */ + + Next_Ptr_Glob = (Rec_Pointer) space1; + Ptr_Glob = (Rec_Pointer) space2; + + //Next_Ptr_Glob = (Rec_Pointer) emalloc (sizeof (Rec_Type)); + //Ptr_Glob = (Rec_Pointer) emalloc (sizeof (Rec_Type)); + + setup(); + + + Ptr_Glob->Ptr_Comp = Next_Ptr_Glob; + Ptr_Glob->Discr = Ident_1; + Ptr_Glob->variant.var_1.Enum_Comp = Ident_3; + Ptr_Glob->variant.var_1.Int_Comp = 40; + strcpy (Ptr_Glob->variant.var_1.Str_Comp, + "DHRYSTONE PROGRAM, SOME STRING"); + strcpy (Str_1_Loc, "DHRYSTONE PROGRAM, 1'ST STRING"); + + Arr_2_Glob [8][7] = 10; + /* Was missing in published program. Without this statement, */ + /* Arr_2_Glob [8][7] would have an undefined value. */ + /* Warning: With 16-Bit processors and Number_Of_Runs > 32000, */ + /* overflow may occur for this array element. */ + + acia_print_str ("\n"); + acia_print_str ("Dhrystone Benchmark, Version 2.1 (Language: C, "); + acia_print_str ("Compiler: "); +#ifdef _VBCC + acia_print_str ("vbcc"); +#else + acia_print_str (COMPILER); +#endif + acia_print_str (")\n"); + + if (Reg) + { + acia_print_str ("Program compiled with 'register' attribute\n"); + acia_print_str ("\n"); + } + else + { + acia_print_str ("Program compiled without 'register' attribute\n"); + acia_print_str ("\n"); + } + + Number_Of_Runs = 200; /* Turbo9: hardcode the number of runs */ + acia_print_str ("Execution starts, "); + acia_print_signed_long (Number_Of_Runs); + acia_print_str (" runs through Dhrystone\n"); + + /***************/ + /* Start timer */ + /***************/ + + COUNTER_START + + for (Run_Index = 1; Run_Index <= Number_Of_Runs; ++Run_Index) + { + Proc_5(); + Proc_4(); + /* Ch_1_Glob == 'A', Ch_2_Glob == 'B', Bool_Glob == true */ + Int_1_Loc = 2; + Int_2_Loc = 3; + strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 2'ND STRING"); + Enum_Loc = Ident_2; + Bool_Glob = ! Func_2 (Str_1_Loc, Str_2_Loc); + /* Bool_Glob == 1 */ + while (Int_1_Loc < Int_2_Loc) /* loop body executed once */ + { + Int_3_Loc = 5 * Int_1_Loc - Int_2_Loc; + //Int_3_Loc = emul(5, Int_1_Loc) - Int_2_Loc; + + /* Int_3_Loc == 7 */ + Proc_7 (Int_1_Loc, Int_2_Loc, &Int_3_Loc); + /* Int_3_Loc == 7 */ + Int_1_Loc += 1; + } /* while */ + /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ + Proc_8 (Arr_1_Glob, Arr_2_Glob, Int_1_Loc, Int_3_Loc); + /* Int_Glob == 5 */ + Proc_1 (Ptr_Glob); + for (Ch_Index = 'A'; Ch_Index <= Ch_2_Glob; ++Ch_Index) + /* loop body executed twice */ + { + if (Enum_Loc == Func_1 (Ch_Index, 'C')) + /* then, not executed */ + { + Proc_6 (Ident_1, &Enum_Loc); + strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 3'RD STRING"); + Int_2_Loc = Run_Index; + Int_Glob = Run_Index; + } + } + /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ + Int_2_Loc = Int_2_Loc * Int_1_Loc; + //Int_2_Loc = emul(Int_2_Loc, Int_1_Loc); + Int_1_Loc = Int_2_Loc / Int_3_Loc; + //Int_1_Loc = idiv(Int_2_Loc, Int_3_Loc); + Int_2_Loc = 7 * (Int_2_Loc - Int_3_Loc) - Int_1_Loc; + //Int_2_Loc = emul(7, (Int_2_Loc - Int_3_Loc)) - Int_1_Loc; + /* Int_1_Loc == 1, Int_2_Loc == 13, Int_3_Loc == 7 */ + Proc_2 (&Int_1_Loc); + /* Int_1_Loc == 5 */ + + } /* loop "for Run_Index" */ + + /**************/ + /* Stop timer */ + /**************/ + + COUNTER_STOP + + + + acia_print_str ("Execution ends\n"); + acia_print_str ("\n"); + acia_print_str ("Final values of the variables used in the benchmark:\n"); + acia_print_str ("\n"); + + acia_print_str ("Int_Glob: "); + acia_print_signed_long (Int_Glob); + acia_print_str ("\n should be: 5\n"); + + acia_print_str ("Bool_Glob: "); + acia_print_signed_long (Bool_Glob); + acia_print_str ("\n should be: 1\n"); + + acia_print_str ("Ch_1_Glob: "); + acia_put_char (Ch_1_Glob); + acia_print_str ("\n should be: 'A'\n"); + + acia_print_str ("Ch_2_Glob: "); + acia_put_char (Ch_2_Glob); + acia_print_str ("\n should be: 'B'\n"); + + acia_print_str ("Arr_1_Glob[8]: "); + acia_print_signed_long (Arr_1_Glob[8]); + acia_print_str ("\n should be: 7\n"); + + acia_print_str ("Arr_2_Glob[8][7]: "); + acia_print_signed_long (Arr_2_Glob[8][7]); + acia_print_str ("\n should be: Number_Of_Runs + 10\n"); + + acia_print_str ("Ptr_Glob->\n"); + acia_print_str (" Ptr_Comp: 0x"); + acia_print_hex_16bit ((unsigned int)Ptr_Glob->Ptr_Comp); + acia_print_str ("\n should be: (implementation-dependent)\n"); + + acia_print_str (" Discr: "); + acia_print_signed_long (Ptr_Glob->Discr); + acia_print_str ("\n should be: 0\n"); + + acia_print_str (" Enum_Comp: "); + acia_print_signed_long (Ptr_Glob->variant.var_1.Enum_Comp); + acia_print_str ("\n should be: 2\n"); + + acia_print_str (" Int_Comp: "); + acia_print_signed_long (Ptr_Glob->variant.var_1.Int_Comp); + acia_print_str ("\n should be: 17\n"); + + acia_print_str (" Str_Comp: "); + acia_print_str (Ptr_Glob->variant.var_1.Str_Comp); + acia_print_str ("\n should be: DHRYSTONE PROGRAM, SOME STRING\n"); + + acia_print_str ("Next_Ptr_Glob->\n"); + acia_print_str (" Ptr_Comp: 0x"); + acia_print_hex_16bit ((unsigned int) Next_Ptr_Glob->Ptr_Comp); + acia_print_str ("\n should be: (implementation-dependent), same as above\n"); + + acia_print_str (" Discr: "); + acia_print_signed_long (Next_Ptr_Glob->Discr); + acia_print_str ("\n should be: 0\n"); + + acia_print_str (" Enum_Comp: "); + acia_print_signed_long (Next_Ptr_Glob->variant.var_1.Enum_Comp); + acia_print_str ("\n should be: 1\n"); + + acia_print_str (" Int_Comp: "); + acia_print_signed_long (Next_Ptr_Glob->variant.var_1.Int_Comp); + acia_print_str ("\n should be: 18\n"); + + acia_print_str (" Str_Comp: "); + acia_print_str (Next_Ptr_Glob->variant.var_1.Str_Comp); + acia_print_str ("\n should be: DHRYSTONE PROGRAM, SOME STRING\n"); + + acia_print_str ("Int_1_Loc: "); + acia_print_signed_long (Int_1_Loc); + acia_print_str ("\n should be: 5\n"); + + acia_print_str ("Int_2_Loc: "); + acia_print_signed_long (Int_2_Loc); + acia_print_str ("\n should be: 13\n"); + + acia_print_str ("Int_3_Loc: "); + acia_print_signed_long (Int_3_Loc); + acia_print_str ("\n should be: 7\n"); + + acia_print_str ("Enum_Loc: "); + acia_print_signed_long (Enum_Loc); + acia_print_str ("\n should be: 1\n"); + + acia_print_str ("Str_1_Loc: "); + acia_print_str (Str_1_Loc); + acia_print_str ("\n should be: DHRYSTONE PROGRAM, 1'ST STRING\n"); + + acia_print_str ("Str_2_Loc: "); + acia_print_str (Str_2_Loc); + acia_print_str ("\n should be: DHRYSTONE PROGRAM, 2'ND STRING\n"); + acia_print_str ("\n"); + + acia_print_str ("Number of runs through Dhrystone: "); + acia_print_signed_long (Number_Of_Runs); + acia_print_str ("\n\n"); + + COUNTER_PRINT + + acia_print_str ("\n"); + + teardown(); + + return ( 0 ); +} + + +void Proc_1( REG Rec_Pointer Ptr_Val_Par ) +/******************/ + /* executed once */ +{ + REG Rec_Pointer Next_Record = Ptr_Val_Par->Ptr_Comp; + /* == Ptr_Glob_Next */ + /* Local variable, initialized with Ptr_Val_Par->Ptr_Comp, */ + /* corresponds to "rename" in Ada, "with" in Pascal */ + + structassign (*Ptr_Val_Par->Ptr_Comp, *Ptr_Glob); + Ptr_Val_Par->variant.var_1.Int_Comp = 5; + Next_Record->variant.var_1.Int_Comp + = Ptr_Val_Par->variant.var_1.Int_Comp; + Next_Record->Ptr_Comp = Ptr_Val_Par->Ptr_Comp; + Proc_3 (&Next_Record->Ptr_Comp); + /* Ptr_Val_Par->Ptr_Comp->Ptr_Comp + == Ptr_Glob->Ptr_Comp */ + if (Next_Record->Discr == Ident_1) + /* then, executed */ + { + Next_Record->variant.var_1.Int_Comp = 6; + Proc_6 (Ptr_Val_Par->variant.var_1.Enum_Comp, + &Next_Record->variant.var_1.Enum_Comp); + Next_Record->Ptr_Comp = Ptr_Glob->Ptr_Comp; + Proc_7 (Next_Record->variant.var_1.Int_Comp, 10, + &Next_Record->variant.var_1.Int_Comp); + } + else /* not executed */ + structassign (*Ptr_Val_Par, *Ptr_Val_Par->Ptr_Comp); +} /* Proc_1 */ + + +void Proc_2( One_Fifty * Int_Par_Ref ) +/******************/ + /* executed once */ + /* *Int_Par_Ref == 1, becomes 4 */ +{ + One_Fifty Int_Loc; + Enumeration Enum_Loc; + + Int_Loc = *Int_Par_Ref + 10; + do /* executed once */ + if (Ch_1_Glob == 'A') + /* then, executed */ + { + Int_Loc -= 1; + *Int_Par_Ref = Int_Loc - Int_Glob; + Enum_Loc = Ident_1; + } /* if */ + while (Enum_Loc != Ident_1); /* true */ +} /* Proc_2 */ + + +void Proc_3( Rec_Pointer * Ptr_Ref_Par ) +/******************/ + /* executed once */ + /* Ptr_Ref_Par becomes Ptr_Glob */ +{ + if (Ptr_Glob != Null) + /* then, executed */ + *Ptr_Ref_Par = Ptr_Glob->Ptr_Comp; + Proc_7 (10, Int_Glob, &Ptr_Glob->variant.var_1.Int_Comp); +} /* Proc_3 */ + + +void Proc_4( void ) /* without parameters */ +/*******/ + /* executed once */ +{ + Boolean Bool_Loc; + + Bool_Loc = Ch_1_Glob == 'A'; + Bool_Glob = Bool_Loc | Bool_Glob; + Ch_2_Glob = 'B'; +} /* Proc_4 */ + + +void Proc_5( void ) /* without parameters */ +/*******/ + /* executed once */ +{ + Ch_1_Glob = 'A'; + Bool_Glob = false; +} /* Proc_5 */ + + + /* Procedure for the assignment of structures, */ + /* if the C compiler doesn't support this feature */ +#ifdef NOSTRUCTASSIGN +memcpy (d, s, l) +register char *d; +register char *s; +register int l; +{ + while (l--) *d++ = *s++; +} +#endif + + diff --git a/turbo9team_turbo9/c_code/dhrystone_src/dhry2.c b/turbo9team_turbo9/c_code/dhrystone_src/dhry2.c new file mode 100644 index 0000000000000000000000000000000000000000..fec9f6ea5ab3013437a2af6bfe0c64c65e6c9a14 --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/dhry2.c @@ -0,0 +1,191 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry_2.c (part 3 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * + **************************************************************************** + */ + +/*************************************************************************** + * Adapted for embedded microcontrollers by Graham Davies, ECROS Technology. + * + * Further adapted for Turbo9 (pipelined 6809 microprocessor) + * Reverted as much as possible back to original dhrystone 2.1 (diff to review) + * All timing related code and replaced with simple clock counter HW + * turbo9_lib.* contains necessary std_lib functions + * By Kevin Phillipson & Michael Rywalt + * + **************************************************************************/ + +#include "dhry.h" +/*#include //Turbo9: remove */ +#include "lib.h" + +#ifndef REG +#define REG + /* REG becomes defined as empty */ + /* i.e. no register variables */ +#endif + +extern int Int_Glob; +extern char Ch_1_Glob; + +Boolean Func_3( Enumeration Enum_Par_Val ); + +void Proc_6( Enumeration Enum_Val_Par, Enumeration * Enum_Ref_Par ) +/*********************************/ + /* executed once */ + /* Enum_Val_Par == Ident_3, Enum_Ref_Par becomes Ident_2 */ +{ + *Enum_Ref_Par = Enum_Val_Par; + if (! Func_3 (Enum_Val_Par)) + /* then, not executed */ + *Enum_Ref_Par = Ident_4; + switch (Enum_Val_Par) + { + case Ident_1: + *Enum_Ref_Par = Ident_1; + break; + case Ident_2: + if (Int_Glob > 100) + /* then */ + *Enum_Ref_Par = Ident_1; + else *Enum_Ref_Par = Ident_4; + break; + case Ident_3: /* executed */ + *Enum_Ref_Par = Ident_2; + break; + case Ident_4: break; + case Ident_5: + *Enum_Ref_Par = Ident_3; + break; + } /* switch */ +} /* Proc_6 */ + + +void Proc_7( One_Fifty Int_1_Par_Val, One_Fifty Int_2_Par_Val, + One_Fifty * Int_Par_Ref ) +/**********************************************/ + /* executed three times */ + /* first call: Int_1_Par_Val == 2, Int_2_Par_Val == 3, */ + /* Int_Par_Ref becomes 7 */ + /* second call: Int_1_Par_Val == 10, Int_2_Par_Val == 5, */ + /* Int_Par_Ref becomes 17 */ + /* third call: Int_1_Par_Val == 6, Int_2_Par_Val == 10, */ + /* Int_Par_Ref becomes 18 */ +{ + One_Fifty Int_Loc; + + Int_Loc = Int_1_Par_Val + 2; + *Int_Par_Ref = Int_2_Par_Val + Int_Loc; +} /* Proc_7 */ + + +void Proc_8( Arr_1_Dim Arr_1_Par_Ref, Arr_2_Dim Arr_2_Par_Ref, + int Int_1_Par_Val, int Int_2_Par_Val ) +/*********************************************************************/ + /* executed once */ + /* Int_Par_Val_1 == 3 */ + /* Int_Par_Val_2 == 7 */ +{ + REG One_Fifty Int_Index; + REG One_Fifty Int_Loc; + + Int_Loc = Int_1_Par_Val + 5; + Arr_1_Par_Ref [Int_Loc] = Int_2_Par_Val; + Arr_1_Par_Ref [Int_Loc+1] = Arr_1_Par_Ref [Int_Loc]; + Arr_1_Par_Ref [Int_Loc+30] = Int_Loc; + for (Int_Index = Int_Loc; Int_Index <= Int_Loc+1; ++Int_Index) + Arr_2_Par_Ref [Int_Loc] [Int_Index] = Int_Loc; + Arr_2_Par_Ref [Int_Loc] [Int_Loc-1] += 1; + Arr_2_Par_Ref [Int_Loc+20] [Int_Loc] = Arr_1_Par_Ref [Int_Loc]; + Int_Glob = 5; +} /* Proc_8 */ + + +Enumeration Func_1 ( Capital_Letter Ch_1_Par_Val, Capital_Letter Ch_2_Par_Val ) +/*************************************************/ + /* executed three times */ + /* first call: Ch_1_Par_Val == 'H', Ch_2_Par_Val == 'R' */ + /* second call: Ch_1_Par_Val == 'A', Ch_2_Par_Val == 'C' */ + /* third call: Ch_1_Par_Val == 'B', Ch_2_Par_Val == 'C' */ +{ + Capital_Letter Ch_1_Loc; + Capital_Letter Ch_2_Loc; + + Ch_1_Loc = Ch_1_Par_Val; + Ch_2_Loc = Ch_1_Loc; + if (Ch_2_Loc != Ch_2_Par_Val) + /* then, executed */ + return (Ident_1); + else /* not executed */ + { + Ch_1_Glob = Ch_1_Loc; + return (Ident_2); + } +} /* Func_1 */ + + +Boolean Func_2( Str_30 Str_1_Par_Ref, Str_30 Str_2_Par_Ref ) +/*************************************************/ + /* executed once */ + /* Str_1_Par_Ref == "DHRYSTONE PROGRAM, 1'ST STRING" */ + /* Str_2_Par_Ref == "DHRYSTONE PROGRAM, 2'ND STRING" */ +{ + REG One_Thirty Int_Loc; + Capital_Letter Ch_Loc; + + Int_Loc = 2; + while (Int_Loc <= 2) /* loop body executed once */ + if (Func_1 (Str_1_Par_Ref[Int_Loc], + Str_2_Par_Ref[Int_Loc+1]) == Ident_1) + /* then, executed */ + { + Ch_Loc = 'A'; + Int_Loc += 1; + } /* if, while */ + if (Ch_Loc >= 'W' && Ch_Loc < 'Z') + /* then, not executed */ + Int_Loc = 7; + if (Ch_Loc == 'R') + /* then, not executed */ + return (true); + else /* executed */ + { + if (strcmp (Str_1_Par_Ref, Str_2_Par_Ref) > 0) + /* then, not executed */ + { + Int_Loc += 7; + Int_Glob = Int_Loc; + return (true); + } + else /* executed */ + return (false); + } /* if Ch_Loc */ +} /* Func_2 */ + + +Boolean Func_3( Enumeration Enum_Par_Val ) +/***************************/ + /* executed once */ + /* Enum_Par_Val == Ident_3 */ +{ + Enumeration Enum_Loc; + + Enum_Loc = Enum_Par_Val; + if (Enum_Loc == Ident_3) + /* then, executed */ + return (true); + else /* not executed */ + return (false); +} /* Func_3 */ + diff --git a/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry.h b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry.h new file mode 100644 index 0000000000000000000000000000000000000000..404adb42b0d3c7625535333a17122e7cb58b0348 --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry.h @@ -0,0 +1,431 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry.h (part 1 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * Siemens AG, E STE 35 + * Postfach 3240 + * 8520 Erlangen + * Germany (West) + * Phone: [xxx-49]-9131-7-20330 + * (8-17 Central European Time) + * Usenet: ..!mcvax!unido!estevax!weicker + * + * Original Version (in Ada) published in + * "Communications of the ACM" vol. 27., no. 10 (Oct. 1984), + * pp. 1013 - 1030, together with the statistics + * on which the distribution of statements etc. is based. + * + * In this C version, the following C library functions are used: + * - strcpy, strcmp (inside the measurement loop) + * - printf, scanf (outside the measurement loop) + * In addition, Berkeley UNIX system calls "times ()" or "time ()" + * are used for execution time measurement. For measurements + * on other systems, these calls have to be changed. + * + * Collection of Results: + * Reinhold Weicker (address see above) and + * + * Rick Richardson + * PC Research. Inc. + * 94 Apple Orchard Drive + * Tinton Falls, NJ 07724 + * Phone: (201) 389-8963 (9-17 EST) + * Usenet: ...!uunet!pcrat!rick + * + * Please send results to Rick Richardson and/or Reinhold Weicker. + * Complete information should be given on hardware and software used. + * Hardware information includes: Machine type, CPU, type and size + * of caches; for microprocessors: clock frequency, memory speed + * (number of wait states). + * Software information includes: Compiler (and runtime library) + * manufacturer and version, compilation switches, OS version. + * The Operating System version may give an indication about the + * compiler; Dhrystone itself performs no OS calls in the measurement loop. + * + * The complete output generated by the program should be mailed + * such that at least some checks for correctness can be made. + * + *************************************************************************** + * + * History: This version C/2.1 has been made for two reasons: + * + * 1) There is an obvious need for a common C version of + * Dhrystone, since C is at present the most popular system + * programming language for the class of processors + * (microcomputers, minicomputers) where Dhrystone is used most. + * There should be, as far as possible, only one C version of + * Dhrystone such that results can be compared without + * restrictions. In the past, the C versions distributed + * by Rick Richardson (Version 1.1) and by Reinhold Weicker + * had small (though not significant) differences. + * + * 2) As far as it is possible without changes to the Dhrystone + * statistics, optimizing compilers should be prevented from + * removing significant statements. + * + * This C version has been developed in cooperation with + * Rick Richardson (Tinton Falls, NJ), it incorporates many + * ideas from the "Version 1.1" distributed previously by + * him over the UNIX network Usenet. + * I also thank Chaim Benedelac (National Semiconductor), + * David Ditzel (SUN), Earl Killian and John Mashey (MIPS), + * Alan Smith and Rafael Saavedra-Barrera (UC at Berkeley) + * for their help with comments on earlier versions of the + * benchmark. + * + * Changes: In the initialization part, this version follows mostly + * Rick Richardson's version distributed via Usenet, not the + * version distributed earlier via floppy disk by Reinhold Weicker. + * As a concession to older compilers, names have been made + * unique within the first 8 characters. + * Inside the measurement loop, this version follows the + * version previously distributed by Reinhold Weicker. + * + * At several places in the benchmark, code has been added, + * but within the measurement loop only in branches that + * are not executed. The intention is that optimizing compilers + * should be prevented from moving code out of the measurement + * loop, or from removing code altogether. Since the statements + * that are executed within the measurement loop have NOT been + * changed, the numbers defining the "Dhrystone distribution" + * (distribution of statements, operand types and locality) + * still hold. Except for sophisticated optimizing compilers, + * execution times for this version should be the same as + * for previous versions. + * + * Since it has proven difficult to subtract the time for the + * measurement loop overhead in a correct way, the loop check + * has been made a part of the benchmark. This does have + * an impact - though a very minor one - on the distribution + * statistics which have been updated for this version. + * + * All changes within the measurement loop are described + * and discussed in the companion paper "Rationale for + * Dhrystone version 2". + * + * Because of the self-imposed limitation that the order and + * distribution of the executed statements should not be + * changed, there are still cases where optimizing compilers + * may not generate code for some statements. To a certain + * degree, this is unavoidable for small synthetic benchmarks. + * Users of the benchmark are advised to check code listings + * whether code is generated for all statements of Dhrystone. + * + * Version 2.1 is identical to version 2.0 distributed via + * the UNIX network Usenet in March 1988 except that it corrects + * some minor deficiencies that were found by users of version 2.0. + * The only change within the measurement loop is that a + * non-executed "else" part was added to the "if" statement in + * Func_3, and a non-executed "else" part removed from Proc_3. + * + *************************************************************************** + * + * Defines: The following "Defines" are possible: + * -DREG=register (default: Not defined) + * As an approximation to what an average C programmer + * might do, the "register" storage class is applied + * (if enabled by -DREG=register) + * - for local variables, if they are used (dynamically) + * five or more times + * - for parameters if they are used (dynamically) + * six or more times + * Note that an optimal "register" strategy is + * compiler-dependent, and that "register" declarations + * do not necessarily lead to faster execution. + * -DNOSTRUCTASSIGN (default: Not defined) + * Define if the C compiler does not support + * assignment of structures. + * -DNOENUMS (default: Not defined) + * Define if the C compiler does not support + * enumeration types. + * -DTIMES (default) + * -DTIME + * The "times" function of UNIX (returning process times) + * or the "time" function (returning wallclock time) + * is used for measurement. + * For single user machines, "time ()" is adequate. For + * multi-user machines where you cannot get single-user + * access, use the "times ()" function. If you have + * neither, use a stopwatch in the dead of night. + * "printf"s are provided marking the points "Start Timer" + * and "Stop Timer". DO NOT use the UNIX "time(1)" + * command, as this will measure the total time to + * run this program, which will (erroneously) include + * the time to allocate storage (malloc) and to perform + * the initialization. + * -DHZ=nnn + * In Berkeley UNIX, the function "times" returns process + * time in 1/HZ seconds, with HZ = 60 for most systems. + * CHECK YOUR SYSTEM DESCRIPTION BEFORE YOU JUST APPLY + * A VALUE. + * + *************************************************************************** + * + * Compilation model and measurement (IMPORTANT): + * + * This C version of Dhrystone consists of three files: + * - dhry.h (this file, containing global definitions and comments) + * - dhry_1.c (containing the code corresponding to Ada package Pack_1) + * - dhry_2.c (containing the code corresponding to Ada package Pack_2) + * + * The following "ground rules" apply for measurements: + * - Separate compilation + * - No procedure merging + * - Otherwise, compiler optimizations are allowed but should be indicated + * - Default results are those without register declarations + * See the companion paper "Rationale for Dhrystone Version 2" for a more + * detailed discussion of these ground rules. + * + * For 16-Bit processors (e.g. 80186, 80286), times for all compilation + * models ("small", "medium", "large" etc.) should be given if possible, + * together with a definition of these models for the compiler system used. + * + ************************************************************************** + * + * Dhrystone (C version) statistics: + * + * [Comment from the first distribution, updated for version 2. + * Note that because of language differences, the numbers are slightly + * different from the Ada version.] + * + * The following program contains statements of a high level programming + * language (here: C) in a distribution considered representative: + * + * assignments 52 (51.0 %) + * control statements 33 (32.4 %) + * procedure, function calls 17 (16.7 %) + * + * 103 statements are dynamically executed. The program is balanced with + * respect to the three aspects: + * + * - statement type + * - operand type + * - operand locality + * operand global, local, parameter, or constant. + * + * The combination of these three aspects is balanced only approximately. + * + * 1. Statement Type: + * ----------------- number + * + * V1 = V2 9 + * (incl. V1 = F(..) + * V = Constant 12 + * Assignment, 7 + * with array element + * Assignment, 6 + * with record component + * -- + * 34 34 + * + * X = Y +|-|"&&"|"|" Z 5 + * X = Y +|-|"==" Constant 6 + * X = X +|- 1 3 + * X = Y *|/ Z 2 + * X = Expression, 1 + * two operators + * X = Expression, 1 + * three operators + * -- + * 18 18 + * + * if .... 14 + * with "else" 7 + * without "else" 7 + * executed 3 + * not executed 4 + * for ... 7 | counted every time + * while ... 4 | the loop condition + * do ... while 1 | is evaluated + * switch ... 1 + * break 1 + * declaration with 1 + * initialization + * -- + * 34 34 + * + * P (...) procedure call 11 + * user procedure 10 + * library procedure 1 + * X = F (...) + * function call 6 + * user function 5 + * library function 1 + * -- + * 17 17 + * --- + * 103 + * + * The average number of parameters in procedure or function calls + * is 1.82 (not counting the function values aX * + * + * 2. Operators + * ------------ + * number approximate + * percentage + * + * Arithmetic 32 50.8 + * + * + 21 33.3 + * - 7 11.1 + * * 3 4.8 + * / (int div) 1 1.6 + * + * Comparison 27 42.8 + * + * == 9 14.3 + * /= 4 6.3 + * > 1 1.6 + * < 3 4.8 + * >= 1 1.6 + * <= 9 14.3 + * + * Logic 4 6.3 + * + * && (AND-THEN) 1 1.6 + * | (OR) 1 1.6 + * ! (NOT) 2 3.2 + * + * -- ----- + * 63 100.1 + * + * + * 3. Operand Type (counted once per operand reference): + * --------------- + * number approximate + * percentage + * + * Integer 175 72.3 % + * Character 45 18.6 % + * Pointer 12 5.0 % + * String30 6 2.5 % + * Array 2 0.8 % + * Record 2 0.8 % + * --- ------- + * 242 100.0 % + * + * When there is an access path leading to the final operand (e.g. a record + * component), only the final data type on the access path is counted. + * + * + * 4. Operand Locality: + * ------------------- + * number approximate + * percentage + * + * local variable 114 47.1 % + * global variable 22 9.1 % + * parameter 45 18.6 % + * value 23 9.5 % + * reference 22 9.1 % + * function result 6 2.5 % + * constant 55 22.7 % + * --- ------- + * 242 100.0 % + * + * + * The program does not compute anything meaningful, but it is syntactically + * and semantically correct. All variables have a value assigned to them + * before they are used as a source operand. + * + * There has been no explicit effort to account for the effects of a + * cache, or to balance the use of long or short displacements for code or + * data. + * + *************************************************************************** + */ + +/* Compiler and system dependent definitions: */ + +#ifndef TIME +#undef TIMES +#define TIMES +#endif + /* Use times(2) time function unless */ + /* explicitly defined otherwise */ + +#ifdef MSC_CLOCK +#undef HZ +#undef TIMES +#include +#define HZ CLK_TCK +#endif + /* Use Microsoft C hi-res clock */ + +#ifdef TIMES +#include +#include + /* for "times" */ +#endif + +#define Mic_secs_Per_Second 1000000.0 + /* Berkeley UNIX C returns process times in seconds/HZ */ + +#ifdef NOSTRUCTASSIGN +#define structassign(d, s) memcpy(&(d), &(s), sizeof(d)) +#else +#define structassign(d, s) d = s +#endif + +#ifdef NOENUM +#define Ident_1 0 +#define Ident_2 1 +#define Ident_3 2 +#define Ident_4 3 +#define Ident_5 4 + typedef int Enumeration; +#else + typedef enum {Ident_1, Ident_2, Ident_3, Ident_4, Ident_5} + Enumeration; +#endif + /* for boolean and enumeration types in Ada, Pascal */ + +/* General definitions: */ + +#include + /* for strcpy, strcmp */ + +#define Null 0 + /* Value of a Null pointer */ +#define true 1 +#define false 0 + +typedef int One_Thirty; +typedef int One_Fifty; +typedef char Capital_Letter; +typedef int Boolean; +typedef char Str_30 [31]; +typedef int Arr_1_Dim [50]; +typedef int Arr_2_Dim [50] [50]; + +typedef struct record + { + struct record *Ptr_Comp; + Enumeration Discr; + union { + struct { + Enumeration Enum_Comp; + int Int_Comp; + char Str_Comp [31]; + } var_1; + struct { + Enumeration E_Comp_2; + char Str_2_Comp [31]; + } var_2; + struct { + char Ch_1_Comp; + char Ch_2_Comp; + } var_3; + } variant; + } Rec_Type, *Rec_Pointer; + + diff --git a/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_1.c b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_1.c new file mode 100644 index 0000000000000000000000000000000000000000..164c6f946d2e542868f881cda9de895f32022d2f --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_1.c @@ -0,0 +1,395 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry_1.c (part 2 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * + **************************************************************************** + */ + +#include "dhry.h" + +/* Global Variables: */ + +Rec_Pointer Ptr_Glob, + Next_Ptr_Glob; +int Int_Glob; +Boolean Bool_Glob; +char Ch_1_Glob, + Ch_2_Glob; +int Arr_1_Glob [50]; +int Arr_2_Glob [50] [50]; + +extern char *malloc (); +Enumeration Func_1 (); + /* forward declaration necessary since Enumeration may not simply be int */ + +#ifndef REG + Boolean Reg = false; +#define REG + /* REG becomes defined as empty */ + /* i.e. no register variables */ +#else + Boolean Reg = true; +#endif + +/* variables for time measurement: */ + +#ifdef TIMES +struct tms time_info; +extern int times (); + /* see library function "times" */ +#define Too_Small_Time (2*HZ) + /* Measurements should last at least about 2 seconds */ +#endif +#ifdef TIME +extern long time(); + /* see library function "time" */ +#define Too_Small_Time 2 + /* Measurements should last at least 2 seconds */ +#endif +#ifdef MSC_CLOCK +extern clock_t clock(); +#define Too_Small_Time (2*HZ) +#endif + +long Begin_Time, + End_Time, + User_Time; +float Microseconds, + Dhrystones_Per_Second; + +/* end of variables for time measurement */ + + +main () +/*****/ + + /* main program, corresponds to procedures */ + /* Main and Proc_0 in the Ada version */ +{ + One_Fifty Int_1_Loc; + REG One_Fifty Int_2_Loc; + One_Fifty Int_3_Loc; + REG char Ch_Index; + Enumeration Enum_Loc; + Str_30 Str_1_Loc; + Str_30 Str_2_Loc; + REG int Run_Index; + REG int Number_Of_Runs; + + /* Initializations */ + + Next_Ptr_Glob = (Rec_Pointer) malloc (sizeof (Rec_Type)); + Ptr_Glob = (Rec_Pointer) malloc (sizeof (Rec_Type)); + + Ptr_Glob->Ptr_Comp = Next_Ptr_Glob; + Ptr_Glob->Discr = Ident_1; + Ptr_Glob->variant.var_1.Enum_Comp = Ident_3; + Ptr_Glob->variant.var_1.Int_Comp = 40; + strcpy (Ptr_Glob->variant.var_1.Str_Comp, + "DHRYSTONE PROGRAM, SOME STRING"); + strcpy (Str_1_Loc, "DHRYSTONE PROGRAM, 1'ST STRING"); + + Arr_2_Glob [8][7] = 10; + /* Was missing in published program. Without this statement, */ + /* Arr_2_Glob [8][7] would have an undefined value. */ + /* Warning: With 16-Bit processors and Number_Of_Runs > 32000, */ + /* overflow may occur for this array element. */ + + printf ("\n"); + printf ("Dhrystone Benchmark, Version 2.1 (Language: C)\n"); + printf ("\n"); + if (Reg) + { + printf ("Program compiled with 'register' attribute\n"); + printf ("\n"); + } + else + { + printf ("Program compiled without 'register' attribute\n"); + printf ("\n"); + } + printf ("Please give the number of runs through the benchmark: "); + { + int n; + scanf ("%d", &n); + Number_Of_Runs = n; + } + printf ("\n"); + + printf ("Execution starts, %d runs through Dhrystone\n", Number_Of_Runs); + + /***************/ + /* Start timer */ + /***************/ + +#ifdef TIMES + times (&time_info); + Begin_Time = (long) time_info.tms_utime; +#endif +#ifdef TIME + Begin_Time = time ( (long *) 0); +#endif +#ifdef MSC_CLOCK + Begin_Time = clock(); +#endif + + for (Run_Index = 1; Run_Index <= Number_Of_Runs; ++Run_Index) + { + + Proc_5(); + Proc_4(); + /* Ch_1_Glob == 'A', Ch_2_Glob == 'B', Bool_Glob == true */ + Int_1_Loc = 2; + Int_2_Loc = 3; + strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 2'ND STRING"); + Enum_Loc = Ident_2; + Bool_Glob = ! Func_2 (Str_1_Loc, Str_2_Loc); + /* Bool_Glob == 1 */ + while (Int_1_Loc < Int_2_Loc) /* loop body executed once */ + { + Int_3_Loc = 5 * Int_1_Loc - Int_2_Loc; + /* Int_3_Loc == 7 */ + Proc_7 (Int_1_Loc, Int_2_Loc, &Int_3_Loc); + /* Int_3_Loc == 7 */ + Int_1_Loc += 1; + } /* while */ + /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ + Proc_8 (Arr_1_Glob, Arr_2_Glob, Int_1_Loc, Int_3_Loc); + /* Int_Glob == 5 */ + Proc_1 (Ptr_Glob); + for (Ch_Index = 'A'; Ch_Index <= Ch_2_Glob; ++Ch_Index) + /* loop body executed twice */ + { + if (Enum_Loc == Func_1 (Ch_Index, 'C')) + /* then, not executed */ + { + Proc_6 (Ident_1, &Enum_Loc); + strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 3'RD STRING"); + Int_2_Loc = Run_Index; + Int_Glob = Run_Index; + } + } + /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ + Int_2_Loc = Int_2_Loc * Int_1_Loc; + Int_1_Loc = Int_2_Loc / Int_3_Loc; + Int_2_Loc = 7 * (Int_2_Loc - Int_3_Loc) - Int_1_Loc; + /* Int_1_Loc == 1, Int_2_Loc == 13, Int_3_Loc == 7 */ + Proc_2 (&Int_1_Loc); + /* Int_1_Loc == 5 */ + + } /* loop "for Run_Index" */ + + /**************/ + /* Stop timer */ + /**************/ + +#ifdef TIMES + times (&time_info); + End_Time = (long) time_info.tms_utime; +#endif +#ifdef TIME + End_Time = time ( (long *) 0); +#endif +#ifdef MSC_CLOCK + End_Time = clock(); +#endif + + printf ("Execution ends\n"); + printf ("\n"); + printf ("Final values of the variables used in the benchmark:\n"); + printf ("\n"); + printf ("Int_Glob: %d\n", Int_Glob); + printf (" should be: %d\n", 5); + printf ("Bool_Glob: %d\n", Bool_Glob); + printf (" should be: %d\n", 1); + printf ("Ch_1_Glob: %c\n", Ch_1_Glob); + printf (" should be: %c\n", 'A'); + printf ("Ch_2_Glob: %c\n", Ch_2_Glob); + printf (" should be: %c\n", 'B'); + printf ("Arr_1_Glob[8]: %d\n", Arr_1_Glob[8]); + printf (" should be: %d\n", 7); + printf ("Arr_2_Glob[8][7]: %d\n", Arr_2_Glob[8][7]); + printf (" should be: Number_Of_Runs + 10\n"); + printf ("Ptr_Glob->\n"); + printf (" Ptr_Comp: %d\n", (int) Ptr_Glob->Ptr_Comp); + printf (" should be: (implementation-dependent)\n"); + printf (" Discr: %d\n", Ptr_Glob->Discr); + printf (" should be: %d\n", 0); + printf (" Enum_Comp: %d\n", Ptr_Glob->variant.var_1.Enum_Comp); + printf (" should be: %d\n", 2); + printf (" Int_Comp: %d\n", Ptr_Glob->variant.var_1.Int_Comp); + printf (" should be: %d\n", 17); + printf (" Str_Comp: %s\n", Ptr_Glob->variant.var_1.Str_Comp); + printf (" should be: DHRYSTONE PROGRAM, SOME STRING\n"); + printf ("Next_Ptr_Glob->\n"); + printf (" Ptr_Comp: %d\n", (int) Next_Ptr_Glob->Ptr_Comp); + printf (" should be: (implementation-dependent), same as above\n"); + printf (" Discr: %d\n", Next_Ptr_Glob->Discr); + printf (" should be: %d\n", 0); + printf (" Enum_Comp: %d\n", Next_Ptr_Glob->variant.var_1.Enum_Comp); + printf (" should be: %d\n", 1); + printf (" Int_Comp: %d\n", Next_Ptr_Glob->variant.var_1.Int_Comp); + printf (" should be: %d\n", 18); + printf (" Str_Comp: %s\n", + Next_Ptr_Glob->variant.var_1.Str_Comp); + printf (" should be: DHRYSTONE PROGRAM, SOME STRING\n"); + printf ("Int_1_Loc: %d\n", Int_1_Loc); + printf (" should be: %d\n", 5); + printf ("Int_2_Loc: %d\n", Int_2_Loc); + printf (" should be: %d\n", 13); + printf ("Int_3_Loc: %d\n", Int_3_Loc); + printf (" should be: %d\n", 7); + printf ("Enum_Loc: %d\n", Enum_Loc); + printf (" should be: %d\n", 1); + printf ("Str_1_Loc: %s\n", Str_1_Loc); + printf (" should be: DHRYSTONE PROGRAM, 1'ST STRING\n"); + printf ("Str_2_Loc: %s\n", Str_2_Loc); + printf (" should be: DHRYSTONE PROGRAM, 2'ND STRING\n"); + printf ("\n"); + + User_Time = End_Time - Begin_Time; + + if (User_Time < Too_Small_Time) + { + printf ("Measured time too small to obtain meaningful results\n"); + printf ("Please increase number of runs\n"); + printf ("\n"); + } + else + { +#ifdef TIME + Microseconds = (float) User_Time * Mic_secs_Per_Second + / (float) Number_Of_Runs; + Dhrystones_Per_Second = (float) Number_Of_Runs / (float) User_Time; +#else + Microseconds = (float) User_Time * Mic_secs_Per_Second + / ((float) HZ * ((float) Number_Of_Runs)); + Dhrystones_Per_Second = ((float) HZ * (float) Number_Of_Runs) + / (float) User_Time; +#endif + printf ("Microseconds for one run through Dhrystone: "); + printf ("%6.1f \n", Microseconds); + printf ("Dhrystones per Second: "); + printf ("%6.1f \n", Dhrystones_Per_Second); + printf ("\n"); + } + +} + + +Proc_1 (Ptr_Val_Par) +/******************/ + +REG Rec_Pointer Ptr_Val_Par; + /* executed once */ +{ + REG Rec_Pointer Next_Record = Ptr_Val_Par->Ptr_Comp; + /* == Ptr_Glob_Next */ + /* Local variable, initialized with Ptr_Val_Par->Ptr_Comp, */ + /* corresponds to "rename" in Ada, "with" in Pascal */ + + structassign (*Ptr_Val_Par->Ptr_Comp, *Ptr_Glob); + Ptr_Val_Par->variant.var_1.Int_Comp = 5; + Next_Record->variant.var_1.Int_Comp + = Ptr_Val_Par->variant.var_1.Int_Comp; + Next_Record->Ptr_Comp = Ptr_Val_Par->Ptr_Comp; + Proc_3 (&Next_Record->Ptr_Comp); + /* Ptr_Val_Par->Ptr_Comp->Ptr_Comp + == Ptr_Glob->Ptr_Comp */ + if (Next_Record->Discr == Ident_1) + /* then, executed */ + { + Next_Record->variant.var_1.Int_Comp = 6; + Proc_6 (Ptr_Val_Par->variant.var_1.Enum_Comp, + &Next_Record->variant.var_1.Enum_Comp); + Next_Record->Ptr_Comp = Ptr_Glob->Ptr_Comp; + Proc_7 (Next_Record->variant.var_1.Int_Comp, 10, + &Next_Record->variant.var_1.Int_Comp); + } + else /* not executed */ + structassign (*Ptr_Val_Par, *Ptr_Val_Par->Ptr_Comp); +} /* Proc_1 */ + + +Proc_2 (Int_Par_Ref) +/******************/ + /* executed once */ + /* *Int_Par_Ref == 1, becomes 4 */ + +One_Fifty *Int_Par_Ref; +{ + One_Fifty Int_Loc; + Enumeration Enum_Loc; + + Int_Loc = *Int_Par_Ref + 10; + do /* executed once */ + if (Ch_1_Glob == 'A') + /* then, executed */ + { + Int_Loc -= 1; + *Int_Par_Ref = Int_Loc - Int_Glob; + Enum_Loc = Ident_1; + } /* if */ + while (Enum_Loc != Ident_1); /* true */ +} /* Proc_2 */ + + +Proc_3 (Ptr_Ref_Par) +/******************/ + /* executed once */ + /* Ptr_Ref_Par becomes Ptr_Glob */ + +Rec_Pointer *Ptr_Ref_Par; + +{ + if (Ptr_Glob != Null) + /* then, executed */ + *Ptr_Ref_Par = Ptr_Glob->Ptr_Comp; + Proc_7 (10, Int_Glob, &Ptr_Glob->variant.var_1.Int_Comp); +} /* Proc_3 */ + + +Proc_4 () /* without parameters */ +/*******/ + /* executed once */ +{ + Boolean Bool_Loc; + + Bool_Loc = Ch_1_Glob == 'A'; + Bool_Glob = Bool_Loc | Bool_Glob; + Ch_2_Glob = 'B'; +} /* Proc_4 */ + + +Proc_5 () /* without parameters */ +/*******/ + /* executed once */ +{ + Ch_1_Glob = 'A'; + Bool_Glob = false; +} /* Proc_5 */ + + + /* Procedure for the assignment of structures, */ + /* if the C compiler doesn't support this feature */ +#ifdef NOSTRUCTASSIGN +memcpy (d, s, l) +register char *d; +register char *s; +register int l; +{ + while (l--) *d++ = *s++; +} +#endif + + diff --git a/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_2.c b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_2.c new file mode 100644 index 0000000000000000000000000000000000000000..63a3d3ea03378b7b68a5acf784085548e11859d9 --- /dev/null +++ b/turbo9team_turbo9/c_code/dhrystone_src/orig_src/dhry_2.c @@ -0,0 +1,192 @@ +/* + **************************************************************************** + * + * "DHRYSTONE" Benchmark Program + * ----------------------------- + * + * Version: C, Version 2.1 + * + * File: dhry_2.c (part 3 of 3) + * + * Date: May 25, 1988 + * + * Author: Reinhold P. Weicker + * + **************************************************************************** + */ + +#include "dhry.h" + +#ifndef REG +#define REG + /* REG becomes defined as empty */ + /* i.e. no register variables */ +#endif + +extern int Int_Glob; +extern char Ch_1_Glob; + + +Proc_6 (Enum_Val_Par, Enum_Ref_Par) +/*********************************/ + /* executed once */ + /* Enum_Val_Par == Ident_3, Enum_Ref_Par becomes Ident_2 */ + +Enumeration Enum_Val_Par; +Enumeration *Enum_Ref_Par; +{ + *Enum_Ref_Par = Enum_Val_Par; + if (! Func_3 (Enum_Val_Par)) + /* then, not executed */ + *Enum_Ref_Par = Ident_4; + switch (Enum_Val_Par) + { + case Ident_1: + *Enum_Ref_Par = Ident_1; + break; + case Ident_2: + if (Int_Glob > 100) + /* then */ + *Enum_Ref_Par = Ident_1; + else *Enum_Ref_Par = Ident_4; + break; + case Ident_3: /* executed */ + *Enum_Ref_Par = Ident_2; + break; + case Ident_4: break; + case Ident_5: + *Enum_Ref_Par = Ident_3; + break; + } /* switch */ +} /* Proc_6 */ + + +Proc_7 (Int_1_Par_Val, Int_2_Par_Val, Int_Par_Ref) +/**********************************************/ + /* executed three times */ + /* first call: Int_1_Par_Val == 2, Int_2_Par_Val == 3, */ + /* Int_Par_Ref becomes 7 */ + /* second call: Int_1_Par_Val == 10, Int_2_Par_Val == 5, */ + /* Int_Par_Ref becomes 17 */ + /* third call: Int_1_Par_Val == 6, Int_2_Par_Val == 10, */ + /* Int_Par_Ref becomes 18 */ +One_Fifty Int_1_Par_Val; +One_Fifty Int_2_Par_Val; +One_Fifty *Int_Par_Ref; +{ + One_Fifty Int_Loc; + + Int_Loc = Int_1_Par_Val + 2; + *Int_Par_Ref = Int_2_Par_Val + Int_Loc; +} /* Proc_7 */ + + +Proc_8 (Arr_1_Par_Ref, Arr_2_Par_Ref, Int_1_Par_Val, Int_2_Par_Val) +/*********************************************************************/ + /* executed once */ + /* Int_Par_Val_1 == 3 */ + /* Int_Par_Val_2 == 7 */ +Arr_1_Dim Arr_1_Par_Ref; +Arr_2_Dim Arr_2_Par_Ref; +int Int_1_Par_Val; +int Int_2_Par_Val; +{ + REG One_Fifty Int_Index; + REG One_Fifty Int_Loc; + + Int_Loc = Int_1_Par_Val + 5; + Arr_1_Par_Ref [Int_Loc] = Int_2_Par_Val; + Arr_1_Par_Ref [Int_Loc+1] = Arr_1_Par_Ref [Int_Loc]; + Arr_1_Par_Ref [Int_Loc+30] = Int_Loc; + for (Int_Index = Int_Loc; Int_Index <= Int_Loc+1; ++Int_Index) + Arr_2_Par_Ref [Int_Loc] [Int_Index] = Int_Loc; + Arr_2_Par_Ref [Int_Loc] [Int_Loc-1] += 1; + Arr_2_Par_Ref [Int_Loc+20] [Int_Loc] = Arr_1_Par_Ref [Int_Loc]; + Int_Glob = 5; +} /* Proc_8 */ + + +Enumeration Func_1 (Ch_1_Par_Val, Ch_2_Par_Val) +/*************************************************/ + /* executed three times */ + /* first call: Ch_1_Par_Val == 'H', Ch_2_Par_Val == 'R' */ + /* second call: Ch_1_Par_Val == 'A', Ch_2_Par_Val == 'C' */ + /* third call: Ch_1_Par_Val == 'B', Ch_2_Par_Val == 'C' */ + +Capital_Letter Ch_1_Par_Val; +Capital_Letter Ch_2_Par_Val; +{ + Capital_Letter Ch_1_Loc; + Capital_Letter Ch_2_Loc; + + Ch_1_Loc = Ch_1_Par_Val; + Ch_2_Loc = Ch_1_Loc; + if (Ch_2_Loc != Ch_2_Par_Val) + /* then, executed */ + return (Ident_1); + else /* not executed */ + { + Ch_1_Glob = Ch_1_Loc; + return (Ident_2); + } +} /* Func_1 */ + + +Boolean Func_2 (Str_1_Par_Ref, Str_2_Par_Ref) +/*************************************************/ + /* executed once */ + /* Str_1_Par_Ref == "DHRYSTONE PROGRAM, 1'ST STRING" */ + /* Str_2_Par_Ref == "DHRYSTONE PROGRAM, 2'ND STRING" */ + +Str_30 Str_1_Par_Ref; +Str_30 Str_2_Par_Ref; +{ + REG One_Thirty Int_Loc; + Capital_Letter Ch_Loc; + + Int_Loc = 2; + while (Int_Loc <= 2) /* loop body executed once */ + if (Func_1 (Str_1_Par_Ref[Int_Loc], + Str_2_Par_Ref[Int_Loc+1]) == Ident_1) + /* then, executed */ + { + Ch_Loc = 'A'; + Int_Loc += 1; + } /* if, while */ + if (Ch_Loc >= 'W' && Ch_Loc < 'Z') + /* then, not executed */ + Int_Loc = 7; + if (Ch_Loc == 'R') + /* then, not executed */ + return (true); + else /* executed */ + { + if (strcmp (Str_1_Par_Ref, Str_2_Par_Ref) > 0) + /* then, not executed */ + { + Int_Loc += 7; + Int_Glob = Int_Loc; + return (true); + } + else /* executed */ + return (false); + } /* if Ch_Loc */ +} /* Func_2 */ + + +Boolean Func_3 (Enum_Par_Val) +/***************************/ + /* executed once */ + /* Enum_Par_Val == Ident_3 */ +Enumeration Enum_Par_Val; +{ + Enumeration Enum_Loc; + + Enum_Loc = Enum_Par_Val; + if (Enum_Loc == Ident_3) + /* then, executed */ + return (true); + else /* not executed */ + return (false); +} /* Func_3 */ + diff --git a/turbo9team_turbo9/c_code/hello_world_src/hello_world.c b/turbo9team_turbo9/c_code/hello_world_src/hello_world.c new file mode 100644 index 0000000000000000000000000000000000000000..850f362b340059622b5775fbe5168a5f48275f45 --- /dev/null +++ b/turbo9team_turbo9/c_code/hello_world_src/hello_world.c @@ -0,0 +1,66 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Hello World for vbcc or GCC6809 +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include "lib.h" + +SECTION_START + int main() { + COUNTER_VAR + + setup(); + + COUNTER_START + + acia_print_str("\nHello, World!\n"); + + COUNTER_STOP + + COUNTER_PRINT + + teardown(); + + return 0; +} + diff --git a/turbo9team_turbo9/c_code/lib_gcc/lib.c b/turbo9team_turbo9/c_code/lib_gcc/lib.c new file mode 100644 index 0000000000000000000000000000000000000000..2fe3671cbe0c0ec0e9a978bb39ed84b919d4eac7 --- /dev/null +++ b/turbo9team_turbo9/c_code/lib_gcc/lib.c @@ -0,0 +1,328 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Library for GCC6809 +// Provides basic std_lib functions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include "lib.h" + +//////////////////////////////////////// Print String +// +void acia_print_str(char *string_ptr) +{ + + while (*string_ptr != NULL) + { + acia_put_char(*string_ptr); + string_ptr++; + } + +} + + +//////////////////////////////////////// Put Char +// +/* +void acia_put_char(char data) +{ + + if (SIM_BOOT_DETECT == 0) + { + while (!(ACIA_STATUS & (char)0x10)); // wait for TX buffer empty + ACIA_DATA = data; + } + else + { + SIM_BOOT_ACIA_OUT = data; + } +} +*/ + +__asm__ +( + " .area .text \n" + " .globl _acia_put_char \n" + "_acia_put_char \n" + " lda #3 \n" + " swi \n" + " rts \n" +); + + + +//////////////////////////////////////// Put 16-bit Hex +// +void acia_print_hex_16bit(u16 data) +{ + union WORD tmp; + tmp.ui = data; + + acia_print_hex_byte(tmp.ub[0]); // big endian + acia_print_hex_byte(tmp.ub[1]); +} + + +//////////////////////////////////////// Put 8-bit Hex +// +void acia_print_hex_byte(u08 data) +{ + acia_put_hex_nibble((data>>4)&0x0F); + acia_put_hex_nibble((data)&0x0F); +} + + +//////////////////////////////////////// Put 4-bit Hex +// +void acia_put_hex_nibble(u08 data) +{ + if (data > 9) + { + data += 0x07; + } + + data += 0x30; + + acia_put_char(data); +} + + +//////////////////////////////////////// Print signed decimal +// +void acia_print_signed_long(s32 snum) +{ + + union LONG tmp; + + tmp.sl = snum; + + if (tmp.ub[0] & 0x80) // Negative? (big endian) + { + // This method accounts for -2147483648 case. + // casting can cause issues depending on compiler + acia_put_char('-'); + tmp.ul = ~tmp.ul; + tmp.ul++; + } + + acia_print_unsigned_long(tmp.ul); +} + + +//////////////////////////////////////// Print unsigned decimal +// +void acia_print_unsigned_long(u32 unum) +{ + + u32 divisor = 1000000000; + u08 digit; + u08 flag; + + flag = 0; + for (divisor = 1000000000; divisor != 0; divisor=divisor/10) + { + digit = (u08)(unum / divisor); + unum = unum % divisor; + if ((digit != 0) || (divisor == 1)) + { + flag = 1; + } + if (flag) + { + digit += 0x30; + acia_put_char(digit); + } + } + +} + + +//////////////////////////////////////// +// +void setup(void) +{ +} + +//////////////////////////////////////// +// +void teardown(void) +{ +} + + +//////////////////////////////////////// +// +void abort(void) +{ + acia_print_str("\nNaN\n"); +} + + + +/* +int strcmp(const char *s1, const char *s2) +{ + // check if s1 and s2 vectors are equal + while(*s1 != '\0' && *s1 == *s2) + { + s1++; + s2++; + } + + // return the difference of the last char on the string + return (*(unsigned char *) s1) - (*(unsigned char *) s2); +} +*/ + + +__asm__ +( + " .area .text \n" + " .globl _strcmp \n" + "_strcmp: \n" + " pshs u \n" + " ldu 4,s \n" + "strcmp_loop: \n" + " ldb ,x+ \n" + " beq strcmp_done_cond1 \n" + " subb ,u+ \n" + " bne strcmp_done \n" + " ; \n" + " ldb ,x+ \n" + " beq strcmp_done_cond1 \n" + " subb ,u+ \n" + " beq strcmp_loop \n" + "strcmp_done: \n" + " sex \n" + " tfr d,x \n" + " puls u,pc \n" + "strcmp_done_cond1: \n" + " subb ,u \n" + " sex \n" + " tfr d,x \n" + " puls u,pc \n" +); + + + +/* +void *memcpy(char *d, const char *s, unsigned l) +{ + while (l--) *d++ = *s++; +} +*/ + + +__asm__ +( + " .area .text \n" + " .globl _memcpy \n" + "_memcpy: \n" + " pshs y,u \n" + " ldu 6,s ; *s (source) \n" + " ldd 8,s ; l (num of bytes) \n" + " tfr d,y \n" + " lsrb ; odd num of bytes? \n" + " bcc memcopy_16bit \n" + "memcopy_8bit \n" + " lda ,u+ \n" + " sta ,x+ \n" + " leay -1,y \n" + " beq memcopy_done \n" + "memcopy_16bit \n" + " ldd ,u++ \n" + " std ,x++ \n" + " leay -2,y \n" + " beq memcopy_done \n" + " ; \n" + " ldd ,u++ \n" + " std ,x++ \n" + " leay -2,y \n" + " bne memcopy_16bit \n" + "memcopy_done \n" + " puls y,u,pc \n" +); + + +/* +char* strcpy(char *dst0, const char * src0) +{ + char *s = dst0; + + // copy the source to the destination + while(*dst0++ = *src0++); + + return s; +} +*/ + +__asm__ +( + " .area .text \n" + " .globl _strcpy \n" + "_strcpy: \n" + " pshs y,u \n" + " tfr x,y \n" + " ldu 6,s \n" + "strcpy_loop: \n" + " lda ,u+ \n" + " beq strcpy_done_wr_8bit \n" + " ldb ,u+ \n" + " beq strcpy_done_wr_16bit \n" + " std ,y++ \n" + " ; \n" + " lda ,u+ \n" + " beq strcpy_done_wr_8bit \n" + " ldb ,u+ \n" + " beq strcpy_done_wr_16bit \n" + " std ,y++ \n" + " bra strcpy_loop \n" + "strcpy_done_wr_16bit: \n" + " std ,y \n" + " puls y,u,pc \n" + "strcpy_done_wr_8bit: \n" + " sta ,y \n" + " puls y,u,pc \n" +); + + + diff --git a/turbo9team_turbo9/c_code/lib_gcc/lib.h b/turbo9team_turbo9/c_code/lib_gcc/lib.h new file mode 100644 index 0000000000000000000000000000000000000000..87f0baf9c0b35af998f3f4742ba4f5fa2dec8456 --- /dev/null +++ b/turbo9team_turbo9/c_code/lib_gcc/lib.h @@ -0,0 +1,121 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Library for GCC6809 compiler +// Provides basic std_lib functions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _TURBO9_LIB_ +#define _TURBO9_LIB_ + +////////////////////////////////////// Type Defs +// +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +union LONG +{ + s32 sl; + u32 ul; + s16 si[2]; + u16 ui[2]; + s08 sb[4]; + u08 ub[4]; +}; + +union WORD +{ + s16 si; + u16 ui; + s08 sb[2]; + u08 ub[2]; +}; + + +////////////////////////////////////// Defines & Macros +// +#define OUTPUT_PORT (*(volatile u08 *)0x0000) +#define CLOCK_COUNT (*(volatile u32 *)0x0004) +#define CLOCK_COUNT_H (*(volatile u16 *)0x0004) +#define CLOCK_COUNT_L (*(volatile u16 *)0x0006) +#define NULL 0x00 + +#define SECTION_START __attribute__((section (".prog_start"))) + +#define COUNTER_VAR \ + union LONG clk_cnt; + +#define COUNTER_START \ + OUTPUT_PORT = 0x01; \ + OUTPUT_PORT = 0x03; + +#define COUNTER_STOP \ + OUTPUT_PORT = 0x43; \ + clk_cnt.ui[0] = CLOCK_COUNT_H; \ + clk_cnt.ui[1] = CLOCK_COUNT_L; \ + +#define COUNTER_PRINT \ + acia_print_str("Clock Count: "); \ + acia_print_unsigned_long(clk_cnt.ul); \ + acia_print_str(" (CPU clocks)\n"); + + +////////////////////////////////////// Function Declaration +// +extern void acia_print_str(char *string_ptr); +extern void acia_put_char(char data); +extern void acia_print_hex_16bit(u16 data); +extern void acia_print_hex_byte(u08 data); +extern void acia_put_hex_nibble(u08 data); +extern void acia_print_unsigned_long(u32 unum); +extern void acia_print_signed_long(s32 snum); +extern void abort(void); +extern void setup(void); +extern void teardown(void); +extern char * strcpy(char *dst0, const char * src0); +extern int strcmp(const char *s1, const char *s2); +extern void * memcpy(char *d, const char *s, unsigned l); + +#endif diff --git a/turbo9team_turbo9/c_code/lib_vbcc/lib.c b/turbo9team_turbo9/c_code/lib_vbcc/lib.c new file mode 100644 index 0000000000000000000000000000000000000000..07f53189cb84b3332099ef881f02d4b23531c881 --- /dev/null +++ b/turbo9team_turbo9/c_code/lib_vbcc/lib.c @@ -0,0 +1,197 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Library for vbcc compiler +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include "lib.h" + +//////////////////////////////////////// Print String +// +void acia_print_str(char *string_ptr) +{ + + while (*string_ptr != NULL) + { + acia_put_char(*string_ptr); + string_ptr++; + } + +} + + +//////////////////////////////////////// Put 16-bit Hex +// +void acia_print_hex_16bit(u16 data) +{ + union WORD tmp; + tmp.ui = data; + + acia_print_hex_byte(tmp.ub[0]); // big endian + acia_print_hex_byte(tmp.ub[1]); +} + + +//////////////////////////////////////// Put 8-bit Hex +// +void acia_print_hex_byte(u08 data) +{ + acia_put_hex_nibble((data>>4)&0x0F); + acia_put_hex_nibble((data)&0x0F); +} + + +//////////////////////////////////////// Put 4-bit Hex +// +void acia_put_hex_nibble(u08 data) +{ + if (data > 9) + data += 0x07; + + data += 0x30; + + acia_put_char(data); +} + + +//////////////////////////////////////// Print signed decimal +// +void acia_print_signed_long(s32 snum) +{ + + union LONG tmp; + + tmp.sl = snum; + + if (tmp.ub[0] & 0x80) // Negative? (big endian) + { + // This method accounts for -2147483648 case. + // casting can cause issues depending on compiler + acia_put_char('-'); + tmp.ul = ~tmp.ul; + tmp.ul++; + } + + acia_print_unsigned_long(tmp.ul); +} + + + +//////////////////////////////////////// Print unsigned decimal +// +void acia_print_unsigned_long(u32 unum) +{ + + u32 divisor = 1000000000; + u08 digit; + u08 flag; + + flag = 0; + for (divisor = 1000000000; divisor != 0; divisor=divisor/10) + { + digit = (u08)(unum / divisor); + unum = unum % divisor; + if ((digit != 0) || (divisor == 1)) + { + flag = 1; + } + if (flag) + { + digit += 0x30; + acia_put_char(digit); + } + } + +} + + +/* +//////////////////////////////////////// Print unsigned decimal +// +void acia_print_unsigned_long(u32 unum) +{ + + static u32 div_array[10] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; + u32 div; + u08 digit; + u08 flag; + u08 idx; + + flag = 0; + for (idx = 10; idx !=0; idx--) + { + digit = 0; + div = 0; + while ((unum > div) && ~((idx == 10) && (digit == 4))) + { + div = div + div_array[idx-1]; + digit++; + } + if ((unum < div) + { + div = div - div_array[idx-1]; + digit--; + } + unum = unum - div; + if ((idx == 1) || (digit != 0)) + { + flag = 1; + } + if (flag) + { + digit += 0x30; + acia_put_char(digit); + } + } + +} +*/ + +void setup(void) +{ +} + +void teardown(void) +{ +} + + diff --git a/turbo9team_turbo9/c_code/lib_vbcc/lib.h b/turbo9team_turbo9/c_code/lib_vbcc/lib.h new file mode 100644 index 0000000000000000000000000000000000000000..d0753442508254613a075ab946ecec05a613b255 --- /dev/null +++ b/turbo9team_turbo9/c_code/lib_vbcc/lib.h @@ -0,0 +1,164 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Library for vbcc compiler +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#ifndef _TURBO9_LIB_ +#define _TURBO9_LIB_ + + +////////////////////////////////////// Type Defs +// +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +union LONG +{ + s32 sl; + u32 ul; + s16 si[2]; + u16 ui[2]; + s08 sb[4]; + u08 ub[4]; +}; + +union WORD +{ + s16 si; + u16 ui; + s08 sb[2]; + u08 ub[2]; +}; + + +////////////////////////////////////// Defines & Macros +// +#define OUTPUT_PORT (*(volatile u08 *)0x0000) +#define CLOCK_COUNT (*(volatile u32 *)0x0004) +#define CLOCK_COUNT_H (*(volatile u16 *)0x0004) +#define CLOCK_COUNT_L (*(volatile u16 *)0x0006) +#define NULL 0x00 + +#define SECTION_START +//#define SECTION_START __section(.prog_start,"prog_start") +//__attribute__((section (".prog_start"))) + +#define COUNTER_VAR \ + union LONG clk_cnt; + +#define COUNTER_START \ + OUTPUT_PORT = 0x01; \ + OUTPUT_PORT = 0x03; + +#define COUNTER_STOP \ + OUTPUT_PORT = 0x43; \ + clk_cnt.ui[0] = CLOCK_COUNT_H; \ + clk_cnt.ui[1] = CLOCK_COUNT_L; \ + +#define COUNTER_PRINT \ + acia_print_str("Clock Count: "); \ + acia_print_unsigned_long(clk_cnt.ul); \ + acia_print_str(" (CPU clocks)\n"); + + +////////////////////////////////////// Function Declaration +// +extern void acia_print_str(char *string_ptr); +//extern void acia_put_char(char data); +extern void acia_print_hex_16bit(u16 data); +extern void acia_print_hex_byte(u08 data); +extern void acia_put_hex_nibble(u08 data); +extern void acia_print_unsigned_long(u32 unum); +extern void acia_print_signed_long(s32 snum); +//extern void abort(void); +extern void setup(void); +extern void teardown(void); +//extern char * strcpy(char *dst0, const char * src0); +//extern int strcmp(const char *s1, const char *s2); +//extern void * memcpy(char *d, const char *s, unsigned l); +//extern void acia_put_char(__reg("d") char); +//extern int emul(int dy, int dd); +//extern int idiv(int dd, int dx); + +void acia_put_char(__reg("d") char)="\tlda\t#3\n\tswi"; + +int strcmp(__reg("y") const char *, __reg("x")const char *) = + ".1: \n" + " ldd ,y++ \n" + " tsta \n" + " beq .3 \n" + " tstb \n" + " beq .5 \n" + " subd ,x++ \n" + " bne .2 \n" + " ; \n" + " ldd ,y++ \n" + " tsta \n" + " beq .3 \n" + " tstb \n" + " beq .5 \n" + " subd ,x++ \n" + " beq .1 \n" + " ; \n" + ".2: \n" + " ldd -2,y \n" + " suba -2,x \n" + " bne .4 \n" + " subb -1,x \n" + " bra .6 \n" + ".3: \n" + " suba ,x \n" + ".4: \n" + " tfr a,b \n" + " bra .6 \n" + ".5: \n" + " subb 1,x \n" + ".6: \n" + " sex \n"; + + +#endif diff --git a/turbo9team_turbo9/rtl/README.md b/turbo9team_turbo9/rtl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0f83457fbbbc62e4c10812a94dc0291c64f98294 --- /dev/null +++ b/turbo9team_turbo9/rtl/README.md @@ -0,0 +1,15 @@ + +# Top Level Files + +| | | +|---------------|---------------------------------------| +| fpga_top.v | FPGA top | +| | | +| soc_top.v | SoC top 8-bit memory bus | +| soc_top_r.v | SoC top 16-bit memory bus | +| soc_top_gtr.v | SoC top 16-bit Harvard memory bus | +| | | +| turbo9.v | Turbo9 top 8-bit memory bus | +| turbo9_r.v | Turbo9 top 16-bit memory bus | +| turbo9_gtr.v | Turbo9 top 16-bit Harvard memory bus | +| | | diff --git a/turbo9team_turbo9/rtl/clk_counter.v b/turbo9team_turbo9/rtl/clk_counter.v new file mode 100644 index 0000000000000000000000000000000000000000..7731684f87bfc5c168082988ee917842027f8d58 --- /dev/null +++ b/turbo9team_turbo9/rtl/clk_counter.v @@ -0,0 +1,103 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Simple timer for counting clock cycles +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module clk_counter +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input [ 7:0] PORT_I, + output [31:0] CLK_CNT_DATA_O +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +reg [31:0] clk_cnt_reg; +localparam clk_cnt_rst = 32'd0; + +wire [1:0] state = {PORT_I[6], PORT_I[1]}; +localparam CLEAR = 2'b00; +localparam RUN = 2'b01; +localparam STOP = 2'b11; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Clock Counter +///////////////////////////////////////////////////////////////////////////// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + clk_cnt_reg <= clk_cnt_rst; + end else begin + if (state == CLEAR) begin + clk_cnt_reg <= clk_cnt_rst; + end else if (state == RUN) begin + clk_cnt_reg <= clk_cnt_reg + 32'd1; + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +assign CLK_CNT_DATA_O = clk_cnt_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/clk_div.v b/turbo9team_turbo9/rtl/clk_div.v new file mode 100644 index 0000000000000000000000000000000000000000..cfcc940c5b1ca983c562bff31f06a06fc01ce885 --- /dev/null +++ b/turbo9team_turbo9/rtl/clk_div.v @@ -0,0 +1,89 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Simple clock divider +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +// Engineer: Kevin Phillipson + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module clk_div +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + + // Outputs + output CLK_DIV2 +); +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +reg clk_div_reg; +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + clk_div_reg <= 1'b0; + end else begin + clk_div_reg <= ~clk_div_reg; + end +end +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +// Outputs +assign CLK_DIV2 = clk_div_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/fpga_leds.v b/turbo9team_turbo9/rtl/fpga_leds.v new file mode 100644 index 0000000000000000000000000000000000000000..28d54cb93064e3a91c733d63af77974908aa0bbb --- /dev/null +++ b/turbo9team_turbo9/rtl/fpga_leds.v @@ -0,0 +1,135 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: LED interface with PWM dimming +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module fpga_leds +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + + // Inputs + input [7:0] LED_PORT_I, + + // Outputs + output [3:0] LED_O, + output LED0_B_O, + output LED0_G_O, + output LED0_R_O, + output LED1_B_O, + output LED1_G_O, + output LED1_R_O, + output LED2_B_O, + output LED2_G_O, + output LED2_R_O, + output LED3_B_O, + output LED3_G_O, + output LED3_R_O + +); + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +wire [7:0] led_pwm; +reg [7:0] led_pwm_reg; +reg [19:0] cnt_reg; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + cnt_reg <= 20'd0; + led_pwm_reg <= 8'd0; + end else begin + cnt_reg <= cnt_reg + 20'd1; + led_pwm_reg <= led_pwm; + end +end +assign led_pwm[7:4] = (cnt_reg[19] == 1'd0) ? LED_PORT_I[7:4] : 4'h0; +assign led_pwm[3:0] = (cnt_reg[19:12] == 8'd0) ? LED_PORT_I[3:0] : 4'h0; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +assign LED0_B_O = 1'b0; +assign LED1_B_O = 1'b0; +assign LED2_B_O = 1'b0; +assign LED3_B_O = 1'b0; + +assign LED0_R_O = 1'b0; +assign LED1_R_O = 1'b0; +assign LED2_R_O = 1'b0; +assign LED3_R_O = 1'b0; + +assign LED0_G_O = led_pwm_reg[0]; +assign LED1_G_O = led_pwm_reg[1]; +assign LED2_G_O = led_pwm_reg[2]; +assign LED3_G_O = led_pwm_reg[3]; +assign LED_O[0] = led_pwm_reg[4]; +assign LED_O[1] = led_pwm_reg[5]; +assign LED_O[2] = led_pwm_reg[6]; +assign LED_O[3] = led_pwm_reg[7]; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/fpga_top.v b/turbo9team_turbo9/rtl/fpga_top.v new file mode 100644 index 0000000000000000000000000000000000000000..fa934a66721d49ddbb340a2f23424d2f936b7a2d --- /dev/null +++ b/turbo9team_turbo9/rtl/fpga_top.v @@ -0,0 +1,200 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: FPGA top level that instaniates the SoC +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module fpga_top +( + // Inputs: Clock & Reset + input CLK100MHZ, + input ck_rst, //active low + + // Inputs + input uart_txd_in, + + // Outputs + output uart_rxd_out, + + // Outputs + output [3:0] led, + output led0_b, + output led0_g, + output led0_r, + output led1_b, + output led1_g, + output led1_r, + output led2_b, + output led2_g, + output led2_r, + output led3_b, + output led3_g, + output led3_r + +); + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +reg clk100_rst_meta; +reg clk100_rst_sync; + +wire clk; +reg rst_meta; +reg rst_sync; + +wire [7:0] led_port; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// CLOCK & RESET LOGIC +///////////////////////////////////////////////////////////////////////////// + +//assign clk = CLK100MHZ; + +// Reset Synchro +always @(posedge CLK100MHZ, negedge ck_rst) begin + if (~ck_rst) begin + clk100_rst_meta <= 1'b1; + clk100_rst_sync <= 1'b1; + end else begin + clk100_rst_meta <= 1'b0; + clk100_rst_sync <= clk100_rst_meta; + end +end + + +clk_div I_clk_div +( + // Inputs: Clock & Reset + .CLK_I (CLK100MHZ ), + .RST_I (clk100_rst_sync ), + + // Outputs + .CLK_DIV2 (clk ) +); + + +// Reset Synchro +always @(posedge clk, negedge ck_rst) begin + if (~ck_rst) begin + rst_meta <= 1'b1; + rst_sync <= 1'b1; + end else begin + rst_meta <= 1'b0; + rst_sync <= rst_meta; + end +end + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +//soc_top +soc_top_s +//soc_top +#( + 15 // MEM_ADDR_WIDTH +) +//I_soc_top +I_soc_top_s +//I_soc_top +( + // Inputs: Clock & Reset + .RST_I (rst_sync ), // Reset. Active high and synchronized to CLK_I + .CLK_I (clk ), // Clock + + .RXD_PIN_I (uart_txd_in ), + + // Outputs + .TXD_PIN_O (uart_rxd_out ), + + .OUTPUT_PORT_O (led_port ) +); + + + +fpga_leds I_fpga_leds +( + // Inputs: Clock & Reset + .CLK_I (clk ), + .RST_I (rst_sync ), + // + // Inputs + .LED_PORT_I (led_port ), + // + // Outputs + .LED_O (led ), + .LED0_B_O (led0_b ), + .LED0_G_O (led0_g ), + .LED0_R_O (led0_r ), + .LED1_B_O (led1_b ), + .LED1_G_O (led1_g ), + .LED1_R_O (led1_r ), + .LED2_B_O (led2_b ), + .LED2_G_O (led2_g ), + .LED2_R_O (led2_r ), + .LED3_B_O (led3_b ), + .LED3_G_O (led3_g ), + .LED3_R_O (led3_r ) +); +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/output_port.v b/turbo9team_turbo9/rtl/output_port.v new file mode 100644 index 0000000000000000000000000000000000000000..df987d46d0daf2b1690d93d7eba8140409d8bd72 --- /dev/null +++ b/turbo9team_turbo9/rtl/output_port.v @@ -0,0 +1,81 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Simple memory mapped 8-bit output port +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module output_port +( + input CLK_I, + input RST_I, + input WE_I, + input [ 7:0] DAT_I, + output [ 7:0] DAT_O, + output [ 7:0] PORT_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +reg [7:0] port_reg; +localparam port_rst = 8'd0; + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + port_reg <= port_rst; + end else if (WE_I) begin + port_reg <= DAT_I; + end +end + +assign DAT_O = port_reg; +assign PORT_O = port_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + + diff --git a/turbo9team_turbo9/rtl/soc_top.v b/turbo9team_turbo9/rtl/soc_top.v new file mode 100644 index 0000000000000000000000000000000000000000..82c65ef62313a16f5b9c40411c2e9a708b2610e5 --- /dev/null +++ b/turbo9team_turbo9/rtl/soc_top.v @@ -0,0 +1,279 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Target independent SoC top level for the Turbo9 (8-bit bus) +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module soc_top +#( + parameter MEM_ADDR_WIDTH = 15 +) +( + // Inputs: Clock & Reset + input RST_I, // Reset. Active high and synchronized to CLK_I + input CLK_I, // Clock + + // Inputs + input RXD_PIN_I, + + // Outputs + output TXD_PIN_O, + output [7:0] OUTPUT_PORT_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +wire [3:0] turbo9_tgd_o; +reg [3:0] turbo9_tgd_reg; +localparam turbo9_tgd_rst = 4'b0000; + +wire [15:0] turbo9_adr; +reg [15:0] turbo9_adr_reg; +localparam turbo9_adr_rst = 16'h0000; + +wire [7:0] turbo9_wr_dat; +reg [7:0] turbo9_rd_dat; + +wire turbo9_stb; +reg turbo9_ack; +wire turbo9_we; +reg turbo9_we_reg; +localparam turbo9_we_rst = 1'b0; + +wire [7:0] acia_data_rd_dat; +wire [7:0] acia_status_rd_dat; + +reg acia_data_wr_en; +reg acia_data_rd_en; + +reg ram_we; +wire [7:0] ram_rd_dat; + +reg port_we; +wire [7:0] port_rd_dat; + +wire [31:0] clk_cnt_rd_dat; + +wire ram_clk; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// + + turbo9 + #( + .REGISTER_WB_OUTPUTS (0), // Register Wishbone Ouputs: True=1, False=0 + .QUEUE_SIZE (7) // Fetch Queue Size: 6=Default, 4=Min, 7=Max + ) + I_turbo9 + ( + // Inputs: Clock & Reset + .RST_I (RST_I), + .CLK_I (CLK_I), + + // Inputs + .DAT_I (turbo9_rd_dat), + .TGD_I (turbo9_tgd_reg), + .ACK_I (turbo9_ack), + .STALL_I (1'b0), + + // Outputs + .ADR_O (turbo9_adr), + .DAT_O (turbo9_wr_dat), + .TGD_O (turbo9_tgd_o), + .WE_O (turbo9_we), + .STB_O (turbo9_stb), + .CYC_O () + ); + +/* + assign ram_clk = CLK_I; + + // Wishbone Pipeline Registers (Even Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + turbo9_adr_reg <= turbo9_adr_rst; + turbo9_ack <= 1'b0; + turbo9_tgd_reg <= turbo9_tgd_rst; + turbo9_we_reg <= turbo9_we_rst; + end else begin + turbo9_adr_reg <= turbo9_adr; + turbo9_ack <= turbo9_stb; + turbo9_tgd_reg <= turbo9_tgd_o; + turbo9_we_reg <= turbo9_we; + end + end +*/ + + + assign ram_clk = ~CLK_I; + + always @* begin + turbo9_adr_reg = turbo9_adr; + turbo9_ack = turbo9_stb; + turbo9_tgd_reg = turbo9_tgd_o; + turbo9_we_reg = turbo9_we; + end + + + + // Write Enables (Even Bytes) + always @* begin + // Defaults + ram_we = 1'b0; + port_we = 1'b0; + acia_data_wr_en = 1'b0; + // + // Even Memory Bus Read Data Mux + if (turbo9_adr[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin + ram_we = turbo9_we; + end else begin + case (turbo9_adr[3:0]) + // + 4'h2: acia_data_wr_en = turbo9_we; + 4'h0: port_we = turbo9_we; + endcase + end + end + + // RAM + syncram_8bit + #( + .MEM_ADDR_WIDTH (MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default.hex") + ) + I_syncram_8bit + ( + .CLK_I (ram_clk), + .WE_I (ram_we), + .ADR_I (turbo9_adr[MEM_ADDR_WIDTH-1:0]), + .DAT_I (turbo9_wr_dat), + .DAT_O (ram_rd_dat) + ); + + // Output Port + output_port I_output_port + ( + .CLK_I (CLK_I), + .RST_I (RST_I), + .WE_I (port_we), + .DAT_I (turbo9_wr_dat), + .DAT_O (port_rd_dat), + .PORT_O (OUTPUT_PORT_O) + ); + + // UART + t6551 I_t6551 + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .TX_DATA_I (turbo9_wr_dat ), + .TX_DATA_WR_EN_I (acia_data_wr_en ), + .RXD_PIN_I (RXD_PIN_I ), + .RX_DATA_RD_EN_I (acia_data_rd_en ), + + // Outputs + .TXD_PIN_O (TXD_PIN_O ), + .RX_DATA_O (acia_data_rd_dat ), + .STATUS_DATA_O (acia_status_rd_dat ) + ); + + // Clock Count Timer + clk_counter I_clk_counter + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // Inputs + .PORT_I (OUTPUT_PORT_O ), + .CLK_CNT_DATA_O (clk_cnt_rd_dat ) + ); + + // Read Data Muxes & Enables + always @* begin + // Defaults + turbo9_rd_dat = 8'h00; + acia_data_rd_en = 1'b0; + // + if (turbo9_adr_reg[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin + turbo9_rd_dat = ram_rd_dat; + end else begin + case (turbo9_adr_reg[3:0]) + // + 4'h7: turbo9_rd_dat = clk_cnt_rd_dat[ 7: 0]; + 4'h6: turbo9_rd_dat = clk_cnt_rd_dat[15: 8]; + 4'h5: turbo9_rd_dat = clk_cnt_rd_dat[23:16]; + 4'h4: turbo9_rd_dat = clk_cnt_rd_dat[31:24]; + 4'h3: turbo9_rd_dat = acia_status_rd_dat; + 4'h2: begin + turbo9_rd_dat = acia_data_rd_dat; + acia_data_rd_en = ~turbo9_we_reg; + end + 4'h0: turbo9_rd_dat = port_rd_dat; + default: turbo9_rd_dat = 8'h00; + endcase + end + end + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/soc_top_gtr.v b/turbo9team_turbo9/rtl/soc_top_gtr.v new file mode 100644 index 0000000000000000000000000000000000000000..7df8befeab1d25bc6f0187d52365c57123a54568 --- /dev/null +++ b/turbo9team_turbo9/rtl/soc_top_gtr.v @@ -0,0 +1,506 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Target independent top level for the Turbo9GTR +// (16-bit program & 16-bit data buses) +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module soc_top_gtr +#( + parameter MEM_ADDR_WIDTH = 15 +) +( + // Inputs: Clock & Reset + input RST_I, // Reset. Active high and synchronized to CLK_I + input CLK_I, // Clock + + // Inputs + input RXD_PIN_I, + + // Outputs + output TXD_PIN_O, + output [7:0] OUTPUT_PORT_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +localparam FULL_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH; +localparam EVEN_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH-1; +localparam ODD_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH-1; + + +wire [4:0] pmem_even_turbo9_tgd_o; +reg [4:0] pmem_even_turbo9_tgd_reg; +localparam pmem_even_turbo9_tgd_rst = 5'b00000; + +wire [14:0] pmem_even_turbo9_adr; +reg [14:0] pmem_even_turbo9_adr_reg; +localparam pmem_even_turbo9_adr_rst = 15'h0000; + +wire [15:0] pmem_even_turbo9_adr_full = {pmem_even_turbo9_adr, 1'b0}; +wire [15:0] pmem_even_turbo9_adr_reg_full = {pmem_even_turbo9_adr_reg, 1'b0}; + +wire [7:0] pmem_even_turbo9_wr_dat; +reg [7:0] pmem_even_turbo9_rd_dat; + +wire pmem_even_turbo9_stb; +reg pmem_even_turbo9_ack; +wire pmem_even_turbo9_we; +reg pmem_even_turbo9_we_reg; +localparam pmem_even_turbo9_we_rst = 1'b0; + +wire [14:0] pmem_odd_turbo9_adr; +reg [14:0] pmem_odd_turbo9_adr_reg; +localparam pmem_odd_turbo9_adr_rst = 15'h0000; + +wire [15:0] pmem_odd_turbo9_adr_full = {pmem_odd_turbo9_adr, 1'b1}; +wire [15:0] pmem_odd_turbo9_adr_reg_full = {pmem_odd_turbo9_adr_reg, 1'b1}; + +wire [7:0] pmem_odd_turbo9_wr_dat; +reg [7:0] pmem_odd_turbo9_rd_dat; + +wire pmem_odd_turbo9_stb; +reg pmem_odd_turbo9_ack; +wire pmem_odd_turbo9_we; + +reg pmem_even_ram_we; +wire [7:0] pmem_even_ram_rd_dat; + +reg pmem_odd_ram_we; +wire [7:0] pmem_odd_ram_rd_dat; + + + +wire [4:0] dmem_even_turbo9_tgd_o; +reg [4:0] dmem_even_turbo9_tgd_reg; +localparam dmem_even_turbo9_tgd_rst = 5'b00000; + +wire [14:0] dmem_even_turbo9_adr; +reg [14:0] dmem_even_turbo9_adr_reg; +localparam dmem_even_turbo9_adr_rst = 15'h0000; + +wire [15:0] dmem_even_turbo9_adr_full = {dmem_even_turbo9_adr, 1'b0}; +wire [15:0] dmem_even_turbo9_adr_reg_full = {dmem_even_turbo9_adr_reg, 1'b0}; + +wire [7:0] dmem_even_turbo9_wr_dat; +reg [7:0] dmem_even_turbo9_rd_dat; + +wire dmem_even_turbo9_stb; +reg dmem_even_turbo9_ack; +wire dmem_even_turbo9_we; +reg dmem_even_turbo9_we_reg; +localparam dmem_even_turbo9_we_rst = 1'b0; + +wire [14:0] dmem_odd_turbo9_adr; +reg [14:0] dmem_odd_turbo9_adr_reg; +localparam dmem_odd_turbo9_adr_rst = 15'h0000; + +wire [15:0] dmem_odd_turbo9_adr_full = {dmem_odd_turbo9_adr, 1'b1}; +wire [15:0] dmem_odd_turbo9_adr_reg_full = {dmem_odd_turbo9_adr_reg, 1'b1}; + +wire [7:0] dmem_odd_turbo9_wr_dat; +reg [7:0] dmem_odd_turbo9_rd_dat; + +wire dmem_odd_turbo9_stb; +reg dmem_odd_turbo9_ack; +wire dmem_odd_turbo9_we; + +reg dmem_even_ram_we; +wire [7:0] dmem_even_ram_rd_dat; + +reg dmem_odd_ram_we; +wire [7:0] dmem_odd_ram_rd_dat; + +wire [7:0] acia_data_rd_dat; +wire [7:0] acia_status_rd_dat; + +reg acia_data_wr_en; +reg acia_data_rd_en; + +reg port_we; +wire [7:0] port_rd_dat; + +wire [31:0] clk_cnt_rd_dat; + +wire ram_clk; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// + + // Turbo9R + turbo9_gtr + #( + .REGISTER_WB_OUTPUTS (0), + .QUEUE_SIZE (6) + ) + I_turbo9_gtr + ( + // Inputs: Clock & Reset + .RST_I (RST_I), + .CLK_I (CLK_I), + // + // Program Memory Wishbone Interface (Even bytes) + .PMEM_EVEN_TGD_I (pmem_even_turbo9_tgd_reg ), + .PMEM_EVEN_TGD_O (pmem_even_turbo9_tgd_o ), + // + .PMEM_EVEN_DAT_I (pmem_even_turbo9_rd_dat ), + .PMEM_EVEN_ACK_I (pmem_even_turbo9_ack ), + .PMEM_EVEN_STALL_I (1'b0 ), + .PMEM_EVEN_ADR_O (pmem_even_turbo9_adr ), + .PMEM_EVEN_DAT_O (pmem_even_turbo9_wr_dat ), + .PMEM_EVEN_WE_O (pmem_even_turbo9_we ), + .PMEM_EVEN_STB_O (pmem_even_turbo9_stb ), + .PMEM_EVEN_CYC_O ( ), + // + // Program Memory Wishbone Interface (Odd bytes) + .PMEM_ODD_DAT_I (pmem_odd_turbo9_rd_dat ), + .PMEM_ODD_ACK_I (pmem_odd_turbo9_ack ), + .PMEM_ODD_STALL_I (1'b0 ), + .PMEM_ODD_ADR_O (pmem_odd_turbo9_adr ), + .PMEM_ODD_DAT_O (pmem_odd_turbo9_wr_dat ), + .PMEM_ODD_WE_O (pmem_odd_turbo9_we ), + .PMEM_ODD_STB_O (pmem_odd_turbo9_stb ), + .PMEM_ODD_CYC_O ( ), + // + // Data Memory Wishbone Interface (Even bytes) + .DMEM_EVEN_TGD_I (dmem_even_turbo9_tgd_reg ), + .DMEM_EVEN_TGD_O (dmem_even_turbo9_tgd_o ), + // + .DMEM_EVEN_DAT_I (dmem_even_turbo9_rd_dat ), + .DMEM_EVEN_ACK_I (dmem_even_turbo9_ack ), + .DMEM_EVEN_STALL_I (1'b0 ), + .DMEM_EVEN_ADR_O (dmem_even_turbo9_adr ), + .DMEM_EVEN_DAT_O (dmem_even_turbo9_wr_dat ), + .DMEM_EVEN_WE_O (dmem_even_turbo9_we ), + .DMEM_EVEN_STB_O (dmem_even_turbo9_stb ), + .DMEM_EVEN_CYC_O ( ), + // + // Data Memory Wishbone Interface (Odd bytes) + .DMEM_ODD_DAT_I (dmem_odd_turbo9_rd_dat ), + .DMEM_ODD_ACK_I (dmem_odd_turbo9_ack ), + .DMEM_ODD_STALL_I (1'b0 ), + .DMEM_ODD_ADR_O (dmem_odd_turbo9_adr ), + .DMEM_ODD_DAT_O (dmem_odd_turbo9_wr_dat ), + .DMEM_ODD_WE_O (dmem_odd_turbo9_we ), + .DMEM_ODD_STB_O (dmem_odd_turbo9_stb ), + .DMEM_ODD_CYC_O ( ) + + ); + + /* + assign ram_clk = CLK_I; + + // Wishbone Pipeline Registers (Even Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + dmem_even_turbo9_adr_reg <= dmem_even_turbo9_adr_rst; + dmem_even_turbo9_ack <= 1'b0; + dmem_even_turbo9_tgd_reg <= dmem_even_turbo9_tgd_rst; + dmem_even_turbo9_we_reg <= dmem_even_turbo9_we_rst; + end else begin + dmem_even_turbo9_adr_reg <= dmem_even_turbo9_adr; + dmem_even_turbo9_ack <= dmem_even_turbo9_stb; + dmem_even_turbo9_tgd_reg <= dmem_even_turbo9_tgd_o; + dmem_even_turbo9_we_reg <= dmem_even_turbo9_we; + end + end + + // Wishbone Pipeline Registers (Odd Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + dmem_odd_turbo9_adr_reg <= dmem_odd_turbo9_adr_rst; + dmem_odd_turbo9_ack <= 1'b0; + end else begin + dmem_odd_turbo9_adr_reg <= dmem_odd_turbo9_adr; + dmem_odd_turbo9_ack <= dmem_odd_turbo9_stb; + end + end + */ + + assign ram_clk = ~CLK_I; + + always @* begin + dmem_even_turbo9_adr_reg = dmem_even_turbo9_adr; + dmem_even_turbo9_ack = dmem_even_turbo9_stb; + dmem_even_turbo9_tgd_reg = dmem_even_turbo9_tgd_o; + dmem_even_turbo9_we_reg = dmem_even_turbo9_we; + dmem_odd_turbo9_adr_reg = dmem_odd_turbo9_adr; + dmem_odd_turbo9_ack = dmem_odd_turbo9_stb; + end + + + /* + // Wishbone Pipeline Registers (Even Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + pmem_even_turbo9_adr_reg <= pmem_even_turbo9_adr_rst; + pmem_even_turbo9_ack <= 1'b0; + pmem_even_turbo9_tgd_reg <= pmem_even_turbo9_tgd_rst; + pmem_even_turbo9_we_reg <= pmem_even_turbo9_we_rst; + end else begin + pmem_even_turbo9_adr_reg <= pmem_even_turbo9_adr; + pmem_even_turbo9_ack <= pmem_even_turbo9_stb; + pmem_even_turbo9_tgd_reg <= pmem_even_turbo9_tgd_o; + pmem_even_turbo9_we_reg <= pmem_even_turbo9_we; + end + end + + // Wishbone Pipeline Registers (Odd Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + pmem_odd_turbo9_adr_reg <= pmem_odd_turbo9_adr_rst; + pmem_odd_turbo9_ack <= 1'b0; + end else begin + pmem_odd_turbo9_adr_reg <= pmem_odd_turbo9_adr; + pmem_odd_turbo9_ack <= pmem_odd_turbo9_stb; + end + end + */ + + always @* begin + pmem_even_turbo9_adr_reg = pmem_even_turbo9_adr; + pmem_even_turbo9_ack = pmem_even_turbo9_stb; + pmem_even_turbo9_tgd_reg = pmem_even_turbo9_tgd_o; + pmem_even_turbo9_we_reg = pmem_even_turbo9_we; + pmem_odd_turbo9_adr_reg = pmem_odd_turbo9_adr; + pmem_odd_turbo9_ack = pmem_odd_turbo9_stb; + end + + + + // Write Enables (Even Bytes) + always @* begin + // Defaults + dmem_even_ram_we = 1'b0; + port_we = 1'b0; + acia_data_wr_en = 1'b0; + // + // Even Memory Bus Read Data Mux + if (dmem_even_turbo9_adr_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + dmem_even_ram_we = dmem_even_turbo9_we; + end else begin + case (dmem_even_turbo9_adr_full[3:0]) + // + 4'h2: acia_data_wr_en = dmem_even_turbo9_we; + 4'h0: port_we = dmem_even_turbo9_we; + endcase + end + end + + // Write Enables (Odd Bytes) + always @* begin + // Defaults + dmem_odd_ram_we = 1'b0; + // + // Odd Memory Bus Read Data Mux + if (dmem_odd_turbo9_adr_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + dmem_odd_ram_we = dmem_odd_turbo9_we; + end + end + + // RAM (Even bytes) + syncram_dp_8bit + #( + .MEM_ADDR_WIDTH (EVEN_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_even.hex") + ) + I_even_syncram_8bit + ( + .CLK_I (ram_clk), + + .A_WE_I (dmem_even_ram_we), + .A_ADR_I (dmem_even_turbo9_adr[EVEN_MEM_ADDR_WIDTH-1:0]), + .A_DAT_I (dmem_even_turbo9_wr_dat), + .A_DAT_O (dmem_even_ram_rd_dat), + + .B_ADR_I (pmem_even_turbo9_adr[EVEN_MEM_ADDR_WIDTH-1:0]), + .B_DAT_O (pmem_even_ram_rd_dat) + ); + + // RAM (Odd bytes) + syncram_dp_8bit + #( + .MEM_ADDR_WIDTH (ODD_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_odd.hex") + ) + I_odd_syncram_8bit + ( + .CLK_I (ram_clk), + + .A_WE_I (dmem_odd_ram_we), + .A_ADR_I (dmem_odd_turbo9_adr[ODD_MEM_ADDR_WIDTH-1:0]), + .A_DAT_I (dmem_odd_turbo9_wr_dat), + .A_DAT_O (dmem_odd_ram_rd_dat), + + .B_ADR_I (pmem_odd_turbo9_adr[ODD_MEM_ADDR_WIDTH-1:0]), + .B_DAT_O (pmem_odd_ram_rd_dat) + ); + + // Output Port + output_port I_output_port + ( + .CLK_I (CLK_I), + .RST_I (RST_I), + .WE_I (port_we), + .DAT_I (dmem_even_turbo9_wr_dat), + .DAT_O (port_rd_dat), + .PORT_O (OUTPUT_PORT_O) + ); + + // UART + t6551 I_t6551 + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .TX_DATA_I (dmem_even_turbo9_wr_dat ), + .TX_DATA_WR_EN_I (acia_data_wr_en ), + .RXD_PIN_I (RXD_PIN_I ), + .RX_DATA_RD_EN_I (acia_data_rd_en ), + + // Outputs + .TXD_PIN_O (TXD_PIN_O ), + .RX_DATA_O (acia_data_rd_dat ), + .STATUS_DATA_O (acia_status_rd_dat ) + ); + + // Clock Count Timer + clk_counter I_clk_counter + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // Inputs + .PORT_I (OUTPUT_PORT_O ), + .CLK_CNT_DATA_O (clk_cnt_rd_dat ) + ); + + + // Read Data Muxes & Enables (Even Bytes) + always @* begin + // Defaults + dmem_even_turbo9_rd_dat = 8'h00; + acia_data_rd_en = 1'b0; + // + if (dmem_even_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + dmem_even_turbo9_rd_dat = dmem_even_ram_rd_dat; + end else begin + case (dmem_even_turbo9_adr_reg_full[3:0]) + // + 4'h6: dmem_even_turbo9_rd_dat = clk_cnt_rd_dat[15: 8]; + 4'h4: dmem_even_turbo9_rd_dat = clk_cnt_rd_dat[31:24]; + 4'h2: begin + dmem_even_turbo9_rd_dat = acia_data_rd_dat; + acia_data_rd_en = ~dmem_even_turbo9_we_reg; + end + 4'h0: dmem_even_turbo9_rd_dat = port_rd_dat; + default: dmem_even_turbo9_rd_dat = 8'h00; + endcase + end + end + + // Read Data Mux & Enables (Odd Bytes) + always @* begin + // Defaults + dmem_odd_turbo9_rd_dat = 8'h00; + // + if (dmem_odd_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + dmem_odd_turbo9_rd_dat = dmem_odd_ram_rd_dat; + end else begin + case (dmem_odd_turbo9_adr_reg_full[3:0]) + // + 4'h7: dmem_odd_turbo9_rd_dat = clk_cnt_rd_dat[ 7: 0]; + 4'h5: dmem_odd_turbo9_rd_dat = clk_cnt_rd_dat[23:16]; + 4'h3: dmem_odd_turbo9_rd_dat = acia_status_rd_dat; + default: dmem_odd_turbo9_rd_dat = 8'h00; + endcase + end + end + + // Read Program Memory Muxes & Enables (Even Bytes) + always @* begin + // Defaults + pmem_even_turbo9_rd_dat = 8'h00; + // + if (pmem_even_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + pmem_even_turbo9_rd_dat = pmem_even_ram_rd_dat; + end else begin + pmem_even_turbo9_rd_dat = 8'h00; + end + end + + // Read Program Memory Mux & Enables (Odd Bytes) + always @* begin + // Defaults + pmem_odd_turbo9_rd_dat = 8'h00; + // + if (pmem_odd_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + pmem_odd_turbo9_rd_dat = pmem_odd_ram_rd_dat; + end else begin + pmem_odd_turbo9_rd_dat = 8'h00; + end + end + + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/soc_top_r.v b/turbo9team_turbo9/rtl/soc_top_r.v new file mode 100644 index 0000000000000000000000000000000000000000..103ffe590611660f43b42d97662b36c6d61b4f88 --- /dev/null +++ b/turbo9team_turbo9/rtl/soc_top_r.v @@ -0,0 +1,368 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Target independent top level for the Turbo9R +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module soc_top_r +#( + parameter MEM_ADDR_WIDTH = 15 +) +( + // Inputs: Clock & Reset + input RST_I, // Reset. Active high and synchronized to CLK_I + input CLK_I, // Clock + + // Inputs + input RXD_PIN_I, + + // Outputs + output TXD_PIN_O, + output [7:0] OUTPUT_PORT_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +localparam FULL_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH; +localparam EVEN_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH-1; +localparam ODD_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH-1; + +wire [4:0] even_turbo9_tgd_o; +reg [4:0] even_turbo9_tgd_reg; +localparam even_turbo9_tgd_rst = 5'b00000; + +wire [14:0] even_turbo9_adr; +reg [14:0] even_turbo9_adr_reg; +localparam even_turbo9_adr_rst = 15'h0000; + +wire [15:0] even_turbo9_adr_full = {even_turbo9_adr, 1'b0}; +wire [15:0] even_turbo9_adr_reg_full = {even_turbo9_adr_reg, 1'b0}; + +wire [7:0] even_turbo9_wr_dat; +reg [7:0] even_turbo9_rd_dat; + +wire even_turbo9_stb; +reg even_turbo9_ack; +wire even_turbo9_we; +reg even_turbo9_we_reg; +localparam even_turbo9_we_rst = 1'b0; + +wire [14:0] odd_turbo9_adr; +reg [14:0] odd_turbo9_adr_reg; +localparam odd_turbo9_adr_rst = 15'h0000; + +wire [15:0] odd_turbo9_adr_full = {odd_turbo9_adr, 1'b1}; +wire [15:0] odd_turbo9_adr_reg_full = {odd_turbo9_adr_reg, 1'b1}; + +wire [7:0] odd_turbo9_wr_dat; +reg [7:0] odd_turbo9_rd_dat; + +wire odd_turbo9_stb; +reg odd_turbo9_ack; +wire odd_turbo9_we; + +wire [7:0] acia_data_rd_dat; +wire [7:0] acia_status_rd_dat; + +reg acia_data_wr_en; +reg acia_data_rd_en; + +reg even_ram_we; +wire [7:0] even_ram_rd_dat; + +reg odd_ram_we; +wire [7:0] odd_ram_rd_dat; + +reg port_we; +wire [7:0] port_rd_dat; + +wire [31:0] clk_cnt_rd_dat; + +wire ram_clk; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// + + // Turbo9R + turbo9_r + #( + .REGISTER_WB_OUTPUTS (0), // Register Wishbone Ouputs: True=1, False=0 + .QUEUE_SIZE (6) // Fetch Queue Size: 6=Default, 4=Min, 7=Max + ) + I_turbo9_r + ( + // Inputs: Clock & Reset + .RST_I (RST_I), + .CLK_I (CLK_I), + // + // Wishbone Interface (Even bytes) + .EVEN_TGD_I (even_turbo9_tgd_reg ), + .EVEN_TGD_O (even_turbo9_tgd_o ), + // + .EVEN_DAT_I (even_turbo9_rd_dat ), + .EVEN_ACK_I (even_turbo9_ack ), + .EVEN_STALL_I (1'b0 ), + .EVEN_ADR_O (even_turbo9_adr ), + .EVEN_DAT_O (even_turbo9_wr_dat ), + .EVEN_WE_O (even_turbo9_we ), + .EVEN_STB_O (even_turbo9_stb ), + .EVEN_CYC_O ( ), + // + // Wishbone Interface (Odd bytes) + .ODD_DAT_I (odd_turbo9_rd_dat ), + .ODD_ACK_I (odd_turbo9_ack ), + .ODD_STALL_I (1'b0 ), + .ODD_ADR_O (odd_turbo9_adr ), + .ODD_DAT_O (odd_turbo9_wr_dat ), + .ODD_WE_O (odd_turbo9_we ), + .ODD_STB_O (odd_turbo9_stb ), + .ODD_CYC_O ( ) + + ); + + /* + assign ram_clk = CLK_I; + + // Wishbone Pipeline Registers (Even Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + even_turbo9_adr_reg <= even_turbo9_adr_rst; + even_turbo9_ack <= 1'b0; + even_turbo9_tgd_reg <= even_turbo9_tgd_rst; + even_turbo9_we_reg <= even_turbo9_we_rst; + end else begin + even_turbo9_adr_reg <= even_turbo9_adr; + even_turbo9_ack <= even_turbo9_stb; + even_turbo9_tgd_reg <= even_turbo9_tgd_o; + even_turbo9_we_reg <= even_turbo9_we; + end + end + + // Wishbone Pipeline Registers (Odd Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + odd_turbo9_adr_reg <= odd_turbo9_adr_rst; + odd_turbo9_ack <= 1'b0; + end else begin + odd_turbo9_adr_reg <= odd_turbo9_adr; + odd_turbo9_ack <= odd_turbo9_stb; + end + end + */ + + assign ram_clk = ~CLK_I; + + always @* begin + even_turbo9_adr_reg = even_turbo9_adr; + even_turbo9_ack = even_turbo9_stb; + even_turbo9_tgd_reg = even_turbo9_tgd_o; + even_turbo9_we_reg = even_turbo9_we; + odd_turbo9_adr_reg = odd_turbo9_adr; + odd_turbo9_ack = odd_turbo9_stb; + end + + + + // Write Enables (Even Bytes) + always @* begin + // Defaults + even_ram_we = 1'b0; + port_we = 1'b0; + acia_data_wr_en = 1'b0; + // + // Even Memory Bus Read Data Mux + if (even_turbo9_adr_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + even_ram_we = even_turbo9_we; + end else begin + case (even_turbo9_adr_full[3:0]) + // + 4'h2: acia_data_wr_en = even_turbo9_we; + 4'h0: port_we = even_turbo9_we; + endcase + end + end + + // Write Enables (Odd Bytes) + always @* begin + // Defaults + odd_ram_we = 1'b0; + // + // Odd Memory Bus Read Data Mux + if (odd_turbo9_adr_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + odd_ram_we = odd_turbo9_we; + end + end + + // RAM (Even bytes) + syncram_8bit + #( + .MEM_ADDR_WIDTH (EVEN_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_even.hex") + ) + I_even_syncram_8bit + ( + .CLK_I (ram_clk), + .WE_I (even_ram_we), + .ADR_I (even_turbo9_adr[EVEN_MEM_ADDR_WIDTH-1:0]), + .DAT_I (even_turbo9_wr_dat), + .DAT_O (even_ram_rd_dat) + ); + + // RAM (Odd bytes) + syncram_8bit + #( + .MEM_ADDR_WIDTH (ODD_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_odd.hex") + ) + I_odd_syncram_8bit + ( + .CLK_I (ram_clk), + .WE_I (odd_ram_we), + .ADR_I (odd_turbo9_adr[ODD_MEM_ADDR_WIDTH-1:0]), + .DAT_I (odd_turbo9_wr_dat), + .DAT_O (odd_ram_rd_dat) + ); + + // Output Port + output_port I_output_port + ( + .CLK_I (CLK_I), + .RST_I (RST_I), + .WE_I (port_we), + .DAT_I (even_turbo9_wr_dat), + .DAT_O (port_rd_dat), + .PORT_O (OUTPUT_PORT_O) + ); + + // UART + t6551 I_t6551 + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .TX_DATA_I (even_turbo9_wr_dat ), + .TX_DATA_WR_EN_I (acia_data_wr_en ), + .RXD_PIN_I (RXD_PIN_I ), + .RX_DATA_RD_EN_I (acia_data_rd_en ), + + // Outputs + .TXD_PIN_O (TXD_PIN_O ), + .RX_DATA_O (acia_data_rd_dat ), + .STATUS_DATA_O (acia_status_rd_dat ) + ); + + // Clock Count Timer + clk_counter I_clk_counter + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // Inputs + .PORT_I (OUTPUT_PORT_O ), + .CLK_CNT_DATA_O (clk_cnt_rd_dat ) + ); + + + // Read Data Muxes & Enables (Even Bytes) + always @* begin + // Defaults + even_turbo9_rd_dat = 8'h00; + acia_data_rd_en = 1'b0; + // + if (even_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + even_turbo9_rd_dat = even_ram_rd_dat; + end else begin + case (even_turbo9_adr_reg_full[3:0]) + // + 4'h6: even_turbo9_rd_dat = clk_cnt_rd_dat[15: 8]; + 4'h4: even_turbo9_rd_dat = clk_cnt_rd_dat[31:24]; + 4'h2: begin + even_turbo9_rd_dat = acia_data_rd_dat; + acia_data_rd_en = ~even_turbo9_we_reg; + end + 4'h0: even_turbo9_rd_dat = port_rd_dat; + default: even_turbo9_rd_dat = 8'h00; + endcase + end + end + + // Read Data Mux & Enables (Odd Bytes) + always @* begin + // Defaults + odd_turbo9_rd_dat = 8'h00; + // + if (odd_turbo9_adr_reg_full[15:FULL_MEM_ADDR_WIDTH] == {(16-FULL_MEM_ADDR_WIDTH){1'b1}}) begin + odd_turbo9_rd_dat = odd_ram_rd_dat; + end else begin + case (odd_turbo9_adr_reg_full[3:0]) + // + 4'h7: odd_turbo9_rd_dat = clk_cnt_rd_dat[ 7: 0]; + 4'h5: odd_turbo9_rd_dat = clk_cnt_rd_dat[23:16]; + 4'h3: odd_turbo9_rd_dat = acia_status_rd_dat; + default: odd_turbo9_rd_dat = 8'h00; + endcase + end + end + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/soc_top_s.v b/turbo9team_turbo9/rtl/soc_top_s.v new file mode 100644 index 0000000000000000000000000000000000000000..99c6509847dcf039ed1e9dd4d4273cb1fb4e1d23 --- /dev/null +++ b/turbo9team_turbo9/rtl/soc_top_s.v @@ -0,0 +1,304 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Target independent SoC top level for the Turbo9 (8-bit bus) +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module soc_top_s +#( + parameter MEM_ADDR_WIDTH = 15 +) +( + // Inputs: Clock & Reset + input RST_I, // Reset. Active high and synchronized to CLK_I + input CLK_I, // Clock + + // Inputs + input RXD_PIN_I, + + // Outputs + output TXD_PIN_O, + output [7:0] OUTPUT_PORT_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +localparam WORD_MEM_ADDR_WIDTH = MEM_ADDR_WIDTH-1; + +wire [4:0] turbo9_tgd_o; +reg [4:0] turbo9_tgd_reg; +localparam turbo9_tgd_rst = 5'b00000; + +wire [15:1] turbo9_adr; +reg [15:1] turbo9_adr_reg; +localparam turbo9_adr_rst = 15'h0000; + +wire [1:0] turbo9_sel; +reg [1:0] turbo9_sel_reg; +localparam turbo9_sel_rst = 2'b00; + +wire [15:0] turbo9_wr_dat; +reg [15:0] turbo9_rd_dat; + +wire turbo9_stb; +reg turbo9_stb_reg; +localparam turbo9_stb_rst = 1'b0; +wire turbo9_ack = turbo9_stb_reg; +wire turbo9_we; +reg turbo9_we_reg; +localparam turbo9_we_rst = 1'b0; + +wire [7:0] acia_data_rd_dat; +wire [7:0] acia_status_rd_dat; + +reg acia_data_wr_en; +reg acia_data_rd_en; + +reg even_ram_we; +reg odd_ram_we; +wire [15:0] ram_rd_dat; + +reg port_we; +wire [7:0] port_rd_dat; + +wire [31:0] clk_cnt_rd_dat; + +wire ram_clk; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// + + turbo9_s + #( + .REGISTER_WB_OUTPUTS (0), // Register Wishbone Ouputs: True=1, False=0 + .QUEUE_SIZE (7) // Fetch Queue Size: 6=Default, 4=Min, 7=Max + ) + I_turbo9_s + ( + // Inputs: Clock & Reset + .RST_I (RST_I), + .CLK_I (CLK_I), + + // Inputs + .DAT_I (turbo9_rd_dat), + .TGD_I (turbo9_tgd_reg), + .ACK_I (turbo9_ack), + .STALL_I (1'b0), + + // Outputs + .ADR_O (turbo9_adr), + .DAT_O (turbo9_wr_dat), + .SEL_O (turbo9_sel), + .TGD_O (turbo9_tgd_o), + .WE_O (turbo9_we), + .STB_O (turbo9_stb), + .CYC_O () + ); + +/* + assign ram_clk = CLK_I; + + // Wishbone Pipeline Registers (Even Bytes) + always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + turbo9_adr_reg <= turbo9_adr_rst; + turbo9_stb_reg <= turbo9_stb_rst; + turbo9_tgd_reg <= turbo9_tgd_rst; + turbo9_sel_reg <= turbo9_sel_rst; + turbo9_we_reg <= turbo9_we_rst; + end else begin + turbo9_adr_reg <= turbo9_adr; + turbo9_stb_reg <= turbo9_stb; + turbo9_tgd_reg <= turbo9_tgd_o; + turbo9_sel_reg <= turbo9_sel; + turbo9_we_reg <= turbo9_we; + end + end +*/ + + assign ram_clk = ~CLK_I; + + always @* begin + turbo9_adr_reg = turbo9_adr; + turbo9_stb_reg = turbo9_stb; + turbo9_tgd_reg = turbo9_tgd_o; + turbo9_sel_reg = turbo9_sel; + turbo9_we_reg = turbo9_we; + end + + // Write Enables (Even Bytes) + always @* begin + // Defaults + even_ram_we = 1'b0; + odd_ram_we = 1'b0; + port_we = 1'b0; + acia_data_wr_en = 1'b0; + // + // Even Memory Bus Read Data Mux + if (turbo9_adr[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin + even_ram_we = turbo9_we & turbo9_sel[1]; + odd_ram_we = turbo9_we & turbo9_sel[0]; + end else begin + case ({turbo9_adr[3:1],1'b0}) + // + 4'h2: acia_data_wr_en = turbo9_we & turbo9_sel[1]; + 4'h0: port_we = turbo9_we & turbo9_sel[1]; + endcase + end + end + + // RAM (Even bytes) + syncram_8bit + #( + .MEM_ADDR_WIDTH (WORD_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_even.hex") + ) + I_even_syncram_8bit + ( + .CLK_I (ram_clk), + .WE_I (even_ram_we), + .ADR_I (turbo9_adr[MEM_ADDR_WIDTH-1:1]), + .DAT_I (turbo9_wr_dat[15:8]), + .DAT_O (ram_rd_dat[15:8]) + ); + + // RAM (Odd bytes) + syncram_8bit + #( + .MEM_ADDR_WIDTH (WORD_MEM_ADDR_WIDTH), + .MEM_INIT_FILE ("default_odd.hex") + ) + I_odd_syncram_8bit + ( + .CLK_I (ram_clk), + .WE_I (odd_ram_we), + .ADR_I (turbo9_adr[MEM_ADDR_WIDTH-1:1]), + .DAT_I (turbo9_wr_dat[7:0]), + .DAT_O (ram_rd_dat[7:0]) + ); + + + // Output Port + output_port I_output_port + ( + .CLK_I (CLK_I), + .RST_I (RST_I), + .WE_I (port_we), + .DAT_I (turbo9_wr_dat[15:8]), + .DAT_O (port_rd_dat), + .PORT_O (OUTPUT_PORT_O) + ); + + // UART + t6551 I_t6551 + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .TX_DATA_I (turbo9_wr_dat[15:8] ), + .TX_DATA_WR_EN_I (acia_data_wr_en ), + .RXD_PIN_I (RXD_PIN_I ), + .RX_DATA_RD_EN_I (acia_data_rd_en ), + + // Outputs + .TXD_PIN_O (TXD_PIN_O ), + .RX_DATA_O (acia_data_rd_dat ), + .STATUS_DATA_O (acia_status_rd_dat ) + ); + + // Clock Count Timer + clk_counter I_clk_counter + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // Inputs + .PORT_I (OUTPUT_PORT_O ), + .CLK_CNT_DATA_O (clk_cnt_rd_dat ) + ); + + // Read Data Muxes & Enables + always @* begin + // Defaults + turbo9_rd_dat = 16'h0000; + acia_data_rd_en = 1'b0; + // + if (turbo9_adr_reg[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin + turbo9_rd_dat = ram_rd_dat; + end else begin + case ({turbo9_adr_reg[3:1],1'b0}) + // + 4'h6: turbo9_rd_dat = clk_cnt_rd_dat[15: 0]; + 4'h4: turbo9_rd_dat = clk_cnt_rd_dat[31:16]; + 4'h2: begin + turbo9_rd_dat = {acia_data_rd_dat, acia_status_rd_dat}; + acia_data_rd_en = ~turbo9_we_reg & turbo9_sel_reg[1] & turbo9_stb_reg; + end + 4'h0: turbo9_rd_dat = {port_rd_dat, 8'h00}; + default: turbo9_rd_dat = 16'h0000; + endcase + end + end + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/syncram_8bit.v b/turbo9team_turbo9/rtl/syncram_8bit.v new file mode 100644 index 0000000000000000000000000000000000000000..df470d640c004f59b9f89c661613276047326558 --- /dev/null +++ b/turbo9team_turbo9/rtl/syncram_8bit.v @@ -0,0 +1,91 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: 8-bit synchronous RAM +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module syncram_8bit +#( + parameter MEM_ADDR_WIDTH = 12, + parameter MEM_INIT_FILE = "syncram_8bit.hex" +) +( + input CLK_I, + input WE_I, + input [MEM_ADDR_WIDTH-1:0] ADR_I, + input [ 7:0] DAT_I, + output [ 7:0] DAT_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +reg [7:0] ram [0:(2**MEM_ADDR_WIDTH)-1]; +reg [7:0] dat_o_reg; + +initial +begin + $readmemh(MEM_INIT_FILE,ram); +end + +always @(posedge CLK_I) +begin + if (WE_I) begin + ram[ADR_I] <= DAT_I; + dat_o_reg <= DAT_I; //'write first' or transparent mode, less logic in FPGA block rams + end else begin + dat_o_reg <= ram[ADR_I]; + end +end + + +assign DAT_O = dat_o_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + + diff --git a/turbo9team_turbo9/rtl/syncram_dp_8bit.v b/turbo9team_turbo9/rtl/syncram_dp_8bit.v new file mode 100644 index 0000000000000000000000000000000000000000..b98f463d480a379d569298b59d2e79e1db168986 --- /dev/null +++ b/turbo9team_turbo9/rtl/syncram_dp_8bit.v @@ -0,0 +1,99 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Dual port 8bit Synchronous RAM +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module syncram_dp_8bit +#( + parameter MEM_ADDR_WIDTH = 12, + parameter MEM_INIT_FILE = "syncram_8bit.hex" +) +( + input CLK_I, + input A_WE_I, + input [MEM_ADDR_WIDTH-1:0] A_ADR_I, + input [ 7:0] A_DAT_I, + output [ 7:0] A_DAT_O, + + input [MEM_ADDR_WIDTH-1:0] B_ADR_I, + output [ 7:0] B_DAT_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +reg [7:0] ram [0:(2**MEM_ADDR_WIDTH)-1]; +reg [7:0] a_dat_o_reg; +reg [7:0] b_dat_o_reg; + +initial +begin + $readmemh(MEM_INIT_FILE,ram); +end + +always @(posedge CLK_I) +begin + if (A_WE_I) begin + ram[A_ADR_I] <= A_DAT_I; + a_dat_o_reg <= A_DAT_I; //'write first' or transparent mode, less logic in FPGA block rams + end else begin + a_dat_o_reg <= ram[A_ADR_I]; + end + // + b_dat_o_reg <= ram[B_ADR_I]; + // +end + + +assign A_DAT_O = a_dat_o_reg; +assign B_DAT_O = b_dat_o_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + + diff --git a/turbo9team_turbo9/rtl/t6551.v b/turbo9team_turbo9/rtl/t6551.v new file mode 100644 index 0000000000000000000000000000000000000000..e914b2419a153b2610bebc3bf75c4f5b078f8a4a --- /dev/null +++ b/turbo9team_turbo9/rtl/t6551.v @@ -0,0 +1,217 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: 6551 compatible UART +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module t6551 +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input [ 7:0] TX_DATA_I, + input TX_DATA_WR_EN_I, + input RXD_PIN_I, + input RX_DATA_RD_EN_I, + + // Outputs + output TXD_PIN_O, + output [ 7:0] RX_DATA_O, + output [ 7:0] STATUS_DATA_O +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +/* +reg [1:0] frac_cycle_cnt_reg; +localparam frac_cycle_cnt_rst = 2'b00; +*/ + +reg [2:0] frac_cycle_cnt_reg; +localparam frac_cycle_cnt_rst = 3'b000; + +reg [5:0] baud_div_cnt_reg; +localparam baud_div_cnt_rst = 6'h00; + +reg baud_div_en_reg; +localparam baud_div_en_rst = 1'b0; + +wire rx_overrun; +wire rx_framing_error; +wire rx_data_reg_full; +wire tx_data_reg_empty; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// 1.8432MHz CLOCK ENABLE +///////////////////////////////////////////////////////////////////////////// +// +// Create a 1.8432MHz clock enable signal +// ~ Input clock = 100MHz +// ~ 100 / 1.8432 = 54.25347 (ideal divisor) +// +// Close Enough Fractional divisor: +// ~ 54 + (1/4) +// ~ 54 + 0.25 = 54.25 +// +// Over 4 cycles the _average_ is 1.84332MHz (div=54.25) +// +// The UART divides futher +// ~ div by 160 (16x10 bits per character) +// ~ acts as another "sliding window" average +// +// Frequency Error = 0.0064% +// ~ Perfectly acceptable +// +// Baud_div_cnt_reg is 6-bits and counts 53->0 or 54->0 +// +// frac_cycle_cnt_reg is 2-bits and counts 3->0 +// @ [1:0] = 3 initialize baud_div_cnt_reg with 54, (1/4) +// @ else initialize baud_div_cnt_reg with 53, integer base +// +// baud_div_en_reg is the clock enable signal and is registered. +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + baud_div_cnt_reg <= baud_div_cnt_rst; + frac_cycle_cnt_reg <= frac_cycle_cnt_rst; + baud_div_en_reg <= baud_div_en_rst; + end else begin + + if (baud_div_cnt_reg == 6'd0) begin + // + /* + if (frac_cycle_cnt_reg == 2'h0) begin + baud_div_cnt_reg <= 6'd54; // fractional div = 0.25 (1/4) + end else begin + baud_div_cnt_reg <= 6'd53; // integer div = 54.0 + end + */ + if (frac_cycle_cnt_reg == 3'h0) begin + baud_div_cnt_reg <= 6'd27; // fractional div = 0.125 (1/8) + end else begin + baud_div_cnt_reg <= 6'd26; // integer div = 27.0 + end + // + frac_cycle_cnt_reg <= frac_cycle_cnt_reg - 'd1; + // + baud_div_en_reg <= 1'b1; + end else begin + baud_div_cnt_reg <= baud_div_cnt_reg - 6'd1; + baud_div_en_reg <= 1'b0; + end + + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Receive & Transmit +///////////////////////////////////////////////////////////////////////////// +t6551_rx I_t6551_rx +( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .PROG_RST_I (1'b0 ), + .RXD_PIN_I (RXD_PIN_I ), + .BAUD_DIV_EN_I (baud_div_en_reg ), + .RX_DATA_REG_RD_EN_I (RX_DATA_RD_EN_I ), + + // Outputs + .RX_OVERRUN_O (rx_overrun ), + .RX_FRAMING_ERROR_O (rx_framing_error ), + .RX_DATA_REG_FULL_O (rx_data_reg_full ), + .RX_DATA_REG_O (RX_DATA_O ) +); + + +t6551_tx I_t6551_tx +( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Inputs + .BAUD_DIV_EN_I (baud_div_en_reg ), + .TX_DATA_I (TX_DATA_I ), + .TX_DATA_REG_WR_EN_I (TX_DATA_WR_EN_I ), + + // Outputs + .TXD_PIN_O (TXD_PIN_O ), + .TX_DATA_REG_EMPTY_O (tx_data_reg_empty ) +); + + + +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +assign STATUS_DATA_O[7] = 1'b0; // IRQ +assign STATUS_DATA_O[6] = 1'b0; // ~DSR +assign STATUS_DATA_O[5] = 1'b0; // ~DCD +assign STATUS_DATA_O[4] = tx_data_reg_empty; +assign STATUS_DATA_O[3] = rx_data_reg_full; +assign STATUS_DATA_O[2] = rx_overrun; +assign STATUS_DATA_O[1] = rx_framing_error; +assign STATUS_DATA_O[0] = 1'b0; // Parity Error + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/t6551_rx.v b/turbo9team_turbo9/rtl/t6551_rx.v new file mode 100644 index 0000000000000000000000000000000000000000..5156fc8b02fd29fe5f3414e2741746ce756859fa --- /dev/null +++ b/turbo9team_turbo9/rtl/t6551_rx.v @@ -0,0 +1,291 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Receive module for 6551 compatiable UART +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module t6551_rx +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input PROG_RST_I, + input RXD_PIN_I, + input BAUD_DIV_EN_I, + input RX_DATA_REG_RD_EN_I, + + // Outputs + output RX_OVERRUN_O, + output RX_FRAMING_ERROR_O, + output RX_DATA_REG_FULL_O, + output [ 7:0] RX_DATA_REG_O +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +reg rxd_meta_reg; +localparam rxd_meta_rst = 1'b0; + +reg rxd_sync_reg; +localparam rxd_sync_rst = 1'b0; + +reg clk_cnt_load; +reg clk_cnt_half_load; +reg clk_cnt_dec; +wire clk_cnt_zero; +reg [ 3:0] clk_cnt_reg; +localparam clk_cnt_rst = 4'hF; + +reg bit_cnt_load; +reg bit_cnt_dec; +wire bit_cnt_zero; +reg [ 2:0] bit_cnt_reg; +localparam bit_cnt_rst = 3'h0; + +reg rx_shift_en; +reg [ 7:0] rx_shift_reg; +localparam rx_shift_rst = 8'h00; + +reg rx_data_reg_load; +reg rx_data_reg_full_reg; +localparam rx_data_reg_full_rst = 1'b0; + +reg [ 7:0] rx_data_reg; +localparam rx_data_rst = 8'h00; + +reg rx_overrun_reg; +localparam rx_overrun_rst = 1'b0; + +reg rx_framing_error_reg; +localparam rx_framing_error_rst = 1'b0; + +reg [ 1:0] rx_state_nxt; +reg [ 1:0] rx_state_reg; +localparam RX_IDLE = 2'b00; +localparam RX_START_BIT = 2'b01; +localparam RX_SHIFT_IN = 2'b10; +localparam RX_STOP_BIT = 2'b11; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// NEXT STATE LOGIC +///////////////////////////////////////////////////////////////////////////// +// + +assign clk_cnt_zero = (clk_cnt_reg == 4'h0); +assign bit_cnt_zero = (bit_cnt_reg == 3'h0); + +always @* begin + + // Defaults + clk_cnt_load = 1'b0; + clk_cnt_half_load = 1'b0; + clk_cnt_dec = 1'b0; + bit_cnt_load = 1'b0; + bit_cnt_dec = 1'b0; + rx_shift_en = 1'b0; + rx_data_reg_load = 1'b0; + rx_state_nxt = RX_IDLE; + + case (rx_state_reg) + // + RX_IDLE : begin + clk_cnt_half_load = 1'b1; + if (rxd_sync_reg == 1'b0) begin + rx_state_nxt = RX_START_BIT; + end else begin + rx_state_nxt = RX_IDLE; + end + end + // + RX_START_BIT : begin + bit_cnt_load = 1'b1; + if (rxd_sync_reg == 1'b1) begin + rx_state_nxt = RX_IDLE; + end else if (clk_cnt_zero) begin + clk_cnt_load = 1'b1; + rx_state_nxt = RX_SHIFT_IN; + end else begin + clk_cnt_dec = 1'b1; + rx_state_nxt = RX_START_BIT; + end + end + // + RX_SHIFT_IN : begin + if (clk_cnt_zero) begin + clk_cnt_load = 1'b1; + bit_cnt_dec = 1'b1; + rx_shift_en = 1'b1; + if (bit_cnt_zero) begin + rx_state_nxt = RX_STOP_BIT; + end else begin + rx_state_nxt = RX_SHIFT_IN; + end + end else begin + clk_cnt_dec = 1'b1; + rx_state_nxt = RX_SHIFT_IN; + end + end + // + default : begin // RX_STOP_BIT + if (clk_cnt_zero) begin + clk_cnt_half_load = 1'b1; + rx_data_reg_load = 1'b1; + rx_state_nxt = RX_IDLE; + end else begin + clk_cnt_dec = 1'b1; + rx_state_nxt = RX_STOP_BIT; + end + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + //rxd_meta_reg <= rxd_meta_rst; + //rxd_sync_reg <= rxd_sync_rst; + clk_cnt_reg <= clk_cnt_rst; + bit_cnt_reg <= bit_cnt_rst; + rx_shift_reg <= rx_shift_rst; + rx_data_reg_full_reg <= rx_data_reg_full_rst; + rx_data_reg <= rx_data_rst; + rx_overrun_reg <= rx_overrun_rst; + rx_framing_error_reg <= rx_framing_error_rst; + rx_state_reg <= RX_IDLE; + end else begin + + // RXD Synchronizer + rxd_meta_reg <= RXD_PIN_I; + rxd_sync_reg <= rxd_meta_reg; + + + if (BAUD_DIV_EN_I) begin + // + // State Register + rx_state_reg <= rx_state_nxt; + // + // Clock Per Bit Counter + if (clk_cnt_load) begin + clk_cnt_reg <= clk_cnt_rst; + end else if (clk_cnt_half_load) begin + clk_cnt_reg <= {1'b0, clk_cnt_rst[3:1]}; + end else if (clk_cnt_dec) begin + clk_cnt_reg <= clk_cnt_reg - 4'd1; + end + // + // Bit Counter + if (bit_cnt_load) begin + bit_cnt_reg <= 3'd7; + end else if (bit_cnt_dec) begin + bit_cnt_reg <= bit_cnt_reg - 3'd1; + end + // + // Receive Shift Register + if (rx_shift_en) begin + rx_shift_reg <= {rxd_sync_reg, rx_shift_reg[7:1]}; + end + end + + // Receive Data Register + if (BAUD_DIV_EN_I && rx_data_reg_load) begin + if ((~rx_data_reg_full_reg) || RX_DATA_REG_RD_EN_I) begin + rx_data_reg <= rx_shift_reg; + end + end + + // Receive Data Overrun Bit + if (PROG_RST_I) begin + rx_overrun_reg <= rx_overrun_rst; + end else if (BAUD_DIV_EN_I && rx_data_reg_load) begin + rx_overrun_reg <= rx_data_reg_full_reg & ~RX_DATA_REG_RD_EN_I; + end else if (RX_DATA_REG_RD_EN_I) begin + rx_overrun_reg <= 1'b0; + end + + // Receive Data Register Full Bit + // Framing Error Bit + if (BAUD_DIV_EN_I && rx_data_reg_load) begin + rx_data_reg_full_reg <= 1'b1; + rx_framing_error_reg <= ~rxd_sync_reg; // Sample stop bit + end else if (RX_DATA_REG_RD_EN_I) begin + rx_data_reg_full_reg <= 1'b0; + rx_framing_error_reg <= 1'b0; + end + + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +assign RX_OVERRUN_O = rx_overrun_reg; +assign RX_FRAMING_ERROR_O = rx_framing_error_reg; +assign RX_DATA_REG_FULL_O = rx_data_reg_full_reg; +assign RX_DATA_REG_O = rx_data_reg; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/t6551_tx.v b/turbo9team_turbo9/rtl/t6551_tx.v new file mode 100644 index 0000000000000000000000000000000000000000..f76a268a7d1a74ea1355ffe3b0179ddc770b7076 --- /dev/null +++ b/turbo9team_turbo9/rtl/t6551_tx.v @@ -0,0 +1,236 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Transmit section of 6551 compatible UART +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module t6551_tx +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input BAUD_DIV_EN_I, + input [ 7:0] TX_DATA_I, + input TX_DATA_REG_WR_EN_I, + + // Outputs + output TXD_PIN_O, + output TX_DATA_REG_EMPTY_O +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +reg clk_cnt_load; +reg clk_cnt_dec; +wire clk_cnt_zero; +reg [ 3:0] clk_cnt_reg; +localparam clk_cnt_rst = 4'hF; + +reg bit_cnt_load; +reg bit_cnt_dec; +wire bit_cnt_zero; +reg [ 3:0] bit_cnt_reg; +localparam bit_cnt_rst = 4'h0; + +reg tx_shifter_set; +reg tx_shifter_load; +reg tx_shifter_en; +reg [ 9:0] tx_shifter_reg; +localparam tx_shifter_rst = 10'h3FF; + +reg tx_data_reg_load; +reg tx_data_reg_empty_reg; +localparam tx_data_reg_empty_rst = 1'b1; + +reg [ 7:0] tx_data_reg; +localparam tx_data_rst = 8'h00; + +reg tx_state_nxt; +reg tx_state_reg; +localparam TX_IDLE = 1'b0; +localparam TX_SHIFT_OUT = 1'b1; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// NEXT STATE LOGIC +///////////////////////////////////////////////////////////////////////////// +// + +assign clk_cnt_zero = (clk_cnt_reg == 4'h0); +assign bit_cnt_zero = (bit_cnt_reg == 4'h0); + +always @* begin + + // Defaults + clk_cnt_load = 1'b0; + clk_cnt_dec = 1'b0; + bit_cnt_load = 1'b0; + bit_cnt_dec = 1'b0; + tx_shifter_set = 1'b0; + tx_shifter_load = 1'b0; + tx_shifter_en = 1'b0; + tx_data_reg_load = 1'b0; + tx_state_nxt = TX_IDLE; + + case (tx_state_reg) + // + TX_IDLE : begin + clk_cnt_load = 1'b1; + bit_cnt_load = 1'b1; + if (tx_data_reg_empty_reg == 1'b0) begin + tx_shifter_load = 1'b1; + tx_state_nxt = TX_SHIFT_OUT; + end else begin + tx_shifter_set = 1'b1; + tx_state_nxt = TX_IDLE; + end + end + // + default : begin // TX_SHIFT_OUT + if (clk_cnt_zero) begin + clk_cnt_load = 1'b1; + if (bit_cnt_zero) begin + bit_cnt_load = 1'b1; + if (tx_data_reg_empty_reg == 1'b0) begin + tx_shifter_load = 1'b1; + tx_state_nxt = TX_SHIFT_OUT; + end else begin + tx_shifter_set = 1'b1; + tx_state_nxt = TX_IDLE; + end + end else begin + tx_shifter_en = 1'b1; + bit_cnt_dec = 1'b1; + tx_state_nxt = TX_SHIFT_OUT; + end + end else begin + clk_cnt_dec = 1'b1; + tx_state_nxt = TX_SHIFT_OUT; + end + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// REGISTERS +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + clk_cnt_reg <= clk_cnt_rst; + bit_cnt_reg <= bit_cnt_rst; + tx_shifter_reg <= tx_shifter_rst; + tx_data_reg_empty_reg <= tx_data_reg_empty_rst; + tx_data_reg <= tx_data_rst; + tx_state_reg <= TX_IDLE; + end else begin + + if (BAUD_DIV_EN_I) begin + // + // State Register + tx_state_reg <= tx_state_nxt; + // + // Clock Per Bit Counter + if (clk_cnt_load) begin + clk_cnt_reg <= clk_cnt_rst; + end else if (clk_cnt_dec) begin + clk_cnt_reg <= clk_cnt_reg - 4'd1; + end + // + // Bit Counter + if (bit_cnt_load) begin + bit_cnt_reg <= 4'd9; + end else if (bit_cnt_dec) begin + bit_cnt_reg <= bit_cnt_reg - 3'd1; + end + // + // Receive Shift Register + if (tx_shifter_set) begin + tx_shifter_reg <= tx_shifter_rst; + end else if (tx_shifter_load) begin + tx_shifter_reg <= {1'b1, tx_data_reg, 1'b0}; + end else if (tx_shifter_en) begin + tx_shifter_reg <= {1'b1, tx_shifter_reg[9:1]}; + end + end + + // Transmit Data Register + if (TX_DATA_REG_WR_EN_I) begin + tx_data_reg <= TX_DATA_I; + end + if (TX_DATA_REG_WR_EN_I) begin + tx_data_reg_empty_reg <= 1'b0; + end else if (tx_shifter_load && BAUD_DIV_EN_I) begin + tx_data_reg_empty_reg <= 1'b1; + end + + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +assign TXD_PIN_O = tx_shifter_reg[0]; +assign TX_DATA_REG_EMPTY_O = tx_data_reg_empty_reg; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9.v b/turbo9team_turbo9/rtl/turbo9.v new file mode 100644 index 0000000000000000000000000000000000000000..65a3eef1e0f96e6b72262a8a05cbd480277ec8a3 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9.v @@ -0,0 +1,188 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Turbo9 with 8-bit pipelined Wishbone memory bus +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9 +#( + parameter REGISTER_WB_OUTPUTS = 1, // Register Wishbone Ouputs: True=1, False=0 + parameter QUEUE_SIZE = 6 // Fetch Queue Size: 6=Default, 4=Min, 7=Max +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input [7:0] DAT_I, + input [3:0] TGD_I, + input ACK_I, + input STALL_I, + + // Outputs + output [15:0] ADR_O, + output [7:0] DAT_O, + output [3:0] TGD_O, + output WE_O, + output STB_O, + output CYC_O + +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +wire [15:0] dmem_dat_o; +wire [15:0] dmem_dat_i; +wire [15:0] dmem_adr_o; +wire dmem_busy_i; +wire dmem_req_o; +wire dmem_req_width_o; +wire dmem_we_o; +wire dmem_rd_ack_i; +wire dmem_wr_ack_i; +wire dmem_ack_width_i; + +wire [15:0] pmem_dat_i; +wire [15:0] pmem_adr_o; +wire pmem_busy_i; +wire pmem_rd_req_o; +wire pmem_rd_ack_i; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// CPU ARCHITECTURE +///////////////////////////////////////////////////////////////////////////// + + + turbo9_pipeline + #( + .TURBO9_TYPE (0), // Turbo9 Type: 0=Turbo9, 1=Turbo9S, 2=Turbo9R + .QUEUE_SIZE (QUEUE_SIZE) // Fetch Queue Size: 6=Default, 4=Min, 7=Max + ) + I_turbo9_pipeline + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // + // Data Memory Interface + .DMEM_DAT_O (dmem_dat_o ), + .DMEM_DAT_I (dmem_dat_i ), + .DMEM_ADR_O (dmem_adr_o ), + .DMEM_BUSY_I (dmem_busy_i ), + .DMEM_REQ_O (dmem_req_o ), + .DMEM_REQ_WIDTH_O (dmem_req_width_o ), + .DMEM_WE_O (dmem_we_o ), + .DMEM_RD_ACK_I (dmem_rd_ack_i ), + .DMEM_WR_ACK_I (dmem_wr_ack_i ), + .DMEM_ACK_WIDTH_I (dmem_ack_width_i ), + // + // Program Memory Interface + .PMEM_DAT_I (pmem_dat_i ), + .PMEM_ADR_O (pmem_adr_o ), + .PMEM_BUSY_I (pmem_busy_i ), + .PMEM_REQ_WIDTH_O ( ), + .PMEM_RD_REQ_O (pmem_rd_req_o ), + .PMEM_RD_ACK_I (pmem_rd_ack_i ), + .PMEM_ACK_WIDTH_I (WIDTH_8 ) + ); + + turbo9_wishbone_8bit + #( + .REGISTER_WB_OUTPUTS (REGISTER_WB_OUTPUTS) // Register Wishbone Ouputs: True=1, False=0 + ) + I_turbo9_wishbone_8bit + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // + // External Wishbone Interface + .DAT_I (DAT_I ), + .TGD_I (TGD_I ), + .ACK_I (ACK_I ), + .STALL_I (STALL_I ), + .ADR_O (ADR_O ), + .DAT_O (DAT_O ), + .TGD_O (TGD_O ), + .WE_O (WE_O ), + .STB_O (STB_O ), + .CYC_O (CYC_O ), + // + // Data Memory Interface + .DMEM_DAT_I (dmem_dat_o ), + .DMEM_DAT_O (dmem_dat_i ), + .DMEM_ADR_I (dmem_adr_o ), + .DMEM_BUSY_O (dmem_busy_i ), + .DMEM_REQ_I (dmem_req_o ), + .DMEM_REQ_WIDTH_I (dmem_req_width_o ), + .DMEM_WE_I (dmem_we_o ), + .DMEM_RD_ACK_O (dmem_rd_ack_i ), + .DMEM_WR_ACK_O (dmem_wr_ack_i ), + .DMEM_ACK_WIDTH_O (dmem_ack_width_i ), + // + // Program Memory Interface + .PMEM_DAT_O (pmem_dat_i ), + .PMEM_ADR_I (pmem_adr_o ), + .PMEM_BUSY_O (pmem_busy_i ), + .PMEM_RD_REQ_I (pmem_rd_req_o ), + .PMEM_RD_ACK_O (pmem_rd_ack_i ) + ); + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_address_alu.v b/turbo9team_turbo9/rtl/turbo9_address_alu.v new file mode 100644 index 0000000000000000000000000000000000000000..167d6d1bd33513c8b05b06d846929980bb6aba71 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_address_alu.v @@ -0,0 +1,91 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: 16-bit Address ALU +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_address_alu +( + // + // Address ALU Operation + input ADDR_ALU_EA_OP_I, + input ADDR_ALU_Y_OP_I, + // + // Address ALU Data Inputs / Outputs + input [15:0] ADDR_ALU_REG_I, + input [15:0] ADDR_ALU_OFFSET_I, + output [15:0] ADDR_ALU_Y_O, + output [15:0] ADDR_ALU_EA_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// + +//////////////////////////////////////// ADDR_ALU_EA_OP_I / ADDR_ALU_Y_OP_I defines +// +localparam EQU_REG = 1'b0; +localparam EQU_SUM = 1'b1; + +wire [15:0] adder_sum; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +assign adder_sum = ADDR_ALU_REG_I + ADDR_ALU_OFFSET_I; + +assign ADDR_ALU_Y_O = (ADDR_ALU_Y_OP_I == EQU_SUM) ? adder_sum : ADDR_ALU_REG_I; + +assign ADDR_ALU_EA_O = (ADDR_ALU_EA_OP_I == EQU_SUM) ? adder_sum : ADDR_ALU_REG_I; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_ccr.v b/turbo9team_turbo9/rtl/turbo9_ccr.v new file mode 100644 index 0000000000000000000000000000000000000000..b62a7ead43a2d66e72f69ff3218fa5245e10c30f --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_ccr.v @@ -0,0 +1,389 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Condition Code Register +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// + +module turbo9_ccr // Down on the corner, out in the street. +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + input STALL_MICROCYCLE_I, + + // Inputs + input [3:0] CCR_OP_I, + input [3:0] MICRO_SEQ_COND_SEL_I, + input [3:0] BRANCH_SEL_I, + input STACK_DONE_I, + input IDX_INDIRECT_EN_I, + input DATA_WIDTH_I, + + input [4:0] DATA_ALU_FLAGS_I, + input DATA_ALU_SAU_DONE_I, + + input RA_CCR_WR_EN_I, + input [7:0] RA_CCR_WR_DATA_I, + output [7:0] RA_CCR_RD_DATA_O, + + // Outputs + output [4:0] CCR_FLAGS_O, + output reg MICRO_SEQ_COND_O + +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////// CCR_OP_I defines +// +// EFHINZVC +localparam OP_oooooooo = 4'h0; +localparam OP_oooooXoo = 4'h1; +localparam OP_ooooXXXX = 4'h2; +localparam OP_oooooXoX = 4'h3; +localparam OP_ooooXXXo = 4'h4; +localparam OP_ooXoXXXX = 4'h5; +localparam OP_ooooXXoX = 4'h6; +localparam OP_1ooooooo = 4'h7; +localparam OP_o1o1oooo = 4'h8; +localparam OP_XXXXXXXX = 4'h9; + +//////////////////////////////////////// MICRO_SEQ_COND_SEL_I defines +// +localparam NOT_INDIRECT = 4'b0000; +localparam TRUE = 4'b0001; +localparam STACK_DONE = 4'b0010; +localparam STACK_NEXT = 4'b0011; +localparam SAU_NOT_DONE = 4'b0100; +localparam BRANCH_COND = 4'b1000; // One hot decoded + +//////////////////////////////////////// BRANCH_SEL_I defines +// +localparam BRA = 4'h0; +localparam BRN = 4'h1; +localparam BHI = 4'h2; +localparam BLS = 4'h3; +localparam BCC = 4'h4; // BHS +localparam BCS = 4'h5; // BLO +localparam BNE = 4'h6; +localparam BEQ = 4'h7; +localparam BVC = 4'h8; +localparam BVS = 4'h9; +localparam BPL = 4'hA; +localparam BMI = 4'hB; +localparam BGE = 4'hC; +localparam BLT = 4'hD; +localparam BGT = 4'hE; +localparam BLE = 4'hF; + +reg branch_sig; +// +//////////////////////////////////////// + + +//////////////////////////////////////// Internal CCR Signals +// +wire alu_c; // Carry +wire alu_v; // Overflow +wire alu_z; // Zero +wire alu_n; // Negative +wire alu_h; // Half Carry +wire masked_h; // Half Carry masked for 16bit operations + +reg c_reg; // Carry +reg v_reg; // Overflow +reg z_reg; // Zero +reg n_reg; // Negative +reg i_reg; // IRQ Interrupt Mask +reg h_reg; // Half Carry +reg f_reg; // Fast Interrupt Mask +reg e_reg; // Entire State on Stack + +// +//////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////// ALU Flag Input +// +assign alu_h = DATA_ALU_FLAGS_I[4]; +assign alu_n = DATA_ALU_FLAGS_I[3]; +assign alu_z = DATA_ALU_FLAGS_I[2]; +assign alu_v = DATA_ALU_FLAGS_I[1]; +assign alu_c = DATA_ALU_FLAGS_I[0]; +// +assign masked_h = DATA_WIDTH_I ? alu_h : h_reg; // masked for 16bit operations +// +//////////////////////////////////////// + +//////////////////////////////////////// Condition Code Register +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + // c_reg <= alu_c; + // v_reg <= alu_v; + // z_reg <= alu_z; + // n_reg <= alu_n; + i_reg <= 1'b1; + // h_reg <= masked_h; + f_reg <= 1'b1; + e_reg <= 1'b1; + end else begin + if (STALL_MICROCYCLE_I == 1'b0) begin + //unique case (CCR_OP_I) // FIXME optimize logic + case (CCR_OP_I) + OP_oooooooo : begin + // c_reg <= alu_c; + // v_reg <= alu_v; + // z_reg <= alu_z; + // n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_oooooXoo : begin + // c_reg <= alu_c; + // v_reg <= alu_v; + z_reg <= alu_z; + // n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_ooooXXXX : begin + c_reg <= alu_c; + v_reg <= alu_v; + z_reg <= alu_z; + n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_oooooXoX : begin + c_reg <= alu_c; + //v_reg <= alu_v; + z_reg <= alu_z; + //n_reg <= alu_n; + // i_reg <= 1'b0; + //h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_ooooXXXo : begin + // c_reg <= alu_c; + v_reg <= alu_v; + z_reg <= alu_z; + n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_ooXoXXXX : begin + c_reg <= alu_c; + v_reg <= alu_v; + z_reg <= alu_z; + n_reg <= alu_n; + // i_reg <= 1'b0; + h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_ooooXXoX : begin + c_reg <= alu_c; + // v_reg <= alu_v; + z_reg <= alu_z; + n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + // e_reg <= 1'b0; + end + OP_1ooooooo : begin + // c_reg <= alu_c; + // v_reg <= alu_v; + // z_reg <= alu_z; + // n_reg <= alu_n; + // i_reg <= 1'b0; + // h_reg <= masked_h; + // f_reg <= 1'b0; + e_reg <= 1'b1; + end + OP_o1o1oooo : begin + // c_reg <= alu_c; + // v_reg <= alu_v; + // z_reg <= alu_z; + // n_reg <= alu_n; + i_reg <= 1'b1; + // h_reg <= masked_h; + f_reg <= 1'b1; + // e_reg <= 1'b1; + end + OP_XXXXXXXX : begin // FIXME: push this logic into the decode stage + if (RA_CCR_WR_EN_I) begin + c_reg <= RA_CCR_WR_DATA_I[0]; + v_reg <= RA_CCR_WR_DATA_I[1]; + z_reg <= RA_CCR_WR_DATA_I[2]; + n_reg <= RA_CCR_WR_DATA_I[3]; + i_reg <= RA_CCR_WR_DATA_I[4]; + h_reg <= RA_CCR_WR_DATA_I[5]; + f_reg <= RA_CCR_WR_DATA_I[6]; + e_reg <= RA_CCR_WR_DATA_I[7]; + end + end + endcase + end + end +end +// +//////////////////////////////////////// + + +//////////////////////////////////////// Microsquencer Condition Select Logic +// +wire bra_sig = ~(1'b0); +wire brn_sig = (1'b0); +// +wire bhi_sig = ~(c_reg | z_reg); +wire bls_sig = (c_reg | z_reg); +// +wire bcc_sig = ~(c_reg); // bhs_sig +wire bcs_sig = (c_reg); // blo_sig +// +wire bne_sig = ~(z_reg); +wire beq_sig = (z_reg); +// +wire bvc_sig = ~(v_reg); +wire bvs_sig = (v_reg); +// +wire bpl_sig = ~(n_reg); +wire bmi_sig = (n_reg); +// +wire bge_sig = ~(n_reg ^ v_reg); +wire blt_sig = (n_reg ^ v_reg); +// +wire bgt_sig = ~(z_reg | (n_reg ^ v_reg)); +wire ble_sig = (z_reg | (n_reg ^ v_reg)); + +always @* begin + //unique case (BRANCH_SEL_I) // FIXME optimize logic + case (BRANCH_SEL_I) + BRA : branch_sig = bra_sig; + BRN : branch_sig = brn_sig; + BHI : branch_sig = bhi_sig; + BLS : branch_sig = bls_sig; + BCC : branch_sig = bcc_sig; // BHS + BCS : branch_sig = bcs_sig; // BLO + BNE : branch_sig = bne_sig; + BEQ : branch_sig = beq_sig; + BVC : branch_sig = bvc_sig; + BVS : branch_sig = bvs_sig; + BPL : branch_sig = bpl_sig; + BMI : branch_sig = bmi_sig; + BGE : branch_sig = bge_sig; + BLT : branch_sig = blt_sig; + BGT : branch_sig = bgt_sig; + BLE : branch_sig = ble_sig; + endcase +end + +always @* begin // FIXME we could use an XOR to produce inverted conditions + if (MICRO_SEQ_COND_SEL_I[3]) begin + MICRO_SEQ_COND_O = branch_sig; // BRANCH_COND = 4'b1xxx + end else begin + case (MICRO_SEQ_COND_SEL_I[2:0]) + 3'b000 : MICRO_SEQ_COND_O = ~IDX_INDIRECT_EN_I; // NOT_INDIRECT = 3'b000 + 3'b001 : MICRO_SEQ_COND_O = 1'b1; // TRUE = 3'b001 + 3'b010 : MICRO_SEQ_COND_O = STACK_DONE_I; // STACK_DONE = 3'b010 + 3'b011 : MICRO_SEQ_COND_O = ~STACK_DONE_I; // STACK_NEXT = 3'b011 + 3'b100 : MICRO_SEQ_COND_O = DATA_ALU_SAU_DONE_I; // SAU_DONE = 3'b100 + 3'b101 : MICRO_SEQ_COND_O = ~DATA_ALU_SAU_DONE_I; // SAU_NOT_DONE = 3'b101 + default : MICRO_SEQ_COND_O = ~e_reg; // E_CLEAR = 3'b110 + endcase + end +end + +// +//////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +assign RA_CCR_RD_DATA_O[7] = e_reg; +assign RA_CCR_RD_DATA_O[6] = f_reg; +assign RA_CCR_RD_DATA_O[5] = h_reg; +assign RA_CCR_RD_DATA_O[4] = i_reg; +assign RA_CCR_RD_DATA_O[3] = n_reg; +assign RA_CCR_RD_DATA_O[2] = z_reg; +assign RA_CCR_RD_DATA_O[1] = v_reg; +assign RA_CCR_RD_DATA_O[0] = c_reg; + +assign CCR_FLAGS_O[4] = h_reg; +assign CCR_FLAGS_O[3] = n_reg; +assign CCR_FLAGS_O[2] = z_reg; +assign CCR_FLAGS_O[1] = v_reg; +assign CCR_FLAGS_O[0] = c_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_data_alu.v b/turbo9team_turbo9/rtl/turbo9_data_alu.v new file mode 100644 index 0000000000000000000000000000000000000000..77d100a81df44cd55b58ce038382071899e0fc49 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_data_alu.v @@ -0,0 +1,357 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Data ALU with 8/16-bit capability +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_data_alu +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + input STALL_MICROCYCLE_I, + + // Inputs + input [2:0] DATA_ALU_OP_I, + input [1:0] DATA_ALU_COND_SEL_I, + input [15:0] DATA_ALU_A_I, + input [15:0] DATA_ALU_B_I, + input DATA_ALU_WIDTH_I, + input DATA_ALU_SAU_EN_I, + input DATA_ALU_SAU_DEC_I, + input [3:0] DATA_ALU_SAU_OP_I, + input [47:0] DATA_ALU_SAU_ABXY_I, + input [4:0] CCR_FLAGS_I, + + // Outputs + output [15:0] DATA_ALU_Y_O, + output [4:0] DATA_ALU_FLAGS_O, + output DATA_ALU_SAU_DONE_O +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////// DATA_ALU_OP_I defines +// Note this encoding is critical for partial decoding +localparam A_PLUS_B = 3'h0; // 3'b000 +localparam A_PLUS_NOT_B = 3'h1; // 3'b001 +localparam LSHIFT_A = 3'h2; // 3'b010 +localparam RSHIFT_A = 3'h3; // 3'b011 +localparam A_AND_B = 3'h4; // 3'b100 +localparam A_OR_B = 3'h5; // 3'b101 +localparam A_XOR_B = 3'h6; // 3'b110 +localparam SAU = 3'h7; // 3'b111 + +//////////////////////////////////////// DATA_ALU_COND_SEL_I defines +// +localparam ZERO_BIT = 2'b00; +localparam ONE_BIT = 2'b01; +localparam CARRY_BIT = 2'b10; +localparam SIGN_BIT = 2'b11; + +//////////////////////////////////////// DATA_ALU_WIDTH_I defines +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +reg cond; + +wire [15:0] adder_a; +reg [15:0] adder_b; +reg [15:0] adder_c; +wire [15:0] adder_y; + +wire [15:0] lshift_y; +wire [15:0] rshift_y; +wire [15:0] and_y; +wire [15:0] or_y; +wire [15:0] xor_y; + +wire [15:0] sau_y; + +reg [15:0] alu_y; + +wire n_flag_w; + +wire z_flag_hi; +wire z_flag_lo; +wire z_flag_w; + +wire c_flag_add_w8; +wire c_flag_sub_w8; +wire v_flag_add_w8; +wire v_flag_sub_w8; + +wire c_flag_add_w16; +wire c_flag_sub_w16; +wire v_flag_add_w16; +wire v_flag_sub_w16; + +wire c_flag_add_w; +wire c_flag_sub_w; +wire v_flag_add_w; +wire v_flag_sub_w; + +wire [3:0] sau_flags; + +wire h_flag; // Half Carry +reg n_flag; // Negative +reg z_flag; // Zero +reg v_flag; // Overflow +reg c_flag; // Carry + + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + + +//////////////////////////////////////// ALU Condition Select Logic +// +always @* begin + case (DATA_ALU_COND_SEL_I) + ZERO_BIT : cond = 1'b0; + ONE_BIT : cond = 1'b1; + CARRY_BIT : cond = CCR_FLAGS_I[0]; + default : cond = DATA_ALU_A_I[7]; // SIGN_BIT FIXME ALU[7] not optimal (timing) only really need A,B, DMEM_RD + endcase +end +// +//////////////////////////////////////// + + +//////////////////////////////////////// Adder Logic +// +assign adder_a = DATA_ALU_A_I; + +always @* begin + if (DATA_ALU_OP_I[0]) begin // Partial Decode for A_PLUS_NOT_B + adder_b = ~DATA_ALU_B_I; + adder_c = {15'd0, ~cond}; + end else begin// Partial Decode for A_PLUS_B + adder_b = DATA_ALU_B_I; + adder_c = {15'd0, cond}; + end +end + +// Using a synthesis generated adder. Used my own Look ahead carry before, +// but that sometimes ended up being worse performance depending on the +// target standard library or FPGA. The downside of using a synthesis driven +// adder is it makes generating the C and V flags (especially the V) more +// difficult. The H,C,V "bolt-on" logic should work and there are other ways +// to do this (ex. extra bit adder for carry) but for right now this seems +// to work well, but I'll keep an eye on the timing path reports from +// backend tools to ensure this logic doesn't become to worst timing path. +assign adder_y = adder_a + adder_b + adder_c; + +// Half carry logic +assign h_flag = ( DATA_ALU_A_I[ 3] & DATA_ALU_B_I[ 3] ) | + ( DATA_ALU_B_I[ 3] & ~adder_y[ 3]) | + ( DATA_ALU_A_I[ 3] & ~adder_y[ 3]) ; + +// Carry logic +assign c_flag_add_w8 = ( DATA_ALU_A_I[ 7] & DATA_ALU_B_I[ 7] ) | + ( DATA_ALU_B_I[ 7] & ~adder_y[ 7]) | + ( DATA_ALU_A_I[ 7] & ~adder_y[ 7]) ; + +assign c_flag_add_w16 = ( DATA_ALU_A_I[15] & DATA_ALU_B_I[15] ) | + ( DATA_ALU_B_I[15] & ~adder_y[15]) | + ( DATA_ALU_A_I[15] & ~adder_y[15]) ; + +assign c_flag_sub_w8 = (~DATA_ALU_A_I[ 7] & DATA_ALU_B_I[ 7] ) | + ( DATA_ALU_B_I[ 7] & adder_y[ 7]) | + (~DATA_ALU_A_I[ 7] & adder_y[ 7]) ; + +assign c_flag_sub_w16 = (~DATA_ALU_A_I[15] & DATA_ALU_B_I[15] ) | + ( DATA_ALU_B_I[15] & adder_y[15]) | + (~DATA_ALU_A_I[15] & adder_y[15]) ; + +// Overflow logic +assign v_flag_add_w8 = ( DATA_ALU_A_I[ 7] & DATA_ALU_B_I[ 7] & ~adder_y[ 7]) | + (~DATA_ALU_A_I[ 7] & ~DATA_ALU_B_I[ 7] & adder_y[ 7]) ; + +assign v_flag_add_w16 = ( DATA_ALU_A_I[15] & DATA_ALU_B_I[15] & ~adder_y[15]) | + (~DATA_ALU_A_I[15] & ~DATA_ALU_B_I[15] & adder_y[15]) ; + +assign v_flag_sub_w8 = ( DATA_ALU_A_I[ 7] & ~DATA_ALU_B_I[ 7] & ~adder_y[ 7]) | + (~DATA_ALU_A_I[ 7] & DATA_ALU_B_I[ 7] & adder_y[ 7]) ; + +assign v_flag_sub_w16 = ( DATA_ALU_A_I[15] & ~DATA_ALU_B_I[15] & ~adder_y[15]) | + (~DATA_ALU_A_I[15] & DATA_ALU_B_I[15] & adder_y[15]) ; +// +//////////////////////////////////////// + +//////////////////////////////////////// Boolean Logic +// +assign and_y = {8'h00, (DATA_ALU_A_I[7:0] & DATA_ALU_B_I[7:0])}; // INFO: 8bit only +assign or_y = {8'h00, (DATA_ALU_A_I[7:0] | DATA_ALU_B_I[7:0])}; // INFO: 8bit only +assign xor_y = {8'h00, (DATA_ALU_A_I[7:0] ^ DATA_ALU_B_I[7:0])}; // INFO: 8bit only +// +//////////////////////////////////////// + +//////////////////////////////////////// Shifters +// +assign lshift_y = {8'h00, DATA_ALU_A_I[6:0], cond}; // INFO: 8bit only +assign rshift_y = {8'h00, cond, DATA_ALU_A_I[7:1]}; // INFO: 8bit only +// +//////////////////////////////////////// + +//////////////////////////////////////// Sequential Arithmetic Unit +// +turbo9_seq_arithmetic_unit I_turbo9_seq_arithmetic_unit +( + // Inputs: Clock & Reset + .CLK_I (CLK_I ), + .RST_I (RST_I ), + .STALL_MICROCYCLE_I (STALL_MICROCYCLE_I ), + + .SAU_EN_I (DATA_ALU_SAU_EN_I ), + .SAU_DEC_I (DATA_ALU_SAU_DEC_I ), + .SAU_OP_I (DATA_ALU_SAU_OP_I ), + .SAU_ABXY_I (DATA_ALU_SAU_ABXY_I), + + .CCR_FLAGS_I (CCR_FLAGS_I ), + + .SAU_Y_O (sau_y ), + .SAU_DONE_O (DATA_ALU_SAU_DONE_O), + .SAU_FLAGS_O (sau_flags ) +); +// +//////////////////////////////////////// + +//////////////////////////////////////// ALU Operation Output Select +// +// +always @* begin + case (DATA_ALU_OP_I) + LSHIFT_A : alu_y = lshift_y; + RSHIFT_A : alu_y = rshift_y; + A_AND_B : alu_y = and_y; + A_OR_B : alu_y = or_y; + A_XOR_B : alu_y = xor_y; + SAU : alu_y = sau_y; + default : alu_y = adder_y; // A_PLUS_B or A_PLUS_NOT_B + endcase +end +// +//////////////////////////////////////// + +//////////////////////////////////////// Flags Width Select +// +assign n_flag_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? alu_y[7] : alu_y[15]; +// +assign z_flag_hi = (alu_y[15:8] == 8'h00); +assign z_flag_lo = (alu_y[ 7:0] == 8'h00); +assign z_flag_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? z_flag_lo : (z_flag_hi & z_flag_lo); +// +assign v_flag_add_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? v_flag_add_w8 : v_flag_add_w16; +assign v_flag_sub_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? v_flag_sub_w8 : v_flag_sub_w16; +// +assign c_flag_add_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? c_flag_add_w8 : c_flag_add_w16; +assign c_flag_sub_w = (DATA_ALU_WIDTH_I == WIDTH_8) ? c_flag_sub_w8 : c_flag_sub_w16; +// +//////////////////////////////////////// + +//////////////////////////////////////// Flags Operation Output Select +// +always @* begin + case (DATA_ALU_OP_I) + SAU : n_flag = sau_flags[3]; + default : n_flag = n_flag_w; + endcase +end +// +always @* begin + case (DATA_ALU_OP_I) + SAU : z_flag = sau_flags[2]; + default : z_flag = z_flag_w; + endcase +end +// +always @* begin + case (DATA_ALU_OP_I) + A_PLUS_B : v_flag = v_flag_add_w; + A_PLUS_NOT_B : v_flag = v_flag_sub_w; + LSHIFT_A : v_flag = DATA_ALU_A_I[7] ^ DATA_ALU_A_I[6]; + SAU : v_flag = sau_flags[1]; + default : v_flag = 1'b0; + endcase +end +// +always @* begin + case (DATA_ALU_OP_I) + A_PLUS_B : c_flag = c_flag_add_w; + A_PLUS_NOT_B : c_flag = c_flag_sub_w; + LSHIFT_A : c_flag = DATA_ALU_A_I[7]; + RSHIFT_A : c_flag = DATA_ALU_A_I[0]; + SAU : c_flag = sau_flags[0]; + default : c_flag = 1'b0; + endcase +end +// +//////////////////////////////////////// + +//////////////////////////////////////// ALU Outputs +// +assign DATA_ALU_Y_O = alu_y; + +assign DATA_ALU_FLAGS_O[4] = h_flag; +assign DATA_ALU_FLAGS_O[3] = n_flag; +assign DATA_ALU_FLAGS_O[2] = z_flag; +assign DATA_ALU_FLAGS_O[1] = v_flag; +assign DATA_ALU_FLAGS_O[0] = c_flag; +// +//////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_data_mem_ctrl.v b/turbo9team_turbo9/rtl/turbo9_data_mem_ctrl.v new file mode 100644 index 0000000000000000000000000000000000000000..29c5b08d797ab87739c3c9ae5904a0bed6712e45 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_data_mem_ctrl.v @@ -0,0 +1,263 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: The Turbo9 Data Memory Controller for the execute stage +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_data_mem_ctrl +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + input STALL_MICROCYCLE_I, //FIXME using this is not optimal. We want the state machine to start ASAP. + + // Execution Stage Interface + input [1:0] DMEM_OP_I, + output DMEM_OP_READY_O, + output [15:0] DMEM_RD_DATA_REG_O, + output DMEM_RD_DATA_READY_O, + input [15:0] DMEM_DATA_ALU_Y_I, + input [15:0] DMEM_ADDR_ALU_EA_I, + + // Indirect Addressing / 8bit or 16bit Instruction + input DATA_WIDTH_I, + + // Data Memory Interface + output [15:0] DMEM_DAT_O, + input [15:0] DMEM_DAT_I, + output [15:0] DMEM_ADR_O, + input DMEM_BUSY_I, + output DMEM_REQ_O, + output DMEM_REQ_WIDTH_O, + output DMEM_WE_O, + input DMEM_RD_ACK_I, + input DMEM_WR_ACK_I, + input DMEM_ACK_WIDTH_I + +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////// DMEM_OP_I defines +// +// Note this encoding is critical. +// MSB is a "one-hot" +localparam DMEM_OP_IDLE = 2'b00; // EQU $0 +localparam DMEM_OP_RD = 2'b10; // EQU $2 +localparam DMEM_OP_WR = 2'b11; // EQU $3 + +//////////////////////////////////////// DATA_WIDTH_I defines +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +reg [15:0] dmem_dat_o_reg; +reg [15:0] dmem_dat_o_nxt; +localparam dmem_dat_o_rst = 16'h0000; + +reg [15:0] dmem_adr_o_reg; +reg [15:0] dmem_adr_o_nxt; +localparam dmem_adr_o_rst = 16'h0000; + +reg dmem_req_o_reg; +reg dmem_req_o_nxt; +localparam dmem_req_o_rst = 1'b0; + +reg dmem_we_o_reg; +reg dmem_we_o_nxt; +localparam dmem_we_o_rst = 1'b0; + +reg dmem_req_width_o_reg; +reg dmem_req_width_o_nxt; +localparam dmem_req_width_o_rst = WIDTH_8; + +reg dmem_state_reg; +reg dmem_state_nxt; +localparam DMEM_STATE_OP_ACCEPT = 1'b0; +localparam DMEM_STATE_OP_WAIT = 1'b1; +localparam dmem_state_rst = DMEM_STATE_OP_ACCEPT; + +reg dmem_rd_data_ready_reg; +reg dmem_rd_data_ready_nxt; +localparam dmem_rd_data_ready_rst = 1'b0; + +reg [15:0] dmem_rd_data_reg; +reg [15:0] dmem_rd_data_nxt; +localparam dmem_rd_data_rst = 16'h0000; + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// NEXT STATE LOGIC +///////////////////////////////////////////////////////////////////////////// +// + + +always @* begin + + // Default State + dmem_state_nxt = DMEM_STATE_OP_ACCEPT; + + dmem_dat_o_nxt = DMEM_DATA_ALU_Y_I; + dmem_adr_o_nxt = DMEM_ADDR_ALU_EA_I; + dmem_req_o_nxt = 1'b0; + dmem_we_o_nxt = 1'b0; + dmem_req_width_o_nxt = DATA_WIDTH_I; + + // Next State Logic + case (dmem_state_reg) + DMEM_STATE_OP_ACCEPT: begin + // + if (~STALL_MICROCYCLE_I) begin //FIXME Using this stall signal is safe but not optimal!!!! + + dmem_dat_o_nxt = DMEM_DATA_ALU_Y_I; + dmem_adr_o_nxt = DMEM_ADDR_ALU_EA_I; + dmem_req_o_nxt = DMEM_OP_I[1]; + dmem_we_o_nxt = DMEM_OP_I[0]; + dmem_req_width_o_nxt = DATA_WIDTH_I; + + if (DMEM_BUSY_I) begin + dmem_state_nxt = DMEM_STATE_OP_WAIT; + end else begin + dmem_state_nxt = DMEM_STATE_OP_ACCEPT; + end + + end else begin + dmem_state_nxt = DMEM_STATE_OP_ACCEPT; + end + end + // + DMEM_STATE_OP_WAIT: begin + dmem_dat_o_nxt = dmem_dat_o_reg; + dmem_adr_o_nxt = dmem_adr_o_reg; + dmem_req_o_nxt = dmem_req_o_reg; + dmem_we_o_nxt = dmem_we_o_reg; + dmem_req_width_o_nxt = dmem_req_width_o_reg; + + if (DMEM_BUSY_I) begin + dmem_state_nxt = DMEM_STATE_OP_WAIT; + end else begin + dmem_state_nxt = DMEM_STATE_OP_ACCEPT; + end + end + // + endcase +end +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// MEMORY ACCESS TAG FIFO & WISHBONE OUTPUT REGISTERS +///////////////////////////////////////////////////////////////////////////// +// + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + + dmem_dat_o_reg <= dmem_dat_o_rst; + dmem_adr_o_reg <= dmem_adr_o_rst; + dmem_req_o_reg <= dmem_req_o_rst; + dmem_we_o_reg <= dmem_we_o_rst; + dmem_req_width_o_reg <= dmem_req_width_o_rst; + + dmem_state_reg <= dmem_state_rst; + + dmem_rd_data_ready_reg <= dmem_rd_data_ready_rst; + dmem_rd_data_reg <= dmem_rd_data_rst; + + end else begin + + dmem_dat_o_reg <= dmem_dat_o_nxt; + dmem_adr_o_reg <= dmem_adr_o_nxt; + dmem_req_o_reg <= dmem_req_o_nxt; + dmem_we_o_reg <= dmem_we_o_nxt; + dmem_req_width_o_reg <= dmem_req_width_o_nxt; + + dmem_state_reg <= dmem_state_nxt; + + if (DMEM_RD_ACK_I) begin + dmem_rd_data_ready_reg <= 1'b1; + end else if (dmem_req_o_nxt & ~dmem_we_o_nxt) begin + dmem_rd_data_ready_reg <= 1'b0; + end + + if (DMEM_RD_ACK_I) begin + dmem_rd_data_reg <= DMEM_DAT_I; + end + + end +end + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Data Memory Interface +// +assign DMEM_OP_READY_O = ~((dmem_state_reg == DMEM_STATE_OP_WAIT) & DMEM_OP_I[1]); +assign DMEM_RD_DATA_REG_O = dmem_rd_data_reg; +assign DMEM_RD_DATA_READY_O = dmem_rd_data_ready_reg; + +assign DMEM_DAT_O = dmem_dat_o_nxt; +assign DMEM_ADR_O = dmem_adr_o_nxt; +assign DMEM_REQ_O = dmem_req_o_nxt; +assign DMEM_REQ_WIDTH_O = dmem_req_width_o_nxt; +assign DMEM_WE_O = dmem_we_o_nxt; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + + + diff --git a/turbo9team_turbo9/rtl/turbo9_decode_stage.v b/turbo9team_turbo9/rtl/turbo9_decode_stage.v new file mode 100644 index 0000000000000000000000000000000000000000..445fc40407161978e3f79d21cecf26cf33817ef1 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_decode_stage.v @@ -0,0 +1,323 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Turbo9 Decode Stage +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_decode_stage +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + // + // Decode Execute Control Interface + output DEC_EXE_STALL_MICROCYCLE_O, + input DEC_EXE_DMEM_OP_READY_I, + input DEC_EXE_REGISTER_ARRAY_READY_I, + input DEC_EXE_MICRO_SEQ_COND_I, + output DEC_EXE_NEXT_INSTR_ACK_O, + output [15:0] DEC_EXE_NXT_PC_O, + input DEC_EXE_NEW_PC_WR_EN_I, + input [15:0] DEC_EXE_NEW_PC_I, + // + // Micro-Op + output [3:0] DEC_EXE_UOP_DATA_ALU_A_SEL_O, + output [3:0] DEC_EXE_UOP_DATA_ALU_B_SEL_O, + output [3:0] DEC_EXE_UOP_DATA_ALU_WR_SEL_O, + output [3:0] DEC_EXE_UOP_ADDR_ALU_REG_SEL_O, + output [3:0] DEC_EXE_UOP_ADDR_ALU_OFFSET_SEL_O, + output DEC_EXE_UOP_ADDR_ALU_EA_OP_O, + output DEC_EXE_UOP_ADDR_ALU_EA_WR_EN_O, + output DEC_EXE_UOP_ADDR_ALU_Y_OP_O, + output [2:0] DEC_EXE_UOP_DATA_ALU_OP_O, + output [3:0] DEC_EXE_UOP_CCR_OP_O, + output [1:0] DEC_EXE_UOP_DATA_ALU_COND_SEL_O, + output [3:0] DEC_EXE_UOP_MICRO_SEQ_COND_SEL_O, + output [1:0] DEC_EXE_UOP_DMEM_OP_O, + output DEC_EXE_UOP_DATA_WIDTH_O, + output DEC_EXE_UOP_DATA_ALU_SAU_EN_O, + output [3:0] DEC_EXE_UOP_DATA_ALU_SAU_OP_O, + output DEC_EXE_UOP_IDX_INDIRECT_EN_O, + output [3:0] DEC_EXE_UOP_BRANCH_SEL_O, + output [15:0] DEC_EXE_UOP_DATA_O, + output DEC_EXE_UOP_DIRECT_EN_O, + output DEC_EXE_UOP_STACK_DONE_O, + + // Fetch/Decode Interface + output [15:0] FET_DEC_PC_O, + output FET_DEC_LOAD_PC_O, + output FET_DEC_INSTR_RD_EN_O, + output [2:0] FET_DEC_INSTR_LEN_O, + // + input [15:0] FET_DEC_NXT_PC_I, + input [2:0] FET_DEC_REG_QUEUE_LVL_I, + input [7:0] FET_DEC_REG_QUEUE_D3_I, + input [7:0] FET_DEC_REG_QUEUE_D2_I, + input [7:0] FET_DEC_REG_QUEUE_D1_I, + input [7:0] FET_DEC_REG_QUEUE_D0_I, + input FET_DEC_REG_PREBYTE_EN_I +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +wire [2:0] instr_len; +wire instr_len_valid; + +wire microcycle_start; +wire next_instr_req; + +wire stall_microcycle; + +reg next_instr_ack; +reg decode_ready; + +wire [7:0] jump_table_a; +wire [7:0] jump_table_b; +wire [15:0] instr_data; +wire instr_direct_en; +wire instr_inh_en; +wire [3:0] instr_r1_sel; +wire [3:0] instr_r2_sel; +wire [3:0] instr_ar_sel; + +reg fet_dec_load_pc; + +reg page_sel_load; +reg page_sel_clear; +reg [1:0] page_sel_reg; +localparam page_sel_rst = 2'b00; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// DECODE CONTROL LOGIC +///////////////////////////////////////////////////////////////////////////// + +assign instr_len_valid = (FET_DEC_REG_QUEUE_LVL_I >= instr_len); //FIXME optimize this path. Register instr_len! + +assign stall_microcycle = ~(decode_ready & DEC_EXE_DMEM_OP_READY_I & DEC_EXE_REGISTER_ARRAY_READY_I); + +always @* begin + if (next_instr_req) begin + if (DEC_EXE_NEW_PC_WR_EN_I & microcycle_start) begin + // + // Execute state is ready for next instruction but the PC was updated + // (JUMP, BRANCH, etc) + decode_ready = 1'b0; // decode stage not ready + next_instr_ack = 1'b0; + fet_dec_load_pc = 1'b1; // update fetch stage w/ new PC & flush instr queue + page_sel_load = 1'b0; + page_sel_clear = 1'b1; + // + end else if (instr_len_valid) begin + // + // Execute stage ready for next instruction & instruction is decoded + decode_ready = 1'b1; // decode stage ready + next_instr_ack = 1'b1; // update execute stage w/ next PC + // read next instruction from instruction queue + fet_dec_load_pc = 1'b0; + if (FET_DEC_REG_PREBYTE_EN_I && ~page_sel_reg[1]) begin + page_sel_load = 1'b1; // decode prebyte in page_sel_reg + page_sel_clear = 1'b0; + end else begin + page_sel_load = 1'b0; + page_sel_clear = ~stall_microcycle; // clear page_sel for next instr + end + // + end else begin + // + // Execute stage ready for next instruction & instruction is NOT decoded + decode_ready = 1'b0; // decode stage not ready + next_instr_ack = 1'b0; + fet_dec_load_pc = 1'b0; + page_sel_load = 1'b0; + page_sel_clear = 1'b0; + // + end + end else begin + // + // Execute stage NOT ready for next instruction + decode_ready = 1'b1; // no need to stall the execute stage + next_instr_ack = 1'b0; + fet_dec_load_pc = 1'b0; + if (instr_len_valid && FET_DEC_REG_PREBYTE_EN_I && ~page_sel_reg[1]) begin + page_sel_load = 1'b1; // decode prebyte in page_sel_reg + end else begin + page_sel_load = 1'b0; + end + page_sel_clear = 1'b0; + end +end + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + // + page_sel_reg <= page_sel_rst; + // + end else begin + // + if (page_sel_load) begin + page_sel_reg <= {1'b1, FET_DEC_REG_QUEUE_D0_I[0]}; + end else if (page_sel_clear) begin + page_sel_reg <= page_sel_rst; + end + // + end +end + + + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// DECODE BLOCKS +///////////////////////////////////////////////////////////////////////////// +// + +turbo9_instr_format_decode I_turbo9_instr_format_decode +( + // Instruction Queue + .QUEUE_D3_I (FET_DEC_REG_QUEUE_D3_I ), + .QUEUE_D2_I (FET_DEC_REG_QUEUE_D2_I ), + .QUEUE_D1_I (FET_DEC_REG_QUEUE_D1_I ), + .QUEUE_D0_I (FET_DEC_REG_QUEUE_D0_I ), + .PAGE_SEL_I (page_sel_reg ), + + // Instruction Length + .INSTR_LEN_O (instr_len ), + + // Decoded Instruction + .INSTR_DATA_O (instr_data ), + .INSTR_DIRECT_EN_O (instr_direct_en ), + .INSTR_INH_EN_O (instr_inh_en ), + .INSTR_R1_SEL_O (instr_r1_sel ), + .INSTR_R2_SEL_O (instr_r2_sel ), + .INSTR_AR_SEL_O (instr_ar_sel ), + .INSTR_JUMP_TABLE_A_O (jump_table_a ), + .INSTR_JUMP_TABLE_B_O (jump_table_b ) +); + +turbo9_uop_generator I_turbo9_uop_generator +( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + + // Control Interface + .MICROCYCLE_START_O (microcycle_start ), + .NEXT_INSTR_REQ_O (next_instr_req ), + .STALL_MICROCYCLE_I (stall_microcycle ), + .MICRO_SEQ_COND_I (DEC_EXE_MICRO_SEQ_COND_I ), + .NEXT_INSTR_ACK_I (next_instr_ack ), + + // Instruction Queue + //.QUEUE_D2_I (FET_DEC_REG_QUEUE_D2_I ), + .QUEUE_D1_I (FET_DEC_REG_QUEUE_D1_I ), + .QUEUE_D0_I (FET_DEC_REG_QUEUE_D0_I ), + .PAGE_SEL_I (page_sel_reg ), + + // Decoded Instruction + .INSTR_DATA_I (instr_data ), + .INSTR_DIRECT_EN_I (instr_direct_en ), + .INSTR_INH_EN_I (instr_inh_en ), + .INSTR_R1_SEL_I (instr_r1_sel ), + .INSTR_R2_SEL_I (instr_r2_sel ), + .INSTR_AR_SEL_I (instr_ar_sel ), + .INSTR_JUMP_TABLE_A_I (jump_table_a ), + .INSTR_JUMP_TABLE_B_I (jump_table_b ), + + // Micro-Op + .UOP_MICRO_SEQ_OP_O ( ), + .UOP_MICRO_SEQ_BRANCH_ADDR_O ( ), + .UOP_DATA_ALU_A_SEL_O (DEC_EXE_UOP_DATA_ALU_A_SEL_O ), + .UOP_DATA_ALU_B_SEL_O (DEC_EXE_UOP_DATA_ALU_B_SEL_O ), + .UOP_DATA_ALU_WR_SEL_O (DEC_EXE_UOP_DATA_ALU_WR_SEL_O ), + .UOP_ADDR_ALU_REG_SEL_O (DEC_EXE_UOP_ADDR_ALU_REG_SEL_O ), + .UOP_ADDR_ALU_OFFSET_SEL_O (DEC_EXE_UOP_ADDR_ALU_OFFSET_SEL_O), + .UOP_ADDR_ALU_EA_OP_O (DEC_EXE_UOP_ADDR_ALU_EA_OP_O ), + .UOP_ADDR_ALU_EA_WR_EN_O (DEC_EXE_UOP_ADDR_ALU_EA_WR_EN_O ), + .UOP_ADDR_ALU_Y_OP_O (DEC_EXE_UOP_ADDR_ALU_Y_OP_O ), + .UOP_DATA_ALU_OP_O (DEC_EXE_UOP_DATA_ALU_OP_O ), + .UOP_CCR_OP_O (DEC_EXE_UOP_CCR_OP_O ), + .UOP_DATA_ALU_COND_SEL_O (DEC_EXE_UOP_DATA_ALU_COND_SEL_O ), + .UOP_MICRO_SEQ_COND_SEL_O (DEC_EXE_UOP_MICRO_SEQ_COND_SEL_O ), + .UOP_DMEM_OP_O (DEC_EXE_UOP_DMEM_OP_O ), + .UOP_DATA_WIDTH_O (DEC_EXE_UOP_DATA_WIDTH_O ), + .UOP_DATA_ALU_SAU_EN_O (DEC_EXE_UOP_DATA_ALU_SAU_EN_O ), + .UOP_DATA_ALU_SAU_OP_O (DEC_EXE_UOP_DATA_ALU_SAU_OP_O ), + .UOP_IDX_INDIRECT_EN_O (DEC_EXE_UOP_IDX_INDIRECT_EN_O ), + .UOP_BRANCH_SEL_O (DEC_EXE_UOP_BRANCH_SEL_O ), + .UOP_DATA_O (DEC_EXE_UOP_DATA_O ), + .UOP_DIRECT_EN_O (DEC_EXE_UOP_DIRECT_EN_O ), + .UOP_JUMP_TABLE_B_O ( ), + .UOP_STACK_DONE_O (DEC_EXE_UOP_STACK_DONE_O ) +); +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// + +assign DEC_EXE_STALL_MICROCYCLE_O = stall_microcycle; +assign DEC_EXE_NXT_PC_O = FET_DEC_NXT_PC_I; +assign DEC_EXE_NEXT_INSTR_ACK_O = next_instr_ack; + +assign FET_DEC_LOAD_PC_O = fet_dec_load_pc; +assign FET_DEC_PC_O = DEC_EXE_NEW_PC_I; +assign FET_DEC_INSTR_RD_EN_O = (next_instr_ack & ~stall_microcycle) | page_sel_load; +assign FET_DEC_INSTR_LEN_O = instr_len; + +///////////////////////////////////////////////////////////////////////////// + + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_execute_stage.v b/turbo9team_turbo9/rtl/turbo9_execute_stage.v new file mode 100644 index 0000000000000000000000000000000000000000..4ab1d2ce305d69f7d374c5e295e6b5a19b4b868c --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_execute_stage.v @@ -0,0 +1,296 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Turbo9 Execute Stage +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_execute_stage +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Decode Execute Control Interface + input DEC_EXE_STALL_MICROCYCLE_I, + output DEC_EXE_DMEM_OP_READY_O, + output DEC_EXE_REGISTER_ARRAY_READY_O, + output DEC_EXE_MICRO_SEQ_COND_O, + input DEC_EXE_NEXT_INSTR_ACK_I, + input [15:0] DEC_EXE_NXT_PC_I, + output DEC_EXE_NEW_PC_WR_EN_O, + output [15:0] DEC_EXE_NEW_PC_O, + + // Micro-Op + input [3:0] DEC_EXE_UOP_DATA_ALU_A_SEL_I, + input [3:0] DEC_EXE_UOP_DATA_ALU_B_SEL_I, + input [3:0] DEC_EXE_UOP_DATA_ALU_WR_SEL_I, + input [3:0] DEC_EXE_UOP_ADDR_ALU_REG_SEL_I, + input [3:0] DEC_EXE_UOP_ADDR_ALU_OFFSET_SEL_I, + input DEC_EXE_UOP_ADDR_ALU_EA_WR_EN_I, + input DEC_EXE_UOP_ADDR_ALU_Y_OP_I, + input DEC_EXE_UOP_ADDR_ALU_EA_OP_I, + input [2:0] DEC_EXE_UOP_DATA_ALU_OP_I, + input [3:0] DEC_EXE_UOP_CCR_OP_I, + input [1:0] DEC_EXE_UOP_DATA_ALU_COND_SEL_I, + input [3:0] DEC_EXE_UOP_MICRO_SEQ_COND_SEL_I, + input [1:0] DEC_EXE_UOP_DMEM_OP_I, + input [15:0] DEC_EXE_UOP_DATA_I, + input DEC_EXE_UOP_DIRECT_EN_I, + input DEC_EXE_UOP_DATA_WIDTH_I, + input DEC_EXE_UOP_DATA_ALU_SAU_EN_I, + input [3:0] DEC_EXE_UOP_DATA_ALU_SAU_OP_I, + input DEC_EXE_UOP_IDX_INDIRECT_EN_I, + input [3:0] DEC_EXE_UOP_BRANCH_SEL_I, + input DEC_EXE_UOP_STACK_DONE_I, + + // Data Memory Interface + output [15:0] DMEM_DAT_O, + input [15:0] DMEM_DAT_I, + output [15:0] DMEM_ADR_O, + input DMEM_BUSY_I, + output DMEM_REQ_O, + output DMEM_REQ_WIDTH_O, + output DMEM_WE_O, + input DMEM_RD_ACK_I, + input DMEM_WR_ACK_I, + input DMEM_ACK_WIDTH_I +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +// Register Array Control Vectors +wire ra_ccr_wr_en; +wire [7:0] ra_ccr_wr_data; +wire [7:0] ra_ccr_rd_data; + +wire [15:0] data_alu_a; +wire [15:0] data_alu_b; +wire [15:0] data_alu_y; +wire data_alu_cond; +wire [4:0] data_alu_flags; +wire data_alu_sau_done; +wire [47:0] data_alu_sau_abxy; +wire [4:0] ccr_flags; + +// Address ALU Data Inputs / Outputs +wire [15:0] addr_alu_reg; +wire [15:0] addr_alu_y; +wire [15:0] addr_alu_ea; +wire [15:0] addr_alu_offset; + +wire dmem_rd_data_ready; +wire [15:0] dmem_rd_data_reg; + + + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////// Register Array + turbo9_register_array I_turbo9_register_array + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + .STALL_MICROCYCLE_I (DEC_EXE_STALL_MICROCYCLE_I ), + .REGISTER_ARRAY_READY_O (DEC_EXE_REGISTER_ARRAY_READY_O ), + // + // PC Interface to Fetch & Decode + .NXT_PC_WR_EN_I (DEC_EXE_NEXT_INSTR_ACK_I ), + .NXT_PC_I (DEC_EXE_NXT_PC_I ), + .NEW_PC_WR_EN_O (DEC_EXE_NEW_PC_WR_EN_O ), + .NEW_PC_O (DEC_EXE_NEW_PC_O ), + // + // Data ALU + .DATA_ALU_A_SEL_I (DEC_EXE_UOP_DATA_ALU_A_SEL_I ), + .DATA_ALU_B_SEL_I (DEC_EXE_UOP_DATA_ALU_B_SEL_I ), + .DATA_ALU_WR_SEL_I (DEC_EXE_UOP_DATA_ALU_WR_SEL_I ), + .DATA_ALU_A_O (data_alu_a ), + .DATA_ALU_B_O (data_alu_b ), + .DATA_ALU_Y_I (data_alu_y ), + .DATA_ALU_SAU_ABXY_O (data_alu_sau_abxy ), + // + // Register Array ALU Selects + .ADDR_ALU_REG_SEL_I (DEC_EXE_UOP_ADDR_ALU_REG_SEL_I ), + .ADDR_ALU_OFFSET_SEL_I (DEC_EXE_UOP_ADDR_ALU_OFFSET_SEL_I ), + .ADDR_ALU_EA_WR_EN_I (DEC_EXE_UOP_ADDR_ALU_EA_WR_EN_I ), + // + // Address ALU Data Inputs / Outputs + .ADDR_ALU_REG_O (addr_alu_reg ), + .ADDR_ALU_OFFSET_O (addr_alu_offset ), + .ADDR_ALU_Y_I (addr_alu_y ), + .ADDR_ALU_EA_I (addr_alu_ea ), + // + // Other Registers + .DMEM_RD_DATA_READY_I (dmem_rd_data_ready ), + .DMEM_RD_DATA_REG_I (dmem_rd_data_reg ), + .INSTR_DATA_I (DEC_EXE_UOP_DATA_I ), + .INSTR_DIRECT_EN_I (DEC_EXE_UOP_DIRECT_EN_I ), + // + // CCR to Register Array + .RA_CCR_WR_EN_O (ra_ccr_wr_en ), + .RA_CCR_WR_DATA_O (ra_ccr_wr_data ), + .RA_CCR_RD_DATA_I (ra_ccr_rd_data ) + ); + + //////////////////////////////////////// Address ALU + turbo9_address_alu I_turbo9_address_alu + ( + // + // Address ALU Operation + .ADDR_ALU_EA_OP_I (DEC_EXE_UOP_ADDR_ALU_EA_OP_I ), + .ADDR_ALU_Y_OP_I (DEC_EXE_UOP_ADDR_ALU_Y_OP_I ), + // + // Address ALU Data Inputs / Outputs + .ADDR_ALU_REG_I (addr_alu_reg ), + .ADDR_ALU_OFFSET_I (addr_alu_offset ), + .ADDR_ALU_Y_O (addr_alu_y ), + .ADDR_ALU_EA_O (addr_alu_ea ) + ); + + //////////////////////////////////////// Data ALU + turbo9_data_alu I_turbo9_data_alu + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + .STALL_MICROCYCLE_I (DEC_EXE_STALL_MICROCYCLE_I ), + // + // Inputs + .DATA_ALU_OP_I (DEC_EXE_UOP_DATA_ALU_OP_I ), + .DATA_ALU_COND_SEL_I (DEC_EXE_UOP_DATA_ALU_COND_SEL_I ), + .DATA_ALU_A_I (data_alu_a ), + .DATA_ALU_B_I (data_alu_b ), + .DATA_ALU_WIDTH_I (DEC_EXE_UOP_DATA_WIDTH_I ), + .DATA_ALU_SAU_EN_I (DEC_EXE_UOP_DATA_ALU_SAU_EN_I ), + .DATA_ALU_SAU_DEC_I (DEC_EXE_UOP_DMEM_OP_I[0] ), + .DATA_ALU_SAU_OP_I (DEC_EXE_UOP_DATA_ALU_SAU_OP_I ), + .DATA_ALU_SAU_ABXY_I (data_alu_sau_abxy ), + .CCR_FLAGS_I (ccr_flags ), + // + // Outputs + .DATA_ALU_Y_O (data_alu_y ), + .DATA_ALU_FLAGS_O (data_alu_flags ), + .DATA_ALU_SAU_DONE_O (data_alu_sau_done ) + ); + + //////////////////////////////////////// Condition Code Register + turbo9_ccr I_turbo9_ccr + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + .STALL_MICROCYCLE_I (DEC_EXE_STALL_MICROCYCLE_I ), + // + // Inputs + .CCR_OP_I (DEC_EXE_UOP_CCR_OP_I ), + .MICRO_SEQ_COND_SEL_I (DEC_EXE_UOP_MICRO_SEQ_COND_SEL_I ), + .BRANCH_SEL_I (DEC_EXE_UOP_BRANCH_SEL_I ), + .STACK_DONE_I (DEC_EXE_UOP_STACK_DONE_I ), + .IDX_INDIRECT_EN_I (DEC_EXE_UOP_IDX_INDIRECT_EN_I ), + .DATA_WIDTH_I (DEC_EXE_UOP_DATA_WIDTH_I ), + .DATA_ALU_FLAGS_I (data_alu_flags ), + .DATA_ALU_SAU_DONE_I (data_alu_sau_done ), + // + // Register Array + .RA_CCR_WR_EN_I (ra_ccr_wr_en ), + .RA_CCR_WR_DATA_I (ra_ccr_wr_data ), + .RA_CCR_RD_DATA_O (ra_ccr_rd_data ), + // + // Outputs + .CCR_FLAGS_O (ccr_flags ), + .MICRO_SEQ_COND_O (DEC_EXE_MICRO_SEQ_COND_O ) + ); + + //////////////////////////////////////// Data Memory Controller + turbo9_data_mem_ctrl I_turbo9_data_mem_ctrl + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + .STALL_MICROCYCLE_I (DEC_EXE_STALL_MICROCYCLE_I ), //FIXME Using this stall signal is safe but could be optimized + // + // Execution Stage Interface + .DMEM_OP_I (DEC_EXE_UOP_DMEM_OP_I ), + .DMEM_OP_READY_O (DEC_EXE_DMEM_OP_READY_O ), + .DMEM_RD_DATA_REG_O (dmem_rd_data_reg ), + .DMEM_RD_DATA_READY_O (dmem_rd_data_ready ), + .DMEM_DATA_ALU_Y_I (data_alu_y ), + .DMEM_ADDR_ALU_EA_I (addr_alu_ea ), + // + // 8bit or 16bit Data Width + .DATA_WIDTH_I (DEC_EXE_UOP_DATA_WIDTH_I ), + // + // Data Memory Interface + .DMEM_DAT_O (DMEM_DAT_O ), + .DMEM_DAT_I (DMEM_DAT_I ), + .DMEM_ADR_O (DMEM_ADR_O ), + .DMEM_BUSY_I (DMEM_BUSY_I ), + .DMEM_REQ_O (DMEM_REQ_O ), + .DMEM_REQ_WIDTH_O (DMEM_REQ_WIDTH_O ), + .DMEM_WE_O (DMEM_WE_O ), + .DMEM_RD_ACK_I (DMEM_RD_ACK_I ), + .DMEM_WR_ACK_I (DMEM_WR_ACK_I ), + .DMEM_ACK_WIDTH_I (DMEM_ACK_WIDTH_I ) + ); + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUPUTS +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_fetch_queue.v b/turbo9team_turbo9/rtl/turbo9_fetch_queue.v new file mode 100644 index 0000000000000000000000000000000000000000..5c35b8a2ba1587ede8c72bdef4377e839d74f9d5 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_fetch_queue.v @@ -0,0 +1,333 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Fetch Queue (8-bit by 4to7 shifting FIFO) +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_fetch_queue +#( + parameter TURBO9_TYPE = 0, // Turbo9 Type: 0=Turbo9, 1=Turbo9S, 2=Turbo9R + parameter QUEUE_SIZE = 6 // Fetch Queue Size: 6=Default, 4=Min, 7=Max +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + input [2:0] QUEUE_RD_LEN_I, + input QUEUE_FLUSH_I, + input QUEUE_WR_EN_I, + + input QUEUE_WIDTH_I, + input [15:0] QUEUE_DAT_I, + + output [2:0] QUEUE_LEVEL_O, + output [2:0] QUEUE_REJECT_LEN_O, + // + output [7:0] QUEUE_DATA_3_O, + output [7:0] QUEUE_DATA_2_O, + output [7:0] QUEUE_DATA_1_O, + output [7:0] QUEUE_DATA_0_O, + output PREBYTE_EN_O + // +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////// WIDTH_I defines +// + +localparam CLOG2_SIZE = 3; // Solve: 2^CLOG2_SIZE >= QUEUE_SIZE (keep it Verilog2001!) + +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +wire [(CLOG2_SIZE-1):0] size_const = QUEUE_SIZE; +wire [(CLOG2_SIZE-1):0] size_m1_const = QUEUE_SIZE-1; + + +wire [(QUEUE_SIZE-1):0] queue_wr_en; + +wire [(CLOG2_SIZE-1):0] queue_wr_ptr; + +reg [(CLOG2_SIZE-1):0] queue_reject_len; + +wire [(CLOG2_SIZE-1):0] queue_level_term; +wire [(CLOG2_SIZE-1):0] queue_level_inc; +reg [(CLOG2_SIZE-1):0] queue_level_reg; +wire [(CLOG2_SIZE-1):0] queue_level_nxt; +localparam queue_level_rst = 'd0; + +reg prebyte_en_reg; +localparam prebyte_en_rst = 1'b0; + +reg [7:0] queue_data_reg [(QUEUE_SIZE-1):0]; +wire [7:0] queue_data_nxt [(QUEUE_SIZE-1):0]; +localparam queue_data_rst = 'd0; + +wire [7:0] queue_data_shift4 [(QUEUE_SIZE-1):0]; +wire [7:0] queue_data_shift2 [(QUEUE_SIZE-1):0]; +wire [7:0] queue_data_shift1 [(QUEUE_SIZE-1):0]; +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// QUEUE LOGIC +///////////////////////////////////////////////////////////////////////////// + + + +/////////////////////////////////// Pointer & Level Calculation +// +assign queue_level_term = (QUEUE_WIDTH_I == WIDTH_16) ? 'd2 : 'd1; + +// +assign queue_level_inc = (QUEUE_WR_EN_I) ? queue_level_term : 'd0; +assign queue_wr_ptr = QUEUE_FLUSH_I ? 'd0 : queue_level_reg - QUEUE_RD_LEN_I; +assign queue_level_nxt = queue_wr_ptr + queue_level_inc - queue_reject_len; + + + +/////////////////////////////////// Reject Calculation +// +always @* begin + if ((QUEUE_WIDTH_I==WIDTH_16) && (queue_wr_ptr==size_const ) && QUEUE_WR_EN_I) + queue_reject_len = 'd2; + else if ((QUEUE_WIDTH_I==WIDTH_16) && (queue_wr_ptr==size_m1_const) && QUEUE_WR_EN_I) + queue_reject_len = 'd1; + else if ((QUEUE_WIDTH_I==WIDTH_8 ) && (queue_wr_ptr==size_const ) && QUEUE_WR_EN_I) + queue_reject_len = 'd1; + else + queue_reject_len = 'd0; +end + + + +/////////////////////////////////// Write Enables +// +genvar i; +generate + // QUEUE_SIZE = 7 example: + // assign queue_wr_en[0] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd0)); + // assign queue_wr_en[1] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd1)); + // assign queue_wr_en[2] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd2)); + // assign queue_wr_en[3] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd3)); + // assign queue_wr_en[4] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd4)); + // assign queue_wr_en[5] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd5)); + // assign queue_wr_en[6] = (QUEUE_WR_EN_I & (queue_wr_ptr == 'd6)); + for (i=0; i 4) begin + for (i=0; i bit0 +PULS 'h35 stk_postbyte // pull bit0 -> bit7 +PSHU 'h36 stk_postbyte // push bit7 -> bit0 +PULU 'h37 stk_postbyte // pull bit0 -> bit7 + +BSR 'h8D 8'h80 // push, PC +JSR (dir) 'h9D 8'h80 // push, PC +JSR (idx) 'hAD 8'h80 // push, PC +JSR (ext) 'hBD 8'h80 // push, PC +LBSR 'h17 8'h80 // push, PC +RTS 'h39 8'h80 // pull, PC +RTI 'h3B if (cc.e) 8'hFF else 8'h80 // pull, must wait for E from previous instruction +CWAI 'h3C 8'hFF // push, QUEUE_D1 anded with CC, E always set +SWI 'h3F 8'hFF // Set E, push all regs, set I & F +SWI2 'h103F 8'hFF // Set E, push all regs +SWI3 'h113F 8'hFF // Set E, push all regs +RESET '3E + +/////////////////// Partial Decoding for postbyte +00 0000 0000 +33 0011 0011 + 00?? 00?? Page2 or Page3 SWI2,SWI3 (8'hFF) + +04 0000 0100 +17 0001 0111 + 000? 01?? LBSR (8'h80) + +24 0010 0100 +37 0011 0111 + 001? 01?? PSHS,PULS,PSHU,PULU (stk_postbyte) + +08 0000 1000 +3B 0011 1011 + 00?? 10?? RTS,RTI (8'h80) + +0C 0000 1100 +1F 0001 1111 + 000? 11?? EXG,TFR (stk_postbyte) + +2C 0010 1100 +3F 0011 1111 + 001? 11?? CWAI,SWI (8'hFF) + +40 0100 0000 +FF 1111 1111 + ?1?? ???? BSR,JSR (8'h80) + +06 0000 0110 +FF 1111 1111 + +0F 0000 1111 +F6 1111 0110 + ???? ?11? U Stack pointer + + X Y U S ++X +Y +U +S +-X -Y -U -S + X Y U S + + +*/ + +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUPUTS +///////////////////////////////////////////////////////////////////////////// +// + +assign IDX_INDIRECT_EN_O = idx_ind_en; +assign STACK_DONE_O = stack_done; + +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_register_array.v b/turbo9team_turbo9/rtl/turbo9_register_array.v new file mode 100644 index 0000000000000000000000000000000000000000..5d369c3a279697f035c3d786b0e939e28cfa1350 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_register_array.v @@ -0,0 +1,392 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Register file for the Turbo9 Execute Stage +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_register_array +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + input STALL_MICROCYCLE_I, + output REGISTER_ARRAY_READY_O, + + // PC Interface to Fetch & Decode + input NXT_PC_WR_EN_I, + input [15:0] NXT_PC_I, + output NEW_PC_WR_EN_O, + output [15:0] NEW_PC_O, + + // Data ALU + input [3:0] DATA_ALU_A_SEL_I, + input [3:0] DATA_ALU_B_SEL_I, + input [3:0] DATA_ALU_WR_SEL_I, + output reg [15:0] DATA_ALU_A_O, + output reg [15:0] DATA_ALU_B_O, + input [15:0] DATA_ALU_Y_I, + output [47:0] DATA_ALU_SAU_ABXY_O, + + // Register Array ALU Selects + input [3:0] ADDR_ALU_REG_SEL_I, + input [3:0] ADDR_ALU_OFFSET_SEL_I, + input ADDR_ALU_EA_WR_EN_I, + + // Address ALU Data Inputs / Outputs + output reg [15:0] ADDR_ALU_REG_O, + output reg [15:0] ADDR_ALU_OFFSET_O, + input [15:0] ADDR_ALU_Y_I, + input [15:0] ADDR_ALU_EA_I, + + input DMEM_RD_DATA_READY_I, + input [15:0] DMEM_RD_DATA_REG_I, + input [15:0] INSTR_DATA_I, + input INSTR_DIRECT_EN_I, + // + // CCR to Register Array + output RA_CCR_WR_EN_O, + output [7:0] RA_CCR_WR_DATA_O, + input [7:0] RA_CCR_RD_DATA_I +); + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +// Register Select Defines +localparam ZERO = 4'b1111; +localparam IDATA = 4'b1110; +localparam DMEM_RD = 4'b1101; +localparam EA = 4'b1100; +localparam DPR = 4'b1011; +localparam CCR = 4'b1010; +localparam B = 4'b1001; +localparam A = 4'b1000; +localparam SEXB = 4'b0111; +//localparam = 4'b0110; +localparam PC = 4'b0101; +localparam S = 4'b0100; +localparam U = 4'b0011; +localparam Y = 4'b0010; +localparam X = 4'b0001; +localparam D = 4'b0000; + + +// Index Offset Select Decoding (matches postbyte[3:0]) +localparam ADDR_OFFSET_SEL_POS1 = 4'b0000; +localparam ADDR_OFFSET_SEL_POS2 = 4'b0001; +localparam ADDR_OFFSET_SEL_NEG1 = 4'b0010; +localparam ADDR_OFFSET_SEL_NEG2 = 4'b0011; +localparam ADDR_OFFSET_SEL_ZERO = 4'b0100; +localparam ADDR_OFFSET_SEL_B = 4'b0101; +localparam ADDR_OFFSET_SEL_A = 4'b0110; +localparam ADDR_OFFSET_SEL_D = 4'b0111; +localparam ADDR_OFFSET_SEL_IDATA = 4'b1000; + + +reg [7:0] a_reg; +localparam a_rst = 8'h00; + +reg [7:0] b_reg; +localparam b_rst = 8'h00; + +reg [15:0] x_reg; +localparam x_rst = 16'h0000; + +reg [15:0] y_reg; +localparam y_rst = 16'h0000; + +reg [15:0] u_reg; +localparam u_rst = 16'h0000; + +reg [15:0] s_reg; +localparam s_rst = 16'h0000; + +reg [15:0] pc_reg; +localparam pc_rst = 16'h0000; + +reg [7:0] dpr_reg; +localparam dpr_rst = 8'h00; + +reg [15:0] ea_reg; +localparam ea_rst = 16'h0000; + +reg new_pc_wr_en_reg; +localparam new_pc_wr_en_rst = 1'b0; + +wire [15:0] zero_u16 = 16'h0000; +wire [15:0] pos1_u16 = 16'h0001; +wire [15:0] pos2_u16 = 16'h0002; +wire [15:0] neg1_s16 = 16'hFFFF; +wire [15:0] neg2_s16 = 16'hFFFE; +localparam REG_DONT_CARE = 16'hxxxx; + +wire [15:0] a_reg_u16 = {8'h00, a_reg}; +wire [15:0] a_reg_s16 = {{8{a_reg[7]}}, a_reg}; +// +wire [15:0] b_reg_u16 = {8'h00, b_reg}; +wire [15:0] b_reg_s16 = {{8{b_reg[7]}}, b_reg}; +// +wire [15:0] d_reg = {a_reg, b_reg}; +// +wire [15:0] dpr_reg_u16 = {8'h00, dpr_reg}; +// +wire [15:0] instr_data = (INSTR_DIRECT_EN_I) ? {dpr_reg, INSTR_DATA_I[7:0]} : + INSTR_DATA_I; + +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + a_reg <= a_rst; + b_reg <= b_rst; + x_reg <= x_rst; + y_reg <= y_rst; + u_reg <= u_rst; + s_reg <= s_rst; + pc_reg <= pc_rst; + dpr_reg <= dpr_rst; + ea_reg <= ea_rst; + new_pc_wr_en_reg <= new_pc_wr_en_rst; + end else begin + + if (~STALL_MICROCYCLE_I) begin + // + // A & D Register + if (DATA_ALU_WR_SEL_I == A) a_reg <= DATA_ALU_Y_I[ 7:0]; + else if (DATA_ALU_WR_SEL_I == D) a_reg <= DATA_ALU_Y_I[15:8]; + //else if (ADDR_ALU_REG_SEL_I == A) a_reg <= ADDR_ALU_Y_I[ 7:0]; + //else if (ADDR_ALU_REG_SEL_I == D) a_reg <= ADDR_ALU_Y_I[15:8]; + else a_reg <= a_reg; + // + // B & D Register + if (DATA_ALU_WR_SEL_I == B) b_reg <= DATA_ALU_Y_I[ 7:0]; + else if (DATA_ALU_WR_SEL_I == D) b_reg <= DATA_ALU_Y_I[ 7:0]; + //else if (ADDR_ALU_REG_SEL_I == B) b_reg <= ADDR_ALU_Y_I[ 7:0]; + //else if (ADDR_ALU_REG_SEL_I == D) b_reg <= ADDR_ALU_Y_I[ 7:0]; + else b_reg <= b_reg; + // + // X Register + if (DATA_ALU_WR_SEL_I == X) x_reg <= DATA_ALU_Y_I; + else if (ADDR_ALU_REG_SEL_I == X) x_reg <= ADDR_ALU_Y_I; + else x_reg <= x_reg; + // + // Y Register + if (DATA_ALU_WR_SEL_I == Y) y_reg <= DATA_ALU_Y_I; + else if (ADDR_ALU_REG_SEL_I == Y) y_reg <= ADDR_ALU_Y_I; + else y_reg <= y_reg; + // + // U Register + if (DATA_ALU_WR_SEL_I == U) u_reg <= DATA_ALU_Y_I; + else if (ADDR_ALU_REG_SEL_I == U) u_reg <= ADDR_ALU_Y_I; + else u_reg <= u_reg; + // + // S Register + if (DATA_ALU_WR_SEL_I == S) s_reg <= DATA_ALU_Y_I; + else if (ADDR_ALU_REG_SEL_I == S) s_reg <= ADDR_ALU_Y_I; + else s_reg <= s_reg; + // + // PC Register + if (NXT_PC_WR_EN_I) begin + pc_reg <= NXT_PC_I; + new_pc_wr_en_reg <= 1'b0; + end else if (DATA_ALU_WR_SEL_I == PC) begin // FIXME could register new_pc_wr_en_reg one stage earlier + pc_reg <= DATA_ALU_Y_I; + new_pc_wr_en_reg <= 1'b1; + //end else if (ADDR_ALU_REG_SEL_I == PC) begin + // pc_reg <= ADDR_ALU_Y_I; //PC is never written from ADDR_ALU + // new_pc_wr_en_reg <= 1'b1; + end else begin + pc_reg <= pc_reg; + new_pc_wr_en_reg <= new_pc_wr_en_reg; + end + // + // DPR Register + //if (data_alu_wr_sel == DPR) dpr_reg <= DATA_ALU_Y_I[ 7:0]; + if (DATA_ALU_WR_SEL_I == DPR) dpr_reg <= DATA_ALU_Y_I[ 7:0]; + //else if (ADDR_ALU_REG_SEL_I == DPR) dpr_reg <= ADDR_ALU_Y_I[ 7:0]; + else dpr_reg <= dpr_reg; + // + // EA Register + if (ADDR_ALU_EA_WR_EN_I) ea_reg <= ADDR_ALU_EA_I; + else if (DATA_ALU_WR_SEL_I == EA) ea_reg <= DATA_ALU_Y_I; + //else if (ADDR_ALU_REG_SEL_I == EA) ea_reg <= ADDR_ALU_Y_I; //Not needed + else ea_reg <= ea_reg; + // + end + + end +end +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (DATA_ALU_A_SEL_I) + ZERO : DATA_ALU_A_O = zero_u16; + IDATA : DATA_ALU_A_O = instr_data; + DMEM_RD : DATA_ALU_A_O = DMEM_RD_DATA_REG_I; + EA : DATA_ALU_A_O = ea_reg; + // + DPR : DATA_ALU_A_O = dpr_reg_u16; + CCR : DATA_ALU_A_O = RA_CCR_RD_DATA_I; + B : DATA_ALU_A_O = b_reg_u16; + A : DATA_ALU_A_O = a_reg_u16; + // + SEXB : DATA_ALU_A_O = b_reg_s16; + // : DATA_ALU_A_O = ; + PC : DATA_ALU_A_O = pc_reg; + S : DATA_ALU_A_O = s_reg; + // + U : DATA_ALU_A_O = u_reg; + Y : DATA_ALU_A_O = y_reg; + X : DATA_ALU_A_O = x_reg; + D : DATA_ALU_A_O = d_reg; + // + //default : DATA_ALU_A_O = zero_u16; + default : DATA_ALU_A_O = REG_DONT_CARE; + endcase +end + +always @* begin + case (DATA_ALU_B_SEL_I) + ZERO : DATA_ALU_B_O = zero_u16; + IDATA : DATA_ALU_B_O = instr_data; + DMEM_RD : DATA_ALU_B_O = DMEM_RD_DATA_REG_I; + EA : DATA_ALU_B_O = ea_reg; + // + DPR : DATA_ALU_B_O = dpr_reg_u16; + CCR : DATA_ALU_B_O = RA_CCR_RD_DATA_I; + B : DATA_ALU_B_O = b_reg_u16; + A : DATA_ALU_B_O = a_reg_u16; + // + SEXB : DATA_ALU_B_O = b_reg_s16; + // : DATA_ALU_B_O = ; + PC : DATA_ALU_B_O = pc_reg; + S : DATA_ALU_B_O = s_reg; + // + U : DATA_ALU_B_O = u_reg; + Y : DATA_ALU_B_O = y_reg; + X : DATA_ALU_B_O = x_reg; + D : DATA_ALU_B_O = d_reg; + // + //default : DATA_ALU_B_O = zero_u16; + default : DATA_ALU_B_O = REG_DONT_CARE; + endcase +end + +always @* begin + case (ADDR_ALU_REG_SEL_I) + ZERO : ADDR_ALU_REG_O = zero_u16; + IDATA : ADDR_ALU_REG_O = instr_data; + DMEM_RD : ADDR_ALU_REG_O = DMEM_RD_DATA_REG_I; + EA : ADDR_ALU_REG_O = ea_reg; + // + //DPR : ADDR_ALU_REG_O = dpr_reg_u16; + //CCR : ADDR_ALU_REG_O = RA_CCR_RD_DATA_I; + //B : ADDR_ALU_REG_O = b_reg_u16; + //A : ADDR_ALU_REG_O = a_reg_u16; + // + //SEXB : ADDR_ALU_REG_O = b_reg_s16; + // : ADDR_ALU_REG_O = ; + PC : ADDR_ALU_REG_O = pc_reg; // used in indexed mode + S : ADDR_ALU_REG_O = s_reg; + // + U : ADDR_ALU_REG_O = u_reg; + Y : ADDR_ALU_REG_O = y_reg; + X : ADDR_ALU_REG_O = x_reg; + //D : ADDR_ALU_REG_O = d_reg; + // + //default : ADDR_ALU_REG_O = zero_u16; + default : ADDR_ALU_REG_O = REG_DONT_CARE; + endcase +end + +// Index Offset Select Decoding +always @* begin + case (ADDR_ALU_OFFSET_SEL_I) + ADDR_OFFSET_SEL_POS1 : ADDR_ALU_OFFSET_O = pos1_u16; + ADDR_OFFSET_SEL_POS2 : ADDR_ALU_OFFSET_O = pos2_u16; + ADDR_OFFSET_SEL_NEG1 : ADDR_ALU_OFFSET_O = neg1_s16; + ADDR_OFFSET_SEL_NEG2 : ADDR_ALU_OFFSET_O = neg2_s16; + ADDR_OFFSET_SEL_ZERO : ADDR_ALU_OFFSET_O = zero_u16; + ADDR_OFFSET_SEL_B : ADDR_ALU_OFFSET_O = b_reg_s16; + ADDR_OFFSET_SEL_A : ADDR_ALU_OFFSET_O = a_reg_s16; + ADDR_OFFSET_SEL_D : ADDR_ALU_OFFSET_O = d_reg; + ADDR_OFFSET_SEL_IDATA : ADDR_ALU_OFFSET_O = instr_data; + // + //default : ADDR_ALU_OFFSET_O = instr_data; + default : ADDR_ALU_OFFSET_O = REG_DONT_CARE; + endcase +end + +// Sequential Arithmetic Unit Registers +assign DATA_ALU_SAU_ABXY_O[47:40] = a_reg; +assign DATA_ALU_SAU_ABXY_O[39:32] = b_reg; +assign DATA_ALU_SAU_ABXY_O[31:16] = x_reg; +assign DATA_ALU_SAU_ABXY_O[15: 0] = y_reg; + +// CCR Write Data +assign RA_CCR_WR_DATA_O = DATA_ALU_Y_I[7:0]; +assign RA_CCR_WR_EN_O = (DATA_ALU_WR_SEL_I == CCR); + +assign REGISTER_ARRAY_READY_O = ((ADDR_ALU_REG_SEL_I == DMEM_RD) | // FIXME Optimize this logic + (DATA_ALU_A_SEL_I == DMEM_RD) | + (DATA_ALU_B_SEL_I == DMEM_RD)) ? DMEM_RD_DATA_READY_I : 1'b1; + +assign NEW_PC_WR_EN_O = new_pc_wr_en_reg; +assign NEW_PC_O = pc_reg; + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_s.v b/turbo9team_turbo9/rtl/turbo9_s.v new file mode 100644 index 0000000000000000000000000000000000000000..556a808c9f6f12b9070204e30799e0f213493709 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_s.v @@ -0,0 +1,192 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Turbo9S with 16-bit pipelined Wishbone memory bus +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_s +#( + parameter REGISTER_WB_OUTPUTS = 1, // Register Wishbone Ouputs: True=1, False=0 + parameter QUEUE_SIZE = 6 // Fetch Queue Size: 6=Default, 4=Min, 7=Max +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Inputs + input [15:0] DAT_I, + input [4:0] TGD_I, + input ACK_I, + input STALL_I, + + // Outputs + output [15:1] ADR_O, + output [15:0] DAT_O, + output [1:0] SEL_O, + output [4:0] TGD_O, + output WE_O, + output STB_O, + output CYC_O + +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +wire [15:0] dmem_dat_o; +wire [15:0] dmem_dat_i; +wire [15:0] dmem_adr_o; +wire dmem_busy_i; +wire dmem_req_o; +wire dmem_req_width_o; +wire dmem_we_o; +wire dmem_rd_ack_i; +wire dmem_wr_ack_i; +wire dmem_ack_width_i; + +wire [15:0] pmem_dat_i; +wire [15:0] pmem_adr_o; +wire pmem_busy_i; +wire pmem_rd_req_o; +wire pmem_rd_ack_i; +wire pmem_ack_width_i; +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// CPU ARCHITECTURE +///////////////////////////////////////////////////////////////////////////// + + + turbo9_pipeline + #( + .TURBO9_TYPE (1), // Turbo9 Type: 0=Turbo9, 1=Turbo9S, 2=Turbo9R + .QUEUE_SIZE (QUEUE_SIZE) // Fetch Queue Size: 6=Default, 4=Min, 7=Max + ) + I_turbo9_pipeline + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // + // Data Memory Interface + .DMEM_DAT_O (dmem_dat_o ), + .DMEM_DAT_I (dmem_dat_i ), + .DMEM_ADR_O (dmem_adr_o ), + .DMEM_BUSY_I (dmem_busy_i ), + .DMEM_REQ_O (dmem_req_o ), + .DMEM_REQ_WIDTH_O (dmem_req_width_o ), + .DMEM_WE_O (dmem_we_o ), + .DMEM_RD_ACK_I (dmem_rd_ack_i ), + .DMEM_WR_ACK_I (dmem_wr_ack_i ), + .DMEM_ACK_WIDTH_I (dmem_ack_width_i ), + // + // Program Memory Interface + .PMEM_DAT_I (pmem_dat_i ), + .PMEM_ADR_O (pmem_adr_o ), + .PMEM_BUSY_I (pmem_busy_i ), + .PMEM_REQ_WIDTH_O ( ), + .PMEM_RD_REQ_O (pmem_rd_req_o ), + .PMEM_RD_ACK_I (pmem_rd_ack_i ), + .PMEM_ACK_WIDTH_I (pmem_ack_width_i ) + ); + + turbo9_wishbone_16bit + #( + .REGISTER_WB_OUTPUTS (REGISTER_WB_OUTPUTS) // Register Wishbone Ouputs: True=1, False=0 + ) + I_turbo9_wishbone_16bit + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // + // External Wishbone Interface + .DAT_I (DAT_I ), + .TGD_I (TGD_I ), + .ACK_I (ACK_I ), + .STALL_I (STALL_I ), + .ADR_O (ADR_O ), + .DAT_O (DAT_O ), + .SEL_O (SEL_O ), + .TGD_O (TGD_O ), + .WE_O (WE_O ), + .STB_O (STB_O ), + .CYC_O (CYC_O ), + // + // Data Memory Interface + .DMEM_DAT_I (dmem_dat_o ), + .DMEM_DAT_O (dmem_dat_i ), + .DMEM_ADR_I (dmem_adr_o ), + .DMEM_BUSY_O (dmem_busy_i ), + .DMEM_REQ_I (dmem_req_o ), + .DMEM_REQ_WIDTH_I (dmem_req_width_o ), + .DMEM_WE_I (dmem_we_o ), + .DMEM_RD_ACK_O (dmem_rd_ack_i ), + .DMEM_WR_ACK_O (dmem_wr_ack_i ), + .DMEM_ACK_WIDTH_O (dmem_ack_width_i ), + // + // Program Memory Interface + .PMEM_DAT_O (pmem_dat_i ), + .PMEM_ADR_I (pmem_adr_o ), + .PMEM_BUSY_O (pmem_busy_i ), + .PMEM_RD_REQ_I (pmem_rd_req_o ), + .PMEM_RD_ACK_O (pmem_rd_ack_i ), + .PMEM_ACK_WIDTH_O (pmem_ack_width_i ) + ); + + + +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.mul.v b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.mul.v new file mode 100644 index 0000000000000000000000000000000000000000..201faf5deeec4801195102953fbf33d54c1090fa --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.mul.v @@ -0,0 +1,447 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: +// This module executes sequential or irregular math operations and isolates +// them from the critical timing path. There are registers on the inputs and +// outputs. Functions are parameterized so they can be removed to save area. +// +// //////////// Currently Implemented +// // NZVC +// MUL 8 by 8 unsigned multiply D = A * B oXoX 6809 ISA +// DAA BCD correction A = A + BDC_CF XXoX 6809 ISA +// +// //////////// Future +// // NZVC +// IDIV 16 by 16 unsigned int divide X = D / X, D = R oXXX HC11 ISA +// FDIV 16 by 16 unsigned frac divide X = D / X, D = R oXXX HC11 ISA +// +// EMUL 16 by 16 unsigned multiply Y:D = D * Y XXoX HC12 ISA +// EMULS 16 by 16 signed multiply Y:D = D * Y XXoX HC12 ISA +// +// EDIV 32 by 16 unsigned int divide Y = Y:D / X, D = R XXXX HC12 ISA +// EDIVS 32 by 16 signed int divide Y = Y:D / X, D = R XXXX HC12 ISA +// IDIVS 16 by 16 signed int divide X = D / X, D = R XXXX HC12 ISA +// +// COS CORDIC cosine implemtation +// SIN CORDIC sine implemtation +// +// SQRT square root implemation +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_seq_arithmetic_unit +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + input STALL_MICROCYCLE_I, + + input SAU_EN_I, + input SAU_OP_I, + input [47:0] SAU_ABXY_I, + + input [4:0] CCR_FLAGS_I, + + output [15:0] SAU_Y_O, + output SAU_DONE_O, + output [3:0] SAU_FLAGS_O +); + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// +wire [7:0] a_acc_in = SAU_ABXY_I[47:40]; +wire [7:0] b_acc_in = SAU_ABXY_I[39:32]; +//wire [15:0] x_reg_in = SAU_ABXY_I[31:16]; +//wire [15:0] y_reg_in = SAU_ABXY_I[15: 0]; + +wire ccr_h = CCR_FLAGS_I[4]; +wire ccr_n = CCR_FLAGS_I[3]; +wire ccr_z = CCR_FLAGS_I[2]; +wire ccr_v = CCR_FLAGS_I[1]; +wire ccr_c = CCR_FLAGS_I[0]; + +///////////////////// SAU_OP_I defines +// +localparam SAU_MUL = 1'b0; +localparam SAU_DAA = 1'b1; + +///////////////////// A register +// +reg [1:0] a_op; +localparam a_idle = 2'b00; +localparam a_load_a_acc = 2'b01; +localparam a_clear = 2'b10; +localparam a_update = 2'b11; +reg [7:0] a_reg; +reg [7:0] a_nxt; +localparam a_rst = 8'h00; + +///////////////////// B register +// +reg b_op; +localparam b_idle = 1'b0; +localparam b_load_b_acc = 1'b1; +reg [7:0] b_reg; +reg [7:0] b_nxt; +localparam b_rst = 8'h00; + +///////////////////// Q register +// +reg [1:0] q_op; +localparam q_idle = 2'b00; +localparam q_load_a_acc = 2'b01; +localparam q_update = 2'b10; +reg [7:0] q_reg; +reg [7:0] q_nxt; +localparam q_rst = 8'h00; + +///////////////////// Flags +// +reg [1:0] flags_op; +localparam flags_idle = 2'b00; +localparam flags_mul = 2'b01; +localparam flags_daa = 2'b10; + +reg n_reg; +reg n_nxt; +localparam n_rst = 1'b0; + +reg z_reg; +reg z_nxt; +localparam z_rst = 1'b0; + +reg v_reg; +reg v_nxt; +localparam v_rst = 1'b0; + +reg c_reg; +reg c_nxt; +localparam c_rst = 1'b0; + +wire z_hi8; +wire z_w8; +wire z_w16; + +///////////////////// Adder +// +reg [1:0] adder_op; +localparam adder_pass_a = 2'b00; +localparam adder_a_plus_b = 2'b01; +localparam adder_a_plus_bcd_cf = 2'b10; +reg [7:0] adder_a_in; +reg [7:0] adder_b_in; +reg adder_c_in; +wire [8:0] adder_y; + +///////////////////// Shifter +// +reg shifter_op; +localparam shifter_pass = 1'b0; +localparam shifter_shift = 1'b1; +reg [15:0] shifter_y; + +///////////////////// State Counter & Done +// +reg cnt_load; +reg [3:0] cnt_reg; +reg [3:0] cnt_nxt; +localparam cnt_rst = 4'h0; +// +reg done_reg; +reg done_nxt; +localparam done_rst = 1'h0; + +///////////////////// BCD Adjust Logic for DAA +// +wire lsn_gt_9 = (a_reg[3:0] > 4'h9); +wire msn_gt_9 = (a_reg[7:4] > 4'h9); +wire msn_gt_8 = (a_reg[7:4] > 4'h8); +wire [3:0] lsn_cf = (ccr_h || lsn_gt_9) ? 4'h6 : 4'h0; +wire [3:0] msn_cf = (ccr_c || msn_gt_9 || (msn_gt_8 && lsn_gt_9)) ? 4'h6 : 4'h0; +wire [7:0] bcd_cf = {msn_cf, lsn_cf}; // BCD Correction Factor + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Control +///////////////////////////////////////////////////////////////////////////// +// +always @* begin + // + // Defaults + a_op = a_idle; + b_op = b_idle; + q_op = q_idle; + flags_op = flags_idle; + adder_op = adder_pass_a; + shifter_op = shifter_pass; + cnt_load = 1'b0; + cnt_nxt = 4'h8; + done_nxt = 1'b0; + // + case (SAU_OP_I) + // + SAU_DAA : begin //////////////////// SAU_DAA + case (cnt_reg) + 4'h0 : begin + if (SAU_EN_I) begin + a_op = a_load_a_acc; + cnt_load = 1'b1; + cnt_nxt = 3'h1; + done_nxt = 1'b1; + end + end + default : begin + adder_op = adder_a_plus_bcd_cf; + shifter_op = shifter_pass; + a_op = a_clear; + q_op = q_update; + flags_op = flags_daa; + end + endcase + end + // + default : begin //////////////////// SAU_MUL + case (cnt_reg) + 4'h0 : begin + if (SAU_EN_I) begin + a_op = a_clear; + b_op = b_load_b_acc; + q_op = q_load_a_acc; + cnt_load = 1'b1; + cnt_nxt = 4'h8; + end + end + default : begin + if (q_reg[0]) begin + adder_op = adder_a_plus_b; + end + shifter_op = shifter_shift; + a_op = a_update; + q_op = q_update; + done_nxt = (cnt_reg == 4'h2); // Optimal for min cycles + if (cnt_reg == 4'h1) begin + flags_op = flags_mul; + end + end + endcase + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Datapath +///////////////////////////////////////////////////////////////////////////// +// +///////////////////// A Register Logic +// +always @* begin + case (a_op) + a_load_a_acc : a_nxt = a_acc_in; + a_clear : a_nxt = 8'h00; + a_update : a_nxt = shifter_y[15:8]; + default : a_nxt = a_reg; // a_idle + endcase +end + +///////////////////// B Register Logic +// +always @* begin + case (b_op) + b_load_b_acc : b_nxt = b_acc_in; + default : b_nxt = b_reg; // a_idle + endcase +end + +///////////////////// Adder +// +always @* begin + case (adder_op) + adder_a_plus_b : adder_a_in = a_reg; + adder_a_plus_bcd_cf : adder_a_in = a_reg; + default : adder_a_in = a_reg; // adder_pass_a + endcase + case (adder_op) + adder_a_plus_b : adder_b_in = b_reg; + adder_a_plus_bcd_cf : adder_b_in = bcd_cf; + default : adder_b_in = 8'h00; // adder_pass_a + endcase + case (adder_op) + adder_a_plus_b : adder_c_in = 1'b0; + adder_a_plus_bcd_cf : adder_c_in = 1'b0; + default : adder_c_in = 1'b0; // adder_pass_a + endcase +end +assign adder_y = {1'b0,adder_a_in} + {1'b0,adder_b_in} + {8'h00,adder_c_in}; + +///////////////////// Shifter +// +always @* begin + case (shifter_op) + shifter_shift : shifter_y = {adder_y, q_reg[7:1] }; + default : shifter_y = {8'h00, adder_y[7:0]}; // shifter_pass + endcase +end + +///////////////////// Q Register Logic +// +always @* begin + case (q_op) + q_load_a_acc : q_nxt = a_acc_in; + q_update : q_nxt = shifter_y[7:0]; + default : q_nxt = q_reg; // q_idle + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Flags +///////////////////////////////////////////////////////////////////////////// +// +assign z_hi8 = (shifter_y[15:8] == 8'h00); +assign z_w8 = (shifter_y[7:0] == 8'h00); +assign z_w16 = z_hi8 & z_w8; +// +///////////////////// Flag Logic +// +always @* begin + case (flags_op) + // + flags_mul : begin + n_nxt = ccr_n; // Not affected + z_nxt = z_w16; + v_nxt = ccr_v; // Not affected + c_nxt = shifter_y[7]; + end + // + flags_daa : begin + n_nxt = shifter_y[7]; + z_nxt = z_w8; + v_nxt = ccr_v; // INFO: Spec Undefined, Turbo9 not affected + c_nxt = (ccr_c | adder_y[8]); + end + // + default : begin // flags_idle + n_nxt = n_reg; + z_nxt = z_reg; + v_nxt = v_reg; + c_nxt = c_reg; + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Registers +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + a_reg <= a_rst; + b_reg <= b_rst; + q_reg <= q_rst; + n_reg <= n_rst; + z_reg <= z_rst; + v_reg <= v_rst; + c_reg <= c_rst; + cnt_reg <= cnt_rst; + done_reg <= done_rst; + end else begin + if (~STALL_MICROCYCLE_I) begin + a_reg <= a_nxt; + b_reg <= b_nxt; + q_reg <= q_nxt; + n_reg <= n_nxt; + z_reg <= z_nxt; + v_reg <= v_nxt; + c_reg <= c_nxt; + done_reg <= done_nxt; + // + if (cnt_load) begin + cnt_reg <= cnt_nxt; + end else if (cnt_reg != 4'h0) begin + cnt_reg <= cnt_reg - 4'h1; + end + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +assign SAU_Y_O = {a_reg, q_reg}; + +assign SAU_FLAGS_O[3] = n_reg; +assign SAU_FLAGS_O[2] = z_reg; +assign SAU_FLAGS_O[1] = v_reg; +assign SAU_FLAGS_O[0] = c_reg; + +assign SAU_DONE_O = done_reg; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.non_restore.v b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.non_restore.v new file mode 100644 index 0000000000000000000000000000000000000000..e3a28b75ac46957d45ba780c97fabaceac609ed4 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.non_restore.v @@ -0,0 +1,595 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: +// This module executes sequential or irregular math operations and isolates +// them from the critical timing path. There are registers on the inputs and +// outputs. Functions are parameterized so they can be removed to save area. +// +// //////////// Currently Implemented +// // NZVC +// MUL 8 by 8 unsigned multiply D = A * B oXoX 6809 ISA - +// DAA BCD correction A = A + BDC_CF XXoX 6809 ISA +// +// //////////// Future +// // NZVC +// IDIV 16 by 16 unsigned int divide X = D / X, D = R oXXX HC11 ISA +// FDIV 16 by 16 unsigned frac divide X = D / X, D = R oXXX HC11 ISA +// +// EMUL 16 by 16 unsigned multiply Y:D = D * Y XXoX HC12 ISA - +// EMULS 16 by 16 signed multiply Y:D = D * Y XXoX HC12 ISA +// +// EDIV 32 by 16 unsigned int divide Y = Y:D / X, D = R XXXX HC12 ISA - +// EDIVS 32 by 16 signed int divide Y = Y:D / X, D = R XXXX HC12 ISA +// IDIVS 16 by 16 signed int divide X = D / X, D = R XXXX HC12 ISA +// +// COS CORDIC cosine implemtation +// SIN CORDIC sine implemtation +// +// SQRT square root implemation +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_seq_arithmetic_unit +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + input STALL_MICROCYCLE_I, + + input SAU_EN_I, + input [3:0] SAU_OP_I, + input [47:0] SAU_ABXY_I, + + input [4:0] CCR_FLAGS_I, + + output [15:0] SAU_Y_O, + output SAU_DONE_O, + output [3:0] SAU_FLAGS_O +); + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// +wire [15:0] d_acc_in = SAU_ABXY_I[47:32]; +// +wire [7:0] a_acc_in = SAU_ABXY_I[47:40]; +wire [7:0] b_acc_in = SAU_ABXY_I[39:32]; +wire [15:0] x_reg_in = SAU_ABXY_I[31:16]; +wire [15:0] y_reg_in = SAU_ABXY_I[15: 0]; + +wire ccr_h = CCR_FLAGS_I[4]; +wire ccr_n = CCR_FLAGS_I[3]; +wire ccr_z = CCR_FLAGS_I[2]; +wire ccr_v = CCR_FLAGS_I[1]; +wire ccr_c = CCR_FLAGS_I[0]; + +///////////////////// SAU_OP_I defines +// opcode[3:0] | (Page2_en<<1) +// Page1 +localparam SAU_EMUL = 4'b0100; // 4 +localparam SAU_EMULS = 4'b0101; // 5 +localparam SAU_IDIV = 4'b1000; // 8 +localparam SAU_DAA = 4'b1001; // 9 +localparam SAU_MUL = 4'b1101; // D +// Page2 +localparam SAU_EDIV = 4'b0110; // 6 +localparam SAU_EDIVS = 4'b0111; // 7 +localparam SAU_IDIVS = 4'b1010; // A +localparam SAU_FDIV = 4'b1011; // B + +///////////////////// A register +// +reg [1:0] a_op; +localparam a_idle = 2'h0; +localparam a_clear = 2'h1; +localparam a_rshift = 2'h2; +localparam a_update = 2'h3; +reg [16:0] a_reg; +reg [16:0] a_nxt; +localparam a_rst = 17'h00000; + +///////////////////// M register +// +reg [2:0] m_op; +localparam m_idle = 3'h0; +localparam m_load_b_acc = 3'h1; +localparam m_load_y_reg = 3'h2; +localparam m_load_x_reg = 3'h3; +localparam m_load_bcd_cf = 3'h4; +reg [15:0] m_reg; +reg [15:0] m_nxt; +localparam m_rst = 16'h0000; + +///////////////////// Q register +// +reg [1:0] q_op; +localparam q_idle = 2'h0; +localparam q_load_d_acc = 2'h1; +localparam q_lshift = 2'h2; +localparam q_rshift = 2'h3; +reg [15:0] q_reg; +reg [15:0] q_nxt; +localparam q_rst = 16'h0000; + +///////////////////// Flags +// +reg [2:0] flags_op; +localparam flags_idle = 3'h0; +localparam flags_mul = 3'h1; +localparam flags_daa = 3'h2; +localparam flags_emul = 3'h3; +localparam flags_idiv = 3'h4; + +reg n_reg; +reg n_nxt; +localparam n_rst = 1'b0; + +reg z_reg; +reg z_nxt; +localparam z_rst = 1'b0; + +reg v_reg; +reg v_nxt; +localparam v_rst = 1'b0; + +reg c_reg; +reg c_nxt; +localparam c_rst = 1'b0; + +///////////////////// Adder +// +reg [2:0] adder_op; +localparam adder_pass_a = 3'h0; +localparam adder_a_plus_m = 3'h1; +localparam adder_aq_plus_m = 3'h2; +localparam adder_aq_minus_m = 3'h3; +localparam adder_q_plus_m = 3'h4; +localparam adder_pass_q = 3'h5; +reg [16:0] adder_a_in; +reg [16:0] adder_m_in; +reg adder_c_in; +wire [16:0] adder_y; + +///////////////////// State Counter & Done +// +reg cnt_load; +reg [4:0] cnt_reg; +reg [4:0] cnt_nxt; +localparam cnt_rst = 5'h0; +// +reg done_reg; +reg done_nxt; +localparam done_rst = 1'h0; + +///////////////////// BCD Adjust Logic for DAA +// +wire lsn_gt_9 = (q_reg[11: 8] > 4'h9); +wire msn_gt_9 = (q_reg[15:12] > 4'h9); +wire msn_gt_8 = (q_reg[15:12] > 4'h8); +wire [3:0] lsn_cf = (ccr_h || lsn_gt_9) ? 4'h6 : 4'h0; +wire [3:0] msn_cf = (ccr_c || msn_gt_9 || (msn_gt_8 && lsn_gt_9)) ? 4'h6 : 4'h0; +wire [7:0] bcd_cf = {msn_cf, lsn_cf}; // BCD Correction Factor + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Control +///////////////////////////////////////////////////////////////////////////// +// +always @* begin + // + // Defaults + a_op = a_idle; + m_op = m_idle; + q_op = q_idle; + flags_op = flags_idle; + adder_op = adder_pass_a; + cnt_load = 1'b0; + cnt_nxt = 5'h8; + done_nxt = 1'b0; + // + case (SAU_OP_I) + // + SAU_DAA : begin //////////////////// SAU_DAA + case (cnt_reg) + 5'h0 : begin + if (SAU_EN_I) begin + q_op = q_load_d_acc; + cnt_load = 1'b1; + cnt_nxt = 5'h2; + end + end + 5'h2 : begin + m_op = m_load_bcd_cf; + done_nxt = 1'b1; + end + default : begin + adder_op = adder_q_plus_m; + a_op = a_update; + flags_op = flags_daa; + end + endcase + end + // + SAU_EMUL : begin //////////////////// SAU_EMUL + case (cnt_reg) + 5'h0 : begin + if (SAU_EN_I) begin + a_op = a_clear; + m_op = m_load_y_reg; + q_op = q_load_d_acc; + cnt_load = 1'b1; + cnt_nxt = 5'd17; + end + end + default : begin + if (q_reg[0]) begin + adder_op = adder_a_plus_m; + end + a_op = a_rshift; + q_op = q_rshift; + done_nxt = (cnt_reg == 5'h3); // Optimal for min cycles + if (cnt_reg == 5'h2) begin + flags_op = flags_emul; + end + end + 5'h1 : begin + adder_op = adder_pass_q; + a_op = a_update; + end + endcase + end + // + SAU_IDIVS : begin //////////////////// SAU_IDIVS + case (cnt_reg) + 5'h0 : begin + if (SAU_EN_I) begin + a_op = a_clear; + m_op = m_load_x_reg; + q_op = q_load_d_acc; + cnt_load = 1'b1; + cnt_nxt = 5'd24; + end + end + 5'd24, + 5'd23, + 5'd22, + 5'd21, + 5'd20, + 5'd19 : begin + adder_op = adder_pass_a; + end + default : begin + q_op = q_lshift; + if (a_reg[16]) begin // Sign of A negative? + adder_op = adder_aq_plus_m; + end else begin + adder_op = adder_aq_minus_m; + end + a_op = a_update; + done_nxt = (cnt_reg == 5'h3); // Optimal for min cycles + end + 5'h2 : begin + q_op = q_lshift; + if (a_reg[16]) begin // Sign of A negative? + adder_op = adder_a_plus_m; + end else begin + adder_op = adder_pass_a; + end + a_op = a_update; + flags_op = flags_idiv; + end + 5'h1 : begin + adder_op = adder_pass_q; + a_op = a_update; + end + endcase + end + // + // + SAU_IDIV : begin //////////////////// SAU_IDIV + case (cnt_reg) + 5'h0 : begin + if (SAU_EN_I) begin + a_op = a_clear; + m_op = m_load_x_reg; + q_op = q_load_d_acc; + cnt_load = 1'b1; + cnt_nxt = 5'd18; + end + end + default : begin + q_op = q_lshift; + if (a_reg[16]) begin // Sign of A negative? + adder_op = adder_aq_plus_m; + end else begin + adder_op = adder_aq_minus_m; + end + a_op = a_update; + done_nxt = (cnt_reg == 5'h3); // Optimal for min cycles + end + 5'h2 : begin + q_op = q_lshift; + if (a_reg[16]) begin // Sign of A negative? + adder_op = adder_a_plus_m; + end else begin + adder_op = adder_pass_a; + end + a_op = a_update; + flags_op = flags_idiv; + end + 5'h1 : begin + adder_op = adder_pass_q; + a_op = a_update; + end + endcase + end + // + default : begin //////////////////// SAU_MUL + case (cnt_reg) + 5'h0 : begin + if (SAU_EN_I) begin + a_op = a_clear; + m_op = m_load_b_acc; + q_op = q_load_d_acc; + cnt_load = 1'b1; + cnt_nxt = 5'h8; + end + end + default : begin + if (q_reg[8]) begin + adder_op = adder_a_plus_m; + end + a_op = a_rshift; + q_op = q_rshift; + done_nxt = (cnt_reg == 5'h2); // Optimal for min cycles + if (cnt_reg == 5'h1) begin + flags_op = flags_mul; + end + end + endcase + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Datapath +///////////////////////////////////////////////////////////////////////////// +// +///////////////////// A Register Logic +// +always @* begin + case (a_op) + a_clear : a_nxt = 17'h00000; + a_rshift : a_nxt = {1'b0, adder_y[16:1]}; + a_update : a_nxt = adder_y; + default : a_nxt = a_reg; // a_idle + endcase +end + +///////////////////// M Register Logic +// +always @* begin + case (m_op) + m_load_b_acc : m_nxt = {b_acc_in, 8'h00}; + m_load_y_reg : m_nxt = y_reg_in; + m_load_x_reg : m_nxt = x_reg_in; + m_load_bcd_cf : m_nxt = {bcd_cf, 8'h00}; + default : m_nxt = m_reg; // m_idle + endcase +end + +///////////////////// Q Register Logic +// +always @* begin + case (q_op) + q_load_d_acc : q_nxt = d_acc_in; + q_lshift : q_nxt = {q_reg[14:0], ~a_reg[16]}; + q_rshift : q_nxt = {adder_y[0], q_reg[15:1]}; + default : q_nxt = q_reg; // q_idle + endcase +end + +///////////////////// Adder +// +always @* begin + case (adder_op) + adder_a_plus_m : adder_a_in = a_reg; + adder_aq_plus_m : adder_a_in = {a_reg[15:0], q_reg[15]}; + adder_aq_minus_m : adder_a_in = {a_reg[15:0], q_reg[15]}; + adder_q_plus_m : adder_a_in = {1'b0, q_reg}; + adder_pass_q : adder_a_in = {1'b0, q_reg}; + default : adder_a_in = a_reg; // adder_pass_a + endcase + case (adder_op) + adder_a_plus_m : adder_m_in = {1'b0, m_reg}; + adder_aq_plus_m : adder_m_in = {1'b0, m_reg}; + adder_aq_minus_m : adder_m_in = {1'b1, ~m_reg}; //m_reg is always positive do not sign extend + adder_q_plus_m : adder_m_in = {1'b0, m_reg}; + adder_pass_q : adder_m_in = 17'h00000; + default : adder_m_in = 17'h00000; // adder_pass_a + endcase + case (adder_op) + adder_a_plus_m : adder_c_in = 1'b0; + adder_aq_plus_m : adder_c_in = 1'b0; + adder_aq_minus_m : adder_c_in = 1'b1; + adder_q_plus_m : adder_c_in = 1'b0; + adder_pass_q : adder_c_in = 1'b0; + default : adder_c_in = 1'b0; // adder_pass_a + endcase +end +assign adder_y = adder_a_in + adder_m_in + {16'h0000,adder_c_in}; + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Flags +///////////////////////////////////////////////////////////////////////////// +// +wire z_a_h8 = (a_nxt[15:8] == 8'h00); +wire z_a_l8 = (a_nxt[ 7:0] == 8'h00); +wire z_a_w16 = z_a_h8 & z_a_l8; +// +wire z_q_h8 = (q_nxt[15:8] == 8'h00); +wire z_q_l8 = (q_nxt[ 7:0] == 8'h00); +wire z_q_w16 = z_q_h8 & z_q_l8; +// +wire z_w32 = z_q_w16 & z_a_w16; +// +wire div_by_zero = (m_reg == 16'h0000); +// +///////////////////// Flag Logic +// +always @* begin + case (flags_op) + // + flags_mul : begin + n_nxt = ccr_n; // Not affected + z_nxt = z_a_w16; + v_nxt = ccr_v; // Not affected + c_nxt = a_nxt[7]; + end + // + flags_emul : begin + n_nxt = a_nxt[15]; // MSB of result; + z_nxt = z_w32; + v_nxt = ccr_v; // Not affected + c_nxt = q_nxt[15]; + end + // + flags_idiv : begin + n_nxt = ccr_n; // Not affected + z_nxt = z_q_w16; + v_nxt = 1'b0; // Cleared + c_nxt = div_by_zero; + end + // + flags_daa : begin + n_nxt = a_nxt[15]; + z_nxt = z_a_h8; + v_nxt = ccr_v; // INFO: Spec Undefined, Turbo9 not affected + c_nxt = (ccr_c | a_nxt[16]); + end + // + default : begin // flags_idle + n_nxt = n_reg; + z_nxt = z_reg; + v_nxt = v_reg; + c_nxt = c_reg; + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Registers +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + // a_reg <= a_rst; // NO_INIT + // m_reg <= m_rst; // NO_INIT + // q_reg <= q_rst; // NO_INIT + // n_reg <= n_rst; // NO_INIT + // z_reg <= z_rst; // NO_INIT + // v_reg <= v_rst; // NO_INIT + // c_reg <= c_rst; // NO_INIT + cnt_reg <= cnt_rst; + done_reg <= done_rst; + end else begin + if (~STALL_MICROCYCLE_I) begin + a_reg <= a_nxt; + m_reg <= m_nxt; + q_reg <= q_nxt; + n_reg <= n_nxt; + z_reg <= z_nxt; + v_reg <= v_nxt; + c_reg <= c_nxt; + done_reg <= done_nxt; + // + if (cnt_load) begin + cnt_reg <= cnt_nxt; + end else if (cnt_reg != 5'h0) begin + cnt_reg <= cnt_reg - 5'd1; + end + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +assign SAU_Y_O = a_reg; + +assign SAU_FLAGS_O[3] = n_reg; +assign SAU_FLAGS_O[2] = z_reg; +assign SAU_FLAGS_O[1] = v_reg; +assign SAU_FLAGS_O[0] = c_reg; + +assign SAU_DONE_O = done_reg; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.v b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.v new file mode 100644 index 0000000000000000000000000000000000000000..ee7874c6fe6cec3f6464dc1da0609a437ec05c5c --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_seq_arithmetic_unit.v @@ -0,0 +1,1071 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: +// This module executes sequential or irregular math operations and isolates +// them from the critical timing path. There are registers on the inputs and +// outputs. +// +// //////////// Currently Implemented +// // NZVC +// MUL 8 by 8 unsigned multiply D = A * B oXoX 6809 ISA - +// DAA BCD correction A = A + BDC_CF XXoX 6809 ISA +// +// IDIV 16 by 16 unsigned int divide X = D / X, D = R oXXX HC11 ISA +// FDIV 16 by 16 unsigned frac divide X = D / X, D = R oXXX HC11 ISA +// +// EMUL 16 by 16 unsigned multiply Y:D = D * Y XXoX HC12 ISA - +// EMULS 16 by 16 signed multiply Y:D = D * Y XXoX HC12 ISA +// +// EDIV 32 by 16 unsigned int divide Y = Y:D / X, D = R XXXX HC12 ISA - +// EDIVS 32 by 16 signed int divide Y = Y:D / X, D = R XXXX HC12 ISA +// IDIVS 16 by 16 signed int divide X = D / X, D = R XXXX HC12 ISA +// +// //////////// Beta +// // +// CPY Memory copy loop counter +// +////////////////////////////////////////////////////////////////////////////// + + + ///////////////////////////////////////////// EMUL + // + // 16 by 16 unsigned integer multiply + // + // Y:D = D * Y + // + // N = MSB of product + // + // Z = 1 if product = 0x0000_0000 + // + // C = bit 15 of product + + ///////////////////////////////////////////// EMULS + // + // 16 by 16 signed integer multiply + // + // Y:D = D * Y + // + // N = MSB of product + // + // Z = 1 if product = 0x0000_0000 + // + // C = bit 15 of product + + ///////////////////////////////////////////// IDIVS + // + // 16 by 16 signed integer divide + // + // X = D / X + // X input when div_by_0 or overflow + // + // D = remainder + // D input when div_by_0 or overflow + // + // N = MSB of quotient + // MSB of Y input when div_by_0 or overflow (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 1 if Y input = 0x0000, when div_by_0 or overflow (HC12 undefined) + // + // V = 1 if quotient > 0x7FFF (+32767) or 0x8000 (-32768) + // 1 when div_by_0 (HC12 undefined) + // + // C = 1 if divisor = 0x0000 + + + ///////////////////////////////////////////// EDIV + // + // 32 by 16 unsigned integer divide + // + // Y = Y:D / X + // Y input when div_by_0 or overflow + // + // D = remainder + // D input when div_by_0 or overflow + // + // N = MSB of quotient + // MSB of Y input when div_by_0 or overflow (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 1 if Y input = 0x0000, when div_by_0 or overflow (HC12 undefined) + // + // V = 1 if quotient > 0xFFFF + // 1 when div_by_0 (HC12 undefined) + // + // C = 1 if divisor = 0x0000 + + + ///////////////////////////////////////////// IDIV + // + // 16 by 16 unsigned integer divide + // + // X = D / X + // 0xFFFF when div_by_0 + // + // D = remainder + // D input when div_by_0 (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 0 when div_by_0 + // + // V = 0 + // + // C = 1 if divisor = 0x0000 + + + ///////////////////////////////////////////// FDIV + // + // 16 by 16 unsigned fractional divide + // 0.16 = 0.16 / 16.0 + // + // X = D / X + // 0xFFFF when div_by_0 + // + // D = remainder + // D input when div_by_0 (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 0 when div_by_0 + // + // V = 1 if X <= D + // + // C = 1 if divisor = 0x0000 + + +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +// 07.30.2025 - Kevin Phillipson +// Everything works +// All instructions with condition codes verified +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_seq_arithmetic_unit +( + // Inputs: Clock & Reset + input CLK_I, + input RST_I, + input STALL_MICROCYCLE_I, + + input SAU_EN_I, + input SAU_DEC_I, + input [3:0] SAU_OP_I, + input [47:0] SAU_ABXY_I, + + input [4:0] CCR_FLAGS_I, + + output [15:0] SAU_Y_O, + output SAU_DONE_O, + output [3:0] SAU_FLAGS_O +); + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// +// +wire [7:0] a_acc_in = SAU_ABXY_I[47:40]; +wire [7:0] b_acc_in = SAU_ABXY_I[39:32]; +wire [15:0] d_acc_in = SAU_ABXY_I[47:32]; +wire [15:0] x_reg_in = SAU_ABXY_I[31:16]; +wire [15:0] y_reg_in = SAU_ABXY_I[15: 0]; + +wire ccr_h = CCR_FLAGS_I[4]; +wire ccr_n = CCR_FLAGS_I[3]; +wire ccr_z = CCR_FLAGS_I[2]; +wire ccr_v = CCR_FLAGS_I[1]; +wire ccr_c = CCR_FLAGS_I[0]; + +///////////////////// SAU_OP_I defines +// opcode[3:0] | (Page2_en<<1) +// Page1 +localparam SAU_EMUL = 4'b0100; // 4 opcode = $14 +localparam SAU_EMULS = 4'b0101; // 5 opcode = $15 +localparam SAU_IDIV = 4'b1000; // 8 opcode = $18 +localparam SAU_DAA = 4'b1001; // 9 opcode = $19 +localparam SAU_MUL = 4'b1101; // D opcode = $3D +// Page2 +localparam SAU_EDIV = 4'b0110; // 6 opcode = $1014 +localparam SAU_EDIVS = 4'b0111; // 7 opcode = $1015 +localparam SAU_IDIVS = 4'b1010; // A opcode = $1018 +localparam SAU_FDIV = 4'b1011; // B opcode = $1019 +localparam SAU_CPY = 4'b1111; // F opcode = $101F + +wire sau_op_is_emul = (SAU_OP_I == SAU_EMUL); +wire sau_op_is_emuls = (SAU_OP_I == SAU_EMULS); +wire sau_op_is_idiv = (SAU_OP_I == SAU_IDIV); +wire sau_op_is_daa = (SAU_OP_I == SAU_DAA); +wire sau_op_is_mul = (SAU_OP_I == SAU_MUL); + +wire sau_op_is_ediv = (SAU_OP_I == SAU_EDIV); +wire sau_op_is_edivs = (SAU_OP_I == SAU_EDIVS); +wire sau_op_is_idivs = (SAU_OP_I == SAU_IDIVS); +wire sau_op_is_fdiv = (SAU_OP_I == SAU_FDIV); +wire sau_op_is_cpy = (SAU_OP_I == SAU_CPY); + +wire sau_op_is_emul_or_emuls = (sau_op_is_emul | sau_op_is_emuls); + +wire sau_op_is_ediv_or_edivs = (sau_op_is_ediv | sau_op_is_edivs); + +wire sau_op_is_idivs_or_edivs = (sau_op_is_idivs | sau_op_is_edivs); + +wire sau_op_is_idiv_or_fdiv = (sau_op_is_idiv | sau_op_is_fdiv); + +wire sau_op_is_idiv_or_fdiv_or_ediv = (sau_op_is_idiv_or_fdiv | sau_op_is_ediv); + +wire divisor_sign = (m_reg[15] & sau_op_is_idivs_or_edivs); +wire dividend_sign = (n_reg & sau_op_is_idivs_or_edivs); +wire quotient_sign = (dividend_sign ^ divisor_sign); + +///////////////////// A register +// +reg [2:0] a_op; +localparam a_idle = 3'b000; // INFO a_op[2] is one hot! +localparam a_load_d_acc = 3'b100; +localparam a_load_y_reg = 3'b101; +localparam a_rshift = 3'b110; +localparam a_adder_out = 3'b111; +reg [15:0] a_reg; +reg [15:0] a_nxt; +localparam a_rst = 16'h0000; + +///////////////////// A Restore Register +// +wire [16:0] aq_lshift; + +///////////////////// M register +// +reg [2:0] m_op; +localparam m_idle = 3'b000; // INFO m_op[2] is one hot! +localparam m_load_b_acc = 3'b100; +localparam m_load_y_reg = 3'b101; +localparam m_load_x_reg = 3'b110; +localparam m_load_bcd_cf = 3'b111; +reg [15:0] m_reg; +reg [15:0] m_nxt; +localparam m_rst = 16'h0000; + +///////////////////// Q register +// +reg [2:0] q_op; +localparam q_idle = 3'b000; // INFO q_op[2] is one hot! +localparam q_load_d_acc = 3'b100; +localparam q_lshift = 3'b101; +localparam q_rshift = 3'b110; +localparam q_adder_out = 3'b111; +reg [15:0] q_reg; +reg [15:0] q_nxt; +localparam q_rst = 16'h0000; + +///////////////////// S register +// +reg [1:0] s_op; +localparam s_idle = 2'h0; +localparam s_clear = 2'h1; +localparam s_load_q0 = 2'h2; +localparam s_load_c_out = 2'h3; +reg s_reg; +reg s_nxt; +localparam s_rst = 1'b0; + +///////////////////// Flags +// +reg [2:0] flags_op; +localparam flags_idle = 3'h0; +localparam flags_init = 3'h1; +localparam flags_mul = 3'h2; +localparam flags_div_nz = 3'h3; +localparam flags_div_vc = 3'h4; +localparam flags_daa = 3'h5; + +reg n_reg; +reg n_nxt; +localparam n_rst = 1'b0; + +reg z_reg; +reg z_nxt; +localparam z_rst = 1'b0; + +reg v_reg; +reg v_nxt; +localparam v_rst = 1'b0; + +reg c_reg; +reg c_nxt; +localparam c_rst = 1'b0; + +wire c_nor_v = ~(c_reg | v_reg); + +///////////////////// Left and Right Muxes +// +reg [1:0] l_mux_sel; +localparam l_mux_zero = 2'h0; +localparam l_mux_a_reg = 2'h1; +localparam l_mux_aq_lshift = 2'h2; +localparam l_mux_q_reg = 2'h3; +reg [15:0] l_mux; +// +reg [1:0] r_mux_sel; +localparam r_mux_zero = 2'h0; +localparam r_mux_a_reg = 2'h1; +localparam r_mux_m_reg = 2'h2; +localparam r_mux_q_reg = 2'h3; +reg [15:0] r_mux; + +///////////////////// Sign Extension +// +reg [1:0] ext_op; +localparam ext_zero = 2'h0; +localparam ext_sign = 2'h1; +localparam ext_aq_lshift = 2'h2; +reg l_ext; +reg r_ext; + +///////////////////// Adder +// +reg [1:0] adder_op; +localparam adder_l_plus_r = 2'h0; +localparam adder_l_minus_r = 2'h1; +localparam adder_l_minus_r_dec1 = 2'h2; +localparam adder_l_minus_r_carry = 2'h3; +reg [16:0] adder_l_in; +reg [16:0] adder_r_in; +reg adder_c_in; +wire [15:0] adder_out; +wire adder_c_out; + +///////////////////// State, Counter & Done +// +localparam SAU_STATE_IDLE = 4'h0; +localparam SAU_STATE_DIV_ABS = 4'h1; +localparam SAU_STATE_DIV_ABS_EXT = 4'h2; +localparam SAU_STATE_DIV_SET_CV = 4'h3; +localparam SAU_STATE_DIV_LOOP = 4'h4; +localparam SAU_STATE_DIV_CORRECTION = 4'h5; +localparam SAU_STATE_DIV_FIX_REM_SIGN = 4'h6; +localparam SAU_STATE_DIV_FIX_QUO_SIGN = 4'h7; +localparam SAU_STATE_DAA_LOAD_BCD_CF = 4'h8; +localparam SAU_STATE_DAA_BCD_ADJUST = 4'h9; +localparam SAU_STATE_CPY_LOOP = 4'hA; +localparam SAU_STATE_MUL_LOOP = 4'hB; +localparam SAU_STATE_MUL_Q_OUT = 4'hC; +reg [3:0] state_nxt; +reg [3:0] state_reg; +localparam state_rst = SAU_STATE_IDLE; +// +reg cycle_load; +reg [3:0] cycle_reg; +reg [3:0] cycle_nxt; +// +wire cycle_reg_3_1_z = ~|cycle_reg[3:1]; +wire cycle_reg_is_0 = cycle_reg_3_1_z & ~cycle_reg[0]; +wire cycle_reg_is_1 = cycle_reg_3_1_z & cycle_reg[0]; +// +reg done_reg; +reg done_nxt; +localparam done_rst = 1'h0; + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Control +///////////////////////////////////////////////////////////////////////////// +// +always @* begin + + /////////////////////// Defaults + // + a_op = a_idle; + m_op = m_idle; + q_op = q_idle; + s_op = s_idle; + // + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_zero; + ext_op = ext_zero; + adder_op = adder_l_plus_r; + flags_op = flags_idle; + // + cycle_load = 1'b0; + cycle_nxt = 4'd0; + done_nxt = 1'b0; + state_nxt = SAU_STATE_IDLE; + + case (state_reg) + + /////////////////////// Idle State + // + // When SAU enabled, initialize registers + // and jump to correct state. + // + SAU_STATE_IDLE : begin + // + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_zero; + adder_op = adder_l_plus_r; // = 0 + s_op = s_clear; + // + if (SAU_EN_I) begin // && ~done_reg) begin + // + flags_op = flags_init; + // + if (sau_op_is_idiv_or_fdiv_or_ediv) begin // Unsigned Divide: IDIV FDIV EDIV + if (sau_op_is_idiv) begin // IDIV + a_op = a_adder_out; // A = 0 + q_op = q_load_d_acc; + end else if (sau_op_is_fdiv) begin // FDIV + a_op = a_load_d_acc; + q_op = q_adder_out; // Q = 0 + end else begin // sau_op_is_ediv EDIV + a_op = a_load_y_reg; + q_op = q_load_d_acc; + end + m_op = m_load_x_reg; + state_nxt = SAU_STATE_DIV_SET_CV; + end else if (sau_op_is_idivs_or_edivs) begin // Signed Divide: IDIVS EDIVS + if (sau_op_is_idivs) begin // IDIVS + a_op = a_adder_out; // A = 0 + q_op = q_load_d_acc; + end else begin // sau_op_is_edivs // EDIVS + a_op = a_load_y_reg; + q_op = q_load_d_acc; + end + m_op = m_load_x_reg; + state_nxt = SAU_STATE_DIV_ABS; + end else if (sau_op_is_daa) begin // Binary Decimal Adjust: DAA + q_op = q_load_d_acc; + state_nxt = SAU_STATE_DAA_LOAD_BCD_CF; + end else if (sau_op_is_cpy) begin // Memory Copy Counter: CPY + q_op = q_load_d_acc; + done_nxt = z_q_15_0; + state_nxt = SAU_STATE_CPY_LOOP; + end else begin // Multiply: MUL EMUL EMULS + if (sau_op_is_mul) begin + m_op = m_load_b_acc; + cycle_nxt = 4'd7; + end else begin // sau_op_is_emul_or_emuls + m_op = m_load_y_reg; + cycle_nxt = 4'd15; + end + a_op = a_adder_out; // A = 0 + q_op = q_load_d_acc; + cycle_load = 1'b1; + state_nxt = SAU_STATE_MUL_LOOP; + end + end + end + + /////////////////////// Absolute value dividend + // + // IDIVS, EDIVS start here + // absolute value for dividend[15:0] + // + SAU_STATE_DIV_ABS : begin + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_q_reg; + if (dividend_sign) begin + adder_op = adder_l_minus_r; // Q = 0 - -Q + end else begin + adder_op = adder_l_plus_r; // Q = 0 + +Q + end + q_op = q_adder_out; + s_op = s_load_c_out; + if (sau_op_is_idivs) begin + state_nxt = SAU_STATE_DIV_SET_CV; + end else begin + state_nxt = SAU_STATE_DIV_ABS_EXT; + end + end + + /////////////////////// Extended absolute value dividend + // + // EDIVS absolute value for dividend[31:16] + // + SAU_STATE_DIV_ABS_EXT : begin + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_a_reg; + if (dividend_sign) begin + adder_op = adder_l_minus_r_carry; // A = 0 - -A w/ borrow + end else begin + adder_op = adder_l_plus_r; // A = 0 + +A + end + a_op = a_adder_out; + state_nxt = SAU_STATE_DIV_SET_CV; + end + + /////////////////////// Check Overflow / Divide-by-zero state + // + // IDIV, FDIV, EDIV start here + // + // For EDIV: + // dividend[31:16] (Y) >= divisor[15:0] (X) then overflow + // therefore if borrow from A(Y) minus M(X) then no overflow + // if div-by-zero V will be set via adder_c_out + // + // For IDIV: + // A=0 + // M=divisor (X) + // so v=0 always (forced in flag_op logic b/c of div-by-zero condition) + // + // For FDIV + // A=dividend (D) + // M=divisor (X) + // V with be evaluated the same as EDIV + // + // A - M + SAU_STATE_DIV_SET_CV : begin + if (sau_op_is_idivs_or_edivs) begin + l_mux_sel = l_mux_aq_lshift; + ext_op = ext_aq_lshift; + end else begin + l_mux_sel = l_mux_a_reg; + ext_op = ext_zero; + end + r_mux_sel = r_mux_m_reg; + if (divisor_sign) begin + adder_op = adder_l_plus_r; // A + -M + end else begin + adder_op = adder_l_minus_r; // A - +M + end + // + flags_op = flags_div_vc; + s_op = s_clear; + cycle_load = 1'b1; + cycle_nxt = 4'd15; + state_nxt = SAU_STATE_DIV_LOOP; + end + + /////////////////////// Non-restoring Division Loop + // + SAU_STATE_DIV_LOOP : begin + if (c_nor_v) begin // if no (div-by-0 or overflow) do non-restoring division + if (s_reg ^ divisor_sign) begin // Sign of A negative? Sign of M negative? + adder_op = adder_l_plus_r; // AQ + M + end else begin + adder_op = adder_l_minus_r; // AQ - M + end + l_mux_sel = l_mux_aq_lshift; + r_mux_sel = r_mux_m_reg; + ext_op = ext_aq_lshift; + a_op = a_adder_out; + q_op = q_lshift; + s_op = s_load_c_out; + // + end else begin // if (div_by_0 or overflow) + l_mux_sel = l_mux_zero; + if (sau_op_is_ediv_or_edivs) begin // EDIV: don't change Y & D + r_mux_sel = r_mux_a_reg; + adder_op = adder_l_plus_r; // Pass A + if (cycle_reg_is_0) begin + a_op = a_load_d_acc; + q_op = q_adder_out; // = Y + end else begin + a_op = a_load_y_reg; + end + end else if (sau_op_is_idivs) begin // IDIVS: don't change X & D + r_mux_sel = r_mux_m_reg; + adder_op = adder_l_plus_r; // 0 + M + a_op = a_load_d_acc; + q_op = q_adder_out; + end else begin // IDIV/FDIV: X=FFFF and don't change D + r_mux_sel = r_mux_zero; + adder_op = adder_l_minus_r_dec1; // = FFFF + a_op = a_load_d_acc; + q_op = q_adder_out; + end + cycle_load = 1'b0; + cycle_nxt = 4'd0; // stay here for only one more cycle + end + // + if (cycle_reg_is_0) begin + done_nxt = ~sau_op_is_idivs_or_edivs; // Optimal for min cycles + state_nxt = SAU_STATE_DIV_CORRECTION; + end else begin + state_nxt = SAU_STATE_DIV_LOOP; + end + end + + /////////////////////// Correction step for non-restoring division + // + SAU_STATE_DIV_CORRECTION : begin + l_mux_sel = l_mux_a_reg; + r_mux_sel = r_mux_m_reg; + if (divisor_sign) begin + adder_op = adder_l_minus_r; // A - -M + end else begin + adder_op = adder_l_plus_r; // A + +M + end + // + if (s_reg && c_nor_v) begin // Sign of A negative? + a_op = a_adder_out; + end + // + done_nxt = 1'b1; + if (sau_op_is_idivs_or_edivs) begin + state_nxt = SAU_STATE_DIV_FIX_REM_SIGN; + end else begin + state_nxt = SAU_STATE_DIV_FIX_QUO_SIGN; + end + end + + /////////////////////// Remainder (A) sign correction for IDIVS/EDIVS + // + SAU_STATE_DIV_FIX_REM_SIGN : begin + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_a_reg; + if (dividend_sign && c_nor_v) begin // do not correct sign if no (div-by-0 or overflow) + adder_op = adder_l_minus_r; // 0 - A + end else begin + adder_op = adder_l_plus_r; // 0 + A + end + a_op = a_adder_out; + state_nxt = SAU_STATE_DIV_FIX_QUO_SIGN; + end + + /////////////////////// Pass Q or if IDIVS/EDIVS restore quotient sign + // + SAU_STATE_DIV_FIX_QUO_SIGN : begin + l_mux_sel = l_mux_zero; + r_mux_sel = r_mux_q_reg; + if (quotient_sign && c_nor_v) begin // do not correct sign if no (div-by-0 or overflow) + adder_op = adder_l_minus_r; // 0 - Q + end else begin + adder_op = adder_l_plus_r; // 0 + Q + end + a_op = a_adder_out; + flags_op = flags_div_nz; + state_nxt = SAU_STATE_IDLE; + end + + /////////////////////// Load Binary Coded Decimal Correction Factor + // + // DAA starts here + // + SAU_STATE_DAA_LOAD_BCD_CF : begin + m_op = m_load_bcd_cf; + done_nxt = 1'b1; + state_nxt = SAU_STATE_DAA_BCD_ADJUST; + end + + /////////////////////// Perform Binary Coded Decimal Adjustment + // + SAU_STATE_DAA_BCD_ADJUST : begin + l_mux_sel = l_mux_q_reg; + r_mux_sel = r_mux_m_reg; + adder_op = adder_l_plus_r; // Q + BCD_CF + a_op = a_adder_out; + flags_op = flags_daa; + state_nxt = SAU_STATE_IDLE; + end + + /////////////////////// Memory Copy Loop + // + // CPY starts here + // + SAU_STATE_CPY_LOOP : begin + l_mux_sel = l_mux_q_reg; + r_mux_sel = r_mux_zero; + adder_op = adder_l_minus_r_dec1; + if (SAU_DEC_I) begin + q_op = q_adder_out; // Dec Q + end + done_nxt = z_q_15_0; + if (done_reg) begin + state_nxt = SAU_STATE_IDLE; + end else begin + state_nxt = SAU_STATE_CPY_LOOP; + end + end + + /////////////////////// Multiply Loop for Signed and Unsigned + // + // MUL, EMUL, EMULS start here + // + SAU_STATE_MUL_LOOP : begin + l_mux_sel = l_mux_a_reg; + if (sau_op_is_emuls) begin // signed multiply + ext_op = ext_sign; + if (~q_reg[0] && s_reg) begin + r_mux_sel = r_mux_m_reg; + adder_op = adder_l_plus_r; // A + M (sign extended) + end else if (q_reg[0] && ~s_reg) begin + r_mux_sel = r_mux_m_reg; + adder_op = adder_l_minus_r; // A - M (sign extended) + end else begin + r_mux_sel = r_mux_zero; + adder_op = adder_l_plus_r; // Pass A + end + end else begin // unsigned multiply + ext_op = ext_zero; + if ((sau_op_is_mul && q_reg[8]) || (sau_op_is_emul && q_reg[0])) begin + r_mux_sel = r_mux_m_reg; + adder_op = adder_l_plus_r; // A + M + end else begin + r_mux_sel = r_mux_zero; + adder_op = adder_l_plus_r; // Pass A + end + end + a_op = a_rshift; + q_op = q_rshift; + s_op = s_load_q0; + done_nxt = (cycle_reg_is_1); // Optimal for min cycles + if (cycle_reg_is_0) begin + flags_op = flags_mul; + if (sau_op_is_mul) begin + state_nxt = SAU_STATE_IDLE; + end else begin + state_nxt = SAU_STATE_MUL_Q_OUT; + end + end else begin + state_nxt = SAU_STATE_MUL_LOOP; + end + end + + /////////////////////// Multiply output Q register + // + default : begin // SAU_STATE_MUL_Q_OUT + l_mux_sel = l_mux_q_reg; + r_mux_sel = r_mux_zero; + adder_op = adder_l_plus_r; + a_op = a_adder_out; // Pass Q + state_nxt = SAU_STATE_IDLE; + end + + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Datapath +///////////////////////////////////////////////////////////////////////////// +// + +///////////////////// BCD Adjust Logic for DAA +// +wire lsn_gt_9 = (q_reg[11: 8] > 4'h9); +wire msn_gt_9 = (q_reg[15:12] > 4'h9); +wire msn_gt_8 = (q_reg[15:12] > 4'h8); +wire [3:0] lsn_cf = (z_reg || lsn_gt_9) ? 4'h6 : 4'h0; // z_reg = half carry bit +wire [3:0] msn_cf = (c_reg || msn_gt_9 || (msn_gt_8 && lsn_gt_9)) ? 4'h6 : 4'h0; +wire [7:0] bcd_cf = {msn_cf, lsn_cf}; // BCD Correction Factor + +///////////////////// A Register Logic +// +always @* begin + case (a_op) + default : a_nxt = a_reg; // a_idle + a_load_d_acc : a_nxt = d_acc_in; + a_load_y_reg : a_nxt = y_reg_in; + a_rshift : a_nxt = {adder_c_out, adder_out[15:1]}; + a_adder_out : a_nxt = adder_out; + endcase +end + +///////////////////// M Register Logic +// +always @* begin + case (m_op) + default : m_nxt = m_reg; // m_idle + m_load_b_acc : m_nxt = {b_acc_in, 8'h00}; + m_load_y_reg : m_nxt = y_reg_in; + m_load_x_reg : m_nxt = x_reg_in; + m_load_bcd_cf : m_nxt = {bcd_cf, 8'h00}; + endcase +end + +///////////////////// Q Register Logic +// +always @* begin + case (q_op) + default : q_nxt = q_reg; // q_idle + q_load_d_acc : q_nxt = d_acc_in; + q_lshift : q_nxt = {q_reg[14:0], ~adder_c_out}; + q_rshift : q_nxt = {adder_out[0], q_reg[15:1]}; + q_adder_out : q_nxt = adder_out; + endcase +end + +///////////////////// AQ Left Shift +// +assign aq_lshift = {a_reg[15:0], q_reg[15]}; + +///////////////////// S Register Logic +// +always @* begin + case (s_op) + default : s_nxt = s_reg; // s_idle + s_clear : s_nxt = 1'b0; + s_load_q0 : s_nxt = q_reg[0]; + s_load_c_out : s_nxt = adder_c_out; + endcase +end + +///////////////////// Left and Right Muxes +// +always @* begin + case (l_mux_sel) + default : l_mux = 16'h0000; // l_mux_zero + l_mux_a_reg : l_mux = a_reg; + l_mux_aq_lshift : l_mux = aq_lshift[15:0]; + l_mux_q_reg : l_mux = q_reg; + endcase + // + case (r_mux_sel) + default : r_mux = 16'h0000; // r_mux_zero + r_mux_a_reg : r_mux = a_reg; + r_mux_m_reg : r_mux = m_reg; + r_mux_q_reg : r_mux = q_reg; + endcase +end + +///////////////////// Sign Extension +// +always @* begin + case (ext_op) + default : l_ext = 1'b0; // ext_zero + ext_sign : l_ext = l_mux[15]; + ext_aq_lshift : l_ext = aq_lshift[16]; + endcase + // + case (ext_op) + default : r_ext = 1'b0; // ext_zero + ext_sign : r_ext = r_mux[15]; + ext_aq_lshift : r_ext = (sau_op_is_idivs_or_edivs) ? r_mux[15] : 1'b0; + endcase +end + +///////////////////// Adder +// +always @* begin + adder_l_in = {l_ext, l_mux}; + // + case (adder_op) + default : adder_r_in = { r_ext, r_mux}; // adder_l_plus_r + adder_l_minus_r : adder_r_in = {~r_ext, ~r_mux}; + adder_l_minus_r_dec1 : adder_r_in = {~r_ext, ~r_mux}; + adder_l_minus_r_carry : adder_r_in = {~r_ext, ~r_mux}; + endcase + // + case (adder_op) + default : adder_c_in = 1'b0; // adder_l_plus_r + adder_l_minus_r : adder_c_in = 1'b1; + adder_l_minus_r_dec1 : adder_c_in = 1'b0; + adder_l_minus_r_carry : adder_c_in = ~s_reg; + endcase +end +assign {adder_c_out, adder_out} = adder_l_in + adder_r_in + {16'h0000,adder_c_in}; + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Flags +///////////////////////////////////////////////////////////////////////////// +// +wire z_adder_15_8 = ~|adder_out[15:8]; +wire z_adder_15_1 = z_adder_15_8 & ~|adder_out[7:1]; +wire z_adder_15_0 = z_adder_15_1 & ~adder_out[0]; +// +wire z_q_14_0 = ~|q_nxt[14:0]; +wire z_q_15_0 = ~q_nxt[15] & z_q_14_0; // FIXME +// FIXME (cont) adjust CPY to use q_reg for zero test not q_nxt +// FIXME (cont) q_nxt has a path to registers outside this block +// +wire z_m_15_0 = ~|m_reg[15:0]; +// +wire z_mul_15_0 = ~adder_c_out & z_adder_15_1; +wire z_mul_31_0 = z_q_15_0 & z_mul_15_0; +// +wire v_div_pos = ~quotient_sign & ~adder_c_out; +wire v_div_neg = quotient_sign & ~adder_c_out & ~(z_adder_15_0 & z_q_14_0); +wire v_div = v_div_pos | v_div_neg | z_m_15_0; +// 16 / 16 = 16 +// +// 16 / 16 = 16 +// +// 8000 / FFFF +// +// -32678 / -1 = 32678 +// +// - x10000 / 1 +// +// 32bit / 16bit +// +// abs_dividend[31:16] - abs_divisor[15:0] if negative then no overflow +// +// abs_dividend[30:15] - abs_divisor[15:0] if negative then no overflow +// +// 1 - 1 = 0 +// +// 2 - 2 = 0 + +///////////////////// Flag Logic +// +always @* begin + + // Defaults + n_nxt = n_reg; + z_nxt = z_reg; + v_nxt = v_reg; + c_nxt = c_reg; + + case (flags_op) + // + flags_init : begin + n_nxt = sau_op_is_idivs ? d_acc_in[15] : // use n_reg to hold dividend sign... + sau_op_is_edivs ? y_reg_in[15] : ccr_n; + z_nxt = sau_op_is_daa ? ccr_h : ccr_z; // Use z to hold the half carry + v_nxt = ccr_v; + c_nxt = ccr_c; + end + // + flags_mul : begin + if (sau_op_is_mul) begin + n_nxt = n_reg; + z_nxt = z_mul_15_0; + c_nxt = adder_out[8]; // = a_nxt[7] + end else begin + n_nxt = adder_c_out; // = a_nxt[15] (MSB of result) + z_nxt = z_mul_31_0; + c_nxt = adder_out[0]; // = q_nxt[15] + end + end + // + flags_div_nz : begin + n_nxt = (sau_op_is_idiv_or_fdiv) ? n_reg : adder_out[15]; // = a_nxt[15] (MSB of result) + z_nxt = z_adder_15_0; + end + // + flags_div_vc : begin + c_nxt = z_m_15_0; // if div-by-zero + v_nxt = sau_op_is_idiv ? 1'b0 : v_div; + end + // + flags_daa : begin + n_nxt = adder_out[15]; + z_nxt = z_adder_15_8; + //v_nxt = ccr_v; // INFO: Spec Undefined, Turbo9 not affected + c_nxt = (c_reg | adder_c_out); + end + // + default : begin // flags_idle + n_nxt = n_reg; + z_nxt = z_reg; + v_nxt = v_reg; + c_nxt = c_reg; + end + // + endcase +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Registers +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + // a_reg <= a_rst; // NO_INIT + // m_reg <= m_rst; // NO_INIT + // q_reg <= q_rst; // NO_INIT + // s_reg <= s_rst; // NO_INIT + // n_reg <= n_rst; // NO_INIT + // z_reg <= z_rst; // NO_INIT + // v_reg <= v_rst; // NO_INIT + // c_reg <= c_rst; // NO_INIT + // cycle_reg <= cycle_rst; // NO_INIT + // done_reg <= done_rst; // NO_INIT + if (RST_I) begin + state_reg <= state_rst; + end else begin + if (~STALL_MICROCYCLE_I) begin + state_reg <= state_nxt; + // + a_reg <= a_nxt; + m_reg <= m_nxt; + q_reg <= q_nxt; + s_reg <= s_nxt; + n_reg <= n_nxt; + z_reg <= z_nxt; + v_reg <= v_nxt; + c_reg <= c_nxt; + // + done_reg <= done_nxt; + // + if (cycle_load) begin + cycle_reg <= cycle_nxt; + end else if (~cycle_reg_is_0) begin + cycle_reg <= cycle_reg - 4'd1; + end + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +assign SAU_Y_O = a_reg; + +assign SAU_FLAGS_O[3] = n_reg; +assign SAU_FLAGS_O[2] = z_reg; +assign SAU_FLAGS_O[1] = v_reg; +assign SAU_FLAGS_O[0] = c_reg; + +assign SAU_DONE_O = done_reg; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_uop_generator.v b/turbo9team_turbo9/rtl/turbo9_uop_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..dfb07e99b39b309da46d5c90701f3c48e8284b6f --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_uop_generator.v @@ -0,0 +1,426 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: CISC to RISC Micro-Op generation block +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_uop_generator +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // Control Interface + output MICROCYCLE_START_O, + output NEXT_INSTR_REQ_O, + input STALL_MICROCYCLE_I, + input MICRO_SEQ_COND_I, + input NEXT_INSTR_ACK_I, + + // Instruction Queue + //input [7:0] QUEUE_D2_I, + input [7:0] QUEUE_D1_I, + input [7:0] QUEUE_D0_I, + input [1:0] PAGE_SEL_I, + + // Decoded Instruction + input [15:0] INSTR_DATA_I, + input INSTR_DIRECT_EN_I, + input INSTR_INH_EN_I, + input [3:0] INSTR_R1_SEL_I, + input [3:0] INSTR_R2_SEL_I, + input [3:0] INSTR_AR_SEL_I, + input [7:0] INSTR_JUMP_TABLE_A_I, + input [7:0] INSTR_JUMP_TABLE_B_I, + + // Micro-Op + output [2:0] UOP_MICRO_SEQ_OP_O, + output [7:0] UOP_MICRO_SEQ_BRANCH_ADDR_O, + output [3:0] UOP_DATA_ALU_A_SEL_O, + output [3:0] UOP_DATA_ALU_B_SEL_O, + output [3:0] UOP_DATA_ALU_WR_SEL_O, + output [3:0] UOP_ADDR_ALU_REG_SEL_O, + output [3:0] UOP_ADDR_ALU_OFFSET_SEL_O, + output UOP_ADDR_ALU_EA_OP_O, + output UOP_ADDR_ALU_EA_WR_EN_O, + output UOP_ADDR_ALU_Y_OP_O, + output [2:0] UOP_DATA_ALU_OP_O, + output [3:0] UOP_CCR_OP_O, + output [1:0] UOP_DATA_ALU_COND_SEL_O, + output [3:0] UOP_MICRO_SEQ_COND_SEL_O, + output [1:0] UOP_DMEM_OP_O, + output UOP_DATA_WIDTH_O, + output UOP_DATA_ALU_SAU_EN_O, + output [3:0] UOP_DATA_ALU_SAU_OP_O, + output UOP_IDX_INDIRECT_EN_O, + output [3:0] UOP_BRANCH_SEL_O, + output [15:0] UOP_DATA_O, + output UOP_DIRECT_EN_O, + output [7:0] UOP_JUMP_TABLE_B_O, + output UOP_STACK_DONE_O +); + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + +wire [7:0] microcode_adr; + +//////////////////////////////////////// Microcode Control Vector Micro-Op Fields +// +wire [2:0] cv_micro_seq_op; +reg [2:0] uop_micro_seq_op_reg; +localparam uop_micro_seq_op_rst = 3'h1; // INFO: JUMP to initialize pipeline reg after reset + +wire [7:0] cv_micro_seq_branch_addr; +reg [7:0] uop_micro_seq_branch_addr_reg; +localparam uop_micro_seq_branch_addr_rst = 8'h0; // INFO: addr = 0 to initialize pipeline reg after reset + +wire [3:0] cv_data_alu_a_sel; +wire [3:0] data_alu_a_sel; +reg [3:0] uop_data_alu_a_sel_reg; +localparam uop_data_alu_a_sel_rst = 4'h0; + +wire [2:0] cv_data_alu_b_sel; +wire [3:0] data_alu_b_sel; +reg [3:0] uop_data_alu_b_sel_reg; +localparam uop_data_alu_b_sel_rst = 4'h0; + +wire [3:0] cv_data_alu_wr_sel; +wire [3:0] data_alu_wr_sel; +reg [3:0] uop_data_alu_wr_sel_reg; +localparam uop_data_alu_wr_sel_rst = 4'h0; + +wire [3:0] cv_addr_alu_reg_sel; +wire [3:0] addr_alu_reg_sel; +reg [3:0] uop_addr_alu_reg_sel_reg; +localparam uop_addr_alu_reg_sel_rst = 4'h0; + +wire [3:0] addr_alu_offset_sel; +reg [3:0] uop_addr_alu_offset_sel_reg; +localparam uop_addr_alu_offset_sel_rst = 4'h0; + +wire addr_alu_ea_op; +reg uop_addr_alu_ea_op_reg; +localparam uop_addr_alu_ea_op_rst = 1'b0; + +wire addr_alu_ea_wr_en; +reg uop_addr_alu_ea_wr_en_reg; +localparam uop_addr_alu_ea_wr_en_rst = 1'b0; + +wire addr_alu_y_op; +reg uop_addr_alu_y_op_reg; +localparam uop_addr_alu_y_op_rst = 1'b0; + +wire [2:0] cv_data_alu_op; +reg [2:0] uop_data_alu_op_reg; +localparam uop_data_alu_op_rst = 3'h0; + +wire [3:0] cv_ccr_op; +reg [3:0] uop_ccr_op_reg; +localparam uop_ccr_op_rst = 4'h0; + +wire [1:0] cv_data_alu_cond_sel; +reg [1:0] uop_data_alu_cond_sel_reg; +localparam uop_data_alu_cond_sel_rst = 2'h0; + +wire [3:0] cv_micro_seq_cond_sel; +reg [3:0] uop_micro_seq_cond_sel_reg; +localparam uop_micro_seq_cond_sel_rst = 4'h1; // INFO: cond = true initialize pipeline reg after reset + +wire [1:0] cv_dmem_op; +wire [1:0] dmem_op; +reg [1:0] uop_dmem_op_reg; +localparam uop_dmem_op_rst = 2'h0; + +wire [1:0] cv_stack_op; + +wire [2:0] cv_data_width_sel; +wire data_width; +reg uop_data_width_reg; +localparam uop_data_width_rst = 1'b0; + +wire cv_data_alu_sau_en; +reg uop_data_alu_sau_en_reg; +localparam uop_data_alu_sau_en_rst = 1'b0; + +wire [3:0] data_alu_sau_op; +reg [3:0] uop_data_alu_sau_op_reg; +localparam uop_data_alu_sau_op_rst = 4'h0; + +wire idx_indirect_en; +reg uop_idx_indirect_en_reg; +localparam uop_idx_indirect_en_rst = 1'b0; + +wire stack_done; +reg uop_stack_done_reg; +localparam uop_stack_done_rst = 1'b0; + +wire [3:0] branch_sel; +reg [3:0] uop_branch_sel_reg; +localparam uop_branch_sel_rst = 1'b0; + + +//////////////////////////////////////// Instruction Decoded Fields +// +reg [15:0] uop_data_reg; +localparam uop_data_rst = 16'h0000; + +reg uop_direct_en_reg; +localparam uop_direct_en_rst = 1'b0; + +reg [7:0] uop_jump_table_b_reg; +localparam uop_jump_table_b_rst = 8'h00; + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + + + //////////////////////////////////////// Microsequencer + turbo9_microsequencer I_turbo9_microsequencer + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // Inputs + .STALL_MICROCYCLE_I (STALL_MICROCYCLE_I ), + .CONDITION_I (MICRO_SEQ_COND_I ), + .MICRO_SEQ_OP_I (uop_micro_seq_op_reg ), + .MICRO_SEQ_BRANCH_ADDR_I (uop_micro_seq_branch_addr_reg ), + .JUMP_TABLE_A_I (INSTR_JUMP_TABLE_A_I ), + .JUMP_TABLE_B_I (uop_jump_table_b_reg ), + // Outputs + .MICROCYCLE_START_O (MICROCYCLE_START_O ), + .MICROCODE_ADR_O (microcode_adr ), + .EXECUTE_NEXT_INSTR_O (NEXT_INSTR_REQ_O ) + ); + + //////////////////////////////////////// Microcode + turbo9_urtl_microcode I_turbo9_urtl_microcode + ( + // Inputs: + .MICROCODE_ADR_I ({1'b0,microcode_adr} ), + + // Control Vectors + .CV_MICRO_SEQ_OP_O (cv_micro_seq_op ), + .CV_MICRO_SEQ_BRANCH_ADDR_O (cv_micro_seq_branch_addr ), + .CV_DATA_ALU_A_SEL_O (cv_data_alu_a_sel ), + .CV_DATA_ALU_B_SEL_O (cv_data_alu_b_sel ), + .CV_DATA_ALU_WR_SEL_O (cv_data_alu_wr_sel ), + .CV_ADDR_ALU_REG_SEL_O (cv_addr_alu_reg_sel ), + .CV_DATA_ALU_OP_O (cv_data_alu_op ), + .CV_DATA_WIDTH_SEL_O (cv_data_width_sel ), + .CV_DATA_ALU_SAU_EN_O (cv_data_alu_sau_en ), + .CV_CCR_OP_O (cv_ccr_op ), + .CV_DATA_ALU_COND_SEL_O (cv_data_alu_cond_sel ), + .CV_MICRO_SEQ_COND_SEL_O (cv_micro_seq_cond_sel ), + .CV_DMEM_OP_O (cv_dmem_op ), + .CV_STACK_OP_O (cv_stack_op ) + ); + + //////////////////////////////////////// Register Control + turbo9_reg_addr_ctrl I_turbo9_reg_addr_ctrl + ( + // Inputs: Clock & Reset + .RST_I (RST_I ), + .CLK_I (CLK_I ), + // + // Stall & Next Instruction ACK + .STALL_MICROCYCLE_I (STALL_MICROCYCLE_I ), + .NEXT_INSTR_ACK_I (NEXT_INSTR_ACK_I ), + // + // Instruction Queue + //.QUEUE_D2_I (QUEUE_D2_I ), + .QUEUE_D1_I (QUEUE_D1_I ), + .QUEUE_D0_I (QUEUE_D0_I ), + .PAGE_SEL_I (PAGE_SEL_I ), + // + // Instrution Decoded Controls + .INSTR_INH_EN_I (INSTR_INH_EN_I ), + .INSTR_R1_SEL_I (INSTR_R1_SEL_I ), + .INSTR_R2_SEL_I (INSTR_R2_SEL_I ), + .INSTR_AR_SEL_I (INSTR_AR_SEL_I ), + // + // Control Vector Register Selects + .CV_DATA_WIDTH_SEL_I (cv_data_width_sel ), + .CV_DATA_ALU_A_SEL_I (cv_data_alu_a_sel ), + .CV_DATA_ALU_B_SEL_I (cv_data_alu_b_sel ), + .CV_DATA_ALU_WR_SEL_I (cv_data_alu_wr_sel ), + .CV_ADDR_ALU_REG_SEL_I (cv_addr_alu_reg_sel ), + .CV_DMEM_OP_I (cv_dmem_op ), + .CV_STACK_OP_I (cv_stack_op ), + // + // Data ALU + .DATA_WIDTH_O (data_width ), + .DATA_ALU_A_SEL_O (data_alu_a_sel ), + .DATA_ALU_B_SEL_O (data_alu_b_sel ), + .DATA_ALU_WR_SEL_O (data_alu_wr_sel ), + .DATA_ALU_SAU_OP (data_alu_sau_op ), + // + // Address ALU + .ADDR_ALU_REG_SEL_O (addr_alu_reg_sel ), + .ADDR_ALU_OFFSET_SEL_O (addr_alu_offset_sel ), + .ADDR_ALU_EA_WR_EN_O (addr_alu_ea_wr_en ), + .ADDR_ALU_EA_OP_O (addr_alu_ea_op ), + .ADDR_ALU_Y_OP_O (addr_alu_y_op ), + // + // Other + .DMEM_OP (dmem_op ), + .BRANCH_SEL_O (branch_sel ), + .IDX_INDIRECT_EN_O (idx_indirect_en ), + .STACK_DONE_O (stack_done ) + ); +///////////////////////////////////////////////////////////////////////////// +// MICRO-OPERATION REGISTER +///////////////////////////////////////////////////////////////////////////// +// +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + // + uop_micro_seq_op_reg <= uop_micro_seq_op_rst; + uop_micro_seq_branch_addr_reg <= uop_micro_seq_branch_addr_rst; + uop_data_alu_a_sel_reg <= uop_data_alu_a_sel_rst; + uop_data_alu_b_sel_reg <= uop_data_alu_b_sel_rst; + uop_data_alu_wr_sel_reg <= uop_data_alu_wr_sel_rst; + uop_addr_alu_reg_sel_reg <= uop_addr_alu_reg_sel_rst; + uop_addr_alu_offset_sel_reg <= uop_addr_alu_offset_sel_rst; + uop_addr_alu_ea_op_reg <= uop_addr_alu_ea_op_rst; + uop_addr_alu_ea_wr_en_reg <= uop_addr_alu_ea_wr_en_rst; + uop_addr_alu_y_op_reg <= uop_addr_alu_y_op_rst; + uop_data_alu_op_reg <= uop_data_alu_op_rst; + uop_ccr_op_reg <= uop_ccr_op_rst; + uop_data_alu_cond_sel_reg <= uop_data_alu_cond_sel_rst; + uop_micro_seq_cond_sel_reg <= uop_micro_seq_cond_sel_rst; + uop_dmem_op_reg <= uop_dmem_op_rst; + uop_data_width_reg <= uop_data_width_rst; + uop_data_alu_sau_en_reg <= uop_data_alu_sau_en_rst; + uop_data_alu_sau_op_reg <= uop_data_alu_sau_op_rst; + uop_idx_indirect_en_reg <= uop_idx_indirect_en_rst; + uop_stack_done_reg <= uop_stack_done_rst; + uop_branch_sel_reg <= uop_branch_sel_rst; + // // + uop_data_reg <= uop_data_rst; + uop_direct_en_reg <= uop_direct_en_rst; + uop_jump_table_b_reg <= uop_jump_table_b_rst; + // + end else begin + if (~STALL_MICROCYCLE_I) begin + // + uop_micro_seq_op_reg <= cv_micro_seq_op; + uop_micro_seq_branch_addr_reg <= cv_micro_seq_branch_addr; + uop_data_alu_a_sel_reg <= data_alu_a_sel; + uop_data_alu_b_sel_reg <= data_alu_b_sel; + uop_data_alu_wr_sel_reg <= data_alu_wr_sel; + uop_addr_alu_reg_sel_reg <= addr_alu_reg_sel; + uop_addr_alu_offset_sel_reg <= addr_alu_offset_sel; + uop_addr_alu_ea_op_reg <= addr_alu_ea_op; + uop_addr_alu_ea_wr_en_reg <= addr_alu_ea_wr_en; + uop_addr_alu_y_op_reg <= addr_alu_y_op; + uop_data_alu_op_reg <= cv_data_alu_op; + uop_ccr_op_reg <= cv_ccr_op; + uop_data_alu_cond_sel_reg <= cv_data_alu_cond_sel; + uop_micro_seq_cond_sel_reg <= cv_micro_seq_cond_sel; + uop_dmem_op_reg <= dmem_op; + uop_data_width_reg <= data_width; + uop_data_alu_sau_en_reg <= cv_data_alu_sau_en; + uop_idx_indirect_en_reg <= idx_indirect_en; + uop_stack_done_reg <= stack_done; + uop_branch_sel_reg <= branch_sel; + // + if (NEXT_INSTR_ACK_I) begin + // + uop_data_reg <= INSTR_DATA_I; + uop_direct_en_reg <= INSTR_DIRECT_EN_I; + uop_jump_table_b_reg <= INSTR_JUMP_TABLE_B_I; + uop_data_alu_sau_op_reg <= data_alu_sau_op; + // + end + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// ASSIGN OUPUTS +///////////////////////////////////////////////////////////////////////////// +// +// +assign UOP_MICRO_SEQ_OP_O = uop_micro_seq_op_reg; +assign UOP_MICRO_SEQ_BRANCH_ADDR_O = uop_micro_seq_branch_addr_reg; +assign UOP_DATA_ALU_A_SEL_O = uop_data_alu_a_sel_reg; +assign UOP_DATA_ALU_B_SEL_O = uop_data_alu_b_sel_reg; +assign UOP_DATA_ALU_WR_SEL_O = uop_data_alu_wr_sel_reg; +assign UOP_ADDR_ALU_REG_SEL_O = uop_addr_alu_reg_sel_reg; +assign UOP_ADDR_ALU_OFFSET_SEL_O = uop_addr_alu_offset_sel_reg; +assign UOP_ADDR_ALU_EA_OP_O = uop_addr_alu_ea_op_reg; +assign UOP_ADDR_ALU_EA_WR_EN_O = uop_addr_alu_ea_wr_en_reg; +assign UOP_ADDR_ALU_Y_OP_O = uop_addr_alu_y_op_reg; +assign UOP_DATA_ALU_OP_O = uop_data_alu_op_reg; +assign UOP_CCR_OP_O = uop_ccr_op_reg; +assign UOP_DATA_ALU_COND_SEL_O = uop_data_alu_cond_sel_reg; +assign UOP_MICRO_SEQ_COND_SEL_O = uop_micro_seq_cond_sel_reg; +assign UOP_DMEM_OP_O = uop_dmem_op_reg; +assign UOP_DATA_WIDTH_O = uop_data_width_reg; +assign UOP_DATA_ALU_SAU_EN_O = uop_data_alu_sau_en_reg; +assign UOP_DATA_ALU_SAU_OP_O = uop_data_alu_sau_op_reg; +assign UOP_IDX_INDIRECT_EN_O = uop_idx_indirect_en_reg; +assign UOP_BRANCH_SEL_O = uop_branch_sel_reg; +assign UOP_DATA_O = uop_data_reg; +assign UOP_DIRECT_EN_O = uop_direct_en_reg; +assign UOP_JUMP_TABLE_B_O = uop_jump_table_b_reg; +assign UOP_STACK_DONE_O = uop_stack_done_reg; +// +///////////////////////////////////////////////////////////////////////////// + + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_AR.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_AR.v new file mode 100644 index 0000000000000000000000000000000000000000..5df1f1926d3e8932d95720b8be0d1466784bcc4c --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_AR.v @@ -0,0 +1,178 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_AR_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg1_AR( + input [7:0] OPCODE_I, + output reg [3:0] PG1_AR_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h0F : PG1_AR_O = 4'he; // IDATA CLR (dir ext) + 8'h17 : PG1_AR_O = 4'h4; // S BSR LBSR + 8'h34 : PG1_AR_O = 4'h4; // S PSHS + 8'h35 : PG1_AR_O = 4'h4; // S PULS + 8'h36 : PG1_AR_O = 4'h3; // U PSHU + 8'h37 : PG1_AR_O = 4'h3; // U PULU + 8'h39 : PG1_AR_O = 4'h4; // S RTS + 8'h3B : PG1_AR_O = 4'h4; // S RTI + 8'h3F : PG1_AR_O = 4'h4; // S SWI + 8'h6F : PG1_AR_O = 4'hc; // EA CLR (idx) + 8'h7F : PG1_AR_O = 4'he; // IDATA CLR (dir ext) + 8'h8D : PG1_AR_O = 4'h4; // S BSR LBSR + 8'h97 : PG1_AR_O = 4'he; // IDATA STA (dir ext) + 8'h9D : PG1_AR_O = 4'h4; // S JSR (dir ext) + 8'h9F : PG1_AR_O = 4'he; // IDATA STX (dir ext) + 8'hA7 : PG1_AR_O = 4'hc; // EA STA (idx) + 8'hAD : PG1_AR_O = 4'h4; // S JSR (idx) + 8'hAF : PG1_AR_O = 4'hc; // EA STX (idx) + 8'hB7 : PG1_AR_O = 4'he; // IDATA STA (dir ext) + 8'hBD : PG1_AR_O = 4'h4; // S JSR (dir ext) + 8'hBF : PG1_AR_O = 4'he; // IDATA STX (dir ext) + 8'hD7 : PG1_AR_O = 4'he; // IDATA STB (dir ext) + 8'hDD : PG1_AR_O = 4'he; // IDATA STD (dir ext) + 8'hDF : PG1_AR_O = 4'he; // IDATA STU (dir ext) + 8'hE7 : PG1_AR_O = 4'hc; // EA STB (idx) + 8'hED : PG1_AR_O = 4'hc; // EA STD (idx) + 8'hEF : PG1_AR_O = 4'hc; // EA STU (idx) + 8'hF7 : PG1_AR_O = 4'he; // IDATA STB (dir ext) + 8'hFD : PG1_AR_O = 4'he; // IDATA STD (dir ext) + 8'hFF : PG1_AR_O = 4'he; // IDATA STU (dir ext) + default : PG1_AR_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG1_AR_op; + +always @* begin + case (OPCODE_I) + 8'h0F : PG1_AR_op = "CLR (dir ext)"; + 8'h17 : PG1_AR_op = "BSR LBSR"; + 8'h34 : PG1_AR_op = "PSHS"; + 8'h35 : PG1_AR_op = "PULS"; + 8'h36 : PG1_AR_op = "PSHU"; + 8'h37 : PG1_AR_op = "PULU"; + 8'h39 : PG1_AR_op = "RTS"; + 8'h3B : PG1_AR_op = "RTI"; + 8'h3F : PG1_AR_op = "SWI"; + 8'h6F : PG1_AR_op = "CLR (idx)"; + 8'h7F : PG1_AR_op = "CLR (dir ext)"; + 8'h8D : PG1_AR_op = "BSR LBSR"; + 8'h97 : PG1_AR_op = "STA (dir ext)"; + 8'h9D : PG1_AR_op = "JSR (dir ext)"; + 8'h9F : PG1_AR_op = "STX (dir ext)"; + 8'hA7 : PG1_AR_op = "STA (idx)"; + 8'hAD : PG1_AR_op = "JSR (idx)"; + 8'hAF : PG1_AR_op = "STX (idx)"; + 8'hB7 : PG1_AR_op = "STA (dir ext)"; + 8'hBD : PG1_AR_op = "JSR (dir ext)"; + 8'hBF : PG1_AR_op = "STX (dir ext)"; + 8'hD7 : PG1_AR_op = "STB (dir ext)"; + 8'hDD : PG1_AR_op = "STD (dir ext)"; + 8'hDF : PG1_AR_op = "STU (dir ext)"; + 8'hE7 : PG1_AR_op = "STB (idx)"; + 8'hED : PG1_AR_op = "STD (idx)"; + 8'hEF : PG1_AR_op = "STU (idx)"; + 8'hF7 : PG1_AR_op = "STB (dir ext)"; + 8'hFD : PG1_AR_op = "STD (dir ext)"; + 8'hFF : PG1_AR_op = "STU (dir ext)"; + default : PG1_AR_op = "invalid"; + endcase +end + +reg [(8*64):0] PG1_AR_eq; + +always @* begin + case (OPCODE_I) + 8'h0F : PG1_AR_eq = "IDATA"; + 8'h17 : PG1_AR_eq = "S"; + 8'h34 : PG1_AR_eq = "S"; + 8'h35 : PG1_AR_eq = "S"; + 8'h36 : PG1_AR_eq = "U"; + 8'h37 : PG1_AR_eq = "U"; + 8'h39 : PG1_AR_eq = "S"; + 8'h3B : PG1_AR_eq = "S"; + 8'h3F : PG1_AR_eq = "S"; + 8'h6F : PG1_AR_eq = "EA"; + 8'h7F : PG1_AR_eq = "IDATA"; + 8'h8D : PG1_AR_eq = "S"; + 8'h97 : PG1_AR_eq = "IDATA"; + 8'h9D : PG1_AR_eq = "S"; + 8'h9F : PG1_AR_eq = "IDATA"; + 8'hA7 : PG1_AR_eq = "EA"; + 8'hAD : PG1_AR_eq = "S"; + 8'hAF : PG1_AR_eq = "EA"; + 8'hB7 : PG1_AR_eq = "IDATA"; + 8'hBD : PG1_AR_eq = "S"; + 8'hBF : PG1_AR_eq = "IDATA"; + 8'hD7 : PG1_AR_eq = "IDATA"; + 8'hDD : PG1_AR_eq = "IDATA"; + 8'hDF : PG1_AR_eq = "IDATA"; + 8'hE7 : PG1_AR_eq = "EA"; + 8'hED : PG1_AR_eq = "EA"; + 8'hEF : PG1_AR_eq = "EA"; + 8'hF7 : PG1_AR_eq = "IDATA"; + 8'hFD : PG1_AR_eq = "IDATA"; + 8'hFF : PG1_AR_eq = "IDATA"; + default : PG1_AR_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTA.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTA.v new file mode 100644 index 0000000000000000000000000000000000000000..379bd4ccc204c67eb7203523a705da4b9b4d413b --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTA.v @@ -0,0 +1,760 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg1_JTA( + input [7:0] OPCODE_I, + output reg [7:0] PG1_JTA_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTA_O = 8'h1; // LD_DIR_EXT NEG (dir ext) + 8'h03 : PG1_JTA_O = 8'h1; // LD_DIR_EXT COM (dir ext) + 8'h04 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LSR (dir ext) + 8'h06 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ROR (dir ext) + 8'h07 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ASR (dir ext) + 8'h08 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ASL LSL (dir ext) + 8'h09 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ROL (dir ext) + 8'h0A : PG1_JTA_O = 8'h1; // LD_DIR_EXT DEC (dir ext) + 8'h0C : PG1_JTA_O = 8'h1; // LD_DIR_EXT INC (dir ext) + 8'h0D : PG1_JTA_O = 8'h1; // LD_DIR_EXT TST (dir ext) + 8'h0E : PG1_JTA_O = 8'h30; // JMP JMP (dir ext) + 8'h0F : PG1_JTA_O = 8'h25; // CLR CLR (dir ext) + 8'h10 : PG1_JTA_O = 8'hc; // NOP page2 (prebyte) + 8'h11 : PG1_JTA_O = 8'hc; // NOP page3 (prebyte) + 8'h12 : PG1_JTA_O = 8'hc; // NOP NOP(inh) + 8'h14 : PG1_JTA_O = 8'hd; // SAU16 EMUL (inh) + 8'h15 : PG1_JTA_O = 8'hd; // SAU16 EMULS (inh) + 8'h16 : PG1_JTA_O = 8'h2e; // BRANCH LBRA On page 1! + 8'h17 : PG1_JTA_O = 8'h2e; // BRANCH BSR LBSR // FIXME could do this without JUMP_TABLE_A + 8'h18 : PG1_JTA_O = 8'hd; // SAU16 IDIV (inh) + 8'h19 : PG1_JTA_O = 8'hf; // SAU8 DAA (inh) + 8'h1A : PG1_JTA_O = 8'h1f; // ORCC ORCC (imm) + 8'h1C : PG1_JTA_O = 8'h19; // ANDCC ANDCC (imm) + 8'h1D : PG1_JTA_O = 8'h11; // SEX SEX(inh) + 8'h1E : PG1_JTA_O = 8'h7; // EXG EXG(inh) + 8'h1F : PG1_JTA_O = 8'h15; // TFR TFR(inh) + 8'h20 : PG1_JTA_O = 8'h2e; // BRANCH BRA BRN BHI BLS + 8'h21 : PG1_JTA_O = 8'h2e; // BRANCH BRA BRN BHI BLS + 8'h22 : PG1_JTA_O = 8'h2e; // BRANCH BRA BRN BHI BLS + 8'h23 : PG1_JTA_O = 8'h2e; // BRANCH BRA BRN BHI BLS + 8'h24 : PG1_JTA_O = 8'h2e; // BRANCH BCC BCS BNE BEQ + 8'h25 : PG1_JTA_O = 8'h2e; // BRANCH BCC BCS BNE BEQ + 8'h26 : PG1_JTA_O = 8'h2e; // BRANCH BCC BCS BNE BEQ + 8'h27 : PG1_JTA_O = 8'h2e; // BRANCH BCC BCS BNE BEQ + 8'h28 : PG1_JTA_O = 8'h2e; // BRANCH BVC BVS BPL BMI + 8'h29 : PG1_JTA_O = 8'h2e; // BRANCH BVC BVS BPL BMI + 8'h2A : PG1_JTA_O = 8'h2e; // BRANCH BVC BVS BPL BMI + 8'h2B : PG1_JTA_O = 8'h2e; // BRANCH BVC BVS BPL BMI + 8'h2C : PG1_JTA_O = 8'h2e; // BRANCH BGE BLT BGT BLE + 8'h2D : PG1_JTA_O = 8'h2e; // BRANCH BGE BLT BGT BLE + 8'h2E : PG1_JTA_O = 8'h2e; // BRANCH BGE BLT BGT BLE + 8'h2F : PG1_JTA_O = 8'h2e; // BRANCH BGE BLT BGT BLE + 8'h30 : PG1_JTA_O = 8'h4; // ST_INDEXED LEAX(inh) + 8'h31 : PG1_JTA_O = 8'h4; // ST_INDEXED LEAY(inh) + 8'h32 : PG1_JTA_O = 8'h4; // ST_INDEXED LEAS(inh) + 8'h33 : PG1_JTA_O = 8'h4; // ST_INDEXED LEAU(inh) + 8'h34 : PG1_JTA_O = 8'h3c; // PSH PSHS + 8'h35 : PG1_JTA_O = 8'h38; // PUL PULS + 8'h36 : PG1_JTA_O = 8'h3c; // PSH PSHU + 8'h37 : PG1_JTA_O = 8'h38; // PUL PULU + 8'h39 : PG1_JTA_O = 8'h32; // RTS RTS + 8'h3A : PG1_JTA_O = 8'h6; // ABX ABX(inh) + 8'h3B : PG1_JTA_O = 8'h33; // RTI RTI + 8'h3D : PG1_JTA_O = 8'hf; // SAU8 MUL (inh) + 8'h3F : PG1_JTA_O = 8'h3f; // SWI SWI + 8'h40 : PG1_JTA_O = 8'h2a; // NEG NEGA (inh) + 8'h43 : PG1_JTA_O = 8'h26; // COM COMA (inh) + 8'h44 : PG1_JTA_O = 8'h29; // LSR LSRA (inh) + 8'h46 : PG1_JTA_O = 8'h2c; // ROR RORA (inh) + 8'h47 : PG1_JTA_O = 8'h24; // ASR ASRA (inh) + 8'h48 : PG1_JTA_O = 8'h23; // ASL_LSL ASLA LSLA (inh) + 8'h49 : PG1_JTA_O = 8'h2b; // ROL ROLA (inh) + 8'h4A : PG1_JTA_O = 8'h27; // DEC DECA (inh) + 8'h4C : PG1_JTA_O = 8'h28; // INC INCA (inh) + 8'h4D : PG1_JTA_O = 8'h2d; // TST TSTA (inh) + 8'h4F : PG1_JTA_O = 8'h25; // CLR CLRA (inh) + 8'h50 : PG1_JTA_O = 8'h2a; // NEG NEGB (inh) + 8'h53 : PG1_JTA_O = 8'h26; // COM COMB (inh) + 8'h54 : PG1_JTA_O = 8'h29; // LSR LSRB (inh) + 8'h56 : PG1_JTA_O = 8'h2c; // ROR RORB (inh) + 8'h57 : PG1_JTA_O = 8'h24; // ASR ASRB (inh) + 8'h58 : PG1_JTA_O = 8'h23; // ASL_LSL ASLB LSLB (inh) + 8'h59 : PG1_JTA_O = 8'h2b; // ROL ROLB (inh) + 8'h5A : PG1_JTA_O = 8'h27; // DEC DECB (inh) + 8'h5C : PG1_JTA_O = 8'h28; // INC INCB (inh) + 8'h5D : PG1_JTA_O = 8'h2d; // TST TSTB (inh) + 8'h5F : PG1_JTA_O = 8'h25; // CLR CLRB (inh) + 8'h60 : PG1_JTA_O = 8'h2; // LD_INDEXED NEG (idx) + 8'h63 : PG1_JTA_O = 8'h2; // LD_INDEXED COM (idx) + 8'h64 : PG1_JTA_O = 8'h2; // LD_INDEXED LSR (idx) + 8'h66 : PG1_JTA_O = 8'h2; // LD_INDEXED ROR (idx) + 8'h67 : PG1_JTA_O = 8'h2; // LD_INDEXED ASR (idx) + 8'h68 : PG1_JTA_O = 8'h2; // LD_INDEXED ASL LSL (idx) + 8'h69 : PG1_JTA_O = 8'h2; // LD_INDEXED ROL (idx) + 8'h6A : PG1_JTA_O = 8'h2; // LD_INDEXED DEC (idx) + 8'h6C : PG1_JTA_O = 8'h2; // LD_INDEXED INC (idx) + 8'h6D : PG1_JTA_O = 8'h2; // LD_INDEXED TST (idx) + 8'h6E : PG1_JTA_O = 8'h4; // ST_INDEXED JMP(idx) + 8'h6F : PG1_JTA_O = 8'h4; // ST_INDEXED CLR(idx) + 8'h70 : PG1_JTA_O = 8'h1; // LD_DIR_EXT NEG (dir ext) + 8'h73 : PG1_JTA_O = 8'h1; // LD_DIR_EXT COM (dir ext) + 8'h74 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LSR (dir ext) + 8'h76 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ROR (dir ext) + 8'h77 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ASR (dir ext) + 8'h78 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ASL LSL (dir ext) + 8'h79 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ROL (dir ext) + 8'h7A : PG1_JTA_O = 8'h1; // LD_DIR_EXT DEC (dir ext) + 8'h7C : PG1_JTA_O = 8'h1; // LD_DIR_EXT INC (dir ext) + 8'h7D : PG1_JTA_O = 8'h1; // LD_DIR_EXT TST (dir ext) + 8'h7E : PG1_JTA_O = 8'h30; // JMP JMP (dir ext) + 8'h7F : PG1_JTA_O = 8'h25; // CLR CLR (dir ext) + 8'h80 : PG1_JTA_O = 8'h21; // SUB SUBA (imm) + 8'h81 : PG1_JTA_O = 8'h1b; // CMP CMPA (imm) + 8'h82 : PG1_JTA_O = 8'h20; // SBC SBCA (imm) + 8'h83 : PG1_JTA_O = 8'h21; // SUB SUBD (imm) + 8'h84 : PG1_JTA_O = 8'h18; // AND ANDA (imm) + 8'h85 : PG1_JTA_O = 8'h1a; // BIT BITA (imm) + 8'h86 : PG1_JTA_O = 8'h1d; // LD LDA (imm) + 8'h88 : PG1_JTA_O = 8'h1c; // EOR EORA (imm) + 8'h89 : PG1_JTA_O = 8'h16; // ADC ADCA (imm) + 8'h8A : PG1_JTA_O = 8'h1e; // OR ORA (imm) + 8'h8B : PG1_JTA_O = 8'h17; // ADD ADDA (imm) + 8'h8C : PG1_JTA_O = 8'h1b; // CMP CMPX (imm) + 8'h8D : PG1_JTA_O = 8'h2e; // BRANCH BSR LBSR // FIXME could do this without JUMP_TABLE_A + 8'h8E : PG1_JTA_O = 8'h1d; // LD LDX (imm) + 8'h90 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBA (dir ext) + 8'h91 : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPA (dir ext) + 8'h92 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SBCA (dir ext) + 8'h93 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBD (dir ext) + 8'h94 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ANDA (dir ext) + 8'h95 : PG1_JTA_O = 8'h1; // LD_DIR_EXT BITA (dir ext) + 8'h96 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDA (dir ext) + 8'h97 : PG1_JTA_O = 8'h22; // ST STA (dir ext) + 8'h98 : PG1_JTA_O = 8'h1; // LD_DIR_EXT EORA (dir ext) + 8'h99 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADCA (dir ext) + 8'h9A : PG1_JTA_O = 8'h1; // LD_DIR_EXT ORA (dir ext) + 8'h9B : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDA (dir ext) + 8'h9C : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPX (dir ext) + 8'h9D : PG1_JTA_O = 8'h31; // JSR JSR (dir ext) + 8'h9E : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDX (dir ext) + 8'h9F : PG1_JTA_O = 8'h22; // ST STX (dir ext) + 8'hA0 : PG1_JTA_O = 8'h2; // LD_INDEXED SUBA (idx) + 8'hA1 : PG1_JTA_O = 8'h2; // LD_INDEXED CMPA (idx) + 8'hA2 : PG1_JTA_O = 8'h2; // LD_INDEXED SBCA (idx) + 8'hA3 : PG1_JTA_O = 8'h2; // LD_INDEXED SUBD (idx) + 8'hA4 : PG1_JTA_O = 8'h2; // LD_INDEXED ANDA (idx) + 8'hA5 : PG1_JTA_O = 8'h2; // LD_INDEXED BITA (idx) + 8'hA6 : PG1_JTA_O = 8'h2; // LD_INDEXED LDA (idx) + 8'hA7 : PG1_JTA_O = 8'h4; // ST_INDEXED STA (idx) + 8'hA8 : PG1_JTA_O = 8'h2; // LD_INDEXED EORA (idx) + 8'hA9 : PG1_JTA_O = 8'h2; // LD_INDEXED ADCA (idx) + 8'hAA : PG1_JTA_O = 8'h2; // LD_INDEXED ORA (idx) + 8'hAB : PG1_JTA_O = 8'h2; // LD_INDEXED ADDA (idx) + 8'hAC : PG1_JTA_O = 8'h2; // LD_INDEXED CMPX (idx) + 8'hAD : PG1_JTA_O = 8'h4; // ST_INDEXED JSR (idx) + 8'hAE : PG1_JTA_O = 8'h2; // LD_INDEXED LDX (idx) + 8'hAF : PG1_JTA_O = 8'h4; // ST_INDEXED STX (idx) + 8'hB0 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBA (dir ext) + 8'hB1 : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPA (dir ext) + 8'hB2 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SBCA (dir ext) + 8'hB3 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBD (dir ext) + 8'hB4 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ANDA (dir ext) + 8'hB5 : PG1_JTA_O = 8'h1; // LD_DIR_EXT BITA (dir ext) + 8'hB6 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDA (dir ext) + 8'hB7 : PG1_JTA_O = 8'h22; // ST STA (dir ext) + 8'hB8 : PG1_JTA_O = 8'h1; // LD_DIR_EXT EORA (dir ext) + 8'hB9 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADCA (dir ext) + 8'hBA : PG1_JTA_O = 8'h1; // LD_DIR_EXT ORA (dir ext) + 8'hBB : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDA (dir ext) + 8'hBC : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPX (dir ext) + 8'hBD : PG1_JTA_O = 8'h31; // JSR JSR (dir ext) + 8'hBE : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDX (dir ext) + 8'hBF : PG1_JTA_O = 8'h22; // ST STX (dir ext) + 8'hC0 : PG1_JTA_O = 8'h21; // SUB SUBB (imm) + 8'hC1 : PG1_JTA_O = 8'h1b; // CMP CMPB (imm) + 8'hC2 : PG1_JTA_O = 8'h20; // SBC SBCB (imm) + 8'hC3 : PG1_JTA_O = 8'h17; // ADD ADDD (imm) + 8'hC4 : PG1_JTA_O = 8'h18; // AND ANDB (imm) + 8'hC5 : PG1_JTA_O = 8'h1a; // BIT BITB (imm) + 8'hC6 : PG1_JTA_O = 8'h1d; // LD LDB (imm) + 8'hC8 : PG1_JTA_O = 8'h1c; // EOR EORB (imm) + 8'hC9 : PG1_JTA_O = 8'h16; // ADC ADCB (imm) + 8'hCA : PG1_JTA_O = 8'h1e; // OR ORB (imm) + 8'hCB : PG1_JTA_O = 8'h17; // ADD ADDB (imm) + 8'hCC : PG1_JTA_O = 8'h1d; // LD LDD (imm) + 8'hCE : PG1_JTA_O = 8'h1d; // LD LDU (imm) + 8'hD0 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBB (dir ext) + 8'hD1 : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPB (dir ext) + 8'hD2 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SBCB (dir ext) + 8'hD3 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDD (dir ext) + 8'hD4 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ANDB (dir ext) + 8'hD5 : PG1_JTA_O = 8'h1; // LD_DIR_EXT BITB (dir ext) + 8'hD6 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDB (dir ext) + 8'hD7 : PG1_JTA_O = 8'h22; // ST STB (dir ext) + 8'hD8 : PG1_JTA_O = 8'h1; // LD_DIR_EXT EORB (dir ext) + 8'hD9 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADCB (dir ext) + 8'hDA : PG1_JTA_O = 8'h1; // LD_DIR_EXT ORB (dir ext) + 8'hDB : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDB (dir ext) + 8'hDC : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDD (dir ext) + 8'hDD : PG1_JTA_O = 8'h22; // ST STD (dir ext) + 8'hDE : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDU (dir ext) + 8'hDF : PG1_JTA_O = 8'h22; // ST STU (dir ext) + 8'hE0 : PG1_JTA_O = 8'h2; // LD_INDEXED SUBB (idx) + 8'hE1 : PG1_JTA_O = 8'h2; // LD_INDEXED CMPB (idx) + 8'hE2 : PG1_JTA_O = 8'h2; // LD_INDEXED SBCB (idx) + 8'hE3 : PG1_JTA_O = 8'h2; // LD_INDEXED ADDD (idx) + 8'hE4 : PG1_JTA_O = 8'h2; // LD_INDEXED ANDB (idx) + 8'hE5 : PG1_JTA_O = 8'h2; // LD_INDEXED BITB (idx) + 8'hE6 : PG1_JTA_O = 8'h2; // LD_INDEXED LDB (idx) + 8'hE7 : PG1_JTA_O = 8'h4; // ST_INDEXED STB (idx) + 8'hE8 : PG1_JTA_O = 8'h2; // LD_INDEXED EORB (idx) + 8'hE9 : PG1_JTA_O = 8'h2; // LD_INDEXED ADCB (idx) + 8'hEA : PG1_JTA_O = 8'h2; // LD_INDEXED ORB (idx) + 8'hEB : PG1_JTA_O = 8'h2; // LD_INDEXED ADDB (idx) + 8'hEC : PG1_JTA_O = 8'h2; // LD_INDEXED LDD (idx) + 8'hED : PG1_JTA_O = 8'h4; // ST_INDEXED STD (idx) + 8'hEE : PG1_JTA_O = 8'h2; // LD_INDEXED LDU (idx) + 8'hEF : PG1_JTA_O = 8'h4; // ST_INDEXED STU (idx) + 8'hF0 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SUBB (dir ext) + 8'hF1 : PG1_JTA_O = 8'h1; // LD_DIR_EXT CMPB (dir ext) + 8'hF2 : PG1_JTA_O = 8'h1; // LD_DIR_EXT SBCB (dir ext) + 8'hF3 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDD (dir ext) + 8'hF4 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ANDB (dir ext) + 8'hF5 : PG1_JTA_O = 8'h1; // LD_DIR_EXT BITB (dir ext) + 8'hF6 : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDB (dir ext) + 8'hF7 : PG1_JTA_O = 8'h22; // ST STB (dir ext) + 8'hF8 : PG1_JTA_O = 8'h1; // LD_DIR_EXT EORB (dir ext) + 8'hF9 : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADCB (dir ext) + 8'hFA : PG1_JTA_O = 8'h1; // LD_DIR_EXT ORB (dir ext) + 8'hFB : PG1_JTA_O = 8'h1; // LD_DIR_EXT ADDB (dir ext) + 8'hFC : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDD (dir ext) + 8'hFD : PG1_JTA_O = 8'h22; // ST STD (dir ext) + 8'hFE : PG1_JTA_O = 8'h1; // LD_DIR_EXT LDU (dir ext) + 8'hFF : PG1_JTA_O = 8'h22; // ST STU (dir ext) + default : PG1_JTA_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG1_JTA_op; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTA_op = "NEG (dir ext)"; + 8'h03 : PG1_JTA_op = "COM (dir ext)"; + 8'h04 : PG1_JTA_op = "LSR (dir ext)"; + 8'h06 : PG1_JTA_op = "ROR (dir ext)"; + 8'h07 : PG1_JTA_op = "ASR (dir ext)"; + 8'h08 : PG1_JTA_op = "ASL LSL (dir ext)"; + 8'h09 : PG1_JTA_op = "ROL (dir ext)"; + 8'h0A : PG1_JTA_op = "DEC (dir ext)"; + 8'h0C : PG1_JTA_op = "INC (dir ext)"; + 8'h0D : PG1_JTA_op = "TST (dir ext)"; + 8'h0E : PG1_JTA_op = "JMP (dir ext)"; + 8'h0F : PG1_JTA_op = "CLR (dir ext)"; + 8'h10 : PG1_JTA_op = "page2 (prebyte)"; + 8'h11 : PG1_JTA_op = "page3 (prebyte)"; + 8'h12 : PG1_JTA_op = "NOP(inh)"; + 8'h14 : PG1_JTA_op = "EMUL (inh)"; + 8'h15 : PG1_JTA_op = "EMULS (inh)"; + 8'h16 : PG1_JTA_op = "LBRA On page 1!"; + 8'h17 : PG1_JTA_op = "BSR LBSR // FIXME could do this without JUMP_TABLE_A"; + 8'h18 : PG1_JTA_op = "IDIV (inh)"; + 8'h19 : PG1_JTA_op = "DAA (inh)"; + 8'h1A : PG1_JTA_op = "ORCC (imm)"; + 8'h1C : PG1_JTA_op = "ANDCC (imm)"; + 8'h1D : PG1_JTA_op = "SEX(inh)"; + 8'h1E : PG1_JTA_op = "EXG(inh)"; + 8'h1F : PG1_JTA_op = "TFR(inh)"; + 8'h20 : PG1_JTA_op = "BRA BRN BHI BLS"; + 8'h21 : PG1_JTA_op = "BRA BRN BHI BLS"; + 8'h22 : PG1_JTA_op = "BRA BRN BHI BLS"; + 8'h23 : PG1_JTA_op = "BRA BRN BHI BLS"; + 8'h24 : PG1_JTA_op = "BCC BCS BNE BEQ"; + 8'h25 : PG1_JTA_op = "BCC BCS BNE BEQ"; + 8'h26 : PG1_JTA_op = "BCC BCS BNE BEQ"; + 8'h27 : PG1_JTA_op = "BCC BCS BNE BEQ"; + 8'h28 : PG1_JTA_op = "BVC BVS BPL BMI"; + 8'h29 : PG1_JTA_op = "BVC BVS BPL BMI"; + 8'h2A : PG1_JTA_op = "BVC BVS BPL BMI"; + 8'h2B : PG1_JTA_op = "BVC BVS BPL BMI"; + 8'h2C : PG1_JTA_op = "BGE BLT BGT BLE"; + 8'h2D : PG1_JTA_op = "BGE BLT BGT BLE"; + 8'h2E : PG1_JTA_op = "BGE BLT BGT BLE"; + 8'h2F : PG1_JTA_op = "BGE BLT BGT BLE"; + 8'h30 : PG1_JTA_op = "LEAX(inh)"; + 8'h31 : PG1_JTA_op = "LEAY(inh)"; + 8'h32 : PG1_JTA_op = "LEAS(inh)"; + 8'h33 : PG1_JTA_op = "LEAU(inh)"; + 8'h34 : PG1_JTA_op = "PSHS"; + 8'h35 : PG1_JTA_op = "PULS"; + 8'h36 : PG1_JTA_op = "PSHU"; + 8'h37 : PG1_JTA_op = "PULU"; + 8'h39 : PG1_JTA_op = "RTS"; + 8'h3A : PG1_JTA_op = "ABX(inh)"; + 8'h3B : PG1_JTA_op = "RTI"; + 8'h3D : PG1_JTA_op = "MUL (inh)"; + 8'h3F : PG1_JTA_op = "SWI"; + 8'h40 : PG1_JTA_op = "NEGA (inh)"; + 8'h43 : PG1_JTA_op = "COMA (inh)"; + 8'h44 : PG1_JTA_op = "LSRA (inh)"; + 8'h46 : PG1_JTA_op = "RORA (inh)"; + 8'h47 : PG1_JTA_op = "ASRA (inh)"; + 8'h48 : PG1_JTA_op = "ASLA LSLA (inh)"; + 8'h49 : PG1_JTA_op = "ROLA (inh)"; + 8'h4A : PG1_JTA_op = "DECA (inh)"; + 8'h4C : PG1_JTA_op = "INCA (inh)"; + 8'h4D : PG1_JTA_op = "TSTA (inh)"; + 8'h4F : PG1_JTA_op = "CLRA (inh)"; + 8'h50 : PG1_JTA_op = "NEGB (inh)"; + 8'h53 : PG1_JTA_op = "COMB (inh)"; + 8'h54 : PG1_JTA_op = "LSRB (inh)"; + 8'h56 : PG1_JTA_op = "RORB (inh)"; + 8'h57 : PG1_JTA_op = "ASRB (inh)"; + 8'h58 : PG1_JTA_op = "ASLB LSLB (inh)"; + 8'h59 : PG1_JTA_op = "ROLB (inh)"; + 8'h5A : PG1_JTA_op = "DECB (inh)"; + 8'h5C : PG1_JTA_op = "INCB (inh)"; + 8'h5D : PG1_JTA_op = "TSTB (inh)"; + 8'h5F : PG1_JTA_op = "CLRB (inh)"; + 8'h60 : PG1_JTA_op = "NEG (idx)"; + 8'h63 : PG1_JTA_op = "COM (idx)"; + 8'h64 : PG1_JTA_op = "LSR (idx)"; + 8'h66 : PG1_JTA_op = "ROR (idx)"; + 8'h67 : PG1_JTA_op = "ASR (idx)"; + 8'h68 : PG1_JTA_op = "ASL LSL (idx)"; + 8'h69 : PG1_JTA_op = "ROL (idx)"; + 8'h6A : PG1_JTA_op = "DEC (idx)"; + 8'h6C : PG1_JTA_op = "INC (idx)"; + 8'h6D : PG1_JTA_op = "TST (idx)"; + 8'h6E : PG1_JTA_op = "JMP(idx)"; + 8'h6F : PG1_JTA_op = "CLR(idx)"; + 8'h70 : PG1_JTA_op = "NEG (dir ext)"; + 8'h73 : PG1_JTA_op = "COM (dir ext)"; + 8'h74 : PG1_JTA_op = "LSR (dir ext)"; + 8'h76 : PG1_JTA_op = "ROR (dir ext)"; + 8'h77 : PG1_JTA_op = "ASR (dir ext)"; + 8'h78 : PG1_JTA_op = "ASL LSL (dir ext)"; + 8'h79 : PG1_JTA_op = "ROL (dir ext)"; + 8'h7A : PG1_JTA_op = "DEC (dir ext)"; + 8'h7C : PG1_JTA_op = "INC (dir ext)"; + 8'h7D : PG1_JTA_op = "TST (dir ext)"; + 8'h7E : PG1_JTA_op = "JMP (dir ext)"; + 8'h7F : PG1_JTA_op = "CLR (dir ext)"; + 8'h80 : PG1_JTA_op = "SUBA (imm)"; + 8'h81 : PG1_JTA_op = "CMPA (imm)"; + 8'h82 : PG1_JTA_op = "SBCA (imm)"; + 8'h83 : PG1_JTA_op = "SUBD (imm)"; + 8'h84 : PG1_JTA_op = "ANDA (imm)"; + 8'h85 : PG1_JTA_op = "BITA (imm)"; + 8'h86 : PG1_JTA_op = "LDA (imm)"; + 8'h88 : PG1_JTA_op = "EORA (imm)"; + 8'h89 : PG1_JTA_op = "ADCA (imm)"; + 8'h8A : PG1_JTA_op = "ORA (imm)"; + 8'h8B : PG1_JTA_op = "ADDA (imm)"; + 8'h8C : PG1_JTA_op = "CMPX (imm)"; + 8'h8D : PG1_JTA_op = "BSR LBSR // FIXME could do this without JUMP_TABLE_A"; + 8'h8E : PG1_JTA_op = "LDX (imm)"; + 8'h90 : PG1_JTA_op = "SUBA (dir ext)"; + 8'h91 : PG1_JTA_op = "CMPA (dir ext)"; + 8'h92 : PG1_JTA_op = "SBCA (dir ext)"; + 8'h93 : PG1_JTA_op = "SUBD (dir ext)"; + 8'h94 : PG1_JTA_op = "ANDA (dir ext)"; + 8'h95 : PG1_JTA_op = "BITA (dir ext)"; + 8'h96 : PG1_JTA_op = "LDA (dir ext)"; + 8'h97 : PG1_JTA_op = "STA (dir ext)"; + 8'h98 : PG1_JTA_op = "EORA (dir ext)"; + 8'h99 : PG1_JTA_op = "ADCA (dir ext)"; + 8'h9A : PG1_JTA_op = "ORA (dir ext)"; + 8'h9B : PG1_JTA_op = "ADDA (dir ext)"; + 8'h9C : PG1_JTA_op = "CMPX (dir ext)"; + 8'h9D : PG1_JTA_op = "JSR (dir ext)"; + 8'h9E : PG1_JTA_op = "LDX (dir ext)"; + 8'h9F : PG1_JTA_op = "STX (dir ext)"; + 8'hA0 : PG1_JTA_op = "SUBA (idx)"; + 8'hA1 : PG1_JTA_op = "CMPA (idx)"; + 8'hA2 : PG1_JTA_op = "SBCA (idx)"; + 8'hA3 : PG1_JTA_op = "SUBD (idx)"; + 8'hA4 : PG1_JTA_op = "ANDA (idx)"; + 8'hA5 : PG1_JTA_op = "BITA (idx)"; + 8'hA6 : PG1_JTA_op = "LDA (idx)"; + 8'hA7 : PG1_JTA_op = "STA (idx)"; + 8'hA8 : PG1_JTA_op = "EORA (idx)"; + 8'hA9 : PG1_JTA_op = "ADCA (idx)"; + 8'hAA : PG1_JTA_op = "ORA (idx)"; + 8'hAB : PG1_JTA_op = "ADDA (idx)"; + 8'hAC : PG1_JTA_op = "CMPX (idx)"; + 8'hAD : PG1_JTA_op = "JSR (idx)"; + 8'hAE : PG1_JTA_op = "LDX (idx)"; + 8'hAF : PG1_JTA_op = "STX (idx)"; + 8'hB0 : PG1_JTA_op = "SUBA (dir ext)"; + 8'hB1 : PG1_JTA_op = "CMPA (dir ext)"; + 8'hB2 : PG1_JTA_op = "SBCA (dir ext)"; + 8'hB3 : PG1_JTA_op = "SUBD (dir ext)"; + 8'hB4 : PG1_JTA_op = "ANDA (dir ext)"; + 8'hB5 : PG1_JTA_op = "BITA (dir ext)"; + 8'hB6 : PG1_JTA_op = "LDA (dir ext)"; + 8'hB7 : PG1_JTA_op = "STA (dir ext)"; + 8'hB8 : PG1_JTA_op = "EORA (dir ext)"; + 8'hB9 : PG1_JTA_op = "ADCA (dir ext)"; + 8'hBA : PG1_JTA_op = "ORA (dir ext)"; + 8'hBB : PG1_JTA_op = "ADDA (dir ext)"; + 8'hBC : PG1_JTA_op = "CMPX (dir ext)"; + 8'hBD : PG1_JTA_op = "JSR (dir ext)"; + 8'hBE : PG1_JTA_op = "LDX (dir ext)"; + 8'hBF : PG1_JTA_op = "STX (dir ext)"; + 8'hC0 : PG1_JTA_op = "SUBB (imm)"; + 8'hC1 : PG1_JTA_op = "CMPB (imm)"; + 8'hC2 : PG1_JTA_op = "SBCB (imm)"; + 8'hC3 : PG1_JTA_op = "ADDD (imm)"; + 8'hC4 : PG1_JTA_op = "ANDB (imm)"; + 8'hC5 : PG1_JTA_op = "BITB (imm)"; + 8'hC6 : PG1_JTA_op = "LDB (imm)"; + 8'hC8 : PG1_JTA_op = "EORB (imm)"; + 8'hC9 : PG1_JTA_op = "ADCB (imm)"; + 8'hCA : PG1_JTA_op = "ORB (imm)"; + 8'hCB : PG1_JTA_op = "ADDB (imm)"; + 8'hCC : PG1_JTA_op = "LDD (imm)"; + 8'hCE : PG1_JTA_op = "LDU (imm)"; + 8'hD0 : PG1_JTA_op = "SUBB (dir ext)"; + 8'hD1 : PG1_JTA_op = "CMPB (dir ext)"; + 8'hD2 : PG1_JTA_op = "SBCB (dir ext)"; + 8'hD3 : PG1_JTA_op = "ADDD (dir ext)"; + 8'hD4 : PG1_JTA_op = "ANDB (dir ext)"; + 8'hD5 : PG1_JTA_op = "BITB (dir ext)"; + 8'hD6 : PG1_JTA_op = "LDB (dir ext)"; + 8'hD7 : PG1_JTA_op = "STB (dir ext)"; + 8'hD8 : PG1_JTA_op = "EORB (dir ext)"; + 8'hD9 : PG1_JTA_op = "ADCB (dir ext)"; + 8'hDA : PG1_JTA_op = "ORB (dir ext)"; + 8'hDB : PG1_JTA_op = "ADDB (dir ext)"; + 8'hDC : PG1_JTA_op = "LDD (dir ext)"; + 8'hDD : PG1_JTA_op = "STD (dir ext)"; + 8'hDE : PG1_JTA_op = "LDU (dir ext)"; + 8'hDF : PG1_JTA_op = "STU (dir ext)"; + 8'hE0 : PG1_JTA_op = "SUBB (idx)"; + 8'hE1 : PG1_JTA_op = "CMPB (idx)"; + 8'hE2 : PG1_JTA_op = "SBCB (idx)"; + 8'hE3 : PG1_JTA_op = "ADDD (idx)"; + 8'hE4 : PG1_JTA_op = "ANDB (idx)"; + 8'hE5 : PG1_JTA_op = "BITB (idx)"; + 8'hE6 : PG1_JTA_op = "LDB (idx)"; + 8'hE7 : PG1_JTA_op = "STB (idx)"; + 8'hE8 : PG1_JTA_op = "EORB (idx)"; + 8'hE9 : PG1_JTA_op = "ADCB (idx)"; + 8'hEA : PG1_JTA_op = "ORB (idx)"; + 8'hEB : PG1_JTA_op = "ADDB (idx)"; + 8'hEC : PG1_JTA_op = "LDD (idx)"; + 8'hED : PG1_JTA_op = "STD (idx)"; + 8'hEE : PG1_JTA_op = "LDU (idx)"; + 8'hEF : PG1_JTA_op = "STU (idx)"; + 8'hF0 : PG1_JTA_op = "SUBB (dir ext)"; + 8'hF1 : PG1_JTA_op = "CMPB (dir ext)"; + 8'hF2 : PG1_JTA_op = "SBCB (dir ext)"; + 8'hF3 : PG1_JTA_op = "ADDD (dir ext)"; + 8'hF4 : PG1_JTA_op = "ANDB (dir ext)"; + 8'hF5 : PG1_JTA_op = "BITB (dir ext)"; + 8'hF6 : PG1_JTA_op = "LDB (dir ext)"; + 8'hF7 : PG1_JTA_op = "STB (dir ext)"; + 8'hF8 : PG1_JTA_op = "EORB (dir ext)"; + 8'hF9 : PG1_JTA_op = "ADCB (dir ext)"; + 8'hFA : PG1_JTA_op = "ORB (dir ext)"; + 8'hFB : PG1_JTA_op = "ADDB (dir ext)"; + 8'hFC : PG1_JTA_op = "LDD (dir ext)"; + 8'hFD : PG1_JTA_op = "STD (dir ext)"; + 8'hFE : PG1_JTA_op = "LDU (dir ext)"; + 8'hFF : PG1_JTA_op = "STU (dir ext)"; + default : PG1_JTA_op = "invalid"; + endcase +end + +reg [(8*64):0] PG1_JTA_eq; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h03 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h04 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h06 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h07 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h08 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h09 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h0A : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h0C : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h0D : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h0E : PG1_JTA_eq = "JMP"; + 8'h0F : PG1_JTA_eq = "CLR"; + 8'h10 : PG1_JTA_eq = "NOP"; + 8'h11 : PG1_JTA_eq = "NOP"; + 8'h12 : PG1_JTA_eq = "NOP"; + 8'h14 : PG1_JTA_eq = "SAU16"; + 8'h15 : PG1_JTA_eq = "SAU16"; + 8'h16 : PG1_JTA_eq = "BRANCH"; + 8'h17 : PG1_JTA_eq = "BRANCH"; + 8'h18 : PG1_JTA_eq = "SAU16"; + 8'h19 : PG1_JTA_eq = "SAU8"; + 8'h1A : PG1_JTA_eq = "ORCC"; + 8'h1C : PG1_JTA_eq = "ANDCC"; + 8'h1D : PG1_JTA_eq = "SEX"; + 8'h1E : PG1_JTA_eq = "EXG"; + 8'h1F : PG1_JTA_eq = "TFR"; + 8'h20 : PG1_JTA_eq = "BRANCH"; + 8'h21 : PG1_JTA_eq = "BRANCH"; + 8'h22 : PG1_JTA_eq = "BRANCH"; + 8'h23 : PG1_JTA_eq = "BRANCH"; + 8'h24 : PG1_JTA_eq = "BRANCH"; + 8'h25 : PG1_JTA_eq = "BRANCH"; + 8'h26 : PG1_JTA_eq = "BRANCH"; + 8'h27 : PG1_JTA_eq = "BRANCH"; + 8'h28 : PG1_JTA_eq = "BRANCH"; + 8'h29 : PG1_JTA_eq = "BRANCH"; + 8'h2A : PG1_JTA_eq = "BRANCH"; + 8'h2B : PG1_JTA_eq = "BRANCH"; + 8'h2C : PG1_JTA_eq = "BRANCH"; + 8'h2D : PG1_JTA_eq = "BRANCH"; + 8'h2E : PG1_JTA_eq = "BRANCH"; + 8'h2F : PG1_JTA_eq = "BRANCH"; + 8'h30 : PG1_JTA_eq = "ST_INDEXED"; + 8'h31 : PG1_JTA_eq = "ST_INDEXED"; + 8'h32 : PG1_JTA_eq = "ST_INDEXED"; + 8'h33 : PG1_JTA_eq = "ST_INDEXED"; + 8'h34 : PG1_JTA_eq = "PSH"; + 8'h35 : PG1_JTA_eq = "PUL"; + 8'h36 : PG1_JTA_eq = "PSH"; + 8'h37 : PG1_JTA_eq = "PUL"; + 8'h39 : PG1_JTA_eq = "RTS"; + 8'h3A : PG1_JTA_eq = "ABX"; + 8'h3B : PG1_JTA_eq = "RTI"; + 8'h3D : PG1_JTA_eq = "SAU8"; + 8'h3F : PG1_JTA_eq = "SWI"; + 8'h40 : PG1_JTA_eq = "NEG"; + 8'h43 : PG1_JTA_eq = "COM"; + 8'h44 : PG1_JTA_eq = "LSR"; + 8'h46 : PG1_JTA_eq = "ROR"; + 8'h47 : PG1_JTA_eq = "ASR"; + 8'h48 : PG1_JTA_eq = "ASL_LSL"; + 8'h49 : PG1_JTA_eq = "ROL"; + 8'h4A : PG1_JTA_eq = "DEC"; + 8'h4C : PG1_JTA_eq = "INC"; + 8'h4D : PG1_JTA_eq = "TST"; + 8'h4F : PG1_JTA_eq = "CLR"; + 8'h50 : PG1_JTA_eq = "NEG"; + 8'h53 : PG1_JTA_eq = "COM"; + 8'h54 : PG1_JTA_eq = "LSR"; + 8'h56 : PG1_JTA_eq = "ROR"; + 8'h57 : PG1_JTA_eq = "ASR"; + 8'h58 : PG1_JTA_eq = "ASL_LSL"; + 8'h59 : PG1_JTA_eq = "ROL"; + 8'h5A : PG1_JTA_eq = "DEC"; + 8'h5C : PG1_JTA_eq = "INC"; + 8'h5D : PG1_JTA_eq = "TST"; + 8'h5F : PG1_JTA_eq = "CLR"; + 8'h60 : PG1_JTA_eq = "LD_INDEXED"; + 8'h63 : PG1_JTA_eq = "LD_INDEXED"; + 8'h64 : PG1_JTA_eq = "LD_INDEXED"; + 8'h66 : PG1_JTA_eq = "LD_INDEXED"; + 8'h67 : PG1_JTA_eq = "LD_INDEXED"; + 8'h68 : PG1_JTA_eq = "LD_INDEXED"; + 8'h69 : PG1_JTA_eq = "LD_INDEXED"; + 8'h6A : PG1_JTA_eq = "LD_INDEXED"; + 8'h6C : PG1_JTA_eq = "LD_INDEXED"; + 8'h6D : PG1_JTA_eq = "LD_INDEXED"; + 8'h6E : PG1_JTA_eq = "ST_INDEXED"; + 8'h6F : PG1_JTA_eq = "ST_INDEXED"; + 8'h70 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h73 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h74 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h76 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h77 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h78 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h79 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h7A : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h7C : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h7D : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h7E : PG1_JTA_eq = "JMP"; + 8'h7F : PG1_JTA_eq = "CLR"; + 8'h80 : PG1_JTA_eq = "SUB"; + 8'h81 : PG1_JTA_eq = "CMP"; + 8'h82 : PG1_JTA_eq = "SBC"; + 8'h83 : PG1_JTA_eq = "SUB"; + 8'h84 : PG1_JTA_eq = "AND"; + 8'h85 : PG1_JTA_eq = "BIT"; + 8'h86 : PG1_JTA_eq = "LD"; + 8'h88 : PG1_JTA_eq = "EOR"; + 8'h89 : PG1_JTA_eq = "ADC"; + 8'h8A : PG1_JTA_eq = "OR"; + 8'h8B : PG1_JTA_eq = "ADD"; + 8'h8C : PG1_JTA_eq = "CMP"; + 8'h8D : PG1_JTA_eq = "BRANCH"; + 8'h8E : PG1_JTA_eq = "LD"; + 8'h90 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h91 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h92 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h93 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h94 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h95 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h96 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h97 : PG1_JTA_eq = "ST"; + 8'h98 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h99 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h9A : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h9B : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h9C : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h9D : PG1_JTA_eq = "JSR"; + 8'h9E : PG1_JTA_eq = "LD_DIR_EXT"; + 8'h9F : PG1_JTA_eq = "ST"; + 8'hA0 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA1 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA2 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA3 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA4 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA5 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA6 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA7 : PG1_JTA_eq = "ST_INDEXED"; + 8'hA8 : PG1_JTA_eq = "LD_INDEXED"; + 8'hA9 : PG1_JTA_eq = "LD_INDEXED"; + 8'hAA : PG1_JTA_eq = "LD_INDEXED"; + 8'hAB : PG1_JTA_eq = "LD_INDEXED"; + 8'hAC : PG1_JTA_eq = "LD_INDEXED"; + 8'hAD : PG1_JTA_eq = "ST_INDEXED"; + 8'hAE : PG1_JTA_eq = "LD_INDEXED"; + 8'hAF : PG1_JTA_eq = "ST_INDEXED"; + 8'hB0 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB1 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB2 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB3 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB4 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB5 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB6 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB7 : PG1_JTA_eq = "ST"; + 8'hB8 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hB9 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hBA : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hBB : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hBC : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hBD : PG1_JTA_eq = "JSR"; + 8'hBE : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hBF : PG1_JTA_eq = "ST"; + 8'hC0 : PG1_JTA_eq = "SUB"; + 8'hC1 : PG1_JTA_eq = "CMP"; + 8'hC2 : PG1_JTA_eq = "SBC"; + 8'hC3 : PG1_JTA_eq = "ADD"; + 8'hC4 : PG1_JTA_eq = "AND"; + 8'hC5 : PG1_JTA_eq = "BIT"; + 8'hC6 : PG1_JTA_eq = "LD"; + 8'hC8 : PG1_JTA_eq = "EOR"; + 8'hC9 : PG1_JTA_eq = "ADC"; + 8'hCA : PG1_JTA_eq = "OR"; + 8'hCB : PG1_JTA_eq = "ADD"; + 8'hCC : PG1_JTA_eq = "LD"; + 8'hCE : PG1_JTA_eq = "LD"; + 8'hD0 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD1 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD2 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD3 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD4 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD5 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD6 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD7 : PG1_JTA_eq = "ST"; + 8'hD8 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hD9 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hDA : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hDB : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hDC : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hDD : PG1_JTA_eq = "ST"; + 8'hDE : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hDF : PG1_JTA_eq = "ST"; + 8'hE0 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE1 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE2 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE3 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE4 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE5 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE6 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE7 : PG1_JTA_eq = "ST_INDEXED"; + 8'hE8 : PG1_JTA_eq = "LD_INDEXED"; + 8'hE9 : PG1_JTA_eq = "LD_INDEXED"; + 8'hEA : PG1_JTA_eq = "LD_INDEXED"; + 8'hEB : PG1_JTA_eq = "LD_INDEXED"; + 8'hEC : PG1_JTA_eq = "LD_INDEXED"; + 8'hED : PG1_JTA_eq = "ST_INDEXED"; + 8'hEE : PG1_JTA_eq = "LD_INDEXED"; + 8'hEF : PG1_JTA_eq = "ST_INDEXED"; + 8'hF0 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF1 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF2 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF3 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF4 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF5 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF6 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF7 : PG1_JTA_eq = "ST"; + 8'hF8 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hF9 : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hFA : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hFB : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hFC : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hFD : PG1_JTA_eq = "ST"; + 8'hFE : PG1_JTA_eq = "LD_DIR_EXT"; + 8'hFF : PG1_JTA_eq = "ST"; + default : PG1_JTA_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTB.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTB.v new file mode 100644 index 0000000000000000000000000000000000000000..5a15995ab87d013a4c96c8a2c844504b3c342705 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_JTB.v @@ -0,0 +1,505 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg1_JTB( + input [7:0] OPCODE_I, + output reg [7:0] PG1_JTB_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTB_O = 8'h2a; // NEG NEG (dir idx ext) + 8'h03 : PG1_JTB_O = 8'h26; // COM COM (dir idx ext) + 8'h04 : PG1_JTB_O = 8'h29; // LSR LSR (dir idx ext) + 8'h06 : PG1_JTB_O = 8'h2c; // ROR ROR (dir idx ext) + 8'h07 : PG1_JTB_O = 8'h24; // ASR ASR (dir idx ext) + 8'h08 : PG1_JTB_O = 8'h23; // ASL_LSL ASL LSL (dir idx ext) + 8'h09 : PG1_JTB_O = 8'h2b; // ROL ROL (dir idx ext) + 8'h0A : PG1_JTB_O = 8'h27; // DEC DEC (dir idx ext) + 8'h0C : PG1_JTB_O = 8'h28; // INC INC (dir idx ext) + 8'h0D : PG1_JTB_O = 8'h2d; // TST TST (dir idx ext) + 8'h16 : PG1_JTB_O = 8'h30; // JMP LBRA + 8'h17 : PG1_JTB_O = 8'h31; // JSR BSR LBSR // FIXME check if smaller area + 8'h20 : PG1_JTB_O = 8'h30; // JMP BRA BRN BHI BLS + 8'h21 : PG1_JTB_O = 8'h30; // JMP BRA BRN BHI BLS + 8'h22 : PG1_JTB_O = 8'h30; // JMP BRA BRN BHI BLS + 8'h23 : PG1_JTB_O = 8'h30; // JMP BRA BRN BHI BLS + 8'h24 : PG1_JTB_O = 8'h30; // JMP BCC BCS BNE BEQ + 8'h25 : PG1_JTB_O = 8'h30; // JMP BCC BCS BNE BEQ + 8'h26 : PG1_JTB_O = 8'h30; // JMP BCC BCS BNE BEQ + 8'h27 : PG1_JTB_O = 8'h30; // JMP BCC BCS BNE BEQ + 8'h28 : PG1_JTB_O = 8'h30; // JMP BVC BVS BPL BMI + 8'h29 : PG1_JTB_O = 8'h30; // JMP BVC BVS BPL BMI + 8'h2A : PG1_JTB_O = 8'h30; // JMP BVC BVS BPL BMI + 8'h2B : PG1_JTB_O = 8'h30; // JMP BVC BVS BPL BMI + 8'h2C : PG1_JTB_O = 8'h30; // JMP BGE BLT BGT BLE + 8'h2D : PG1_JTB_O = 8'h30; // JMP BGE BLT BGT BLE + 8'h2E : PG1_JTB_O = 8'h30; // JMP BGE BLT BGT BLE + 8'h2F : PG1_JTB_O = 8'h30; // JMP BGE BLT BGT BLE + 8'h30 : PG1_JTB_O = 8'hb; // LEA_XY LEAX(inh) + 8'h31 : PG1_JTB_O = 8'hb; // LEA_XY LEAY(inh) + 8'h32 : PG1_JTB_O = 8'ha; // LEA_SU LEAS(inh) + 8'h33 : PG1_JTB_O = 8'ha; // LEA_SU LEAU(inh) + 8'h60 : PG1_JTB_O = 8'h2a; // NEG NEG (dir idx ext) + 8'h63 : PG1_JTB_O = 8'h26; // COM COM (dir idx ext) + 8'h64 : PG1_JTB_O = 8'h29; // LSR LSR (dir idx ext) + 8'h66 : PG1_JTB_O = 8'h2c; // ROR ROR (dir idx ext) + 8'h67 : PG1_JTB_O = 8'h24; // ASR ASR (dir idx ext) + 8'h68 : PG1_JTB_O = 8'h23; // ASL_LSL ASL LSL (dir idx ext) + 8'h69 : PG1_JTB_O = 8'h2b; // ROL ROL (dir idx ext) + 8'h6A : PG1_JTB_O = 8'h27; // DEC DEC (dir idx ext) + 8'h6C : PG1_JTB_O = 8'h28; // INC INC (dir idx ext) + 8'h6D : PG1_JTB_O = 8'h2d; // TST TST (dir idx ext) + 8'h6E : PG1_JTB_O = 8'h30; // JMP JMP (idx) + 8'h6F : PG1_JTB_O = 8'h25; // CLR CLR (idx) + 8'h70 : PG1_JTB_O = 8'h2a; // NEG NEG (dir idx ext) + 8'h73 : PG1_JTB_O = 8'h26; // COM COM (dir idx ext) + 8'h74 : PG1_JTB_O = 8'h29; // LSR LSR (dir idx ext) + 8'h76 : PG1_JTB_O = 8'h2c; // ROR ROR (dir idx ext) + 8'h77 : PG1_JTB_O = 8'h24; // ASR ASR (dir idx ext) + 8'h78 : PG1_JTB_O = 8'h23; // ASL_LSL ASL LSL (dir idx ext) + 8'h79 : PG1_JTB_O = 8'h2b; // ROL ROL (dir idx ext) + 8'h7A : PG1_JTB_O = 8'h27; // DEC DEC (dir idx ext) + 8'h7C : PG1_JTB_O = 8'h28; // INC INC (dir idx ext) + 8'h7D : PG1_JTB_O = 8'h2d; // TST TST (dir idx ext) + 8'h8D : PG1_JTB_O = 8'h31; // JSR BSR LBSR // FIXME check if smaller area + 8'h90 : PG1_JTB_O = 8'h21; // SUB SUBA (dir idx ext) + 8'h91 : PG1_JTB_O = 8'h1b; // CMP CMPA (dir idx ext) + 8'h92 : PG1_JTB_O = 8'h20; // SBC SBCA (dir idx ext) + 8'h93 : PG1_JTB_O = 8'h21; // SUB SUBD (dir idx ext) + 8'h94 : PG1_JTB_O = 8'h18; // AND ANDA (dir idx ext) + 8'h95 : PG1_JTB_O = 8'h1a; // BIT BITA (dir idx ext) + 8'h96 : PG1_JTB_O = 8'h1d; // LD LDA (dir idx ext) + 8'h98 : PG1_JTB_O = 8'h1c; // EOR EORA (dir idx ext) + 8'h99 : PG1_JTB_O = 8'h16; // ADC ADCA (dir idx ext) + 8'h9A : PG1_JTB_O = 8'h1e; // OR ORA (dir idx ext) + 8'h9B : PG1_JTB_O = 8'h17; // ADD ADDA (dir idx ext) + 8'h9C : PG1_JTB_O = 8'h1b; // CMP CMPX (dir idx ext) + 8'h9E : PG1_JTB_O = 8'h1d; // LD LDX (dir idx ext) + 8'hA0 : PG1_JTB_O = 8'h21; // SUB SUBA (dir idx ext) + 8'hA1 : PG1_JTB_O = 8'h1b; // CMP CMPA (dir idx ext) + 8'hA2 : PG1_JTB_O = 8'h20; // SBC SBCA (dir idx ext) + 8'hA3 : PG1_JTB_O = 8'h21; // SUB SUBD (dir idx ext) + 8'hA4 : PG1_JTB_O = 8'h18; // AND ANDA (dir idx ext) + 8'hA5 : PG1_JTB_O = 8'h1a; // BIT BITA (dir idx ext) + 8'hA6 : PG1_JTB_O = 8'h1d; // LD LDA (dir idx ext) + 8'hA7 : PG1_JTB_O = 8'h22; // ST STA (idx) + 8'hA8 : PG1_JTB_O = 8'h1c; // EOR EORA (dir idx ext) + 8'hA9 : PG1_JTB_O = 8'h16; // ADC ADCA (dir idx ext) + 8'hAA : PG1_JTB_O = 8'h1e; // OR ORA (dir idx ext) + 8'hAB : PG1_JTB_O = 8'h17; // ADD ADDA (dir idx ext) + 8'hAC : PG1_JTB_O = 8'h1b; // CMP CMPX (dir idx ext) + 8'hAD : PG1_JTB_O = 8'h31; // JSR JSR (idx) + 8'hAE : PG1_JTB_O = 8'h1d; // LD LDX (dir idx ext) + 8'hAF : PG1_JTB_O = 8'h22; // ST STX (idx) + 8'hB0 : PG1_JTB_O = 8'h21; // SUB SUBA (dir idx ext) + 8'hB1 : PG1_JTB_O = 8'h1b; // CMP CMPA (dir idx ext) + 8'hB2 : PG1_JTB_O = 8'h20; // SBC SBCA (dir idx ext) + 8'hB3 : PG1_JTB_O = 8'h21; // SUB SUBD (dir idx ext) + 8'hB4 : PG1_JTB_O = 8'h18; // AND ANDA (dir idx ext) + 8'hB5 : PG1_JTB_O = 8'h1a; // BIT BITA (dir idx ext) + 8'hB6 : PG1_JTB_O = 8'h1d; // LD LDA (dir idx ext) + 8'hB8 : PG1_JTB_O = 8'h1c; // EOR EORA (dir idx ext) + 8'hB9 : PG1_JTB_O = 8'h16; // ADC ADCA (dir idx ext) + 8'hBA : PG1_JTB_O = 8'h1e; // OR ORA (dir idx ext) + 8'hBB : PG1_JTB_O = 8'h17; // ADD ADDA (dir idx ext) + 8'hBC : PG1_JTB_O = 8'h1b; // CMP CMPX (dir idx ext) + 8'hBE : PG1_JTB_O = 8'h1d; // LD LDX (dir idx ext) + 8'hD0 : PG1_JTB_O = 8'h21; // SUB SUBB (dir idx ext) + 8'hD1 : PG1_JTB_O = 8'h1b; // CMP CMPB (dir idx ext) + 8'hD2 : PG1_JTB_O = 8'h20; // SBC SBCB (dir idx ext) + 8'hD3 : PG1_JTB_O = 8'h17; // ADD ADDD (dir idx ext) + 8'hD4 : PG1_JTB_O = 8'h18; // AND ANDB (dir idx ext) + 8'hD5 : PG1_JTB_O = 8'h1a; // BIT BITB (dir idx ext) + 8'hD6 : PG1_JTB_O = 8'h1d; // LD LDB (dir idx ext) + 8'hD8 : PG1_JTB_O = 8'h1c; // EOR EORB (dir idx ext) + 8'hD9 : PG1_JTB_O = 8'h16; // ADC ADCB (dir idx ext) + 8'hDA : PG1_JTB_O = 8'h1e; // OR ORB (dir idx ext) + 8'hDB : PG1_JTB_O = 8'h17; // ADD ADDB (dir idx ext) + 8'hDC : PG1_JTB_O = 8'h1d; // LD LDD (dir idx ext) + 8'hDE : PG1_JTB_O = 8'h1d; // LD LDU (dir idx ext) + 8'hE0 : PG1_JTB_O = 8'h21; // SUB SUBB (dir idx ext) + 8'hE1 : PG1_JTB_O = 8'h1b; // CMP CMPB (dir idx ext) + 8'hE2 : PG1_JTB_O = 8'h20; // SBC SBCB (dir idx ext) + 8'hE3 : PG1_JTB_O = 8'h17; // ADD ADDD (dir idx ext) + 8'hE4 : PG1_JTB_O = 8'h18; // AND ANDB (dir idx ext) + 8'hE5 : PG1_JTB_O = 8'h1a; // BIT BITB (dir idx ext) + 8'hE6 : PG1_JTB_O = 8'h1d; // LD LDB (dir idx ext) + 8'hE7 : PG1_JTB_O = 8'h22; // ST STB (idx) + 8'hE8 : PG1_JTB_O = 8'h1c; // EOR EORB (dir idx ext) + 8'hE9 : PG1_JTB_O = 8'h16; // ADC ADCB (dir idx ext) + 8'hEA : PG1_JTB_O = 8'h1e; // OR ORB (dir idx ext) + 8'hEB : PG1_JTB_O = 8'h17; // ADD ADDB (dir idx ext) + 8'hEC : PG1_JTB_O = 8'h1d; // LD LDD (dir idx ext) + 8'hED : PG1_JTB_O = 8'h22; // ST STD (idx) + 8'hEE : PG1_JTB_O = 8'h1d; // LD LDU (dir idx ext) + 8'hEF : PG1_JTB_O = 8'h22; // ST STU (idx) + 8'hF0 : PG1_JTB_O = 8'h21; // SUB SUBB (dir idx ext) + 8'hF1 : PG1_JTB_O = 8'h1b; // CMP CMPB (dir idx ext) + 8'hF2 : PG1_JTB_O = 8'h20; // SBC SBCB (dir idx ext) + 8'hF3 : PG1_JTB_O = 8'h17; // ADD ADDD (dir idx ext) + 8'hF4 : PG1_JTB_O = 8'h18; // AND ANDB (dir idx ext) + 8'hF5 : PG1_JTB_O = 8'h1a; // BIT BITB (dir idx ext) + 8'hF6 : PG1_JTB_O = 8'h1d; // LD LDB (dir idx ext) + 8'hF8 : PG1_JTB_O = 8'h1c; // EOR EORB (dir idx ext) + 8'hF9 : PG1_JTB_O = 8'h16; // ADC ADCB (dir idx ext) + 8'hFA : PG1_JTB_O = 8'h1e; // OR ORB (dir idx ext) + 8'hFB : PG1_JTB_O = 8'h17; // ADD ADDB (dir idx ext) + 8'hFC : PG1_JTB_O = 8'h1d; // LD LDD (dir idx ext) + 8'hFE : PG1_JTB_O = 8'h1d; // LD LDU (dir idx ext) + default : PG1_JTB_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG1_JTB_op; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTB_op = "NEG (dir idx ext)"; + 8'h03 : PG1_JTB_op = "COM (dir idx ext)"; + 8'h04 : PG1_JTB_op = "LSR (dir idx ext)"; + 8'h06 : PG1_JTB_op = "ROR (dir idx ext)"; + 8'h07 : PG1_JTB_op = "ASR (dir idx ext)"; + 8'h08 : PG1_JTB_op = "ASL LSL (dir idx ext)"; + 8'h09 : PG1_JTB_op = "ROL (dir idx ext)"; + 8'h0A : PG1_JTB_op = "DEC (dir idx ext)"; + 8'h0C : PG1_JTB_op = "INC (dir idx ext)"; + 8'h0D : PG1_JTB_op = "TST (dir idx ext)"; + 8'h16 : PG1_JTB_op = "LBRA"; + 8'h17 : PG1_JTB_op = "BSR LBSR // FIXME check if smaller area"; + 8'h20 : PG1_JTB_op = "BRA BRN BHI BLS"; + 8'h21 : PG1_JTB_op = "BRA BRN BHI BLS"; + 8'h22 : PG1_JTB_op = "BRA BRN BHI BLS"; + 8'h23 : PG1_JTB_op = "BRA BRN BHI BLS"; + 8'h24 : PG1_JTB_op = "BCC BCS BNE BEQ"; + 8'h25 : PG1_JTB_op = "BCC BCS BNE BEQ"; + 8'h26 : PG1_JTB_op = "BCC BCS BNE BEQ"; + 8'h27 : PG1_JTB_op = "BCC BCS BNE BEQ"; + 8'h28 : PG1_JTB_op = "BVC BVS BPL BMI"; + 8'h29 : PG1_JTB_op = "BVC BVS BPL BMI"; + 8'h2A : PG1_JTB_op = "BVC BVS BPL BMI"; + 8'h2B : PG1_JTB_op = "BVC BVS BPL BMI"; + 8'h2C : PG1_JTB_op = "BGE BLT BGT BLE"; + 8'h2D : PG1_JTB_op = "BGE BLT BGT BLE"; + 8'h2E : PG1_JTB_op = "BGE BLT BGT BLE"; + 8'h2F : PG1_JTB_op = "BGE BLT BGT BLE"; + 8'h30 : PG1_JTB_op = "LEAX(inh)"; + 8'h31 : PG1_JTB_op = "LEAY(inh)"; + 8'h32 : PG1_JTB_op = "LEAS(inh)"; + 8'h33 : PG1_JTB_op = "LEAU(inh)"; + 8'h60 : PG1_JTB_op = "NEG (dir idx ext)"; + 8'h63 : PG1_JTB_op = "COM (dir idx ext)"; + 8'h64 : PG1_JTB_op = "LSR (dir idx ext)"; + 8'h66 : PG1_JTB_op = "ROR (dir idx ext)"; + 8'h67 : PG1_JTB_op = "ASR (dir idx ext)"; + 8'h68 : PG1_JTB_op = "ASL LSL (dir idx ext)"; + 8'h69 : PG1_JTB_op = "ROL (dir idx ext)"; + 8'h6A : PG1_JTB_op = "DEC (dir idx ext)"; + 8'h6C : PG1_JTB_op = "INC (dir idx ext)"; + 8'h6D : PG1_JTB_op = "TST (dir idx ext)"; + 8'h6E : PG1_JTB_op = "JMP (idx)"; + 8'h6F : PG1_JTB_op = "CLR (idx)"; + 8'h70 : PG1_JTB_op = "NEG (dir idx ext)"; + 8'h73 : PG1_JTB_op = "COM (dir idx ext)"; + 8'h74 : PG1_JTB_op = "LSR (dir idx ext)"; + 8'h76 : PG1_JTB_op = "ROR (dir idx ext)"; + 8'h77 : PG1_JTB_op = "ASR (dir idx ext)"; + 8'h78 : PG1_JTB_op = "ASL LSL (dir idx ext)"; + 8'h79 : PG1_JTB_op = "ROL (dir idx ext)"; + 8'h7A : PG1_JTB_op = "DEC (dir idx ext)"; + 8'h7C : PG1_JTB_op = "INC (dir idx ext)"; + 8'h7D : PG1_JTB_op = "TST (dir idx ext)"; + 8'h8D : PG1_JTB_op = "BSR LBSR // FIXME check if smaller area"; + 8'h90 : PG1_JTB_op = "SUBA (dir idx ext)"; + 8'h91 : PG1_JTB_op = "CMPA (dir idx ext)"; + 8'h92 : PG1_JTB_op = "SBCA (dir idx ext)"; + 8'h93 : PG1_JTB_op = "SUBD (dir idx ext)"; + 8'h94 : PG1_JTB_op = "ANDA (dir idx ext)"; + 8'h95 : PG1_JTB_op = "BITA (dir idx ext)"; + 8'h96 : PG1_JTB_op = "LDA (dir idx ext)"; + 8'h98 : PG1_JTB_op = "EORA (dir idx ext)"; + 8'h99 : PG1_JTB_op = "ADCA (dir idx ext)"; + 8'h9A : PG1_JTB_op = "ORA (dir idx ext)"; + 8'h9B : PG1_JTB_op = "ADDA (dir idx ext)"; + 8'h9C : PG1_JTB_op = "CMPX (dir idx ext)"; + 8'h9E : PG1_JTB_op = "LDX (dir idx ext)"; + 8'hA0 : PG1_JTB_op = "SUBA (dir idx ext)"; + 8'hA1 : PG1_JTB_op = "CMPA (dir idx ext)"; + 8'hA2 : PG1_JTB_op = "SBCA (dir idx ext)"; + 8'hA3 : PG1_JTB_op = "SUBD (dir idx ext)"; + 8'hA4 : PG1_JTB_op = "ANDA (dir idx ext)"; + 8'hA5 : PG1_JTB_op = "BITA (dir idx ext)"; + 8'hA6 : PG1_JTB_op = "LDA (dir idx ext)"; + 8'hA7 : PG1_JTB_op = "STA (idx)"; + 8'hA8 : PG1_JTB_op = "EORA (dir idx ext)"; + 8'hA9 : PG1_JTB_op = "ADCA (dir idx ext)"; + 8'hAA : PG1_JTB_op = "ORA (dir idx ext)"; + 8'hAB : PG1_JTB_op = "ADDA (dir idx ext)"; + 8'hAC : PG1_JTB_op = "CMPX (dir idx ext)"; + 8'hAD : PG1_JTB_op = "JSR (idx)"; + 8'hAE : PG1_JTB_op = "LDX (dir idx ext)"; + 8'hAF : PG1_JTB_op = "STX (idx)"; + 8'hB0 : PG1_JTB_op = "SUBA (dir idx ext)"; + 8'hB1 : PG1_JTB_op = "CMPA (dir idx ext)"; + 8'hB2 : PG1_JTB_op = "SBCA (dir idx ext)"; + 8'hB3 : PG1_JTB_op = "SUBD (dir idx ext)"; + 8'hB4 : PG1_JTB_op = "ANDA (dir idx ext)"; + 8'hB5 : PG1_JTB_op = "BITA (dir idx ext)"; + 8'hB6 : PG1_JTB_op = "LDA (dir idx ext)"; + 8'hB8 : PG1_JTB_op = "EORA (dir idx ext)"; + 8'hB9 : PG1_JTB_op = "ADCA (dir idx ext)"; + 8'hBA : PG1_JTB_op = "ORA (dir idx ext)"; + 8'hBB : PG1_JTB_op = "ADDA (dir idx ext)"; + 8'hBC : PG1_JTB_op = "CMPX (dir idx ext)"; + 8'hBE : PG1_JTB_op = "LDX (dir idx ext)"; + 8'hD0 : PG1_JTB_op = "SUBB (dir idx ext)"; + 8'hD1 : PG1_JTB_op = "CMPB (dir idx ext)"; + 8'hD2 : PG1_JTB_op = "SBCB (dir idx ext)"; + 8'hD3 : PG1_JTB_op = "ADDD (dir idx ext)"; + 8'hD4 : PG1_JTB_op = "ANDB (dir idx ext)"; + 8'hD5 : PG1_JTB_op = "BITB (dir idx ext)"; + 8'hD6 : PG1_JTB_op = "LDB (dir idx ext)"; + 8'hD8 : PG1_JTB_op = "EORB (dir idx ext)"; + 8'hD9 : PG1_JTB_op = "ADCB (dir idx ext)"; + 8'hDA : PG1_JTB_op = "ORB (dir idx ext)"; + 8'hDB : PG1_JTB_op = "ADDB (dir idx ext)"; + 8'hDC : PG1_JTB_op = "LDD (dir idx ext)"; + 8'hDE : PG1_JTB_op = "LDU (dir idx ext)"; + 8'hE0 : PG1_JTB_op = "SUBB (dir idx ext)"; + 8'hE1 : PG1_JTB_op = "CMPB (dir idx ext)"; + 8'hE2 : PG1_JTB_op = "SBCB (dir idx ext)"; + 8'hE3 : PG1_JTB_op = "ADDD (dir idx ext)"; + 8'hE4 : PG1_JTB_op = "ANDB (dir idx ext)"; + 8'hE5 : PG1_JTB_op = "BITB (dir idx ext)"; + 8'hE6 : PG1_JTB_op = "LDB (dir idx ext)"; + 8'hE7 : PG1_JTB_op = "STB (idx)"; + 8'hE8 : PG1_JTB_op = "EORB (dir idx ext)"; + 8'hE9 : PG1_JTB_op = "ADCB (dir idx ext)"; + 8'hEA : PG1_JTB_op = "ORB (dir idx ext)"; + 8'hEB : PG1_JTB_op = "ADDB (dir idx ext)"; + 8'hEC : PG1_JTB_op = "LDD (dir idx ext)"; + 8'hED : PG1_JTB_op = "STD (idx)"; + 8'hEE : PG1_JTB_op = "LDU (dir idx ext)"; + 8'hEF : PG1_JTB_op = "STU (idx)"; + 8'hF0 : PG1_JTB_op = "SUBB (dir idx ext)"; + 8'hF1 : PG1_JTB_op = "CMPB (dir idx ext)"; + 8'hF2 : PG1_JTB_op = "SBCB (dir idx ext)"; + 8'hF3 : PG1_JTB_op = "ADDD (dir idx ext)"; + 8'hF4 : PG1_JTB_op = "ANDB (dir idx ext)"; + 8'hF5 : PG1_JTB_op = "BITB (dir idx ext)"; + 8'hF6 : PG1_JTB_op = "LDB (dir idx ext)"; + 8'hF8 : PG1_JTB_op = "EORB (dir idx ext)"; + 8'hF9 : PG1_JTB_op = "ADCB (dir idx ext)"; + 8'hFA : PG1_JTB_op = "ORB (dir idx ext)"; + 8'hFB : PG1_JTB_op = "ADDB (dir idx ext)"; + 8'hFC : PG1_JTB_op = "LDD (dir idx ext)"; + 8'hFE : PG1_JTB_op = "LDU (dir idx ext)"; + default : PG1_JTB_op = "invalid"; + endcase +end + +reg [(8*64):0] PG1_JTB_eq; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_JTB_eq = "NEG"; + 8'h03 : PG1_JTB_eq = "COM"; + 8'h04 : PG1_JTB_eq = "LSR"; + 8'h06 : PG1_JTB_eq = "ROR"; + 8'h07 : PG1_JTB_eq = "ASR"; + 8'h08 : PG1_JTB_eq = "ASL_LSL"; + 8'h09 : PG1_JTB_eq = "ROL"; + 8'h0A : PG1_JTB_eq = "DEC"; + 8'h0C : PG1_JTB_eq = "INC"; + 8'h0D : PG1_JTB_eq = "TST"; + 8'h16 : PG1_JTB_eq = "JMP"; + 8'h17 : PG1_JTB_eq = "JSR"; + 8'h20 : PG1_JTB_eq = "JMP"; + 8'h21 : PG1_JTB_eq = "JMP"; + 8'h22 : PG1_JTB_eq = "JMP"; + 8'h23 : PG1_JTB_eq = "JMP"; + 8'h24 : PG1_JTB_eq = "JMP"; + 8'h25 : PG1_JTB_eq = "JMP"; + 8'h26 : PG1_JTB_eq = "JMP"; + 8'h27 : PG1_JTB_eq = "JMP"; + 8'h28 : PG1_JTB_eq = "JMP"; + 8'h29 : PG1_JTB_eq = "JMP"; + 8'h2A : PG1_JTB_eq = "JMP"; + 8'h2B : PG1_JTB_eq = "JMP"; + 8'h2C : PG1_JTB_eq = "JMP"; + 8'h2D : PG1_JTB_eq = "JMP"; + 8'h2E : PG1_JTB_eq = "JMP"; + 8'h2F : PG1_JTB_eq = "JMP"; + 8'h30 : PG1_JTB_eq = "LEA_XY"; + 8'h31 : PG1_JTB_eq = "LEA_XY"; + 8'h32 : PG1_JTB_eq = "LEA_SU"; + 8'h33 : PG1_JTB_eq = "LEA_SU"; + 8'h60 : PG1_JTB_eq = "NEG"; + 8'h63 : PG1_JTB_eq = "COM"; + 8'h64 : PG1_JTB_eq = "LSR"; + 8'h66 : PG1_JTB_eq = "ROR"; + 8'h67 : PG1_JTB_eq = "ASR"; + 8'h68 : PG1_JTB_eq = "ASL_LSL"; + 8'h69 : PG1_JTB_eq = "ROL"; + 8'h6A : PG1_JTB_eq = "DEC"; + 8'h6C : PG1_JTB_eq = "INC"; + 8'h6D : PG1_JTB_eq = "TST"; + 8'h6E : PG1_JTB_eq = "JMP"; + 8'h6F : PG1_JTB_eq = "CLR"; + 8'h70 : PG1_JTB_eq = "NEG"; + 8'h73 : PG1_JTB_eq = "COM"; + 8'h74 : PG1_JTB_eq = "LSR"; + 8'h76 : PG1_JTB_eq = "ROR"; + 8'h77 : PG1_JTB_eq = "ASR"; + 8'h78 : PG1_JTB_eq = "ASL_LSL"; + 8'h79 : PG1_JTB_eq = "ROL"; + 8'h7A : PG1_JTB_eq = "DEC"; + 8'h7C : PG1_JTB_eq = "INC"; + 8'h7D : PG1_JTB_eq = "TST"; + 8'h8D : PG1_JTB_eq = "JSR"; + 8'h90 : PG1_JTB_eq = "SUB"; + 8'h91 : PG1_JTB_eq = "CMP"; + 8'h92 : PG1_JTB_eq = "SBC"; + 8'h93 : PG1_JTB_eq = "SUB"; + 8'h94 : PG1_JTB_eq = "AND"; + 8'h95 : PG1_JTB_eq = "BIT"; + 8'h96 : PG1_JTB_eq = "LD"; + 8'h98 : PG1_JTB_eq = "EOR"; + 8'h99 : PG1_JTB_eq = "ADC"; + 8'h9A : PG1_JTB_eq = "OR"; + 8'h9B : PG1_JTB_eq = "ADD"; + 8'h9C : PG1_JTB_eq = "CMP"; + 8'h9E : PG1_JTB_eq = "LD"; + 8'hA0 : PG1_JTB_eq = "SUB"; + 8'hA1 : PG1_JTB_eq = "CMP"; + 8'hA2 : PG1_JTB_eq = "SBC"; + 8'hA3 : PG1_JTB_eq = "SUB"; + 8'hA4 : PG1_JTB_eq = "AND"; + 8'hA5 : PG1_JTB_eq = "BIT"; + 8'hA6 : PG1_JTB_eq = "LD"; + 8'hA7 : PG1_JTB_eq = "ST"; + 8'hA8 : PG1_JTB_eq = "EOR"; + 8'hA9 : PG1_JTB_eq = "ADC"; + 8'hAA : PG1_JTB_eq = "OR"; + 8'hAB : PG1_JTB_eq = "ADD"; + 8'hAC : PG1_JTB_eq = "CMP"; + 8'hAD : PG1_JTB_eq = "JSR"; + 8'hAE : PG1_JTB_eq = "LD"; + 8'hAF : PG1_JTB_eq = "ST"; + 8'hB0 : PG1_JTB_eq = "SUB"; + 8'hB1 : PG1_JTB_eq = "CMP"; + 8'hB2 : PG1_JTB_eq = "SBC"; + 8'hB3 : PG1_JTB_eq = "SUB"; + 8'hB4 : PG1_JTB_eq = "AND"; + 8'hB5 : PG1_JTB_eq = "BIT"; + 8'hB6 : PG1_JTB_eq = "LD"; + 8'hB8 : PG1_JTB_eq = "EOR"; + 8'hB9 : PG1_JTB_eq = "ADC"; + 8'hBA : PG1_JTB_eq = "OR"; + 8'hBB : PG1_JTB_eq = "ADD"; + 8'hBC : PG1_JTB_eq = "CMP"; + 8'hBE : PG1_JTB_eq = "LD"; + 8'hD0 : PG1_JTB_eq = "SUB"; + 8'hD1 : PG1_JTB_eq = "CMP"; + 8'hD2 : PG1_JTB_eq = "SBC"; + 8'hD3 : PG1_JTB_eq = "ADD"; + 8'hD4 : PG1_JTB_eq = "AND"; + 8'hD5 : PG1_JTB_eq = "BIT"; + 8'hD6 : PG1_JTB_eq = "LD"; + 8'hD8 : PG1_JTB_eq = "EOR"; + 8'hD9 : PG1_JTB_eq = "ADC"; + 8'hDA : PG1_JTB_eq = "OR"; + 8'hDB : PG1_JTB_eq = "ADD"; + 8'hDC : PG1_JTB_eq = "LD"; + 8'hDE : PG1_JTB_eq = "LD"; + 8'hE0 : PG1_JTB_eq = "SUB"; + 8'hE1 : PG1_JTB_eq = "CMP"; + 8'hE2 : PG1_JTB_eq = "SBC"; + 8'hE3 : PG1_JTB_eq = "ADD"; + 8'hE4 : PG1_JTB_eq = "AND"; + 8'hE5 : PG1_JTB_eq = "BIT"; + 8'hE6 : PG1_JTB_eq = "LD"; + 8'hE7 : PG1_JTB_eq = "ST"; + 8'hE8 : PG1_JTB_eq = "EOR"; + 8'hE9 : PG1_JTB_eq = "ADC"; + 8'hEA : PG1_JTB_eq = "OR"; + 8'hEB : PG1_JTB_eq = "ADD"; + 8'hEC : PG1_JTB_eq = "LD"; + 8'hED : PG1_JTB_eq = "ST"; + 8'hEE : PG1_JTB_eq = "LD"; + 8'hEF : PG1_JTB_eq = "ST"; + 8'hF0 : PG1_JTB_eq = "SUB"; + 8'hF1 : PG1_JTB_eq = "CMP"; + 8'hF2 : PG1_JTB_eq = "SBC"; + 8'hF3 : PG1_JTB_eq = "ADD"; + 8'hF4 : PG1_JTB_eq = "AND"; + 8'hF5 : PG1_JTB_eq = "BIT"; + 8'hF6 : PG1_JTB_eq = "LD"; + 8'hF8 : PG1_JTB_eq = "EOR"; + 8'hF9 : PG1_JTB_eq = "ADC"; + 8'hFA : PG1_JTB_eq = "OR"; + 8'hFB : PG1_JTB_eq = "ADD"; + 8'hFC : PG1_JTB_eq = "LD"; + 8'hFE : PG1_JTB_eq = "LD"; + default : PG1_JTB_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R1.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R1.v new file mode 100644 index 0000000000000000000000000000000000000000..835cc74fd699fece789ea76c2d65ad194dd885ac --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R1.v @@ -0,0 +1,733 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R1_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg1_R1( + input [7:0] OPCODE_I, + output reg [3:0] PG1_R1_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R1_O = 4'hd; // DMEM_RD NEG (dir idx ext) sets 8bit width + 8'h03 : PG1_R1_O = 4'hd; // DMEM_RD COM (dir idx ext) sets 8bit width + 8'h04 : PG1_R1_O = 4'hd; // DMEM_RD LSR (dir idx ext) + 8'h06 : PG1_R1_O = 4'hd; // DMEM_RD ROR (dir idx ext) + 8'h07 : PG1_R1_O = 4'hd; // DMEM_RD ASR (dir idx ext) + 8'h08 : PG1_R1_O = 4'hd; // DMEM_RD ASL LSL (dir idx ext) + 8'h09 : PG1_R1_O = 4'hd; // DMEM_RD ROL (dir idx ext) + 8'h0A : PG1_R1_O = 4'hd; // DMEM_RD DEC (dir idx ext) + 8'h0C : PG1_R1_O = 4'hd; // DMEM_RD INC (dir idx ext) + 8'h0D : PG1_R1_O = 4'hd; // DMEM_RD TST (dir idx ext) + 8'h0E : PG1_R1_O = 4'h5; // PC JMP (dir ext) + 8'h0F : PG1_R1_O = 4'hd; // DMEM_RD CLR (dir ext) sets 8bit width + 8'h14 : PG1_R1_O = 4'h0; // D EMUL (inh) + 8'h15 : PG1_R1_O = 4'h0; // D EMULS (inh) + 8'h16 : PG1_R1_O = 4'h5; // PC LBRA + 8'h17 : PG1_R1_O = 4'h5; // PC BSR LBSR + 8'h18 : PG1_R1_O = 4'h1; // X IDIV (inh) + 8'h19 : PG1_R1_O = 4'h0; // D DAA (inh) + 8'h1A : PG1_R1_O = 4'ha; // CCR ORCC (imm) + 8'h1C : PG1_R1_O = 4'ha; // CCR ANDCC (imm) + 8'h1D : PG1_R1_O = 4'h0; // D SEX(inh) + 8'h20 : PG1_R1_O = 4'h5; // PC BRA BRN BHI BLS + 8'h21 : PG1_R1_O = 4'h5; // PC BRA BRN BHI BLS + 8'h22 : PG1_R1_O = 4'h5; // PC BRA BRN BHI BLS + 8'h23 : PG1_R1_O = 4'h5; // PC BRA BRN BHI BLS + 8'h24 : PG1_R1_O = 4'h5; // PC BCC BCS BNE BEQ + 8'h25 : PG1_R1_O = 4'h5; // PC BCC BCS BNE BEQ + 8'h26 : PG1_R1_O = 4'h5; // PC BCC BCS BNE BEQ + 8'h27 : PG1_R1_O = 4'h5; // PC BCC BCS BNE BEQ + 8'h28 : PG1_R1_O = 4'h5; // PC BVC BVS BPL BMI + 8'h29 : PG1_R1_O = 4'h5; // PC BVC BVS BPL BMI + 8'h2A : PG1_R1_O = 4'h5; // PC BVC BVS BPL BMI + 8'h2B : PG1_R1_O = 4'h5; // PC BVC BVS BPL BMI + 8'h2C : PG1_R1_O = 4'h5; // PC BGE BLT BGT BLE + 8'h2D : PG1_R1_O = 4'h5; // PC BGE BLT BGT BLE + 8'h2E : PG1_R1_O = 4'h5; // PC BGE BLT BGT BLE + 8'h2F : PG1_R1_O = 4'h5; // PC BGE BLT BGT BLE + 8'h30 : PG1_R1_O = 4'h1; // X LEAX(inh) + 8'h31 : PG1_R1_O = 4'h2; // Y LEAY(inh) + 8'h32 : PG1_R1_O = 4'h4; // S LEAS(inh) + 8'h33 : PG1_R1_O = 4'h3; // U LEAU(inh) + 8'h39 : PG1_R1_O = 4'h5; // PC RTS + 8'h3A : PG1_R1_O = 4'h1; // X ABX(inh) + 8'h3B : PG1_R1_O = 4'h5; // PC RTI + 8'h3D : PG1_R1_O = 4'h0; // D MUL (inh) + 8'h3F : PG1_R1_O = 4'h5; // PC SWI + 8'h40 : PG1_R1_O = 4'h8; // A NEGA (inh) + 8'h43 : PG1_R1_O = 4'h8; // A COMA (inh) + 8'h44 : PG1_R1_O = 4'h8; // A LSRA (inh) + 8'h46 : PG1_R1_O = 4'h8; // A RORA (inh) + 8'h47 : PG1_R1_O = 4'h8; // A ASRA (inh) + 8'h48 : PG1_R1_O = 4'h8; // A ASLA LSLA (inh) + 8'h49 : PG1_R1_O = 4'h8; // A ROLA (inh) + 8'h4A : PG1_R1_O = 4'h8; // A DECA (inh) + 8'h4C : PG1_R1_O = 4'h8; // A INCA (inh) + 8'h4D : PG1_R1_O = 4'h8; // A TSTA (inh) + 8'h4F : PG1_R1_O = 4'h8; // A CLRA (inh) + 8'h50 : PG1_R1_O = 4'h9; // B NEGB (inh) + 8'h53 : PG1_R1_O = 4'h9; // B COMB (inh) + 8'h54 : PG1_R1_O = 4'h9; // B LSRB (inh) + 8'h56 : PG1_R1_O = 4'h9; // B RORB (inh) + 8'h57 : PG1_R1_O = 4'h9; // B ASRB (inh) + 8'h58 : PG1_R1_O = 4'h9; // B ASLB LSLB (inh) + 8'h59 : PG1_R1_O = 4'h9; // B ROLB (inh) + 8'h5A : PG1_R1_O = 4'h9; // B DECB (inh) + 8'h5C : PG1_R1_O = 4'h9; // B INCB (inh) + 8'h5D : PG1_R1_O = 4'h9; // B TSTB (inh) + 8'h5F : PG1_R1_O = 4'h9; // B CLRB (inh) + 8'h60 : PG1_R1_O = 4'hd; // DMEM_RD NEG (dir idx ext) sets 8bit width + 8'h63 : PG1_R1_O = 4'hd; // DMEM_RD COM (dir idx ext) sets 8bit width + 8'h64 : PG1_R1_O = 4'hd; // DMEM_RD LSR (dir idx ext) + 8'h66 : PG1_R1_O = 4'hd; // DMEM_RD ROR (dir idx ext) + 8'h67 : PG1_R1_O = 4'hd; // DMEM_RD ASR (dir idx ext) + 8'h68 : PG1_R1_O = 4'hd; // DMEM_RD ASL LSL (dir idx ext) + 8'h69 : PG1_R1_O = 4'hd; // DMEM_RD ROL (dir idx ext) + 8'h6A : PG1_R1_O = 4'hd; // DMEM_RD DEC (dir idx ext) + 8'h6C : PG1_R1_O = 4'hd; // DMEM_RD INC (dir idx ext) + 8'h6D : PG1_R1_O = 4'hd; // DMEM_RD TST (dir idx ext) + 8'h6E : PG1_R1_O = 4'h5; // PC JMP (idx) + 8'h6F : PG1_R1_O = 4'hd; // DMEM_RD CLR (idx) sets 8bit width + 8'h70 : PG1_R1_O = 4'hd; // DMEM_RD NEG (dir idx ext) sets 8bit width + 8'h73 : PG1_R1_O = 4'hd; // DMEM_RD COM (dir idx ext) sets 8bit width + 8'h74 : PG1_R1_O = 4'hd; // DMEM_RD LSR (dir idx ext) + 8'h76 : PG1_R1_O = 4'hd; // DMEM_RD ROR (dir idx ext) + 8'h77 : PG1_R1_O = 4'hd; // DMEM_RD ASR (dir idx ext) + 8'h78 : PG1_R1_O = 4'hd; // DMEM_RD ASL LSL (dir idx ext) + 8'h79 : PG1_R1_O = 4'hd; // DMEM_RD ROL (dir idx ext) + 8'h7A : PG1_R1_O = 4'hd; // DMEM_RD DEC (dir idx ext) + 8'h7C : PG1_R1_O = 4'hd; // DMEM_RD INC (dir idx ext) + 8'h7D : PG1_R1_O = 4'hd; // DMEM_RD TST (dir idx ext) + 8'h7E : PG1_R1_O = 4'h5; // PC JMP (dir ext) + 8'h7F : PG1_R1_O = 4'hd; // DMEM_RD CLR (dir ext) sets 8bit width + 8'h80 : PG1_R1_O = 4'h8; // A SUBA (imm) + 8'h81 : PG1_R1_O = 4'h8; // A CMPA (imm) + 8'h82 : PG1_R1_O = 4'h8; // A SBCA (imm) + 8'h83 : PG1_R1_O = 4'h0; // D SUBD (imm) + 8'h84 : PG1_R1_O = 4'h8; // A ANDA (imm) + 8'h85 : PG1_R1_O = 4'h8; // A BITA (imm) + 8'h86 : PG1_R1_O = 4'h8; // A LDA (imm) + 8'h88 : PG1_R1_O = 4'h8; // A EORA (imm) + 8'h89 : PG1_R1_O = 4'h8; // A ADCA (imm) + 8'h8A : PG1_R1_O = 4'h8; // A ORA (imm) + 8'h8B : PG1_R1_O = 4'h8; // A ADDA (imm) + 8'h8C : PG1_R1_O = 4'h1; // X CMPX (imm) + 8'h8D : PG1_R1_O = 4'h5; // PC BSR LBSR + 8'h8E : PG1_R1_O = 4'h1; // X LDX (imm) + 8'h90 : PG1_R1_O = 4'h8; // A SUBA (dir idx ext) + 8'h91 : PG1_R1_O = 4'h8; // A CMPA (dir idx ext) + 8'h92 : PG1_R1_O = 4'h8; // A SBCA (dir idx ext) + 8'h93 : PG1_R1_O = 4'h0; // D SUBD (dir idx ext) + 8'h94 : PG1_R1_O = 4'h8; // A ANDA (dir idx ext) + 8'h95 : PG1_R1_O = 4'h8; // A BITA (dir idx ext) + 8'h96 : PG1_R1_O = 4'h8; // A LDA (dir idx ext) + 8'h97 : PG1_R1_O = 4'h8; // A STA (dir ext) + 8'h98 : PG1_R1_O = 4'h8; // A EORA (dir idx ext) + 8'h99 : PG1_R1_O = 4'h8; // A ADCA (dir idx ext) + 8'h9A : PG1_R1_O = 4'h8; // A ORA (dir idx ext) + 8'h9B : PG1_R1_O = 4'h8; // A ADDA (dir idx ext) + 8'h9C : PG1_R1_O = 4'h1; // X CMPX (dir idx ext) + 8'h9D : PG1_R1_O = 4'h5; // PC JSR (dir ext) + 8'h9E : PG1_R1_O = 4'h1; // X LDX (dir idx ext) + 8'h9F : PG1_R1_O = 4'h1; // X STX (dir ext) + 8'hA0 : PG1_R1_O = 4'h8; // A SUBA (dir idx ext) + 8'hA1 : PG1_R1_O = 4'h8; // A CMPA (dir idx ext) + 8'hA2 : PG1_R1_O = 4'h8; // A SBCA (dir idx ext) + 8'hA3 : PG1_R1_O = 4'h0; // D SUBD (dir idx ext) + 8'hA4 : PG1_R1_O = 4'h8; // A ANDA (dir idx ext) + 8'hA5 : PG1_R1_O = 4'h8; // A BITA (dir idx ext) + 8'hA6 : PG1_R1_O = 4'h8; // A LDA (dir idx ext) + 8'hA7 : PG1_R1_O = 4'h8; // A STA (idx) + 8'hA8 : PG1_R1_O = 4'h8; // A EORA (dir idx ext) + 8'hA9 : PG1_R1_O = 4'h8; // A ADCA (dir idx ext) + 8'hAA : PG1_R1_O = 4'h8; // A ORA (dir idx ext) + 8'hAB : PG1_R1_O = 4'h8; // A ADDA (dir idx ext) + 8'hAC : PG1_R1_O = 4'h1; // X CMPX (dir idx ext) + 8'hAD : PG1_R1_O = 4'h5; // PC JSR (idx) + 8'hAE : PG1_R1_O = 4'h1; // X LDX (dir idx ext) + 8'hAF : PG1_R1_O = 4'h1; // X STX (idx) + 8'hB0 : PG1_R1_O = 4'h8; // A SUBA (dir idx ext) + 8'hB1 : PG1_R1_O = 4'h8; // A CMPA (dir idx ext) + 8'hB2 : PG1_R1_O = 4'h8; // A SBCA (dir idx ext) + 8'hB3 : PG1_R1_O = 4'h0; // D SUBD (dir idx ext) + 8'hB4 : PG1_R1_O = 4'h8; // A ANDA (dir idx ext) + 8'hB5 : PG1_R1_O = 4'h8; // A BITA (dir idx ext) + 8'hB6 : PG1_R1_O = 4'h8; // A LDA (dir idx ext) + 8'hB7 : PG1_R1_O = 4'h8; // A STA (dir ext) + 8'hB8 : PG1_R1_O = 4'h8; // A EORA (dir idx ext) + 8'hB9 : PG1_R1_O = 4'h8; // A ADCA (dir idx ext) + 8'hBA : PG1_R1_O = 4'h8; // A ORA (dir idx ext) + 8'hBB : PG1_R1_O = 4'h8; // A ADDA (dir idx ext) + 8'hBC : PG1_R1_O = 4'h1; // X CMPX (dir idx ext) + 8'hBD : PG1_R1_O = 4'h5; // PC JSR (dir ext) + 8'hBE : PG1_R1_O = 4'h1; // X LDX (dir idx ext) + 8'hBF : PG1_R1_O = 4'h1; // X STX (dir ext) + 8'hC0 : PG1_R1_O = 4'h9; // B SUBB (imm) + 8'hC1 : PG1_R1_O = 4'h9; // B CMPB (imm) + 8'hC2 : PG1_R1_O = 4'h9; // B SBCB (imm) + 8'hC3 : PG1_R1_O = 4'h0; // D ADDD (imm) + 8'hC4 : PG1_R1_O = 4'h9; // B ANDB (imm) + 8'hC5 : PG1_R1_O = 4'h9; // B BITB (imm) + 8'hC6 : PG1_R1_O = 4'h9; // B LDB (imm) + 8'hC8 : PG1_R1_O = 4'h9; // B EORB (imm) + 8'hC9 : PG1_R1_O = 4'h9; // B ADCB (imm) + 8'hCA : PG1_R1_O = 4'h9; // B ORB (imm) + 8'hCB : PG1_R1_O = 4'h9; // B ADDB (imm) + 8'hCC : PG1_R1_O = 4'h0; // D LDD (imm) + 8'hCE : PG1_R1_O = 4'h3; // U LDU (imm) + 8'hD0 : PG1_R1_O = 4'h9; // B SUBB (dir idx ext) + 8'hD1 : PG1_R1_O = 4'h9; // B CMPB (dir idx ext) + 8'hD2 : PG1_R1_O = 4'h9; // B SBCB (dir idx ext) + 8'hD3 : PG1_R1_O = 4'h0; // D ADDD (dir idx ext) + 8'hD4 : PG1_R1_O = 4'h9; // B ANDB (dir idx ext) + 8'hD5 : PG1_R1_O = 4'h9; // B BITB (dir idx ext) + 8'hD6 : PG1_R1_O = 4'h9; // B LDB (dir idx ext) + 8'hD7 : PG1_R1_O = 4'h9; // B STB (dir ext) + 8'hD8 : PG1_R1_O = 4'h9; // B EORB (dir idx ext) + 8'hD9 : PG1_R1_O = 4'h9; // B ADCB (dir idx ext) + 8'hDA : PG1_R1_O = 4'h9; // B ORB (dir idx ext) + 8'hDB : PG1_R1_O = 4'h9; // B ADDB (dir idx ext) + 8'hDC : PG1_R1_O = 4'h0; // D LDD (dir idx ext) + 8'hDD : PG1_R1_O = 4'h0; // D STD (dir ext) + 8'hDE : PG1_R1_O = 4'h3; // U LDU (dir idx ext) + 8'hDF : PG1_R1_O = 4'h3; // U STU (dir ext) + 8'hE0 : PG1_R1_O = 4'h9; // B SUBB (dir idx ext) + 8'hE1 : PG1_R1_O = 4'h9; // B CMPB (dir idx ext) + 8'hE2 : PG1_R1_O = 4'h9; // B SBCB (dir idx ext) + 8'hE3 : PG1_R1_O = 4'h0; // D ADDD (dir idx ext) + 8'hE4 : PG1_R1_O = 4'h9; // B ANDB (dir idx ext) + 8'hE5 : PG1_R1_O = 4'h9; // B BITB (dir idx ext) + 8'hE6 : PG1_R1_O = 4'h9; // B LDB (dir idx ext) + 8'hE7 : PG1_R1_O = 4'h9; // B STB (idx) + 8'hE8 : PG1_R1_O = 4'h9; // B EORB (dir idx ext) + 8'hE9 : PG1_R1_O = 4'h9; // B ADCB (dir idx ext) + 8'hEA : PG1_R1_O = 4'h9; // B ORB (dir idx ext) + 8'hEB : PG1_R1_O = 4'h9; // B ADDB (dir idx ext) + 8'hEC : PG1_R1_O = 4'h0; // D LDD (dir idx ext) + 8'hED : PG1_R1_O = 4'h0; // D STD (idx) + 8'hEE : PG1_R1_O = 4'h3; // U LDU (dir idx ext) + 8'hEF : PG1_R1_O = 4'h3; // U STU (idx) + 8'hF0 : PG1_R1_O = 4'h9; // B SUBB (dir idx ext) + 8'hF1 : PG1_R1_O = 4'h9; // B CMPB (dir idx ext) + 8'hF2 : PG1_R1_O = 4'h9; // B SBCB (dir idx ext) + 8'hF3 : PG1_R1_O = 4'h0; // D ADDD (dir idx ext) + 8'hF4 : PG1_R1_O = 4'h9; // B ANDB (dir idx ext) + 8'hF5 : PG1_R1_O = 4'h9; // B BITB (dir idx ext) + 8'hF6 : PG1_R1_O = 4'h9; // B LDB (dir idx ext) + 8'hF7 : PG1_R1_O = 4'h9; // B STB (dir ext) + 8'hF8 : PG1_R1_O = 4'h9; // B EORB (dir idx ext) + 8'hF9 : PG1_R1_O = 4'h9; // B ADCB (dir idx ext) + 8'hFA : PG1_R1_O = 4'h9; // B ORB (dir idx ext) + 8'hFB : PG1_R1_O = 4'h9; // B ADDB (dir idx ext) + 8'hFC : PG1_R1_O = 4'h0; // D LDD (dir idx ext) + 8'hFD : PG1_R1_O = 4'h0; // D STD (dir ext) + 8'hFE : PG1_R1_O = 4'h3; // U LDU (dir idx ext) + 8'hFF : PG1_R1_O = 4'h3; // U STU (dir ext) + default : PG1_R1_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG1_R1_op; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R1_op = "NEG (dir idx ext) sets 8bit width"; + 8'h03 : PG1_R1_op = "COM (dir idx ext) sets 8bit width"; + 8'h04 : PG1_R1_op = "LSR (dir idx ext)"; + 8'h06 : PG1_R1_op = "ROR (dir idx ext)"; + 8'h07 : PG1_R1_op = "ASR (dir idx ext)"; + 8'h08 : PG1_R1_op = "ASL LSL (dir idx ext)"; + 8'h09 : PG1_R1_op = "ROL (dir idx ext)"; + 8'h0A : PG1_R1_op = "DEC (dir idx ext)"; + 8'h0C : PG1_R1_op = "INC (dir idx ext)"; + 8'h0D : PG1_R1_op = "TST (dir idx ext)"; + 8'h0E : PG1_R1_op = "JMP (dir ext)"; + 8'h0F : PG1_R1_op = "CLR (dir ext) sets 8bit width"; + 8'h14 : PG1_R1_op = "EMUL (inh)"; + 8'h15 : PG1_R1_op = "EMULS (inh)"; + 8'h16 : PG1_R1_op = "LBRA "; + 8'h17 : PG1_R1_op = "BSR LBSR"; + 8'h18 : PG1_R1_op = "IDIV (inh)"; + 8'h19 : PG1_R1_op = "DAA (inh)"; + 8'h1A : PG1_R1_op = "ORCC (imm)"; + 8'h1C : PG1_R1_op = "ANDCC (imm)"; + 8'h1D : PG1_R1_op = "SEX(inh)"; + 8'h20 : PG1_R1_op = "BRA BRN BHI BLS"; + 8'h21 : PG1_R1_op = "BRA BRN BHI BLS"; + 8'h22 : PG1_R1_op = "BRA BRN BHI BLS"; + 8'h23 : PG1_R1_op = "BRA BRN BHI BLS"; + 8'h24 : PG1_R1_op = "BCC BCS BNE BEQ"; + 8'h25 : PG1_R1_op = "BCC BCS BNE BEQ"; + 8'h26 : PG1_R1_op = "BCC BCS BNE BEQ"; + 8'h27 : PG1_R1_op = "BCC BCS BNE BEQ"; + 8'h28 : PG1_R1_op = "BVC BVS BPL BMI"; + 8'h29 : PG1_R1_op = "BVC BVS BPL BMI"; + 8'h2A : PG1_R1_op = "BVC BVS BPL BMI"; + 8'h2B : PG1_R1_op = "BVC BVS BPL BMI"; + 8'h2C : PG1_R1_op = "BGE BLT BGT BLE"; + 8'h2D : PG1_R1_op = "BGE BLT BGT BLE"; + 8'h2E : PG1_R1_op = "BGE BLT BGT BLE"; + 8'h2F : PG1_R1_op = "BGE BLT BGT BLE"; + 8'h30 : PG1_R1_op = "LEAX(inh)"; + 8'h31 : PG1_R1_op = "LEAY(inh)"; + 8'h32 : PG1_R1_op = "LEAS(inh)"; + 8'h33 : PG1_R1_op = "LEAU(inh)"; + 8'h39 : PG1_R1_op = "RTS"; + 8'h3A : PG1_R1_op = "ABX(inh)"; + 8'h3B : PG1_R1_op = "RTI"; + 8'h3D : PG1_R1_op = "MUL (inh)"; + 8'h3F : PG1_R1_op = "SWI"; + 8'h40 : PG1_R1_op = "NEGA (inh)"; + 8'h43 : PG1_R1_op = "COMA (inh)"; + 8'h44 : PG1_R1_op = "LSRA (inh)"; + 8'h46 : PG1_R1_op = "RORA (inh)"; + 8'h47 : PG1_R1_op = "ASRA (inh)"; + 8'h48 : PG1_R1_op = "ASLA LSLA (inh)"; + 8'h49 : PG1_R1_op = "ROLA (inh)"; + 8'h4A : PG1_R1_op = "DECA (inh)"; + 8'h4C : PG1_R1_op = "INCA (inh)"; + 8'h4D : PG1_R1_op = "TSTA (inh)"; + 8'h4F : PG1_R1_op = "CLRA (inh)"; + 8'h50 : PG1_R1_op = "NEGB (inh)"; + 8'h53 : PG1_R1_op = "COMB (inh)"; + 8'h54 : PG1_R1_op = "LSRB (inh)"; + 8'h56 : PG1_R1_op = "RORB (inh)"; + 8'h57 : PG1_R1_op = "ASRB (inh)"; + 8'h58 : PG1_R1_op = "ASLB LSLB (inh)"; + 8'h59 : PG1_R1_op = "ROLB (inh)"; + 8'h5A : PG1_R1_op = "DECB (inh)"; + 8'h5C : PG1_R1_op = "INCB (inh)"; + 8'h5D : PG1_R1_op = "TSTB (inh)"; + 8'h5F : PG1_R1_op = "CLRB (inh)"; + 8'h60 : PG1_R1_op = "NEG (dir idx ext) sets 8bit width"; + 8'h63 : PG1_R1_op = "COM (dir idx ext) sets 8bit width"; + 8'h64 : PG1_R1_op = "LSR (dir idx ext)"; + 8'h66 : PG1_R1_op = "ROR (dir idx ext)"; + 8'h67 : PG1_R1_op = "ASR (dir idx ext)"; + 8'h68 : PG1_R1_op = "ASL LSL (dir idx ext)"; + 8'h69 : PG1_R1_op = "ROL (dir idx ext)"; + 8'h6A : PG1_R1_op = "DEC (dir idx ext)"; + 8'h6C : PG1_R1_op = "INC (dir idx ext)"; + 8'h6D : PG1_R1_op = "TST (dir idx ext)"; + 8'h6E : PG1_R1_op = "JMP (idx)"; + 8'h6F : PG1_R1_op = "CLR (idx) sets 8bit width"; + 8'h70 : PG1_R1_op = "NEG (dir idx ext) sets 8bit width"; + 8'h73 : PG1_R1_op = "COM (dir idx ext) sets 8bit width"; + 8'h74 : PG1_R1_op = "LSR (dir idx ext)"; + 8'h76 : PG1_R1_op = "ROR (dir idx ext)"; + 8'h77 : PG1_R1_op = "ASR (dir idx ext)"; + 8'h78 : PG1_R1_op = "ASL LSL (dir idx ext)"; + 8'h79 : PG1_R1_op = "ROL (dir idx ext)"; + 8'h7A : PG1_R1_op = "DEC (dir idx ext)"; + 8'h7C : PG1_R1_op = "INC (dir idx ext)"; + 8'h7D : PG1_R1_op = "TST (dir idx ext)"; + 8'h7E : PG1_R1_op = "JMP (dir ext)"; + 8'h7F : PG1_R1_op = "CLR (dir ext) sets 8bit width"; + 8'h80 : PG1_R1_op = "SUBA (imm)"; + 8'h81 : PG1_R1_op = "CMPA (imm)"; + 8'h82 : PG1_R1_op = "SBCA (imm)"; + 8'h83 : PG1_R1_op = "SUBD (imm)"; + 8'h84 : PG1_R1_op = "ANDA (imm)"; + 8'h85 : PG1_R1_op = "BITA (imm)"; + 8'h86 : PG1_R1_op = "LDA (imm)"; + 8'h88 : PG1_R1_op = "EORA (imm)"; + 8'h89 : PG1_R1_op = "ADCA (imm)"; + 8'h8A : PG1_R1_op = "ORA (imm)"; + 8'h8B : PG1_R1_op = "ADDA (imm)"; + 8'h8C : PG1_R1_op = "CMPX (imm)"; + 8'h8D : PG1_R1_op = "BSR LBSR"; + 8'h8E : PG1_R1_op = "LDX (imm)"; + 8'h90 : PG1_R1_op = "SUBA (dir idx ext)"; + 8'h91 : PG1_R1_op = "CMPA (dir idx ext)"; + 8'h92 : PG1_R1_op = "SBCA (dir idx ext)"; + 8'h93 : PG1_R1_op = "SUBD (dir idx ext)"; + 8'h94 : PG1_R1_op = "ANDA (dir idx ext)"; + 8'h95 : PG1_R1_op = "BITA (dir idx ext)"; + 8'h96 : PG1_R1_op = "LDA (dir idx ext)"; + 8'h97 : PG1_R1_op = "STA (dir ext)"; + 8'h98 : PG1_R1_op = "EORA (dir idx ext)"; + 8'h99 : PG1_R1_op = "ADCA (dir idx ext)"; + 8'h9A : PG1_R1_op = "ORA (dir idx ext)"; + 8'h9B : PG1_R1_op = "ADDA (dir idx ext)"; + 8'h9C : PG1_R1_op = "CMPX (dir idx ext)"; + 8'h9D : PG1_R1_op = "JSR (dir ext)"; + 8'h9E : PG1_R1_op = "LDX (dir idx ext)"; + 8'h9F : PG1_R1_op = "STX (dir ext)"; + 8'hA0 : PG1_R1_op = "SUBA (dir idx ext)"; + 8'hA1 : PG1_R1_op = "CMPA (dir idx ext)"; + 8'hA2 : PG1_R1_op = "SBCA (dir idx ext)"; + 8'hA3 : PG1_R1_op = "SUBD (dir idx ext)"; + 8'hA4 : PG1_R1_op = "ANDA (dir idx ext)"; + 8'hA5 : PG1_R1_op = "BITA (dir idx ext)"; + 8'hA6 : PG1_R1_op = "LDA (dir idx ext)"; + 8'hA7 : PG1_R1_op = "STA (idx)"; + 8'hA8 : PG1_R1_op = "EORA (dir idx ext)"; + 8'hA9 : PG1_R1_op = "ADCA (dir idx ext)"; + 8'hAA : PG1_R1_op = "ORA (dir idx ext)"; + 8'hAB : PG1_R1_op = "ADDA (dir idx ext)"; + 8'hAC : PG1_R1_op = "CMPX (dir idx ext)"; + 8'hAD : PG1_R1_op = "JSR (idx)"; + 8'hAE : PG1_R1_op = "LDX (dir idx ext)"; + 8'hAF : PG1_R1_op = "STX (idx)"; + 8'hB0 : PG1_R1_op = "SUBA (dir idx ext)"; + 8'hB1 : PG1_R1_op = "CMPA (dir idx ext)"; + 8'hB2 : PG1_R1_op = "SBCA (dir idx ext)"; + 8'hB3 : PG1_R1_op = "SUBD (dir idx ext)"; + 8'hB4 : PG1_R1_op = "ANDA (dir idx ext)"; + 8'hB5 : PG1_R1_op = "BITA (dir idx ext)"; + 8'hB6 : PG1_R1_op = "LDA (dir idx ext)"; + 8'hB7 : PG1_R1_op = "STA (dir ext)"; + 8'hB8 : PG1_R1_op = "EORA (dir idx ext)"; + 8'hB9 : PG1_R1_op = "ADCA (dir idx ext)"; + 8'hBA : PG1_R1_op = "ORA (dir idx ext)"; + 8'hBB : PG1_R1_op = "ADDA (dir idx ext)"; + 8'hBC : PG1_R1_op = "CMPX (dir idx ext)"; + 8'hBD : PG1_R1_op = "JSR (dir ext)"; + 8'hBE : PG1_R1_op = "LDX (dir idx ext)"; + 8'hBF : PG1_R1_op = "STX (dir ext)"; + 8'hC0 : PG1_R1_op = "SUBB (imm)"; + 8'hC1 : PG1_R1_op = "CMPB (imm)"; + 8'hC2 : PG1_R1_op = "SBCB (imm)"; + 8'hC3 : PG1_R1_op = "ADDD (imm)"; + 8'hC4 : PG1_R1_op = "ANDB (imm)"; + 8'hC5 : PG1_R1_op = "BITB (imm)"; + 8'hC6 : PG1_R1_op = "LDB (imm)"; + 8'hC8 : PG1_R1_op = "EORB (imm)"; + 8'hC9 : PG1_R1_op = "ADCB (imm)"; + 8'hCA : PG1_R1_op = "ORB (imm)"; + 8'hCB : PG1_R1_op = "ADDB (imm)"; + 8'hCC : PG1_R1_op = "LDD (imm)"; + 8'hCE : PG1_R1_op = "LDU (imm)"; + 8'hD0 : PG1_R1_op = "SUBB (dir idx ext)"; + 8'hD1 : PG1_R1_op = "CMPB (dir idx ext)"; + 8'hD2 : PG1_R1_op = "SBCB (dir idx ext)"; + 8'hD3 : PG1_R1_op = "ADDD (dir idx ext)"; + 8'hD4 : PG1_R1_op = "ANDB (dir idx ext)"; + 8'hD5 : PG1_R1_op = "BITB (dir idx ext)"; + 8'hD6 : PG1_R1_op = "LDB (dir idx ext)"; + 8'hD7 : PG1_R1_op = "STB (dir ext)"; + 8'hD8 : PG1_R1_op = "EORB (dir idx ext)"; + 8'hD9 : PG1_R1_op = "ADCB (dir idx ext)"; + 8'hDA : PG1_R1_op = "ORB (dir idx ext)"; + 8'hDB : PG1_R1_op = "ADDB (dir idx ext)"; + 8'hDC : PG1_R1_op = "LDD (dir idx ext)"; + 8'hDD : PG1_R1_op = "STD (dir ext)"; + 8'hDE : PG1_R1_op = "LDU (dir idx ext)"; + 8'hDF : PG1_R1_op = "STU (dir ext)"; + 8'hE0 : PG1_R1_op = "SUBB (dir idx ext)"; + 8'hE1 : PG1_R1_op = "CMPB (dir idx ext)"; + 8'hE2 : PG1_R1_op = "SBCB (dir idx ext)"; + 8'hE3 : PG1_R1_op = "ADDD (dir idx ext)"; + 8'hE4 : PG1_R1_op = "ANDB (dir idx ext)"; + 8'hE5 : PG1_R1_op = "BITB (dir idx ext)"; + 8'hE6 : PG1_R1_op = "LDB (dir idx ext)"; + 8'hE7 : PG1_R1_op = "STB (idx)"; + 8'hE8 : PG1_R1_op = "EORB (dir idx ext)"; + 8'hE9 : PG1_R1_op = "ADCB (dir idx ext)"; + 8'hEA : PG1_R1_op = "ORB (dir idx ext)"; + 8'hEB : PG1_R1_op = "ADDB (dir idx ext)"; + 8'hEC : PG1_R1_op = "LDD (dir idx ext)"; + 8'hED : PG1_R1_op = "STD (idx)"; + 8'hEE : PG1_R1_op = "LDU (dir idx ext)"; + 8'hEF : PG1_R1_op = "STU (idx)"; + 8'hF0 : PG1_R1_op = "SUBB (dir idx ext)"; + 8'hF1 : PG1_R1_op = "CMPB (dir idx ext)"; + 8'hF2 : PG1_R1_op = "SBCB (dir idx ext)"; + 8'hF3 : PG1_R1_op = "ADDD (dir idx ext)"; + 8'hF4 : PG1_R1_op = "ANDB (dir idx ext)"; + 8'hF5 : PG1_R1_op = "BITB (dir idx ext)"; + 8'hF6 : PG1_R1_op = "LDB (dir idx ext)"; + 8'hF7 : PG1_R1_op = "STB (dir ext)"; + 8'hF8 : PG1_R1_op = "EORB (dir idx ext)"; + 8'hF9 : PG1_R1_op = "ADCB (dir idx ext)"; + 8'hFA : PG1_R1_op = "ORB (dir idx ext)"; + 8'hFB : PG1_R1_op = "ADDB (dir idx ext)"; + 8'hFC : PG1_R1_op = "LDD (dir idx ext)"; + 8'hFD : PG1_R1_op = "STD (dir ext)"; + 8'hFE : PG1_R1_op = "LDU (dir idx ext)"; + 8'hFF : PG1_R1_op = "STU (dir ext)"; + default : PG1_R1_op = "invalid"; + endcase +end + +reg [(8*64):0] PG1_R1_eq; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R1_eq = "DMEM_RD"; + 8'h03 : PG1_R1_eq = "DMEM_RD"; + 8'h04 : PG1_R1_eq = "DMEM_RD"; + 8'h06 : PG1_R1_eq = "DMEM_RD"; + 8'h07 : PG1_R1_eq = "DMEM_RD"; + 8'h08 : PG1_R1_eq = "DMEM_RD"; + 8'h09 : PG1_R1_eq = "DMEM_RD"; + 8'h0A : PG1_R1_eq = "DMEM_RD"; + 8'h0C : PG1_R1_eq = "DMEM_RD"; + 8'h0D : PG1_R1_eq = "DMEM_RD"; + 8'h0E : PG1_R1_eq = "PC"; + 8'h0F : PG1_R1_eq = "DMEM_RD"; + 8'h14 : PG1_R1_eq = "D"; + 8'h15 : PG1_R1_eq = "D"; + 8'h16 : PG1_R1_eq = "PC"; + 8'h17 : PG1_R1_eq = "PC"; + 8'h18 : PG1_R1_eq = "X"; + 8'h19 : PG1_R1_eq = "D"; + 8'h1A : PG1_R1_eq = "CCR"; + 8'h1C : PG1_R1_eq = "CCR"; + 8'h1D : PG1_R1_eq = "D"; + 8'h20 : PG1_R1_eq = "PC"; + 8'h21 : PG1_R1_eq = "PC"; + 8'h22 : PG1_R1_eq = "PC"; + 8'h23 : PG1_R1_eq = "PC"; + 8'h24 : PG1_R1_eq = "PC"; + 8'h25 : PG1_R1_eq = "PC"; + 8'h26 : PG1_R1_eq = "PC"; + 8'h27 : PG1_R1_eq = "PC"; + 8'h28 : PG1_R1_eq = "PC"; + 8'h29 : PG1_R1_eq = "PC"; + 8'h2A : PG1_R1_eq = "PC"; + 8'h2B : PG1_R1_eq = "PC"; + 8'h2C : PG1_R1_eq = "PC"; + 8'h2D : PG1_R1_eq = "PC"; + 8'h2E : PG1_R1_eq = "PC"; + 8'h2F : PG1_R1_eq = "PC"; + 8'h30 : PG1_R1_eq = "X"; + 8'h31 : PG1_R1_eq = "Y"; + 8'h32 : PG1_R1_eq = "S"; + 8'h33 : PG1_R1_eq = "U"; + 8'h39 : PG1_R1_eq = "PC"; + 8'h3A : PG1_R1_eq = "X"; + 8'h3B : PG1_R1_eq = "PC"; + 8'h3D : PG1_R1_eq = "D"; + 8'h3F : PG1_R1_eq = "PC"; + 8'h40 : PG1_R1_eq = "A"; + 8'h43 : PG1_R1_eq = "A"; + 8'h44 : PG1_R1_eq = "A"; + 8'h46 : PG1_R1_eq = "A"; + 8'h47 : PG1_R1_eq = "A"; + 8'h48 : PG1_R1_eq = "A"; + 8'h49 : PG1_R1_eq = "A"; + 8'h4A : PG1_R1_eq = "A"; + 8'h4C : PG1_R1_eq = "A"; + 8'h4D : PG1_R1_eq = "A"; + 8'h4F : PG1_R1_eq = "A"; + 8'h50 : PG1_R1_eq = "B"; + 8'h53 : PG1_R1_eq = "B"; + 8'h54 : PG1_R1_eq = "B"; + 8'h56 : PG1_R1_eq = "B"; + 8'h57 : PG1_R1_eq = "B"; + 8'h58 : PG1_R1_eq = "B"; + 8'h59 : PG1_R1_eq = "B"; + 8'h5A : PG1_R1_eq = "B"; + 8'h5C : PG1_R1_eq = "B"; + 8'h5D : PG1_R1_eq = "B"; + 8'h5F : PG1_R1_eq = "B"; + 8'h60 : PG1_R1_eq = "DMEM_RD"; + 8'h63 : PG1_R1_eq = "DMEM_RD"; + 8'h64 : PG1_R1_eq = "DMEM_RD"; + 8'h66 : PG1_R1_eq = "DMEM_RD"; + 8'h67 : PG1_R1_eq = "DMEM_RD"; + 8'h68 : PG1_R1_eq = "DMEM_RD"; + 8'h69 : PG1_R1_eq = "DMEM_RD"; + 8'h6A : PG1_R1_eq = "DMEM_RD"; + 8'h6C : PG1_R1_eq = "DMEM_RD"; + 8'h6D : PG1_R1_eq = "DMEM_RD"; + 8'h6E : PG1_R1_eq = "PC"; + 8'h6F : PG1_R1_eq = "DMEM_RD"; + 8'h70 : PG1_R1_eq = "DMEM_RD"; + 8'h73 : PG1_R1_eq = "DMEM_RD"; + 8'h74 : PG1_R1_eq = "DMEM_RD"; + 8'h76 : PG1_R1_eq = "DMEM_RD"; + 8'h77 : PG1_R1_eq = "DMEM_RD"; + 8'h78 : PG1_R1_eq = "DMEM_RD"; + 8'h79 : PG1_R1_eq = "DMEM_RD"; + 8'h7A : PG1_R1_eq = "DMEM_RD"; + 8'h7C : PG1_R1_eq = "DMEM_RD"; + 8'h7D : PG1_R1_eq = "DMEM_RD"; + 8'h7E : PG1_R1_eq = "PC"; + 8'h7F : PG1_R1_eq = "DMEM_RD"; + 8'h80 : PG1_R1_eq = "A"; + 8'h81 : PG1_R1_eq = "A"; + 8'h82 : PG1_R1_eq = "A"; + 8'h83 : PG1_R1_eq = "D"; + 8'h84 : PG1_R1_eq = "A"; + 8'h85 : PG1_R1_eq = "A"; + 8'h86 : PG1_R1_eq = "A"; + 8'h88 : PG1_R1_eq = "A"; + 8'h89 : PG1_R1_eq = "A"; + 8'h8A : PG1_R1_eq = "A"; + 8'h8B : PG1_R1_eq = "A"; + 8'h8C : PG1_R1_eq = "X"; + 8'h8D : PG1_R1_eq = "PC"; + 8'h8E : PG1_R1_eq = "X"; + 8'h90 : PG1_R1_eq = "A"; + 8'h91 : PG1_R1_eq = "A"; + 8'h92 : PG1_R1_eq = "A"; + 8'h93 : PG1_R1_eq = "D"; + 8'h94 : PG1_R1_eq = "A"; + 8'h95 : PG1_R1_eq = "A"; + 8'h96 : PG1_R1_eq = "A"; + 8'h97 : PG1_R1_eq = "A"; + 8'h98 : PG1_R1_eq = "A"; + 8'h99 : PG1_R1_eq = "A"; + 8'h9A : PG1_R1_eq = "A"; + 8'h9B : PG1_R1_eq = "A"; + 8'h9C : PG1_R1_eq = "X"; + 8'h9D : PG1_R1_eq = "PC"; + 8'h9E : PG1_R1_eq = "X"; + 8'h9F : PG1_R1_eq = "X"; + 8'hA0 : PG1_R1_eq = "A"; + 8'hA1 : PG1_R1_eq = "A"; + 8'hA2 : PG1_R1_eq = "A"; + 8'hA3 : PG1_R1_eq = "D"; + 8'hA4 : PG1_R1_eq = "A"; + 8'hA5 : PG1_R1_eq = "A"; + 8'hA6 : PG1_R1_eq = "A"; + 8'hA7 : PG1_R1_eq = "A"; + 8'hA8 : PG1_R1_eq = "A"; + 8'hA9 : PG1_R1_eq = "A"; + 8'hAA : PG1_R1_eq = "A"; + 8'hAB : PG1_R1_eq = "A"; + 8'hAC : PG1_R1_eq = "X"; + 8'hAD : PG1_R1_eq = "PC"; + 8'hAE : PG1_R1_eq = "X"; + 8'hAF : PG1_R1_eq = "X"; + 8'hB0 : PG1_R1_eq = "A"; + 8'hB1 : PG1_R1_eq = "A"; + 8'hB2 : PG1_R1_eq = "A"; + 8'hB3 : PG1_R1_eq = "D"; + 8'hB4 : PG1_R1_eq = "A"; + 8'hB5 : PG1_R1_eq = "A"; + 8'hB6 : PG1_R1_eq = "A"; + 8'hB7 : PG1_R1_eq = "A"; + 8'hB8 : PG1_R1_eq = "A"; + 8'hB9 : PG1_R1_eq = "A"; + 8'hBA : PG1_R1_eq = "A"; + 8'hBB : PG1_R1_eq = "A"; + 8'hBC : PG1_R1_eq = "X"; + 8'hBD : PG1_R1_eq = "PC"; + 8'hBE : PG1_R1_eq = "X"; + 8'hBF : PG1_R1_eq = "X"; + 8'hC0 : PG1_R1_eq = "B"; + 8'hC1 : PG1_R1_eq = "B"; + 8'hC2 : PG1_R1_eq = "B"; + 8'hC3 : PG1_R1_eq = "D"; + 8'hC4 : PG1_R1_eq = "B"; + 8'hC5 : PG1_R1_eq = "B"; + 8'hC6 : PG1_R1_eq = "B"; + 8'hC8 : PG1_R1_eq = "B"; + 8'hC9 : PG1_R1_eq = "B"; + 8'hCA : PG1_R1_eq = "B"; + 8'hCB : PG1_R1_eq = "B"; + 8'hCC : PG1_R1_eq = "D"; + 8'hCE : PG1_R1_eq = "U"; + 8'hD0 : PG1_R1_eq = "B"; + 8'hD1 : PG1_R1_eq = "B"; + 8'hD2 : PG1_R1_eq = "B"; + 8'hD3 : PG1_R1_eq = "D"; + 8'hD4 : PG1_R1_eq = "B"; + 8'hD5 : PG1_R1_eq = "B"; + 8'hD6 : PG1_R1_eq = "B"; + 8'hD7 : PG1_R1_eq = "B"; + 8'hD8 : PG1_R1_eq = "B"; + 8'hD9 : PG1_R1_eq = "B"; + 8'hDA : PG1_R1_eq = "B"; + 8'hDB : PG1_R1_eq = "B"; + 8'hDC : PG1_R1_eq = "D"; + 8'hDD : PG1_R1_eq = "D"; + 8'hDE : PG1_R1_eq = "U"; + 8'hDF : PG1_R1_eq = "U"; + 8'hE0 : PG1_R1_eq = "B"; + 8'hE1 : PG1_R1_eq = "B"; + 8'hE2 : PG1_R1_eq = "B"; + 8'hE3 : PG1_R1_eq = "D"; + 8'hE4 : PG1_R1_eq = "B"; + 8'hE5 : PG1_R1_eq = "B"; + 8'hE6 : PG1_R1_eq = "B"; + 8'hE7 : PG1_R1_eq = "B"; + 8'hE8 : PG1_R1_eq = "B"; + 8'hE9 : PG1_R1_eq = "B"; + 8'hEA : PG1_R1_eq = "B"; + 8'hEB : PG1_R1_eq = "B"; + 8'hEC : PG1_R1_eq = "D"; + 8'hED : PG1_R1_eq = "D"; + 8'hEE : PG1_R1_eq = "U"; + 8'hEF : PG1_R1_eq = "U"; + 8'hF0 : PG1_R1_eq = "B"; + 8'hF1 : PG1_R1_eq = "B"; + 8'hF2 : PG1_R1_eq = "B"; + 8'hF3 : PG1_R1_eq = "D"; + 8'hF4 : PG1_R1_eq = "B"; + 8'hF5 : PG1_R1_eq = "B"; + 8'hF6 : PG1_R1_eq = "B"; + 8'hF7 : PG1_R1_eq = "B"; + 8'hF8 : PG1_R1_eq = "B"; + 8'hF9 : PG1_R1_eq = "B"; + 8'hFA : PG1_R1_eq = "B"; + 8'hFB : PG1_R1_eq = "B"; + 8'hFC : PG1_R1_eq = "D"; + 8'hFD : PG1_R1_eq = "D"; + 8'hFE : PG1_R1_eq = "U"; + 8'hFF : PG1_R1_eq = "U"; + default : PG1_R1_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R2.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R2.v new file mode 100644 index 0000000000000000000000000000000000000000..c09a344548b1dcd22f9a02fff2861a97bb93f3ae --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg1_R2.v @@ -0,0 +1,535 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R2_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg1_R2( + input [7:0] OPCODE_I, + output reg [3:0] PG1_R2_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R2_O = 4'hd; // DMEM_RD NEG (dir idx ext) + 8'h03 : PG1_R2_O = 4'hd; // DMEM_RD COM (dir idx ext) + 8'h0E : PG1_R2_O = 4'he; // IDATA JMP (dir ext) + 8'h14 : PG1_R2_O = 4'h2; // Y EMUL (inh) + 8'h15 : PG1_R2_O = 4'h2; // Y EMULS (inh) + 8'h16 : PG1_R2_O = 4'hc; // EA LBRA + 8'h17 : PG1_R2_O = 4'hc; // EA BSR LBSR + 8'h18 : PG1_R2_O = 4'h0; // D IDIV (inh) + 8'h1A : PG1_R2_O = 4'he; // IDATA ORCC (imm) + 8'h1C : PG1_R2_O = 4'he; // IDATA ANDCC (imm) + 8'h1D : PG1_R2_O = 4'h7; // SEXB SEX(inh) + 8'h20 : PG1_R2_O = 4'hc; // EA BRA BRN BHI BLS + 8'h21 : PG1_R2_O = 4'hc; // EA BRA BRN BHI BLS + 8'h22 : PG1_R2_O = 4'hc; // EA BRA BRN BHI BLS + 8'h23 : PG1_R2_O = 4'hc; // EA BRA BRN BHI BLS + 8'h24 : PG1_R2_O = 4'hc; // EA BCC BCS BNE BEQ + 8'h25 : PG1_R2_O = 4'hc; // EA BCC BCS BNE BEQ + 8'h26 : PG1_R2_O = 4'hc; // EA BCC BCS BNE BEQ + 8'h27 : PG1_R2_O = 4'hc; // EA BCC BCS BNE BEQ + 8'h28 : PG1_R2_O = 4'hc; // EA BVC BVS BPL BMI + 8'h29 : PG1_R2_O = 4'hc; // EA BVC BVS BPL BMI + 8'h2A : PG1_R2_O = 4'hc; // EA BVC BVS BPL BMI + 8'h2B : PG1_R2_O = 4'hc; // EA BVC BVS BPL BMI + 8'h2C : PG1_R2_O = 4'hc; // EA BGE BLT BGT BLE + 8'h2D : PG1_R2_O = 4'hc; // EA BGE BLT BGT BLE + 8'h2E : PG1_R2_O = 4'hc; // EA BGE BLT BGT BLE + 8'h2F : PG1_R2_O = 4'hc; // EA BGE BLT BGT BLE + 8'h39 : PG1_R2_O = 4'hd; // DMEM_RD RTS + 8'h3A : PG1_R2_O = 4'h9; // B ABX(inh) + 8'h3B : PG1_R2_O = 4'hd; // DMEM_RD RTI + 8'h3F : PG1_R2_O = 4'hd; // DMEM_RD SWI + 8'h40 : PG1_R2_O = 4'h8; // A NEGA (inh) + 8'h43 : PG1_R2_O = 4'h8; // A COMA (inh) + 8'h50 : PG1_R2_O = 4'h9; // B NEGB (inh) + 8'h53 : PG1_R2_O = 4'h9; // B COMB (inh) + 8'h60 : PG1_R2_O = 4'hd; // DMEM_RD NEG (dir idx ext) + 8'h63 : PG1_R2_O = 4'hd; // DMEM_RD COM (dir idx ext) + 8'h6E : PG1_R2_O = 4'hc; // EA JMP (idx) + 8'h70 : PG1_R2_O = 4'hd; // DMEM_RD NEG (dir idx ext) + 8'h73 : PG1_R2_O = 4'hd; // DMEM_RD COM (dir idx ext) + 8'h7E : PG1_R2_O = 4'he; // IDATA JMP (dir ext) + 8'h80 : PG1_R2_O = 4'he; // IDATA SUBA (imm) + 8'h81 : PG1_R2_O = 4'he; // IDATA CMPA (imm) + 8'h82 : PG1_R2_O = 4'he; // IDATA SBCA (imm) + 8'h83 : PG1_R2_O = 4'he; // IDATA SUBD (imm) + 8'h84 : PG1_R2_O = 4'he; // IDATA ANDA (imm) + 8'h85 : PG1_R2_O = 4'he; // IDATA BITA (imm) + 8'h86 : PG1_R2_O = 4'he; // IDATA LDA (imm) + 8'h88 : PG1_R2_O = 4'he; // IDATA EORA (imm) + 8'h89 : PG1_R2_O = 4'he; // IDATA ADCA (imm) + 8'h8A : PG1_R2_O = 4'he; // IDATA ORA (imm) + 8'h8B : PG1_R2_O = 4'he; // IDATA ADDA (imm) + 8'h8C : PG1_R2_O = 4'he; // IDATA CMPX (imm) + 8'h8D : PG1_R2_O = 4'hc; // EA BSR LBSR + 8'h8E : PG1_R2_O = 4'he; // IDATA LDX (imm) + 8'h90 : PG1_R2_O = 4'hd; // DMEM_RD SUBA (dir idx ext) + 8'h91 : PG1_R2_O = 4'hd; // DMEM_RD CMPA (dir idx ext) + 8'h92 : PG1_R2_O = 4'hd; // DMEM_RD SBCA (dir idx ext) + 8'h93 : PG1_R2_O = 4'hd; // DMEM_RD SUBD (dir idx ext) + 8'h94 : PG1_R2_O = 4'hd; // DMEM_RD ANDA (dir idx ext) + 8'h95 : PG1_R2_O = 4'hd; // DMEM_RD BITA (dir idx ext) + 8'h96 : PG1_R2_O = 4'hd; // DMEM_RD LDA (dir idx ext) + 8'h98 : PG1_R2_O = 4'hd; // DMEM_RD EORA (dir idx ext) + 8'h99 : PG1_R2_O = 4'hd; // DMEM_RD ADCA (dir idx ext) + 8'h9A : PG1_R2_O = 4'hd; // DMEM_RD ORA (dir idx ext) + 8'h9B : PG1_R2_O = 4'hd; // DMEM_RD ADDA (dir idx ext) + 8'h9C : PG1_R2_O = 4'hd; // DMEM_RD CMPX (dir idx ext) + 8'h9D : PG1_R2_O = 4'he; // IDATA JSR (dir ext) + 8'h9E : PG1_R2_O = 4'hd; // DMEM_RD LDX (dir idx ext) + 8'hA0 : PG1_R2_O = 4'hd; // DMEM_RD SUBA (dir idx ext) + 8'hA1 : PG1_R2_O = 4'hd; // DMEM_RD CMPA (dir idx ext) + 8'hA2 : PG1_R2_O = 4'hd; // DMEM_RD SBCA (dir idx ext) + 8'hA3 : PG1_R2_O = 4'hd; // DMEM_RD SUBD (dir idx ext) + 8'hA4 : PG1_R2_O = 4'hd; // DMEM_RD ANDA (dir idx ext) + 8'hA5 : PG1_R2_O = 4'hd; // DMEM_RD BITA (dir idx ext) + 8'hA6 : PG1_R2_O = 4'hd; // DMEM_RD LDA (dir idx ext) + 8'hA8 : PG1_R2_O = 4'hd; // DMEM_RD EORA (dir idx ext) + 8'hA9 : PG1_R2_O = 4'hd; // DMEM_RD ADCA (dir idx ext) + 8'hAA : PG1_R2_O = 4'hd; // DMEM_RD ORA (dir idx ext) + 8'hAB : PG1_R2_O = 4'hd; // DMEM_RD ADDA (dir idx ext) + 8'hAC : PG1_R2_O = 4'hd; // DMEM_RD CMPX (dir idx ext) + 8'hAD : PG1_R2_O = 4'hc; // EA JSR (idx) + 8'hAE : PG1_R2_O = 4'hd; // DMEM_RD LDX (dir idx ext) + 8'hB0 : PG1_R2_O = 4'hd; // DMEM_RD SUBA (dir idx ext) + 8'hB1 : PG1_R2_O = 4'hd; // DMEM_RD CMPA (dir idx ext) + 8'hB2 : PG1_R2_O = 4'hd; // DMEM_RD SBCA (dir idx ext) + 8'hB3 : PG1_R2_O = 4'hd; // DMEM_RD SUBD (dir idx ext) + 8'hB4 : PG1_R2_O = 4'hd; // DMEM_RD ANDA (dir idx ext) + 8'hB5 : PG1_R2_O = 4'hd; // DMEM_RD BITA (dir idx ext) + 8'hB6 : PG1_R2_O = 4'hd; // DMEM_RD LDA (dir idx ext) + 8'hB8 : PG1_R2_O = 4'hd; // DMEM_RD EORA (dir idx ext) + 8'hB9 : PG1_R2_O = 4'hd; // DMEM_RD ADCA (dir idx ext) + 8'hBA : PG1_R2_O = 4'hd; // DMEM_RD ORA (dir idx ext) + 8'hBB : PG1_R2_O = 4'hd; // DMEM_RD ADDA (dir idx ext) + 8'hBC : PG1_R2_O = 4'hd; // DMEM_RD CMPX (dir idx ext) + 8'hBD : PG1_R2_O = 4'he; // IDATA JSR (dir ext) + 8'hBE : PG1_R2_O = 4'hd; // DMEM_RD LDX (dir idx ext) + 8'hC0 : PG1_R2_O = 4'he; // IDATA SUBB (imm) + 8'hC1 : PG1_R2_O = 4'he; // IDATA CMPB (imm) + 8'hC2 : PG1_R2_O = 4'he; // IDATA SBCB (imm) + 8'hC3 : PG1_R2_O = 4'he; // IDATA ADDD (imm) + 8'hC4 : PG1_R2_O = 4'he; // IDATA ANDB (imm) + 8'hC5 : PG1_R2_O = 4'he; // IDATA BITB (imm) + 8'hC6 : PG1_R2_O = 4'he; // IDATA LDB (imm) + 8'hC8 : PG1_R2_O = 4'he; // IDATA EORB (imm) + 8'hC9 : PG1_R2_O = 4'he; // IDATA ADCB (imm) + 8'hCA : PG1_R2_O = 4'he; // IDATA ORB (imm) + 8'hCB : PG1_R2_O = 4'he; // IDATA ADDB (imm) + 8'hCC : PG1_R2_O = 4'he; // IDATA LDD (imm) + 8'hCE : PG1_R2_O = 4'he; // IDATA LDU (imm) + 8'hD0 : PG1_R2_O = 4'hd; // DMEM_RD SUBB (dir idx ext) + 8'hD1 : PG1_R2_O = 4'hd; // DMEM_RD CMPB (dir idx ext) + 8'hD2 : PG1_R2_O = 4'hd; // DMEM_RD SBCB (dir idx ext) + 8'hD3 : PG1_R2_O = 4'hd; // DMEM_RD ADDD (dir idx ext) + 8'hD4 : PG1_R2_O = 4'hd; // DMEM_RD ANDB (dir idx ext) + 8'hD5 : PG1_R2_O = 4'hd; // DMEM_RD BITB (dir idx ext) + 8'hD6 : PG1_R2_O = 4'hd; // DMEM_RD LDB (dir idx ext) + 8'hD8 : PG1_R2_O = 4'hd; // DMEM_RD EORB (dir idx ext) + 8'hD9 : PG1_R2_O = 4'hd; // DMEM_RD ADCB (dir idx ext) + 8'hDA : PG1_R2_O = 4'hd; // DMEM_RD ORB (dir idx ext) + 8'hDB : PG1_R2_O = 4'hd; // DMEM_RD ADDB (dir idx ext) + 8'hDC : PG1_R2_O = 4'hd; // DMEM_RD LDD (dir idx ext) + 8'hDE : PG1_R2_O = 4'hd; // DMEM_RD LDU (dir idx ext) + 8'hE0 : PG1_R2_O = 4'hd; // DMEM_RD SUBB (dir idx ext) + 8'hE1 : PG1_R2_O = 4'hd; // DMEM_RD CMPB (dir idx ext) + 8'hE2 : PG1_R2_O = 4'hd; // DMEM_RD SBCB (dir idx ext) + 8'hE3 : PG1_R2_O = 4'hd; // DMEM_RD ADDD (dir idx ext) + 8'hE4 : PG1_R2_O = 4'hd; // DMEM_RD ANDB (dir idx ext) + 8'hE5 : PG1_R2_O = 4'hd; // DMEM_RD BITB (dir idx ext) + 8'hE6 : PG1_R2_O = 4'hd; // DMEM_RD LDB (dir idx ext) + 8'hE8 : PG1_R2_O = 4'hd; // DMEM_RD EORB (dir idx ext) + 8'hE9 : PG1_R2_O = 4'hd; // DMEM_RD ADCB (dir idx ext) + 8'hEA : PG1_R2_O = 4'hd; // DMEM_RD ORB (dir idx ext) + 8'hEB : PG1_R2_O = 4'hd; // DMEM_RD ADDB (dir idx ext) + 8'hEC : PG1_R2_O = 4'hd; // DMEM_RD LDD (dir idx ext) + 8'hEE : PG1_R2_O = 4'hd; // DMEM_RD LDU (dir idx ext) + 8'hF0 : PG1_R2_O = 4'hd; // DMEM_RD SUBB (dir idx ext) + 8'hF1 : PG1_R2_O = 4'hd; // DMEM_RD CMPB (dir idx ext) + 8'hF2 : PG1_R2_O = 4'hd; // DMEM_RD SBCB (dir idx ext) + 8'hF3 : PG1_R2_O = 4'hd; // DMEM_RD ADDD (dir idx ext) + 8'hF4 : PG1_R2_O = 4'hd; // DMEM_RD ANDB (dir idx ext) + 8'hF5 : PG1_R2_O = 4'hd; // DMEM_RD BITB (dir idx ext) + 8'hF6 : PG1_R2_O = 4'hd; // DMEM_RD LDB (dir idx ext) + 8'hF8 : PG1_R2_O = 4'hd; // DMEM_RD EORB (dir idx ext) + 8'hF9 : PG1_R2_O = 4'hd; // DMEM_RD ADCB (dir idx ext) + 8'hFA : PG1_R2_O = 4'hd; // DMEM_RD ORB (dir idx ext) + 8'hFB : PG1_R2_O = 4'hd; // DMEM_RD ADDB (dir idx ext) + 8'hFC : PG1_R2_O = 4'hd; // DMEM_RD LDD (dir idx ext) + 8'hFE : PG1_R2_O = 4'hd; // DMEM_RD LDU (dir idx ext) + default : PG1_R2_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG1_R2_op; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R2_op = "NEG (dir idx ext)"; + 8'h03 : PG1_R2_op = "COM (dir idx ext)"; + 8'h0E : PG1_R2_op = "JMP (dir ext)"; + 8'h14 : PG1_R2_op = "EMUL (inh)"; + 8'h15 : PG1_R2_op = "EMULS (inh)"; + 8'h16 : PG1_R2_op = "LBRA "; + 8'h17 : PG1_R2_op = "BSR LBSR"; + 8'h18 : PG1_R2_op = "IDIV (inh)"; + 8'h1A : PG1_R2_op = "ORCC (imm)"; + 8'h1C : PG1_R2_op = "ANDCC (imm)"; + 8'h1D : PG1_R2_op = "SEX(inh)"; + 8'h20 : PG1_R2_op = "BRA BRN BHI BLS"; + 8'h21 : PG1_R2_op = "BRA BRN BHI BLS"; + 8'h22 : PG1_R2_op = "BRA BRN BHI BLS"; + 8'h23 : PG1_R2_op = "BRA BRN BHI BLS"; + 8'h24 : PG1_R2_op = "BCC BCS BNE BEQ"; + 8'h25 : PG1_R2_op = "BCC BCS BNE BEQ"; + 8'h26 : PG1_R2_op = "BCC BCS BNE BEQ"; + 8'h27 : PG1_R2_op = "BCC BCS BNE BEQ"; + 8'h28 : PG1_R2_op = "BVC BVS BPL BMI"; + 8'h29 : PG1_R2_op = "BVC BVS BPL BMI"; + 8'h2A : PG1_R2_op = "BVC BVS BPL BMI"; + 8'h2B : PG1_R2_op = "BVC BVS BPL BMI"; + 8'h2C : PG1_R2_op = "BGE BLT BGT BLE"; + 8'h2D : PG1_R2_op = "BGE BLT BGT BLE"; + 8'h2E : PG1_R2_op = "BGE BLT BGT BLE"; + 8'h2F : PG1_R2_op = "BGE BLT BGT BLE"; + 8'h39 : PG1_R2_op = "RTS"; + 8'h3A : PG1_R2_op = "ABX(inh)"; + 8'h3B : PG1_R2_op = "RTI"; + 8'h3F : PG1_R2_op = "SWI"; + 8'h40 : PG1_R2_op = "NEGA (inh)"; + 8'h43 : PG1_R2_op = "COMA (inh)"; + 8'h50 : PG1_R2_op = "NEGB (inh)"; + 8'h53 : PG1_R2_op = "COMB (inh)"; + 8'h60 : PG1_R2_op = "NEG (dir idx ext)"; + 8'h63 : PG1_R2_op = "COM (dir idx ext)"; + 8'h6E : PG1_R2_op = "JMP (idx)"; + 8'h70 : PG1_R2_op = "NEG (dir idx ext)"; + 8'h73 : PG1_R2_op = "COM (dir idx ext)"; + 8'h7E : PG1_R2_op = "JMP (dir ext)"; + 8'h80 : PG1_R2_op = "SUBA (imm)"; + 8'h81 : PG1_R2_op = "CMPA (imm)"; + 8'h82 : PG1_R2_op = "SBCA (imm)"; + 8'h83 : PG1_R2_op = "SUBD (imm)"; + 8'h84 : PG1_R2_op = "ANDA (imm)"; + 8'h85 : PG1_R2_op = "BITA (imm)"; + 8'h86 : PG1_R2_op = "LDA (imm)"; + 8'h88 : PG1_R2_op = "EORA (imm)"; + 8'h89 : PG1_R2_op = "ADCA (imm)"; + 8'h8A : PG1_R2_op = "ORA (imm)"; + 8'h8B : PG1_R2_op = "ADDA (imm)"; + 8'h8C : PG1_R2_op = "CMPX (imm)"; + 8'h8D : PG1_R2_op = "BSR LBSR"; + 8'h8E : PG1_R2_op = "LDX (imm)"; + 8'h90 : PG1_R2_op = "SUBA (dir idx ext)"; + 8'h91 : PG1_R2_op = "CMPA (dir idx ext)"; + 8'h92 : PG1_R2_op = "SBCA (dir idx ext)"; + 8'h93 : PG1_R2_op = "SUBD (dir idx ext)"; + 8'h94 : PG1_R2_op = "ANDA (dir idx ext)"; + 8'h95 : PG1_R2_op = "BITA (dir idx ext)"; + 8'h96 : PG1_R2_op = "LDA (dir idx ext)"; + 8'h98 : PG1_R2_op = "EORA (dir idx ext)"; + 8'h99 : PG1_R2_op = "ADCA (dir idx ext)"; + 8'h9A : PG1_R2_op = "ORA (dir idx ext)"; + 8'h9B : PG1_R2_op = "ADDA (dir idx ext)"; + 8'h9C : PG1_R2_op = "CMPX (dir idx ext)"; + 8'h9D : PG1_R2_op = "JSR (dir ext)"; + 8'h9E : PG1_R2_op = "LDX (dir idx ext)"; + 8'hA0 : PG1_R2_op = "SUBA (dir idx ext)"; + 8'hA1 : PG1_R2_op = "CMPA (dir idx ext)"; + 8'hA2 : PG1_R2_op = "SBCA (dir idx ext)"; + 8'hA3 : PG1_R2_op = "SUBD (dir idx ext)"; + 8'hA4 : PG1_R2_op = "ANDA (dir idx ext)"; + 8'hA5 : PG1_R2_op = "BITA (dir idx ext)"; + 8'hA6 : PG1_R2_op = "LDA (dir idx ext)"; + 8'hA8 : PG1_R2_op = "EORA (dir idx ext)"; + 8'hA9 : PG1_R2_op = "ADCA (dir idx ext)"; + 8'hAA : PG1_R2_op = "ORA (dir idx ext)"; + 8'hAB : PG1_R2_op = "ADDA (dir idx ext)"; + 8'hAC : PG1_R2_op = "CMPX (dir idx ext)"; + 8'hAD : PG1_R2_op = "JSR (idx)"; + 8'hAE : PG1_R2_op = "LDX (dir idx ext)"; + 8'hB0 : PG1_R2_op = "SUBA (dir idx ext)"; + 8'hB1 : PG1_R2_op = "CMPA (dir idx ext)"; + 8'hB2 : PG1_R2_op = "SBCA (dir idx ext)"; + 8'hB3 : PG1_R2_op = "SUBD (dir idx ext)"; + 8'hB4 : PG1_R2_op = "ANDA (dir idx ext)"; + 8'hB5 : PG1_R2_op = "BITA (dir idx ext)"; + 8'hB6 : PG1_R2_op = "LDA (dir idx ext)"; + 8'hB8 : PG1_R2_op = "EORA (dir idx ext)"; + 8'hB9 : PG1_R2_op = "ADCA (dir idx ext)"; + 8'hBA : PG1_R2_op = "ORA (dir idx ext)"; + 8'hBB : PG1_R2_op = "ADDA (dir idx ext)"; + 8'hBC : PG1_R2_op = "CMPX (dir idx ext)"; + 8'hBD : PG1_R2_op = "JSR (dir ext)"; + 8'hBE : PG1_R2_op = "LDX (dir idx ext)"; + 8'hC0 : PG1_R2_op = "SUBB (imm)"; + 8'hC1 : PG1_R2_op = "CMPB (imm)"; + 8'hC2 : PG1_R2_op = "SBCB (imm)"; + 8'hC3 : PG1_R2_op = "ADDD (imm)"; + 8'hC4 : PG1_R2_op = "ANDB (imm)"; + 8'hC5 : PG1_R2_op = "BITB (imm)"; + 8'hC6 : PG1_R2_op = "LDB (imm)"; + 8'hC8 : PG1_R2_op = "EORB (imm)"; + 8'hC9 : PG1_R2_op = "ADCB (imm)"; + 8'hCA : PG1_R2_op = "ORB (imm)"; + 8'hCB : PG1_R2_op = "ADDB (imm)"; + 8'hCC : PG1_R2_op = "LDD (imm)"; + 8'hCE : PG1_R2_op = "LDU (imm)"; + 8'hD0 : PG1_R2_op = "SUBB (dir idx ext)"; + 8'hD1 : PG1_R2_op = "CMPB (dir idx ext)"; + 8'hD2 : PG1_R2_op = "SBCB (dir idx ext)"; + 8'hD3 : PG1_R2_op = "ADDD (dir idx ext)"; + 8'hD4 : PG1_R2_op = "ANDB (dir idx ext)"; + 8'hD5 : PG1_R2_op = "BITB (dir idx ext)"; + 8'hD6 : PG1_R2_op = "LDB (dir idx ext)"; + 8'hD8 : PG1_R2_op = "EORB (dir idx ext)"; + 8'hD9 : PG1_R2_op = "ADCB (dir idx ext)"; + 8'hDA : PG1_R2_op = "ORB (dir idx ext)"; + 8'hDB : PG1_R2_op = "ADDB (dir idx ext)"; + 8'hDC : PG1_R2_op = "LDD (dir idx ext)"; + 8'hDE : PG1_R2_op = "LDU (dir idx ext)"; + 8'hE0 : PG1_R2_op = "SUBB (dir idx ext)"; + 8'hE1 : PG1_R2_op = "CMPB (dir idx ext)"; + 8'hE2 : PG1_R2_op = "SBCB (dir idx ext)"; + 8'hE3 : PG1_R2_op = "ADDD (dir idx ext)"; + 8'hE4 : PG1_R2_op = "ANDB (dir idx ext)"; + 8'hE5 : PG1_R2_op = "BITB (dir idx ext)"; + 8'hE6 : PG1_R2_op = "LDB (dir idx ext)"; + 8'hE8 : PG1_R2_op = "EORB (dir idx ext)"; + 8'hE9 : PG1_R2_op = "ADCB (dir idx ext)"; + 8'hEA : PG1_R2_op = "ORB (dir idx ext)"; + 8'hEB : PG1_R2_op = "ADDB (dir idx ext)"; + 8'hEC : PG1_R2_op = "LDD (dir idx ext)"; + 8'hEE : PG1_R2_op = "LDU (dir idx ext)"; + 8'hF0 : PG1_R2_op = "SUBB (dir idx ext)"; + 8'hF1 : PG1_R2_op = "CMPB (dir idx ext)"; + 8'hF2 : PG1_R2_op = "SBCB (dir idx ext)"; + 8'hF3 : PG1_R2_op = "ADDD (dir idx ext)"; + 8'hF4 : PG1_R2_op = "ANDB (dir idx ext)"; + 8'hF5 : PG1_R2_op = "BITB (dir idx ext)"; + 8'hF6 : PG1_R2_op = "LDB (dir idx ext)"; + 8'hF8 : PG1_R2_op = "EORB (dir idx ext)"; + 8'hF9 : PG1_R2_op = "ADCB (dir idx ext)"; + 8'hFA : PG1_R2_op = "ORB (dir idx ext)"; + 8'hFB : PG1_R2_op = "ADDB (dir idx ext)"; + 8'hFC : PG1_R2_op = "LDD (dir idx ext)"; + 8'hFE : PG1_R2_op = "LDU (dir idx ext)"; + default : PG1_R2_op = "invalid"; + endcase +end + +reg [(8*64):0] PG1_R2_eq; + +always @* begin + case (OPCODE_I) + 8'h00 : PG1_R2_eq = "DMEM_RD"; + 8'h03 : PG1_R2_eq = "DMEM_RD"; + 8'h0E : PG1_R2_eq = "IDATA"; + 8'h14 : PG1_R2_eq = "Y"; + 8'h15 : PG1_R2_eq = "Y"; + 8'h16 : PG1_R2_eq = "EA"; + 8'h17 : PG1_R2_eq = "EA"; + 8'h18 : PG1_R2_eq = "D"; + 8'h1A : PG1_R2_eq = "IDATA"; + 8'h1C : PG1_R2_eq = "IDATA"; + 8'h1D : PG1_R2_eq = "SEXB"; + 8'h20 : PG1_R2_eq = "EA"; + 8'h21 : PG1_R2_eq = "EA"; + 8'h22 : PG1_R2_eq = "EA"; + 8'h23 : PG1_R2_eq = "EA"; + 8'h24 : PG1_R2_eq = "EA"; + 8'h25 : PG1_R2_eq = "EA"; + 8'h26 : PG1_R2_eq = "EA"; + 8'h27 : PG1_R2_eq = "EA"; + 8'h28 : PG1_R2_eq = "EA"; + 8'h29 : PG1_R2_eq = "EA"; + 8'h2A : PG1_R2_eq = "EA"; + 8'h2B : PG1_R2_eq = "EA"; + 8'h2C : PG1_R2_eq = "EA"; + 8'h2D : PG1_R2_eq = "EA"; + 8'h2E : PG1_R2_eq = "EA"; + 8'h2F : PG1_R2_eq = "EA"; + 8'h39 : PG1_R2_eq = "DMEM_RD"; + 8'h3A : PG1_R2_eq = "B"; + 8'h3B : PG1_R2_eq = "DMEM_RD"; + 8'h3F : PG1_R2_eq = "DMEM_RD"; + 8'h40 : PG1_R2_eq = "A"; + 8'h43 : PG1_R2_eq = "A"; + 8'h50 : PG1_R2_eq = "B"; + 8'h53 : PG1_R2_eq = "B"; + 8'h60 : PG1_R2_eq = "DMEM_RD"; + 8'h63 : PG1_R2_eq = "DMEM_RD"; + 8'h6E : PG1_R2_eq = "EA"; + 8'h70 : PG1_R2_eq = "DMEM_RD"; + 8'h73 : PG1_R2_eq = "DMEM_RD"; + 8'h7E : PG1_R2_eq = "IDATA"; + 8'h80 : PG1_R2_eq = "IDATA"; + 8'h81 : PG1_R2_eq = "IDATA"; + 8'h82 : PG1_R2_eq = "IDATA"; + 8'h83 : PG1_R2_eq = "IDATA"; + 8'h84 : PG1_R2_eq = "IDATA"; + 8'h85 : PG1_R2_eq = "IDATA"; + 8'h86 : PG1_R2_eq = "IDATA"; + 8'h88 : PG1_R2_eq = "IDATA"; + 8'h89 : PG1_R2_eq = "IDATA"; + 8'h8A : PG1_R2_eq = "IDATA"; + 8'h8B : PG1_R2_eq = "IDATA"; + 8'h8C : PG1_R2_eq = "IDATA"; + 8'h8D : PG1_R2_eq = "EA"; + 8'h8E : PG1_R2_eq = "IDATA"; + 8'h90 : PG1_R2_eq = "DMEM_RD"; + 8'h91 : PG1_R2_eq = "DMEM_RD"; + 8'h92 : PG1_R2_eq = "DMEM_RD"; + 8'h93 : PG1_R2_eq = "DMEM_RD"; + 8'h94 : PG1_R2_eq = "DMEM_RD"; + 8'h95 : PG1_R2_eq = "DMEM_RD"; + 8'h96 : PG1_R2_eq = "DMEM_RD"; + 8'h98 : PG1_R2_eq = "DMEM_RD"; + 8'h99 : PG1_R2_eq = "DMEM_RD"; + 8'h9A : PG1_R2_eq = "DMEM_RD"; + 8'h9B : PG1_R2_eq = "DMEM_RD"; + 8'h9C : PG1_R2_eq = "DMEM_RD"; + 8'h9D : PG1_R2_eq = "IDATA"; + 8'h9E : PG1_R2_eq = "DMEM_RD"; + 8'hA0 : PG1_R2_eq = "DMEM_RD"; + 8'hA1 : PG1_R2_eq = "DMEM_RD"; + 8'hA2 : PG1_R2_eq = "DMEM_RD"; + 8'hA3 : PG1_R2_eq = "DMEM_RD"; + 8'hA4 : PG1_R2_eq = "DMEM_RD"; + 8'hA5 : PG1_R2_eq = "DMEM_RD"; + 8'hA6 : PG1_R2_eq = "DMEM_RD"; + 8'hA8 : PG1_R2_eq = "DMEM_RD"; + 8'hA9 : PG1_R2_eq = "DMEM_RD"; + 8'hAA : PG1_R2_eq = "DMEM_RD"; + 8'hAB : PG1_R2_eq = "DMEM_RD"; + 8'hAC : PG1_R2_eq = "DMEM_RD"; + 8'hAD : PG1_R2_eq = "EA"; + 8'hAE : PG1_R2_eq = "DMEM_RD"; + 8'hB0 : PG1_R2_eq = "DMEM_RD"; + 8'hB1 : PG1_R2_eq = "DMEM_RD"; + 8'hB2 : PG1_R2_eq = "DMEM_RD"; + 8'hB3 : PG1_R2_eq = "DMEM_RD"; + 8'hB4 : PG1_R2_eq = "DMEM_RD"; + 8'hB5 : PG1_R2_eq = "DMEM_RD"; + 8'hB6 : PG1_R2_eq = "DMEM_RD"; + 8'hB8 : PG1_R2_eq = "DMEM_RD"; + 8'hB9 : PG1_R2_eq = "DMEM_RD"; + 8'hBA : PG1_R2_eq = "DMEM_RD"; + 8'hBB : PG1_R2_eq = "DMEM_RD"; + 8'hBC : PG1_R2_eq = "DMEM_RD"; + 8'hBD : PG1_R2_eq = "IDATA"; + 8'hBE : PG1_R2_eq = "DMEM_RD"; + 8'hC0 : PG1_R2_eq = "IDATA"; + 8'hC1 : PG1_R2_eq = "IDATA"; + 8'hC2 : PG1_R2_eq = "IDATA"; + 8'hC3 : PG1_R2_eq = "IDATA"; + 8'hC4 : PG1_R2_eq = "IDATA"; + 8'hC5 : PG1_R2_eq = "IDATA"; + 8'hC6 : PG1_R2_eq = "IDATA"; + 8'hC8 : PG1_R2_eq = "IDATA"; + 8'hC9 : PG1_R2_eq = "IDATA"; + 8'hCA : PG1_R2_eq = "IDATA"; + 8'hCB : PG1_R2_eq = "IDATA"; + 8'hCC : PG1_R2_eq = "IDATA"; + 8'hCE : PG1_R2_eq = "IDATA"; + 8'hD0 : PG1_R2_eq = "DMEM_RD"; + 8'hD1 : PG1_R2_eq = "DMEM_RD"; + 8'hD2 : PG1_R2_eq = "DMEM_RD"; + 8'hD3 : PG1_R2_eq = "DMEM_RD"; + 8'hD4 : PG1_R2_eq = "DMEM_RD"; + 8'hD5 : PG1_R2_eq = "DMEM_RD"; + 8'hD6 : PG1_R2_eq = "DMEM_RD"; + 8'hD8 : PG1_R2_eq = "DMEM_RD"; + 8'hD9 : PG1_R2_eq = "DMEM_RD"; + 8'hDA : PG1_R2_eq = "DMEM_RD"; + 8'hDB : PG1_R2_eq = "DMEM_RD"; + 8'hDC : PG1_R2_eq = "DMEM_RD"; + 8'hDE : PG1_R2_eq = "DMEM_RD"; + 8'hE0 : PG1_R2_eq = "DMEM_RD"; + 8'hE1 : PG1_R2_eq = "DMEM_RD"; + 8'hE2 : PG1_R2_eq = "DMEM_RD"; + 8'hE3 : PG1_R2_eq = "DMEM_RD"; + 8'hE4 : PG1_R2_eq = "DMEM_RD"; + 8'hE5 : PG1_R2_eq = "DMEM_RD"; + 8'hE6 : PG1_R2_eq = "DMEM_RD"; + 8'hE8 : PG1_R2_eq = "DMEM_RD"; + 8'hE9 : PG1_R2_eq = "DMEM_RD"; + 8'hEA : PG1_R2_eq = "DMEM_RD"; + 8'hEB : PG1_R2_eq = "DMEM_RD"; + 8'hEC : PG1_R2_eq = "DMEM_RD"; + 8'hEE : PG1_R2_eq = "DMEM_RD"; + 8'hF0 : PG1_R2_eq = "DMEM_RD"; + 8'hF1 : PG1_R2_eq = "DMEM_RD"; + 8'hF2 : PG1_R2_eq = "DMEM_RD"; + 8'hF3 : PG1_R2_eq = "DMEM_RD"; + 8'hF4 : PG1_R2_eq = "DMEM_RD"; + 8'hF5 : PG1_R2_eq = "DMEM_RD"; + 8'hF6 : PG1_R2_eq = "DMEM_RD"; + 8'hF8 : PG1_R2_eq = "DMEM_RD"; + 8'hF9 : PG1_R2_eq = "DMEM_RD"; + 8'hFA : PG1_R2_eq = "DMEM_RD"; + 8'hFB : PG1_R2_eq = "DMEM_RD"; + 8'hFC : PG1_R2_eq = "DMEM_RD"; + 8'hFE : PG1_R2_eq = "DMEM_RD"; + default : PG1_R2_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_AR.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_AR.v new file mode 100644 index 0000000000000000000000000000000000000000..9b997389f4bbc46784ee31a8ab3fa35197c8b828 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_AR.v @@ -0,0 +1,106 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_AR_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg2_AR( + input [7:0] OPCODE_I, + output reg [3:0] PG2_AR_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h9F : PG2_AR_O = 4'he; // IDATA STY (dir ext) + 8'hAF : PG2_AR_O = 4'hc; // EA STY (idx) + 8'hBF : PG2_AR_O = 4'he; // IDATA STY (dir ext) + 8'hDF : PG2_AR_O = 4'he; // IDATA STS (dir ext) + 8'hEF : PG2_AR_O = 4'hc; // EA STS (idx) + 8'hFF : PG2_AR_O = 4'he; // IDATA STS (dir ext) + default : PG2_AR_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG2_AR_op; + +always @* begin + case (OPCODE_I) + 8'h9F : PG2_AR_op = "STY (dir ext)"; + 8'hAF : PG2_AR_op = "STY (idx)"; + 8'hBF : PG2_AR_op = "STY (dir ext)"; + 8'hDF : PG2_AR_op = "STS (dir ext)"; + 8'hEF : PG2_AR_op = "STS (idx)"; + 8'hFF : PG2_AR_op = "STS (dir ext)"; + default : PG2_AR_op = "invalid"; + endcase +end + +reg [(8*64):0] PG2_AR_eq; + +always @* begin + case (OPCODE_I) + 8'h9F : PG2_AR_eq = "IDATA"; + 8'hAF : PG2_AR_eq = "EA"; + 8'hBF : PG2_AR_eq = "IDATA"; + 8'hDF : PG2_AR_eq = "IDATA"; + 8'hEF : PG2_AR_eq = "EA"; + 8'hFF : PG2_AR_eq = "IDATA"; + default : PG2_AR_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTA.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTA.v new file mode 100644 index 0000000000000000000000000000000000000000..744d401303aaf3737416f06f471b9a480b3ed726 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTA.v @@ -0,0 +1,217 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg2_JTA( + input [7:0] OPCODE_I, + output reg [7:0] PG2_JTA_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_JTA_O = 8'hd; // SAU16 EDIV (inh) + 8'h15 : PG2_JTA_O = 8'hd; // SAU16 EDIVS (inh) + 8'h18 : PG2_JTA_O = 8'hd; // SAU16 IDIVS (inh) + 8'h19 : PG2_JTA_O = 8'hd; // SAU16 FDIV (inh) + 8'h1F : PG2_JTA_O = 8'h12; // CPY CPY (inh) + 8'h20 : PG2_JTA_O = 8'h2e; // BRANCH LBRA LBRN LBHI LBLS + 8'h21 : PG2_JTA_O = 8'h2e; // BRANCH LBRA LBRN LBHI LBLS + 8'h22 : PG2_JTA_O = 8'h2e; // BRANCH LBRA LBRN LBHI LBLS + 8'h23 : PG2_JTA_O = 8'h2e; // BRANCH LBRA LBRN LBHI LBLS + 8'h24 : PG2_JTA_O = 8'h2e; // BRANCH LBCC LBCS LBNE LBEQ + 8'h25 : PG2_JTA_O = 8'h2e; // BRANCH LBCC LBCS LBNE LBEQ + 8'h26 : PG2_JTA_O = 8'h2e; // BRANCH LBCC LBCS LBNE LBEQ + 8'h27 : PG2_JTA_O = 8'h2e; // BRANCH LBCC LBCS LBNE LBEQ + 8'h28 : PG2_JTA_O = 8'h2e; // BRANCH LBVC LBVS LBPL LBMI + 8'h29 : PG2_JTA_O = 8'h2e; // BRANCH LBVC LBVS LBPL LBMI + 8'h2A : PG2_JTA_O = 8'h2e; // BRANCH LBVC LBVS LBPL LBMI + 8'h2B : PG2_JTA_O = 8'h2e; // BRANCH LBVC LBVS LBPL LBMI + 8'h2C : PG2_JTA_O = 8'h2e; // BRANCH LBGE LBLT LBGT LBLE + 8'h2D : PG2_JTA_O = 8'h2e; // BRANCH LBGE LBLT LBGT LBLE + 8'h2E : PG2_JTA_O = 8'h2e; // BRANCH LBGE LBLT LBGT LBLE + 8'h2F : PG2_JTA_O = 8'h2e; // BRANCH LBGE LBLT LBGT LBLE + 8'h83 : PG2_JTA_O = 8'h1b; // CMP CMPD (imm) + 8'h8C : PG2_JTA_O = 8'h1b; // CMP CMPY (imm) + 8'h8E : PG2_JTA_O = 8'h1d; // LD LDY (imm) + 8'h93 : PG2_JTA_O = 8'h1; // LD_DIR_EXT CMPD (dir ext) + 8'h9C : PG2_JTA_O = 8'h1; // LD_DIR_EXT CMPY (dir ext) + 8'h9E : PG2_JTA_O = 8'h1; // LD_DIR_EXT LDY (dir ext) + 8'h9F : PG2_JTA_O = 8'h22; // ST STY (dir ext) + 8'hA3 : PG2_JTA_O = 8'h2; // LD_INDEXED CMPD (idx) + 8'hAC : PG2_JTA_O = 8'h2; // LD_INDEXED CMPY (idx) + 8'hAE : PG2_JTA_O = 8'h2; // LD_INDEXED LDY (idx) + 8'hAF : PG2_JTA_O = 8'h4; // ST_INDEXED STY (idx) + 8'hB3 : PG2_JTA_O = 8'h1; // LD_DIR_EXT CMPD (dir ext) + 8'hBC : PG2_JTA_O = 8'h1; // LD_DIR_EXT CMPY (dir ext) + 8'hBE : PG2_JTA_O = 8'h1; // LD_DIR_EXT LDY (dir ext) + 8'hBF : PG2_JTA_O = 8'h22; // ST STY (dir ext) + 8'hCE : PG2_JTA_O = 8'h1d; // LD LDS (imm) + 8'hDE : PG2_JTA_O = 8'h1; // LD_DIR_EXT LDS (dir ext) + 8'hDF : PG2_JTA_O = 8'h22; // ST STS (dir ext) + 8'hEE : PG2_JTA_O = 8'h2; // LD_INDEXED LDS (idx) + 8'hEF : PG2_JTA_O = 8'h4; // ST_INDEXED STS (idx) + 8'hFE : PG2_JTA_O = 8'h1; // LD_DIR_EXT LDS (dir ext) + 8'hFF : PG2_JTA_O = 8'h22; // ST STS (dir ext) + default : PG2_JTA_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG2_JTA_op; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_JTA_op = "EDIV (inh)"; + 8'h15 : PG2_JTA_op = "EDIVS (inh)"; + 8'h18 : PG2_JTA_op = "IDIVS (inh)"; + 8'h19 : PG2_JTA_op = "FDIV (inh)"; + 8'h1F : PG2_JTA_op = "CPY (inh)"; + 8'h20 : PG2_JTA_op = "LBRA LBRN LBHI LBLS"; + 8'h21 : PG2_JTA_op = "LBRA LBRN LBHI LBLS"; + 8'h22 : PG2_JTA_op = "LBRA LBRN LBHI LBLS"; + 8'h23 : PG2_JTA_op = "LBRA LBRN LBHI LBLS"; + 8'h24 : PG2_JTA_op = "LBCC LBCS LBNE LBEQ"; + 8'h25 : PG2_JTA_op = "LBCC LBCS LBNE LBEQ"; + 8'h26 : PG2_JTA_op = "LBCC LBCS LBNE LBEQ"; + 8'h27 : PG2_JTA_op = "LBCC LBCS LBNE LBEQ"; + 8'h28 : PG2_JTA_op = "LBVC LBVS LBPL LBMI"; + 8'h29 : PG2_JTA_op = "LBVC LBVS LBPL LBMI"; + 8'h2A : PG2_JTA_op = "LBVC LBVS LBPL LBMI"; + 8'h2B : PG2_JTA_op = "LBVC LBVS LBPL LBMI"; + 8'h2C : PG2_JTA_op = "LBGE LBLT LBGT LBLE"; + 8'h2D : PG2_JTA_op = "LBGE LBLT LBGT LBLE"; + 8'h2E : PG2_JTA_op = "LBGE LBLT LBGT LBLE"; + 8'h2F : PG2_JTA_op = "LBGE LBLT LBGT LBLE"; + 8'h83 : PG2_JTA_op = "CMPD (imm)"; + 8'h8C : PG2_JTA_op = "CMPY (imm)"; + 8'h8E : PG2_JTA_op = "LDY (imm)"; + 8'h93 : PG2_JTA_op = "CMPD (dir ext)"; + 8'h9C : PG2_JTA_op = "CMPY (dir ext)"; + 8'h9E : PG2_JTA_op = "LDY (dir ext)"; + 8'h9F : PG2_JTA_op = "STY (dir ext)"; + 8'hA3 : PG2_JTA_op = "CMPD (idx)"; + 8'hAC : PG2_JTA_op = "CMPY (idx)"; + 8'hAE : PG2_JTA_op = "LDY (idx)"; + 8'hAF : PG2_JTA_op = "STY (idx)"; + 8'hB3 : PG2_JTA_op = "CMPD (dir ext)"; + 8'hBC : PG2_JTA_op = "CMPY (dir ext)"; + 8'hBE : PG2_JTA_op = "LDY (dir ext)"; + 8'hBF : PG2_JTA_op = "STY (dir ext)"; + 8'hCE : PG2_JTA_op = "LDS (imm)"; + 8'hDE : PG2_JTA_op = "LDS (dir ext)"; + 8'hDF : PG2_JTA_op = "STS (dir ext)"; + 8'hEE : PG2_JTA_op = "LDS (idx)"; + 8'hEF : PG2_JTA_op = "STS (idx)"; + 8'hFE : PG2_JTA_op = "LDS (dir ext)"; + 8'hFF : PG2_JTA_op = "STS (dir ext)"; + default : PG2_JTA_op = "invalid"; + endcase +end + +reg [(8*64):0] PG2_JTA_eq; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_JTA_eq = "SAU16"; + 8'h15 : PG2_JTA_eq = "SAU16"; + 8'h18 : PG2_JTA_eq = "SAU16"; + 8'h19 : PG2_JTA_eq = "SAU16"; + 8'h1F : PG2_JTA_eq = "CPY"; + 8'h20 : PG2_JTA_eq = "BRANCH"; + 8'h21 : PG2_JTA_eq = "BRANCH"; + 8'h22 : PG2_JTA_eq = "BRANCH"; + 8'h23 : PG2_JTA_eq = "BRANCH"; + 8'h24 : PG2_JTA_eq = "BRANCH"; + 8'h25 : PG2_JTA_eq = "BRANCH"; + 8'h26 : PG2_JTA_eq = "BRANCH"; + 8'h27 : PG2_JTA_eq = "BRANCH"; + 8'h28 : PG2_JTA_eq = "BRANCH"; + 8'h29 : PG2_JTA_eq = "BRANCH"; + 8'h2A : PG2_JTA_eq = "BRANCH"; + 8'h2B : PG2_JTA_eq = "BRANCH"; + 8'h2C : PG2_JTA_eq = "BRANCH"; + 8'h2D : PG2_JTA_eq = "BRANCH"; + 8'h2E : PG2_JTA_eq = "BRANCH"; + 8'h2F : PG2_JTA_eq = "BRANCH"; + 8'h83 : PG2_JTA_eq = "CMP"; + 8'h8C : PG2_JTA_eq = "CMP"; + 8'h8E : PG2_JTA_eq = "LD"; + 8'h93 : PG2_JTA_eq = "LD_DIR_EXT"; + 8'h9C : PG2_JTA_eq = "LD_DIR_EXT"; + 8'h9E : PG2_JTA_eq = "LD_DIR_EXT"; + 8'h9F : PG2_JTA_eq = "ST"; + 8'hA3 : PG2_JTA_eq = "LD_INDEXED"; + 8'hAC : PG2_JTA_eq = "LD_INDEXED"; + 8'hAE : PG2_JTA_eq = "LD_INDEXED"; + 8'hAF : PG2_JTA_eq = "ST_INDEXED"; + 8'hB3 : PG2_JTA_eq = "LD_DIR_EXT"; + 8'hBC : PG2_JTA_eq = "LD_DIR_EXT"; + 8'hBE : PG2_JTA_eq = "LD_DIR_EXT"; + 8'hBF : PG2_JTA_eq = "ST"; + 8'hCE : PG2_JTA_eq = "LD"; + 8'hDE : PG2_JTA_eq = "LD_DIR_EXT"; + 8'hDF : PG2_JTA_eq = "ST"; + 8'hEE : PG2_JTA_eq = "LD_INDEXED"; + 8'hEF : PG2_JTA_eq = "ST_INDEXED"; + 8'hFE : PG2_JTA_eq = "LD_DIR_EXT"; + 8'hFF : PG2_JTA_eq = "ST"; + default : PG2_JTA_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTB.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTB.v new file mode 100644 index 0000000000000000000000000000000000000000..66a73411acf6e80eee41ccd387396f140e599475 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_JTB.v @@ -0,0 +1,178 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg2_JTB( + input [7:0] OPCODE_I, + output reg [7:0] PG2_JTB_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h20 : PG2_JTB_O = 8'h30; // JMP LBRA LBRN LBHI LBLS + 8'h21 : PG2_JTB_O = 8'h30; // JMP LBRA LBRN LBHI LBLS + 8'h22 : PG2_JTB_O = 8'h30; // JMP LBRA LBRN LBHI LBLS + 8'h23 : PG2_JTB_O = 8'h30; // JMP LBRA LBRN LBHI LBLS + 8'h24 : PG2_JTB_O = 8'h30; // JMP LBCC LBCS LBNE LBEQ + 8'h25 : PG2_JTB_O = 8'h30; // JMP LBCC LBCS LBNE LBEQ + 8'h26 : PG2_JTB_O = 8'h30; // JMP LBCC LBCS LBNE LBEQ + 8'h27 : PG2_JTB_O = 8'h30; // JMP LBCC LBCS LBNE LBEQ + 8'h28 : PG2_JTB_O = 8'h30; // JMP LBVC LBVS LBPL LBMI + 8'h29 : PG2_JTB_O = 8'h30; // JMP LBVC LBVS LBPL LBMI + 8'h2A : PG2_JTB_O = 8'h30; // JMP LBVC LBVS LBPL LBMI + 8'h2B : PG2_JTB_O = 8'h30; // JMP LBVC LBVS LBPL LBMI + 8'h2C : PG2_JTB_O = 8'h30; // JMP LBGE LBLT LBGT LBLE + 8'h2D : PG2_JTB_O = 8'h30; // JMP LBGE LBLT LBGT LBLE + 8'h2E : PG2_JTB_O = 8'h30; // JMP LBGE LBLT LBGT LBLE + 8'h2F : PG2_JTB_O = 8'h30; // JMP LBGE LBLT LBGT LBLE + 8'h93 : PG2_JTB_O = 8'h1b; // CMP CMPD (dir idx ext) + 8'h9C : PG2_JTB_O = 8'h1b; // CMP CMPY (dir idx ext) + 8'h9E : PG2_JTB_O = 8'h1d; // LD LDY (dir idx ext) + 8'hA3 : PG2_JTB_O = 8'h1b; // CMP CMPD (dir idx ext) + 8'hAC : PG2_JTB_O = 8'h1b; // CMP CMPY (dir idx ext) + 8'hAE : PG2_JTB_O = 8'h1d; // LD LDY (dir idx ext) + 8'hAF : PG2_JTB_O = 8'h22; // ST STY (idx) + 8'hB3 : PG2_JTB_O = 8'h1b; // CMP CMPD (dir idx ext) + 8'hBC : PG2_JTB_O = 8'h1b; // CMP CMPY (dir idx ext) + 8'hBE : PG2_JTB_O = 8'h1d; // LD LDY (dir idx ext) + 8'hDE : PG2_JTB_O = 8'h1d; // LD LDS (dir idx ext) + 8'hEE : PG2_JTB_O = 8'h1d; // LD LDS (dir idx ext) + 8'hEF : PG2_JTB_O = 8'h22; // ST STS (idx) + 8'hFE : PG2_JTB_O = 8'h1d; // LD LDS (dir idx ext) + default : PG2_JTB_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG2_JTB_op; + +always @* begin + case (OPCODE_I) + 8'h20 : PG2_JTB_op = "LBRA LBRN LBHI LBLS"; + 8'h21 : PG2_JTB_op = "LBRA LBRN LBHI LBLS"; + 8'h22 : PG2_JTB_op = "LBRA LBRN LBHI LBLS"; + 8'h23 : PG2_JTB_op = "LBRA LBRN LBHI LBLS"; + 8'h24 : PG2_JTB_op = "LBCC LBCS LBNE LBEQ"; + 8'h25 : PG2_JTB_op = "LBCC LBCS LBNE LBEQ"; + 8'h26 : PG2_JTB_op = "LBCC LBCS LBNE LBEQ"; + 8'h27 : PG2_JTB_op = "LBCC LBCS LBNE LBEQ"; + 8'h28 : PG2_JTB_op = "LBVC LBVS LBPL LBMI"; + 8'h29 : PG2_JTB_op = "LBVC LBVS LBPL LBMI"; + 8'h2A : PG2_JTB_op = "LBVC LBVS LBPL LBMI"; + 8'h2B : PG2_JTB_op = "LBVC LBVS LBPL LBMI"; + 8'h2C : PG2_JTB_op = "LBGE LBLT LBGT LBLE"; + 8'h2D : PG2_JTB_op = "LBGE LBLT LBGT LBLE"; + 8'h2E : PG2_JTB_op = "LBGE LBLT LBGT LBLE"; + 8'h2F : PG2_JTB_op = "LBGE LBLT LBGT LBLE"; + 8'h93 : PG2_JTB_op = "CMPD (dir idx ext)"; + 8'h9C : PG2_JTB_op = "CMPY (dir idx ext)"; + 8'h9E : PG2_JTB_op = "LDY (dir idx ext)"; + 8'hA3 : PG2_JTB_op = "CMPD (dir idx ext)"; + 8'hAC : PG2_JTB_op = "CMPY (dir idx ext)"; + 8'hAE : PG2_JTB_op = "LDY (dir idx ext)"; + 8'hAF : PG2_JTB_op = "STY (idx)"; + 8'hB3 : PG2_JTB_op = "CMPD (dir idx ext)"; + 8'hBC : PG2_JTB_op = "CMPY (dir idx ext)"; + 8'hBE : PG2_JTB_op = "LDY (dir idx ext)"; + 8'hDE : PG2_JTB_op = "LDS (dir idx ext)"; + 8'hEE : PG2_JTB_op = "LDS (dir idx ext)"; + 8'hEF : PG2_JTB_op = "STS (idx)"; + 8'hFE : PG2_JTB_op = "LDS (dir idx ext)"; + default : PG2_JTB_op = "invalid"; + endcase +end + +reg [(8*64):0] PG2_JTB_eq; + +always @* begin + case (OPCODE_I) + 8'h20 : PG2_JTB_eq = "JMP"; + 8'h21 : PG2_JTB_eq = "JMP"; + 8'h22 : PG2_JTB_eq = "JMP"; + 8'h23 : PG2_JTB_eq = "JMP"; + 8'h24 : PG2_JTB_eq = "JMP"; + 8'h25 : PG2_JTB_eq = "JMP"; + 8'h26 : PG2_JTB_eq = "JMP"; + 8'h27 : PG2_JTB_eq = "JMP"; + 8'h28 : PG2_JTB_eq = "JMP"; + 8'h29 : PG2_JTB_eq = "JMP"; + 8'h2A : PG2_JTB_eq = "JMP"; + 8'h2B : PG2_JTB_eq = "JMP"; + 8'h2C : PG2_JTB_eq = "JMP"; + 8'h2D : PG2_JTB_eq = "JMP"; + 8'h2E : PG2_JTB_eq = "JMP"; + 8'h2F : PG2_JTB_eq = "JMP"; + 8'h93 : PG2_JTB_eq = "CMP"; + 8'h9C : PG2_JTB_eq = "CMP"; + 8'h9E : PG2_JTB_eq = "LD"; + 8'hA3 : PG2_JTB_eq = "CMP"; + 8'hAC : PG2_JTB_eq = "CMP"; + 8'hAE : PG2_JTB_eq = "LD"; + 8'hAF : PG2_JTB_eq = "ST"; + 8'hB3 : PG2_JTB_eq = "CMP"; + 8'hBC : PG2_JTB_eq = "CMP"; + 8'hBE : PG2_JTB_eq = "LD"; + 8'hDE : PG2_JTB_eq = "LD"; + 8'hEE : PG2_JTB_eq = "LD"; + 8'hEF : PG2_JTB_eq = "ST"; + 8'hFE : PG2_JTB_eq = "LD"; + default : PG2_JTB_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R1.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R1.v new file mode 100644 index 0000000000000000000000000000000000000000..a03f23010e22246fd6d8fdf6beafb47cc0673bc5 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R1.v @@ -0,0 +1,214 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R1_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg2_R1( + input [7:0] OPCODE_I, + output reg [3:0] PG2_R1_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R1_O = 4'h2; // Y EDIV (inh) + 8'h15 : PG2_R1_O = 4'h2; // Y EDIVS (inh) + 8'h18 : PG2_R1_O = 4'h1; // X IDIVS (inh) + 8'h19 : PG2_R1_O = 4'h1; // X FDIV (inh) + 8'h20 : PG2_R1_O = 4'h5; // PC LBRA LBRN LBHI LBLS + 8'h21 : PG2_R1_O = 4'h5; // PC LBRA LBRN LBHI LBLS + 8'h22 : PG2_R1_O = 4'h5; // PC LBRA LBRN LBHI LBLS + 8'h23 : PG2_R1_O = 4'h5; // PC LBRA LBRN LBHI LBLS + 8'h24 : PG2_R1_O = 4'h5; // PC LBCC LBCS LBNE LBEQ + 8'h25 : PG2_R1_O = 4'h5; // PC LBCC LBCS LBNE LBEQ + 8'h26 : PG2_R1_O = 4'h5; // PC LBCC LBCS LBNE LBEQ + 8'h27 : PG2_R1_O = 4'h5; // PC LBCC LBCS LBNE LBEQ + 8'h28 : PG2_R1_O = 4'h5; // PC LBVC LBVS LBPL LBMI + 8'h29 : PG2_R1_O = 4'h5; // PC LBVC LBVS LBPL LBMI + 8'h2A : PG2_R1_O = 4'h5; // PC LBVC LBVS LBPL LBMI + 8'h2B : PG2_R1_O = 4'h5; // PC LBVC LBVS LBPL LBMI + 8'h2C : PG2_R1_O = 4'h5; // PC LBGE LBLT LBGT LBLE + 8'h2D : PG2_R1_O = 4'h5; // PC LBGE LBLT LBGT LBLE + 8'h2E : PG2_R1_O = 4'h5; // PC LBGE LBLT LBGT LBLE + 8'h2F : PG2_R1_O = 4'h5; // PC LBGE LBLT LBGT LBLE + 8'h83 : PG2_R1_O = 4'h0; // D CMPD (imm) + 8'h8C : PG2_R1_O = 4'h2; // Y CMPY (imm) + 8'h8E : PG2_R1_O = 4'h2; // Y LDY (imm) + 8'h93 : PG2_R1_O = 4'h0; // D CMPD (dir idx ext) + 8'h9C : PG2_R1_O = 4'h2; // Y CMPY (dir idx ext) + 8'h9E : PG2_R1_O = 4'h2; // Y LDY (dir idx ext) + 8'h9F : PG2_R1_O = 4'h2; // Y STY (dir ext) + 8'hA3 : PG2_R1_O = 4'h0; // D CMPD (dir idx ext) + 8'hAC : PG2_R1_O = 4'h2; // Y CMPY (dir idx ext) + 8'hAE : PG2_R1_O = 4'h2; // Y LDY (dir idx ext) + 8'hAF : PG2_R1_O = 4'h2; // Y STY (idx) + 8'hB3 : PG2_R1_O = 4'h0; // D CMPD (dir idx ext) + 8'hBC : PG2_R1_O = 4'h2; // Y CMPY (dir idx ext) + 8'hBE : PG2_R1_O = 4'h2; // Y LDY (dir idx ext) + 8'hBF : PG2_R1_O = 4'h2; // Y STY (dir ext) + 8'hCE : PG2_R1_O = 4'h4; // S LDS (imm) + 8'hDE : PG2_R1_O = 4'h4; // S LDS (dir idx ext) + 8'hDF : PG2_R1_O = 4'h4; // S STS (dir ext) + 8'hEE : PG2_R1_O = 4'h4; // S LDS (dir idx ext) + 8'hEF : PG2_R1_O = 4'h4; // S STS (idx) + 8'hFE : PG2_R1_O = 4'h4; // S LDS (dir idx ext) + 8'hFF : PG2_R1_O = 4'h4; // S STS (dir ext) + default : PG2_R1_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG2_R1_op; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R1_op = "EDIV (inh)"; + 8'h15 : PG2_R1_op = "EDIVS (inh)"; + 8'h18 : PG2_R1_op = "IDIVS (inh)"; + 8'h19 : PG2_R1_op = "FDIV (inh)"; + 8'h20 : PG2_R1_op = "LBRA LBRN LBHI LBLS"; + 8'h21 : PG2_R1_op = "LBRA LBRN LBHI LBLS"; + 8'h22 : PG2_R1_op = "LBRA LBRN LBHI LBLS"; + 8'h23 : PG2_R1_op = "LBRA LBRN LBHI LBLS"; + 8'h24 : PG2_R1_op = "LBCC LBCS LBNE LBEQ"; + 8'h25 : PG2_R1_op = "LBCC LBCS LBNE LBEQ"; + 8'h26 : PG2_R1_op = "LBCC LBCS LBNE LBEQ"; + 8'h27 : PG2_R1_op = "LBCC LBCS LBNE LBEQ"; + 8'h28 : PG2_R1_op = "LBVC LBVS LBPL LBMI"; + 8'h29 : PG2_R1_op = "LBVC LBVS LBPL LBMI"; + 8'h2A : PG2_R1_op = "LBVC LBVS LBPL LBMI"; + 8'h2B : PG2_R1_op = "LBVC LBVS LBPL LBMI"; + 8'h2C : PG2_R1_op = "LBGE LBLT LBGT LBLE"; + 8'h2D : PG2_R1_op = "LBGE LBLT LBGT LBLE"; + 8'h2E : PG2_R1_op = "LBGE LBLT LBGT LBLE"; + 8'h2F : PG2_R1_op = "LBGE LBLT LBGT LBLE"; + 8'h83 : PG2_R1_op = "CMPD (imm)"; + 8'h8C : PG2_R1_op = "CMPY (imm)"; + 8'h8E : PG2_R1_op = "LDY (imm)"; + 8'h93 : PG2_R1_op = "CMPD (dir idx ext)"; + 8'h9C : PG2_R1_op = "CMPY (dir idx ext)"; + 8'h9E : PG2_R1_op = "LDY (dir idx ext)"; + 8'h9F : PG2_R1_op = "STY (dir ext)"; + 8'hA3 : PG2_R1_op = "CMPD (dir idx ext)"; + 8'hAC : PG2_R1_op = "CMPY (dir idx ext)"; + 8'hAE : PG2_R1_op = "LDY (dir idx ext)"; + 8'hAF : PG2_R1_op = "STY (idx)"; + 8'hB3 : PG2_R1_op = "CMPD (dir idx ext)"; + 8'hBC : PG2_R1_op = "CMPY (dir idx ext)"; + 8'hBE : PG2_R1_op = "LDY (dir idx ext)"; + 8'hBF : PG2_R1_op = "STY (dir ext)"; + 8'hCE : PG2_R1_op = "LDS (imm)"; + 8'hDE : PG2_R1_op = "LDS (dir idx ext)"; + 8'hDF : PG2_R1_op = "STS (dir ext)"; + 8'hEE : PG2_R1_op = "LDS (dir idx ext)"; + 8'hEF : PG2_R1_op = "STS (idx)"; + 8'hFE : PG2_R1_op = "LDS (dir idx ext)"; + 8'hFF : PG2_R1_op = "STS (dir ext)"; + default : PG2_R1_op = "invalid"; + endcase +end + +reg [(8*64):0] PG2_R1_eq; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R1_eq = "Y"; + 8'h15 : PG2_R1_eq = "Y"; + 8'h18 : PG2_R1_eq = "X"; + 8'h19 : PG2_R1_eq = "X"; + 8'h20 : PG2_R1_eq = "PC"; + 8'h21 : PG2_R1_eq = "PC"; + 8'h22 : PG2_R1_eq = "PC"; + 8'h23 : PG2_R1_eq = "PC"; + 8'h24 : PG2_R1_eq = "PC"; + 8'h25 : PG2_R1_eq = "PC"; + 8'h26 : PG2_R1_eq = "PC"; + 8'h27 : PG2_R1_eq = "PC"; + 8'h28 : PG2_R1_eq = "PC"; + 8'h29 : PG2_R1_eq = "PC"; + 8'h2A : PG2_R1_eq = "PC"; + 8'h2B : PG2_R1_eq = "PC"; + 8'h2C : PG2_R1_eq = "PC"; + 8'h2D : PG2_R1_eq = "PC"; + 8'h2E : PG2_R1_eq = "PC"; + 8'h2F : PG2_R1_eq = "PC"; + 8'h83 : PG2_R1_eq = "D"; + 8'h8C : PG2_R1_eq = "Y"; + 8'h8E : PG2_R1_eq = "Y"; + 8'h93 : PG2_R1_eq = "D"; + 8'h9C : PG2_R1_eq = "Y"; + 8'h9E : PG2_R1_eq = "Y"; + 8'h9F : PG2_R1_eq = "Y"; + 8'hA3 : PG2_R1_eq = "D"; + 8'hAC : PG2_R1_eq = "Y"; + 8'hAE : PG2_R1_eq = "Y"; + 8'hAF : PG2_R1_eq = "Y"; + 8'hB3 : PG2_R1_eq = "D"; + 8'hBC : PG2_R1_eq = "Y"; + 8'hBE : PG2_R1_eq = "Y"; + 8'hBF : PG2_R1_eq = "Y"; + 8'hCE : PG2_R1_eq = "S"; + 8'hDE : PG2_R1_eq = "S"; + 8'hDF : PG2_R1_eq = "S"; + 8'hEE : PG2_R1_eq = "S"; + 8'hEF : PG2_R1_eq = "S"; + 8'hFE : PG2_R1_eq = "S"; + 8'hFF : PG2_R1_eq = "S"; + default : PG2_R1_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R2.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R2.v new file mode 100644 index 0000000000000000000000000000000000000000..046c3f5f11cde90945515e249cc757559570dd2a --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg2_R2.v @@ -0,0 +1,196 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R2_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg2_R2( + input [7:0] OPCODE_I, + output reg [3:0] PG2_R2_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R2_O = 4'h0; // D EDIV (inh) + 8'h15 : PG2_R2_O = 4'h0; // D EDIVS (inh) + 8'h18 : PG2_R2_O = 4'h0; // D IDIVS (inh) + 8'h19 : PG2_R2_O = 4'h0; // D FDIV (inh) + 8'h20 : PG2_R2_O = 4'hc; // EA LBRA LBRN LBHI LBLS + 8'h21 : PG2_R2_O = 4'hc; // EA LBRA LBRN LBHI LBLS + 8'h22 : PG2_R2_O = 4'hc; // EA LBRA LBRN LBHI LBLS + 8'h23 : PG2_R2_O = 4'hc; // EA LBRA LBRN LBHI LBLS + 8'h24 : PG2_R2_O = 4'hc; // EA LBCC LBCS LBNE LBEQ + 8'h25 : PG2_R2_O = 4'hc; // EA LBCC LBCS LBNE LBEQ + 8'h26 : PG2_R2_O = 4'hc; // EA LBCC LBCS LBNE LBEQ + 8'h27 : PG2_R2_O = 4'hc; // EA LBCC LBCS LBNE LBEQ + 8'h28 : PG2_R2_O = 4'hc; // EA LBVC LBVS LBPL LBMI + 8'h29 : PG2_R2_O = 4'hc; // EA LBVC LBVS LBPL LBMI + 8'h2A : PG2_R2_O = 4'hc; // EA LBVC LBVS LBPL LBMI + 8'h2B : PG2_R2_O = 4'hc; // EA LBVC LBVS LBPL LBMI + 8'h2C : PG2_R2_O = 4'hc; // EA LBGE LBLT LBGT LBLE + 8'h2D : PG2_R2_O = 4'hc; // EA LBGE LBLT LBGT LBLE + 8'h2E : PG2_R2_O = 4'hc; // EA LBGE LBLT LBGT LBLE + 8'h2F : PG2_R2_O = 4'hc; // EA LBGE LBLT LBGT LBLE + 8'h83 : PG2_R2_O = 4'he; // IDATA CMPD (imm) + 8'h8C : PG2_R2_O = 4'he; // IDATA CMPY (imm) + 8'h8E : PG2_R2_O = 4'he; // IDATA LDY (imm) + 8'h93 : PG2_R2_O = 4'hd; // DMEM_RD CMPD (dir idx ext) + 8'h9C : PG2_R2_O = 4'hd; // DMEM_RD CMPY (dir idx ext) + 8'h9E : PG2_R2_O = 4'hd; // DMEM_RD LDY (dir idx ext) + 8'hA3 : PG2_R2_O = 4'hd; // DMEM_RD CMPD (dir idx ext) + 8'hAC : PG2_R2_O = 4'hd; // DMEM_RD CMPY (dir idx ext) + 8'hAE : PG2_R2_O = 4'hd; // DMEM_RD LDY (dir idx ext) + 8'hB3 : PG2_R2_O = 4'hd; // DMEM_RD CMPD (dir idx ext) + 8'hBC : PG2_R2_O = 4'hd; // DMEM_RD CMPY (dir idx ext) + 8'hBE : PG2_R2_O = 4'hd; // DMEM_RD LDY (dir idx ext) + 8'hCE : PG2_R2_O = 4'he; // IDATA LDS (imm) + 8'hDE : PG2_R2_O = 4'hd; // DMEM_RD LDS (dir idx ext) + 8'hEE : PG2_R2_O = 4'hd; // DMEM_RD LDS (dir idx ext) + 8'hFE : PG2_R2_O = 4'hd; // DMEM_RD LDS (dir idx ext) + default : PG2_R2_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG2_R2_op; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R2_op = "EDIV (inh)"; + 8'h15 : PG2_R2_op = "EDIVS (inh)"; + 8'h18 : PG2_R2_op = "IDIVS (inh)"; + 8'h19 : PG2_R2_op = "FDIV (inh)"; + 8'h20 : PG2_R2_op = "LBRA LBRN LBHI LBLS"; + 8'h21 : PG2_R2_op = "LBRA LBRN LBHI LBLS"; + 8'h22 : PG2_R2_op = "LBRA LBRN LBHI LBLS"; + 8'h23 : PG2_R2_op = "LBRA LBRN LBHI LBLS"; + 8'h24 : PG2_R2_op = "LBCC LBCS LBNE LBEQ"; + 8'h25 : PG2_R2_op = "LBCC LBCS LBNE LBEQ"; + 8'h26 : PG2_R2_op = "LBCC LBCS LBNE LBEQ"; + 8'h27 : PG2_R2_op = "LBCC LBCS LBNE LBEQ"; + 8'h28 : PG2_R2_op = "LBVC LBVS LBPL LBMI"; + 8'h29 : PG2_R2_op = "LBVC LBVS LBPL LBMI"; + 8'h2A : PG2_R2_op = "LBVC LBVS LBPL LBMI"; + 8'h2B : PG2_R2_op = "LBVC LBVS LBPL LBMI"; + 8'h2C : PG2_R2_op = "LBGE LBLT LBGT LBLE"; + 8'h2D : PG2_R2_op = "LBGE LBLT LBGT LBLE"; + 8'h2E : PG2_R2_op = "LBGE LBLT LBGT LBLE"; + 8'h2F : PG2_R2_op = "LBGE LBLT LBGT LBLE"; + 8'h83 : PG2_R2_op = "CMPD (imm)"; + 8'h8C : PG2_R2_op = "CMPY (imm)"; + 8'h8E : PG2_R2_op = "LDY (imm)"; + 8'h93 : PG2_R2_op = "CMPD (dir idx ext)"; + 8'h9C : PG2_R2_op = "CMPY (dir idx ext)"; + 8'h9E : PG2_R2_op = "LDY (dir idx ext)"; + 8'hA3 : PG2_R2_op = "CMPD (dir idx ext)"; + 8'hAC : PG2_R2_op = "CMPY (dir idx ext)"; + 8'hAE : PG2_R2_op = "LDY (dir idx ext)"; + 8'hB3 : PG2_R2_op = "CMPD (dir idx ext)"; + 8'hBC : PG2_R2_op = "CMPY (dir idx ext)"; + 8'hBE : PG2_R2_op = "LDY (dir idx ext)"; + 8'hCE : PG2_R2_op = "LDS (imm)"; + 8'hDE : PG2_R2_op = "LDS (dir idx ext)"; + 8'hEE : PG2_R2_op = "LDS (dir idx ext)"; + 8'hFE : PG2_R2_op = "LDS (dir idx ext)"; + default : PG2_R2_op = "invalid"; + endcase +end + +reg [(8*64):0] PG2_R2_eq; + +always @* begin + case (OPCODE_I) + 8'h14 : PG2_R2_eq = "D"; + 8'h15 : PG2_R2_eq = "D"; + 8'h18 : PG2_R2_eq = "D"; + 8'h19 : PG2_R2_eq = "D"; + 8'h20 : PG2_R2_eq = "EA"; + 8'h21 : PG2_R2_eq = "EA"; + 8'h22 : PG2_R2_eq = "EA"; + 8'h23 : PG2_R2_eq = "EA"; + 8'h24 : PG2_R2_eq = "EA"; + 8'h25 : PG2_R2_eq = "EA"; + 8'h26 : PG2_R2_eq = "EA"; + 8'h27 : PG2_R2_eq = "EA"; + 8'h28 : PG2_R2_eq = "EA"; + 8'h29 : PG2_R2_eq = "EA"; + 8'h2A : PG2_R2_eq = "EA"; + 8'h2B : PG2_R2_eq = "EA"; + 8'h2C : PG2_R2_eq = "EA"; + 8'h2D : PG2_R2_eq = "EA"; + 8'h2E : PG2_R2_eq = "EA"; + 8'h2F : PG2_R2_eq = "EA"; + 8'h83 : PG2_R2_eq = "IDATA"; + 8'h8C : PG2_R2_eq = "IDATA"; + 8'h8E : PG2_R2_eq = "IDATA"; + 8'h93 : PG2_R2_eq = "DMEM_RD"; + 8'h9C : PG2_R2_eq = "DMEM_RD"; + 8'h9E : PG2_R2_eq = "DMEM_RD"; + 8'hA3 : PG2_R2_eq = "DMEM_RD"; + 8'hAC : PG2_R2_eq = "DMEM_RD"; + 8'hAE : PG2_R2_eq = "DMEM_RD"; + 8'hB3 : PG2_R2_eq = "DMEM_RD"; + 8'hBC : PG2_R2_eq = "DMEM_RD"; + 8'hBE : PG2_R2_eq = "DMEM_RD"; + 8'hCE : PG2_R2_eq = "IDATA"; + 8'hDE : PG2_R2_eq = "DMEM_RD"; + 8'hEE : PG2_R2_eq = "DMEM_RD"; + 8'hFE : PG2_R2_eq = "DMEM_RD"; + default : PG2_R2_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_AR.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_AR.v new file mode 100644 index 0000000000000000000000000000000000000000..c12914bd959f899a688b6bfa3fc77e0dd2aed9e1 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_AR.v @@ -0,0 +1,88 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_AR_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg3_AR( + input [7:0] OPCODE_I, + output reg [3:0] PG3_AR_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + default : PG3_AR_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG3_AR_op; + +always @* begin + case (OPCODE_I) + default : PG3_AR_op = "invalid"; + endcase +end + +reg [(8*64):0] PG3_AR_eq; + +always @* begin + case (OPCODE_I) + default : PG3_AR_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTA.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTA.v new file mode 100644 index 0000000000000000000000000000000000000000..e80d750bfb606103cda01b91df586e4cdf8ec145 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTA.v @@ -0,0 +1,112 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg3_JTA( + input [7:0] OPCODE_I, + output reg [7:0] PG3_JTA_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_JTA_O = 8'h1b; // CMP CMPU (imm) + 8'h8C : PG3_JTA_O = 8'h1b; // CMP CMPS (imm) + 8'h93 : PG3_JTA_O = 8'h1; // LD_DIR_EXT CMPU (dir ext) + 8'h9C : PG3_JTA_O = 8'h1; // LD_DIR_EXT CMPS (dir ext) + 8'hA3 : PG3_JTA_O = 8'h2; // LD_INDEXED CMPU (idx) + 8'hAC : PG3_JTA_O = 8'h2; // LD_INDEXED CMPS (idx) + 8'hB3 : PG3_JTA_O = 8'h1; // LD_DIR_EXT CMPU (dir ext) + 8'hBC : PG3_JTA_O = 8'h1; // LD_DIR_EXT CMPS (dir ext) + default : PG3_JTA_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG3_JTA_op; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_JTA_op = "CMPU (imm)"; + 8'h8C : PG3_JTA_op = "CMPS (imm)"; + 8'h93 : PG3_JTA_op = "CMPU (dir ext)"; + 8'h9C : PG3_JTA_op = "CMPS (dir ext)"; + 8'hA3 : PG3_JTA_op = "CMPU (idx)"; + 8'hAC : PG3_JTA_op = "CMPS (idx)"; + 8'hB3 : PG3_JTA_op = "CMPU (dir ext)"; + 8'hBC : PG3_JTA_op = "CMPS (dir ext)"; + default : PG3_JTA_op = "invalid"; + endcase +end + +reg [(8*64):0] PG3_JTA_eq; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_JTA_eq = "CMP"; + 8'h8C : PG3_JTA_eq = "CMP"; + 8'h93 : PG3_JTA_eq = "LD_DIR_EXT"; + 8'h9C : PG3_JTA_eq = "LD_DIR_EXT"; + 8'hA3 : PG3_JTA_eq = "LD_INDEXED"; + 8'hAC : PG3_JTA_eq = "LD_INDEXED"; + 8'hB3 : PG3_JTA_eq = "LD_DIR_EXT"; + 8'hBC : PG3_JTA_eq = "LD_DIR_EXT"; + default : PG3_JTA_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTB.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTB.v new file mode 100644 index 0000000000000000000000000000000000000000..c93cbf7737aeaa97207c4c70c4a4608a761a5a2c --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_JTB.v @@ -0,0 +1,106 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_MICRO_SEQ_BRANCH_ADDR ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg3_JTB( + input [7:0] OPCODE_I, + output reg [7:0] PG3_JTB_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h93 : PG3_JTB_O = 8'h1b; // CMP CMPU (dir idx ext) + 8'h9C : PG3_JTB_O = 8'h1b; // CMP CMPS (dir idx ext) + 8'hA3 : PG3_JTB_O = 8'h1b; // CMP CMPU (dir idx ext) + 8'hAC : PG3_JTB_O = 8'h1b; // CMP CMPS (dir idx ext) + 8'hB3 : PG3_JTB_O = 8'h1b; // CMP CMPU (dir idx ext) + 8'hBC : PG3_JTB_O = 8'h1b; // CMP CMPS (dir idx ext) + default : PG3_JTB_O = 8'hFF; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG3_JTB_op; + +always @* begin + case (OPCODE_I) + 8'h93 : PG3_JTB_op = "CMPU (dir idx ext)"; + 8'h9C : PG3_JTB_op = "CMPS (dir idx ext)"; + 8'hA3 : PG3_JTB_op = "CMPU (dir idx ext)"; + 8'hAC : PG3_JTB_op = "CMPS (dir idx ext)"; + 8'hB3 : PG3_JTB_op = "CMPU (dir idx ext)"; + 8'hBC : PG3_JTB_op = "CMPS (dir idx ext)"; + default : PG3_JTB_op = "invalid"; + endcase +end + +reg [(8*64):0] PG3_JTB_eq; + +always @* begin + case (OPCODE_I) + 8'h93 : PG3_JTB_eq = "CMP"; + 8'h9C : PG3_JTB_eq = "CMP"; + 8'hA3 : PG3_JTB_eq = "CMP"; + 8'hAC : PG3_JTB_eq = "CMP"; + 8'hB3 : PG3_JTB_eq = "CMP"; + 8'hBC : PG3_JTB_eq = "CMP"; + default : PG3_JTB_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R1.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R1.v new file mode 100644 index 0000000000000000000000000000000000000000..e45b7cdf89fb3ef6e9315976c30ab89959c09127 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R1.v @@ -0,0 +1,112 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R1_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg3_R1( + input [7:0] OPCODE_I, + output reg [3:0] PG3_R1_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R1_O = 4'h3; // U CMPU (imm) + 8'h8C : PG3_R1_O = 4'h4; // S CMPS (imm) + 8'h93 : PG3_R1_O = 4'h3; // U CMPU (dir idx ext) + 8'h9C : PG3_R1_O = 4'h4; // S CMPS (dir idx ext) + 8'hA3 : PG3_R1_O = 4'h3; // U CMPU (dir idx ext) + 8'hAC : PG3_R1_O = 4'h4; // S CMPS (dir idx ext) + 8'hB3 : PG3_R1_O = 4'h3; // U CMPU (dir idx ext) + 8'hBC : PG3_R1_O = 4'h4; // S CMPS (dir idx ext) + default : PG3_R1_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG3_R1_op; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R1_op = "CMPU (imm)"; + 8'h8C : PG3_R1_op = "CMPS (imm)"; + 8'h93 : PG3_R1_op = "CMPU (dir idx ext)"; + 8'h9C : PG3_R1_op = "CMPS (dir idx ext)"; + 8'hA3 : PG3_R1_op = "CMPU (dir idx ext)"; + 8'hAC : PG3_R1_op = "CMPS (dir idx ext)"; + 8'hB3 : PG3_R1_op = "CMPU (dir idx ext)"; + 8'hBC : PG3_R1_op = "CMPS (dir idx ext)"; + default : PG3_R1_op = "invalid"; + endcase +end + +reg [(8*64):0] PG3_R1_eq; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R1_eq = "U"; + 8'h8C : PG3_R1_eq = "S"; + 8'h93 : PG3_R1_eq = "U"; + 8'h9C : PG3_R1_eq = "S"; + 8'hA3 : PG3_R1_eq = "U"; + 8'hAC : PG3_R1_eq = "S"; + 8'hB3 : PG3_R1_eq = "U"; + 8'hBC : PG3_R1_eq = "S"; + default : PG3_R1_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R2.v b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R2.v new file mode 100644 index 0000000000000000000000000000000000000000..f58be3629219e7fc1a787cd1262b62bd7da448da --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_decode_pg3_R2.v @@ -0,0 +1,112 @@ +// [TURBO9_DECODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_DECODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file +// built using cv_R2_SEL ctrl_vec +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_DECODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_decode_pg3_R2( + input [7:0] OPCODE_I, + output reg [3:0] PG3_R2_O +); + +///////////////////////////////////////////////////////////////////////////// +// LOGIC +///////////////////////////////////////////////////////////////////////////// + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R2_O = 4'he; // IDATA CMPU (imm) + 8'h8C : PG3_R2_O = 4'he; // IDATA CMPS (imm) + 8'h93 : PG3_R2_O = 4'hd; // DMEM_RD CMPU (dir idx ext) + 8'h9C : PG3_R2_O = 4'hd; // DMEM_RD CMPS (dir idx ext) + 8'hA3 : PG3_R2_O = 4'hd; // DMEM_RD CMPU (dir idx ext) + 8'hAC : PG3_R2_O = 4'hd; // DMEM_RD CMPS (dir idx ext) + 8'hB3 : PG3_R2_O = 4'hd; // DMEM_RD CMPU (dir idx ext) + 8'hBC : PG3_R2_O = 4'hd; // DMEM_RD CMPS (dir idx ext) + default : PG3_R2_O = 4'hx; // from decode_init + endcase +end + +`ifdef SIM_TURBO9 + +reg [(8*64):0] PG3_R2_op; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R2_op = "CMPU (imm)"; + 8'h8C : PG3_R2_op = "CMPS (imm)"; + 8'h93 : PG3_R2_op = "CMPU (dir idx ext)"; + 8'h9C : PG3_R2_op = "CMPS (dir idx ext)"; + 8'hA3 : PG3_R2_op = "CMPU (dir idx ext)"; + 8'hAC : PG3_R2_op = "CMPS (dir idx ext)"; + 8'hB3 : PG3_R2_op = "CMPU (dir idx ext)"; + 8'hBC : PG3_R2_op = "CMPS (dir idx ext)"; + default : PG3_R2_op = "invalid"; + endcase +end + +reg [(8*64):0] PG3_R2_eq; + +always @* begin + case (OPCODE_I) + 8'h83 : PG3_R2_eq = "IDATA"; + 8'h8C : PG3_R2_eq = "IDATA"; + 8'h93 : PG3_R2_eq = "DMEM_RD"; + 8'h9C : PG3_R2_eq = "DMEM_RD"; + 8'hA3 : PG3_R2_eq = "DMEM_RD"; + 8'hAC : PG3_R2_eq = "DMEM_RD"; + 8'hB3 : PG3_R2_eq = "DMEM_RD"; + 8'hBC : PG3_R2_eq = "DMEM_RD"; + default : PG3_R2_eq = "invalid"; + endcase +end + +`endif + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_urtl_microcode.v b/turbo9team_turbo9/rtl/turbo9_urtl_microcode.v new file mode 100644 index 0000000000000000000000000000000000000000..046f5ae23864d6a4a3d0710e993a01c4adfe73f0 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_urtl_microcode.v @@ -0,0 +1,2505 @@ +// [TURBO9_MICROCODE_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_MICROCODE_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_MICROCODE_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: +// Assembled from turbo9_urtl.asm file + +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_MICROCODE_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_urtl_microcode +( + // Inputs: + input [7:0] MICROCODE_ADR_I, + + // Control Vectors + output reg [2:0] CV_MICRO_SEQ_OP_O, + output reg [7:0] CV_MICRO_SEQ_BRANCH_ADDR_O, + output reg [3:0] CV_DATA_ALU_A_SEL_O, + output reg [2:0] CV_DATA_ALU_B_SEL_O, + output reg [3:0] CV_DATA_ALU_WR_SEL_O, + output reg [3:0] CV_ADDR_ALU_REG_SEL_O, + output reg [2:0] CV_DATA_ALU_OP_O, + output reg [2:0] CV_DATA_WIDTH_SEL_O, + output reg [0:0] CV_DATA_ALU_SAU_EN_O, + output reg [3:0] CV_CCR_OP_O, + output reg [1:0] CV_DATA_ALU_COND_SEL_O, + output reg [3:0] CV_MICRO_SEQ_COND_SEL_O, + output reg [1:0] CV_DMEM_OP_O, + output reg [1:0] CV_STACK_OP_O +); + + +///////////////////////////////////////////////////////////////////////////// +// MICROCODE +///////////////////////////////////////////////////////////////////////////// + +always @* begin + // + // Control Logic Defaults + CV_MICRO_SEQ_OP_O = 3'h0; // OP_CONTINUE + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h0; // RESET + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'hf; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_SAU_EN_O = 1'h0; // FALSE + CV_CCR_OP_O = 4'h0; // OP_OOOOOOOO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h1; // TRUE + CV_DMEM_OP_O = 2'h0; // DMEM_OP_IDLE + CV_STACK_OP_O = 2'h0; // STACK_OP_IDLE + // + // Decode Microcode Address + case (MICROCODE_ADR_I) + + // 0001: ; [TURBO9_HEADER_START] + // 0002: ; //////////////////////////////////////////////////////////////////////////// + // 0003: ; Turbo9 Microprocessor IP + // 0004: ; //////////////////////////////////////////////////////////////////////////// + // 0005: ; Website: www.turbo9.org + // 0006: ; Contact: team[at]turbo9[dot]org + // 0007: ; //////////////////////////////////////////////////////////////////////////// + // 0008: ; [TURBO9_LICENSE_START] + // 0009: ; BSD-1-Clause + // 0010: ; + // 0011: ; Copyright (c) 2020-2023 + // 0012: ; Kevin Phillipson + // 0013: ; Michael Rywalt + // 0014: ; All rights reserved. + // 0015: ; + // 0016: ; Redistribution and use in source and binary forms, with or without + // 0017: ; modification, are permitted provided that the following conditions are met: + // 0018: ; + // 0019: ; 1. Redistributions of source code must retain the above copyright notice, + // 0020: ; this list of conditions and the following disclaimer. + // 0021: ; + // 0022: ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // 0023: ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // 0024: ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // 0025: ; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE + // 0026: ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // 0027: ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // 0028: ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // 0029: ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // 0030: ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // 0031: ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // 0032: ; POSSIBILITY OF SUCH DAMAGE. + // 0033: ; [TURBO9_LICENSE_END] + // 0034: ; //////////////////////////////////////////////////////////////////////////// + // 0035: ; Engineer: Kevin Phillipson + // 0036: ; Description: Turbo9 uRTL microcode + // 0037: ; + // 0038: ; vim syntax :set syn=asm68k + // 0039: ; + // 0040: ; //////////////////////////////////////////////////////////////////////////// + // 0041: ; History: + // 0042: ; 07.14.2023 - Kevin Phillipson + // 0043: ; File header added + // 0044: ; + // 0045: ; //////////////////////////////////////////////////////////////////////////// + // 0046: ; [TURBO9_HEADER_END] + // 0047: + // 0048: ; decode_init ; Comment + // 0049: + // 0050: ; Jump Table A + // 0051: decode_init pg1_JTA cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 1 + // 0052: decode_init pg2_JTA cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 2 + // 0053: decode_init pg3_JTA cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 3 + // 0054: + // 0055: ; Jump Table B + // 0056: decode_init pg1_JTB cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 1 + // 0057: decode_init pg2_JTB cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 2 + // 0058: decode_init pg3_JTB cv_MICRO_SEQ_BRANCH_ADDR FF 8 ; Page 3 + // 0059: + // 0060: ; Register A Decode + // 0061: ; A side of ALU and ALU write + // 0062: decode_init pg1_R1 cv_R1_SEL x 8 ; Page 1 + // 0063: decode_init pg2_R1 cv_R1_SEL x 8 ; Page 2 + // 0064: decode_init pg3_R1 cv_R1_SEL x 8 ; Page 3 + // 0065: + // 0066: ; Register B Decode + // 0067: ; B side of ALU + // 0068: decode_init pg1_R2 cv_R2_SEL x 8 ; Page 1 + // 0069: decode_init pg2_R2 cv_R2_SEL x 8 ; Page 2 + // 0070: decode_init pg3_R2 cv_R2_SEL x 8 ; Page 3 + // 0071: + // 0072: ; Address Register Decode + // 0073: decode_init pg1_AR cv_AR_SEL x 8 ; Page 1 + // 0074: decode_init pg2_AR cv_AR_SEL x 8 ; Page 2 + // 0075: decode_init pg3_AR cv_AR_SEL x 8 ; Page 3 + // 0076: + // 0077: ; decode ; Comment + // 0078: ; + // 0079: ; EXAMPLE: + // 0080: ; decode pg1_JTA ABX $3A ; ABX(inh) + // 0081: + // 0082: + // 0083: + // 0084: ORG $00 + // 0085: RESET: + // 0086: ; R1 is reset to PC + // 0087: ; R2 is reset to DMEM_RD + // 0088: + // 0089: SET_DATA_WIDTH W_16 + // 0090: + // 0091: STACK_PUSH ZERO ; a cute way of creating EA=$FFFE + // 0092: DMEM_LOAD_W + // 0093: + // 0094: JUMP JMP + // 0095: micro_op_end + 8'h000: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h30; // JMP + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_DATA_WIDTH_SEL_O = 3'h3; // W_16 + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 0096: + // 0097: ; //////////////////////////////////////////////////////////////////////////// + // 0098: ; LOAD ADDRESSING MODES + // 0099: ; //////////////////////////////////////////////////////////////////////////// + // 0100: ; // + // 0101: LD_DIR_EXT: + // 0102: decode pg1_JTA LD_DIR_EXT $99 $B9 ; ADCA (dir ext) + // 0103: decode pg1_JTA LD_DIR_EXT $D9 $F9 ; ADCB (dir ext) + // 0104: ; + // 0105: decode pg1_JTA LD_DIR_EXT $9B $BB ; ADDA (dir ext) + // 0106: decode pg1_JTA LD_DIR_EXT $DB $FB ; ADDB (dir ext) + // 0107: decode pg1_JTA LD_DIR_EXT $D3 $F3 ; ADDD (dir ext) + // 0108: ; // + // 0109: decode pg1_JTA LD_DIR_EXT $94 $B4 ; ANDA (dir ext) + // 0110: decode pg1_JTA LD_DIR_EXT $D4 $F4 ; ANDB (dir ext) + // 0111: ; // + // 0112: decode pg1_JTA LD_DIR_EXT $08 $78 ; ASL LSL (dir ext) + // 0113: ; // + // 0114: decode pg1_JTA LD_DIR_EXT $07 $77 ; ASR (dir ext) + // 0115: ; // + // 0116: decode pg1_JTA LD_DIR_EXT $95 $B5 ; BITA (dir ext) + // 0117: decode pg1_JTA LD_DIR_EXT $D5 $F5 ; BITB (dir ext) + // 0118: ; // + // 0119: decode pg1_JTA LD_DIR_EXT $91 $B1 ; CMPA (dir ext) + // 0120: decode pg1_JTA LD_DIR_EXT $D1 $F1 ; CMPB (dir ext) + // 0121: decode pg2_JTA LD_DIR_EXT $93 $B3 ; CMPD (dir ext) + // 0122: decode pg3_JTA LD_DIR_EXT $9C $BC ; CMPS (dir ext) + // 0123: decode pg3_JTA LD_DIR_EXT $93 $B3 ; CMPU (dir ext) + // 0124: decode pg1_JTA LD_DIR_EXT $9C $BC ; CMPX (dir ext) + // 0125: decode pg2_JTA LD_DIR_EXT $9C $BC ; CMPY (dir ext) + // 0126: ; // + // 0127: decode pg1_JTA LD_DIR_EXT $03 $73 ; COM (dir ext) + // 0128: ; // + // 0129: decode pg1_JTA LD_DIR_EXT $0A $7A ; DEC (dir ext) + // 0130: ; // + // 0131: decode pg1_JTA LD_DIR_EXT $98 $B8 ; EORA (dir ext) + // 0132: decode pg1_JTA LD_DIR_EXT $D8 $F8 ; EORB (dir ext) + // 0133: ; // + // 0134: decode pg1_JTA LD_DIR_EXT $0C $7C ; INC (dir ext) + // 0135: ; // + // 0136: decode pg1_JTA LD_DIR_EXT $96 $B6 ; LDA (dir ext) + // 0137: decode pg1_JTA LD_DIR_EXT $D6 $F6 ; LDB (dir ext) + // 0138: decode pg1_JTA LD_DIR_EXT $DC $FC ; LDD (dir ext) + // 0139: decode pg2_JTA LD_DIR_EXT $DE $FE ; LDS (dir ext) + // 0140: decode pg1_JTA LD_DIR_EXT $DE $FE ; LDU (dir ext) + // 0141: decode pg1_JTA LD_DIR_EXT $9E $BE ; LDX (dir ext) + // 0142: decode pg2_JTA LD_DIR_EXT $9E $BE ; LDY (dir ext) + // 0143: ; // + // 0144: decode pg1_JTA LD_DIR_EXT $04 $74 ; LSR (dir ext) + // 0145: ; // + // 0146: decode pg1_JTA LD_DIR_EXT $00 $70 ; NEG (dir ext) + // 0147: ; // + // 0148: decode pg1_JTA LD_DIR_EXT $9A $BA ; ORA (dir ext) + // 0149: decode pg1_JTA LD_DIR_EXT $DA $FA ; ORB (dir ext) + // 0150: ; // + // 0151: decode pg1_JTA LD_DIR_EXT $09 $79 ; ROL (dir ext) + // 0152: decode pg1_JTA LD_DIR_EXT $06 $76 ; ROR (dir ext) + // 0153: ; // + // 0154: decode pg1_JTA LD_DIR_EXT $92 $B2 ; SBCA (dir ext) + // 0155: decode pg1_JTA LD_DIR_EXT $D2 $F2 ; SBCB (dir ext) + // 0156: ; // + // 0157: decode pg1_JTA LD_DIR_EXT $90 $B0 ; SUBA (dir ext) + // 0158: decode pg1_JTA LD_DIR_EXT $D0 $F0 ; SUBB (dir ext) + // 0159: decode pg1_JTA LD_DIR_EXT $93 $B3 ; SUBD (dir ext) + // 0160: ; // + // 0161: decode pg1_JTA LD_DIR_EXT $0D $7D ; TST (dir ext) + // 0162: + // 0163: DATA_PASS_B IDATA + // 0164: DATA_WRITE EA + // 0165: + // 0166: SET_DATA_WIDTH W_R1 + // 0167: + // 0168: ADDR_PASS IDATA + // 0169: DMEM_LOAD_W + // 0170: + // 0171: JUMP_TABLE_B + // 0172: micro_op_end + 8'h001: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h6; // IDATA + CV_DATA_ALU_WR_SEL_O = 4'hc; // EA + CV_ADDR_ALU_REG_SEL_O = 4'he; // IDATA + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + end + + + // 0173: + // 0174: + // 0175: LD_INDEXED: + // 0176: decode pg1_JTA LD_INDEXED $A9 ; ADCA (idx) + // 0177: decode pg1_JTA LD_INDEXED $E9 ; ADCB (idx) + // 0178: ; // + // 0179: decode pg1_JTA LD_INDEXED $AB ; ADDA (idx) + // 0180: decode pg1_JTA LD_INDEXED $EB ; ADDB (idx) + // 0181: decode pg1_JTA LD_INDEXED $E3 ; ADDD (idx) + // 0182: ; // + // 0183: decode pg1_JTA LD_INDEXED $A4 ; ANDA (idx) + // 0184: decode pg1_JTA LD_INDEXED $E4 ; ANDB (idx) + // 0185: ; // + // 0186: decode pg1_JTA LD_INDEXED $68 ; ASL LSL (idx) + // 0187: ; // + // 0188: decode pg1_JTA LD_INDEXED $67 ; ASR (idx) + // 0189: ; // + // 0190: decode pg1_JTA LD_INDEXED $A5 ; BITA (idx) + // 0191: decode pg1_JTA LD_INDEXED $E5 ; BITB (idx) + // 0192: ; // + // 0193: decode pg1_JTA LD_INDEXED $A1 ; CMPA (idx) + // 0194: decode pg1_JTA LD_INDEXED $E1 ; CMPB (idx) + // 0195: decode pg2_JTA LD_INDEXED $A3 ; CMPD (idx) + // 0196: decode pg3_JTA LD_INDEXED $AC ; CMPS (idx) + // 0197: decode pg3_JTA LD_INDEXED $A3 ; CMPU (idx) + // 0198: decode pg1_JTA LD_INDEXED $AC ; CMPX (idx) + // 0199: decode pg2_JTA LD_INDEXED $AC ; CMPY (idx) + // 0200: ; // + // 0201: decode pg1_JTA LD_INDEXED $63 ; COM (idx) + // 0202: ; // + // 0203: decode pg1_JTA LD_INDEXED $6A ; DEC (idx) + // 0204: ; // + // 0205: decode pg1_JTA LD_INDEXED $A8 ; EORA (idx) + // 0206: decode pg1_JTA LD_INDEXED $E8 ; EORB (idx) + // 0207: ; // + // 0208: decode pg1_JTA LD_INDEXED $6C ; INC (idx) + // 0209: ; // + // 0210: decode pg1_JTA LD_INDEXED $A6 ; LDA (idx) + // 0211: decode pg1_JTA LD_INDEXED $E6 ; LDB (idx) + // 0212: decode pg1_JTA LD_INDEXED $EC ; LDD (idx) + // 0213: decode pg2_JTA LD_INDEXED $EE ; LDS (idx) + // 0214: decode pg1_JTA LD_INDEXED $EE ; LDU (idx) + // 0215: decode pg1_JTA LD_INDEXED $AE ; LDX (idx) + // 0216: decode pg2_JTA LD_INDEXED $AE ; LDY (idx) + // 0217: ; // + // 0218: decode pg1_JTA LD_INDEXED $64 ; LSR (idx) + // 0219: ; // + // 0220: decode pg1_JTA LD_INDEXED $60 ; NEG (idx) + // 0221: ; // + // 0222: decode pg1_JTA LD_INDEXED $AA ; ORA (idx) + // 0223: decode pg1_JTA LD_INDEXED $EA ; ORB (idx) + // 0224: ; // + // 0225: decode pg1_JTA LD_INDEXED $69 ; ROL (idx) + // 0226: decode pg1_JTA LD_INDEXED $66 ; ROR (idx) + // 0227: ; // + // 0228: decode pg1_JTA LD_INDEXED $A2 ; SBCA (idx) + // 0229: decode pg1_JTA LD_INDEXED $E2 ; SBCB (idx) + // 0230: ; // + // 0231: decode pg1_JTA LD_INDEXED $A0 ; SUBA (idx) + // 0232: decode pg1_JTA LD_INDEXED $E0 ; SUBB (idx) + // 0233: decode pg1_JTA LD_INDEXED $A3 ; SUBD (idx) + // 0234: ; // + // 0235: decode pg1_JTA LD_INDEXED $6D ; TST (idx) + // 0236: + // 0237: SET_DATA_WIDTH W_R1_OR_IND + // 0238: + // 0239: ADDR_INX_OR_LOAD_IND + // 0240: DMEM_LOAD_W ; LOAD_IND can override + // 0241: + // 0242: IF NOT_INDIRECT + // 0243: JUMP_TABLE_B + // 0244: micro_op_end + 8'h002: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_ADDR_ALU_REG_SEL_O = 4'h0; // INDEXED + CV_DATA_WIDTH_SEL_O = 3'h1; // W_R1_OR_IND + CV_MICRO_SEQ_COND_SEL_O = 4'h0; // NOT_INDIRECT + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + end + + + // 0245: + // 0246: LD_INDIRECT: + // 0247: DATA_PASS_B DMEM_RD + // 0248: DATA_WRITE EA + // 0249: + // 0250: SET_DATA_WIDTH W_R1 + // 0251: + // 0252: ADDR_PASS DMEM_RD + // 0253: DMEM_LOAD_W + // 0254: + // 0255: JUMP_TABLE_B + // 0256: micro_op_end + 8'h003: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_DATA_ALU_WR_SEL_O = 4'hc; // EA + CV_ADDR_ALU_REG_SEL_O = 4'hd; // DMEM_RD + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + end + + + // 0257: ; // + // 0258: ; //////////////////////////////////////////////////////////////////////////// + // 0259: + // 0260: + // 0261: ; //////////////////////////////////////////////////////////////////////////// + // 0262: ; STORE ADDRESSING MODES + // 0263: ; //////////////////////////////////////////////////////////////////////////// + // 0264: ; // + // 0265: ST_INDEXED: + // 0266: decode pg1_JTA ST_INDEXED $6F ; CLR(idx) + // 0267: ; // + // 0268: decode pg1_JTA ST_INDEXED $6E ; JMP(idx) + // 0269: ; // + // 0270: decode pg1_JTA ST_INDEXED $AD ; JSR (idx) + // 0271: ; // + // 0272: decode pg1_JTA ST_INDEXED $32 ; LEAS(inh) + // 0273: decode pg1_JTA ST_INDEXED $33 ; LEAU(inh) + // 0274: decode pg1_JTA ST_INDEXED $30 ; LEAX(inh) + // 0275: decode pg1_JTA ST_INDEXED $31 ; LEAY(inh) + // 0276: ; // + // 0277: decode pg1_JTA ST_INDEXED $A7 ; STA (idx) + // 0278: decode pg1_JTA ST_INDEXED $E7 ; STB (idx) + // 0279: decode pg1_JTA ST_INDEXED $ED ; STD (idx) + // 0280: decode pg2_JTA ST_INDEXED $EF ; STS (idx) + // 0281: decode pg1_JTA ST_INDEXED $EF ; STU (idx) + // 0282: decode pg1_JTA ST_INDEXED $AF ; STX (idx) + // 0283: decode pg2_JTA ST_INDEXED $AF ; STY (idx) + // 0284: + // 0285: SET_DATA_WIDTH W_R1_OR_IND + // 0286: + // 0287: ADDR_INX_OR_LOAD_IND + // 0288: + // 0289: IF NOT_INDIRECT + // 0290: JUMP_TABLE_B + // 0291: micro_op_end + 8'h004: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_ADDR_ALU_REG_SEL_O = 4'h0; // INDEXED + CV_DATA_WIDTH_SEL_O = 3'h1; // W_R1_OR_IND + CV_MICRO_SEQ_COND_SEL_O = 4'h0; // NOT_INDIRECT + end + + + // 0292: + // 0293: ST_INDIRECT: + // 0294: DATA_PASS_B DMEM_RD + // 0295: DATA_WRITE EA + // 0296: + // 0297: JUMP_TABLE_B + // 0298: micro_op_end + 8'h005: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_DATA_ALU_WR_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0299: + // 0300: ; // + // 0301: ; //////////////////////////////////////////////////////////////////////////// + // 0302: + // 0303: + // 0304: ; //////////////////////////////////////////////////////////////////////////// + // 0305: ; INHERENT INSTRUCTIONS + // 0306: ; //////////////////////////////////////////////////////////////////////////// + // 0307: ; // + // 0308: + // 0309: ; //////////////////////////////////////////// ABX + // 0310: ; // + // 0311: ABX: + // 0312: decode pg1_JTA ABX $3A ; ABX(inh) + // 0313: decode pg1_R1 X $3A ; ABX(inh) + // 0314: decode pg1_R2 B $3A ; ABX(inh) + // 0315: + // 0316: DATA_ADD R1, R2 + // 0317: DATA_WRITE R1 + // 0318: + // 0319: JUMP_TABLE_A_NEXT_PC + // 0320: micro_op_end + 8'h006: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0321: + // 0322: ; //////////////////////////////////////////// EXG + // 0323: ; // + // 0324: EXG: + // 0325: decode pg1_JTA EXG $1E ; EXG(inh) + // 0326: ; R1 = postbyte[7:0] $1E ; EXG(inh) + // 0327: ; R2 = postbyte[3:0] $1E ; EXG(inh) + // 0328: + // 0329: DATA_PASS_A R1 + // 0330: DATA_WRITE EA + // 0331: micro_op_end + 8'h007: begin + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0332: + // 0333: DATA_PASS_A R2 + // 0334: DATA_WRITE R1 + // 0335: + // 0336: CCR_OP_W OP_XXXXXXXX ; Just in case CCR is destination + // 0337: micro_op_end + 8'h008: begin + CV_DATA_ALU_A_SEL_O = 4'h4; // R2 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0338: + // 0339: DATA_PASS_A EA + // 0340: DATA_WRITE R2 + // 0341: + // 0342: CCR_OP_W OP_XXXXXXXX ; Just in case CCR is destination + // 0343: + // 0344: JUMP GO_NEW_PC ; Just in case PC is destination + // 0345: micro_op_end + 8'h009: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h2f; // GO_NEW_PC + CV_DATA_ALU_A_SEL_O = 4'hc; // EA + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h4; // R2 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0346: + // 0347: + // 0348: ; //////////////////////////////////////////// LEA S or U + // 0349: ; // + // 0350: LEA_SU: + // 0351: decode pg1_JTB LEA_SU $32 ; LEAS(inh) + // 0352: decode pg1_R1 S $32 ; LEAS(inh) + // 0353: + // 0354: decode pg1_JTB LEA_SU $33 ; LEAU(inh) + // 0355: decode pg1_R1 U $33 ; LEAU(inh) + // 0356: + // 0357: DATA_PASS_B EA + // 0358: DATA_WRITE R1 + // 0359: + // 0360: JUMP_TABLE_A_NEXT_PC + // 0361: micro_op_end + 8'h00a: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h4; // EA + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0362: + // 0363: ; //////////////////////////////////////////// LEA X or Y + // 0364: ; // + // 0365: LEA_XY: + // 0366: decode pg1_JTB LEA_XY $30 ; LEAX(inh) + // 0367: decode pg1_R1 X $30 ; LEAX(inh) + // 0368: + // 0369: decode pg1_JTB LEA_XY $31 ; LEAY(inh) + // 0370: decode pg1_R1 Y $31 ; LEAY(inh) + // 0371: + // 0372: DATA_PASS_B EA + // 0373: DATA_WRITE R1 + // 0374: + // 0375: SET_DATA_WIDTH W_R1 + // 0376: + // 0377: CCR_OP_W OP_oooooXoo + // 0378: + // 0379: JUMP_TABLE_A_NEXT_PC + // 0380: micro_op_end + 8'h00b: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h4; // EA + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h1; // OP_OOOOOXOO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0381: + // 0382: ; //////////////////////////////////////////// NOP + // 0383: ; // + // 0384: ; // Prebytes are sent here if the execute stage has nothing + // 0385: ; // else better to do. However, this is unnecessary given + // 0386: ; // prebyte processing logic is contained in the decode stage + // 0387: ; // and prebytes are decoded independently without delay if + // 0388: ; // the execute stage is busy. It's called pipelining ;-) + // 0389: ; // + // 0390: NOP: + // 0391: decode pg1_JTA NOP $12 ; NOP(inh) + // 0392: decode pg1_JTA NOP $11 ; page3 (prebyte) + // 0393: decode pg1_JTA NOP $10 ; page2 (prebyte) + // 0394: + // 0395: JUMP_TABLE_A_NEXT_PC + // 0396: micro_op_end + 8'h00c: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + end + + + // 0397: + // 0398: ; //////////////////////////////////////////// EMUL EMULS IDIV EDIV EDIVS IDIVS FDIV + // 0399: ; // + // 0400: SAU16: + // 0401: decode pg1_JTA SAU16 $14 ; EMUL (inh) + // 0402: decode pg1_R2 Y $14 ; EMUL (inh) + // 0403: decode pg1_R1 D $14 ; EMUL (inh) + // 0404: + // 0405: decode pg1_JTA SAU16 $15 ; EMULS (inh) + // 0406: decode pg1_R2 Y $15 ; EMULS (inh) + // 0407: decode pg1_R1 D $15 ; EMULS (inh) + // 0408: + // 0409: decode pg1_JTA SAU16 $18 ; IDIV (inh) + // 0410: decode pg1_R2 D $18 ; IDIV (inh) + // 0411: decode pg1_R1 X $18 ; IDIV (inh) + // 0412: + // 0413: decode pg2_JTA SAU16 $14 ; EDIV (inh) + // 0414: decode pg2_R2 D $14 ; EDIV (inh) + // 0415: decode pg2_R1 Y $14 ; EDIV (inh) + // 0416: + // 0417: decode pg2_JTA SAU16 $15 ; EDIVS (inh) + // 0418: decode pg2_R2 D $15 ; EDIVS (inh) + // 0419: decode pg2_R1 Y $15 ; EDIVS (inh) + // 0420: + // 0421: decode pg2_JTA SAU16 $19 ; FDIV (inh) + // 0422: decode pg2_R2 D $19 ; FDIV (inh) + // 0423: decode pg2_R1 X $19 ; FDIV (inh) + // 0424: + // 0425: decode pg2_JTA SAU16 $18 ; IDIVS (inh) + // 0426: decode pg2_R2 D $18 ; IDIVS (inh) + // 0427: decode pg2_R1 X $18 ; IDIVS (inh) + // 0428: + // 0429: DATA_SAU_EN + // 0430: + // 0431: IF SAU_NOT_DONE + // 0432: JUMP SAU16 + // 0433: micro_op_end + 8'h00d: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'hd; // SAU16 + CV_DATA_ALU_SAU_EN_O = 1'h1; // TRUE + CV_MICRO_SEQ_COND_SEL_O = 4'h5; // SAU_NOT_DONE + end + + + // 0434: + // 0435: SAU16_DONE: + // 0436: + // 0437: DATA_SAU_DONE + // 0438: DATA_WRITE R2 + // 0439: + // 0440: JUMP SAU8_DONE + // 0441: micro_op_end + 8'h00e: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h10; // SAU8_DONE + CV_DATA_ALU_WR_SEL_O = 4'h4; // R2 + CV_DATA_ALU_OP_O = 3'h7; // SAU + end + + + // 0442: + // 0443: ; //////////////////////////////////////////// DAA MUL + // 0444: ; // + // 0445: SAU8: + // 0446: decode pg1_JTA SAU8 $19 ; DAA (inh) + // 0447: decode pg1_R1 D $19 ; DAA (inh) + // 0448: + // 0449: decode pg1_JTA SAU8 $3D ; MUL (inh) + // 0450: decode pg1_R1 D $3D ; MUL (inh) + // 0451: + // 0452: DATA_SAU_EN + // 0453: + // 0454: IF SAU_NOT_DONE + // 0455: JUMP SAU8 + // 0456: micro_op_end + 8'h00f: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'hf; // SAU8 + CV_DATA_ALU_SAU_EN_O = 1'h1; // TRUE + CV_MICRO_SEQ_COND_SEL_O = 4'h5; // SAU_NOT_DONE + end + + + // 0457: + // 0458: SAU8_DONE: + // 0459: + // 0460: DATA_SAU_DONE + // 0461: DATA_WRITE R1 + // 0462: + // 0463: CCR_OP_W OP_ooooXXXX ; SAU masks correct bits + // 0464: + // 0465: JUMP_TABLE_A_NEXT_PC + // 0466: micro_op_end + 8'h010: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h7; // SAU + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + end + + + // 0467: + // 0468: ; //////////////////////////////////////////// SEX (in 1 micro-cycle!) + // 0469: ; // + // 0470: SEX: + // 0471: decode pg1_JTA SEX $1D ; SEX(inh) + // 0472: decode pg1_R1 D $1D ; SEX(inh) + // 0473: decode pg1_R2 SEXB $1D ; SEX(inh) + // 0474: + // 0475: DATA_PASS_B R2 + // 0476: DATA_WRITE R1 + // 0477: + // 0478: SET_DATA_WIDTH W_R1 + // 0479: + // 0480: CCR_OP_W OP_ooooXXXo ; INFO Prog Man says V unaffected, datasheet says v=0 + // 0481: + // 0482: JUMP_TABLE_A_NEXT_PC + // 0483: micro_op_end + 8'h011: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0484: + // 0485: ; //////////////////////////////////////////// CPY + // 0486: ; // + // 0487: CPY: + // 0488: decode pg2_JTA CPY $1F ; CPY (inh) + // 0489: ; R1 = postbyte[7:0] $1F ; CPY (inh) + // 0490: ; R2 = postbyte[3:0] $1F ; CPY (inh) + // 0491: + // 0492: ; TODO INFO: could combine this state with SAU states + // 0493: + // 0494: DATA_SAU_EN ; initalize byte counter from D register + // 0495: micro_op_end + 8'h012: begin + CV_DATA_ALU_SAU_EN_O = 1'h1; // TRUE + end + + + // 0496: + // 0497: CPY_LOOP: + // 0498: DATA_SAU_EN ; enable byte counter + // 0499: + // 0500: SET_DATA_WIDTH W_8 + // 0501: + // 0502: ADDR_PASS RR1_WR2 + // 0503: DMEM_LOAD_W + // 0504: + // 0505: IF SAU_DONE + // 0506: JUMP GO_NEW_PC + // 0507: micro_op_end + 8'h013: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h2f; // GO_NEW_PC + CV_ADDR_ALU_REG_SEL_O = 4'h4; // RR1_WR2 + CV_DATA_WIDTH_SEL_O = 3'h4; // W_8 + CV_DATA_ALU_SAU_EN_O = 1'h1; // TRUE + CV_MICRO_SEQ_COND_SEL_O = 4'h4; // SAU_DONE + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + end + + + // 0508: + // 0509: DATA_SAU_EN ; enable byte counter + // 0510: + // 0511: SET_DATA_WIDTH W_8 + // 0512: + // 0513: DATA_PASS_B DMEM_RD + // 0514: + // 0515: ADDR_PASS RR1_WR2 + // 0516: DMEM_STORE_W + // 0517: + // 0518: JUMP CPY_LOOP + // 0519: micro_op_end + 8'h014: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h13; // CPY_LOOP + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_ADDR_ALU_REG_SEL_O = 4'h4; // RR1_WR2 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h4; // W_8 + CV_DATA_ALU_SAU_EN_O = 1'h1; // TRUE + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 0520: + // 0521: + // 0522: + // 0523: ; //////////////////////////////////////////// TFR + // 0524: ; // + // 0525: TFR: + // 0526: decode pg1_JTA TFR $1F ; TFR(inh) + // 0527: ; R1 = postbyte[7:0] $1F ; TFR(inh) + // 0528: ; R2 = postbyte[3:0] $1F ; TFR(inh) + // 0529: + // 0530: DATA_PASS_A R1 + // 0531: DATA_WRITE R2 + // 0532: + // 0533: CCR_OP_W OP_XXXXXXXX ; Just in case CCR is destination + // 0534: + // 0535: JUMP GO_NEW_PC ; Just in case PC is destination + // 0536: micro_op_end + 8'h015: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h2f; // GO_NEW_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h4; // R2 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0537: + // 0538: ; // + // 0539: ; //////////////////////////////////////////////////////////////////////////// + // 0540: + // 0541: + // 0542: ; //////////////////////////////////////////////////////////////////////////// + // 0543: ; LOAD TYPE INSTRUCTIONS + // 0544: ; //////////////////////////////////////////////////////////////////////////// + // 0545: + // 0546: ; //////////////////////////////////////////// ADC + // 0547: ; // + // 0548: ADC: + // 0549: decode pg1_JTA ADC $89 ; ADCA (imm) + // 0550: decode pg1_R1 A $89 ; ADCA (imm) + // 0551: decode pg1_R2 IDATA $89 ; ADCA (imm) + // 0552: + // 0553: decode pg1_JTA ADC $C9 ; ADCB (imm) + // 0554: decode pg1_R1 B $C9 ; ADCB (imm) + // 0555: decode pg1_R2 IDATA $C9 ; ADCB (imm) + // 0556: + // 0557: decode pg1_JTB ADC $99 $A9 $B9 ; ADCA (dir idx ext) + // 0558: decode pg1_R1 A $99 $A9 $B9 ; ADCA (dir idx ext) + // 0559: decode pg1_R2 DMEM_RD $99 $A9 $B9 ; ADCA (dir idx ext) + // 0560: + // 0561: decode pg1_JTB ADC $D9 $E9 $F9 ; ADCB (dir idx ext) + // 0562: decode pg1_R1 B $D9 $E9 $F9 ; ADCB (dir idx ext) + // 0563: decode pg1_R2 DMEM_RD $D9 $E9 $F9 ; ADCB (dir idx ext) + // 0564: + // 0565: DATA_ADDC R1, R2 + // 0566: DATA_WRITE R1 + // 0567: + // 0568: SET_DATA_WIDTH W_R1 + // 0569: + // 0570: CCR_OP_W OP_ooXoXXXX ; H is masked for 16bit + // 0571: + // 0572: JUMP_TABLE_A_NEXT_PC + // 0573: micro_op_end + 8'h016: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h5; // OP_OOXOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h2; // CARRY_BIT + end + + + // 0574: + // 0575: ; //////////////////////////////////////////// ADD + // 0576: ; // + // 0577: ADD: + // 0578: decode pg1_JTA ADD $8B ; ADDA (imm) + // 0579: decode pg1_R1 A $8B ; ADDA (imm) + // 0580: decode pg1_R2 IDATA $8B ; ADDA (imm) + // 0581: + // 0582: decode pg1_JTA ADD $CB ; ADDB (imm) + // 0583: decode pg1_R1 B $CB ; ADDB (imm) + // 0584: decode pg1_R2 IDATA $CB ; ADDB (imm) + // 0585: + // 0586: decode pg1_JTA ADD $C3 ; ADDD (imm) + // 0587: decode pg1_R1 D $C3 ; ADDD (imm) + // 0588: decode pg1_R2 IDATA $C3 ; ADDD (imm) + // 0589: + // 0590: decode pg1_JTB ADD $9B $AB $BB ; ADDA (dir idx ext) + // 0591: decode pg1_R1 A $9B $AB $BB ; ADDA (dir idx ext) + // 0592: decode pg1_R2 DMEM_RD $9B $AB $BB ; ADDA (dir idx ext) + // 0593: + // 0594: decode pg1_JTB ADD $DB $EB $FB ; ADDB (dir idx ext) + // 0595: decode pg1_R1 B $DB $EB $FB ; ADDB (dir idx ext) + // 0596: decode pg1_R2 DMEM_RD $DB $EB $FB ; ADDB (dir idx ext) + // 0597: + // 0598: decode pg1_JTB ADD $D3 $E3 $F3 ; ADDD (dir idx ext) + // 0599: decode pg1_R1 D $D3 $E3 $F3 ; ADDD (dir idx ext) + // 0600: decode pg1_R2 DMEM_RD $D3 $E3 $F3 ; ADDD (dir idx ext) + // 0601: + // 0602: DATA_ADD R1, R2 + // 0603: DATA_WRITE R1 + // 0604: + // 0605: SET_DATA_WIDTH W_R1 + // 0606: + // 0607: CCR_OP_W OP_ooXoXXXX ; H is masked for 16bit + // 0608: + // 0609: JUMP_TABLE_A_NEXT_PC + // 0610: micro_op_end + 8'h017: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h5; // OP_OOXOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0611: + // 0612: + // 0613: ; //////////////////////////////////////////// AND + // 0614: ; // + // 0615: AND: + // 0616: decode pg1_JTA AND $84 ; ANDA (imm) + // 0617: decode pg1_R1 A $84 ; ANDA (imm) + // 0618: decode pg1_R2 IDATA $84 ; ANDA (imm) + // 0619: + // 0620: decode pg1_JTA AND $C4 ; ANDB (imm) + // 0621: decode pg1_R1 B $C4 ; ANDB (imm) + // 0622: decode pg1_R2 IDATA $C4 ; ANDB (imm) + // 0623: + // 0624: decode pg1_JTB AND $94 $A4 $B4 ; ANDA (dir idx ext) + // 0625: decode pg1_R1 A $94 $A4 $B4 ; ANDA (dir idx ext) + // 0626: decode pg1_R2 DMEM_RD $94 $A4 $B4 ; ANDA (dir idx ext) + // 0627: + // 0628: decode pg1_JTB AND $D4 $E4 $F4 ; ANDB (dir idx ext) + // 0629: decode pg1_R1 B $D4 $E4 $F4 ; ANDB (dir idx ext) + // 0630: decode pg1_R2 DMEM_RD $D4 $E4 $F4 ; ANDB (dir idx ext) + // 0631: + // 0632: DATA_AND R1, R2 + // 0633: DATA_WRITE R1 + // 0634: + // 0635: SET_DATA_WIDTH W_R1 + // 0636: + // 0637: CCR_OP_W OP_ooooXXXo + // 0638: + // 0639: JUMP_TABLE_A_NEXT_PC + // 0640: micro_op_end + 8'h018: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h4; // A_AND_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0641: + // 0642: ANDCC: + // 0643: decode pg1_JTA ANDCC $1C ; ANDCC (imm) + // 0644: decode pg1_R1 CCR $1C ; ANDCC (imm) + // 0645: decode pg1_R2 IDATA $1C ; ANDCC (imm) + // 0646: + // 0647: DATA_AND R1, R2 + // 0648: DATA_WRITE R1 + // 0649: + // 0650: SET_DATA_WIDTH W_R1 + // 0651: + // 0652: CCR_OP_W OP_XXXXXXXX + // 0653: + // 0654: JUMP_TABLE_A_NEXT_PC + // 0655: micro_op_end + 8'h019: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h4; // A_AND_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0656: + // 0657: ; //////////////////////////////////////////// BIT + // 0658: ; // + // 0659: BIT: + // 0660: decode pg1_JTA BIT $85 ; BITA (imm) + // 0661: decode pg1_R1 A $85 ; BITA (imm) + // 0662: decode pg1_R2 IDATA $85 ; BITA (imm) + // 0663: + // 0664: decode pg1_JTA BIT $C5 ; BITB (imm) + // 0665: decode pg1_R1 B $C5 ; BITB (imm) + // 0666: decode pg1_R2 IDATA $C5 ; BITB (imm) + // 0667: + // 0668: decode pg1_JTB BIT $95 $A5 $B5 ; BITA (dir idx ext) + // 0669: decode pg1_R1 A $95 $A5 $B5 ; BITA (dir idx ext) + // 0670: decode pg1_R2 DMEM_RD $95 $A5 $B5 ; BITA (dir idx ext) + // 0671: + // 0672: decode pg1_JTB BIT $D5 $E5 $F5 ; BITB (dir idx ext) + // 0673: decode pg1_R1 B $D5 $E5 $F5 ; BITB (dir idx ext) + // 0674: decode pg1_R2 DMEM_RD $D5 $E5 $F5 ; BITB (dir idx ext) + // 0675: + // 0676: DATA_AND R1, R2 + // 0677: + // 0678: SET_DATA_WIDTH W_R1 + // 0679: + // 0680: CCR_OP_W OP_ooooXXXo + // 0681: + // 0682: JUMP_TABLE_A_NEXT_PC + // 0683: micro_op_end + 8'h01a: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_OP_O = 3'h4; // A_AND_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0684: + // 0685: ; //////////////////////////////////////////// CMP + // 0686: ; // + // 0687: CMP: + // 0688: decode pg1_JTA CMP $81 ; CMPA (imm) + // 0689: decode pg1_R1 A $81 ; CMPA (imm) + // 0690: decode pg1_R2 IDATA $81 ; CMPA (imm) + // 0691: + // 0692: decode pg1_JTA CMP $C1 ; CMPB (imm) + // 0693: decode pg1_R1 B $C1 ; CMPB (imm) + // 0694: decode pg1_R2 IDATA $C1 ; CMPB (imm) + // 0695: + // 0696: decode pg2_JTA CMP $83 ; CMPD (imm) + // 0697: decode pg2_R1 D $83 ; CMPD (imm) + // 0698: decode pg2_R2 IDATA $83 ; CMPD (imm) + // 0699: + // 0700: decode pg3_JTA CMP $8C ; CMPS (imm) + // 0701: decode pg3_R1 S $8C ; CMPS (imm) + // 0702: decode pg3_R2 IDATA $8C ; CMPS (imm) + // 0703: + // 0704: decode pg3_JTA CMP $83 ; CMPU (imm) + // 0705: decode pg3_R1 U $83 ; CMPU (imm) + // 0706: decode pg3_R2 IDATA $83 ; CMPU (imm) + // 0707: + // 0708: decode pg1_JTA CMP $8C ; CMPX (imm) + // 0709: decode pg1_R1 X $8C ; CMPX (imm) + // 0710: decode pg1_R2 IDATA $8C ; CMPX (imm) + // 0711: + // 0712: decode pg2_JTA CMP $8C ; CMPY (imm) + // 0713: decode pg2_R1 Y $8C ; CMPY (imm) + // 0714: decode pg2_R2 IDATA $8C ; CMPY (imm) + // 0715: + // 0716: decode pg1_JTB CMP $91 $A1 $B1 ; CMPA (dir idx ext) + // 0717: decode pg1_R1 A $91 $A1 $B1 ; CMPA (dir idx ext) + // 0718: decode pg1_R2 DMEM_RD $91 $A1 $B1 ; CMPA (dir idx ext) + // 0719: + // 0720: decode pg1_JTB CMP $D1 $E1 $F1 ; CMPB (dir idx ext) + // 0721: decode pg1_R1 B $D1 $E1 $F1 ; CMPB (dir idx ext) + // 0722: decode pg1_R2 DMEM_RD $D1 $E1 $F1 ; CMPB (dir idx ext) + // 0723: + // 0724: decode pg2_JTB CMP $93 $A3 $B3 ; CMPD (dir idx ext) + // 0725: decode pg2_R1 D $93 $A3 $B3 ; CMPD (dir idx ext) + // 0726: decode pg2_R2 DMEM_RD $93 $A3 $B3 ; CMPD (dir idx ext) + // 0727: + // 0728: decode pg3_JTB CMP $9C $AC $BC ; CMPS (dir idx ext) + // 0729: decode pg3_R1 S $9C $AC $BC ; CMPS (dir idx ext) + // 0730: decode pg3_R2 DMEM_RD $9C $AC $BC ; CMPS (dir idx ext) + // 0731: + // 0732: decode pg3_JTB CMP $93 $A3 $B3 ; CMPU (dir idx ext) + // 0733: decode pg3_R1 U $93 $A3 $B3 ; CMPU (dir idx ext) + // 0734: decode pg3_R2 DMEM_RD $93 $A3 $B3 ; CMPU (dir idx ext) + // 0735: + // 0736: decode pg1_JTB CMP $9C $AC $BC ; CMPX (dir idx ext) + // 0737: decode pg1_R1 X $9C $AC $BC ; CMPX (dir idx ext) + // 0738: decode pg1_R2 DMEM_RD $9C $AC $BC ; CMPX (dir idx ext) + // 0739: + // 0740: decode pg2_JTB CMP $9C $AC $BC ; CMPY (dir idx ext) + // 0741: decode pg2_R1 Y $9C $AC $BC ; CMPY (dir idx ext) + // 0742: decode pg2_R2 DMEM_RD $9C $AC $BC ; CMPY (dir idx ext) + // 0743: + // 0744: DATA_SUB R1, R2 + // 0745: + // 0746: SET_DATA_WIDTH W_R1 + // 0747: + // 0748: CCR_OP_W OP_ooooXXXX ; INFO: Spec H Undefined, Turbo9 H not affected + // 0749: + // 0750: JUMP_TABLE_A_NEXT_PC + // 0751: micro_op_end + 8'h01b: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0752: + // 0753: ; //////////////////////////////////////////// EOR + // 0754: ; // + // 0755: EOR: + // 0756: decode pg1_JTA EOR $88 ; EORA (imm) + // 0757: decode pg1_R1 A $88 ; EORA (imm) + // 0758: decode pg1_R2 IDATA $88 ; EORA (imm) + // 0759: + // 0760: decode pg1_JTA EOR $C8 ; EORB (imm) + // 0761: decode pg1_R1 B $C8 ; EORB (imm) + // 0762: decode pg1_R2 IDATA $C8 ; EORB (imm) + // 0763: + // 0764: decode pg1_JTB EOR $98 $A8 $B8 ; EORA (dir idx ext) + // 0765: decode pg1_R1 A $98 $A8 $B8 ; EORA (dir idx ext) + // 0766: decode pg1_R2 DMEM_RD $98 $A8 $B8 ; EORA (dir idx ext) + // 0767: + // 0768: decode pg1_JTB EOR $D8 $E8 $F8 ; EORB (dir idx ext) + // 0769: decode pg1_R1 B $D8 $E8 $F8 ; EORB (dir idx ext) + // 0770: decode pg1_R2 DMEM_RD $D8 $E8 $F8 ; EORB (dir idx ext) + // 0771: + // 0772: DATA_XOR R1, R2 + // 0773: DATA_WRITE R1 + // 0774: + // 0775: SET_DATA_WIDTH W_R1 + // 0776: + // 0777: CCR_OP_W OP_ooooXXXo + // 0778: + // 0779: JUMP_TABLE_A_NEXT_PC + // 0780: micro_op_end + 8'h01c: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h6; // A_XOR_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0781: + // 0782: ; //////////////////////////////////////////// LD + // 0783: ; // + // 0784: LD: + // 0785: decode pg1_JTA LD $86 ; LDA (imm) + // 0786: decode pg1_R1 A $86 ; LDA (imm) + // 0787: decode pg1_R2 IDATA $86 ; LDA (imm) + // 0788: + // 0789: decode pg1_JTA LD $C6 ; LDB (imm) + // 0790: decode pg1_R1 B $C6 ; LDB (imm) + // 0791: decode pg1_R2 IDATA $C6 ; LDB (imm) + // 0792: + // 0793: decode pg1_JTA LD $CC ; LDD (imm) + // 0794: decode pg1_R1 D $CC ; LDD (imm) + // 0795: decode pg1_R2 IDATA $CC ; LDD (imm) + // 0796: + // 0797: decode pg2_JTA LD $CE ; LDS (imm) + // 0798: decode pg2_R1 S $CE ; LDS (imm) + // 0799: decode pg2_R2 IDATA $CE ; LDS (imm) + // 0800: + // 0801: decode pg1_JTA LD $CE ; LDU (imm) + // 0802: decode pg1_R1 U $CE ; LDU (imm) + // 0803: decode pg1_R2 IDATA $CE ; LDU (imm) + // 0804: + // 0805: decode pg1_JTA LD $8E ; LDX (imm) + // 0806: decode pg1_R1 X $8E ; LDX (imm) + // 0807: decode pg1_R2 IDATA $8E ; LDX (imm) + // 0808: + // 0809: decode pg2_JTA LD $8E ; LDY (imm) + // 0810: decode pg2_R1 Y $8E ; LDY (imm) + // 0811: decode pg2_R2 IDATA $8E ; LDY (imm) + // 0812: + // 0813: decode pg1_JTB LD $96 $A6 $B6 ; LDA (dir idx ext) + // 0814: decode pg1_R1 A $96 $A6 $B6 ; LDA (dir idx ext) + // 0815: decode pg1_R2 DMEM_RD $96 $A6 $B6 ; LDA (dir idx ext) + // 0816: + // 0817: decode pg1_JTB LD $D6 $E6 $F6 ; LDB (dir idx ext) + // 0818: decode pg1_R1 B $D6 $E6 $F6 ; LDB (dir idx ext) + // 0819: decode pg1_R2 DMEM_RD $D6 $E6 $F6 ; LDB (dir idx ext) + // 0820: + // 0821: decode pg1_JTB LD $DC $EC $FC ; LDD (dir idx ext) + // 0822: decode pg1_R1 D $DC $EC $FC ; LDD (dir idx ext) + // 0823: decode pg1_R2 DMEM_RD $DC $EC $FC ; LDD (dir idx ext) + // 0824: + // 0825: decode pg2_JTB LD $DE $EE $FE ; LDS (dir idx ext) + // 0826: decode pg2_R1 S $DE $EE $FE ; LDS (dir idx ext) + // 0827: decode pg2_R2 DMEM_RD $DE $EE $FE ; LDS (dir idx ext) + // 0828: + // 0829: decode pg1_JTB LD $DE $EE $FE ; LDU (dir idx ext) + // 0830: decode pg1_R1 U $DE $EE $FE ; LDU (dir idx ext) + // 0831: decode pg1_R2 DMEM_RD $DE $EE $FE ; LDU (dir idx ext) + // 0832: + // 0833: decode pg1_JTB LD $9E $AE $BE ; LDX (dir idx ext) + // 0834: decode pg1_R1 X $9E $AE $BE ; LDX (dir idx ext) + // 0835: decode pg1_R2 DMEM_RD $9E $AE $BE ; LDX (dir idx ext) + // 0836: + // 0837: decode pg2_JTB LD $9E $AE $BE ; LDY (dir idx ext) + // 0838: decode pg2_R1 Y $9E $AE $BE ; LDY (dir idx ext) + // 0839: decode pg2_R2 DMEM_RD $9E $AE $BE ; LDY (dir idx ext) + // 0840: + // 0841: DATA_PASS_B R2 + // 0842: DATA_WRITE R1 + // 0843: + // 0844: SET_DATA_WIDTH W_R1 + // 0845: + // 0846: CCR_OP_W OP_ooooXXXo + // 0847: + // 0848: JUMP_TABLE_A_NEXT_PC + // 0849: micro_op_end + 8'h01d: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0850: + // 0851: ; //////////////////////////////////////////// OR + // 0852: ; // + // 0853: OR: + // 0854: decode pg1_JTA OR $8A ; ORA (imm) + // 0855: decode pg1_R1 A $8A ; ORA (imm) + // 0856: decode pg1_R2 IDATA $8A ; ORA (imm) + // 0857: + // 0858: decode pg1_JTA OR $CA ; ORB (imm) + // 0859: decode pg1_R1 B $CA ; ORB (imm) + // 0860: decode pg1_R2 IDATA $CA ; ORB (imm) + // 0861: + // 0862: decode pg1_JTB OR $9A $AA $BA ; ORA (dir idx ext) + // 0863: decode pg1_R1 A $9A $AA $BA ; ORA (dir idx ext) + // 0864: decode pg1_R2 DMEM_RD $9A $AA $BA ; ORA (dir idx ext) + // 0865: + // 0866: decode pg1_JTB OR $DA $EA $FA ; ORB (dir idx ext) + // 0867: decode pg1_R1 B $DA $EA $FA ; ORB (dir idx ext) + // 0868: decode pg1_R2 DMEM_RD $DA $EA $FA ; ORB (dir idx ext) + // 0869: + // 0870: DATA_OR R1, R2 + // 0871: DATA_WRITE R1 + // 0872: + // 0873: SET_DATA_WIDTH W_R1 + // 0874: + // 0875: CCR_OP_W OP_ooooXXXo + // 0876: + // 0877: JUMP_TABLE_A_NEXT_PC + // 0878: micro_op_end + 8'h01e: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h5; // A_OR_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0879: + // 0880: ORCC: + // 0881: decode pg1_JTA ORCC $1A ; ORCC (imm) + // 0882: decode pg1_R1 CCR $1A ; ORCC (imm) + // 0883: decode pg1_R2 IDATA $1A ; ORCC (imm) + // 0884: + // 0885: DATA_OR R1, R2 + // 0886: DATA_WRITE R1 + // 0887: + // 0888: SET_DATA_WIDTH W_R1 + // 0889: + // 0890: CCR_OP_W OP_XXXXXXXX + // 0891: + // 0892: JUMP_TABLE_A_NEXT_PC + // 0893: micro_op_end + 8'h01f: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h5; // A_OR_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0894: + // 0895: ; //////////////////////////////////////////// SBC + // 0896: ; // + // 0897: SBC: + // 0898: decode pg1_JTA SBC $82 ; SBCA (imm) + // 0899: decode pg1_R1 A $82 ; SBCA (imm) + // 0900: decode pg1_R2 IDATA $82 ; SBCA (imm) + // 0901: + // 0902: decode pg1_JTA SBC $C2 ; SBCB (imm) + // 0903: decode pg1_R1 B $C2 ; SBCB (imm) + // 0904: decode pg1_R2 IDATA $C2 ; SBCB (imm) + // 0905: + // 0906: decode pg1_JTB SBC $92 $A2 $B2 ; SBCA (dir idx ext) + // 0907: decode pg1_R1 A $92 $A2 $B2 ; SBCA (dir idx ext) + // 0908: decode pg1_R2 DMEM_RD $92 $A2 $B2 ; SBCA (dir idx ext) + // 0909: + // 0910: decode pg1_JTB SBC $D2 $E2 $F2 ; SBCB (dir idx ext) + // 0911: decode pg1_R1 B $D2 $E2 $F2 ; SBCB (dir idx ext) + // 0912: decode pg1_R2 DMEM_RD $D2 $E2 $F2 ; SBCB (dir idx ext) + // 0913: + // 0914: DATA_SUBC R1, R2 + // 0915: DATA_WRITE R1 + // 0916: + // 0917: SET_DATA_WIDTH W_R1 + // 0918: + // 0919: CCR_OP_W OP_ooooXXXX ; INFO: Spec H Undefined, Turbo9 H not affected + // 0920: + // 0921: JUMP_TABLE_A_NEXT_PC + // 0922: micro_op_end + 8'h020: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h2; // CARRY_BIT + end + + + // 0923: + // 0924: ; //////////////////////////////////////////// SUB + // 0925: ; // + // 0926: SUB: + // 0927: decode pg1_JTA SUB $80 ; SUBA (imm) + // 0928: decode pg1_R1 A $80 ; SUBA (imm) + // 0929: decode pg1_R2 IDATA $80 ; SUBA (imm) + // 0930: + // 0931: decode pg1_JTA SUB $C0 ; SUBB (imm) + // 0932: decode pg1_R1 B $C0 ; SUBB (imm) + // 0933: decode pg1_R2 IDATA $C0 ; SUBB (imm) + // 0934: + // 0935: decode pg1_JTA SUB $83 ; SUBD (imm) + // 0936: decode pg1_R1 D $83 ; SUBD (imm) + // 0937: decode pg1_R2 IDATA $83 ; SUBD (imm) + // 0938: + // 0939: decode pg1_JTB SUB $90 $A0 $B0 ; SUBA (dir idx ext) + // 0940: decode pg1_R1 A $90 $A0 $B0 ; SUBA (dir idx ext) + // 0941: decode pg1_R2 DMEM_RD $90 $A0 $B0 ; SUBA (dir idx ext) + // 0942: + // 0943: decode pg1_JTB SUB $D0 $E0 $F0 ; SUBB (dir idx ext) + // 0944: decode pg1_R1 B $D0 $E0 $F0 ; SUBB (dir idx ext) + // 0945: decode pg1_R2 DMEM_RD $D0 $E0 $F0 ; SUBB (dir idx ext) + // 0946: + // 0947: decode pg1_JTB SUB $93 $A3 $B3 ; SUBD (dir idx ext) + // 0948: decode pg1_R1 D $93 $A3 $B3 ; SUBD (dir idx ext) + // 0949: decode pg1_R2 DMEM_RD $93 $A3 $B3 ; SUBD (dir idx ext) + // 0950: + // 0951: DATA_SUB R1, R2 + // 0952: DATA_WRITE R1 + // 0953: + // 0954: SET_DATA_WIDTH W_R1 + // 0955: + // 0956: CCR_OP_W OP_ooooXXXX ; INFO: Spec H Undefined, Turbo9 H not affected (8-bit) + // 0957: + // 0958: JUMP_TABLE_A_NEXT_PC + // 0959: micro_op_end + 8'h021: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 0960: + // 0961: + // 0962: ; // + // 0963: ; //////////////////////////////////////////////////////////////////////////// + // 0964: + // 0965: + // 0966: ; //////////////////////////////////////////////////////////////////////////// + // 0967: ; STORE INSTRUCTIONS + // 0968: ; //////////////////////////////////////////////////////////////////////////// + // 0969: ; // + // 0970: + // 0971: ; //////////////////////////////////////////// ST + // 0972: ; // + // 0973: ST: + // 0974: decode pg1_JTA ST $97 $B7 ; STA (dir ext) + // 0975: decode pg1_R1 A $97 $B7 ; STA (dir ext) + // 0976: decode pg1_AR IDATA $97 $B7 ; STA (dir ext) + // 0977: + // 0978: decode pg1_JTA ST $D7 $F7 ; STB (dir ext) + // 0979: decode pg1_R1 B $D7 $F7 ; STB (dir ext) + // 0980: decode pg1_AR IDATA $D7 $F7 ; STB (dir ext) + // 0981: + // 0982: decode pg1_JTA ST $DD $FD ; STD (dir ext) + // 0983: decode pg1_R1 D $DD $FD ; STD (dir ext) + // 0984: decode pg1_AR IDATA $DD $FD ; STD (dir ext) + // 0985: + // 0986: decode pg2_JTA ST $DF $FF ; STS (dir ext) + // 0987: decode pg2_R1 S $DF $FF ; STS (dir ext) + // 0988: decode pg2_AR IDATA $DF $FF ; STS (dir ext) + // 0989: + // 0990: decode pg1_JTA ST $DF $FF ; STU (dir ext) + // 0991: decode pg1_R1 U $DF $FF ; STU (dir ext) + // 0992: decode pg1_AR IDATA $DF $FF ; STU (dir ext) + // 0993: + // 0994: decode pg1_JTA ST $9F $BF ; STX (dir ext) + // 0995: decode pg1_R1 X $9F $BF ; STX (dir ext) + // 0996: decode pg1_AR IDATA $9F $BF ; STX (dir ext) + // 0997: + // 0998: decode pg2_JTA ST $9F $BF ; STY (dir ext) + // 0999: decode pg2_R1 Y $9F $BF ; STY (dir ext) + // 1000: decode pg2_AR IDATA $9F $BF ; STY (dir ext) + // 1001: + // 1002: decode pg1_JTB ST $A7 ; STA (idx) + // 1003: decode pg1_R1 A $A7 ; STA (idx) + // 1004: decode pg1_AR EA $A7 ; STA (idx) + // 1005: + // 1006: decode pg1_JTB ST $E7 ; STB (idx) + // 1007: decode pg1_R1 B $E7 ; STB (idx) + // 1008: decode pg1_AR EA $E7 ; STB (idx) + // 1009: + // 1010: decode pg1_JTB ST $ED ; STD (idx) + // 1011: decode pg1_R1 D $ED ; STD (idx) + // 1012: decode pg1_AR EA $ED ; STD (idx) + // 1013: + // 1014: decode pg2_JTB ST $EF ; STS (idx) + // 1015: decode pg2_R1 S $EF ; STS (idx) + // 1016: decode pg2_AR EA $EF ; STS (idx) + // 1017: + // 1018: decode pg1_JTB ST $EF ; STU (idx) + // 1019: decode pg1_R1 U $EF ; STU (idx) + // 1020: decode pg1_AR EA $EF ; STU (idx) + // 1021: + // 1022: decode pg1_JTB ST $AF ; STX (idx) + // 1023: decode pg1_R1 X $AF ; STX (idx) + // 1024: decode pg1_AR EA $AF ; STX (idx) + // 1025: + // 1026: decode pg2_JTB ST $AF ; STY (idx) + // 1027: decode pg2_R1 Y $AF ; STY (idx) + // 1028: decode pg2_AR EA $AF ; STY (idx) + // 1029: + // 1030: DATA_PASS_A R1 + // 1031: + // 1032: SET_DATA_WIDTH W_R1 + // 1033: + // 1034: CCR_OP_W OP_ooooXXXo + // 1035: + // 1036: ADDR_PASS AR + // 1037: DMEM_STORE_W + // 1038: + // 1039: JUMP_TABLE_A_NEXT_PC + // 1040: micro_op_end + 8'h022: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1041: + // 1042: ; // + // 1043: ; //////////////////////////////////////////////////////////////////////////// + // 1044: + // 1045: + // 1046: ; //////////////////////////////////////////////////////////////////////////// + // 1047: ; MODIFY MEMORY OR ACCUMULATOR INSTRUCTIONS + // 1048: ; //////////////////////////////////////////////////////////////////////////// + // 1049: ; // + // 1050: + // 1051: ; //////////////////////////////////////////// ASL LSL + // 1052: ; // + // 1053: ASL_LSL: + // 1054: decode pg1_JTA ASL_LSL $48 ; ASLA LSLA (inh) + // 1055: decode pg1_R1 A $48 ; ASLA LSLA (inh) + // 1056: + // 1057: decode pg1_JTA ASL_LSL $58 ; ASLB LSLB (inh) + // 1058: decode pg1_R1 B $58 ; ASLB LSLB (inh) + // 1059: + // 1060: decode pg1_JTB ASL_LSL $08 $68 $78 ; ASL LSL (dir idx ext) + // 1061: decode pg1_R1 DMEM_RD $08 $68 $78 ; ASL LSL (dir idx ext) + // 1062: + // 1063: DATA_LSHIFT_W R1, ZERO_BIT + // 1064: DATA_WRITE R1 + // 1065: + // 1066: SET_DATA_WIDTH W_R1 + // 1067: + // 1068: CCR_OP_W OP_ooooXXXX ; INFO: Spec H Undefined, Turbo9 H not affected + // 1069: + // 1070: ADDR_PASS EA + // 1071: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1072: + // 1073: JUMP_TABLE_A_NEXT_PC + // 1074: micro_op_end + 8'h023: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h2; // LSHIFT_A + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1075: + // 1076: ; //////////////////////////////////////////// ASR + // 1077: ; // + // 1078: ASR: + // 1079: decode pg1_JTA ASR $47 ; ASRA (inh) + // 1080: decode pg1_R1 A $47 ; ASRA (inh) + // 1081: + // 1082: decode pg1_JTA ASR $57 ; ASRB (inh) + // 1083: decode pg1_R1 B $57 ; ASRB (inh) + // 1084: + // 1085: decode pg1_JTB ASR $07 $67 $77 ; ASR (dir idx ext) + // 1086: decode pg1_R1 DMEM_RD $07 $67 $77 ; ASR (dir idx ext) + // 1087: + // 1088: DATA_RSHIFT_W SIGN_BIT, R1 + // 1089: DATA_WRITE R1 + // 1090: + // 1091: SET_DATA_WIDTH W_R1 + // 1092: + // 1093: CCR_OP_W OP_ooooXXoX ; INFO: Spec H Undefined, Turbo9 H not affected + // 1094: + // 1095: ADDR_PASS EA + // 1096: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1097: + // 1098: JUMP_TABLE_A_NEXT_PC + // 1099: micro_op_end + 8'h024: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h3; // RSHIFT_A + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h6; // OP_OOOOXXOX + CV_DATA_ALU_COND_SEL_O = 2'h3; // SIGN_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1100: + // 1101: ; //////////////////////////////////////////// CLR + // 1102: ; // + // 1103: ; // This is a little different than other memory modify + // 1104: ; // instructions. It does not load the memory first like + // 1105: ; // the 6809. It just writes a zero to be more efficient + // 1106: CLR: + // 1107: + // 1108: decode pg1_JTA CLR $4F ; CLRA (inh) + // 1109: decode pg1_R1 A $4F ; CLRA (inh) + // 1110: + // 1111: decode pg1_JTA CLR $5F ; CLRB (inh) + // 1112: decode pg1_R1 B $5F ; CLRB (inh) + // 1113: + // 1114: decode pg1_JTA CLR $0F $7F ; CLR (dir ext) + // 1115: decode pg1_R1 DMEM_RD $0F $7F ; CLR (dir ext) sets 8bit width + // 1116: decode pg1_AR IDATA $0F $7F ; CLR (dir ext) + // 1117: + // 1118: decode pg1_JTB CLR $6F ; CLR (idx) + // 1119: decode pg1_R1 DMEM_RD $6F ; CLR (idx) sets 8bit width + // 1120: decode pg1_AR EA $6F ; CLR (idx) + // 1121: + // 1122: DATA_PASS_B ZERO + // 1123: DATA_WRITE R1 + // 1124: + // 1125: SET_DATA_WIDTH W_R1 + // 1126: + // 1127: CCR_OP_W OP_ooooXXXX + // 1128: + // 1129: ADDR_PASS AR + // 1130: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1131: + // 1132: JUMP_TABLE_A_NEXT_PC + // 1133: micro_op_end + 8'h025: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1134: + // 1135: ; //////////////////////////////////////////// COM + // 1136: ; // + // 1137: COM: + // 1138: decode pg1_JTA COM $43 ; COMA (inh) + // 1139: decode pg1_R1 A $43 ; COMA (inh) + // 1140: decode pg1_R2 A $43 ; COMA (inh) + // 1141: + // 1142: decode pg1_JTA COM $53 ; COMB (inh) + // 1143: decode pg1_R1 B $53 ; COMB (inh) + // 1144: decode pg1_R2 B $53 ; COMB (inh) + // 1145: + // 1146: decode pg1_JTB COM $03 $63 $73 ; COM (dir idx ext) + // 1147: decode pg1_R1 DMEM_RD $03 $63 $73 ; COM (dir idx ext) sets 8bit width + // 1148: decode pg1_R2 DMEM_RD $03 $63 $73 ; COM (dir idx ext) + // 1149: + // 1150: DATA_INVERT_B R2 + // 1151: DATA_WRITE R1 + // 1152: + // 1153: SET_DATA_WIDTH W_R1 + // 1154: + // 1155: CCR_OP_W OP_ooooXXXX ; INFO Carry should be set to 1 for 6800 compatibility + // 1156: + // 1157: ADDR_PASS EA + // 1158: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1159: + // 1160: JUMP_TABLE_A_NEXT_PC + // 1161: micro_op_end + 8'h026: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h1; // ONE_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1162: + // 1163: ; //////////////////////////////////////////// DEC + // 1164: ; // + // 1165: DEC: + // 1166: decode pg1_JTA DEC $4A ; DECA (inh) + // 1167: decode pg1_R1 A $4A ; DECA (inh) + // 1168: + // 1169: decode pg1_JTA DEC $5A ; DECB (inh) + // 1170: decode pg1_R1 B $5A ; DECB (inh) + // 1171: + // 1172: decode pg1_JTB DEC $0A $6A $7A ; DEC (dir idx ext) + // 1173: decode pg1_R1 DMEM_RD $0A $6A $7A ; DEC (dir idx ext) + // 1174: + // 1175: DATA_DEC R1 + // 1176: DATA_WRITE R1 + // 1177: + // 1178: SET_DATA_WIDTH W_R1 + // 1179: + // 1180: CCR_OP_W OP_ooooXXXo + // 1181: + // 1182: ADDR_PASS EA + // 1183: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1184: + // 1185: JUMP_TABLE_A_NEXT_PC + // 1186: micro_op_end + 8'h027: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h1; // ONE_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1187: + // 1188: ; //////////////////////////////////////////// INC + // 1189: ; // + // 1190: INC: + // 1191: decode pg1_JTA INC $4C ; INCA (inh) + // 1192: decode pg1_R1 A $4C ; INCA (inh) + // 1193: + // 1194: decode pg1_JTA INC $5C ; INCB (inh) + // 1195: decode pg1_R1 B $5C ; INCB (inh) + // 1196: + // 1197: decode pg1_JTB INC $0C $6C $7C ; INC (dir idx ext) + // 1198: decode pg1_R1 DMEM_RD $0C $6C $7C ; INC (dir idx ext) + // 1199: + // 1200: DATA_INC R1 + // 1201: DATA_WRITE R1 + // 1202: + // 1203: SET_DATA_WIDTH W_R1 + // 1204: + // 1205: CCR_OP_W OP_ooooXXXo + // 1206: + // 1207: ADDR_PASS EA + // 1208: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1209: + // 1210: JUMP_TABLE_A_NEXT_PC + // 1211: micro_op_end + 8'h028: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h1; // ONE_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1212: + // 1213: ; //////////////////////////////////////////// LSR + // 1214: ; // + // 1215: LSR: + // 1216: decode pg1_JTA LSR $44 ; LSRA (inh) + // 1217: decode pg1_R1 A $44 ; LSRA (inh) + // 1218: + // 1219: decode pg1_JTA LSR $54 ; LSRB (inh) + // 1220: decode pg1_R1 B $54 ; LSRB (inh) + // 1221: + // 1222: decode pg1_JTB LSR $04 $64 $74 ; LSR (dir idx ext) + // 1223: decode pg1_R1 DMEM_RD $04 $64 $74 ; LSR (dir idx ext) + // 1224: + // 1225: DATA_RSHIFT_W ZERO_BIT, R1 + // 1226: DATA_WRITE R1 + // 1227: + // 1228: SET_DATA_WIDTH W_R1 + // 1229: + // 1230: CCR_OP_W OP_ooooXXoX + // 1231: + // 1232: ADDR_PASS EA + // 1233: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1234: + // 1235: JUMP_TABLE_A_NEXT_PC + // 1236: micro_op_end + 8'h029: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h3; // RSHIFT_A + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h6; // OP_OOOOXXOX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1237: + // 1238: ; //////////////////////////////////////////// NEG + // 1239: ; // + // 1240: NEG: + // 1241: decode pg1_JTA NEG $40 ; NEGA (inh) + // 1242: decode pg1_R1 A $40 ; NEGA (inh) + // 1243: decode pg1_R2 A $40 ; NEGA (inh) + // 1244: + // 1245: decode pg1_JTA NEG $50 ; NEGB (inh) + // 1246: decode pg1_R1 B $50 ; NEGB (inh) + // 1247: decode pg1_R2 B $50 ; NEGB (inh) + // 1248: + // 1249: decode pg1_JTB NEG $00 $60 $70 ; NEG (dir idx ext) + // 1250: decode pg1_R1 DMEM_RD $00 $60 $70 ; NEG (dir idx ext) sets 8bit width + // 1251: decode pg1_R2 DMEM_RD $00 $60 $70 ; NEG (dir idx ext) + // 1252: + // 1253: DATA_SUB ZERO, R2 + // 1254: DATA_WRITE R1 + // 1255: + // 1256: SET_DATA_WIDTH W_R1 + // 1257: + // 1258: CCR_OP_W OP_ooooXXXX ; INFO: Spec H Undefined, Turbo9 H not affected + // 1259: + // 1260: ADDR_PASS EA + // 1261: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1262: + // 1263: JUMP_TABLE_A_NEXT_PC + // 1264: micro_op_end + 8'h02a: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h1; // A_PLUS_NOT_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1265: + // 1266: ; //////////////////////////////////////////// ROL + // 1267: ; // + // 1268: ROL: + // 1269: decode pg1_JTA ROL $49 ; ROLA (inh) + // 1270: decode pg1_R1 A $49 ; ROLA (inh) + // 1271: + // 1272: decode pg1_JTA ROL $59 ; ROLB (inh) + // 1273: decode pg1_R1 B $59 ; ROLB (inh) + // 1274: + // 1275: decode pg1_JTB ROL $09 $69 $79 ; ROL (dir idx ext) + // 1276: decode pg1_R1 DMEM_RD $09 $69 $79 ; ROL (dir idx ext) + // 1277: + // 1278: DATA_LSHIFT_W R1, CARRY_BIT + // 1279: DATA_WRITE R1 + // 1280: + // 1281: SET_DATA_WIDTH W_R1 + // 1282: + // 1283: CCR_OP_W OP_ooooXXXX + // 1284: + // 1285: ADDR_PASS EA + // 1286: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1287: + // 1288: JUMP_TABLE_A_NEXT_PC + // 1289: micro_op_end + 8'h02b: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h2; // LSHIFT_A + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h2; // OP_OOOOXXXX + CV_DATA_ALU_COND_SEL_O = 2'h2; // CARRY_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1290: + // 1291: ; //////////////////////////////////////////// ROR + // 1292: ; // + // 1293: ROR: + // 1294: decode pg1_JTA ROR $46 ; RORA (inh) + // 1295: decode pg1_R1 A $46 ; RORA (inh) + // 1296: + // 1297: decode pg1_JTA ROR $56 ; RORB (inh) + // 1298: decode pg1_R1 B $56 ; RORB (inh) + // 1299: + // 1300: decode pg1_JTB ROR $06 $66 $76 ; ROR (dir idx ext) + // 1301: decode pg1_R1 DMEM_RD $06 $66 $76 ; ROR (dir idx ext) + // 1302: + // 1303: DATA_RSHIFT_W CARRY_BIT, R1 + // 1304: DATA_WRITE R1 + // 1305: + // 1306: SET_DATA_WIDTH W_R1 + // 1307: + // 1308: CCR_OP_W OP_ooooXXoX + // 1309: + // 1310: ADDR_PASS EA + // 1311: DMEM_STORE_W ; Disabled for inherent addressing modes + // 1312: + // 1313: JUMP_TABLE_A_NEXT_PC + // 1314: micro_op_end + 8'h02c: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_ADDR_ALU_REG_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h3; // RSHIFT_A + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h6; // OP_OOOOXXOX + CV_DATA_ALU_COND_SEL_O = 2'h2; // CARRY_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + end + + + // 1315: + // 1316: ; //////////////////////////////////////////// TST + // 1317: ; // + // 1318: TST: + // 1319: decode pg1_JTA TST $4D ; TSTA (inh) + // 1320: decode pg1_R1 A $4D ; TSTA (inh) + // 1321: + // 1322: decode pg1_JTA TST $5D ; TSTB (inh) + // 1323: decode pg1_R1 B $5D ; TSTB (inh) + // 1324: + // 1325: decode pg1_JTB TST $0D $6D $7D ; TST (dir idx ext) + // 1326: decode pg1_R1 DMEM_RD $0D $6D $7D ; TST (dir idx ext) + // 1327: + // 1328: DATA_PASS_A R1 ; Pass A, B or DMEM + // 1329: + // 1330: SET_DATA_WIDTH W_R1 + // 1331: + // 1332: CCR_OP_W OP_ooooXXXo + // 1333: + // 1334: JUMP_TABLE_A_NEXT_PC + // 1335: micro_op_end + 8'h02d: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_CCR_OP_O = 4'h4; // OP_OOOOXXXO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 1336: + // 1337: ; // + // 1338: ; //////////////////////////////////////////////////////////////////////////// + // 1339: + // 1340: + // 1341: + // 1342: ; //////////////////////////////////////////////////////////////////////////// + // 1343: ; JUMP & BRANCH INSTRUCTIONS + // 1344: ; //////////////////////////////////////////////////////////////////////////// + // 1345: ; // + // 1346: + // 1347: ; //////////////////////////////////////////// BRANCH + // 1348: ; // + // 1349: BRANCH: + // 1350: decode pg1_JTA BRANCH $20 $21 $22 $23 ; BRA BRN BHI BLS + // 1351: decode pg1_JTB JMP $20 $21 $22 $23 ; BRA BRN BHI BLS + // 1352: decode pg1_R1 PC $20 $21 $22 $23 ; BRA BRN BHI BLS + // 1353: decode pg1_R2 EA $20 $21 $22 $23 ; BRA BRN BHI BLS + // 1354: + // 1355: decode pg1_JTA BRANCH $24 $25 $26 $27 ; BCC BCS BNE BEQ + // 1356: decode pg1_JTB JMP $24 $25 $26 $27 ; BCC BCS BNE BEQ + // 1357: decode pg1_R1 PC $24 $25 $26 $27 ; BCC BCS BNE BEQ + // 1358: decode pg1_R2 EA $24 $25 $26 $27 ; BCC BCS BNE BEQ + // 1359: + // 1360: decode pg1_JTA BRANCH $28 $29 $2A $2B ; BVC BVS BPL BMI + // 1361: decode pg1_JTB JMP $28 $29 $2A $2B ; BVC BVS BPL BMI + // 1362: decode pg1_R1 PC $28 $29 $2A $2B ; BVC BVS BPL BMI + // 1363: decode pg1_R2 EA $28 $29 $2A $2B ; BVC BVS BPL BMI + // 1364: + // 1365: decode pg1_JTA BRANCH $2C $2D $2E $2F ; BGE BLT BGT BLE + // 1366: decode pg1_JTB JMP $2C $2D $2E $2F ; BGE BLT BGT BLE + // 1367: decode pg1_R1 PC $2C $2D $2E $2F ; BGE BLT BGT BLE + // 1368: decode pg1_R2 EA $2C $2D $2E $2F ; BGE BLT BGT BLE + // 1369: + // 1370: decode pg1_JTA BRANCH $16 ; LBRA On page 1! + // 1371: decode pg1_JTB JMP $16 ; LBRA + // 1372: decode pg1_R1 PC $16 ; LBRA + // 1373: decode pg1_R2 EA $16 ; LBRA + // 1374: + // 1375: decode pg1_JTA BRANCH $8D $17 ; BSR LBSR // FIXME could do this without JUMP_TABLE_A + // 1376: decode pg1_JTB JSR $8D $17 ; BSR LBSR // FIXME check if smaller area + // 1377: decode pg1_R1 PC $8D $17 ; BSR LBSR + // 1378: decode pg1_R2 EA $8D $17 ; BSR LBSR + // 1379: decode pg1_AR S $8D $17 ; BSR LBSR + // 1380: + // 1381: ; Another LBRA hidden on Page 2! + // 1382: decode pg2_JTA BRANCH $20 $21 $22 $23 ; LBRA LBRN LBHI LBLS + // 1383: decode pg2_JTB JMP $20 $21 $22 $23 ; LBRA LBRN LBHI LBLS + // 1384: decode pg2_R1 PC $20 $21 $22 $23 ; LBRA LBRN LBHI LBLS + // 1385: decode pg2_R2 EA $20 $21 $22 $23 ; LBRA LBRN LBHI LBLS + // 1386: + // 1387: decode pg2_JTA BRANCH $24 $25 $26 $27 ; LBCC LBCS LBNE LBEQ + // 1388: decode pg2_JTB JMP $24 $25 $26 $27 ; LBCC LBCS LBNE LBEQ + // 1389: decode pg2_R1 PC $24 $25 $26 $27 ; LBCC LBCS LBNE LBEQ + // 1390: decode pg2_R2 EA $24 $25 $26 $27 ; LBCC LBCS LBNE LBEQ + // 1391: + // 1392: decode pg2_JTA BRANCH $28 $29 $2A $2B ; LBVC LBVS LBPL LBMI + // 1393: decode pg2_JTB JMP $28 $29 $2A $2B ; LBVC LBVS LBPL LBMI + // 1394: decode pg2_R1 PC $28 $29 $2A $2B ; LBVC LBVS LBPL LBMI + // 1395: decode pg2_R2 EA $28 $29 $2A $2B ; LBVC LBVS LBPL LBMI + // 1396: + // 1397: decode pg2_JTA BRANCH $2C $2D $2E $2F ; LBGE LBLT LBGT LBLE + // 1398: decode pg2_JTB JMP $2C $2D $2E $2F ; LBGE LBLT LBGT LBLE + // 1399: decode pg2_R1 PC $2C $2D $2E $2F ; LBGE LBLT LBGT LBLE + // 1400: decode pg2_R2 EA $2C $2D $2E $2F ; LBGE LBLT LBGT LBLE + // 1401: + // 1402: DATA_ADD R1, IDATA ; PC + signed offset + // 1403: DATA_WRITE EA + // 1404: + // 1405: SET_DATA_WIDTH W_R1 + // 1406: + // 1407: IF BRANCH_COND + // 1408: JUMP_TABLE_B + // 1409: micro_op_end + 8'h02e: begin + CV_MICRO_SEQ_OP_O = 3'h4; // OP_JUMP_TABLE_B + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h6; // IDATA + CV_DATA_ALU_WR_SEL_O = 4'hc; // EA + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h8; // BRANCH_COND + end + + + // 1410: + // 1411: GO_NEW_PC: + // 1412: JUMP_TABLE_A_NEXT_PC + // 1413: micro_op_end + 8'h02f: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + end + + + // 1414: + // 1415: ; //////////////////////////////////////////// JMP + // 1416: ; // + // 1417: JMP: + // 1418: decode pg1_JTA JMP $0E $7E ; JMP (dir ext) + // 1419: decode pg1_R1 PC $0E $7E ; JMP (dir ext) + // 1420: decode pg1_R2 IDATA $0E $7E ; JMP (dir ext) + // 1421: + // 1422: decode pg1_JTB JMP $6E ; JMP (idx) + // 1423: decode pg1_R1 PC $6E ; JMP (idx) + // 1424: decode pg1_R2 EA $6E ; JMP (idx) + // 1425: + // 1426: DATA_PASS_B R2 ; IDATA or EA + // 1427: DATA_WRITE R1 ; PC + // 1428: + // 1429: JUMP GO_NEW_PC ; PC must be written before "JUMP_TABLE_A_NEXT_PC" + // 1430: micro_op_end + 8'h030: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h2f; // GO_NEW_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h0; // R2 + CV_DATA_ALU_WR_SEL_O = 4'h8; // R1 + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 1431: + // 1432: + // 1433: ; //////////////////////////////////////////////////////////////////////////// + // 1434: + // 1435: + // 1436: + // 1437: ; //////////////////////////////////////////////////////////////////////////// + // 1438: ; STACK INSTRUCTIONS + // 1439: ; //////////////////////////////////////////////////////////////////////////// + // 1440: ; // + // 1441: + // 1442: + // 1443: ; //////////////////////////////////////////// JSR + // 1444: ; // + // 1445: JSR: + // 1446: decode pg1_JTA JSR $9D $BD ; JSR (dir ext) + // 1447: decode pg1_R1 PC $9D $BD ; JSR (dir ext) + // 1448: decode pg1_R2 IDATA $9D $BD ; JSR (dir ext) + // 1449: decode pg1_AR S $9D $BD ; JSR (dir ext) + // 1450: + // 1451: decode pg1_JTB JSR $AD ; JSR (idx) + // 1452: decode pg1_R1 PC $AD ; JSR (idx) + // 1453: decode pg1_R2 EA $AD ; JSR (idx) + // 1454: decode pg1_AR S $AD ; JSR (idx) + // 1455: + // 1456: DATA_PASS_A R1 ; PC + // 1457: + // 1458: SET_DATA_WIDTH W_R1 + // 1459: + // 1460: STACK_PUSH AR + // 1461: DMEM_STORE_W + // 1462: + // 1463: JUMP JMP + // 1464: micro_op_end + 8'h031: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h30; // JMP + CV_DATA_ALU_A_SEL_O = 4'h8; // R1 + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 1465: + // 1466: ; //////////////////////////////////////////// RTS + // 1467: ; // + // 1468: RTS: + // 1469: decode pg1_JTA RTS $39 ; RTS + // 1470: decode pg1_R1 PC $39 ; RTS + // 1471: decode pg1_R2 DMEM_RD $39 ; RTS + // 1472: decode pg1_AR S $39 ; RTS + // 1473: + // 1474: SET_DATA_WIDTH W_R1 + // 1475: + // 1476: STACK_PULL AR + // 1477: DMEM_LOAD_W + // 1478: + // 1479: JUMP JMP + // 1480: micro_op_end + 8'h032: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h30; // JMP + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1481: + // 1482: ; //////////////////////////////////////////// RTI + // 1483: ; // + // 1484: RTI: + // 1485: decode pg1_JTA RTI $3B ; RTI + // 1486: decode pg1_R1 PC $3B ; RTI + // 1487: decode pg1_R2 DMEM_RD $3B ; RTI + // 1488: decode pg1_AR S $3B ; RTI + // 1489: + // 1490: STACK_PULL ZERO ; Prime the decode pipeline! + // 1491: micro_op_end + 8'h033: begin + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1492: + // 1493: SET_DATA_WIDTH W_STACK_REG + // 1494: + // 1495: STACK_PULL AR + // 1496: DMEM_LOAD_W + // 1497: micro_op_end + 8'h034: begin + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1498: + // 1499: RTI_CCR: + // 1500: DATA_PASS_B DMEM_RD + // 1501: DATA_WRITE STACK_REG + // 1502: + // 1503: CCR_OP_W OP_XXXXXXXX ; FIXME get rid of this requirement + // 1504: micro_op_end + 8'h035: begin + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_DATA_ALU_WR_SEL_O = 4'h0; // STACK_REG + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 1505: + // 1506: RTI_TEST_E: + // 1507: IF E_CLEAR + // 1508: JUMP RTS + // 1509: micro_op_end + 8'h036: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h32; // RTS + CV_MICRO_SEQ_COND_SEL_O = 4'h6; // E_CLEAR + end + + + // 1510: + // 1511: RTI_PUL_ALL: + // 1512: SET_DATA_WIDTH W_STACK_REG + // 1513: + // 1514: STACK_PULL AR + // 1515: DMEM_LOAD_W + // 1516: + // 1517: JUMP PUL_LOOP + // 1518: micro_op_end + 8'h037: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h3a; // PUL_LOOP + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1519: + // 1520: + // 1521: ; //////////////////////////////////////////// PULS PULU + // 1522: ; // + // 1523: PUL: + // 1524: decode pg1_JTA PUL $35 ; PULS + // 1525: decode pg1_AR S $35 ; PULS + // 1526: + // 1527: decode pg1_JTA PUL $37 ; PULU + // 1528: decode pg1_AR U $37 ; PULU + // 1529: + // 1530: + // 1531: STACK_PULL ZERO ; Prime the decode pipeline! + // 1532: + // 1533: IF STACK_DONE + // 1534: JUMP NOP + // 1535: micro_op_end + 8'h038: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'hc; // NOP + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_MICRO_SEQ_COND_SEL_O = 4'h2; // STACK_DONE + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1536: + // 1537: SET_DATA_WIDTH W_STACK_REG + // 1538: + // 1539: STACK_PULL AR + // 1540: DMEM_LOAD_W + // 1541: + // 1542: IF STACK_DONE + // 1543: JUMP PUL_DONE + // 1544: micro_op_end + 8'h039: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h3b; // PUL_DONE + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_MICRO_SEQ_COND_SEL_O = 4'h2; // STACK_DONE + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1545: + // 1546: PUL_LOOP: + // 1547: DATA_PASS_B DMEM_RD + // 1548: DATA_WRITE STACK_REG + // 1549: + // 1550: CCR_OP_W OP_XXXXXXXX ; FIXME get rid of this requirement + // 1551: + // 1552: SET_DATA_WIDTH W_STACK_REG + // 1553: + // 1554: STACK_PULL AR + // 1555: DMEM_LOAD_W + // 1556: + // 1557: IF STACK_NEXT + // 1558: JUMP PUL_LOOP + // 1559: micro_op_end + 8'h03a: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h3a; // PUL_LOOP + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_DATA_ALU_WR_SEL_O = 4'h0; // STACK_REG + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h3; // STACK_NEXT + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + CV_STACK_OP_O = 2'h1; // STACK_OP_PULL + end + + + // 1560: + // 1561: PUL_DONE: + // 1562: DATA_PASS_B DMEM_RD + // 1563: DATA_WRITE STACK_REG + // 1564: + // 1565: CCR_OP_W OP_XXXXXXXX ; FIXME get rid of this requirement + // 1566: + // 1567: JUMP GO_NEW_PC ; PC must be written before "JUMP_TABLE_A_NEXT_PC" FIXME? + // 1568: micro_op_end + 8'h03b: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h2f; // GO_NEW_PC + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h5; // DMEM_RD + CV_DATA_ALU_WR_SEL_O = 4'h0; // STACK_REG + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_CCR_OP_O = 4'h9; // OP_XXXXXXXX + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + end + + + // 1569: + // 1570: + // 1571: ; //////////////////////////////////////////// PSHS PSHU + // 1572: ; // + // 1573: PSH: + // 1574: decode pg1_JTA PSH $34 ; PSHS + // 1575: decode pg1_AR S $34 ; PSHS + // 1576: + // 1577: decode pg1_JTA PSH $36 ; PSHU + // 1578: decode pg1_AR U $36 ; PSHU + // 1579: + // 1580: STACK_PUSH ZERO ; Prime the decode pipeline! + // 1581: + // 1582: IF STACK_DONE + // 1583: JUMP NOP + // 1584: micro_op_end + 8'h03c: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'hc; // NOP + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_MICRO_SEQ_COND_SEL_O = 4'h2; // STACK_DONE + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 1585: + // 1586: PSH_LOOP: + // 1587: DATA_PASS_A STACK_REG + // 1588: + // 1589: SET_DATA_WIDTH W_STACK_REG + // 1590: + // 1591: STACK_PUSH AR + // 1592: DMEM_STORE_W + // 1593: + // 1594: IF STACK_NEXT + // 1595: JUMP PSH_LOOP + // 1596: micro_op_end + 8'h03d: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h3d; // PSH_LOOP + CV_DATA_ALU_A_SEL_O = 4'h0; // STACK_REG + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h3; // STACK_NEXT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 1597: + // 1598: JUMP_TABLE_A_NEXT_PC + // 1599: micro_op_end + 8'h03e: begin + CV_MICRO_SEQ_OP_O = 3'h5; // OP_JUMP_TABLE_A_NEXT_PC + end + + + // 1600: + // 1601: + // 1602: ; //////////////////////////////////////////// SWI + // 1603: ; // + // 1604: SWI: + // 1605: decode pg1_JTA SWI $3F ; SWI + // 1606: decode pg1_AR S $3F ; SWI + // 1607: decode pg1_R1 PC $3F ; SWI + // 1608: decode pg1_R2 DMEM_RD $3F ; SWI + // 1609: + // 1610: STACK_PUSH ZERO ; Prime the decode pipeline! + // 1611: + // 1612: CCR_OP_W OP_1ooooooo ; Set E + // 1613: micro_op_end + 8'h03f: begin + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_CCR_OP_O = 4'h7; // OP_1OOOOOOO + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 1614: + // 1615: SWI_LOOP: + // 1616: DATA_PASS_A STACK_REG + // 1617: + // 1618: SET_DATA_WIDTH W_STACK_REG + // 1619: + // 1620: STACK_PUSH AR + // 1621: DMEM_STORE_W + // 1622: + // 1623: IF STACK_NEXT + // 1624: JUMP SWI_LOOP + // 1625: micro_op_end + 8'h040: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h40; // SWI_LOOP + CV_DATA_ALU_A_SEL_O = 4'h0; // STACK_REG + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'h8; // AR + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h2; // W_STACK_REG + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h3; // STACK_NEXT + CV_DMEM_OP_O = 2'h3; // DMEM_OP_WR + CV_STACK_OP_O = 2'h2; // STACK_OP_PUSH + end + + + // 1626: + // 1627: ; R1 is PC + // 1628: ; R2 is DMEM_RD + // 1629: + // 1630: SET_DATA_WIDTH W_16 + // 1631: + // 1632: ADDR_PASS IDATA ; SWI vector + // 1633: DMEM_LOAD_W + // 1634: + // 1635: CCR_OP_W OP_o1o1oooo ; Set I & F + // 1636: + // 1637: JUMP JMP + // 1638: micro_op_end + 8'h041: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h30; // JMP + CV_ADDR_ALU_REG_SEL_O = 4'he; // IDATA + CV_DATA_WIDTH_SEL_O = 3'h3; // W_16 + CV_CCR_OP_O = 4'h8; // OP_O1O1OOOO + CV_DMEM_OP_O = 2'h2; // DMEM_OP_RD + end + + + // 1639: + // 1640: + // 1641: + // 1642: ; //////////////////////////////////////////////////////////////////////////// + // 1643: + // 1644: + // 1645: ORG $FF + // 1646: + // 1647: TRAP: + // 1648: + // 1649: JUMP TRAP + // 1650: micro_op_end + 8'h0ff: begin + CV_MICRO_SEQ_OP_O = 3'h1; // OP_JUMP + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'hff; // TRAP + end + + + // 1651: + default: begin + // + // Control Logic Defaults + CV_MICRO_SEQ_OP_O = 3'h0; // OP_CONTINUE + CV_MICRO_SEQ_BRANCH_ADDR_O = 8'h0; // RESET + CV_DATA_ALU_A_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_B_SEL_O = 3'h7; // ZERO + CV_DATA_ALU_WR_SEL_O = 4'hf; // ZERO + CV_ADDR_ALU_REG_SEL_O = 4'hf; // ZERO + CV_DATA_ALU_OP_O = 3'h0; // A_PLUS_B + CV_DATA_WIDTH_SEL_O = 3'h0; // W_R1 + CV_DATA_ALU_SAU_EN_O = 1'h0; // FALSE + CV_CCR_OP_O = 4'h0; // OP_OOOOOOOO + CV_DATA_ALU_COND_SEL_O = 2'h0; // ZERO_BIT + CV_MICRO_SEQ_COND_SEL_O = 4'h1; // TRUE + CV_DMEM_OP_O = 2'h0; // DMEM_OP_IDLE + CV_STACK_OP_O = 2'h0; // STACK_OP_IDLE + end + endcase +end + +///////////////////////////////////////////////////////////////////////////// + +endmodule diff --git a/turbo9team_turbo9/rtl/turbo9_wishbone_16bit.v b/turbo9team_turbo9/rtl/turbo9_wishbone_16bit.v new file mode 100644 index 0000000000000000000000000000000000000000..792b53ce0ecfce3c23b562a06de4219e0f5a63af --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_wishbone_16bit.v @@ -0,0 +1,621 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Shared 8-bit program/data pipelined Wishbone memory interface +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_wishbone_16bit +#( + parameter REGISTER_WB_OUTPUTS = 1 // Register Wishbone Ouputs: True=1, False=0 +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // External Wishbone Interface + input [15:0] DAT_I, + input [4:0] TGD_I, + input ACK_I, + input STALL_I, + output [15:1] ADR_O, + output [15:0] DAT_O, + output [1:0] SEL_O, + output [4:0] TGD_O, + output WE_O, + output STB_O, + output CYC_O, + + // Data Memory Interface + input [15:0] DMEM_DAT_I, + output [15:0] DMEM_DAT_O, + input [15:0] DMEM_ADR_I, + output DMEM_BUSY_O, + input DMEM_REQ_I, + input DMEM_REQ_WIDTH_I, + input DMEM_WE_I, + output DMEM_RD_ACK_O, + output DMEM_WR_ACK_O, + output DMEM_ACK_WIDTH_O, + + // Program Memory Interface + output [15:0] PMEM_DAT_O, + input [15:0] PMEM_ADR_I, + output PMEM_BUSY_O, + input PMEM_RD_REQ_I, + output PMEM_RD_ACK_O, + output PMEM_ACK_WIDTH_O + +); + +///////////////////////////////////////////////////////////////////////////// +// INPUTS / OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Inputs: Clock & Reset +//input RST_I; // Reset. Active high and synchronized to CLK_I +//input CLK_I; // Clock + +// Wishbone Inputs +//input [7:0] DAT_I; // The data input array [DAT_I()] is used to pass + // binary data. + // +//input ACK_I; // The acknowledge input [ACK_I], when asserted, + // indicates the normal termination of a bus cycle. + // Also see the [ERR_I] and [RTY_I] signal descriptions. + // +//input STALL_I;// The pipeline stall input [STALL_I] indicates that + // current slave is not able to accept the transfer + // in the transaction queue. + // +//input ERR_I; // The error input [ERR_I] indicates an abnormal + // cycle termination. The source of the error, and + // the response generated by the MASTER is defined + // by the IP core supplier. Also see the [ACK_I] and + // [RTY_I] signal descriptions. + // +//input RTY_I; // The retry input [RTY_I] indicates that the interface + // is not ready to accept or send data, and that the + // cycle should be retried. When and how the cycle is + // retried is defined by the IP core supplier. Also + // see the [ERR_I] and [RTY_I] signal descriptions. + // +// Wishbone Outputs +//output [15:0] ADR_O; // The address output array [ADR_O()] is used to pass + // a binary address. The higher array boundary is + // specific to the address width of the core, and the + // lower array boundary is determined by the data port + // size and granularity. For example the array size on + // a 32-bit data port with BYTE granularity is + // [ADR_O(n..2)]. In some cases (such as FIFO + // interfaces) the array may not be present on the + // interface. + // +//output [7:0] DAT_O; // The data output array [DAT_O()] is used to pass + // binary data. The array boundaries are determined by + // the port size, with a maximum port size of 64-bits + // (e.g. [DAT_I(63..0)]). Also see the [DAT_I()] and + // [SEL_O()] signal descriptions. + // +//output WE_O; // The write enable output [WE_O] indicates whether + // the current local bus cycle is a READ or WRITE + // cycle. The signal is negated during READ cycles, + // and is asserted during WRITE cycles. + // +//output STB_O; // The strobe output [STB_O] indicates a valid data + // transfer cycle. It is used to qualify various other + // signals on the interface such as [SEL_O()]. The + // SLAVE asserts either the [ACK_I], [ERR_I] or + // [RTY_I] signals in response to every assertion of + // the [STB_O] signal. + // +//output CYC_O; // The cycle output [CYC_O], when asserted, indicates + // that a valid bus cycle is in progress. The signal + // is asserted for the duration of all bus cycles. For + // example, during a BLOCK transfer cycle there can be + // multiple data transfers. The [CYC_O] signal is + // asserted during the first data transfer, and remains + // asserted until the last data transfer. The [CYC_O] + // signal is useful for interfaces with multi-port + // interfaces (such as dual port memories). In these + // cases, the [CYC_O] signal requests use of a common + // bus from an arbiter. + +//output SEL_O: // The select output array [SEL_O()] indicates where + // valid data is expected on the [DAT_I()] signal array + // during READ cycles, and where it is placed on the + // [DAT_O()] signal array during WRITE cycles. The array + // boundaries are determined by the granularity of a + // port. For example, if 8-bit granularity is used on a + // 64-bit port, then there would be an array of eight + // select signals with boundaries of [SEL_O(7..0)]. Each + // individual select signal correlates to one of eight + // active bytes on the 64-bit data port. + + + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + + +//////////////////////////////////////// WIDTH_I defines +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +reg [15:1] adr_o_reg; +reg [15:1] adr_o_nxt; +localparam adr_o_rst = 15'h0000; + +reg [15:0] dat_o_reg; +reg [15:0] dat_o_nxt; +localparam dat_o_rst = 16'h0000; + +reg [7:0] lsb_byte_reg; +wire [7:0] lsb_byte_nxt; +localparam lsb_byte_rst = 8'h00; + +reg [7:0] msb_byte_reg; +wire [7:0] msb_byte_nxt; +localparam msb_byte_rst = 8'h00; + +reg [1:0] sel_o_reg; +reg [1:0] sel_o_nxt; +localparam sel_o_rst = 2'b00; + +reg we_o_reg; +reg we_o_nxt; +localparam we_o_rst = 1'b0; + +reg stb_o_reg; +reg stb_o_nxt; +localparam stb_o_rst = 1'b0; + +reg cyc_o_reg; +wire cyc_o_nxt; +localparam cyc_o_rst = 1'b0; + +wire tag_dmem_rd_i; +reg tag_dmem_rd_o_cycle1_reg; +reg tag_dmem_rd_o_cycle1_nxt; +localparam tag_dmem_rd_o_cycle1_rst = 1'b0; +reg tag_dmem_rd_o_reg; +reg tag_dmem_rd_o_nxt; +localparam tag_dmem_rd_o_rst = 1'b0; + +wire tag_dmem_wr_i; +reg tag_dmem_wr_o_cycle1_reg; +reg tag_dmem_wr_o_cycle1_nxt; +localparam tag_dmem_wr_o_cycle1_rst = 1'b0; +reg tag_dmem_wr_o_reg; +reg tag_dmem_wr_o_nxt; +localparam tag_dmem_wr_o_rst = 1'b0; + +wire tag_pmem_rd_i; +reg tag_pmem_rd_o_reg; +reg tag_pmem_rd_o_nxt; +localparam tag_pmem_rd_o_rst = 1'b0; + + +wire tag_width_i; +reg tag_width_o_reg; +reg tag_width_o_nxt; +localparam tag_width_o_rst = 1'b0; + +wire tag_adr0_i; +reg tag_adr0_o_reg; +reg tag_adr0_o_nxt; +localparam tag_adr0_o_rst = 1'b0; + +reg wishbone_state_reg; +reg wishbone_state_nxt; +localparam WISHBONE_CYCLE0 = 1'b0; +localparam WISHBONE_CYCLE1 = 1'b1; +wire wishbone_multicycle = (wishbone_state_reg != WISHBONE_CYCLE0); + +reg [2:0] pending_cnt_reg; +wire [2:0] pending_cnt_nxt; +localparam pending_cnt_rst = 3'b000; +wire [2:0] pending_cnt_term; + +wire ack_width; + +reg [15:0] dmem_dat; +reg [15:0] pmem_dat; + +wire [7:0] even_byte; +wire [7:0] odd_byte; + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// WISHBONE PIPELINE OUTPUT LOGIC +///////////////////////////////////////////////////////////////////////////// +// +// + +always @* begin + // + // Defaults + // + tag_dmem_rd_o_nxt = 1'b0; + tag_dmem_wr_o_nxt = 1'b0; + tag_pmem_rd_o_nxt = 1'b0; + // + tag_dmem_rd_o_cycle1_nxt = 1'b0; + tag_dmem_wr_o_cycle1_nxt = 1'b0; + // + tag_width_o_nxt = DMEM_REQ_WIDTH_I; + tag_adr0_o_nxt = DMEM_ADR_I[0]; + adr_o_nxt = DMEM_ADR_I[15:1]; + dat_o_nxt[15:8] = DMEM_DAT_I[15:8]; + dat_o_nxt[ 7:0] = DMEM_DAT_I[ 7:0]; + sel_o_nxt = 2'b00; + we_o_nxt = 1'b0; + stb_o_nxt = 1'b0; + // + wishbone_state_nxt = WISHBONE_CYCLE0; + + case (wishbone_state_reg) + WISHBONE_CYCLE0: begin + // + case ({DMEM_ADR_I[0], DMEM_REQ_WIDTH_I}) + // + {1'b0, WIDTH_16} : begin // even address, 16bit + dat_o_nxt[15:8] = DMEM_DAT_I[15:8]; // msb + dat_o_nxt[ 7:0] = DMEM_DAT_I[ 7:0]; // lsb + end + // + {1'b1, WIDTH_16} : begin // odd address, 16bit + //dat_o_nxt[15:8] = DMEM_DAT_I[7:0]; // don't care + dat_o_nxt[ 7:0] = DMEM_DAT_I[15:8]; // msb + end + // + {1'b0, WIDTH_8} : begin // even address, 8bit + dat_o_nxt[15:8] = DMEM_DAT_I[ 7:0]; // byte + //dat_o_nxt[ 7:0] = DMEM_DAT_I[15:8]; // don't care + end + // + {1'b1, WIDTH_8} : begin // odd address, 8bit + //dat_o_nxt[15:8] = DMEM_DAT_I[15:0]; // don't care + dat_o_nxt[ 7:0] = DMEM_DAT_I[ 7:0]; // byte + end + endcase + // + if (DMEM_REQ_I) begin + // + case ({DMEM_ADR_I[0], DMEM_REQ_WIDTH_I}) + // + {1'b0, WIDTH_16} : begin // even address, 16bit + sel_o_nxt = 2'b11; + // + tag_dmem_rd_o_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_nxt = DMEM_WE_I; + wishbone_state_nxt = WISHBONE_CYCLE0; + end + // + {1'b1, WIDTH_16} : begin // odd address, 16bit + sel_o_nxt = 2'b01; + // + tag_dmem_rd_o_cycle1_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_cycle1_nxt = DMEM_WE_I; + wishbone_state_nxt = WISHBONE_CYCLE1; + end + // + {1'b0, WIDTH_8} : begin // even address, 8bit + sel_o_nxt = 2'b10; + // + tag_dmem_rd_o_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_nxt = DMEM_WE_I; + wishbone_state_nxt = WISHBONE_CYCLE0; + end + // + {1'b1, WIDTH_8} : begin // odd address, 8bit + sel_o_nxt = 2'b01; + // + tag_dmem_rd_o_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_nxt = DMEM_WE_I; + wishbone_state_nxt = WISHBONE_CYCLE0; + end + endcase + // + tag_width_o_nxt = DMEM_REQ_WIDTH_I; + tag_adr0_o_nxt = DMEM_ADR_I[0]; + adr_o_nxt = DMEM_ADR_I[15:1]; + we_o_nxt = DMEM_WE_I; + stb_o_nxt = 1'b1; + // + end else if (PMEM_RD_REQ_I) begin + case (PMEM_ADR_I[0]) + 1'b0 : begin // even address, 16bit + tag_width_o_nxt = WIDTH_16; + sel_o_nxt = 2'b11; + end + 1'b1 : begin // odd address, 8bit + tag_width_o_nxt = WIDTH_8; + sel_o_nxt = 2'b01; + end + endcase + tag_pmem_rd_o_nxt = 1'b1; + wishbone_state_nxt = WISHBONE_CYCLE0; + //end + // + tag_adr0_o_nxt = PMEM_ADR_I[0]; + adr_o_nxt = PMEM_ADR_I[15:1] ; + we_o_nxt = 1'b0; + stb_o_nxt = 1'b1; + // + end else begin + wishbone_state_nxt = WISHBONE_CYCLE0; + end + // + end + + WISHBONE_CYCLE1: begin // multicycle state + + tag_dmem_rd_o_nxt = tag_dmem_rd_o_cycle1_reg; + tag_dmem_wr_o_nxt = tag_dmem_wr_o_cycle1_reg; + tag_pmem_rd_o_nxt = 1'b0; + tag_width_o_nxt = WIDTH_16; + tag_adr0_o_nxt = 1'b1; + adr_o_nxt = adr_o_reg + 15'h0001; + dat_o_nxt[15:8] = lsb_byte_reg; // lsb + //dat_o_nxt[ 7:0] = // don't care + sel_o_nxt = 2'b10; + we_o_nxt = we_o_reg; + stb_o_nxt = 1'b1; + wishbone_state_nxt = WISHBONE_CYCLE0; + + end + endcase +end + +assign lsb_byte_nxt = DMEM_DAT_I[7:0]; + +assign cyc_o_nxt = (pending_cnt_nxt != 3'b000) ? 1'b1 : 1'b0; + +assign pending_cnt_term = ( stb_o_nxt & ~ACK_I) ? 3'b001 : // inc + (~stb_o_nxt & ACK_I) ? 3'b111 : // dec + 3'b000 ; // hold +assign pending_cnt_nxt = pending_cnt_reg + pending_cnt_term; + + +always @(posedge CLK_I, posedge RST_I) begin + + if (RST_I) begin + adr_o_reg <= adr_o_rst; + dat_o_reg <= dat_o_rst; + sel_o_reg <= sel_o_rst; + we_o_reg <= we_o_rst; + stb_o_reg <= stb_o_rst; + cyc_o_reg <= cyc_o_rst; + tag_dmem_rd_o_reg <= tag_dmem_rd_o_rst; + tag_dmem_wr_o_reg <= tag_dmem_wr_o_rst; + tag_pmem_rd_o_reg <= tag_pmem_rd_o_rst; + tag_dmem_rd_o_cycle1_reg <= tag_dmem_rd_o_cycle1_rst; + tag_dmem_wr_o_cycle1_reg <= tag_dmem_wr_o_cycle1_rst; + tag_width_o_reg <= tag_width_o_rst; + tag_adr0_o_reg <= tag_adr0_o_rst; + pending_cnt_reg <= pending_cnt_rst; + lsb_byte_reg <= lsb_byte_rst; + wishbone_state_reg <= WISHBONE_CYCLE0; + end else begin + if (~STALL_I) begin // STALL_I should be generated externally and must be _registered_ + adr_o_reg <= adr_o_nxt; + dat_o_reg <= dat_o_nxt; + sel_o_reg <= sel_o_nxt; + we_o_reg <= we_o_nxt; + stb_o_reg <= stb_o_nxt; + cyc_o_reg <= cyc_o_nxt; + tag_dmem_rd_o_reg <= tag_dmem_rd_o_nxt; + tag_dmem_wr_o_reg <= tag_dmem_wr_o_nxt; + tag_pmem_rd_o_reg <= tag_pmem_rd_o_nxt; + tag_dmem_rd_o_cycle1_reg <= tag_dmem_rd_o_cycle1_nxt; + tag_dmem_wr_o_cycle1_reg <= tag_dmem_wr_o_cycle1_nxt; + tag_width_o_reg <= tag_width_o_nxt; + tag_adr0_o_reg <= tag_adr0_o_nxt; + pending_cnt_reg <= pending_cnt_nxt; + lsb_byte_reg <= lsb_byte_nxt; + wishbone_state_reg <= wishbone_state_nxt; + end + end +end + + +generate + if (REGISTER_WB_OUTPUTS) begin + // + assign ADR_O = adr_o_reg; + assign DAT_O = dat_o_reg; + assign SEL_O = sel_o_reg; + assign WE_O = we_o_reg ; + assign STB_O = stb_o_reg; + assign CYC_O = cyc_o_reg; + // + assign TGD_O[4] = tag_dmem_rd_o_reg; + assign TGD_O[3] = tag_dmem_wr_o_reg; + assign TGD_O[2] = tag_pmem_rd_o_reg; + assign TGD_O[1] = tag_adr0_o_reg; + assign TGD_O[0] = tag_width_o_reg; + // + end else begin + // + assign ADR_O = adr_o_nxt; + assign DAT_O = dat_o_nxt; + assign SEL_O = sel_o_nxt; + assign WE_O = we_o_nxt ; + assign STB_O = stb_o_nxt; + assign CYC_O = cyc_o_nxt; + // + assign TGD_O[4] = tag_dmem_rd_o_nxt; + assign TGD_O[3] = tag_dmem_wr_o_nxt; + assign TGD_O[2] = tag_pmem_rd_o_nxt; + assign TGD_O[1] = tag_adr0_o_nxt; + assign TGD_O[0] = tag_width_o_nxt; + // + end +endgenerate + + +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// WISHBONE PIPELINE FEEDBACK INPUT LOGIC +///////////////////////////////////////////////////////////////////////////// + +assign tag_dmem_rd_i = TGD_I[4]; +assign tag_dmem_wr_i = TGD_I[3]; +assign tag_pmem_rd_i = TGD_I[2]; +assign tag_adr0_i = TGD_I[1]; +assign tag_width_i = TGD_I[0]; + +assign even_byte = DAT_I[15:8]; +assign odd_byte = DAT_I[ 7:0]; + +assign msb_byte_nxt = DAT_I[7:0]; + +always @(posedge CLK_I, posedge RST_I) begin + if (RST_I) begin + msb_byte_reg <= msb_byte_rst; // INFO: Could remove if data_mem_ctrl register was used + end else begin + if (~STALL_I) begin // STALL_I should be generated externally and must be _registered_ + msb_byte_reg <= msb_byte_nxt; + end + end +end + + +// Program Memory Mux +always @* begin + // + // Defaults + // + pmem_dat[15:8] = even_byte; + pmem_dat[ 7:0] = odd_byte; + // + case (tag_adr0_i) + // + 1'b0 : begin // PMEM read, even address, 16bit + pmem_dat[15:8] = even_byte; + pmem_dat[ 7:0] = odd_byte; + end + // + 1'b1 : begin // PMEM read, odd address, 8bit + pmem_dat[15:8] = odd_byte; + //pmem_dat[ 7:0] = //Reduce Logic (Dont care for 8bit) + end + // + endcase +end + + +// Data Memory Mux +always @* begin + // + // Defaults + // + dmem_dat[15:8] = even_byte; + dmem_dat[ 7:0] = odd_byte; + // + case ({tag_adr0_i, tag_width_i}) + // + {1'b0, WIDTH_16} : begin // DMEM read, even address, 16bit + dmem_dat[15:8] = even_byte; + dmem_dat[ 7:0] = odd_byte; + end + // + {1'b1, WIDTH_16} : begin // DMEM read, odd address, 16bit + dmem_dat[15:8] = msb_byte_reg; + dmem_dat[ 7:0] = even_byte; + end + // + {1'b0, WIDTH_8} : begin // DMEM read, even address, 8bit + dmem_dat[15:8] = 8'h00; + dmem_dat[ 7:0] = even_byte; + end + // + {1'b1, WIDTH_8} : begin // DMEM read, odd address, 8bit + dmem_dat[15:8] = 8'h00; + dmem_dat[ 7:0] = odd_byte; + end + // + endcase +end + +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// PROG & DATA MEM OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// +// STALL_I should be generated externally and must be _registered_ +// +// Data Memory Interface +assign DMEM_DAT_O = dmem_dat; +assign DMEM_BUSY_O = STALL_I | wishbone_multicycle; +assign DMEM_RD_ACK_O = ~STALL_I & tag_dmem_rd_i & ~STALL_I; +assign DMEM_WR_ACK_O = ~STALL_I & tag_dmem_wr_i & ~STALL_I; +assign DMEM_ACK_WIDTH_O = tag_width_i; + +// Program Memory Interface +assign PMEM_DAT_O = pmem_dat; +assign PMEM_BUSY_O = STALL_I | DMEM_REQ_I | wishbone_multicycle; +assign PMEM_RD_ACK_O = ~STALL_I & tag_pmem_rd_i; +assign PMEM_ACK_WIDTH_O = tag_width_i; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_wishbone_2x8bit.v b/turbo9team_turbo9/rtl/turbo9_wishbone_2x8bit.v new file mode 100644 index 0000000000000000000000000000000000000000..3c5f3716b405c580f930c69b47ae8654c8f57e70 --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_wishbone_2x8bit.v @@ -0,0 +1,556 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Non-aligned 16-bit shared program/data pipelined Wishbone +// memory interface +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_wishbone_2x8bit +#( + parameter REGISTER_WB_OUTPUTS = 1 +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // External Wishbone Interface (Even bytes) + input [4:0] EVEN_TGD_I, + output [4:0] EVEN_TGD_O, + // + input [7:0] EVEN_DAT_I, + input EVEN_ACK_I, + input EVEN_STALL_I, + output [14:0] EVEN_ADR_O, + output [7:0] EVEN_DAT_O, + output EVEN_WE_O, + output EVEN_STB_O, + output EVEN_CYC_O, + + // External Wishbone Interface (Odd bytes) + input [7:0] ODD_DAT_I, + input ODD_ACK_I, + input ODD_STALL_I, + output [14:0] ODD_ADR_O, + output [7:0] ODD_DAT_O, + output ODD_WE_O, + output ODD_STB_O, + output ODD_CYC_O, + + // Data Memory Interface + input [15:0] DMEM_DAT_I, + output [15:0] DMEM_DAT_O, + input [15:0] DMEM_ADR_I, + output DMEM_BUSY_O, + input DMEM_REQ_I, + input DMEM_REQ_WIDTH_I, + input DMEM_WE_I, + output DMEM_RD_ACK_O, + output DMEM_WR_ACK_O, + output DMEM_ACK_WIDTH_O, + + // Program Memory Interface + output [15:0] PMEM_DAT_O, + input [15:0] PMEM_ADR_I, + output PMEM_BUSY_O, + input PMEM_RD_REQ_I, + //input PMEM_REQ_WIDTH_I, + output PMEM_RD_ACK_O + //output PMEM_ACK_WIDTH_O + +); + +///////////////////////////////////////////////////////////////////////////// +// INPUTS / OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Inputs: Clock & Reset +//input RST_I; // Reset. Active high and synchronized to CLK_I +//input CLK_I; // Clock + +// Wishbone Inputs +//input [15:0] DAT_I; // The data input array [DAT_I()] is used to pass + // binary data. + // +//input ACK_I; // The acknowledge input [ACK_I], when asserted, + // indicates the normal termination of a bus cycle. + // Also see the [ERR_I] and [RTY_I] signal descriptions. + // +//input STALL_I;// The pipeline stall input [STALL_I] indicates that + // current slave is not able to accept the transfer + // in the transaction queue. + // +//input ERR_I; // The error input [ERR_I] indicates an abnormal + // cycle termination. The source of the error, and + // the response generated by the MASTER is defined + // by the IP core supplier. Also see the [ACK_I] and + // [RTY_I] signal descriptions. + // +//input RTY_I; // The retry input [RTY_I] indicates that the interface + // is not ready to accept or send data, and that the + // cycle should be retried. When and how the cycle is + // retried is defined by the IP core supplier. Also + // see the [ERR_I] and [RTY_I] signal descriptions. + // +// Wishbone Outputs +//output [15:0] ADR_O; // The address output array [ADR_O()] is used to pass + // a binary address. The higher array boundary is + // specific to the address width of the core, and the + // lower array boundary is determined by the data port + // size and granularity. For example the array size on + // a 32-bit data port with BYTE granularity is + // [ADR_O(n..2)]. In some cases (such as FIFO + // interfaces) the array may not be present on the + // interface. + // +//output [15:0] DAT_O; // The data output array [DAT_O()] is used to pass + // binary data. The array boundaries are determined by + // the port size, with a maximum port size of 64-bits + // (e.g. [DAT_I(63..0)]). Also see the [DAT_I()] and + // [SEL_O()] signal descriptions. + // +//output WE_O; // The write enable output [WE_O] indicates whether + // the current local bus cycle is a READ or WRITE + // cycle. The signal is negated during READ cycles, + // and is asserted during WRITE cycles. + // +//output STB_O; // The strobe output [STB_O] indicates a valid data + // transfer cycle. It is used to qualify various other + // signals on the interface such as [SEL_O()]. The + // SLAVE asserts either the [ACK_I], [ERR_I] or + // [RTY_I] signals in response to every assertion of + // the [STB_O] signal. + // +//output CYC_O; // The cycle output [CYC_O], when asserted, indicates + // that a valid bus cycle is in progress. The signal + // is asserted for the duration of all bus cycles. For + // example, during a BLOCK transfer cycle there can be + // multiple data transfers. The [CYC_O] signal is + // asserted during the first data transfer, and remains + // asserted until the last data transfer. The [CYC_O] + // signal is useful for interfaces with multi-port + // interfaces (such as dual port memories). In these + // cases, the [CYC_O] signal requests use of a common + // bus from an arbiter. + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + + +//////////////////////////////////////// WIDTH_I defines +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + + +reg [14:0] even_adr_o_reg; +reg [14:0] even_adr_o_nxt; +localparam even_adr_o_rst = 15'h0000; + +reg [7:0] even_dat_o_reg; +reg [7:0] even_dat_o_nxt; +localparam even_dat_o_rst = 8'h00; + +reg even_we_o_reg; +reg even_we_o_nxt; +localparam even_we_o_rst = 1'b0; + +reg even_stb_o_reg; +reg even_stb_o_nxt; +localparam even_stb_o_rst = 1'b0; + +reg [14:0] odd_adr_o_reg; +reg [14:0] odd_adr_o_nxt; +localparam odd_adr_o_rst = 15'h0000; + +reg [7:0] odd_dat_o_reg; +reg [7:0] odd_dat_o_nxt; +localparam odd_dat_o_rst = 8'h00; + +reg odd_we_o_reg; +reg odd_we_o_nxt; +localparam odd_we_o_rst = 1'b0; + +reg odd_stb_o_reg; +reg odd_stb_o_nxt; +localparam odd_stb_o_rst = 1'b0; + +reg cyc_o_reg; +wire cyc_o_nxt; +localparam cyc_o_rst = 1'b0; + +wire even_tag_dmem_rd_i; +reg even_tag_dmem_rd_o_reg; +reg even_tag_dmem_rd_o_nxt; +localparam even_tag_dmem_rd_o_rst = 1'b0; + +wire even_tag_dmem_wr_i; +reg even_tag_dmem_wr_o_reg; +reg even_tag_dmem_wr_o_nxt; +localparam even_tag_dmem_wr_o_rst = 1'b0; + +wire even_tag_pmem_rd_i; +reg even_tag_pmem_rd_o_reg; +reg even_tag_pmem_rd_o_nxt; +localparam even_tag_pmem_rd_o_rst = 1'b0; + +wire even_tag_adr0_i; +reg even_tag_adr0_o_reg; +reg even_tag_adr0_o_nxt; +localparam even_tag_adr0_o_rst = 1'b0; + +wire even_tag_width_i; +reg even_tag_width_o_reg; +reg even_tag_width_o_nxt; +localparam even_tag_width_o_rst = WIDTH_16; + +reg [2:0] pending_cnt_reg; +wire [2:0] pending_cnt_nxt; +localparam pending_cnt_rst = 3'b000; +wire [2:0] pending_cnt_term; + +reg [15:0] dmem_dat; +reg [15:0] pmem_dat; + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// MEMORY ACCESS TAG LOGIC & WISHBONE OUTPUT REGISTERS +///////////////////////////////////////////////////////////////////////////// +// +// STALL_I should be generated externally and must be _registered_ +// +wire [14:0] dmem_even_adr_inc = DMEM_ADR_I[15:1] + {14'd0, DMEM_ADR_I[0]}; +wire [14:0] dmem_odd_adr = DMEM_ADR_I[15:1]; +wire dmem_adr0 = DMEM_ADR_I[0]; +// +wire [14:0] pmem_even_adr_inc = PMEM_ADR_I[15:1] + {14'd0, PMEM_ADR_I[0]}; +wire [14:0] pmem_odd_adr = PMEM_ADR_I[15:1]; +wire pmem_adr0 = PMEM_ADR_I[0]; + +wire stall_i = (EVEN_STALL_I|ODD_STALL_I); +wire stb_o_nxt = (even_stb_o_nxt|odd_stb_o_nxt); +wire ack_i = (EVEN_ACK_I|ODD_ACK_I); + +always @* begin + // + // Defaults + // + even_tag_dmem_rd_o_nxt = 1'b0; + even_tag_dmem_wr_o_nxt = 1'b0; + even_tag_pmem_rd_o_nxt = 1'b0; + even_tag_adr0_o_nxt = dmem_adr0; + even_tag_width_o_nxt = WIDTH_16; + // + even_stb_o_nxt = 1'b0; + even_we_o_nxt = 1'b0; + even_adr_o_nxt = dmem_even_adr_inc; + even_dat_o_nxt = DMEM_DAT_I[15:8]; + // + odd_stb_o_nxt = 1'b0; + odd_we_o_nxt = 1'b0; + odd_adr_o_nxt = dmem_odd_adr; + odd_dat_o_nxt = DMEM_DAT_I[ 7:0]; + + + if (DMEM_REQ_I) begin + even_tag_dmem_rd_o_nxt = ~DMEM_WE_I; + even_tag_dmem_wr_o_nxt = DMEM_WE_I; + even_tag_adr0_o_nxt = dmem_adr0; + // + if (DMEM_REQ_WIDTH_I == WIDTH_8) begin + even_tag_width_o_nxt = WIDTH_8; + even_stb_o_nxt = ~dmem_adr0; + even_we_o_nxt = ~dmem_adr0 & DMEM_WE_I; + // + odd_stb_o_nxt = dmem_adr0; + odd_we_o_nxt = dmem_adr0 & DMEM_WE_I; + end else begin + even_tag_width_o_nxt = WIDTH_16; + even_stb_o_nxt = 1'b1; + even_we_o_nxt = DMEM_WE_I; + // + odd_stb_o_nxt = 1'b1; + odd_we_o_nxt = DMEM_WE_I; + end + // + even_adr_o_nxt = dmem_even_adr_inc; + odd_adr_o_nxt = dmem_odd_adr; + // + end else if (PMEM_RD_REQ_I) begin + even_tag_pmem_rd_o_nxt = 1'b1; + even_tag_adr0_o_nxt = pmem_adr0; + // + //if (PMEM_REQ_WIDTH_I == WIDTH_8) begin + // even_tag_width_o_nxt = WIDTH_8; + // even_stb_o_nxt = ~pmem_adr0; + // // + // odd_stb_o_nxt = pmem_adr0; + //end else begin + even_tag_width_o_nxt = WIDTH_16; + even_stb_o_nxt = 1'b1; + // + odd_stb_o_nxt = 1'b1; + //end + // + even_we_o_nxt = 1'b0; + odd_we_o_nxt = 1'b0; + // + even_adr_o_nxt = pmem_even_adr_inc; + odd_adr_o_nxt = pmem_odd_adr; + // + end + // + case ({DMEM_REQ_WIDTH_I, dmem_adr0}) + // + {WIDTH_16, 1'b0} : begin + even_dat_o_nxt = DMEM_DAT_I[15:8]; + odd_dat_o_nxt = DMEM_DAT_I[ 7:0]; + end + // + {WIDTH_16, 1'b1} : begin + even_dat_o_nxt = DMEM_DAT_I[ 7:0]; + odd_dat_o_nxt = DMEM_DAT_I[15:8]; + end + // + {WIDTH_8, 1'b0} : begin + even_dat_o_nxt = DMEM_DAT_I[ 7:0]; + odd_dat_o_nxt = DMEM_DAT_I[15:8]; //INFO: Minimize logic? + end + // + {WIDTH_8, 1'b1} : begin + even_dat_o_nxt = DMEM_DAT_I[15:8]; //INFO: Dont care! + odd_dat_o_nxt = DMEM_DAT_I[ 7:0]; + end + // + endcase +end + +assign cyc_o_nxt = (pending_cnt_nxt != 3'b000) ? 1'b1 : 1'b0; + +assign pending_cnt_term = ( stb_o_nxt & ~ack_i) ? 3'b001 : // inc + (~stb_o_nxt & ack_i) ? 3'b111 : // dec + 3'b000 ; // hold +assign pending_cnt_nxt = pending_cnt_reg + pending_cnt_term; + + +// Program Memory Mux +always @* begin + // + // Defaults + // + pmem_dat[15:8] = EVEN_DAT_I; + pmem_dat[ 7:0] = ODD_DAT_I; + case (even_tag_adr0_i) + // + 1'b0 : begin // PMEM read, even address, 16bit or 8bit + pmem_dat[15:8] = EVEN_DAT_I; + pmem_dat[ 7:0] = ODD_DAT_I; + end + // + 1'b1 : begin // PMEM read, odd address, 16bit or 8bit + pmem_dat[15:8] = ODD_DAT_I; + pmem_dat[ 7:0] = EVEN_DAT_I; + end + // + endcase +end + + +// Data Memory Mux +always @* begin + // + // Defaults + // + dmem_dat[15:8] = EVEN_DAT_I; + dmem_dat[ 7:0] = ODD_DAT_I; + case ({even_tag_adr0_i, even_tag_width_i}) + // + {1'b0, WIDTH_16} : begin // DMEM read, even address, 16bit + dmem_dat[15:8] = EVEN_DAT_I; + dmem_dat[ 7:0] = ODD_DAT_I; + end + // + {1'b1, WIDTH_16} : begin // DMEM read, odd address, 16bit + dmem_dat[15:8] = ODD_DAT_I; + dmem_dat[ 7:0] = EVEN_DAT_I; + end + // + {1'b0, WIDTH_8} : begin // DMEM read, even address, 8bit + dmem_dat[15:8] = 8'h00; + dmem_dat[ 7:0] = EVEN_DAT_I; + end + // + {1'b1, WIDTH_8} : begin // DMEM read, odd address, 8bit + dmem_dat[15:8] = 8'h00; + dmem_dat[ 7:0] = ODD_DAT_I; + end + // + endcase +end + + +always @(posedge CLK_I, posedge RST_I) begin + + if (RST_I) begin + even_adr_o_reg <= even_adr_o_rst; + even_dat_o_reg <= even_dat_o_rst; + even_we_o_reg <= even_we_o_rst; + even_stb_o_reg <= even_stb_o_rst; + odd_adr_o_reg <= odd_adr_o_rst; + odd_dat_o_reg <= odd_dat_o_rst; + odd_we_o_reg <= odd_we_o_rst; + odd_stb_o_reg <= odd_stb_o_rst; + cyc_o_reg <= cyc_o_rst; + even_tag_dmem_rd_o_reg <= even_tag_dmem_rd_o_rst; + even_tag_dmem_wr_o_reg <= even_tag_dmem_wr_o_rst; + even_tag_pmem_rd_o_reg <= even_tag_pmem_rd_o_rst; + even_tag_adr0_o_reg <= even_tag_adr0_o_rst; + even_tag_width_o_reg <= even_tag_width_o_rst; + pending_cnt_reg <= pending_cnt_rst; + end else begin + if (~stall_i) begin + even_adr_o_reg <= even_adr_o_nxt; + even_dat_o_reg <= even_dat_o_nxt; + even_we_o_reg <= even_we_o_nxt; + even_stb_o_reg <= even_stb_o_nxt; + odd_adr_o_reg <= odd_adr_o_nxt; + odd_dat_o_reg <= odd_dat_o_nxt; + odd_we_o_reg <= odd_we_o_nxt; + odd_stb_o_reg <= odd_stb_o_nxt; + cyc_o_reg <= cyc_o_nxt; + even_tag_dmem_rd_o_reg <= even_tag_dmem_rd_o_nxt; + even_tag_dmem_wr_o_reg <= even_tag_dmem_wr_o_nxt; + even_tag_pmem_rd_o_reg <= even_tag_pmem_rd_o_nxt; + even_tag_adr0_o_reg <= even_tag_adr0_o_nxt; + even_tag_width_o_reg <= even_tag_width_o_nxt; + pending_cnt_reg <= pending_cnt_nxt; + end + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// EXTERNAL WISHBONE INTERFACE +///////////////////////////////////////////////////////////////////////////// +generate + if (REGISTER_WB_OUTPUTS) begin + assign ODD_ADR_O = odd_adr_o_reg; + assign ODD_DAT_O = odd_dat_o_reg; + assign ODD_WE_O = odd_we_o_reg ; + assign ODD_STB_O = odd_stb_o_reg; + assign ODD_CYC_O = cyc_o_reg; + + assign EVEN_ADR_O = even_adr_o_reg; + assign EVEN_DAT_O = even_dat_o_reg; + assign EVEN_WE_O = even_we_o_reg ; + assign EVEN_STB_O = even_stb_o_reg; + assign EVEN_CYC_O = cyc_o_reg; + + assign EVEN_TGD_O[4] = even_tag_dmem_rd_o_reg; + assign EVEN_TGD_O[3] = even_tag_dmem_wr_o_reg; + assign EVEN_TGD_O[2] = even_tag_pmem_rd_o_reg; + assign EVEN_TGD_O[1] = even_tag_adr0_o_reg; + assign EVEN_TGD_O[0] = even_tag_width_o_reg; + end else begin + assign ODD_ADR_O = odd_adr_o_nxt; + assign ODD_DAT_O = odd_dat_o_nxt; + assign ODD_WE_O = odd_we_o_nxt; + assign ODD_STB_O = odd_stb_o_nxt; + assign ODD_CYC_O = cyc_o_nxt; + + assign EVEN_ADR_O = even_adr_o_nxt; + assign EVEN_DAT_O = even_dat_o_nxt; + assign EVEN_WE_O = even_we_o_nxt; + assign EVEN_STB_O = even_stb_o_nxt; + assign EVEN_CYC_O = cyc_o_nxt; + + assign EVEN_TGD_O[4] = even_tag_dmem_rd_o_nxt; + assign EVEN_TGD_O[3] = even_tag_dmem_wr_o_nxt; + assign EVEN_TGD_O[2] = even_tag_pmem_rd_o_nxt; + assign EVEN_TGD_O[1] = even_tag_adr0_o_nxt; + assign EVEN_TGD_O[0] = even_tag_width_o_nxt; + end +endgenerate + + +assign even_tag_dmem_rd_i = EVEN_TGD_I[4]; +assign even_tag_dmem_wr_i = EVEN_TGD_I[3]; +assign even_tag_pmem_rd_i = EVEN_TGD_I[2]; +assign even_tag_adr0_i = EVEN_TGD_I[1]; +assign even_tag_width_i = EVEN_TGD_I[0]; +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// PROG & DATA MEM OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Data Memory Interface +assign DMEM_DAT_O = dmem_dat; +assign DMEM_BUSY_O = stall_i; +assign DMEM_RD_ACK_O = even_tag_dmem_rd_i & ~stall_i; +assign DMEM_WR_ACK_O = even_tag_dmem_wr_i & ~stall_i; +assign DMEM_ACK_WIDTH_O = even_tag_width_i; + +// Program Memory Interface +assign PMEM_DAT_O = pmem_dat; +assign PMEM_BUSY_O = DMEM_REQ_I | stall_i; +assign PMEM_RD_ACK_O = even_tag_pmem_rd_i & ~stall_i; +//assign PMEM_ACK_WIDTH_O = even_tag_width_i; +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/rtl/turbo9_wishbone_8bit.v b/turbo9team_turbo9/rtl/turbo9_wishbone_8bit.v new file mode 100644 index 0000000000000000000000000000000000000000..6b23baf5acf04c7de4d30f32e860f1555a55bced --- /dev/null +++ b/turbo9team_turbo9/rtl/turbo9_wishbone_8bit.v @@ -0,0 +1,464 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Shared 8-bit program/data pipelined Wishbone memory interface +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// MODULE +///////////////////////////////////////////////////////////////////////////// +module turbo9_wishbone_8bit +#( + parameter REGISTER_WB_OUTPUTS = 1 // Register Wishbone Ouputs: True=1, False=0 +) +( + // Inputs: Clock & Reset + input RST_I, + input CLK_I, + + // External Wishbone Interface + input [7:0] DAT_I, + input [3:0] TGD_I, + input ACK_I, + input STALL_I, + output [15:0] ADR_O, + output [7:0] DAT_O, + output [3:0] TGD_O, + output WE_O, + output STB_O, + output CYC_O, + + // Data Memory Interface + input [15:0] DMEM_DAT_I, + output [15:0] DMEM_DAT_O, + input [15:0] DMEM_ADR_I, + output DMEM_BUSY_O, + input DMEM_REQ_I, + input DMEM_REQ_WIDTH_I, + input DMEM_WE_I, + output DMEM_RD_ACK_O, + output DMEM_WR_ACK_O, + output DMEM_ACK_WIDTH_O, + + // Program Memory Interface + output [15:0] PMEM_DAT_O, + input [15:0] PMEM_ADR_I, + output PMEM_BUSY_O, + input PMEM_RD_REQ_I, + //input PMEM_REQ_WIDTH_I, + output PMEM_RD_ACK_O + //output PMEM_ACK_WIDTH_O + +); + +///////////////////////////////////////////////////////////////////////////// +// INPUTS / OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Inputs: Clock & Reset +//input RST_I; // Reset. Active high and synchronized to CLK_I +//input CLK_I; // Clock + +// Wishbone Inputs +//input [7:0] DAT_I; // The data input array [DAT_I()] is used to pass + // binary data. + // +//input ACK_I; // The acknowledge input [ACK_I], when asserted, + // indicates the normal termination of a bus cycle. + // Also see the [ERR_I] and [RTY_I] signal descriptions. + // +//input STALL_I;// The pipeline stall input [STALL_I] indicates that + // current slave is not able to accept the transfer + // in the transaction queue. + // +//input ERR_I; // The error input [ERR_I] indicates an abnormal + // cycle termination. The source of the error, and + // the response generated by the MASTER is defined + // by the IP core supplier. Also see the [ACK_I] and + // [RTY_I] signal descriptions. + // +//input RTY_I; // The retry input [RTY_I] indicates that the interface + // is not ready to accept or send data, and that the + // cycle should be retried. When and how the cycle is + // retried is defined by the IP core supplier. Also + // see the [ERR_I] and [RTY_I] signal descriptions. + // +// Wishbone Outputs +//output [15:0] ADR_O; // The address output array [ADR_O()] is used to pass + // a binary address. The higher array boundary is + // specific to the address width of the core, and the + // lower array boundary is determined by the data port + // size and granularity. For example the array size on + // a 32-bit data port with BYTE granularity is + // [ADR_O(n..2)]. In some cases (such as FIFO + // interfaces) the array may not be present on the + // interface. + // +//output [7:0] DAT_O; // The data output array [DAT_O()] is used to pass + // binary data. The array boundaries are determined by + // the port size, with a maximum port size of 64-bits + // (e.g. [DAT_I(63..0)]). Also see the [DAT_I()] and + // [SEL_O()] signal descriptions. + // +//output WE_O; // The write enable output [WE_O] indicates whether + // the current local bus cycle is a READ or WRITE + // cycle. The signal is negated during READ cycles, + // and is asserted during WRITE cycles. + // +//output STB_O; // The strobe output [STB_O] indicates a valid data + // transfer cycle. It is used to qualify various other + // signals on the interface such as [SEL_O()]. The + // SLAVE asserts either the [ACK_I], [ERR_I] or + // [RTY_I] signals in response to every assertion of + // the [STB_O] signal. + // +//output CYC_O; // The cycle output [CYC_O], when asserted, indicates + // that a valid bus cycle is in progress. The signal + // is asserted for the duration of all bus cycles. For + // example, during a BLOCK transfer cycle there can be + // multiple data transfers. The [CYC_O] signal is + // asserted during the first data transfer, and remains + // asserted until the last data transfer. The [CYC_O] + // signal is useful for interfaces with multi-port + // interfaces (such as dual port memories). In these + // cases, the [CYC_O] signal requests use of a common + // bus from an arbiter. + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// INTERNAL SIGNALS +///////////////////////////////////////////////////////////////////////////// + + +//////////////////////////////////////// WIDTH_I defines +// +// This must match the MSB of the *_REG_SEL control vectors +localparam WIDTH_16 = 1'b0; +localparam WIDTH_8 = 1'b1; + +reg [15:0] adr_o_reg; +reg [15:0] adr_o_nxt; +localparam adr_o_rst = 16'h0000; + +reg [7:0] dat_o_reg; +reg [7:0] dat_o_nxt; +localparam dat_o_rst = 8'h00; + +reg [7:0] dat_o_lo_byte_reg; +wire [7:0] dat_o_lo_byte_nxt; +localparam dat_o_lo_byte_rst = 8'h00; + +reg [7:0] dat_i_hi_byte_reg; +wire [7:0] dat_i_hi_byte_nxt; +localparam dat_i_hi_byte_rst = 8'h00; + +reg we_o_reg; +reg we_o_nxt; +localparam we_o_rst = 1'b0; + +reg stb_o_reg; +reg stb_o_nxt; +localparam stb_o_rst = 1'b0; + +reg cyc_o_reg; +wire cyc_o_nxt; +localparam cyc_o_rst = 1'b0; + +wire tag_dmem_rd_i; +reg tag_dmem_rd_o_16bit_reg; +reg tag_dmem_rd_o_16bit_nxt; +localparam tag_dmem_rd_o_16bit_rst = 1'b0; +reg tag_dmem_rd_o_reg; +reg tag_dmem_rd_o_nxt; +localparam tag_dmem_rd_o_rst = 1'b0; + +wire tag_dmem_wr_i; +reg tag_dmem_wr_o_16bit_reg; +reg tag_dmem_wr_o_16bit_nxt; +localparam tag_dmem_wr_o_16bit_rst = 1'b0; +reg tag_dmem_wr_o_reg; +reg tag_dmem_wr_o_nxt; +localparam tag_dmem_wr_o_rst = 1'b0; + +wire tag_pmem_rd_i; +//reg tag_pmem_rd_o_16bit_reg; +//reg tag_pmem_rd_o_16bit_nxt; +//localparam tag_pmem_rd_o_16bit_rst = 1'b0; +reg tag_pmem_rd_o_reg; +reg tag_pmem_rd_o_nxt; +localparam tag_pmem_rd_o_rst = 1'b0; + +wire tag_16bit_i; +reg tag_16bit_i_reg; +wire tag_16bit_i_nxt; +localparam tag_16bit_i_rst = 1'b0; + +wire tag_16bit_o; +reg tag_16bit_o_reg; +reg tag_16bit_o_nxt; +localparam tag_16bit_o_rst = 1'b0; + +reg [2:0] pending_cnt_reg; +wire [2:0] pending_cnt_nxt; +localparam pending_cnt_rst = 3'b000; +wire [2:0] pending_cnt_term; + +wire ack_width; + +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// MEMORY ACCESS TAG LOGIC & WISHBONE OUTPUT REGISTERS +///////////////////////////////////////////////////////////////////////////// +// +// STALL_I should be generated externally and must be _registered_ +// + +always @* begin + // + // Defaults + // + tag_dmem_rd_o_nxt = 1'b0; + tag_dmem_wr_o_nxt = 1'b0; + tag_pmem_rd_o_nxt = 1'b0; + // + tag_dmem_rd_o_16bit_nxt = 1'b0; + tag_dmem_wr_o_16bit_nxt = 1'b0; + //tag_pmem_rd_o_16bit_nxt = 1'b0; + // + tag_16bit_o_nxt = 1'b0; + // + adr_o_nxt = DMEM_ADR_I; + dat_o_nxt = DMEM_DAT_I[ 7:0]; + we_o_nxt = 1'b0; + stb_o_nxt = 1'b0; + + case (tag_16bit_o_reg) + 1'b0: begin // 8bit state + // + if (DMEM_REQ_I) begin + // + if (DMEM_REQ_WIDTH_I == WIDTH_16) begin + tag_dmem_rd_o_16bit_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_16bit_nxt = DMEM_WE_I; + tag_16bit_o_nxt = 1'b1; + end else begin + tag_dmem_rd_o_nxt = ~DMEM_WE_I; + tag_dmem_wr_o_nxt = DMEM_WE_I; + tag_16bit_o_nxt = 1'b0; + end + // + adr_o_nxt = DMEM_ADR_I; + we_o_nxt = DMEM_WE_I; + stb_o_nxt = 1'b1; + // + end else if (PMEM_RD_REQ_I) begin + // + //if (PMEM_REQ_WIDTH_I == WIDTH_16) begin // INFO 8bit only is better performance + // tag_pmem_rd_o_16bit_nxt = 1'b1; + // tag_16bit_o_nxt = 1'b1; + //end else begin + tag_pmem_rd_o_nxt = 1'b1; + tag_16bit_o_nxt = 1'b0; + //end + // + adr_o_nxt = PMEM_ADR_I; + we_o_nxt = 1'b0; + stb_o_nxt = 1'b1; + // + end else begin + tag_16bit_o_nxt = 1'b0; + end + // + if (DMEM_REQ_WIDTH_I == WIDTH_16) begin + dat_o_nxt = DMEM_DAT_I[15:8]; + end else begin + dat_o_nxt = DMEM_DAT_I[ 7:0]; + end + // + end + + 1'b1: begin // 16bit state + + tag_dmem_rd_o_nxt = tag_dmem_rd_o_16bit_reg; + tag_dmem_wr_o_nxt = tag_dmem_wr_o_16bit_reg; + //tag_pmem_rd_o_nxt = tag_pmem_rd_o_16bit_reg; + tag_16bit_o_nxt = 1'b0; + adr_o_nxt = adr_o_reg + 16'h0001; + dat_o_nxt = dat_o_lo_byte_reg; + we_o_nxt = we_o_reg; + stb_o_nxt = stb_o_reg; + + end + endcase +end + +assign dat_o_lo_byte_nxt = DMEM_DAT_I[7:0]; + +assign cyc_o_nxt = (pending_cnt_nxt != 3'b000) ? 1'b1 : 1'b0; + +assign pending_cnt_term = ( stb_o_nxt & ~ACK_I) ? 3'b001 : // inc + (~stb_o_nxt & ACK_I) ? 3'b111 : // dec + 3'b000 ; // hold +assign pending_cnt_nxt = pending_cnt_reg + pending_cnt_term; + +assign dat_i_hi_byte_nxt = (tag_16bit_i) ? DAT_I : 8'h00; + +assign tag_16bit_i_nxt = tag_16bit_i; +assign ack_width = (tag_16bit_i_reg) ? WIDTH_16 : WIDTH_8; // FIXME just do this like the 16bit version + +always @(posedge CLK_I, posedge RST_I) begin + + if (RST_I) begin + adr_o_reg <= adr_o_rst; + dat_o_reg <= dat_o_rst; + we_o_reg <= we_o_rst; + stb_o_reg <= stb_o_rst; + cyc_o_reg <= cyc_o_rst; + tag_dmem_rd_o_reg <= tag_dmem_rd_o_rst; + tag_dmem_wr_o_reg <= tag_dmem_wr_o_rst; + tag_pmem_rd_o_reg <= tag_pmem_rd_o_rst; + tag_dmem_rd_o_16bit_reg <= tag_dmem_rd_o_16bit_rst; + tag_dmem_wr_o_16bit_reg <= tag_dmem_wr_o_16bit_rst; + //tag_pmem_rd_o_16bit_reg <= tag_pmem_rd_o_16bit_rst; + tag_16bit_o_reg <= tag_16bit_o_rst; + pending_cnt_reg <= pending_cnt_rst; + dat_o_lo_byte_reg <= dat_o_lo_byte_rst; + dat_i_hi_byte_reg <= dat_i_hi_byte_rst; + tag_16bit_i_reg <= tag_16bit_i_rst; + + end else begin + + if (~STALL_I) begin + adr_o_reg <= adr_o_nxt; + dat_o_reg <= dat_o_nxt; + we_o_reg <= we_o_nxt; + stb_o_reg <= stb_o_nxt; + cyc_o_reg <= cyc_o_nxt; + tag_dmem_rd_o_reg <= tag_dmem_rd_o_nxt; + tag_dmem_wr_o_reg <= tag_dmem_wr_o_nxt; + tag_pmem_rd_o_reg <= tag_pmem_rd_o_nxt; + tag_dmem_rd_o_16bit_reg <= tag_dmem_rd_o_16bit_nxt; + tag_dmem_wr_o_16bit_reg <= tag_dmem_wr_o_16bit_nxt; + //tag_pmem_rd_o_16bit_reg <= tag_pmem_rd_o_16bit_nxt; + tag_16bit_o_reg <= tag_16bit_o_nxt; + pending_cnt_reg <= pending_cnt_nxt; + dat_o_lo_byte_reg <= dat_o_lo_byte_nxt; + dat_i_hi_byte_reg <= dat_i_hi_byte_nxt; + tag_16bit_i_reg <= tag_16bit_i_nxt; + end + + end +end +// +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// WISHBONE +///////////////////////////////////////////////////////////////////////////// + +generate + if (REGISTER_WB_OUTPUTS) begin + // + assign ADR_O = adr_o_reg; + assign DAT_O = dat_o_reg; + assign WE_O = we_o_reg ; + assign STB_O = stb_o_reg; + assign CYC_O = cyc_o_reg; + // + assign TGD_O[3] = tag_dmem_rd_o_reg; + assign TGD_O[2] = tag_dmem_wr_o_reg; + assign TGD_O[1] = tag_pmem_rd_o_reg; + assign TGD_O[0] = tag_16bit_o_reg; + assign tag_16bit_o = tag_16bit_o_reg; + // + end else begin + // + assign ADR_O = adr_o_nxt; + assign DAT_O = dat_o_nxt; + assign WE_O = we_o_nxt ; + assign STB_O = stb_o_nxt; + assign CYC_O = cyc_o_nxt; + // + assign TGD_O[3] = tag_dmem_rd_o_nxt; + assign TGD_O[2] = tag_dmem_wr_o_nxt; + assign TGD_O[1] = tag_pmem_rd_o_nxt; + assign TGD_O[0] = tag_16bit_o_nxt; + assign tag_16bit_o = tag_16bit_o_reg; + // + end +endgenerate + +assign tag_dmem_rd_i = TGD_I[3]; +assign tag_dmem_wr_i = TGD_I[2]; +assign tag_pmem_rd_i = TGD_I[1]; +assign tag_16bit_i = TGD_I[0]; +///////////////////////////////////////////////////////////////////////////// + + + +///////////////////////////////////////////////////////////////////////////// +// PROG & DATA MEM OUTPUTS +///////////////////////////////////////////////////////////////////////////// +// Data Memory Interface +assign DMEM_DAT_O = {dat_i_hi_byte_reg, DAT_I}; +assign DMEM_BUSY_O = tag_16bit_o | STALL_I; +assign DMEM_RD_ACK_O = tag_dmem_rd_i & ~STALL_I; +assign DMEM_WR_ACK_O = tag_dmem_wr_i & ~STALL_I; +assign DMEM_ACK_WIDTH_O = ack_width; + +// Program Memory Interface +//assign PMEM_DAT_O = {dat_i_hi_byte_reg, DAT_I}; +assign PMEM_DAT_O = {8'h00, DAT_I}; //INFO 8bit only for PMEM, to reduce wasted cycles +assign PMEM_BUSY_O = DMEM_REQ_I | tag_16bit_o | STALL_I; +assign PMEM_RD_ACK_O = tag_pmem_rd_i & ~STALL_I; +//assign PMEM_ACK_WIDTH_O = WIDTH_8; //INFO tie to constant to reduce logic. +// +///////////////////////////////////////////////////////////////////////////// + +endmodule + diff --git a/turbo9team_turbo9/tb/README.md b/turbo9team_turbo9/tb/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b77f7ddad34ae64d2985ea6b3788dae189c6a59 --- /dev/null +++ b/turbo9team_turbo9/tb/README.md @@ -0,0 +1,57 @@ + + + + +# Testbench & Testcases +| | | +|------------------------|--------------------------------------------------------------| +| f.list.tb_dv_top | File list for testbench | +| f.list.tb_stim_top | File list for stimbench | +| README.txt | This file | +| sim_boot.vh | Defines from sim_boot.asm | +| tb_dv_6809_model.v | Testbench: 6809 behavioral model | +| tb_dv_asm.vh | Defines from tb_dv_asm.asm | +| tb_dv_lib.v | Testbench: Library of functions and tasks | +| tb_dv_memory.v | Testbench: wrapper for memory array | +| tb_dv_top.v | Testbench: Top level of the testbench | +| tb_stim_flags.v | Stimbench: flag logic | +| tb_stim_fpga.v | Stimbench: fpga_top | +| tb_stim_mul_div.v | Stimbench: Multiply & divide algroithm | +| tb_stim_top.v | Stimbench: Top level | +| tc_dv_dir_instr.v | Testcase: Direct instructions | +| tc_dv_exg_16b_instr.v | Testcase: Exchange instruction w/ 16-bit registers | +| tc_dv_exg_8b_instr.v | Testcase: Exchange instruction w/ 8-bit registers | +| tc_dv_ext_ind_instr.v | Testcase: Extended Indirect instructions (Not completed) | +| tc_dv_ext_instr.v | Testcase: Extended instructions | +| tc_dv_idx_0b_instr.v | Testcase: Indexed no offset instructions | +| tc_dv_idx_16b_instr.v | Testcase: Indexed 16-bit offset instructions | +| tc_dv_idx_5b_instr.v | Testcase: Indexed 5-bit offset instructions | +| tc_dv_idx_8b_instr.v | Testcase: Indexed 8-bit offset instructions | +| tc_dv_idx_a_instr.v | Testcase: Indexed A offset instructions | +| tc_dv_idx_b_instr.v | Testcase: Indexed B offset instructions | +| tc_dv_idx_d_instr.v | Testcase: Indexed D offset instructions | +| tc_dv_idx_m1_instr.v | Testcase: Indexed Minus 1 instructions | +| tc_dv_idx_m2_instr.v | Testcase: Indexed Minus 2 instructions | +| tc_dv_idx_p1_instr.v | Testcase: Indexed Plus 1 instructions | +| tc_dv_idx_p2_instr.v | Testcase: Indexed Plus 2 instructions | +| tc_dv_idx_pc16_instr.v | Testcase: Indexed PC 16-bit offset instructions | +| tc_dv_idx_pc8_instr.v | Testcase: Indexed PC 8-bit offset instructions | +| tc_dv_imm_instr.v | Testcase: Immediate instructions | +| tc_dv_ind_0b_instr.v | Testcase: Indirect no offset | +| tc_dv_ind_16b_instr.v | Testcase: Indirect 16-bit offset | +| tc_dv_ind_8b_instr.v | Testcase: Indirect 8-bit offset | +| tc_dv_ind_a_instr.v | Testcase: Indirect A offset | +| tc_dv_ind_b_instr.v | Testcase: Indirect B offset | +| tc_dv_ind_d_instr.v | Testcase: Indirect D offset | +| tc_dv_ind_m2_instr.v | Testcase: Indirect Minus 2 | +| tc_dv_ind_p2_instr.v | Testcase: Indirect Plus 2 | +| tc_dv_ind_pc16_instr.v | Testcase: Indirect PC 16-bit offset | +| tc_dv_ind_pc8_instr.v | Testcase: Indirect PC 8-bit offset | +| tc_dv_inh_instr.v | Testcase: Inherent instructions | +| tc_dv_rel16_instr.v | Testcase: Relative 16-bit instructions | +| tc_dv_rel_instr.v | Testcase: Relative 8-bit instructions | +| tc_dv_run_code.v | Testcase: Run Code | +| tc_dv_sau_instr.v | Testcase: Sequential Arithmetic Unit instructions | +| tc_dv_tfr_16b_instr.v | Testcase: Transfer instruction w/ 16-bit registers | +| tc_dv_tfr_8b_instr.v | Testcase: Transfer instruction w/ 8-bit registers | +| | | diff --git a/turbo9team_turbo9/tb/sim_boot.vh b/turbo9team_turbo9/tb/sim_boot.vh new file mode 100644 index 0000000000000000000000000000000000000000..914feb924caac989d56ed652350b6273b15aefea --- /dev/null +++ b/turbo9team_turbo9/tb/sim_boot.vh @@ -0,0 +1,66 @@ +//////////////////////////////////////////////////////////////////////////////// +// // +// Definition file // +// // +//////////////////////////////////////////////////////////////////////////////// + +`define asm_acia_data 16'h0002 +`define asm_acia_putchar_a 16'hFEBE +`define asm_acia_status 16'h0003 +`define asm_apa_wait 16'hFEC0 +`define asm_apx_end 16'hFF93 +`define asm_apx_loop 16'hFF8A +`define asm_boot_firq_vector 16'hFFF6 +`define asm_boot_irq_vector 16'hFFF8 +`define asm_boot_nmi_vector 16'hFFFC +`define asm_boot_reserved_vector 16'hFFF0 +`define asm_boot_reset_vector 16'hFFFE +`define asm_boot_return 16'hFE9C +`define asm_boot_sim_stop 16'hFEAA +`define asm_boot_stack 16'hFE00 +`define asm_boot_start 16'hFE00 +`define asm_boot_swi2_vector 16'hFFF4 +`define asm_boot_swi3_vector 16'hFFF2 +`define asm_boot_swi_vector 16'hFFFA +`define asm_boot_vector_table 16'hFFF0 +`define asm_call_prog_start 16'hFE96 +`define asm_getchar_a 16'hFED7 +`define asm_gethex_byte 16'hFFB8 +`define asm_gethex_digit 16'hFFA8 +`define asm_ghd_0to9 16'hFFB1 +`define asm_ghd_AtoF 16'hFFB5 +`define asm_ghd_done 16'hFFB7 +`define asm_input_prompt 16'hFF68 +`define asm_LF 16'h000A +`define asm_load_bad 16'hFF2E +`define asm_load_good0 16'hFF3E +`define asm_load_good1 16'hFF50 +`define asm_main_loop 16'hFE16 +`define asm_output_port 16'h0000 +`define asm_pca_not_lf 16'hFEBE +`define asm_pca_sim_out 16'hFECD +`define asm_print_x 16'hFF88 +`define asm_prog_start 16'h8000 +`define asm_prompt 16'hFF0E +`define asm_putchar_a 16'hFEAF +`define asm_puthex_16bit 16'hFFD2 +`define asm_puthex_byte 16'hFFC5 +`define asm_puthex_digit 16'hFF95 +`define asm_puthex_digit1 16'hFFA1 +`define asm_puthex_digit2 16'hFFA3 +`define asm_return_msg 16'hFF6C +`define asm_s1_record 16'hFE2A +`define asm_s1r_checkit 16'hFE5C +`define asm_s1r_loop 16'hFE4E +`define asm_s9_record 16'hFE6D +`define asm_s9r_good_load 16'hFE7A +`define asm_sim_detect 16'hFFED +`define asm_sim_putchar_buf 16'hFFEF +`define asm_sim_putchar_en 16'hFFEE +`define asm_swi_handler 16'hFEE2 +`define asm_swi_handler_1 16'hFF02 +`define asm_swi_handler_2 16'hFEF6 +`define asm_swi_handler_3 16'hFEEC +`define asm_swi_handler_exit 16'hFF0B +`define asm_uca_done 16'hFFE5 +`define asm_ucase_a 16'hFFDB diff --git a/turbo9team_turbo9/tb/tb_dv_6809_model.v b/turbo9team_turbo9/tb/tb_dv_6809_model.v new file mode 100644 index 0000000000000000000000000000000000000000..463f2c8afd4172eb5d19182f3ae208ebf1dddc17 --- /dev/null +++ b/turbo9team_turbo9/tb/tb_dv_6809_model.v @@ -0,0 +1,2494 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testbench: 6809 behavioral model +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// 6809 Behavioral Model +///////////////////////////////////////////////////////////////////////////// + +module tb_dv_6809_model +#( + parameter MEM_ADDR_WIDTH = 12, + parameter BREAK_COM_DIR_OP = 0 +) +( + // Inputs: Clock & Reset + input RST_N_I, + input CLK_I, + + // Inputs + input QUIET_I, + input FAST_CLK_I, + + // Outputs + output E_CLK_O, + output Q_CLK_O, + output ERROR_O, + output [ 7:0] OUTPUT_PORT_O, + input [31:0] CYCLE_CNT_O +); + + tb_dv_memory + #( + MEM_ADDR_WIDTH + ) + I_tb_dv_6809_memory (); + + reg [7:0] output_port; + integer cycle_cnt; + + wire quiet = QUIET_I; + + //////////////////////////////////////////////////////////////////////////// + // 6809 Model Signals + //////////////////////////////////////////////////////////////////////////// + + ///////////////////////////////////////////// Programmer Model Regs + // + reg [15:0] d_model; + reg [15:0] x_model; + reg [15:0] y_model; + reg [15:0] u_model; + reg [15:0] s_model; + reg [15:0] pc_model; + reg [ 7:0] dp_model; + reg [ 7:0] cc_model; + + `define d d_model + `define a d_model[15:8] + `define b d_model[ 7:0] + + `define x x_model + `define y y_model + `define u u_model + `define s s_model + `define pc pc_model + `define dp dp_model + + `define cc cc_model + `define cc_e cc_model[7] + `define cc_f cc_model[6] + `define cc_h cc_model[5] + `define cc_i cc_model[4] + `define cc_n cc_model[3] + `define cc_z cc_model[2] + `define cc_v cc_model[1] + `define cc_c cc_model[0] + + // For viewing in simulation + wire [7:0] a_model = `a; + wire [7:0] b_model = `b; + wire cc_e_model = `cc_e; + wire cc_f_model = `cc_f; + wire cc_h_model = `cc_h; + wire cc_i_model = `cc_i; + wire cc_n_model = `cc_n; + wire cc_z_model = `cc_z; + wire cc_v_model = `cc_v; + wire cc_c_model = `cc_c; + + ///////////////////////////////////////////// Other Model Regs & Signals + // + reg exe_state; + reg reset_meta; + reg reset_sync; + wire e_clk_model; + reg e_clk_i; + wire q_clk_model; + reg q_clk_i; + reg error_model; + reg [ 7:0] prebyte_model; + reg [ 7:0] opcode_model; + reg [ 7:0] postbyte_model; + reg [15:0] ea_model; + + `define e_clk e_clk_model + `define q_clk q_clk_model + `define error error_model + `define prebyte prebyte_model + `define opcode opcode_model + `define postbyte postbyte_model + `define ea ea_model + `define memory I_tb_dv_6809_memory.memory + + //////////////////////////////////////////////////////////////////////////// + // Quaduature Clock Generation + //////////////////////////////////////////////////////////////////////////// + initial begin + e_clk_i = 1'b0; + q_clk_i = 1'b0; + forever begin + @ (negedge CLK_I) q_clk_i = ~q_clk_i; + @ (negedge CLK_I) e_clk_i = ~e_clk_i; + end + end + + assign `q_clk = (FAST_CLK_I) ? ~CLK_I : q_clk_i; + assign `e_clk = (FAST_CLK_I) ? CLK_I : e_clk_i; + + //////////////////////////////////////////////////////////////////////////// + // Reset Synchronizer (async set, sync release) + //////////////////////////////////////////////////////////////////////////// + always @(negedge RST_N_I or negedge `e_clk) + begin + if (~RST_N_I) begin + reset_meta <= 1'b1; + reset_sync <= 1'b1; + end else begin + if (~exe_state) begin + reset_meta <= 1'b0; + reset_sync <= reset_meta; + end + end + end + + //////////////////////////////////////////////////////////////////////////// + // Execute Model + //////////////////////////////////////////////////////////////////////////// + initial begin + forever begin + exe_state = 1'b0; + // + wait (reset_sync == 1'b1); + `error = 1'b0; + output_port = 8'h00; + // + @ (negedge reset_sync) exe_state = 1'b1; + // + if (~quiet) $display("[TB: tb_dv_6809_model] Reset released synchonized to falling edge of E clock"); + execute6809; + // + end + end + + //////////////////////////////////////////////////////////////////////////// + // 6809 Model Execution Task + //////////////////////////////////////////////////////////////////////////// + task execute6809; + + reg tmp1; + reg [ 7:0] tmp8; + reg [15:0] tmp16; + + reg cin; + reg cout; + reg hout; + + reg [ 7:0] data8_a; + reg [ 7:0] data8_b; + reg [ 7:0] data8_y; + + reg [15:0] data16_a; + reg [15:0] data16_b; + reg [15:0] data16_y; + + reg [31:0] data32_a; + reg [31:0] data32_b; + reg [31:0] data32_y; + + reg [ 7:0] instruction_reg; + reg [ 7:0] instruction_reg2; + + integer bus_cycles; + + begin + + + // Reset the 6809 model + `d = 16'h0; + `x = 16'h0; + `y = 16'h0; + `u = 16'h0; + `s = 16'h0; + `pc = 16'h0; + `dp = 8'h0; + `cc = 8'h0; + + `cc_i = 1'b1; + `cc_f = 1'b1; + + `pc = read_mem16(16'hfffe); // Read the reset vector + + if (~quiet) $display("[TB: tb_dv_6809_model] @ 0x%4x : Loading from reset vector, PC = 0x%4x", 16'hfffe, `pc); + + bus_cycles = 6; // reset syncho give 2 cycles so total is 8 + e_clock_cycles(bus_cycles); + + while (~reset_sync & ~`error) begin // While not in reset and no error + + bus_cycles = 0; + + `ea = 16'hxxxx; + `prebyte = 8'hxx; + `postbyte = 8'hxx; + + if (~quiet) $write("[TB: tb_dv_6809_model] @ 0x%4x : Executing ", `pc); + `opcode = read_mem8(`pc++); + if (~quiet) print_opcode_info(`prebyte, `opcode, 1'b1); + + instruction_reg = `opcode; + + case (instruction_reg) + + ///////////////////////////////////////////// NEG + 8'h00, // NEG (dir) + 8'h40, // NEGA (inh) + 8'h50, // NEGB (inh) + 8'h60, // NEG (idx) + 8'h70: // NEG (ext) + begin + bus_cycles = 6; //dir + data8_a = 8'h00; + load_mm(`ea, data8_b, bus_cycles); + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Spec H Undefined, Turbo9 H not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = (data8_b == 8'h80); + `cc_c = cout; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// COM + 8'h03, // COM (dir) + 8'h43, // COMA (inh) + 8'h53, // COMB (inh) + 8'h63, // COM (idx) + 8'h73: // COM (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + if (BREAK_COM_DIR_OP) begin + data8_y = data8_b; + end else begin + data8_y = ~data8_b; + end + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + `cc_c = 1'b1; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// LSR + 8'h04, // LSR (dir) + 8'h44, // LSRA (inh) + 8'h54, // LSRB (inh) + 8'h64, // LSR (idx) + 8'h74: // LSR (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = {1'b0, data8_b[7:1]}; + //`cc_h = 1'b0; // Not affected + `cc_n = 1'b0; + `cc_z = (data8_y == 8'h00); + //`cc_v = 1'b0; // Not affected + `cc_c = data8_b[0]; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// ROR + 8'h06, // ROR (dir) + 8'h46, // RORA (inh) + 8'h56, // RORB (inh) + 8'h66, // ROR (idx) + 8'h76: // ROR (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = {`cc_c, data8_b[7:1]}; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + //`cc_v = 1'b0; // Not affected + `cc_c = data8_b[0]; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// ASR + 8'h07, // ASR (dir) + 8'h47, // ASRA (inh) + 8'h57, // ASRB (inh) + 8'h67, // ASR (idx) + 8'h77: // ASR (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = {data8_b[7], data8_b[7:1]}; + //`cc_h = 1'b0; // INFO: Spec H Undefined, Turbo9 H not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + //`cc_v = 1'b0; + `cc_c = data8_b[0]; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// ASL + 8'h08, // ASL (dir) + 8'h48, // ASLA (inh) + 8'h58, // ASLB (inh) + 8'h68, // ASL (idx) + 8'h78: // ASL (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = {data8_b[6:0], 1'b0}; + //`cc_h = 1'b0; // INFO: Spec H Undefined, Turbo9 H not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = data8_b[7] ^ data8_b[6]; + `cc_c = data8_b[7]; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// ROL + 8'h09, // ROL (dir) + 8'h49, // ROLA (inh) + 8'h59, // ROLB (inh) + 8'h69, // ROL (idx) + 8'h79: // ROL (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = {data8_b[6:0], `cc_c}; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = data8_b[7] ^ data8_b[6]; + `cc_c = data8_b[7]; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// DEC + 8'h0A, // DEC (dir) + 8'h4A, // DECA (inh) + 8'h5A, // DECB (inh) + 8'h6A, // DEC (idx) + 8'h7A: // DEC (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_a, bus_cycles); + data8_b = 8'h01; + data8_y = data8_a - data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = (data8_a == 8'h80); + //`cc_c = 1'b0; // Not affected + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// INC + 8'h0C, // INC (dir) + 8'h4C, // INCA (inh) + 8'h5C, // INCB (inh) + 8'h6C, // INC (idx) + 8'h7C: // INC (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_a, bus_cycles); + data8_b = 8'h01; + data8_y = data8_a + data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = (data8_a == 8'h7F); + //`cc_c = 1'b0; // Not affected + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// TST + 8'h0D, // TST (dir) + 8'h4D, // TSTA (inh) + 8'h5D, // TSTB (inh) + 8'h6D, // TST (idx) + 8'h7D: // TST (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + //store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// JMP + 8'h0E, // JMP (dir) + 8'h6E, // JMP (idx) + 8'h7E: // JMP (ext) + begin + bus_cycles = 3; //dir + calc_ea16(`ea, bus_cycles); + `pc = `ea; + end + + ///////////////////////////////////////////// CLR + 8'h0F, // CLR (dir) + 8'h4F, // CLRA (inh) + 8'h5F, // CLRB (inh) + 8'h6F, // CLR (idx) + 8'h7F: // CLR (ext) + begin + bus_cycles = 6; //dir + load_mm(`ea, data8_b, bus_cycles); + data8_y = 8'h00; + //`cc_h = 1'b0; // Not affected + `cc_n = 1'b0; + `cc_z = 1'b1; + `cc_v = 1'b0; + `cc_c = 1'b0; + store_mm(`ea, data8_y); + end + + ///////////////////////////////////////////// Page 2 + 8'h10 : begin + // + `prebyte = `opcode; + `opcode = read_mem8(`pc++); + instruction_reg2 = `opcode; + if (~quiet) print_opcode_info(`prebyte, `opcode, 1'b1); + // + case (instruction_reg2) + + ///////////////////////////////////////////// EDIVS + // + // 32 by 16 signed integer divide + // + // Y = Y:D / X + // Y unchanged when div_by_0 or overflow + // + // D = remainder + // D unchanged when div_by_0 or overflow + // + // N = MSB of quotient + // MSB of unchanged Y when div_by_0 or overflow (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 1 if unchanged Y = 0x0000, when div_by_0 or overflow (HC12 undefined) + // + // V = 1 if quotient > 0x7FFF (+32767) or 0x8000 (-32768) + // 0 when div_by_0 (HC12 undefined) + // + // C = 1 if divisor = 0x0000 + // + 8'h15 : // EDIVS (inh) + begin + bus_cycles = 25; + data32_a = $signed({`y,`d}); + data32_b = $signed(`x); + data32_y = $signed(data32_a) / $signed(data32_b); + `cc_c = (data32_b == 32'h0000); + `cc_v = ($signed(data32_y) > 32767) | ($signed(data32_y) < -32768) | `cc_c; + // + if (~(`cc_c || `cc_v)) begin // if div-by-zero or overflow + `y = data32_y[15:0]; + data32_y = $signed(data32_a) % $signed(data32_b); + `d = data32_y[15:0]; + end + `cc_n = `y[15]; + `cc_z = (`y == 16'h0000); + end + + ///////////////////////////////////////////// IDIVS + // + // 16 by 16 signed integer divide + // + // X = D / X + // X unchanged when div_by_0 or overflow + // + // D = remainder + // D unchanged when div_by_0 or overflow + // + // N = MSB of quotient + // MSB of unchanged X when div_by_0 or overflow (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 1 if unchanged X = 0x0000, when div_by_0 or overflow (HC12 undefined) + // + // V = 1 if quotient > 0x7FFF (+32767) or 0x8000 (-32768) + // 1 when div_by_0 (HC12 undefined) + // + // C = 1 if divisor = 0x0000 + // + 8'h18 : // IDIVS (inh) + begin + bus_cycles = 25; + data32_a = $signed(`d); + data32_b = $signed(`x); + data32_y = $signed(data32_a) / $signed(data32_b); + `cc_c = (data32_b == 32'h0000); + `cc_v = (($signed(data32_y) > 32767) | ($signed(data32_y) < -32768) | `cc_c); + // + if (~(`cc_c || `cc_v)) begin // if div-by-zero or overflow + `x = data32_y[15:0]; + data32_y = $signed(data32_a) % $signed(data32_b); + `d = data32_y[15:0]; + end + `cc_n = `x[15]; + `cc_z = (`x == 16'h0000); + end + + ///////////////////////////////////////////// EDIV + // + // 32 by 16 unsigned integer divide + // + // Y = Y:D / X + // Y input when div_by_0 or overflow + // + // D = remainder + // D input when div_by_0 or overflow + // + // N = MSB of quotient + // MSB of Y input when div_by_0 or overflow (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 1 if Y input = 0x0000, when div_by_0 or overflow (HC12 undefined) + // + // V = 1 if quotient > 0xFFFF + // 1 when div_by_0 (HC12 undefined) + // + // C = 1 if divisor = 0x0000 + // + 8'h14 : // EDIV (inh) + begin + bus_cycles = 25; + data32_a = {`y,`d}; + data32_b = {16'h0000, `x}; + data32_y = $unsigned(data32_a) / $unsigned(data32_b); + `cc_c = (data32_b[15:0] == 16'h0000); + if (`cc_c) begin + `cc_v = 1'b1; // if div-by-zero set overflow + end else begin + `cc_v = (data32_y[31:16] != 16'h0000); + end + if (`cc_v | `cc_c) begin + `cc_n = `y[15]; + `cc_z = (`y == 16'h0000); + end else begin // if no overflow or divide-by-zero + `cc_n = data32_y[15]; + `cc_z = (data32_y[15:0] == 16'h0000); + `y = data32_y[15:0]; + data32_y = $unsigned(data32_a) % $unsigned(data32_b); + `d = data32_y[15:0]; + end + end + + ///////////////////////////////////////////// FDIV + // + // 16 by 16 unsigned fractional divide + // 0.16 = 0.16 / 16.0 + // + // X = D / X + // 0xFFFF when div_by_0 + // + // D = remainder + // D input when div_by_0 (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 0 when div_by_0 + // + // V = 1 if X <= D + // + // C = 1 if divisor = 0x0000 + // + 8'h19 : // FDIV (inh) + begin + bus_cycles = 25; + data32_a = {`d, 16'h0000}; + data32_b = {16'h0000, `x}; + data32_y = $unsigned(data32_a) / $unsigned(data32_b); + //`cc_h = 1'b0; + //`cc_n = 1'b0; + `cc_c = (data32_b[15:0] == 16'h0000); // 1 if X = 0 + `cc_v = (data32_b[15:0] <= data32_a[31:16]); // 1 if X <= D + if (`cc_c || `cc_v) begin // if div-by-zero or overflow + `cc_z = 1'b0; + `x = 16'hFFFF; + //`d = unchanged + end else begin + `cc_z = (data32_y[15:0] == 16'h0000); + `x = data32_y[15:0]; + data32_y = $unsigned(data32_a) % $unsigned(data32_b); + `d = data32_y[15:0]; + end + end + + ///////////////////////////////////////////// LBxx (rel) + 8'h20, // LBRA // Hidden + 8'h21, // LBRN + 8'h22, // LBHI + 8'h23, // LBLS + 8'h24, // LBHS, LBCC + 8'h25, // LBLO, LBCS + 8'h26, // LBNE + 8'h27, // LBEQ + 8'h28, // LBVC + 8'h29, // LBVS + 8'h2A, // LBPL + 8'h2B, // LBMI + 8'h2C, // LBGE + 8'h2D, // LBLT + 8'h2E, // LBGT + 8'h2F: // LBLE + begin + rel16_ea(`ea); + if (eval_branch(`opcode[3:0])) begin + `pc = `ea; + bus_cycles = 6; + end else begin + bus_cycles = 5; + end + end + + ///////////////////////////////////////////// CMPD + 8'h83, // CMPD (imm) + 8'h93, // CMPD (dir) + 8'hA3, // CMPD (idx) + 8'hB3: // CMPD (ext) + begin + bus_cycles = 7; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `d; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + end + + ///////////////////////////////////////////// CMPY + 8'h8C, // CMPY (imm) + 8'h9C, // CMPY (dir) + 8'hAC, // CMPY (idx) + 8'hBC: // CMPY (ext) + begin + bus_cycles = 7; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `y; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + end + + ///////////////////////////////////////////// LDY + 8'h8E, // LDY (imm) + 8'h9E, // LDY (dir) + 8'hAE, // LDY (idx) + 8'hBE: // LDY (ext) + begin + bus_cycles = 6; // dir + load_op16(`ea,data16_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + // `cc_c = 1'b0; // Not affected + `y = data16_y; + end + + ///////////////////////////////////////////// STY + 8'h9F, // STY (dir) + 8'hAF, // STY (idx) + 8'hBF: // STY (ext) + begin + bus_cycles = 6; // dir + calc_ea16(`ea, bus_cycles); + data16_y = `y; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem16(`ea, data16_y); + end + + ///////////////////////////////////////////// LDS + 8'hCE, // LDS (imm) + 8'hDE, // LDS (dir) + 8'hEE, // LDS (idx) + 8'hFE: // LDS (ext) + begin + bus_cycles = 6; // dir + load_op16(`ea,data16_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + // `cc_c = 1'b0; // Not affected + `s = data16_y; + end + + ///////////////////////////////////////////// STS + 8'hDF, // STS (dir) + 8'hEF, // STS (idx) + 8'hFF: // STS (ext) + begin + bus_cycles = 6; // dir + calc_ea16(`ea, bus_cycles); + data16_y = `s; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem16(`ea, data16_y); + end + + default : begin // Unimplemented Page 2 Opcode + $display("[TB: tb_dv_6809_model] ERROR: Unimplemented Page 2 opcode!"); + hasta_la_vista_baby; + end + + endcase // + end + + ///////////////////////////////////////////// Page 3 + 8'h11 : begin + // + `prebyte = `opcode; + `opcode = read_mem8(`pc++); + instruction_reg2 = `opcode; + if (~quiet) print_opcode_info(`prebyte, `opcode, 1'b1); + // + case (instruction_reg2) + + ///////////////////////////////////////////// CMPU + 8'h83, // CMPU (imm) + 8'h93, // CMPU (dir) + 8'hA3, // CMPU (idx) + 8'hB3: // CMPU (ext) + begin + bus_cycles = 7; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `u; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + end + + ///////////////////////////////////////////// CMPS + 8'h8C, // CMPS (imm) + 8'h9C, // CMPS (dir) + 8'hAC, // CMPS (idx) + 8'hBC: // CMPS (ext) + begin + bus_cycles = 7; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `s; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + end + + default : begin // Unimplemented Page 3 Opcode + $display("[TB: tb_dv_6809_model] ERROR: Unimplemented Page 3 opcode!"); + hasta_la_vista_baby; + end + + endcase // + end + + ///////////////////////////////////////////// NOP (inh) + 8'h12 : begin + bus_cycles = 2; + end + + ///////////////////////////////////////////// SYNC (inh) FIXME + 8'h13 : begin + $display("[TB: tb_dv_6809_model] ERROR: Unimplemented SYNC opcode!"); + hasta_la_vista_baby; + end + + ///////////////////////////////////////////// EMUL + // + // 16 by 16 unsigned integer multiply + // + // Y:D = D * Y + // + // N = MSB of product + // + // Z = 1 if product = 0x0000_0000 + // + // C = bit 15 of product + // + 8'h14 : // EMUL (inh) + begin + bus_cycles = 19; + data16_a = `d; + data16_b = `y; + data32_y = $unsigned(data16_a) * $unsigned(data16_b); + //`cc_h = 1'b0; + `cc_n = data32_y[31]; + `cc_z = (data32_y == 32'h00000000); + //`cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = data32_y[15]; + `y = data32_y[31:16]; + `d = data32_y[15:0]; + end + + ///////////////////////////////////////////// EMULS + // + // 16 by 16 signed integer multiply + // + // Y:D = D * Y + // + // N = MSB of product + // + // Z = 1 if product = 0x0000_0000 + // + // C = bit 15 of product + // + 8'h15 : // EMULS (inh) + begin + bus_cycles = 19; + data16_a = `d; + data16_b = `y; + data32_y = $signed(data16_a) * $signed(data16_b); + //`cc_h = 1'b0; + `cc_n = data32_y[31]; + `cc_z = (data32_y == 32'h00000000); + //`cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = data32_y[15]; + `y = data32_y[31:16]; + `d = data32_y[15:0]; + end + + ///////////////////////////////////////////// LBRA (rel) + 8'h16 : // LBRA + begin + rel16_ea(`ea); + `pc = `ea; + bus_cycles = 5; + end + + ///////////////////////////////////////////// LBSR (rel) + 8'h17 : begin + rel16_ea(`ea); + write_mem8(--`s,`pc[ 7:0]); + write_mem8(--`s,`pc[15:8]); + `pc = `ea; + bus_cycles = 9; + end + + ///////////////////////////////////////////// IDIV + // + // 16 by 16 unsigned integer divide + // + // X = D / X + // 0xFFFF when div_by_0 + // + // D = remainder + // D input when div_by_0 (HC12 undefined) + // + // Z = 1 if quotient = 0x0000 + // 0 when div_by_0 + // + // V = 0 + // + // C = 1 if divisor = 0x0000 + // + 8'h18 : // IDIV (inh) + begin + bus_cycles = 19; + data16_a = `d; + data16_b = `x; + data16_y = $unsigned(data16_a) / $unsigned(data16_b); + //`cc_h = 1'b0; + //`cc_n = 1'b0; + `cc_c = (data16_b == 16'h0000); + if (`cc_c) begin // if div-by-zero + `cc_z = 1'b0; + `cc_v = 1'b0; + `x = 16'hFFFF; + //`d = + end else begin + `cc_z = (data16_y == 16'h0000); + `cc_v = 1'b0; + `x = data16_y; + `d = $unsigned(data16_a) % $unsigned(data16_b); + end + end + + ///////////////////////////////////////////// DAA (inh) + 8'h19 : begin + // + data8_a = `a; + // + if ((data8_a[3:0] > 4'h9) || `cc_h) + data8_b[3:0] = 4'h6; + else + data8_b[3:0] = 4'h0; + // + if (((data8_a[7:4] > 4'h9) || `cc_c) || ((data8_a[7:4] > 4'h8) && (data8_a[3:0] > 4'h9))) + data8_b[7:4] = 4'h6; + else + data8_b[7:4] = 4'h0; + // + {tmp1, data8_y} = {1'b0, data8_a} + {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + //`cc_v = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_c |= tmp1; + `a = data8_y; + bus_cycles = 2; + end + + ///////////////////////////////////////////// ORCC (imm) + 8'h1A : begin + imm8_ea(`ea, bus_cycles); + bus_cycles = 3; // set + data8_a = read_mem8(`ea); + `cc |= data8_a; + end + + ///////////////////////////////////////////// ANDCC (imm) + 8'h1C : begin + imm8_ea(`ea, bus_cycles); + bus_cycles = 3; // set + data8_a = read_mem8(`ea); + `cc &= data8_a; + end + + ///////////////////////////////////////////// SEX (inh) + 8'h1D : begin + data8_b = `b; + data16_y = {{8{data8_b[7]}}, data8_b}; + `d = data16_y; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; // INFO Prog Man says V unaffected, datasheet says v=0 + //`cc_c = 1'b0; // Not affected + bus_cycles = 2; + end + + ///////////////////////////////////////////// EXG (inh) + 8'h1E : begin + `ea = `pc++; + tmp8 = read_mem8(`ea); + // + data16_a = read_reg(tmp8[7:4]); + data16_b = read_reg(tmp8[3:0]); + write_reg(tmp8[7:4],data16_b); + write_reg(tmp8[3:0],data16_a); + // + bus_cycles = 8; + end + + ///////////////////////////////////////////// TFR (inh) + 8'h1F : begin + `ea = `pc++; + tmp8 = read_mem8(`ea); + // + data16_a = read_reg(tmp8[7:4]); + write_reg(tmp8[3:0],data16_a); + // + bus_cycles = 6; + end + + ///////////////////////////////////////////// Bxx (rel) + 8'h20, // BRA + 8'h21, // BRN + 8'h22, // BHI + 8'h23, // BLS + 8'h24, // BHS, BCC + 8'h25, // BLO, BCS + 8'h26, // BNE + 8'h27, // BEQ + 8'h28, // BVC + 8'h29, // BVS + 8'h2A, // BPL + 8'h2B, // BMI + 8'h2C, // BGE + 8'h2D, // BLT + 8'h2E, // BGT + 8'h2F: // BLE + begin + rel8_ea(`ea); + if (eval_branch(`opcode[3:0])) begin + `pc = `ea; + bus_cycles = 3; + end else begin + bus_cycles = 3; + end + end + + ///////////////////////////////////////////// LEAX + 8'h30 : // LEAX (idx) + begin + bus_cycles = 4; + idx_ea(`ea, bus_cycles); + data16_y = `ea; + //`cc_h = 1'b0; // Not affected + //`cc_n = 1'b0; // Not affected + `cc_z = (data16_y == 16'h0000); + //`cc_v = 1'b0; // Not affected + //`cc_c = 1'b0; // Not affected + `x = data16_y; + end + + ///////////////////////////////////////////// LEAY + 8'h31 : // LEAY (idx) + begin + bus_cycles = 4; + idx_ea(`ea, bus_cycles); + data16_y = `ea; + //`cc_h = 1'b0; // Not affected + //`cc_n = 1'b0; // Not affected + `cc_z = (data16_y == 16'h0000); + //`cc_v = 1'b0; // Not affected + //`cc_c = 1'b0; // Not affected + `y = data16_y; + end + + ///////////////////////////////////////////// LEAS + 8'h32 : // LEAS (idx) + begin + bus_cycles = 4; + idx_ea(`ea, bus_cycles); + data16_y = `ea; + //`cc_h = 1'b0; // Not affected + //`cc_n = 1'b0; // Not affected + //`cc_z = 1'b0; // Not affected + //`cc_v = 1'b0; // Not affected + //`cc_c = 1'b0; // Not affected + `s = data16_y; + end + + ///////////////////////////////////////////// LEAU + 8'h33 : // LEAU (idx) + begin + bus_cycles = 4; + idx_ea(`ea, bus_cycles); + data16_y = `ea; + //`cc_h = 1'b0; // Not affected + //`cc_n = 1'b0; // Not affected + //`cc_z = 1'b0; // Not affected + //`cc_v = 1'b0; // Not affected + //`cc_c = 1'b0; // Not affected + `u = data16_y; + end + + ///////////////////////////////////////////// PSHS (stack) + 8'h34 : begin + `postbyte = read_mem8(`pc++); + push_regs(`postbyte, `s, `u, tmp16, bus_cycles); + `s = tmp16; + bus_cycles += 5; + end + + ///////////////////////////////////////////// PULS (stack) + 8'h35 : begin + `postbyte = read_mem8(`pc++); + pull_regs(`postbyte, `s, `u, tmp16, bus_cycles); + `s = tmp16; + bus_cycles += 5; + end + + ///////////////////////////////////////////// PSHU (stack) + 8'h36 : begin + `postbyte = read_mem8(`pc++); + push_regs(`postbyte, `u, `s, tmp16, bus_cycles); + `u = tmp16; + bus_cycles += 5; + end + + ///////////////////////////////////////////// PULU (stack) + 8'h37 : begin + `postbyte = read_mem8(`pc++); + pull_regs(`postbyte, `u, `s, tmp16, bus_cycles); + `u = tmp16; + bus_cycles += 5; + end + + ///////////////////////////////////////////// RTS (stack) + 8'h39 : begin + `pc[15:8] = read_mem8(`s++); + `pc[ 7:0] = read_mem8(`s++); + bus_cycles = 5; + end + + ///////////////////////////////////////////// ABX + 8'h3A : // ABX (inh) + begin + bus_cycles = 11; + data16_a = `x; + data16_b = {8'h00,`b}; + data16_y = data16_a + data16_b; + //`cc_h = 1'b0; + //`cc_n = data8_y[7]; + //`cc_z = (data16_y == 16'h0000); + //`cc_v = sub_vout8(data8_y, data8_a, data8_b); + //`cc_c = data16_y[7]; + `x = data16_y; + end + + ///////////////////////////////////////////// RTI (stack) + 8'h3B : begin + pull_regs(8'h01, `s, `u, tmp16, bus_cycles); + `s = tmp16; + if (`cc_e) begin + pull_regs(8'hFE, `s, `u, tmp16, bus_cycles); + `s = tmp16; + bus_cycles = 15; + end else begin + pull_regs(8'h80, `s, `u, tmp16, bus_cycles); + `s = tmp16; + bus_cycles = 6; + end + end + + ///////////////////////////////////////////// MUL + 8'h3D : // MUL (inh) + begin + bus_cycles = 11; + data8_a = `a; + data8_b = `b; + data16_y = $unsigned(data8_a) * $unsigned(data8_b); + //`cc_h = 1'b0; + //`cc_n = data8_y[7]; + `cc_z = (data16_y == 16'h0000); + //`cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = data16_y[7]; + `d = data16_y; + end + + ///////////////////////////////////////////// SWI (stack) + 8'h3F : begin + `cc_e = 1'b1; + push_regs(8'hFF, `s, `u, tmp16, bus_cycles); + `s = tmp16; + `cc_i = 1'b1; + `cc_f = 1'b1; + `pc = read_mem16(16'hFFFA); + bus_cycles = 19; + end + + ///////////////////////////////////////////// SUBA + 8'h80, // SUBA (imm) + 8'h90, // SUBA (dir) + 8'hA0, // SUBA (idx) + 8'hB0: // SUBA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `a = data8_y; + end + + ///////////////////////////////////////////// CMPA + 8'h81, // CMPA (imm) + 8'h91, // CMPA (dir) + 8'hA1, // CMPA (idx) + 8'hB1: // CMPA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + end + + ///////////////////////////////////////////// SBCA + 8'h82, // SBCA (imm) + 8'h92, // SBCA (dir) + 8'hA2, // SBCA (idx) + 8'hB2: // SBCA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + cin = `cc_c; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b} - {8'h00, cin}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `a = data8_y; + end + + ///////////////////////////////////////////// SUBD + 8'h83, // SUBD (imm) + 8'h93, // SUBD (dir) + 8'hA3, // SUBD (idx) + 8'hB3: // SUBD (ext) + begin + bus_cycles = 6; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `d; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + `d = data16_y; + end + + ///////////////////////////////////////////// ANDA + 8'h84, // ANDA (imm) + 8'h94, // ANDA (dir) + 8'hA4, // ANDA (idx) + 8'hB4: // ANDA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + data8_y = data8_a & data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `a = data8_y; + end + + ///////////////////////////////////////////// BITA + 8'h85, // BITA (imm) + 8'h95, // BITA (dir) + 8'hA5, // BITA (idx) + 8'hB5: // BITA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + data8_y = data8_a & data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + end + + ///////////////////////////////////////////// LDA + 8'h86, // LDA (imm) + 8'h96, // LDA (dir) + 8'hA6, // LDA (idx) + 8'hB6: // LDA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `a = data8_y; + end + + ///////////////////////////////////////////// STA + 8'h97, // STA (dir) + 8'hA7, // STA (idx) + 8'hB7: // STA (ext) + begin + bus_cycles = 4; // dir + calc_ea8(`ea, bus_cycles); + data8_y = `a; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem8(`ea, data8_y); + end + + ///////////////////////////////////////////// EORA + 8'h88, // EORA (imm) + 8'h98, // EORA (dir) + 8'hA8, // EORA (idx) + 8'hB8: // EORA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + data8_y = data8_a ^ data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `a = data8_y; + end + + ///////////////////////////////////////////// ADCA + 8'h89, // ADCA (imm) + 8'h99, // ADCA (dir) + 8'hA9, // ADCA (idx) + 8'hB9: // ADCA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + cin = `cc_c; + {hout, data8_y[3:0]} = {1'b0, data8_a[3:0]} + {1'b0, data8_b[3:0]} + {4'h0, cin}; + {cout, data8_y} = {1'b0, data8_a} + {1'b0, data8_b} + {8'h00, cin}; + `cc_h = hout; + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = add_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `a = data8_y; + end + + ///////////////////////////////////////////// ORA + 8'h8A, // ORA (imm) + 8'h9A, // ORA (dir) + 8'hAA, // ORA (idx) + 8'hBA: // ORA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + data8_y = data8_a | data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `a = data8_y; + end + + ///////////////////////////////////////////// ADDA + 8'h8B, // ADDA (imm) + 8'h9B, // ADDA (dir) + 8'hAB, // ADDA (idx) + 8'hBB: // ADDA (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `a; + {hout, data8_y[3:0]} = {1'b0, data8_a[3:0]} + {1'b0, data8_b[3:0]}; + {cout, data8_y} = {1'b0, data8_a} + {1'b0, data8_b}; + `cc_h = hout; + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = add_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `a = data8_y; + end + + ///////////////////////////////////////////// CMPX + 8'h8C, // CMPX (imm) + 8'h9C, // CMPX (dir) + 8'hAC, // CMPX (idx) + 8'hBC: // CMPX (ext) + begin + bus_cycles = 6; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `x; + {cout, data16_y} = {1'b0, data16_a} - {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = sub_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + end + + + ///////////////////////////////////////////// BSR + 8'h8D: // BSR (rel) + begin + rel8_ea(`ea); + write_mem8(--`s,`pc[ 7:0]); + write_mem8(--`s,`pc[15:8]); + `pc = `ea; + bus_cycles = 7; + end + + ///////////////////////////////////////////// JSR + 8'h9D, // JSR (dir) + 8'hAD, // JSR (idx) + 8'hBD: // JSR (ext) + begin + bus_cycles = 7; //dir + calc_ea16(`ea, bus_cycles); + write_mem8(--`s,`pc[ 7:0]); + write_mem8(--`s,`pc[15:8]); + `pc = `ea; + end + + ///////////////////////////////////////////// LDX + 8'h8E, // LDX (imm) + 8'h9E, // LDX (dir) + 8'hAE, // LDX (idx) + 8'hBE: // LDX (ext) + begin + bus_cycles = 5; // dir + load_op16(`ea,data16_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + // `cc_c = 1'b0; // Not affected + `x = data16_y; + end + + ///////////////////////////////////////////// STX + 8'h9F, // STX (dir) + 8'hAF, // STX (idx) + 8'hBF: // STX (ext) + begin + bus_cycles = 5; // dir + calc_ea16(`ea, bus_cycles); + data16_y = `x; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem16(`ea, data16_y); + end + + ///////////////////////////////////////////// SUBB + 8'hC0, // SUBB (imm) + 8'hD0, // SUBB (dir) + 8'hE0, // SUBB (idx) + 8'hF0: // SUBB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `b = data8_y; + end + + ///////////////////////////////////////////// CMPB + 8'hC1, // CMPB (imm) + 8'hD1, // CMPB (dir) + 8'hE1, // CMPB (idx) + 8'hF1: // CMPB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + end + + ///////////////////////////////////////////// SBCB + 8'hC2, // SBCB (imm) + 8'hD2, // SBCB (dir) + 8'hE2, // SBCB (idx) + 8'hF2: // SBCB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + cin = `cc_c; + {cout, data8_y} = {1'b0, data8_a} - {1'b0, data8_b} - {8'h00, cin}; + //`cc_h = 1'b0; // INFO: Undefined (Turbo9: Not affected) + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = sub_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `b = data8_y; + end + + ///////////////////////////////////////////// ADDD + 8'hC3, // ADDD (imm) + 8'hD3, // ADDD (dir) + 8'hE3, // ADDD (idx) + 8'hF3: // ADDD (ext) + begin + bus_cycles = 6; // dir + load_op16(`ea,data16_b,bus_cycles); + data16_a = `d; + {cout, data16_y} = {1'b0, data16_a} + {1'b0, data16_b}; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = add_vout16(data16_y, data16_a, data16_b); + `cc_c = cout; + `d = data16_y; + end + + ///////////////////////////////////////////// ANDB + 8'hC4, // ANDB (imm) + 8'hD4, // ANDB (dir) + 8'hE4, // ANDB (idx) + 8'hF4: // ANDB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + data8_y = data8_a & data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `b = data8_y; + end + + ///////////////////////////////////////////// BITB + 8'hC5, // BITB (imm) + 8'hD5, // BITB (dir) + 8'hE5, // BITB (idx) + 8'hF5: // BITB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + data8_y = data8_a & data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + end + + ///////////////////////////////////////////// LDB + 8'hC6, // LDB (imm) + 8'hD6, // LDB (dir) + 8'hE6, // LDB (idx) + 8'hF6: // LDB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `b = data8_y; + end + + ///////////////////////////////////////////// STB + 8'hD7, // STB (dir) + 8'hE7, // STB (idx) + 8'hF7: // STB (ext) + begin + bus_cycles = 4; // dir + calc_ea8(`ea, bus_cycles); + data8_y = `b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem8(`ea, data8_y); + end + + ///////////////////////////////////////////// EORB + 8'hC8, // EORB (imm) + 8'hD8, // EORB (dir) + 8'hE8, // EORB (idx) + 8'hF8: // EORB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + data8_y = data8_a ^ data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `b = data8_y; + end + + ///////////////////////////////////////////// ADCB + 8'hC9, // ADCB (imm) + 8'hD9, // ADCB (dir) + 8'hE9, // ADCB (idx) + 8'hF9: // ADCB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + cin = `cc_c; + {hout, data8_y[3:0]} = {1'b0, data8_a[3:0]} + {1'b0, data8_b[3:0]} + {4'h0, cin}; + {cout, data8_y} = {1'b0, data8_a} + {1'b0, data8_b} + {8'h00, cin}; + `cc_h = hout; + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = add_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `b = data8_y; + end + + ///////////////////////////////////////////// ORB + 8'hCA, // ORB (imm) + 8'hDA, // ORB (dir) + 8'hEA, // ORB (idx) + 8'hFA: // ORB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + data8_y = data8_a | data8_b; + //`cc_h = 1'b0; // Not affected + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + `b = data8_y; + end + + ///////////////////////////////////////////// ADDB + 8'hCB, // ADDB (imm) + 8'hDB, // ADDB (dir) + 8'hEB, // ADDB (idx) + 8'hFB: // ADDB (ext) + begin + bus_cycles = 4; // dir + load_op8(`ea,data8_b,bus_cycles); + data8_a = `b; + {hout, data8_y[3:0]} = {1'b0, data8_a[3:0]} + {1'b0, data8_b[3:0]}; + {cout, data8_y} = {1'b0, data8_a} + {1'b0, data8_b}; + `cc_h = hout; + `cc_n = data8_y[7]; + `cc_z = (data8_y == 8'h00); + `cc_v = add_vout8(data8_y, data8_a, data8_b); + `cc_c = cout; + `b = data8_y; + end + + ///////////////////////////////////////////// LDD + 8'hCC, // LDD (imm) + 8'hDC, // LDD (dir) + 8'hEC, // LDD (idx) + 8'hFC: // LDD (ext) + begin + bus_cycles = 5; // dir + load_op16(`ea,data16_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + // `cc_c = 1'b0; // Not affected + `d = data16_y; + end + + ///////////////////////////////////////////// STD + 8'hDD, // STD (dir) + 8'hED, // STD (idx) + 8'hFD: // STD (ext) + begin + bus_cycles = 5; // dir + calc_ea16(`ea, bus_cycles); + data16_y = `d; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem16(`ea, data16_y); + end + + ///////////////////////////////////////////// LDU + 8'hCE, // LDU (imm) + 8'hDE, // LDU (dir) + 8'hEE, // LDU (idx) + 8'hFE: // LDU (ext) + begin + bus_cycles = 5; // dir + load_op16(`ea,data16_y,bus_cycles); + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + // `cc_c = 1'b0; // Not affected + `u = data16_y; + end + + ///////////////////////////////////////////// STU + 8'hDF, // STU (dir) + 8'hEF, // STU (idx) + 8'hFF: // STU (ext) + begin + bus_cycles = 5; // dir + calc_ea16(`ea, bus_cycles); + data16_y = `u; + //`cc_h = 1'b0; // Not affected + `cc_n = data16_y[15]; + `cc_z = (data16_y == 16'h00); + `cc_v = 1'b0; + //`cc_c = 1'b0; // Not affected + write_mem16(`ea, data16_y); + end + + default : begin // Unimplemented Opcode + $display("[TB: tb_dv_6809_model] ERROR: Unimplemented opcode!"); + hasta_la_vista_baby; + end + + endcase + + if (bus_cycles) begin + e_clock_cycles(bus_cycles); + end else begin + $display("[TB: tb_dv_6809_model] ERROR: Bus cycles not set!"); + hasta_la_vista_baby; + end + + end + + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Read Memory (8-bit) + //////////////////////////////////////////////////////////////////////////// + function reg [7:0] read_mem8(input [15:0] addr); + begin + if (addr == 16'h0000) begin + read_mem8 = output_port; + end else if (addr == 16'h0004) begin + read_mem8 = cycle_cnt[31:24]; + end else if (addr == 16'h0005) begin + read_mem8 = cycle_cnt[23:16]; + end else if (addr == 16'h0006) begin + read_mem8 = cycle_cnt[15: 8]; + end else if (addr == 16'h0007) begin + read_mem8 = cycle_cnt[ 7: 0]; + end else if (addr[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin // Place Memory at the end of the memory map + read_mem8 = `memory[addr[(MEM_ADDR_WIDTH-1):0]]; + end else begin + read_mem8 = 8'h00; + end + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Read Memory (16-bit) + //////////////////////////////////////////////////////////////////////////// + function reg [15:0] read_mem16(input [15:0] addr); + reg [15:0] addr_inc; + begin + addr_inc = addr + 'h1; + read_mem16 = {read_mem8(addr), read_mem8(addr_inc)}; + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Write Memory (8-bit) + //////////////////////////////////////////////////////////////////////////// + task write_mem8(input [15:0] addr, input [7:0] data); + begin + if (addr == 16'h0000) begin + output_port = data; + end else if (addr[15:MEM_ADDR_WIDTH] == {(16-MEM_ADDR_WIDTH){1'b1}}) begin // Place Memory at the end of the memory map + `memory[addr[(MEM_ADDR_WIDTH-1):0]] = data; + end + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Write Memory (16-bit) + //////////////////////////////////////////////////////////////////////////// + task write_mem16(input [15:0] addr, input [15:0] data); + reg [15:0] addr_inc; + begin + addr_inc = addr + 'h1; + write_mem8(addr,data[15:8]); + write_mem8(addr_inc,data[7:0]); + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Run E clock + //////////////////////////////////////////////////////////////////////////// + task e_clock_cycles(input integer cycles); + integer i; + begin + for (i=0; i= `asm_init_stack_data) begin + case(addr) + `asm_init_cc : $display("[TB: copy_tb_mem ] Stack Initialized Reg: EFHI_NZVC = 0x%2x", `tb_mem[ptr]); + `asm_init_a : $display("[TB: copy_tb_mem ] Stack Initialized Reg: AorD[15:8] = 0x%2x", `tb_mem[ptr]); + `asm_init_b : $display("[TB: copy_tb_mem ] Stack Initialized Reg: BorD[ 7:0] = 0x%2x", `tb_mem[ptr]); + `asm_init_dp : $display("[TB: copy_tb_mem ] Stack Initialized Reg: DP = 0x%2x", `tb_mem[ptr]); + (`asm_init_x+0) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: X[15:8] = 0x%2x", `tb_mem[ptr]); + (`asm_init_x+1) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: X[ 7:0] = 0x%2x", `tb_mem[ptr]); + (`asm_init_y+0) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: Y[15:8] = 0x%2x", `tb_mem[ptr]); + (`asm_init_y+1) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: Y[ 7:0] = 0x%2x", `tb_mem[ptr]); + (`asm_init_u_s+0) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: U/S[15:8] = 0x%2x", `tb_mem[ptr]); + (`asm_init_u_s+1) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: U/S[ 7:0] = 0x%2x", `tb_mem[ptr]); + (`asm_init_pc+0) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: PC[15:8] = 0x%2x", `tb_mem[ptr]); + (`asm_init_pc+1) : $display("[TB: copy_tb_mem ] Stack Initialized Reg: PC[ 7:0] = 0x%2x", `tb_mem[ptr]); + endcase + end + end + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Compare Model and DUT memories + //////////////////////////////////////////////////////////////////////////// + + function integer mem_diff_cnt(input stop_on_err); + integer ptr; + integer diff_cnt; + reg [15:0] addr; + reg [7:0] mdc_dut_mem; + begin + ptr = 0; + diff_cnt = 0; + while ((ptr < (2**`MEM_ADDR_WIDTH)) && ((diff_cnt == 0) || ~stop_on_err) ) begin + + addr = {{(16-`MEM_ADDR_WIDTH){1'b1}},ptr[(`MEM_ADDR_WIDTH-1):0]}; + mdc_dut_mem = read_dut_mem8(ptr); + + if (addr >= `asm_init_stack_data) begin + case(addr) + `asm_init_cc : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: EFHI_NZVC = 0x%2x", mdc_dut_mem); + `asm_init_a : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: AorD[15:8] = 0x%2x", mdc_dut_mem); + `asm_init_b : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: BorD[ 7:0] = 0x%2x", mdc_dut_mem); + `asm_init_dp : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: DP = 0x%2x", mdc_dut_mem); + (`asm_init_x+0) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: X[15:8] = 0x%2x", mdc_dut_mem); + (`asm_init_x+1) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: X[ 7:0] = 0x%2x", mdc_dut_mem); + (`asm_init_y+0) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: Y[15:8] = 0x%2x", mdc_dut_mem); + (`asm_init_y+1) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: Y[ 7:0] = 0x%2x", mdc_dut_mem); + (`asm_init_u_s+0) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: U/S[15:8] = 0x%2x", mdc_dut_mem); + (`asm_init_u_s+1) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: U/S[ 7:0] = 0x%2x", mdc_dut_mem); + (`asm_init_pc+0) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: PC[15:8] = 0x%2x", mdc_dut_mem); + (`asm_init_pc+1) : $display("[TB: mem_diff_cnt ] DUT Stacked Reg: PC[ 7:0] = 0x%2x", mdc_dut_mem); + endcase + end + + + if (mdc_dut_mem !== `model_mem[ptr]) begin // must use !== to test for X !!! + + $write("[TB: mem_diff_cnt ] ERROR: Memory mismatch. "); + + case(addr) + `asm_init_cc : $write("Stacked Reg: EFHI_NZVC "); + `asm_init_a : $write("Stacked Reg: AorD[15:8] "); + `asm_init_b : $write("Stacked Reg: BorD[ 7:0] "); + `asm_init_dp : $write("Stacked Reg: DP "); + (`asm_init_x+0) : $write("Stacked Reg: X[15:8] "); + (`asm_init_x+1) : $write("Stacked Reg: X[ 7:0] "); + (`asm_init_y+0) : $write("Stacked Reg: Y[15:8] "); + (`asm_init_y+1) : $write("Stacked Reg: Y[ 7:0] "); + (`asm_init_u_s+0) : $write("Stacked Reg: U/S[15:8] "); + (`asm_init_u_s+1) : $write("Stacked Reg: U/S[ 7:0] "); + (`asm_init_pc+0) : $write("Stacked Reg: PC[15:8] "); + (`asm_init_pc+1) : $write("Stacked Reg: PC[ 7:0] "); + endcase + + $display("DUT = 0x%2x / Model = 0x%2x @ Address: 0x%4x (Memory Index %0d)", mdc_dut_mem, `model_mem[ptr], addr, ptr); + + diff_cnt++; + end + ptr++; + + end + if (diff_cnt == 0) begin + $display("[TB: mem_diff_cnt ] DUT memory matches Model memory!"); + end else begin + $display("[TB: mem_diff_cnt ] ERROR: Memory mismatch total: %0d",diff_cnt); + end + mem_diff_cnt = diff_cnt; + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Create a random block of data + //////////////////////////////////////////////////////////////////////////// + task random_block_p(input [15:0] block_start, input [15:0] block_last_byte); + integer ptr; + reg [31:0] rand32; + begin + // Initialize the data block with random data + rand32 = {$random(seed)}; // {} = unsigned + for (ptr = block_start; ptr <= block_last_byte; ptr++) begin + case (ptr[1:0]) + 2'h0 : begin + rand32 = {$random(seed)}; // {} = unsigned + write_tb_mem8(ptr, rand32[31:24]); + end + 2'h1 : write_tb_mem8(ptr, rand32[23:16]); + 2'h2 : write_tb_mem8(ptr, rand32[15: 8]); + default : write_tb_mem8(ptr, rand32[ 7: 0]); + endcase + end + $write("[TB: random_block_p ] @ 0x%4x to 0x%4x : ", block_start, block_last_byte); + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Random corner number (32-bit) + //////////////////////////////////////////////////////////////////////////// + function reg [31:0] random_corner_num32(input rcn_null); + reg [31:0] rand32; + reg [31:0] num32; + begin + rand32 = {$random(seed)}; // {} = unsigned + case (rand32[4:0]) + 5'h1F : num32 = 32'hFFFF_FFFF; + 5'h1E : num32 = 32'hFFFF_FFFE; + 5'h1D : num32 = 32'hFFFF_8001; + 5'h1C : num32 = 32'hFFFF_8000; + 5'h1B : num32 = 32'hFFFF_7FFF; + 5'h1A : num32 = 32'hFFFF_7FFE; + 5'h19 : num32 = 32'hFFFF_0001; + 5'h18 : num32 = 32'hFFFF_0000; + + 5'h17 : num32 = 32'h8000_FFFF; + 5'h16 : num32 = 32'h8000_FFFE; + 5'h15 : num32 = 32'h8000_8001; + 5'h14 : num32 = 32'h8000_8000; + 5'h13 : num32 = 32'h8000_7FFF; + 5'h12 : num32 = 32'h8000_7FFE; + 5'h11 : num32 = 32'h8000_0001; + 5'h10 : num32 = 32'h8000_0000; + + 5'h0F : num32 = 32'h7FFF_FFFF; + 5'h0E : num32 = 32'h7FFF_FFFE; + 5'h0D : num32 = 32'h7FFF_8001; + 5'h0C : num32 = 32'h7FFF_8000; + 5'h0B : num32 = 32'h7FFF_7FFF; + 5'h0A : num32 = 32'h7FFF_7FFE; + 5'h09 : num32 = 32'h7FFF_0001; + 5'h08 : num32 = 32'h7FFF_0000; + + 5'h07 : num32 = 32'h0000_FFFF; + 5'h06 : num32 = 32'h0000_FFFE; + 5'h05 : num32 = 32'h0000_8001; + 5'h04 : num32 = 32'h0000_8000; + 5'h03 : num32 = 32'h0000_7FFF; + 5'h02 : num32 = 32'h0000_7FFE; + 5'h01 : num32 = 32'h0000_0001; + 5'h00 : num32 = 32'h0000_0000; + default : num32 = 32'h0000_0000; + endcase + random_corner_num32 = num32; + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Random corner number (16-bit) + //////////////////////////////////////////////////////////////////////////// + function reg [15:0] random_corner_num16(input rcn_null); + reg [31:0] rand32; + reg [15:0] num16; + begin + rand32 = {$random(seed)}; // {} = unsigned + case (rand32[2:0]) + 3'h7 : num16 = 16'hFFFF; // -1 + 3'h6 : num16 = 16'hFFFE; // -2 + 3'h5 : num16 = 16'h8001; // -32767 + 3'h4 : num16 = 16'h8000; // -32768 + 3'h3 : num16 = 16'h7FFF; // +32767 + 3'h2 : num16 = 16'h7FFE; // +32766 + 3'h1 : num16 = 16'h0001; // 1 + default : num16 = 16'h0000; // 0 + endcase + random_corner_num16 = num16; + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Random corner number (8-bit) + //////////////////////////////////////////////////////////////////////////// + function reg [7:0] random_corner_num8(input rcn_null); + reg [31:0] rand32; + reg [7:0] num8; + begin + rand32 = {$random(seed)}; // {} = unsigned + case (rand32[2:0]) + 3'h7 : num8 = 8'hFF; // -1 + 3'h6 : num8 = 8'hFE; // -2 + 3'h5 : num8 = 8'h81; // -127 + 3'h4 : num8 = 8'h80; // -128 + 3'h3 : num8 = 8'h7F; // +127 + 3'h2 : num8 = 8'h7E; // +126 + 3'h1 : num8 = 8'h01; // 1 + default : num8 = 8'h00; // 0 + endcase + random_corner_num8 = num8; + end + endfunction + + + //////////////////////////////////////////////////////////////////////////// + // Debug $random + //////////////////////////////////////////////////////////////////////////// + task debug_random; + reg [31:0] rand32; + begin + // this is a scratchpad task for debugging $random + $display("[TB: debug_random ]"); + rand32 = 0; + while (rand32[31:30] != 2'h1) begin + rand32 = {$random(seed)}; // {} = unsigned + $display("[TB: debug_random ]rand32[31:0] = %8h",rand32[31:0]); + $display("[TB: debug_random ]rand32[31:30] = %1h", rand32[31:30]); + end + $display("[TB: debug_random ]"); + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Wait Clock Cycles + //////////////////////////////////////////////////////////////////////////// + task wait_clk_cycles(input integer wait_cycle_total); + integer wait_cycle_cnt; + begin + $display("[TB: wait_clk_cycles] Waiting %0d clock cycles ", wait_cycle_total); + for (wait_cycle_cnt = 0; wait_cycle_cnt < wait_cycle_total; wait_cycle_cnt++) begin + @(posedge sysclk); + end + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Choose Stack Pointer + //////////////////////////////////////////////////////////////////////////// + function reg choose_stack_ptr(input [1:0] stack_ptr_field); + begin + $write("[TB: choose_stack_ptr] "); + if (stack_ptr_field == 2'h2) begin + $write("Selecting random stack pointer... "); + choose_stack_ptr = {$random(seed)}; //{} = unsigned + end else begin + choose_stack_ptr = stack_ptr_field[0]; + end + if (choose_stack_ptr == 1'b0) begin + $display("S selected as stack pointer."); + end else begin + $display("U selected as stack pointer."); + end + end + endfunction + + + //////////////////////////////////////////////////////////////////////////// + // Write Opcode + //////////////////////////////////////////////////////////////////////////// + task write_opcode(input [7:0] prebyte, input [7:0] opcode, inout reg [15:0] addr_ptr, input newline); + begin + $write("[TB: write_opcode ] @ 0x%4x <= ",addr_ptr); + if (prebyte != 8'h00) begin + write_tb_mem16(addr_ptr, {prebyte, opcode}); + addr_ptr+=2; + end else begin + write_tb_mem8(addr_ptr++, opcode); + end + print_opcode_info(prebyte, opcode, newline); + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Write Jump to Done + //////////////////////////////////////////////////////////////////////////// + task write_jump_done(input stack_ptr_sel, inout reg [15:0] addr_ptr); + begin + write_opcode(8'h00,8'h7E,addr_ptr,1'b1); + if (stack_ptr_sel == 1'b0) begin + write_tb_mem16p(addr_ptr,`asm_done_s_ptr); + addr_ptr+=2; + $display("writing address `asm_done_s_ptr for JMP"); + end else begin + write_tb_mem16p(addr_ptr,`asm_done_u_ptr); + addr_ptr+=2; + $display("writing address `asm_done_u_ptr for JMP"); + end + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Write Reset Vector + //////////////////////////////////////////////////////////////////////////// + task write_reset_vector(input stack_ptr_sel); + begin + if (stack_ptr_sel == 1'b0) begin + write_tb_mem16p(`asm_reset_vector,`asm_start_s_ptr); + $display("setting Reset Vector to `asm_start_s_ptr"); + end else begin + write_tb_mem16p(`asm_reset_vector,`asm_start_u_ptr); + $display("setting Reset Vector to `asm_start_u_ptr"); + end + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Save Testbench Memory + //////////////////////////////////////////////////////////////////////////// + task save_tb_mem(input [(32*8)-1:0] test_name, input [7:0] prebyte, input [7:0] opcode, input integer itr_idx); + integer hex_file_ptr; + integer hex_file_idx; + reg [(64*8)-1:0] hex_file_name; + begin + if (prebyte != 8'h00) begin + $sformat(hex_file_name,"%0s.0x%4x.%0d.hex",test_name,{prebyte,opcode},itr_idx); + end else begin + $sformat(hex_file_name,"%0s.0x%2x.%0d.hex",test_name,opcode,itr_idx); + end + hex_file_ptr = $fopen(hex_file_name,"w"); + for (hex_file_idx = 0; hex_file_idx<(2**`MEM_ADDR_WIDTH); hex_file_idx++) begin + $fwrite(hex_file_ptr,"%2x\n",`tb_mem[hex_file_idx]); + end + $fclose(hex_file_ptr); + $display("[TB: save_tb_mem ] Saving tb_mem as \"%0s\" for future debug", hex_file_name); + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // Load S19 into Testbench Memory + //////////////////////////////////////////////////////////////////////////// + task load_s19_tb_mem(input [(128*8)-1:0] s19_load_file); + integer s19_file_ptr; + integer read_byte; + reg [ 7:0] s19_data; + reg [ 7:0] s19_len; + reg [15:0] s19_addr; + integer s19_idx; + begin + $display("[TB: load_s19_tb_mem ] Loading S19 file into tb_mem: %0s", s19_load_file); + s19_file_ptr = $fopen(s19_load_file,"r"); + read_byte = $fgetc(s19_file_ptr); + while (read_byte > 0) // ~EOF + begin + if (read_byte[7:0] == "S") begin + read_byte = $fgetc(s19_file_ptr); + if (read_byte[7:0] == "1") begin + s19_len [ 7: 4] = hex2bin($fgetc(s19_file_ptr)); + s19_len [ 3: 0] = hex2bin($fgetc(s19_file_ptr)); + // + s19_addr[15:12] = hex2bin($fgetc(s19_file_ptr)); + s19_addr[11: 8] = hex2bin($fgetc(s19_file_ptr)); + s19_addr[ 7: 4] = hex2bin($fgetc(s19_file_ptr)); + s19_addr[ 3: 0] = hex2bin($fgetc(s19_file_ptr)); + // + s19_len = s19_len - 8'd3; // subtract address & checksum + // + $display("[TB: load_s19_tb_mem ] s19_len = 0x%2x , s19_addr = 0x%4x ", s19_len, s19_addr); + for (s19_idx = 0; s19_idx < s19_len; s19_idx++) begin + s19_data[ 7: 4] = hex2bin($fgetc(s19_file_ptr)); + s19_data[ 3: 0] = hex2bin($fgetc(s19_file_ptr)); + write_tb_mem8(s19_addr, s19_data); + s19_addr++; + end + end + end + read_byte = $fgetc(s19_file_ptr); + end + end + endtask + + //////////////////////////////////////////////////////////////////////////// + // HEX to bin + //////////////////////////////////////////////////////////////////////////// + function reg [3:0] hex2bin(input reg [7:0] hex_byte); + begin + if (hex_byte >= "a") begin + hex_byte = hex_byte - 8'h20; //Adjust to ucase + end + // + if (hex_byte >= "A") begin + hex_byte = hex_byte - 8'h37; + end else begin + hex_byte = hex_byte - "0"; + end + // + hex2bin = hex_byte[3:0]; + end + endfunction + + //////////////////////////////////////////////////////////////////////////// + // Wait for bits to clear + //////////////////////////////////////////////////////////////////////////// + task wait_bits_clear(input [7:0] mask, input integer timeout, inout integer error_cnt); + integer clk_cycles; + begin + $display("[TB: wait_bits_clear] Waiting for masked output_port bits of Model and DUT to clear. mask = 0x%2x", mask); + clk_cycles = 0; + while ((~model_error) && (clk_cycles < timeout) && (((model_output_port&mask) != 8'h00) || ((dut_output_port&mask) != 8'h00))) + begin + @(posedge sysclk) clk_cycles++; + end + // + if (clk_cycles == timeout) begin + $display("[TB: wait_bits_clear] Timeout! clk_cycles: %0d", clk_cycles); + if ((model_output_port&mask) != 8'h00) begin + $display("[TB: wait_bits_clear] ERROR Model masked output_port bits did not clear. model_output_port(0x%2x) & mask(0x%2x) = 0x%2x", + model_output_port, mask, (model_output_port&mask)); + error_cnt++; + end + // + if ((dut_output_port&mask) != 8'h00) begin + $display("[TB: wait_bits_clear] ERROR DUT masked output_port bits did not clear. dut_output_port(0x%2x) & mask(0x%2x) = 0x%2x", + dut_output_port, mask, (dut_output_port&mask)); + error_cnt++; + end + end if (model_error) begin + $display("[TB: wait_bits_set ] ERROR Model error detected"); + end else begin + $display("[TB: wait_bits_clear] Masked output_port bits of Model and DUT clear! clk_cycles: %0d", clk_cycles); + end + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Wait for bits to set + //////////////////////////////////////////////////////////////////////////// + task wait_bits_set(input [7:0] mask, input integer timeout, inout integer error_cnt); + integer clk_cycles; + begin + $display("[TB: wait_bits_set ] Waiting for masked output_port bits of Model and DUT to set. mask = 0x%2x", mask); + clk_cycles = 0; + while ((~model_error) && (clk_cycles < timeout) && (((model_output_port|(~mask)) != 8'hFF) || ((dut_output_port|(~mask)) != 8'hFF))) + begin + @(posedge sysclk) clk_cycles++; + end + // + if (clk_cycles == timeout) begin + $display("[TB: wait_bits_set ] Timeout! clk_cycles: %0d", clk_cycles); + if ((model_output_port|(~mask)) != 8'hFF) begin + $display("[TB: wait_bits_set ] ERROR Model masked output_port bits did not set. model_output_port(0x%2x) & mask(0x%2x) = 0x%2x", + model_output_port, mask, (model_output_port&mask)); + error_cnt++; + end + // + if ((dut_output_port|(~mask)) != 8'hFF) begin + $display("[TB: wait_bits_set ] ERROR DUT masked output_port bits did not set. dut_output_port(0x%2x) & mask(0x%2x) = 0x%2x", + dut_output_port, mask, (dut_output_port&mask)); + error_cnt++; + end + end if (model_error) begin + $display("[TB: wait_bits_set ] ERROR Model error detected"); + end else begin + $display("[TB: wait_bits_set ] Masked output_port bits of Model and DUT set! clk_cycles: %0d", clk_cycles); + end + end + endtask + + + //////////////////////////////////////////////////////////////////////////// + // Print Opcode Infomation + //////////////////////////////////////////////////////////////////////////// + task print_opcode_info(input [7:0] prebyte, input [7:0] opcode, input newline); + begin + if (prebyte == 8'h11) begin + case (opcode) + 8'h3F : $write("0x%2x%2x : SWI3 (stack_op) (page3)", prebyte, opcode); + 8'h83 : $write("0x%2x%2x : CMPU (immediate) (page3)", prebyte, opcode); + 8'h8C : $write("0x%2x%2x : CMPS (immediate) (page3)", prebyte, opcode); + 8'h93 : $write("0x%2x%2x : CMPU (direct) (page3)", prebyte, opcode); + 8'h9C : $write("0x%2x%2x : CMPS (direct) (page3)", prebyte, opcode); + 8'hA3 : $write("0x%2x%2x : CMPU (indexed) (page3)", prebyte, opcode); + 8'hAC : $write("0x%2x%2x : CMPS (indexed) (page3)", prebyte, opcode); + 8'hB3 : $write("0x%2x%2x : CMPU (extended) (page3)", prebyte, opcode); + 8'hBC : $write("0x%2x%2x : CMPS (extended) (page3)", prebyte, opcode); + default : $write("0x%2x%2x : Invalid Opcode (page3)", prebyte, opcode); + endcase + if (newline) $display(""); + end else if (prebyte == 8'h10) begin + case (opcode) + 8'h14 : $write("0x%2x%2x : EDIV (inherent) (page2)", prebyte, opcode); + 8'h15 : $write("0x%2x%2x : EDIVS (inherent) (page2)", prebyte, opcode); + 8'h18 : $write("0x%2x%2x : IDIVS (inherent) (page2)", prebyte, opcode); + 8'h19 : $write("0x%2x%2x : FDIV (inherent) (page2)", prebyte, opcode); + 8'h20 : $write("0x%2x%2x : LBRA (relative) (page2)", prebyte, opcode); + 8'h21 : $write("0x%2x%2x : LBRN (relative) (page2)", prebyte, opcode); + 8'h22 : $write("0x%2x%2x : LBHI (relative) (page2)", prebyte, opcode); + 8'h23 : $write("0x%2x%2x : LBLS (relative) (page2)", prebyte, opcode); + 8'h24 : $write("0x%2x%2x : LBHS,LBCC (relative) (page2)", prebyte, opcode); + 8'h25 : $write("0x%2x%2x : LBLO,LBCS (relative) (page2)", prebyte, opcode); + 8'h26 : $write("0x%2x%2x : LBNE (relative) (page2)", prebyte, opcode); + 8'h27 : $write("0x%2x%2x : LBEQ (relative) (page2)", prebyte, opcode); + 8'h28 : $write("0x%2x%2x : LBVC (relative) (page2)", prebyte, opcode); + 8'h29 : $write("0x%2x%2x : LBVS (relative) (page2)", prebyte, opcode); + 8'h2A : $write("0x%2x%2x : LBPL (relative) (page2)", prebyte, opcode); + 8'h2B : $write("0x%2x%2x : LBMI (relative) (page2)", prebyte, opcode); + 8'h2C : $write("0x%2x%2x : LBGE (relative) (page2)", prebyte, opcode); + 8'h2D : $write("0x%2x%2x : LBLT (relative) (page2)", prebyte, opcode); + 8'h2E : $write("0x%2x%2x : LBGT (relative) (page2)", prebyte, opcode); + 8'h2F : $write("0x%2x%2x : LBLE (relative) (page2)", prebyte, opcode); + 8'h3F : $write("0x%2x%2x : SWI2 (stack_op) (page2)", prebyte, opcode); + 8'h83 : $write("0x%2x%2x : CMPD (immediate) (page2)", prebyte, opcode); + 8'h8C : $write("0x%2x%2x : CMPY (immediate) (page2)", prebyte, opcode); + 8'h8E : $write("0x%2x%2x : LDY (immediate) (page2)", prebyte, opcode); + 8'h93 : $write("0x%2x%2x : CMPD (direct) (page2)", prebyte, opcode); + 8'h9C : $write("0x%2x%2x : CMPY (direct) (page2)", prebyte, opcode); + 8'h9E : $write("0x%2x%2x : LDY (direct) (page2)", prebyte, opcode); + 8'h9F : $write("0x%2x%2x : STY (direct) (page2)", prebyte, opcode); + 8'hA3 : $write("0x%2x%2x : CMPD (indexed) (page2)", prebyte, opcode); + 8'hAC : $write("0x%2x%2x : CMPY (indexed) (page2)", prebyte, opcode); + 8'hAE : $write("0x%2x%2x : LDY (indexed) (page2)", prebyte, opcode); + 8'hAF : $write("0x%2x%2x : STY (indexed) (page2)", prebyte, opcode); + 8'hB3 : $write("0x%2x%2x : CMPD (extended) (page2)", prebyte, opcode); + 8'hBC : $write("0x%2x%2x : CMPY (extended) (page2)", prebyte, opcode); + 8'hBE : $write("0x%2x%2x : LDY (extended) (page2)", prebyte, opcode); + 8'hBF : $write("0x%2x%2x : STY (extended) (page2)", prebyte, opcode); + 8'hCE : $write("0x%2x%2x : LDS (immediate) (page2)", prebyte, opcode); + 8'hDE : $write("0x%2x%2x : LDS (direct) (page2)", prebyte, opcode); + 8'hDF : $write("0x%2x%2x : STS (direct) (page2)", prebyte, opcode); + 8'hEE : $write("0x%2x%2x : LDS (indexed) (page2)", prebyte, opcode); + 8'hEF : $write("0x%2x%2x : STS (indexed) (page2)", prebyte, opcode); + 8'hFE : $write("0x%2x%2x : LDS (extended) (page2)", prebyte, opcode); + 8'hFF : $write("0x%2x%2x : STS (extended) (page2)", prebyte, opcode); + default : $write("0x%2x%2x : Invalid Opcode (page2)", prebyte, opcode); + endcase + if (newline) $display(""); + end else if (~((opcode == 8'h10) || (opcode == 8'h11))) begin + case (opcode) + 8'h00 : $write(" 0x%2x : NEG (direct) (page1)", opcode); + //8'h01 : $write(" 0x%2x : * () (page1)", opcode); + //8'h02 : $write(" 0x%2x : * () (page1)", opcode); + 8'h03 : $write(" 0x%2x : COM (direct) (page1)", opcode); + 8'h04 : $write(" 0x%2x : LSR (direct) (page1)", opcode); + //8'h05 : $write(" 0x%2x : * () (page1)", opcode); + 8'h06 : $write(" 0x%2x : ROR (direct) (page1)", opcode); + 8'h07 : $write(" 0x%2x : ASR (direct) (page1)", opcode); + 8'h08 : $write(" 0x%2x : ASL,LSL (direct) (page1)", opcode); + 8'h09 : $write(" 0x%2x : ROL (direct) (page1)", opcode); + 8'h0A : $write(" 0x%2x : DEC (direct) (page1)", opcode); + //8'h0B : $write(" 0x%2x : * () (page1)", opcode); + 8'h0C : $write(" 0x%2x : INC (direct) (page1)", opcode); + 8'h0D : $write(" 0x%2x : TST (direct) (page1)", opcode); + 8'h0E : $write(" 0x%2x : JMP (direct) (page1)", opcode); + 8'h0F : $write(" 0x%2x : CLR (direct) (page1)", opcode); + //8'h10 : $write(" 0x%2x : Prebyte () (page1)", opcode); + //8'h11 : $write(" 0x%2x : Prebyte () (page1)", opcode); + 8'h12 : $write(" 0x%2x : NOP (inherent) (page1)", opcode); + 8'h13 : $write(" 0x%2x : SYNC (inherent) (page1)", opcode); + 8'h14 : $write(" 0x%2x : EMUL (inherent) (page1)", opcode); + 8'h15 : $write(" 0x%2x : EMULS (inherent) (page1)", opcode); + 8'h16 : $write(" 0x%2x : LBRA (relative) (page1)", opcode); + 8'h17 : $write(" 0x%2x : LBSR (relative) (page1)", opcode); + 8'h18 : $write(" 0x%2x : IDIV (inherent) (page1)", opcode); + 8'h19 : $write(" 0x%2x : DAA (inherent) (page1)", opcode); + 8'h1A : $write(" 0x%2x : ORCC (immediate) (page1)", opcode); + //8'h1B : $write(" 0x%2x : * () (page1)", opcode); + 8'h1C : $write(" 0x%2x : ANDCC (immediate) (page1)", opcode); + 8'h1D : $write(" 0x%2x : SEX (inherent) (page1)", opcode); + 8'h1E : $write(" 0x%2x : EXG (inherent) (page1)", opcode); + 8'h1F : $write(" 0x%2x : TFR (inherent) (page1)", opcode); + 8'h20 : $write(" 0x%2x : BRA (relative) (page1)", opcode); + 8'h21 : $write(" 0x%2x : BRN (relative) (page1)", opcode); + 8'h22 : $write(" 0x%2x : BHI (relative) (page1)", opcode); + 8'h23 : $write(" 0x%2x : BLS (relative) (page1)", opcode); + 8'h24 : $write(" 0x%2x : BHS,BCC (relative) (page1)", opcode); + 8'h25 : $write(" 0x%2x : BLO,BCS (relative) (page1)", opcode); + 8'h26 : $write(" 0x%2x : BNE (relative) (page1)", opcode); + 8'h27 : $write(" 0x%2x : BEQ (relative) (page1)", opcode); + 8'h28 : $write(" 0x%2x : BVC (relative) (page1)", opcode); + 8'h29 : $write(" 0x%2x : BVS (relative) (page1)", opcode); + 8'h2A : $write(" 0x%2x : BPL (relative) (page1)", opcode); + 8'h2B : $write(" 0x%2x : BMI (relative) (page1)", opcode); + 8'h2C : $write(" 0x%2x : BGE (relative) (page1)", opcode); + 8'h2D : $write(" 0x%2x : BLT (relative) (page1)", opcode); + 8'h2E : $write(" 0x%2x : BGT (relative) (page1)", opcode); + 8'h2F : $write(" 0x%2x : BLE (relative) (page1)", opcode); + 8'h30 : $write(" 0x%2x : LEAX (indexed) (page1)", opcode); + 8'h31 : $write(" 0x%2x : LEAY (indexed) (page1)", opcode); + 8'h32 : $write(" 0x%2x : LEAS (indexed) (page1)", opcode); + 8'h33 : $write(" 0x%2x : LEAU (indexed) (page1)", opcode); + 8'h34 : $write(" 0x%2x : PSHS (stack_op) (page1)", opcode); + 8'h35 : $write(" 0x%2x : PULS (stack_op) (page1)", opcode); + 8'h36 : $write(" 0x%2x : PSHU (stack_op) (page1)", opcode); + 8'h37 : $write(" 0x%2x : PULU (stack_op) (page1)", opcode); + //8'h38 : $write(" 0x%2x : * () (page1)", opcode); + 8'h39 : $write(" 0x%2x : RTS (stack_op) (page1)", opcode); + 8'h3A : $write(" 0x%2x : ABX (inherent) (page1)", opcode); + 8'h3B : $write(" 0x%2x : RTI (stack_op) (page1)", opcode); + 8'h3C : $write(" 0x%2x : CWAI (stack_op) (page1)", opcode); + 8'h3D : $write(" 0x%2x : MUL (inherent) (page1)", opcode); + //8'h3E : $write(" 0x%2x : * () (page1)", opcode); + 8'h3F : $write(" 0x%2x : SWI (stack_op) (page1)", opcode); + 8'h40 : $write(" 0x%2x : NEGA (inherent) (page1)", opcode); + //8'h41 : $write(" 0x%2x : * () (page1)", opcode); + //8'h42 : $write(" 0x%2x : * () (page1)", opcode); + 8'h43 : $write(" 0x%2x : COMA (inherent) (page1)", opcode); + 8'h44 : $write(" 0x%2x : LSRA (inherent) (page1)", opcode); + //8'h45 : $write(" 0x%2x : * () (page1)", opcode); + 8'h46 : $write(" 0x%2x : RORA (inherent) (page1)", opcode); + 8'h47 : $write(" 0x%2x : ASRA (inherent) (page1)", opcode); + 8'h48 : $write(" 0x%2x : ASLA,LSLA (inherent) (page1)", opcode); + 8'h49 : $write(" 0x%2x : ROLA (inherent) (page1)", opcode); + 8'h4A : $write(" 0x%2x : DECA (inherent) (page1)", opcode); + //8'h4B : $write(" 0x%2x : * () (page1)", opcode); + 8'h4C : $write(" 0x%2x : INCA (inherent) (page1)", opcode); + 8'h4D : $write(" 0x%2x : TSTA (inherent) (page1)", opcode); + //8'h4E : $write(" 0x%2x : * () (page1)", opcode); + 8'h4F : $write(" 0x%2x : CLRA (inherent) (page1)", opcode); + 8'h50 : $write(" 0x%2x : NEGB (inherent) (page1)", opcode); + //8'h51 : $write(" 0x%2x : * () (page1)", opcode); + //8'h52 : $write(" 0x%2x : * () (page1)", opcode); + 8'h53 : $write(" 0x%2x : COMB (inherent) (page1)", opcode); + 8'h54 : $write(" 0x%2x : LSRB (inherent) (page1)", opcode); + //8'h55 : $write(" 0x%2x : * () (page1)", opcode); + 8'h56 : $write(" 0x%2x : RORB (inherent) (page1)", opcode); + 8'h57 : $write(" 0x%2x : ASRB (inherent) (page1)", opcode); + 8'h58 : $write(" 0x%2x : ASLB,LSLB (inherent) (page1)", opcode); + 8'h59 : $write(" 0x%2x : ROLB (inherent) (page1)", opcode); + 8'h5A : $write(" 0x%2x : DECB (inherent) (page1)", opcode); + //8'h5B : $write(" 0x%2x : * () (page1)", opcode); + 8'h5C : $write(" 0x%2x : INCB (inherent) (page1)", opcode); + 8'h5D : $write(" 0x%2x : TSTB (inherent) (page1)", opcode); + //8'h5E : $write(" 0x%2x : * () (page1)", opcode); + 8'h5F : $write(" 0x%2x : CLRB (inherent) (page1)", opcode); + 8'h60 : $write(" 0x%2x : NEG (indexed) (page1)", opcode); + //8'h61 : $write(" 0x%2x : * () (page1)", opcode); + //8'h62 : $write(" 0x%2x : * () (page1)", opcode); + 8'h63 : $write(" 0x%2x : COM (indexed) (page1)", opcode); + 8'h64 : $write(" 0x%2x : LSR (indexed) (page1)", opcode); + //8'h65 : $write(" 0x%2x : * () (page1)", opcode); + 8'h66 : $write(" 0x%2x : ROR (indexed) (page1)", opcode); + 8'h67 : $write(" 0x%2x : ASR (indexed) (page1)", opcode); + 8'h68 : $write(" 0x%2x : ASL,LSL (indexed) (page1)", opcode); + 8'h69 : $write(" 0x%2x : ROL (indexed) (page1)", opcode); + 8'h6A : $write(" 0x%2x : DEC (indexed) (page1)", opcode); + //8'h6B : $write(" 0x%2x : * () (page1)", opcode); + 8'h6C : $write(" 0x%2x : INC (indexed) (page1)", opcode); + 8'h6D : $write(" 0x%2x : TST (indexed) (page1)", opcode); + 8'h6E : $write(" 0x%2x : JMP (indexed) (page1)", opcode); + 8'h6F : $write(" 0x%2x : CLR (indexed) (page1)", opcode); + 8'h70 : $write(" 0x%2x : NEG (extended) (page1)", opcode); + //8'h71 : $write(" 0x%2x : * () (page1)", opcode); + //8'h72 : $write(" 0x%2x : * () (page1)", opcode); + 8'h73 : $write(" 0x%2x : COM (extended) (page1)", opcode); + 8'h74 : $write(" 0x%2x : LSR (extended) (page1)", opcode); + //8'h75 : $write(" 0x%2x : * () (page1)", opcode); + 8'h76 : $write(" 0x%2x : ROR (extended) (page1)", opcode); + 8'h77 : $write(" 0x%2x : ASR (extended) (page1)", opcode); + 8'h78 : $write(" 0x%2x : ASL,LSL (extended) (page1)", opcode); + 8'h79 : $write(" 0x%2x : ROL (extended) (page1)", opcode); + 8'h7A : $write(" 0x%2x : DEC (extended) (page1)", opcode); + //8'h7B : $write(" 0x%2x : * () (page1)", opcode); + 8'h7C : $write(" 0x%2x : INC (extended) (page1)", opcode); + 8'h7D : $write(" 0x%2x : TST (extended) (page1)", opcode); + 8'h7E : $write(" 0x%2x : JMP (extended) (page1)", opcode); + 8'h7F : $write(" 0x%2x : CLR (extended) (page1)", opcode); + 8'h80 : $write(" 0x%2x : SUBA (immediate) (page1)", opcode); + 8'h81 : $write(" 0x%2x : CMPA (immediate) (page1)", opcode); + 8'h82 : $write(" 0x%2x : SBCA (immediate) (page1)", opcode); + 8'h83 : $write(" 0x%2x : SUBD (immediate) (page1)", opcode); + 8'h84 : $write(" 0x%2x : ANDA (immediate) (page1)", opcode); + 8'h85 : $write(" 0x%2x : BITA (immediate) (page1)", opcode); + 8'h86 : $write(" 0x%2x : LDA (immediate) (page1)", opcode); + //8'h87 : $write(" 0x%2x : * () (page1)", opcode); + 8'h88 : $write(" 0x%2x : EORA (immediate) (page1)", opcode); + 8'h89 : $write(" 0x%2x : ADCA (immediate) (page1)", opcode); + 8'h8A : $write(" 0x%2x : ORA (immediate) (page1)", opcode); + 8'h8B : $write(" 0x%2x : ADDA (immediate) (page1)", opcode); + 8'h8C : $write(" 0x%2x : CMPX (immediate) (page1)", opcode); + 8'h8D : $write(" 0x%2x : BSR (relative) (page1)", opcode); + 8'h8E : $write(" 0x%2x : LDX (immediate) (page1)", opcode); + //8'h8F : $write(" 0x%2x : * () (page1)", opcode); + 8'h90 : $write(" 0x%2x : SUBA (direct) (page1)", opcode); + 8'h91 : $write(" 0x%2x : CMPA (direct) (page1)", opcode); + 8'h92 : $write(" 0x%2x : SBCA (direct) (page1)", opcode); + 8'h93 : $write(" 0x%2x : SUBD (direct) (page1)", opcode); + 8'h94 : $write(" 0x%2x : ANDA (direct) (page1)", opcode); + 8'h95 : $write(" 0x%2x : BITA (direct) (page1)", opcode); + 8'h96 : $write(" 0x%2x : LDA (direct) (page1)", opcode); + 8'h97 : $write(" 0x%2x : STA (direct) (page1)", opcode); + 8'h98 : $write(" 0x%2x : EORA (direct) (page1)", opcode); + 8'h99 : $write(" 0x%2x : ADCA (direct) (page1)", opcode); + 8'h9A : $write(" 0x%2x : ORA (direct) (page1)", opcode); + 8'h9B : $write(" 0x%2x : ADDA (direct) (page1)", opcode); + 8'h9C : $write(" 0x%2x : CMPX (direct) (page1)", opcode); + 8'h9D : $write(" 0x%2x : JSR (direct) (page1)", opcode); + 8'h9E : $write(" 0x%2x : LDX (direct) (page1)", opcode); + 8'h9F : $write(" 0x%2x : STX (direct) (page1)", opcode); + 8'hA0 : $write(" 0x%2x : SUBA (indexed) (page1)", opcode); + 8'hA1 : $write(" 0x%2x : CMPA (indexed) (page1)", opcode); + 8'hA2 : $write(" 0x%2x : SBCA (indexed) (page1)", opcode); + 8'hA3 : $write(" 0x%2x : SUBD (indexed) (page1)", opcode); + 8'hA4 : $write(" 0x%2x : ANDA (indexed) (page1)", opcode); + 8'hA5 : $write(" 0x%2x : BITA (indexed) (page1)", opcode); + 8'hA6 : $write(" 0x%2x : LDA (indexed) (page1)", opcode); + 8'hA7 : $write(" 0x%2x : STA (indexed) (page1)", opcode); + 8'hA8 : $write(" 0x%2x : EORA (indexed) (page1)", opcode); + 8'hA9 : $write(" 0x%2x : ADCA (indexed) (page1)", opcode); + 8'hAA : $write(" 0x%2x : ORA (indexed) (page1)", opcode); + 8'hAB : $write(" 0x%2x : ADDA (indexed) (page1)", opcode); + 8'hAC : $write(" 0x%2x : CMPX (indexed) (page1)", opcode); + 8'hAD : $write(" 0x%2x : JSR (indexed) (page1)", opcode); + 8'hAE : $write(" 0x%2x : LDX (indexed) (page1)", opcode); + 8'hAF : $write(" 0x%2x : STX (indexed) (page1)", opcode); + 8'hB0 : $write(" 0x%2x : SUBA (extended) (page1)", opcode); + 8'hB1 : $write(" 0x%2x : CMPA (extended) (page1)", opcode); + 8'hB2 : $write(" 0x%2x : SBCA (extended) (page1)", opcode); + 8'hB3 : $write(" 0x%2x : SUBD (extended) (page1)", opcode); + 8'hB4 : $write(" 0x%2x : ANDA (extended) (page1)", opcode); + 8'hB5 : $write(" 0x%2x : BITA (extended) (page1)", opcode); + 8'hB6 : $write(" 0x%2x : LDA (extended) (page1)", opcode); + 8'hB7 : $write(" 0x%2x : STA (extended) (page1)", opcode); + 8'hB8 : $write(" 0x%2x : EORA (extended) (page1)", opcode); + 8'hB9 : $write(" 0x%2x : ADCA (extended) (page1)", opcode); + 8'hBA : $write(" 0x%2x : ORA (extended) (page1)", opcode); + 8'hBB : $write(" 0x%2x : ADDA (extended) (page1)", opcode); + 8'hBC : $write(" 0x%2x : CMPX (extended) (page1)", opcode); + 8'hBD : $write(" 0x%2x : JSR (extended) (page1)", opcode); + 8'hBE : $write(" 0x%2x : LDX (extended) (page1)", opcode); + 8'hBF : $write(" 0x%2x : STX (extended) (page1)", opcode); + 8'hC0 : $write(" 0x%2x : SUBB (immediate) (page1)", opcode); + 8'hC1 : $write(" 0x%2x : CMPB (immediate) (page1)", opcode); + 8'hC2 : $write(" 0x%2x : SBCB (immediate) (page1)", opcode); + 8'hC3 : $write(" 0x%2x : ADDD (immediate) (page1)", opcode); + 8'hC4 : $write(" 0x%2x : ANDB (immediate) (page1)", opcode); + 8'hC5 : $write(" 0x%2x : BITB (immediate) (page1)", opcode); + 8'hC6 : $write(" 0x%2x : LDB (immediate) (page1)", opcode); + //8'hC7 : $write(" 0x%2x : * () (page1)", opcode); + 8'hC8 : $write(" 0x%2x : EORB (immediate) (page1)", opcode); + 8'hC9 : $write(" 0x%2x : ADCB (immediate) (page1)", opcode); + 8'hCA : $write(" 0x%2x : ORB (immediate) (page1)", opcode); + 8'hCB : $write(" 0x%2x : ADDB (immediate) (page1)", opcode); + 8'hCC : $write(" 0x%2x : LDD (immediate) (page1)", opcode); + //8'hCD : $write(" 0x%2x : * () (page1)", opcode); + 8'hCE : $write(" 0x%2x : LDU (immediate) (page1)", opcode); + //8'hCF : $write(" 0x%2x : * () (page1)", opcode); + 8'hD0 : $write(" 0x%2x : SUBB (direct) (page1)", opcode); + 8'hD1 : $write(" 0x%2x : CMPB (direct) (page1)", opcode); + 8'hD2 : $write(" 0x%2x : SBCB (direct) (page1)", opcode); + 8'hD3 : $write(" 0x%2x : ADDD (direct) (page1)", opcode); + 8'hD4 : $write(" 0x%2x : ANDB (direct) (page1)", opcode); + 8'hD5 : $write(" 0x%2x : BITB (direct) (page1)", opcode); + 8'hD6 : $write(" 0x%2x : LDB (direct) (page1)", opcode); + 8'hD7 : $write(" 0x%2x : STB (direct) (page1)", opcode); + 8'hD8 : $write(" 0x%2x : EORB (direct) (page1)", opcode); + 8'hD9 : $write(" 0x%2x : ADCB (direct) (page1)", opcode); + 8'hDA : $write(" 0x%2x : ORB (direct) (page1)", opcode); + 8'hDB : $write(" 0x%2x : ADDB (direct) (page1)", opcode); + 8'hDC : $write(" 0x%2x : LDD (direct) (page1)", opcode); + 8'hDD : $write(" 0x%2x : STD (direct) (page1)", opcode); + 8'hDE : $write(" 0x%2x : LDU (direct) (page1)", opcode); + 8'hDF : $write(" 0x%2x : STU (direct) (page1)", opcode); + 8'hE0 : $write(" 0x%2x : SUBB (indexed) (page1)", opcode); + 8'hE1 : $write(" 0x%2x : CMPB (indexed) (page1)", opcode); + 8'hE2 : $write(" 0x%2x : SBCB (indexed) (page1)", opcode); + 8'hE3 : $write(" 0x%2x : ADDD (indexed) (page1)", opcode); + 8'hE4 : $write(" 0x%2x : ANDB (indexed) (page1)", opcode); + 8'hE5 : $write(" 0x%2x : BITB (indexed) (page1)", opcode); + 8'hE6 : $write(" 0x%2x : LDB (indexed) (page1)", opcode); + 8'hE7 : $write(" 0x%2x : STB (indexed) (page1)", opcode); + 8'hE8 : $write(" 0x%2x : EORB (indexed) (page1)", opcode); + 8'hE9 : $write(" 0x%2x : ADCB (indexed) (page1)", opcode); + 8'hEA : $write(" 0x%2x : ORB (indexed) (page1)", opcode); + 8'hEB : $write(" 0x%2x : ADDB (indexed) (page1)", opcode); + 8'hEC : $write(" 0x%2x : LDD (indexed) (page1)", opcode); + 8'hED : $write(" 0x%2x : STD (indexed) (page1)", opcode); + 8'hEE : $write(" 0x%2x : LDU (indexed) (page1)", opcode); + 8'hEF : $write(" 0x%2x : STU (indexed) (page1)", opcode); + 8'hF0 : $write(" 0x%2x : SUBB (extended) (page1)", opcode); + 8'hF1 : $write(" 0x%2x : CMPB (extended) (page1)", opcode); + 8'hF2 : $write(" 0x%2x : SBCB (extended) (page1)", opcode); + 8'hF3 : $write(" 0x%2x : ADDD (extended) (page1)", opcode); + 8'hF4 : $write(" 0x%2x : ANDB (extended) (page1)", opcode); + 8'hF5 : $write(" 0x%2x : BITB (extended) (page1)", opcode); + 8'hF6 : $write(" 0x%2x : LDB (extended) (page1)", opcode); + 8'hF7 : $write(" 0x%2x : STB (extended) (page1)", opcode); + 8'hF8 : $write(" 0x%2x : EORB (extended) (page1)", opcode); + 8'hF9 : $write(" 0x%2x : ADCB (extended) (page1)", opcode); + 8'hFA : $write(" 0x%2x : ORB (extended) (page1)", opcode); + 8'hFB : $write(" 0x%2x : ADDB (extended) (page1)", opcode); + 8'hFC : $write(" 0x%2x : LDD (extended) (page1)", opcode); + 8'hFD : $write(" 0x%2x : STD (extended) (page1)", opcode); + 8'hFE : $write(" 0x%2x : LDU (extended) (page1)", opcode); + 8'hFF : $write(" 0x%2x : STU (extended) (page1)", opcode); + default : $write(" 0x%2x : Invalid Opcode (page1)", opcode); + endcase + if (newline) $display(""); + end + end + endtask + + + diff --git a/turbo9team_turbo9/tb/tb_dv_memory.v b/turbo9team_turbo9/tb/tb_dv_memory.v new file mode 100644 index 0000000000000000000000000000000000000000..a1f68db5b78f614b4aaa3133eca5dd2782ebd0a2 --- /dev/null +++ b/turbo9team_turbo9/tb/tb_dv_memory.v @@ -0,0 +1,61 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testbench: wrapper for memory array +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Memory Module +///////////////////////////////////////////////////////////////////////////// +// +// Wrap the memory array in a module so that the memory elements are contained +// within their own module in the VCD dump +// +module tb_dv_memory +#( + parameter MEM_ADDR_WIDTH = 12 +); + + reg [7:0] memory [0:(2**MEM_ADDR_WIDTH)-1]; + +endmodule + diff --git a/turbo9team_turbo9/tb/tb_dv_top.v b/turbo9team_turbo9/tb/tb_dv_top.v new file mode 100644 index 0000000000000000000000000000000000000000..5616aeda57f980317e20bfe9575d7b5f359684f9 --- /dev/null +++ b/turbo9team_turbo9/tb/tb_dv_top.v @@ -0,0 +1,570 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testbench: Top level of the testbench +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Top Level Of Turbo9 Testbench +///////////////////////////////////////////////////////////////////////////// +`timescale 1ps/1ps + +module tb_dv_top; + + ///////////////////// Select one of the following: + `define TURBO9 + //`define TURBO9_S + //`define TURBO9_R + ///////////////////// + + `define SIM_TURBO9 // Turns on debug strings in decode table verilog files + + `define MEM_ADDR_WIDTH 15 //32 Kbyte Memory, adjust the asm accordingly + + `define model_mem I_tb_dv_6809_model.I_tb_dv_6809_memory.memory +//`define dut_mem I_broken_6809_model.I_tb_dv_6809_memory.memory + +`ifdef TURBO9_R + `define dut_mem_even I_soc_top_r.I_even_syncram_8bit.ram + `define dut_mem_odd I_soc_top_r.I_odd_syncram_8bit.ram + `define dut_cycle_cnt I_soc_top_r.clk_cnt_rd_dat +`elsif TURBO9_S + `define dut_mem_even I_soc_top_s.I_even_syncram_8bit.ram + `define dut_mem_odd I_soc_top_s.I_odd_syncram_8bit.ram + `define dut_cycle_cnt I_soc_top_s.clk_cnt_rd_dat +`else + `define dut_mem I_soc_top.I_syncram_8bit.ram + `define dut_cycle_cnt I_soc_top.clk_cnt_rd_dat +`endif + + `define tb_mem I_tb_dv_memory.memory + + `include "sim_boot.vh" // Address defines from simulation bootloader + `include "tb_dv_asm.vh" // Address defines from assembly testbench + `include "tb_dv_lib.v" // Library of utility tasks & functions + `include "tc_dv_dir_instr.v" // Testcase for direct addressing instrutions + `include "tc_dv_ext_instr.v" // Testcase for extended addressing instrutions + `include "tc_dv_imm_instr.v" // Testcase for immediate addressing instrutions + `include "tc_dv_rel_instr.v" // Testcase for relative addressing 8-bit instrutions + `include "tc_dv_rel16_instr.v" // Testcase for relative addressing 16-bit instrutions + `include "tc_dv_inh_instr.v" // Testcase for inherent addressing instructions + `include "tc_dv_sau_instr.v" // Testcase for sequential arithmetic instructions + `include "tc_dv_run_code.v" // Testcase for running code + `include "tc_dv_idx_a_instr.v" // Testcase for indexed + `include "tc_dv_idx_b_instr.v" // Testcase for indexed + `include "tc_dv_idx_d_instr.v" // Testcase for indexed + `include "tc_dv_idx_0b_instr.v" // Testcase for indexed + `include "tc_dv_idx_5b_instr.v" // Testcase for indexed + `include "tc_dv_idx_8b_instr.v" // Testcase for indexed + `include "tc_dv_idx_16b_instr.v" // Testcase for indexed + `include "tc_dv_idx_p1_instr.v" // Testcase for indexed + `include "tc_dv_idx_p2_instr.v" // Testcase for indexed + `include "tc_dv_idx_m1_instr.v" // Testcase for indexed + `include "tc_dv_idx_m2_instr.v" // Testcase for indexed + `include "tc_dv_idx_pc8_instr.v" // Testcase for indexed + `include "tc_dv_idx_pc16_instr.v" // Testcase for indexed + `include "tc_dv_ind_0b_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_8b_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_16b_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_a_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_b_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_d_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_p2_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_m2_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_pc8_instr.v" // Testcase for indirect indexed + `include "tc_dv_ind_pc16_instr.v" // Testcase for indirect indexed + `include "tc_dv_exg_8b_instr.v" // Testcase for exchange 8-bit registers + `include "tc_dv_exg_16b_instr.v" // Testcase for exchange 16-bit registers + `include "tc_dv_tfr_8b_instr.v" // Testcase for transfer 8-bit registers + `include "tc_dv_tfr_16b_instr.v" // Testcase for transfer 16-bit registers + + reg sysclk; + reg reset; + + integer seed; + integer rand_itr_total; + integer fail_test_cnt; + integer pass_test_cnt; + reg [(128*8)-1:0] hex_file; + reg [(128*8)-1:0] s19_file; + + + integer model_cycle_cnt; + wire model_error; + wire [7:0] model_output_port; + wire [7:0] dut_output_port; + + //////////////////////////////////////////////////////////////////////////// + // Dump VCD + //////////////////////////////////////////////////////////////////////////// + reg [(128*8)-1:0] vcd_file_name; + integer dump_idx; + initial + begin + if ($value$plusargs("dump_vcd=%s", vcd_file_name)) begin + $dumpfile(vcd_file_name); + $dumpvars(0,tb_dv_top); + /* + for (dump_idx = 0; dump_idx < 7; dump_idx = dump_idx + 1) begin + $dumpvars(0, I_soc_top_r.I_turbo9_r.I_turbo9_pipeline.I_turbo9_fetch_stage.I_turbo9_fetch_queue.queue_data_nxt[dump_idx]); + $dumpvars(0, I_soc_top_r.I_turbo9_r.I_turbo9_pipeline.I_turbo9_fetch_stage.I_turbo9_fetch_queue.queue_data_reg[dump_idx]); + $dumpvars(0, I_soc_top_r.I_turbo9_r.I_turbo9_pipeline.I_turbo9_fetch_stage.I_turbo9_fetch_queue.queue_data_shift4[dump_idx]); + $dumpvars(0, I_soc_top_r.I_turbo9_r.I_turbo9_pipeline.I_turbo9_fetch_stage.I_turbo9_fetch_queue.queue_data_shift2[dump_idx]); + $dumpvars(0, I_soc_top_r.I_turbo9_r.I_turbo9_pipeline.I_turbo9_fetch_stage.I_turbo9_fetch_queue.queue_data_shift1[dump_idx]); + end + + for (dump_idx = 16'h2000; dump_idx < 16'h3000; dump_idx = dump_idx + 1) begin + $dumpvars(0, `model_mem[dump_idx]); + $dumpvars(0, `dut_mem[dump_idx]); + //$dumpvars(0, `tb_mem[dump_idx]); + end + + for (dump_idx = (2**`MEM_ADDR_WIDTH)-4096; dump_idx < (2**`MEM_ADDR_WIDTH); dump_idx = dump_idx + 1) begin + $dumpvars(0, `model_mem[dump_idx]); + $dumpvars(0, `dut_mem[dump_idx]); + //$dumpvars(0, `tb_mem[dump_idx]); + end + */ + end + end + + + //////////////////////////////////////////////////////////////////////////// + // Generate Clock + //////////////////////////////////////////////////////////////////////////// + initial begin + sysclk = 1'b0; + + fork + forever begin + #5000 sysclk = ~sysclk; + end + // Add more clocks here + join + end + + ///////////////////////////////////////////////////////////////////////////// + // Testbench "Main" + ///////////////////////////////////////////////////////////////////////////// + initial begin + + /////////// Initialize global variables / signals + // + pass_test_cnt = 0; + fail_test_cnt = 0; + reset = 1'b1; + + + $display("[TB; tb_dv_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_dv_top ] // Turbo9 Testbench "); + $display("[TB; tb_dv_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_dv_top ]"); + + + /////////// Initialize global variables / signals from the command line + // + // Defaults + seed = 123; + rand_itr_total = 4; + hex_file = ""; + s19_file = ""; + // + if ($value$plusargs("seed=%0d", seed)); + if ($value$plusargs("rand_itr=%0d", rand_itr_total)); + if ($value$plusargs("hex_file=%s", hex_file)); + if ($value$plusargs("s19_file=%s", s19_file)); + + $display("[TB; tb_dv_top ] Random seed value = %0d", seed); + $display("[TB; tb_dv_top ] Random iterations = %0d", rand_itr_total); + $display("[TB; tb_dv_top ] HEX file = %0s", hex_file); + $display("[TB; tb_dv_top ] S19 file = %0s", s19_file); + $display("[TB; tb_dv_top ]"); + + + + /////////// Run selected tests + // + if ($test$plusargs("tc_dv_dir_instr")) begin // Direct Addressing Test + tc_dv_dir_instr; + end + // + if ($test$plusargs("tc_dv_ext_instr")) begin // Extended Addressing Test + tc_dv_ext_instr; + end + // + if ($test$plusargs("tc_dv_imm_instr")) begin // Immediate Addressing Test + tc_dv_imm_instr; + end + // + if ($test$plusargs("tc_dv_rel_instr")) begin // Relative Addressing Test + tc_dv_rel_instr; + end + // + if ($test$plusargs("tc_dv_rel16_instr")) begin // Long Relative Addressing Test + tc_dv_rel16_instr; + end + // + if ($test$plusargs("tc_dv_run_code")) begin // Run HEX or S19 Code + tc_dv_run_code; + end + // + if ($test$plusargs("tc_dv_inh_instr")) begin // Inherent Addressing Test + tc_dv_inh_instr; + end + // + if ($test$plusargs("tc_dv_sau_instr")) begin // Sequential Arithmetic Test + tc_dv_sau_instr; + end + // + if ($test$plusargs("tc_dv_idx_a_instr")) begin // Indexed A Offset Addressing Test + tc_dv_idx_a_instr; + end + // + if ($test$plusargs("tc_dv_idx_b_instr")) begin // Indexed B Offset Addressing Test + tc_dv_idx_b_instr; + end + // + if ($test$plusargs("tc_dv_idx_d_instr")) begin // Indexed D Offset Addressing Test + tc_dv_idx_d_instr; + end + // + if ($test$plusargs("tc_dv_idx_0b_instr")) begin // Indexed No Offset Addressing Test + tc_dv_idx_0b_instr; + end + // + if ($test$plusargs("tc_dv_idx_5b_instr")) begin // Indexed 5bit Offset Addressing Test + tc_dv_idx_5b_instr; + end + // + if ($test$plusargs("tc_dv_idx_8b_instr")) begin // Indexed 8bit Offset Addressing Test + tc_dv_idx_8b_instr; + end + // + if ($test$plusargs("tc_dv_idx_16b_instr")) begin // Indexed 16bit Offset Addressing Test + tc_dv_idx_16b_instr; + end + // + // + if ($test$plusargs("tc_dv_idx_p1_instr")) begin // Indexed Auto Increment by 1 Addressing Test + tc_dv_idx_p1_instr; + end + // + if ($test$plusargs("tc_dv_idx_p2_instr")) begin // Indexed Auto Increment by 2 Addressing Test + tc_dv_idx_p2_instr; + end + // + if ($test$plusargs("tc_dv_idx_m1_instr")) begin // Indexed Auto Increment by 1 Addressing Test + tc_dv_idx_m1_instr; + end + // + if ($test$plusargs("tc_dv_idx_m2_instr")) begin // Indexed Auto Increment by 2 Addressing Test + tc_dv_idx_m2_instr; + end + // + if ($test$plusargs("tc_dv_idx_pc8_instr")) begin // Indexed PC 8-bit Offset Addressing Test + tc_dv_idx_pc8_instr; + end + if ($test$plusargs("tc_dv_idx_pc16_instr")) begin // Indexed PC 16-bit Offset Addressing Test + tc_dv_idx_pc16_instr; + end + if ($test$plusargs("tc_dv_ind_0b_instr")) begin // Indexed Indirect Addressing Test + tc_dv_ind_0b_instr; + end + if ($test$plusargs("tc_dv_ind_8b_instr")) begin // Indexed 8-bit Indirect Addressing Test + tc_dv_ind_8b_instr; + end + if ($test$plusargs("tc_dv_ind_16b_instr")) begin // Indexed 16-bit Indirect Addressing Test + tc_dv_ind_16b_instr; + end + if ($test$plusargs("tc_dv_ind_a_instr")) begin // Indexed A Offset Indirect Addressing Test + tc_dv_ind_a_instr; + end + if ($test$plusargs("tc_dv_ind_b_instr")) begin // Indexed B Offset Indirect Addressing Test + tc_dv_ind_b_instr; + end + if ($test$plusargs("tc_dv_ind_d_instr")) begin // Indexed D Offset Indirect Addressing Test + tc_dv_ind_d_instr; + end + if ($test$plusargs("tc_dv_ind_p2_instr")) begin // Indexed Auto Increment by 2 Indirect Addressing Test + tc_dv_ind_p2_instr; + end + if ($test$plusargs("tc_dv_ind_m2_instr")) begin // Indexed Auto Increment by 2 Indirect Addressing Test + tc_dv_ind_m2_instr; + end + if ($test$plusargs("tc_dv_ind_pc8_instr")) begin // Indexed Auto Increment by 2 Indirect Addressing Test + tc_dv_ind_pc8_instr; + end + if ($test$plusargs("tc_dv_ind_pc16_instr")) begin // Indexed Auto Increment by 2 Indirect Addressing Test + tc_dv_ind_pc16_instr; + end + if ($test$plusargs("tc_dv_exg_8b_instr")) begin // Exchange 8-bit Registers Test + tc_dv_exg_8b_instr; + end + if ($test$plusargs("tc_dv_exg_16b_instr")) begin // Exchange 16-bit Registers Test + tc_dv_exg_16b_instr; + end + if ($test$plusargs("tc_dv_tfr_8b_instr")) begin // Exchange 8-bit Registers Test + tc_dv_tfr_8b_instr; + end + if ($test$plusargs("tc_dv_tfr_16b_instr")) begin // Exchange 16-bit Registers Test + tc_dv_tfr_16b_instr; + end + if ($test$plusargs("debug_random")) begin // debug random + debug_random; + end + + + $display("[TB; tb_dv_top ]"); + $display("[TB; tb_dv_top ]"); + $display("[TB; tb_dv_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_dv_top ] // Turbo9 Testbench Summary"); + $display("[TB; tb_dv_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_dv_top ]"); + $display("[TB; tb_dv_top ] Number of passing tests: %0d", pass_test_cnt); + $display("[TB; tb_dv_top ] Number of failing tests: %0d", fail_test_cnt); + $display("[TB; tb_dv_top ]"); + if(fail_test_cnt > 0 || pass_test_cnt == 0) begin + $display("[TB; tb_dv_top ] Testbench FAIL!"); + end else begin + $display("[TB; tb_dv_top ] Testbench PASS!"); + end + $display("[TB; tb_dv_top ]"); + + $finish(); + + end + + + ///////////////////////////////////////////////////////////////////////////// + // DUT + ///////////////////////////////////////////////////////////////////////////// + + reg turbo9_rst_meta; + reg turbo9_rst_sync; + + always @(posedge reset or posedge sysclk) + begin + if (reset) begin + turbo9_rst_meta <= 1'b1; + turbo9_rst_sync <= 1'b1; + end else begin + turbo9_rst_meta <= 1'b0; + turbo9_rst_sync <= turbo9_rst_meta; + end + end + +`ifdef TURBO9_R + soc_top_r + #( + `MEM_ADDR_WIDTH // MEM_ADDR_WIDTH + ) + I_soc_top_r +`elsif TURBO9_S + soc_top_s + #( + `MEM_ADDR_WIDTH // MEM_ADDR_WIDTH + ) + I_soc_top_s +`else + soc_top + #( + `MEM_ADDR_WIDTH // MEM_ADDR_WIDTH + ) + I_soc_top +`endif + ( + // Inputs: Clock & Reset + .RST_I (turbo9_rst_sync), // Reset. Active high and synchronized to CLK_I + .CLK_I (sysclk), // Clock + // + // Inputs + .RXD_PIN_I (1'b1), + + // Outputs + .TXD_PIN_O (), + .OUTPUT_PORT_O (dut_output_port) + ); + + ///////////////////////////////////////////////////////////////////////////// + // 6809 Behavioral Model + ///////////////////////////////////////////////////////////////////////////// + tb_dv_6809_model + #( + `MEM_ADDR_WIDTH, // MEM_ADDR_WIDTH + 0, // BREAK_COM_DIR_OP + ) + I_tb_dv_6809_model + ( + // Inputs: Clock & Reset + .RST_N_I (~reset), + .CLK_I (sysclk), + + // Inputs + .QUIET_I (1'b1), + .FAST_CLK_I (1'b1), + + + // Outputs + .E_CLK_O (), + .Q_CLK_O (), + .ERROR_O (model_error), + .OUTPUT_PORT_O (model_output_port), + .CYCLE_CNT_O (model_cycle_cnt) + ); + + + ///////////////////////////////////////////////////////////////////////////// + // Broken 6809 Behavioral Model + ///////////////////////////////////////////////////////////////////////////// + /* + tb_dv_6809_model + #( + `MEM_ADDR_WIDTH, // MEM_ADDR_WIDTH + 1, // BREAK_COM_DIR_OP + ) + I_broken_6809_model + ( + // Inputs: Clock & Reset + .RST_N_I (~reset), + .CLK_I (sysclk), + + // Inputs + .QUIET_I (1'b1), + .FAST_CLK_I (1'b1), + + // Outputs + .E_CLK_O (), + .Q_CLK_O (), + .ERROR_O (), + .OUTPUT_PORT_O (dut_output_port) + ); + */ + ///////////////////////////////////////////////////////////////////////////// + // Testbench Memory + ///////////////////////////////////////////////////////////////////////////// + tb_dv_memory + #( + `MEM_ADDR_WIDTH + ) + I_tb_dv_memory (); + + always @(posedge sysclk) + begin + if ((dut_output_port[1]) && (~dut_output_port[6]) && ((`dut_cycle_cnt % 100_000) == 0)) begin + $display("[TB: tb_dv_top ] DUT clock cycle count: %d", `dut_cycle_cnt); + end + if ((model_output_port[1]) && (~model_output_port[6]) && ((model_cycle_cnt % 100_000) == 0)) begin + $display("[TB: tb_dv_top ] Model E clock cycle count: %d", model_cycle_cnt); + + + end + end + + //////////////////////////////////////////////////////////////////////////// + // Console File Output + //////////////////////////////////////////////////////////////////////////// + integer model_console_file_ptr; + integer dut_console_file_ptr; + reg console_output_en; + integer putchar_en_addr; + integer putchar_buf_addr; + + initial begin + console_output_en = 1'b0; + putchar_en_addr = `asm_sim_putchar_en-((2**16)-(2**`MEM_ADDR_WIDTH)); + putchar_buf_addr = `asm_sim_putchar_buf-((2**16)-(2**`MEM_ADDR_WIDTH)); + end + + task console_file_open(input [(32*8)-1:0] test_name); + reg [(64*8)-1:0] console_file_name; + begin + $sformat(console_file_name,"%0s.model.console.txt",test_name); + model_console_file_ptr = $fopen(console_file_name,"w"); + $display("[TB: console_file_open] Opening %0s for console output", console_file_name); + // + $sformat(console_file_name,"%0s.dut.console.txt",test_name); + dut_console_file_ptr = $fopen(console_file_name,"w"); + $display("[TB: console_file_open] Opening %0s for console output", console_file_name); + // + console_output_en = 1'b1; + end + endtask + + task console_file_close; + begin + $fclose(model_console_file_ptr); + $fclose(dut_console_file_ptr); + end + endtask + + wire model_putchar_en = `model_mem[putchar_en_addr][0] & console_output_en; + wire [7:0] model_putchar_buf = `model_mem[putchar_buf_addr]; + +`ifdef TURBO9_R + wire dut_putchar_en = (~putchar_en_addr[0]) ? (`dut_mem_even[putchar_en_addr[15:1]][0] & console_output_en) : + (`dut_mem_odd [putchar_en_addr[15:1]][0] & console_output_en) ; + + wire [7:0] dut_putchar_buf = (~putchar_buf_addr[0]) ? `dut_mem_even[putchar_buf_addr[15:1]] : + `dut_mem_odd [putchar_buf_addr[15:1]] ; +`elsif TURBO9_S + wire dut_putchar_en = (~putchar_en_addr[0]) ? (`dut_mem_even[putchar_en_addr[15:1]][0] & console_output_en) : + (`dut_mem_odd [putchar_en_addr[15:1]][0] & console_output_en) ; + + wire [7:0] dut_putchar_buf = (~putchar_buf_addr[0]) ? `dut_mem_even[putchar_buf_addr[15:1]] : + `dut_mem_odd [putchar_buf_addr[15:1]] ; +`else + wire dut_putchar_en = `dut_mem[putchar_en_addr][0] & console_output_en; + wire [7:0] dut_putchar_buf = `dut_mem[putchar_buf_addr]; +`endif + + always @(posedge model_putchar_en) + begin + $fwrite(model_console_file_ptr,"%0s", model_putchar_buf); + end + + always @(posedge dut_putchar_en) + begin + $fwrite(dut_console_file_ptr,"%0s", dut_putchar_buf); + end + +endmodule + diff --git a/turbo9team_turbo9/tb/tb_stim_flags.v b/turbo9team_turbo9/tb/tb_stim_flags.v new file mode 100644 index 0000000000000000000000000000000000000000..d1ea29aabca9704c917b5dd1e7c6d6d1744d290a --- /dev/null +++ b/turbo9team_turbo9/tb/tb_stim_flags.v @@ -0,0 +1,144 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Stimbench: simple simulation of flag logic +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Test Flags +///////////////////////////////////////////////////////////////////////////// + +task tb_stim_flags; + + integer idx_a, idx_b, idx_c; + + reg signed [1:0] s2_a, s2_b, s2_y; + reg signed [2:0] s3_y; + reg unsigned [1:0] u2_a, u2_b, u2_y; + reg unsigned [2:0] u3_y; + reg cin, vout, cout; + +begin + $display("[TB; tb_stim_flags ] Signed 2bit Addition"); + s2_a = 0; + for (idx_a=0; idx_a<4; idx_a=idx_a+1) begin + s2_b = 0; + for (idx_b=0; idx_b<4; idx_b=idx_b+1) begin + cin = 0; + for (idx_c=0; idx_c<2; idx_c=idx_c+1) begin + s3_y = {s2_a[1], s2_a} + {s2_b[1], s2_b} + {2'b00, cin}; + {cout, s2_y} = {1'b0, s2_a} + {1'b0, s2_b} + {2'b00, cin}; + //vout = cout^( s2_a[ 1] ^ s2_b[ 1] ^ s2_y[ 1]); + vout = ( s2_a[ 1] & s2_b[ 1] & ~s2_y[ 1]) | + (~s2_a[ 1] & ~s2_b[ 1] & s2_y[ 1]) ; + $display("[TB; tb_stim_flags ] %2d + %2d + %d = %2d (correct: %2d) ; %b + %b + %b = %b FLAG: %b V: %b", s2_a, s2_b, cin, s2_y, s3_y, s2_a, s2_b, cin, s2_y, (s3_y != {s2_y[1], s2_y}), vout); + cin++; + end + s2_b++; + end + s2_a++; + end + + $display("[TB; tb_stim_flags ] "); + $display("[TB; tb_stim_flags ] Signed 2bit Subtraction"); + s2_a = 0; + for (idx_a=0; idx_a<4; idx_a=idx_a+1) begin + s2_b = 0; + for (idx_b=0; idx_b<4; idx_b=idx_b+1) begin + cin = 0; + for (idx_c=0; idx_c<2; idx_c=idx_c+1) begin + s3_y = {s2_a[1], s2_a} - {s2_b[1], s2_b} - {2'b00, cin}; + s2_y = s2_a + ~s2_b + {1'b0, ~cin}; + vout = ( s2_a[ 1] & ~s2_b[ 1] & ~s2_y[ 1]) | + (~s2_a[ 1] & s2_b[ 1] & s2_y[ 1]) ; + $display("[TB; tb_stim_flags ] %2d - %2d - %d = %2d (correct: %2d) ; %b + %b + %b = %b FLAG: %b V: %b", s2_a, s2_b, cin, s2_y, s3_y, s2_a, s2_b, cin, s2_y, (s3_y != {s2_y[1], s2_y}), vout); + cin++; + end + s2_b++; + end + s2_a++; + end + + $display("[TB; tb_stim_flags ] "); + $display("[TB; tb_stim_flags ] Unsigned 2bit Addition"); + u2_a = 0; + for (idx_a=0; idx_a<4; idx_a=idx_a+1) begin + u2_b = 0; + for (idx_b=0; idx_b<4; idx_b=idx_b+1) begin + cin = 0; + for (idx_c=0; idx_c<2; idx_c=idx_c+1) begin + u3_y = {1'b0, u2_a} + {1'b0, u2_b} + {2'b00, cin}; + u2_y = u2_a + u2_b + {1'b0, cin}; + cout = ( u2_a[ 1] & u2_b[ 1] ) | + ( u2_b[ 1] & ~u2_y[ 1]) | + ( u2_a[ 1] & ~u2_y[ 1]) ; + $display("[TB; tb_stim_flags ] %2d + %2d + %d = %2d (correct: %2d) ; %b + %b + %b = %b FLAG: %b C: %b", u2_a, u2_b, cin, u2_y, u3_y, u2_a, u2_b, cin, u2_y, (u3_y != {1'b0, u2_y}), cout); + cin++; + end + u2_b++; + end + u2_a++; + end + + $display("[TB; tb_stim_flags ] "); + $display("[TB; tb_stim_flags ] Unsigned 2bit Subtraction"); + u2_a = 0; + for (idx_a=0; idx_a<4; idx_a=idx_a+1) begin + u2_b = 0; + for (idx_b=0; idx_b<4; idx_b=idx_b+1) begin + cin = 0; + for (idx_c=0; idx_c<2; idx_c=idx_c+1) begin + u3_y = {1'b0, u2_a} - {1'b0, u2_b} - {2'b00, cin}; + u2_y = u2_a + ~u2_b + {1'b0, ~cin}; + cout = (~u2_a[ 1] & u2_b[ 1] ) | + ( u2_b[ 1] & u2_y[ 1]) | + (~u2_a[ 1] & u2_y[ 1]) ; + $display("[TB; tb_stim_flags ] %2d - %2d - %d = %2d (correct: %2d) ; %b + %b + %b = %b FLAG: %b C: %b", u2_a, u2_b, cin, u2_y, u3_y, u2_a, u2_b, cin, u2_y, (u3_y != {1'b0, u2_y}), cout); + cin++; + end + u2_b++; + end + u2_a++; + end + +end +endtask diff --git a/turbo9team_turbo9/tb/tb_stim_fpga.v b/turbo9team_turbo9/tb/tb_stim_fpga.v new file mode 100644 index 0000000000000000000000000000000000000000..1213a2898286160834274b5b7799df58232be735 --- /dev/null +++ b/turbo9team_turbo9/tb/tb_stim_fpga.v @@ -0,0 +1,107 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Stimbench: simple simulation of fpga_top +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Test FPGA +///////////////////////////////////////////////////////////////////////////// + `define FPGA_CYCLES 200_000 + +task tb_stim_fpga; + + integer i; + +begin + + fpga_reset = 1'b1; + for (i=0; i<4; i=i+1) begin + @ (posedge sys_clk); + end + + fpga_reset = 1'b0; + $display("[TB; tb_stim_fpga ] Releasing fpga_reset..."); + $display("[TB; tb_stim_fpga ] Running clock for %0d cycles", `FPGA_CYCLES); + for (i=0; i<`FPGA_CYCLES; i=i+1) begin + @ (posedge sys_clk); + end + +end +endtask + +wire loop_back; + + ///////////////////////////////////////////////////////////////////////////// + // DUT + ///////////////////////////////////////////////////////////////////////////// + fpga_top I_fpga_top + ( + // Inputs: Clock & Reset + .CLK100MHZ (sys_clk), + .ck_rst (~fpga_reset), //active low + + // Inputs + .uart_txd_in (loop_back), + + // Outputs + .uart_rxd_out (loop_back), + + // Outputs + .led (), + .led0_b (), + .led0_g (), + .led0_r (), + .led1_b (), + .led1_g (), + .led1_r (), + .led2_b (), + .led2_g (), + .led2_r (), + .led3_b (), + .led3_g (), + .led3_r () + ); + + + + diff --git a/turbo9team_turbo9/tb/tb_stim_mul_div.v b/turbo9team_turbo9/tb/tb_stim_mul_div.v new file mode 100644 index 0000000000000000000000000000000000000000..9d9c7c6807b560dde783d41adfa85fca0007127a --- /dev/null +++ b/turbo9team_turbo9/tb/tb_stim_mul_div.v @@ -0,0 +1,106 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Stimbench: simple simulation of multiply divide algrorithms +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Test SAU +///////////////////////////////////////////////////////////////////////////// + `define SAU_CYCLES 10 + reg mul_div_reset; + reg mul_div_en; + +task tb_stim_mul_div; + + integer i; + +begin + mul_div_en = 1'b0; + mul_div_reset = 1'b1; + for (i=0; i<4; i=i+1) begin + @ (posedge sys_clk); + end + + mul_div_reset = 1'b0; + $display("[TB; tb_stim_mul_div ] Releasing mul_div_reset..."); + + @ (posedge sys_clk); + mul_div_en = 1'b1; + + @ (posedge sys_clk); + mul_div_en = 1'b0; + + $display("[TB; tb_stim_mul_div ] Running clock for %0d cycles", `SAU_CYCLES); + for (i=0; i<`SAU_CYCLES; i=i+1) begin + @ (posedge sys_clk); + end + +end +endtask + + + + ///////////////////////////////////////////////////////////////////////////// + // DUT + ///////////////////////////////////////////////////////////////////////////// + turbo9_seq_arithmetic_unit I_turbo9_seq_arithmetic_unit + ( + // Inputs: Clock & Reset + .CLK_I (sys_clk), + .RST_I (mul_div_reset), + .STALL_MICROCYCLE_I (1'b0), + + .SAU_EN_I (mul_div_en), + .SAU_OP_I (1'b1), + + .CCR_H_I (1'b1), + .CCR_C_I (1'b0), + + .SAU_ABXY_I (48'h80ff_0000_0000), + + .SAU_Y_O (), + .SAU_DONE_O (), + .SAU_C_BIT_O () + ); + + diff --git a/turbo9team_turbo9/tb/tb_stim_top.v b/turbo9team_turbo9/tb/tb_stim_top.v new file mode 100644 index 0000000000000000000000000000000000000000..77f06e4a0bb8525acfc2139a3d781e69f1cb06ab --- /dev/null +++ b/turbo9team_turbo9/tb/tb_stim_top.v @@ -0,0 +1,178 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Stimbench: Top level +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Top Level Of Turbo9 Testbench +///////////////////////////////////////////////////////////////////////////// +`timescale 1ps/1ps + +module tb_stim_top; + + ///////////////////// Select one of the following: + //`define TURBO9 + //`define TURBO9_S + `define TURBO9_R + ///////////////////// + + `define MEM_ADDR_WIDTH 15 //32 Kbyte Memory, adjust the asm accordingly + + +`ifdef TURBO9_R + `define dut_mem_even I_fpga_top.I_soc_top_r.I_even_syncram_8bit.ram + `define dut_mem_odd I_fpga_top.I_soc_top_r.I_odd_syncram_8bit.ram +`elsif TURBO9_S + `define dut_mem_even I_fpga_top.I_soc_top_r.I_even_syncram_8bit.ram + `define dut_mem_odd I_fpga_top.I_soc_top_r.I_odd_syncram_8bit.ram +`else + `define dut_mem I_fpga_top.I_soc_top.I_syncram_8bit.ram +`endif + + + reg sys_clk; + reg fpga_reset; + + `include "tb_stim_flags.v" // Flags + `include "tb_stim_fpga.v" // FPGA + //`include "tb_stim_mul_div.v" // MUL_DIV + + integer seed; + integer rand_itr_total; + + //////////////////////////////////////////////////////////////////////////// + // Dump VCD + //////////////////////////////////////////////////////////////////////////// + reg [(128*8)-1:0] vcd_file_name; + integer dump_idx; + initial + begin + if ($value$plusargs("dump_vcd=%s", vcd_file_name)) begin + $dumpfile(vcd_file_name); + $dumpvars(0,tb_stim_top); + /* + for (dump_idx = 16'h2000; dump_idx < 16'h3000; dump_idx = dump_idx + 1) begin + $dumpvars(0, `dut_mem[dump_idx]); + //$dumpvars(0, `tb_mem[dump_idx]); + end + + for (dump_idx = (2**`MEM_ADDR_WIDTH)-4096; dump_idx < (2**`MEM_ADDR_WIDTH); dump_idx = dump_idx + 1) begin + $dumpvars(0, `dut_mem[dump_idx]); + //$dumpvars(0, `tb_mem[dump_idx]); + end + */ + end + end + + + + //////////////////////////////////////////////////////////////////////////// + // Generate Clock + //////////////////////////////////////////////////////////////////////////// + initial begin + sys_clk = 1'b0; + + fork + forever begin + #5000 sys_clk = ~sys_clk; + end + // Add more clocks here + join + end + + ///////////////////////////////////////////////////////////////////////////// + // Testbench "Main" + ///////////////////////////////////////////////////////////////////////////// + initial begin + + fpga_reset = 1'b1; + + $display("[TB; tb_stim_top ]"); + $display("[TB; tb_stim_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_stim_top ] // Turbo9 Stim Bench Start"); + $display("[TB; tb_stim_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_stim_top ]"); + + + /////////// Initialize global variables / signals from the command line + // + seed = 123; // default + if ($value$plusargs ("seed=%0d", seed)); + // + rand_itr_total = 4; // default + if ($value$plusargs ("rand_itr=%0d", rand_itr_total)); + + $display("[TB; tb_stim_top ] Random seed value = %0d", seed); + $display("[TB; tb_stim_top ] Random iterations = %0d", rand_itr_total); + $display("[TB; tb_stim_top ]"); + + + + /////////// Run selected tests + // + if ($test$plusargs("tb_stim_flags")) begin // Test Flags + tb_stim_flags; + end + // + if ($test$plusargs("tb_stim_fpga")) begin // Test FPGA + tb_stim_fpga; + end + // + //if ($test$plusargs("tb_stim_mul_div")) begin // Test MUL_DIV + // tb_stim_mul_div; + //end + + + $display("[TB; tb_stim_top ]"); + $display("[TB; tb_stim_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_stim_top ] // Turbo9 Stim Bench End"); + $display("[TB; tb_stim_top ] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tb_stim_top ]"); + + + $finish(); + + end + + +endmodule diff --git a/turbo9team_turbo9/tb/tc_dv_dir_instr.v b/turbo9team_turbo9/tb/tc_dv_dir_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..b37e32884e3ba539aac51bb42f6d1ba7cf430a12 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_dir_instr.v @@ -0,0 +1,331 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testcase: Direct instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Direct Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_DIR_TOTAL_INSTR 50 + `define TEST_DIR_RESET_CYCLES 40 // (16 nominal) + `define TEST_DIR_START_CYCLES 200 // (100 nominal) + `define TEST_DIR_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_dir_instr; + + reg [15:0] addr_ptr; + reg [15:0] dir_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer dir_instr_list [0:`TEST_DIR_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // dir_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + dir_instr_list[ 0] = 'h00_2_1_00_00; // NEG + //dir_instr_list[] = 'h00_2_1_00_01; // + //dir_instr_list[] = 'h00_2_1_00_02; // + dir_instr_list[ 1] = 'h00_2_1_00_03; // COM + dir_instr_list[ 2] = 'h00_2_1_00_04; // LSR + //dir_instr_list[] = 'h00_2_1_00_05; // + dir_instr_list[ 3] = 'h00_2_1_00_06; // ROR + dir_instr_list[ 4] = 'h00_2_1_00_07; // ASR + dir_instr_list[ 5] = 'h00_2_1_00_08; // ASL,LSL + dir_instr_list[ 6] = 'h00_2_1_00_09; // ROL + dir_instr_list[ 7] = 'h00_2_1_00_0A; // DEC + //dir_instr_list[] = 'h00_2_1_00_0B; // + dir_instr_list[ 8] = 'h00_2_1_00_0C; // INC + dir_instr_list[ 9] = 'h00_2_1_00_0D; // TST + //dir_instr_list[] = 'h00_2_2_00_0E; // JMP (different test) + dir_instr_list[10] = 'h00_2_1_00_0F; // CLR + + dir_instr_list[11] = 'h00_2_1_00_90; // SUBA + dir_instr_list[12] = 'h00_2_1_00_91; // CMPA + dir_instr_list[13] = 'h00_2_1_00_92; // SBCA + dir_instr_list[14] = 'h00_2_2_00_93; // SUBD + dir_instr_list[15] = 'h00_2_1_00_94; // ANDA + dir_instr_list[16] = 'h00_2_1_00_95; // BITA + dir_instr_list[17] = 'h00_2_1_00_96; // LDA + dir_instr_list[18] = 'h00_2_1_00_97; // STA + dir_instr_list[19] = 'h00_2_1_00_98; // EORA + dir_instr_list[20] = 'h00_2_1_00_99; // ADCA + dir_instr_list[21] = 'h00_2_1_00_9A; // ORA + dir_instr_list[22] = 'h00_2_1_00_9B; // ADDA + dir_instr_list[23] = 'h00_2_2_00_9C; // CMPX + //dir_instr_list[] = 'h00_2_2_00_9D; // JSR (different test) + dir_instr_list[24] = 'h00_2_2_00_9E; // LDX + dir_instr_list[25] = 'h00_2_2_00_9F; // STX + + dir_instr_list[26] = 'h00_2_1_00_D0; // SUBB + dir_instr_list[27] = 'h00_2_1_00_D1; // CMPB + dir_instr_list[28] = 'h00_2_1_00_D2; // SBCB + dir_instr_list[29] = 'h00_2_2_00_D3; // ADDD + dir_instr_list[30] = 'h00_2_1_00_D4; // ANDB + dir_instr_list[31] = 'h00_2_1_00_D5; // BITB + dir_instr_list[32] = 'h00_2_1_00_D6; // LDB + dir_instr_list[33] = 'h00_2_1_00_D7; // STB + dir_instr_list[34] = 'h00_2_1_00_D8; // EORB + dir_instr_list[35] = 'h00_2_1_00_D9; // ADCB + dir_instr_list[36] = 'h00_2_1_00_DA; // ORB + dir_instr_list[37] = 'h00_2_1_00_DB; // ADDB + dir_instr_list[38] = 'h00_2_2_00_DC; // LDD + dir_instr_list[39] = 'h00_2_2_00_DD; // STD + dir_instr_list[40] = 'h00_0_2_00_DE; // LDU + dir_instr_list[41] = 'h00_0_2_00_DF; // STU + + // Page 2 + dir_instr_list[42] = 'h00_2_2_10_93; // CMPD + dir_instr_list[43] = 'h00_2_2_10_9C; // CMPY + dir_instr_list[44] = 'h00_2_2_10_9E; // LDY + dir_instr_list[45] = 'h00_2_2_10_9F; // STY + dir_instr_list[46] = 'h00_1_2_10_DE; // LDS + dir_instr_list[47] = 'h00_1_2_10_DF; // STS + + // Page 3 + dir_instr_list[48] = 'h00_0_2_11_93; // CMPU + dir_instr_list[49] = 'h00_1_2_11_9C; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_DIR_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = dir_instr_list[instr_idx][ 7: 0]; + prebyte = dir_instr_list[instr_idx][15: 8]; + operand_size = dir_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_dir_instr]"); + $display("[TB: tc_dv_dir_instr]"); + $display("[TB: tc_dv_dir_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_dir_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_dir_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_dir_instr]"); + $write("[TB: tc_dv_dir_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(dir_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_dir_instr] Loading testbench template: %0s",hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_dir_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 42 neg "); + case(lsn) + 'b000: $write("D"); + 'b001: $write("X"); + 'b010: $write("Y"); + 'b011: $write("US"); + 'b100: $write("SP"); + endcase + $display(""); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_exg_16b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_exg_16b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_EXG_16_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_exg_16b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_exg_16b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_EXG_16_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_exg_16b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_EXG_16_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_exg_16b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_exg_16b_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_exg_16b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_exg_16b_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_exg_16b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_exg_16b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_exg_8b_instr.v b/turbo9team_turbo9/tb/tc_dv_exg_8b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..44075f0ca0fe9a0d69a9046fd8cd84fc10788127 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_exg_8b_instr.v @@ -0,0 +1,262 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Exchange instruction w/ 8-bit registers +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Inherent Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_EXG_8_TOTAL_INSTR 1 + `define TEST_EXG_8_RESET_CYCLES 40 // (16 nominal) + `define TEST_EXG_8_START_CYCLES 200 // (100 nominal) + `define TEST_EXG_8_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_exg_8b_instr; + + reg [15:0] addr_ptr; + reg [15:0] inh_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer inh_instr_list [0:`TEST_EXG_8_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + reg [ 3:0] msn; + reg [ 3:0] lsn; + + begin + // inh_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + inh_instr_list[0] = 'h00_2_1_00_1E; // EXG_8 + + for (instr_idx = 0; instr_idx < `TEST_EXG_8_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = inh_instr_list[instr_idx][ 7: 0]; + prebyte = inh_instr_list[instr_idx][15: 8]; + operand_size = inh_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_exg_8b_instr]"); + $display("[TB: tc_dv_exg_8b_instr]"); + $display("[TB: tc_dv_exg_8b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_exg_8b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_exg_8b_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_exg_8b_instr]"); + $write("[TB: tc_dv_exg_8b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(inh_instr_list[instr_idx][21:20]); + + // Get a random number to use to select bits for most and least significant bits of exchange postbyte. + rand32 = {$random(seed)}; + msn = rand32[31:29] % 3; // we can only use values between 0 and 3. + lsn = rand32[28:26] % 3; // same as above. + msn[3] = 1'b1; // append the top one bit to indicate 8-bit registers for exchange. + lsn[3] = 1'b1; + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_exg_8b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_exg_8b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 1E 89 exg a,b + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Write the postbyte to the opcode + write_tb_mem8p(addr_ptr, {msn,lsn}); + addr_ptr++; + + case(msn) + 'b1000: $write("A"); + 'b1001: $write("B"); + 'b1010: $write("CCR"); + 'b1011: $write("DPR"); + endcase + $write(" <- exchanged with -> "); + case(lsn) + 'b1000: $write("A"); + 'b1001: $write("B"); + 'b1010: $write("CCR"); + 'b1011: $write("DPR"); + endcase + $display(""); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_exg_8b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_exg_8b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_EXG_8_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_exg_8b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_exg_8b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_EXG_8_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_exg_8b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_EXG_8_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_exg_8b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_exg_8b_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_exg_8b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_exg_8b_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_exg_8b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_exg_8b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ext_instr.v b/turbo9team_turbo9/tb/tc_dv_ext_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..ea47ddbf52958fd238b568c17129ab912a8ee255 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ext_instr.v @@ -0,0 +1,330 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Extended instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Extended Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_EXT_TOTAL_INSTR 50 + `define TEST_EXT_RESET_CYCLES 40 // (16 nominal) + `define TEST_EXT_START_CYCLES 200 // (100 nominal) + `define TEST_EXT_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ext_instr; + + reg [15:0] addr_ptr; + reg [15:0] ext_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ext_instr_list [0:`TEST_EXT_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // ext_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + ext_instr_list[ 0] = 'h00_2_1_00_70; // NEG + // 71 + // 72 + ext_instr_list[ 1] = 'h00_2_1_00_73; // COM + ext_instr_list[ 2] = 'h00_2_1_00_74; // LSR + // 75 + ext_instr_list[ 3] = 'h00_2_1_00_76; // ROR + ext_instr_list[ 4] = 'h00_2_1_00_77; // ASR + ext_instr_list[ 5] = 'h00_2_1_00_78; // ASL,LSL + ext_instr_list[ 6] = 'h00_2_1_00_79; // ROL + ext_instr_list[ 7] = 'h00_2_1_00_7A; // DEC + // 7B + ext_instr_list[ 8] = 'h00_2_1_00_7C; // INC + ext_instr_list[ 9] = 'h00_2_1_00_7D; // TST +// ext_instr_list[ ] = 'h00_2_1_00_7E; // JMP + ext_instr_list[10] = 'h00_2_1_00_7F; // CLR + ext_instr_list[11] = 'h00_2_1_00_B0; // SUBA + ext_instr_list[12] = 'h00_2_1_00_B1; // CMPA + ext_instr_list[13] = 'h00_2_1_00_B2; // SBCA + ext_instr_list[14] = 'h00_2_2_00_B3; // SUBD + ext_instr_list[15] = 'h00_2_1_00_B4; // ANDA + ext_instr_list[16] = 'h00_2_1_00_B5; // BITA + ext_instr_list[17] = 'h00_2_1_00_B6; // LDA + ext_instr_list[18] = 'h00_2_1_00_B7; // STA + ext_instr_list[19] = 'h00_2_1_00_B8; // EORA + ext_instr_list[20] = 'h00_2_1_00_B9; // ADCA + ext_instr_list[21] = 'h00_2_1_00_BA; // ORA + ext_instr_list[22] = 'h00_2_1_00_BB; // ADDA + ext_instr_list[23] = 'h00_2_2_00_BC; // CMPX +// ext_instr_list[ ] = 'h00_2_1_00_BD; // JSR + ext_instr_list[24] = 'h00_2_2_00_BE; // LDX + ext_instr_list[25] = 'h00_2_2_00_BF; // STX + ext_instr_list[26] = 'h00_2_1_00_F0; // SUBB + ext_instr_list[27] = 'h00_2_1_00_F1; // CMPB + ext_instr_list[28] = 'h00_2_1_00_F2; // SBCB + ext_instr_list[29] = 'h00_2_2_00_F3; // ADDD + ext_instr_list[30] = 'h00_2_1_00_F4; // ANDB + ext_instr_list[31] = 'h00_2_1_00_F5; // BITB + ext_instr_list[32] = 'h00_2_1_00_F6; // LDB + ext_instr_list[33] = 'h00_2_1_00_F7; // STB + ext_instr_list[34] = 'h00_2_1_00_F8; // EORB + ext_instr_list[35] = 'h00_2_1_00_F9; // ADCB + ext_instr_list[36] = 'h00_2_1_00_FA; // ORB + ext_instr_list[37] = 'h00_2_1_00_FB; // ADDB + ext_instr_list[38] = 'h00_2_2_00_FC; // LDD + ext_instr_list[39] = 'h00_2_2_00_FD; // STD + ext_instr_list[40] = 'h00_0_2_00_FE; // LDU + ext_instr_list[41] = 'h00_0_2_00_FF; // STU + + // Page 2 + ext_instr_list[42] = 'h00_2_2_10_B3; // CMPD + ext_instr_list[43] = 'h00_2_2_10_BC; // CMPY + ext_instr_list[44] = 'h00_2_2_10_BE; // LDY + ext_instr_list[45] = 'h00_2_2_10_BF; // STY + ext_instr_list[46] = 'h00_1_2_10_FE; // LDS + ext_instr_list[47] = 'h00_1_2_10_FF; // STS + + // Page 3 + ext_instr_list[48] = 'h00_0_2_11_B3; // CMPU + ext_instr_list[49] = 'h00_1_2_11_BC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_EXT_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ext_instr_list[instr_idx][ 7: 0]; + prebyte = ext_instr_list[instr_idx][15: 8]; + operand_size = ext_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ext_instr]"); + $display("[TB: tc_dv_ext_instr]"); + $display("[TB: tc_dv_ext_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ext_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ext_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ext_instr]"); + $write("[TB: tc_dv_ext_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(ext_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ext_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ext_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Save a pointer to the extended address + // + ext_addr_ptr = addr_ptr; + addr_ptr += 2; + $display("[TB: tc_dv_ext_instr] @ 0x%4x : This is the extended address location, saving. Will be updated after calculating effective address", ext_addr_ptr); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ext_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ext_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + + ///////////////// Write effective address to extended address + // + write_tb_mem16p(ext_addr_ptr, data_ea[15:0]); + $display("writing effective address to the extended address field in instruction"); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ext_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ext_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_EXT_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ext_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ext_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_EXT_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ext_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_EXT_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ext_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ext_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ext_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ext_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ext_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ext_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_0b_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_0b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..6e380d5880d771c2dc6b2dd6d46b24396bc16517 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_0b_instr.v @@ -0,0 +1,403 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed no offset instructions +// (reviewed 9/16/21) -KP +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_0B_TOTAL_INSTR 54 + `define TEST_IDX_0B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_0B_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_0B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_0b_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_0B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IDX_0B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_0b_instr]"); + $display("[TB: tc_dv_idx_0b_instr]"); + $display("[TB: tc_dv_idx_0b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_0b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_0b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_0b_instr]"); + $write("[TB: tc_dv_idx_0b_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE4; + u_sel: post_byte = 'hC4; + y_sel: post_byte = 'hA4; + x_sel: post_byte = 'h84; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_0b_instr]"); + $write("[TB: tc_dv_idx_0b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_0b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_0b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 84 neg ,x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + // Save address pointer, increment past post-byte + //idx_addr_ptr = addr_ptr; + addr_ptr++; + $display("Writing post-byte for no offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_0b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_0b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_idx_0b_instr] Offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_idx_0b_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_0b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_0b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_0B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_0b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_0b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_0B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_0b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_0B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_0b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_0b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_0b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_0b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_0b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_0b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_16b_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_16b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..fadca67ada3f55757b1e4ec238b7d584061a67a1 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_16b_instr.v @@ -0,0 +1,411 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed 16-bit offset instructions +// (reviewed 9/16/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_16B_TOTAL_INSTR 54 + `define TEST_IDX_16B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_16B_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_16B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_16b_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_16B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [15:0] offset16; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_16B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_16b_instr]"); + $display("[TB: tc_dv_idx_16b_instr]"); + $display("[TB: tc_dv_idx_16b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_16b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_16b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_d_instr]"); + $write("[TB: tc_dv_idx_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE9; + u_sel: post_byte = 'hC9; + y_sel: post_byte = 'hA9; + x_sel: post_byte = 'h89; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_16b_instr]"); + $write("[TB: tc_dv_idx_16b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_16b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_16b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 89 FFFE neg 16bit, x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for accu_16b_offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 16 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr+=2; + $display("[TB: tc_dv_idx_16b_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_16b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_16b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset16 = rand32[31:16]; + $display("[TB: tc_dv_idx_16b_instr] Random offset value: 0x%x", offset16); + + index_reg = data_ea - offset16; + $display("[TB: tc_dv_idx_16b_instr] Index register value: 0x%x", index_reg); + + // After the post-byte, write the 16 bit offset + write_tb_mem16p(offset_addr_ptr, offset16); + $display("Writing 16-bit offset follwing post-byte."); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_16b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_16b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_16B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_16b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_16b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_16B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_16b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_16B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_16b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_16b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_16b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_16b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_16b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_16b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_5b_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_5b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..9078850a6e6e604bf5bcf1683a0d3351e8d9cca5 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_5b_instr.v @@ -0,0 +1,410 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed 5-bit offset instructions +// (reviewed 9/20/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_5B_TOTAL_INSTR 54 + `define TEST_IDX_5B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_5B_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_5B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_5b_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_5B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 4:0] offset5; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_5B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_5b_instr]"); + $display("[TB: tc_dv_idx_5b_instr]"); + $display("[TB: tc_dv_idx_5b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_5b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_5b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_d_instr]"); + $write("[TB: tc_dv_idx_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + case (idx_reg_sel) + s_sel: post_byte = 'h60; + u_sel: post_byte = 'h40; + y_sel: post_byte = 'h20; + x_sel: post_byte = 'h00; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_5b_instr]"); + $write("[TB: tc_dv_idx_5b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_5b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_5b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 04 neg 4, x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Save space for the post byte that includes the 5 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr++; + $display("[TB: tc_dv_idx_0b_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_16b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_5b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset5 = rand32[31:27]; + $display("[TB: tc_dv_idx_5b_instr] Random offset value: 0x%x", offset5); + + index_reg = data_ea - {{11{offset5[4]}},{offset5}}; + $display("[TB: tc_dv_idx_5b_instr] Index register value: 0x%x", index_reg); + + // After the post-byte, write the 5 bit offset + write_tb_mem8p(offset_addr_ptr, post_byte | {3'b000,offset5}); + $display("Writing post-byte for 5-bit offset Indexed Addressing mode test."); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_5b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_5b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_5b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_5B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_5b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_5b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_5B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_5b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_5B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_5b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_5b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_5b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_5b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_5b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_5b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_8b_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_8b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..6dd024f7103a20aae971dd5055e922e7d22c9477 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_8b_instr.v @@ -0,0 +1,411 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed 8-bit offset instructions +// (reviewed 9/20/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_8B_TOTAL_INSTR 54 + `define TEST_IDX_8B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_8B_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_8B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_8b_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_8B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_8B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_8b_instr]"); + $display("[TB: tc_dv_idx_8b_instr]"); + $display("[TB: tc_dv_idx_8b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_8b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_8b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_d_instr]"); + $write("[TB: tc_dv_idx_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE8; + u_sel: post_byte = 'hC8; + y_sel: post_byte = 'hA8; + x_sel: post_byte = 'h88; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_8b_instr]"); + $write("[TB: tc_dv_idx_8b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_8b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_8b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 88 7F neg 127, x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 8-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 8 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr++; + $display("[TB: tc_dv_idx_8b_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_8b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_8b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = rand32[31:24]; + $display("[TB: tc_dv_idx_8b_instr] Random offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}},{offset8}}; + $display("[TB: tc_dv_idx_8b_instr] Index register value: 0x%x", index_reg); + + // After the post-byte, write the 16 bit offset + write_tb_mem8p(offset_addr_ptr, offset8); + $display("Writing 8-bit offset following post-byte."); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_8b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_8b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_8B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_8b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_8b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_8B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_8b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_8B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_8b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_8b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_8b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_8b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_8b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_8b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_a_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_a_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..7258ae69d36997d2444fbc9842a11d7364d82939 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_a_instr.v @@ -0,0 +1,402 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed A offset instructions +// (reviewed 9/16/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_A_TOTAL_INSTR 54 + `define TEST_IDX_A_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_A_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_A_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_a_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_A_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_A_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_a_instr]"); + $display("[TB: tc_dv_idx_a_instr]"); + $display("[TB: tc_dv_idx_a_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_a_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_a_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_a_instr]"); + $write("[TB: tc_dv_idx_a_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE6; + u_sel: post_byte = 'hC6; + y_sel: post_byte = 'hA6; + x_sel: post_byte = 'h86; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_a_instr]"); + $write("[TB: tc_dv_idx_a_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_a_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_a_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 86 neg a,x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for accu_A_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_a_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_a_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = rand32[23:16]; + $display("[TB: tc_dv_idx_a_instr] Creating a random offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_idx_a_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + write_tb_mem8p(`asm_init_a, offset8); $display("setting Acc A stack intialization value to 0x%x", offset8); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_a_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_a_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_A_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_a_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_a_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_A_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_a_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_A_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_a_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_a_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_a_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_a_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_a_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_a_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_b_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..94bd20ad8ee04e0feaafab4429d3f80f8925b152 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_b_instr.v @@ -0,0 +1,397 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed B offset instructions +// (reviewed 9/16/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_B_TOTAL_INSTR 54 + `define TEST_IDX_B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_B_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_b_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_b_instr]"); + $display("[TB: tc_dv_idx_b_instr]"); + $display("[TB: tc_dv_idx_b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_b_instr]"); + $write("[TB: tc_dv_idx_b_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE5; + u_sel: post_byte = 'hC5; + y_sel: post_byte = 'hA5; + x_sel: post_byte = 'h85; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_b_instr]"); + $write("[TB: tc_dv_idx_b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 85 neg b,x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + + $display("Writing post-byte for accu_B_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = rand32[23:16]; + $display("[TB: tc_dv_idx_b_instr] Creating a random offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_idx_b_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + write_tb_mem8p(`asm_init_b, offset8); $display("setting Acc B stack intialization value to 0x%x", offset8); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_d_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_d_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..e87215572eff34f646442ff5986719dedd031797 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_d_instr.v @@ -0,0 +1,404 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed D offset instructions +// reviewed 9/21/2021 -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_D_TOTAL_INSTR 54 + `define TEST_IDX_D_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_D_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_D_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_d_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_D_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [15:0] offset16; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_D_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_d_instr]"); + $display("[TB: tc_dv_idx_d_instr]"); + $display("[TB: tc_dv_idx_d_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_d_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_d_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_d_instr]"); + $write("[TB: tc_dv_idx_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hEB; + u_sel: post_byte = 'hCB; + y_sel: post_byte = 'hAB; + x_sel: post_byte = 'h8B; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_d_instr]"); + $write("[TB: tc_dv_idx_d_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_d_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_d_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 8B neg d,x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for accu_D_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_d_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_d_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset16 = rand32[31:16]; + $display("[TB: tc_dv_idx_d_instr] Creating a random offset value: 0x%x", offset16); + + index_reg = data_ea - offset16[15:0]; + $display("[TB: tc_dv_idx_d_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + write_tb_mem8p( `asm_init_a, offset16[15:8]); // A + $display("setting Acc A (Acc D[15:8]) stack intialization value to 0x%x", offset16[15:8]); // A + write_tb_mem8p( `asm_init_b, offset16[7:0]); // B + $display("setting Acc B (Acc D[ 7:0]) stack intialization value to 0x%x", offset16[7:0]); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_d_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_d_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_D_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_d_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_d_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_D_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_d_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_D_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_d_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_d_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_d_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_d_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_d_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_d_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_m1_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_m1_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..e58baf68c200d5ead530bec09b5eea9129f35054 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_m1_instr.v @@ -0,0 +1,402 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed Minus 1 instructions +// (reviewed 9/28/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_M1_TOTAL_INSTR 54 + `define TEST_IDX_M1_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_M1_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_M1_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_m1_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_M1_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IDX_M1_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_m1_instr]"); + $display("[TB: tc_dv_idx_m1_instr]"); + $display("[TB: tc_dv_idx_m1_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_m1_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_m1_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_m1_instr]"); + $write("[TB: tc_dv_idx_m1_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE2; + u_sel: post_byte = 'hC2; + y_sel: post_byte = 'hA2; + x_sel: post_byte = 'h82; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_m1_instr]"); + $write("[TB: tc_dv_idx_m1_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_m1_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_m1_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 82 neg ,-x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for pre decrement Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_m1_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_m1_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_idx_m1_instr] Offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]} + 1; // Add 1 to algebraically decrement by 1. + $display("[TB: tc_dv_idx_m1_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_m1_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_m1_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_M1_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_m1_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_m1_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_M1_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_m1_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_M1_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_m1_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_m1_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_m1_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_m1_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_m1_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_m1_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_m2_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_m2_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..852700027d0af414e92ee80d3f010a4dee27b79a --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_m2_instr.v @@ -0,0 +1,402 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed Minus 2 instructions +// (reviewed 9/28/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_M2_TOTAL_INSTR 54 + `define TEST_IDX_M2_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_M2_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_M2_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_m2_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_M2_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IDX_M2_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_m2_instr]"); + $display("[TB: tc_dv_idx_m2_instr]"); + $display("[TB: tc_dv_idx_m2_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_m2_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_m2_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_m2_instr]"); + $write("[TB: tc_dv_idx_m2_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE3; + u_sel: post_byte = 'hC3; + y_sel: post_byte = 'hA3; + x_sel: post_byte = 'h83; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_m2_instr]"); + $write("[TB: tc_dv_idx_m2_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_m2_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_m2_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 83 neg ,--x + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for no offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_m2_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_m2_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_idx_m2_instr] Offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]} + 2; // Add 2 to algebraically decrement by 2. + $display("[TB: tc_dv_idx_m2_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_m2_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_m2_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_M2_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_m2_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_m2_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_M2_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_m2_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_M2_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_m2_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_m2_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_m2_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_m2_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_m2_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_m2_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_p1_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_p1_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..d37177bceecc0d364cb34ce24946c9564904848b --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_p1_instr.v @@ -0,0 +1,402 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed Plus 1 instructions +// (reviewed 9/28/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_P1_TOTAL_INSTR 54 + `define TEST_IDX_P1_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_P1_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_P1_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_p1_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_P1_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IDX_P1_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_p1_instr]"); + $display("[TB: tc_dv_idx_p1_instr]"); + $display("[TB: tc_dv_idx_p1_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_p1_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_p1_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_p1_instr]"); + $write("[TB: tc_dv_idx_p1_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE0; + u_sel: post_byte = 'hC0; + y_sel: post_byte = 'hA0; + x_sel: post_byte = 'h80; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_p1_instr]"); + $write("[TB: tc_dv_idx_p1_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_p1_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_p1_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 80 neg ,x+ + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for post increment Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_p1_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_p1_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_idx_p1_instr] Offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_idx_p1_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_p1_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_p1_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_P1_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_p1_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_p1_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_P1_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_p1_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_P1_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_p1_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_p1_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_p1_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_p1_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_p1_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_p1_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_p2_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_p2_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..ebf21e31b70fd313092a35683196d42785d5b847 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_p2_instr.v @@ -0,0 +1,402 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed Plus 2 instructions +// (reviewed 9/28/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_P2_TOTAL_INSTR 54 + `define TEST_IDX_P2_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_P2_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_P2_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_p2_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_P2_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IDX_P2_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_p2_instr]"); + $display("[TB: tc_dv_idx_p2_instr]"); + $display("[TB: tc_dv_idx_p2_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_p2_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_p2_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_idx_p2_instr]"); + $write("[TB: tc_dv_idx_p2_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hE1; + u_sel: post_byte = 'hC1; + y_sel: post_byte = 'hA1; + x_sel: post_byte = 'h81; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_p2_instr]"); + $write("[TB: tc_dv_idx_p2_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_p2_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_p2_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 81 neg ,x++ + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for post increment 2 Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_idx_p2_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_idx_p2_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + ///////////////// Calculate Offset and Index + // + // data_ea = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = data_ea - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_idx_p2_instr] Offset value: 0x%x", offset8); + + index_reg = data_ea - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_idx_p2_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_p2_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_p2_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_P2_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_p2_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_p2_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_P2_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_p2_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_P2_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_p2_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_p2_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_p2_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_p2_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_p2_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_p2_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_pc16_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_pc16_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..f6073cb19e80c53c063b15bf5be0e8c6ea84ff67 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_pc16_instr.v @@ -0,0 +1,366 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed PC 16-bit offset instructions +// (reviewed 11/7/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_PC16_TOTAL_INSTR 54 + `define TEST_IDX_PC16_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_PC16_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_PC16_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_pc16_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_PC16_TOTAL_INSTR-1]; + integer instr_idx; + integer postbyte_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] temp16; + reg [15:0] pc_index_reg; + reg [15:0] offset16; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_PC16_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_pc16_instr]"); + $display("[TB: tc_dv_idx_pc16_instr]"); + $display("[TB: tc_dv_idx_pc16_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_pc16_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_pc16_instr] ////////////////////////////////////////////////////////////////////"); + + for (postbyte_sel = 0; postbyte_sel < 4; postbyte_sel++) begin + + $display("[TB: tc_dv_idx_pc16_instr]"); + + ///////////////// Set post-byte one of the index registers. + // + case (postbyte_sel) + 0: post_byte = 'hED; + 1: post_byte = 'hCD; + 2: post_byte = 'hAD; + 3: post_byte = 'h8D; + endcase + $display("[TB: tc_dv_idx_pc16_instr] //////////// Selecting postbyte 0x%x for PC 8bit offset", post_byte); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_pc16_instr]"); + $write("[TB: tc_dv_idx_pc16_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_pc16_instr] Loading testbench template: tb_dv_asm.hex"); + $readmemh("tb_dv_asm.hex",`tb_mem); + end else begin + $display("[TB: tc_dv_idx_pc16_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 8D 80 00 neg 128, PC + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 16-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 16 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr+=2; + $display("[TB: tc_dv_idx_pc16_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + // After the offset, save the PC value + // + pc_index_reg = addr_ptr; + $display("[TB: tc_dv_idx_pc16_instr] PC = 0x%x", pc_index_reg); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to go forwards or backwards + // + if(rand32[31]) begin + $write("[TB: tc_dv_idx_pc16_instr] Creating a random address for a forward PC 16bit index... "); + data_ea = data_block_start + ((rand32[15:0])%((`asm_data_block_end ) - data_block_start)); + $display("effective address = 0x%4x", data_ea); + end else begin + $write("[TB: tc_dv_idx_pc16_instr] Creating a random address for a backward PC 16bit index... "); + data_ea = (`asm_code_under_test) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test ) - operand_size)); + $display("effective address = 0x%4x", data_ea); + end + + ///////////////// Create a random relative address offset for the data + // + $write("[TB: tc_dv_idx_pc16_instr] Calculate offset... "); + temp16 = data_ea - pc_index_reg; // Offset = ea - pc + offset16 = temp16[15:0]; + $display("16bit offset = 0x%2x", offset16); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem16p(offset_addr_ptr, offset16); + $display("writing 16-bit offset to the offset field after postbyte"); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_u_s, ); // U or S + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_x, ); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_pc16_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_pc16_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_PC16_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_pc16_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_pc16_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_PC16_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_pc16_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_PC16_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_pc16_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + error_cnt += model_error; //add model error to error count + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_pc16_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_pc16_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_pc16_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_pc16_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_pc16_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_idx_pc8_instr.v b/turbo9team_turbo9/tb/tc_dv_idx_pc8_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..d6ced5b4e4b1c895e14b75daf2c346539951f505 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_idx_pc8_instr.v @@ -0,0 +1,378 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indexed PC 8-bit offset instructions +// (reviewed 9/20/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IDX_PC8_TOTAL_INSTR 54 + `define TEST_IDX_PC8_RESET_CYCLES 40 // (16 nominal) + `define TEST_IDX_PC8_START_CYCLES 200 // (100 nominal) + `define TEST_IDX_PC8_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_idx_pc8_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IDX_PC8_TOTAL_INSTR-1]; + integer instr_idx; + integer postbyte_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] temp16; + reg [15:0] pc_index_reg; + reg [ 7:0] offset8; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IDX_PC8_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_idx_pc8_instr]"); + $display("[TB: tc_dv_idx_pc8_instr]"); + $display("[TB: tc_dv_idx_pc8_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_idx_pc8_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_idx_pc8_instr] ////////////////////////////////////////////////////////////////////"); + + for (postbyte_sel = 0; postbyte_sel < 4; postbyte_sel++) begin + + $display("[TB: tc_dv_idx_pc8_instr]"); + + ///////////////// Set post-byte one of the index registers. + // + case (postbyte_sel) + 0: post_byte = 'hEC; + 1: post_byte = 'hCC; + 2: post_byte = 'hAC; + 3: post_byte = 'h8C; + endcase + $display("[TB: tc_dv_idx_pc8_instr] //////////// Selecting postbyte 0x%x for PC 8bit offset", post_byte); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_idx_pc8_instr]"); + $write("[TB: tc_dv_idx_pc8_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_idx_pc8_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_idx_pc8_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 8C 7F neg 127, PC + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 8-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 8 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr++; + $display("[TB: tc_dv_idx_pc8_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + // After the offset, save the PC value + // + pc_index_reg = addr_ptr; + $display("[TB: tc_dv_idx_pc8_instr] PC = 0x%x", pc_index_reg); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to go forwards or backwards + // + if (prebyte) begin + temp16 = 16'd1; + end else begin + temp16 = 16'd0; + end + // + if(rand32[31]) begin + $write("[TB: tc_dv_idx_pc8_instr] Creating a random address for a forward PC 8bit index... "); + data_ea = data_block_start + ((rand32[15:0])%((`asm_code_under_test_idx_pc8_fwd + temp16) - data_block_start)); + $display("effective address = 0x%4x", data_ea); + end else begin + $write("[TB: tc_dv_idx_pc8_instr] Creating a random address for a backward PC 8bit index... "); + data_ea = (`asm_code_under_test_idx_pc8_bwd + temp16) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test_idx_pc8_bwd + temp16) - operand_size)); + $display("effective address = 0x%4x", data_ea); + end + + ///////////////// Create a random relative address offset for the data + // + $write("[TB: tc_dv_idx_pc8_instr] Calculate offset... "); + temp16 = data_ea - pc_index_reg; // Offset = ea - pc + offset8 = temp16[7:0]; + $display("8bit offset = 0x%2x", offset8); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem8p(offset_addr_ptr, offset8); + $display("writing 8-bit offset to the offset field after postbyte"); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_u_s, ); // U or S + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_x, ); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_idx_pc8_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_idx_pc8_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IDX_PC8_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_idx_pc8_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_idx_pc8_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IDX_PC8_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_idx_pc8_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IDX_PC8_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_idx_pc8_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_idx_pc8_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_idx_pc8_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_idx_pc8_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_idx_pc8_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_idx_pc8_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_imm_instr.v b/turbo9team_turbo9/tb/tc_dv_imm_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..8aa9fbf180463c4288362d4a2cdb302c6c00324a --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_imm_instr.v @@ -0,0 +1,296 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Immediate instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Immedate Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IMM_TOTAL_INSTR 34 + `define TEST_IMM_RESET_CYCLES 40 // (16 nominal) + `define TEST_IMM_START_CYCLES 200 // (100 nominal) + `define TEST_IMM_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_imm_instr; + + reg [15:0] addr_ptr; + reg [15:0] imm_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer imm_instr_list [0:`TEST_IMM_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // imm_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + imm_instr_list[ 0] = 'h00_2_1_00_1A; // ORCC + imm_instr_list[ 1] = 'h00_2_1_00_1C; // ANDCC + // + imm_instr_list[ 2] = 'h00_2_1_00_80; // SUBA + imm_instr_list[ 3] = 'h00_2_1_00_81; // CMPA + imm_instr_list[ 4] = 'h00_2_1_00_82; // SBCA + imm_instr_list[ 5] = 'h00_2_2_00_83; // SUBD + imm_instr_list[ 6] = 'h00_2_1_00_84; // ANDA + imm_instr_list[ 7] = 'h00_2_1_00_85; // BITA + imm_instr_list[ 8] = 'h00_2_1_00_86; // LDA + //imm_instr_list[] = 'h00_2_1_00_87; + imm_instr_list[ 9] = 'h00_2_1_00_88; // EORA + imm_instr_list[10] = 'h00_2_1_00_89; // ADCA + imm_instr_list[11] = 'h00_2_1_00_8A; // ORA + imm_instr_list[12] = 'h00_2_1_00_8B; // ADDA + imm_instr_list[13] = 'h00_2_2_00_8C; // CMPX + imm_instr_list[14] = 'h00_2_2_00_8E; // LDX + //imm_instr_list[] = 'h00_2_1_00_8F; + // + imm_instr_list[15] = 'h00_2_1_00_C0; // SUBB + imm_instr_list[16] = 'h00_2_1_00_C1; // CMPB + imm_instr_list[17] = 'h00_2_1_00_C2; // SBCB + imm_instr_list[18] = 'h00_2_2_00_C3; // ADDD + imm_instr_list[19] = 'h00_2_1_00_C4; // ANDB + imm_instr_list[20] = 'h00_2_1_00_C5; // BITB + imm_instr_list[21] = 'h00_2_1_00_C6; // LDB + //imm_instr_list[] = 'h00_2_1_00_C7; + imm_instr_list[22] = 'h00_2_1_00_C8; // EORB + imm_instr_list[23] = 'h00_2_1_00_C9; // ADCB + imm_instr_list[24] = 'h00_2_1_00_CA; // ORB + imm_instr_list[25] = 'h00_2_1_00_CB; // ADDB + imm_instr_list[26] = 'h00_2_2_00_CC; // LDD + //imm_instr_list[] = 'h00_2_1_00_CD; + imm_instr_list[27] = 'h00_0_2_00_CE; // LDU + //imm_instr_list[] = 'h00_2_1_00_CF; + + // Page 2 + imm_instr_list[28] = 'h00_2_2_10_83; // CMPD + imm_instr_list[29] = 'h00_2_2_10_8C; // CMPY + imm_instr_list[30] = 'h00_2_2_10_8E; // LDY + imm_instr_list[31] = 'h00_1_2_10_CE; // LDS + + // Page 3 + imm_instr_list[32] = 'h00_0_2_11_83; // CMPU + imm_instr_list[33] = 'h00_1_2_11_8C; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IMM_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = imm_instr_list[instr_idx][ 7: 0]; + prebyte = imm_instr_list[instr_idx][15: 8]; + operand_size = imm_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_imm_instr]"); + $display("[TB: tc_dv_imm_instr]"); + $display("[TB: tc_dv_imm_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_imm_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_imm_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_imm_instr]"); + $write("[TB: tc_dv_imm_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(imm_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_imm_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_imm_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Save a pointer to the immediate data + // + imm_addr_ptr = addr_ptr; + addr_ptr += operand_size; + $display("[TB: tc_dv_imm_instr] @ 0x%4x : This is the immediate data address location", imm_addr_ptr); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_imm_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_imm_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IMM_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_imm_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_imm_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IMM_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_imm_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IMM_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_imm_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_imm_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_imm_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_imm_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_imm_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_imm_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_0b_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_0b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..315dce7c32e18ebf325fa3a122ec8f04116a9c26 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_0b_instr.v @@ -0,0 +1,411 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect no offset +// (reviewed 11/10/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_0B_TOTAL_INSTR 54 + `define TEST_IND_0B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_0B_START_CYCLES 200 // (100 nominal) + `define TEST_IND_0B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_0b_instr; + + reg [15:0] addr_ptr; + reg [15:0] ind_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_0B_TOTAL_INSTR-1]; + integer instr_idx; + integer ind_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IND_0B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_0b_instr]"); + $display("[TB: tc_dv_ind_0b_instr]"); + $display("[TB: tc_dv_ind_0b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_0b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_0b_instr] ////////////////////////////////////////////////////////////////////"); + + for (ind_reg_sel = 0; ind_reg_sel < 4; ind_reg_sel++) begin + + // Dont use stack pointer as index + if (((ind_reg_sel == s_sel) || (ind_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == ind_reg_sel)) + ind_reg_sel++; + + $display("[TB: tc_dv_ind_0b_instr]"); + $write("[TB: tc_dv_ind_0b_instr] //////////// Selecting "); + case (ind_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (ind_reg_sel) + s_sel: post_byte = 'hF4; + u_sel: post_byte = 'hD4; + y_sel: post_byte = 'hB4; + x_sel: post_byte = 'h94; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_0b_instr]"); + $write("[TB: tc_dv_ind_0b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (ind_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_0b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_0b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 94 neg [,x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + // Save address pointer, increment past post-byte + //ind_addr_ptr = addr_ptr; + addr_ptr++; + $display("Writing post-byte for no offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_0b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_0b_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_0b_instr] Creating a random effective address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_ind_0b_instr] Offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_ind_0b_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (ind_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_0b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_0b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_0B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_0b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_0b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_0B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_0b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_0B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_0b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_0b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_0b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_0b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_0b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_0b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_16b_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_16b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..ba0657f7e6be8a82800acce9a611e38e9bffccbf --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_16b_instr.v @@ -0,0 +1,416 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect 16-bit offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_16B_TOTAL_INSTR 54 + `define TEST_IND_16B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_16B_START_CYCLES 200 // (100 nominal) + `define TEST_IND_16B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_16b_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_16B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [15:0] offset16; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_16B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_16b_instr]"); + $display("[TB: tc_dv_ind_16b_instr]"); + $display("[TB: tc_dv_ind_16b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_16b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_16b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_16b_instr]"); + $write("[TB: tc_dv_ind_16b_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF9; + u_sel: post_byte = 'hD9; + y_sel: post_byte = 'hB9; + x_sel: post_byte = 'h99; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_16b_instr]"); + $write("[TB: tc_dv_ind_16b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_16b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_16b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 99 FFFE neg [16bit, x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for accu_16b_offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 16 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr+=2; + $display("[TB: tc_dv_ind_16b_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_16b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_16b_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_16b_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset16 = rand32[31:16]; + $display("[TB: tc_dv_ind_16b_instr] Random offset value: 0x%x", offset16); + + index_reg = indirect_addr - offset16; + $display("[TB: tc_dv_ind_16b_instr] Index register value: 0x%x", index_reg); + + // After the post-byte, write the 16 bit offset + write_tb_mem16p(offset_addr_ptr, offset16); + $display("Writing 16-bit offset follwing post-byte."); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_16b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_16b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_16B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_16b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_16b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_16B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_16b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_16B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_16b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_16b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_16b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_16b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_16b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_16b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_8b_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_8b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..c49767d923b9284bfcbd9e2f9fe0d194c2afa3a3 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_8b_instr.v @@ -0,0 +1,417 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect 8-bit offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_8B_TOTAL_INSTR 54 + `define TEST_IND_8B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_8B_START_CYCLES 200 // (100 nominal) + `define TEST_IND_8B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_8b_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_8B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_8B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_8b_instr]"); + $display("[TB: tc_dv_ind_8b_instr]"); + $display("[TB: tc_dv_ind_8b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_8b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_8b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_d_instr]"); + $write("[TB: tc_dv_ind_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF8; + u_sel: post_byte = 'hD8; + y_sel: post_byte = 'hB8; + x_sel: post_byte = 'h98; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_8b_instr]"); + $write("[TB: tc_dv_ind_8b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_8b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_8b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 98 7F neg [127, x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 8-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 8 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr++; + $display("[TB: tc_dv_ind_8b_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_8b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_8b_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_8b_instr] Creating a random effective address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = rand32[31:24]; + $display("[TB: tc_dv_ind_8b_instr] Random offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}},{offset8}}; + $display("[TB: tc_dv_ind_8b_instr] Index register value: 0x%x", index_reg); + + // After the post-byte, write the 16 bit offset + write_tb_mem8p(offset_addr_ptr, offset8); + $display("Writing 8-bit offset following post-byte."); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_8b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_8b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_8B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_8b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_8b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_8B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_8b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_8B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_8b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_8b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_8b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_8b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_8b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_8b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_a_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_a_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..f202bf7efd0caa3c27ce103fb827f2b699c21d60 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_a_instr.v @@ -0,0 +1,406 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect A offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_A_TOTAL_INSTR 54 + `define TEST_IND_A_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_A_START_CYCLES 200 // (100 nominal) + `define TEST_IND_A_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_a_instr; + + reg [15:0] addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_A_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_A_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_a_instr]"); + $display("[TB: tc_dv_ind_a_instr]"); + $display("[TB: tc_dv_ind_a_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_a_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_a_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_a_instr]"); + $write("[TB: tc_dv_ind_a_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF6; + u_sel: post_byte = 'hD6; + y_sel: post_byte = 'hB6; + x_sel: post_byte = 'h96; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_a_instr]"); + $write("[TB: tc_dv_ind_a_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_a_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_a_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 96 neg [a,x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + + $display("Writing post-byte for accu_A_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_a_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_a_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_a_instr] Creating a random effective address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = rand32[23:16]; + $display("[TB: tc_dv_ind_a_instr] Creating a random offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_ind_a_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + write_tb_mem8p(`asm_init_a, offset8); $display("setting Acc A stack intialization value to 0x%x", offset8); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_a_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_a_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_A_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_a_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_a_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_A_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_a_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_A_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_a_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_a_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_a_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_a_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_a_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_a_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_b_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..1934bf444de42e219356f97430da55d480710ff2 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_b_instr.v @@ -0,0 +1,406 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect B offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_B_TOTAL_INSTR 54 + `define TEST_IND_B_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_B_START_CYCLES 200 // (100 nominal) + `define TEST_IND_B_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_b_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_B_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_B_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_b_instr]"); + $display("[TB: tc_dv_ind_b_instr]"); + $display("[TB: tc_dv_ind_b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_b_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_b_instr]"); + $write("[TB: tc_dv_ind_b_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF5; + u_sel: post_byte = 'hD5; + y_sel: post_byte = 'hB5; + x_sel: post_byte = 'h95; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_b_instr]"); + $write("[TB: tc_dv_ind_b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 95 neg [b,x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + + $display("Writing post-byte for accu_B_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_b_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_b_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_b_instr] Creating a random effective address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = rand32[23:16]; + $display("[TB: tc_dv_ind_b_instr] Creating a random offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_ind_b_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + write_tb_mem8p(`asm_init_b, offset8); $display("setting Acc B stack intialization value to 0x%x", offset8); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_B_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_B_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_B_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_b_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_b_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_d_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_d_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..65bcb9da1648568a6fa406b6ef62cd4cf3ff0150 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_d_instr.v @@ -0,0 +1,410 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect D offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_D_TOTAL_INSTR 54 + `define TEST_IND_D_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_D_START_CYCLES 200 // (100 nominal) + `define TEST_IND_D_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_d_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer idx_instr_list [0:`TEST_IND_D_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [15:0] offset16; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // idx_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + idx_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + idx_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + idx_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + idx_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + idx_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //idx_instr_list[ ] = 'h00_2_1_00_61; // * + //idx_instr_list[ ] = 'h00_2_1_00_62; // * + idx_instr_list[ 5] = 'h00_2_1_00_63; // COM + idx_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //idx_instr_list[ ] = 'h00_2_1_00_65; // * + idx_instr_list[ 7] = 'h00_2_1_00_66; // ROR + idx_instr_list[ 8] = 'h00_2_1_00_67; // ASR + idx_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + idx_instr_list[10] = 'h00_2_1_00_69; // ROL + idx_instr_list[11] = 'h00_2_1_00_6A; // DEC + //idx_instr_list[ ] = 'h00_2_1_00_6B; // * + idx_instr_list[12] = 'h00_2_1_00_6C; // INC + idx_instr_list[13] = 'h00_2_1_00_6D; // TST + //idx_instr_list[ ] = 'h00_2_1_00_6E; // JMP + idx_instr_list[14] = 'h00_2_1_00_6F; // CLR + idx_instr_list[15] = 'h00_2_1_00_A0; // SUBA + idx_instr_list[16] = 'h00_2_1_00_A1; // CMPA + idx_instr_list[17] = 'h00_2_1_00_A2; // SBCA + idx_instr_list[18] = 'h00_2_2_00_A3; // SUBD + idx_instr_list[19] = 'h00_2_1_00_A4; // ANDA + idx_instr_list[20] = 'h00_2_1_00_A5; // BITA + idx_instr_list[21] = 'h00_2_1_00_A6; // LDA + idx_instr_list[22] = 'h00_2_1_00_A7; // STA + idx_instr_list[23] = 'h00_2_1_00_A8; // EORA + idx_instr_list[24] = 'h00_2_1_00_A9; // ADCA + idx_instr_list[25] = 'h00_2_1_00_AA; // ORA + idx_instr_list[26] = 'h00_2_1_00_AB; // ADDA + idx_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //idx_instr_list[ ] = 'h00_2_1_00_AD; // JSR + idx_instr_list[28] = 'h00_2_2_00_AE; // LDX + idx_instr_list[29] = 'h00_2_2_00_AF; // STX + idx_instr_list[30] = 'h00_2_1_00_E0; // SUBB + idx_instr_list[31] = 'h00_2_1_00_E1; // CMPB + idx_instr_list[32] = 'h00_2_1_00_E2; // SBCB + idx_instr_list[33] = 'h00_2_2_00_E3; // ADDD + idx_instr_list[34] = 'h00_2_1_00_E4; // ANDB + idx_instr_list[35] = 'h00_2_1_00_E5; // BITB + idx_instr_list[36] = 'h00_2_1_00_E6; // LDB + idx_instr_list[37] = 'h00_2_1_00_E7; // STB + idx_instr_list[38] = 'h00_2_1_00_E8; // EORB + idx_instr_list[39] = 'h00_2_1_00_E9; // ADCB + idx_instr_list[40] = 'h00_2_1_00_EA; // ORB + idx_instr_list[41] = 'h00_2_1_00_EB; // ADDB + idx_instr_list[42] = 'h00_2_2_00_EC; // LDD + idx_instr_list[43] = 'h00_2_2_00_ED; // STD + idx_instr_list[44] = 'h00_0_2_00_EE; // LDU + idx_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + idx_instr_list[46] = 'h00_2_2_10_A3; // CMPD + idx_instr_list[47] = 'h00_2_2_10_AC; // CMPY + idx_instr_list[48] = 'h00_2_2_10_AE; // LDY + idx_instr_list[49] = 'h00_2_2_10_AF; // STY + idx_instr_list[50] = 'h00_1_2_10_EE; // LDS + idx_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + idx_instr_list[52] = 'h00_0_2_11_A3; // CMPU + idx_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_D_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = idx_instr_list[instr_idx][ 7: 0]; + prebyte = idx_instr_list[instr_idx][15: 8]; + operand_size = idx_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_d_instr]"); + $display("[TB: tc_dv_ind_d_instr]"); + $display("[TB: tc_dv_ind_d_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_d_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_d_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (idx_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_d_instr]"); + $write("[TB: tc_dv_ind_d_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hFB; + u_sel: post_byte = 'hDB; + y_sel: post_byte = 'hBB; + x_sel: post_byte = 'h9B; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_d_instr]"); + $write("[TB: tc_dv_ind_d_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(idx_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_d_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_d_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 9B neg [d,x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for accu_D_offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_d_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_d_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_d_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = (data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size))); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset16 = rand32[31:16]; + $display("[TB: tc_dv_ind_d_instr] Creating a random offset value: 0x%x", offset16); + + index_reg = indirect_addr - offset16[15:0]; + $display("[TB: tc_dv_ind_d_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + write_tb_mem8p( `asm_init_a, offset16[15:8]); // A + $display("setting Acc A (Acc D[15:8]) stack intialization value to 0x%x", offset16[15:8]); // A + write_tb_mem8p( `asm_init_b, offset16[7:0]); // B + $display("setting Acc B (Acc D[ 7:0]) stack intialization value to 0x%x", offset16[7:0]); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_d_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_d_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_D_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_d_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_d_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_D_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_d_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_D_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_d_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_d_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_d_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_d_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_d_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_d_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_m2_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_m2_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..c53cefad831f0237589eb13f02861125747ab57a --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_m2_instr.v @@ -0,0 +1,411 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect Minus 2 +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_M2_TOTAL_INSTR 54 + `define TEST_IND_M2_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_M2_START_CYCLES 200 // (100 nominal) + `define TEST_IND_M2_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_m2_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_M2_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IND_M2_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_m2_instr]"); + $display("[TB: tc_dv_ind_m2_instr]"); + $display("[TB: tc_dv_ind_m2_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_m2_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_m2_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_m2_instr]"); + $write("[TB: tc_dv_ind_m2_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF3; + u_sel: post_byte = 'hD3; + y_sel: post_byte = 'hB3; + x_sel: post_byte = 'h93; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_m2_instr]"); + $write("[TB: tc_dv_ind_m2_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_m2_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_m2_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 93 neg [,--x] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for no offset Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_m2_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_m2_instr] Creating a random indirect address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_m2_instr] Creating a random effective address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_ind_m2_instr] Offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}}, offset8[7:0]} + 2; // Add 2 to algebraically decrement by 2. + $display("[TB: tc_dv_ind_m2_instr] Index register value: 0x%x", index_reg); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_m2_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_m2_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_M2_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_m2_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_m2_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_M2_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_m2_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_M2_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_m2_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_m2_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_m2_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_m2_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_m2_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_m2_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_p2_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_p2_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..e7cbb9dde18e8ee5cb7a9e4cfb83db1166b4180c --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_p2_instr.v @@ -0,0 +1,409 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect Plus 2 +// (reviewed 9/28/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_P2_TOTAL_INSTR 54 + `define TEST_IND_P2_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_P2_START_CYCLES 200 // (100 nominal) + `define TEST_IND_P2_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_p2_instr; + + reg [15:0] addr_ptr; + reg [15:0] idx_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_P2_TOTAL_INSTR-1]; + integer instr_idx; + integer idx_reg_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] init_ptr; + reg [15:0] index_reg; + reg [ 7:0] offset8; + + localparam s_sel = 0; + localparam u_sel = 1; + localparam y_sel = 2; + localparam x_sel = 3; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + for (instr_idx = 0; instr_idx < `TEST_IND_P2_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_p2_instr]"); + $display("[TB: tc_dv_ind_p2_instr]"); + $display("[TB: tc_dv_ind_p2_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_p2_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_p2_instr] ////////////////////////////////////////////////////////////////////"); + + for (idx_reg_sel = 0; idx_reg_sel < 4; idx_reg_sel++) begin + + // Dont use stack pointer as index + if (((idx_reg_sel == s_sel) || (idx_reg_sel == u_sel)) && (ind_instr_list[instr_idx][21:20] == idx_reg_sel)) + idx_reg_sel++; + + $display("[TB: tc_dv_ind_p2_instr]"); + $write("[TB: tc_dv_ind_p2_instr] //////////// Selecting "); + case (idx_reg_sel) + s_sel: $write("S "); + u_sel: $write("U "); + y_sel: $write("Y "); + x_sel: $write("X "); + endcase + $display("as index register ////////////"); + + ///////////////// Set post-byte one of the index registers. + // + case (idx_reg_sel) + s_sel: post_byte = 'hF1; + u_sel: post_byte = 'hD1; + y_sel: post_byte = 'hB1; + x_sel: post_byte = 'h91; + endcase + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_p2_instr]"); + $write("[TB: tc_dv_ind_p2_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + case (idx_reg_sel) + s_sel: stack_ptr_sel = choose_stack_ptr(u_sel); + u_sel: stack_ptr_sel = choose_stack_ptr(s_sel); + y_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // Y + x_sel: stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); // X + endcase + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_p2_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_p2_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 00 91 neg [,x++] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for post increment 2 Indexed Addressing mode test"); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Calculate the start and range of the data block + // + data_block_start = addr_ptr; + $display("[TB: tc_dv_ind_p2_instr] @ 0x%4x to 0x%4x : will be used as the data block (%0d bytes)", + data_block_start,`asm_data_block_last_byte,(`asm_data_block_end-data_block_start)); + + ///////////////// Create a random indirect address for the data + // + $write("[TB: tc_dv_ind_p2_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + indirect_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("indirect address = 0x%4x", indirect_addr); + + ///////////////// Create a random effective address for the data + // + $write("[TB: tc_dv_ind_p2_instr] Creating a random address within the data block for data... "); + rand32 = {$random(seed)}; //{} = unsigned + data_ea = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - operand_size)); + $display("effective address = 0x%4x", data_ea); + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Calculate Offset and Index + // + // indirect_addr = index_reg + signed offset + // - randomize offset and solve for index_reg + // + // index_reg = indirect_addr - signed offset + // + offset8 = 8'd0; + $display("[TB: tc_dv_ind_p2_instr] Offset value: 0x%x", offset8); + + index_reg = indirect_addr - {{8{offset8[7]}}, offset8[7:0]}; + $display("[TB: tc_dv_ind_p2_instr] Index register value: 0x%x", index_reg); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + + case (idx_reg_sel) + s_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting S "); + end + u_sel: + begin + write_tb_mem16p(`asm_init_u_s, index_reg); + $write("Setting U "); + end + y_sel: + begin + write_tb_mem16p(`asm_init_y, index_reg); + $write("Setting Y "); + end + x_sel: + begin + write_tb_mem16p(`asm_init_x, index_reg); + $write("Setting X "); + end + endcase + $display("index register stack intialization value to 0x%x", index_reg); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_p2_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_p2_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_P2_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_p2_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_p2_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_P2_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_p2_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_P2_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_p2_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_p2_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_p2_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_p2_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_p2_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_p2_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_pc16_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_pc16_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..b6b8937435aadf1f3dda184116214598aab97c50 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_pc16_instr.v @@ -0,0 +1,381 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect PC 16-bit offset +// (reviewed 11/7/21) -KP +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_PC16_TOTAL_INSTR 54 + `define TEST_IND_PC16_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_PC16_START_CYCLES 200 // (100 nominal) + `define TEST_IND_PC16_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_pc16_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_PC16_TOTAL_INSTR-1]; + integer instr_idx; + integer postbyte_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] temp16; + reg [15:0] pc_index_reg; + reg [15:0] offset16; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_PC16_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_pc16_instr]"); + $display("[TB: tc_dv_ind_pc16_instr]"); + $display("[TB: tc_dv_ind_pc16_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_pc16_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_pc16_instr] ////////////////////////////////////////////////////////////////////"); + + for (postbyte_sel = 0; postbyte_sel < 4; postbyte_sel++) begin + + $display("[TB: tc_dv_ind_pc16_instr]"); + + ///////////////// Set post-byte one of the index registers. + // + case (postbyte_sel) + 0: post_byte = 'hFD; + 1: post_byte = 'hDD; + 2: post_byte = 'hBD; + 3: post_byte = 'h9D; + endcase + $display("[TB: tc_dv_ind_pc16_instr] //////////// Selecting postbyte 0x%x for PC 8bit offset", post_byte); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_pc16_instr]"); + $write("[TB: tc_dv_ind_pc16_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_pc16_instr] Loading testbench template: tb_dv_asm.hex"); + $readmemh("tb_dv_asm.hex",`tb_mem); + end else begin + $display("[TB: tc_dv_ind_pc16_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 9D 80 00 neg [128, PC] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 16-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 16 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr+=2; + $display("[TB: tc_dv_ind_pc16_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + // After the offset, save the PC value + // + pc_index_reg = addr_ptr; + $display("[TB: tc_dv_ind_pc16_instr] PC = 0x%x", pc_index_reg); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to go forwards or backwards + // + if(rand32[31]) begin + $write("[TB: tc_dv_ind_pc16_instr] Creating a random address for a forward PC 16bit index... "); + indirect_addr = data_block_start + ((rand32[15:0])%((`asm_data_block_end ) - data_block_start)); + $display("effective address = 0x%4x", indirect_addr); + end else begin + $write("[TB: tc_dv_ind_pc16_instr] Creating a random address for a backward PC 16bit index... "); + indirect_addr = (`asm_code_under_test) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test ) - operand_size)); + $display("effective address = 0x%4x", indirect_addr); + end + + rand32 = {$random(seed)}; + + if(rand32[31]) begin + $write("[TB: tc_dv_ind_pc16_instr] Creating a random address for a forward PC 16bit index... "); + data_ea = data_block_start + ((rand32[15:0])%((`asm_data_block_end ) - data_block_start)); + $display("effective address = 0x%4x", data_ea); + end else begin + $write("[TB: tc_dv_ind_pc16_instr] Creating a random address for a backward PC 16bit index... "); + data_ea = (`asm_code_under_test) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test ) - operand_size)); + $display("effective address = 0x%4x", data_ea); + end + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Create a random indexed indirect address offset for the data + // + $write("[TB: tc_dv_ind_pc16_instr] Calculate offset... "); + temp16 = indirect_addr - pc_index_reg; // Offset = ea - pc + offset16 = temp16[15:0]; + $display("16bit offset = 0x%2x", offset16); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem16p(offset_addr_ptr, offset16); + $display("writing 16-bit offset to the offset field after postbyte"); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_u_s, ); // U or S + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_x, ); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_pc16_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_pc16_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_PC16_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_pc16_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_pc16_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_PC16_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_pc16_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_PC16_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_pc16_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + error_cnt += model_error; //add model error to error count + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_pc16_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_pc16_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_pc16_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_pc16_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_pc16_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_ind_pc8_instr.v b/turbo9team_turbo9/tb/tc_dv_ind_pc8_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..a00e6f9f8b676d01e6d41c98302eed5646c1757c --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_ind_pc8_instr.v @@ -0,0 +1,393 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt & Kevin Phillipson +// Description: Testcase: Indirect PC 8-bit offset +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Indexed Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_IND_PC8_TOTAL_INSTR 54 + `define TEST_IND_PC8_RESET_CYCLES 40 // (16 nominal) + `define TEST_IND_PC8_START_CYCLES 200 // (100 nominal) + `define TEST_IND_PC8_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Indexed Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_ind_pc8_instr; + + reg [15:0] addr_ptr; + reg [15:0] offset_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] indirect_addr; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer ind_instr_list [0:`TEST_IND_PC8_TOTAL_INSTR-1]; + integer instr_idx; + integer postbyte_sel; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] post_byte; + reg [ 7:0] opcode; + reg [15:0] temp16; + reg [15:0] pc_index_reg; + reg [ 7:0] offset8; + + begin + // ind_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + ind_instr_list[ 0] = 'h00_2_2_00_30; // LEAX + ind_instr_list[ 1] = 'h00_2_2_00_31; // LEAY + ind_instr_list[ 2] = 'h00_1_2_00_32; // LEAS + ind_instr_list[ 3] = 'h00_0_2_00_33; // LEAU + ind_instr_list[ 4] = 'h00_2_1_00_60; // NEG + //ind_instr_list[ ] = 'h00_2_1_00_61; // * + //ind_instr_list[ ] = 'h00_2_1_00_62; // * + ind_instr_list[ 5] = 'h00_2_1_00_63; // COM + ind_instr_list[ 6] = 'h00_2_1_00_64; // LSR + //ind_instr_list[ ] = 'h00_2_1_00_65; // * + ind_instr_list[ 7] = 'h00_2_1_00_66; // ROR + ind_instr_list[ 8] = 'h00_2_1_00_67; // ASR + ind_instr_list[ 9] = 'h00_2_1_00_68; // ASL,LSL + ind_instr_list[10] = 'h00_2_1_00_69; // ROL + ind_instr_list[11] = 'h00_2_1_00_6A; // DEC + //ind_instr_list[ ] = 'h00_2_1_00_6B; // * + ind_instr_list[12] = 'h00_2_1_00_6C; // INC + ind_instr_list[13] = 'h00_2_1_00_6D; // TST + //ind_instr_list[ ] = 'h00_2_1_00_6E; // JMP + ind_instr_list[14] = 'h00_2_1_00_6F; // CLR + ind_instr_list[15] = 'h00_2_1_00_A0; // SUBA + ind_instr_list[16] = 'h00_2_1_00_A1; // CMPA + ind_instr_list[17] = 'h00_2_1_00_A2; // SBCA + ind_instr_list[18] = 'h00_2_2_00_A3; // SUBD + ind_instr_list[19] = 'h00_2_1_00_A4; // ANDA + ind_instr_list[20] = 'h00_2_1_00_A5; // BITA + ind_instr_list[21] = 'h00_2_1_00_A6; // LDA + ind_instr_list[22] = 'h00_2_1_00_A7; // STA + ind_instr_list[23] = 'h00_2_1_00_A8; // EORA + ind_instr_list[24] = 'h00_2_1_00_A9; // ADCA + ind_instr_list[25] = 'h00_2_1_00_AA; // ORA + ind_instr_list[26] = 'h00_2_1_00_AB; // ADDA + ind_instr_list[27] = 'h00_2_2_00_AC; // CMPX + //ind_instr_list[ ] = 'h00_2_1_00_AD; // JSR + ind_instr_list[28] = 'h00_2_2_00_AE; // LDX + ind_instr_list[29] = 'h00_2_2_00_AF; // STX + ind_instr_list[30] = 'h00_2_1_00_E0; // SUBB + ind_instr_list[31] = 'h00_2_1_00_E1; // CMPB + ind_instr_list[32] = 'h00_2_1_00_E2; // SBCB + ind_instr_list[33] = 'h00_2_2_00_E3; // ADDD + ind_instr_list[34] = 'h00_2_1_00_E4; // ANDB + ind_instr_list[35] = 'h00_2_1_00_E5; // BITB + ind_instr_list[36] = 'h00_2_1_00_E6; // LDB + ind_instr_list[37] = 'h00_2_1_00_E7; // STB + ind_instr_list[38] = 'h00_2_1_00_E8; // EORB + ind_instr_list[39] = 'h00_2_1_00_E9; // ADCB + ind_instr_list[40] = 'h00_2_1_00_EA; // ORB + ind_instr_list[41] = 'h00_2_1_00_EB; // ADDB + ind_instr_list[42] = 'h00_2_2_00_EC; // LDD + ind_instr_list[43] = 'h00_2_2_00_ED; // STD + ind_instr_list[44] = 'h00_0_2_00_EE; // LDU + ind_instr_list[45] = 'h00_0_2_00_EF; // STU + + // Page 2 + ind_instr_list[46] = 'h00_2_2_10_A3; // CMPD + ind_instr_list[47] = 'h00_2_2_10_AC; // CMPY + ind_instr_list[48] = 'h00_2_2_10_AE; // LDY + ind_instr_list[49] = 'h00_2_2_10_AF; // STY + ind_instr_list[50] = 'h00_1_2_10_EE; // LDS + ind_instr_list[51] = 'h00_1_2_10_EF; // STS + + // Page 3 + ind_instr_list[52] = 'h00_0_2_11_A3; // CMPU + ind_instr_list[53] = 'h00_1_2_11_AC; // CMPS + + + for (instr_idx = 0; instr_idx < `TEST_IND_PC8_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = ind_instr_list[instr_idx][ 7: 0]; + prebyte = ind_instr_list[instr_idx][15: 8]; + operand_size = ind_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_ind_pc8_instr]"); + $display("[TB: tc_dv_ind_pc8_instr]"); + $display("[TB: tc_dv_ind_pc8_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_ind_pc8_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_ind_pc8_instr] ////////////////////////////////////////////////////////////////////"); + + for (postbyte_sel = 0; postbyte_sel < 4; postbyte_sel++) begin + + $display("[TB: tc_dv_ind_pc8_instr]"); + + ///////////////// Set post-byte one of the index registers. + // + case (postbyte_sel) + 0: post_byte = 'hFC; + 1: post_byte = 'hDC; + 2: post_byte = 'hBC; + 3: post_byte = 'h9C; + endcase + $display("[TB: tc_dv_ind_pc8_instr] //////////// Selecting postbyte 0x%x for PC 8bit offset", post_byte); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_ind_pc8_instr]"); + $write("[TB: tc_dv_ind_pc8_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(ind_instr_list[instr_idx][21:20]); + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_ind_pc8_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_ind_pc8_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 60 9C 7F neg [127, PC] + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write post-byte + write_tb_mem8p(addr_ptr, post_byte); + addr_ptr++; + $display("Writing post-byte for 8-bit offset Indexed Addressing mode test."); + + // After the post-byte, save space for the 8 bit offset + offset_addr_ptr = addr_ptr; + addr_ptr++; + $display("[TB: tc_dv_ind_pc8_instr] Offset field in instruction at address: 0x%x", offset_addr_ptr); + + // After the offset, save the PC value + // + pc_index_reg = addr_ptr; + $display("[TB: tc_dv_ind_pc8_instr] PC = 0x%x", pc_index_reg); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to go forwards or backwards + // + if (prebyte) begin + temp16 = 16'd1; + end else begin + temp16 = 16'd0; + end + // + if(rand32[31]) begin + $write("[TB: tc_dv_ind_pc8_instr] Creating a random indirect address for a forward PC 8bit index... "); + indirect_addr = data_block_start + ((rand32[15:0])%((`asm_code_under_test_idx_pc8_fwd + temp16) - data_block_start)); + $display("effective address = 0x%4x", indirect_addr); + end else begin + $write("[TB: tc_dv_ind_pc8_instr] Creating a random indirect address for a backward PC 8bit index... "); + indirect_addr = (`asm_code_under_test_idx_pc8_bwd + temp16) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test_idx_pc8_bwd + temp16) - operand_size)); + $display("effective address = 0x%4x", indirect_addr); + end + + // Re-randomize + rand32 = {$random(seed)}; + + if(rand32[31]) begin + $write("[TB: tc_dv_ind_pc8_instr] Creating a random effective address for a forward PC 8bit index... "); + data_ea = data_block_start + ((rand32[15:0])%((`asm_code_under_test_idx_pc8_fwd + temp16) - data_block_start)); + $display("effective address = 0x%4x", data_ea); + end else begin + $write("[TB: tc_dv_ind_pc8_instr] Creating a random effective address for a backward PC 8bit index... "); + data_ea = (`asm_code_under_test_idx_pc8_bwd + temp16) + ((rand32[15:0])%(`asm_code_under_test_mid - (`asm_code_under_test_idx_pc8_bwd + temp16) - operand_size)); + $display("effective address = 0x%4x", data_ea); + end + + write_tb_mem16p(indirect_addr, data_ea); + + ///////////////// Create a random relative address offset for the data + // + $write("[TB: tc_dv_ind_pc8_instr] Calculate offset... "); + temp16 = indirect_addr - pc_index_reg; // Offset = ea - pc + offset8 = temp16[7:0]; + $display("8bit offset = 0x%2x", offset8); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem8p(offset_addr_ptr, offset8); + $display("writing 8-bit offset to the offset field after postbyte"); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_u_s, ); // U or S + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_x, ); // X + + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_ind_pc8_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_ind_pc8_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_IND_PC8_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_ind_pc8_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_ind_pc8_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_IND_PC8_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_ind_pc8_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_IND_PC8_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_ind_pc8_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_ind_pc8_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_ind_pc8_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_ind_pc8_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_ind_pc8_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_ind_pc8_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_inh_instr.v b/turbo9team_turbo9/tb/tc_dv_inh_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..39231a907f85ea9e718a0f3c6da486267bc28f16 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_inh_instr.v @@ -0,0 +1,298 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Inherent instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Inherent Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_INH_TOTAL_INSTR 30 + `define TEST_INH_RESET_CYCLES 40 // (16 nominal) + `define TEST_INH_START_CYCLES 200 // (100 nominal) + `define TEST_INH_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_inh_instr; + + reg [15:0] addr_ptr; + reg [15:0] inh_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer inh_instr_list [0:`TEST_INH_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // inh_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + //inh_instr_list[] = 'h00_2_1_00_10; // Page 1 + //inh_instr_list[] = 'h00_2_1_00_11; // Page 2 + inh_instr_list[ 0] = 'h00_2_1_00_12; // NOP + //inh_instr_list[] = 'h00_2_1_00_13; // SYNC + inh_instr_list[ 1] = 'h00_2_1_00_14; // EMUL + //inh_instr_list[] = 'h00_2_1_00_15; + //inh_instr_list[] = 'h00_2_1_00_16; // LBRA + //inh_instr_list[] = 'h00_2_1_00_17; // LBSR + inh_instr_list[ 2] = 'h00_2_1_00_18; // IDIV + inh_instr_list[ 3] = 'h00_2_1_00_19; // DAA + //inh_instr_list[] = 'h00_2_1_00_1A; // ORCC + //inh_instr_list[] = 'h00_2_1_00_1B; + //inh_instr_list[] = 'h00_2_1_00_1C; // ANDCC + inh_instr_list[ 4] = 'h00_2_1_00_1D; // SEX + //inh_instr_list[] = 'h00_2_1_00_1E; // EXG + //inh_instr_list[] = 'h00_2_1_00_1F; // TRF + + inh_instr_list[ 5] = 'h00_2_1_00_3A; // ABX + inh_instr_list[ 6] = 'h00_2_1_00_3D; // MUL + // + inh_instr_list[ 7] = 'h00_2_1_00_40; // NEGA + //inh_instr_list[] = 'h00_2_1_00_41; + //inh_instr_list[] = 'h00_2_1_00_42; + inh_instr_list[ 8] = 'h00_2_1_00_43; // COMA + inh_instr_list[ 9] = 'h00_2_1_00_44; // LSRA + //inh_instr_list[] = 'h00_2_1_00_45; + inh_instr_list[10] = 'h00_2_1_00_46; // RORA + inh_instr_list[11] = 'h00_2_1_00_47; // ASRA + inh_instr_list[12] = 'h00_2_1_00_48; // ASLA,LSLA + inh_instr_list[13] = 'h00_2_1_00_49; // ROLA + inh_instr_list[14] = 'h00_2_1_00_4A; // DECA + //inh_instr_list[] = 'h00_2_1_00_4B; + inh_instr_list[15] = 'h00_2_1_00_4C; // INCA + inh_instr_list[16] = 'h00_2_1_00_4D; // TSTA + //inh_instr_list[] = 'h00_2_1_00_4E; + inh_instr_list[17] = 'h00_2_1_00_4F; // CLRA + // + inh_instr_list[18] = 'h00_2_1_00_50; // NEGB + //inh_instr_list[] = 'h00_2_1_00_51; + //inh_instr_list[] = 'h00_2_1_00_52; + inh_instr_list[19] = 'h00_2_1_00_53; // COMB + inh_instr_list[20] = 'h00_2_1_00_54; // LSRB + //inh_instr_list[] = 'h00_2_1_00_55; + inh_instr_list[21] = 'h00_2_1_00_56; // RORB + inh_instr_list[22] = 'h00_2_1_00_57; // ASRB + inh_instr_list[23] = 'h00_2_1_00_58; // ASLB,LSLB + inh_instr_list[24] = 'h00_2_1_00_59; // ROLB + inh_instr_list[25] = 'h00_2_1_00_5A; // DECB + //inh_instr_list[] = 'h00_2_1_00_5B; + inh_instr_list[26] = 'h00_2_1_00_5C; // INCB + inh_instr_list[27] = 'h00_2_1_00_5D; // TSTB + //inh_instr_list[] = 'h00_2_1_00_5E; + inh_instr_list[28] = 'h00_2_1_00_5F; // CLRB + inh_instr_list[29] = 'h00_2_1_10_18; // IDIVS + + + for (instr_idx = 0; instr_idx < `TEST_INH_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = inh_instr_list[instr_idx][ 7: 0]; + prebyte = inh_instr_list[instr_idx][15: 8]; + operand_size = inh_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_inh_instr]"); + $display("[TB: tc_dv_inh_instr]"); + $display("[TB: tc_dv_inh_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_inh_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_inh_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_inh_instr]"); + $write("[TB: tc_dv_inh_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(inh_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_inh_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_inh_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_inh_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_inh_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_INH_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_inh_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_inh_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_INH_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_inh_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_INH_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_inh_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_inh_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_inh_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_inh_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_inh_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_inh_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_rel16_instr.v b/turbo9team_turbo9/tb/tc_dv_rel16_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..684889b07a7529a67e13fa68f67368e78a452033 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_rel16_instr.v @@ -0,0 +1,304 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testcase: Relative 16-bit instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Relative (16-Bit) Long Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_REL16_TOTAL_INSTR 17 + `define TEST_REL16_RESET_CYCLES 40 // (16 nominal) + `define TEST_REL16_START_CYCLES 200 // (100 nominal) + `define TEST_REL16_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_rel16_instr; + + reg [15:0] addr_ptr; + reg [15:0] rel_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] effective_addr; + reg [31:0] rand32; + reg [15:0] rel_addr_offset; + reg [15:0] temp16; + + integer rel_instr_list [0:`TEST_REL16_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // rel_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + rel_instr_list[ 0] = 'h00_2_1_00_16; // LBRA + //rel_instr_list[] = 'h00_2_1_00_17; // LBSR (different test needed) + rel_instr_list[ 1] = 'h00_2_1_10_20; // LBRA + rel_instr_list[ 2] = 'h00_2_1_10_21; // LBRN + rel_instr_list[ 3] = 'h00_2_1_10_22; // LBHI + rel_instr_list[ 4] = 'h00_2_1_10_23; // LBLS + rel_instr_list[ 5] = 'h00_2_1_10_24; // LBHS,LBCC + rel_instr_list[ 6] = 'h00_2_1_10_25; // LBLO,LBCS + rel_instr_list[ 7] = 'h00_2_1_10_26; // LBNE + rel_instr_list[ 8] = 'h00_2_1_10_27; // LBEQ + rel_instr_list[ 9] = 'h00_2_1_10_28; // LBVC + rel_instr_list[10] = 'h00_2_1_10_29; // LBVS + rel_instr_list[11] = 'h00_2_1_10_2A; // LBPL + rel_instr_list[12] = 'h00_2_1_10_2B; // LBMI + rel_instr_list[13] = 'h00_2_1_10_2C; // LBGE + rel_instr_list[14] = 'h00_2_1_10_2D; // LBLT + rel_instr_list[15] = 'h00_2_1_10_2E; // LBGT + rel_instr_list[16] = 'h00_2_1_10_2F; // LBLE + + for (instr_idx = 0; instr_idx < `TEST_REL16_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = rel_instr_list[instr_idx][ 7: 0]; + prebyte = rel_instr_list[instr_idx][15: 8]; + operand_size = rel_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_rel_instr]"); + $display("[TB: tc_dv_rel_instr]"); + $display("[TB: tc_dv_rel_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_rel_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_rel_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_rel_instr]"); + $write("[TB: tc_dv_rel_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(rel_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_rel_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_rel_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Save address pointer + rel_addr_ptr = addr_ptr; + addr_ptr+=2; + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to branch forwards or backwards + // + if(rand32[31]) begin + $write("[TB: tc_dv_rel_instr] Creating a random address for a forward branch... "); + effective_addr = data_block_start + ((rand32[15:0])%(`asm_data_block_end - data_block_start - 4)); + end else begin + $write("[TB: tc_dv_rel_instr] Creating a random address for a backward branch... "); + effective_addr = `asm_code_under_test + ((rand32[15:0])%(`asm_code_under_test_mid - `asm_code_under_test - 4)); + end + $display("effective address = 0x%4x", effective_addr); + + + ///////////////// Create a random relative address offset for the data + // + $write("[TB: tc_dv_rel_instr] Calculate relative address offset... "); + rel_addr_offset = effective_addr - (rel_addr_ptr + 1); // Offset = ea - pc + $display("relative offset = 0x%2x", rel_addr_offset); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem16p(rel_addr_ptr, rel_addr_offset); + $display("writing relative offset to the relative address field in instruction"); + + + ///////////////// Write INCA + // + addr_ptr = effective_addr; + write_opcode('h0, 'h4C, addr_ptr, 1'b0); + $display(" writing INCA canary instruction"); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test_mid"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_rel_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_rel_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_REL16_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_rel_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_rel_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_REL16_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_rel_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_REL16_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_rel_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_rel_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_rel_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_rel_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_rel_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_rel_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_rel_instr.v b/turbo9team_turbo9/tb/tc_dv_rel_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..1dfbd969e1753e0aa6d808251b2b1280f2473b53 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_rel_instr.v @@ -0,0 +1,305 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testcase: Relative 8-bit instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Relative (8-bit) Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_REL_TOTAL_INSTR 16 + `define TEST_REL_RESET_CYCLES 40 // (16 nominal) + `define TEST_REL_START_CYCLES 200 // (100 nominal) + `define TEST_REL_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_rel_instr; + + reg [15:0] addr_ptr; + reg [15:0] rel_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] effective_addr; + reg [31:0] rand32; + reg [ 7:0] rel_addr_offset; + reg [15:0] temp16; + + integer rel_instr_list [0:`TEST_REL_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // rel_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + rel_instr_list[ 0] = 'h00_2_1_00_20; // BRA + rel_instr_list[ 1] = 'h00_2_1_00_21; // BRN + rel_instr_list[ 2] = 'h00_2_1_00_22; // BHI + rel_instr_list[ 3] = 'h00_2_1_00_23; // BLS + rel_instr_list[ 4] = 'h00_2_1_00_24; // BHS,BCC + rel_instr_list[ 5] = 'h00_2_1_00_25; // BLO,BCS + rel_instr_list[ 6] = 'h00_2_1_00_26; // BNE + rel_instr_list[ 7] = 'h00_2_1_00_27; // BEQ + rel_instr_list[ 8] = 'h00_2_1_00_28; // BVC + rel_instr_list[ 9] = 'h00_2_1_00_29; // BVS + rel_instr_list[10] = 'h00_2_1_00_2A; // BPL + rel_instr_list[11] = 'h00_2_1_00_2B; // BMI + rel_instr_list[12] = 'h00_2_1_00_2C; // BGE + rel_instr_list[13] = 'h00_2_1_00_2D; // BLT + rel_instr_list[14] = 'h00_2_1_00_2E; // BGT + rel_instr_list[15] = 'h00_2_1_00_2F; // BLE + //rel_instr_list[16] = 'h00_2_1_00_8D; // BSR (different test needed) + + for (instr_idx = 0; instr_idx < `TEST_REL_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = rel_instr_list[instr_idx][ 7: 0]; + prebyte = rel_instr_list[instr_idx][15: 8]; + operand_size = rel_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_rel_instr]"); + $display("[TB: tc_dv_rel_instr]"); + $display("[TB: tc_dv_rel_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_rel_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_rel_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_rel_instr]"); + $write("[TB: tc_dv_rel_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(rel_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_rel_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_rel_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test_mid; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Save address pointer + rel_addr_ptr = addr_ptr; + addr_ptr++; + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + data_block_start = addr_ptr; + rand32 = {$random(seed)}; + + ///////////////// 50/50 choice to branch forwards or backwards + // + if(rand32[31]) begin + $write("[TB: tc_dv_rel_instr] Creating a random address for a forward branch... "); + effective_addr = data_block_start + ((rand32[15:0])%(`asm_code_under_test_br_fwd - data_block_start)); + $display("effective address = 0x%4x", effective_addr); + end else begin + $write("[TB: tc_dv_rel_instr] Creating a random address for a backward branch... "); + effective_addr = `asm_code_under_test_br_bwd + ((rand32[15:0])%(`asm_code_under_test_mid - `asm_code_under_test_br_bwd - 4)); // 4bytes of INCA, JMP + $display("effective address = 0x%4x", effective_addr); + end + + + ///////////////// Create a random relative address offset for the data + // + $write("[TB: tc_dv_rel_instr] Calculate relative address offset... "); + temp16 = effective_addr - (rel_addr_ptr + 1); // Offset = ea - pc + rel_addr_offset = temp16[7:0]; + $display("relative offset = 0x%2x", rel_addr_offset); + + + ///////////////// Write offset byte for relative address instructions + // + write_tb_mem8p(rel_addr_ptr, rel_addr_offset); + $display("writing relative offset to the relative address field in instruction"); + + + ///////////////// Write INCA + // + addr_ptr = effective_addr; + write_opcode('h0, 'h4C, addr_ptr, 1'b0); + $display(" writing INCA canary instruction"); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test_mid); $display("setting PC stack intialization value to `asm_code_under_test_mid"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_rel_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_rel_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_REL_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_rel_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_rel_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_REL_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_rel_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_REL_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_rel_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_rel_instr] Test PASS for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_rel_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_rel_instr] Test FAIL for interation %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_rel_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_rel_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_run_code.v b/turbo9team_turbo9/tb/tc_dv_run_code.v new file mode 100644 index 0000000000000000000000000000000000000000..83f55f64c17ab8415349a5ec0a32c07b43ba3737 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_run_code.v @@ -0,0 +1,177 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson +// Description: Testcase: Run Code +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Test Code Testcase +///////////////////////////////////////////////////////////////////////////// + + `define RUN_CODE_RESET_CYCLES 100 + `define RUN_CODE_START_CYCLES 10_000 + `define RUN_CODE_FINISH_CYCLES 300_000_000 + + //////////////////////////////////////////////////////////////////////////// + // Test Code + //////////////////////////////////////////////////////////////////////////// + task tc_dv_run_code; + + integer error_cnt; + real dut_ticks; + real model_ticks; + real ratio; + + begin + + ///////////////// Load the instruction setup + // + $display("[TB: tc_dv_run_code]"); + $display("[TB: tc_dv_run_code]"); + $display("[TB: tc_dv_run_code] ////////////////////////////////////////////////////////////////////"); + $display("[TB; tc_dv_run_code] // Test Code "); + $display("[TB: tc_dv_run_code] ////////////////////////////////////////////////////////////////////"); + + error_cnt = 0; + + ///////////////// Loading HEX test code + // + $display("[TB: tc_dv_run_code] Loading HEX test code: %0s",hex_file); + $readmemh(hex_file,`tb_mem); + + ///////////////// Loading S19 test code + // + if (s19_file != "") begin + $display("[TB: tc_dv_run_code] Loading S19 test code: %0s",s19_file); + load_s19_tb_mem(s19_file); + end + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_run_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Open Console File + // + console_file_open("tc_dv_run_code"); + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_run_code] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `RUN_CODE_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_run_code] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_run_code] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `RUN_CODE_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_run_code] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `RUN_CODE_FINISH_CYCLES, error_cnt); + model_ticks = model_cycle_cnt; + dut_ticks = `dut_cycle_cnt; + + wait_clk_cycles(32); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + $display("[TB: tc_dv_run_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Close Console File + // + console_file_close; + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_run_code] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + ///////////////// Display performance + // + $display("[TB: tc_dv_run_code] Turbo9 clock cycles: %16d", dut_ticks); + $display("[TB: tc_dv_run_code] 6809 Model E clock cycles: %16d", model_ticks); + ratio = model_ticks / dut_ticks; + $display("[TB: tc_dv_run_code] Ratio: %f", ratio); + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + if (s19_file != "") begin + $display("[TB: tc_dv_run_code] Test PASS for %0s",s19_file); + end else begin + $display("[TB: tc_dv_run_code] Test PASS for %0s",hex_file); + end + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_run_code] ERROR count: %0d", error_cnt); + if (s19_file != "") begin + $display("[TB; tc_dv_run_code] Test FAIL for %0s",s19_file); + end else begin + $display("[TB; tc_dv_run_code] Test FAIL for %0s",hex_file); + end + $display("[TB: tc_dv_run_code] Exiting... "); + fail_test_cnt++; + end + + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_sau_instr.v b/turbo9team_turbo9/tb/tc_dv_sau_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..794521cb4241fdaa434e3b689545a21f56d38715 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_sau_instr.v @@ -0,0 +1,282 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Sequential Arithmetic Unit instructions +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Inherent Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_SAU_TOTAL_INSTR 9 + `define TEST_SAU_RESET_CYCLES 40 // (16 nominal) + `define TEST_SAU_START_CYCLES 200 // (100 nominal) + `define TEST_SAU_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_sau_instr; + + reg [15:0] addr_ptr; + reg [15:0] inh_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer inh_instr_list [0:`TEST_SAU_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + + begin + // inh_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + inh_instr_list[ 0] = 'h00_2_1_00_14; // EMUL + inh_instr_list[ 1] = 'h00_2_1_00_15; // EMULS + inh_instr_list[ 2] = 'h00_2_1_00_18; // IDIV + inh_instr_list[ 3] = 'h00_2_1_00_19; // DAA + inh_instr_list[ 4] = 'h00_2_1_00_3D; // MUL + inh_instr_list[ 5] = 'h00_2_1_10_14; // EDIV + inh_instr_list[ 6] = 'h00_2_1_10_15; // EDIVS + inh_instr_list[ 7] = 'h00_2_1_10_18; // IDIVS + inh_instr_list[ 8] = 'h00_2_1_10_19; // FDIV + + + for (instr_idx = 0; instr_idx < `TEST_SAU_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = inh_instr_list[instr_idx][ 7: 0]; + prebyte = inh_instr_list[instr_idx][15: 8]; + operand_size = inh_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_sau_instr]"); + $display("[TB: tc_dv_sau_instr]"); + $display("[TB: tc_dv_sau_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_sau_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_sau_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_sau_instr]"); + $write("[TB: tc_dv_sau_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(inh_instr_list[instr_idx][21:20]); + + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_sau_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_sau_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 70 FF 42 neg >data_addr + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + if (rand_itr_idx[1:0] == 2'b01) begin + case({prebyte,opcode}) + 'h00_14, // EMUL Y:D = D * Y + 'h00_15: begin // EMULS Y:D = D * Y + write_tb_mem16p( `asm_init_a, random_corner_num16(0) ); $display(" FORCE CORNER VALUE register D "); + write_tb_mem16p( `asm_init_y, random_corner_num16(0) ); $display(" FORCE CORNER VALUE register Y "); + end + 'h00_18, // IDIV X = D / X, D = R + 'h10_18, // IDIVS X = D / X, D = R + 'h10_19: begin // FDIV X = D / X, D = R + write_tb_mem16p( `asm_init_a, random_corner_num16(0) ); $display(" FORCE CORNER VALUE register D "); + write_tb_mem16p( `asm_init_x, random_corner_num16(0) ); $display(" FORCE CORNER VALUE register X "); + end + 'h00_19: begin // DAA A = A + BDC_CF + write_tb_mem8p( `asm_init_a, random_corner_num8(0) ); $display(" FORCE CORNER VALUE register A "); + end + 'h00_3D: begin // MUL D = A * B + write_tb_mem8p( `asm_init_a, random_corner_num8(0) ); $display(" FORCE CORNER VALUE register A "); + write_tb_mem8p( `asm_init_b, random_corner_num8(0) ); $display(" FORCE CORNER VALUE register B "); + end + 'h10_14, // EDIV Y = Y:D / X, D = R + 'h10_15: begin // EDIVS Y = Y:D / X, D = R + rand32 = random_corner_num32(0); + write_tb_mem16p( `asm_init_y, rand32[31:16] ); $display(" FORCE CORNER VALUE register Y "); + write_tb_mem16p( `asm_init_a, rand32[15: 0] ); $display(" FORCE CORNER VALUE register D "); + write_tb_mem16p( `asm_init_x, random_corner_num16(0) ); $display(" FORCE CORNER VALUE register X "); + end + endcase + end + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_sau_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_sau_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_SAU_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_sau_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_sau_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_SAU_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_sau_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_SAU_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + + + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_sau_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_sau_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_sau_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_sau_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_sau_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_sau_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_tfr_16b_instr.v b/turbo9team_turbo9/tb/tc_dv_tfr_16b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..6c646ed5b6b7052ab4488869049488e8cfd75448 --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_tfr_16b_instr.v @@ -0,0 +1,278 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Transfer instruction w/ 16-bit registers +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Inherent Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_EXG_16_TOTAL_INSTR 1 + `define TEST_EXG_16_RESET_CYCLES 40 // (16 nominal) + `define TEST_EXG_16_START_CYCLES 200 // (100 nominal) + `define TEST_EXG_16_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_tfr_16b_instr; + + reg [15:0] addr_ptr; + reg [15:0] inh_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer inh_instr_list [0:`TEST_EXG_16_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + reg [ 3:0] msn; + reg [ 3:0] lsn; + + begin + // inh_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + inh_instr_list[0] = 'h00_2_1_00_1E; // EXG_16 + + for (instr_idx = 0; instr_idx < `TEST_EXG_16_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = inh_instr_list[instr_idx][ 7: 0]; + prebyte = inh_instr_list[instr_idx][15: 8]; + operand_size = inh_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_tfr_16b_instr]"); + $display("[TB: tc_dv_tfr_16b_instr]"); + $display("[TB: tc_dv_tfr_16b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_tfr_16b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_tfr_16b_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_tfr_16b_instr]"); + $write("[TB: tc_dv_tfr_16b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(inh_instr_list[instr_idx][21:20]); + + // Get a random number to use to select bits for most and least significant bits of exchange postbyte. + rand32 = {$random(seed)}; + msn = rand32[31:29] % 4; // we can only use values between 0 and 4 + lsn = rand32[28:26] % 4; // same as above. + + // If the S stack pointer is selected, make sure the msn doesn't select S. + // Otherwise if U is selected as the stack pointer, make sure the msn doesn't select U. + if(!stack_ptr_sel && msn == 'h4) msn--; + else if(stack_ptr_sel && msn == 'h3) msn++; + + // If the S stack pointer is selected, make sure the lsn doesn't select S. + // Otherwise if U is selected as the stack pointer, make sure the lsn doesn't select U. + if(!stack_ptr_sel && lsn == 'h4) lsn--; + else if(stack_ptr_sel && lsn == 'h3) lsn++; + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_tfr_16b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_tfr_16b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 1E 12 exg x,y + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Write the postbyte to the opcode + write_tb_mem8p(addr_ptr, {msn,lsn}); + addr_ptr++; + + case(msn) + 'b000: $write("D"); + 'b001: $write("X"); + 'b010: $write("Y"); + 'b011: $write("US"); + 'b100: $write("SP"); + endcase + $write(" -> transferred to -> "); + case(lsn) + 'b000: $write("D"); + 'b001: $write("X"); + 'b010: $write("Y"); + 'b011: $write("US"); + 'b100: $write("SP"); + endcase + $display(""); + + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_tfr_16b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_tfr_16b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_EXG_16_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_tfr_16b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_tfr_16b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_EXG_16_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_tfr_16b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_EXG_16_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_tfr_16b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_tfr_16b_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_tfr_16b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_tfr_16b_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_tfr_16b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_tfr_16b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/tb/tc_dv_tfr_8b_instr.v b/turbo9team_turbo9/tb/tc_dv_tfr_8b_instr.v new file mode 100644 index 0000000000000000000000000000000000000000..9818f07da002aae3831c73d8456484ebf21d3e3f --- /dev/null +++ b/turbo9team_turbo9/tb/tc_dv_tfr_8b_instr.v @@ -0,0 +1,262 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson & Michael Rywalt +// Description: Testcase: Transfer instruction w/ 8-bit registers +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +///////////////////////////////////////////////////////////////////////////// +// Inherent Addressing Instruction Testcase +///////////////////////////////////////////////////////////////////////////// + + `define TEST_TFR_8_TOTAL_INSTR 1 + `define TEST_TFR_8_RESET_CYCLES 40 // (16 nominal) + `define TEST_TFR_8_START_CYCLES 200 // (100 nominal) + `define TEST_TFR_8_FINISH_CYCLES 500 // (240 nominal) + + //////////////////////////////////////////////////////////////////////////// + // Test Direct Addressing Instructions + //////////////////////////////////////////////////////////////////////////// + task tc_dv_tfr_8b_instr; + + reg [15:0] addr_ptr; + reg [15:0] inh_addr_ptr; + reg [15:0] data_block_start; + reg [15:0] data_ea; + reg [31:0] rand32; + + integer inh_instr_list [0:`TEST_TFR_8_TOTAL_INSTR-1]; + integer instr_idx; + integer error_cnt; + + integer rand_itr_idx; + + reg stack_ptr_sel; + reg [ 1:0] operand_size; + reg [ 7:0] prebyte; + reg [ 7:0] opcode; + + reg [ 3:0] msn; + reg [ 3:0] lsn; + + begin + // inh_instr_list define: + // [23:20] : Stack ptr sel : 'h0 = S / 'h1 = U / 'h2 = random + // [19:16] : Operand size : 'h1 = 8bit / 'h2 = 16bit + // [15: 8] : Prebyte : 'h00 = none / 'h10 = Page2 / 'h11 = Page3 + // [ 7: 0] : Opcode + + // Page 1 + inh_instr_list[0] = 'h00_2_1_00_1E; // TFR_8 + + for (instr_idx = 0; instr_idx < `TEST_TFR_8_TOTAL_INSTR; instr_idx++) begin + + ///////////////// Load the instruction setup + // + opcode = inh_instr_list[instr_idx][ 7: 0]; + prebyte = inh_instr_list[instr_idx][15: 8]; + operand_size = inh_instr_list[instr_idx][17:16]; + $display("[TB: tc_dv_tfr_8b_instr]"); + $display("[TB: tc_dv_tfr_8b_instr]"); + $display("[TB: tc_dv_tfr_8b_instr] ////////////////////////////////////////////////////////////////////"); + $write("[TB; tc_dv_tfr_8b_instr] // Testcase "); + print_opcode_info(prebyte, opcode, 1'b1); + $display("[TB: tc_dv_tfr_8b_instr] ////////////////////////////////////////////////////////////////////"); + + rand_itr_idx = 1; + error_cnt = 0; + while ((rand_itr_idx <= rand_itr_total) && (error_cnt == 0)) begin + + $display("[TB: tc_dv_tfr_8b_instr]"); + $write("[TB: tc_dv_tfr_8b_instr] Random Iteration %0d of %0d for ",rand_itr_idx,rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + + ///////////////// Select or randomize the stack pointer + // + stack_ptr_sel = choose_stack_ptr(inh_instr_list[instr_idx][21:20]); + + // Get a random number to use to select bits for most and least significant bits of exchange postbyte. + rand32 = {$random(seed)}; + msn = rand32[31:29] % 3; // we can only use values between 0 and 3. + lsn = rand32[28:26] % 3; // same as above. + msn[3] = 1'b1; // append the top one bit to indicate 8-bit registers for exchange. + lsn[3] = 1'b1; + + ///////////////// Loading testbench template + // + if (rand_itr_idx == 1) begin + $display("[TB: tc_dv_tfr_8b_instr] Loading testbench template: %0s", hex_file); + $readmemh(hex_file,`tb_mem); + end else begin + $display("[TB: tc_dv_tfr_8b_instr] Skip loading testbench template for subsequent randomization iterations"); + end + + ///////////////// Randomizing data block + // + random_block_p(`asm_code_under_test,`asm_data_block_last_byte); + $display("writing random data from `asm_code_under_test to `asm_data_block_last_byte"); + + + ///////////////// Write opcode under test + // + // code_under_test: + // 1E 89 tfr a,b + // 7E F0 1F jmp save_state + // + addr_ptr = `asm_code_under_test; + write_opcode(prebyte, opcode, addr_ptr, 1'b0); + $display(" *** OPCODE UNDER TEST *** "); + + // Write the postbyte to the opcode + write_tb_mem8p(addr_ptr, {msn,lsn}); + addr_ptr++; + + case(msn) + 'b1000: $write("A"); + 'b1001: $write("B"); + 'b1010: $write("CCR"); + 'b1011: $write("DPR"); + endcase + $write(" -> transferred to -> "); + case(lsn) + 'b1000: $write("A"); + 'b1001: $write("B"); + 'b1010: $write("CCR"); + 'b1011: $write("DPR"); + endcase + $display(""); + + ///////////////// Write JMP opcode & program done address + // + write_jump_done(stack_ptr_sel, addr_ptr); + + ///////////////// Write random data to stack & vector table + // + random_block_p(`asm_stack_end, 16'hFFFF); + $display("writing random data to stack & vector table *** This includes processor initalization state! ***"); + + ///////////////// Initialize the processor state on the stack + // + //write_tb_mem8p( `asm_init_cc, ); // CC + //write_tb_mem8p( `asm_init_a, ); // A + //write_tb_mem8p( `asm_init_b, ); // B + //write_tb_mem8p( `asm_init_dp, ); // DP + //write_tb_mem16p(`asm_init_x, ); // X + //write_tb_mem16p(`asm_init_y, ); // Y + //write_tb_mem16p(`asm_init_u_s, ); // U or S + write_tb_mem16p(`asm_init_pc,`asm_code_under_test); $display("setting PC stack intialization value to `asm_code_under_test"); + + ///////////////// Initialize Reset Vector + // + write_reset_vector(stack_ptr_sel); + + ///////////////// Copy testbench program into model and DUT memory + // + copy_tb_mem; + + + ///////////////// Reset DUT and Model + // + $display("[TB: tc_dv_tfr_8b_instr] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + + ///////////////// Ensure the output port are cleared + // + $display("[TB: tc_dv_tfr_8b_instr] Waiting for output ports of Model and DUT to clear..."); + wait_bits_clear(8'hFF, `TEST_TFR_8_RESET_CYCLES, error_cnt); + + + ///////////////// Release Reset and begin testcase + // + $display("[TB: tc_dv_tfr_8b_instr] Release reset and begin testcase!"); + reset = 1'b0; + + + ///////////////// Waiting for indication of begining of code under test + // + $display("[TB: tc_dv_tfr_8b_instr] Waiting for Model and DUT to indicate begining of code under test..."); + wait_bits_set(8'h01, `TEST_TFR_8_START_CYCLES, error_cnt); + + + ///////////////// Waiting for indication of completed code under test + // + $display("[TB: tc_dv_tfr_8b_instr] Waiting for Model and DUT to indicate completion of code under test..."); + wait_bits_set(8'h80, `TEST_TFR_8_FINISH_CYCLES, error_cnt); + + wait_clk_cycles(4); // wait a few cycles to capture the output port in waveform dump + + error_cnt += model_error; //add model error to error count + + $display("[TB: tb_dv_test_code] Resetting DUT and Model"); + reset = 1'b1; + wait_clk_cycles(4); + + ///////////////// Running a diff on the memories + // + $display("[TB: tc_dv_tfr_8b_instr] Comparing DUT memory and Model memory..."); + error_cnt += mem_diff_cnt(1'b0); + + + + ///////////////// Test PASS / FAIL summary + // + if (error_cnt == 0) begin + $write("[TB: tc_dv_tfr_8b_instr] Test PASS for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + pass_test_cnt++; + end else begin + $display("[TB: tc_dv_tfr_8b_instr] ERROR count: %0d", error_cnt); + $write("[TB; tc_dv_tfr_8b_instr] Test FAIL for iteration %0d of %0d for ", rand_itr_idx, rand_itr_total); + print_opcode_info(prebyte, opcode, 1'b1); + save_tb_mem("tc_dv_tfr_8b_instr",prebyte,opcode,rand_itr_idx); + $display("[TB: tc_dv_tfr_8b_instr] Exiting randomization iteration loop... "); + fail_test_cnt++; + end + + + rand_itr_idx++; + end + end + end + endtask + diff --git a/turbo9team_turbo9/urtl_asm_src/assemble.c b/turbo9team_turbo9/urtl_asm_src/assemble.c new file mode 100644 index 0000000000000000000000000000000000000000..2c25550be8adcc9fd944709d18daa4dd4e54c5e1 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/assemble.c @@ -0,0 +1,246 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Assembler function library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include "err.h" +#include "log.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "ctrl_vec.h" +#include "macro.h" +#include "strproc.h" +#include "verilog.h" + +static char *null_string = ""; +static macro_ctx_t *_macro_ctx; + +// --==============================================-- +s16 init_assembler(macro_ctx_t *macro_ctx) +{ + s16 retval = ERR_OK; + + if(!macro_ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + _macro_ctx = macro_ctx; + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +s16 assemble(macro_ctx_t *macro_ctx, char *asm_file_name, s16 (*f)(ctrl_vec_ctx_t *, u32, ctrl_vec_t *)) +{ + FILE *asm_file_ptr = NULL; + s16 retval = ERR_OK; + char line[255] = {0}; + char name[255] = {0}; + char macro_name[255] = {0}; + u32 address = 0; + macro_t *macro; + ctrl_vec_ctx_t *cv_ctx; + u08 begin = 0; + u32 line_num = 0; + + asm_file_ptr = fopen(asm_file_name, "r"); + if(asm_file_ptr == NULL) + { + printf("%s - ", asm_file_name); + puts(asm_file_name); + retval = ERR_FILE_IO; + goto done; + } + + if(!macro_ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + cv_ctx = macro_ctx->ctrl_vec_ctx; + + while((fgets(line, 254, asm_file_ptr)) != NULL) + { + line_num++; + + if((retval = dump_comment(line_num, line)) != ERR_OK) + { + printf("dump_comment failed.\n"); + goto done; + } + + if(is_comment(line) || is_empty_line(line)) continue; + + if(strstr(line, "ORG")) + { + //strmspc(line); + if(!sscanf(line, " %*4c %*1c%3lx", &address)) + { + retval = ERR_NOT_FOUND; + goto done; + } + } + else if(strstr(line, "micro_op_end")) + { + u08 idx; + // TODO: Here is where you want to call whatever function to + // convert the current set of control vectors into verilog or + // some other data output. Do this before the call to reset + // below... + + // Here is where the new control vector/EQU can be sent to a verilog + // or other handler, and subsequently dumped. + for(idx = 0; idx < cv_ctx->total_ctrl_vec; idx++) + { + if(cv_ctx->list[idx].equ_is_coded) + { + if((retval = ((*f)(cv_ctx, address, &cv_ctx->list[idx]))) != ERR_OK) + goto done; + } + } + + WRITE_LOG_NF(LOG_HIGH, "###############################################################\n"); + WRITE_LOG_NF(LOG_HIGH, "STATE OF CONTROL VECTORS AT micro_op_end\n"); + print_ctrl_vec_list_equ_sel(cv_ctx); + printf("------------------------------------------------------------------\n"); + + if(begin) + { + if((retval = dump_verilog_end_case()) != ERR_OK) + goto done; + + begin = 0; + } + + if((retval = reset_all_ctrl_vec_equ_sel(cv_ctx)) != ERR_OK) + goto done; + + address++; + } + else if(!get_label(line)) + { + strip_string(line, 1); + get_field(line, macro_name, 0, 0); + + if(strstr(line, "decode") || strstr(line, "decode_init")) + { + printf("Found a decode/decode_init, ignoring\n"); + continue; + } + + // Get a pointer to the current macro. + if((macro = find_macro_by_name(macro_ctx, macro_name)) != NULL) + { + u08 cv_idx; + ctrl_vec_t *ctrl_vec; + equ_t *equ; + begin = 1; + + // Only if the macro has control vector defs... + + if(macro->total_ctrl_vec > 0) + { + printf("Address: %05lx: Macro Name: %s, Num Ctrl Vecs: %d, Num Args: %d\n", address, macro_name, macro->total_ctrl_vec, macro->total_args); + + // Iterate over each of the control vector defs in the macro. + for(cv_idx = 0; cv_idx < macro->total_ctrl_vec; cv_idx++) + { + // Now get a pointer to the actual control vector from the original ctrl_vec list. + ctrl_vec = macro->ctrl_vec_def[cv_idx].ctrl_vec; + + // If this is an EQU (not a parameterized value)... + if(macro->ctrl_vec_def[cv_idx].arg_num < 0) + { + printf("\tVAL: "); + equ = macro->ctrl_vec_def[cv_idx].data.equ; + } + // Otherwise, this is a parameterized value (arg)... + else + { + // Parse the current line, get the name of the EQU name from the line. + if((retval = get_field(line, name, macro->ctrl_vec_def[cv_idx].data.value + 1, 0)) < ERR_OK) + goto done; + + printf("\tARG: "); + + // Using the EQU as parameter, now find it in the given control vector. + if((equ = find_equ_by_name(ctrl_vec, name)) == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + } + + printf("\tctrl_vec: %s \tequ: %d (%s)\n", macro->ctrl_vec_def[cv_idx].ctrl_vec->name, equ->value, equ->name); + // + // In any case, now that we have an equ, either by value or arg, + // assign it to the current control vector. + if((retval = set_ctrl_vec_equ_sel(macro->ctrl_vec_def[cv_idx].ctrl_vec, equ)) != ERR_OK) + goto done; + + } + + } + } + else + { + printf("Macro %s not found!\n", macro_name); + retval = ERR_NOT_FOUND; + goto done; + } + } + } + +done: + if(retval != ERR_OK) printf("Error %s on line num %ld in file %s\n", get_error_by_name(retval), line_num, asm_file_name); + if(asm_file_ptr) fclose(asm_file_ptr); + return retval; +} diff --git a/turbo9team_turbo9/urtl_asm_src/assemble.h b/turbo9team_turbo9/urtl_asm_src/assemble.h new file mode 100644 index 0000000000000000000000000000000000000000..7c6bc34a459d01f1fec272bed48b3986a98af7ed --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/assemble.h @@ -0,0 +1,66 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Assembler header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _ASSEMBLE_H +#define _ASSEMBLE_H + +#include "macro.h" +#include "mytypedef.h" + +// +// Assembler API Follows: +// + +s16 init_assembler(macro_ctx_t *macro_ctx); + +// This is the function that is called to process the asm file +// and deliver the assembled data into the function pointer +// parameter. The function pointer parameter must have the +// following signature: +// +// s16 function(ctrl_vec_t *); +// +s16 assemble(macro_ctx_t *macro_ctx, char *asm_file_name, s16 (*f)(ctrl_vec_ctx_t *, u32, ctrl_vec_t *)); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/ctrl_vec.c b/turbo9team_turbo9/urtl_asm_src/ctrl_vec.c new file mode 100644 index 0000000000000000000000000000000000000000..ff4ee0c40c559ef7ffa62c6223055c402009f068 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/ctrl_vec.c @@ -0,0 +1,1126 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Control vector generation library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include "err.h" +#include "log.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "ctrl_vec.h" +#include "statistics.h" +#include "strproc.h" + +static char * null_string = ""; +static ctrl_vec_t _ctrl_vec_list[MAX_CTRL_VEC]; // TODO: allocate to dynamic memory, use linked list, or other data structure. +extern u08 log_level; + +// --==============================================-- +// print_ctrl_vec_list_equ_sel +// +// prints equ_sel values for all ctrl_vecs in the list from given context.. +// +// this is a debug function that has no purpose elsewhere. +// +void print_ctrl_vec_list_equ_sel(ctrl_vec_ctx_t *ctx) +{ + u16 ctrl_vec_idx; + u16 equ_idx; + ctrl_vec_t *ctrl_vec; + + WRITE_LOG_NF(LOG_HIGH, "\n"); + WRITE_LOG(LOG_HIGH, "Control Vector equ_sel list dump follows:\n"); + WRITE_LOG(LOG_HIGH, "total ctrl_vec count: %d\n", ctx->total_ctrl_vec); + + for(ctrl_vec_idx = 0; ctrl_vec_idx < ctx->total_ctrl_vec; ctrl_vec_idx++) + { + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + WRITE_LOG_NF(LOG_HIGH, "list index: %d\nname: %s\nindex: %d\nwidth: %d\nmsb: %d\nlsb: %d\n", + ctrl_vec_idx, + ctx->list[ctrl_vec_idx].name, + ctx->list[ctrl_vec_idx].index, + ctx->list[ctrl_vec_idx].width, + ctx->list[ctrl_vec_idx].msb, + ctx->list[ctrl_vec_idx].lsb); + ctrl_vec = &ctx->list[ctrl_vec_idx]; + WRITE_LOG_NF(LOG_HIGH, "total equs: %d\n", ctrl_vec->total_equ); + WRITE_LOG_NF(LOG_HIGH, "macro equ sel = %s\n", ctrl_vec->equ_sel->name); + WRITE_LOG_NF(LOG_HIGH, "macro equ is coded? %s\n", ctrl_vec->equ_is_coded ? "Yes": "No"); + WRITE_LOG_NF(LOG_HIGH, "EQU used %d times\n", ctrl_vec->equ_sel->use_cnt); + WRITE_LOG_NF(LOG_HIGH, "EQU used %d times in decode\n", ctrl_vec->equ_sel->decode_use_cnt); + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + } +} + +// --==============================================-- +// print_ctrl_vec_list +// +// prints all names and associated values for all list elements. +// +// this is a debug function that has no purpose elsewhere. +// +void print_ctrl_vec_list(ctrl_vec_ctx_t *ctx) +{ + u16 ctrl_vec_idx; + u16 equ_idx; + ctrl_vec_t *ctrl_vec; + + WRITE_LOG_NF(LOG_HIGH, "\n"); + WRITE_LOG(LOG_HIGH, "control vector list dump follows:\n"); + WRITE_LOG(LOG_HIGH, "total ctrl_vec count: %d\n", ctx->total_ctrl_vec); + + for(ctrl_vec_idx = 0; ctrl_vec_idx < ctx->total_ctrl_vec; ctrl_vec_idx++) + { + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + WRITE_LOG_NF(LOG_HIGH, "list index: %d\nname: %s\n%sindex: %d\nwidth: %d\nmsb: %d\nlsb: %d\n", + ctrl_vec_idx, + ctx->list[ctrl_vec_idx].name, + ctx->list[ctrl_vec_idx].microcode_vector ? "microcode vector\n": "\n", + ctx->list[ctrl_vec_idx].index, + ctx->list[ctrl_vec_idx].width, + ctx->list[ctrl_vec_idx].msb, + ctx->list[ctrl_vec_idx].lsb); + ctrl_vec = &ctx->list[ctrl_vec_idx]; + WRITE_LOG_NF(LOG_HIGH, "macro equ sel = %s\n", ctrl_vec->equ_sel->name); + WRITE_LOG_NF(LOG_HIGH, "macro equ is coded? %s\n", ctrl_vec->equ_is_coded ? "Yes": "No"); + WRITE_LOG_NF(LOG_HIGH, "total equs: %d\n", ctrl_vec->total_equ); + for(equ_idx = 0; equ_idx < ctrl_vec->total_equ; equ_idx++) + { + WRITE_LOG_NF(LOG_HIGH, "\t%s equ $%x (equ index %d)\n", ctrl_vec->equ[equ_idx].name, ctrl_vec->equ[equ_idx].value, ctrl_vec->equ[equ_idx].index); + } + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + } +} + +// --==============================================-- +// print_label_list +// +// Prints all names and associated values for all labels in the context. +// +// This is a debug function that has no purpose elsewhere. +// +void print_label_list(ctrl_vec_ctx_t *ctx) +{ + u16 label_idx; + + for(label_idx = 0; label_idx < ctx->total_labels; label_idx++) + { + printf("=============================\n"); + printf("%d\nName: %s\nValue: %d (label index %d)\n", label_idx, ctx->labels[label_idx].name, ctx->labels[label_idx].value, ctx->labels[label_idx].index); + printf("=============================\n"); + } +} + +// --==============================================-- +// get_ctrl_vec_index_by_name +s16 get_ctrl_vec_index_by_name(ctrl_vec_ctx_t *ctx, char *ctrl_vec_name) +{ + s16 retval = ERR_NOT_FOUND; + u16 idx; + + for(idx = 0; idx < MAX_CTRL_VEC; idx++) + { + if(ctx->list[idx].name) + if(!strcmp(ctrl_vec_name, ctx->list[idx].name)) + retval = ctx->list[idx].index; + } + + return retval; +} + + +// --==============================================-- +// find_ctrl_vec_by_name +ctrl_vec_t * find_ctrl_vec_by_name(ctrl_vec_ctx_t *ctx, char *name) +{ + s32 idx; + ctrl_vec_t *ctrl_vec = NULL; + + for(idx = 0; idx < MAX_CTRL_VEC; idx++) + { + if(ctx->list[idx].name) + if(!strcmp(name, ctx->list[idx].name)) + ctrl_vec = &ctx->list[idx]; + } + + return ctrl_vec; +} + +// --==============================================-- +// find_equ_by_name +equ_t * find_equ_by_name(ctrl_vec_t *ctrl_vec, char *equ_name) +{ + s16 equ_idx; + equ_t *equ = NULL; + + if(ctrl_vec != NULL) + { + for(equ_idx = 0; equ_idx < MAX_EQU; equ_idx++) + { + if(ctrl_vec->equ[equ_idx].name) + if(!strcmp(equ_name, ctrl_vec->equ[equ_idx].name)) + equ = &ctrl_vec->equ[equ_idx]; + } + } + + return equ; +} + +// --==============================================-- +// find_equ_by_value +equ_t * find_equ_by_value(ctrl_vec_t *ctrl_vec, u16 value) +{ + s16 equ_idx; + equ_t *equ = NULL; + + if(ctrl_vec != NULL) + { + for(equ_idx = 0; equ_idx < MAX_EQU; equ_idx++) + { + if(ctrl_vec->equ[equ_idx].name) + if(value == ctrl_vec->equ[equ_idx].value) + equ = &ctrl_vec->equ[equ_idx]; + } + } + + return equ; +} + +// --==============================================-- +// find_label_by_name +equ_t * find_label_by_name(ctrl_vec_ctx_t *ctx, char *label_name) +{ + s16 label_idx; + equ_t *label = NULL; + + if(ctx != NULL) + { + for(label_idx = 0; label_idx < MAX_EQU; label_idx++) + { + if(ctx->labels[label_idx].name) + if(!strcmp(label_name, ctx->labels[label_idx].name)) + label = &ctx->labels[label_idx]; + } + } + + return label; +} + +// --==============================================-- +s16 init_ctrl_vec_ctx(ctrl_vec_ctx_t *ctx) +{ + s16 retval = ERR_OK; + u16 idx; + u16 equ_idx; + + if(!ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + ctx->list = _ctrl_vec_list; + ctx->total_ctrl_vec = 0; + ctx->total_microcode_vec = 0; + ctx->total_labels = 0; + + // This is LABELS only. + for(idx = 0; idx < MAX_EQU; idx++) + { + ctx->labels[idx].name = NULL; + ctx->labels[idx].value = 0; + } + + for(idx = 0; idx < MAX_CTRL_VEC; idx++) + { + ctx->list[idx].name = NULL; + ctx->list[idx].index = 0; + ctx->list[idx].width = 0; + ctx->list[idx].lsb = 0; + ctx->list[idx].msb = 0; + ctx->list[idx].total_equ = 0; + + for(equ_idx = 0; equ_idx < MAX_EQU; equ_idx++) + { + ctx->list[idx].equ[equ_idx].name = NULL; + ctx->list[idx].equ[equ_idx].index = 0; + ctx->list[idx].equ[equ_idx].value = 0; + ctx->list[idx].equ[equ_idx].use_cnt = 0; + ctx->list[idx].equ[equ_idx].decode_use_cnt = 0; + } + + // Upon init, always set the "equ_sel" to the default 0th EQU. + // When assembling, this entry will change as arguments are read + // and then it will be reset back to 0 after an micro_op_end. + ctx->list[idx].equ_sel = &ctx->list[idx].equ[0]; + ctx->list[idx].equ_is_coded = 0; + } + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// free_equs_from_ctrl_vec +// +// This will clear out and free all EQUs from the +// given control vector. This will probably be +// rarely used on its own. It is used by the +// free_ctrl_vec_ctx() function below. +// +void free_equs_from_ctrl_vec(ctrl_vec_t *ctrl_vec) +{ + u16 idx; + + ctrl_vec->total_equ = 0; + + for(idx = 0; idx < MAX_EQU; idx++) + { + if(ctrl_vec->equ[idx].name) free(ctrl_vec->equ[idx].name); + ctrl_vec->equ[idx].index = 0; + ctrl_vec->equ[idx].value = 0; + ctrl_vec->equ[idx].use_cnt = 0; + ctrl_vec->equ[idx].decode_use_cnt = 0; + } +} + +// --==============================================-- +// free_ctrl_vec_ctx +// +// This clears out and frees up all members of the +// control vector context, including lists of all +// control vectors and their associated EQUs. +// +void free_ctrl_vec_ctx(ctrl_vec_ctx_t *ctx) +{ + u16 idx; + u16 equ_idx; + + ctx->list = _ctrl_vec_list; + ctx->total_ctrl_vec = 0; + ctx->total_microcode_vec = 0; + + for(idx = 0; idx < MAX_CTRL_VEC; idx++) + { + if(ctx->list[idx].name) free(ctx->list[idx].name); + ctx->list[idx].index = 0; + ctx->list[idx].width = 0; + ctx->list[idx].lsb = 0; + ctx->list[idx].msb = 0; + ctx->list[idx].total_equ = 0; + + free_equs_from_ctrl_vec(&ctx->list[idx]); + } +} + +// --==============================================-- +// reset_all_ctrl_vec_equ_sel +// +// Resets all ctrl_vec equ_sel pointers back to the 0th (default) EQU element. +s16 reset_all_ctrl_vec_equ_sel(ctrl_vec_ctx_t *ctx) +{ + u16 idx; + s16 retval = ERR_OK; + + if(ctx == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + for(idx = 0; idx < ctx->total_ctrl_vec; idx++) + { + ctx->list[idx].equ_sel = &ctx->list[idx].equ[0]; + ctx->list[idx].equ_is_coded = 0; + // Do NOT reset the use_cnt or decode_use_cnt here + // as this will be called frequently, and the counts + // are used to gather statistics over all runs. + } + +done: + return retval; +} + +// --==============================================-- +// set_ctrl_vec_equ_sel +// +// Sets the given control vector's equ_sel to the given equ. +// +// NOTE: This also increments the use_cnt member of the equ, +// for use in statistical information. +// +s16 set_ctrl_vec_equ_sel(ctrl_vec_t *ctrl_vec, equ_t *equ) +{ + s16 retval = ERR_OK; + + if(!ctrl_vec || !equ) + { + retval = ERR_NULL_PTR; + goto done; + } + + ctrl_vec->equ_sel = equ; + ctrl_vec->equ_sel->use_cnt++; + ctrl_vec->equ_is_coded = 1; + +done: + return retval; +} + +// --==============================================-- +// add_ctrl_vec +// Takes: +// name +// width (optional) +// msb (optional) +// lsb (optional) +// mcv - microcode vector = 1, other vector = 0 +// +// returns error level, ERR_OK is success, ERR_DUPLICATE_ENTRY on failure. +// +s16 add_ctrl_vec(ctrl_vec_ctx_t *ctx, char *name, u08 width, u16 msb, u16 lsb, u08 mcv) +{ + s16 retval = ERR_DUPLICATE_ENTRY; + ctrl_vec_t *ctrl_vec; + + if(ctx == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + if(find_ctrl_vec_by_name(ctx, name) == NULL) + { + ctrl_vec = &ctx->list[ctx->total_ctrl_vec]; + ctrl_vec->name = malloc(strlen(name)+1); + strcpy(ctrl_vec->name, name); + ctrl_vec->index = ctx->total_ctrl_vec; + ctrl_vec->width = width; + ctrl_vec->msb = msb; + ctrl_vec->lsb = lsb; + ctrl_vec->microcode_vector = mcv; + ctx->total_ctrl_vec++; + if(mcv) ctx->total_microcode_vec++; + retval = ERR_OK; + } + +done: + return retval; +} + +// --==============================================-- +// +// get_total_ctrl_vec_count +// +// Returns the total number of control vectors in our list. +// +s32 get_total_ctrl_vec_count(ctrl_vec_ctx_t *ctx) +{ + s32 retval = ERR_NULL_PTR; + if(ctx) + { + retval = ctx->total_ctrl_vec; + } + + return retval; +} + +// --==============================================-- +// +// get_total_microcode_vec_count +// +// Returns the total number of control vectors in our list. +// +s32 get_total_microcode_vec_count(ctrl_vec_ctx_t *ctx) +{ + s32 retval = ERR_NULL_PTR; + if(ctx) + { + retval = ctx->total_microcode_vec; + } + + return retval; +} + +// --==============================================-- +// add_equ_by_ctrl_vec +// +s16 add_equ_by_ctrl_vec(ctrl_vec_t *ctrl_vec, char *equ_name, u16 equ_val) +{ + s16 retval = ERR_DUPLICATE_ENTRY; + equ_t *equ; + + // If the EQU we're tryint to add is already not part of the list... + if((equ = find_equ_by_name(ctrl_vec, equ_name)) == NULL) + { + equ = &ctrl_vec->equ[ctrl_vec->total_equ]; + equ->name = malloc(strlen(equ_name)+1); + if(equ->name) + { + strcpy(equ->name, equ_name); + equ->index = ctrl_vec->total_equ; + equ->value = equ_val; + ctrl_vec->total_equ++; + retval = ERR_OK; + } + else + retval = ERR_NULL_PTR; + } + + return retval; +} + +// --==============================================-- +// add_equ_by_ctrl_vec_name +// +// Adds a new equ to an existing ctrl vector. +s16 add_equ_by_ctrl_vec_name(ctrl_vec_ctx_t *ctx, char *ctrl_vec_name, char *equ_name, u16 equ_val) +{ + u16 ctrl_vec_idx; + s16 retval = ERR_DUPLICATE_ENTRY; + ctrl_vec_t *ctrl_vec; + equ_t *equ; + + if((ctrl_vec = find_ctrl_vec_by_name(ctx, ctrl_vec_name)) != NULL) + { + retval = add_equ_by_ctrl_vec(ctrl_vec, equ_name, equ_val); + } + + return retval; +} + +// --==============================================-- +// add_label_to_context +// +// Adds a new label to the list of labels in the context. +s16 add_label_to_context(ctrl_vec_ctx_t *ctx, char *label_name, u16 value) +{ + u16 ctrl_vec_idx; + s16 retval = ERR_DUPLICATE_ENTRY; + equ_t *equ; + + if(!ctx || !label_name) + { + retval = ERR_NULL_PTR; + goto done; + } + + WRITE_LOG(LOG_HIGH, "Searching for label: %s\n", label_name); + if((equ = find_label_by_name(ctx, label_name)) == NULL) + { + equ = &ctx->labels[ctx->total_labels]; + equ->name = malloc(strlen(label_name)+1); + if(equ->name) + { + strcpy(equ->name, label_name); + equ->index = ctx->total_labels; + equ->value = value; + ctx->total_labels++; + retval = ERR_OK; + WRITE_LOG(LOG_HIGH, "Found label %s, adding with value %d\n", equ->name, equ->value); + } + else + retval = ERR_NULL_PTR; + } + +done: + return retval; +} + +// --==============================================-- +s16 set_ctrl_vec_width_by_name(ctrl_vec_ctx_t *ctx, char *name, u08 width) +{ + s16 retval = ERR_NOT_FOUND; + ctrl_vec_t *ctrl_vec; + + if((ctrl_vec = find_ctrl_vec_by_name(ctx, name)) != NULL) + { + // TODO: find out if this is not an addr ctrl_vec, and if that is the case, + // then check if the value is < 0. If it is less than 0, return an error. + // Don't do this check if the ctrl_vec is an addr ctrl_vec! + ctrl_vec->width = width; + retval = ERR_OK; + } + + return retval; +} + +s16 set_ctrl_vec_msb_by_name(ctrl_vec_ctx_t *ctx, char *name, u16 msb) +{ + s16 retval = ERR_NOT_FOUND; + ctrl_vec_t *ctrl_vec; + + if((ctrl_vec = find_ctrl_vec_by_name(ctx, name)) != NULL) + { + ctrl_vec->msb = msb; + retval = ERR_OK; + } + + return retval; +} + +s16 set_ctrl_vec_lsb_by_name(ctrl_vec_ctx_t *ctx, char *name, u16 lsb) +{ + s16 retval = ERR_NOT_FOUND; + ctrl_vec_t *ctrl_vec; + + if((ctrl_vec = find_ctrl_vec_by_name(ctx, name)) != NULL) + { + ctrl_vec->lsb = lsb; + retval = ERR_OK; + } + + return retval; +} + +// --==============================================-- +// slice_up_the_word() +// +// set the LSB & MSB of each ctrl_vec +// return the overall bit width of +// +//s16 slice_up_the_word(ctrl_vec_t *cv_list, u16 list_len) +s16 slice_up_the_word(ctrl_vec_ctx_t *ctx) +{ + s16 i; + s16 retval = ERR_OK; + s16 overall_width = 0; + + if(ctx == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + for(i = ctx->total_ctrl_vec-1; i >= 0; i--) + { + if(!ctx->list[i].microcode_vector) continue; + + ctx->list[i].lsb = overall_width; + overall_width += ctx->list[i].width; + ctx->list[i].msb = overall_width - 1; + + WRITE_LOG(LOG_LOW, "Ctrl Vec: %s, Width: %d, MSB: %d, LSB: %d Overall width of word: %d\n", + ctx->list[i].name, ctx->list[i].width, + ctx->list[i].msb, ctx->list[i].lsb, + overall_width); + } + + retval = overall_width; + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// load_labels_to_context_from_asm_file +// +// Given a ctrl vector name that should exist in the context ctx, +// this function will open the asm_filename file, and start +// loading all of the labels encountered as EQU values into +// the given control vector. +s16 load_labels_to_context_from_asm_file(ctrl_vec_ctx_t *ctx, char *asm_filename) +{ + enum asm_states { + ASM_FIND_FIRST_ORG = 0, + ASM_FIND_LABEL = 1, + ASM_END_STATE = 2 + }; + + FILE *fp; + char line[256]; + char val[32]; + s16 retval = ERR_OK; + s16 label_name_len; + s32 value; + + if(!ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + fp = fopen(asm_filename, "r"); + if(fp == NULL) + { + puts(asm_filename); /* why didn't the file open? */ + retval = ERR_NULL_PTR; + goto done; + } + + // Read each line from the file, one by one... + while(fgets(line, 256, fp) != NULL) + { + // Skip lines beginning with a semicolon, treat like comments. + if(is_comment(line)) continue; + + strip_string(line, 0); + if(get_org_val(line, &value) == ERR_OK) + { + WRITE_LOG(LOG_HIGH, "Found ORG, setting address to %x (%d)\n", value, value); + //printf("Found ORG, setting address to %x (%d)\n", value, value); + } + else if(check_field(line, "micro_op_end", 1, 0) == ERR_OK) + { + value++; + } + else if((label_name_len = get_label(line)) > 0) + { + line[label_name_len] = '\0'; + if(retval = add_label_to_context(ctx, line, value) != ERR_OK) + { + printf("ERROR: add_label_to_context(): Could not add equ to ctrl vector (%d).\n", retval); + goto done; + } + } + + } + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// set_ctrl_vec_equs_from_ctx_labels +// +// As the name implies, this copies all of the EQUs +// from one control vector to another. +// +// NOTE: This will free up any previous name and value +// stored in the destination ctrl vector EQU names. +s16 set_ctrl_vec_equs_from_ctx_labels(ctrl_vec_ctx_t *ctx, char *dst_ctrl_vec_name) +{ + s16 retval = ERR_OK; + ctrl_vec_t *ctrl_vec_dst; + int i; + + if((ctrl_vec_dst = find_ctrl_vec_by_name(ctx, dst_ctrl_vec_name)) == NULL) + { + WRITE_LOG(LOG_HIGH, "Found ctrl_vec %s\n", dst_ctrl_vec_name); + retval = ERR_NOT_FOUND; + goto done; + } + + ctrl_vec_dst->total_equ = ctx->total_labels; + + WRITE_LOG(LOG_HIGH, "Adding labels as equs to destination ctrl_vec %s\n", dst_ctrl_vec_name); + for(i = 0; i < ctx->total_labels; i++) + { + ctrl_vec_dst->equ[i].name = ctx->labels[i].name; + + if(ctrl_vec_dst->equ[i].name && ctx->labels[i].name) + { + ctrl_vec_dst->equ[i].index = ctx->labels[i].index; + ctrl_vec_dst->equ[i].value = ctx->labels[i].value; + + WRITE_LOG(LOG_HIGH, "Found %s, added label as equ %s with value %d\n", + dst_ctrl_vec_name, ctrl_vec_dst->equ[i].name, ctrl_vec_dst->equ[i].value); + } + } + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// copy_all_equs_between_ctrl_vecs +// +// As the name implies, this copies all of the EQUs +// from one control vector to another. +// +// NOTE: This will free up any previous name and value +// stored in the destination ctrl vector EQU names. +s16 copy_all_equs_between_ctrl_vecs(ctrl_vec_ctx_t *ctx, char *src_ctrl_vec_name, char *dst_ctrl_vec_name) +{ + s16 retval = ERR_OK; + ctrl_vec_t *ctrl_vec_src; + ctrl_vec_t *ctrl_vec_dst; + int i; + + if((ctrl_vec_src = find_ctrl_vec_by_name(ctx, src_ctrl_vec_name)) == NULL) + { + retval = ERR_NOT_FOUND; + goto done; + } + + if((ctrl_vec_dst = find_ctrl_vec_by_name(ctx, dst_ctrl_vec_name)) == NULL) + { + retval = ERR_NOT_FOUND; + goto done; + } + + ctrl_vec_dst->total_equ = ctrl_vec_src->total_equ; + + for(i = 0; i < ctrl_vec_src->total_equ; i++) + { + if(ctrl_vec_dst->equ[i].name) free(ctrl_vec_dst->equ[i].name); + ctrl_vec_dst->equ[i].name = malloc(strlen(ctrl_vec_src->equ[i].name)+1); + + if(ctrl_vec_dst->equ[i].name && ctrl_vec_src->equ[i].name) + { + strcpy(ctrl_vec_dst->equ[i].name, ctrl_vec_src->equ[i].name); + ctrl_vec_dst->equ[i].index = ctrl_vec_src->equ[i].index; + ctrl_vec_dst->equ[i].value = ctrl_vec_src->equ[i].value; + } + } + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// get_equ_name_from_val +// +// Given a ctrl vec cv_list and total entries count +// find the first equate name associated with the value. +// Function returns name through name parameter, +// Return value of 0 is pass, negative failure. +s16 get_equ_name_from_val(ctrl_vec_t *cv_list, u16 cv_idx, u32 value, char **name) +{ + s16 retval = ERR_NOT_FOUND; // Assume failure until pass. + u16 j; + + static char * null_string = ""; + + *name = null_string; + + if(!cv_list) + { + printf("get_equ_name_from_val: cv_list was null\n"); + goto end; + } + + for(j = 0; j < cv_list[cv_idx].total_equ; j++) + { + if(cv_list[cv_idx].equ[j].value == value) + { + *name = cv_list[cv_idx].equ[j].name; + retval = ERR_OK; + break; + } + } + +end: + return retval; +} +// --==============================================-- + +// --==============================================-- +s16 inc_decode_use_cnt(equ_t *equ) +{ + s16 retval = ERR_OK; + + if(!equ) + { + retval = ERR_NULL_PTR; + goto done; + } + + equ->decode_use_cnt++; + +done: + return retval; +} +// --==============================================-- + +// --==============================================-- +equ_t * get_equ_by_name_from_ctrl_vec(ctrl_vec_t *ctrl_vec, char *name) +{ + equ_t *retval = NULL; + u16 idx; + + if(!ctrl_vec || !name) + { + printf("get_equ_by_name_from_ctrl_vec: ctrl_vec or name is NULL!\n"); + goto done; + } + + for(idx = 0; idx < ctrl_vec->total_equ; idx++) + { + if(!strcmp(name, ctrl_vec->equ[idx].name)) + retval = &ctrl_vec->equ[idx]; + } + +done: + return retval; +} + +// --==============================================-- +// get_ctrl_vec_value() +// Returns the control vector value given its index and the microprogram address +// +u16 get_ctrl_vec_value(ctrl_vec_t *cv_list, u16 cv_idx, u08 *mem, u16 addr) +{ + u16 mpw_len_in_bytes; + u08 mpw_offset_in_bytes; + u16 mem_pos; + s08 i; + u32 raw_data = 0; + u16 retval = 0; + u32 mask_data = 0xFFFFFFFF; + + if(mem == NULL) + { + printf("get_ctrl_vec_value: memory pointer is null.\n"); + goto end; + } + + mpw_len_in_bytes = (rnd_up((cv_list[0].msb + 1), 8))/8; // Calculate the Microprogram Word length rounded up to the nearest byte + mpw_offset_in_bytes = mpw_len_in_bytes - (cv_list[cv_idx].lsb / 8); // Calculate which byte of the mpw is the first to load. + mem_pos = (mpw_len_in_bytes * addr) + mpw_offset_in_bytes - 1; // Calculate memory position of first byte + + + // Read in 24bits + for (i = 0; i < 3; i++) + { + if (((s32)mem_pos-i)>=0) // Ensure we are not out bounds + raw_data += (u32)(mem[mem_pos-i]) <<(i*8); + } + + //Shift & Mask Data + raw_data = raw_data >>(cv_list[cv_idx].lsb % 8); + mask_data = ~(mask_data <total_ctrl_vec, line); + + switch (state) + { + case FIND_MICROPROGRAM_WORD: + if(strstr(line, "microprogram_word_begin")) state = READ_MICROPROGRAM_WORD_INIT; + break; + + case READ_MICROPROGRAM_WORD_INIT: + if(strstr(line, "microprogram_word_end")) + { + state = FIND_CTRL_VEC; + done = 1; + } + else + { + // This is where each entry is collected. + if(strstr(line, "INIT")) + { + get_field(line, field, 1, 0); + if((retval = add_ctrl_vec(ctx, field, 0, 0, 0, 1)) != ERR_OK) + { + printf("State READ_MICROPROGRAM_WORD_INIT: Could not add control vector.\n"); + goto done; + } + } + } + + get_field(line, field, 0, 0); + break; + + case FIND_CTRL_VEC: + if(strstr(line, "microprogram_addr_width")) + { + s32 addr_width; + get_field(line, field, 1, 0); + addr_width = atoi(field); + if(addr_width < 1) { + printf("microprogram_addr_width is %ld, must be > 1.", addr_width); + goto done; + } + ctx->addr_width = addr_width; + } + + if(strstr(line, "ctrl_vec_begin") || strstr(line, "ctrl_vec_addr_begin")) + { + get_field(line, curr_ctrl_vec_name, 1, 0); + get_field(line, field, 2, 0); + if((retval = set_ctrl_vec_width_by_name(ctx, curr_ctrl_vec_name, atoi(field))) != ERR_OK) + { + // This is not necessarily an error now. If we see control vectors that are not + // already in the INIT list, then we are dealing with other control vectors that + // are used to build additional LUTs that are not necessarily true control vecs. + // Note the last 0 parameter sets the microcode_vector to 0 so we know not to + // output these control vectors in microcode. This is part of the change to add + // the global use of decode muxes, not just jump tables. Need to use the field to + // set the width accordingly. + if((retval = add_ctrl_vec(ctx, curr_ctrl_vec_name, atoi(field), 0, 0, 0)) != ERR_OK) + { + printf("State READ_MICROPROGRAM_WORD_INIT: Could not add control vector.\n"); + goto done; + } + //printf("State FIND_CTRL_VEC: Could not set ctrl_vec width by name.\n"); + //goto done; + } + + if(strstr(line, "ctrl_vec_addr_begin")) + { + state = SET_CTRL_VEC_ADDR_EQU; + } + else + state = READ_CTRL_VEC_EQU; + + if(strstr(line, "ctrl_vec_end") || strstr(line, "ctrl_vec_addr_end")) + { + printf("ERROR: Found ctrl_vec_end or ctrl_vec_addr_end before ctrl_vec_begin.\n"); + retval = ERR_INVALID_STATE; + goto done; + } + } + + break; + + case SET_CTRL_VEC_ADDR_EQU: + WRITE_LOG(LOG_HIGH, "In state SET_CTRL_VEC_ADDR_EQU, Calling set_ctrl_vec_equs_from_ctx_labels()\n"); + if((retval = set_ctrl_vec_equs_from_ctx_labels(ctx, curr_ctrl_vec_name)) != ERR_OK) + { + printf("State FIND_CTRL_VEC: Could not set label equs to control vector.\n"); + goto done; + } + + if(strstr(line, "ctrl_vec_addr_end")) + { + WRITE_LOG(LOG_HIGH, "Found ctrl_vec_addr_end\n"); + state = FIND_CTRL_VEC; + } + break; + + case READ_CTRL_VEC_EQU: + if(strstr(line, "ctrl_vec_end")) + { + state = FIND_CTRL_VEC; + } + else if(strstr(line, "ctrl_vec_begin")) + { + printf("Error: Found ctrl_vec_begin when expecting ctrl_vec_end.\n"); + retval = ERR_INVALID_STATE; + goto done; + } + else + { + //get_field(line, field, 1, 0); + //if(strncmp(field, "EQU", 3) == 0) + if(strstr(line, "EQU")) + { + char name[128]; + get_field(line, name, 0, 0); + get_field(line, field, 2, 0); + if(field[0] == '$') + { + if(strlen(field) <= 1) + { + retval = ERR_INVALID_FIELD; + goto done; + } + } + if((retval = add_equ_by_ctrl_vec_name(ctx, curr_ctrl_vec_name, name, str2num(field))) != ERR_OK) + { + printf("State READ_CTRL_VEC_EQU: Could not add equ to ctrl vector\n"); + goto done; + } // if(add_equ_by_ctrl_vec_name) + } // if(strncmp) + } // else + break; + + } // switch(state) + } // while(read lines) + +done: + if(retval != ERR_OK) printf("Error %s on line num %ld in file %s (state %d)\n", get_error_by_name(retval), line_num, macro_file_name, state); + if(macro_file_ptr) fclose(macro_file_ptr); + return retval; +} + diff --git a/turbo9team_turbo9/urtl_asm_src/ctrl_vec.h b/turbo9team_turbo9/urtl_asm_src/ctrl_vec.h new file mode 100644 index 0000000000000000000000000000000000000000..47b32c0e1faa51800514012a2d5c21112f25fd62 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/ctrl_vec.h @@ -0,0 +1,195 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Control vector generator header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _CTRL_VEC_H +#define _CTRL_VEC_H + +#include "mytypedef.h" + +// EQU type +typedef struct _equ_t +{ + char *name; + u16 index; + u16 value; + + // Statistical data, not used elsewhere. + u16 use_cnt; + u16 decode_use_cnt; +} equ_t; + +// Control vector type +typedef struct _ctrl_vec_t +{ + char *name; + u16 index; + u08 width; + u16 lsb; + u16 msb; + u08 microcode_vector; + + equ_t equ[MAX_EQU]; + u16 total_equ; + + equ_t *equ_sel; + u08 equ_is_coded; + u16 equ_microcode_cnt; + +} ctrl_vec_t; + +typedef struct _ctrl_vec_ctx_t +{ + ctrl_vec_t *list; + u16 total_microcode_vec; + u16 total_ctrl_vec; + + // Special type that is stored once, used many. + equ_t labels[MAX_EQU]; + u16 total_labels; + u08 addr_width; + +} ctrl_vec_ctx_t; + +// +// Control Vector API Follows: +// + +// Initialize the list of control vectors in the given mandatory context. +// Must be called prior to using this library. +s16 init_ctrl_vec_ctx(ctrl_vec_ctx_t *ctx); + +// Free all memory allocated in the mandatory given context when using this library. +// Must be called when done using this library to avoid memory leak. +void free_ctrl_vec_ctx(ctrl_vec_ctx_t *ctx); + +// Find an EQU by name from within a control vector. +equ_t * get_equ_by_name_from_ctrl_vec(ctrl_vec_t *ctrl_vec, char *name); + +// Main state machine used to build the control vector list. +s16 build_ctrl_vec_list(ctrl_vec_ctx_t *ctx, char *macro_file_name); + +// Add a control vector with required name, and optional width, msb, lsb arguments. +// The context argument is mandatory, and it is on this context that the function operates. +s16 add_ctrl_vec(ctrl_vec_ctx_t *ctx, char *name, u08 width, u16 msb, u16 lsb, u08 mcv); + +// Set the width of a control vector, located by providing the mandatory name argument. +// The context argument is mandatory, and it is on this context that the function operates. +s16 set_ctrl_vec_width_by_name(ctrl_vec_ctx_t *ctx, char *name, u08 width); + +// Set the msb of a control vector, located by providing the mandatory name argument. +// The context argument is mandatory, and it is on this context that the function operates. +s16 set_ctrl_vec_msb_by_name(ctrl_vec_ctx_t *ctx, char *name, u16 msb); + +// Set the lsb of a control vector, located by providing the mandatory name argument. +// The context argument is mandatory, and it is on this context that the function operates. +s16 set_ctrl_vec_lsb_by_name(ctrl_vec_ctx_t *ctx, char *name, u16 lsb); + +// Find a control vector in the given context by searching for the mandatory name arguemnt. +// The context argument is mandatory, and it is on this context that the function operates. +ctrl_vec_t * find_ctrl_vec_by_name(ctrl_vec_ctx_t *ctx, char *name); + +// Return the count of all control vectors for the given mandatory context. +s32 get_total_ctrl_vec_count(ctrl_vec_ctx_t *ctx); + +// Add an equ to the control vector given by the mandatory name argument. The equ_name +// argument is mandatory, and an optional value can be set as well at this time. +// The context argument is mandatory, and it is on this context that the function operates. +s16 add_equ_by_ctrl_vec_name(ctrl_vec_ctx_t *ctx, char *ctrl_vec_name, char *equ_name, u16 equ_val); + +// Add a label to the context list that is reused for control vectors that have no EQUs. +s16 add_label_to_context(ctrl_vec_ctx_t *ctx, char *label_name, u16 value); + +// Add an equ to the control vector given by the mandatory ctrl_vec argument. The equ_name +// argument is mandatory, and an optional value can be set as well at this time. +// The context argument is mandatory, and it is on this context that the function operates. +s16 add_equ_by_ctrl_vec(ctrl_vec_t *ctrl_vec, char *equ_name, u16 equ_val); + +// Opens asm_filename file, and loads all labels as EQUs into given ctrl_vec_name found in the context ctx. +s16 load_labels_to_context_from_asm_file(ctrl_vec_ctx_t *ctx, char *asm_filename); + +s16 set_ctrl_vec_equs_from_ctx_labels(ctrl_vec_ctx_t *ctx, char *dst_ctrl_vec_name); + +// +s16 copy_all_equs_between_ctrl_vecs(ctrl_vec_ctx_t *ctx, char *src_ctrl_vec_name, char *dst_ctrl_vec_name); + +// Resets all ctrl_vec equ_sel pointers back to the 0th (default) EQU element. +s16 reset_all_ctrl_vec_equ_sel(ctrl_vec_ctx_t *ctx); + +// Set a control vector's equ_sel to a given EQU. +s16 set_ctrl_vec_equ_sel(ctrl_vec_t *ctrl_vec, equ_t *equ); + +// Find an equ by the mandatory given equ_name argument. +// The context argument is mandatory, and it is on this context that the function operates. +equ_t * find_equ_by_name(ctrl_vec_t *ctrl_vec, char *equ_name); + +// Find a label by the mandatory given label_name argument. +// The context argument is mandatory, and it is on this context that the function operates. +equ_t * find_label_by_name(ctrl_vec_ctx_t *ctx, char *label_name); + +// Run through all control vectors and assign the actual lsb and msb offset based on its location in +// the microprogram word. +s16 slice_up_the_word(ctrl_vec_ctx_t *ctx); + +// This is a convenience function that should not normally need to be used, except for debug. +// Prints out all control vectors and EQUs in list of control vectors. +void print_ctrl_vec_list(ctrl_vec_ctx_t *ctx); + +// This is a convenience function that should not normally need to be used, except for debug. +// Prints out the ctrl_vec list's equ_sel value. Useful after setting equ_sel from +// assembly calls. +void print_ctrl_vec_list_equ_sel(ctrl_vec_ctx_t *ctx); + +// This is a convenience function that should not normally need to be used, except for debug. +// Prints out all label names in the special list of names in the context. +void print_label_list(ctrl_vec_ctx_t *ctx); + +s16 inc_decode_use_cnt(equ_t *equ); + +// TODO: The following functions need to be updated to use the new context. + +s16 get_equ_name_from_val(ctrl_vec_t *cv_list, u16 cv_idx, u32 value, char **name); + +u16 get_ctrl_vec_value(ctrl_vec_t *cv_list, u16 cv_idx, u08 *mem, u16 addr); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/debug.c b/turbo9team_turbo9/urtl_asm_src/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..d637982f5da311273fed76c3b58015da03c7bee6 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/debug.c @@ -0,0 +1,114 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Debug tools library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include "ctrl_vec.h" +#include "err.h" + +s16 debug_print(ctrl_vec_ctx_t *ctx) +{ + s16 retval = ERR_MISC; + + if(debug_file_ptr) + { + // Write data to to debug file + fprintf(debug_file_ptr, "\n =====================================================> Control Vectors\n"); + for (ctrl_vec_idx = 0; ctrl_vec_idx < ctrl_vec_total; ctrl_vec_idx++) + { + fprintf(debug_file_ptr, "Control Vector Index = %d\n",ctrl_vec_idx); + fprintf(debug_file_ptr, ctrl_vec_list[ctrl_vec_idx].name); + fprintf(debug_file_ptr, "(%d bits)\n", ctrl_vec_list[ctrl_vec_idx].width); + fprintf(debug_file_ptr, "microprogram_word[%d:%d]\n", ctrl_vec_list[ctrl_vec_idx].msb, ctrl_vec_list[ctrl_vec_idx].lsb); + + for (equ_idx = 0; equ_idx < ctrl_vec_list[ctrl_vec_idx].total_equ; equ_idx++) + { + + fprintf(debug_file_ptr, " %s ", ctrl_vec_list[ctrl_vec_idx].equ[equ_idx].name); + make_str_pad(strlen(ctrl_vec_list[ctrl_vec_idx].equ[equ_idx].name), 32, '.', field); + fprintf(debug_file_ptr, "%s", field); + num2hex_str(ctrl_vec_list[ctrl_vec_idx].equ[equ_idx].value, ctrl_vec_list[ctrl_vec_idx].width, field); + fprintf(debug_file_ptr, " 0x%s\n", field); + } + fprintf(debug_file_ptr, "\n"); + } + + // Write out the loaded microprogram memory and decode it + fprintf(debug_file_ptr, "\n =====================================================> uProgram Memory\n"); + for(i = 0x43; i < 0x48; i++) + { + + fprintf(debug_file_ptr, "----> Address = %03x\n", i); + fprintf(debug_file_ptr, " ", i); + + for(j = 0; j < 7; j++) + { + fputc(num2hex(s_rec_mem[(i*7)+j] >> 4), debug_file_ptr); + fputc(num2hex(s_rec_mem[(i*7)+j] & 0x0F), debug_file_ptr); + } + fputc('\n', debug_file_ptr); + + for(j = 0; j < ctrl_vec_total; j++) + { + fprintf(debug_file_ptr, " %s ",ctrl_vec_list[j].name); + make_str_pad(strlen(ctrl_vec_list[j].name), 25, '.', field); + fprintf(debug_file_ptr, "%s ", field); + + k = get_ctrl_vec_value(ctrl_vec_list, j, s_rec_mem, i); + + get_equ_name_from_val(ctrl_vec_list, j, k, &equ_name); + fprintf(debug_file_ptr, "%s ",equ_name); + + make_str_pad(strlen(equ_name), 20, '.', field); + fprintf(debug_file_ptr, "%s ", field); + + num2hex_str(k, ctrl_vec_list[j].width, field); + fprintf(debug_file_ptr, "0x%s\n",field); + } + fprintf(debug_file_ptr, "\n"); + + } + + fclose (debug_file_ptr); + } + diff --git a/turbo9team_turbo9/urtl_asm_src/decode_table.c b/turbo9team_turbo9/urtl_asm_src/decode_table.c new file mode 100644 index 0000000000000000000000000000000000000000..544b708f8d94c89fb7caf2b1d063e22bd2bcc7e3 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/decode_table.c @@ -0,0 +1,769 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Decode table generator library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include +#include +#include +#include "ctrl_vec.h" +#include "err.h" +#include "decode_table.h" +#include "log.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "strproc.h" + +#define MAX_JM_LIST 32 +#define EQU_PADDING 12 + +// This type is used by the function that prints the tables. +// Three types exist: +// reg - the register type that takes a value. +// op - a string type to represent the operation description. +// eq - a string type to represent the equ. +enum table {reg, op, eq}; + +// --==============================================-- +s16 init_decode_table_ctx(decode_table_ctx_t **ctx, ctrl_vec_ctx_t *cv_ctx) +{ + s16 retval = ERR_OK; + + if(*ctx == NULL) + { + *ctx = malloc(sizeof(decode_table_ctx_t)); + if(!ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + // Newly allocated context has no prebyte list. + (*ctx)->tables = NULL; + (*ctx)->num_tables = 0; + (*ctx)->cv_ctx = cv_ctx; + } + else + retval = ERR_ALREADY_ALLOCATED; + +done: + return retval; +} + +// --==============================================-- +decode_table_t * find_table_by_name(decode_table_ctx_t *ctx, char *table_name) +{ + decode_table_t *table = NULL; + u16 idx; + + if(!ctx) + { + WRITE_LOG(LOG_HIGH, "Context null!\n"); + goto done; + } + + if(!table_name) + { + WRITE_LOG(LOG_HIGH, "Table name null!\n"); + goto done; + } + + for(idx = 0; idx < ctx->num_tables; idx++) + { + if(!ctx->tables[idx].name) + { + WRITE_LOG(LOG_HIGH, "Table index %d, name null!\n", idx); + goto done; + } + + if(!strcmp(ctx->tables[idx].name, table_name)) + { + table = &ctx->tables[idx]; + WRITE_LOG(LOG_HIGH, "Table index %d, found table %s!\n", idx, table_name); + goto done; + } + } + +done: + return table; +} + +// --==============================================-- +s16 find_opcode_in_decode_table(decode_table_t *table, u32 opcode) +{ + s16 retval = ERR_NOT_FOUND; + u16 idx; + + if(!table) + { + retval = ERR_NULL_PTR; + goto done; + } + + for(idx = 0; idx < table->list_len; idx++) + { + if(table->list[idx].opcode == opcode) + { + retval = idx; + } + } + +done: + return retval; +} + +// --==============================================-- +s16 swap_list_elements(decode_t *a, decode_t *b) +{ + s16 retval = ERR_OK; + decode_t c; + + if(!a || !b) + { + retval = ERR_NULL_PTR; + goto done; + } + + c.opcode = a->opcode; + c.has_comment = a->has_comment; + c.comment = a->comment; + c.equ = a->equ; + + a->opcode = b->opcode; + a->has_comment = b->has_comment; + a->comment = b->comment; + a->equ = b->equ; + + b->opcode = c.opcode; + b->has_comment = c.has_comment; + b->comment = c.comment; + b->equ = c.equ; + +done: + return retval; +} +// --==============================================-- +s16 add_opcode_to_table(decode_table_ctx_t *ctx, decode_table_t *table, u32 opcode, equ_t *equ, u08 has_comment, char *comment) +{ + s16 retval = ERR_OK; + s16 index; + s16 traversal; + + if(!ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + if(index = find_opcode_in_decode_table(table, opcode) == ERR_NOT_FOUND) + { + WRITE_LOG(LOG_HIGH, "table %s len: %d, alloc size: %d\n", table->name, table->list_len, (table->list_len+1)*sizeof(decode_t)); + table->list = realloc(table->list, (table->list_len+1)*sizeof(decode_t)); + if(table->list) + { + // Add the new element to the end of the list. + table->list[table->list_len].opcode = opcode; + table->list[table->list_len].equ = equ; + + if((retval = inc_decode_use_cnt(equ)) != ERR_OK) + { + printf("add_opcode_to_table: Error: (%d) EQU pointer is NULL!\n", retval); + goto done; + } + + if(has_comment) + { + char padding[32] = {0}; + s16 str_len; + s16 equ_name_len; + str_len = strlen(comment); + equ_name_len = strlen(equ->name); + + make_str_pad(strlen(equ->name), EQU_PADDING, ' ', padding); + + table->list[table->list_len].comment = malloc(equ_name_len*sizeof(char)+str_len*sizeof(char)+6+20); + sprintf(table->list[table->list_len].comment, "// %s%s%s", equ->name, padding, comment); + table->list[table->list_len].has_comment = has_comment; + } + else + table->list[table->list_len].has_comment = 0; + + table->list_len++; + + // Cheap sort... This can be optimized... + if(table->list_len > 1) + { + // Move the element into place. + for(traversal = table->list_len-1; traversal >= 1; traversal--) + { + // Sort by opcode. + if(table->list[traversal-1].opcode > table->list[traversal].opcode) + { + // TODO: maybe change this to swap list element instead of list element contents...? + retval = swap_list_elements(&table->list[traversal-1], &table->list[traversal]); + } + } + } + } + else + retval = ERR_NULL_PTR; + } + else + { + WRITE_LOG(LOG_HIGH, "Duplicate opcode found at table %s, list element %d.\n", table->name, index); + retval = index; + } + +done: + return retval; +} + +// --==============================================-- +s16 add_table_to_ctx(decode_table_ctx_t *ctx, char *table_name, ctrl_vec_t *ctrl_vec, char *default_val, u32 op_width) +{ + u32 idx; + s16 retval = ERR_OK; + + if(!ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + if(!ctx->cv_ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + for(idx = 0; idx < ctx->num_tables; idx++) + { + if(strcmp(table_name, ctx->tables[idx].name) == 0) + { + WRITE_LOG(LOG_HIGH, "Found duplicate table at index %d with name %s\n", idx, table_name); + goto done; + } + } + + ctx->tables = realloc(ctx->tables, (ctx->num_tables+1)*sizeof(decode_table_t)); + if(ctx->tables) + { + // Newly allocated table has no mappings yet... + ctx->tables[ctx->num_tables].name = malloc(strlen(table_name)*sizeof(char)+1); + if(ctx->tables[ctx->num_tables].name) + { + memset(ctx->tables[ctx->num_tables].name, 0, strlen(table_name)*sizeof(char)+1); + memcpy(ctx->tables[ctx->num_tables].name, table_name, strlen(table_name)*sizeof(char)); + //strcpy(ctx->tables[ctx->num_tables].name, table_name); + ctx->tables[ctx->num_tables].list_len = 0; + ctx->tables[ctx->num_tables].list = NULL; + ctx->tables[ctx->num_tables].ctrl_vec = ctrl_vec; + ctx->tables[ctx->num_tables].default_val = malloc(strlen(default_val)*sizeof(char)+1); + strcpy(ctx->tables[ctx->num_tables].default_val, default_val); + ctx->tables[ctx->num_tables].op_width = op_width; + ctx->num_tables++; + } + else + { + retval = ERR_NULL_PTR; + goto done; + } + } + else + retval = ERR_NULL_PTR; + +done: + return retval; +} + +// --==============================================-- +s16 free_decode_list(decode_t *list) +{ + s16 retval = ERR_OK; + + if(list) + { + if(list->comment) free(list->comment); + free(list); + } + +done: + return retval; +} + +// --==============================================-- +s16 free_all_tables(decode_table_ctx_t *ctx) +{ + u16 idx; + s16 retval = ERR_OK; + + if(ctx->tables) + { + for(idx = 0; idx < ctx->num_tables; idx++) + { + if(ctx->tables[idx].default_val) free(ctx->tables[idx].default_val); + if(ctx->tables[idx].name) free(ctx->tables[idx].name); + } + + if((retval = free_decode_list(ctx->tables->list)) != ERR_OK) + { + goto done; + } + free(ctx->tables); + } + +done: + return retval; +} + +// --==============================================-- +s16 free_decode_table_ctx(decode_table_ctx_t *ctx) +{ + s16 retval = ERR_OK; + + if(ctx) + { + if((retval = free_all_tables(ctx)) != ERR_OK) + { + goto done; + } + free(ctx); + ctx = NULL; + } + else + retval = ERR_NULL_PTR; + +done: + return retval; +} + + +// --==============================================-- +// Main state machine used to build the control vector list. +// +// Give it a context pointer and a macro file name. +// Returns ERR_OK on pass, other error code on failure. +s16 build_decode_table(decode_table_ctx_t *ctx, char *asm_file_name) +{ + s16 retval = ERR_OK; + FILE *decode_table_fp; + char line[255]; // TODO: Prefer this to be dynamic + char field[64]; + u32 value = 0; + u32 line_num = 0; + s16 comment_pos; + u32 count = 0; + ctrl_vec_t *ctrl_vec; + decode_table_t *table; + + if(!ctx || !asm_file_name) + { + printf("build_decode_table(ctx = %p, file name = %s)\n", ctx, asm_file_name); + retval = ERR_NULL_PTR; + goto done; + } + + decode_table_fp = fopen(asm_file_name, "r"); + if(decode_table_fp == NULL) + { + retval = ERR_FILE_IO; + goto done; + } + + while((fgets(line, 254, decode_table_fp))) + { + line_num++; + + comment_pos = strip_string(line, 0); + + printf("line %ld: %s\n", count++, line); + + if(check_field(line, "decode_init", 1, 0) == ERR_OK) + { + char *table_name; + char *ctrl_vec_name; + char *default_val; + char *width; + + if((retval = get_field_ex(line, &table_name, 2, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + retval = ERR_OK; + + if((retval = get_field_ex(line, &ctrl_vec_name, 3, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + { + retval = ERR_OK; + // The name of the control vector used to be passed into add_table_to_ctx, but + // the EQU is needed, and it is more appropriate to pull it from the ctrl_vec list. + if((ctrl_vec = find_ctrl_vec_by_name(ctx->cv_ctx, ctrl_vec_name)) == NULL) + { + retval = ERR_NOT_FOUND; + goto done; + } + } + + if((retval = get_field_ex(line, &default_val, 4, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + retval = ERR_OK; + + if((retval = get_field_ex(line, &width, 5, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + retval = ERR_OK; + + WRITE_LOG(LOG_HIGH, "Found decode_init, table: %s ctrl_vec_name: %s default_val: %s\n", table_name, ctrl_vec_name, default_val); + + if((retval = add_table_to_ctx(ctx, table_name, ctrl_vec, default_val, atoi(width))) != ERR_OK) + { + printf("ERROR: add_table_to_ctx returned %d\n", retval); + goto done; + } + + if(table_name) free(table_name); + if(ctrl_vec_name) free(ctrl_vec_name); + if(default_val) free(default_val); + } + else if(check_field(line, "decode", 1, 0) == ERR_OK) + { + char *table_name = NULL; + char *equ_name = NULL; + char *val = NULL; + s08 idx = 0; + u16 opcode = 0; + s16 temp; + equ_t *equ = NULL; + + if((retval = get_field_ex(line, &table_name, 2, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + { + table = find_table_by_name(ctx, table_name); + if(!table) + { + retval = ERR_NOT_FOUND; + WRITE_LOG(LOG_HIGH, "Table %s not found.\n", table_name); + goto done; + } + } + + if((retval = get_field_ex(line, &equ_name, 3, 0)) <= ERR_OK) + { + printf("get_field_ex failed.\n"); + goto done; + } + else + { + equ = get_equ_by_name_from_ctrl_vec(table->ctrl_vec, equ_name); + if(!equ) + { + retval = ERR_NOT_FOUND; + WRITE_LOG(LOG_HIGH, "EQU %s could not be found in ctrl vec %s\n", equ_name, ctrl_vec->name); + goto done; + } + } + + // TODO: 64 seems arbitrary, although probably excessive... + for(idx = 4; idx < 64; idx++) + { + val = NULL; + temp = get_field_ex(line, &val, idx, 0); + if(temp >= ERR_OK) + { + opcode = (str2num(val)); + + // The comment position is greater than 0. ERR_OK is 0. Real errors are less than 0. + if((temp = add_opcode_to_table(ctx, table, opcode, equ, comment_pos > ERR_OK, line+comment_pos)) == ERR_OK) + WRITE_LOG(LOG_HIGH, "idx = %d, opcode %x for table: %s, EQU: %s\n", idx, opcode, table_name, equ_name); + + if(val) free(val); + } + } + + // The get_field_ex calls will return a position or a failure, so clear the position. + if(retval >= ERR_OK) retval = ERR_OK; + + if(table_name) free(table_name); + if(equ_name) free(equ_name); + } + } // while(read lines) + +done: + if(retval != ERR_OK) printf("Error %s on line num %ld in file %s\n", get_error_by_name(retval), line_num, asm_file_name); + if(decode_table_fp) fclose(decode_table_fp); + return retval; +} + +void fprint_decode_logic(FILE *fp, decode_table_ctx_t *ctx, char *reg_name, u32 table_num, u16 addr_width, enum table type) +{ + u32 idx; + char sub_str[64] = {0}; + int digits; + + if(ctx->tables[table_num].list_len) + { + for(idx = 0; idx < ctx->tables[table_num].list_len; idx++) + { + printf("opcode %x\n", (u08)ctx->tables[table_num].list[idx].opcode); + { + // Compute zero padding for opcode width. + digits = ctx->tables[table_num].op_width / 4; + + // First, print out the verilog case along with the reg name. + fprintf(fp, " %ld'h%0*lX : %s_", ctx->tables[table_num].op_width, + digits, ctx->tables[table_num].list[idx].opcode, reg_name); + + // Now use a C case statement to fill out the rest of the verilog case statements. + switch(type) + { + case reg: + fprintf(fp, "O = %d'h%x; %s%s", + addr_width, + ctx->tables[table_num].list[idx].equ->value, + ctx->tables[table_num].list[idx].comment, + ctx->tables[table_num].list[idx].has_comment ? "" : "\n"); // comments have \n already. + break; + + case op: + sub_str_by_field(ctx->tables[table_num].list[idx].comment, ' ', sub_str, 3, 99); + fprintf(fp, "op = \"%s\";\n", sub_str); + break; + + case eq: + //sub_str_by_field(ctx->tables[table_num].list[idx].comment, ' ', sub_str, 2, 2); + fprintf(fp, "eq = \"%s\";\n", ctx->tables[table_num].list[idx].equ->name); + break; + } + } + } + } + switch(type) { + case reg: fprintf(fp, " default : %s_O = %d'h%s; // from decode_init\n", reg_name, addr_width, ctx->tables[table_num].default_val); break; + case op: fprintf(fp, " default : %s_op = \"invalid\";\n", reg_name); break; + case eq: fprintf(fp, " default : %s_eq = \"invalid\";\n", reg_name); break; + } +} + +s16 build_decode_table_file(decode_table_ctx_t *ctx, u32 table_num, char *filename, char *asm_filename) +{ + s16 retval = ERR_OK; + char table_filename[78] = {0}; + char full_table_filename[80] = {0}; + u32 idx; + u16 addr_width; + char pb[16] = {0}; + char *uppercase_str; + FILE *fp; + + if(!ctx || !filename) + { + retval = ERR_NULL_PTR; + goto done; + } + + strcpy(table_filename, filename); + sprintf(table_filename, "%s_%s", filename, ctx->tables[table_num].name); + sprintf(full_table_filename, "%s.v", table_filename); + + printf("built name: %s\n", full_table_filename); + + fp = fopen(full_table_filename, "w"); + if(!fp) + { + retval = ERR_FILE_IO; + goto done; + } + + uppercase_str = convert_to_upper_case(ctx->tables[table_num].name); + addr_width = ctx->tables[table_num].ctrl_vec->width; + + + fprintf(fp, "// [TURBO9_DECODE_HEADER_START]\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// Turbo9 Microprocessor IP\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// Website: www.turbo9.org\n"); + fprintf(fp, "// Contact: team[at]turbo9[dot]org\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// [TURBO9_DECODE_LICENSE_START]\n"); + fprintf(fp, "// BSD-1-Clause\n"); + fprintf(fp, "//\n"); + fprintf(fp, "// Copyright (c) 2020-2023\n"); + fprintf(fp, "// Kevin Phillipson\n"); + fprintf(fp, "// Michael Rywalt\n"); + fprintf(fp, "// All rights reserved.\n"); + fprintf(fp, "//\n"); + fprintf(fp, "// Redistribution and use in source and binary forms, with or without\n"); + fprintf(fp, "// modification, are permitted provided that the following conditions are met:\n"); + fprintf(fp, "//\n"); + fprintf(fp, "// 1. Redistributions of source code must retain the above copyright notice,\n"); + fprintf(fp, "// this list of conditions and the following disclaimer.\n"); + fprintf(fp, "//\n"); + fprintf(fp, "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n"); + fprintf(fp, "// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"); + fprintf(fp, "// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"); + fprintf(fp, "// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE\n"); + fprintf(fp, "// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"); + fprintf(fp, "// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"); + fprintf(fp, "// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n"); + fprintf(fp, "// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n"); + fprintf(fp, "// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n"); + fprintf(fp, "// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n"); + fprintf(fp, "// POSSIBILITY OF SUCH DAMAGE.\n"); + fprintf(fp, "// [TURBO9_DECODE_LICENSE_END]\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// Engineer: Kevin Phillipson & Michael Rywalt\n"); + fprintf(fp, "// Description:\n"); + fprintf(fp, "// Assembled from %s file\n", asm_filename); + fprintf(fp, "// built using %s ctrl_vec\n", ctx->tables[table_num].ctrl_vec->name); + fprintf(fp, "//\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// History:\n"); + fprintf(fp, "// 07.14.2023 - Kevin Phillipson\n"); + fprintf(fp, "// File header added\n"); + fprintf(fp, "//\n"); + fprintf(fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// [TURBO9_DECODE_HEADER_END]\n"); + fprintf(fp, "\n"); + fprintf(fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// MODULE\n"); + fprintf(fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "module %s", table_filename); + fprintf(fp, "(\n"); + fprintf(fp, " input [%ld:0] OPCODE_I,\n", ctx->tables[table_num].op_width-1); + fprintf(fp, " output reg [%d:0] %s_O\n", addr_width-1, uppercase_str); + fprintf(fp, ");\n"); + fprintf(fp, "\n"); + fprintf(fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "// LOGIC\n"); + fprintf(fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "\n"); + ////////////////////////////////////// + fprintf(fp, "always @* begin\n"); + fprintf(fp, " case (OPCODE_I)\n"); + + fprint_decode_logic(fp, ctx, uppercase_str, table_num, addr_width, reg); + +// fprintf(fp, " default : %s_O = %d'h%s; // from decode_init\n", uppercase_str, addr_width, ctx->tables[table_num].default_val); + + fprintf(fp, " endcase\n"); + fprintf(fp, "end\n\n"); + ////////////////////////////////////// + + fprintf(fp, "`ifdef SIM_TURBO9\n\n"); + fprintf(fp, "reg [(8*64):0] %s_op;\n\n", uppercase_str); + fprintf(fp, "always @* begin\n"); + fprintf(fp, " case (OPCODE_I)\n"); + fprint_decode_logic(fp, ctx, uppercase_str, table_num, addr_width, op); +// fprintf(fp, " default : %s_op = \"invalid\";\n", uppercase_str); + fprintf(fp, " endcase\n"); + fprintf(fp, "end\n\n"); + + fprintf(fp, "reg [(8*64):0] %s_eq;\n\n", uppercase_str); + fprintf(fp, "always @* begin\n"); + fprintf(fp, " case (OPCODE_I)\n"); + fprint_decode_logic(fp, ctx, uppercase_str, table_num, addr_width, eq); +// fprintf(fp, " default : %s_op = \"invalid\";\n", uppercase_str); + fprintf(fp, " endcase\n"); + fprintf(fp, "end\n\n"); + fprintf(fp, "`endif\n"); + + fprintf(fp, "\n"); + fprintf(fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(fp, "\n"); + fprintf(fp, "endmodule\n"); + + +done: + if(fp) fclose(fp); + if(uppercase_str) free(uppercase_str); + + return retval; +} + +// --==============================================-- +// output_decode_tables +// +s16 output_decode_tables(decode_table_ctx_t *ctx, char *base_filename, char *asm_filename) +{ + u32 idx, idx_tables, idx_list; + s16 retval = ERR_OK; + char decode_filename[256] = {0}; + + if(!ctx || !base_filename) + { + retval = ERR_NULL_PTR; + goto done; + } + + strcpy(decode_filename, base_filename); + + strcat(decode_filename, "_decode"); + + // Build a separate file for each of the prebytes. + for(idx_tables = 0; idx_tables < ctx->num_tables; idx_tables++) + { + if((retval = build_decode_table_file(ctx, idx_tables, decode_filename, asm_filename)) != ERR_OK) + goto done; + } + +done: + return retval; +} diff --git a/turbo9team_turbo9/urtl_asm_src/decode_table.h b/turbo9team_turbo9/urtl_asm_src/decode_table.h new file mode 100644 index 0000000000000000000000000000000000000000..9db1f2206f454e50c0070e750065505724a4ea25 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/decode_table.h @@ -0,0 +1,106 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Decode table library header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _JUMP_TABLE_H +#define _JUMP_TABLE_H + +#include "ctrl_vec.h" +#include "mytypedef.h" + +// One per opcode. Several opcodes per table. +typedef struct _decode_t +{ + u32 opcode; + u08 has_comment; + char *comment; + equ_t *equ; + +} decode_t; + +// Tables contain a control vector, and for a list of opcodes, +// an equ. +typedef struct _decode_table_t +{ + ctrl_vec_t *ctrl_vec; + char *default_val; + char *name; + decode_t *list; + u32 list_len; + u32 op_width; + +} decode_table_t; + +// Context carries around the tables list. +typedef struct _decode_table_ctx_t +{ + ctrl_vec_ctx_t *cv_ctx; + decode_table_t *tables; + u32 num_tables; + +} decode_table_ctx_t; + + +// +// API Follows: +// + +s16 init_decode_table_ctx(decode_table_ctx_t **ctx, ctrl_vec_ctx_t *cv_ctx); + +decode_table_t * find_table_by_name(decode_table_ctx_t *ctx, char *table_name); + +s16 add_table_to_ctx(decode_table_ctx_t *ctx, char *table_name, ctrl_vec_t *ctrl_vec, char *default_val, u32 width); + +s16 add_opcode_to_table(decode_table_ctx_t *ctx, decode_table_t *table, u32 opcode, equ_t *equ, u08 has_comment, char *comment); + +s16 free_decode_list(decode_t *list); + +s16 free_all_tables(decode_table_ctx_t *ctx); + +s16 free_decode_table_ctx(decode_table_ctx_t *ctx); + +s16 build_decode_table(decode_table_ctx_t *ctx, char *asm_file_name); + +s16 output_decode_tables(decode_table_ctx_t *ctx, char *base_filename, char *asm_filename); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/err.c b/turbo9team_turbo9/urtl_asm_src/err.c new file mode 100644 index 0000000000000000000000000000000000000000..20bb691bbd1aae9631e592f341b5e7aae11a5ec1 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/err.c @@ -0,0 +1,66 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Error handling library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include "err.h" + +const char * get_error_by_name(enum error_codes code) +{ + switch(code) + { + case ERR_ALREADY_ALLOCATED : return "ERR_ALREADY_ALLOCATED"; + case ERR_INVALID_STATE : return "ERR_INVALID_STATE"; + case ERR_INVALID_FIELD : return "ERR_INVALID_FIELD"; + case ERR_FILE_IO : return "ERR_FILE_IO"; + case ERR_DUPLICATE_ENTRY : return "ERR_DUPLICATE_ENTRY"; + case ERR_NOT_FOUND : return "ERR_NOT_FOUND"; + case ERR_MISC : return "ERR_MISC"; + case ERR_NULL_PTR : return "ERR_NULL_PTR"; + case ERR_OK : return "ERR_OK"; + default : return "UNKNOWN ERROR"; + } +} + diff --git a/turbo9team_turbo9/urtl_asm_src/err.h b/turbo9team_turbo9/urtl_asm_src/err.h new file mode 100644 index 0000000000000000000000000000000000000000..07613990bacde2e79bba816df013212f3e031fb2 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/err.h @@ -0,0 +1,66 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywatl +// Description: Error handling header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _ERR_H_ +#define _ERR_H_ + +#include "mytypedef.h" + +enum error_codes { + ERR_ALREADY_ALLOCATED = -8, + ERR_INVALID_STATE = -7, + ERR_INVALID_FIELD = -6, + ERR_FILE_IO = -5, + ERR_DUPLICATE_ENTRY = -4, + ERR_NOT_FOUND = -3, + ERR_MISC = -2, + ERR_NULL_PTR = -1, + ERR_OK = 0 +}; + +u08 log_level; + +const char * get_error_by_name(enum error_codes code); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/fileproc.c b/turbo9team_turbo9/urtl_asm_src/fileproc.c new file mode 100644 index 0000000000000000000000000000000000000000..950905bd5adf6fda949f2aa3f6e247a6f0b05c8d --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/fileproc.c @@ -0,0 +1,190 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: File processing library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include "ctrl_vec.h" +#include "err.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "strproc.h" + +// --==============================================-- +// load_s_records() +// +// Loads contents of file_name into newly allocated +// memory. This function allocates memory on heap, +// so it is up to the caller to free this block of +// memory. +// +// Function will return the memory bit-width. +// Negative value indicates error condition. +// +s32 load_s_records(char *file_name, ctrl_vec_ctx_t *ctx, u08 **memory) +{ + FILE *fp; + u08 s_rec[MAX_SREC_LEN]; + s32 ret_val = 0; + s32 bit_width; + int i = 0; + int s_rec_offset; + long file_size; + u08 *mem; + ctrl_vec_t *cv_list; + u16 list_len; + + if(!ctx) + { + printf("load_s_records: context pointer is null\n"); + ret_val = ERR_NULL_PTR; + goto end; + } + + if(!ctx->list) + { + printf("load_s_records: list pointer inside context is null\n"); + ret_val = ERR_NULL_PTR; + goto end; + } + + cv_list = ctx->list; + list_len = ctx->total_ctrl_vec; + + if(!file_name) + { + printf("load_s_records: filename parameter is null\n"); + ret_val = -1; + goto end; + } + + // Calculate the bit width here. + bit_width = rnd_up(cv_list[0].msb + 1, 8); + if(!bit_width) + { + printf("load_s_records: bit width cannot be 0.\n"); + ret_val = -1; + goto end; + } + printf("load_s_records: got a bit width of %ld\n", bit_width); + + // Function returns bit width. + ret_val = bit_width; + + fp = fopen(file_name, "r"); + if(fp) + { + if(fseek(fp, 0, SEEK_END) != 0) + { + printf("load_s_records: Cannot seek end of file.\n"); + ret_val = -1; + goto end; + } + + file_size = ftell(fp); + rewind(fp); + if(file_size > MAX_SREC_DEPTH * MAX_SREC_LEN) + { + printf("load_s_records: File contains more records than MAX_SREC_LEN.\n"); + ret_val = -1; + goto end; + } + + *memory = (u08*) malloc(MAX_SREC_DEPTH * bit_width/8); + mem = *memory; + if(!mem) + { + printf("Memory allocation failed."); + ret_val = -1; + goto end; + } + + memset(mem, 0, MAX_SREC_DEPTH * bit_width/8); + + // Read lines in until EOF + while(fscanf(fp, "%s", s_rec) != EOF) + { + // If the current line matches the S-record signature... + if(strncmp(s_rec, "S2140", 5) == 0) + { + u32 address; // address from string. + size_t s_rec_len; + u16 mpw_len_in_bytes; + u16 mpw_len_in_nibbles; + u16 mpw_srec_offset; + u16 mem_pos; + u16 srec_pos; + + // Get the address to know where in the memory block to lay out + // each row of data into the memory block. + address = ((hex2num(s_rec[4+0]) << 16) | + (hex2num(s_rec[4+1]) << 12) | + (hex2num(s_rec[4+2]) << 8) | + (hex2num(s_rec[4+3]) << 4) | + hex2num(s_rec[4+4])); + + // Find the number of string nibbles to convert to binary memory. + s_rec_len = strlen(s_rec); // total length of current s-record. + mpw_len_in_bytes = bit_width/8; // microprogram word length as byte count. + mpw_len_in_nibbles = bit_width/4; // microprogram word length as nibble count. + mpw_srec_offset = s_rec_len - mpw_len_in_nibbles - 2; // points to beginning of microprogrammed word in str, minus checksum. + + // Reading s-record string left to right, but + // storing the data big endian into memory. + for(i = 0; i < mpw_len_in_bytes; i++) + { + mem_pos = (address * mpw_len_in_bytes) + i; // Destination pointer in binary memory expressed in bytes. + srec_pos = mpw_srec_offset + (i*2); + mem[mem_pos] = (hex2num(s_rec[srec_pos]) << 4) | (hex2num(s_rec[srec_pos+1])); + } + } + } + fclose(fp); + } + +end: + return ret_val; +} + + diff --git a/turbo9team_turbo9/urtl_asm_src/fileproc.h b/turbo9team_turbo9/urtl_asm_src/fileproc.h new file mode 100644 index 0000000000000000000000000000000000000000..f701b7ced545a5449f0f88f0c3b6b99b15830491 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/fileproc.h @@ -0,0 +1,53 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: File processing header. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _FILEPROC_H_ +#define _FILEPROC_H_ + +#include "mytypedef.h" + +s32 load_s_records(char *file_name, ctrl_vec_ctx_t *ctx, u08 **memory); + + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/log.c b/turbo9team_turbo9/urtl_asm_src/log.c new file mode 100644 index 0000000000000000000000000000000000000000..529ff8cd7c5f44f587d2aa2817f3e0e07f3926e8 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/log.c @@ -0,0 +1,102 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Logging function library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include +#include +#include +#include "log.h" + +#define LOG_PATH "./urtl_debug.log" +extern int log_level; + +void clear_log(int level) +{ + FILE *fp; + + if(level > LOG_OFF && level <= LOG_DEBUG_LEVEL) + { + fp = fopen(LOG_PATH, "w"); + fclose(fp); + } +} + +void write_log(const char * caller_name, int level, int timestamp, int show_caller, char * log_entry, ...) +{ + FILE *fp; + time_t rawtime; + char log_str[256] = {0}; + va_list args; + char timestr[80]; + char marker[256]; + struct tm *tmp; + + va_start(args, log_entry); + vsprintf(log_str, log_entry, args); + va_end(args); + + if(log_level >= level) + { + fp = fopen(LOG_PATH, "a"); + if(fp) + { + rawtime = time(NULL); + tmp = localtime(&rawtime); + if(strftime(timestr, sizeof(timestr), "%a, %d %b %Y %T %z", tmp) == 0) + { + fprintf(fp, "strftime returned 0"); + } + + if(timestamp) + sprintf(marker, "[%s : %s]: ", timestr, caller_name); + else + sprintf(marker, "[%s]: ", caller_name); + + fprintf(fp, "%s%s", show_caller? marker: "", log_str); + + fclose(fp); + } + } +} + diff --git a/turbo9team_turbo9/urtl_asm_src/log.h b/turbo9team_turbo9/urtl_asm_src/log.h new file mode 100644 index 0000000000000000000000000000000000000000..2d0a181c45c2e42360920f2bdb7ce7af2423c568 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/log.h @@ -0,0 +1,65 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Logging library header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _LOG_H_ +#define _LOG_H_ + +void clear_log(); +void write_log(const char * caller_name, int level, int timestamp, int show_caller, char * log_entry, ...); + +#define LOG_DEBUG_LEVEL 2 + +// log prioritization. +// 0 is debug disabled +#define LOG_OFF 0 +#define LOG_LOW 1 +#define LOG_HIGH 2 + +#define WRITE_LOG(level, ...) write_log(__func__, level, 0, 1, __VA_ARGS__); +#define WRITE_LOG_T(level, ...) write_log(__func__, level, 1, 1, __VA_ARGS__); + +#define WRITE_LOG_NF(level, ...) write_log(__func__, level, 0, 0, __VA_ARGS__); + +#endif + diff --git a/turbo9team_turbo9/urtl_asm_src/macro.c b/turbo9team_turbo9/urtl_asm_src/macro.c new file mode 100644 index 0000000000000000000000000000000000000000..09f0bfeb4999eb999a0ca4287991970fbab48a96 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/macro.c @@ -0,0 +1,450 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Macro function library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include "err.h" +#include "log.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "ctrl_vec.h" +#include "macro.h" +#include "statistics.h" +#include "strproc.h" + +static char * null_string = ""; +static macro_t _macro_list[MAX_MACROS]; // TODO: allocate to dynamic memory, use linked list, or other data structure. + +// --==============================================-- +// print_macro_list +// +// Prints all names and associated values for all list elements. +// +// This is a debug function that has no purpose elsewhere. +// +void print_macro_list(macro_ctx_t *ctx) +{ + u16 macro_idx; + u16 ctrl_vec_idx; + macro_t *macro; + + WRITE_LOG_NF(LOG_HIGH, "\n"); + WRITE_LOG(LOG_HIGH, "High Level Macros List Dump Follows:\n"); + WRITE_LOG(LOG_HIGH, "Total macro count: %d\n", ctx->total_macros); + + for(macro_idx = 0; macro_idx < ctx->total_macros; macro_idx++) + { + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + WRITE_LOG_NF(LOG_HIGH, "List index: %d\nName: %s\n", + macro_idx, + ctx->list[macro_idx].name); + macro = &ctx->list[macro_idx]; + WRITE_LOG_NF(LOG_HIGH, "Total ctrl_vecs: %d\n", macro->total_ctrl_vec); + for(ctrl_vec_idx = 0; ctrl_vec_idx < ctx->list[macro_idx].total_ctrl_vec; ctrl_vec_idx++) + { + if(macro->ctrl_vec_def[ctrl_vec_idx].arg_num == -1) + { + WRITE_LOG_NF(LOG_HIGH, "\t%s\t%s $%x (%d -> %d)\n", macro->ctrl_vec_def[ctrl_vec_idx].ctrl_vec->name, macro->ctrl_vec_def[ctrl_vec_idx].data.equ->name, macro->ctrl_vec_def[ctrl_vec_idx].data.equ->value, macro->ctrl_vec_def[ctrl_vec_idx].ctrl_vec->index, macro->ctrl_vec_def[ctrl_vec_idx].data.equ->index); + } + else + { + WRITE_LOG_NF(LOG_HIGH, "\t%s\t$%d\n", macro->ctrl_vec_def[ctrl_vec_idx].ctrl_vec->name, macro->ctrl_vec_def[ctrl_vec_idx].data.value); + } + } + WRITE_LOG_NF(LOG_HIGH, "=============================\n"); + } + + return; +} + + +// --==============================================-- +s16 init_macro_ctx(ctrl_vec_ctx_t IN *ctrl_vec_ctx, macro_ctx_t OUT *macro_ctx) +{ + s16 retval = ERR_OK; + u16 idx, ctrl_vec_idx; + + if(!ctrl_vec_ctx || !macro_ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + macro_ctx->list = _macro_list; + macro_ctx->total_macros = 0; + macro_ctx->ctrl_vec_ctx = ctrl_vec_ctx; + + for(idx = 0; idx < MAX_MACROS; idx++) + { + if(macro_ctx->list[idx].name) free(macro_ctx->list[idx].name); + macro_ctx->list[idx].name = NULL; + macro_ctx->total_macros = 0; + + for(ctrl_vec_idx = 0; ctrl_vec_idx < MAX_CTRL_VEC; ctrl_vec_idx++) + { + macro_ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].ctrl_vec = NULL; + macro_ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].data.equ = NULL; + macro_ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].arg_num = -1; + } + } + +done: + return retval; +} +// --==============================================-- + + +// --==============================================-- +// free_ctrl_vec_defs_from_macro +// +// This will clear out and free all ctrl_vec_defs from the +// given macro. +void free_ctrl_vec_defs_from_macro(macro_t *macro) +{ + u16 idx; + + macro->total_ctrl_vec = 0; + + for(idx = 0; idx < MAX_CTRL_VEC; idx++) + { + macro->ctrl_vec_def[idx].ctrl_vec = NULL; + macro->ctrl_vec_def[idx].data.equ = NULL; + macro->ctrl_vec_def[idx].arg_num = -1; + } +} + +// --==============================================-- +void free_macro_ctx(macro_ctx_t *ctx) +{ + u16 idx; + u16 ctrl_vec_idx; + + ctx->list = _macro_list; + ctx->total_macros = 0; + + for(idx = 0; idx < MAX_MACROS; idx++) + { + if(ctx->list[idx].name) free(ctx->list[idx].name); + ctx->total_macros = 0; + ctx->ctrl_vec_ctx = NULL; // Do not free here, allow to be freed in ctrl_vec context. + + for(ctrl_vec_idx = 0; ctrl_vec_idx < MAX_CTRL_VEC; ctrl_vec_idx++) + { + ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].ctrl_vec = NULL; + ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].data.equ = NULL; + ctx->list[idx].ctrl_vec_def[ctrl_vec_idx].arg_num = -1; + } + } +} + +macro_t * find_macro_by_name(macro_ctx_t *ctx, char * name) +{ + s32 idx; + macro_t *macro = NULL; + + if(ctx == NULL || name == NULL) + goto done; + + for(idx = 0; idx < MAX_MACROS; idx++) + { + if(ctx->list[idx].name) + if(!strcmp(name, ctx->list[idx].name)) + macro = &ctx->list[idx]; + } + +done: + return macro; +} + +// --==============================================-- +// add_macro +// Takes: +// name +// +// returns error level, ERR_OK is success, ERR_DUPLICATE_ENTRY on failure. +// +s16 add_macro(macro_ctx_t *ctx, char *name) +{ + s16 retval = ERR_DUPLICATE_ENTRY; + macro_t *macro; + + if(ctx == NULL || name == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + if(find_macro_by_name(ctx, name) == NULL) + { + macro = &ctx->list[ctx->total_macros]; + macro->name = malloc(strlen(name)+1); + strcpy(macro->name, name); + ctx->total_macros++; + retval = ERR_OK; + } + +done: + return retval; +} + +// --==============================================-- +// add_ctrl_vec_def_by_macro +// +// Given the macro context (needed for the associated ctrl_vec_ctx +// that is needed to find ctrl_vecs and their equs), and a +// control vector name and equ name, find the given control +// vector and then add it to the current macro given by the +// current_macro paramter. +// +s16 add_ctrl_vec_def_by_macro(macro_ctx_t *ctx, macro_t *current_macro, char *type, char *ctrl_vec_name, char *equ_name) +{ + s16 retval = ERR_NOT_FOUND; + ctrl_vec_ctx_t *ctrl_vec_ctx; + ctrl_vec_t *ctrl_vec; + equ_t *equ; + + if(ctx == NULL || ctx->ctrl_vec_ctx == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + // Get the ctrl_vec from the list of control vectors. + if((ctrl_vec = find_ctrl_vec_by_name(ctx->ctrl_vec_ctx, ctrl_vec_name)) != NULL) + { + WRITE_LOG(LOG_HIGH, "Found control vector by name: %s, type: %s\n", ctrl_vec_name, type); + + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].ctrl_vec = ctrl_vec; + + if(!strcmp(type, "arg")) + { + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].data.value = atoi(equ_name); + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].arg_num = current_macro->total_args++; + + WRITE_LOG(LOG_HIGH, "ARG add ctrl_vec_def_by_macro: data value: %d, arg_num = %d\n", + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].data.value, + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].arg_num); + retval = ERR_OK; + } + else if((equ = find_equ_by_name(ctrl_vec, equ_name)) != NULL) + { + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].data.equ = equ; + WRITE_LOG(LOG_HIGH, "VAL add_ctrl_vec_def_by_macro: equ.name = %s, its value = %d\n", + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].data.equ->name, + current_macro->ctrl_vec_def[current_macro->total_ctrl_vec].data.equ->value); + retval = ERR_OK; + } + + current_macro->total_ctrl_vec++; + } + +done: + return retval; +} + +// --==============================================-- +// add_ctrl_vec_def_by_macro_name +// +// Given the macro context (needed for the associated ctrl_vec_ctx +// that is needed to find ctrl_vecs and their equs), and a +// control vector name and equ name, find the given control +// vector and then add it to the current macro given by the +// curr_macro string. This function will find the current macro. +// +s16 add_ctrl_vec_def_by_macro_name(macro_ctx_t *ctx, char *curr_macro, char *type, char *ctrl_vec_name, char *equ_name) +{ + s16 retval = ERR_NOT_FOUND; + ctrl_vec_ctx_t *ctrl_vec_ctx; + ctrl_vec_t *ctrl_vec; + macro_t *macro; + equ_t *equ; + + if(ctx == NULL || ctx->ctrl_vec_ctx == NULL) + { + retval = ERR_NULL_PTR; + goto done; + } + + if((macro = find_macro_by_name(ctx, curr_macro)) != NULL) + { + retval = add_ctrl_vec_def_by_macro(ctx, macro, type, ctrl_vec_name, equ_name); + } + +done: + return retval; +} + + +// --==============================================-- +// +// get_total macro count_ +// +// Returns the total number of macros in our list. +// +s32 get_total_macro_count(macro_ctx_t *ctx) +{ + s32 retval = ERR_NULL_PTR; + if(ctx) + { + retval = ctx->total_macros; + } + + return retval; +} + +// --==============================================-- +// Main state machine used to build the macro list. +// +// Give it a context pointer and a macro file name. +// Returns ERR_OK on pass, other error code on failure. +s16 build_macro_list(macro_ctx_t *ctx, char *macro_file_name) +{ + enum main_states + { + FIND_MACRO_BEGIN = 0, + READ_CTRL_VECS = 1 + }; + + char line[255]; // TODO: Prefer this to be dynamic + char *stripped_line = NULL; + char curr_macro_name[128]; + FILE *macro_file_ptr = NULL; + s16 retval = ERR_OK; + u08 state = FIND_MACRO_BEGIN; + u08 done = 0; + u32 line_num = 0; + + macro_file_ptr = fopen(macro_file_name, "r"); + if(macro_file_ptr == NULL) + { + printf("%s - ", macro_file_name); + puts(macro_file_name); /* why didn't the file open? */ + retval = ERR_FILE_IO; + goto done; + } + + while((fgets(line, 254, macro_file_ptr))) + { + line_num++; + if(is_comment(line)) continue; + + strip_string(line, 1); + + WRITE_LOG(LOG_HIGH, "state: %d \tmacro_total: %d \t%s\n", state, ctx->total_macros, line); + + switch (state) + { + case FIND_MACRO_BEGIN: + if(strstr(line, "macro_begin")) + { + get_field(line, curr_macro_name, 1, 0); + if((retval = add_macro(ctx, curr_macro_name)) != ERR_OK) + { + goto done; + } + state = READ_CTRL_VECS; + WRITE_LOG(LOG_HIGH, "Found macro_begin name %s\n", curr_macro_name); + } + else if(strstr(line, "macro_end")) + { + printf("\n\n########## ERROR: Found macro_end before macro_begin. ##########\n"); + retval = ERR_INVALID_STATE; + goto done; + } + else if(strstr(line, "decode_init")) + { + printf("Found a decode_init, ignoring\n"); + } + else if(strstr(line, "decode")) + { + printf("Found a decode, ignoring\n"); + } + break; + + case READ_CTRL_VECS: + if(strstr(line, "macro_end")) + { + state = FIND_MACRO_BEGIN; + WRITE_LOG(LOG_HIGH, "Found macro_end, going back to find macro_begin...\n"); + } + else if(strstr(line, "macro_begin")) + { + printf("\n\n########## ERROR: Found macro_begin when expecting macro_end or a macro. ##########\n"); + retval = ERR_INVALID_STATE; + goto done; + } + else if(strstr(line, "set_table")) + { + printf("Found a set_table, ignoring\n"); + } + else + { + char ctrl_vec_name[64]; + char equ_name[64]; + char type[64]; + get_field(line, ctrl_vec_name, 0, 0); + get_field(line, type, 1, 0); + get_field(line, equ_name, 2, 0); + // Add control vectors and their default value. + if((retval = add_ctrl_vec_def_by_macro_name(ctx, curr_macro_name, type, ctrl_vec_name, equ_name)) != ERR_OK) + { + printf("\n\n########## ERROR: Could not add ctrl_vec_def by macro name. ##########\n"); + goto done; + } + } + break; + + } // switch(state) + + //if(stripped_line) free(stripped_line); + } // while(read lines) + +done: + if(retval != ERR_OK) printf("Error %s on line num %ld in file %s (state %d)\n", get_error_by_name(retval), line_num, macro_file_name, state); + if(macro_file_ptr) fclose(macro_file_ptr); + return retval; +} + + diff --git a/turbo9team_turbo9/urtl_asm_src/macro.h b/turbo9team_turbo9/urtl_asm_src/macro.h new file mode 100644 index 0000000000000000000000000000000000000000..b5c03b2635283dce0f8723be33a8a65fbd3a6f08 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/macro.h @@ -0,0 +1,114 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Macro list generator header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _MACRO_H +#define _MACRO_H + +#include "ctrl_vec.h" +#include "mytypedef.h" + +// ctrl_vec definition type +typedef struct _ctrl_vec_def_t +{ + ctrl_vec_t *ctrl_vec; + + union { + equ_t *equ; + s32 value; + } data; + + s08 arg_num; + +} ctrl_vec_def_t; + +// macro type +typedef struct _macro_t +{ + char *name; + ctrl_vec_def_t ctrl_vec_def[MAX_CTRL_VEC]; + u08 total_ctrl_vec; + s08 total_args; + +} macro_t; + +typedef struct _macro_ctx_t +{ + macro_t *list; + u16 total_macros; + + // We keep this internal to the macro context so we only + // pass around one list of control vectors that are + // directly associated with this macro list. + ctrl_vec_ctx_t *ctrl_vec_ctx; + +} macro_ctx_t; + +// +// Macro API Follows: +// + +// Initialize the list of macros in the given mandatory context. +// Must be called prior to using this library. +// Note that the ctrl_vec_ctx must have already been created, as it is +// an input to this function. +s16 init_macro_ctx(ctrl_vec_ctx_t *ctrl_vec_ctx, macro_ctx_t *macro_ctx); + +// Free all control vector defs from the current macro. +void free_ctrl_vec_defs_from_macro(macro_t *macro); + +// Free all memory allocated in the mandatory given context when using this library. +// Must be called when done using this library to avoid memory leak. +void free_macro_ctx(macro_ctx_t *ctx); + +// Main state machine used to build the macro list. +s16 build_macro_list(macro_ctx_t *ctx, char *macro_file_name); + +// Finds a macro by a string given by name parameter. +macro_t * find_macro_by_name(macro_ctx_t *ctx, char * name); + +// This is a convenience function that should not normally need to be used, except for debug. +// Prints out all control vectors and EQUs in list of control vectors. +void print_macro_list(macro_ctx_t *ctx); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/mathlib.c b/turbo9team_turbo9/urtl_asm_src/mathlib.c new file mode 100644 index 0000000000000000000000000000000000000000..c39f5be6a90b5a4f4202b4ddbf8c69242147a501 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/mathlib.c @@ -0,0 +1,72 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Mathematical function library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _MATHLIB_H_ +#define _MATHLIB_H_ +#include "mytypedef.h" + +// --==============================================-- +// rnd_up() +// +// Helper function to round up to nearest mult. +u16 rnd_up(u16 num, u16 mult) +{ + u16 rem; + + if (mult == 0) + return num; + + rem = num % mult; + if (rem == 0) + return num; + + return num + mult - rem; +} +// --==============================================-- + + +// --==============================================-- + + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/mathlib.h b/turbo9team_turbo9/urtl_asm_src/mathlib.h new file mode 100644 index 0000000000000000000000000000000000000000..91b2a2b4573bcd738771528aad28955ae6fca567 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/mathlib.h @@ -0,0 +1,52 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Math library header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _MATHLIB_H_ +#define _MATHLIB_H_ + +#include "mytypedef.h" + +u16 rnd_up(u16 num, u16 mult); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/mytypedef.h b/turbo9team_turbo9/urtl_asm_src/mytypedef.h new file mode 100644 index 0000000000000000000000000000000000000000..54afc8affa424ac5bd0d86ed129b4dbc0d8aea2a --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/mytypedef.h @@ -0,0 +1,85 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt and Kevin Phillipson +// Description: My typedefs for fixed witdh signed/unsigned variables +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#ifndef MYTYPEDEF_H +#define MYTYPEDEF_H + +typedef unsigned char u08; +typedef signed char s08; +typedef unsigned short u16; +typedef signed short s16; +typedef unsigned long u32; +typedef signed long s32; + +union LONG +{ + s32 sl; + u32 ul; + s16 si[2]; + u16 ui[2]; + s08 sb[4]; + u08 ub[4]; +}; + +union WORD +{ + s16 si; + u16 ui; + s08 sb[2]; + u08 ub[2]; +}; + +#define MAX_CTRL_VEC 256 +#define MAX_PTR_VEC 256 +#define MAX_EQU 256 +#define MAX_MACROS 256 +#define MAX_SREC_LEN 64 +#define MAX_SREC_DEPTH 512 + +#define IN +#define OUT + +#endif + diff --git a/turbo9team_turbo9/urtl_asm_src/statistics.c b/turbo9team_turbo9/urtl_asm_src/statistics.c new file mode 100644 index 0000000000000000000000000000000000000000..8a39683f813edc577f8880fe5467f770e3607b9b --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/statistics.c @@ -0,0 +1,193 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Statistics library source. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include "ctrl_vec.h" +#include "err.h" +#include "mathlib.h" +#include "mytypedef.h" +#include "strproc.h" + +// --==============================================-- +// run_statistics() +// +// +//s32 run_statistics(char *file_name, ctrl_vec_t *cv_list, u16 cv_total, u08 *mem) +s32 run_statistics(char *file_name, ctrl_vec_ctx_t *ctx, u08 *mem) +{ + FILE *fp; + s32 ret_val = 0; + u16 cv_idx = 0; + u16 equ_idx = 0; + u16 value_idx = 0; + u32 value_total = 0; + u32 value_cnt = 0; + u16 i = 0; + u16 bar_graph; + u16 addr_idx = 0; + s32 tmp; + char field[128]; + char * equ_name; + ctrl_vec_t *cv_list; + u16 cv_total; + + if(!file_name) + { + printf("run_statistics(): filename parameter is null\n"); + ret_val = -1; + goto end; + } + + if(!ctx) + { + printf("run_statistics(): ctx pointer is null\n"); + ret_val = ERR_NULL_PTR; + goto end; + } + + if(!ctx->list) + { + printf("run_statistics(): list is null\n"); + ret_val = ERR_NULL_PTR; + goto end; + } + + cv_list = ctx->list; + cv_total = ctx->total_ctrl_vec; + + fp = fopen(file_name, "w"); + if(fp) + { + for (cv_idx = 0; cv_idx < cv_total; cv_idx++) + { + fprintf(fp, "+==========================================================================================================+\n"); + make_str_pad(rnd_up(strlen(cv_list[cv_idx].name),2)/2, 46, ' ', field); + fprintf(fp, "| %s %s (%2d bits)", field, cv_list[cv_idx].name, cv_list[cv_idx].width); + make_str_pad(strlen(cv_list[cv_idx].name)/2, 46, ' ', field); + fprintf(fp, " %s |\n", field); + fprintf(fp, "| microprogram_word[%2d:%2d] |\n", cv_list[cv_idx].msb, cv_list[cv_idx].lsb); + fprintf(fp, "+==========================================================================================================+\n"); + + + fprintf(fp, "Use Count:\n"); + for(equ_idx = 0; equ_idx < cv_list[cv_idx].total_equ; equ_idx++) + { + equ_name = cv_list[cv_idx].equ[equ_idx].name; + + make_str_pad((strlen(equ_name)+4+(rnd_up(cv_list[cv_idx].width,4)/4)), 20, ' ', field); + fprintf(fp, "%s", field); + + fprintf(fp, " %s",equ_name); + + num2hex_str(cv_list[cv_idx].equ[equ_idx].value, cv_list[cv_idx].width, field); + fprintf(fp, " (%s) ",field); + + bar_graph = cv_list[cv_idx].equ[equ_idx].use_cnt; + if (value_cnt > 30) + bar_graph = 60; + fprintf(fp, "|"); + for (i = 0; i < bar_graph; i++) + fprintf(fp, "#"); + + fprintf(fp, " %d", cv_list[cv_idx].equ[equ_idx].use_cnt); + + if (cv_list[cv_idx].equ_sel == &cv_list[cv_idx].equ[equ_idx]) + fprintf(fp, " (default)"); + + if (cv_list[cv_idx].equ[equ_idx].use_cnt > 30) + fprintf(fp, " (clipped)"); + + if (cv_list[cv_idx].equ[equ_idx].use_cnt) + fprintf(fp, "\n"); + else + fprintf(fp, " (equate not used!) \n"); + } + + fprintf(fp, "\nDecode Use Count:\n"); + for(equ_idx = 0; equ_idx < cv_list[cv_idx].total_equ; equ_idx++) + { + equ_name = cv_list[cv_idx].equ[equ_idx].name; + + make_str_pad((strlen(equ_name)+4+(rnd_up(cv_list[cv_idx].width,4)/4)), 20, ' ', field); + fprintf(fp, "%s", field); + + fprintf(fp, " %s",equ_name); + + num2hex_str(cv_list[cv_idx].equ[equ_idx].value, cv_list[cv_idx].width, field); + fprintf(fp, " (%s) ",field); + + bar_graph = cv_list[cv_idx].equ[equ_idx].decode_use_cnt; + if (value_cnt > 30) + bar_graph = 60; + fprintf(fp, "|"); + for (i = 0; i < bar_graph; i++) + fprintf(fp, "#"); + + fprintf(fp, " %d", cv_list[cv_idx].equ[equ_idx].decode_use_cnt); + + if (cv_list[cv_idx].equ_sel == &cv_list[cv_idx].equ[equ_idx]) + fprintf(fp, " (default)"); + + if (cv_list[cv_idx].equ[equ_idx].decode_use_cnt > 30) + fprintf(fp, " (clipped)"); + + if (cv_list[cv_idx].equ[equ_idx].decode_use_cnt) + fprintf(fp, "\n"); + else + fprintf(fp, " (equate not used!) \n"); + } + + + + fprintf(fp, "\n\n"); + } + fclose(fp); + } + +end: + return ret_val; +} +// --==============================================-- + diff --git a/turbo9team_turbo9/urtl_asm_src/statistics.h b/turbo9team_turbo9/urtl_asm_src/statistics.h new file mode 100644 index 0000000000000000000000000000000000000000..c565d351de6604a26f56e0140c9b4054f62ab088 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/statistics.h @@ -0,0 +1,55 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Statistics header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _STATISTICS_H_ +#define _STATISTICS_H_ + +#include "mytypedef.h" +#include "ctrl_vec.h" + +u16 rnd_up(u16 num, u16 mult); +s32 run_statistics(char *file_name, ctrl_vec_ctx_t *ctx, u08 *mem); + + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/strproc.c b/turbo9team_turbo9/urtl_asm_src/strproc.c new file mode 100644 index 0000000000000000000000000000000000000000..b03739b26f9652a37d0aa96af86837e266a31ca1 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/strproc.c @@ -0,0 +1,792 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: String processing library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#include +#include +#include +#include +#include "err.h" +#include "log.h" +#include "mytypedef.h" +#include "statistics.h" + +#define LF 0x0A + + +char * convert_to_upper_case(char *str) +{ + char *retval = NULL; + char *p = NULL; + u16 len = 0; + + if(!str) + { + goto done; + } + + len = strlen(str); + + if(len) + { + retval = malloc(len * sizeof(char)+1); + if(retval) + { + memset(retval, '\0', len * sizeof(char)+1); + p = retval; + + while(*str != '\0') + *p++ = toupper((unsigned char)*str++); + } + } + +done: + return retval; +} + +// --==============================================-- +// is_comment +// +// If the string passed in has a ; at the beginning of +// the line, return 1 (it is a comment). If it doesn't +// and no longer meets the qualifications as a full line +// comment, returns 0; +s16 is_comment(char *line) +{ + char *a; + s16 retval = 0; + + if(!line) + { + goto done; + } + + a = line; + while(*a != '\0' && *a != '\n') + { + if(*a == ' ' || *a == '\t') + { + a++; + continue; + } + else if(*a == ';') + { + retval = 1; + goto done; + } + else + { + goto done; + } + } + +done: + return retval; +} + +// --==============================================-- +// is_empty_line +// +// If the string passed in has no characters in it other than +// spaces, tabs, or just a single newline, it is empty. +// +s16 is_empty_line(char *line) +{ + char *a; + s16 retval = 1; // Assume empty + + if(!line) + { + goto done; + } + + a = line; + while(*a != '\0' && *a != '\n') + { + if(*a != ' ' && *a != '\t') + { + retval = 0; // It's not empty + goto done; + } + else + { + a++; + continue; + } + } + +done: + return retval; +} + +// --==============================================-- +// strspc +// +// Strip the leading spaces out of a string. +// This function is destructive and will modify the +// string passed into the function. +// +s16 strmspc(char *line) +{ + char *a, *b; + u08 find_spaces = 1; + s16 retval = ERR_OK; + + if(!line) + { + retval = ERR_NULL_PTR; + goto done; + } + + a = line; + b = line; + + while(*a != '\0' && *a != '\n') + { + if(find_spaces && (*a == ' ' || *a == '\t')) + { + a++; + } + else + { + find_spaces = 0; + *b++ = *a++; + } + } + +done: + return retval; +} + +char * find_next_nonblank_char(char *str) +{ + char *retval = NULL; + char *a; + + if(!str) + { + retval = NULL; + goto done; + } + + a = str; + while(*a != '\0' && *a != '\n' && *a != ';') + { + if(*a == '\t' || *a == ' ') + { + a++; + } + else + { + retval = a; + goto done; + } + } + +done: + return retval; +} + +// --==============================================-- +// chop the string at a given character +s16 chop_string(char *line, char chop) +{ + s16 retval = ERR_OK; + + u16 i = 0; + u16 j = 0; + + if (!line) + { + retval = ERR_NULL_PTR; + printf( "Error: null pointer passed to strip_string function\n"); + goto done; + } + + while ((line[j] != '\0') && (line[j] != LF)) // While not end of string + { + if + ( + ((line[j] >= 'A') && (line[j] <= 'Z')) || + ((line[j] >= 'a') && (line[j] <= 'z')) || + ((line[j] >= '0') && (line[j] <= '9')) || + (line[j] == ']') || + (line[j] == '[') || + (line[j] == '/') || + (line[j] == '$') || + (line[j] == '_') + ) + { + line[i] = line[j]; // Valid character. Copy back into string + i++; + } + else if(line[j] == chop) + { + line[i] = '\0'; + goto done; + } + j++; + } + + line[i] = '\0'; + +done: + return retval; +} + + +// --==============================================-- +// strip_string +// +// This function will take a string and strip out all characters that are +// not in the large if statement condition below. Repeated invalid +// characters will be consolidated into a single space character. +// +// line - the string to be operated ron. +// clip_leading_whitespace - remove leading whitespace +// retval - returns 0 if successful. Negative value is return if error +// +s16 strip_string(char *line, u08 clip_leading_whitespace) +{ + s16 retval = ERR_OK; + + u16 i = 0; + u16 j = 0; + u08 flag = clip_leading_whitespace; + + if (!line) + { + retval = ERR_NULL_PTR; + printf( "Error: null pointer passed to strip_string function\n"); + goto done; + } + + while ((line[j] != '\0') && (line[j] != LF)) // While not end of string + { + if + ( + ((line[j] >= 'A') && (line[j] <= 'Z')) || + ((line[j] >= 'a') && (line[j] <= 'z')) || + ((line[j] >= '0') && (line[j] <= '9')) || + (line[j] == '.') || + (line[j] == ']') || + (line[j] == '[') || + (line[j] == '/') || + (line[j] == '$') || + (line[j] == '_') + ) + { + line[i] = line[j]; // Valid character. Copy back into string + i++; + flag = 0; + } + else if(line[j] == ';') + { + line[i] = '\0'; + retval = j+2; // Point to beginning of comment as return val. + goto done; + } + else + { + if (flag == 0) + { + line[i] = ' '; // First invalid character. Insert a space + i++; + flag = 1; + } + } + j++; + } + + line[i] = '\0'; + +done: + return retval; +} + + +// --==============================================-- +// strip_string_s +// Performs the same operation as strip_string, but +// is not destructive to the input string. +// +// The out_str must be freed when not needed any +// longer. +s16 strip_string_s(char *in_str, char **out_str, u08 clip_leading_whitespace) +{ + s16 retval = ERR_OK; + size_t str_len; + char *new_str; + + // Get the size of the original string. + str_len = strlen(in_str); + if(str_len > 1) + { + // Allocate at least as much memory. We will be + // stripping the string, so the result will be smaller. + new_str = malloc(str_len * sizeof(char)); + if(new_str) + { + strcpy(new_str, in_str); + retval = strip_string(new_str, clip_leading_whitespace); + if(retval) + { + goto done; + } + *out_str = new_str; + } + else + { + retval = ERR_NULL_PTR; + goto done; + } + } + +done: + return retval; +} + +// --==============================================-- +// Get Field Function +// +// This function will take a string that is made up of fields seperated +// by space characters and return the desired field. +// +// line - input string with space delimiters +// field - output string +// field_num - specifies field number to return +// field_spaces - specifies how many spaces to include in field +// ret_val - the starting position of the desired field. +// returns an ERR_* type if error +// +// TODO: Needs reevaluation to use strtok() and not take in a stack variable to store fields. +// *field output should not be a char array, but just point to the tokenized field from +// strtok(). +s16 get_field(char *line, char *field, u08 field_num, u08 field_spaces) +{ + s16 ret_val = ERR_NOT_FOUND; + u16 i = 0; + u16 j = 0; + + if (!line) + { + ret_val = ERR_NULL_PTR; + printf( "Error: null pointer passed to get_field function\n"); + goto done; + } + + while ((line[i] != '\0') && (j != field_num)) // While not end of string + { + if (line[i] == ' ') j++; + i++; + } + if (j != field_num) // Field not found + { + ret_val = ERR_NOT_FOUND; + field[0] = '\0'; + goto done; + } + else + { + ret_val = i; // return position + } + + j = 0; + while ((line[i] != '\0') && !((line[i] == ' ') && (field_spaces == 0))) // While not end of string + { + field[j] = line[i]; + if (line[i] == ' ') + field_spaces--; + j++; + i++; + } + field[j] = '\0'; + + if (j == 0) // Field has zero length + { + ret_val = ERR_NOT_FOUND; + goto done; + } + +done: + return ret_val; +} + +// --==============================================-- +s16 sub_str_by_field(char *in_str, char sep_ch, char *out_str, u08 start_field, u08 end_field) +{ + s16 ret_val = ERR_NOT_FOUND; + u08 field = 0; + u16 i = 0, j = 0, spc_cnt = 0; + u08 state = 0; + u08 copy = 0; + + if(in_str == NULL) + { + ret_val = ERR_NULL_PTR; + printf("Error: null pointer passed to sub_str_by_field function.\n"); + goto done; + } + + while(in_str[i] != '\0' && field < end_field+1) + { + switch(state) + { + case 0: // look for text + { + if(in_str[i] == ' ') // Any further spaces, + copy = 0; // don't copy if we see spaces in this state. + else if(in_str[i] != ' ') + { + field++; + if(field == start_field) + copy = 1; + else if(field == end_field+1) + copy = 0; + state = 1; // state to find spaces. + } + } + break; + case 1: // look for spaces + { + if(in_str[i] == ' ') + state = 0; // If we see a space, eat it and go back to look for characters. + } + break; + } + + if(copy == 1 && in_str[i] != '\n') + out_str[j++] = in_str[i]; + + i++; + } + + out_str[j] = '\0'; + +done: + return ret_val; +} + +// --==============================================-- +u08 hex2num(char hex_digit) +{ + u08 num; + + if ((hex_digit >= 0x30) && (hex_digit <= 0x39)) // 0 to 9 + num = hex_digit - 0x30; + else if ((hex_digit >= 0x41) && (hex_digit <= 0x46)) // A to F + num = hex_digit - 0x37; + else if ((hex_digit >= 0x61) && (hex_digit <= 0x66)) // a to f + num = hex_digit - 0x57; + else + num = 0xff; + + return num; +} +// --==============================================-- +// +// --==============================================-- +u32 hex_str2num(char * hex_str) +{ + u08 i = 0; + u08 len = strlen(hex_str); + u32 num = 0; + + for (i=0; i 1) + { + if(*str == '$') + return hex_str2num(&str[1]); + else + return atoi(str); + } + } +} + +// --==============================================-- +char num2hex(u08 num) +{ + char hex_digit; + + if (num < 0x0A) + hex_digit = num + 0x30; + else + hex_digit = num + 0x37; + + return hex_digit; +} +// --==============================================-- + + +// --==============================================-- +void num2bin_str(u16 num, u08 width, char * bin_str) +{ + u08 i; + + for (i=0; i>(width-1-i)) & 0x01); + } + bin_str[width] = '\0'; +} +// --==============================================-- + + +// --==============================================-- +void num2hex_str(u16 num, u08 width, char * hex_str) +{ + u08 hex_str_len; + u08 i; + + hex_str_len = rnd_up(width, 4)/4; + + for (i=0; i>((hex_str_len-1-i)*4)) & 0x0F); + } + hex_str[hex_str_len] = '\0'; +} +// --==============================================-- + + +// --==============================================-- +void make_str_pad(u08 str_len, u08 width, char pad_char, char * pad) +{ + u08 i; + + if ( width <= str_len ) + { + pad[0] = pad_char; + pad[1] = '\0'; + } + else + { + for (i=0; i<(width-str_len); i++) + { + pad[i] = pad_char; + } + pad[(width-str_len)] = '\0'; + } +} +// --==============================================-- + + +// --==============================================-- +// is_valid +// +// returns TRUE if a valid character is input, FALSE +// if not. +u08 is_valid(char c) +{ + return (c >= 0x61 && c <= 0x7A) || (c >= 0x41 && c <= 0x5A) || (c >= 0x30 && c <= 0x39) || c == 0x5F; +} +// --==============================================-- + + +// --==============================================-- +// is_number +// +// returns TRUE if a valid character is input, FALSE +// if not. +u08 is_number(char c) +{ + return (c >= 0x30 && c <= 0x39); +} + +// --==============================================-- +// --==============================================-- +// get_label +// +// Returns a length of the label name if present, +// or if no label is present, 0 is returned. +// +s16 get_label(char *line) +{ + size_t str_len; + s16 label_len = 0; + + if(!line) + goto done; + + str_len = strlen(line); + if(str_len) + { + while(is_valid(line[label_len++])); + } + +done: + return label_len-1; +} +// --==============================================-- + +// --==============================================-- +// check_field +// +// Returns ERR_OK if the token given by tok is found on the given line +// in the given field number. If the string token is not found, then +// this function will return ERR_NOT_FOUND. +s16 check_field(char IN *line, char IN *tok, u08 field_num, u08 field_spaces) +{ + size_t line_len, tok_len; + s16 retval = ERR_NOT_FOUND; + char * field; + + if(!line || !tok) + { + retval = ERR_NULL_PTR; + goto done; + } + + line_len = strlen(line); + tok_len = strlen(tok); + + // See that the token length is less than the length of the + // whole line, and that the token is larger than 0. + if((tok_len <= line_len) && (tok_len > 0)) + { + field = malloc(line_len * sizeof(char)); + if(field) + { + get_field(line, field, field_num, field_spaces); + if(strcmp(field, tok) == 0) + { + retval = ERR_OK; + } + free(field); + } + } + else + retval = ERR_MISC; + +done: + return retval; +} + + +// --==============================================-- +// get_org +// +// Get the ORG value if ORG is found. +s16 get_org_val(char IN *line, u32 *val) +{ + size_t len; + s16 retval = ERR_NOT_FOUND; + char * field; + + if(!line || !val) + { + retval = ERR_NULL_PTR; + goto done; + } + + if(check_field(line, "ORG", 1, 0) == ERR_OK) + { + WRITE_LOG(LOG_HIGH, "Found ORG\n"); + len = strlen(line); + field = malloc(len * sizeof(char)); + if(field) + { + get_field(line, field, 2, 0); + *val = str2num(field); + retval = ERR_OK; + free(field); + } + } + +done: + return retval; +} + + +// --==============================================-- +// get_field_ex +// +// Returns ERR_OK if the token given by tok is found on the given line +// in the given field number. If the string token is not found, then +// this function will return ERR_NOT_FOUND. +s16 get_field_ex(char IN *line, char OUT **field, u08 field_num, u08 field_spaces) +{ + size_t line_len; + s16 retval = ERR_NOT_FOUND; + char * tmp; + + if(!line || !field) + { + retval = ERR_NULL_PTR; + goto done; + } + + line_len = strlen(line); + + // See that the token length is less than the length of the + // whole line, and that the token is larger than 0. + if(line_len > 0) + { + tmp = malloc(line_len * sizeof(char)); + if(tmp) + { + memset(tmp, 0, line_len * sizeof(char)); + retval = get_field(line, tmp, field_num, field_spaces); + *field = tmp; + } + } + else + retval = ERR_MISC; + +done: + return retval; +} + + diff --git a/turbo9team_turbo9/urtl_asm_src/strproc.h b/turbo9team_turbo9/urtl_asm_src/strproc.h new file mode 100644 index 0000000000000000000000000000000000000000..7da86d4b70d4c9dd5866110862ab9fe6a51b9059 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/strproc.h @@ -0,0 +1,73 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: String processing header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#ifndef _STRPROC_H_ +#define _STRPROC_H_ + +#include "mytypedef.h" + +char * convert_to_upper_case(char *str); +s16 strmspc(char *line); +s16 chop_string(char *line, char chop); +s16 strip_string(char *line, u08 clip_leading_whitespace); +s16 sub_str_by_field(char *in_str, char sep_ch, char *out_str, u08 start_field, u08 end_field); +s16 get_field(char *line, char *field, u08 field_num, u08 field_spaces); +s16 get_field_ex(char IN *line, char OUT **field, u08 field_num, u08 field_spaces); +s16 check_field(char IN *line, char IN *tok, u08 field_num, u08 field_spaces); +u32 hex_str2num(char * hex_str); +u32 str2num(char * str); +u08 hex2num(char hex_digit); +u08 is_valid(char c); +u08 is_number(char c); +s16 is_comment(char *line); +s16 is_empty_line(char *line); +void num2bin_str(u16 num, u08 width, char * bin_str); +void num2hex_str(u16 num, u08 width, char * hex_str); +char num2hex(u08 num); +void make_str_pad(u08 str_len, u08 width, char pad_char, char * pad); +s16 get_label(char *line); +s16 get_org_val(char IN *line, u32 *val); + +#endif diff --git a/turbo9team_turbo9/urtl_asm_src/urtl_asm.c b/turbo9team_turbo9/urtl_asm_src/urtl_asm.c new file mode 100644 index 0000000000000000000000000000000000000000..89a7f7c52550f398c460d231880c1331de5c2881 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/urtl_asm.c @@ -0,0 +1,252 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Kevin Phillipson and Michael Rywalt +// Description: Microcode Assembler main entry point. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include +#include +#include +#include +#include +#include +#include +#include +#include "assemble.h" +#include "ctrl_vec.h" +#include "err.h" +#include "decode_table.h" +#include "log.h" +#include "macro.h" +#include "mytypedef.h" +#include "statistics.h" +#include "strproc.h" +#include "urtl_asm.h" +#include "verilog.h" + +#define MAX_ERROR_MSG 0x1000 + + +// --==============================================-- Main +s08 main(int argc, char *argv[]) +{ + s08 retval = 0; + char * macro_file_name; + char * asm_file_name; + char base_filename[256] = {0}; + u08 *s_rec_mem = NULL; + u08 append_log = 0; + ctrl_vec_ctx_t ctrl_vec_ctx; + macro_ctx_t macro_ctx; + decode_table_ctx_t *jt_ctx = NULL; + int c; + + if ( argc != 2 ) /* argc should be 2 for correct execution */ + while ((c = getopt(argc, argv, "hld:c:a:")) != -1) + { + switch (c) + { + case 'h': + printf("usage: %s -c -a -d \n", argv[0]); + break; + case 'a': + asm_file_name = optarg; + break; + case 'c': + macro_file_name = optarg; + break; + case 'd': + log_level = (u08)atoi(optarg); + if(log_level > 2) log_level = 2; + break; + case 'l': + append_log = 1; + break; + case '?': + if(optopt == 'c') + { + fprintf(stderr, "Required file name missing (%s -c ).\n", argv[0]); + } + else if(optopt == 'd') + { + fprintf(stderr, "Required debug log level missing (%s -d ).\n", argv[0]); + } + else if(isprint (optopt)) + { + fprintf(stderr, "Unknown option `-%c'.\n", optopt); + } + else + { + fprintf(stderr, + "Unknown option character `\\x%x'.\n", + optopt); + } + errno = -1; + goto done; + default: + abort(); + } + } + + // If no options were given, exit. + if((optind == 1 && argc >= 1 )) + { + printf("usage: %s -c -a -o [-d ] (to append log, use -l)\n", argv[0]); + exit(1); + } + + + // TODO: Needs more checking. + strcpy(base_filename, asm_file_name); + + if((retval = chop_string(base_filename, '.')) != ERR_OK) + { + printf("main.c: Could not chop string at .\n"); + goto done; + } + + + + if(!append_log) clear_log(log_level); + + // Initalize data structure + init_ctrl_vec_ctx(&ctrl_vec_ctx); + init_macro_ctx(&ctrl_vec_ctx, ¯o_ctx); + init_assembler(¯o_ctx); + + // This is first-pass. Load the EQUs from labels in the asm file. + // These will be used later whenever we see a branch addr control + // vector. + if((errno = load_labels_to_context_from_asm_file(&ctrl_vec_ctx, asm_file_name)) != ERR_OK) + { + printf("Could not load or add label equs.\n"); + goto done; + } + + if((errno = build_ctrl_vec_list(&ctrl_vec_ctx, macro_file_name)) != ERR_OK) + { + printf("Could not build control vector list.\n"); + goto done; + } + + slice_up_the_word(&ctrl_vec_ctx); + + // This inits the context on the heap. + if((retval = init_decode_table_ctx(&jt_ctx, &ctrl_vec_ctx)) != ERR_OK) + { + printf("Could not initialize decode table context.\n"); + goto done; + } + + // Build the decode tables first. + if((retval = build_decode_table(jt_ctx, asm_file_name)) != ERR_OK) + { + printf("Could not build decode table. (errno=%d)\n", retval); + goto done; + } + + if((retval = output_decode_tables(jt_ctx, base_filename, asm_file_name)) != ERR_OK) + { + printf("Could not output decode tables.\n"); + goto done; + } + + // No more need for decode table context, free it all up. + // This frees everything within the top level struct too. + if((retval = free_decode_table_ctx(jt_ctx)) != ERR_OK) + { + printf("Could not free decode table context.\n"); + goto done; + } + + if((errno = build_macro_list(¯o_ctx, macro_file_name)) != ERR_OK) + { + printf("Could not build macro list.\n"); + goto done; + } + +// print_ctrl_vec_list(&ctrl_vec_ctx); +// print_macro_list(¯o_ctx); + + // Initialize dumper + if((errno = init_verilog_dump(¯o_ctx, base_filename, asm_file_name)) != ERR_OK) + { + printf("Could not initialize dumper.\n"); + goto done; + } + + if((errno = dump_verilog_header(&ctrl_vec_ctx)) != ERR_OK) + { + printf("Could not dump verilog header.\n"); + goto done; + } + + // Assemble. Pass in verilog dump function for individual ctrl_vec and EQUs. + if((errno = assemble(¯o_ctx, asm_file_name, dump_verilog_ctrl_vec)) != ERR_OK) + { + printf("Could not assemble!\n"); + goto done; + } + + if((errno = dump_verilog_footer(&ctrl_vec_ctx)) != ERR_OK) + { + printf("Could not dump verilog footer.\n"); + goto done; + } + + run_statistics("urtl_statistics.log", &ctrl_vec_ctx, s_rec_mem); + + //print_ctrl_vec_list(&ctrl_vec_ctx); + print_ctrl_vec_list_equ_sel(&ctrl_vec_ctx); + +done: + + if(s_rec_mem) free(s_rec_mem); + free_ctrl_vec_ctx(&ctrl_vec_ctx); + free_macro_ctx(¯o_ctx); + uninit_verilog_dump(); + + return errno; +} +// --==============================================-- + + diff --git a/turbo9team_turbo9/urtl_asm_src/urtl_asm.h b/turbo9team_turbo9/urtl_asm_src/urtl_asm.h new file mode 100644 index 0000000000000000000000000000000000000000..514ffc3be383899b0c057802971cae8ec0c7f098 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/urtl_asm.h @@ -0,0 +1,53 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Micro RTL Header File. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _URTL_H +#define _URTL_H + +#define LF 0x0A + +// States + + +#endif // URTL diff --git a/turbo9team_turbo9/urtl_asm_src/verilog.c b/turbo9team_turbo9/urtl_asm_src/verilog.c new file mode 100644 index 0000000000000000000000000000000000000000..86510ef4d4ce5f3e55de3206c4c833ada5de4795 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/verilog.c @@ -0,0 +1,346 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Verilog generator library. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] + +#include +#include +#include +#include +#include +#include "err.h" +#include "libgen.h" +#include "log.h" +#include "mytypedef.h" +#include "ctrl_vec.h" +#include "macro.h" +#include "strproc.h" + +static macro_ctx_t *_macro_ctx; +static FILE *_verilog_fp; +static char _vlog_file_name[256]; +static char _asm_file_name[256]; + +s16 init_verilog_dump(macro_ctx_t *ctx, char *base_filename, char *asm_filename) +{ + s16 retval = ERR_OK; + + if(!ctx || !base_filename) + { + retval = ERR_NULL_PTR; + goto done; + } + + strcpy(_vlog_file_name, base_filename); + + strcat(_vlog_file_name, "_microcode.v"); + + strcpy(_asm_file_name, asm_filename); + + _macro_ctx = ctx; + + _verilog_fp = fopen(_vlog_file_name, "w"); + if(_verilog_fp == NULL) + { + printf("%s - ", _vlog_file_name); + perror(_vlog_file_name); + retval = ERR_FILE_IO; + goto done; + } + +done: + return retval; +} + + +s16 dump_verilog_header() +{ + u16 idx; + s16 retval = ERR_OK; + ctrl_vec_t *ctrl_vec; + char *ctrl_vec_name; + char *equ_name; + char *module_name; + + if(! _verilog_fp || !_macro_ctx) + { + retval = ERR_NULL_PTR; + goto done; + } + + + + fprintf(_verilog_fp, "// [TURBO9_MICROCODE_HEADER_START]\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// Turbo9 Microprocessor IP\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// Website: www.turbo9.org\n"); + fprintf(_verilog_fp, "// Contact: team[at]turbo9[dot]org\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// [TURBO9_MICROCODE_LICENSE_START]\n"); + fprintf(_verilog_fp, "// BSD-1-Clause\n"); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "// Copyright (c) 2020-2023\n"); + fprintf(_verilog_fp, "// Kevin Phillipson\n"); + fprintf(_verilog_fp, "// Michael Rywalt\n"); + fprintf(_verilog_fp, "// All rights reserved.\n"); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "// Redistribution and use in source and binary forms, with or without\n"); + fprintf(_verilog_fp, "// modification, are permitted provided that the following conditions are met:\n"); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "// 1. Redistributions of source code must retain the above copyright notice,\n"); + fprintf(_verilog_fp, "// this list of conditions and the following disclaimer.\n"); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n"); + fprintf(_verilog_fp, "// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"); + fprintf(_verilog_fp, "// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"); + fprintf(_verilog_fp, "// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE\n"); + fprintf(_verilog_fp, "// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"); + fprintf(_verilog_fp, "// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"); + fprintf(_verilog_fp, "// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n"); + fprintf(_verilog_fp, "// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n"); + fprintf(_verilog_fp, "// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n"); + fprintf(_verilog_fp, "// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n"); + fprintf(_verilog_fp, "// POSSIBILITY OF SUCH DAMAGE.\n"); + fprintf(_verilog_fp, "// [TURBO9_MICROCODE_LICENSE_END]\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// Engineer: Kevin Phillipson & Michael Rywalt\n"); + fprintf(_verilog_fp, "// Description:\n"); + fprintf(_verilog_fp, "// Assembled from %s file\n\n", _asm_file_name); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// History:\n"); + fprintf(_verilog_fp, "// 07.14.2023 - Kevin Phillipson\n"); + fprintf(_verilog_fp, "// File header added\n"); + fprintf(_verilog_fp, "//\n"); + fprintf(_verilog_fp, "//////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// [TURBO9_MICROCODE_HEADER_END]\n"); + fprintf(_verilog_fp, "\n"); + fprintf(_verilog_fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// MODULE\n"); + fprintf(_verilog_fp, "/////////////////////////////////////////////////////////////////////////////\n"); + module_name = basename(_vlog_file_name); + module_name = strtok(module_name,"."); + fprintf(_verilog_fp, "module %s\n", module_name); + fprintf(_verilog_fp, "(\n"); + fprintf(_verilog_fp, " // Inputs:\n"); + fprintf(_verilog_fp, " input [%d:0] MICROCODE_ADR_I,\n\n", _macro_ctx->ctrl_vec_ctx->addr_width-1); + fprintf(_verilog_fp, " // Control Vectors\n"); + + for(idx = 0; idx < _macro_ctx->ctrl_vec_ctx->total_ctrl_vec; idx++) + { + ctrl_vec = &_macro_ctx->ctrl_vec_ctx->list[idx]; + if(!ctrl_vec->microcode_vector) continue; + ctrl_vec_name = convert_to_upper_case(ctrl_vec->name); + if(ctrl_vec_name) + { + fprintf(_verilog_fp, " output reg [%d:0] %s_O%c\n", ctrl_vec->msb - ctrl_vec->lsb, ctrl_vec_name, idx < _macro_ctx->ctrl_vec_ctx->total_microcode_vec-1? ',': ' '); + memset(ctrl_vec_name, '\0', strlen(ctrl_vec_name)); + free(ctrl_vec_name); + ctrl_vec_name = NULL; + } + + } + + fprintf(_verilog_fp, ");\n\n\n"); + fprintf(_verilog_fp, "/////////////////////////////////////////////////////////////////////////////\n"); + fprintf(_verilog_fp, "// MICROCODE\n"); + fprintf(_verilog_fp, "/////////////////////////////////////////////////////////////////////////////\n\n"); + fprintf(_verilog_fp, "always @* begin\n"); + fprintf(_verilog_fp, " //\n"); + fprintf(_verilog_fp, " // Control Logic Defaults\n"); + + for(idx = 0; idx < _macro_ctx->ctrl_vec_ctx->total_ctrl_vec; idx++) + { + ctrl_vec = &_macro_ctx->ctrl_vec_ctx->list[idx]; + if(!ctrl_vec->microcode_vector) continue; + equ_name = convert_to_upper_case(ctrl_vec->equ[0].name); + ctrl_vec_name = convert_to_upper_case(ctrl_vec->name); + if(equ_name && ctrl_vec_name) + { + fprintf(_verilog_fp, " %s_O = %d'h%x; // %s\n", ctrl_vec_name, ctrl_vec->width, ctrl_vec->equ[0].value, equ_name); + memset(equ_name, '\0', strlen(equ_name)); + memset(ctrl_vec_name, '\0', strlen(ctrl_vec_name)); + free(equ_name); + free(ctrl_vec_name); + equ_name = NULL; + ctrl_vec_name = NULL; + } + } + + fprintf(_verilog_fp, " //\n"); + fprintf(_verilog_fp, " // Decode Microcode Address\n"); + fprintf(_verilog_fp, " case (MICROCODE_ADR_I)\n"); + fprintf(_verilog_fp, "\n"); + +done: + return retval; +} + +s16 dump_comment(u32 line_number, char *comment, ...) +{ + va_list args; + char str[256] = {0}; + s16 retval = ERR_OK; + + va_start(args, comment); + vsprintf(str, comment, args); + va_end(args); + + if(!_verilog_fp) + { + retval = ERR_NULL_PTR; + goto done; + } + + fprintf(_verilog_fp, " // %04ld: %s", line_number, str); + +done: + return retval; +} + +s16 dump_verilog_ctrl_vec(ctrl_vec_ctx_t *ctx, u32 address, ctrl_vec_t *ctrl_vec) +{ + char * ctrl_vec_name; + char * equ_name; + s16 retval = ERR_OK; + static u32 addr = 0xFFFFFFFF; + + if(!ctrl_vec || !_verilog_fp) + { + retval = ERR_NULL_PTR; + goto done; + } + + equ_name = convert_to_upper_case(ctrl_vec->equ_sel->name); + ctrl_vec_name = convert_to_upper_case(ctrl_vec->name); + + if(addr != address) + { + fprintf(_verilog_fp, " %d'h%03lx: begin\n", ctx->addr_width, address); + addr = address; + } + + fprintf(_verilog_fp, " %s_O = %d'h%x; // %s\n", ctrl_vec_name, ctrl_vec->width, ctrl_vec->equ_sel->value, equ_name); + memset(equ_name, '\0', strlen(equ_name)); + memset(ctrl_vec_name, '\0', strlen(ctrl_vec_name)); + free(equ_name); + free(ctrl_vec_name); + equ_name = NULL; + ctrl_vec_name = NULL; + +done: + return retval; +} + +s16 dump_verilog_end_case() +{ + s16 retval = ERR_OK; + + if(!_verilog_fp) + { + retval = ERR_NULL_PTR; + goto done; + } + + fprintf(_verilog_fp, " end\n\n\n"); + +done: + return retval; +} + +s16 dump_verilog_footer() +{ + u16 idx; + ctrl_vec_t *ctrl_vec; + char * ctrl_vec_name; + char * equ_name; + s16 retval = ERR_OK; + + if(!_verilog_fp) + { + retval = ERR_NULL_PTR; + goto done; + } + + fprintf(_verilog_fp, " default: begin\n"); + fprintf(_verilog_fp, " //\n"); + fprintf(_verilog_fp, " // Control Logic Defaults\n"); + + for(idx = 0; idx < _macro_ctx->ctrl_vec_ctx->total_ctrl_vec; idx++) + { + ctrl_vec = &_macro_ctx->ctrl_vec_ctx->list[idx]; + if(!ctrl_vec->microcode_vector) continue; + equ_name = convert_to_upper_case(ctrl_vec->equ[0].name); + ctrl_vec_name = convert_to_upper_case(ctrl_vec->name); + if(equ_name && ctrl_vec_name) + { + fprintf(_verilog_fp, " %s_O = %d'h%x; // %s\n", ctrl_vec_name, ctrl_vec->width, ctrl_vec->equ[0].value, equ_name); + memset(equ_name, '\0', strlen(equ_name)); + memset(ctrl_vec_name, '\0', strlen(ctrl_vec_name)); + free(equ_name); + free(ctrl_vec_name); + equ_name = NULL; + ctrl_vec_name = NULL; + } + } + + fprintf(_verilog_fp, " end\n"); + fprintf(_verilog_fp, " endcase\n"); + fprintf(_verilog_fp, "end\n\n"); + fprintf(_verilog_fp, "/////////////////////////////////////////////////////////////////////////////\n\n"); + fprintf(_verilog_fp, "endmodule\n"); + + +done: + return retval; +} + + +s16 uninit_verilog_dump() +{ + if(_verilog_fp) + { + fclose(_verilog_fp); + } +} diff --git a/turbo9team_turbo9/urtl_asm_src/verilog.h b/turbo9team_turbo9/urtl_asm_src/verilog.h new file mode 100644 index 0000000000000000000000000000000000000000..eed69d011efe3e4659ab06047c210ba3bda53da5 --- /dev/null +++ b/turbo9team_turbo9/urtl_asm_src/verilog.h @@ -0,0 +1,78 @@ +// [TURBO9_HEADER_START] +////////////////////////////////////////////////////////////////////////////// +// Turbo9 Microprocessor IP +////////////////////////////////////////////////////////////////////////////// +// Website: www.turbo9.org +// Contact: team[at]turbo9[dot]org +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_LICENSE_START] +// BSD-1-Clause +// +// Copyright (c) 2020-2023 +// Kevin Phillipson +// Michael Rywalt +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// [TURBO9_LICENSE_END] +////////////////////////////////////////////////////////////////////////////// +// Engineer: Michael Rywalt +// Description: Debug dump header file. +// +////////////////////////////////////////////////////////////////////////////// +// History: +// 07.14.2023 - Kevin Phillipson +// File header added +// +////////////////////////////////////////////////////////////////////////////// +// [TURBO9_HEADER_END] +#ifndef _VERILOG_H_ +#define _VERILOG_H_ + +#include "mytypedef.h" +#include "ctrl_vec.h" + +// Called to initialize the verilog dumping. This also opens the +// output verilog file for writing. NOTE: This will overwrite any +// existing verilog file by the same name. Call +s16 init_verilog_dump(macro_ctx_t *ctx, char *base_filename, char *asm_filename); + +// Call this to print the header portion of the file up to, and +// including the start of the case statements. This will dump +// the control vector defaults just before the case switch. +s16 dump_verilog_header(ctrl_vec_ctx_t *ctx); + +// This will dump a string as a comment into the file. +s16 dump_comment(u32 line_number, char *comment, ...); + +// When building the case statements, call this with each new +// control vector that changes. +s16 dump_verilog_ctrl_vec(ctrl_vec_ctx_t *ctx, u32 address, ctrl_vec_t *ctrl_vec); + +s16 dump_verilog_end_case(); + +// Once the control vectors have been added to the case switch, +// call this function. It will populate the default case and +// close out the dump. +s16 dump_verilog_footer(ctrl_vec_ctx_t *ctx); + +// Close the file handle and cleanup. +s16 uninit_verilog_dump(); + +#endif diff --git a/zeldin_iceGDROM/README.md b/zeldin_iceGDROM/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c4b24b8fd56229dcca5d3b307b7277c210ff4fd --- /dev/null +++ b/zeldin_iceGDROM/README.md @@ -0,0 +1,93 @@ +iceGDROM +======== + +This is an implementation of IDE and the "Sega Packet Interface" +as used by the Dreamcast GD-ROM drive, using an iCE40 FPGA. + +In addition to the IDE interface itself, and the accompanying CD-DA +interface, the FPGA bitstream implements an RV32EMC-compatible CPU and +an SD Card interface. Software running on the CPU responds to +disc access commands from the Dreamcast by fetching data from disc +images on an SD Card. + +For more detailed information, please see [the webpage][1]. + +This is free software (and hardware) licensed under the GNU +General Public License version 3. + + +Hardware +-------- + +The hardware is based on the Lattice iCE40-HX8K Breakout Board. +In order to connect this board to the Dreamcast motherboard, a +custom "riser board" with the appropriate connectors and some +additional components is used. The design files for this can be +found in the `pcb/riser` directory. The bill of materials can be +found in the file `pcb/riser/bom.txt`. The pin headers with a `J` +designation should be soldered to the Breakout Board (pins facing downwards). + +The components CN4, R8, D1, and JP2 through JP4 are optional. They +are a passthrough for a slave hard drive, and not used by the GD-ROM +emulator. + +For the hardware to be complete, the following additional things are +needed: + +* A USB-mini cable to connect CN6 to the Breakout Board. This is how + the Breakout Board is powered when not attached to a host computer. +* An SD Card module, to connect to CN5. +* Rubber feet or similar to support the weight of the board in the + corners not resting on CN1. + + +Required tools +-------------- + +To build the FPGA bitstream, the following tools are needed: + +* Yosys 0.6 +* arachne-pnr +* icestorm + +To build the RISC-V software, the following tools are needed: + +* riscv32-unknown-elf gcc 10.2.0 +* riscv32-unknown-elf binutils 2.34.0 + + +Building +-------- + +Building is done by running GNU make. Running make at the top level +will build everything, running it in a subdir will build that part. +Note that building in fpga requires the rv32 stuff to be built first. + +The file `rv32/source/config.h` can be modified to adapt to the polarity +of the CD signal on the chosen SD Card module, or to enable debug traces +on the serial port of the FTDI chip. + +In order to flash the FPGA bitstream to the breakout board, run +`make flash`. + + +Making image files +------------------ + +Building the project will also create a host tool in `tools/obj/makegdimg` +which can create image files from either `.gdi` files (for GD-ROM images) +or from `.nrg` or `.cdi` files (for MIL-CD and audio CD images). The +image files should be named `DISC0000.GI0`, `DISC0001.GI0` etc on the +SD Card. To switch between images, extract and reinsert the SD Card. + + +Acknowledgements +---------------- + +* RISC-V softcore "VexRiscv" was developed by Charles Papon +* GD-ROM connector pinout was provided by OzOnE +* SD Card and FAT code based on sdfatlib by Bill Greiman +* DiscJuggler reader code based on CDIrip by DeXT/Lawrence Williams + + +[1]: http://mc.pp.se/dc/gdromemu.html diff --git a/zeldin_iceGDROM/fpga/source/avr/avr109.v b/zeldin_iceGDROM/fpga/source/avr/avr109.v new file mode 100644 index 0000000000000000000000000000000000000000..f01022bbc6c65cdc2505a46e2763a532d64dce1a --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/avr/avr109.v @@ -0,0 +1,339 @@ +// To use: + +// avrdude -c butterfly_mk -p ucr2 -b -P -U flash:w: + + +module avr109 ( + input rst, + input clk, + input rxd, + output txd, + output intercept_mode, + output prog_mode, + output[15:0] prog_addr, + output[15:0] prog_data, + input[15:0] prog_data_in, + output prog_low, + output prog_high, + output[7:0] debug + ); + parameter CLK_FREQUENCY = 1000000; + parameter BAUD_RATE = 19200; + + parameter VERSION_HIGH = "1"; + parameter VERSION_LOW = "0"; + + reg tx_avail_d, tx_avail_q; + reg [7:0] tx_data_d, tx_data_q; + reg [4:0] state_d, state_q; + reg [7:0] cnt_d, cnt_q; + reg [16:0] addr_d, addr_q; + reg prog_strobe; + reg prog_mode_d, prog_mode_q; + + wire tx_ready; + wire rx_avail; + wire [7:0] rx_data; + wire rx_enabled; + wire send_ok; + + assign intercept_mode = (state_q >= STATE_IDLE); + assign prog_addr = addr_q[16:1]; + assign prog_data = {rx_data,rx_data}; + assign prog_mode = prog_mode_q; + assign prog_low = prog_strobe & ~addr_q[0]; + assign prog_high = prog_strobe & addr_q[0]; + assign send_ok = tx_ready & ~tx_avail_q; + + assign debug = {intercept_mode, rxd, txd, state_q}; + + localparam STATE_INACTIVE = 0; + localparam STATE_ATTACHING = 1; + localparam STATE_IDLE = 2; + localparam STATE_BAD_COMMAND = 3; + localparam STATE_GET_V_HIGH = 4; + localparam STATE_GET_V_LOW = 5; + localparam STATE_SEND_Y = 6; + localparam STATE_GET_BS_Y = 7; + localparam STATE_GET_BS_HI = 8; + localparam STATE_GET_BS_LO = 9; + localparam STATE_SEND_00 = 10; + localparam STATE_IGNORE_DATA = 11; + localparam STATE_ACK_CMD = 12; + localparam STATE_SET_ADDR_HI = 13; + localparam STATE_SET_ADDR_LO = 14; + localparam STATE_SET_CNT_HI = 16; + localparam STATE_SET_CNT_LO = 17; + localparam STATE_CHECK_FLASH = 18; + localparam STATE_PROG_GET = 19; + localparam STATE_PROG_PUT = 20; + localparam STATE_EXIT1 = 21; + localparam STATE_EXIT2 = 22; + localparam STATE_SET_CNT_HI2 = 24; + localparam STATE_SET_CNT_LO2 = 25; + localparam STATE_CHECK_FLASH2 = 26; + localparam STATE_READ_GET = 27; + localparam STATE_READ_PUT = 28; + + avr109tx #(.CLK_FREQUENCY(CLK_FREQUENCY), .BAUD_RATE(BAUD_RATE)) + avr109tx_inst(.rst(rst), .clk(clk), + .tx_data(tx_data_q), .tx_avail(tx_avail_q), + .txd(txd), .tx_ready(tx_ready)); + + avr109rx #(.CLK_FREQUENCY(CLK_FREQUENCY), .BAUD_RATE(BAUD_RATE)) + avr109rx_inst(.rst(rst), .clk(clk), + .rx_data(rx_data), .rx_avail(rx_avail), + .rxd(rxd), .rx_enabled(rx_enabled)); + + assign rx_enabled = 1'b1; + + always @(*) begin + tx_avail_d = 0; + tx_data_d = 8'h00; + state_d = state_q; + cnt_d = cnt_q; + addr_d = addr_q; + prog_strobe = 1'b0; + prog_mode_d = prog_mode_q; + + case (state_q) + + STATE_INACTIVE: begin + cnt_d = 0; + prog_mode_d = 0; + if (rx_avail & (rx_data == 8'h1b)) begin + state_d = STATE_ATTACHING; + tx_data_d = 8'hff; + tx_avail_d = 1'b1; + end + end + + STATE_ATTACHING: begin + if (rx_avail) begin + if (rx_data != ((cnt_q&1)? 8'h1b : 8'haa)) + state_d = STATE_INACTIVE; + else begin + cnt_d[2:0] = cnt_q[2:0] + 1; + if (cnt_q[2:0] == 5) + state_d = STATE_IDLE; + end + end + end + + STATE_IDLE: begin + if (rx_avail) begin + case (rx_data) + 8'h0a, 8'h1b: ; + 8'h41: state_d = STATE_SET_ADDR_HI; + 8'h42: state_d = STATE_SET_CNT_HI; + 8'h45: state_d = STATE_EXIT1; + 8'h4c: begin + prog_mode_d = 1'b0; + state_d = STATE_ACK_CMD; + end + 8'h50: begin + prog_mode_d = 1'b1; + state_d = STATE_ACK_CMD; + end + 8'h54: state_d = STATE_IGNORE_DATA; + 8'h56: state_d = STATE_GET_V_HIGH; + 8'h61: state_d = STATE_SEND_Y; + 8'h62: state_d = STATE_GET_BS_Y; + 8'h67: state_d = STATE_SET_CNT_HI2; + 8'h74: state_d = STATE_SEND_00; + default: state_d = STATE_BAD_COMMAND; + endcase // case (rx_data) + end + end + + STATE_BAD_COMMAND: begin + if (send_ok) begin + tx_data_d = 8'h3f; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_GET_V_HIGH: begin + if (send_ok) begin + tx_data_d = VERSION_HIGH; + tx_avail_d = 1'b1; + state_d = STATE_GET_V_LOW; + end + end + + STATE_GET_V_LOW: begin + if (send_ok) begin + tx_data_d = VERSION_LOW; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_SEND_Y: begin + if (send_ok) begin + tx_data_d = 8'h59; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_GET_BS_Y: begin + if (send_ok) begin + tx_data_d = 8'h59; + tx_avail_d = 1'b1; + state_d = STATE_GET_BS_HI; + end + end + STATE_GET_BS_HI: begin + if (send_ok) begin + tx_data_d = 8'h00; + tx_avail_d = 1'b1; + state_d = STATE_GET_BS_LO; + end + end + STATE_GET_BS_LO: begin + if (send_ok) begin + tx_data_d = 8'hff; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_SEND_00: begin + if (send_ok) begin + tx_data_d = 8'h00; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_IGNORE_DATA: begin + if (rx_avail) + state_d = STATE_ACK_CMD; + end + + STATE_ACK_CMD: begin + if (send_ok) begin + tx_data_d = 8'h0d; + tx_avail_d = 1'b1; + state_d = STATE_IDLE; + end + end + + STATE_SET_ADDR_HI: begin + if (rx_avail) begin + addr_d[16:9] = rx_data; + state_d = STATE_SET_ADDR_LO; + end + end + STATE_SET_ADDR_LO: begin + if (rx_avail) begin + addr_d[8:0] = { rx_data, 1'b0 }; + state_d = STATE_ACK_CMD; + end + end + + STATE_SET_CNT_HI: begin + if (rx_avail) begin + if (rx_data == 0) + state_d = STATE_SET_CNT_LO; + else + state_d = STATE_BAD_COMMAND; + end + end + STATE_SET_CNT_LO: begin + if (rx_avail) begin + cnt_d = rx_data; + state_d = STATE_CHECK_FLASH; + end + end + STATE_CHECK_FLASH: begin + if (rx_avail) begin + if (rx_data == 8'h46) + state_d = (cnt_q == 0? STATE_ACK_CMD : STATE_PROG_GET); + else + state_d = STATE_BAD_COMMAND; + end + end + STATE_PROG_GET: begin + if (rx_avail) begin + cnt_d = cnt_q - 1; + state_d = STATE_PROG_PUT; + prog_strobe = 1'b1; + end + end + STATE_PROG_PUT: begin + addr_d = addr_q + 1; + state_d = (cnt_q == 0? STATE_ACK_CMD : STATE_PROG_GET); + end + + STATE_SET_CNT_HI2: begin + if (rx_avail) begin + if (rx_data == 0) + state_d = STATE_SET_CNT_LO2; + else + state_d = STATE_BAD_COMMAND; + end + end + STATE_SET_CNT_LO2: begin + if (rx_avail) begin + cnt_d = rx_data; + state_d = STATE_CHECK_FLASH2; + end + end + STATE_CHECK_FLASH2: begin + if (rx_avail) begin + if (rx_data == 8'h46) + state_d = (cnt_q == 0? STATE_IDLE : STATE_READ_GET); + else + state_d = STATE_BAD_COMMAND; + end + end + STATE_READ_GET: begin + tx_data_d = (addr_q[0]? prog_data_in[15:8]:prog_data_in[7:0]); + if (send_ok) begin + tx_avail_d = 1'b1; + cnt_d = cnt_q - 1; + state_d = STATE_READ_PUT; + end + end + STATE_READ_PUT: begin + addr_d = addr_q + 1; + state_d = (cnt_q == 0? STATE_IDLE : STATE_READ_GET); + end + + STATE_EXIT1: begin + if (send_ok) begin + tx_data_d = 8'h0d; + tx_avail_d = 1'b1; + state_d = STATE_EXIT2; + end + end + STATE_EXIT2: begin + if (send_ok) + state_d = STATE_INACTIVE; + end + + endcase // case (state) + end + + always @(posedge clk) begin + if (rst) begin + tx_avail_q <= 1'b0; + tx_data_q <= 8'h00; + state_q <= STATE_INACTIVE; + cnt_q <= 0; + addr_q <= 0; + prog_mode_q <= 1'b0; + end else begin + tx_avail_q <= tx_avail_d; + tx_data_q <= tx_data_d; + state_q <= state_d; + cnt_q <= cnt_d; + addr_q <= addr_d; + prog_mode_q <= prog_mode_d; + end + end + +endmodule // avr109 diff --git a/zeldin_iceGDROM/fpga/source/avr/avr109rx.v b/zeldin_iceGDROM/fpga/source/avr/avr109rx.v new file mode 100644 index 0000000000000000000000000000000000000000..a57be568650ec588a4a73501903118a808a1de4a --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/avr/avr109rx.v @@ -0,0 +1,82 @@ +module avr109rx ( + input rst, + input clk, + output[7:0] rx_data, + output rx_avail, + input rxd, + input rx_enabled + ); + parameter CLK_FREQUENCY = 1000000; + parameter BAUD_RATE = 19200; + + function integer log2; + input integer value; + begin + value = value-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end + endfunction + + localparam BAUDDIV = (CLK_FREQUENCY / BAUD_RATE); + localparam LOG2_BAUDDIV = log2(BAUDDIV); + + reg [7:0] rxshift_d, rxshift_q; + reg rx_active_d, rx_active_q; + reg rx_done_d, rx_done_q; + reg [3:0] rxcnt_d, rxcnt_q; + reg [LOG2_BAUDDIV-1:0] rxbaud_d, rxbaud_q; + + assign rx_data = rxshift_q; + assign rx_avail = rx_done_q; + + always @(*) begin + rx_active_d = rx_active_q; + rx_done_d = 1'b0; + + if (rx_active_q) begin + rxshift_d = rxshift_q; + rxcnt_d = rxcnt_q; + if (rxbaud_q == BAUDDIV-1) begin + if (rxcnt_q == 9) begin + if (rxd) begin + rx_active_d = 1'b0; + rx_done_d = 1'b1; + end + end else begin + rxshift_d = {rxd, rxshift_q[7:1]}; + rxcnt_d = rxcnt_q + 1; + end + rxbaud_d = 0; + end else begin + rxbaud_d = rxbaud_q + 1; + end + end else begin + rxshift_d = {8{1'b0}}; + rxcnt_d = 0; + rxbaud_d = BAUDDIV/2; + if (~rxd) begin + rx_active_d = 1'b1; + end + end + + end + + always @(posedge clk) begin + if (rst | ~rx_enabled) begin + rxshift_q <= {8{1'b0}}; + rx_active_q <= 1'b0; + rx_done_q <= 1'b0; + rxcnt_q <= 0; + rxbaud_q <= 0; + end else begin + rxshift_q <= rxshift_d; + rx_active_q <= rx_active_d; + rx_done_q <= rx_done_d; + rxcnt_q <= rxcnt_d; + rxbaud_q <= rxbaud_d; + end + end + +endmodule // avr109rx + diff --git a/zeldin_iceGDROM/fpga/source/avr/avr109tx.v b/zeldin_iceGDROM/fpga/source/avr/avr109tx.v new file mode 100644 index 0000000000000000000000000000000000000000..13eecc3ca20c7eca4438b218728fdb5fc65ade4e --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/avr/avr109tx.v @@ -0,0 +1,70 @@ +module avr109tx ( + input rst, + input clk, + input[7:0] tx_data, + input tx_avail, + output txd, + output tx_ready + ); + parameter CLK_FREQUENCY = 1000000; + parameter BAUD_RATE = 19200; + + function integer log2; + input integer value; + begin + value = value-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end + endfunction + + localparam BAUDDIV = (CLK_FREQUENCY / BAUD_RATE); + localparam LOG2_BAUDDIV = log2(BAUDDIV); + + reg [8:0] txshift_d, txshift_q; + reg [3:0] txcnt_d, txcnt_q; + reg tx_active_d, tx_active_q; + reg [LOG2_BAUDDIV-1:0] txbaud_d, txbaud_q; + + assign txd = txshift_q[0]; + assign tx_ready = ~tx_active_q; + + always @(*) begin + txshift_d = txshift_q; + txcnt_d = txcnt_q; + tx_active_d = tx_active_q; + txbaud_d = txbaud_q; + + if (tx_active_q) begin + if (txbaud_q == BAUDDIV-1) begin + txshift_d = {1'b1, txshift_q[8:1]}; + if (txcnt_q == 9) + tx_active_d = 0; + txcnt_d = txcnt_q + 1; + txbaud_d = 0; + end else begin + txbaud_d = txbaud_q + 1; + end + end else if (tx_avail) begin + txshift_d = {tx_data, 1'b0}; + txcnt_d = 0; + txbaud_d = 0; + tx_active_d = 1; + end + end + + always @(posedge clk) begin + if (rst) begin + txshift_q <= 9'b111111111; + txcnt_q <= 4'b0; + tx_active_q <= 1'b0; + txbaud_q <= {LOG2_BAUDDIV{1'b0}}; + end else begin + txshift_q <= txshift_d; + txcnt_q <= txcnt_d; + tx_active_q <= tx_active_d; + txbaud_q <= txbaud_d; + end + end + +endmodule // avr109tx diff --git a/zeldin_iceGDROM/fpga/source/cdda/cdda_interface.v b/zeldin_iceGDROM/fpga/source/cdda/cdda_interface.v new file mode 100644 index 0000000000000000000000000000000000000000..2b851c7e63d06384170508bb9e3ad99ae87efe20 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/cdda/cdda_interface.v @@ -0,0 +1,154 @@ +module cdda_interface ( + output bck, + output sd, + output lrck, + + input clk, + input rst, + input[10:0] sram_a, + input[31:0] sram_d_in, + output[7:0] sram_d_out, + input sram_cs, + input sram_oe, + input[3:0] sram_wstrb, + output sram_wait, + input[7:0] sdcard_dma_data, + input[8:0] sdcard_dma_addr, + input sdcard_dma_strobe, + ); + + parameter CLK_FREQUENCY = 33868800; + + assign sram_wait = 1'b0; + + reg [7:0] sram_d; + assign sram_d_out = sram_d; + + wire consume_data; + + wire [15:0] left_read_data, right_read_data; + + wire [7:0] cpu_access_pos; + wire cpu_writes_to_buffer; + wire cpu_writes_left_low, cpu_writes_left_high; + wire cpu_writes_right_low, cpu_writes_right_high; + + reg enabled_d, enabled_q; + reg dso_enabled_d, dso_enabled_q; + reg underflow_d, underflow_q; + reg dma_mode_d, dma_mode_q; + reg dma_buffer_select_d, dma_buffer_select_q; + reg [7:0] bufpos_d, bufpos_q; + reg [7:0] last_valid_data_d, last_valid_data_q; + reg [7:0] scratchpad_d, scratchpad_q; + + wire [9:0] write_addr; + wire [3:0] write_strobe; + wire [15:0] write_data_l; + wire [15:0] write_data_r; + assign write_addr = (dma_mode_q? {dma_buffer_select_q, sdcard_dma_addr} : sram_a[9:0]); + assign write_strobe = (dma_mode_q? 1 << sdcard_dma_addr[1:0] : sram_wstrb); + assign write_data_l = (dma_mode_q? {2{sdcard_dma_data}} : sram_d_in[15:0]); + assign write_data_r = (dma_mode_q? {2{sdcard_dma_data}} : sram_d_in[31:16]); + + assign cpu_access_pos = write_addr[9:2]; + assign cpu_writes_to_buffer = (dma_mode_q? sdcard_dma_strobe : (sram_cs & sram_a[10])); + assign cpu_writes_left_low = cpu_writes_to_buffer & write_strobe[0]; + assign cpu_writes_left_high = cpu_writes_to_buffer & write_strobe[1]; + assign cpu_writes_right_low = cpu_writes_to_buffer & write_strobe[2]; + assign cpu_writes_right_high = cpu_writes_to_buffer & write_strobe[3]; + + digital_sound_output #(.CLK_FREQUENCY(CLK_FREQUENCY)) + dso_inst(.clk(clk), .rst(rst), .enabled(dso_enabled_q), + .left(left_read_data), .right(right_read_data), + .bck(bck), .sd(sd), .lrck(lrck), .consume(consume_data)); + + ide_data_buffer left_data(.clk(clk), .rst(rst), + .read_addr(bufpos_q), + .read_data(left_read_data), + .write_addr(cpu_access_pos), + .write_data(write_data_l), + .write_hi(cpu_writes_left_high), + .write_lo(cpu_writes_left_low)); + + ide_data_buffer right_data(.clk(clk), .rst(rst), + .read_addr(bufpos_q), + .read_data(right_read_data), + .write_addr(cpu_access_pos), + .write_data(write_data_r), + .write_hi(cpu_writes_right_high), + .write_lo(cpu_writes_right_low)); + + always @(*) begin + case (sram_a[3:2]) + 2'b00: sram_d = { 4'b0000, dma_buffer_select_q, dma_mode_q, underflow_q, enabled_q }; + 2'b01: sram_d = bufpos_q; + 2'b10: sram_d = last_valid_data_q; + 2'b11: sram_d = scratchpad_q; + default: sram_d = 0; + endcase // case (sram_a[3:2]) + end + + always @(*) begin + bufpos_d = bufpos_q; + underflow_d = underflow_q; + enabled_d = enabled_q; + last_valid_data_d = last_valid_data_q; + scratchpad_d = scratchpad_q; + dma_mode_d = dma_mode_q; + dma_buffer_select_d = dma_buffer_select_q; + + if (enabled_q) begin + dso_enabled_d = 1'b1; + if (consume_data) begin + if (bufpos_q == last_valid_data_q) + underflow_d = 1'b1; + else + bufpos_d = bufpos_q+1; + end + end else begin + if (consume_data) + dso_enabled_d = 1'b0; + else + dso_enabled_d = dso_enabled_q; + end + + if (sram_cs & sram_wstrb[0] & ~sram_a[10]) begin + case (sram_a[3:2]) + 2'b00: begin + enabled_d = sram_d_in[0]; + if (sram_d_in[1]) underflow_d = 1'b0; + dma_mode_d = sram_d_in[2]; + dma_buffer_select_d = sram_d_in[3]; + end + 2'b01: bufpos_d = sram_d_in[7:0]; + 2'b10: last_valid_data_d = sram_d_in[7:0]; + 2'b11: scratchpad_d = sram_d_in[7:0]; + endcase // case (sram_a[3:2]) + end + end + + always @(posedge clk) begin + if (rst) begin + enabled_q <= 1'b0; + dso_enabled_q <= 1'b0; + underflow_q <= 1'b0; + bufpos_q <= 8'h00; + last_valid_data_q <= 8'h00; + scratchpad_q <= 8'h55; + dma_mode_q <= 1'b0; + dma_buffer_select_q <= 1'b0; + end else begin + enabled_q <= enabled_d; + dso_enabled_q <= dso_enabled_d; + underflow_q <= underflow_d; + bufpos_q <= bufpos_d; + last_valid_data_q <= last_valid_data_d; + scratchpad_q <= scratchpad_d; + dma_mode_q <= dma_mode_d; + dma_buffer_select_q <= dma_buffer_select_d; + end + end + +endmodule // cdda_interface + diff --git a/zeldin_iceGDROM/fpga/source/cdda/digital_sound_output.v b/zeldin_iceGDROM/fpga/source/cdda/digital_sound_output.v new file mode 100644 index 0000000000000000000000000000000000000000..31406f0ec2494c2ec319671edb41ae7dfe3f30a6 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/cdda/digital_sound_output.v @@ -0,0 +1,106 @@ +module digital_sound_output ( + input clk, + input rst, + input enabled, + input[15:0] left, + input[15:0] right, + output bck, + output sd, + output lrck, + output consume + ); + + parameter CLK_FREQUENCY = 33868800; + + localparam BCK_HALF_PERIOD = (CLK_FREQUENCY / 44100 / 64 / 2); + + function integer log2; + input integer value; + begin + value = value-1; + for (log2=0; value>0; log2=log2+1) + value = value>>1; + end + endfunction + + reg [log2(BCK_HALF_PERIOD)-1:0] bck_counter_d, bck_counter_q; + reg bck_d, bck_q; + reg sd_d, sd_q; + reg lrck_d, lrck_q; + reg bit_active_d, bit_active_q; + reg [5:0] bit_counter_d, bit_counter_q; + reg [31:0] shiftreg_d, shiftreg_q; + reg consume_d, consume_q; + + assign bck = bck_q; + assign sd = sd_q; + assign lrck = lrck_q; + assign consume = consume_q; + + always @(*) begin + + if (enabled) begin + if (bck_counter_q == BCK_HALF_PERIOD-1) begin + bck_counter_d = 0; + bck_d = ~bck_q; + end else begin + bck_counter_d = bck_counter_q + 1; + bck_d = bck_q; + end + end else begin + bck_counter_d = 0; + bck_d = bck_q; + end + + if ((bck_counter_q == BCK_HALF_PERIOD-2) & bck_q & enabled) + bit_active_d = 1'b1; + else + bit_active_d = 1'b0; + + shiftreg_d = (enabled? shiftreg_q : 32'h00000000); + consume_d = 1'b0; + if (bit_active_q) begin + if (bit_counter_q[4]) begin + sd_d = shiftreg_q[31]; + shiftreg_d = {shiftreg_q[30:0],1'b0}; + end else begin + sd_d = 1'b0; + if (bit_counter_q == 0) begin + shiftreg_d = {left, right}; + consume_d = 1'b1; + end + end + lrck_d = ~bit_counter_q[5]; + bit_counter_d = bit_counter_q+1; + end else begin + sd_d = sd_q; + lrck_d = lrck_q; + bit_counter_d = bit_counter_q; + end + + end + + always @(posedge clk) begin + if (rst) begin + bck_counter_q <= 0; + bck_q <= 1'b0; + sd_q <= 1'b0; + lrck_q <= 1'b0; + bit_active_q <= 1'b0; + bit_counter_q <= 5'b00000; + shiftreg_q <= 32'h00000000; + consume_q <= 1'b0; + end else begin + bck_counter_q <= bck_counter_d; + bck_q <= bck_d; + sd_q <= sd_d; + lrck_q <= lrck_d; + bit_active_q <= bit_active_d; + bit_counter_q <= bit_counter_d; + shiftreg_q <= shiftreg_d; + consume_q <= consume_d; + end + end + +endmodule // digital_sound_output + diff --git a/zeldin_iceGDROM/fpga/source/ide/ide_interface.v b/zeldin_iceGDROM/fpga/source/ide/ide_interface.v new file mode 100644 index 0000000000000000000000000000000000000000..68f5fc636e40b8b74e126282aa065df37a6a1a55 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/ide_interface.v @@ -0,0 +1,454 @@ +module ide_interface ( + inout[15:0] dd, + input[2:0] da, + input cs1fx_, + input cs3fx_, + inout dasp_, + input dior_, + input diow_, + input dmack_, + inout dmarq, + inout intrq, + inout iocs16_, + inout iordy, + inout pdiag_, + input reset_, + input csel, + input clk, + input[10:0] sram_a, + input[31:0] sram_d_in, + output[31:0] sram_d_out, + input sram_cs, + input sram_oe, + input[3:0] sram_wstrb, + output sram_wait, + output cpu_irq, + input[7:0] sdcard_dma_data, + input[8:0] sdcard_dma_addr, + input sdcard_dma_strobe + ); + + parameter drv = 1'b0; + parameter add_read_ws = 0; + + assign dasp_ = 1'bz; + assign pdiag_ = 1'bz; + + wire [2:0] da_in; + wire cs1fx_in, cs3fx_in, dior_in, diow_in; + wire dmack_in, reset_in; + + ide_status_pin da_pin[2:0](.pin(da), .in(da_in), .clk(clk)); + ide_status_pin cs1fx_pin(.pin(cs1fx_), .in(cs1fx_in), .clk(clk)); + ide_status_pin cs3fx_pin(.pin(cs3fx_), .in(cs3fx_in), .clk(clk)); + ide_status_pin dior_pin(.pin(dior_), .in(dior_in), .clk(clk)); + ide_status_pin diow_pin(.pin(diow_), .in(diow_in), .clk(clk)); + ide_status_pin dmack_pin(.pin(dmack_), .in(dmack_in), .clk(clk)); + ide_status_pin reset_pin(.pin(reset_), .in(reset_in), .clk(clk)); + + wire dmarq_enabled; + wire dmarq_level; + wire intrq_enabled; + wire intrq_level; + wire iocs16_asserted; + wire iowait; + + ide_control_pin + dmarq_pin(.pin(dmarq), .out(dmarq_level), .enable(dmarq_enabled), .clk(clk)); + ide_control_pin + intrq_pin(.pin(intrq), .out(intrq_level), .enable(intrq_enabled), .clk(clk)); + ide_control_pin + iocs16_pin(.pin(iocs16_), .out(1'b0), .enable(iocs16_asserted), .clk(clk)); + ide_control_pin + iordy_pin(.pin(iordy), .out(1'b0), .enable(iowait), .clk(clk)); + + assign dmarq_enabled = dma_mode&drv_selected; + assign dmarq_level = dmarq_q; + assign iocs16_asserted = 1'b0; + assign iowait = 1'b0; + + wire [15:0] dd_in; + reg [15:0] dd_out; + wire dd_latch; + wire dd_enable; + + ide_data_pin ide_data_pin_inst[15:0](.pin(dd), .in(dd_in), .out(dd_out), + .latch({16{dd_latch}}), + .enable({16{dd_enable}}), + .clk({16{clk}})); + + assign dd_latch = diow_in; + assign dd_enable = (ctrl_blk|cmnd_blk|dma_active)&(~cur_dior)&drv_selected; + + wire rst; + + reg [8:0] buffer_read_addr, buffer_write_addr; + wire [15:0] buffer_read_data, buffer_read_data_a, buffer_read_data_b; + reg [15:0] buffer_write_data_a, buffer_write_data_b; + reg buffer_write_hi_a, buffer_write_lo_a; + reg buffer_write_hi_b, buffer_write_lo_b; + + reg [7:0] busctl_oldold, busctl_old, busctl_cur; + + assign buffer_read_data = (buffer_read_addr[0]? buffer_read_data_b : buffer_read_data_a); + + always @(posedge clk) begin + if (rst) begin + busctl_oldold <= 8'b11111000; + busctl_old <= 8'b11111000; + end else begin + busctl_oldold <= busctl_old; + busctl_old <= busctl_cur; + end + busctl_cur <= {dmack_in,diow_in,dior_in,cs3fx_in,cs1fx_in,da_in}; + end + + wire[2:0] bus_addr; + wire bus_cs1; + wire bus_cs3; + wire oldold_dior; + wire oldold_diow; + wire old_dior; + wire old_diow; + wire cur_dior; + wire cur_diow; + wire cur_dmack; + wire old_dmack; + assign bus_addr = busctl_old[2:0]; + assign bus_cs1 = busctl_old[3]; + assign bus_cs3 = busctl_old[4]; + assign oldold_dior = busctl_oldold[5]; + assign oldold_diow = busctl_oldold[6]; + assign old_dior = busctl_old[5]; + assign old_diow = busctl_old[6]; + assign cur_dior = busctl_cur[5]; + assign cur_diow = busctl_cur[6]; + assign cur_dmack = busctl_cur[7]; + assign old_dmack = busctl_old[7]; + + wire ctrl_blk; + wire cmnd_blk; + wire write_cycle; + wire read_cycle; + wire dma_active; + + assign ctrl_blk = (~bus_cs3)&(bus_addr[2:1]==2'b11); + assign cmnd_blk = ~bus_cs1; + assign dma_active = dma_mode&~cur_dmack; + assign write_cycle = (~oldold_diow)&(~old_diow)&cur_diow; + assign read_cycle = (~oldold_dior)&(~old_dior)&cur_dior; + + reg [7:0] status_d, status_q; + reg [7:0] error_d, error_q; + reg [7:0] features_d, features_q; + reg [7:0] seccnt_d, seccnt_q; + reg [7:0] secnr_d, secnr_q; + reg [7:0] cyllo_d, cyllo_q; + reg [7:0] cylhi_d, cylhi_q; + reg [7:0] drvhead_d, drvhead_q; + reg [7:0] command_d, command_q; + reg [7:0] iocontrol_d, iocontrol_q; + reg [7:0] iopos_d, iopos_q; + reg [7:0] iotarget_d, iotarget_q; + reg cmd_d, cmd_q; + reg data_d, data_q; + reg hrst_d, hrst_q; + reg srst_d, srst_q; + reg nien_d, nien_q; + reg irq_d, irq_q; + reg dmarq_d, dmarq_q; + wire bsy; + wire drv_selected; + wire pio_mode; + wire dma_mode; + wire sdcard_dma_mode; + wire sdcard_dma_bank; + wire active_bank; + assign bsy = status_q[7]; + assign drv_selected = (drvhead_q[4] == drv); + assign pio_mode = iocontrol_q[1]; + assign dma_mode = iocontrol_q[2]; + assign sdcard_dma_bank = iocontrol_q[5]; + assign sdcard_dma_mode = iocontrol_q[6]; + assign active_bank = iocontrol_q[7]; + assign cpu_irq = (srst_q | hrst_q | cmd_q | data_q) & ~rst; + + assign intrq_enabled = (~nien_q) & drv_selected; + assign intrq_level = irq_q; + + reg [31:0] sram_d; + assign sram_d_out = sram_d; + + generate + if(add_read_ws) begin : read_ws_is_added + assign sram_wait = sram_cs & sram_oe & sram_a[10] & !sram_wait_q; + reg sram_wait_q; + always @(posedge clk) begin + sram_wait_q <= sram_wait; + end + end else begin : read_ws_is_not_added + assign sram_wait = 1'b0; + end + endgenerate + + always @(posedge clk) begin + if (rst) begin + dd_out <= 16'h0000; + end else if (dma_active) begin + dd_out <= buffer_read_data; + end else begin + case ({bus_cs1,bus_cs3,bus_addr}) + 5'b10110: dd_out <= {8'h00, status_q}; /* Alternate status */ + 5'b01000: dd_out <= buffer_read_data; /* Data */ + 5'b01001: dd_out <= {8'h00, error_q}; /* Error register */ + 5'b01010: dd_out <= {8'h00, seccnt_q}; /* Sector count */ + 5'b01011: dd_out <= {8'h00, secnr_q}; /* Sector number */ + 5'b01100: dd_out <= {8'h00, cyllo_q}; /* Cylinder low */ + 5'b01101: dd_out <= {8'h00, cylhi_q}; /* Cylinder high */ + 5'b01110: dd_out <= {8'h00, drvhead_q}; /* Drive/head */ + 5'b01111: dd_out <= {8'h00, status_q}; /* Status */ + default: dd_out <= 16'h0000; + endcase + end + end + + always @(*) begin + if (sram_a[10]) begin + sram_d = { buffer_read_data_b, buffer_read_data_a }; + end else begin + sram_d[31:8] = 0; + case (sram_a[5:2]) + 4'b0000: sram_d[7:0] = status_q; + 4'b0001: sram_d[7:0] = error_q; + 4'b0010: sram_d[7:0] = iocontrol_q; + 4'b0011: sram_d[7:0] = iopos_q; + 4'b0100: sram_d[7:0] = status_q; + 4'b0101: sram_d[7:0] = iotarget_q; + 4'b0110: sram_d[7:0] = { 2'b00, data_q, cmd_q, hrst_q, srst_q, nien_q, irq_q }; + 4'b1001: sram_d[7:0] = features_q; + 4'b1010: sram_d[7:0] = seccnt_q; + 4'b1011: sram_d[7:0] = secnr_q; + 4'b1100: sram_d[7:0] = cyllo_q; + 4'b1101: sram_d[7:0] = cylhi_q; + 4'b1110: sram_d[7:0] = drvhead_q; + 4'b1111: sram_d[7:0] = command_q; + default: sram_d[7:0] = 0; + endcase // case (sram_a[5:2]) + end + end + + always @(*) begin + status_d = status_q; + error_d = error_q; + features_d = features_q; + seccnt_d = seccnt_q; + secnr_d = secnr_q; + cyllo_d = cyllo_q; + cylhi_d = cylhi_q; + drvhead_d = drvhead_q; + command_d = command_q; + iocontrol_d = iocontrol_q; + iopos_d = iopos_q; + iotarget_d = iotarget_q; + cmd_d = cmd_q; + data_d = data_q; + hrst_d = hrst_q; + srst_d = srst_q; + nien_d = nien_q; + irq_d = irq_q; + dmarq_d = dmarq_q; + if (read_cycle & ({bus_cs1,bus_cs3,bus_addr} == 5'b01111) & drv_selected) begin + /* Read status register; clear IRQ */ + irq_d = 1'b0; + end + if (write_cycle & {bus_cs1,bus_cs3,bus_addr} == 5'b10110) begin + /* Write device control */ + nien_d = dd_in[1]; + srst_d = dd_in[2]; + end + if ((read_cycle|write_cycle) & ({bus_cs1,bus_cs3,bus_addr} == 5'b01000) & drv_selected & pio_mode) begin + /* Read or write Data increments iopos */ + iopos_d = iopos_q+1; + if (iopos_q == iotarget_q) begin + data_d = 1'b1; + status_d[7] = 1'b1; /* BSY */ + end + end + if (read_cycle & dma_mode & ~old_dmack) begin + /* DMA read */ + iopos_d = iopos_q+1; + if (iopos_q == iotarget_q) begin + data_d = 1'b1; + iocontrol_d[2] = 1'b0; /* Disable DMA */ + end + end + if (dma_mode & ~old_dmack & ~cur_dior & (iopos_q == iotarget_q)) begin + dmarq_d = 1'b0; /* Last word, so negate DMARQ */ + end + if (sram_cs & sram_wstrb[0] & ~sram_a[10]) begin + case (sram_a[5:2]) + 4'b0000: begin + status_d = sram_d_in[7:0]; + irq_d = 1'b1; + end + 4'b0100: status_d = sram_d_in[7:0]; + 4'b0001: error_d = sram_d_in[7:0]; + 4'b0010: begin + if (sram_d_in[7]) + iocontrol_d[7] = ~iocontrol_q[7]; + else if (sram_d_in[6]) + iocontrol_d[6:4] = sram_d_in[2:0]; + else begin + iocontrol_d[3:0] = sram_d_in[3:0]; + dmarq_d = sram_d_in[2]; + end + end + 4'b0011: iopos_d = sram_d_in[7:0]; + 4'b0101: iotarget_d = sram_d_in[7:0]; + 4'b0110: begin + if (sram_d_in[0]) + irq_d = 1'b0; + if (sram_d_in[2]) + srst_d = 1'b0; + if (sram_d_in[3]) + hrst_d = 1'b0; + if (sram_d_in[4]) + cmd_d = 1'b0; + if (sram_d_in[5]) + data_d = 1'b0; + end + 4'b1011: secnr_d = sram_d_in[7:0]; + endcase + end + if (bsy) begin + if (sram_cs & sram_wstrb[0] & ~sram_a[10]) begin + case (sram_a[5:2]) + 4'b1001: features_d = sram_d_in[7:0]; + 4'b1010: seccnt_d = sram_d_in[7:0]; + 4'b1100: cyllo_d = sram_d_in[7:0]; + 4'b1101: cylhi_d = sram_d_in[7:0]; + 4'b1110: drvhead_d = sram_d_in[7:0]; + endcase + end + end else if (write_cycle) begin + case ({bus_cs1,bus_cs3,bus_addr}) + 5'b01001: features_d = dd_in[7:0]; + 5'b01010: seccnt_d = dd_in[7:0]; + 5'b01100: cyllo_d = dd_in[7:0]; + 5'b01101: cylhi_d = dd_in[7:0]; + 5'b01110: drvhead_d = dd_in[7:0]; + endcase + end + if (write_cycle & ({bus_cs1,bus_cs3,bus_addr} == 5'b01111)) begin + /* Write to Command */ + irq_d = 1'b0; + command_d = dd_in[7:0]; + status_d[7] = 1'b1; /* BSY */ + cmd_d = 1'b1; + end + end + + always @(posedge clk) begin + if (rst) begin + status_q <= 8'b10000000; + error_q <= 8'h00; + features_q <= 8'h00; + seccnt_q <= 8'h00; + secnr_q <= 8'h00; + cyllo_q <= 8'h00; + cylhi_q <= 8'h00; + drvhead_q <= 8'h00; + command_q <= 8'h00; + iocontrol_q <= 8'h00; + iopos_q <= 8'h00; + iotarget_q <= 8'h00; + cmd_q <= 1'b0; + data_q <= 1'b0; + hrst_q <= 1'b1; + srst_q <= 1'b0; + nien_q <= 1'b0; + irq_q <= 1'b0; + dmarq_q <= 1'b0; + end else begin + status_q <= status_d; + error_q <= error_d; + features_q <= features_d; + seccnt_q <= seccnt_d; + secnr_q <= secnr_d; + cyllo_q <= cyllo_d; + cylhi_q <= cylhi_d; + drvhead_q <= drvhead_d; + command_q <= command_d; + iocontrol_q <= iocontrol_d; + iopos_q <= iopos_d; + iotarget_q <= iotarget_d; + cmd_q <= cmd_d; + data_q <= data_d; + hrst_q <= hrst_d; + srst_q <= srst_d; + nien_q <= nien_d; + irq_q <= irq_d; + dmarq_q <= dmarq_d; + end + end + + wire bus_data_write, rv_data_write; + assign bus_data_write = write_cycle & ({bus_cs1,bus_cs3,bus_addr} == 5'b01000) & pio_mode; + assign rv_data_write = sram_cs & sram_a[10]; + + always @(*) begin + if (iocontrol_q[0]) begin + /* Bus writes, RISC-V reads */ + buffer_write_hi_a = bus_data_write && !iopos_q[0]; + buffer_write_lo_a = bus_data_write && !iopos_q[0]; + buffer_write_hi_b = bus_data_write && iopos_q[0]; + buffer_write_lo_b = bus_data_write && iopos_q[0]; + buffer_write_addr = {active_bank, iopos_q}; + buffer_write_data_a = dd_in; + buffer_write_data_b = dd_in; + + buffer_read_addr = {sram_a[9]^active_bank, sram_a[8:1]}; + end else if(sdcard_dma_mode) begin + /* Bus reads, SDCARD writes */ + buffer_write_hi_a = sdcard_dma_strobe & (sdcard_dma_addr[1:0] == 2'b01); + buffer_write_lo_a = sdcard_dma_strobe & (sdcard_dma_addr[1:0] == 2'b00); + buffer_write_hi_b = sdcard_dma_strobe & (sdcard_dma_addr[1:0] == 2'b11); + buffer_write_lo_b = sdcard_dma_strobe & (sdcard_dma_addr[1:0] == 2'b10); + buffer_write_addr = {sdcard_dma_bank^active_bank, sdcard_dma_addr[8:1]}; + buffer_write_data_a = {sdcard_dma_data, sdcard_dma_data}; + buffer_write_data_b = {sdcard_dma_data, sdcard_dma_data}; + + buffer_read_addr = {active_bank, iopos_q}; + end else begin + /* Bus reads, RISC-V writes */ + buffer_write_hi_a = rv_data_write & sram_wstrb[1]; + buffer_write_lo_a = rv_data_write & sram_wstrb[0]; + buffer_write_hi_b = rv_data_write & sram_wstrb[3]; + buffer_write_lo_b = rv_data_write & sram_wstrb[2]; + buffer_write_addr = {sram_a[9]^active_bank, sram_a[8:1]}; + buffer_write_data_a = sram_d_in[15:0]; + buffer_write_data_b = sram_d_in[31:16]; + + buffer_read_addr = {active_bank, iopos_q}; + end + end + + ide_data_buffer buffer_inst_a(.clk(clk), .rst(rst), + .read_addr(buffer_read_addr[8:1]), + .read_data(buffer_read_data_a), + .write_addr(buffer_write_addr[8:1]), + .write_data(buffer_write_data_a), + .write_hi(buffer_write_hi_a), + .write_lo(buffer_write_lo_a)); + + ide_data_buffer buffer_inst_b(.clk(clk), .rst(rst), + .read_addr(buffer_read_addr[8:1]), + .read_data(buffer_read_data_b), + .write_addr(buffer_write_addr[8:1]), + .write_data(buffer_write_data_b), + .write_hi(buffer_write_hi_b), + .write_lo(buffer_write_lo_b)); + + ide_reset_generator reset_inst(.rst_in(reset_in), .clk(clk), .rst_out(rst)); + +endmodule // ide_interface diff --git a/zeldin_iceGDROM/fpga/source/ide/ide_reset_generator.v b/zeldin_iceGDROM/fpga/source/ide/ide_reset_generator.v new file mode 100644 index 0000000000000000000000000000000000000000..e8a1ccc300e064c7e117d2bee0deff7594828d94 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/ide_reset_generator.v @@ -0,0 +1,24 @@ +module ide_reset_generator ( + input rst_in, + input clk, + output rst_out + ); + + reg rst; + reg [20:0] rst_cnt; + assign rst_out = ~rst; + + always @(posedge clk) begin + if (rst_in == rst) begin + rst_cnt <= 21'h000000; + end else begin + if (rst_in == 1'b0 && rst_cnt == 21'h000300) begin + rst <= 1'b0; + end else if (rst_in == 1'b1 && rst_cnt == 21'h150000) begin + rst <= 1'b1; + end + rst_cnt <= rst_cnt + 1; + end + end + +endmodule // ide_reset_generator diff --git a/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_control_pin.v b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_control_pin.v new file mode 100644 index 0000000000000000000000000000000000000000..a2984576fe06bbc6b7a54dab0dcd6960282e013a --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_control_pin.v @@ -0,0 +1,20 @@ +module ide_control_pin( + inout pin, + input out, + input enable, + input clk + ); + + SB_IO #(.PIN_TYPE(6'b111001), .PULLUP(1'b0), .NEG_TRIGGER(1'b1)) + ide_data_pin_impl(.PACKAGE_PIN(pin), + .CLOCK_ENABLE(1'b1), + .INPUT_CLK(), + .OUTPUT_CLK(clk), + .OUTPUT_ENABLE(enable), + .D_OUT_0(out), + .D_OUT_1(), + .D_IN_0(), + .D_IN_1() + ); + +endmodule // ide_control_pin diff --git a/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_buffer.v b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_buffer.v new file mode 100644 index 0000000000000000000000000000000000000000..3fd01b8a156fd6df5457132bd24c907c29708781 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_buffer.v @@ -0,0 +1,25 @@ +module ide_data_buffer(input clk, + input rst, + input[7:0] read_addr, + output[15:0] read_data, + input[7:0] write_addr, + input[15:0] write_data, + input write_hi, + input write_lo + ); + + reg [15:0] ram_data[255:0]; + reg [15:0] data_latch; + + assign read_data = data_latch; + + always @(posedge clk) begin + if (write_hi) + ram_data[write_addr][15:8] <= write_data[15:8]; + if (write_lo) + ram_data[write_addr][7:0] <= write_data[7:0]; + + data_latch <= ram_data[read_addr]; + end + +endmodule // ide_data_buffer diff --git a/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_pin.v b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_pin.v new file mode 100644 index 0000000000000000000000000000000000000000..4e83641deb873467af99a5175f693dfb67b4f2e8 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_data_pin.v @@ -0,0 +1,23 @@ +module ide_data_pin ( + inout pin, + output in, + input out, + input latch, + input enable, + input clk + ); + + SB_IO #(.PIN_TYPE(6'b111011), .PULLUP(1'b0), .NEG_TRIGGER(1'b1)) + ide_data_pin_impl(.PACKAGE_PIN(pin), + .LATCH_INPUT_VALUE(latch), + .CLOCK_ENABLE(1'b1), + .INPUT_CLK(), + .OUTPUT_CLK(clk), + .OUTPUT_ENABLE(enable), + .D_OUT_0(out), + .D_OUT_1(), + .D_IN_0(in), + .D_IN_1() + ); + +endmodule // ide_data_pin diff --git a/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_status_pin.v b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_status_pin.v new file mode 100644 index 0000000000000000000000000000000000000000..cd36cfa2aa06844cae2b2c5894d41ccf8681d9c8 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/ide/tech/ice40/ide_status_pin.v @@ -0,0 +1,18 @@ +module ide_status_pin( + inout pin, + output in, + input clk + ); + + SB_IO #(.PIN_TYPE(6'b000001), .PULLUP(1'b0), .NEG_TRIGGER(1'b1)) + ide_data_pin_impl(.PACKAGE_PIN(pin), + .CLOCK_ENABLE(1'b1), + .INPUT_CLK(clk), + .OUTPUT_CLK(), + .D_OUT_0(), + .D_OUT_1(), + .D_IN_0(in), + .D_IN_1() + ); + +endmodule // ide_status_pin diff --git a/zeldin_iceGDROM/fpga/source/sdcard/sdcard_interface.v b/zeldin_iceGDROM/fpga/source/sdcard/sdcard_interface.v new file mode 100644 index 0000000000000000000000000000000000000000..9779cfe75096232b2ca88e9d0704fa1d7ead0822 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/sdcard/sdcard_interface.v @@ -0,0 +1,147 @@ +module sdcard_interface( + output sclk, + output mosi, + input miso, + + input clk, + input rst, + input [9:0] sram_a, + input [15:0] sram_d_in, + output [15:0] sram_d_out, + input sram_cs, + input sram_oe, + input [1:0] sram_wstrb, + output sram_wait, + output [7:0] dma_data, + output [8:0] dma_addr, + output dma_strobe + ); + + wire [7:0] spi_data_in; + wire [7:0] spi_data_out; + wire start, finished; + wire spi_crc_in_bit, spi_crc_out_bit, spi_crc_strobe; + wire crc16_x, crc7_x; + + reg [7:0] divider_d, divider_q; + reg [4:0] bits_d, bits_q; + reg [7:0] latch_d, latch_q; + reg avail_d, avail_q; + reg [8:0] dma_counter_d, dma_counter_q; + reg dma_mode_d, dma_mode_q, dma_trigger_d, dma_trigger_q; + reg [15:0] crc16_d, crc16_q; + reg [6:0] crc7_d, crc7_q; + + assign spi_data_in = (dma_mode_q? 8'hff : sram_d_in[7:0]); + assign start = (dma_mode_q? dma_trigger_q : (sram_cs & sram_wstrb[0] & (sram_a[4:2] == 3'b001))); + assign sram_wait = 1'b0; + + assign dma_data = latch_q; + assign dma_addr = dma_counter_q; + assign dma_strobe = avail_q & dma_mode_q; + + reg [15:0] sram_d; + assign sram_d_out = sram_d; + + assign crc16_x = crc16_q[15]^spi_crc_in_bit; + assign crc7_x = crc7_q[6]^spi_crc_out_bit; + + sdcard_spi spi_inst(.sclk(sclk), .mosi(mosi), .miso(miso), + .rst(rst), .clk(clk), .data_in(spi_data_in), + .data_out(spi_data_out), .divider(divider_q), + .bits(bits_q), .start(start), .finished(finished), + .crc_in_bit(spi_crc_in_bit), .crc_out_bit(spi_crc_out_bit), + .crc_strobe(spi_crc_strobe)); + + always @(*) begin + sram_d = 16'h0000; + case (sram_a[4:2]) + 3'b000: sram_d[7:0] = {avail_q, dma_mode_q, 1'b0, bits_q}; + 3'b001: sram_d[7:0] = latch_q; + 3'b010: sram_d[7:0] = divider_q; + 3'b100: sram_d = crc16_q; + 3'b101: sram_d[7:0] = { crc7_q, 1'b1 }; + endcase + end + + always @(*) begin + divider_d = divider_q; + bits_d = bits_q; + avail_d = avail_q; + latch_d = latch_q; + dma_counter_d = dma_counter_q; + dma_mode_d = dma_mode_q; + dma_trigger_d = 1'b0; + crc16_d = crc16_q; + crc7_d = crc7_q; + + if (sram_cs & sram_wstrb[0]) begin + case (sram_a[4:2]) + 3'b000: begin + bits_d = sram_d_in[4:0]; + if (sram_d_in[6]) begin + dma_mode_d = 1'b1; + dma_trigger_d = 1'b1; + dma_counter_d = 9'h000; + end else begin + dma_mode_d = 1'b0; + end + avail_d = sram_d_in[7]; + end + 3'b001: avail_d = 1'b0; + 3'b010: divider_d = sram_d_in[7:0]; + 3'b100: crc16_d[7:0] = sram_d_in[7:0]; + 3'b101: crc7_d = sram_d_in[7:1]; + endcase + end + if (sram_cs & sram_wstrb[1]) begin + case (sram_a[4:2]) + 3'b100: crc16_d[15:8] = sram_d_in[15:8]; + endcase // case (sram_a[4:2]) + end + + if (finished) begin + avail_d = 1'b1; + latch_d = spi_data_out; + end + + if (avail_q & dma_mode_q) begin + avail_d = 1'b0; + dma_counter_d = dma_counter_q + 1; + if (dma_counter_q == 9'h1ff) + dma_mode_d = 1'b0; + else + dma_trigger_d = 1'b1; + end + + if (spi_crc_strobe) begin + crc16_d = {crc16_q[14:0],1'b0}^{3'b000,crc16_x,6'b000000,crc16_x,4'b0000,crc16_x}; + crc7_d = {crc7_q[6:0],1'b0}^{3'b000,crc7_x,2'b00,crc7_x}; + end + end // always @ (*) + + always @(posedge clk) begin + if (rst) begin + divider_q <= 8'h00; + bits_q <= 5'h00; + avail_q <= 1'b0; + latch_q <= 8'h00; + dma_counter_q <= 8'h00; + dma_mode_q <= 1'b0; + dma_trigger_q <= 1'b0; + crc16_q <= 16'h0000; + crc7_q <= 7'h00; + end else begin + divider_q <= divider_d; + bits_q <= bits_d; + avail_q <= avail_d; + latch_q <= latch_d; + dma_counter_q <= dma_counter_d; + dma_mode_q <= dma_mode_d; + dma_trigger_q <= dma_trigger_d; + crc16_q <= crc16_d; + crc7_q <= crc7_d; + end + end + +endmodule // sdcard_interface diff --git a/zeldin_iceGDROM/fpga/source/sdcard/sdcard_spi.v b/zeldin_iceGDROM/fpga/source/sdcard/sdcard_spi.v new file mode 100644 index 0000000000000000000000000000000000000000..f1075a42a0533347843908501a58c82c90302a1d --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/sdcard/sdcard_spi.v @@ -0,0 +1,92 @@ +module sdcard_spi ( + output sclk, + output mosi, + input miso, + + input rst, + input clk, + input [7:0] data_in, + output [7:0] data_out, + input [7:0] divider, + input [4:0] bits, + input start, + output finished, + output crc_in_bit, + output crc_out_bit, + output crc_strobe, + ); + + reg sclk_d, sclk_q; + reg [7:0] shift_in_d, shift_in_q, shift_out_d, shift_out_q; + reg [7:0] counter; + reg toggle, latch_d, latch_q, active_d, active_q; + reg [4:0] bits_d, bits_q; + + assign sclk = sclk_q; + assign mosi = shift_out_q[7]; + assign finished = active_q & ~active_d; + assign data_out = {shift_in_q[6:0], latch_q}; + assign crc_in_bit = latch_q; + assign crc_out_bit = shift_out_q[7]; + assign crc_strobe = active_q & toggle & sclk_q; + + always @(posedge clk) begin + if (divider == 0) + toggle <= 1'b1; + else + toggle <= (counter+1 == divider); + if (toggle | ~active_q) + counter <= 0; + else + counter <= counter+1; + end + + always @(*) begin + sclk_d = sclk_q; + shift_in_d = shift_in_q; + shift_out_d = shift_out_q; + latch_d = latch_q; + bits_d = bits_q; + active_d = active_q; + if (active_q & toggle) begin + sclk_d = ~sclk_q; + if (sclk_q) begin + shift_in_d = {shift_in_q[6:0], latch_q}; + shift_out_d = {shift_out_q[6:0], 1'b1}; + if ((bits_q == 0) | ~shift_in_q[6]) begin + active_d = 1'b0; + end else begin + bits_d = bits_q-1; + end + end else begin + latch_d = miso; + end + end + + if (start) begin + shift_in_d = 8'hff; + shift_out_d = data_in; + bits_d = bits; + active_d = 1'b1; + end + end + + always @(posedge clk) begin + if (rst) begin + active_q <= 1'b0; + bits_q <= 5'h00; + sclk_q <= 1'b0; + latch_q <= 1'b0; + shift_in_q <= 8'h00; + shift_out_q <= 8'h00; + end else begin + active_q <= active_d; + bits_q <= bits_d; + sclk_q <= sclk_d; + latch_q <= latch_d; + shift_in_q <= shift_in_d; + shift_out_q <= shift_out_d; + end + end + +endmodule // sdcard_spi diff --git a/zeldin_iceGDROM/fpga/source/tech/ice40/clkgen.v b/zeldin_iceGDROM/fpga/source/tech/ice40/clkgen.v new file mode 100644 index 0000000000000000000000000000000000000000..a1114a40676d19b6093cf43f501c914bdb13ffac --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/tech/ice40/clkgen.v @@ -0,0 +1,86 @@ +module clkgen( + input clkin, + output clkout, + output lock +); + + parameter INCLOCK_FREQ = 12000000; + parameter OUTCLOCK_FREQ = 24000000; + + localparam r_bits = 4; + localparam f_bits = 7; + localparam q_bits = 3; + + localparam rfq = compute_divisors(INCLOCK_FREQ, OUTCLOCK_FREQ); + localparam r = rfq[(q_bits+f_bits) +: r_bits]; + localparam f = rfq[q_bits +: f_bits]; + localparam q = rfq[0 +: q_bits]; + + function integer gcd; + input integer a; + input integer b; + integer t; + begin + while (b != 0) begin + t = b; + b = a % b; + a = t; + end; + gcd = a; + end + endfunction // gcd + + function integer pack_rfq; + input integer r; + input integer f; + input integer q; + begin + pack_rfq = {r[0 +: r_bits], f[0 +: f_bits], q[0 +: q_bits]}; + end + endfunction // pack_rfq + + function integer compute_divisors; + input integer f_ref; + input integer f_out; + integer g; + integer r; + integer f; + integer q; + begin + g = gcd(f_ref, f_out); + r = f_ref / g; + f = f_out / g; + q = 3; + while (q > 0 && f_out > f_ref) begin + q = q - 1; + f_ref = f_ref * 2; + end + if (r < 1 || r > 16 || f < 1 || f > 64) + compute_divisors = -1; + else + compute_divisors = pack_rfq(r-1, f-1, q); + end + endfunction // compute_divisors + + generate + if (rfq < 0) begin + initial $finish; + end else begin + initial $display("r = %d, f = %d, q = %d", r, f, q); + + SB_PLL40_CORE #(.DIVR(r), .DIVF(f), .DIVQ(q), + .FILTER_RANGE(1), .FEEDBACK_PATH("PHASE_AND_DELAY"), + .DELAY_ADJUSTMENT_MODE_FEEDBACK("FIXED"), + .DELAY_ADJUSTMENT_MODE_RELATIVE("FIXED"), + .FDA_FEEDBACK(0), .FDA_RELATIVE(0), + .SHIFTREG_DIV_MODE(0), .ENABLE_ICEGATE(0), + .PLLOUT_SELECT("SHIFTREG_0deg")) + pll_inst(.REFERENCECLK(clkin), + .PLLOUTGLOBAL(clkout), + .RESETB(1'b1), + .BYPASS(1'b0), + .LOCK(lock)); + end + endgenerate + +endmodule // clkgen diff --git a/zeldin_iceGDROM/fpga/source/tech/ice40/tri_buf.v b/zeldin_iceGDROM/fpga/source/tech/ice40/tri_buf.v new file mode 100644 index 0000000000000000000000000000000000000000..08ab904254514879f5663b33fec8cb00f0ca83fe --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/tech/ice40/tri_buf.v @@ -0,0 +1,22 @@ +module tri_buf( + input out, + output in, + input en, + inout pin + ); + + SB_IO #(.PIN_TYPE(6'b101001), .PULLUP(1'b1)) + tri_buf_impl(.PACKAGE_PIN(pin), + .LATCH_INPUT_VALUE(), + .CLOCK_ENABLE(), + .INPUT_CLK(), + .OUTPUT_CLK(), + .OUTPUT_ENABLE(en), + .D_OUT_0(out), + .D_OUT_1(), + .D_IN_0(in), + .D_IN_1() + ); + +endmodule // tri_buf + diff --git a/zeldin_iceGDROM/fpga/source/top.v b/zeldin_iceGDROM/fpga/source/top.v new file mode 100644 index 0000000000000000000000000000000000000000..a7d8dac0967442faaa07e021fb3866cbd52e0aff --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/top.v @@ -0,0 +1,158 @@ +module top ( + input clk, + input RXD, + output TXD, + inout LED0, + inout LED1, + inout LED2, + inout LED3, + inout LED4, + inout LED5, + inout LED6, + inout LED7, + inout PORTB0, + inout PORTB1, + inout PORTB2, + inout PORTB3, + inout PORTB4, + inout PORTB5, + inout PORTB6, + inout PORTB7, + + output CDCLK, + output SCK, + output SDAT, + output LRCK, + + input G_RST, + inout D0, + inout D1, + inout D2, + inout D3, + inout D4, + inout D5, + inout D6, + inout D7, + inout D8, + inout D9, + inout D10, + inout D11, + inout D12, + inout D13, + inout D14, + inout D15, + inout DMARQ, + input WRn, + input RDn, + inout IORDY, + input DMACKn, + inout INTRQ, + input CS0n, + input CS1n, + input A0, + input A1, + input A2 + ); + + localparam REFCLK_FREQ = 11289600; + localparam CDCLK_FREQ = 33868800; + localparam CPU_FREQ = 39513600; + localparam CLKOUT_FREQ = CPU_FREQ*2; + + wire clkout, lock, lock_cdclk; + wire [15:0] sram_a; + wire [31:0] d_to_ide_or_cdda_or_sdcard, d_from_ide; + wire [15:0] d_from_sdcard; + wire [7:0] d_from_cdda; + wire sram_cs, sram_oe, sram_wait_ide, sram_wait_cdda, sram_wait_sdcard; + wire [3:0] sram_wstrb; + wire ide_irq; + reg ide_irq_sync; + wire cs_gate, sram_cs_ide, sram_cs_cdda, sram_cs_sdcard; + wire sdcard_sck, sdcard_miso, sdcard_mosi; + wire [7:0] sdcard_dma_data; + wire [8:0] sdcard_dma_addr; + wire sdcard_dma_strobe; + wire rv32_reset; + + assign cs_gate = ~clkout_cpu; + assign sram_cs_ide = sram_cs & sram_a[12] & cs_gate; + assign sram_cs_sdcard = sram_cs & ~sram_a[12] & ~sram_a[11] & cs_gate; + assign sram_cs_cdda = sram_cs & ~sram_a[12] & sram_a[11] & cs_gate; + + generate + if(REFCLK_FREQ != CLKOUT_FREQ) begin : use_clkgen + + clkgen #(.INCLOCK_FREQ(REFCLK_FREQ), + .OUTCLOCK_FREQ(CLKOUT_FREQ)) + clkgen_inst(.clkin(clk), .clkout(clkout), .lock(lock)); + + end + else begin : use_refclk + + assign clkout = clk; + assign lock = 1'b1; + + end + endgenerate + + clkgen #(.INCLOCK_FREQ(REFCLK_FREQ), + .OUTCLOCK_FREQ(CDCLK_FREQ)) + clkgen_cdclk_inst(.clkin(clk), .clkout(CDCLK), .lock(lock_cdclk)); + + reg clkout_cpu; + always @(posedge clkout) begin + clkout_cpu <= ~clkout_cpu; + if (~clkout_cpu) + ide_irq_sync <= ide_irq; + end + + ide_interface #(.drv(1'b0), .add_read_ws(0)) + ide_inst(.dd({D15,D14,D13,D12,D11,D10,D9,D8,D7,D6,D5,D4,D3,D2,D1,D0}), + .da({A2,A1,A0}), .cs1fx_(CS0n), .cs3fx_(CS1n), .dasp_(), + .dior_(RDn), .diow_(WRn), .dmack_(DMACKn), .dmarq(DMARQ), + .intrq(INTRQ), .iocs16_(), .iordy(IORDY), .pdiag_(), + .reset_(G_RST), .csel(1'b0), .clk(clkout), .sram_a(sram_a), + .sram_d_in(d_to_ide_or_cdda_or_sdcard), .sram_d_out(d_from_ide), + .sram_cs(sram_cs_ide), .sram_oe(sram_oe), .sram_wstrb(sram_wstrb), + .sram_wait(sram_wait_ide), .cpu_irq(ide_irq), + .sdcard_dma_data(sdcard_dma_data), .sdcard_dma_addr(sdcard_dma_addr), + .sdcard_dma_strobe(sdcard_dma_strobe)); + + cdda_interface #(.CLK_FREQUENCY(CLKOUT_FREQ)) + cdda_inst(.bck(SCK), .sd(SDAT), .lrck(LRCK), + .clk(clkout), .rst(rv32_reset), + .sram_a(sram_a), + .sram_d_in(d_to_ide_or_cdda_or_sdcard), .sram_d_out(d_from_cdda), + .sram_cs(sram_cs_cdda), .sram_oe(sram_oe), .sram_wstrb(sram_wstrb), + .sram_wait(sram_wait_cdda), .sdcard_dma_data(sdcard_dma_data), + .sdcard_dma_addr(sdcard_dma_addr), .sdcard_dma_strobe(sdcard_dma_strobe)); + + sdcard_interface + sdcard_inst(.sclk(sdcard_sck), .mosi(sdcard_mosi), .miso(sdcard_miso), + .clk(clkout), .rst(rv32_reset), + .sram_a(sram_a), .sram_d_in(d_to_ide_or_cdda_or_sdcard[15:0]), + .sram_d_out(d_from_sdcard), .sram_cs(sram_cs_sdcard), + .sram_oe(sram_oe), .sram_wstrb(sram_wstrb[1:0]), .sram_wait(sram_wait_sdcard), + .dma_data(sdcard_dma_data), .dma_addr(sdcard_dma_addr), .dma_strobe(sdcard_dma_strobe)); + + vexriscv_wrapper #(.mem_size(12), + .CLK_FREQUENCY(CPU_FREQ), + .AVR109_BAUD_RATE(115200), +`ifdef PM_INIT + .mem_init(`PM_INIT), +`endif + ) + vexrv_inst(.clk(clkout_cpu), .rst_out(rv32_reset), + .porta({LED7, LED6, LED5, LED4, LED3, LED2, LED1, LED0}), + .portb({PORTB7, PORTB6, PORTB5, PORTB4, PORTB3, PORTB2, PORTB1, PORTB0}), + .sdcard_sck(sdcard_sck), .sdcard_mosi(sdcard_mosi), + .sdcard_miso(sdcard_miso), .rxd(RXD), .txd(TXD), + .extram_a(sram_a), + .extram_d_in(sram_a[12]? d_from_ide : + {16'h0000, (sram_a[11]? {8'h00, d_from_cdda} : d_from_sdcard)}), + .extram_d_out(d_to_ide_or_cdda_or_sdcard), + .extram_cs(sram_cs), .extram_oe(sram_oe), .extram_wstrb(sram_wstrb), + .ext_irq3(ide_irq_sync)); + +endmodule // top diff --git a/zeldin_iceGDROM/fpga/source/vexriscv/core/README.md b/zeldin_iceGDROM/fpga/source/vexriscv/core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bd61bef4c113db5b778f0256221e7f0e05d0a69e --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/vexriscv/core/README.md @@ -0,0 +1,76 @@ +The file VexRiscv.v was generated from the SpinalHDL code in commit +775b336e of the https://github.com/SpinalHDL/VexRiscv repository, +using the following configuration: + + VexRiscvConfig( + plugins = List( + new IBusSimplePlugin( + resetVector = 0l, + cmdForkOnSecondStage = true, + cmdForkPersistence = false, + prediction = NONE, + catchAccessFault = false, + compressedGen = true + ), + new DBusSimplePlugin( + catchAddressMisaligned = false, + catchAccessFault = false, + earlyInjection = true + ), + new CsrPlugin(CsrPluginConfig( + catchIllegalAccess = false, + mvendorid = null, + marchid = null, + mimpid = null, + mhartid = null, + misaExtensionsInit = 66, + misaAccess = CsrAccess.NONE, + mtvecAccess = CsrAccess.NONE, + mtvecInit = 4l, + mepcAccess = CsrAccess.NONE, + mscratchGen = true, + mcauseAccess = CsrAccess.READ_ONLY, + mbadaddrAccess = CsrAccess.NONE, + mcycleAccess = CsrAccess.NONE, + minstretAccess = CsrAccess.NONE, + ecallGen = false, + wfiGenAsWait = false, + ucycleAccess = CsrAccess.NONE, + uinstretAccess = CsrAccess.NONE + )), + new DecoderSimplePlugin( + catchIllegalInstruction = false + ), + new RegFilePlugin( + regFileReadyKind = plugin.SYNC, + rv32e = true, + zeroBoot = false, + x0Init = true + ), + new IntAluPlugin, + new SrcPlugin( + separatedAddSub = false, + executeInsertion = true + ), + new FullBarrelShifterPlugin(earlyInjection = true), + new HazardSimplePlugin( + bypassExecute = true, + bypassMemory = true, + bypassWriteBack = true, + bypassWriteBackBuffer = true, + pessimisticUseSrc = false, + pessimisticWriteRegFile = false, + pessimisticAddressMatch = false + ), + new MulDivIterativePlugin( + genMul = true, + genDiv = true, + mulUnrollFactor = 2, + divUnrollFactor = 2 + ), + new BranchPlugin( + earlyBranch = true, + catchAddressMisaligned = false + ) + ) + ) diff --git a/zeldin_iceGDROM/fpga/source/vexriscv/core/VexRiscv.v b/zeldin_iceGDROM/fpga/source/vexriscv/core/VexRiscv.v new file mode 100644 index 0000000000000000000000000000000000000000..5725a9bb3ff9cf4bb240a2fa0ac7bb9a423ab7ef --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/vexriscv/core/VexRiscv.v @@ -0,0 +1,3949 @@ +// Generator : SpinalHDL v1.4.0 git head : ecb5a80b713566f417ea3ea061f9969e73770a7f +// Date : 12/09/2020, 16:28:00 +// Component : VexRiscv + + +`define AluBitwiseCtrlEnum_defaultEncoding_type [1:0] +`define AluBitwiseCtrlEnum_defaultEncoding_XOR_1 2'b00 +`define AluBitwiseCtrlEnum_defaultEncoding_OR_1 2'b01 +`define AluBitwiseCtrlEnum_defaultEncoding_AND_1 2'b10 + +`define Src2CtrlEnum_defaultEncoding_type [1:0] +`define Src2CtrlEnum_defaultEncoding_RS 2'b00 +`define Src2CtrlEnum_defaultEncoding_IMI 2'b01 +`define Src2CtrlEnum_defaultEncoding_IMS 2'b10 +`define Src2CtrlEnum_defaultEncoding_PC 2'b11 + +`define ShiftCtrlEnum_defaultEncoding_type [1:0] +`define ShiftCtrlEnum_defaultEncoding_DISABLE_1 2'b00 +`define ShiftCtrlEnum_defaultEncoding_SLL_1 2'b01 +`define ShiftCtrlEnum_defaultEncoding_SRL_1 2'b10 +`define ShiftCtrlEnum_defaultEncoding_SRA_1 2'b11 + +`define Src1CtrlEnum_defaultEncoding_type [1:0] +`define Src1CtrlEnum_defaultEncoding_RS 2'b00 +`define Src1CtrlEnum_defaultEncoding_IMU 2'b01 +`define Src1CtrlEnum_defaultEncoding_PC_INCREMENT 2'b10 +`define Src1CtrlEnum_defaultEncoding_URS1 2'b11 + +`define BranchCtrlEnum_defaultEncoding_type [1:0] +`define BranchCtrlEnum_defaultEncoding_INC 2'b00 +`define BranchCtrlEnum_defaultEncoding_B 2'b01 +`define BranchCtrlEnum_defaultEncoding_JAL 2'b10 +`define BranchCtrlEnum_defaultEncoding_JALR 2'b11 + +`define AluCtrlEnum_defaultEncoding_type [1:0] +`define AluCtrlEnum_defaultEncoding_ADD_SUB 2'b00 +`define AluCtrlEnum_defaultEncoding_SLT_SLTU 2'b01 +`define AluCtrlEnum_defaultEncoding_BITWISE 2'b10 + +`define EnvCtrlEnum_defaultEncoding_type [0:0] +`define EnvCtrlEnum_defaultEncoding_NONE 1'b0 +`define EnvCtrlEnum_defaultEncoding_XRET 1'b1 + + +module StreamFifoLowLatency ( + input io_push_valid, + output io_push_ready, + input io_push_payload_error, + input [31:0] io_push_payload_inst, + output reg io_pop_valid, + input io_pop_ready, + output reg io_pop_payload_error, + output reg [31:0] io_pop_payload_inst, + input io_flush, + output [0:0] io_occupancy, + input clk, + input reset +); + wire _zz_4_; + wire [0:0] _zz_5_; + reg _zz_1_; + reg pushPtr_willIncrement; + reg pushPtr_willClear; + wire pushPtr_willOverflowIfInc; + wire pushPtr_willOverflow; + reg popPtr_willIncrement; + reg popPtr_willClear; + wire popPtr_willOverflowIfInc; + wire popPtr_willOverflow; + wire ptrMatch; + reg risingOccupancy; + wire empty; + wire full; + wire pushing; + wire popping; + wire [32:0] _zz_2_; + reg [32:0] _zz_3_; + + assign _zz_4_ = (! empty); + assign _zz_5_ = _zz_2_[0 : 0]; + always @ (*) begin + _zz_1_ = 1'b0; + if(pushing)begin + _zz_1_ = 1'b1; + end + end + + always @ (*) begin + pushPtr_willIncrement = 1'b0; + if(pushing)begin + pushPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + pushPtr_willClear = 1'b0; + if(io_flush)begin + pushPtr_willClear = 1'b1; + end + end + + assign pushPtr_willOverflowIfInc = 1'b1; + assign pushPtr_willOverflow = (pushPtr_willOverflowIfInc && pushPtr_willIncrement); + always @ (*) begin + popPtr_willIncrement = 1'b0; + if(popping)begin + popPtr_willIncrement = 1'b1; + end + end + + always @ (*) begin + popPtr_willClear = 1'b0; + if(io_flush)begin + popPtr_willClear = 1'b1; + end + end + + assign popPtr_willOverflowIfInc = 1'b1; + assign popPtr_willOverflow = (popPtr_willOverflowIfInc && popPtr_willIncrement); + assign ptrMatch = 1'b1; + assign empty = (ptrMatch && (! risingOccupancy)); + assign full = (ptrMatch && risingOccupancy); + assign pushing = (io_push_valid && io_push_ready); + assign popping = (io_pop_valid && io_pop_ready); + assign io_push_ready = (! full); + always @ (*) begin + if(_zz_4_)begin + io_pop_valid = 1'b1; + end else begin + io_pop_valid = io_push_valid; + end + end + + assign _zz_2_ = _zz_3_; + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_error = _zz_5_[0]; + end else begin + io_pop_payload_error = io_push_payload_error; + end + end + + always @ (*) begin + if(_zz_4_)begin + io_pop_payload_inst = _zz_2_[32 : 1]; + end else begin + io_pop_payload_inst = io_push_payload_inst; + end + end + + assign io_occupancy = (risingOccupancy && ptrMatch); + always @ (posedge clk or posedge reset) begin + if (reset) begin + risingOccupancy <= 1'b0; + end else begin + if((pushing != popping))begin + risingOccupancy <= pushing; + end + if(io_flush)begin + risingOccupancy <= 1'b0; + end + end + end + + always @ (posedge clk) begin + if(_zz_1_)begin + _zz_3_ <= {io_push_payload_inst,io_push_payload_error}; + end + end + + +endmodule + +module VexRiscv ( + output iBus_cmd_valid, + input iBus_cmd_ready, + output [31:0] iBus_cmd_payload_pc, + input iBus_rsp_valid, + input iBus_rsp_payload_error, + input [31:0] iBus_rsp_payload_inst, + input timerInterrupt, + input externalInterrupt, + input softwareInterrupt, + output dBus_cmd_valid, + input dBus_cmd_ready, + output dBus_cmd_payload_wr, + output [31:0] dBus_cmd_payload_address, + output [31:0] dBus_cmd_payload_data, + output [1:0] dBus_cmd_payload_size, + input dBus_rsp_ready, + input dBus_rsp_error, + input [31:0] dBus_rsp_data, + input clk, + input reset +); + wire _zz_159_; + wire _zz_160_; + reg [31:0] _zz_161_; + reg [31:0] _zz_162_; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + wire [0:0] IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy; + wire _zz_163_; + wire _zz_164_; + wire _zz_165_; + wire _zz_166_; + wire _zz_167_; + wire _zz_168_; + wire _zz_169_; + wire _zz_170_; + wire _zz_171_; + wire _zz_172_; + wire [1:0] _zz_173_; + wire _zz_174_; + wire _zz_175_; + wire _zz_176_; + wire _zz_177_; + wire _zz_178_; + wire _zz_179_; + wire _zz_180_; + wire _zz_181_; + wire _zz_182_; + wire _zz_183_; + wire _zz_184_; + wire _zz_185_; + wire _zz_186_; + wire _zz_187_; + wire [4:0] _zz_188_; + wire [1:0] _zz_189_; + wire [1:0] _zz_190_; + wire [1:0] _zz_191_; + wire _zz_192_; + wire [0:0] _zz_193_; + wire [2:0] _zz_194_; + wire [31:0] _zz_195_; + wire [0:0] _zz_196_; + wire [0:0] _zz_197_; + wire [0:0] _zz_198_; + wire [0:0] _zz_199_; + wire [0:0] _zz_200_; + wire [0:0] _zz_201_; + wire [0:0] _zz_202_; + wire [0:0] _zz_203_; + wire [0:0] _zz_204_; + wire [0:0] _zz_205_; + wire [0:0] _zz_206_; + wire [32:0] _zz_207_; + wire [31:0] _zz_208_; + wire [32:0] _zz_209_; + wire [0:0] _zz_210_; + wire [0:0] _zz_211_; + wire [0:0] _zz_212_; + wire [1:0] _zz_213_; + wire [1:0] _zz_214_; + wire [2:0] _zz_215_; + wire [31:0] _zz_216_; + wire [2:0] _zz_217_; + wire [31:0] _zz_218_; + wire [31:0] _zz_219_; + wire [11:0] _zz_220_; + wire [11:0] _zz_221_; + wire [2:0] _zz_222_; + wire [0:0] _zz_223_; + wire [2:0] _zz_224_; + wire [0:0] _zz_225_; + wire [2:0] _zz_226_; + wire [0:0] _zz_227_; + wire [2:0] _zz_228_; + wire [0:0] _zz_229_; + wire [2:0] _zz_230_; + wire [4:0] _zz_231_; + wire [11:0] _zz_232_; + wire [11:0] _zz_233_; + wire [31:0] _zz_234_; + wire [31:0] _zz_235_; + wire [31:0] _zz_236_; + wire [31:0] _zz_237_; + wire [31:0] _zz_238_; + wire [31:0] _zz_239_; + wire [31:0] _zz_240_; + wire [0:0] _zz_241_; + wire [4:0] _zz_242_; + wire [34:0] _zz_243_; + wire [34:0] _zz_244_; + wire [32:0] _zz_245_; + wire [34:0] _zz_246_; + wire [33:0] _zz_247_; + wire [34:0] _zz_248_; + wire [33:0] _zz_249_; + wire [32:0] _zz_250_; + wire [34:0] _zz_251_; + wire [32:0] _zz_252_; + wire [0:0] _zz_253_; + wire [4:0] _zz_254_; + wire [32:0] _zz_255_; + wire [31:0] _zz_256_; + wire [31:0] _zz_257_; + wire [32:0] _zz_258_; + wire [32:0] _zz_259_; + wire [31:0] _zz_260_; + wire [31:0] _zz_261_; + wire [32:0] _zz_262_; + wire [32:0] _zz_263_; + wire [32:0] _zz_264_; + wire [32:0] _zz_265_; + wire [0:0] _zz_266_; + wire [32:0] _zz_267_; + wire [0:0] _zz_268_; + wire [32:0] _zz_269_; + wire [0:0] _zz_270_; + wire [31:0] _zz_271_; + wire [19:0] _zz_272_; + wire [11:0] _zz_273_; + wire [11:0] _zz_274_; + wire [0:0] _zz_275_; + wire [0:0] _zz_276_; + wire [0:0] _zz_277_; + wire [0:0] _zz_278_; + wire [0:0] _zz_279_; + wire [0:0] _zz_280_; + wire _zz_281_; + wire _zz_282_; + wire _zz_283_; + wire _zz_284_; + wire [6:0] _zz_285_; + wire [4:0] _zz_286_; + wire _zz_287_; + wire [4:0] _zz_288_; + wire [31:0] _zz_289_; + wire [31:0] _zz_290_; + wire _zz_291_; + wire [0:0] _zz_292_; + wire [0:0] _zz_293_; + wire _zz_294_; + wire [0:0] _zz_295_; + wire [0:0] _zz_296_; + wire [1:0] _zz_297_; + wire [1:0] _zz_298_; + wire _zz_299_; + wire [0:0] _zz_300_; + wire [22:0] _zz_301_; + wire [31:0] _zz_302_; + wire [31:0] _zz_303_; + wire [31:0] _zz_304_; + wire [31:0] _zz_305_; + wire [31:0] _zz_306_; + wire [31:0] _zz_307_; + wire [31:0] _zz_308_; + wire [31:0] _zz_309_; + wire _zz_310_; + wire [0:0] _zz_311_; + wire [0:0] _zz_312_; + wire _zz_313_; + wire [0:0] _zz_314_; + wire [19:0] _zz_315_; + wire _zz_316_; + wire _zz_317_; + wire _zz_318_; + wire _zz_319_; + wire _zz_320_; + wire [0:0] _zz_321_; + wire [0:0] _zz_322_; + wire _zz_323_; + wire [0:0] _zz_324_; + wire [15:0] _zz_325_; + wire [31:0] _zz_326_; + wire [0:0] _zz_327_; + wire [3:0] _zz_328_; + wire [0:0] _zz_329_; + wire [0:0] _zz_330_; + wire [1:0] _zz_331_; + wire [1:0] _zz_332_; + wire _zz_333_; + wire [0:0] _zz_334_; + wire [12:0] _zz_335_; + wire [31:0] _zz_336_; + wire [31:0] _zz_337_; + wire [31:0] _zz_338_; + wire _zz_339_; + wire [0:0] _zz_340_; + wire [0:0] _zz_341_; + wire [31:0] _zz_342_; + wire [31:0] _zz_343_; + wire [31:0] _zz_344_; + wire [31:0] _zz_345_; + wire [31:0] _zz_346_; + wire [31:0] _zz_347_; + wire [0:0] _zz_348_; + wire [1:0] _zz_349_; + wire [1:0] _zz_350_; + wire [1:0] _zz_351_; + wire _zz_352_; + wire [0:0] _zz_353_; + wire [9:0] _zz_354_; + wire [31:0] _zz_355_; + wire [31:0] _zz_356_; + wire [31:0] _zz_357_; + wire [31:0] _zz_358_; + wire [31:0] _zz_359_; + wire [31:0] _zz_360_; + wire [31:0] _zz_361_; + wire _zz_362_; + wire _zz_363_; + wire _zz_364_; + wire [0:0] _zz_365_; + wire [0:0] _zz_366_; + wire [0:0] _zz_367_; + wire [0:0] _zz_368_; + wire _zz_369_; + wire [0:0] _zz_370_; + wire [7:0] _zz_371_; + wire [31:0] _zz_372_; + wire [31:0] _zz_373_; + wire _zz_374_; + wire _zz_375_; + wire [0:0] _zz_376_; + wire [1:0] _zz_377_; + wire [1:0] _zz_378_; + wire [1:0] _zz_379_; + wire _zz_380_; + wire [0:0] _zz_381_; + wire [4:0] _zz_382_; + wire [31:0] _zz_383_; + wire [31:0] _zz_384_; + wire [31:0] _zz_385_; + wire [31:0] _zz_386_; + wire [31:0] _zz_387_; + wire [31:0] _zz_388_; + wire [31:0] _zz_389_; + wire [31:0] _zz_390_; + wire [31:0] _zz_391_; + wire _zz_392_; + wire [2:0] _zz_393_; + wire [2:0] _zz_394_; + wire _zz_395_; + wire [0:0] _zz_396_; + wire [1:0] _zz_397_; + wire [31:0] _zz_398_; + wire _zz_399_; + wire _zz_400_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type decode_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_1_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_2_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_3_; + wire decode_MEMORY_ENABLE; + wire `Src2CtrlEnum_defaultEncoding_type decode_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_4_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_5_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_6_; + wire [31:0] writeBack_FORMAL_PC_NEXT; + wire [31:0] memory_FORMAL_PC_NEXT; + wire [31:0] execute_FORMAL_PC_NEXT; + wire [31:0] decode_FORMAL_PC_NEXT; + wire decode_CSR_READ_OPCODE; + wire decode_CSR_WRITE_OPCODE; + wire `ShiftCtrlEnum_defaultEncoding_type decode_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_7_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_8_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_9_; + wire decode_IS_MUL; + wire decode_MEMORY_STORE; + wire `Src1CtrlEnum_defaultEncoding_type decode_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_10_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_11_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_12_; + wire decode_IS_CSR; + wire decode_BYPASSABLE_EXECUTE_STAGE; + wire [31:0] writeBack_REGFILE_WRITE_DATA; + wire [31:0] memory_REGFILE_WRITE_DATA; + wire [31:0] execute_REGFILE_WRITE_DATA; + wire decode_IS_RS1_SIGNED; + wire `BranchCtrlEnum_defaultEncoding_type decode_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_13_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_14_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_15_; + wire execute_BYPASSABLE_MEMORY_STAGE; + wire decode_BYPASSABLE_MEMORY_STAGE; + wire [31:0] memory_PC; + wire `AluCtrlEnum_defaultEncoding_type decode_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_16_; + wire `AluCtrlEnum_defaultEncoding_type _zz_17_; + wire `AluCtrlEnum_defaultEncoding_type _zz_18_; + wire decode_SRC2_FORCE_ZERO; + wire `EnvCtrlEnum_defaultEncoding_type _zz_19_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_20_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_21_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_22_; + wire `EnvCtrlEnum_defaultEncoding_type decode_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_23_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_24_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_25_; + wire decode_SRC_LESS_UNSIGNED; + wire decode_IS_RS2_SIGNED; + wire decode_IS_DIV; + wire [1:0] execute_MEMORY_ADDRESS_LOW; + wire [31:0] execute_BRANCH_CALC; + wire execute_BRANCH_DO; + wire [31:0] execute_PC; + wire `BranchCtrlEnum_defaultEncoding_type execute_BRANCH_CTRL; + wire `BranchCtrlEnum_defaultEncoding_type _zz_26_; + wire execute_IS_RS1_SIGNED; + wire [31:0] execute_RS1; + wire execute_IS_DIV; + wire execute_IS_MUL; + wire execute_IS_RS2_SIGNED; + wire memory_IS_DIV; + wire memory_IS_MUL; + wire decode_RS2_USE; + wire decode_RS1_USE; + wire execute_REGFILE_WRITE_VALID; + wire execute_BYPASSABLE_EXECUTE_STAGE; + wire memory_REGFILE_WRITE_VALID; + wire memory_BYPASSABLE_MEMORY_STAGE; + wire writeBack_REGFILE_WRITE_VALID; + reg [31:0] decode_RS2; + reg [31:0] decode_RS1; + wire [31:0] execute_SHIFT_RIGHT; + wire `ShiftCtrlEnum_defaultEncoding_type execute_SHIFT_CTRL; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_27_; + wire execute_SRC_LESS_UNSIGNED; + wire execute_SRC2_FORCE_ZERO; + wire execute_SRC_USE_SUB_LESS; + wire [31:0] _zz_28_; + wire `Src2CtrlEnum_defaultEncoding_type execute_SRC2_CTRL; + wire `Src2CtrlEnum_defaultEncoding_type _zz_29_; + wire execute_IS_RVC; + wire `Src1CtrlEnum_defaultEncoding_type execute_SRC1_CTRL; + wire `Src1CtrlEnum_defaultEncoding_type _zz_30_; + wire decode_SRC_USE_SUB_LESS; + wire decode_SRC_ADD_ZERO; + wire [31:0] execute_SRC_ADD_SUB; + wire execute_SRC_LESS; + wire `AluCtrlEnum_defaultEncoding_type execute_ALU_CTRL; + wire `AluCtrlEnum_defaultEncoding_type _zz_31_; + wire [31:0] execute_SRC2; + wire `AluBitwiseCtrlEnum_defaultEncoding_type execute_ALU_BITWISE_CTRL; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_32_; + wire [31:0] _zz_33_; + wire [31:0] _zz_34_; + wire _zz_35_; + reg _zz_36_; + wire [31:0] decode_INSTRUCTION_ANTICIPATED; + reg decode_REGFILE_WRITE_VALID; + wire `Src2CtrlEnum_defaultEncoding_type _zz_37_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_38_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_39_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_40_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_41_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_42_; + wire `AluCtrlEnum_defaultEncoding_type _zz_43_; + reg [31:0] _zz_44_; + wire [31:0] execute_SRC1; + wire execute_CSR_READ_OPCODE; + wire execute_CSR_WRITE_OPCODE; + wire execute_IS_CSR; + wire `EnvCtrlEnum_defaultEncoding_type memory_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_45_; + wire `EnvCtrlEnum_defaultEncoding_type execute_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_46_; + wire `EnvCtrlEnum_defaultEncoding_type writeBack_ENV_CTRL; + wire `EnvCtrlEnum_defaultEncoding_type _zz_47_; + reg [31:0] _zz_48_; + wire [31:0] memory_INSTRUCTION; + wire [1:0] memory_MEMORY_ADDRESS_LOW; + wire [31:0] memory_MEMORY_READ_DATA; + wire memory_MEMORY_STORE; + wire memory_MEMORY_ENABLE; + wire [31:0] execute_SRC_ADD; + wire [31:0] execute_RS2; + wire [31:0] execute_INSTRUCTION; + wire execute_MEMORY_STORE; + wire execute_MEMORY_ENABLE; + wire execute_ALIGNEMENT_FAULT; + reg [31:0] _zz_49_; + wire [31:0] decode_PC; + wire [31:0] decode_INSTRUCTION; + wire decode_IS_RVC; + wire [31:0] writeBack_PC; + wire [31:0] writeBack_INSTRUCTION; + wire decode_arbitration_haltItself; + reg decode_arbitration_haltByOther; + reg decode_arbitration_removeIt; + wire decode_arbitration_flushIt; + wire decode_arbitration_flushNext; + wire decode_arbitration_isValid; + wire decode_arbitration_isStuck; + wire decode_arbitration_isStuckByOthers; + wire decode_arbitration_isFlushed; + wire decode_arbitration_isMoving; + wire decode_arbitration_isFiring; + reg execute_arbitration_haltItself; + wire execute_arbitration_haltByOther; + reg execute_arbitration_removeIt; + wire execute_arbitration_flushIt; + reg execute_arbitration_flushNext; + reg execute_arbitration_isValid; + wire execute_arbitration_isStuck; + wire execute_arbitration_isStuckByOthers; + wire execute_arbitration_isFlushed; + wire execute_arbitration_isMoving; + wire execute_arbitration_isFiring; + reg memory_arbitration_haltItself; + wire memory_arbitration_haltByOther; + reg memory_arbitration_removeIt; + wire memory_arbitration_flushIt; + wire memory_arbitration_flushNext; + reg memory_arbitration_isValid; + wire memory_arbitration_isStuck; + wire memory_arbitration_isStuckByOthers; + wire memory_arbitration_isFlushed; + wire memory_arbitration_isMoving; + wire memory_arbitration_isFiring; + wire writeBack_arbitration_haltItself; + wire writeBack_arbitration_haltByOther; + reg writeBack_arbitration_removeIt; + wire writeBack_arbitration_flushIt; + reg writeBack_arbitration_flushNext; + reg writeBack_arbitration_isValid; + wire writeBack_arbitration_isStuck; + wire writeBack_arbitration_isStuckByOthers; + wire writeBack_arbitration_isFlushed; + wire writeBack_arbitration_isMoving; + wire writeBack_arbitration_isFiring; + wire [31:0] lastStageInstruction /* verilator public */ ; + wire [31:0] lastStagePc /* verilator public */ ; + wire lastStageIsValid /* verilator public */ ; + wire lastStageIsFiring /* verilator public */ ; + reg IBusSimplePlugin_fetcherHalt; + reg IBusSimplePlugin_incomingInstruction; + wire IBusSimplePlugin_pcValids_0; + wire IBusSimplePlugin_pcValids_1; + wire IBusSimplePlugin_pcValids_2; + wire IBusSimplePlugin_pcValids_3; + wire CsrPlugin_inWfi /* verilator public */ ; + wire CsrPlugin_thirdPartyWake; + reg CsrPlugin_jumpInterface_valid; + reg [31:0] CsrPlugin_jumpInterface_payload; + wire CsrPlugin_exceptionPendings_0; + wire CsrPlugin_exceptionPendings_1; + wire CsrPlugin_exceptionPendings_2; + wire CsrPlugin_exceptionPendings_3; + wire contextSwitching; + reg [1:0] CsrPlugin_privilege; + wire CsrPlugin_forceMachineWire; + wire CsrPlugin_allowInterrupts; + wire CsrPlugin_allowException; + wire BranchPlugin_jumpInterface_valid; + wire [31:0] BranchPlugin_jumpInterface_payload; + wire IBusSimplePlugin_externalFlush; + wire IBusSimplePlugin_jump_pcLoad_valid; + wire [31:0] IBusSimplePlugin_jump_pcLoad_payload; + wire [1:0] _zz_50_; + wire IBusSimplePlugin_fetchPc_output_valid; + wire IBusSimplePlugin_fetchPc_output_ready; + wire [31:0] IBusSimplePlugin_fetchPc_output_payload; + reg [31:0] IBusSimplePlugin_fetchPc_pcReg /* verilator public */ ; + reg IBusSimplePlugin_fetchPc_correction; + reg IBusSimplePlugin_fetchPc_correctionReg; + wire IBusSimplePlugin_fetchPc_corrected; + reg IBusSimplePlugin_fetchPc_pcRegPropagate; + reg IBusSimplePlugin_fetchPc_booted; + reg IBusSimplePlugin_fetchPc_inc; + reg [31:0] IBusSimplePlugin_fetchPc_pc; + reg IBusSimplePlugin_fetchPc_flushed; + reg IBusSimplePlugin_decodePc_flushed; + reg [31:0] IBusSimplePlugin_decodePc_pcReg /* verilator public */ ; + wire [31:0] IBusSimplePlugin_decodePc_pcPlus; + wire IBusSimplePlugin_decodePc_injectedDecode; + wire IBusSimplePlugin_iBusRsp_redoFetch; + wire IBusSimplePlugin_iBusRsp_stages_0_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_0_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_0_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_0_output_payload; + wire IBusSimplePlugin_iBusRsp_stages_0_halt; + wire IBusSimplePlugin_iBusRsp_stages_1_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_1_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_1_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_1_output_payload; + reg IBusSimplePlugin_iBusRsp_stages_1_halt; + wire IBusSimplePlugin_iBusRsp_stages_2_input_valid; + wire IBusSimplePlugin_iBusRsp_stages_2_input_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_2_input_payload; + wire IBusSimplePlugin_iBusRsp_stages_2_output_valid; + wire IBusSimplePlugin_iBusRsp_stages_2_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_stages_2_output_payload; + wire IBusSimplePlugin_iBusRsp_stages_2_halt; + wire _zz_51_; + wire _zz_52_; + wire _zz_53_; + wire IBusSimplePlugin_iBusRsp_flush; + wire _zz_54_; + wire _zz_55_; + reg _zz_56_; + wire _zz_57_; + reg _zz_58_; + reg [31:0] _zz_59_; + reg IBusSimplePlugin_iBusRsp_readyForError; + wire IBusSimplePlugin_iBusRsp_output_valid; + wire IBusSimplePlugin_iBusRsp_output_ready; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_pc; + wire IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + wire [31:0] IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + wire IBusSimplePlugin_iBusRsp_output_payload_isRvc; + wire IBusSimplePlugin_decompressor_input_valid; + wire IBusSimplePlugin_decompressor_input_ready; + wire [31:0] IBusSimplePlugin_decompressor_input_payload_pc; + wire IBusSimplePlugin_decompressor_input_payload_rsp_error; + wire [31:0] IBusSimplePlugin_decompressor_input_payload_rsp_inst; + wire IBusSimplePlugin_decompressor_input_payload_isRvc; + wire IBusSimplePlugin_decompressor_output_valid; + wire IBusSimplePlugin_decompressor_output_ready; + wire [31:0] IBusSimplePlugin_decompressor_output_payload_pc; + wire IBusSimplePlugin_decompressor_output_payload_rsp_error; + wire [31:0] IBusSimplePlugin_decompressor_output_payload_rsp_inst; + wire IBusSimplePlugin_decompressor_output_payload_isRvc; + wire IBusSimplePlugin_decompressor_flushNext; + wire IBusSimplePlugin_decompressor_consumeCurrent; + reg IBusSimplePlugin_decompressor_bufferValid; + reg [15:0] IBusSimplePlugin_decompressor_bufferData; + wire IBusSimplePlugin_decompressor_isInputLowRvc; + wire IBusSimplePlugin_decompressor_isInputHighRvc; + reg IBusSimplePlugin_decompressor_throw2BytesReg; + wire IBusSimplePlugin_decompressor_throw2Bytes; + wire IBusSimplePlugin_decompressor_unaligned; + wire [31:0] IBusSimplePlugin_decompressor_raw; + wire IBusSimplePlugin_decompressor_isRvc; + wire [15:0] _zz_60_; + reg [31:0] IBusSimplePlugin_decompressor_decompressed; + wire [4:0] _zz_61_; + wire [4:0] _zz_62_; + wire [11:0] _zz_63_; + wire _zz_64_; + reg [11:0] _zz_65_; + wire _zz_66_; + reg [9:0] _zz_67_; + wire [20:0] _zz_68_; + wire _zz_69_; + reg [14:0] _zz_70_; + wire _zz_71_; + reg [2:0] _zz_72_; + wire _zz_73_; + reg [9:0] _zz_74_; + wire [20:0] _zz_75_; + wire _zz_76_; + reg [4:0] _zz_77_; + wire [12:0] _zz_78_; + wire [4:0] _zz_79_; + wire [4:0] _zz_80_; + wire [4:0] _zz_81_; + wire _zz_82_; + reg [2:0] _zz_83_; + reg [2:0] _zz_84_; + wire _zz_85_; + reg [6:0] _zz_86_; + wire IBusSimplePlugin_decompressor_bufferFill; + wire IBusSimplePlugin_injector_decodeInput_valid; + wire IBusSimplePlugin_injector_decodeInput_ready; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_pc; + wire IBusSimplePlugin_injector_decodeInput_payload_rsp_error; + wire [31:0] IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + wire IBusSimplePlugin_injector_decodeInput_payload_isRvc; + reg _zz_87_; + reg [31:0] _zz_88_; + reg _zz_89_; + reg [31:0] _zz_90_; + reg _zz_91_; + reg IBusSimplePlugin_injector_nextPcCalc_valids_0; + reg IBusSimplePlugin_injector_nextPcCalc_valids_1; + reg IBusSimplePlugin_injector_nextPcCalc_valids_2; + reg IBusSimplePlugin_injector_nextPcCalc_valids_3; + reg [31:0] IBusSimplePlugin_injector_formal_rawInDecode; + wire IBusSimplePlugin_cmd_valid; + wire IBusSimplePlugin_cmd_ready; + wire [31:0] IBusSimplePlugin_cmd_payload_pc; + wire IBusSimplePlugin_pending_inc; + wire IBusSimplePlugin_pending_dec; + reg [2:0] IBusSimplePlugin_pending_value; + wire [2:0] IBusSimplePlugin_pending_next; + wire IBusSimplePlugin_cmdFork_canEmit; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_valid; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_ready; + wire IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + wire [31:0] IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + reg [2:0] IBusSimplePlugin_rspJoin_rspBuffer_discardCounter; + wire IBusSimplePlugin_rspJoin_rspBuffer_flush; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_pc; + reg IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + wire IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + wire IBusSimplePlugin_rspJoin_join_valid; + wire IBusSimplePlugin_rspJoin_join_ready; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_pc; + wire IBusSimplePlugin_rspJoin_join_payload_rsp_error; + wire [31:0] IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + wire IBusSimplePlugin_rspJoin_join_payload_isRvc; + wire IBusSimplePlugin_rspJoin_exceptionDetected; + wire _zz_92_; + wire _zz_93_; + reg execute_DBusSimplePlugin_skipCmd; + reg [31:0] _zz_94_; + reg [3:0] _zz_95_; + wire [3:0] execute_DBusSimplePlugin_formalMask; + reg [31:0] memory_DBusSimplePlugin_rspShifted; + wire _zz_96_; + reg [31:0] _zz_97_; + wire _zz_98_; + reg [31:0] _zz_99_; + reg [31:0] memory_DBusSimplePlugin_rspFormated; + wire [1:0] CsrPlugin_misa_base; + wire [25:0] CsrPlugin_misa_extensions; + wire [1:0] CsrPlugin_mtvec_mode; + wire [29:0] CsrPlugin_mtvec_base; + reg [31:0] CsrPlugin_mepc; + reg CsrPlugin_mstatus_MIE; + reg CsrPlugin_mstatus_MPIE; + reg [1:0] CsrPlugin_mstatus_MPP; + reg CsrPlugin_mip_MEIP; + reg CsrPlugin_mip_MTIP; + reg CsrPlugin_mip_MSIP; + reg CsrPlugin_mie_MEIE; + reg CsrPlugin_mie_MTIE; + reg CsrPlugin_mie_MSIE; + reg [31:0] CsrPlugin_mscratch; + reg CsrPlugin_mcause_interrupt; + reg [3:0] CsrPlugin_mcause_exceptionCode; + reg [31:0] CsrPlugin_mtval; + reg [63:0] CsrPlugin_mcycle = 64'b0000000000000000000000000000000000000000000000000000000000000000; + reg [63:0] CsrPlugin_minstret = 64'b0000000000000000000000000000000000000000000000000000000000000000; + wire _zz_100_; + wire _zz_101_; + wire _zz_102_; + reg CsrPlugin_interrupt_valid; + reg [3:0] CsrPlugin_interrupt_code /* verilator public */ ; + reg [1:0] CsrPlugin_interrupt_targetPrivilege; + wire CsrPlugin_exception; + wire CsrPlugin_lastStageWasWfi; + reg CsrPlugin_pipelineLiberator_pcValids_0; + reg CsrPlugin_pipelineLiberator_pcValids_1; + reg CsrPlugin_pipelineLiberator_pcValids_2; + wire CsrPlugin_pipelineLiberator_active; + reg CsrPlugin_pipelineLiberator_done; + wire CsrPlugin_interruptJump /* verilator public */ ; + reg CsrPlugin_hadException; + wire [1:0] CsrPlugin_targetPrivilege; + wire [3:0] CsrPlugin_trapCause; + reg [1:0] CsrPlugin_xtvec_mode; + reg [29:0] CsrPlugin_xtvec_base; + reg execute_CsrPlugin_wfiWake; + wire execute_CsrPlugin_blockedBySideEffects; + reg execute_CsrPlugin_illegalAccess; + reg execute_CsrPlugin_illegalInstruction; + wire [31:0] execute_CsrPlugin_readData; + wire execute_CsrPlugin_writeInstruction; + wire execute_CsrPlugin_readInstruction; + wire execute_CsrPlugin_writeEnable; + wire execute_CsrPlugin_readEnable; + wire [31:0] execute_CsrPlugin_readToWriteData; + reg [31:0] execute_CsrPlugin_writeData; + wire [11:0] execute_CsrPlugin_csrAddress; + wire [28:0] _zz_103_; + wire _zz_104_; + wire _zz_105_; + wire _zz_106_; + wire _zz_107_; + wire _zz_108_; + wire _zz_109_; + wire _zz_110_; + wire `AluCtrlEnum_defaultEncoding_type _zz_111_; + wire `ShiftCtrlEnum_defaultEncoding_type _zz_112_; + wire `EnvCtrlEnum_defaultEncoding_type _zz_113_; + wire `Src1CtrlEnum_defaultEncoding_type _zz_114_; + wire `BranchCtrlEnum_defaultEncoding_type _zz_115_; + wire `AluBitwiseCtrlEnum_defaultEncoding_type _zz_116_; + wire `Src2CtrlEnum_defaultEncoding_type _zz_117_; + wire [3:0] decode_RegFilePlugin_regFileReadAddress1; + wire [3:0] decode_RegFilePlugin_regFileReadAddress2; + wire [31:0] decode_RegFilePlugin_rs1Data; + wire [31:0] decode_RegFilePlugin_rs2Data; + reg lastStageRegFileWrite_valid /* verilator public */ ; + wire [3:0] lastStageRegFileWrite_payload_address /* verilator public */ ; + wire [31:0] lastStageRegFileWrite_payload_data /* verilator public */ ; + reg _zz_118_; + reg [31:0] execute_IntAluPlugin_bitwise; + reg [31:0] _zz_119_; + reg [31:0] _zz_120_; + wire _zz_121_; + reg [19:0] _zz_122_; + wire _zz_123_; + reg [19:0] _zz_124_; + reg [31:0] _zz_125_; + reg [31:0] execute_SrcPlugin_addSub; + wire execute_SrcPlugin_less; + wire [4:0] execute_FullBarrelShifterPlugin_amplitude; + reg [31:0] _zz_126_; + wire [31:0] execute_FullBarrelShifterPlugin_reversed; + reg [31:0] _zz_127_; + reg _zz_128_; + reg _zz_129_; + reg _zz_130_; + reg [4:0] _zz_131_; + reg [31:0] _zz_132_; + wire _zz_133_; + wire _zz_134_; + wire _zz_135_; + wire _zz_136_; + wire _zz_137_; + wire _zz_138_; + reg [32:0] memory_MulDivIterativePlugin_rs1; + reg [31:0] memory_MulDivIterativePlugin_rs2; + reg [64:0] memory_MulDivIterativePlugin_accumulator; + wire memory_MulDivIterativePlugin_frontendOk; + reg memory_MulDivIterativePlugin_mul_counter_willIncrement; + reg memory_MulDivIterativePlugin_mul_counter_willClear; + reg [4:0] memory_MulDivIterativePlugin_mul_counter_valueNext; + reg [4:0] memory_MulDivIterativePlugin_mul_counter_value; + wire memory_MulDivIterativePlugin_mul_counter_willOverflowIfInc; + wire memory_MulDivIterativePlugin_mul_counter_willOverflow; + reg memory_MulDivIterativePlugin_div_needRevert; + reg memory_MulDivIterativePlugin_div_counter_willIncrement; + reg memory_MulDivIterativePlugin_div_counter_willClear; + reg [4:0] memory_MulDivIterativePlugin_div_counter_valueNext; + reg [4:0] memory_MulDivIterativePlugin_div_counter_value; + wire memory_MulDivIterativePlugin_div_counter_willOverflowIfInc; + wire memory_MulDivIterativePlugin_div_counter_willOverflow; + reg memory_MulDivIterativePlugin_div_done; + reg [31:0] memory_MulDivIterativePlugin_div_result; + wire [31:0] _zz_139_; + wire [32:0] memory_MulDivIterativePlugin_div_stage_0_remainderShifted; + wire [32:0] memory_MulDivIterativePlugin_div_stage_0_remainderMinusDenominator; + wire [31:0] memory_MulDivIterativePlugin_div_stage_0_outRemainder; + wire [31:0] memory_MulDivIterativePlugin_div_stage_0_outNumerator; + wire [32:0] memory_MulDivIterativePlugin_div_stage_1_remainderShifted; + wire [32:0] memory_MulDivIterativePlugin_div_stage_1_remainderMinusDenominator; + wire [31:0] memory_MulDivIterativePlugin_div_stage_1_outRemainder; + wire [31:0] memory_MulDivIterativePlugin_div_stage_1_outNumerator; + wire [31:0] _zz_140_; + wire _zz_141_; + wire _zz_142_; + reg [32:0] _zz_143_; + wire execute_BranchPlugin_eq; + wire [2:0] _zz_144_; + reg _zz_145_; + reg _zz_146_; + wire [31:0] execute_BranchPlugin_branch_src1; + wire _zz_147_; + reg [10:0] _zz_148_; + wire _zz_149_; + reg [19:0] _zz_150_; + wire _zz_151_; + reg [18:0] _zz_152_; + reg [31:0] _zz_153_; + wire [31:0] execute_BranchPlugin_branch_src2; + wire [31:0] execute_BranchPlugin_branchAdder; + reg [31:0] decode_to_execute_RS1; + reg [1:0] execute_to_memory_MEMORY_ADDRESS_LOW; + reg decode_to_execute_IS_DIV; + reg execute_to_memory_IS_DIV; + reg decode_to_execute_IS_RVC; + reg decode_to_execute_IS_RS2_SIGNED; + reg decode_to_execute_SRC_USE_SUB_LESS; + reg decode_to_execute_SRC_LESS_UNSIGNED; + reg `EnvCtrlEnum_defaultEncoding_type decode_to_execute_ENV_CTRL; + reg `EnvCtrlEnum_defaultEncoding_type execute_to_memory_ENV_CTRL; + reg `EnvCtrlEnum_defaultEncoding_type memory_to_writeBack_ENV_CTRL; + reg decode_to_execute_SRC2_FORCE_ZERO; + reg `AluCtrlEnum_defaultEncoding_type decode_to_execute_ALU_CTRL; + reg decode_to_execute_REGFILE_WRITE_VALID; + reg execute_to_memory_REGFILE_WRITE_VALID; + reg memory_to_writeBack_REGFILE_WRITE_VALID; + reg [31:0] decode_to_execute_PC; + reg [31:0] execute_to_memory_PC; + reg [31:0] memory_to_writeBack_PC; + reg decode_to_execute_BYPASSABLE_MEMORY_STAGE; + reg execute_to_memory_BYPASSABLE_MEMORY_STAGE; + reg `BranchCtrlEnum_defaultEncoding_type decode_to_execute_BRANCH_CTRL; + reg decode_to_execute_IS_RS1_SIGNED; + reg [31:0] execute_to_memory_REGFILE_WRITE_DATA; + reg [31:0] memory_to_writeBack_REGFILE_WRITE_DATA; + reg decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + reg decode_to_execute_IS_CSR; + reg `Src1CtrlEnum_defaultEncoding_type decode_to_execute_SRC1_CTRL; + reg decode_to_execute_MEMORY_STORE; + reg execute_to_memory_MEMORY_STORE; + reg [31:0] decode_to_execute_INSTRUCTION; + reg [31:0] execute_to_memory_INSTRUCTION; + reg [31:0] memory_to_writeBack_INSTRUCTION; + reg decode_to_execute_IS_MUL; + reg execute_to_memory_IS_MUL; + reg `ShiftCtrlEnum_defaultEncoding_type decode_to_execute_SHIFT_CTRL; + reg decode_to_execute_CSR_WRITE_OPCODE; + reg decode_to_execute_CSR_READ_OPCODE; + reg [31:0] decode_to_execute_FORMAL_PC_NEXT; + reg [31:0] execute_to_memory_FORMAL_PC_NEXT; + reg [31:0] memory_to_writeBack_FORMAL_PC_NEXT; + reg `Src2CtrlEnum_defaultEncoding_type decode_to_execute_SRC2_CTRL; + reg decode_to_execute_MEMORY_ENABLE; + reg execute_to_memory_MEMORY_ENABLE; + reg `AluBitwiseCtrlEnum_defaultEncoding_type decode_to_execute_ALU_BITWISE_CTRL; + reg [31:0] decode_to_execute_RS2; + reg execute_CsrPlugin_csr_768; + reg execute_CsrPlugin_csr_836; + reg execute_CsrPlugin_csr_772; + reg execute_CsrPlugin_csr_832; + reg execute_CsrPlugin_csr_834; + reg [31:0] _zz_154_; + reg [31:0] _zz_155_; + reg [31:0] _zz_156_; + reg [31:0] _zz_157_; + reg [31:0] _zz_158_; + `ifndef SYNTHESIS + reg [39:0] decode_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_1__string; + reg [39:0] _zz_2__string; + reg [39:0] _zz_3__string; + reg [23:0] decode_SRC2_CTRL_string; + reg [23:0] _zz_4__string; + reg [23:0] _zz_5__string; + reg [23:0] _zz_6__string; + reg [71:0] decode_SHIFT_CTRL_string; + reg [71:0] _zz_7__string; + reg [71:0] _zz_8__string; + reg [71:0] _zz_9__string; + reg [95:0] decode_SRC1_CTRL_string; + reg [95:0] _zz_10__string; + reg [95:0] _zz_11__string; + reg [95:0] _zz_12__string; + reg [31:0] decode_BRANCH_CTRL_string; + reg [31:0] _zz_13__string; + reg [31:0] _zz_14__string; + reg [31:0] _zz_15__string; + reg [63:0] decode_ALU_CTRL_string; + reg [63:0] _zz_16__string; + reg [63:0] _zz_17__string; + reg [63:0] _zz_18__string; + reg [31:0] _zz_19__string; + reg [31:0] _zz_20__string; + reg [31:0] _zz_21__string; + reg [31:0] _zz_22__string; + reg [31:0] decode_ENV_CTRL_string; + reg [31:0] _zz_23__string; + reg [31:0] _zz_24__string; + reg [31:0] _zz_25__string; + reg [31:0] execute_BRANCH_CTRL_string; + reg [31:0] _zz_26__string; + reg [71:0] execute_SHIFT_CTRL_string; + reg [71:0] _zz_27__string; + reg [23:0] execute_SRC2_CTRL_string; + reg [23:0] _zz_29__string; + reg [95:0] execute_SRC1_CTRL_string; + reg [95:0] _zz_30__string; + reg [63:0] execute_ALU_CTRL_string; + reg [63:0] _zz_31__string; + reg [39:0] execute_ALU_BITWISE_CTRL_string; + reg [39:0] _zz_32__string; + reg [23:0] _zz_37__string; + reg [39:0] _zz_38__string; + reg [31:0] _zz_39__string; + reg [95:0] _zz_40__string; + reg [31:0] _zz_41__string; + reg [71:0] _zz_42__string; + reg [63:0] _zz_43__string; + reg [31:0] memory_ENV_CTRL_string; + reg [31:0] _zz_45__string; + reg [31:0] execute_ENV_CTRL_string; + reg [31:0] _zz_46__string; + reg [31:0] writeBack_ENV_CTRL_string; + reg [31:0] _zz_47__string; + reg [63:0] _zz_111__string; + reg [71:0] _zz_112__string; + reg [31:0] _zz_113__string; + reg [95:0] _zz_114__string; + reg [31:0] _zz_115__string; + reg [39:0] _zz_116__string; + reg [23:0] _zz_117__string; + reg [31:0] decode_to_execute_ENV_CTRL_string; + reg [31:0] execute_to_memory_ENV_CTRL_string; + reg [31:0] memory_to_writeBack_ENV_CTRL_string; + reg [63:0] decode_to_execute_ALU_CTRL_string; + reg [31:0] decode_to_execute_BRANCH_CTRL_string; + reg [95:0] decode_to_execute_SRC1_CTRL_string; + reg [71:0] decode_to_execute_SHIFT_CTRL_string; + reg [23:0] decode_to_execute_SRC2_CTRL_string; + reg [39:0] decode_to_execute_ALU_BITWISE_CTRL_string; + `endif + + reg [31:0] RegFilePlugin_regFile [0:15] /* verilator public */ ; + + assign _zz_163_ = (writeBack_arbitration_isValid && writeBack_REGFILE_WRITE_VALID); + assign _zz_164_ = 1'b1; + assign _zz_165_ = (memory_arbitration_isValid && memory_REGFILE_WRITE_VALID); + assign _zz_166_ = (execute_arbitration_isValid && execute_REGFILE_WRITE_VALID); + assign _zz_167_ = (execute_arbitration_isValid && execute_IS_CSR); + assign _zz_168_ = (memory_arbitration_isValid && memory_IS_MUL); + assign _zz_169_ = (memory_arbitration_isValid && memory_IS_DIV); + assign _zz_170_ = (memory_MulDivIterativePlugin_frontendOk && (! memory_MulDivIterativePlugin_mul_counter_willOverflowIfInc)); + assign _zz_171_ = (CsrPlugin_hadException || CsrPlugin_interruptJump); + assign _zz_172_ = (writeBack_arbitration_isValid && (writeBack_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)); + assign _zz_173_ = writeBack_INSTRUCTION[29 : 28]; + assign _zz_174_ = (IBusSimplePlugin_jump_pcLoad_valid && ((! decode_arbitration_isStuck) || decode_arbitration_removeIt)); + assign _zz_175_ = (writeBack_arbitration_isValid && writeBack_REGFILE_WRITE_VALID); + assign _zz_176_ = (1'b0 || (! 1'b1)); + assign _zz_177_ = (memory_arbitration_isValid && memory_REGFILE_WRITE_VALID); + assign _zz_178_ = (1'b0 || (! memory_BYPASSABLE_MEMORY_STAGE)); + assign _zz_179_ = (execute_arbitration_isValid && execute_REGFILE_WRITE_VALID); + assign _zz_180_ = (1'b0 || (! execute_BYPASSABLE_EXECUTE_STAGE)); + assign _zz_181_ = (memory_MulDivIterativePlugin_frontendOk && (! memory_MulDivIterativePlugin_div_done)); + assign _zz_182_ = (! memory_arbitration_isStuck); + assign _zz_183_ = (IBusSimplePlugin_decompressor_output_ready && IBusSimplePlugin_decompressor_input_valid); + assign _zz_184_ = (CsrPlugin_mstatus_MIE || (CsrPlugin_privilege < (2'b11))); + assign _zz_185_ = ((_zz_100_ && 1'b1) && (! 1'b0)); + assign _zz_186_ = ((_zz_101_ && 1'b1) && (! 1'b0)); + assign _zz_187_ = ((_zz_102_ && 1'b1) && (! 1'b0)); + assign _zz_188_ = {_zz_60_[1 : 0],_zz_60_[15 : 13]}; + assign _zz_189_ = _zz_60_[6 : 5]; + assign _zz_190_ = _zz_60_[11 : 10]; + assign _zz_191_ = memory_INSTRUCTION[13 : 12]; + assign _zz_192_ = execute_INSTRUCTION[13]; + assign _zz_193_ = _zz_103_[18 : 18]; + assign _zz_194_ = (decode_IS_RVC ? (3'b010) : (3'b100)); + assign _zz_195_ = {29'd0, _zz_194_}; + assign _zz_196_ = _zz_103_[1 : 1]; + assign _zz_197_ = _zz_103_[19 : 19]; + assign _zz_198_ = _zz_103_[25 : 25]; + assign _zz_199_ = _zz_103_[21 : 21]; + assign _zz_200_ = _zz_103_[4 : 4]; + assign _zz_201_ = _zz_103_[5 : 5]; + assign _zz_202_ = _zz_103_[16 : 16]; + assign _zz_203_ = _zz_103_[6 : 6]; + assign _zz_204_ = _zz_103_[0 : 0]; + assign _zz_205_ = _zz_103_[7 : 7]; + assign _zz_206_ = _zz_103_[28 : 28]; + assign _zz_207_ = ($signed(_zz_209_) >>> execute_FullBarrelShifterPlugin_amplitude); + assign _zz_208_ = _zz_207_[31 : 0]; + assign _zz_209_ = {((execute_SHIFT_CTRL == `ShiftCtrlEnum_defaultEncoding_SRA_1) && execute_FullBarrelShifterPlugin_reversed[31]),execute_FullBarrelShifterPlugin_reversed}; + assign _zz_210_ = _zz_103_[13 : 13]; + assign _zz_211_ = _zz_103_[24 : 24]; + assign _zz_212_ = _zz_103_[17 : 17]; + assign _zz_213_ = (_zz_50_ & (~ _zz_214_)); + assign _zz_214_ = (_zz_50_ - (2'b01)); + assign _zz_215_ = {IBusSimplePlugin_fetchPc_inc,(2'b00)}; + assign _zz_216_ = {29'd0, _zz_215_}; + assign _zz_217_ = (decode_IS_RVC ? (3'b010) : (3'b100)); + assign _zz_218_ = {29'd0, _zz_217_}; + assign _zz_219_ = {{_zz_70_,_zz_60_[6 : 2]},12'h0}; + assign _zz_220_ = {{{(4'b0000),_zz_60_[8 : 7]},_zz_60_[12 : 9]},(2'b00)}; + assign _zz_221_ = {{{(4'b0000),_zz_60_[8 : 7]},_zz_60_[12 : 9]},(2'b00)}; + assign _zz_222_ = (IBusSimplePlugin_pending_value + _zz_224_); + assign _zz_223_ = IBusSimplePlugin_pending_inc; + assign _zz_224_ = {2'd0, _zz_223_}; + assign _zz_225_ = IBusSimplePlugin_pending_dec; + assign _zz_226_ = {2'd0, _zz_225_}; + assign _zz_227_ = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000))); + assign _zz_228_ = {2'd0, _zz_227_}; + assign _zz_229_ = execute_SRC_LESS; + assign _zz_230_ = (execute_IS_RVC ? (3'b010) : (3'b100)); + assign _zz_231_ = execute_INSTRUCTION[19 : 15]; + assign _zz_232_ = execute_INSTRUCTION[31 : 20]; + assign _zz_233_ = {execute_INSTRUCTION[31 : 25],execute_INSTRUCTION[11 : 7]}; + assign _zz_234_ = ($signed(_zz_235_) + $signed(_zz_238_)); + assign _zz_235_ = ($signed(_zz_236_) + $signed(_zz_237_)); + assign _zz_236_ = execute_SRC1; + assign _zz_237_ = (execute_SRC_USE_SUB_LESS ? (~ execute_SRC2) : execute_SRC2); + assign _zz_238_ = (execute_SRC_USE_SUB_LESS ? _zz_239_ : _zz_240_); + assign _zz_239_ = 32'h00000001; + assign _zz_240_ = 32'h0; + assign _zz_241_ = memory_MulDivIterativePlugin_mul_counter_willIncrement; + assign _zz_242_ = {4'd0, _zz_241_}; + assign _zz_243_ = (_zz_244_ + _zz_251_); + assign _zz_244_ = (_zz_246_ + _zz_248_); + assign _zz_245_ = (memory_MulDivIterativePlugin_rs2[0] ? memory_MulDivIterativePlugin_rs1 : 33'h0); + assign _zz_246_ = {{2{_zz_245_[32]}}, _zz_245_}; + assign _zz_247_ = (memory_MulDivIterativePlugin_rs2[1] ? _zz_249_ : 34'h0); + assign _zz_248_ = {{1{_zz_247_[33]}}, _zz_247_}; + assign _zz_249_ = ({1'd0,memory_MulDivIterativePlugin_rs1} <<< 1); + assign _zz_250_ = _zz_252_; + assign _zz_251_ = {{2{_zz_250_[32]}}, _zz_250_}; + assign _zz_252_ = (memory_MulDivIterativePlugin_accumulator >>> 32); + assign _zz_253_ = memory_MulDivIterativePlugin_div_counter_willIncrement; + assign _zz_254_ = {4'd0, _zz_253_}; + assign _zz_255_ = {1'd0, memory_MulDivIterativePlugin_rs2}; + assign _zz_256_ = memory_MulDivIterativePlugin_div_stage_0_remainderMinusDenominator[31:0]; + assign _zz_257_ = memory_MulDivIterativePlugin_div_stage_0_remainderShifted[31:0]; + assign _zz_258_ = {_zz_139_,(! memory_MulDivIterativePlugin_div_stage_0_remainderMinusDenominator[32])}; + assign _zz_259_ = {1'd0, memory_MulDivIterativePlugin_rs2}; + assign _zz_260_ = memory_MulDivIterativePlugin_div_stage_1_remainderMinusDenominator[31:0]; + assign _zz_261_ = memory_MulDivIterativePlugin_div_stage_1_remainderShifted[31:0]; + assign _zz_262_ = {memory_MulDivIterativePlugin_div_stage_0_outNumerator,(! memory_MulDivIterativePlugin_div_stage_1_remainderMinusDenominator[32])}; + assign _zz_263_ = _zz_264_; + assign _zz_264_ = _zz_265_; + assign _zz_265_ = ({1'b0,(memory_MulDivIterativePlugin_div_needRevert ? (~ _zz_140_) : _zz_140_)} + _zz_267_); + assign _zz_266_ = memory_MulDivIterativePlugin_div_needRevert; + assign _zz_267_ = {32'd0, _zz_266_}; + assign _zz_268_ = _zz_142_; + assign _zz_269_ = {32'd0, _zz_268_}; + assign _zz_270_ = _zz_141_; + assign _zz_271_ = {31'd0, _zz_270_}; + assign _zz_272_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}; + assign _zz_273_ = execute_INSTRUCTION[31 : 20]; + assign _zz_274_ = {{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}; + assign _zz_275_ = execute_CsrPlugin_writeData[7 : 7]; + assign _zz_276_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_277_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_278_ = execute_CsrPlugin_writeData[11 : 11]; + assign _zz_279_ = execute_CsrPlugin_writeData[7 : 7]; + assign _zz_280_ = execute_CsrPlugin_writeData[3 : 3]; + assign _zz_281_ = 1'b1; + assign _zz_282_ = 1'b1; + assign _zz_283_ = (_zz_60_[11 : 10] == (2'b01)); + assign _zz_284_ = ((_zz_60_[11 : 10] == (2'b11)) && (_zz_60_[6 : 5] == (2'b00))); + assign _zz_285_ = 7'h0; + assign _zz_286_ = _zz_60_[6 : 2]; + assign _zz_287_ = _zz_60_[12]; + assign _zz_288_ = _zz_60_[11 : 7]; + assign _zz_289_ = (decode_INSTRUCTION & 32'h00000044); + assign _zz_290_ = 32'h0; + assign _zz_291_ = ((decode_INSTRUCTION & 32'h00000018) == 32'h0); + assign _zz_292_ = _zz_104_; + assign _zz_293_ = ((decode_INSTRUCTION & _zz_302_) == 32'h00001000); + assign _zz_294_ = ((decode_INSTRUCTION & 32'h00000070) == 32'h00000020); + assign _zz_295_ = _zz_110_; + assign _zz_296_ = ((decode_INSTRUCTION & _zz_303_) == 32'h0); + assign _zz_297_ = {(_zz_304_ == _zz_305_),(_zz_306_ == _zz_307_)}; + assign _zz_298_ = (2'b00); + assign _zz_299_ = ((_zz_308_ == _zz_309_) != (1'b0)); + assign _zz_300_ = (_zz_310_ != (1'b0)); + assign _zz_301_ = {(_zz_311_ != _zz_312_),{_zz_313_,{_zz_314_,_zz_315_}}}; + assign _zz_302_ = 32'h00005004; + assign _zz_303_ = 32'h00000020; + assign _zz_304_ = (decode_INSTRUCTION & 32'h00001050); + assign _zz_305_ = 32'h00001050; + assign _zz_306_ = (decode_INSTRUCTION & 32'h00002050); + assign _zz_307_ = 32'h00002050; + assign _zz_308_ = (decode_INSTRUCTION & 32'h00000064); + assign _zz_309_ = 32'h00000024; + assign _zz_310_ = ((decode_INSTRUCTION & 32'h00001000) == 32'h00001000); + assign _zz_311_ = _zz_106_; + assign _zz_312_ = (1'b0); + assign _zz_313_ = ({_zz_110_,{_zz_316_,_zz_317_}} != (3'b000)); + assign _zz_314_ = ({_zz_318_,_zz_319_} != (2'b00)); + assign _zz_315_ = {(_zz_320_ != (1'b0)),{(_zz_321_ != _zz_322_),{_zz_323_,{_zz_324_,_zz_325_}}}}; + assign _zz_316_ = ((decode_INSTRUCTION & 32'h00000030) == 32'h00000010); + assign _zz_317_ = ((decode_INSTRUCTION & 32'h02000060) == 32'h00000020); + assign _zz_318_ = ((decode_INSTRUCTION & 32'h00000050) == 32'h00000040); + assign _zz_319_ = ((decode_INSTRUCTION & 32'h00003040) == 32'h00000040); + assign _zz_320_ = ((decode_INSTRUCTION & 32'h00000020) == 32'h00000020); + assign _zz_321_ = ((decode_INSTRUCTION & _zz_326_) == 32'h0); + assign _zz_322_ = (1'b0); + assign _zz_323_ = ({_zz_109_,{_zz_327_,_zz_328_}} != 6'h0); + assign _zz_324_ = ({_zz_329_,_zz_330_} != (2'b00)); + assign _zz_325_ = {(_zz_331_ != _zz_332_),{_zz_333_,{_zz_334_,_zz_335_}}}; + assign _zz_326_ = 32'h00000058; + assign _zz_327_ = ((decode_INSTRUCTION & _zz_336_) == 32'h00001010); + assign _zz_328_ = {(_zz_337_ == _zz_338_),{_zz_339_,{_zz_340_,_zz_341_}}}; + assign _zz_329_ = ((decode_INSTRUCTION & _zz_342_) == 32'h00002000); + assign _zz_330_ = ((decode_INSTRUCTION & _zz_343_) == 32'h00001000); + assign _zz_331_ = {_zz_109_,(_zz_344_ == _zz_345_)}; + assign _zz_332_ = (2'b00); + assign _zz_333_ = ((_zz_346_ == _zz_347_) != (1'b0)); + assign _zz_334_ = ({_zz_348_,_zz_349_} != (3'b000)); + assign _zz_335_ = {(_zz_350_ != _zz_351_),{_zz_352_,{_zz_353_,_zz_354_}}}; + assign _zz_336_ = 32'h00001010; + assign _zz_337_ = (decode_INSTRUCTION & 32'h00002010); + assign _zz_338_ = 32'h00002010; + assign _zz_339_ = ((decode_INSTRUCTION & _zz_355_) == 32'h00000010); + assign _zz_340_ = (_zz_356_ == _zz_357_); + assign _zz_341_ = (_zz_358_ == _zz_359_); + assign _zz_342_ = 32'h00002010; + assign _zz_343_ = 32'h00005000; + assign _zz_344_ = (decode_INSTRUCTION & 32'h0000001c); + assign _zz_345_ = 32'h00000004; + assign _zz_346_ = (decode_INSTRUCTION & 32'h00000058); + assign _zz_347_ = 32'h00000040; + assign _zz_348_ = (_zz_360_ == _zz_361_); + assign _zz_349_ = {_zz_362_,_zz_363_}; + assign _zz_350_ = {_zz_364_,_zz_108_}; + assign _zz_351_ = (2'b00); + assign _zz_352_ = ({_zz_365_,_zz_366_} != (2'b00)); + assign _zz_353_ = (_zz_367_ != _zz_368_); + assign _zz_354_ = {_zz_369_,{_zz_370_,_zz_371_}}; + assign _zz_355_ = 32'h00000050; + assign _zz_356_ = (decode_INSTRUCTION & 32'h0000000c); + assign _zz_357_ = 32'h00000004; + assign _zz_358_ = (decode_INSTRUCTION & 32'h00000028); + assign _zz_359_ = 32'h0; + assign _zz_360_ = (decode_INSTRUCTION & 32'h00000044); + assign _zz_361_ = 32'h00000040; + assign _zz_362_ = ((decode_INSTRUCTION & 32'h00002014) == 32'h00002010); + assign _zz_363_ = ((decode_INSTRUCTION & 32'h40000034) == 32'h40000030); + assign _zz_364_ = ((decode_INSTRUCTION & 32'h00000014) == 32'h00000004); + assign _zz_365_ = ((decode_INSTRUCTION & _zz_372_) == 32'h00000004); + assign _zz_366_ = _zz_108_; + assign _zz_367_ = ((decode_INSTRUCTION & _zz_373_) == 32'h00000050); + assign _zz_368_ = (1'b0); + assign _zz_369_ = ({_zz_374_,_zz_375_} != (2'b00)); + assign _zz_370_ = ({_zz_376_,_zz_377_} != (3'b000)); + assign _zz_371_ = {(_zz_378_ != _zz_379_),{_zz_380_,{_zz_381_,_zz_382_}}}; + assign _zz_372_ = 32'h00000044; + assign _zz_373_ = 32'h00003050; + assign _zz_374_ = ((decode_INSTRUCTION & 32'h00007034) == 32'h00005010); + assign _zz_375_ = ((decode_INSTRUCTION & 32'h02007064) == 32'h00005020); + assign _zz_376_ = ((decode_INSTRUCTION & _zz_383_) == 32'h40001010); + assign _zz_377_ = {(_zz_384_ == _zz_385_),(_zz_386_ == _zz_387_)}; + assign _zz_378_ = {(_zz_388_ == _zz_389_),(_zz_390_ == _zz_391_)}; + assign _zz_379_ = (2'b00); + assign _zz_380_ = ({_zz_107_,_zz_105_} != (2'b00)); + assign _zz_381_ = (_zz_392_ != (1'b0)); + assign _zz_382_ = {(_zz_393_ != _zz_394_),{_zz_395_,{_zz_396_,_zz_397_}}}; + assign _zz_383_ = 32'h40003054; + assign _zz_384_ = (decode_INSTRUCTION & 32'h00007034); + assign _zz_385_ = 32'h00001010; + assign _zz_386_ = (decode_INSTRUCTION & 32'h02007054); + assign _zz_387_ = 32'h00001010; + assign _zz_388_ = (decode_INSTRUCTION & 32'h00000034); + assign _zz_389_ = 32'h00000020; + assign _zz_390_ = (decode_INSTRUCTION & 32'h00000064); + assign _zz_391_ = 32'h00000020; + assign _zz_392_ = ((decode_INSTRUCTION & 32'h0) == 32'h0); + assign _zz_393_ = {_zz_107_,{_zz_106_,_zz_105_}}; + assign _zz_394_ = (3'b000); + assign _zz_395_ = (((decode_INSTRUCTION & _zz_398_) == 32'h00004000) != (1'b0)); + assign _zz_396_ = (_zz_104_ != (1'b0)); + assign _zz_397_ = {(_zz_399_ != (1'b0)),(_zz_400_ != (1'b0))}; + assign _zz_398_ = 32'h00004004; + assign _zz_399_ = ((decode_INSTRUCTION & 32'h02004074) == 32'h02000030); + assign _zz_400_ = ((decode_INSTRUCTION & 32'h02004064) == 32'h02004020); + always @ (posedge clk) begin + if(_zz_281_) begin + _zz_161_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress1]; + end + end + + always @ (posedge clk) begin + if(_zz_282_) begin + _zz_162_ <= RegFilePlugin_regFile[decode_RegFilePlugin_regFileReadAddress2]; + end + end + + always @ (posedge clk) begin + if(_zz_36_) begin + RegFilePlugin_regFile[lastStageRegFileWrite_payload_address] <= lastStageRegFileWrite_payload_data; + end + end + + StreamFifoLowLatency IBusSimplePlugin_rspJoin_rspBuffer_c ( + .io_push_valid (iBus_rsp_valid ), //i + .io_push_ready (IBusSimplePlugin_rspJoin_rspBuffer_c_io_push_ready ), //o + .io_push_payload_error (iBus_rsp_payload_error ), //i + .io_push_payload_inst (iBus_rsp_payload_inst[31:0] ), //i + .io_pop_valid (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid ), //o + .io_pop_ready (_zz_159_ ), //i + .io_pop_payload_error (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error ), //o + .io_pop_payload_inst (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst[31:0] ), //o + .io_flush (_zz_160_ ), //i + .io_occupancy (IBusSimplePlugin_rspJoin_rspBuffer_c_io_occupancy ), //o + .clk (clk ), //i + .reset (reset ) //i + ); + `ifndef SYNTHESIS + always @(*) begin + case(decode_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_1_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_1__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_1__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_1__string = "AND_1"; + default : _zz_1__string = "?????"; + endcase + end + always @(*) begin + case(_zz_2_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_2__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_2__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_2__string = "AND_1"; + default : _zz_2__string = "?????"; + endcase + end + always @(*) begin + case(_zz_3_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_3__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_3__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_3__string = "AND_1"; + default : _zz_3__string = "?????"; + endcase + end + always @(*) begin + case(decode_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_SRC2_CTRL_string = "PC "; + default : decode_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_4_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_4__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_4__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_4__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_4__string = "PC "; + default : _zz_4__string = "???"; + endcase + end + always @(*) begin + case(_zz_5_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_5__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_5__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_5__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_5__string = "PC "; + default : _zz_5__string = "???"; + endcase + end + always @(*) begin + case(_zz_6_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_6__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_6__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_6__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_6__string = "PC "; + default : _zz_6__string = "???"; + endcase + end + always @(*) begin + case(decode_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_SHIFT_CTRL_string = "SRA_1 "; + default : decode_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_7_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_7__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_7__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_7__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_7__string = "SRA_1 "; + default : _zz_7__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_8_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_8__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_8__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_8__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_8__string = "SRA_1 "; + default : _zz_8__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_9_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_9__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_9__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_9__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_9__string = "SRA_1 "; + default : _zz_9__string = "?????????"; + endcase + end + always @(*) begin + case(decode_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_SRC1_CTRL_string = "URS1 "; + default : decode_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_10_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_10__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_10__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_10__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_10__string = "URS1 "; + default : _zz_10__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_11_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_11__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_11__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_11__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_11__string = "URS1 "; + default : _zz_11__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_12_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_12__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_12__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_12__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_12__string = "URS1 "; + default : _zz_12__string = "????????????"; + endcase + end + always @(*) begin + case(decode_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_BRANCH_CTRL_string = "JALR"; + default : decode_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_13_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_13__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_13__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_13__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_13__string = "JALR"; + default : _zz_13__string = "????"; + endcase + end + always @(*) begin + case(_zz_14_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_14__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_14__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_14__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_14__string = "JALR"; + default : _zz_14__string = "????"; + endcase + end + always @(*) begin + case(_zz_15_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_15__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_15__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_15__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_15__string = "JALR"; + default : _zz_15__string = "????"; + endcase + end + always @(*) begin + case(decode_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_ALU_CTRL_string = "BITWISE "; + default : decode_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_16_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_16__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_16__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_16__string = "BITWISE "; + default : _zz_16__string = "????????"; + endcase + end + always @(*) begin + case(_zz_17_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_17__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_17__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_17__string = "BITWISE "; + default : _zz_17__string = "????????"; + endcase + end + always @(*) begin + case(_zz_18_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_18__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_18__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_18__string = "BITWISE "; + default : _zz_18__string = "????????"; + endcase + end + always @(*) begin + case(_zz_19_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_19__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_19__string = "XRET"; + default : _zz_19__string = "????"; + endcase + end + always @(*) begin + case(_zz_20_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_20__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_20__string = "XRET"; + default : _zz_20__string = "????"; + endcase + end + always @(*) begin + case(_zz_21_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_21__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_21__string = "XRET"; + default : _zz_21__string = "????"; + endcase + end + always @(*) begin + case(_zz_22_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_22__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_22__string = "XRET"; + default : _zz_22__string = "????"; + endcase + end + always @(*) begin + case(decode_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : decode_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : decode_ENV_CTRL_string = "XRET"; + default : decode_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_23_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_23__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_23__string = "XRET"; + default : _zz_23__string = "????"; + endcase + end + always @(*) begin + case(_zz_24_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_24__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_24__string = "XRET"; + default : _zz_24__string = "????"; + endcase + end + always @(*) begin + case(_zz_25_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_25__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_25__string = "XRET"; + default : _zz_25__string = "????"; + endcase + end + always @(*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : execute_BRANCH_CTRL_string = "JALR"; + default : execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_26_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_26__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_26__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_26__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_26__string = "JALR"; + default : _zz_26__string = "????"; + endcase + end + always @(*) begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : execute_SHIFT_CTRL_string = "SRA_1 "; + default : execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(_zz_27_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_27__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_27__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_27__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_27__string = "SRA_1 "; + default : _zz_27__string = "?????????"; + endcase + end + always @(*) begin + case(execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : execute_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : execute_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : execute_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : execute_SRC2_CTRL_string = "PC "; + default : execute_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(_zz_29_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_29__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_29__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_29__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_29__string = "PC "; + default : _zz_29__string = "???"; + endcase + end + always @(*) begin + case(execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : execute_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : execute_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : execute_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : execute_SRC1_CTRL_string = "URS1 "; + default : execute_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(_zz_30_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_30__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_30__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_30__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_30__string = "URS1 "; + default : _zz_30__string = "????????????"; + endcase + end + always @(*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : execute_ALU_CTRL_string = "BITWISE "; + default : execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(_zz_31_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_31__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_31__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_31__string = "BITWISE "; + default : _zz_31__string = "????????"; + endcase + end + always @(*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + always @(*) begin + case(_zz_32_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_32__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_32__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_32__string = "AND_1"; + default : _zz_32__string = "?????"; + endcase + end + always @(*) begin + case(_zz_37_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_37__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_37__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_37__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_37__string = "PC "; + default : _zz_37__string = "???"; + endcase + end + always @(*) begin + case(_zz_38_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_38__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_38__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_38__string = "AND_1"; + default : _zz_38__string = "?????"; + endcase + end + always @(*) begin + case(_zz_39_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_39__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_39__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_39__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_39__string = "JALR"; + default : _zz_39__string = "????"; + endcase + end + always @(*) begin + case(_zz_40_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_40__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_40__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_40__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_40__string = "URS1 "; + default : _zz_40__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_41_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_41__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_41__string = "XRET"; + default : _zz_41__string = "????"; + endcase + end + always @(*) begin + case(_zz_42_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_42__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_42__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_42__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_42__string = "SRA_1 "; + default : _zz_42__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_43_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_43__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_43__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_43__string = "BITWISE "; + default : _zz_43__string = "????????"; + endcase + end + always @(*) begin + case(memory_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : memory_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : memory_ENV_CTRL_string = "XRET"; + default : memory_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_45_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_45__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_45__string = "XRET"; + default : _zz_45__string = "????"; + endcase + end + always @(*) begin + case(execute_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : execute_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : execute_ENV_CTRL_string = "XRET"; + default : execute_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_46_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_46__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_46__string = "XRET"; + default : _zz_46__string = "????"; + endcase + end + always @(*) begin + case(writeBack_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : writeBack_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : writeBack_ENV_CTRL_string = "XRET"; + default : writeBack_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(_zz_47_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_47__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_47__string = "XRET"; + default : _zz_47__string = "????"; + endcase + end + always @(*) begin + case(_zz_111_) + `AluCtrlEnum_defaultEncoding_ADD_SUB : _zz_111__string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : _zz_111__string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : _zz_111__string = "BITWISE "; + default : _zz_111__string = "????????"; + endcase + end + always @(*) begin + case(_zz_112_) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : _zz_112__string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : _zz_112__string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : _zz_112__string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : _zz_112__string = "SRA_1 "; + default : _zz_112__string = "?????????"; + endcase + end + always @(*) begin + case(_zz_113_) + `EnvCtrlEnum_defaultEncoding_NONE : _zz_113__string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : _zz_113__string = "XRET"; + default : _zz_113__string = "????"; + endcase + end + always @(*) begin + case(_zz_114_) + `Src1CtrlEnum_defaultEncoding_RS : _zz_114__string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : _zz_114__string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : _zz_114__string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : _zz_114__string = "URS1 "; + default : _zz_114__string = "????????????"; + endcase + end + always @(*) begin + case(_zz_115_) + `BranchCtrlEnum_defaultEncoding_INC : _zz_115__string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : _zz_115__string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : _zz_115__string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : _zz_115__string = "JALR"; + default : _zz_115__string = "????"; + endcase + end + always @(*) begin + case(_zz_116_) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : _zz_116__string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : _zz_116__string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : _zz_116__string = "AND_1"; + default : _zz_116__string = "?????"; + endcase + end + always @(*) begin + case(_zz_117_) + `Src2CtrlEnum_defaultEncoding_RS : _zz_117__string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : _zz_117__string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : _zz_117__string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : _zz_117__string = "PC "; + default : _zz_117__string = "???"; + endcase + end + always @(*) begin + case(decode_to_execute_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : decode_to_execute_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : decode_to_execute_ENV_CTRL_string = "XRET"; + default : decode_to_execute_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(execute_to_memory_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : execute_to_memory_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : execute_to_memory_ENV_CTRL_string = "XRET"; + default : execute_to_memory_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(memory_to_writeBack_ENV_CTRL) + `EnvCtrlEnum_defaultEncoding_NONE : memory_to_writeBack_ENV_CTRL_string = "NONE"; + `EnvCtrlEnum_defaultEncoding_XRET : memory_to_writeBack_ENV_CTRL_string = "XRET"; + default : memory_to_writeBack_ENV_CTRL_string = "????"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_ADD_SUB : decode_to_execute_ALU_CTRL_string = "ADD_SUB "; + `AluCtrlEnum_defaultEncoding_SLT_SLTU : decode_to_execute_ALU_CTRL_string = "SLT_SLTU"; + `AluCtrlEnum_defaultEncoding_BITWISE : decode_to_execute_ALU_CTRL_string = "BITWISE "; + default : decode_to_execute_ALU_CTRL_string = "????????"; + endcase + end + always @(*) begin + case(decode_to_execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : decode_to_execute_BRANCH_CTRL_string = "INC "; + `BranchCtrlEnum_defaultEncoding_B : decode_to_execute_BRANCH_CTRL_string = "B "; + `BranchCtrlEnum_defaultEncoding_JAL : decode_to_execute_BRANCH_CTRL_string = "JAL "; + `BranchCtrlEnum_defaultEncoding_JALR : decode_to_execute_BRANCH_CTRL_string = "JALR"; + default : decode_to_execute_BRANCH_CTRL_string = "????"; + endcase + end + always @(*) begin + case(decode_to_execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : decode_to_execute_SRC1_CTRL_string = "RS "; + `Src1CtrlEnum_defaultEncoding_IMU : decode_to_execute_SRC1_CTRL_string = "IMU "; + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : decode_to_execute_SRC1_CTRL_string = "PC_INCREMENT"; + `Src1CtrlEnum_defaultEncoding_URS1 : decode_to_execute_SRC1_CTRL_string = "URS1 "; + default : decode_to_execute_SRC1_CTRL_string = "????????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_DISABLE_1 : decode_to_execute_SHIFT_CTRL_string = "DISABLE_1"; + `ShiftCtrlEnum_defaultEncoding_SLL_1 : decode_to_execute_SHIFT_CTRL_string = "SLL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRL_1 : decode_to_execute_SHIFT_CTRL_string = "SRL_1 "; + `ShiftCtrlEnum_defaultEncoding_SRA_1 : decode_to_execute_SHIFT_CTRL_string = "SRA_1 "; + default : decode_to_execute_SHIFT_CTRL_string = "?????????"; + endcase + end + always @(*) begin + case(decode_to_execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : decode_to_execute_SRC2_CTRL_string = "RS "; + `Src2CtrlEnum_defaultEncoding_IMI : decode_to_execute_SRC2_CTRL_string = "IMI"; + `Src2CtrlEnum_defaultEncoding_IMS : decode_to_execute_SRC2_CTRL_string = "IMS"; + `Src2CtrlEnum_defaultEncoding_PC : decode_to_execute_SRC2_CTRL_string = "PC "; + default : decode_to_execute_SRC2_CTRL_string = "???"; + endcase + end + always @(*) begin + case(decode_to_execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_XOR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "XOR_1"; + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "OR_1 "; + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : decode_to_execute_ALU_BITWISE_CTRL_string = "AND_1"; + default : decode_to_execute_ALU_BITWISE_CTRL_string = "?????"; + endcase + end + `endif + + assign decode_ALU_BITWISE_CTRL = _zz_1_; + assign _zz_2_ = _zz_3_; + assign decode_MEMORY_ENABLE = _zz_193_[0]; + assign decode_SRC2_CTRL = _zz_4_; + assign _zz_5_ = _zz_6_; + assign writeBack_FORMAL_PC_NEXT = memory_to_writeBack_FORMAL_PC_NEXT; + assign memory_FORMAL_PC_NEXT = execute_to_memory_FORMAL_PC_NEXT; + assign execute_FORMAL_PC_NEXT = decode_to_execute_FORMAL_PC_NEXT; + assign decode_FORMAL_PC_NEXT = (decode_PC + _zz_195_); + assign decode_CSR_READ_OPCODE = (decode_INSTRUCTION[13 : 7] != 7'h20); + assign decode_CSR_WRITE_OPCODE = (! (((decode_INSTRUCTION[14 : 13] == (2'b01)) && (decode_INSTRUCTION[19 : 15] == 5'h0)) || ((decode_INSTRUCTION[14 : 13] == (2'b11)) && (decode_INSTRUCTION[19 : 15] == 5'h0)))); + assign decode_SHIFT_CTRL = _zz_7_; + assign _zz_8_ = _zz_9_; + assign decode_IS_MUL = _zz_196_[0]; + assign decode_MEMORY_STORE = _zz_197_[0]; + assign decode_SRC1_CTRL = _zz_10_; + assign _zz_11_ = _zz_12_; + assign decode_IS_CSR = _zz_198_[0]; + assign decode_BYPASSABLE_EXECUTE_STAGE = _zz_199_[0]; + assign writeBack_REGFILE_WRITE_DATA = memory_to_writeBack_REGFILE_WRITE_DATA; + assign memory_REGFILE_WRITE_DATA = execute_to_memory_REGFILE_WRITE_DATA; + assign execute_REGFILE_WRITE_DATA = _zz_119_; + assign decode_IS_RS1_SIGNED = _zz_200_[0]; + assign decode_BRANCH_CTRL = _zz_13_; + assign _zz_14_ = _zz_15_; + assign execute_BYPASSABLE_MEMORY_STAGE = decode_to_execute_BYPASSABLE_MEMORY_STAGE; + assign decode_BYPASSABLE_MEMORY_STAGE = _zz_201_[0]; + assign memory_PC = execute_to_memory_PC; + assign decode_ALU_CTRL = _zz_16_; + assign _zz_17_ = _zz_18_; + assign decode_SRC2_FORCE_ZERO = (decode_SRC_ADD_ZERO && (! decode_SRC_USE_SUB_LESS)); + assign _zz_19_ = _zz_20_; + assign _zz_21_ = _zz_22_; + assign decode_ENV_CTRL = _zz_23_; + assign _zz_24_ = _zz_25_; + assign decode_SRC_LESS_UNSIGNED = _zz_202_[0]; + assign decode_IS_RS2_SIGNED = _zz_203_[0]; + assign decode_IS_DIV = _zz_204_[0]; + assign execute_MEMORY_ADDRESS_LOW = dBus_cmd_payload_address[1 : 0]; + assign execute_BRANCH_CALC = {execute_BranchPlugin_branchAdder[31 : 1],(1'b0)}; + assign execute_BRANCH_DO = _zz_146_; + assign execute_PC = decode_to_execute_PC; + assign execute_BRANCH_CTRL = _zz_26_; + assign execute_IS_RS1_SIGNED = decode_to_execute_IS_RS1_SIGNED; + assign execute_RS1 = decode_to_execute_RS1; + assign execute_IS_DIV = decode_to_execute_IS_DIV; + assign execute_IS_MUL = decode_to_execute_IS_MUL; + assign execute_IS_RS2_SIGNED = decode_to_execute_IS_RS2_SIGNED; + assign memory_IS_DIV = execute_to_memory_IS_DIV; + assign memory_IS_MUL = execute_to_memory_IS_MUL; + assign decode_RS2_USE = _zz_205_[0]; + assign decode_RS1_USE = _zz_206_[0]; + assign execute_REGFILE_WRITE_VALID = decode_to_execute_REGFILE_WRITE_VALID; + assign execute_BYPASSABLE_EXECUTE_STAGE = decode_to_execute_BYPASSABLE_EXECUTE_STAGE; + assign memory_REGFILE_WRITE_VALID = execute_to_memory_REGFILE_WRITE_VALID; + assign memory_BYPASSABLE_MEMORY_STAGE = execute_to_memory_BYPASSABLE_MEMORY_STAGE; + assign writeBack_REGFILE_WRITE_VALID = memory_to_writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + decode_RS2 = decode_RegFilePlugin_rs2Data; + if(_zz_130_)begin + if((_zz_131_ == decode_INSTRUCTION[24 : 20]))begin + decode_RS2 = _zz_132_; + end + end + if(_zz_163_)begin + if(_zz_164_)begin + if(_zz_134_)begin + decode_RS2 = _zz_33_; + end + end + end + if(_zz_165_)begin + if(memory_BYPASSABLE_MEMORY_STAGE)begin + if(_zz_136_)begin + decode_RS2 = _zz_48_; + end + end + end + if(_zz_166_)begin + if(execute_BYPASSABLE_EXECUTE_STAGE)begin + if(_zz_138_)begin + decode_RS2 = _zz_44_; + end + end + end + end + + always @ (*) begin + decode_RS1 = decode_RegFilePlugin_rs1Data; + if(_zz_130_)begin + if((_zz_131_ == decode_INSTRUCTION[19 : 15]))begin + decode_RS1 = _zz_132_; + end + end + if(_zz_163_)begin + if(_zz_164_)begin + if(_zz_133_)begin + decode_RS1 = _zz_33_; + end + end + end + if(_zz_165_)begin + if(memory_BYPASSABLE_MEMORY_STAGE)begin + if(_zz_135_)begin + decode_RS1 = _zz_48_; + end + end + end + if(_zz_166_)begin + if(execute_BYPASSABLE_EXECUTE_STAGE)begin + if(_zz_137_)begin + decode_RS1 = _zz_44_; + end + end + end + end + + assign execute_SHIFT_RIGHT = _zz_208_; + assign execute_SHIFT_CTRL = _zz_27_; + assign execute_SRC_LESS_UNSIGNED = decode_to_execute_SRC_LESS_UNSIGNED; + assign execute_SRC2_FORCE_ZERO = decode_to_execute_SRC2_FORCE_ZERO; + assign execute_SRC_USE_SUB_LESS = decode_to_execute_SRC_USE_SUB_LESS; + assign _zz_28_ = execute_PC; + assign execute_SRC2_CTRL = _zz_29_; + assign execute_IS_RVC = decode_to_execute_IS_RVC; + assign execute_SRC1_CTRL = _zz_30_; + assign decode_SRC_USE_SUB_LESS = _zz_210_[0]; + assign decode_SRC_ADD_ZERO = _zz_211_[0]; + assign execute_SRC_ADD_SUB = execute_SrcPlugin_addSub; + assign execute_SRC_LESS = execute_SrcPlugin_less; + assign execute_ALU_CTRL = _zz_31_; + assign execute_SRC2 = _zz_125_; + assign execute_ALU_BITWISE_CTRL = _zz_32_; + assign _zz_33_ = writeBack_REGFILE_WRITE_DATA; + assign _zz_34_ = writeBack_INSTRUCTION; + assign _zz_35_ = writeBack_REGFILE_WRITE_VALID; + always @ (*) begin + _zz_36_ = 1'b0; + if(lastStageRegFileWrite_valid)begin + _zz_36_ = 1'b1; + end + end + + assign decode_INSTRUCTION_ANTICIPATED = (decode_arbitration_isStuck ? decode_INSTRUCTION : IBusSimplePlugin_decompressor_output_payload_rsp_inst); + always @ (*) begin + decode_REGFILE_WRITE_VALID = _zz_212_[0]; + if((decode_INSTRUCTION[11 : 7] == 5'h0))begin + decode_REGFILE_WRITE_VALID = 1'b0; + end + if(decode_INSTRUCTION[11])begin + decode_REGFILE_WRITE_VALID = 1'b0; + end + end + + always @ (*) begin + _zz_44_ = execute_REGFILE_WRITE_DATA; + if(_zz_167_)begin + _zz_44_ = execute_CsrPlugin_readData; + end + if(execute_arbitration_isValid)begin + case(execute_SHIFT_CTRL) + `ShiftCtrlEnum_defaultEncoding_SLL_1 : begin + _zz_44_ = _zz_127_; + end + `ShiftCtrlEnum_defaultEncoding_SRL_1, `ShiftCtrlEnum_defaultEncoding_SRA_1 : begin + _zz_44_ = execute_SHIFT_RIGHT; + end + default : begin + end + endcase + end + end + + assign execute_SRC1 = _zz_120_; + assign execute_CSR_READ_OPCODE = decode_to_execute_CSR_READ_OPCODE; + assign execute_CSR_WRITE_OPCODE = decode_to_execute_CSR_WRITE_OPCODE; + assign execute_IS_CSR = decode_to_execute_IS_CSR; + assign memory_ENV_CTRL = _zz_45_; + assign execute_ENV_CTRL = _zz_46_; + assign writeBack_ENV_CTRL = _zz_47_; + always @ (*) begin + _zz_48_ = memory_REGFILE_WRITE_DATA; + if((memory_arbitration_isValid && memory_MEMORY_ENABLE))begin + _zz_48_ = memory_DBusSimplePlugin_rspFormated; + end + if(_zz_168_)begin + _zz_48_ = ((memory_INSTRUCTION[13 : 12] == (2'b00)) ? memory_MulDivIterativePlugin_accumulator[31 : 0] : memory_MulDivIterativePlugin_accumulator[63 : 32]); + end + if(_zz_169_)begin + _zz_48_ = memory_MulDivIterativePlugin_div_result; + end + end + + assign memory_INSTRUCTION = execute_to_memory_INSTRUCTION; + assign memory_MEMORY_ADDRESS_LOW = execute_to_memory_MEMORY_ADDRESS_LOW; + assign memory_MEMORY_READ_DATA = dBus_rsp_data; + assign memory_MEMORY_STORE = execute_to_memory_MEMORY_STORE; + assign memory_MEMORY_ENABLE = execute_to_memory_MEMORY_ENABLE; + assign execute_SRC_ADD = execute_SrcPlugin_addSub; + assign execute_RS2 = decode_to_execute_RS2; + assign execute_INSTRUCTION = decode_to_execute_INSTRUCTION; + assign execute_MEMORY_STORE = decode_to_execute_MEMORY_STORE; + assign execute_MEMORY_ENABLE = decode_to_execute_MEMORY_ENABLE; + assign execute_ALIGNEMENT_FAULT = 1'b0; + always @ (*) begin + _zz_49_ = execute_FORMAL_PC_NEXT; + if(BranchPlugin_jumpInterface_valid)begin + _zz_49_ = BranchPlugin_jumpInterface_payload; + end + end + + assign decode_PC = IBusSimplePlugin_decodePc_pcReg; + assign decode_INSTRUCTION = IBusSimplePlugin_injector_decodeInput_payload_rsp_inst; + assign decode_IS_RVC = IBusSimplePlugin_injector_decodeInput_payload_isRvc; + assign writeBack_PC = memory_to_writeBack_PC; + assign writeBack_INSTRUCTION = memory_to_writeBack_INSTRUCTION; + assign decode_arbitration_haltItself = 1'b0; + always @ (*) begin + decode_arbitration_haltByOther = 1'b0; + if(CsrPlugin_pipelineLiberator_active)begin + decode_arbitration_haltByOther = 1'b1; + end + if(({(writeBack_arbitration_isValid && (writeBack_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)),{(memory_arbitration_isValid && (memory_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)),(execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET))}} != (3'b000)))begin + decode_arbitration_haltByOther = 1'b1; + end + if((decode_arbitration_isValid && (_zz_128_ || _zz_129_)))begin + decode_arbitration_haltByOther = 1'b1; + end + end + + always @ (*) begin + decode_arbitration_removeIt = 1'b0; + if(decode_arbitration_isFlushed)begin + decode_arbitration_removeIt = 1'b1; + end + end + + assign decode_arbitration_flushIt = 1'b0; + assign decode_arbitration_flushNext = 1'b0; + always @ (*) begin + execute_arbitration_haltItself = 1'b0; + if(((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! dBus_cmd_ready)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_93_)))begin + execute_arbitration_haltItself = 1'b1; + end + if(_zz_167_)begin + if(execute_CsrPlugin_blockedBySideEffects)begin + execute_arbitration_haltItself = 1'b1; + end + end + end + + assign execute_arbitration_haltByOther = 1'b0; + always @ (*) begin + execute_arbitration_removeIt = 1'b0; + if(execute_arbitration_isFlushed)begin + execute_arbitration_removeIt = 1'b1; + end + end + + assign execute_arbitration_flushIt = 1'b0; + always @ (*) begin + execute_arbitration_flushNext = 1'b0; + if(BranchPlugin_jumpInterface_valid)begin + execute_arbitration_flushNext = 1'b1; + end + end + + always @ (*) begin + memory_arbitration_haltItself = 1'b0; + if((((memory_arbitration_isValid && memory_MEMORY_ENABLE) && (! memory_MEMORY_STORE)) && ((! dBus_rsp_ready) || 1'b0)))begin + memory_arbitration_haltItself = 1'b1; + end + if(_zz_168_)begin + if(((! memory_MulDivIterativePlugin_frontendOk) || (! memory_MulDivIterativePlugin_mul_counter_willOverflowIfInc)))begin + memory_arbitration_haltItself = 1'b1; + end + if(_zz_170_)begin + memory_arbitration_haltItself = 1'b1; + end + end + if(_zz_169_)begin + if(((! memory_MulDivIterativePlugin_frontendOk) || (! memory_MulDivIterativePlugin_div_done)))begin + memory_arbitration_haltItself = 1'b1; + end + end + end + + assign memory_arbitration_haltByOther = 1'b0; + always @ (*) begin + memory_arbitration_removeIt = 1'b0; + if(memory_arbitration_isFlushed)begin + memory_arbitration_removeIt = 1'b1; + end + end + + assign memory_arbitration_flushIt = 1'b0; + assign memory_arbitration_flushNext = 1'b0; + assign writeBack_arbitration_haltItself = 1'b0; + assign writeBack_arbitration_haltByOther = 1'b0; + always @ (*) begin + writeBack_arbitration_removeIt = 1'b0; + if(writeBack_arbitration_isFlushed)begin + writeBack_arbitration_removeIt = 1'b1; + end + end + + assign writeBack_arbitration_flushIt = 1'b0; + always @ (*) begin + writeBack_arbitration_flushNext = 1'b0; + if(_zz_171_)begin + writeBack_arbitration_flushNext = 1'b1; + end + if(_zz_172_)begin + writeBack_arbitration_flushNext = 1'b1; + end + end + + assign lastStageInstruction = writeBack_INSTRUCTION; + assign lastStagePc = writeBack_PC; + assign lastStageIsValid = writeBack_arbitration_isValid; + assign lastStageIsFiring = writeBack_arbitration_isFiring; + always @ (*) begin + IBusSimplePlugin_fetcherHalt = 1'b0; + if(_zz_171_)begin + IBusSimplePlugin_fetcherHalt = 1'b1; + end + if(_zz_172_)begin + IBusSimplePlugin_fetcherHalt = 1'b1; + end + end + + always @ (*) begin + IBusSimplePlugin_incomingInstruction = 1'b0; + if((IBusSimplePlugin_iBusRsp_stages_1_input_valid || IBusSimplePlugin_iBusRsp_stages_2_input_valid))begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_incomingInstruction = 1'b1; + end + end + + assign CsrPlugin_inWfi = 1'b0; + assign CsrPlugin_thirdPartyWake = 1'b0; + always @ (*) begin + CsrPlugin_jumpInterface_valid = 1'b0; + if(_zz_171_)begin + CsrPlugin_jumpInterface_valid = 1'b1; + end + if(_zz_172_)begin + CsrPlugin_jumpInterface_valid = 1'b1; + end + end + + always @ (*) begin + CsrPlugin_jumpInterface_payload = 32'h0; + if(_zz_171_)begin + CsrPlugin_jumpInterface_payload = {CsrPlugin_xtvec_base,(2'b00)}; + end + if(_zz_172_)begin + case(_zz_173_) + 2'b11 : begin + CsrPlugin_jumpInterface_payload = CsrPlugin_mepc; + end + default : begin + end + endcase + end + end + + assign CsrPlugin_forceMachineWire = 1'b0; + assign CsrPlugin_allowInterrupts = 1'b1; + assign CsrPlugin_allowException = 1'b1; + assign IBusSimplePlugin_externalFlush = ({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,{execute_arbitration_flushNext,decode_arbitration_flushNext}}} != (4'b0000)); + assign IBusSimplePlugin_jump_pcLoad_valid = ({BranchPlugin_jumpInterface_valid,CsrPlugin_jumpInterface_valid} != (2'b00)); + assign _zz_50_ = {BranchPlugin_jumpInterface_valid,CsrPlugin_jumpInterface_valid}; + assign IBusSimplePlugin_jump_pcLoad_payload = (_zz_213_[0] ? CsrPlugin_jumpInterface_payload : BranchPlugin_jumpInterface_payload); + always @ (*) begin + IBusSimplePlugin_fetchPc_correction = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_correction = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_corrected = (IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_correctionReg); + always @ (*) begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b0; + if(IBusSimplePlugin_iBusRsp_stages_1_input_ready)begin + IBusSimplePlugin_fetchPc_pcRegPropagate = 1'b1; + end + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_pc = (IBusSimplePlugin_fetchPc_pcReg + _zz_216_); + if(IBusSimplePlugin_fetchPc_inc)begin + IBusSimplePlugin_fetchPc_pc[1] = 1'b0; + end + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_pc = IBusSimplePlugin_jump_pcLoad_payload; + end + IBusSimplePlugin_fetchPc_pc[0] = 1'b0; + end + + always @ (*) begin + IBusSimplePlugin_fetchPc_flushed = 1'b0; + if(IBusSimplePlugin_jump_pcLoad_valid)begin + IBusSimplePlugin_fetchPc_flushed = 1'b1; + end + end + + assign IBusSimplePlugin_fetchPc_output_valid = ((! IBusSimplePlugin_fetcherHalt) && IBusSimplePlugin_fetchPc_booted); + assign IBusSimplePlugin_fetchPc_output_payload = IBusSimplePlugin_fetchPc_pc; + always @ (*) begin + IBusSimplePlugin_decodePc_flushed = 1'b0; + if(_zz_174_)begin + IBusSimplePlugin_decodePc_flushed = 1'b1; + end + end + + assign IBusSimplePlugin_decodePc_pcPlus = (IBusSimplePlugin_decodePc_pcReg + _zz_218_); + assign IBusSimplePlugin_decodePc_injectedDecode = 1'b0; + assign IBusSimplePlugin_iBusRsp_redoFetch = 1'b0; + assign IBusSimplePlugin_iBusRsp_stages_0_input_valid = IBusSimplePlugin_fetchPc_output_valid; + assign IBusSimplePlugin_fetchPc_output_ready = IBusSimplePlugin_iBusRsp_stages_0_input_ready; + assign IBusSimplePlugin_iBusRsp_stages_0_input_payload = IBusSimplePlugin_fetchPc_output_payload; + assign IBusSimplePlugin_iBusRsp_stages_0_halt = 1'b0; + assign _zz_51_ = (! IBusSimplePlugin_iBusRsp_stages_0_halt); + assign IBusSimplePlugin_iBusRsp_stages_0_input_ready = (IBusSimplePlugin_iBusRsp_stages_0_output_ready && _zz_51_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_valid = (IBusSimplePlugin_iBusRsp_stages_0_input_valid && _zz_51_); + assign IBusSimplePlugin_iBusRsp_stages_0_output_payload = IBusSimplePlugin_iBusRsp_stages_0_input_payload; + always @ (*) begin + IBusSimplePlugin_iBusRsp_stages_1_halt = 1'b0; + if((IBusSimplePlugin_iBusRsp_stages_1_input_valid && ((! IBusSimplePlugin_cmdFork_canEmit) || (! IBusSimplePlugin_cmd_ready))))begin + IBusSimplePlugin_iBusRsp_stages_1_halt = 1'b1; + end + end + + assign _zz_52_ = (! IBusSimplePlugin_iBusRsp_stages_1_halt); + assign IBusSimplePlugin_iBusRsp_stages_1_input_ready = (IBusSimplePlugin_iBusRsp_stages_1_output_ready && _zz_52_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_valid = (IBusSimplePlugin_iBusRsp_stages_1_input_valid && _zz_52_); + assign IBusSimplePlugin_iBusRsp_stages_1_output_payload = IBusSimplePlugin_iBusRsp_stages_1_input_payload; + assign IBusSimplePlugin_iBusRsp_stages_2_halt = 1'b0; + assign _zz_53_ = (! IBusSimplePlugin_iBusRsp_stages_2_halt); + assign IBusSimplePlugin_iBusRsp_stages_2_input_ready = (IBusSimplePlugin_iBusRsp_stages_2_output_ready && _zz_53_); + assign IBusSimplePlugin_iBusRsp_stages_2_output_valid = (IBusSimplePlugin_iBusRsp_stages_2_input_valid && _zz_53_); + assign IBusSimplePlugin_iBusRsp_stages_2_output_payload = IBusSimplePlugin_iBusRsp_stages_2_input_payload; + assign IBusSimplePlugin_iBusRsp_flush = (IBusSimplePlugin_externalFlush || IBusSimplePlugin_iBusRsp_redoFetch); + assign IBusSimplePlugin_iBusRsp_stages_0_output_ready = _zz_54_; + assign _zz_54_ = ((1'b0 && (! _zz_55_)) || IBusSimplePlugin_iBusRsp_stages_1_input_ready); + assign _zz_55_ = _zz_56_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_valid = _zz_55_; + assign IBusSimplePlugin_iBusRsp_stages_1_input_payload = IBusSimplePlugin_fetchPc_pcReg; + assign IBusSimplePlugin_iBusRsp_stages_1_output_ready = ((1'b0 && (! _zz_57_)) || IBusSimplePlugin_iBusRsp_stages_2_input_ready); + assign _zz_57_ = _zz_58_; + assign IBusSimplePlugin_iBusRsp_stages_2_input_valid = _zz_57_; + assign IBusSimplePlugin_iBusRsp_stages_2_input_payload = _zz_59_; + always @ (*) begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b1; + if(IBusSimplePlugin_injector_decodeInput_valid)begin + IBusSimplePlugin_iBusRsp_readyForError = 1'b0; + end + end + + assign IBusSimplePlugin_decompressor_input_valid = (IBusSimplePlugin_iBusRsp_output_valid && (! IBusSimplePlugin_iBusRsp_redoFetch)); + assign IBusSimplePlugin_decompressor_input_payload_pc = IBusSimplePlugin_iBusRsp_output_payload_pc; + assign IBusSimplePlugin_decompressor_input_payload_rsp_error = IBusSimplePlugin_iBusRsp_output_payload_rsp_error; + assign IBusSimplePlugin_decompressor_input_payload_rsp_inst = IBusSimplePlugin_iBusRsp_output_payload_rsp_inst; + assign IBusSimplePlugin_decompressor_input_payload_isRvc = IBusSimplePlugin_iBusRsp_output_payload_isRvc; + assign IBusSimplePlugin_iBusRsp_output_ready = IBusSimplePlugin_decompressor_input_ready; + assign IBusSimplePlugin_decompressor_flushNext = 1'b0; + assign IBusSimplePlugin_decompressor_consumeCurrent = 1'b0; + assign IBusSimplePlugin_decompressor_isInputLowRvc = (IBusSimplePlugin_decompressor_input_payload_rsp_inst[1 : 0] != (2'b11)); + assign IBusSimplePlugin_decompressor_isInputHighRvc = (IBusSimplePlugin_decompressor_input_payload_rsp_inst[17 : 16] != (2'b11)); + assign IBusSimplePlugin_decompressor_throw2Bytes = (IBusSimplePlugin_decompressor_throw2BytesReg || IBusSimplePlugin_decompressor_input_payload_pc[1]); + assign IBusSimplePlugin_decompressor_unaligned = (IBusSimplePlugin_decompressor_throw2Bytes || IBusSimplePlugin_decompressor_bufferValid); + assign IBusSimplePlugin_decompressor_raw = (IBusSimplePlugin_decompressor_bufferValid ? {IBusSimplePlugin_decompressor_input_payload_rsp_inst[15 : 0],IBusSimplePlugin_decompressor_bufferData} : {IBusSimplePlugin_decompressor_input_payload_rsp_inst[31 : 16],(IBusSimplePlugin_decompressor_throw2Bytes ? IBusSimplePlugin_decompressor_input_payload_rsp_inst[31 : 16] : IBusSimplePlugin_decompressor_input_payload_rsp_inst[15 : 0])}); + assign IBusSimplePlugin_decompressor_isRvc = (IBusSimplePlugin_decompressor_raw[1 : 0] != (2'b11)); + assign _zz_60_ = IBusSimplePlugin_decompressor_raw[15 : 0]; + always @ (*) begin + IBusSimplePlugin_decompressor_decompressed = 32'h0; + case(_zz_188_) + 5'b00000 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{{{{{(2'b00),_zz_60_[10 : 7]},_zz_60_[12 : 11]},_zz_60_[5]},_zz_60_[6]},(2'b00)},5'h02},(3'b000)},_zz_62_},7'h13}; + end + 5'b00010 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{_zz_63_,_zz_61_},(3'b010)},_zz_62_},7'h03}; + end + 5'b00110 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{_zz_63_[11 : 5],_zz_62_},_zz_61_},(3'b010)},_zz_63_[4 : 0]},7'h23}; + end + 5'b01000 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{_zz_65_,_zz_60_[11 : 7]},(3'b000)},_zz_60_[11 : 7]},7'h13}; + end + 5'b01001 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{_zz_68_[20],_zz_68_[10 : 1]},_zz_68_[11]},_zz_68_[19 : 12]},_zz_80_},7'h6f}; + end + 5'b01010 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{_zz_65_,5'h0},(3'b000)},_zz_60_[11 : 7]},7'h13}; + end + 5'b01011 : begin + IBusSimplePlugin_decompressor_decompressed = ((_zz_60_[11 : 7] == 5'h02) ? {{{{{{{{{_zz_72_,_zz_60_[4 : 3]},_zz_60_[5]},_zz_60_[2]},_zz_60_[6]},(4'b0000)},_zz_60_[11 : 7]},(3'b000)},_zz_60_[11 : 7]},7'h13} : {{_zz_219_[31 : 12],_zz_60_[11 : 7]},7'h37}); + end + 5'b01100 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{((_zz_60_[11 : 10] == (2'b10)) ? _zz_86_ : {{(1'b0),(_zz_283_ || _zz_284_)},5'h0}),(((! _zz_60_[11]) || _zz_82_) ? _zz_60_[6 : 2] : _zz_62_)},_zz_61_},_zz_84_},_zz_61_},(_zz_82_ ? 7'h13 : 7'h33)}; + end + 5'b01101 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{_zz_75_[20],_zz_75_[10 : 1]},_zz_75_[11]},_zz_75_[19 : 12]},_zz_79_},7'h6f}; + end + 5'b01110 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{{{_zz_78_[12],_zz_78_[10 : 5]},_zz_79_},_zz_61_},(3'b000)},_zz_78_[4 : 1]},_zz_78_[11]},7'h63}; + end + 5'b01111 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{{{_zz_78_[12],_zz_78_[10 : 5]},_zz_79_},_zz_61_},(3'b001)},_zz_78_[4 : 1]},_zz_78_[11]},7'h63}; + end + 5'b10000 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{7'h0,_zz_60_[6 : 2]},_zz_60_[11 : 7]},(3'b001)},_zz_60_[11 : 7]},7'h13}; + end + 5'b10010 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{{{{(4'b0000),_zz_60_[3 : 2]},_zz_60_[12]},_zz_60_[6 : 4]},(2'b00)},_zz_81_},(3'b010)},_zz_60_[11 : 7]},7'h03}; + end + 5'b10100 : begin + IBusSimplePlugin_decompressor_decompressed = ((_zz_60_[12 : 2] == 11'h400) ? 32'h00100073 : ((_zz_60_[6 : 2] == 5'h0) ? {{{{12'h0,_zz_60_[11 : 7]},(3'b000)},(_zz_60_[12] ? _zz_80_ : _zz_79_)},7'h67} : {{{{{_zz_285_,_zz_286_},(_zz_287_ ? _zz_288_ : _zz_79_)},(3'b000)},_zz_60_[11 : 7]},7'h33})); + end + 5'b10110 : begin + IBusSimplePlugin_decompressor_decompressed = {{{{{_zz_220_[11 : 5],_zz_60_[6 : 2]},_zz_81_},(3'b010)},_zz_221_[4 : 0]},7'h23}; + end + default : begin + end + endcase + end + + assign _zz_61_ = {(2'b01),_zz_60_[9 : 7]}; + assign _zz_62_ = {(2'b01),_zz_60_[4 : 2]}; + assign _zz_63_ = {{{{5'h0,_zz_60_[5]},_zz_60_[12 : 10]},_zz_60_[6]},(2'b00)}; + assign _zz_64_ = _zz_60_[12]; + always @ (*) begin + _zz_65_[11] = _zz_64_; + _zz_65_[10] = _zz_64_; + _zz_65_[9] = _zz_64_; + _zz_65_[8] = _zz_64_; + _zz_65_[7] = _zz_64_; + _zz_65_[6] = _zz_64_; + _zz_65_[5] = _zz_64_; + _zz_65_[4 : 0] = _zz_60_[6 : 2]; + end + + assign _zz_66_ = _zz_60_[12]; + always @ (*) begin + _zz_67_[9] = _zz_66_; + _zz_67_[8] = _zz_66_; + _zz_67_[7] = _zz_66_; + _zz_67_[6] = _zz_66_; + _zz_67_[5] = _zz_66_; + _zz_67_[4] = _zz_66_; + _zz_67_[3] = _zz_66_; + _zz_67_[2] = _zz_66_; + _zz_67_[1] = _zz_66_; + _zz_67_[0] = _zz_66_; + end + + assign _zz_68_ = {{{{{{{{_zz_67_,_zz_60_[8]},_zz_60_[10 : 9]},_zz_60_[6]},_zz_60_[7]},_zz_60_[2]},_zz_60_[11]},_zz_60_[5 : 3]},(1'b0)}; + assign _zz_69_ = _zz_60_[12]; + always @ (*) begin + _zz_70_[14] = _zz_69_; + _zz_70_[13] = _zz_69_; + _zz_70_[12] = _zz_69_; + _zz_70_[11] = _zz_69_; + _zz_70_[10] = _zz_69_; + _zz_70_[9] = _zz_69_; + _zz_70_[8] = _zz_69_; + _zz_70_[7] = _zz_69_; + _zz_70_[6] = _zz_69_; + _zz_70_[5] = _zz_69_; + _zz_70_[4] = _zz_69_; + _zz_70_[3] = _zz_69_; + _zz_70_[2] = _zz_69_; + _zz_70_[1] = _zz_69_; + _zz_70_[0] = _zz_69_; + end + + assign _zz_71_ = _zz_60_[12]; + always @ (*) begin + _zz_72_[2] = _zz_71_; + _zz_72_[1] = _zz_71_; + _zz_72_[0] = _zz_71_; + end + + assign _zz_73_ = _zz_60_[12]; + always @ (*) begin + _zz_74_[9] = _zz_73_; + _zz_74_[8] = _zz_73_; + _zz_74_[7] = _zz_73_; + _zz_74_[6] = _zz_73_; + _zz_74_[5] = _zz_73_; + _zz_74_[4] = _zz_73_; + _zz_74_[3] = _zz_73_; + _zz_74_[2] = _zz_73_; + _zz_74_[1] = _zz_73_; + _zz_74_[0] = _zz_73_; + end + + assign _zz_75_ = {{{{{{{{_zz_74_,_zz_60_[8]},_zz_60_[10 : 9]},_zz_60_[6]},_zz_60_[7]},_zz_60_[2]},_zz_60_[11]},_zz_60_[5 : 3]},(1'b0)}; + assign _zz_76_ = _zz_60_[12]; + always @ (*) begin + _zz_77_[4] = _zz_76_; + _zz_77_[3] = _zz_76_; + _zz_77_[2] = _zz_76_; + _zz_77_[1] = _zz_76_; + _zz_77_[0] = _zz_76_; + end + + assign _zz_78_ = {{{{{_zz_77_,_zz_60_[6 : 5]},_zz_60_[2]},_zz_60_[11 : 10]},_zz_60_[4 : 3]},(1'b0)}; + assign _zz_79_ = 5'h0; + assign _zz_80_ = 5'h01; + assign _zz_81_ = 5'h02; + assign _zz_82_ = (_zz_60_[11 : 10] != (2'b11)); + always @ (*) begin + case(_zz_189_) + 2'b00 : begin + _zz_83_ = (3'b000); + end + 2'b01 : begin + _zz_83_ = (3'b100); + end + 2'b10 : begin + _zz_83_ = (3'b110); + end + default : begin + _zz_83_ = (3'b111); + end + endcase + end + + always @ (*) begin + case(_zz_190_) + 2'b00 : begin + _zz_84_ = (3'b101); + end + 2'b01 : begin + _zz_84_ = (3'b101); + end + 2'b10 : begin + _zz_84_ = (3'b111); + end + default : begin + _zz_84_ = _zz_83_; + end + endcase + end + + assign _zz_85_ = _zz_60_[12]; + always @ (*) begin + _zz_86_[6] = _zz_85_; + _zz_86_[5] = _zz_85_; + _zz_86_[4] = _zz_85_; + _zz_86_[3] = _zz_85_; + _zz_86_[2] = _zz_85_; + _zz_86_[1] = _zz_85_; + _zz_86_[0] = _zz_85_; + end + + assign IBusSimplePlugin_decompressor_output_valid = (IBusSimplePlugin_decompressor_input_valid && (! ((IBusSimplePlugin_decompressor_throw2Bytes && (! IBusSimplePlugin_decompressor_bufferValid)) && (! IBusSimplePlugin_decompressor_isInputHighRvc)))); + assign IBusSimplePlugin_decompressor_output_payload_pc = IBusSimplePlugin_decompressor_input_payload_pc; + assign IBusSimplePlugin_decompressor_output_payload_isRvc = IBusSimplePlugin_decompressor_isRvc; + assign IBusSimplePlugin_decompressor_output_payload_rsp_inst = (IBusSimplePlugin_decompressor_isRvc ? IBusSimplePlugin_decompressor_decompressed : IBusSimplePlugin_decompressor_raw); + assign IBusSimplePlugin_decompressor_input_ready = (IBusSimplePlugin_decompressor_output_ready && (((! IBusSimplePlugin_iBusRsp_stages_2_input_valid) || IBusSimplePlugin_decompressor_flushNext) || ((! (IBusSimplePlugin_decompressor_bufferValid && IBusSimplePlugin_decompressor_isInputHighRvc)) && (! (((! IBusSimplePlugin_decompressor_unaligned) && IBusSimplePlugin_decompressor_isInputLowRvc) && IBusSimplePlugin_decompressor_isInputHighRvc))))); + assign IBusSimplePlugin_decompressor_bufferFill = (((((! IBusSimplePlugin_decompressor_unaligned) && IBusSimplePlugin_decompressor_isInputLowRvc) && (! IBusSimplePlugin_decompressor_isInputHighRvc)) || (IBusSimplePlugin_decompressor_bufferValid && (! IBusSimplePlugin_decompressor_isInputHighRvc))) || ((IBusSimplePlugin_decompressor_throw2Bytes && (! IBusSimplePlugin_decompressor_isRvc)) && (! IBusSimplePlugin_decompressor_isInputHighRvc))); + assign IBusSimplePlugin_decompressor_output_ready = ((1'b0 && (! IBusSimplePlugin_injector_decodeInput_valid)) || IBusSimplePlugin_injector_decodeInput_ready); + assign IBusSimplePlugin_injector_decodeInput_valid = _zz_87_; + assign IBusSimplePlugin_injector_decodeInput_payload_pc = _zz_88_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_error = _zz_89_; + assign IBusSimplePlugin_injector_decodeInput_payload_rsp_inst = _zz_90_; + assign IBusSimplePlugin_injector_decodeInput_payload_isRvc = _zz_91_; + assign IBusSimplePlugin_pcValids_0 = IBusSimplePlugin_injector_nextPcCalc_valids_0; + assign IBusSimplePlugin_pcValids_1 = IBusSimplePlugin_injector_nextPcCalc_valids_1; + assign IBusSimplePlugin_pcValids_2 = IBusSimplePlugin_injector_nextPcCalc_valids_2; + assign IBusSimplePlugin_pcValids_3 = IBusSimplePlugin_injector_nextPcCalc_valids_3; + assign IBusSimplePlugin_injector_decodeInput_ready = (! decode_arbitration_isStuck); + assign decode_arbitration_isValid = IBusSimplePlugin_injector_decodeInput_valid; + assign iBus_cmd_valid = IBusSimplePlugin_cmd_valid; + assign IBusSimplePlugin_cmd_ready = iBus_cmd_ready; + assign iBus_cmd_payload_pc = IBusSimplePlugin_cmd_payload_pc; + assign IBusSimplePlugin_pending_next = (_zz_222_ - _zz_226_); + assign IBusSimplePlugin_cmdFork_canEmit = (IBusSimplePlugin_iBusRsp_stages_1_output_ready && (IBusSimplePlugin_pending_value != (3'b111))); + assign IBusSimplePlugin_cmd_valid = (IBusSimplePlugin_iBusRsp_stages_1_input_valid && IBusSimplePlugin_cmdFork_canEmit); + assign IBusSimplePlugin_pending_inc = (IBusSimplePlugin_cmd_valid && IBusSimplePlugin_cmd_ready); + assign IBusSimplePlugin_cmd_payload_pc = {IBusSimplePlugin_iBusRsp_stages_1_input_payload[31 : 2],(2'b00)}; + assign IBusSimplePlugin_rspJoin_rspBuffer_flush = ((IBusSimplePlugin_rspJoin_rspBuffer_discardCounter != (3'b000)) || IBusSimplePlugin_iBusRsp_flush); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_valid = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter == (3'b000))); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_error; + assign IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst = IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_payload_inst; + assign _zz_159_ = (IBusSimplePlugin_rspJoin_rspBuffer_output_ready || IBusSimplePlugin_rspJoin_rspBuffer_flush); + assign IBusSimplePlugin_pending_dec = (IBusSimplePlugin_rspJoin_rspBuffer_c_io_pop_valid && _zz_159_); + assign IBusSimplePlugin_rspJoin_fetchRsp_pc = IBusSimplePlugin_iBusRsp_stages_2_output_payload; + always @ (*) begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_error; + if((! IBusSimplePlugin_rspJoin_rspBuffer_output_valid))begin + IBusSimplePlugin_rspJoin_fetchRsp_rsp_error = 1'b0; + end + end + + assign IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst = IBusSimplePlugin_rspJoin_rspBuffer_output_payload_inst; + assign IBusSimplePlugin_rspJoin_exceptionDetected = 1'b0; + assign IBusSimplePlugin_rspJoin_join_valid = (IBusSimplePlugin_iBusRsp_stages_2_output_valid && IBusSimplePlugin_rspJoin_rspBuffer_output_valid); + assign IBusSimplePlugin_rspJoin_join_payload_pc = IBusSimplePlugin_rspJoin_fetchRsp_pc; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_error = IBusSimplePlugin_rspJoin_fetchRsp_rsp_error; + assign IBusSimplePlugin_rspJoin_join_payload_rsp_inst = IBusSimplePlugin_rspJoin_fetchRsp_rsp_inst; + assign IBusSimplePlugin_rspJoin_join_payload_isRvc = IBusSimplePlugin_rspJoin_fetchRsp_isRvc; + assign IBusSimplePlugin_iBusRsp_stages_2_output_ready = (IBusSimplePlugin_iBusRsp_stages_2_output_valid ? (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready) : IBusSimplePlugin_rspJoin_join_ready); + assign IBusSimplePlugin_rspJoin_rspBuffer_output_ready = (IBusSimplePlugin_rspJoin_join_valid && IBusSimplePlugin_rspJoin_join_ready); + assign _zz_92_ = (! IBusSimplePlugin_rspJoin_exceptionDetected); + assign IBusSimplePlugin_rspJoin_join_ready = (IBusSimplePlugin_iBusRsp_output_ready && _zz_92_); + assign IBusSimplePlugin_iBusRsp_output_valid = (IBusSimplePlugin_rspJoin_join_valid && _zz_92_); + assign IBusSimplePlugin_iBusRsp_output_payload_pc = IBusSimplePlugin_rspJoin_join_payload_pc; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_error = IBusSimplePlugin_rspJoin_join_payload_rsp_error; + assign IBusSimplePlugin_iBusRsp_output_payload_rsp_inst = IBusSimplePlugin_rspJoin_join_payload_rsp_inst; + assign IBusSimplePlugin_iBusRsp_output_payload_isRvc = IBusSimplePlugin_rspJoin_join_payload_isRvc; + assign _zz_93_ = 1'b0; + always @ (*) begin + execute_DBusSimplePlugin_skipCmd = 1'b0; + if(execute_ALIGNEMENT_FAULT)begin + execute_DBusSimplePlugin_skipCmd = 1'b1; + end + end + + assign dBus_cmd_valid = (((((execute_arbitration_isValid && execute_MEMORY_ENABLE) && (! execute_arbitration_isStuckByOthers)) && (! execute_arbitration_isFlushed)) && (! execute_DBusSimplePlugin_skipCmd)) && (! _zz_93_)); + assign dBus_cmd_payload_wr = execute_MEMORY_STORE; + assign dBus_cmd_payload_size = execute_INSTRUCTION[13 : 12]; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_94_ = {{{execute_RS2[7 : 0],execute_RS2[7 : 0]},execute_RS2[7 : 0]},execute_RS2[7 : 0]}; + end + 2'b01 : begin + _zz_94_ = {execute_RS2[15 : 0],execute_RS2[15 : 0]}; + end + default : begin + _zz_94_ = execute_RS2[31 : 0]; + end + endcase + end + + assign dBus_cmd_payload_data = _zz_94_; + always @ (*) begin + case(dBus_cmd_payload_size) + 2'b00 : begin + _zz_95_ = (4'b0001); + end + 2'b01 : begin + _zz_95_ = (4'b0011); + end + default : begin + _zz_95_ = (4'b1111); + end + endcase + end + + assign execute_DBusSimplePlugin_formalMask = (_zz_95_ <<< dBus_cmd_payload_address[1 : 0]); + assign dBus_cmd_payload_address = execute_SRC_ADD; + always @ (*) begin + memory_DBusSimplePlugin_rspShifted = memory_MEMORY_READ_DATA; + case(memory_MEMORY_ADDRESS_LOW) + 2'b01 : begin + memory_DBusSimplePlugin_rspShifted[7 : 0] = memory_MEMORY_READ_DATA[15 : 8]; + end + 2'b10 : begin + memory_DBusSimplePlugin_rspShifted[15 : 0] = memory_MEMORY_READ_DATA[31 : 16]; + end + 2'b11 : begin + memory_DBusSimplePlugin_rspShifted[7 : 0] = memory_MEMORY_READ_DATA[31 : 24]; + end + default : begin + end + endcase + end + + assign _zz_96_ = (memory_DBusSimplePlugin_rspShifted[7] && (! memory_INSTRUCTION[14])); + always @ (*) begin + _zz_97_[31] = _zz_96_; + _zz_97_[30] = _zz_96_; + _zz_97_[29] = _zz_96_; + _zz_97_[28] = _zz_96_; + _zz_97_[27] = _zz_96_; + _zz_97_[26] = _zz_96_; + _zz_97_[25] = _zz_96_; + _zz_97_[24] = _zz_96_; + _zz_97_[23] = _zz_96_; + _zz_97_[22] = _zz_96_; + _zz_97_[21] = _zz_96_; + _zz_97_[20] = _zz_96_; + _zz_97_[19] = _zz_96_; + _zz_97_[18] = _zz_96_; + _zz_97_[17] = _zz_96_; + _zz_97_[16] = _zz_96_; + _zz_97_[15] = _zz_96_; + _zz_97_[14] = _zz_96_; + _zz_97_[13] = _zz_96_; + _zz_97_[12] = _zz_96_; + _zz_97_[11] = _zz_96_; + _zz_97_[10] = _zz_96_; + _zz_97_[9] = _zz_96_; + _zz_97_[8] = _zz_96_; + _zz_97_[7 : 0] = memory_DBusSimplePlugin_rspShifted[7 : 0]; + end + + assign _zz_98_ = (memory_DBusSimplePlugin_rspShifted[15] && (! memory_INSTRUCTION[14])); + always @ (*) begin + _zz_99_[31] = _zz_98_; + _zz_99_[30] = _zz_98_; + _zz_99_[29] = _zz_98_; + _zz_99_[28] = _zz_98_; + _zz_99_[27] = _zz_98_; + _zz_99_[26] = _zz_98_; + _zz_99_[25] = _zz_98_; + _zz_99_[24] = _zz_98_; + _zz_99_[23] = _zz_98_; + _zz_99_[22] = _zz_98_; + _zz_99_[21] = _zz_98_; + _zz_99_[20] = _zz_98_; + _zz_99_[19] = _zz_98_; + _zz_99_[18] = _zz_98_; + _zz_99_[17] = _zz_98_; + _zz_99_[16] = _zz_98_; + _zz_99_[15 : 0] = memory_DBusSimplePlugin_rspShifted[15 : 0]; + end + + always @ (*) begin + case(_zz_191_) + 2'b00 : begin + memory_DBusSimplePlugin_rspFormated = _zz_97_; + end + 2'b01 : begin + memory_DBusSimplePlugin_rspFormated = _zz_99_; + end + default : begin + memory_DBusSimplePlugin_rspFormated = memory_DBusSimplePlugin_rspShifted; + end + endcase + end + + always @ (*) begin + CsrPlugin_privilege = (2'b11); + if(CsrPlugin_forceMachineWire)begin + CsrPlugin_privilege = (2'b11); + end + end + + assign CsrPlugin_misa_base = (2'b01); + assign CsrPlugin_misa_extensions = 26'h0000042; + assign CsrPlugin_mtvec_mode = (2'b00); + assign CsrPlugin_mtvec_base = 30'h00000001; + assign _zz_100_ = (CsrPlugin_mip_MTIP && CsrPlugin_mie_MTIE); + assign _zz_101_ = (CsrPlugin_mip_MSIP && CsrPlugin_mie_MSIE); + assign _zz_102_ = (CsrPlugin_mip_MEIP && CsrPlugin_mie_MEIE); + assign CsrPlugin_exception = 1'b0; + assign CsrPlugin_lastStageWasWfi = 1'b0; + assign CsrPlugin_pipelineLiberator_active = ((CsrPlugin_interrupt_valid && CsrPlugin_allowInterrupts) && decode_arbitration_isValid); + always @ (*) begin + CsrPlugin_pipelineLiberator_done = CsrPlugin_pipelineLiberator_pcValids_2; + if(CsrPlugin_hadException)begin + CsrPlugin_pipelineLiberator_done = 1'b0; + end + end + + assign CsrPlugin_interruptJump = ((CsrPlugin_interrupt_valid && CsrPlugin_pipelineLiberator_done) && CsrPlugin_allowInterrupts); + assign CsrPlugin_targetPrivilege = CsrPlugin_interrupt_targetPrivilege; + assign CsrPlugin_trapCause = CsrPlugin_interrupt_code; + always @ (*) begin + CsrPlugin_xtvec_mode = (2'bxx); + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_xtvec_mode = CsrPlugin_mtvec_mode; + end + default : begin + end + endcase + end + + always @ (*) begin + CsrPlugin_xtvec_base = 30'h0; + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_xtvec_base = CsrPlugin_mtvec_base; + end + default : begin + end + endcase + end + + assign contextSwitching = CsrPlugin_jumpInterface_valid; + assign execute_CsrPlugin_blockedBySideEffects = ({writeBack_arbitration_isValid,memory_arbitration_isValid} != (2'b00)); + always @ (*) begin + execute_CsrPlugin_illegalAccess = 1'b1; + if(execute_CsrPlugin_csr_768)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + if(execute_CsrPlugin_csr_836)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + if(execute_CsrPlugin_csr_772)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + if(execute_CsrPlugin_csr_832)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + if(execute_CsrPlugin_csr_834)begin + if(execute_CSR_READ_OPCODE)begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + end + if((CsrPlugin_privilege < execute_CsrPlugin_csrAddress[9 : 8]))begin + execute_CsrPlugin_illegalAccess = 1'b1; + end + if(((! execute_arbitration_isValid) || (! execute_IS_CSR)))begin + execute_CsrPlugin_illegalAccess = 1'b0; + end + end + + always @ (*) begin + execute_CsrPlugin_illegalInstruction = 1'b0; + if((execute_arbitration_isValid && (execute_ENV_CTRL == `EnvCtrlEnum_defaultEncoding_XRET)))begin + if((CsrPlugin_privilege < execute_INSTRUCTION[29 : 28]))begin + execute_CsrPlugin_illegalInstruction = 1'b1; + end + end + end + + assign execute_CsrPlugin_writeInstruction = ((execute_arbitration_isValid && execute_IS_CSR) && execute_CSR_WRITE_OPCODE); + assign execute_CsrPlugin_readInstruction = ((execute_arbitration_isValid && execute_IS_CSR) && execute_CSR_READ_OPCODE); + assign execute_CsrPlugin_writeEnable = ((execute_CsrPlugin_writeInstruction && (! execute_CsrPlugin_blockedBySideEffects)) && (! execute_arbitration_isStuckByOthers)); + assign execute_CsrPlugin_readEnable = ((execute_CsrPlugin_readInstruction && (! execute_CsrPlugin_blockedBySideEffects)) && (! execute_arbitration_isStuckByOthers)); + assign execute_CsrPlugin_readToWriteData = execute_CsrPlugin_readData; + always @ (*) begin + case(_zz_192_) + 1'b0 : begin + execute_CsrPlugin_writeData = execute_SRC1; + end + default : begin + execute_CsrPlugin_writeData = (execute_INSTRUCTION[12] ? (execute_CsrPlugin_readToWriteData & (~ execute_SRC1)) : (execute_CsrPlugin_readToWriteData | execute_SRC1)); + end + endcase + end + + assign execute_CsrPlugin_csrAddress = execute_INSTRUCTION[31 : 20]; + assign _zz_104_ = ((decode_INSTRUCTION & 32'h00006004) == 32'h00002000); + assign _zz_105_ = ((decode_INSTRUCTION & 32'h00007000) == 32'h00001000); + assign _zz_106_ = ((decode_INSTRUCTION & 32'h00003000) == 32'h00002000); + assign _zz_107_ = ((decode_INSTRUCTION & 32'h00005000) == 32'h00004000); + assign _zz_108_ = ((decode_INSTRUCTION & 32'h00004050) == 32'h00004050); + assign _zz_109_ = ((decode_INSTRUCTION & 32'h00000048) == 32'h00000048); + assign _zz_110_ = ((decode_INSTRUCTION & 32'h00000004) == 32'h00000004); + assign _zz_103_ = {({(_zz_289_ == _zz_290_),{_zz_291_,{_zz_292_,_zz_293_}}} != (4'b0000)),{({_zz_110_,_zz_294_} != (2'b00)),{({_zz_295_,_zz_296_} != (2'b00)),{(_zz_297_ != _zz_298_),{_zz_299_,{_zz_300_,_zz_301_}}}}}}; + assign _zz_111_ = _zz_103_[3 : 2]; + assign _zz_43_ = _zz_111_; + assign _zz_112_ = _zz_103_[9 : 8]; + assign _zz_42_ = _zz_112_; + assign _zz_113_ = _zz_103_[10 : 10]; + assign _zz_41_ = _zz_113_; + assign _zz_114_ = _zz_103_[12 : 11]; + assign _zz_40_ = _zz_114_; + assign _zz_115_ = _zz_103_[15 : 14]; + assign _zz_39_ = _zz_115_; + assign _zz_116_ = _zz_103_[23 : 22]; + assign _zz_38_ = _zz_116_; + assign _zz_117_ = _zz_103_[27 : 26]; + assign _zz_37_ = _zz_117_; + assign decode_RegFilePlugin_regFileReadAddress1 = decode_INSTRUCTION_ANTICIPATED[18 : 15]; + assign decode_RegFilePlugin_regFileReadAddress2 = decode_INSTRUCTION_ANTICIPATED[23 : 20]; + assign decode_RegFilePlugin_rs1Data = _zz_161_; + assign decode_RegFilePlugin_rs2Data = _zz_162_; + always @ (*) begin + lastStageRegFileWrite_valid = (_zz_35_ && writeBack_arbitration_isFiring); + if(_zz_118_)begin + lastStageRegFileWrite_valid = 1'b1; + end + end + + assign lastStageRegFileWrite_payload_address = _zz_34_[10 : 7]; + assign lastStageRegFileWrite_payload_data = _zz_33_; + always @ (*) begin + case(execute_ALU_BITWISE_CTRL) + `AluBitwiseCtrlEnum_defaultEncoding_AND_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 & execute_SRC2); + end + `AluBitwiseCtrlEnum_defaultEncoding_OR_1 : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 | execute_SRC2); + end + default : begin + execute_IntAluPlugin_bitwise = (execute_SRC1 ^ execute_SRC2); + end + endcase + end + + always @ (*) begin + case(execute_ALU_CTRL) + `AluCtrlEnum_defaultEncoding_BITWISE : begin + _zz_119_ = execute_IntAluPlugin_bitwise; + end + `AluCtrlEnum_defaultEncoding_SLT_SLTU : begin + _zz_119_ = {31'd0, _zz_229_}; + end + default : begin + _zz_119_ = execute_SRC_ADD_SUB; + end + endcase + end + + always @ (*) begin + case(execute_SRC1_CTRL) + `Src1CtrlEnum_defaultEncoding_RS : begin + _zz_120_ = execute_RS1; + end + `Src1CtrlEnum_defaultEncoding_PC_INCREMENT : begin + _zz_120_ = {29'd0, _zz_230_}; + end + `Src1CtrlEnum_defaultEncoding_IMU : begin + _zz_120_ = {execute_INSTRUCTION[31 : 12],12'h0}; + end + default : begin + _zz_120_ = {27'd0, _zz_231_}; + end + endcase + end + + assign _zz_121_ = _zz_232_[11]; + always @ (*) begin + _zz_122_[19] = _zz_121_; + _zz_122_[18] = _zz_121_; + _zz_122_[17] = _zz_121_; + _zz_122_[16] = _zz_121_; + _zz_122_[15] = _zz_121_; + _zz_122_[14] = _zz_121_; + _zz_122_[13] = _zz_121_; + _zz_122_[12] = _zz_121_; + _zz_122_[11] = _zz_121_; + _zz_122_[10] = _zz_121_; + _zz_122_[9] = _zz_121_; + _zz_122_[8] = _zz_121_; + _zz_122_[7] = _zz_121_; + _zz_122_[6] = _zz_121_; + _zz_122_[5] = _zz_121_; + _zz_122_[4] = _zz_121_; + _zz_122_[3] = _zz_121_; + _zz_122_[2] = _zz_121_; + _zz_122_[1] = _zz_121_; + _zz_122_[0] = _zz_121_; + end + + assign _zz_123_ = _zz_233_[11]; + always @ (*) begin + _zz_124_[19] = _zz_123_; + _zz_124_[18] = _zz_123_; + _zz_124_[17] = _zz_123_; + _zz_124_[16] = _zz_123_; + _zz_124_[15] = _zz_123_; + _zz_124_[14] = _zz_123_; + _zz_124_[13] = _zz_123_; + _zz_124_[12] = _zz_123_; + _zz_124_[11] = _zz_123_; + _zz_124_[10] = _zz_123_; + _zz_124_[9] = _zz_123_; + _zz_124_[8] = _zz_123_; + _zz_124_[7] = _zz_123_; + _zz_124_[6] = _zz_123_; + _zz_124_[5] = _zz_123_; + _zz_124_[4] = _zz_123_; + _zz_124_[3] = _zz_123_; + _zz_124_[2] = _zz_123_; + _zz_124_[1] = _zz_123_; + _zz_124_[0] = _zz_123_; + end + + always @ (*) begin + case(execute_SRC2_CTRL) + `Src2CtrlEnum_defaultEncoding_RS : begin + _zz_125_ = execute_RS2; + end + `Src2CtrlEnum_defaultEncoding_IMI : begin + _zz_125_ = {_zz_122_,execute_INSTRUCTION[31 : 20]}; + end + `Src2CtrlEnum_defaultEncoding_IMS : begin + _zz_125_ = {_zz_124_,{execute_INSTRUCTION[31 : 25],execute_INSTRUCTION[11 : 7]}}; + end + default : begin + _zz_125_ = _zz_28_; + end + endcase + end + + always @ (*) begin + execute_SrcPlugin_addSub = _zz_234_; + if(execute_SRC2_FORCE_ZERO)begin + execute_SrcPlugin_addSub = execute_SRC1; + end + end + + assign execute_SrcPlugin_less = ((execute_SRC1[31] == execute_SRC2[31]) ? execute_SrcPlugin_addSub[31] : (execute_SRC_LESS_UNSIGNED ? execute_SRC2[31] : execute_SRC1[31])); + assign execute_FullBarrelShifterPlugin_amplitude = execute_SRC2[4 : 0]; + always @ (*) begin + _zz_126_[0] = execute_SRC1[31]; + _zz_126_[1] = execute_SRC1[30]; + _zz_126_[2] = execute_SRC1[29]; + _zz_126_[3] = execute_SRC1[28]; + _zz_126_[4] = execute_SRC1[27]; + _zz_126_[5] = execute_SRC1[26]; + _zz_126_[6] = execute_SRC1[25]; + _zz_126_[7] = execute_SRC1[24]; + _zz_126_[8] = execute_SRC1[23]; + _zz_126_[9] = execute_SRC1[22]; + _zz_126_[10] = execute_SRC1[21]; + _zz_126_[11] = execute_SRC1[20]; + _zz_126_[12] = execute_SRC1[19]; + _zz_126_[13] = execute_SRC1[18]; + _zz_126_[14] = execute_SRC1[17]; + _zz_126_[15] = execute_SRC1[16]; + _zz_126_[16] = execute_SRC1[15]; + _zz_126_[17] = execute_SRC1[14]; + _zz_126_[18] = execute_SRC1[13]; + _zz_126_[19] = execute_SRC1[12]; + _zz_126_[20] = execute_SRC1[11]; + _zz_126_[21] = execute_SRC1[10]; + _zz_126_[22] = execute_SRC1[9]; + _zz_126_[23] = execute_SRC1[8]; + _zz_126_[24] = execute_SRC1[7]; + _zz_126_[25] = execute_SRC1[6]; + _zz_126_[26] = execute_SRC1[5]; + _zz_126_[27] = execute_SRC1[4]; + _zz_126_[28] = execute_SRC1[3]; + _zz_126_[29] = execute_SRC1[2]; + _zz_126_[30] = execute_SRC1[1]; + _zz_126_[31] = execute_SRC1[0]; + end + + assign execute_FullBarrelShifterPlugin_reversed = ((execute_SHIFT_CTRL == `ShiftCtrlEnum_defaultEncoding_SLL_1) ? _zz_126_ : execute_SRC1); + always @ (*) begin + _zz_127_[0] = execute_SHIFT_RIGHT[31]; + _zz_127_[1] = execute_SHIFT_RIGHT[30]; + _zz_127_[2] = execute_SHIFT_RIGHT[29]; + _zz_127_[3] = execute_SHIFT_RIGHT[28]; + _zz_127_[4] = execute_SHIFT_RIGHT[27]; + _zz_127_[5] = execute_SHIFT_RIGHT[26]; + _zz_127_[6] = execute_SHIFT_RIGHT[25]; + _zz_127_[7] = execute_SHIFT_RIGHT[24]; + _zz_127_[8] = execute_SHIFT_RIGHT[23]; + _zz_127_[9] = execute_SHIFT_RIGHT[22]; + _zz_127_[10] = execute_SHIFT_RIGHT[21]; + _zz_127_[11] = execute_SHIFT_RIGHT[20]; + _zz_127_[12] = execute_SHIFT_RIGHT[19]; + _zz_127_[13] = execute_SHIFT_RIGHT[18]; + _zz_127_[14] = execute_SHIFT_RIGHT[17]; + _zz_127_[15] = execute_SHIFT_RIGHT[16]; + _zz_127_[16] = execute_SHIFT_RIGHT[15]; + _zz_127_[17] = execute_SHIFT_RIGHT[14]; + _zz_127_[18] = execute_SHIFT_RIGHT[13]; + _zz_127_[19] = execute_SHIFT_RIGHT[12]; + _zz_127_[20] = execute_SHIFT_RIGHT[11]; + _zz_127_[21] = execute_SHIFT_RIGHT[10]; + _zz_127_[22] = execute_SHIFT_RIGHT[9]; + _zz_127_[23] = execute_SHIFT_RIGHT[8]; + _zz_127_[24] = execute_SHIFT_RIGHT[7]; + _zz_127_[25] = execute_SHIFT_RIGHT[6]; + _zz_127_[26] = execute_SHIFT_RIGHT[5]; + _zz_127_[27] = execute_SHIFT_RIGHT[4]; + _zz_127_[28] = execute_SHIFT_RIGHT[3]; + _zz_127_[29] = execute_SHIFT_RIGHT[2]; + _zz_127_[30] = execute_SHIFT_RIGHT[1]; + _zz_127_[31] = execute_SHIFT_RIGHT[0]; + end + + always @ (*) begin + _zz_128_ = 1'b0; + if(_zz_175_)begin + if(_zz_176_)begin + if(_zz_133_)begin + _zz_128_ = 1'b1; + end + end + end + if(_zz_177_)begin + if(_zz_178_)begin + if(_zz_135_)begin + _zz_128_ = 1'b1; + end + end + end + if(_zz_179_)begin + if(_zz_180_)begin + if(_zz_137_)begin + _zz_128_ = 1'b1; + end + end + end + if((! decode_RS1_USE))begin + _zz_128_ = 1'b0; + end + end + + always @ (*) begin + _zz_129_ = 1'b0; + if(_zz_175_)begin + if(_zz_176_)begin + if(_zz_134_)begin + _zz_129_ = 1'b1; + end + end + end + if(_zz_177_)begin + if(_zz_178_)begin + if(_zz_136_)begin + _zz_129_ = 1'b1; + end + end + end + if(_zz_179_)begin + if(_zz_180_)begin + if(_zz_138_)begin + _zz_129_ = 1'b1; + end + end + end + if((! decode_RS2_USE))begin + _zz_129_ = 1'b0; + end + end + + assign _zz_133_ = (writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]); + assign _zz_134_ = (writeBack_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]); + assign _zz_135_ = (memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]); + assign _zz_136_ = (memory_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]); + assign _zz_137_ = (execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[19 : 15]); + assign _zz_138_ = (execute_INSTRUCTION[11 : 7] == decode_INSTRUCTION[24 : 20]); + assign memory_MulDivIterativePlugin_frontendOk = 1'b1; + always @ (*) begin + memory_MulDivIterativePlugin_mul_counter_willIncrement = 1'b0; + if(_zz_168_)begin + if(_zz_170_)begin + memory_MulDivIterativePlugin_mul_counter_willIncrement = 1'b1; + end + end + end + + always @ (*) begin + memory_MulDivIterativePlugin_mul_counter_willClear = 1'b0; + if((! memory_arbitration_isStuck))begin + memory_MulDivIterativePlugin_mul_counter_willClear = 1'b1; + end + end + + assign memory_MulDivIterativePlugin_mul_counter_willOverflowIfInc = (memory_MulDivIterativePlugin_mul_counter_value == 5'h10); + assign memory_MulDivIterativePlugin_mul_counter_willOverflow = (memory_MulDivIterativePlugin_mul_counter_willOverflowIfInc && memory_MulDivIterativePlugin_mul_counter_willIncrement); + always @ (*) begin + if(memory_MulDivIterativePlugin_mul_counter_willOverflow)begin + memory_MulDivIterativePlugin_mul_counter_valueNext = 5'h0; + end else begin + memory_MulDivIterativePlugin_mul_counter_valueNext = (memory_MulDivIterativePlugin_mul_counter_value + _zz_242_); + end + if(memory_MulDivIterativePlugin_mul_counter_willClear)begin + memory_MulDivIterativePlugin_mul_counter_valueNext = 5'h0; + end + end + + always @ (*) begin + memory_MulDivIterativePlugin_div_counter_willIncrement = 1'b0; + if(_zz_169_)begin + if(_zz_181_)begin + memory_MulDivIterativePlugin_div_counter_willIncrement = 1'b1; + end + end + end + + always @ (*) begin + memory_MulDivIterativePlugin_div_counter_willClear = 1'b0; + if(_zz_182_)begin + memory_MulDivIterativePlugin_div_counter_willClear = 1'b1; + end + end + + assign memory_MulDivIterativePlugin_div_counter_willOverflowIfInc = (memory_MulDivIterativePlugin_div_counter_value == 5'h11); + assign memory_MulDivIterativePlugin_div_counter_willOverflow = (memory_MulDivIterativePlugin_div_counter_willOverflowIfInc && memory_MulDivIterativePlugin_div_counter_willIncrement); + always @ (*) begin + if(memory_MulDivIterativePlugin_div_counter_willOverflow)begin + memory_MulDivIterativePlugin_div_counter_valueNext = 5'h0; + end else begin + memory_MulDivIterativePlugin_div_counter_valueNext = (memory_MulDivIterativePlugin_div_counter_value + _zz_254_); + end + if(memory_MulDivIterativePlugin_div_counter_willClear)begin + memory_MulDivIterativePlugin_div_counter_valueNext = 5'h0; + end + end + + assign _zz_139_ = memory_MulDivIterativePlugin_rs1[31 : 0]; + assign memory_MulDivIterativePlugin_div_stage_0_remainderShifted = {memory_MulDivIterativePlugin_accumulator[31 : 0],_zz_139_[31]}; + assign memory_MulDivIterativePlugin_div_stage_0_remainderMinusDenominator = (memory_MulDivIterativePlugin_div_stage_0_remainderShifted - _zz_255_); + assign memory_MulDivIterativePlugin_div_stage_0_outRemainder = ((! memory_MulDivIterativePlugin_div_stage_0_remainderMinusDenominator[32]) ? _zz_256_ : _zz_257_); + assign memory_MulDivIterativePlugin_div_stage_0_outNumerator = _zz_258_[31:0]; + assign memory_MulDivIterativePlugin_div_stage_1_remainderShifted = {memory_MulDivIterativePlugin_div_stage_0_outRemainder,memory_MulDivIterativePlugin_div_stage_0_outNumerator[31]}; + assign memory_MulDivIterativePlugin_div_stage_1_remainderMinusDenominator = (memory_MulDivIterativePlugin_div_stage_1_remainderShifted - _zz_259_); + assign memory_MulDivIterativePlugin_div_stage_1_outRemainder = ((! memory_MulDivIterativePlugin_div_stage_1_remainderMinusDenominator[32]) ? _zz_260_ : _zz_261_); + assign memory_MulDivIterativePlugin_div_stage_1_outNumerator = _zz_262_[31:0]; + assign _zz_140_ = (memory_INSTRUCTION[13] ? memory_MulDivIterativePlugin_accumulator[31 : 0] : memory_MulDivIterativePlugin_rs1[31 : 0]); + assign _zz_141_ = (execute_RS2[31] && execute_IS_RS2_SIGNED); + assign _zz_142_ = ((execute_IS_MUL && _zz_141_) || ((execute_IS_DIV && execute_RS1[31]) && execute_IS_RS1_SIGNED)); + always @ (*) begin + _zz_143_[32] = (execute_IS_RS1_SIGNED && execute_RS1[31]); + _zz_143_[31 : 0] = execute_RS1; + end + + assign execute_BranchPlugin_eq = (execute_SRC1 == execute_SRC2); + assign _zz_144_ = execute_INSTRUCTION[14 : 12]; + always @ (*) begin + if((_zz_144_ == (3'b000))) begin + _zz_145_ = execute_BranchPlugin_eq; + end else if((_zz_144_ == (3'b001))) begin + _zz_145_ = (! execute_BranchPlugin_eq); + end else if((((_zz_144_ & (3'b101)) == (3'b101)))) begin + _zz_145_ = (! execute_SRC_LESS); + end else begin + _zz_145_ = execute_SRC_LESS; + end + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_INC : begin + _zz_146_ = 1'b0; + end + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_146_ = 1'b1; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_146_ = 1'b1; + end + default : begin + _zz_146_ = _zz_145_; + end + endcase + end + + assign execute_BranchPlugin_branch_src1 = ((execute_BRANCH_CTRL == `BranchCtrlEnum_defaultEncoding_JALR) ? execute_RS1 : execute_PC); + assign _zz_147_ = _zz_272_[19]; + always @ (*) begin + _zz_148_[10] = _zz_147_; + _zz_148_[9] = _zz_147_; + _zz_148_[8] = _zz_147_; + _zz_148_[7] = _zz_147_; + _zz_148_[6] = _zz_147_; + _zz_148_[5] = _zz_147_; + _zz_148_[4] = _zz_147_; + _zz_148_[3] = _zz_147_; + _zz_148_[2] = _zz_147_; + _zz_148_[1] = _zz_147_; + _zz_148_[0] = _zz_147_; + end + + assign _zz_149_ = _zz_273_[11]; + always @ (*) begin + _zz_150_[19] = _zz_149_; + _zz_150_[18] = _zz_149_; + _zz_150_[17] = _zz_149_; + _zz_150_[16] = _zz_149_; + _zz_150_[15] = _zz_149_; + _zz_150_[14] = _zz_149_; + _zz_150_[13] = _zz_149_; + _zz_150_[12] = _zz_149_; + _zz_150_[11] = _zz_149_; + _zz_150_[10] = _zz_149_; + _zz_150_[9] = _zz_149_; + _zz_150_[8] = _zz_149_; + _zz_150_[7] = _zz_149_; + _zz_150_[6] = _zz_149_; + _zz_150_[5] = _zz_149_; + _zz_150_[4] = _zz_149_; + _zz_150_[3] = _zz_149_; + _zz_150_[2] = _zz_149_; + _zz_150_[1] = _zz_149_; + _zz_150_[0] = _zz_149_; + end + + assign _zz_151_ = _zz_274_[11]; + always @ (*) begin + _zz_152_[18] = _zz_151_; + _zz_152_[17] = _zz_151_; + _zz_152_[16] = _zz_151_; + _zz_152_[15] = _zz_151_; + _zz_152_[14] = _zz_151_; + _zz_152_[13] = _zz_151_; + _zz_152_[12] = _zz_151_; + _zz_152_[11] = _zz_151_; + _zz_152_[10] = _zz_151_; + _zz_152_[9] = _zz_151_; + _zz_152_[8] = _zz_151_; + _zz_152_[7] = _zz_151_; + _zz_152_[6] = _zz_151_; + _zz_152_[5] = _zz_151_; + _zz_152_[4] = _zz_151_; + _zz_152_[3] = _zz_151_; + _zz_152_[2] = _zz_151_; + _zz_152_[1] = _zz_151_; + _zz_152_[0] = _zz_151_; + end + + always @ (*) begin + case(execute_BRANCH_CTRL) + `BranchCtrlEnum_defaultEncoding_JAL : begin + _zz_153_ = {{_zz_148_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[19 : 12]},execute_INSTRUCTION[20]},execute_INSTRUCTION[30 : 21]}},1'b0}; + end + `BranchCtrlEnum_defaultEncoding_JALR : begin + _zz_153_ = {_zz_150_,execute_INSTRUCTION[31 : 20]}; + end + default : begin + _zz_153_ = {{_zz_152_,{{{execute_INSTRUCTION[31],execute_INSTRUCTION[7]},execute_INSTRUCTION[30 : 25]},execute_INSTRUCTION[11 : 8]}},1'b0}; + end + endcase + end + + assign execute_BranchPlugin_branch_src2 = _zz_153_; + assign execute_BranchPlugin_branchAdder = (execute_BranchPlugin_branch_src1 + execute_BranchPlugin_branch_src2); + assign BranchPlugin_jumpInterface_valid = ((execute_arbitration_isValid && execute_BRANCH_DO) && (! 1'b0)); + assign BranchPlugin_jumpInterface_payload = execute_BRANCH_CALC; + assign _zz_25_ = decode_ENV_CTRL; + assign _zz_22_ = execute_ENV_CTRL; + assign _zz_20_ = memory_ENV_CTRL; + assign _zz_23_ = _zz_41_; + assign _zz_46_ = decode_to_execute_ENV_CTRL; + assign _zz_45_ = execute_to_memory_ENV_CTRL; + assign _zz_47_ = memory_to_writeBack_ENV_CTRL; + assign _zz_18_ = decode_ALU_CTRL; + assign _zz_16_ = _zz_43_; + assign _zz_31_ = decode_to_execute_ALU_CTRL; + assign _zz_15_ = decode_BRANCH_CTRL; + assign _zz_13_ = _zz_39_; + assign _zz_26_ = decode_to_execute_BRANCH_CTRL; + assign _zz_12_ = decode_SRC1_CTRL; + assign _zz_10_ = _zz_40_; + assign _zz_30_ = decode_to_execute_SRC1_CTRL; + assign _zz_9_ = decode_SHIFT_CTRL; + assign _zz_7_ = _zz_42_; + assign _zz_27_ = decode_to_execute_SHIFT_CTRL; + assign _zz_6_ = decode_SRC2_CTRL; + assign _zz_4_ = _zz_37_; + assign _zz_29_ = decode_to_execute_SRC2_CTRL; + assign _zz_3_ = decode_ALU_BITWISE_CTRL; + assign _zz_1_ = _zz_38_; + assign _zz_32_ = decode_to_execute_ALU_BITWISE_CTRL; + assign decode_arbitration_isFlushed = (({writeBack_arbitration_flushNext,{memory_arbitration_flushNext,execute_arbitration_flushNext}} != (3'b000)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,{execute_arbitration_flushIt,decode_arbitration_flushIt}}} != (4'b0000))); + assign execute_arbitration_isFlushed = (({writeBack_arbitration_flushNext,memory_arbitration_flushNext} != (2'b00)) || ({writeBack_arbitration_flushIt,{memory_arbitration_flushIt,execute_arbitration_flushIt}} != (3'b000))); + assign memory_arbitration_isFlushed = ((writeBack_arbitration_flushNext != (1'b0)) || ({writeBack_arbitration_flushIt,memory_arbitration_flushIt} != (2'b00))); + assign writeBack_arbitration_isFlushed = (1'b0 || (writeBack_arbitration_flushIt != (1'b0))); + assign decode_arbitration_isStuckByOthers = (decode_arbitration_haltByOther || (((1'b0 || execute_arbitration_isStuck) || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign decode_arbitration_isStuck = (decode_arbitration_haltItself || decode_arbitration_isStuckByOthers); + assign decode_arbitration_isMoving = ((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)); + assign decode_arbitration_isFiring = ((decode_arbitration_isValid && (! decode_arbitration_isStuck)) && (! decode_arbitration_removeIt)); + assign execute_arbitration_isStuckByOthers = (execute_arbitration_haltByOther || ((1'b0 || memory_arbitration_isStuck) || writeBack_arbitration_isStuck)); + assign execute_arbitration_isStuck = (execute_arbitration_haltItself || execute_arbitration_isStuckByOthers); + assign execute_arbitration_isMoving = ((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)); + assign execute_arbitration_isFiring = ((execute_arbitration_isValid && (! execute_arbitration_isStuck)) && (! execute_arbitration_removeIt)); + assign memory_arbitration_isStuckByOthers = (memory_arbitration_haltByOther || (1'b0 || writeBack_arbitration_isStuck)); + assign memory_arbitration_isStuck = (memory_arbitration_haltItself || memory_arbitration_isStuckByOthers); + assign memory_arbitration_isMoving = ((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)); + assign memory_arbitration_isFiring = ((memory_arbitration_isValid && (! memory_arbitration_isStuck)) && (! memory_arbitration_removeIt)); + assign writeBack_arbitration_isStuckByOthers = (writeBack_arbitration_haltByOther || 1'b0); + assign writeBack_arbitration_isStuck = (writeBack_arbitration_haltItself || writeBack_arbitration_isStuckByOthers); + assign writeBack_arbitration_isMoving = ((! writeBack_arbitration_isStuck) && (! writeBack_arbitration_removeIt)); + assign writeBack_arbitration_isFiring = ((writeBack_arbitration_isValid && (! writeBack_arbitration_isStuck)) && (! writeBack_arbitration_removeIt)); + always @ (*) begin + _zz_154_ = 32'h0; + if(execute_CsrPlugin_csr_768)begin + _zz_154_[12 : 11] = CsrPlugin_mstatus_MPP; + _zz_154_[7 : 7] = CsrPlugin_mstatus_MPIE; + _zz_154_[3 : 3] = CsrPlugin_mstatus_MIE; + end + end + + always @ (*) begin + _zz_155_ = 32'h0; + if(execute_CsrPlugin_csr_836)begin + _zz_155_[11 : 11] = CsrPlugin_mip_MEIP; + _zz_155_[7 : 7] = CsrPlugin_mip_MTIP; + _zz_155_[3 : 3] = CsrPlugin_mip_MSIP; + end + end + + always @ (*) begin + _zz_156_ = 32'h0; + if(execute_CsrPlugin_csr_772)begin + _zz_156_[11 : 11] = CsrPlugin_mie_MEIE; + _zz_156_[7 : 7] = CsrPlugin_mie_MTIE; + _zz_156_[3 : 3] = CsrPlugin_mie_MSIE; + end + end + + always @ (*) begin + _zz_157_ = 32'h0; + if(execute_CsrPlugin_csr_832)begin + _zz_157_[31 : 0] = CsrPlugin_mscratch; + end + end + + always @ (*) begin + _zz_158_ = 32'h0; + if(execute_CsrPlugin_csr_834)begin + _zz_158_[31 : 31] = CsrPlugin_mcause_interrupt; + _zz_158_[3 : 0] = CsrPlugin_mcause_exceptionCode; + end + end + + assign execute_CsrPlugin_readData = (((_zz_154_ | _zz_155_) | (_zz_156_ | _zz_157_)) | _zz_158_); + assign _zz_160_ = 1'b0; + always @ (posedge clk or posedge reset) begin + if (reset) begin + IBusSimplePlugin_fetchPc_pcReg <= 32'h0; + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + IBusSimplePlugin_fetchPc_booted <= 1'b0; + IBusSimplePlugin_fetchPc_inc <= 1'b0; + IBusSimplePlugin_decodePc_pcReg <= 32'h0; + _zz_56_ <= 1'b0; + _zz_58_ <= 1'b0; + IBusSimplePlugin_decompressor_bufferValid <= 1'b0; + IBusSimplePlugin_decompressor_throw2BytesReg <= 1'b0; + _zz_87_ <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + IBusSimplePlugin_pending_value <= (3'b000); + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (3'b000); + CsrPlugin_mstatus_MIE <= 1'b0; + CsrPlugin_mstatus_MPIE <= 1'b0; + CsrPlugin_mstatus_MPP <= (2'b11); + CsrPlugin_mie_MEIE <= 1'b0; + CsrPlugin_mie_MTIE <= 1'b0; + CsrPlugin_mie_MSIE <= 1'b0; + CsrPlugin_interrupt_valid <= 1'b0; + CsrPlugin_pipelineLiberator_pcValids_0 <= 1'b0; + CsrPlugin_pipelineLiberator_pcValids_1 <= 1'b0; + CsrPlugin_pipelineLiberator_pcValids_2 <= 1'b0; + CsrPlugin_hadException <= 1'b0; + execute_CsrPlugin_wfiWake <= 1'b0; + _zz_118_ <= 1'b1; + _zz_130_ <= 1'b0; + memory_MulDivIterativePlugin_mul_counter_value <= 5'h0; + memory_MulDivIterativePlugin_div_counter_value <= 5'h0; + execute_arbitration_isValid <= 1'b0; + memory_arbitration_isValid <= 1'b0; + writeBack_arbitration_isValid <= 1'b0; + memory_to_writeBack_REGFILE_WRITE_DATA <= 32'h0; + memory_to_writeBack_INSTRUCTION <= 32'h0; + end else begin + if(IBusSimplePlugin_fetchPc_correction)begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b1; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_correctionReg <= 1'b0; + end + IBusSimplePlugin_fetchPc_booted <= 1'b1; + if((IBusSimplePlugin_fetchPc_correction || IBusSimplePlugin_fetchPc_pcRegPropagate))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_output_valid && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b1; + end + if(((! IBusSimplePlugin_fetchPc_output_valid) && IBusSimplePlugin_fetchPc_output_ready))begin + IBusSimplePlugin_fetchPc_inc <= 1'b0; + end + if((IBusSimplePlugin_fetchPc_booted && ((IBusSimplePlugin_fetchPc_output_ready || IBusSimplePlugin_fetchPc_correction) || IBusSimplePlugin_fetchPc_pcRegPropagate)))begin + IBusSimplePlugin_fetchPc_pcReg <= IBusSimplePlugin_fetchPc_pc; + end + if((decode_arbitration_isFiring && (! IBusSimplePlugin_decodePc_injectedDecode)))begin + IBusSimplePlugin_decodePc_pcReg <= IBusSimplePlugin_decodePc_pcPlus; + end + if(_zz_174_)begin + IBusSimplePlugin_decodePc_pcReg <= IBusSimplePlugin_jump_pcLoad_payload; + end + if(IBusSimplePlugin_iBusRsp_flush)begin + _zz_56_ <= 1'b0; + end + if(_zz_54_)begin + _zz_56_ <= (IBusSimplePlugin_iBusRsp_stages_0_output_valid && (! 1'b0)); + end + if(IBusSimplePlugin_iBusRsp_flush)begin + _zz_58_ <= 1'b0; + end + if(IBusSimplePlugin_iBusRsp_stages_1_output_ready)begin + _zz_58_ <= (IBusSimplePlugin_iBusRsp_stages_1_output_valid && (! IBusSimplePlugin_iBusRsp_flush)); + end + if((IBusSimplePlugin_decompressor_output_valid && IBusSimplePlugin_decompressor_output_ready))begin + IBusSimplePlugin_decompressor_throw2BytesReg <= ((((! IBusSimplePlugin_decompressor_unaligned) && IBusSimplePlugin_decompressor_isInputLowRvc) && IBusSimplePlugin_decompressor_isInputHighRvc) || (IBusSimplePlugin_decompressor_bufferValid && IBusSimplePlugin_decompressor_isInputHighRvc)); + end + if((IBusSimplePlugin_decompressor_output_ready && IBusSimplePlugin_decompressor_input_valid))begin + IBusSimplePlugin_decompressor_bufferValid <= 1'b0; + end + if(_zz_183_)begin + if(IBusSimplePlugin_decompressor_bufferFill)begin + IBusSimplePlugin_decompressor_bufferValid <= 1'b1; + end + end + if((IBusSimplePlugin_externalFlush || IBusSimplePlugin_decompressor_consumeCurrent))begin + IBusSimplePlugin_decompressor_throw2BytesReg <= 1'b0; + IBusSimplePlugin_decompressor_bufferValid <= 1'b0; + end + if(decode_arbitration_removeIt)begin + _zz_87_ <= 1'b0; + end + if(IBusSimplePlugin_decompressor_output_ready)begin + _zz_87_ <= (IBusSimplePlugin_decompressor_output_valid && (! IBusSimplePlugin_externalFlush)); + end + if((! 1'b0))begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b1; + end + if(IBusSimplePlugin_decodePc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_0 <= 1'b0; + end + if((! execute_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= IBusSimplePlugin_injector_nextPcCalc_valids_0; + end + if(IBusSimplePlugin_decodePc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_1 <= 1'b0; + end + if((! memory_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= IBusSimplePlugin_injector_nextPcCalc_valids_1; + end + if(IBusSimplePlugin_decodePc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_2 <= 1'b0; + end + if((! writeBack_arbitration_isStuck))begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= IBusSimplePlugin_injector_nextPcCalc_valids_2; + end + if(IBusSimplePlugin_decodePc_flushed)begin + IBusSimplePlugin_injector_nextPcCalc_valids_3 <= 1'b0; + end + IBusSimplePlugin_pending_value <= IBusSimplePlugin_pending_next; + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= (IBusSimplePlugin_rspJoin_rspBuffer_discardCounter - _zz_228_); + if(IBusSimplePlugin_iBusRsp_flush)begin + IBusSimplePlugin_rspJoin_rspBuffer_discardCounter <= IBusSimplePlugin_pending_next; + end + CsrPlugin_interrupt_valid <= 1'b0; + if(_zz_184_)begin + if(_zz_185_)begin + CsrPlugin_interrupt_valid <= 1'b1; + end + if(_zz_186_)begin + CsrPlugin_interrupt_valid <= 1'b1; + end + if(_zz_187_)begin + CsrPlugin_interrupt_valid <= 1'b1; + end + end + if(CsrPlugin_pipelineLiberator_active)begin + if((! execute_arbitration_isStuck))begin + CsrPlugin_pipelineLiberator_pcValids_0 <= 1'b1; + end + if((! memory_arbitration_isStuck))begin + CsrPlugin_pipelineLiberator_pcValids_1 <= CsrPlugin_pipelineLiberator_pcValids_0; + end + if((! writeBack_arbitration_isStuck))begin + CsrPlugin_pipelineLiberator_pcValids_2 <= CsrPlugin_pipelineLiberator_pcValids_1; + end + end + if(((! CsrPlugin_pipelineLiberator_active) || decode_arbitration_removeIt))begin + CsrPlugin_pipelineLiberator_pcValids_0 <= 1'b0; + CsrPlugin_pipelineLiberator_pcValids_1 <= 1'b0; + CsrPlugin_pipelineLiberator_pcValids_2 <= 1'b0; + end + if(CsrPlugin_interruptJump)begin + CsrPlugin_interrupt_valid <= 1'b0; + end + CsrPlugin_hadException <= CsrPlugin_exception; + if(_zz_171_)begin + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_mstatus_MIE <= 1'b0; + CsrPlugin_mstatus_MPIE <= CsrPlugin_mstatus_MIE; + CsrPlugin_mstatus_MPP <= CsrPlugin_privilege; + end + default : begin + end + endcase + end + if(_zz_172_)begin + case(_zz_173_) + 2'b11 : begin + CsrPlugin_mstatus_MPP <= (2'b00); + CsrPlugin_mstatus_MIE <= CsrPlugin_mstatus_MPIE; + CsrPlugin_mstatus_MPIE <= 1'b1; + end + default : begin + end + endcase + end + execute_CsrPlugin_wfiWake <= (({_zz_102_,{_zz_101_,_zz_100_}} != (3'b000)) || CsrPlugin_thirdPartyWake); + _zz_118_ <= 1'b0; + _zz_130_ <= (_zz_35_ && writeBack_arbitration_isFiring); + memory_MulDivIterativePlugin_mul_counter_value <= memory_MulDivIterativePlugin_mul_counter_valueNext; + memory_MulDivIterativePlugin_div_counter_value <= memory_MulDivIterativePlugin_div_counter_valueNext; + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_DATA <= _zz_48_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_INSTRUCTION <= memory_INSTRUCTION; + end + if(((! execute_arbitration_isStuck) || execute_arbitration_removeIt))begin + execute_arbitration_isValid <= 1'b0; + end + if(((! decode_arbitration_isStuck) && (! decode_arbitration_removeIt)))begin + execute_arbitration_isValid <= decode_arbitration_isValid; + end + if(((! memory_arbitration_isStuck) || memory_arbitration_removeIt))begin + memory_arbitration_isValid <= 1'b0; + end + if(((! execute_arbitration_isStuck) && (! execute_arbitration_removeIt)))begin + memory_arbitration_isValid <= execute_arbitration_isValid; + end + if(((! writeBack_arbitration_isStuck) || writeBack_arbitration_removeIt))begin + writeBack_arbitration_isValid <= 1'b0; + end + if(((! memory_arbitration_isStuck) && (! memory_arbitration_removeIt)))begin + writeBack_arbitration_isValid <= memory_arbitration_isValid; + end + if(execute_CsrPlugin_csr_768)begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mstatus_MPP <= execute_CsrPlugin_writeData[12 : 11]; + CsrPlugin_mstatus_MPIE <= _zz_275_[0]; + CsrPlugin_mstatus_MIE <= _zz_276_[0]; + end + end + if(execute_CsrPlugin_csr_772)begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mie_MEIE <= _zz_278_[0]; + CsrPlugin_mie_MTIE <= _zz_279_[0]; + CsrPlugin_mie_MSIE <= _zz_280_[0]; + end + end + end + end + + always @ (posedge clk) begin + if(IBusSimplePlugin_iBusRsp_stages_1_output_ready)begin + _zz_59_ <= IBusSimplePlugin_iBusRsp_stages_1_output_payload; + end + if(_zz_183_)begin + IBusSimplePlugin_decompressor_bufferData <= IBusSimplePlugin_decompressor_input_payload_rsp_inst[31 : 16]; + end + if(IBusSimplePlugin_decompressor_output_ready)begin + _zz_88_ <= IBusSimplePlugin_decompressor_output_payload_pc; + _zz_89_ <= IBusSimplePlugin_decompressor_output_payload_rsp_error; + _zz_90_ <= IBusSimplePlugin_decompressor_output_payload_rsp_inst; + _zz_91_ <= IBusSimplePlugin_decompressor_output_payload_isRvc; + end + if(IBusSimplePlugin_injector_decodeInput_ready)begin + IBusSimplePlugin_injector_formal_rawInDecode <= IBusSimplePlugin_decompressor_raw; + end + `ifndef SYNTHESIS + `ifdef FORMAL + assert((! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) + `else + if(!(! (((dBus_rsp_ready && memory_MEMORY_ENABLE) && memory_arbitration_isValid) && memory_arbitration_isStuck))) begin + $display("FAILURE DBusSimplePlugin doesn't allow memory stage stall when read happend"); + $finish; + end + `endif + `endif + CsrPlugin_mip_MEIP <= externalInterrupt; + CsrPlugin_mip_MTIP <= timerInterrupt; + CsrPlugin_mip_MSIP <= softwareInterrupt; + CsrPlugin_mcycle <= (CsrPlugin_mcycle + 64'h0000000000000001); + if(writeBack_arbitration_isFiring)begin + CsrPlugin_minstret <= (CsrPlugin_minstret + 64'h0000000000000001); + end + if(_zz_184_)begin + if(_zz_185_)begin + CsrPlugin_interrupt_code <= (4'b0111); + CsrPlugin_interrupt_targetPrivilege <= (2'b11); + end + if(_zz_186_)begin + CsrPlugin_interrupt_code <= (4'b0011); + CsrPlugin_interrupt_targetPrivilege <= (2'b11); + end + if(_zz_187_)begin + CsrPlugin_interrupt_code <= (4'b1011); + CsrPlugin_interrupt_targetPrivilege <= (2'b11); + end + end + if(_zz_171_)begin + case(CsrPlugin_targetPrivilege) + 2'b11 : begin + CsrPlugin_mcause_interrupt <= (! CsrPlugin_hadException); + CsrPlugin_mcause_exceptionCode <= CsrPlugin_trapCause; + CsrPlugin_mepc <= decode_PC; + end + default : begin + end + endcase + end + _zz_131_ <= _zz_34_[11 : 7]; + _zz_132_ <= _zz_33_; + if(_zz_168_)begin + if(_zz_170_)begin + memory_MulDivIterativePlugin_rs2 <= (memory_MulDivIterativePlugin_rs2 >>> 2); + memory_MulDivIterativePlugin_accumulator <= ({_zz_243_,memory_MulDivIterativePlugin_accumulator[31 : 0]} >>> 2); + end + end + if((memory_MulDivIterativePlugin_div_counter_value == 5'h10))begin + memory_MulDivIterativePlugin_div_done <= 1'b1; + end + if((! memory_arbitration_isStuck))begin + memory_MulDivIterativePlugin_div_done <= 1'b0; + end + if(_zz_169_)begin + if(_zz_181_)begin + memory_MulDivIterativePlugin_rs1[31 : 0] <= memory_MulDivIterativePlugin_div_stage_1_outNumerator; + memory_MulDivIterativePlugin_accumulator[31 : 0] <= memory_MulDivIterativePlugin_div_stage_1_outRemainder; + if((memory_MulDivIterativePlugin_div_counter_value == 5'h10))begin + memory_MulDivIterativePlugin_div_result <= _zz_263_[31:0]; + end + end + end + if(_zz_182_)begin + memory_MulDivIterativePlugin_accumulator <= 65'h0; + memory_MulDivIterativePlugin_rs1 <= ((_zz_142_ ? (~ _zz_143_) : _zz_143_) + _zz_269_); + memory_MulDivIterativePlugin_rs2 <= ((_zz_141_ ? (~ execute_RS2) : execute_RS2) + _zz_271_); + memory_MulDivIterativePlugin_div_needRevert <= ((_zz_142_ ^ (_zz_141_ && (! execute_INSTRUCTION[13]))) && (! (((execute_RS2 == 32'h0) && execute_IS_RS2_SIGNED) && (! execute_INSTRUCTION[13])))); + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS1 <= decode_RS1; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ADDRESS_LOW <= execute_MEMORY_ADDRESS_LOW; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_DIV <= decode_IS_DIV; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_IS_DIV <= execute_IS_DIV; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_RVC <= decode_IS_RVC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_RS2_SIGNED <= decode_IS_RS2_SIGNED; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_USE_SUB_LESS <= decode_SRC_USE_SUB_LESS; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC_LESS_UNSIGNED <= decode_SRC_LESS_UNSIGNED; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ENV_CTRL <= _zz_24_; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_ENV_CTRL <= _zz_21_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_ENV_CTRL <= _zz_19_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_FORCE_ZERO <= decode_SRC2_FORCE_ZERO; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_CTRL <= _zz_17_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_REGFILE_WRITE_VALID <= decode_REGFILE_WRITE_VALID; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_REGFILE_WRITE_VALID <= execute_REGFILE_WRITE_VALID; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_REGFILE_WRITE_VALID <= memory_REGFILE_WRITE_VALID; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_PC <= decode_PC; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_PC <= _zz_28_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_PC <= memory_PC; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_MEMORY_STAGE <= decode_BYPASSABLE_MEMORY_STAGE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_BYPASSABLE_MEMORY_STAGE <= execute_BYPASSABLE_MEMORY_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BRANCH_CTRL <= _zz_14_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_RS1_SIGNED <= decode_IS_RS1_SIGNED; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_REGFILE_WRITE_DATA <= _zz_44_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_BYPASSABLE_EXECUTE_STAGE <= decode_BYPASSABLE_EXECUTE_STAGE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_CSR <= decode_IS_CSR; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC1_CTRL <= _zz_11_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_STORE <= decode_MEMORY_STORE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_STORE <= execute_MEMORY_STORE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_INSTRUCTION <= decode_INSTRUCTION; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_INSTRUCTION <= execute_INSTRUCTION; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_IS_MUL <= decode_IS_MUL; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_IS_MUL <= execute_IS_MUL; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SHIFT_CTRL <= _zz_8_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_CSR_WRITE_OPCODE <= decode_CSR_WRITE_OPCODE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_CSR_READ_OPCODE <= decode_CSR_READ_OPCODE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_FORMAL_PC_NEXT <= decode_FORMAL_PC_NEXT; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_FORMAL_PC_NEXT <= _zz_49_; + end + if((! writeBack_arbitration_isStuck))begin + memory_to_writeBack_FORMAL_PC_NEXT <= memory_FORMAL_PC_NEXT; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_SRC2_CTRL <= _zz_5_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_MEMORY_ENABLE <= decode_MEMORY_ENABLE; + end + if((! memory_arbitration_isStuck))begin + execute_to_memory_MEMORY_ENABLE <= execute_MEMORY_ENABLE; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_ALU_BITWISE_CTRL <= _zz_2_; + end + if((! execute_arbitration_isStuck))begin + decode_to_execute_RS2 <= decode_RS2; + end + if((! execute_arbitration_isStuck))begin + execute_CsrPlugin_csr_768 <= (decode_INSTRUCTION[31 : 20] == 12'h300); + end + if((! execute_arbitration_isStuck))begin + execute_CsrPlugin_csr_836 <= (decode_INSTRUCTION[31 : 20] == 12'h344); + end + if((! execute_arbitration_isStuck))begin + execute_CsrPlugin_csr_772 <= (decode_INSTRUCTION[31 : 20] == 12'h304); + end + if((! execute_arbitration_isStuck))begin + execute_CsrPlugin_csr_832 <= (decode_INSTRUCTION[31 : 20] == 12'h340); + end + if((! execute_arbitration_isStuck))begin + execute_CsrPlugin_csr_834 <= (decode_INSTRUCTION[31 : 20] == 12'h342); + end + if(execute_CsrPlugin_csr_836)begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mip_MSIP <= _zz_277_[0]; + end + end + if(execute_CsrPlugin_csr_832)begin + if(execute_CsrPlugin_writeEnable)begin + CsrPlugin_mscratch <= execute_CsrPlugin_writeData[31 : 0]; + end + end + end + + +endmodule diff --git a/zeldin_iceGDROM/fpga/source/vexriscv/peripherals.v b/zeldin_iceGDROM/fpga/source/vexriscv/peripherals.v new file mode 100644 index 0000000000000000000000000000000000000000..a15643b8d367275c59d9ff8e3462ccc8c2e92eda --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/vexriscv/peripherals.v @@ -0,0 +1,169 @@ +module peripherals ( + input clk, + input nrst, + + output reg[31:0] data_out, + input wire[31:0] data_in, + input wire[5:0] addr, + input cs, + input oe, + input[3:0] wstrb, + + // PORTA + inout[7:0] porta, + + // PORTB + inout[7:0] portb, + + // SDCARD + input sdcard_sck, + input sdcard_mosi, + output sdcard_miso, + + // UART related + input rxd, + output wire txd, + + // TIMER0 + output timer0_comp_irq + ); + + wire [7:0] porta_pinx; + reg [7:0] porta_portx; + reg [7:0] porta_ddrx; + + wire [7:0] portb_pinx; + reg [7:0] portb_portx; + reg [7:0] portb_ddrx; + + reg [10:0] ser_out = ~0; + reg [8:0] ser_in = ~0; + reg [15:0] ser_tx_cnt = 0; + reg [15:0] ser_rx_cnt = 0; + reg [7:0] ser_rx_data; + reg [15:0] ser_brr; + reg ser_rxc; + reg ser_fe; + reg ser_dor; + reg rxd_s; + assign txd = ser_out[0]; + + reg ocie0, ocf0; + reg [23:0] tcnt0, ocr0; + assign timer0_comp_irq = ocie0 && ocf0; + + tri_buf tri_buf_porta_inst[7:0](.out(porta_portx), .in(porta_pinx), + .en(porta_ddrx), .pin(porta)); + + tri_buf tri_buf_portb_inst[7:0]( + .out ({portb_portx[7:3], + {sdcard_mosi, sdcard_sck}, + portb_portx[0]}), + .in (portb_pinx), + .en ({portb_ddrx[7:4], 1'b0, portb_ddrx[2:0]}), + .pin (portb)); + assign sdcard_miso = portb_pinx[3]; + + always @(posedge clk) + if (~nrst) begin + porta_portx <= 8'h00; + porta_ddrx <= 8'h00; + portb_portx <= 8'h00; + portb_ddrx <= 8'h00; + ser_out <= ~0; + ser_in <= ~0; + ser_tx_cnt <= 0; + ser_rx_cnt <= 0; + ser_brr <= 0; + ser_rx_data <= 8'h00; + ser_rxc <= 1'b0; + ser_fe <= 1'b0; + ser_dor <= 1'b0; + rxd_s <= 1'b1; + ocie0 <= 1'b0; + ocf0 <= 1'b0; + tcnt0 <= 0; + ocr0 <= 0; + end else begin + if (ser_tx_cnt == 0) begin + ser_out <= {1'b1,ser_out[10:1]}; + ser_tx_cnt <= ser_brr; + end else + ser_tx_cnt <= ser_tx_cnt - 1; + + if (ser_rx_cnt == 0) begin + ser_rx_cnt <= ser_brr; + if (!ser_in[0]) begin + ser_rx_data <= ser_in[8:1]; + ser_fe <= ~rxd_s; + ser_dor <= ser_rxc; + ser_rxc <= 1'b1; + ser_in <= ~0; + end else + ser_in <= { rxd_s, ser_in[8:1] }; + end else if (&ser_in && rxd_s) // if (ser_rx_cnt == 0) + ser_rx_cnt <= ser_brr >> 1; + else + ser_rx_cnt <= ser_rx_cnt - 1; + rxd_s <= rxd; + + if(cs && oe && addr == 6'h08) begin + /* UDR0 is read, clear RXC0, FE0, and DOR0 */ + ser_rxc <= 1'b0; + ser_fe <= 1'b0; + ser_dor <= 1'b0; + end + + if (tcnt0 == ocr0) begin + tcnt0 <= 0; + ocf0 <= 1'b1; + end else + tcnt0 <= tcnt0 + 1; + + if(cs && wstrb[0]) + case(addr) + 6'h00: porta_portx <= data_in[7:0]; + 6'h02: porta_ddrx <= data_in[7:0]; + 6'h04: portb_portx <= data_in[7:0]; + 6'h06: portb_ddrx <= data_in[7:0]; + 6'h08: ser_out <= {1'b1, data_in[7:0], 1'b0, 1'b1}; + 6'h0a: ser_brr[7:0] <= data_in[7:0]; + 6'h0c: tcnt0[7:0] <= data_in[7:0]; + 6'h0d: ocr0[7:0] <= data_in[7:0]; + 6'h0e: if (data_in[0]) ocf0 <= 1'b0; + 6'h0f: ocie0 <= data_in[0]; + endcase; // case (addr) + if(cs && wstrb[1]) + case(addr) + 6'h0a: ser_brr[15:8] <= data_in[15:8]; + 6'h0c: tcnt0[15:8] <= data_in[15:8]; + 6'h0d: ocr0[15:8] <= data_in[15:8]; + endcase; // case (addr) + if(cs && wstrb[2]) + case(addr) + 6'h0c: tcnt0[23:16] <= data_in[23:16]; + 6'h0d: ocr0[23:16] <= data_in[23:16]; + endcase; // case (addr) + end // else: !if(~nrst) + + always @(*) begin + data_out = 32'h00000000; + if (nrst && cs && oe) + case(addr) + 6'h00: data_out[7:0] = porta_portx; + 6'h01: data_out[7:0] = porta_pinx; + 6'h02: data_out[7:0] = porta_ddrx; + 6'h04: data_out[7:0] = portb_portx; + 6'h05: data_out[7:0] = portb_pinx; + 6'h06: data_out[7:0] = portb_ddrx; + 6'h08: data_out[7:0] = ser_rx_data; + 6'h09: data_out[7:0] = {ser_rxc, &ser_out, &ser_out, ser_fe, ser_dor, 3'b000}; + 6'h0a: data_out[15:0] = ser_brr; + 6'h0c: data_out[23:0] = tcnt0; + 6'h0d: data_out[23:0] = ocr0; + 6'h0e: data_out[0] = ocf0; + 6'h0f: data_out[0] = ocie0; + endcase // case (addr) + end + +endmodule // peripherals diff --git a/zeldin_iceGDROM/fpga/source/vexriscv/rst_gen.v b/zeldin_iceGDROM/fpga/source/vexriscv/rst_gen.v new file mode 100644 index 0000000000000000000000000000000000000000..8bbc9c855b8c29ad845ea24fda3c2f83f3f36549 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/vexriscv/rst_gen.v @@ -0,0 +1,13 @@ +module rst_gen(input clk, output reg nrst); + + reg [7:0] cnt = 0; + + always @(posedge clk) + if (&cnt) + nrst <= 1'b1; + else begin + nrst <= 1'b0; + cnt <= cnt + 1; + end + +endmodule // rst_gen diff --git a/zeldin_iceGDROM/fpga/source/vexriscv/vexriscv_wrapper.v b/zeldin_iceGDROM/fpga/source/vexriscv/vexriscv_wrapper.v new file mode 100644 index 0000000000000000000000000000000000000000..d43144aae0907793cbad38cfd4533450a7de6e61 --- /dev/null +++ b/zeldin_iceGDROM/fpga/source/vexriscv/vexriscv_wrapper.v @@ -0,0 +1,286 @@ +module vexriscv_wrapper ( + input clk, + output rst_out, + + // PORTA + inout[7:0] porta, + + // PORTB + inout[7:0] portb, + + // SDCARD + input sdcard_sck, + input sdcard_mosi, + output sdcard_miso, + + // UART related + input rxd, + output reg txd, + + // EXTRAM i/f + output wire[15:0] extram_a, + input wire[31:0] extram_d_in, + output wire[31:0] extram_d_out, + output wire extram_cs, + output wire extram_oe, + output wire[3:0] extram_wstrb, + + // IRQ + input wire ext_irq3 + ); + + parameter CLK_FREQUENCY = 50000000; + parameter AVR109_BAUD_RATE = 19200; + parameter mem_init = ""; + parameter mem_size = 1; + + // ------------------------------- + // Reset generator + + wire nrst; + assign rst_out = ~nrst; + + rst_gen rst_gen_inst(.clk(clk), .nrst(nrst)); + + + // ------------------------------- + // AVR109 + + wire prog_mode; + wire intercept_mode; + wire [15:0] prog_addr; + wire [15:0] prog_data; + wire prog_low; + wire prog_high; + wire txd_core; + wire txd_avr109; + + avr109 #(.CLK_FREQUENCY(CLK_FREQUENCY), .BAUD_RATE(AVR109_BAUD_RATE)) + avr109_inst(.rst(~nrst), .clk(clk), + .rxd(rxd), .txd(txd_avr109), .intercept_mode(intercept_mode), + .prog_mode(prog_mode), .prog_addr(prog_addr), + .prog_data(prog_data), + .prog_data_in(prog_addr[0]? ram_read[31:16] : ram_read[15:0]), + .prog_low(prog_low), .prog_high(prog_high)); + + always @(posedge clk) + txd <= (nrst ? (intercept_mode ? txd_avr109 : txd_core ) : 1'b1); + + + // ------------------------------- + // VexRiscv Core + + wire iBus_cmd_valid; + wire iBus_cmd_ready; + wire [31:0] iBus_cmd_payload_pc; + wire iBus_rsp_valid; + wire iBus_rsp_payload_error; + wire [31:0] iBus_rsp_payload_inst; + wire dBus_cmd_valid; + wire dBus_cmd_ready; + wire dBus_cmd_payload_wr; + wire [31:0] dBus_cmd_payload_address; + wire [31:0] dBus_cmd_payload_data; + wire [1:0] dBus_cmd_payload_size; + wire dBus_rsp_ready; + wire dBus_rsp_error; + wire [31:0] dBus_rsp_data; + + VexRiscv cpu(.iBus_cmd_valid(iBus_cmd_valid), + .iBus_cmd_ready(iBus_cmd_ready), + .iBus_cmd_payload_pc(iBus_cmd_payload_pc), + .iBus_rsp_valid(iBus_rsp_valid), + .iBus_rsp_payload_error(iBus_rsp_payload_error), + .iBus_rsp_payload_inst(iBus_rsp_payload_inst), + .timerInterrupt(timer0_comp_irq), + .externalInterrupt(ext_irq3), + .softwareInterrupt(1'b0), + .dBus_cmd_valid(dBus_cmd_valid), + .dBus_cmd_ready(dBus_cmd_ready), + .dBus_cmd_payload_wr(dBus_cmd_payload_wr), + .dBus_cmd_payload_address(dBus_cmd_payload_address), + .dBus_cmd_payload_data(dBus_cmd_payload_data), + .dBus_cmd_payload_size(dBus_cmd_payload_size), + .dBus_rsp_ready(dBus_rsp_ready), + .dBus_rsp_error(dBus_rsp_error), + .dBus_rsp_data(dBus_rsp_data), + .clk(clk), .reset(rst_out | prog_mode)); + + // ------------------------------- + // Memory/IO Interface + + reg [31:0] ram[0:(mem_size*256)-1]; + reg [31:0] ram_read; + reg [13:0] ram_read_addr; + reg ram_read_enable; + + wire dbus_ram_access; + // assign dbus_ram_access = dBus_cmd_payload_address < mem_size * 1024; + assign dbus_ram_access = dBus_cmd_payload_address[31] == 1'b0; + + generate + if (mem_init == "") begin : no_initdata + ; + end else begin : yes_initdata + initial $readmemh(mem_init, ram); + end + endgenerate + + always @(*) begin + ram_read_enable = 1'b1; + ram_read_addr = 14'hx; + if (prog_mode) begin + ram_read_addr = prog_addr >> 1; + end else if (!rst_out) begin + if (dBus_cmd_valid && !dBus_cmd_payload_wr && dbus_ram_access) + ram_read_addr = dBus_cmd_payload_address[15:2]; + else if (ibus_stalled) + ram_read_addr = ibus_stall_pc; + else if (iBus_cmd_valid) + ram_read_addr = iBus_cmd_payload_pc[15:2]; + else + ram_read_enable = 1'b0; + end else + ram_read_enable = 1'b0; + end + + always @(posedge clk) + if (ram_read_enable) + ram_read <= ram[ram_read_addr]; + + + /* iBus */ + + reg ibus_valid; + reg ibus_ready; + reg ibus_stalled; + reg [15:2] ibus_stall_pc; + + assign iBus_cmd_ready = ibus_ready; + assign iBus_rsp_valid = ibus_valid; + assign iBus_rsp_payload_error = 1'b0; + assign iBus_rsp_payload_inst = ram_read; + + always @(posedge clk) + if (prog_mode || rst_out) begin + ibus_valid <= 1'b0; + ibus_ready <= 1'b0; + ibus_stalled <= 1'b0; + end else if (dBus_cmd_valid && !dBus_cmd_payload_wr && dbus_ram_access) begin + if (iBus_cmd_valid && ibus_ready) begin + // Stall until dBus read complete + ibus_valid <= 1'b0; + ibus_ready <= 1'b0; + ibus_stalled <= 1'b1; + ibus_stall_pc <= iBus_cmd_payload_pc[15:2]; + end + end else if (ibus_stalled) begin + // Clear stall + ibus_valid <= 1'b1; + ibus_ready <= 1'b1; + ibus_stalled <= 1'b0; + end else if(iBus_cmd_valid && ibus_ready) begin + // Can read without stall + ibus_valid <= 1'b1; + ibus_ready <= 1'b1; + end else begin + ibus_valid <= 1'b0; + ibus_ready <= 1'b1; + end + + /* dBus */ + + reg dbus_ready; + reg [31:0] reg_read; + reg dbus_regspace; + + wire dbus_reg_access; + wire valid_internal_reg, valid_external_reg; + wire [3:0] write_mask; + assign dbus_reg_access = !dbus_ram_access; + assign write_mask = (dBus_cmd_payload_size == 2'b00 ? + 4'b0001 << dBus_cmd_payload_address[1:0] : + (dBus_cmd_payload_size == 2'b01 ? + (dBus_cmd_payload_address[1]? 4'b1100 : 4'b0011) : + 4'b1111)); + assign valid_internal_reg = &dBus_cmd_payload_address[31:8]; + assign valid_external_reg = &dBus_cmd_payload_address[31:17] && + dBus_cmd_payload_address[16:13] == 4'b0111; + + assign dBus_cmd_ready = 1'b1; + assign dBus_rsp_ready = dbus_ready; + assign dBus_rsp_error = 1'b0; + assign dBus_rsp_data = (dbus_regspace? reg_read : ram_read); + + assign extram_a = dBus_cmd_payload_address[15:0]; + assign extram_d_out = dBus_cmd_payload_data; + assign extram_cs = dbus_reg_access && valid_external_reg; + assign extram_oe = dBus_cmd_valid && !dBus_cmd_payload_wr; + assign extram_wstrb = (dBus_cmd_valid && dBus_cmd_payload_wr? write_mask : 4'b0000); + + always @(posedge clk) begin + + if (prog_mode) begin + dbus_ready <= 1'b0; + if (prog_high) begin + if (prog_addr[0]) + ram[prog_addr >> 1][31:24] <= prog_data; + else + ram[prog_addr >> 1][15:8] <= prog_data; + end else if (prog_low) begin + if (prog_addr[0]) + ram[prog_addr >> 1][23:16] <= prog_data; + else + ram[prog_addr >> 1][7:0] <= prog_data; + end + end else if (rst_out || !dBus_cmd_valid) + dbus_ready <= 1'b0; + else begin + dbus_ready <= 1'b1; + if (dbus_ram_access) begin + dbus_regspace <= 1'b0; + if (dBus_cmd_payload_wr) begin + if (write_mask[0]) ram[dBus_cmd_payload_address[15:2]][7:0] <= dBus_cmd_payload_data[7:0]; + if (write_mask[1]) ram[dBus_cmd_payload_address[15:2]][15:8] <= dBus_cmd_payload_data[15:8]; + if (write_mask[2]) ram[dBus_cmd_payload_address[15:2]][23:16] <= dBus_cmd_payload_data[23:16]; + if (write_mask[3]) ram[dBus_cmd_payload_address[15:2]][31:24] <= dBus_cmd_payload_data[31:24]; + end + end else if (dbus_reg_access) begin + dbus_regspace <= 1'b1; + if (!dBus_cmd_payload_wr) begin + if (valid_internal_reg) + reg_read <= periph_rdata; + else if (valid_external_reg) + reg_read <= extram_d_in; + else + reg_read <= 0; + end + end + end // else: !if(rst_out || !dBus_cmd_valid) + end // always @ (posedge clk) + + // ------------- + // Periherals + + wire [31:0] periph_rdata; + wire timer0_comp_irq; + + peripherals peripherals_inst(.clk(clk), + .nrst(nrst), + .data_out(periph_rdata), + .data_in(dBus_cmd_payload_data), + .addr(dBus_cmd_payload_address[7:2]), + .cs(dbus_reg_access && valid_internal_reg), + .oe(dBus_cmd_valid && !dBus_cmd_payload_wr), + .wstrb(dBus_cmd_valid && dBus_cmd_payload_wr? + write_mask : 4'b0000), + + .porta(porta), .portb(portb), + .sdcard_sck(sdcard_sck), + .sdcard_mosi(sdcard_mosi), + .sdcard_miso(sdcard_miso), + .rxd(intercept_mode | rxd), .txd(txd_core), + .timer0_comp_irq(timer0_comp_irq) + ); + +endmodule // vexriscv_wrapper diff --git a/zeldin_iceGDROM/pcb/riser/bom.txt b/zeldin_iceGDROM/pcb/riser/bom.txt new file mode 100644 index 0000000000000000000000000000000000000000..95be822d383376f353d5e750b67007b5df02d788 --- /dev/null +++ b/zeldin_iceGDROM/pcb/riser/bom.txt @@ -0,0 +1,21 @@ +Quantity Designation Description Mouser SKU +======== =========== ============================ ======================= +1 - iCE40-HX8K breakout board 842-ICE40HX8K-B-EVN +2 CN2, CN3 20x2 socket header 517-929975-01-20 +2 J3, J4 20x2 pin header 517-929836-01-20 +1 CN6 USB A female 571-292303-3 +4 - 11mm spacer 761-M0540-3-N +4 - M3 nylon hex nut 534-4688 +4 - M3 nylon screw 16mm 534-29346 +1 X1 11.2896MHz oscillator 732-SG210STF11.289S3 +1 C1 0.01uF - 0.1uF capacitor 581-CB018B0103J +1 CN1 Molex 52602-0579 connector 538-52602-0579 +1 CN5 9 pin header 517-9611096804AR +4 JP1-JP4 3 pin header 517-9611036804AR +4 - Jumper 571-28815452 +5 R2-R6 100 Ohm resistor 603-MFR-25FRF52100R +2 R1, R7 10k Ohm resistor 603-MFR-25FRF5210K +1 CN4 22x2 pin header 517-951244-8622-AR +1 D1 LED 3mm 1.9V 2mA 604-WP710A10LGD +1 R8 1k Ohm resistor 603-MFR-25FRF521K + diff --git a/zeldin_iceGDROM/rv32/source/cdda.c b/zeldin_iceGDROM/rv32/source/cdda.c new file mode 100644 index 0000000000000000000000000000000000000000..ab3520dd9739ac3db026f26999afe2fb0d487592 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/cdda.c @@ -0,0 +1,206 @@ +#include +#include +#include + +#include "config.h" + +#include "debug.h" +#include "cdda.h" +#include "hardware.h" +#include "timer.h" +#include "imgfile.h" +#include "ide.h" + +uint8_t cdda_subcode_q[12]; + +bool cdda_active = false; +uint8_t cdda_toc = 0; +static uint8_t cdda_next_index; +static uint8_t cdda_subframe; + +static uint32_t cdda_start_blk, cdda_end_blk, cdda_blk, cdda_next_track; +static uint8_t cdda_repeat; + +#ifdef CDDA_SUBCHANNEL_Q +static void advance_msf(uint8_t *p) +{ + if ((p[2]&0xf) == 9) { + p[2] += 7; + return; + } + if (p[2] != 0x74) { + p[2] ++; + return; + } + p[2] = 0; + if ((p[1]&0x0f) != 9) { + p[1] ++; + return; + } + if (p[1] != 0x59) { + p[1] += 7; + return; + } + p[1] = 0; + if ((p[0]&0x0f) != 9) { + p[0] ++; + return; + } + p[0] += 7; +} + +static uint32_t tobcd(uint32_t v) +{ + uint8_t l = v%10; + v /= 10; + return (v<<4)|l; +} + +static void set_msf(uint8_t *p, uint32_t blk) +{ + uint8_t m = blk/4500; + uint16_t sf = blk%4500; + uint8_t s = sf/75; + uint8_t f = sf%75; + p[0] = tobcd(m); + p[1] = tobcd(s); + p[2] = tobcd(f); +} +#endif + +static void setup_subchannel_q() +{ +#ifdef CDDA_SUBCHANNEL_Q + cdda_subcode_q[1] = 0xaa; + cdda_subcode_q[2] = 0x01; + set_msf(&cdda_subcode_q[3], 0); + set_msf(&cdda_subcode_q[7], cdda_blk); +#endif + + uint8_t tr; + uint8_t emph = 0; + const struct toc *t = (cdda_toc? &toc[1] : &toc[0]); + const struct tocentry *e = &t->lead_out; + { + union { uint32_t fad; uint8_t b[4]; } u; + u.b[0] = e->fad[2]; + u.b[1] = e->fad[1]; + u.b[2] = e->fad[0]; + u.b[3] = 0; + cdda_next_track = u.fad; + } + e = &t->entry[0]; + for (tr=1; tr<100; tr++, e++) + if (e->ctrl_adr != 0xff) { + union { uint32_t fad; uint8_t b[4]; } u; + u.b[0] = e->fad[2]; + u.b[1] = e->fad[1]; + u.b[2] = e->fad[0]; + u.b[3] = 0; + if (u.fad > cdda_blk) { + cdda_next_track = u.fad; + break; + } +#ifdef CDDA_SUBCHANNEL_Q + cdda_subcode_q[1] = tobcd(tr); + set_msf(&cdda_subcode_q[3], cdda_blk - u.fad); +#endif + emph = e->ctrl_adr & 0x10; + } + if (emph) + PORTB |= _BV(EMPH_BIT); + else + PORTB &= ~_BV(EMPH_BIT); +} + +static bool cdda_fill_buffer() +{ + if (!imgfile_read_next_sector_cdda(cdda_next_index)) + return false; + + CDDA_LIMIT = (cdda_next_index << 7)|0x7f; + + cdda_next_index ^= 1; + + if ((cdda_subframe += (512/16)) >= (2352/16)) { + cdda_subframe -= (2352/16); + /* Advance sector # */ +#ifdef CDDA_SUBCHANNEL_Q + advance_msf(&cdda_subcode_q[3]); + advance_msf(&cdda_subcode_q[7]); +#endif + cdda_blk++; + if (cdda_blk == cdda_next_track) { + setup_subchannel_q(); + } + if (cdda_blk == cdda_end_blk) { + if (cdda_repeat) { + if (cdda_repeat < 15) + --cdda_repeat; + cdda_blk = cdda_start_blk; + setup_subchannel_q(); + if (imgfile_seek_cdda(cdda_blk)) + return true; + } + return false; + } + } + + return true; +} + +void cdda_start(uint32_t start_blk, uint32_t end_blk, uint8_t repeat) +{ + CDDA_CONTROL = 0x00; + cdda_blk = cdda_start_blk = start_blk; + cdda_end_blk = end_blk; + cdda_repeat = repeat; + setup_subchannel_q(); + cdda_next_index = 0; + cdda_subframe = 0; + if (cdda_fill_buffer() && cdda_fill_buffer()) { + DEBUG_PUTS("CDDA start ok\n"); + CDDA_READPOS = 0; + CDDA_CONTROL = 0x03; + cdda_active = true; + } else { + DEBUG_PUTS("CDDA start failed!\n"); + cdda_active = false; + } +} + +void cdda_stop() +{ + CDDA_CONTROL = 0x00; + cdda_active = false; + memset(cdda_subcode_q, 0, sizeof(cdda_subcode_q)); +} + +void service_cdda() +{ + if (!cdda_active) + return; + + uint8_t p = CDDA_READPOS >> 7; + if (p == cdda_next_index) + return; + + if (!cdda_fill_buffer()) { + cdda_stop(); + set_secnr(); + return; + } + + uint8_t c = CDDA_CONTROL; + if (c&2) { + DEBUG_PUTS("{UR "); + DEBUG_PUTX(centis); + DEBUG_PUTC('}'); + CDDA_CONTROL = c; + } +} + +uint8_t cdda_get_status() +{ + return (cdda_active? 0x11 : 0x00); +} diff --git a/zeldin_iceGDROM/rv32/source/cdda.h b/zeldin_iceGDROM/rv32/source/cdda.h new file mode 100644 index 0000000000000000000000000000000000000000..638f331ea9b5d011f9472d2bdca33761c5e09cc4 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/cdda.h @@ -0,0 +1,10 @@ + +extern void cdda_start(uint32_t start_blk, uint32_t end_blk, uint8_t repeat); +extern void cdda_stop(); +extern void service_cdda(); +extern uint8_t cdda_get_status(); + +extern bool cdda_active; +extern uint8_t cdda_toc; +extern uint8_t cdda_subcode_q[12]; + diff --git a/zeldin_iceGDROM/rv32/source/config.h b/zeldin_iceGDROM/rv32/source/config.h new file mode 100644 index 0000000000000000000000000000000000000000..b57e288595f951a6da0ce8dd6c5f15029486405d --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/config.h @@ -0,0 +1,34 @@ + +#define CPU_FREQ 39513600 + + +/* Define as 1 if the CD pin is shorted to GND when the card is removed */ +/* Define as 0 if the CD pin is shorted to GND when the card is inserted */ + +#define SD_CD_PIN_ACTIVE_HIGH 0 + + +/* Comment out to enable debug printouts on serial port */ + +#define NDEBUG + + +/* Uncomment to get extra IDE debug */ + +/* #define IDEDEBUG */ + + +/* Set to desired baudrate for serial debug output */ + +#define BAUDRATE 115200 + + +/* Comment out to disable subchannel Q emulation */ + +#define CDDA_SUBCHANNEL_Q + + +/* Comment out to disable skipahead index */ + +#define FATFS_SKIPAHEAD_INDEX + diff --git a/zeldin_iceGDROM/rv32/source/debug.c b/zeldin_iceGDROM/rv32/source/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..3696d91c2eb5c13599915608ac84f3b10b63f44a --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/debug.c @@ -0,0 +1,44 @@ +#include + +#include "config.h" + +#include "hardware.h" +#include "debug.h" + +#ifndef NDEBUG + +void debug_init() +{ + UBRR0 = CPU_FREQ / BAUDRATE - 1; +} + +void debug_putc(char c) +{ + if (c == '\n') + debug_putc('\r'); + loop_until_bit_is_set(UCSR0, UDRE); + UDR0 = c; +} + +static void debug_putx1(uint8_t x) +{ + if((x &= 0xf) < 10) + debug_putc('0'+x); + else + debug_putc(('A'-10)+x); +} + +void debug_putx(uint8_t x) +{ + debug_putx1(x>>4); + debug_putx1(x); +} + +void debug_puts(const char *str) +{ + char c; + while ((c = *str++)) + debug_putc(c); +} + +#endif diff --git a/zeldin_iceGDROM/rv32/source/debug.h b/zeldin_iceGDROM/rv32/source/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..bfd44ec713167f73e449d398dcd9ec3e8ac3233f --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/debug.h @@ -0,0 +1,21 @@ + +#ifdef NDEBUG + +#define DEBUG_INIT() do{}while(0) +#define DEBUG_PUTC(c) do{(void)(c);}while(0) +#define DEBUG_PUTX(x) do{(void)(x);}while(0) +#define DEBUG_PUTS(s) do{}while(0) + +#else + +#define DEBUG_INIT() debug_init() +#define DEBUG_PUTC(c) debug_putc(c) +#define DEBUG_PUTX(x) debug_putx(x) +#define DEBUG_PUTS(s) debug_puts(s) + +extern void debug_init(); +extern void debug_putc(char c); +extern void debug_putx(uint8_t x); +extern void debug_puts(const char *str); + +#endif diff --git a/zeldin_iceGDROM/rv32/source/delay.h b/zeldin_iceGDROM/rv32/source/delay.h new file mode 100644 index 0000000000000000000000000000000000000000..1bd308512434ad12def279af7c5894aaa9f44dda --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/delay.h @@ -0,0 +1,3 @@ +extern void delay1ms(); +extern void delayms(int32_t ms); +extern void delaycycles(int32_t cycles); diff --git a/zeldin_iceGDROM/rv32/source/fatfs.c b/zeldin_iceGDROM/rv32/source/fatfs.c new file mode 100644 index 0000000000000000000000000000000000000000..9c46a9488e8d0ccb635f6fa1adca3a79fdbf702c --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/fatfs.c @@ -0,0 +1,362 @@ +#include +#include +#include + +#include "config.h" + +#include "sdcard.h" +#include "fatfs.h" +#include "debug.h" + +#define NUM_CACHE_SLOTS 4 + +static uint8_t cache[NUM_CACHE_SLOTS][512]; +static uint32_t cache_block_nr[NUM_CACHE_SLOTS]; +static uint8_t cache_lru[NUM_CACHE_SLOTS]; +static uint32_t fat_start, data_start, root_dir_start; +static uint16_t root_dir_entries; +static uint8_t cluster_shift, blocks_per_cluster; +static bool fat32; +static uint32_t file_start_cluster; +#ifdef FATFS_SKIPAHEAD_INDEX +#define NUM_SKIPAHEAD_ENTRIES 40 +static uint32_t skipahead_index[NUM_SKIPAHEAD_ENTRIES]; +#endif + +#define FAT_EOC 0x80000000 +#define FAT_ERROR 0x40000000 + +char filename[11] = "DISC0000GI0"; +uint8_t fatfs_filenumber = 0; + +static void reset_cache() +{ + uint8_t slot; + for (slot = 0; slot < NUM_CACHE_SLOTS; slot++) { + cache_block_nr[slot] = ~0; + cache_lru[slot] = slot; + } +} + +#ifdef FATFS_SKIPAHEAD_INDEX +static void init_skipahead_index() +{ + unsigned i; + skipahead_index[0] = file_start_cluster; + for (i=1; i= NUM_CACHE_SLOTS) { + if (xslot < NUM_CACHE_SLOTS) + slot = xslot; + else { + for (slot = 0; slot < NUM_CACHE_SLOTS-1; slot++) { + if (cache_lru[slot] == NUM_CACHE_SLOTS-1) + break; + } + } + } + if (nr != cache_block_nr[slot]) { + cache_block_nr[slot] = nr; + if (!sd_read_block(nr, cache[slot])) { + cache_block_nr[slot] = ~0; + return NULL; + } + } + uint8_t i, old_lru = cache_lru[slot]; + for (i=0; i>= 7; + } else { + n = (uint8_t)cluster; + cluster >>= 8; + } + uint8_t *fat_block = read_block(fat_start+cluster); + if (!fat_block) + return FAT_ERROR|FAT_EOC; + if (fat32) { + cluster = (((uint32_t*)fat_block)[n])&0x0fffffff; + if (cluster >= 0x0ffffff8) + cluster |= FAT_EOC; + } else { + cluster = ((uint16_t*)fat_block)[n]; + if (((uint16_t)cluster) >= 0xfff8) + cluster |= FAT_EOC; + } + if (cluster < 2) + cluster |= FAT_ERROR|FAT_EOC; + return cluster; +} + +static bool check_root_block(uint32_t part_start) +{ + uint8_t *data_block = read_block(part_start); + if (!data_block) + return false; + + if(data_block[0x1fe] != 0x55 || + data_block[0x1ff] != 0xaa) + return false; + + /* Check file system type */ + if (data_block[82] != 'F' || data_block[83] != 'A' || data_block[84] != 'T') + return false; + + /* Check required parameters */ + if (data_block[11] != 0 || data_block[12] != 2 || /* 512 bytes per sector */ + (data_block[14] == 0 && data_block[15] == 0) || /* reserved sectors > 0 */ + data_block[16] != 2) /* fat count */ + return false; + + uint8_t i = 0, n = 1; + do { + if (data_block[13] == n) + break; + i++; + n<<=1; + } while(n); + if (!n) + return false; + cluster_shift=i; + blocks_per_cluster = n; + + uint16_t rds = data_block[17] + (data_block[18]<<8); /* rootDirEntryCount */ + root_dir_entries = rds; + rds = (rds >> 4) + ((((uint8_t)rds)&0xf)? 1:0); + uint32_t bpf = *(uint16_t*)(data_block+22); /* sectorsPerFat16 */ + if (!(uint16_t)bpf) + bpf = *(uint32_t*)(data_block+36); /* sectorsPerFat32 */ + uint32_t ds = *(uint16_t*)(data_block+14) + part_start; + fat_start = ds; + ds += bpf<<1; + root_dir_start = ds; + ds += rds; + data_start = ds - (((uint16_t)2)<>= i; + if (cc < 65525) { + if (((uint16_t)cc) < 4085) { + /* FAT12 not supported */ + return false; + } + fat32 = false; + } else { + fat32 = true; + root_dir_start = *(uint32_t*)(data_block+44); + } + + DEBUG_PUTS("Mounted fs with "); + DEBUG_PUTX((uint8_t)(cc>>24)); + DEBUG_PUTX((uint8_t)(cc>>16)); + DEBUG_PUTX((uint8_t)(cc>>8)); + DEBUG_PUTX((uint8_t)cc); + DEBUG_PUTS(" clusters\n"); + + return true; +} + +bool fatfs_mount() +{ + reset_cache(); + if (check_root_block(0)) + return true; + /* Not a valid FAT root block at 0, check for partition table */ + uint8_t *data_block = read_block(0); + if(!data_block || + data_block[0x1fe] != 0x55 || + data_block[0x1ff] != 0xaa) + return false; + if ((data_block[0x1be] & 0x7f) != 0) + return false; + uint32_t part_start = *(uint16_t*)(data_block+0x1c6); + part_start += (*(uint16_t*)(data_block+0x1c8)) << 16; + if (!part_start) + return false; + return check_root_block(part_start); +} + +bool fatfs_read_rootdir() +{ + uint32_t blk = root_dir_start; + uint16_t rde = root_dir_entries; + uint8_t entry = 0, cnr = 0; + const uint8_t *p; + for (;;) { + if (!fat32 && !rde) + break; + if (!entry) { + if (fat32) { + p = read_cluster_block(blk, cnr++); + } else { + p = read_block(blk++); + } + if (!p) + return false; + } + if (!*p) + break; + if (*p != 0xe5 && (p[11]&0x3f) != 0x0f) { + DEBUG_PUTS("Entry "); + int i; + for(i=0; i<11; i++) + DEBUG_PUTC(p[i]); + DEBUG_PUTC('\n'); + if (!memcmp(p, filename, 11)) { + DEBUG_PUTS("Found target at "); + if (fat32) { + DEBUG_PUTX(p[21]); + DEBUG_PUTX(p[20]); + } + DEBUG_PUTX(p[27]); + DEBUG_PUTX(p[26]); + DEBUG_PUTC('\n'); + file_start_cluster = *(uint16_t *)(p+26); + if (fat32) { + file_start_cluster |= (*(uint16_t *)(p+20)) << 16; + } +#ifdef FATFS_SKIPAHEAD_INDEX + init_skipahead_index(); +#endif + return true; + } + } + p += 32; + --rde; + if (++entry == 16) { + entry = 0; + if (fat32) { + if (cnr == blocks_per_cluster) { + cnr = 0; + blk = get_fat_entry(blk); + if (blk & FAT_EOC) + break; + } + } + } + } + return false; +} + +bool fatfs_seek(struct fatfs_handle *handle, uint32_t sector_nr) +{ + uint32_t hpos = handle->pos & ~(blocks_per_cluster-1); +#ifdef FATFS_SKIPAHEAD_INDEX + uint32_t idx = sector_nr >> 16; + if (idx > NUM_SKIPAHEAD_ENTRIES) + idx = NUM_SKIPAHEAD_ENTRIES - 1; + while (idx > 0 && (skipahead_index[idx] & FAT_ERROR)) + --idx; + if (hpos > sector_nr || hpos < (idx << 16)) { + hpos = idx << 16; + handle->cluster_nr = skipahead_index[idx]; + } +#else + if (hpos > sector_nr) { + handle->cluster_nr = file_start_cluster; + hpos = 0; + } +#endif + while((sector_nr ^ hpos) >= blocks_per_cluster) { + if (handle->cluster_nr & FAT_EOC) + break; + handle->cluster_nr = get_fat_entry(handle->cluster_nr); + hpos += blocks_per_cluster; +#ifdef FATFS_SKIPAHEAD_INDEX + if (!(hpos & 0xffffu)) { + uint32_t idx = hpos >> 16; + if (idx < NUM_SKIPAHEAD_ENTRIES) + skipahead_index[idx] = handle->cluster_nr; + } +#endif + } + handle->pos = sector_nr; + return true; +} + +bool fatfs_read_next_sector(struct fatfs_handle *handle, uint8_t *buf) +{ + if (handle->cluster_nr & FAT_EOC) + return false; + uint8_t blk = (handle->pos&0xff)&(blocks_per_cluster-1); + if (buf) { + if (!sd_read_block(data_start+(handle->cluster_nr<cluster_nr = get_fat_entry(handle->cluster_nr); + handle->pos++; +#ifdef FATFS_SKIPAHEAD_INDEX + if (!(handle->pos & 0xffffu)) { + uint32_t idx = handle->pos >> 16; + if (idx < NUM_SKIPAHEAD_ENTRIES) + skipahead_index[idx] = handle->cluster_nr; + } +#endif + return true; +} + + +bool fatfs_read_header(void *buf, uint16_t size, uint8_t blk) +{ + uint32_t clu = file_start_cluster; + while (blk >= blocks_per_cluster) { + clu = get_fat_entry(clu); + if (clu & FAT_EOC) + return false; + blk -= blocks_per_cluster; + } + uint8_t *data_block = read_cluster_block(clu, blk); + if (!data_block) + return false; + memcpy(buf, data_block, size); + return true; +} + +void fatfs_reset_filename() +{ + memset(filename+4, '0', 4); + fatfs_filenumber = 0; +} + +void fatfs_next_filename() +{ + char *p = filename+8; + while (*--p <= '9') { + if (*p == '9') { + *p = '0'; + } else { + (*p)++; + break; + } + } + fatfs_filenumber++; +} diff --git a/zeldin_iceGDROM/rv32/source/fatfs.h b/zeldin_iceGDROM/rv32/source/fatfs.h new file mode 100644 index 0000000000000000000000000000000000000000..8c94c3e41248086030a396891bc3857532120763 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/fatfs.h @@ -0,0 +1,12 @@ +struct fatfs_handle { + uint32_t cluster_nr; + uint32_t pos; +}; +extern bool fatfs_mount(); +extern bool fatfs_read_rootdir(); +extern bool fatfs_seek(struct fatfs_handle *handle, uint32_t sector_nr); +extern bool fatfs_read_next_sector(struct fatfs_handle *handle, uint8_t *buf); +extern bool fatfs_read_header(void *buf, uint16_t size, uint8_t blk); +extern void fatfs_reset_filename(); +extern void fatfs_next_filename(); +extern uint8_t fatfs_filenumber; diff --git a/zeldin_iceGDROM/rv32/source/hardware.h b/zeldin_iceGDROM/rv32/source/hardware.h new file mode 100644 index 0000000000000000000000000000000000000000..ae65a06c8f8bbf0ff855716095cee3f2b4fba77b --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/hardware.h @@ -0,0 +1,97 @@ +#define SD_CD_PIN PINB +#define SD_CD_BIT PIN7 + +#define EMPH_BIT PIN0 + +#ifdef __ASSEMBLER__ +#define _MMIO_BYTE(addr) addr +#define _MMIO_WORD(addr) addr +#else +#define _MMIO_BYTE(addr) (*(volatile uint8_t *)(void *)(addr)) +#define _MMIO_WORD(addr) (*(volatile uint32_t *)(void *)(addr)) +#endif + +#define PORTA _MMIO_BYTE(0xffffff00) +#define PINA _MMIO_BYTE(0xffffff04) +#define DDRA _MMIO_BYTE(0xffffff08) +#define PORTB _MMIO_BYTE(0xffffff10) +#define PINB _MMIO_BYTE(0xffffff14) +#define DDRB _MMIO_BYTE(0xffffff18) +#define UDR0 _MMIO_WORD(0xffffff20) +#define UCSR0 _MMIO_WORD(0xffffff24) +#define UBRR0 _MMIO_WORD(0xffffff28) +#define TCNT0 _MMIO_WORD(0xffffff30) +#define OCR0 _MMIO_WORD(0xffffff34) +#define TIFR _MMIO_WORD(0xffffff38) +#define TIMSK _MMIO_WORD(0xffffff3c) + +#define PIN0 0 +#define PIN1 1 +#define PIN2 2 +#define PIN3 3 +#define PIN4 4 +#define PIN5 5 +#define PIN6 6 +#define PIN7 7 + +#define PB0 PIN0 +#define PB1 PIN1 +#define PB2 PIN2 +#define PB3 PIN3 +#define PB4 PIN4 +#define PB5 PIN5 +#define PB6 PIN6 +#define PB7 PIN7 + +#define RXC 7 +#define TXC 6 +#define UDRE 5 +#define FE 4 +#define DOR 3 + +#define OCIE0 0 +#define OCF0 0 + +#define IDE_STATUS _MMIO_BYTE(0xfffef000) +#define IDE_ERROR _MMIO_BYTE(0xfffef004) +#define IDE_IOCONTROL _MMIO_BYTE(0xfffef008) +#define IDE_IOPOSITION _MMIO_BYTE(0xfffef00c) +#define IDE_ALT_STATUS _MMIO_BYTE(0xfffef010) +#define IDE_IOTARGET _MMIO_BYTE(0xfffef014) +#define IDE_DEVCON _MMIO_BYTE(0xfffef018) +#define IDE_FEATURES _MMIO_BYTE(0xfffef024) +#define IDE_SECCNT _MMIO_BYTE(0xfffef028) +#define IDE_SECNR _MMIO_BYTE(0xfffef02c) +#define IDE_CYLLO _MMIO_BYTE(0xfffef030) +#define IDE_CYLHI _MMIO_BYTE(0xfffef034) +#define IDE_DRVHEAD _MMIO_BYTE(0xfffef038) +#define IDE_COMMAND _MMIO_BYTE(0xfffef03c) + +#define IDE_DATA_BUFFER ((uint8_t *)0xfffef400) + +#define SDCARD_CONTROL _MMIO_BYTE(0xfffee400) +#define SDCARD_DATA _MMIO_BYTE(0xfffee404) +#define SDCARD_DIVIDER _MMIO_BYTE(0xfffee408) +#define SDCARD_CRC16 _MMIO_WORD(0xfffee410) +#define SDCARD_CRC7 _MMIO_BYTE(0xfffee414) + +#define CDDA_CONTROL _MMIO_BYTE(0xfffee800) +#define CDDA_READPOS _MMIO_BYTE(0xfffee804) +#define CDDA_LIMIT _MMIO_BYTE(0xfffee808) +#define CDDA_SCRATCHPAD _MMIO_BYTE(0xfffee80c) + +#define CDDA_DATA_BUFFER ((uint8_t *)0xfffeec00) + +#ifdef __ASSEMBLER__ +#define _BV(bit) (1<<(bit)) +#else +#define _BV(bit) (1U<<(bit)) +#endif + +#define bit_is_clear(reg, bit) (!((reg) & _BV(bit))) +#define bit_is_set(reg, bit) (!bit_is_clear(reg, bit)) +#define loop_until_bit_is_clear(reg, bit) do { } while(!bit_is_clear(reg, bit)) +#define loop_until_bit_is_set(reg, bit) do { } while(!bit_is_set(reg, bit)) + +#define cli() asm volatile("csrrci zero,mstatus,8" ::: "memory") +#define sei() asm volatile("csrrsi zero,mstatus,8" ::: "memory") diff --git a/zeldin_iceGDROM/rv32/source/ide.c b/zeldin_iceGDROM/rv32/source/ide.c new file mode 100644 index 0000000000000000000000000000000000000000..6a1c118901eb67aa19e2cb629cbd334b2ab658e1 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/ide.c @@ -0,0 +1,689 @@ +#include +#include +#include + +#include "config.h" + +#include "hardware.h" +#include "debug.h" +#include "fatfs.h" +#include "imgfile.h" +#include "cdda.h" + +#define DATA_MODE_IDLE 0 +#define DATA_MODE_PACKET 1 +#define DATA_MODE_LAST 2 +#define DATA_MODE_CONT 3 + +static uint8_t data_mode; + +#define SERVICE_MODE_IDLE 0 +#define SERVICE_MODE_RESET 1 +#define SERVICE_MODE_CMD 2 +#define SERVICE_MODE_DATA 3 + +static uint8_t service_mode; +static uint8_t service_dma; +static uint16_t service_sectors_left; +static uint8_t disk_type = 0xff; + +#define PRELOAD_NONE 0 +#define PRELOAD_AVAILABLE 1 +#define PRELOAD_FAILED 2 + +static uint8_t preload_status; + +static union { + uint8_t cmd; + uint8_t data[12]; + struct { + uint8_t cmd; + uint8_t pad1; + uint8_t start_addr; + uint8_t pad2; + uint8_t alloc_len; + } req_stat, req_mode, set_mode; + struct { + uint8_t cmd; + uint8_t pad[3]; + uint8_t alloc_len; + } req_error; + struct { + uint8_t cmd; + uint8_t select; + uint8_t pad; + uint8_t alloc_len_hi; + uint8_t alloc_len_lo; + } get_toc; + struct { + uint8_t cmd; + uint8_t pad1; + uint8_t session_nr; + uint8_t pad2; + uint8_t alloc_len; + } req_ses; + struct { + uint8_t cmd; + uint8_t ptype; + uint8_t start_point[3]; + uint8_t pad1; + uint8_t reptime; + uint8_t pad2; + uint8_t end_point[3]; + } cd_play; + struct { + uint8_t cmd; + uint8_t ptype; + uint8_t seek_point[3]; + } cd_seek; + struct { + uint8_t cmd; + uint8_t pad; + uint8_t dir; + uint8_t speed; + } cd_scan; + struct { + uint8_t cmd; + uint8_t flags; + uint8_t start_addr[3]; + uint8_t pad[3]; + uint8_t transfer_length[3]; + } cd_read; + struct { + uint8_t cmd; + uint8_t flags; + uint8_t start_addr[3]; + uint8_t pad; + uint8_t transfer_length[2]; + uint8_t next_addr[3]; + } cd_read2; + struct { + uint8_t cmd; + uint8_t format; + uint8_t pad; + uint8_t alloc_len_hi; + uint8_t alloc_len_lo; + } get_scd; +} packet; + +static void finish_packet(uint8_t error) __attribute__((noinline)); +static void finish_packet(uint8_t error) +{ + IDE_ERROR = error; + IDE_SECCNT = 0x03; /* I/O=1 C/D=1 REL=0 */ + IDE_STATUS = (error? 0x51 : 0x50); /* BSY=0 */ +} + +static void service_finish_packet(uint8_t error) +{ + cli(); + if (service_mode == SERVICE_MODE_IDLE) + finish_packet(error); + sei(); +} + +static void finish_packet_ok() +{ + finish_packet(0); +} + +static void packet_data_last(uint8_t cnt, uint8_t offs) __attribute__((noinline)); +static void packet_data_last(uint8_t cnt, uint8_t offs) +{ + + IDE_SECCNT = 0x02; /* C/D=0 I/O=1 REL=0 */ + IDE_CYLHI = (cnt? (cnt>>7) : 2); + IDE_CYLLO = (cnt<<1)&0xff; + + data_mode = DATA_MODE_LAST; + IDE_IOCONTROL = 0x02; /* PIO out */ + IDE_IOPOSITION = offs; + IDE_IOTARGET = cnt-1+offs; + IDE_STATUS = 0x58; /* DRQ = 1 BSY = 0 */ +} + +static void packet_data_last0(uint8_t cnt) +{ + packet_data_last(cnt, 0); +} + +static void packet_data_dma(uint8_t cnt, uint8_t offs) __attribute__((noinline)); +static void packet_data_dma(uint8_t cnt, uint8_t offs) +{ + + IDE_SECCNT = 0x02; /* C/D=0 I/O=1 REL=0 */ + IDE_CYLHI = (cnt? (cnt>>7) : 2); + IDE_CYLLO = (cnt<<1)&0xff; + + data_mode = DATA_MODE_CONT; + IDE_IOPOSITION = offs; + IDE_IOTARGET = cnt-1+offs; + IDE_IOCONTROL = 0x04; /* DMA out */ +} + +static void service_packet_data_last(uint8_t cnt, uint8_t offs) +{ + cli(); + if (service_mode == SERVICE_MODE_IDLE) + packet_data_last(cnt, offs); + sei(); +} + +static void service_packet_data_last0(uint8_t cnt) +{ + service_packet_data_last(cnt, 0); +} + +static void service_packet_data_cont(uint8_t cnt, uint8_t offs) +{ + cli(); + if (service_mode == SERVICE_MODE_IDLE) { + packet_data_last(cnt, offs); + data_mode = DATA_MODE_CONT; + } + sei(); +} + +static void service_packet_data_dma(uint8_t cnt, uint8_t offs) +{ + cli(); + if (service_mode == SERVICE_MODE_IDLE) + packet_data_dma(cnt, offs); + sei(); +} + +static const uint8_t gdrom_version[] = "Rev 5.07"; + +static const uint8_t cmd71_reply[] = { + 0xba, 0x06, 0x0d, 0xca, 0x6a, 0x1f +}; + + +static void do_req_mode() +{ + uint8_t addr = packet.req_mode.start_addr; + uint8_t len = packet.req_mode.alloc_len; + if (addr == 18 && len == 8) { + memcpy(&IDE_DATA_BUFFER[0], gdrom_version, sizeof(gdrom_version)); + packet_data_last0(8/2); + } else if(addr == 0 && len == 10) { + memset(IDE_DATA_BUFFER, 0, 10); /* FIXME */ + packet_data_last0(10/2); + } else + finish_packet(0x50); +} + +static void do_set_mode() +{ + uint8_t addr = packet.set_mode.start_addr; + uint8_t len = packet.set_mode.alloc_len; + if(addr == 0 && len == 10) { + IDE_SECCNT = 0x00; /* C/D=0 I/O=0 REL=0 */ + IDE_CYLHI = 0; + IDE_CYLLO = 10; + + data_mode = DATA_MODE_LAST; /* FIXME */ + IDE_IOCONTROL = 0x03; /* PIO in */ + IDE_IOPOSITION = 0x00; + IDE_IOTARGET = 4; + IDE_STATUS = 0x58; /* DRQ = 1 BSY = 0 */ + } else + finish_packet(0x50); +} + +static void do_cmd71() +{ + memcpy(&IDE_DATA_BUFFER[0], cmd71_reply, sizeof(cmd71_reply)); + + packet_data_last0(sizeof(cmd71_reply)/2); +} + +static void do_req_error() +{ + uint8_t i; + memset(IDE_DATA_BUFFER, 0, 10); /* FIXME */ + + packet_data_last0(10/2); +} + +static void process_packet() +{ + memcpy(&packet, IDE_DATA_BUFFER, 12); + IDE_IOCONTROL = 0x00; +#ifdef IDEDEBUG + DEBUG_PUTS("[PKT "); + DEBUG_PUTX(packet.cmd); + DEBUG_PUTS("]\n"); +#endif + switch (packet.cmd) { + case 0x71: + do_cmd71(); + break; + case 0x70: + case 0: /* TEST_UNIT */ + finish_packet_ok(); + break; + case 0x11: /* REQ_MODE */ + do_req_mode(); + break; + case 0x12: /* SET_MODE */ + do_set_mode(); + break; + case 0x13: /* REQ_ERROR */ + do_req_error(); + break; + + case 0x14: /* GET_TOC */ + case 0x15: /* REQ_SES */ + case 0x20: /* CD_PLAY */ + case 0x21: /* CD_SEEK */ + case 0x30: /* CD_READ */ + case 0x40: /* CD_SCD */ + service_dma = (IDE_FEATURES & 1); + service_mode = SERVICE_MODE_CMD; + break; + + default: + finish_packet(0x04); /* Abort */ + break; + } +} + +void set_secnr() +{ + if (disk_type == 0xff) + IDE_SECNR = 0x06; + else + IDE_SECNR = disk_type | (cdda_active? 0x03 : 0x02); +} + +static void reset_irq() +{ +#ifdef IDEDEBUG + DEBUG_PUTS("[RST]\n"); +#endif + data_mode = DATA_MODE_IDLE; + set_secnr(); + IDE_DEVCON = 0x01; /* Negate INTRQ */ + service_mode = SERVICE_MODE_RESET; +} + +static void cmd_irq() +{ +#ifdef IDEDEBUG + DEBUG_PUTS("[CMD "); + DEBUG_PUTX(IDE_COMMAND); + DEBUG_PUTC(']'); +#endif + data_mode = DATA_MODE_IDLE; + IDE_IOCONTROL = 0x00; + switch (IDE_COMMAND) { + case 0xa0: + /* Packet */ + data_mode = DATA_MODE_PACKET; + IDE_SECCNT = 0x01; /* C/D=1 I/O=0 REL=0 */ + IDE_IOCONTROL = 0x03; /* PIO in */ + IDE_IOPOSITION = 0x00; + IDE_IOTARGET = 0x05; /* transfer 6 words */ + IDE_ALT_STATUS = 0x58; /* DRQ = 1 BSY = 0 */ + break; + case 0xef: + /* Set features */ + if (IDE_FEATURES == 0x03) { + uint8_t mode = IDE_SECCNT; + if ((mode & 0xf8) == 0x08) { +#ifdef IDEDEBUG + DEBUG_PUTS("[PIO MODE "); + DEBUG_PUTX(mode & 0x07); + DEBUG_PUTS("]\n"); +#endif + } else if ((mode & 0xf8) == 0x20) { +#ifdef IDEDEBUG + DEBUG_PUTS("[DMA MODE "); + DEBUG_PUTX(mode & 0x07); + DEBUG_PUTS("]\n"); +#endif + } + IDE_ERROR = 0x00; + IDE_STATUS = 0x50; + break; + } + /* Fallthrough to abort */ + default: +#ifdef IDEDEBUG + DEBUG_PUTC('\n'); +#endif + /* Unknown command */ + IDE_ERROR = 0x04; /* Error = Abort */ + IDE_STATUS = 0x51; /* Error, not busy, assert INTRQ */ + break; + } +} + +static void data_irq() +{ + IDE_ALT_STATUS = 0xd0; /* BSY=1, DRQ=0 */ + IDE_IOCONTROL = 0x00; + switch(data_mode) { + case DATA_MODE_PACKET: + data_mode = DATA_MODE_IDLE; + IDE_IOCONTROL = 0x01; + process_packet(); + break; + case DATA_MODE_LAST: + data_mode = DATA_MODE_IDLE; +#ifdef IDEDEBUG + DEBUG_PUTS("[END]"); + DEBUG_PUTX(IDE_IOPOSITION); + DEBUG_PUTC('\n'); +#endif + finish_packet_ok(); + break; + case DATA_MODE_CONT: + service_mode = SERVICE_MODE_DATA; + break; + default: +#ifdef IDEDEBUG + DEBUG_PUTS("[*DATA]\n"); +#endif + IDE_ALT_STATUS = 0x50; + } +} + +void IRQ3_vect(void) __attribute__((interrupt)); +void IRQ3_vect(void) +{ + uint8_t devcon = IDE_DEVCON & 0x3c; + IDE_DEVCON = devcon; +#ifdef IDEDEBUG + DEBUG_PUTS("[IRQ "); + DEBUG_PUTX(devcon); + DEBUG_PUTC(']'); +#endif + if (devcon & 0x0c) + reset_irq(); + else if (devcon & 0x10) + cmd_irq(); + else if (devcon & 0x20) + data_irq(); +} + +static uint32_t get_fad(const uint8_t *bytes, bool msf) +{ + if (msf) { + uint32_t sec = bytes[0]*60+bytes[1]; + return sec*75+bytes[2]; + } else { + union { uint32_t fad; uint8_t b[4]; } u; + u.b[0] = bytes[2]; + u.b[1] = bytes[1]; + u.b[2] = bytes[0]; + u.b[3] = 0; + return u.fad; + } +} + +static void service_get_toc() +{ + uint8_t s = packet.get_toc.select; + if (s >= imgheader.num_tocs) { + service_finish_packet(0x50); + return; + } + memcpy(IDE_DATA_BUFFER, &toc[s], 408); + service_packet_data_last0(408/2); +} + +static void service_req_ses() +{ + uint8_t s = packet.req_ses.session_nr; + if (s >= imgheader.num_sessions) { + service_finish_packet(0x50); + return; + } + IDE_DATA_BUFFER[0] = IDE_SECNR&0x0f; + IDE_DATA_BUFFER[1] = 0; + memcpy(&IDE_DATA_BUFFER[2], imgheader.sessions[s], sizeof(imgheader.sessions[s])); + + service_packet_data_last0(6/2); +} + +static void service_cd_read_cont() +{ +#ifdef IDEDEBUG + if (service_dma) { + DEBUG_PUTS("[DMA READ CONT]["); + } else { + DEBUG_PUTS("[PIO READ CONT]["); + } +#endif + if (!service_sectors_left) { +#ifdef IDEDEBUG + DEBUG_PUTS("COMPLETE]\n"); +#endif + service_finish_packet(0); + return; + } + if (preload_status == PRELOAD_AVAILABLE) { + IDE_IOCONTROL = 0x80; + } else if (preload_status == PRELOAD_FAILED || !imgfile_read_next_sector(&IDE_DATA_BUFFER[0])) { +#ifdef IDEDEBUG + DEBUG_PUTS("READ ERROR]\n"); +#endif + service_finish_packet(0x04); /* Abort */ + return; + } + uint8_t offs = imgfile_data_offs; + uint8_t len = imgfile_data_len; + if (imgfile_sector_complete()) + --service_sectors_left; +#ifdef IDEDEBUG + IDE_IOCONTROL = 0x01; + uint8_t i = 0; + __asm__ __volatile__("" ::: "memory"); + do { + DEBUG_PUTX(IDE_DATA_BUFFER[((uint16_t)(i+offs))*2]); + DEBUG_PUTX(IDE_DATA_BUFFER[((uint16_t)(i+offs))*2+1]); + } while(((uint8_t)(++i)) != len && i<16); + __asm__ __volatile__("" ::: "memory"); + IDE_IOCONTROL = 0x00; + DEBUG_PUTS("]\n"); +#endif + if (service_dma) { + service_packet_data_dma(len, offs); + } else if(service_sectors_left) { + service_packet_data_cont(len, offs); + } else { + service_packet_data_last(len, offs); + } + if (service_sectors_left && imgfile_need_to_read) { + if (imgfile_read_next_sector(&IDE_DATA_BUFFER[512])) + preload_status = PRELOAD_AVAILABLE; + else + preload_status = PRELOAD_FAILED; + } else + preload_status = PRELOAD_NONE; +} + +static void service_cd_read() +{ +#ifdef IDEDEBUG + if (service_dma) { + DEBUG_PUTS("[DMA READ "); + } else { + DEBUG_PUTS("[PIO READ "); + } + DEBUG_PUTX(packet.cd_read.start_addr[0]); + DEBUG_PUTX(packet.cd_read.start_addr[1]); + DEBUG_PUTX(packet.cd_read.start_addr[2]); + DEBUG_PUTC(' '); + DEBUG_PUTX(packet.cd_read.transfer_length[1]); + DEBUG_PUTX(packet.cd_read.transfer_length[2]); + DEBUG_PUTC(']'); +#endif + preload_status = PRELOAD_NONE; + service_sectors_left = ((packet.cd_read.transfer_length[1]<<8)|packet.cd_read.transfer_length[2]); + uint32_t blk = get_fad(packet.cd_read.start_addr, packet.cd_read.flags&1); + if (!imgfile_seek(blk, packet.cd_read.flags)) { +#ifdef IDEDEBUG + DEBUG_PUTS("[SEEK ERROR]\n"); +#endif + service_finish_packet(0x04); /* Abort */ + return; + } + service_cd_read_cont(); +} + +static void service_cd_playseek() +{ + bool msf; + switch (packet.cd_play.ptype) { + case 1: msf=false; break; + case 2: msf=true; break; + default: + service_finish_packet(0x04); /* Abort */ + return; + } + uint32_t blk = get_fad(packet.cd_play.start_point, msf); + uint32_t eblk = get_fad(packet.cd_play.end_point, msf); + + if (!imgfile_seek_cdda(blk)) { +#ifdef IDEDEBUG + DEBUG_PUTS("[SEEK ERROR]\n"); +#endif + service_finish_packet(0x04); /* Abort */ + return; + } + if (packet.cmd == 0x20) { + cdda_start(blk, eblk, packet.cd_play.reptime&0x0f); + } else { + cdda_stop(); + } + set_secnr(); + service_finish_packet(0); +} + +static void service_cd_scd() +{ + memset(IDE_DATA_BUFFER, 0, 4); + if (packet.get_scd.format == 1 && + packet.get_scd.alloc_len_hi == 0 && + packet.get_scd.alloc_len_lo == 14) { + IDE_DATA_BUFFER[1] = cdda_get_status(); + IDE_DATA_BUFFER[3] = 14; + memcpy(&IDE_DATA_BUFFER[4], cdda_subcode_q, 10); + service_packet_data_last0(14/2); + } else if (packet.get_scd.format == 0 && + packet.get_scd.alloc_len_hi == 0 && + packet.get_scd.alloc_len_lo == 100) { + IDE_DATA_BUFFER[1] = cdda_get_status(); + IDE_DATA_BUFFER[3] = 100; + uint8_t i, j, *p = &IDE_DATA_BUFFER[4]; + uint16_t crc = 0; + for (i=0; i<12; i++) { + uint8_t sc = cdda_subcode_q[i]; + for (j=0; j<8; j++) { + if (sc&0x80) { + crc ^= 0x8000; + *p++ = 0x7f; + } else { + *p++ = 0x3f; + } + if (crc & 0x8000) + crc = (crc << 1) ^ 0x1021; + else + crc <<= 1; + sc <<= 1; + } + if (i == 9) { + cdda_subcode_q[10] = (~crc)>>8; + cdda_subcode_q[11] = ~crc; + } + } + service_packet_data_last0(100/2); + } else + service_finish_packet(0x04); /* Abort */ +} + +static void service_reset() +{ + preload_status = PRELOAD_NONE; + cdda_stop(); +} + +static void service_cmd() +{ +#ifdef IDEDEBUG + DEBUG_PUTS("[SVC "); + DEBUG_PUTX(packet.cmd); + DEBUG_PUTS("]\n"); +#endif + switch(packet.cmd) { + case 0x14: /* GET_TOC */ + service_get_toc(); + break; + case 0x15: /* REQ_SES */ + service_req_ses(); + break; + case 0x20: /* CD_PLAY */ + case 0x21: /* CD_SEEK */ + service_cd_playseek(); + break; + case 0x30: /* CD_READ */ + service_cd_read(); + break; + case 0x40: /* CD_SCD */ + service_cd_scd(); + break; + default: + service_finish_packet(0x04); /* Abort */ + break; + } +} + +static void service_data() +{ +#ifdef IDEDEBUG + DEBUG_PUTS("[SVC "); + DEBUG_PUTX(packet.cmd); + DEBUG_PUTS("]\n"); +#endif + switch(packet.cmd) { + case 0x30: /* CD_READ */ + service_cd_read_cont(); + break; + default: + service_finish_packet(0x04); /* Abort */ + break; + } +} + +void service_ide() +{ + uint8_t mode; + cli(); + mode = service_mode; + service_mode = SERVICE_MODE_IDLE; + if (mode == SERVICE_MODE_RESET) + IDE_ALT_STATUS = 0x00; /* Clear BSY */ + sei(); + switch (mode) { + case SERVICE_MODE_IDLE: + return; + case SERVICE_MODE_RESET: + service_reset(); + break; + case SERVICE_MODE_CMD: + service_cmd(); + break; + case SERVICE_MODE_DATA: + service_data(); + break; + } +} + +void set_disk_type(uint8_t type) +{ + disk_type = type; + set_secnr(); +} diff --git a/zeldin_iceGDROM/rv32/source/ide.h b/zeldin_iceGDROM/rv32/source/ide.h new file mode 100644 index 0000000000000000000000000000000000000000..4a67c18f88d9195ff00dca0d3ade4a5519bff65f --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/ide.h @@ -0,0 +1,4 @@ +extern void service_ide(); +extern void set_disk_type(uint8_t type); +extern void set_secnr(); + diff --git a/zeldin_iceGDROM/rv32/source/imgfile.c b/zeldin_iceGDROM/rv32/source/imgfile.c new file mode 100644 index 0000000000000000000000000000000000000000..0d145eb50db467b802ad4fedbc43df730985c15e --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/imgfile.c @@ -0,0 +1,198 @@ +#include +#include + +#include "config.h" + +#include "imgfile.h" +#include "fatfs.h" +#include "hardware.h" +#include "debug.h" +#include "cdda.h" + +struct imgheader imgheader; +struct toc toc[2]; + +static struct fatfs_handle read_handle; +static struct fatfs_handle cdda_handle; + +uint8_t imgfile_data_offs; +uint8_t imgfile_data_len; +static uint8_t imgfile_skip_before, imgfile_skip_after; +static uint16_t imgfile_sector_size, imgfile_sector_completed; +bool imgfile_need_to_read; + +bool imgfile_init() +{ + read_handle.pos = cdda_handle.pos = ~0; + + if (!fatfs_read_header(&imgheader, sizeof(imgheader), 0) || + imgheader.magic != HEADER_MAGIC || + imgheader.num_tocs < 1 || imgheader.num_tocs > 2) + return false; + + uint8_t i; + struct toc *t = &toc[0]; + for (i=0; i (uint8_t)~imgfile_data_offs) { + if (imgfile_need_to_read) + fatfs_read_next_sector(&read_handle, 0); + imgfile_need_to_read = true; + } + imgfile_data_offs += imgfile_skip_before; +} + +bool imgfile_read_next_sector(uint8_t *ptr) +{ + if (imgfile_need_to_read) { + if (!fatfs_read_next_sector(&read_handle, ptr)) + return false; + imgfile_need_to_read = false; + } + if (((uint8_t)~imgfile_data_offs) < (imgfile_sector_size - imgfile_sector_completed)) { + imgfile_data_len = ((uint8_t)~imgfile_data_offs)+1; + } else { + imgfile_data_len = imgfile_sector_size - imgfile_sector_completed; + } + return true; +} + +bool imgfile_sector_complete() +{ + imgfile_sector_completed += (imgfile_data_len? imgfile_data_len : 512/2); + imgfile_data_offs += imgfile_data_len; + if (!imgfile_data_offs) + imgfile_need_to_read = true; + if (imgfile_sector_completed >= imgfile_sector_size) { + imgfile_sector_completed = 0; + if (imgfile_skip_after > (uint8_t)~imgfile_data_offs) { + if (imgfile_need_to_read) + fatfs_read_next_sector(&read_handle, 0); + imgfile_need_to_read = true; + } + imgfile_data_offs += imgfile_skip_after; + imgfile_adjust_sector_start(); + return true; + } + return false; +} + +bool imgfile_read_next_sector_cdda(uint8_t idx) +{ + return fatfs_read_next_sector(&cdda_handle, &CDDA_DATA_BUFFER[(idx? 512:0)]); +} + +static bool imgfile_seek_internal(uint32_t sec, uint8_t mode, bool data) +{ + uint8_t i; + uint32_t blk; + uint8_t rmode = 0xff; + uint8_t secoffs = 0; + for(i=0; i= start) { + rmode = imgheader.regions[i].start_and_type >> 24; + uint32_t wordoffs = (sec-start)*(2352/2); + secoffs = (uint8_t)wordoffs; + blk = (wordoffs>>8)+imgheader.regions[i].fileoffs; + } else { + if (!i) + return false; + break; + } + } + uint8_t skip_before = 0, skip_after = 0; + switch((mode>>1)&7) { + case 0: + if(!(mode & 0x10)) { + /* Data select with "Any type"; check for data track and assume + mode2/form1 for XA and mode1 otherwise */ + if (!(rmode & 4)) + return false; + if (imgheader.disk_type == 0x20) { + skip_after = 280/2; + if (!(mode & 0x40)) + skip_before = 8/2; + } else + skip_after = 288/2; + } + break; + case 1: + if (rmode & 4) + return false; + break; + case 2: + skip_after = 288/2; + case 3: + /* FALLTHRU */ + if (!(rmode & 4) || imgheader.disk_type == 0x20) + return false; + break; + case 4: + skip_after = 276/2; + /* FALLTHRU */ + case 5: + skip_after += 4/2; + if (!(rmode & 4) || imgheader.disk_type != 0x20) + return false; + if (!(mode & 0x40)) + skip_before = 8/2; + break; + case 6: + break; + default: + return false; + } + if (mode & 0x10) { + skip_before = 0; + skip_after = 0; + } else if (!(mode & 0x20)) { + return false; + } else if (!(mode & 0x80)) { + skip_before += 16/2; + } + if (data) { + imgfile_sector_size = 2352/2; + imgfile_sector_size -= skip_before; + imgfile_sector_size -= skip_after; + imgfile_data_offs = secoffs; + imgfile_skip_before = skip_before; + imgfile_skip_after = skip_after; + imgfile_need_to_read = false; + imgfile_sector_completed = 0; + imgfile_adjust_sector_start(); + if (imgfile_need_to_read) + blk++; + else + imgfile_need_to_read = true; + } else { + cdda_subcode_q[0] = (rmode<<4)|1; + cdda_toc = rmode & 0x80; + } + return fatfs_seek((data? &read_handle : &cdda_handle), blk); +} + +bool imgfile_seek(uint32_t sec, uint8_t mode) +{ + if (!imgfile_seek_internal(sec, mode, true)) { + DEBUG_PUTS("SEEK mode="); + DEBUG_PUTX(mode); + DEBUG_PUTS(" failed\n"); + return false; + } + return true; +} + +bool imgfile_seek_cdda(uint32_t sec) +{ + return imgfile_seek_internal(sec, 0x12, false); +} + diff --git a/zeldin_iceGDROM/rv32/source/imgfile.h b/zeldin_iceGDROM/rv32/source/imgfile.h new file mode 100644 index 0000000000000000000000000000000000000000..c6577ba9e3d1be7ce4c9107c38c5d1c080bf93d6 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/imgfile.h @@ -0,0 +1,57 @@ + +#define MAX_SESSIONS 6 +#define MAX_REGIONS 8 + +#define HEADER_MAGIC 0xdc0001dc + +struct region +{ + uint32_t start_and_type; + uint32_t fileoffs; +}; + +struct imgheader +{ + uint32_t magic; + uint8_t disk_type; + uint8_t num_tocs; + uint8_t num_sessions; + uint8_t num_regions; + uint8_t sessions[MAX_SESSIONS][4]; + struct region regions[MAX_REGIONS]; +}; + +struct tocentry +{ + uint8_t ctrl_adr; + uint8_t fad[3]; +}; + +struct tocindex +{ + uint8_t ctrl_adr; + uint8_t track_nr; + uint8_t pad[2]; +}; + +struct toc +{ + struct tocentry entry[99]; + struct tocindex first_track; + struct tocindex last_track; + struct tocentry lead_out; +}; + +extern struct imgheader imgheader; +extern struct toc toc[2]; + +extern uint8_t imgfile_data_offs; +extern uint8_t imgfile_data_len; +extern bool imgfile_need_to_read; + +extern bool imgfile_init(); +extern bool imgfile_read_next_sector(uint8_t *ptr); +extern bool imgfile_read_next_sector_cdda(uint8_t index); +extern bool imgfile_seek(uint32_t sec, uint8_t mode); +extern bool imgfile_seek_cdda(uint32_t sec); +extern bool imgfile_sector_complete(); diff --git a/zeldin_iceGDROM/rv32/source/main.c b/zeldin_iceGDROM/rv32/source/main.c new file mode 100644 index 0000000000000000000000000000000000000000..dd97c1f79afddb633e0d87422fb9ef5ae7b24a3e --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/main.c @@ -0,0 +1,83 @@ +#include +#include + +#include "config.h" + +#include "hardware.h" +#include "debug.h" +#include "delay.h" +#include "sdcard.h" +#include "ide.h" +#include "cdda.h" +#include "fatfs.h" +#include "imgfile.h" +#include "timer.h" + +#if SD_CD_PIN_ACTIVE_HIGH +#define SDCARD_INSERTED (bit_is_set(SD_CD_PIN, SD_CD_BIT)) +#else +#define SDCARD_INSERTED (bit_is_clear(SD_CD_PIN, SD_CD_BIT)) +#endif + +static bool find_imgfile() +{ + if (fatfs_read_rootdir()) + return true; + fatfs_reset_filename(); + return fatfs_read_rootdir(); +} + +void handle_sdcard() +{ + + DEBUG_PUTS("[Card inserted]\n"); + + if (sd_init() && + fatfs_mount() && + find_imgfile() && + imgfile_init()) { + set_disk_type(imgheader.disk_type); + PORTA = fatfs_filenumber; + fatfs_next_filename(); + } else { + fatfs_reset_filename(); + PORTA = ~0; + } + + while (SDCARD_INSERTED) { + service_ide(); + service_cdda(); + } + + DEBUG_PUTS("[Card extracted]\n"); + cdda_stop(); + set_disk_type(0xff); +} + +int main() +{ + DDRA = 0xff; + DDRB = 0x00; + PORTB = 0x00; + DDRB |= _BV(EMPH_BIT); + DEBUG_INIT(); + timer_init(); + sei(); + + uint8_t leds = 1; + + for (;;) { + PORTA = leds; + delayms(250); + delayms(250); + if (!(leds <<= 1)) + leds++; + + service_ide(); + + if (SDCARD_INSERTED) + handle_sdcard(); + } + + return 0; +} diff --git a/zeldin_iceGDROM/rv32/source/sdcard.c b/zeldin_iceGDROM/rv32/source/sdcard.c new file mode 100644 index 0000000000000000000000000000000000000000..798fc5f41a482693550276963573893cbf60767c --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/sdcard.c @@ -0,0 +1,249 @@ +#include +#include + +#include "config.h" + +#include "hardware.h" +#include "debug.h" +#include "delay.h" +#include "timer.h" +#include "sdcard.h" + +#define SPI_CS PB6 +#define SPI_MISO PB3 +#define SPI_MOSI PB2 +#define SPI_SCK PB1 + +#define INIT_TIMEOUT_CS 200 +#define READ_TIMEOUT_CS 30 + +static bool is_hc; + +static __inline void sd_spi_enable_init() +{ + PORTB |= _BV(SPI_CS); + DDRB |= _BV(SPI_CS)|_BV(SPI_MOSI)|_BV(SPI_SCK); + SDCARD_CONTROL = 7; + SDCARD_DIVIDER = 158; /* 39.5MHz/159 = 249kHz */ + PORTB |= _BV(SPI_MOSI); +} + +static __inline void sd_spi_enable() +{ + SDCARD_CONTROL = 7; + SDCARD_DIVIDER = 2; /* 39.5MHz/3 = 13.2MHz */ + PORTB |= _BV(SPI_MOSI); +} + +static __inline void sd_spi_disable() +{ + PORTB &= ~_BV(SPI_MOSI); + SDCARD_CONTROL = 0; +} + +static void spi_send_byte(uint8_t b) +{ + SDCARD_DATA = b; + loop_until_bit_is_set(SDCARD_CONTROL, 7); +} + +static uint8_t spi_recv_byte() +{ + spi_send_byte(0xff); + return SDCARD_DATA; +} + +static uint8_t sd_send_cmd_param(uint8_t cmd, uint32_t param) +{ + uint8_t r1, cnt; + + PORTB &= ~_BV(SPI_CS); + spi_recv_byte(); + SDCARD_CRC7 = 0; + spi_send_byte(0x40|cmd); + spi_send_byte(param>>24); + spi_send_byte(param>>16); + spi_send_byte(param>>8); + spi_send_byte(param); + spi_send_byte(SDCARD_CRC7); + + if (cmd == 12) + spi_send_byte(0xff); + + SDCARD_CONTROL = 31; + r1 = spi_recv_byte(); + SDCARD_CONTROL = 7; + + return r1; +} + +static uint8_t sd_send_cmd(uint8_t cmd) +{ + return sd_send_cmd_param(cmd, 0); +} + +bool sd_init() +{ + uint8_t i, r1; + bool is_sd2 = false; + uint8_t start = centis; + + is_hc = false; + + sd_spi_enable_init(); + for (i=0; i<10; i++) + spi_send_byte(0xff); + + do { + r1 = sd_send_cmd(0); + if (r1 == 1) + break; + } while (((uint8_t)(centis - start)) < INIT_TIMEOUT_CS); + DEBUG_PUTS("CMD0 sent, R1=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTC('\n'); + if (r1 != 1) + goto fail; + + r1 = sd_send_cmd_param(8, 0x1aa); + DEBUG_PUTS("CMD8 sent, R1=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTC('\n'); + + if (!(r1 & 0x04)) { + for (i=0; i<4; i++) { + r1 = spi_recv_byte(); + } + DEBUG_PUTS(" Pat=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTC('\n'); + if (r1 != 0xaa) + goto fail; + + is_sd2 = true; + DEBUG_PUTS("Card is SD2\n"); + } else + DEBUG_PUTS("Card is SD1\n"); + + uint16_t j; + do { + sd_send_cmd(55); + r1 = sd_send_cmd_param(41, (is_sd2? 0x40000000 : 0)); + if (r1 == 0) + break; + } while (((uint8_t)(centis - start)) < INIT_TIMEOUT_CS); + DEBUG_PUTS("ACMD41 sent, R1=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTC('\n'); + if (r1 != 0) + goto fail; + + if (is_sd2) { + r1 = sd_send_cmd(58); + DEBUG_PUTS("CMD58 sent, R1=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTC('\n'); + if (r1 != 0) + goto fail; + r1 = spi_recv_byte(); + DEBUG_PUTS(" OCR=0x"); + DEBUG_PUTX(r1); + DEBUG_PUTS("...\n"); + if ((r1 & 0xc0) == 0xc0) + is_hc = true; + for (i=0; i<3; i++) + spi_recv_byte(); + if (is_hc) + DEBUG_PUTS("Card is SDHC\n"); + } + + PORTB |= _BV(SPI_CS); + sd_spi_disable(); + + return true; + + fail: + PORTB |= _BV(SPI_CS); + sd_spi_disable(); + DEBUG_PUTS("Init failed\n"); + return false; +} + +static void __inline sd_xfer_block_sw(uint8_t *ptr) +{ + uint16_t cnt = 512; + do { + *ptr++ = spi_recv_byte(); + } while(--cnt); +} + +static void sd_xfer_block_hw() +{ + SDCARD_CONTROL = 0x40|7; + loop_until_bit_is_clear(SDCARD_CONTROL, 6); +} + +#define ADDR_HIGH(a) ((uint8_t)(((uint32_t)(void *)(a))>>8)) + +static void __inline sd_xfer_block(uint8_t *ptr) +{ + if (((uint8_t)(ADDR_HIGH(ptr)&0xfc)) == ADDR_HIGH(IDE_DATA_BUFFER)) { + IDE_IOCONTROL = ADDR_HIGH(ptr)&0x46; + sd_xfer_block_hw(); + IDE_IOCONTROL = 0x40; + } else if (((uint8_t)(ADDR_HIGH(ptr)&0xfc)) == ADDR_HIGH(CDDA_DATA_BUFFER)) { + CDDA_CONTROL = (CDDA_CONTROL & ~0xe)|4|(uint8_t)((ADDR_HIGH(ptr)&2)<<2); + sd_xfer_block_hw(); + CDDA_CONTROL &= ~0xe; + } else { + sd_xfer_block_sw(ptr); + } +} + +static bool sd_try_read_block(uint32_t blk, uint8_t *ptr) +{ + PORTA |= 0x80; + if (!is_hc) + blk <<= 9; + sd_spi_enable(); + if (sd_send_cmd_param(17, blk)) { + goto fail; + } + uint8_t r, start = centis; + do { + if ((r = spi_recv_byte()) != 0xff) + break; + } while (((uint8_t)(centis - start)) < READ_TIMEOUT_CS); + if (r != 0xfe) { + goto fail; + } + SDCARD_CRC16 = 0; + sd_xfer_block(ptr); + uint32_t crc1 = SDCARD_CRC16; + uint8_t crc2_hi = spi_recv_byte(); + uint8_t crc2_lo = spi_recv_byte(); + uint32_t crc2 = (crc2_hi << 8) | crc2_lo; + if (crc2 != crc1) + goto fail; + PORTB |= _BV(SPI_CS); + sd_spi_disable(); + PORTA &= ~0x80; + return true; + + fail: + PORTB |= _BV(SPI_CS); + sd_spi_disable(); + PORTA &= ~0x80; + DEBUG_PUTS("Block read failed\n"); + return false; +} + +bool sd_read_block(uint32_t blk, uint8_t *ptr) +{ + uint8_t tries = 0; + do { + if (sd_try_read_block(blk, ptr)) + return true; + } while(++tries < 5); + return false; +} diff --git a/zeldin_iceGDROM/rv32/source/sdcard.h b/zeldin_iceGDROM/rv32/source/sdcard.h new file mode 100644 index 0000000000000000000000000000000000000000..a1d4e0f02ae86e5f398b12c0c170b0e291bf0ba9 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/sdcard.h @@ -0,0 +1,2 @@ +extern bool sd_init(); +extern bool sd_read_block(uint32_t blk, uint8_t *ptr); diff --git a/zeldin_iceGDROM/rv32/source/timer.c b/zeldin_iceGDROM/rv32/source/timer.c new file mode 100644 index 0000000000000000000000000000000000000000..badf89f362f7aea9f8939257adddd34c546c31de --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/timer.c @@ -0,0 +1,14 @@ +#include + +#include "timer.h" +#include "config.h" +#include "hardware.h" + +uint8_t centis; + +void timer_init() +{ + OCR0 = (CPU_FREQ / 100) - 1; + TCNT0 = 0; + TIMSK |= _BV(OCIE0); +} diff --git a/zeldin_iceGDROM/rv32/source/timer.h b/zeldin_iceGDROM/rv32/source/timer.h new file mode 100644 index 0000000000000000000000000000000000000000..b2c7a7a4f606fe911cec7f18416fd51fee23fff3 --- /dev/null +++ b/zeldin_iceGDROM/rv32/source/timer.h @@ -0,0 +1,3 @@ +extern void timer_init(); +extern uint8_t centis; + diff --git a/zeldin_iceGDROM/test/source/aica.c b/zeldin_iceGDROM/test/source/aica.c new file mode 100644 index 0000000000000000000000000000000000000000..bceef4ed4f99aa90347ec69a2c6437bb87214564 --- /dev/null +++ b/zeldin_iceGDROM/test/source/aica.c @@ -0,0 +1,144 @@ +#include "soundcommon.h" +#include "aica.h" + +extern void usleep(unsigned int usec); + +#define SOUNDSTATUS ((volatile struct soundstatus *)(void *)(0xa0800000+SOUNDSTATUS_ADDR)) + +static const unsigned int arm_sound_code[] = { +#include "arm_sound_code.h" +}; + +static int last_soundpos; +static int samples_left; +static const short *sample_ptr; + +static void *memcpy4(void *s1, const void *s2, unsigned int n) +{ + unsigned int *p1 = s1; + const unsigned int *p2 = s2; + n+=3; + n>>=2; + while(n--) + *p1++ = *p2++; + return s1; +} + +static void *memset4(void *s, int c, unsigned int n) +{ + unsigned int *p = s; + n+=3; + n>>=2; + while(n--) + *p++ = c; + return s; +} + +static int read_sound_int(volatile int *p) +{ + int r; + while((*((volatile int *)(void *)0xa05f688c))&32); + r = *p; + return r; +} + +static void write_sound_int(volatile int *p, int v) +{ + while((*((volatile int *)(void *)0xa05f688c))&32); + *p = v; +} + +static void wait_sound_command(int n) +{ + while(read_sound_int(&SOUNDSTATUS->cmdstatus)!=n) + ; +} + +static void do_sound_command(int cmd) +{ + wait_sound_command(0); + write_sound_int(&SOUNDSTATUS->cmd, cmd); + write_sound_int(&SOUNDSTATUS->cmdstatus, 1); + wait_sound_command(2); + write_sound_int(&SOUNDSTATUS->cmdstatus, 0); + wait_sound_command(0); +} + +void aica_pause() +{ + do_sound_command(MODE_PAUSE); +} + +static int aica_get_sample_position() +{ + return read_sound_int(&SOUNDSTATUS->samplepos); +} + +static void fill_samples(const short *samples, int cnt) +{ + int i; + unsigned int *left = (void *)(0xa0800000 + SAMPLE_BASE_LEFT + 2*last_soundpos); + unsigned int *right = (void *)(0xa0800000 + SAMPLE_BASE_RIGHT + 2*last_soundpos); + samples_left -= cnt; + last_soundpos += cnt; + if (last_soundpos >= SAMPLE_DATA_LENGTH) + last_soundpos -= SAMPLE_DATA_LENGTH; + cnt >>= 1; + if (samples) + for (i=0; i= 256) { + delta &= ~255; + if (samples_left > 0) { + int n = (samples_left >= delta ? delta : samples_left); + fill_samples(sample_ptr, n); + sample_ptr += 2*n; + delta -= n; + } + if (delta > 0) + fill_samples(0, delta); + } + if (samples_left <= -SAMPLE_DATA_LENGTH) + return -1; + else if (samples_left > 0) + return samples_left; + else + return 0; +} + +void aica_play_stereo_sample(const short *stereo_buffer, int sample_cnt) +{ + do_sound_command(MODE_PAUSE); + last_soundpos = 0; + fill_samples(0, SAMPLE_DATA_LENGTH); + sample_ptr = stereo_buffer; + samples_left = sample_cnt; + do_sound_command(MODE_PLAY); +} + +void aica_init() +{ + *((volatile unsigned long *)(void *)0xa0702c00) |= 1; + memset4((void*)0xa0800000, 0, 2*1024*1024); + memcpy4((void*)0xa0800000, arm_sound_code, sizeof(arm_sound_code)); + *((volatile unsigned long *)(void *)0xa0702c00) &= ~1; + usleep(10000); +} diff --git a/zeldin_iceGDROM/test/source/aica.h b/zeldin_iceGDROM/test/source/aica.h new file mode 100644 index 0000000000000000000000000000000000000000..94961af1559d131b6e2f2e3fa485725670e9a263 --- /dev/null +++ b/zeldin_iceGDROM/test/source/aica.h @@ -0,0 +1,4 @@ +extern void aica_init(void); +extern void aica_pause(void); +extern void aica_play_stereo_sample(const short *stereo_buffer, int sample_cnt); +extern int aica_check_sample_playback(); diff --git a/zeldin_iceGDROM/test/source/arm_sound_code.c b/zeldin_iceGDROM/test/source/arm_sound_code.c new file mode 100644 index 0000000000000000000000000000000000000000..d8c413446a274991e173526eb72bd37cc8eca807 --- /dev/null +++ b/zeldin_iceGDROM/test/source/arm_sound_code.c @@ -0,0 +1,86 @@ +#include "soundcommon.h" + +#define AICA(n) ((volatile unsigned int *)(void*)(0x800000+(n))) +#define SOUNDSTATUS ((volatile struct soundstatus *)(void *)(SOUNDSTATUS_ADDR)) + +static void __gccmain() { } + +void aica_reset() +{ + int i, j; + volatile unsigned int *hwptr = AICA(0); + + *AICA(0x2800) = 0; + + /* Reset all 64 channels to a silent state */ + for(i=0; i<64; i++) { + hwptr[0] = 0x8000; + hwptr[5] = 0x1f; + hwptr[1] = 0; + hwptr[2] = 0; + hwptr[3] = 0; + hwptr[4] = 0; + for(j=6; j<32; j++) + hwptr[j] = 0; + hwptr += 32; + } + + /* Enable CDDA full volume, normal panning */ + *AICA(0x2040) = 0x0f0f; + *AICA(0x2044) = 0x0f1f; + + *AICA(0x2800) = 15; +} + +void init_channel(int channel, int pan, unsigned long dataptr, int len) +{ + volatile unsigned int *hwptr = AICA(channel<<7); + + /* Set sample format and buffer address */ + hwptr[0] = 0x4200 | (dataptr>>16); + hwptr[1] = dataptr & 0xffff; + /* Number of samples */ + hwptr[3] = len; + /* Frequency */ + hwptr[6] = 0; /* 44100 Hz */ + /* Set volume, pan, and some other stuff */ + ((volatile unsigned char *)(hwptr+9))[4] = 0x24; + ((volatile unsigned char *)(hwptr+9))[1] = 0xf; + ((volatile unsigned char *)(hwptr+9))[5] = 0; + ((volatile unsigned char *)(hwptr+9))[0] = pan; + hwptr[4] = 0x1f; +} + +int main() +{ + SOUNDSTATUS->mode = MODE_PAUSE; + SOUNDSTATUS->samplepos = 0; + + aica_reset(); + + for(;;) { + + if(SOUNDSTATUS->cmdstatus==1) { + if (SOUNDSTATUS->cmd == MODE_PLAY) { + /* Play */ + init_channel(0, 0x1f, SAMPLE_BASE_LEFT, SAMPLE_DATA_LENGTH); + init_channel(1, 0x0f, SAMPLE_BASE_RIGHT, SAMPLE_DATA_LENGTH); + SOUNDSTATUS->samplepos = 0; + *AICA(0) |= 0xc000; + *AICA(0x80) |= 0xc000; + *(unsigned char *)AICA(0x280d) = 0; + SOUNDSTATUS->mode = MODE_PLAY; + } else { + /* Pause */ + *AICA(0) = (*AICA(0) & ~0x4000) | 0x8000; + *AICA(0x80) = (*AICA(0x80) & ~0x4000) | 0x8000; + SOUNDSTATUS->samplepos = 0; + SOUNDSTATUS->mode = MODE_PAUSE; + } + SOUNDSTATUS->cmdstatus = 2; + } + + if(SOUNDSTATUS->mode == MODE_PLAY) + SOUNDSTATUS->samplepos = *AICA(0x2814); + } +} diff --git a/zeldin_iceGDROM/test/source/benchmark.c b/zeldin_iceGDROM/test/source/benchmark.c new file mode 100644 index 0000000000000000000000000000000000000000..86d168c59e5778ad5ff935dddfc1eeeeddba447d --- /dev/null +++ b/zeldin_iceGDROM/test/source/benchmark.c @@ -0,0 +1,63 @@ +#include + +#include "cdops.h" + +extern unsigned long Timer( ); + +static struct TOC toc; +static unsigned int track_start; + +static char bigbuf[2048*1024]; + +static int select_track() +{ + unsigned char disc_status; + if (cdops_init_drive() < 0) { + printf("Failed to init drive%s!\n", ((cdops_disc_status()&0xf)==6? " (no disc in drive)":"")); + return 0; + } + disc_status = cdops_disc_status(); + if (cdops_read_toc(&toc, ((disc_status&0x80)? 1 : 0)) < 0) { + printf("Failed to read TOC!\n"); + return 0; + } + unsigned i, first = TOC_TRACK(toc.first), last = TOC_TRACK(toc.last); + if (first < 1) first = 1; + for (i=last; i>=first; --i) { + if (TOC_CTRL(toc.entry[i-1])&4) { + track_start = TOC_LBA(toc.entry[i-1]); + printf("Using track %d (in %s density region), LBA %d\n", + (int)i, ((disc_status&0x80)? "high" : "low"), (int)track_start); + return 1; + } + } + printf("No suitable track found\n"); + return 0; +} + +static void test_read_performance(int dma, int size, int cnt) +{ + while(cnt--) { + printf("Testing %dK %s read...", size, (dma? "DMA":"PIO")); + unsigned long t0 = Timer(); + int r = (dma? cdops_read_sectors_dma(bigbuf, track_start, size>>1) : + cdops_read_sectors_pio(bigbuf, track_start, size>>1)); + unsigned long t1 = Timer(); + if (r < 0) { + printf(" Read failed!\n"); + continue; + } + printf(" %d \xb5s\n", ((t1-t0)<<11)/100); + } +} + +void run_test() +{ + if (!select_track()) + return; + + test_read_performance(0, 16, 3); + test_read_performance(0, 2048, 3); + test_read_performance(1, 16, 3); + test_read_performance(1, 2048, 3); +} diff --git a/zeldin_iceGDROM/test/source/benchmark.txt b/zeldin_iceGDROM/test/source/benchmark.txt new file mode 100644 index 0000000000000000000000000000000000000000..1608d57fe82125f9bb6a6d13ddd6022f0e664589 --- /dev/null +++ b/zeldin_iceGDROM/test/source/benchmark.txt @@ -0,0 +1,11 @@ +Hardware ID : SEGA SEGAKATANA +Maker ID : SEGA ENTERPRISES +Device Info : 0000 GD-ROM1/1 +Area Symbols : JUE +Peripherals : E000F10 +Product No : T0000 +Version : 1.0 +Release Date : 20160901 +Boot Filename : BENCHMARK.BIN +SW Maker Name : Marcus Comstedt +Game Title : iceGDROM benchmark diff --git a/zeldin_iceGDROM/test/source/cddatest.c b/zeldin_iceGDROM/test/source/cddatest.c new file mode 100644 index 0000000000000000000000000000000000000000..dff20e0d26293264182acb8d6dc16385922d8988 --- /dev/null +++ b/zeldin_iceGDROM/test/source/cddatest.c @@ -0,0 +1,113 @@ +#include +#include + +#include "cdops.h" +#include "aica.h" + +extern void clrscr(int color); +extern void usleep(unsigned int usec); +extern void printat(int x, int y, const char *fmt, ...); + +static struct TOC toc; +static unsigned int track_start; + +static short stereo_buffer[750*588*2]; + +static int select_track() +{ + unsigned char disc_status; + if (cdops_init_drive() < 0) { + printf("Failed to init drive%s!\n", ((cdops_disc_status()&0xf)==6? " (no disc in drive)":"")); + return 0; + } + disc_status = cdops_disc_status(); + if (cdops_read_toc(&toc, ((disc_status&0x80)? 1 : 0)) < 0) { + printf("Failed to read TOC!\n"); + return 0; + } + unsigned i, first = TOC_TRACK(toc.first), last = TOC_TRACK(toc.last); + if (first < 1) first = 1; + for (i=last; i>=first; --i) { + if (!(TOC_CTRL(toc.entry[i-1])&4)) { + track_start = TOC_LBA(toc.entry[i-1]); + printf("Using track %d (in %s density region), LBA %d\n", + (int)i, ((disc_status&0x80)? "high" : "low"), (int)track_start); + return 1; + } + } + printf("No suitable track found\n"); + return 0; +} + +static void play_sectors_test() +{ + int i; + printf("Playing 10 seconds using CD_PLAY..."); + if (cdops_play_cdda_sectors(track_start, track_start+750, 0) < 0) { + printf("Failed!\n"); + return; + } + for(i=0; i<10; i++) { + if ((cdops_disc_status()&0xf)!=3) + break; + printf("%d", i); + usleep(1000000); + } + while ((cdops_disc_status()&0xf)==3) + ; + cdops_stop_cdda(); + printf("Done\n"); +} + +static void read_sectors_test() +{ + int i; + printf("Playing 10 seconds using CD_READ..."); + if (cdops_set_audio_read_mode() < 0 || + cdops_read_sectors_pio((void *)stereo_buffer, track_start, 750) < 0) { + printf("Failed!\n"); + return; + } + aica_play_stereo_sample(stereo_buffer, 441000); + int oldp = -1; + for(;;) { + if ((cdops_disc_status()&0xf)>=6) + break; + int p = aica_check_sample_playback(); + if (p < 0) + break; + p = (441000 - p)/44100 - 1; + if (p > oldp && p < 10) + printf("%d", (oldp=p)); + usleep(100000); + } + aica_pause(); + printf("Done\n"); +} + +void run_cdda_test() +{ + if (!select_track()) + return; + play_sectors_test(); + read_sectors_test(); +} + +void run_test() +{ + for(;;) { + clrscr(0x1f); + printat(0, 0, ""); + if ((cdops_disc_status()&0xf)>=6) { + printf("Please insert an audio disc"); + while ((cdops_disc_status()&0xf)>=6) + ; + } else { + while((cdops_disc_status()&0xf)==0) + ; + run_cdda_test(); + while ((cdops_disc_status()&0xf)<6) + ; + } + } +} diff --git a/zeldin_iceGDROM/test/source/cddatest.txt b/zeldin_iceGDROM/test/source/cddatest.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a47a18624a6fd08ef8ddd34f84b9da4470c17c4 --- /dev/null +++ b/zeldin_iceGDROM/test/source/cddatest.txt @@ -0,0 +1,11 @@ +Hardware ID : SEGA SEGAKATANA +Maker ID : SEGA ENTERPRISES +Device Info : 0000 GD-ROM1/1 +Area Symbols : JUE +Peripherals : E000F10 +Product No : T0000 +Version : 1.0 +Release Date : 20200709 +Boot Filename : CDDATEST.BIN +SW Maker Name : Marcus Comstedt +Game Title : iceGDROM CDDA test diff --git a/zeldin_iceGDROM/test/source/cdops.c b/zeldin_iceGDROM/test/source/cdops.c new file mode 100644 index 0000000000000000000000000000000000000000..95e8072456f54bd0038cf34f7f48b65eb1c4ca29 --- /dev/null +++ b/zeldin_iceGDROM/test/source/cdops.c @@ -0,0 +1,199 @@ +#include "cdops.h" + +extern void gdGdcInitSystem(); +extern void gdGdcReset(); +extern int gdGdcReqCmd(int command, unsigned int *parameterblock); +extern int gdGdcGetCmdStat(int reqid, unsigned int *status); +extern int gdGdcGetDrvStat(unsigned int *status); +extern void gdGdcExecServer(); +extern int gdGdcChangeDataType(unsigned int *format); + +extern void usleep(unsigned int usec); + + +#define GDROM(o) (*(volatile unsigned char *)(0xa05f7000 + (o))) + +#define DATA (*(volatile short *) & GDROM(0x80)) +#define FEATURES GDROM(0x84) +#define SEC_NR GDROM(0x8c) +#define CYL_LO GDROM(0x90) +#define CYL_HI GDROM(0x94) +#define COMMAND GDROM(0x9c) +#define STATUS GDROM(0x9c) +#define ALTSTATUS GDROM(0x18) + +void cdops_init() +{ + register unsigned long p, x; + *((volatile unsigned long *)0xa05f74e4) = 0x1fffff; + for(p=0; p<0x200000/4; p++) + x = ((volatile unsigned long *)0xa0000000)[p]; + gdGdcInitSystem(); + gdGdcReset(); +} + +unsigned char cdops_disc_status() +{ + return SEC_NR; +} + +static int cdops_send_cmd(int cmd, void *param) +{ + return gdGdcReqCmd(cmd, param); +} + +static int cdops_check_cmd(int f) +{ + int blah[4]; + int n; + gdGdcExecServer(); + if((n = gdGdcGetCmdStat(f, blah))==1) + return 0; + if(n == 2) + return 1; + else return -1; +} + +static int cdops_wait_cmd(int f) +{ + int n; + while(!(n = cdops_check_cmd(f))); + return (n>0? 0 : n); +} + +static int cdops_exec_cmd(int cmd, void *param) +{ + int f = cdops_send_cmd(cmd, param); + return cdops_wait_cmd(f); +} + +int cdops_init_drive() +{ + int i, r=0; + unsigned int param[4]; + int cdxa; + + for(i=0; i<8; i++) + if(!(r = cdops_exec_cmd(24, 0))) + break; + if(r) + return r; + + gdGdcGetDrvStat(param); + + cdxa = (param[1] == 32); + + param[0] = 0; /* set data type */ + param[1] = 8192; + param[2] = (cdxa? 2048 : 1024); /* mode 1/2 */ + param[3] = 2048; /* sector size */ + + return gdGdcChangeDataType(param); +} + +int cdops_set_audio_read_mode() +{ + unsigned int param[4]; + + param[0] = 0; /* set data type */ + param[1] = 4096; + param[2] = 512; + param[3] = 2352; + + return gdGdcChangeDataType(param); +} + +int cdops_read_toc(struct TOC *toc, int session) +{ + struct { int session; void *buffer; } param; + param.session = session; + param.buffer = toc; + return cdops_exec_cmd(19, ¶m); +} + +int cdops_read_sectors_pio(char *buf, int sec, int num) +{ + struct { int sec, num; void *buffer; int dunno; } param; + param.sec = sec; + param.num = num; + param.buffer = buf; + param.dunno = 0; + return cdops_exec_cmd(16, ¶m); +} + +int cdops_read_sectors_dma(char *buf, int sec, int num) +{ + struct { int sec, num; void *buffer; int dunno; } param; + param.sec = sec; + param.num = num; + param.buffer = buf; + param.dunno = 0; + return cdops_exec_cmd(17, ¶m); +} + +int cdops_play_cdda_sectors(int start, int stop, int reps) +{ + struct { int start, stop, reps, dunno; } param; + param.start = start; + param.stop = stop; + param.reps = reps; + param.dunno = 0; + return cdops_exec_cmd(21, ¶m); +} + +int cdops_stop_cdda() +{ + return cdops_exec_cmd(22, 0); +} + +int cdops_packet(const unsigned short *packet, unsigned short size, void *buf) +{ + register unsigned int sr = 0; + int i; + unsigned short tot = 0; + size &= ~1; + while(ALTSTATUS & 0x88) + ; + __asm__("stc sr,%0" : "=r" (sr)); + __asm__("ldc %0,sr" : : "r" (sr|(1<<28))); + CYL_LO = size & 0xff; + CYL_HI = size >> 8; + FEATURES = 0; + COMMAND = 0xa0; + while((ALTSTATUS & 0x88) != 8) + ; + for (i=0; i<6; i++) + DATA = packet[i]; + usleep(10); + for(;;) { + unsigned char status = STATUS; + if (status & 0x80) + continue; + if (status & 8) { + unsigned short cnt = (CYL_HI << 8) | CYL_LO; + if (cnt & 1) + cnt++; + tot += cnt; + unsigned short xfer = (cnt > size? size : cnt); + for (i=0; i 0) { + unsigned short discard = DATA; + cnt -= 2; + } + usleep(10); + continue; + } + if (status & 1) { + __asm__("ldc %0,sr" : : "r" (sr)); + return -1; + } + break; + } + __asm__("ldc %0,sr" : : "r" (sr)); + return tot; +} diff --git a/zeldin_iceGDROM/test/source/cdops.h b/zeldin_iceGDROM/test/source/cdops.h new file mode 100644 index 0000000000000000000000000000000000000000..1afa10f64827faed478138c83ebc5e2a43dfc82a --- /dev/null +++ b/zeldin_iceGDROM/test/source/cdops.h @@ -0,0 +1,21 @@ +struct TOC { + unsigned int entry[99]; + unsigned int first, last; + unsigned int leadout; +}; + +#define TOC_LBA(n) ((n)&0x00ffffff) +#define TOC_ADR(n) (((n)&0x0f000000)>>24) +#define TOC_CTRL(n) (((n)&0xf0000000)>>28) +#define TOC_TRACK(n) (((n)&0x00ff0000)>>16) + +extern void cdops_init(void); +extern unsigned char cdops_disc_status(); +extern int cdops_packet(const unsigned short *packet, unsigned short size, void *buf); +extern int cdops_init_drive(); +extern int cdops_set_audio_read_mode(); +extern int cdops_read_toc(struct TOC *toc, int session); +extern int cdops_read_sectors_pio(char *buf, int sec, int num); +extern int cdops_read_sectors_dma(char *buf, int sec, int num); +extern int cdops_play_cdda_sectors(int start, int stop, int reps); +extern int cdops_stop_cdda(); diff --git a/zeldin_iceGDROM/test/source/dmatest.c b/zeldin_iceGDROM/test/source/dmatest.c new file mode 100644 index 0000000000000000000000000000000000000000..43673c5d21a07123caa3238cfb2a08bb001c818f --- /dev/null +++ b/zeldin_iceGDROM/test/source/dmatest.c @@ -0,0 +1,109 @@ +#include +#include + +#include "cdops.h" +#include "pseudorandom.h" + +static struct TOC toc; +static unsigned int track_start; + +static char bigbuf0[14*1024*1024] __attribute__((aligned(32))); +static char smallbuf[8192]; + +#define bigbuf ((char *)((((uint32_t)bigbuf0)&0x1fffffff)|0xa0000000)) + +static int select_track() +{ + unsigned char disc_status; + if (cdops_init_drive() < 0) { + printf("Failed to init drive%s!\n", ((cdops_disc_status()&0xf)==6? " (no disc in drive)":"")); + return 0; + } + disc_status = cdops_disc_status(); + if (cdops_read_toc(&toc, ((disc_status&0x80)? 1 : 0)) < 0) { + printf("Failed to read TOC!\n"); + return 0; + } + unsigned i, first = TOC_TRACK(toc.first), last = TOC_TRACK(toc.last); + if (first < 1) first = 1; + for (i=last; i>=first; --i) { + if (TOC_CTRL(toc.entry[i-1])&4) { + track_start = TOC_LBA(toc.entry[i-1]); + printf("Using track %d (in %s density region), LBA %d\n", + (int)i, ((disc_status&0x80)? "high" : "low"), (int)track_start); + return 1; + } + } + printf("No suitable track found\n"); + return 0; +} + +static int check_bigbuf(int size) +{ + char *p = bigbuf; + int offs = 0; + while (size > 0) { + int chunk = (size > sizeof(smallbuf)? sizeof(smallbuf) : size); + pseudorandom_fill(smallbuf, chunk); + if (memcmp(smallbuf, p, chunk)) { + int pos; + for(pos = 0; pos < chunk; pos++) + if (smallbuf[pos] != p[pos]) { + return pos+offs; + } + printf("memcmp is broken?!\n"); + return offs; + } + p += chunk; + size -= chunk; + offs += chunk; + } + return -1; +} + +static void test_dma(int size, int mode) +{ + int tot = 0, sec = track_start; + printf("Testing %dM %s reads...", size, (mode? "DMA":"PIO")); + pseudorandom_init(PSEUDORANDOM_SEED); + while (tot < 32) { + int sz = (tot + size > 32? 32 - tot : size); + int r = (mode? cdops_read_sectors_dma(bigbuf, sec, sz<<9) : + cdops_read_sectors_pio(bigbuf, sec, sz<<9)); + if (r < 0) { + printf(" Read failed!\n"); + return; + } + r = check_bigbuf(sz<<20); + if (r >= 0) { + int i, locoffs = r % sizeof(smallbuf); + printf(" Bad data after %d bytes\n", (tot<<20)+r); + printf("Expected:"); + for(i=0; i<12 && locoffs+i < sizeof(smallbuf); i++) + printf(" %x", (unsigned)smallbuf[i+locoffs]); + printf("\nReceived:"); + for(i=0; i<12 && locoffs+i < sizeof(smallbuf); i++) + printf(" %x", (unsigned)bigbuf[i+r]); + printf("\n"); + return; + } + sec += sz<<9; + tot += sz; + } + printf("Ok\n"); +} + +void run_test() +{ + if (!select_track()) + return; + + test_dma(14, 1); + test_dma(8, 1); + test_dma(3, 1); + test_dma(1, 1); + test_dma(14, 0); + test_dma(8, 0); + test_dma(3, 0); + test_dma(1, 0); +} diff --git a/zeldin_iceGDROM/test/source/dmatest.txt b/zeldin_iceGDROM/test/source/dmatest.txt new file mode 100644 index 0000000000000000000000000000000000000000..a59044e7ab47ab62a415ab440309d14564bbf6a4 --- /dev/null +++ b/zeldin_iceGDROM/test/source/dmatest.txt @@ -0,0 +1,11 @@ +Hardware ID : SEGA SEGAKATANA +Maker ID : SEGA ENTERPRISES +Device Info : 0000 GD-ROM1/1 +Area Symbols : JUE +Peripherals : E000F10 +Product No : T0000 +Version : 1.0 +Release Date : 20160901 +Boot Filename : DMATEST.BIN +SW Maker Name : Marcus Comstedt +Game Title : iceGDROM DMA test diff --git a/zeldin_iceGDROM/test/source/main.c b/zeldin_iceGDROM/test/source/main.c new file mode 100644 index 0000000000000000000000000000000000000000..872c6b1b5d096a517a1ea3bd36cedaaa8480aa30 --- /dev/null +++ b/zeldin_iceGDROM/test/source/main.c @@ -0,0 +1,219 @@ +#include +#include + +#include "cdops.h" +#include "aica.h" + +extern int check_cable(void); +extern void init_video(int cabletype, int pixelmode); +extern void clrscr(int color); +extern void draw_string(int x, int y, const char *str, int color); +extern void draw_char12(int x, int y, int c, int color); +extern void draw_char24(int x, int y, int c, int color); + +extern void run_test(void); + +#define TMU_REG(n) ((volatile void *)(0xffd80000+(n))) +#define TOCR (*(volatile unsigned char *)TMU_REG(0)) +#define TSTR (*(volatile unsigned char *)TMU_REG(4)) +#define TCOR0 (*(volatile unsigned int *)TMU_REG(8)) +#define TCNT0 (*(volatile unsigned int *)TMU_REG(12)) +#define TCR0 (*(volatile unsigned short *)TMU_REG(16)) + +#define USEC_TO_TIMER(x) (((x)*100)>>11) + +static void init_tmr0() +{ + TSTR = 0; + TOCR = 0; + TCOR0 = ~0; + TCNT0 = ~0; + TCR0 = 4; + TSTR = 1; +} + +unsigned long Timer( ) +{ + return ~TCNT0; +} + +void usleep(unsigned int usec) +{ + unsigned int t0 = Timer(); + unsigned int dly = USEC_TO_TIMER(usec); + while( ((unsigned int)(Timer()-t0)) < dly ); +} + +char *itoa(int x) +{ + static char buf[30]; + int minus = 0; + int ptr=29; + buf[29]=0; + + if(!x) return "0"; + if( x < 0 ) { minus=1; x = -x; } + while(x > 0) + { + buf[--ptr] = x%10 + '0'; + x/=10; + } + if( minus ) buf[--ptr] = '-'; + return buf+ptr; +} + +void chrat(int x, int y, char c, int color) +{ + char buf[2]; + buf[0] = c; + buf[1] = '\0'; + draw_string(x*12, y*24, buf, color); +} + +void wideat(int x, int y, int c, int color) +{ + draw_char24(x*12, y*24, c, color); +} + +int strat(int x, int y, char *s, int color) +{ + draw_string(x*12, y*24, s, color); + return strlen(s); +} + +int wstrat(int x, int y, char *s, int color) +{ + int x0=x, c; + while((c=0xff&*s++)) + if(c<0x81) { + if(c<0x21 || c>0x7e) + c = 96; + else if(c==0x5c) + c = 95; + else if(c==0x7e) + c = 0; + else + c -= 32; + draw_char12(x*12, y*24, c, color); + x++; + } else if(c>=0xa1 && c<=0xdf) { + draw_char12(x*12, y*24, c+32, color); + x++; + } else { + int row, col; + if(!*s) break; + c = (c<<8) | (0xff&*s++); + if(c >= 0xa000) c -= 0x4000; + if((c & 0xff) > 0x9e) { + row = 2*(c>>8)-0x101; + col = (c & 0xff)-0x9f; + } else { + row = 2*(c>>8)-0x102; + col = (c & 0xff)-0x40; + if(col >= 0x40) --col; + } + if(row<0 || col<0 || row>83 || col>93 || (row>6 && row<15)) + row = col = 0; + else if(row>6) + row -= 8; + draw_char24(x*12, y*24, row*94+col, color); + x += 2; + } + return x-x0; +} + +static int last_x = 0, last_y = 0; + +void vprintat(int x, int y, const char *fmt, va_list va) +{ + int p; + int color = 0xffff; + while((p = *fmt++)) + if(p=='\n') { + x = 0; + y++; + } else if(p=='%') + switch(*fmt++) + { + case '\0': --fmt; break; + + case 's': x += strat(x, y, va_arg(va, char *), color ); break; + case 'S': x += wstrat(x, y, va_arg(va, char *), color ); break; + case 'c': chrat(x++, y, va_arg(va, int), color ); break; + case 'W': color = 0xffff; break; + case 'C': color = va_arg(va, int); break; + case 'z': wideat(x, y, va_arg(va, int)+7056, 0xffe0); x+=2; break; + case '%': chrat(x++, y, '%', color); break; + case 'd': x += strat(x, y, itoa(va_arg(va, int)), color ); break; + case 'p': x += strat(x, y, "(void *)0x", color); + case 'x': + { + char buf[9]; + int i, d; + int n = va_arg( va, int ); + for(i=0; i<8; i++) + { + d = n&15; + n>>=4; + if(d<10) + buf[7-i]='0'+d; + else + buf[7-i]='a'+(d-10); + } + buf[8]=0; + if(fmt[-1]=='p') + x += strat(x, y, buf, color); + else + x += strat(x, y, buf+6, color); + break; + } + case 'b': + { + char bits[33]; + int i, d = va_arg( va, int); + bits[32]=0; + for( i = 0; i<31; i++ ) + if( d & (1<>2; + while(n--) { + v = ExtractU32(); + *p++ = v; + *p++ = v>>8; + *p++ = v>>16; + *p++ = v>>24; + } + if((nbytes&=3)) { + v = ExtractU32(); + while(nbytes--) { + *p++ = v; + v >>= 8; + } + } +} + +#ifdef STANDALONE_TOOL + +#include + +int main() +{ + uint8_t buf[8192]; + uint32_t total = 32*1024*1024; + pseudorandom_init(PSEUDORANDOM_SEED); + while(total > 0) { + uint32_t chunk = (total > sizeof(buf)? sizeof(buf) : total); + pseudorandom_fill(buf, chunk); + if (fwrite(buf, sizeof(uint8_t), chunk, stdout) != chunk) { + fprintf(stderr, "Write failed!\n"); + return 1; + } + total -= chunk; + } + return 0; +} + +#endif + +/* Mersenne Twister (https://en.wikipedia.org/wiki/Mersenne_Twister) */ + +// Define MT19937 constants (32-bit RNG) +enum +{ + // Assumes W = 32 (omitting this) + N = 624, + M = 397, + R = 31, + A = 0x9908B0DF, + + F = 1812433253, + + U = 11, + // Assumes D = 0xFFFFFFFF (omitting this) + + S = 7, + B = 0x9D2C5680, + + T = 15, + C = 0xEFC60000, + + L = 18, + + MASK_LOWER = (1ull << R) - 1, + MASK_UPPER = (1ull << R) +}; + +static uint32_t mt[N]; +static uint16_t index; + +// Re-init with a given seed +void Initialize(const uint32_t seed) +{ + uint32_t i; + + mt[0] = seed; + + for ( i = 1; i < N; i++ ) + { + mt[i] = (F * (mt[i - 1] ^ (mt[i - 1] >> 30)) + i); + } + + index = N; +} + +static void Twist() +{ + uint32_t i, x, xA; + + for ( i = 0; i < N; i++ ) + { + x = (mt[i] & MASK_UPPER) + (mt[(i + 1) % N] & MASK_LOWER); + + xA = x >> 1; + + if ( x & 0x1 ) + xA ^= A; + + mt[i] = mt[(i + M) % N] ^ xA; + } + + index = 0; +} + +// Obtain a 32-bit random number +uint32_t ExtractU32() +{ + uint32_t y; + int i = index; + + if ( index >= N ) + { + Twist(); + i = index; + } + + y = mt[i]; + index = i + 1; + + y ^= (mt[i] >> U); + y ^= (y << S) & B; + y ^= (y << T) & C; + y ^= (y >> L); + + return y; +} diff --git a/zeldin_iceGDROM/test/source/pseudorandom.h b/zeldin_iceGDROM/test/source/pseudorandom.h new file mode 100644 index 0000000000000000000000000000000000000000..3c24eb880f201e246d03141b3fd1eaf2d5f605b2 --- /dev/null +++ b/zeldin_iceGDROM/test/source/pseudorandom.h @@ -0,0 +1,7 @@ +#include + +void pseudorandom_init(uint32_t seed); +void pseudorandom_fill(void *ptr, uint32_t nbytes); + +#define PSEUDORANDOM_SEED 0xfeedd00d + diff --git a/zeldin_iceGDROM/test/source/soundcommon.h b/zeldin_iceGDROM/test/source/soundcommon.h new file mode 100644 index 0000000000000000000000000000000000000000..12e54d5980c2b9d317f41c22bb465910e37554d0 --- /dev/null +++ b/zeldin_iceGDROM/test/source/soundcommon.h @@ -0,0 +1,15 @@ +#define MODE_PAUSE 0 +#define MODE_PLAY 1 + +#define SOUNDSTATUS_ADDR 0x00ff80 +#define SAMPLE_BASE_LEFT 0x040000 +#define SAMPLE_BASE_RIGHT 0x120000 + +#define SAMPLE_DATA_LENGTH 32768 + +struct soundstatus { + int mode; + int cmd; + int cmdstatus; + int samplepos; +}; diff --git a/zeldin_iceGDROM/tools/source/cdi.c b/zeldin_iceGDROM/tools/source/cdi.c new file mode 100644 index 0000000000000000000000000000000000000000..5d8f04ae8fe1090444f4162671d2f5d4cd1affd8 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/cdi.c @@ -0,0 +1,225 @@ +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" +#include "cdi.h" + +#define CDI_VERSION_2 0x80000004UL +#define CDI_VERSION_3 0x80000005UL +#define CDI_VERSION_3_5 0x80000006UL + +static uint32_t get_le32(const uint8_t *p) +{ + return (((uint32_t)p[3])<<24)|(((uint32_t)p[2])<<16)|(((uint32_t)p[1])<<8)|p[0]; +} + +static uint16_t get_le16(const uint8_t *p) +{ + return (((uint16_t)p[1])<<8)|p[0]; +} + +static bool cdi_parse_track(FILE *f, const char *fn, uint32_t version, + uint8_t track, uint8_t session, uint32_t *offs) +{ + static const uint8_t mark[10] = { 0, 0, 1, 0, 0, 0, ~0, ~0, ~0, ~0 }; + uint8_t buf[89]; + int i; + if (fread(buf, 1, 4, f) != 4) { + msg_perror(fn); + return false; + } + if (get_le32(buf) != 0 && + fseek(f, 8, SEEK_CUR) < 0) { + msg_perror(fn); + return false; + } + if (fread(buf, 1, 25, f) != 25) { + msg_perror(fn); + return false; + } + if (memcmp(buf, mark, 10) || memcmp(buf+10, mark, 10)) { + msg_error("Track start mark not identified\n"); + return false; + } + if (buf[24] > 0 && + fseek(f, buf[24], SEEK_CUR) < 0) { + msg_perror(fn); + return false; + } + if (fread(buf, 1, 23, f) != 23) { + msg_perror(fn); + return false; + } + if (get_le32(buf+19) == 0x80000000UL && + fseek(f, 8, SEEK_CUR) < 0) { + msg_perror(fn); + return false; + } + if (fread(buf, 1, 89, f) != 89) { + msg_perror(fn); + return false; + } + + struct track *t = track_create(); + if (!t) + return false; + t->track_nr = track; + t->session_nr = session - 1; + t->track_ctl = buf[60]; + t->start_sector = get_le32(buf+32)+150; + + uint32_t pregap = get_le32(buf+2); + uint32_t length = get_le32(buf+6); + uint32_t tot_length = get_le32(buf+36); + + uint32_t secsize; + switch (buf[56]) { + case 0: secsize = 2048; break; + case 1: secsize = 2336; break; + case 2: secsize = 2352; break; + default: + msg_error("Unknown sector size encountered\n"); + return false; + } + + enum track_type type; + switch (buf[16]) { + case 0: + if (secsize != 2352) { + msg_error("Invalid sector size for audio track\n"); + return false; + } + type = TRACK_RAW_2352; + break; + case 1: + if (secsize != 2048) { + msg_error("Invalid sector size for mode 1 track\n"); + return false; + } + type = TRACK_MODE_1_2048; + break; + case 2: + if (secsize == 2336) + type = TRACK_MODE_2_2336; + else if (secsize == 2048) + type = TRACK_XA_FORM_1_2048; + else { + msg_error("Invalid sector size for mode 2 track\n"); + return false; + } + break; + default: + msg_error("Invalid track mode\n"); + return false; + } + + if (!track_data_from_file(t, type, secsize, f, + *offs + pregap * secsize, + length)) + return false; + + *offs += tot_length * secsize; + + if (version != CDI_VERSION_2) { + if (fread(buf, 1, 9, f) != 9) { + msg_perror(fn); + return false; + } + if (get_le32(buf+5) == (uint32_t)(~0UL) && + fseek(f, 78, SEEK_CUR) < 0) { + msg_perror(fn); + return false; + } + } + + return true; +} + +static bool cdi_check_footer(FILE *f, uint32_t *verp, uint32_t *offp) +{ + uint8_t buf[8]; + uint32_t ver, off; + + if (fseek(f, -8, SEEK_END) < 0 || + fread(buf, 1, 8, f) != 8) + return false; + + ver = get_le32(buf+0); + off = get_le32(buf+4); + + if (ver != CDI_VERSION_2 && + ver != CDI_VERSION_3 && + ver != CDI_VERSION_3_5) + return false; + + if (!off) + return false; + + if (ver == CDI_VERSION_3_5) { + long file_end = ftell(f); + if (file_end < 0) + return false; + off = file_end - off; + } + + if (verp) + *verp = ver; + if (offp) + *offp = off; + return true; +} + +bool cdi_check_file(FILE *f) +{ + return cdi_check_footer(f, NULL, NULL); +} + +bool cdi_parse_and_add_tracks(FILE *f, const char *fn) +{ + uint32_t version, hdr_off, offs = 0; + unsigned nses, ses_no, trk_no = 1; + uint8_t buf[2]; + if (!cdi_check_footer(f, &version, &hdr_off)) { + msg_error("Failed to parse CDI footer\n"); + return false; + } + if (fseek(f, hdr_off, SEEK_SET) < 0 || + fread(buf, 1, 2, f) != 2) { + msg_perror(fn); + return false; + } + nses = get_le16(buf); + if (!nses) { + msg_error("No sessions in image\n"); + return false; + } + msg_info("Image has %u session(s)\n", nses); + for (ses_no = 1; ses_no <= nses; ses_no++) { + unsigned ntrk; + if (fread(buf, 1, 2, f) != 2) { + msg_perror(fn); + return false; + } + ntrk = get_le16(buf); + if (!ntrk) { + msg_error("No tracks in session %u\n", ses_no); + return false; + } + msg_info("Session %u has %u track(s)\n", ses_no, ntrk); + do { + if (!cdi_parse_track(f, fn, version, trk_no, ses_no, &offs)) + return false; + trk_no++; + } while(--ntrk); + if (fseek(f, (version == CDI_VERSION_2? 12 : 13), SEEK_CUR) < 0) { + msg_perror(fn); + return false; + } + } + + return true; +} + diff --git a/zeldin_iceGDROM/tools/source/cdi.h b/zeldin_iceGDROM/tools/source/cdi.h new file mode 100644 index 0000000000000000000000000000000000000000..5b062e64918767cf93d3493b0af291b01dd51270 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/cdi.h @@ -0,0 +1,6 @@ +#include + +extern bool cdi_check_file(FILE *); +extern bool cdi_parse_and_add_tracks(FILE *, const char *); + + diff --git a/zeldin_iceGDROM/tools/source/cdrdao.c b/zeldin_iceGDROM/tools/source/cdrdao.c new file mode 100644 index 0000000000000000000000000000000000000000..6a50939b1c0f15af7eea697fa7efa3491c45a0e9 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/cdrdao.c @@ -0,0 +1,727 @@ +#include +#include +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" +#include "cdrdao.h" + +/* + The following directives are not supported: + + CATALOG + CD_TEXT + FIFO + ISRC + PREGAP + + The following directives are ignored: + + END + INDEX + START + disk type (it is inferred from the track types instead) + +*/ + +enum { + TOK_CATALOG = 0, + TOK_CD_DA, + TOK_CD_I, + TOK_CD_ROM, + TOK_CD_ROM_XA, + TOK_FIRST_TRACK_NO, + + TOK_CD_TEXT, + TOK_TRACK, + + TOK_AUDIOFILE, + TOK_COPY, + TOK_DATAFILE, + TOK_END, + TOK_FIFO, + TOK_FILE, + TOK_FOUR_CHANNEL_AUDIO, + TOK_INDEX, + TOK_ISRC, + TOK_NO, + TOK_PREGAP, + TOK_PRE_EMPHASIS, + TOK_SILENCE, + TOK_START, + TOK_TWO_CHANNEL_AUDIO, + TOK_ZERO, + + TOK_ARRANGER, + TOK_AUDIO, + TOK_COMPOSER, + TOK_DISC_ID, + TOK_EN, + TOK_GENRE, + TOK_LANGUAGE, + TOK_LANGUAGE_MAP, + TOK_MESSAGE, + TOK_MODE0, + TOK_MODE1, + TOK_MODE1_RAW, + TOK_MODE2, + TOK_MODE2_FORM1, + TOK_MODE2_FORM2, + TOK_MODE2_FORM_MIX, + TOK_MODE2_RAW, + TOK_PERFORMER, + TOK_RESERVED1, + TOK_RESERVED2, + TOK_RESERVED3, + TOK_RESERVED4, + TOK_RW, + TOK_RW_RAW, + TOK_SIZE_INFO, + TOK_SONGWRITER, + TOK_SWAP, + TOK_TITLE, + TOK_TOC_INFO1, + TOK_TOC_INFO2, + TOK_UPC_EAN, + + TOK_FIRST = TOK_CATALOG, + TOK_LAST_VALID_TRACK_META = TOK_ZERO, + TOK_LAST = TOK_UPC_EAN, + + TOK_NL = -1, + TOK_EOF = -2, + TOK_ERROR = -3, + TOK_NOMEM = -4, +}; + +static const char *token_strings[] = { + "CATALOG", + "CD_DA", + "CD_I", + "CD_ROM", + "CD_ROM_XA", + "FIRST_TRACK_NO", + "CD_TEXT", + "TRACK", + "AUDIOFILE", + "COPY", + "DATAFILE", + "END", + "FIFO", + "FILE", + "FOUR_CHANNEL_AUDIO", + "INDEX", + "ISRC", + "NO", + "PREGAP", + "PRE_EMPHASIS", + "SILENCE", + "START", + "TWO_CHANNEL_AUDIO", + "ZERO", + "ARRANGER", + "AUDIO", + "COMPOSER", + "DISC_ID", + "EN", + "GENRE", + "LANGUAGE", + "LANGUAGE_MAP", + "MESSAGE", + "MODE0", + "MODE1", + "MODE1_RAW", + "MODE2", + "MODE2_FORM1", + "MODE2_FORM2", + "MODE2_FORM_MIX", + "MODE2_RAW", + "PERFORMER", + "RESERVED1", + "RESERVED2", + "RESERVED3", + "RESERVED4", + "RW", + "RW_RAW", + "SIZE_INFO", + "SONGWRITER", + "SWAP", + "TITLE", + "TOC_INFO1", + "TOC_INFO2", + "UPC_EAN", +}; + +bool cdrdao_check_file(FILE *f) +{ + char buf[3]; + if (fread(buf, 1, sizeof(buf), f) != sizeof(buf)) + return false; + return (buf[0] == 'C' && buf[1] == 'D' && buf[2] == '_') || + (buf[0] == 'C' && buf[1] == 'A' && buf[3] == 'T'); +} + +static int match_token(const char *t) +{ + int i; + for (i=TOK_FIRST; i<=TOK_LAST; i++) + if (!strcmp(t, token_strings[i])) + return i; + return TOK_ERROR; +} + +static int skip_whitespace(FILE *f) +{ + int ch; + do { + ch = fgetc(f); + if (ch == '/') { + ch = fgetc(f); + if (ch != '/') { + if (ch != EOF) + ungetc(ch, f); + return '/'; + } + do { + ch = fgetc(f); + } while(ch != EOF && ch != '\n'); + } + } while(ch != EOF && ch != '\n' && isspace(ch)); + return ch; +} + +static int get_token(FILE *f) +{ + char tok[32]; + int l; + int ch = skip_whitespace(f); + if (ch == '\n') + return TOK_NL; + else if (ch == EOF) + return TOK_EOF; + else if (ch < 'A' || ch > 'Z') + return TOK_ERROR; + for (l = 0; l < sizeof(tok); l++) { + if ((ch < 'A' || ch > 'Z') && + (ch < '0' || ch > '9') && + (ch != '_')) { + tok[l] = 0; + if (ch != EOF) + ungetc(ch, f); + return match_token(tok); + } + tok[l] = ch; + ch = fgetc(f); + } + return TOK_ERROR; +} + +static bool check_next(char match, FILE *f) +{ + int ch = skip_whitespace(f); + if (ch == match) + return true; + if (ch != EOF) + ungetc(ch, f); + return false; +} + +static int low_get_string(char **str, FILE *f, char *buf, size_t bufsz, size_t cnt) +{ + int ch = skip_whitespace(f); + if (ch != '"') { + if (buf) + free(buf); + if (ch == '\n') + return TOK_NL; + else if (ch == EOF) + return TOK_EOF; + ungetc(ch, f); + return TOK_ERROR; + } + if (!buf) { + msg_oom(); + return TOK_NOMEM; + } + while ((ch = fgetc(f)) != '"') { + if (ch == EOF || (ch != ' ' && isspace(ch))) { + free(buf); + return TOK_ERROR; + } + if (cnt + 4 > bufsz) { + char *newbuf = realloc(buf, bufsz += (bufsz >> 2)); + if (!newbuf) { + free(buf); + msg_oom(); + return TOK_NOMEM; + } + buf = newbuf; + } + if (ch == '\\') { + char oct[4]; + int i; + for (i=0; i<3; i++) { + ch = fgetc(f); + if (ch < '0' || ch > '9') + break; + oct[i] = ch; + } + if (i == 3) { + oct[3] = 0; + buf[cnt++] = strtol(oct, NULL, 8); + } else if (i == 0 && ch == '"') { + buf[cnt++] = '"'; + } else { + int j; + if (ch == EOF) { + free(buf); + return TOK_ERROR; + } + buf[cnt++] = '\\'; + for (j=0; j '9') + return TOK_ERROR; + n = ch - '0'; + while ((ch = fgetc(f)) >= '0') { + if (ch > '9') + break; + if (n > 0x19999999UL) + return TOK_ERROR; + n *= 10; + if (n > 0xffffffffUL - (ch - '0')) + return TOK_ERROR; + n += (ch - '0'); + } + if (ch != EOF) + ungetc(ch, f); + *ret = n; + return 0; +} + +int get_msf(uint32_t *ret, FILE *f) +{ + uint32_t m, s, fr; + int tok; + if ((tok = get_uint32(&m, f)) < 0) + return tok; + if (!check_next(':', f) || + get_uint32(&s, f) < 0 || + !check_next(':', f) || + get_uint32(&fr, f) < 0) + return TOK_ERROR; + *ret = m * 4500 + s * 75 + fr; + return 0; +} + +int get_msf_or_cnt(uint32_t *ret, FILE *f, uint32_t sectorcnt) +{ + uint32_t m, s, fr; + int tok; + if ((tok = get_uint32(&m, f)) < 0) + return tok; + if (check_next(':', f)) { + if (get_uint32(&s, f) < 0 || + !check_next(':', f) || + get_uint32(&fr, f) < 0) + return TOK_ERROR; + *ret = (m * 4500 + s * 75 + fr) * sectorcnt; + } else { + *ret = m; + } + return 0; +} + +bool cdrdao_parse_and_add_tracks(FILE *f, const char *fn) +{ + int line = 1; + uint32_t trackno = 1; + struct track *t = NULL; + enum track_type ttype = TRACK_RAW_2352; + uint32_t filesecsize = 2352; + const char *slash = strrchr(fn, '/'); + unsigned dirlen = (slash? slash-fn+1 : 0); + for (;;) { + int tok = get_token(f); + if (tok == TOK_NL) { + line ++; + continue; + } else if (tok == TOK_EOF) + break; + else if (tok < 0) { + fprintf(stderr, "Syntax error in TOC file line %d\n", line); + return false; + } + + if (tok == TOK_TRACK) { + uint32_t start_sector = (t? t->start_sector + t->data_count : 150); + t = track_create(); + if (!t) + return false; + if (trackno >= 100) { + fprintf(stderr, "Track number too large on TOC file line %d\n", line); + return false; + } + t->track_nr = trackno ++; + t->start_sector = start_sector; + switch ((tok = get_token(f))) { + case TOK_AUDIO: + ttype = TRACK_SWAP_2352; + filesecsize = 2352; + break; + case TOK_MODE1_RAW: + case TOK_MODE2_RAW: + ttype = TRACK_RAW_2352; + filesecsize = 2352; + break; + case TOK_MODE0: + ttype = TRACK_MODE_0_2336; + filesecsize = 2336; + break; + case TOK_MODE1: + ttype = TRACK_MODE_1_2048; + filesecsize = 2048; + break; + case TOK_MODE2: + case TOK_MODE2_FORM_MIX: + ttype = TRACK_MODE_2_2336; + filesecsize = 2336; + break; + case TOK_MODE2_FORM1: + ttype = TRACK_XA_FORM_1_2048; + filesecsize = 2048; + break; + case TOK_MODE2_FORM2: + ttype = TRACK_XA_FORM_2_2324; + filesecsize = 2324; + break; + default: + fprintf(stderr, "Syntax error in TOC file line %d\n", line); + return false; + } + t->track_ctl = (tok == TOK_AUDIO? 0 : 4); + tok = get_token(f); + if (tok == TOK_RW || tok == TOK_RW_RAW) { + if (filesecsize != 2352) { + fprintf(stderr, "Subchannel data not supported for non-raw tracks in TOC file line %d\n", line); + return false; + } + filesecsize += 96; + tok = get_token(f); + } + if (tok == TOK_NL) + line ++; + else if (tok == TOK_EOF) + break; + else { + fprintf(stderr, "Syntax error in TOC file line %d\n", line); + return false; + } + } else if (t == NULL) { + if (tok > TOK_CD_TEXT) { + if (tok > TOK_LAST_VALID_TRACK_META) + fprintf(stderr, "Unexpected token %s on TOC file line %d\n", + token_strings[tok], line); + else + fprintf(stderr, "Unexpected %s before first TRACK on TOC file line %d\n", + token_strings[tok], line); + return false; + } + switch(tok) { + case TOK_CD_DA: + case TOK_CD_I: + case TOK_CD_ROM: + case TOK_CD_ROM_XA: + /* Ignored, disk type is inferred from tracks */ + break; + case TOK_FIRST_TRACK_NO: + if (get_uint32(&trackno, f) < 0) + tok = TOK_ERROR; + else if (trackno < 1 || trackno > 99) { + fprintf(stderr, "Illegal first track number on TOC file line %d\n", line); + return false; + } + break; + default: + fprintf(stderr, "Unimplemented global directive %s on TOC file line %d\n", + token_strings[tok], line); + return false; + } + if (tok >= 0) + tok = get_token(f); + if (tok == TOK_NL) + line ++; + else if (tok == TOK_EOF) + break; + else { + fprintf(stderr, "Syntax error in TOC file line %d\n", line); + return false; + } + } else { + if (tok < TOK_CD_TEXT) { + fprintf(stderr, "Unexpected %s after first TRACK on TOC file line %d\n", + token_strings[tok], line); + return false; + } else if (tok > TOK_LAST_VALID_TRACK_META) { + fprintf(stderr, "Unexpected token %s on TOC file line %d\n", + token_strings[tok], line); + return false; + } else switch(tok) { + case TOK_NO: + tok = get_token(f); + switch (tok) { + case TOK_COPY: + t->track_ctl &= ~2; + break; + case TOK_PRE_EMPHASIS: + t->track_ctl &= ~1; + break; + default: + tok = TOK_ERROR; + } + break; + case TOK_COPY: + t->track_ctl |= 2; + break; + case TOK_PRE_EMPHASIS: + t->track_ctl |= 1; + break; + case TOK_TWO_CHANNEL_AUDIO: + t->track_ctl &= ~0xc; + break; + case TOK_FOUR_CHANNEL_AUDIO: + t->track_ctl &= ~0x4; + t->track_ctl |= 0x8; + break; + case TOK_ZERO: + { + uint32_t bytes, zsecsize = filesecsize; + int ch = skip_whitespace(f); + if (ch == EOF) { + tok = TOK_ERROR; + break; + } + ungetc(ch, f); + if (ch >= 'A' && ch <= 'Z') { + tok = get_token(f); + if (tok < 0) + tok = TOK_ERROR; + else switch(tok) { + case TOK_AUDIO: + case TOK_MODE1_RAW: + case TOK_MODE2_RAW: + zsecsize = 2352; + break; + case TOK_MODE0: + case TOK_MODE2: + case TOK_MODE2_FORM_MIX: + zsecsize = 2336; + break; + case TOK_MODE1: + case TOK_MODE2_FORM1: + zsecsize = 2048; + break; + case TOK_MODE2_FORM2: + zsecsize = 2324; + break; + case TOK_RW: + case TOK_RW_RAW: + if (zsecsize < 2352) { + fprintf(stderr, "Subchannel data not supported for non-raw tracks in TOC file line %d\n", line); + return false; + } + zsecsize = 2352 + 96; + break; + default: + tok = TOK_ERROR; + break; + } + if (tok < 0) + break; + if (tok != TOK_RW && tok != TOK_RW_RAW) { + ch = skip_whitespace(f); + if (ch == EOF) { + tok = TOK_ERROR; + break; + } + ungetc(ch, f); + if (ch >= 'A' && ch <= 'Z') { + tok = get_token(f); + if (tok == TOK_RW || tok == TOK_RW_RAW) { + if (zsecsize != 2352) { + fprintf(stderr, "Subchannel data not supported for non-raw tracks in TOC file line %d\n", line); + return false; + } + zsecsize = 2352 + 96; + } else { + tok = TOK_ERROR; + break; + } + } + } + } + if (get_msf_or_cnt(&bytes, f, zsecsize) < 0) + tok = TOK_ERROR; + else if (zsecsize < 2352) { + fprintf(stderr, "ZERO only supported for raw tracks, TOC file line %d\n", line); + return false; + } else if (t->data_filename) { + fprintf(stderr, "ZERO not supported after data file, TOC file line %d\n", line); + return false; + } else + t->start_sector += bytes / zsecsize; + break; + } + case TOK_SILENCE: + { + uint32_t samples; + if (get_msf_or_cnt(&samples, f, 588) < 0) + tok = TOK_ERROR; + else if (t->track_ctl & 4) { + fprintf(stderr, "SILENCE only supported for audio tracks, TOC file line %d\n", line); + return false; + } else if (t->data_filename) { + fprintf(stderr, "SILENCE not supported after data file, TOC file line %d\n", line); + return false; + } else + t->start_sector += samples / 588; + break; + } + case TOK_DATAFILE: + { + char *filename; + uint32_t offs = 0; + uint32_t len = 0; + if ((tok = get_filename(&filename, f, fn, dirlen)) < 0) { + if (tok == TOK_NOMEM) + return false; + tok = TOK_ERROR; + break; + } + if (check_next('#', f)) { + if (get_uint32(&offs, f) < 0) { + tok = TOK_ERROR; + free(filename); + break; + } + } + tok = get_msf_or_cnt(&len, f, filesecsize); + if (tok != TOK_ERROR && + !track_data_from_filename(t, ttype, filesecsize, filename, offs, (tok < 0? TRACK_SECTOR_COUNT_PROBE : len / filesecsize))) { + free(filename); + return false; + } + free(filename); + break; + } + case TOK_FILE: + case TOK_AUDIOFILE: + { + char *filename; + uint32_t offs = 0; + uint32_t start = 0; + uint32_t len = 0; + if ((t->track_ctl & 4) || filesecsize != 2352) { + fprintf(stderr, "Audio files only allowed with audio tracks, TOC file line %d\n", line); + return false; + } + if ((tok = get_filename(&filename, f, fn, dirlen)) < 0) { + if (tok == TOK_NOMEM) + return false; + tok = TOK_ERROR; + break; + } + if (check_next('S', f)) { + ungetc('S', f); + if (get_token(f) != TOK_SWAP) { + free(filename); + tok = TOK_ERROR; + break; + } + ttype = TRACK_RAW_2352; + } + if (check_next('#', f)) { + if (get_uint32(&offs, f) < 0) { + tok = TOK_ERROR; + free(filename); + break; + } + } + if (get_msf_or_cnt(&start, f, 588) < 0) { + tok = TOK_ERROR; + free(filename); + break; + } + tok = get_msf_or_cnt(&len, f, 588); + if (tok != TOK_ERROR && + !track_data_from_filename(t, ttype, filesecsize, filename, offs + start*4, (tok < 0? TRACK_SECTOR_COUNT_PROBE : len / 588))) { + free(filename); + return false; + } + free(filename); + break; + } + case TOK_START: + case TOK_END: + case TOK_INDEX: + { + /* Ignored */ + uint32_t pos; + tok = get_msf(&pos, f); + break; + } + default: + fprintf(stderr, "Unimplemented track directive %s on TOC file line %d\n", + token_strings[tok], line); + return false; + } + if (tok >= 0) + tok = get_token(f); + if (tok == TOK_NL) + line ++; + else if (tok == TOK_EOF) + break; + else { + fprintf(stderr, "Syntax error in TOC file line %d\n", line); + return false; + } + } + } + + return true; +} diff --git a/zeldin_iceGDROM/tools/source/cdrdao.h b/zeldin_iceGDROM/tools/source/cdrdao.h new file mode 100644 index 0000000000000000000000000000000000000000..98d39ccaeae5ee28b9f6652c0430b1eef22cd180 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/cdrdao.h @@ -0,0 +1,4 @@ +#include + +extern bool cdrdao_check_file(FILE *); +extern bool cdrdao_parse_and_add_tracks(FILE *, const char *); diff --git a/zeldin_iceGDROM/tools/source/gdi.c b/zeldin_iceGDROM/tools/source/gdi.c new file mode 100644 index 0000000000000000000000000000000000000000..56e81e25179ec362a6fbf391305969ea924bfb08 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/gdi.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" +#include "gdi.h" + +bool gdi_check_file(FILE *f) +{ + char buf[3]; + if (fread(buf, 1, sizeof(buf), f) != sizeof(buf)) + return false; + return (isdigit(buf[0]) && + (isspace(buf[1]) || + (isdigit(buf[1]) && isspace(buf[2])))); +} + +bool gdi_parse_and_add_tracks(FILE *f, const char *fn) +{ + unsigned num_tracks; + const char *slash = strrchr(fn, '/'); + unsigned dirlen = (slash? slash-fn+1 : 0); + if (1 != fscanf(f, "%u", &num_tracks)) { + msg_error("Failed to parse GDI file (track number line)\n"); + return false; + } + for (unsigned i = 0; i < num_tracks; i++) { + unsigned track_no, start, ctrl, secsize, offset; + char fnc1, filename[dirlen+101]; + if (5 != fscanf(f, "%u %u %u %u %c", + &track_no, &start, &ctrl, &secsize, &fnc1)) { + msg_error("Failed to parse GDI file (track %u)\n", i+1); + return false; + } + const char *fmt; + if (fnc1 == '"') + fmt = "%100[^\"]\" %u"; + else { + fmt = "%100s %u"; + ungetc(fnc1, f); + } + if (2 != fscanf(f, fmt, filename+dirlen, &offset)) { + msg_error("Failed to parse GDI file (track %u)\n", i+1); + return false; + } + if (dirlen) + memcpy(filename, fn, dirlen); + struct track *t = track_create(); + if (!t) + return false; + t->track_nr = track_no; + t->track_ctl = ctrl; + if (start >= 45000) + t->toc_nr = 1; + t->start_sector = start+150; + enum track_type type; + switch (secsize) { + case 2048: type = TRACK_MODE_1_2048; break; + case 2336: type = TRACK_MODE_2_2336; break; + case 2352: type = TRACK_RAW_2352; break; + case 2368: + case 2448: + /* Raw format with subchannels, use raw format and discard subchannels */ + type = TRACK_RAW_2352; + break; + default: + msg_error("Unsupported sector size %u in GDI file (track %u)\n", + secsize, i+1); + return false; + } + if (!track_data_from_filename(t, type, secsize, filename, offset, + TRACK_SECTOR_COUNT_PROBE)) + return false; + } + return true; +} + diff --git a/zeldin_iceGDROM/tools/source/gdi.h b/zeldin_iceGDROM/tools/source/gdi.h new file mode 100644 index 0000000000000000000000000000000000000000..b92c9bda84b47f6fe74e2e798f0d59fae272414b --- /dev/null +++ b/zeldin_iceGDROM/tools/source/gdi.h @@ -0,0 +1,6 @@ +#include + +extern bool gdi_check_file(FILE *); +extern bool gdi_parse_and_add_tracks(FILE *, const char *); + + diff --git a/zeldin_iceGDROM/tools/source/imgfile.c b/zeldin_iceGDROM/tools/source/imgfile.c new file mode 100644 index 0000000000000000000000000000000000000000..e0ddb8ab0cb58b07cf790ccca0a193d4149ba4e9 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/imgfile.c @@ -0,0 +1,269 @@ +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" +#include "nrg.h" +#include "gdi.h" +#include "cdi.h" +#include "cdrdao.h" +#include "imgfile.h" + +static struct { + const char *name; + bool binary; + bool (*check_file)(FILE*); + bool (*parse_and_add_tracks)(FILE*, const char *); +} formats[] = { + { "Nero", true, nrg_check_file, nrg_parse_and_add_tracks }, + { "DiscJuggler", true, cdi_check_file, cdi_parse_and_add_tracks }, + { "GDI", false, gdi_check_file, gdi_parse_and_add_tracks }, + { "cdrdao TOC", false, cdrdao_check_file, cdrdao_parse_and_add_tracks }, +}; + +static struct imgheader imgheader; + +static void set_le32(uint32_t *p, uint32_t v) +{ + union { uint32_t i; uint8_t b[4]; } u; + u.b[0] = v&0xff; + u.b[1] = (v>>8)&0xff; + u.b[2] = (v>>16)&0xff; + u.b[3] = (v>>24)&0xff; + *p = u.i; +} + +static bool imgfile_prepare(void) +{ + memset(&imgheader, 0, sizeof(imgheader)); + set_le32(&imgheader.magic, HEADER_MAGIC); + struct track *prev_track = NULL, *first_track = track_get_first(); + if (!first_track) { + msg_error("No tracks in image\n"); + return false; + } + if (first_track->toc_nr != 0) { + msg_error("First track not in TOC 0\n"); + return false; + } + if (first_track->session_nr != 0) { + msg_error("First track not in session 0\n"); + return false; + } + bool found_data = false; + TRACK_FOREACH (t) { + if (t->track_nr < 1 || t->track_nr > 99) { + msg_error("Invalid track number\n"); + return false; + } + if (t->toc_nr > 1) { + msg_error("Too many TOCs\n"); + return false; + } + if (t->session_nr >= MAX_SESSIONS-1) { + msg_error("Too many sessions\n"); + return false; + } + if (t->toc_nr >= imgheader.num_tocs) + imgheader.num_tocs = t->toc_nr+1; + if (t->session_nr >= imgheader.num_sessions) + imgheader.num_sessions = t->session_nr+1; + if (prev_track) { + if (t->toc_nr != prev_track->toc_nr && t->toc_nr != prev_track->toc_nr+1) { + msg_error("Invalid TOC sequence\n"); + return false; + } + if (t->session_nr != prev_track->session_nr && t->session_nr != prev_track->session_nr+1) { + msg_error("Invalid session sequence\n"); + return false; + } + if (t->start_sector < prev_track->start_sector) { + msg_error("FAD goes backwards!\n"); + return false; + } + if (prev_track->data_count > t->start_sector - prev_track->start_sector) { + prev_track->data_count = t->start_sector - prev_track->start_sector; + msg_warning("Truncating track %u to %u sectors\n", + (unsigned)prev_track->track_nr, + (unsigned)prev_track->data_count); + } + } + if (prev_track && t->track_ctl == prev_track->track_ctl && + t->start_sector == prev_track->start_sector+prev_track->data_count) { + t->region_nr = prev_track->region_nr; + } else { + t->region_nr = imgheader.num_regions; + if (++imgheader.num_regions > MAX_REGIONS) { + msg_error("Too many regions\n"); + return false; + } + } + if (prev_track == NULL || prev_track->session_nr != t->session_nr) { + imgheader.sessions[t->session_nr+1][0] = t->session_nr+1; + imgheader.sessions[t->session_nr+1][1] = (t->start_sector>>16)&0xff; + imgheader.sessions[t->session_nr+1][2] = (t->start_sector>>8)&0xff; + imgheader.sessions[t->session_nr+1][3] = t->start_sector&0xff; + } + if(t->track_ctl & 4) + found_data = true; + msg_progress_register_nr(t->track_nr, t->data_count); + prev_track = t; + } + imgheader.sessions[0][0] = imgheader.num_sessions; + if (prev_track) { + imgheader.sessions[0][1] = ((prev_track->start_sector+prev_track->data_count)>>16)&0xff; + imgheader.sessions[0][2] = ((prev_track->start_sector+prev_track->data_count)>>8)&0xff; + imgheader.sessions[0][3] = (prev_track->start_sector+prev_track->data_count)&0xff; + } + if (imgheader.num_tocs > 1) + imgheader.disk_type = 0x80; + else if(imgheader.num_sessions > 1) + imgheader.disk_type = 0x20; + else if(found_data) + imgheader.disk_type = 0x10; + else + imgheader.disk_type = 0x00; + imgheader.num_sessions++; + uint32_t data_offs = 1+imgheader.num_tocs, data_sectors = 0; + prev_track = NULL; + TRACK_FOREACH (t) { + if (prev_track == NULL || t->region_nr != prev_track->region_nr) { + data_offs += (data_sectors*2352+511)>>9; + data_sectors = 0; + uint32_t sat = t->start_sector; + sat |= ((uint32_t)t->track_ctl) << 24; + if (t->toc_nr > 0) + sat |= ((uint32_t)1)<<31; + set_le32(&imgheader.regions[t->region_nr].start_and_type, sat); + set_le32(&imgheader.regions[t->region_nr].fileoffs, data_offs); + } + data_sectors += t->data_count; + prev_track = t; + } + return true; +} + +static bool imgfile_write_toc(FILE *f, uint8_t tnr) +{ + bool first_track = true; + struct toc toc; + uint8_t pad[512-sizeof(toc)]; + memset(&toc, 0xff, sizeof(toc)); + memset(pad, 0, sizeof(pad)); + toc.first_track.pad[0] = 0; + toc.first_track.pad[1] = 0; + toc.last_track.pad[0] = 0; + toc.last_track.pad[1] = 0; + TRACK_FOREACH (t) + if (t->toc_nr == tnr) { + toc.entry[t->track_nr-1].ctrl_adr = (t->track_ctl << 4) | 1; + toc.entry[t->track_nr-1].fad[0] = (t->start_sector>>16)&0xff; + toc.entry[t->track_nr-1].fad[1] = (t->start_sector>>8)&0xff; + toc.entry[t->track_nr-1].fad[2] = t->start_sector&0xff; + if (first_track) { + toc.first_track.ctrl_adr = toc.entry[t->track_nr-1].ctrl_adr; + toc.first_track.track_nr = t->track_nr; + first_track = false; + } + toc.last_track.ctrl_adr = toc.entry[t->track_nr-1].ctrl_adr; + toc.last_track.track_nr = t->track_nr; + toc.lead_out.ctrl_adr = toc.entry[t->track_nr-1].ctrl_adr; + toc.lead_out.fad[0] = ((t->start_sector+t->data_count)>>16)&0xff; + toc.lead_out.fad[1] = ((t->start_sector+t->data_count)>>8)&0xff; + toc.lead_out.fad[2] = (t->start_sector+t->data_count)&0xff; + } + if (first_track) { + msg_error("No tracks in TOC %u\n", (unsigned)tnr); + return false; + } + if (fwrite(&toc, 1, sizeof(toc), f) != sizeof(toc) || + fwrite(&pad, 1, sizeof(pad), f) != sizeof(pad)) { + msg_error("Failed to write TOC\n"); + return false; + } + return true; +} + +static bool pad_region(FILE *f) +{ + uint8_t pad[512]; + memset(pad, 0, sizeof(pad)); + long pos = ftell(f); + if (pos < 0) { + msg_perror("ftell"); + return false; + } + if (pos & 511) { + int cnt = 512 - (pos & 511); + if (fwrite(&pad, 1, cnt, f) != cnt) { + msg_error("Failed to write region pad\n"); + return false; + } + } + return true; +} + +static bool imgfile_convert(FILE *f) +{ + uint8_t pad[512-sizeof(imgheader)]; + memset(pad, 0, sizeof(pad)); + if (fwrite(&imgheader, 1, sizeof(imgheader), f) != sizeof(imgheader) || + fwrite(&pad, 1, sizeof(pad), f) != sizeof(pad)) { + msg_error("Failed to write image header\n"); + return false; + } + for (uint8_t toc = 0; toc < imgheader.num_tocs; toc++) { + if (!imgfile_write_toc(f, toc)) + return false; + } + TRACK_FOREACH (t) { + if (!track_convert(t, f)) + return false; + if (!t->next || t->next->region_nr != t->region_nr) + if (!pad_region(f)) + return false; + } + msg_info("Conversion complete\n"); + return true; +} + +static bool imgfile_create(const char *filename_out) +{ + FILE *f = fopen(filename_out, "wb"); + if (!f) { + msg_perror(filename_out); + return false; + } + bool r = imgfile_convert(f); + fclose(f); + return r; +} + +bool imgfile_create_from_source(const char *filename_in, const char *filename_out) +{ + unsigned fmt; + FILE *f; + for (fmt = 0; fmt < sizeof(formats)/sizeof(formats[0]); fmt ++) { + if (!(f = fopen(filename_in, (formats[fmt].binary? "rb" : "r")))) { + msg_perror(filename_in); + return false; + } + if (formats[fmt].check_file(f)) { + rewind(f); + msg_info("Input appears to be a %s file\n", formats[fmt].name); + bool r = formats[fmt].parse_and_add_tracks(f, filename_in); + if (r) + r = imgfile_prepare(); + if (r) + r = imgfile_create(filename_out); + track_delete_all(); + fclose(f); + return r; + } + fclose(f); + } + msg_error("Unrecognized input file \"%s\"\n", filename_in); + return false; +} diff --git a/zeldin_iceGDROM/tools/source/imgfile.h b/zeldin_iceGDROM/tools/source/imgfile.h new file mode 100644 index 0000000000000000000000000000000000000000..878fb511c37d30e59ad55199fd8ef98975621030 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/imgfile.h @@ -0,0 +1,48 @@ +#include +#include + +#define MAX_SESSIONS 6 +#define MAX_REGIONS 8 + +#define HEADER_MAGIC 0xdc0001dc + +struct region +{ + uint32_t start_and_type; + uint32_t fileoffs; +}; + +struct imgheader +{ + uint32_t magic; + uint8_t disk_type; + uint8_t num_tocs; + uint8_t num_sessions; + uint8_t num_regions; + uint8_t sessions[MAX_SESSIONS][4]; + struct region regions[MAX_REGIONS]; +}; + +struct tocentry +{ + uint8_t ctrl_adr; + uint8_t fad[3]; +}; + +struct tocindex +{ + uint8_t ctrl_adr; + uint8_t track_nr; + uint8_t pad[2]; +}; + +struct toc +{ + struct tocentry entry[99]; + struct tocindex first_track; + struct tocindex last_track; + struct tocentry lead_out; +}; + +extern bool imgfile_create_from_source(const char *, const char *); + diff --git a/zeldin_iceGDROM/tools/source/main.c b/zeldin_iceGDROM/tools/source/main.c new file mode 100644 index 0000000000000000000000000000000000000000..fb8996443882bbd81abeb47a7e40dd18aa2404bc --- /dev/null +++ b/zeldin_iceGDROM/tools/source/main.c @@ -0,0 +1,15 @@ +#include +#include +#include + +#include "msg.h" +#include "imgfile.h" + +int main(int argc, char *argv[]) +{ + if (argc != 3) { + fprintf(stderr, "Usage: %s inputfile outputfile\n", argv[0]); + return 1; + } + return imgfile_create_from_source(argv[1], argv[2])? 0 : 1; +} diff --git a/zeldin_iceGDROM/tools/source/msg.c b/zeldin_iceGDROM/tools/source/msg.c new file mode 100644 index 0000000000000000000000000000000000000000..4f3fbf55c3a61d7679c6f0caebc6367f878f0536 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/msg.c @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include +#include + +#include "msg.h" + +enum msg_level { + MSG_INFO, + MSG_WARNING, + MSG_ERROR, +}; + +static bool progress_shown = false; +static uint32_t prog_complete = 0, prog_total = 0, prog_base = 0; +static uint8_t prog_nr = 0, prog_max_nr = 0, prog_percent = 0; + +static void msg_hide_progress(void) +{ + if (!progress_shown) + return; + printf("\r \r"); + fflush(stdout); + progress_shown = false; +} + +static void msg_show_progress(bool force) +{ + unsigned percent = (prog_total? 100 * prog_complete / prog_total : 100); + if (!force && progress_shown && percent == prog_percent) + return; + unsigned half_percent = percent / 2; + char bar[64]; + if (half_percent > 0) + memset(bar, '=', half_percent); + if (half_percent < 50) + memset(bar+half_percent, '-', 50-half_percent); + bar[50] = 0; + printf("\r[%02d/%02d] [%s] %d%%", prog_nr, prog_max_nr, bar, percent); + fflush(stdout); + prog_percent = percent; + progress_shown = true; +} + +void msg_progress_register_nr(uint8_t nr, uint32_t total) +{ + if (nr > prog_max_nr) + prog_max_nr = nr; + prog_total += total; +} + +void msg_progress_start_nr(uint8_t nr) +{ + prog_nr = nr; + prog_base = prog_complete; + msg_show_progress(true); +} + +void msg_progress_update(uint32_t complete, uint32_t total) +{ + prog_complete = prog_base + complete; + msg_show_progress(false); +} + +static void msg_vmessage(enum msg_level level, const char *fmt, va_list va) +{ + if (progress_shown) { + msg_hide_progress(); + } + if (level >= MSG_WARNING) + vfprintf(stderr, fmt, va); + else + vprintf(fmt, va); +} + +void msg_error(const char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + msg_vmessage(MSG_ERROR, fmt, va); + va_end(va); +} + +void msg_warning(const char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + msg_vmessage(MSG_WARNING, fmt, va); + va_end(va); +} + +void msg_info(const char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + msg_vmessage(MSG_INFO, fmt, va); + va_end(va); +} + +void msg_oom(void) +{ + msg_error("Out of memory!\n"); +} + +void msg_perror(const char *prefix) +{ + if (prefix && *prefix) + msg_error("%s: %s\n", prefix, strerror(errno)); + else + msg_error("%s\n", strerror(errno)); +} + diff --git a/zeldin_iceGDROM/tools/source/msg.h b/zeldin_iceGDROM/tools/source/msg.h new file mode 100644 index 0000000000000000000000000000000000000000..9756c41a388964cbd118e2371a41271859032bba --- /dev/null +++ b/zeldin_iceGDROM/tools/source/msg.h @@ -0,0 +1,10 @@ +#include + +extern void msg_progress_register_nr(uint8_t, uint32_t); +extern void msg_progress_start_nr(uint8_t); +extern void msg_progress_update(uint32_t, uint32_t); +extern void msg_error(const char *, ...); +extern void msg_warning(const char *, ...); +extern void msg_info(const char *, ...); +extern void msg_perror(const char *); +extern void msg_oom(void); diff --git a/zeldin_iceGDROM/tools/source/nrg.c b/zeldin_iceGDROM/tools/source/nrg.c new file mode 100644 index 0000000000000000000000000000000000000000..cca329ec891e6ddd14ccc1e00e29694be6041d31 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/nrg.c @@ -0,0 +1,280 @@ +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" +#include "nrg.h" + +#define CHUNK_ID(a,b,c,d) ((((uint32_t)a)<<24)|(((uint32_t)b)<<16)|(((uint32_t)c)<<8)|d) + +static uint32_t get_be32(const uint8_t *p) +{ + return (((uint32_t)p[0])<<24)|(((uint32_t)p[1])<<16)|(((uint32_t)p[2])<<8)|p[3]; +} + +static uint16_t get_be16(const uint8_t *p) +{ + return (((uint16_t)p[0])<<8)|p[1]; +} + +static uint8_t from_bcd(uint8_t n) +{ + return (n>>4)*10+(n&15); +} + +static uint32_t get_msf(const uint8_t *p) +{ + uint32_t s = from_bcd(p[0])*60 + from_bcd(p[1]); + return s*75 + from_bcd(p[2]); +} + +static bool nrg_parse_cuesx(FILE *f, const char *fn, uint32_t len, bool x) +{ + uint32_t lead_out; + if (len < 16 || (len&15)) { + msg_error("Invalid CUE%c length\n", (x? 'X' : 'S')); + return false; + } + len >>= 3; + for (uint32_t n = 0; n < len; n++) { + uint8_t entry[8]; + if (fread(entry, 1, 8, f) != 8) { + msg_perror(fn); + return false; + } + if (n == 0) { + if (entry[1] != 0x00 || entry[2] != 0x00) { + msg_error("Incorrect header of CUE%c chunk\n", (x? 'X' : 'S')); + return false; + } + } else if (n == len-1) { + if (entry[1] != 0xaa || entry[2] != 0x01) { + msg_error("Incorrect footer of CUE%c chunk\n", (x? 'X' : 'S')); + return false; + } + } + uint32_t lba = (x? get_be32(entry+4)+150 : get_msf(entry+5)); + if (entry[2] == 1) { + if (entry[1] == 0xaa) + lead_out = lba; + else { + struct track *t = track_create(); + if (!t) + return false; + t->track_nr = from_bcd(entry[1]); + t->track_ctl = entry[0]>>4; + t->start_sector = lba; + } + } + } + return true; +} + +static bool nrg_parse_daoix(FILE *f, const char *fn, uint32_t len, bool x) +{ + if (len < 22 || (len-22)%(x?42:30)) { + msg_error("Invalid DAO%c length\n", (x? 'X' : 'I')); + } + uint8_t entry[42]; + if (fread(entry, 1, 22, f) != 22) { + msg_perror(fn); + return false; + } + len -= 22; + len /= (x? 42 : 30); + uint8_t first_track = entry[20], last_track = entry[21]; + if (last_track < first_track || len != last_track-first_track+1) { + msg_error("Invalid length of DAO%c chunk\n", (x? 'X' : 'I')); + return false; + } + struct track *t = track_get_first(); + while (len > 0) { + if (fread(entry, 1, (x? 42 : 30), f) != (x? 42 : 30)) { + msg_perror(fn); + return false; + } + while (t != NULL && t->track_nr != first_track) + t = t->next; + if (t == NULL) { + msg_error("Found DAO%c entry for non-existring track %u\n", + (x? 'X' : 'I'), (unsigned)first_track); + return false; + } + uint16_t secsize = get_be16(entry+12); + uint16_t mode = get_be16(entry+14); + uint16_t unk = get_be16(entry+16); + uint32_t i0_hi = (x? get_be32(entry+18) : 0); + uint32_t i0_lo = (x? get_be32(entry+22) : get_be32(entry+18)); + uint32_t i1_hi = (x? get_be32(entry+26) : 0); + uint32_t i1_lo = (x? get_be32(entry+30) : get_be32(entry+22)); + uint32_t e_hi = (x? get_be32(entry+34) : 0); + uint32_t e_lo = (x? get_be32(entry+38) : get_be32(entry+26)); + if (i0_hi || i1_hi || e_hi) { + msg_error("Unexpected 64-bit value in DAOX\n"); + return false; + } + if (!secsize || e_lo < i1_lo) { + msg_error("Invalid sector size / data length\n"); + return false; + } + enum track_type type; + switch (mode) { + case 0x0500: + case 0x0600: + case 0x0700: + case 0x0f00: + case 0x1000: + case 0x1100: + type = TRACK_RAW_2352; + break; + case 0x0000: + type = TRACK_MODE_1_2048; + break; + case 0x0200: + type = TRACK_XA_FORM_1_2048; + break; + case 0x0300: + type = TRACK_MODE_2_2336; + break; + default: + msg_error("Unknown track mode 0x%04x\n", (unsigned)mode); + return false; + } + if (!track_data_from_file(t, type, secsize, f, i1_lo, (e_lo-i1_lo)/secsize)) + return false; + first_track++; + --len; + } + return true; +} + +static int nrg_parse_sinf(FILE *f, const char *fn, uint32_t len, uint8_t nr, int prev) +{ + if (len != 4) { + msg_error("Invalid SINF length\n"); + return -1; + } + uint8_t entry[4]; + if (fread(entry, 1, 4, f) != 4) { + msg_perror(fn); + return -1; + } + uint32_t sinf = get_be32(entry); + uint32_t cnt = sinf; + TRACK_FOREACH(t) { + if (!cnt) + break; + if (prev) + --prev; + else { + t->session_nr = nr; + --cnt; + } + } + if (cnt || prev) { + msg_error("SINF specifies unexisting track(s)\n"); + return -1; + } + return (int)sinf; +} + +static bool nrg_check_footer(FILE *f, uint32_t *offp) +{ + uint8_t buf[12]; + uint32_t off_hi; + uint32_t off_lo; + + if (fseek(f, -12, SEEK_END) < 0 || + fread(buf, 1, 12, f) != 12) + return false; + + if (!memcmp(buf, "NER5", 4)) { + off_hi = get_be32(buf+4); + off_lo = get_be32(buf+8); + } else if(!memcmp(buf+4, "NERO", 4)) { + off_hi = 0; + off_lo = get_be32(buf+8); + } else + return false; + + if (off_hi || !off_lo) + return false; + if (offp) + *offp = off_lo; + return true; +} + +bool nrg_check_file(FILE *f) +{ + return nrg_check_footer(f, NULL); +} + +bool nrg_parse_and_add_tracks(FILE *f, const char *fn) +{ + uint32_t hdr_off; + if (!nrg_check_footer(f, &hdr_off)) { + msg_error("Failed to parse NRG5 footer\n"); + return false; + } + long file_end = ftell(f); + if (file_end < 0) { + msg_perror(fn); + return false; + } + uint8_t sess_nr = 0; + int prev_sess_tracks = 0; + for (;;) { + uint8_t chdr[8]; + if (fseek(f, hdr_off, SEEK_SET) < 0 || + fread(chdr, 1, 8, f) != 8) { + msg_perror(fn); + return false; + } + if (!memcmp(chdr, "END!\0\0\0\0", 8)) + break; + uint32_t chunklen = get_be32(chdr+4); + hdr_off += 8; + if (hdr_off + chunklen >= (uint32_t)file_end) { + msg_error("Corrupt NRG5 footer\n"); + return false; + } + switch(get_be32(chdr)) { + case CHUNK_ID('C','U','E','S'): + if (!nrg_parse_cuesx(f, fn, chunklen, false)) + return false; + break; + case CHUNK_ID('D','A','O','I'): + if (!nrg_parse_daoix(f, fn, chunklen, false)) + return false; + break; + case CHUNK_ID('C','U','E','X'): + if (!nrg_parse_cuesx(f, fn, chunklen, true)) + return false; + break; + case CHUNK_ID('D','A','O','X'): + if (!nrg_parse_daoix(f, fn, chunklen, true)) + return false; + break; + case CHUNK_ID('S','I','N','F'): + { + int sess_tracks = nrg_parse_sinf(f, fn, chunklen, sess_nr, prev_sess_tracks); + if (sess_tracks < 0) + return false; + prev_sess_tracks += sess_tracks; + sess_nr++; + } + break; + case CHUNK_ID('E','T','N','F'): + case CHUNK_ID('E','T','N','2'): + case CHUNK_ID('M','T','Y','P'): + break; + case CHUNK_ID('E','N','D','!'): + msg_error("Broken END! chunk found\n"); + return false; + } + hdr_off += chunklen; + } + return true; +} diff --git a/zeldin_iceGDROM/tools/source/nrg.h b/zeldin_iceGDROM/tools/source/nrg.h new file mode 100644 index 0000000000000000000000000000000000000000..6e944c9d2cdf216e7d65855970d6cc129a8e0d03 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/nrg.h @@ -0,0 +1,4 @@ +#include + +extern bool nrg_check_file(FILE *); +extern bool nrg_parse_and_add_tracks(FILE *, const char *); diff --git a/zeldin_iceGDROM/tools/source/track.c b/zeldin_iceGDROM/tools/source/track.c new file mode 100644 index 0000000000000000000000000000000000000000..594a78296693c7708bc18de8c68166cbb772f441 --- /dev/null +++ b/zeldin_iceGDROM/tools/source/track.c @@ -0,0 +1,562 @@ +#include +#include +#include +#include +#include + +#include "msg.h" +#include "track.h" + +#define BLOCK_SECTORS 16 + +struct track *first_track = NULL, *last_track = NULL; + +static const uint32_t edctable[] = { + 0x00000000UL,0x90910101UL,0x91210201UL,0x01b00300UL, + 0x92410401UL,0x02d00500UL,0x03600600UL,0x93f10701UL, + 0x94810801UL,0x04100900UL,0x05a00a00UL,0x95310b01UL, + 0x06c00c00UL,0x96510d01UL,0x97e10e01UL,0x07700f00UL, + 0x99011001UL,0x09901100UL,0x08201200UL,0x98b11301UL, + 0x0b401400UL,0x9bd11501UL,0x9a611601UL,0x0af01700UL, + 0x0d801800UL,0x9d111901UL,0x9ca11a01UL,0x0c301b00UL, + 0x9fc11c01UL,0x0f501d00UL,0x0ee01e00UL,0x9e711f01UL, + 0x82012001UL,0x12902100UL,0x13202200UL,0x83b12301UL, + 0x10402400UL,0x80d12501UL,0x81612601UL,0x11f02700UL, + 0x16802800UL,0x86112901UL,0x87a12a01UL,0x17302b00UL, + 0x84c12c01UL,0x14502d00UL,0x15e02e00UL,0x85712f01UL, + 0x1b003000UL,0x8b913101UL,0x8a213201UL,0x1ab03300UL, + 0x89413401UL,0x19d03500UL,0x18603600UL,0x88f13701UL, + 0x8f813801UL,0x1f103900UL,0x1ea03a00UL,0x8e313b01UL, + 0x1dc03c00UL,0x8d513d01UL,0x8ce13e01UL,0x1c703f00UL, + 0xb4014001UL,0x24904100UL,0x25204200UL,0xb5b14301UL, + 0x26404400UL,0xb6d14501UL,0xb7614601UL,0x27f04700UL, + 0x20804800UL,0xb0114901UL,0xb1a14a01UL,0x21304b00UL, + 0xb2c14c01UL,0x22504d00UL,0x23e04e00UL,0xb3714f01UL, + 0x2d005000UL,0xbd915101UL,0xbc215201UL,0x2cb05300UL, + 0xbf415401UL,0x2fd05500UL,0x2e605600UL,0xbef15701UL, + 0xb9815801UL,0x29105900UL,0x28a05a00UL,0xb8315b01UL, + 0x2bc05c00UL,0xbb515d01UL,0xbae15e01UL,0x2a705f00UL, + 0x36006000UL,0xa6916101UL,0xa7216201UL,0x37b06300UL, + 0xa4416401UL,0x34d06500UL,0x35606600UL,0xa5f16701UL, + 0xa2816801UL,0x32106900UL,0x33a06a00UL,0xa3316b01UL, + 0x30c06c00UL,0xa0516d01UL,0xa1e16e01UL,0x31706f00UL, + 0xaf017001UL,0x3f907100UL,0x3e207200UL,0xaeb17301UL, + 0x3d407400UL,0xadd17501UL,0xac617601UL,0x3cf07700UL, + 0x3b807800UL,0xab117901UL,0xaaa17a01UL,0x3a307b00UL, + 0xa9c17c01UL,0x39507d00UL,0x38e07e00UL,0xa8717f01UL, + 0xd8018001UL,0x48908100UL,0x49208200UL,0xd9b18301UL, + 0x4a408400UL,0xdad18501UL,0xdb618601UL,0x4bf08700UL, + 0x4c808800UL,0xdc118901UL,0xdda18a01UL,0x4d308b00UL, + 0xdec18c01UL,0x4e508d00UL,0x4fe08e00UL,0xdf718f01UL, + 0x41009000UL,0xd1919101UL,0xd0219201UL,0x40b09300UL, + 0xd3419401UL,0x43d09500UL,0x42609600UL,0xd2f19701UL, + 0xd5819801UL,0x45109900UL,0x44a09a00UL,0xd4319b01UL, + 0x47c09c00UL,0xd7519d01UL,0xd6e19e01UL,0x46709f00UL, + 0x5a00a000UL,0xca91a101UL,0xcb21a201UL,0x5bb0a300UL, + 0xc841a401UL,0x58d0a500UL,0x5960a600UL,0xc9f1a701UL, + 0xce81a801UL,0x5e10a900UL,0x5fa0aa00UL,0xcf31ab01UL, + 0x5cc0ac00UL,0xcc51ad01UL,0xcde1ae01UL,0x5d70af00UL, + 0xc301b001UL,0x5390b100UL,0x5220b200UL,0xc2b1b301UL, + 0x5140b400UL,0xc1d1b501UL,0xc061b601UL,0x50f0b700UL, + 0x5780b800UL,0xc711b901UL,0xc6a1ba01UL,0x5630bb00UL, + 0xc5c1bc01UL,0x5550bd00UL,0x54e0be00UL,0xc471bf01UL, + 0x6c00c000UL,0xfc91c101UL,0xfd21c201UL,0x6db0c300UL, + 0xfe41c401UL,0x6ed0c500UL,0x6f60c600UL,0xfff1c701UL, + 0xf881c801UL,0x6810c900UL,0x69a0ca00UL,0xf931cb01UL, + 0x6ac0cc00UL,0xfa51cd01UL,0xfbe1ce01UL,0x6b70cf00UL, + 0xf501d001UL,0x6590d100UL,0x6420d200UL,0xf4b1d301UL, + 0x6740d400UL,0xf7d1d501UL,0xf661d601UL,0x66f0d700UL, + 0x6180d800UL,0xf111d901UL,0xf0a1da01UL,0x6030db00UL, + 0xf3c1dc01UL,0x6350dd00UL,0x62e0de00UL,0xf271df01UL, + 0xee01e001UL,0x7e90e100UL,0x7f20e200UL,0xefb1e301UL, + 0x7c40e400UL,0xecd1e501UL,0xed61e601UL,0x7df0e700UL, + 0x7a80e800UL,0xea11e901UL,0xeba1ea01UL,0x7b30eb00UL, + 0xe8c1ec01UL,0x7850ed00UL,0x79e0ee00UL,0xe971ef01UL, + 0x7700f000UL,0xe791f101UL,0xe621f201UL,0x76b0f300UL, + 0xe541f401UL,0x75d0f500UL,0x7460f600UL,0xe4f1f701UL, + 0xe381f801UL,0x7310f900UL,0x72a0fa00UL,0xe231fb01UL, + 0x71c0fc00UL,0xe151fd01UL,0xe0e1fe01UL,0x7070ff00UL, +}; + +static const uint8_t rs_l12_log[] = { + 0x00,0x00,0x01,0x19,0x02,0x32,0x1a,0xc6, + 0x03,0xdf,0x33,0xee,0x1b,0x68,0xc7,0x4b, + 0x04,0x64,0xe0,0x0e,0x34,0x8d,0xef,0x81, + 0x1c,0xc1,0x69,0xf8,0xc8,0x08,0x4c,0x71, + 0x05,0x8a,0x65,0x2f,0xe1,0x24,0x0f,0x21, + 0x35,0x93,0x8e,0xda,0xf0,0x12,0x82,0x45, + 0x1d,0xb5,0xc2,0x7d,0x6a,0x27,0xf9,0xb9, + 0xc9,0x9a,0x09,0x78,0x4d,0xe4,0x72,0xa6, + 0x06,0xbf,0x8b,0x62,0x66,0xdd,0x30,0xfd, + 0xe2,0x98,0x25,0xb3,0x10,0x91,0x22,0x88, + 0x36,0xd0,0x94,0xce,0x8f,0x96,0xdb,0xbd, + 0xf1,0xd2,0x13,0x5c,0x83,0x38,0x46,0x40, + 0x1e,0x42,0xb6,0xa3,0xc3,0x48,0x7e,0x6e, + 0x6b,0x3a,0x28,0x54,0xfa,0x85,0xba,0x3d, + 0xca,0x5e,0x9b,0x9f,0x0a,0x15,0x79,0x2b, + 0x4e,0xd4,0xe5,0xac,0x73,0xf3,0xa7,0x57, + 0x07,0x70,0xc0,0xf7,0x8c,0x80,0x63,0x0d, + 0x67,0x4a,0xde,0xed,0x31,0xc5,0xfe,0x18, + 0xe3,0xa5,0x99,0x77,0x26,0xb8,0xb4,0x7c, + 0x11,0x44,0x92,0xd9,0x23,0x20,0x89,0x2e, + 0x37,0x3f,0xd1,0x5b,0x95,0xbc,0xcf,0xcd, + 0x90,0x87,0x97,0xb2,0xdc,0xfc,0xbe,0x61, + 0xf2,0x56,0xd3,0xab,0x14,0x2a,0x5d,0x9e, + 0x84,0x3c,0x39,0x53,0x47,0x6d,0x41,0xa2, + 0x1f,0x2d,0x43,0xd8,0xb7,0x7b,0xa4,0x76, + 0xc4,0x17,0x49,0xec,0x7f,0x0c,0x6f,0xf6, + 0x6c,0xa1,0x3b,0x52,0x29,0x9d,0x55,0xaa, + 0xfb,0x60,0x86,0xb1,0xbb,0xcc,0x3e,0x5a, + 0xcb,0x59,0x5f,0xb0,0x9c,0xa9,0xa0,0x51, + 0x0b,0xf5,0x16,0xeb,0x7a,0x75,0x2c,0xd7, + 0x4f,0xae,0xd5,0xe9,0xe6,0xe7,0xad,0xe8, + 0x74,0xd6,0xf4,0xea,0xa8,0x50,0x58,0xaf, +}; + +static const uint8_t rs_l12_alog[] = { + 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80, + 0x1d,0x3a,0x74,0xe8,0xcd,0x87,0x13,0x26, + 0x4c,0x98,0x2d,0x5a,0xb4,0x75,0xea,0xc9, + 0x8f,0x03,0x06,0x0c,0x18,0x30,0x60,0xc0, + 0x9d,0x27,0x4e,0x9c,0x25,0x4a,0x94,0x35, + 0x6a,0xd4,0xb5,0x77,0xee,0xc1,0x9f,0x23, + 0x46,0x8c,0x05,0x0a,0x14,0x28,0x50,0xa0, + 0x5d,0xba,0x69,0xd2,0xb9,0x6f,0xde,0xa1, + 0x5f,0xbe,0x61,0xc2,0x99,0x2f,0x5e,0xbc, + 0x65,0xca,0x89,0x0f,0x1e,0x3c,0x78,0xf0, + 0xfd,0xe7,0xd3,0xbb,0x6b,0xd6,0xb1,0x7f, + 0xfe,0xe1,0xdf,0xa3,0x5b,0xb6,0x71,0xe2, + 0xd9,0xaf,0x43,0x86,0x11,0x22,0x44,0x88, + 0x0d,0x1a,0x34,0x68,0xd0,0xbd,0x67,0xce, + 0x81,0x1f,0x3e,0x7c,0xf8,0xed,0xc7,0x93, + 0x3b,0x76,0xec,0xc5,0x97,0x33,0x66,0xcc, + 0x85,0x17,0x2e,0x5c,0xb8,0x6d,0xda,0xa9, + 0x4f,0x9e,0x21,0x42,0x84,0x15,0x2a,0x54, + 0xa8,0x4d,0x9a,0x29,0x52,0xa4,0x55,0xaa, + 0x49,0x92,0x39,0x72,0xe4,0xd5,0xb7,0x73, + 0xe6,0xd1,0xbf,0x63,0xc6,0x91,0x3f,0x7e, + 0xfc,0xe5,0xd7,0xb3,0x7b,0xf6,0xf1,0xff, + 0xe3,0xdb,0xab,0x4b,0x96,0x31,0x62,0xc4, + 0x95,0x37,0x6e,0xdc,0xa5,0x57,0xae,0x41, + 0x82,0x19,0x32,0x64,0xc8,0x8d,0x07,0x0e, + 0x1c,0x38,0x70,0xe0,0xdd,0xa7,0x53,0xa6, + 0x51,0xa2,0x59,0xb2,0x79,0xf2,0xf9,0xef, + 0xc3,0x9b,0x2b,0x56,0xac,0x45,0x8a,0x09, + 0x12,0x24,0x48,0x90,0x3d,0x7a,0xf4,0xf5, + 0xf7,0xf3,0xfb,0xeb,0xcb,0x8b,0x0b,0x16, + 0x2c,0x58,0xb0,0x7d,0xfa,0xe9,0xcf,0x83, + 0x1b,0x36,0x6c,0xd8,0xad,0x47,0x8e,0x01, + 0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1d, + 0x3a,0x74,0xe8,0xcd,0x87,0x13,0x26,0x4c, + 0x98,0x2d,0x5a,0xb4,0x75,0xea,0xc9,0x8f, + 0x03,0x06,0x0c,0x18,0x30,0x60,0xc0,0x9d, + 0x27,0x4e,0x9c,0x25,0x4a,0x94,0x35,0x6a, + 0xd4,0xb5,0x77,0xee,0xc1,0x9f,0x23,0x46, + 0x8c,0x05,0x0a,0x14,0x28,0x50,0xa0,0x5d, + 0xba,0x69,0xd2,0xb9,0x6f,0xde,0xa1,0x5f, + 0xbe,0x61,0xc2,0x99,0x2f,0x5e,0xbc,0x65, + 0xca,0x89,0x0f,0x1e,0x3c,0x78,0xf0,0xfd, + 0xe7,0xd3,0xbb,0x6b,0xd6,0xb1,0x7f,0xfe, + 0xe1,0xdf,0xa3,0x5b,0xb6,0x71,0xe2,0xd9, + 0xaf,0x43,0x86,0x11,0x22,0x44,0x88,0x0d, + 0x1a,0x34,0x68,0xd0,0xbd,0x67,0xce,0x81, + 0x1f,0x3e,0x7c,0xf8,0xed,0xc7,0x93,0x3b, + 0x76,0xec,0xc5,0x97,0x33,0x66,0xcc,0x85, + 0x17,0x2e,0x5c,0xb8,0x6d,0xda,0xa9,0x4f, + 0x9e,0x21,0x42,0x84,0x15,0x2a,0x54,0xa8, + 0x4d,0x9a,0x29,0x52,0xa4,0x55,0xaa,0x49, + 0x92,0x39,0x72,0xe4,0xd5,0xb7,0x73,0xe6, + 0xd1,0xbf,0x63,0xc6,0x91,0x3f,0x7e,0xfc, + 0xe5,0xd7,0xb3,0x7b,0xf6,0xf1,0xff,0xe3, + 0xdb,0xab,0x4b,0x96,0x31,0x62,0xc4,0x95, + 0x37,0x6e,0xdc,0xa5,0x57,0xae,0x41,0x82, + 0x19,0x32,0x64,0xc8,0x8d,0x07,0x0e,0x1c, + 0x38,0x70,0xe0,0xdd,0xa7,0x53,0xa6,0x51, + 0xa2,0x59,0xb2,0x79,0xf2,0xf9,0xef,0xc3, + 0x9b,0x2b,0x56,0xac,0x45,0x8a,0x09,0x12, + 0x24,0x48,0x90,0x3d,0x7a,0xf4,0xf5,0xf7, + 0xf3,0xfb,0xeb,0xcb,0x8b,0x0b,0x16,0x2c, + 0x58,0xb0,0x7d,0xfa,0xe9,0xcf,0x83,0x1b, + 0x36,0x6c,0xd8,0xad,0x47,0x8e, +}; + +static const uint8_t DP0[] = { + 231,229,171,210,240,17,67,215,43,120,8,199,74,102,220,251,95,175, + 87,166,113,75,198,25,0 +}; +static const uint8_t DP1[] = { + 230,172,211,241,18,68,216,44,121,9,200,75,103,221,252,96,176,88, + 167,114,76,199,26,1,0 +}; +static const uint8_t DQ0[] = { + 190,96,250,132,59,81,159,154,200,7,111,245,10,20,41,156,168,79,173, + 231,229,171,210,240,17,67,215,43,120,8,199,74,102,220,251,95,175, + 87,166,113,75,198,25,0 +}; +static const uint8_t DQ1[] = { + 97,251,133,60,82,160,155,201,8,112,246,11,21,42,157,169,80,174,232, + 230,172,211,241,18,68,216,44,121,9,200,75,103,221,252,96,176,88, + 167,114,76,199,26,1,0 +}; + +static void encode_P(const uint8_t *data, unsigned sz, uint8_t *P) +{ + unsigned i=0, j=0, n; + memset(P, 0, 43*2*2); + unsigned dp0 = DP0[0], dp1 = DP1[0]; + for (n=0; n> 8) ^ edctable[v]; + } + EDC[0] = r&0xff; + EDC[1] = (r>>8)&0xff; + EDC[2] = (r>>16)&0xff; + EDC[3] = (r>>24)&0xff; +} + +static void add_ecc(uint8_t *sector) +{ + encode_P(sector+12, 2064, sector+2076); + encode_Q(sector+12, 2236, sector+2248); +} + +static uint8_t to_bcd(uint8_t n) +{ + return ((n/10)<<4)+(n%10); +} + +static void adr_to_msf_bcd(uint32_t adr, uint8_t *msf) +{ + uint8_t m = adr / 4500; + uint8_t s = (adr % 4500) / 75; + uint8_t f = adr % 75; + msf[0] = to_bcd(m); + msf[1] = to_bcd(s); + msf[2] = to_bcd(f); +} + +static void add_header(uint8_t *sector, uint32_t adr, uint8_t mode) +{ + memset(sector, 0, 16); + memset(sector+1, 0xff, 10); + adr_to_msf_bcd(adr, sector+12); + sector[15] = mode; +} + +static void add_xa_subheader(uint8_t *sector) +{ + sector[16] = 0; /* File number */ + sector[17] = 0; /* Channel number */ + sector[18] = 8; /* Submode (Data) */ + sector[19] = 0; /* Data type */ + memcpy(sector+20, sector+16, 4); +} + +void convert_track_swap_2352(uint8_t *sector, uint32_t adr) +{ + for(unsigned i = 0; i < 2352; i+=2) { + uint8_t t = sector[i]; + sector[i] = sector[i+1]; + sector[i+1] = t; + } +} + +void convert_track_mode_0_2336(uint8_t *sector, uint32_t adr) +{ + add_header(sector, adr, 0); +} + +void convert_track_mode_1_2048(uint8_t *sector, uint32_t adr) +{ + add_header(sector, adr, 1); + add_edc(sector, 16+2048, sector+2064); + memset(sector+2068, 0, 8); + add_ecc(sector); +} + +void convert_track_mode_2_2336(uint8_t *sector, uint32_t adr) +{ + add_header(sector, adr, 2); +} + +void convert_track_xa_form_1_2048(uint8_t *sector, uint32_t adr) +{ + add_header(sector, 0, 0); /* Fake header for ECC calculations */ + add_xa_subheader(sector); + add_edc(sector+16, 8+2048, sector+2072); + add_ecc(sector); + add_header(sector, adr, 2); +} + +void convert_track_xa_form_1_2056(uint8_t *sector, uint32_t adr) +{ + add_header(sector, 0, 0); /* Fake header for ECC calculations */ + add_edc(sector+16, 8+2048, sector+2072); + add_ecc(sector); + add_header(sector, adr, 2); +} + +void convert_track_xa_form_2_2324(uint8_t *sector, uint32_t adr) +{ + add_header(sector, adr, 2); + add_xa_subheader(sector); + add_edc(sector+16, 8+2324, sector+2348); +} + +void convert_track_xa_form_2_2332(uint8_t *sector, uint32_t adr) +{ + add_header(sector, adr, 2); + add_edc(sector+16, 8+2324, sector+2348); +} + +static const struct { + uint32_t input_size; + uint32_t input_offs; + void (*convert_func)(uint8_t *, uint32_t); +} formats[] = { + [ TRACK_RAW_2352 ] = { 2352, 0, NULL }, + [ TRACK_SWAP_2352 ] = { 2352, 0, convert_track_swap_2352 }, + [ TRACK_MODE_0_2336 ] = { 2336, 16, convert_track_mode_0_2336 }, + [ TRACK_MODE_1_2048 ] = { 2048, 16, convert_track_mode_1_2048 }, + [ TRACK_MODE_2_2336 ] = { 2336, 16, convert_track_mode_2_2336 }, + [ TRACK_XA_FORM_1_2048 ] = { 2048, 24, convert_track_xa_form_1_2048 }, + [ TRACK_XA_FORM_1_2056 ] = { 2056, 16, convert_track_xa_form_1_2056 }, + [ TRACK_XA_FORM_2_2324 ] = { 2324, 24, convert_track_xa_form_2_2324 }, + [ TRACK_XA_FORM_2_2332 ] = { 2332, 16, convert_track_xa_form_2_2332 }, +}; + +static bool track_validate_size(enum track_type type, uint32_t secsize) +{ + if ((type == TRACK_RAW_2352 || type == TRACK_SWAP_2352) && secsize >= 2352) + /* Allow extra (subchannel) data */ + return true; + + if (secsize != formats[type].input_size) { + msg_error("Invalid sector size (%u != %u) in input\n", + (unsigned)secsize, (unsigned)formats[type].input_size); + return false; + } + + return true; +} + +static bool track_read_sector(struct track *t, uint8_t *sector, FILE *f, + uint32_t adr) +{ + if (f == NULL) + memset(sector, 0, 2352); + if (t->type == TRACK_RAW_2352 || t->type == TRACK_SWAP_2352) { + if (f != NULL) { + size_t r = fread(sector, 1, 2352, f); + if (r != 2352) { + msg_error("Incomplete read from input file\n"); + return false; + } + if (t->data_size > 2352) { + if (fseek(f, t->data_size-2352, SEEK_CUR) < 0) { + msg_error("Failed to seek in input file\n"); + return false; + } + } + if (formats[t->type].convert_func) + formats[t->type].convert_func(sector, adr); + } + } else { + if (f != NULL) { + size_t r = fread(sector+formats[t->type].input_offs, 1, + formats[t->type].input_size, f); + if (r != formats[t->type].input_size) { + msg_error("Incomplete read from input file\n"); + return false; + } + } + formats[t->type].convert_func(sector, adr); + } + return true; +} + +struct track *track_create(void) +{ + struct track *t = calloc(1, sizeof(struct track)); + if (!t) { + msg_oom(); + return NULL; + } + t->next = NULL; + t->data_file = NULL; + t->data_filename = NULL; + if (last_track) + last_track->next = t; + else + first_track = t; + last_track = t; + return t; +} + +void track_delete_all() +{ + while(first_track) { + struct track *t = first_track; + first_track = t->next; + if (t->data_filename) + free(t->data_filename); + free(t); + } + last_track = NULL; +} + +struct track *track_get_first() +{ + return first_track; +} + +bool track_data_from_filename(struct track *t, enum track_type type, uint32_t secsize, const char *filename, uint32_t offset, uint32_t count) +{ + if (!t || t->data_file || t->data_filename) { + msg_error("Invalid track passed to track_data_from_filename\n"); + return false; + } + if (!track_validate_size(type, secsize)) + return false; + char *filename_copy = malloc(strlen(filename)+1); + if (!filename_copy) { + msg_oom(); + return false; + } + strcpy(filename_copy, filename); + t->type = type; + t->data_size = secsize; + t->data_offs = offset; + t->data_filename = filename_copy; + if (count == TRACK_SECTOR_COUNT_PROBE) { + FILE *f = fopen(filename_copy, "rb"); + if (!f) { + msg_perror(filename_copy); + return false; + } + long flen = -1; + if (fseek(f, 0, SEEK_END) >= 0) + flen = ftell(f); + fclose(f); + if (flen < 0) { + msg_perror(filename_copy); + return false; + } + if (flen < offset) { + msg_error("File offset is beyond EOF\n"); + return false; + } + t->data_count = (flen - offset) / secsize; + } else + t->data_count = count; + return true; +} + +bool track_data_from_file(struct track *t, enum track_type type, uint32_t secsize, FILE *file, uint32_t offset, uint32_t count) +{ + if (!t || t->data_file || t->data_filename) { + msg_error("Invalid track passed to track_data_from_file\n"); + return false; + } + if (!track_validate_size(type, secsize)) + return false; + t->type = type; + t->data_size = secsize; + t->data_offs = offset; + t->data_file = file; + if (count == TRACK_SECTOR_COUNT_PROBE) { + msg_error("Invalid sector count passed to track_data_from_file\n"); + return false; + } else + t->data_count = count; + return true; +} + +bool track_convert(struct track *t, FILE *f) +{ + uint8_t (*sector)[BLOCK_SECTORS][2352]; + if (!(sector = malloc(sizeof(*sector)))) { + msg_oom(); + return false; + } + FILE *df = NULL; + bool do_close = false; + if (t->data_filename) { + do_close = true; + df = fopen(t->data_filename, "rb"); + if (!df) { + msg_perror(t->data_filename); + free(sector); + return false; + } + } else + df = t->data_file; + if (df && fseek(df, t->data_offs, SEEK_SET) < 0) { + msg_error("Failed to seek in input file\n"); + free(sector); + if (do_close) + fclose(df); + return false; + } + msg_progress_start_nr(t->track_nr); + for (uint32_t n = 0; n < t->data_count; n += BLOCK_SECTORS) { + msg_progress_update(n, t->data_count); + uint32_t cnt = (t->data_count - n > BLOCK_SECTORS ? + BLOCK_SECTORS : t->data_count - n); + for (uint32_t n2 = 0; n2 < cnt; n2++) + if (!track_read_sector(t, (*sector)[n2], df, t->start_sector+n+n2)) { + free(sector); + if (do_close) + fclose(df); + return false; + } + if (fwrite(&(*sector)[0][0], 2352, cnt, f) != cnt) { + msg_error("Failed to write to output file\n"); + free(sector); + if (do_close) + fclose(df); + return false; + } + } + msg_progress_update(t->data_count, t->data_count); + free(sector); + if (do_close) + fclose(df); + return true; +} diff --git a/zeldin_iceGDROM/tools/source/track.h b/zeldin_iceGDROM/tools/source/track.h new file mode 100644 index 0000000000000000000000000000000000000000..29cc64fa03d511d463ee61bdb4331bc3bcd9b73f --- /dev/null +++ b/zeldin_iceGDROM/tools/source/track.h @@ -0,0 +1,42 @@ +#include +#include + +enum track_type { + TRACK_RAW_2352, /* Raw 2352 byte sector image */ + TRACK_SWAP_2352, /* Byteswapped audio */ + TRACK_MODE_0_2336, /* 2336 byte Mode 0 sectors */ + TRACK_MODE_1_2048, /* Yellow Book 2048 byte data sector */ + TRACK_MODE_2_2336, /* 2336 byte Mode 2 sectors */ + TRACK_XA_FORM_1_2048, /* 2048 byte XA Form 1 sectors */ + TRACK_XA_FORM_1_2056, /* 2048 byte XA Form 1 sectors with 8 byte subheader */ + TRACK_XA_FORM_2_2324, /* 2324 byte XA Form 2 sectors */ + TRACK_XA_FORM_2_2332, /* 2324 byte XA Form 2 sectors with 8 byte subheader */ +}; + +struct track { + struct track *next; + enum track_type type; + uint8_t track_nr; + uint8_t track_ctl; + uint8_t toc_nr; + uint8_t session_nr; + uint8_t region_nr; + uint32_t start_sector; + + uint32_t data_count; + uint32_t data_size; + uint32_t data_offs; + FILE *data_file; + char *data_filename; +}; + +extern struct track *track_create(void); +extern void track_delete_all(void); +extern struct track *track_get_first(void); +extern bool track_data_from_filename(struct track *, enum track_type, uint32_t, const char *, uint32_t, uint32_t); +extern bool track_data_from_file(struct track *, enum track_type, uint32_t, FILE *, uint32_t, uint32_t); +extern bool track_convert(struct track *, FILE *); + +#define TRACK_FOREACH(var) for(struct track *var = track_get_first(); var != NULL; var=var->next) + +#define TRACK_SECTOR_COUNT_PROBE (UINT32_MAX)